summaryrefslogtreecommitdiffstats
path: root/sys/kern/sched_4bsd.c
blob: 53fca8a777d4b258dd9b42fef28f1b7a2c30b719 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
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
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
/*-
 * Copyright (c) 1982, 1986, 1990, 1991, 1993
 *	The Regents of the University of California.  All rights reserved.
 * (c) UNIX System Laboratories, Inc.
 * All or some portions of this file are derived from material licensed
 * to the University of California by American Telephone and Telegraph
 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
 * the permission of UNIX System Laboratories, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include "opt_hwpmc_hooks.h"

#define kse td_sched

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/ktr.h>
#include <sys/lock.h>
#include <sys/kthread.h>
#include <sys/mutex.h>
#include <sys/proc.h>
#include <sys/resourcevar.h>
#include <sys/sched.h>
#include <sys/smp.h>
#include <sys/sysctl.h>
#include <sys/sx.h>
#include <sys/turnstile.h>
#include <sys/umtx.h>
#include <machine/pcb.h>
#include <machine/smp.h>

#ifdef HWPMC_HOOKS
#include <sys/pmckern.h>
#endif

/*
 * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
 * the range 100-256 Hz (approximately).
 */
#define	ESTCPULIM(e) \
    min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
    RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
#ifdef SMP
#define	INVERSE_ESTCPU_WEIGHT	(8 * smp_cpus)
#else
#define	INVERSE_ESTCPU_WEIGHT	8	/* 1 / (priorities per estcpu level). */
#endif
#define	NICE_WEIGHT		1	/* Priorities per nice level. */

#ifdef KSE
/*
 * The schedulable entity that can be given a context to run.
 * A process may have several of these. Probably one per processor
 * but possibly a few more. In this universe they are grouped
 * with a KSEG that contains the priority and niceness
 * for the group.
 */
#else
/*
 * The schedulable entity that runs a context.
 * A process may have several of these. Probably one per processor
 * but posibly a few more.
 */
#endif
struct kse {
	TAILQ_ENTRY(kse) ke_procq;	/* (j/z) Run queue. */
	struct thread	*ke_thread;	/* (*) Active associated thread. */
	fixpt_t		ke_pctcpu;	/* (j) %cpu during p_swtime. */
	u_char		ke_rqindex;	/* (j) Run queue index. */
	enum {
		KES_THREAD = 0x0,	/* slaved to thread state */
		KES_ONRUNQ
	} ke_state;			/* (j) KSE status. */
	int		ke_cpticks;	/* (j) Ticks of cpu time. */
	struct runq	*ke_runq;	/* runq the kse is currently on */
};

#ifdef KSE
#define ke_proc		ke_thread->td_proc
#define ke_ksegrp	ke_thread->td_ksegrp
#endif

#define td_kse td_sched

/* flags kept in td_flags */
#define TDF_DIDRUN	TDF_SCHED0	/* KSE actually ran. */
#define TDF_EXIT	TDF_SCHED1	/* KSE is being killed. */
#define TDF_BOUND	TDF_SCHED2

#define ke_flags	ke_thread->td_flags
#define KEF_DIDRUN	TDF_DIDRUN /* KSE actually ran. */
#define KEF_EXIT	TDF_EXIT /* KSE is being killed. */
#define KEF_BOUND	TDF_BOUND /* stuck to one CPU */

#define SKE_RUNQ_PCPU(ke)						\
    ((ke)->ke_runq != 0 && (ke)->ke_runq != &runq)

#ifdef KSE
struct kg_sched {
	struct thread	*skg_last_assigned; /* (j) Last thread assigned to */
					   /* the system scheduler. */
	int	skg_avail_opennings;	/* (j) Num KSEs requested in group. */
	int	skg_concurrency;	/* (j) Num KSEs requested in group. */
};
#define kg_last_assigned	kg_sched->skg_last_assigned
#define kg_avail_opennings	kg_sched->skg_avail_opennings
#define kg_concurrency		kg_sched->skg_concurrency

#define SLOT_RELEASE(kg)						\
do {									\
	kg->kg_avail_opennings++; 					\
	CTR3(KTR_RUNQ, "kg %p(%d) Slot released (->%d)",		\
	    kg,								\
	    kg->kg_concurrency,						\
	    kg->kg_avail_opennings);					\
/*	KASSERT((kg->kg_avail_opennings <= kg->kg_concurrency),		\
	    ("slots out of whack"));*/					\
} while (0)

#define SLOT_USE(kg)							\
do {									\
	kg->kg_avail_opennings--; 					\
	CTR3(KTR_RUNQ, "kg %p(%d) Slot used (->%d)",			\
	    kg,								\
	    kg->kg_concurrency,						\
	    kg->kg_avail_opennings);					\
/*	KASSERT((kg->kg_avail_opennings >= 0),				\
	    ("slots out of whack"));*/					\
} while (0)
#endif

/*
 * KSE_CAN_MIGRATE macro returns true if the kse can migrate between
 * cpus.
 */
#define KSE_CAN_MIGRATE(ke)						\
    ((ke)->ke_thread->td_pinned == 0 && ((ke)->ke_flags & KEF_BOUND) == 0)

static struct kse kse0;
#ifdef KSE
static struct kg_sched kg_sched0;
#endif

static int	sched_tdcnt;	/* Total runnable threads in the system. */
static int	sched_quantum;	/* Roundrobin scheduling quantum in ticks. */
#define	SCHED_QUANTUM	(hz / 10)	/* Default sched quantum */

static struct callout roundrobin_callout;

#ifdef KSE
static void	slot_fill(struct ksegrp *kg);
static struct kse *sched_choose(void);		/* XXX Should be thread * */
#else
static struct thread *sched_choose(void);
#endif

static void	setup_runqs(void);
static void	roundrobin(void *arg);
static void	schedcpu(void);
static void	schedcpu_thread(void);
static void	sched_priority(struct thread *td, u_char prio);
static void	sched_setup(void *dummy);
static void	maybe_resched(struct thread *td);
#ifdef KSE
static void	updatepri(struct ksegrp *kg);
static void	resetpriority(struct ksegrp *kg);
static void	resetpriority_thread(struct thread *td, struct ksegrp *kg);
#else
static void	updatepri(struct thread *td);
static void	resetpriority(struct thread *td);
static void	resetpriority_thread(struct thread *td);
#endif
#ifdef SMP
static int	forward_wakeup(int  cpunum);
#endif

