1 /*
2  * Copyright (c) 2019 Intel Corporation.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/device.h>
9 #include <zephyr/sys/libc-hooks.h>
10 #include <zephyr/logging/log.h>
11 
12 #include "sample_driver.h"
13 #include "app_shared.h"
14 #include "app_a.h"
15 #include "app_syscall.h"
16 
17 LOG_MODULE_REGISTER(app_a);
18 
19 #define MAX_MSGS	8
20 
21 /* Resource pool for allocations made by the kernel on behalf of system
22  * calls. Needed for k_queue_alloc_append()
23  */
24 K_HEAP_DEFINE(app_a_resource_pool, 256 * 5 + 128);
25 
26 /* Define app_a_partition, where all globals for this app will be routed.
27  * The partition starting address and size are populated by build system
28  * and linker magic.
29  */
30 K_APPMEM_PARTITION_DEFINE(app_a_partition);
31 
32 /* Memory domain for application A, set up and installed in app_a_entry() */
33 static struct k_mem_domain app_a_domain;
34 
35 /* Message queue for IPC between the driver callback and the monitor thread.
36  *
37  * This message queue is being statically initialized, no need to call
38  * k_msgq_init() on it.
39  */
40 K_MSGQ_DEFINE(mqueue, SAMPLE_DRIVER_MSG_SIZE, MAX_MSGS, 4);
41 
42 /* Processing thread. This takes data that has been processed by application
43  * B and writes it to the sample_driver, completing the control loop
44  */
45 struct k_thread writeback_thread;
46 K_THREAD_STACK_DEFINE(writeback_stack, 2048);
47 
48 /* Global data used by application A. By tagging with APP_A_BSS or APP_A_DATA,
49  * we ensure all this gets linked into the continuous region denoted by
50  * app_a_partition.
51  */
52 APP_A_BSS const struct device *sample_device;
53 APP_A_BSS unsigned int pending_count;
54 
55 /* ISR-level callback function. Runs in supervisor mode. Does what's needed
56  * to get the data into this application's accessible memory and have the
57  * worker thread running in user mode do the rest.
58  */
sample_callback(const struct device * dev,void * context,void * data)59 void sample_callback(const struct device *dev, void *context, void *data)
60 {
61 	int ret;
62 
63 	ARG_UNUSED(context);
64 
65 	LOG_DBG("sample callback with %p", data);
66 
67 	/* All the callback does is place the data payload into the
68 	 * message queue. This will wake up the monitor thread for further
69 	 * processing.
70 	 *
71 	 * We use a message queue because it will perform a data copy for us
72 	 * when buffering this data.
73 	 */
74 	ret = k_msgq_put(&mqueue, data, K_NO_WAIT);
75 	if (ret) {
76 		LOG_ERR("k_msgq_put failed with %d", ret);
77 	}
78 }
79 
monitor_entry(void * p1,void * p2,void * p3)80 static void monitor_entry(void *p1, void *p2, void *p3)
81 {
82 	int ret;
83 	void *payload;
84 	unsigned int monitor_count = 0;
85 
86 	ARG_UNUSED(p1);
87 	ARG_UNUSED(p2);
88 	ARG_UNUSED(p3);
89 
90 	/* Monitor thread, running in user mode. Responsible for pulling
91 	 * data out of the message queue for further writeback.
92 	 */
93 	LOG_DBG("monitor thread entered");
94 
95 	ret = sample_driver_state_set(sample_device, true);
96 	if (ret != 0) {
97 		LOG_ERR("couldn't start driver interrupts");
98 		k_oops();
99 	}
100 
101 	while (monitor_count < NUM_LOOPS) {
102 		payload = sys_heap_alloc(&shared_pool,
103 					 SAMPLE_DRIVER_MSG_SIZE);
104 		if (payload == NULL) {
105 			LOG_ERR("couldn't alloc memory from shared pool");
106 			k_oops();
107 			continue;
108 		}
109 
110 		/* Sleep waiting for some data to appear in the queue,
111 		 * and then copy it into the payload buffer.
112 		 */
113 		LOG_DBG("monitor thread waiting for data...");
114 		ret = k_msgq_get(&mqueue, payload, K_FOREVER);
115 		if (ret != 0) {
116 			LOG_ERR("k_msgq_get() failed with %d", ret);
117 			k_oops();
118 		}
119 
120 
121 		LOG_INF("monitor thread got data payload #%u", monitor_count);
122 		LOG_DBG("pending payloads: %u", pending_count);
123 
124 		/* Put the payload in the queue for data to process by
125 		 * app B. This does not copy the data. Because we are using
126 		 * k_queue from user mode, we need to use the
127 		 * k_queue_alloc_append() variant, which needs to allocate
128 		 * some memory on the kernel side from our thread
129 		 * resource pool.
130 		 */
131 		pending_count++;
132 		k_queue_alloc_append(&shared_queue_incoming, payload);
133 		monitor_count++;
134 	}
135 
136 	/* Tell the driver to stop delivering interrupts, we're closing up
137 	 * shop
138 	 */
139 	ret = sample_driver_state_set(sample_device, false);
140 	if (ret != 0) {
141 		LOG_ERR("couldn't disable driver");
142 		k_oops();
143 	}
144 	LOG_DBG("monitor thread exiting");
145 }
146 
writeback_entry(void * p1,void * p2,void * p3)147 static void writeback_entry(void *p1, void *p2, void *p3)
148 {
149 	void *data;
150 	unsigned int writeback_count = 0;
151 	int ret;
152 
153 	ARG_UNUSED(p1);
154 	ARG_UNUSED(p2);
155 	ARG_UNUSED(p3);
156 
157 	LOG_DBG("writeback thread entered");
158 
159 	while (writeback_count < NUM_LOOPS) {
160 		/* Grab a data payload processed by Application B,
161 		 * send it to the driver, and free the buffer.
162 		 */
163 		data = k_queue_get(&shared_queue_outgoing, K_FOREVER);
164 		if (data == NULL) {
165 			LOG_ERR("no data?");
166 			k_oops();
167 		}
168 
169 		LOG_INF("writing processed data back to the sample device");
170 		sample_driver_write(sample_device, data);
171 		sys_heap_free(&shared_pool, data);
172 		pending_count--;
173 		writeback_count++;
174 	}
175 
176 	/* Fairly meaningless example to show an application-defined system
177 	 * call being defined and used.
178 	 */
179 	ret = magic_syscall(&writeback_count);
180 	if (ret != 0) {
181 		LOG_ERR("no more magic!");
182 		k_oops();
183 	}
184 
185 	LOG_DBG("writeback thread exiting");
186 	LOG_INF("SUCCESS");
187 }
188 
189 /* Supervisor mode setup function for application A */
app_a_entry(void * p1,void * p2,void * p3)190 void app_a_entry(void *p1, void *p2, void *p3)
191 {
192 	int ret;
193 	struct k_mem_partition *parts[] = {
194 #if Z_LIBC_PARTITION_EXISTS
195 		&z_libc_partition,
196 #endif
197 		&app_a_partition, &shared_partition
198 	};
199 
200 	sample_device = device_get_binding(SAMPLE_DRIVER_NAME_0);
201 	if (sample_device == NULL) {
202 		LOG_ERR("bad sample device");
203 		k_oops();
204 	}
205 
206 	/* Initialize a memory domain with the specified partitions
207 	 * and add ourself to this domain. We need access to our own
208 	 * partition, the shared partition, and any common libc partition
209 	 * if it exists.
210 	 */
211 	ret = k_mem_domain_init(&app_a_domain, ARRAY_SIZE(parts), parts);
212 	__ASSERT(ret == 0, "k_mem_domain_init failed %d", ret);
213 	ARG_UNUSED(ret);
214 
215 	k_mem_domain_add_thread(&app_a_domain, k_current_get());
216 
217 	/* Assign a resource pool to serve for kernel-side allocations on
218 	 * behalf of application A. Needed for k_queue_alloc_append().
219 	 */
220 	k_thread_heap_assign(k_current_get(), &app_a_resource_pool);
221 
222 	/* Set the callback function for the sample driver. This has to be
223 	 * done from supervisor mode, as this code will run in supervisor
224 	 * mode in IRQ context.
225 	 */
226 	sample_driver_set_callback(sample_device, sample_callback, NULL);
227 
228 	/* Set up the writeback thread, which takes processed data from
229 	 * application B and sends it to the sample device.
230 	 *
231 	 * This child thread automatically inherits the memory domain of
232 	 * this thread that created it; it will be a member of app_a_domain.
233 	 *
234 	 * Initialize this thread with K_FOREVER timeout so we can
235 	 * modify its permissions and then start it.
236 	 */
237 	k_thread_create(&writeback_thread, writeback_stack,
238 			K_THREAD_STACK_SIZEOF(writeback_stack),
239 			writeback_entry, NULL, NULL, NULL,
240 			-1, K_USER, K_FOREVER);
241 	k_thread_access_grant(&writeback_thread, &shared_queue_outgoing,
242 			      sample_device);
243 	k_thread_start(&writeback_thread);
244 
245 	/* We are about to drop to user mode and become the monitor thread.
246 	 * Grant ourselves access to the kernel objects we need for
247 	 * the monitor thread to function.
248 	 *
249 	 * Monitor thread needs access to the message queue shared with the
250 	 * ISR, and the queue to send data to the processing thread in
251 	 * App B.
252 	 */
253 	k_thread_access_grant(k_current_get(), &mqueue, sample_device,
254 			      &shared_queue_incoming);
255 
256 	/* We now do a one-way transition to user mode, and will end up
257 	 * in monitor_thread(). We could create another thread which just
258 	 * starts in user mode, but this lets us re-use the current one.
259 	 */
260 	k_thread_user_mode_enter(monitor_entry, NULL, NULL, NULL);
261 }
262