drm/vmwgfx: Avoid cmdbuf alloc sleeping if !TASK_RUNNING
[linux-2.6-block.git] / drivers / gpu / drm / vmwgfx / vmwgfx_cmdbuf.c
1 /**************************************************************************
2  *
3  * Copyright © 2015 VMware, Inc., Palo Alto, CA., USA
4  * All Rights Reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sub license, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice (including the
15  * next paragraph) shall be included in all copies or substantial portions
16  * of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
21  * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
22  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
23  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
24  * USE OR OTHER DEALINGS IN THE SOFTWARE.
25  *
26  **************************************************************************/
27
28 #include "vmwgfx_drv.h"
29 #include "ttm/ttm_bo_api.h"
30
31 /*
32  * Size of inline command buffers. Try to make sure that a page size is a
33  * multiple of the DMA pool allocation size.
34  */
35 #define VMW_CMDBUF_INLINE_ALIGN 64
36 #define VMW_CMDBUF_INLINE_SIZE \
37         (1024 - ALIGN(sizeof(SVGACBHeader), VMW_CMDBUF_INLINE_ALIGN))
38
39 /**
40  * struct vmw_cmdbuf_context - Command buffer context queues
41  *
42  * @submitted: List of command buffers that have been submitted to the
43  * manager but not yet submitted to hardware.
44  * @hw_submitted: List of command buffers submitted to hardware.
45  * @preempted: List of preempted command buffers.
46  * @num_hw_submitted: Number of buffers currently being processed by hardware
47  */
48 struct vmw_cmdbuf_context {
49         struct list_head submitted;
50         struct list_head hw_submitted;
51         struct list_head preempted;
52         unsigned num_hw_submitted;
53 };
54
55 /**
56  * struct vmw_cmdbuf_man: - Command buffer manager
57  *
58  * @cur_mutex: Mutex protecting the command buffer used for incremental small
59  * kernel command submissions, @cur.
60  * @space_mutex: Mutex to protect against starvation when we allocate
61  * main pool buffer space.
62  * @work: A struct work_struct implementeing command buffer error handling.
63  * Immutable.
64  * @dev_priv: Pointer to the device private struct. Immutable.
65  * @ctx: Array of command buffer context queues. The queues and the context
66  * data is protected by @lock.
67  * @error: List of command buffers that have caused device errors.
68  * Protected by @lock.
69  * @mm: Range manager for the command buffer space. Manager allocations and
70  * frees are protected by @lock.
71  * @cmd_space: Buffer object for the command buffer space, unless we were
72  * able to make a contigous coherent DMA memory allocation, @handle. Immutable.
73  * @map_obj: Mapping state for @cmd_space. Immutable.
74  * @map: Pointer to command buffer space. May be a mapped buffer object or
75  * a contigous coherent DMA memory allocation. Immutable.
76  * @cur: Command buffer for small kernel command submissions. Protected by
77  * the @cur_mutex.
78  * @cur_pos: Space already used in @cur. Protected by @cur_mutex.
79  * @default_size: Default size for the @cur command buffer. Immutable.
80  * @max_hw_submitted: Max number of in-flight command buffers the device can
81  * handle. Immutable.
82  * @lock: Spinlock protecting command submission queues.
83  * @header: Pool of DMA memory for device command buffer headers.
84  * Internal protection.
85  * @dheaders: Pool of DMA memory for device command buffer headers with trailing
86  * space for inline data. Internal protection.
87  * @tasklet: Tasklet struct for irq processing. Immutable.
88  * @alloc_queue: Wait queue for processes waiting to allocate command buffer
89  * space.
90  * @idle_queue: Wait queue for processes waiting for command buffer idle.
91  * @irq_on: Whether the process function has requested irq to be turned on.
92  * Protected by @lock.
93  * @using_mob: Whether the command buffer space is a MOB or a contigous DMA
94  * allocation. Immutable.
95  * @has_pool: Has a large pool of DMA memory which allows larger allocations.
96  * Typically this is false only during bootstrap.
97  * @handle: DMA address handle for the command buffer space if @using_mob is
98  * false. Immutable.
99  * @size: The size of the command buffer space. Immutable.
100  */
101 struct vmw_cmdbuf_man {
102         struct mutex cur_mutex;
103         struct mutex space_mutex;
104         struct work_struct work;
105         struct vmw_private *dev_priv;
106         struct vmw_cmdbuf_context ctx[SVGA_CB_CONTEXT_MAX];
107         struct list_head error;
108         struct drm_mm mm;
109         struct ttm_buffer_object *cmd_space;
110         struct ttm_bo_kmap_obj map_obj;
111         u8 *map;
112         struct vmw_cmdbuf_header *cur;
113         size_t cur_pos;
114         size_t default_size;
115         unsigned max_hw_submitted;
116         spinlock_t lock;
117         struct dma_pool *headers;
118         struct dma_pool *dheaders;
119         struct tasklet_struct tasklet;
120         wait_queue_head_t alloc_queue;
121         wait_queue_head_t idle_queue;
122         bool irq_on;
123         bool using_mob;
124         bool has_pool;
125         dma_addr_t handle;
126         size_t size;
127 };
128
129 /**
130  * struct vmw_cmdbuf_header - Command buffer metadata
131  *
132  * @man: The command buffer manager.
133  * @cb_header: Device command buffer header, allocated from a DMA pool.
134  * @cb_context: The device command buffer context.
135  * @list: List head for attaching to the manager lists.
136  * @node: The range manager node.
137  * @handle. The DMA address of @cb_header. Handed to the device on command
138  * buffer submission.
139  * @cmd: Pointer to the command buffer space of this buffer.
140  * @size: Size of the command buffer space of this buffer.
141  * @reserved: Reserved space of this buffer.
142  * @inline_space: Whether inline command buffer space is used.
143  */
144 struct vmw_cmdbuf_header {
145         struct vmw_cmdbuf_man *man;
146         SVGACBHeader *cb_header;
147         SVGACBContext cb_context;
148         struct list_head list;
149         struct drm_mm_node node;
150         dma_addr_t handle;
151         u8 *cmd;
152         size_t size;
153         size_t reserved;
154         bool inline_space;
155 };
156
157 /**
158  * struct vmw_cmdbuf_dheader - Device command buffer header with inline
159  * command buffer space.
160  *
161  * @cb_header: Device command buffer header.
162  * @cmd: Inline command buffer space.
163  */
164 struct vmw_cmdbuf_dheader {
165         SVGACBHeader cb_header;
166         u8 cmd[VMW_CMDBUF_INLINE_SIZE] __aligned(VMW_CMDBUF_INLINE_ALIGN);
167 };
168
169 /**
170  * struct vmw_cmdbuf_alloc_info - Command buffer space allocation metadata
171  *
172  * @page_size: Size of requested command buffer space in pages.
173  * @node: Pointer to the range manager node.
174  * @done: True if this allocation has succeeded.
175  */
176 struct vmw_cmdbuf_alloc_info {
177         size_t page_size;
178         struct drm_mm_node *node;
179         bool done;
180 };
181
182 /* Loop over each context in the command buffer manager. */
183 #define for_each_cmdbuf_ctx(_man, _i, _ctx) \
184         for (_i = 0, _ctx = &(_man)->ctx[0]; (_i) < SVGA_CB_CONTEXT_MAX; \
185              ++(_i), ++(_ctx))
186
187 static int vmw_cmdbuf_startstop(struct vmw_cmdbuf_man *man, bool enable);
188
189
190 /**
191  * vmw_cmdbuf_cur_lock - Helper to lock the cur_mutex.
192  *
193  * @man: The range manager.
194  * @interruptible: Whether to wait interruptible when locking.
195  */
196 static int vmw_cmdbuf_cur_lock(struct vmw_cmdbuf_man *man, bool interruptible)
197 {
198         if (interruptible) {
199                 if (mutex_lock_interruptible(&man->cur_mutex))
200                         return -ERESTARTSYS;
201         } else {
202                 mutex_lock(&man->cur_mutex);
203         }
204
205         return 0;
206 }
207
208 /**
209  * vmw_cmdbuf_cur_unlock - Helper to unlock the cur_mutex.
210  *
211  * @man: The range manager.
212  */
213 static void vmw_cmdbuf_cur_unlock(struct vmw_cmdbuf_man *man)
214 {
215         mutex_unlock(&man->cur_mutex);
216 }
217
218 /**
219  * vmw_cmdbuf_header_inline_free - Free a struct vmw_cmdbuf_header that has
220  * been used for the device context with inline command buffers.
221  * Need not be called locked.
222  *
223  * @header: Pointer to the header to free.
224  */
225 static void vmw_cmdbuf_header_inline_free(struct vmw_cmdbuf_header *header)
226 {
227         struct vmw_cmdbuf_dheader *dheader;
228
229         if (WARN_ON_ONCE(!header->inline_space))
230                 return;
231
232         dheader = container_of(header->cb_header, struct vmw_cmdbuf_dheader,
233                                cb_header);
234         dma_pool_free(header->man->dheaders, dheader, header->handle);
235         kfree(header);
236 }
237
238 /**
239  * __vmw_cmdbuf_header_free - Free a struct vmw_cmdbuf_header  and its
240  * associated structures.
241  *
242  * header: Pointer to the header to free.
243  *
244  * For internal use. Must be called with man::lock held.
245  */
246 static void __vmw_cmdbuf_header_free(struct vmw_cmdbuf_header *header)
247 {
248         struct vmw_cmdbuf_man *man = header->man;
249
250         BUG_ON(!spin_is_locked(&man->lock));
251
252         if (header->inline_space) {
253                 vmw_cmdbuf_header_inline_free(header);
254                 return;
255         }
256
257         drm_mm_remove_node(&header->node);
258         wake_up_all(&man->alloc_queue);
259         if (header->cb_header)
260                 dma_pool_free(man->headers, header->cb_header,
261                               header->handle);
262         kfree(header);
263 }
264
265 /**
266  * vmw_cmdbuf_header_free - Free a struct vmw_cmdbuf_header  and its
267  * associated structures.
268  *
269  * @header: Pointer to the header to free.
270  */
271 void vmw_cmdbuf_header_free(struct vmw_cmdbuf_header *header)
272 {
273         struct vmw_cmdbuf_man *man = header->man;
274
275         /* Avoid locking if inline_space */
276         if (header->inline_space) {
277                 vmw_cmdbuf_header_inline_free(header);
278                 return;
279         }
280         spin_lock_bh(&man->lock);
281         __vmw_cmdbuf_header_free(header);
282         spin_unlock_bh(&man->lock);
283 }
284
285
286 /**
287  * vmw_cmbuf_header_submit: Submit a command buffer to hardware.
288  *
289  * @header: The header of the buffer to submit.
290  */
291 static int vmw_cmdbuf_header_submit(struct vmw_cmdbuf_header *header)
292 {
293         struct vmw_cmdbuf_man *man = header->man;
294         u32 val;
295
296         val = (header->handle >> 32);
297         vmw_write(man->dev_priv, SVGA_REG_COMMAND_HIGH, val);
298         val = (header->handle & 0xFFFFFFFFULL);
299         val |= header->cb_context & SVGA_CB_CONTEXT_MASK;
300         vmw_write(man->dev_priv, SVGA_REG_COMMAND_LOW, val);
301
302         return header->cb_header->status;
303 }
304
305 /**
306  * vmw_cmdbuf_ctx_init: Initialize a command buffer context.
307  *
308  * @ctx: The command buffer context to initialize
309  */
310 static void vmw_cmdbuf_ctx_init(struct vmw_cmdbuf_context *ctx)
311 {
312         INIT_LIST_HEAD(&ctx->hw_submitted);
313         INIT_LIST_HEAD(&ctx->submitted);
314         INIT_LIST_HEAD(&ctx->preempted);
315         ctx->num_hw_submitted = 0;
316 }
317
318 /**
319  * vmw_cmdbuf_ctx_submit: Submit command buffers from a command buffer
320  * context.
321  *
322  * @man: The command buffer manager.
323  * @ctx: The command buffer context.
324  *
325  * Submits command buffers to hardware until there are no more command
326  * buffers to submit or the hardware can't handle more command buffers.
327  */
328 static void vmw_cmdbuf_ctx_submit(struct vmw_cmdbuf_man *man,
329                                   struct vmw_cmdbuf_context *ctx)
330 {
331         while (ctx->num_hw_submitted < man->max_hw_submitted &&
332               !list_empty(&ctx->submitted)) {
333                 struct vmw_cmdbuf_header *entry;
334                 SVGACBStatus status;
335
336                 entry = list_first_entry(&ctx->submitted,
337                                          struct vmw_cmdbuf_header,
338                                          list);
339
340                 status = vmw_cmdbuf_header_submit(entry);
341
342                 /* This should never happen */
343                 if (WARN_ON_ONCE(status == SVGA_CB_STATUS_QUEUE_FULL)) {
344                         entry->cb_header->status = SVGA_CB_STATUS_NONE;
345                         break;
346                 }
347
348                 list_del(&entry->list);
349                 list_add_tail(&entry->list, &ctx->hw_submitted);
350                 ctx->num_hw_submitted++;
351         }
352
353 }
354
355 /**
356  * vmw_cmdbuf_ctx_submit: Process a command buffer context.
357  *
358  * @man: The command buffer manager.
359  * @ctx: The command buffer context.
360  *
361  * Submit command buffers to hardware if possible, and process finished
362  * buffers. Typically freeing them, but on preemption or error take
363  * appropriate action. Wake up waiters if appropriate.
364  */
365 static void vmw_cmdbuf_ctx_process(struct vmw_cmdbuf_man *man,
366                                    struct vmw_cmdbuf_context *ctx,
367                                    int *notempty)
368 {
369         struct vmw_cmdbuf_header *entry, *next;
370
371         vmw_cmdbuf_ctx_submit(man, ctx);
372
373         list_for_each_entry_safe(entry, next, &ctx->hw_submitted, list) {
374                 SVGACBStatus status = entry->cb_header->status;
375
376                 if (status == SVGA_CB_STATUS_NONE)
377                         break;
378
379                 list_del(&entry->list);
380                 wake_up_all(&man->idle_queue);
381                 ctx->num_hw_submitted--;
382                 switch (status) {
383                 case SVGA_CB_STATUS_COMPLETED:
384                         __vmw_cmdbuf_header_free(entry);
385                         break;
386                 case SVGA_CB_STATUS_COMMAND_ERROR:
387                 case SVGA_CB_STATUS_CB_HEADER_ERROR:
388                         list_add_tail(&entry->list, &man->error);
389                         schedule_work(&man->work);
390                         break;
391                 case SVGA_CB_STATUS_PREEMPTED:
392                         list_add(&entry->list, &ctx->preempted);
393                         break;
394                 default:
395                         WARN_ONCE(true, "Undefined command buffer status.\n");
396                         __vmw_cmdbuf_header_free(entry);
397                         break;
398                 }
399         }
400
401         vmw_cmdbuf_ctx_submit(man, ctx);
402         if (!list_empty(&ctx->submitted))
403                 (*notempty)++;
404 }
405
406 /**
407  * vmw_cmdbuf_man_process - Process all command buffer contexts and
408  * switch on and off irqs as appropriate.
409  *
410  * @man: The command buffer manager.
411  *
412  * Calls vmw_cmdbuf_ctx_process() on all contexts. If any context has
413  * command buffers left that are not submitted to hardware, Make sure
414  * IRQ handling is turned on. Otherwise, make sure it's turned off. This
415  * function may return -EAGAIN to indicate it should be rerun due to
416  * possibly missed IRQs if IRQs has just been turned on.
417  */
418 static int vmw_cmdbuf_man_process(struct vmw_cmdbuf_man *man)
419 {
420         int notempty = 0;
421         struct vmw_cmdbuf_context *ctx;
422         int i;
423
424         for_each_cmdbuf_ctx(man, i, ctx)
425                 vmw_cmdbuf_ctx_process(man, ctx, &notempty);
426
427         if (man->irq_on && !notempty) {
428                 vmw_generic_waiter_remove(man->dev_priv,
429                                           SVGA_IRQFLAG_COMMAND_BUFFER,
430                                           &man->dev_priv->cmdbuf_waiters);
431                 man->irq_on = false;
432         } else if (!man->irq_on && notempty) {
433                 vmw_generic_waiter_add(man->dev_priv,
434                                        SVGA_IRQFLAG_COMMAND_BUFFER,
435                                        &man->dev_priv->cmdbuf_waiters);
436                 man->irq_on = true;
437
438                 /* Rerun in case we just missed an irq. */
439                 return -EAGAIN;
440         }
441
442         return 0;
443 }
444
445 /**
446  * vmw_cmdbuf_ctx_add - Schedule a command buffer for submission on a
447  * command buffer context
448  *
449  * @man: The command buffer manager.
450  * @header: The header of the buffer to submit.
451  * @cb_context: The command buffer context to use.
452  *
453  * This function adds @header to the "submitted" queue of the command
454  * buffer context identified by @cb_context. It then calls the command buffer
455  * manager processing to potentially submit the buffer to hardware.
456  * @man->lock needs to be held when calling this function.
457  */
458 static void vmw_cmdbuf_ctx_add(struct vmw_cmdbuf_man *man,
459                                struct vmw_cmdbuf_header *header,
460                                SVGACBContext cb_context)
461 {
462         if (!(header->cb_header->flags & SVGA_CB_FLAG_DX_CONTEXT))
463                 header->cb_header->dxContext = 0;
464         header->cb_context = cb_context;
465         list_add_tail(&header->list, &man->ctx[cb_context].submitted);
466
467         if (vmw_cmdbuf_man_process(man) == -EAGAIN)
468                 vmw_cmdbuf_man_process(man);
469 }
470
471 /**
472  * vmw_cmdbuf_man_tasklet - The main part of the command buffer interrupt
473  * handler implemented as a tasklet.
474  *
475  * @data: Tasklet closure. A pointer to the command buffer manager cast to
476  * an unsigned long.
477  *
478  * The bottom half (tasklet) of the interrupt handler simply calls into the
479  * command buffer processor to free finished buffers and submit any
480  * queued buffers to hardware.
481  */
482 static void vmw_cmdbuf_man_tasklet(unsigned long data)
483 {
484         struct vmw_cmdbuf_man *man = (struct vmw_cmdbuf_man *) data;
485
486         spin_lock(&man->lock);
487         if (vmw_cmdbuf_man_process(man) == -EAGAIN)
488                 (void) vmw_cmdbuf_man_process(man);
489         spin_unlock(&man->lock);
490 }
491
492 /**
493  * vmw_cmdbuf_work_func - The deferred work function that handles
494  * command buffer errors.
495  *
496  * @work: The work func closure argument.
497  *
498  * Restarting the command buffer context after an error requires process
499  * context, so it is deferred to this work function.
500  */
501 static void vmw_cmdbuf_work_func(struct work_struct *work)
502 {
503         struct vmw_cmdbuf_man *man =
504                 container_of(work, struct vmw_cmdbuf_man, work);
505         struct vmw_cmdbuf_header *entry, *next;
506         bool restart;
507
508         spin_lock_bh(&man->lock);
509         list_for_each_entry_safe(entry, next, &man->error, list) {
510                 restart = true;
511                 DRM_ERROR("Command buffer error.\n");
512
513                 list_del(&entry->list);
514                 __vmw_cmdbuf_header_free(entry);
515                 wake_up_all(&man->idle_queue);
516         }
517         spin_unlock_bh(&man->lock);
518
519         if (restart && vmw_cmdbuf_startstop(man, true))
520                 DRM_ERROR("Failed restarting command buffer context 0.\n");
521
522 }
523
524 /**
525  * vmw_cmdbuf_man idle - Check whether the command buffer manager is idle.
526  *
527  * @man: The command buffer manager.
528  * @check_preempted: Check also the preempted queue for pending command buffers.
529  *
530  */
531 static bool vmw_cmdbuf_man_idle(struct vmw_cmdbuf_man *man,
532                                 bool check_preempted)
533 {
534         struct vmw_cmdbuf_context *ctx;
535         bool idle = false;
536         int i;
537
538         spin_lock_bh(&man->lock);
539         vmw_cmdbuf_man_process(man);
540         for_each_cmdbuf_ctx(man, i, ctx) {
541                 if (!list_empty(&ctx->submitted) ||
542                     !list_empty(&ctx->hw_submitted) ||
543                     (check_preempted && !list_empty(&ctx->preempted)))
544                         goto out_unlock;
545         }
546
547         idle = list_empty(&man->error);
548
549 out_unlock:
550         spin_unlock_bh(&man->lock);
551
552         return idle;
553 }
554
555 /**
556  * __vmw_cmdbuf_cur_flush - Flush the current command buffer for small kernel
557  * command submissions
558  *
559  * @man: The command buffer manager.
560  *
561  * Flushes the current command buffer without allocating a new one. A new one
562  * is automatically allocated when needed. Call with @man->cur_mutex held.
563  */
564 static void __vmw_cmdbuf_cur_flush(struct vmw_cmdbuf_man *man)
565 {
566         struct vmw_cmdbuf_header *cur = man->cur;
567
568         WARN_ON(!mutex_is_locked(&man->cur_mutex));
569
570         if (!cur)
571                 return;
572
573         spin_lock_bh(&man->lock);
574         if (man->cur_pos == 0) {
575                 __vmw_cmdbuf_header_free(cur);
576                 goto out_unlock;
577         }
578
579         man->cur->cb_header->length = man->cur_pos;
580         vmw_cmdbuf_ctx_add(man, man->cur, SVGA_CB_CONTEXT_0);
581 out_unlock:
582         spin_unlock_bh(&man->lock);
583         man->cur = NULL;
584         man->cur_pos = 0;
585 }
586
587 /**
588  * vmw_cmdbuf_cur_flush - Flush the current command buffer for small kernel
589  * command submissions
590  *
591  * @man: The command buffer manager.
592  * @interruptible: Whether to sleep interruptible when sleeping.
593  *
594  * Flushes the current command buffer without allocating a new one. A new one
595  * is automatically allocated when needed.
596  */
597 int vmw_cmdbuf_cur_flush(struct vmw_cmdbuf_man *man,
598                          bool interruptible)
599 {
600         int ret = vmw_cmdbuf_cur_lock(man, interruptible);
601
602         if (ret)
603                 return ret;
604
605         __vmw_cmdbuf_cur_flush(man);
606         vmw_cmdbuf_cur_unlock(man);
607
608         return 0;
609 }
610
611 /**
612  * vmw_cmdbuf_idle - Wait for command buffer manager idle.
613  *
614  * @man: The command buffer manager.
615  * @interruptible: Sleep interruptible while waiting.
616  * @timeout: Time out after this many ticks.
617  *
618  * Wait until the command buffer manager has processed all command buffers,
619  * or until a timeout occurs. If a timeout occurs, the function will return
620  * -EBUSY.
621  */
622 int vmw_cmdbuf_idle(struct vmw_cmdbuf_man *man, bool interruptible,
623                     unsigned long timeout)
624 {
625         int ret;
626
627         ret = vmw_cmdbuf_cur_flush(man, interruptible);
628         vmw_generic_waiter_add(man->dev_priv,
629                                SVGA_IRQFLAG_COMMAND_BUFFER,
630                                &man->dev_priv->cmdbuf_waiters);
631
632         if (interruptible) {
633                 ret = wait_event_interruptible_timeout
634                         (man->idle_queue, vmw_cmdbuf_man_idle(man, true),
635                          timeout);
636         } else {
637                 ret = wait_event_timeout
638                         (man->idle_queue, vmw_cmdbuf_man_idle(man, true),
639                          timeout);
640         }
641         vmw_generic_waiter_remove(man->dev_priv,
642                                   SVGA_IRQFLAG_COMMAND_BUFFER,
643                                   &man->dev_priv->cmdbuf_waiters);
644         if (ret == 0) {
645                 if (!vmw_cmdbuf_man_idle(man, true))
646                         ret = -EBUSY;
647                 else
648                         ret = 0;
649         }
650         if (ret > 0)
651                 ret = 0;
652
653         return ret;
654 }
655
656 /**
657  * vmw_cmdbuf_try_alloc - Try to allocate buffer space from the main pool.
658  *
659  * @man: The command buffer manager.
660  * @info: Allocation info. Will hold the size on entry and allocated mm node
661  * on successful return.
662  *
663  * Try to allocate buffer space from the main pool. Returns true if succeeded.
664  * If a fatal error was hit, the error code is returned in @info->ret.
665  */
666 static bool vmw_cmdbuf_try_alloc(struct vmw_cmdbuf_man *man,
667                                  struct vmw_cmdbuf_alloc_info *info)
668 {
669         int ret;
670
671         if (info->done)
672                 return true;
673  
674         memset(info->node, 0, sizeof(*info->node));
675         spin_lock_bh(&man->lock);
676         ret = drm_mm_insert_node_generic(&man->mm, info->node, info->page_size,
677                                          0, 0,
678                                          DRM_MM_SEARCH_DEFAULT,
679                                          DRM_MM_CREATE_DEFAULT);
680         spin_unlock_bh(&man->lock);
681         info->done = !ret;
682
683         return info->done;
684 }
685
686 /**
687  * vmw_cmdbuf_alloc_space - Allocate buffer space from the main pool.
688  *
689  * @man: The command buffer manager.
690  * @node: Pointer to pre-allocated range-manager node.
691  * @size: The size of the allocation.
692  * @interruptible: Whether to sleep interruptible while waiting for space.
693  *
694  * This function allocates buffer space from the main pool, and if there is
695  * no space available ATM, it turns on IRQ handling and sleeps waiting for it to
696  * become available.
697  */
698 int vmw_cmdbuf_alloc_space(struct vmw_cmdbuf_man *man,
699                            struct drm_mm_node *node,
700                            size_t size,
701                            bool interruptible)
702 {
703         struct vmw_cmdbuf_alloc_info info;
704
705         info.page_size = PAGE_ALIGN(size) >> PAGE_SHIFT;
706         info.node = node;
707         info.done = false;
708
709         /*
710          * To prevent starvation of large requests, only one allocating call
711          * at a time waiting for space.
712          */
713         if (interruptible) {
714                 if (mutex_lock_interruptible(&man->space_mutex))
715                         return -ERESTARTSYS;
716         } else {
717                 mutex_lock(&man->space_mutex);
718         }
719
720         /* Try to allocate space without waiting. */
721         if (vmw_cmdbuf_try_alloc(man, &info))
722                 goto out_unlock;
723
724         vmw_generic_waiter_add(man->dev_priv,
725                                SVGA_IRQFLAG_COMMAND_BUFFER,
726                                &man->dev_priv->cmdbuf_waiters);
727
728         if (interruptible) {
729                 int ret;
730
731                 ret = wait_event_interruptible
732                         (man->alloc_queue, vmw_cmdbuf_try_alloc(man, &info));
733                 if (ret) {
734                         vmw_generic_waiter_remove
735                                 (man->dev_priv, SVGA_IRQFLAG_COMMAND_BUFFER,
736                                  &man->dev_priv->cmdbuf_waiters);
737                         mutex_unlock(&man->space_mutex);
738                         return ret;
739                 }
740         } else {
741                 wait_event(man->alloc_queue, vmw_cmdbuf_try_alloc(man, &info));
742         }
743         vmw_generic_waiter_remove(man->dev_priv,
744                                   SVGA_IRQFLAG_COMMAND_BUFFER,
745                                   &man->dev_priv->cmdbuf_waiters);
746
747 out_unlock:
748         mutex_unlock(&man->space_mutex);
749
750         return 0;
751 }
752
753 /**
754  * vmw_cmdbuf_space_pool - Set up a command buffer header with command buffer
755  * space from the main pool.
756  *
757  * @man: The command buffer manager.
758  * @header: Pointer to the header to set up.
759  * @size: The requested size of the buffer space.
760  * @interruptible: Whether to sleep interruptible while waiting for space.
761  */
762 static int vmw_cmdbuf_space_pool(struct vmw_cmdbuf_man *man,
763                                  struct vmw_cmdbuf_header *header,
764                                  size_t size,
765                                  bool interruptible)
766 {
767         SVGACBHeader *cb_hdr;
768         size_t offset;
769         int ret;
770
771         if (!man->has_pool)
772                 return -ENOMEM;
773
774         ret = vmw_cmdbuf_alloc_space(man, &header->node,  size, interruptible);
775
776         if (ret)
777                 return ret;
778
779         header->cb_header = dma_pool_alloc(man->headers, GFP_KERNEL,
780                                            &header->handle);
781         if (!header->cb_header) {
782                 ret = -ENOMEM;
783                 goto out_no_cb_header;
784         }
785
786         header->size = header->node.size << PAGE_SHIFT;
787         cb_hdr = header->cb_header;
788         offset = header->node.start << PAGE_SHIFT;
789         header->cmd = man->map + offset;
790         memset(cb_hdr, 0, sizeof(*cb_hdr));
791         if (man->using_mob) {
792                 cb_hdr->flags = SVGA_CB_FLAG_MOB;
793                 cb_hdr->ptr.mob.mobid = man->cmd_space->mem.start;
794                 cb_hdr->ptr.mob.mobOffset = offset;
795         } else {
796                 cb_hdr->ptr.pa = (u64)man->handle + (u64)offset;
797         }
798
799         return 0;
800
801 out_no_cb_header:
802         spin_lock_bh(&man->lock);
803         drm_mm_remove_node(&header->node);
804         spin_unlock_bh(&man->lock);
805
806         return ret;
807 }
808
809 /**
810  * vmw_cmdbuf_space_inline - Set up a command buffer header with
811  * inline command buffer space.
812  *
813  * @man: The command buffer manager.
814  * @header: Pointer to the header to set up.
815  * @size: The requested size of the buffer space.
816  */
817 static int vmw_cmdbuf_space_inline(struct vmw_cmdbuf_man *man,
818                                    struct vmw_cmdbuf_header *header,
819                                    int size)
820 {
821         struct vmw_cmdbuf_dheader *dheader;
822         SVGACBHeader *cb_hdr;
823
824         if (WARN_ON_ONCE(size > VMW_CMDBUF_INLINE_SIZE))
825                 return -ENOMEM;
826
827         dheader = dma_pool_alloc(man->dheaders, GFP_KERNEL,
828                                  &header->handle);
829         if (!dheader)
830                 return -ENOMEM;
831
832         header->inline_space = true;
833         header->size = VMW_CMDBUF_INLINE_SIZE;
834         cb_hdr = &dheader->cb_header;
835         header->cb_header = cb_hdr;
836         header->cmd = dheader->cmd;
837         memset(dheader, 0, sizeof(*dheader));
838         cb_hdr->status = SVGA_CB_STATUS_NONE;
839         cb_hdr->flags = SVGA_CB_FLAG_NONE;
840         cb_hdr->ptr.pa = (u64)header->handle +
841                 (u64)offsetof(struct vmw_cmdbuf_dheader, cmd);
842
843         return 0;
844 }
845
846 /**
847  * vmw_cmdbuf_alloc - Allocate a command buffer header complete with
848  * command buffer space.
849  *
850  * @man: The command buffer manager.
851  * @size: The requested size of the buffer space.
852  * @interruptible: Whether to sleep interruptible while waiting for space.
853  * @p_header: points to a header pointer to populate on successful return.
854  *
855  * Returns a pointer to command buffer space if successful. Otherwise
856  * returns an error pointer. The header pointer returned in @p_header should
857  * be used for upcoming calls to vmw_cmdbuf_reserve() and vmw_cmdbuf_commit().
858  */
859 void *vmw_cmdbuf_alloc(struct vmw_cmdbuf_man *man,
860                        size_t size, bool interruptible,
861                        struct vmw_cmdbuf_header **p_header)
862 {
863         struct vmw_cmdbuf_header *header;
864         int ret = 0;
865
866         *p_header = NULL;
867
868         header = kzalloc(sizeof(*header), GFP_KERNEL);
869         if (!header)
870                 return ERR_PTR(-ENOMEM);
871
872         if (size <= VMW_CMDBUF_INLINE_SIZE)
873                 ret = vmw_cmdbuf_space_inline(man, header, size);
874         else
875                 ret = vmw_cmdbuf_space_pool(man, header, size, interruptible);
876
877         if (ret) {
878                 kfree(header);
879                 return ERR_PTR(ret);
880         }
881
882         header->man = man;
883         INIT_LIST_HEAD(&header->list);
884         header->cb_header->status = SVGA_CB_STATUS_NONE;
885         *p_header = header;
886
887         return header->cmd;
888 }
889
890 /**
891  * vmw_cmdbuf_reserve_cur - Reserve space for commands in the current
892  * command buffer.
893  *
894  * @man: The command buffer manager.
895  * @size: The requested size of the commands.
896  * @ctx_id: The context id if any. Otherwise set to SVGA3D_REG_INVALID.
897  * @interruptible: Whether to sleep interruptible while waiting for space.
898  *
899  * Returns a pointer to command buffer space if successful. Otherwise
900  * returns an error pointer.
901  */
902 static void *vmw_cmdbuf_reserve_cur(struct vmw_cmdbuf_man *man,
903                                     size_t size,
904                                     int ctx_id,
905                                     bool interruptible)
906 {
907         struct vmw_cmdbuf_header *cur;
908         void *ret;
909
910         if (vmw_cmdbuf_cur_lock(man, interruptible))
911                 return ERR_PTR(-ERESTARTSYS);
912
913         cur = man->cur;
914         if (cur && (size + man->cur_pos > cur->size ||
915             (ctx_id != SVGA3D_INVALID_ID &&
916              (cur->cb_header->flags & SVGA_CB_FLAG_DX_CONTEXT) &&
917              ctx_id != cur->cb_header->dxContext)))
918                 __vmw_cmdbuf_cur_flush(man);
919
920         if (!man->cur) {
921                 ret = vmw_cmdbuf_alloc(man,
922                                        max_t(size_t, size, man->default_size),
923                                        interruptible, &man->cur);
924                 if (IS_ERR(ret)) {
925                         vmw_cmdbuf_cur_unlock(man);
926                         return ret;
927                 }
928
929                 cur = man->cur;
930         }
931
932         if (ctx_id != SVGA3D_INVALID_ID) {
933                 cur->cb_header->flags |= SVGA_CB_FLAG_DX_CONTEXT;
934                 cur->cb_header->dxContext = ctx_id;
935         }
936
937         cur->reserved = size;
938
939         return (void *) (man->cur->cmd + man->cur_pos);
940 }
941
942 /**
943  * vmw_cmdbuf_commit_cur - Commit commands in the current command buffer.
944  *
945  * @man: The command buffer manager.
946  * @size: The size of the commands actually written.
947  * @flush: Whether to flush the command buffer immediately.
948  */
949 static void vmw_cmdbuf_commit_cur(struct vmw_cmdbuf_man *man,
950                                   size_t size, bool flush)
951 {
952         struct vmw_cmdbuf_header *cur = man->cur;
953
954         WARN_ON(!mutex_is_locked(&man->cur_mutex));
955
956         WARN_ON(size > cur->reserved);
957         man->cur_pos += size;
958         if (!size)
959                 cur->cb_header->flags &= ~SVGA_CB_FLAG_DX_CONTEXT;
960         if (flush)
961                 __vmw_cmdbuf_cur_flush(man);
962         vmw_cmdbuf_cur_unlock(man);
963 }
964
965 /**
966  * vmw_cmdbuf_reserve - Reserve space for commands in a command buffer.
967  *
968  * @man: The command buffer manager.
969  * @size: The requested size of the commands.
970  * @ctx_id: The context id if any. Otherwise set to SVGA3D_REG_INVALID.
971  * @interruptible: Whether to sleep interruptible while waiting for space.
972  * @header: Header of the command buffer. NULL if the current command buffer
973  * should be used.
974  *
975  * Returns a pointer to command buffer space if successful. Otherwise
976  * returns an error pointer.
977  */
978 void *vmw_cmdbuf_reserve(struct vmw_cmdbuf_man *man, size_t size,
979                          int ctx_id, bool interruptible,
980                          struct vmw_cmdbuf_header *header)
981 {
982         if (!header)
983                 return vmw_cmdbuf_reserve_cur(man, size, ctx_id, interruptible);
984
985         if (size > header->size)
986                 return ERR_PTR(-EINVAL);
987
988         if (ctx_id != SVGA3D_INVALID_ID) {
989                 header->cb_header->flags |= SVGA_CB_FLAG_DX_CONTEXT;
990                 header->cb_header->dxContext = ctx_id;
991         }
992
993         header->reserved = size;
994         return header->cmd;
995 }
996
997 /**
998  * vmw_cmdbuf_commit - Commit commands in a command buffer.
999  *
1000  * @man: The command buffer manager.
1001  * @size: The size of the commands actually written.
1002  * @header: Header of the command buffer. NULL if the current command buffer
1003  * should be used.
1004  * @flush: Whether to flush the command buffer immediately.
1005  */
1006 void vmw_cmdbuf_commit(struct vmw_cmdbuf_man *man, size_t size,
1007                        struct vmw_cmdbuf_header *header, bool flush)
1008 {
1009         if (!header) {
1010                 vmw_cmdbuf_commit_cur(man, size, flush);
1011                 return;
1012         }
1013
1014         (void) vmw_cmdbuf_cur_lock(man, false);
1015         __vmw_cmdbuf_cur_flush(man);
1016         WARN_ON(size > header->reserved);
1017         man->cur = header;
1018         man->cur_pos = size;
1019         if (!size)
1020                 header->cb_header->flags &= ~SVGA_CB_FLAG_DX_CONTEXT;
1021         if (flush)
1022                 __vmw_cmdbuf_cur_flush(man);
1023         vmw_cmdbuf_cur_unlock(man);
1024 }
1025
1026 /**
1027  * vmw_cmdbuf_tasklet_schedule - Schedule the interrupt handler bottom half.
1028  *
1029  * @man: The command buffer manager.
1030  */
1031 void vmw_cmdbuf_tasklet_schedule(struct vmw_cmdbuf_man *man)
1032 {
1033         if (!man)
1034                 return;
1035
1036         tasklet_schedule(&man->tasklet);
1037 }
1038
1039 /**
1040  * vmw_cmdbuf_send_device_command - Send a command through the device context.
1041  *
1042  * @man: The command buffer manager.
1043  * @command: Pointer to the command to send.
1044  * @size: Size of the command.
1045  *
1046  * Synchronously sends a device context command.
1047  */
1048 static int vmw_cmdbuf_send_device_command(struct vmw_cmdbuf_man *man,
1049                                           const void *command,
1050                                           size_t size)
1051 {
1052         struct vmw_cmdbuf_header *header;
1053         int status;
1054         void *cmd = vmw_cmdbuf_alloc(man, size, false, &header);
1055
1056         if (IS_ERR(cmd))
1057                 return PTR_ERR(cmd);
1058
1059         memcpy(cmd, command, size);
1060         header->cb_header->length = size;
1061         header->cb_context = SVGA_CB_CONTEXT_DEVICE;
1062         spin_lock_bh(&man->lock);
1063         status = vmw_cmdbuf_header_submit(header);
1064         spin_unlock_bh(&man->lock);
1065         vmw_cmdbuf_header_free(header);
1066
1067         if (status != SVGA_CB_STATUS_COMPLETED) {
1068                 DRM_ERROR("Device context command failed with status %d\n",
1069                           status);
1070                 return -EINVAL;
1071         }
1072
1073         return 0;
1074 }
1075
1076 /**
1077  * vmw_cmdbuf_startstop - Send a start / stop command through the device
1078  * context.
1079  *
1080  * @man: The command buffer manager.
1081  * @enable: Whether to enable or disable the context.
1082  *
1083  * Synchronously sends a device start / stop context command.
1084  */
1085 static int vmw_cmdbuf_startstop(struct vmw_cmdbuf_man *man,
1086                                 bool enable)
1087 {
1088         struct {
1089                 uint32 id;
1090                 SVGADCCmdStartStop body;
1091         } __packed cmd;
1092
1093         cmd.id = SVGA_DC_CMD_START_STOP_CONTEXT;
1094         cmd.body.enable = (enable) ? 1 : 0;
1095         cmd.body.context = SVGA_CB_CONTEXT_0;
1096
1097         return vmw_cmdbuf_send_device_command(man, &cmd, sizeof(cmd));
1098 }
1099
1100 /**
1101  * vmw_cmdbuf_set_pool_size - Set command buffer manager sizes
1102  *
1103  * @man: The command buffer manager.
1104  * @size: The size of the main space pool.
1105  * @default_size: The default size of the command buffer for small kernel
1106  * submissions.
1107  *
1108  * Set the size and allocate the main command buffer space pool,
1109  * as well as the default size of the command buffer for
1110  * small kernel submissions. If successful, this enables large command
1111  * submissions. Note that this function requires that rudimentary command
1112  * submission is already available and that the MOB memory manager is alive.
1113  * Returns 0 on success. Negative error code on failure.
1114  */
1115 int vmw_cmdbuf_set_pool_size(struct vmw_cmdbuf_man *man,
1116                              size_t size, size_t default_size)
1117 {
1118         struct vmw_private *dev_priv = man->dev_priv;
1119         bool dummy;
1120         int ret;
1121
1122         if (man->has_pool)
1123                 return -EINVAL;
1124
1125         /* First, try to allocate a huge chunk of DMA memory */
1126         size = PAGE_ALIGN(size);
1127         man->map = dma_alloc_coherent(&dev_priv->dev->pdev->dev, size,
1128                                       &man->handle, GFP_KERNEL);
1129         if (man->map) {
1130                 man->using_mob = false;
1131         } else {
1132                 /*
1133                  * DMA memory failed. If we can have command buffers in a
1134                  * MOB, try to use that instead. Note that this will
1135                  * actually call into the already enabled manager, when
1136                  * binding the MOB.
1137                  */
1138                 if (!(dev_priv->capabilities & SVGA_CAP_CMD_BUFFERS_3))
1139                         return -ENOMEM;
1140
1141                 ret = ttm_bo_create(&dev_priv->bdev, size, ttm_bo_type_device,
1142                                     &vmw_mob_ne_placement, 0, false, NULL,
1143                                     &man->cmd_space);
1144                 if (ret)
1145                         return ret;
1146
1147                 man->using_mob = true;
1148                 ret = ttm_bo_kmap(man->cmd_space, 0, size >> PAGE_SHIFT,
1149                                   &man->map_obj);
1150                 if (ret)
1151                         goto out_no_map;
1152
1153                 man->map = ttm_kmap_obj_virtual(&man->map_obj, &dummy);
1154         }
1155
1156         man->size = size;
1157         drm_mm_init(&man->mm, 0, size >> PAGE_SHIFT);
1158
1159         man->has_pool = true;
1160         man->default_size = default_size;
1161         DRM_INFO("Using command buffers with %s pool.\n",
1162                  (man->using_mob) ? "MOB" : "DMA");
1163
1164         return 0;
1165
1166 out_no_map:
1167         if (man->using_mob)
1168                 ttm_bo_unref(&man->cmd_space);
1169
1170         return ret;
1171 }
1172
1173 /**
1174  * vmw_cmdbuf_man_create: Create a command buffer manager and enable it for
1175  * inline command buffer submissions only.
1176  *
1177  * @dev_priv: Pointer to device private structure.
1178  *
1179  * Returns a pointer to a cummand buffer manager to success or error pointer
1180  * on failure. The command buffer manager will be enabled for submissions of
1181  * size VMW_CMDBUF_INLINE_SIZE only.
1182  */
1183 struct vmw_cmdbuf_man *vmw_cmdbuf_man_create(struct vmw_private *dev_priv)
1184 {
1185         struct vmw_cmdbuf_man *man;
1186         struct vmw_cmdbuf_context *ctx;
1187         int i;
1188         int ret;
1189
1190         if (!(dev_priv->capabilities & SVGA_CAP_COMMAND_BUFFERS))
1191                 return ERR_PTR(-ENOSYS);
1192
1193         man = kzalloc(sizeof(*man), GFP_KERNEL);
1194         if (!man)
1195                 return ERR_PTR(-ENOMEM);
1196
1197         man->headers = dma_pool_create("vmwgfx cmdbuf",
1198                                        &dev_priv->dev->pdev->dev,
1199                                        sizeof(SVGACBHeader),
1200                                        64, PAGE_SIZE);
1201         if (!man->headers) {
1202                 ret = -ENOMEM;
1203                 goto out_no_pool;
1204         }
1205
1206         man->dheaders = dma_pool_create("vmwgfx inline cmdbuf",
1207                                         &dev_priv->dev->pdev->dev,
1208                                         sizeof(struct vmw_cmdbuf_dheader),
1209                                         64, PAGE_SIZE);
1210         if (!man->dheaders) {
1211                 ret = -ENOMEM;
1212                 goto out_no_dpool;
1213         }
1214
1215         for_each_cmdbuf_ctx(man, i, ctx)
1216                 vmw_cmdbuf_ctx_init(ctx);
1217
1218         INIT_LIST_HEAD(&man->error);
1219         spin_lock_init(&man->lock);
1220         mutex_init(&man->cur_mutex);
1221         mutex_init(&man->space_mutex);
1222         tasklet_init(&man->tasklet, vmw_cmdbuf_man_tasklet,
1223                      (unsigned long) man);
1224         man->default_size = VMW_CMDBUF_INLINE_SIZE;
1225         init_waitqueue_head(&man->alloc_queue);
1226         init_waitqueue_head(&man->idle_queue);
1227         man->dev_priv = dev_priv;
1228         man->max_hw_submitted = SVGA_CB_MAX_QUEUED_PER_CONTEXT - 1;
1229         INIT_WORK(&man->work, &vmw_cmdbuf_work_func);
1230         vmw_generic_waiter_add(dev_priv, SVGA_IRQFLAG_ERROR,
1231                                &dev_priv->error_waiters);
1232         ret = vmw_cmdbuf_startstop(man, true);
1233         if (ret) {
1234                 DRM_ERROR("Failed starting command buffer context 0.\n");
1235                 vmw_cmdbuf_man_destroy(man);
1236                 return ERR_PTR(ret);
1237         }
1238
1239         return man;
1240
1241 out_no_dpool:
1242         dma_pool_destroy(man->headers);
1243 out_no_pool:
1244         kfree(man);
1245
1246         return ERR_PTR(ret);
1247 }
1248
1249 /**
1250  * vmw_cmdbuf_remove_pool - Take down the main buffer space pool.
1251  *
1252  * @man: Pointer to a command buffer manager.
1253  *
1254  * This function removes the main buffer space pool, and should be called
1255  * before MOB memory management is removed. When this function has been called,
1256  * only small command buffer submissions of size VMW_CMDBUF_INLINE_SIZE or
1257  * less are allowed, and the default size of the command buffer for small kernel
1258  * submissions is also set to this size.
1259  */
1260 void vmw_cmdbuf_remove_pool(struct vmw_cmdbuf_man *man)
1261 {
1262         if (!man->has_pool)
1263                 return;
1264
1265         man->has_pool = false;
1266         man->default_size = VMW_CMDBUF_INLINE_SIZE;
1267         (void) vmw_cmdbuf_idle(man, false, 10*HZ);
1268         if (man->using_mob) {
1269                 (void) ttm_bo_kunmap(&man->map_obj);
1270                 ttm_bo_unref(&man->cmd_space);
1271         } else {
1272                 dma_free_coherent(&man->dev_priv->dev->pdev->dev,
1273                                   man->size, man->map, man->handle);
1274         }
1275 }
1276
1277 /**
1278  * vmw_cmdbuf_man_destroy - Take down a command buffer manager.
1279  *
1280  * @man: Pointer to a command buffer manager.
1281  *
1282  * This function idles and then destroys a command buffer manager.
1283  */
1284 void vmw_cmdbuf_man_destroy(struct vmw_cmdbuf_man *man)
1285 {
1286         WARN_ON_ONCE(man->has_pool);
1287         (void) vmw_cmdbuf_idle(man, false, 10*HZ);
1288         if (vmw_cmdbuf_startstop(man, false))
1289                 DRM_ERROR("Failed stopping command buffer context 0.\n");
1290
1291         vmw_generic_waiter_remove(man->dev_priv, SVGA_IRQFLAG_ERROR,
1292                                   &man->dev_priv->error_waiters);
1293         tasklet_kill(&man->tasklet);
1294         (void) cancel_work_sync(&man->work);
1295         dma_pool_destroy(man->dheaders);
1296         dma_pool_destroy(man->headers);
1297         mutex_destroy(&man->cur_mutex);
1298         mutex_destroy(&man->space_mutex);
1299         kfree(man);
1300 }