Linux Advent Calendar 2014 14日目: sched-design-CFS.txtの和訳

Linux Advent Calendar 2014

こんにちは、hiraku_wfsです。
今年はLinux KernelのDocumentation/scheduler/sched-design-CFS.txtを和訳してみました。
過去には2009年頃にsyuu1228さんが機械翻訳ベースの和訳を試みています(sched-design-CFS.txtの和訳 - syuu1228's blog)が、今回v3.18-rc7のものを訳してみます。
ところどころ(ちょっとやりすぎかもしれない)意訳を入れています。
場所によっては原文を見た方が分かりやすい箇所がいくつかあるので、原文と併記しています。
(やっぱり翻訳の専門家ではないので日本語でどう表現したものか悩んだりと結構大変でした...)

原著作者: Ingo Molnar

                      =============
                      CFS Scheduler
                      CFSスケジューラ
                      =============


1.  OVERVIEW
1.  概要

CFS stands for "Completely Fair Scheduler," and is the new "desktop" process
scheduler implemented by Ingo Molnar and merged in Linux 2.6.23.  It is the
replacement for the previous vanilla scheduler's SCHED_OTHER interactivity
code.
CFSは"Completely Fair Scheduler"の略で、Ingo Molnarによって実装された新しい
"デスクトップ向け"プロセススケジューラであり、Linux 2.6.23でマージされました。これは
SCHED_OTHERのために以前のバニラカーネルが持っていた対話的処理向けスケジューラの
置き換えです。

80% of CFS's design can be summed up in a single sentence: CFS basically models
an "ideal, precise multi-tasking CPU" on real hardware.
CFSの設計の80%は次の一文で要約できるでしょう: 一言で言うとCFSは実ハードウェア上で"理想的で
正確なマルチタスクCPU"をモデル化します。

"Ideal multi-tasking CPU" is a (non-existent  :-)) CPU that has 100% physical
power and which can run each task at precise equal speed, in parallel, each at
1/nr_running speed.  For example: if there are 2 tasks running, then it runs
each at 50% physical power --- i.e., actually in parallel.
"理想的なマルチタスクCPU"というのは(存在しないですが :))、物理CPU性能を100%使用でき、
かつ、それぞれのタスクをちょうど等速になるように、同時に1/nr_runningの速度で走行させるよう
なCPUです。例えば、もし2個のタスクが実行されていた場合、そのCPUはそれぞれのタスクを50%の物理
CPU性能で実行します --- すなわち同時にということです。

On real hardware, we can run only a single task at once, so we have to
introduce the concept of "virtual runtime."  The virtual runtime of a task
specifies when its next timeslice would start execution on the ideal
multi-tasking CPU described above.  In practice, the virtual runtime of a task
is its actual runtime normalized to the total number of running tasks.
実ハードウェアでは、一度に一つのタスクしか実行させることができないので、"仮想実行時間"
という概念を導入しなければなりません。タスクの仮想実行時間は、上述した理想的なマルチタスクCPU
上で、いつ次のタイムスライスが実行を開始するかを指し示します。実際には、タスクの仮想実行時間は
実行中のタスクの総数で正規化された事実上の実行時間です。

2.  FEW IMPLEMENTATION DETAILS
2.  ほんの少し実装の詳細について

In CFS the virtual runtime is expressed and tracked via the per-task
p->se.vruntime (nanosec-unit) value.  This way, it's possible to accurately
timestamp and measure the "expected CPU time" a task should have gotten.
CFSでは仮想実行時間がタスクごとのp->se.vruntime (ナノ秒単位)の値によって表現され、また追跡
されます。このようにすることで、タスクが得るべきだった"期待されたCPU時間"に関して
タイムスタンプを付けたり測定したりといったことが正確に可能になります。

[ small detail: on "ideal" hardware, at any time all tasks would have the same
  p->se.vruntime value --- i.e., tasks would execute simultaneously and no task
  would ever get "out of balance" from the "ideal" share of CPU time.  ]
[ ちょっとした詳細: "理想的な"ハードウェア上では、全てのタスクはいつでも同じp->se.vruntime
の値を持っていることでしょう。---言い換えると全てのタスクは同時に実行されるので、CPU時間の
"理想的な"分け前から"不均衡"になるタスクは決して無いでしょう。]

