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