2020/05/26(火)openWRTでカーネルにパッチを当てたい

公式手順に沿って試してみる

Adding or editing kernel patches

make target/linux/clean V=s QUILT=1
make target/linux/prepare V=s QUILT=1
cd build_dir/target-aarch64_generic_glibc/linux-*/linux-4.14.108
quilt new platform/100-my-kernel-patch.patch
Makefileによって 以下にファイルが生成される様子.. (findで見つけた)
FILE: build_dir/target-aarch64_generic_glibc/linux-*/linux-4.14.108/patches/platform/100-my-kernel-patch.patch

いろいろとコードを編集する.
編集・作成する前に quilt add filename してから作業すること(後述。quiltの使い方)
make target/linux/update V=s
make target/linux/update package/index V=s

quiltコマンドの使い方

これはシェルスクリプトで書かれたツールです.

ディレクトリを遡って、ワークディレクトリを探してくれます.
.pc/ patches があると、そこを WORKING TREE先頭とみなすようです(要確認)

ファイルの新規作成は、存在しないファイル名を追加してから 編集をかけます.
quilt add path/to/new-file.c
編集事態は quilt edit path/to/new-file.c としなくてもよいみたいですね.
どこかにファイルを置いて以下を実行すると一括登録できます.
for f in $(ls -1 /new/files/); do
  quilt add $f
  cp -af /new/filew/$f ./
done
symbolic linkの追加は現状できていません.
quilt add の処理で test -L $fname を見て、シンボリックリンクならエラーを出してくれます..

■kernel

make target/linux/clean
make target/linux/prepare V=s QUILT=1
cd build_dir/target-*/linux-*/linux-4.14*

TO=$PWD
FROM=/path/to/patched-files/linux-4.14.108

# pathは seriesに合わせて付与した
quilt new platform/920-add_dts.patch

for f in $(cat /tmp/hogehoge)
do
  quilt add $f
  cp -avf $FROM/$f ./$f
done

quilt refresh
cp -avf patches/platform/920-add_dts.patch  openwrt/target/linux/*/patches-4.14/
予め対象のファイル名は用意しておく..
$ git diff --name-only <変更前のID> -- linux-4.14.108 | sed -e 's,^linux-4.14.108/,,' > /tmp/hogehoge

quiltコマンド覚え書き(man page見た方が詳しい)

# 次のパッチを見る
quilt next

# 全てのパッチを参照する
$ quilt serires
....

# 順番にパッチを適用する
quilt push

# パッチを一つ戻す
quilt pop

参照先

公式のパッチの作り方

ハマったヒト

ひたすらぐぐったけど symblic linkに言及したものが少ない.
OpenWRTのもの
実例が甘い気がする...更新止まっているかもしれん.

debian勉強会@東京の資料 が 良さそう.
debian wikiにもあるけれど ん-..


同じく困っているヒト

DeviceTreeの基礎

2019/03/23import

device.tree.org

devicetreeの実装サイドからの仕様を公開していると思われます。

そもそもdevicetreeとはコンピュータシステムの構成要素を記述するために用いられています。

冒頭で 関連している仕様として、以下が挙げられています:

  • IEEE 1275 Open Firmware standard―IEEE Standard for Boot (Initialization Configuration) Firmware: Core Requirements and Practices [IEEE1275].
  • EPAPR

この仕様書は、2016年からlinaro社, ARM社によって生成されている模様です。

コンピュータシステムの初期化を行う際に、OS起動前に初期化処理の必要なハードウェア類があります。ブートローダ、ハイパーバイザ等が初期化等を行って、最終的にOSへと処理を移します。このプログラム間で情報のやりとりを行うための規定にも使えるもの、とあります。

仕様の詳細は、Devicetree Specificationを参照しましょう。


なぜ必要か

PCでは ACPIがハードウェア情報を提供してくれるため、必要な設定・ドライバのロードが可能でした。

そこで Open Firmwareの頃から powerpcアーキテクチャで devicetreeの利用が始まっていました。その後 Linux kernelソースコードの汚い肥大化をLinusに指摘されたことにより、ARMアーキテクチャにも適用することとなったものです。したがって、poewrpcやARMアーキテクチャのカーネルドライバ・u-bootに関わる方には必須の事項となります。

ブートプログラムがシステム内のハードウェアの初期化処理を行うために必要な情報を得るために必要です。これがなければ、ブートプログラムはシステム内のハードウェア構成にあわせて個々に用意する必要があります。これではブートプログラムの実装効率も悪く、同じようなコードが散乱することになりかねません。そこで、ドライバソフトウェアを個々のハードウェアに対応したものとし、そのリソースを含めて定義できるようにすることでソフトウェアを共通化することができます。

その昔、PC/AT互換機が出てから `Plug and Play` が登場するまでは、ボードのリソース設定等をディップスイッチで行って、インストール作業者がリソース競合を回避するといった作業を行っていました。

PCIデバイスでは、ターゲット側がconfiguration spaceを用意することで、デバイスの素性や要求リソースを検出する仕組みが用意されています。したがって、Devitetreeはこれらのターゲットデバイスの定義を含めないこととしています(例外として、ソフト的にproveできないPCI host bridge deviceを挙げています)。


Devicetree format(概要編)

Devicetree Specificationに詳細な記述仕様があります。ざっと要点を抜粋していきます。

tree状に定義する様式となっており、'/'をルートノードとして、ファイルシステムのディレクトリ階層のように記述していきます。簡単な記述例を以下に示します。実用的な記述ではありませんが、コンパイルは通ります。

/dts-v1/;
/ {
        #address-cells = <1>;
        #size-cells = <1>;

        soc {
                compatible = "simple-bus";
                #address-cells = <1>;
                #size-cells = <1>;
                intc: intc@100 {
                        reg = <1000 100>;
                };
                spi: spi@0 {
                        reg = <0 0>;
                        interrupts = <&intc 1>;
                };
    };
};

ここで socintc@100 はノードといいます。中括弧で括った要素(プロパティ)をまとめる器です。これはバスを表現したり、特定の機能をもつIPコアを表現したり、Flash memoryやセンサICを表現したりします。

また、ノードは何段でも階層化した記述ができ、CPUから見えるシステムバスの多段表現や、その先にあるIPコアのレジスタインタフェースを表現することができます。SoC内部に限らず、SPI・I2C・非同期バスなどを介して接続するデバイスを表現します。

それぞれのノードに、プロパティを定義します。プロパティは 項目名と値とからなる組み合わせで、値がないものも存在します。値はDTspecで規定されているものなら自由に設定できますが、それを参照するのは対応するドライバです。ドライバが判るように設定してあげる必要があります。

kernel versionが新しくなるにつれ、ドキュメントも整備されていきました。kernel/Documentation/devicetree/bindings/ 配下に、ある程度まとめられています。善意の協力のもとで作られていますので、必ずしも欲しい情報が存在する/正しいとは限りません。

自分が商用向けで触ったりする場合には 可能な限りソースコードも参照することをおすすめします。

linux systemにおけるinitの最期

2018/12/18import
Linux Advent Calender 2018の18日目です。

元々の予定はボツになった!?ので ちょっと古い話になります。

7日目のsystemd理解のヒント - systemdの概念と歴史と相反するような記事です。
古い情報も必要としている組込もんもいるので、その助けとなりましたら幸いです。

initとは

PID=1として、カーネルの初期化が終わって初めて生成されるプロセスです。
ユーザランドで必要なファイルシステムのマウント・システム設定・サービス(デーモン)やプロセス起動を行います。

kernel parameterに init=でinitコマンドを指定することができます。省略すると /sbin/initなどが参照されます。
init=/etc/preinit
ここでは 組込装置を前提として、busyboxのinitを想定します

設定ファイル

initが起動すると、以下のファイルを参照します。run levelに応じた処理を記述するようになっています。
シリアルコンソールの設定なども、ここに記述することができます。
/etc/inittab
■/etc/inittab
FILE: 06.build/patches/rootfs/etc/inittab
# /etc/inittab
#
# Copyright (C) 2001 Erik Andersen <andersen@codepoet.org>
#
# Note: BusyBox init doesn't support runlevels.  The runlevels field is
# completely ignored by BusyBox init. If you want runlevels, use
# sysvinit.
#
# Format for each entry: <id>:<runlevels>:<action>:<process>
#
# id        == tty to run on, or empty for /dev/console
# runlevels == ignored
# action    == one of sysinit, respawn, askfirst, wait, and once
# process   == program to run

# Startup the system
::sysinit:/bin/mount -t proc proc /proc
::sysinit:/bin/mount -o remount,rw /
::sysinit:/bin/mkdir -p /dev/pts
::sysinit:/bin/mkdir -p /dev/shm
::sysinit:/bin/mount -a
::sysinit:/bin/hostname -F /etc/hostname
# now run any rc scripts
::sysinit:/etc/init.d/rcS

# Put a getty on the serial port
#ttyS0::respawn:/sbin/getty -L ttyS0 115200 vt100 # GENERIC_SERIAL

# Stuff to do for the 3-finger salute
#::ctrlaltdel:/sbin/reboot

# Stuff to do before rebooting
::shutdown:/etc/init.d/rcK
::shutdown:/sbin/swapoff -a
::shutdown:/bin/umount -a -r

システムの終了

reboot、halt、shutdownといったコマンドを実行すれば、システムを再起動・停止・終了することができますね。
このコマンドを実行したとき、何が行われているのでしょうか。

rebootに対象を絞って、かつ、busybox版で確認していきましょう。

v1.19.4
FILE: init/halt.c
//applet:IF_HALT(APPLET(halt, BB_DIR_SBIN, BB_SUID_DROP))
//applet:IF_HALT(APPLET_ODDNAME(poweroff, halt, BB_DIR_SBIN, BB_SUID_DROP, poweroff))
//applet:IF_HALT(APPLET_ODDNAME(reboot, halt, BB_DIR_SBIN, BB_SUID_DROP, reboot))
rebootは haltのaliasになるようですね。
int halt_main(int argc UNUSED_PARAM, char **argv)
|
...
	sleep(0);
	write_wtmp();  // last.logを記録する
	sync();        // デフォルトはsync(2)を実行する.

	kill(1,SIGTERM)	// initに signalを飛ばす. -f付きなら reboot(2)で 0x01234567 を渡す..
コメントに書いたようにsignalを飛ばすだけでした。
initに処理が移ります:

FILE: init/init.c

FUNC: int init_main(int argc UNUSED_PARAM, char **argv)
		bb_signals(0
			+ (1 << SIGUSR1) /* halt */
			+ (1 << SIGTERM) /* reboot */
			+ (1 << SIGUSR2) /* poweroff */
			, halt_reboot_pwoff);