CFS's task picking logic is based on this p->se.vruntime value and it is thus
very simple: it always tries to run the task with the smallest p->se.vruntime
value (i.e., the task which executed least so far).  CFS always tries to split
up CPU time between runnable tasks as close to "ideal multitasking hardware" as
possible.
CFSのタスク選択ロジックはこのp->se.vruntimeの値に基づいており、次のように非常に単純なもの
です: タスク選択ロジックは常に最小のp->se.vruntimeの値を持つタスクを実行しようとします
(つまり、今まで最も実行されていないタスクです)。CFSは常に"理想的なマルチタスク・
ハードウェア"にできる限り近づけようと実行可能タスク間でCPU時間を分割しようとします。

Most of the rest of CFS's design just falls out of this really simple concept,
with a few add-on embellishments like nice levels, multiprocessing and various
algorithm variants to recognize sleepers.
CFSの設計の残りの大部分はこの本当に単純な考え方からは全く離れたものであり、nice値やマルチ
プロセッシング、sleeperを認識するためのいくつかのアルゴリズムの変化形といった少数の追加的な
装飾物です。



3.  THE RBTREE
3.  RBTREE(赤黒木)

CFS's design is quite radical: it does not use the old data structures for the
runqueues, but it uses a time-ordered rbtree to build a "timeline" of future
task execution, and thus has no "array switch" artifacts (by which both the
previous vanilla scheduler and RSDL/SD are affected).
CFSの設計はとても急進的です: 昔からあるランキューのためのデータ構造は使わず、未来のタスク実行の
"タイムライン"を構築するため時間で順序づけられた赤黒木を使うので、(以前のバニラカーネルの
スケジューラとRSDL/SDの両方が影響を受けた)"配列切り替え"という遺産は持っていません。

CFS also maintains the rq->cfs.min_vruntime value, which is a monotonic
increasing value tracking the smallest vruntime among all tasks in the
runqueue.  The total amount of work done by the system is tracked using
min_vruntime; that value is used to place newly activated entities on the left
side of the tree as much as possible.
CFSはrq->cfs.min_vruntimeという値も管理しますが、これはランキュー内の全タスク中の最小の
vruntimeを表す値であり、単調増加します。システムによって過去に行われたタスク実行時間の合計は
min_vruntimeを用いて追跡されます; そしてその値は新しく活動を開始したエンティティ(訳注: 何の
ことか分からない場合は「タスク」と読み替えてください)をできるだけ赤黒木の左側に置くのに
使われます(訳注: 左側から優先的に選択、実行される)。

The total number of running tasks in the runqueue is accounted through the
rq->cfs.load value, which is the sum of the weights of the tasks queued on the
runqueue.
ランキュー内の実行可能タスクの総数はrq->cfs.loadという値によって管理されますが、これは
ランキューに入れられたタスクの重みの合計です。

CFS maintains a time-ordered rbtree, where all runnable tasks are sorted by the
p->se.vruntime key. CFS picks the "leftmost" task from this tree and sticks to it.
As the system progresses forwards, the executed tasks are put into the tree
more and more to the right --- slowly but surely giving a chance for every task
to become the "leftmost task" and thus get on the CPU within a deterministic
amount of time.
CFSは時間順の赤黒木を管理しますが、そこでは全ての実行可能タスクが
p->se.vruntimeをキーとして整列されています。CFSはこの木から"左端"のタスクを選択し続けます。
システムが前に進むにつれて、実行が終わったタスクはどんどん木の右側へ置かれるようになります--- 
ゆっくりと、しかし確実に、全てのタスクへ"左端のタスク"になる機会を与えるので、実行が終わった
タスクは一定時間以内にCPUへ乗る(訳注: スケジューリングされる)ことになります。

