35f8c7bd0d32c2147c5e2e58e1bcb604c1952e31
[safe/jmp/linux-2.6] / drivers / gpu / drm / i915 / i915_gem.c
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@anholt.net>
25  *
26  */
27
28 #include "drmP.h"
29 #include "drm.h"
30 #include "i915_drm.h"
31 #include "i915_drv.h"
32 #include <linux/swap.h>
33 #include <linux/pci.h>
34
35 #define I915_GEM_GPU_DOMAINS    (~(I915_GEM_DOMAIN_CPU | I915_GEM_DOMAIN_GTT))
36
37 static void i915_gem_object_flush_gpu_write_domain(struct drm_gem_object *obj);
38 static void i915_gem_object_flush_gtt_write_domain(struct drm_gem_object *obj);
39 static void i915_gem_object_flush_cpu_write_domain(struct drm_gem_object *obj);
40 static int i915_gem_object_set_to_cpu_domain(struct drm_gem_object *obj,
41                                              int write);
42 static int i915_gem_object_set_cpu_read_domain_range(struct drm_gem_object *obj,
43                                                      uint64_t offset,
44                                                      uint64_t size);
45 static void i915_gem_object_set_to_full_cpu_read_domain(struct drm_gem_object *obj);
46 static int i915_gem_object_get_page_list(struct drm_gem_object *obj);
47 static void i915_gem_object_free_page_list(struct drm_gem_object *obj);
48 static int i915_gem_object_wait_rendering(struct drm_gem_object *obj);
49 static int i915_gem_object_bind_to_gtt(struct drm_gem_object *obj,
50                                            unsigned alignment);
51 static int i915_gem_object_get_fence_reg(struct drm_gem_object *obj, bool write);
52 static void i915_gem_clear_fence_reg(struct drm_gem_object *obj);
53 static int i915_gem_evict_something(struct drm_device *dev);
54 static int i915_gem_phys_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
55                                 struct drm_i915_gem_pwrite *args,
56                                 struct drm_file *file_priv);
57
58 int i915_gem_do_init(struct drm_device *dev, unsigned long start,
59                      unsigned long end)
60 {
61         drm_i915_private_t *dev_priv = dev->dev_private;
62
63         if (start >= end ||
64             (start & (PAGE_SIZE - 1)) != 0 ||
65             (end & (PAGE_SIZE - 1)) != 0) {
66                 return -EINVAL;
67         }
68
69         drm_mm_init(&dev_priv->mm.gtt_space, start,
70                     end - start);
71
72         dev->gtt_total = (uint32_t) (end - start);
73
74         return 0;
75 }
76
77 int
78 i915_gem_init_ioctl(struct drm_device *dev, void *data,
79                     struct drm_file *file_priv)
80 {
81         struct drm_i915_gem_init *args = data;
82         int ret;
83
84         mutex_lock(&dev->struct_mutex);
85         ret = i915_gem_do_init(dev, args->gtt_start, args->gtt_end);
86         mutex_unlock(&dev->struct_mutex);
87
88         return ret;
89 }
90
91 int
92 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
93                             struct drm_file *file_priv)
94 {
95         struct drm_i915_gem_get_aperture *args = data;
96
97         if (!(dev->driver->driver_features & DRIVER_GEM))
98                 return -ENODEV;
99
100         args->aper_size = dev->gtt_total;
101         args->aper_available_size = (args->aper_size -
102                                      atomic_read(&dev->pin_memory));
103
104         return 0;
105 }
106
107
108 /**
109  * Creates a new mm object and returns a handle to it.
110  */
111 int
112 i915_gem_create_ioctl(struct drm_device *dev, void *data,
113                       struct drm_file *file_priv)
114 {
115         struct drm_i915_gem_create *args = data;
116         struct drm_gem_object *obj;
117         int handle, ret;
118
119         args->size = roundup(args->size, PAGE_SIZE);
120
121         /* Allocate the new object */
122         obj = drm_gem_object_alloc(dev, args->size);
123         if (obj == NULL)
124                 return -ENOMEM;
125
126         ret = drm_gem_handle_create(file_priv, obj, &handle);
127         mutex_lock(&dev->struct_mutex);
128         drm_gem_object_handle_unreference(obj);
129         mutex_unlock(&dev->struct_mutex);
130
131         if (ret)
132                 return ret;
133
134         args->handle = handle;
135
136         return 0;
137 }
138
139 /**
140  * Reads data from the object referenced by handle.
141  *
142  * On error, the contents of *data are undefined.
143  */
144 int
145 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
146                      struct drm_file *file_priv)
147 {
148         struct drm_i915_gem_pread *args = data;
149         struct drm_gem_object *obj;
150         struct drm_i915_gem_object *obj_priv;
151         ssize_t read;
152         loff_t offset;
153         int ret;
154
155         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
156         if (obj == NULL)
157                 return -EBADF;
158         obj_priv = obj->driver_private;
159
160         /* Bounds check source.
161          *
162          * XXX: This could use review for overflow issues...
163          */
164         if (args->offset > obj->size || args->size > obj->size ||
165             args->offset + args->size > obj->size) {
166                 drm_gem_object_unreference(obj);
167                 return -EINVAL;
168         }
169
170         mutex_lock(&dev->struct_mutex);
171
172         ret = i915_gem_object_set_cpu_read_domain_range(obj, args->offset,
173                                                         args->size);
174         if (ret != 0) {
175                 drm_gem_object_unreference(obj);
176                 mutex_unlock(&dev->struct_mutex);
177                 return ret;
178         }
179
180         offset = args->offset;
181
182         read = vfs_read(obj->filp, (char __user *)(uintptr_t)args->data_ptr,
183                         args->size, &offset);
184         if (read != args->size) {
185                 drm_gem_object_unreference(obj);
186                 mutex_unlock(&dev->struct_mutex);
187                 if (read < 0)
188                         return read;
189                 else
190                         return -EINVAL;
191         }
192
193         drm_gem_object_unreference(obj);
194         mutex_unlock(&dev->struct_mutex);
195
196         return 0;
197 }
198
199 /* This is the fast write path which cannot handle
200  * page faults in the source data
201  */
202
203 static inline int
204 fast_user_write(struct io_mapping *mapping,
205                 loff_t page_base, int page_offset,
206                 char __user *user_data,
207                 int length)
208 {
209         char *vaddr_atomic;
210         unsigned long unwritten;
211
212         vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
213         unwritten = __copy_from_user_inatomic_nocache(vaddr_atomic + page_offset,
214                                                       user_data, length);
215         io_mapping_unmap_atomic(vaddr_atomic);
216         if (unwritten)
217                 return -EFAULT;
218         return 0;
219 }
220
221 /* Here's the write path which can sleep for
222  * page faults
223  */
224
225 static inline int
226 slow_kernel_write(struct io_mapping *mapping,
227                   loff_t gtt_base, int gtt_offset,
228                   struct page *user_page, int user_offset,
229                   int length)
230 {
231         char *src_vaddr, *dst_vaddr;
232         unsigned long unwritten;
233
234         dst_vaddr = io_mapping_map_atomic_wc(mapping, gtt_base);
235         src_vaddr = kmap_atomic(user_page, KM_USER1);
236         unwritten = __copy_from_user_inatomic_nocache(dst_vaddr + gtt_offset,
237                                                       src_vaddr + user_offset,
238                                                       length);
239         kunmap_atomic(src_vaddr, KM_USER1);
240         io_mapping_unmap_atomic(dst_vaddr);
241         if (unwritten)
242                 return -EFAULT;
243         return 0;
244 }
245
246 /**
247  * This is the fast pwrite path, where we copy the data directly from the
248  * user into the GTT, uncached.
249  */
250 static int
251 i915_gem_gtt_pwrite_fast(struct drm_device *dev, struct drm_gem_object *obj,
252                          struct drm_i915_gem_pwrite *args,
253                          struct drm_file *file_priv)
254 {
255         struct drm_i915_gem_object *obj_priv = obj->driver_private;
256         drm_i915_private_t *dev_priv = dev->dev_private;
257         ssize_t remain;
258         loff_t offset, page_base;
259         char __user *user_data;
260         int page_offset, page_length;
261         int ret;
262
263         user_data = (char __user *) (uintptr_t) args->data_ptr;
264         remain = args->size;
265         if (!access_ok(VERIFY_READ, user_data, remain))
266                 return -EFAULT;
267
268
269         mutex_lock(&dev->struct_mutex);
270         ret = i915_gem_object_pin(obj, 0);
271         if (ret) {
272                 mutex_unlock(&dev->struct_mutex);
273                 return ret;
274         }
275         ret = i915_gem_object_set_to_gtt_domain(obj, 1);
276         if (ret)
277                 goto fail;
278
279         obj_priv = obj->driver_private;
280         offset = obj_priv->gtt_offset + args->offset;
281
282         while (remain > 0) {
283                 /* Operation in this page
284                  *
285                  * page_base = page offset within aperture
286                  * page_offset = offset within page
287                  * page_length = bytes to copy for this page
288                  */
289                 page_base = (offset & ~(PAGE_SIZE-1));
290                 page_offset = offset & (PAGE_SIZE-1);
291                 page_length = remain;
292                 if ((page_offset + remain) > PAGE_SIZE)
293                         page_length = PAGE_SIZE - page_offset;
294
295                 ret = fast_user_write (dev_priv->mm.gtt_mapping, page_base,
296                                        page_offset, user_data, page_length);
297
298                 /* If we get a fault while copying data, then (presumably) our
299                  * source page isn't available.  Return the error and we'll
300                  * retry in the slow path.
301                  */
302                 if (ret)
303                         goto fail;
304
305                 remain -= page_length;
306                 user_data += page_length;
307                 offset += page_length;
308         }
309
310 fail:
311         i915_gem_object_unpin(obj);
312         mutex_unlock(&dev->struct_mutex);
313
314         return ret;
315 }
316
317 /**
318  * This is the fallback GTT pwrite path, which uses get_user_pages to pin
319  * the memory and maps it using kmap_atomic for copying.
320  *
321  * This code resulted in x11perf -rgb10text consuming about 10% more CPU
322  * than using i915_gem_gtt_pwrite_fast on a G45 (32-bit).
323  */
324 static int
325 i915_gem_gtt_pwrite_slow(struct drm_device *dev, struct drm_gem_object *obj,
326                          struct drm_i915_gem_pwrite *args,
327                          struct drm_file *file_priv)
328 {
329         struct drm_i915_gem_object *obj_priv = obj->driver_private;
330         drm_i915_private_t *dev_priv = dev->dev_private;
331         ssize_t remain;
332         loff_t gtt_page_base, offset;
333         loff_t first_data_page, last_data_page, num_pages;
334         loff_t pinned_pages, i;
335         struct page **user_pages;
336         struct mm_struct *mm = current->mm;
337         int gtt_page_offset, data_page_offset, data_page_index, page_length;
338         int ret;
339         uint64_t data_ptr = args->data_ptr;
340
341         remain = args->size;
342
343         /* Pin the user pages containing the data.  We can't fault while
344          * holding the struct mutex, and all of the pwrite implementations
345          * want to hold it while dereferencing the user data.
346          */
347         first_data_page = data_ptr / PAGE_SIZE;
348         last_data_page = (data_ptr + args->size - 1) / PAGE_SIZE;
349         num_pages = last_data_page - first_data_page + 1;
350
351         user_pages = kcalloc(num_pages, sizeof(struct page *), GFP_KERNEL);
352         if (user_pages == NULL)
353                 return -ENOMEM;
354
355         down_read(&mm->mmap_sem);
356         pinned_pages = get_user_pages(current, mm, (uintptr_t)args->data_ptr,
357                                       num_pages, 0, 0, user_pages, NULL);
358         up_read(&mm->mmap_sem);
359         if (pinned_pages < num_pages) {
360                 ret = -EFAULT;
361                 goto out_unpin_pages;
362         }
363
364         mutex_lock(&dev->struct_mutex);
365         ret = i915_gem_object_pin(obj, 0);
366         if (ret)
367                 goto out_unlock;
368
369         ret = i915_gem_object_set_to_gtt_domain(obj, 1);
370         if (ret)
371                 goto out_unpin_object;
372
373         obj_priv = obj->driver_private;
374         offset = obj_priv->gtt_offset + args->offset;
375
376         while (remain > 0) {
377                 /* Operation in this page
378                  *
379                  * gtt_page_base = page offset within aperture
380                  * gtt_page_offset = offset within page in aperture
381                  * data_page_index = page number in get_user_pages return
382                  * data_page_offset = offset with data_page_index page.
383                  * page_length = bytes to copy for this page
384                  */
385                 gtt_page_base = offset & PAGE_MASK;
386                 gtt_page_offset = offset & ~PAGE_MASK;
387                 data_page_index = data_ptr / PAGE_SIZE - first_data_page;
388                 data_page_offset = data_ptr & ~PAGE_MASK;
389
390                 page_length = remain;
391                 if ((gtt_page_offset + page_length) > PAGE_SIZE)
392                         page_length = PAGE_SIZE - gtt_page_offset;
393                 if ((data_page_offset + page_length) > PAGE_SIZE)
394                         page_length = PAGE_SIZE - data_page_offset;
395
396                 ret = slow_kernel_write(dev_priv->mm.gtt_mapping,
397                                         gtt_page_base, gtt_page_offset,
398                                         user_pages[data_page_index],
399                                         data_page_offset,
400                                         page_length);
401
402                 /* If we get a fault while copying data, then (presumably) our
403                  * source page isn't available.  Return the error and we'll
404                  * retry in the slow path.
405                  */
406                 if (ret)
407                         goto out_unpin_object;
408
409                 remain -= page_length;
410                 offset += page_length;
411                 data_ptr += page_length;
412         }
413
414 out_unpin_object:
415         i915_gem_object_unpin(obj);
416 out_unlock:
417         mutex_unlock(&dev->struct_mutex);
418 out_unpin_pages:
419         for (i = 0; i < pinned_pages; i++)
420                 page_cache_release(user_pages[i]);
421         kfree(user_pages);
422
423         return ret;
424 }
425
426 static int
427 i915_gem_shmem_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
428                       struct drm_i915_gem_pwrite *args,
429                       struct drm_file *file_priv)
430 {
431         int ret;
432         loff_t offset;
433         ssize_t written;
434
435         mutex_lock(&dev->struct_mutex);
436
437         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
438         if (ret) {
439                 mutex_unlock(&dev->struct_mutex);
440                 return ret;
441         }
442
443         offset = args->offset;
444
445         written = vfs_write(obj->filp,
446                             (char __user *)(uintptr_t) args->data_ptr,
447                             args->size, &offset);
448         if (written != args->size) {
449                 mutex_unlock(&dev->struct_mutex);
450                 if (written < 0)
451                         return written;
452                 else
453                         return -EINVAL;
454         }
455
456         mutex_unlock(&dev->struct_mutex);
457
458         return 0;
459 }
460
461 /**
462  * Writes data to the object referenced by handle.
463  *
464  * On error, the contents of the buffer that were to be modified are undefined.
465  */
466 int
467 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
468                       struct drm_file *file_priv)
469 {
470         struct drm_i915_gem_pwrite *args = data;
471         struct drm_gem_object *obj;
472         struct drm_i915_gem_object *obj_priv;
473         int ret = 0;
474
475         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
476         if (obj == NULL)
477                 return -EBADF;
478         obj_priv = obj->driver_private;
479
480         /* Bounds check destination.
481          *
482          * XXX: This could use review for overflow issues...
483          */
484         if (args->offset > obj->size || args->size > obj->size ||
485             args->offset + args->size > obj->size) {
486                 drm_gem_object_unreference(obj);
487                 return -EINVAL;
488         }
489
490         /* We can only do the GTT pwrite on untiled buffers, as otherwise
491          * it would end up going through the fenced access, and we'll get
492          * different detiling behavior between reading and writing.
493          * pread/pwrite currently are reading and writing from the CPU
494          * perspective, requiring manual detiling by the client.
495          */
496         if (obj_priv->phys_obj)
497                 ret = i915_gem_phys_pwrite(dev, obj, args, file_priv);
498         else if (obj_priv->tiling_mode == I915_TILING_NONE &&
499                  dev->gtt_total != 0) {
500                 ret = i915_gem_gtt_pwrite_fast(dev, obj, args, file_priv);
501                 if (ret == -EFAULT) {
502                         ret = i915_gem_gtt_pwrite_slow(dev, obj, args,
503                                                        file_priv);
504                 }
505         } else
506                 ret = i915_gem_shmem_pwrite(dev, obj, args, file_priv);
507
508 #if WATCH_PWRITE
509         if (ret)
510                 DRM_INFO("pwrite failed %d\n", ret);
511 #endif
512
513         drm_gem_object_unreference(obj);
514
515         return ret;
516 }
517
518 /**
519  * Called when user space prepares to use an object with the CPU, either
520  * through the mmap ioctl's mapping or a GTT mapping.
521  */
522 int
523 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
524                           struct drm_file *file_priv)
525 {
526         struct drm_i915_gem_set_domain *args = data;
527         struct drm_gem_object *obj;
528         uint32_t read_domains = args->read_domains;
529         uint32_t write_domain = args->write_domain;
530         int ret;
531
532         if (!(dev->driver->driver_features & DRIVER_GEM))
533                 return -ENODEV;
534
535         /* Only handle setting domains to types used by the CPU. */
536         if (write_domain & ~(I915_GEM_DOMAIN_CPU | I915_GEM_DOMAIN_GTT))
537                 return -EINVAL;
538
539         if (read_domains & ~(I915_GEM_DOMAIN_CPU | I915_GEM_DOMAIN_GTT))
540                 return -EINVAL;
541
542         /* Having something in the write domain implies it's in the read
543          * domain, and only that read domain.  Enforce that in the request.
544          */
545         if (write_domain != 0 && read_domains != write_domain)
546                 return -EINVAL;
547
548         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
549         if (obj == NULL)
550                 return -EBADF;
551
552         mutex_lock(&dev->struct_mutex);
553 #if WATCH_BUF
554         DRM_INFO("set_domain_ioctl %p(%d), %08x %08x\n",
555                  obj, obj->size, read_domains, write_domain);
556 #endif
557         if (read_domains & I915_GEM_DOMAIN_GTT) {
558                 ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
559
560                 /* Silently promote "you're not bound, there was nothing to do"
561                  * to success, since the client was just asking us to
562                  * make sure everything was done.
563                  */
564                 if (ret == -EINVAL)
565                         ret = 0;
566         } else {
567                 ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
568         }
569
570         drm_gem_object_unreference(obj);
571         mutex_unlock(&dev->struct_mutex);
572         return ret;
573 }
574
575 /**
576  * Called when user space has done writes to this buffer
577  */
578 int
579 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
580                       struct drm_file *file_priv)
581 {
582         struct drm_i915_gem_sw_finish *args = data;
583         struct drm_gem_object *obj;
584         struct drm_i915_gem_object *obj_priv;
585         int ret = 0;
586
587         if (!(dev->driver->driver_features & DRIVER_GEM))
588                 return -ENODEV;
589
590         mutex_lock(&dev->struct_mutex);
591         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
592         if (obj == NULL) {
593                 mutex_unlock(&dev->struct_mutex);
594                 return -EBADF;
595         }
596
597 #if WATCH_BUF
598         DRM_INFO("%s: sw_finish %d (%p %d)\n",
599                  __func__, args->handle, obj, obj->size);
600 #endif
601         obj_priv = obj->driver_private;
602
603         /* Pinned buffers may be scanout, so flush the cache */
604         if (obj_priv->pin_count)
605                 i915_gem_object_flush_cpu_write_domain(obj);
606
607         drm_gem_object_unreference(obj);
608         mutex_unlock(&dev->struct_mutex);
609         return ret;
610 }
611
612 /**
613  * Maps the contents of an object, returning the address it is mapped
614  * into.
615  *
616  * While the mapping holds a reference on the contents of the object, it doesn't
617  * imply a ref on the object itself.
618  */
619 int
620 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
621                    struct drm_file *file_priv)
622 {
623         struct drm_i915_gem_mmap *args = data;
624         struct drm_gem_object *obj;
625         loff_t offset;
626         unsigned long addr;
627
628         if (!(dev->driver->driver_features & DRIVER_GEM))
629                 return -ENODEV;
630
631         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
632         if (obj == NULL)
633                 return -EBADF;
634
635         offset = args->offset;
636
637         down_write(&current->mm->mmap_sem);
638         addr = do_mmap(obj->filp, 0, args->size,
639                        PROT_READ | PROT_WRITE, MAP_SHARED,
640                        args->offset);
641         up_write(&current->mm->mmap_sem);
642         mutex_lock(&dev->struct_mutex);
643         drm_gem_object_unreference(obj);
644         mutex_unlock(&dev->struct_mutex);
645         if (IS_ERR((void *)addr))
646                 return addr;
647
648         args->addr_ptr = (uint64_t) addr;
649
650         return 0;
651 }
652
653 /**
654  * i915_gem_fault - fault a page into the GTT
655  * vma: VMA in question
656  * vmf: fault info
657  *
658  * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
659  * from userspace.  The fault handler takes care of binding the object to
660  * the GTT (if needed), allocating and programming a fence register (again,
661  * only if needed based on whether the old reg is still valid or the object
662  * is tiled) and inserting a new PTE into the faulting process.
663  *
664  * Note that the faulting process may involve evicting existing objects
665  * from the GTT and/or fence registers to make room.  So performance may
666  * suffer if the GTT working set is large or there are few fence registers
667  * left.
668  */
669 int i915_gem_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
670 {
671         struct drm_gem_object *obj = vma->vm_private_data;
672         struct drm_device *dev = obj->dev;
673         struct drm_i915_private *dev_priv = dev->dev_private;
674         struct drm_i915_gem_object *obj_priv = obj->driver_private;
675         pgoff_t page_offset;
676         unsigned long pfn;
677         int ret = 0;
678         bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
679
680         /* We don't use vmf->pgoff since that has the fake offset */
681         page_offset = ((unsigned long)vmf->virtual_address - vma->vm_start) >>
682                 PAGE_SHIFT;
683
684         /* Now bind it into the GTT if needed */
685         mutex_lock(&dev->struct_mutex);
686         if (!obj_priv->gtt_space) {
687                 ret = i915_gem_object_bind_to_gtt(obj, obj_priv->gtt_alignment);
688                 if (ret) {
689                         mutex_unlock(&dev->struct_mutex);
690                         return VM_FAULT_SIGBUS;
691                 }
692                 list_add(&obj_priv->list, &dev_priv->mm.inactive_list);
693         }
694
695         /* Need a new fence register? */
696         if (obj_priv->fence_reg == I915_FENCE_REG_NONE &&
697             obj_priv->tiling_mode != I915_TILING_NONE) {
698                 ret = i915_gem_object_get_fence_reg(obj, write);
699                 if (ret) {
700                         mutex_unlock(&dev->struct_mutex);
701                         return VM_FAULT_SIGBUS;
702                 }
703         }
704
705         pfn = ((dev->agp->base + obj_priv->gtt_offset) >> PAGE_SHIFT) +
706                 page_offset;
707
708         /* Finally, remap it using the new GTT offset */
709         ret = vm_insert_pfn(vma, (unsigned long)vmf->virtual_address, pfn);
710
711         mutex_unlock(&dev->struct_mutex);
712
713         switch (ret) {
714         case -ENOMEM:
715         case -EAGAIN:
716                 return VM_FAULT_OOM;
717         case -EFAULT:
718                 return VM_FAULT_SIGBUS;
719         default:
720                 return VM_FAULT_NOPAGE;
721         }
722 }
723
724 /**
725  * i915_gem_create_mmap_offset - create a fake mmap offset for an object
726  * @obj: obj in question
727  *
728  * GEM memory mapping works by handing back to userspace a fake mmap offset
729  * it can use in a subsequent mmap(2) call.  The DRM core code then looks
730  * up the object based on the offset and sets up the various memory mapping
731  * structures.
732  *
733  * This routine allocates and attaches a fake offset for @obj.
734  */
735 static int
736 i915_gem_create_mmap_offset(struct drm_gem_object *obj)
737 {
738         struct drm_device *dev = obj->dev;
739         struct drm_gem_mm *mm = dev->mm_private;
740         struct drm_i915_gem_object *obj_priv = obj->driver_private;
741         struct drm_map_list *list;
742         struct drm_map *map;
743         int ret = 0;
744
745         /* Set the object up for mmap'ing */
746         list = &obj->map_list;
747         list->map = drm_calloc(1, sizeof(struct drm_map_list),
748                                DRM_MEM_DRIVER);
749         if (!list->map)
750                 return -ENOMEM;
751
752         map = list->map;
753         map->type = _DRM_GEM;
754         map->size = obj->size;
755         map->handle = obj;
756
757         /* Get a DRM GEM mmap offset allocated... */
758         list->file_offset_node = drm_mm_search_free(&mm->offset_manager,
759                                                     obj->size / PAGE_SIZE, 0, 0);
760         if (!list->file_offset_node) {
761                 DRM_ERROR("failed to allocate offset for bo %d\n", obj->name);
762                 ret = -ENOMEM;
763                 goto out_free_list;
764         }
765
766         list->file_offset_node = drm_mm_get_block(list->file_offset_node,
767                                                   obj->size / PAGE_SIZE, 0);
768         if (!list->file_offset_node) {
769                 ret = -ENOMEM;
770                 goto out_free_list;
771         }
772
773         list->hash.key = list->file_offset_node->start;
774         if (drm_ht_insert_item(&mm->offset_hash, &list->hash)) {
775                 DRM_ERROR("failed to add to map hash\n");
776                 goto out_free_mm;
777         }
778
779         /* By now we should be all set, any drm_mmap request on the offset
780          * below will get to our mmap & fault handler */
781         obj_priv->mmap_offset = ((uint64_t) list->hash.key) << PAGE_SHIFT;
782
783         return 0;
784
785 out_free_mm:
786         drm_mm_put_block(list->file_offset_node);
787 out_free_list:
788         drm_free(list->map, sizeof(struct drm_map_list), DRM_MEM_DRIVER);
789
790         return ret;
791 }
792
793 static void
794 i915_gem_free_mmap_offset(struct drm_gem_object *obj)
795 {
796         struct drm_device *dev = obj->dev;
797         struct drm_i915_gem_object *obj_priv = obj->driver_private;
798         struct drm_gem_mm *mm = dev->mm_private;
799         struct drm_map_list *list;
800
801         list = &obj->map_list;
802         drm_ht_remove_item(&mm->offset_hash, &list->hash);
803
804         if (list->file_offset_node) {
805                 drm_mm_put_block(list->file_offset_node);
806                 list->file_offset_node = NULL;
807         }
808
809         if (list->map) {
810                 drm_free(list->map, sizeof(struct drm_map), DRM_MEM_DRIVER);
811                 list->map = NULL;
812         }
813
814         obj_priv->mmap_offset = 0;
815 }
816
817 /**
818  * i915_gem_get_gtt_alignment - return required GTT alignment for an object
819  * @obj: object to check
820  *
821  * Return the required GTT alignment for an object, taking into account
822  * potential fence register mapping if needed.
823  */
824 static uint32_t
825 i915_gem_get_gtt_alignment(struct drm_gem_object *obj)
826 {
827         struct drm_device *dev = obj->dev;
828         struct drm_i915_gem_object *obj_priv = obj->driver_private;
829         int start, i;
830
831         /*
832          * Minimum alignment is 4k (GTT page size), but might be greater
833          * if a fence register is needed for the object.
834          */
835         if (IS_I965G(dev) || obj_priv->tiling_mode == I915_TILING_NONE)
836                 return 4096;
837
838         /*
839          * Previous chips need to be aligned to the size of the smallest
840          * fence register that can contain the object.
841          */
842         if (IS_I9XX(dev))
843                 start = 1024*1024;
844         else
845                 start = 512*1024;
846
847         for (i = start; i < obj->size; i <<= 1)
848                 ;
849
850         return i;
851 }
852
853 /**
854  * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
855  * @dev: DRM device
856  * @data: GTT mapping ioctl data
857  * @file_priv: GEM object info
858  *
859  * Simply returns the fake offset to userspace so it can mmap it.
860  * The mmap call will end up in drm_gem_mmap(), which will set things
861  * up so we can get faults in the handler above.
862  *
863  * The fault handler will take care of binding the object into the GTT
864  * (since it may have been evicted to make room for something), allocating
865  * a fence register, and mapping the appropriate aperture address into
866  * userspace.
867  */
868 int
869 i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
870                         struct drm_file *file_priv)
871 {
872         struct drm_i915_gem_mmap_gtt *args = data;
873         struct drm_i915_private *dev_priv = dev->dev_private;
874         struct drm_gem_object *obj;
875         struct drm_i915_gem_object *obj_priv;
876         int ret;
877
878         if (!(dev->driver->driver_features & DRIVER_GEM))
879                 return -ENODEV;
880
881         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
882         if (obj == NULL)
883                 return -EBADF;
884
885         mutex_lock(&dev->struct_mutex);
886
887         obj_priv = obj->driver_private;
888
889         if (!obj_priv->mmap_offset) {
890                 ret = i915_gem_create_mmap_offset(obj);
891                 if (ret) {
892                         drm_gem_object_unreference(obj);
893                         mutex_unlock(&dev->struct_mutex);
894                         return ret;
895                 }
896         }
897
898         args->offset = obj_priv->mmap_offset;
899
900         obj_priv->gtt_alignment = i915_gem_get_gtt_alignment(obj);
901
902         /* Make sure the alignment is correct for fence regs etc */
903         if (obj_priv->agp_mem &&
904             (obj_priv->gtt_offset & (obj_priv->gtt_alignment - 1))) {
905                 drm_gem_object_unreference(obj);
906                 mutex_unlock(&dev->struct_mutex);
907                 return -EINVAL;
908         }
909
910         /*
911          * Pull it into the GTT so that we have a page list (makes the
912          * initial fault faster and any subsequent flushing possible).
913          */
914         if (!obj_priv->agp_mem) {
915                 ret = i915_gem_object_bind_to_gtt(obj, obj_priv->gtt_alignment);
916                 if (ret) {
917                         drm_gem_object_unreference(obj);
918                         mutex_unlock(&dev->struct_mutex);
919                         return ret;
920                 }
921                 list_add(&obj_priv->list, &dev_priv->mm.inactive_list);
922         }
923
924         drm_gem_object_unreference(obj);
925         mutex_unlock(&dev->struct_mutex);
926
927         return 0;
928 }
929
930 static void
931 i915_gem_object_free_page_list(struct drm_gem_object *obj)
932 {
933         struct drm_i915_gem_object *obj_priv = obj->driver_private;
934         int page_count = obj->size / PAGE_SIZE;
935         int i;
936
937         if (obj_priv->page_list == NULL)
938                 return;
939
940
941         for (i = 0; i < page_count; i++)
942                 if (obj_priv->page_list[i] != NULL) {
943                         if (obj_priv->dirty)
944                                 set_page_dirty(obj_priv->page_list[i]);
945                         mark_page_accessed(obj_priv->page_list[i]);
946                         page_cache_release(obj_priv->page_list[i]);
947                 }
948         obj_priv->dirty = 0;
949
950         drm_free(obj_priv->page_list,
951                  page_count * sizeof(struct page *),
952                  DRM_MEM_DRIVER);
953         obj_priv->page_list = NULL;
954 }
955
956 static void
957 i915_gem_object_move_to_active(struct drm_gem_object *obj, uint32_t seqno)
958 {
959         struct drm_device *dev = obj->dev;
960         drm_i915_private_t *dev_priv = dev->dev_private;
961         struct drm_i915_gem_object *obj_priv = obj->driver_private;
962
963         /* Add a reference if we're newly entering the active list. */
964         if (!obj_priv->active) {
965                 drm_gem_object_reference(obj);
966                 obj_priv->active = 1;
967         }
968         /* Move from whatever list we were on to the tail of execution. */
969         list_move_tail(&obj_priv->list,
970                        &dev_priv->mm.active_list);
971         obj_priv->last_rendering_seqno = seqno;
972 }
973
974 static void
975 i915_gem_object_move_to_flushing(struct drm_gem_object *obj)
976 {
977         struct drm_device *dev = obj->dev;
978         drm_i915_private_t *dev_priv = dev->dev_private;
979         struct drm_i915_gem_object *obj_priv = obj->driver_private;
980
981         BUG_ON(!obj_priv->active);
982         list_move_tail(&obj_priv->list, &dev_priv->mm.flushing_list);
983         obj_priv->last_rendering_seqno = 0;
984 }
985
986 static void
987 i915_gem_object_move_to_inactive(struct drm_gem_object *obj)
988 {
989         struct drm_device *dev = obj->dev;
990         drm_i915_private_t *dev_priv = dev->dev_private;
991         struct drm_i915_gem_object *obj_priv = obj->driver_private;
992
993         i915_verify_inactive(dev, __FILE__, __LINE__);
994         if (obj_priv->pin_count != 0)
995                 list_del_init(&obj_priv->list);
996         else
997                 list_move_tail(&obj_priv->list, &dev_priv->mm.inactive_list);
998
999         obj_priv->last_rendering_seqno = 0;
1000         if (obj_priv->active) {
1001                 obj_priv->active = 0;
1002                 drm_gem_object_unreference(obj);
1003         }
1004         i915_verify_inactive(dev, __FILE__, __LINE__);
1005 }
1006
1007 /**
1008  * Creates a new sequence number, emitting a write of it to the status page
1009  * plus an interrupt, which will trigger i915_user_interrupt_handler.
1010  *
1011  * Must be called with struct_lock held.
1012  *
1013  * Returned sequence numbers are nonzero on success.
1014  */
1015 static uint32_t
1016 i915_add_request(struct drm_device *dev, uint32_t flush_domains)
1017 {
1018         drm_i915_private_t *dev_priv = dev->dev_private;
1019         struct drm_i915_gem_request *request;
1020         uint32_t seqno;
1021         int was_empty;
1022         RING_LOCALS;
1023
1024         request = drm_calloc(1, sizeof(*request), DRM_MEM_DRIVER);
1025         if (request == NULL)
1026                 return 0;
1027
1028         /* Grab the seqno we're going to make this request be, and bump the
1029          * next (skipping 0 so it can be the reserved no-seqno value).
1030          */
1031         seqno = dev_priv->mm.next_gem_seqno;
1032         dev_priv->mm.next_gem_seqno++;
1033         if (dev_priv->mm.next_gem_seqno == 0)
1034                 dev_priv->mm.next_gem_seqno++;
1035
1036         BEGIN_LP_RING(4);
1037         OUT_RING(MI_STORE_DWORD_INDEX);
1038         OUT_RING(I915_GEM_HWS_INDEX << MI_STORE_DWORD_INDEX_SHIFT);
1039         OUT_RING(seqno);
1040
1041         OUT_RING(MI_USER_INTERRUPT);
1042         ADVANCE_LP_RING();
1043
1044         DRM_DEBUG("%d\n", seqno);
1045
1046         request->seqno = seqno;
1047         request->emitted_jiffies = jiffies;
1048         was_empty = list_empty(&dev_priv->mm.request_list);
1049         list_add_tail(&request->list, &dev_priv->mm.request_list);
1050
1051         /* Associate any objects on the flushing list matching the write
1052          * domain we're flushing with our flush.
1053          */
1054         if (flush_domains != 0) {
1055                 struct drm_i915_gem_object *obj_priv, *next;
1056
1057                 list_for_each_entry_safe(obj_priv, next,
1058                                          &dev_priv->mm.flushing_list, list) {
1059                         struct drm_gem_object *obj = obj_priv->obj;
1060
1061                         if ((obj->write_domain & flush_domains) ==
1062                             obj->write_domain) {
1063                                 obj->write_domain = 0;
1064                                 i915_gem_object_move_to_active(obj, seqno);
1065                         }
1066                 }
1067
1068         }
1069
1070         if (was_empty && !dev_priv->mm.suspended)
1071                 schedule_delayed_work(&dev_priv->mm.retire_work, HZ);
1072         return seqno;
1073 }
1074
1075 /**
1076  * Command execution barrier
1077  *
1078  * Ensures that all commands in the ring are finished
1079  * before signalling the CPU
1080  */
1081 static uint32_t
1082 i915_retire_commands(struct drm_device *dev)
1083 {
1084         drm_i915_private_t *dev_priv = dev->dev_private;
1085         uint32_t cmd = MI_FLUSH | MI_NO_WRITE_FLUSH;
1086         uint32_t flush_domains = 0;
1087         RING_LOCALS;
1088
1089         /* The sampler always gets flushed on i965 (sigh) */
1090         if (IS_I965G(dev))
1091                 flush_domains |= I915_GEM_DOMAIN_SAMPLER;
1092         BEGIN_LP_RING(2);
1093         OUT_RING(cmd);
1094         OUT_RING(0); /* noop */
1095         ADVANCE_LP_RING();
1096         return flush_domains;
1097 }
1098
1099 /**
1100  * Moves buffers associated only with the given active seqno from the active
1101  * to inactive list, potentially freeing them.
1102  */
1103 static void
1104 i915_gem_retire_request(struct drm_device *dev,
1105                         struct drm_i915_gem_request *request)
1106 {
1107         drm_i915_private_t *dev_priv = dev->dev_private;
1108
1109         /* Move any buffers on the active list that are no longer referenced
1110          * by the ringbuffer to the flushing/inactive lists as appropriate.
1111          */
1112         while (!list_empty(&dev_priv->mm.active_list)) {
1113                 struct drm_gem_object *obj;
1114                 struct drm_i915_gem_object *obj_priv;
1115
1116                 obj_priv = list_first_entry(&dev_priv->mm.active_list,
1117                                             struct drm_i915_gem_object,
1118                                             list);
1119                 obj = obj_priv->obj;
1120
1121                 /* If the seqno being retired doesn't match the oldest in the
1122                  * list, then the oldest in the list must still be newer than
1123                  * this seqno.
1124                  */
1125                 if (obj_priv->last_rendering_seqno != request->seqno)
1126                         return;
1127
1128 #if WATCH_LRU
1129                 DRM_INFO("%s: retire %d moves to inactive list %p\n",
1130                          __func__, request->seqno, obj);
1131 #endif
1132
1133                 if (obj->write_domain != 0)
1134                         i915_gem_object_move_to_flushing(obj);
1135                 else
1136                         i915_gem_object_move_to_inactive(obj);
1137         }
1138 }
1139
1140 /**
1141  * Returns true if seq1 is later than seq2.
1142  */
1143 static int
1144 i915_seqno_passed(uint32_t seq1, uint32_t seq2)
1145 {
1146         return (int32_t)(seq1 - seq2) >= 0;
1147 }
1148
1149 uint32_t
1150 i915_get_gem_seqno(struct drm_device *dev)
1151 {
1152         drm_i915_private_t *dev_priv = dev->dev_private;
1153
1154         return READ_HWSP(dev_priv, I915_GEM_HWS_INDEX);
1155 }
1156
1157 /**
1158  * This function clears the request list as sequence numbers are passed.
1159  */
1160 void
1161 i915_gem_retire_requests(struct drm_device *dev)
1162 {
1163         drm_i915_private_t *dev_priv = dev->dev_private;
1164         uint32_t seqno;
1165
1166         if (!dev_priv->hw_status_page)
1167                 return;
1168
1169         seqno = i915_get_gem_seqno(dev);
1170
1171         while (!list_empty(&dev_priv->mm.request_list)) {
1172                 struct drm_i915_gem_request *request;
1173                 uint32_t retiring_seqno;
1174
1175                 request = list_first_entry(&dev_priv->mm.request_list,
1176                                            struct drm_i915_gem_request,
1177                                            list);
1178                 retiring_seqno = request->seqno;
1179
1180                 if (i915_seqno_passed(seqno, retiring_seqno) ||
1181                     dev_priv->mm.wedged) {
1182                         i915_gem_retire_request(dev, request);
1183
1184                         list_del(&request->list);
1185                         drm_free(request, sizeof(*request), DRM_MEM_DRIVER);
1186                 } else
1187                         break;
1188         }
1189 }
1190
1191 void
1192 i915_gem_retire_work_handler(struct work_struct *work)
1193 {
1194         drm_i915_private_t *dev_priv;
1195         struct drm_device *dev;
1196
1197         dev_priv = container_of(work, drm_i915_private_t,
1198                                 mm.retire_work.work);
1199         dev = dev_priv->dev;
1200
1201         mutex_lock(&dev->struct_mutex);
1202         i915_gem_retire_requests(dev);
1203         if (!dev_priv->mm.suspended &&
1204             !list_empty(&dev_priv->mm.request_list))
1205                 schedule_delayed_work(&dev_priv->mm.retire_work, HZ);
1206         mutex_unlock(&dev->struct_mutex);
1207 }
1208
1209 /**
1210  * Waits for a sequence number to be signaled, and cleans up the
1211  * request and object lists appropriately for that event.
1212  */
1213 static int
1214 i915_wait_request(struct drm_device *dev, uint32_t seqno)
1215 {
1216         drm_i915_private_t *dev_priv = dev->dev_private;
1217         int ret = 0;
1218
1219         BUG_ON(seqno == 0);
1220
1221         if (!i915_seqno_passed(i915_get_gem_seqno(dev), seqno)) {
1222                 dev_priv->mm.waiting_gem_seqno = seqno;
1223                 i915_user_irq_get(dev);
1224                 ret = wait_event_interruptible(dev_priv->irq_queue,
1225                                                i915_seqno_passed(i915_get_gem_seqno(dev),
1226                                                                  seqno) ||
1227                                                dev_priv->mm.wedged);
1228                 i915_user_irq_put(dev);
1229                 dev_priv->mm.waiting_gem_seqno = 0;
1230         }
1231         if (dev_priv->mm.wedged)
1232                 ret = -EIO;
1233
1234         if (ret && ret != -ERESTARTSYS)
1235                 DRM_ERROR("%s returns %d (awaiting %d at %d)\n",
1236                           __func__, ret, seqno, i915_get_gem_seqno(dev));
1237
1238         /* Directly dispatch request retiring.  While we have the work queue
1239          * to handle this, the waiter on a request often wants an associated
1240          * buffer to have made it to the inactive list, and we would need
1241          * a separate wait queue to handle that.
1242          */
1243         if (ret == 0)
1244                 i915_gem_retire_requests(dev);
1245
1246         return ret;
1247 }
1248
1249 static void
1250 i915_gem_flush(struct drm_device *dev,
1251                uint32_t invalidate_domains,
1252                uint32_t flush_domains)
1253 {
1254         drm_i915_private_t *dev_priv = dev->dev_private;
1255         uint32_t cmd;
1256         RING_LOCALS;
1257
1258 #if WATCH_EXEC
1259         DRM_INFO("%s: invalidate %08x flush %08x\n", __func__,
1260                   invalidate_domains, flush_domains);
1261 #endif
1262
1263         if (flush_domains & I915_GEM_DOMAIN_CPU)
1264                 drm_agp_chipset_flush(dev);
1265
1266         if ((invalidate_domains | flush_domains) & ~(I915_GEM_DOMAIN_CPU |
1267                                                      I915_GEM_DOMAIN_GTT)) {
1268                 /*
1269                  * read/write caches:
1270                  *
1271                  * I915_GEM_DOMAIN_RENDER is always invalidated, but is
1272                  * only flushed if MI_NO_WRITE_FLUSH is unset.  On 965, it is
1273                  * also flushed at 2d versus 3d pipeline switches.
1274                  *
1275                  * read-only caches:
1276                  *
1277                  * I915_GEM_DOMAIN_SAMPLER is flushed on pre-965 if
1278                  * MI_READ_FLUSH is set, and is always flushed on 965.
1279                  *
1280                  * I915_GEM_DOMAIN_COMMAND may not exist?
1281                  *
1282                  * I915_GEM_DOMAIN_INSTRUCTION, which exists on 965, is
1283                  * invalidated when MI_EXE_FLUSH is set.
1284                  *
1285                  * I915_GEM_DOMAIN_VERTEX, which exists on 965, is
1286                  * invalidated with every MI_FLUSH.
1287                  *
1288                  * TLBs:
1289                  *
1290                  * On 965, TLBs associated with I915_GEM_DOMAIN_COMMAND
1291                  * and I915_GEM_DOMAIN_CPU in are invalidated at PTE write and
1292                  * I915_GEM_DOMAIN_RENDER and I915_GEM_DOMAIN_SAMPLER
1293                  * are flushed at any MI_FLUSH.
1294                  */
1295
1296                 cmd = MI_FLUSH | MI_NO_WRITE_FLUSH;
1297                 if ((invalidate_domains|flush_domains) &
1298                     I915_GEM_DOMAIN_RENDER)
1299                         cmd &= ~MI_NO_WRITE_FLUSH;
1300                 if (!IS_I965G(dev)) {
1301                         /*
1302                          * On the 965, the sampler cache always gets flushed
1303                          * and this bit is reserved.
1304                          */
1305                         if (invalidate_domains & I915_GEM_DOMAIN_SAMPLER)
1306                                 cmd |= MI_READ_FLUSH;
1307                 }
1308                 if (invalidate_domains & I915_GEM_DOMAIN_INSTRUCTION)
1309                         cmd |= MI_EXE_FLUSH;
1310
1311 #if WATCH_EXEC
1312                 DRM_INFO("%s: queue flush %08x to ring\n", __func__, cmd);
1313 #endif
1314                 BEGIN_LP_RING(2);
1315                 OUT_RING(cmd);
1316                 OUT_RING(0); /* noop */
1317                 ADVANCE_LP_RING();
1318         }
1319 }
1320
1321 /**
1322  * Ensures that all rendering to the object has completed and the object is
1323  * safe to unbind from the GTT or access from the CPU.
1324  */
1325 static int
1326 i915_gem_object_wait_rendering(struct drm_gem_object *obj)
1327 {
1328         struct drm_device *dev = obj->dev;
1329         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1330         int ret;
1331
1332         /* This function only exists to support waiting for existing rendering,
1333          * not for emitting required flushes.
1334          */
1335         BUG_ON((obj->write_domain & I915_GEM_GPU_DOMAINS) != 0);
1336
1337         /* If there is rendering queued on the buffer being evicted, wait for
1338          * it.
1339          */
1340         if (obj_priv->active) {
1341 #if WATCH_BUF
1342                 DRM_INFO("%s: object %p wait for seqno %08x\n",
1343                           __func__, obj, obj_priv->last_rendering_seqno);
1344 #endif
1345                 ret = i915_wait_request(dev, obj_priv->last_rendering_seqno);
1346                 if (ret != 0)
1347                         return ret;
1348         }
1349
1350         return 0;
1351 }
1352
1353 /**
1354  * Unbinds an object from the GTT aperture.
1355  */
1356 int
1357 i915_gem_object_unbind(struct drm_gem_object *obj)
1358 {
1359         struct drm_device *dev = obj->dev;
1360         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1361         loff_t offset;
1362         int ret = 0;
1363
1364 #if WATCH_BUF
1365         DRM_INFO("%s:%d %p\n", __func__, __LINE__, obj);
1366         DRM_INFO("gtt_space %p\n", obj_priv->gtt_space);
1367 #endif
1368         if (obj_priv->gtt_space == NULL)
1369                 return 0;
1370
1371         if (obj_priv->pin_count != 0) {
1372                 DRM_ERROR("Attempting to unbind pinned buffer\n");
1373                 return -EINVAL;
1374         }
1375
1376         /* Move the object to the CPU domain to ensure that
1377          * any possible CPU writes while it's not in the GTT
1378          * are flushed when we go to remap it. This will
1379          * also ensure that all pending GPU writes are finished
1380          * before we unbind.
1381          */
1382         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
1383         if (ret) {
1384                 if (ret != -ERESTARTSYS)
1385                         DRM_ERROR("set_domain failed: %d\n", ret);
1386                 return ret;
1387         }
1388
1389         if (obj_priv->agp_mem != NULL) {
1390                 drm_unbind_agp(obj_priv->agp_mem);
1391                 drm_free_agp(obj_priv->agp_mem, obj->size / PAGE_SIZE);
1392                 obj_priv->agp_mem = NULL;
1393         }
1394
1395         BUG_ON(obj_priv->active);
1396
1397         /* blow away mappings if mapped through GTT */
1398         offset = ((loff_t) obj->map_list.hash.key) << PAGE_SHIFT;
1399         if (dev->dev_mapping)
1400                 unmap_mapping_range(dev->dev_mapping, offset, obj->size, 1);
1401
1402         if (obj_priv->fence_reg != I915_FENCE_REG_NONE)
1403                 i915_gem_clear_fence_reg(obj);
1404
1405         i915_gem_object_free_page_list(obj);
1406
1407         if (obj_priv->gtt_space) {
1408                 atomic_dec(&dev->gtt_count);
1409                 atomic_sub(obj->size, &dev->gtt_memory);
1410
1411                 drm_mm_put_block(obj_priv->gtt_space);
1412                 obj_priv->gtt_space = NULL;
1413         }
1414
1415         /* Remove ourselves from the LRU list if present. */
1416         if (!list_empty(&obj_priv->list))
1417                 list_del_init(&obj_priv->list);
1418
1419         return 0;
1420 }
1421
1422 static int
1423 i915_gem_evict_something(struct drm_device *dev)
1424 {
1425         drm_i915_private_t *dev_priv = dev->dev_private;
1426         struct drm_gem_object *obj;
1427         struct drm_i915_gem_object *obj_priv;
1428         int ret = 0;
1429
1430         for (;;) {
1431                 /* If there's an inactive buffer available now, grab it
1432                  * and be done.
1433                  */
1434                 if (!list_empty(&dev_priv->mm.inactive_list)) {
1435                         obj_priv = list_first_entry(&dev_priv->mm.inactive_list,
1436                                                     struct drm_i915_gem_object,
1437                                                     list);
1438                         obj = obj_priv->obj;
1439                         BUG_ON(obj_priv->pin_count != 0);
1440 #if WATCH_LRU
1441                         DRM_INFO("%s: evicting %p\n", __func__, obj);
1442 #endif
1443                         BUG_ON(obj_priv->active);
1444
1445                         /* Wait on the rendering and unbind the buffer. */
1446                         ret = i915_gem_object_unbind(obj);
1447                         break;
1448                 }
1449
1450                 /* If we didn't get anything, but the ring is still processing
1451                  * things, wait for one of those things to finish and hopefully
1452                  * leave us a buffer to evict.
1453                  */
1454                 if (!list_empty(&dev_priv->mm.request_list)) {
1455                         struct drm_i915_gem_request *request;
1456
1457                         request = list_first_entry(&dev_priv->mm.request_list,
1458                                                    struct drm_i915_gem_request,
1459                                                    list);
1460
1461                         ret = i915_wait_request(dev, request->seqno);
1462                         if (ret)
1463                                 break;
1464
1465                         /* if waiting caused an object to become inactive,
1466                          * then loop around and wait for it. Otherwise, we
1467                          * assume that waiting freed and unbound something,
1468                          * so there should now be some space in the GTT
1469                          */
1470                         if (!list_empty(&dev_priv->mm.inactive_list))
1471                                 continue;
1472                         break;
1473                 }
1474
1475                 /* If we didn't have anything on the request list but there
1476                  * are buffers awaiting a flush, emit one and try again.
1477                  * When we wait on it, those buffers waiting for that flush
1478                  * will get moved to inactive.
1479                  */
1480                 if (!list_empty(&dev_priv->mm.flushing_list)) {
1481                         obj_priv = list_first_entry(&dev_priv->mm.flushing_list,
1482                                                     struct drm_i915_gem_object,
1483                                                     list);
1484                         obj = obj_priv->obj;
1485
1486                         i915_gem_flush(dev,
1487                                        obj->write_domain,
1488                                        obj->write_domain);
1489                         i915_add_request(dev, obj->write_domain);
1490
1491                         obj = NULL;
1492                         continue;
1493                 }
1494
1495                 DRM_ERROR("inactive empty %d request empty %d "
1496                           "flushing empty %d\n",
1497                           list_empty(&dev_priv->mm.inactive_list),
1498                           list_empty(&dev_priv->mm.request_list),
1499                           list_empty(&dev_priv->mm.flushing_list));
1500                 /* If we didn't do any of the above, there's nothing to be done
1501                  * and we just can't fit it in.
1502                  */
1503                 return -ENOMEM;
1504         }
1505         return ret;
1506 }
1507
1508 static int
1509 i915_gem_evict_everything(struct drm_device *dev)
1510 {
1511         int ret;
1512
1513         for (;;) {
1514                 ret = i915_gem_evict_something(dev);
1515                 if (ret != 0)
1516                         break;
1517         }
1518         if (ret == -ENOMEM)
1519                 return 0;
1520         return ret;
1521 }
1522
1523 static int
1524 i915_gem_object_get_page_list(struct drm_gem_object *obj)
1525 {
1526         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1527         int page_count, i;
1528         struct address_space *mapping;
1529         struct inode *inode;
1530         struct page *page;
1531         int ret;
1532
1533         if (obj_priv->page_list)
1534                 return 0;
1535
1536         /* Get the list of pages out of our struct file.  They'll be pinned
1537          * at this point until we release them.
1538          */
1539         page_count = obj->size / PAGE_SIZE;
1540         BUG_ON(obj_priv->page_list != NULL);
1541         obj_priv->page_list = drm_calloc(page_count, sizeof(struct page *),
1542                                          DRM_MEM_DRIVER);
1543         if (obj_priv->page_list == NULL) {
1544                 DRM_ERROR("Faled to allocate page list\n");
1545                 return -ENOMEM;
1546         }
1547
1548         inode = obj->filp->f_path.dentry->d_inode;
1549         mapping = inode->i_mapping;
1550         for (i = 0; i < page_count; i++) {
1551                 page = read_mapping_page(mapping, i, NULL);
1552                 if (IS_ERR(page)) {
1553                         ret = PTR_ERR(page);
1554                         DRM_ERROR("read_mapping_page failed: %d\n", ret);
1555                         i915_gem_object_free_page_list(obj);
1556                         return ret;
1557                 }
1558                 obj_priv->page_list[i] = page;
1559         }
1560         return 0;
1561 }
1562
1563 static void i965_write_fence_reg(struct drm_i915_fence_reg *reg)
1564 {
1565         struct drm_gem_object *obj = reg->obj;
1566         struct drm_device *dev = obj->dev;
1567         drm_i915_private_t *dev_priv = dev->dev_private;
1568         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1569         int regnum = obj_priv->fence_reg;
1570         uint64_t val;
1571
1572         val = (uint64_t)((obj_priv->gtt_offset + obj->size - 4096) &
1573                     0xfffff000) << 32;
1574         val |= obj_priv->gtt_offset & 0xfffff000;
1575         val |= ((obj_priv->stride / 128) - 1) << I965_FENCE_PITCH_SHIFT;
1576         if (obj_priv->tiling_mode == I915_TILING_Y)
1577                 val |= 1 << I965_FENCE_TILING_Y_SHIFT;
1578         val |= I965_FENCE_REG_VALID;
1579
1580         I915_WRITE64(FENCE_REG_965_0 + (regnum * 8), val);
1581 }
1582
1583 static void i915_write_fence_reg(struct drm_i915_fence_reg *reg)
1584 {
1585         struct drm_gem_object *obj = reg->obj;
1586         struct drm_device *dev = obj->dev;
1587         drm_i915_private_t *dev_priv = dev->dev_private;
1588         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1589         int regnum = obj_priv->fence_reg;
1590         int tile_width;
1591         uint32_t fence_reg, val;
1592         uint32_t pitch_val;
1593
1594         if ((obj_priv->gtt_offset & ~I915_FENCE_START_MASK) ||
1595             (obj_priv->gtt_offset & (obj->size - 1))) {
1596                 WARN(1, "%s: object 0x%08x not 1M or size (0x%zx) aligned\n",
1597                      __func__, obj_priv->gtt_offset, obj->size);
1598                 return;
1599         }
1600
1601         if (obj_priv->tiling_mode == I915_TILING_Y &&
1602             HAS_128_BYTE_Y_TILING(dev))
1603                 tile_width = 128;
1604         else
1605                 tile_width = 512;
1606
1607         /* Note: pitch better be a power of two tile widths */
1608         pitch_val = obj_priv->stride / tile_width;
1609         pitch_val = ffs(pitch_val) - 1;
1610
1611         val = obj_priv->gtt_offset;
1612         if (obj_priv->tiling_mode == I915_TILING_Y)
1613                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
1614         val |= I915_FENCE_SIZE_BITS(obj->size);
1615         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
1616         val |= I830_FENCE_REG_VALID;
1617
1618         if (regnum < 8)
1619                 fence_reg = FENCE_REG_830_0 + (regnum * 4);
1620         else
1621                 fence_reg = FENCE_REG_945_8 + ((regnum - 8) * 4);
1622         I915_WRITE(fence_reg, val);
1623 }
1624
1625 static void i830_write_fence_reg(struct drm_i915_fence_reg *reg)
1626 {
1627         struct drm_gem_object *obj = reg->obj;
1628         struct drm_device *dev = obj->dev;
1629         drm_i915_private_t *dev_priv = dev->dev_private;
1630         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1631         int regnum = obj_priv->fence_reg;
1632         uint32_t val;
1633         uint32_t pitch_val;
1634
1635         if ((obj_priv->gtt_offset & ~I915_FENCE_START_MASK) ||
1636             (obj_priv->gtt_offset & (obj->size - 1))) {
1637                 WARN(1, "%s: object 0x%08x not 1M or size aligned\n",
1638                      __func__, obj_priv->gtt_offset);
1639                 return;
1640         }
1641
1642         pitch_val = (obj_priv->stride / 128) - 1;
1643
1644         val = obj_priv->gtt_offset;
1645         if (obj_priv->tiling_mode == I915_TILING_Y)
1646                 val |= 1 << I830_FENCE_TILING_Y_SHIFT;
1647         val |= I830_FENCE_SIZE_BITS(obj->size);
1648         val |= pitch_val << I830_FENCE_PITCH_SHIFT;
1649         val |= I830_FENCE_REG_VALID;
1650
1651         I915_WRITE(FENCE_REG_830_0 + (regnum * 4), val);
1652
1653 }
1654
1655 /**
1656  * i915_gem_object_get_fence_reg - set up a fence reg for an object
1657  * @obj: object to map through a fence reg
1658  * @write: object is about to be written
1659  *
1660  * When mapping objects through the GTT, userspace wants to be able to write
1661  * to them without having to worry about swizzling if the object is tiled.
1662  *
1663  * This function walks the fence regs looking for a free one for @obj,
1664  * stealing one if it can't find any.
1665  *
1666  * It then sets up the reg based on the object's properties: address, pitch
1667  * and tiling format.
1668  */
1669 static int
1670 i915_gem_object_get_fence_reg(struct drm_gem_object *obj, bool write)
1671 {
1672         struct drm_device *dev = obj->dev;
1673         struct drm_i915_private *dev_priv = dev->dev_private;
1674         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1675         struct drm_i915_fence_reg *reg = NULL;
1676         struct drm_i915_gem_object *old_obj_priv = NULL;
1677         int i, ret, avail;
1678
1679         switch (obj_priv->tiling_mode) {
1680         case I915_TILING_NONE:
1681                 WARN(1, "allocating a fence for non-tiled object?\n");
1682                 break;
1683         case I915_TILING_X:
1684                 if (!obj_priv->stride)
1685                         return -EINVAL;
1686                 WARN((obj_priv->stride & (512 - 1)),
1687                      "object 0x%08x is X tiled but has non-512B pitch\n",
1688                      obj_priv->gtt_offset);
1689                 break;
1690         case I915_TILING_Y:
1691                 if (!obj_priv->stride)
1692                         return -EINVAL;
1693                 WARN((obj_priv->stride & (128 - 1)),
1694                      "object 0x%08x is Y tiled but has non-128B pitch\n",
1695                      obj_priv->gtt_offset);
1696                 break;
1697         }
1698
1699         /* First try to find a free reg */
1700 try_again:
1701         avail = 0;
1702         for (i = dev_priv->fence_reg_start; i < dev_priv->num_fence_regs; i++) {
1703                 reg = &dev_priv->fence_regs[i];
1704                 if (!reg->obj)
1705                         break;
1706
1707                 old_obj_priv = reg->obj->driver_private;
1708                 if (!old_obj_priv->pin_count)
1709                     avail++;
1710         }
1711
1712         /* None available, try to steal one or wait for a user to finish */
1713         if (i == dev_priv->num_fence_regs) {
1714                 uint32_t seqno = dev_priv->mm.next_gem_seqno;
1715                 loff_t offset;
1716
1717                 if (avail == 0)
1718                         return -ENOMEM;
1719
1720                 for (i = dev_priv->fence_reg_start;
1721                      i < dev_priv->num_fence_regs; i++) {
1722                         uint32_t this_seqno;
1723
1724                         reg = &dev_priv->fence_regs[i];
1725                         old_obj_priv = reg->obj->driver_private;
1726
1727                         if (old_obj_priv->pin_count)
1728                                 continue;
1729
1730                         /* i915 uses fences for GPU access to tiled buffers */
1731                         if (IS_I965G(dev) || !old_obj_priv->active)
1732                                 break;
1733
1734                         /* find the seqno of the first available fence */
1735                         this_seqno = old_obj_priv->last_rendering_seqno;
1736                         if (this_seqno != 0 &&
1737                             reg->obj->write_domain == 0 &&
1738                             i915_seqno_passed(seqno, this_seqno))
1739                                 seqno = this_seqno;
1740                 }
1741
1742                 /*
1743                  * Now things get ugly... we have to wait for one of the
1744                  * objects to finish before trying again.
1745                  */
1746                 if (i == dev_priv->num_fence_regs) {
1747                         if (seqno == dev_priv->mm.next_gem_seqno) {
1748                                 i915_gem_flush(dev,
1749                                                I915_GEM_GPU_DOMAINS,
1750                                                I915_GEM_GPU_DOMAINS);
1751                                 seqno = i915_add_request(dev,
1752                                                          I915_GEM_GPU_DOMAINS);
1753                                 if (seqno == 0)
1754                                         return -ENOMEM;
1755                         }
1756
1757                         ret = i915_wait_request(dev, seqno);
1758                         if (ret)
1759                                 return ret;
1760                         goto try_again;
1761                 }
1762
1763                 BUG_ON(old_obj_priv->active ||
1764                        (reg->obj->write_domain & I915_GEM_GPU_DOMAINS));
1765
1766                 /*
1767                  * Zap this virtual mapping so we can set up a fence again
1768                  * for this object next time we need it.
1769                  */
1770                 offset = ((loff_t) reg->obj->map_list.hash.key) << PAGE_SHIFT;
1771                 if (dev->dev_mapping)
1772                         unmap_mapping_range(dev->dev_mapping, offset,
1773                                             reg->obj->size, 1);
1774                 old_obj_priv->fence_reg = I915_FENCE_REG_NONE;
1775         }
1776
1777         obj_priv->fence_reg = i;
1778         reg->obj = obj;
1779
1780         if (IS_I965G(dev))
1781                 i965_write_fence_reg(reg);
1782         else if (IS_I9XX(dev))
1783                 i915_write_fence_reg(reg);
1784         else
1785                 i830_write_fence_reg(reg);
1786
1787         return 0;
1788 }
1789
1790 /**
1791  * i915_gem_clear_fence_reg - clear out fence register info
1792  * @obj: object to clear
1793  *
1794  * Zeroes out the fence register itself and clears out the associated
1795  * data structures in dev_priv and obj_priv.
1796  */
1797 static void
1798 i915_gem_clear_fence_reg(struct drm_gem_object *obj)
1799 {
1800         struct drm_device *dev = obj->dev;
1801         drm_i915_private_t *dev_priv = dev->dev_private;
1802         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1803
1804         if (IS_I965G(dev))
1805                 I915_WRITE64(FENCE_REG_965_0 + (obj_priv->fence_reg * 8), 0);
1806         else {
1807                 uint32_t fence_reg;
1808
1809                 if (obj_priv->fence_reg < 8)
1810                         fence_reg = FENCE_REG_830_0 + obj_priv->fence_reg * 4;
1811                 else
1812                         fence_reg = FENCE_REG_945_8 + (obj_priv->fence_reg -
1813                                                        8) * 4;
1814
1815                 I915_WRITE(fence_reg, 0);
1816         }
1817
1818         dev_priv->fence_regs[obj_priv->fence_reg].obj = NULL;
1819         obj_priv->fence_reg = I915_FENCE_REG_NONE;
1820 }
1821
1822 /**
1823  * Finds free space in the GTT aperture and binds the object there.
1824  */
1825 static int
1826 i915_gem_object_bind_to_gtt(struct drm_gem_object *obj, unsigned alignment)
1827 {
1828         struct drm_device *dev = obj->dev;
1829         drm_i915_private_t *dev_priv = dev->dev_private;
1830         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1831         struct drm_mm_node *free_space;
1832         int page_count, ret;
1833
1834         if (dev_priv->mm.suspended)
1835                 return -EBUSY;
1836         if (alignment == 0)
1837                 alignment = i915_gem_get_gtt_alignment(obj);
1838         if (alignment & (PAGE_SIZE - 1)) {
1839                 DRM_ERROR("Invalid object alignment requested %u\n", alignment);
1840                 return -EINVAL;
1841         }
1842
1843  search_free:
1844         free_space = drm_mm_search_free(&dev_priv->mm.gtt_space,
1845                                         obj->size, alignment, 0);
1846         if (free_space != NULL) {
1847                 obj_priv->gtt_space = drm_mm_get_block(free_space, obj->size,
1848                                                        alignment);
1849                 if (obj_priv->gtt_space != NULL) {
1850                         obj_priv->gtt_space->private = obj;
1851                         obj_priv->gtt_offset = obj_priv->gtt_space->start;
1852                 }
1853         }
1854         if (obj_priv->gtt_space == NULL) {
1855                 /* If the gtt is empty and we're still having trouble
1856                  * fitting our object in, we're out of memory.
1857                  */
1858 #if WATCH_LRU
1859                 DRM_INFO("%s: GTT full, evicting something\n", __func__);
1860 #endif
1861                 if (list_empty(&dev_priv->mm.inactive_list) &&
1862                     list_empty(&dev_priv->mm.flushing_list) &&
1863                     list_empty(&dev_priv->mm.active_list)) {
1864                         DRM_ERROR("GTT full, but LRU list empty\n");
1865                         return -ENOMEM;
1866                 }
1867
1868                 ret = i915_gem_evict_something(dev);
1869                 if (ret != 0) {
1870                         if (ret != -ERESTARTSYS)
1871                                 DRM_ERROR("Failed to evict a buffer %d\n", ret);
1872                         return ret;
1873                 }
1874                 goto search_free;
1875         }
1876
1877 #if WATCH_BUF
1878         DRM_INFO("Binding object of size %d at 0x%08x\n",
1879                  obj->size, obj_priv->gtt_offset);
1880 #endif
1881         ret = i915_gem_object_get_page_list(obj);
1882         if (ret) {
1883                 drm_mm_put_block(obj_priv->gtt_space);
1884                 obj_priv->gtt_space = NULL;
1885                 return ret;
1886         }
1887
1888         page_count = obj->size / PAGE_SIZE;
1889         /* Create an AGP memory structure pointing at our pages, and bind it
1890          * into the GTT.
1891          */
1892         obj_priv->agp_mem = drm_agp_bind_pages(dev,
1893                                                obj_priv->page_list,
1894                                                page_count,
1895                                                obj_priv->gtt_offset,
1896                                                obj_priv->agp_type);
1897         if (obj_priv->agp_mem == NULL) {
1898                 i915_gem_object_free_page_list(obj);
1899                 drm_mm_put_block(obj_priv->gtt_space);
1900                 obj_priv->gtt_space = NULL;
1901                 return -ENOMEM;
1902         }
1903         atomic_inc(&dev->gtt_count);
1904         atomic_add(obj->size, &dev->gtt_memory);
1905
1906         /* Assert that the object is not currently in any GPU domain. As it
1907          * wasn't in the GTT, there shouldn't be any way it could have been in
1908          * a GPU cache
1909          */
1910         BUG_ON(obj->read_domains & ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
1911         BUG_ON(obj->write_domain & ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
1912
1913         return 0;
1914 }
1915
1916 void
1917 i915_gem_clflush_object(struct drm_gem_object *obj)
1918 {
1919         struct drm_i915_gem_object      *obj_priv = obj->driver_private;
1920
1921         /* If we don't have a page list set up, then we're not pinned
1922          * to GPU, and we can ignore the cache flush because it'll happen
1923          * again at bind time.
1924          */
1925         if (obj_priv->page_list == NULL)
1926                 return;
1927
1928         drm_clflush_pages(obj_priv->page_list, obj->size / PAGE_SIZE);
1929 }
1930
1931 /** Flushes any GPU write domain for the object if it's dirty. */
1932 static void
1933 i915_gem_object_flush_gpu_write_domain(struct drm_gem_object *obj)
1934 {
1935         struct drm_device *dev = obj->dev;
1936         uint32_t seqno;
1937
1938         if ((obj->write_domain & I915_GEM_GPU_DOMAINS) == 0)
1939                 return;
1940
1941         /* Queue the GPU write cache flushing we need. */
1942         i915_gem_flush(dev, 0, obj->write_domain);
1943         seqno = i915_add_request(dev, obj->write_domain);
1944         obj->write_domain = 0;
1945         i915_gem_object_move_to_active(obj, seqno);
1946 }
1947
1948 /** Flushes the GTT write domain for the object if it's dirty. */
1949 static void
1950 i915_gem_object_flush_gtt_write_domain(struct drm_gem_object *obj)
1951 {
1952         if (obj->write_domain != I915_GEM_DOMAIN_GTT)
1953                 return;
1954
1955         /* No actual flushing is required for the GTT write domain.   Writes
1956          * to it immediately go to main memory as far as we know, so there's
1957          * no chipset flush.  It also doesn't land in render cache.
1958          */
1959         obj->write_domain = 0;
1960 }
1961
1962 /** Flushes the CPU write domain for the object if it's dirty. */
1963 static void
1964 i915_gem_object_flush_cpu_write_domain(struct drm_gem_object *obj)
1965 {
1966         struct drm_device *dev = obj->dev;
1967
1968         if (obj->write_domain != I915_GEM_DOMAIN_CPU)
1969                 return;
1970
1971         i915_gem_clflush_object(obj);
1972         drm_agp_chipset_flush(dev);
1973         obj->write_domain = 0;
1974 }
1975
1976 /**
1977  * Moves a single object to the GTT read, and possibly write domain.
1978  *
1979  * This function returns when the move is complete, including waiting on
1980  * flushes to occur.
1981  */
1982 int
1983 i915_gem_object_set_to_gtt_domain(struct drm_gem_object *obj, int write)
1984 {
1985         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1986         int ret;
1987
1988         /* Not valid to be called on unbound objects. */
1989         if (obj_priv->gtt_space == NULL)
1990                 return -EINVAL;
1991
1992         i915_gem_object_flush_gpu_write_domain(obj);
1993         /* Wait on any GPU rendering and flushing to occur. */
1994         ret = i915_gem_object_wait_rendering(obj);
1995         if (ret != 0)
1996                 return ret;
1997
1998         /* If we're writing through the GTT domain, then CPU and GPU caches
1999          * will need to be invalidated at next use.
2000          */
2001         if (write)
2002                 obj->read_domains &= I915_GEM_DOMAIN_GTT;
2003
2004         i915_gem_object_flush_cpu_write_domain(obj);
2005
2006         /* It should now be out of any other write domains, and we can update
2007          * the domain values for our changes.
2008          */
2009         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
2010         obj->read_domains |= I915_GEM_DOMAIN_GTT;
2011         if (write) {
2012                 obj->write_domain = I915_GEM_DOMAIN_GTT;
2013                 obj_priv->dirty = 1;
2014         }
2015
2016         return 0;
2017 }
2018
2019 /**
2020  * Moves a single object to the CPU read, and possibly write domain.
2021  *
2022  * This function returns when the move is complete, including waiting on
2023  * flushes to occur.
2024  */
2025 static int
2026 i915_gem_object_set_to_cpu_domain(struct drm_gem_object *obj, int write)
2027 {
2028         struct drm_device *dev = obj->dev;
2029         int ret;
2030
2031         i915_gem_object_flush_gpu_write_domain(obj);
2032         /* Wait on any GPU rendering and flushing to occur. */
2033         ret = i915_gem_object_wait_rendering(obj);
2034         if (ret != 0)
2035                 return ret;
2036
2037         i915_gem_object_flush_gtt_write_domain(obj);
2038
2039         /* If we have a partially-valid cache of the object in the CPU,
2040          * finish invalidating it and free the per-page flags.
2041          */
2042         i915_gem_object_set_to_full_cpu_read_domain(obj);
2043
2044         /* Flush the CPU cache if it's still invalid. */
2045         if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0) {
2046                 i915_gem_clflush_object(obj);
2047                 drm_agp_chipset_flush(dev);
2048
2049                 obj->read_domains |= I915_GEM_DOMAIN_CPU;
2050         }
2051
2052         /* It should now be out of any other write domains, and we can update
2053          * the domain values for our changes.
2054          */
2055         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
2056
2057         /* If we're writing through the CPU, then the GPU read domains will
2058          * need to be invalidated at next use.
2059          */
2060         if (write) {
2061                 obj->read_domains &= I915_GEM_DOMAIN_CPU;
2062                 obj->write_domain = I915_GEM_DOMAIN_CPU;
2063         }
2064
2065         return 0;
2066 }
2067
2068 /*
2069  * Set the next domain for the specified object. This
2070  * may not actually perform the necessary flushing/invaliding though,
2071  * as that may want to be batched with other set_domain operations
2072  *
2073  * This is (we hope) the only really tricky part of gem. The goal
2074  * is fairly simple -- track which caches hold bits of the object
2075  * and make sure they remain coherent. A few concrete examples may
2076  * help to explain how it works. For shorthand, we use the notation
2077  * (read_domains, write_domain), e.g. (CPU, CPU) to indicate the
2078  * a pair of read and write domain masks.
2079  *
2080  * Case 1: the batch buffer
2081  *
2082  *      1. Allocated
2083  *      2. Written by CPU
2084  *      3. Mapped to GTT
2085  *      4. Read by GPU
2086  *      5. Unmapped from GTT
2087  *      6. Freed
2088  *
2089  *      Let's take these a step at a time
2090  *
2091  *      1. Allocated
2092  *              Pages allocated from the kernel may still have
2093  *              cache contents, so we set them to (CPU, CPU) always.
2094  *      2. Written by CPU (using pwrite)
2095  *              The pwrite function calls set_domain (CPU, CPU) and
2096  *              this function does nothing (as nothing changes)
2097  *      3. Mapped by GTT
2098  *              This function asserts that the object is not
2099  *              currently in any GPU-based read or write domains
2100  *      4. Read by GPU
2101  *              i915_gem_execbuffer calls set_domain (COMMAND, 0).
2102  *              As write_domain is zero, this function adds in the
2103  *              current read domains (CPU+COMMAND, 0).
2104  *              flush_domains is set to CPU.
2105  *              invalidate_domains is set to COMMAND
2106  *              clflush is run to get data out of the CPU caches
2107  *              then i915_dev_set_domain calls i915_gem_flush to
2108  *              emit an MI_FLUSH and drm_agp_chipset_flush
2109  *      5. Unmapped from GTT
2110  *              i915_gem_object_unbind calls set_domain (CPU, CPU)
2111  *              flush_domains and invalidate_domains end up both zero
2112  *              so no flushing/invalidating happens
2113  *      6. Freed
2114  *              yay, done
2115  *
2116  * Case 2: The shared render buffer
2117  *
2118  *      1. Allocated
2119  *      2. Mapped to GTT
2120  *      3. Read/written by GPU
2121  *      4. set_domain to (CPU,CPU)
2122  *      5. Read/written by CPU
2123  *      6. Read/written by GPU
2124  *
2125  *      1. Allocated
2126  *              Same as last example, (CPU, CPU)
2127  *      2. Mapped to GTT
2128  *              Nothing changes (assertions find that it is not in the GPU)
2129  *      3. Read/written by GPU
2130  *              execbuffer calls set_domain (RENDER, RENDER)
2131  *              flush_domains gets CPU
2132  *              invalidate_domains gets GPU
2133  *              clflush (obj)
2134  *              MI_FLUSH and drm_agp_chipset_flush
2135  *      4. set_domain (CPU, CPU)
2136  *              flush_domains gets GPU
2137  *              invalidate_domains gets CPU
2138  *              wait_rendering (obj) to make sure all drawing is complete.
2139  *              This will include an MI_FLUSH to get the data from GPU
2140  *              to memory
2141  *              clflush (obj) to invalidate the CPU cache
2142  *              Another MI_FLUSH in i915_gem_flush (eliminate this somehow?)
2143  *      5. Read/written by CPU
2144  *              cache lines are loaded and dirtied
2145  *      6. Read written by GPU
2146  *              Same as last GPU access
2147  *
2148  * Case 3: The constant buffer
2149  *
2150  *      1. Allocated
2151  *      2. Written by CPU
2152  *      3. Read by GPU
2153  *      4. Updated (written) by CPU again
2154  *      5. Read by GPU
2155  *
2156  *      1. Allocated
2157  *              (CPU, CPU)
2158  *      2. Written by CPU
2159  *              (CPU, CPU)
2160  *      3. Read by GPU
2161  *              (CPU+RENDER, 0)
2162  *              flush_domains = CPU
2163  *              invalidate_domains = RENDER
2164  *              clflush (obj)
2165  *              MI_FLUSH
2166  *              drm_agp_chipset_flush
2167  *      4. Updated (written) by CPU again
2168  *              (CPU, CPU)
2169  *              flush_domains = 0 (no previous write domain)
2170  *              invalidate_domains = 0 (no new read domains)
2171  *      5. Read by GPU
2172  *              (CPU+RENDER, 0)
2173  *              flush_domains = CPU
2174  *              invalidate_domains = RENDER
2175  *              clflush (obj)
2176  *              MI_FLUSH
2177  *              drm_agp_chipset_flush
2178  */
2179 static void
2180 i915_gem_object_set_to_gpu_domain(struct drm_gem_object *obj)
2181 {
2182         struct drm_device               *dev = obj->dev;
2183         struct drm_i915_gem_object      *obj_priv = obj->driver_private;
2184         uint32_t                        invalidate_domains = 0;
2185         uint32_t                        flush_domains = 0;
2186
2187         BUG_ON(obj->pending_read_domains & I915_GEM_DOMAIN_CPU);
2188         BUG_ON(obj->pending_write_domain == I915_GEM_DOMAIN_CPU);
2189
2190 #if WATCH_BUF
2191         DRM_INFO("%s: object %p read %08x -> %08x write %08x -> %08x\n",
2192                  __func__, obj,
2193                  obj->read_domains, obj->pending_read_domains,
2194                  obj->write_domain, obj->pending_write_domain);
2195 #endif
2196         /*
2197          * If the object isn't moving to a new write domain,
2198          * let the object stay in multiple read domains
2199          */
2200         if (obj->pending_write_domain == 0)
2201                 obj->pending_read_domains |= obj->read_domains;
2202         else
2203                 obj_priv->dirty = 1;
2204
2205         /*
2206          * Flush the current write domain if
2207          * the new read domains don't match. Invalidate
2208          * any read domains which differ from the old
2209          * write domain
2210          */
2211         if (obj->write_domain &&
2212             obj->write_domain != obj->pending_read_domains) {
2213                 flush_domains |= obj->write_domain;
2214                 invalidate_domains |=
2215                         obj->pending_read_domains & ~obj->write_domain;
2216         }
2217         /*
2218          * Invalidate any read caches which may have
2219          * stale data. That is, any new read domains.
2220          */
2221         invalidate_domains |= obj->pending_read_domains & ~obj->read_domains;
2222         if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_CPU) {
2223 #if WATCH_BUF
2224                 DRM_INFO("%s: CPU domain flush %08x invalidate %08x\n",
2225                          __func__, flush_domains, invalidate_domains);
2226 #endif
2227                 i915_gem_clflush_object(obj);
2228         }
2229
2230         /* The actual obj->write_domain will be updated with
2231          * pending_write_domain after we emit the accumulated flush for all
2232          * of our domain changes in execbuffers (which clears objects'
2233          * write_domains).  So if we have a current write domain that we
2234          * aren't changing, set pending_write_domain to that.
2235          */
2236         if (flush_domains == 0 && obj->pending_write_domain == 0)
2237                 obj->pending_write_domain = obj->write_domain;
2238         obj->read_domains = obj->pending_read_domains;
2239
2240         dev->invalidate_domains |= invalidate_domains;
2241         dev->flush_domains |= flush_domains;
2242 #if WATCH_BUF
2243         DRM_INFO("%s: read %08x write %08x invalidate %08x flush %08x\n",
2244                  __func__,
2245                  obj->read_domains, obj->write_domain,
2246                  dev->invalidate_domains, dev->flush_domains);
2247 #endif
2248 }
2249
2250 /**
2251  * Moves the object from a partially CPU read to a full one.
2252  *
2253  * Note that this only resolves i915_gem_object_set_cpu_read_domain_range(),
2254  * and doesn't handle transitioning from !(read_domains & I915_GEM_DOMAIN_CPU).
2255  */
2256 static void
2257 i915_gem_object_set_to_full_cpu_read_domain(struct drm_gem_object *obj)
2258 {
2259         struct drm_device *dev = obj->dev;
2260         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2261
2262         if (!obj_priv->page_cpu_valid)
2263                 return;
2264
2265         /* If we're partially in the CPU read domain, finish moving it in.
2266          */
2267         if (obj->read_domains & I915_GEM_DOMAIN_CPU) {
2268                 int i;
2269
2270                 for (i = 0; i <= (obj->size - 1) / PAGE_SIZE; i++) {
2271                         if (obj_priv->page_cpu_valid[i])
2272                                 continue;
2273                         drm_clflush_pages(obj_priv->page_list + i, 1);
2274                 }
2275                 drm_agp_chipset_flush(dev);
2276         }
2277
2278         /* Free the page_cpu_valid mappings which are now stale, whether
2279          * or not we've got I915_GEM_DOMAIN_CPU.
2280          */
2281         drm_free(obj_priv->page_cpu_valid, obj->size / PAGE_SIZE,
2282                  DRM_MEM_DRIVER);
2283         obj_priv->page_cpu_valid = NULL;
2284 }
2285
2286 /**
2287  * Set the CPU read domain on a range of the object.
2288  *
2289  * The object ends up with I915_GEM_DOMAIN_CPU in its read flags although it's
2290  * not entirely valid.  The page_cpu_valid member of the object flags which
2291  * pages have been flushed, and will be respected by
2292  * i915_gem_object_set_to_cpu_domain() if it's called on to get a valid mapping
2293  * of the whole object.
2294  *
2295  * This function returns when the move is complete, including waiting on
2296  * flushes to occur.
2297  */
2298 static int
2299 i915_gem_object_set_cpu_read_domain_range(struct drm_gem_object *obj,
2300                                           uint64_t offset, uint64_t size)
2301 {
2302         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2303         int i, ret;
2304
2305         if (offset == 0 && size == obj->size)
2306                 return i915_gem_object_set_to_cpu_domain(obj, 0);
2307
2308         i915_gem_object_flush_gpu_write_domain(obj);
2309         /* Wait on any GPU rendering and flushing to occur. */
2310         ret = i915_gem_object_wait_rendering(obj);
2311         if (ret != 0)
2312                 return ret;
2313         i915_gem_object_flush_gtt_write_domain(obj);
2314
2315         /* If we're already fully in the CPU read domain, we're done. */
2316         if (obj_priv->page_cpu_valid == NULL &&
2317             (obj->read_domains & I915_GEM_DOMAIN_CPU) != 0)
2318                 return 0;
2319
2320         /* Otherwise, create/clear the per-page CPU read domain flag if we're
2321          * newly adding I915_GEM_DOMAIN_CPU
2322          */
2323         if (obj_priv->page_cpu_valid == NULL) {
2324                 obj_priv->page_cpu_valid = drm_calloc(1, obj->size / PAGE_SIZE,
2325                                                       DRM_MEM_DRIVER);
2326                 if (obj_priv->page_cpu_valid == NULL)
2327                         return -ENOMEM;
2328         } else if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0)
2329                 memset(obj_priv->page_cpu_valid, 0, obj->size / PAGE_SIZE);
2330
2331         /* Flush the cache on any pages that are still invalid from the CPU's
2332          * perspective.
2333          */
2334         for (i = offset / PAGE_SIZE; i <= (offset + size - 1) / PAGE_SIZE;
2335              i++) {
2336                 if (obj_priv->page_cpu_valid[i])
2337                         continue;
2338
2339                 drm_clflush_pages(obj_priv->page_list + i, 1);
2340
2341                 obj_priv->page_cpu_valid[i] = 1;
2342         }
2343
2344         /* It should now be out of any other write domains, and we can update
2345          * the domain values for our changes.
2346          */
2347         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
2348
2349         obj->read_domains |= I915_GEM_DOMAIN_CPU;
2350
2351         return 0;
2352 }
2353
2354 /**
2355  * Pin an object to the GTT and evaluate the relocations landing in it.
2356  */
2357 static int
2358 i915_gem_object_pin_and_relocate(struct drm_gem_object *obj,
2359                                  struct drm_file *file_priv,
2360                                  struct drm_i915_gem_exec_object *entry)
2361 {
2362         struct drm_device *dev = obj->dev;
2363         drm_i915_private_t *dev_priv = dev->dev_private;
2364         struct drm_i915_gem_relocation_entry reloc;
2365         struct drm_i915_gem_relocation_entry __user *relocs;
2366         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2367         int i, ret;
2368         void __iomem *reloc_page;
2369
2370         /* Choose the GTT offset for our buffer and put it there. */
2371         ret = i915_gem_object_pin(obj, (uint32_t) entry->alignment);
2372         if (ret)
2373                 return ret;
2374
2375         entry->offset = obj_priv->gtt_offset;
2376
2377         relocs = (struct drm_i915_gem_relocation_entry __user *)
2378                  (uintptr_t) entry->relocs_ptr;
2379         /* Apply the relocations, using the GTT aperture to avoid cache
2380          * flushing requirements.
2381          */
2382         for (i = 0; i < entry->relocation_count; i++) {
2383                 struct drm_gem_object *target_obj;
2384                 struct drm_i915_gem_object *target_obj_priv;
2385                 uint32_t reloc_val, reloc_offset;
2386                 uint32_t __iomem *reloc_entry;
2387
2388                 ret = copy_from_user(&reloc, relocs + i, sizeof(reloc));
2389                 if (ret != 0) {
2390                         i915_gem_object_unpin(obj);
2391                         return ret;
2392                 }
2393
2394                 target_obj = drm_gem_object_lookup(obj->dev, file_priv,
2395                                                    reloc.target_handle);
2396                 if (target_obj == NULL) {
2397                         i915_gem_object_unpin(obj);
2398                         return -EBADF;
2399                 }
2400                 target_obj_priv = target_obj->driver_private;
2401
2402                 /* The target buffer should have appeared before us in the
2403                  * exec_object list, so it should have a GTT space bound by now.
2404                  */
2405                 if (target_obj_priv->gtt_space == NULL) {
2406                         DRM_ERROR("No GTT space found for object %d\n",
2407                                   reloc.target_handle);
2408                         drm_gem_object_unreference(target_obj);
2409                         i915_gem_object_unpin(obj);
2410                         return -EINVAL;
2411                 }
2412
2413                 if (reloc.offset > obj->size - 4) {
2414                         DRM_ERROR("Relocation beyond object bounds: "
2415                                   "obj %p target %d offset %d size %d.\n",
2416                                   obj, reloc.target_handle,
2417                                   (int) reloc.offset, (int) obj->size);
2418                         drm_gem_object_unreference(target_obj);
2419                         i915_gem_object_unpin(obj);
2420                         return -EINVAL;
2421                 }
2422                 if (reloc.offset & 3) {
2423                         DRM_ERROR("Relocation not 4-byte aligned: "
2424                                   "obj %p target %d offset %d.\n",
2425                                   obj, reloc.target_handle,
2426                                   (int) reloc.offset);
2427                         drm_gem_object_unreference(target_obj);
2428                         i915_gem_object_unpin(obj);
2429                         return -EINVAL;
2430                 }
2431
2432                 if (reloc.write_domain & I915_GEM_DOMAIN_CPU ||
2433                     reloc.read_domains & I915_GEM_DOMAIN_CPU) {
2434                         DRM_ERROR("reloc with read/write CPU domains: "
2435                                   "obj %p target %d offset %d "
2436                                   "read %08x write %08x",
2437                                   obj, reloc.target_handle,
2438                                   (int) reloc.offset,
2439                                   reloc.read_domains,
2440                                   reloc.write_domain);
2441                         drm_gem_object_unreference(target_obj);
2442                         i915_gem_object_unpin(obj);
2443                         return -EINVAL;
2444                 }
2445
2446                 if (reloc.write_domain && target_obj->pending_write_domain &&
2447                     reloc.write_domain != target_obj->pending_write_domain) {
2448                         DRM_ERROR("Write domain conflict: "
2449                                   "obj %p target %d offset %d "
2450                                   "new %08x old %08x\n",
2451                                   obj, reloc.target_handle,
2452                                   (int) reloc.offset,
2453                                   reloc.write_domain,
2454                                   target_obj->pending_write_domain);
2455                         drm_gem_object_unreference(target_obj);
2456                         i915_gem_object_unpin(obj);
2457                         return -EINVAL;
2458                 }
2459
2460 #if WATCH_RELOC
2461                 DRM_INFO("%s: obj %p offset %08x target %d "
2462                          "read %08x write %08x gtt %08x "
2463                          "presumed %08x delta %08x\n",
2464                          __func__,
2465                          obj,
2466                          (int) reloc.offset,
2467                          (int) reloc.target_handle,
2468                          (int) reloc.read_domains,
2469                          (int) reloc.write_domain,
2470                          (int) target_obj_priv->gtt_offset,
2471                          (int) reloc.presumed_offset,
2472                          reloc.delta);
2473 #endif
2474
2475                 target_obj->pending_read_domains |= reloc.read_domains;
2476                 target_obj->pending_write_domain |= reloc.write_domain;
2477
2478                 /* If the relocation already has the right value in it, no
2479                  * more work needs to be done.
2480                  */
2481                 if (target_obj_priv->gtt_offset == reloc.presumed_offset) {
2482                         drm_gem_object_unreference(target_obj);
2483                         continue;
2484                 }
2485
2486                 ret = i915_gem_object_set_to_gtt_domain(obj, 1);
2487                 if (ret != 0) {
2488                         drm_gem_object_unreference(target_obj);
2489                         i915_gem_object_unpin(obj);
2490                         return -EINVAL;
2491                 }
2492
2493                 /* Map the page containing the relocation we're going to
2494                  * perform.
2495                  */
2496                 reloc_offset = obj_priv->gtt_offset + reloc.offset;
2497                 reloc_page = io_mapping_map_atomic_wc(dev_priv->mm.gtt_mapping,
2498                                                       (reloc_offset &
2499                                                        ~(PAGE_SIZE - 1)));
2500                 reloc_entry = (uint32_t __iomem *)(reloc_page +
2501                                                    (reloc_offset & (PAGE_SIZE - 1)));
2502                 reloc_val = target_obj_priv->gtt_offset + reloc.delta;
2503
2504 #if WATCH_BUF
2505                 DRM_INFO("Applied relocation: %p@0x%08x %08x -> %08x\n",
2506                           obj, (unsigned int) reloc.offset,
2507                           readl(reloc_entry), reloc_val);
2508 #endif
2509                 writel(reloc_val, reloc_entry);
2510                 io_mapping_unmap_atomic(reloc_page);
2511
2512                 /* Write the updated presumed offset for this entry back out
2513                  * to the user.
2514                  */
2515                 reloc.presumed_offset = target_obj_priv->gtt_offset;
2516                 ret = copy_to_user(relocs + i, &reloc, sizeof(reloc));
2517                 if (ret != 0) {
2518                         drm_gem_object_unreference(target_obj);
2519                         i915_gem_object_unpin(obj);
2520                         return ret;
2521                 }
2522
2523                 drm_gem_object_unreference(target_obj);
2524         }
2525
2526 #if WATCH_BUF
2527         if (0)
2528                 i915_gem_dump_object(obj, 128, __func__, ~0);
2529 #endif
2530         return 0;
2531 }
2532
2533 /** Dispatch a batchbuffer to the ring
2534  */
2535 static int
2536 i915_dispatch_gem_execbuffer(struct drm_device *dev,
2537                               struct drm_i915_gem_execbuffer *exec,
2538                               uint64_t exec_offset)
2539 {
2540         drm_i915_private_t *dev_priv = dev->dev_private;
2541         struct drm_clip_rect __user *boxes = (struct drm_clip_rect __user *)
2542                                              (uintptr_t) exec->cliprects_ptr;
2543         int nbox = exec->num_cliprects;
2544         int i = 0, count;
2545         uint32_t        exec_start, exec_len;
2546         RING_LOCALS;
2547
2548         exec_start = (uint32_t) exec_offset + exec->batch_start_offset;
2549         exec_len = (uint32_t) exec->batch_len;
2550
2551         if ((exec_start | exec_len) & 0x7) {
2552                 DRM_ERROR("alignment\n");
2553                 return -EINVAL;
2554         }
2555
2556         if (!exec_start)
2557                 return -EINVAL;
2558
2559         count = nbox ? nbox : 1;
2560
2561         for (i = 0; i < count; i++) {
2562                 if (i < nbox) {
2563                         int ret = i915_emit_box(dev, boxes, i,
2564                                                 exec->DR1, exec->DR4);
2565                         if (ret)
2566                                 return ret;
2567                 }
2568
2569                 if (IS_I830(dev) || IS_845G(dev)) {
2570                         BEGIN_LP_RING(4);
2571                         OUT_RING(MI_BATCH_BUFFER);
2572                         OUT_RING(exec_start | MI_BATCH_NON_SECURE);
2573                         OUT_RING(exec_start + exec_len - 4);
2574                         OUT_RING(0);
2575                         ADVANCE_LP_RING();
2576                 } else {
2577                         BEGIN_LP_RING(2);
2578                         if (IS_I965G(dev)) {
2579                                 OUT_RING(MI_BATCH_BUFFER_START |
2580                                          (2 << 6) |
2581                                          MI_BATCH_NON_SECURE_I965);
2582                                 OUT_RING(exec_start);
2583                         } else {
2584                                 OUT_RING(MI_BATCH_BUFFER_START |
2585                                          (2 << 6));
2586                                 OUT_RING(exec_start | MI_BATCH_NON_SECURE);
2587                         }
2588                         ADVANCE_LP_RING();
2589                 }
2590         }
2591
2592         /* XXX breadcrumb */
2593         return 0;
2594 }
2595
2596 /* Throttle our rendering by waiting until the ring has completed our requests
2597  * emitted over 20 msec ago.
2598  *
2599  * This should get us reasonable parallelism between CPU and GPU but also
2600  * relatively low latency when blocking on a particular request to finish.
2601  */
2602 static int
2603 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file_priv)
2604 {
2605         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
2606         int ret = 0;
2607         uint32_t seqno;
2608
2609         mutex_lock(&dev->struct_mutex);
2610         seqno = i915_file_priv->mm.last_gem_throttle_seqno;
2611         i915_file_priv->mm.last_gem_throttle_seqno =
2612                 i915_file_priv->mm.last_gem_seqno;
2613         if (seqno)
2614                 ret = i915_wait_request(dev, seqno);
2615         mutex_unlock(&dev->struct_mutex);
2616         return ret;
2617 }
2618
2619 int
2620 i915_gem_execbuffer(struct drm_device *dev, void *data,
2621                     struct drm_file *file_priv)
2622 {
2623         drm_i915_private_t *dev_priv = dev->dev_private;
2624         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
2625         struct drm_i915_gem_execbuffer *args = data;
2626         struct drm_i915_gem_exec_object *exec_list = NULL;
2627         struct drm_gem_object **object_list = NULL;
2628         struct drm_gem_object *batch_obj;
2629         struct drm_i915_gem_object *obj_priv;
2630         int ret, i, pinned = 0;
2631         uint64_t exec_offset;
2632         uint32_t seqno, flush_domains;
2633         int pin_tries;
2634
2635 #if WATCH_EXEC
2636         DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
2637                   (int) args->buffers_ptr, args->buffer_count, args->batch_len);
2638 #endif
2639
2640         if (args->buffer_count < 1) {
2641                 DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
2642                 return -EINVAL;
2643         }
2644         /* Copy in the exec list from userland */
2645         exec_list = drm_calloc(sizeof(*exec_list), args->buffer_count,
2646                                DRM_MEM_DRIVER);
2647         object_list = drm_calloc(sizeof(*object_list), args->buffer_count,
2648                                  DRM_MEM_DRIVER);
2649         if (exec_list == NULL || object_list == NULL) {
2650                 DRM_ERROR("Failed to allocate exec or object list "
2651                           "for %d buffers\n",
2652                           args->buffer_count);
2653                 ret = -ENOMEM;
2654                 goto pre_mutex_err;
2655         }
2656         ret = copy_from_user(exec_list,
2657                              (struct drm_i915_relocation_entry __user *)
2658                              (uintptr_t) args->buffers_ptr,
2659                              sizeof(*exec_list) * args->buffer_count);
2660         if (ret != 0) {
2661                 DRM_ERROR("copy %d exec entries failed %d\n",
2662                           args->buffer_count, ret);
2663                 goto pre_mutex_err;
2664         }
2665
2666         mutex_lock(&dev->struct_mutex);
2667
2668         i915_verify_inactive(dev, __FILE__, __LINE__);
2669
2670         if (dev_priv->mm.wedged) {
2671                 DRM_ERROR("Execbuf while wedged\n");
2672                 mutex_unlock(&dev->struct_mutex);
2673                 ret = -EIO;
2674                 goto pre_mutex_err;
2675         }
2676
2677         if (dev_priv->mm.suspended) {
2678                 DRM_ERROR("Execbuf while VT-switched.\n");
2679                 mutex_unlock(&dev->struct_mutex);
2680                 ret = -EBUSY;
2681                 goto pre_mutex_err;
2682         }
2683
2684         /* Look up object handles */
2685         for (i = 0; i < args->buffer_count; i++) {
2686                 object_list[i] = drm_gem_object_lookup(dev, file_priv,
2687                                                        exec_list[i].handle);
2688                 if (object_list[i] == NULL) {
2689                         DRM_ERROR("Invalid object handle %d at index %d\n",
2690                                    exec_list[i].handle, i);
2691                         ret = -EBADF;
2692                         goto err;
2693                 }
2694
2695                 obj_priv = object_list[i]->driver_private;
2696                 if (obj_priv->in_execbuffer) {
2697                         DRM_ERROR("Object %p appears more than once in object list\n",
2698                                    object_list[i]);
2699                         ret = -EBADF;
2700                         goto err;
2701                 }
2702                 obj_priv->in_execbuffer = true;
2703         }
2704
2705         /* Pin and relocate */
2706         for (pin_tries = 0; ; pin_tries++) {
2707                 ret = 0;
2708                 for (i = 0; i < args->buffer_count; i++) {
2709                         object_list[i]->pending_read_domains = 0;
2710                         object_list[i]->pending_write_domain = 0;
2711                         ret = i915_gem_object_pin_and_relocate(object_list[i],
2712                                                                file_priv,
2713                                                                &exec_list[i]);
2714                         if (ret)
2715                                 break;
2716                         pinned = i + 1;
2717                 }
2718                 /* success */
2719                 if (ret == 0)
2720                         break;
2721
2722                 /* error other than GTT full, or we've already tried again */
2723                 if (ret != -ENOMEM || pin_tries >= 1) {
2724                         if (ret != -ERESTARTSYS)
2725                                 DRM_ERROR("Failed to pin buffers %d\n", ret);
2726                         goto err;
2727                 }
2728
2729                 /* unpin all of our buffers */
2730                 for (i = 0; i < pinned; i++)
2731                         i915_gem_object_unpin(object_list[i]);
2732                 pinned = 0;
2733
2734                 /* evict everyone we can from the aperture */
2735                 ret = i915_gem_evict_everything(dev);
2736                 if (ret)
2737                         goto err;
2738         }
2739
2740         /* Set the pending read domains for the batch buffer to COMMAND */
2741         batch_obj = object_list[args->buffer_count-1];
2742         batch_obj->pending_read_domains = I915_GEM_DOMAIN_COMMAND;
2743         batch_obj->pending_write_domain = 0;
2744
2745         i915_verify_inactive(dev, __FILE__, __LINE__);
2746
2747         /* Zero the global flush/invalidate flags. These
2748          * will be modified as new domains are computed
2749          * for each object
2750          */
2751         dev->invalidate_domains = 0;
2752         dev->flush_domains = 0;
2753
2754         for (i = 0; i < args->buffer_count; i++) {
2755                 struct drm_gem_object *obj = object_list[i];
2756
2757                 /* Compute new gpu domains and update invalidate/flush */
2758                 i915_gem_object_set_to_gpu_domain(obj);
2759         }
2760
2761         i915_verify_inactive(dev, __FILE__, __LINE__);
2762
2763         if (dev->invalidate_domains | dev->flush_domains) {
2764 #if WATCH_EXEC
2765                 DRM_INFO("%s: invalidate_domains %08x flush_domains %08x\n",
2766                           __func__,
2767                          dev->invalidate_domains,
2768                          dev->flush_domains);
2769 #endif
2770                 i915_gem_flush(dev,
2771                                dev->invalidate_domains,
2772                                dev->flush_domains);
2773                 if (dev->flush_domains)
2774                         (void)i915_add_request(dev, dev->flush_domains);
2775         }
2776
2777         for (i = 0; i < args->buffer_count; i++) {
2778                 struct drm_gem_object *obj = object_list[i];
2779
2780                 obj->write_domain = obj->pending_write_domain;
2781         }
2782
2783         i915_verify_inactive(dev, __FILE__, __LINE__);
2784
2785 #if WATCH_COHERENCY
2786         for (i = 0; i < args->buffer_count; i++) {
2787                 i915_gem_object_check_coherency(object_list[i],
2788                                                 exec_list[i].handle);
2789         }
2790 #endif
2791
2792         exec_offset = exec_list[args->buffer_count - 1].offset;
2793
2794 #if WATCH_EXEC
2795         i915_gem_dump_object(object_list[args->buffer_count - 1],
2796                               args->batch_len,
2797                               __func__,
2798                               ~0);
2799 #endif
2800
2801         /* Exec the batchbuffer */
2802         ret = i915_dispatch_gem_execbuffer(dev, args, exec_offset);
2803         if (ret) {
2804                 DRM_ERROR("dispatch failed %d\n", ret);
2805                 goto err;
2806         }
2807
2808         /*
2809          * Ensure that the commands in the batch buffer are
2810          * finished before the interrupt fires
2811          */
2812         flush_domains = i915_retire_commands(dev);
2813
2814         i915_verify_inactive(dev, __FILE__, __LINE__);
2815
2816         /*
2817          * Get a seqno representing the execution of the current buffer,
2818          * which we can wait on.  We would like to mitigate these interrupts,
2819          * likely by only creating seqnos occasionally (so that we have
2820          * *some* interrupts representing completion of buffers that we can
2821          * wait on when trying to clear up gtt space).
2822          */
2823         seqno = i915_add_request(dev, flush_domains);
2824         BUG_ON(seqno == 0);
2825         i915_file_priv->mm.last_gem_seqno = seqno;
2826         for (i = 0; i < args->buffer_count; i++) {
2827                 struct drm_gem_object *obj = object_list[i];
2828
2829                 i915_gem_object_move_to_active(obj, seqno);
2830 #if WATCH_LRU
2831                 DRM_INFO("%s: move to exec list %p\n", __func__, obj);
2832 #endif
2833         }
2834 #if WATCH_LRU
2835         i915_dump_lru(dev, __func__);
2836 #endif
2837
2838         i915_verify_inactive(dev, __FILE__, __LINE__);
2839
2840 err:
2841         for (i = 0; i < pinned; i++)
2842                 i915_gem_object_unpin(object_list[i]);
2843
2844         for (i = 0; i < args->buffer_count; i++) {
2845                 if (object_list[i]) {
2846                         obj_priv = object_list[i]->driver_private;
2847                         obj_priv->in_execbuffer = false;
2848                 }
2849                 drm_gem_object_unreference(object_list[i]);
2850         }
2851
2852         mutex_unlock(&dev->struct_mutex);
2853
2854         if (!ret) {
2855                 /* Copy the new buffer offsets back to the user's exec list. */
2856                 ret = copy_to_user((struct drm_i915_relocation_entry __user *)
2857                                    (uintptr_t) args->buffers_ptr,
2858                                    exec_list,
2859                                    sizeof(*exec_list) * args->buffer_count);
2860                 if (ret)
2861                         DRM_ERROR("failed to copy %d exec entries "
2862                                   "back to user (%d)\n",
2863                                   args->buffer_count, ret);
2864         }
2865
2866 pre_mutex_err:
2867         drm_free(object_list, sizeof(*object_list) * args->buffer_count,
2868                  DRM_MEM_DRIVER);
2869         drm_free(exec_list, sizeof(*exec_list) * args->buffer_count,
2870                  DRM_MEM_DRIVER);
2871
2872         return ret;
2873 }
2874
2875 int
2876 i915_gem_object_pin(struct drm_gem_object *obj, uint32_t alignment)
2877 {
2878         struct drm_device *dev = obj->dev;
2879         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2880         int ret;
2881
2882         i915_verify_inactive(dev, __FILE__, __LINE__);
2883         if (obj_priv->gtt_space == NULL) {
2884                 ret = i915_gem_object_bind_to_gtt(obj, alignment);
2885                 if (ret != 0) {
2886                         if (ret != -EBUSY && ret != -ERESTARTSYS)
2887                                 DRM_ERROR("Failure to bind: %d\n", ret);
2888                         return ret;
2889                 }
2890         }
2891         /*
2892          * Pre-965 chips need a fence register set up in order to
2893          * properly handle tiled surfaces.
2894          */
2895         if (!IS_I965G(dev) &&
2896             obj_priv->fence_reg == I915_FENCE_REG_NONE &&
2897             obj_priv->tiling_mode != I915_TILING_NONE) {
2898                 ret = i915_gem_object_get_fence_reg(obj, true);
2899                 if (ret != 0) {
2900                         if (ret != -EBUSY && ret != -ERESTARTSYS)
2901                                 DRM_ERROR("Failure to install fence: %d\n",
2902                                           ret);
2903                         return ret;
2904                 }
2905         }
2906         obj_priv->pin_count++;
2907
2908         /* If the object is not active and not pending a flush,
2909          * remove it from the inactive list
2910          */
2911         if (obj_priv->pin_count == 1) {
2912                 atomic_inc(&dev->pin_count);
2913                 atomic_add(obj->size, &dev->pin_memory);
2914                 if (!obj_priv->active &&
2915                     (obj->write_domain & ~(I915_GEM_DOMAIN_CPU |
2916                                            I915_GEM_DOMAIN_GTT)) == 0 &&
2917                     !list_empty(&obj_priv->list))
2918                         list_del_init(&obj_priv->list);
2919         }
2920         i915_verify_inactive(dev, __FILE__, __LINE__);
2921
2922         return 0;
2923 }
2924
2925 void
2926 i915_gem_object_unpin(struct drm_gem_object *obj)
2927 {
2928         struct drm_device *dev = obj->dev;
2929         drm_i915_private_t *dev_priv = dev->dev_private;
2930         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2931
2932         i915_verify_inactive(dev, __FILE__, __LINE__);
2933         obj_priv->pin_count--;
2934         BUG_ON(obj_priv->pin_count < 0);
2935         BUG_ON(obj_priv->gtt_space == NULL);
2936
2937         /* If the object is no longer pinned, and is
2938          * neither active nor being flushed, then stick it on
2939          * the inactive list
2940          */
2941         if (obj_priv->pin_count == 0) {
2942                 if (!obj_priv->active &&
2943                     (obj->write_domain & ~(I915_GEM_DOMAIN_CPU |
2944                                            I915_GEM_DOMAIN_GTT)) == 0)
2945                         list_move_tail(&obj_priv->list,
2946                                        &dev_priv->mm.inactive_list);
2947                 atomic_dec(&dev->pin_count);
2948                 atomic_sub(obj->size, &dev->pin_memory);
2949         }
2950         i915_verify_inactive(dev, __FILE__, __LINE__);
2951 }
2952
2953 int
2954 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
2955                    struct drm_file *file_priv)
2956 {
2957         struct drm_i915_gem_pin *args = data;
2958         struct drm_gem_object *obj;
2959         struct drm_i915_gem_object *obj_priv;
2960         int ret;
2961
2962         mutex_lock(&dev->struct_mutex);
2963
2964         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
2965         if (obj == NULL) {
2966                 DRM_ERROR("Bad handle in i915_gem_pin_ioctl(): %d\n",
2967                           args->handle);
2968                 mutex_unlock(&dev->struct_mutex);
2969                 return -EBADF;
2970         }
2971         obj_priv = obj->driver_private;
2972
2973         if (obj_priv->pin_filp != NULL && obj_priv->pin_filp != file_priv) {
2974                 DRM_ERROR("Already pinned in i915_gem_pin_ioctl(): %d\n",
2975                           args->handle);
2976                 drm_gem_object_unreference(obj);
2977                 mutex_unlock(&dev->struct_mutex);
2978                 return -EINVAL;
2979         }
2980
2981         obj_priv->user_pin_count++;
2982         obj_priv->pin_filp = file_priv;
2983         if (obj_priv->user_pin_count == 1) {
2984                 ret = i915_gem_object_pin(obj, args->alignment);
2985                 if (ret != 0) {
2986                         drm_gem_object_unreference(obj);
2987                         mutex_unlock(&dev->struct_mutex);
2988                         return ret;
2989                 }
2990         }
2991
2992         /* XXX - flush the CPU caches for pinned objects
2993          * as the X server doesn't manage domains yet
2994          */
2995         i915_gem_object_flush_cpu_write_domain(obj);
2996         args->offset = obj_priv->gtt_offset;
2997         drm_gem_object_unreference(obj);
2998         mutex_unlock(&dev->struct_mutex);
2999
3000         return 0;
3001 }
3002
3003 int
3004 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
3005                      struct drm_file *file_priv)
3006 {
3007         struct drm_i915_gem_pin *args = data;
3008         struct drm_gem_object *obj;
3009         struct drm_i915_gem_object *obj_priv;
3010
3011         mutex_lock(&dev->struct_mutex);
3012
3013         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
3014         if (obj == NULL) {
3015                 DRM_ERROR("Bad handle in i915_gem_unpin_ioctl(): %d\n",
3016                           args->handle);
3017                 mutex_unlock(&dev->struct_mutex);
3018                 return -EBADF;
3019         }
3020
3021         obj_priv = obj->driver_private;
3022         if (obj_priv->pin_filp != file_priv) {
3023                 DRM_ERROR("Not pinned by caller in i915_gem_pin_ioctl(): %d\n",
3024                           args->handle);
3025                 drm_gem_object_unreference(obj);
3026                 mutex_unlock(&dev->struct_mutex);
3027                 return -EINVAL;
3028         }
3029         obj_priv->user_pin_count--;
3030         if (obj_priv->user_pin_count == 0) {
3031                 obj_priv->pin_filp = NULL;
3032                 i915_gem_object_unpin(obj);
3033         }
3034
3035         drm_gem_object_unreference(obj);
3036         mutex_unlock(&dev->struct_mutex);
3037         return 0;
3038 }
3039
3040 int
3041 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
3042                     struct drm_file *file_priv)
3043 {
3044         struct drm_i915_gem_busy *args = data;
3045         struct drm_gem_object *obj;
3046         struct drm_i915_gem_object *obj_priv;
3047
3048         mutex_lock(&dev->struct_mutex);
3049         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
3050         if (obj == NULL) {
3051                 DRM_ERROR("Bad handle in i915_gem_busy_ioctl(): %d\n",
3052                           args->handle);
3053                 mutex_unlock(&dev->struct_mutex);
3054                 return -EBADF;
3055         }
3056
3057         /* Update the active list for the hardware's current position.
3058          * Otherwise this only updates on a delayed timer or when irqs are
3059          * actually unmasked, and our working set ends up being larger than
3060          * required.
3061          */
3062         i915_gem_retire_requests(dev);
3063
3064         obj_priv = obj->driver_private;
3065         /* Don't count being on the flushing list against the object being
3066          * done.  Otherwise, a buffer left on the flushing list but not getting
3067          * flushed (because nobody's flushing that domain) won't ever return
3068          * unbusy and get reused by libdrm's bo cache.  The other expected
3069          * consumer of this interface, OpenGL's occlusion queries, also specs
3070          * that the objects get unbusy "eventually" without any interference.
3071          */
3072         args->busy = obj_priv->active && obj_priv->last_rendering_seqno != 0;
3073
3074         drm_gem_object_unreference(obj);
3075         mutex_unlock(&dev->struct_mutex);
3076         return 0;
3077 }
3078
3079 int
3080 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
3081                         struct drm_file *file_priv)
3082 {
3083     return i915_gem_ring_throttle(dev, file_priv);
3084 }
3085
3086 int i915_gem_init_object(struct drm_gem_object *obj)
3087 {
3088         struct drm_i915_gem_object *obj_priv;
3089
3090         obj_priv = drm_calloc(1, sizeof(*obj_priv), DRM_MEM_DRIVER);
3091         if (obj_priv == NULL)
3092                 return -ENOMEM;
3093
3094         /*
3095          * We've just allocated pages from the kernel,
3096          * so they've just been written by the CPU with
3097          * zeros. They'll need to be clflushed before we
3098          * use them with the GPU.
3099          */
3100         obj->write_domain = I915_GEM_DOMAIN_CPU;
3101         obj->read_domains = I915_GEM_DOMAIN_CPU;
3102
3103         obj_priv->agp_type = AGP_USER_MEMORY;
3104
3105         obj->driver_private = obj_priv;
3106         obj_priv->obj = obj;
3107         obj_priv->fence_reg = I915_FENCE_REG_NONE;
3108         INIT_LIST_HEAD(&obj_priv->list);
3109
3110         return 0;
3111 }
3112
3113 void i915_gem_free_object(struct drm_gem_object *obj)
3114 {
3115         struct drm_device *dev = obj->dev;
3116         struct drm_i915_gem_object *obj_priv = obj->driver_private;
3117
3118         while (obj_priv->pin_count > 0)
3119                 i915_gem_object_unpin(obj);
3120
3121         if (obj_priv->phys_obj)
3122                 i915_gem_detach_phys_object(dev, obj);
3123
3124         i915_gem_object_unbind(obj);
3125
3126         i915_gem_free_mmap_offset(obj);
3127
3128         drm_free(obj_priv->page_cpu_valid, 1, DRM_MEM_DRIVER);
3129         drm_free(obj->driver_private, 1, DRM_MEM_DRIVER);
3130 }
3131
3132 /** Unbinds all objects that are on the given buffer list. */
3133 static int
3134 i915_gem_evict_from_list(struct drm_device *dev, struct list_head *head)
3135 {
3136         struct drm_gem_object *obj;
3137         struct drm_i915_gem_object *obj_priv;
3138         int ret;
3139
3140         while (!list_empty(head)) {
3141                 obj_priv = list_first_entry(head,
3142                                             struct drm_i915_gem_object,
3143                                             list);
3144                 obj = obj_priv->obj;
3145
3146                 if (obj_priv->pin_count != 0) {
3147                         DRM_ERROR("Pinned object in unbind list\n");
3148                         mutex_unlock(&dev->struct_mutex);
3149                         return -EINVAL;
3150                 }
3151
3152                 ret = i915_gem_object_unbind(obj);
3153                 if (ret != 0) {
3154                         DRM_ERROR("Error unbinding object in LeaveVT: %d\n",
3155                                   ret);
3156                         mutex_unlock(&dev->struct_mutex);
3157                         return ret;
3158                 }
3159         }
3160
3161
3162         return 0;
3163 }
3164
3165 int
3166 i915_gem_idle(struct drm_device *dev)
3167 {
3168         drm_i915_private_t *dev_priv = dev->dev_private;
3169         uint32_t seqno, cur_seqno, last_seqno;
3170         int stuck, ret;
3171
3172         mutex_lock(&dev->struct_mutex);
3173
3174         if (dev_priv->mm.suspended || dev_priv->ring.ring_obj == NULL) {
3175                 mutex_unlock(&dev->struct_mutex);
3176                 return 0;
3177         }
3178
3179         /* Hack!  Don't let anybody do execbuf while we don't control the chip.
3180          * We need to replace this with a semaphore, or something.
3181          */
3182         dev_priv->mm.suspended = 1;
3183
3184         /* Cancel the retire work handler, wait for it to finish if running
3185          */
3186         mutex_unlock(&dev->struct_mutex);
3187         cancel_delayed_work_sync(&dev_priv->mm.retire_work);
3188         mutex_lock(&dev->struct_mutex);
3189
3190         i915_kernel_lost_context(dev);
3191
3192         /* Flush the GPU along with all non-CPU write domains
3193          */
3194         i915_gem_flush(dev, ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT),
3195                        ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
3196         seqno = i915_add_request(dev, ~I915_GEM_DOMAIN_CPU);
3197
3198         if (seqno == 0) {
3199                 mutex_unlock(&dev->struct_mutex);
3200                 return -ENOMEM;
3201         }
3202
3203         dev_priv->mm.waiting_gem_seqno = seqno;
3204         last_seqno = 0;
3205         stuck = 0;
3206         for (;;) {
3207                 cur_seqno = i915_get_gem_seqno(dev);
3208                 if (i915_seqno_passed(cur_seqno, seqno))
3209                         break;
3210                 if (last_seqno == cur_seqno) {
3211                         if (stuck++ > 100) {
3212                                 DRM_ERROR("hardware wedged\n");
3213                                 dev_priv->mm.wedged = 1;
3214                                 DRM_WAKEUP(&dev_priv->irq_queue);
3215                                 break;
3216                         }
3217                 }
3218                 msleep(10);
3219                 last_seqno = cur_seqno;
3220         }
3221         dev_priv->mm.waiting_gem_seqno = 0;
3222
3223         i915_gem_retire_requests(dev);
3224
3225         if (!dev_priv->mm.wedged) {
3226                 /* Active and flushing should now be empty as we've
3227                  * waited for a sequence higher than any pending execbuffer
3228                  */
3229                 WARN_ON(!list_empty(&dev_priv->mm.active_list));
3230                 WARN_ON(!list_empty(&dev_priv->mm.flushing_list));
3231                 /* Request should now be empty as we've also waited
3232                  * for the last request in the list
3233                  */
3234                 WARN_ON(!list_empty(&dev_priv->mm.request_list));
3235         }
3236
3237         /* Empty the active and flushing lists to inactive.  If there's
3238          * anything left at this point, it means that we're wedged and
3239          * nothing good's going to happen by leaving them there.  So strip
3240          * the GPU domains and just stuff them onto inactive.
3241          */
3242         while (!list_empty(&dev_priv->mm.active_list)) {
3243                 struct drm_i915_gem_object *obj_priv;
3244
3245                 obj_priv = list_first_entry(&dev_priv->mm.active_list,
3246                                             struct drm_i915_gem_object,
3247                                             list);
3248                 obj_priv->obj->write_domain &= ~I915_GEM_GPU_DOMAINS;
3249                 i915_gem_object_move_to_inactive(obj_priv->obj);
3250         }
3251
3252         while (!list_empty(&dev_priv->mm.flushing_list)) {
3253                 struct drm_i915_gem_object *obj_priv;
3254
3255                 obj_priv = list_first_entry(&dev_priv->mm.flushing_list,
3256                                             struct drm_i915_gem_object,
3257                                             list);
3258                 obj_priv->obj->write_domain &= ~I915_GEM_GPU_DOMAINS;
3259                 i915_gem_object_move_to_inactive(obj_priv->obj);
3260         }
3261
3262
3263         /* Move all inactive buffers out of the GTT. */
3264         ret = i915_gem_evict_from_list(dev, &dev_priv->mm.inactive_list);
3265         WARN_ON(!list_empty(&dev_priv->mm.inactive_list));
3266         if (ret) {
3267                 mutex_unlock(&dev->struct_mutex);
3268                 return ret;
3269         }
3270
3271         i915_gem_cleanup_ringbuffer(dev);
3272         mutex_unlock(&dev->struct_mutex);
3273
3274         return 0;
3275 }
3276
3277 static int
3278 i915_gem_init_hws(struct drm_device *dev)
3279 {
3280         drm_i915_private_t *dev_priv = dev->dev_private;
3281         struct drm_gem_object *obj;
3282         struct drm_i915_gem_object *obj_priv;
3283         int ret;
3284
3285         /* If we need a physical address for the status page, it's already
3286          * initialized at driver load time.
3287          */
3288         if (!I915_NEED_GFX_HWS(dev))
3289                 return 0;
3290
3291         obj = drm_gem_object_alloc(dev, 4096);
3292         if (obj == NULL) {
3293                 DRM_ERROR("Failed to allocate status page\n");
3294                 return -ENOMEM;
3295         }
3296         obj_priv = obj->driver_private;
3297         obj_priv->agp_type = AGP_USER_CACHED_MEMORY;
3298
3299         ret = i915_gem_object_pin(obj, 4096);
3300         if (ret != 0) {
3301                 drm_gem_object_unreference(obj);
3302                 return ret;
3303         }
3304
3305         dev_priv->status_gfx_addr = obj_priv->gtt_offset;
3306
3307         dev_priv->hw_status_page = kmap(obj_priv->page_list[0]);
3308         if (dev_priv->hw_status_page == NULL) {
3309                 DRM_ERROR("Failed to map status page.\n");
3310                 memset(&dev_priv->hws_map, 0, sizeof(dev_priv->hws_map));
3311                 i915_gem_object_unpin(obj);
3312                 drm_gem_object_unreference(obj);
3313                 return -EINVAL;
3314         }
3315         dev_priv->hws_obj = obj;
3316         memset(dev_priv->hw_status_page, 0, PAGE_SIZE);
3317         I915_WRITE(HWS_PGA, dev_priv->status_gfx_addr);
3318         I915_READ(HWS_PGA); /* posting read */
3319         DRM_DEBUG("hws offset: 0x%08x\n", dev_priv->status_gfx_addr);
3320
3321         return 0;
3322 }
3323
3324 static void
3325 i915_gem_cleanup_hws(struct drm_device *dev)
3326 {
3327         drm_i915_private_t *dev_priv = dev->dev_private;
3328         struct drm_gem_object *obj;
3329         struct drm_i915_gem_object *obj_priv;
3330
3331         if (dev_priv->hws_obj == NULL)
3332                 return;
3333
3334         obj = dev_priv->hws_obj;
3335         obj_priv = obj->driver_private;
3336
3337         kunmap(obj_priv->page_list[0]);
3338         i915_gem_object_unpin(obj);
3339         drm_gem_object_unreference(obj);
3340         dev_priv->hws_obj = NULL;
3341
3342         memset(&dev_priv->hws_map, 0, sizeof(dev_priv->hws_map));
3343         dev_priv->hw_status_page = NULL;
3344
3345         /* Write high address into HWS_PGA when disabling. */
3346         I915_WRITE(HWS_PGA, 0x1ffff000);
3347 }
3348
3349 int
3350 i915_gem_init_ringbuffer(struct drm_device *dev)
3351 {
3352         drm_i915_private_t *dev_priv = dev->dev_private;
3353         struct drm_gem_object *obj;
3354         struct drm_i915_gem_object *obj_priv;
3355         drm_i915_ring_buffer_t *ring = &dev_priv->ring;
3356         int ret;
3357         u32 head;
3358
3359         ret = i915_gem_init_hws(dev);
3360         if (ret != 0)
3361                 return ret;
3362
3363         obj = drm_gem_object_alloc(dev, 128 * 1024);
3364         if (obj == NULL) {
3365                 DRM_ERROR("Failed to allocate ringbuffer\n");
3366                 i915_gem_cleanup_hws(dev);
3367                 return -ENOMEM;
3368         }
3369         obj_priv = obj->driver_private;
3370
3371         ret = i915_gem_object_pin(obj, 4096);
3372         if (ret != 0) {
3373                 drm_gem_object_unreference(obj);
3374                 i915_gem_cleanup_hws(dev);
3375                 return ret;
3376         }
3377
3378         /* Set up the kernel mapping for the ring. */
3379         ring->Size = obj->size;
3380         ring->tail_mask = obj->size - 1;
3381
3382         ring->map.offset = dev->agp->base + obj_priv->gtt_offset;
3383         ring->map.size = obj->size;
3384         ring->map.type = 0;
3385         ring->map.flags = 0;
3386         ring->map.mtrr = 0;
3387
3388         drm_core_ioremap_wc(&ring->map, dev);
3389         if (ring->map.handle == NULL) {
3390                 DRM_ERROR("Failed to map ringbuffer.\n");
3391                 memset(&dev_priv->ring, 0, sizeof(dev_priv->ring));
3392                 i915_gem_object_unpin(obj);
3393                 drm_gem_object_unreference(obj);
3394                 i915_gem_cleanup_hws(dev);
3395                 return -EINVAL;
3396         }
3397         ring->ring_obj = obj;
3398         ring->virtual_start = ring->map.handle;
3399
3400         /* Stop the ring if it's running. */
3401         I915_WRITE(PRB0_CTL, 0);
3402         I915_WRITE(PRB0_TAIL, 0);
3403         I915_WRITE(PRB0_HEAD, 0);
3404
3405         /* Initialize the ring. */
3406         I915_WRITE(PRB0_START, obj_priv->gtt_offset);
3407         head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
3408
3409         /* G45 ring initialization fails to reset head to zero */
3410         if (head != 0) {
3411                 DRM_ERROR("Ring head not reset to zero "
3412                           "ctl %08x head %08x tail %08x start %08x\n",
3413                           I915_READ(PRB0_CTL),
3414                           I915_READ(PRB0_HEAD),
3415                           I915_READ(PRB0_TAIL),
3416                           I915_READ(PRB0_START));
3417                 I915_WRITE(PRB0_HEAD, 0);
3418
3419                 DRM_ERROR("Ring head forced to zero "
3420                           "ctl %08x head %08x tail %08x start %08x\n",
3421                           I915_READ(PRB0_CTL),
3422                           I915_READ(PRB0_HEAD),
3423                           I915_READ(PRB0_TAIL),
3424                           I915_READ(PRB0_START));
3425         }
3426
3427         I915_WRITE(PRB0_CTL,
3428                    ((obj->size - 4096) & RING_NR_PAGES) |
3429                    RING_NO_REPORT |
3430                    RING_VALID);
3431
3432         head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
3433
3434         /* If the head is still not zero, the ring is dead */
3435         if (head != 0) {
3436                 DRM_ERROR("Ring initialization failed "
3437                           "ctl %08x head %08x tail %08x start %08x\n",
3438                           I915_READ(PRB0_CTL),
3439                           I915_READ(PRB0_HEAD),
3440                           I915_READ(PRB0_TAIL),
3441                           I915_READ(PRB0_START));
3442                 return -EIO;
3443         }
3444
3445         /* Update our cache of the ring state */
3446         if (!drm_core_check_feature(dev, DRIVER_MODESET))
3447                 i915_kernel_lost_context(dev);
3448         else {
3449                 ring->head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
3450                 ring->tail = I915_READ(PRB0_TAIL) & TAIL_ADDR;
3451                 ring->space = ring->head - (ring->tail + 8);
3452                 if (ring->space < 0)
3453                         ring->space += ring->Size;
3454         }
3455
3456         return 0;
3457 }
3458
3459 void
3460 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
3461 {
3462         drm_i915_private_t *dev_priv = dev->dev_private;
3463
3464         if (dev_priv->ring.ring_obj == NULL)
3465                 return;
3466
3467         drm_core_ioremapfree(&dev_priv->ring.map, dev);
3468
3469         i915_gem_object_unpin(dev_priv->ring.ring_obj);
3470         drm_gem_object_unreference(dev_priv->ring.ring_obj);
3471         dev_priv->ring.ring_obj = NULL;
3472         memset(&dev_priv->ring, 0, sizeof(dev_priv->ring));
3473
3474         i915_gem_cleanup_hws(dev);
3475 }
3476
3477 int
3478 i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
3479                        struct drm_file *file_priv)
3480 {
3481         drm_i915_private_t *dev_priv = dev->dev_private;
3482         int ret;
3483
3484         if (drm_core_check_feature(dev, DRIVER_MODESET))
3485                 return 0;
3486
3487         if (dev_priv->mm.wedged) {
3488                 DRM_ERROR("Reenabling wedged hardware, good luck\n");
3489                 dev_priv->mm.wedged = 0;
3490         }
3491
3492         mutex_lock(&dev->struct_mutex);
3493         dev_priv->mm.suspended = 0;
3494
3495         ret = i915_gem_init_ringbuffer(dev);
3496         if (ret != 0)
3497                 return ret;
3498
3499         BUG_ON(!list_empty(&dev_priv->mm.active_list));
3500         BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
3501         BUG_ON(!list_empty(&dev_priv->mm.inactive_list));
3502         BUG_ON(!list_empty(&dev_priv->mm.request_list));
3503         mutex_unlock(&dev->struct_mutex);
3504
3505         drm_irq_install(dev);
3506
3507         return 0;
3508 }
3509
3510 int
3511 i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
3512                        struct drm_file *file_priv)
3513 {
3514         int ret;
3515
3516         if (drm_core_check_feature(dev, DRIVER_MODESET))
3517                 return 0;
3518
3519         ret = i915_gem_idle(dev);
3520         drm_irq_uninstall(dev);
3521
3522         return ret;
3523 }
3524
3525 void
3526 i915_gem_lastclose(struct drm_device *dev)
3527 {
3528         int ret;
3529
3530         if (drm_core_check_feature(dev, DRIVER_MODESET))
3531                 return;
3532
3533         ret = i915_gem_idle(dev);
3534         if (ret)
3535                 DRM_ERROR("failed to idle hardware: %d\n", ret);
3536 }
3537
3538 void
3539 i915_gem_load(struct drm_device *dev)
3540 {
3541         drm_i915_private_t *dev_priv = dev->dev_private;
3542
3543         INIT_LIST_HEAD(&dev_priv->mm.active_list);
3544         INIT_LIST_HEAD(&dev_priv->mm.flushing_list);
3545         INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
3546         INIT_LIST_HEAD(&dev_priv->mm.request_list);
3547         INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
3548                           i915_gem_retire_work_handler);
3549         dev_priv->mm.next_gem_seqno = 1;
3550
3551         /* Old X drivers will take 0-2 for front, back, depth buffers */
3552         dev_priv->fence_reg_start = 3;
3553
3554         if (IS_I965G(dev) || IS_I945G(dev) || IS_I945GM(dev) || IS_G33(dev))
3555                 dev_priv->num_fence_regs = 16;
3556         else
3557                 dev_priv->num_fence_regs = 8;
3558
3559         i915_gem_detect_bit_6_swizzle(dev);
3560 }
3561
3562 /*
3563  * Create a physically contiguous memory object for this object
3564  * e.g. for cursor + overlay regs
3565  */
3566 int i915_gem_init_phys_object(struct drm_device *dev,
3567                               int id, int size)
3568 {
3569         drm_i915_private_t *dev_priv = dev->dev_private;
3570         struct drm_i915_gem_phys_object *phys_obj;
3571         int ret;
3572
3573         if (dev_priv->mm.phys_objs[id - 1] || !size)
3574                 return 0;
3575
3576         phys_obj = drm_calloc(1, sizeof(struct drm_i915_gem_phys_object), DRM_MEM_DRIVER);
3577         if (!phys_obj)
3578                 return -ENOMEM;
3579
3580         phys_obj->id = id;
3581
3582         phys_obj->handle = drm_pci_alloc(dev, size, 0, 0xffffffff);
3583         if (!phys_obj->handle) {
3584                 ret = -ENOMEM;
3585                 goto kfree_obj;
3586         }
3587 #ifdef CONFIG_X86
3588         set_memory_wc((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
3589 #endif
3590
3591         dev_priv->mm.phys_objs[id - 1] = phys_obj;
3592
3593         return 0;
3594 kfree_obj:
3595         drm_free(phys_obj, sizeof(struct drm_i915_gem_phys_object), DRM_MEM_DRIVER);
3596         return ret;
3597 }
3598
3599 void i915_gem_free_phys_object(struct drm_device *dev, int id)
3600 {
3601         drm_i915_private_t *dev_priv = dev->dev_private;
3602         struct drm_i915_gem_phys_object *phys_obj;
3603
3604         if (!dev_priv->mm.phys_objs[id - 1])
3605                 return;
3606
3607         phys_obj = dev_priv->mm.phys_objs[id - 1];
3608         if (phys_obj->cur_obj) {
3609                 i915_gem_detach_phys_object(dev, phys_obj->cur_obj);
3610         }
3611
3612 #ifdef CONFIG_X86
3613         set_memory_wb((unsigned long)phys_obj->handle->vaddr, phys_obj->handle->size / PAGE_SIZE);
3614 #endif
3615         drm_pci_free(dev, phys_obj->handle);
3616         kfree(phys_obj);
3617         dev_priv->mm.phys_objs[id - 1] = NULL;
3618 }
3619
3620 void i915_gem_free_all_phys_object(struct drm_device *dev)
3621 {
3622         int i;
3623
3624         for (i = I915_GEM_PHYS_CURSOR_0; i <= I915_MAX_PHYS_OBJECT; i++)
3625                 i915_gem_free_phys_object(dev, i);
3626 }
3627
3628 void i915_gem_detach_phys_object(struct drm_device *dev,
3629                                  struct drm_gem_object *obj)
3630 {
3631         struct drm_i915_gem_object *obj_priv;
3632         int i;
3633         int ret;
3634         int page_count;
3635
3636         obj_priv = obj->driver_private;
3637         if (!obj_priv->phys_obj)
3638                 return;
3639
3640         ret = i915_gem_object_get_page_list(obj);
3641         if (ret)
3642                 goto out;
3643
3644         page_count = obj->size / PAGE_SIZE;
3645
3646         for (i = 0; i < page_count; i++) {
3647                 char *dst = kmap_atomic(obj_priv->page_list[i], KM_USER0);
3648                 char *src = obj_priv->phys_obj->handle->vaddr + (i * PAGE_SIZE);
3649
3650                 memcpy(dst, src, PAGE_SIZE);
3651                 kunmap_atomic(dst, KM_USER0);
3652         }
3653         drm_clflush_pages(obj_priv->page_list, page_count);
3654         drm_agp_chipset_flush(dev);
3655 out:
3656         obj_priv->phys_obj->cur_obj = NULL;
3657         obj_priv->phys_obj = NULL;
3658 }
3659
3660 int
3661 i915_gem_attach_phys_object(struct drm_device *dev,
3662                             struct drm_gem_object *obj, int id)
3663 {
3664         drm_i915_private_t *dev_priv = dev->dev_private;
3665         struct drm_i915_gem_object *obj_priv;
3666         int ret = 0;
3667         int page_count;
3668         int i;
3669
3670         if (id > I915_MAX_PHYS_OBJECT)
3671                 return -EINVAL;
3672
3673         obj_priv = obj->driver_private;
3674
3675         if (obj_priv->phys_obj) {
3676                 if (obj_priv->phys_obj->id == id)
3677                         return 0;
3678                 i915_gem_detach_phys_object(dev, obj);
3679         }
3680
3681
3682         /* create a new object */
3683         if (!dev_priv->mm.phys_objs[id - 1]) {
3684                 ret = i915_gem_init_phys_object(dev, id,
3685                                                 obj->size);
3686                 if (ret) {
3687                         DRM_ERROR("failed to init phys object %d size: %zu\n", id, obj->size);
3688                         goto out;
3689                 }
3690         }
3691
3692         /* bind to the object */
3693         obj_priv->phys_obj = dev_priv->mm.phys_objs[id - 1];
3694         obj_priv->phys_obj->cur_obj = obj;
3695
3696         ret = i915_gem_object_get_page_list(obj);
3697         if (ret) {
3698                 DRM_ERROR("failed to get page list\n");
3699                 goto out;
3700         }
3701
3702         page_count = obj->size / PAGE_SIZE;
3703
3704         for (i = 0; i < page_count; i++) {
3705                 char *src = kmap_atomic(obj_priv->page_list[i], KM_USER0);
3706                 char *dst = obj_priv->phys_obj->handle->vaddr + (i * PAGE_SIZE);
3707
3708                 memcpy(dst, src, PAGE_SIZE);
3709                 kunmap_atomic(src, KM_USER0);
3710         }
3711
3712         return 0;
3713 out:
3714         return ret;
3715 }
3716
3717 static int
3718 i915_gem_phys_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
3719                      struct drm_i915_gem_pwrite *args,
3720                      struct drm_file *file_priv)
3721 {
3722         struct drm_i915_gem_object *obj_priv = obj->driver_private;
3723         void *obj_addr;
3724         int ret;
3725         char __user *user_data;
3726
3727         user_data = (char __user *) (uintptr_t) args->data_ptr;
3728         obj_addr = obj_priv->phys_obj->handle->vaddr + args->offset;
3729
3730         DRM_DEBUG("obj_addr %p, %lld\n", obj_addr, args->size);
3731         ret = copy_from_user(obj_addr, user_data, args->size);
3732         if (ret)
3733                 return -EFAULT;
3734
3735         drm_agp_chipset_flush(dev);
3736         return 0;
3737 }