forked from torvalds/linux
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ext.c
4035 lines (3417 loc) · 109 KB
/
ext.c
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
/* SPDX-License-Identifier: GPL-2.0 */
/*
* Copyright (c) 2022 Meta Platforms, Inc. and affiliates.
* Copyright (c) 2022 Tejun Heo <tj@kernel.org>
* Copyright (c) 2022 David Vernet <dvernet@meta.com>
*/
#define SCX_OP_IDX(op) (offsetof(struct sched_ext_ops, op) / sizeof(void (*)(void)))
enum scx_internal_consts {
SCX_NR_ONLINE_OPS = SCX_OP_IDX(init),
SCX_DSP_DFL_MAX_BATCH = 32,
SCX_DSP_MAX_LOOPS = 32,
SCX_WATCHDOG_MAX_TIMEOUT = 30 * HZ,
};
enum scx_ops_enable_state {
SCX_OPS_PREPPING,
SCX_OPS_ENABLING,
SCX_OPS_ENABLED,
SCX_OPS_DISABLING,
SCX_OPS_DISABLED,
};
/*
* sched_ext_entity->ops_state
*
* Used to track the task ownership between the SCX core and the BPF scheduler.
* State transitions look as follows:
*
* NONE -> QUEUEING -> QUEUED -> DISPATCHING
* ^ | |
* | v v
* \-------------------------------/
*
* QUEUEING and DISPATCHING states can be waited upon. See wait_ops_state() call
* sites for explanations on the conditions being waited upon and why they are
* safe. Transitions out of them into NONE or QUEUED must store_release and the
* waiters should load_acquire.
*
* Tracking scx_ops_state enables sched_ext core to reliably determine whether
* any given task can be dispatched by the BPF scheduler at all times and thus
* relaxes the requirements on the BPF scheduler. This allows the BPF scheduler
* to try to dispatch any task anytime regardless of its state as the SCX core
* can safely reject invalid dispatches.
*/
enum scx_ops_state {
SCX_OPSS_NONE, /* owned by the SCX core */
SCX_OPSS_QUEUEING, /* in transit to the BPF scheduler */
SCX_OPSS_QUEUED, /* owned by the BPF scheduler */
SCX_OPSS_DISPATCHING, /* in transit back to the SCX core */
/*
* QSEQ brands each QUEUED instance so that, when dispatch races
* dequeue/requeue, the dispatcher can tell whether it still has a claim
* on the task being dispatched.
*/
SCX_OPSS_QSEQ_SHIFT = 2,
SCX_OPSS_STATE_MASK = (1LLU << SCX_OPSS_QSEQ_SHIFT) - 1,
SCX_OPSS_QSEQ_MASK = ~SCX_OPSS_STATE_MASK,
};
/*
* During exit, a task may schedule after losing its PIDs. When disabling the
* BPF scheduler, we need to be able to iterate tasks in every state to
* guarantee system safety. Maintain a dedicated task list which contains every
* task between its fork and eventual free.
*/
static DEFINE_SPINLOCK(scx_tasks_lock);
static LIST_HEAD(scx_tasks);
/* ops enable/disable */
static struct kthread_worker *scx_ops_helper;
static DEFINE_MUTEX(scx_ops_enable_mutex);
DEFINE_STATIC_KEY_FALSE(__scx_ops_enabled);
DEFINE_STATIC_PERCPU_RWSEM(scx_fork_rwsem);
static atomic_t scx_ops_enable_state_var = ATOMIC_INIT(SCX_OPS_DISABLED);
static bool scx_switch_all_req;
static bool scx_switching_all;
DEFINE_STATIC_KEY_FALSE(__scx_switched_all);
static struct sched_ext_ops scx_ops;
static bool scx_warned_zero_slice;
static DEFINE_STATIC_KEY_FALSE(scx_ops_enq_last);
static DEFINE_STATIC_KEY_FALSE(scx_ops_enq_exiting);
DEFINE_STATIC_KEY_FALSE(scx_ops_cpu_preempt);
static DEFINE_STATIC_KEY_FALSE(scx_builtin_idle_enabled);
struct static_key_false scx_has_op[SCX_NR_ONLINE_OPS] =
{ [0 ... SCX_NR_ONLINE_OPS-1] = STATIC_KEY_FALSE_INIT };
static atomic_t scx_exit_type = ATOMIC_INIT(SCX_EXIT_DONE);
static struct scx_exit_info scx_exit_info;
static atomic64_t scx_nr_rejected = ATOMIC64_INIT(0);
/*
* The maximum amount of time in jiffies that a task may be runnable without
* being scheduled on a CPU. If this timeout is exceeded, it will trigger
* scx_ops_error().
*/
unsigned long scx_watchdog_timeout;
/*
* The last time the delayed work was run. This delayed work relies on
* ksoftirqd being able to run to service timer interrupts, so it's possible
* that this work itself could get wedged. To account for this, we check that
* it's not stalled in the timer tick, and trigger an error if it is.
*/
unsigned long scx_watchdog_timestamp = INITIAL_JIFFIES;
static struct delayed_work scx_watchdog_work;
/* idle tracking */
#ifdef CONFIG_SMP
#ifdef CONFIG_CPUMASK_OFFSTACK
#define CL_ALIGNED_IF_ONSTACK
#else
#define CL_ALIGNED_IF_ONSTACK __cacheline_aligned_in_smp
#endif
static struct {
cpumask_var_t cpu;
cpumask_var_t smt;
} idle_masks CL_ALIGNED_IF_ONSTACK;
static bool __cacheline_aligned_in_smp scx_has_idle_cpus;
#endif /* CONFIG_SMP */
/* for %SCX_KICK_WAIT */
static u64 __percpu *scx_kick_cpus_pnt_seqs;
/*
* Direct dispatch marker.
*
* Non-NULL values are used for direct dispatch from enqueue path. A valid
* pointer points to the task currently being enqueued. An ERR_PTR value is used
* to indicate that direct dispatch has already happened.
*/
static DEFINE_PER_CPU(struct task_struct *, direct_dispatch_task);
/* dispatch queues */
static struct scx_dispatch_q __cacheline_aligned_in_smp scx_dsq_global;
static const struct rhashtable_params dsq_hash_params = {
.key_len = 8,
.key_offset = offsetof(struct scx_dispatch_q, id),
.head_offset = offsetof(struct scx_dispatch_q, hash_node),
};
static struct rhashtable dsq_hash;
static LLIST_HEAD(dsqs_to_free);
/* dispatch buf */
struct scx_dsp_buf_ent {
struct task_struct *task;
u64 qseq;
u64 dsq_id;
u64 enq_flags;
};
static u32 scx_dsp_max_batch;
static struct scx_dsp_buf_ent __percpu *scx_dsp_buf;
struct scx_dsp_ctx {
struct rq *rq;
struct rq_flags *rf;
u32 buf_cursor;
u32 nr_tasks;
};
static DEFINE_PER_CPU(struct scx_dsp_ctx, scx_dsp_ctx);
void scx_bpf_dispatch(struct task_struct *p, u64 dsq_id, u64 slice,
u64 enq_flags);
void scx_bpf_kick_cpu(s32 cpu, u64 flags);
struct scx_task_iter {
struct sched_ext_entity cursor;
struct task_struct *locked;
struct rq *rq;
struct rq_flags rf;
};
#define SCX_HAS_OP(op) static_branch_likely(&scx_has_op[SCX_OP_IDX(op)])
/*
* scx_kf_mask enforcement. Some kfuncs can only be called from specific SCX
* ops. When invoking SCX ops, SCX_CALL_OP[_RET]() should be used to indicate
* the allowed kfuncs and those kfuncs should use scx_kf_allowed() to check
* whether it's running from an allowed context.
*/
static void scx_kf_allow(u32 mask)
{
u32 allowed_nesters = 0;
/*
* INIT|SLEEPABLE can nest others but not themselves. CPU_RELEASE can
* additionally nest ENQUEUE_DISPATCH.
*/
if (!(mask & (SCX_KF_INIT | SCX_KF_SLEEPABLE)))
allowed_nesters |= SCX_KF_INIT | SCX_KF_SLEEPABLE;
if (mask & SCX_KF_ENQUEUE_DISPATCH)
allowed_nesters |= SCX_KF_CPU_RELEASE;
WARN_ONCE(current->scx.kf_mask & ~allowed_nesters,
"invalid nesting current->scx.kf_mask=0x%x mask=0x%x allowed_nesters=0x%x\n",
current->scx.kf_mask, mask, allowed_nesters);
current->scx.kf_mask |= mask;
}
static void scx_kf_disallow(u32 mask)
{
current->scx.kf_mask &= ~mask;
}
#define SCX_CALL_OP(mask, op, args...) \
do { \
scx_kf_allow(mask); \
scx_ops.op(args); \
scx_kf_disallow(mask); \
} while (0)
#define SCX_CALL_OP_RET(mask, op, args...) \
({ \
__typeof__(scx_ops.op(args)) __ret; \
scx_kf_allow(mask); \
__ret = scx_ops.op(args); \
scx_kf_disallow(mask); \
__ret; \
})
static bool scx_kf_allowed(u32 mask)
{
if (unlikely(!(current->scx.kf_mask & mask))) {
scx_ops_error("kfunc with mask 0x%x called from an operation only allowing 0x%x",
mask, current->scx.kf_mask);
return false;
}
if (unlikely((mask & SCX_KF_SLEEPABLE) && in_interrupt())) {
scx_ops_error("sleepable kfunc called from non-sleepable context");
return false;
}
if (unlikely((mask & SCX_KF_CPU_RELEASE) &&
(current->scx.kf_mask & __SCX_KF_TERMINAL))) {
scx_ops_error("cpu_release kfunc called from terminal operations");
return false;
}
return true;
}
/**
* scx_task_iter_init - Initialize a task iterator
* @iter: iterator to init
*
* Initialize @iter. Must be called with scx_tasks_lock held. Once initialized,
* @iter must eventually be exited with scx_task_iter_exit().
*
* scx_tasks_lock may be released between this and the first next() call or
* between any two next() calls. If scx_tasks_lock is released between two
* next() calls, the caller is responsible for ensuring that the task being
* iterated remains accessible either through RCU read lock or obtaining a
* reference count.
*
* All tasks which existed when the iteration started are guaranteed to be
* visited as long as they still exist.
*/
static void scx_task_iter_init(struct scx_task_iter *iter)
{
lockdep_assert_held(&scx_tasks_lock);
iter->cursor = (struct sched_ext_entity){ .flags = SCX_TASK_CURSOR };
list_add(&iter->cursor.tasks_node, &scx_tasks);
iter->locked = NULL;
}
/**
* scx_task_iter_exit - Exit a task iterator
* @iter: iterator to exit
*
* Exit a previously initialized @iter. Must be called with scx_tasks_lock held.
* If the iterator holds a task's rq lock, that rq lock is released. See
* scx_task_iter_init() for details.
*/
static void scx_task_iter_exit(struct scx_task_iter *iter)
{
struct list_head *cursor = &iter->cursor.tasks_node;
lockdep_assert_held(&scx_tasks_lock);
if (iter->locked) {
task_rq_unlock(iter->rq, iter->locked, &iter->rf);
iter->locked = NULL;
}
if (list_empty(cursor))
return;
list_del_init(cursor);
}
/**
* scx_task_iter_next - Next task
* @iter: iterator to walk
*
* Visit the next task. See scx_task_iter_init() for details.
*/
static struct task_struct *scx_task_iter_next(struct scx_task_iter *iter)
{
struct list_head *cursor = &iter->cursor.tasks_node;
struct sched_ext_entity *pos;
lockdep_assert_held(&scx_tasks_lock);
list_for_each_entry(pos, cursor, tasks_node) {
if (&pos->tasks_node == &scx_tasks)
return NULL;
if (!(pos->flags & SCX_TASK_CURSOR)) {
list_move(cursor, &pos->tasks_node);
return container_of(pos, struct task_struct, scx);
}
}
/* can't happen, should always terminate at scx_tasks above */
BUG();
}
/**
* scx_task_iter_next_filtered - Next non-idle task
* @iter: iterator to walk
*
* Visit the next non-idle task. See scx_task_iter_init() for details.
*/
static struct task_struct *
scx_task_iter_next_filtered(struct scx_task_iter *iter)
{
struct task_struct *p;
while ((p = scx_task_iter_next(iter))) {
if (!is_idle_task(p))
return p;
}
return NULL;
}
/**
* scx_task_iter_next_filtered_locked - Next non-idle task with its rq locked
* @iter: iterator to walk
*
* Visit the next non-idle task with its rq lock held. See scx_task_iter_init()
* for details.
*/
static struct task_struct *
scx_task_iter_next_filtered_locked(struct scx_task_iter *iter)
{
struct task_struct *p;
if (iter->locked) {
task_rq_unlock(iter->rq, iter->locked, &iter->rf);
iter->locked = NULL;
}
p = scx_task_iter_next_filtered(iter);
if (!p)
return NULL;
iter->rq = task_rq_lock(p, &iter->rf);
iter->locked = p;
return p;
}
static enum scx_ops_enable_state scx_ops_enable_state(void)
{
return atomic_read(&scx_ops_enable_state_var);
}
static enum scx_ops_enable_state
scx_ops_set_enable_state(enum scx_ops_enable_state to)
{
return atomic_xchg(&scx_ops_enable_state_var, to);
}
static bool scx_ops_tryset_enable_state(enum scx_ops_enable_state to,
enum scx_ops_enable_state from)
{
int from_v = from;
return atomic_try_cmpxchg(&scx_ops_enable_state_var, &from_v, to);
}
static bool scx_ops_disabling(void)
{
return unlikely(scx_ops_enable_state() == SCX_OPS_DISABLING);
}
/**
* wait_ops_state - Busy-wait the specified ops state to end
* @p: target task
* @opss: state to wait the end of
*
* Busy-wait for @p to transition out of @opss. This can only be used when the
* state part of @opss is %SCX_QUEUEING or %SCX_DISPATCHING. This function also
* has load_acquire semantics to ensure that the caller can see the updates made
* in the enqueueing and dispatching paths.
*/
static void wait_ops_state(struct task_struct *p, u64 opss)
{
do {
cpu_relax();
} while (atomic64_read_acquire(&p->scx.ops_state) == opss);
}
/**
* ops_cpu_valid - Verify a cpu number
* @cpu: cpu number which came from a BPF ops
*
* @cpu is a cpu number which came from the BPF scheduler and can be any value.
* Verify that it is in range and one of the possible cpus.
*/
static bool ops_cpu_valid(s32 cpu)
{
return likely(cpu >= 0 && cpu < nr_cpu_ids && cpu_possible(cpu));
}
/**
* ops_sanitize_err - Sanitize a -errno value
* @ops_name: operation to blame on failure
* @err: -errno value to sanitize
*
* Verify @err is a valid -errno. If not, trigger scx_ops_error() and return
* -%EPROTO. This is necessary because returning a rogue -errno up the chain can
* cause misbehaviors. For an example, a large negative return from
* ops.prep_enable() triggers an oops when passed up the call chain because the
* value fails IS_ERR() test after being encoded with ERR_PTR() and then is
* handled as a pointer.
*/
static int ops_sanitize_err(const char *ops_name, s32 err)
{
if (err < 0 && err >= -MAX_ERRNO)
return err;
scx_ops_error("ops.%s() returned an invalid errno %d", ops_name, err);
return -EPROTO;
}
/**
* touch_core_sched - Update timestamp used for core-sched task ordering
* @rq: rq to read clock from, must be locked
* @p: task to update the timestamp for
*
* Update @p->scx.core_sched_at timestamp. This is used by scx_prio_less() to
* implement global or local-DSQ FIFO ordering for core-sched. Should be called
* when a task becomes runnable and its turn on the CPU ends (e.g. slice
* exhaustion).
*/
static void touch_core_sched(struct rq *rq, struct task_struct *p)
{
#ifdef CONFIG_SCHED_CORE
p->scx.core_sched_at = rq_clock_task(rq);
#endif
}
/**
* touch_core_sched_dispatch - Update core-sched timestamp on dispatch
* @rq: rq to read clock from, must be locked
* @p: task being dispatched
*
* If the BPF scheduler implements custom core-sched ordering via
* ops.core_sched_before(), @p->scx.core_sched_at is used to implement FIFO
* ordering within each local DSQ. This function is called from dispatch paths
* and updates @p->scx.core_sched_at if custom core-sched ordering is in effect.
*/
static void touch_core_sched_dispatch(struct rq *rq, struct task_struct *p)
{
lockdep_assert_rq_held(rq);
assert_clock_updated(rq);
#ifdef CONFIG_SCHED_CORE
if (SCX_HAS_OP(core_sched_before))
touch_core_sched(rq, p);
#endif
}
static void update_curr_scx(struct rq *rq)
{
struct task_struct *curr = rq->curr;
u64 now = rq_clock_task(rq);
u64 delta_exec;
if (time_before_eq64(now, curr->se.exec_start))
return;
delta_exec = now - curr->se.exec_start;
curr->se.exec_start = now;
curr->se.sum_exec_runtime += delta_exec;
account_group_exec_runtime(curr, delta_exec);
cgroup_account_cputime(curr, delta_exec);
if (curr->scx.slice != SCX_SLICE_INF) {
curr->scx.slice -= min(curr->scx.slice, delta_exec);
if (!curr->scx.slice)
touch_core_sched(rq, curr);
}
}
static void dispatch_enqueue(struct scx_dispatch_q *dsq, struct task_struct *p,
u64 enq_flags)
{
bool is_local = dsq->id == SCX_DSQ_LOCAL;
WARN_ON_ONCE(p->scx.dsq || !list_empty(&p->scx.dsq_node));
if (!is_local) {
raw_spin_lock(&dsq->lock);
if (unlikely(dsq->id == SCX_DSQ_INVALID)) {
scx_ops_error("attempting to dispatch to a destroyed dsq");
/* fall back to the global dsq */
raw_spin_unlock(&dsq->lock);
dsq = &scx_dsq_global;
raw_spin_lock(&dsq->lock);
}
}
if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT))
list_add(&p->scx.dsq_node, &dsq->fifo);
else
list_add_tail(&p->scx.dsq_node, &dsq->fifo);
dsq->nr++;
p->scx.dsq = dsq;
/*
* We're transitioning out of QUEUEING or DISPATCHING. store_release to
* match waiters' load_acquire.
*/
if (enq_flags & SCX_ENQ_CLEAR_OPSS)
atomic64_set_release(&p->scx.ops_state, SCX_OPSS_NONE);
if (is_local) {
struct rq *rq = container_of(dsq, struct rq, scx.local_dsq);
bool preempt = false;
if ((enq_flags & SCX_ENQ_PREEMPT) && p != rq->curr &&
rq->curr->sched_class == &ext_sched_class) {
rq->curr->scx.slice = 0;
preempt = true;
}
if (preempt || sched_class_above(&ext_sched_class,
rq->curr->sched_class))
resched_curr(rq);
} else {
raw_spin_unlock(&dsq->lock);
}
}
static void dispatch_dequeue(struct scx_rq *scx_rq, struct task_struct *p)
{
struct scx_dispatch_q *dsq = p->scx.dsq;
bool is_local = dsq == &scx_rq->local_dsq;
if (!dsq) {
WARN_ON_ONCE(!list_empty(&p->scx.dsq_node));
/*
* When dispatching directly from the BPF scheduler to a local
* DSQ, the task isn't associated with any DSQ but
* @p->scx.holding_cpu may be set under the protection of
* %SCX_OPSS_DISPATCHING.
*/
if (p->scx.holding_cpu >= 0)
p->scx.holding_cpu = -1;
return;
}
if (!is_local)
raw_spin_lock(&dsq->lock);
/*
* Now that we hold @dsq->lock, @p->holding_cpu and @p->scx.dsq_node
* can't change underneath us.
*/
if (p->scx.holding_cpu < 0) {
/* @p must still be on @dsq, dequeue */
WARN_ON_ONCE(list_empty(&p->scx.dsq_node));
list_del_init(&p->scx.dsq_node);
dsq->nr--;
} else {
/*
* We're racing against dispatch_to_local_dsq() which already
* removed @p from @dsq and set @p->scx.holding_cpu. Clear the
* holding_cpu which tells dispatch_to_local_dsq() that it lost
* the race.
*/
WARN_ON_ONCE(!list_empty(&p->scx.dsq_node));
p->scx.holding_cpu = -1;
}
p->scx.dsq = NULL;
if (!is_local)
raw_spin_unlock(&dsq->lock);
}
static struct scx_dispatch_q *find_non_local_dsq(u64 dsq_id)
{
lockdep_assert(rcu_read_lock_any_held());
if (dsq_id == SCX_DSQ_GLOBAL)
return &scx_dsq_global;
else
return rhashtable_lookup_fast(&dsq_hash, &dsq_id,
dsq_hash_params);
}
static struct scx_dispatch_q *find_dsq_for_dispatch(struct rq *rq, u64 dsq_id,
struct task_struct *p)
{
struct scx_dispatch_q *dsq;
if (dsq_id == SCX_DSQ_LOCAL)
return &rq->scx.local_dsq;
dsq = find_non_local_dsq(dsq_id);
if (unlikely(!dsq)) {
scx_ops_error("non-existent DSQ 0x%llx for %s[%d]",
dsq_id, p->comm, p->pid);
return &scx_dsq_global;
}
return dsq;
}
static void direct_dispatch(struct task_struct *ddsp_task, struct task_struct *p,
u64 dsq_id, u64 enq_flags)
{
struct scx_dispatch_q *dsq;
/* @p must match the task which is being enqueued */
if (unlikely(p != ddsp_task)) {
if (IS_ERR(ddsp_task))
scx_ops_error("%s[%d] already direct-dispatched",
p->comm, p->pid);
else
scx_ops_error("enqueueing %s[%d] but trying to direct-dispatch %s[%d]",
ddsp_task->comm, ddsp_task->pid,
p->comm, p->pid);
return;
}
/*
* %SCX_DSQ_LOCAL_ON is not supported during direct dispatch because
* dispatching to the local DSQ of a different CPU requires unlocking
* the current rq which isn't allowed in the enqueue path. Use
* ops.select_cpu() to be on the target CPU and then %SCX_DSQ_LOCAL.
*/
if (unlikely((dsq_id & SCX_DSQ_LOCAL_ON) == SCX_DSQ_LOCAL_ON)) {
scx_ops_error("SCX_DSQ_LOCAL_ON can't be used for direct-dispatch");
return;
}
touch_core_sched_dispatch(task_rq(p), p);
dsq = find_dsq_for_dispatch(task_rq(p), dsq_id, p);
dispatch_enqueue(dsq, p, enq_flags | SCX_ENQ_CLEAR_OPSS);
/*
* Mark that dispatch already happened by spoiling direct_dispatch_task
* with a non-NULL value which can never match a valid task pointer.
*/
__this_cpu_write(direct_dispatch_task, ERR_PTR(-ESRCH));
}
static bool test_rq_online(struct rq *rq)
{
#ifdef CONFIG_SMP
return rq->online;
#else
return true;
#endif
}
static void do_enqueue_task(struct rq *rq, struct task_struct *p, u64 enq_flags,
int sticky_cpu)
{
struct task_struct **ddsp_taskp;
u64 qseq;
WARN_ON_ONCE(!(p->scx.flags & SCX_TASK_QUEUED));
if (p->scx.flags & SCX_TASK_ENQ_LOCAL) {
enq_flags |= SCX_ENQ_LOCAL;
p->scx.flags &= ~SCX_TASK_ENQ_LOCAL;
}
/* rq migration */
if (sticky_cpu == cpu_of(rq))
goto local_norefill;
/*
* If !rq->online, we already told the BPF scheduler that the CPU is
* offline. We're just trying to on/offline the CPU. Don't bother the
* BPF scheduler.
*/
if (unlikely(!test_rq_online(rq)))
goto local;
/* see %SCX_OPS_ENQ_EXITING */
if (!static_branch_unlikely(&scx_ops_enq_exiting) &&
unlikely(p->flags & PF_EXITING))
goto local;
/* see %SCX_OPS_ENQ_LAST */
if (!static_branch_unlikely(&scx_ops_enq_last) &&
(enq_flags & SCX_ENQ_LAST))
goto local;
if (!SCX_HAS_OP(enqueue)) {
if (enq_flags & SCX_ENQ_LOCAL)
goto local;
else
goto global;
}
/* DSQ bypass didn't trigger, enqueue on the BPF scheduler */
qseq = rq->scx.ops_qseq++ << SCX_OPSS_QSEQ_SHIFT;
WARN_ON_ONCE(atomic64_read(&p->scx.ops_state) != SCX_OPSS_NONE);
atomic64_set(&p->scx.ops_state, SCX_OPSS_QUEUEING | qseq);
ddsp_taskp = this_cpu_ptr(&direct_dispatch_task);
WARN_ON_ONCE(*ddsp_taskp);
*ddsp_taskp = p;
SCX_CALL_OP(SCX_KF_ENQUEUE_DISPATCH, enqueue, p, enq_flags);
/*
* If not directly dispatched, QUEUEING isn't clear yet and dispatch or
* dequeue may be waiting. The store_release matches their load_acquire.
*/
if (*ddsp_taskp == p)
atomic64_set_release(&p->scx.ops_state, SCX_OPSS_QUEUED | qseq);
*ddsp_taskp = NULL;
return;
local:
/*
* For task-ordering, slice refill must be treated as implying the end
* of the current slice. Otherwise, the longer @p stays on the CPU, the
* higher priority it becomes from scx_prio_less()'s POV.
*/
touch_core_sched(rq, p);
p->scx.slice = SCX_SLICE_DFL;
local_norefill:
dispatch_enqueue(&rq->scx.local_dsq, p, enq_flags);
return;
global:
touch_core_sched(rq, p); /* see the comment in local: */
p->scx.slice = SCX_SLICE_DFL;
dispatch_enqueue(&scx_dsq_global, p, enq_flags);
}
static bool watchdog_task_watched(const struct task_struct *p)
{
return !list_empty(&p->scx.watchdog_node);
}
static void watchdog_watch_task(struct rq *rq, struct task_struct *p)
{
lockdep_assert_rq_held(rq);
if (p->scx.flags & SCX_TASK_WATCHDOG_RESET)
p->scx.runnable_at = jiffies;
p->scx.flags &= ~SCX_TASK_WATCHDOG_RESET;
list_add_tail(&p->scx.watchdog_node, &rq->scx.watchdog_list);
}
static void watchdog_unwatch_task(struct task_struct *p, bool reset_timeout)
{
list_del_init(&p->scx.watchdog_node);
if (reset_timeout)
p->scx.flags |= SCX_TASK_WATCHDOG_RESET;
}
static void enqueue_task_scx(struct rq *rq, struct task_struct *p, int enq_flags)
{
int sticky_cpu = p->scx.sticky_cpu;
if (sticky_cpu >= 0)
p->scx.sticky_cpu = -1;
/*
* Restoring a running task will be immediately followed by
* set_next_task_scx() which expects the task to not be on the BPF
* scheduler as tasks can only start running through local DSQs. Force
* direct-dispatch into the local DSQ by setting the sticky_cpu.
*/
if (unlikely(enq_flags & ENQUEUE_RESTORE) && task_current(rq, p))
sticky_cpu = cpu_of(rq);
if (p->scx.flags & SCX_TASK_QUEUED) {
WARN_ON_ONCE(!watchdog_task_watched(p));
return;
}
watchdog_watch_task(rq, p);
p->scx.flags |= SCX_TASK_QUEUED;
rq->scx.nr_running++;
add_nr_running(rq, 1);
if (SCX_HAS_OP(runnable))
scx_ops.runnable(p, enq_flags);
if (enq_flags & SCX_ENQ_WAKEUP)
touch_core_sched(rq, p);
do_enqueue_task(rq, p, enq_flags, sticky_cpu);
}
static void ops_dequeue(struct task_struct *p, u64 deq_flags)
{
u64 opss;
watchdog_unwatch_task(p, false);
/* acquire ensures that we see the preceding updates on QUEUED */
opss = atomic64_read_acquire(&p->scx.ops_state);
switch (opss & SCX_OPSS_STATE_MASK) {
case SCX_OPSS_NONE:
break;
case SCX_OPSS_QUEUEING:
/*
* QUEUEING is started and finished while holding @p's rq lock.
* As we're holding the rq lock now, we shouldn't see QUEUEING.
*/
BUG();
case SCX_OPSS_QUEUED:
if (SCX_HAS_OP(dequeue))
scx_ops.dequeue(p, deq_flags);
if (atomic64_try_cmpxchg(&p->scx.ops_state, &opss,
SCX_OPSS_NONE))
break;
fallthrough;
case SCX_OPSS_DISPATCHING:
/*
* If @p is being dispatched from the BPF scheduler to a DSQ,
* wait for the transfer to complete so that @p doesn't get
* added to its DSQ after dequeueing is complete.
*
* As we're waiting on DISPATCHING with the rq locked, the
* dispatching side shouldn't try to lock the rq while
* DISPATCHING is set. See dispatch_to_local_dsq().
*
* DISPATCHING shouldn't have qseq set and control can reach
* here with NONE @opss from the above QUEUED case block.
* Explicitly wait on %SCX_OPSS_DISPATCHING instead of @opss.
*/
wait_ops_state(p, SCX_OPSS_DISPATCHING);
BUG_ON(atomic64_read(&p->scx.ops_state) != SCX_OPSS_NONE);
break;
}
}
static void dequeue_task_scx(struct rq *rq, struct task_struct *p, int deq_flags)
{
struct scx_rq *scx_rq = &rq->scx;
if (!(p->scx.flags & SCX_TASK_QUEUED)) {
WARN_ON_ONCE(watchdog_task_watched(p));
return;
}
ops_dequeue(p, deq_flags);
/*
* A currently running task which is going off @rq first gets dequeued
* and then stops running. As we want running <-> stopping transitions
* to be contained within runnable <-> quiescent transitions, trigger
* ->stopping() early here instead of in put_prev_task_scx().
*
* @p may go through multiple stopping <-> running transitions between
* here and put_prev_task_scx() if task attribute changes occur while
* balance_scx() leaves @rq unlocked. However, they don't contain any
* information meaningful to the BPF scheduler and can be suppressed by
* skipping the callbacks if the task is !QUEUED.
*/
if (SCX_HAS_OP(stopping) && task_current(rq, p)) {
update_curr_scx(rq);
scx_ops.stopping(p, false);
}
if (SCX_HAS_OP(quiescent))
scx_ops.quiescent(p, deq_flags);
if (deq_flags & SCX_DEQ_SLEEP)
p->scx.flags |= SCX_TASK_DEQD_FOR_SLEEP;
else
p->scx.flags &= ~SCX_TASK_DEQD_FOR_SLEEP;
p->scx.flags &= ~SCX_TASK_QUEUED;
scx_rq->nr_running--;
sub_nr_running(rq, 1);
dispatch_dequeue(scx_rq, p);
}
static void yield_task_scx(struct rq *rq)
{
struct task_struct *p = rq->curr;
if (SCX_HAS_OP(yield))
scx_ops.yield(p, NULL);
else
p->scx.slice = 0;
}
static bool yield_to_task_scx(struct rq *rq, struct task_struct *to)
{
struct task_struct *from = rq->curr;
if (SCX_HAS_OP(yield))
return scx_ops.yield(from, to);
else
return false;
}
#ifdef CONFIG_SMP
/**
* move_task_to_local_dsq - Move a task from a different rq to a local DSQ
* @rq: rq to move the task into, currently locked
* @p: task to move
*
* Move @p which is currently on a different rq to @rq's local DSQ. The caller
* must:
*
* 1. Start with exclusive access to @p either through its DSQ lock or
* %SCX_OPSS_DISPATCHING flag.
*
* 2. Set @p->scx.holding_cpu to raw_smp_processor_id().
*
* 3. Remember task_rq(@p). Release the exclusive access so that we don't
* deadlock with dequeue.
*
* 4. Lock @rq and the task_rq from #3.
*
* 5. Call this function.
*
* Returns %true if @p was successfully moved. %false after racing dequeue and
* losing.
*/
static bool move_task_to_local_dsq(struct rq *rq, struct task_struct *p)
{
struct rq *task_rq;
lockdep_assert_rq_held(rq);
/*
* If dequeue got to @p while we were trying to lock both rq's, it'd
* have cleared @p->scx.holding_cpu to -1. While other cpus may have
* updated it to different values afterwards, as this operation can't be
* preempted or recurse, @p->scx.holding_cpu can never become
* raw_smp_processor_id() again before we're done. Thus, we can tell
* whether we lost to dequeue by testing whether @p->scx.holding_cpu is
* still raw_smp_processor_id().
*
* See dispatch_dequeue() for the counterpart.
*/
if (unlikely(p->scx.holding_cpu != raw_smp_processor_id()))
return false;
/* @p->rq couldn't have changed if we're still the holding cpu */
task_rq = task_rq(p);
lockdep_assert_rq_held(task_rq);
WARN_ON_ONCE(!cpumask_test_cpu(cpu_of(rq), p->cpus_ptr));
deactivate_task(task_rq, p, 0);
set_task_cpu(p, cpu_of(rq));
p->scx.sticky_cpu = cpu_of(rq);
activate_task(rq, p, 0);
return true;
}
/**
* dispatch_to_local_dsq_lock - Ensure source and desitnation rq's are locked
* @rq: current rq which is locked
* @rf: rq_flags to use when unlocking @rq
* @src_rq: rq to move task from
* @dst_rq: rq to move task to
*
* We're holding @rq lock and trying to dispatch a task from @src_rq to
* @dst_rq's local DSQ and thus need to lock both @src_rq and @dst_rq. Whether
* @rq stays locked isn't important as long as the state is restored after
* dispatch_to_local_dsq_unlock().
*/
static void dispatch_to_local_dsq_lock(struct rq *rq, struct rq_flags *rf,
struct rq *src_rq, struct rq *dst_rq)