static struct kproc_desc sched_kp = {
        "schedcpu",
        schedcpu_thread,
        NULL
};
SYSINIT(schedcpu, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, kproc_start, &sched_kp)
SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)

/*
 * Global run queue.
 */
static struct runq runq;

#ifdef SMP
/*
 * Per-CPU run queues
 */
static struct runq runq_pcpu[MAXCPU];
#endif

static void
setup_runqs(void)
{
#ifdef SMP
	int i;

	for (i = 0; i < MAXCPU; ++i)
		runq_init(&runq_pcpu[i]);
#endif

	runq_init(&runq);
}

static int
sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
{
	int error, new_val;

	new_val = sched_quantum * tick;
	error = sysctl_handle_int(oidp, &new_val, 0, req);
        if (error != 0 || req->newptr == NULL)
		return (error);
	if (new_val < tick)
		return (EINVAL);
	sched_quantum = new_val / tick;
	hogticks = 2 * sched_quantum;
	return (0);
}

SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");

SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
    "Scheduler name");

SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
    0, sizeof sched_quantum, sysctl_kern_quantum, "I",
    "Roundrobin scheduling quantum in microseconds");

#ifdef SMP
/* Enable forwarding of wakeups to all other cpus */
SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup, CTLFLAG_RD, NULL, "Kernel SMP");

static int forward_wakeup_enabled = 1;
SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
	   &forward_wakeup_enabled, 0,
	   "Forwarding of wakeup to idle CPUs");

static int forward_wakeups_requested = 0;
SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
	   &forward_wakeups_requested, 0,
	   "Requests for Forwarding of wakeup to idle CPUs");

static int forward_wakeups_delivered = 0;
SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
	   &forward_wakeups_delivered, 0,
	   "Completed Forwarding of wakeup to idle CPUs");

static int forward_wakeup_use_mask = 1;
SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
	   &forward_wakeup_use_mask, 0,
	   "Use the mask of idle cpus");

static int forward_wakeup_use_loop = 0;
SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
	   &forward_wakeup_use_loop, 0,
	   "Use a loop to find idle cpus");

static int forward_wakeup_use_single = 0;
SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, onecpu, CTLFLAG_RW,
	   &forward_wakeup_use_single, 0,
	   "Only signal one idle cpu");

static int forward_wakeup_use_htt = 0;
SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, htt2, CTLFLAG_RW,
	   &forward_wakeup_use_htt, 0,
	   "account for htt");

#endif
#ifdef KSE
static int sched_followon = 0;
SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
	   &sched_followon, 0,
	   "allow threads to share a quantum");

static int sched_pfollowons = 0;
SYSCTL_INT(_kern_sched, OID_AUTO, pfollowons, CTLFLAG_RD,
	   &sched_pfollowons, 0,
	   "number of followons done to a different ksegrp");

static int sched_kgfollowons = 0;
SYSCTL_INT(_kern_sched, OID_AUTO, kgfollowons, CTLFLAG_RD,
	   &sched_kgfollowons, 0,
	   "number of followons done in a ksegrp");
#endif

static __inline void
sched_load_add(void)
{
	sched_tdcnt++;
	CTR1(KTR_SCHED, "global load: %d", sched_tdcnt);
}

static __inline void
sched_load_rem(void)
{
	sched_tdcnt--;
	CTR1(KTR_SCHED, "global load: %d", sched_tdcnt);
}
/*
 * Arrange to reschedule if necessary, taking the priorities and
 * schedulers into account.
 */
static void
maybe_resched(struct thread *td)
{

	mtx_assert(&sched_lock, MA_OWNED);
	if (td->td_priority < curthread->td_priority)
		curthread->td_flags |= TDF_NEEDRESCHED;
}

/*
 * Force switch among equal priority processes every 100ms.
 * We don't actually need to force a context switch of the current process.
 * The act of firing the event triggers a context switch to softclock() and
 * then switching back out again which is equivalent to a preemption, thus
 * no further work is needed on the local CPU.
 */
/* ARGSUSED */
static void
roundrobin(void *arg)
{

#ifdef SMP
	mtx_lock_spin(&sched_lock);
	forward_roundrobin();
	mtx_unlock_spin(&sched_lock);
#endif

	callout_reset(&roundrobin_callout, sched_quantum, roundrobin, NULL);
}

/*
 * Constants for digital decay and forget:
 * ifdef KSE
 *	90% of (kg_estcpu) usage in 5 * loadav time
 * else
 *	90% of (td_estcpu) usage in 5 * loadav time
 * endif
 *	95% of (ke_pctcpu) usage in 60 seconds (load insensitive)
 *          Note that, as ps(1) mentions, this can let percentages
 *          total over 100% (I've seen 137.9% for 3 processes).
 *
 * ifdef KSE
 * Note that schedclock() updates kg_estcpu and p_cpticks asynchronously.
 * else
 * Note that schedclock() updates td_estcpu and p_cpticks asynchronously.
 * endif
 *
 * ifdef KSE
 * We wish to decay away 90% of kg_estcpu in (5 * loadavg) seconds.
 * else
 * We wish to decay away 90% of td_estcpu in (5 * loadavg) seconds.
 * endif
 * That is, the system wants to compute a value of decay such
 * that the following for loop:
 * 	for (i = 0; i < (5 * loadavg); i++)
 * ifdef KSE
 * 		kg_estcpu *= decay;
 * else
 * 		td_estcpu *= decay;
 * endif
 * will compute
 * ifdef KSE
 * 	kg_estcpu *= 0.1;
 * else
 * 	td_estcpu *= 0.1;
 * endif
 * for all values of loadavg:
 *
 * Mathematically this loop can be expressed by saying:
 * 	decay ** (5 * loadavg) ~= .1
 *
 * The system computes decay as:
 * 	decay = (2 * loadavg) / (2 * loadavg + 1)
 *
 * We wish to prove that the system's computation of decay
 * will always fulfill the equation:
 * 	decay ** (5 * loadavg) ~= .1
 *
 * If we compute b as:
 * 	b = 2 * loadavg
 * then
 * 	decay = b / (b + 1)
 *
 * We now need to prove two things:
 *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
 *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
 *
 * Facts:
 *         For x close to zero, exp(x) =~ 1 + x, since
 *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
 *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
 *         For x close to zero, ln(1+x) =~ x, since
 *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
 *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
 *         ln(.1) =~ -2.30
 *
 * Proof of (1):
 *    Solve (factor)**(power) =~ .1 given power (5*loadav):
 *	solving for factor,
 *      ln(factor) =~ (-2.30/5*loadav), or
 *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
 *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
 *
 * Proof of (2):
 *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
 *	solving for power,
 *      power*ln(b/(b+1)) =~ -2.30, or
 *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
 *
 * Actual power values for the implemented algorithm are as follows:
 *      loadav: 1       2       3       4
 *      power:  5.68    10.32   14.94   19.55
 */

