aboutsummaryrefslogtreecommitdiffstats
path: root/litmus/sched_mc2.c
blob: 6c02a56959b5063a09b280f506d480815e64bd86 (plain) (blame)
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
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
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
/*
 * litmus/sched_mc2.c
 *
 * Implementation of the Mixed-Criticality on MultiCore scheduler
 *
 * This plugin implements a scheduling algorithm proposed in 
 * "Mixed-Criticality Real-Time Scheduling for Multicore System" paper.
 */ 
 
#include <linux/percpu.h>
#include <linux/slab.h>
#include <asm/uaccess.h>

#include <litmus/sched_plugin.h>
#include <litmus/preempt.h>
#include <litmus/debug_trace.h>

#include <litmus/litmus.h>
#include <litmus/jobs.h>
#include <litmus/budget.h>
#include <litmus/litmus_proc.h>
#include <litmus/sched_trace.h>
#include <litmus/cache_proc.h>
#include <litmus/trace.h>

#include <litmus/mc2_common.h>
#include <litmus/reservation.h>
#include <litmus/polling_reservations.h>

#define BUDGET_ENFORCEMENT_AT_C 0

extern void do_partition(enum crit_level lv, int cpu);

/* _global_env - reservation container for level-C tasks*/
struct gmp_reservation_environment _global_env;

/* cpu_entry - keep track of a running task on a cpu
 * This state is used to decide the lowest priority cpu
 */
struct cpu_entry {
	struct task_struct *scheduled;
	lt_t deadline;
	int cpu;
	enum crit_level lv;
	/* if will_schedule is true, this cpu is already selected and
	   call mc2_schedule() soon. */
	bool will_schedule;
};

/* cpu_priority - a global state for choosing the lowest priority CPU */
struct cpu_priority {
	raw_spinlock_t lock;
	struct cpu_entry cpu_entries[NR_CPUS];
};

struct cpu_priority _lowest_prio_cpu;
	
/* mc2_task_state - a task state structure */
struct mc2_task_state {
	struct task_client res_info;
	/* if cpu == -1, this task is a global task (level C) */
	int cpu;
	bool has_departed;
	struct mc2_task mc2_param;
};

/* crit_entry - maintain the logically running job (ghost job) */
struct crit_entry {
	enum crit_level level;
	struct task_struct *running;
};

/* mc2_cpu_state - maintain the scheduled state and ghost jobs
 * timer : timer for partitioned tasks (level A and B)
 * g_timer : timer for global tasks (level C)
 */
struct mc2_cpu_state {
	raw_spinlock_t lock;

	struct sup_reservation_environment sup_env;
	struct hrtimer timer;

	int cpu;
	struct task_struct* scheduled;
	struct crit_entry crit_entries[NUM_CRIT_LEVELS];
};

static int resched_cpu[NR_CPUS];
static DEFINE_PER_CPU(struct mc2_cpu_state, mc2_cpu_state);
static int level_a_priorities[NR_CPUS];

#define cpu_state_for(cpu_id)	(&per_cpu(mc2_cpu_state, cpu_id))
#define local_cpu_state()	(this_cpu_ptr(&mc2_cpu_state))

/* get_mc2_state - get the task's state */
static struct mc2_task_state* get_mc2_state(struct task_struct *tsk)
{
	struct mc2_task_state* tinfo;
	
	tinfo = (struct mc2_task_state*)tsk_rt(tsk)->plugin_state;
	
	if (tinfo)
		return tinfo;
	else
		return NULL;
}

/* get_task_crit_level - return the criticaility level of a task */
static enum crit_level get_task_crit_level(struct task_struct *tsk)
{
	struct mc2_task *mp;
	
	if (!tsk || !is_realtime(tsk))
		return NUM_CRIT_LEVELS;
	
	mp = tsk_rt(tsk)->mc2_data;
	
	if (!mp)
		return NUM_CRIT_LEVELS;
	else
		return mp->crit;
}

/* task_depart - remove a task from its reservation
 *               If the job has remaining budget, convert it to a ghost job
 *               and update crit_entries[]
 *               
 * @job_complete	indicate whether job completes or not              
 */
static void task_departs(struct task_struct *tsk, int job_complete)
{
	struct mc2_task_state* tinfo = get_mc2_state(tsk);

	struct reservation* res = NULL;
	struct reservation_client *client = NULL;

	BUG_ON(!is_realtime(tsk));
	
	res    = tinfo->res_info.client.reservation;
	client = &tinfo->res_info.client;
	BUG_ON(!res);
	BUG_ON(!client);

    /* No ghost job handling, empty remaining budget */
	if (job_complete) {
		res->cur_budget = 0;
		sched_trace_task_completion(tsk, 0);
	}

	res->ops->client_departs(res, client, job_complete);
	tinfo->has_departed = true;
	TRACE_TASK(tsk, "Client departs with budget %llu at %llu\n", res->cur_budget, litmus_clock());
}

/* task_arrive - put a task into its reservation
 *               If the job was a ghost job, remove it from crit_entries[]
 */
static void task_arrives(struct mc2_cpu_state *state, struct task_struct *tsk)
{
	struct mc2_task_state* tinfo = get_mc2_state(tsk);
	struct reservation* res;
	struct reservation_client *client;
	enum crit_level lv = get_task_crit_level(tsk);

	res    = tinfo->res_info.client.reservation;
	client = &tinfo->res_info.client;

	tinfo->has_departed = false;

	res->ops->client_arrives(res, client);
	TRACE_TASK(tsk, "Client arrives at %llu\n", litmus_clock());
	
	if (lv != NUM_CRIT_LEVELS) {
		struct crit_entry *ce;
		ce = &state->crit_entries[lv];
		/* if the currrent task is a ghost job, remove it */
		if (ce->running == tsk)
			ce->running = NULL;
	}
}

/* get_lowest_prio_cpu - return the lowest priority cpu
 *                       This will be used for scheduling level-C tasks.
 *                       If all CPUs are running tasks which has
 *                       higher priority than level C, return NO_CPU.
 */