signal handlerを登録します。bb_*は、Busyboxのライブラリ関数です。
第一引数で指定されたsignalを許可し、第二引数の関数をハンドラとして登録します。

ハンドラを見ていきましょう:
static void halt_reboot_pwoff(int sig)
{
	const char *m;
	unsigned rb;

	/* We may call run() and it unmasks signals,
	 * including the one masked inside this signal handler.
	 * Testcase which would start multiple reboot scripts:
	 *  while true; do reboot; done
	 * Preventing it:
	 */
	reset_sighandlers_and_unblock_sigs();
		// ハンドラをデフォルトに戻して, 有効化

	run_shutdown_and_kill_processes();
		// 後述. run_actrions(),全プロセスにSIGTERM, sync(2),sleep(1sec),SIGKILL,sync(2)

	m = "halt";
	rb = RB_HALT_SYSTEM;
	if (sig == SIGTERM) {
		m = "reboot";
		rb = RB_AUTOBOOT;
	} else if (sig == SIGUSR2) {
		m = "poweroff";
		rb = RB_POWER_OFF;
	}
	message(L_CONSOLE, "Requesting system %s", m);
	pause_and_low_level_reboot(rb);
		// 後述. sleep(1sec), vfork(2)した子で reboot(magic:0x1234567), 親(pid=1)はsleep forever.
	/* not reached */
}
いくつか関数を読んでいるので、引用します。コメントに書いたような処理を行っています。
static void run_shutdown_and_kill_processes(void)
{
	/* Run everything to be run at "shutdown".  This is done _prior_
	 * to killing everything, in case people wish to use scripts to
	 * shut things down gracefully... */
	run_actions(SHUTDOWN);

	message(L_CONSOLE | L_LOG, "The system is going down NOW!");

	/* Send signals to every process _except_ pid 1 */
	kill(-1, SIGTERM);
	message(L_CONSOLE | L_LOG, "Sent SIG%s to all processes", "TERM");
	sync();
	sleep(1);

	kill(-1, SIGKILL);
	message(L_CONSOLE, "Sent SIG%s to all processes", "KILL");
	sync();
	/*sleep(1); - callers take care about making a pause */
}
run_actions(SHUTDOWN);では、 inittabで記述した "::shutdown:"のコマンドを実行していきます。
swapoff, unmount -a -rが特徴的ですね。とくに後者は ファイルシステムをアンマウントすることで、
終了処理中に書き込みを行わせないようにしています(アンマウントできないときは
read onlyでリマウントするオプションが設定されています)。
static void pause_and_low_level_reboot(unsigned magic)
{
	pid_t pid;

	/* Allow time for last message to reach serial console, etc */
	sleep(1);

	/* We have to fork here, since the kernel calls do_exit(EXIT_SUCCESS)
	 * in linux/kernel/sys.c, which can cause the machine to panic when
	 * the init process exits... */
	pid = vfork();
	if (pid == 0) { /* child */
		reboot(magic);
		_exit(EXIT_SUCCESS);
	}
	while (1)
		sleep(1);
}
reboot(2)を実行しているようなので、libcを見ていきましょう。

libc

reboot(2)は以下のようにシステムコールを実行するだけでした。
/* Call kernel with additional two arguments the syscall requires.  */
int
reboot (int howto)
{
  return INLINE_SYSCALL (reboot, 3, (int) 0xfee1dead, 672274793, howto);
}
magic1: 0xfee1dead
magic2: 0x28121969

マジックナンバーが入っているけれども、これはカーネルソースで定義されている値ですね。

FILE: include/linux/reboot.h
/*
 * Magic values required to use _reboot() system call.
 */

#define LINUX_REBOOT_MAGIC1     0xfee1dead
#define LINUX_REBOOT_MAGIC2     672274793
#define LINUX_REBOOT_MAGIC2A    85072278
#define LINUX_REBOOT_MAGIC2B    369367448
#define LINUX_REBOOT_MAGIC2C    537993216

/*
 * Commands accepted by the _reboot() system call.
 *
 * RESTART     Restart system using default command and mode.
 * HALT        Stop OS and give system control to ROM monitor, if any.
 * CAD_ON      Ctrl-Alt-Del sequence causes RESTART command.
 * CAD_OFF     Ctrl-Alt-Del sequence sends SIGINT to init task.
 * POWER_OFF   Stop OS and remove all power from system, if possible.
 * RESTART2    Restart system using given command string.
 * SW_SUSPEND  Suspend system using software suspend if compiled in.
 * KEXEC       Restart system using a previously loaded Linux kernel
 */

#define LINUX_REBOOT_CMD_RESTART        0x01234567
#define LINUX_REBOOT_CMD_HALT           0xCDEF0123
#define LINUX_REBOOT_CMD_CAD_ON         0x89ABCDEF
#define LINUX_REBOOT_CMD_CAD_OFF        0x00000000
#define LINUX_REBOOT_CMD_POWER_OFF      0x4321FEDC
#define LINUX_REBOOT_CMD_RESTART2       0xA1B2C3D4
#define LINUX_REBOOT_CMD_SW_SUSPEND     0xD000FCE2
#define LINUX_REBOOT_CMD_KEXEC          0x45584543


kernel実装

(v4.4.120を参照しています)
システムコールから呼ばれる関数は以下ですね:

FILE: kernel/reboot.c
/*
 * Reboot system call: for obvious reasons only root may call it,
 * and even root needs to set up some magic numbers in the registers
 * so that some mistake won't make this reboot the whole machine.
 * You can also set the meaning of the ctrl-alt-del-key here.
 *
 * reboot doesn't sync: do that yourself before calling this.
 */
SYSCALL_DEFINE4(reboot, int, magic1, int, magic2, unsigned int, cmd,
		void __user *, arg)
	mutex_lock(&reboot_mutex);
	switch (cmd) {
	case LINUX_REBOOT_CMD_RESTART:
		kernel_restart(NULL);
		break;
..
	mutex_unlock(&reboot_mutex);
	return ret;
}
/**
 *	kernel_restart - reboot the system
 *	@cmd: pointer to buffer containing command to execute for restart
 *		or %NULL
 *
 *	Shutdown everything and perform a clean reboot.
 *	This is not safe to call in interrupt context.
 */