Summing up, CFS works like this: it runs a task a bit, and when the task
schedules (or a scheduler tick happens) the task's CPU usage is "accounted
for": the (small) time it just spent using the physical CPU is added to
p->se.vruntime.  Once p->se.vruntime gets high enough so that another task
becomes the "leftmost task" of the time-ordered rbtree it maintains (plus a
small amount of "granularity" distance relative to the leftmost task so that we
do not over-schedule tasks and trash the cache), then the new leftmost task is
picked and the current task is preempted.
要約すると、CFSは次のように動作します: タスクをちょっとだけ実行し、そしてタスクがスケジュール
される(もしくはスケジューラティックが起こった)時、そのタスクのCPU使用率を"課金"します:
今さっき物理CPUを使うのに費やした(少しの)時間がp->se.vruntimeへ加算されるのです。別の
タスクがCFSの管理する時間順の赤黒木の"左端のタスク"になるぐらい十分にp->se.vruntimeが大きく
なると(実際にはタスクを過剰に実行したりキャッシュを捨てたりしないように左端のタスクへの
相対的な少量の"granularity"距離より大きくなった場合ですが)、新しい左端のタスクが選択されて
現在のタスクはプリエンプトされます。



4.  SOME FEATURES OF CFS
4.  CFSのいくつかの機能

CFS uses nanosecond granularity accounting and does not rely on any jiffies or
other HZ detail.  Thus the CFS scheduler has no notion of "timeslices" in the
way the previous scheduler had, and has no heuristics whatsoever.  There is
only one central tunable (you have to switch on CONFIG_SCHED_DEBUG):
CFSナノ秒粒度の課金を行い、jiffiesやその他のHZ関連のものには依存していません。なので
CFSには以前のスケジューラが持っていた"タイムスライス"という概念はありません。次に示す
たった一つのチューニング可能なパラメータがあるだけです(CONFIG_SCHED_DEBUGを有効
にする必要はありますが)。

   /proc/sys/kernel/sched_min_granularity_ns

which can be used to tune the scheduler from "desktop" (i.e., low latencies) to
"server" (i.e., good batching) workloads.  It defaults to a setting suitable
for desktop workloads.  SCHED_BATCH is handled by the CFS scheduler module too.
これは"デスクトップ"(すなわち低レイテンシ向け)から"サーバ"(すなわりバッチ処理向け)
までワークロードに応じてスケジューラをチューニングするために使われます。SCHED_BATCH
についてもCFSスケジューラモジュールによって処理されます。

Due to its design, the CFS scheduler is not prone to any of the "attacks" that
exist today against the heuristics of the stock scheduler: fiftyp.c, thud.c,
chew.c, ring-test.c, massive_intr.c all work fine and do not impact
interactivity and produce the expected behavior.
この設計のために、古くさいスケジューラのヒューリスティックに対して今日存在する"攻撃"の
影響をCFSスケジューラは受けにくくなっています:  fiftyp.c、thud.c、chew.c、ring-test.c、
massive_intr.cなどは全てきちんと動作しますし、対話的処理にも影響を与えず期待された挙動
を示します。

The CFS scheduler has a much stronger handling of nice levels and SCHED_BATCH
than the previous vanilla scheduler: both types of workloads are isolated much
more aggressively.
CFSスケジューラは以前のバニラカーネルのスケジューラより強力なniceレベルやSCHED_BATCHの
ハンドリングを行います: 両方のワークロードはより強く分離されます。

SMP load-balancing has been reworked/sanitized: the runqueue-walking
assumptions are gone from the load-balancing code now, and iterators of the
scheduling modules are used.  The balancing code got quite a bit simpler as a
result.
SMPロードバランシングは作り直しされてきれいにされています: runqueue-walking
の仮定(訳注: 何のことか不明...)は今やロードバランシングのコードからは無くなり、
スケジューリングモジュール(訳注: 後述)のイテレータが使われています。
結果としてバランシングのコードはかなりシンプルになりました。



5. Scheduling policies
5. スケジューリングポリシー

CFS implements three scheduling policies:
CFSは3つのスケジューリングポリシーを実装しています。

  - SCHED_NORMAL (traditionally called SCHED_OTHER): The scheduling
    policy that is used for regular tasks.
  - SCHED_NORMAL(伝統的にはSCHED_OTHERと呼ばれます): 通常のタスクに使われる
    スケジューリングポリシーです。

  - SCHED_BATCH: Does not preempt nearly as often as regular tasks
    would, thereby allowing tasks to run longer and make better use of
    caches but at the cost of interactivity. This is well suited for
    batch jobs.
  - SCHED_BATCH: 通常のタスクのように頻繁にはプリエンプトしないので、対話性を犠牲に
    にはしますがタスクをより長く実行したりキャッシュの利用効率を良くします。これはバッチ
    ジョブに向いています。

  - SCHED_IDLE: This is even weaker than nice 19, but its not a true
    idle timer scheduler in order to avoid to get into priority
    inversion problems which would deadlock the machine.
  - SCHED_IDLE: これはnice値19よりもさらに弱いのですが、マシンをデッドロック
    させる優先度逆転問題へと陥らせるのを避けるため、idleタイマースケジューラには
    なっていません。()