static int get_lowest_prio_cpu(lt_t priority)
{
	struct cpu_entry *ce;
	int cpu, ret = NO_CPU;
	lt_t latest_deadline = 0;
	
	ce = &_lowest_prio_cpu.cpu_entries[local_cpu_state()->cpu];
	if (!ce->will_schedule && !ce->scheduled) {
		TRACE("CPU %d (local) is the lowest!\n", ce->cpu);
		return ce->cpu;
	} else {
		TRACE("Local CPU will_schedule=%d, scheduled=(%s/%d)\n", ce->will_schedule, ce->scheduled ? (ce->scheduled)->comm : "null", ce->scheduled ? (ce->scheduled)->pid : 0);
	}

	for_each_online_cpu(cpu) {
		ce = &_lowest_prio_cpu.cpu_entries[cpu];
		/* If a CPU will call schedule() in the near future, we don't
		   return that CPU. */
		TRACE("CPU %d will_schedule=%d, scheduled=(%s/%d:%d)\n", cpu, ce->will_schedule,
	      ce->scheduled ? (ce->scheduled)->comm : "null",
	      ce->scheduled ? (ce->scheduled)->pid : 0,
	      ce->scheduled ? (ce->scheduled)->rt_param.job_params.job_no : 0);
		if (!ce->will_schedule) {
			if (!ce->scheduled) {
				/* Idle cpu, return this. */
				TRACE("CPU %d is the lowest!\n", ce->cpu);
				return ce->cpu;
			} else if (ce->lv == CRIT_LEVEL_C && 
			           ce->deadline > latest_deadline) {
				latest_deadline = ce->deadline;
				ret = ce->cpu;
			}
		}
	}		

	if (priority >= latest_deadline)
		ret = NO_CPU;
	
	TRACE("CPU %d is the lowest!\n", ret);

	return ret;
}

/* NOTE: drops state->lock */
/* mc2_update_timer_and_unlock - set a timer and g_timer and unlock 
 *                               Whenever res_env.current_time is updated,
 *                               we check next_scheduler_update and set 
 *                               a timer.
 *                               If there exist a global event which is 
 *                               not armed on any CPU and g_timer is not
 *                               active, set a g_timer for that event.
 */
static void mc2_update_timer_and_unlock(struct mc2_cpu_state *state)
{
	int local, cpus;
	lt_t update, now;
	struct next_timer_event *event, *next;
	int reschedule[NR_CPUS];
	
	for (cpus = 0; cpus<NR_CPUS; cpus++)
		reschedule[cpus] = 0;
	
	update = state->sup_env.next_scheduler_update;
	now = state->sup_env.env.current_time;

	/* Be sure we're actually running on the right core,
	 * as pres_update_timer() is also called from pres_task_resume(),
	 * which might be called on any CPU when a thread resumes.
	 */
	local = local_cpu_state() == state;

	raw_spin_lock(&_global_env.lock);
		
	list_for_each_entry_safe(event, next, &_global_env.next_events, list) {
		/* If the event time is already passed, we call schedule() on
		   the lowest priority cpu */
		if (event->next_update >= update) {
			break;
		}
		
		if (event->next_update < litmus_clock()) {
			if (event->timer_armed_on == NO_CPU) {
				struct reservation *res = gmp_find_by_id(&_global_env, event->id);
				int cpu = get_lowest_prio_cpu(res?res->priority:0);
				TRACE("GLOBAL EVENT PASSED!! poking CPU %d to reschedule\n", cpu);
				list_del(&event->list);
				kfree(event);
				if (cpu != NO_CPU) {
					_lowest_prio_cpu.cpu_entries[cpu].will_schedule = true;
					if (cpu == local_cpu_state()->cpu)
						litmus_reschedule_local();
					else
						reschedule[cpu] = 1;
				}
			}
		} else if (event->next_update < update && (event->timer_armed_on == NO_CPU || event->timer_armed_on == state->cpu)) {
			event->timer_armed_on = state->cpu;
			update = event->next_update;
			break;
		}
	}
	
	/* Must drop state lock before calling into hrtimer_start(), which
	 * may raise a softirq, which in turn may wake ksoftirqd. */
	raw_spin_unlock(&_global_env.lock);
	raw_spin_unlock(&state->lock);
		
	if (update <= now || reschedule[state->cpu]) {
		reschedule[state->cpu] = 0;
		litmus_reschedule(state->cpu);
	} else if (likely(local && update != SUP_NO_SCHEDULER_UPDATE)) {
		/* Reprogram only if not already set correctly. */
		if (!hrtimer_active(&state->timer) ||
		    ktime_to_ns(hrtimer_get_expires(&state->timer)) != update) {
			TRACE("canceling timer...at %llu\n", 
			      ktime_to_ns(hrtimer_get_expires(&state->timer)));
			hrtimer_cancel(&state->timer);
			TRACE("setting scheduler timer for %llu\n", update);
			/* We cannot use hrtimer_start() here because the
			 * wakeup flag must be set to zero. */
			__hrtimer_start_range_ns(&state->timer,
					ns_to_ktime(update),
					0 /* timer coalescing slack */,
					HRTIMER_MODE_ABS_PINNED,
					0 /* wakeup */);
			if (update < litmus_clock()) {
				/* uh oh, timer expired while trying to set it */
				TRACE("timer expired during setting "
				      "update:%llu now:%llu actual:%llu\n",
				      update, now, litmus_clock());
	 			/* The timer HW may not have been reprogrammed
	 			 * correctly; force rescheduling now. */
				litmus_reschedule(state->cpu);
			}
		}
	} else if (unlikely(!local && update != SUP_NO_SCHEDULER_UPDATE)) {
		/* Poke remote core only if timer needs to be set earlier than
		 * it is currently set.
		 */
		TRACE("mc2_update_timer for remote CPU %d (update=%llu, "
		      "active:%d, set:%llu)\n",
			state->cpu,
			update,
			hrtimer_active(&state->timer),
			ktime_to_ns(hrtimer_get_expires(&state->timer)));
		if (!hrtimer_active(&state->timer) ||
		    ktime_to_ns(hrtimer_get_expires(&state->timer)) > update) {
			TRACE("poking CPU %d so that it can update its "
			       "scheduling timer (active:%d, set:%llu)\n",
			       state->cpu,
			       hrtimer_active(&state->timer),
			       ktime_to_ns(hrtimer_get_expires(&state->timer)));
			raw_spin_lock(&state->lock);
			preempt_if_preemptable(state->scheduled, state->cpu);
			raw_spin_unlock(&state->lock);
			reschedule[state->cpu] = 0;
		}
	}
	for (cpus = 0; cpus<NR_CPUS; cpus++) {
		if (reschedule[cpus]) {
			litmus_reschedule(cpus);
		}
	}
}

/* update_cpu_prio - Update cpu's priority
 *                   When a cpu picks a new task, call this function
 *                   to update cpu priorities.
 */
