summaryrefslogtreecommitdiffstats
path: root/include/libtf/fiber.h
blob: d5c615348d60796b28b3aff4410a4d797c0530a5 (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
/* fiber.h - libtf fiber manager header
 *
 * Copyright (C) 2009-2010 Timo Teräs <timo.teras@iki.fi>
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 or later as
 * published by the Free Software Foundation.
 *
 * See http://www.gnu.org/ for details.
 */

#ifndef TF_FIBER_H
#define TF_FIBER_H

#include <errno.h>
#include <libtf/defines.h>
#include <libtf/heap.h>

/* Fiber wakeup reasons */
#define TF_WAKEUP_NONE		0
#define TF_WAKEUP_IMMEDIATE	-EAGAIN
#define TF_WAKEUP_KILL		-EINTR
#define TF_WAKEUP_TIMEOUT	-ETIME
#define TF_WAKEUP_THIS_TIMEOUT	-ETIMEDOUT
#define TF_WAKEUP_FD		-EIO

/* Fiber management */
struct tf_scheduler;
typedef void (*tf_fiber_proc)(void *fiber);

void *__tf_fiber_create(tf_fiber_proc fiber_main, int private_size);
void *tf_fiber_create(tf_fiber_proc fiber_main, int private_size);
void *tf_fiber_get(void *data);
void tf_fiber_put(void *data);
void __tf_fiber_wakeup(void *data, int wakeup_type);
void __tf_fiber_wakeup_heapnode(struct tf_heap_node *node);
int  __tf_fiber_schedule(void);
int  __tf_fiber_bind_scheduler(struct tf_scheduler *sched);
int  __tf_fiber_release_scheduler(struct tf_scheduler *sched);

void tf_fiber_exit(void) attribute_noreturn;
void tf_fiber_kill(void *fiber);
int  tf_fiber_yield(void);

/* Scheduling and fiber management */
struct tf_timeout {
	tf_mtime_t	saved_timeout;
	unsigned int	timeout_change;
};

#define tf_timed(func, timeout)						\
	({								\
		struct tf_timeout __timeout;				\
		tf_timeout_push(&__timeout, timeout);			\
		tf_timeout_pop(&__timeout, (func));			\
	})

void tf_timeout_push(struct tf_timeout *timeout, tf_mtime_diff_t milliseconds);
int __tf_timeout_pop(struct tf_timeout *timeout, int err);

static inline int tf_timeout_pop(struct tf_timeout *timeout, int err)
{
	if (unlikely(timeout->timeout_change))
		return __tf_timeout_pop(timeout, err);
	return err;
}

static inline
int tf_msleep(tf_mtime_diff_t milliseconds)
{
	int r;
	r = tf_timed(__tf_fiber_schedule(), milliseconds);
	if (r == TF_WAKEUP_THIS_TIMEOUT)
		r = 0;
	return r;
}

#endif