Home | History | Annotate | Line # | Download | only in i915
i915_gem.c revision 1.1.1.1.2.5
      1 /*
      2  * Copyright  2008 Intel Corporation
      3  *
      4  * Permission is hereby granted, free of charge, to any person obtaining a
      5  * copy of this software and associated documentation files (the "Software"),
      6  * to deal in the Software without restriction, including without limitation
      7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
      8  * and/or sell copies of the Software, and to permit persons to whom the
      9  * Software is furnished to do so, subject to the following conditions:
     10  *
     11  * The above copyright notice and this permission notice (including the next
     12  * paragraph) shall be included in all copies or substantial portions of the
     13  * Software.
     14  *
     15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
     18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
     20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
     21  * IN THE SOFTWARE.
     22  *
     23  * Authors:
     24  *    Eric Anholt <eric (at) anholt.net>
     25  *
     26  */
     27 
     28 #include <drm/drmP.h>
     29 #include <drm/i915_drm.h>
     30 #include "i915_drv.h"
     31 #include "i915_trace.h"
     32 #include "intel_drv.h"
     33 #include <linux/shmem_fs.h>
     34 #include <linux/slab.h>
     35 #include <linux/swap.h>
     36 #include <linux/pci.h>
     37 #include <linux/dma-buf.h>
     38 #include <asm/param.h>
     39 
     40 static void i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj);
     41 static void i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj);
     42 static __must_check int i915_gem_object_bind_to_gtt(struct drm_i915_gem_object *obj,
     43 						    unsigned alignment,
     44 						    bool map_and_fenceable,
     45 						    bool nonblocking);
     46 static int i915_gem_phys_pwrite(struct drm_device *dev,
     47 				struct drm_i915_gem_object *obj,
     48 				struct drm_i915_gem_pwrite *args,
     49 				struct drm_file *file);
     50 
     51 static void i915_gem_write_fence(struct drm_device *dev, int reg,
     52 				 struct drm_i915_gem_object *obj);
     53 static void i915_gem_object_update_fence(struct drm_i915_gem_object *obj,
     54 					 struct drm_i915_fence_reg *fence,
     55 					 bool enable);
     56 
     57 static int i915_gem_inactive_shrink(struct shrinker *shrinker,
     58 				    struct shrink_control *sc);
     59 static long i915_gem_purge(struct drm_i915_private *dev_priv, long target);
     60 static void i915_gem_shrink_all(struct drm_i915_private *dev_priv);
     61 static void i915_gem_object_truncate(struct drm_i915_gem_object *obj);
     62 
     63 static inline void i915_gem_object_fence_lost(struct drm_i915_gem_object *obj)
     64 {
     65 	if (obj->tiling_mode)
     66 		i915_gem_release_mmap(obj);
     67 
     68 	/* As we do not have an associated fence register, we will force
     69 	 * a tiling change if we ever need to acquire one.
     70 	 */
     71 	obj->fence_dirty = false;
     72 	obj->fence_reg = I915_FENCE_REG_NONE;
     73 }
     74 
     75 /* some bookkeeping */
     76 static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
     77 				  size_t size)
     78 {
     79 	dev_priv->mm.object_count++;
     80 	dev_priv->mm.object_memory += size;
     81 }
     82 
     83 static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
     84 				     size_t size)
     85 {
     86 	dev_priv->mm.object_count--;
     87 	dev_priv->mm.object_memory -= size;
     88 }
     89 
     90 static int
     91 i915_gem_wait_for_error(struct drm_device *dev)
     92 {
     93 	struct drm_i915_private *dev_priv = dev->dev_private;
     94 	struct completion *x = &dev_priv->error_completion;
     95 #ifndef __NetBSD__
     96 	unsigned long flags;
     97 #endif
     98 	int ret;
     99 
    100 	if (!atomic_read(&dev_priv->mm.wedged))
    101 		return 0;
    102 
    103 	/*
    104 	 * Only wait 10 seconds for the gpu reset to complete to avoid hanging
    105 	 * userspace. If it takes that long something really bad is going on and
    106 	 * we should simply try to bail out and fail as gracefully as possible.
    107 	 */
    108 	ret = wait_for_completion_interruptible_timeout(x, 10*HZ);
    109 	if (ret == 0) {
    110 		DRM_ERROR("Timed out waiting for the gpu reset to complete\n");
    111 		return -EIO;
    112 	} else if (ret < 0) {
    113 		return ret;
    114 	}
    115 
    116 	if (atomic_read(&dev_priv->mm.wedged)) {
    117 		/* GPU is hung, bump the completion count to account for
    118 		 * the token we just consumed so that we never hit zero and
    119 		 * end up waiting upon a subsequent completion event that
    120 		 * will never happen.
    121 		 */
    122 #ifdef __NetBSD__
    123 		/* XXX Hope it's not a problem that we might wake someone.  */
    124 		complete(x);
    125 #else
    126 		spin_lock_irqsave(&x->wait.lock, flags);
    127 		x->done++;
    128 		spin_unlock_irqrestore(&x->wait.lock, flags);
    129 #endif
    130 	}
    131 	return 0;
    132 }
    133 
    134 int i915_mutex_lock_interruptible(struct drm_device *dev)
    135 {
    136 	int ret;
    137 
    138 	ret = i915_gem_wait_for_error(dev);
    139 	if (ret)
    140 		return ret;
    141 
    142 	ret = mutex_lock_interruptible(&dev->struct_mutex);
    143 	if (ret)
    144 		return ret;
    145 
    146 	WARN_ON(i915_verify_lists(dev));
    147 	return 0;
    148 }
    149 
    150 static inline bool
    151 i915_gem_object_is_inactive(struct drm_i915_gem_object *obj)
    152 {
    153 	return obj->gtt_space && !obj->active;
    154 }
    155 
    156 int
    157 i915_gem_init_ioctl(struct drm_device *dev, void *data,
    158 		    struct drm_file *file)
    159 {
    160 	struct drm_i915_gem_init *args = data;
    161 
    162 	if (drm_core_check_feature(dev, DRIVER_MODESET))
    163 		return -ENODEV;
    164 
    165 	if (args->gtt_start >= args->gtt_end ||
    166 	    (args->gtt_end | args->gtt_start) & (PAGE_SIZE - 1))
    167 		return -EINVAL;
    168 
    169 	/* GEM with user mode setting was never supported on ilk and later. */
    170 	if (INTEL_INFO(dev)->gen >= 5)
    171 		return -ENODEV;
    172 
    173 	mutex_lock(&dev->struct_mutex);
    174 	i915_gem_init_global_gtt(dev, args->gtt_start,
    175 				 args->gtt_end, args->gtt_end);
    176 	mutex_unlock(&dev->struct_mutex);
    177 
    178 	return 0;
    179 }
    180 
    181 int
    182 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
    183 			    struct drm_file *file)
    184 {
    185 	struct drm_i915_private *dev_priv = dev->dev_private;
    186 	struct drm_i915_gem_get_aperture *args = data;
    187 	struct drm_i915_gem_object *obj;
    188 	size_t pinned;
    189 
    190 	pinned = 0;
    191 	mutex_lock(&dev->struct_mutex);
    192 	list_for_each_entry(obj, &dev_priv->mm.bound_list, gtt_list)
    193 		if (obj->pin_count)
    194 			pinned += obj->gtt_space->size;
    195 	mutex_unlock(&dev->struct_mutex);
    196 
    197 	args->aper_size = dev_priv->mm.gtt_total;
    198 	args->aper_available_size = args->aper_size - pinned;
    199 
    200 	return 0;
    201 }
    202 
    203 static int
    204 i915_gem_create(struct drm_file *file,
    205 		struct drm_device *dev,
    206 		uint64_t size,
    207 		uint32_t *handle_p)
    208 {
    209 	struct drm_i915_gem_object *obj;
    210 	int ret;
    211 	u32 handle;
    212 
    213 	size = roundup(size, PAGE_SIZE);
    214 	if (size == 0)
    215 		return -EINVAL;
    216 
    217 	/* Allocate the new object */
    218 	obj = i915_gem_alloc_object(dev, size);
    219 	if (obj == NULL)
    220 		return -ENOMEM;
    221 
    222 	ret = drm_gem_handle_create(file, &obj->base, &handle);
    223 	if (ret) {
    224 		drm_gem_object_release(&obj->base);
    225 		i915_gem_info_remove_obj(dev->dev_private, obj->base.size);
    226 		kfree(obj);
    227 		return ret;
    228 	}
    229 
    230 	/* drop reference from allocate - handle holds it now */
    231 	drm_gem_object_unreference(&obj->base);
    232 	trace_i915_gem_object_create(obj);
    233 
    234 	*handle_p = handle;
    235 	return 0;
    236 }
    237 
    238 int
    239 i915_gem_dumb_create(struct drm_file *file,
    240 		     struct drm_device *dev,
    241 		     struct drm_mode_create_dumb *args)
    242 {
    243 	/* have to work out size/pitch and return them */
    244 	args->pitch = ALIGN(args->width * ((args->bpp + 7) / 8), 64);
    245 	args->size = args->pitch * args->height;
    246 	return i915_gem_create(file, dev,
    247 			       args->size, &args->handle);
    248 }
    249 
    250 int i915_gem_dumb_destroy(struct drm_file *file,
    251 			  struct drm_device *dev,
    252 			  uint32_t handle)
    253 {
    254 	return drm_gem_handle_delete(file, handle);
    255 }
    256 
    257 /**
    258  * Creates a new mm object and returns a handle to it.
    259  */
    260 int
    261 i915_gem_create_ioctl(struct drm_device *dev, void *data,
    262 		      struct drm_file *file)
    263 {
    264 	struct drm_i915_gem_create *args = data;
    265 
    266 	return i915_gem_create(file, dev,
    267 			       args->size, &args->handle);
    268 }
    269 
    270 static int i915_gem_object_needs_bit17_swizzle(struct drm_i915_gem_object *obj)
    271 {
    272 	drm_i915_private_t *dev_priv = obj->base.dev->dev_private;
    273 
    274 	return dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_9_10_17 &&
    275 		obj->tiling_mode != I915_TILING_NONE;
    276 }
    277 
    278 static inline int
    279 __copy_to_user_swizzled(char __user *cpu_vaddr,
    280 			const char *gpu_vaddr, int gpu_offset,
    281 			int length)
    282 {
    283 	int ret, cpu_offset = 0;
    284 
    285 	while (length > 0) {
    286 		int cacheline_end = ALIGN(gpu_offset + 1, 64);
    287 		int this_length = min(cacheline_end - gpu_offset, length);
    288 		int swizzled_gpu_offset = gpu_offset ^ 64;
    289 
    290 		ret = __copy_to_user(cpu_vaddr + cpu_offset,
    291 				     gpu_vaddr + swizzled_gpu_offset,
    292 				     this_length);
    293 		if (ret)
    294 			return ret + length;
    295 
    296 		cpu_offset += this_length;
    297 		gpu_offset += this_length;
    298 		length -= this_length;
    299 	}
    300 
    301 	return 0;
    302 }
    303 
    304 static inline int
    305 __copy_from_user_swizzled(char *gpu_vaddr, int gpu_offset,
    306 			  const char __user *cpu_vaddr,
    307 			  int length)
    308 {
    309 	int ret, cpu_offset = 0;
    310 
    311 	while (length > 0) {
    312 		int cacheline_end = ALIGN(gpu_offset + 1, 64);
    313 		int this_length = min(cacheline_end - gpu_offset, length);
    314 		int swizzled_gpu_offset = gpu_offset ^ 64;
    315 
    316 		ret = __copy_from_user(gpu_vaddr + swizzled_gpu_offset,
    317 				       cpu_vaddr + cpu_offset,
    318 				       this_length);
    319 		if (ret)
    320 			return ret + length;
    321 
    322 		cpu_offset += this_length;
    323 		gpu_offset += this_length;
    324 		length -= this_length;
    325 	}
    326 
    327 	return 0;
    328 }
    329 
    330 /* Per-page copy function for the shmem pread fastpath.
    331  * Flushes invalid cachelines before reading the target if
    332  * needs_clflush is set. */
    333 static int
    334 shmem_pread_fast(struct page *page, int shmem_page_offset, int page_length,
    335 		 char __user *user_data,
    336 		 bool page_do_bit17_swizzling, bool needs_clflush)
    337 {
    338 	char *vaddr;
    339 	int ret;
    340 
    341 	if (unlikely(page_do_bit17_swizzling))
    342 		return -EINVAL;
    343 
    344 	vaddr = kmap_atomic(page);
    345 	if (needs_clflush)
    346 		drm_clflush_virt_range(vaddr + shmem_page_offset,
    347 				       page_length);
    348 	ret = __copy_to_user_inatomic(user_data,
    349 				      vaddr + shmem_page_offset,
    350 				      page_length);
    351 	kunmap_atomic(vaddr);
    352 
    353 	return ret ? -EFAULT : 0;
    354 }
    355 
    356 static void
    357 shmem_clflush_swizzled_range(char *addr, unsigned long length,
    358 			     bool swizzled)
    359 {
    360 	if (unlikely(swizzled)) {
    361 		unsigned long start = (unsigned long) addr;
    362 		unsigned long end = (unsigned long) addr + length;
    363 
    364 		/* For swizzling simply ensure that we always flush both
    365 		 * channels. Lame, but simple and it works. Swizzled
    366 		 * pwrite/pread is far from a hotpath - current userspace
    367 		 * doesn't use it at all. */
    368 		start = round_down(start, 128);
    369 		end = round_up(end, 128);
    370 
    371 		drm_clflush_virt_range((void *)start, end - start);
    372 	} else {
    373 		drm_clflush_virt_range(addr, length);
    374 	}
    375 
    376 }
    377 
    378 /* Only difference to the fast-path function is that this can handle bit17
    379  * and uses non-atomic copy and kmap functions. */
    380 static int
    381 shmem_pread_slow(struct page *page, int shmem_page_offset, int page_length,
    382 		 char __user *user_data,
    383 		 bool page_do_bit17_swizzling, bool needs_clflush)
    384 {
    385 	char *vaddr;
    386 	int ret;
    387 
    388 	vaddr = kmap(page);
    389 	if (needs_clflush)
    390 		shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
    391 					     page_length,
    392 					     page_do_bit17_swizzling);
    393 
    394 	if (page_do_bit17_swizzling)
    395 		ret = __copy_to_user_swizzled(user_data,
    396 					      vaddr, shmem_page_offset,
    397 					      page_length);
    398 	else
    399 		ret = __copy_to_user(user_data,
    400 				     vaddr + shmem_page_offset,
    401 				     page_length);
    402 	kunmap(page);
    403 
    404 	return ret ? - EFAULT : 0;
    405 }
    406 
    407 static int
    408 i915_gem_shmem_pread(struct drm_device *dev,
    409 		     struct drm_i915_gem_object *obj,
    410 		     struct drm_i915_gem_pread *args,
    411 		     struct drm_file *file)
    412 {
    413 	char __user *user_data;
    414 	ssize_t remain;
    415 	loff_t offset;
    416 	int shmem_page_offset, page_length, ret = 0;
    417 	int obj_do_bit17_swizzling, page_do_bit17_swizzling;
    418 	int hit_slowpath = 0;
    419 	int prefaulted = 0;
    420 	int needs_clflush = 0;
    421 	struct scatterlist *sg;
    422 	int i;
    423 
    424 	user_data = (char __user *) (uintptr_t) args->data_ptr;
    425 	remain = args->size;
    426 
    427 	obj_do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
    428 
    429 	if (!(obj->base.read_domains & I915_GEM_DOMAIN_CPU)) {
    430 		/* If we're not in the cpu read domain, set ourself into the gtt
    431 		 * read domain and manually flush cachelines (if required). This
    432 		 * optimizes for the case when the gpu will dirty the data
    433 		 * anyway again before the next pread happens. */
    434 		if (obj->cache_level == I915_CACHE_NONE)
    435 			needs_clflush = 1;
    436 		if (obj->gtt_space) {
    437 			ret = i915_gem_object_set_to_gtt_domain(obj, false);
    438 			if (ret)
    439 				return ret;
    440 		}
    441 	}
    442 
    443 	ret = i915_gem_object_get_pages(obj);
    444 	if (ret)
    445 		return ret;
    446 
    447 	i915_gem_object_pin_pages(obj);
    448 
    449 	offset = args->offset;
    450 
    451 	for_each_sg(obj->pages->sgl, sg, obj->pages->nents, i) {
    452 		struct page *page;
    453 
    454 		if (i < offset >> PAGE_SHIFT)
    455 			continue;
    456 
    457 		if (remain <= 0)
    458 			break;
    459 
    460 		/* Operation in this page
    461 		 *
    462 		 * shmem_page_offset = offset within page in shmem file
    463 		 * page_length = bytes to copy for this page
    464 		 */
    465 		shmem_page_offset = offset_in_page(offset);
    466 		page_length = remain;
    467 		if ((shmem_page_offset + page_length) > PAGE_SIZE)
    468 			page_length = PAGE_SIZE - shmem_page_offset;
    469 
    470 		page = sg_page(sg);
    471 		page_do_bit17_swizzling = obj_do_bit17_swizzling &&
    472 			(page_to_phys(page) & (1 << 17)) != 0;
    473 
    474 		ret = shmem_pread_fast(page, shmem_page_offset, page_length,
    475 				       user_data, page_do_bit17_swizzling,
    476 				       needs_clflush);
    477 		if (ret == 0)
    478 			goto next_page;
    479 
    480 		hit_slowpath = 1;
    481 		mutex_unlock(&dev->struct_mutex);
    482 
    483 		if (!prefaulted) {
    484 			ret = fault_in_multipages_writeable(user_data, remain);
    485 			/* Userspace is tricking us, but we've already clobbered
    486 			 * its pages with the prefault and promised to write the
    487 			 * data up to the first fault. Hence ignore any errors
    488 			 * and just continue. */
    489 			(void)ret;
    490 			prefaulted = 1;
    491 		}
    492 
    493 		ret = shmem_pread_slow(page, shmem_page_offset, page_length,
    494 				       user_data, page_do_bit17_swizzling,
    495 				       needs_clflush);
    496 
    497 		mutex_lock(&dev->struct_mutex);
    498 
    499 next_page:
    500 		mark_page_accessed(page);
    501 
    502 		if (ret)
    503 			goto out;
    504 
    505 		remain -= page_length;
    506 		user_data += page_length;
    507 		offset += page_length;
    508 	}
    509 
    510 out:
    511 	i915_gem_object_unpin_pages(obj);
    512 
    513 	if (hit_slowpath) {
    514 		/* Fixup: Kill any reinstated backing storage pages */
    515 		if (obj->madv == __I915_MADV_PURGED)
    516 			i915_gem_object_truncate(obj);
    517 	}
    518 
    519 	return ret;
    520 }
    521 
    522 /**
    523  * Reads data from the object referenced by handle.
    524  *
    525  * On error, the contents of *data are undefined.
    526  */
    527 int
    528 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
    529 		     struct drm_file *file)
    530 {
    531 	struct drm_i915_gem_pread *args = data;
    532 	struct drm_i915_gem_object *obj;
    533 	int ret = 0;
    534 
    535 	if (args->size == 0)
    536 		return 0;
    537 
    538 	if (!access_ok(VERIFY_WRITE,
    539 		       (char __user *)(uintptr_t)args->data_ptr,
    540 		       args->size))
    541 		return -EFAULT;
    542 
    543 	ret = i915_mutex_lock_interruptible(dev);
    544 	if (ret)
    545 		return ret;
    546 
    547 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
    548 	if (&obj->base == NULL) {
    549 		ret = -ENOENT;
    550 		goto unlock;
    551 	}
    552 
    553 	/* Bounds check source.  */
    554 	if (args->offset > obj->base.size ||
    555 	    args->size > obj->base.size - args->offset) {
    556 		ret = -EINVAL;
    557 		goto out;
    558 	}
    559 
    560 	/* prime objects have no backing filp to GEM pread/pwrite
    561 	 * pages from.
    562 	 */
    563 	if (!obj->base.filp) {
    564 		ret = -EINVAL;
    565 		goto out;
    566 	}
    567 
    568 	trace_i915_gem_object_pread(obj, args->offset, args->size);
    569 
    570 	ret = i915_gem_shmem_pread(dev, obj, args, file);
    571 
    572 out:
    573 	drm_gem_object_unreference(&obj->base);
    574 unlock:
    575 	mutex_unlock(&dev->struct_mutex);
    576 	return ret;
    577 }
    578 
    579 /* This is the fast write path which cannot handle
    580  * page faults in the source data
    581  */
    582 
    583 static inline int
    584 fast_user_write(struct io_mapping *mapping,
    585 		loff_t page_base, int page_offset,
    586 		char __user *user_data,
    587 		int length)
    588 {
    589 	void __iomem *vaddr_atomic;
    590 	void *vaddr;
    591 	unsigned long unwritten;
    592 
    593 	vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
    594 	/* We can use the cpu mem copy function because this is X86. */
    595 	vaddr = (void __force*)vaddr_atomic + page_offset;
    596 	unwritten = __copy_from_user_inatomic_nocache(vaddr,
    597 						      user_data, length);
    598 	io_mapping_unmap_atomic(vaddr_atomic);
    599 	return unwritten;
    600 }
    601 
    602 /**
    603  * This is the fast pwrite path, where we copy the data directly from the
    604  * user into the GTT, uncached.
    605  */
    606 static int
    607 i915_gem_gtt_pwrite_fast(struct drm_device *dev,
    608 			 struct drm_i915_gem_object *obj,
    609 			 struct drm_i915_gem_pwrite *args,
    610 			 struct drm_file *file)
    611 {
    612 	drm_i915_private_t *dev_priv = dev->dev_private;
    613 	ssize_t remain;
    614 	loff_t offset, page_base;
    615 	char __user *user_data;
    616 	int page_offset, page_length, ret;
    617 
    618 	ret = i915_gem_object_pin(obj, 0, true, true);
    619 	if (ret)
    620 		goto out;
    621 
    622 	ret = i915_gem_object_set_to_gtt_domain(obj, true);
    623 	if (ret)
    624 		goto out_unpin;
    625 
    626 	ret = i915_gem_object_put_fence(obj);
    627 	if (ret)
    628 		goto out_unpin;
    629 
    630 	user_data = (char __user *) (uintptr_t) args->data_ptr;
    631 	remain = args->size;
    632 
    633 	offset = obj->gtt_offset + args->offset;
    634 
    635 	while (remain > 0) {
    636 		/* Operation in this page
    637 		 *
    638 		 * page_base = page offset within aperture
    639 		 * page_offset = offset within page
    640 		 * page_length = bytes to copy for this page
    641 		 */
    642 		page_base = offset & PAGE_MASK;
    643 		page_offset = offset_in_page(offset);
    644 		page_length = remain;
    645 		if ((page_offset + remain) > PAGE_SIZE)
    646 			page_length = PAGE_SIZE - page_offset;
    647 
    648 		/* If we get a fault while copying data, then (presumably) our
    649 		 * source page isn't available.  Return the error and we'll
    650 		 * retry in the slow path.
    651 		 */
    652 		if (fast_user_write(dev_priv->mm.gtt_mapping, page_base,
    653 				    page_offset, user_data, page_length)) {
    654 			ret = -EFAULT;
    655 			goto out_unpin;
    656 		}
    657 
    658 		remain -= page_length;
    659 		user_data += page_length;
    660 		offset += page_length;
    661 	}
    662 
    663 out_unpin:
    664 	i915_gem_object_unpin(obj);
    665 out:
    666 	return ret;
    667 }
    668 
    669 /* Per-page copy function for the shmem pwrite fastpath.
    670  * Flushes invalid cachelines before writing to the target if
    671  * needs_clflush_before is set and flushes out any written cachelines after
    672  * writing if needs_clflush is set. */
    673 static int
    674 shmem_pwrite_fast(struct page *page, int shmem_page_offset, int page_length,
    675 		  char __user *user_data,
    676 		  bool page_do_bit17_swizzling,
    677 		  bool needs_clflush_before,
    678 		  bool needs_clflush_after)
    679 {
    680 	char *vaddr;
    681 	int ret;
    682 
    683 	if (unlikely(page_do_bit17_swizzling))
    684 		return -EINVAL;
    685 
    686 	vaddr = kmap_atomic(page);
    687 	if (needs_clflush_before)
    688 		drm_clflush_virt_range(vaddr + shmem_page_offset,
    689 				       page_length);
    690 	ret = __copy_from_user_inatomic_nocache(vaddr + shmem_page_offset,
    691 						user_data,
    692 						page_length);
    693 	if (needs_clflush_after)
    694 		drm_clflush_virt_range(vaddr + shmem_page_offset,
    695 				       page_length);
    696 	kunmap_atomic(vaddr);
    697 
    698 	return ret ? -EFAULT : 0;
    699 }
    700 
    701 /* Only difference to the fast-path function is that this can handle bit17
    702  * and uses non-atomic copy and kmap functions. */
    703 static int
    704 shmem_pwrite_slow(struct page *page, int shmem_page_offset, int page_length,
    705 		  char __user *user_data,
    706 		  bool page_do_bit17_swizzling,
    707 		  bool needs_clflush_before,
    708 		  bool needs_clflush_after)
    709 {
    710 	char *vaddr;
    711 	int ret;
    712 
    713 	vaddr = kmap(page);
    714 	if (unlikely(needs_clflush_before || page_do_bit17_swizzling))
    715 		shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
    716 					     page_length,
    717 					     page_do_bit17_swizzling);
    718 	if (page_do_bit17_swizzling)
    719 		ret = __copy_from_user_swizzled(vaddr, shmem_page_offset,
    720 						user_data,
    721 						page_length);
    722 	else
    723 		ret = __copy_from_user(vaddr + shmem_page_offset,
    724 				       user_data,
    725 				       page_length);
    726 	if (needs_clflush_after)
    727 		shmem_clflush_swizzled_range(vaddr + shmem_page_offset,
    728 					     page_length,
    729 					     page_do_bit17_swizzling);
    730 	kunmap(page);
    731 
    732 	return ret ? -EFAULT : 0;
    733 }
    734 
    735 static int
    736 i915_gem_shmem_pwrite(struct drm_device *dev,
    737 		      struct drm_i915_gem_object *obj,
    738 		      struct drm_i915_gem_pwrite *args,
    739 		      struct drm_file *file)
    740 {
    741 	ssize_t remain;
    742 	loff_t offset;
    743 	char __user *user_data;
    744 	int shmem_page_offset, page_length, ret = 0;
    745 	int obj_do_bit17_swizzling, page_do_bit17_swizzling;
    746 	int hit_slowpath = 0;
    747 	int needs_clflush_after = 0;
    748 	int needs_clflush_before = 0;
    749 	int i;
    750 	struct scatterlist *sg;
    751 
    752 	user_data = (char __user *) (uintptr_t) args->data_ptr;
    753 	remain = args->size;
    754 
    755 	obj_do_bit17_swizzling = i915_gem_object_needs_bit17_swizzle(obj);
    756 
    757 	if (obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
    758 		/* If we're not in the cpu write domain, set ourself into the gtt
    759 		 * write domain and manually flush cachelines (if required). This
    760 		 * optimizes for the case when the gpu will use the data
    761 		 * right away and we therefore have to clflush anyway. */
    762 		if (obj->cache_level == I915_CACHE_NONE)
    763 			needs_clflush_after = 1;
    764 		if (obj->gtt_space) {
    765 			ret = i915_gem_object_set_to_gtt_domain(obj, true);
    766 			if (ret)
    767 				return ret;
    768 		}
    769 	}
    770 	/* Same trick applies for invalidate partially written cachelines before
    771 	 * writing.  */
    772 	if (!(obj->base.read_domains & I915_GEM_DOMAIN_CPU)
    773 	    && obj->cache_level == I915_CACHE_NONE)
    774 		needs_clflush_before = 1;
    775 
    776 	ret = i915_gem_object_get_pages(obj);
    777 	if (ret)
    778 		return ret;
    779 
    780 	i915_gem_object_pin_pages(obj);
    781 
    782 	offset = args->offset;
    783 	obj->dirty = 1;
    784 
    785 	for_each_sg(obj->pages->sgl, sg, obj->pages->nents, i) {
    786 		struct page *page;
    787 		int partial_cacheline_write;
    788 
    789 		if (i < offset >> PAGE_SHIFT)
    790 			continue;
    791 
    792 		if (remain <= 0)
    793 			break;
    794 
    795 		/* Operation in this page
    796 		 *
    797 		 * shmem_page_offset = offset within page in shmem file
    798 		 * page_length = bytes to copy for this page
    799 		 */
    800 		shmem_page_offset = offset_in_page(offset);
    801 
    802 		page_length = remain;
    803 		if ((shmem_page_offset + page_length) > PAGE_SIZE)
    804 			page_length = PAGE_SIZE - shmem_page_offset;
    805 
    806 		/* If we don't overwrite a cacheline completely we need to be
    807 		 * careful to have up-to-date data by first clflushing. Don't
    808 		 * overcomplicate things and flush the entire patch. */
    809 		partial_cacheline_write = needs_clflush_before &&
    810 			((shmem_page_offset | page_length)
    811 				& (boot_cpu_data.x86_clflush_size - 1));
    812 
    813 		page = sg_page(sg);
    814 		page_do_bit17_swizzling = obj_do_bit17_swizzling &&
    815 			(page_to_phys(page) & (1 << 17)) != 0;
    816 
    817 		ret = shmem_pwrite_fast(page, shmem_page_offset, page_length,
    818 					user_data, page_do_bit17_swizzling,
    819 					partial_cacheline_write,
    820 					needs_clflush_after);
    821 		if (ret == 0)
    822 			goto next_page;
    823 
    824 		hit_slowpath = 1;
    825 		mutex_unlock(&dev->struct_mutex);
    826 		ret = shmem_pwrite_slow(page, shmem_page_offset, page_length,
    827 					user_data, page_do_bit17_swizzling,
    828 					partial_cacheline_write,
    829 					needs_clflush_after);
    830 
    831 		mutex_lock(&dev->struct_mutex);
    832 
    833 next_page:
    834 		set_page_dirty(page);
    835 		mark_page_accessed(page);
    836 
    837 		if (ret)
    838 			goto out;
    839 
    840 		remain -= page_length;
    841 		user_data += page_length;
    842 		offset += page_length;
    843 	}
    844 
    845 out:
    846 	i915_gem_object_unpin_pages(obj);
    847 
    848 	if (hit_slowpath) {
    849 		/* Fixup: Kill any reinstated backing storage pages */
    850 		if (obj->madv == __I915_MADV_PURGED)
    851 			i915_gem_object_truncate(obj);
    852 		/* and flush dirty cachelines in case the object isn't in the cpu write
    853 		 * domain anymore. */
    854 		if (obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
    855 			i915_gem_clflush_object(obj);
    856 			i915_gem_chipset_flush(dev);
    857 		}
    858 	}
    859 
    860 	if (needs_clflush_after)
    861 		i915_gem_chipset_flush(dev);
    862 
    863 	return ret;
    864 }
    865 
    866 /**
    867  * Writes data to the object referenced by handle.
    868  *
    869  * On error, the contents of the buffer that were to be modified are undefined.
    870  */
    871 int
    872 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
    873 		      struct drm_file *file)
    874 {
    875 	struct drm_i915_gem_pwrite *args = data;
    876 	struct drm_i915_gem_object *obj;
    877 	int ret;
    878 
    879 	if (args->size == 0)
    880 		return 0;
    881 
    882 	if (!access_ok(VERIFY_READ,
    883 		       (char __user *)(uintptr_t)args->data_ptr,
    884 		       args->size))
    885 		return -EFAULT;
    886 
    887 	ret = fault_in_multipages_readable((char __user *)(uintptr_t)args->data_ptr,
    888 					   args->size);
    889 	if (ret)
    890 		return -EFAULT;
    891 
    892 	ret = i915_mutex_lock_interruptible(dev);
    893 	if (ret)
    894 		return ret;
    895 
    896 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
    897 	if (&obj->base == NULL) {
    898 		ret = -ENOENT;
    899 		goto unlock;
    900 	}
    901 
    902 	/* Bounds check destination. */
    903 	if (args->offset > obj->base.size ||
    904 	    args->size > obj->base.size - args->offset) {
    905 		ret = -EINVAL;
    906 		goto out;
    907 	}
    908 
    909 	/* prime objects have no backing filp to GEM pread/pwrite
    910 	 * pages from.
    911 	 */
    912 	if (!obj->base.filp) {
    913 		ret = -EINVAL;
    914 		goto out;
    915 	}
    916 
    917 	trace_i915_gem_object_pwrite(obj, args->offset, args->size);
    918 
    919 	ret = -EFAULT;
    920 	/* We can only do the GTT pwrite on untiled buffers, as otherwise
    921 	 * it would end up going through the fenced access, and we'll get
    922 	 * different detiling behavior between reading and writing.
    923 	 * pread/pwrite currently are reading and writing from the CPU
    924 	 * perspective, requiring manual detiling by the client.
    925 	 */
    926 	if (obj->phys_obj) {
    927 		ret = i915_gem_phys_pwrite(dev, obj, args, file);
    928 		goto out;
    929 	}
    930 
    931 	if (obj->cache_level == I915_CACHE_NONE &&
    932 	    obj->tiling_mode == I915_TILING_NONE &&
    933 	    obj->base.write_domain != I915_GEM_DOMAIN_CPU) {
    934 		ret = i915_gem_gtt_pwrite_fast(dev, obj, args, file);
    935 		/* Note that the gtt paths might fail with non-page-backed user
    936 		 * pointers (e.g. gtt mappings when moving data between
    937 		 * textures). Fallback to the shmem path in that case. */
    938 	}
    939 
    940 	if (ret == -EFAULT || ret == -ENOSPC)
    941 		ret = i915_gem_shmem_pwrite(dev, obj, args, file);
    942 
    943 out:
    944 	drm_gem_object_unreference(&obj->base);
    945 unlock:
    946 	mutex_unlock(&dev->struct_mutex);
    947 	return ret;
    948 }
    949 
    950 int
    951 i915_gem_check_wedge(struct drm_i915_private *dev_priv,
    952 		     bool interruptible)
    953 {
    954 	if (atomic_read(&dev_priv->mm.wedged)) {
    955 		struct completion *x = &dev_priv->error_completion;
    956 		bool recovery_complete;
    957 		unsigned long flags;
    958 
    959 		/* Give the error handler a chance to run. */
    960 		spin_lock_irqsave(&x->wait.lock, flags);
    961 		recovery_complete = x->done > 0;
    962 		spin_unlock_irqrestore(&x->wait.lock, flags);
    963 
    964 		/* Non-interruptible callers can't handle -EAGAIN, hence return
    965 		 * -EIO unconditionally for these. */
    966 		if (!interruptible)
    967 			return -EIO;
    968 
    969 		/* Recovery complete, but still wedged means reset failure. */
    970 		if (recovery_complete)
    971 			return -EIO;
    972 
    973 		return -EAGAIN;
    974 	}
    975 
    976 	return 0;
    977 }
    978 
    979 /*
    980  * Compare seqno against outstanding lazy request. Emit a request if they are
    981  * equal.
    982  */
    983 static int
    984 i915_gem_check_olr(struct intel_ring_buffer *ring, u32 seqno)
    985 {
    986 	int ret;
    987 
    988 	BUG_ON(!mutex_is_locked(&ring->dev->struct_mutex));
    989 
    990 	ret = 0;
    991 	if (seqno == ring->outstanding_lazy_request)
    992 		ret = i915_add_request(ring, NULL, NULL);
    993 
    994 	return ret;
    995 }
    996 
    997 /**
    998  * __wait_seqno - wait until execution of seqno has finished
    999  * @ring: the ring expected to report seqno
   1000  * @seqno: duh!
   1001  * @interruptible: do an interruptible wait (normally yes)
   1002  * @timeout: in - how long to wait (NULL forever); out - how much time remaining
   1003  *
   1004  * Returns 0 if the seqno was found within the alloted time. Else returns the
   1005  * errno with remaining time filled in timeout argument.
   1006  */
   1007 static int __wait_seqno(struct intel_ring_buffer *ring, u32 seqno,
   1008 			bool interruptible, struct timespec *timeout)
   1009 {
   1010 	drm_i915_private_t *dev_priv = ring->dev->dev_private;
   1011 	struct timespec before, now, wait_time={1,0};
   1012 	unsigned long timeout_jiffies;
   1013 	long end;
   1014 	bool wait_forever = true;
   1015 	int ret;
   1016 
   1017 	if (i915_seqno_passed(ring->get_seqno(ring, true), seqno))
   1018 		return 0;
   1019 
   1020 	trace_i915_gem_request_wait_begin(ring, seqno);
   1021 
   1022 	if (timeout != NULL) {
   1023 		wait_time = *timeout;
   1024 		wait_forever = false;
   1025 	}
   1026 
   1027 	timeout_jiffies = timespec_to_jiffies(&wait_time);
   1028 
   1029 	if (WARN_ON(!ring->irq_get(ring)))
   1030 		return -ENODEV;
   1031 
   1032 	/* Record current time in case interrupted by signal, or wedged * */
   1033 	getrawmonotonic(&before);
   1034 
   1035 #define EXIT_COND \
   1036 	(i915_seqno_passed(ring->get_seqno(ring, false), seqno) || \
   1037 	atomic_read(&dev_priv->mm.wedged))
   1038 	do {
   1039 #ifdef __NetBSD__
   1040 		/*
   1041 		 * XXX This wait is always interruptible; we should
   1042 		 * heed the flag `interruptible'.
   1043 		 */
   1044 		DRM_TIMED_WAIT_UNTIL(end, &ring->irq_queue, &drm_global_mutex,
   1045 		    timeout_jiffies,
   1046 		    EXIT_COND);
   1047 #else
   1048 		if (interruptible)
   1049 			end = wait_event_interruptible_timeout(ring->irq_queue,
   1050 							       EXIT_COND,
   1051 							       timeout_jiffies);
   1052 		else
   1053 			end = wait_event_timeout(ring->irq_queue, EXIT_COND,
   1054 						 timeout_jiffies);
   1055 
   1056 #endif
   1057 		ret = i915_gem_check_wedge(dev_priv, interruptible);
   1058 		if (ret)
   1059 			end = ret;
   1060 	} while (end == 0 && wait_forever);
   1061 
   1062 	getrawmonotonic(&now);
   1063 
   1064 	ring->irq_put(ring);
   1065 	trace_i915_gem_request_wait_end(ring, seqno);
   1066 #undef EXIT_COND
   1067 
   1068 	if (timeout) {
   1069 		struct timespec sleep_time = timespec_sub(now, before);
   1070 		*timeout = timespec_sub(*timeout, sleep_time);
   1071 	}
   1072 
   1073 	switch (end) {
   1074 	case -EIO:
   1075 	case -EAGAIN: /* Wedged */
   1076 	case -ERESTARTSYS: /* Signal */
   1077 		return (int)end;
   1078 	case 0: /* Timeout */
   1079 		if (timeout)
   1080 			set_normalized_timespec(timeout, 0, 0);
   1081 		return -ETIME;
   1082 	default: /* Completed */
   1083 		WARN_ON(end < 0); /* We're not aware of other errors */
   1084 		return 0;
   1085 	}
   1086 }
   1087 
   1088 /**
   1089  * Waits for a sequence number to be signaled, and cleans up the
   1090  * request and object lists appropriately for that event.
   1091  */
   1092 int
   1093 i915_wait_seqno(struct intel_ring_buffer *ring, uint32_t seqno)
   1094 {
   1095 	struct drm_device *dev = ring->dev;
   1096 	struct drm_i915_private *dev_priv = dev->dev_private;
   1097 	bool interruptible = dev_priv->mm.interruptible;
   1098 	int ret;
   1099 
   1100 	BUG_ON(!mutex_is_locked(&dev->struct_mutex));
   1101 	BUG_ON(seqno == 0);
   1102 
   1103 	ret = i915_gem_check_wedge(dev_priv, interruptible);
   1104 	if (ret)
   1105 		return ret;
   1106 
   1107 	ret = i915_gem_check_olr(ring, seqno);
   1108 	if (ret)
   1109 		return ret;
   1110 
   1111 	return __wait_seqno(ring, seqno, interruptible, NULL);
   1112 }
   1113 
   1114 /**
   1115  * Ensures that all rendering to the object has completed and the object is
   1116  * safe to unbind from the GTT or access from the CPU.
   1117  */
   1118 static __must_check int
   1119 i915_gem_object_wait_rendering(struct drm_i915_gem_object *obj,
   1120 			       bool readonly)
   1121 {
   1122 	struct intel_ring_buffer *ring = obj->ring;
   1123 	u32 seqno;
   1124 	int ret;
   1125 
   1126 	seqno = readonly ? obj->last_write_seqno : obj->last_read_seqno;
   1127 	if (seqno == 0)
   1128 		return 0;
   1129 
   1130 	ret = i915_wait_seqno(ring, seqno);
   1131 	if (ret)
   1132 		return ret;
   1133 
   1134 	i915_gem_retire_requests_ring(ring);
   1135 
   1136 	/* Manually manage the write flush as we may have not yet
   1137 	 * retired the buffer.
   1138 	 */
   1139 	if (obj->last_write_seqno &&
   1140 	    i915_seqno_passed(seqno, obj->last_write_seqno)) {
   1141 		obj->last_write_seqno = 0;
   1142 		obj->base.write_domain &= ~I915_GEM_GPU_DOMAINS;
   1143 	}
   1144 
   1145 	return 0;
   1146 }
   1147 
   1148 /* A nonblocking variant of the above wait. This is a highly dangerous routine
   1149  * as the object state may change during this call.
   1150  */
   1151 static __must_check int
   1152 i915_gem_object_wait_rendering__nonblocking(struct drm_i915_gem_object *obj,
   1153 					    bool readonly)
   1154 {
   1155 	struct drm_device *dev = obj->base.dev;
   1156 	struct drm_i915_private *dev_priv = dev->dev_private;
   1157 	struct intel_ring_buffer *ring = obj->ring;
   1158 	u32 seqno;
   1159 	int ret;
   1160 
   1161 	BUG_ON(!mutex_is_locked(&dev->struct_mutex));
   1162 	BUG_ON(!dev_priv->mm.interruptible);
   1163 
   1164 	seqno = readonly ? obj->last_write_seqno : obj->last_read_seqno;
   1165 	if (seqno == 0)
   1166 		return 0;
   1167 
   1168 	ret = i915_gem_check_wedge(dev_priv, true);
   1169 	if (ret)
   1170 		return ret;
   1171 
   1172 	ret = i915_gem_check_olr(ring, seqno);
   1173 	if (ret)
   1174 		return ret;
   1175 
   1176 	mutex_unlock(&dev->struct_mutex);
   1177 	ret = __wait_seqno(ring, seqno, true, NULL);
   1178 	mutex_lock(&dev->struct_mutex);
   1179 
   1180 	i915_gem_retire_requests_ring(ring);
   1181 
   1182 	/* Manually manage the write flush as we may have not yet
   1183 	 * retired the buffer.
   1184 	 */
   1185 	if (obj->last_write_seqno &&
   1186 	    i915_seqno_passed(seqno, obj->last_write_seqno)) {
   1187 		obj->last_write_seqno = 0;
   1188 		obj->base.write_domain &= ~I915_GEM_GPU_DOMAINS;
   1189 	}
   1190 
   1191 	return ret;
   1192 }
   1193 
   1194 /**
   1195  * Called when user space prepares to use an object with the CPU, either
   1196  * through the mmap ioctl's mapping or a GTT mapping.
   1197  */
   1198 int
   1199 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
   1200 			  struct drm_file *file)
   1201 {
   1202 	struct drm_i915_gem_set_domain *args = data;
   1203 	struct drm_i915_gem_object *obj;
   1204 	uint32_t read_domains = args->read_domains;
   1205 	uint32_t write_domain = args->write_domain;
   1206 	int ret;
   1207 
   1208 	/* Only handle setting domains to types used by the CPU. */
   1209 	if (write_domain & I915_GEM_GPU_DOMAINS)
   1210 		return -EINVAL;
   1211 
   1212 	if (read_domains & I915_GEM_GPU_DOMAINS)
   1213 		return -EINVAL;
   1214 
   1215 	/* Having something in the write domain implies it's in the read
   1216 	 * domain, and only that read domain.  Enforce that in the request.
   1217 	 */
   1218 	if (write_domain != 0 && read_domains != write_domain)
   1219 		return -EINVAL;
   1220 
   1221 	ret = i915_mutex_lock_interruptible(dev);
   1222 	if (ret)
   1223 		return ret;
   1224 
   1225 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   1226 	if (&obj->base == NULL) {
   1227 		ret = -ENOENT;
   1228 		goto unlock;
   1229 	}
   1230 
   1231 	/* Try to flush the object off the GPU without holding the lock.
   1232 	 * We will repeat the flush holding the lock in the normal manner
   1233 	 * to catch cases where we are gazumped.
   1234 	 */
   1235 	ret = i915_gem_object_wait_rendering__nonblocking(obj, !write_domain);
   1236 	if (ret)
   1237 		goto unref;
   1238 
   1239 	if (read_domains & I915_GEM_DOMAIN_GTT) {
   1240 		ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
   1241 
   1242 		/* Silently promote "you're not bound, there was nothing to do"
   1243 		 * to success, since the client was just asking us to
   1244 		 * make sure everything was done.
   1245 		 */
   1246 		if (ret == -EINVAL)
   1247 			ret = 0;
   1248 	} else {
   1249 		ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
   1250 	}
   1251 
   1252 unref:
   1253 	drm_gem_object_unreference(&obj->base);
   1254 unlock:
   1255 	mutex_unlock(&dev->struct_mutex);
   1256 	return ret;
   1257 }
   1258 
   1259 /**
   1260  * Called when user space has done writes to this buffer
   1261  */
   1262 int
   1263 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
   1264 			 struct drm_file *file)
   1265 {
   1266 	struct drm_i915_gem_sw_finish *args = data;
   1267 	struct drm_i915_gem_object *obj;
   1268 	int ret = 0;
   1269 
   1270 	ret = i915_mutex_lock_interruptible(dev);
   1271 	if (ret)
   1272 		return ret;
   1273 
   1274 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   1275 	if (&obj->base == NULL) {
   1276 		ret = -ENOENT;
   1277 		goto unlock;
   1278 	}
   1279 
   1280 	/* Pinned buffers may be scanout, so flush the cache */
   1281 	if (obj->pin_count)
   1282 		i915_gem_object_flush_cpu_write_domain(obj);
   1283 
   1284 	drm_gem_object_unreference(&obj->base);
   1285 unlock:
   1286 	mutex_unlock(&dev->struct_mutex);
   1287 	return ret;
   1288 }
   1289 
   1290 /**
   1291  * Maps the contents of an object, returning the address it is mapped
   1292  * into.
   1293  *
   1294  * While the mapping holds a reference on the contents of the object, it doesn't
   1295  * imply a ref on the object itself.
   1296  */
   1297 int
   1298 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
   1299 		    struct drm_file *file)
   1300 {
   1301 	struct drm_i915_gem_mmap *args = data;
   1302 	struct drm_gem_object *obj;
   1303 	unsigned long addr;
   1304 
   1305 	obj = drm_gem_object_lookup(dev, file, args->handle);
   1306 	if (obj == NULL)
   1307 		return -ENOENT;
   1308 
   1309 	/* prime objects have no backing filp to GEM mmap
   1310 	 * pages from.
   1311 	 */
   1312 	if (!obj->filp) {
   1313 		drm_gem_object_unreference_unlocked(obj);
   1314 		return -EINVAL;
   1315 	}
   1316 
   1317 	addr = vm_mmap(obj->filp, 0, args->size,
   1318 		       PROT_READ | PROT_WRITE, MAP_SHARED,
   1319 		       args->offset);
   1320 	drm_gem_object_unreference_unlocked(obj);
   1321 	if (IS_ERR((void *)addr))
   1322 		return addr;
   1323 
   1324 	args->addr_ptr = (uint64_t) addr;
   1325 
   1326 	return 0;
   1327 }
   1328 
   1329 /**
   1330  * i915_gem_fault - fault a page into the GTT
   1331  * vma: VMA in question
   1332  * vmf: fault info
   1333  *
   1334  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
   1335  * from userspace.  The fault handler takes care of binding the object to
   1336  * the GTT (if needed), allocating and programming a fence register (again,
   1337  * only if needed based on whether the old reg is still valid or the object
   1338  * is tiled) and inserting a new PTE into the faulting process.
   1339  *
   1340  * Note that the faulting process may involve evicting existing objects
   1341  * from the GTT and/or fence registers to make room.  So performance may
   1342  * suffer if the GTT working set is large or there are few fence registers
   1343  * left.
   1344  */
   1345 int i915_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
   1346 {
   1347 	struct drm_i915_gem_object *obj = to_intel_bo(vma->vm_private_data);
   1348 	struct drm_device *dev = obj->base.dev;
   1349 	drm_i915_private_t *dev_priv = dev->dev_private;
   1350 	pgoff_t page_offset;
   1351 	unsigned long pfn;
   1352 	int ret = 0;
   1353 	bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
   1354 
   1355 	/* We don't use vmf->pgoff since that has the fake offset */
   1356 	page_offset = ((unsigned long)vmf->virtual_address - vma->vm_start) >>
   1357 		PAGE_SHIFT;
   1358 
   1359 	ret = i915_mutex_lock_interruptible(dev);
   1360 	if (ret)
   1361 		goto out;
   1362 
   1363 	trace_i915_gem_object_fault(obj, page_offset, true, write);
   1364 
   1365 	/* Now bind it into the GTT if needed */
   1366 	ret = i915_gem_object_pin(obj, 0, true, false);
   1367 	if (ret)
   1368 		goto unlock;
   1369 
   1370 	ret = i915_gem_object_set_to_gtt_domain(obj, write);
   1371 	if (ret)
   1372 		goto unpin;
   1373 
   1374 	ret = i915_gem_object_get_fence(obj);
   1375 	if (ret)
   1376 		goto unpin;
   1377 
   1378 	obj->fault_mappable = true;
   1379 
   1380 	pfn = ((dev_priv->mm.gtt_base_addr + obj->gtt_offset) >> PAGE_SHIFT) +
   1381 		page_offset;
   1382 
   1383 	/* Finally, remap it using the new GTT offset */
   1384 	ret = vm_insert_pfn(vma, (unsigned long)vmf->virtual_address, pfn);
   1385 unpin:
   1386 	i915_gem_object_unpin(obj);
   1387 unlock:
   1388 	mutex_unlock(&dev->struct_mutex);
   1389 out:
   1390 	switch (ret) {
   1391 	case -EIO:
   1392 		/* If this -EIO is due to a gpu hang, give the reset code a
   1393 		 * chance to clean up the mess. Otherwise return the proper
   1394 		 * SIGBUS. */
   1395 		if (!atomic_read(&dev_priv->mm.wedged))
   1396 			return VM_FAULT_SIGBUS;
   1397 	case -EAGAIN:
   1398 		/* Give the error handler a chance to run and move the
   1399 		 * objects off the GPU active list. Next time we service the
   1400 		 * fault, we should be able to transition the page into the
   1401 		 * GTT without touching the GPU (and so avoid further
   1402 		 * EIO/EGAIN). If the GPU is wedged, then there is no issue
   1403 		 * with coherency, just lost writes.
   1404 		 */
   1405 		set_need_resched();
   1406 	case 0:
   1407 	case -ERESTARTSYS:
   1408 	case -EINTR:
   1409 	case -EBUSY:
   1410 		/*
   1411 		 * EBUSY is ok: this just means that another thread
   1412 		 * already did the job.
   1413 		 */
   1414 		return VM_FAULT_NOPAGE;
   1415 	case -ENOMEM:
   1416 		return VM_FAULT_OOM;
   1417 	case -ENOSPC:
   1418 		return VM_FAULT_SIGBUS;
   1419 	default:
   1420 		WARN_ONCE(ret, "unhandled error in i915_gem_fault: %i\n", ret);
   1421 		return VM_FAULT_SIGBUS;
   1422 	}
   1423 }
   1424 
   1425 /**
   1426  * i915_gem_release_mmap - remove physical page mappings
   1427  * @obj: obj in question
   1428  *
   1429  * Preserve the reservation of the mmapping with the DRM core code, but
   1430  * relinquish ownership of the pages back to the system.
   1431  *
   1432  * It is vital that we remove the page mapping if we have mapped a tiled
   1433  * object through the GTT and then lose the fence register due to
   1434  * resource pressure. Similarly if the object has been moved out of the
   1435  * aperture, than pages mapped into userspace must be revoked. Removing the
   1436  * mapping will then trigger a page fault on the next user access, allowing
   1437  * fixup by i915_gem_fault().
   1438  */
   1439 void
   1440 i915_gem_release_mmap(struct drm_i915_gem_object *obj)
   1441 {
   1442 	if (!obj->fault_mappable)
   1443 		return;
   1444 
   1445 	if (obj->base.dev->dev_mapping)
   1446 		unmap_mapping_range(obj->base.dev->dev_mapping,
   1447 				    (loff_t)obj->base.map_list.hash.key<<PAGE_SHIFT,
   1448 				    obj->base.size, 1);
   1449 
   1450 	obj->fault_mappable = false;
   1451 }
   1452 
   1453 static uint32_t
   1454 i915_gem_get_gtt_size(struct drm_device *dev, uint32_t size, int tiling_mode)
   1455 {
   1456 	uint32_t gtt_size;
   1457 
   1458 	if (INTEL_INFO(dev)->gen >= 4 ||
   1459 	    tiling_mode == I915_TILING_NONE)
   1460 		return size;
   1461 
   1462 	/* Previous chips need a power-of-two fence region when tiling */
   1463 	if (INTEL_INFO(dev)->gen == 3)
   1464 		gtt_size = 1024*1024;
   1465 	else
   1466 		gtt_size = 512*1024;
   1467 
   1468 	while (gtt_size < size)
   1469 		gtt_size <<= 1;
   1470 
   1471 	return gtt_size;
   1472 }
   1473 
   1474 /**
   1475  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
   1476  * @obj: object to check
   1477  *
   1478  * Return the required GTT alignment for an object, taking into account
   1479  * potential fence register mapping.
   1480  */
   1481 static uint32_t
   1482 i915_gem_get_gtt_alignment(struct drm_device *dev,
   1483 			   uint32_t size,
   1484 			   int tiling_mode)
   1485 {
   1486 	/*
   1487 	 * Minimum alignment is 4k (GTT page size), but might be greater
   1488 	 * if a fence register is needed for the object.
   1489 	 */
   1490 	if (INTEL_INFO(dev)->gen >= 4 ||
   1491 	    tiling_mode == I915_TILING_NONE)
   1492 		return 4096;
   1493 
   1494 	/*
   1495 	 * Previous chips need to be aligned to the size of the smallest
   1496 	 * fence register that can contain the object.
   1497 	 */
   1498 	return i915_gem_get_gtt_size(dev, size, tiling_mode);
   1499 }
   1500 
   1501 /**
   1502  * i915_gem_get_unfenced_gtt_alignment - return required GTT alignment for an
   1503  *					 unfenced object
   1504  * @dev: the device
   1505  * @size: size of the object
   1506  * @tiling_mode: tiling mode of the object
   1507  *
   1508  * Return the required GTT alignment for an object, only taking into account
   1509  * unfenced tiled surface requirements.
   1510  */
   1511 uint32_t
   1512 i915_gem_get_unfenced_gtt_alignment(struct drm_device *dev,
   1513 				    uint32_t size,
   1514 				    int tiling_mode)
   1515 {
   1516 	/*
   1517 	 * Minimum alignment is 4k (GTT page size) for sane hw.
   1518 	 */
   1519 	if (INTEL_INFO(dev)->gen >= 4 || IS_G33(dev) ||
   1520 	    tiling_mode == I915_TILING_NONE)
   1521 		return 4096;
   1522 
   1523 	/* Previous hardware however needs to be aligned to a power-of-two
   1524 	 * tile height. The simplest method for determining this is to reuse
   1525 	 * the power-of-tile object size.
   1526 	 */
   1527 	return i915_gem_get_gtt_size(dev, size, tiling_mode);
   1528 }
   1529 
   1530 static int i915_gem_object_create_mmap_offset(struct drm_i915_gem_object *obj)
   1531 {
   1532 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   1533 	int ret;
   1534 
   1535 	if (obj->base.map_list.map)
   1536 		return 0;
   1537 
   1538 	dev_priv->mm.shrinker_no_lock_stealing = true;
   1539 
   1540 	ret = drm_gem_create_mmap_offset(&obj->base);
   1541 	if (ret != -ENOSPC)
   1542 		goto out;
   1543 
   1544 	/* Badly fragmented mmap space? The only way we can recover
   1545 	 * space is by destroying unwanted objects. We can't randomly release
   1546 	 * mmap_offsets as userspace expects them to be persistent for the
   1547 	 * lifetime of the objects. The closest we can is to release the
   1548 	 * offsets on purgeable objects by truncating it and marking it purged,
   1549 	 * which prevents userspace from ever using that object again.
   1550 	 */
   1551 	i915_gem_purge(dev_priv, obj->base.size >> PAGE_SHIFT);
   1552 	ret = drm_gem_create_mmap_offset(&obj->base);
   1553 	if (ret != -ENOSPC)
   1554 		goto out;
   1555 
   1556 	i915_gem_shrink_all(dev_priv);
   1557 	ret = drm_gem_create_mmap_offset(&obj->base);
   1558 out:
   1559 	dev_priv->mm.shrinker_no_lock_stealing = false;
   1560 
   1561 	return ret;
   1562 }
   1563 
   1564 static void i915_gem_object_free_mmap_offset(struct drm_i915_gem_object *obj)
   1565 {
   1566 	if (!obj->base.map_list.map)
   1567 		return;
   1568 
   1569 	drm_gem_free_mmap_offset(&obj->base);
   1570 }
   1571 
   1572 int
   1573 i915_gem_mmap_gtt(struct drm_file *file,
   1574 		  struct drm_device *dev,
   1575 		  uint32_t handle,
   1576 		  uint64_t *offset)
   1577 {
   1578 	struct drm_i915_private *dev_priv = dev->dev_private;
   1579 	struct drm_i915_gem_object *obj;
   1580 	int ret;
   1581 
   1582 	ret = i915_mutex_lock_interruptible(dev);
   1583 	if (ret)
   1584 		return ret;
   1585 
   1586 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, handle));
   1587 	if (&obj->base == NULL) {
   1588 		ret = -ENOENT;
   1589 		goto unlock;
   1590 	}
   1591 
   1592 	if (obj->base.size > dev_priv->mm.gtt_mappable_end) {
   1593 		ret = -E2BIG;
   1594 		goto out;
   1595 	}
   1596 
   1597 	if (obj->madv != I915_MADV_WILLNEED) {
   1598 		DRM_ERROR("Attempting to mmap a purgeable buffer\n");
   1599 		ret = -EINVAL;
   1600 		goto out;
   1601 	}
   1602 
   1603 	ret = i915_gem_object_create_mmap_offset(obj);
   1604 	if (ret)
   1605 		goto out;
   1606 
   1607 	*offset = (u64)obj->base.map_list.hash.key << PAGE_SHIFT;
   1608 
   1609 out:
   1610 	drm_gem_object_unreference(&obj->base);
   1611 unlock:
   1612 	mutex_unlock(&dev->struct_mutex);
   1613 	return ret;
   1614 }
   1615 
   1616 /**
   1617  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
   1618  * @dev: DRM device
   1619  * @data: GTT mapping ioctl data
   1620  * @file: GEM object info
   1621  *
   1622  * Simply returns the fake offset to userspace so it can mmap it.
   1623  * The mmap call will end up in drm_gem_mmap(), which will set things
   1624  * up so we can get faults in the handler above.
   1625  *
   1626  * The fault handler will take care of binding the object into the GTT
   1627  * (since it may have been evicted to make room for something), allocating
   1628  * a fence register, and mapping the appropriate aperture address into
   1629  * userspace.
   1630  */
   1631 int
   1632 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
   1633 			struct drm_file *file)
   1634 {
   1635 	struct drm_i915_gem_mmap_gtt *args = data;
   1636 
   1637 	return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
   1638 }
   1639 
   1640 /* Immediately discard the backing storage */
   1641 static void
   1642 i915_gem_object_truncate(struct drm_i915_gem_object *obj)
   1643 {
   1644 	struct inode *inode;
   1645 
   1646 	i915_gem_object_free_mmap_offset(obj);
   1647 
   1648 	if (obj->base.filp == NULL)
   1649 		return;
   1650 
   1651 	/* Our goal here is to return as much of the memory as
   1652 	 * is possible back to the system as we are called from OOM.
   1653 	 * To do this we must instruct the shmfs to drop all of its
   1654 	 * backing pages, *now*.
   1655 	 */
   1656 	inode = obj->base.filp->f_path.dentry->d_inode;
   1657 	shmem_truncate_range(inode, 0, (loff_t)-1);
   1658 
   1659 	obj->madv = __I915_MADV_PURGED;
   1660 }
   1661 
   1662 static inline int
   1663 i915_gem_object_is_purgeable(struct drm_i915_gem_object *obj)
   1664 {
   1665 	return obj->madv == I915_MADV_DONTNEED;
   1666 }
   1667 
   1668 static void
   1669 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj)
   1670 {
   1671 	int page_count = obj->base.size / PAGE_SIZE;
   1672 	struct scatterlist *sg;
   1673 	int ret, i;
   1674 
   1675 	BUG_ON(obj->madv == __I915_MADV_PURGED);
   1676 
   1677 	ret = i915_gem_object_set_to_cpu_domain(obj, true);
   1678 	if (ret) {
   1679 		/* In the event of a disaster, abandon all caches and
   1680 		 * hope for the best.
   1681 		 */
   1682 		WARN_ON(ret != -EIO);
   1683 		i915_gem_clflush_object(obj);
   1684 		obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
   1685 	}
   1686 
   1687 	if (i915_gem_object_needs_bit17_swizzle(obj))
   1688 		i915_gem_object_save_bit_17_swizzle(obj);
   1689 
   1690 	if (obj->madv == I915_MADV_DONTNEED)
   1691 		obj->dirty = 0;
   1692 
   1693 	for_each_sg(obj->pages->sgl, sg, page_count, i) {
   1694 		struct page *page = sg_page(sg);
   1695 
   1696 		if (obj->dirty)
   1697 			set_page_dirty(page);
   1698 
   1699 		if (obj->madv == I915_MADV_WILLNEED)
   1700 			mark_page_accessed(page);
   1701 
   1702 		page_cache_release(page);
   1703 	}
   1704 	obj->dirty = 0;
   1705 
   1706 	sg_free_table(obj->pages);
   1707 	kfree(obj->pages);
   1708 }
   1709 
   1710 static int
   1711 i915_gem_object_put_pages(struct drm_i915_gem_object *obj)
   1712 {
   1713 	const struct drm_i915_gem_object_ops *ops = obj->ops;
   1714 
   1715 	if (obj->pages == NULL)
   1716 		return 0;
   1717 
   1718 	BUG_ON(obj->gtt_space);
   1719 
   1720 	if (obj->pages_pin_count)
   1721 		return -EBUSY;
   1722 
   1723 	/* ->put_pages might need to allocate memory for the bit17 swizzle
   1724 	 * array, hence protect them from being reaped by removing them from gtt
   1725 	 * lists early. */
   1726 	list_del(&obj->gtt_list);
   1727 
   1728 	ops->put_pages(obj);
   1729 	obj->pages = NULL;
   1730 
   1731 	if (i915_gem_object_is_purgeable(obj))
   1732 		i915_gem_object_truncate(obj);
   1733 
   1734 	return 0;
   1735 }
   1736 
   1737 static long
   1738 __i915_gem_shrink(struct drm_i915_private *dev_priv, long target,
   1739 		  bool purgeable_only)
   1740 {
   1741 	struct drm_i915_gem_object *obj, *next;
   1742 	long count = 0;
   1743 
   1744 	list_for_each_entry_safe(obj, next,
   1745 				 &dev_priv->mm.unbound_list,
   1746 				 gtt_list) {
   1747 		if ((i915_gem_object_is_purgeable(obj) || !purgeable_only) &&
   1748 		    i915_gem_object_put_pages(obj) == 0) {
   1749 			count += obj->base.size >> PAGE_SHIFT;
   1750 			if (count >= target)
   1751 				return count;
   1752 		}
   1753 	}
   1754 
   1755 	list_for_each_entry_safe(obj, next,
   1756 				 &dev_priv->mm.inactive_list,
   1757 				 mm_list) {
   1758 		if ((i915_gem_object_is_purgeable(obj) || !purgeable_only) &&
   1759 		    i915_gem_object_unbind(obj) == 0 &&
   1760 		    i915_gem_object_put_pages(obj) == 0) {
   1761 			count += obj->base.size >> PAGE_SHIFT;
   1762 			if (count >= target)
   1763 				return count;
   1764 		}
   1765 	}
   1766 
   1767 	return count;
   1768 }
   1769 
   1770 static long
   1771 i915_gem_purge(struct drm_i915_private *dev_priv, long target)
   1772 {
   1773 	return __i915_gem_shrink(dev_priv, target, true);
   1774 }
   1775 
   1776 static void
   1777 i915_gem_shrink_all(struct drm_i915_private *dev_priv)
   1778 {
   1779 	struct drm_i915_gem_object *obj, *next;
   1780 
   1781 	i915_gem_evict_everything(dev_priv->dev);
   1782 
   1783 	list_for_each_entry_safe(obj, next, &dev_priv->mm.unbound_list, gtt_list)
   1784 		i915_gem_object_put_pages(obj);
   1785 }
   1786 
   1787 static int
   1788 i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
   1789 {
   1790 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   1791 	int page_count, i;
   1792 	struct address_space *mapping;
   1793 	struct sg_table *st;
   1794 	struct scatterlist *sg;
   1795 	struct page *page;
   1796 	gfp_t gfp;
   1797 
   1798 	/* Assert that the object is not currently in any GPU domain. As it
   1799 	 * wasn't in the GTT, there shouldn't be any way it could have been in
   1800 	 * a GPU cache
   1801 	 */
   1802 	BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
   1803 	BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
   1804 
   1805 	st = kmalloc(sizeof(*st), GFP_KERNEL);
   1806 	if (st == NULL)
   1807 		return -ENOMEM;
   1808 
   1809 	page_count = obj->base.size / PAGE_SIZE;
   1810 	if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
   1811 		sg_free_table(st);
   1812 		kfree(st);
   1813 		return -ENOMEM;
   1814 	}
   1815 
   1816 	/* Get the list of pages out of our struct file.  They'll be pinned
   1817 	 * at this point until we release them.
   1818 	 *
   1819 	 * Fail silently without starting the shrinker
   1820 	 */
   1821 	mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
   1822 	gfp = mapping_gfp_mask(mapping);
   1823 	gfp |= __GFP_NORETRY | __GFP_NOWARN | __GFP_NO_KSWAPD;
   1824 	gfp &= ~(__GFP_IO | __GFP_WAIT);
   1825 	for_each_sg(st->sgl, sg, page_count, i) {
   1826 		page = shmem_read_mapping_page_gfp(mapping, i, gfp);
   1827 		if (IS_ERR(page)) {
   1828 			i915_gem_purge(dev_priv, page_count);
   1829 			page = shmem_read_mapping_page_gfp(mapping, i, gfp);
   1830 		}
   1831 		if (IS_ERR(page)) {
   1832 			/* We've tried hard to allocate the memory by reaping
   1833 			 * our own buffer, now let the real VM do its job and
   1834 			 * go down in flames if truly OOM.
   1835 			 */
   1836 			gfp &= ~(__GFP_NORETRY | __GFP_NOWARN | __GFP_NO_KSWAPD);
   1837 			gfp |= __GFP_IO | __GFP_WAIT;
   1838 
   1839 			i915_gem_shrink_all(dev_priv);
   1840 			page = shmem_read_mapping_page_gfp(mapping, i, gfp);
   1841 			if (IS_ERR(page))
   1842 				goto err_pages;
   1843 
   1844 			gfp |= __GFP_NORETRY | __GFP_NOWARN | __GFP_NO_KSWAPD;
   1845 			gfp &= ~(__GFP_IO | __GFP_WAIT);
   1846 		}
   1847 
   1848 		sg_set_page(sg, page, PAGE_SIZE, 0);
   1849 	}
   1850 
   1851 	obj->pages = st;
   1852 
   1853 	if (i915_gem_object_needs_bit17_swizzle(obj))
   1854 		i915_gem_object_do_bit_17_swizzle(obj);
   1855 
   1856 	return 0;
   1857 
   1858 err_pages:
   1859 	for_each_sg(st->sgl, sg, i, page_count)
   1860 		page_cache_release(sg_page(sg));
   1861 	sg_free_table(st);
   1862 	kfree(st);
   1863 	return PTR_ERR(page);
   1864 }
   1865 
   1866 /* Ensure that the associated pages are gathered from the backing storage
   1867  * and pinned into our object. i915_gem_object_get_pages() may be called
   1868  * multiple times before they are released by a single call to
   1869  * i915_gem_object_put_pages() - once the pages are no longer referenced
   1870  * either as a result of memory pressure (reaping pages under the shrinker)
   1871  * or as the object is itself released.
   1872  */
   1873 int
   1874 i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
   1875 {
   1876 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   1877 	const struct drm_i915_gem_object_ops *ops = obj->ops;
   1878 	int ret;
   1879 
   1880 	if (obj->pages)
   1881 		return 0;
   1882 
   1883 	BUG_ON(obj->pages_pin_count);
   1884 
   1885 	ret = ops->get_pages(obj);
   1886 	if (ret)
   1887 		return ret;
   1888 
   1889 	list_add_tail(&obj->gtt_list, &dev_priv->mm.unbound_list);
   1890 	return 0;
   1891 }
   1892 
   1893 void
   1894 i915_gem_object_move_to_active(struct drm_i915_gem_object *obj,
   1895 			       struct intel_ring_buffer *ring)
   1896 {
   1897 	struct drm_device *dev = obj->base.dev;
   1898 	struct drm_i915_private *dev_priv = dev->dev_private;
   1899 	u32 seqno = intel_ring_get_seqno(ring);
   1900 
   1901 	BUG_ON(ring == NULL);
   1902 	obj->ring = ring;
   1903 
   1904 	/* Add a reference if we're newly entering the active list. */
   1905 	if (!obj->active) {
   1906 		drm_gem_object_reference(&obj->base);
   1907 		obj->active = 1;
   1908 	}
   1909 
   1910 	/* Move from whatever list we were on to the tail of execution. */
   1911 	list_move_tail(&obj->mm_list, &dev_priv->mm.active_list);
   1912 	list_move_tail(&obj->ring_list, &ring->active_list);
   1913 
   1914 	obj->last_read_seqno = seqno;
   1915 
   1916 	if (obj->fenced_gpu_access) {
   1917 		obj->last_fenced_seqno = seqno;
   1918 
   1919 		/* Bump MRU to take account of the delayed flush */
   1920 		if (obj->fence_reg != I915_FENCE_REG_NONE) {
   1921 			struct drm_i915_fence_reg *reg;
   1922 
   1923 			reg = &dev_priv->fence_regs[obj->fence_reg];
   1924 			list_move_tail(&reg->lru_list,
   1925 				       &dev_priv->mm.fence_list);
   1926 		}
   1927 	}
   1928 }
   1929 
   1930 static void
   1931 i915_gem_object_move_to_inactive(struct drm_i915_gem_object *obj)
   1932 {
   1933 	struct drm_device *dev = obj->base.dev;
   1934 	struct drm_i915_private *dev_priv = dev->dev_private;
   1935 
   1936 	BUG_ON(obj->base.write_domain & ~I915_GEM_GPU_DOMAINS);
   1937 	BUG_ON(!obj->active);
   1938 
   1939 	if (obj->pin_count) /* are we a framebuffer? */
   1940 		intel_mark_fb_idle(obj);
   1941 
   1942 	list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
   1943 
   1944 	list_del_init(&obj->ring_list);
   1945 	obj->ring = NULL;
   1946 
   1947 	obj->last_read_seqno = 0;
   1948 	obj->last_write_seqno = 0;
   1949 	obj->base.write_domain = 0;
   1950 
   1951 	obj->last_fenced_seqno = 0;
   1952 	obj->fenced_gpu_access = false;
   1953 
   1954 	obj->active = 0;
   1955 	drm_gem_object_unreference(&obj->base);
   1956 
   1957 	WARN_ON(i915_verify_lists(dev));
   1958 }
   1959 
   1960 static int
   1961 i915_gem_handle_seqno_wrap(struct drm_device *dev)
   1962 {
   1963 	struct drm_i915_private *dev_priv = dev->dev_private;
   1964 	struct intel_ring_buffer *ring;
   1965 	int ret, i, j;
   1966 
   1967 	/* The hardware uses various monotonic 32-bit counters, if we
   1968 	 * detect that they will wraparound we need to idle the GPU
   1969 	 * and reset those counters.
   1970 	 */
   1971 	ret = 0;
   1972 	for_each_ring(ring, dev_priv, i) {
   1973 		for (j = 0; j < ARRAY_SIZE(ring->sync_seqno); j++)
   1974 			ret |= ring->sync_seqno[j] != 0;
   1975 	}
   1976 	if (ret == 0)
   1977 		return ret;
   1978 
   1979 	ret = i915_gpu_idle(dev);
   1980 	if (ret)
   1981 		return ret;
   1982 
   1983 	i915_gem_retire_requests(dev);
   1984 	for_each_ring(ring, dev_priv, i) {
   1985 		for (j = 0; j < ARRAY_SIZE(ring->sync_seqno); j++)
   1986 			ring->sync_seqno[j] = 0;
   1987 	}
   1988 
   1989 	return 0;
   1990 }
   1991 
   1992 int
   1993 i915_gem_get_seqno(struct drm_device *dev, u32 *seqno)
   1994 {
   1995 	struct drm_i915_private *dev_priv = dev->dev_private;
   1996 
   1997 	/* reserve 0 for non-seqno */
   1998 	if (dev_priv->next_seqno == 0) {
   1999 		int ret = i915_gem_handle_seqno_wrap(dev);
   2000 		if (ret)
   2001 			return ret;
   2002 
   2003 		dev_priv->next_seqno = 1;
   2004 	}
   2005 
   2006 	*seqno = dev_priv->next_seqno++;
   2007 	return 0;
   2008 }
   2009 
   2010 int
   2011 i915_add_request(struct intel_ring_buffer *ring,
   2012 		 struct drm_file *file,
   2013 		 u32 *out_seqno)
   2014 {
   2015 	drm_i915_private_t *dev_priv = ring->dev->dev_private;
   2016 	struct drm_i915_gem_request *request;
   2017 	u32 request_ring_position;
   2018 	int was_empty;
   2019 	int ret;
   2020 
   2021 	/*
   2022 	 * Emit any outstanding flushes - execbuf can fail to emit the flush
   2023 	 * after having emitted the batchbuffer command. Hence we need to fix
   2024 	 * things up similar to emitting the lazy request. The difference here
   2025 	 * is that the flush _must_ happen before the next request, no matter
   2026 	 * what.
   2027 	 */
   2028 	ret = intel_ring_flush_all_caches(ring);
   2029 	if (ret)
   2030 		return ret;
   2031 
   2032 	request = kmalloc(sizeof(*request), GFP_KERNEL);
   2033 	if (request == NULL)
   2034 		return -ENOMEM;
   2035 
   2036 
   2037 	/* Record the position of the start of the request so that
   2038 	 * should we detect the updated seqno part-way through the
   2039 	 * GPU processing the request, we never over-estimate the
   2040 	 * position of the head.
   2041 	 */
   2042 	request_ring_position = intel_ring_get_tail(ring);
   2043 
   2044 	ret = ring->add_request(ring);
   2045 	if (ret) {
   2046 		kfree(request);
   2047 		return ret;
   2048 	}
   2049 
   2050 	request->seqno = intel_ring_get_seqno(ring);
   2051 	request->ring = ring;
   2052 	request->tail = request_ring_position;
   2053 	request->emitted_jiffies = jiffies;
   2054 	was_empty = list_empty(&ring->request_list);
   2055 	list_add_tail(&request->list, &ring->request_list);
   2056 	request->file_priv = NULL;
   2057 
   2058 	if (file) {
   2059 		struct drm_i915_file_private *file_priv = file->driver_priv;
   2060 
   2061 		spin_lock(&file_priv->mm.lock);
   2062 		request->file_priv = file_priv;
   2063 		list_add_tail(&request->client_list,
   2064 			      &file_priv->mm.request_list);
   2065 		spin_unlock(&file_priv->mm.lock);
   2066 	}
   2067 
   2068 	trace_i915_gem_request_add(ring, request->seqno);
   2069 	ring->outstanding_lazy_request = 0;
   2070 
   2071 	if (!dev_priv->mm.suspended) {
   2072 		if (i915_enable_hangcheck) {
   2073 			mod_timer(&dev_priv->hangcheck_timer,
   2074 				  round_jiffies_up(jiffies + DRM_I915_HANGCHECK_JIFFIES));
   2075 		}
   2076 		if (was_empty) {
   2077 			queue_delayed_work(dev_priv->wq,
   2078 					   &dev_priv->mm.retire_work,
   2079 					   round_jiffies_up_relative(HZ));
   2080 			intel_mark_busy(dev_priv->dev);
   2081 		}
   2082 	}
   2083 
   2084 	if (out_seqno)
   2085 		*out_seqno = request->seqno;
   2086 	return 0;
   2087 }
   2088 
   2089 static inline void
   2090 i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
   2091 {
   2092 	struct drm_i915_file_private *file_priv = request->file_priv;
   2093 
   2094 	if (!file_priv)
   2095 		return;
   2096 
   2097 	spin_lock(&file_priv->mm.lock);
   2098 	if (request->file_priv) {
   2099 		list_del(&request->client_list);
   2100 		request->file_priv = NULL;
   2101 	}
   2102 	spin_unlock(&file_priv->mm.lock);
   2103 }
   2104 
   2105 static void i915_gem_reset_ring_lists(struct drm_i915_private *dev_priv,
   2106 				      struct intel_ring_buffer *ring)
   2107 {
   2108 	while (!list_empty(&ring->request_list)) {
   2109 		struct drm_i915_gem_request *request;
   2110 
   2111 		request = list_first_entry(&ring->request_list,
   2112 					   struct drm_i915_gem_request,
   2113 					   list);
   2114 
   2115 		list_del(&request->list);
   2116 		i915_gem_request_remove_from_client(request);
   2117 		kfree(request);
   2118 	}
   2119 
   2120 	while (!list_empty(&ring->active_list)) {
   2121 		struct drm_i915_gem_object *obj;
   2122 
   2123 		obj = list_first_entry(&ring->active_list,
   2124 				       struct drm_i915_gem_object,
   2125 				       ring_list);
   2126 
   2127 		i915_gem_object_move_to_inactive(obj);
   2128 	}
   2129 }
   2130 
   2131 static void i915_gem_reset_fences(struct drm_device *dev)
   2132 {
   2133 	struct drm_i915_private *dev_priv = dev->dev_private;
   2134 	int i;
   2135 
   2136 	for (i = 0; i < dev_priv->num_fence_regs; i++) {
   2137 		struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
   2138 
   2139 		i915_gem_write_fence(dev, i, NULL);
   2140 
   2141 		if (reg->obj)
   2142 			i915_gem_object_fence_lost(reg->obj);
   2143 
   2144 		reg->pin_count = 0;
   2145 		reg->obj = NULL;
   2146 		INIT_LIST_HEAD(&reg->lru_list);
   2147 	}
   2148 
   2149 	INIT_LIST_HEAD(&dev_priv->mm.fence_list);
   2150 }
   2151 
   2152 void i915_gem_reset(struct drm_device *dev)
   2153 {
   2154 	struct drm_i915_private *dev_priv = dev->dev_private;
   2155 	struct drm_i915_gem_object *obj;
   2156 	struct intel_ring_buffer *ring;
   2157 	int i;
   2158 
   2159 	for_each_ring(ring, dev_priv, i)
   2160 		i915_gem_reset_ring_lists(dev_priv, ring);
   2161 
   2162 	/* Move everything out of the GPU domains to ensure we do any
   2163 	 * necessary invalidation upon reuse.
   2164 	 */
   2165 	list_for_each_entry(obj,
   2166 			    &dev_priv->mm.inactive_list,
   2167 			    mm_list)
   2168 	{
   2169 		obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
   2170 	}
   2171 
   2172 	/* The fence registers are invalidated so clear them out */
   2173 	i915_gem_reset_fences(dev);
   2174 }
   2175 
   2176 /**
   2177  * This function clears the request list as sequence numbers are passed.
   2178  */
   2179 void
   2180 i915_gem_retire_requests_ring(struct intel_ring_buffer *ring)
   2181 {
   2182 	uint32_t seqno;
   2183 
   2184 	if (list_empty(&ring->request_list))
   2185 		return;
   2186 
   2187 	WARN_ON(i915_verify_lists(ring->dev));
   2188 
   2189 	seqno = ring->get_seqno(ring, true);
   2190 
   2191 	while (!list_empty(&ring->request_list)) {
   2192 		struct drm_i915_gem_request *request;
   2193 
   2194 		request = list_first_entry(&ring->request_list,
   2195 					   struct drm_i915_gem_request,
   2196 					   list);
   2197 
   2198 		if (!i915_seqno_passed(seqno, request->seqno))
   2199 			break;
   2200 
   2201 		trace_i915_gem_request_retire(ring, request->seqno);
   2202 		/* We know the GPU must have read the request to have
   2203 		 * sent us the seqno + interrupt, so use the position
   2204 		 * of tail of the request to update the last known position
   2205 		 * of the GPU head.
   2206 		 */
   2207 		ring->last_retired_head = request->tail;
   2208 
   2209 		list_del(&request->list);
   2210 		i915_gem_request_remove_from_client(request);
   2211 		kfree(request);
   2212 	}
   2213 
   2214 	/* Move any buffers on the active list that are no longer referenced
   2215 	 * by the ringbuffer to the flushing/inactive lists as appropriate.
   2216 	 */
   2217 	while (!list_empty(&ring->active_list)) {
   2218 		struct drm_i915_gem_object *obj;
   2219 
   2220 		obj = list_first_entry(&ring->active_list,
   2221 				      struct drm_i915_gem_object,
   2222 				      ring_list);
   2223 
   2224 		if (!i915_seqno_passed(seqno, obj->last_read_seqno))
   2225 			break;
   2226 
   2227 		i915_gem_object_move_to_inactive(obj);
   2228 	}
   2229 
   2230 	if (unlikely(ring->trace_irq_seqno &&
   2231 		     i915_seqno_passed(seqno, ring->trace_irq_seqno))) {
   2232 		ring->irq_put(ring);
   2233 		ring->trace_irq_seqno = 0;
   2234 	}
   2235 
   2236 	WARN_ON(i915_verify_lists(ring->dev));
   2237 }
   2238 
   2239 void
   2240 i915_gem_retire_requests(struct drm_device *dev)
   2241 {
   2242 	drm_i915_private_t *dev_priv = dev->dev_private;
   2243 	struct intel_ring_buffer *ring;
   2244 	int i;
   2245 
   2246 	for_each_ring(ring, dev_priv, i)
   2247 		i915_gem_retire_requests_ring(ring);
   2248 }
   2249 
   2250 static void
   2251 i915_gem_retire_work_handler(struct work_struct *work)
   2252 {
   2253 	drm_i915_private_t *dev_priv;
   2254 	struct drm_device *dev;
   2255 	struct intel_ring_buffer *ring;
   2256 	bool idle;
   2257 	int i;
   2258 
   2259 	dev_priv = container_of(work, drm_i915_private_t,
   2260 				mm.retire_work.work);
   2261 	dev = dev_priv->dev;
   2262 
   2263 	/* Come back later if the device is busy... */
   2264 	if (!mutex_trylock(&dev->struct_mutex)) {
   2265 		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work,
   2266 				   round_jiffies_up_relative(HZ));
   2267 		return;
   2268 	}
   2269 
   2270 	i915_gem_retire_requests(dev);
   2271 
   2272 	/* Send a periodic flush down the ring so we don't hold onto GEM
   2273 	 * objects indefinitely.
   2274 	 */
   2275 	idle = true;
   2276 	for_each_ring(ring, dev_priv, i) {
   2277 		if (ring->gpu_caches_dirty)
   2278 			i915_add_request(ring, NULL, NULL);
   2279 
   2280 		idle &= list_empty(&ring->request_list);
   2281 	}
   2282 
   2283 	if (!dev_priv->mm.suspended && !idle)
   2284 		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work,
   2285 				   round_jiffies_up_relative(HZ));
   2286 	if (idle)
   2287 		intel_mark_idle(dev);
   2288 
   2289 	mutex_unlock(&dev->struct_mutex);
   2290 }
   2291 
   2292 /**
   2293  * Ensures that an object will eventually get non-busy by flushing any required
   2294  * write domains, emitting any outstanding lazy request and retiring and
   2295  * completed requests.
   2296  */
   2297 static int
   2298 i915_gem_object_flush_active(struct drm_i915_gem_object *obj)
   2299 {
   2300 	int ret;
   2301 
   2302 	if (obj->active) {
   2303 		ret = i915_gem_check_olr(obj->ring, obj->last_read_seqno);
   2304 		if (ret)
   2305 			return ret;
   2306 
   2307 		i915_gem_retire_requests_ring(obj->ring);
   2308 	}
   2309 
   2310 	return 0;
   2311 }
   2312 
   2313 /**
   2314  * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
   2315  * @DRM_IOCTL_ARGS: standard ioctl arguments
   2316  *
   2317  * Returns 0 if successful, else an error is returned with the remaining time in
   2318  * the timeout parameter.
   2319  *  -ETIME: object is still busy after timeout
   2320  *  -ERESTARTSYS: signal interrupted the wait
   2321  *  -ENONENT: object doesn't exist
   2322  * Also possible, but rare:
   2323  *  -EAGAIN: GPU wedged
   2324  *  -ENOMEM: damn
   2325  *  -ENODEV: Internal IRQ fail
   2326  *  -E?: The add request failed
   2327  *
   2328  * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
   2329  * non-zero timeout parameter the wait ioctl will wait for the given number of
   2330  * nanoseconds on an object becoming unbusy. Since the wait itself does so
   2331  * without holding struct_mutex the object may become re-busied before this
   2332  * function completes. A similar but shorter * race condition exists in the busy
   2333  * ioctl
   2334  */
   2335 int
   2336 i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
   2337 {
   2338 	struct drm_i915_gem_wait *args = data;
   2339 	struct drm_i915_gem_object *obj;
   2340 	struct intel_ring_buffer *ring = NULL;
   2341 	struct timespec timeout_stack, *timeout = NULL;
   2342 	u32 seqno = 0;
   2343 	int ret = 0;
   2344 
   2345 	if (args->timeout_ns >= 0) {
   2346 		timeout_stack = ns_to_timespec(args->timeout_ns);
   2347 		timeout = &timeout_stack;
   2348 	}
   2349 
   2350 	ret = i915_mutex_lock_interruptible(dev);
   2351 	if (ret)
   2352 		return ret;
   2353 
   2354 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->bo_handle));
   2355 	if (&obj->base == NULL) {
   2356 		mutex_unlock(&dev->struct_mutex);
   2357 		return -ENOENT;
   2358 	}
   2359 
   2360 	/* Need to make sure the object gets inactive eventually. */
   2361 	ret = i915_gem_object_flush_active(obj);
   2362 	if (ret)
   2363 		goto out;
   2364 
   2365 	if (obj->active) {
   2366 		seqno = obj->last_read_seqno;
   2367 		ring = obj->ring;
   2368 	}
   2369 
   2370 	if (seqno == 0)
   2371 		 goto out;
   2372 
   2373 	/* Do this after OLR check to make sure we make forward progress polling
   2374 	 * on this IOCTL with a 0 timeout (like busy ioctl)
   2375 	 */
   2376 	if (!args->timeout_ns) {
   2377 		ret = -ETIME;
   2378 		goto out;
   2379 	}
   2380 
   2381 	drm_gem_object_unreference(&obj->base);
   2382 	mutex_unlock(&dev->struct_mutex);
   2383 
   2384 	ret = __wait_seqno(ring, seqno, true, timeout);
   2385 	if (timeout) {
   2386 		WARN_ON(!timespec_valid(timeout));
   2387 		args->timeout_ns = timespec_to_ns(timeout);
   2388 	}
   2389 	return ret;
   2390 
   2391 out:
   2392 	drm_gem_object_unreference(&obj->base);
   2393 	mutex_unlock(&dev->struct_mutex);
   2394 	return ret;
   2395 }
   2396 
   2397 /**
   2398  * i915_gem_object_sync - sync an object to a ring.
   2399  *
   2400  * @obj: object which may be in use on another ring.
   2401  * @to: ring we wish to use the object on. May be NULL.
   2402  *
   2403  * This code is meant to abstract object synchronization with the GPU.
   2404  * Calling with NULL implies synchronizing the object with the CPU
   2405  * rather than a particular GPU ring.
   2406  *
   2407  * Returns 0 if successful, else propagates up the lower layer error.
   2408  */
   2409 int
   2410 i915_gem_object_sync(struct drm_i915_gem_object *obj,
   2411 		     struct intel_ring_buffer *to)
   2412 {
   2413 	struct intel_ring_buffer *from = obj->ring;
   2414 	u32 seqno;
   2415 	int ret, idx;
   2416 
   2417 	if (from == NULL || to == from)
   2418 		return 0;
   2419 
   2420 	if (to == NULL || !i915_semaphore_is_enabled(obj->base.dev))
   2421 		return i915_gem_object_wait_rendering(obj, false);
   2422 
   2423 	idx = intel_ring_sync_index(from, to);
   2424 
   2425 	seqno = obj->last_read_seqno;
   2426 	if (seqno <= from->sync_seqno[idx])
   2427 		return 0;
   2428 
   2429 	ret = i915_gem_check_olr(obj->ring, seqno);
   2430 	if (ret)
   2431 		return ret;
   2432 
   2433 	ret = to->sync_to(to, from, seqno);
   2434 	if (!ret)
   2435 		/* We use last_read_seqno because sync_to()
   2436 		 * might have just caused seqno wrap under
   2437 		 * the radar.
   2438 		 */
   2439 		from->sync_seqno[idx] = obj->last_read_seqno;
   2440 
   2441 	return ret;
   2442 }
   2443 
   2444 static void i915_gem_object_finish_gtt(struct drm_i915_gem_object *obj)
   2445 {
   2446 	u32 old_write_domain, old_read_domains;
   2447 
   2448 	/* Act a barrier for all accesses through the GTT */
   2449 	mb();
   2450 
   2451 	/* Force a pagefault for domain tracking on next user access */
   2452 	i915_gem_release_mmap(obj);
   2453 
   2454 	if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
   2455 		return;
   2456 
   2457 	old_read_domains = obj->base.read_domains;
   2458 	old_write_domain = obj->base.write_domain;
   2459 
   2460 	obj->base.read_domains &= ~I915_GEM_DOMAIN_GTT;
   2461 	obj->base.write_domain &= ~I915_GEM_DOMAIN_GTT;
   2462 
   2463 	trace_i915_gem_object_change_domain(obj,
   2464 					    old_read_domains,
   2465 					    old_write_domain);
   2466 }
   2467 
   2468 /**
   2469  * Unbinds an object from the GTT aperture.
   2470  */
   2471 int
   2472 i915_gem_object_unbind(struct drm_i915_gem_object *obj)
   2473 {
   2474 	drm_i915_private_t *dev_priv = obj->base.dev->dev_private;
   2475 	int ret = 0;
   2476 
   2477 	if (obj->gtt_space == NULL)
   2478 		return 0;
   2479 
   2480 	if (obj->pin_count)
   2481 		return -EBUSY;
   2482 
   2483 	BUG_ON(obj->pages == NULL);
   2484 
   2485 	ret = i915_gem_object_finish_gpu(obj);
   2486 	if (ret)
   2487 		return ret;
   2488 	/* Continue on if we fail due to EIO, the GPU is hung so we
   2489 	 * should be safe and we need to cleanup or else we might
   2490 	 * cause memory corruption through use-after-free.
   2491 	 */
   2492 
   2493 	i915_gem_object_finish_gtt(obj);
   2494 
   2495 	/* release the fence reg _after_ flushing */
   2496 	ret = i915_gem_object_put_fence(obj);
   2497 	if (ret)
   2498 		return ret;
   2499 
   2500 	trace_i915_gem_object_unbind(obj);
   2501 
   2502 	if (obj->has_global_gtt_mapping)
   2503 		i915_gem_gtt_unbind_object(obj);
   2504 	if (obj->has_aliasing_ppgtt_mapping) {
   2505 		i915_ppgtt_unbind_object(dev_priv->mm.aliasing_ppgtt, obj);
   2506 		obj->has_aliasing_ppgtt_mapping = 0;
   2507 	}
   2508 	i915_gem_gtt_finish_object(obj);
   2509 
   2510 	list_del(&obj->mm_list);
   2511 	list_move_tail(&obj->gtt_list, &dev_priv->mm.unbound_list);
   2512 	/* Avoid an unnecessary call to unbind on rebind. */
   2513 	obj->map_and_fenceable = true;
   2514 
   2515 	drm_mm_put_block(obj->gtt_space);
   2516 	obj->gtt_space = NULL;
   2517 	obj->gtt_offset = 0;
   2518 
   2519 	return 0;
   2520 }
   2521 
   2522 int i915_gpu_idle(struct drm_device *dev)
   2523 {
   2524 	drm_i915_private_t *dev_priv = dev->dev_private;
   2525 	struct intel_ring_buffer *ring;
   2526 	int ret, i;
   2527 
   2528 	/* Flush everything onto the inactive list. */
   2529 	for_each_ring(ring, dev_priv, i) {
   2530 		ret = i915_switch_context(ring, NULL, DEFAULT_CONTEXT_ID);
   2531 		if (ret)
   2532 			return ret;
   2533 
   2534 		ret = intel_ring_idle(ring);
   2535 		if (ret)
   2536 			return ret;
   2537 	}
   2538 
   2539 	return 0;
   2540 }
   2541 
   2542 static void sandybridge_write_fence_reg(struct drm_device *dev, int reg,
   2543 					struct drm_i915_gem_object *obj)
   2544 {
   2545 	drm_i915_private_t *dev_priv = dev->dev_private;
   2546 	uint64_t val;
   2547 
   2548 	if (obj) {
   2549 		u32 size = obj->gtt_space->size;
   2550 
   2551 		val = (uint64_t)((obj->gtt_offset + size - 4096) &
   2552 				 0xfffff000) << 32;
   2553 		val |= obj->gtt_offset & 0xfffff000;
   2554 		val |= (uint64_t)((obj->stride / 128) - 1) <<
   2555 			SANDYBRIDGE_FENCE_PITCH_SHIFT;
   2556 
   2557 		if (obj->tiling_mode == I915_TILING_Y)
   2558 			val |= 1 << I965_FENCE_TILING_Y_SHIFT;
   2559 		val |= I965_FENCE_REG_VALID;
   2560 	} else
   2561 		val = 0;
   2562 
   2563 	I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 + reg * 8, val);
   2564 	POSTING_READ(FENCE_REG_SANDYBRIDGE_0 + reg * 8);
   2565 }
   2566 
   2567 static void i965_write_fence_reg(struct drm_device *dev, int reg,
   2568 				 struct drm_i915_gem_object *obj)
   2569 {
   2570 	drm_i915_private_t *dev_priv = dev->dev_private;
   2571 	uint64_t val;
   2572 
   2573 	if (obj) {
   2574 		u32 size = obj->gtt_space->size;
   2575 
   2576 		val = (uint64_t)((obj->gtt_offset + size - 4096) &
   2577 				 0xfffff000) << 32;
   2578 		val |= obj->gtt_offset & 0xfffff000;
   2579 		val |= ((obj->stride / 128) - 1) << I965_FENCE_PITCH_SHIFT;
   2580 		if (obj->tiling_mode == I915_TILING_Y)
   2581 			val |= 1 << I965_FENCE_TILING_Y_SHIFT;
   2582 		val |= I965_FENCE_REG_VALID;
   2583 	} else
   2584 		val = 0;
   2585 
   2586 	I915_WRITE64(FENCE_REG_965_0 + reg * 8, val);
   2587 	POSTING_READ(FENCE_REG_965_0 + reg * 8);
   2588 }
   2589 
   2590 static void i915_write_fence_reg(struct drm_device *dev, int reg,
   2591 				 struct drm_i915_gem_object *obj)
   2592 {
   2593 	drm_i915_private_t *dev_priv = dev->dev_private;
   2594 	u32 val;
   2595 
   2596 	if (obj) {
   2597 		u32 size = obj->gtt_space->size;
   2598 		int pitch_val;
   2599 		int tile_width;
   2600 
   2601 		WARN((obj->gtt_offset & ~I915_FENCE_START_MASK) ||
   2602 		     (size & -size) != size ||
   2603 		     (obj->gtt_offset & (size - 1)),
   2604 		     "object 0x%08x [fenceable? %d] not 1M or pot-size (0x%08x) aligned\n",
   2605 		     obj->gtt_offset, obj->map_and_fenceable, size);
   2606 
   2607 		if (obj->tiling_mode == I915_TILING_Y && HAS_128_BYTE_Y_TILING(dev))
   2608 			tile_width = 128;
   2609 		else
   2610 			tile_width = 512;
   2611 
   2612 		/* Note: pitch better be a power of two tile widths */
   2613 		pitch_val = obj->stride / tile_width;
   2614 		pitch_val = ffs(pitch_val) - 1;
   2615 
   2616 		val = obj->gtt_offset;
   2617 		if (obj->tiling_mode == I915_TILING_Y)
   2618 			val |= 1 << I830_FENCE_TILING_Y_SHIFT;
   2619 		val |= I915_FENCE_SIZE_BITS(size);
   2620 		val |= pitch_val << I830_FENCE_PITCH_SHIFT;
   2621 		val |= I830_FENCE_REG_VALID;
   2622 	} else
   2623 		val = 0;
   2624 
   2625 	if (reg < 8)
   2626 		reg = FENCE_REG_830_0 + reg * 4;
   2627 	else
   2628 		reg = FENCE_REG_945_8 + (reg - 8) * 4;
   2629 
   2630 	I915_WRITE(reg, val);
   2631 	POSTING_READ(reg);
   2632 }
   2633 
   2634 static void i830_write_fence_reg(struct drm_device *dev, int reg,
   2635 				struct drm_i915_gem_object *obj)
   2636 {
   2637 	drm_i915_private_t *dev_priv = dev->dev_private;
   2638 	uint32_t val;
   2639 
   2640 	if (obj) {
   2641 		u32 size = obj->gtt_space->size;
   2642 		uint32_t pitch_val;
   2643 
   2644 		WARN((obj->gtt_offset & ~I830_FENCE_START_MASK) ||
   2645 		     (size & -size) != size ||
   2646 		     (obj->gtt_offset & (size - 1)),
   2647 		     "object 0x%08x not 512K or pot-size 0x%08x aligned\n",
   2648 		     obj->gtt_offset, size);
   2649 
   2650 		pitch_val = obj->stride / 128;
   2651 		pitch_val = ffs(pitch_val) - 1;
   2652 
   2653 		val = obj->gtt_offset;
   2654 		if (obj->tiling_mode == I915_TILING_Y)
   2655 			val |= 1 << I830_FENCE_TILING_Y_SHIFT;
   2656 		val |= I830_FENCE_SIZE_BITS(size);
   2657 		val |= pitch_val << I830_FENCE_PITCH_SHIFT;
   2658 		val |= I830_FENCE_REG_VALID;
   2659 	} else
   2660 		val = 0;
   2661 
   2662 	I915_WRITE(FENCE_REG_830_0 + reg * 4, val);
   2663 	POSTING_READ(FENCE_REG_830_0 + reg * 4);
   2664 }
   2665 
   2666 static void i915_gem_write_fence(struct drm_device *dev, int reg,
   2667 				 struct drm_i915_gem_object *obj)
   2668 {
   2669 	switch (INTEL_INFO(dev)->gen) {
   2670 	case 7:
   2671 	case 6: sandybridge_write_fence_reg(dev, reg, obj); break;
   2672 	case 5:
   2673 	case 4: i965_write_fence_reg(dev, reg, obj); break;
   2674 	case 3: i915_write_fence_reg(dev, reg, obj); break;
   2675 	case 2: i830_write_fence_reg(dev, reg, obj); break;
   2676 	default: break;
   2677 	}
   2678 }
   2679 
   2680 static inline int fence_number(struct drm_i915_private *dev_priv,
   2681 			       struct drm_i915_fence_reg *fence)
   2682 {
   2683 	return fence - dev_priv->fence_regs;
   2684 }
   2685 
   2686 static void i915_gem_object_update_fence(struct drm_i915_gem_object *obj,
   2687 					 struct drm_i915_fence_reg *fence,
   2688 					 bool enable)
   2689 {
   2690 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   2691 	int reg = fence_number(dev_priv, fence);
   2692 
   2693 	i915_gem_write_fence(obj->base.dev, reg, enable ? obj : NULL);
   2694 
   2695 	if (enable) {
   2696 		obj->fence_reg = reg;
   2697 		fence->obj = obj;
   2698 		list_move_tail(&fence->lru_list, &dev_priv->mm.fence_list);
   2699 	} else {
   2700 		obj->fence_reg = I915_FENCE_REG_NONE;
   2701 		fence->obj = NULL;
   2702 		list_del_init(&fence->lru_list);
   2703 	}
   2704 }
   2705 
   2706 static int
   2707 i915_gem_object_flush_fence(struct drm_i915_gem_object *obj)
   2708 {
   2709 	if (obj->last_fenced_seqno) {
   2710 		int ret = i915_wait_seqno(obj->ring, obj->last_fenced_seqno);
   2711 		if (ret)
   2712 			return ret;
   2713 
   2714 		obj->last_fenced_seqno = 0;
   2715 	}
   2716 
   2717 	/* Ensure that all CPU reads are completed before installing a fence
   2718 	 * and all writes before removing the fence.
   2719 	 */
   2720 	if (obj->base.read_domains & I915_GEM_DOMAIN_GTT)
   2721 		mb();
   2722 
   2723 	obj->fenced_gpu_access = false;
   2724 	return 0;
   2725 }
   2726 
   2727 int
   2728 i915_gem_object_put_fence(struct drm_i915_gem_object *obj)
   2729 {
   2730 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   2731 	int ret;
   2732 
   2733 	ret = i915_gem_object_flush_fence(obj);
   2734 	if (ret)
   2735 		return ret;
   2736 
   2737 	if (obj->fence_reg == I915_FENCE_REG_NONE)
   2738 		return 0;
   2739 
   2740 	i915_gem_object_update_fence(obj,
   2741 				     &dev_priv->fence_regs[obj->fence_reg],
   2742 				     false);
   2743 	i915_gem_object_fence_lost(obj);
   2744 
   2745 	return 0;
   2746 }
   2747 
   2748 static struct drm_i915_fence_reg *
   2749 i915_find_fence_reg(struct drm_device *dev)
   2750 {
   2751 	struct drm_i915_private *dev_priv = dev->dev_private;
   2752 	struct drm_i915_fence_reg *reg, *avail;
   2753 	int i;
   2754 
   2755 	/* First try to find a free reg */
   2756 	avail = NULL;
   2757 	for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
   2758 		reg = &dev_priv->fence_regs[i];
   2759 		if (!reg->obj)
   2760 			return reg;
   2761 
   2762 		if (!reg->pin_count)
   2763 			avail = reg;
   2764 	}
   2765 
   2766 	if (avail == NULL)
   2767 		return NULL;
   2768 
   2769 	/* None available, try to steal one or wait for a user to finish */
   2770 	list_for_each_entry(reg, &dev_priv->mm.fence_list, lru_list) {
   2771 		if (reg->pin_count)
   2772 			continue;
   2773 
   2774 		return reg;
   2775 	}
   2776 
   2777 	return NULL;
   2778 }
   2779 
   2780 /**
   2781  * i915_gem_object_get_fence - set up fencing for an object
   2782  * @obj: object to map through a fence reg
   2783  *
   2784  * When mapping objects through the GTT, userspace wants to be able to write
   2785  * to them without having to worry about swizzling if the object is tiled.
   2786  * This function walks the fence regs looking for a free one for @obj,
   2787  * stealing one if it can't find any.
   2788  *
   2789  * It then sets up the reg based on the object's properties: address, pitch
   2790  * and tiling format.
   2791  *
   2792  * For an untiled surface, this removes any existing fence.
   2793  */
   2794 int
   2795 i915_gem_object_get_fence(struct drm_i915_gem_object *obj)
   2796 {
   2797 	struct drm_device *dev = obj->base.dev;
   2798 	struct drm_i915_private *dev_priv = dev->dev_private;
   2799 	bool enable = obj->tiling_mode != I915_TILING_NONE;
   2800 	struct drm_i915_fence_reg *reg;
   2801 	int ret;
   2802 
   2803 	/* Have we updated the tiling parameters upon the object and so
   2804 	 * will need to serialise the write to the associated fence register?
   2805 	 */
   2806 	if (obj->fence_dirty) {
   2807 		ret = i915_gem_object_flush_fence(obj);
   2808 		if (ret)
   2809 			return ret;
   2810 	}
   2811 
   2812 	/* Just update our place in the LRU if our fence is getting reused. */
   2813 	if (obj->fence_reg != I915_FENCE_REG_NONE) {
   2814 		reg = &dev_priv->fence_regs[obj->fence_reg];
   2815 		if (!obj->fence_dirty) {
   2816 			list_move_tail(&reg->lru_list,
   2817 				       &dev_priv->mm.fence_list);
   2818 			return 0;
   2819 		}
   2820 	} else if (enable) {
   2821 		reg = i915_find_fence_reg(dev);
   2822 		if (reg == NULL)
   2823 			return -EDEADLK;
   2824 
   2825 		if (reg->obj) {
   2826 			struct drm_i915_gem_object *old = reg->obj;
   2827 
   2828 			ret = i915_gem_object_flush_fence(old);
   2829 			if (ret)
   2830 				return ret;
   2831 
   2832 			i915_gem_object_fence_lost(old);
   2833 		}
   2834 	} else
   2835 		return 0;
   2836 
   2837 	i915_gem_object_update_fence(obj, reg, enable);
   2838 	obj->fence_dirty = false;
   2839 
   2840 	return 0;
   2841 }
   2842 
   2843 static bool i915_gem_valid_gtt_space(struct drm_device *dev,
   2844 				     struct drm_mm_node *gtt_space,
   2845 				     unsigned long cache_level)
   2846 {
   2847 	struct drm_mm_node *other;
   2848 
   2849 	/* On non-LLC machines we have to be careful when putting differing
   2850 	 * types of snoopable memory together to avoid the prefetcher
   2851 	 * crossing memory domains and dieing.
   2852 	 */
   2853 	if (HAS_LLC(dev))
   2854 		return true;
   2855 
   2856 	if (gtt_space == NULL)
   2857 		return true;
   2858 
   2859 	if (list_empty(&gtt_space->node_list))
   2860 		return true;
   2861 
   2862 	other = list_entry(gtt_space->node_list.prev, struct drm_mm_node, node_list);
   2863 	if (other->allocated && !other->hole_follows && other->color != cache_level)
   2864 		return false;
   2865 
   2866 	other = list_entry(gtt_space->node_list.next, struct drm_mm_node, node_list);
   2867 	if (other->allocated && !gtt_space->hole_follows && other->color != cache_level)
   2868 		return false;
   2869 
   2870 	return true;
   2871 }
   2872 
   2873 static void i915_gem_verify_gtt(struct drm_device *dev)
   2874 {
   2875 #if WATCH_GTT
   2876 	struct drm_i915_private *dev_priv = dev->dev_private;
   2877 	struct drm_i915_gem_object *obj;
   2878 	int err = 0;
   2879 
   2880 	list_for_each_entry(obj, &dev_priv->mm.gtt_list, gtt_list) {
   2881 		if (obj->gtt_space == NULL) {
   2882 			printk(KERN_ERR "object found on GTT list with no space reserved\n");
   2883 			err++;
   2884 			continue;
   2885 		}
   2886 
   2887 		if (obj->cache_level != obj->gtt_space->color) {
   2888 			printk(KERN_ERR "object reserved space [%08lx, %08lx] with wrong color, cache_level=%x, color=%lx\n",
   2889 			       obj->gtt_space->start,
   2890 			       obj->gtt_space->start + obj->gtt_space->size,
   2891 			       obj->cache_level,
   2892 			       obj->gtt_space->color);
   2893 			err++;
   2894 			continue;
   2895 		}
   2896 
   2897 		if (!i915_gem_valid_gtt_space(dev,
   2898 					      obj->gtt_space,
   2899 					      obj->cache_level)) {
   2900 			printk(KERN_ERR "invalid GTT space found at [%08lx, %08lx] - color=%x\n",
   2901 			       obj->gtt_space->start,
   2902 			       obj->gtt_space->start + obj->gtt_space->size,
   2903 			       obj->cache_level);
   2904 			err++;
   2905 			continue;
   2906 		}
   2907 	}
   2908 
   2909 	WARN_ON(err);
   2910 #endif
   2911 }
   2912 
   2913 /**
   2914  * Finds free space in the GTT aperture and binds the object there.
   2915  */
   2916 static int
   2917 i915_gem_object_bind_to_gtt(struct drm_i915_gem_object *obj,
   2918 			    unsigned alignment,
   2919 			    bool map_and_fenceable,
   2920 			    bool nonblocking)
   2921 {
   2922 	struct drm_device *dev = obj->base.dev;
   2923 	drm_i915_private_t *dev_priv = dev->dev_private;
   2924 	struct drm_mm_node *node;
   2925 	u32 size, fence_size, fence_alignment, unfenced_alignment;
   2926 	bool mappable, fenceable;
   2927 	int ret;
   2928 
   2929 	if (obj->madv != I915_MADV_WILLNEED) {
   2930 		DRM_ERROR("Attempting to bind a purgeable object\n");
   2931 		return -EINVAL;
   2932 	}
   2933 
   2934 	fence_size = i915_gem_get_gtt_size(dev,
   2935 					   obj->base.size,
   2936 					   obj->tiling_mode);
   2937 	fence_alignment = i915_gem_get_gtt_alignment(dev,
   2938 						     obj->base.size,
   2939 						     obj->tiling_mode);
   2940 	unfenced_alignment =
   2941 		i915_gem_get_unfenced_gtt_alignment(dev,
   2942 						    obj->base.size,
   2943 						    obj->tiling_mode);
   2944 
   2945 	if (alignment == 0)
   2946 		alignment = map_and_fenceable ? fence_alignment :
   2947 						unfenced_alignment;
   2948 	if (map_and_fenceable && alignment & (fence_alignment - 1)) {
   2949 		DRM_ERROR("Invalid object alignment requested %u\n", alignment);
   2950 		return -EINVAL;
   2951 	}
   2952 
   2953 	size = map_and_fenceable ? fence_size : obj->base.size;
   2954 
   2955 	/* If the object is bigger than the entire aperture, reject it early
   2956 	 * before evicting everything in a vain attempt to find space.
   2957 	 */
   2958 	if (obj->base.size >
   2959 	    (map_and_fenceable ? dev_priv->mm.gtt_mappable_end : dev_priv->mm.gtt_total)) {
   2960 		DRM_ERROR("Attempting to bind an object larger than the aperture\n");
   2961 		return -E2BIG;
   2962 	}
   2963 
   2964 	ret = i915_gem_object_get_pages(obj);
   2965 	if (ret)
   2966 		return ret;
   2967 
   2968 	i915_gem_object_pin_pages(obj);
   2969 
   2970 	node = kzalloc(sizeof(*node), GFP_KERNEL);
   2971 	if (node == NULL) {
   2972 		i915_gem_object_unpin_pages(obj);
   2973 		return -ENOMEM;
   2974 	}
   2975 
   2976  search_free:
   2977 	if (map_and_fenceable)
   2978 		ret = drm_mm_insert_node_in_range_generic(&dev_priv->mm.gtt_space, node,
   2979 							  size, alignment, obj->cache_level,
   2980 							  0, dev_priv->mm.gtt_mappable_end);
   2981 	else
   2982 		ret = drm_mm_insert_node_generic(&dev_priv->mm.gtt_space, node,
   2983 						 size, alignment, obj->cache_level);
   2984 	if (ret) {
   2985 		ret = i915_gem_evict_something(dev, size, alignment,
   2986 					       obj->cache_level,
   2987 					       map_and_fenceable,
   2988 					       nonblocking);
   2989 		if (ret == 0)
   2990 			goto search_free;
   2991 
   2992 		i915_gem_object_unpin_pages(obj);
   2993 		kfree(node);
   2994 		return ret;
   2995 	}
   2996 	if (WARN_ON(!i915_gem_valid_gtt_space(dev, node, obj->cache_level))) {
   2997 		i915_gem_object_unpin_pages(obj);
   2998 		drm_mm_put_block(node);
   2999 		return -EINVAL;
   3000 	}
   3001 
   3002 	ret = i915_gem_gtt_prepare_object(obj);
   3003 	if (ret) {
   3004 		i915_gem_object_unpin_pages(obj);
   3005 		drm_mm_put_block(node);
   3006 		return ret;
   3007 	}
   3008 
   3009 	list_move_tail(&obj->gtt_list, &dev_priv->mm.bound_list);
   3010 	list_add_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
   3011 
   3012 	obj->gtt_space = node;
   3013 	obj->gtt_offset = node->start;
   3014 
   3015 	fenceable =
   3016 		node->size == fence_size &&
   3017 		(node->start & (fence_alignment - 1)) == 0;
   3018 
   3019 	mappable =
   3020 		obj->gtt_offset + obj->base.size <= dev_priv->mm.gtt_mappable_end;
   3021 
   3022 	obj->map_and_fenceable = mappable && fenceable;
   3023 
   3024 	i915_gem_object_unpin_pages(obj);
   3025 	trace_i915_gem_object_bind(obj, map_and_fenceable);
   3026 	i915_gem_verify_gtt(dev);
   3027 	return 0;
   3028 }
   3029 
   3030 void
   3031 i915_gem_clflush_object(struct drm_i915_gem_object *obj)
   3032 {
   3033 	/* If we don't have a page list set up, then we're not pinned
   3034 	 * to GPU, and we can ignore the cache flush because it'll happen
   3035 	 * again at bind time.
   3036 	 */
   3037 	if (obj->pages == NULL)
   3038 		return;
   3039 
   3040 	/* If the GPU is snooping the contents of the CPU cache,
   3041 	 * we do not need to manually clear the CPU cache lines.  However,
   3042 	 * the caches are only snooped when the render cache is
   3043 	 * flushed/invalidated.  As we always have to emit invalidations
   3044 	 * and flushes when moving into and out of the RENDER domain, correct
   3045 	 * snooping behaviour occurs naturally as the result of our domain
   3046 	 * tracking.
   3047 	 */
   3048 	if (obj->cache_level != I915_CACHE_NONE)
   3049 		return;
   3050 
   3051 	trace_i915_gem_object_clflush(obj);
   3052 
   3053 	drm_clflush_sg(obj->pages);
   3054 }
   3055 
   3056 /** Flushes the GTT write domain for the object if it's dirty. */
   3057 static void
   3058 i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj)
   3059 {
   3060 	uint32_t old_write_domain;
   3061 
   3062 	if (obj->base.write_domain != I915_GEM_DOMAIN_GTT)
   3063 		return;
   3064 
   3065 	/* No actual flushing is required for the GTT write domain.  Writes
   3066 	 * to it immediately go to main memory as far as we know, so there's
   3067 	 * no chipset flush.  It also doesn't land in render cache.
   3068 	 *
   3069 	 * However, we do have to enforce the order so that all writes through
   3070 	 * the GTT land before any writes to the device, such as updates to
   3071 	 * the GATT itself.
   3072 	 */
   3073 	wmb();
   3074 
   3075 	old_write_domain = obj->base.write_domain;
   3076 	obj->base.write_domain = 0;
   3077 
   3078 	trace_i915_gem_object_change_domain(obj,
   3079 					    obj->base.read_domains,
   3080 					    old_write_domain);
   3081 }
   3082 
   3083 /** Flushes the CPU write domain for the object if it's dirty. */
   3084 static void
   3085 i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj)
   3086 {
   3087 	uint32_t old_write_domain;
   3088 
   3089 	if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
   3090 		return;
   3091 
   3092 	i915_gem_clflush_object(obj);
   3093 	i915_gem_chipset_flush(obj->base.dev);
   3094 	old_write_domain = obj->base.write_domain;
   3095 	obj->base.write_domain = 0;
   3096 
   3097 	trace_i915_gem_object_change_domain(obj,
   3098 					    obj->base.read_domains,
   3099 					    old_write_domain);
   3100 }
   3101 
   3102 /**
   3103  * Moves a single object to the GTT read, and possibly write domain.
   3104  *
   3105  * This function returns when the move is complete, including waiting on
   3106  * flushes to occur.
   3107  */
   3108 int
   3109 i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
   3110 {
   3111 	drm_i915_private_t *dev_priv = obj->base.dev->dev_private;
   3112 	uint32_t old_write_domain, old_read_domains;
   3113 	int ret;
   3114 
   3115 	/* Not valid to be called on unbound objects. */
   3116 	if (obj->gtt_space == NULL)
   3117 		return -EINVAL;
   3118 
   3119 	if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
   3120 		return 0;
   3121 
   3122 	ret = i915_gem_object_wait_rendering(obj, !write);
   3123 	if (ret)
   3124 		return ret;
   3125 
   3126 	i915_gem_object_flush_cpu_write_domain(obj);
   3127 
   3128 	old_write_domain = obj->base.write_domain;
   3129 	old_read_domains = obj->base.read_domains;
   3130 
   3131 	/* It should now be out of any other write domains, and we can update
   3132 	 * the domain values for our changes.
   3133 	 */
   3134 	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
   3135 	obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
   3136 	if (write) {
   3137 		obj->base.read_domains = I915_GEM_DOMAIN_GTT;
   3138 		obj->base.write_domain = I915_GEM_DOMAIN_GTT;
   3139 		obj->dirty = 1;
   3140 	}
   3141 
   3142 	trace_i915_gem_object_change_domain(obj,
   3143 					    old_read_domains,
   3144 					    old_write_domain);
   3145 
   3146 	/* And bump the LRU for this access */
   3147 	if (i915_gem_object_is_inactive(obj))
   3148 		list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
   3149 
   3150 	return 0;
   3151 }
   3152 
   3153 int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
   3154 				    enum i915_cache_level cache_level)
   3155 {
   3156 	struct drm_device *dev = obj->base.dev;
   3157 	drm_i915_private_t *dev_priv = dev->dev_private;
   3158 	int ret;
   3159 
   3160 	if (obj->cache_level == cache_level)
   3161 		return 0;
   3162 
   3163 	if (obj->pin_count) {
   3164 		DRM_DEBUG("can not change the cache level of pinned objects\n");
   3165 		return -EBUSY;
   3166 	}
   3167 
   3168 	if (!i915_gem_valid_gtt_space(dev, obj->gtt_space, cache_level)) {
   3169 		ret = i915_gem_object_unbind(obj);
   3170 		if (ret)
   3171 			return ret;
   3172 	}
   3173 
   3174 	if (obj->gtt_space) {
   3175 		ret = i915_gem_object_finish_gpu(obj);
   3176 		if (ret)
   3177 			return ret;
   3178 
   3179 		i915_gem_object_finish_gtt(obj);
   3180 
   3181 		/* Before SandyBridge, you could not use tiling or fence
   3182 		 * registers with snooped memory, so relinquish any fences
   3183 		 * currently pointing to our region in the aperture.
   3184 		 */
   3185 		if (INTEL_INFO(dev)->gen < 6) {
   3186 			ret = i915_gem_object_put_fence(obj);
   3187 			if (ret)
   3188 				return ret;
   3189 		}
   3190 
   3191 		if (obj->has_global_gtt_mapping)
   3192 			i915_gem_gtt_bind_object(obj, cache_level);
   3193 		if (obj->has_aliasing_ppgtt_mapping)
   3194 			i915_ppgtt_bind_object(dev_priv->mm.aliasing_ppgtt,
   3195 					       obj, cache_level);
   3196 
   3197 		obj->gtt_space->color = cache_level;
   3198 	}
   3199 
   3200 	if (cache_level == I915_CACHE_NONE) {
   3201 		u32 old_read_domains, old_write_domain;
   3202 
   3203 		/* If we're coming from LLC cached, then we haven't
   3204 		 * actually been tracking whether the data is in the
   3205 		 * CPU cache or not, since we only allow one bit set
   3206 		 * in obj->write_domain and have been skipping the clflushes.
   3207 		 * Just set it to the CPU cache for now.
   3208 		 */
   3209 		WARN_ON(obj->base.write_domain & ~I915_GEM_DOMAIN_CPU);
   3210 		WARN_ON(obj->base.read_domains & ~I915_GEM_DOMAIN_CPU);
   3211 
   3212 		old_read_domains = obj->base.read_domains;
   3213 		old_write_domain = obj->base.write_domain;
   3214 
   3215 		obj->base.read_domains = I915_GEM_DOMAIN_CPU;
   3216 		obj->base.write_domain = I915_GEM_DOMAIN_CPU;
   3217 
   3218 		trace_i915_gem_object_change_domain(obj,
   3219 						    old_read_domains,
   3220 						    old_write_domain);
   3221 	}
   3222 
   3223 	obj->cache_level = cache_level;
   3224 	i915_gem_verify_gtt(dev);
   3225 	return 0;
   3226 }
   3227 
   3228 int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
   3229 			       struct drm_file *file)
   3230 {
   3231 	struct drm_i915_gem_caching *args = data;
   3232 	struct drm_i915_gem_object *obj;
   3233 	int ret;
   3234 
   3235 	ret = i915_mutex_lock_interruptible(dev);
   3236 	if (ret)
   3237 		return ret;
   3238 
   3239 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   3240 	if (&obj->base == NULL) {
   3241 		ret = -ENOENT;
   3242 		goto unlock;
   3243 	}
   3244 
   3245 	args->caching = obj->cache_level != I915_CACHE_NONE;
   3246 
   3247 	drm_gem_object_unreference(&obj->base);
   3248 unlock:
   3249 	mutex_unlock(&dev->struct_mutex);
   3250 	return ret;
   3251 }
   3252 
   3253 int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
   3254 			       struct drm_file *file)
   3255 {
   3256 	struct drm_i915_gem_caching *args = data;
   3257 	struct drm_i915_gem_object *obj;
   3258 	enum i915_cache_level level;
   3259 	int ret;
   3260 
   3261 	switch (args->caching) {
   3262 	case I915_CACHING_NONE:
   3263 		level = I915_CACHE_NONE;
   3264 		break;
   3265 	case I915_CACHING_CACHED:
   3266 		level = I915_CACHE_LLC;
   3267 		break;
   3268 	default:
   3269 		return -EINVAL;
   3270 	}
   3271 
   3272 	ret = i915_mutex_lock_interruptible(dev);
   3273 	if (ret)
   3274 		return ret;
   3275 
   3276 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   3277 	if (&obj->base == NULL) {
   3278 		ret = -ENOENT;
   3279 		goto unlock;
   3280 	}
   3281 
   3282 	ret = i915_gem_object_set_cache_level(obj, level);
   3283 
   3284 	drm_gem_object_unreference(&obj->base);
   3285 unlock:
   3286 	mutex_unlock(&dev->struct_mutex);
   3287 	return ret;
   3288 }
   3289 
   3290 /*
   3291  * Prepare buffer for display plane (scanout, cursors, etc).
   3292  * Can be called from an uninterruptible phase (modesetting) and allows
   3293  * any flushes to be pipelined (for pageflips).
   3294  */
   3295 int
   3296 i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
   3297 				     u32 alignment,
   3298 				     struct intel_ring_buffer *pipelined)
   3299 {
   3300 	u32 old_read_domains, old_write_domain;
   3301 	int ret;
   3302 
   3303 	if (pipelined != obj->ring) {
   3304 		ret = i915_gem_object_sync(obj, pipelined);
   3305 		if (ret)
   3306 			return ret;
   3307 	}
   3308 
   3309 	/* The display engine is not coherent with the LLC cache on gen6.  As
   3310 	 * a result, we make sure that the pinning that is about to occur is
   3311 	 * done with uncached PTEs. This is lowest common denominator for all
   3312 	 * chipsets.
   3313 	 *
   3314 	 * However for gen6+, we could do better by using the GFDT bit instead
   3315 	 * of uncaching, which would allow us to flush all the LLC-cached data
   3316 	 * with that bit in the PTE to main memory with just one PIPE_CONTROL.
   3317 	 */
   3318 	ret = i915_gem_object_set_cache_level(obj, I915_CACHE_NONE);
   3319 	if (ret)
   3320 		return ret;
   3321 
   3322 	/* As the user may map the buffer once pinned in the display plane
   3323 	 * (e.g. libkms for the bootup splash), we have to ensure that we
   3324 	 * always use map_and_fenceable for all scanout buffers.
   3325 	 */
   3326 	ret = i915_gem_object_pin(obj, alignment, true, false);
   3327 	if (ret)
   3328 		return ret;
   3329 
   3330 	i915_gem_object_flush_cpu_write_domain(obj);
   3331 
   3332 	old_write_domain = obj->base.write_domain;
   3333 	old_read_domains = obj->base.read_domains;
   3334 
   3335 	/* It should now be out of any other write domains, and we can update
   3336 	 * the domain values for our changes.
   3337 	 */
   3338 	obj->base.write_domain = 0;
   3339 	obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
   3340 
   3341 	trace_i915_gem_object_change_domain(obj,
   3342 					    old_read_domains,
   3343 					    old_write_domain);
   3344 
   3345 	return 0;
   3346 }
   3347 
   3348 int
   3349 i915_gem_object_finish_gpu(struct drm_i915_gem_object *obj)
   3350 {
   3351 	int ret;
   3352 
   3353 	if ((obj->base.read_domains & I915_GEM_GPU_DOMAINS) == 0)
   3354 		return 0;
   3355 
   3356 	ret = i915_gem_object_wait_rendering(obj, false);
   3357 	if (ret)
   3358 		return ret;
   3359 
   3360 	/* Ensure that we invalidate the GPU's caches and TLBs. */
   3361 	obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
   3362 	return 0;
   3363 }
   3364 
   3365 /**
   3366  * Moves a single object to the CPU read, and possibly write domain.
   3367  *
   3368  * This function returns when the move is complete, including waiting on
   3369  * flushes to occur.
   3370  */
   3371 int
   3372 i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
   3373 {
   3374 	uint32_t old_write_domain, old_read_domains;
   3375 	int ret;
   3376 
   3377 	if (obj->base.write_domain == I915_GEM_DOMAIN_CPU)
   3378 		return 0;
   3379 
   3380 	ret = i915_gem_object_wait_rendering(obj, !write);
   3381 	if (ret)
   3382 		return ret;
   3383 
   3384 	i915_gem_object_flush_gtt_write_domain(obj);
   3385 
   3386 	old_write_domain = obj->base.write_domain;
   3387 	old_read_domains = obj->base.read_domains;
   3388 
   3389 	/* Flush the CPU cache if it's still invalid. */
   3390 	if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
   3391 		i915_gem_clflush_object(obj);
   3392 
   3393 		obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
   3394 	}
   3395 
   3396 	/* It should now be out of any other write domains, and we can update
   3397 	 * the domain values for our changes.
   3398 	 */
   3399 	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
   3400 
   3401 	/* If we're writing through the CPU, then the GPU read domains will
   3402 	 * need to be invalidated at next use.
   3403 	 */
   3404 	if (write) {
   3405 		obj->base.read_domains = I915_GEM_DOMAIN_CPU;
   3406 		obj->base.write_domain = I915_GEM_DOMAIN_CPU;
   3407 	}
   3408 
   3409 	trace_i915_gem_object_change_domain(obj,
   3410 					    old_read_domains,
   3411 					    old_write_domain);
   3412 
   3413 	return 0;
   3414 }
   3415 
   3416 /* Throttle our rendering by waiting until the ring has completed our requests
   3417  * emitted over 20 msec ago.
   3418  *
   3419  * Note that if we were to use the current jiffies each time around the loop,
   3420  * we wouldn't escape the function with any frames outstanding if the time to
   3421  * render a frame was over 20ms.
   3422  *
   3423  * This should get us reasonable parallelism between CPU and GPU but also
   3424  * relatively low latency when blocking on a particular request to finish.
   3425  */
   3426 static int
   3427 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
   3428 {
   3429 	struct drm_i915_private *dev_priv = dev->dev_private;
   3430 	struct drm_i915_file_private *file_priv = file->driver_priv;
   3431 	unsigned long recent_enough = jiffies - msecs_to_jiffies(20);
   3432 	struct drm_i915_gem_request *request;
   3433 	struct intel_ring_buffer *ring = NULL;
   3434 	u32 seqno = 0;
   3435 	int ret;
   3436 
   3437 	if (atomic_read(&dev_priv->mm.wedged))
   3438 		return -EIO;
   3439 
   3440 	spin_lock(&file_priv->mm.lock);
   3441 	list_for_each_entry(request, &file_priv->mm.request_list, client_list) {
   3442 		if (time_after_eq(request->emitted_jiffies, recent_enough))
   3443 			break;
   3444 
   3445 		ring = request->ring;
   3446 		seqno = request->seqno;
   3447 	}
   3448 	spin_unlock(&file_priv->mm.lock);
   3449 
   3450 	if (seqno == 0)
   3451 		return 0;
   3452 
   3453 	ret = __wait_seqno(ring, seqno, true, NULL);
   3454 	if (ret == 0)
   3455 		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, 0);
   3456 
   3457 	return ret;
   3458 }
   3459 
   3460 int
   3461 i915_gem_object_pin(struct drm_i915_gem_object *obj,
   3462 		    uint32_t alignment,
   3463 		    bool map_and_fenceable,
   3464 		    bool nonblocking)
   3465 {
   3466 	int ret;
   3467 
   3468 	if (WARN_ON(obj->pin_count == DRM_I915_GEM_OBJECT_MAX_PIN_COUNT))
   3469 		return -EBUSY;
   3470 
   3471 	if (obj->gtt_space != NULL) {
   3472 		if ((alignment && obj->gtt_offset & (alignment - 1)) ||
   3473 		    (map_and_fenceable && !obj->map_and_fenceable)) {
   3474 			WARN(obj->pin_count,
   3475 			     "bo is already pinned with incorrect alignment:"
   3476 			     " offset=%x, req.alignment=%x, req.map_and_fenceable=%d,"
   3477 			     " obj->map_and_fenceable=%d\n",
   3478 			     obj->gtt_offset, alignment,
   3479 			     map_and_fenceable,
   3480 			     obj->map_and_fenceable);
   3481 			ret = i915_gem_object_unbind(obj);
   3482 			if (ret)
   3483 				return ret;
   3484 		}
   3485 	}
   3486 
   3487 	if (obj->gtt_space == NULL) {
   3488 		struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   3489 
   3490 		ret = i915_gem_object_bind_to_gtt(obj, alignment,
   3491 						  map_and_fenceable,
   3492 						  nonblocking);
   3493 		if (ret)
   3494 			return ret;
   3495 
   3496 		if (!dev_priv->mm.aliasing_ppgtt)
   3497 			i915_gem_gtt_bind_object(obj, obj->cache_level);
   3498 	}
   3499 
   3500 	if (!obj->has_global_gtt_mapping && map_and_fenceable)
   3501 		i915_gem_gtt_bind_object(obj, obj->cache_level);
   3502 
   3503 	obj->pin_count++;
   3504 	obj->pin_mappable |= map_and_fenceable;
   3505 
   3506 	return 0;
   3507 }
   3508 
   3509 void
   3510 i915_gem_object_unpin(struct drm_i915_gem_object *obj)
   3511 {
   3512 	BUG_ON(obj->pin_count == 0);
   3513 	BUG_ON(obj->gtt_space == NULL);
   3514 
   3515 	if (--obj->pin_count == 0)
   3516 		obj->pin_mappable = false;
   3517 }
   3518 
   3519 int
   3520 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
   3521 		   struct drm_file *file)
   3522 {
   3523 	struct drm_i915_gem_pin *args = data;
   3524 	struct drm_i915_gem_object *obj;
   3525 	int ret;
   3526 
   3527 	ret = i915_mutex_lock_interruptible(dev);
   3528 	if (ret)
   3529 		return ret;
   3530 
   3531 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   3532 	if (&obj->base == NULL) {
   3533 		ret = -ENOENT;
   3534 		goto unlock;
   3535 	}
   3536 
   3537 	if (obj->madv != I915_MADV_WILLNEED) {
   3538 		DRM_ERROR("Attempting to pin a purgeable buffer\n");
   3539 		ret = -EINVAL;
   3540 		goto out;
   3541 	}
   3542 
   3543 	if (obj->pin_filp != NULL && obj->pin_filp != file) {
   3544 		DRM_ERROR("Already pinned in i915_gem_pin_ioctl(): %d\n",
   3545 			  args->handle);
   3546 		ret = -EINVAL;
   3547 		goto out;
   3548 	}
   3549 
   3550 	if (obj->user_pin_count == 0) {
   3551 		ret = i915_gem_object_pin(obj, args->alignment, true, false);
   3552 		if (ret)
   3553 			goto out;
   3554 	}
   3555 
   3556 	obj->user_pin_count++;
   3557 	obj->pin_filp = file;
   3558 
   3559 	/* XXX - flush the CPU caches for pinned objects
   3560 	 * as the X server doesn't manage domains yet
   3561 	 */
   3562 	i915_gem_object_flush_cpu_write_domain(obj);
   3563 	args->offset = obj->gtt_offset;
   3564 out:
   3565 	drm_gem_object_unreference(&obj->base);
   3566 unlock:
   3567 	mutex_unlock(&dev->struct_mutex);
   3568 	return ret;
   3569 }
   3570 
   3571 int
   3572 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
   3573 		     struct drm_file *file)
   3574 {
   3575 	struct drm_i915_gem_pin *args = data;
   3576 	struct drm_i915_gem_object *obj;
   3577 	int ret;
   3578 
   3579 	ret = i915_mutex_lock_interruptible(dev);
   3580 	if (ret)
   3581 		return ret;
   3582 
   3583 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   3584 	if (&obj->base == NULL) {
   3585 		ret = -ENOENT;
   3586 		goto unlock;
   3587 	}
   3588 
   3589 	if (obj->pin_filp != file) {
   3590 		DRM_ERROR("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
   3591 			  args->handle);
   3592 		ret = -EINVAL;
   3593 		goto out;
   3594 	}
   3595 	obj->user_pin_count--;
   3596 	if (obj->user_pin_count == 0) {
   3597 		obj->pin_filp = NULL;
   3598 		i915_gem_object_unpin(obj);
   3599 	}
   3600 
   3601 out:
   3602 	drm_gem_object_unreference(&obj->base);
   3603 unlock:
   3604 	mutex_unlock(&dev->struct_mutex);
   3605 	return ret;
   3606 }
   3607 
   3608 int
   3609 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
   3610 		    struct drm_file *file)
   3611 {
   3612 	struct drm_i915_gem_busy *args = data;
   3613 	struct drm_i915_gem_object *obj;
   3614 	int ret;
   3615 
   3616 	ret = i915_mutex_lock_interruptible(dev);
   3617 	if (ret)
   3618 		return ret;
   3619 
   3620 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   3621 	if (&obj->base == NULL) {
   3622 		ret = -ENOENT;
   3623 		goto unlock;
   3624 	}
   3625 
   3626 	/* Count all active objects as busy, even if they are currently not used
   3627 	 * by the gpu. Users of this interface expect objects to eventually
   3628 	 * become non-busy without any further actions, therefore emit any
   3629 	 * necessary flushes here.
   3630 	 */
   3631 	ret = i915_gem_object_flush_active(obj);
   3632 
   3633 	args->busy = obj->active;
   3634 	if (obj->ring) {
   3635 		BUILD_BUG_ON(I915_NUM_RINGS > 16);
   3636 		args->busy |= intel_ring_flag(obj->ring) << 16;
   3637 	}
   3638 
   3639 	drm_gem_object_unreference(&obj->base);
   3640 unlock:
   3641 	mutex_unlock(&dev->struct_mutex);
   3642 	return ret;
   3643 }
   3644 
   3645 int
   3646 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
   3647 			struct drm_file *file_priv)
   3648 {
   3649 	return i915_gem_ring_throttle(dev, file_priv);
   3650 }
   3651 
   3652 int
   3653 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
   3654 		       struct drm_file *file_priv)
   3655 {
   3656 	struct drm_i915_gem_madvise *args = data;
   3657 	struct drm_i915_gem_object *obj;
   3658 	int ret;
   3659 
   3660 	switch (args->madv) {
   3661 	case I915_MADV_DONTNEED:
   3662 	case I915_MADV_WILLNEED:
   3663 	    break;
   3664 	default:
   3665 	    return -EINVAL;
   3666 	}
   3667 
   3668 	ret = i915_mutex_lock_interruptible(dev);
   3669 	if (ret)
   3670 		return ret;
   3671 
   3672 	obj = to_intel_bo(drm_gem_object_lookup(dev, file_priv, args->handle));
   3673 	if (&obj->base == NULL) {
   3674 		ret = -ENOENT;
   3675 		goto unlock;
   3676 	}
   3677 
   3678 	if (obj->pin_count) {
   3679 		ret = -EINVAL;
   3680 		goto out;
   3681 	}
   3682 
   3683 	if (obj->madv != __I915_MADV_PURGED)
   3684 		obj->madv = args->madv;
   3685 
   3686 	/* if the object is no longer attached, discard its backing storage */
   3687 	if (i915_gem_object_is_purgeable(obj) && obj->pages == NULL)
   3688 		i915_gem_object_truncate(obj);
   3689 
   3690 	args->retained = obj->madv != __I915_MADV_PURGED;
   3691 
   3692 out:
   3693 	drm_gem_object_unreference(&obj->base);
   3694 unlock:
   3695 	mutex_unlock(&dev->struct_mutex);
   3696 	return ret;
   3697 }
   3698 
   3699 void i915_gem_object_init(struct drm_i915_gem_object *obj,
   3700 			  const struct drm_i915_gem_object_ops *ops)
   3701 {
   3702 	INIT_LIST_HEAD(&obj->mm_list);
   3703 	INIT_LIST_HEAD(&obj->gtt_list);
   3704 	INIT_LIST_HEAD(&obj->ring_list);
   3705 	INIT_LIST_HEAD(&obj->exec_list);
   3706 
   3707 	obj->ops = ops;
   3708 
   3709 	obj->fence_reg = I915_FENCE_REG_NONE;
   3710 	obj->madv = I915_MADV_WILLNEED;
   3711 	/* Avoid an unnecessary call to unbind on the first bind. */
   3712 	obj->map_and_fenceable = true;
   3713 
   3714 	i915_gem_info_add_obj(obj->base.dev->dev_private, obj->base.size);
   3715 }
   3716 
   3717 static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
   3718 	.get_pages = i915_gem_object_get_pages_gtt,
   3719 	.put_pages = i915_gem_object_put_pages_gtt,
   3720 };
   3721 
   3722 struct drm_i915_gem_object *i915_gem_alloc_object(struct drm_device *dev,
   3723 						  size_t size)
   3724 {
   3725 	struct drm_i915_gem_object *obj;
   3726 	struct address_space *mapping;
   3727 	u32 mask;
   3728 
   3729 	obj = kzalloc(sizeof(*obj), GFP_KERNEL);
   3730 	if (obj == NULL)
   3731 		return NULL;
   3732 
   3733 	if (drm_gem_object_init(dev, &obj->base, size) != 0) {
   3734 		kfree(obj);
   3735 		return NULL;
   3736 	}
   3737 
   3738 	mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
   3739 	if (IS_CRESTLINE(dev) || IS_BROADWATER(dev)) {
   3740 		/* 965gm cannot relocate objects above 4GiB. */
   3741 		mask &= ~__GFP_HIGHMEM;
   3742 		mask |= __GFP_DMA32;
   3743 	}
   3744 
   3745 	mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
   3746 	mapping_set_gfp_mask(mapping, mask);
   3747 
   3748 	i915_gem_object_init(obj, &i915_gem_object_ops);
   3749 
   3750 	obj->base.write_domain = I915_GEM_DOMAIN_CPU;
   3751 	obj->base.read_domains = I915_GEM_DOMAIN_CPU;
   3752 
   3753 	if (HAS_LLC(dev)) {
   3754 		/* On some devices, we can have the GPU use the LLC (the CPU
   3755 		 * cache) for about a 10% performance improvement
   3756 		 * compared to uncached.  Graphics requests other than
   3757 		 * display scanout are coherent with the CPU in
   3758 		 * accessing this cache.  This means in this mode we
   3759 		 * don't need to clflush on the CPU side, and on the
   3760 		 * GPU side we only need to flush internal caches to
   3761 		 * get data visible to the CPU.
   3762 		 *
   3763 		 * However, we maintain the display planes as UC, and so
   3764 		 * need to rebind when first used as such.
   3765 		 */
   3766 		obj->cache_level = I915_CACHE_LLC;
   3767 	} else
   3768 		obj->cache_level = I915_CACHE_NONE;
   3769 
   3770 	return obj;
   3771 }
   3772 
   3773 int i915_gem_init_object(struct drm_gem_object *obj)
   3774 {
   3775 	BUG();
   3776 
   3777 	return 0;
   3778 }
   3779 
   3780 void i915_gem_free_object(struct drm_gem_object *gem_obj)
   3781 {
   3782 	struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
   3783 	struct drm_device *dev = obj->base.dev;
   3784 	drm_i915_private_t *dev_priv = dev->dev_private;
   3785 
   3786 	trace_i915_gem_object_destroy(obj);
   3787 
   3788 	if (obj->phys_obj)
   3789 		i915_gem_detach_phys_object(dev, obj);
   3790 
   3791 	obj->pin_count = 0;
   3792 	if (WARN_ON(i915_gem_object_unbind(obj) == -ERESTARTSYS)) {
   3793 		bool was_interruptible;
   3794 
   3795 		was_interruptible = dev_priv->mm.interruptible;
   3796 		dev_priv->mm.interruptible = false;
   3797 
   3798 		WARN_ON(i915_gem_object_unbind(obj));
   3799 
   3800 		dev_priv->mm.interruptible = was_interruptible;
   3801 	}
   3802 
   3803 	obj->pages_pin_count = 0;
   3804 	i915_gem_object_put_pages(obj);
   3805 	i915_gem_object_free_mmap_offset(obj);
   3806 
   3807 	BUG_ON(obj->pages);
   3808 
   3809 	if (obj->base.import_attach)
   3810 		drm_prime_gem_destroy(&obj->base, NULL);
   3811 
   3812 	drm_gem_object_release(&obj->base);
   3813 	i915_gem_info_remove_obj(dev_priv, obj->base.size);
   3814 
   3815 	kfree(obj->bit_17);
   3816 	kfree(obj);
   3817 }
   3818 
   3819 int
   3820 i915_gem_idle(struct drm_device *dev)
   3821 {
   3822 	drm_i915_private_t *dev_priv = dev->dev_private;
   3823 	int ret;
   3824 
   3825 	mutex_lock(&dev->struct_mutex);
   3826 
   3827 	if (dev_priv->mm.suspended) {
   3828 		mutex_unlock(&dev->struct_mutex);
   3829 		return 0;
   3830 	}
   3831 
   3832 	ret = i915_gpu_idle(dev);
   3833 	if (ret) {
   3834 		mutex_unlock(&dev->struct_mutex);
   3835 		return ret;
   3836 	}
   3837 	i915_gem_retire_requests(dev);
   3838 
   3839 	/* Under UMS, be paranoid and evict. */
   3840 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
   3841 		i915_gem_evict_everything(dev);
   3842 
   3843 	i915_gem_reset_fences(dev);
   3844 
   3845 	/* Hack!  Don't let anybody do execbuf while we don't control the chip.
   3846 	 * We need to replace this with a semaphore, or something.
   3847 	 * And not confound mm.suspended!
   3848 	 */
   3849 	dev_priv->mm.suspended = 1;
   3850 	del_timer_sync(&dev_priv->hangcheck_timer);
   3851 
   3852 	i915_kernel_lost_context(dev);
   3853 	i915_gem_cleanup_ringbuffer(dev);
   3854 
   3855 	mutex_unlock(&dev->struct_mutex);
   3856 
   3857 	/* Cancel the retire work handler, which should be idle now. */
   3858 	cancel_delayed_work_sync(&dev_priv->mm.retire_work);
   3859 
   3860 	return 0;
   3861 }
   3862 
   3863 void i915_gem_l3_remap(struct drm_device *dev)
   3864 {
   3865 	drm_i915_private_t *dev_priv = dev->dev_private;
   3866 	u32 misccpctl;
   3867 	int i;
   3868 
   3869 	if (!IS_IVYBRIDGE(dev))
   3870 		return;
   3871 
   3872 	if (!dev_priv->l3_parity.remap_info)
   3873 		return;
   3874 
   3875 	misccpctl = I915_READ(GEN7_MISCCPCTL);
   3876 	I915_WRITE(GEN7_MISCCPCTL, misccpctl & ~GEN7_DOP_CLOCK_GATE_ENABLE);
   3877 	POSTING_READ(GEN7_MISCCPCTL);
   3878 
   3879 	for (i = 0; i < GEN7_L3LOG_SIZE; i += 4) {
   3880 		u32 remap = I915_READ(GEN7_L3LOG_BASE + i);
   3881 		if (remap && remap != dev_priv->l3_parity.remap_info[i/4])
   3882 			DRM_DEBUG("0x%x was already programmed to %x\n",
   3883 				  GEN7_L3LOG_BASE + i, remap);
   3884 		if (remap && !dev_priv->l3_parity.remap_info[i/4])
   3885 			DRM_DEBUG_DRIVER("Clearing remapped register\n");
   3886 		I915_WRITE(GEN7_L3LOG_BASE + i, dev_priv->l3_parity.remap_info[i/4]);
   3887 	}
   3888 
   3889 	/* Make sure all the writes land before disabling dop clock gating */
   3890 	POSTING_READ(GEN7_L3LOG_BASE);
   3891 
   3892 	I915_WRITE(GEN7_MISCCPCTL, misccpctl);
   3893 }
   3894 
   3895 void i915_gem_init_swizzling(struct drm_device *dev)
   3896 {
   3897 	drm_i915_private_t *dev_priv = dev->dev_private;
   3898 
   3899 	if (INTEL_INFO(dev)->gen < 5 ||
   3900 	    dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
   3901 		return;
   3902 
   3903 	I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
   3904 				 DISP_TILE_SURFACE_SWIZZLING);
   3905 
   3906 	if (IS_GEN5(dev))
   3907 		return;
   3908 
   3909 	I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
   3910 	if (IS_GEN6(dev))
   3911 		I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
   3912 	else
   3913 		I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
   3914 }
   3915 
   3916 static bool
   3917 intel_enable_blt(struct drm_device *dev)
   3918 {
   3919 	if (!HAS_BLT(dev))
   3920 		return false;
   3921 
   3922 	/* The blitter was dysfunctional on early prototypes */
   3923 	if (IS_GEN6(dev) && dev->pdev->revision < 8) {
   3924 		DRM_INFO("BLT not supported on this pre-production hardware;"
   3925 			 " graphics performance will be degraded.\n");
   3926 		return false;
   3927 	}
   3928 
   3929 	return true;
   3930 }
   3931 
   3932 int
   3933 i915_gem_init_hw(struct drm_device *dev)
   3934 {
   3935 	drm_i915_private_t *dev_priv = dev->dev_private;
   3936 	int ret;
   3937 
   3938 	if (INTEL_INFO(dev)->gen < 6 && !intel_enable_gtt())
   3939 		return -EIO;
   3940 
   3941 	if (IS_HASWELL(dev) && (I915_READ(0x120010) == 1))
   3942 		I915_WRITE(0x9008, I915_READ(0x9008) | 0xf0000);
   3943 
   3944 	i915_gem_l3_remap(dev);
   3945 
   3946 	i915_gem_init_swizzling(dev);
   3947 
   3948 	ret = intel_init_render_ring_buffer(dev);
   3949 	if (ret)
   3950 		return ret;
   3951 
   3952 	if (HAS_BSD(dev)) {
   3953 		ret = intel_init_bsd_ring_buffer(dev);
   3954 		if (ret)
   3955 			goto cleanup_render_ring;
   3956 	}
   3957 
   3958 	if (intel_enable_blt(dev)) {
   3959 		ret = intel_init_blt_ring_buffer(dev);
   3960 		if (ret)
   3961 			goto cleanup_bsd_ring;
   3962 	}
   3963 
   3964 	dev_priv->next_seqno = 1;
   3965 
   3966 	/*
   3967 	 * XXX: There was some w/a described somewhere suggesting loading
   3968 	 * contexts before PPGTT.
   3969 	 */
   3970 	i915_gem_context_init(dev);
   3971 	i915_gem_init_ppgtt(dev);
   3972 
   3973 	return 0;
   3974 
   3975 cleanup_bsd_ring:
   3976 	intel_cleanup_ring_buffer(&dev_priv->ring[VCS]);
   3977 cleanup_render_ring:
   3978 	intel_cleanup_ring_buffer(&dev_priv->ring[RCS]);
   3979 	return ret;
   3980 }
   3981 
   3982 static bool
   3983 intel_enable_ppgtt(struct drm_device *dev)
   3984 {
   3985 	if (i915_enable_ppgtt >= 0)
   3986 		return i915_enable_ppgtt;
   3987 
   3988 #ifdef CONFIG_INTEL_IOMMU
   3989 	/* Disable ppgtt on SNB if VT-d is on. */
   3990 	if (INTEL_INFO(dev)->gen == 6 && intel_iommu_gfx_mapped)
   3991 		return false;
   3992 #endif
   3993 
   3994 	return true;
   3995 }
   3996 
   3997 int i915_gem_init(struct drm_device *dev)
   3998 {
   3999 	struct drm_i915_private *dev_priv = dev->dev_private;
   4000 	unsigned long gtt_size, mappable_size;
   4001 	int ret;
   4002 
   4003 	gtt_size = dev_priv->mm.gtt->gtt_total_entries << PAGE_SHIFT;
   4004 	mappable_size = dev_priv->mm.gtt->gtt_mappable_entries << PAGE_SHIFT;
   4005 
   4006 	mutex_lock(&dev->struct_mutex);
   4007 	if (intel_enable_ppgtt(dev) && HAS_ALIASING_PPGTT(dev)) {
   4008 		/* PPGTT pdes are stolen from global gtt ptes, so shrink the
   4009 		 * aperture accordingly when using aliasing ppgtt. */
   4010 		gtt_size -= I915_PPGTT_PD_ENTRIES*PAGE_SIZE;
   4011 
   4012 		i915_gem_init_global_gtt(dev, 0, mappable_size, gtt_size);
   4013 
   4014 		ret = i915_gem_init_aliasing_ppgtt(dev);
   4015 		if (ret) {
   4016 			mutex_unlock(&dev->struct_mutex);
   4017 			return ret;
   4018 		}
   4019 	} else {
   4020 		/* Let GEM Manage all of the aperture.
   4021 		 *
   4022 		 * However, leave one page at the end still bound to the scratch
   4023 		 * page.  There are a number of places where the hardware
   4024 		 * apparently prefetches past the end of the object, and we've
   4025 		 * seen multiple hangs with the GPU head pointer stuck in a
   4026 		 * batchbuffer bound at the last page of the aperture.  One page
   4027 		 * should be enough to keep any prefetching inside of the
   4028 		 * aperture.
   4029 		 */
   4030 		i915_gem_init_global_gtt(dev, 0, mappable_size,
   4031 					 gtt_size);
   4032 	}
   4033 
   4034 	ret = i915_gem_init_hw(dev);
   4035 	mutex_unlock(&dev->struct_mutex);
   4036 	if (ret) {
   4037 		i915_gem_cleanup_aliasing_ppgtt(dev);
   4038 		return ret;
   4039 	}
   4040 
   4041 	/* Allow hardware batchbuffers unless told otherwise, but not for KMS. */
   4042 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
   4043 		dev_priv->dri1.allow_batchbuffer = 1;
   4044 	return 0;
   4045 }
   4046 
   4047 void
   4048 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
   4049 {
   4050 	drm_i915_private_t *dev_priv = dev->dev_private;
   4051 	struct intel_ring_buffer *ring;
   4052 	int i;
   4053 
   4054 	for_each_ring(ring, dev_priv, i)
   4055 		intel_cleanup_ring_buffer(ring);
   4056 }
   4057 
   4058 int
   4059 i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
   4060 		       struct drm_file *file_priv)
   4061 {
   4062 	drm_i915_private_t *dev_priv = dev->dev_private;
   4063 	int ret;
   4064 
   4065 	if (drm_core_check_feature(dev, DRIVER_MODESET))
   4066 		return 0;
   4067 
   4068 	if (atomic_read(&dev_priv->mm.wedged)) {
   4069 		DRM_ERROR("Reenabling wedged hardware, good luck\n");
   4070 		atomic_set(&dev_priv->mm.wedged, 0);
   4071 	}
   4072 
   4073 	mutex_lock(&dev->struct_mutex);
   4074 	dev_priv->mm.suspended = 0;
   4075 
   4076 	ret = i915_gem_init_hw(dev);
   4077 	if (ret != 0) {
   4078 		mutex_unlock(&dev->struct_mutex);
   4079 		return ret;
   4080 	}
   4081 
   4082 	BUG_ON(!list_empty(&dev_priv->mm.active_list));
   4083 	mutex_unlock(&dev->struct_mutex);
   4084 
   4085 	ret = drm_irq_install(dev);
   4086 	if (ret)
   4087 		goto cleanup_ringbuffer;
   4088 
   4089 	return 0;
   4090 
   4091 cleanup_ringbuffer:
   4092 	mutex_lock(&dev->struct_mutex);
   4093 	i915_gem_cleanup_ringbuffer(dev);
   4094 	dev_priv->mm.suspended = 1;
   4095 	mutex_unlock(&dev->struct_mutex);
   4096 
   4097 	return ret;
   4098 }
   4099 
   4100 int
   4101 i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
   4102 		       struct drm_file *file_priv)
   4103 {
   4104 	if (drm_core_check_feature(dev, DRIVER_MODESET))
   4105 		return 0;
   4106 
   4107 	drm_irq_uninstall(dev);
   4108 	return i915_gem_idle(dev);
   4109 }
   4110 
   4111 void
   4112 i915_gem_lastclose(struct drm_device *dev)
   4113 {
   4114 	int ret;
   4115 
   4116 	if (drm_core_check_feature(dev, DRIVER_MODESET))
   4117 		return;
   4118 
   4119 	ret = i915_gem_idle(dev);
   4120 	if (ret)
   4121 		DRM_ERROR("failed to idle hardware: %d\n", ret);
   4122 }
   4123 
   4124 static void
   4125 init_ring_lists(struct intel_ring_buffer *ring)
   4126 {
   4127 	INIT_LIST_HEAD(&ring->active_list);
   4128 	INIT_LIST_HEAD(&ring->request_list);
   4129 }
   4130 
   4131 void
   4132 i915_gem_load(struct drm_device *dev)
   4133 {
   4134 	int i;
   4135 	drm_i915_private_t *dev_priv = dev->dev_private;
   4136 
   4137 	INIT_LIST_HEAD(&dev_priv->mm.active_list);
   4138 	INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
   4139 	INIT_LIST_HEAD(&dev_priv->mm.unbound_list);
   4140 	INIT_LIST_HEAD(&dev_priv->mm.bound_list);
   4141 	INIT_LIST_HEAD(&dev_priv->mm.fence_list);
   4142 	for (i = 0; i < I915_NUM_RINGS; i++)
   4143 		init_ring_lists(&dev_priv->ring[i]);
   4144 	for (i = 0; i < I915_MAX_NUM_FENCES; i++)
   4145 		INIT_LIST_HEAD(&dev_priv->fence_regs[i].lru_list);
   4146 	INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
   4147 			  i915_gem_retire_work_handler);
   4148 	init_completion(&dev_priv->error_completion);
   4149 
   4150 	/* On GEN3 we really need to make sure the ARB C3 LP bit is set */
   4151 	if (IS_GEN3(dev)) {
   4152 		I915_WRITE(MI_ARB_STATE,
   4153 			   _MASKED_BIT_ENABLE(MI_ARB_C3_LP_WRITE_ENABLE));
   4154 	}
   4155 
   4156 	dev_priv->relative_constants_mode = I915_EXEC_CONSTANTS_REL_GENERAL;
   4157 
   4158 	/* Old X drivers will take 0-2 for front, back, depth buffers */
   4159 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
   4160 		dev_priv->fence_reg_start = 3;
   4161 
   4162 	if (INTEL_INFO(dev)->gen >= 4 || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
   4163 		dev_priv->num_fence_regs = 16;
   4164 	else
   4165 		dev_priv->num_fence_regs = 8;
   4166 
   4167 	/* Initialize fence registers to zero */
   4168 	i915_gem_reset_fences(dev);
   4169 
   4170 	i915_gem_detect_bit_6_swizzle(dev);
   4171 	init_waitqueue_head(&dev_priv->pending_flip_queue);
   4172 
   4173 	dev_priv->mm.interruptible = true;
   4174 
   4175 	dev_priv->mm.inactive_shrinker.shrink = i915_gem_inactive_shrink;
   4176 	dev_priv->mm.inactive_shrinker.seeks = DEFAULT_SEEKS;
   4177 	register_shrinker(&dev_priv->mm.inactive_shrinker);
   4178 }
   4179 
   4180 /*
   4181  * Create a physically contiguous memory object for this object
   4182  * e.g. for cursor + overlay regs
   4183  */
   4184 static int i915_gem_init_phys_object(struct drm_device *dev,
   4185 				     int id, int size, int align)
   4186 {
   4187 	drm_i915_private_t *dev_priv = dev->dev_private;
   4188 	struct drm_i915_gem_phys_object *phys_obj;
   4189 	int ret;
   4190 
   4191 	if (dev_priv->mm.phys_objs[id - 1] || !size)
   4192 		return 0;
   4193 
   4194 	phys_obj = kzalloc(sizeof(struct drm_i915_gem_phys_object), GFP_KERNEL);
   4195 	if (!phys_obj)
   4196 		return -ENOMEM;
   4197 
   4198 	phys_obj->id = id;
   4199 
   4200 	phys_obj->handle = drm_pci_alloc(dev, size, align);
   4201 	if (!phys_obj->handle) {
   4202 		ret = -ENOMEM;
   4203 		goto kfree_obj;
   4204 	}
   4205 #ifdef CONFIG_X86
   4206 	set_memory_wc((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
   4207 #endif
   4208 
   4209 	dev_priv->mm.phys_objs[id - 1] = phys_obj;
   4210 
   4211 	return 0;
   4212 kfree_obj:
   4213 	kfree(phys_obj);
   4214 	return ret;
   4215 }
   4216 
   4217 static void i915_gem_free_phys_object(struct drm_device *dev, int id)
   4218 {
   4219 	drm_i915_private_t *dev_priv = dev->dev_private;
   4220 	struct drm_i915_gem_phys_object *phys_obj;
   4221 
   4222 	if (!dev_priv->mm.phys_objs[id - 1])
   4223 		return;
   4224 
   4225 	phys_obj = dev_priv->mm.phys_objs[id - 1];
   4226 	if (phys_obj->cur_obj) {
   4227 		i915_gem_detach_phys_object(dev, phys_obj->cur_obj);
   4228 	}
   4229 
   4230 #ifdef CONFIG_X86
   4231 	set_memory_wb((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
   4232 #endif
   4233 	drm_pci_free(dev, phys_obj->handle);
   4234 	kfree(phys_obj);
   4235 	dev_priv->mm.phys_objs[id - 1] = NULL;
   4236 }
   4237 
   4238 void i915_gem_free_all_phys_object(struct drm_device *dev)
   4239 {
   4240 	int i;
   4241 
   4242 	for (i = I915_GEM_PHYS_CURSOR_0; i <= I915_MAX_PHYS_OBJECT; i++)
   4243 		i915_gem_free_phys_object(dev, i);
   4244 }
   4245 
   4246 void i915_gem_detach_phys_object(struct drm_device *dev,
   4247 				 struct drm_i915_gem_object *obj)
   4248 {
   4249 	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
   4250 	char *vaddr;
   4251 	int i;
   4252 	int page_count;
   4253 
   4254 	if (!obj->phys_obj)
   4255 		return;
   4256 	vaddr = obj->phys_obj->handle->vaddr;
   4257 
   4258 	page_count = obj->base.size / PAGE_SIZE;
   4259 	for (i = 0; i < page_count; i++) {
   4260 		struct page *page = shmem_read_mapping_page(mapping, i);
   4261 		if (!IS_ERR(page)) {
   4262 			char *dst = kmap_atomic(page);
   4263 			memcpy(dst, vaddr + i*PAGE_SIZE, PAGE_SIZE);
   4264 			kunmap_atomic(dst);
   4265 
   4266 			drm_clflush_pages(&page, 1);
   4267 
   4268 			set_page_dirty(page);
   4269 			mark_page_accessed(page);
   4270 			page_cache_release(page);
   4271 		}
   4272 	}
   4273 	i915_gem_chipset_flush(dev);
   4274 
   4275 	obj->phys_obj->cur_obj = NULL;
   4276 	obj->phys_obj = NULL;
   4277 }
   4278 
   4279 int
   4280 i915_gem_attach_phys_object(struct drm_device *dev,
   4281 			    struct drm_i915_gem_object *obj,
   4282 			    int id,
   4283 			    int align)
   4284 {
   4285 	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
   4286 	drm_i915_private_t *dev_priv = dev->dev_private;
   4287 	int ret = 0;
   4288 	int page_count;
   4289 	int i;
   4290 
   4291 	if (id > I915_MAX_PHYS_OBJECT)
   4292 		return -EINVAL;
   4293 
   4294 	if (obj->phys_obj) {
   4295 		if (obj->phys_obj->id == id)
   4296 			return 0;
   4297 		i915_gem_detach_phys_object(dev, obj);
   4298 	}
   4299 
   4300 	/* create a new object */
   4301 	if (!dev_priv->mm.phys_objs[id - 1]) {
   4302 		ret = i915_gem_init_phys_object(dev, id,
   4303 						obj->base.size, align);
   4304 		if (ret) {
   4305 			DRM_ERROR("failed to init phys object %d size: %zu\n",
   4306 				  id, obj->base.size);
   4307 			return ret;
   4308 		}
   4309 	}
   4310 
   4311 	/* bind to the object */
   4312 	obj->phys_obj = dev_priv->mm.phys_objs[id - 1];
   4313 	obj->phys_obj->cur_obj = obj;
   4314 
   4315 	page_count = obj->base.size / PAGE_SIZE;
   4316 
   4317 	for (i = 0; i < page_count; i++) {
   4318 		struct page *page;
   4319 		char *dst, *src;
   4320 
   4321 		page = shmem_read_mapping_page(mapping, i);
   4322 		if (IS_ERR(page))
   4323 			return PTR_ERR(page);
   4324 
   4325 		src = kmap_atomic(page);
   4326 		dst = obj->phys_obj->handle->vaddr + (i * PAGE_SIZE);
   4327 		memcpy(dst, src, PAGE_SIZE);
   4328 		kunmap_atomic(src);
   4329 
   4330 		mark_page_accessed(page);
   4331 		page_cache_release(page);
   4332 	}
   4333 
   4334 	return 0;
   4335 }
   4336 
   4337 static int
   4338 i915_gem_phys_pwrite(struct drm_device *dev,
   4339 		     struct drm_i915_gem_object *obj,
   4340 		     struct drm_i915_gem_pwrite *args,
   4341 		     struct drm_file *file_priv)
   4342 {
   4343 	void *vaddr = obj->phys_obj->handle->vaddr + args->offset;
   4344 	char __user *user_data = (char __user *) (uintptr_t) args->data_ptr;
   4345 
   4346 	if (__copy_from_user_inatomic_nocache(vaddr, user_data, args->size)) {
   4347 		unsigned long unwritten;
   4348 
   4349 		/* The physical object once assigned is fixed for the lifetime
   4350 		 * of the obj, so we can safely drop the lock and continue
   4351 		 * to access vaddr.
   4352 		 */
   4353 		mutex_unlock(&dev->struct_mutex);
   4354 		unwritten = copy_from_user(vaddr, user_data, args->size);
   4355 		mutex_lock(&dev->struct_mutex);
   4356 		if (unwritten)
   4357 			return -EFAULT;
   4358 	}
   4359 
   4360 	i915_gem_chipset_flush(dev);
   4361 	return 0;
   4362 }
   4363 
   4364 void i915_gem_release(struct drm_device *dev, struct drm_file *file)
   4365 {
   4366 	struct drm_i915_file_private *file_priv = file->driver_priv;
   4367 
   4368 	/* Clean up our request list when the client is going away, so that
   4369 	 * later retire_requests won't dereference our soon-to-be-gone
   4370 	 * file_priv.
   4371 	 */
   4372 	spin_lock(&file_priv->mm.lock);
   4373 	while (!list_empty(&file_priv->mm.request_list)) {
   4374 		struct drm_i915_gem_request *request;
   4375 
   4376 		request = list_first_entry(&file_priv->mm.request_list,
   4377 					   struct drm_i915_gem_request,
   4378 					   client_list);
   4379 		list_del(&request->client_list);
   4380 		request->file_priv = NULL;
   4381 	}
   4382 	spin_unlock(&file_priv->mm.lock);
   4383 }
   4384 
   4385 static bool mutex_is_locked_by(struct mutex *mutex, struct task_struct *task)
   4386 {
   4387 	if (!mutex_is_locked(mutex))
   4388 		return false;
   4389 
   4390 #if defined(CONFIG_SMP) || defined(CONFIG_DEBUG_MUTEXES)
   4391 	return mutex->owner == task;
   4392 #else
   4393 	/* Since UP may be pre-empted, we cannot assume that we own the lock */
   4394 	return false;
   4395 #endif
   4396 }
   4397 
   4398 static int
   4399 i915_gem_inactive_shrink(struct shrinker *shrinker, struct shrink_control *sc)
   4400 {
   4401 	struct drm_i915_private *dev_priv =
   4402 		container_of(shrinker,
   4403 			     struct drm_i915_private,
   4404 			     mm.inactive_shrinker);
   4405 	struct drm_device *dev = dev_priv->dev;
   4406 	struct drm_i915_gem_object *obj;
   4407 	int nr_to_scan = sc->nr_to_scan;
   4408 	bool unlock = true;
   4409 	int cnt;
   4410 
   4411 	if (!mutex_trylock(&dev->struct_mutex)) {
   4412 		if (!mutex_is_locked_by(&dev->struct_mutex, current))
   4413 			return 0;
   4414 
   4415 		if (dev_priv->mm.shrinker_no_lock_stealing)
   4416 			return 0;
   4417 
   4418 		unlock = false;
   4419 	}
   4420 
   4421 	if (nr_to_scan) {
   4422 		nr_to_scan -= i915_gem_purge(dev_priv, nr_to_scan);
   4423 		if (nr_to_scan > 0)
   4424 			nr_to_scan -= __i915_gem_shrink(dev_priv, nr_to_scan,
   4425 							false);
   4426 		if (nr_to_scan > 0)
   4427 			i915_gem_shrink_all(dev_priv);
   4428 	}
   4429 
   4430 	cnt = 0;
   4431 	list_for_each_entry(obj, &dev_priv->mm.unbound_list, gtt_list)
   4432 		if (obj->pages_pin_count == 0)
   4433 			cnt += obj->base.size >> PAGE_SHIFT;
   4434 	list_for_each_entry(obj, &dev_priv->mm.inactive_list, gtt_list)
   4435 		if (obj->pin_count == 0 && obj->pages_pin_count == 0)
   4436 			cnt += obj->base.size >> PAGE_SHIFT;
   4437 
   4438 	if (unlock)
   4439 		mutex_unlock(&dev->struct_mutex);
   4440 	return cnt;
   4441 }
   4442