1 /**************************************************************************
2  *
3  * Copyright © 2011 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 <drm/drmP.h>
29 #include "vmwgfx_drv.h"
30 
31 #define VMW_FENCE_WRAP (1 << 31)
32 
33 struct vmw_fence_manager {
34 	int num_fence_objects;
35 	struct vmw_private *dev_priv;
36 	spinlock_t lock;
37 	struct list_head fence_list;
38 	struct work_struct work, ping_work;
39 	u32 user_fence_size;
40 	u32 fence_size;
41 	u32 event_fence_action_size;
42 	bool fifo_down;
43 	struct list_head cleanup_list;
44 	uint32_t pending_actions[VMW_ACTION_MAX];
45 	struct mutex goal_irq_mutex;
46 	bool goal_irq_on; /* Protected by @goal_irq_mutex */
47 	bool seqno_valid; /* Protected by @lock, and may not be set to true
48 			     without the @goal_irq_mutex held. */
49 	unsigned ctx;
50 };
51 
52 struct vmw_user_fence {
53 	struct ttm_base_object base;
54 	struct vmw_fence_obj fence;
55 };
56 
57 /**
58  * struct vmw_event_fence_action - fence action that delivers a drm event.
59  *
60  * @e: A struct drm_pending_event that controls the event delivery.
61  * @action: A struct vmw_fence_action to hook up to a fence.
62  * @fence: A referenced pointer to the fence to keep it alive while @action
63  * hangs on it.
64  * @dev: Pointer to a struct drm_device so we can access the event stuff.
65  * @kref: Both @e and @action has destructors, so we need to refcount.
66  * @size: Size accounted for this object.
67  * @tv_sec: If non-null, the variable pointed to will be assigned
68  * current time tv_sec val when the fence signals.
69  * @tv_usec: Must be set if @tv_sec is set, and the variable pointed to will
70  * be assigned the current time tv_usec val when the fence signals.
71  */
72 struct vmw_event_fence_action {
73 	struct vmw_fence_action action;
74 	struct list_head fpriv_head;
75 
76 	struct drm_pending_event *event;
77 	struct vmw_fence_obj *fence;
78 	struct drm_device *dev;
79 
80 	uint32_t *tv_sec;
81 	uint32_t *tv_usec;
82 };
83 
84 static struct vmw_fence_manager *
85 fman_from_fence(struct vmw_fence_obj *fence)
86 {
87 	return container_of(fence->base.lock, struct vmw_fence_manager, lock);
88 }
89 
90 /**
91  * Note on fencing subsystem usage of irqs:
92  * Typically the vmw_fences_update function is called
93  *
94  * a) When a new fence seqno has been submitted by the fifo code.
95  * b) On-demand when we have waiters. Sleeping waiters will switch on the
96  * ANY_FENCE irq and call vmw_fences_update function each time an ANY_FENCE
97  * irq is received. When the last fence waiter is gone, that IRQ is masked
98  * away.
99  *
100  * In situations where there are no waiters and we don't submit any new fences,
101  * fence objects may not be signaled. This is perfectly OK, since there are
102  * no consumers of the signaled data, but that is NOT ok when there are fence
103  * actions attached to a fence. The fencing subsystem then makes use of the
104  * FENCE_GOAL irq and sets the fence goal seqno to that of the next fence
105  * which has an action attached, and each time vmw_fences_update is called,
106  * the subsystem makes sure the fence goal seqno is updated.
107  *
108  * The fence goal seqno irq is on as long as there are unsignaled fence
109  * objects with actions attached to them.
110  */
111 
112 static void vmw_fence_obj_destroy(struct fence *f)
113 {
114 	struct vmw_fence_obj *fence =
115 		container_of(f, struct vmw_fence_obj, base);
116 
117 	struct vmw_fence_manager *fman = fman_from_fence(fence);
118 	unsigned long irq_flags;
119 
120 	spin_lock_irqsave(&fman->lock, irq_flags);
121 	list_del_init(&fence->head);
122 	--fman->num_fence_objects;
123 	spin_unlock_irqrestore(&fman->lock, irq_flags);
124 	fence->destroy(fence);
125 }
126 
127 static const char *vmw_fence_get_driver_name(struct fence *f)
128 {
129 	return "vmwgfx";
130 }
131 
132 static const char *vmw_fence_get_timeline_name(struct fence *f)
133 {
134 	return "svga";
135 }
136 
137 static void vmw_fence_ping_func(struct work_struct *work)
138 {
139 	struct vmw_fence_manager *fman =
140 		container_of(work, struct vmw_fence_manager, ping_work);
141 
142 	vmw_fifo_ping_host(fman->dev_priv, SVGA_SYNC_GENERIC);
143 }
144 
145 static bool vmw_fence_enable_signaling(struct fence *f)
146 {
147 	struct vmw_fence_obj *fence =
148 		container_of(f, struct vmw_fence_obj, base);
149 
150 	struct vmw_fence_manager *fman = fman_from_fence(fence);
151 	struct vmw_private *dev_priv = fman->dev_priv;
152 
153 	__le32 __iomem *fifo_mem = dev_priv->mmio_virt;
154 	u32 seqno = ioread32(fifo_mem + SVGA_FIFO_FENCE);
155 	if (seqno - fence->base.seqno < VMW_FENCE_WRAP)
156 		return false;
157 
158 	if (mutex_trylock(&dev_priv->hw_mutex)) {
159 		vmw_fifo_ping_host_locked(dev_priv, SVGA_SYNC_GENERIC);
160 		mutex_unlock(&dev_priv->hw_mutex);
161 	} else
162 		schedule_work(&fman->ping_work);
163 
164 	return true;
165 }
166 
167 struct vmwgfx_wait_cb {
168 	struct fence_cb base;
169 	struct task_struct *task;
170 };
171 
172 static void
173 vmwgfx_wait_cb(struct fence *fence, struct fence_cb *cb)
174 {
175 	struct vmwgfx_wait_cb *wait =
176 		container_of(cb, struct vmwgfx_wait_cb, base);
177 
178 	wake_up_process(wait->task);
179 }
180 
181 static void __vmw_fences_update(struct vmw_fence_manager *fman);
182 
183 static long vmw_fence_wait(struct fence *f, bool intr, signed long timeout)
184 {
185 	struct vmw_fence_obj *fence =
186 		container_of(f, struct vmw_fence_obj, base);
187 
188 	struct vmw_fence_manager *fman = fman_from_fence(fence);
189 	struct vmw_private *dev_priv = fman->dev_priv;
190 	struct vmwgfx_wait_cb cb;
191 	long ret = timeout;
192 	unsigned long irq_flags;
193 
194 	if (likely(vmw_fence_obj_signaled(fence)))
195 		return timeout;
196 
197 	vmw_fifo_ping_host(dev_priv, SVGA_SYNC_GENERIC);
198 	vmw_seqno_waiter_add(dev_priv);
199 
200 	spin_lock_irqsave(f->lock, irq_flags);
201 
202 	if (intr && signal_pending(current)) {
203 		ret = -ERESTARTSYS;
204 		goto out;
205 	}
206 
207 	cb.base.func = vmwgfx_wait_cb;
208 	cb.task = current;
209 	list_add(&cb.base.node, &f->cb_list);
210 
211 	while (ret > 0) {
212 		__vmw_fences_update(fman);
213 		if (test_bit(FENCE_FLAG_SIGNALED_BIT, &f->flags))
214 			break;
215 
216 		if (intr)
217 			__set_current_state(TASK_INTERRUPTIBLE);
218 		else
219 			__set_current_state(TASK_UNINTERRUPTIBLE);
220 		spin_unlock_irqrestore(f->lock, irq_flags);
221 
222 		ret = schedule_timeout(ret);
223 
224 		spin_lock_irqsave(f->lock, irq_flags);
225 		if (ret > 0 && intr && signal_pending(current))
226 			ret = -ERESTARTSYS;
227 	}
228 
229 	if (!list_empty(&cb.base.node))
230 		list_del(&cb.base.node);
231 	__set_current_state(TASK_RUNNING);
232 
233 out:
234 	spin_unlock_irqrestore(f->lock, irq_flags);
235 
236 	vmw_seqno_waiter_remove(dev_priv);
237 
238 	return ret;
239 }
240 
241 static struct fence_ops vmw_fence_ops = {
242 	.get_driver_name = vmw_fence_get_driver_name,
243 	.get_timeline_name = vmw_fence_get_timeline_name,
244 	.enable_signaling = vmw_fence_enable_signaling,
245 	.wait = vmw_fence_wait,
246 	.release = vmw_fence_obj_destroy,
247 };
248 
249 
250 /**
251  * Execute signal actions on fences recently signaled.
252  * This is done from a workqueue so we don't have to execute
253  * signal actions from atomic context.
254  */
255 
256 static void vmw_fence_work_func(struct work_struct *work)
257 {
258 	struct vmw_fence_manager *fman =
259 		container_of(work, struct vmw_fence_manager, work);
260 	struct list_head list;
261 	struct vmw_fence_action *action, *next_action;
262 	bool seqno_valid;
263 
264 	do {
265 		INIT_LIST_HEAD(&list);
266 		mutex_lock(&fman->goal_irq_mutex);
267 
268 		spin_lock_irq(&fman->lock);
269 		list_splice_init(&fman->cleanup_list, &list);
270 		seqno_valid = fman->seqno_valid;
271 		spin_unlock_irq(&fman->lock);
272 
273 		if (!seqno_valid && fman->goal_irq_on) {
274 			fman->goal_irq_on = false;
275 			vmw_goal_waiter_remove(fman->dev_priv);
276 		}
277 		mutex_unlock(&fman->goal_irq_mutex);
278 
279 		if (list_empty(&list))
280 			return;
281 
282 		/*
283 		 * At this point, only we should be able to manipulate the
284 		 * list heads of the actions we have on the private list.
285 		 * hence fman::lock not held.
286 		 */
287 
288 		list_for_each_entry_safe(action, next_action, &list, head) {
289 			list_del_init(&action->head);
290 			if (action->cleanup)
291 				action->cleanup(action);
292 		}
293 	} while (1);
294 }
295 
296 struct vmw_fence_manager *vmw_fence_manager_init(struct vmw_private *dev_priv)
297 {
298 	struct vmw_fence_manager *fman = kzalloc(sizeof(*fman), GFP_KERNEL);
299 
300 	if (unlikely(fman == NULL))
301 		return NULL;
302 
303 	fman->dev_priv = dev_priv;
304 	spin_lock_init(&fman->lock);
305 	INIT_LIST_HEAD(&fman->fence_list);
306 	INIT_LIST_HEAD(&fman->cleanup_list);
307 	INIT_WORK(&fman->work, &vmw_fence_work_func);
308 	INIT_WORK(&fman->ping_work, &vmw_fence_ping_func);
309 	fman->fifo_down = true;
310 	fman->user_fence_size = ttm_round_pot(sizeof(struct vmw_user_fence));
311 	fman->fence_size = ttm_round_pot(sizeof(struct vmw_fence_obj));
312 	fman->event_fence_action_size =
313 		ttm_round_pot(sizeof(struct vmw_event_fence_action));
314 	mutex_init(&fman->goal_irq_mutex);
315 	fman->ctx = fence_context_alloc(1);
316 
317 	return fman;
318 }
319 
320 void vmw_fence_manager_takedown(struct vmw_fence_manager *fman)
321 {
322 	unsigned long irq_flags;
323 	bool lists_empty;
324 
325 	(void) cancel_work_sync(&fman->work);
326 	(void) cancel_work_sync(&fman->ping_work);
327 
328 	spin_lock_irqsave(&fman->lock, irq_flags);
329 	lists_empty = list_empty(&fman->fence_list) &&
330 		list_empty(&fman->cleanup_list);
331 	spin_unlock_irqrestore(&fman->lock, irq_flags);
332 
333 	BUG_ON(!lists_empty);
334 	kfree(fman);
335 }
336 
337 static int vmw_fence_obj_init(struct vmw_fence_manager *fman,
338 			      struct vmw_fence_obj *fence, u32 seqno,
339 			      void (*destroy) (struct vmw_fence_obj *fence))
340 {
341 	unsigned long irq_flags;
342 	int ret = 0;
343 
344 	fence_init(&fence->base, &vmw_fence_ops, &fman->lock,
345 		   fman->ctx, seqno);
346 	INIT_LIST_HEAD(&fence->seq_passed_actions);
347 	fence->destroy = destroy;
348 
349 	spin_lock_irqsave(&fman->lock, irq_flags);
350 	if (unlikely(fman->fifo_down)) {
351 		ret = -EBUSY;
352 		goto out_unlock;
353 	}
354 	list_add_tail(&fence->head, &fman->fence_list);
355 	++fman->num_fence_objects;
356 
357 out_unlock:
358 	spin_unlock_irqrestore(&fman->lock, irq_flags);
359 	return ret;
360 
361 }
362 
363 static void vmw_fences_perform_actions(struct vmw_fence_manager *fman,
364 				struct list_head *list)
365 {
366 	struct vmw_fence_action *action, *next_action;
367 
368 	list_for_each_entry_safe(action, next_action, list, head) {
369 		list_del_init(&action->head);
370 		fman->pending_actions[action->type]--;
371 		if (action->seq_passed != NULL)
372 			action->seq_passed(action);
373 
374 		/*
375 		 * Add the cleanup action to the cleanup list so that
376 		 * it will be performed by a worker task.
377 		 */
378 
379 		list_add_tail(&action->head, &fman->cleanup_list);
380 	}
381 }
382 
383 /**
384  * vmw_fence_goal_new_locked - Figure out a new device fence goal
385  * seqno if needed.
386  *
387  * @fman: Pointer to a fence manager.
388  * @passed_seqno: The seqno the device currently signals as passed.
389  *
390  * This function should be called with the fence manager lock held.
391  * It is typically called when we have a new passed_seqno, and
392  * we might need to update the fence goal. It checks to see whether
393  * the current fence goal has already passed, and, in that case,
394  * scans through all unsignaled fences to get the next fence object with an
395  * action attached, and sets the seqno of that fence as a new fence goal.
396  *
397  * returns true if the device goal seqno was updated. False otherwise.
398  */
399 static bool vmw_fence_goal_new_locked(struct vmw_fence_manager *fman,
400 				      u32 passed_seqno)
401 {
402 	u32 goal_seqno;
403 	__le32 __iomem *fifo_mem;
404 	struct vmw_fence_obj *fence;
405 
406 	if (likely(!fman->seqno_valid))
407 		return false;
408 
409 	fifo_mem = fman->dev_priv->mmio_virt;
410 	goal_seqno = ioread32(fifo_mem + SVGA_FIFO_FENCE_GOAL);
411 	if (likely(passed_seqno - goal_seqno >= VMW_FENCE_WRAP))
412 		return false;
413 
414 	fman->seqno_valid = false;
415 	list_for_each_entry(fence, &fman->fence_list, head) {
416 		if (!list_empty(&fence->seq_passed_actions)) {
417 			fman->seqno_valid = true;
418 			iowrite32(fence->base.seqno,
419 				  fifo_mem + SVGA_FIFO_FENCE_GOAL);
420 			break;
421 		}
422 	}
423 
424 	return true;
425 }
426 
427 
428 /**
429  * vmw_fence_goal_check_locked - Replace the device fence goal seqno if
430  * needed.
431  *
432  * @fence: Pointer to a struct vmw_fence_obj the seqno of which should be
433  * considered as a device fence goal.
434  *
435  * This function should be called with the fence manager lock held.
436  * It is typically called when an action has been attached to a fence to
437  * check whether the seqno of that fence should be used for a fence
438  * goal interrupt. This is typically needed if the current fence goal is
439  * invalid, or has a higher seqno than that of the current fence object.
440  *
441  * returns true if the device goal seqno was updated. False otherwise.
442  */
443 static bool vmw_fence_goal_check_locked(struct vmw_fence_obj *fence)
444 {
445 	struct vmw_fence_manager *fman = fman_from_fence(fence);
446 	u32 goal_seqno;
447 	__le32 __iomem *fifo_mem;
448 
449 	if (fence_is_signaled_locked(&fence->base))
450 		return false;
451 
452 	fifo_mem = fman->dev_priv->mmio_virt;
453 	goal_seqno = ioread32(fifo_mem + SVGA_FIFO_FENCE_GOAL);
454 	if (likely(fman->seqno_valid &&
455 		   goal_seqno - fence->base.seqno < VMW_FENCE_WRAP))
456 		return false;
457 
458 	iowrite32(fence->base.seqno, fifo_mem + SVGA_FIFO_FENCE_GOAL);
459 	fman->seqno_valid = true;
460 
461 	return true;
462 }
463 
464 static void __vmw_fences_update(struct vmw_fence_manager *fman)
465 {
466 	struct vmw_fence_obj *fence, *next_fence;
467 	struct list_head action_list;
468 	bool needs_rerun;
469 	uint32_t seqno, new_seqno;
470 	__le32 __iomem *fifo_mem = fman->dev_priv->mmio_virt;
471 
472 	seqno = ioread32(fifo_mem + SVGA_FIFO_FENCE);
473 rerun:
474 	list_for_each_entry_safe(fence, next_fence, &fman->fence_list, head) {
475 		if (seqno - fence->base.seqno < VMW_FENCE_WRAP) {
476 			list_del_init(&fence->head);
477 			fence_signal_locked(&fence->base);
478 			INIT_LIST_HEAD(&action_list);
479 			list_splice_init(&fence->seq_passed_actions,
480 					 &action_list);
481 			vmw_fences_perform_actions(fman, &action_list);
482 		} else
483 			break;
484 	}
485 
486 	/*
487 	 * Rerun if the fence goal seqno was updated, and the
488 	 * hardware might have raced with that update, so that
489 	 * we missed a fence_goal irq.
490 	 */
491 
492 	needs_rerun = vmw_fence_goal_new_locked(fman, seqno);
493 	if (unlikely(needs_rerun)) {
494 		new_seqno = ioread32(fifo_mem + SVGA_FIFO_FENCE);
495 		if (new_seqno != seqno) {
496 			seqno = new_seqno;
497 			goto rerun;
498 		}
499 	}
500 
501 	if (!list_empty(&fman->cleanup_list))
502 		(void) schedule_work(&fman->work);
503 }
504 
505 void vmw_fences_update(struct vmw_fence_manager *fman)
506 {
507 	unsigned long irq_flags;
508 
509 	spin_lock_irqsave(&fman->lock, irq_flags);
510 	__vmw_fences_update(fman);
511 	spin_unlock_irqrestore(&fman->lock, irq_flags);
512 }
513 
514 bool vmw_fence_obj_signaled(struct vmw_fence_obj *fence)
515 {
516 	struct vmw_fence_manager *fman = fman_from_fence(fence);
517 
518 	if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->base.flags))
519 		return 1;
520 
521 	vmw_fences_update(fman);
522 
523 	return fence_is_signaled(&fence->base);
524 }
525 
526 int vmw_fence_obj_wait(struct vmw_fence_obj *fence, bool lazy,
527 		       bool interruptible, unsigned long timeout)
528 {
529 	long ret = fence_wait_timeout(&fence->base, interruptible, timeout);
530 
531 	if (likely(ret > 0))
532 		return 0;
533 	else if (ret == 0)
534 		return -EBUSY;
535 	else
536 		return ret;
537 }
538 
539 void vmw_fence_obj_flush(struct vmw_fence_obj *fence)
540 {
541 	struct vmw_private *dev_priv = fman_from_fence(fence)->dev_priv;
542 
543 	vmw_fifo_ping_host(dev_priv, SVGA_SYNC_GENERIC);
544 }
545 
546 static void vmw_fence_destroy(struct vmw_fence_obj *fence)
547 {
548 	struct vmw_fence_manager *fman = fman_from_fence(fence);
549 
550 	fence_free(&fence->base);
551 
552 	/*
553 	 * Free kernel space accounting.
554 	 */
555 	ttm_mem_global_free(vmw_mem_glob(fman->dev_priv),
556 			    fman->fence_size);
557 }
558 
559 int vmw_fence_create(struct vmw_fence_manager *fman,
560 		     uint32_t seqno,
561 		     struct vmw_fence_obj **p_fence)
562 {
563 	struct ttm_mem_global *mem_glob = vmw_mem_glob(fman->dev_priv);
564 	struct vmw_fence_obj *fence;
565 	int ret;
566 
567 	ret = ttm_mem_global_alloc(mem_glob, fman->fence_size,
568 				   false, false);
569 	if (unlikely(ret != 0))
570 		return ret;
571 
572 	fence = kzalloc(sizeof(*fence), GFP_KERNEL);
573 	if (unlikely(fence == NULL)) {
574 		ret = -ENOMEM;
575 		goto out_no_object;
576 	}
577 
578 	ret = vmw_fence_obj_init(fman, fence, seqno,
579 				 vmw_fence_destroy);
580 	if (unlikely(ret != 0))
581 		goto out_err_init;
582 
583 	*p_fence = fence;
584 	return 0;
585 
586 out_err_init:
587 	kfree(fence);
588 out_no_object:
589 	ttm_mem_global_free(mem_glob, fman->fence_size);
590 	return ret;
591 }
592 
593 
594 static void vmw_user_fence_destroy(struct vmw_fence_obj *fence)
595 {
596 	struct vmw_user_fence *ufence =
597 		container_of(fence, struct vmw_user_fence, fence);
598 	struct vmw_fence_manager *fman = fman_from_fence(fence);
599 
600 	ttm_base_object_kfree(ufence, base);
601 	/*
602 	 * Free kernel space accounting.
603 	 */
604 	ttm_mem_global_free(vmw_mem_glob(fman->dev_priv),
605 			    fman->user_fence_size);
606 }
607 
608 static void vmw_user_fence_base_release(struct ttm_base_object **p_base)
609 {
610 	struct ttm_base_object *base = *p_base;
611 	struct vmw_user_fence *ufence =
612 		container_of(base, struct vmw_user_fence, base);
613 	struct vmw_fence_obj *fence = &ufence->fence;
614 
615 	*p_base = NULL;
616 	vmw_fence_obj_unreference(&fence);
617 }
618 
619 int vmw_user_fence_create(struct drm_file *file_priv,
620 			  struct vmw_fence_manager *fman,
621 			  uint32_t seqno,
622 			  struct vmw_fence_obj **p_fence,
623 			  uint32_t *p_handle)
624 {
625 	struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
626 	struct vmw_user_fence *ufence;
627 	struct vmw_fence_obj *tmp;
628 	struct ttm_mem_global *mem_glob = vmw_mem_glob(fman->dev_priv);
629 	int ret;
630 
631 	/*
632 	 * Kernel memory space accounting, since this object may
633 	 * be created by a user-space request.
634 	 */
635 
636 	ret = ttm_mem_global_alloc(mem_glob, fman->user_fence_size,
637 				   false, false);
638 	if (unlikely(ret != 0))
639 		return ret;
640 
641 	ufence = kzalloc(sizeof(*ufence), GFP_KERNEL);
642 	if (unlikely(ufence == NULL)) {
643 		ret = -ENOMEM;
644 		goto out_no_object;
645 	}
646 
647 	ret = vmw_fence_obj_init(fman, &ufence->fence, seqno,
648 				 vmw_user_fence_destroy);
649 	if (unlikely(ret != 0)) {
650 		kfree(ufence);
651 		goto out_no_object;
652 	}
653 
654 	/*
655 	 * The base object holds a reference which is freed in
656 	 * vmw_user_fence_base_release.
657 	 */
658 	tmp = vmw_fence_obj_reference(&ufence->fence);
659 	ret = ttm_base_object_init(tfile, &ufence->base, false,
660 				   VMW_RES_FENCE,
661 				   &vmw_user_fence_base_release, NULL);
662 
663 
664 	if (unlikely(ret != 0)) {
665 		/*
666 		 * Free the base object's reference
667 		 */
668 		vmw_fence_obj_unreference(&tmp);
669 		goto out_err;
670 	}
671 
672 	*p_fence = &ufence->fence;
673 	*p_handle = ufence->base.hash.key;
674 
675 	return 0;
676 out_err:
677 	tmp = &ufence->fence;
678 	vmw_fence_obj_unreference(&tmp);
679 out_no_object:
680 	ttm_mem_global_free(mem_glob, fman->user_fence_size);
681 	return ret;
682 }
683 
684 
685 /**
686  * vmw_fence_fifo_down - signal all unsignaled fence objects.
687  */
688 
689 void vmw_fence_fifo_down(struct vmw_fence_manager *fman)
690 {
691 	struct list_head action_list;
692 	int ret;
693 
694 	/*
695 	 * The list may be altered while we traverse it, so always
696 	 * restart when we've released the fman->lock.
697 	 */
698 
699 	spin_lock_irq(&fman->lock);
700 	fman->fifo_down = true;
701 	while (!list_empty(&fman->fence_list)) {
702 		struct vmw_fence_obj *fence =
703 			list_entry(fman->fence_list.prev, struct vmw_fence_obj,
704 				   head);
705 		fence_get(&fence->base);
706 		spin_unlock_irq(&fman->lock);
707 
708 		ret = vmw_fence_obj_wait(fence, false, false,
709 					 VMW_FENCE_WAIT_TIMEOUT);
710 
711 		if (unlikely(ret != 0)) {
712 			list_del_init(&fence->head);
713 			fence_signal(&fence->base);
714 			INIT_LIST_HEAD(&action_list);
715 			list_splice_init(&fence->seq_passed_actions,
716 					 &action_list);
717 			vmw_fences_perform_actions(fman, &action_list);
718 		}
719 
720 		BUG_ON(!list_empty(&fence->head));
721 		fence_put(&fence->base);
722 		spin_lock_irq(&fman->lock);
723 	}
724 	spin_unlock_irq(&fman->lock);
725 }
726 
727 void vmw_fence_fifo_up(struct vmw_fence_manager *fman)
728 {
729 	unsigned long irq_flags;
730 
731 	spin_lock_irqsave(&fman->lock, irq_flags);
732 	fman->fifo_down = false;
733 	spin_unlock_irqrestore(&fman->lock, irq_flags);
734 }
735 
736 
737 int vmw_fence_obj_wait_ioctl(struct drm_device *dev, void *data,
738 			     struct drm_file *file_priv)
739 {
740 	struct drm_vmw_fence_wait_arg *arg =
741 	    (struct drm_vmw_fence_wait_arg *)data;
742 	unsigned long timeout;
743 	struct ttm_base_object *base;
744 	struct vmw_fence_obj *fence;
745 	struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
746 	int ret;
747 	uint64_t wait_timeout = ((uint64_t)arg->timeout_us * HZ);
748 
749 	/*
750 	 * 64-bit division not present on 32-bit systems, so do an
751 	 * approximation. (Divide by 1000000).
752 	 */
753 
754 	wait_timeout = (wait_timeout >> 20) + (wait_timeout >> 24) -
755 	  (wait_timeout >> 26);
756 
757 	if (!arg->cookie_valid) {
758 		arg->cookie_valid = 1;
759 		arg->kernel_cookie = jiffies + wait_timeout;
760 	}
761 
762 	base = ttm_base_object_lookup(tfile, arg->handle);
763 	if (unlikely(base == NULL)) {
764 		printk(KERN_ERR "Wait invalid fence object handle "
765 		       "0x%08lx.\n",
766 		       (unsigned long)arg->handle);
767 		return -EINVAL;
768 	}
769 
770 	fence = &(container_of(base, struct vmw_user_fence, base)->fence);
771 
772 	timeout = jiffies;
773 	if (time_after_eq(timeout, (unsigned long)arg->kernel_cookie)) {
774 		ret = ((vmw_fence_obj_signaled(fence)) ?
775 		       0 : -EBUSY);
776 		goto out;
777 	}
778 
779 	timeout = (unsigned long)arg->kernel_cookie - timeout;
780 
781 	ret = vmw_fence_obj_wait(fence, arg->lazy, true, timeout);
782 
783 out:
784 	ttm_base_object_unref(&base);
785 
786 	/*
787 	 * Optionally unref the fence object.
788 	 */
789 
790 	if (ret == 0 && (arg->wait_options & DRM_VMW_WAIT_OPTION_UNREF))
791 		return ttm_ref_object_base_unref(tfile, arg->handle,
792 						 TTM_REF_USAGE);
793 	return ret;
794 }
795 
796 int vmw_fence_obj_signaled_ioctl(struct drm_device *dev, void *data,
797 				 struct drm_file *file_priv)
798 {
799 	struct drm_vmw_fence_signaled_arg *arg =
800 		(struct drm_vmw_fence_signaled_arg *) data;
801 	struct ttm_base_object *base;
802 	struct vmw_fence_obj *fence;
803 	struct vmw_fence_manager *fman;
804 	struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile;
805 	struct vmw_private *dev_priv = vmw_priv(dev);
806 
807 	base = ttm_base_object_lookup(tfile, arg->handle);
808 	if (unlikely(base == NULL)) {
809 		printk(KERN_ERR "Fence signaled invalid fence object handle "
810 		       "0x%08lx.\n",
811 		       (unsigned long)arg->handle);
812 		return -EINVAL;
813 	}
814 
815 	fence = &(container_of(base, struct vmw_user_fence, base)->fence);
816 	fman = fman_from_fence(fence);
817 
818 	arg->signaled = vmw_fence_obj_signaled(fence);
819 
820 	arg->signaled_flags = arg->flags;
821 	spin_lock_irq(&fman->lock);
822 	arg->passed_seqno = dev_priv->last_read_seqno;
823 	spin_unlock_irq(&fman->lock);
824 
825 	ttm_base_object_unref(&base);
826 
827 	return 0;
828 }
829 
830 
831 int vmw_fence_obj_unref_ioctl(struct drm_device *dev, void *data,
832 			      struct drm_file *file_priv)
833 {
834 	struct drm_vmw_fence_arg *arg =
835 		(struct drm_vmw_fence_arg *) data;
836 
837 	return ttm_ref_object_base_unref(vmw_fpriv(file_priv)->tfile,
838 					 arg->handle,
839 					 TTM_REF_USAGE);
840 }
841 
842 /**
843  * vmw_event_fence_fpriv_gone - Remove references to struct drm_file objects
844  *
845  * @fman: Pointer to a struct vmw_fence_manager
846  * @event_list: Pointer to linked list of struct vmw_event_fence_action objects
847  * with pointers to a struct drm_file object about to be closed.
848  *
849  * This function removes all pending fence events with references to a
850  * specific struct drm_file object about to be closed. The caller is required
851  * to pass a list of all struct vmw_event_fence_action objects with such
852  * events attached. This function is typically called before the
853  * struct drm_file object's event management is taken down.
854  */
855 void vmw_event_fence_fpriv_gone(struct vmw_fence_manager *fman,
856 				struct list_head *event_list)
857 {
858 	struct vmw_event_fence_action *eaction;
859 	struct drm_pending_event *event;
860 	unsigned long irq_flags;
861 
862 	while (1) {
863 		spin_lock_irqsave(&fman->lock, irq_flags);
864 		if (list_empty(event_list))
865 			goto out_unlock;
866 		eaction = list_first_entry(event_list,
867 					   struct vmw_event_fence_action,
868 					   fpriv_head);
869 		list_del_init(&eaction->fpriv_head);
870 		event = eaction->event;
871 		eaction->event = NULL;
872 		spin_unlock_irqrestore(&fman->lock, irq_flags);
873 		event->destroy(event);
874 	}
875 out_unlock:
876 	spin_unlock_irqrestore(&fman->lock, irq_flags);
877 }
878 
879 
880 /**
881  * vmw_event_fence_action_seq_passed
882  *
883  * @action: The struct vmw_fence_action embedded in a struct
884  * vmw_event_fence_action.
885  *
886  * This function is called when the seqno of the fence where @action is
887  * attached has passed. It queues the event on the submitter's event list.
888  * This function is always called from atomic context, and may be called
889  * from irq context.
890  */
891 static void vmw_event_fence_action_seq_passed(struct vmw_fence_action *action)
892 {
893 	struct vmw_event_fence_action *eaction =
894 		container_of(action, struct vmw_event_fence_action, action);
895 	struct drm_device *dev = eaction->dev;
896 	struct drm_pending_event *event = eaction->event;
897 	struct drm_file *file_priv;
898 	unsigned long irq_flags;
899 
900 	if (unlikely(event == NULL))
901 		return;
902 
903 	file_priv = event->file_priv;
904 	spin_lock_irqsave(&dev->event_lock, irq_flags);
905 
906 	if (likely(eaction->tv_sec != NULL)) {
907 		struct timeval tv;
908 
909 		do_gettimeofday(&tv);
910 		*eaction->tv_sec = tv.tv_sec;
911 		*eaction->tv_usec = tv.tv_usec;
912 	}
913 
914 	list_del_init(&eaction->fpriv_head);
915 	list_add_tail(&eaction->event->link, &file_priv->event_list);
916 	eaction->event = NULL;
917 	wake_up_all(&file_priv->event_wait);
918 	spin_unlock_irqrestore(&dev->event_lock, irq_flags);
919 }
920 
921 /**
922  * vmw_event_fence_action_cleanup
923  *
924  * @action: The struct vmw_fence_action embedded in a struct
925  * vmw_event_fence_action.
926  *
927  * This function is the struct vmw_fence_action destructor. It's typically
928  * called from a workqueue.
929  */
930 static void vmw_event_fence_action_cleanup(struct vmw_fence_action *action)
931 {
932 	struct vmw_event_fence_action *eaction =
933 		container_of(action, struct vmw_event_fence_action, action);
934 	struct vmw_fence_manager *fman = fman_from_fence(eaction->fence);
935 	unsigned long irq_flags;
936 
937 	spin_lock_irqsave(&fman->lock, irq_flags);
938 	list_del(&eaction->fpriv_head);
939 	spin_unlock_irqrestore(&fman->lock, irq_flags);
940 
941 	vmw_fence_obj_unreference(&eaction->fence);
942 	kfree(eaction);
943 }
944 
945 
946 /**
947  * vmw_fence_obj_add_action - Add an action to a fence object.
948  *
949  * @fence - The fence object.
950  * @action - The action to add.
951  *
952  * Note that the action callbacks may be executed before this function
953  * returns.
954  */
955 static void vmw_fence_obj_add_action(struct vmw_fence_obj *fence,
956 			      struct vmw_fence_action *action)
957 {
958 	struct vmw_fence_manager *fman = fman_from_fence(fence);
959 	unsigned long irq_flags;
960 	bool run_update = false;
961 
962 	mutex_lock(&fman->goal_irq_mutex);
963 	spin_lock_irqsave(&fman->lock, irq_flags);
964 
965 	fman->pending_actions[action->type]++;
966 	if (fence_is_signaled_locked(&fence->base)) {
967 		struct list_head action_list;
968 
969 		INIT_LIST_HEAD(&action_list);
970 		list_add_tail(&action->head, &action_list);
971 		vmw_fences_perform_actions(fman, &action_list);
972 	} else {
973 		list_add_tail(&action->head, &fence->seq_passed_actions);
974 
975 		/*
976 		 * This function may set fman::seqno_valid, so it must
977 		 * be run with the goal_irq_mutex held.
978 		 */
979 		run_update = vmw_fence_goal_check_locked(fence);
980 	}
981 
982 	spin_unlock_irqrestore(&fman->lock, irq_flags);
983 
984 	if (run_update) {
985 		if (!fman->goal_irq_on) {
986 			fman->goal_irq_on = true;
987 			vmw_goal_waiter_add(fman->dev_priv);
988 		}
989 		vmw_fences_update(fman);
990 	}
991 	mutex_unlock(&fman->goal_irq_mutex);
992 
993 }
994 
995 /**
996  * vmw_event_fence_action_create - Post an event for sending when a fence
997  * object seqno has passed.
998  *
999  * @file_priv: The file connection on which the event should be posted.
1000  * @fence: The fence object on which to post the event.
1001  * @event: Event to be posted. This event should've been alloced
1002  * using k[mz]alloc, and should've been completely initialized.
1003  * @interruptible: Interruptible waits if possible.
1004  *
1005  * As a side effect, the object pointed to by @event may have been
1006  * freed when this function returns. If this function returns with
1007  * an error code, the caller needs to free that object.
1008  */
1009 
1010 int vmw_event_fence_action_queue(struct drm_file *file_priv,
1011 				 struct vmw_fence_obj *fence,
1012 				 struct drm_pending_event *event,
1013 				 uint32_t *tv_sec,
1014 				 uint32_t *tv_usec,
1015 				 bool interruptible)
1016 {
1017 	struct vmw_event_fence_action *eaction;
1018 	struct vmw_fence_manager *fman = fman_from_fence(fence);
1019 	struct vmw_fpriv *vmw_fp = vmw_fpriv(file_priv);
1020 	unsigned long irq_flags;
1021 
1022 	eaction = kzalloc(sizeof(*eaction), GFP_KERNEL);
1023 	if (unlikely(eaction == NULL))
1024 		return -ENOMEM;
1025 
1026 	eaction->event = event;
1027 
1028 	eaction->action.seq_passed = vmw_event_fence_action_seq_passed;
1029 	eaction->action.cleanup = vmw_event_fence_action_cleanup;
1030 	eaction->action.type = VMW_ACTION_EVENT;
1031 
1032 	eaction->fence = vmw_fence_obj_reference(fence);
1033 	eaction->dev = fman->dev_priv->dev;
1034 	eaction->tv_sec = tv_sec;
1035 	eaction->tv_usec = tv_usec;
1036 
1037 	spin_lock_irqsave(&fman->lock, irq_flags);
1038 	list_add_tail(&eaction->fpriv_head, &vmw_fp->fence_events);
1039 	spin_unlock_irqrestore(&fman->lock, irq_flags);
1040 
1041 	vmw_fence_obj_add_action(fence, &eaction->action);
1042 
1043 	return 0;
1044 }
1045 
1046 struct vmw_event_fence_pending {
1047 	struct drm_pending_event base;
1048 	struct drm_vmw_event_fence event;
1049 };
1050 
1051 static int vmw_event_fence_action_create(struct drm_file *file_priv,
1052 				  struct vmw_fence_obj *fence,
1053 				  uint32_t flags,
1054 				  uint64_t user_data,
1055 				  bool interruptible)
1056 {
1057 	struct vmw_event_fence_pending *event;
1058 	struct vmw_fence_manager *fman = fman_from_fence(fence);
1059 	struct drm_device *dev = fman->dev_priv->dev;
1060 	unsigned long irq_flags;
1061 	int ret;
1062 
1063 	spin_lock_irqsave(&dev->event_lock, irq_flags);
1064 
1065 	ret = (file_priv->event_space < sizeof(event->event)) ? -EBUSY : 0;
1066 	if (likely(ret == 0))
1067 		file_priv->event_space -= sizeof(event->event);
1068 
1069 	spin_unlock_irqrestore(&dev->event_lock, irq_flags);
1070 
1071 	if (unlikely(ret != 0)) {
1072 		DRM_ERROR("Failed to allocate event space for this file.\n");
1073 		goto out_no_space;
1074 	}
1075 
1076 
1077 	event = kzalloc(sizeof(*event), GFP_KERNEL);
1078 	if (unlikely(event == NULL)) {
1079 		DRM_ERROR("Failed to allocate an event.\n");
1080 		ret = -ENOMEM;
1081 		goto out_no_event;
1082 	}
1083 
1084 	event->event.base.type = DRM_VMW_EVENT_FENCE_SIGNALED;
1085 	event->event.base.length = sizeof(*event);
1086 	event->event.user_data = user_data;
1087 
1088 	event->base.event = &event->event.base;
1089 	event->base.file_priv = file_priv;
1090 	event->base.destroy = (void (*) (struct drm_pending_event *)) kfree;
1091 
1092 
1093 	if (flags & DRM_VMW_FE_FLAG_REQ_TIME)
1094 		ret = vmw_event_fence_action_queue(file_priv, fence,
1095 						   &event->base,
1096 						   &event->event.tv_sec,
1097 						   &event->event.tv_usec,
1098 						   interruptible);
1099 	else
1100 		ret = vmw_event_fence_action_queue(file_priv, fence,
1101 						   &event->base,
1102 						   NULL,
1103 						   NULL,
1104 						   interruptible);
1105 	if (ret != 0)
1106 		goto out_no_queue;
1107 
1108 out_no_queue:
1109 	event->base.destroy(&event->base);
1110 out_no_event:
1111 	spin_lock_irqsave(&dev->event_lock, irq_flags);
1112 	file_priv->event_space += sizeof(*event);
1113 	spin_unlock_irqrestore(&dev->event_lock, irq_flags);
1114 out_no_space:
1115 	return ret;
1116 }
1117 
1118 int vmw_fence_event_ioctl(struct drm_device *dev, void *data,
1119 			  struct drm_file *file_priv)
1120 {
1121 	struct vmw_private *dev_priv = vmw_priv(dev);
1122 	struct drm_vmw_fence_event_arg *arg =
1123 		(struct drm_vmw_fence_event_arg *) data;
1124 	struct vmw_fence_obj *fence = NULL;
1125 	struct vmw_fpriv *vmw_fp = vmw_fpriv(file_priv);
1126 	struct drm_vmw_fence_rep __user *user_fence_rep =
1127 		(struct drm_vmw_fence_rep __user *)(unsigned long)
1128 		arg->fence_rep;
1129 	uint32_t handle;
1130 	int ret;
1131 
1132 	/*
1133 	 * Look up an existing fence object,
1134 	 * and if user-space wants a new reference,
1135 	 * add one.
1136 	 */
1137 	if (arg->handle) {
1138 		struct ttm_base_object *base =
1139 			ttm_base_object_lookup_for_ref(dev_priv->tdev,
1140 						       arg->handle);
1141 
1142 		if (unlikely(base == NULL)) {
1143 			DRM_ERROR("Fence event invalid fence object handle "
1144 				  "0x%08lx.\n",
1145 				  (unsigned long)arg->handle);
1146 			return -EINVAL;
1147 		}
1148 		fence = &(container_of(base, struct vmw_user_fence,
1149 				       base)->fence);
1150 		(void) vmw_fence_obj_reference(fence);
1151 
1152 		if (user_fence_rep != NULL) {
1153 			bool existed;
1154 
1155 			ret = ttm_ref_object_add(vmw_fp->tfile, base,
1156 						 TTM_REF_USAGE, &existed);
1157 			if (unlikely(ret != 0)) {
1158 				DRM_ERROR("Failed to reference a fence "
1159 					  "object.\n");
1160 				goto out_no_ref_obj;
1161 			}
1162 			handle = base->hash.key;
1163 		}
1164 		ttm_base_object_unref(&base);
1165 	}
1166 
1167 	/*
1168 	 * Create a new fence object.
1169 	 */
1170 	if (!fence) {
1171 		ret = vmw_execbuf_fence_commands(file_priv, dev_priv,
1172 						 &fence,
1173 						 (user_fence_rep) ?
1174 						 &handle : NULL);
1175 		if (unlikely(ret != 0)) {
1176 			DRM_ERROR("Fence event failed to create fence.\n");
1177 			return ret;
1178 		}
1179 	}
1180 
1181 	BUG_ON(fence == NULL);
1182 
1183 	if (arg->flags & DRM_VMW_FE_FLAG_REQ_TIME)
1184 		ret = vmw_event_fence_action_create(file_priv, fence,
1185 						    arg->flags,
1186 						    arg->user_data,
1187 						    true);
1188 	else
1189 		ret = vmw_event_fence_action_create(file_priv, fence,
1190 						    arg->flags,
1191 						    arg->user_data,
1192 						    true);
1193 
1194 	if (unlikely(ret != 0)) {
1195 		if (ret != -ERESTARTSYS)
1196 			DRM_ERROR("Failed to attach event to fence.\n");
1197 		goto out_no_create;
1198 	}
1199 
1200 	vmw_execbuf_copy_fence_user(dev_priv, vmw_fp, 0, user_fence_rep, fence,
1201 				    handle);
1202 	vmw_fence_obj_unreference(&fence);
1203 	return 0;
1204 out_no_create:
1205 	if (user_fence_rep != NULL)
1206 		ttm_ref_object_base_unref(vmw_fpriv(file_priv)->tfile,
1207 					  handle, TTM_REF_USAGE);
1208 out_no_ref_obj:
1209 	vmw_fence_obj_unreference(&fence);
1210 	return ret;
1211 }
1212