SCHED_FIFO/_RR are implemented in sched/rt.c and are as specified by
POSIX.
SCHED_FIFO/_RRは sched/rt.cで実装されており、POSIXで規定されている通りです。

The command chrt from util-linux-ng 2.13.1.1 can set all of these except
SCHED_IDLE.
util-linux-ng 2.13.1.1におけるchrtコマンドによってSCHED_IDLEを除く全ポリシーを設定
できます。(訳注: 最近のchrtではSCHED_IDLEにも対応しているようですが)



6.  SCHEDULING CLASSES
6.  スケジューリングクラス

The new CFS scheduler has been designed in such a way to introduce "Scheduling
Classes," an extensible hierarchy of scheduler modules.  These modules
encapsulate scheduling policy details and are handled by the scheduler core
without the core code assuming too much about them.
この新しいCFSスケジューラは"スケジューリングクラス"という拡張可能なスケジューリング
モジュール階層を導入するという方法で設計されています。これらのモジュールは
スケジューリングポリシーの詳細をカプセル化し、また、スケジューラのコアコードはこれらの
ポリシーを意識しすぎることなくこれらのモジュールを統御します。

sched/fair.c implements the CFS scheduler described above.
sched/fair.cはCFSスケジューラを先述したように実装しています。

sched/rt.c implements SCHED_FIFO and SCHED_RR semantics, in a simpler way than
the previous vanilla scheduler did.  It uses 100 runqueues (for all 100 RT
priority levels, instead of 140 in the previous scheduler) and it needs no
expired array.
sched/rt.cはSCHED_FIFOとSCHED_RRのセマンティクスを、以前のバニラカーネルの
スケジューラよりもシンプルな方法で実装します。100個のランキュー(全部で100個ある
RT優先度レベルのためです。以前のスケジューラでは140個の優先度レベルがありました)を
使用し、(訳注: 以前のように)時間切れ配列は必要としません。

Scheduling classes are implemented through the sched_class structure, which
contains hooks to functions that must be called whenever an interesting event
occurs.
スケジューリングクラスはsched_class構造体によって実装され、興味深いイベントが起こる
度に呼び出されないといけない関数へのフックを含んでいます。

This is the (partial) list of the hooks:
以下がそのフックの(部分的な)リストです:

 - enqueue_task(...)

   Called when a task enters a runnable state.
   It puts the scheduling entity (task) into the red-black tree and
   increments the nr_running variable.
   タスクが実行可能状態になった時に呼び出されます。
   これはスケジューリングエンティティ(タスク)を赤黒木へ入れ、nr_runningの値を
   インクリメントします。

 - dequeue_task(...)

   When a task is no longer runnable, this function is called to keep the
   corresponding scheduling entity out of the red-black tree.  It decrements
   the nr_running variable.
   タスクがもはや実行可能でなくなった時、対応するスケジューリングエンティティを
   赤黒木から追い出すためにこの関数が呼び出されます。これはnr_runningの値を
   デクリメントします。

 - yield_task(...)

   This function is basically just a dequeue followed by an enqueue, unless the
   compat_yield sysctl is turned on; in that case, it places the scheduling
   entity at the right-most end of the red-black tree.
   この関数は基本的にはデキューした後にエンキューするだけです。compat_yield sysctl
   が有効になっている場合は、スケジューリングエンティティを赤黒木の右端に置きます。

 - check_preempt_curr(...)

   This function checks if a task that entered the runnable state should
   preempt the currently running task.
   この関数は実行可能状態になったタスクが現在実行中のタスクをプリエンプトすべきか
   確認します。

 - pick_next_task(...)

   This function chooses the most appropriate task eligible to run next.
   この関数は次に実行するのにふさわしい最も適切なタスクを選択します。

 - set_curr_task(...)

   This function is called when a task changes its scheduling class or changes
   its task group.
   この関数はタスクがスケジューリングクラスやタスクグループを変更した時に呼び出され
   ます。

 - task_tick(...)

   This function is mostly called from time tick functions; it might lead to
   process switch.  This drives the running preemption.
   この関数は主にティック関数から呼び出されます; この呼び出しによってプロセス切り替え
   が起こるかもしれません。これはタスク実行中のプリエンプションを駆動させます。



