aboutsummaryrefslogtreecommitdiffstats
path: root/package/libs/libnl-tiny/src/genl.c
blob: 055be919e1d35d71b0ce69f1880b2b1cfb5ec89b (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
/*
 * lib/genl/genl.c		Generic Netlink
 *
 *	This library is free software; you can redistribute it and/or
 *	modify it under the terms of the GNU Lesser General Public
 *	License as published by the Free Software Foundation version 2.1
 *	of the License.
 *
 * Copyright (c) 2003-2008 Thomas Graf <tgraf@suug.ch>
 */

/**
 * @defgroup genl Generic Netlink
 *
 * @par Message Format
 * @code
 *  <------- NLMSG_ALIGN(hlen) ------> <---- NLMSG_ALIGN(len) --->
 * +----------------------------+- - -+- - - - - - - - - - -+- - -+
 * |           Header           | Pad |       Payload       | Pad |
 * |      struct nlmsghdr       |     |                     |     |
 * +----------------------------+- - -+- - - - - - - - - - -+- - -+
 * @endcode
 * @code
 *  <-------- GENL_HDRLEN -------> <--- hdrlen -->
 *                                 <------- genlmsg_len(ghdr) ------>
 * +------------------------+- - -+---------------+- - -+------------+
 * | Generic Netlink Header | Pad | Family Header | Pad | Attributes |
 * |    struct genlmsghdr   |     |               |     |            |
 * +------------------------+- - -+---------------+- - -+------------+
 * genlmsg_data(ghdr)--------------^                     ^
 * genlmsg_attrdata(ghdr, hdrlen)-------------------------
 * @endcode
 *
 * @par Example
 * @code
 * #include <netlink/netlink.h>
 * #include <netlink/genl/genl.h>
 * #include <netlink/genl/ctrl.h>
 *
 * struct nl_sock *sock;
 * struct nl_msg *msg;
 * int family;
 *
 * // Allocate a new netlink socket
 * sock = nl_socket_alloc();
 *
 * // Connect to generic netlink socket on kernel side
 * genl_connect(sock);
 *
 * // Ask kernel to resolve family name to family id
 * family = genl_ctrl_resolve(sock, "generic_netlink_family_name");
 *
 * // Construct a generic netlink by allocating a new message, fill in
 * // the header and append a simple integer attribute.
 * msg = nlmsg_alloc();
 * genlmsg_put(msg, NL_AUTO_PID, NL_AUTO_SEQ, family, 0, NLM_F_ECHO,
 *             CMD_FOO_GET, FOO_VERSION);
 * nla_put_u32(msg, ATTR_FOO, 123);
 *
 * // Send message over netlink socket
 * nl_send_auto_complete(sock, msg);
 *
 * // Free message
 * nlmsg_free(msg);
 *
 * // Prepare socket to receive the answer by specifying the callback
 * // function to be called for valid messages.
 * nl_socket_modify_cb(sock, NL_CB_VALID, NL_CB_CUSTOM, parse_cb, NULL);
 *
 * // Wait for the answer and receive it
 * nl_recvmsgs_default(sock);
 *
 * static int parse_cb(struct nl_msg *msg, void *arg)
 * {
 *     struct nlmsghdr *nlh = nlmsg_hdr(msg);
 *     struct nlattr *attrs[ATTR_MAX+1];
 *
 *     // Validate message and parse attributes
 *     genlmsg_parse(nlh, 0, attrs, ATTR_MAX, policy);
 *
 *     if (attrs[ATTR_FOO]) {
 *         uint32_t value = nla_get_u32(attrs[ATTR_FOO]);
 *         ...
 *     }
 *
 *     return 0;
 * }
 * @endcode
 * @{
 */

#include <netlink-generic.h>
#include <netlink/netlink.h>
#include <netlink/genl/genl.h>
#include <netlink/utils.h>

/**
 * @name Socket Creating
 * @{
 */

int genl_connect(struct nl_sock *sk)
{
	return nl_connect(sk, NETLINK_GENERIC);
}

/** @} */

/**
 * @name Sending
 * @{
 */

/**
 * Send trivial generic netlink message
 * @arg sk		Netlink socket.
 * @arg family		Generic netlink family
 * @arg cmd		Command
 * @arg version		Version
 * @arg flags		Additional netlink message flags.
 *
 * Fills out a routing netlink request message and sends it out
 * using nl_send_simple().
 *
 * @return 0 on success or a negative error code.
 */
int genl_send_simple(struct nl_sock *sk, int family, int cmd,
		     int version, int flags)
{
	struct genlmsghdr hdr = {
		.cmd = cmd,
		.version = version,
	};

	return nl_send_simple(sk, family, flags, &hdr, sizeof(hdr));
}

/** @} */


/**
 * @name Message Parsing
 * @{
 */

int genlmsg_valid_hdr(struct nlmsghdr *nlh, int hdrlen)
{
	struct genlmsghdr *ghdr;

	if (!nlmsg_valid_hdr(nlh, GENL_HDRLEN))
		return 0;

	ghdr = nlmsg_data(nlh);
	if (genlmsg_len(ghdr) < NLMSG_ALIGN(hdrlen))
		return 0;

	return 1;
}

int genlmsg_validate(struct nlmsghdr *nlh, int hdrlen, int maxtype,
		   struct nla_policy *policy)
{
	struct genlmsghdr *ghdr;

	if (!genlmsg_valid_hdr(nlh, hdrlen))
		return -NLE_MSG_TOOSHORT;

	ghdr = nlmsg_data(nlh);
	return nla_validate(genlmsg_attrdata(ghdr, hdrlen),
			    genlmsg_attrlen(ghdr, hdrlen), maxtype, policy);
}

int genlmsg_parse(struct nlmsghdr *nlh, int hdrlen, struct nlattr *tb[],
		  int maxtype, struct nla_policy *policy)
{
	struct genlmsghdr *ghdr;

	if (!genlmsg_valid_hdr(nlh, hdrlen))
		return -NLE_MSG_TOOSHORT;

	ghdr = nlmsg_data(nlh);
	return nla_parse(tb, maxtype, genlmsg_attrdata(ghdr, hdrlen),
			 genlmsg_attrlen(ghdr, hdrlen), policy);
}

/**
 * Get head of message payload
 * @arg gnlh	genetlink messsage header
 */
void *genlmsg_data(const struct genlmsghdr *gnlh)
{
	return ((unsigned char *) gnlh + GENL_HDRLEN);
}

/**
 * Get lenght of message payload
 * @arg gnlh	genetlink message header
 */
int genlmsg_len(const struct genlmsghdr *gnlh)
{
	struct nlmsghdr *nlh = (struct nlmsghdr *)((unsigned char *)gnlh -
							NLMSG_HDRLEN);
	return (nlh->nlmsg_len - GENL_HDRLEN - NLMSG_HDRLEN);
}

/**
 * Get head of attribute data
 * @arg gnlh	generic netlink message header
 * @arg hdrlen	length of family specific header
 */
struct nlattr *genlmsg_attrdata(const struct genlmsghdr *gnlh, int hdrlen)
{
	return genlmsg_data(gnlh) + NLMSG_ALIGN(hdrlen);
}

/**
 * Get length of attribute data
 * @arg gnlh	generic netlink message header
 * @arg hdrlen	length of family specific header
 */
int genlmsg_attrlen(const struct genlmsghdr *gnlh, int hdrlen)
{
	return genlmsg_len(gnlh) - NLMSG_ALIGN(hdrlen);
}

/** @} */

/**
 * @name Message Building
 * @{
 */

/**
 * Add generic netlink header to netlink message
 * @arg msg		netlink message
 * @arg pid		netlink process id or NL_AUTO_PID
 * @arg seq		sequence number of message or NL_AUTO_SEQ
 * @arg family		generic netlink family
 * @arg hdrlen		length of user specific header
 * @arg flags		message flags
 * @arg cmd		generic netlink command
 * @arg version		protocol version
 *
 * Returns pointer to user specific header.
 */
void *genlmsg_put(struct nl_msg *msg, uint32_t pid, uint32_t seq, int family,
		  int hdrlen, int flags, uint8_t cmd, uint8_t version)
{
	struct nlmsghdr *nlh;
	struct genlmsghdr hdr = {
		.cmd = cmd,
		.version = version,
	};

	nlh = nlmsg_put(msg, pid, seq, family, GENL_HDRLEN + hdrlen, flags);
	if (nlh == NULL)
		return NULL;

	memcpy(nlmsg_data(nlh), &hdr, sizeof(hdr));
	NL_DBG(2, "msg %p: Added generic netlink header cmd=%d version=%d\n",
	       msg, cmd, version);

	return nlmsg_data(nlh) + GENL_HDRLEN;
}

/** @} */

/** @} */
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
/******************************************************************************
 * Simple EDF scheduler for xen
 *
 * by Stephan Diestelhorst (C)  2004 Cambridge University
 * based on code by Mark Williamson (C) 2004 Intel Research Cambridge
 */

#include <xen/lib.h>
#include <xen/sched.h>
#include <xen/sched-if.h>
#include <xen/timer.h>
#include <xen/softirq.h>
#include <xen/time.h>
#include <xen/errno.h>

/*verbosity settings*/
#define SEDFLEVEL 0
#define PRINT(_f, _a...)                        \
    do {                                        \
        if ( (_f) <= SEDFLEVEL )                \
            printk(_a );                        \
    } while ( 0 )

#ifndef NDEBUG
#define SEDF_STATS
#define CHECK(_p)                                           \
    do {                                                    \
        if ( !(_p) )                                        \
            printk("Check '%s' failed, line %d, file %s\n", \
                   #_p , __LINE__, __FILE__);               \
    } while ( 0 )
#else
#define CHECK(_p) ((void)0)
#endif

#define EXTRA_NONE (0)
#define EXTRA_AWARE (1)
#define EXTRA_RUN_PEN (2)
#define EXTRA_RUN_UTIL (4)
#define EXTRA_WANT_PEN_Q (8)
#define EXTRA_PEN_Q (0)
#define EXTRA_UTIL_Q (1)
#define SEDF_ASLEEP (16)

#define EXTRA_QUANTUM (MICROSECS(500)) 
#define WEIGHT_PERIOD (MILLISECS(100))
#define WEIGHT_SAFETY (MILLISECS(5))

#define PERIOD_MAX MILLISECS(10000) /* 10s  */
#define PERIOD_MIN (MICROSECS(10))  /* 10us */
#define SLICE_MIN (MICROSECS(5))    /*  5us */

#define IMPLY(a, b) (!(a) || (b))
#define EQ(a, b) ((!!(a)) == (!!(b)))


struct sedf_dom_info {
    struct domain  *domain;
};

struct sedf_vcpu_info {
    struct vcpu *vcpu;
    struct list_head list;
    struct list_head extralist[2];
 
    /*Parameters for EDF*/
    s_time_t  period;  /*=(relative deadline)*/
    s_time_t  slice;  /*=worst case execution time*/
 
    /*Advaced Parameters*/
    /*Latency Scaling*/
    s_time_t  period_orig;
    s_time_t  slice_orig;
    s_time_t  latency;
 
    /*status of domain*/
    int       status;
    /*weights for "Scheduling for beginners/ lazy/ etc." ;)*/
    short     weight;
    short     extraweight;
    /*Bookkeeping*/
    s_time_t  deadl_abs;
    s_time_t  sched_start_abs;
    s_time_t  cputime;
    /* times the domain un-/blocked */
    s_time_t  block_abs;
    s_time_t  unblock_abs;
 
    /*scores for {util, block penalty}-weighted extratime distribution*/
    int   score[2];
    s_time_t  short_block_lost_tot;
 
    /*Statistics*/
    s_time_t  extra_time_tot;

#ifdef SEDF_STATS
    s_time_t  block_time_tot;
    s_time_t  penalty_time_tot;
    int   block_tot;
    int   short_block_tot;
    int   long_block_tot;
    int   short_cont;
    int   pen_extra_blocks;
    int   pen_extra_slices;
#endif
};

struct sedf_cpu_info {
    struct list_head runnableq;
    struct list_head waitq;
    struct list_head extraq[2];
    s_time_t         current_slice_expires;
};

#define EDOM_INFO(d)   ((struct sedf_vcpu_info *)((d)->sched_priv))
#define CPU_INFO(cpu)  \
    ((struct sedf_cpu_info *)per_cpu(schedule_data, cpu).sched_priv)
#define LIST(d)        (&EDOM_INFO(d)->list)
#define EXTRALIST(d,i) (&(EDOM_INFO(d)->extralist[i]))
#define RUNQ(cpu)      (&CPU_INFO(cpu)->runnableq)
#define WAITQ(cpu)     (&CPU_INFO(cpu)->waitq)
#define EXTRAQ(cpu,i)  (&(CPU_INFO(cpu)->extraq[i]))
#define IDLETASK(cpu)  ((struct vcpu *)per_cpu(schedule_data, cpu).idle)

#define PERIOD_BEGIN(inf) ((inf)->deadl_abs - (inf)->period)

#define MIN(x,y)    (((x)<(y))?(x):(y))
#define DIV_UP(x,y) (((x) + (y) - 1) / y)

#define extra_runs(inf)      ((inf->status) & 6)
#define extra_get_cur_q(inf) (((inf->status & 6) >> 1)-1)
#define sedf_runnable(edom)  (!(EDOM_INFO(edom)->status & SEDF_ASLEEP))


static void sedf_dump_cpu_state(int i);

static inline int extraq_on(struct vcpu *d, int i)
{
    return ((EXTRALIST(d,i)->next != NULL) &&
            (EXTRALIST(d,i)->next != EXTRALIST(d,i)));
}

static inline void extraq_add_head(struct vcpu *d, int i)
{
    list_add(EXTRALIST(d,i), EXTRAQ(d->processor,i));
    ASSERT(extraq_on(d, i));
}

static inline void extraq_add_tail(struct vcpu *d, int i)
{
    list_add_tail(EXTRALIST(d,i), EXTRAQ(d->processor,i));
    ASSERT(extraq_on(d, i));
}

static inline void extraq_del(struct vcpu *d, int i)
{
    struct list_head *list = EXTRALIST(d,i);
    ASSERT(extraq_on(d,i));
    PRINT(3, "Removing domain %i.%i from L%i extraq\n",
          d->domain->domain_id, d->vcpu_id, i);
    list_del(list);
    list->next = NULL;
    ASSERT(!extraq_on(d, i));
}

/* adds a domain to the queue of processes which are aware of extra time. List
   is sorted by score, where a lower score means higher priority for an extra
   slice. It also updates the score, by simply subtracting a fixed value from
   each entry, in order to avoid overflow. The algorithm works by simply
   charging each domain that recieved extratime with an inverse of its weight.
 */ 
static inline void extraq_add_sort_update(struct vcpu *d, int i, int sub)
{
    struct list_head      *cur;
    struct sedf_vcpu_info *curinf;
 
    ASSERT(!extraq_on(d,i));

    PRINT(3, "Adding domain %i.%i (score= %i, short_pen= %"PRIi64")"
          " to L%i extraq\n",
          d->domain->domain_id, d->vcpu_id, EDOM_INFO(d)->score[i],
          EDOM_INFO(d)->short_block_lost_tot, i);

    /*
     * Iterate through all elements to find our "hole" and on our way
     * update all the other scores.
     */
    list_for_each ( cur, EXTRAQ(d->processor, i) )
    {
        curinf = list_entry(cur,struct sedf_vcpu_info,extralist[i]);
        curinf->score[i] -= sub;
        if ( EDOM_INFO(d)->score[i] < curinf->score[i] )
            break;
        PRINT(4,"\tbehind domain %i.%i (score= %i)\n",
              curinf->vcpu->domain->domain_id,
              curinf->vcpu->vcpu_id, curinf->score[i]);
    }

    /* cur now contains the element, before which we'll enqueue. */
    PRINT(3, "\tlist_add to %p\n", cur->prev);
    list_add(EXTRALIST(d,i),cur->prev);
 
    /* Continue updating the extraq. */
    if ( (cur != EXTRAQ(d->processor,i)) && sub )
    {
        for ( cur = cur->next; cur != EXTRAQ(d->processor,i); cur = cur->next )
        {
            curinf = list_entry(cur,struct sedf_vcpu_info, extralist[i]);
            curinf->score[i] -= sub;
            PRINT(4, "\tupdating domain %i.%i (score= %u)\n",
                  curinf->vcpu->domain->domain_id, 
                  curinf->vcpu->vcpu_id, curinf->score[i]);
        }
    }

    ASSERT(extraq_on(d,i));
}
static inline void extraq_check(struct vcpu *d)
{
    if ( extraq_on(d, EXTRA_UTIL_Q) )
    {
        PRINT(2,"Dom %i.%i is on L1 extraQ\n",
              d->domain->domain_id, d->vcpu_id);

        if ( !(EDOM_INFO(d)->status & EXTRA_AWARE) &&
             !extra_runs(EDOM_INFO(d)) )
        {
            extraq_del(d, EXTRA_UTIL_Q);
            PRINT(2,"Removed dom %i.%i from L1 extraQ\n",
                  d->domain->domain_id, d->vcpu_id);
        }
    }
    else
    {
        PRINT(2, "Dom %i.%i is NOT on L1 extraQ\n",
              d->domain->domain_id,
              d->vcpu_id);

        if ( (EDOM_INFO(d)->status & EXTRA_AWARE) && sedf_runnable(d) )
        {
            extraq_add_sort_update(d, EXTRA_UTIL_Q, 0);
            PRINT(2,"Added dom %i.%i to L1 extraQ\n",
                  d->domain->domain_id, d->vcpu_id);
        }
    }
}

static inline void extraq_check_add_unblocked(struct vcpu *d, int priority)
{
    struct sedf_vcpu_info *inf = EDOM_INFO(d);

    if ( inf->status & EXTRA_AWARE )
        /* Put on the weighted extraq without updating any scores. */
        extraq_add_sort_update(d, EXTRA_UTIL_Q, 0);
}

static inline int __task_on_queue(struct vcpu *d)
{
    return (((LIST(d))->next != NULL) && (LIST(d)->next != LIST(d)));
}

static inline void __del_from_queue(struct vcpu *d)
{
    struct list_head *list = LIST(d);
    ASSERT(__task_on_queue(d));
    PRINT(3,"Removing domain %i.%i (bop= %"PRIu64") from runq/waitq\n",
          d->domain->domain_id, d->vcpu_id, PERIOD_BEGIN(EDOM_INFO(d)));
    list_del(list);
    list->next = NULL;
    ASSERT(!__task_on_queue(d));
}

typedef int(*list_comparer)(struct list_head* el1, struct list_head* el2);

static inline void list_insert_sort(
    struct list_head *list, struct list_head *element, list_comparer comp)
{
    struct list_head     *cur;

    /* Iterate through all elements to find our "hole". */
    list_for_each( cur, list )
        if ( comp(element, cur) < 0 )
            break;

    /* cur now contains the element, before which we'll enqueue. */
    PRINT(3,"\tlist_add to %p\n",cur->prev);
    list_add(element, cur->prev);
}

#define DOMAIN_COMPARER(name, field, comp1, comp2)          \
int name##_comp(struct list_head* el1, struct list_head* el2) \
{                                                           \
    struct sedf_vcpu_info *d1, *d2;                     \
    d1 = list_entry(el1,struct sedf_vcpu_info, field);  \
    d2 = list_entry(el2,struct sedf_vcpu_info, field);  \
    if ( (comp1) == (comp2) )                             \
        return 0;                                   \
    if ( (comp1) < (comp2) )                              \
        return -1;                                  \
    else                                                \
        return 1;                                   \
}

/* adds a domain to the queue of processes which wait for the beginning of the
   next period; this list is therefore sortet by this time, which is simply
   absol. deadline - period
 */ 
DOMAIN_COMPARER(waitq, list, PERIOD_BEGIN(d1), PERIOD_BEGIN(d2));
static inline void __add_to_waitqueue_sort(struct vcpu *v)
{
    ASSERT(!__task_on_queue(v));
    PRINT(3,"Adding domain %i.%i (bop= %"PRIu64") to waitq\n",
          v->domain->domain_id, v->vcpu_id, PERIOD_BEGIN(EDOM_INFO(v)));
    list_insert_sort(WAITQ(v->processor), LIST(v), waitq_comp);
    ASSERT(__task_on_queue(v));
}

/* adds a domain to the queue of processes which have started their current
   period and are runnable (i.e. not blocked, dieing,...). The first element
   on this list is running on the processor, if the list is empty the idle
   task will run. As we are implementing EDF, this list is sorted by deadlines.
 */ 
DOMAIN_COMPARER(runq, list, d1->deadl_abs, d2->deadl_abs);
static inline void __add_to_runqueue_sort(struct vcpu *v)
{
    PRINT(3,"Adding domain %i.%i (deadl= %"PRIu64") to runq\n",
          v->domain->domain_id, v->vcpu_id, EDOM_INFO(v)->deadl_abs);
    list_insert_sort(RUNQ(v->processor), LIST(v), runq_comp);
}


static int sedf_init_vcpu(struct vcpu *v)
{
    struct sedf_vcpu_info *inf;

    if ( (v->sched_priv = xmalloc(struct sedf_vcpu_info)) == NULL )
        return -1;
    memset(v->sched_priv, 0, sizeof(struct sedf_vcpu_info));

    inf = EDOM_INFO(v);
    inf->vcpu = v;
 
    /* Allocate per-CPU context if this is the first domain to be added. */
    if ( unlikely(per_cpu(schedule_data, v->processor).sched_priv == NULL) )
    {
        per_cpu(schedule_data, v->processor).sched_priv = 
            xmalloc(struct sedf_cpu_info);
        BUG_ON(per_cpu(schedule_data, v->processor).sched_priv == NULL);
        memset(CPU_INFO(v->processor), 0, sizeof(*CPU_INFO(v->processor)));
        INIT_LIST_HEAD(WAITQ(v->processor));
        INIT_LIST_HEAD(RUNQ(v->processor));
        INIT_LIST_HEAD(EXTRAQ(v->processor,EXTRA_PEN_Q));
        INIT_LIST_HEAD(EXTRAQ(v->processor,EXTRA_UTIL_Q));
    }
       
    /* Every VCPU gets an equal share of extratime by default. */
    inf->deadl_abs   = 0;
    inf->latency     = 0;
    inf->status      = EXTRA_AWARE | SEDF_ASLEEP;
    inf->extraweight = 1;

    if ( v->domain->domain_id == 0 )
    {
        /* Domain0 gets 75% guaranteed (15ms every 20ms). */
        inf->period    = MILLISECS(20);
        inf->slice     = MILLISECS(15);
    }
    else
    {
        /* Best-effort extratime only. */
        inf->period    = WEIGHT_PERIOD;
        inf->slice     = 0;
    }

    inf->period_orig = inf->period; inf->slice_orig = inf->slice;
    INIT_LIST_HEAD(&(inf->list));
    INIT_LIST_HEAD(&(inf->extralist[EXTRA_PEN_Q]));
    INIT_LIST_HEAD(&(inf->extralist[EXTRA_UTIL_Q]));
 
    if ( !is_idle_vcpu(v) )
    {
        extraq_check(v);
    }
    else
    {
        EDOM_INFO(v)->deadl_abs = 0;
        EDOM_INFO(v)->status &= ~SEDF_ASLEEP;
    }

    return 0;
}

static void sedf_destroy_vcpu(struct vcpu *v)
{
    xfree(v->sched_priv);
}

static int sedf_init_domain(struct domain *d)
{
    d->sched_priv = xmalloc(struct sedf_dom_info);
    if ( d->sched_priv == NULL )
        return -ENOMEM;

    memset(d->sched_priv, 0, sizeof(struct sedf_dom_info));

    return 0;
}

static void sedf_destroy_domain(struct domain *d)
{
    xfree(d->sched_priv);
}

static int sedf_pick_cpu(struct vcpu *v)
{
    cpumask_t online_affinity;

    cpus_and(online_affinity, v->cpu_affinity, cpu_online_map);
    return first_cpu(online_affinity);
}

/*
 * Handles the rescheduling & bookkeeping of domains running in their
 * guaranteed timeslice.
 */
static void desched_edf_dom(s_time_t now, struct vcpu* d)
{
    struct sedf_vcpu_info* inf = EDOM_INFO(d);

    /* Current domain is running in real time mode. */
    ASSERT(__task_on_queue(d));

    /* Update the domain's cputime. */
    inf->cputime += now - inf->sched_start_abs;

    /*
     * Scheduling decisions which don't remove the running domain from the
     * runq. 
     */
    if ( (inf->cputime < inf->slice) && sedf_runnable(d) )
        return;
  
    __del_from_queue(d);
  
    /*
     * Manage bookkeeping (i.e. calculate next deadline, memorise
     * overrun-time of slice) of finished domains.
     */
    if ( inf->cputime >= inf->slice )
    {
        inf->cputime -= inf->slice;
  
        if ( inf->period < inf->period_orig )
        {
            /* This domain runs in latency scaling or burst mode. */
            inf->period *= 2;
            inf->slice  *= 2;
            if ( (inf->period > inf->period_orig) ||
                 (inf->slice > inf->slice_orig) )
            {
                /* Reset slice and period. */
                inf->period = inf->period_orig;
                inf->slice = inf->slice_orig;
            }
        }

        /* Set next deadline. */
        inf->deadl_abs += inf->period;
    }
 
    /* Add a runnable domain to the waitqueue. */
    if ( sedf_runnable(d) )
    {
        __add_to_waitqueue_sort(d);
    }
    else
    {
        /* We have a blocked realtime task -> remove it from exqs too. */
        if ( extraq_on(d, EXTRA_PEN_Q) )
            extraq_del(d, EXTRA_PEN_Q);
        if ( extraq_on(d, EXTRA_UTIL_Q) )
            extraq_del(d, EXTRA_UTIL_Q);
    }

    ASSERT(EQ(sedf_runnable(d), __task_on_queue(d)));
    ASSERT(IMPLY(extraq_on(d, EXTRA_UTIL_Q) || extraq_on(d, EXTRA_PEN_Q), 
                 sedf_runnable(d)));
}


/* Update all elements on the queues */
static void update_queues(
    s_time_t now, struct list_head *runq, struct list_head *waitq)
{
    struct list_head     *cur, *tmp;
    struct sedf_vcpu_info *curinf;
 
    PRINT(3,"Updating waitq..\n");

    /*
     * Check for the first elements of the waitqueue, whether their
     * next period has already started.
     */
    list_for_each_safe ( cur, tmp, waitq )
    {
        curinf = list_entry(cur, struct sedf_vcpu_info, list);
        PRINT(4,"\tLooking @ dom %i.%i\n",
              curinf->vcpu->domain->domain_id, curinf->vcpu->vcpu_id);
        if ( PERIOD_BEGIN(curinf) > now )
            break;
        __del_from_queue(curinf->vcpu);
        __add_to_runqueue_sort(curinf->vcpu);
    }
 
    PRINT(3,"Updating runq..\n");

    /* Process the runq, find domains that are on the runq that shouldn't. */
    list_for_each_safe ( cur, tmp, runq )
    {
        curinf = list_entry(cur,struct sedf_vcpu_info,list);
        PRINT(4,"\tLooking @ dom %i.%i\n",
              curinf->vcpu->domain->domain_id, curinf->vcpu->vcpu_id);

        if ( unlikely(curinf->slice == 0) )
        {
            /* Ignore domains with empty slice. */
            PRINT(4,"\tUpdating zero-slice domain %i.%i\n",
                  curinf->vcpu->domain->domain_id,
                  curinf->vcpu->vcpu_id);
            __del_from_queue(curinf->vcpu);

            /* Move them to their next period. */
            curinf->deadl_abs += curinf->period;

            /* Ensure that the start of the next period is in the future. */
            if ( unlikely(PERIOD_BEGIN(curinf) < now) )
                curinf->deadl_abs += 
                    (DIV_UP(now - PERIOD_BEGIN(curinf),
                            curinf->period)) * curinf->period;

            /* Put them back into the queue. */
            __add_to_waitqueue_sort(curinf->vcpu);
        }
        else if ( unlikely((curinf->deadl_abs < now) ||
                           (curinf->cputime > curinf->slice)) )
        {
            /*
             * We missed the deadline or the slice was already finished.
             * Might hapen because of dom_adj.
             */
            PRINT(4,"\tDomain %i.%i exceeded it's deadline/"
                  "slice (%"PRIu64" / %"PRIu64") now: %"PRIu64
                  " cputime: %"PRIu64"\n",
                  curinf->vcpu->domain->domain_id,
                  curinf->vcpu->vcpu_id,
                  curinf->deadl_abs, curinf->slice, now,
                  curinf->cputime);
            __del_from_queue(curinf->vcpu);

            /* Common case: we miss one period. */
            curinf->deadl_abs += curinf->period;
   
            /*
             * If we are still behind: modulo arithmetic, force deadline
             * to be in future and aligned to period borders.
             */
            if ( unlikely(curinf->deadl_abs < now) )
                curinf->deadl_abs += 
                    DIV_UP(now - curinf->deadl_abs,
                           curinf->period) * curinf->period;
            ASSERT(curinf->deadl_abs >= now);

            /* Give a fresh slice. */
            curinf->cputime = 0;
            if ( PERIOD_BEGIN(curinf) > now )
                __add_to_waitqueue_sort(curinf->vcpu);
            else
                __add_to_runqueue_sort(curinf->vcpu);
        }
        else
            break;
    }

    PRINT(3,"done updating the queues\n");
}


/* removes a domain from the head of the according extraQ and
   requeues it at a specified position:
     round-robin extratime: end of extraQ
     weighted ext.: insert in sorted list by score
   if the domain is blocked / has regained its short-block-loss
   time it is not put on any queue */
static void desched_extra_dom(s_time_t now, struct vcpu *d)
{
    struct sedf_vcpu_info *inf = EDOM_INFO(d);
    int i = extra_get_cur_q(inf);
    unsigned long oldscore;

    ASSERT(extraq_on(d, i));

    /* Unset all running flags. */
    inf->status  &= ~(EXTRA_RUN_PEN | EXTRA_RUN_UTIL);
    /* Fresh slice for the next run. */
    inf->cputime = 0;
    /* Accumulate total extratime. */
    inf->extra_time_tot += now - inf->sched_start_abs;
    /* Remove extradomain from head of the queue. */
    extraq_del(d, i);

    /* Update the score. */
    oldscore = inf->score[i];
    if ( i == EXTRA_PEN_Q )
    {
        /*domain was running in L0 extraq*/
        /*reduce block lost, probably more sophistication here!*/
        /*inf->short_block_lost_tot -= EXTRA_QUANTUM;*/
        inf->short_block_lost_tot -= now - inf->sched_start_abs;
        PRINT(3,"Domain %i.%i: Short_block_loss: %"PRIi64"\n", 
              inf->vcpu->domain->domain_id, inf->vcpu->vcpu_id,
              inf->short_block_lost_tot);
#if 0
        /*
         * KAF: If we don't exit short-blocking state at this point
         * domain0 can steal all CPU for up to 10 seconds before
         * scheduling settles down (when competing against another
         * CPU-bound domain). Doing this seems to make things behave
         * nicely. Noone gets starved by default.
         */
        if ( inf->short_block_lost_tot <= 0 )
#endif
        {
            PRINT(4,"Domain %i.%i compensated short block loss!\n",
                  inf->vcpu->domain->domain_id, inf->vcpu->vcpu_id);
            /*we have (over-)compensated our block penalty*/
            inf->short_block_lost_tot = 0;
            /*we don't want a place on the penalty queue anymore!*/
            inf->status &= ~EXTRA_WANT_PEN_Q;
            goto check_extra_queues;
        }

        /*we have to go again for another try in the block-extraq,
          the score is not used incremantally here, as this is
          already done by recalculating the block_lost*/
        inf->score[EXTRA_PEN_Q] = (inf->period << 10) /
            inf->short_block_lost_tot;
        oldscore = 0;
    }
    else
    {
        /*domain was running in L1 extraq => score is inverse of
          utilization and is used somewhat incremental!*/
        if ( !inf->extraweight )
            /*NB: use fixed point arithmetic with 10 bits*/
            inf->score[EXTRA_UTIL_Q] = (inf->period << 10) /
                inf->slice;
        else
            /*conversion between realtime utilisation and extrawieght:
              full (ie 100%) utilization is equivalent to 128 extraweight*/
            inf->score[EXTRA_UTIL_Q] = (1<<17) / inf->extraweight;
    }

 check_extra_queues:
    /* Adding a runnable domain to the right queue and removing blocked ones*/
    if ( sedf_runnable(d) )
    {
        /*add according to score: weighted round robin*/
        if (((inf->status & EXTRA_AWARE) && (i == EXTRA_UTIL_Q)) ||
            ((inf->status & EXTRA_WANT_PEN_Q) && (i == EXTRA_PEN_Q)))
            extraq_add_sort_update(d, i, oldscore);
    }
    else
    {
        /*remove this blocked domain from the waitq!*/
        __del_from_queue(d);
        /*make sure that we remove a blocked domain from the other
          extraq too*/
        if ( i == EXTRA_PEN_Q )
        {
            if ( extraq_on(d, EXTRA_UTIL_Q) )
                extraq_del(d, EXTRA_UTIL_Q);
        }
        else
        {
            if ( extraq_on(d, EXTRA_PEN_Q) )
                extraq_del(d, EXTRA_PEN_Q);
        }
    }

    ASSERT(EQ(sedf_runnable(d), __task_on_queue(d)));
    ASSERT(IMPLY(extraq_on(d, EXTRA_UTIL_Q) || extraq_on(d, EXTRA_PEN_Q), 
                 sedf_runnable(d)));
}


static struct task_slice sedf_do_extra_schedule(
    s_time_t now, s_time_t end_xt, struct list_head *extraq[], int cpu)
{
    struct task_slice   ret;
    struct sedf_vcpu_info *runinf;
    ASSERT(end_xt > now);

    /* Enough time left to use for extratime? */
    if ( end_xt - now < EXTRA_QUANTUM )
        goto return_idle;

    if ( !list_empty(extraq[EXTRA_PEN_Q]) )
    {
        /*we still have elements on the level 0 extraq 
          => let those run first!*/
        runinf   = list_entry(extraq[EXTRA_PEN_Q]->next, 
                              struct sedf_vcpu_info, extralist[EXTRA_PEN_Q]);
        runinf->status |= EXTRA_RUN_PEN;
        ret.task = runinf->vcpu;
        ret.time = EXTRA_QUANTUM;
#ifdef SEDF_STATS
        runinf->pen_extra_slices++;
#endif
    }
    else
    {
        if ( !list_empty(extraq[EXTRA_UTIL_Q]) )
        {
            /*use elements from the normal extraqueue*/
            runinf   = list_entry(extraq[EXTRA_UTIL_Q]->next,
                                  struct sedf_vcpu_info,
                                  extralist[EXTRA_UTIL_Q]);
            runinf->status |= EXTRA_RUN_UTIL;
            ret.task = runinf->vcpu;
            ret.time = EXTRA_QUANTUM;
        }
        else
            goto return_idle;
    }

    ASSERT(ret.time > 0);
    ASSERT(sedf_runnable(ret.task));
    return ret;
 
 return_idle:
    ret.task = IDLETASK(cpu);
    ret.time = end_xt - now;
    ASSERT(ret.time > 0);
    ASSERT(sedf_runnable(ret.task));
    return ret;
}


/* Main scheduling function
   Reasons for calling this function are:
   -timeslice for the current period used up
   -domain on waitqueue has started it's period
   -and various others ;) in general: determine which domain to run next*/
static struct task_slice sedf_do_schedule(s_time_t now)
{
    int                   cpu      = smp_processor_id();
    struct list_head     *runq     = RUNQ(cpu);
    struct list_head     *waitq    = WAITQ(cpu);
    struct sedf_vcpu_info *inf     = EDOM_INFO(current);
    struct list_head      *extraq[] = {
        EXTRAQ(cpu, EXTRA_PEN_Q), EXTRAQ(cpu, EXTRA_UTIL_Q)};
    struct sedf_vcpu_info *runinf, *waitinf;
    struct task_slice      ret;

    /*idle tasks don't need any of the following stuf*/
    if ( is_idle_vcpu(current) )
        goto check_waitq;
 
    /* create local state of the status of the domain, in order to avoid
       inconsistent state during scheduling decisions, because data for
       vcpu_runnable is not protected by the scheduling lock!*/
    if ( !vcpu_runnable(current) )
        inf->status |= SEDF_ASLEEP;
 
    if ( inf->status & SEDF_ASLEEP )
        inf->block_abs = now;

    if ( unlikely(extra_runs(inf)) )
    {
        /*special treatment of domains running in extra time*/
        desched_extra_dom(now, current);
    }
    else 
    {
        desched_edf_dom(now, current);
    }
 check_waitq:
    update_queues(now, runq, waitq);
 
    /*now simply pick the first domain from the runqueue, which has the
      earliest deadline, because the list is sorted*/
 
    if ( !list_empty(runq) )
    {
        runinf   = list_entry(runq->next,struct sedf_vcpu_info,list);
        ret.task = runinf->vcpu;
        if ( !list_empty(waitq) )
        {
            waitinf  = list_entry(waitq->next,
                                  struct sedf_vcpu_info,list);
            /*rerun scheduler, when scheduled domain reaches it's
              end of slice or the first domain from the waitqueue
              gets ready*/
            ret.time = MIN(now + runinf->slice - runinf->cputime,
                           PERIOD_BEGIN(waitinf)) - now;
        }
        else
        {
            ret.time = runinf->slice - runinf->cputime;
        }
        CHECK(ret.time > 0);
        goto sched_done;
    }
 
    if ( !list_empty(waitq) )
    {
        waitinf  = list_entry(waitq->next,struct sedf_vcpu_info, list);
        /*we could not find any suitable domain 
          => look for domains that are aware of extratime*/
        ret = sedf_do_extra_schedule(now, PERIOD_BEGIN(waitinf),
                                     extraq, cpu);
        CHECK(ret.time > 0);
    }
    else
    {
        /*this could probably never happen, but one never knows...*/
        /*it can... imagine a second CPU, which is pure scifi ATM,
          but one never knows ;)*/
        ret.task = IDLETASK(cpu);
        ret.time = SECONDS(1);
    }

 sched_done: 
    /*TODO: Do something USEFUL when this happens and find out, why it
      still can happen!!!*/
    if ( ret.time < 0)
    {
        printk("Ouch! We are seriously BEHIND schedule! %"PRIi64"\n",
               ret.time);
        ret.time = EXTRA_QUANTUM;
    }

    EDOM_INFO(ret.task)->sched_start_abs = now;
    CHECK(ret.time > 0);
    ASSERT(sedf_runnable(ret.task));
    CPU_INFO(cpu)->current_slice_expires = now + ret.time;
    return ret;
}


static void sedf_sleep(struct vcpu *d)
{
    PRINT(2,"sedf_sleep was called, domain-id %i.%i\n",
          d->domain->domain_id, d->vcpu_id);
 
    if ( is_idle_vcpu(d) )
        return;

    EDOM_INFO(d)->status |= SEDF_ASLEEP;
 
    if ( per_cpu(schedule_data, d->processor).curr == d )
    {
        cpu_raise_softirq(d->processor, SCHEDULE_SOFTIRQ);
    }
    else
    {
        if ( __task_on_queue(d) )
            __del_from_queue(d);
        if ( extraq_on(d, EXTRA_UTIL_Q) ) 
            extraq_del(d, EXTRA_UTIL_Q);
        if ( extraq_on(d, EXTRA_PEN_Q) )
            extraq_del(d, EXTRA_PEN_Q);
    }
}


/* This function wakes up a domain, i.e. moves them into the waitqueue
 * things to mention are: admission control is taking place nowhere at
 * the moment, so we can't be sure, whether it is safe to wake the domain
 * up at all. Anyway, even if it is safe (total cpu usage <=100%) there are
 * some considerations on when to allow the domain to wake up and have it's
 * first deadline...
 * I detected 3 cases, which could describe the possible behaviour of the
 * scheduler,
 * and I'll try to make them more clear:
 *
 * 1. Very conservative
 *     -when a blocked domain unblocks, it is allowed to start execution at
 *      the beginning of the next complete period
 *      (D..deadline, R..running, B..blocking/sleeping, U..unblocking/waking up
 *
 *      DRRB_____D__U_____DRRRRR___D________ ... 
 *
 *     -this causes the domain to miss a period (and a deadlline)
 *     -doesn't disturb the schedule at all
 *     -deadlines keep occuring isochronous
 *
 * 2. Conservative Part 1: Short Unblocking
 *     -when a domain unblocks in the same period as it was blocked it
 *      unblocks and may consume the rest of it's original time-slice minus
 *      the time it was blocked
 *      (assume period=9, slice=5)
 *
 *      DRB_UR___DRRRRR___D...
 *
 *     -this also doesn't disturb scheduling, but might lead to the fact, that
 *      the domain can't finish it's workload in the period
 *     -in addition to that the domain can be treated prioritised when
 *      extratime is available
 *     -addition: experiments have shown that this may have a HUGE impact on
 *      performance of other domains, becaus it can lead to excessive context
 *      switches
 *
 *    Part2: Long Unblocking
 *    Part 2a
 *     -it is obvious that such accounting of block time, applied when
 *      unblocking is happening in later periods, works fine aswell
 *     -the domain is treated as if it would have been running since the start
 *      of its new period
 *
 *      DRB______D___UR___D... 
 *
 *    Part 2b
 *     -if one needs the full slice in the next period, it is necessary to
 *      treat the unblocking time as the start of the new period, i.e. move
 *      the deadline further back (later)
 *     -this doesn't disturb scheduling as well, because for EDF periods can
 *      be treated as minimal inter-release times and scheduling stays
 *      correct, when deadlines are kept relative to the time the process
 *      unblocks
 *
 *      DRB______D___URRRR___D...<prev [Thread] next>
 *                       (D) <- old deadline was here
 *     -problem: deadlines don't occur isochronous anymore
 *    Part 2c (Improved Atropos design)
 *     -when a domain unblocks it is given a very short period (=latency hint)
 *      and slice length scaled accordingly
 *     -both rise again to the original value (e.g. get doubled every period)
 *
 * 3. Unconservative (i.e. incorrect)
 *     -to boost the performance of I/O dependent domains it would be possible
 *      to put the domain into the runnable queue immediately, and let it run
 *      for the remainder of the slice of the current period
 *      (or even worse: allocate a new full slice for the domain) 
 *     -either behaviour can lead to missed deadlines in other domains as
 *      opposed to approaches 1,2a,2b
 */
static void unblock_short_extra_support(
    struct sedf_vcpu_info* inf, s_time_t now)
{
    /*this unblocking scheme tries to support the domain, by assigning it
    a priority in extratime distribution according to the loss of time
    in this slice due to blocking*/
    s_time_t pen;
 
    /*no more realtime execution in this period!*/
    inf->deadl_abs += inf->period;
    if ( likely(inf->block_abs) )
    {
        //treat blocked time as consumed by the domain*/
        /*inf->cputime += now - inf->block_abs;*/
        /*penalty is time the domain would have
          had if it continued to run */
        pen = (inf->slice - inf->cputime);
        if ( pen < 0 )
            pen = 0;
        /*accumulate all penalties over the periods*/
        /*inf->short_block_lost_tot += pen;*/
        /*set penalty to the current value*/
        inf->short_block_lost_tot = pen;
        /*not sure which one is better.. but seems to work well...*/
  
        if ( inf->short_block_lost_tot )
        {
            inf->score[0] = (inf->period << 10) /
                inf->short_block_lost_tot;
#ifdef SEDF_STATS
            inf->pen_extra_blocks++;
#endif
            if ( extraq_on(inf->vcpu, EXTRA_PEN_Q) )
                /*remove domain for possible resorting!*/
                extraq_del(inf->vcpu, EXTRA_PEN_Q);
            else
                /*remember that we want to be on the penalty q
                  so that we can continue when we (un-)block
                  in penalty-extratime*/
                inf->status |= EXTRA_WANT_PEN_Q;
   
            /*(re-)add domain to the penalty extraq*/
            extraq_add_sort_update(inf->vcpu, EXTRA_PEN_Q, 0);
        }
    }

    /*give it a fresh slice in the next period!*/
    inf->cputime = 0;
}


static void unblock_long_cons_b(struct sedf_vcpu_info* inf,s_time_t now)
{
    /*Conservative 2b*/
    /*Treat the unblocking time as a start of a new period */
    inf->deadl_abs = now + inf->period;
    inf->cputime = 0;
}


#define DOMAIN_EDF   1
#define DOMAIN_EXTRA_PEN  2
#define DOMAIN_EXTRA_UTIL  3
#define DOMAIN_IDLE   4
static inline int get_run_type(struct vcpu* d)
{
    struct sedf_vcpu_info* inf = EDOM_INFO(d);
    if (is_idle_vcpu(d))
        return DOMAIN_IDLE;
    if (inf->status & EXTRA_RUN_PEN)
        return DOMAIN_EXTRA_PEN;
    if (inf->status & EXTRA_RUN_UTIL)
        return DOMAIN_EXTRA_UTIL;
    return DOMAIN_EDF;
}


/*Compares two domains in the relation of whether the one is allowed to
  interrupt the others execution.
  It returns true (!=0) if a switch to the other domain is good.
  Current Priority scheme is as follows:
   EDF > L0 (penalty based) extra-time > 
   L1 (utilization) extra-time > idle-domain
  In the same class priorities are assigned as following:
   EDF: early deadline > late deadline
   L0 extra-time: lower score > higher score*/
static inline int should_switch(struct vcpu *cur,
                                struct vcpu *other,
                                s_time_t now)
{
    struct sedf_vcpu_info *cur_inf, *other_inf;
    cur_inf   = EDOM_INFO(cur);
    other_inf = EDOM_INFO(other);
 
    /* Check whether we need to make an earlier scheduling decision. */
    if ( PERIOD_BEGIN(other_inf) < 
         CPU_INFO(other->processor)->current_slice_expires )
        return 1;

    /* No timing-based switches need to be taken into account here. */
    switch ( get_run_type(cur) )
    {
    case DOMAIN_EDF:
        /* Do not interrupt a running EDF domain. */
        return 0;
    case DOMAIN_EXTRA_PEN:
        /* Check whether we also want the L0 ex-q with lower score. */
        return ((other_inf->status & EXTRA_WANT_PEN_Q) &&
                (other_inf->score[EXTRA_PEN_Q] < 
                 cur_inf->score[EXTRA_PEN_Q]));
    case DOMAIN_EXTRA_UTIL:
        /* Check whether we want the L0 extraq. Don't
         * switch if both domains want L1 extraq.
         */
        return !!(other_inf->status & EXTRA_WANT_PEN_Q);
    case DOMAIN_IDLE:
        return 1;
    }

    return 1;
}

void sedf_wake(struct vcpu *d)
{
    s_time_t              now = NOW();
    struct sedf_vcpu_info* inf = EDOM_INFO(d);

    PRINT(3, "sedf_wake was called, domain-id %i.%i\n",d->domain->domain_id,
          d->vcpu_id);

    if ( unlikely(is_idle_vcpu(d)) )
        return;
   
    if ( unlikely(__task_on_queue(d)) )
    {
        PRINT(3,"\tdomain %i.%i is already in some queue\n",
              d->domain->domain_id, d->vcpu_id);
        return;
    }

    ASSERT(!sedf_runnable(d));
    inf->status &= ~SEDF_ASLEEP;
    ASSERT(!extraq_on(d, EXTRA_UTIL_Q));
    ASSERT(!extraq_on(d, EXTRA_PEN_Q));
 
    if ( unlikely(inf->deadl_abs == 0) )
    {
        /*initial setup of the deadline*/
        inf->deadl_abs = now + inf->slice;
    }
  
    PRINT(3, "waking up domain %i.%i (deadl= %"PRIu64" period= %"PRIu64
          "now= %"PRIu64")\n",
          d->domain->domain_id, d->vcpu_id, inf->deadl_abs, inf->period, now);

#ifdef SEDF_STATS 
    inf->block_tot++;
#endif

    if ( unlikely(now < PERIOD_BEGIN(inf)) )
    {
        PRINT(4,"extratime unblock\n");
        /* unblocking in extra-time! */
        if ( inf->status & EXTRA_WANT_PEN_Q )
        {
            /*we have a domain that wants compensation
              for block penalty and did just block in
              its compensation time. Give it another
              chance!*/
            extraq_add_sort_update(d, EXTRA_PEN_Q, 0);
        }
        extraq_check_add_unblocked(d, 0);
    }  
    else
    {  
        if ( now < inf->deadl_abs )
        {
            PRINT(4,"short unblocking\n");
            /*short blocking*/
#ifdef SEDF_STATS
            inf->short_block_tot++;
#endif
            unblock_short_extra_support(inf, now);

            extraq_check_add_unblocked(d, 1);
        }
        else
        {
            PRINT(4,"long unblocking\n");
            /*long unblocking*/
#ifdef SEDF_STATS
            inf->long_block_tot++;
#endif
            unblock_long_cons_b(inf, now);

            extraq_check_add_unblocked(d, 1);
        }
    }

    PRINT(3, "woke up domain %i.%i (deadl= %"PRIu64" period= %"PRIu64
          "now= %"PRIu64")\n",
          d->domain->domain_id, d->vcpu_id, inf->deadl_abs,
          inf->period, now);

    if ( PERIOD_BEGIN(inf) > now )
    {
        __add_to_waitqueue_sort(d);
        PRINT(3,"added to waitq\n");
    }
    else
    {
        __add_to_runqueue_sort(d);
        PRINT(3,"added to runq\n");
    }
 
#ifdef SEDF_STATS
    /*do some statistics here...*/
    if ( inf->block_abs != 0 )
    {
        inf->block_time_tot += now - inf->block_abs;
        inf->penalty_time_tot +=
            PERIOD_BEGIN(inf) + inf->cputime - inf->block_abs;
    }
#endif

    /*sanity check: make sure each extra-aware domain IS on the util-q!*/
    ASSERT(IMPLY(inf->status & EXTRA_AWARE, extraq_on(d, EXTRA_UTIL_Q)));
    ASSERT(__task_on_queue(d));
    /*check whether the awakened task needs to invoke the do_schedule
      routine. Try to avoid unnecessary runs but:
      Save approximation: Always switch to scheduler!*/
    ASSERT(d->processor >= 0);
    ASSERT(d->processor < NR_CPUS);
    ASSERT(per_cpu(schedule_data, d->processor).curr);

    if ( should_switch(per_cpu(schedule_data, d->processor).curr, d, now) )
        cpu_raise_softirq(d->processor, SCHEDULE_SOFTIRQ);
}


/* Print a lot of useful information about a domains in the system */
static void sedf_dump_domain(struct vcpu *d)
{
    printk("%i.%i has=%c ", d->domain->domain_id, d->vcpu_id,
           test_bit(_VCPUF_running, &d->vcpu_flags) ? 'T':'F');
    printk("p=%"PRIu64" sl=%"PRIu64" ddl=%"PRIu64" w=%hu"
           " sc=%i xtr(%s)=%"PRIu64" ew=%hu",
           EDOM_INFO(d)->period, EDOM_INFO(d)->slice, EDOM_INFO(d)->deadl_abs,
           EDOM_INFO(d)->weight,
           EDOM_INFO(d)->score[EXTRA_UTIL_Q],
           (EDOM_INFO(d)->status & EXTRA_AWARE) ? "yes" : "no",
           EDOM_INFO(d)->extra_time_tot, EDOM_INFO(d)->extraweight);
    
#ifdef SEDF_STATS
    if ( EDOM_INFO(d)->block_time_tot != 0 )
        printk(" pen=%"PRIu64"%%", (EDOM_INFO(d)->penalty_time_tot * 100) /
               EDOM_INFO(d)->block_time_tot);
    if ( EDOM_INFO(d)->block_tot != 0 )
        printk("\n   blks=%u sh=%u (%u%%) (shc=%u (%u%%) shex=%i "\
               "shexsl=%i) l=%u (%u%%) avg: b=%"PRIu64" p=%"PRIu64"",
               EDOM_INFO(d)->block_tot, EDOM_INFO(d)->short_block_tot,
               (EDOM_INFO(d)->short_block_tot * 100) 
               / EDOM_INFO(d)->block_tot, EDOM_INFO(d)->short_cont,
               (EDOM_INFO(d)->short_cont * 100) / EDOM_INFO(d)->block_tot,
               EDOM_INFO(d)->pen_extra_blocks,
               EDOM_INFO(d)->pen_extra_slices,
               EDOM_INFO(d)->long_block_tot,
               (EDOM_INFO(d)->long_block_tot * 100) / EDOM_INFO(d)->block_tot,
               (EDOM_INFO(d)->block_time_tot) / EDOM_INFO(d)->block_tot,
               (EDOM_INFO(d)->penalty_time_tot) / EDOM_INFO(d)->block_tot);
#endif
    printk("\n");
}


/* dumps all domains on hte specified cpu */
static void sedf_dump_cpu_state(int i)
{
    struct list_head      *list, *queue, *tmp;
    struct sedf_vcpu_info *d_inf;
    struct domain         *d;
    struct vcpu    *ed;
    int loop = 0;
 
    printk("now=%"PRIu64"\n",NOW());
    queue = RUNQ(i);
    printk("RUNQ rq %lx   n: %lx, p: %lx\n",  (unsigned long)queue,
           (unsigned long) queue->next, (unsigned long) queue->prev);
    list_for_each_safe ( list, tmp, queue )
    {
        printk("%3d: ",loop++);
        d_inf = list_entry(list, struct sedf_vcpu_info, list);
        sedf_dump_domain(d_inf->vcpu);
    }
 
    queue = WAITQ(i); loop = 0;
    printk("\nWAITQ rq %lx   n: %lx, p: %lx\n",  (unsigned long)queue,
           (unsigned long) queue->next, (unsigned long) queue->prev);
    list_for_each_safe ( list, tmp, queue )
    {
        printk("%3d: ",loop++);
        d_inf = list_entry(list, struct sedf_vcpu_info, list);
        sedf_dump_domain(d_inf->vcpu);
    }
 
    queue = EXTRAQ(i,EXTRA_PEN_Q); loop = 0;
    printk("\nEXTRAQ (penalty) rq %lx   n: %lx, p: %lx\n",
           (unsigned long)queue, (unsigned long) queue->next,
           (unsigned long) queue->prev);
    list_for_each_safe ( list, tmp, queue )
    {
        d_inf = list_entry(list, struct sedf_vcpu_info,
                           extralist[EXTRA_PEN_Q]);
        printk("%3d: ",loop++);
        sedf_dump_domain(d_inf->vcpu);
    }
 
    queue = EXTRAQ(i,EXTRA_UTIL_Q); loop = 0;
    printk("\nEXTRAQ (utilization) rq %lx   n: %lx, p: %lx\n",
           (unsigned long)queue, (unsigned long) queue->next,
           (unsigned long) queue->prev);
    list_for_each_safe ( list, tmp, queue )
    {
        d_inf = list_entry(list, struct sedf_vcpu_info,
                           extralist[EXTRA_UTIL_Q]);
        printk("%3d: ",loop++);
        sedf_dump_domain(d_inf->vcpu);
    }
 
    loop = 0;
    printk("\nnot on Q\n");

    for_each_domain ( d )
    {
        for_each_vcpu(d, ed)
        {
            if ( !__task_on_queue(ed) && (ed->processor == i) )
            {
                printk("%3d: ",loop++);
                sedf_dump_domain(ed);
            }
        }
    }
}


/* Adjusts periods and slices of the domains accordingly to their weights. */
static int sedf_adjust_weights(struct xen_domctl_scheduler_op *cmd)
{
    struct vcpu *p;
    struct domain      *d;
    int                 sumw[NR_CPUS] = { 0 };
    s_time_t            sumt[NR_CPUS] = { 0 };
 
    /* Sum across all weights. */
    for_each_domain( d )
    {
        for_each_vcpu( d, p )
        {
            if ( EDOM_INFO(p)->weight )
            {
                sumw[p->processor] += EDOM_INFO(p)->weight;
            }
            else
            {
                /*don't modify domains who don't have a weight, but sum
                  up the time they need, projected to a WEIGHT_PERIOD,
                  so that this time is not given to the weight-driven
                  domains*/
                /*check for overflows*/
                ASSERT((WEIGHT_PERIOD < ULONG_MAX) 
                       && (EDOM_INFO(p)->slice_orig < ULONG_MAX));
                sumt[p->processor] += 
                    (WEIGHT_PERIOD * EDOM_INFO(p)->slice_orig) / 
                    EDOM_INFO(p)->period_orig;
            }
        }
    }

    /* Adjust all slices (and periods) to the new weight. */
    for_each_domain( d )
    {
        for_each_vcpu ( d, p )
        {
            if ( EDOM_INFO(p)->weight )
            {
                EDOM_INFO(p)->period_orig = 
                    EDOM_INFO(p)->period  = WEIGHT_PERIOD;
                EDOM_INFO(p)->slice_orig  =
                    EDOM_INFO(p)->slice   = 
                    (EDOM_INFO(p)->weight *
                     (WEIGHT_PERIOD - WEIGHT_SAFETY - sumt[p->processor])) / 
                    sumw[p->processor];
            }
        }
    }

    return 0;
}


/* set or fetch domain scheduling parameters */
static int sedf_adjust(struct domain *p, struct xen_domctl_scheduler_op *op)
{
    struct vcpu *v;

    PRINT(2,"sedf_adjust was called, domain-id %i new period %"PRIu64" "
          "new slice %"PRIu64"\nlatency %"PRIu64" extra:%s\n",
          p->domain_id, op->u.sedf.period, op->u.sedf.slice,
          op->u.sedf.latency, (op->u.sedf.extratime)?"yes":"no");

    if ( op->cmd == XEN_DOMCTL_SCHEDOP_putinfo )
    {
        /* Check for sane parameters. */
        if ( !op->u.sedf.period && !op->u.sedf.weight )
            return -EINVAL;
        if ( op->u.sedf.weight )
        {
            if ( (op->u.sedf.extratime & EXTRA_AWARE) &&
                 (!op->u.sedf.period) )
            {
                /* Weight-driven domains with extratime only. */
                for_each_vcpu ( p, v )
                {
                    EDOM_INFO(v)->extraweight = op->u.sedf.weight;
                    EDOM_INFO(v)->weight = 0;
                    EDOM_INFO(v)->slice = 0;
                    EDOM_INFO(v)->period = WEIGHT_PERIOD;
                }
            }
            else
            {
                /* Weight-driven domains with real-time execution. */
                for_each_vcpu ( p, v )
                    EDOM_INFO(v)->weight = op->u.sedf.weight;
            }
        }
        else
        {
            /* Time-driven domains. */
            for_each_vcpu ( p, v )
            {
                /*
                 * Sanity checking: note that disabling extra weight requires
                 * that we set a non-zero slice.
                 */
                if ( (op->u.sedf.period > PERIOD_MAX) ||
                     (op->u.sedf.period < PERIOD_MIN) ||
                     (op->u.sedf.slice  > op->u.sedf.period) ||
                     (op->u.sedf.slice  < SLICE_MIN) )
                    return -EINVAL;
                EDOM_INFO(v)->weight = 0;
                EDOM_INFO(v)->extraweight = 0;
                EDOM_INFO(v)->period_orig = 
                    EDOM_INFO(v)->period  = op->u.sedf.period;
                EDOM_INFO(v)->slice_orig  = 
                    EDOM_INFO(v)->slice   = op->u.sedf.slice;
            }
        }

        if ( sedf_adjust_weights(op) )
            return -EINVAL;

        for_each_vcpu ( p, v )
        {
            EDOM_INFO(v)->status  = 
                (EDOM_INFO(v)->status &
                 ~EXTRA_AWARE) | (op->u.sedf.extratime & EXTRA_AWARE);
            EDOM_INFO(v)->latency = op->u.sedf.latency;
            extraq_check(v);
        }
    }
    else if ( op->cmd == XEN_DOMCTL_SCHEDOP_getinfo )
    {
        if ( p->vcpu[0] == NULL )
            return -EINVAL;
        op->u.sedf.period    = EDOM_INFO(p->vcpu[0])->period;
        op->u.sedf.slice     = EDOM_INFO(p->vcpu[0])->slice;
        op->u.sedf.extratime = EDOM_INFO(p->vcpu[0])->status & EXTRA_AWARE;
        op->u.sedf.latency   = EDOM_INFO(p->vcpu[0])->latency;
        op->u.sedf.weight    = EDOM_INFO(p->vcpu[0])->weight;
    }

    PRINT(2,"sedf_adjust_finished\n");
    return 0;
}

struct scheduler sched_sedf_def = {
    .name     = "Simple EDF Scheduler",
    .opt_name = "sedf",
    .sched_id = XEN_SCHEDULER_SEDF,
    
    .init_domain    = sedf_init_domain,
    .destroy_domain = sedf_destroy_domain,

    .init_vcpu      = sedf_init_vcpu,
    .destroy_vcpu   = sedf_destroy_vcpu,

    .do_schedule    = sedf_do_schedule,
    .pick_cpu       = sedf_pick_cpu,
    .dump_cpu_state = sedf_dump_cpu_state,
    .sleep          = sedf_sleep,
    .wake           = sedf_wake,
    .adjust         = sedf_adjust,
};

/*
 * Local variables:
 * mode: C
 * c-set-style: "BSD"
 * c-basic-offset: 4
 * tab-width: 4
 * indent-tabs-mode: nil
 * End:
 */