~maresja1/+junk/helenos_qemu_porting

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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*
 * Copyright (c) 2006 Jakub Jermar
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 * - The name of the author may not be used to endorse or promote products
 *   derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/** @addtogroup libc
 * @{
 */
/** @file
 */

#include <thread.h>
#include <libc.h>
#include <stdlib.h>
#include <libarch/faddr.h>
#include <abi/proc/uarg.h>
#include <fibril.h>
#include <stack.h>
#include <str.h>
#include <async.h>
#include <errno.h>
#include <as.h>
#include <stdio.h>
#include "private/thread.h"
#include "../include/thread.h"
#include "../include/fibril_synch.h"

#ifdef FUTEX_UPGRADABLE
#include <rcu.h>
#endif
typedef enum{
    THREAD_JOINABLE,
    THREAD_EXITED,
    THREAD_DETACHED
} thread_state_t;

typedef struct{
    uspace_arg_t arg;
    thread_id_t id;
    fibril_mutex_t state_lock;
    fibril_condvar_t state_condvar;
    thread_retval_t retval;
    thread_state_t state;
    atomic_t ref_count;
} thread_internal_t;

static futex_t threads_protect = FUTEX_INITIALIZER;
static thread_internal_t **threads = NULL;

static void thread_del(thread_internal_t *thread);

static void thread_add(thread_internal_t *thread);

static thread_internal_t *thread_get(thread_id_t id);

static thread_internal_t *thread_alloc(void);

/** Main thread function.
 *
 * This function is called from __thread_entry() and is used
 * to call the thread's implementing function and perform cleanup
 * and exit when thread returns back.
 *
 * @param uarg Pointer to userspace argument structure.
 *
 */
void __thread_main(uspace_arg_t *uarg)
{
	fibril_t *fibril = fibril_setup();
	if (fibril == NULL)
		thread_exit(0);
	
	__tcb_set(fibril->tcb);
	
#ifdef FUTEX_UPGRADABLE
	rcu_register_fibril();
	futex_upgrade_all_and_wait();
#endif
	thread_retval_t retval = uarg->uspace_thread_function(uarg->uspace_thread_arg);
	/*
	 * XXX: we cannot free the userspace stack while running on it
	 *
	 * free(uarg->uspace_stack);
	 * free(uarg);
	 */
	
	/* If there is a manager, destroy it */
	async_destroy_manager();

#ifdef FUTEX_UPGRADABLE
	rcu_deregister_fibril();
#endif
	
//	fibril_teardown(fibril);
	
	thread_exit(retval);
}

/** Create userspace thread.
 *
 * This function creates new userspace thread and allocates userspace
 * stack and userspace argument structure for it.
 *
 * @param function Function implementing the thread.
 * @param arg Argument to be passed to thread.
 * @param name Symbolic name of the thread.
 * @param tid Thread ID of the newly created thread.
 *
 * @return Zero on success or a code from @ref errno.h on failure.
 */
int thread_create(void* (*function)(void *), void *arg, const char *name,
    thread_id_t *tid)
{
    thread_internal_t *thread = thread_alloc();
	if (!thread)
		return ENOMEM;

    uspace_arg_t *uarg = &thread->arg;


    size_t stack_size = stack_size_get();
	void *stack = as_area_create(AS_AREA_ANY, stack_size,
	    AS_AREA_READ | AS_AREA_WRITE | AS_AREA_CACHEABLE | AS_AREA_GUARD |
	    AS_AREA_LATE_RESERVE);
	if (stack == AS_MAP_FAILED) {
		free(uarg);
		return ENOMEM;
	}


	/* Make heap thread safe. */
	malloc_enable_multithreaded();
	
	uarg->uspace_entry = (void *) FADDR(__thread_entry);
	uarg->uspace_stack = stack;
	uarg->uspace_stack_size = stack_size;
	uarg->uspace_thread_function = function;
	uarg->uspace_thread_arg = arg;
	uarg->uspace_uarg = uarg;
	
	int rc = __SYSCALL4(SYS_THREAD_CREATE, (sysarg_t) uarg,
	    (sysarg_t) name, (sysarg_t) str_size(name), (sysarg_t) &thread->id);

    thread_add(thread);

    if (rc != EOK) {
		/*
		 * Failed to create a new thread.
		 * Free up the allocated data.
		 */
		as_area_destroy(stack);
		free(uarg);
	}

    if(tid){
        *tid = thread->id;
    }

	return rc;
}

