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

カーネル/VM Advent Calendar 2013 23日目: Linuxのseqlockに新しいreader typeが追加された話

カーネル/VM Advent Calendar 2013

こんにちは、hiraku_wfsです。
今年はちょっと大きなネタを構想していたのですが、ここ最近体調が芳しくなかったので小ネタになります。

seqlockとは

シーケンスロック(seqlock)というのは、読み書きロック(rwlock: reader同士はブロックせずに並列実行可能、writer実行中はそれ以外はブロックされる)に似ているのですが、読み書きロックと異なる点として、reader側ではロックを取らないためwriterをブロックしないという利点があります。
当然reader実行中にwriterが走ったらロック対象の値が変化するわけですが、これに対してはreader側の処理開始〜終了の区間にwriterが走ったかどうか確認し、走っていた場合はreader側でretryをかけます。

使い方としては下のような感じ。

writer側。

write_seqlock(&slock)
/* ここでロック対象の値を更新する */
write_sequnlock(&slock)

reader側。

do {
        seq = read_seqbegin(&slock);
        /* ここでロック対象の値を読み込む */
} while (read_seqretry(&slock, seq)); /* writerが走ってたらretry */

新しいreader type

Linux 3.12で次のパッチがmergeされました。

seqlock: Add a new locking reader type (by Waiman Long)

趣旨としては、データの更新を行わなくても他のwriterからの変更が許容できないような区間ではread_seqbegin()ではなくwrite_seqlock()を使わなければいけなかったけれど、それは非効率なので既存のreaderはブロックせず(retryさせず)writerのみをブロックするread_seqlock_excl()を追加したよ、という話です。

それぞれが同時に動作した場合に何が起こるかを表にしてみました。

read_seqbegin read_seqlock_excl write_seqlock
read_seqbegin 並行動作可能 並行動作可能 順番に関わらずreaderがretry
read_seqlock_excl - 後に入ってきた方がブロック 後に入ってきた方がブロック
write_seqlock - - 後に入ってきた方がブロック

今のところ、VFSのパス名探索まわりで使われてるみたいです。
(余談ですが、ちらっと見た感じVFSのコードも2.6の頃と結構変わってますねー。スケーラビリティ向上のためか、複雑になっているみたい。)

おわりに

かなりてきとーな説明になってしまったので辻斬りに遭いそうですが、来年もよろしくお願いいたします。
それでは、良いお年を。

Kernel/VM Advent Calendar 33日目: VirtualBoxでホストOSからゲストOSのコマンドを実行する

VBoxManage guestcontrol exec

VMwareのvmrunやUser Mode Linuxのumlrunを使うとホストからゲストのコマンドを叩けるのですが、VirtualBoxにも同じような仕組みが無いかなーと思ったら、ありました。

Chapter 8. VBoxManage


execute, which allows for executing a program/script (process) which is already installed and runnable on the guest. This command only works while a VM is up and running and has the following syntax:


VBoxManage guestcontrol | exec[ute]
--image
--username --password
[--dos2unix]
[--environment "= [=]"]
[--timeout ] [--unix2dos] [--verbose]
[--wait-exit] [--wait-stdout] [--wait-stderr]
-- [[] ... []]

「--image」の後にコマンド名を入れて、あとはゲストOS上のユーザ名/パスワードを打ち込めば良さそうです。

というわけで、MacホストからLinuxゲストのコマンドを叩いてみたいと思います。

やってみた

実験環境はこんな感じです。

ハードウェア Mac mini, Intel Core 2 Duo(2.53GHz)
ホストOS Mac OS X 10.6
VMM VirtualBox 4.1.4
ゲストOS Linux 3.1.6 (x86_64) (Fedora16)

まずはゲストOSにGuest Additionsを入れる必要があります。
VMのメニューの「デバイス」->「Guest Additions のインストール」でインストール用の仮想デバイスをゲストOSに認識させた後、

GuestOS:# /media/VBOXADDITIONS_4.1.4_74291/VBoxLinuxAdditions.run

とやると、Guest Additionsがインストールされます。(カーネルモジュールのコンパイルも含まれるので事前にkernel-develやgcc等のパッケージを入れておきましょう)

準備はここまでで、早速ホストからゲストのコマンドを叩いてみましょう。

HostOS:$ VBoxManage guestcontrol fed16-64-vbox1 exec --image /bin/ls --username hoge --password hogehoge
HostOS:$

