summaryrefslogtreecommitdiff
path: root/kc/core/task.c
blob: a298a05d0466e95f753d64640e06e857fca2e6f7 (plain)
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
#include "task.h"
#include "timer.h"
#include "memory.h"
#include "panic.h"
#include "cpu.h"
#include "cpu/irq.h"
#include "cpu/mmu.h"
#include "pit8253.h"
#include "port.h"

#include <stdatomic.h>
#include <stdbool.h>

#include <lib/elf.h>
#include <libc/stdio.h>

#include "arch_thread.h"

static void lock_scheduler(void);
static void unlock_scheduler(void);
static void lock_preempt(void);
static void unlock_preempt(void);

static void update_time(void);

static struct kc_thread *create_thread(void *(*thread_f)(void *), void *p);
static void destroy_thread(struct kc_thread *thread);
static void set_thread(struct kc_thread *thread);
static void block_thread(enum kc_thread_status reason);
static void unblock_thread(struct kc_thread *thread);
static void sleep_thread(uint64_t nanoseconds);
static void sleep_thread_until(uint64_t nanoseconds);

static int sleeping_thread_callback(uint64_t nanoseconds);

const struct timer_source * timesource;

/* static threads that are always present
 * TODO: make this a per-CPU thing at some point
 */
static struct kc_thread *idle_thread;

// thread lists for the scheduler to manipulate
static struct kc_thread *current_thread;

struct thread_queue
{
	struct kc_thread
		*first,
		*last;
};

static void thread_queue_push(struct thread_queue *queue, struct kc_thread *thread);
static void thread_queue_push_back(struct thread_queue *queue, struct kc_thread *thread);

static void thread_queue_push(struct thread_queue *queue, struct kc_thread *thread)
{
	thread->next = queue->first;
	queue->first = thread;

	if (!queue->last) 
	{
		thread_queue_push_back(queue, thread);
	}
}

static void thread_queue_push_back(struct thread_queue *queue, struct kc_thread *thread)
{
	if (!queue->first)
	{
		thread_queue_push(queue, thread);
	}
	else if (queue->last)
	{
		queue->last->next = thread;
	}

	queue->last = thread;
}

struct kc_thread *thread_queue_pop(struct thread_queue *queue)
{
	if (!queue->first)
	{
		return nullptr;
	}

	struct kc_thread *thread = queue->first;
	queue->first = thread->next;
	thread->next = nullptr;
	if (!queue->first)
	{
		queue->last = nullptr;
	}

	return thread;
}

bool thread_queue_any(struct thread_queue queue)
{
	return queue.first && queue.last;
}

static struct thread_queue ready_queue;
static struct thread_queue sleep_queue;
static struct thread_queue wait_queue;

static volatile atomic_uint_fast64_t preempt_switch_count = 0;
static volatile atomic_bool preempt_switch_flag = false;

static void *idle_thread_entry(void *)
{
    printf("idle thread started\n");

	__asm__ ("sti");

    
    while (true)
    {
        __asm__ ("hlt;");
    }

	return nullptr;
}

static void *sleepy_thread_entry(void *p)
{
	uint64_t sleep_nanoseconds = (uint64_t)p;
    int thread_slept_count = 0;

    while (true)
    {
        sleep_thread(sleep_nanoseconds);
        thread_slept_count++;
		printf("thread slept %d times\n", thread_slept_count);
    }

    (void)thread_slept_count;
	return nullptr;
}



static uint64_t scheduler_flags;

static inline bool check_preempt_count()
{
	if (atomic_load(&preempt_switch_count) > 0)
	{
		return true;
	}

	return false;
}

void task_schedule(void)
{
	if(check_preempt_count())
	{
		preempt_switch_flag = true;
		return;
	}

	struct kc_thread *t = thread_queue_pop(&ready_queue);

	if (t == idle_thread)
	{
		thread_queue_push_back(&ready_queue, t);
		t = thread_queue_pop(&ready_queue);
	}

	if (t && current_thread->status != RUNNING)
	{
		set_thread(t);
	}
}

static void lock_scheduler(void)
{
    scheduler_flags = irq_lock();
}

static void lock_preempt(void)
{
    scheduler_flags = irq_lock();
    preempt_switch_count++;
}

static void unlock_scheduler(void)
{
    irq_unlock(scheduler_flags);
}

static void unlock_preempt(void)
{
    if (atomic_load(&preempt_switch_count) > 0)
    {
        preempt_switch_count--;
    }

    if (!atomic_load(&preempt_switch_count) && 
            atomic_load(&preempt_switch_flag))
    {
        preempt_switch_flag = false;
        task_schedule();
    }

    irq_unlock(scheduler_flags);
}

void update_time(void)
{
    static uint64_t last_elapsed = 0;
    if (current_thread)
    {
        uint64_t current_elapsed = timesource->nanoseconds_elapsed();
        uint64_t delta = current_elapsed - last_elapsed;
        last_elapsed = current_elapsed;
        current_thread->time_elapsed += delta;
    }
}

#define KC_THREAD_SIZE 0x3000

static struct kc_thread *create_thread(void *(*thread_f)(void *), void *p)
{
	void *buffer = vm_alloc(KC_THREAD_SIZE, VM_ALLOC_ANONYMOUS|VM_ALLOC_ANY); 
	memset(buffer, 0, KC_THREAD_SIZE);

	uintptr_t stack_head = (uintptr_t)buffer + KC_THREAD_SIZE;
	struct kc_thread *thread = (struct kc_thread *)(stack_head -= sizeof(*thread));

	thread->kernel_stack_head = (void *)stack_head;
	thread->kernel_stack_pointer = (void *)stack_head;
	thread->status = READY;