static void update_cpu_prio(struct mc2_cpu_state *state)
{
	struct cpu_entry *ce = &_lowest_prio_cpu.cpu_entries[state->cpu];
	enum crit_level lv = get_task_crit_level(state->scheduled);
	
	if (!state->scheduled) {
		/* cpu is idle. */
		ce->scheduled = NULL;
		ce->deadline = ULLONG_MAX;
		ce->lv = NUM_CRIT_LEVELS;
	} else if (lv == CRIT_LEVEL_C) {
		ce->scheduled = state->scheduled;
		ce->deadline = get_deadline(state->scheduled);
		ce->lv = lv;
	} else if (lv < CRIT_LEVEL_C) {
		/* If cpu is running level A or B tasks, it is not eligible
		   to run level-C tasks */
		ce->scheduled = state->scheduled;
		ce->deadline = 0;
		ce->lv = lv;
	}
};

/* on_scheduling_timer - timer event for partitioned tasks
 */                       
static enum hrtimer_restart on_scheduling_timer(struct hrtimer *timer)
{
	unsigned long flags;
	enum hrtimer_restart restart = HRTIMER_NORESTART;
	struct mc2_cpu_state *state;
	lt_t update, now;
	int global_schedule_now;
	int reschedule[NR_CPUS];
	int cpus;
	
	for (cpus = 0; cpus<NR_CPUS; cpus++)
		reschedule[cpus] = 0;
	
	state = container_of(timer, struct mc2_cpu_state, timer);

	/* The scheduling timer should only fire on the local CPU, because
	 * otherwise deadlocks via timer_cancel() are possible.
	 * Note: this does not interfere with dedicated interrupt handling, as
	 * even under dedicated interrupt handling scheduling timers for
	 * budget enforcement must occur locally on each CPU.
	 */
	BUG_ON(state->cpu != raw_smp_processor_id());

	TS_ISR_START;
	
	TRACE("Timer fired at %llu\n", litmus_clock());
	raw_spin_lock_irqsave(&state->lock, flags);
	now = litmus_clock();
	sup_update_time(&state->sup_env, now);

	update = state->sup_env.next_scheduler_update;
	now = state->sup_env.env.current_time;

	if (update <= now) {
		litmus_reschedule_local();
	} else if (update != SUP_NO_SCHEDULER_UPDATE) {
		hrtimer_set_expires(timer, ns_to_ktime(update));
		restart = HRTIMER_RESTART;
	}

	raw_spin_lock(&_global_env.lock);
	global_schedule_now = gmp_update_time(&_global_env, now);
	
	BUG_ON(global_schedule_now < 0 || global_schedule_now > 4);
	
	/* Find the lowest cpu, and call reschedule */
	while (global_schedule_now--) {
		int cpu = get_lowest_prio_cpu(0);
		if (cpu != NO_CPU && _lowest_prio_cpu.cpu_entries[cpu].will_schedule == false) {
			_lowest_prio_cpu.cpu_entries[cpu].will_schedule = true;
			TRACE("LOWEST CPU = P%d\n", cpu);
			if (cpu == state->cpu && update > now)
				litmus_reschedule_local();
			else
				reschedule[cpu] = 1;
		}
	} 
	raw_spin_unlock(&_global_env.lock);
	
	raw_spin_unlock_irqrestore(&state->lock, flags);
	
	TS_ISR_END;
	
	for (cpus = 0; cpus<NR_CPUS; cpus++) {
		if (reschedule[cpus]) {
			litmus_reschedule(cpus);
		}
	}
	
	
	return restart;
}

/* mc2_complete_job - syscall backend for job completions
 */
static long mc2_complete_job(void)
{
	ktime_t next_release;
	long err;

	tsk_rt(current)->completed = 1;
	
	/* If this the first job instance, we need to reset replenish
	   time to the next release time */
	if (tsk_rt(current)->sporadic_release) {
		struct mc2_cpu_state *state;
		struct reservation_environment *env;
		struct mc2_task_state *tinfo;
		struct reservation *res = NULL;
		unsigned long flags;
		enum crit_level lv;

		preempt_disable();
		local_irq_save(flags);
		
		tinfo = get_mc2_state(current);
		lv = get_task_crit_level(current);
		
		if (lv < CRIT_LEVEL_C) {
			state = cpu_state_for(tinfo->cpu);
			raw_spin_lock(&state->lock);
			env = &(state->sup_env.env);
			res = sup_find_by_id(&state->sup_env, tinfo->mc2_param.res_id);
			env->time_zero = tsk_rt(current)->sporadic_release_time;
		}
		else if (lv == CRIT_LEVEL_C) {
			state = local_cpu_state();		
			raw_spin_lock(&state->lock);
			raw_spin_lock(&_global_env.lock);
			res = gmp_find_by_id(&_global_env, tinfo->mc2_param.res_id);
			_global_env.env.time_zero = tsk_rt(current)->sporadic_release_time;
		}
		else
			BUG();

		/* set next_replenishtime to synchronous release time */
		BUG_ON(!res);
		res->next_replenishment = tsk_rt(current)->sporadic_release_time;
		res->cur_budget = 0;
		res->env->change_state(res->env, res, RESERVATION_DEPLETED);

		if (lv == CRIT_LEVEL_C)
			raw_spin_unlock(&_global_env.lock);
		
		raw_spin_unlock(&state->lock);
		local_irq_restore(flags);
		preempt_enable();
	}
	
	sched_trace_task_completion(current, 0);		
	/* update the next release time and deadline */
	prepare_for_next_period(current);
	sched_trace_task_release(current);
	next_release = ns_to_ktime(get_release(current));
	preempt_disable();
	TRACE_CUR("next_release=%llu\n", get_release(current));
	if (get_release(current) > litmus_clock()) {
		/* sleep until next_release */
		set_current_state(TASK_INTERRUPTIBLE);
		preempt_enable_no_resched();
		err = schedule_hrtimeout(&next_release, HRTIMER_MODE_ABS);
	} else {
		/* release the next job immediately */
		err = 0;
		TRACE_CUR("TARDY: release=%llu now=%llu\n", get_release(current), litmus_clock());
		preempt_enable();
	}

	TRACE_CUR("mc2_complete_job returns at %llu\n", litmus_clock());

	tsk_rt(current)->completed = 0;
	return err;
}

/* mc2_dispatch - Select the next task to schedule.
 */
struct task_struct* mc2_dispatch(struct sup_reservation_environment* sup_env, struct mc2_cpu_state* state)
{
	struct reservation *res, *next;
	struct task_struct *tsk = NULL;
	struct crit_entry *ce;
	enum crit_level lv;
	lt_t time_slice;