/* calculations for digital decay to forget 90% of usage in 5*loadav sec */
#define	loadfactor(loadav)	(2 * (loadav))
#define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))

/* decay 95% of `ke_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
static fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");

/*
 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
 *
 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
 *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
 *
 * If you don't want to bother with the faster/more-accurate formula, you
 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
 * (more general) method of calculating the %age of CPU used by a process.
 */
#define	CCPU_SHIFT	11

/*
 * Recompute process priorities, every hz ticks.
 * MP-safe, called without the Giant mutex.
 */
/* ARGSUSED */
static void
schedcpu(void)
{
	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
	struct thread *td;
	struct proc *p;
	struct kse *ke;
#ifdef KSE
	struct ksegrp *kg;
#endif
	int awake, realstathz;

	realstathz = stathz ? stathz : hz;
	sx_slock(&allproc_lock);
	FOREACH_PROC_IN_SYSTEM(p) {
		/*
		 * Prevent state changes and protect run queue.
		 */
		mtx_lock_spin(&sched_lock);
		/*
		 * Increment time in/out of memory.  We ignore overflow; with
		 * 16-bit int's (remember them?) overflow takes 45 days.
		 */
		p->p_swtime++;
#ifdef KSE
		FOREACH_KSEGRP_IN_PROC(p, kg) { 
#else
		FOREACH_THREAD_IN_PROC(p, td) { 
#endif
			awake = 0;
#ifdef KSE
			FOREACH_THREAD_IN_GROUP(kg, td) {
				ke = td->td_kse;
				/*
				 * Increment sleep time (if sleeping).  We
				 * ignore overflow, as above.
				 */
				/*
				 * The kse slptimes are not touched in wakeup
				 * because the thread may not HAVE a KSE.
				 */
				if (ke->ke_state == KES_ONRUNQ) {
					awake = 1;
					ke->ke_flags &= ~KEF_DIDRUN;
				} else if ((ke->ke_state == KES_THREAD) &&
				    (TD_IS_RUNNING(td))) {
					awake = 1;
					/* Do not clear KEF_DIDRUN */
				} else if (ke->ke_flags & KEF_DIDRUN) {
					awake = 1;
					ke->ke_flags &= ~KEF_DIDRUN;
				}

				/*
				 * ke_pctcpu is only for ps and ttyinfo().
				 * Do it per kse, and add them up at the end?
				 * XXXKSE
				 */
				ke->ke_pctcpu = (ke->ke_pctcpu * ccpu) >>
				    FSHIFT;
				/*
				 * If the kse has been idle the entire second,
				 * stop recalculating its priority until
				 * it wakes up.
				 */
				if (ke->ke_cpticks == 0)
					continue;
#if	(FSHIFT >= CCPU_SHIFT)
				ke->ke_pctcpu += (realstathz == 100)
				    ? ((fixpt_t) ke->ke_cpticks) <<
				    (FSHIFT - CCPU_SHIFT) :
				    100 * (((fixpt_t) ke->ke_cpticks)
				    << (FSHIFT - CCPU_SHIFT)) / realstathz;
#else
				ke->ke_pctcpu += ((FSCALE - ccpu) *
				    (ke->ke_cpticks *
				    FSCALE / realstathz)) >> FSHIFT;
#endif
				ke->ke_cpticks = 0;
			} /* end of kse loop */
#else
			ke = td->td_kse;
			/*
			 * Increment sleep time (if sleeping).  We
			 * ignore overflow, as above.
			 */
			/*
			 * The kse slptimes are not touched in wakeup
			 * because the thread may not HAVE a KSE.
			 */
			if (ke->ke_state == KES_ONRUNQ) {
				awake = 1;
				ke->ke_flags &= ~KEF_DIDRUN;
			} else if ((ke->ke_state == KES_THREAD) &&
			    (TD_IS_RUNNING(td))) {
				awake = 1;
				/* Do not clear KEF_DIDRUN */
			} else if (ke->ke_flags & KEF_DIDRUN) {
				awake = 1;
				ke->ke_flags &= ~KEF_DIDRUN;
			}

			/*
			 * ke_pctcpu is only for ps and ttyinfo().
			 * Do it per kse, and add them up at the end?
			 * XXXKSE
			 */
			ke->ke_pctcpu = (ke->ke_pctcpu * ccpu) >>
			    FSHIFT;
			/*
			 * If the kse has been idle the entire second,
			 * stop recalculating its priority until
			 * it wakes up.
			 */
			if (ke->ke_cpticks == 0)
				continue;
#if	(FSHIFT >= CCPU_SHIFT)
			ke->ke_pctcpu += (realstathz == 100)
			    ? ((fixpt_t) ke->ke_cpticks) <<
			    (FSHIFT - CCPU_SHIFT) :
			    100 * (((fixpt_t) ke->ke_cpticks)
			    << (FSHIFT - CCPU_SHIFT)) / realstathz;
#else
			ke->ke_pctcpu += ((FSCALE - ccpu) *
			    (ke->ke_cpticks *
			    FSCALE / realstathz)) >> FSHIFT;
#endif
			ke->ke_cpticks = 0;
#endif

			/* 
			 * ifdef KSE
			 * If there are ANY running threads in this KSEGRP,
			 * else
			 * If there are ANY running threads in this process,
			 * endif
			 * then don't count it as sleeping.
			 */
			if (awake) {
#ifdef KSE
				if (kg->kg_slptime > 1) {
#else
				if (td->td_slptime > 1) {
#endif
					/*
					 * In an ideal world, this should not
					 * happen, because whoever woke us
					 * up from the long sleep should have
					 * unwound the slptime and reset our
					 * priority before we run at the stale
					 * priority.  Should KASSERT at some
					 * point when all the cases are fixed.
					 */
#ifdef KSE
					updatepri(kg);
				}
				kg->kg_slptime = 0;
			} else
				kg->kg_slptime++;
			if (kg->kg_slptime > 1)
				continue;
			kg->kg_estcpu = decay_cpu(loadfac, kg->kg_estcpu);
		      	resetpriority(kg);
			FOREACH_THREAD_IN_GROUP(kg, td) {
				resetpriority_thread(td, kg);
			}
		} /* end of ksegrp loop */
#else
					updatepri(td);
				}
				td->td_slptime = 0;
			} else
				td->td_slptime++;
			if (td->td_slptime > 1)
				continue;
			td->td_estcpu = decay_cpu(loadfac, td->td_estcpu);
		      	resetpriority(td);
			resetpriority_thread(td);
		} /* end of thread loop */
#endif
		mtx_unlock_spin(&sched_lock);
	} /* end of process loop */
	sx_sunlock(&allproc_lock);
}

