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