void kernel_restart(char *cmd)
{
	kernel_restart_prepare(cmd);
	migrate_to_reboot_cpu();
	syscore_shutdown();		// syscore_ops_listを走査する
	if (!cmd)
		printk(KERN_EMERG "Restarting system.\n");
	else
		printk(KERN_EMERG "Restarting system with command '%s'.\n", cmd);
	kmsg_dump(KMSG_DUMP_RESTART);
	machine_restart(cmd);
}
EXPORT_SYMBOL_GPL(kernel_restart);
void kernel_restart_prepare(char *cmd)
{
	blocking_notifier_call_chain(&reboot_notifier_list, SYS_RESTART, cmd);
	system_state = SYSTEM_RESTART;
	usermodehelper_disable();		// timeout: 5sec
	device_shutdown();		// timeoutなし, devices_kset->list を走査する.
}
device_shutdown()と syscore_shutdown()の詳細は追い切れていませんが、
登録されているコールバック関数を呼び出して後処理をしているようです。
loadable moduleは removeされるような挙動を見かけたので、ここで解放されていると思われます(要確認)。

アーキテクチャ依存部: machine_restart()

armの場合は以下のとおり。
さらにプラットフォーム依存・ボード依存部で定義された関数呼び出しへと続きます。

FILE: arch/arm/kernel/reboot.c
void machine_restart(char *cmd)
{
	local_irq_disable();
	smp_send_stop();

	if (arm_pm_restart)
		arm_pm_restart(reboot_mode, cmd);
	else
		do_kernel_restart(cmd);

	/* Give a grace period for failure to restart of 1s */
	mdelay(1000);

	/* Whoops - the platform was unable to reboot. Tell the user! */
	printk("Reboot failed -- System halted\n");
	local_irq_disable();
	while (1);
}
このあたりは使用されているターゲットのコードを追いかけましょう。



参考まで、arm64の場合は以下のとおり。firmwareがUEFI対応であれば、それを使うようです。
FILE: arm64/kernel/process.c
/*
 * Restart requires that the secondary CPUs stop performing any activity
 * while the primary CPU resets the system. Systems with multiple CPUs must
 * provide a HW restart implementation, to ensure that all CPUs reset at once.
 * This is required so that any code running after reset on the primary CPU
 * doesn't have to co-ordinate with other CPUs to ensure they aren't still
 * executing pre-reset code, and using RAM that the primary CPU's code wishes
 * to use. Implementing such co-ordination would be essentially impossible.
 */
void machine_restart(char *cmd)
{
	/* Disable interrupts first */
	local_irq_disable();
	smp_send_stop();

	/*
	 * UpdateCapsule() depends on the system being reset via
	 * ResetSystem().
	 */
	if (efi_enabled(EFI_RUNTIME_SERVICES))
		efi_reboot(reboot_mode, NULL);

	/* Now call the architecture specific reboot code. */
	if (arm_pm_restart)
		arm_pm_restart(reboot_mode, cmd);
	else
		do_kernel_restart(cmd);

	/*
	 * Whoops - the architecture was unable to reboot.
	 */
	printk("Reboot failed -- System halted\n");
	while (1);
}

FILE: kernel/reboot.c
/**
 *	do_kernel_restart - Execute kernel restart handler call chain
 *
 *	Calls functions registered with register_restart_handler.
 *
 *	Expected to be called from machine_restart as last step of the restart
 *	sequence.
 *
 *	Restarts the system immediately if a restart handler function has been
 *	registered. Otherwise does nothing.
 */
void do_kernel_restart(char *cmd)
{
	atomic_notifier_call_chain(&restart_handler_list, reboot_mode, cmd);
}

