summaryrefslogtreecommitdiff
path: root/src/monitor/monitor-thread.c
blob: 55b4bfeeb378e2639b20e5052e1a1dcc429c899f (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
100
101
/*
 * PASS (Power Aware System Service)
 *
 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <util/log.h>
#include <monitor/monitor.h>

#include <libsyscommon/resource-manager.h>

thread_local int empty_counter = 0;

static int monitor_func(void *data, void **result)
{
	struct monitor *monitor = data;
	struct monitor_command *cmd;

new_command:
	if (dequeue(monitor->q, (void *)&cmd) < 0) {
		if (empty_counter++ > MONITOR_POLLING_DURATION) {
			empty_counter = 0;
			mtx_lock(&monitor->lock);
			cnd_wait(&monitor->signal, &monitor->lock);
			mtx_unlock(&monitor->lock);
			goto new_command;
		}
		return THREAD_RETURN_CONTINUE;
	}

	syscommon_resman_update_resource_attrs(cmd->resource_id);

	cmd->done = true;
	smp_wmb();

	cnd_signal(&cmd->signal);

	return THREAD_RETURN_CONTINUE;
}

int monitor_thread_init(struct monitor *monitor)
{
	struct thread *thread;
	struct queue *queue;
	int ret;

	ret = create_queue(&queue, free);
	if (ret < 0) {
		_E("failed to create command queue\n");
		return ret;
	}

	/* q should be assigned before create daemon thread */
	monitor->q = queue;
	monitor->priv = NULL;
	mtx_init(&monitor->lock, mtx_plain);
	cnd_init(&monitor->signal);

	ret = create_daemon_thread(&thread, monitor_func, monitor);
	if (ret < 0) {
		_E("failed to create monitor thread\n");
		cnd_destroy(&monitor->signal);
		mtx_destroy(&monitor->lock);
		destroy_queue(queue);
		monitor->q = NULL;
		return ret;
	}

	monitor->thread = thread;

	return 0;
}

void monitor_thread_exit(struct monitor *monitor)
{
	if (monitor->thread) {
		cnd_signal(&monitor->signal);
		destroy_thread(monitor->thread);
		monitor->thread = NULL;
	}

	cnd_destroy(&monitor->signal);
	mtx_destroy(&monitor->lock);

	if (monitor->q) {
		destroy_queue(monitor->q);
		monitor->q = NULL;
	}
}