	list_for_each_entry_safe(res, next, &sup_env->active_reservations, list) {
		if (res->state == RESERVATION_ACTIVE) {
			tsk = res->ops->dispatch_client(res, &time_slice);
			if (likely(tsk)) {
				lv = get_task_crit_level(tsk);
				if (lv == NUM_CRIT_LEVELS) {
					sup_scheduler_update_after(sup_env, res->cur_budget);
					return tsk;
				} else {
					ce = &state->crit_entries[lv];
					sup_scheduler_update_after(sup_env, res->cur_budget);
					res->blocked_by_ghost = 0;
					res->is_ghost = NO_CPU;
					return tsk;
				}
			}
		}
	}
	
	return NULL;
}

struct task_struct* mc2_global_dispatch(struct mc2_cpu_state* state)
{
	struct reservation *res, *next;
	struct task_struct *tsk = NULL;

	enum crit_level lv;
	lt_t time_slice;
	
	list_for_each_entry_safe(res, next, &_global_env.active_reservations, list) {
		BUG_ON(!res);
		if (res->state == RESERVATION_ACTIVE && res->scheduled_on == NO_CPU) {
			tsk = res->ops->dispatch_client(res, &time_slice);
			if (likely(tsk)) {
				lv = get_task_crit_level(tsk);
				if (lv == NUM_CRIT_LEVELS) {
#if BUDGET_ENFORCEMENT_AT_C			
					gmp_add_event_after(&_global_env, res->cur_budget, res->id, EVENT_DRAIN);
#endif
					res->event_added = 1;
					res->blocked_by_ghost = 0;
					res->is_ghost = NO_CPU;
					res->scheduled_on = state->cpu;
					return tsk;
				} else if (lv == CRIT_LEVEL_C) {
#if BUDGET_ENFORCEMENT_AT_C
						gmp_add_event_after(&_global_env, res->cur_budget, res->id, EVENT_DRAIN);
#endif
						res->event_added = 1;
						res->blocked_by_ghost = 0;
						res->is_ghost = NO_CPU;
						res->scheduled_on = state->cpu;
						return tsk;
				} else {
					BUG();
				}
			}
		}
	}
	
	return NULL;
}

static inline void pre_schedule(struct task_struct *prev, int cpu)
{
	TS_SCHED_A_START;
	TS_SCHED_C_START;
	
	if (!prev || !is_realtime(prev))
		return;
	
	do_partition(CRIT_LEVEL_C, cpu);
}

static inline void post_schedule(struct task_struct *next, int cpu)
{
	enum crit_level lev;
	if ((!next) || !is_realtime(next))
		return;

	lev = get_task_crit_level(next);
	do_partition(lev, cpu);
	
	switch(lev) {
		case CRIT_LEVEL_A:
		case CRIT_LEVEL_B:
			TS_SCHED_A_END(next);
			break;
		case CRIT_LEVEL_C:
			TS_SCHED_C_END(next);
			break;
		default:
			break;
	}
	
}

/* mc2_schedule - main scheduler function. pick the next task to run
 */
static struct task_struct* mc2_schedule(struct task_struct * prev)
{
	int np, blocks, exists, preempt, to_schedule;
	/* next == NULL means "schedule background work". */
	lt_t now;
	struct mc2_cpu_state *state = local_cpu_state();
	
	pre_schedule(prev, state->cpu);
	
	raw_spin_lock(&state->lock);
	
	if (state->scheduled && state->scheduled != prev)
		printk(KERN_ALERT "BUG1!!!!!!!! %s %s\n", state->scheduled ? (state->scheduled)->comm : "null", prev ? (prev)->comm : "null");
	if (state->scheduled && !is_realtime(prev))
		printk(KERN_ALERT "BUG2!!!!!!!! \n");

	/* (0) Determine state */
	exists = state->scheduled != NULL;
	blocks = exists && !is_current_running();
	np = exists && is_np(state->scheduled);
	
	raw_spin_lock(&_global_env.lock);
	preempt = resched_cpu[state->cpu];
	resched_cpu[state->cpu] = 0;
	raw_spin_unlock(&_global_env.lock);

	/* update time */
	state->sup_env.will_schedule = true;

	now = litmus_clock();
	sup_update_time(&state->sup_env, now);

	if (is_realtime(current) && blocks) {
		if (get_task_crit_level(current) == CRIT_LEVEL_C)
			raw_spin_lock(&_global_env.lock);
		task_departs(current, is_completed(current));
		if (get_task_crit_level(current) == CRIT_LEVEL_C)
			raw_spin_unlock(&_global_env.lock);
	}
	
	/* figure out what to schedule next */
	if (!np)
		state->scheduled = mc2_dispatch(&state->sup_env, state);

	if (!state->scheduled) {
		raw_spin_lock(&_global_env.lock);
		to_schedule = gmp_update_time(&_global_env, now);
		state->scheduled = mc2_global_dispatch(state);
		_lowest_prio_cpu.cpu_entries[state->cpu].will_schedule = false;
		update_cpu_prio(state);
		raw_spin_unlock(&_global_env.lock);
	} else {
		raw_spin_lock(&_global_env.lock);
		_lowest_prio_cpu.cpu_entries[state->cpu].will_schedule = false;
		update_cpu_prio(state);
		raw_spin_unlock(&_global_env.lock);
	}
	
	/* Notify LITMUS^RT core that we've arrived at a scheduling decision. */
	sched_state_task_picked();

	/* program scheduler timer */
	state->sup_env.will_schedule = false;
		
	/* NOTE: drops state->lock */
	mc2_update_timer_and_unlock(state);

	if (prev != state->scheduled && is_realtime(prev)) {
		struct mc2_task_state* tinfo = get_mc2_state(prev);
		struct reservation* res = tinfo->res_info.client.reservation;
		TRACE_TASK(prev, "PREV JOB scheduled_on = P%d\n", res->scheduled_on);
		res->scheduled_on = NO_CPU;
		TRACE_TASK(prev, "descheduled.\n");
		/* if prev is preempted and a global task, find the lowest cpu and reschedule */
		if (tinfo->has_departed == false && get_task_crit_level(prev) == CRIT_LEVEL_C) {
			int cpu;
			raw_spin_lock(&_global_env.lock);
			cpu = get_lowest_prio_cpu(res?res->priority:0);
			TRACE("LEVEL-C TASK PREEMPTED!! poking CPU %d to reschedule\n", cpu);
			if (cpu != NO_CPU && _lowest_prio_cpu.cpu_entries[cpu].will_schedule == false) {
				_lowest_prio_cpu.cpu_entries[cpu].will_schedule = true;
				resched_cpu[cpu] = 1;
			}
			raw_spin_unlock(&_global_env.lock);
		}
	}
	