/*
 * Main loop for a kthread that executes schedcpu once a second.
 */
static void
schedcpu_thread(void)
{
	int nowake;

	for (;;) {
		schedcpu();
		tsleep(&nowake, 0, "-", hz);
	}
}

/*
 * Recalculate the priority of a process after it has slept for a while.
 * ifdef KSE
 * For all load averages >= 1 and max kg_estcpu of 255, sleeping for at
 * least six times the loadfactor will decay kg_estcpu to zero.
 * else
 * For all load averages >= 1 and max td_estcpu of 255, sleeping for at
 * least six times the loadfactor will decay td_estcpu to zero.
 * endif
 */
static void
#ifdef KSE
updatepri(struct ksegrp *kg)
#else
updatepri(struct thread *td)
#endif
{
	register fixpt_t loadfac;
	register unsigned int newcpu;

	loadfac = loadfactor(averunnable.ldavg[0]);
#ifdef KSE
	if (kg->kg_slptime > 5 * loadfac)
		kg->kg_estcpu = 0;
#else
	if (td->td_slptime > 5 * loadfac)
		td->td_estcpu = 0;
#endif
	else {
#ifdef KSE
		newcpu = kg->kg_estcpu;
		kg->kg_slptime--;	/* was incremented in schedcpu() */
		while (newcpu && --kg->kg_slptime)
#else
		newcpu = td->td_estcpu;
		td->td_slptime--;	/* was incremented in schedcpu() */
		while (newcpu && --td->td_slptime)
#endif
			newcpu = decay_cpu(loadfac, newcpu);
#ifdef KSE
		kg->kg_estcpu = newcpu;
#else
		td->td_estcpu = newcpu;
#endif
	}
}

/*
 * Compute the priority of a process when running in user mode.
 * Arrange to reschedule if the resulting priority is better
 * than that of the current process.
 */
static void
#ifdef KSE
resetpriority(struct ksegrp *kg)
#else
resetpriority(struct thread *td)
#endif
{
	register unsigned int newpriority;

#ifdef KSE
	if (kg->kg_pri_class == PRI_TIMESHARE) {
		newpriority = PUSER + kg->kg_estcpu / INVERSE_ESTCPU_WEIGHT +
		    NICE_WEIGHT * (kg->kg_proc->p_nice - PRIO_MIN);
#else
	if (td->td_pri_class == PRI_TIMESHARE) {
		newpriority = PUSER + td->td_estcpu / INVERSE_ESTCPU_WEIGHT +
		    NICE_WEIGHT * (td->td_proc->p_nice - PRIO_MIN);
#endif
		newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
		    PRI_MAX_TIMESHARE);
#ifdef KSE
		sched_user_prio(kg, newpriority);
#else
		sched_user_prio(td, newpriority);
#endif
	}
}

/*
 * Update the thread's priority when the associated ksegroup's user
 * priority changes.
 */
static void
#ifdef KSE
resetpriority_thread(struct thread *td, struct ksegrp *kg)
#else
resetpriority_thread(struct thread *td)
#endif
{

	/* Only change threads with a time sharing user priority. */
	if (td->td_priority < PRI_MIN_TIMESHARE ||
	    td->td_priority > PRI_MAX_TIMESHARE)
		return;

	/* XXX the whole needresched thing is broken, but not silly. */
	maybe_resched(td);

#ifdef KSE
	sched_prio(td, kg->kg_user_pri);
#else
	sched_prio(td, td->td_user_pri);
#endif
}

/* ARGSUSED */
static void
sched_setup(void *dummy)
{
	setup_runqs();

	if (sched_quantum == 0)
		sched_quantum = SCHED_QUANTUM;
	hogticks = 2 * sched_quantum;

	callout_init(&roundrobin_callout, CALLOUT_MPSAFE);

	/* Kick off timeout driven events by calling first time. */
	roundrobin(NULL);

	/* Account for thread0. */
	sched_load_add();
}

/* External interfaces start here */
/*
 * Very early in the boot some setup of scheduler-specific
 * parts of proc0 and of some scheduler resources needs to be done.
 * Called from:
 *  proc0_init()
 */
void
schedinit(void)
{
	/*
	 * Set up the scheduler specific parts of proc0.
	 */
	proc0.p_sched = NULL; /* XXX */
#ifdef KSE
	ksegrp0.kg_sched = &kg_sched0;
#endif
	thread0.td_sched = &kse0;
	kse0.ke_thread = &thread0;
	kse0.ke_state = KES_THREAD;
#ifdef KSE
	kg_sched0.skg_concurrency = 1;
	kg_sched0.skg_avail_opennings = 0; /* we are already running */
#endif
}

int
sched_runnable(void)
{
#ifdef SMP
	return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
#else
	return runq_check(&runq);
#endif
}

int 
sched_rr_interval(void)
{
	if (sched_quantum == 0)
		sched_quantum = SCHED_QUANTUM;
	return (sched_quantum);
}

/*
 * We adjust the priority of the current process.  The priority of
 * a process gets worse as it accumulates CPU time.  The cpu usage
 * ifdef KSE
 * estimator (kg_estcpu) is increased here.  resetpriority() will
 * compute a different priority each time kg_estcpu increases by
 * else
 * estimator (td_estcpu) is increased here.  resetpriority() will
 * compute a different priority each time td_estcpu increases by
 * endif
 * INVERSE_ESTCPU_WEIGHT
 * (until MAXPRI is reached).  The cpu usage estimator ramps up
 * quite quickly when the process is running (linearly), and decays
 * away exponentially, at a rate which is proportionally slower when
 * the system is busy.  The basic principle is that the system will
 * 90% forget that the process used a lot of CPU time in 5 * loadav
 * seconds.  This causes the system to favor processes which haven't
 * run much recently, and to round-robin among other processes.
 */