	arch_create_thread(thread, thread_f, p);

    return thread;
}

static void destroy_thread(struct kc_thread *thread)
{
    (void)thread;
}

static void set_thread(struct kc_thread *thread)
{
	if (thread == current_thread)
	{
		return;
	}

    if (atomic_load(&preempt_switch_count))
    {
        preempt_switch_flag = true;
        return;
    }

    update_time();
    struct kc_thread *previous_thread = current_thread;
    current_thread = thread;
    
    if (previous_thread->status == RUNNING)
    {
        previous_thread->status = READY;
        thread_queue_push(&ready_queue, previous_thread);
    }

    current_thread->status = RUNNING;
	arch_swap_thread(previous_thread, current_thread);
}

static void block_thread(enum kc_thread_status reason)
{
    lock_scheduler();
    current_thread->status = reason;
    task_schedule();
    unlock_scheduler();
}

static void unblock_thread(struct kc_thread *thread)
{
    lock_scheduler();

    thread->status = READY;

    if (!thread_queue_any(ready_queue) || (current_thread == idle_thread))
    {
        unlock_preempt();
        set_thread(thread);
    }
    else
    {
        thread_queue_push_back(&ready_queue, thread);
    }

    unlock_scheduler();
}

static void sleep_thread(uint64_t nanoseconds)
{
    sleep_thread_until(timesource->nanoseconds_elapsed() + nanoseconds);
}

static void sleep_thread_until(uint64_t nanoseconds)
{
    lock_preempt();

    if (nanoseconds < timesource->nanoseconds_elapsed())
    {
        unlock_scheduler();
        return;
    }

    current_thread->sleep_expiration = nanoseconds;
	
	thread_queue_push_back(&sleep_queue, current_thread);

    unlock_preempt();

    block_thread(SLEEPING);
}

static int sleeping_thread_callback(uint64_t timestamp)
{
    lock_preempt();

	struct thread_queue queue = sleep_queue;

	sleep_queue = (struct thread_queue){ nullptr, nullptr };

	{
		struct kc_thread *t;
		while((t = thread_queue_pop(&queue)) != nullptr)
		{
			if (t->sleep_expiration <= timestamp)
			{
				t->sleep_expiration = 0;
				unblock_thread(t);
			}
			else
			{
				thread_queue_push(&sleep_queue, t);
			}
		}
	}

	unlock_preempt();
	lock_scheduler();
	task_schedule();
	unlock_scheduler();

    return 0;
}

typedef void (locked_scheduler_action)(void *);

static void with_locked_scheduler(
		locked_scheduler_action *action,
		void *action_parameter)
{
	lock_scheduler();
	action(action_parameter);
	unlock_scheduler();
}

static void terminate_action(void *result)
{
	union kc_thread_result *result_value = result;
	current_thread->result = *result_value;
	current_thread->kernel_stack_pointer = current_thread->kernel_stack_head;

	struct thread_queue queue = wait_queue;
	
	lock_preempt();

	wait_queue = (struct thread_queue) { nullptr, nullptr };

	{
		struct kc_thread *t;
		while((t = thread_queue_pop(&queue)) != nullptr)
		{
			if (t->wait_target == current_thread)
			{
				t->wait_target = nullptr;
				t->status = READY;
				thread_queue_push_back(&ready_queue, t);
			}
			else
			{
				thread_queue_push(&wait_queue, t);
			}
		}
	}

	unlock_preempt();

	block_thread(TERMINATED);
}

void kct_terminate(union kc_thread_result result)
{
	with_locked_scheduler(terminate_action, &result);
}

union kc_thread_result kct_wait(struct kc_thread *target)
{
	current_thread->wait_target = target;
	thread_queue_push_back(&wait_queue, current_thread);
	block_thread(WAITING);
	return target->result;
}

static void *waited_thread_test(void *)
{
	printf("worker thread, sleeping for some time...\n");
	sleep_thread(30000000000);
	return (void *)1;
}

static void *waiting_thread_test(void *)
{
	printf("waiting thread\n");
	struct kc_thread *t = create_thread(waited_thread_test, nullptr);
	t->status = READY;
	thread_queue_push_back(&ready_queue, t);
	union kc_thread_result r = kct_wait(t);
	printf("waited thread terminated result: %d\n", r);
	return nullptr;
}

noreturn void task_init(void)
{
	struct kc_thread boot_thread;
	boot_thread.status = RUNNING;
	current_thread = &boot_thread;

    timesource = &pit8253_timer_source;
    timesource->append_callback(sleeping_thread_callback);
    timesource->start();
    printf(
            "starting task management, timesource delta %luns\n",
            timesource->nanoseconds_delta());

	idle_thread = create_thread(idle_thread_entry, nullptr);
	struct kc_thread *sleepy_thread = create_thread(sleepy_thread_entry, (void *)3000000000);
	struct kc_thread *sleepy_thread2 = create_thread(sleepy_thread_entry, (void *)5000000000);
	struct kc_thread *waiting_thread = create_thread(waiting_thread_test, nullptr);
	thread_queue_push(&ready_queue, sleepy_thread);
	thread_queue_push(&ready_queue, sleepy_thread2);
	thread_queue_push_back(&ready_queue, waiting_thread);
	__asm__ volatile ("movq %%rsp, %0" : "=g"(boot_thread.kernel_stack_pointer) :);
	thread_queue_push(&ready_queue, idle_thread);
	block_thread(BLOCKED);
    // shouldn't ever get here
	printf("the idle thread exited somehow. we're back in the boot thread. this is not good.\n");
    PANIC(DEAD_END);
}