summaryrefslogtreecommitdiff
path: root/linux-core/drm_bo_lock2.c
blob: 73e58bc06b1e25df68657ba132cea793758df5b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include "drmP.h"

void drm_bo_init_lock(struct drm_bo_lock *lock)
{
	DRM_INIT_WAITQUEUE(&lock->queue);
	atomic_set(&lock->write_lock_pending, 0);
	atomic_set(&lock->readers, 0);
	
}

void drm_bo_read_unlock(struct drm_bo_lock *lock)
{
	if (unlikely(atomic_add_negative(-1, &lock->readers) == 0))
		BUG();
	if (atomic_read(&lock->readers) == 0)
		wake_up_interruptible(&lock->queue);
}

int drm_bo_read_lock(struct drm_bo_lock *lock)
{
	while( unlikely(atomic_read(&lock->write_lock_pending) != 0)) {
		int ret;
		ret = wait_event_interruptible
			(lock->queue, 
			 atomic_read(&lock->write_lock_pending) == 0);
		if (ret)
			return -EAGAIN;
	}

	while( unlikely (!atomic_add_unless(&lock->readers, 1, -1))) {
		int ret;
		ret = wait_event_interruptible
			(lock->queue, 
			 atomic_add_unless(&lock->readers, 1, -1));
		if (ret)
			return -EAGAIN;
	}
	return 0;
}
		
static int __drm_bo_write_unlock(struct drm_bo_lock *lock)
{
	if (unlikely(atomic_cmpxchg(&lock->readers, -1, 0) != -1))
		return -EINVAL;
	if (unlikely(atomic_cmpxchg(&lock->write_lock_pending, 1, 0) != 1))
		return -EINVAL;
	wake_up_interruptible(&lock->queue);
	return 0;
}

static void drm_bo_write_lock_remove(struct drm_file *file_priv, 
				     struct drm_user_object *item)
{
	struct drm_bo_lock *lock = 
		container_of(item, struct drm_bo_lock, base);
	int ret;

	ret = __drm_bo_write_unlock(lock);
	BUG_ON(ret);
}
		
int drm_bo_write_lock(struct drm_bo_lock *lock, struct drm_file *file_priv)
{
	int ret = 0;
	struct drm_device *dev;

	if (unlikely(atomic_cmpxchg(&lock->write_lock_pending, 0, 1) != 0)) 
		return -EINVAL;

	while(unlikely(atomic_cmpxchg(&lock->readers, 0, -1) != 0)) {
		ret = wait_event_interruptible
			(lock->queue,
			 atomic_cmpxchg(&lock->readers, 0, -1) == 0);

		if (ret) {
			atomic_set(&lock->write_lock_pending, 0);
			wake_up_interruptible(&lock->queue);
			return -EAGAIN;
		}
	}
	
	dev = file_priv->head->dev;
	mutex_lock(&dev->struct_mutex);
	ret = drm_add_user_object(file_priv, &lock->base, 0);
	lock->base.remove = &drm_bo_write_lock_remove;
	lock->base.type = drm_lock_type;
	if (ret) 
		(void) __drm_bo_write_unlock(lock);		
	mutex_unlock(&dev->struct_mutex);

	return ret;
}


int drm_bo_write_unlock(struct drm_bo_lock *lock, struct drm_file *file_priv)
{
	return drm_user_object_unref(file_priv, lock->base.hash.key, 
				     drm_lock_type);
}