奥が深いですね...(ぇ

arm-inline-asm

本コンテンツは、以下のサイトの文章を翻訳したものです。
おおむねごっごる先生による自動翻訳ですが、自分が判るレベルに修正しています。たぶん。
少しでもアセンブラ、インラインアセンブラの記述、読解に役立てれば幸いです。
This contents is translated from following web page.
It is almost translated by translate.google.co.jp. But I modify them to understand for me, maybe.
I hope you reading and writing assembler code with ARM. Let's enjoy!
http://www.ethernut.de/en/documents/arm-inline-asm.html


About this document

The GNU C compiler for ARM RISC processors offers, to embed assembly language code into C programs.
This cool feature may be used for manually optimizing time critical parts of the software or to use specific processor instruction, which are not available in the C language.
ARM RISCプロセッサー用のGNU Cコンパイラは、Cプログラムにアセンブリ言語コードを埋め込むことを提供します。
このクールな機能は、手動でソフトウェアのタイムクリティカルな部分を最適化するか、
C言語では利用できない特定のプロセッサ命令を使用するために使用することができます。
It's assumed, that you are familiar with writing ARM assembler programs, because this is not an ARM assembler programming tutorial.
It's not a C language tutorial either.
この記事は、ARMアセンブラプログラミングのチュートリアルではありませんので、
それは、あなたが書き込みARMアセンブラプログラムに精通していることを仮定します。
この記事は、C言語のチュートリアルでもありません。
All samples had been tested with GCC version 4, but most of them should work with earlier versions too.
すべてのサンプルは、GCCバージョン4でテストされていますが、
それらのほとんどは、以前のバージョンでも動作するでしょう。

GCC asm statement

Let's start with a simple example.
The following statement may be included in your code like any other C statement.
シンプルな例から始めましょう。
以下の文は、ほかのC文のようにあなたのコードに含まれていてもよいでしょう。
/* NOP example */
asm("mov r0,r0");
It moves the contents of register r0 to register r0.
In other words, it doesn't do much more than nothing.
It is also known as a NOP (no operation) statement and is typically used for very short delays.
これは、レジスタr0の内容を、レジスタr0へ移します。
言い換えると、何もしません。NOP(no operation)文として知られており、普通はとても短い遅延のために使われます。
Stop! Before adding this example right away to your C code, keep on reading and learn, why this may not work as expected.
待ってください!
この例を正しいあなたのCコードに追加する前に、何故期待したとおりに機能しない場合があるのか、読み進めて学んでください。
With inline assembly you can use the same assembler instruction mnemonics as you'd use for writing pure ARM assembly code.
And you can write more than one assembler instruction in a single inline asm statement.
To make it more readable, you can put each instruction on a separate line.
あなたは純粋なARMアセンブリコードを書くために使用したいようインラインアセンブリを使用すると、
同じアセンブラ命令ニーモニックを使用することができます。
そして、あなたは、単一のインラインasm分に複数のアセンブラ命令を記述することができます。
それを読みやすくするには、別の行に各命令を置くことができます。
asm(
"mov     r0, r0\n\t"
"mov     r0, r0\n\t"
"mov     r0, r0\n\t"
"mov     r0, r0"
);
The special sequence of linefeed and tab characters will keep the assembler listing looking nice.
It may seem a bit odd for the first time, but that's the way the compiler creates its own assembler code while compiling C statements.
改行やタブ文字の特別なシーケンスは、見栄えの良いアセンブラリストを維持します。
これは、初めて見ると少し奇妙に思えるかもしれないけれど、
Cステートメントのコンパイル中に、コンパイラが、独自のアセンブラコードを
作成する方法です。
So far, the assembler instructions are much the same as they'd appear in pure assembly language programs.
However, registers and constants are specified in a different way, if they refer to C expressions.
The general form of an inline assembler statement is
これまでのところ、アセンブラ命令は、彼らは純粋なアセンブリ言語プログラムで
表示されていたものとほとんど同じです。
ただし、Cの式を参照する場合、レジスタと定数は、異なる方法で指定されます。
インラインアセンブラ文の一般的な形式は、以下のとおりです:
asm(code : output operand list : input operand list : clobber list);
The connection between assembly language and C operands is provided by an optional second and third part of the asm statement, the list of output and input operands.
We will explain the third optional part, the list of clobbers, later.
アセンブリ言語とCオペランドとの間の接続は、asm文と、オプションの第二の部分(出力オペランドリスト)と
第三の部分(出力オペランドリスト)によって提供されています。
オプションの第三の部分(clobbersリスト)については後ほど説明します。
The next example of rotating bits passes C variables to assembly language.
It takes the value of one integer variable, right rotates the bits by one and stores the result in a second integer variable.
ビット回転の次の例では、アセンブリ言語にC変数を渡します。
これは、右に1ビット回転させ、第2の整数の変数に結果を格納し、1つの整数変数の値をとります。
/* Rotating bits example */
asm("mov %[result], %[value], ror #1" : [result] "=r" (y) : [value] "r" (x));
Each asm statement is divided by colons into up to four parts:
各asm文は、4つの部分までに、コロンで分割されます。
1.The assembler instructions, defined in a single string literal:
アセンブラ命令、1つの文字列リテラルで定義される
"mov %[result], %[value], ror #1"
An optional list of output operands, separated by commas.
Each entry consists of a symbolic name enclosed in square brackets, followed by a constraint string, followed by a C expression enclosed in parentheses.
Our example uses just one entry:
コンマで区切られた、オプションの出力オペランドリスト。
[result] "=r" (y)
A comma separated list of input operands, which uses the same syntax as the list of output operands.
Again, this is optional and our example uses one operand only:
コンマで区切られた、出力オペランドリストと同じような文法を使う、入力オペランドリスト。
[value] "r" (x)
Optional list of clobbered registers, omitted in our example.
オプションのclobberedレジスタリストは、この例では省略されています。
As shown in the initial NOP example, trailing parts of the asm statement may be omitted, if unused.
Inline asm statements containing assembler instruction only are also known as basic inline assembly, while statements containing optional parts are called extended inline assembly.
If an unused part is followed by one which is used, it must be left empty.
The following example sets the current program status register of the ARM CPU.
It uses an input, but no output operand.
最初のNOPの例に示すように、未使用の場合は、asm文の末尾部分は、省略してもよいです。
アセンブラ命令を含むインラインのasm文のみは、基本的なインラインアセンブリ(basic inline assembly)として知られている。
オプションパーツを含む文が拡張されたインラインアセンブリ(extended inline assembly)と呼ばれている。
未使用のオペランドリスト(からっぽ)に、使用されるオペランドリストが続く場合は、
(未使用の部分は)空のままにしておく必要があります。
次の例は、ARM CPUの現在のプログラムステータスレジスタを設定します。
入力オペランドはあるけれど、出力オペランドが無い例です:
asm("msr cpsr,%[ps]" : : [ps]"r"(status));
Even the code part may be left empty, though an empty string is required.
The next statement creates a special clobber to tell the compiler, that memory contents may have changed.
Again, the clobber list will be explained later, when we take a look to code optimization.
コード部分が空のままであっても、からの文字列を渡すことが要求されます。
次のステートメントは、特別なclobberをコンパイラに伝えます。それはメモリコンテンツが変化する、というものです。
クロバーリストは、後述します(コードの最適化を見るとき)。
asm("":::"memory");
You can insert spaces, newlines and even C comments to increase readability.
あなたは、読みやすさを向上させるために、スペース、改行、さらにはCのコメントを挿入することができます。
In the code section, operands are referenced by a percent sign followed by the related symbolic name enclosed in square brackets.
It refers to the entry in one of the operand lists that contains the same symbolic name.
From the rotating bits example:
%[result] refers to output operand, the C variable y, and

%[value] refers to the input operand, the C variable x.
コードセクションでは、オペランドは、角括弧で囲まれた関連シンボリック名が続くパーセント記号によって参照されます。
これは、同じシンボル名が含まれているオペランドリスト内の1つのエントリを参照します。
ローテートビットの例から:
%[result]出力オペランドを参照します。Cの変数はyです。
%[value]入力オペランドを参照します。Cの変数はxです。
Symbolic operand names use a separate name space.
That means, that there is no relation to any other symbol table.
To put it simple: You can choose a name without taking care whether the same name already exists in your C code.
However, unique symbols must be used within each asm statement.
シンボリックオペランド名が別々の名前空間を使用します。
それは、他のシンボルテーブルとは関係がないことを、意味します。
シンプルに置くには:同じ名前が既にあなたのCコードに存在するかどうか、気にせずに名前を選択することができます。
しかし、ユニークなシンボルを各asmステートメント内で使用する必要があります。
If you already looked to some working inline assembler statements written by other authors, you may have noticed a significant difference.
In fact, the GCC compiler supports symbolic names since version 3.1. For earlier releases the rotating bit example must be written as
既に他の著者によって書かれた、動いているインラインアセンブラ文を見た場合に、
有意な差に気づいているかもしれません。
実際には、GCCコンパイラは、バージョン3.1以降のシンボル名をサポートしています。
以前のリリースの場合、ローテートビットの例は次のように記述する必要があります
asm("mov %0, %1, ror #1" : "=r" (result) : "r" (value));
Operands are referenced by a percent sign followed by a single digit, where %0 refers to the first %1 to the second operand and so forth.
This format is still supported by the latest GCC releases, but quite error-prone and difficult to maintain.
Imagine, that you have written a large number of assembler instructions, where operands have to be renumbered manually after inserting a new output operand.
オペランドは、単一の数字が続くパーセント記号によって参照されます。%0は1つ目の、%1は2つ目のオペランド、のように。
このフォーマットは、まだ最新のGCCリリースによってサポートされていますが、非常にエラーが発生しやすく、メンテナンスも難しいです。。
あながた大きな数のアセンブラ命令を多数書いていたことを想像してみてください。
オペランドに新しい出力オペランドを挿入した後、手動で再番号付けしなくてはなりません。
If all this stuff still looks a little odd, don't worry.
Beside the mysterious clobber list, you have the strong feeling that something else is missing, right? Indeed, we didn't talk about the constraint strings in the operand lists.
I'd like to ask for your patience.
There's something more important to highlight in the next chapter.
すべてのこのようなものが、まだ少し奇妙に見える場合は、心配しないでください。
ミステリアスなクロバーリストのほかに、何か他のものが、
不足しているという強い気持ちを持っていますね?。
確かに、我々は、オペランドリストの制約文字列について話しませんでした。
私はあなたに辛抱をお願いしたいと思います。
次の章で強調表示するために、より重要な何かがあります。

C code optimization

There are two possible reasons why you want to use assembly language.
First is, that C is limited when we are getting closer to the hardware.
E.g. there's no C statement for directly modifying the processor status register.
The second reason is to create highly optimized code.
No doubt, the GNU C code optimizer does a good job, but the results are far away from handcrafted assembler code.
あなたはアセンブリ言語を使用する2つの理由があります。
我々は、ハードウェアに近づいているときに最初に、そのCが限られています。
例えば。直接プロセッサステータスレジスタを変更するにはCの文はありません。
第二の理由は、高度に最適化されたコードを作成することです。
間違いなく、GNU Cコードオプティマイザは、良い仕事をしていますが、結果は手作りのアセンブラコードにおよびません*1
The subject of the chapter is often overlooked: When adding assembly language code by using inline assembler statements, this code is also processed by the C compiler's code optimizer.
Let's examine the part of a compiler listing which may have been generated from our rotating bits example:
閑話休題。
インラインアセンブラ文を使用して、アセンブリ言語コードを追加する場合、このコードは、Cコンパイラのコード最適化によって処理されます。
ローテートビットの例から生成された可能性がある、コンパイラーリストの一部調べてみましょう:
00309DE5    ldr   r3, [sp, #0]    @ x, x
E330A0E1    mov   r3, r3, ror #1  @ tmp, x
04308DE5    str   r3, [sp, #4]    @ tmp, y
The compiler selected register r3 for bit rotation.
It could have selected any other register or two registers, one for each C variable.
It may not explicitly load the value or store the result.
Here is another listing, generated by a different compiler version with different compile options:
コンパイラは、レジスタr3をビットローテーションのために選択しました。
これは、任意の他のレジスタまたは二つのレジスタは、各C変数のための1つを選択している可能性があります。
明示的に値をロードしたり、結果を保存しない場合があります。
以下は、異なるコンパイルオプションを使用して、別のコンパイラのバージョンによって生成された別のリストです:
E420A0E1    mov r2, r4, ror #1    @ y, x
The compiler selected a unique register for each operand, using the value already cached in r4 and passing the result to the following code in r2.
Did you get the picture?
コンパイラは、それぞれのオペランドにユニークなレジスタを選択しました。
すでにレジスタr4にキャッシュされていた値を使い、結果を続くコード内のr2に渡します。
写真をとりましたか?
Often it becomes worse.
The compiler may even decide not to include your assembler code at all.
These decisions are part of the compiler's optimization strategy and depend on the context in which your assembler instructions are used.
For example, if you never use any of the output operands in the remaining part of the C program, the optimizer will most likely remove your inline assembler statement.
The NOP example we presented initially may be such a candidate as well, because to the compiler this is useless overhead, slowing down program execution.
多くの場合、悪くなります。
コンパイラは、まったくあなたのアセンブラコードが含まれないことを決定することができます。
これらの決定はコンパイラの最適化戦略の一部であり、あなたのアセンブラ命令が使用される文脈に依存します。
例えば、Cプログラムの残りの部分では、出力オペランドのいずれかを使用することがなければ、
オプティマイザは、おそらくあなたのインラインアセンブラ文を削除します。
最初に紹介したNOPの例は、このような候補になることがあります。
なぜならば、コンパイラにとって、これは無用のオーバーヘッドであるため、プログラムの実行が遅くなるためです。
The solution is to add the volatile attribute to the asm statement to instruct the compiler to exclude your assembler code from code optimization.
Remember, that you have been warned to use the initial example.
Here is the revised version:
解決策は、コード最適化から、あなたのアセンブラコードを除外しないよう、
コンパイラに命令するために、volatile属性をasm文に追加することです。
修正版を以下に示します:
/* NOP example, revised */
asm volatile("mov r0, r0");
But there is more trouble waiting for us.
A sophisticated optimizer will re-arrange the code.
The following C snippet had been left over after several last minute changes:
しかし、私たちを待っている多くの問題があります。
洗練されたオプティマイザがコードを再配置します。
次のCコードの断片は、いくつかの最後の分の変更後に残されていました:
i++;
if (j == 1)
    x += 3;
i++;
The optimizer will recognize, that the two increments do not have any impact on the conditional statement.
Furthermore it knows, that incrementing a value by 2 will cost one ARM instruction only.
Thus, it will re-arrange the code to
オプティマイザは次のように認識するでしょう。2つのインクリメントは、条件文に影響を及ぼさないだろう。
さらに、インクリメントによって値を2つ増やすことは、1つのARM命令のみよりコストがかかることを知っています。
したがって、以下のようにコードを再配置します。
if (j == 1)
    x += 3;
i += 2;
and save one ARM instruction.
As a result: There is no guarantee, that the compiled code will retain the sequence of statements given in the source code.
そして、ARM命令を1つ節約します。
結果:コンパイルされたコードがソースコード内で指定された一連の文を保持される保証はありません。
This may have a great impact on your code, as we will demonstrate now.
The following code intends to multiply c with b, of which one or both may be modified by an interrupt routine.
Disabling interrupts before accessing the variables and re-enable them afterwards looks like a good idea.
これは、以下にデモで示すように、貴方のコードに於いて、とても大きな影響があるでしょう。
以下のコードは、cをbで乗じます。1つまたは両法が、割込みルーチンで変更されるかもしれません。
変数アクセスの前に割込みを禁止し、処理後に再度有効にすると良さそうです。
asm volatile("mrs r12, cpsr\n\t"
    "orr r12, r12, #0xC0\n\t"
    "msr cpsr_c, r12\n\t" ::: "r12", "cc");
c *= b; /* This may fail. */
asm volatile("mrs r12, cpsr\n"
    "bic r12, r12, #0xC0\n"
    "msr cpsr_c, r12" ::: "r12", "cc");
Unfortunately the optimizer may decide to do the multiplication first and then execute both inline assembler instructions or vice versa.
This will make our assembly code useless.
不幸なことに、オプティマイザは、乗算を先に行い、その後、インラインアセンブラ命令を実行することを決定します。もしくは逆。
これはアセンブラコードを無意味にします。
We can solve this with the help of the clobber list, which will be explained now.
The clobber list from the example above
ここで解説するクロバーリストの助けにより、これを解決できます。
クロバーリストの例は上記のとおりで、以下の文字列です:
"r12", "cc"
informs the compiler that the assembly code modifies register r12 and updates the condition code flags.
Btw. using a hard coded register will typically prevent best optimization results.
In general you should pass a variable and let the compiler choose the adequate register.
Beside register names and cc for the condition register, memory is a valid keyword too.
It tells the compiler that the assembler instruction may change memory locations.
This forces the compiler to store all cached values before and reload them after executing the assembler instructions.
And it must retain the sequence, because the contents of all variables is unpredictable after executing an asm statement with a memory clobber.
アセンブラコードが、レジスタr12とcondition code flagsを更新することをコンパイラに情報を与えます。
ところで。通常、ハードコーディングされたレジスタを使用すると、最良の最適化の結果を防ぐことになります。
一般的には、変数を渡すと、コンパイラが適切なレジスタを選択するようにする必要があります。
レジスタ名と条件レジスタ用"cc"の他に、"memory"も有効なキーワードです。
これは、アセンブラ命令がメモリ位置を変更することがあることを、コンパイラに指示します。
前にすべてのキャッシュされた値を保存し、アセンブラ命令を実行した後にそれらを再ロードするようにコンパイラを強制します。
そして、それは、順序を保持しなければなりません。
"memory"クロバーでasm文を実行した後の、すべての変数の内容は予測不可能であるためです。
asm volatile("mrs r12, cpsr\n\t"
    "orr r12, r12, #0xC0\n\t"
    "msr cpsr_c, r12\n\t" :: : "r12", "cc", "memory");
c *= b; /* This is safe. */
asm volatile("mrs r12, cpsr\n"
    "bic r12, r12, #0xC0\n"
    "msr cpsr_c, r12" ::: "r12", "cc", "memory");
Invalidating all cached values may be suboptimal.
Alternatively you can add a dummy operand to create an artificial dependency:
すべてのキャッシュされた値を無効化することは次善の策なのかもしれません。
別の方法としては、人工的な依存関係を作成するために、ダミーのオペランドを追加することができます。
asm volatile("mrs r12, cpsr\n\t"
    "orr r12, r12, #0xC0\n\t"
    "msr cpsr_c, r12\n\t" : "=X" (b) :: "r12", "cc");
c *= b; /* This is safe. */
asm volatile("mrs r12, cpsr\n"
    "bic r12, r12, #0xC0\n"
    "msr cpsr_c, r12" :: "X" (c) : "r12", "cc");
This code pretends to modify variable b in the first asm statement and to use the contents variable c in the second.
This will preserve the sequence of our three statements without invalidating other cached variables.
このコードは、最初のasmステートメントに変数bを変更すると第二のコンテンツを変数cを使用するフリをします。
これは、他のキャッシュされた変数を無効にすることなく、私たちの3つの文の順序を保持します。
It is essential to understand how the optimizer affects inline assembler statements.
If something remains nebulous, better re-read this part before moving on the the next topic.
これは、オプティマイザは、インラインアセンブラ文にどのように影響するかを理解することが不可欠です。
何かが漠然としたままの場合は、より良い次のトピックに移動する前に、この部分を再度読んでください。。

*1 : 訳注:ずいぶんと良くなっているので、どうかなぁ。vectorizeまでやってるものなぁ。

Input and output operands

We learned, that each input and output operand is described by a symbolic name enclosed in square bracket,
followed by a constraint string, which in turn is followed by a C expression in parentheses.
私たちは、それぞれの入力および出力オペランドが、順番に括弧内のCの式が続く制約文字列が続く、
角括弧で囲まれたシンボル名で記述されていること、を学びました。
What are these constraints and why do we need them?
You probably know that every assembly instruction accepts specific operand types only.
For example, the branch instruction expects a target address to jump at.
However, not every memory address is valid, because the final opcode accepts a 24-bit offset only.
In contrary, the branch and exchange instruction expects a register that contains a 32-bit target address.
In both cases the operand passed from C to the inline assembler may be the same C function pointer.
Thus, when passing constants, pointers or variables to inline assembly statements, the inline assembler must know, how they should be represented in the assembly code.
どのようなこれらの制約があり、我々にはなぜそれが必要なのですか?
あなたは、おそらくすべてのアセンブリ命令は、特定のオペランドのタイプを受け入れることを知っています。
例えば、分岐命令がでジャンプするターゲットアドレスを期待しています。
しかし、全てのメモリアドレスが有効ではありません。最終的にオペコードは24bitオフセットのみを許容するからです。
逆に、分岐交換命令は、32ビット・ターゲット・アドレスを含むレジスタを期待しています。
どちらの場合も、インラインアセンブラにCから渡されたオペランドは、同じCの関数ポインタである場合があります。
したがって、定数やポインタや変数をインラインアセンブリ分文へ渡すとき、
インラインアセンブラは、それらがアセンブリコードで表現する方法を、知っている必要があります。
For ARM processors, GCC 4 provides the following constraints.
ARMプロセッサ用のGCC4は、以下の制約を提供します:
Constraint Usage in ARM state Usage in Thumb state
fFloating point registers f0 .. f7Not available
hNot availableRegisters r8..r15
GImmediate floating point constantNot available
HSame a G, but negatedNot available
IImmediate value in data processing instructions
e.g. ORR R0, R0, #operand
Constant in the range 0 .. 255
e.g. SWI operand
JIndexing constants -4095 .. 4095
e.g. LDR R1, [PC, #operand]
Constant in the range -255 .. -1
e.g. SUB R0, R0, #operand
KSame as I, but invertedSame as I, but shifted
LSame as I, but negatedConstant in the range -7 .. 7
e.g. SUB R0, R1, #operand
lSame as rRegisters r0..r7
e.g. PUSH operand
MConstant in the range of 0 .. 32 or a power of 2
e.g. MOV R2, R1, ROR #operand
Constant that is a multiple of 4 in the range of 0 .. 1020
e.g. ADD R0, SP, #operand
mAny valid memory address
NNot availableConstant in the range of 0 .. 31
e.g. LSL R0, R1, #operand
ONot availableConstant that is a multiple of 4 in the range of -508 .. 508
e.g. ADD SP, #operand
rGeneral register r0 .. r15
e.g. SUB operand1, operand2, operand3
Not available
wVector floating point registers s0 .. s31Not available
XAny operand
Constraint characters may be prepended by a single constraint modifier.
Constraints without a modifier specify read-only operands.
Modifiers are:
制約文字は単一の制約修飾子で、前に付加することができます。
修飾子のない制約は、読み取り専用のオペランドを指定します。
修飾子は以下のとおり:
Modifier Specifies
=Write-only operand, usually used for all output operands
+Read-write operand, must be listed as an output operand
&A register that should be used for output only
Output operands must be write-only and the C expression result must be an lvalue, which means that the operands must be valid on the left side of assignments.
The C compiler is able to check this.
出力オペランドは書き込み専用にし、Cの式の結果は左辺値でなければなりません。
これは、オペランドは代入の左辺で有効である必要があることを意味します。。
Cコンパイラは、これを確認することができます。
Input operands are, you guessed it, read-only.
Note, that the C compiler will not be able to check, whether the operands are of reasonable type for the kind of operation used in the assembler instructions.
Most problems will be detected during the late assembly stage, which is well known for its weird error messages.
Even if it claims to have found an internal compiler problem that should be immediately reported to the authors, you better check your inline assembler code first.
入力オペランドは、想像どおり、読込専用です。
Cコンパイラは、オペランドがアセンブラ命令で使用するのに妥当な型か、を、チェックできないことに注意してください。
ほとんどの問題はよく、後半の組立段階中に検出され、その奇妙なエラーメッセージのために知られています。
すぐに作者に報告すべき内部コンパイラの問題を発見した、と、主張している場合でも、
あなたは最初に、インラインアセンブラコードを確認したほうが良いです。
A strict rule is: Never ever write to an input operand.
But what, if you need the same operand for input and output?
The constraint modifier + does the trick as shown in the next example:
厳格なルールは次のとおりです:"これまでに入力オペランドに書き込むことはありません"。
しかし、あなたが入力と出力のための同じオペランドが必要な場合は?
制約修飾子"+"は、次の例に示すように、トリックを行います。
asm("mov %[value], %[value], ror #1" : [value] "+r" (y));
This is similar to our rotating bits example presented above.
It rotates the contents of the variable value to the right by one bit.
In opposite to the previous example, the result is not stored in another variable.
Instead the original contents of input variable will be modified.
前述のローテートビットの例に酷似しています。
これは変数の値のコンテンツを、右に1ビットだけローテートします。
前の例とは逆に、結果が別の変数に格納されていません。
代わりに、入力変数の元の内容が変更されます。
The modifier + may not be supported by earlier releases of the compiler.
Luckily they offer another solution, which still works with the latest compiler version.
For input operators it is possible to use a single digit in the constraint string.
Using digit n tells the compiler to use the same register as for the n-th operand, starting with zero.
Here is an example:
修飾子"+"は、コンパイラの以前のリリースではサポートされない場合があります。
幸いなことに、彼らはまだ最新のコンパイラのバージョンで動作する別のソリューションを提供します。
入力オペレータにとっては、制約文字列に単一の数字を使用することが可能です。
数字nを使用すると、ゼロから始まるn番目のオペランドのためのと同じレジスタを使用するようにコンパイラに指示します。
asm("mov %0, %0, ror #1" : "=r" (value) : "0" (value));
Constraint "0" tells the compiler, to use the same input register that is used for the first output operand.
制約"0"は、コンパイラに、最初の出力オペランドで使われたレジスタと同じ入力レジスタを使うことを伝えます。
Note however, that this doesn't automatically imply the reverse case.
The compiler may choose the same registers for input and output, even if not told to do so.
You may remember the first assembly listing of the rotating bits example with two variables, where the compiler used the same register r3 for both variables.
The asm statement
これは、自動的に逆の場合を意味するものではありませんので、注意してください。
そうするように言われていない場合でも、コンパイラは、入力と出力に同じレジスタを選択することができます。
あなたは、コンパイラは両方の変数に同じレジスタr3を使用し、
2つの変数で回転ビットの例の最初のアセンブリー・リストを覚えています:
asm("mov %[result],%[value],ror #1":[result] "=r" (y):[value] "r" (x));
generated this code:
00309DE5    ldr   r3, [sp, #0]    @ x, x
E330A0E1    mov   r3, r3, ror #1  @ tmp, x
04308DE5    str   r3, [sp, #4]    @ tmp, y
This is not a problem in most cases, but may be fatal if the output operator is modified by the assembler code before the input operator is used.
In situations where your code depends on different registers used for input and output operands, you must add the & constraint modifier to your output operand.
The following code demonstrates this problem.
これは、ほとんどの場合、問題ではありませんが、入力演算子が使用される前に出力オペレータは、
アセンブラコードによって変更された場合、致命的なことがあります。
あなたのコードは、入力と出力オペランドに使用する異なるレジスタに依存する状況では、
あなたの出力オペランドに"&"制約修飾子を追加する必要があります。
次のコードは、この問題を示します。
asm volatile("ldr %0, [%1]"     "\n\t"
             "str %2, [%1, #4]" "\n\t"
             : "=&r" (rdv)
             : "r" (&table), "r" (wdv)
             : "memory");
A value is read from a table and then another value is written to another location in this table.
If the compiler would have chosen the same register for input and output, then the output value would have been destroyed on the first assembler instruction.
Fortunately, the & modifier instructs the compiler not to select any register for the output value, which is used for any of the input operands.
値は、テーブルから読み取られ、次に別の値は、このテーブル内の別の場所に書き込まれます。
コンパイラは、入力と出力に同じレジスタを選択したことになる場合には、出力値は最初のアセンブラ命令で破壊されたと推定します。
幸いなことに、"&"修飾子は、入力オペランドのいずれかのために使用される出力値のための任意のレジスタを選択しないようにコンパイラに指示します。

More recipes

Inline assembler as preprocessor macro(プリプロセッサマクロとしてのインラインアセンブラ)

In order to reuse your assembler language parts, it is useful to define them as macros and put them into include files.
Using such include files may produce compiler warnings, if they are used in modules, which are compiled in strict ANSI mode.
To avoid that, you can write __asm__ instead of asm and __volatile__ instead of volatile.
These are equivalent aliases.
アセンブラ言語の部分を再利用するためには、マクロとして定義し、includeファイルにそれらを置くことが有用である。
そのようなインクルードファイルを使用することは、厳密なANSIモードでコンパイルされたモジュールで使用されている場合、コンパイラの警告を生成することがあるでしょう。
それを回避するには、asmの代わりに__asm__で、volatileの代わりに__volatile__と書くことができます。
これらは同等の別名(alias)です。
Here is a macro which will convert a long value from little endian to big endian or vice versa:
ここでは、リトルエンディアンからビッグエンディアンに、またはその逆にlong値を変換するマクロをしめします:
#define BYTESWAP(val) \
    __asm__ __volatile__ ( \
        "eor     r3, %1, %1, ror #16\n\t" \
        "bic     r3, r3, #0x00FF0000\n\t" \
        "mov     %0, %1, ror #8\n\t" \
        "eor     %0, %0, r3, lsr #8" \
        : "=r" (val) \
        : "0"(val) \
        : "r3", "cc" \
    );

C stub functions

Macro definitions will include the same assembler code whenever they are referenced.
This may not be acceptable for larger routines.
In this case you may define a C stub function.
マクロ定義は、それらが参照されるたびに同じアセンブラコードが含まれます。
マクロ定義は、自身を参照するアセンブラコードを含むでしょう。
これは大きなルーチンでは許容されない場合があります。
このようなケースでは、Cのスタブ関数を定義することができます。
Here is the byte swap procedure again, this time implemented as a C function.
ここでは、バイトスワップ手順を再び示します:この時、Cの関数として実装します。
unsigned long ByteSwap(unsigned long val)
{
asm volatile (
        "eor     r3, %1, %1, ror #16\n\t"
        "bic     r3, r3, #0x00FF0000\n\t"
        "mov     %0, %1, ror #8\n\t"
        "eor     %0, %0, r3, lsr #8"
        : "=r" (val)
        : "0"(val)
        : "r3"
);
return val;
}

Replacing symbolic names of C variables(Cの変数をシンボリックに置換する)

By default GCC uses the same symbolic names of functions or variables in C and assembler code.
You can specify a different name for the assembler code by using a special form of the asm statement:
デフォルトでは、GCCは、Cとアセンブラコード内の関数や変数の同じシンボル名を使用しています。
あなたはasm文の特別なフォームを使用してアセンブラコードに別の名前を指定することができます。
unsigned long value asm("clock") = 3686400;
This statement instructs the compiler to use the symbolic name clock rather than value.
This makes sense only for global variables.
Local variables (aka auto variables) do not have symbolic names in assembler code.
この文は、値ではなく、シンボリック名の"clock"を使用するようにコンパイラに指示します。
これは、グローバル変数のために理にかなっています。
ローカル変数(自動変数)は、アセンブラコードのシンボル名を持っていません。
Replacing symbolic names of C functions
In order to change the name of a function, you need a prototype declaration, because the compiler will not accept the asm keyword in the function definition:
C関数のシンボリック名を置き換えます
コンパイラは、関数定義のasmキーワードを受け入れないので、関数の名前を変更するためには、あなたは、プロトタイプ宣言が必要になります。
extern long Calc(void) asm ("CALCULATE");
Calling the function Calc() will create assembler instructions to call the function CALCULATE.
関数Calc()を呼び出す際には、関数CALCULATEを呼び出すためのアセンブラ命令を作成します。

Forcing usage of specific registers(指定レジスタの使用を強制する)

A local variable may be held in a register.
You can instruct the inline assembler to use a specific register for it.
ローカル変数は、レジスタに保持されることがあります。
あなたはそれのために特定のレジスタを使用するインラインアセンブラに指示することができます。
void Count(void) {
register unsigned char counter asm("r3");

... some code...
asm volatile("eor r3, r3, r3" : "=l" (counter));
... more code...
}
The assembler instruction, "eor r3, r3, r3", will clear the variable counter.
Be warned, that this sample is bad in most situations, because it interferes with the compiler's optimizer.
Furthermore, GCC will not completely reserve the specified register.
If the optimizer recognizes that the variable will not be referenced any longer, the register may be re-used.
But the compiler is not able to check whether this register usage conflicts with any predefined register.
If you reserve too many registers in this way, the compiler may even run out of registers during code generation.
アセンブラ命令、"eor r3, r3, r3"は、変数カウンタをクリアします。
これはコンパイラの最適化に干渉するため、このサンプルでは、ほとんどの状況で悪いことを警告されます。
また、GCCは完全に指定されたレジスタを予約しません。
オプティマイザは、変数がもはや参照されないことを認識した場合、レジスタを再使用することができます。
しかし、コンパイラは、任意の事前定義されたレジスタと、このレジスタ使用するかどうかの競合を確認することができません。
あなたはこのようにあまりにも多くのレジスタを予約した場合、コンパイラはあっても、コード生成時レジスタが不足することがあります。

Using registers temporarily

If you are using registers, which had not been passed as operands, you need to inform the compiler about this.
The following code will adjust a value to a multiple of four.
It uses r3 as a scratch register and lets the compiler know about this by specifying r3 in the clobber list.
Furthermore the CPU status flags are modified by the ands instruction and thus cc had been added to the clobbers.
あなたがオペランドとして渡されていないレジスタを使用している場合は、このことについてコンパイラに通知する必要があります。
次のコードは、4の倍数に値を調整します。
これは、スクラッチ・レジスタとしてr3を使用し、コンパイラはクロバーリストにr3を指定することで、これについて知ることができます。
さらに、CPUのステータスフラグは論理積命令によって変更されているので、ccがクロバーリストに追加されています。
asm volatile(
    "ands    r3, %1, #3"     "\n\t"
    "eor     %0, %0, r3" "\n\t"
    "addne   %0, #4"
    : "=r" (len)
    : "0" (len)
    : "cc", "r3"
  );
Again, hard coding register usage is always bad coding style.
Better implement a C stub function and use a local variable for temporary values.
再度書きますが、ハードレジスタの使用をコーディングすることは、常に悪いコーディングスタイルです。
より良いCスタブ機能を実装し、一時的な値については、ローカル変数を使用します。

Using constants(定数を使う)

You can use the mov instruction to load an immediate constant value into a register.
Basically, this is limited to values ranging from 0 to 255.
あなたはレジスタに即値定数値をロードするmov命令を使用することができます。
基本的に、これは、0から255の範囲の値に制限されています。
asm("mov r0, %[flag]" : : [flag] "I" (0x80));
But also larger values can be used when rotating the given range by an even number of bits.
In other words, any result of

n * 2^x

with n is in the mentioned range of 0 to 255 and x is an even number in the range of 0 to 24.
Because of rotation, x may be set to 26, 28 or 30, in which case bits 37 to 32 are folded to bits 5 to 0 resp.
Last not least, the binary complement of these values may be given, when using mvn instead of mov.
偶数のビット数だけ回転させた範囲で、より大きな値を使用することができます。
言い換えると、次の任意の結果を使うことができます:
n * 2^x : nは0から255の値で, xは0から24の偶数
回転なので、ビット37から32は、それぞれビット5から0に折りたたまれても良いような場合には、26,28,30に設定することができます。
movのかわりにmvnを使う時は、これらの値の2の補数は与えられてもよいです。
Sometimes you need to jump to a fixed memory address, which may be defined by a preprocessor macro.
You can use the following assembly code:
時々、プリプロセッサマクロに依って定義された固定メモリアドレスへジャンプしたい時があります。
以下のアセンブリコードを使うことができます:
    ldr  r3, =JMPADDR
    bx   r3
This will work with any legal address value.
If the constant fits (for example 0x20000000), then the smart assembler will convert this to
これは任意の有効なアドレス値で動作します。
定数がフィットするならば(例えば0x20000000)、賢いアセンブラは以下のように変換するでしょう:
    mov  r3, #0x20000000
    bx   r3
If it doesn't fit (for example 0x00F000F0), then the assembler will load the value from the literal pool.
もしフィットしないなら(例えば、0x00F000F0)、アセンブラはリテラルプールから値を読みだすでしょう:
    ldr  r3, .L1
    bx   r3
    ...
    .L1: .word 0x00F000F0
With inline assembly it works in the same way.
But instead of using ldr, you can simply provide a constant as a register value:
インラインアセンブリでも、同様にふるまいます。
しかし、ldrを使う代わりに、レジスタ値のように定数を簡単に与えることができます
asm volatile("bx %0" : : "r" (JMPADDR));
Depending on the actual value of the constant, either mov, ldr or any of its variants is used.
If JMPADDR is defined as 0xFFFFFF00, then the resulting code will be similar to
定数の実際の値に依存して、ldrまたは、その変形が使われます。
JMPADDRが、0xFFFFFF00と定義されているなら、結果のコードは以下のようになるでしょう:
    mvn  r3, #0xFF
    bx   r3
The real world is more complicated.
It may happen, that we need to load a specific register with a constant.
Let's assume, that we want to call a subroutine, but we want to return to another address than the one that follows our branch.
This is can be useful when embedded firmware returns from main.
In this case we need to load the link register. Here is the assembly code:
現実では、もっと複雑です。指定されたレジスタに定数をロードする必要が起きるでしょう。
サブルーチン呼び出しをしたいけれども、分岐の続きではなく、他のアドレスへ戻りたいと仮定しましょう。
これは、組み込みファームウェアが、mainから戻るときに使えます。
このケースでは、リンクレジスタに読み出す必要があります。
アセンブリコードを示します:
    ldr  lr, =JMPADDR
    ldr  r3, main
    bx   r3
Any idea how to implement this in inline assembly? Here is a solution:
インラインアセンブリで実装するアイデアはあるでしょうか。
解決法を示します:
asm volatile(
    "mov lr, %1\n\t"
    "bx %0\n\t"
    : : "r" (main), "I" (JMPADDR));
But there is still a problem.
We use mov here and this will work as long as the value of JMPADDR fits.
The resulting code will be the same than what we get in pure assembly code.
If it doesn't fit, then we need ldr instead.
But unfortunately there is no way to express in inline assembly.
しかし、少し問題があります。
ここでmov命令を使い、JMPADDRがフィットする間は動きます。
結果のコードは、ピュアアセンブリコードで得たものと同じになるでしょう。
JMPADDRがフィットしない場合、ldr命令に変えなければなりません。
しかし、不幸なことにインラインアセンブリで表現する手段はありません。
    ldr  lr, =JMPADDR
Instead, we must write
代わりに、以下のように書かなければなりません。
asm volatile(
    "mov lr, %1\n\t"
    "bx %0\n\t"
    : : "r" (main), "r" (JMPADDR));
Compared to the pure assembly code, we end up with an additional statement, using an additional register.
ピュアアセンブリコードと比べましょう。
追加の分と追加のレジスタを使って終わります。
    ldr     r3, .L1
    ldr     r2, .L2
    mov     lr, r2
    bx      r3

Register Usage(レジスタの使い方)

It is always a good idea to analyze the assembly listing output of the C compiler and study the generated code.
The following table of the compiler's typical register usage will be probably helpful to understand the code.
常にCコンパイラのアセンブリ出力リストを分析し、生成されたコードを勉強することをお勧めします。
コンパイラの典型的なレジスタの使用の次の表は、コードを理解するために、おそらく参考になります。
Register Alt.Name Usage
r0a1First function argument Integer function result Scratch register
r1a2Second function argument Scratch register
r2a3Third function argument Scratch register
r3a4Fourth function argument Scratch register
r4v1Register variable
r5v2Register variable
r6v3Register variable
r7v4Register variable
r8v5Register variable
r9v6Register variable
rfpReal frame pointer
r10slStack limit
r11fpArgument pointer
r12ipTemporary workspace
r13spStack pointer
r14lrLink register Workspace
r15pcProgram counter

Common pitfalls

Instruction sequence

Developers often expect, that a sequence of instructions remains in the final code as specified in the source code.
This assumption is wrong and often introduces hard to find bugs.
Actually, asm statements are processed by the optimizer in the same way as other C statements.
They may be rearranged if dependencies allow this.
開発者は、多くの場合、ソースコードで指定された命令のシーケンスは、最終的なコードに残っていることを、期待しています。
この仮定が間違っていると、多くの場合、バグを見つけるのは難しいことを紹介します。
実際に、asm文が他のC言語の文と同じように、オプティマイザによって処理されています。
依存関係がこれを許可した場合、asm文は再配置することができます。
The chapter "C code optimization" discusses the details and offers solutions.
"C code optimization"の章で、詳細を議論し、解決法を提案しています。

Defining a variable as a specific register

Even if a variable had been forcibly assigned to a specific register, the resulting code may not work as expected.
Consider the following snippet:
変数を強制的に特定のレジスタに割り当てられていた場合であっても、予想通り、結果のコードは動作しない可能性があります。
以下のコードを考えてみます。
int foo(int n1, int n2) {
  register int n3 asm("r7") = n2;
  asm("mov r7, #4");
  return n3;
}
The compiler is instructed to use r7 as a local variable n3, which is initialized by parameter n2.
Then the inlined assembly statement sets r7 to 4, which should be finally returned.
However, this may go completely wrong.
Remember, that compiler cannot recognize, what's happening inside the inline assembly.
But the optimizer is smart on the C code, generating the following assembly code.
コンパイラは、パラメータn2で初期化されているローカル変数n3としてr7を使用するように指示されます。
そして、インラインアセンブリステートメントがr7に4をセットし、最終的に返されるべきである。
しかし、これは完全に間違って行くことがあります。
そのコンパイラは、インラインアセンブリの内部で何が起こっているか、認識できない、ということを、覚えておいてください。
しかし、オプティマイザは、Cコードに賢く、次のアセンブリコードを生成します:
foo:
  mov r7, #4
  mov r0, r1
  bx  lr
Instead of returning r7, the value of n2 is returned, which had been passed to our function in r1.
What happed here? Well, while the final code still contains our inline assembly statement, the C code optimizer decided, that n3 is not required.
It directly returns parameter n2 instead.
r7を返す代わりに、私たちの関数に渡されていたr1に入っているn2の値が返されます。
ここで何が起こったのか?
最終的なコードは、まだ私達のインラインアセンブリ文は、決定したCのコード最適化が含まれていながら、まあ、そのn3は必要ありません。
代わりに直接パラメータn2を返します。
Just assigning a variable to a fixed register does not mean, that the C compiler will use that variable.
We still have to tell the compiler, that a variable is modified inside the inline assembly operation.
For the given example, we need to extend the asm statement with an output operator:
固定レジスタに変数を割り当てるとが、Cコンパイラはその変数を使用すること、を直ちに意味するものではありません。
まだ、変数はインラインアセンブリ演算の内部で修正されていることを、コンパイラに指示する必要があります。
与えられた例では、出力演算子でasm文を拡張する必要があります。
asm("mov %0, #4" : "=l" (n3));
Now the C compiler is aware, that n3 is modified and will generate the expected result:
今、Cコンパイラが認識して、n3が変更されると予想される結果を生成します:
foo:
  push {r7, lr}
  mov  r7, #4
  mov  r0, r7
  pop  {r7, pc}

Executing in Thumb status

Be aware, that, depending on the given compile options, the compiler may switch to thumb state.
Using inline assembler with instructions that are not available in thumb state will result in cryptic compile errors.
指定されたコンパイルオプションに応じて、コンパイラがThumb状態に切り替えることができる、ということに注意してください。
Thumb状態では使用できない命令でインラインアセンブラを使用すると、不可解なコンパイルエラーになります。

Assembly code size

In most cases the compiler will correctly determine the size of the assembler instruction, but it may become confused by assembler macros.
Better avoid them.
ほとんどの場合、コンパイラは正しくアセンブラ命令のサイズを決定しますが、それはアセンブラマクロによって混乱することがあります。
それらを避けることがより良いです。
In case you are confused: This is about assembly language macros, not C preprocessor macros.
It is fine to use the latter.
あなたが混乱しているケース:これは、アセンブリ言語のマクロではなく、Cプリプロセッサマクロについてです。
後者を使用するのがよいです。

Labels

Within the assembler instruction you can use labels as jump targets.
However, you must not jump from one assembler instruction into another.
The optimizer knows nothing about those branches and may generate bad code.
アセンブラ命令内では、ジャンプターゲットとしてラベルを使用することができます。
しかし、あなたは別のものに1アセンブラ命令からジャンプしてはなりません。
オプティマイザは、これらの分岐について何も知らないし、不正なコードを生成することがあります。

Preprocessor macros

Inline assembly instruction cannot contain preprocessor macros, because for the preprocessor these instruction are nothing else but string constants.
プリプロセッサのために、これらの命令は何もないが、文字列定数であるため、
インラインアセンブリ命令は、プリプロセッサマクロを含めることはできません。
If your assembly code must refer to values that are defined by macros, see the chapter about "Using constants" above.
あなたのアセンブリコードは、マクロによって定義された値を参照する必要がある場合は、
上記の"Using constants"に関する章を参照してください。

External links

For a more thorough discussion of inline assembly usage, see the gcc user manual.
The latest version of the gcc manual is always available here:
http://gcc.gnu.org/onlinedocs/
インラインアセンブリの使用状況についての全体的な説明については、gccのマニュアルを参照してください。
gccのマニュアルの最新バージョンは、以下で常に利用可能です:
http://gcc.gnu.org/onlinedocs/

Copyright

Copyright (C) 2007-2013 by Harald Kipp.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation.
If you think that something hasn't been explained clearly enough or is even wrong, please let me know.

Document History

Date (YMD} Change Thanks to
2014/02/11Fixed the first constant example, where the constant must be an input operand.spider391Tang
2013/08/16Corrected the example code of specific register usage and added a new pitfall section about the same topic.Sven Köhler
2012/03/28Corrected the pitfall section about constant parameters and moved to the usage section.enh
Added a preprocessor macros pitfall.
Added this history.

2016/01/11(月)あるコミットが含まれるカーネルバージョンを知りたい

昔々, "sync_supers"プロセスが, dirty pageをwritebackしていた.
upstreamを覗くと そういう文字列が消失していた. どこかで消されたっぽい.

結果

v3.6からメインラインで削除された.

手順

削除されたというコミットログを探す.
$ git log --grep sync_supers
タグを探す
当該コミットが含まれる直近のタグを探すのに git-describeコマンドが使える.
$ git describe --all --contains f0cd2dbb6cf387c11f87265462e370bb5469299e
tags/v3.6-rc2~30^2~15
チルダ以降の読み方がわからないのだけど, v3.6-rc2に含まれているのは確実..
バージョンを問われれば, 『v3.6から』と, 云えば良いだろう.