]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - drivers/gpu/drm/i915/i915_gem.c
3fde82be014f3a4b2e4046826b076d7540e17afc
[linux-2.6-omap-h63xx.git] / 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
34 #define I915_GEM_GPU_DOMAINS    (~(I915_GEM_DOMAIN_CPU | I915_GEM_DOMAIN_GTT))
35
36 static void
37 i915_gem_object_set_to_gpu_domain(struct drm_gem_object *obj,
38                                   uint32_t read_domains,
39                                   uint32_t write_domain);
40 static void i915_gem_object_flush_gpu_write_domain(struct drm_gem_object *obj);
41 static void i915_gem_object_flush_gtt_write_domain(struct drm_gem_object *obj);
42 static void i915_gem_object_flush_cpu_write_domain(struct drm_gem_object *obj);
43 static int i915_gem_object_set_to_gtt_domain(struct drm_gem_object *obj,
44                                              int write);
45 static int i915_gem_object_set_to_cpu_domain(struct drm_gem_object *obj,
46                                              int write);
47 static int i915_gem_object_set_cpu_read_domain_range(struct drm_gem_object *obj,
48                                                      uint64_t offset,
49                                                      uint64_t size);
50 static void i915_gem_object_set_to_full_cpu_read_domain(struct drm_gem_object *obj);
51 static int i915_gem_object_get_page_list(struct drm_gem_object *obj);
52 static void i915_gem_object_free_page_list(struct drm_gem_object *obj);
53 static int i915_gem_object_wait_rendering(struct drm_gem_object *obj);
54
55 static void
56 i915_gem_cleanup_ringbuffer(struct drm_device *dev);
57
58 int
59 i915_gem_init_ioctl(struct drm_device *dev, void *data,
60                     struct drm_file *file_priv)
61 {
62         drm_i915_private_t *dev_priv = dev->dev_private;
63         struct drm_i915_gem_init *args = data;
64
65         mutex_lock(&dev->struct_mutex);
66
67         if (args->gtt_start >= args->gtt_end ||
68             (args->gtt_start & (PAGE_SIZE - 1)) != 0 ||
69             (args->gtt_end & (PAGE_SIZE - 1)) != 0) {
70                 mutex_unlock(&dev->struct_mutex);
71                 return -EINVAL;
72         }
73
74         drm_mm_init(&dev_priv->mm.gtt_space, args->gtt_start,
75             args->gtt_end - args->gtt_start);
76
77         dev->gtt_total = (uint32_t) (args->gtt_end - args->gtt_start);
78
79         mutex_unlock(&dev->struct_mutex);
80
81         return 0;
82 }
83
84 int
85 i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
86                             struct drm_file *file_priv)
87 {
88         struct drm_i915_gem_get_aperture *args = data;
89
90         if (!(dev->driver->driver_features & DRIVER_GEM))
91                 return -ENODEV;
92
93         args->aper_size = dev->gtt_total;
94         args->aper_available_size = (args->aper_size -
95                                      atomic_read(&dev->pin_memory));
96
97         return 0;
98 }
99
100
101 /**
102  * Creates a new mm object and returns a handle to it.
103  */
104 int
105 i915_gem_create_ioctl(struct drm_device *dev, void *data,
106                       struct drm_file *file_priv)
107 {
108         struct drm_i915_gem_create *args = data;
109         struct drm_gem_object *obj;
110         int handle, ret;
111
112         args->size = roundup(args->size, PAGE_SIZE);
113
114         /* Allocate the new object */
115         obj = drm_gem_object_alloc(dev, args->size);
116         if (obj == NULL)
117                 return -ENOMEM;
118
119         ret = drm_gem_handle_create(file_priv, obj, &handle);
120         mutex_lock(&dev->struct_mutex);
121         drm_gem_object_handle_unreference(obj);
122         mutex_unlock(&dev->struct_mutex);
123
124         if (ret)
125                 return ret;
126
127         args->handle = handle;
128
129         return 0;
130 }
131
132 /**
133  * Reads data from the object referenced by handle.
134  *
135  * On error, the contents of *data are undefined.
136  */
137 int
138 i915_gem_pread_ioctl(struct drm_device *dev, void *data,
139                      struct drm_file *file_priv)
140 {
141         struct drm_i915_gem_pread *args = data;
142         struct drm_gem_object *obj;
143         struct drm_i915_gem_object *obj_priv;
144         ssize_t read;
145         loff_t offset;
146         int ret;
147
148         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
149         if (obj == NULL)
150                 return -EBADF;
151         obj_priv = obj->driver_private;
152
153         /* Bounds check source.
154          *
155          * XXX: This could use review for overflow issues...
156          */
157         if (args->offset > obj->size || args->size > obj->size ||
158             args->offset + args->size > obj->size) {
159                 drm_gem_object_unreference(obj);
160                 return -EINVAL;
161         }
162
163         mutex_lock(&dev->struct_mutex);
164
165         ret = i915_gem_object_set_cpu_read_domain_range(obj, args->offset,
166                                                         args->size);
167         if (ret != 0) {
168                 drm_gem_object_unreference(obj);
169                 mutex_unlock(&dev->struct_mutex);
170                 return ret;
171         }
172
173         offset = args->offset;
174
175         read = vfs_read(obj->filp, (char __user *)(uintptr_t)args->data_ptr,
176                         args->size, &offset);
177         if (read != args->size) {
178                 drm_gem_object_unreference(obj);
179                 mutex_unlock(&dev->struct_mutex);
180                 if (read < 0)
181                         return read;
182                 else
183                         return -EINVAL;
184         }
185
186         drm_gem_object_unreference(obj);
187         mutex_unlock(&dev->struct_mutex);
188
189         return 0;
190 }
191
192 /* This is the fast write path which cannot handle
193  * page faults in the source data
194  */
195
196 static inline int
197 fast_user_write(struct io_mapping *mapping,
198                 loff_t page_base, int page_offset,
199                 char __user *user_data,
200                 int length)
201 {
202         char *vaddr_atomic;
203         unsigned long unwritten;
204
205         vaddr_atomic = io_mapping_map_atomic_wc(mapping, page_base);
206         unwritten = __copy_from_user_inatomic_nocache(vaddr_atomic + page_offset,
207                                                       user_data, length);
208         io_mapping_unmap_atomic(vaddr_atomic);
209         if (unwritten)
210                 return -EFAULT;
211         return 0;
212 }
213
214 /* Here's the write path which can sleep for
215  * page faults
216  */
217
218 static inline int
219 slow_user_write(struct io_mapping *mapping,
220                 loff_t page_base, int page_offset,
221                 char __user *user_data,
222                 int length)
223 {
224         char __iomem *vaddr;
225         unsigned long unwritten;
226
227         vaddr = io_mapping_map_wc(mapping, page_base);
228         if (vaddr == NULL)
229                 return -EFAULT;
230         unwritten = __copy_from_user(vaddr + page_offset,
231                                      user_data, length);
232         io_mapping_unmap(vaddr);
233         if (unwritten)
234                 return -EFAULT;
235         return 0;
236 }
237
238 static int
239 i915_gem_gtt_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
240                     struct drm_i915_gem_pwrite *args,
241                     struct drm_file *file_priv)
242 {
243         struct drm_i915_gem_object *obj_priv = obj->driver_private;
244         drm_i915_private_t *dev_priv = dev->dev_private;
245         ssize_t remain;
246         loff_t offset, page_base;
247         char __user *user_data;
248         int page_offset, page_length;
249         int ret;
250
251         user_data = (char __user *) (uintptr_t) args->data_ptr;
252         remain = args->size;
253         if (!access_ok(VERIFY_READ, user_data, remain))
254                 return -EFAULT;
255
256
257         mutex_lock(&dev->struct_mutex);
258         ret = i915_gem_object_pin(obj, 0);
259         if (ret) {
260                 mutex_unlock(&dev->struct_mutex);
261                 return ret;
262         }
263         ret = i915_gem_object_set_to_gtt_domain(obj, 1);
264         if (ret)
265                 goto fail;
266
267         obj_priv = obj->driver_private;
268         offset = obj_priv->gtt_offset + args->offset;
269         obj_priv->dirty = 1;
270
271         while (remain > 0) {
272                 /* Operation in this page
273                  *
274                  * page_base = page offset within aperture
275                  * page_offset = offset within page
276                  * page_length = bytes to copy for this page
277                  */
278                 page_base = (offset & ~(PAGE_SIZE-1));
279                 page_offset = offset & (PAGE_SIZE-1);
280                 page_length = remain;
281                 if ((page_offset + remain) > PAGE_SIZE)
282                         page_length = PAGE_SIZE - page_offset;
283
284                 ret = fast_user_write (dev_priv->mm.gtt_mapping, page_base,
285                                        page_offset, user_data, page_length);
286
287                 /* If we get a fault while copying data, then (presumably) our
288                  * source page isn't available. In this case, use the
289                  * non-atomic function
290                  */
291                 if (ret) {
292                         ret = slow_user_write (dev_priv->mm.gtt_mapping,
293                                                page_base, page_offset,
294                                                user_data, page_length);
295                         if (ret)
296                                 goto fail;
297                 }
298
299                 remain -= page_length;
300                 user_data += page_length;
301                 offset += page_length;
302         }
303
304 fail:
305         i915_gem_object_unpin(obj);
306         mutex_unlock(&dev->struct_mutex);
307
308         return ret;
309 }
310
311 static int
312 i915_gem_shmem_pwrite(struct drm_device *dev, struct drm_gem_object *obj,
313                       struct drm_i915_gem_pwrite *args,
314                       struct drm_file *file_priv)
315 {
316         int ret;
317         loff_t offset;
318         ssize_t written;
319
320         mutex_lock(&dev->struct_mutex);
321
322         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
323         if (ret) {
324                 mutex_unlock(&dev->struct_mutex);
325                 return ret;
326         }
327
328         offset = args->offset;
329
330         written = vfs_write(obj->filp,
331                             (char __user *)(uintptr_t) args->data_ptr,
332                             args->size, &offset);
333         if (written != args->size) {
334                 mutex_unlock(&dev->struct_mutex);
335                 if (written < 0)
336                         return written;
337                 else
338                         return -EINVAL;
339         }
340
341         mutex_unlock(&dev->struct_mutex);
342
343         return 0;
344 }
345
346 /**
347  * Writes data to the object referenced by handle.
348  *
349  * On error, the contents of the buffer that were to be modified are undefined.
350  */
351 int
352 i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
353                       struct drm_file *file_priv)
354 {
355         struct drm_i915_gem_pwrite *args = data;
356         struct drm_gem_object *obj;
357         struct drm_i915_gem_object *obj_priv;
358         int ret = 0;
359
360         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
361         if (obj == NULL)
362                 return -EBADF;
363         obj_priv = obj->driver_private;
364
365         /* Bounds check destination.
366          *
367          * XXX: This could use review for overflow issues...
368          */
369         if (args->offset > obj->size || args->size > obj->size ||
370             args->offset + args->size > obj->size) {
371                 drm_gem_object_unreference(obj);
372                 return -EINVAL;
373         }
374
375         /* We can only do the GTT pwrite on untiled buffers, as otherwise
376          * it would end up going through the fenced access, and we'll get
377          * different detiling behavior between reading and writing.
378          * pread/pwrite currently are reading and writing from the CPU
379          * perspective, requiring manual detiling by the client.
380          */
381         if (obj_priv->tiling_mode == I915_TILING_NONE &&
382             dev->gtt_total != 0)
383                 ret = i915_gem_gtt_pwrite(dev, obj, args, file_priv);
384         else
385                 ret = i915_gem_shmem_pwrite(dev, obj, args, file_priv);
386
387 #if WATCH_PWRITE
388         if (ret)
389                 DRM_INFO("pwrite failed %d\n", ret);
390 #endif
391
392         drm_gem_object_unreference(obj);
393
394         return ret;
395 }
396
397 /**
398  * Called when user space prepares to use an object with the CPU, either
399  * through the mmap ioctl's mapping or a GTT mapping.
400  */
401 int
402 i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
403                           struct drm_file *file_priv)
404 {
405         struct drm_i915_gem_set_domain *args = data;
406         struct drm_gem_object *obj;
407         uint32_t read_domains = args->read_domains;
408         uint32_t write_domain = args->write_domain;
409         int ret;
410
411         if (!(dev->driver->driver_features & DRIVER_GEM))
412                 return -ENODEV;
413
414         /* Only handle setting domains to types used by the CPU. */
415         if (write_domain & ~(I915_GEM_DOMAIN_CPU | I915_GEM_DOMAIN_GTT))
416                 return -EINVAL;
417
418         if (read_domains & ~(I915_GEM_DOMAIN_CPU | I915_GEM_DOMAIN_GTT))
419                 return -EINVAL;
420
421         /* Having something in the write domain implies it's in the read
422          * domain, and only that read domain.  Enforce that in the request.
423          */
424         if (write_domain != 0 && read_domains != write_domain)
425                 return -EINVAL;
426
427         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
428         if (obj == NULL)
429                 return -EBADF;
430
431         mutex_lock(&dev->struct_mutex);
432 #if WATCH_BUF
433         DRM_INFO("set_domain_ioctl %p(%d), %08x %08x\n",
434                  obj, obj->size, read_domains, write_domain);
435 #endif
436         if (read_domains & I915_GEM_DOMAIN_GTT) {
437                 ret = i915_gem_object_set_to_gtt_domain(obj, write_domain != 0);
438
439                 /* Silently promote "you're not bound, there was nothing to do"
440                  * to success, since the client was just asking us to
441                  * make sure everything was done.
442                  */
443                 if (ret == -EINVAL)
444                         ret = 0;
445         } else {
446                 ret = i915_gem_object_set_to_cpu_domain(obj, write_domain != 0);
447         }
448
449         drm_gem_object_unreference(obj);
450         mutex_unlock(&dev->struct_mutex);
451         return ret;
452 }
453
454 /**
455  * Called when user space has done writes to this buffer
456  */
457 int
458 i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
459                       struct drm_file *file_priv)
460 {
461         struct drm_i915_gem_sw_finish *args = data;
462         struct drm_gem_object *obj;
463         struct drm_i915_gem_object *obj_priv;
464         int ret = 0;
465
466         if (!(dev->driver->driver_features & DRIVER_GEM))
467                 return -ENODEV;
468
469         mutex_lock(&dev->struct_mutex);
470         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
471         if (obj == NULL) {
472                 mutex_unlock(&dev->struct_mutex);
473                 return -EBADF;
474         }
475
476 #if WATCH_BUF
477         DRM_INFO("%s: sw_finish %d (%p %d)\n",
478                  __func__, args->handle, obj, obj->size);
479 #endif
480         obj_priv = obj->driver_private;
481
482         /* Pinned buffers may be scanout, so flush the cache */
483         if (obj_priv->pin_count)
484                 i915_gem_object_flush_cpu_write_domain(obj);
485
486         drm_gem_object_unreference(obj);
487         mutex_unlock(&dev->struct_mutex);
488         return ret;
489 }
490
491 /**
492  * Maps the contents of an object, returning the address it is mapped
493  * into.
494  *
495  * While the mapping holds a reference on the contents of the object, it doesn't
496  * imply a ref on the object itself.
497  */
498 int
499 i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
500                    struct drm_file *file_priv)
501 {
502         struct drm_i915_gem_mmap *args = data;
503         struct drm_gem_object *obj;
504         loff_t offset;
505         unsigned long addr;
506
507         if (!(dev->driver->driver_features & DRIVER_GEM))
508                 return -ENODEV;
509
510         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
511         if (obj == NULL)
512                 return -EBADF;
513
514         offset = args->offset;
515
516         down_write(&current->mm->mmap_sem);
517         addr = do_mmap(obj->filp, 0, args->size,
518                        PROT_READ | PROT_WRITE, MAP_SHARED,
519                        args->offset);
520         up_write(&current->mm->mmap_sem);
521         mutex_lock(&dev->struct_mutex);
522         drm_gem_object_unreference(obj);
523         mutex_unlock(&dev->struct_mutex);
524         if (IS_ERR((void *)addr))
525                 return addr;
526
527         args->addr_ptr = (uint64_t) addr;
528
529         return 0;
530 }
531
532 static void
533 i915_gem_object_free_page_list(struct drm_gem_object *obj)
534 {
535         struct drm_i915_gem_object *obj_priv = obj->driver_private;
536         int page_count = obj->size / PAGE_SIZE;
537         int i;
538
539         if (obj_priv->page_list == NULL)
540                 return;
541
542
543         for (i = 0; i < page_count; i++)
544                 if (obj_priv->page_list[i] != NULL) {
545                         if (obj_priv->dirty)
546                                 set_page_dirty(obj_priv->page_list[i]);
547                         mark_page_accessed(obj_priv->page_list[i]);
548                         page_cache_release(obj_priv->page_list[i]);
549                 }
550         obj_priv->dirty = 0;
551
552         drm_free(obj_priv->page_list,
553                  page_count * sizeof(struct page *),
554                  DRM_MEM_DRIVER);
555         obj_priv->page_list = NULL;
556 }
557
558 static void
559 i915_gem_object_move_to_active(struct drm_gem_object *obj, uint32_t seqno)
560 {
561         struct drm_device *dev = obj->dev;
562         drm_i915_private_t *dev_priv = dev->dev_private;
563         struct drm_i915_gem_object *obj_priv = obj->driver_private;
564
565         /* Add a reference if we're newly entering the active list. */
566         if (!obj_priv->active) {
567                 drm_gem_object_reference(obj);
568                 obj_priv->active = 1;
569         }
570         /* Move from whatever list we were on to the tail of execution. */
571         list_move_tail(&obj_priv->list,
572                        &dev_priv->mm.active_list);
573         obj_priv->last_rendering_seqno = seqno;
574 }
575
576 static void
577 i915_gem_object_move_to_flushing(struct drm_gem_object *obj)
578 {
579         struct drm_device *dev = obj->dev;
580         drm_i915_private_t *dev_priv = dev->dev_private;
581         struct drm_i915_gem_object *obj_priv = obj->driver_private;
582
583         BUG_ON(!obj_priv->active);
584         list_move_tail(&obj_priv->list, &dev_priv->mm.flushing_list);
585         obj_priv->last_rendering_seqno = 0;
586 }
587
588 static void
589 i915_gem_object_move_to_inactive(struct drm_gem_object *obj)
590 {
591         struct drm_device *dev = obj->dev;
592         drm_i915_private_t *dev_priv = dev->dev_private;
593         struct drm_i915_gem_object *obj_priv = obj->driver_private;
594
595         i915_verify_inactive(dev, __FILE__, __LINE__);
596         if (obj_priv->pin_count != 0)
597                 list_del_init(&obj_priv->list);
598         else
599                 list_move_tail(&obj_priv->list, &dev_priv->mm.inactive_list);
600
601         obj_priv->last_rendering_seqno = 0;
602         if (obj_priv->active) {
603                 obj_priv->active = 0;
604                 drm_gem_object_unreference(obj);
605         }
606         i915_verify_inactive(dev, __FILE__, __LINE__);
607 }
608
609 /**
610  * Creates a new sequence number, emitting a write of it to the status page
611  * plus an interrupt, which will trigger i915_user_interrupt_handler.
612  *
613  * Must be called with struct_lock held.
614  *
615  * Returned sequence numbers are nonzero on success.
616  */
617 static uint32_t
618 i915_add_request(struct drm_device *dev, uint32_t flush_domains)
619 {
620         drm_i915_private_t *dev_priv = dev->dev_private;
621         struct drm_i915_gem_request *request;
622         uint32_t seqno;
623         int was_empty;
624         RING_LOCALS;
625
626         request = drm_calloc(1, sizeof(*request), DRM_MEM_DRIVER);
627         if (request == NULL)
628                 return 0;
629
630         /* Grab the seqno we're going to make this request be, and bump the
631          * next (skipping 0 so it can be the reserved no-seqno value).
632          */
633         seqno = dev_priv->mm.next_gem_seqno;
634         dev_priv->mm.next_gem_seqno++;
635         if (dev_priv->mm.next_gem_seqno == 0)
636                 dev_priv->mm.next_gem_seqno++;
637
638         BEGIN_LP_RING(4);
639         OUT_RING(MI_STORE_DWORD_INDEX);
640         OUT_RING(I915_GEM_HWS_INDEX << MI_STORE_DWORD_INDEX_SHIFT);
641         OUT_RING(seqno);
642
643         OUT_RING(MI_USER_INTERRUPT);
644         ADVANCE_LP_RING();
645
646         DRM_DEBUG("%d\n", seqno);
647
648         request->seqno = seqno;
649         request->emitted_jiffies = jiffies;
650         was_empty = list_empty(&dev_priv->mm.request_list);
651         list_add_tail(&request->list, &dev_priv->mm.request_list);
652
653         /* Associate any objects on the flushing list matching the write
654          * domain we're flushing with our flush.
655          */
656         if (flush_domains != 0) {
657                 struct drm_i915_gem_object *obj_priv, *next;
658
659                 list_for_each_entry_safe(obj_priv, next,
660                                          &dev_priv->mm.flushing_list, list) {
661                         struct drm_gem_object *obj = obj_priv->obj;
662
663                         if ((obj->write_domain & flush_domains) ==
664                             obj->write_domain) {
665                                 obj->write_domain = 0;
666                                 i915_gem_object_move_to_active(obj, seqno);
667                         }
668                 }
669
670         }
671
672         if (was_empty && !dev_priv->mm.suspended)
673                 schedule_delayed_work(&dev_priv->mm.retire_work, HZ);
674         return seqno;
675 }
676
677 /**
678  * Command execution barrier
679  *
680  * Ensures that all commands in the ring are finished
681  * before signalling the CPU
682  */
683 static uint32_t
684 i915_retire_commands(struct drm_device *dev)
685 {
686         drm_i915_private_t *dev_priv = dev->dev_private;
687         uint32_t cmd = MI_FLUSH | MI_NO_WRITE_FLUSH;
688         uint32_t flush_domains = 0;
689         RING_LOCALS;
690
691         /* The sampler always gets flushed on i965 (sigh) */
692         if (IS_I965G(dev))
693                 flush_domains |= I915_GEM_DOMAIN_SAMPLER;
694         BEGIN_LP_RING(2);
695         OUT_RING(cmd);
696         OUT_RING(0); /* noop */
697         ADVANCE_LP_RING();
698         return flush_domains;
699 }
700
701 /**
702  * Moves buffers associated only with the given active seqno from the active
703  * to inactive list, potentially freeing them.
704  */
705 static void
706 i915_gem_retire_request(struct drm_device *dev,
707                         struct drm_i915_gem_request *request)
708 {
709         drm_i915_private_t *dev_priv = dev->dev_private;
710
711         /* Move any buffers on the active list that are no longer referenced
712          * by the ringbuffer to the flushing/inactive lists as appropriate.
713          */
714         while (!list_empty(&dev_priv->mm.active_list)) {
715                 struct drm_gem_object *obj;
716                 struct drm_i915_gem_object *obj_priv;
717
718                 obj_priv = list_first_entry(&dev_priv->mm.active_list,
719                                             struct drm_i915_gem_object,
720                                             list);
721                 obj = obj_priv->obj;
722
723                 /* If the seqno being retired doesn't match the oldest in the
724                  * list, then the oldest in the list must still be newer than
725                  * this seqno.
726                  */
727                 if (obj_priv->last_rendering_seqno != request->seqno)
728                         return;
729 #if WATCH_LRU
730                 DRM_INFO("%s: retire %d moves to inactive list %p\n",
731                          __func__, request->seqno, obj);
732 #endif
733
734                 if (obj->write_domain != 0)
735                         i915_gem_object_move_to_flushing(obj);
736                 else
737                         i915_gem_object_move_to_inactive(obj);
738         }
739 }
740
741 /**
742  * Returns true if seq1 is later than seq2.
743  */
744 static int
745 i915_seqno_passed(uint32_t seq1, uint32_t seq2)
746 {
747         return (int32_t)(seq1 - seq2) >= 0;
748 }
749
750 uint32_t
751 i915_get_gem_seqno(struct drm_device *dev)
752 {
753         drm_i915_private_t *dev_priv = dev->dev_private;
754
755         return READ_HWSP(dev_priv, I915_GEM_HWS_INDEX);
756 }
757
758 /**
759  * This function clears the request list as sequence numbers are passed.
760  */
761 void
762 i915_gem_retire_requests(struct drm_device *dev)
763 {
764         drm_i915_private_t *dev_priv = dev->dev_private;
765         uint32_t seqno;
766
767         seqno = i915_get_gem_seqno(dev);
768
769         while (!list_empty(&dev_priv->mm.request_list)) {
770                 struct drm_i915_gem_request *request;
771                 uint32_t retiring_seqno;
772
773                 request = list_first_entry(&dev_priv->mm.request_list,
774                                            struct drm_i915_gem_request,
775                                            list);
776                 retiring_seqno = request->seqno;
777
778                 if (i915_seqno_passed(seqno, retiring_seqno) ||
779                     dev_priv->mm.wedged) {
780                         i915_gem_retire_request(dev, request);
781
782                         list_del(&request->list);
783                         drm_free(request, sizeof(*request), DRM_MEM_DRIVER);
784                 } else
785                         break;
786         }
787 }
788
789 void
790 i915_gem_retire_work_handler(struct work_struct *work)
791 {
792         drm_i915_private_t *dev_priv;
793         struct drm_device *dev;
794
795         dev_priv = container_of(work, drm_i915_private_t,
796                                 mm.retire_work.work);
797         dev = dev_priv->dev;
798
799         mutex_lock(&dev->struct_mutex);
800         i915_gem_retire_requests(dev);
801         if (!dev_priv->mm.suspended &&
802             !list_empty(&dev_priv->mm.request_list))
803                 schedule_delayed_work(&dev_priv->mm.retire_work, HZ);
804         mutex_unlock(&dev->struct_mutex);
805 }
806
807 /**
808  * Waits for a sequence number to be signaled, and cleans up the
809  * request and object lists appropriately for that event.
810  */
811 static int
812 i915_wait_request(struct drm_device *dev, uint32_t seqno)
813 {
814         drm_i915_private_t *dev_priv = dev->dev_private;
815         int ret = 0;
816
817         BUG_ON(seqno == 0);
818
819         if (!i915_seqno_passed(i915_get_gem_seqno(dev), seqno)) {
820                 dev_priv->mm.waiting_gem_seqno = seqno;
821                 i915_user_irq_get(dev);
822                 ret = wait_event_interruptible(dev_priv->irq_queue,
823                                                i915_seqno_passed(i915_get_gem_seqno(dev),
824                                                                  seqno) ||
825                                                dev_priv->mm.wedged);
826                 i915_user_irq_put(dev);
827                 dev_priv->mm.waiting_gem_seqno = 0;
828         }
829         if (dev_priv->mm.wedged)
830                 ret = -EIO;
831
832         if (ret && ret != -ERESTARTSYS)
833                 DRM_ERROR("%s returns %d (awaiting %d at %d)\n",
834                           __func__, ret, seqno, i915_get_gem_seqno(dev));
835
836         /* Directly dispatch request retiring.  While we have the work queue
837          * to handle this, the waiter on a request often wants an associated
838          * buffer to have made it to the inactive list, and we would need
839          * a separate wait queue to handle that.
840          */
841         if (ret == 0)
842                 i915_gem_retire_requests(dev);
843
844         return ret;
845 }
846
847 static void
848 i915_gem_flush(struct drm_device *dev,
849                uint32_t invalidate_domains,
850                uint32_t flush_domains)
851 {
852         drm_i915_private_t *dev_priv = dev->dev_private;
853         uint32_t cmd;
854         RING_LOCALS;
855
856 #if WATCH_EXEC
857         DRM_INFO("%s: invalidate %08x flush %08x\n", __func__,
858                   invalidate_domains, flush_domains);
859 #endif
860
861         if (flush_domains & I915_GEM_DOMAIN_CPU)
862                 drm_agp_chipset_flush(dev);
863
864         if ((invalidate_domains | flush_domains) & ~(I915_GEM_DOMAIN_CPU |
865                                                      I915_GEM_DOMAIN_GTT)) {
866                 /*
867                  * read/write caches:
868                  *
869                  * I915_GEM_DOMAIN_RENDER is always invalidated, but is
870                  * only flushed if MI_NO_WRITE_FLUSH is unset.  On 965, it is
871                  * also flushed at 2d versus 3d pipeline switches.
872                  *
873                  * read-only caches:
874                  *
875                  * I915_GEM_DOMAIN_SAMPLER is flushed on pre-965 if
876                  * MI_READ_FLUSH is set, and is always flushed on 965.
877                  *
878                  * I915_GEM_DOMAIN_COMMAND may not exist?
879                  *
880                  * I915_GEM_DOMAIN_INSTRUCTION, which exists on 965, is
881                  * invalidated when MI_EXE_FLUSH is set.
882                  *
883                  * I915_GEM_DOMAIN_VERTEX, which exists on 965, is
884                  * invalidated with every MI_FLUSH.
885                  *
886                  * TLBs:
887                  *
888                  * On 965, TLBs associated with I915_GEM_DOMAIN_COMMAND
889                  * and I915_GEM_DOMAIN_CPU in are invalidated at PTE write and
890                  * I915_GEM_DOMAIN_RENDER and I915_GEM_DOMAIN_SAMPLER
891                  * are flushed at any MI_FLUSH.
892                  */
893
894                 cmd = MI_FLUSH | MI_NO_WRITE_FLUSH;
895                 if ((invalidate_domains|flush_domains) &
896                     I915_GEM_DOMAIN_RENDER)
897                         cmd &= ~MI_NO_WRITE_FLUSH;
898                 if (!IS_I965G(dev)) {
899                         /*
900                          * On the 965, the sampler cache always gets flushed
901                          * and this bit is reserved.
902                          */
903                         if (invalidate_domains & I915_GEM_DOMAIN_SAMPLER)
904                                 cmd |= MI_READ_FLUSH;
905                 }
906                 if (invalidate_domains & I915_GEM_DOMAIN_INSTRUCTION)
907                         cmd |= MI_EXE_FLUSH;
908
909 #if WATCH_EXEC
910                 DRM_INFO("%s: queue flush %08x to ring\n", __func__, cmd);
911 #endif
912                 BEGIN_LP_RING(2);
913                 OUT_RING(cmd);
914                 OUT_RING(0); /* noop */
915                 ADVANCE_LP_RING();
916         }
917 }
918
919 /**
920  * Ensures that all rendering to the object has completed and the object is
921  * safe to unbind from the GTT or access from the CPU.
922  */
923 static int
924 i915_gem_object_wait_rendering(struct drm_gem_object *obj)
925 {
926         struct drm_device *dev = obj->dev;
927         struct drm_i915_gem_object *obj_priv = obj->driver_private;
928         int ret;
929
930         /* This function only exists to support waiting for existing rendering,
931          * not for emitting required flushes.
932          */
933         BUG_ON((obj->write_domain & I915_GEM_GPU_DOMAINS) != 0);
934
935         /* If there is rendering queued on the buffer being evicted, wait for
936          * it.
937          */
938         if (obj_priv->active) {
939 #if WATCH_BUF
940                 DRM_INFO("%s: object %p wait for seqno %08x\n",
941                           __func__, obj, obj_priv->last_rendering_seqno);
942 #endif
943                 ret = i915_wait_request(dev, obj_priv->last_rendering_seqno);
944                 if (ret != 0)
945                         return ret;
946         }
947
948         return 0;
949 }
950
951 /**
952  * Unbinds an object from the GTT aperture.
953  */
954 static int
955 i915_gem_object_unbind(struct drm_gem_object *obj)
956 {
957         struct drm_device *dev = obj->dev;
958         struct drm_i915_gem_object *obj_priv = obj->driver_private;
959         int ret = 0;
960
961 #if WATCH_BUF
962         DRM_INFO("%s:%d %p\n", __func__, __LINE__, obj);
963         DRM_INFO("gtt_space %p\n", obj_priv->gtt_space);
964 #endif
965         if (obj_priv->gtt_space == NULL)
966                 return 0;
967
968         if (obj_priv->pin_count != 0) {
969                 DRM_ERROR("Attempting to unbind pinned buffer\n");
970                 return -EINVAL;
971         }
972
973         /* Move the object to the CPU domain to ensure that
974          * any possible CPU writes while it's not in the GTT
975          * are flushed when we go to remap it. This will
976          * also ensure that all pending GPU writes are finished
977          * before we unbind.
978          */
979         ret = i915_gem_object_set_to_cpu_domain(obj, 1);
980         if (ret) {
981                 if (ret != -ERESTARTSYS)
982                         DRM_ERROR("set_domain failed: %d\n", ret);
983                 return ret;
984         }
985
986         if (obj_priv->agp_mem != NULL) {
987                 drm_unbind_agp(obj_priv->agp_mem);
988                 drm_free_agp(obj_priv->agp_mem, obj->size / PAGE_SIZE);
989                 obj_priv->agp_mem = NULL;
990         }
991
992         BUG_ON(obj_priv->active);
993
994         i915_gem_object_free_page_list(obj);
995
996         if (obj_priv->gtt_space) {
997                 atomic_dec(&dev->gtt_count);
998                 atomic_sub(obj->size, &dev->gtt_memory);
999
1000                 drm_mm_put_block(obj_priv->gtt_space);
1001                 obj_priv->gtt_space = NULL;
1002         }
1003
1004         /* Remove ourselves from the LRU list if present. */
1005         if (!list_empty(&obj_priv->list))
1006                 list_del_init(&obj_priv->list);
1007
1008         return 0;
1009 }
1010
1011 static int
1012 i915_gem_evict_something(struct drm_device *dev)
1013 {
1014         drm_i915_private_t *dev_priv = dev->dev_private;
1015         struct drm_gem_object *obj;
1016         struct drm_i915_gem_object *obj_priv;
1017         int ret = 0;
1018
1019         for (;;) {
1020                 /* If there's an inactive buffer available now, grab it
1021                  * and be done.
1022                  */
1023                 if (!list_empty(&dev_priv->mm.inactive_list)) {
1024                         obj_priv = list_first_entry(&dev_priv->mm.inactive_list,
1025                                                     struct drm_i915_gem_object,
1026                                                     list);
1027                         obj = obj_priv->obj;
1028                         BUG_ON(obj_priv->pin_count != 0);
1029 #if WATCH_LRU
1030                         DRM_INFO("%s: evicting %p\n", __func__, obj);
1031 #endif
1032                         BUG_ON(obj_priv->active);
1033
1034                         /* Wait on the rendering and unbind the buffer. */
1035                         ret = i915_gem_object_unbind(obj);
1036                         break;
1037                 }
1038
1039                 /* If we didn't get anything, but the ring is still processing
1040                  * things, wait for one of those things to finish and hopefully
1041                  * leave us a buffer to evict.
1042                  */
1043                 if (!list_empty(&dev_priv->mm.request_list)) {
1044                         struct drm_i915_gem_request *request;
1045
1046                         request = list_first_entry(&dev_priv->mm.request_list,
1047                                                    struct drm_i915_gem_request,
1048                                                    list);
1049
1050                         ret = i915_wait_request(dev, request->seqno);
1051                         if (ret)
1052                                 break;
1053
1054                         /* if waiting caused an object to become inactive,
1055                          * then loop around and wait for it. Otherwise, we
1056                          * assume that waiting freed and unbound something,
1057                          * so there should now be some space in the GTT
1058                          */
1059                         if (!list_empty(&dev_priv->mm.inactive_list))
1060                                 continue;
1061                         break;
1062                 }
1063
1064                 /* If we didn't have anything on the request list but there
1065                  * are buffers awaiting a flush, emit one and try again.
1066                  * When we wait on it, those buffers waiting for that flush
1067                  * will get moved to inactive.
1068                  */
1069                 if (!list_empty(&dev_priv->mm.flushing_list)) {
1070                         obj_priv = list_first_entry(&dev_priv->mm.flushing_list,
1071                                                     struct drm_i915_gem_object,
1072                                                     list);
1073                         obj = obj_priv->obj;
1074
1075                         i915_gem_flush(dev,
1076                                        obj->write_domain,
1077                                        obj->write_domain);
1078                         i915_add_request(dev, obj->write_domain);
1079
1080                         obj = NULL;
1081                         continue;
1082                 }
1083
1084                 DRM_ERROR("inactive empty %d request empty %d "
1085                           "flushing empty %d\n",
1086                           list_empty(&dev_priv->mm.inactive_list),
1087                           list_empty(&dev_priv->mm.request_list),
1088                           list_empty(&dev_priv->mm.flushing_list));
1089                 /* If we didn't do any of the above, there's nothing to be done
1090                  * and we just can't fit it in.
1091                  */
1092                 return -ENOMEM;
1093         }
1094         return ret;
1095 }
1096
1097 static int
1098 i915_gem_evict_everything(struct drm_device *dev)
1099 {
1100         int ret;
1101
1102         for (;;) {
1103                 ret = i915_gem_evict_something(dev);
1104                 if (ret != 0)
1105                         break;
1106         }
1107         return ret;
1108 }
1109
1110 static int
1111 i915_gem_object_get_page_list(struct drm_gem_object *obj)
1112 {
1113         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1114         int page_count, i;
1115         struct address_space *mapping;
1116         struct inode *inode;
1117         struct page *page;
1118         int ret;
1119
1120         if (obj_priv->page_list)
1121                 return 0;
1122
1123         /* Get the list of pages out of our struct file.  They'll be pinned
1124          * at this point until we release them.
1125          */
1126         page_count = obj->size / PAGE_SIZE;
1127         BUG_ON(obj_priv->page_list != NULL);
1128         obj_priv->page_list = drm_calloc(page_count, sizeof(struct page *),
1129                                          DRM_MEM_DRIVER);
1130         if (obj_priv->page_list == NULL) {
1131                 DRM_ERROR("Faled to allocate page list\n");
1132                 return -ENOMEM;
1133         }
1134
1135         inode = obj->filp->f_path.dentry->d_inode;
1136         mapping = inode->i_mapping;
1137         for (i = 0; i < page_count; i++) {
1138                 page = read_mapping_page(mapping, i, NULL);
1139                 if (IS_ERR(page)) {
1140                         ret = PTR_ERR(page);
1141                         DRM_ERROR("read_mapping_page failed: %d\n", ret);
1142                         i915_gem_object_free_page_list(obj);
1143                         return ret;
1144                 }
1145                 obj_priv->page_list[i] = page;
1146         }
1147         return 0;
1148 }
1149
1150 /**
1151  * Finds free space in the GTT aperture and binds the object there.
1152  */
1153 static int
1154 i915_gem_object_bind_to_gtt(struct drm_gem_object *obj, unsigned alignment)
1155 {
1156         struct drm_device *dev = obj->dev;
1157         drm_i915_private_t *dev_priv = dev->dev_private;
1158         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1159         struct drm_mm_node *free_space;
1160         int page_count, ret;
1161
1162         if (alignment == 0)
1163                 alignment = PAGE_SIZE;
1164         if (alignment & (PAGE_SIZE - 1)) {
1165                 DRM_ERROR("Invalid object alignment requested %u\n", alignment);
1166                 return -EINVAL;
1167         }
1168
1169  search_free:
1170         free_space = drm_mm_search_free(&dev_priv->mm.gtt_space,
1171                                         obj->size, alignment, 0);
1172         if (free_space != NULL) {
1173                 obj_priv->gtt_space = drm_mm_get_block(free_space, obj->size,
1174                                                        alignment);
1175                 if (obj_priv->gtt_space != NULL) {
1176                         obj_priv->gtt_space->private = obj;
1177                         obj_priv->gtt_offset = obj_priv->gtt_space->start;
1178                 }
1179         }
1180         if (obj_priv->gtt_space == NULL) {
1181                 /* If the gtt is empty and we're still having trouble
1182                  * fitting our object in, we're out of memory.
1183                  */
1184 #if WATCH_LRU
1185                 DRM_INFO("%s: GTT full, evicting something\n", __func__);
1186 #endif
1187                 if (list_empty(&dev_priv->mm.inactive_list) &&
1188                     list_empty(&dev_priv->mm.flushing_list) &&
1189                     list_empty(&dev_priv->mm.active_list)) {
1190                         DRM_ERROR("GTT full, but LRU list empty\n");
1191                         return -ENOMEM;
1192                 }
1193
1194                 ret = i915_gem_evict_something(dev);
1195                 if (ret != 0) {
1196                         if (ret != -ERESTARTSYS)
1197                                 DRM_ERROR("Failed to evict a buffer %d\n", ret);
1198                         return ret;
1199                 }
1200                 goto search_free;
1201         }
1202
1203 #if WATCH_BUF
1204         DRM_INFO("Binding object of size %d at 0x%08x\n",
1205                  obj->size, obj_priv->gtt_offset);
1206 #endif
1207         ret = i915_gem_object_get_page_list(obj);
1208         if (ret) {
1209                 drm_mm_put_block(obj_priv->gtt_space);
1210                 obj_priv->gtt_space = NULL;
1211                 return ret;
1212         }
1213
1214         page_count = obj->size / PAGE_SIZE;
1215         /* Create an AGP memory structure pointing at our pages, and bind it
1216          * into the GTT.
1217          */
1218         obj_priv->agp_mem = drm_agp_bind_pages(dev,
1219                                                obj_priv->page_list,
1220                                                page_count,
1221                                                obj_priv->gtt_offset,
1222                                                obj_priv->agp_type);
1223         if (obj_priv->agp_mem == NULL) {
1224                 i915_gem_object_free_page_list(obj);
1225                 drm_mm_put_block(obj_priv->gtt_space);
1226                 obj_priv->gtt_space = NULL;
1227                 return -ENOMEM;
1228         }
1229         atomic_inc(&dev->gtt_count);
1230         atomic_add(obj->size, &dev->gtt_memory);
1231
1232         /* Assert that the object is not currently in any GPU domain. As it
1233          * wasn't in the GTT, there shouldn't be any way it could have been in
1234          * a GPU cache
1235          */
1236         BUG_ON(obj->read_domains & ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
1237         BUG_ON(obj->write_domain & ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
1238
1239         return 0;
1240 }
1241
1242 void
1243 i915_gem_clflush_object(struct drm_gem_object *obj)
1244 {
1245         struct drm_i915_gem_object      *obj_priv = obj->driver_private;
1246
1247         /* If we don't have a page list set up, then we're not pinned
1248          * to GPU, and we can ignore the cache flush because it'll happen
1249          * again at bind time.
1250          */
1251         if (obj_priv->page_list == NULL)
1252                 return;
1253
1254         drm_clflush_pages(obj_priv->page_list, obj->size / PAGE_SIZE);
1255 }
1256
1257 /** Flushes any GPU write domain for the object if it's dirty. */
1258 static void
1259 i915_gem_object_flush_gpu_write_domain(struct drm_gem_object *obj)
1260 {
1261         struct drm_device *dev = obj->dev;
1262         uint32_t seqno;
1263
1264         if ((obj->write_domain & I915_GEM_GPU_DOMAINS) == 0)
1265                 return;
1266
1267         /* Queue the GPU write cache flushing we need. */
1268         i915_gem_flush(dev, 0, obj->write_domain);
1269         seqno = i915_add_request(dev, obj->write_domain);
1270         obj->write_domain = 0;
1271         i915_gem_object_move_to_active(obj, seqno);
1272 }
1273
1274 /** Flushes the GTT write domain for the object if it's dirty. */
1275 static void
1276 i915_gem_object_flush_gtt_write_domain(struct drm_gem_object *obj)
1277 {
1278         if (obj->write_domain != I915_GEM_DOMAIN_GTT)
1279                 return;
1280
1281         /* No actual flushing is required for the GTT write domain.   Writes
1282          * to it immediately go to main memory as far as we know, so there's
1283          * no chipset flush.  It also doesn't land in render cache.
1284          */
1285         obj->write_domain = 0;
1286 }
1287
1288 /** Flushes the CPU write domain for the object if it's dirty. */
1289 static void
1290 i915_gem_object_flush_cpu_write_domain(struct drm_gem_object *obj)
1291 {
1292         struct drm_device *dev = obj->dev;
1293
1294         if (obj->write_domain != I915_GEM_DOMAIN_CPU)
1295                 return;
1296
1297         i915_gem_clflush_object(obj);
1298         drm_agp_chipset_flush(dev);
1299         obj->write_domain = 0;
1300 }
1301
1302 /**
1303  * Moves a single object to the GTT read, and possibly write domain.
1304  *
1305  * This function returns when the move is complete, including waiting on
1306  * flushes to occur.
1307  */
1308 static int
1309 i915_gem_object_set_to_gtt_domain(struct drm_gem_object *obj, int write)
1310 {
1311         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1312         int ret;
1313
1314         /* Not valid to be called on unbound objects. */
1315         if (obj_priv->gtt_space == NULL)
1316                 return -EINVAL;
1317
1318         i915_gem_object_flush_gpu_write_domain(obj);
1319         /* Wait on any GPU rendering and flushing to occur. */
1320         ret = i915_gem_object_wait_rendering(obj);
1321         if (ret != 0)
1322                 return ret;
1323
1324         /* If we're writing through the GTT domain, then CPU and GPU caches
1325          * will need to be invalidated at next use.
1326          */
1327         if (write)
1328                 obj->read_domains &= I915_GEM_DOMAIN_GTT;
1329
1330         i915_gem_object_flush_cpu_write_domain(obj);
1331
1332         /* It should now be out of any other write domains, and we can update
1333          * the domain values for our changes.
1334          */
1335         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
1336         obj->read_domains |= I915_GEM_DOMAIN_GTT;
1337         if (write) {
1338                 obj->write_domain = I915_GEM_DOMAIN_GTT;
1339                 obj_priv->dirty = 1;
1340         }
1341
1342         return 0;
1343 }
1344
1345 /**
1346  * Moves a single object to the CPU read, and possibly write domain.
1347  *
1348  * This function returns when the move is complete, including waiting on
1349  * flushes to occur.
1350  */
1351 static int
1352 i915_gem_object_set_to_cpu_domain(struct drm_gem_object *obj, int write)
1353 {
1354         struct drm_device *dev = obj->dev;
1355         int ret;
1356
1357         i915_gem_object_flush_gpu_write_domain(obj);
1358         /* Wait on any GPU rendering and flushing to occur. */
1359         ret = i915_gem_object_wait_rendering(obj);
1360         if (ret != 0)
1361                 return ret;
1362
1363         i915_gem_object_flush_gtt_write_domain(obj);
1364
1365         /* If we have a partially-valid cache of the object in the CPU,
1366          * finish invalidating it and free the per-page flags.
1367          */
1368         i915_gem_object_set_to_full_cpu_read_domain(obj);
1369
1370         /* Flush the CPU cache if it's still invalid. */
1371         if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0) {
1372                 i915_gem_clflush_object(obj);
1373                 drm_agp_chipset_flush(dev);
1374
1375                 obj->read_domains |= I915_GEM_DOMAIN_CPU;
1376         }
1377
1378         /* It should now be out of any other write domains, and we can update
1379          * the domain values for our changes.
1380          */
1381         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
1382
1383         /* If we're writing through the CPU, then the GPU read domains will
1384          * need to be invalidated at next use.
1385          */
1386         if (write) {
1387                 obj->read_domains &= I915_GEM_DOMAIN_CPU;
1388                 obj->write_domain = I915_GEM_DOMAIN_CPU;
1389         }
1390
1391         return 0;
1392 }
1393
1394 /*
1395  * Set the next domain for the specified object. This
1396  * may not actually perform the necessary flushing/invaliding though,
1397  * as that may want to be batched with other set_domain operations
1398  *
1399  * This is (we hope) the only really tricky part of gem. The goal
1400  * is fairly simple -- track which caches hold bits of the object
1401  * and make sure they remain coherent. A few concrete examples may
1402  * help to explain how it works. For shorthand, we use the notation
1403  * (read_domains, write_domain), e.g. (CPU, CPU) to indicate the
1404  * a pair of read and write domain masks.
1405  *
1406  * Case 1: the batch buffer
1407  *
1408  *      1. Allocated
1409  *      2. Written by CPU
1410  *      3. Mapped to GTT
1411  *      4. Read by GPU
1412  *      5. Unmapped from GTT
1413  *      6. Freed
1414  *
1415  *      Let's take these a step at a time
1416  *
1417  *      1. Allocated
1418  *              Pages allocated from the kernel may still have
1419  *              cache contents, so we set them to (CPU, CPU) always.
1420  *      2. Written by CPU (using pwrite)
1421  *              The pwrite function calls set_domain (CPU, CPU) and
1422  *              this function does nothing (as nothing changes)
1423  *      3. Mapped by GTT
1424  *              This function asserts that the object is not
1425  *              currently in any GPU-based read or write domains
1426  *      4. Read by GPU
1427  *              i915_gem_execbuffer calls set_domain (COMMAND, 0).
1428  *              As write_domain is zero, this function adds in the
1429  *              current read domains (CPU+COMMAND, 0).
1430  *              flush_domains is set to CPU.
1431  *              invalidate_domains is set to COMMAND
1432  *              clflush is run to get data out of the CPU caches
1433  *              then i915_dev_set_domain calls i915_gem_flush to
1434  *              emit an MI_FLUSH and drm_agp_chipset_flush
1435  *      5. Unmapped from GTT
1436  *              i915_gem_object_unbind calls set_domain (CPU, CPU)
1437  *              flush_domains and invalidate_domains end up both zero
1438  *              so no flushing/invalidating happens
1439  *      6. Freed
1440  *              yay, done
1441  *
1442  * Case 2: The shared render buffer
1443  *
1444  *      1. Allocated
1445  *      2. Mapped to GTT
1446  *      3. Read/written by GPU
1447  *      4. set_domain to (CPU,CPU)
1448  *      5. Read/written by CPU
1449  *      6. Read/written by GPU
1450  *
1451  *      1. Allocated
1452  *              Same as last example, (CPU, CPU)
1453  *      2. Mapped to GTT
1454  *              Nothing changes (assertions find that it is not in the GPU)
1455  *      3. Read/written by GPU
1456  *              execbuffer calls set_domain (RENDER, RENDER)
1457  *              flush_domains gets CPU
1458  *              invalidate_domains gets GPU
1459  *              clflush (obj)
1460  *              MI_FLUSH and drm_agp_chipset_flush
1461  *      4. set_domain (CPU, CPU)
1462  *              flush_domains gets GPU
1463  *              invalidate_domains gets CPU
1464  *              wait_rendering (obj) to make sure all drawing is complete.
1465  *              This will include an MI_FLUSH to get the data from GPU
1466  *              to memory
1467  *              clflush (obj) to invalidate the CPU cache
1468  *              Another MI_FLUSH in i915_gem_flush (eliminate this somehow?)
1469  *      5. Read/written by CPU
1470  *              cache lines are loaded and dirtied
1471  *      6. Read written by GPU
1472  *              Same as last GPU access
1473  *
1474  * Case 3: The constant buffer
1475  *
1476  *      1. Allocated
1477  *      2. Written by CPU
1478  *      3. Read by GPU
1479  *      4. Updated (written) by CPU again
1480  *      5. Read by GPU
1481  *
1482  *      1. Allocated
1483  *              (CPU, CPU)
1484  *      2. Written by CPU
1485  *              (CPU, CPU)
1486  *      3. Read by GPU
1487  *              (CPU+RENDER, 0)
1488  *              flush_domains = CPU
1489  *              invalidate_domains = RENDER
1490  *              clflush (obj)
1491  *              MI_FLUSH
1492  *              drm_agp_chipset_flush
1493  *      4. Updated (written) by CPU again
1494  *              (CPU, CPU)
1495  *              flush_domains = 0 (no previous write domain)
1496  *              invalidate_domains = 0 (no new read domains)
1497  *      5. Read by GPU
1498  *              (CPU+RENDER, 0)
1499  *              flush_domains = CPU
1500  *              invalidate_domains = RENDER
1501  *              clflush (obj)
1502  *              MI_FLUSH
1503  *              drm_agp_chipset_flush
1504  */
1505 static void
1506 i915_gem_object_set_to_gpu_domain(struct drm_gem_object *obj,
1507                                   uint32_t read_domains,
1508                                   uint32_t write_domain)
1509 {
1510         struct drm_device               *dev = obj->dev;
1511         struct drm_i915_gem_object      *obj_priv = obj->driver_private;
1512         uint32_t                        invalidate_domains = 0;
1513         uint32_t                        flush_domains = 0;
1514
1515         BUG_ON(read_domains & I915_GEM_DOMAIN_CPU);
1516         BUG_ON(write_domain == I915_GEM_DOMAIN_CPU);
1517
1518 #if WATCH_BUF
1519         DRM_INFO("%s: object %p read %08x -> %08x write %08x -> %08x\n",
1520                  __func__, obj,
1521                  obj->read_domains, read_domains,
1522                  obj->write_domain, write_domain);
1523 #endif
1524         /*
1525          * If the object isn't moving to a new write domain,
1526          * let the object stay in multiple read domains
1527          */
1528         if (write_domain == 0)
1529                 read_domains |= obj->read_domains;
1530         else
1531                 obj_priv->dirty = 1;
1532
1533         /*
1534          * Flush the current write domain if
1535          * the new read domains don't match. Invalidate
1536          * any read domains which differ from the old
1537          * write domain
1538          */
1539         if (obj->write_domain && obj->write_domain != read_domains) {
1540                 flush_domains |= obj->write_domain;
1541                 invalidate_domains |= read_domains & ~obj->write_domain;
1542         }
1543         /*
1544          * Invalidate any read caches which may have
1545          * stale data. That is, any new read domains.
1546          */
1547         invalidate_domains |= read_domains & ~obj->read_domains;
1548         if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_CPU) {
1549 #if WATCH_BUF
1550                 DRM_INFO("%s: CPU domain flush %08x invalidate %08x\n",
1551                          __func__, flush_domains, invalidate_domains);
1552 #endif
1553                 i915_gem_clflush_object(obj);
1554         }
1555
1556         if ((write_domain | flush_domains) != 0)
1557                 obj->write_domain = write_domain;
1558         obj->read_domains = read_domains;
1559
1560         dev->invalidate_domains |= invalidate_domains;
1561         dev->flush_domains |= flush_domains;
1562 #if WATCH_BUF
1563         DRM_INFO("%s: read %08x write %08x invalidate %08x flush %08x\n",
1564                  __func__,
1565                  obj->read_domains, obj->write_domain,
1566                  dev->invalidate_domains, dev->flush_domains);
1567 #endif
1568 }
1569
1570 /**
1571  * Moves the object from a partially CPU read to a full one.
1572  *
1573  * Note that this only resolves i915_gem_object_set_cpu_read_domain_range(),
1574  * and doesn't handle transitioning from !(read_domains & I915_GEM_DOMAIN_CPU).
1575  */
1576 static void
1577 i915_gem_object_set_to_full_cpu_read_domain(struct drm_gem_object *obj)
1578 {
1579         struct drm_device *dev = obj->dev;
1580         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1581
1582         if (!obj_priv->page_cpu_valid)
1583                 return;
1584
1585         /* If we're partially in the CPU read domain, finish moving it in.
1586          */
1587         if (obj->read_domains & I915_GEM_DOMAIN_CPU) {
1588                 int i;
1589
1590                 for (i = 0; i <= (obj->size - 1) / PAGE_SIZE; i++) {
1591                         if (obj_priv->page_cpu_valid[i])
1592                                 continue;
1593                         drm_clflush_pages(obj_priv->page_list + i, 1);
1594                 }
1595                 drm_agp_chipset_flush(dev);
1596         }
1597
1598         /* Free the page_cpu_valid mappings which are now stale, whether
1599          * or not we've got I915_GEM_DOMAIN_CPU.
1600          */
1601         drm_free(obj_priv->page_cpu_valid, obj->size / PAGE_SIZE,
1602                  DRM_MEM_DRIVER);
1603         obj_priv->page_cpu_valid = NULL;
1604 }
1605
1606 /**
1607  * Set the CPU read domain on a range of the object.
1608  *
1609  * The object ends up with I915_GEM_DOMAIN_CPU in its read flags although it's
1610  * not entirely valid.  The page_cpu_valid member of the object flags which
1611  * pages have been flushed, and will be respected by
1612  * i915_gem_object_set_to_cpu_domain() if it's called on to get a valid mapping
1613  * of the whole object.
1614  *
1615  * This function returns when the move is complete, including waiting on
1616  * flushes to occur.
1617  */
1618 static int
1619 i915_gem_object_set_cpu_read_domain_range(struct drm_gem_object *obj,
1620                                           uint64_t offset, uint64_t size)
1621 {
1622         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1623         int i, ret;
1624
1625         if (offset == 0 && size == obj->size)
1626                 return i915_gem_object_set_to_cpu_domain(obj, 0);
1627
1628         i915_gem_object_flush_gpu_write_domain(obj);
1629         /* Wait on any GPU rendering and flushing to occur. */
1630         ret = i915_gem_object_wait_rendering(obj);
1631         if (ret != 0)
1632                 return ret;
1633         i915_gem_object_flush_gtt_write_domain(obj);
1634
1635         /* If we're already fully in the CPU read domain, we're done. */
1636         if (obj_priv->page_cpu_valid == NULL &&
1637             (obj->read_domains & I915_GEM_DOMAIN_CPU) != 0)
1638                 return 0;
1639
1640         /* Otherwise, create/clear the per-page CPU read domain flag if we're
1641          * newly adding I915_GEM_DOMAIN_CPU
1642          */
1643         if (obj_priv->page_cpu_valid == NULL) {
1644                 obj_priv->page_cpu_valid = drm_calloc(1, obj->size / PAGE_SIZE,
1645                                                       DRM_MEM_DRIVER);
1646                 if (obj_priv->page_cpu_valid == NULL)
1647                         return -ENOMEM;
1648         } else if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0)
1649                 memset(obj_priv->page_cpu_valid, 0, obj->size / PAGE_SIZE);
1650
1651         /* Flush the cache on any pages that are still invalid from the CPU's
1652          * perspective.
1653          */
1654         for (i = offset / PAGE_SIZE; i <= (offset + size - 1) / PAGE_SIZE;
1655              i++) {
1656                 if (obj_priv->page_cpu_valid[i])
1657                         continue;
1658
1659                 drm_clflush_pages(obj_priv->page_list + i, 1);
1660
1661                 obj_priv->page_cpu_valid[i] = 1;
1662         }
1663
1664         /* It should now be out of any other write domains, and we can update
1665          * the domain values for our changes.
1666          */
1667         BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_CPU) != 0);
1668
1669         obj->read_domains |= I915_GEM_DOMAIN_CPU;
1670
1671         return 0;
1672 }
1673
1674 /**
1675  * Pin an object to the GTT and evaluate the relocations landing in it.
1676  */
1677 static int
1678 i915_gem_object_pin_and_relocate(struct drm_gem_object *obj,
1679                                  struct drm_file *file_priv,
1680                                  struct drm_i915_gem_exec_object *entry)
1681 {
1682         struct drm_device *dev = obj->dev;
1683         drm_i915_private_t *dev_priv = dev->dev_private;
1684         struct drm_i915_gem_relocation_entry reloc;
1685         struct drm_i915_gem_relocation_entry __user *relocs;
1686         struct drm_i915_gem_object *obj_priv = obj->driver_private;
1687         int i, ret;
1688         void __iomem *reloc_page;
1689
1690         /* Choose the GTT offset for our buffer and put it there. */
1691         ret = i915_gem_object_pin(obj, (uint32_t) entry->alignment);
1692         if (ret)
1693                 return ret;
1694
1695         entry->offset = obj_priv->gtt_offset;
1696
1697         relocs = (struct drm_i915_gem_relocation_entry __user *)
1698                  (uintptr_t) entry->relocs_ptr;
1699         /* Apply the relocations, using the GTT aperture to avoid cache
1700          * flushing requirements.
1701          */
1702         for (i = 0; i < entry->relocation_count; i++) {
1703                 struct drm_gem_object *target_obj;
1704                 struct drm_i915_gem_object *target_obj_priv;
1705                 uint32_t reloc_val, reloc_offset;
1706                 uint32_t __iomem *reloc_entry;
1707
1708                 ret = copy_from_user(&reloc, relocs + i, sizeof(reloc));
1709                 if (ret != 0) {
1710                         i915_gem_object_unpin(obj);
1711                         return ret;
1712                 }
1713
1714                 target_obj = drm_gem_object_lookup(obj->dev, file_priv,
1715                                                    reloc.target_handle);
1716                 if (target_obj == NULL) {
1717                         i915_gem_object_unpin(obj);
1718                         return -EBADF;
1719                 }
1720                 target_obj_priv = target_obj->driver_private;
1721
1722                 /* The target buffer should have appeared before us in the
1723                  * exec_object list, so it should have a GTT space bound by now.
1724                  */
1725                 if (target_obj_priv->gtt_space == NULL) {
1726                         DRM_ERROR("No GTT space found for object %d\n",
1727                                   reloc.target_handle);
1728                         drm_gem_object_unreference(target_obj);
1729                         i915_gem_object_unpin(obj);
1730                         return -EINVAL;
1731                 }
1732
1733                 if (reloc.offset > obj->size - 4) {
1734                         DRM_ERROR("Relocation beyond object bounds: "
1735                                   "obj %p target %d offset %d size %d.\n",
1736                                   obj, reloc.target_handle,
1737                                   (int) reloc.offset, (int) obj->size);
1738                         drm_gem_object_unreference(target_obj);
1739                         i915_gem_object_unpin(obj);
1740                         return -EINVAL;
1741                 }
1742                 if (reloc.offset & 3) {
1743                         DRM_ERROR("Relocation not 4-byte aligned: "
1744                                   "obj %p target %d offset %d.\n",
1745                                   obj, reloc.target_handle,
1746                                   (int) reloc.offset);
1747                         drm_gem_object_unreference(target_obj);
1748                         i915_gem_object_unpin(obj);
1749                         return -EINVAL;
1750                 }
1751
1752                 if (reloc.write_domain & I915_GEM_DOMAIN_CPU ||
1753                     reloc.read_domains & I915_GEM_DOMAIN_CPU) {
1754                         DRM_ERROR("reloc with read/write CPU domains: "
1755                                   "obj %p target %d offset %d "
1756                                   "read %08x write %08x",
1757                                   obj, reloc.target_handle,
1758                                   (int) reloc.offset,
1759                                   reloc.read_domains,
1760                                   reloc.write_domain);
1761                         return -EINVAL;
1762                 }
1763
1764                 if (reloc.write_domain && target_obj->pending_write_domain &&
1765                     reloc.write_domain != target_obj->pending_write_domain) {
1766                         DRM_ERROR("Write domain conflict: "
1767                                   "obj %p target %d offset %d "
1768                                   "new %08x old %08x\n",
1769                                   obj, reloc.target_handle,
1770                                   (int) reloc.offset,
1771                                   reloc.write_domain,
1772                                   target_obj->pending_write_domain);
1773                         drm_gem_object_unreference(target_obj);
1774                         i915_gem_object_unpin(obj);
1775                         return -EINVAL;
1776                 }
1777
1778 #if WATCH_RELOC
1779                 DRM_INFO("%s: obj %p offset %08x target %d "
1780                          "read %08x write %08x gtt %08x "
1781                          "presumed %08x delta %08x\n",
1782                          __func__,
1783                          obj,
1784                          (int) reloc.offset,
1785                          (int) reloc.target_handle,
1786                          (int) reloc.read_domains,
1787                          (int) reloc.write_domain,
1788                          (int) target_obj_priv->gtt_offset,
1789                          (int) reloc.presumed_offset,
1790                          reloc.delta);
1791 #endif
1792
1793                 target_obj->pending_read_domains |= reloc.read_domains;
1794                 target_obj->pending_write_domain |= reloc.write_domain;
1795
1796                 /* If the relocation already has the right value in it, no
1797                  * more work needs to be done.
1798                  */
1799                 if (target_obj_priv->gtt_offset == reloc.presumed_offset) {
1800                         drm_gem_object_unreference(target_obj);
1801                         continue;
1802                 }
1803
1804                 ret = i915_gem_object_set_to_gtt_domain(obj, 1);
1805                 if (ret != 0) {
1806                         drm_gem_object_unreference(target_obj);
1807                         i915_gem_object_unpin(obj);
1808                         return -EINVAL;
1809                 }
1810
1811                 /* Map the page containing the relocation we're going to
1812                  * perform.
1813                  */
1814                 reloc_offset = obj_priv->gtt_offset + reloc.offset;
1815                 reloc_page = io_mapping_map_atomic_wc(dev_priv->mm.gtt_mapping,
1816                                                       (reloc_offset &
1817                                                        ~(PAGE_SIZE - 1)));
1818                 reloc_entry = (uint32_t __iomem *)(reloc_page +
1819                                                    (reloc_offset & (PAGE_SIZE - 1)));
1820                 reloc_val = target_obj_priv->gtt_offset + reloc.delta;
1821
1822 #if WATCH_BUF
1823                 DRM_INFO("Applied relocation: %p@0x%08x %08x -> %08x\n",
1824                           obj, (unsigned int) reloc.offset,
1825                           readl(reloc_entry), reloc_val);
1826 #endif
1827                 writel(reloc_val, reloc_entry);
1828                 io_mapping_unmap_atomic(reloc_page);
1829
1830                 /* Write the updated presumed offset for this entry back out
1831                  * to the user.
1832                  */
1833                 reloc.presumed_offset = target_obj_priv->gtt_offset;
1834                 ret = copy_to_user(relocs + i, &reloc, sizeof(reloc));
1835                 if (ret != 0) {
1836                         drm_gem_object_unreference(target_obj);
1837                         i915_gem_object_unpin(obj);
1838                         return ret;
1839                 }
1840
1841                 drm_gem_object_unreference(target_obj);
1842         }
1843
1844 #if WATCH_BUF
1845         if (0)
1846                 i915_gem_dump_object(obj, 128, __func__, ~0);
1847 #endif
1848         return 0;
1849 }
1850
1851 /** Dispatch a batchbuffer to the ring
1852  */
1853 static int
1854 i915_dispatch_gem_execbuffer(struct drm_device *dev,
1855                               struct drm_i915_gem_execbuffer *exec,
1856                               uint64_t exec_offset)
1857 {
1858         drm_i915_private_t *dev_priv = dev->dev_private;
1859         struct drm_clip_rect __user *boxes = (struct drm_clip_rect __user *)
1860                                              (uintptr_t) exec->cliprects_ptr;
1861         int nbox = exec->num_cliprects;
1862         int i = 0, count;
1863         uint32_t        exec_start, exec_len;
1864         RING_LOCALS;
1865
1866         exec_start = (uint32_t) exec_offset + exec->batch_start_offset;
1867         exec_len = (uint32_t) exec->batch_len;
1868
1869         if ((exec_start | exec_len) & 0x7) {
1870                 DRM_ERROR("alignment\n");
1871                 return -EINVAL;
1872         }
1873
1874         if (!exec_start)
1875                 return -EINVAL;
1876
1877         count = nbox ? nbox : 1;
1878
1879         for (i = 0; i < count; i++) {
1880                 if (i < nbox) {
1881                         int ret = i915_emit_box(dev, boxes, i,
1882                                                 exec->DR1, exec->DR4);
1883                         if (ret)
1884                                 return ret;
1885                 }
1886
1887                 if (IS_I830(dev) || IS_845G(dev)) {
1888                         BEGIN_LP_RING(4);
1889                         OUT_RING(MI_BATCH_BUFFER);
1890                         OUT_RING(exec_start | MI_BATCH_NON_SECURE);
1891                         OUT_RING(exec_start + exec_len - 4);
1892                         OUT_RING(0);
1893                         ADVANCE_LP_RING();
1894                 } else {
1895                         BEGIN_LP_RING(2);
1896                         if (IS_I965G(dev)) {
1897                                 OUT_RING(MI_BATCH_BUFFER_START |
1898                                          (2 << 6) |
1899                                          MI_BATCH_NON_SECURE_I965);
1900                                 OUT_RING(exec_start);
1901                         } else {
1902                                 OUT_RING(MI_BATCH_BUFFER_START |
1903                                          (2 << 6));
1904                                 OUT_RING(exec_start | MI_BATCH_NON_SECURE);
1905                         }
1906                         ADVANCE_LP_RING();
1907                 }
1908         }
1909
1910         /* XXX breadcrumb */
1911         return 0;
1912 }
1913
1914 /* Throttle our rendering by waiting until the ring has completed our requests
1915  * emitted over 20 msec ago.
1916  *
1917  * This should get us reasonable parallelism between CPU and GPU but also
1918  * relatively low latency when blocking on a particular request to finish.
1919  */
1920 static int
1921 i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file_priv)
1922 {
1923         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
1924         int ret = 0;
1925         uint32_t seqno;
1926
1927         mutex_lock(&dev->struct_mutex);
1928         seqno = i915_file_priv->mm.last_gem_throttle_seqno;
1929         i915_file_priv->mm.last_gem_throttle_seqno =
1930                 i915_file_priv->mm.last_gem_seqno;
1931         if (seqno)
1932                 ret = i915_wait_request(dev, seqno);
1933         mutex_unlock(&dev->struct_mutex);
1934         return ret;
1935 }
1936
1937 int
1938 i915_gem_execbuffer(struct drm_device *dev, void *data,
1939                     struct drm_file *file_priv)
1940 {
1941         drm_i915_private_t *dev_priv = dev->dev_private;
1942         struct drm_i915_file_private *i915_file_priv = file_priv->driver_priv;
1943         struct drm_i915_gem_execbuffer *args = data;
1944         struct drm_i915_gem_exec_object *exec_list = NULL;
1945         struct drm_gem_object **object_list = NULL;
1946         struct drm_gem_object *batch_obj;
1947         int ret, i, pinned = 0;
1948         uint64_t exec_offset;
1949         uint32_t seqno, flush_domains;
1950         int pin_tries;
1951
1952 #if WATCH_EXEC
1953         DRM_INFO("buffers_ptr %d buffer_count %d len %08x\n",
1954                   (int) args->buffers_ptr, args->buffer_count, args->batch_len);
1955 #endif
1956
1957         if (args->buffer_count < 1) {
1958                 DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
1959                 return -EINVAL;
1960         }
1961         /* Copy in the exec list from userland */
1962         exec_list = drm_calloc(sizeof(*exec_list), args->buffer_count,
1963                                DRM_MEM_DRIVER);
1964         object_list = drm_calloc(sizeof(*object_list), args->buffer_count,
1965                                  DRM_MEM_DRIVER);
1966         if (exec_list == NULL || object_list == NULL) {
1967                 DRM_ERROR("Failed to allocate exec or object list "
1968                           "for %d buffers\n",
1969                           args->buffer_count);
1970                 ret = -ENOMEM;
1971                 goto pre_mutex_err;
1972         }
1973         ret = copy_from_user(exec_list,
1974                              (struct drm_i915_relocation_entry __user *)
1975                              (uintptr_t) args->buffers_ptr,
1976                              sizeof(*exec_list) * args->buffer_count);
1977         if (ret != 0) {
1978                 DRM_ERROR("copy %d exec entries failed %d\n",
1979                           args->buffer_count, ret);
1980                 goto pre_mutex_err;
1981         }
1982
1983         mutex_lock(&dev->struct_mutex);
1984
1985         i915_verify_inactive(dev, __FILE__, __LINE__);
1986
1987         if (dev_priv->mm.wedged) {
1988                 DRM_ERROR("Execbuf while wedged\n");
1989                 mutex_unlock(&dev->struct_mutex);
1990                 return -EIO;
1991         }
1992
1993         if (dev_priv->mm.suspended) {
1994                 DRM_ERROR("Execbuf while VT-switched.\n");
1995                 mutex_unlock(&dev->struct_mutex);
1996                 return -EBUSY;
1997         }
1998
1999         /* Look up object handles */
2000         for (i = 0; i < args->buffer_count; i++) {
2001                 object_list[i] = drm_gem_object_lookup(dev, file_priv,
2002                                                        exec_list[i].handle);
2003                 if (object_list[i] == NULL) {
2004                         DRM_ERROR("Invalid object handle %d at index %d\n",
2005                                    exec_list[i].handle, i);
2006                         ret = -EBADF;
2007                         goto err;
2008                 }
2009         }
2010
2011         /* Pin and relocate */
2012         for (pin_tries = 0; ; pin_tries++) {
2013                 ret = 0;
2014                 for (i = 0; i < args->buffer_count; i++) {
2015                         object_list[i]->pending_read_domains = 0;
2016                         object_list[i]->pending_write_domain = 0;
2017                         ret = i915_gem_object_pin_and_relocate(object_list[i],
2018                                                                file_priv,
2019                                                                &exec_list[i]);
2020                         if (ret)
2021                                 break;
2022                         pinned = i + 1;
2023                 }
2024                 /* success */
2025                 if (ret == 0)
2026                         break;
2027
2028                 /* error other than GTT full, or we've already tried again */
2029                 if (ret != -ENOMEM || pin_tries >= 1) {
2030                         DRM_ERROR("Failed to pin buffers %d\n", ret);
2031                         goto err;
2032                 }
2033
2034                 /* unpin all of our buffers */
2035                 for (i = 0; i < pinned; i++)
2036                         i915_gem_object_unpin(object_list[i]);
2037
2038                 /* evict everyone we can from the aperture */
2039                 ret = i915_gem_evict_everything(dev);
2040                 if (ret)
2041                         goto err;
2042         }
2043
2044         /* Set the pending read domains for the batch buffer to COMMAND */
2045         batch_obj = object_list[args->buffer_count-1];
2046         batch_obj->pending_read_domains = I915_GEM_DOMAIN_COMMAND;
2047         batch_obj->pending_write_domain = 0;
2048
2049         i915_verify_inactive(dev, __FILE__, __LINE__);
2050
2051         /* Zero the global flush/invalidate flags. These
2052          * will be modified as new domains are computed
2053          * for each object
2054          */
2055         dev->invalidate_domains = 0;
2056         dev->flush_domains = 0;
2057
2058         for (i = 0; i < args->buffer_count; i++) {
2059                 struct drm_gem_object *obj = object_list[i];
2060
2061                 /* Compute new gpu domains and update invalidate/flush */
2062                 i915_gem_object_set_to_gpu_domain(obj,
2063                                                   obj->pending_read_domains,
2064                                                   obj->pending_write_domain);
2065         }
2066
2067         i915_verify_inactive(dev, __FILE__, __LINE__);
2068
2069         if (dev->invalidate_domains | dev->flush_domains) {
2070 #if WATCH_EXEC
2071                 DRM_INFO("%s: invalidate_domains %08x flush_domains %08x\n",
2072                           __func__,
2073                          dev->invalidate_domains,
2074                          dev->flush_domains);
2075 #endif
2076                 i915_gem_flush(dev,
2077                                dev->invalidate_domains,
2078                                dev->flush_domains);
2079                 if (dev->flush_domains)
2080                         (void)i915_add_request(dev, dev->flush_domains);
2081         }
2082
2083         i915_verify_inactive(dev, __FILE__, __LINE__);
2084
2085 #if WATCH_COHERENCY
2086         for (i = 0; i < args->buffer_count; i++) {
2087                 i915_gem_object_check_coherency(object_list[i],
2088                                                 exec_list[i].handle);
2089         }
2090 #endif
2091
2092         exec_offset = exec_list[args->buffer_count - 1].offset;
2093
2094 #if WATCH_EXEC
2095         i915_gem_dump_object(object_list[args->buffer_count - 1],
2096                               args->batch_len,
2097                               __func__,
2098                               ~0);
2099 #endif
2100
2101         /* Exec the batchbuffer */
2102         ret = i915_dispatch_gem_execbuffer(dev, args, exec_offset);
2103         if (ret) {
2104                 DRM_ERROR("dispatch failed %d\n", ret);
2105                 goto err;
2106         }
2107
2108         /*
2109          * Ensure that the commands in the batch buffer are
2110          * finished before the interrupt fires
2111          */
2112         flush_domains = i915_retire_commands(dev);
2113
2114         i915_verify_inactive(dev, __FILE__, __LINE__);
2115
2116         /*
2117          * Get a seqno representing the execution of the current buffer,
2118          * which we can wait on.  We would like to mitigate these interrupts,
2119          * likely by only creating seqnos occasionally (so that we have
2120          * *some* interrupts representing completion of buffers that we can
2121          * wait on when trying to clear up gtt space).
2122          */
2123         seqno = i915_add_request(dev, flush_domains);
2124         BUG_ON(seqno == 0);
2125         i915_file_priv->mm.last_gem_seqno = seqno;
2126         for (i = 0; i < args->buffer_count; i++) {
2127                 struct drm_gem_object *obj = object_list[i];
2128
2129                 i915_gem_object_move_to_active(obj, seqno);
2130 #if WATCH_LRU
2131                 DRM_INFO("%s: move to exec list %p\n", __func__, obj);
2132 #endif
2133         }
2134 #if WATCH_LRU
2135         i915_dump_lru(dev, __func__);
2136 #endif
2137
2138         i915_verify_inactive(dev, __FILE__, __LINE__);
2139
2140         /* Copy the new buffer offsets back to the user's exec list. */
2141         ret = copy_to_user((struct drm_i915_relocation_entry __user *)
2142                            (uintptr_t) args->buffers_ptr,
2143                            exec_list,
2144                            sizeof(*exec_list) * args->buffer_count);
2145         if (ret)
2146                 DRM_ERROR("failed to copy %d exec entries "
2147                           "back to user (%d)\n",
2148                            args->buffer_count, ret);
2149 err:
2150         if (object_list != NULL) {
2151                 for (i = 0; i < pinned; i++)
2152                         i915_gem_object_unpin(object_list[i]);
2153
2154                 for (i = 0; i < args->buffer_count; i++)
2155                         drm_gem_object_unreference(object_list[i]);
2156         }
2157         mutex_unlock(&dev->struct_mutex);
2158
2159 pre_mutex_err:
2160         drm_free(object_list, sizeof(*object_list) * args->buffer_count,
2161                  DRM_MEM_DRIVER);
2162         drm_free(exec_list, sizeof(*exec_list) * args->buffer_count,
2163                  DRM_MEM_DRIVER);
2164
2165         return ret;
2166 }
2167
2168 int
2169 i915_gem_object_pin(struct drm_gem_object *obj, uint32_t alignment)
2170 {
2171         struct drm_device *dev = obj->dev;
2172         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2173         int ret;
2174
2175         i915_verify_inactive(dev, __FILE__, __LINE__);
2176         if (obj_priv->gtt_space == NULL) {
2177                 ret = i915_gem_object_bind_to_gtt(obj, alignment);
2178                 if (ret != 0) {
2179                         DRM_ERROR("Failure to bind: %d", ret);
2180                         return ret;
2181                 }
2182         }
2183         obj_priv->pin_count++;
2184
2185         /* If the object is not active and not pending a flush,
2186          * remove it from the inactive list
2187          */
2188         if (obj_priv->pin_count == 1) {
2189                 atomic_inc(&dev->pin_count);
2190                 atomic_add(obj->size, &dev->pin_memory);
2191                 if (!obj_priv->active &&
2192                     (obj->write_domain & ~(I915_GEM_DOMAIN_CPU |
2193                                            I915_GEM_DOMAIN_GTT)) == 0 &&
2194                     !list_empty(&obj_priv->list))
2195                         list_del_init(&obj_priv->list);
2196         }
2197         i915_verify_inactive(dev, __FILE__, __LINE__);
2198
2199         return 0;
2200 }
2201
2202 void
2203 i915_gem_object_unpin(struct drm_gem_object *obj)
2204 {
2205         struct drm_device *dev = obj->dev;
2206         drm_i915_private_t *dev_priv = dev->dev_private;
2207         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2208
2209         i915_verify_inactive(dev, __FILE__, __LINE__);
2210         obj_priv->pin_count--;
2211         BUG_ON(obj_priv->pin_count < 0);
2212         BUG_ON(obj_priv->gtt_space == NULL);
2213
2214         /* If the object is no longer pinned, and is
2215          * neither active nor being flushed, then stick it on
2216          * the inactive list
2217          */
2218         if (obj_priv->pin_count == 0) {
2219                 if (!obj_priv->active &&
2220                     (obj->write_domain & ~(I915_GEM_DOMAIN_CPU |
2221                                            I915_GEM_DOMAIN_GTT)) == 0)
2222                         list_move_tail(&obj_priv->list,
2223                                        &dev_priv->mm.inactive_list);
2224                 atomic_dec(&dev->pin_count);
2225                 atomic_sub(obj->size, &dev->pin_memory);
2226         }
2227         i915_verify_inactive(dev, __FILE__, __LINE__);
2228 }
2229
2230 int
2231 i915_gem_pin_ioctl(struct drm_device *dev, void *data,
2232                    struct drm_file *file_priv)
2233 {
2234         struct drm_i915_gem_pin *args = data;
2235         struct drm_gem_object *obj;
2236         struct drm_i915_gem_object *obj_priv;
2237         int ret;
2238
2239         mutex_lock(&dev->struct_mutex);
2240
2241         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
2242         if (obj == NULL) {
2243                 DRM_ERROR("Bad handle in i915_gem_pin_ioctl(): %d\n",
2244                           args->handle);
2245                 mutex_unlock(&dev->struct_mutex);
2246                 return -EBADF;
2247         }
2248         obj_priv = obj->driver_private;
2249
2250         ret = i915_gem_object_pin(obj, args->alignment);
2251         if (ret != 0) {
2252                 drm_gem_object_unreference(obj);
2253                 mutex_unlock(&dev->struct_mutex);
2254                 return ret;
2255         }
2256
2257         /* XXX - flush the CPU caches for pinned objects
2258          * as the X server doesn't manage domains yet
2259          */
2260         i915_gem_object_flush_cpu_write_domain(obj);
2261         args->offset = obj_priv->gtt_offset;
2262         drm_gem_object_unreference(obj);
2263         mutex_unlock(&dev->struct_mutex);
2264
2265         return 0;
2266 }
2267
2268 int
2269 i915_gem_unpin_ioctl(struct drm_device *dev, void *data,
2270                      struct drm_file *file_priv)
2271 {
2272         struct drm_i915_gem_pin *args = data;
2273         struct drm_gem_object *obj;
2274
2275         mutex_lock(&dev->struct_mutex);
2276
2277         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
2278         if (obj == NULL) {
2279                 DRM_ERROR("Bad handle in i915_gem_unpin_ioctl(): %d\n",
2280                           args->handle);
2281                 mutex_unlock(&dev->struct_mutex);
2282                 return -EBADF;
2283         }
2284
2285         i915_gem_object_unpin(obj);
2286
2287         drm_gem_object_unreference(obj);
2288         mutex_unlock(&dev->struct_mutex);
2289         return 0;
2290 }
2291
2292 int
2293 i915_gem_busy_ioctl(struct drm_device *dev, void *data,
2294                     struct drm_file *file_priv)
2295 {
2296         struct drm_i915_gem_busy *args = data;
2297         struct drm_gem_object *obj;
2298         struct drm_i915_gem_object *obj_priv;
2299
2300         mutex_lock(&dev->struct_mutex);
2301         obj = drm_gem_object_lookup(dev, file_priv, args->handle);
2302         if (obj == NULL) {
2303                 DRM_ERROR("Bad handle in i915_gem_busy_ioctl(): %d\n",
2304                           args->handle);
2305                 mutex_unlock(&dev->struct_mutex);
2306                 return -EBADF;
2307         }
2308
2309         obj_priv = obj->driver_private;
2310         args->busy = obj_priv->active;
2311
2312         drm_gem_object_unreference(obj);
2313         mutex_unlock(&dev->struct_mutex);
2314         return 0;
2315 }
2316
2317 int
2318 i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
2319                         struct drm_file *file_priv)
2320 {
2321     return i915_gem_ring_throttle(dev, file_priv);
2322 }
2323
2324 int i915_gem_init_object(struct drm_gem_object *obj)
2325 {
2326         struct drm_i915_gem_object *obj_priv;
2327
2328         obj_priv = drm_calloc(1, sizeof(*obj_priv), DRM_MEM_DRIVER);
2329         if (obj_priv == NULL)
2330                 return -ENOMEM;
2331
2332         /*
2333          * We've just allocated pages from the kernel,
2334          * so they've just been written by the CPU with
2335          * zeros. They'll need to be clflushed before we
2336          * use them with the GPU.
2337          */
2338         obj->write_domain = I915_GEM_DOMAIN_CPU;
2339         obj->read_domains = I915_GEM_DOMAIN_CPU;
2340
2341         obj_priv->agp_type = AGP_USER_MEMORY;
2342
2343         obj->driver_private = obj_priv;
2344         obj_priv->obj = obj;
2345         INIT_LIST_HEAD(&obj_priv->list);
2346         return 0;
2347 }
2348
2349 void i915_gem_free_object(struct drm_gem_object *obj)
2350 {
2351         struct drm_i915_gem_object *obj_priv = obj->driver_private;
2352
2353         while (obj_priv->pin_count > 0)
2354                 i915_gem_object_unpin(obj);
2355
2356         i915_gem_object_unbind(obj);
2357
2358         drm_free(obj_priv->page_cpu_valid, 1, DRM_MEM_DRIVER);
2359         drm_free(obj->driver_private, 1, DRM_MEM_DRIVER);
2360 }
2361
2362 /** Unbinds all objects that are on the given buffer list. */
2363 static int
2364 i915_gem_evict_from_list(struct drm_device *dev, struct list_head *head)
2365 {
2366         struct drm_gem_object *obj;
2367         struct drm_i915_gem_object *obj_priv;
2368         int ret;
2369
2370         while (!list_empty(head)) {
2371                 obj_priv = list_first_entry(head,
2372                                             struct drm_i915_gem_object,
2373                                             list);
2374                 obj = obj_priv->obj;
2375
2376                 if (obj_priv->pin_count != 0) {
2377                         DRM_ERROR("Pinned object in unbind list\n");
2378                         mutex_unlock(&dev->struct_mutex);
2379                         return -EINVAL;
2380                 }
2381
2382                 ret = i915_gem_object_unbind(obj);
2383                 if (ret != 0) {
2384                         DRM_ERROR("Error unbinding object in LeaveVT: %d\n",
2385                                   ret);
2386                         mutex_unlock(&dev->struct_mutex);
2387                         return ret;
2388                 }
2389         }
2390
2391
2392         return 0;
2393 }
2394
2395 static int
2396 i915_gem_idle(struct drm_device *dev)
2397 {
2398         drm_i915_private_t *dev_priv = dev->dev_private;
2399         uint32_t seqno, cur_seqno, last_seqno;
2400         int stuck, ret;
2401
2402         mutex_lock(&dev->struct_mutex);
2403
2404         if (dev_priv->mm.suspended || dev_priv->ring.ring_obj == NULL) {
2405                 mutex_unlock(&dev->struct_mutex);
2406                 return 0;
2407         }
2408
2409         /* Hack!  Don't let anybody do execbuf while we don't control the chip.
2410          * We need to replace this with a semaphore, or something.
2411          */
2412         dev_priv->mm.suspended = 1;
2413
2414         /* Cancel the retire work handler, wait for it to finish if running
2415          */
2416         mutex_unlock(&dev->struct_mutex);
2417         cancel_delayed_work_sync(&dev_priv->mm.retire_work);
2418         mutex_lock(&dev->struct_mutex);
2419
2420         i915_kernel_lost_context(dev);
2421
2422         /* Flush the GPU along with all non-CPU write domains
2423          */
2424         i915_gem_flush(dev, ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT),
2425                        ~(I915_GEM_DOMAIN_CPU|I915_GEM_DOMAIN_GTT));
2426         seqno = i915_add_request(dev, ~(I915_GEM_DOMAIN_CPU |
2427                                         I915_GEM_DOMAIN_GTT));
2428
2429         if (seqno == 0) {
2430                 mutex_unlock(&dev->struct_mutex);
2431                 return -ENOMEM;
2432         }
2433
2434         dev_priv->mm.waiting_gem_seqno = seqno;
2435         last_seqno = 0;
2436         stuck = 0;
2437         for (;;) {
2438                 cur_seqno = i915_get_gem_seqno(dev);
2439                 if (i915_seqno_passed(cur_seqno, seqno))
2440                         break;
2441                 if (last_seqno == cur_seqno) {
2442                         if (stuck++ > 100) {
2443                                 DRM_ERROR("hardware wedged\n");
2444                                 dev_priv->mm.wedged = 1;
2445                                 DRM_WAKEUP(&dev_priv->irq_queue);
2446                                 break;
2447                         }
2448                 }
2449                 msleep(10);
2450                 last_seqno = cur_seqno;
2451         }
2452         dev_priv->mm.waiting_gem_seqno = 0;
2453
2454         i915_gem_retire_requests(dev);
2455
2456         if (!dev_priv->mm.wedged) {
2457                 /* Active and flushing should now be empty as we've
2458                  * waited for a sequence higher than any pending execbuffer
2459                  */
2460                 WARN_ON(!list_empty(&dev_priv->mm.active_list));
2461                 WARN_ON(!list_empty(&dev_priv->mm.flushing_list));
2462                 /* Request should now be empty as we've also waited
2463                  * for the last request in the list
2464                  */
2465                 WARN_ON(!list_empty(&dev_priv->mm.request_list));
2466         }
2467
2468         /* Empty the active and flushing lists to inactive.  If there's
2469          * anything left at this point, it means that we're wedged and
2470          * nothing good's going to happen by leaving them there.  So strip
2471          * the GPU domains and just stuff them onto inactive.
2472          */
2473         while (!list_empty(&dev_priv->mm.active_list)) {
2474                 struct drm_i915_gem_object *obj_priv;
2475
2476                 obj_priv = list_first_entry(&dev_priv->mm.active_list,
2477                                             struct drm_i915_gem_object,
2478                                             list);
2479                 obj_priv->obj->write_domain &= ~I915_GEM_GPU_DOMAINS;
2480                 i915_gem_object_move_to_inactive(obj_priv->obj);
2481         }
2482
2483         while (!list_empty(&dev_priv->mm.flushing_list)) {
2484                 struct drm_i915_gem_object *obj_priv;
2485
2486                 obj_priv = list_first_entry(&dev_priv->mm.flushing_list,
2487                                             struct drm_i915_gem_object,
2488                                             list);
2489                 obj_priv->obj->write_domain &= ~I915_GEM_GPU_DOMAINS;
2490                 i915_gem_object_move_to_inactive(obj_priv->obj);
2491         }
2492
2493
2494         /* Move all inactive buffers out of the GTT. */
2495         ret = i915_gem_evict_from_list(dev, &dev_priv->mm.inactive_list);
2496         WARN_ON(!list_empty(&dev_priv->mm.inactive_list));
2497         if (ret) {
2498                 mutex_unlock(&dev->struct_mutex);
2499                 return ret;
2500         }
2501
2502         i915_gem_cleanup_ringbuffer(dev);
2503         mutex_unlock(&dev->struct_mutex);
2504
2505         return 0;
2506 }
2507
2508 static int
2509 i915_gem_init_hws(struct drm_device *dev)
2510 {
2511         drm_i915_private_t *dev_priv = dev->dev_private;
2512         struct drm_gem_object *obj;
2513         struct drm_i915_gem_object *obj_priv;
2514         int ret;
2515
2516         /* If we need a physical address for the status page, it's already
2517          * initialized at driver load time.
2518          */
2519         if (!I915_NEED_GFX_HWS(dev))
2520                 return 0;
2521
2522         obj = drm_gem_object_alloc(dev, 4096);
2523         if (obj == NULL) {
2524                 DRM_ERROR("Failed to allocate status page\n");
2525                 return -ENOMEM;
2526         }
2527         obj_priv = obj->driver_private;
2528         obj_priv->agp_type = AGP_USER_CACHED_MEMORY;
2529
2530         ret = i915_gem_object_pin(obj, 4096);
2531         if (ret != 0) {
2532                 drm_gem_object_unreference(obj);
2533                 return ret;
2534         }
2535
2536         dev_priv->status_gfx_addr = obj_priv->gtt_offset;
2537
2538         dev_priv->hw_status_page = kmap(obj_priv->page_list[0]);
2539         if (dev_priv->hw_status_page == NULL) {
2540                 DRM_ERROR("Failed to map status page.\n");
2541                 memset(&dev_priv->hws_map, 0, sizeof(dev_priv->hws_map));
2542                 drm_gem_object_unreference(obj);
2543                 return -EINVAL;
2544         }
2545         dev_priv->hws_obj = obj;
2546         memset(dev_priv->hw_status_page, 0, PAGE_SIZE);
2547         I915_WRITE(HWS_PGA, dev_priv->status_gfx_addr);
2548         I915_READ(HWS_PGA); /* posting read */
2549         DRM_DEBUG("hws offset: 0x%08x\n", dev_priv->status_gfx_addr);
2550
2551         return 0;
2552 }
2553
2554 static int
2555 i915_gem_init_ringbuffer(struct drm_device *dev)
2556 {
2557         drm_i915_private_t *dev_priv = dev->dev_private;
2558         struct drm_gem_object *obj;
2559         struct drm_i915_gem_object *obj_priv;
2560         int ret;
2561         u32 head;
2562
2563         ret = i915_gem_init_hws(dev);
2564         if (ret != 0)
2565                 return ret;
2566
2567         obj = drm_gem_object_alloc(dev, 128 * 1024);
2568         if (obj == NULL) {
2569                 DRM_ERROR("Failed to allocate ringbuffer\n");
2570                 return -ENOMEM;
2571         }
2572         obj_priv = obj->driver_private;
2573
2574         ret = i915_gem_object_pin(obj, 4096);
2575         if (ret != 0) {
2576                 drm_gem_object_unreference(obj);
2577                 return ret;
2578         }
2579
2580         /* Set up the kernel mapping for the ring. */
2581         dev_priv->ring.Size = obj->size;
2582         dev_priv->ring.tail_mask = obj->size - 1;
2583
2584         dev_priv->ring.map.offset = dev->agp->base + obj_priv->gtt_offset;
2585         dev_priv->ring.map.size = obj->size;
2586         dev_priv->ring.map.type = 0;
2587         dev_priv->ring.map.flags = 0;
2588         dev_priv->ring.map.mtrr = 0;
2589
2590         drm_core_ioremap_wc(&dev_priv->ring.map, dev);
2591         if (dev_priv->ring.map.handle == NULL) {
2592                 DRM_ERROR("Failed to map ringbuffer.\n");
2593                 memset(&dev_priv->ring, 0, sizeof(dev_priv->ring));
2594                 drm_gem_object_unreference(obj);
2595                 return -EINVAL;
2596         }
2597         dev_priv->ring.ring_obj = obj;
2598         dev_priv->ring.virtual_start = dev_priv->ring.map.handle;
2599
2600         /* Stop the ring if it's running. */
2601         I915_WRITE(PRB0_CTL, 0);
2602         I915_WRITE(PRB0_TAIL, 0);
2603         I915_WRITE(PRB0_HEAD, 0);
2604
2605         /* Initialize the ring. */
2606         I915_WRITE(PRB0_START, obj_priv->gtt_offset);
2607         head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
2608
2609         /* G45 ring initialization fails to reset head to zero */
2610         if (head != 0) {
2611                 DRM_ERROR("Ring head not reset to zero "
2612                           "ctl %08x head %08x tail %08x start %08x\n",
2613                           I915_READ(PRB0_CTL),
2614                           I915_READ(PRB0_HEAD),
2615                           I915_READ(PRB0_TAIL),
2616                           I915_READ(PRB0_START));
2617                 I915_WRITE(PRB0_HEAD, 0);
2618
2619                 DRM_ERROR("Ring head forced to zero "
2620                           "ctl %08x head %08x tail %08x start %08x\n",
2621                           I915_READ(PRB0_CTL),
2622                           I915_READ(PRB0_HEAD),
2623                           I915_READ(PRB0_TAIL),
2624                           I915_READ(PRB0_START));
2625         }
2626
2627         I915_WRITE(PRB0_CTL,
2628                    ((obj->size - 4096) & RING_NR_PAGES) |
2629                    RING_NO_REPORT |
2630                    RING_VALID);
2631
2632         head = I915_READ(PRB0_HEAD) & HEAD_ADDR;
2633
2634         /* If the head is still not zero, the ring is dead */
2635         if (head != 0) {
2636                 DRM_ERROR("Ring initialization failed "
2637                           "ctl %08x head %08x tail %08x start %08x\n",
2638                           I915_READ(PRB0_CTL),
2639                           I915_READ(PRB0_HEAD),
2640                           I915_READ(PRB0_TAIL),
2641                           I915_READ(PRB0_START));
2642                 return -EIO;
2643         }
2644
2645         /* Update our cache of the ring state */
2646         i915_kernel_lost_context(dev);
2647
2648         return 0;
2649 }
2650
2651 static void
2652 i915_gem_cleanup_ringbuffer(struct drm_device *dev)
2653 {
2654         drm_i915_private_t *dev_priv = dev->dev_private;
2655
2656         if (dev_priv->ring.ring_obj == NULL)
2657                 return;
2658
2659         drm_core_ioremapfree(&dev_priv->ring.map, dev);
2660
2661         i915_gem_object_unpin(dev_priv->ring.ring_obj);
2662         drm_gem_object_unreference(dev_priv->ring.ring_obj);
2663         dev_priv->ring.ring_obj = NULL;
2664         memset(&dev_priv->ring, 0, sizeof(dev_priv->ring));
2665
2666         if (dev_priv->hws_obj != NULL) {
2667                 struct drm_gem_object *obj = dev_priv->hws_obj;
2668                 struct drm_i915_gem_object *obj_priv = obj->driver_private;
2669
2670                 kunmap(obj_priv->page_list[0]);
2671                 i915_gem_object_unpin(obj);
2672                 drm_gem_object_unreference(obj);
2673                 dev_priv->hws_obj = NULL;
2674                 memset(&dev_priv->hws_map, 0, sizeof(dev_priv->hws_map));
2675                 dev_priv->hw_status_page = NULL;
2676
2677                 /* Write high address into HWS_PGA when disabling. */
2678                 I915_WRITE(HWS_PGA, 0x1ffff000);
2679         }
2680 }
2681
2682 int
2683 i915_gem_entervt_ioctl(struct drm_device *dev, void *data,
2684                        struct drm_file *file_priv)
2685 {
2686         drm_i915_private_t *dev_priv = dev->dev_private;
2687         int ret;
2688
2689         if (dev_priv->mm.wedged) {
2690                 DRM_ERROR("Reenabling wedged hardware, good luck\n");
2691                 dev_priv->mm.wedged = 0;
2692         }
2693
2694         ret = i915_gem_init_ringbuffer(dev);
2695         if (ret != 0)
2696                 return ret;
2697
2698         dev_priv->mm.gtt_mapping = io_mapping_create_wc(dev->agp->base,
2699                                                         dev->agp->agp_info.aper_size
2700                                                         * 1024 * 1024);
2701
2702         mutex_lock(&dev->struct_mutex);
2703         BUG_ON(!list_empty(&dev_priv->mm.active_list));
2704         BUG_ON(!list_empty(&dev_priv->mm.flushing_list));
2705         BUG_ON(!list_empty(&dev_priv->mm.inactive_list));
2706         BUG_ON(!list_empty(&dev_priv->mm.request_list));
2707         dev_priv->mm.suspended = 0;
2708         mutex_unlock(&dev->struct_mutex);
2709
2710         drm_irq_install(dev);
2711
2712         return 0;
2713 }
2714
2715 int
2716 i915_gem_leavevt_ioctl(struct drm_device *dev, void *data,
2717                        struct drm_file *file_priv)
2718 {
2719         drm_i915_private_t *dev_priv = dev->dev_private;
2720         int ret;
2721
2722         ret = i915_gem_idle(dev);
2723         drm_irq_uninstall(dev);
2724
2725         io_mapping_free(dev_priv->mm.gtt_mapping);
2726         return ret;
2727 }
2728
2729 void
2730 i915_gem_lastclose(struct drm_device *dev)
2731 {
2732         int ret;
2733
2734         ret = i915_gem_idle(dev);
2735         if (ret)
2736                 DRM_ERROR("failed to idle hardware: %d\n", ret);
2737 }
2738
2739 void
2740 i915_gem_load(struct drm_device *dev)
2741 {
2742         drm_i915_private_t *dev_priv = dev->dev_private;
2743
2744         INIT_LIST_HEAD(&dev_priv->mm.active_list);
2745         INIT_LIST_HEAD(&dev_priv->mm.flushing_list);
2746         INIT_LIST_HEAD(&dev_priv->mm.inactive_list);
2747         INIT_LIST_HEAD(&dev_priv->mm.request_list);
2748         INIT_DELAYED_WORK(&dev_priv->mm.retire_work,
2749                           i915_gem_retire_work_handler);
2750         dev_priv->mm.next_gem_seqno = 1;
2751
2752         i915_gem_detect_bit_6_swizzle(dev);
2753 }