blob: 0256af52958e8a45775431a9cb66e1d995afbcfb [file] [log] [blame]
rjw1f884582022-01-06 17:20:42 +08001/*
2 * Copyright (c) 2008 Travis Geiselbrecht
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files
6 * (the "Software"), to deal in the Software without restriction,
7 * including without limitation the rights to use, copy, modify, merge,
8 * publish, distribute, sublicense, and/or sell copies of the Software,
9 * and to permit persons to whom the Software is furnished to do so,
10 * subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23#include <debug.h>
24#include <stddef.h>
25#include <list.h>
26#include <malloc.h>
27#include <err.h>
28#include <lib/dpc.h>
29#include <kernel/thread.h>
30#include <kernel/event.h>
31#include <lk/init.h>
32
33struct dpc {
34 struct list_node node;
35
36 dpc_callback cb;
37 void *arg;
38};
39
40static struct list_node dpc_list = LIST_INITIAL_VALUE(dpc_list);
41static event_t dpc_event;
42
43static int dpc_thread_routine(void *arg);
44
45status_t dpc_queue(dpc_callback cb, void *arg, uint flags)
46{
47 struct dpc *dpc;
48
49 dpc = malloc(sizeof(struct dpc));
50
51 if (dpc == NULL)
52 return ERR_NO_MEMORY;
53
54 dpc->cb = cb;
55 dpc->arg = arg;
56 enter_critical_section();
57 list_add_tail(&dpc_list, &dpc->node);
58 event_signal(&dpc_event, (flags & DPC_FLAG_NORESCHED) ? false : true);
59 exit_critical_section();
60
61 return NO_ERROR;
62}
63
64static int dpc_thread_routine(void *arg)
65{
66 for (;;) {
67 event_wait(&dpc_event);
68
69 enter_critical_section();
70 struct dpc *dpc = list_remove_head_type(&dpc_list, struct dpc, node);
71 if (!dpc)
72 event_unsignal(&dpc_event);
73 exit_critical_section();
74
75 if (dpc) {
76// dprintf("dpc calling %p, arg %p\n", dpc->cb, dpc->arg);
77 dpc->cb(dpc->arg);
78
79 free(dpc);
80 }
81 }
82
83 return 0;
84}
85
86static void dpc_init(uint level)
87{
88 event_init(&dpc_event, false, 0);
89
90 thread_detach_and_resume(thread_create("dpc", &dpc_thread_routine, NULL, DPC_PRIORITY, DEFAULT_STACK_SIZE));
91}
92
93LK_INIT_HOOK(libdpc, &dpc_init, LK_INIT_LEVEL_THREADING);
94
95