	if (to_schedule != 0) {
		raw_spin_lock(&_global_env.lock);
		while (to_schedule--) {
			int cpu = get_lowest_prio_cpu(0);
			if (cpu != NO_CPU && _lowest_prio_cpu.cpu_entries[cpu].will_schedule == false) {
				_lowest_prio_cpu.cpu_entries[cpu].will_schedule = true;
				resched_cpu[cpu] = 1;
			}
		}
		raw_spin_unlock(&_global_env.lock);	
	}

	if (state->scheduled) {
		TRACE_TASK(state->scheduled, "scheduled.\n");
	}
	
	post_schedule(state->scheduled, state->cpu);
	
	return state->scheduled;
}

/* mc2_task_resume - Called when the state of tsk changes back to 
 *                   TASK_RUNNING. We need to requeue the task.
 */
static void mc2_task_resume(struct task_struct  *tsk)
{
	unsigned long flags;
	struct mc2_task_state* tinfo = get_mc2_state(tsk);
	struct mc2_cpu_state *state;

	TRACE_TASK(tsk, "thread wakes up at %llu\n", litmus_clock());

	local_irq_save(flags);
	if (tinfo->cpu != -1)
		state = cpu_state_for(tinfo->cpu);
	else
		state = local_cpu_state();

	/* Requeue only if self-suspension was already processed. */
	if (tinfo->has_departed)
	{
		/* We don't want to consider jobs before synchronous releases */
		if (tsk_rt(tsk)->job_params.job_no > 5) {
			switch(get_task_crit_level(tsk)) {
				case CRIT_LEVEL_A:
					TS_RELEASE_LATENCY_A(get_release(tsk));
					break;
				case CRIT_LEVEL_B:
					TS_RELEASE_LATENCY_B(get_release(tsk));
					break;
				case CRIT_LEVEL_C:
					TS_RELEASE_LATENCY_C(get_release(tsk));
					break;
				default:
					break;
			}
		}

		raw_spin_lock(&state->lock);
		/* Assumption: litmus_clock() is synchronized across cores,
		 * since we might not actually be executing on tinfo->cpu
		 * at the moment. */
		if (tinfo->cpu != -1) {
			sup_update_time(&state->sup_env, litmus_clock());
			task_arrives(state, tsk);
		} else {
			raw_spin_lock(&_global_env.lock);
			gmp_update_time(&_global_env, litmus_clock());
			task_arrives(state, tsk);
			raw_spin_unlock(&_global_env.lock);
		}
			
		/* NOTE: drops state->lock */
		TRACE_TASK(tsk, "mc2_resume()\n");
		mc2_update_timer_and_unlock(state);	
	} else {
		TRACE_TASK(tsk, "resume event ignored, still scheduled\n");
	}

	local_irq_restore(flags);
}


/* mc2_admit_task - Setup mc2 task parameters
 */
static long mc2_admit_task(struct task_struct *tsk)
{
	long err = -ESRCH;
	unsigned long flags;
	struct reservation *res;
	struct mc2_cpu_state *state;
	struct mc2_task_state *tinfo = kzalloc(sizeof(*tinfo), GFP_ATOMIC);
	struct mc2_task *mp = tsk_rt(tsk)->mc2_data;
	enum crit_level lv;
	
	if (!tinfo)
		return -ENOMEM;

	if (!mp) {
		printk(KERN_ERR "mc2_admit_task: criticality level has not been set\n");
		return err;
	}
	
	lv = mp->crit;
	preempt_disable();

	if (lv < CRIT_LEVEL_C) {
		state = cpu_state_for(task_cpu(tsk));
		raw_spin_lock_irqsave(&state->lock, flags);

		res = sup_find_by_id(&state->sup_env, mp->res_id);

		/* found the appropriate reservation */
		if (res) {
			TRACE_TASK(tsk, "SUP FOUND RES ID\n");
			tinfo->mc2_param.crit = mp->crit;
			tinfo->mc2_param.res_id = mp->res_id;
		
			/* initial values */
			err = mc2_task_client_init(&tinfo->res_info, &tinfo->mc2_param, tsk, res);
			tinfo->cpu = task_cpu(tsk);
			tinfo->has_departed = true;
			tsk_rt(tsk)->plugin_state = tinfo;

			/* disable LITMUS^RT's per-thread budget enforcement */
			tsk_rt(tsk)->task_params.budget_policy = NO_ENFORCEMENT;
		}

		raw_spin_unlock_irqrestore(&state->lock, flags);
	} else if (lv == CRIT_LEVEL_C) {
		state = local_cpu_state();
		raw_spin_lock_irqsave(&state->lock, flags);
		raw_spin_lock(&_global_env.lock);
		
		res = gmp_find_by_id(&_global_env, mp->res_id);

		/* found the appropriate reservation (or vCPU) */
		if (res) {
			TRACE_TASK(tsk, "GMP FOUND RES ID\n");
			tinfo->mc2_param.crit = mp->crit;
			tinfo->mc2_param.res_id = mp->res_id;
			
			/* initial values */
			err = mc2_task_client_init(&tinfo->res_info, &tinfo->mc2_param, tsk, res);
			tinfo->cpu = -1;
			tinfo->has_departed = true;
			tsk_rt(tsk)->plugin_state = tinfo;

			/* disable LITMUS^RT's per-thread budget enforcement */
			tsk_rt(tsk)->task_params.budget_policy = NO_ENFORCEMENT;
		}

		raw_spin_unlock(&_global_env.lock);
		raw_spin_unlock_irqrestore(&state->lock, flags);	
	}
	
	preempt_enable();

	if (err)
		kfree(tinfo);

	return err;
}

/* mc2_task_new - A new real-time job is arrived. Release the next job
 *                at the next reservation replenish time
 */