void
sched_clock(struct thread *td)
{
#ifdef KSE
	struct ksegrp *kg;
#endif
	struct kse *ke;

	mtx_assert(&sched_lock, MA_OWNED);
#ifdef KSE
	kg = td->td_ksegrp;
#endif
	ke = td->td_kse;

	ke->ke_cpticks++;
#ifdef KSE
	kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + 1);
	if ((kg->kg_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
		resetpriority(kg);
		resetpriority_thread(td, kg);
#else
	td->td_estcpu = ESTCPULIM(td->td_estcpu + 1);
	if ((td->td_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
		resetpriority(td);
		resetpriority_thread(td);
#endif
	}
}

#ifdef KSE
/*
 * charge childs scheduling cpu usage to parent.
 *
 * XXXKSE assume only one thread & kse & ksegrp keep estcpu in each ksegrp.
 * Charge it to the ksegrp that did the wait since process estcpu is sum of
 * all ksegrps, this is strictly as expected.  Assume that the child process
 * aggregated all the estcpu into the 'built-in' ksegrp.
 */
#else
/*
 * charge childs scheduling cpu usage to parent.
 */
#endif
void
sched_exit(struct proc *p, struct thread *td)
{
#ifdef KSE
	sched_exit_ksegrp(FIRST_KSEGRP_IN_PROC(p), td);
	sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
#else
	struct thread *parent = FIRST_THREAD_IN_PROC(p);

	CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
	    td, td->td_proc->p_comm, td->td_priority);

	parent->td_estcpu = ESTCPULIM(parent->td_estcpu + td->td_estcpu);
	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
		sched_load_rem();
#endif
}

#ifdef KSE
void
sched_exit_ksegrp(struct ksegrp *kg, struct thread *childtd)
{

	mtx_assert(&sched_lock, MA_OWNED);
	kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + childtd->td_ksegrp->kg_estcpu);
}

void
sched_exit_thread(struct thread *td, struct thread *child)
{
	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
	    child, child->td_proc->p_comm, child->td_priority);
	if ((child->td_proc->p_flag & P_NOLOAD) == 0)
		sched_load_rem();
}
#endif

void
sched_fork(struct thread *td, struct thread *childtd)
{
#ifdef KSE
	sched_fork_ksegrp(td, childtd->td_ksegrp);
	sched_fork_thread(td, childtd);
#else
	childtd->td_estcpu = td->td_estcpu;
	sched_newthread(childtd);
#endif
}

#ifdef KSE
void
sched_fork_ksegrp(struct thread *td, struct ksegrp *child)
{
	mtx_assert(&sched_lock, MA_OWNED);
	child->kg_estcpu = td->td_ksegrp->kg_estcpu;
}

void
sched_fork_thread(struct thread *td, struct thread *childtd)
{
	sched_newthread(childtd);
}
#endif

void
sched_nice(struct proc *p, int nice)
{
#ifdef KSE
	struct ksegrp *kg;
#endif
	struct thread *td;

	PROC_LOCK_ASSERT(p, MA_OWNED);
	mtx_assert(&sched_lock, MA_OWNED);
	p->p_nice = nice;
#ifdef KSE
	FOREACH_KSEGRP_IN_PROC(p, kg) {
		resetpriority(kg);
		FOREACH_THREAD_IN_GROUP(kg, td) {
			resetpriority_thread(td, kg);
		}
	}
#else
	FOREACH_THREAD_IN_PROC(p, td) {
		resetpriority(td);
		resetpriority_thread(td);
	}
#endif
}

void
#ifdef KSE
sched_class(struct ksegrp *kg, int class)
#else
sched_class(struct thread *td, int class)
#endif
{
	mtx_assert(&sched_lock, MA_OWNED);
#ifdef KSE
	kg->kg_pri_class = class;
#else
	td->td_pri_class = class;
#endif
}

#ifdef KSE
/*
 * Adjust the priority of a thread.
 * This may include moving the thread within the KSEGRP,
 * changing the assignment of a kse to the thread,
 * and moving a KSE in the system run queue.
 */
#else
/*
 * Adjust the priority of a thread.
 */
#endif
static void
sched_priority(struct thread *td, u_char prio)
{
	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
	    td, td->td_proc->p_comm, td->td_priority, prio, curthread, 
	    curthread->td_proc->p_comm);

	mtx_assert(&sched_lock, MA_OWNED);
	if (td->td_priority == prio)
		return;
	if (TD_ON_RUNQ(td)) {
		adjustrunqueue(td, prio);
	} else {
		td->td_priority = prio;
	}
}

/*
 * Update a thread's priority when it is lent another thread's
 * priority.
 */
void
sched_lend_prio(struct thread *td, u_char prio)
{

	td->td_flags |= TDF_BORROWING;
	sched_priority(td, prio);
}

/*
 * Restore a thread's priority when priority propagation is
 * over.  The prio argument is the minimum priority the thread
 * needs to have to satisfy other possible priority lending
 * requests.  If the thread's regulary priority is less
 * important than prio the thread will keep a priority boost
 * of prio.
 */
void
sched_unlend_prio(struct thread *td, u_char prio)
{
	u_char base_pri;

	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
	    td->td_base_pri <= PRI_MAX_TIMESHARE)
#ifdef KSE
		base_pri = td->td_ksegrp->kg_user_pri;
#else
		base_pri = td->td_user_pri;
#endif
	else
		base_pri = td->td_base_pri;
	if (prio >= base_pri) {
		td->td_flags &= ~TDF_BORROWING;
		sched_prio(td, base_pri);
	} else
		sched_lend_prio(td, prio);
}

void
sched_prio(struct thread *td, u_char prio)
{
	u_char oldprio;

	/* First, update the base priority. */
	td->td_base_pri = prio;

	/*
	 * If the thread is borrowing another thread's priority, don't ever
	 * lower the priority.
	 */
	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
		return;

	/* Change the real priority. */
	oldprio = td->td_priority;
	sched_priority(td, prio);

	/*
	 * If the thread is on a turnstile, then let the turnstile update
	 * its state.
	 */
	if (TD_ON_LOCK(td) && oldprio != prio)
		turnstile_adjust(td, oldprio);
}

void
#ifdef KSE
sched_user_prio(struct ksegrp *kg, u_char prio)
#else
sched_user_prio(struct thread *td, u_char prio)
#endif
{
#ifdef KSE
	struct thread *td;
#endif
	u_char oldprio;

#ifdef KSE
	kg->kg_base_user_pri = prio;

	/* XXXKSE only for 1:1 */

	td = TAILQ_FIRST(&kg->kg_threads);
	if (td == NULL) {
		kg->kg_user_pri = prio;
		return;
	}

	if (td->td_flags & TDF_UBORROWING && kg->kg_user_pri <= prio)
		return;

	oldprio = kg->kg_user_pri;
	kg->kg_user_pri = prio;
#else
	td->td_base_user_pri = prio;

	oldprio = td->td_user_pri;
	td->td_user_pri = prio;
#endif

	if (TD_ON_UPILOCK(td) && oldprio != prio)
		umtx_pi_adjust(td, oldprio);
}

