Home | History | Annotate | Line # | Download | only in i915
i915_gem.c revision 1.1.1.1.2.20
      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 		    atop(offset));
    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 		    atop(offset));
    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 		unsigned long flags;
   1197 		spin_lock_irqsave(&dev_priv->irq_lock, flags);
   1198 		/*
   1199 		 * XXX This wait is always interruptible; we should
   1200 		 * heed the flag `interruptible'.
   1201 		 */
   1202 		DRM_SPIN_TIMED_WAIT_UNTIL(end, &ring->irq_queue,
   1203 		    &dev_priv->irq_lock,
   1204 		    timeout_jiffies,
   1205 		    EXIT_COND);
   1206 		spin_unlock_irqrestore(&dev_priv->irq_lock, flags);
   1207 #else
   1208 		if (interruptible)
   1209 			end = wait_event_interruptible_timeout(ring->irq_queue,
   1210 							       EXIT_COND,
   1211 							       timeout_jiffies);
   1212 		else
   1213 			end = wait_event_timeout(ring->irq_queue, EXIT_COND,
   1214 						 timeout_jiffies);
   1215 
   1216 #endif
   1217 		ret = i915_gem_check_wedge(dev_priv, interruptible);
   1218 		if (ret)
   1219 			end = ret;
   1220 	} while (end == 0 && wait_forever);
   1221 
   1222 	getrawmonotonic(&now);
   1223 
   1224 	ring->irq_put(ring);
   1225 	trace_i915_gem_request_wait_end(ring, seqno);
   1226 #undef EXIT_COND
   1227 
   1228 	if (timeout) {
   1229 		struct timespec sleep_time = timespec_sub(now, before);
   1230 		*timeout = timespec_sub(*timeout, sleep_time);
   1231 	}
   1232 
   1233 	switch (end) {
   1234 	case -EIO:
   1235 	case -EAGAIN: /* Wedged */
   1236 	case -ERESTARTSYS: /* Signal */
   1237 	case -EINTR:
   1238 		return (int)end;
   1239 	case 0: /* Timeout */
   1240 		if (timeout)
   1241 			set_normalized_timespec(timeout, 0, 0);
   1242 		return -ETIME;
   1243 	default: /* Completed */
   1244 		WARN_ON(end < 0); /* We're not aware of other errors */
   1245 		return 0;
   1246 	}
   1247 }
   1248 
   1249 /**
   1250  * Waits for a sequence number to be signaled, and cleans up the
   1251  * request and object lists appropriately for that event.
   1252  */
   1253 int
   1254 i915_wait_seqno(struct intel_ring_buffer *ring, uint32_t seqno)
   1255 {
   1256 	struct drm_device *dev = ring->dev;
   1257 	struct drm_i915_private *dev_priv = dev->dev_private;
   1258 	bool interruptible = dev_priv->mm.interruptible;
   1259 	int ret;
   1260 
   1261 	BUG_ON(!mutex_is_locked(&dev->struct_mutex));
   1262 	BUG_ON(seqno == 0);
   1263 
   1264 	ret = i915_gem_check_wedge(dev_priv, interruptible);
   1265 	if (ret)
   1266 		return ret;
   1267 
   1268 	ret = i915_gem_check_olr(ring, seqno);
   1269 	if (ret)
   1270 		return ret;
   1271 
   1272 	return __wait_seqno(ring, seqno, interruptible, NULL);
   1273 }
   1274 
   1275 /**
   1276  * Ensures that all rendering to the object has completed and the object is
   1277  * safe to unbind from the GTT or access from the CPU.
   1278  */
   1279 static __must_check int
   1280 i915_gem_object_wait_rendering(struct drm_i915_gem_object *obj,
   1281 			       bool readonly)
   1282 {
   1283 	struct intel_ring_buffer *ring = obj->ring;
   1284 	u32 seqno;
   1285 	int ret;
   1286 
   1287 	seqno = readonly ? obj->last_write_seqno : obj->last_read_seqno;
   1288 	if (seqno == 0)
   1289 		return 0;
   1290 
   1291 	ret = i915_wait_seqno(ring, seqno);
   1292 	if (ret)
   1293 		return ret;
   1294 
   1295 	i915_gem_retire_requests_ring(ring);
   1296 
   1297 	/* Manually manage the write flush as we may have not yet
   1298 	 * retired the buffer.
   1299 	 */
   1300 	if (obj->last_write_seqno &&
   1301 	    i915_seqno_passed(seqno, obj->last_write_seqno)) {
   1302 		obj->last_write_seqno = 0;
   1303 		obj->base.write_domain &= ~I915_GEM_GPU_DOMAINS;
   1304 	}
   1305 
   1306 	return 0;
   1307 }
   1308 
   1309 /* A nonblocking variant of the above wait. This is a highly dangerous routine
   1310  * as the object state may change during this call.
   1311  */
   1312 static __must_check int
   1313 i915_gem_object_wait_rendering__nonblocking(struct drm_i915_gem_object *obj,
   1314 					    bool readonly)
   1315 {
   1316 	struct drm_device *dev = obj->base.dev;
   1317 	struct drm_i915_private *dev_priv = dev->dev_private;
   1318 	struct intel_ring_buffer *ring = obj->ring;
   1319 	u32 seqno;
   1320 	int ret;
   1321 
   1322 	BUG_ON(!mutex_is_locked(&dev->struct_mutex));
   1323 	BUG_ON(!dev_priv->mm.interruptible);
   1324 
   1325 	seqno = readonly ? obj->last_write_seqno : obj->last_read_seqno;
   1326 	if (seqno == 0)
   1327 		return 0;
   1328 
   1329 	ret = i915_gem_check_wedge(dev_priv, true);
   1330 	if (ret)
   1331 		return ret;
   1332 
   1333 	ret = i915_gem_check_olr(ring, seqno);
   1334 	if (ret)
   1335 		return ret;
   1336 
   1337 	mutex_unlock(&dev->struct_mutex);
   1338 	ret = __wait_seqno(ring, seqno, true, NULL);
   1339 	mutex_lock(&dev->struct_mutex);
   1340 
   1341 	i915_gem_retire_requests_ring(ring);
   1342 
   1343 	/* Manually manage the write flush as we may have not yet
   1344 	 * retired the buffer.
   1345 	 */
   1346 	if (obj->last_write_seqno &&
   1347 	    i915_seqno_passed(seqno, obj->last_write_seqno)) {
   1348 		obj->last_write_seqno = 0;
   1349 		obj->base.write_domain &= ~I915_GEM_GPU_DOMAINS;
   1350 	}
   1351 
   1352 	return ret;
   1353 }
   1354 
   1355 /**
   1356  * Called when user space prepares to use an object with the CPU, either
   1357  * through the mmap ioctl's mapping or a GTT mapping.
   1358  */
   1359 int
   1360 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
   1361 			  struct drm_file *file)
   1362 {
   1363 	struct drm_i915_gem_set_domain *args = data;
   1364 	struct drm_i915_gem_object *obj;
   1365 	uint32_t read_domains = args->read_domains;
   1366 	uint32_t write_domain = args->write_domain;
   1367 	int ret;
   1368 
   1369 	/* Only handle setting domains to types used by the CPU. */
   1370 	if (write_domain & I915_GEM_GPU_DOMAINS)
   1371 		return -EINVAL;
   1372 
   1373 	if (read_domains & I915_GEM_GPU_DOMAINS)
   1374 		return -EINVAL;
   1375 
   1376 	/* Having something in the write domain implies it's in the read
   1377 	 * domain, and only that read domain.  Enforce that in the request.
   1378 	 */
   1379 	if (write_domain != 0 && read_domains != write_domain)
   1380 		return -EINVAL;
   1381 
   1382 	ret = i915_mutex_lock_interruptible(dev);
   1383 	if (ret)
   1384 		return ret;
   1385 
   1386 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   1387 	if (&obj->base == NULL) {
   1388 		ret = -ENOENT;
   1389 		goto unlock;
   1390 	}
   1391 
   1392 	/* Try to flush the object off the GPU without holding the lock.
   1393 	 * We will repeat the flush holding the lock in the normal manner
   1394 	 * to catch cases where we are gazumped.
   1395 	 */
   1396 	ret = i915_gem_object_wait_rendering__nonblocking(obj, !write_domain);
   1397 	if (ret)
   1398 		goto unref;
   1399 
   1400 	if (read_domains & I915_GEM_DOMAIN_GTT) {
   1401 		ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
   1402 
   1403 		/* Silently promote "you're not bound, there was nothing to do"
   1404 		 * to success, since the client was just asking us to
   1405 		 * make sure everything was done.
   1406 		 */
   1407 		if (ret == -EINVAL)
   1408 			ret = 0;
   1409 	} else {
   1410 		ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
   1411 	}
   1412 
   1413 unref:
   1414 	drm_gem_object_unreference(&obj->base);
   1415 unlock:
   1416 	mutex_unlock(&dev->struct_mutex);
   1417 	return ret;
   1418 }
   1419 
   1420 /**
   1421  * Called when user space has done writes to this buffer
   1422  */
   1423 int
   1424 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
   1425 			 struct drm_file *file)
   1426 {
   1427 	struct drm_i915_gem_sw_finish *args = data;
   1428 	struct drm_i915_gem_object *obj;
   1429 	int ret = 0;
   1430 
   1431 	ret = i915_mutex_lock_interruptible(dev);
   1432 	if (ret)
   1433 		return ret;
   1434 
   1435 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   1436 	if (&obj->base == NULL) {
   1437 		ret = -ENOENT;
   1438 		goto unlock;
   1439 	}
   1440 
   1441 	/* Pinned buffers may be scanout, so flush the cache */
   1442 	if (obj->pin_count)
   1443 		i915_gem_object_flush_cpu_write_domain(obj);
   1444 
   1445 	drm_gem_object_unreference(&obj->base);
   1446 unlock:
   1447 	mutex_unlock(&dev->struct_mutex);
   1448 	return ret;
   1449 }
   1450 
   1451 /**
   1452  * Maps the contents of an object, returning the address it is mapped
   1453  * into.
   1454  *
   1455  * While the mapping holds a reference on the contents of the object, it doesn't
   1456  * imply a ref on the object itself.
   1457  */
   1458 int
   1459 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
   1460 		    struct drm_file *file)
   1461 {
   1462 	struct drm_i915_gem_mmap *args = data;
   1463 	struct drm_gem_object *obj;
   1464 	unsigned long addr;
   1465 #ifdef __NetBSD__
   1466 	int ret;
   1467 #endif
   1468 
   1469 	obj = drm_gem_object_lookup(dev, file, args->handle);
   1470 	if (obj == NULL)
   1471 		return -ENOENT;
   1472 
   1473 #ifndef __NetBSD__    /* XXX drm prime */
   1474 	/* prime objects have no backing filp to GEM mmap
   1475 	 * pages from.
   1476 	 */
   1477 	if (!obj->filp) {
   1478 		drm_gem_object_unreference_unlocked(obj);
   1479 		return -EINVAL;
   1480 	}
   1481 #endif
   1482 
   1483 #ifdef __NetBSD__
   1484 	addr = (*curproc->p_emul->e_vm_default_addr)(curproc,
   1485 	    (vaddr_t)curproc->p_vmspace->vm_daddr, args->size);
   1486 	/* XXX errno NetBSD->Linux */
   1487 	ret = -uvm_map(&curproc->p_vmspace->vm_map, &addr, args->size,
   1488 	    obj->gemo_shm_uao, args->offset, 0,
   1489 	    UVM_MAPFLAG((VM_PROT_READ | VM_PROT_WRITE),
   1490 		(VM_PROT_READ | VM_PROT_WRITE), UVM_INH_COPY, UVM_ADV_NORMAL,
   1491 		UVM_FLAG_COPYONW));
   1492 	if (ret)
   1493 		return ret;
   1494 #else
   1495 	addr = vm_mmap(obj->filp, 0, args->size,
   1496 		       PROT_READ | PROT_WRITE, MAP_SHARED,
   1497 		       args->offset);
   1498 	drm_gem_object_unreference_unlocked(obj);
   1499 	if (IS_ERR((void *)addr))
   1500 		return addr;
   1501 #endif
   1502 
   1503 	args->addr_ptr = (uint64_t) addr;
   1504 
   1505 	return 0;
   1506 }
   1507 
   1508 #ifdef __NetBSD__		/* XXX gem gtt fault */
   1509 static int	i915_udv_fault(struct uvm_faultinfo *, vaddr_t,
   1510 		    struct vm_page **, int, int, vm_prot_t, int, paddr_t);
   1511 
   1512 int
   1513 i915_gem_fault(struct uvm_faultinfo *ufi, vaddr_t vaddr, struct vm_page **pps,
   1514     int npages, int centeridx, vm_prot_t access_type, int flags)
   1515 {
   1516 	struct uvm_object *uobj = ufi->entry->object.uvm_obj;
   1517 	struct drm_gem_object *gem_obj =
   1518 	    container_of(uobj, struct drm_gem_object, gemo_uvmobj);
   1519 	struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
   1520 	struct drm_device *dev = obj->base.dev;
   1521 	struct drm_i915_private *dev_priv = dev->dev_private;
   1522 	pgoff_t page_offset;
   1523 	int ret = 0;
   1524 	bool write = ISSET(access_type, VM_PROT_WRITE)? 1 : 0;
   1525 
   1526 	page_offset = (ufi->entry->offset + (vaddr - ufi->entry->start)) >>
   1527 	    PAGE_SHIFT;
   1528 
   1529 	ret = i915_mutex_lock_interruptible(dev);
   1530 	if (ret)
   1531 		goto out;
   1532 
   1533 	trace_i915_gem_object_fault(obj, page_offset, true, write);
   1534 
   1535 	/* Now bind it into the GTT if needed */
   1536 	ret = i915_gem_object_pin(obj, 0, true, false);
   1537 	if (ret)
   1538 		goto unlock;
   1539 
   1540 	ret = i915_gem_object_set_to_gtt_domain(obj, write);
   1541 	if (ret)
   1542 		goto unpin;
   1543 
   1544 	ret = i915_gem_object_get_fence(obj);
   1545 	if (ret)
   1546 		goto unpin;
   1547 
   1548 	obj->fault_mappable = true;
   1549 
   1550 	/* Finally, remap it using the new GTT offset */
   1551 	/* XXX errno NetBSD->Linux */
   1552 	ret = -i915_udv_fault(ufi, vaddr, pps, npages, centeridx, access_type,
   1553 	    flags, (dev_priv->mm.gtt_base_addr + obj->gtt_offset));
   1554 unpin:
   1555 	i915_gem_object_unpin(obj);
   1556 unlock:
   1557 	mutex_unlock(&dev->struct_mutex);
   1558 out:
   1559 	return ret;
   1560 }
   1561 
   1562 /*
   1563  * XXX i915_udv_fault is copypasta of udv_fault from uvm_device.c.
   1564  *
   1565  * XXX pmap_enter_default instead of pmap_enter because of a problem
   1566  * with using weak aliases in kernel modules or something.
   1567  */
   1568 int	pmap_enter_default(pmap_t, vaddr_t, paddr_t, vm_prot_t, unsigned);
   1569 
   1570 static int
   1571 i915_udv_fault(struct uvm_faultinfo *ufi, vaddr_t vaddr, struct vm_page **pps,
   1572     int npages, int centeridx, vm_prot_t access_type, int flags,
   1573     paddr_t gtt_paddr)
   1574 {
   1575 	struct vm_map_entry *entry = ufi->entry;
   1576 	struct uvm_object *uobj = entry->object.uvm_obj;
   1577 	vaddr_t curr_va;
   1578 	off_t curr_offset;
   1579 	paddr_t paddr;
   1580 	u_int mmapflags;
   1581 	int lcv, retval;
   1582 	vm_prot_t mapprot;
   1583 	UVMHIST_FUNC("i915_udv_fault"); UVMHIST_CALLED(maphist);
   1584 	UVMHIST_LOG(maphist,"  flags=%d", flags,0,0,0);
   1585 
   1586 	/*
   1587 	 * we do not allow device mappings to be mapped copy-on-write
   1588 	 * so we kill any attempt to do so here.
   1589 	 */
   1590 
   1591 	if (UVM_ET_ISCOPYONWRITE(entry)) {
   1592 		UVMHIST_LOG(maphist, "<- failed -- COW entry (etype=0x%x)",
   1593 		entry->etype, 0,0,0);
   1594 		uvmfault_unlockall(ufi, ufi->entry->aref.ar_amap, uobj);
   1595 		return(EIO);
   1596 	}
   1597 
   1598 	/*
   1599 	 * now we must determine the offset in udv to use and the VA to
   1600 	 * use for pmap_enter.  note that we always use orig_map's pmap
   1601 	 * for pmap_enter (even if we have a submap).   since virtual
   1602 	 * addresses in a submap must match the main map, this is ok.
   1603 	 */
   1604 
   1605 	/* udv offset = (offset from start of entry) + entry's offset */
   1606 	curr_offset = entry->offset + (vaddr - entry->start);
   1607 	/* pmap va = vaddr (virtual address of pps[0]) */
   1608 	curr_va = vaddr;
   1609 
   1610 	/*
   1611 	 * loop over the page range entering in as needed
   1612 	 */
   1613 
   1614 	retval = 0;
   1615 	for (lcv = 0 ; lcv < npages ; lcv++, curr_offset += PAGE_SIZE,
   1616 	    curr_va += PAGE_SIZE) {
   1617 		if ((flags & PGO_ALLPAGES) == 0 && lcv != centeridx)
   1618 			continue;
   1619 
   1620 		if (pps[lcv] == PGO_DONTCARE)
   1621 			continue;
   1622 
   1623 		paddr = (gtt_paddr + curr_offset);
   1624 		mmapflags = 0;
   1625 		mapprot = ufi->entry->protection;
   1626 		UVMHIST_LOG(maphist,
   1627 		    "  MAPPING: device: pm=0x%x, va=0x%x, pa=0x%lx, at=%d",
   1628 		    ufi->orig_map->pmap, curr_va, paddr, mapprot);
   1629 		if (pmap_enter_default(ufi->orig_map->pmap, curr_va, paddr, mapprot,
   1630 		    PMAP_CANFAIL | mapprot | mmapflags) != 0) {
   1631 			/*
   1632 			 * pmap_enter() didn't have the resource to
   1633 			 * enter this mapping.  Unlock everything,
   1634 			 * wait for the pagedaemon to free up some
   1635 			 * pages, and then tell uvm_fault() to start
   1636 			 * the fault again.
   1637 			 *
   1638 			 * XXX Needs some rethinking for the PGO_ALLPAGES
   1639 			 * XXX case.
   1640 			 */
   1641 			pmap_update(ufi->orig_map->pmap);	/* sync what we have so far */
   1642 			uvmfault_unlockall(ufi, ufi->entry->aref.ar_amap,
   1643 			    uobj);
   1644 			uvm_wait("i915flt");
   1645 			return (ERESTART);
   1646 		}
   1647 	}
   1648 
   1649 	pmap_update(ufi->orig_map->pmap);
   1650 	uvmfault_unlockall(ufi, ufi->entry->aref.ar_amap, uobj);
   1651 	return (retval);
   1652 }
   1653 #else
   1654 /**
   1655  * i915_gem_fault - fault a page into the GTT
   1656  * vma: VMA in question
   1657  * vmf: fault info
   1658  *
   1659  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
   1660  * from userspace.  The fault handler takes care of binding the object to
   1661  * the GTT (if needed), allocating and programming a fence register (again,
   1662  * only if needed based on whether the old reg is still valid or the object
   1663  * is tiled) and inserting a new PTE into the faulting process.
   1664  *
   1665  * Note that the faulting process may involve evicting existing objects
   1666  * from the GTT and/or fence registers to make room.  So performance may
   1667  * suffer if the GTT working set is large or there are few fence registers
   1668  * left.
   1669  */
   1670 int i915_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
   1671 {
   1672 	struct drm_i915_gem_object *obj = to_intel_bo(vma->vm_private_data);
   1673 	struct drm_device *dev = obj->base.dev;
   1674 	drm_i915_private_t *dev_priv = dev->dev_private;
   1675 	pgoff_t page_offset;
   1676 	unsigned long pfn;
   1677 	int ret = 0;
   1678 	bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
   1679 
   1680 	/* We don't use vmf->pgoff since that has the fake offset */
   1681 	page_offset = ((unsigned long)vmf->virtual_address - vma->vm_start) >>
   1682 		PAGE_SHIFT;
   1683 
   1684 	ret = i915_mutex_lock_interruptible(dev);
   1685 	if (ret)
   1686 		goto out;
   1687 
   1688 	trace_i915_gem_object_fault(obj, page_offset, true, write);
   1689 
   1690 	/* Now bind it into the GTT if needed */
   1691 	ret = i915_gem_object_pin(obj, 0, true, false);
   1692 	if (ret)
   1693 		goto unlock;
   1694 
   1695 	ret = i915_gem_object_set_to_gtt_domain(obj, write);
   1696 	if (ret)
   1697 		goto unpin;
   1698 
   1699 	ret = i915_gem_object_get_fence(obj);
   1700 	if (ret)
   1701 		goto unpin;
   1702 
   1703 	obj->fault_mappable = true;
   1704 
   1705 	pfn = ((dev_priv->mm.gtt_base_addr + obj->gtt_offset) >> PAGE_SHIFT) +
   1706 		page_offset;
   1707 
   1708 	/* Finally, remap it using the new GTT offset */
   1709 	ret = vm_insert_pfn(vma, (unsigned long)vmf->virtual_address, pfn);
   1710 unpin:
   1711 	i915_gem_object_unpin(obj);
   1712 unlock:
   1713 	mutex_unlock(&dev->struct_mutex);
   1714 out:
   1715 	switch (ret) {
   1716 	case -EIO:
   1717 		/* If this -EIO is due to a gpu hang, give the reset code a
   1718 		 * chance to clean up the mess. Otherwise return the proper
   1719 		 * SIGBUS. */
   1720 		if (!atomic_read(&dev_priv->mm.wedged))
   1721 			return VM_FAULT_SIGBUS;
   1722 	case -EAGAIN:
   1723 		/* Give the error handler a chance to run and move the
   1724 		 * objects off the GPU active list. Next time we service the
   1725 		 * fault, we should be able to transition the page into the
   1726 		 * GTT without touching the GPU (and so avoid further
   1727 		 * EIO/EGAIN). If the GPU is wedged, then there is no issue
   1728 		 * with coherency, just lost writes.
   1729 		 */
   1730 		set_need_resched();
   1731 	case 0:
   1732 	case -ERESTARTSYS:
   1733 	case -EINTR:
   1734 	case -EBUSY:
   1735 		/*
   1736 		 * EBUSY is ok: this just means that another thread
   1737 		 * already did the job.
   1738 		 */
   1739 		return VM_FAULT_NOPAGE;
   1740 	case -ENOMEM:
   1741 		return VM_FAULT_OOM;
   1742 	case -ENOSPC:
   1743 		return VM_FAULT_SIGBUS;
   1744 	default:
   1745 		WARN_ONCE(ret, "unhandled error in i915_gem_fault: %i\n", ret);
   1746 		return VM_FAULT_SIGBUS;
   1747 	}
   1748 }
   1749 #endif
   1750 
   1751 /**
   1752  * i915_gem_release_mmap - remove physical page mappings
   1753  * @obj: obj in question
   1754  *
   1755  * Preserve the reservation of the mmapping with the DRM core code, but
   1756  * relinquish ownership of the pages back to the system.
   1757  *
   1758  * It is vital that we remove the page mapping if we have mapped a tiled
   1759  * object through the GTT and then lose the fence register due to
   1760  * resource pressure. Similarly if the object has been moved out of the
   1761  * aperture, than pages mapped into userspace must be revoked. Removing the
   1762  * mapping will then trigger a page fault on the next user access, allowing
   1763  * fixup by i915_gem_fault().
   1764  */
   1765 void
   1766 i915_gem_release_mmap(struct drm_i915_gem_object *obj)
   1767 {
   1768 	if (!obj->fault_mappable)
   1769 		return;
   1770 
   1771 #ifdef __NetBSD__		/* XXX gem gtt fault */
   1772 	{
   1773 		struct vm_page *page;
   1774 
   1775 		KASSERT(obj->pages != NULL);
   1776 		/* Force a fresh fault for each page.  */
   1777 		TAILQ_FOREACH(page, &obj->igo_pageq, pageq.queue)
   1778 			pmap_page_protect(page, VM_PROT_NONE);
   1779 	}
   1780 #else
   1781 	if (obj->base.dev->dev_mapping)
   1782 		unmap_mapping_range(obj->base.dev->dev_mapping,
   1783 				    (loff_t)obj->base.map_list.hash.key<<PAGE_SHIFT,
   1784 				    obj->base.size, 1);
   1785 #endif
   1786 
   1787 	obj->fault_mappable = false;
   1788 }
   1789 
   1790 static uint32_t
   1791 i915_gem_get_gtt_size(struct drm_device *dev, uint32_t size, int tiling_mode)
   1792 {
   1793 	uint32_t gtt_size;
   1794 
   1795 	if (INTEL_INFO(dev)->gen >= 4 ||
   1796 	    tiling_mode == I915_TILING_NONE)
   1797 		return size;
   1798 
   1799 	/* Previous chips need a power-of-two fence region when tiling */
   1800 	if (INTEL_INFO(dev)->gen == 3)
   1801 		gtt_size = 1024*1024;
   1802 	else
   1803 		gtt_size = 512*1024;
   1804 
   1805 	while (gtt_size < size)
   1806 		gtt_size <<= 1;
   1807 
   1808 	return gtt_size;
   1809 }
   1810 
   1811 /**
   1812  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
   1813  * @obj: object to check
   1814  *
   1815  * Return the required GTT alignment for an object, taking into account
   1816  * potential fence register mapping.
   1817  */
   1818 static uint32_t
   1819 i915_gem_get_gtt_alignment(struct drm_device *dev,
   1820 			   uint32_t size,
   1821 			   int tiling_mode)
   1822 {
   1823 	/*
   1824 	 * Minimum alignment is 4k (GTT page size), but might be greater
   1825 	 * if a fence register is needed for the object.
   1826 	 */
   1827 	if (INTEL_INFO(dev)->gen >= 4 ||
   1828 	    tiling_mode == I915_TILING_NONE)
   1829 		return 4096;
   1830 
   1831 	/*
   1832 	 * Previous chips need to be aligned to the size of the smallest
   1833 	 * fence register that can contain the object.
   1834 	 */
   1835 	return i915_gem_get_gtt_size(dev, size, tiling_mode);
   1836 }
   1837 
   1838 /**
   1839  * i915_gem_get_unfenced_gtt_alignment - return required GTT alignment for an
   1840  *					 unfenced object
   1841  * @dev: the device
   1842  * @size: size of the object
   1843  * @tiling_mode: tiling mode of the object
   1844  *
   1845  * Return the required GTT alignment for an object, only taking into account
   1846  * unfenced tiled surface requirements.
   1847  */
   1848 uint32_t
   1849 i915_gem_get_unfenced_gtt_alignment(struct drm_device *dev,
   1850 				    uint32_t size,
   1851 				    int tiling_mode)
   1852 {
   1853 	/*
   1854 	 * Minimum alignment is 4k (GTT page size) for sane hw.
   1855 	 */
   1856 	if (INTEL_INFO(dev)->gen >= 4 || IS_G33(dev) ||
   1857 	    tiling_mode == I915_TILING_NONE)
   1858 		return 4096;
   1859 
   1860 	/* Previous hardware however needs to be aligned to a power-of-two
   1861 	 * tile height. The simplest method for determining this is to reuse
   1862 	 * the power-of-tile object size.
   1863 	 */
   1864 	return i915_gem_get_gtt_size(dev, size, tiling_mode);
   1865 }
   1866 
   1867 static int i915_gem_object_create_mmap_offset(struct drm_i915_gem_object *obj)
   1868 {
   1869 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   1870 	int ret;
   1871 
   1872 	if (obj->base.map_list.map)
   1873 		return 0;
   1874 
   1875 	dev_priv->mm.shrinker_no_lock_stealing = true;
   1876 
   1877 	ret = drm_gem_create_mmap_offset(&obj->base);
   1878 	if (ret != -ENOSPC)
   1879 		goto out;
   1880 
   1881 	/* Badly fragmented mmap space? The only way we can recover
   1882 	 * space is by destroying unwanted objects. We can't randomly release
   1883 	 * mmap_offsets as userspace expects them to be persistent for the
   1884 	 * lifetime of the objects. The closest we can is to release the
   1885 	 * offsets on purgeable objects by truncating it and marking it purged,
   1886 	 * which prevents userspace from ever using that object again.
   1887 	 */
   1888 	i915_gem_purge(dev_priv, obj->base.size >> PAGE_SHIFT);
   1889 	ret = drm_gem_create_mmap_offset(&obj->base);
   1890 	if (ret != -ENOSPC)
   1891 		goto out;
   1892 
   1893 	i915_gem_shrink_all(dev_priv);
   1894 	ret = drm_gem_create_mmap_offset(&obj->base);
   1895 out:
   1896 	dev_priv->mm.shrinker_no_lock_stealing = false;
   1897 
   1898 	return ret;
   1899 }
   1900 
   1901 static void i915_gem_object_free_mmap_offset(struct drm_i915_gem_object *obj)
   1902 {
   1903 	if (!obj->base.map_list.map)
   1904 		return;
   1905 
   1906 	drm_gem_free_mmap_offset(&obj->base);
   1907 }
   1908 
   1909 int
   1910 i915_gem_mmap_gtt(struct drm_file *file,
   1911 		  struct drm_device *dev,
   1912 		  uint32_t handle,
   1913 		  uint64_t *offset)
   1914 {
   1915 	struct drm_i915_private *dev_priv = dev->dev_private;
   1916 	struct drm_i915_gem_object *obj;
   1917 	int ret;
   1918 
   1919 	ret = i915_mutex_lock_interruptible(dev);
   1920 	if (ret)
   1921 		return ret;
   1922 
   1923 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, handle));
   1924 	if (&obj->base == NULL) {
   1925 		ret = -ENOENT;
   1926 		goto unlock;
   1927 	}
   1928 
   1929 	if (obj->base.size > dev_priv->mm.gtt_mappable_end) {
   1930 		ret = -E2BIG;
   1931 		goto out;
   1932 	}
   1933 
   1934 	if (obj->madv != I915_MADV_WILLNEED) {
   1935 		DRM_ERROR("Attempting to mmap a purgeable buffer\n");
   1936 		ret = -EINVAL;
   1937 		goto out;
   1938 	}
   1939 
   1940 	ret = i915_gem_object_create_mmap_offset(obj);
   1941 	if (ret)
   1942 		goto out;
   1943 
   1944 	*offset = (u64)obj->base.map_list.hash.key << PAGE_SHIFT;
   1945 
   1946 out:
   1947 	drm_gem_object_unreference(&obj->base);
   1948 unlock:
   1949 	mutex_unlock(&dev->struct_mutex);
   1950 	return ret;
   1951 }
   1952 
   1953 /**
   1954  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
   1955  * @dev: DRM device
   1956  * @data: GTT mapping ioctl data
   1957  * @file: GEM object info
   1958  *
   1959  * Simply returns the fake offset to userspace so it can mmap it.
   1960  * The mmap call will end up in drm_gem_mmap(), which will set things
   1961  * up so we can get faults in the handler above.
   1962  *
   1963  * The fault handler will take care of binding the object into the GTT
   1964  * (since it may have been evicted to make room for something), allocating
   1965  * a fence register, and mapping the appropriate aperture address into
   1966  * userspace.
   1967  */
   1968 int
   1969 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
   1970 			struct drm_file *file)
   1971 {
   1972 	struct drm_i915_gem_mmap_gtt *args = data;
   1973 
   1974 	return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
   1975 }
   1976 
   1977 /* Immediately discard the backing storage */
   1978 static void
   1979 i915_gem_object_truncate(struct drm_i915_gem_object *obj)
   1980 {
   1981 #ifndef __NetBSD__
   1982 	struct inode *inode;
   1983 #endif
   1984 
   1985 	i915_gem_object_free_mmap_offset(obj);
   1986 
   1987 #ifdef __NetBSD__
   1988 	{
   1989 		struct uvm_object *const uobj = obj->base.gemo_shm_uao;
   1990 
   1991 		if (uobj != NULL) {
   1992 			/* XXX Calling pgo_put like this is bogus.  */
   1993 			mutex_enter(uobj->vmobjlock);
   1994 			(*uobj->pgops->pgo_put)(uobj, 0, obj->base.size,
   1995 			    (PGO_ALLPAGES | PGO_FREE));
   1996 		}
   1997 	}
   1998 #else
   1999 	if (obj->base.filp == NULL)
   2000 		return;
   2001 
   2002 	/* Our goal here is to return as much of the memory as
   2003 	 * is possible back to the system as we are called from OOM.
   2004 	 * To do this we must instruct the shmfs to drop all of its
   2005 	 * backing pages, *now*.
   2006 	 */
   2007 	inode = obj->base.filp->f_path.dentry->d_inode;
   2008 	shmem_truncate_range(inode, 0, (loff_t)-1);
   2009 #endif
   2010 
   2011 	obj->madv = __I915_MADV_PURGED;
   2012 }
   2013 
   2014 static inline int
   2015 i915_gem_object_is_purgeable(struct drm_i915_gem_object *obj)
   2016 {
   2017 	return obj->madv == I915_MADV_DONTNEED;
   2018 }
   2019 
   2020 #ifdef __NetBSD__
   2021 static void
   2022 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj)
   2023 {
   2024 	struct drm_device *const dev = obj->base.dev;
   2025 	int ret;
   2026 
   2027 	/* XXX Cargo-culted from the Linux code.  */
   2028 	BUG_ON(obj->madv == __I915_MADV_PURGED);
   2029 
   2030 	ret = i915_gem_object_set_to_cpu_domain(obj, true);
   2031 	if (ret) {
   2032 		WARN_ON(ret != -EIO);
   2033 		i915_gem_clflush_object(obj);
   2034 		obj->base.read_domains = obj->base.write_domain =
   2035 		    I915_GEM_DOMAIN_CPU;
   2036 	}
   2037 
   2038 	if (i915_gem_object_needs_bit17_swizzle(obj))
   2039 		i915_gem_object_save_bit_17_swizzle(obj);
   2040 
   2041 	/* XXX Maintain dirty flag?  */
   2042 
   2043 	bus_dmamap_destroy(dev->dmat, obj->igo_dmamap);
   2044 	bus_dmamem_unwire_uvm_object(dev->dmat, obj->base.gemo_shm_uao, 0,
   2045 	    obj->base.size, obj->pages, obj->igo_nsegs);
   2046 
   2047 	kfree(obj->pages);
   2048 }
   2049 #else
   2050 static void
   2051 i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj)
   2052 {
   2053 	int page_count = obj->base.size / PAGE_SIZE;
   2054 	struct scatterlist *sg;
   2055 	int ret, i;
   2056 
   2057 	BUG_ON(obj->madv == __I915_MADV_PURGED);
   2058 
   2059 	ret = i915_gem_object_set_to_cpu_domain(obj, true);
   2060 	if (ret) {
   2061 		/* In the event of a disaster, abandon all caches and
   2062 		 * hope for the best.
   2063 		 */
   2064 		WARN_ON(ret != -EIO);
   2065 		i915_gem_clflush_object(obj);
   2066 		obj->base.read_domains = obj->base.write_domain = I915_GEM_DOMAIN_CPU;
   2067 	}
   2068 
   2069 	if (i915_gem_object_needs_bit17_swizzle(obj))
   2070 		i915_gem_object_save_bit_17_swizzle(obj);
   2071 
   2072 	if (obj->madv == I915_MADV_DONTNEED)
   2073 		obj->dirty = 0;
   2074 
   2075 	for_each_sg(obj->pages->sgl, sg, page_count, i) {
   2076 		struct page *page = sg_page(sg);
   2077 
   2078 		if (obj->dirty)
   2079 			set_page_dirty(page);
   2080 
   2081 		if (obj->madv == I915_MADV_WILLNEED)
   2082 			mark_page_accessed(page);
   2083 
   2084 		page_cache_release(page);
   2085 	}
   2086 	obj->dirty = 0;
   2087 
   2088 	sg_free_table(obj->pages);
   2089 	kfree(obj->pages);
   2090 }
   2091 #endif
   2092 
   2093 static int
   2094 i915_gem_object_put_pages(struct drm_i915_gem_object *obj)
   2095 {
   2096 	const struct drm_i915_gem_object_ops *ops = obj->ops;
   2097 
   2098 	if (obj->pages == NULL)
   2099 		return 0;
   2100 
   2101 	BUG_ON(obj->gtt_space);
   2102 
   2103 	if (obj->pages_pin_count)
   2104 		return -EBUSY;
   2105 
   2106 	/* ->put_pages might need to allocate memory for the bit17 swizzle
   2107 	 * array, hence protect them from being reaped by removing them from gtt
   2108 	 * lists early. */
   2109 	list_del(&obj->gtt_list);
   2110 
   2111 	ops->put_pages(obj);
   2112 	obj->pages = NULL;
   2113 
   2114 	if (i915_gem_object_is_purgeable(obj))
   2115 		i915_gem_object_truncate(obj);
   2116 
   2117 	return 0;
   2118 }
   2119 
   2120 static long
   2121 __i915_gem_shrink(struct drm_i915_private *dev_priv, long target,
   2122 		  bool purgeable_only)
   2123 {
   2124 	struct drm_i915_gem_object *obj, *next;
   2125 	long count = 0;
   2126 
   2127 	list_for_each_entry_safe(obj, next,
   2128 				 &dev_priv->mm.unbound_list,
   2129 				 gtt_list) {
   2130 		if ((i915_gem_object_is_purgeable(obj) || !purgeable_only) &&
   2131 		    i915_gem_object_put_pages(obj) == 0) {
   2132 			count += obj->base.size >> PAGE_SHIFT;
   2133 			if (count >= target)
   2134 				return count;
   2135 		}
   2136 	}
   2137 
   2138 	list_for_each_entry_safe(obj, next,
   2139 				 &dev_priv->mm.inactive_list,
   2140 				 mm_list) {
   2141 		if ((i915_gem_object_is_purgeable(obj) || !purgeable_only) &&
   2142 		    i915_gem_object_unbind(obj) == 0 &&
   2143 		    i915_gem_object_put_pages(obj) == 0) {
   2144 			count += obj->base.size >> PAGE_SHIFT;
   2145 			if (count >= target)
   2146 				return count;
   2147 		}
   2148 	}
   2149 
   2150 	return count;
   2151 }
   2152 
   2153 static long
   2154 i915_gem_purge(struct drm_i915_private *dev_priv, long target)
   2155 {
   2156 	return __i915_gem_shrink(dev_priv, target, true);
   2157 }
   2158 
   2159 static void
   2160 i915_gem_shrink_all(struct drm_i915_private *dev_priv)
   2161 {
   2162 	struct drm_i915_gem_object *obj, *next;
   2163 
   2164 	i915_gem_evict_everything(dev_priv->dev);
   2165 
   2166 	list_for_each_entry_safe(obj, next, &dev_priv->mm.unbound_list, gtt_list)
   2167 		i915_gem_object_put_pages(obj);
   2168 }
   2169 
   2170 #ifdef __NetBSD__
   2171 static int
   2172 i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
   2173 {
   2174 	struct drm_device *const dev = obj->base.dev;
   2175 	struct vm_page *page;
   2176 	int error;
   2177 
   2178 	/* XXX Cargo-culted from the Linux code.  */
   2179 	BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
   2180 	BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
   2181 
   2182 	KASSERT(obj->pages == NULL);
   2183 	TAILQ_INIT(&obj->igo_pageq);
   2184 	obj->pages = kcalloc((obj->base.size / PAGE_SIZE),
   2185 	    sizeof(obj->pages[0]), GFP_KERNEL);
   2186 	if (obj->pages == NULL) {
   2187 		error = -ENOMEM;
   2188 		goto fail0;
   2189 	}
   2190 
   2191 	/* XXX errno NetBSD->Linux */
   2192 	error = -bus_dmamem_wire_uvm_object(dev->dmat, obj->base.gemo_shm_uao,
   2193 	    0, obj->base.size, &obj->igo_pageq, PAGE_SIZE, 0, obj->pages,
   2194 	    (obj->base.size / PAGE_SIZE), &obj->igo_nsegs, BUS_DMA_NOWAIT);
   2195 	if (error)
   2196 		/* XXX Try i915_gem_purge, i915_gem_shrink_all.  */
   2197 		goto fail1;
   2198 	KASSERT(0 < obj->igo_nsegs);
   2199 	KASSERT(obj->igo_nsegs <= (obj->base.size / PAGE_SIZE));
   2200 
   2201 	/*
   2202 	 * Check that the paddrs will fit in 40 bits.
   2203 	 *
   2204 	 * XXX This is wrong; we ought to pass this constraint to
   2205 	 * bus_dmamem_wire_uvm_object instead.
   2206 	 */
   2207 	TAILQ_FOREACH(page, &obj->igo_pageq, pageq.queue) {
   2208 		if (VM_PAGE_TO_PHYS(page) & ~0xffffffffffULL) {
   2209 			DRM_ERROR("GEM physical address exceeds 40 bits"
   2210 			    ": %"PRIxMAX"\n",
   2211 			    (uintmax_t)VM_PAGE_TO_PHYS(page));
   2212 			goto fail2;
   2213 		}
   2214 	}
   2215 
   2216 	/* XXX errno NetBSD->Linux */
   2217 	error = -bus_dmamap_create(dev->dmat, obj->base.size, obj->igo_nsegs,
   2218 	    PAGE_SIZE, 0, BUS_DMA_NOWAIT, &obj->igo_dmamap);
   2219 	if (error)
   2220 		goto fail2;
   2221 
   2222 	/* XXX Cargo-culted from the Linux code.  */
   2223 	if (i915_gem_object_needs_bit17_swizzle(obj))
   2224 		i915_gem_object_do_bit_17_swizzle(obj);
   2225 
   2226 	/* Success!  */
   2227 	return 0;
   2228 
   2229 fail2:	bus_dmamem_unwire_uvm_object(dev->dmat, obj->base.gemo_shm_uao, 0,
   2230 	    obj->base.size, obj->pages, (obj->base.size / PAGE_SIZE));
   2231 fail1:	kfree(obj->pages);
   2232 	obj->pages = NULL;
   2233 fail0:	return error;
   2234 }
   2235 #else
   2236 static int
   2237 i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
   2238 {
   2239 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   2240 	int page_count, i;
   2241 	struct address_space *mapping;
   2242 	struct sg_table *st;
   2243 	struct scatterlist *sg;
   2244 	struct page *page;
   2245 	gfp_t gfp;
   2246 
   2247 	/* Assert that the object is not currently in any GPU domain. As it
   2248 	 * wasn't in the GTT, there shouldn't be any way it could have been in
   2249 	 * a GPU cache
   2250 	 */
   2251 	BUG_ON(obj->base.read_domains & I915_GEM_GPU_DOMAINS);
   2252 	BUG_ON(obj->base.write_domain & I915_GEM_GPU_DOMAINS);
   2253 
   2254 	st = kmalloc(sizeof(*st), GFP_KERNEL);
   2255 	if (st == NULL)
   2256 		return -ENOMEM;
   2257 
   2258 	page_count = obj->base.size / PAGE_SIZE;
   2259 	if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
   2260 		sg_free_table(st);
   2261 		kfree(st);
   2262 		return -ENOMEM;
   2263 	}
   2264 
   2265 	/* Get the list of pages out of our struct file.  They'll be pinned
   2266 	 * at this point until we release them.
   2267 	 *
   2268 	 * Fail silently without starting the shrinker
   2269 	 */
   2270 	mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
   2271 	gfp = mapping_gfp_mask(mapping);
   2272 	gfp |= __GFP_NORETRY | __GFP_NOWARN | __GFP_NO_KSWAPD;
   2273 	gfp &= ~(__GFP_IO | __GFP_WAIT);
   2274 	for_each_sg(st->sgl, sg, page_count, i) {
   2275 		page = shmem_read_mapping_page_gfp(mapping, i, gfp);
   2276 		if (IS_ERR(page)) {
   2277 			i915_gem_purge(dev_priv, page_count);
   2278 			page = shmem_read_mapping_page_gfp(mapping, i, gfp);
   2279 		}
   2280 		if (IS_ERR(page)) {
   2281 			/* We've tried hard to allocate the memory by reaping
   2282 			 * our own buffer, now let the real VM do its job and
   2283 			 * go down in flames if truly OOM.
   2284 			 */
   2285 			gfp &= ~(__GFP_NORETRY | __GFP_NOWARN | __GFP_NO_KSWAPD);
   2286 			gfp |= __GFP_IO | __GFP_WAIT;
   2287 
   2288 			i915_gem_shrink_all(dev_priv);
   2289 			page = shmem_read_mapping_page_gfp(mapping, i, gfp);
   2290 			if (IS_ERR(page))
   2291 				goto err_pages;
   2292 
   2293 			gfp |= __GFP_NORETRY | __GFP_NOWARN | __GFP_NO_KSWAPD;
   2294 			gfp &= ~(__GFP_IO | __GFP_WAIT);
   2295 		}
   2296 
   2297 		sg_set_page(sg, page, PAGE_SIZE, 0);
   2298 	}
   2299 
   2300 	obj->pages = st;
   2301 
   2302 	if (i915_gem_object_needs_bit17_swizzle(obj))
   2303 		i915_gem_object_do_bit_17_swizzle(obj);
   2304 
   2305 	return 0;
   2306 
   2307 err_pages:
   2308 	for_each_sg(st->sgl, sg, i, page_count)
   2309 		page_cache_release(sg_page(sg));
   2310 	sg_free_table(st);
   2311 	kfree(st);
   2312 	return PTR_ERR(page);
   2313 }
   2314 #endif
   2315 
   2316 /* Ensure that the associated pages are gathered from the backing storage
   2317  * and pinned into our object. i915_gem_object_get_pages() may be called
   2318  * multiple times before they are released by a single call to
   2319  * i915_gem_object_put_pages() - once the pages are no longer referenced
   2320  * either as a result of memory pressure (reaping pages under the shrinker)
   2321  * or as the object is itself released.
   2322  */
   2323 int
   2324 i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
   2325 {
   2326 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   2327 	const struct drm_i915_gem_object_ops *ops = obj->ops;
   2328 	int ret;
   2329 
   2330 	if (obj->pages)
   2331 		return 0;
   2332 
   2333 	BUG_ON(obj->pages_pin_count);
   2334 
   2335 	ret = ops->get_pages(obj);
   2336 	if (ret)
   2337 		return ret;
   2338 
   2339 	list_add_tail(&obj->gtt_list, &dev_priv->mm.unbound_list);
   2340 	return 0;
   2341 }
   2342 
   2343 void
   2344 i915_gem_object_move_to_active(struct drm_i915_gem_object *obj,
   2345 			       struct intel_ring_buffer *ring)
   2346 {
   2347 	struct drm_device *dev = obj->base.dev;
   2348 	struct drm_i915_private *dev_priv = dev->dev_private;
   2349 	u32 seqno = intel_ring_get_seqno(ring);
   2350 
   2351 	BUG_ON(ring == NULL);
   2352 	obj->ring = ring;
   2353 
   2354 	/* Add a reference if we're newly entering the active list. */
   2355 	if (!obj->active) {
   2356 		drm_gem_object_reference(&obj->base);
   2357 		obj->active = 1;
   2358 	}
   2359 
   2360 	/* Move from whatever list we were on to the tail of execution. */
   2361 	list_move_tail(&obj->mm_list, &dev_priv->mm.active_list);
   2362 	list_move_tail(&obj->ring_list, &ring->active_list);
   2363 
   2364 	obj->last_read_seqno = seqno;
   2365 
   2366 	if (obj->fenced_gpu_access) {
   2367 		obj->last_fenced_seqno = seqno;
   2368 
   2369 		/* Bump MRU to take account of the delayed flush */
   2370 		if (obj->fence_reg != I915_FENCE_REG_NONE) {
   2371 			struct drm_i915_fence_reg *reg;
   2372 
   2373 			reg = &dev_priv->fence_regs[obj->fence_reg];
   2374 			list_move_tail(&reg->lru_list,
   2375 				       &dev_priv->mm.fence_list);
   2376 		}
   2377 	}
   2378 }
   2379 
   2380 static void
   2381 i915_gem_object_move_to_inactive(struct drm_i915_gem_object *obj)
   2382 {
   2383 	struct drm_device *dev = obj->base.dev;
   2384 	struct drm_i915_private *dev_priv = dev->dev_private;
   2385 
   2386 	BUG_ON(obj->base.write_domain & ~I915_GEM_GPU_DOMAINS);
   2387 	BUG_ON(!obj->active);
   2388 
   2389 	if (obj->pin_count) /* are we a framebuffer? */
   2390 		intel_mark_fb_idle(obj);
   2391 
   2392 	list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
   2393 
   2394 	list_del_init(&obj->ring_list);
   2395 	obj->ring = NULL;
   2396 
   2397 	obj->last_read_seqno = 0;
   2398 	obj->last_write_seqno = 0;
   2399 	obj->base.write_domain = 0;
   2400 
   2401 	obj->last_fenced_seqno = 0;
   2402 	obj->fenced_gpu_access = false;
   2403 
   2404 	obj->active = 0;
   2405 	drm_gem_object_unreference(&obj->base);
   2406 
   2407 	WARN_ON(i915_verify_lists(dev));
   2408 }
   2409 
   2410 static int
   2411 i915_gem_handle_seqno_wrap(struct drm_device *dev)
   2412 {
   2413 	struct drm_i915_private *dev_priv = dev->dev_private;
   2414 	struct intel_ring_buffer *ring;
   2415 	int ret, i, j;
   2416 
   2417 	/* The hardware uses various monotonic 32-bit counters, if we
   2418 	 * detect that they will wraparound we need to idle the GPU
   2419 	 * and reset those counters.
   2420 	 */
   2421 	ret = 0;
   2422 	for_each_ring(ring, dev_priv, i) {
   2423 		for (j = 0; j < ARRAY_SIZE(ring->sync_seqno); j++)
   2424 			ret |= ring->sync_seqno[j] != 0;
   2425 	}
   2426 	if (ret == 0)
   2427 		return ret;
   2428 
   2429 	ret = i915_gpu_idle(dev);
   2430 	if (ret)
   2431 		return ret;
   2432 
   2433 	i915_gem_retire_requests(dev);
   2434 	for_each_ring(ring, dev_priv, i) {
   2435 		for (j = 0; j < ARRAY_SIZE(ring->sync_seqno); j++)
   2436 			ring->sync_seqno[j] = 0;
   2437 	}
   2438 
   2439 	return 0;
   2440 }
   2441 
   2442 int
   2443 i915_gem_get_seqno(struct drm_device *dev, u32 *seqno)
   2444 {
   2445 	struct drm_i915_private *dev_priv = dev->dev_private;
   2446 
   2447 	/* reserve 0 for non-seqno */
   2448 	if (dev_priv->next_seqno == 0) {
   2449 		int ret = i915_gem_handle_seqno_wrap(dev);
   2450 		if (ret)
   2451 			return ret;
   2452 
   2453 		dev_priv->next_seqno = 1;
   2454 	}
   2455 
   2456 	*seqno = dev_priv->next_seqno++;
   2457 	return 0;
   2458 }
   2459 
   2460 int
   2461 i915_add_request(struct intel_ring_buffer *ring,
   2462 		 struct drm_file *file,
   2463 		 u32 *out_seqno)
   2464 {
   2465 	drm_i915_private_t *dev_priv = ring->dev->dev_private;
   2466 	struct drm_i915_gem_request *request;
   2467 	u32 request_ring_position;
   2468 	int was_empty;
   2469 	int ret;
   2470 
   2471 	/*
   2472 	 * Emit any outstanding flushes - execbuf can fail to emit the flush
   2473 	 * after having emitted the batchbuffer command. Hence we need to fix
   2474 	 * things up similar to emitting the lazy request. The difference here
   2475 	 * is that the flush _must_ happen before the next request, no matter
   2476 	 * what.
   2477 	 */
   2478 	ret = intel_ring_flush_all_caches(ring);
   2479 	if (ret)
   2480 		return ret;
   2481 
   2482 	request = kmalloc(sizeof(*request), GFP_KERNEL);
   2483 	if (request == NULL)
   2484 		return -ENOMEM;
   2485 
   2486 
   2487 	/* Record the position of the start of the request so that
   2488 	 * should we detect the updated seqno part-way through the
   2489 	 * GPU processing the request, we never over-estimate the
   2490 	 * position of the head.
   2491 	 */
   2492 	request_ring_position = intel_ring_get_tail(ring);
   2493 
   2494 	ret = ring->add_request(ring);
   2495 	if (ret) {
   2496 		kfree(request);
   2497 		return ret;
   2498 	}
   2499 
   2500 	request->seqno = intel_ring_get_seqno(ring);
   2501 	request->ring = ring;
   2502 	request->tail = request_ring_position;
   2503 	request->emitted_jiffies = jiffies;
   2504 	was_empty = list_empty(&ring->request_list);
   2505 	list_add_tail(&request->list, &ring->request_list);
   2506 	request->file_priv = NULL;
   2507 
   2508 	if (file) {
   2509 		struct drm_i915_file_private *file_priv = file->driver_priv;
   2510 
   2511 		spin_lock(&file_priv->mm.lock);
   2512 		request->file_priv = file_priv;
   2513 		list_add_tail(&request->client_list,
   2514 			      &file_priv->mm.request_list);
   2515 		spin_unlock(&file_priv->mm.lock);
   2516 	}
   2517 
   2518 	trace_i915_gem_request_add(ring, request->seqno);
   2519 	ring->outstanding_lazy_request = 0;
   2520 
   2521 	if (!dev_priv->mm.suspended) {
   2522 		if (i915_enable_hangcheck) {
   2523 			mod_timer(&dev_priv->hangcheck_timer,
   2524 				  round_jiffies_up(jiffies + DRM_I915_HANGCHECK_JIFFIES));
   2525 		}
   2526 		if (was_empty) {
   2527 			queue_delayed_work(dev_priv->wq,
   2528 					   &dev_priv->mm.retire_work,
   2529 					   round_jiffies_up_relative(HZ));
   2530 			intel_mark_busy(dev_priv->dev);
   2531 		}
   2532 	}
   2533 
   2534 	if (out_seqno)
   2535 		*out_seqno = request->seqno;
   2536 	return 0;
   2537 }
   2538 
   2539 static inline void
   2540 i915_gem_request_remove_from_client(struct drm_i915_gem_request *request)
   2541 {
   2542 	struct drm_i915_file_private *file_priv = request->file_priv;
   2543 
   2544 	if (!file_priv)
   2545 		return;
   2546 
   2547 	spin_lock(&file_priv->mm.lock);
   2548 	if (request->file_priv) {
   2549 		list_del(&request->client_list);
   2550 		request->file_priv = NULL;
   2551 	}
   2552 	spin_unlock(&file_priv->mm.lock);
   2553 }
   2554 
   2555 static void i915_gem_reset_ring_lists(struct drm_i915_private *dev_priv,
   2556 				      struct intel_ring_buffer *ring)
   2557 {
   2558 	while (!list_empty(&ring->request_list)) {
   2559 		struct drm_i915_gem_request *request;
   2560 
   2561 		request = list_first_entry(&ring->request_list,
   2562 					   struct drm_i915_gem_request,
   2563 					   list);
   2564 
   2565 		list_del(&request->list);
   2566 		i915_gem_request_remove_from_client(request);
   2567 		kfree(request);
   2568 	}
   2569 
   2570 	while (!list_empty(&ring->active_list)) {
   2571 		struct drm_i915_gem_object *obj;
   2572 
   2573 		obj = list_first_entry(&ring->active_list,
   2574 				       struct drm_i915_gem_object,
   2575 				       ring_list);
   2576 
   2577 		i915_gem_object_move_to_inactive(obj);
   2578 	}
   2579 }
   2580 
   2581 static void i915_gem_reset_fences(struct drm_device *dev)
   2582 {
   2583 	struct drm_i915_private *dev_priv = dev->dev_private;
   2584 	int i;
   2585 
   2586 	for (i = 0; i < dev_priv->num_fence_regs; i++) {
   2587 		struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
   2588 
   2589 		i915_gem_write_fence(dev, i, NULL);
   2590 
   2591 		if (reg->obj)
   2592 			i915_gem_object_fence_lost(reg->obj);
   2593 
   2594 		reg->pin_count = 0;
   2595 		reg->obj = NULL;
   2596 		INIT_LIST_HEAD(&reg->lru_list);
   2597 	}
   2598 
   2599 	INIT_LIST_HEAD(&dev_priv->mm.fence_list);
   2600 }
   2601 
   2602 void i915_gem_reset(struct drm_device *dev)
   2603 {
   2604 	struct drm_i915_private *dev_priv = dev->dev_private;
   2605 	struct drm_i915_gem_object *obj;
   2606 	struct intel_ring_buffer *ring;
   2607 	int i;
   2608 
   2609 	for_each_ring(ring, dev_priv, i)
   2610 		i915_gem_reset_ring_lists(dev_priv, ring);
   2611 
   2612 	/* Move everything out of the GPU domains to ensure we do any
   2613 	 * necessary invalidation upon reuse.
   2614 	 */
   2615 	list_for_each_entry(obj,
   2616 			    &dev_priv->mm.inactive_list,
   2617 			    mm_list)
   2618 	{
   2619 		obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
   2620 	}
   2621 
   2622 	/* The fence registers are invalidated so clear them out */
   2623 	i915_gem_reset_fences(dev);
   2624 }
   2625 
   2626 /**
   2627  * This function clears the request list as sequence numbers are passed.
   2628  */
   2629 void
   2630 i915_gem_retire_requests_ring(struct intel_ring_buffer *ring)
   2631 {
   2632 	uint32_t seqno;
   2633 
   2634 	if (list_empty(&ring->request_list))
   2635 		return;
   2636 
   2637 	WARN_ON(i915_verify_lists(ring->dev));
   2638 
   2639 	seqno = ring->get_seqno(ring, true);
   2640 
   2641 	while (!list_empty(&ring->request_list)) {
   2642 		struct drm_i915_gem_request *request;
   2643 
   2644 		request = list_first_entry(&ring->request_list,
   2645 					   struct drm_i915_gem_request,
   2646 					   list);
   2647 
   2648 		if (!i915_seqno_passed(seqno, request->seqno))
   2649 			break;
   2650 
   2651 		trace_i915_gem_request_retire(ring, request->seqno);
   2652 		/* We know the GPU must have read the request to have
   2653 		 * sent us the seqno + interrupt, so use the position
   2654 		 * of tail of the request to update the last known position
   2655 		 * of the GPU head.
   2656 		 */
   2657 		ring->last_retired_head = request->tail;
   2658 
   2659 		list_del(&request->list);
   2660 		i915_gem_request_remove_from_client(request);
   2661 		kfree(request);
   2662 	}
   2663 
   2664 	/* Move any buffers on the active list that are no longer referenced
   2665 	 * by the ringbuffer to the flushing/inactive lists as appropriate.
   2666 	 */
   2667 	while (!list_empty(&ring->active_list)) {
   2668 		struct drm_i915_gem_object *obj;
   2669 
   2670 		obj = list_first_entry(&ring->active_list,
   2671 				      struct drm_i915_gem_object,
   2672 				      ring_list);
   2673 
   2674 		if (!i915_seqno_passed(seqno, obj->last_read_seqno))
   2675 			break;
   2676 
   2677 		i915_gem_object_move_to_inactive(obj);
   2678 	}
   2679 
   2680 	if (unlikely(ring->trace_irq_seqno &&
   2681 		     i915_seqno_passed(seqno, ring->trace_irq_seqno))) {
   2682 		ring->irq_put(ring);
   2683 		ring->trace_irq_seqno = 0;
   2684 	}
   2685 
   2686 	WARN_ON(i915_verify_lists(ring->dev));
   2687 }
   2688 
   2689 void
   2690 i915_gem_retire_requests(struct drm_device *dev)
   2691 {
   2692 	drm_i915_private_t *dev_priv = dev->dev_private;
   2693 	struct intel_ring_buffer *ring;
   2694 	int i;
   2695 
   2696 	for_each_ring(ring, dev_priv, i)
   2697 		i915_gem_retire_requests_ring(ring);
   2698 }
   2699 
   2700 static void
   2701 i915_gem_retire_work_handler(struct work_struct *work)
   2702 {
   2703 	drm_i915_private_t *dev_priv;
   2704 	struct drm_device *dev;
   2705 	struct intel_ring_buffer *ring;
   2706 	bool idle;
   2707 	int i;
   2708 
   2709 	dev_priv = container_of(work, drm_i915_private_t,
   2710 				mm.retire_work.work);
   2711 	dev = dev_priv->dev;
   2712 
   2713 	/* Come back later if the device is busy... */
   2714 	if (!mutex_trylock(&dev->struct_mutex)) {
   2715 		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work,
   2716 				   round_jiffies_up_relative(HZ));
   2717 		return;
   2718 	}
   2719 
   2720 	i915_gem_retire_requests(dev);
   2721 
   2722 	/* Send a periodic flush down the ring so we don't hold onto GEM
   2723 	 * objects indefinitely.
   2724 	 */
   2725 	idle = true;
   2726 	for_each_ring(ring, dev_priv, i) {
   2727 		if (ring->gpu_caches_dirty)
   2728 			i915_add_request(ring, NULL, NULL);
   2729 
   2730 		idle &= list_empty(&ring->request_list);
   2731 	}
   2732 
   2733 	if (!dev_priv->mm.suspended && !idle)
   2734 		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work,
   2735 				   round_jiffies_up_relative(HZ));
   2736 	if (idle)
   2737 		intel_mark_idle(dev);
   2738 
   2739 	mutex_unlock(&dev->struct_mutex);
   2740 }
   2741 
   2742 /**
   2743  * Ensures that an object will eventually get non-busy by flushing any required
   2744  * write domains, emitting any outstanding lazy request and retiring and
   2745  * completed requests.
   2746  */
   2747 static int
   2748 i915_gem_object_flush_active(struct drm_i915_gem_object *obj)
   2749 {
   2750 	int ret;
   2751 
   2752 	if (obj->active) {
   2753 		ret = i915_gem_check_olr(obj->ring, obj->last_read_seqno);
   2754 		if (ret)
   2755 			return ret;
   2756 
   2757 		i915_gem_retire_requests_ring(obj->ring);
   2758 	}
   2759 
   2760 	return 0;
   2761 }
   2762 
   2763 /**
   2764  * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
   2765  * @DRM_IOCTL_ARGS: standard ioctl arguments
   2766  *
   2767  * Returns 0 if successful, else an error is returned with the remaining time in
   2768  * the timeout parameter.
   2769  *  -ETIME: object is still busy after timeout
   2770  *  -ERESTARTSYS: signal interrupted the wait
   2771  *  -ENONENT: object doesn't exist
   2772  * Also possible, but rare:
   2773  *  -EAGAIN: GPU wedged
   2774  *  -ENOMEM: damn
   2775  *  -ENODEV: Internal IRQ fail
   2776  *  -E?: The add request failed
   2777  *
   2778  * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
   2779  * non-zero timeout parameter the wait ioctl will wait for the given number of
   2780  * nanoseconds on an object becoming unbusy. Since the wait itself does so
   2781  * without holding struct_mutex the object may become re-busied before this
   2782  * function completes. A similar but shorter * race condition exists in the busy
   2783  * ioctl
   2784  */
   2785 int
   2786 i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
   2787 {
   2788 	struct drm_i915_gem_wait *args = data;
   2789 	struct drm_i915_gem_object *obj;
   2790 	struct intel_ring_buffer *ring = NULL;
   2791 	struct timespec timeout_stack, *timeout = NULL;
   2792 	u32 seqno = 0;
   2793 	int ret = 0;
   2794 
   2795 	if (args->timeout_ns >= 0) {
   2796 		timeout_stack = ns_to_timespec(args->timeout_ns);
   2797 		timeout = &timeout_stack;
   2798 	}
   2799 
   2800 	ret = i915_mutex_lock_interruptible(dev);
   2801 	if (ret)
   2802 		return ret;
   2803 
   2804 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->bo_handle));
   2805 	if (&obj->base == NULL) {
   2806 		mutex_unlock(&dev->struct_mutex);
   2807 		return -ENOENT;
   2808 	}
   2809 
   2810 	/* Need to make sure the object gets inactive eventually. */
   2811 	ret = i915_gem_object_flush_active(obj);
   2812 	if (ret)
   2813 		goto out;
   2814 
   2815 	if (obj->active) {
   2816 		seqno = obj->last_read_seqno;
   2817 		ring = obj->ring;
   2818 	}
   2819 
   2820 	if (seqno == 0)
   2821 		 goto out;
   2822 
   2823 	/* Do this after OLR check to make sure we make forward progress polling
   2824 	 * on this IOCTL with a 0 timeout (like busy ioctl)
   2825 	 */
   2826 	if (!args->timeout_ns) {
   2827 		ret = -ETIME;
   2828 		goto out;
   2829 	}
   2830 
   2831 	drm_gem_object_unreference(&obj->base);
   2832 	mutex_unlock(&dev->struct_mutex);
   2833 
   2834 	ret = __wait_seqno(ring, seqno, true, timeout);
   2835 	if (timeout) {
   2836 		WARN_ON(!timespec_valid(timeout));
   2837 		args->timeout_ns = timespec_to_ns(timeout);
   2838 	}
   2839 	return ret;
   2840 
   2841 out:
   2842 	drm_gem_object_unreference(&obj->base);
   2843 	mutex_unlock(&dev->struct_mutex);
   2844 	return ret;
   2845 }
   2846 
   2847 /**
   2848  * i915_gem_object_sync - sync an object to a ring.
   2849  *
   2850  * @obj: object which may be in use on another ring.
   2851  * @to: ring we wish to use the object on. May be NULL.
   2852  *
   2853  * This code is meant to abstract object synchronization with the GPU.
   2854  * Calling with NULL implies synchronizing the object with the CPU
   2855  * rather than a particular GPU ring.
   2856  *
   2857  * Returns 0 if successful, else propagates up the lower layer error.
   2858  */
   2859 int
   2860 i915_gem_object_sync(struct drm_i915_gem_object *obj,
   2861 		     struct intel_ring_buffer *to)
   2862 {
   2863 	struct intel_ring_buffer *from = obj->ring;
   2864 	u32 seqno;
   2865 	int ret, idx;
   2866 
   2867 	if (from == NULL || to == from)
   2868 		return 0;
   2869 
   2870 	if (to == NULL || !i915_semaphore_is_enabled(obj->base.dev))
   2871 		return i915_gem_object_wait_rendering(obj, false);
   2872 
   2873 	idx = intel_ring_sync_index(from, to);
   2874 
   2875 	seqno = obj->last_read_seqno;
   2876 	if (seqno <= from->sync_seqno[idx])
   2877 		return 0;
   2878 
   2879 	ret = i915_gem_check_olr(obj->ring, seqno);
   2880 	if (ret)
   2881 		return ret;
   2882 
   2883 	ret = to->sync_to(to, from, seqno);
   2884 	if (!ret)
   2885 		/* We use last_read_seqno because sync_to()
   2886 		 * might have just caused seqno wrap under
   2887 		 * the radar.
   2888 		 */
   2889 		from->sync_seqno[idx] = obj->last_read_seqno;
   2890 
   2891 	return ret;
   2892 }
   2893 
   2894 static void i915_gem_object_finish_gtt(struct drm_i915_gem_object *obj)
   2895 {
   2896 	u32 old_write_domain, old_read_domains;
   2897 
   2898 	/* Act a barrier for all accesses through the GTT */
   2899 	mb();
   2900 
   2901 	/* Force a pagefault for domain tracking on next user access */
   2902 	i915_gem_release_mmap(obj);
   2903 
   2904 	if ((obj->base.read_domains & I915_GEM_DOMAIN_GTT) == 0)
   2905 		return;
   2906 
   2907 	old_read_domains = obj->base.read_domains;
   2908 	old_write_domain = obj->base.write_domain;
   2909 
   2910 	obj->base.read_domains &= ~I915_GEM_DOMAIN_GTT;
   2911 	obj->base.write_domain &= ~I915_GEM_DOMAIN_GTT;
   2912 
   2913 	trace_i915_gem_object_change_domain(obj,
   2914 					    old_read_domains,
   2915 					    old_write_domain);
   2916 }
   2917 
   2918 /**
   2919  * Unbinds an object from the GTT aperture.
   2920  */
   2921 int
   2922 i915_gem_object_unbind(struct drm_i915_gem_object *obj)
   2923 {
   2924 	drm_i915_private_t *dev_priv = obj->base.dev->dev_private;
   2925 	int ret = 0;
   2926 
   2927 	if (obj->gtt_space == NULL)
   2928 		return 0;
   2929 
   2930 	if (obj->pin_count)
   2931 		return -EBUSY;
   2932 
   2933 	BUG_ON(obj->pages == NULL);
   2934 
   2935 	ret = i915_gem_object_finish_gpu(obj);
   2936 	if (ret)
   2937 		return ret;
   2938 	/* Continue on if we fail due to EIO, the GPU is hung so we
   2939 	 * should be safe and we need to cleanup or else we might
   2940 	 * cause memory corruption through use-after-free.
   2941 	 */
   2942 
   2943 	i915_gem_object_finish_gtt(obj);
   2944 
   2945 	/* release the fence reg _after_ flushing */
   2946 	ret = i915_gem_object_put_fence(obj);
   2947 	if (ret)
   2948 		return ret;
   2949 
   2950 	trace_i915_gem_object_unbind(obj);
   2951 
   2952 	if (obj->has_global_gtt_mapping)
   2953 		i915_gem_gtt_unbind_object(obj);
   2954 	if (obj->has_aliasing_ppgtt_mapping) {
   2955 		i915_ppgtt_unbind_object(dev_priv->mm.aliasing_ppgtt, obj);
   2956 		obj->has_aliasing_ppgtt_mapping = 0;
   2957 	}
   2958 	i915_gem_gtt_finish_object(obj);
   2959 
   2960 	list_del(&obj->mm_list);
   2961 	list_move_tail(&obj->gtt_list, &dev_priv->mm.unbound_list);
   2962 	/* Avoid an unnecessary call to unbind on rebind. */
   2963 	obj->map_and_fenceable = true;
   2964 
   2965 	drm_mm_put_block(obj->gtt_space);
   2966 	obj->gtt_space = NULL;
   2967 	obj->gtt_offset = 0;
   2968 
   2969 	return 0;
   2970 }
   2971 
   2972 int i915_gpu_idle(struct drm_device *dev)
   2973 {
   2974 	drm_i915_private_t *dev_priv = dev->dev_private;
   2975 	struct intel_ring_buffer *ring;
   2976 	int ret, i;
   2977 
   2978 	/* Flush everything onto the inactive list. */
   2979 	for_each_ring(ring, dev_priv, i) {
   2980 		ret = i915_switch_context(ring, NULL, DEFAULT_CONTEXT_ID);
   2981 		if (ret)
   2982 			return ret;
   2983 
   2984 		ret = intel_ring_idle(ring);
   2985 		if (ret)
   2986 			return ret;
   2987 	}
   2988 
   2989 	return 0;
   2990 }
   2991 
   2992 static void sandybridge_write_fence_reg(struct drm_device *dev, int reg,
   2993 					struct drm_i915_gem_object *obj)
   2994 {
   2995 	drm_i915_private_t *dev_priv = dev->dev_private;
   2996 	uint64_t val;
   2997 
   2998 	if (obj) {
   2999 		u32 size = obj->gtt_space->size;
   3000 
   3001 		val = (uint64_t)((obj->gtt_offset + size - 4096) &
   3002 				 0xfffff000) << 32;
   3003 		val |= obj->gtt_offset & 0xfffff000;
   3004 		val |= (uint64_t)((obj->stride / 128) - 1) <<
   3005 			SANDYBRIDGE_FENCE_PITCH_SHIFT;
   3006 
   3007 		if (obj->tiling_mode == I915_TILING_Y)
   3008 			val |= 1 << I965_FENCE_TILING_Y_SHIFT;
   3009 		val |= I965_FENCE_REG_VALID;
   3010 	} else
   3011 		val = 0;
   3012 
   3013 	I915_WRITE64(FENCE_REG_SANDYBRIDGE_0 + reg * 8, val);
   3014 	POSTING_READ(FENCE_REG_SANDYBRIDGE_0 + reg * 8);
   3015 }
   3016 
   3017 static void i965_write_fence_reg(struct drm_device *dev, int reg,
   3018 				 struct drm_i915_gem_object *obj)
   3019 {
   3020 	drm_i915_private_t *dev_priv = dev->dev_private;
   3021 	uint64_t val;
   3022 
   3023 	if (obj) {
   3024 		u32 size = obj->gtt_space->size;
   3025 
   3026 		val = (uint64_t)((obj->gtt_offset + size - 4096) &
   3027 				 0xfffff000) << 32;
   3028 		val |= obj->gtt_offset & 0xfffff000;
   3029 		val |= ((obj->stride / 128) - 1) << I965_FENCE_PITCH_SHIFT;
   3030 		if (obj->tiling_mode == I915_TILING_Y)
   3031 			val |= 1 << I965_FENCE_TILING_Y_SHIFT;
   3032 		val |= I965_FENCE_REG_VALID;
   3033 	} else
   3034 		val = 0;
   3035 
   3036 	I915_WRITE64(FENCE_REG_965_0 + reg * 8, val);
   3037 	POSTING_READ(FENCE_REG_965_0 + reg * 8);
   3038 }
   3039 
   3040 static void i915_write_fence_reg(struct drm_device *dev, int reg,
   3041 				 struct drm_i915_gem_object *obj)
   3042 {
   3043 	drm_i915_private_t *dev_priv = dev->dev_private;
   3044 	u32 val;
   3045 
   3046 	if (obj) {
   3047 		u32 size = obj->gtt_space->size;
   3048 		int pitch_val;
   3049 		int tile_width;
   3050 
   3051 		WARN((obj->gtt_offset & ~I915_FENCE_START_MASK) ||
   3052 		     (size & -size) != size ||
   3053 		     (obj->gtt_offset & (size - 1)),
   3054 		     "object 0x%08x [fenceable? %d] not 1M or pot-size (0x%08x) aligned\n",
   3055 		     obj->gtt_offset, obj->map_and_fenceable, size);
   3056 
   3057 		if (obj->tiling_mode == I915_TILING_Y && HAS_128_BYTE_Y_TILING(dev))
   3058 			tile_width = 128;
   3059 		else
   3060 			tile_width = 512;
   3061 
   3062 		/* Note: pitch better be a power of two tile widths */
   3063 		pitch_val = obj->stride / tile_width;
   3064 		pitch_val = ffs(pitch_val) - 1;
   3065 
   3066 		val = obj->gtt_offset;
   3067 		if (obj->tiling_mode == I915_TILING_Y)
   3068 			val |= 1 << I830_FENCE_TILING_Y_SHIFT;
   3069 		val |= I915_FENCE_SIZE_BITS(size);
   3070 		val |= pitch_val << I830_FENCE_PITCH_SHIFT;
   3071 		val |= I830_FENCE_REG_VALID;
   3072 	} else
   3073 		val = 0;
   3074 
   3075 	if (reg < 8)
   3076 		reg = FENCE_REG_830_0 + reg * 4;
   3077 	else
   3078 		reg = FENCE_REG_945_8 + (reg - 8) * 4;
   3079 
   3080 	I915_WRITE(reg, val);
   3081 	POSTING_READ(reg);
   3082 }
   3083 
   3084 static void i830_write_fence_reg(struct drm_device *dev, int reg,
   3085 				struct drm_i915_gem_object *obj)
   3086 {
   3087 	drm_i915_private_t *dev_priv = dev->dev_private;
   3088 	uint32_t val;
   3089 
   3090 	if (obj) {
   3091 		u32 size = obj->gtt_space->size;
   3092 		uint32_t pitch_val;
   3093 
   3094 		WARN((obj->gtt_offset & ~I830_FENCE_START_MASK) ||
   3095 		     (size & -size) != size ||
   3096 		     (obj->gtt_offset & (size - 1)),
   3097 		     "object 0x%08x not 512K or pot-size 0x%08x aligned\n",
   3098 		     obj->gtt_offset, size);
   3099 
   3100 		pitch_val = obj->stride / 128;
   3101 		pitch_val = ffs(pitch_val) - 1;
   3102 
   3103 		val = obj->gtt_offset;
   3104 		if (obj->tiling_mode == I915_TILING_Y)
   3105 			val |= 1 << I830_FENCE_TILING_Y_SHIFT;
   3106 		val |= I830_FENCE_SIZE_BITS(size);
   3107 		val |= pitch_val << I830_FENCE_PITCH_SHIFT;
   3108 		val |= I830_FENCE_REG_VALID;
   3109 	} else
   3110 		val = 0;
   3111 
   3112 	I915_WRITE(FENCE_REG_830_0 + reg * 4, val);
   3113 	POSTING_READ(FENCE_REG_830_0 + reg * 4);
   3114 }
   3115 
   3116 static void i915_gem_write_fence(struct drm_device *dev, int reg,
   3117 				 struct drm_i915_gem_object *obj)
   3118 {
   3119 	switch (INTEL_INFO(dev)->gen) {
   3120 	case 7:
   3121 	case 6: sandybridge_write_fence_reg(dev, reg, obj); break;
   3122 	case 5:
   3123 	case 4: i965_write_fence_reg(dev, reg, obj); break;
   3124 	case 3: i915_write_fence_reg(dev, reg, obj); break;
   3125 	case 2: i830_write_fence_reg(dev, reg, obj); break;
   3126 	default: break;
   3127 	}
   3128 }
   3129 
   3130 static inline int fence_number(struct drm_i915_private *dev_priv,
   3131 			       struct drm_i915_fence_reg *fence)
   3132 {
   3133 	return fence - dev_priv->fence_regs;
   3134 }
   3135 
   3136 static void i915_gem_object_update_fence(struct drm_i915_gem_object *obj,
   3137 					 struct drm_i915_fence_reg *fence,
   3138 					 bool enable)
   3139 {
   3140 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   3141 	int reg = fence_number(dev_priv, fence);
   3142 
   3143 	i915_gem_write_fence(obj->base.dev, reg, enable ? obj : NULL);
   3144 
   3145 	if (enable) {
   3146 		obj->fence_reg = reg;
   3147 		fence->obj = obj;
   3148 		list_move_tail(&fence->lru_list, &dev_priv->mm.fence_list);
   3149 	} else {
   3150 		obj->fence_reg = I915_FENCE_REG_NONE;
   3151 		fence->obj = NULL;
   3152 		list_del_init(&fence->lru_list);
   3153 	}
   3154 }
   3155 
   3156 static int
   3157 i915_gem_object_flush_fence(struct drm_i915_gem_object *obj)
   3158 {
   3159 	if (obj->last_fenced_seqno) {
   3160 		int ret = i915_wait_seqno(obj->ring, obj->last_fenced_seqno);
   3161 		if (ret)
   3162 			return ret;
   3163 
   3164 		obj->last_fenced_seqno = 0;
   3165 	}
   3166 
   3167 	/* Ensure that all CPU reads are completed before installing a fence
   3168 	 * and all writes before removing the fence.
   3169 	 */
   3170 	if (obj->base.read_domains & I915_GEM_DOMAIN_GTT)
   3171 		mb();
   3172 
   3173 	obj->fenced_gpu_access = false;
   3174 	return 0;
   3175 }
   3176 
   3177 int
   3178 i915_gem_object_put_fence(struct drm_i915_gem_object *obj)
   3179 {
   3180 	struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   3181 	int ret;
   3182 
   3183 	ret = i915_gem_object_flush_fence(obj);
   3184 	if (ret)
   3185 		return ret;
   3186 
   3187 	if (obj->fence_reg == I915_FENCE_REG_NONE)
   3188 		return 0;
   3189 
   3190 	i915_gem_object_update_fence(obj,
   3191 				     &dev_priv->fence_regs[obj->fence_reg],
   3192 				     false);
   3193 	i915_gem_object_fence_lost(obj);
   3194 
   3195 	return 0;
   3196 }
   3197 
   3198 static struct drm_i915_fence_reg *
   3199 i915_find_fence_reg(struct drm_device *dev)
   3200 {
   3201 	struct drm_i915_private *dev_priv = dev->dev_private;
   3202 	struct drm_i915_fence_reg *reg, *avail;
   3203 	int i;
   3204 
   3205 	/* First try to find a free reg */
   3206 	avail = NULL;
   3207 	for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
   3208 		reg = &dev_priv->fence_regs[i];
   3209 		if (!reg->obj)
   3210 			return reg;
   3211 
   3212 		if (!reg->pin_count)
   3213 			avail = reg;
   3214 	}
   3215 
   3216 	if (avail == NULL)
   3217 		return NULL;
   3218 
   3219 	/* None available, try to steal one or wait for a user to finish */
   3220 	list_for_each_entry(reg, &dev_priv->mm.fence_list, lru_list) {
   3221 		if (reg->pin_count)
   3222 			continue;
   3223 
   3224 		return reg;
   3225 	}
   3226 
   3227 	return NULL;
   3228 }
   3229 
   3230 /**
   3231  * i915_gem_object_get_fence - set up fencing for an object
   3232  * @obj: object to map through a fence reg
   3233  *
   3234  * When mapping objects through the GTT, userspace wants to be able to write
   3235  * to them without having to worry about swizzling if the object is tiled.
   3236  * This function walks the fence regs looking for a free one for @obj,
   3237  * stealing one if it can't find any.
   3238  *
   3239  * It then sets up the reg based on the object's properties: address, pitch
   3240  * and tiling format.
   3241  *
   3242  * For an untiled surface, this removes any existing fence.
   3243  */
   3244 int
   3245 i915_gem_object_get_fence(struct drm_i915_gem_object *obj)
   3246 {
   3247 	struct drm_device *dev = obj->base.dev;
   3248 	struct drm_i915_private *dev_priv = dev->dev_private;
   3249 	bool enable = obj->tiling_mode != I915_TILING_NONE;
   3250 	struct drm_i915_fence_reg *reg;
   3251 	int ret;
   3252 
   3253 	/* Have we updated the tiling parameters upon the object and so
   3254 	 * will need to serialise the write to the associated fence register?
   3255 	 */
   3256 	if (obj->fence_dirty) {
   3257 		ret = i915_gem_object_flush_fence(obj);
   3258 		if (ret)
   3259 			return ret;
   3260 	}
   3261 
   3262 	/* Just update our place in the LRU if our fence is getting reused. */
   3263 	if (obj->fence_reg != I915_FENCE_REG_NONE) {
   3264 		reg = &dev_priv->fence_regs[obj->fence_reg];
   3265 		if (!obj->fence_dirty) {
   3266 			list_move_tail(&reg->lru_list,
   3267 				       &dev_priv->mm.fence_list);
   3268 			return 0;
   3269 		}
   3270 	} else if (enable) {
   3271 		reg = i915_find_fence_reg(dev);
   3272 		if (reg == NULL)
   3273 			return -EDEADLK;
   3274 
   3275 		if (reg->obj) {
   3276 			struct drm_i915_gem_object *old = reg->obj;
   3277 
   3278 			ret = i915_gem_object_flush_fence(old);
   3279 			if (ret)
   3280 				return ret;
   3281 
   3282 			i915_gem_object_fence_lost(old);
   3283 		}
   3284 	} else
   3285 		return 0;
   3286 
   3287 	i915_gem_object_update_fence(obj, reg, enable);
   3288 	obj->fence_dirty = false;
   3289 
   3290 	return 0;
   3291 }
   3292 
   3293 static bool i915_gem_valid_gtt_space(struct drm_device *dev,
   3294 				     struct drm_mm_node *gtt_space,
   3295 				     unsigned long cache_level)
   3296 {
   3297 	struct drm_mm_node *other;
   3298 
   3299 	/* On non-LLC machines we have to be careful when putting differing
   3300 	 * types of snoopable memory together to avoid the prefetcher
   3301 	 * crossing memory domains and dieing.
   3302 	 */
   3303 	if (HAS_LLC(dev))
   3304 		return true;
   3305 
   3306 	if (gtt_space == NULL)
   3307 		return true;
   3308 
   3309 	if (list_empty(&gtt_space->node_list))
   3310 		return true;
   3311 
   3312 	other = list_entry(gtt_space->node_list.prev, struct drm_mm_node, node_list);
   3313 	if (other->allocated && !other->hole_follows && other->color != cache_level)
   3314 		return false;
   3315 
   3316 	other = list_entry(gtt_space->node_list.next, struct drm_mm_node, node_list);
   3317 	if (other->allocated && !gtt_space->hole_follows && other->color != cache_level)
   3318 		return false;
   3319 
   3320 	return true;
   3321 }
   3322 
   3323 static void i915_gem_verify_gtt(struct drm_device *dev)
   3324 {
   3325 #if WATCH_GTT
   3326 	struct drm_i915_private *dev_priv = dev->dev_private;
   3327 	struct drm_i915_gem_object *obj;
   3328 	int err = 0;
   3329 
   3330 	list_for_each_entry(obj, &dev_priv->mm.gtt_list, gtt_list) {
   3331 		if (obj->gtt_space == NULL) {
   3332 			printk(KERN_ERR "object found on GTT list with no space reserved\n");
   3333 			err++;
   3334 			continue;
   3335 		}
   3336 
   3337 		if (obj->cache_level != obj->gtt_space->color) {
   3338 			printk(KERN_ERR "object reserved space [%08lx, %08lx] with wrong color, cache_level=%x, color=%lx\n",
   3339 			       obj->gtt_space->start,
   3340 			       obj->gtt_space->start + obj->gtt_space->size,
   3341 			       obj->cache_level,
   3342 			       obj->gtt_space->color);
   3343 			err++;
   3344 			continue;
   3345 		}
   3346 
   3347 		if (!i915_gem_valid_gtt_space(dev,
   3348 					      obj->gtt_space,
   3349 					      obj->cache_level)) {
   3350 			printk(KERN_ERR "invalid GTT space found at [%08lx, %08lx] - color=%x\n",
   3351 			       obj->gtt_space->start,
   3352 			       obj->gtt_space->start + obj->gtt_space->size,
   3353 			       obj->cache_level);
   3354 			err++;
   3355 			continue;
   3356 		}
   3357 	}
   3358 
   3359 	WARN_ON(err);
   3360 #endif
   3361 }
   3362 
   3363 /**
   3364  * Finds free space in the GTT aperture and binds the object there.
   3365  */
   3366 static int
   3367 i915_gem_object_bind_to_gtt(struct drm_i915_gem_object *obj,
   3368 			    unsigned alignment,
   3369 			    bool map_and_fenceable,
   3370 			    bool nonblocking)
   3371 {
   3372 	struct drm_device *dev = obj->base.dev;
   3373 	drm_i915_private_t *dev_priv = dev->dev_private;
   3374 	struct drm_mm_node *node;
   3375 	u32 size, fence_size, fence_alignment, unfenced_alignment;
   3376 	bool mappable, fenceable;
   3377 	int ret;
   3378 
   3379 	if (obj->madv != I915_MADV_WILLNEED) {
   3380 		DRM_ERROR("Attempting to bind a purgeable object\n");
   3381 		return -EINVAL;
   3382 	}
   3383 
   3384 	fence_size = i915_gem_get_gtt_size(dev,
   3385 					   obj->base.size,
   3386 					   obj->tiling_mode);
   3387 	fence_alignment = i915_gem_get_gtt_alignment(dev,
   3388 						     obj->base.size,
   3389 						     obj->tiling_mode);
   3390 	unfenced_alignment =
   3391 		i915_gem_get_unfenced_gtt_alignment(dev,
   3392 						    obj->base.size,
   3393 						    obj->tiling_mode);
   3394 
   3395 	if (alignment == 0)
   3396 		alignment = map_and_fenceable ? fence_alignment :
   3397 						unfenced_alignment;
   3398 	if (map_and_fenceable && alignment & (fence_alignment - 1)) {
   3399 		DRM_ERROR("Invalid object alignment requested %u\n", alignment);
   3400 		return -EINVAL;
   3401 	}
   3402 
   3403 	size = map_and_fenceable ? fence_size : obj->base.size;
   3404 
   3405 	/* If the object is bigger than the entire aperture, reject it early
   3406 	 * before evicting everything in a vain attempt to find space.
   3407 	 */
   3408 	if (obj->base.size >
   3409 	    (map_and_fenceable ? dev_priv->mm.gtt_mappable_end : dev_priv->mm.gtt_total)) {
   3410 		DRM_ERROR("Attempting to bind an object larger than the aperture\n");
   3411 		return -E2BIG;
   3412 	}
   3413 
   3414 	ret = i915_gem_object_get_pages(obj);
   3415 	if (ret)
   3416 		return ret;
   3417 
   3418 	i915_gem_object_pin_pages(obj);
   3419 
   3420 	node = kzalloc(sizeof(*node), GFP_KERNEL);
   3421 	if (node == NULL) {
   3422 		i915_gem_object_unpin_pages(obj);
   3423 		return -ENOMEM;
   3424 	}
   3425 
   3426  search_free:
   3427 	if (map_and_fenceable)
   3428 		ret = drm_mm_insert_node_in_range_generic(&dev_priv->mm.gtt_space, node,
   3429 							  size, alignment, obj->cache_level,
   3430 							  0, dev_priv->mm.gtt_mappable_end);
   3431 	else
   3432 		ret = drm_mm_insert_node_generic(&dev_priv->mm.gtt_space, node,
   3433 						 size, alignment, obj->cache_level);
   3434 	if (ret) {
   3435 		ret = i915_gem_evict_something(dev, size, alignment,
   3436 					       obj->cache_level,
   3437 					       map_and_fenceable,
   3438 					       nonblocking);
   3439 		if (ret == 0)
   3440 			goto search_free;
   3441 
   3442 		i915_gem_object_unpin_pages(obj);
   3443 		kfree(node);
   3444 		return ret;
   3445 	}
   3446 	if (WARN_ON(!i915_gem_valid_gtt_space(dev, node, obj->cache_level))) {
   3447 		i915_gem_object_unpin_pages(obj);
   3448 		drm_mm_put_block(node);
   3449 		return -EINVAL;
   3450 	}
   3451 
   3452 	ret = i915_gem_gtt_prepare_object(obj);
   3453 	if (ret) {
   3454 		i915_gem_object_unpin_pages(obj);
   3455 		drm_mm_put_block(node);
   3456 		return ret;
   3457 	}
   3458 
   3459 	list_move_tail(&obj->gtt_list, &dev_priv->mm.bound_list);
   3460 	list_add_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
   3461 
   3462 	obj->gtt_space = node;
   3463 	obj->gtt_offset = node->start;
   3464 
   3465 	fenceable =
   3466 		node->size == fence_size &&
   3467 		(node->start & (fence_alignment - 1)) == 0;
   3468 
   3469 	mappable =
   3470 		obj->gtt_offset + obj->base.size <= dev_priv->mm.gtt_mappable_end;
   3471 
   3472 	obj->map_and_fenceable = mappable && fenceable;
   3473 
   3474 	i915_gem_object_unpin_pages(obj);
   3475 	trace_i915_gem_object_bind(obj, map_and_fenceable);
   3476 	i915_gem_verify_gtt(dev);
   3477 	return 0;
   3478 }
   3479 
   3480 void
   3481 i915_gem_clflush_object(struct drm_i915_gem_object *obj)
   3482 {
   3483 	/* If we don't have a page list set up, then we're not pinned
   3484 	 * to GPU, and we can ignore the cache flush because it'll happen
   3485 	 * again at bind time.
   3486 	 */
   3487 	if (obj->pages == NULL)
   3488 		return;
   3489 
   3490 	/* If the GPU is snooping the contents of the CPU cache,
   3491 	 * we do not need to manually clear the CPU cache lines.  However,
   3492 	 * the caches are only snooped when the render cache is
   3493 	 * flushed/invalidated.  As we always have to emit invalidations
   3494 	 * and flushes when moving into and out of the RENDER domain, correct
   3495 	 * snooping behaviour occurs naturally as the result of our domain
   3496 	 * tracking.
   3497 	 */
   3498 	if (obj->cache_level != I915_CACHE_NONE)
   3499 		return;
   3500 
   3501 	trace_i915_gem_object_clflush(obj);
   3502 
   3503 #ifdef __NetBSD__
   3504 	drm_clflush_pglist(&obj->igo_pageq);
   3505 #else
   3506 	drm_clflush_sg(obj->pages);
   3507 #endif
   3508 }
   3509 
   3510 /** Flushes the GTT write domain for the object if it's dirty. */
   3511 static void
   3512 i915_gem_object_flush_gtt_write_domain(struct drm_i915_gem_object *obj)
   3513 {
   3514 	uint32_t old_write_domain;
   3515 
   3516 	if (obj->base.write_domain != I915_GEM_DOMAIN_GTT)
   3517 		return;
   3518 
   3519 	/* No actual flushing is required for the GTT write domain.  Writes
   3520 	 * to it immediately go to main memory as far as we know, so there's
   3521 	 * no chipset flush.  It also doesn't land in render cache.
   3522 	 *
   3523 	 * However, we do have to enforce the order so that all writes through
   3524 	 * the GTT land before any writes to the device, such as updates to
   3525 	 * the GATT itself.
   3526 	 */
   3527 	wmb();
   3528 
   3529 	old_write_domain = obj->base.write_domain;
   3530 	obj->base.write_domain = 0;
   3531 
   3532 	trace_i915_gem_object_change_domain(obj,
   3533 					    obj->base.read_domains,
   3534 					    old_write_domain);
   3535 }
   3536 
   3537 /** Flushes the CPU write domain for the object if it's dirty. */
   3538 static void
   3539 i915_gem_object_flush_cpu_write_domain(struct drm_i915_gem_object *obj)
   3540 {
   3541 	uint32_t old_write_domain;
   3542 
   3543 	if (obj->base.write_domain != I915_GEM_DOMAIN_CPU)
   3544 		return;
   3545 
   3546 	i915_gem_clflush_object(obj);
   3547 	i915_gem_chipset_flush(obj->base.dev);
   3548 	old_write_domain = obj->base.write_domain;
   3549 	obj->base.write_domain = 0;
   3550 
   3551 	trace_i915_gem_object_change_domain(obj,
   3552 					    obj->base.read_domains,
   3553 					    old_write_domain);
   3554 }
   3555 
   3556 /**
   3557  * Moves a single object to the GTT read, and possibly write domain.
   3558  *
   3559  * This function returns when the move is complete, including waiting on
   3560  * flushes to occur.
   3561  */
   3562 int
   3563 i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
   3564 {
   3565 	drm_i915_private_t *dev_priv = obj->base.dev->dev_private;
   3566 	uint32_t old_write_domain, old_read_domains;
   3567 	int ret;
   3568 
   3569 	/* Not valid to be called on unbound objects. */
   3570 	if (obj->gtt_space == NULL)
   3571 		return -EINVAL;
   3572 
   3573 	if (obj->base.write_domain == I915_GEM_DOMAIN_GTT)
   3574 		return 0;
   3575 
   3576 	ret = i915_gem_object_wait_rendering(obj, !write);
   3577 	if (ret)
   3578 		return ret;
   3579 
   3580 	i915_gem_object_flush_cpu_write_domain(obj);
   3581 
   3582 	old_write_domain = obj->base.write_domain;
   3583 	old_read_domains = obj->base.read_domains;
   3584 
   3585 	/* It should now be out of any other write domains, and we can update
   3586 	 * the domain values for our changes.
   3587 	 */
   3588 	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
   3589 	obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
   3590 	if (write) {
   3591 		obj->base.read_domains = I915_GEM_DOMAIN_GTT;
   3592 		obj->base.write_domain = I915_GEM_DOMAIN_GTT;
   3593 		obj->dirty = 1;
   3594 	}
   3595 
   3596 	trace_i915_gem_object_change_domain(obj,
   3597 					    old_read_domains,
   3598 					    old_write_domain);
   3599 
   3600 	/* And bump the LRU for this access */
   3601 	if (i915_gem_object_is_inactive(obj))
   3602 		list_move_tail(&obj->mm_list, &dev_priv->mm.inactive_list);
   3603 
   3604 	return 0;
   3605 }
   3606 
   3607 int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
   3608 				    enum i915_cache_level cache_level)
   3609 {
   3610 	struct drm_device *dev = obj->base.dev;
   3611 	drm_i915_private_t *dev_priv = dev->dev_private;
   3612 	int ret;
   3613 
   3614 	if (obj->cache_level == cache_level)
   3615 		return 0;
   3616 
   3617 	if (obj->pin_count) {
   3618 		DRM_DEBUG("can not change the cache level of pinned objects\n");
   3619 		return -EBUSY;
   3620 	}
   3621 
   3622 	if (!i915_gem_valid_gtt_space(dev, obj->gtt_space, cache_level)) {
   3623 		ret = i915_gem_object_unbind(obj);
   3624 		if (ret)
   3625 			return ret;
   3626 	}
   3627 
   3628 	if (obj->gtt_space) {
   3629 		ret = i915_gem_object_finish_gpu(obj);
   3630 		if (ret)
   3631 			return ret;
   3632 
   3633 		i915_gem_object_finish_gtt(obj);
   3634 
   3635 		/* Before SandyBridge, you could not use tiling or fence
   3636 		 * registers with snooped memory, so relinquish any fences
   3637 		 * currently pointing to our region in the aperture.
   3638 		 */
   3639 		if (INTEL_INFO(dev)->gen < 6) {
   3640 			ret = i915_gem_object_put_fence(obj);
   3641 			if (ret)
   3642 				return ret;
   3643 		}
   3644 
   3645 		if (obj->has_global_gtt_mapping)
   3646 			i915_gem_gtt_bind_object(obj, cache_level);
   3647 		if (obj->has_aliasing_ppgtt_mapping)
   3648 			i915_ppgtt_bind_object(dev_priv->mm.aliasing_ppgtt,
   3649 					       obj, cache_level);
   3650 
   3651 		obj->gtt_space->color = cache_level;
   3652 	}
   3653 
   3654 	if (cache_level == I915_CACHE_NONE) {
   3655 		u32 old_read_domains, old_write_domain;
   3656 
   3657 		/* If we're coming from LLC cached, then we haven't
   3658 		 * actually been tracking whether the data is in the
   3659 		 * CPU cache or not, since we only allow one bit set
   3660 		 * in obj->write_domain and have been skipping the clflushes.
   3661 		 * Just set it to the CPU cache for now.
   3662 		 */
   3663 		WARN_ON(obj->base.write_domain & ~I915_GEM_DOMAIN_CPU);
   3664 		WARN_ON(obj->base.read_domains & ~I915_GEM_DOMAIN_CPU);
   3665 
   3666 		old_read_domains = obj->base.read_domains;
   3667 		old_write_domain = obj->base.write_domain;
   3668 
   3669 		obj->base.read_domains = I915_GEM_DOMAIN_CPU;
   3670 		obj->base.write_domain = I915_GEM_DOMAIN_CPU;
   3671 
   3672 		trace_i915_gem_object_change_domain(obj,
   3673 						    old_read_domains,
   3674 						    old_write_domain);
   3675 	}
   3676 
   3677 	obj->cache_level = cache_level;
   3678 	i915_gem_verify_gtt(dev);
   3679 	return 0;
   3680 }
   3681 
   3682 int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
   3683 			       struct drm_file *file)
   3684 {
   3685 	struct drm_i915_gem_caching *args = data;
   3686 	struct drm_i915_gem_object *obj;
   3687 	int ret;
   3688 
   3689 	ret = i915_mutex_lock_interruptible(dev);
   3690 	if (ret)
   3691 		return ret;
   3692 
   3693 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   3694 	if (&obj->base == NULL) {
   3695 		ret = -ENOENT;
   3696 		goto unlock;
   3697 	}
   3698 
   3699 	args->caching = obj->cache_level != I915_CACHE_NONE;
   3700 
   3701 	drm_gem_object_unreference(&obj->base);
   3702 unlock:
   3703 	mutex_unlock(&dev->struct_mutex);
   3704 	return ret;
   3705 }
   3706 
   3707 int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
   3708 			       struct drm_file *file)
   3709 {
   3710 	struct drm_i915_gem_caching *args = data;
   3711 	struct drm_i915_gem_object *obj;
   3712 	enum i915_cache_level level;
   3713 	int ret;
   3714 
   3715 	switch (args->caching) {
   3716 	case I915_CACHING_NONE:
   3717 		level = I915_CACHE_NONE;
   3718 		break;
   3719 	case I915_CACHING_CACHED:
   3720 		level = I915_CACHE_LLC;
   3721 		break;
   3722 	default:
   3723 		return -EINVAL;
   3724 	}
   3725 
   3726 	ret = i915_mutex_lock_interruptible(dev);
   3727 	if (ret)
   3728 		return ret;
   3729 
   3730 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   3731 	if (&obj->base == NULL) {
   3732 		ret = -ENOENT;
   3733 		goto unlock;
   3734 	}
   3735 
   3736 	ret = i915_gem_object_set_cache_level(obj, level);
   3737 
   3738 	drm_gem_object_unreference(&obj->base);
   3739 unlock:
   3740 	mutex_unlock(&dev->struct_mutex);
   3741 	return ret;
   3742 }
   3743 
   3744 /*
   3745  * Prepare buffer for display plane (scanout, cursors, etc).
   3746  * Can be called from an uninterruptible phase (modesetting) and allows
   3747  * any flushes to be pipelined (for pageflips).
   3748  */
   3749 int
   3750 i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
   3751 				     u32 alignment,
   3752 				     struct intel_ring_buffer *pipelined)
   3753 {
   3754 	u32 old_read_domains, old_write_domain;
   3755 	int ret;
   3756 
   3757 	if (pipelined != obj->ring) {
   3758 		ret = i915_gem_object_sync(obj, pipelined);
   3759 		if (ret)
   3760 			return ret;
   3761 	}
   3762 
   3763 	/* The display engine is not coherent with the LLC cache on gen6.  As
   3764 	 * a result, we make sure that the pinning that is about to occur is
   3765 	 * done with uncached PTEs. This is lowest common denominator for all
   3766 	 * chipsets.
   3767 	 *
   3768 	 * However for gen6+, we could do better by using the GFDT bit instead
   3769 	 * of uncaching, which would allow us to flush all the LLC-cached data
   3770 	 * with that bit in the PTE to main memory with just one PIPE_CONTROL.
   3771 	 */
   3772 	ret = i915_gem_object_set_cache_level(obj, I915_CACHE_NONE);
   3773 	if (ret)
   3774 		return ret;
   3775 
   3776 	/* As the user may map the buffer once pinned in the display plane
   3777 	 * (e.g. libkms for the bootup splash), we have to ensure that we
   3778 	 * always use map_and_fenceable for all scanout buffers.
   3779 	 */
   3780 	ret = i915_gem_object_pin(obj, alignment, true, false);
   3781 	if (ret)
   3782 		return ret;
   3783 
   3784 	i915_gem_object_flush_cpu_write_domain(obj);
   3785 
   3786 	old_write_domain = obj->base.write_domain;
   3787 	old_read_domains = obj->base.read_domains;
   3788 
   3789 	/* It should now be out of any other write domains, and we can update
   3790 	 * the domain values for our changes.
   3791 	 */
   3792 	obj->base.write_domain = 0;
   3793 	obj->base.read_domains |= I915_GEM_DOMAIN_GTT;
   3794 
   3795 	trace_i915_gem_object_change_domain(obj,
   3796 					    old_read_domains,
   3797 					    old_write_domain);
   3798 
   3799 	return 0;
   3800 }
   3801 
   3802 int
   3803 i915_gem_object_finish_gpu(struct drm_i915_gem_object *obj)
   3804 {
   3805 	int ret;
   3806 
   3807 	if ((obj->base.read_domains & I915_GEM_GPU_DOMAINS) == 0)
   3808 		return 0;
   3809 
   3810 	ret = i915_gem_object_wait_rendering(obj, false);
   3811 	if (ret)
   3812 		return ret;
   3813 
   3814 	/* Ensure that we invalidate the GPU's caches and TLBs. */
   3815 	obj->base.read_domains &= ~I915_GEM_GPU_DOMAINS;
   3816 	return 0;
   3817 }
   3818 
   3819 /**
   3820  * Moves a single object to the CPU read, and possibly write domain.
   3821  *
   3822  * This function returns when the move is complete, including waiting on
   3823  * flushes to occur.
   3824  */
   3825 int
   3826 i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
   3827 {
   3828 	uint32_t old_write_domain, old_read_domains;
   3829 	int ret;
   3830 
   3831 	if (obj->base.write_domain == I915_GEM_DOMAIN_CPU)
   3832 		return 0;
   3833 
   3834 	ret = i915_gem_object_wait_rendering(obj, !write);
   3835 	if (ret)
   3836 		return ret;
   3837 
   3838 	i915_gem_object_flush_gtt_write_domain(obj);
   3839 
   3840 	old_write_domain = obj->base.write_domain;
   3841 	old_read_domains = obj->base.read_domains;
   3842 
   3843 	/* Flush the CPU cache if it's still invalid. */
   3844 	if ((obj->base.read_domains & I915_GEM_DOMAIN_CPU) == 0) {
   3845 		i915_gem_clflush_object(obj);
   3846 
   3847 		obj->base.read_domains |= I915_GEM_DOMAIN_CPU;
   3848 	}
   3849 
   3850 	/* It should now be out of any other write domains, and we can update
   3851 	 * the domain values for our changes.
   3852 	 */
   3853 	BUG_ON((obj->base.write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
   3854 
   3855 	/* If we're writing through the CPU, then the GPU read domains will
   3856 	 * need to be invalidated at next use.
   3857 	 */
   3858 	if (write) {
   3859 		obj->base.read_domains = I915_GEM_DOMAIN_CPU;
   3860 		obj->base.write_domain = I915_GEM_DOMAIN_CPU;
   3861 	}
   3862 
   3863 	trace_i915_gem_object_change_domain(obj,
   3864 					    old_read_domains,
   3865 					    old_write_domain);
   3866 
   3867 	return 0;
   3868 }
   3869 
   3870 /* Throttle our rendering by waiting until the ring has completed our requests
   3871  * emitted over 20 msec ago.
   3872  *
   3873  * Note that if we were to use the current jiffies each time around the loop,
   3874  * we wouldn't escape the function with any frames outstanding if the time to
   3875  * render a frame was over 20ms.
   3876  *
   3877  * This should get us reasonable parallelism between CPU and GPU but also
   3878  * relatively low latency when blocking on a particular request to finish.
   3879  */
   3880 static int
   3881 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
   3882 {
   3883 	struct drm_i915_private *dev_priv = dev->dev_private;
   3884 	struct drm_i915_file_private *file_priv = file->driver_priv;
   3885 	unsigned long recent_enough = jiffies - msecs_to_jiffies(20);
   3886 	struct drm_i915_gem_request *request;
   3887 	struct intel_ring_buffer *ring = NULL;
   3888 	u32 seqno = 0;
   3889 	int ret;
   3890 
   3891 	if (atomic_read(&dev_priv->mm.wedged))
   3892 		return -EIO;
   3893 
   3894 	spin_lock(&file_priv->mm.lock);
   3895 	list_for_each_entry(request, &file_priv->mm.request_list, client_list) {
   3896 		if (time_after_eq(request->emitted_jiffies, recent_enough))
   3897 			break;
   3898 
   3899 		ring = request->ring;
   3900 		seqno = request->seqno;
   3901 	}
   3902 	spin_unlock(&file_priv->mm.lock);
   3903 
   3904 	if (seqno == 0)
   3905 		return 0;
   3906 
   3907 	ret = __wait_seqno(ring, seqno, true, NULL);
   3908 	if (ret == 0)
   3909 		queue_delayed_work(dev_priv->wq, &dev_priv->mm.retire_work, 0);
   3910 
   3911 	return ret;
   3912 }
   3913 
   3914 int
   3915 i915_gem_object_pin(struct drm_i915_gem_object *obj,
   3916 		    uint32_t alignment,
   3917 		    bool map_and_fenceable,
   3918 		    bool nonblocking)
   3919 {
   3920 	int ret;
   3921 
   3922 	if (WARN_ON(obj->pin_count == DRM_I915_GEM_OBJECT_MAX_PIN_COUNT))
   3923 		return -EBUSY;
   3924 
   3925 	if (obj->gtt_space != NULL) {
   3926 		if ((alignment && obj->gtt_offset & (alignment - 1)) ||
   3927 		    (map_and_fenceable && !obj->map_and_fenceable)) {
   3928 			WARN(obj->pin_count,
   3929 			     "bo is already pinned with incorrect alignment:"
   3930 			     " offset=%x, req.alignment=%x, req.map_and_fenceable=%d,"
   3931 			     " obj->map_and_fenceable=%d\n",
   3932 			     obj->gtt_offset, alignment,
   3933 			     map_and_fenceable,
   3934 			     obj->map_and_fenceable);
   3935 			ret = i915_gem_object_unbind(obj);
   3936 			if (ret)
   3937 				return ret;
   3938 		}
   3939 	}
   3940 
   3941 	if (obj->gtt_space == NULL) {
   3942 		struct drm_i915_private *dev_priv = obj->base.dev->dev_private;
   3943 
   3944 		ret = i915_gem_object_bind_to_gtt(obj, alignment,
   3945 						  map_and_fenceable,
   3946 						  nonblocking);
   3947 		if (ret)
   3948 			return ret;
   3949 
   3950 		if (!dev_priv->mm.aliasing_ppgtt)
   3951 			i915_gem_gtt_bind_object(obj, obj->cache_level);
   3952 	}
   3953 
   3954 	if (!obj->has_global_gtt_mapping && map_and_fenceable)
   3955 		i915_gem_gtt_bind_object(obj, obj->cache_level);
   3956 
   3957 	obj->pin_count++;
   3958 	obj->pin_mappable |= map_and_fenceable;
   3959 
   3960 	return 0;
   3961 }
   3962 
   3963 void
   3964 i915_gem_object_unpin(struct drm_i915_gem_object *obj)
   3965 {
   3966 	BUG_ON(obj->pin_count == 0);
   3967 	BUG_ON(obj->gtt_space == NULL);
   3968 
   3969 	if (--obj->pin_count == 0)
   3970 		obj->pin_mappable = false;
   3971 }
   3972 
   3973 int
   3974 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
   3975 		   struct drm_file *file)
   3976 {
   3977 	struct drm_i915_gem_pin *args = data;
   3978 	struct drm_i915_gem_object *obj;
   3979 	int ret;
   3980 
   3981 	ret = i915_mutex_lock_interruptible(dev);
   3982 	if (ret)
   3983 		return ret;
   3984 
   3985 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   3986 	if (&obj->base == NULL) {
   3987 		ret = -ENOENT;
   3988 		goto unlock;
   3989 	}
   3990 
   3991 	if (obj->madv != I915_MADV_WILLNEED) {
   3992 		DRM_ERROR("Attempting to pin a purgeable buffer\n");
   3993 		ret = -EINVAL;
   3994 		goto out;
   3995 	}
   3996 
   3997 	if (obj->pin_filp != NULL && obj->pin_filp != file) {
   3998 		DRM_ERROR("Already pinned in i915_gem_pin_ioctl(): %d\n",
   3999 			  args->handle);
   4000 		ret = -EINVAL;
   4001 		goto out;
   4002 	}
   4003 
   4004 	if (obj->user_pin_count == 0) {
   4005 		ret = i915_gem_object_pin(obj, args->alignment, true, false);
   4006 		if (ret)
   4007 			goto out;
   4008 	}
   4009 
   4010 	obj->user_pin_count++;
   4011 	obj->pin_filp = file;
   4012 
   4013 	/* XXX - flush the CPU caches for pinned objects
   4014 	 * as the X server doesn't manage domains yet
   4015 	 */
   4016 	i915_gem_object_flush_cpu_write_domain(obj);
   4017 	args->offset = obj->gtt_offset;
   4018 out:
   4019 	drm_gem_object_unreference(&obj->base);
   4020 unlock:
   4021 	mutex_unlock(&dev->struct_mutex);
   4022 	return ret;
   4023 }
   4024 
   4025 int
   4026 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
   4027 		     struct drm_file *file)
   4028 {
   4029 	struct drm_i915_gem_pin *args = data;
   4030 	struct drm_i915_gem_object *obj;
   4031 	int ret;
   4032 
   4033 	ret = i915_mutex_lock_interruptible(dev);
   4034 	if (ret)
   4035 		return ret;
   4036 
   4037 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   4038 	if (&obj->base == NULL) {
   4039 		ret = -ENOENT;
   4040 		goto unlock;
   4041 	}
   4042 
   4043 	if (obj->pin_filp != file) {
   4044 		DRM_ERROR("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
   4045 			  args->handle);
   4046 		ret = -EINVAL;
   4047 		goto out;
   4048 	}
   4049 	obj->user_pin_count--;
   4050 	if (obj->user_pin_count == 0) {
   4051 		obj->pin_filp = NULL;
   4052 		i915_gem_object_unpin(obj);
   4053 	}
   4054 
   4055 out:
   4056 	drm_gem_object_unreference(&obj->base);
   4057 unlock:
   4058 	mutex_unlock(&dev->struct_mutex);
   4059 	return ret;
   4060 }
   4061 
   4062 int
   4063 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
   4064 		    struct drm_file *file)
   4065 {
   4066 	struct drm_i915_gem_busy *args = data;
   4067 	struct drm_i915_gem_object *obj;
   4068 	int ret;
   4069 
   4070 	ret = i915_mutex_lock_interruptible(dev);
   4071 	if (ret)
   4072 		return ret;
   4073 
   4074 	obj = to_intel_bo(drm_gem_object_lookup(dev, file, args->handle));
   4075 	if (&obj->base == NULL) {
   4076 		ret = -ENOENT;
   4077 		goto unlock;
   4078 	}
   4079 
   4080 	/* Count all active objects as busy, even if they are currently not used
   4081 	 * by the gpu. Users of this interface expect objects to eventually
   4082 	 * become non-busy without any further actions, therefore emit any
   4083 	 * necessary flushes here.
   4084 	 */
   4085 	ret = i915_gem_object_flush_active(obj);
   4086 
   4087 	args->busy = obj->active;
   4088 	if (obj->ring) {
   4089 		BUILD_BUG_ON(I915_NUM_RINGS > 16);
   4090 		args->busy |= intel_ring_flag(obj->ring) << 16;
   4091 	}
   4092 
   4093 	drm_gem_object_unreference(&obj->base);
   4094 unlock:
   4095 	mutex_unlock(&dev->struct_mutex);
   4096 	return ret;
   4097 }
   4098 
   4099 int
   4100 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
   4101 			struct drm_file *file_priv)
   4102 {
   4103 	return i915_gem_ring_throttle(dev, file_priv);
   4104 }
   4105 
   4106 int
   4107 i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
   4108 		       struct drm_file *file_priv)
   4109 {
   4110 	struct drm_i915_gem_madvise *args = data;
   4111 	struct drm_i915_gem_object *obj;
   4112 	int ret;
   4113 
   4114 	switch (args->madv) {
   4115 	case I915_MADV_DONTNEED:
   4116 	case I915_MADV_WILLNEED:
   4117 	    break;
   4118 	default:
   4119 	    return -EINVAL;
   4120 	}
   4121 
   4122 	ret = i915_mutex_lock_interruptible(dev);
   4123 	if (ret)
   4124 		return ret;
   4125 
   4126 	obj = to_intel_bo(drm_gem_object_lookup(dev, file_priv, args->handle));
   4127 	if (&obj->base == NULL) {
   4128 		ret = -ENOENT;
   4129 		goto unlock;
   4130 	}
   4131 
   4132 	if (obj->pin_count) {
   4133 		ret = -EINVAL;
   4134 		goto out;
   4135 	}
   4136 
   4137 	if (obj->madv != __I915_MADV_PURGED)
   4138 		obj->madv = args->madv;
   4139 
   4140 	/* if the object is no longer attached, discard its backing storage */
   4141 	if (i915_gem_object_is_purgeable(obj) && obj->pages == NULL)
   4142 		i915_gem_object_truncate(obj);
   4143 
   4144 	args->retained = obj->madv != __I915_MADV_PURGED;
   4145 
   4146 out:
   4147 	drm_gem_object_unreference(&obj->base);
   4148 unlock:
   4149 	mutex_unlock(&dev->struct_mutex);
   4150 	return ret;
   4151 }
   4152 
   4153 void i915_gem_object_init(struct drm_i915_gem_object *obj,
   4154 			  const struct drm_i915_gem_object_ops *ops)
   4155 {
   4156 	INIT_LIST_HEAD(&obj->mm_list);
   4157 	INIT_LIST_HEAD(&obj->gtt_list);
   4158 	INIT_LIST_HEAD(&obj->ring_list);
   4159 	INIT_LIST_HEAD(&obj->exec_list);
   4160 
   4161 	obj->ops = ops;
   4162 
   4163 	obj->fence_reg = I915_FENCE_REG_NONE;
   4164 	obj->madv = I915_MADV_WILLNEED;
   4165 	/* Avoid an unnecessary call to unbind on the first bind. */
   4166 	obj->map_and_fenceable = true;
   4167 
   4168 	i915_gem_info_add_obj(obj->base.dev->dev_private, obj->base.size);
   4169 }
   4170 
   4171 static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
   4172 	.get_pages = i915_gem_object_get_pages_gtt,
   4173 	.put_pages = i915_gem_object_put_pages_gtt,
   4174 };
   4175 
   4176 struct drm_i915_gem_object *i915_gem_alloc_object(struct drm_device *dev,
   4177 						  size_t size)
   4178 {
   4179 	struct drm_i915_gem_object *obj;
   4180 #ifndef __NetBSD__		/* XXX >32bit dma?  */
   4181 	struct address_space *mapping;
   4182 	u32 mask;
   4183 #endif
   4184 
   4185 	obj = kzalloc(sizeof(*obj), GFP_KERNEL);
   4186 	if (obj == NULL)
   4187 		return NULL;
   4188 
   4189 	if (drm_gem_object_init(dev, &obj->base, size) != 0) {
   4190 		kfree(obj);
   4191 		return NULL;
   4192 	}
   4193 
   4194 #ifndef __NetBSD__		/* XXX >32bit dma?  */
   4195 	mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
   4196 	if (IS_CRESTLINE(dev) || IS_BROADWATER(dev)) {
   4197 		/* 965gm cannot relocate objects above 4GiB. */
   4198 		mask &= ~__GFP_HIGHMEM;
   4199 		mask |= __GFP_DMA32;
   4200 	}
   4201 
   4202 	mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
   4203 	mapping_set_gfp_mask(mapping, mask);
   4204 #endif
   4205 
   4206 	i915_gem_object_init(obj, &i915_gem_object_ops);
   4207 
   4208 	obj->base.write_domain = I915_GEM_DOMAIN_CPU;
   4209 	obj->base.read_domains = I915_GEM_DOMAIN_CPU;
   4210 
   4211 	if (HAS_LLC(dev)) {
   4212 		/* On some devices, we can have the GPU use the LLC (the CPU
   4213 		 * cache) for about a 10% performance improvement
   4214 		 * compared to uncached.  Graphics requests other than
   4215 		 * display scanout are coherent with the CPU in
   4216 		 * accessing this cache.  This means in this mode we
   4217 		 * don't need to clflush on the CPU side, and on the
   4218 		 * GPU side we only need to flush internal caches to
   4219 		 * get data visible to the CPU.
   4220 		 *
   4221 		 * However, we maintain the display planes as UC, and so
   4222 		 * need to rebind when first used as such.
   4223 		 */
   4224 		obj->cache_level = I915_CACHE_LLC;
   4225 	} else
   4226 		obj->cache_level = I915_CACHE_NONE;
   4227 
   4228 	return obj;
   4229 }
   4230 
   4231 int i915_gem_init_object(struct drm_gem_object *obj)
   4232 {
   4233 	BUG();
   4234 
   4235 	return 0;
   4236 }
   4237 
   4238 void i915_gem_free_object(struct drm_gem_object *gem_obj)
   4239 {
   4240 	struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
   4241 	struct drm_device *dev = obj->base.dev;
   4242 	drm_i915_private_t *dev_priv = dev->dev_private;
   4243 
   4244 	trace_i915_gem_object_destroy(obj);
   4245 
   4246 	if (obj->phys_obj)
   4247 		i915_gem_detach_phys_object(dev, obj);
   4248 
   4249 	obj->pin_count = 0;
   4250 	if (WARN_ON(i915_gem_object_unbind(obj) == -ERESTARTSYS)) {
   4251 		bool was_interruptible;
   4252 
   4253 		was_interruptible = dev_priv->mm.interruptible;
   4254 		dev_priv->mm.interruptible = false;
   4255 
   4256 		WARN_ON(i915_gem_object_unbind(obj));
   4257 
   4258 		dev_priv->mm.interruptible = was_interruptible;
   4259 	}
   4260 
   4261 	obj->pages_pin_count = 0;
   4262 	i915_gem_object_put_pages(obj);
   4263 	i915_gem_object_free_mmap_offset(obj);
   4264 
   4265 	BUG_ON(obj->pages);
   4266 
   4267 #ifndef __NetBSD__		/* XXX drm prime */
   4268 	if (obj->base.import_attach)
   4269 		drm_prime_gem_destroy(&obj->base, NULL);
   4270 #endif
   4271 
   4272 	drm_gem_object_release(&obj->base);
   4273 	i915_gem_info_remove_obj(dev_priv, obj->base.size);
   4274 
   4275 	kfree(obj->bit_17);
   4276 	kfree(obj);
   4277 }
   4278 
   4279 int
   4280 i915_gem_idle(struct drm_device *dev)
   4281 {
   4282 	drm_i915_private_t *dev_priv = dev->dev_private;
   4283 	int ret;
   4284 
   4285 	mutex_lock(&dev->struct_mutex);
   4286 
   4287 	if (dev_priv->mm.suspended) {
   4288 		mutex_unlock(&dev->struct_mutex);
   4289 		return 0;
   4290 	}
   4291 
   4292 	ret = i915_gpu_idle(dev);
   4293 	if (ret) {
   4294 		mutex_unlock(&dev->struct_mutex);
   4295 		return ret;
   4296 	}
   4297 	i915_gem_retire_requests(dev);
   4298 
   4299 	/* Under UMS, be paranoid and evict. */
   4300 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
   4301 		i915_gem_evict_everything(dev);
   4302 
   4303 	i915_gem_reset_fences(dev);
   4304 
   4305 	/* Hack!  Don't let anybody do execbuf while we don't control the chip.
   4306 	 * We need to replace this with a semaphore, or something.
   4307 	 * And not confound mm.suspended!
   4308 	 */
   4309 	dev_priv->mm.suspended = 1;
   4310 	del_timer_sync(&dev_priv->hangcheck_timer);
   4311 
   4312 	i915_kernel_lost_context(dev);
   4313 	i915_gem_cleanup_ringbuffer(dev);
   4314 
   4315 	mutex_unlock(&dev->struct_mutex);
   4316 
   4317 	/* Cancel the retire work handler, which should be idle now. */
   4318 	cancel_delayed_work_sync(&dev_priv->mm.retire_work);
   4319 
   4320 	return 0;
   4321 }
   4322 
   4323 void i915_gem_l3_remap(struct drm_device *dev)
   4324 {
   4325 	drm_i915_private_t *dev_priv = dev->dev_private;
   4326 	u32 misccpctl;
   4327 	int i;
   4328 
   4329 	if (!IS_IVYBRIDGE(dev))
   4330 		return;
   4331 
   4332 	if (!dev_priv->l3_parity.remap_info)
   4333 		return;
   4334 
   4335 	misccpctl = I915_READ(GEN7_MISCCPCTL);
   4336 	I915_WRITE(GEN7_MISCCPCTL, misccpctl & ~GEN7_DOP_CLOCK_GATE_ENABLE);
   4337 	POSTING_READ(GEN7_MISCCPCTL);
   4338 
   4339 	for (i = 0; i < GEN7_L3LOG_SIZE; i += 4) {
   4340 		u32 remap = I915_READ(GEN7_L3LOG_BASE + i);
   4341 		if (remap && remap != dev_priv->l3_parity.remap_info[i/4])
   4342 			DRM_DEBUG("0x%x was already programmed to %x\n",
   4343 				  GEN7_L3LOG_BASE + i, remap);
   4344 		if (remap && !dev_priv->l3_parity.remap_info[i/4])
   4345 			DRM_DEBUG_DRIVER("Clearing remapped register\n");
   4346 		I915_WRITE(GEN7_L3LOG_BASE + i, dev_priv->l3_parity.remap_info[i/4]);
   4347 	}
   4348 
   4349 	/* Make sure all the writes land before disabling dop clock gating */
   4350 	POSTING_READ(GEN7_L3LOG_BASE);
   4351 
   4352 	I915_WRITE(GEN7_MISCCPCTL, misccpctl);
   4353 }
   4354 
   4355 void i915_gem_init_swizzling(struct drm_device *dev)
   4356 {
   4357 	drm_i915_private_t *dev_priv = dev->dev_private;
   4358 
   4359 	if (INTEL_INFO(dev)->gen < 5 ||
   4360 	    dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
   4361 		return;
   4362 
   4363 	I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
   4364 				 DISP_TILE_SURFACE_SWIZZLING);
   4365 
   4366 	if (IS_GEN5(dev))
   4367 		return;
   4368 
   4369 	I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
   4370 	if (IS_GEN6(dev))
   4371 		I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
   4372 	else
   4373 		I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
   4374 }
   4375 
   4376 static bool
   4377 intel_enable_blt(struct drm_device *dev)
   4378 {
   4379 	if (!HAS_BLT(dev))
   4380 		return false;
   4381 
   4382 	/* The blitter was dysfunctional on early prototypes */
   4383 	if (IS_GEN6(dev) && dev->pdev->revision < 8) {
   4384 		DRM_INFO("BLT not supported on this pre-production hardware;"
   4385 			 " graphics performance will be degraded.\n");
   4386 		return false;
   4387 	}
   4388 
   4389 	return true;
   4390 }
   4391 
   4392 int
   4393 i915_gem_init_hw(struct drm_device *dev)
   4394 {
   4395 	drm_i915_private_t *dev_priv = dev->dev_private;
   4396 	int ret;
   4397 
   4398 	if (INTEL_INFO(dev)->gen < 6 && !intel_enable_gtt())
   4399 		return -EIO;
   4400 
   4401 	if (IS_HASWELL(dev) && (I915_READ(0x120010) == 1))
   4402 		I915_WRITE(0x9008, I915_READ(0x9008) | 0xf0000);
   4403 
   4404 	i915_gem_l3_remap(dev);
   4405 
   4406 	i915_gem_init_swizzling(dev);
   4407 
   4408 	ret = intel_init_render_ring_buffer(dev);
   4409 	if (ret)
   4410 		return ret;
   4411 
   4412 	if (HAS_BSD(dev)) {
   4413 		ret = intel_init_bsd_ring_buffer(dev);
   4414 		if (ret)
   4415 			goto cleanup_render_ring;
   4416 	}
   4417 
   4418 	if (intel_enable_blt(dev)) {
   4419 		ret = intel_init_blt_ring_buffer(dev);
   4420 		if (ret)
   4421 			goto cleanup_bsd_ring;
   4422 	}
   4423 
   4424 	dev_priv->next_seqno = 1;
   4425 
   4426 	/*
   4427 	 * XXX: There was some w/a described somewhere suggesting loading
   4428 	 * contexts before PPGTT.
   4429 	 */
   4430 	i915_gem_context_init(dev);
   4431 	i915_gem_init_ppgtt(dev);
   4432 
   4433 	return 0;
   4434 
   4435 cleanup_bsd_ring:
   4436 	intel_cleanup_ring_buffer(&dev_priv->ring[VCS]);
   4437 cleanup_render_ring:
   4438 	intel_cleanup_ring_buffer(&dev_priv->ring[RCS]);
   4439 	return ret;
   4440 }
   4441 
   4442 static bool
   4443 intel_enable_ppgtt(struct drm_device *dev)
   4444 {
   4445 #ifdef __NetBSD__		/* XXX ppgtt */
   4446 	return false;
   4447 #else
   4448 	if (i915_enable_ppgtt >= 0)
   4449 		return i915_enable_ppgtt;
   4450 
   4451 #ifdef CONFIG_INTEL_IOMMU
   4452 	/* Disable ppgtt on SNB if VT-d is on. */
   4453 	if (INTEL_INFO(dev)->gen == 6 && intel_iommu_gfx_mapped)
   4454 		return false;
   4455 #endif
   4456 
   4457 	return true;
   4458 #endif
   4459 }
   4460 
   4461 int i915_gem_init(struct drm_device *dev)
   4462 {
   4463 	struct drm_i915_private *dev_priv = dev->dev_private;
   4464 	unsigned long gtt_size, mappable_size;
   4465 	int ret;
   4466 
   4467 	gtt_size = dev_priv->mm.gtt->gtt_total_entries << PAGE_SHIFT;
   4468 	mappable_size = dev_priv->mm.gtt->gtt_mappable_entries << PAGE_SHIFT;
   4469 
   4470 	mutex_lock(&dev->struct_mutex);
   4471 	if (intel_enable_ppgtt(dev) && HAS_ALIASING_PPGTT(dev)) {
   4472 		/* PPGTT pdes are stolen from global gtt ptes, so shrink the
   4473 		 * aperture accordingly when using aliasing ppgtt. */
   4474 		gtt_size -= I915_PPGTT_PD_ENTRIES*PAGE_SIZE;
   4475 
   4476 		i915_gem_init_global_gtt(dev, 0, mappable_size, gtt_size);
   4477 
   4478 		ret = i915_gem_init_aliasing_ppgtt(dev);
   4479 		if (ret) {
   4480 			i915_gem_fini_global_gtt(dev);
   4481 			mutex_unlock(&dev->struct_mutex);
   4482 			return ret;
   4483 		}
   4484 	} else {
   4485 		/* Let GEM Manage all of the aperture.
   4486 		 *
   4487 		 * However, leave one page at the end still bound to the scratch
   4488 		 * page.  There are a number of places where the hardware
   4489 		 * apparently prefetches past the end of the object, and we've
   4490 		 * seen multiple hangs with the GPU head pointer stuck in a
   4491 		 * batchbuffer bound at the last page of the aperture.  One page
   4492 		 * should be enough to keep any prefetching inside of the
   4493 		 * aperture.
   4494 		 */
   4495 		i915_gem_init_global_gtt(dev, 0, mappable_size,
   4496 					 gtt_size);
   4497 	}
   4498 
   4499 	ret = i915_gem_init_hw(dev);
   4500 #ifdef __NetBSD__		/* XXX fini global gtt */
   4501 	if (ret)
   4502 		i915_gem_fini_global_gtt(dev);
   4503 #endif
   4504 	mutex_unlock(&dev->struct_mutex);
   4505 	if (ret) {
   4506 		i915_gem_cleanup_aliasing_ppgtt(dev);
   4507 		return ret;
   4508 	}
   4509 
   4510 	/* Allow hardware batchbuffers unless told otherwise, but not for KMS. */
   4511 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
   4512 		dev_priv->dri1.allow_batchbuffer = 1;
   4513 	return 0;
   4514 }
   4515 
   4516 void
   4517 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
   4518 {
   4519 	drm_i915_private_t *dev_priv = dev->dev_private;
   4520 	struct intel_ring_buffer *ring;
   4521 	int i;
   4522 
   4523 	for_each_ring(ring, dev_priv, i)
   4524 		intel_cleanup_ring_buffer(ring);
   4525 }
   4526 
   4527 int
   4528 i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
   4529 		       struct drm_file *file_priv)
   4530 {
   4531 	drm_i915_private_t *dev_priv = dev->dev_private;
   4532 	int ret;
   4533 
   4534 	if (drm_core_check_feature(dev, DRIVER_MODESET))
   4535 		return 0;
   4536 
   4537 	if (atomic_read(&dev_priv->mm.wedged)) {
   4538 		DRM_ERROR("Reenabling wedged hardware, good luck\n");
   4539 		atomic_set(&dev_priv->mm.wedged, 0);
   4540 	}
   4541 
   4542 	mutex_lock(&dev->struct_mutex);
   4543 	dev_priv->mm.suspended = 0;
   4544 
   4545 	ret = i915_gem_init_hw(dev);
   4546 	if (ret != 0) {
   4547 		mutex_unlock(&dev->struct_mutex);
   4548 		return ret;
   4549 	}
   4550 
   4551 	BUG_ON(!list_empty(&dev_priv->mm.active_list));
   4552 	mutex_unlock(&dev->struct_mutex);
   4553 
   4554 	ret = drm_irq_install(dev);
   4555 	if (ret)
   4556 		goto cleanup_ringbuffer;
   4557 
   4558 	return 0;
   4559 
   4560 cleanup_ringbuffer:
   4561 	mutex_lock(&dev->struct_mutex);
   4562 	i915_gem_cleanup_ringbuffer(dev);
   4563 	dev_priv->mm.suspended = 1;
   4564 	mutex_unlock(&dev->struct_mutex);
   4565 
   4566 	return ret;
   4567 }
   4568 
   4569 int
   4570 i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
   4571 		       struct drm_file *file_priv)
   4572 {
   4573 	if (drm_core_check_feature(dev, DRIVER_MODESET))
   4574 		return 0;
   4575 
   4576 	drm_irq_uninstall(dev);
   4577 	return i915_gem_idle(dev);
   4578 }
   4579 
   4580 void
   4581 i915_gem_lastclose(struct drm_device *dev)
   4582 {
   4583 	int ret;
   4584 
   4585 	if (drm_core_check_feature(dev, DRIVER_MODESET))
   4586 		return;
   4587 
   4588 	ret = i915_gem_idle(dev);
   4589 	if (ret)
   4590 		DRM_ERROR("failed to idle hardware: %d\n", ret);
   4591 }
   4592 
   4593 static void
   4594 init_ring_lists(struct intel_ring_buffer *ring)
   4595 {
   4596 	INIT_LIST_HEAD(&ring->active_list);
   4597 	INIT_LIST_HEAD(&ring->request_list);
   4598 }
   4599 
   4600 void
   4601 i915_gem_load(struct drm_device *dev)
   4602 {
   4603 	int i;
   4604 	drm_i915_private_t *dev_priv = dev->dev_private;
   4605 
   4606 	INIT_LIST_HEAD(&dev_priv->mm.active_list);
   4607 	INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
   4608 	INIT_LIST_HEAD(&dev_priv->mm.unbound_list);
   4609 	INIT_LIST_HEAD(&dev_priv->mm.bound_list);
   4610 	INIT_LIST_HEAD(&dev_priv->mm.fence_list);
   4611 	for (i = 0; i < I915_NUM_RINGS; i++)
   4612 		init_ring_lists(&dev_priv->ring[i]);
   4613 	for (i = 0; i < I915_MAX_NUM_FENCES; i++)
   4614 		INIT_LIST_HEAD(&dev_priv->fence_regs[i].lru_list);
   4615 	INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
   4616 			  i915_gem_retire_work_handler);
   4617 	init_completion(&dev_priv->error_completion);
   4618 
   4619 	/* On GEN3 we really need to make sure the ARB C3 LP bit is set */
   4620 	if (IS_GEN3(dev)) {
   4621 		I915_WRITE(MI_ARB_STATE,
   4622 			   _MASKED_BIT_ENABLE(MI_ARB_C3_LP_WRITE_ENABLE));
   4623 	}
   4624 
   4625 	dev_priv->relative_constants_mode = I915_EXEC_CONSTANTS_REL_GENERAL;
   4626 
   4627 	/* Old X drivers will take 0-2 for front, back, depth buffers */
   4628 	if (!drm_core_check_feature(dev, DRIVER_MODESET))
   4629 		dev_priv->fence_reg_start = 3;
   4630 
   4631 	if (INTEL_INFO(dev)->gen >= 4 || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
   4632 		dev_priv->num_fence_regs = 16;
   4633 	else
   4634 		dev_priv->num_fence_regs = 8;
   4635 
   4636 	/* Initialize fence registers to zero */
   4637 	i915_gem_reset_fences(dev);
   4638 
   4639 	i915_gem_detect_bit_6_swizzle(dev);
   4640 #ifdef __NetBSD__
   4641 	DRM_INIT_WAITQUEUE(&dev_priv->pending_flip_queue, "i915flip");
   4642 	linux_mutex_init(&dev_priv->pending_flip_lock);
   4643 #else
   4644 	init_waitqueue_head(&dev_priv->pending_flip_queue);
   4645 #endif
   4646 
   4647 	dev_priv->mm.interruptible = true;
   4648 
   4649 	dev_priv->mm.inactive_shrinker.shrink = i915_gem_inactive_shrink;
   4650 	dev_priv->mm.inactive_shrinker.seeks = DEFAULT_SEEKS;
   4651 	register_shrinker(&dev_priv->mm.inactive_shrinker);
   4652 }
   4653 
   4654 /*
   4655  * Create a physically contiguous memory object for this object
   4656  * e.g. for cursor + overlay regs
   4657  */
   4658 static int i915_gem_init_phys_object(struct drm_device *dev,
   4659 				     int id, int size, int align)
   4660 {
   4661 	drm_i915_private_t *dev_priv = dev->dev_private;
   4662 	struct drm_i915_gem_phys_object *phys_obj;
   4663 	int ret;
   4664 
   4665 	if (dev_priv->mm.phys_objs[id - 1] || !size)
   4666 		return 0;
   4667 
   4668 	phys_obj = kzalloc(sizeof(struct drm_i915_gem_phys_object), GFP_KERNEL);
   4669 	if (!phys_obj)
   4670 		return -ENOMEM;
   4671 
   4672 	phys_obj->id = id;
   4673 
   4674 	phys_obj->handle = drm_pci_alloc(dev, size, align);
   4675 	if (!phys_obj->handle) {
   4676 		ret = -ENOMEM;
   4677 		goto kfree_obj;
   4678 	}
   4679 #ifndef __NetBSD__		/* XXX x86 wc?  */
   4680 #ifdef CONFIG_X86
   4681 	set_memory_wc((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
   4682 #endif
   4683 #endif
   4684 
   4685 	dev_priv->mm.phys_objs[id - 1] = phys_obj;
   4686 
   4687 	return 0;
   4688 kfree_obj:
   4689 	kfree(phys_obj);
   4690 	return ret;
   4691 }
   4692 
   4693 static void i915_gem_free_phys_object(struct drm_device *dev, int id)
   4694 {
   4695 	drm_i915_private_t *dev_priv = dev->dev_private;
   4696 	struct drm_i915_gem_phys_object *phys_obj;
   4697 
   4698 	if (!dev_priv->mm.phys_objs[id - 1])
   4699 		return;
   4700 
   4701 	phys_obj = dev_priv->mm.phys_objs[id - 1];
   4702 	if (phys_obj->cur_obj) {
   4703 		i915_gem_detach_phys_object(dev, phys_obj->cur_obj);
   4704 	}
   4705 
   4706 #ifndef __NetBSD__		/* XXX x86 wb?  */
   4707 #ifdef CONFIG_X86
   4708 	set_memory_wb((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
   4709 #endif
   4710 #endif
   4711 	drm_pci_free(dev, phys_obj->handle);
   4712 	kfree(phys_obj);
   4713 	dev_priv->mm.phys_objs[id - 1] = NULL;
   4714 }
   4715 
   4716 void i915_gem_free_all_phys_object(struct drm_device *dev)
   4717 {
   4718 	int i;
   4719 
   4720 	for (i = I915_GEM_PHYS_CURSOR_0; i <= I915_MAX_PHYS_OBJECT; i++)
   4721 		i915_gem_free_phys_object(dev, i);
   4722 }
   4723 
   4724 void i915_gem_detach_phys_object(struct drm_device *dev,
   4725 				 struct drm_i915_gem_object *obj)
   4726 {
   4727 #ifndef __NetBSD__
   4728 	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
   4729 #endif
   4730 	char *vaddr;
   4731 	int i;
   4732 	int page_count;
   4733 
   4734 	if (!obj->phys_obj)
   4735 		return;
   4736 	vaddr = obj->phys_obj->handle->vaddr;
   4737 
   4738 	page_count = obj->base.size / PAGE_SIZE;
   4739 	for (i = 0; i < page_count; i++) {
   4740 #ifdef __NetBSD__
   4741 		/* XXX Just use ubc_uiomove?  */
   4742 		struct pglist pages;
   4743 		int error;
   4744 
   4745 		TAILQ_INIT(&pages);
   4746 		error = uvm_obj_wirepages(obj->base.gemo_shm_uao, i*PAGE_SIZE,
   4747 		    (i+1)*PAGE_SIZE, &pages);
   4748 		if (error) {
   4749 			printf("unable to map page %d of i915 gem obj: %d\n",
   4750 			    i, error);
   4751 			continue;
   4752 		}
   4753 
   4754 		KASSERT(!TAILQ_EMPTY(&pages));
   4755 		struct vm_page *const page = TAILQ_FIRST(&pages);
   4756 		TAILQ_REMOVE(&pages, page, pageq.queue);
   4757 		KASSERT(TAILQ_EMPTY(&pages));
   4758 
   4759 		char *const dst = kmap_atomic(container_of(page, struct page,
   4760 			p_vmp));
   4761 		(void)memcpy(dst, vaddr + (i*PAGE_SIZE), PAGE_SIZE);
   4762 		kunmap_atomic(dst);
   4763 
   4764 		drm_clflush_page(container_of(page, struct page, p_vmp));
   4765 		page->flags &= ~PG_CLEAN;
   4766 		/* XXX mark page accessed */
   4767 		uvm_obj_unwirepages(obj->base.gemo_shm_uao, i*PAGE_SIZE,
   4768 		    (i+1)*PAGE_SIZE);
   4769 #else
   4770 		struct page *page = shmem_read_mapping_page(mapping, i);
   4771 		if (!IS_ERR(page)) {
   4772 			char *dst = kmap_atomic(page);
   4773 			memcpy(dst, vaddr + i*PAGE_SIZE, PAGE_SIZE);
   4774 			kunmap_atomic(dst);
   4775 
   4776 			drm_clflush_pages(&page, 1);
   4777 
   4778 			set_page_dirty(page);
   4779 			mark_page_accessed(page);
   4780 			page_cache_release(page);
   4781 		}
   4782 #endif
   4783 	}
   4784 	i915_gem_chipset_flush(dev);
   4785 
   4786 	obj->phys_obj->cur_obj = NULL;
   4787 	obj->phys_obj = NULL;
   4788 }
   4789 
   4790 int
   4791 i915_gem_attach_phys_object(struct drm_device *dev,
   4792 			    struct drm_i915_gem_object *obj,
   4793 			    int id,
   4794 			    int align)
   4795 {
   4796 #ifndef __NetBSD__
   4797 	struct address_space *mapping = obj->base.filp->f_path.dentry->d_inode->i_mapping;
   4798 #endif
   4799 	drm_i915_private_t *dev_priv = dev->dev_private;
   4800 	int ret = 0;
   4801 	int page_count;
   4802 	int i;
   4803 
   4804 	if (id > I915_MAX_PHYS_OBJECT)
   4805 		return -EINVAL;
   4806 
   4807 	if (obj->phys_obj) {
   4808 		if (obj->phys_obj->id == id)
   4809 			return 0;
   4810 		i915_gem_detach_phys_object(dev, obj);
   4811 	}
   4812 
   4813 	/* create a new object */
   4814 	if (!dev_priv->mm.phys_objs[id - 1]) {
   4815 		ret = i915_gem_init_phys_object(dev, id,
   4816 						obj->base.size, align);
   4817 		if (ret) {
   4818 			DRM_ERROR("failed to init phys object %d size: %zu\n",
   4819 				  id, obj->base.size);
   4820 			return ret;
   4821 		}
   4822 	}
   4823 
   4824 	/* bind to the object */
   4825 	obj->phys_obj = dev_priv->mm.phys_objs[id - 1];
   4826 	obj->phys_obj->cur_obj = obj;
   4827 
   4828 	page_count = obj->base.size / PAGE_SIZE;
   4829 
   4830 	for (i = 0; i < page_count; i++) {
   4831 #ifdef __NetBSD__
   4832 		char *const vaddr = obj->phys_obj->handle->vaddr;
   4833 		struct pglist pages;
   4834 		int error;
   4835 
   4836 		TAILQ_INIT(&pages);
   4837 		error = uvm_obj_wirepages(obj->base.gemo_shm_uao, i*PAGE_SIZE,
   4838 		    (i+1)*PAGE_SIZE, &pages);
   4839 		if (error)
   4840 			/* XXX errno NetBSD->Linux */
   4841 			return -error;
   4842 
   4843 		KASSERT(!TAILQ_EMPTY(&pages));
   4844 		struct vm_page *const page = TAILQ_FIRST(&pages);
   4845 		TAILQ_REMOVE(&pages, page, pageq.queue);
   4846 		KASSERT(TAILQ_EMPTY(&pages));
   4847 
   4848 		char *const src = kmap_atomic(container_of(page, struct page,
   4849 			p_vmp));
   4850 		(void)memcpy(vaddr + (i*PAGE_SIZE), src, PAGE_SIZE);
   4851 		kunmap_atomic(src);
   4852 
   4853 		/* XXX mark page accessed */
   4854 		uvm_obj_unwirepages(obj->base.gemo_shm_uao, i*PAGE_SIZE,
   4855 		    (i+1)*PAGE_SIZE);
   4856 #else
   4857 		struct page *page;
   4858 		char *dst, *src;
   4859 
   4860 		page = shmem_read_mapping_page(mapping, i);
   4861 		if (IS_ERR(page))
   4862 			return PTR_ERR(page);
   4863 
   4864 		src = kmap_atomic(page);
   4865 		dst = obj->phys_obj->handle->vaddr + (i * PAGE_SIZE);
   4866 		memcpy(dst, src, PAGE_SIZE);
   4867 		kunmap_atomic(src);
   4868 
   4869 		mark_page_accessed(page);
   4870 		page_cache_release(page);
   4871 #endif
   4872 	}
   4873 
   4874 	return 0;
   4875 }
   4876 
   4877 static int
   4878 i915_gem_phys_pwrite(struct drm_device *dev,
   4879 		     struct drm_i915_gem_object *obj,
   4880 		     struct drm_i915_gem_pwrite *args,
   4881 		     struct drm_file *file_priv)
   4882 {
   4883 	void *vaddr = (char *)obj->phys_obj->handle->vaddr + args->offset;
   4884 	char __user *user_data = (char __user *) (uintptr_t) args->data_ptr;
   4885 
   4886 	if (__copy_from_user_inatomic_nocache(vaddr, user_data, args->size)) {
   4887 		unsigned long unwritten;
   4888 
   4889 		/* The physical object once assigned is fixed for the lifetime
   4890 		 * of the obj, so we can safely drop the lock and continue
   4891 		 * to access vaddr.
   4892 		 */
   4893 		mutex_unlock(&dev->struct_mutex);
   4894 		unwritten = copy_from_user(vaddr, user_data, args->size);
   4895 		mutex_lock(&dev->struct_mutex);
   4896 		if (unwritten)
   4897 			return -EFAULT;
   4898 	}
   4899 
   4900 	i915_gem_chipset_flush(dev);
   4901 	return 0;
   4902 }
   4903 
   4904 void i915_gem_release(struct drm_device *dev, struct drm_file *file)
   4905 {
   4906 	struct drm_i915_file_private *file_priv = file->driver_priv;
   4907 
   4908 	/* Clean up our request list when the client is going away, so that
   4909 	 * later retire_requests won't dereference our soon-to-be-gone
   4910 	 * file_priv.
   4911 	 */
   4912 	spin_lock(&file_priv->mm.lock);
   4913 	while (!list_empty(&file_priv->mm.request_list)) {
   4914 		struct drm_i915_gem_request *request;
   4915 
   4916 		request = list_first_entry(&file_priv->mm.request_list,
   4917 					   struct drm_i915_gem_request,
   4918 					   client_list);
   4919 		list_del(&request->client_list);
   4920 		request->file_priv = NULL;
   4921 	}
   4922 	spin_unlock(&file_priv->mm.lock);
   4923 }
   4924 
   4925 #ifndef __NetBSD__		/* XXX */
   4926 static bool mutex_is_locked_by(struct mutex *mutex, struct task_struct *task)
   4927 {
   4928 	if (!mutex_is_locked(mutex))
   4929 		return false;
   4930 
   4931 #if defined(CONFIG_SMP) || defined(CONFIG_DEBUG_MUTEXES)
   4932 	return mutex->owner == task;
   4933 #else
   4934 	/* Since UP may be pre-empted, we cannot assume that we own the lock */
   4935 	return false;
   4936 #endif
   4937 }
   4938 #endif
   4939 
   4940 static int
   4941 i915_gem_inactive_shrink(struct shrinker *shrinker, struct shrink_control *sc)
   4942 {
   4943 #ifdef __NetBSD__		/* XXX shrinkers */
   4944 	return 0;
   4945 #else
   4946 	struct drm_i915_private *dev_priv =
   4947 		container_of(shrinker,
   4948 			     struct drm_i915_private,
   4949 			     mm.inactive_shrinker);
   4950 	struct drm_device *dev = dev_priv->dev;
   4951 	struct drm_i915_gem_object *obj;
   4952 	int nr_to_scan = sc->nr_to_scan;
   4953 	bool unlock = true;
   4954 	int cnt;
   4955 
   4956 	if (!mutex_trylock(&dev->struct_mutex)) {
   4957 		if (!mutex_is_locked_by(&dev->struct_mutex, current))
   4958 			return 0;
   4959 
   4960 		if (dev_priv->mm.shrinker_no_lock_stealing)
   4961 			return 0;
   4962 
   4963 		unlock = false;
   4964 	}
   4965 
   4966 	if (nr_to_scan) {
   4967 		nr_to_scan -= i915_gem_purge(dev_priv, nr_to_scan);
   4968 		if (nr_to_scan > 0)
   4969 			nr_to_scan -= __i915_gem_shrink(dev_priv, nr_to_scan,
   4970 							false);
   4971 		if (nr_to_scan > 0)
   4972 			i915_gem_shrink_all(dev_priv);
   4973 	}
   4974 
   4975 	cnt = 0;
   4976 	list_for_each_entry(obj, &dev_priv->mm.unbound_list, gtt_list)
   4977 		if (obj->pages_pin_count == 0)
   4978 			cnt += obj->base.size >> PAGE_SHIFT;
   4979 	list_for_each_entry(obj, &dev_priv->mm.inactive_list, gtt_list)
   4980 		if (obj->pin_count == 0 && obj->pages_pin_count == 0)
   4981 			cnt += obj->base.size >> PAGE_SHIFT;
   4982 
   4983 	if (unlock)
   4984 		mutex_unlock(&dev->struct_mutex);
   4985 	return cnt;
   4986 #endif
   4987 }
   4988