static void mc2_task_new(struct task_struct *tsk, int on_runqueue,
			  int is_running)
{
	unsigned long flags;
	struct mc2_task_state* tinfo = get_mc2_state(tsk);
	struct mc2_cpu_state *state; // = cpu_state_for(tinfo->cpu);
	struct reservation *res;
	enum crit_level lv = get_task_crit_level(tsk);
	lt_t release = 0;

	TRACE_TASK(tsk, "new RT task %llu (on_rq:%d, running:%d)\n",
		   litmus_clock(), on_runqueue, is_running);

	if (tinfo->cpu == -1)
		state = local_cpu_state();
	else 
		state = cpu_state_for(tinfo->cpu);

	
	if (is_running) {
		state->scheduled = tsk;
		/* make sure this task should actually be running */
		litmus_reschedule_local();
	}

	/* acquire the lock protecting the state and disable interrupts */
	local_irq_save(flags);
	raw_spin_lock(&state->lock);

	if (lv == CRIT_LEVEL_C) {
		raw_spin_lock(&_global_env.lock);
		res = gmp_find_by_id(&_global_env, tinfo->mc2_param.res_id);
	}
	else {
		res = sup_find_by_id(&state->sup_env, tinfo->mc2_param.res_id);
	}
	release = res->next_replenishment;
	
	if (on_runqueue || is_running) {
		/* Assumption: litmus_clock() is synchronized across cores
		 * [see comment in pres_task_resume()] */
		if (lv == CRIT_LEVEL_C) {
			gmp_update_time(&_global_env, litmus_clock());
		}
		else
			sup_update_time(&state->sup_env, litmus_clock());
		task_arrives(state, tsk);
		if (lv == CRIT_LEVEL_C)
			raw_spin_unlock(&_global_env.lock);
		/* NOTE: drops state->lock */
		TRACE("mc2_new()\n");
		
		mc2_update_timer_and_unlock(state);
	} else {
		if (lv == CRIT_LEVEL_C)
			raw_spin_unlock(&_global_env.lock);
		raw_spin_unlock(&state->lock);
	}
	local_irq_restore(flags);
	
	if (!release) {
		TRACE_TASK(tsk, "mc2_task_new() next_release = %llu\n", release);
	}
	else
		TRACE_TASK(tsk, "mc2_task_new() next_release = NULL\n");
}

/* mc2_reservation_destroy - reservation_destroy system call backend
 */
static long mc2_reservation_destroy(unsigned int reservation_id, int cpu)
{
	long ret = -EINVAL;
	struct mc2_cpu_state *state;
	struct reservation *res = NULL, *next;
	struct sup_reservation_environment *sup_env;
	int found = 0;
	unsigned long flags;
	
	if (cpu == -1) {
		/* if the reservation is global reservation */
		local_irq_save(flags);
		raw_spin_lock(&_global_env.lock);
		
		list_for_each_entry_safe(res, next, &_global_env.depleted_reservations, list) {
			if (res->id == reservation_id) {
				list_del(&res->list);
				kfree(res);
				found = 1;
				ret = 0;
			}
		}
		if (!found) {
			list_for_each_entry_safe(res, next, &_global_env.inactive_reservations, list) {
				if (res->id == reservation_id) {
					list_del(&res->list);
					kfree(res);
					found = 1;
					ret = 0;
				}
			}
		}
		if (!found) {
			list_for_each_entry_safe(res, next, &_global_env.active_reservations, list) {
				if (res->id == reservation_id) {
					list_del(&res->list);
					kfree(res);
					found = 1;
					ret = 0;
				}
			}
		}

		raw_spin_unlock(&_global_env.lock);
		local_irq_restore(flags);
	} else {
		/* if the reservation is partitioned reservation */
		state = cpu_state_for(cpu);
		local_irq_save(flags);
		raw_spin_lock(&state->lock);
		
		sup_env = &state->sup_env;
		list_for_each_entry_safe(res, next, &sup_env->depleted_reservations, list) {
			if (res->id == reservation_id) {
				list_del(&res->list);
				kfree(res);
				found = 1;
				ret = 0;
			}
		}
		if (!found) {
			list_for_each_entry_safe(res, next, &sup_env->inactive_reservations, list) {
				if (res->id == reservation_id) {
					list_del(&res->list);
					kfree(res);
					found = 1;
					ret = 0;
				}
			}
		}
		if (!found) {
			list_for_each_entry_safe(res, next, &sup_env->active_reservations, list) {
				if (res->id == reservation_id) {
					list_del(&res->list);
					kfree(res);
					found = 1;
					ret = 0;
				}
			}
		}

		raw_spin_unlock(&state->lock);
		local_irq_restore(flags);
	}
	
	TRACE("Rerservation destroyed ret = %d\n", ret);
	return ret;
}

/* mc2_task_exit - Task became a normal task (not real-time task)
 */
static void mc2_task_exit(struct task_struct *tsk)
{
	unsigned long flags;
	struct mc2_task_state* tinfo = get_mc2_state(tsk);
	struct mc2_cpu_state *state;
	enum crit_level lv = tinfo->mc2_param.crit;
	struct crit_entry* ce;
	int cpu;

	local_irq_save(flags);
	if (tinfo->cpu != -1)
		state = cpu_state_for(tinfo->cpu);
	else 
		state = local_cpu_state();
	
	raw_spin_lock(&state->lock);
	
	if (state->scheduled == tsk)
		state->scheduled = NULL;

	ce = &state->crit_entries[lv];
	if (ce->running == tsk)
		ce->running = NULL;
	
	/* remove from queues */
	if (is_running(tsk)) {
		/* Assumption: litmus_clock() is synchronized across cores
		 * [see comment in pres_task_resume()] */
		
		/* update both global and partitioned */
		if (lv < CRIT_LEVEL_C) {
			sup_update_time(&state->sup_env, litmus_clock());
		}
		else if (lv == CRIT_LEVEL_C) {
			raw_spin_lock(&_global_env.lock);
			gmp_update_time(&_global_env, litmus_clock());
		}
		task_departs(tsk, 0);
		if (lv == CRIT_LEVEL_C)
			raw_spin_unlock(&_global_env.lock);
		
		/* NOTE: drops state->lock */
		TRACE("mc2_exit()\n");

		mc2_update_timer_and_unlock(state);	
	} else {
		raw_spin_unlock(&state->lock);
		
	}

	if (lv == CRIT_LEVEL_C) {
		for_each_online_cpu(cpu) {
			state = cpu_state_for(cpu);
			if (state == local_cpu_state())
				continue;
			raw_spin_lock(&state->lock);
			
			if (state->scheduled == tsk)
				state->scheduled = NULL;
			
			ce = &state->crit_entries[lv];
			if (ce->running == tsk)
				ce->running = NULL;
			
			raw_spin_unlock(&state->lock);
		}
	}
	
	local_irq_restore(flags);
	
	kfree(tsk_rt(tsk)->plugin_state);
	tsk_rt(tsk)->plugin_state = NULL;
	kfree(tsk_rt(tsk)->mc2_data);
	tsk_rt(tsk)->mc2_data = NULL;
}

/* create_polling_reservation - create a new polling reservation
 */
static long create_polling_reservation(
	int res_type,
	struct reservation_config *config)
{
	struct mc2_cpu_state *state;
	struct reservation* res;
	struct polling_reservation *pres;
	unsigned long flags;
	int use_edf  = config->priority == LITMUS_NO_PRIORITY;
	int periodic =  res_type == PERIODIC_POLLING;
	long err = -EINVAL;