void
sched_lend_user_prio(struct thread *td, u_char prio)
{
	u_char oldprio;

	td->td_flags |= TDF_UBORROWING;

#ifdef KSE
	oldprio = td->td_ksegrp->kg_user_pri;
	td->td_ksegrp->kg_user_pri = prio;
#else
	oldprio = td->td_user_pri;
	td->td_user_pri = prio;
#endif

	if (TD_ON_UPILOCK(td) && oldprio != prio)
		umtx_pi_adjust(td, oldprio);
}

void
sched_unlend_user_prio(struct thread *td, u_char prio)
{
#ifdef KSE
	struct ksegrp *kg = td->td_ksegrp;
#endif
	u_char base_pri;

#ifdef KSE
	base_pri = kg->kg_base_user_pri;
#else
	base_pri = td->td_base_user_pri;
#endif
	if (prio >= base_pri) {
		td->td_flags &= ~TDF_UBORROWING;
#ifdef KSE
		sched_user_prio(kg, base_pri);
#else
		sched_user_prio(td, base_pri);
#endif
	} else
		sched_lend_user_prio(td, prio);
}

void
sched_sleep(struct thread *td)
{

	mtx_assert(&sched_lock, MA_OWNED);
#ifdef KSE
	td->td_ksegrp->kg_slptime = 0;
#else
	td->td_slptime = 0;
#endif
}

#ifdef KSE
static void remrunqueue(struct thread *td);
#endif

void
sched_switch(struct thread *td, struct thread *newtd, int flags)
{
	struct kse *ke;
#ifdef KSE
	struct ksegrp *kg;
#endif
	struct proc *p;

	ke = td->td_kse;
	p = td->td_proc;

	mtx_assert(&sched_lock, MA_OWNED);

	if ((p->p_flag & P_NOLOAD) == 0)
		sched_load_rem();
#ifdef KSE
	/* 
	 * We are volunteering to switch out so we get to nominate
	 * a successor for the rest of our quantum
	 * First try another thread in our ksegrp, and then look for 
	 * other ksegrps in our process.
	 */
	if (sched_followon &&
	    (p->p_flag & P_HADTHREADS) &&
	    (flags & SW_VOL) &&
	    newtd == NULL) {
		/* lets schedule another thread from this process */
		 kg = td->td_ksegrp;
		 if ((newtd = TAILQ_FIRST(&kg->kg_runq))) {
			remrunqueue(newtd);
			sched_kgfollowons++;
		 } else {
			FOREACH_KSEGRP_IN_PROC(p, kg) {
				if ((newtd = TAILQ_FIRST(&kg->kg_runq))) {
					sched_pfollowons++;
					remrunqueue(newtd);
					break;
				}
			}
		}
	}
#endif

	if (newtd) 
		newtd->td_flags |= (td->td_flags & TDF_NEEDRESCHED);

	td->td_lastcpu = td->td_oncpu;
	td->td_flags &= ~TDF_NEEDRESCHED;
	td->td_owepreempt = 0;
	td->td_oncpu = NOCPU;
	/*
	 * At the last moment, if this thread is still marked RUNNING,
	 * then put it back on the run queue as it has not been suspended
	 * or stopped or any thing else similar.  We never put the idle
	 * threads on the run queue, however.
	 */
	if (td == PCPU_GET(idlethread))
		TD_SET_CAN_RUN(td);
	else {
#ifdef KSE
		SLOT_RELEASE(td->td_ksegrp);
#endif
		if (TD_IS_RUNNING(td)) {
			/* Put us back on the run queue (kse and all). */
			setrunqueue(td, (flags & SW_PREEMPT) ?
			    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
			    SRQ_OURSELF|SRQ_YIELDING);
#ifdef KSE
		} else if (p->p_flag & P_HADTHREADS) {
			/*
			 * We will not be on the run queue. So we must be
			 * sleeping or similar. As it's available,
			 * someone else can use the KSE if they need it.
			 * It's NOT available if we are about to need it
			 */
			if (newtd == NULL || newtd->td_ksegrp != td->td_ksegrp)
				slot_fill(td->td_ksegrp);
#endif
		}
	}
	if (newtd) {
		/* 
		 * The thread we are about to run needs to be counted
		 * as if it had been added to the run queue and selected.
		 * It came from:
		 * * A preemption
		 * ifdef KSE
		 * * An upcall 
		 * endif
		 * * A followon
		 */
		KASSERT((newtd->td_inhibitors == 0),
			("trying to run inhibitted thread"));
#ifdef KSE
		SLOT_USE(newtd->td_ksegrp);
#endif
		newtd->td_kse->ke_flags |= KEF_DIDRUN;
        	TD_SET_RUNNING(newtd);
		if ((newtd->td_proc->p_flag & P_NOLOAD) == 0)
			sched_load_add();
	} else {
		newtd = choosethread();
	}

	if (td != newtd) {
#ifdef	HWPMC_HOOKS
		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
#endif

		cpu_switch(td, newtd);
#ifdef	HWPMC_HOOKS
		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
#endif
	}

	sched_lock.mtx_lock = (uintptr_t)td;
	td->td_oncpu = PCPU_GET(cpuid);
}

void
sched_wakeup(struct thread *td)
{
#ifdef KSE
	struct ksegrp *kg;
#endif

	mtx_assert(&sched_lock, MA_OWNED);
#ifdef KSE
	kg = td->td_ksegrp;
	if (kg->kg_slptime > 1) {
		updatepri(kg);
		resetpriority(kg);
	}
	kg->kg_slptime = 0;
#else
	if (td->td_slptime > 1) {
		updatepri(td);
		resetpriority(td);
	}
	td->td_slptime = 0;
#endif
	setrunqueue(td, SRQ_BORING);
}