thread_internal_t *thread_alloc(void) {
    thread_internal_t *thread = (thread_internal_t*)malloc(sizeof(thread_internal_t));
    if(thread){
        thread->state = THREAD_JOINABLE;
        atomic_set(&thread->ref_count,1);
        fibril_mutex_initialize(&thread->state_lock);
        fibril_condvar_initialize(&thread->state_condvar);
    }
    return thread;
}

void thread_add(thread_internal_t *thread)
{
    futex_down(&threads_protect);
        if(threads == NULL){
            threads = malloc(sizeof(thread_internal_t*)* THREAD_MAX);
        }
        threads[thread->id] = thread;
        fprintf(stdout, "Thread id: %"PRIu64" add to address:%p",thread->id,thread);
    futex_up(&threads_protect);
}

thread_internal_t *thread_get(thread_id_t id)
{
    thread_internal_t *ret;
    futex_down(&threads_protect);
        ret = threads[id];
    futex_up(&threads_protect);
    return ret;
}

void thread_del(thread_internal_t *thread)
{
    futex_down(&threads_protect);
        threads[thread->id] = NULL;
    fprintf(stdout, "Thread id: %"PRIu64" with address:%p deleted.",thread->id,thread);
    futex_up(&threads_protect);
}

static void thread_dealloc(thread_internal_t *thread)
{
    if(atomic_predec(&thread->ref_count)){
        return;
    }
    //TODO dealloc thread
}

/** Terminate current thread.
 *
 * @param status Exit status. Currently not used.
 *
 */
void thread_exit(thread_retval_t status)
{
    thread_id_t id = thread_get_id();
    fprintf(stdout, "Exit id:%"PRIu64"\n", id);
    thread_internal_t *thread = thread_get(id);
    fprintf(stdout, " of address:%p",thread);
    fprintf(stdout, " and id:%"PRIu64"\n", thread->id);

    fibril_mutex_lock(&thread->state_lock);
    if(thread->state == THREAD_JOINABLE){
        thread->state = THREAD_EXITED;
        thread->retval = status;
        fibril_condvar_broadcast(&thread->state_condvar);
    }
    fibril_mutex_unlock(&thread->state_lock);

//    fi
	__SYSCALL1(SYS_THREAD_EXIT, (sysarg_t) 0);

    thread_del(thread);
	/* Unreachable */
	while (1);
}


/** Detach thread.
 *
 * Currently not implemented.
 *
 * @param thread TID.
 */
int thread_detach(thread_id_t thread)
{
    return 0;
}

/** Join thread.
 *
 * Currently not implemented.
 *
 * @param thread TID.
 *
 * @return Thread exit status.
 */
int thread_join(thread_id_t thread_id, thread_retval_t *retval)
{
    fprintf(stdout, "Join to:%"PRIu64"\n", thread_id);
    int err = 0;
    thread_internal_t *thread = thread_get(thread_id);
    if(thread == NULL){
        return EINVAL;
    }


    fibril_mutex_lock(&thread->state_lock);
    fprintf(stdout, "*");
    /* Rely on pthread_cond_wait being a cancellation point to make
     pthread_join one too.  */
    while (thread->state == THREAD_JOINABLE){
        fibril_condvar_wait(&thread->state_condvar,&thread->state_lock);
        fprintf(stdout, "@");
    }


    switch (thread->state)
    {
        case THREAD_EXITED:
            /* THREAD has already exited.  Salvage its exit status.  */
            if (retval)
                *retval = thread->retval;

            fibril_mutex_unlock(&thread->state_lock);

            thread_dealloc(thread);
            break;

        default:
            /* Thou shalt not join non-joinable threads!  */
            fibril_mutex_unlock (&thread->state_lock);
            err = EINVAL;
            break;
    }

    fprintf(stderr, "Join end:%"PRIu64"\n", thread_id);
	return err;
}

/** Get current thread ID.
 *
 * @return Current thread ID.
 */
thread_id_t thread_get_id(void)
{
	thread_id_t thread_id;

	(void) __SYSCALL1(SYS_THREAD_GET_ID, (sysarg_t) &thread_id);
    fprintf(stdout, "Thread id:%"PRIu64"\n", thread_id);

	return thread_id;
}

/** @}
 */