792014e62b4d3c88c1ecc052a4de120c25cace52
[model-checker.git] / threads.cc
1 #include "libthreads.h"
2 #include "common.h"
3 #include "threads.h"
4
5 /* global "model" object */
6 #include "model.h"
7
8 #define STACK_SIZE (1024 * 1024)
9
10 static void * stack_allocate(size_t size)
11 {
12         return malloc(size);
13 }
14
15 static void stack_free(void *stack)
16 {
17         free(stack);
18 }
19
20 Thread * thread_current(void)
21 {
22         ASSERT(model);
23         return model->scheduler->get_current_thread();
24 }
25
26 /**
27  * Provides a startup wrapper for each thread, allowing some initial
28  * model-checking data to be recorded. This method also gets around makecontext
29  * not being 64-bit clean
30  */
31 void thread_startup() {
32         Thread * curr_thread = thread_current();
33
34         /* TODO -- we should make this event always immediately follow the
35                  CREATE event, so we don't get redundant traces...  */
36
37         /* Add dummy "start" action, just to create a first clock vector */
38         model->switch_to_master(new ModelAction(THREAD_START, std::memory_order_seq_cst, curr_thread));
39
40         /* Call the actual thread function */
41         curr_thread->start_routine(curr_thread->arg);
42 }
43
44 int Thread::create_context()
45 {
46         int ret;
47
48         ret = getcontext(&context);
49         if (ret)
50                 return ret;
51
52         /* Initialize new managed context */
53         stack = stack_allocate(STACK_SIZE);
54         context.uc_stack.ss_sp = stack;
55         context.uc_stack.ss_size = STACK_SIZE;
56         context.uc_stack.ss_flags = 0;
57         context.uc_link = model->get_system_context();
58         makecontext(&context, thread_startup, 0);
59
60         return 0;
61 }
62
63 int Thread::swap(Thread *t, ucontext_t *ctxt)
64 {
65         return swapcontext(&t->context, ctxt);
66 }
67
68 int Thread::swap(ucontext_t *ctxt, Thread *t)
69 {
70         return swapcontext(ctxt, &t->context);
71 }
72
73 void Thread::complete()
74 {
75         if (state != THREAD_COMPLETED) {
76                 DEBUG("completed thread %d\n", get_id());
77                 state = THREAD_COMPLETED;
78                 if (stack)
79                         stack_free(stack);
80         }
81 }
82
83 Thread::Thread(thrd_t *t, void (*func)(void *), void *a) :
84         start_routine(func),
85         arg(a),
86         user_thread(t),
87         state(THREAD_CREATED),
88         last_action_val(VALUE_NONE)
89 {
90         int ret;
91
92         /* Initialize state */
93         ret = create_context();
94         if (ret)
95                 printf("Error in create_context\n");
96
97         id = model->get_next_id();
98         *user_thread = id;
99         parent = thread_current();
100 }
101
102 Thread::~Thread()
103 {
104         complete();
105         model->remove_thread(this);
106 }
107
108 thread_id_t Thread::get_id()
109 {
110         return id;
111 }