#ifdef SMP
/* enable HTT_2 if you have a 2-way HTT cpu.*/
static int
forward_wakeup(int  cpunum)
{
	cpumask_t map, me, dontuse;
	cpumask_t map2;
	struct pcpu *pc;
	cpumask_t id, map3;

	mtx_assert(&sched_lock, MA_OWNED);

	CTR0(KTR_RUNQ, "forward_wakeup()");

	if ((!forward_wakeup_enabled) ||
	     (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
		return (0);
	if (!smp_started || cold || panicstr)
		return (0);

	forward_wakeups_requested++;

/*
 * check the idle mask we received against what we calculated before
 * in the old version.
 */
	me = PCPU_GET(cpumask);
	/* 
	 * don't bother if we should be doing it ourself..
	 */
	if ((me & idle_cpus_mask) && (cpunum == NOCPU || me == (1 << cpunum)))
		return (0);

	dontuse = me | stopped_cpus | hlt_cpus_mask;
	map3 = 0;
	if (forward_wakeup_use_loop) {
		SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
			id = pc->pc_cpumask;
			if ( (id & dontuse) == 0 &&
			    pc->pc_curthread == pc->pc_idlethread) {
				map3 |= id;
			}
		}
	}

	if (forward_wakeup_use_mask) {
		map = 0;
		map = idle_cpus_mask & ~dontuse;

		/* If they are both on, compare and use loop if different */
		if (forward_wakeup_use_loop) {
			if (map != map3) {
				printf("map (%02X) != map3 (%02X)\n",
						map, map3);
				map = map3;
			}
		}
	} else {
		map = map3;
	}
	/* If we only allow a specific CPU, then mask off all the others */
	if (cpunum != NOCPU) {
		KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
		map &= (1 << cpunum);
	} else {
		/* Try choose an idle die. */
		if (forward_wakeup_use_htt) {
			map2 =  (map & (map >> 1)) & 0x5555;
			if (map2) {
				map = map2;
			}
		}

		/* set only one bit */ 
		if (forward_wakeup_use_single) {
			map = map & ((~map) + 1);
		}
	}
	if (map) {
		forward_wakeups_delivered++;
		ipi_selected(map, IPI_AST);
		return (1);
	}
	if (cpunum == NOCPU)
		printf("forward_wakeup: Idle processor not found\n");
	return (0);
}
#endif

#ifdef SMP
static void kick_other_cpu(int pri,int cpuid);

static void
kick_other_cpu(int pri,int cpuid)
{	
	struct pcpu * pcpu = pcpu_find(cpuid);
	int cpri = pcpu->pc_curthread->td_priority;

	if (idle_cpus_mask & pcpu->pc_cpumask) {
		forward_wakeups_delivered++;
		ipi_selected(pcpu->pc_cpumask, IPI_AST);
		return;
	}

	if (pri >= cpri)
		return;

#if defined(IPI_PREEMPTION) && defined(PREEMPTION)
#if !defined(FULL_PREEMPTION)
	if (pri <= PRI_MAX_ITHD)
#endif /* ! FULL_PREEMPTION */
	{
		ipi_selected(pcpu->pc_cpumask, IPI_PREEMPT);
		return;
	}
#endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */

	pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
	ipi_selected( pcpu->pc_cpumask , IPI_AST);
	return;
}
#endif /* SMP */

void
sched_add(struct thread *td, int flags)
#ifdef SMP
{
	struct kse *ke;
	int forwarded = 0;
	int cpu;
	int single_cpu = 0;

	ke = td->td_kse;
	mtx_assert(&sched_lock, MA_OWNED);
	KASSERT(ke->ke_state != KES_ONRUNQ,
	    ("sched_add: kse %p (%s) already in run queue", ke,
#ifdef KSE
	    ke->ke_proc->p_comm));
	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
#else
	    td->td_proc->p_comm));
	KASSERT(td->td_proc->p_sflag & PS_INMEM,
#endif
	    ("sched_add: process swapped out"));
	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
	    td, td->td_proc->p_comm, td->td_priority, curthread,
	    curthread->td_proc->p_comm);


	if (td->td_pinned != 0) {
		cpu = td->td_lastcpu;
		ke->ke_runq = &runq_pcpu[cpu];
		single_cpu = 1;
		CTR3(KTR_RUNQ,
		    "sched_add: Put kse:%p(td:%p) on cpu%d runq", ke, td, cpu);
	} else if ((ke)->ke_flags & KEF_BOUND) {
		/* Find CPU from bound runq */
		KASSERT(SKE_RUNQ_PCPU(ke),("sched_add: bound kse not on cpu runq"));
		cpu = ke->ke_runq - &runq_pcpu[0];
		single_cpu = 1;
		CTR3(KTR_RUNQ,
		    "sched_add: Put kse:%p(td:%p) on cpu%d runq", ke, td, cpu);
	} else {	
		CTR2(KTR_RUNQ,
		    "sched_add: adding kse:%p (td:%p) to gbl runq", ke, td);
		cpu = NOCPU;
		ke->ke_runq = &runq;
	}
	
	if (single_cpu && (cpu != PCPU_GET(cpuid))) {
	        kick_other_cpu(td->td_priority,cpu);
	} else {
		
		if (!single_cpu) {
			cpumask_t me = PCPU_GET(cpumask);
			int idle = idle_cpus_mask & me;	

			if (!idle && ((flags & SRQ_INTR) == 0) &&
			    (idle_cpus_mask & ~(hlt_cpus_mask | me)))
				forwarded = forward_wakeup(cpu);
		}

		if (!forwarded) {
			if ((flags & SRQ_YIELDING) == 0 && maybe_preempt(td))
				return;
			else
				maybe_resched(td);
		}
	}
	
	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
		sched_load_add();
#ifdef KSE
	SLOT_USE(td->td_ksegrp);
#endif
	runq_add(ke->ke_runq, ke, flags);
	ke->ke_state = KES_ONRUNQ;
}
#else /* SMP */
{
	struct kse *ke;
	ke = td->td_kse;
	mtx_assert(&sched_lock, MA_OWNED);
	KASSERT(ke->ke_state != KES_ONRUNQ,
	    ("sched_add: kse %p (%s) already in run queue", ke,
#ifdef KSE
	    ke->ke_proc->p_comm));
	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
#else
	    td->td_proc->p_comm));
	KASSERT(td->td_proc->p_sflag & PS_INMEM,
#endif
	    ("sched_add: process swapped out"));
	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
	    td, td->td_proc->p_comm, td->td_priority, curthread,
	    curthread->td_proc->p_comm);
	CTR2(KTR_RUNQ, "sched_add: adding kse:%p (td:%p) to runq", ke, td);
	ke->ke_runq = &runq;

	/* 
	 * If we are yielding (on the way out anyhow) 
	 * or the thread being saved is US,
	 * then don't try be smart about preemption
	 * or kicking off another CPU
	 * as it won't help and may hinder.
	 * In the YIEDLING case, we are about to run whoever is 
	 * being put in the queue anyhow, and in the 
	 * OURSELF case, we are puting ourself on the run queue
	 * which also only happens when we are about to yield.
	 */
	if((flags & SRQ_YIELDING) == 0) {
		if (maybe_preempt(td))
			return;
	}	
	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
		sched_load_add();