	/* sanity checks */
	if (config->polling_params.budget >
	    config->polling_params.period) {
		printk(KERN_ERR "invalid polling reservation (%u): "
		       "budget > period\n", config->id);
		return -EINVAL;
	}
	if (config->polling_params.budget >
	    config->polling_params.relative_deadline
	    && config->polling_params.relative_deadline) {
		printk(KERN_ERR "invalid polling reservation (%u): "
		       "budget > deadline\n", config->id);
		return -EINVAL;
	}
	if (config->polling_params.offset >
	    config->polling_params.period) {
		printk(KERN_ERR "invalid polling reservation (%u): "
		       "offset > period\n", config->id);
		return -EINVAL;
	}

	/* Allocate before we grab a spin lock.
	 * Todo: would be nice to use a core-local allocation.
	 */
	pres = kzalloc(sizeof(*pres), GFP_KERNEL);
	if (!pres)
		return -ENOMEM;

	if (config->cpu != -1) {
		state = cpu_state_for(config->cpu);
		raw_spin_lock_irqsave(&state->lock, flags);

		res = sup_find_by_id(&state->sup_env, config->id);
		if (!res) {
			polling_reservation_init(pres, use_edf, periodic,
				config->polling_params.budget,
				config->polling_params.period,
				config->polling_params.relative_deadline,
				config->polling_params.offset);
			pres->res.id = config->id;
			pres->res.blocked_by_ghost = 0;
			pres->res.is_ghost = NO_CPU;
			if (!use_edf)
				pres->res.priority = config->priority;
			sup_add_new_reservation(&state->sup_env, &pres->res);
			err = config->id;
			TRACE_CUR("reservation created R%d priority : %llu\n", config->id, pres->res.priority);
		} else {
			err = -EEXIST;
		}

		raw_spin_unlock_irqrestore(&state->lock, flags);

	} else {
		raw_spin_lock_irqsave(&_global_env.lock, flags);
		
		res = gmp_find_by_id(&_global_env, config->id);
		if (!res) {
			polling_reservation_init(pres, use_edf, periodic,
				config->polling_params.budget,
				config->polling_params.period,
				config->polling_params.relative_deadline,
				config->polling_params.offset);
			pres->res.id = config->id;
			pres->res.blocked_by_ghost = 0;
			pres->res.scheduled_on = NO_CPU;
			pres->res.is_ghost = NO_CPU;
			if (!use_edf)
				pres->res.priority = config->priority;
			gmp_add_new_reservation(&_global_env, &pres->res);
			err = config->id;
		} else {
			err = -EEXIST;
		}
		raw_spin_unlock_irqrestore(&_global_env.lock, flags);		
	}
	
	if (err < 0)
		kfree(pres);

	return err;
}

#define MAX_INTERVALS 1024

/* create_table_driven_reservation - create a table_driven reservation
 */
static long create_table_driven_reservation(
	struct reservation_config *config)
{
	struct mc2_cpu_state *state;
	struct reservation* res;
	struct table_driven_reservation *td_res = NULL;
	struct lt_interval *slots = NULL;
	size_t slots_size;
	unsigned int i, num_slots;
	unsigned long flags;
	long err = -EINVAL;


	if (!config->table_driven_params.num_intervals) {
		printk(KERN_ERR "invalid table-driven reservation (%u): "
		       "no intervals\n", config->id);
		return -EINVAL;
	}

	if (config->table_driven_params.num_intervals > MAX_INTERVALS) {
		printk(KERN_ERR "invalid table-driven reservation (%u): "
		       "too many intervals (max: %d)\n", config->id, MAX_INTERVALS);
		return -EINVAL;
	}

	num_slots = config->table_driven_params.num_intervals;
	slots_size = sizeof(slots[0]) * num_slots;
	slots = kzalloc(slots_size, GFP_KERNEL);
	if (!slots)
		return -ENOMEM;

	td_res = kzalloc(sizeof(*td_res), GFP_KERNEL);
	if (!td_res)
		err = -ENOMEM;
	else
		err = copy_from_user(slots,
			config->table_driven_params.intervals, slots_size);

	if (!err) {
		/* sanity checks */
		for (i = 0; !err && i < num_slots; i++)
			if (slots[i].end <= slots[i].start) {
				printk(KERN_ERR
				       "invalid table-driven reservation (%u): "
				       "invalid interval %u => [%llu, %llu]\n",
				       config->id, i,
				       slots[i].start, slots[i].end);
				err = -EINVAL;
			}

		for (i = 0; !err && i + 1 < num_slots; i++)
			if (slots[i + 1].start <= slots[i].end) {
				printk(KERN_ERR
				       "invalid table-driven reservation (%u): "
				       "overlapping intervals %u, %u\n",
				       config->id, i, i + 1);
				err = -EINVAL;
			}

		if (slots[num_slots - 1].end >
			config->table_driven_params.major_cycle_length) {
			printk(KERN_ERR
				"invalid table-driven reservation (%u): last "
				"interval ends past major cycle %llu > %llu\n",
				config->id,
				slots[num_slots - 1].end,
				config->table_driven_params.major_cycle_length);
			err = -EINVAL;
		}
	}

	if (!err) {
		state = cpu_state_for(config->cpu);
		raw_spin_lock_irqsave(&state->lock, flags);

		res = sup_find_by_id(&state->sup_env, config->id);
		if (!res) {
			table_driven_reservation_init(td_res,
				config->table_driven_params.major_cycle_length,
				slots, num_slots);
			td_res->res.id = config->id;
			td_res->res.priority = config->priority;
			td_res->res.blocked_by_ghost = 0;
			sup_add_new_reservation(&state->sup_env, &td_res->res);
			err = config->id;
		} else {
			err = -EEXIST;
		}

		raw_spin_unlock_irqrestore(&state->lock, flags);
	}

	if (err < 0) {
		kfree(slots);
		kfree(td_res);
	}

	return err;
}

/* mc2_reservation_create - reservation_create system call backend
 */
static long mc2_reservation_create(int res_type, void* __user _config)
{
	long ret = -EINVAL;
	struct reservation_config config;

	TRACE("Attempt to create reservation (%d)\n", res_type);

	if (copy_from_user(&config, _config, sizeof(config)))
		return -EFAULT;

	if (config.cpu != -1) {
		if (config.cpu < 0 || !cpu_online(config.cpu)) {
			printk(KERN_ERR "invalid polling reservation (%u): "
				   "CPU %d offline\n", config.id, config.cpu);
			return -EINVAL;
		}
	}

	switch (res_type) {
		case PERIODIC_POLLING:
		case SPORADIC_POLLING:
			ret = create_polling_reservation(res_type, &config);
			break;

		case TABLE_DRIVEN:
			ret = create_table_driven_reservation(&config);
			break;

		default:
			return -EINVAL;
	};

	return ret;
}