あれ。へんじがない、ただのしかばねの(ry
マニュアルをよく見ると、「--wait-stdout」を付けないと標準出力に出された結果を受け取れないようですね。

HostOS:$ VBoxManage guestcontrol fed16-64-vbox1 exec --image /bin/ls --username hoge --password hogehoge --wait-stdout
bin
boot
dev
etc
home
...
HostOS:$

今度はうまくいきました。

他には、引数を渡すための「--」くらいは覚えておくと良さそうですね。

誰がゲストのコマンドを実行してるの?

ちょっと気になったので調べてみました。

最近のLinuxにはftraceという便利なトレースツールが組み込まれています。今回はこれを使ってゲストのコマンドを実行しているプログラムを探してみましょう。

ftraceはdebugfsのインタフェースで操作します。debugfsがマウントされていない場合は、下のようにしてマウントしましょう。

GuestOS:# mount -t debugfs none /sys/kernel/debug
GuestOS:# cd /sys/kernel/debug/tracing/

ftraceには色んな機能があるのですが、今回はEvent Tracingというものを使います。これは、カーネル内に埋め込まれたトレースポイントの情報を取ってくる仕組みです。
イベントはたくさんあるのですが、今回はプロセスのコンテキストスイッチのイベント「sched_switch」とfork()のイベント「sched_process_fork」を採取しましょう。
とりあえずこの2つがあると、「sched_switch」イベントからは、ホストから実行されたコマンドのPIDが分かり、「sched_process_fork」イベントからは、そのコマンドのためのプロセスをforkした親プロセスが分かります。

イベントをONにするには、対応する疑似ファイルに1を書き込みます。デフォルトではこれでトレースが始まります。

GuestOS:# echo 1 > events/sched/sched_process_fork/enable
GuestOS:# echo 1 > events/sched/sched_switch/enable

ここでホストOSからコマンドを実行してみましょう。

HostOS:$ VBoxManage guestcontrol fed16-64-vbox1 exec --image /home/hoge/my_command --username hoge --password hogehoge

実行したら、ゲストのトレースをいったん止めます。

GuestOS:# echo 0 > tracing_on

トレースの結果はtraceファイルに入っているので、grepしてみましょう。

GuestOS:# grep my_command trace
      my_command-1850  [000]  3146.618841: sched_switch: prev_comm=VBoxService prev_pid=1850 prev_prio=120 prev_state=R ==> next_comm=VBoxService next_pid=1849 next_prio=120
...

my_commandはPID 1850で実行されているようです。これをfork()したのは誰かというと、、、

GuestOS:# grep sched_process_fork trace
...
     VBoxService-1849  [000]  3146.615976: sched_process_fork: comm=VBoxService pid=1849 child_comm=VBoxService child_pid=1850
...

どうやら、VBoxService(PID 1849)のようです。

おわりに

というわけで、VirtualBoxでホストからゲストのコマンドを実行するguestcontrol execを簡単に使ってみました。
ゲスト側で実際にコマンドを実行しているVBoxServiceを辿っていけば、ゲスト-ホスト間の通信路がどうなっているのか等、さらに詳しいことも分かりそうですね。

それではカーネル/VMな皆様、今年もよろしくお願いいたします。

Kernel/VM Advent Calendar 9日目: VirtualBoxによるLinuxへのCPU hotplug

もう、だいぶ前からですが、VirtualBoxはCPU hotplugをサポートしています。
virtualization.info | リリース:Oracle VM VirtualBox 3.2(20100519-2)

マニュアルもあります。
Chapter 9. Advanced topics

というわけで、手元のMac OS XVirtualBoxでも実際できるのか、確かめてみました。

やってみた

実験環境はこんな感じです。

ハードウェア Mac mini, Intel Core 2 Duo(2.53GHz)
ホストOS Mac OS X 10.6.4
VMM VirtualBox 3.2.12
ゲストOS Linux 2.6.33 (x86_64) (Fedora13)

ゲストLinuxは64bit版じゃないとダメだそうです。8CPUとあるのは、たぶん、ゲストに割り当てる仮想CPUのことだと思われ。
おそらく上は誤訳で、仮想CPUが8個より多い場合でやる時は64bit版ゲストLinuxが必要だよ、ということだと思います。
なので32bit版Linuxでも出来るんじゃないかと(試してませんが)。

http://www.virtualbox.org/manual/ch09.html#cpuhotplug

Windows supports only hot-add while Linux supports hot-add and hot-remove but to use this feature with more than 8 CPUs a 64bit Linux guest is required.

まずは、VMの起動前にやること。

ホストOSから、VMのCPU hotplug機能をONにして、最大CPU数を8に設定してみます
GUIからは設定できないので、コマンドライン(ターミナル.appとか)から。

HostOS:$ VBoxManage modifyvm  --cpuhotplug on
HostOS:$ VBoxManage modifyvm  --cpus 8

には、自分で設定したVMの名前を指定しましょう。

次にVMを起動します。これはGUIからでOK。コマンドラインからやりたければ、次のような感じ(たぶん)。

HostOS:$ VBoxManage startvm 

ゲストOSが起動したら、ゲストから見えるCPU数を見てみましょう。

GuestOS:$ grep processor /proc/cpuinfo
processor	: 0

現在のところ、1個(CPU0のみ)です。

では、CPUを1個追加(hot-add)してみましょう。

HostOS:$ VBoxManage controlvm  plugcpu 

具体的には、CPU3を追加したいなら、次のような感じ。

HostOS:$ VBoxManage controlvm "fed13-64-vbox1" plugcpu 3

増えたかどうか、ゲストで確認しましょう。

GuestOS:$ grep processor /proc/cpuinfo
processor	: 0
processor	: 1

ゲストにはCPU1として認識されるようです。
hot-add成功ですね!
さらにもう1個追加しましょう。

HostOS:$ VBoxManage controlvm "fed13-64-vbox1" plugcpu 1
GuestOS:$ grep processor /proc/cpuinfo
processor	: 0
processor	: 1
processor	: 2

今の状態は、こんな感じでしょうか。

仮想CPU ゲストから見えるCPU
CPU 0 CPU 0
CPU 3 CPU 1
CPU 1 CPU 2

さて、次に削除(hot-remove)を試してみましょう。今度はunplugcpuです。

HostOS:$ VBoxManage controlvm "fed13-64-vbox1" unplugcpu 3
GuestOS:$ grep processor /proc/cpuinfo
processor	: 0
processor	: 2

ゲストからはCPU1がなくなったように見えます。

仮想CPU ゲストから見えるCPU
CPU 0 CPU 0
CPU 1 CPU 2

CPU online/offlineコード

それでは、CPU hotplugを行った時にLinuxの中でどのようなコードが実行されているのか、追いかけてみましょう。

と思ったのですが、時間的に無理でした。。。><
という訳で、この話は後日書きたいと思います。