Linuc ja: Difference between revisions
Line 737: | Line 737: | ||
--- | --- | ||
==DKMS for Kernel | ==DKMS for Kernel Modules(カーネルモジュールのためのDKMS)== | ||
'''Dynamic Kernel Module Support (DKMS)''' automates module rebuilding for new kernels: | '''Dynamic Kernel Module Support (DKMS)''' automates module rebuilding for new kernels: | ||
*Add a Module: | *'''Add a Module:''' | ||
<pre>sudo dkms add -m nvidia -v 470.141.03</pre> | <pre>sudo dkms add -m nvidia -v 470.141.03</pre> | ||
*'''Build and Install''': | *'''Build and Install''': | ||
Line 746: | Line 746: | ||
*'''Verify Status''': | *'''Verify Status''': | ||
<pre>dkms status # Shows installed modules and kernel compatibility[7]</pre> | <pre>dkms status # Shows installed modules and kernel compatibility[7]</pre> | ||
--- | |||
DKMS(Dynamic Kernel Module Support)は、Linuxで使われる「カーネルモジュール(主にサードパーティのドライバなど)」を、カーネルが新しくなったときやアップデートされたときに、自動的に再ビルド(作り直し)してくれる仕組みです。 | |||
*モジュールを追加 | |||
<pre> | |||
sudo dkms add -m nvidia -v 470.141.03 | |||
</pre> | |||
*構築とインストール | |||
<pre> | |||
sudo dkms build -m nvidia -v 470.141.03 | |||
sudo dkms install -m nvidia -v 470.141.03[7] | |||
</pre> | |||
*状態を確認する | |||
<pre> | |||
dkms status #インストール済みのモジュールとカーネルの互換性を表示します | |||
</pre> | |||
--- | |||
==Initrd Configuration== | ==Initrd Configuration== | ||
'''Initial RAM Disk (initrd)''' loads critical modules before the root filesystem mounts: | '''Initial RAM Disk (initrd)''' loads critical modules before the root filesystem mounts: |
Revision as of 05:51, 6 May 2025
2.01: System Boot and Linux Kernel(システムの起動(ブート)とLinuxカーネル)
BIOS and UEFI Fundamentals(BIOS及びUEFIの基礎)
The BIOS (Basic Input/Output System) and UEFI (Unified Extensible Firmware Interface) are firmware interfaces responsible for initializing hardware during system startup and loading the operating system. BIOS, the older standard, relies on the Master Boot Record (MBR) partitioning scheme, which supports up to four primary partitions and boot drives up to 2.2 TB. In contrast, UEFI uses the GUID Partition Table (GPT), allowing up to 128 partitions and boot drives exceeding 9 zettabytes. UEFI also introduces the EFI System Partition (ESP), a FAT-formatted partition storing bootloaders, kernel images, and UEFI applications like efibootmgr. The ESP is critical for UEFI systems, as it hosts the grubx64.efi bootloader and enables Secure Boot to verify firmware integrity.
---
BIOSとUEFIって何?
パソコンの電源を入れると、最初に動くのが「BIOS」や「UEFI」と呼ばれる仕組みです。 これは、パソコンの部品(ハードウェア)をチェックして、OS(WindowsやLinuxなど)を起動するための準備をする役割を持っています。
---
BIOS(バイオス)とは?
- 昔から使われている仕組みです。 - 「MBR(マスターブートレコード)」という方式でハードディスクを管理します。 - 2.2TB(テラバイト)までの大きさのハードディスクしか使えません。 - パーティション(ハードディスクの仕切り)は最大4つまでしか作れません。
---
UEFI(ユーイーエフアイ)とは?
- 新しいパソコンで使われている仕組みです。 - 「GPT(GUIDパーティションテーブル)」という新しい方式でハードディスクを管理します。 - とても大きなハードディスク(9ゼタバイト以上、ほぼ無制限)も使えます。 - パーティションは最大128個まで作れます。 - 「ESP(EFIシステムパーティション)」という特別な場所に、パソコンを起動するための大事なファイル(ブートローダーなど)を保存します。 - 「セキュアブート」という機能で、ウイルスなどの不正なプログラムが勝手に起動しないように守ってくれます。
---
まとめ
- **BIOS**は昔の仕組みで、使えるハードディスクやパーティションの数に制限があります。
- **UEFI**は新しい仕組みで、大きなハードディスクやたくさんのパーティションが使え、セキュリティも強化されています。
---
Boot Loader Configuration and Shell Usage(ブートローダーの設定とシェルの利用)
Modifying boot options varies by firmware type. In UEFI systems, efibootmgr manages boot entries, allowing users to adjust boot order, set active/inactive entries, and create new boot options via commands like efibootmgr -o 0001,0002. For Windows, bcdedit /default {GUID} changes the default OS entry. In BIOS-based systems, GRUB’s command-line interface provides direct control using commands such as kernel /vmlinuz root=/dev/sda1 to specify the kernel and initrd /initramfs.img to load the initial RAM disk. GRUB’s shell also supports disk exploration with ls (hd0,1)/ and boot troubleshooting via grub-install.
---
ブートオプション(パソコンが起動するときに使う設定)の変更方法は、パソコンのファームウェア(BIOSやUEFIなど)によって違います。
- UEFIを使っている場合
「efibootmgr」というコマンドを使って、どの順番で起動するか(ブート順序)を変えたり、起動項目を追加・無効にしたりできます。
例: efibootmgr -o 0001,0002 でブート順序を「0001」→「0002」に変更できます。
- Windowsの場合
「bcdedit /default {GUID}」というコマンドで、最初に起動するOS(Windowsなど)を選べます。
- BIOSを使っている場合
「GRUB」という起動プログラムのコマンドラインで、直接カーネル(OSの中核部分)や初期RAMディスク(起動時に使うファイル)を指定できます。
例: kernel /vmlinuz root=/dev/sda1 でカーネルを指定 initrd /initramfs.img で初期RAMディスクを読み込む
GRUBのシェルでは、ls (hd0,1)/ でディスクの中身を見たり、grub-install でブートのトラブルを直したりもできます。
---
GRUB Boot Menu Generation(GRUBブートメニュー生成)
The GRUB boot menu is regenerated using grub2-mkconfig, which synthesizes configuration files from /etc/default/grub and scripts in /etc/grub.d/. Customizations like timeout adjustments or theme changes are added to /etc/default/grub, and executing grub2-mkconfig -o /boot/grub2/grub.cfg applies these changes. For UEFI systems, the configuration resides in /boot/efi/EFI/[distro]/grub.cfg, while BIOS systems use /boot/grub2/grub.cfg.
---
GRUBのブートメニューは「grub2-mkconfig」というコマンドで作り直します。
- このコマンドは、/etc/default/grub という設定ファイルと、/etc/grub.d/ フォルダの中のスクリプトを元にして、ブートメニューの内容を自動で作ります。
- メニューを表示する時間を変えたり、見た目(テーマ)を変えたりしたいときは、/etc/default/grub ファイルを書き換えます。
- 設定を実際に反映するには、「grub2-mkconfig -o /boot/grub2/grub.cfg」とコマンドを打ちます。
- UEFIを使っているパソコンの場合、設定ファイルは「/boot/efi/EFI/[ディストリ名]/grub.cfg」にあります。
- BIOSを使っているパソコンの場合、設定ファイルは「/boot/grub2/grub.cfg」です。
まとめ
設定を変えたらコマンドを実行して、ブートメニューを更新しましょう。
パソコンの種類(UEFIかBIOSか)によって、設定ファイルの場所が違うので注意してください。
---
Kernel Module Loading with initrd/initramfs(initrd/initramfsによるカーネルモジュールのロード)
The initrd (initial RAM disk) or initramfs (initial RAM filesystem) preloads essential kernel modules and drivers before the root filesystem is mounted. Modules like storage controllers or filesystem drivers are included by editing /etc/initramfs-tools/modules and rebuilding with update-initramfs -u. For example, adding netconsole to initrd involves creating a hook script in /etc/initramfs-tools/hooks/ to ensure the module is included during initramfs generation.
---
initrd(初期RAMディスク)やinitramfs(初期RAMファイルシステム)は、パソコンが起動するとき、OSの「根っこ」(ルートファイルシステム)を読み込む前に、まず必要なカーネルモジュールやドライバを準備するための仕組みです。
- なぜ必要?
たとえば、HDDやSSDなどのストレージや、ファイルシステムのドライバなどは、OSの根っこを読み込むために必要ですが、その根っこ自体を読み込む前に必要になる場合があります。そのため、initrdやinitramfsで先に必要なものをメモリ上に用意しておきます。
- どうやって必要なモジュールを追加するの?
- /etc/initramfs-tools/modules というファイルに、必要なモジュール名(例:netconsole)を書きます。
- その後、update-initramfs -u コマンドを実行します。これで、initramfsが新しくなり、書いたモジュールが含まれます。
- さらに細かく追加したい場合
たとえばnetconsoleというモジュール(ネットワーク経由でコンソールを使うためのもの)をinitrdに確実に追加したい場合は、/etc/initramfs-tools/hooks/ という場所に専用のスクリプトを作ります。すると、initramfsを作るときにそのモジュールも自動的に含まれます。
まとめ
initrdやinitramfsは、OSが起動する前に必要なドライバや機能を準備する「前準備」の仕組みです。必要なものを追加したいときは、設定ファイルやスクリプトを用意して、コマンドで再構築します。
---
Hardware Initialization and Filesystem Mounting(ハードウェアの初期化とファイルシステムのマウント)
During boot, the kernel initializes hardware via udev, which dynamically loads kernel modules based on detected devices. After module loading, the kernel mounts the root filesystem specified by the root= parameter in the bootloader. If the root filesystem is encrypted or on a RAID array, initrd handles decryption or assembly before passing control to the OS.
---
パソコンが起動するとき、カーネル(OSの中心部分)は「udev(ユーデブ)」という仕組みを使って、パソコンのハードウェア(HDDやUSBなど)を準備します。udevは、パソコンにつながっているデバイスを自動で見つけて、それに合ったドライバ(カーネルモジュール)を読み込みます。
- ドライバの準備が終わったら、カーネルは「root=」という設定で指定された場所(通常はHDDやSSDの中の一部)を「ルートファイルシステム」として使えるようにします(マウントします)。
- もしルートファイルシステムが暗号化されている場合や、複数のディスクをまとめて使うRAIDの場合は、initrd(初期RAMディスク)が暗号の解除やRAIDの準備をしてくれます。
- initrdがこれらの準備を終えると、OS本体が動き始めます。
まとめ
起動時には、パソコンのハードウェアやドライバの準備、暗号化やRAIDの処理などが自動で行われ、その後にOSがしっかり動き始めます。
---
Service Initialization with systemd(systemdによるサービスの初期化)
Post-filesystem mount, systemd initializes services defined in systemd.unit files. The default target (e.g., multi-user.target or graphical.target) is set using systemctl set-default, while systemctl enable [service] configures services to start at boot. Systemd also manages dependencies, ensuring services like networking or logging start in the correct order.
---
パソコンの起動でファイルシステム(データの整理場所)が準備できた後、systemd(システィムディー)が、設定ファイルで決められたさまざまなサービス(ネットワークやログなど)を自動で動かし始めます。
- 「systemctl set-default」コマンドで、起動後にどの画面を使うか(たとえば文字だけか、グラフィカルな画面かなど)を選べます。
- 「systemctl enable [サービス名]」コマンドを使うと、そのサービスがパソコンの電源を入れたとき自動で起動するようになります。
- systemdは、サービス同士の「どれを先に動かすか」も自動で調整してくれるので、ネットワークやログなどのサービスが正しい順番で動きます。
まとめ
systemdは、パソコンの起動後に必要なサービスを自動で準備し、順番や自動起動も簡単に管理できます。
---
Boot Loader Installation and Filesystem Structure(ブートローダーのインストールとファイルシステムの構造)
The grub-install or grub2-install command installs GRUB to the MBR (for BIOS) or ESP (for UEFI). Key directories include:
- /boot/: Contains the kernel (vmlinuz) and initramfs.
- /boot/grub2/: Stores GRUB configuration files (e.g., grub.cfg) on BIOS systems.
- /boot/efi/: Houses UEFI bootloaders and the ESP partition contents.
For UEFI installations, grub-install copies the grubx64.efi bootloader to /boot/efi/EFI/[distro]/, ensuring compatibility with firmware expectations.
---
「grub-install」や「grub2-install」というコマンドを使うと、GRUBというブートローダーをパソコンにインストールできます。
- BIOSを使うパソコンの場合
GRUBはディスクの先頭(MBRと呼ばれる場所)にインストールされます。
- UEFIを使うパソコンの場合
GRUBはEFIシステムパーティション(ESP)という特別な場所にインストールされます。
主なフォルダと役割
- /boot/
カーネル(vmlinuz)や初期RAMディスク(initramfs)など、起動に必要なファイルが入っています。
- /boot/grub2/
BIOSを使うパソコンの場合、GRUBの設定ファイル(例:grub.cfg)がここに保存されます。
- /boot/efi/
UEFIを使うパソコンの場合、ブートローダーやESPパーティションの中身がここに置かれます。
UEFIの場合のインストールの流れ
- grub-installコマンドは、grubx64.efiというファイル(UEFI用のブートローダー)を「/boot/efi/EFI/[ディストリ名]/」という場所にコピーします。
- これで、パソコンのファームウェア(UEFI)がGRUBを正しく認識し、OSが起動できるようになります。
まとめ
GRUBのインストール場所や必要なフォルダの役割を知っておくと、パソコンの起動やトラブル対応がしやすくなります。
他にも知りたいことがあれば、どうぞご質問ください。
---
What is Systemd? - Systemd boot customization(Systemdとは何か? – Systemdによる起動のカスタマイズ)
Systemd is a modern system and service manager for Linux, designed to replace traditional init systems like SysV. As the first process started during boot (PID 1), it initializes hardware, mounts filesystems, and manages services through unit files-configuration files defining resources like services, sockets, and targets. Unlike SysV, systemd enables parallel service startup, reducing boot times, and integrates logging via journalctl for troubleshooting.
---
Systemd(システィムディー)は、Linuxで最近使われているシステムとサービスの管理プログラムです。昔の「init(イニット)」という仕組みに代わって、今のLinuxで広く使われています。
- パソコンの電源を入れると、systemdが最初に動き始めます。
- systemdは、ハードウェアの準備やファイルシステムのマウント(読み込み準備)を行い、必要なサービス(ネットワークやログなど)を自動で起動します。
- サービスの起動や設定は「ユニットファイル」という設定ファイルで管理します。
- systemdは「複数のサービスを同時に起動できる」ため、パソコンの起動が早くなります。
- また、systemdには「journalctl(ジャーナルコントロール)」というログ管理機能もついていて、トラブルがあったときもログを見て簡単に原因を調べられます。
まとめ
Systemdは、Linuxの起動やサービス管理を「速く、簡単に、便利に」してくれる仕組みです。
他にも知りたいことがあれば、気軽に聞いてください。
---
Paths and Their Roles(パス(フォルダやファイルの場所)とその役割)
- /usr/lib/systemd/
- This directory stores default unit files provided by installed packages (e.g., nginx.service, sshd.socket). These files are managed by the system and should not be modified directly. For example, the sshd.service unit here defines how the SSH daemon starts, including dependencies and environment variables
- /etc/systemd/
- Administrators place custom unit files and overrides here. When you modify a service (e.g., adding Restart=always to ensure a service auto-recovery), create a subdirectory like /etc/systemd/system/nginx.service.d/override.conf. These configurations take precedence over /usr/lib/systemd/, allowing tailored behavior without altering package defaults.
- /run/systemd/
- Runtime configurations reside here, generated dynamically during system operation. For instance, temporary service states or transient units (e.g., systemd-tmpfiles-clean.service) are stored here and cleared on reboot. This directory reflects the current system state, unlike /etc/ or /usr/lib/, which persist across reboots.
---
- /usr/lib/systemd/
- ここには、Linuxにインストールしたソフト(例:nginxやsshなど)が「どうやって起動するか」の説明書(ユニットファイル)が自動で置かれます。この中のファイルは直接編集しません。たとえば、sshサービスは「sshd.service」ファイルで「どうやって起動するか」「他の何が必要か」などが決められています。
- /etc/systemd/
- 管理者(ユーザー)が「自分で設定を変えたい!」と思った時に使う場所です。たとえば「もしnginxが止まっても自動で再起動してほしい」という設定を追加したい場合、/etc/systemd/system/nginx.service.d/override.conf というファイルを作って中に Restart=always と書きます。この設定が一番優先されます。ここで設定を変更すれば、元の設定(/usr/lib/systemd/)は壊さずに済みます。
- /run/systemd/
- パソコンが動いている間に自動で作られる「一時的な設定や状態」が入っています。たとえば「今だけ動かしているサービス」や「一時的に作ったユニットファイル」などです。再起動すると、この中身は消えます。/etc/ や /usr/lib/ は再起動しても残りますが、ここは「今だけの状態」を保存する場所です。
まとめ
- /usr/lib/systemd/:ソフトが作った「元の説明書」がある
- /etc/systemd/:自分で「説明書の書き足し」をする場所(ここが一番優先)
- /run/systemd/:今だけの「一時的な説明書や状態」が入る(再起動で消える)
---
systemctl Commands(systemctlコマンド)
- systemctl status [unit]: Displays the current state of a service, including active/inactive status, recent logs, and dependencies. For example, systemctl status apache2 reveals if the web server is running, its uptime, and error messages.
- systemctl list-units: Lists all loaded units (services, mounts, devices). Adding --type=service --state=failed filters to show only failed services, aiding quick diagnostics.
- systemctl start/stop [unit]: Directly controls service execution. For instance, systemctl stop mysql halts the database, while systemctl start nginx activates the web server.
- systemctl enable/disable [unit]: Configures autostart behavior. enable creates symlinks in /etc/systemd/system/[target].wants/, ensuring the service starts at boot. Conversely, disable removes these links.
- systemctl mask/unmask [unit]: Prevents accidental activation. Masking (e.g., systemctl mask bluetooth) links the service to /dev/null, blocking all start attempts. Unmasking restores the original configuration.
---
- systemctl status [unit](サービスの状態確認)
「systemctl status サービス名」と入力すると、そのサービスが今動いているか、止まっているか、直近のログやエラーメッセージ、他の何が必要か、などが画面に表示されます。
たとえば「systemctl status apache2」と打つと、Webサーバー(apache2)が今どうなっているかすぐに分かります。
- systemctl list-units(サービスの一覧表示)
「systemctl list-units」と入力すると、今パソコンで動いているすべてのサービスやマウント、デバイスなどが一覧で表示されます。
オプションをつけて「systemctl list-units --type=service --state=failed」とすれば、動かなくなったサービスだけをピックアップして確認できます。
トラブルのときにとても便利です。
- systemctl start/stop [unit](サービスの起動・停止)
「systemctl start サービス名」でサービスをすぐに起動できます。
「systemctl stop サービス名」でサービスをすぐに止められます。
たとえば「systemctl stop mysql」でデータベースを止め、「systemctl start nginx」でWebサーバーを動かせます。
- systemctl enable/disable [unit](自動起動の設定)
「systemctl enable サービス名」とすると、パソコンの電源を入れたときに自動でそのサービスが動くようになります。
「systemctl disable サービス名」とすると、自動起動をやめます。
自動で動かしたいサービスや、いらないサービスを簡単に設定できます。
- systemctl mask/unmask [unit](サービスのブロック・解除)
「systemctl mask サービス名」とすると、そのサービスが絶対に起動しなくなります(誤って動いてほしくないときなどに便利です)。
「systemctl unmask サービス名」とすると、ブロックを解除して元に戻せます。
たとえば「systemctl mask bluetooth」でBluetoothサービスを完全に止められます。
---
systemd-delta: Managing Configuration Overrides(systemd-delta:設定の上書き管理)
This tool identifies conflicts between unit file layers (e.g., /usr/lib/ vs. /etc/). Running systemd-delta highlights modified files, showing where administrators have overridden defaults. For example, if you’ve customized nginx.service in /etc/, it flags this as an "overridden" unit, ensuring transparency in configuration management.
Workflow Example: Customizing a Service To increase the file handle limit for Nginx:
- Create an override:
sudo mkdir -p /etc/systemd/system/nginx.service.d/ echo -e '[Service]\nLimitNOFILE=65536' | sudo tee /etc/systemd/system/nginx.service.d/override.conf
- Reload systemd:
sudo systemctl daemon-reload
- Restart Nginx:
sudo systemctl restart nginx
This ensures Nginx can handle more concurrent connections without altering the original package file in /usr/lib/systemd/.
---
systemd-delta(システィムディー・デルタ)とは
このツールを使うと、「設定ファイルがどこでどう変わっているか」がすぐ分かります。 たとえば、/usr/lib/ にある「元の説明書(設定ファイル)」と、自分で /etc/ に作った「自分用の説明書」が違う場合、どこがどう違うか教えてくれます。 管理者が「自分で上書きした設定」があると、「ここが変更されています」と表示されます。
例:Nginxのファイルハンドル上限を増やす手順
- 自分用の設定ファイルを作る
bash sudo mkdir -p /etc/systemd/system/nginx.service.d/ echo -e '[Service]\nLimitNOFILE=65536' | sudo tee /etc/systemd/system/nginx.service.d/override.conf
これでNginxが一度にたくさんの接続を受けられるようになります。
- systemdに設定を読み込ませる
bash sudo systemctl daemon-reload
新しい設定をパソコンに反映させます。
- Nginxを再起動する
bash sudo systemctl restart nginx
設定が有効になります。
ポイント
- /usr/lib/ の元の設定ファイルはそのまま
- /etc/ に自分用の設定を書くだけ
- systemd-delta で「どこが変わったか」すぐ分かる
---
Rescue and Emergency Modes(レスキューモードと緊急モード)
- Rescue Mode: Boots to a minimal root shell with critical services. Use systemctl rescue or append systemd.unit=rescue.target to the kernel command line. Ideal for fixing broken packages or misconfigured network settings[^prev^].
- Emergency Mode: Provides a bare-bones environment without mounting most filesystems. Trigger via systemctl emergency or systemd.unit=emergency.target. Required for repairing corrupted /etc/fstab or root filesystem errors[^prev^].
---
レスキューモード(Rescue Mode)
パソコンが最低限動く状態で起動します。
必要なサービスだけが動いていて、問題を直すのに使います。
使い方:
systemctl rescue と入力するか、
起動時に「systemd.unit=rescue.target」と指定します。
たとえば、壊れたソフトやネットワークの設定ミスを直すときに便利です。
緊急モード(Emergency Mode)
ほとんど何も動かさず、すごくシンプルな状態で起動します。
ファイルの読み込みもほとんどしません。
使い方:
systemctl emergency と入力するか、
起動時に「systemd.unit=emergency.target」と指定します。
たとえば、パソコンの大事な設定ファイルやシステムが壊れたときに使います。
---
Integration with Journalctl(journalctlとの連携)
Systemd’s logging tool, journalctl, centralizes log collection. For example, journalctl -u nginx --since "1 hour ago" filters logs for Nginx in the past hour, while journalctl -b shows all boot-related messages.
---
journalctl(ジャーナルコントロール)とは
systemd(システィムディー)には「journalctl」というログを見るための便利なコマンドがあります。
このコマンドを使うと、パソコンの動きやエラーなどの「記録(ログ)」を、一つの場所でまとめて見ることができます。
使い方の例:
- Nginx(Webサーバー)のログを1時間分だけ見たいとき
journalctl -u nginx --since "1 hour ago" → 過去1時間のNginxに関するログだけ表示されます。
- パソコンの起動時のログを全部見たいとき
journalctl -b → パソコンが起動したときの記録が全部表示されます。
まとめ
- journalctlは、いろいろなログをまとめて見られる便利なコマンドです。
- 必要なログだけを絞り込んで見ることができます。
---
Linux Kernel Distribution Format(Linuxカーネルディストリビューション形式)
bzImage and xz Compression The bzImage (big zImage) is a compressed Linux kernel executable format used in x86 and x86-64 architectures. Despite its name, it does not use bzip2 compression. Instead, it employs gzip by default for compressing the kernel image, though modern systems may use xz (LZMA2 algorithm) for higher compression ratios. The bzImage structure splits the kernel into two parts:
- Setup Code: A small assembly stub (loaded below 1 MB in memory) responsible for decompressing the kernel and transitioning to protected mode.
- Compressed Kernel: The main kernel code compressed with gzip/xz, decompressed into high memory (above 1 GB on 64-bit systems).
The xz compression reduces kernel size significantly, improving boot times on systems with slow storage (e.g., embedded devices). For example, a 10 MB uncompressed kernel might shrink to 4 MB with xz, compared to 6 MB with gzip[^prev^]
Kernel Modules and Documentation(カーネルモジュールとドキュメント)
/usr/src/linux/
This directory traditionally contains kernel source code, including:
- Source Files: Core kernel code (e.g., kernel/sched.c for task scheduling).
- Header Files: Architecture-specific headers (e.g., arch/x86/include/asm/io.h for x86 I/O operations).
- Build System: Makefiles and Kconfig files for compiling modules or custom kernels.On modern distributions, this is often a symbolic link to /usr/src/linux-[version] (e.g., /usr/src/linux-5.15.0). Administrators use this to compile kernel modules or apply patches.
---
このディレクトリは、Linuxカーネルのソースコードが入っている場所です。ここには、カーネルを動かすための大事なプログラムや設定ファイルが入っています。
たとえば:
- ソースファイル
カーネルの中心的なプログラム(例:スケジューラのプログラム kernel/sched.c)
- ヘッダーファイル
パソコンの種類ごとの設定ファイル(例:x86用のI/O設定 arch/x86/include/asm/io.h)
- ビルドシステム
カーネルやモジュールをコンパイル(ビルド)するための Makefile や Kconfig ファイル
最近のLinuxでは、このディレクトリは実際のソースコードがある場所(例:/usr/src/linux-5.15.0)への「ショートカット(シンボリックリンク)」になっていることが多いです。
管理者はここを使って、新しいカーネルモジュールを作ったり、カーネルにパッチを当てたりします。
---
/usr/src/linux/Documentation/
A repository of kernel documentation, including:
- Process Guides: Files like process/howto.rst explain kernel development workflows.
- Driver Documentation: Instructions for device drivers (e.g., Documentation/networking/device_drivers/ethernet/intel/e1000e.rst).
- ABI Specifications: Stability guarantees for sysfs/procfs interfaces (e.g., Documentation/ABI/stable/sysfs-class-net).
- Security: Guidelines like Documentation/security/credentials.rst detail kernel security models.This directory is critical for developers debugging hardware interactions or implementing kernel features[^prev^].
---
このディレクトリは、カーネルに関するさまざまな説明やガイドを集めた場所です。カーネル開発やデバイスドライバの作成、カーネルの使い方を知りたいときに役立つ資料がたくさん入っています。たとえば:
- 開発の手順ガイド
カーネル開発の進め方やルールについて書かれたファイル(例:process/howto.rst)があります。
- デバイスドライバの説明
特定のデバイス(例:Intelのネットワークカードなど)のドライバを作る方法や注意点がまとめられています(例:Documentation/networking/device_drivers/ethernet/intel/e1000e.rst)。
- インターフェースの仕様
カーネルが外部とやりとりするためのルール(sysfs/procfsなど)の安定性や使い方が書かれています(例:Documentation/ABI/stable/sysfs-class-net)。
- セキュリティのガイドライン
カーネルのセキュリティを守るための注意点や仕組みについての説明もあります(例:Documentation/security/credentials.rst)。
このディレクトリは、カーネル開発者やハードウェアの動作確認をする人にとって、とても大切な情報源です。
---
Kernel Module Management(カーネルモジュール管理)
Kernel modules are dynamically loaded components that extend kernel functionality (e.g., device drivers, filesystems). Key concepts include:
- Compilation: Modules are built using the kernel’s build system. A trivial module hello-1.ko might include:
#include <linux/module.h> MODULE_LICENSE("GPL"); static int __init hello_init(void) { printk("Hello, kernel\n"); return 0; } module_init(hello_init);
Compilation requires a Makefile referencing the kernel’s build directory:
obj-m += hello-1.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
- Loading: Use insmod hello-1.ko or modprobe hello-1 (which resolves dependencies).
- Inspection: modinfo hello-1 displays module metadata (license, version), while lsmod lists loaded modules.
---
カーネルモジュールは、Linuxカーネルの「追加パーツ」のようなものです。たとえば、新しい周辺機器を使いたいときや、特別なファイルシステムを使いたいときに、このモジュールを追加します。
カーネルモジュールの基本的な流れ
1. 作る(コンパイル)
まず、モジュールのプログラム(ソースコード)を書きます。
たとえば、カーネルに「Hello, kernel」と表示させるだけの簡単なモジュールの場合、こんなふうに書きます:
c #include <linux/module.h> MODULE_LICENSE("GPL"); static int __init hello_init(void) { printk("Hello, kernel\n"); return 0; } module_init(hello_init);
そして、Makefile(モジュールを作るためのレシピ)も用意します:
text obj-m += hello-1.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
このMakefileを使って、モジュール(hello-1.ko)を作ります。
2. カーネルに追加する(ロード)
作ったモジュール(hello-1.ko)を、次のコマンドでカーネルに追加できます。
bash insmod hello-1.ko
または、依存関係も自動で解決してくれるコマンドもあります。
bash modprobe hello-1
3. 確認する
モジュールが追加されたかどうかや、どんな情報を持っているかは、次のコマンドで調べられます。
モジュール情報を表示
bash modinfo hello-1
このコマンドで、ライセンスやバージョンなどの情報が見られます。
現在読み込まれているモジュール一覧
bash lsmod
このコマンドで、今カーネルに追加されているモジュールの一覧が表示されます。
このように、カーネルモジュールは「必要なときに追加して、カーネルの機能を広げる」ための便利な仕組みです。
---
Versioning and Distribution(バージョン管理と配布)
- Kernel Versioning: Follows x.y.z format (e.g., 5.15.0), where x is the major version, y the minor, and z the patch. Stable releases receive incremental patches (e.g., 5.15.1), while -rc suffixes denote release candidates (e.g., 5.16-rc3).
- Distributions: Ship customized kernels (e.g., Red Hat’s kernel-3.10.0-1160.el7.x86_64) with backported fixes and vendor-specific drivers. The uname -r command reveals the running kernel version.
---
- カーネルのバージョン管理
カーネルのバージョン番号は「x.y.z」という形式(例:5.15.0)で表されます。
x はメジャーバージョン(大きな機能変更) y はマイナーバージョン(小さな機能追加や修正) z はパッチバージョン(バグ修正など)
安定版(Stable)リリースでは、パッチバージョンが増えていきます(例:5.15.1)。
また、「-rc」が付くもの(例:5.16-rc3)はリリース候補版(テスト版)です。
- ディストリビューション(配布版)
各Linuxディストリビューション(例:Red Hat)は、独自の修正やバックポートされた修正、ベンダー固有のドライバを加えたカスタムカーネルを提供します(例:kernel-3.10.0-1160.el7.x86_64)。
現在使っているカーネルのバージョンは、uname -r コマンドで確認できます
---
Practical Workflow Example(実践的なワークフローの例)
- Extract Kernel Sources:
tar xvf linux-5.15.0.tar.xz -C /usr/src/
- Configure:
cd /usr/src/linux-5.15.0 make menuconfig # Enable/disable kernel features via TUI
- Compile:
make -j$(nproc) # Build kernel and modules make modules_install # Install modules to /lib/modules/5.15.0/
- Install:
cp arch/x86/boot/bzImage /boot/vmlinuz-5.15.0 update-grub # Update bootloader entries
This structure ensures modularity, enabling efficient updates and hardware support across diverse systems
---
1. カーネルソースの展開
まず、Linuxカーネルのソースファイルを解凍します。
bash tar xvf linux-5.15.0.tar.xz -C /usr/src/
意味:linux-5.15.0.tar.xz という圧縮ファイルを /usr/src/ フォルダに展開します。
2. カーネルの設定
展開したフォルダに移動して、カーネルの設定を行います。
bash cd /usr/src/linux-5.15.0 make menuconfig
意味:menuconfig という画面で、必要な機能を有効・無効に設定します。マウスや矢印キーで操作できます。
3. カーネルのコンパイル
設定が終わったら、カーネルをビルド(コンパイル)します。
bash make -j$(nproc) make modules_install
意味:
make -j$(nproc):パソコンのCPUのコア数を利用して、できるだけ速くカーネルをビルドします。
make modules_install:必要なモジュール(ドライバなど)を /lib/modules/5.15.0/ にインストールします。
4. カーネルのインストール
最後に、カーネルをシステムにインストールします。
bash cp arch/x86/boot/bzImage /boot/vmlinuz-5.15.0 update-grub
意味:
cp arch/x86/boot/bzImage /boot/vmlinuz-5.15.0:ビルドしたカーネルを /boot にコピーします。
update-grub:ブートローダー(起動時にOSを選ぶ画面)を更新します。
まとめ
この手順で、カーネルを自分でカスタマイズしてアップデートできます。モジュール化されているので、必要な機能だけを追加・削除でき、いろいろなパソコンに対応できます。
---
Compiling the Linux Kernel: Core Components and Workflow(Linuxカーネルのコンパイル:主要な構成要素と作業手順)
/usr/src/linux/ Directory Structure(/usr/src/linux/ ディレクトリ構造)
The /usr/src/linux/ directory typically contains the kernel source code, configuration files, and build artifacts. The .config file within this directory stores the kernel’s build configuration, including enabled features, drivers, and hardware support. This file is generated during the configuration phase (e.g., via make menuconfig) and defines compilation parameters such as processor architecture, filesystem support, and security settings.
---
/usr/src/linux/ ディレクトリには、Linuxカーネルの「ソースコード(プログラムの元になるファイル)」や「設定ファイル」、「ビルド作業でできたファイル」などが入っています。
このディレクトリの中にある .config というファイルは、カーネルをビルド(組み立て)するときの「設定内容」を記録しています。たとえば「どんな機能を使うか」「どんなドライバを組み込むか」「どんなハードウェアに対応するか」といった細かな設定が書かれています。
この .config ファイルは、make menuconfig などのコマンドでカーネルの設定を決めたときに自動的に作られます。ここに書かれた設定に従って、カーネルのコンパイル(変換)や組み込みが進みます。たとえば「CPUの種類」「使うファイルシステム」「セキュリティ設定」などもここで決まります。
---
Kernel Makefile and Targets(カーネルの Makefile とターゲット)
The Kernel Makefile orchestrates the compilation process. Key targets include:
- all: Compiles the kernel (vmlinux) and modules (*.ko).
- config/menuconfig/xconfig: Configure kernel options via text/TUI/GUI interfaces.
- oldconfig: Updates an existing .config file to include new options while retaining user choices.
- mrproper: Cleans the source tree, including .config and generated files.
- bzImage: Generates a compressed kernel image for x86/x86_64 systems.
- modules/modules_install: Builds and installs loadable modules to /lib/modules/<version>/.
- rpm-pkg/deb-pkg: Creates distribution-specific packages for easy deployment.
---
- all:カーネルの本体と追加機能(モジュール)をまとめてコンパイルします。
- config/menuconfig/xconfig:テキスト画面やTUI(メニュー式画面)、GUI(マウスで操作する画面)を使って、カーネルの設定を変更できます。
- oldconfig:今までの設定はそのままに、新しいカーネルの設定項目だけを追加・更新して.configファイルを最新にします。
- mrproper:コンパイル作業でできた一時ファイルや設定ファイルなど、不要なファイルを全部きれいに消します。
- bzImage:x86やx86_64パソコン用のカーネル本体(圧縮されたイメージファイル)を作ります。
- modules/modules_install:必要な追加機能(モジュール)をコンパイルして、/lib/modules/<バージョン>/ にインストールします。
- rpm-pkg/deb-pkg:RPMやdebといったパッケージを作って、他のパソコンに簡単にインストールできるようにします。
---
Customizing Kernel Configuration(カーネル設定のカスタマイズ)
To modify the kernel configuration:
- Copy the Current Config:
cp /boot/config-$(uname -r) /usr/src/linux/.config
- Launch Configuration Tools:
- make menuconfig for an ncurses-based interface.
- make xconfig for a Qt GUI (requires qt5-devel).
- Adjust Settings:Enable/disable features like CONFIG_DEBUG_KERNEL for debugging or CONFIG_NET_VENDOR_INTEL for Intel NIC drivers.
---
カーネルの設定を変更する手順
1. 今の設定ファイルをコピーする
今使っているカーネルの設定を新しいカーネルでも使えるようにコピーします。
bash cp /boot/config-$(uname -r) /usr/src/linux/.config
2. 設定ツールを開く
- make menuconfig
→ ターミナルで動く、メニュー形式の設定画面が開きます。
- make xconfig
→ マウス操作ができるグラフィカルな設定画面が開きます(Qtの開発パッケージが必要です)。
3. 必要な設定を変更する
例えば「カーネルデバッグ機能」や「Intelのネットワークドライバ」など、必要なものを有効にしたり、不要なものを無効にしたりできます。
この手順で、カーネルの設定を自分の使いやすいようにカスタマイズできます。
---
Building the Kernel and Modules(カーネルとモジュールのビルド)
- Compile the Kernel:
make -j$(nproc) # Parallel build using all CPU cores
This generates vmlinux (uncompressed kernel) and arch/x86/boot/bzImage (bootable image).
- Build Modules:
make modules # Compiles loadable modules (*.ko files)
---
- カーネルのコンパイル
bash make -j$(nproc) #パソコンのすべてのCPUコアを使って、カーネル本体を効率よくコンパイルします
→ パソコンのCPUが持っている全てのコア(頭脳の数)を使って、同時にたくさんの作業を進めます。これにより、ビルド(プログラムの組み立て作業)がとても速く終わります。
このように、CPUの力をフルに活用して効率よく作業を進めることができます。
これで、カーネル本体(vmlinux)と、起動できる圧縮されたカーネルイメージ(arch/x86/boot/bzImage)が作られます。
- モジュールのコンパイル
bash make modules #追加の機能やドライバ(モジュール、*.koファイル)をコンパイルします
→ カーネル本体とは別に、必要なときに追加できるドライバや機能(モジュール、*.koファイル)をコンパイルします。
このコマンドを使うことで、たとえば新しいハードウェアのドライバや特別な機能を、いつでもカーネルに追加できるように準備できます。
---
Installing the Kernel and Modules(カーネルとモジュールのインストール)
- Install Modules:
sudo make modules_install # Copies modules to /lib/modules/<version>/
- Install Kernel:
sudo make install # Copies bzImage to /boot/vmlinuz-<version> and updates GRUB
- Update Module Dependencies:
sudo depmod -a # Generates /lib/modules/<version>/modules.dep[^prev^]
---
- モジュールをインストール
sudo make modules_install #モジュールを /lib/modules/<バージョン>/ にコピーします
→ コンパイルしたモジュール(追加機能やドライバ)を、カーネルが使える場所「/lib/modules/<バージョン>/」に設置します。
- カーネルをインストール
sudo make install #bzImage を /boot/vmlinuz-<バージョン> にコピーし、GRUB を更新します
→ コンパイルしてできたカーネルイメージ(bzImage)を、/boot ディレクトリ内に「vmlinuz-<バージョン>」という名前でコピーします。
→ その後、ブートローダー(GRUB)の設定を最新にして、新しいカーネルで起動できるようにします
- モジュールの依存関係を更新する
「モジュールの依存関係を更新する」とは、追加機能やドライバ(モジュール)が正しく動くように、必要な情報や設定を最新の状態に整える作業のこと。
sudo depmod -a #/lib/modules/<バージョン>/modules.dep を生成します
→ カーネルモジュールの依存関係(どのモジュールがどのモジュールを必要としているか)をまとめた「modules.dep」というファイルを、/lib/modules/<バージョン>/ ディレクトリに作成します。
---
Bootloader Configuration(ブートローダーの設定)
After installation, update the bootloader to recognize the new kernel:
- GRUB (most distributions):
sudo grub2-mkconfig -o /boot/grub2/grub.cfg
- systemd-boot (UEFI systems):
Add a new entry in /boot/efi/loader/entries/ referencing the kernel and initrd[^prev^].
---
インストールが終わったら、新しいカーネルを起動できるようにブートローダーを更新しましょう
- GRUBを使っている場合(多くのLinuxで使われています):
bash sudo grub2-mkconfig -o /boot/grub2/grub.cfg
このコマンドを実行すると、ブートローダーが新しいカーネルを自動で認識し、起動メニューに追加します。
- systemd-bootを使っている場合(UEFI対応のパソコンで使われています):
/boot/efi/loader/entries/ ディレクトリに、新しいカーネル(vmlinuz)とinitrd(初期RAMディスク)を指定する設定ファイルを追加します。
---
Module Configuration Files(モジュールの設定ファイル)
Module behavior is defined in:
- /etc/modprobe.d/: Contains override files (e.g., blacklist.conf to block problematic modules).
- /etc/modules-load.d/: Lists modules to load at boot (e.g., vfio.conf for virtualization)[^prev^].
---
モジュールの動作設定について:
- /etc/modprobe.d/
ここにある設定ファイル(例:blacklist.conf)で、カーネルモジュールの動作を細かく調整できます。たとえば「このモジュールは使わない」と指定したり、モジュールにオプションを渡したりできます。
- /etc/modules-load.d/
ここにファイルを作ってモジュール名を書くと、起動時に自動的にそのモジュールが読み込まれます。
---
DKMS for Kernel Modules(カーネルモジュールのためのDKMS)
Dynamic Kernel Module Support (DKMS) automates module rebuilding for new kernels:
- Add a Module:
sudo dkms add -m nvidia -v 470.141.03
- Build and Install:
sudo dkms build -m nvidia -v 470.141.03 sudo dkms install -m nvidia -v 470.141.03[7]
- Verify Status:
dkms status # Shows installed modules and kernel compatibility[7]
---
DKMS(Dynamic Kernel Module Support)は、Linuxで使われる「カーネルモジュール(主にサードパーティのドライバなど)」を、カーネルが新しくなったときやアップデートされたときに、自動的に再ビルド(作り直し)してくれる仕組みです。
- モジュールを追加
sudo dkms add -m nvidia -v 470.141.03
- 構築とインストール
sudo dkms build -m nvidia -v 470.141.03 sudo dkms install -m nvidia -v 470.141.03[7]
- 状態を確認する
dkms status #インストール済みのモジュールとカーネルの互換性を表示します
---
Initrd Configuration
Initial RAM Disk (initrd) loads critical modules before the root filesystem mounts:
- Generate with Dracut:
sudo dracut --force /boot/initramfs-<version>.img <version>
- Generate with mkinitramfs:
sudo mkinitramfs -o /boot/initrd.img-<version> <version>
- Troubleshoot: Use lsinitrd /boot/initramfs-<version>.img to verify included drivers[^prev^].
Version-Specific Considerations
- Kernel 2.6.x: Uses make oldconfig for backward compatibility.
- Kernel 5.x: Supports make menuconfig with modern features like CONFIG_KASAN for memory sanitization.
- Compression: Use CONFIG_KERNEL_XZ for xz compression (smaller size) or CONFIG_KERNEL_GZIP for faster decompression[^prev^].
Workflow Example
- Download and Extract:
wget https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.0.7.tar.xz tar xvf linux-6.0.7.tar.xz -C /usr/src/
- Configure:
cd /usr/src/linux-6.0.7 make menuconfig
- Compile and Install:
make -j$(nproc) && sudo make modules_install && sudo make install
- Update Bootloader:
sudo grub2-mkconfig -o /boot/grub2/grub.cfg
Management and troubleshooting during kernel execution
To obtain details about the currently running Linux kernel and its modules, several command-line utilities are available. The uname command is the most direct way to check the kernel version. Executing uname -r outputs the kernel release, while uname -a provides additional information such as the kernel name, version, and machine architecture. Another method is to inspect /proc/version, which contains the kernel build details. The /lib/modules/$(uname -r)/modules.dep file lists module dependencies for the current kernel version
For kernel modules, utilities like depmod and modinfo are essential. depmod generates a list of module dependencies, which is crucial for module management. modinfo displays information about a specific kernel module, including its parameters, author, and description.
Loading and Unloading Kernel Modules
Kernel modules can be managed manually using several utilities. insmod inserts a module into the kernel, but it does not resolve dependencies. modprobe is more advanced, as it automatically loads any dependencies required by the module. To view all loaded modules, lsmod lists them along with their sizes and usage counts. If you need to remove a module, rmmod unloads it from the kernel. modprobe -r can also be used to remove modules, handling dependencies as necessary.
Determining When a Module Can Be Unloaded
A kernel module can be unloaded only if it is not in use by any processes or other modules. The lsmod command displays a usage count for each loaded module. If the usage count is zero, the module can typically be unloaded safely. Attempting to remove a module with active dependencies or usage will result in an error, preventing potential system instability.
Determining Module Parameters
Modules often accept parameters at load time, which can be viewed using the modinfo command. This utility lists all parameters a module can receive. Additionally, configuration files in /etc/modprobe.d/ can be used to set persistent module parameters. These files allow administrators to specify options that are applied whenever a module is loaded.
Checking the Kernel Version
The kernel version is most commonly checked using the uname -r command, which prints the release number of the running kernel . More detailed information, including the build time and compiler version, is available with uname -a or by reading /proc/version. The /lib/modules/kernel-version/modules.dep file is also tied to the specific kernel version and contains information about module dependencies.
Loading Modules with Different Names
Linux allows the system to load modules using aliases or alternative names instead of the actual file names. This is configured in files under /etc/modprobe.d/, where alias directives can map a device or module name to a specific module file. This mechanism is useful for hardware abstraction and compatibility with different naming conventions.
The /proc File System
The /proc file system provides a virtual interface to kernel data structures. The /proc/sys/kernel/ directory contains tunable kernel parameters. These parameters can be modified at runtime using the sysctl utility or by editing /etc/sysctl.conf and files in /etc/sysctl.d/. Changes can be applied immediately with /sbin/sysctl.
Configuring initrd
The initial RAM disk (initrd) is a temporary root file system loaded into memory during the boot process. Tools such as dracut, mkinitrd, and mkinitramfs are used to generate or update the initrd image. This image contains necessary drivers and modules required for booting, especially on systems with complex storage configurations.
The /sys File System (sysfs)
The /sys file system, or sysfs, is a virtual file system that exposes kernel objects, device information, and module data to user space. It is typically mounted at /sys and provides detailed information about devices, drivers, and kernel subsystems. Unlike /dev, which provides device nodes for direct access, /sys is primarily for viewing and managing device attributes and relationships.
Contents of /boot and /lib/modules
The /boot directory contains files required for the system to boot, such as the kernel image (vmlinuz), initial RAM disk images (initrd or initramfs), and bootloader configuration files. The /lib/modules/$(uname -r)/ directory stores all kernel modules for the current kernel version, along with dependency files and module configuration data.
Tools for Hardware Information
Several command-line tools are available to analyze hardware information. dmesg prints kernel ring buffer messages, which include hardware initialization logs. lspci lists PCI devices, lsusb shows USB devices, and lsdev displays information about system devices. journalctl can be used to view system logs, including kernel and hardware events.
udev Rules and Module Configuration
udev is the device manager for the Linux kernel, handling dynamic device node creation. Tools like udevmonitor and udevadm monitor allow real-time monitoring of device events. udev rules, stored in /etc/udev/, define how devices are named, what permissions they have, and which modules or scripts are triggered on device events. Module configuration files in /etc can specify options or aliases for modules, integrating with udev actions
Obtaining a Kernel Dump
To capture a kernel dump for debugging, utilities such as kdump and kexec are used. kdump sets up a crash kernel and captures memory dumps when a kernel panic occurs. kexec allows booting into a new kernel directly from the running system, which is often used in conjunction with kdump for crash analysis. These tools help diagnose critical kernel failures by preserving system state at the time of a crash.
Filesystem setup and mount
The /etc/fstab file, known as the file system table, is a critical configuration file in Linux systems. It defines how and where disk partitions, block devices, and remote file systems should be mounted, particularly during system boot. Each line in /etc/fstab represents a single file system and includes six fields: the device identifier (such as a device file, UUID, or label), the mount point, the file system type, mount options, a dump flag for backups, and the fsck order for file system checks at boot. Using UUIDs or PARTUUIDs to identify devices is recommended, as device names like /dev/sda1 can change between boots, leading to potential mounting errors
Mounting and Unmounting Filesystems
To manually mount a file system, the mount command is used. It attaches the specified device to a directory in the file system hierarchy, known as the mount point. For example, mount /dev/sdb1 /mnt/data mounts the device /dev/sdb1 at /mnt/data. To detach, the umount command is used, specifying either the device or the mount point. If a file system is busy, unmounting will fail unless the -l (lazy) or -f (force) options are used. The current mount status can be checked with /etc/mtab or /proc/mounts, which list all active mounts. On modern systems, systemd also manages mounts and can influence the mount order, which is important for ensuring that dependencies between file systems are respected during boot.
Managing Swap Partitions and Files
Swap space can be provided either by a dedicated partition or a swap file. The mkswap command is used to initialize a swap area on a device or file. To enable swap, the swapon command activates it, while swapoff deactivates it. Swap entries can also be defined in /etc/fstab to ensure they are automatically enabled at boot. Proper management of swap is crucial for system performance, especially on systems with limited RAM.
Using UUIDs to Identify and Mount Filesystems
UUIDs (Universally Unique Identifiers) provide a stable and unique way to identify storage devices and partitions. They are generated when a file system is created and are not affected by device name changes. Tools like blkid and lsblk can display UUIDs and other file system metadata. For example, blkid /dev/sda1 or lsblk -f will show the UUID, file system type, and label for the specified device. Using UUIDs in /etc/fstab ensures reliable mounting regardless of how the kernel assigns device names during boot.
The /etc/fstab file automates and standardizes the mounting of file systems and swap areas on Linux systems. Manual mounting and unmounting are performed with mount and umount, and the status of mounts can be checked with /etc/mtab and /proc/mounts. Swap management is handled with mkswap, swapon, and swapoff. To avoid issues with changing device names, UUIDs should be used to reference devices, which can be obtained with blkid and lsblk. This approach ensures a good and reliable storage configuration across reboots and hardware changes
Filesystem managment
This section will help explain what tools are available for filesystem management
Tools for Manipulating Filesystems mkfs and fsck
The mkfs (make filesystem) utility is used to create a new filesystem on a storage device or partition. It acts as a front-end to filesystem-specific commands such as mkfs.ext4, mkfs.xfs, or mkfs.vfat. For example, if you want to format a partition as ext4, you would run:
sudo mkfs.ext4 /dev/sdb1
This command erases all data on /dev/sdb1 and creates a fresh ext4 filesystem. Similarly, to create an XFS filesystem, you would use:
sudo mkfs.xfs /dev/sdb2
Once filesystems are in use, the fsck (filesystem check) tool helps maintain their integrity. fsck scans the filesystem for inconsistencies and can repair many types of corruption. The command automatically detects the filesystem type, but you can also use filesystem-specific versions like fsck.ext4 or fsck.xfs. For example, to check and repair an ext4 filesystem, you might run:
sudo fsck.ext4 -y /dev/sdb1
The -y flag automatically answers "yes" to any prompts, allowing the tool to fix issues without user intervention.
Tools for Operating ext4: tune2fs, dumpe2fs, dump, restore
For ext4 filesystems, several specialized tools exist for maintenance and management. The tune2fs command allows you to adjust filesystem parameters after creation. For instance, you can change the maximum mount count before a forced check is required:
sudo tune2fs -c 30 /dev/sdb1
This sets the maximum mount count to 30, meaning the filesystem will be checked after every 30 mounts.
To examine detailed information about an ext4 filesystem, dumpe2fs is invaluable. It prints out superblock details, block group information, and more. For example:
sudo dumpe2fs /dev/sdb1 | less
This command provides a scrollable view of the filesystem’s internal structure.
For backup and recovery, the dump and restore utilities are used. dump creates a backup archive of a filesystem, while restore can extract files or entire filesystems from that archive. A typical backup command might be:
sudo dump -0uf /backup/sdb1.dump /dev/sdb1
This performs a level-0 (full) backup of /dev/sdb1 to /backup/sdb1.dump. To restore from this backup, you would use:
cd /mnt/restorepoint sudo restore -rf /backup/sdb1.dump
cd /mnt/restorepoint sudo restore -rf /backup/sdb1.dump
This command restores the contents of the dump archive to the specified directory.
Tools for Manipulating XFS: xfs_info, xfs_check, xfs_repair, xfsdump, xfsrestore
XFS filesystems have their own suite of management tools. xfs_info displays detailed information about an XFS filesystem, such as its geometry and configuration. For example:
sudo xfs_info /mnt/data
If you suspect corruption, xfs_check (now deprecated in favor of xfs_repair) and xfs_repair are used to verify and fix filesystem problems. Always unmount the filesystem before running these tools. For example:
sudo umount /mnt/data sudo xfs_repair /dev/sdb2
For backup and restore, xfsdump and xfsrestore are used. xfsdump creates a backup of the filesystem, while xfsrestore restores it. For instance:
sudo xfsdump -l 0 -f /backup/xfs.dump /mnt/data sudo xfsrestore -f /backup/xfs.dump /mnt/restore
This sequence backs up the /mnt/data filesystem and restores it to /mnt/restore.
Tools to Manipulate Basic Btrfs: Subvolumes and Snapshots
Btrfs is a modern filesystem that supports advanced features like subvolumes and snapshots. Subvolumes are separate, mountable parts of the filesystem, while snapshots are read-only or read-write copies of subvolumes at a point in time. To create a subvolume, use:
sudo btrfs subvolume create /mnt/data/subvol1
To create a snapshot of this subvolume:
sudo btrfs subvolume snapshot /mnt/data/subvol1 /mnt/data/snapshots/subvol1_snap
These features are useful for backups, testing, and system rollbacks.
Convert and Manipulate ext4 Filesystems to Btrfs: btrfs, btrfs-convert
If you wish to convert an existing ext2, ext3, or ext4 filesystem to Btrfs without losing data, the btrfs-convert tool is available. It preserves the original data and allows you to roll back if needed. For example:
sudo btrfs-convert /dev/sdb1
After conversion, you can use the btrfs command suite to manage the filesystem, create subvolumes, take snapshots, and more.
Monitoring the Health of HDD and SSD: smartd, smartctl
SMART (Self-Monitoring, Analysis, and Reporting Technology) tools help you monitor and predict hardware failures in storage devices. The smartctl command provides detailed information about a disk’s health, including temperature, error logs, and test results. For example:
sudo smartctl -a /dev/sda
This outputs all available SMART data for the device. To run a long self-test:
sudo smartctl -t long /dev/sda
For continuous monitoring, the smartd daemon can be enabled. It regularly checks all configured drives and can send notifications if problems are detected. To enable it, edit /etc/smartd.conf as needed and start the service:
sudo systemctl enable --now smartd
This proactive monitoring helps you catch disk failures before they lead to data loss.