static struct domain_proc_info mc2_domain_proc_info;

static long mc2_get_domain_proc_info(struct domain_proc_info **ret)
{
	*ret = &mc2_domain_proc_info;
	return 0;
}

static void mc2_setup_domain_proc(void)
{
	int i, cpu;
	int num_rt_cpus = num_online_cpus();

	struct cd_mapping *cpu_map, *domain_map;

	memset(&mc2_domain_proc_info, sizeof(mc2_domain_proc_info), 0);
	init_domain_proc_info(&mc2_domain_proc_info, num_rt_cpus, num_rt_cpus);
	mc2_domain_proc_info.num_cpus = num_rt_cpus;
	mc2_domain_proc_info.num_domains = num_rt_cpus;

	i = 0;
	for_each_online_cpu(cpu) {
		cpu_map = &mc2_domain_proc_info.cpu_to_domains[i];
		domain_map = &mc2_domain_proc_info.domain_to_cpus[i];

		cpu_map->id = cpu;
		domain_map->id = i;
		cpumask_set_cpu(i, cpu_map->mask);
		cpumask_set_cpu(cpu, domain_map->mask);
		++i;
	}
}

static long mc2_activate_plugin(void)
{
	int cpu, lv;
	struct mc2_cpu_state *state;
	struct cpu_entry *ce;

	gmp_init(&_global_env);
	raw_spin_lock_init(&_lowest_prio_cpu.lock);
	
	for_each_online_cpu(cpu) {
		TRACE("Initializing CPU%d...\n", cpu);

		resched_cpu[cpu] = 0;
		level_a_priorities[cpu] = 0;
		state = cpu_state_for(cpu);
		ce = &_lowest_prio_cpu.cpu_entries[cpu];
		
		ce->cpu = cpu;
		ce->scheduled = NULL;
		ce->deadline = ULLONG_MAX;
		ce->lv = NUM_CRIT_LEVELS;
		ce->will_schedule = false;

		raw_spin_lock_init(&state->lock);
		state->cpu = cpu;
		state->scheduled = NULL;
		for (lv = 0; lv < NUM_CRIT_LEVELS; lv++) {
			struct crit_entry *cr_entry = &state->crit_entries[lv];
			cr_entry->level = lv;
			cr_entry->running = NULL;
		}
		sup_init(&state->sup_env);

		hrtimer_init(&state->timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
		state->timer.function = on_scheduling_timer;
	}

	mc2_setup_domain_proc();

	return 0;
}

static void mc2_finish_switch(struct task_struct *prev)
{
	int cpus;
	enum crit_level lv = get_task_crit_level(prev);
	struct mc2_cpu_state *state = local_cpu_state();
	
	state->scheduled = is_realtime(current) ? current : NULL;
	if (lv == CRIT_LEVEL_C) {
		for (cpus = 0; cpus<NR_CPUS; cpus++) {
			if (resched_cpu[cpus]) {
				litmus_reschedule(cpus);
			}
		}
	}
}

static long mc2_deactivate_plugin(void)
{
	int cpu;
	struct mc2_cpu_state *state;
	struct reservation *res;
	struct next_timer_event *event;
	struct cpu_entry *ce;
	
	for_each_online_cpu(cpu) {
		state = cpu_state_for(cpu);
		raw_spin_lock(&state->lock);

		hrtimer_cancel(&state->timer);

		ce = &_lowest_prio_cpu.cpu_entries[cpu];
		
		ce->cpu = cpu;
		ce->scheduled = NULL;
		ce->deadline = ULLONG_MAX;
		ce->lv = NUM_CRIT_LEVELS;
		ce->will_schedule = false;

		/* Delete all reservations --- assumes struct reservation
		 * is prefix of containing struct. */

		while (!list_empty(&state->sup_env.active_reservations)) {
			res = list_first_entry(
				&state->sup_env.active_reservations,
			        struct reservation, list);
			list_del(&res->list);
			kfree(res);
		}

		while (!list_empty(&state->sup_env.inactive_reservations)) {
			res = list_first_entry(
				&state->sup_env.inactive_reservations,
			        struct reservation, list);
			list_del(&res->list);
			kfree(res);
		}

		while (!list_empty(&state->sup_env.depleted_reservations)) {
			res = list_first_entry(
				&state->sup_env.depleted_reservations,
			        struct reservation, list);
			list_del(&res->list);
			kfree(res);
		}

		raw_spin_unlock(&state->lock);
	}

	raw_spin_lock(&_global_env.lock);
	
	while (!list_empty(&_global_env.active_reservations)) {
		res = list_first_entry(
			&_global_env.active_reservations,
				struct reservation, list);
		list_del(&res->list);
		kfree(res);
	}

	while (!list_empty(&_global_env.inactive_reservations)) {
		res = list_first_entry(
			&_global_env.inactive_reservations,
				struct reservation, list);
		list_del(&res->list);
		kfree(res);
	}

	while (!list_empty(&_global_env.depleted_reservations)) {
		res = list_first_entry(
			&_global_env.depleted_reservations,
				struct reservation, list);
		list_del(&res->list);
		kfree(res);
	}
	
	while (!list_empty(&_global_env.next_events)) {
		event = list_first_entry(
			&_global_env.next_events,
				struct next_timer_event, list);
		list_del(&event->list);
		kfree(event);
	}
	
	raw_spin_unlock(&_global_env.lock);
	
	destroy_domain_proc_info(&mc2_domain_proc_info);
	return 0;
}

static struct sched_plugin mc2_plugin = {
	.plugin_name			= "MC2",
	.schedule				= mc2_schedule,
	.finish_switch			= mc2_finish_switch,
	.task_wake_up			= mc2_task_resume,
	.admit_task				= mc2_admit_task,
	.task_new				= mc2_task_new,
	.task_exit				= mc2_task_exit,
	.complete_job           = mc2_complete_job,
	.get_domain_proc_info   = mc2_get_domain_proc_info,
	.activate_plugin		= mc2_activate_plugin,
	.deactivate_plugin      = mc2_deactivate_plugin,
	.reservation_create     = mc2_reservation_create,
	.reservation_destroy	= mc2_reservation_destroy,
};

static int __init init_mc2(void)
{
	return register_sched_plugin(&mc2_plugin);
}

module_init(init_mc2);