1 /*
2  * Copyright (c) 2018 Intel Corporation
3  * Copyright (c) 2016 Wind River Systems, Inc.
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <kernel.h>
9 
z_work_user_q_main(void * work_q_ptr,void * p2,void * p3)10 static void z_work_user_q_main(void *work_q_ptr, void *p2, void *p3)
11 {
12 	struct k_work_user_q *work_q = work_q_ptr;
13 
14 	ARG_UNUSED(p2);
15 	ARG_UNUSED(p3);
16 
17 	while (true) {
18 		struct k_work_user *work;
19 		k_work_user_handler_t handler;
20 
21 		work = k_queue_get(&work_q->queue, K_FOREVER);
22 		if (work == NULL) {
23 			continue;
24 		}
25 
26 		handler = work->handler;
27 		__ASSERT(handler != NULL, "handler must be provided");
28 
29 		/* Reset pending state so it can be resubmitted by handler */
30 		if (atomic_test_and_clear_bit(&work->flags,
31 					      K_WORK_USER_STATE_PENDING)) {
32 			handler(work);
33 		}
34 
35 		/* Make sure we don't hog up the CPU if the FIFO never (or
36 		 * very rarely) gets empty.
37 		 */
38 		k_yield();
39 	}
40 }
41 
k_work_user_queue_start(struct k_work_user_q * work_q,k_thread_stack_t * stack,size_t stack_size,int prio,const char * name)42 void k_work_user_queue_start(struct k_work_user_q *work_q, k_thread_stack_t *stack,
43 			     size_t stack_size, int prio, const char *name)
44 {
45 	k_queue_init(&work_q->queue);
46 
47 	/* Created worker thread will inherit object permissions and memory
48 	 * domain configuration of the caller
49 	 */
50 	k_thread_create(&work_q->thread, stack, stack_size, z_work_user_q_main,
51 			work_q, NULL, NULL, prio, K_USER | K_INHERIT_PERMS,
52 			K_FOREVER);
53 	k_object_access_grant(&work_q->queue, &work_q->thread);
54 	if (name != NULL) {
55 		k_thread_name_set(&work_q->thread, name);
56 	}
57 
58 	k_thread_start(&work_q->thread);
59 }
60