7.  GROUP SCHEDULER EXTENSIONS TO CFS
7.  CFSへのグループスケジューラ拡張

Normally, the scheduler operates on individual tasks and strives to provide
fair CPU time to each task.  Sometimes, it may be desirable to group tasks and
provide fair CPU time to each such task group.  For example, it may be
desirable to first provide fair CPU time to each user on the system and then to
each task belonging to a user.
通常、スケジューラは個々のタスクを操作しCPU時間を公平に割り当てようとします。時折、
グループ化されたタスク群にとってはCPU時間をそれぞれのタスクグループへと公平に割り
当てることが望ましいかもしれません。例えば、システム上のユーザごとに、それらユーザに
所属する個々のタスクに対してCPU時間を公平に割り当てることが望ましいかもしれない
ということです。

CONFIG_CGROUP_SCHED strives to achieve exactly that.  It lets tasks to be
grouped and divides CPU time fairly among such groups.
CONFIG_CGROUP_SCHEDは正確にそれを達成しようとします。これはタスクをグループ化
し、CPU時間を公平にそれらのグループへ配分します。

CONFIG_RT_GROUP_SCHED permits to group real-time (i.e., SCHED_FIFO and
SCHED_RR) tasks.
CONFIG_RT_GROUP_SCHEDはリアルタイム(つまりSCHED_FIFOとSCHED_RRの)
タスクをグループ化することを許可します。

CONFIG_FAIR_GROUP_SCHED permits to group CFS (i.e., SCHED_NORMAL and
SCHED_BATCH) tasks.
CONFIG_FAIR_GROUP_SCHEDはCFS(つまりSCHED_NORMALとSCHED_BATCHの)
タスクをグループ化することを許可します。

   These options need CONFIG_CGROUPS to be defined, and let the administrator
   create arbitrary groups of tasks, using the "cgroup" pseudo filesystem.  See
   Documentation/cgroups/cgroups.txt for more information about this filesystem.
   これらのオプションはCONFIG_CGROUPSが定義されていることを必要とします。この
   オプションはシステム管理者に"cgroup"擬似ファイルシステムを使って任意のタスク
   グループを作成させることを可能にします。このファイルシステムについてのさらなる情報
   はDocumentation/cgroups/cgroups.txtを見てください。

When CONFIG_FAIR_GROUP_SCHED is defined, a "cpu.shares" file is created for each
group created using the pseudo filesystem.  See example steps below to create
task groups and modify their CPU share using the "cgroups" pseudo filesystem.
CONFIG_FAIR_GROUP_SCHEDが定義されている時は、擬似ファイルシステムを使って作られた
グループごとに"cpu.shares"というファイルが作られています。それでは、"cgroups"擬似ファイル
システムを使ってタスクグループを作ったりそれらのCPU時間の分け前を変えたりするステップの
例を見てみましょう

	# mount -t tmpfs cgroup_root /sys/fs/cgroup
	# mkdir /sys/fs/cgroup/cpu
	# mount -t cgroup -ocpu none /sys/fs/cgroup/cpu
	# cd /sys/fs/cgroup/cpu

	# mkdir multimedia	# create "multimedia" group of tasks
                                        # "multimedia"タスクグループを作成
	# mkdir browser		# create "browser" group of tasks
                                                # "browser"タスクグループを作成

	# #Configure the multimedia group to receive twice the CPU bandwidth
	# #that of browser group
        # #multimediaグループがbrowserグループの2倍のCPU帯域を受け取る
        # #ように設定

	# echo 2048 > multimedia/cpu.shares
	# echo 1024 > browser/cpu.shares

	# firefox &	# Launch firefox and move it to "browser" group
                                # firefoxを起動し"browser"グループへと移動
	# echo  > browser/tasks

	# #Launch gmplayer (or your favourite movie player)
        # #gmplayer(もしくはあなたの好きな動画プレイヤー)を起動
	# echo  > multimedia/tasks