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