#ifdef KSE
	SLOT_USE(td->td_ksegrp);
#endif
	runq_add(ke->ke_runq, ke, flags);
	ke->ke_state = KES_ONRUNQ;
	maybe_resched(td);
}
#endif /* SMP */

void
sched_rem(struct thread *td)
{
	struct kse *ke;

	ke = td->td_kse;
#ifdef KSE
	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
#else
	KASSERT(td->td_proc->p_sflag & PS_INMEM,
#endif
	    ("sched_rem: process swapped out"));
	KASSERT((ke->ke_state == KES_ONRUNQ),
	    ("sched_rem: KSE not on run queue"));
	mtx_assert(&sched_lock, MA_OWNED);
	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
	    td, td->td_proc->p_comm, td->td_priority, curthread,
	    curthread->td_proc->p_comm);

	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
		sched_load_rem();
#ifdef KSE
	SLOT_RELEASE(td->td_ksegrp);
#endif
	runq_remove(ke->ke_runq, ke);

	ke->ke_state = KES_THREAD;
}

/*
 * Select threads to run.
 * Notice that the running threads still consume a slot.
 */
#ifdef KSE
struct kse *
#else
struct thread *
#endif
sched_choose(void)
{
	struct kse *ke;
	struct runq *rq;

#ifdef SMP
	struct kse *kecpu;

	rq = &runq;
	ke = runq_choose(&runq);
	kecpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);

	if (ke == NULL || 
	    (kecpu != NULL && 
	     kecpu->ke_thread->td_priority < ke->ke_thread->td_priority)) {
		CTR2(KTR_RUNQ, "choosing kse %p from pcpu runq %d", kecpu,
		     PCPU_GET(cpuid));
		ke = kecpu;
		rq = &runq_pcpu[PCPU_GET(cpuid)];
	} else { 
		CTR1(KTR_RUNQ, "choosing kse %p from main runq", ke);
	}

#else
	rq = &runq;
	ke = runq_choose(&runq);
#endif

#ifdef KSE
	if (ke != NULL) {
#else
	if (ke) {
#endif
		runq_remove(rq, ke);
		ke->ke_state = KES_THREAD;

#ifdef KSE
		KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
		    ("sched_choose: process swapped out"));
#else
		KASSERT(ke->ke_thread->td_proc->p_sflag & PS_INMEM,
		    ("sched_choose: process swapped out"));
		return (ke->ke_thread);
#endif
	}
#ifdef KSE
	return (ke);
#else
	return (NULL);
#endif
}

void
sched_userret(struct thread *td)
{
#ifdef KSE
	struct ksegrp *kg;
#endif
	/*
	 * XXX we cheat slightly on the locking here to avoid locking in
	 * the usual case.  Setting td_priority here is essentially an
	 * incomplete workaround for not setting it properly elsewhere.
	 * Now that some interrupt handlers are threads, not setting it
	 * properly elsewhere can clobber it in the window between setting
	 * it here and returning to user mode, so don't waste time setting
	 * it perfectly here.
	 */
	KASSERT((td->td_flags & TDF_BORROWING) == 0,
	    ("thread with borrowed priority returning to userland"));
#ifdef KSE
	kg = td->td_ksegrp;
	if (td->td_priority != kg->kg_user_pri) {
		mtx_lock_spin(&sched_lock);
		td->td_priority = kg->kg_user_pri;
		td->td_base_pri = kg->kg_user_pri;
		mtx_unlock_spin(&sched_lock);
	}
#else
	if (td->td_priority != td->td_user_pri) {
		mtx_lock_spin(&sched_lock);
		td->td_priority = td->td_user_pri;
		td->td_base_pri = td->td_user_pri;
		mtx_unlock_spin(&sched_lock);
	}
#endif
}

void
sched_bind(struct thread *td, int cpu)
{
	struct kse *ke;

	mtx_assert(&sched_lock, MA_OWNED);
	KASSERT(TD_IS_RUNNING(td),
	    ("sched_bind: cannot bind non-running thread"));

	ke = td->td_kse;

	ke->ke_flags |= KEF_BOUND;
#ifdef SMP
	ke->ke_runq = &runq_pcpu[cpu];
	if (PCPU_GET(cpuid) == cpu)
		return;

	ke->ke_state = KES_THREAD;

	mi_switch(SW_VOL, NULL);
#endif
}

void
sched_unbind(struct thread* td)
{
	mtx_assert(&sched_lock, MA_OWNED);
	td->td_kse->ke_flags &= ~KEF_BOUND;
}

int
sched_is_bound(struct thread *td)
{
	mtx_assert(&sched_lock, MA_OWNED);
	return (td->td_kse->ke_flags & KEF_BOUND);
}

void
sched_relinquish(struct thread *td)
{
#ifdef KSE
	struct ksegrp *kg;

	kg = td->td_ksegrp;
#endif
	mtx_lock_spin(&sched_lock);
#ifdef KSE
	if (kg->kg_pri_class == PRI_TIMESHARE)
#else
	if (td->td_pri_class == PRI_TIMESHARE)
#endif
		sched_prio(td, PRI_MAX_TIMESHARE);
	mi_switch(SW_VOL, NULL);
	mtx_unlock_spin(&sched_lock);
}

int
sched_load(void)
{
	return (sched_tdcnt);
}

#ifdef KSE
int
sched_sizeof_ksegrp(void)
{
	return (sizeof(struct ksegrp) + sizeof(struct kg_sched));
}
#endif

int
sched_sizeof_proc(void)
{
	return (sizeof(struct proc));
}

int
sched_sizeof_thread(void)
{
	return (sizeof(struct thread) + sizeof(struct kse));
}

fixpt_t
sched_pctcpu(struct thread *td)
{
	struct kse *ke;

	ke = td->td_kse;
	return (ke->ke_pctcpu);
}

void
sched_tick(void)
{
}
#define KERN_SWITCH_INCLUDE 1
#include "kern/kern_switch.c"
OpenPOWER on IntegriCloud