# FreeBSD 使用手冊

Revision: 49533

Redistribution and use in source (XML DocBook) and 'compiled' forms (XML, HTML, PDF, PostScript, RTF and so forth) with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code (XML DocBook) must retain the above copyright notice, this list of conditions and the following disclaimer as the first lines of this file unmodified.

2. Redistributions in compiled form (transformed to other DTDs, converted to PDF, PostScript, RTF and other formats) must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

### 重要:

THIS DOCUMENTATION IS PROVIDED BY THE FREEBSD DOCUMENTATION PROJECT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FREEBSD DOCUMENTATION PROJECT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

FreeBSD 是 FreeBSD 基金會的註冊商標。

3Com 和 HomeConnect 是 3Com Corporation 的註冊商標。

3ware 是 3ware Inc 的註冊商標。

ARM 是 ARM Limited. 的註冊商標。

Apple, AirPort, FireWire, iMac, iPhone, iPad, Mac, Macintosh, Mac OS, Quicktime 以及 TrueType 是 Apple Inc. 在美國以及其他國家的註冊商標。

Heidelberg, Helvetica, Palatino 以及 Times Roman 是 Heidelberger Druckmaschinen AG 在美國以及其他國家的商標或註冊商標。

IBM, AIX, OS/2, PowerPC, PS/2, S/390 以及 ThinkPad 是 International Business Machines Corporation 在美國和其他國家的商標。

IEEE, POSIX 以及 802 是 Institute of Electrical and Electronics Engineers, Inc. 在美國的註冊商標。

Intel, Celeron, Centrino, Core, EtherExpress, i386, i486, Itanium, Pentium 以及 Xeon 是 Intel Corporation 及其分支機構在美國和其他國家的商標或註冊商標。

Intuit 和 Quicken 是 Intuit Inc., 或其子公司在美國和其他國家的商標或註冊商標。

Linux 是 Linus Torvalds 的註冊商標。

LSI Logic, AcceleRAID, eXtremeRAID, MegaRAID 以及 Mylex 是 LSI Logic Corp 的商標或註冊商標。

Microsoft, IntelliMouse, MS-DOS, Outlook, Windows, Windows Media 以及 Windows NT 是 Microsoft Corporation 在美國和/或其他國家的商標或註冊商標。

Motif, OSF/1 以及 UNIX 是 The Open Group 在美國和其他國家的註冊商標； IT DialTone 和 The Open Group 是其商標。

Oracle 是 Oracle Corporation 的註冊商標。

RealNetworks, RealPlayer, 和 RealAudio 是 RealNetworks, Inc. 的註冊商標。

Red Hat, RPM, 是 Red Hat, Inc. 在美國和其他國家的註冊商標。

Sun, Sun Microsystems, Java, Java Virtual Machine, JDK, JRE, JSP, JVM, Netra, OpenJDK, Solaris, StarOffice, SunOS 以及 VirtualBox 是 Sun Microsystems, Inc. 在美國和其他國家的商標或註冊商標。

MATLAB 是 The MathWorks, Inc. 的註冊商標。

SpeedTouch 是 Thomson 的商標。

VMware 是 VMware, Inc. 的商標。

Mathematica 是 Wolfram Research, Inc 的註冊商標。

XFree86 是 The XFree86 Project, Inc 的商標。

Ogg Vorbis 以及 Xiph.Org 是 Xiph.Org 的商標。

FreeBSD 網站 可以找到這份文件的最新版本，舊版文件可從 http://docs.FreeBSD.org/doc/ 取得，也可以從 FreeBSD FTP 伺服器 或是眾多 鏡像網站 下載不同格式的資料。 如果比較偏好實體書面資料，那可以在 FreeBSD 商城 購買。 此外，您可在 搜尋頁面 中搜尋本文件或其他文件的資料。

[ 章節模式 / 完整模式 ]

2.1. FreeBSD 開機載入程式選單
2.2. FreeBSD 開機選項選單
2.3. 歡迎選單
2.4. 鍵盤對應表選擇
2.5. 選擇鍵盤選單
2.6. 改進後的鍵盤對應表選單
2.7. 設定主機名稱
2.8. 選擇要安裝的元件
2.9. 從網路安裝
2.10. 選擇鏡像站
2.11. FreeBSD 9.x 的磁碟分割選項
2.12. FreeBSD 10.x 或更新版本的磁碟分割選項
2.13. 自多個磁碟選擇
2.14. 選擇完整磁碟或分割區
2.15. 確認已建立的分割區
2.16. 手動建立分割區
2.17. 手動建立分割區
2.18. 手動建立分割區
2.19. ZFS 磁碟分割選單
2.20. ZFS 儲存池類型
2.21. 磁碟選擇
2.22. 無效的選擇
2.23. 分析磁碟
2.24. 磁碟加密密碼
2.25. 最後修改
2.26. 最後確認
2.27. 取得發行版檔案
2.28. 檢驗發行版檔案
2.29. 解開發行版檔案
2.30. 設定 root 密碼
2.31. 選擇網路介面卡
2.32. 掃描無線網路存取點
2.33. 選擇無線網路
2.34. WPA2 設定
2.35. 選擇 IPv4 網路
2.36. 選擇 IPv4 DHCP 設定
2.37. IPv4 靜態位置設定
2.38. 選擇 IPv6 網路
2.39. 選擇 IPv6 SLAAC 設定
2.40. IPv6 靜態位置設定
2.41. DNS 設定
2.42. 選擇本地或 UTC 時鐘
2.43. 選擇區域
2.44. 選擇城市
2.45. 選擇時區
2.46. 確認時區
2.47. 選擇要開啟的其他服務
2.48. 開啟當機資訊 (Crash Dump)
2.49. 新增使用者帳號
2.50. 輸入使用者資訊
2.51. 離開使用者與群組管理
2.52. 最後設定
2.53. 手動設定
2.54. 完成安裝
30.1. 使用 NFS Root Mount 進行 PXE 開機程序

2.1. 磁碟分割表格式
3.1. 管理使用者帳號的工具
3.2. UNIX® 權限
3.3. 磁碟裝置名稱
3.4. 常用環境變數
5.1. XDM 設定檔
7.1. 常見錯誤訊息
9.1. 輸出 PDL 格式
12.1. 載入程式內建指令
12.2. 開機時核心互動參數
13.1. 登入類別限制資源類型
16.1. 預設稽查事件類別
16.2. 稽查事件類別字首
22.1. 常用語言及城市代碼
22.2. 已定義供特定字元集使用的終端機類型
22.3. Port 套件集中可用的 Console
22.4. 可用的輸入法
25.1. RS-232C 信號名稱
25.2. DB-25 對 DB-25 Null-Modem 線
25.3. DB-9 對 DB-9 Null-Modem 線
25.4. DB-9 對 DB-25 Null-Modem 線
28.1. NIS 術語
28.2. 其他使用者
28.3. 其他系統
28.4. DNS 術語
29.1. 有用的 pfctl 選項
30.1. 常見路由表標記
30.2. 站台功能代號
30.3. 已保留的 IPv6 位址

2.1. 建立傳統分割的檔案系統分割區
3.1. 以超級使用者的身份安裝程式
3.2. 在 FreeBSD 新增使用者
3.3. rmuser 互動式帳號移除
3.4. 以超級使用者的身份使用 chpass
3.5. 以一般使用者的身份使用 chpass
3.6. 更改您的密碼
3.7. 以超級使用者的身份更改其他使用者的密碼
3.8. 使用 pw(8) 新增群組
3.9. 使用 pw(8) 加入使用者帳號到新的群組
3.10. 使用 pw(8) 加入新成員到群組
3.11. 使用 id(1) 來查看所屬群組
3.12. 磁碟、切割區及分區命名範例
3.13. 磁碟的概念模型
5.1. 在單檔中選擇 Intel® 影像驅動程式
5.3. 在單檔中選擇 VESA 影像驅動程式
5.4. 在單檔中選擇 scfb 影像驅動程式
5.5. 在單檔中設定螢幕解析度
5.6. 手動設定顯示器頻率
5.7. 設定鍵盤配置
5.8. 設定多個鍵盤配置
5.9. 開啟鍵盤離開 X 功能
5.10. 設定滑鼠按鍵數
11.1. 日誌伺服器設定範例
11.2. 建立交換檔於 FreeBSD 10.X 及以後版本
11.3. 建立交換檔於 FreeBSD 9.X 及先前版本
12.1. boot0 螢幕截圖
12.2. boot2 螢幕截圖
12.3. /etc/ttys 設定不安全的 Console
13.1. 建立供 SMTP 使用的安全通道
13.2. 安全存取 POP3 伺服器
13.3. 跳過防火牆
14.1. 在不信任的 Jail 做 mergemaster(8)
14.2. 在信任的 Jail 做 mergemaster(8)
14.3. 在 Jail 中執行 BIND
17.1. ssh 使用 dump
17.2. ssh 使用 dump 透過 RSH 設定
17.3. 使用 tar 備份目前目錄
17.4. 使用 tar 還原目前目錄
17.5. 使用 lscpio 來製作目前目錄的遞迴備份
17.6. 使用 pax 備份目前目錄
18.1. 在開機磁碟標記分割區標籤
25.1. 設定終端機項目
28.1. 重新庫入 inetd 設定檔
28.2. 使用 amd 掛載 Export
28.3. 使用 autofs(5) 掛載 Export
28.4. /etc/ntp.conf 範例
30.1. Cisco® 交換器上設定 LACP Aggregation
30.2. 容錯移轉模式
30.3. 乙太網路與無線介面間的容錯移轉模式

# 序

## 自第二版後的主要修訂 (2004)

• 章 11, 設定與調校 已針對新內容作更新，如：ACPI 電源管理、cron 以及其他更多的核心調校選項說明內容。

• 章 13, 安全性 增加了虛擬私人網路 (VPN)、檔案系統的存取控制 (ACL)，以及安全報告。

• 章 15, 強制存取控制 (MAC) 是此版本新增的章節。該章介紹：什麼是 MAC 機制？以及如何運用它來使您的 FreeBSD 系統更安全。

• 章 17, 儲存設備 新增了像是：USB 隨身碟、檔案系統快照 (Snapshot)、檔案系統配額 (Quota) 、檔案與網路為基礎的檔案系統、以及如何對硬碟分割區作加密等詳解。

• 章 26, PPP 增加了疑難排解的章節。

• 章 27, 電子郵件 新增有關如何使用其它的傳輸代理程式、SMTP 認證、UUCP、fetchmailprocmail 的運用以及其它進階主題。

• 章 28, 網路伺服器 是該版中全新的一章。這一章介紹了如何架設 Apache HTTP 伺服器ftpd 以及用於支援 Microsoft® Windows® 客戶端的 Samba。其中有些段落來自原先的 章 30, 進階網路設定

• 章 30, 進階網路設定 新增有關在 FreeBSD 中使用藍牙®裝置、設定無線網路以及使用非同步傳輸模式 (Asynchronous Transfer Mode, ATM) 網路的介紹。

• 增加詞彙表，用以說明全書中出現的術語。

• 重新美編書中所列的圖表。

## 自第一版後的主要修訂 (2001)

• 增加完整的目錄索引。

• 所有的 ASCII 圖表均改成圖檔格式的圖表。

• 每個章節均加入概述，以便快速的瀏覽該章節內容摘要、讀者所欲了解的部分。

• 內容架構重新組織成三大部分：入門系統管理 以及 附錄

• 章 3, FreeBSD 基礎 新增了程序、Daemon 以及信號 (Signal) 的介紹。

• 章 4, 安裝應用程式：套件與 Port 新增了介紹如何管理 Binary 套件的資訊。

• 章 5, X Window 系統 經過全面改寫，著重於在 XFree86™ 4.X 上的現代桌面技術，如： KDEGNOME

• 章 12, FreeBSD 開機程序 更新相關內容。

• 章 17, 儲存設備 分別以兩個章節 磁碟備份 來撰寫。我們認為這樣子會比單一章節來得容易瞭解。還有關於 RAID (包含硬體、軟體 RAID) 的段落也新增上去了。

• 章 25, 序列通訊 架構重新改寫，並更新至 FreeBSD 4.X/5.X 的內容。

• 章 26, PPP 有相當程度的更新。

• 章 30, 進階網路設定 加入許多新內容。

• 章 27, 電子郵件 大量新增了設定 sendmail 的介紹。

• 章 10, Linux® Binary 相容性 增加許多有關安裝 Oracle® 以及 SAP® R/3® 的介紹。

• 此外，第二版還新加章節，以介紹下列新主題：

## 本書的編排體裁

### 文字編排體裁

等寬字

等寬字用於： 錯誤訊息、指令、環境變數、Port 名稱、主機名稱、帳號、群組、裝置名稱、變數、程式碼等。

Ctrl+Alt+Del

Ctrl+X, Ctrl+S

### 範例

E:\> tools\fdimage floppies\kern.flp A:

# dd if=kern.flp of=/dev/fd0

% top

# 部 I. 入門

• 介紹 FreeBSD 給您。

• 在安裝過程給您指引。

• 教您 UNIX® 的基礎及原理。

• 展示給您看如何安裝豐富的 FreeBSD 的應用軟體。

• 向您介紹 X，UNIX® 的視窗系統以及詳細的桌面環境設定，讓您更有生產力。

## 章 1. 簡介

Restructured, reorganized, and parts rewritten by .

## 1.1. 概述

• FreeBSD 與其他作業系統之間的關係。

• FreeBSD 計劃的歷史。

• FreeBSD 計劃的目標。

• FreeBSD 開源開發模式的基礎概念。

• 當然囉，還有 FreeBSD 這名字的由來。

## 1.2. 歡迎使用 FreeBSD！

FreeBSD 是一個從 4.4BSD-Lite 衍生出而能在以 Intel (x86 與 Itanium®), AMD64, Sun UltraSPARC® 為基礎的電腦上執行的作業系統。同時，移植到其他平台的工作也在進行中。 對於本計劃歷史的介紹，請看 FreeBSD 歷史， 對於 FreeBSD 的最新版本介紹，請看 最新的發行版。 若打算對於 FreeBSD 計劃有所貢獻的話 (程式碼、硬體、經費)， 請看 如何對 FreeBSD 貢獻

### 1.2.1. FreeBSD 能做什麼？

FreeBSD 提供給你許多先進功能。這些功能包括：

• 動態優先權調整的 先佔式多工 能夠確保，即使在系統負擔很重的情況下，程式執行平順並且應用程式與使用者公平地共享資源。

• 多人共用 代表著許多人可以同時使用一個 FreeBSD 系統來處理各自的事務。 系統的硬體周邊 (如印表機及磁帶機) 也可以讓所有的使用者適當地分享。 也可以針對各別使用者或一群使用者的系統資源，予以設限，以保護系統不致被過度使用。

• 強大的 TCP/IP 網路 功能可支援許多業界標準，如：SCTP、DHCP、NFS、NIS、PPP、SLIP、IPSec、IPv6 的支援，也就是說 FreeBSD 可以容易地跟其他作業系統透過網路共同運作，或是當作企業的伺服器用途 ，例如提供遠端檔案共享 (NFS) 及電子郵件等服務， 或是讓您的企業連上網際網路並提供 WWW、FTP、路由及防火牆 (安全性) 等必備服務。

• 記憶體保護 能確保程式 (或使用者) 不會互相干擾，即使任何程式有不正常的運作，都不會影響其他程式的執行。

• 業界標準的 X Window 系統 (X11R7) 可以在常見的便宜 VGA 顯示卡/螢幕， 提供了圖形化的使用者介面 (GUI)，並且包括了完整的原始程式碼。

• Binary 相容性 可執行許多其他作業系統 (如： Linux、SCO、SVR4、BSDI 和 NetBSD) 的可執行檔。

• 數以萬計的 立即可以執行 的應用程式，這些都可透過 FreeBSD 的 Port套件 管理機制來取得。 不再需要費心到網路上到處搜尋所需要的軟體。

• 在網路上有數以千計 易於移植 的應用程式。FreeBSD 的原始程式碼與許多常見的商業版 UNIX® 系統都相容， 所以大部分的程式都只需要很少的修改 (或根本不用修改) ，就可以編譯執行。

• 依需要換頁的 虛擬記憶體合併式 VM/buffer 快取 設計，有效的滿足了需使用大量記憶體的程式，同時也能維持與其他使用者的互動。

• 支援 CPU 的對稱多工處理 (SMP)：可以支援多 CPU 的電腦系統。

• 完全相容的 CC++ 以及 Fortran 的環境和其他開發工具。 以及其他許多可供進階研發的程式語言也收集在 Port 和套件集。

• 整個系統都有 原始程式碼， 這讓你對作業環境擁有最完全的掌握度。 既然能擁有完全開放的系統，何苦被特定封閉軟體所約束，任廠商擺佈呢？

• 廣泛且豐富的 線上文件

• 當然囉，還不止如此！

FreeBSD 系統乃是基於美國加州大學柏克萊分校的電腦系統研究組 (Computer Systems Research Group 也就是 CSRG) 所發行的 4.4BSD-Lite，以及基於 BSD 系統開發的優良傳統。 除了由 CSRG 所提供的高品質的成果， 為了提供可處理真正具負荷的工作， FreeBSD 計劃也投入了數千小時以上的細部調整， 以能獲得最好的執行效率以及系統的穩定度。 正當許多商業上的巨人正努力地希望能提供效能及穩定時，FreeBSD 已經具備這樣的特質，並具有其他地方沒有的尖端功能。

FreeBSD 的運用範圍無限，其實完全限制在你的想像力上。 從軟體的開發到工廠自動化，或是人造衛星上面的天線的方位角度的遠端控制； 這些功能若可以用商用的 UNIX® 產品來達成， 那麼極有可能使用 FreeBSD 也能辦到！ FreeBSD 也受益於來自於全球各研究中心及大學所開發的數千個高品質的軟體 ，這些通常只需要花費很少的費用或根本就是免費的。 當然也有商業軟體，而且出現的數目是與日俱增。

• 網際網路服務： FreeBSD 內建強勁的網路功能使它成為網路服務 (如下例) 的理想平台：

• 全球資訊網伺服器 (標準的或更安全的 [SSL])

• IPv4 及 IPv6 路由

• 防火牆以及 NAT (IP 偽裝) 通訊閘。

• 檔案傳輸協定伺服器

• 電子郵件伺服器

• 還有更多...

• 教育：若您是資工相關領域的學生，再也沒有比使用 FreeBSD 能學到更多作業系統、計算機結構、及網路的方法了。 另外如果你想利用電腦來處理一些其他的工作，還有一些如 CAD、 數學運算以及圖形處理軟體等可以免費地取得使用。

• 研究：有了完整的原始程式碼，FreeBSD 是研究作業系統及電腦科學的極佳環境。 具有免費且自由取得特性的 FreeBSD 也使得一個分置兩地的合作計劃，不必擔心版權及系統開放性的問題， 而能自在的交流。

• 網路： 你如果需要 路由器、名稱伺服器 (DNS) 或安全的防火牆， FreeBSD 可以輕易的將你沒有用到的 386 或 486 PC 變身成為絕佳的伺服器，甚至具有過濾封包的功能。

• 嵌入式： FreeBSD 是一套可用來建立嵌入式系統的傑出平台。 支援 ARM®, MIPS® 以及 PowerPC® 平台，再加上健全的網路環境、尖端的功能以及自由的 BSD 授權條款，FreeBSD 成為用來建置嵌入式路由器、防火牆及其他裝置的絕佳基礎。

• 桌面: FreeBSD 同時也是低成本桌面解決方案中不錯的選擇，使用了免費的 X11 伺服器。FreeBSD 提供許多開源桌面環境可選擇，包含了標準 GNOMEKDE 圖型化使用者介面。FreeBSD 甚至可以透過中央伺服器做 無磁碟 開機，讓個人工作站變的更便宜、更易於管理。

• 軟體開發： 基本安裝的 FreeBSD 就包含了完整的程式開發工具，如 C/C++ 編譯器及除錯器。 透過 Port 與套件管理系統也可支援需多其他語言。

### 1.2.2. 誰在用 FreeBSD？

FreeBSD 先進的功能、成熟的安全性、可預測的發佈週期以及自由的授權條款，讓 FreeBSD 已經被用來做為建立許多商業、開源應用、裝置以及產品的平台，有許多世界上最大的資訊公司使用 FreeBSD：

• Apache - Apache 軟體基金會中大部分面對大眾的基礎設施，包括可能是世界上最大的 SVN 檔案庫 (擁有超過 140 萬次提交) 都是在 FreeBSD 上運作。

• Apple - OS X 大量借鑒 FreeBSD 的網路 Stack、虛擬檔案系統以及許多使用者空間的元件。Apple iOS 中含有從 FreeBSD 借鑒來的元素。

• Cisco - IronPort 網路安全及反垃圾郵件設備是採用改良後 FreeBSD 核心來運作。

• Citrix - 安全設備的 NetScaler 產品線提供的第 4-7 層的負載均衡、內容快取、應用層防火牆、安全的 VPN 以及行動雲端網路存取，皆運用了 FreeBSD Shell 強大的功能。

• Dell KACE - KACE 系統管理設備中運作了 FreeBSD，因為 FreeBSD 的可靠性、可擴展性以及支持其持續發展的社群。

• Experts Exchange - 所有面對大眾的 Web 伺服器皆由 FreeBSD 驅動，且他們大量使用 Jail 來隔離開發與測試環境，減少了虛擬化的額外開銷。

• Isilon - Isilon 的企業存儲設備以 FreeBSD 為基礎。非常自由的 FreeBSD 授權條款讓 Isilon 整合了它們的智慧財產到整個核心，並專注打造自己的產品，而不是一個作業系統。

• iXsystems - 統合存儲 (Unified Storage) 設備的 TrueNAS 產品線是以 FreeBSD 為基礎。除了該公司自己的商業產品外，iXsystems 也管理著 PC-BSD 和 FreeNAS 兩個開源計劃的開發。

• Juniper - JunOS 作業系統驅動了所有的 Juniper 網絡設備 (包括路由器，交換器，安全與網絡設備) 便是以 FreeBSD 為基礎。Juniper 在眾多廠商之中，展現了計劃與商業產品供應商之間的共生關係。由 Juniper 所開發的改進內容會回饋給 FreeBSD 來降低未來新功能從 FreeBSD 整合回 JunOS 的複雜性。

• McAfee - SecurOS 是 McAfee 企業防火牆產品的基礎，其中包含了 Sidewinder ，也是以 FreeBSD 為基礎。

• NetApp - 存儲設備中的 Data ONTAP GX 產品線是以 FreeBSD 為基礎。除此之外，NetApp 還貢獻了回 FreeBSD 許多功能，包括新 BSD 條款授權的 hypervisor, bhyve。

• Netflix - Netflix 用來以串流傳送電影到客戶的 OpenConnect 設備是以 FreeBSD 為基礎。 Netflix 也做了大量貢獻到程式碼庫，並致力於維持與主線 FreeBSD 的零修正關係。Netflix 的 OpenConnect 設備負責了北美所有的網路流量 32％ 以上。

• Sandvine - Sandvine 使用 FreeBSD 作為它們的高性能即時網路處理平台，來建立它們的智慧網路策略控制產品。

• Sony - PlayStation 4 遊戲主機使用了修改過的 FreeBSD 版本來運作。

• Sophos - Sophos 電子郵件設備產品是以加強防護 (Hardened) 的 FreeBSD 為基礎，可掃描入站郵件中的垃圾郵件和病毒，同時也可監控出站郵件中的惡意軟體及敏感資訊。

• Spectra Logic - 儲藏級儲存設備的 nTier 產品線以 FreeBSD 和 OpenZFS 來運作。

• The Weather Channel - 被安裝在各地有線電視營運商前端，負責加入當地天氣預報到有線電視網路節目的 IntelliStar 設備便是使用 FreeBSD。

• Verisign - VeriSign 主要經營 .com 與 .net 根網域名稱註冊業務以及隨附的 DNS 基礎設施運作。這些基礎設施的運作仰賴各種不同的網路作業系統包括 FreeBSD 來確保不會有單點故障的問題。

• Voxer - Voxer 使用了 FreeBSD 的 ZFS 來驅動行動語音通訊平台，讓 Voxer 從 Solaris 改使用 FreeBSD 的原因是 FreeBSD 擁有詳盡的文件、更大型且活躍的社群、較便利的開發人員環境。除了提供關鍵的 ZFS 和 DTrace 功能之外 FreeBSD 的 ZFS 也支援了 TRIM。

• WhatsApp - 當 WhatsApp 面臨需要一個每台伺服器能夠同時處理超過 100 萬個 TCP 連線的平台時，它們選擇了 FreeBSD。它們接著擴大規模到每台伺服器處理超過 250 萬的連線。

• Wheel Systems - FUDO 安全性設備讓企業可以監控、控制、記錄以及稽查在其系統中作業的承包商與管理員。這些功能皆是以 FreeBSD 最佳的安全性功能為基礎，包括 ZFS, GELI, Capsicum, HAST 及 auditdistd。

FreeBSD 也催生了數個相關的開源計劃：

• BSD Router - 以 FreeBSD 為基礎的大型企業路由器替代方案，專門設計為可在標準 PC 硬體上運作。

• FreeNAS - 專為網路檔案伺服器設備使用所設計的 FreeBSD。提供了以 Python 為基礎的網頁介面來簡化 UFS 與 ZFS 檔案系統的管理，支援了 NFS、SMB/ CIFS、AFP、FTP 與 iSCSI，還有以 FreeBSD Jail 為基礎的套件系統。

• GhostBSD - 採用 Gnome 桌面環境的 FreeBSD 發行版。

• mfsBSD - 用來建置可完全從記憶體執行 FreeBSD 系統映像檔工具。

• NAS4Free - 以 FreeBSD 及 PHP 驅動網頁介面為基礎的檔案伺服器。

• OPNSense - OPNsense 是一個以 FreeBSD 為基礎的開源、易於使用及易於建置的防火牆和路由平台。OPNsense 有大多數在昂貴的商業防火牆上才有的功能。它帶來了商業產品的豐富功能集，同時擁有開放和安全的來源。

• PC-BSD - 訂製版本的 FreeBSD，裝備了給桌面使用者使用的圖型化工具來展示 FreeBSD 強大的功能給所有使用者，專門設計來緩解使用者在 Windows 與 OS X 間的過渡。

• pfSense - 以 FreeBSD 為基礎的防火牆發行版，支援巨型陣列及大規模 IPv6。

• ZRouter - 嵌入式裝置韌體的開源替代方案，以 FreeBSD 為基礎，專門設計來取代現成路由器上的專用韌體。

FreeBSD 也同時被用來驅動一些網際網路上的大型網站，包括：

## 1.3. 關於 FreeBSD 計劃

### 1.3.1. FreeBSD 歷史簡介

FreeBSD 計畫起源於 1993 年初， 那是源自於維護一組『非官方 386BSD 修正工具』計劃的最後三個協調人 Nate Williams，Rod Grimes 和 Jordan Hubbard。

386BSD 是 Bill Jolitz 的作業系統，在當時就已經忍受了將近一年的忽視，隨著修正工具日漸龐大的令人不舒服，他們決定提供一份過渡性的 簡潔 快照來幫助 Bill。 然而，由於 Bill Jolitz 忽然決定取消其對該計劃的認可，且沒有明確指出未來的打算，所以該計劃便突然面臨中止。

FreeBSD 便開始了這宛如『重新發明輪子』的艱鉅工作 -- 從全新的且不完整的 4.4BSD-Lite 重新整合。 這個 Lite 版本是不完整的，因為 Berkeley 的 CSRG 已經刪除了大量在建立一個可以開機執行的系統所需要的程式碼 (基於若干法律上的要求)，且該版本在 Intel 平台的移植是非常不完整的。 直到 1994 年 11 月本計劃才完成了這個轉移， 同時在該年 12 月底以 CD-ROM 以及網路的形式發行了 FreeBSD 2.0。 雖然該份版本在當時有點匆促粗糙，但仍是富有意義的成功。 隨之於 1995 年 6 月又發行了更容易安裝，更好的 FreeBSD 2.0.5。

### 1.3.2. FreeBSD 計劃目標

Contributed by .

FreeBSD 計劃的目標在於提供可作任意用途的軟體而不附帶任何限制條文。 我們之中許多人對程式碼 (以及計畫本身) 都有非常大的投入， 因此，當然不介意偶爾有一些資金上的補償，但我們並沒打算堅決地要求得到這類資助。 我們認為我們的首要使命是為任何人提供程式碼， 不管他們打算用這些程式碼做什麼， 因為這樣程式碼將能夠被更廣泛地使用，從而發揮其價值。 我認為這是自由軟體最基本的，同時也是我們所倡導的一個目標。

### 1.3.3. FreeBSD 開發模式

Contributed by .

FreeBSD 的開發是一個非常開放且具彈性的過程，就像從 貢獻者名單 所看到的，是由全世界成千上萬的貢獻者發展起來的。 FreeBSD 的開發基礎架構允許數以百計的開發者透過網際網路協同工作。 我們也經常關注著那些對我們的計畫感興趣的新開發者和新的創意， 那些有興趣更進一步參與計劃的人只需要在 FreeBSD 技術討論郵遞論壇 連繫我們。 FreeBSD 公告郵遞論壇 對那些希望了解我們進度的人也是相當有用的。

SVN 檔案庫

FreeBSD 核心團隊

### 注意:

FreeBSD 貢獻者名單 相當長且不斷成長中， 只要有貢獻就會被列入其中， 要不要立即考慮貢獻 FreeBSD 一些回饋呢？

## 章 2. 安裝 FreeBSD

Restructured, reorganized, and parts rewritten by .
Updated for bsdinstall by and .
Updated for root-on-ZFS by .

## 2.1. 概述

### 注意:

• 最低的硬體需求和 FreeBSD 支援的架構。

• 如何建立 FreeBSD 的安裝媒體。

• 如何開始執行 bsdinstall

• bsdinstall 會詢問的問題，問題代表的意思，以及如何回答。

• 安裝失敗時如何做故障排除。

• 如何在正式安裝前使用 live 版本的 FreeBSD。

• 閱讀即將安裝的 FreeBSD 版本所附帶的硬體支援清單，並核對系統的硬體是否有支援。

## 2.2. 最低硬體需求

FreeBSD 安裝程序需要至少 96 MB 的 RAM 以及 1.5 GB 的硬碟空間。然而，如此少的記憶體及磁碟空間只適合在客製的應用上，如嵌入式設備。一般用途的桌面系統會需要更多的資源，2-4 GB RAM 與至少 8 GB 的硬碟空間是不錯的起點。

amd64

i386

FreeBSD 可在有支援實體位址延伸 (Physical Address Extensions, PAE) 功能的 CPU 上運用該功能所帶來的優點。有開啟 PAE 支援的核心會偵測超過 4 GB 的記憶體，並讓這些超過的記憶體能夠被系統使用。 但使用 PAE 會限制裝置驅動程式及 FreeBSD 的其他功能，詳情請見 pae(4)

ia64

pc98

NEC PC-9801/9821 系列幾乎所有 i386 相容處理器包括 80486、Pentium®、 Pentium® Pro 和 Pentium® II 都有支援。 所有 AMD, Cyrix, IBM, 及 IDT 的i386 相容處理器都有支援。 相容 NEC PC-9801 的 EPSON PC-386/486/586 系列都有支援。 NEC FC-9801/9821 及 NEC SV-98 系列也有支援。

powerpc

32 位元的核心只能使用前 2 GB 的 RAM

sparc64

FreeBSD/sparc64 支援的系統列在 FreeBSD/sparc64 計劃

## 2.3. 安裝前準備工作

1. 備份重要資料

安裝任何作業系統前， 總是 要先備份所有重要資料。 不要儲存備份在即將安裝的系統上，而是將資料儲存在可移除磁碟，像是 USB 隨身碟、網路上的另一個系統或是線上備份服務上。 開始安裝程序前要檢查備份，確定備份含有所有需要的檔案，一旦安裝程式格式化系統的磁碟，所有儲存在上面的資料都會遺失。

2. 決定 FreeBSD 安裝在哪裡

如果 FreeBSD 是唯一一套要安裝到電腦的作業系統，這個步驟可以略過。 但是假如 FreeBSD 要和其他作業系統共用磁碟空間的話，就要決定 FreeBSD 要安裝在哪個磁碟或是哪個分割區 (Partition)。

在 i386 和 amd64 架構，可將磁碟分割成多個分割區，可以選擇下列兩種分割表格式 (Partitioning scheme) 的其中一種達成。 傳統的主開機紀錄 (Master Boot Record, MBR) 的一個分割區表定義最多可有四個主分割區 (Primary partition)，因一些歷史淵源，FreeBSD 稱這些主分割區為 slice，其中一個主分割區可作為延伸分割區 (Extended partition)，延伸分割區又可分割成多個邏輯分割區 (Logical partition)。 GUID 分割區表 (GUID Partition Table, GPT) 是較新和較簡單的分割磁碟的方法，一般 GPT 實作允許每個磁碟多達 128 個分割區，不再需要使用邏輯分割區。

### 警告:

一些比較舊的作業系統，像是 Windows® XP 並不相容 GPT 分割表格式。 如果 FreeBSD 將和這類作業系統共用一個磁碟，則需要用 MBR 分割表格式。

FreeBSD 開機啟動程式需要主分割區或是 GPT 分割區。如果所有的主分割區或 GPT 分割區都已使用，必須釋放其中一個分割區讓 FreeBSD 使用。如果要建立一個分割區而不刪除原有的資料，可以使用磁碟重設大小的工具來縮小現有的分割區，並使用釋放出來的空間建立新分割區。

各種免費和付費的磁碟重設大小工具列於 http://en.wikipedia.org/wiki/List_of_disk_partitioning_softwareGParted Live (http://gparted.sourceforge.net/livecd.php) 是內含分割區編輯程式 GParted 的免費 Live CD。 GParted 同時也被許多 Linux Live CD 發行版所收錄。

### 警告:

在正確使用的情況下，磁碟重設大小的工具可以安全的建立讓新的分割區使用的空間。 但因仍有可能會誤選已經存在的分割區，所以在修改磁碟分割區前， 一定要備份重要資料，並確認備份的完整性。

在磁碟分割區中儲存不同的作業系統讓一台電腦可以安裝多個作業系統，另一種作法是使用虛擬化技術 (章 21, 虛擬化) ，可讓多個作業系統同時間執行而不需要改變任何磁碟分割區。

3. 收集網路資訊

部份 FreeBSD 安裝方式需要網路連線來下載安裝檔，因此之後的安裝程序，安裝程式進入設定系統網路的介面。

如果網路中有 DHCP 伺服器，則可透過該伺服器自動設定網路，若無法使用 DHCP，則需要從區域網路管理者或是網際網路服務供應商 (Internet Service Provider, ISP) 取得以的網路資訊供系統使用：

需要的網路資訊
1. IP 位址

2. 子網路遮罩

3. 預設閘道器 IP 位址

4. 網路的網域名稱

5. 網路 DNS 伺服器 IP 位址

4. 檢查 FreeBSD 勘誤表

儘管 FreeBSD Project 努力確保每個 FreeBSD 發行版能夠儘可能地穩定，錯誤偶爾還是會悄悄出現。 有極小的機會錯誤會影響安裝過程。 當這些問題被發現並修正後，會被紀錄在 FreeBSD 網站的 FreeBSD 勘誤表 (http://www.freebsd.org/releases/10.3R/errata.html)。 安裝前要檢查勘誤表，確保沒有會影響到安裝的問題。

所有發行版的資訊和勘誤表可以在 FreeBSD 網站的發行資訊找到 (http://www.freebsd.org/releases/index.html)。

### 2.3.1. 準備安裝的媒體

FreeBSD 安裝程式並不是一個可以在其他作業系統上執行的應用程式，反而您需要下載 FreeBSD 安裝檔，燒錄安裝檔到符合其檔案類型與大小的媒體 (CD, DVDUSB)，然後開機從插入的媒體來安裝。

FreeBSD 的安裝檔可於 www.freebsd.org/where.html#download 取得。安裝檔的名稱由 FreeBSD 發佈版本、架構、以及檔案類型所組成，舉例，要從 DVD 安裝 FreeBSD 10.2 到 amd64 的系統，需下載 FreeBSD-10.2-RELEASE-amd64-dvd1.iso，並燒錄這個檔案到 DVD，然後使用插入 DVD 來開機。

• -bootonly.iso：這是最精簡的安裝檔，檔案中只含安裝程式。 安裝時需要網際網路連線來下載所需的檔案以完成 FreeBSD 安裝。這個檔案應使用 CD 燒錄應用程式燒錄到 CD 使用。

• -disc1.iso：這個檔案含有所有安裝 FreeBSD 所需的檔案，包含原始碼及 Port 套件集。這個檔案應使用 CD 燒錄應用程式燒錄到 CD 使用。

• -dvd1.iso：這個檔案含有所有安裝 FreeBSD 所需的檔案，包含原始碼及 Port 套件集，也內含熱門的 Binary 套件可安裝視窗管理程式以及一些應用程式，如此便可從媒體安裝完整的系統，無須連線到網際網路。這個檔案應使用 DVD 燒錄應用程式燒錄到 DVD 使用。

• -memstick.img：這個檔案含有所有安裝 FreeBSD 所需的檔案，包含原始碼及 Port 套件集。這個檔案應依據以下操作指示寫入到 USB 隨身碟使用。

#### 2.3.1.1. 寫入映象檔到 USB

*.img 檔案是隨身碟的完整內容的映像檔 (image)，該檔案不能直接用檔案的方式複製到目標裝置。有許多應用程式可用來寫入 *.imgUSB 隨身碟，本節會介紹其中兩種。

### 警告:

• dd(1) 指令列工具在 BSD, Linux® 以及Mac OS® 系統皆可使用。要使用 dd 燒錄映像檔需先插入 USB 隨身碟，然後確認隨身碟的裝置名稱。然後指定已下載的安裝檔名稱以及 USB 隨身碟的裝置名稱。本例示範在已有的 FreeBSD 系統燒錄 amd64 安裝映像檔到第一個 USB 裝置。

# dd if=FreeBSD-10.2-RELEASE-amd64-memstick.img of=/dev/da0 bs=1M conv=sync

若這個指示執行失敗，請確認 USB 隨身碟是否未掛載，以及該裝置名稱是否為這個隨身碟，而非一個分割區。部份作業系統可能需要使用 sudo(8) 來執行這個指令。像 Linux® 這類的系統可能會暫存寫入動作，要強制完成所有寫入動作，可使用 sync(8)

### 警告:

1. 取得 Image Writer Windows® 版

Image Writer Windows® 版 是一個免費的應用程式，可以正確地將映像檔寫入隨身碟。 從 https://launchpad.net/win32-image-writer/ 下載，並解壓縮到一個資料夾。

2. 用 Image Writer 寫入映象檔

雙擊 Win32DiskImager 圖示啟動程式。 確認 Device 顯示的磁碟機代號是隨身碟的磁碟機代號。 按下資料夾圖示選擇要寫入隨身碟的映像檔。 按下 按鈕確定映像檔名。 確認所有東西都正確，隨身碟的資料夾並沒有在其他視窗開啟。 所有東西準備好後，按下 將映像檔寫入隨身碟。

## 2.4. 開始安裝

### 重要:

Your changes will now be written to disk.  If you
have chosen to overwrite existing data, it will
be PERMANENTLY ERASED. Are you sure you want to
commit your changes?

### 2.4.1. 在 i386™ 及 amd64 開機

1. 執行開機程序時安裝媒體插入主機的時間不夠早，請讓安裝媒體留在電腦中並重新啟動電腦。

2. 未正確修改 BIOS 或未儲檔，請再三檢查第一個開機裝置選擇了正確的裝置。

3. 系統太舊，無法支援使用選擇的開機媒體開機，發生這個情況可以使用 Plop Boot Manager (http://www.plop.at/en/bootmanagers.html) 來從選擇的開機媒體開機。

### 2.4.2. 在 PowerPC® 開機

boot cd:,\ppc\loader cd:0

### 2.4.3. 在 SPARC64® 開機

Sun Blade 100 (UltraSPARC-IIe), Keyboard Present
OpenBoot 4.2, 128 MB memory installed, Serial #51090132.
Ethernet address 0:3:ba:b:92:d4, Host ID: 830b92d4.

### 2.4.4. FreeBSD 開機選單

• 啟動多使用者模式 (Boot Multi User)：這個選項會繼續 FreeBSD 開機程序，若開機計時器已經暫停，可按 1、大寫或小寫 BEnter 鍵。

• 啟動單使用者模式 (Boot Single User)：這個模式用來修正已安裝的 FreeBSD，如 節 12.2.4.1, “單使用者模式” 所述。可按 2、大寫或小寫 S 進入這個模式。

• 離開到載入程式提示 (Escape to loader prompt)：這個選項會開機進入修復提示，這個模式含有有限數量的低階指令，這個模式詳細說明於 節 12.2.3, “階段三”。可按 3Esc 進入這個提示。

• 重新開機 (Reboot)：重新開啟系統。

• 設定開機選項 (Configure Boot Options)：開啟內部選單，詳細說明於 圖形 2.2, “FreeBSD 開機選項選單”

• ACPI 支援 (ACPI Support)：若系統在開機時卡住，可嘗試切換這個選項為關 (Off)。

• 安全模式 (Safe Mode)：若系統在 ACPI 支援 (ACPI Support) 設為關 (Off) 時開機時仍然會卡住，可嘗試將此選項設為開 (On)。

• 單使用者 (Single User)：切換這個選項為開 (On) 來修正已存在的 FreeBSD 如 節 12.2.4.1, “單使用者模式” 所述，問題修正後，將其設回關 (Off)。

• 詳細資訊 (Verbose)：切換這個選項為開 (On) 來查看開機程序中更詳細的訊息，這在診斷硬體問題時非常有用。

## 2.5. 使用 bsdinstall

### 注意:

Esc 會離開這個選單然後使用預設的鍵盤對應表，若不清楚要使用那種鍵盤對應表，United States of America ISO-8859-1 是也是保險的選項。

### 2.5.3. 選擇要安裝的元件

• doc - 額外的說明文件，大部份是經年累月的產物，會安裝到 /usr/share/doc。由 FreeBSD 文件計劃所提供的說明文件可在之後安裝，依照 節 23.3, “更新文件集” 中的指示操作。

• games - 數個傳統 BSD 遊戲，包含 fortune, rot13 以及其他。

• lib32 - 在 64-bit 版本的 FreeBSD 供執行 32-bit 應用程式使用的相容性程式庫。

• ports - FreeBSD Port 套件集是一套可自動下載、編譯安裝第三方軟體套件的集合，章 4, 安裝應用程式：套件與 Port 中會討論到如何使用 Port 套件集。

### 警告:

安裝程式並不會檢查是否有充足的磁碟空間，FreeBSD Port 套件集會使用約 500 MB 的磁碟空間，只有在有足夠的磁碟空間時才選擇這個選項。

• src - 完整的 FreeBSD 原始碼，包含核心 (Kernel) 與 Userland。雖然大多數的應用程式並不需要，但它可以編譯裝置驅動程式、核心模組或部份來自 Port 套件集的應用程式，它同時也用來做為開發 FreeBSD 本身所使用。完整的原始碼樹需要 1 GB 的磁碟空間，重新編譯整個 FreeBSD 系統需要額外再 5 GB 的空間。

## 2.6. 配置磁碟空間

### 注意:

/usr 分割區會保存許多支持系統運作的檔案，包含 FreeBSD Port 套件集以及系統原始碼。這個分割區建議至少要有 2 GB 的空間。

### 2.6.3. 手動磁碟分割

amd64 電腦最適合的選擇通常是 GPT，無法相容 GPT 的舊電腦則應使用 MBR。而其他分割表格式一般會用在那些較罕見或較舊的電腦上。

APMApple Partition Map，用於 PowerPC®。
BSDMBRBSD 標籤，因非 BSD 的磁碟工具可能無法辨識該標籤，有時被稱做 危險專用模式 (Dangerously dedicated mode)
GPTGUID 分割區表 (http://en.wikipedia.org/wiki/GUID_Partition_Table)。
MBR主開機記錄 (http://en.wikipedia.org/wiki/Master_boot_record)。
PC98使用 MBR 改編，用於 NEC PC-98 電腦 (http://en.wikipedia.org/wiki/Pc9801)。

• freebsd-boot - 儲存 FreeBSD 開機程式 (Boot code)。

• freebsd-ufs - FreeBSD 的 UFS 檔案系統。

• freebsd-swap - FreeBSD 交換空間。

### 提示:

freebsd-boot512K
freebsd-ufs2G/exrootfs
freebsd-swap4G exswap
freebsd-ufs2G/varexvarfs
freebsd-ufs1G/tmpextmpfs
freebsd-ufs接受預設值 (依磁碟提示)/usrexusrfs

### 2.6.4. Root-on-ZFS 自動磁碟分割

ZFS 設定選單也允許使用者輸入儲存池名稱、關閉強制 4k 扇區對齊、開啟或關閉加密、切換 GPT (建議) 與 MBR 分割表類型以及選擇交換空間容量。設定所有選項為想要的值之後，請選擇選單上方的安裝 () 選項。

## 2.8. 安裝後注意事項

FreeBSD 安裝完之後，bsdinstall 會在開機進入新安裝的系統之前提示設定數個選項，本節將介紹這些設定選項。

### 注意:

• IP 位址 (IP Address) - 要分配給這台電腦的 IPv4 位址。位址必須獨一無二且不可已被其他在區域網路上的設備使用。

• 子網路遮罩 (Subnet Mask) - 網路的子網路遮罩。

• 預設路由器 (Default Router) - IP 位址所在網段的預設閘道器。

• IPv6 位址 (IPv6 Address) - 要分配給這台電腦的 IPv6 位址。位址必須獨一無二且不可已被其他在區域網路上的設備使用。

• 預設路由器 (Default Router) - IPv6 位址所在網段的預設閘道器。

### 2.8.4. 開啟服務

• sshd - Secure Shell (SSH) Daemon 可從遠端透過加密的連線存取系統，只有在系統允許遠端登入時開啟這個服務。

• moused - 若在指令列系統 Console 會使用到滑鼠時，可開啟此服務。

• ntpd - 網路時間通訊協定 (Network Time Protoco, NTP) Daemon 用來自動同步時間。若在網路上有使用 Windows®, Kerberos 或 LDAP 伺服器時，可開啟此服務。

• powerd - 系統電源控制工具用來做電源控制與節能。

### 2.8.6. 新增使用者

• 使用者名稱 (Username) - 登入時使用者要輸入的名稱，常見的慣例是用姓的前一個字母與名結合，只要每個使用者名稱在系統唯一的皆可。使用者名稱區分大小寫且不應含有任何空白字元。

• 全名 (Full name) - 使用者的全名，這個欄位可使用空白並且會用來描述該使用者帳號。

• Uid - 使用者 ID，通常這個欄位會留空，系統會自動分配一個值。

• 登入群組 (Login group) - 使用者的群組，通常這個欄位會留空來使用預設值。

• 邀請使用者進入其他群組? (Invite user into other groups?) - 使用者要加入成為其成員的其他群組，若該使用者需要管理權限，則在此輸入 wheel

• 登入類別 (Login class) - 通常會留空來使用預設值。

• Shell - 輸入清單中的其中一項來設定使用者所互動的 Shell，請參考 節 3.9, “Shell” 取得更多有關 Shell 的資訊。

• 家目錄 (Home directory) - 使用者的家目錄，預設值通常是沒有問題的。

• 家目錄權限 (Home directory permissions) - 使用者家目錄的權限，預設值通常是沒有問題的。

• 使用密碼為基礎的認証方式? (Use password-based authentication?) - 通常為是 (yes)，使用者才可於登入時輸入密碼。

• 使用空白密碼? (Use an empty password?) - 通常為否 (no)，因為使用空白密碼並不安全。

• 使用隨機密碼? (Use a random password?) - 通常為否 (no)，這樣使用者接下來才可設定自己的密碼。

• 輸入密碼 (Enter password) - 這個使用者的密碼，輸入的字元不會顯示在畫面上。

• 再輸入密碼一次 (Enter password again) - 再輸入一次密碼來確認無誤。

• 建立後鎖定使用者帳號? (Lock out the account after creation?) - 通常為否 (no)，這樣使用者才可以登入。

### 2.8.7. 最後設定

bsdinstall 會提示是否有任何額外的設定需要在重新開機進入新系統之前完成。選擇 會離開進入到新系統的 Shell 或 繼續最後的安裝步驟。

FreeBSD 開機的過程會顯示許多可以參考的訊息，系統開機完成後，會顯示登入提示，在 login: 提示，輸入安裝時新增的使用者名稱。登入時避免直接使用 root，請參考 節 3.3.1.3, “超級使用者帳號” 來取得當需要管理權限時如何成為超級使用者的說明。

Generating public/private rsa1 key pair.
Your identification has been saved in /etc/ssh/ssh_host_key.
Your public key has been saved in /etc/ssh/ssh_host_key.pub.
The key fingerprint is:
10:a0:f5:af:93:ae:a3:1a:b2:bb:3c:35:d9:5a:b3:f3 root@machine3.example.com
The key's randomart image is:
+--[RSA1 1024]----+
|    o..          |
|   o . .         |
|  .   o          |
|       o         |
|    o   S        |
|   + + o         |
|o . + *          |
|o+ ..+ .         |
|==o..o+E         |
+-----------------+
Generating public/private dsa key pair.
Your identification has been saved in /etc/ssh/ssh_host_dsa_key.
Your public key has been saved in /etc/ssh/ssh_host_dsa_key.pub.
The key fingerprint is:
7e:1c:ce:dc:8a:3a:18:13:5b:34:b5:cf:d9:d1:47:b2 root@machine3.example.com
The key's randomart image is:
+--[ DSA 1024]----+
|       ..     . .|
|      o  .   . + |
|     . ..   . E .|
|    . .  o o . . |
|     +  S = .    |
|    +  . = o     |
|     +  . * .    |
|    . .  o .     |
|      .o. .      |
+-----------------+
Starting sshd.

FreeBSD 預設並不會安裝圖型化介面，請參考 章 5, X Window 系統 取得有關安裝與設定圖型化視窗管理程式的資訊。

## 2.9. 疑難排解

### 注意:

set hint.acpi.0.disabled="1"

## 2.10. 使用 Live CD

• 若要增加存取權限，必須透過認証。使用者名稱為 root 而密碼則是空白。

• 系統是直接從安裝媒體上執行，比起安裝到硬碟的系統，效能可能較差。

• 這個選項只提供指令提示，不會有圖型化介面。

## 3.1. 概述

• 如何使用 FreeBSD 的虛擬 Console。

• 如何在 FreeBSD 建立與管理使用者與群組。

• UNIX® 檔案權限以及 FreeBSD 檔案標記的運作方式。

• 預設的 FreeBSD 檔案系統配置。

• FreeBSD 的磁碟組織。

• 如何掛載 (Mount)、卸載 (Umount) 檔案系統。

• 什麼是程序、Daemon 以及信號 (Signal)。

• 什麼是 Shell，以及如何變更您預設的登入環境。

• 如何使用基本的文字編輯器。

• 什麼是裝置 (Device) 和裝置節點 (Device node)。

• 如何閱讀操作手冊以獲得更多的資訊。

## 3.2. 虛擬 Console 與終端機

FreeBSD/amd64 (pc3.example.org) (ttyv0)

login:

Shell 中有特殊字元用來表示特殊資料，我們將其稱作 Meta-character。 其中最常見的 Meta-character 是 * 字元，它代表了檔名中的任意字元。 Meta-character 可以用在搜尋檔名，舉例來說，輸入 echo * 會和輸入 ls 得到幾乎相同的結果，這是因為 shell 會將所有符合 * 字元的檔案由 echo 顯示出來。

### 注意:

有一些 Port 並非由個人維護，而是由 郵遞論壇 維護，只要郵件地址長的像 都是，寄信時記得代入實際的論壇名稱。

尤其是顯示 的 Port 都不是由特定個人維護，該 Port 的修正與支援來自訂閱該郵遞論壇的一般社群所提供，我們非常歡迎志工參與。

若寄信後沒有取得任何回應，可以依照 撰寫 FreeBSD 問題回報 的說明使用 Bugzilla 提出問題回報。

3. 自行修正看看！Porter's Handbook 中含有 Port 基礎架構的詳細資訊，可提供資訊讓您可修正偶然損壞的 Port 或甚至您可以提交之自己的 Port。

4. 依照 節 4.4, “使用 pkg 管理 Binary 套件” 中的說明安裝 Binary 套件，替代使用 Port 安裝。

## 5.1. 概述

### 注意:

• 組成 X Window 系統的各種元件以及它們是如何相互運作。

• 如何安裝並設定 Xorg

• 如何安裝並設定各種視窗管理程式與桌面環境。

• 如何在 Xorg 上使用 TrueType® 字型。

• 如何設定系統以使用圖形化登入 (XDM)。

## 5.2. 術語

X 伺服器 (X Server)

X 最初設計是以網路為中心，採用 client-server 架構。在此架構下 X 伺服器 在有鍵盤、螢幕、滑鼠的電腦上運作。該伺服器負責的工作包含管理顯示、處理來自鍵盤、滑鼠的輸入及來自其他設備 (如平板或或影像投影機) 的輸入或輸出。這點可能會讓人感到困惑，因為 X 使用的術語與一般的認知剛好相反。 一般認知會以為 X 伺服器 是要在最強悍的主機上執行，而 X 客戶端 才是在桌機上面執行，實際上卻是相反。

X 客戶端 (X Client)

X 並不規定螢幕上的視窗該長什麼樣、要如何移動滑鼠指標、 要用什麼鍵來在視窗切換、每個視窗的標題列長相，及是否該有關閉按鈕，等等。事實上，X 把這部分交給所謂的視窗管理程式來管理。可用的視窗管理程式有很多種，每一種視窗管理程式都提供不同的使用介面風格：有些支援虛擬桌面，有些允許自訂組合鍵來管理桌面，有些有 開始 鈕，有些則是可更換佈景主題，可自行安裝新的佈景主題以更換外觀。 視窗管理程式可在 Port 套件集的 x11-wm 分類找到。

KDEGNOME 會被稱作桌面環境是因為包含了完整常用桌面作業的應用程式，這些應用程式可能包含文書軟體、網頁瀏覽器及遊戲。

## 5.3. 安裝 Xorg

# cd /usr/ports/x11/xorg
# make install clean

# pkg install xorg

## 5.4. Xorg 設定

Warren Block

### 5.4.1. 快速開始

Xorg 支援大多數常見的顯示卡、鍵盤以及指標裝置，Xorg 會自動偵測這些裝置，並不需要手動設定。

1. Xorg 曾經在電腦使用過，可先將現有的設定檔重新命名或移除：

# mv /etc/X11/xorg.conf ~/xorg.conf.etc
# mv /usr/local/etc/X11/xorg.conf ~/xorg.conf.localetc
2. 加入要執行 Xorg 的使用者到 videowheel 群組，以便在可用時能開啟 3D 加速。要加入使用者 jru 到任一個可用的群組：

# pw groupmod video -m jru || pw groupmod wheel -m jru
3. 預設內含 TWM 視窗管理程式，啟動 Xorg 時便會啟動該視窗管理程式：

% startx
4. 在部份較舊版的 FreeBSD，在切換回文字 Console 前系統 Console 必須設為 vt(4) 才可正常運作，請參考 節 5.4.3, “核心模式設定 (Kernel Mode Setting, KMS)”

### 5.4.2. 可加速影像處理的使用者群組

# pw groupmod video -m slurms || pw groupmod wheel -m slurms

### 5.4.3. 核心模式設定 (Kernel Mode Setting, KMS)

kern.vty=vt

### 5.4.4. 設定檔

#### 5.4.4.1. 目錄

Xorg 會查看數個目錄來尋找設定檔，在 FreeBSD 較建議使用 /usr/local/etc/X11/ 來存放這些設定檔，使用這個目錄可以幫助將應用程式檔案與作業系統檔案分離。

### 5.4.5. 顯示卡

Intel®

3D 加速在大多數 Intel® 顯示晶片都有支援，最新到 Ivy Bridge (HD Graphics 2500, 4000, 及 P4000) 包含 Iron Lake (HD Graphics) 與 Sandy Bridge (HD Graphics 2000)。

Radeon 顯示卡支援 2D 及 3D 加速，最新到 HD6000 系列。

NVIDIA

BIOS 設定會依電腦的型號有所不同，在某些情況下，可以同時開啟兩個 GPU，而在建立的設定檔中的 Device 節只使用主要的 GPU 便能讓系統運作。

x11-drivers/xf86-video-scfb 也是不特定顯示卡的驅動程式，可在許多 UEFIARM® 的電腦上運作。

/usr/local/etc/X11/xorg.conf.d/driver-intel.conf

Section "Device"
Identifier "Card0"
Driver     "intel"
# BusID    "PCI:1:0:0"
EndSection

/usr/local/etc/X11/xorg.conf.d/driver-radeon.conf

Section "Device"
Identifier "Card0"
EndSection

/usr/local/etc/X11/xorg.conf.d/driver-vesa.conf

Section "Device"
Identifier "Card0"
Driver     "vesa"
EndSection

/usr/local/etc/X11/xorg.conf.d/driver-scfb.conf

Section "Device"
Identifier "Card0"
Driver     "scfb"
EndSection

### 5.4.6. 顯示器

% xrandr
Screen 0: minimum 320 x 200, current 3000 x 1920, maximum 8192 x 8192
DVI-0 connected primary 1920x1200+1080+0 (normal left inverted right x axis y axis) 495mm x 310mm
1920x1200     59.95*+
1600x1200     60.00
1280x1024     85.02    75.02    60.02
1280x960      60.00
1152x864      75.00
1024x768      85.00    75.08    70.07    60.00
832x624       74.55
800x600       75.00    60.32
640x480       75.00    60.00
720x400       70.08
DisplayPort-0 disconnected (normal left inverted right x axis y axis)
HDMI-0 disconnected (normal left inverted right x axis y axis)

% xrandr --mode 1280x1024 --rate 60

% xrandr
Screen 0: minimum 320 x 200, current 1366 x 768, maximum 8192 x 8192
LVDS1 connected 1366x768+0+0 (normal left inverted right x axis y axis) 344mm x 193mm
1366x768      60.04*+
1024x768      60.00
800x600       60.32    56.25
640x480       59.94
VGA1 connected (normal left inverted right x axis y axis)
1280x1024     60.02 +  75.02
1280x960      60.00
1152x864      75.00
1024x768      75.08    70.07    60.00
832x624       74.55
800x600       72.19    75.00    60.32    56.25
640x480       75.00    72.81    66.67    60.00
720x400       70.08
HDMI1 disconnected (normal left inverted right x axis y axis)
DP1 disconnected (normal left inverted right x axis y axis)

% xrandr --output VGA1 --auto --right-of LVDS1

--auto 會選擇使用 EDID 偵測到的解析度與更新頻率。若未正確偵測解析度，可替換 --auto--mode 然後給予固定值。例如大部份的投影機可使用 1024x768 解析度為，則可設定 --mode 1024x768

xrandr(1) 通常會在 .xinitrc 執行以在 X 啟動時設定適合的模式。

/usr/local/etc/X11/xorg.conf.d/screen-resolution.conf

Section "Screen"
Identifier "Screen0"
Device     "Card0"
SubSection "Display"
Modes      "1024x768"
EndSubSection
EndSection

/usr/local/etc/X11/xorg.conf.d/monitor0-freq.conf

Section "Monitor"
Identifier   "Monitor0"
HorizSync    30-83   # kHz
VertRefresh  50-76   # Hz
EndSection

### 5.4.7. 輸入裝置

#### 5.4.7.1. 鍵盤

/usr/local/etc/X11/xorg.conf.d/keyboard-fr-oss.conf

Section	"InputClass"
Identifier	"KeyboardDefaults"
Driver		"keyboard"
MatchIsKeyboard	"on"
Option		"XkbLayout" "fr"
Option		"XkbVariant" "oss"
EndSection

/usr/local/etc/X11/xorg.conf.d/kbd-layout-multi.conf

Section	"InputClass"
Identifier	"All Keyboards"
MatchIsKeyboard	"yes"
Option		"XkbLayout" "us, es, ua"
EndSection

X 可以使用組合鍵來關閉，預設並未設定組合鍵，因為該組合鍵與部份應用程式的鍵盤指令衝突。要開啟這個選項需要更改鍵盤 InputDevice 節：

/usr/local/etc/X11/xorg.conf.d/keyboard-zap.conf

Section	"InputClass"
Identifier	"KeyboardDefaults"
Driver		"keyboard"
MatchIsKeyboard	"on"
Option		"XkbOptions" "terminate:ctrl_alt_bksp"
EndSection

#### 5.4.7.2. 滑鼠與指標裝置

/usr/local/etc/X11/xorg.conf.d/mouse0-buttons.conf

Section "InputDevice"
Identifier  "Mouse0"
Option      "Buttons" "7"
EndSection

### 5.4.8. 手動設定

# Xorg -configure

# Xorg -config /root/xorg.conf.new

## 5.5. 在 Xorg 使用字型

### 5.5.1. Type1 字型

# cd /usr/ports/x11-fonts/urwfonts
# make install clean

FontPath "/usr/local/share/fonts/urwfonts/"

% xset fp+ /usr/local/share/fonts/urwfonts
% xset fp rehash

### 5.5.2. TrueType® 字型

Xorg 內建支援繪製 TrueType® 字型，目前有兩個模組可以支援這項功能。在本例中使用 freetype 模組，由於此模組與其他字型繪製後端較為一致。要開啟 freetype 模組只需要將下行加入到 /etc/X11/xorg.conf 中的 "Module" section。

Load  "freetype"

# pkg install mkfontdir

# cd /usr/local/share/fonts/TrueType
# mkfontdir

% xset fp+ /usr/local/share/fonts/TrueType
% xset fp rehash

### 5.5.3. 反鋸齒字型

<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>

<dir>/path/to/my/fonts</dir>

# fc-cache -f

        <match target="font">
<test name="size" compare="less">
<double>14</double>
</test>
<edit name="antialias" mode="assign">
<bool>false</bool>
</edit>
</match>
<match target="font">
<test name="pixelsize" compare="less" qual="any">
<double>14</double>
</test>
<edit mode="assign" name="antialias">
<bool>false</bool>
</edit>
</match>

	<match target="pattern" name="family">
<test qual="any" name="family">
<string>fixed</string>
</test>
<edit name="family" mode="assign">
<string>mono</string>
</edit>
</match>
<match target="pattern" name="family">
<test qual="any" name="family">
<string>console</string>
</test>
<edit name="family" mode="assign">
<string>mono</string>
</edit>
</match>

(這會設定等寬字型的其他常用名稱為 "mono")，然後加入：

         <match target="pattern" name="family">
<test qual="any" name="family">
<string>mono</string>
</test>
<edit name="spacing" mode="assign">
<int>100</int>
</edit>
</match>      

         <match target="pattern" name="family">
<test qual="any" name="family">
<string>Helvetica</string>
</test>
<edit name="family" mode="assign">
<string>sans-serif</string>
</edit>
</match>        

Users can add personalized settings by creating their own ~/.config/fontconfig/fonts.conf. This file uses the same XML format described above.

	 <match target="font">
<test qual="all" name="rgba">
<const>unknown</const>
</test>
<edit name="rgba" mode="assign">
<const>rgb</const>
</edit>
</match>

## 5.6. X 顯示管理程式

Contributed by .

Xorg 提供了 X 顯示管理程式 (X Display Manager, XDM)，可用來做登入階段的管理。XDM 提供了一個圖型化的介面來選擇要連結的顯示伺服器以及輸入認証資訊 (登入與密碼)。

### 5.6.1. 設定 XDM

ttyv8   "/usr/local/bin/xdm -nodaemon"  xterm   off secure

XDM 的設定目錄位於 /usr/local/lib/X11/xdm。此目錄中包含數個可用來更改 XDM 行為與外觀的檔案以及在 XDM 執行時用來設定桌面的一些 Script 及程式，表格 5.1, “XDM 設定檔” 摘要了每個檔案的功能。這些檔案正確的語法與用法在 xdm(1) 有說明。

Xaccess連線到 XDM 所需的通訊協定稱做 X 顯示管理程式連線通訊協定 (X Display Manager Connection Protocol, XDMCP)，此檔案為客戶端認証規則，用來控制來自遠端機器的 XDMCP 連線。預設此檔案並不允許任何遠端的客戶端連線。
Xresources此檔案控制 XDM 顯示選擇器及登入畫面的外觀。預設的設定簡單的矩形登入視窗，上方用較大的字型顯示機器的主機名稱，並在下方顯示 Login:Password: 提示。此檔案的格式與 Xorg 說明文件中說明的 app-defaults 檔相同。
Xservers登入選擇時在選擇器上要提供的本地及遠端顯示清單。
Xsession預設的登入階段 Script，使用者登入之後由 XDM 執行。一般每一位使用者都會有自訂的階段 Script 在 ~/.xsession 來覆蓋此 Script 的設定。
Xsetup_*用來在顯示選擇器與登入介面之前自動執行應用程式的 Script。每一個顯示各有一個 Script，名稱為 Xsetup_*，其中 * 為本地顯示編號。正常情況這些 Script 會在背景執行一兩個程式，例如 xconsole
xdm-config用來設定所有在此機器上執行的顯示的全域設定檔。
xdm-errors內含由伺服器程式產生的錯誤訊息，若 XDM 嘗試啟動的顯示沒有回應，可查看此檔案來取得錯誤訊息。以登入階段為基礎，這些訊息也同樣會寫入至使用者的 ~/.xsession-errors
xdm-pidXDM 的執行程序 ID

### 5.6.2. 設定遠端存取

! SECURITY: do not listen for XDMCP or Chooser requests
! Comment out this line if you want to manage X terminals with xdm
DisplayManager.requestPort:     0

## 5.7. 桌面環境

Contributed by .

### 5.7.1. GNOME

GNOME 是一個擁有友善使用者介面的的桌面環境，它包括用於啟動應用程式和顯示狀態的面板、一系列工具與應用程序及一套可讓應用程式更容易進行合作、相互一致的協定。更多有關 FreeBSD GNOME 的訊息可在 http://www.FreeBSD.org/gnome 取得，該網站包含了有關在 FreeBSD 安裝、設定和管理 GNOME 的額外文件。

# pkg install gnome3

# cd /usr/ports/x11/gnome3
# make install clean

GNOME 需要掛載 /proc。加入下行到 /etc/fstab 讓系統啟動時會自動掛載這個檔案系統。

proc           /proc       procfs  rw  0   0

GNOME 使用了 D-Bus 以及 HAL 的 Message bus 與 Hardware abstraction。這兩個應用程式會隨著 GNOME 的相依一併自動安裝，但需要在 /etc/rc.conf 開啟，這樣在系統開機時才會啟動：

dbus_enable="YES"
hald_enable="YES"

gdm_enable="YES"

gnome_enable="YES"

GDM 則會在系統開機時自動啟動。

% echo "exec /usr/local/bin/gnome-session" > ~/.xinitrc

% echo "#!/bin/sh" > ~/.xsession
% echo "exec /usr/local/bin/gnome-session" >> ~/.xsession
% chmod +x ~/.xsession

### 5.7.2. KDE

KDE 是另一套易於使用的桌面環境。這個桌面環境提供了一致外觀的應用程式、標準化的選單和工具列、組合鍵、配色方案、國際化與集中、對話框導向的桌面設定。更多有關 KDE 可在 http://www.kde.org/ 取得。要取得 FreeBSD 特定的資訊，則可參考 http://freebsd.kde.org

# pkg install x11/kde4

# cd /usr/ports/x11/kde4
# make install clean

KDE 需要掛載 /proc。加入下行到 /etc/fstab 讓系統啟動時會自動掛載這個檔案系統：

proc           /proc       procfs  rw  0   0

KDE 使用了 D-Bus 以及 HAL 的 Message bus 與 Hardware abstraction。這兩個應用程式會隨著 KDE 的相依一併自動安裝，但需要在 /etc/rc.conf 開啟，這樣在系統開機時才會啟動：

dbus_enable="YES"
hald_enable="YES"

KDE 的安裝包含了 KDE Display Manager, KDM，要開啟這個顯示管理程式，需加入下行到 /etc/rc.conf

kdm4_enable="YES"

exec /usr/local/bin/startkde

% echo "#!/bin/sh" > ~/.xsession
% echo "exec /usr/local/bin/startkde" >> ~/.xsession
% chmod +x ~/.xsession

### 5.7.3. Xfce

Xfce 是以 GNOME 使用的 GTK +工具包做為基礎所開發的桌面環境，但是它更輕巧且提供了一種簡單、高效、易於使用的桌面。它可完全自訂設定、附有選單、Applet 及應用程式啟動器的主面板、提供檔案管理程式和音效管理程式並且可設定主題。由於它是快速、輕巧、高效的桌面環境，因此它非常適合有記憶體限制的較舊或較慢機器。更多有關 Xfce 的資訊可至 http://www.xfce.org 取得。

# pkg install xfce

# cd /usr/ports/x11-wm/xfce4
# make install clean

% echo "exec /usr/local/bin/startxfce4 --with-ck-launch" > ~/.xinitrc

% echo "#!/bin/sh" > ~/.xsession
% echo "exec /usr/local/bin/startxfce4 --with-ck-launch" >> ~/.xsession
% chmod +x ~/.xsession

## 5.8. 安裝 Compiz Fusion

### 5.8.1. 設定 FreeBSD nVidia 驅動程式

# pkg install x11/nvidia-driver

nvidia_load="YES"

### 注意:

Driver      "nv"

Driver      "nvidia"

### 5.8.2. 設定 xorg.conf 來啟動桌面特效

Section "Extensions"
Option         "Composite" "Enable"
EndSection

Section "Screen"
Identifier     "Screen0"
Device         "Card0"
Monitor        "Monitor0"
...

DefaultDepth    24
Option         "AddARGBGLXVisuals" "True"

SubSection     "Display"
Viewport    0 0
Modes      "1280x1024"
EndSubSection

SubSection     "Display"
Viewport    0 0
Depth       24
Modes      "1280x1024"
EndSubSection

Section "Module"
...

# nvidia-xconfig --add-argb-glx-visuals
# nvidia-xconfig --composite
# nvidia-xconfig --depth=24

### 5.8.3. 安裝與設定 Compiz Fusion

# pkg install x11-wm/compiz-fusion

% compiz --replace --sm-disable --ignore-desktop-hints ccp &
% emerald --replace &

#! /bin/sh
compiz --replace --sm-disable --ignore-desktop-hints ccp &
emerald --replace &

% chmod +x ~/start-compiz

% ccsm

### 注意:

GNOME 中，也可在系統 System, 偏好設定 Preferences 選單中找到。

## 5.9. 疑難排解

Option "AutoAddDevices" "false"

### 注意:

<?xml version="1.0" encoding="iso-8859-1"?>
<deviceinfo version="0.2">
<device>
<match key="info.capabilities" contains="input.keyboard">
<merge key="input.x11_options.XkbModel" type="string">pc102</merge>
<merge key="input.x11_options.XkbLayout" type="string">fr</merge>
</match>
</device>
</deviceinfo>

% setxkbmap -model pc102 -layout fr

/usr/local/share/X11/xkb/rules/base.lst 中列出了各種可用的鍵盤、配置與設定。

Section "Monitor"
Identifier   "Monitor0"
VendorName   "Monitor Vendor"
ModelName    "Monitor Model"
HorizSync    30-107
VertRefresh  48-120
EndSection

X 允許在支援的顯示器使用 DPMS (Energy Star) 功能，xset(1) 程式可以控制逾時並可強制待機 (Standby)、暫停 (Suspend) 或關閉 (Off) 模式。若您想要為您的顯示器開啟 DPMS 功能，您需要加入下行到顯示器 (Monitor) 的 Section：

Option       "DPMS"

Section "Screen"
Identifier "Screen0"
Device     "Card0"
Monitor    "Monitor0"
DefaultDepth 24
SubSection "Display"
Viewport  0 0
Depth     24
Modes     "1024x768"
EndSubSection
EndSection

DefaultDepth 關鍵字代表預設執行要使用的色彩深度，這個設定可以被 Xorg(1) 的指令列參數 -depth 覆蓋。Modes 關鍵字代表執行要使用的解析度，注意，只有 VESA 標準模式才支援目標系統的繪圖硬體來定義解析度。在上述的例子中，預設使用的色彩深度為每像素 24 bit，這個色彩深度可用的解析度為 1024 x 768 像素。

### 注意:

# cp xorg.conf.new /etc/X11/xorg.conf

### 5.9.2. 加入寬螢幕平板顯示器到設定檔

• 2560x1600

• 1920x1200

• 1680x1050

• 1440x900

• 1280x800

Section "Screen"
Identifier "Screen0"
Device     "Card0"
Monitor    "Monitor0"
DefaultDepth 24
SubSection "Display"
Viewport  0 0
Depth     24
Modes     "1680x1050"
EndSubSection
EndSection

Xorg 能夠從寬螢幕設定取得解析度資訊 (透過 I2C/DDC)，因此能夠知道螢幕能處理的頻率及解析度。

(II) MGA(0): Supported additional Video Mode:
(II) MGA(0): clock: 146.2 MHz   Image Size:  433 x 271 mm
(II) MGA(0): h_active: 1680  h_sync: 1784  h_sync_end 1960 h_blank_end 2240 h_border: 0
(II) MGA(0): v_active: 1050  v_sync: 1053  v_sync_end 1059 v_blanking: 1089 v_border: 0
(II) MGA(0): Ranges: V min: 48  V max: 85 Hz, H min: 30  H max: 94 kHz, PixClock max 170 MHz

ModeLine <name> <clock> <4 horiz. timings> <4 vert. timings>

Section "Monitor"
Identifier      "Monitor1"
VendorName      "Bigname"
ModelName       "BestModel"
ModeLine        "1680x1050" 146.2 1680 1784 1960 2240 1050 1053 1059 1089
Option          "DPMS"
EndSection

### 5.9.3. Compiz Fusion 疑難排解

5.9.3.1. 我已經安裝了 Compiz Fusion，但在執行了您所提到的指令後，我的視窗的標題列與按鈕便消失了。是那裡有問題?
5.9.3.2. 當我執行指令來啟動 Compiz Fusion，X 伺服器便當掉了，然後我又返回 Console。是那裡有問題?
 5.9.3.1. 我已經安裝了 Compiz Fusion，但在執行了您所提到的指令後，我的視窗的標題列與按鈕便消失了。是那裡有問題? 您可能忘記在 /etc/X11/xorg.conf 中的設定。請重新檢查這個檔案，特別是 DefaultDepth 及 AddARGBGLXVisuals 指令項。 5.9.3.2. 當我執行指令來啟動 Compiz Fusion，X 伺服器便當掉了，然後我又返回 Console。是那裡有問題? 若您檢查 /var/log/Xorg.0.log，您可能可以找到當 X 啟動時所發生的錯誤訊息。最常發生的錯誤會是：(EE) NVIDIA(0): Failed to initialize the GLX module; please check in your X (EE) NVIDIA(0): log file that the GLX module has been loaded in your X (EE) NVIDIA(0): server, and that the module is the NVIDIA GLX module. If (EE) NVIDIA(0): you continue to encounter problems, Please try (EE) NVIDIA(0): reinstalling the NVIDIA driver.會發生這個情形通常是因為您升級了 Xorg，您需要重新安裝 x11/nvidia-driver 套件來重新編譯 glx。

# 部 II. 一般作業

• 介紹給您常見且實用的桌面應用軟體：瀏覽器、辦工工具、文件閱覽程式等。

• 介紹給您眾多 FreeBSD 上可用的多媒體工具。

• 解釋如何編譯量身訂做的 FreeBSD 核心以增加額外系統功能的流程。

• 詳細描述列印系統，包含桌上型印表機及網路印表機的設定。

• 展示給您看如何在您的 FreeBSD 系統中執行 Linux 應用軟體。

## 6.2. 瀏覽器

KDEGNOME 桌面環境都有提供自有的 HTML 瀏覽器。請參考 節 5.7, “桌面環境” 來了解更多有關如何設定完整桌面環境的資訊。

Firefox有 FreeBSD 、 Linux® 及在地化版本
Opera有 FreeBSD 、 Linux® 版本
Konqueror需要 KDE 程式庫
Chromium需要 Gtk+ 程式庫

### 6.2.1. Firefox

Firefox 是一套已完整植到 FreeBSD 的開放源始碼瀏覽器，它具備符合 HTML 標準的顯示引擎、頁籤瀏覽、彈出視窗封鎖、擴充套件、強化安全性及其他更多功能。Firefox 的基礎使用了 Mozilla 的程式庫。

# pkg install firefox

# pkg install firefox-esr

# cd /usr/ports/www/firefox
# make install clean

#### 6.2.1.1. Firefox 與 Java™ 附加元件

Firefox 的安裝並不包含 Java™ 支援，雖然如此 java/icedtea-web 提供了免費的網頁瀏覽器附加元件來執行 Java applet，此附加元件可以用 Binary 套件安裝或者自 Port 編譯：

# cd /usr/ports/java/icedtea-web
# make install clean

% ln -s /usr/local/lib/IcedTeaPlugin.so \
$HOME/.mozilla/plugins/ #### 6.2.1.2. Firefox 與 Adobe® Flash® 附加元件 FreeBSD 並沒有原生的 Adobe® Flash® 附加原件。雖然如此，仍可以使用軟體包裝程式來執行 Linux® 版本 的附加元件。該包裝程式也提供其他瀏覽器附加元件的支援，如 RealPlayer®。 要安裝並開啟此附加元件，可執行以下步驟： 1. 自 Port 安裝 www/nspluginwrapper ，受到授權條款的限制，該套件無 Binary 版本。此 Port 需安裝 emulators/linux_base-c6 2. 自 Port 安裝 www/linux-c6-flashplugin11 ，受到授權條款的限制，該套件無 Binary 版本。 3. 第一次使用附加元件前，每位使用者需要先執行： % nspluginwrapper -v -a -i 當附加元件 Port 完成更新並且重新安裝後，每位使用者需要執行： % nspluginwrapper -v -a -u 開啟瀏覽器並在網址列輸入 about:plugins 並按 Enter 鍵，目前可用的附加元件清單中應會顯示該附加元件。 #### 6.2.1.3. Firefox 與 Swfdec Flash® 附加元件 SwfdecFlash® 動畫的解碼程式及繪製程式。Swfdec-Mozilla 是供 Firefox 瀏覽器使用的附加元件，可使用 Swfdec 程式庫來播放 SWF 檔案。 要安裝套件可： # pkg install swfdec-plugin 若無套件可用，可自 Port 套件集編譯並安裝該附加元件： # cd /usr/ports/www/swfdec-plugin # make install clean 重新啟動瀏覽器來啟動此附加元件。 ### 6.2.2. Opera Opera 是個具備完整功能、符合標準且輕量、執行速度快的瀏覽器。 它同時也具備了內建的郵件、新聞閱讀器、IRC 客戶端、RSS/Atom 來源閱讀器等。 可用的版本有兩種原生的 FreeBSD 版本及 Linux® 模擬模式下執行的版本。 以下指令可安裝 FreeBSD Binary 套件版本的 Opera，替換 operalinux-opera 則可改安裝 Linux® 版本。 # pkg install opera 或者，可安裝 Port 套件集中的版本，以下範例會編譯原生的版本。 # cd /usr/ports/www/opera # make install clean 要安裝 Linux® 則替換 operalinux-opera 要安裝 Adobe® Flash® 附加元件，需先編譯 www/linux-c6-flashplugin11 Port，因受到授權條款限制無法事先做為 Binary 套件。然後安裝 www/opera-linuxplugins。以下範例示範編譯 Port 中的這兩個應用程式。 # cd /usr/ports/www/linux-c6-flashplugin11 # make install clean # cd /usr/ports/www/opera-linuxplugins # make install clean 安裝完成後，開啟瀏覽器檢查附加元件是否存在，在網址列輸入 opera:plugins 並按下 Enter 鍵，便會有清單顯示目前可用的附加元件。 若要安裝 Java 附加元件請依照 節 6.2.1.1, “Firefox 與 Java™ 附加元件” 中的指示。 ### 6.2.3. Konqueror Konqueror 不只是個網頁瀏覽器， 它同時也是檔案管理器和多媒體瀏覽器。它包含在 x11/kde4-baseapps 套件或 Port 中。 Konqueror 使用支援 WebKit 以及它自有的 KTHML。WebKit 是一套被許多現代瀏覽器所使用的繪圖引擎，包含 Chromium。要在 FreeBSD 的 Konqueror 使用 WebKit 需安裝 www/kwebkitpart 套件或 Port。此範例示範使用 Port 編譯： # cd /usr/ports/www/kwebkitpart # make install clean 要啟動 Konqueror 中的 WebKit 點選 SettingsConfigure Konqueror。在 General 設定頁面內點選 Default web browser engine 旁的下拉示選單並變更 KHTMLWebKit Konqueror 也支援 Flash®如何Konqueror 上安裝 Flash® 的說明可參考 http://freebsd.kde.org/howtos/konqueror-flash.php ### 6.2.4. Chromium Chromium 是一個開放源始碼的瀏覽器計劃，該計劃的目標是要建立一個安全、快速且更穩定的網頁瀏覽體驗。Chromium 的功能有頁籤式瀏覽、彈出視窗封鎖、擴充套件等等。Chromium 也是 Google Chrome 網頁瀏覽器所採用的基礎。 Chromium 可以使用套件來安裝，只要輸入： # pkg install chromium 或者可從 Port 套件集的原始碼編譯 Chromium # cd /usr/ports/www/chromium # make install clean ### 注意: Chromium 的執行檔為 /usr/local/bin/chrome，並非 /usr/local/bin/chromium #### 6.2.4.1. Chromium 與 Java™ 附加元件 Chromium 的安裝並不包含 Java™ 的支援。要安裝 Java™ 附加元件支援，請依照 節 6.2.1.1, “Firefox 與 Java™ 附加元件” 的指示操作。 Java™ 支援安裝完成後，啟動 Chromium 然後在網址列輸入 about:plugins。已安裝的附件元件其中之一應該會有 IcedTea-Web。 Chromium 未顯示 IcedTea-Web 為附件元件，請執行以下指令然後重新啟動網頁瀏覽器： # mkdir -p /usr/local/share/chromium/plugins # ln -s /usr/local/lib/IcedTeaPlugin.so \ /usr/local/share/chromium/plugins/ #### 6.2.4.2. Chromium 與 Adobe® Flash® 附加元件 設定 ChromiumAdobe® Flash® 與 節 6.2.1.2, “Firefox 與 Adobe® Flash® 附加元件” 中的操作相似，無須額外的設定，因 Chromium 能夠使用部份來自其他瀏覽器的附加元件。 ## 6.3. 辦工工具 當開始進行辦公，新的使用者通常會去找好用的辦公室軟體或是好上手的文件處理程式。 雖然有些 桌面環境 像是 KDE 已經提供了辦公軟體組合的套件，FreeBSD 預設未提供任何辦工工具。 不論是否有安裝視窗管理程式，FreeBSD 可安裝多套辦公軟體以及圖型化文件處理程式。 本章節元範如何安裝以下熱門的辦工軟體以及說明該應用程式所需的資源、自 Port 編譯的時間或者是否有其他主要相依套件。 應用程式名稱所需資源自 Port 安裝時間主要相依套件 CalligraKDE AbiWordGtk+GNOME The GimpGtk+ Apache OpenOffice非常多JDKMozilla LibreOffice有點多非常多Gtk+KDE/ GNOMEJDK ### 6.3.1. Calligra KDE 桌面環境中內含辦公軟體可以與 KDE 分開安裝。Calligra 中也有可在其他辦公軟體中找到的標準元件，如 Words 是文件處理程式、Sheets 是試算表程式、Stage 可管理投影片以及 Karbon 用來繪製圖型文件。 在 FreeBSD 中 editors/calligra 可以使用套件或 Port 的方式安裝，要使用套件安裝： # pkg install calligra 若沒有可用的套件，可改使用 Port 套件集安裝： # cd /usr/ports/editors/calligra # make install clean ### 6.3.2. AbiWord AbiWord 是一個免費的文件處理軟體，外觀和感覺都近似於 Microsoft® Word。 它非常快速，包含了許多功能而且非常容易上手。 AbiWord 可以輸入或輸出許多檔案格式， 包括一些有專用的格式，例如 Microsoft® .rtf 格式。 要安裝 AbiWord Binary 套件，可使用下列指令： # pkg install abiword 若沒有 Binary 套件版本，也可以從 Port 套件集中編譯安裝： # cd /usr/ports/editors/abiword # make install clean ### 6.3.3. The GIMP 對於影像的編輯及修改來說，The GIMP 是非常精緻的影像處理軟體。 它可以當作簡單的繪圖軟體或是高品質的相片處理軟體。 它支援為數眾多的外掛程式及指令稿 (script-fu) 介面。 The GIMP 可以讀寫許多檔案格式。 它也支援掃描器和手寫板。 要安裝套件可： # pkg install gimp 或使用 Port 套件集安裝： # cd /usr/ports/graphics/gimp # make install clean 在 Port 套件集的 graphics 分類 (freebsd.org/ports/graphics.html) 下也包含了許多 GIMP 相關的附加元件，說明檔及使用手冊。 ### 6.3.4. Apache OpenOffice Apache OpenOffice 是開放原始碼的辦工室軟體，由 Apache Software Foundation's Incubator 底下的團隊所開發。 它包含了所有完整的辦公軟體組合： 文字處理器、試算表、簡報軟體還有繪圖軟體。 除了它的使用者介面非常類似其他的辦公軟體， 他還能夠輸入和輸出許多熱門的檔案格式。 它也包含了不同語言的使用者介面、拼字檢查和字典。 Apache OpenOffice 的文字處理器使用原生的 XML 檔案格式來增加移植性及彈性。 試算表程式支援巨集 (Macro) 功能而且能夠使用外來的資料庫介面。 Apache OpenOffice 已經十分穩定， 並且能夠在 Windows®, Solaris™, Linux®, FreeBSD 及 Mac OS® X 等作業系統上面執行。 想知道更多關於 Apache OpenOffice 的資訊可以在 openoffice.org 網頁上查詢。在 FreeBSD 特定的資訊可參考 porting.openoffice.org/freebsd/ 要安裝 Apache OpenOffice 套件： # pkg install apache-openoffice 當套件安裝完成之後，只要輸入下面的指令就能執行 Apache OpenOffice % openoffice-X.Y.Z 其中 X.Y.Z 是已安裝的 Apache OpenOffice 的版本編號。第一次執行 Apache OpenOffice 會詢問一些問題且會在使用者的家目錄建立一個 .openoffice.org 資料夾。 若無法由套件取得想要的 Apache OpenOffice，仍可選擇從 Port 編譯。 不過必須注意：編譯的過程會需要大量的磁碟空間與時間： # cd /usr/ports/editors/openoffice-4 # make install clean ### 注意: 如果想要編譯在地化的版本，將前面的指令替換成為： # make LOCALIZED_LANG=your_language install clean 替換 your_language 為正確的語言 ISO 編碼。支援的語言編碼清單在 files/Makefile.localized，位於該 Port 的目錄。 ### 6.3.5. LibreOffice LibreOffice 是一套自由的辦公軟體由 documentfoundation.org 所開發。它可相容其他主流的辦公軟體以及可在各種平台上使用。它是 Apache OpenOffice 品牌重塑後的分支，含有可在完整辦公生產力軟體中找到的應用程式：文件處理程式、試算表、簡報管理程式、繪圖程式、資料庫管理程式以及建立與編輯數學公式的工具。它也支援數種語言與國際化一直延伸到介面、拼字檢查程式與字典。 LibreOffice 的文件處理程式使用了原生的 XML 檔案格式來增加可攜性與彈性，試算表程式支援可與外部資料庫連接的巨集語言。LibreOffice 非常穩定且可直接在 Windows®, Linux®, FreeBSD 以及 Mac OS® X 上執行。更多有關 LibreOffice 的資訊可在 libreoffice.org 找到。 要安裝英文版本的 LibreOffice 套件： # pkg install libreoffice Port 套件集的編輯器分類 (freebsd.org/ports/editors.html) 中含有數個 LibreOffice 的語系。安裝在地化套件時，請替換 libreoffice 為在地化套件的名稱。 套件安裝之後，輸入以下指令來執行 LibreOffice % libreoffice 第一次啟動的過程中會詢問一些問題並在使用者的家目錄建立 .libreoffice 資料夾。 若找不到想使用的 LibreOffice 套件，也可從 Port 編譯，但這會要大量的磁碟空間及漫長的時間編譯。以下例子示範編譯英文版本： # cd /usr/ports/editors/libreoffice # make install clean ### 注意: 要編譯在地化版本，則需 cd 進入想要的語言 Port 目錄。支援的語言可在 Port 套件集的編輯器分類 (freebsd.org/ports/editors.html) 中找到。 ## 6.4. 文件閱覽程式 UNIX® 出現之後，有一些新的文件格式才越來越熱門，這些文件所需的檢視程式可能並不在基礎系統中。本節將示範如何安裝以下文件檢視程式： 應用程式名稱所需資源自 Port 安裝時間主要相依套件 XpdfFreeType gvXaw3d GeeqieGtk+GNOME ePDFViewGtk+ OkularKDE ### 6.4.1. Xpdf 如果你想要一個小型的 FreeBSD PDF 閱覽軟體， Xpdf 是個輕量級而且有效率的閱覽器。 它只需要非常少的資源而且十分穩定。 它只使用標準的 X 字型且不需要額外的工具包(Toolkit)。 安裝 Xpdf 套件： # pkg install xpdf 若沒有可用的套件版本，可使用 Port 套件集安裝： # cd /usr/ports/graphics/xpdf # make install clean 完成安裝後，執行 xpdf 並使用滑鼠右鍵開啟選單。 ### 6.4.2. gv gvPostScript® 和 PDF 的閱覽器。 它建構於 ghostview 的基礎上，不過因為使用 Xaw3d 視窗元件工具包，所以外觀看起來比較漂亮。 gv 有許多可設定的功能，比如說紙張方向、紙張大小、縮放比例、和反鋸齒(Anti-aliasing)等。 而且幾乎所有的使用都可以從鍵盤或滑鼠來完成。 安裝 gv 套件： # pkg install gv 若沒有可用的套件版本，可使用 Port 套件集安裝： # cd /usr/ports/print/gv # make install clean ### 6.4.3. Geeqie Geeqie 是由已經停止維護的 GQView 專案所衍伸出來的分支，並致力開發新功能並整合已有的修補。Geeqie 是一套影像管理軟體，支援單鍵閱覽檔案、啟動外部編輯器、縮圖預覽等功能。 它也有幻燈片模式及一些基本的檔案操作的功能，能輕鬆的管理大量影像並找出重複的檔案。 Geeqie 也支援使用全螢幕閱覽以及國際化。 安裝 Geeqie 套件： # pkg install geeqie 若沒有可用的套件版本，可使用 Port 套件集安裝： # cd /usr/ports/graphics/geeqie # make install clean ### 6.4.4. ePDFView ePDFView 是一套小巧的 PDF 文件檢視程式，只使用了 Gtk+Poppler 程式庫。它目前還在開發當中，但已經可以開啟大部份 PDF 檔案 (甚至是加密過的)、儲存文件複本以及支援使用 CUPS 來列印。 要以套件安裝 ePDFView # pkg install epdfview 若沒有可用的套件版本，可使用 Port 套件集安裝： # cd /usr/ports/graphics/epdfview # make install clean ### 6.4.5. Okular Okular 是一套通用的文件檢視程式，以 KDEKPDF 為基礎。它可以開啟許多種文件格式，包含了 PDF, PostScript®, DjVu, CHM, XPS 以及 ePub。 要以套件安裝 Okular # pkg install okular 若沒有可用的套件版本，可使用 Port 套件集安裝： # cd /usr/ports/graphics/okular # make install clean ## 6.5. 財務 如果有任何理由你想要在你的 FreeBSD 桌面環境上管理你的個人財務， 這裡有一些功能強大、使用簡單的應用程式可供安裝。 這些財務管理軟體之中有些是相容於流行的 QuickenExcel 文件。 這節涵蓋了下面這些軟體： 應用程式名稱所需資源自 Port 安裝時間主要相依套件 GnuCashGNOME GnumericGNOME KMyMoneyKDE ### 6.5.1. GnuCash GnuCashGNOME 團隊努力成果中的一部分， GNOME 團隊主要提供親切而強大的桌面應用程式給終端使用者。使用 GnuCash 可以持續追蹤收入與花費、銀行帳戶以及股票證券等。 它的特性是介面直覺但功能仍非常專業。 GnuCash 提供了智慧的計數器、多階層帳戶系統以及快速鍵及自動完成功能。 它也能分開單一的報表至數個詳細的部份。 GnuCash 也能夠匯入及合併 Quicken QIF 檔案。 它也能處理大部分國際的日期及通用貨幣之格式。 安裝 GnuCash 套件： # pkg install gnucash 若沒有可用的套件版本，可使用 Port 套件集安裝： # cd /usr/ports/finance/gnucash # make install clean ### 6.5.2. Gnumeric GnumericGNOME 社群所開發的試算表程式。 它的特點是擁有能夠根據儲存格格式 「猜出」使用者的輸入來自動補齊的系統。 它也能夠匯入許多熱門的檔案格式，像是 Excel, Lotus 1-2-3 以及 Quattro Pro。 它有大量內建的函數而且能夠使用常用的儲存格格式，像是：數字、貨幣、日期、時間及其他格式等。 安裝 Gnumeric 套件： # pkg install gnumeric 若沒有可用的套件版本，可使用 Port 套件集安裝： # cd /usr/ports/math/gnumeric # make install clean ### 6.5.3. KMyMoney KMyMoney 是一套個人財務應用程式，由 KDE 社群所開發。KMyMoney 的目標是提供可在商業個人財務管理應用程式中找到的重要功能，它也強調簡單易用及其功能間採用合適的複式記帳。KMyMoney 可從標準 Quicken QIF 檔案匯入資料、追蹤投資、處理多種貨幣並提供財務報表。 要以套件安裝 KMyMoney # pkg install kmymoney-kde4 若沒有可用的套件版本，可使用 Port 套件集安裝： # cd /usr/ports/finance/kmymoney-kde4 # make install clean ## 章 7. 多媒體 Edited by . ## 7.1. 概述 FreeBSD 廣泛地支援各種音效卡， 讓您可以享受來自電腦上的高傳真音質(Hi-Fi)， 此外還包括了錄製和播放 MPEG Audio Layer 3 (MP3)、 Waveform Audio File (WAV)、Ogg Vorbis 以及其他許多種格式聲音的能力。同時 FreeBSD Port 套件集也包含了許多可讓您可以錄音、編修音效以及控制 MIDI 配備的應用程式。 FreeBSD 也能播放一般的視訊檔和 DVD。 FreeBSD Port 套件集中含有可編碼、轉換以及播放格種影像媒體的應用程式。 本章會說明如何設定 FreeBSD 上的音效卡、影像播放器、電視卡及掃描器。同時會說明有那些應用程式可以使用這些裝置。 讀完這章，您將了解： • 設定 FreeBSD 上的音效卡。 • 音效設定疑難排解。 • 播放、錄製 MP3 及其他聲音檔案格式。 • FreeBSD 系統播放影像的準備工具。 • 播放 DVD.mpg.avi 檔。 • 擷取(Rip) CDDVD的內容至檔案。 • 設定電視卡。 • 在 FreeBSD 安裝 MythTV 。 • 設定影像掃描機。 在開始閱讀這章之前，您需要︰ ## 7.2. 設定音效卡 Contributed by . Enhanced by . 開始設定之前，必須先知道你的音效卡型號、晶片為何。 FreeBSD 支援許多種音效卡，請檢查支援的音效硬體表 Hardware Notes，以確認你的音效卡是否支援以及如何在 FreeBSD 上驅動。 要使用音效裝置，必須要載入正確的驅動程式才行。最簡單方式就是以 kldload(8) 來載入核心模組。以下範例示範載入 Intel 規格內建的音效晶片驅動程式。 # kldload snd_hda 要開機時自動載入驅動程式，需將驅動程式加到 /boot/loader.conf 檔，以此驅動程式為例： snd_hda_load="YES" 其他可用的音效卡模組清單列於 /boot/defaults/loader.conf。當不確認要使用何種驅動程式時，可載入 snd_driver 模組： # kldload snd_driver 它是 metadriver 會載入所有最通用的音效驅動程式並且用來加速尋找正確的驅動程式。也可以把 metadriver 加入 /boot/loader.conf 檔來載入所有音效驅動程式。 要知道載入 snd_driver metadriver 後使用了那個音效卡驅動程式，請輸入 cat /dev/sndstat ### 7.2.1. 設定自訂核心支援音效 This section is for users who prefer to statically compile in support for the sound card in a custom kernel. For more information about recompiling a kernel, refer to 章 8, 設定 FreeBSD 核心. When using a custom kernel to provide sound support, make sure that the audio framework driver exists in the custom kernel configuration file: device sound Next, add support for the sound card. To continue the example of the built-in audio chipset based on the Intel specification from the previous section, use the following line in the custom kernel configuration file: device snd_hda Be sure to read the manual page of the driver for the device name to use for the driver. Non-PnP ISA sound cards may require the IRQ and I/O port settings of the card to be added to /boot/device.hints. During the boot process, loader(8) reads this file and passes the settings to the kernel. For example, an old Creative SoundBlaster® 16 ISA non-PnP card will use the snd_sbc(4) driver in conjunction with snd_sb16. For this card, the following lines must be added to the kernel configuration file: device snd_sbc device snd_sb16 If the card uses the 0x220 I/O port and IRQ 5, these lines must also be added to /boot/device.hints: hint.sbc.0.at="isa" hint.sbc.0.port="0x220" hint.sbc.0.irq="5" hint.sbc.0.drq="1" hint.sbc.0.flags="0x15" The syntax used in /boot/device.hints is described in sound(4) and the manual page for the driver of the sound card. The settings shown above are the defaults. In some cases, the IRQ or other settings may need to be changed to match the card. Refer to snd_sbc(4) for more information about this card. ### 7.2.2. 測試音效 After loading the required module or rebooting into the custom kernel, the sound card should be detected. To confirm, run dmesg | grep pcm. This example is from a system with a built-in Conexant CX20590 chipset: pcm0: <NVIDIA (0x001c) (HDMI/DP 8ch)> at nid 5 on hdaa0 pcm1: <NVIDIA (0x001c) (HDMI/DP 8ch)> at nid 6 on hdaa0 pcm2: <Conexant CX20590 (Analog 2.0+HP/2.0)> at nid 31,25 and 35,27 on hdaa1 The status of the sound card may also be checked using this command: # cat /dev/sndstat FreeBSD Audio Driver (newpcm: 64bit 2009061500/amd64) Installed devices: pcm0: <NVIDIA (0x001c) (HDMI/DP 8ch)> (play) pcm1: <NVIDIA (0x001c) (HDMI/DP 8ch)> (play) pcm2: <Conexant CX20590 (Analog 2.0+HP/2.0)> (play/rec) default The output will vary depending upon the sound card. If no pcm devices are listed, double-check that the correct device driver was loaded or compiled into the kernel. The next section lists some common problems and their solutions. If all goes well, the sound card should now work in FreeBSD. If the CD or DVD drive is properly connected to the sound card, one can insert an audio CD in the drive and play it with cdcontrol(1): % cdcontrol -f /dev/acd0 play 1 ### 警告: Audio CDs have specialized encodings which means that they should not be mounted using mount(8). Various applications, such as audio/workman, provide a friendlier interface. The audio/mpg123 port can be installed to listen to MP3 audio files. Another quick way to test the card is to send data to /dev/dsp: % cat filename > /dev/dsp where filename can be any type of file. This command should produce some noise, confirming that the sound card is working. ### 注意: The /dev/dsp* device nodes will be created automatically as needed. When not in use, they do not exist and will not appear in the output of ls(1). ### 7.2.3. 疑難排解音效 表格 7.1, “常見錯誤訊息” lists some common error messages and their solutions: 表格 7.1. 常見錯誤訊息 錯誤解決方式 sb_dspwr(XX) timed out The I/O port is not set correctly. bad irq XX The IRQ is set incorrectly. Make sure that the set IRQ and the sound IRQ are the same. xxx: gus pcm not attached, out of memory There is not enough available memory to use the device. xxx: can't open /dev/dsp! Type fstat | grep dsp to check if another application is holding the device open. Noteworthy troublemakers are esound and KDE's sound support. Modern graphics cards often come with their own sound driver for use with HDMI. This sound device is sometimes enumerated before the sound card meaning that the sound card will not be used as the default playback device. To check if this is the case, run dmesg and look for pcm. The output looks something like this: ... hdac0: HDA Driver Revision: 20100226_0142 hdac1: HDA Driver Revision: 20100226_0142 hdac0: HDA Codec #0: NVidia (Unknown) hdac0: HDA Codec #1: NVidia (Unknown) hdac0: HDA Codec #2: NVidia (Unknown) hdac0: HDA Codec #3: NVidia (Unknown) pcm0: <HDA NVidia (Unknown) PCM #0 DisplayPort> at cad 0 nid 1 on hdac0 pcm1: <HDA NVidia (Unknown) PCM #0 DisplayPort> at cad 1 nid 1 on hdac0 pcm2: <HDA NVidia (Unknown) PCM #0 DisplayPort> at cad 2 nid 1 on hdac0 pcm3: <HDA NVidia (Unknown) PCM #0 DisplayPort> at cad 3 nid 1 on hdac0 hdac1: HDA Codec #2: Realtek ALC889 pcm4: <HDA Realtek ALC889 PCM #0 Analog> at cad 2 nid 1 on hdac1 pcm5: <HDA Realtek ALC889 PCM #1 Analog> at cad 2 nid 1 on hdac1 pcm6: <HDA Realtek ALC889 PCM #2 Digital> at cad 2 nid 1 on hdac1 pcm7: <HDA Realtek ALC889 PCM #3 Digital> at cad 2 nid 1 on hdac1 ... In this example, the graphics card (NVidia) has been enumerated before the sound card (Realtek ALC889). To use the sound card as the default playback device, change hw.snd.default_unit to the unit that should be used for playback: # sysctl hw.snd.default_unit=n where n is the number of the sound device to use. In this example, it should be 4. Make this change permanent by adding the following line to /etc/sysctl.conf: hw.snd.default_unit=4 ### 7.2.4. 使用多個音效來源 Contributed by . It is often desirable to have multiple sources of sound that are able to play simultaneously. FreeBSD uses Virtual Sound Channels to multiplex the sound card's playback by mixing sound in the kernel. Three sysctl(8) knobs are available for configuring virtual channels: # sysctl dev.pcm.0.play.vchans=4 # sysctl dev.pcm.0.rec.vchans=4 # sysctl hw.snd.maxautovchans=4 This example allocates four virtual channels, which is a practical number for everyday use. Both dev.pcm.0.play.vchans=4 and dev.pcm.0.rec.vchans=4 are configurable after a device has been attached and represent the number of virtual channels pcm0 has for playback and recording. Since the pcm module can be loaded independently of the hardware drivers, hw.snd.maxautovchans indicates how many virtual channels will be given to an audio device when it is attached. Refer to pcm(4) for more information. ### 注意: The number of virtual channels for a device cannot be changed while it is in use. First, close any programs using the device, such as music players or sound daemons. The correct pcm device will automatically be allocated transparently to a program that requests /dev/dsp0. ### 7.2.5. 設定混音器頻道的預設值 Contributed by . The default values for the different mixer channels are hardcoded in the source code of the pcm(4) driver. While sound card mixer levels can be changed using mixer(8) or third-party applications and daemons, this is not a permanent solution. To instead set default mixer values at the driver level, define the appropriate values in /boot/device.hints, as seen in this example: hint.pcm.0.vol="50" This will set the volume channel to a default value of 50 when the pcm(4) module is loaded. ## 7.3. MP3 音樂 Contributed by . This section describes some MP3 players available for FreeBSD, how to rip audio CD tracks, and how to encode and decode MP3s. ### 7.3.1. MP3 播放器 A popular graphical MP3 player is XMMS. It supports Winamp skins and additional plugins. The interface is intuitive, with a playlist, graphic equalizer, and more. Those familiar with Winamp will find XMMS simple to use. On FreeBSD, XMMS can be installed from the multimedia/xmms port or package. The audio/mpg123 package or port provides an alternative, command-line MP3 player. Once installed, specify the MP3 file to play on the command line. If the system has multiple audio devices, the sound device can also be specifed: # mpg123 -a /dev/dsp1.0 Foobar-GreatestHits.mp3 High Performance MPEG 1.0/2.0/2.5 Audio Player for Layers 1, 2 and 3 version 1.18.1; written and copyright by Michael Hipp and others free software (LGPL) without any warranty but with best wishes Playing MPEG stream from Foobar-GreatestHits.mp3 ... MPEG 1.0 layer III, 128 kbit/s, 44100 Hz joint-stereo Additional MP3 players are available in the FreeBSD Ports Collection. ### 7.3.2. 擷取 CD 音軌 Before encoding a CD or CD track to MP3, the audio data on the CD must be ripped to the hard drive. This is done by copying the raw CD Digital Audio (CDDA) data to WAV files. The cdda2wav tool, which is installed with the sysutils/cdrtools suite, can be used to rip audio information from CDs. With the audio CD in the drive, the following command can be issued as root to rip an entire CD into individual, per track, WAV files: # cdda2wav -D 0,1,0 -B In this example, the -D 0,1,0 indicates the SCSI device 0,1,0 containing the CD to rip. Use cdrecord -scanbus to determine the correct device parameters for the system. To rip individual tracks, use -t to specify the track: # cdda2wav -D 0,1,0 -t 7 To rip a range of tracks, such as track one to seven, specify a range: # cdda2wav -D 0,1,0 -t 1+7 To rip from an ATAPI (IDE) CDROM drive, specify the device name in place of the SCSI unit numbers. For example, to rip track 7 from an IDE drive: # cdda2wav -D /dev/acd0 -t 7 Alternately, dd can be used to extract audio tracks on ATAPI drives, as described in 節 17.5.5, “複製音樂 CD. ### 7.3.3. MP3 編碼與解碼 Lame is a popular MP3 encoder which can be installed from the audio/lame port. Due to patent issues, a package is not available. The following command will convert the ripped WAV file audio01.wav to audio01.mp3: # lame -h -b 128 --tt "Foo Song Title" --ta "FooBar Artist" --tl "FooBar Album" \ --ty "2014" --tc "Ripped and encoded by Foo" --tg "Genre" audio01.wav audio01.mp3 The specified 128 kbits is a standard MP3 bitrate while the 160 and 192 bitrates provide higher quality. The higher the bitrate, the larger the size of the resulting MP3. The -h turns on the higher quality but a little slower mode. The options beginning with --t indicate ID3 tags, which usually contain song information, to be embedded within the MP3 file. Additional encoding options can be found in the lame manual page. In order to burn an audio CD from MP3s, they must first be converted to a non-compressed file format. XMMS can be used to convert to the WAV format, while mpg123 can be used to convert to the raw Pulse-Code Modulation (PCM) audio data format. To convert audio01.mp3 using mpg123, specify the name of the PCM file: # mpg123 -s audio01.mp3 > audio01.pcm To use XMMS to convert a MP3 to WAV format, use these steps: 過程 7.1. Converting to WAV Format in XMMS 1. Launch XMMS. 2. Right-click the window to bring up the XMMS menu. 3. Select Preferences under Options. 4. Change the Output Plugin to Disk Writer Plugin. 5. Press Configure. 6. Enter or browse to a directory to write the uncompressed files to. 7. Load the MP3 file into XMMS as usual, with volume at 100% and EQ settings turned off. 8. Press Play. The XMMS will appear as if it is playing the MP3, but no music will be heard. It is actually playing the MP3 to a file. 9. When finished, be sure to set the default Output Plugin back to what it was before in order to listen to MP3s again. Both the WAV and PCM formats can be used with cdrecord. When using WAV files, there will be a small tick sound at the beginning of each track. This sound is the header of the WAV file. The audio/sox port or package can be used to remove the header: % sox -t wav -r 44100 -s -w -c 2 track.wav track.raw Refer to 節 17.5, “建立與使用 CD 媒體” for more information on using a CD burner in FreeBSD. ## 7.4. 影片播放 Contributed by . Before configuring video playback, determine the model and chipset of the video card. While Xorg supports a wide variety of video cards, not all provide good playback performance. To obtain a list of extensions supported by the Xorg server using the card, run xdpyinfo while Xorg is running. It is a good idea to have a short MPEG test file for evaluating various players and options. Since some DVD applications look for DVD media in /dev/dvd by default, or have this device name hardcoded in them, it might be useful to make a symbolic link to the proper device: # ln -sf /dev/cd0 /dev/dvd Due to the nature of devfs(5), manually created links will not persist after a system reboot. In order to recreate the symbolic link automatically when the system boots, add the following line to /etc/devfs.conf: link cd0 dvd DVD decryption invokes certain functions that require write permission to the DVD device. To enhance the shared memory Xorg interface, it is recommended to increase the values of these sysctl(8) variables: kern.ipc.shmmax=67108864 kern.ipc.shmall=32768 ### 7.4.1. 偵測影像處理能力 There are several possible ways to display video under Xorg and what works is largely hardware dependent. Each method described below will have varying quality across different hardware. Common video interfaces include: 1. Xorg: normal output using shared memory. 2. XVideo: an extension to the Xorg interface which allows video to be directly displayed in drawable objects through a special acceleration. This extension provides good quality playback even on low-end machines. The next section describes how to determine if this extension is running. 3. SDL: the Simple Directmedia Layer is a porting layer for many operating systems, allowing cross-platform applications to be developed which make efficient use of sound and graphics. SDL provides a low-level abstraction to the hardware which can sometimes be more efficient than the Xorg interface. On FreeBSD, SDL can be installed using the devel/sdl20 package or port. 4. DGA: the Direct Graphics Access is an Xorg extension which allows a program to bypass the Xorg server and directly alter the framebuffer. Because it relies on a low level memory mapping, programs using it must be run as root. The DGA extension can be tested and benchmarked using dga(1). When dga is running, it changes the colors of the display whenever a key is pressed. To quit, press q. 5. SVGAlib: a low level console graphics layer. #### 7.4.1.1. XVideo To check whether this extension is running, use xvinfo: % xvinfo XVideo is supported for the card if the result is similar to: X-Video Extension version 2.2 screen #0 Adaptor #0: "Savage Streams Engine" number of ports: 1 port base: 43 operations supported: PutImage supported visuals: depth 16, visualID 0x22 depth 16, visualID 0x23 number of attributes: 5 "XV_COLORKEY" (range 0 to 16777215) client settable attribute client gettable attribute (current value is 2110) "XV_BRIGHTNESS" (range -128 to 127) client settable attribute client gettable attribute (current value is 0) "XV_CONTRAST" (range 0 to 255) client settable attribute client gettable attribute (current value is 128) "XV_SATURATION" (range 0 to 255) client settable attribute client gettable attribute (current value is 128) "XV_HUE" (range -180 to 180) client settable attribute client gettable attribute (current value is 0) maximum XvImage size: 1024 x 1024 Number of image formats: 7 id: 0x32595559 (YUY2) guid: 59555932-0000-0010-8000-00aa00389b71 bits per pixel: 16 number of planes: 1 type: YUV (packed) id: 0x32315659 (YV12) guid: 59563132-0000-0010-8000-00aa00389b71 bits per pixel: 12 number of planes: 3 type: YUV (planar) id: 0x30323449 (I420) guid: 49343230-0000-0010-8000-00aa00389b71 bits per pixel: 12 number of planes: 3 type: YUV (planar) id: 0x36315652 (RV16) guid: 52563135-0000-0000-0000-000000000000 bits per pixel: 16 number of planes: 1 type: RGB (packed) depth: 0 red, green, blue masks: 0x1f, 0x3e0, 0x7c00 id: 0x35315652 (RV15) guid: 52563136-0000-0000-0000-000000000000 bits per pixel: 16 number of planes: 1 type: RGB (packed) depth: 0 red, green, blue masks: 0x1f, 0x7e0, 0xf800 id: 0x31313259 (Y211) guid: 59323131-0000-0010-8000-00aa00389b71 bits per pixel: 6 number of planes: 3 type: YUV (packed) id: 0x0 guid: 00000000-0000-0000-0000-000000000000 bits per pixel: 0 number of planes: 0 type: RGB (packed) depth: 1 red, green, blue masks: 0x0, 0x0, 0x0 The formats listed, such as YUV2 and YUV12, are not present with every implementation of XVideo and their absence may hinder some players. If the result instead looks like: X-Video Extension version 2.2 screen #0 no adaptors present XVideo is probably not supported for the card. This means that it will be more difficult for the display to meet the computational demands of rendering video, depending on the video card and processor. ### 7.4.2. 可處理影像的 Port 與套件 This section introduces some of the software available from the FreeBSD Ports Collection which can be used for video playback. #### 7.4.2.1. MPlayer 與 MEncoder MPlayer is a command-line video player with an optional graphical interface which aims to provide speed and flexibility. Other graphical front-ends to MPlayer are available from the FreeBSD Ports Collection. MPlayer can be installed using the multimedia/mplayer package or port. Several compile options are available and a variety of hardware checks occur during the build process. For these reasons, some users prefer to build the port rather than install the package. When compiling the port, the menu options should be reviewed to determine the type of support to compile into the port. If an option is not selected, MPlayer will not be able to display that type of video format. Use the arrow keys and spacebar to select the required formats. When finished, press Enter to continue the port compile and installation. By default, the package or port will build the mplayer command line utility and the gmplayer graphical utility. To encode videos, compile the multimedia/mencoder port. Due to licensing restrictions, a package is not available for MEncoder. The first time MPlayer is run, it will create ~/.mplayer in the user's home directory. This subdirectory contains default versions of the user-specific configuration files. This section describes only a few common uses. Refer to mplayer(1) for a complete description of its numerous options. To play the file testfile.avi, specify the video interfaces with -vo, as seen in the following examples: % mplayer -vo xv testfile.avi % mplayer -vo sdl testfile.avi % mplayer -vo x11 testfile.avi # mplayer -vo dga testfile.avi # mplayer -vo 'sdl:dga' testfile.avi It is worth trying all of these options, as their relative performance depends on many factors and will vary significantly with hardware. To play a DVD, replace testfile.avi with dvd://N -dvd-device DEVICE, where N is the title number to play and DEVICE is the device node for the DVD. For example, to play title 3 from /dev/dvd: # mplayer -vo xv dvd://3 -dvd-device /dev/dvd ### 注意: The default DVD device can be defined during the build of the MPlayer port by including the WITH_DVD_DEVICE=/path/to/desired/device option. By default, the device is /dev/cd0. More details can be found in the port's Makefile.options. To stop, pause, advance, and so on, use a keybinding. To see the list of keybindings, run mplayer -h or read mplayer(1). Additional playback options include -fs -zoom, which engages fullscreen mode, and -framedrop, which helps performance. Each user can add commonly used options to their ~/.mplayer/config like so: vo=xv fs=yes zoom=yes mplayer can be used to rip a DVD title to a .vob. To dump the second title from a DVD: # mplayer -dumpstream -dumpfile out.vob dvd://2 -dvd-device /dev/dvd The output file, out.vob, will be in MPEG format. Anyone wishing to obtain a high level of expertise with UNIX® video should consult mplayerhq.hu/DOCS as it is technically informative. This documentation should be considered as required reading before submitting any bug reports. Before using mencoder, it is a good idea to become familiar with the options described at mplayerhq.hu/DOCS/HTML/en/mencoder.html. There are innumerable ways to improve quality, lower bitrate, and change formats, and some of these options may make the difference between good or bad performance. Improper combinations of command line options can yield output files that are unplayable even by mplayer. Here is an example of a simple copy: % mencoder input.avi -oac copy -ovc copy -o output.avi To rip to a file, use -dumpfile with mplayer. To convert input.avi to the MPEG4 codec with MPEG3 audio encoding, first install the audio/lame port. Due to licensing restrictions, a package is not available. Once installed, type: % mencoder input.avi -oac mp3lame -lameopts br=192 \ -ovc lavc -lavcopts vcodec=mpeg4:vhq -o output.avi This will produce output playable by applications such as mplayer and xine. input.avi can be replaced with dvd://1 -dvd-device /dev/dvd and run as root to re-encode a DVD title directly. Since it may take a few tries to get the desired result, it is recommended to instead dump the title to a file and to work on the file. #### 7.4.2.2. xine 影像播放器 xine is a video player with a reusable base library and a modular executable which can be extended with plugins. It can be installed using the multimedia/xine package or port. In practice, xine requires either a fast CPU with a fast video card, or support for the XVideo extension. The xine video player performs best on XVideo interfaces. By default, the xine player starts a graphical user interface. The menus can then be used to open a specific file. Alternatively, xine may be invoked from the command line by specifying the name of the file to play: % xine -g -p mymovie.avi Refer to xine-project.org/faq for more information and troubleshooting tips. #### 7.4.2.3. Transcode 工具 Transcode provides a suite of tools for re-encoding video and audio files. Transcode can be used to merge video files or repair broken files using command line tools with stdin/stdout stream interfaces. In FreeBSD, Transcode can be installed using the multimedia/transcode package or port. Many users prefer to compile the port as it provides a menu of compile options for specifying the support and codecs to compile in. If an option is not selected, Transcode will not be able to encode that format. Use the arrow keys and spacebar to select the required formats. When finished, press Enter to continue the port compile and installation. This example demonstrates how to convert a DivX file into a PAL MPEG-1 file (PAL VCD): % transcode -i input.avi -V --export_prof vcd-pal -o output_vcd % mplex -f 1 -o output_vcd.mpg output_vcd.m1v output_vcd.mpa The resulting MPEG file, output_vcd.mpg, is ready to be played with MPlayer. The file can be burned on a CD media to create a video CD using a utility such as multimedia/vcdimager or sysutils/cdrdao. In addition to the manual page for transcode, refer to transcoding.org/cgi-bin/transcode for further information and examples. ## 7.5. 電視卡 Original contribution by . Enhanced and adapted by . 電視卡 (TV card) 可以讓您用電腦來看無線、有線電視節目。許多卡都是透過 RCA 或 S-video 輸入端子來接收視訊，而且有些卡還可接收 FM 廣播的功能。 FreeBSD 可透過 bktr(4) 驅動程式，來支援 PCI 介面的電視卡，只要這些卡使用的是 Brooktree Bt848/849/878/879 或 Conexant CN-878/Fusion 878a 視訊擷取晶片。此外，要再確認哪些卡上所附的選台功能是否有支援，可以參考 bktr(4) 說明，以查看所支援的硬體清單。 ### 7.5.1. 載入驅動程式 要用電視卡的話，就要載入 bktr(4) 驅動程式，這個可以透過在 /boot/loader.conf 檔加上下面這一行就可以了： bktr_load="YES" 或者可以將電視卡支援靜態編譯到自訂的核心當中，若要這麼做則可在自訂核心設定檔加入以下行： device bktr device iicbus device iicbb device smbus 之所以要加上這些額外的驅動程式，是因為卡的各組成部分都是透過 I2C 匯流排而相互連接的。接下來，請編譯、安裝新的核心 。 要測試調諧器 (Tuner) 是否被正確的偵測，請先重新啟動系統。電視卡應該會出現在開機訊息檔中，如同此範例： bktr0: <BrookTree 848A> mem 0xd7000000-0xd7000fff irq 10 at device 10.0 on pci0 iicbb0: <I2C bit-banging driver> on bti2c0 iicbus0: <Philips I2C bus> on iicbb0 master-only iicbus1: <Philips I2C bus> on iicbb0 master-only smbus0: <System Management Bus> on bti2c0 bktr0: Pinnacle/Miro TV, Philips SECAM tuner. 該訊息會依硬體不同而有所不同。若必要，可以使用 sysctl(8) 系統偵測的參數或者自訂核心設定選項。例如要強制使用 Philips SECAM 調諧器則可加入下列行至自訂核心設定檔： options OVERRIDE_TUNER=6 或使用 sysctl(8) # sysctl hw.bt848.tuner=6 請參考 bktr(4) 查看 sysctl(8) 可用的參數說明及核心選項。 ### 7.5.2. 好用的應用程式 To use the TV card, install one of the following applications: • multimedia/fxtv provides TV-in-a-window and image/audio/video capture capabilities. • multimedia/xawtv is another TV application with similar features. • audio/xmradio provides an application for using the FM radio tuner of a TV card. More applications are available in the FreeBSD Ports Collection. ### 7.5.3. 疑難排解 If any problems are encountered with the TV card, check that the video capture chip and the tuner are supported by bktr(4) and that the right configuration options were used. For more support or to ask questions about supported TV cards, refer to the freebsd-multimedia mailing list. ## 7.6. MythTV MythTV is a popular, open source Personal Video Recorder (PVR) application. This section demonstrates how to install and setup MythTV on FreeBSD. Refer to mythtv.org/wiki for more information on how to use MythTV. MythTV requires a frontend and a backend. These components can either be installed on the same system or on different machines. The frontend can be installed on FreeBSD using the multimedia/mythtv-frontend package or port. Xorg must also be installed and configured as described in 章 5, X Window 系統. Ideally, this system has a video card that supports X-Video Motion Compensation (XvMC) and, optionally, a Linux Infrared Remote Control (LIRC)-compatible remote. To install both the backend and the frontend on FreeBSD, use the multimedia/mythtv package or port. A MySQL™ database server is also required and should automatically be installed as a dependency. Optionally, this system should have a tuner card and sufficient storage to hold recorded data. ### 7.6.1. 硬體 MythTV uses Video for Linux (V4L) to access video input devices such as encoders and tuners. In FreeBSD, MythTV works best with USB DVB-S/C/T cards as they are well supported by the multimedia/webcamd package or port which provides a V4L userland application. Any Digital Video Broadcasting (DVB) card supported by webcamd should work with MythTV. A list of known working cards can be found at wiki.freebsd.org/WebcamCompat. Drivers are also available for Hauppauge cards in the multimedia/pvr250 and multimedia/pvrxxx ports, but they provide a non-standard driver interface that does not work with versions of MythTV greater than 0.23. Due to licensing restrictions, no packages are available and these two ports must be compiled. The wiki.freebsd.org/HTPC page contains a list of all available DVB drivers. ### 7.6.2. 設定 MythTV 後端 To install MythTV using the port: # cd /usr/ports/multimedia/mythtv # make install Once installed, set up the MythTV database: # mysql -uroot -p < /usr/local/share/mythtv/database/mc.sql Then, configure the backend: # mythtv-setup Finally, start the backend: # echo 'mythbackend_enable="YES"' >> /etc/rc.conf # service mythbackend start ## 7.7. 影像掃描器 Written by . In FreeBSD, access to image scanners is provided by SANE (Scanner Access Now Easy), which is available in the FreeBSD Ports Collection. SANE will also use some FreeBSD device drivers to provide access to the scanner hardware. FreeBSD supports both SCSI and USB scanners. Depending upon the scanner interface, different device drivers are required. Be sure the scanner is supported by SANE prior to performing any configuration. Refer to http://www.sane-project.org/sane-supported-devices.html for more information about supported scanners. This chapter describes how to determine if the scanner has been detected by FreeBSD. It then provides an overview of how to configure and use SANE on a FreeBSD system. ### 7.7.1. 檢查掃描器 The GENERIC kernel includes the device drivers needed to support USB scanners. Users with a custom kernel should ensure that the following lines are present in the custom kernel configuration file: device usb device uhci device ohci device ehci To determine if the USB scanner is detected, plug it in and use dmesg to determine whether the scanner appears in the system message buffer. If it does, it should display a message similar to this: ugen0.2: <EPSON> at usbus0 In this example, an EPSON Perfection® 1650 USB scanner was detected on /dev/ugen0.2. If the scanner uses a SCSI interface, it is important to know which SCSI controller board it will use. Depending upon the SCSI chipset, a custom kernel configuration file may be needed. The GENERIC kernel supports the most common SCSI controllers. Refer to /usr/src/sys/conf/NOTES to determine the correct line to add to a custom kernel configuration file. In addition to the SCSI adapter driver, the following lines are needed in a custom kernel configuration file: device scbus device pass Verify that the device is displayed in the system message buffer: pass2 at aic0 bus 0 target 2 lun 0 pass2: <AGFA SNAPSCAN 600 1.10> Fixed Scanner SCSI-2 device pass2: 3.300MB/s transfers If the scanner was not powered-on at system boot, it is still possible to manually force detection by performing a SCSI bus scan with camcontrol: # camcontrol rescan all Re-scan of bus 0 was successful Re-scan of bus 1 was successful Re-scan of bus 2 was successful Re-scan of bus 3 was successful The scanner should now appear in the SCSI devices list: # camcontrol devlist <IBM DDRS-34560 S97B> at scbus0 target 5 lun 0 (pass0,da0) <IBM DDRS-34560 S97B> at scbus0 target 6 lun 0 (pass1,da1) <AGFA SNAPSCAN 600 1.10> at scbus1 target 2 lun 0 (pass3) <PHILIPS CDD3610 CD-R/RW 1.00> at scbus2 target 0 lun 0 (pass2,cd0) Refer to scsi(4) and camcontrol(8) for more details about SCSI devices on FreeBSD. ### 7.7.2. SANE 設定 The SANE system is split in two parts: the backends (graphics/sane-backends) and the frontends (graphics/sane-frontends or graphics/xsane). The backends provide access to the scanner. Refer to http://www.sane-project.org/sane-supported-devices.html to determine which backend supports the scanner. The frontends provide the graphical scanning interface. graphics/sane-frontends installs xscanimage while graphics/xsane installs xsane. After installing the graphics/sane-backends port or package, use sane-find-scanner to check the scanner detection by the SANE system: # sane-find-scanner -q found SCSI scanner "AGFA SNAPSCAN 600 1.10" at /dev/pass3 The output should show the interface type of the scanner and the device node used to attach the scanner to the system. The vendor and the product model may or may not appear. ### 注意: Some USB scanners require firmware to be loaded. Refer to sane-find-scanner(1) and sane(7) for details. Next, check if the scanner will be identified by a scanning frontend. The SANE backends include scanimage which can be used to list the devices and perform an image acquisition. Use -L to list the scanner devices. The first example is for a SCSI scanner and the second is for a USB scanner: # scanimage -L device snapscan:/dev/pass3' is a AGFA SNAPSCAN 600 flatbed scanner # scanimage -L device 'epson2:libusb:/dev/usb:/dev/ugen0.2' is a Epson GT-8200 flatbed scanner In this second example, 'epson2:libusb:/dev/usb:/dev/ugen0.2' is the backend name (epson2) and /dev/ugen0.2 is the device node used by the scanner. If scanimage is unable to identify the scanner, this message will appear: # scanimage -L No scanners were identified. If you were expecting something different, check that the scanner is plugged in, turned on and detected by the sane-find-scanner tool (if appropriate). Please read the documentation which came with this software (README, FAQ, manpages). If this happens, edit the backend configuration file in /usr/local/etc/sane.d/ and define the scanner device used. For example, if the undetected scanner model is an EPSON Perfection® 1650 and it uses the epson2 backend, edit /usr/local/etc/sane.d/epson2.conf. When editing, add a line specifying the interface and the device node used. In this case, add the following line: usb /dev/ugen0.2 Save the edits and verify that the scanner is identified with the right backend name and the device node: # scanimage -L device 'epson2:libusb:/dev/usb:/dev/ugen0.2' is a Epson GT-8200 flatbed scanner Once scanimage -L sees the scanner, the configuration is complete and the scanner is now ready to use. While scanimage can be used to perform an image acquisition from the command line, it is often preferable to use a graphical interface to perform image scanning. The graphics/sane-frontends package or port installs a simple but efficient graphical interface, xscanimage. Alternately, xsane, which is installed with the graphics/xsane package or port, is another popular graphical scanning frontend. It offers advanced features such as various scanning modes, color correction, and batch scans. Both of these applications are usable as a GIMP plugin. ### 7.7.3. 掃描器權限 In order to have access to the scanner, a user needs read and write permissions to the device node used by the scanner. In the previous example, the USB scanner uses the device node /dev/ugen0.2 which is really a symlink to the real device node /dev/usb/0.2.0. The symlink and the device node are owned, respectively, by the wheel and operator groups. While adding the user to these groups will allow access to the scanner, it is considered insecure to add a user to wheel. A better solution is to create a group and make the scanner device accessible to members of this group. This example creates a group called usb: # pw groupadd usb Then, make the /dev/ugen0.2 symlink and the /dev/usb/0.2.0 device node accessible to the usb group with write permissions of 0660 or 0664 by adding the following lines to /etc/devfs.rules: [system=5] add path ugen0.2 mode 0660 group usb add path usb/0.2.0 mode 0666 group usb Finally, add the users to usb in order to allow access to the scanner: # pw groupmod usb -m joe For more details refer to pw(8). ## 章 8. 設定 FreeBSD 核心 ## 8.1. 概述 核心 (Kernel) 是 FreeBSD 作業系統最重要的部份之一。它負責記憶體管理、安全控管、網路、硬碟存取等等。 儘管目前 FreeBSD 大多可以用動態設定， 但有時仍需要設定並編譯自訂的核心。 讀完這章，您將了解︰ • 何時需要編譯自訂核心。 • 如何取得硬體資訊。 • 如何量身訂做核心設定檔。 • 如何使用核心設定檔來建立並編譯新的核心。 • 如何安裝新的核心。 • 發生錯誤時如何排除問題。 所有在本章所列出的指令均應以 root 來執行。 ## 8.2. 為何要編譯自訂的核心? 早期的 FreeBSD 的核心 (Kernel) 被戲稱為 “巨石”。因為當時的核心是一個非常大的程式，且只支援固定的硬體裝置，如果您想改變核心的設定，就必須編譯一個新核心並重新開機，才能使用。 現在，大多數在 FreeBSD 核心的功能已採用模組 (Module) 的方式包裝，可以依據需求動態在核心載入或卸載。 這使得核心能夠快速採用新硬體環境的新功能，就叫做模組化核心 (Modular Kernel)。 儘管如此，還是有一些功能因使用到靜態的核心設定須要編譯，因為這些功能與核心緊密結合，無法將做成可動態載入的模組。且部份強調安全性的環境會盡量避免載入與卸載核心模組，且只要將需要的功能靜態的編譯到核心當中。 編譯自訂的核心幾乎是每位進階的 BSD 使用者所必須經歷的過程。儘管這項工作可能比較耗時，但在 FreeBSD 的使用上會有許多好處。 跟必須支援大多數各式硬體的 GENERIC 核心相比的話， 自訂的核心可以更『體貼』，只支援『自己硬體』的部分就好。 自訂核心有許多項優點，如︰ • 加速開機，因為自訂的核心只需要偵測您系統上存在的硬體，所以讓啟動所花的過程更流暢快速。 • 減少記憶體使用，自訂的核心通常會比 GENERIC 核心使用更少的記憶體，這很重要，因為核心必須一直存放在實體記憶體內，會讓其他應用程式無法使用。因此，自訂核心對於記憶體較小的系統來說，發揮很大的作用。 • 支援額外的硬體，自訂的核心可以增加一些 GENERIC 核心沒有提供的硬體支援。 在編譯自訂核心之前，請思考要這麼做的原因，若是因為需要特定硬體的支援，很可能已有既有的模組可以使用。 核心模組會放在 /boot/kernel 並且可使用 kldload(8) 動態載入到執行中的核心。大部份的核心驅動程式都有可載入的模組與操作手冊。例如 ath(4) 無線乙太網路驅動程式在其操作手冊有以下資訊： Alternatively, to load the driver as a module at boot time, place the following line in loader.conf(5): if_ath_load="YES" 加入 if_ath_load="YES"/boot/loader.conf 會於開機期間自動載入這個模組。 部份情況在 /boot/kernel 會沒有相關的模組，這對於某些子系統大多是真的。 ## 8.3. 偵測系統硬體 在編輯核心設定檔之前，建議先調查清楚機器各項硬體資訊。在雙作業系統的環境，也可透過其他作業系統來了解目前機器上的硬體資訊。 舉例來說，Microsoft® 的 裝置管理員 (Device Manager) 內會有目前已安裝的硬體資訊。 ### 注意: 某些版本的 Microsoft® Windows® 會有系統 (System) 圖示可用來進入 裝置管理員 若 FreeBSD 是唯一安裝的作業系統，則可使用 dmesg(8) 來查看開時時系統偵測到的硬體資訊 。FreeBSD 上大多硬體驅動程式都有操作手冊會列出支援的硬體。例如，以下幾行是說 psm(4) 驅動程式偵測到了一隻滑鼠： psm0: <PS/2 Mouse> irq 12 on atkbdc0 psm0: [GIANT-LOCKED] psm0: [ITHREAD] psm0: model Generic PS/2 mouse, device ID 0 因為該硬體存在，此驅動程式便不應該從自訂核心設定檔中移除。 dmesg 輸出的結果未顯示開機偵測硬體的部份，則可改閱讀 /var/run/dmesg.boot 檔案的內容。 另外，也可以透過 pciconf(8) 工具可用來查詢硬體資訊，該工具會列出更詳細的硬體資訊如： % pciconf -lv ath0@pci0:3:0:0: class=0x020000 card=0x058a1014 chip=0x1014168c rev=0x01 hdr=0x00 vendor = 'Atheros Communications Inc.' device = 'AR5212 Atheros AR5212 802.11abg wireless' class = network subclass = ethernet 以上輸出資訊說明 ath 驅動程式已經找到一個無線乙太網路裝置。 man(1) 指令加上 -k 參數，可提供有用的資訊，例如，列出有包含指定關鍵字的手冊頁面清單： # man -k Atheros ath(4) - Atheros IEEE 802.11 wireless network driver ath_hal(4) - Atheros Hardware Access Layer (HAL) 準備好硬體清單之後，參考該清單來確認已安裝的硬體驅動程式在編輯自訂核心設定時沒有被移除。 ## 8.4. 設定檔 為了要建立自訂核心設定檔並編譯自訂核心，必須先安裝完整的 FreeBSD 原始碼樹。 /usr/src/ 目錄不存在或者是空的，代表尚未安裝。原始碼可以使用 Subversion 並依據 節 A.3, “使用 Subversion 中的操作說明來安裝。 完成原始碼完成後，需檢查 /usr/src/sys 內的檔案。該目錄內包含數個子目錄，這些子目錄中包了支援的硬體架構 (Architecture) 如下：amd64, i386, ia64, pc98, powerpc 以及 sparc64。在指定架構目錄中的內容只對該架構有效，其餘部份的程式碼與硬體架構無關，可通用所有平台。每個支援的硬體架構中會有 conf 子目錄，裡面含有供該架構使用的 GENERIC 核心設定檔。 請不要直接對 GENERIC 檔案做編輯。複製該檔案為另一個名稱，並對複製出來的檔案做編輯，習慣上檔名會全部使用大寫字元。當維護多台安裝不同的硬體的 FreeBSD 機器時，將檔名後方加上機器的主機名稱 (Host name) 是個不錯的方法。以下範例使用 amd64 架構的 GENERIC 設定檔建立了一個複本名稱為 MYKERNEL # cd /usr/src/sys/amd64/conf # cp GENERIC MYKERNEL 現在可以使用任何 ASCII 文字編輯器來自訂 MYKERNEL。預設的編輯器為 vi，在 FreeBSD 也內建一個易於初學者使用的編輯器叫做 ee 核心設定檔的格式很簡單，每一行會含有代表裝置 (Device) 或子系統 (Subsystem) 的關鍵字、參數以及簡短的說明。任何在 # 符號之後的文字會被當做註解並且略過。要移除核心對某個裝置或子系統的支援，僅需要在代表該裝置或子系統的行前加上 # 符號。請不要在您還不了解用途的行前加上或移除 # 符號。 ### 警告: 移除對裝置或選項的支援很容易會造成核心損壞。例如，若從核心設定檔 ata(4) 驅動程式，那麼使用 ATA 磁碟驅動程式的系統便會無法開機。因此當您不確定時，請在核心保留該項目的支援。 除了在設定檔中提供的簡短說明之外，尚有其他的說明在 NOTES 檔案中，可在與該架構 GENERIC 相同的目錄底下找到。要查看所有架構通用的選項，請參考 /usr/src/sys/conf/NOTES ### 提示: 當完成自訂的核心設定檔，請備份到 /usr/src 位置之外。 或者，將核心設定檔放在其他地方，然後建立一個符號連結 (Symbolic link) 至該檔案： # cd /usr/src/sys/amd64/conf # mkdir /root/kernels # cp GENERIC /root/kernels/MYKERNEL # ln -s /root/kernels/MYKERNEL 設定檔中可以使用 include 指令 (Directive)。該指令可以引用其他設定檔到目前的設定檔，這讓只需根據現有檔案設定做些微調整時更簡單。若只有少量的額外選項或驅動程式需要設定，該指令可引用 GENERIC 並設定額外增加的選項，如範例所示： include GENERIC ident MYKERNEL options IPFIREWALL options DUMMYNET options IPFIREWALL_DEFAULT_TO_ACCEPT options IPDIVERT 使用此方法，設定檔只含有與 GENERIC 核心不同的部份。當升級有新功能加入 GENERIC 時，也可一併引用，除非特別使用 nooptionsnodevice 選項來排除設定。更詳細的設定檔指令及其說明可在 config(5) 找到。 ### 注意: 要產生含有所有可用選項的設定檔，可以 root 執行以下指令： # cd /usr/src/sys/arch/conf && make LINT ## 8.5. 編譯與安裝自訂核心 完成自訂設定檔的編輯並儲存之後，便可依據以下步驟編譯核心的原始碼： 過程 8.1. 編譯核心 1. 切換至此目錄： # cd /usr/src 2. 指定自訂核心設定檔的名稱來編譯新的核心： # make buildkernel KERNCONF=MYKERNEL 3. 安裝使用指定核心設定檔所編譯的新核心。此指令將會複製新核心到 /boot/kernel/kernel 並將舊核心備份到 /boot/kernel.old/kernel # make installkernel KERNCONF=MYKERNEL 4. 關機並重新開機載入新的核心，若發生錯誤請參考 無法使用核心開機 預設在自訂核心編譯完成後，所有核心模組也同被重新編譯。要快速更新核心或只編譯自訂的模組，需在開始編譯之前先編輯 /etc/make.conf 例如，使用以下變數可指定要編譯的模組清單來替代預設編譯所有模組的設定： MODULES_OVERRIDE = linux acpi 或者，可使用以下變數來從編譯程序中排除要編譯的模組： WITHOUT_MODULES = linux acpi sound 尚有其他可用的變數，請參考 make.conf(5) 取得詳細資訊。 ## 8.6. 如果發生錯誤 當編譯自訂核心時可能發生以下四種類型的問題： config 失敗 config 失敗，會列出不正確的行號。使用以下訊息為例子，需要與 GENERICNOTES 比對來確認第 17 行輸入的內容正確： config: line 17: syntax error make 失敗 make 失敗，通常是因為核心設定檔未提供足夠的資訊讓 config 找到問題。請仔細檢查設定檔，若仍不清楚問題，請寄發電子郵件給 FreeBSD general questions mailing list 並附上核心設定檔。 無法使用核心開機 若新核心無法開機或無法辨識裝置並不要恐慌！幸好，FreeBSD 有良好的機制可以從不相容的核心復原。只需要在 FreeBSD 開機載入程式 (Boot loader) 選擇要用來開機的核心便可，當系統開機選單出現時選擇 Escape to a loader prompt 選項，並在指令提示後輸入 boot kernel.old 或替換為任何其他已經知道可以正常開機的核心名稱。 使用好的核心開機之後，檢查設定檔並嘗試再編譯一次。/var/log/messages 是有用的資源，它在每次成功開機時會記錄核心訊息。同樣的，dmesg(8) 也會印出自本次開機後的核心訊息。 ### 注意: 在排除核心問題時，請確定留有 GENERIC 的複本，或者其他已知可以運作的核心，並使用不同的名稱來確保下次編譯時不會被刪除，這很重要，因此每當新的核心被安裝之後，kernel.old 都會被最後安裝的核心覆寫，有可能會無法開機。盡快，透過重新命名將可運作的核心目錄移動到目前運作的核心目錄。 # mv /boot/kernel /boot/kernel.bad # mv /boot/kernel.good /boot/kernel 核心可運作，但 ps(1) 無法運作 若核心版本與系統工具所編譯的版本不同，例如，有一個核心使用 -CURRENT 的原始碼編譯並安裝在 -RELEASE 的系統上，許多系統狀態指令如 ps(1)vmstat(8) 將會無法運作。要修正此問題，請使用與核心相同版本的原始碼樹 (Source tree) 重新編譯並安裝 World。使用與作業系統其他部份版本不同的核心永遠不會是個好主意。 ## 章 9. 列印 Originally contributed by . 儘管很多人試圖淘汰列印功能，但列印資訊到紙上仍是一個重要的功能。列印由兩個基本元件組成，包含了資料傳送到印表機的方式以及印表機可以理解的資料形式。 ## 9.1. 快速開始 基本的列印功能可以快速設定完成，列印機必須能夠列印純 ASCII 文字。若要列印其他類型的檔案，請參考 節 9.5.3, “過濾器” 1. 建立一個目錄來儲存要被列印的檔案： # mkdir -p /var/spool/lpd/lp # chown daemon:daemon /var/spool/lpd/lp # chmod 770 /var/spool/lpd/lp 2. root 建立 /etc/printcap 內容如下： lp:\ :lp=/dev/unlpt0:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :lf=/var/log/lpd-errs:  此行是針對連接到 USB 埠的印表機：連接到並列或 “印表器 (Printer)” 埠的印表機要使用：:lp=/dev/lpt0:\直接連接到網路的印表機要使用：:lp=:rm=network-printer-name:rp=raw:\替換 network-printer-name 為網路印表機的 DNS 主機名稱。 3. 編輯 /etc/rc.conf 加入下行來開啟 lpd lpd_enable="YES" 啟動服務： # service lpd start Starting lpd. 4. 測試列印： # printf "1. This printer can print.\n2. This is the second line.\n" | lpr ### 提示: 若列印的兩行未從左邊界開始，而是呈現 階梯狀 (Stairstep)，請參考 節 9.5.3.1, “避免在純文字印表機階梯狀列印” 現在可以使用 lpr 來列印文字檔，只要在指令列給序檔案名稱，或者將輸出使用管線符號 (Pipe) 傳送給 lpr % lpr textfile.txt % ls -lh | lpr ## 9.2. 印表機連線 印表機有許多方式可以連接到電腦，小型的桌面印表機會直接連接到電腦的 USB 埠，舊式的印表機會連接到並列 (Parallel) 或 印表機 (Printer) 埠，而有一部份印表機則是直接連接網路，讓印表機能夠給多台電腦共享使用，還有少部分印表機則是連接到較罕見的序列 (Serial) 埠。 FreeBSD 可以與這些類型的印表機溝通。 USB USB 印表機可以連接到電腦上任何可用的 USB 埠。 當 FreeBSD 偵測到 USB 印表機，會建立兩個裝置項目：/dev/ulpt0 以及 /dev/unlpt0，傳送到兩者任一裝置的資料都會被轉發到印表機。在每個列印工作完成後 ulpt0 便會重設 USB 埠，重設 USB 埠可能會在部份印表機造成問題，因此通常可以改使用 unlpt0 裝置。unlpt0 不會重設 USB 埠。 並列 (IEEE-1284) 並列埠裝置使用 /dev/lpt0，此裝置不論印表機是否連接上都會存在，它並不會自動偵測。 供應商已不再採用這種 舊式 連接埠，且有許多電腦甚至已沒有這種連接埠。可以用轉接器來連接並列印表機到 USB 埠，有了轉接器，並列印表機可以被當作 USB 印表機使用。有另一種稱作 列印伺服器 (Print server) 的裝置也可用來連接並列印表機到網路。 序列 (RS-232) 序列埠也是另一種舊式連接埠，已很少用在印表機上，除了某些特殊的應用外，纜線、接頭與需要的佈線方式依需求變化性很大。 內建在主機板的序列埠的序列裝置名稱為 /dev/cuau0/dev/cuau1。也有序列 USB 轉接器可使用，而裝置的的名稱則會是 /dev/cuaU0 要與序列印表機通訊必須知道數個通訊參數，其中最重要的是 傳輸速率 (Baud rate)BPS (Bits Per Second) 以及 同位檢查 (Parity)。數值有數種，但一般序列印表機會使用 的傳輸速率是 9600 且無同位檢查。 網路 網路印表機可直接連接到區域網路。 若印表機透過 DHCP 分配動態位址，則必須要知道 DNS 主機名稱，DNS 應動態更新來讓主機名稱能夠對應到正確的 IP 位址。指定網路印表機一個靜態的 IP 位址可避免這個問題。 大多數網路印表機可以認得使用 LPD 通訊協定所送出的列印工作，列印佇列 (Print queue) 的名稱也會在這時指定。部份印表機會依據使用的佇列來決定處理資料的方式，例如 raw 佇列會列印原始資料，而 text 佇列則會在純文字上增加換行符號 (Carriage return)。 大部份網路印表機也可列印直接傳送到埠號 9100 的資料。 ### 9.2.1. 摘要 有線網路連線通常是安裝最簡單的方式，且可以提供快速的列印。若要直接連接到電腦，較建議使用 USB，由於較快速、簡單。並列連線仍然可以使用，但有纜線長度與速度上的限制。而序列連線則比較難設定，不同型號的纜線佈線方式不同，且通訊參數如傳輸速率及同位檢查增加了複雜性，所幸序列印表機並不多。 ## 9.3. 常見的頁面描述語言 傳送給印表機的資料必須使用印表機能夠理解的語言，這些語言稱為頁面描述語言 (Page Description Languages) 或 PDL ASCII ASCII 文字是傳送資料到印表機最簡單的方式，一個字元對應一個要列印的文字：資料中的 A 會列印一個 A 在頁面。可以使用的格式非常少，沒有辦法選擇字型或者比例間距。強迫使用簡單的純 ASCII 為的是讓文字可以直接從電腦列印只需一點或甚至不需要編碼或轉譯，列印的結果可直接對應傳送的內容。 部份便宜印表機無法列印純 ASCII 文字，這讓這些印表機較難設定。 PostScript® PostScript® 與 ASCII 幾乎相反，與簡單的文字不同，PostScript® 程式語言有一套指令可以繪出最終所要的文件，可以使用不同的字型與圖形，但是，這樣強大的功能是有代價的，繪製頁面需要搛寫程式語言，通常這個程式語言會由應用程式產生，所以使用者是看不到的。 便宜的印表機有時會移除 PostScript® 的相容性來節省成本。 PCL (Printer Command Language) PCLASCII 延伸而來，加入了跳脫序列 (Escape sequence) 來標示格式、選擇字型以及列印圖型。大部份印表機都支援 PCL5，少數支援較新的 PCL6PCLXL，這些後來的版本是 PCL5 的超集合 (Superset)，並可以提供更快的列印速度。 以主機為基礎 (Host-Based) 製造商可能會使用簡單的處理器和較小的記憶體來降低印表機的成本，這些印表機無法列印純文字，相反的，文字與圖形會先在機器上的驅動程式畫完後傳送到印表機。這些稱為以主機為基礎 (Host-based) 的印表機。 驅動程式與以主機為基礎的印表機通訊通常會透過專用或無文件的通訊協定，這讓這些印表機只能在最常用的作業系統上運作。 ### 9.3.1. 轉換 PostScript® 至其他 PDL Port 套件集與 FreeBSD 工具集有許多可以處理 PostScript® 輸出的應用程式，此表整理出了可轉換 PostScript® 成其他常用 PDL 的工具： 表格 9.1. 輸出 PDL 格式 輸出 PDL產生由說明 PCLPCL5print/ghostscript9單色使用 -sDEVICE=ljet4、彩色使用 -sDEVICE=cljet5 PCLXLPCL6print/ghostscript9單色使用 -sDEVICE=pxlmono、彩色使用 -sDEVICE=pxlcolor ESC/P2print/ghostscript9-sDEVICE=uniprint XQXprint/foo2zjs ### 9.3.2. 摘要 要最簡單可以列印，可選擇支援 PostScript® 的印表機。其次則為支援 PCL 的印表機，有了 print/ghostscript 這些印表機也可像原生支援 PostScript® 的印表機一般使用。有直接支援 PostScript® 或 PCL 的印表機通常也會直接支援純 ASCII 文字檔案。 行列式印表機如同典型的噴墨式印表機通常不支援 PostScript® 或 PCL，這種印表機通常可以列印純 ASCII 文字檔案。print/ghostscript 支援部份這種印表機使用的 PDL，不過要在這種印表機上列印完全以圖型為基礎的頁面通常會非常緩慢，由於需要傳送大量的資料並列印。 以主機為基礎的印表機通常較難設定，有些會因為用了專用的 PDL 而無法使用，盡可能避免使用這類的印表機。 有關各種 PDL 的介紹可至 http://www.undocprint.org/formats/page_description_languages。各種型號印表機所使用的特定 PDL 可至 http://www.openprinting.org/printers 查詢。 ## 9.4. 直接列印 對於偶爾列印，檔案可以直接傳送到印表機裝置，無需做任何設定。例如，要傳送一個名稱為 sample.txt 的檔案到 USB 印表機： # cp sample.txt /dev/unlpt0 要直接使用網路印表機列印需看該印表機支援的功能，但大多數會接受埠號 9100 的列印作業，可使用 nc(1) 來完成。要使用 DNS 主機名稱為 netlaser 的印表機列印與上述相同的檔案可： # nc netlaser 9100 < sample.txt ## 9.5. LPD (行列式印表機 Daemon) 在背景列印一個檔案稱作 Spooling，緩衝程式 (Spooler) 讓使用者能夠繼續執行電腦的其他程式而不需要等候印表機緩慢的完成列印工作。 FreeBSD 內含的緩衝程式 (Spooler) 稱作 lpd(8)，而列印工作會使用 lpr(1) 來提交。 ### 9.5.1. 初始設定 建立要用來儲存列印工作的目錄、設定擁有關係以及權限來避免其他使用者可以檢視這些檔案的內容： # mkdir -p /var/spool/lpd/lp # chown daemon:daemon /var/spool/lpd/lp # chmod 770 /var/spool/lpd/lp 印表機會定義在 /etc/printcap，每台印表機項目所包含的詳細資料有名稱、連接的接頭以及各種其他設定。建立 /etc/printcap 使用以下內容： lp:\ :lp=/dev/unlpt0:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :lf=/var/log/lpd-errs:  印表機的名稱。 lpr(1) 會傳送列印工作到 lp 印表機，除非有使用 -P 來指定其他印表機，所以預的印表機名稱應使用 lp 印表機所連接到裝置。替換此行為正確的連線類型，如此處所示。 連線類型/etc/printcap 的裝置項目 USB :lp=/dev/unlpt0:\ 此為不會重設 USB 印表機的裝置，若使用上發生問題，請改使用 ulpt0，這個裝置會在每次使用後重設 USB 埠。 並列 :lp=/dev/lpt0:\ 網路 針對支援 LPD 通訊協定的印表機： :lp=:rm=network-printer-name:rp=raw:\ 針對支援使用埠號 9100 列印的印表機： :lp=9100@network-printer-name:\ 針對兩者皆支援的印表機，請替換 network-printer-name 為網路印表機的 DNS 主機名稱。 序列 :lp=/dev/cuau0:br=9600:pa=none:\ 這些是一般序列印表機連接到主機板序列埠會採用的數值，傳輸速率 (Baud rate) 是 9600 且無同位檢查 (No Parity)。 在列印工作開始時不列印首頁。 不限制列印工作的最大尺寸。 此印表機的緩衝 (Spooling) 目錄路徑，每台印表機會自己使用一個獨立的緩衝 (Spooling) 目錄。 回報此印表機的錯誤的日誌檔。 在建立 /etc/printcap 之後，使用 chkprintcap(8) 測試印表機是否有錯誤： # chkprintcap 在繼續之前修正任何回報的問題。 開啟 /etc/rc.conf 中的 lpd(8) lpd_enable="YES" 啟動服務： # service lpd start ### 9.5.2. 使用 lpr(1) 列印 Documents are sent to the printer with lpr. A file to be printed can be named on the command line or piped into lpr. These two commands are equivalent, sending the contents of doc.txt to the default printer: % lpr doc.txt % cat doc.txt | lpr Printers can be selected with -P. To print to a printer called laser: % lpr -Plaser doc.txt ### 9.5.3. 過濾器 The examples shown so far have sent the contents of a text file directly to the printer. As long as the printer understands the content of those files, output will be printed correctly. Some printers are not capable of printing plain text, and the input file might not even be plain text. Filters allow files to be translated or processed. The typical use is to translate one type of input, like plain text, into a form that the printer can understand, like PostScript® or PCL. Filters can also be used to provide additional features, like adding page numbers or highlighting source code to make it easier to read. The filters discussed here are input filters or text filters. These filters convert the incoming file into different forms. Use su(1) to become root before creating the files. Filters are specified in /etc/printcap with the if= identifier. To use /usr/local/libexec/lf2crlf as a filter, modify /etc/printcap like this: lp:\ :lp=/dev/unlpt0:\ :sh:\ :mx#0:\ :sd=/var/spool/lpd/lp:\ :if=/usr/local/libexec/lf2crlf:\ :lf=/var/log/lpd-errs:  if= identifies the input filter that will be used on incoming text. ### 提示: The backslash line continuation characters at the end of the lines in printcap entries reveal that an entry for a printer is really just one long line with entries delimited by colon characters. An earlier example can be rewritten as a single less-readable line: lp:lp=/dev/unlpt0:sh:mx#0:sd=/var/spool/lpd/lp:if=/usr/local/libexec/lf2crlf:lf=/var/log/lpd-errs: #### 9.5.3.1. 避免在純文字印表機階梯狀列印 Typical FreeBSD text files contain only a single line feed character at the end of each line. These lines will stairstep on a standard printer: A printed file looks like the steps of a staircase scattered by the wind A filter can convert the newline characters into carriage returns and newlines. The carriage returns make the printer return to the left after each line. Create /usr/local/libexec/lf2crlf with these contents: #!/bin/sh CR=$'\r'
/usr/bin/sed -e "s/$/${CR}/g"

Set the permissions and make it executable:

# chmod 555 /usr/local/libexec/lf2crlf

Modify /etc/printcap to use the new filter:

:if=/usr/local/libexec/lf2crlf:\

Test the filter by printing the same plain text file. The carriage returns will cause each line to start at the left side of the page.

#### 9.5.3.2. 使用 print/enscript 在 PostScript® 印表機美化純文字內容

GNU Enscript converts plain text files into nicely-formatted PostScript® for printing on PostScript® printers. It adds page numbers, wraps long lines, and provides numerous other features to make printed text files easier to read. Depending on the local paper size, install either print/enscript-letter or print/enscript-a4 from the Ports Collection.

Create /usr/local/libexec/enscript with these contents:

#!/bin/sh
/usr/local/bin/enscript -o -

Set the permissions and make it executable:

# chmod 555 /usr/local/libexec/enscript

Modify /etc/printcap to use the new filter:

:if=/usr/local/libexec/enscript:\

Test the filter by printing a plain text file.

#### 9.5.3.3. 列印 PostScript® 到 PCL 印表機

Many programs produce PostScript® documents. However, inexpensive printers often only understand plain text or PCL. This filter converts PostScript® files to PCL before sending them to the printer.

Install the Ghostscript PostScript® interpreter, print/ghostscript9, from the Ports Collection.

Create /usr/local/libexec/ps2pcl with these contents:

#!/bin/sh
/usr/local/bin/gs -dSAFER -dNOPAUSE -dBATCH -q -sDEVICE=ljet4 -sOutputFile=- -

Set the permissions and make it executable:

# chmod 555 /usr/local/libexec/ps2pcl

PostScript® input sent to this script will be rendered and converted to PCL before being sent on to the printer.

Modify /etc/printcap to use this new input filter:

:if=/usr/local/libexec/ps2pcl:\

Test the filter by sending a small PostScript® program to it:

% printf "%%\!PS \n /Helvetica findfont 18 scalefont setfont \
72 432 moveto (PostScript printing successful.) show showpage \004" | lpr

#### 9.5.3.4. 智慧過濾器

A filter that detects the type of input and automatically converts it to the correct format for the printer can be very convenient. The first two characters of a PostScript® file are usually %!. A filter can detect those two characters. PostScript® files can be sent on to a PostScript® printer unchanged. Text files can be converted to PostScript® with Enscript as shown earlier. Create /usr/local/libexec/psif with these contents:

#!/bin/sh
#
#  psif - Print PostScript or plain text on a PostScript printer
#
first_two_chars=expr "$first_line" : '$$..$$' case "$first_two_chars" in
%!)
# %! : PostScript job, print it.
echo "$first_line" && cat && exit 0 exit 2 ;; *) # otherwise, format with enscript ( echo "$first_line"; cat ) | /usr/local/bin/enscript -o - && exit 0
exit 2
;;
esac

Set the permissions and make it executable:

# chmod 555 /usr/local/libexec/psif

Modify /etc/printcap to use this new input filter:

:if=/usr/local/libexec/psif:\

Test the filter by printing PostScript® and plain text files.

#### 9.5.3.5. 其他智慧過濾器

Writing a filter that detects many different types of input and formats them correctly is challenging. print/apsfilter from the Ports Collection is a smart magic filter that detects dozens of file types and automatically converts them to the PDL understood by the printer. See http://www.apsfilter.org for more details.

### 9.5.4. 多序列

The entries in /etc/printcap are really definitions of queues. There can be more than one queue for a single printer. When combined with filters, multiple queues provide users more control over how their jobs are printed.

As an example, consider a networked PostScript® laser printer in an office. Most users want to print plain text, but a few advanced users want to be able to print PostScript® files directly. Two entries can be created for the same printer in /etc/printcap:

textprinter:\
:lp=9100@officelaser:\
:sh:\
:mx#0:\
:sd=/var/spool/lpd/textprinter:\
:if=/usr/local/libexec/enscript:\
:lf=/var/log/lpd-errs:

psprinter:\
:lp=9100@officelaser:\
:sh:\
:mx#0:\
:sd=/var/spool/lpd/psprinter:\
:lf=/var/log/lpd-errs:

Documents sent to textprinter will be formatted by the /usr/local/libexec/enscript filter shown in an earlier example. Advanced users can print PostScript® files on psprinter, where no filtering is done.

This multiple queue technique can be used to provide direct access to all kinds of printer features. A printer with a duplexer could use two queues, one for ordinary single-sided printing, and one with a filter that sends the command sequence to enable double-sided printing and then sends the incoming file.

### 9.5.5. 監視與控制列印

Several utilities are available to monitor print jobs and check and control printer operation.

#### 9.5.5.1. lpq(1)

lpq(1) shows the status of a user's print jobs. Print jobs from other users are not shown.

Show the current user's pending jobs on a single printer:

% lpq -Plp
Rank   Owner      Job  Files                                 Total Size
1st    jsmith     0    (standard input)                      12792 bytes

Show the current user's pending jobs on all printers:

% lpq -a
lp:
Rank   Owner      Job  Files                                 Total Size
1st    jsmith     1    (standard input)                      27320 bytes

laser:
Rank   Owner      Job  Files                                 Total Size
1st    jsmith     287  (standard input)                      22443 bytes

#### 9.5.5.2. lprm(1)

lprm(1) is used to remove print jobs. Normal users are only allowed to remove their own jobs. root can remove any or all jobs.

Remove all pending jobs from a printer:

# lprm -Plp -
dfA002smithy dequeued
cfA002smithy dequeued
dfA003smithy dequeued
cfA003smithy dequeued
dfA004smithy dequeued
cfA004smithy dequeued

Remove a single job from a printer. lpq(1) is used to find the job number.

% lpq
Rank   Owner      Job  Files                                 Total Size
1st    jsmith     5    (standard input)                      12188 bytes
% lprm -Plp 5
dfA005smithy dequeued
cfA005smithy dequeued

#### 9.5.5.3. lpc(8)

lpc(8) is used to check and modify printer status. lpc is followed by a command and an optional printer name. all can be used instead of a specific printer name, and the command will be applied to all printers. Normal users can view status with lpc(8). Only  class="username">root can use commands which modify printer status.

Show the status of all printers:

% lpc status all
lp:
queuing is enabled
printing is enabled
1 entry in spool area
printer idle
laser:
queuing is enabled
printing is enabled
1 entry in spool area
waiting for laser to come up

Prevent a printer from accepting new jobs, then begin accepting new jobs again:

# lpc disable lp
lp:
queuing disabled
# lpc enable lp
lp:
queuing enabled

Stop printing, but continue to accept new jobs. Then begin printing again:

# lpc stop lp
lp:
printing disabled
# lpc start lp
lp:
printing enabled
daemon started

Restart a printer after some error condition:

# lpc restart lp
lp:
no daemon to abort
printing enabled
daemon restarted

Turn the print queue off and disable printing, with a message to explain the problem to users:

# lpc down lp Repair parts will arrive on Monday
lp:
printer and queuing disabled
status message is now: Repair parts will arrive on Monday

Re-enable a printer that is down:

# lpc up lp
lp:
printing enabled
daemon started

See lpc(8) for more commands and options.

### 9.5.6. 分享印表機

Printers are often shared by multiple users in businesses and schools. Additional features are provided to make sharing printers more convenient.

#### 9.5.6.1. 別名

The printer name is set in the first line of the entry in /etc/printcap. Additional names, or aliases, can be added after that name. Aliases are separated from the name and each other by vertical bars:

lp|repairsprinter|salesprinter:\

Aliases can be used in place of the printer name. For example, users in the Sales department print to their printer with

% lpr -Psalesprinter sales-report.txt

Users in the Repairs department print to their printer with

% lpr -Prepairsprinter repairs-report.txt

All of the documents print on that single printer. When the Sales department grows enough to need their own printer, the alias can be removed from the shared printer entry and used as the name of a new printer. Users in both departments continue to use the same commands, but the Sales documents are sent to the new printer.

#### 9.5.6.2. 頁首

It can be difficult for users to locate their documents in the stack of pages produced by a busy shared printer. Header pages were created to solve this problem. A header page with the user name and document name is printed before each print job. These pages are also sometimes called banner or separator pages.

Enabling header pages differs depending on whether the printer is connected directly to the computer with a USB, parallel, or serial cable, or is connected remotely over a network.

Header pages on directly-connected printers are enabled by removing the :sh:\ (Suppress Header) line from the entry in /etc/printcap. These header pages only use line feed characters for new lines. Some printers will need the /usr/share/examples/printing/hpif filter to prevent stairstepped text. The filter configures PCL printers to print both carriage returns and line feeds when a line feed is received.

Header pages for network printers must be configured on the printer itself. Header page entries in /etc/printcap are ignored. Settings are usually available from the printer front panel or a configuration web page accessible with a web browser.

### 9.5.7. 參考文獻

Example files: /usr/share/examples/printing/.

The 4.3BSD Line Printer Spooler Manual, /usr/share/doc/smm/07.lpd/paper.ascii.gz.

Manual pages: printcap(5), lpd(8), lpr(1), lpc(8), lprm(1), lpq(1).

## 9.6. 其他列印系統

Several other printing systems are available in addition to the built-in lpd(8). These systems offer support for other protocols or additional features.

### 9.6.1. CUPS (Common UNIX® Printing System)

CUPS is a popular printing system available on many operating systems. Using CUPS on FreeBSD is documented in a separate article:../../../../doc/en_US.ISO8859-1/articles/cups

### 9.6.2. HPLIP

Hewlett Packard provides a printing system that supports many of their inkjet and laser printers. The port is print/hplip. The main web page is at http://hplipopensource.com/hplip-web/index.html. The port handles all the installation details on FreeBSD. Configuration information is shown at http://hplipopensource.com/hplip-web/install/manual/hp_setup.html.

### 9.6.3. LPRng

LPRng was developed as an enhanced alternative to lpd(8). The port is sysutils/LPRng. For details and documentation, see http://www.lprng.com/.

## 章 10. Linux® Binary 相容性

Restructured and parts updated by .
Originally contributed by and .

## 10.1. 概述

FreeBSD 提供 Linux® Binary 的相容性，允許使用者在 FreeBSD 系統上不需要修改就可以安裝和執行大部份的 Linux® Binary。 曾經有報告指出，在某些情況下，Linux® Binary 在 FreeBSD 的表現比在 Linux® 好。

### 注意:

FreeBSD 10.3 後支援 64 位元的 Linux® Binary 相容性。

• 如何在 FreeBSD 系統啟用 Linux® Binary 相容模式。

• 如何安裝其他的 Linux® 共用程式庫。

• 如何在 FreeBSD 系統安裝 Linux® 應用程式。

• 在 FreeBSD 中 Linux® 相容性的實作細節。

## 10.2. 設定 Linux® Binary 相容性

Linux® 程式庫預設並不會安裝，且並不會開啟 Linux® Binary 相容性。 Linux® 程式庫可以手動安裝或是從 FreeBSD Port 套件集安裝。

# kldload linux

For 64-bit compatibility:

# kldload linux64

% kldstat
1    2 0xc0100000 16bdb8   kernel
7    1 0xc24db000 d000     linux.ko

# printf "compat.linux.osrelease=2.6.18\n" >> /etc/sysctl.conf
# sysctl compat.linux.osrelease=2.6.18
# pkg install emulators/linux_base-c6

linux_enable="YES"

On 64-bit machines, /etc/rc.d/abi will automatically load the module for 64-bit emulation.

### 10.2.1. 手動安裝其他程式庫

Linux® 系統，可使用 ldd 來找出應用程式需要哪個共用程式庫。 例如，檢查 linuxdoom 需要哪個共用程式庫，在有安裝 DoomLinux® 系統執行這個指令：

% ldd linuxdoom
libXt.so.3 (DLL Jump 3.1) => /usr/X11/lib/libXt.so.3.1.0
libX11.so.3 (DLL Jump 3.1) => /usr/X11/lib/libX11.so.3.1.0
libc.so.4 (DLL Jump 4.5pl26) => /lib/libc.so.4.6.29

/compat/linux/usr/X11/lib/libXt.so.3.1.0
/compat/linux/usr/X11/lib/libXt.so.3 -> libXt.so.3.1.0
/compat/linux/usr/X11/lib/libX11.so.3.1.0
/compat/linux/usr/X11/lib/libX11.so.3 -> libX11.so.3.1.0
/compat/linux/lib/libc.so.4.6.29
/compat/linux/lib/libc.so.4 -> libc.so.4.6.29

Linux® 共用程式庫已經存在，並符合 ldd 輸出結果第一欄的主要修訂版號，則不需要複製該行最後一欄的檔案，使用既有的程式庫應可運作。若有較新的版本建議仍要複製共用程式庫，只要符號連結指向新版的程式庫，舊版便可移除。

/compat/linux/lib/libc.so.4.6.27
/compat/linux/lib/libc.so.4 -> libc.so.4.6.27

ldd 顯示 Binary 需要使用較新的版本：

libc.so.4 (DLL Jump 4.5pl26) -> libc.so.4.6.29

/compat/linux/lib/libc.so.4.6.29
/compat/linux/lib/libc.so.4 -> libc.so.4.6.29

### 10.2.2. 安裝 Linux® ELF Binary

ELF Binary 有時候需要額外的步驟。當執行無商標 (Unbranded) 的 ELF Binary，會產生錯誤訊息：

% ./my-linux-elf-binary
ELF binary type not known
Abort

% brandelf -t Linux my-linux-elf-binary

### 10.2.3. 安裝以 Linux® RPM 為基礎的應用程式

# cd /compat/linux
# rpm2cpio < /path/to/linux.archive.rpm | cpio -id

### 10.2.4. 設定主機名稱解析器

resolv+: "bind" is an invalid keyword resolv+:
"hosts" is an invalid keyword

/compat/linux/etc/host.conf 設定如下：

order hosts, bind
multi on

## 10.3. 進階主題

This section describes how Linux® binary compatibility works and is based on an email written to FreeBSD chat mailing list by Terry Lambert (Message ID: <199906020108.SAA07001@usr09.primenet.com>).

FreeBSD has an abstraction called an execution class loader. This is a wedge into the execve(2) system call.

Historically, the UNIX® loader examined the magic number (generally the first 4 or 8 bytes of the file) to see if it was a binary known to the system, and if so, invoked the binary loader.

If it was not the binary type for the system, the execve(2) call returned a failure, and the shell attempted to start executing it as shell commands. The assumption was a default of whatever the current shell is.

Later, a hack was made for sh(1) to examine the first two characters, and if they were :\n, it invoked the csh(1) shell instead.

FreeBSD has a list of loaders, instead of a single loader, with a fallback to the #! loader for running shell interpreters or shell scripts.

For the Linux® ABI support, FreeBSD sees the magic number as an ELF binary. The ELF loader looks for a specialized brand, which is a comment section in the ELF image, and which is not present on SVR4/Solaris™ ELF binaries.

For Linux® binaries to function, they must be branded as type Linux using brandelf(1):

# brandelf -t Linux file

When the ELF loader sees the Linux brand, the loader replaces a pointer in the proc structure. All system calls are indexed through this pointer. In addition, the process is flagged for special handling of the trap vector for the signal trampoline code, and several other (minor) fix-ups that are handled by the Linux® kernel module.

The Linux® system call vector contains, among other things, a list of sysent[] entries whose addresses reside in the kernel module.

When a system call is called by the Linux® binary, the trap code dereferences the system call function pointer off the proc structure, and gets the Linux®, not the FreeBSD, system call entry points.

Linux® mode dynamically reroots lookups. This is, in effect, equivalent to the union option to file system mounts. First, an attempt is made to lookup the file in /compat/linux/original-path. If that fails, the lookup is done in /original-path. This makes sure that binaries that require other binaries can run. For example, the Linux® toolchain can all run under Linux® ABI support. It also means that the Linux® binaries can load and execute FreeBSD binaries, if there are no corresponding Linux® binaries present, and that a uname(1) command can be placed in the /compat/linux directory tree to ensure that the Linux® binaries cannot tell they are not running on Linux®.

In effect, there is a Linux® kernel in the FreeBSD kernel. The various underlying functions that implement all of the services provided by the kernel are identical to both the FreeBSD system call table entries, and the Linux® system call table entries: file system operations, virtual memory operations, signal delivery, and System V IPC. The only difference is that FreeBSD binaries get the FreeBSD glue functions, and Linux® binaries get the Linux® glue functions. The FreeBSD glue functions are statically linked into the kernel, and the Linux® glue functions can be statically linked, or they can be accessed via a kernel module.

Technically, this is not really emulation, it is an ABI implementation. It is sometimes called Linux® emulation because the implementation was done at a time when there was no other word to describe what was going on. Saying that FreeBSD ran Linux® binaries was not true, since the code was not compiled in.

# 部 III. 系統管理

## 章 11. 設定與調校

Written by .
Based on a tutorial written by .
Also based on tuning(7) written by .

## 11.1. 概述

• rc.conf 設定的基礎概念及 /usr/local/etc/rc.d 啟動 Script。

• 如何設定並測試網路卡。

• 如何在網路裝置上設定虛擬主機。

• 如何使用在 /etc 中的各種設定檔。

• 如何使用 sysctl(8) 變數調校 FreeBSD。

• 如何調校磁碟效能及修改核心限制。

## 11.2. 啟動服務

Contributed by .

Many users install third party software on FreeBSD from the Ports Collection and require the installed services to be started upon system initialization. Services, such as mail/postfix or www/apache22 are just two of the many software packages which may be started during system initialization. This section explains the procedures available for starting third party software.

In FreeBSD, most included services, such as cron(8), are started through the system start up scripts.

### 11.2.1. 延伸應用程式設定

Now that FreeBSD includes rc.d, configuration of application startup is easier and provides more features. Using the key words discussed in 節 11.4, “管理 FreeBSD 中的服務”, applications can be set to start after certain other services and extra flags can be passed through /etc/rc.conf in place of hard coded flags in the start up script. A basic script may look similar to the following:

#!/bin/sh
#
# PROVIDE: utility
# REQUIRE: DAEMON
# KEYWORD: shutdown

. /etc/rc.subr

name=utility
rcvar=utility_enable

command="/usr/local/sbin/utility"

load_rc_config $name # # DO NOT CHANGE THESE DEFAULT VALUES HERE # SET THEM IN THE /etc/rc.conf FILE # utility_enable=${utility_enable-"NO"}
pidfile=${utility_pidfile-"/var/run/utility.pid"} run_rc_command "$1"

This script will ensure that the provided utility will be started after the DAEMON pseudo-service. It also provides a method for setting and tracking the process ID (PID).

This application could then have the following line placed in /etc/rc.conf:

utility_enable="YES"

This method allows for easier manipulation of command line arguments, inclusion of the default functions provided in /etc/rc.subr, compatibility with rcorder(8), and provides for easier configuration via rc.conf.

### 11.2.2. 使用服務來啟動其他服務

Other services can be started using inetd(8). Working with inetd(8) and its configuration is described in depth in 節 28.2, “inetd 超級伺服器”.

In some cases, it may make more sense to use cron(8) to start system services. This approach has a number of advantages as cron(8) runs these processes as the owner of the crontab(5). This allows regular users to start and maintain their own applications.

The @reboot feature of cron(8), may be used in place of the time specification. This causes the job to run when cron(8) is started, normally during system initialization.

## 11.3. 設定 cron(8)

Contributed by .

One of the most useful utilities in FreeBSD is cron. This utility runs in the background and regularly checks /etc/crontab for tasks to execute and searches /var/cron/tabs for custom crontab files. These files are used to schedule tasks which cron runs at the specified times. Each entry in a crontab defines a task to run and is known as a cron job.

Two different types of configuration files are used: the system crontab, which should not be modified, and user crontabs, which can be created and edited as needed. The format used by these files is documented in crontab(5). The format of the system crontab, /etc/crontab includes a who column which does not exist in user crontabs. In the system crontab, cron runs the command as the user specified in this column. In a user crontab, all commands run as the user who created the crontab.

User crontabs allow individual users to schedule their own tasks. The root user can also have a user crontab which can be used to schedule tasks that do not exist in the system crontab.

Here is a sample entry from the system crontab, /etc/crontab:

# /etc/crontab - root's crontab for FreeBSD
#
# $FreeBSD: head/zh_TW.UTF-8/books/handbook/book.xml 49533 2016-10-21 14:27:10Z wblock$
#
SHELL=/bin/sh
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin
#
#minute	hour	mday	month	wday	who	command
#
*/5	*	*	*	*	root	/usr/libexec/atrun 
 Lines that begin with the # character are comments. A comment can be placed in the file as a reminder of what and why a desired action is performed. Comments cannot be on the same line as a command or else they will be interpreted as part of the command; they must be on a new line. Blank lines are ignored. The equals (=) character is used to define any environment settings. In this example, it is used to define the SHELL and PATH. If the SHELL is omitted, cron will use the default Bourne shell. If the PATH is omitted, the full path must be given to the command or script to run. This line defines the seven fields used in a system crontab: minute, hour, mday, month, wday, who, and command. The minute field is the time in minutes when the specified command will be run, the hour is the hour when the specified command will be run, the mday is the day of the month, month is the month, and wday is the day of the week. These fields must be numeric values, representing the twenty-four hour clock, or a *, representing all values for that field. The who field only exists in the system crontab and specifies which user the command should be run as. The last field is the command to be executed. This entry defines the values for this cron job. The */5, followed by several more * characters, specifies that /usr/libexec/atrun is invoked by root every five minutes of every hour, of every day and day of the week, of every month.Commands can include any number of switches. However, commands which extend to multiple lines need to be broken with the backslash “\” continuation character.

### 11.3.1. 建立使用者的 Crontab

To create a user crontab, invoke crontab in editor mode:

% crontab -e

This will open the user's crontab using the default text editor. The first time a user runs this command, it will open an empty file. Once a user creates a crontab, this command will open that file for editing.

It is useful to add these lines to the top of the crontab file in order to set the environment variables and to remember the meanings of the fields in the crontab:

SHELL=/bin/sh
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin
# Order of crontab fields
# minute	hour	mday	month	wday	command

Then add a line for each command or script to run, specifying the time to run the command. This example runs the specified custom Bourne shell script every day at two in the afternoon. Since the path to the script is not specified in PATH, the full path to the script is given:

0	14	*	*	*	/usr/home/dru/bin/mycustomscript.sh

### 提示:

Before using a custom script, make sure it is executable and test it with the limited set of environment variables set by cron. To replicate the environment that would be used to run the above cron entry, use:

env -i SHELL=/bin/sh PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin HOME=/home/dru LOGNAME=dru /usr/home/dru/bin/mycustomscript.sh

The environment set by cron is discussed in crontab(5). Checking that scripts operate correctly in a cron environment is especially important if they include any commands that delete files using wildcards.

When finished editing the crontab, save the file. It will automatically be installed and cron will read the crontab and run its cron jobs at their specified times. To list the cron jobs in a crontab, use this command:

% crontab -l
0	14	*	*	*	/usr/home/dru/bin/mycustomscript.sh

To remove all of the cron jobs in a user crontab:

% crontab -r
remove crontab for dru? y

## 11.4. 管理 FreeBSD 中的服務

Contributed by .

FreeBSD uses the rc(8) system of startup scripts during system initialization and for managing services. The scripts listed in /etc/rc.d provide basic services which can be controlled with the start, stop, and restart options to service(8). For instance, sshd(8) can be restarted with the following command:

# service sshd restart

This procedure can be used to start services on a running system. Services will be started automatically at boot time as specified in rc.conf(5). For example, to enable natd(8) at system startup, add the following line to /etc/rc.conf:

natd_enable="YES"

If a natd_enable="NO" line is already present, change the NO to YES. The rc(8) scripts will automatically load any dependent services during the next boot, as described below.

Since the rc(8) system is primarily intended to start and stop services at system startup and shutdown time, the start, stop and restart options will only perform their action if the appropriate /etc/rc.conf variable is set. For instance, sshd restart will only work if sshd_enable is set to YES in /etc/rc.conf. To start, stop or restart a service regardless of the settings in /etc/rc.conf, these commands should be prefixed with one. For instance, to restart sshd(8) regardless of the current /etc/rc.conf setting, execute the following command:

# service sshd onerestart

To check if a service is enabled in /etc/rc.conf, run the appropriate rc(8) script with rcvar. This example checks to see if sshd(8) is enabled in /etc/rc.conf:

# service sshd rcvar
# sshd
#
sshd_enable="YES"
#   (default: "")

### 注意:

The # sshd line is output from the above command, not a root console.

To determine whether or not a service is running, use status. For instance, to verify that sshd(8) is running:

# service sshd status
sshd is running as pid 433.

In some cases, it is also possible to reload a service. This attempts to send a signal to an individual service, forcing the service to reload its configuration files. In most cases, this means sending the service a SIGHUP signal. Support for this feature is not included for every service.

The rc(8) system is used for network services and it also contributes to most of the system initialization. For instance, when the /etc/rc.d/bgfsck script is executed, it prints out the following message:

Starting background file system checks in 60 seconds.

This script is used for background file system checks, which occur only during system initialization.

Many system services depend on other services to function properly. For example, yp(8) and other RPC-based services may fail to start until after the rpcbind(8) service has started. To resolve this issue, information about dependencies and other meta-data is included in the comments at the top of each startup script. The rcorder(8) program is used to parse these comments during system initialization to determine the order in which system services should be invoked to satisfy the dependencies.

The following key word must be included in all startup scripts as it is required by rc.subr(8) to enable the startup script:

• PROVIDE: Specifies the services this file provides.

The following key words may be included at the top of each startup script. They are not strictly necessary, but are useful as hints to rcorder(8):

• REQUIRE: Lists services which are required for this service. The script containing this key word will run after the specified services.

• BEFORE: Lists services which depend on this service. The script containing this key word will run before the specified services.

By carefully setting these keywords for each startup script, an administrator has a fine-grained level of control of the startup order of the scripts, without the need for runlevels used by some UNIX® operating systems.

Additional information can be found in rc(8) and rc.subr(8). Refer to this article for instructions on how to create custom rc(8) scripts.

### 11.4.1. 管理特定系統的設定

The principal location for system configuration information is /etc/rc.conf. This file contains a wide range of configuration information and it is read at system startup to configure the system. It provides the configuration information for the rc* files.

The entries in /etc/rc.conf override the default settings in /etc/defaults/rc.conf. The file containing the default settings should not be edited. Instead, all system-specific changes should be made to /etc/rc.conf.

A number of strategies may be applied in clustered applications to separate site-wide configuration from system-specific configuration in order to reduce administration overhead. The recommended approach is to place system-specific configuration into /etc/rc.conf.local. For example, these entries in /etc/rc.conf apply to all systems:

sshd_enable="YES"
keyrate="fast"
defaultrouter="10.1.1.254"

Whereas these entries in /etc/rc.conf.local apply to this system only:

hostname="node1.example.org"
ifconfig_fxp0="inet 10.1.1.1/8"

Distribute /etc/rc.conf to every system using an application such as rsync or puppet, while /etc/rc.conf.local remains unique.

Upgrading the system will not overwrite /etc/rc.conf, so system configuration information will not be lost.

### 提示:

Both /etc/rc.conf and /etc/rc.conf.local are parsed by sh(1). This allows system operators to create complex configuration scenarios. Refer to rc.conf(5) for further information on this topic.

## 11.5. 設定網路介面卡

Contributed by .

### 11.5.1. 找到正確的驅動程式

First, determine the model of the NIC and the chip it uses. FreeBSD supports a wide variety of NICs. Check the Hardware Compatibility List for the FreeBSD release to see if the NIC is supported.

If the NIC is supported, determine the name of the FreeBSD driver for the NIC. Refer to /usr/src/sys/conf/NOTES and /usr/src/sys/arch/conf/NOTES for the list of NIC drivers with some information about the supported chipsets. When in doubt, read the manual page of the driver as it will provide more information about the supported hardware and any known limitations of the driver.

The drivers for common NICs are already present in the GENERIC kernel, meaning the NIC should be probed during boot. The system's boot messages can be viewed by typing more /var/run/dmesg.boot and using the spacebar to scroll through the text. In this example, two Ethernet NICs using the dc(4) driver are present on the system:

dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38
000ff irq 15 at device 11.0 on pci0
miibus0: <MII bus> on dc0
bmtphy0: <BCM5201 10/100baseTX PHY> PHY 1 on miibus0
bmtphy0:  10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto
dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30
000ff irq 11 at device 12.0 on pci0
miibus1: <MII bus> on dc1
bmtphy1: <BCM5201 10/100baseTX PHY> PHY 1 on miibus1
bmtphy1:  10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto
dc1: [ITHREAD]

If the driver for the NIC is not present in GENERIC, but a driver is available, the driver will need to be loaded before the NIC can be configured and used. This may be accomplished in one of two ways:

• The easiest way is to load a kernel module for the NIC using kldload(8). To also automatically load the driver at boot time, add the appropriate line to /boot/loader.conf. Not all NIC drivers are available as modules.

• Alternatively, statically compile support for the NIC into a custom kernel. Refer to /usr/src/sys/conf/NOTES, /usr/src/sys/arch/conf/NOTES and the manual page of the driver to determine which line to add to the custom kernel configuration file. For more information about recompiling the kernel, refer to 章 8, 設定 FreeBSD 核心. If the NIC was detected at boot, the kernel does not need to be recompiled.

#### 11.5.1.1. 使用 Windows® NDIS 驅動程式

Unfortunately, there are still many vendors that do not provide schematics for their drivers to the open source community because they regard such information as trade secrets. Consequently, the developers of FreeBSD and other operating systems are left with two choices: develop the drivers by a long and pain-staking process of reverse engineering or using the existing driver binaries available for Microsoft® Windows® platforms.

FreeBSD provides native support for the Network Driver Interface Specification (NDIS). It includes ndisgen(8) which can be used to convert a Windows® XP driver into a format that can be used on FreeBSD. Because the ndis(4) driver uses a Windows® XP binary, it only runs on i386™ and amd64 systems. PCI, CardBus, PCMCIA, and USB devices are supported.

To use ndisgen(8), three things are needed:

1. FreeBSD kernel sources.

2. A Windows® XP driver binary with a .SYS extension.

3. A Windows® XP driver configuration file with a .INF extension.

Download the .SYS and .INF files for the specific NIC. Generally, these can be found on the driver CD or at the vendor's website. The following examples use W32DRIVER.SYS and W32DRIVER.INF.

The driver bit width must match the version of FreeBSD. For FreeBSD/i386, use a Windows® 32-bit driver. For FreeBSD/amd64, a Windows® 64-bit driver is needed.

The next step is to compile the driver binary into a loadable kernel module. As root, use ndisgen(8):

# ndisgen /path/to/W32DRIVER.INF /path/to/W32DRIVER.SYS

This command is interactive and prompts for any extra information it requires. A new kernel module will be generated in the current directory. Use kldload(8) to load the new module:

# kldload ./W32DRIVER_SYS.ko

In addition to the generated kernel module, the ndis.ko and if_ndis.ko modules must be loaded. This should happen automatically when any module that depends on ndis(4) is loaded. If not, load them manually, using the following commands:

# kldload ndis
# kldload if_ndis

The first command loads the ndis(4) miniport driver wrapper and the second loads the generated NIC driver.

Check dmesg(8) to see if there were any load errors. If all went well, the output should be similar to the following:

ndis0: <Wireless-G PCI Adapter> mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1
ndis0: NDIS API version: 5.0
ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps
ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps

From here, ndis0 can be configured like any other NIC.

To configure the system to load the ndis(4) modules at boot time, copy the generated module, W32DRIVER_SYS.ko, to /boot/modules. Then, add the following line to /boot/loader.conf:

W32DRIVER_SYS_load="YES"

### 11.5.2. 設定網路卡

Once the right driver is loaded for the NIC, the card needs to be configured. It may have been configured at installation time by bsdinstall(8).

To display the NIC configuration, enter the following command:

% ifconfig
dc0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
ether 00:a0:cc:da:da:da
media: Ethernet autoselect (100baseTX <full-duplex>)
status: active
dc1: flags=8802<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
ether 00:a0:cc:da:da:db
media: Ethernet 10baseT/UTP
status: no carrier
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> metric 0 mtu 16384
options=3<RXCSUM,TXCSUM>
inet6 fe80::1%lo0 prefixlen 64 scopeid 0x4
inet6 ::1 prefixlen 128
nd6 options=3<PERFORMNUD,ACCEPT_RTADV>

In this example, the following devices were displayed:

• dc0: The first Ethernet interface.

• dc1: The second Ethernet interface.

• lo0: The loopback device.

FreeBSD uses the driver name followed by the order in which the card is detected at boot to name the NIC. For example, sis2 is the third NIC on the system using the sis(4) driver.

In this example, dc0 is up and running. The key indicators are:

1. UP means that the card is configured and ready.

2. The card has an Internet (inet) address, 192.168.1.3.

3. It has a valid subnet mask (netmask), where 0xffffff00 is the same as 255.255.255.0.

4. It has a valid broadcast address, 192.168.1.255.

5. The MAC address of the card (ether) is 00:a0:cc:da:da:da.

6. The physical media selection is on autoselection mode (media: Ethernet autoselect (100baseTX <full-duplex>)). In this example, dc1 is configured to run with 10baseT/UTP media. For more information on available media types for a driver, refer to its manual page.

7. The status of the link (status) is active, indicating that the carrier signal is detected. For dc1, the status: no carrier status is normal when an Ethernet cable is not plugged into the card.

If the ifconfig(8) output had shown something similar to:

dc0: flags=8843<BROADCAST,SIMPLEX,MULTICAST> metric 0 mtu 1500
ether 00:a0:cc:da:da:da
media: Ethernet autoselect (100baseTX <full-duplex>)
status: active

it would indicate the card has not been configured.

The card must be configured as root. The NIC configuration can be performed from the command line with ifconfig(8) but will not persist after a reboot unless the configuration is also added to /etc/rc.conf. If a DHCP server is present on the LAN, just add this line:

ifconfig_dc0="DHCP"

Replace dc0 with the correct value for the system.

The line added, then, follow the instructions given in 節 11.5.3, “測試與疑難排解”.

### 注意:

If the network was configured during installation, some entries for the NIC(s) may be already present. Double check /etc/rc.conf before adding any lines.

In the case, there is no DHCP server, the NIC(s) have to be configured manually. Add a line for each NIC present on the system, as seen in this example:

ifconfig_dc0="inet 192.168.1.3 netmask 255.255.255.0"
ifconfig_dc1="inet 10.0.0.1 netmask 255.255.255.0 media 10baseT/UTP"

Replace dc0 and dc1 and the IP address information with the correct values for the system. Refer to the man page for the driver, ifconfig(8), and rc.conf(5) for more details about the allowed options and the syntax of /etc/rc.conf.

If the network is not using DNS, edit /etc/hosts to add the names and IP addresses of the hosts on the LAN, if they are not already there. For more information, refer to hosts(5) and to /usr/share/examples/etc/hosts.

### 注意:

If there is no DHCP server and access to the Internet is needed, manually configure the default gateway and the nameserver:

# echo 'defaultrouter="your_default_router"' >> /etc/rc.conf
# echo 'nameserver your_DNS_server' >> /etc/resolv.conf

### 11.5.3. 測試與疑難排解

Once the necessary changes to /etc/rc.conf are saved, a reboot can be used to test the network configuration and to verify that the system restarts without any configuration errors. Alternatively, apply the settings to the networking system with this command:

# service netif restart

### 注意:

If a default gateway has been set in /etc/rc.conf, also issue this command:

# service routing restart

Once the networking system has been relaunched, test the NICs.

#### 11.5.3.1. 測試乙太網路卡

To verify that an Ethernet card is configured correctly, ping(8) the interface itself, and then ping(8) another machine on the LAN:

% ping -c5 192.168.1.3
PING 192.168.1.3 (192.168.1.3): 56 data bytes
64 bytes from 192.168.1.3: icmp_seq=0 ttl=64 time=0.082 ms
64 bytes from 192.168.1.3: icmp_seq=1 ttl=64 time=0.074 ms
64 bytes from 192.168.1.3: icmp_seq=2 ttl=64 time=0.076 ms
64 bytes from 192.168.1.3: icmp_seq=3 ttl=64 time=0.108 ms
64 bytes from 192.168.1.3: icmp_seq=4 ttl=64 time=0.076 ms

--- 192.168.1.3 ping statistics ---
5 packets transmitted, 5 packets received, 0% packet loss
round-trip min/avg/max/stddev = 0.074/0.083/0.108/0.013 ms
% ping -c5 192.168.1.2
PING 192.168.1.2 (192.168.1.2): 56 data bytes
64 bytes from 192.168.1.2: icmp_seq=0 ttl=64 time=0.726 ms
64 bytes from 192.168.1.2: icmp_seq=1 ttl=64 time=0.766 ms
64 bytes from 192.168.1.2: icmp_seq=2 ttl=64 time=0.700 ms
64 bytes from 192.168.1.2: icmp_seq=3 ttl=64 time=0.747 ms
64 bytes from 192.168.1.2: icmp_seq=4 ttl=64 time=0.704 ms

--- 192.168.1.2 ping statistics ---
5 packets transmitted, 5 packets received, 0% packet loss
round-trip min/avg/max/stddev = 0.700/0.729/0.766/0.025 ms

To test network resolution, use the host name instead of the IP address. If there is no DNS server on the network, /etc/hosts must first be configured. To this purpose, edit /etc/hosts to add the names and IP addresses of the hosts on the LAN, if they are not already there. For more information, refer to hosts(5) and to /usr/share/examples/etc/hosts.

#### 11.5.3.2. 疑難排解

When troubleshooting hardware and software configurations, check the simple things first. Is the network cable plugged in? Are the network services properly configured? Is the firewall configured correctly? Is the NIC supported by FreeBSD? Before sending a bug report, always check the Hardware Notes, update the version of FreeBSD to the latest STABLE version, check the mailing list archives, and search the Internet.

If the card works, yet performance is poor, read through tuning(7). Also, check the network configuration as incorrect network settings can cause slow connections.

Some users experience one or two device timeout messages, which is normal for some cards. If they continue, or are bothersome, determine if the device is conflicting with another device. Double check the cable connections. Consider trying another card.

To resolve watchdog timeout errors, first check the network cable. Many cards require a PCI slot which supports bus mastering. On some old motherboards, only one PCI slot allows it, usually slot 0. Check the NIC and the motherboard documentation to determine if that may be the problem.

No route to host messages occur if the system is unable to route a packet to the destination host. This can happen if no default route is specified or if a cable is unplugged. Check the output of netstat -rn and make sure there is a valid route to the host. If there is not, read 節 30.2, “通訊閘與路由”.

ping: sendto: Permission denied error messages are often caused by a misconfigured firewall. If a firewall is enabled on FreeBSD but no rules have been defined, the default policy is to deny all traffic, even ping(8). Refer to 章 29, 防火牆 for more information.

Sometimes performance of the card is poor or below average. In these cases, try setting the media selection mode from autoselect to the correct media selection. While this works for most hardware, it may or may not resolve the issue. Again, check all the network settings, and refer to tuning(7).

## 11.6. 虛擬主機

A common use of FreeBSD is virtual site hosting, where one server appears to the network as many servers. This is achieved by assigning multiple network addresses to a single interface.

A given network interface has one real address, and may have any number of alias addresses. These aliases are normally added by placing alias entries in /etc/rc.conf, as seen in this example:

ifconfig_fxp0_alias0="inet xxx.xxx.xxx.xxx netmask xxx.xxx.xxx.xxx"

Alias entries must start with alias0 using a sequential number such as alias0, alias1, and so on. The configuration process will stop at the first missing number.

The calculation of alias netmasks is important. For a given interface, there must be one address which correctly represents the network's netmask. Any other addresses which fall within this network must have a netmask of all 1s, expressed as either 255.255.255.255 or 0xffffffff.

For example, consider the case where the fxp0 interface is connected to two networks: 10.1.1.0 with a netmask of 255.255.255.0 and 202.0.75.16 with a netmask of 255.255.255.240. The system is to be configured to appear in the ranges 10.1.1.1 through 10.1.1.5 and 202.0.75.17 through 202.0.75.20. Only the first address in a given network range should have a real netmask. All the rest (10.1.1.2 through 10.1.1.5 and 202.0.75.18 through 202.0.75.20) must be configured with a netmask of 255.255.255.255.

The following /etc/rc.conf entries configure the adapter correctly for this scenario:

ifconfig_fxp0="inet 10.1.1.1 netmask 255.255.255.0"
ifconfig_fxp0_alias7="inet 202.0.75.20 netmask 255.255.255.255"

A simpler way to express this is with a space-separated list of IP address ranges. The first address will be given the indicated subnet mask and the additional addresses will have a subnet mask of 255.255.255.255.

ifconfig_fxp0_aliases="inet 10.1.1.1-5/24 inet 202.0.75.17-20/28"

## 11.7. 設定系統日誌

Contributed by .

Generating and reading system logs is an important aspect of system administration. The information in system logs can be used to detect hardware and software issues as well as application and system configuration errors. This information also plays an important role in security auditing and incident response. Most system daemons and applications will generate log entries.

FreeBSD provides a system logger, syslogd, to manage logging. By default, syslogd is started when the system boots. This is controlled by the variable syslogd_enable in /etc/rc.conf. There are numerous application arguments that can be set using syslogd_flags in /etc/rc.conf. Refer to syslogd(8) for more information on the available arguments.

This section describes how to configure the FreeBSD system logger for both local and remote logging and how to perform log rotation and log management.

### 11.7.1. 設定本地日誌

The configuration file, /etc/syslog.conf, controls what syslogd does with log entries as they are received. There are several parameters to control the handling of incoming events. The facility describes which subsystem generated the message, such as the kernel or a daemon, and the level describes the severity of the event that occurred. This makes it possible to configure if and where a log message is logged, depending on the facility and level. It is also possible to take action depending on the application that sent the message, and in the case of remote logging, the hostname of the machine generating the logging event.

This configuration file contains one line per action, where the syntax for each line is a selector field followed by an action field. The syntax of the selector field is facility.level which will match log messages from facility at level level or higher. It is also possible to add an optional comparison flag before the level to specify more precisely what is logged. Multiple selector fields can be used for the same action, and are separated with a semicolon (;). Using * will match everything. The action field denotes where to send the log message, such as to a file or remote log host. As an example, here is the default syslog.conf from FreeBSD:

# $FreeBSD: head/zh_TW.UTF-8/books/handbook/book.xml 49533 2016-10-21 14:27:10Z wblock$
#
#       Spaces ARE valid field separators in this file. However,
#       other *nix-like systems still insist on using tabs as field
#       separators. If you are sharing this file between systems, you
#       may want to use only tabs as field separators here.
#       Consult the syslog.conf(5) manpage.
*.err;kern.warning;auth.notice;mail.crit                /dev/console
*.notice;authpriv.none;kern.debug;lpr.info;mail.crit;news.err   /var/log/messages
security.*                                      /var/log/security
auth.info;authpriv.info                         /var/log/auth.log
mail.info                                       /var/log/maillog
lpr.info                                        /var/log/lpd-errs
ftp.info                                        /var/log/xferlog
cron.*                                          /var/log/cron
!-devd
*.=debug                                        /var/log/debug.log
*.emerg                                         *
# uncomment this to log all writes to /dev/console to /var/log/console.log
#console.info                                   /var/log/console.log
# uncomment this to enable logging of all log messages to /var/log/all.log
# touch /var/log/all.log and chmod it to mode 600 before it will work
#*.*                                            /var/log/all.log
# uncomment this to enable logging to a remote loghost named loghost
#*.*                                            @loghost
# uncomment these if you're running inn
# news.crit                                     /var/log/news/news.crit
# news.err                                      /var/log/news/news.err
# news.notice                                   /var/log/news/news.notice
# Uncomment this if you wish to see messages produced by devd
# !devd
# *.>=info
!ppp
*.*                                             /var/log/ppp.log
!*

In this example:

• Line 8 matches all messages with a level of err or higher, as well as kern.warning, auth.notice and mail.crit, and sends these log messages to the console (/dev/console).

• Line 12 matches all messages from the mail facility at level info or above and logs the messages to /var/log/maillog.

• Line 17 uses a comparison flag (=) to only match messages at level debug and logs them to /var/log/debug.log.

• Line 33 is an example usage of a program specification. This makes the rules following it only valid for the specified program. In this case, only the messages generated by ppp are logged to /var/log/ppp.log.

The available levels, in order from most to least critical are emerg, alert, crit, err, warning, notice, info, and debug.

The facilities, in no particular order, are auth, authpriv, console, cron, daemon, ftp, kern, lpr, mail, mark, news, security, syslog, user, uucp, and local0 through local7. Be aware that other operating systems might have different facilities.

To log everything of level notice and higher to /var/log/daemon.log, add the following entry:

daemon.notice                                        /var/log/daemon.log

For more information about the different levels and facilities, refer to syslog(3) and syslogd(8). For more information about /etc/syslog.conf, its syntax, and more advanced usage examples, see syslog.conf(5).

### 11.7.2. 日誌管理與循環

Log files can grow quickly, taking up disk space and making it more difficult to locate useful information. Log management attempts to mitigate this. In FreeBSD, newsyslog is used to manage log files. This built-in program periodically rotates and compresses log files, and optionally creates missing log files and signals programs when log files are moved. The log files may be generated by syslogd or by any other program which generates log files. While newsyslog is normally run from cron(8), it is not a system daemon. In the default configuration, it runs every hour.

To know which actions to take, newsyslog reads its configuration file, /etc/newsyslog.conf. This file contains one line for each log file that newsyslog manages. Each line states the file owner, permissions, when to rotate that file, optional flags that affect log rotation, such as compression, and programs to signal when the log is rotated. Here is the default configuration in FreeBSD:

# configuration file for newsyslog
# $FreeBSD: head/zh_TW.UTF-8/books/handbook/book.xml 49533 2016-10-21 14:27:10Z wblock$
#
# Entries which do not specify the '/pid_file' field will cause the
# syslogd process to be signalled when that log file is rotated.  This
# action is only appropriate for log files which are written to by the
# syslogd process (ie, files listed in /etc/syslog.conf).  If there
# is no process which needs to be signalled when a given log file is
# rotated, then the entry for that file should include the 'N' flag.
#
# The 'flags' field is one or more of the letters: BCDGJNUXZ or a '-'.
#
# Note: some sites will want to select more restrictive protections than the
# defaults.  In particular, it may be desirable to switch many of the 644
# entries to 640 or 600.  For example, some sites will consider the
# contents of maillog, messages, and lpd-errs to be confidential.  In the
# future, these defaults may change to more conservative ones.
#
# logfilename          [owner:group]    mode count size when  flags [/pid_file] [sig_num]
/var/log/all.log                        600  7     *    @T00  J
/var/log/amd.log                        644  7     100  *     J
/var/log/auth.log                       600  7     100  @0101T JC
/var/log/console.log                    600  5     100  *     J
/var/log/cron                           600  3     100  *     JC
/var/log/daily.log                      640  7     *    @T00  JN
/var/log/debug.log                      600  7     100  *     JC
/var/log/kerberos.log                   600  7     100  *     J
/var/log/lpd-errs                       644  7     100  *     JC
/var/log/maillog                        640  7     *    @T00  JC
/var/log/messages                       644  5     100  @0101T JC
/var/log/monthly.log                    640  12    *    $M1D0 JN /var/log/pflog 600 3 100 * JB /var/run/pflogd.pid /var/log/ppp.log root:network 640 3 100 * JC /var/log/devd.log 644 3 100 * JC /var/log/security 600 10 100 * JC /var/log/sendmail.st 640 10 * 168 B /var/log/utx.log 644 3 * @01T05 B /var/log/weekly.log 640 5 1$W6D0 JN
/var/log/xferlog                        600  7     100  *     JC

Each line starts with the name of the log to be rotated, optionally followed by an owner and group for both rotated and newly created files. The mode field sets the permissions on the log file and count denotes how many rotated log files should be kept. The size and when fields tell newsyslog when to rotate the file. A log file is rotated when either its size is larger than the size field or when the time in the when field has passed. An asterisk (*) means that this field is ignored. The flags field gives further instructions, such as how to compress the rotated file or to create the log file if it is missing. The last two fields are optional and specify the name of the Process ID (PID) file of a process and a signal number to send to that process when the file is rotated.

For more information on all fields, valid flags, and how to specify the rotation time, refer to newsyslog.conf(5). Since newsyslog is run from cron(8), it cannot rotate files more often than it is scheduled to run from cron(8).

### 11.7.3. 設定遠端日誌

Contributed by .

Monitoring the log files of multiple hosts can become unwieldy as the number of systems increases. Configuring centralized logging can reduce some of the administrative burden of log file administration.

In FreeBSD, centralized log file aggregation, merging, and rotation can be configured using syslogd and newsyslog. This section demonstrates an example configuration, where host A, named logserv.example.com, will collect logging information for the local network. Host B, named logclient.example.com, will be configured to pass logging information to the logging server.

#### 11.7.3.1. 日誌伺服器設定

A log server is a system that has been configured to accept logging information from other hosts. Before configuring a log server, check the following:

• If there is a firewall between the logging server and any logging clients, ensure that the firewall ruleset allows UDP port 514 for both the clients and the server.

• The logging server and all client machines must have forward and reverse entries in the local DNS. If the network does not have a DNS server, create entries in each system's /etc/hosts. Proper name resolution is required so that log entries are not rejected by the logging server.

On the log server, edit /etc/syslog.conf to specify the name of the client to receive log entries from, the logging facility to be used, and the name of the log to store the host's log entries. This example adds the hostname of B, logs all facilities, and stores the log entries in /var/log/logclient.log.

+logclient.example.com
*.*     /var/log/logclient.log

Next, configure /etc/rc.conf:

syslogd_enable="YES"
syslogd_flags="-a logclient.example.com -v -v"

The first entry starts syslogd at system boot. The second entry allows log entries from the specified client. The -v -v increases the verbosity of logged messages. This is useful for tweaking facilities as administrators are able to see what type of messages are being logged under each facility.

Multiple -a options may be specified to allow logging from multiple clients. IP addresses and whole netblocks may also be specified. Refer to syslogd(8) for a full list of possible options.

Finally, create the log file:

# touch /var/log/logclient.log

At this point, syslogd should be restarted and verified:

# service syslogd restart
# pgrep syslog

If a PID is returned, the server restarted successfully, and client configuration can begin. If the server did not restart, consult /var/log/messages for the error.

#### 11.7.3.2. 日誌客戶端設定

A logging client sends log entries to a logging server on the network. The client also keeps a local copy of its own logs.

Once a logging server has been configured, edit /etc/rc.conf on the logging client:

syslogd_enable="YES"
syslogd_flags="-s -v -v"

The first entry enables syslogd on boot up. The second entry prevents logs from being accepted by this client from other hosts (-s) and increases the verbosity of logged messages.

Next, define the logging server in the client's /etc/syslog.conf. In this example, all logged facilities are sent to a remote system, denoted by the @ symbol, with the specified hostname:

*.*		@logserv.example.com

After saving the edit, restart syslogd for the changes to take effect:

# service syslogd restart

To test that log messages are being sent across the network, use logger(1) on the client to send a message to syslogd:

# logger "Test message from logclient"

This message should now exist both in /var/log/messages on the client and /var/log/logclient.log on the log server.

#### 11.7.3.3. 日誌伺服器除錯

If no messages are being received on the log server, the cause is most likely a network connectivity issue, a hostname resolution issue, or a typo in a configuration file. To isolate the cause, ensure that both the logging server and the logging client are able to ping each other using the hostname specified in their /etc/rc.conf. If this fails, check the network cabling, the firewall ruleset, and the hostname entries in the DNS server or /etc/hosts on both the logging server and clients. Repeat until the ping is successful from both hosts.

If the ping succeeds on both hosts but log messages are still not being received, temporarily increase logging verbosity to narrow down the configuration issue. In the following example, /var/log/logclient.log on the logging server is empty and /var/log/messages on the logging client does not indicate a reason for the failure. To increase debugging output, edit the syslogd_flags entry on the logging server and issue a restart:

syslogd_flags="-d -a logclient.example.com -v -v"
# service syslogd restart

Debugging data similar to the following will flash on the console immediately after the restart:

logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart
syslogd: restarted
logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel
Logging to FILE /var/log/messages
syslogd: kernel boot file is /boot/kernel/kernel
cvthname(192.168.1.10)
validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com;
rejected in rule 0 due to name mismatch.

In this example, the log messages are being rejected due to a typo which results in a hostname mismatch. The client's hostname should be logclient, not logclien. Fix the typo, issue a restart, and verify the results:

# service syslogd restart
logmsg: pri 56, flags 4, from logserv.example.com, msg syslogd: restart
syslogd: restarted
logmsg: pri 6, flags 4, from logserv.example.com, msg syslogd: kernel boot file is /boot/kernel/kernel
syslogd: kernel boot file is /boot/kernel/kernel
logmsg: pri 166, flags 17, from logserv.example.com,
msg Dec 10 20:55:02 <syslog.err> logserv.example.com syslogd: exiting on signal 2
cvthname(192.168.1.10)
validate: dgram from IP 192.168.1.10, port 514, name logclient.example.com;
accepted in rule 0.
logmsg: pri 15, flags 0, from logclient.example.com, msg Dec 11 02:01:28 trhodes: Test message 2
Logging to FILE /var/log/logclient.log
Logging to FILE /var/log/messages

At this point, the messages are being properly received and placed in the correct file.

#### 11.7.3.4. 安全注意事項

As with any network service, security requirements should be considered before implementing a logging server. Log files may contain sensitive data about services enabled on the local host, user accounts, and configuration data. Network data sent from the client to the server will not be encrypted or password protected. If a need for encryption exists, consider using security/stunnel, which will transmit the logging data over an encrypted tunnel.

Local security is also an issue. Log files are not encrypted during use or after log rotation. Local users may access log files to gain additional insight into system configuration. Setting proper permissions on log files is critical. The built-in log rotator, newsyslog, supports setting permissions on newly created and rotated log files. Setting log files to mode 600 should prevent unwanted access by local users. Refer to newsyslog.conf(5) for additional information.

## 11.8. 設定檔

### 11.8.1. /etc 配置

There are a number of directories in which configuration information is kept. These include:

 /etc Generic system-specific configuration information. /etc/defaults Default versions of system configuration files. /etc/mail Extra sendmail(8) configuration and other MTA configuration files. /etc/ppp Configuration for both user- and kernel-ppp programs. /etc/namedb Default location for named(8) data. Normally named.conf and zone files are stored here. /usr/local/etc Configuration files for installed applications. May contain per-application subdirectories. /usr/local/etc/rc.d rc(8) scripts for installed applications. /var/db Automatically generated system-specific database files, such as the package database and the locate(1) database.

### 11.8.2. 主機名稱

#### 11.8.2.1. /etc/resolv.conf

How a FreeBSD system accesses the Internet Domain Name System (DNS) is controlled by resolv.conf(5).

The most common entries to /etc/resolv.conf are:

 nameserver The IP address of a name server the resolver should query. The servers are queried in the order listed with a maximum of three. search Search list for hostname lookup. This is normally determined by the domain of the local hostname. domain The local domain name.

A typical /etc/resolv.conf looks like this:

search example.com
nameserver 147.11.1.11
nameserver 147.11.100.30

### 注意:

Only one of the search and domain options should be used.

When using DHCP, dhclient(8) usually rewrites /etc/resolv.conf with information received from the DHCP server.

#### 11.8.2.2. /etc/hosts

/etc/hosts is a simple text database which works in conjunction with DNS and NIS to provide host name to IP address mappings. Entries for local computers connected via a LAN can be added to this file for simplistic naming purposes instead of setting up a named(8) server. Additionally, /etc/hosts can be used to provide a local record of Internet names, reducing the need to query external DNS servers for commonly accessed names.

# $FreeBSD: head/zh_TW.UTF-8/books/handbook/book.xml 49533 2016-10-21 14:27:10Z wblock$
#
#
# Host Database
#
# This file should contain the addresses and aliases for local hosts that
# share this file.  Replace 'my.domain' below with the domainname of your
# machine.
#
# In the presence of the domain name service or NIS, this file may
# not be consulted at all; see /etc/nsswitch.conf for the resolution order.
#
#
::1			localhost localhost.my.domain
127.0.0.1		localhost localhost.my.domain
#
# Imaginary network.
#10.0.0.2		myname.my.domain myname
#10.0.0.3		myfriend.my.domain myfriend
#
# According to RFC 1918, you can use the following IP networks for
# private nets which will never be connected to the Internet:
#
#	10.0.0.0	-   10.255.255.255
#	172.16.0.0	-   172.31.255.255
#	192.168.0.0	-   192.168.255.255
#
# In case you want to be able to connect to the Internet, you need
# real official assigned numbers.  Do not try to invent your own network
# numbers but instead get one from your network provider (if any) or
# from your regional registry (ARIN, APNIC, LACNIC, RIPE NCC, or AfriNIC.)
#

The format of /etc/hosts is as follows:

[Internet address] [official hostname] [alias1] [alias2] ...

For example:

10.0.0.1 myRealHostname.example.com myRealHostname foobar1 foobar2

## 11.9. 使用 sysctl(8) 調校

sysctl(8) is used to make changes to a running FreeBSD system. This includes many advanced options of the TCP/IP stack and virtual memory system that can dramatically improve performance for an experienced system administrator. Over five hundred system variables can be read and set using sysctl(8).

At its core, sysctl(8) serves two functions: to read and to modify system settings.

% sysctl -a

To read a particular variable, specify its name:

% sysctl kern.maxproc
kern.maxproc: 1044

To set a particular variable, use the variable=value syntax:

# sysctl kern.maxfiles=5000
kern.maxfiles: 2088 -> 5000

Settings of sysctl variables are usually either strings, numbers, or booleans, where a boolean is 1 for yes or 0 for no.

To automatically set some variables each time the machine boots, add them to /etc/sysctl.conf. For more information, refer to sysctl.conf(5) and 節 11.9.1, “sysctl.conf.

### 11.9.1. sysctl.conf

The configuration file for sysctl(8), /etc/sysctl.conf, looks much like /etc/rc.conf. Values are set in a variable=value form. The specified values are set after the system goes into multi-user mode. Not all variables are settable in this mode.

For example, to turn off logging of fatal signal exits and prevent users from seeing processes started by other users, the following tunables can be set in /etc/sysctl.conf:

# Do not log fatal signal exits (e.g., sig 11)
kern.logsigexit=0

# Prevent users from seeing information about processes that
# are being run under another UID.
security.bsd.see_other_uids=0

### 11.9.2. 唯讀 sysctl(8)

Contributed by .

In some cases it may be desirable to modify read-only sysctl(8) values, which will require a reboot of the system.

For instance, on some laptop models the cardbus(4) device will not probe memory ranges and will fail with errors similar to:

cbb0: Could not map register memory
device_probe_and_attach: cbb0 attach returned 12

The fix requires the modification of a read-only sysctl(8) setting. Add hw.pci.allow_unsupported_io_range=1 to /boot/loader.conf and reboot. Now cardbus(4) should work properly.

## 11.10. 調校磁碟

The following section will discuss various tuning mechanisms and options which may be applied to disk devices. In many cases, disks with mechanical parts, such as SCSI drives, will be the bottleneck driving down the overall system performance. While a solution is to install a drive without mechanical parts, such as a solid state drive, mechanical drives are not going away anytime in the near future. When tuning disks, it is advisable to utilize the features of the iostat(8) command to test various changes to the system. This command will allow the user to obtain valuable information on system IO.

### 11.10.1. Sysctl 變數

#### 11.10.1.1. vfs.vmiodirenable

The vfs.vmiodirenable sysctl(8) variable may be set to either 0 (off) or 1 (on). It is set to 1 by default. This variable controls how directories are cached by the system. Most directories are small, using just a single fragment (typically 1 K) in the file system and typically 512 bytes in the buffer cache. With this variable turned off, the buffer cache will only cache a fixed number of directories, even if the system has a huge amount of memory. When turned on, this sysctl(8) allows the buffer cache to use the VM page cache to cache the directories, making all the memory available for caching directories. However, the minimum in-core memory used to cache a directory is the physical page size (typically 4 K) rather than 512  bytes. Keeping this option enabled is recommended if the system is running any services which manipulate large numbers of files. Such services can include web caches, large mail systems, and news systems. Keeping this option on will generally not reduce performance, even with the wasted memory, but one should experiment to find out.

#### 11.10.1.2. vfs.write_behind

The vfs.write_behind sysctl(8) variable defaults to 1 (on). This tells the file system to issue media writes as full clusters are collected, which typically occurs when writing large sequential files. This avoids saturating the buffer cache with dirty buffers when it would not benefit I/O performance. However, this may stall processes and under certain circumstances should be turned off.

#### 11.10.1.3. vfs.hirunningspace

The vfs.hirunningspace sysctl(8) variable determines how much outstanding write I/O may be queued to disk controllers system-wide at any given instance. The default is usually sufficient, but on machines with many disks, try bumping it up to four or five megabytes. Setting too high a value which exceeds the buffer cache's write threshold can lead to bad clustering performance. Do not set this value arbitrarily high as higher write values may add latency to reads occurring at the same time.

There are various other buffer cache and VM page cache related sysctl(8) values. Modifying these values is not recommended as the VM system does a good job of automatically tuning itself.

#### 11.10.1.4. vm.swap_idle_enabled

The vm.swap_idle_enabled sysctl(8) variable is useful in large multi-user systems with many active login users and lots of idle processes. Such systems tend to generate continuous pressure on free memory reserves. Turning this feature on and tweaking the swapout hysteresis (in idle seconds) via vm.swap_idle_threshold1 and vm.swap_idle_threshold2 depresses the priority of memory pages associated with idle processes more quickly then the normal pageout algorithm. This gives a helping hand to the pageout daemon. Only turn this option on if needed, because the tradeoff is essentially pre-page memory sooner rather than later which eats more swap and disk bandwidth. In a small system this option will have a determinable effect, but in a large system that is already doing moderate paging, this option allows the VM system to stage whole processes into and out of memory easily.

#### 11.10.1.5. hw.ata.wc

Turning off IDE write caching reduces write bandwidth to IDE disks, but may sometimes be necessary due to data consistency issues introduced by hard drive vendors. The problem is that some IDE drives lie about when a write completes. With IDE write caching turned on, IDE hard drives write data to disk out of order and will sometimes delay writing some blocks indefinitely when under heavy disk load. A crash or power failure may cause serious file system corruption. Check the default on the system by observing the hw.ata.wc sysctl(8) variable. If IDE write caching is turned off, one can set this read-only variable to 1 in /boot/loader.conf in order to enable it at boot time.

#### 11.10.1.6. SCSI_DELAY (kern.cam.scsi_delay)

The SCSI_DELAY kernel configuration option may be used to reduce system boot times. The defaults are fairly high and can be responsible for 15 seconds of delay in the boot process. Reducing it to 5 seconds usually works with modern drives. The kern.cam.scsi_delay boot time tunable should be used. The tunable and kernel configuration option accept values in terms of milliseconds and not seconds.

### 11.10.2. 軟更新

To fine-tune a file system, use tunefs(8). This program has many different options. To toggle Soft Updates on and off, use:

# tunefs -n enable /filesystem
# tunefs -n disable /filesystem

A file system cannot be modified with tunefs(8) while it is mounted. A good time to enable Soft Updates is before any partitions have been mounted, in single-user mode.

Soft Updates is recommended for UFS file systems as it drastically improves meta-data performance, mainly file creation and deletion, through the use of a memory cache. There are two downsides to Soft Updates to be aware of. First, Soft Updates guarantee file system consistency in the case of a crash, but could easily be several seconds or even a minute behind updating the physical disk. If the system crashes, unwritten data may be lost. Secondly, Soft Updates delay the freeing of file system blocks. If the root file system is almost full, performing a major update, such as make installworld, can cause the file system to run out of space and the update to fail.

#### 11.10.2.1. 有關軟更新的更多詳細資訊

Meta-data updates are updates to non-content data like inodes or directories. There are two traditional approaches to writing a file system's meta-data back to disk.

Historically, the default behavior was to write out meta-data updates synchronously. If a directory changed, the system waited until the change was actually written to disk. The file data buffers (file contents) were passed through the buffer cache and backed up to disk later on asynchronously. The advantage of this implementation is that it operates safely. If there is a failure during an update, meta-data is always in a consistent state. A file is either created completely or not at all. If the data blocks of a file did not find their way out of the buffer cache onto the disk by the time of the crash, fsck(8) recognizes this and repairs the file system by setting the file length to 0. Additionally, the implementation is clear and simple. The disadvantage is that meta-data changes are slow. For example, rm -r touches all the files in a directory sequentially, but each directory change will be written synchronously to the disk. This includes updates to the directory itself, to the inode table, and possibly to indirect blocks allocated by the file. Similar considerations apply for unrolling large hierarchies using tar -x.

The second approach is to use asynchronous meta-data updates. This is the default for a UFS file system mounted with mount -o async. Since all meta-data updates are also passed through the buffer cache, they will be intermixed with the updates of the file content data. The advantage of this implementation is there is no need to wait until each meta-data update has been written to disk, so all operations which cause huge amounts of meta-data updates work much faster than in the synchronous case. This implementation is still clear and simple, so there is a low risk for bugs creeping into the code. The disadvantage is that there is no guarantee for a consistent state of the file system. If there is a failure during an operation that updated large amounts of meta-data, like a power failure or someone pressing the reset button, the file system will be left in an unpredictable state. There is no opportunity to examine the state of the file system when the system comes up again as the data blocks of a file could already have been written to the disk while the updates of the inode table or the associated directory were not. It is impossible to implement a fsck(8) which is able to clean up the resulting chaos because the necessary information is not available on the disk. If the file system has been damaged beyond repair, the only choice is to reformat it and restore from backup.

The usual solution for this problem is to implement dirty region logging, which is also referred to as journaling. Meta-data updates are still written synchronously, but only into a small region of the disk. Later on, they are moved to their proper location. Because the logging area is a small, contiguous region on the disk, there are no long distances for the disk heads to move, even during heavy operations, so these operations are quicker than synchronous updates. Additionally, the complexity of the implementation is limited, so the risk of bugs being present is low. A disadvantage is that all meta-data is written twice, once into the logging region and once to the proper location, so performance pessimization might result. On the other hand, in case of a crash, all pending meta-data operations can be either quickly rolled back or completed from the logging area after the system comes up again, resulting in a fast file system startup.

Kirk McKusick, the developer of Berkeley FFS, solved this problem with Soft Updates. All pending meta-data updates are kept in memory and written out to disk in a sorted sequence (ordered meta-data updates). This has the effect that, in case of heavy meta-data operations, later updates to an item catch the earlier ones which are still in memory and have not already been written to disk. All operations are generally performed in memory before the update is written to disk and the data blocks are sorted according to their position so that they will not be on the disk ahead of their meta-data. If the system crashes, an implicit log rewind causes all operations which were not written to the disk appear as if they never happened. A consistent file system state is maintained that appears to be the one of 30 to 60 seconds earlier. The algorithm used guarantees that all resources in use are marked as such in their blocks and inodes. After a crash, the only resource allocation error that occurs is that resources are marked as used which are actually free. fsck(8) recognizes this situation, and frees the resources that are no longer used. It is safe to ignore the dirty state of the file system after a crash by forcibly mounting it with mount -f. In order to free resources that may be unused, fsck(8) needs to be run at a later time. This is the idea behind the background fsck(8): at system startup time, only a snapshot of the file system is recorded and fsck(8) is run afterwards. All file systems can then be mounted dirty, so the system startup proceeds in multi-user mode. Then, background fsck(8) is scheduled for all file systems where this is required, to free resources that may be unused. File systems that do not use Soft Updates still need the usual foreground fsck(8).

The advantage is that meta-data operations are nearly as fast as asynchronous updates and are faster than logging, which has to write the meta-data twice. The disadvantages are the complexity of the code, a higher memory consumption, and some idiosyncrasies. After a crash, the state of the file system appears to be somewhat older. In situations where the standard synchronous approach would have caused some zero-length files to remain after the fsck(8), these files do not exist at all with Soft Updates because neither the meta-data nor the file contents have been written to disk. Disk space is not released until the updates have been written to disk, which may take place some time after running rm(1). This may cause problems when installing large amounts of data on a file system that does not have enough free space to hold all the files twice.

## 11.11. 調校核心限制

### 11.11.1. 檔案/程序限制

#### 11.11.1.1. kern.maxfiles

The kern.maxfiles sysctl(8) variable can be raised or lowered based upon system requirements. This variable indicates the maximum number of file descriptors on the system. When the file descriptor table is full, file: table is full will show up repeatedly in the system message buffer, which can be viewed using dmesg(8).

Each open file, socket, or fifo uses one file descriptor. A large-scale production server may easily require many thousands of file descriptors, depending on the kind and number of services running concurrently.

In older FreeBSD releases, the default value of kern.maxfiles is derived from maxusers in the kernel configuration file. kern.maxfiles grows proportionally to the value of maxusers. When compiling a custom kernel, consider setting this kernel configuration option according to the use of the system. From this number, the kernel is given most of its pre-defined limits. Even though a production machine may not have 256 concurrent users, the resources needed may be similar to a high-scale web server.

The read-only sysctl(8) variable kern.maxusers is automatically sized at boot based on the amount of memory available in the system, and may be determined at run-time by inspecting the value of kern.maxusers. Some systems require larger or smaller values of kern.maxusers and values of 64, 128, and 256 are not uncommon. Going above 256 is not recommended unless a huge number of file descriptors is needed. Many of the tunable values set to their defaults by kern.maxusers may be individually overridden at boot-time or run-time in /boot/loader.conf. Refer to loader.conf(5) and /boot/defaults/loader.conf for more details and some hints.

In older releases, the system will auto-tune maxusers if it is set to 0. [2]. When setting this option, set maxusers to at least 4, especially if the system runs Xorg or is used to compile software. The most important table set by maxusers is the maximum number of processes, which is set to 20 + 16 * maxusers. If maxusers is set to 1, there can only be 36 simultaneous processes, including the 18 or so that the system starts up at boot time and the 15 or so used by Xorg. Even a simple task like reading a manual page will start up nine processes to filter, decompress, and view it. Setting maxusers to 64 allows up to 1044 simultaneous processes, which should be enough for nearly all uses. If, however, the proc table full error is displayed when trying to start another program, or a server is running with a large number of simultaneous users, increase the number and rebuild.

### 注意:

maxusers does not limit the number of users which can log into the machine. It instead sets various table sizes to reasonable values considering the maximum number of users on the system and how many processes each user will be running.

#### 11.11.1.2. kern.ipc.soacceptqueue

The kern.ipc.soacceptqueue sysctl(8) variable limits the size of the listen queue for accepting new TCP connections. The default value of 128 is typically too low for robust handling of new connections on a heavily loaded web server. For such environments, it is recommended to increase this value to 1024 or higher. A service such as sendmail(8), or Apache may itself limit the listen queue size, but will often have a directive in its configuration file to adjust the queue size. Large listen queues do a better job of avoiding Denial of Service (DoS) attacks.

### 11.11.2. 網路限制

The NMBCLUSTERS kernel configuration option dictates the amount of network Mbufs available to the system. A heavily-trafficked server with a low number of Mbufs will hinder performance. Each cluster represents approximately 2 K of memory, so a value of 1024 represents 2 megabytes of kernel memory reserved for network buffers. A simple calculation can be done to figure out how many are needed. A web server which maxes out at 1000 simultaneous connections where each connection uses a 6 K receive and 16 K send buffer, requires approximately 32 MB worth of network buffers to cover the web server. A good rule of thumb is to multiply by 2, so 2x32 MB / 2 KB = 64 MB / 2 kB = 32768. Values between 4096 and 32768 are recommended for machines with greater amounts of memory. Never specify an arbitrarily high value for this parameter as it could lead to a boot time crash. To observe network cluster usage, use -m with netstat(1).

The kern.ipc.nmbclusters loader tunable should be used to tune this at boot time. Only older versions of FreeBSD will require the use of the NMBCLUSTERS kernel config(8) option.

For busy servers that make extensive use of the sendfile(2) system call, it may be necessary to increase the number of sendfile(2) buffers via the NSFBUFS kernel configuration option or by setting its value in /boot/loader.conf (see loader(8) for details). A common indicator that this parameter needs to be adjusted is when processes are seen in the sfbufa state. The sysctl(8) variable kern.ipc.nsfbufs is read-only. This parameter nominally scales with kern.maxusers, however it may be necessary to tune accordingly.

### 重要:

Even though a socket has been marked as non-blocking, calling sendfile(2) on the non-blocking socket may result in the sendfile(2) call blocking until enough struct sf_buf's are made available.

#### 11.11.2.1. net.inet.ip.portrange.*

The net.inet.ip.portrange.* sysctl(8) variables control the port number ranges automatically bound to TCP and UDP sockets. There are three ranges: a low range, a default range, and a high range. Most network programs use the default range which is controlled by net.inet.ip.portrange.first and net.inet.ip.portrange.last, which default to 1024 and 5000, respectively. Bound port ranges are used for outgoing connections and it is possible to run the system out of ports under certain circumstances. This most commonly occurs when running a heavily loaded web proxy. The port range is not an issue when running a server which handles mainly incoming connections, such as a web server, or has a limited number of outgoing connections, such as a mail relay. For situations where there is a shortage of ports, it is recommended to increase net.inet.ip.portrange.last modestly. A value of 10000, 20000 or 30000 may be reasonable. Consider firewall effects when changing the port range. Some firewalls may block large ranges of ports, usually low-numbered ports, and expect systems to use higher ranges of ports for outgoing connections. For this reason, it is not recommended that the value of net.inet.ip.portrange.first be lowered.

#### 11.11.2.2. TCP 頻寬延遲乘積

TCP bandwidth delay product limiting can be enabled by setting the net.inet.tcp.inflight.enable sysctl(8) variable to 1. This instructs the system to attempt to calculate the bandwidth delay product for each connection and limit the amount of data queued to the network to just the amount required to maintain optimum throughput.

This feature is useful when serving data over modems, Gigabit Ethernet, high speed WAN links, or any other link with a high bandwidth delay product, especially when also using window scaling or when a large send window has been configured. When enabling this option, also set net.inet.tcp.inflight.debug to 0 to disable debugging. For production use, setting net.inet.tcp.inflight.min to at least 6144 may be beneficial. Setting high minimums may effectively disable bandwidth limiting, depending on the link. The limiting feature reduces the amount of data built up in intermediate route and switch packet queues and reduces the amount of data built up in the local host's interface queue. With fewer queued packets, interactive connections, especially over slow modems, will operate with lower Round Trip Times. This feature only effects server side data transmission such as uploading. It has no effect on data reception or downloading.

Adjusting net.inet.tcp.inflight.stab is not recommended. This parameter defaults to 20, representing 2 maximal packets added to the bandwidth delay product window calculation. The additional window is required to stabilize the algorithm and improve responsiveness to changing conditions, but it can also result in higher ping(8) times over slow links, though still much lower than without the inflight algorithm. In such cases, try reducing this parameter to 15, 10, or 5 and reducing net.inet.tcp.inflight.min to a value such as 3500 to get the desired effect. Reducing these parameters should be done as a last resort only.

### 11.11.3. 虛擬記憶體

#### 11.11.3.1. kern.maxvnodes

A vnode is the internal representation of a file or directory. Increasing the number of vnodes available to the operating system reduces disk I/O. Normally, this is handled by the operating system and does not need to be changed. In some cases where disk I/O is a bottleneck and the system is running out of vnodes, this setting needs to be increased. The amount of inactive and free RAM will need to be taken into account.

To see the current number of vnodes in use:

# sysctl vfs.numvnodes
vfs.numvnodes: 91349

To see the maximum vnodes:

# sysctl kern.maxvnodes
kern.maxvnodes: 100000

If the current vnode usage is near the maximum, try increasing kern.maxvnodes by a value of 1000. Keep an eye on the number of vfs.numvnodes. If it climbs up to the maximum again, kern.maxvnodes will need to be increased further. Otherwise, a shift in memory usage as reported by top(1) should be visible and more memory should be active.

## 11.12. 增加交換空間

Sometimes a system requires more swap space. This section describes two methods to increase swap space: adding swap to an existing partition or new hard drive, and creating a swap file on an existing partition.

For information on how to encrypt swap space, which options exist, and why it should be done, refer to 節 17.13, “交換空間加密”.

### 11.12.1. 使用新硬碟或既有分割區增加交換空間

Adding a new hard drive for swap gives better performance than using a partition on an existing drive. Setting up partitions and hard drives is explained in 節 17.2, “加入磁碟” while 節 2.6.1, “規劃分割區配置” discusses partition layouts and swap partition size considerations.

Use swapon to add a swap partition to the system. For example:

# swapon /dev/ada1s1b

### 警告:

It is possible to use any partition not currently mounted, even if it already contains data. Using swapon on a partition that contains data will overwrite and destroy that data. Make sure that the partition to be added as swap is really the intended partition before running swapon.

To automatically add this swap partition on boot, add an entry to /etc/fstab:

/dev/ada1s1b	none	swap	sw	0	0

See fstab(5) for an explanation of the entries in /etc/fstab. More information about swapon can be found in swapon(8).

### 11.12.2. 建立交換檔

These examples create a 64M swap file called /usr/swap0 instead of using a partition.

Using swap files requires that the module needed by md(4) has either been built into the kernel or has been loaded before swap is enabled. See 章 8, 設定 FreeBSD 核心 for information about building a custom kernel.

1. Create the swap file:

# dd if=/dev/zero of=/usr/swap0 bs=1m count=64
2. Set the proper permissions on the new file:

# chmod 0600 /usr/swap0
3. Inform the system about the swap file by adding a line to /etc/fstab:

md99	none	swap	sw,file=/usr/swap0,late	0	0

The md(4) device md99 is used, leaving lower device numbers available for interactive use.

4. Swap space will be added on system startup. To add swap space immediately, use swapon(8):

# swapon -aL

1. Create the swap file, /usr/swap0:

# dd if=/dev/zero of=/usr/swap0 bs=1m count=64
2. Set the proper permissions on /usr/swap0:

# chmod 0600 /usr/swap0
3. Enable the swap file in /etc/rc.conf:

swapfile="/usr/swap0"   # Set to name of swap file
4. Swap space will be added on system startup. To enable the swap file immediately, specify a free memory device. Refer to 節 17.9, “記憶體磁碟” for more information about memory devices.

# mdconfig -a -t vnode -f /usr/swap0 -u 0 && swapon /dev/md0

## 11.13. 電源與資源管理

Written by and .

It is important to utilize hardware resources in an efficient manner. Power and resource management allows the operating system to monitor system limits and to possibly provide an alert if the system temperature increases unexpectedly. An early specification for providing power management was the Advanced Power Management (APM) facility. APM controls the power usage of a system based on its activity. However, it was difficult and inflexible for operating systems to manage the power usage and thermal properties of a system. The hardware was managed by the BIOS and the user had limited configurability and visibility into the power management settings. The APM BIOS is supplied by the vendor and is specific to the hardware platform. An APM driver in the operating system mediates access to the APM Software Interface, which allows management of power levels.

There are four major problems in APM. First, power management is done by the vendor-specific BIOS, separate from the operating system. For example, the user can set idle-time values for a hard drive in the APM BIOS so that, when exceeded, the BIOS spins down the hard drive without the consent of the operating system. Second, the APM logic is embedded in the BIOS, and it operates outside the scope of the operating system. This means that users can only fix problems in the APM BIOS by flashing a new one into the ROM, which is a dangerous procedure with the potential to leave the system in an unrecoverable state if it fails. Third, APM is a vendor-specific technology, meaning that there is a lot of duplication of efforts and bugs found in one vendor's BIOS may not be solved in others. Lastly, the APM BIOS did not have enough room to implement a sophisticated power policy or one that can adapt well to the purpose of the machine.

The Plug and Play BIOS (PNPBIOS) was unreliable in many situations. PNPBIOS is 16-bit technology, so the operating system has to use 16-bit emulation in order to interface with PNPBIOS methods. FreeBSD provides an APM driver as APM should still be used for systems manufactured at or before the year 2000. The driver is documented in apm(4).

The successor to APM is the Advanced Configuration and Power Interface (ACPI). ACPI is a standard written by an alliance of vendors to provide an interface for hardware resources and power management. It is a key element in Operating System-directed configuration and Power Management as it provides more control and flexibility to the operating system.

This chapter demonstrates how to configure ACPI on FreeBSD. It then offers some tips on how to debug ACPI and how to submit a problem report containing debugging information so that developers can diagnosis and fix ACPI issues.

### 11.13.1. 設定 ACPI

In FreeBSD the acpi(4) driver is loaded by default at system boot and should not be compiled into the kernel. This driver cannot be unloaded after boot because the system bus uses it for various hardware interactions. However, if the system is experiencing problems, ACPI can be disabled altogether by rebooting after setting hint.acpi.0.disabled="1" in /boot/loader.conf or by setting this variable at the loader prompt, as described in 節 12.2.3, “階段三”.

### 注意:

ACPI and APM cannot coexist and should be used separately. The last one to load will terminate if the driver notices the other is running.

ACPI can be used to put the system into a sleep mode with acpiconf, the -s flag, and a number from 1 to 5. Most users only need 1 (quick suspend to RAM) or 3 (suspend to RAM). Option 5 performs a soft-off which is the same as running halt -p.

Other options are available using sysctl. Refer to acpi(4) and acpiconf(8) for more information.

### 11.13.2. 常見問題

ACPI is present in all modern computers that conform to the ia32 (x86), ia64 (Itanium), and amd64 (AMD) architectures. The full standard has many features including CPU performance management, power planes control, thermal zones, various battery systems, embedded controllers, and bus enumeration. Most systems implement less than the full standard. For instance, a desktop system usually only implements bus enumeration while a laptop might have cooling and battery management support as well. Laptops also have suspend and resume, with their own associated complexity.

An ACPI-compliant system has various components. The BIOS and chipset vendors provide various fixed tables, such as FADT, in memory that specify things like the APIC map (used for SMP), config registers, and simple configuration values. Additionally, a bytecode table, the Differentiated System Description Table DSDT, specifies a tree-like name space of devices and methods.

The ACPI driver must parse the fixed tables, implement an interpreter for the bytecode, and modify device drivers and the kernel to accept information from the ACPI subsystem. For FreeBSD, Intel® has provided an interpreter (ACPI-CA) that is shared with Linux® and NetBSD. The path to the ACPI-CA source code is src/sys/contrib/dev/acpica. The glue code that allows ACPI-CA to work on FreeBSD is in src/sys/dev/acpica/Osd. Finally, drivers that implement various ACPI devices are found in src/sys/dev/acpica.

For ACPI to work correctly, all the parts have to work correctly. Here are some common problems, in order of frequency of appearance, and some possible workarounds or fixes. If a fix does not resolve the issue, refer to 節 11.13.4, “取得與回報除錯資訊” for instructions on how to submit a bug report.

#### 11.13.2.1. 滑鼠問題

In some cases, resuming from a suspend operation will cause the mouse to fail. A known work around is to add hint.psm.0.flags="0x3000" to /boot/loader.conf.

#### 11.13.2.2. 待機/喚醒

ACPI has three suspend to RAM (STR) states, S1-S3, and one suspend to disk state (STD), called S4. STD can be implemented in two separate ways. The S4BIOS is a BIOS-assisted suspend to disk and S4OS is implemented entirely by the operating system. The normal state the system is in when plugged in but not powered up is soft off (S5).

Use sysctl hw.acpi to check for the suspend-related items. These example results are from a Thinkpad:

hw.acpi.supported_sleep_state: S3 S4 S5
hw.acpi.s4bios: 0

Use acpiconf -s to test S3, S4, and S5. An s4bios of one (1) indicates S4BIOS support instead of S4 operating system support.

When testing suspend/resume, start with S1, if supported. This state is most likely to work since it does not require much driver support. No one has implemented S2, which is similar to S1. Next, try S3. This is the deepest STR state and requires a lot of driver support to properly reinitialize the hardware.

A common problem with suspend/resume is that many device drivers do not save, restore, or reinitialize their firmware, registers, or device memory properly. As a first attempt at debugging the problem, try:

# sysctl debug.bootverbose=1
# sysctl debug.acpi.suspend_bounce=1
# acpiconf -s 3

This test emulates the suspend/resume cycle of all device drivers without actually going into S3 state. In some cases, problems such as losing firmware state, device watchdog time out, and retrying forever, can be captured with this method. Note that the system will not really enter S3 state, which means devices may not lose power, and many will work fine even if suspend/resume methods are totally missing, unlike real S3 state.

Harder cases require additional hardware, such as a serial port and cable for debugging through a serial console, a Firewire port and cable for using dcons(4), and kernel debugging skills.

To help isolate the problem, unload as many drivers as possible. If it works, narrow down which driver is the problem by loading drivers until it fails again. Typically, binary drivers like nvidia.ko, display drivers, and USB will have the most problems while Ethernet interfaces usually work fine. If drivers can be properly loaded and unloaded, automate this by putting the appropriate commands in /etc/rc.suspend and /etc/rc.resume. Try setting hw.acpi.reset_video to 1 if the display is messed up after resume. Try setting longer or shorter values for hw.acpi.sleep_delay to see if that helps.

Try loading a recent Linux® distribution to see if suspend/resume works on the same hardware. If it works on Linux®, it is likely a FreeBSD driver problem. Narrowing down which driver causes the problem will assist developers in fixing the problem. Since the ACPI maintainers rarely maintain other drivers, such as sound or ATA, any driver problems should also be posted to the freebsd-current list and mailed to the driver maintainer. Advanced users can include debugging printf(3)s in a problematic driver to track down where in its resume function it hangs.

Finally, try disabling ACPI and enabling APM instead. If suspend/resume works with APM, stick with APM, especially on older hardware (pre-2000). It took vendors a while to get ACPI support correct and older hardware is more likely to have BIOS problems with ACPI.

#### 11.13.2.3. 系統無回應

Most system hangs are a result of lost interrupts or an interrupt storm. Chipsets may have problems based on boot, how the BIOS configures interrupts before correctness of the APIC (MADT) table, and routing of the System Control Interrupt (SCI).

Interrupt storms can be distinguished from lost interrupts by checking the output of vmstat -i and looking at the line that has acpi0. If the counter is increasing at more than a couple per second, there is an interrupt storm. If the system appears hung, try breaking to DDB (CTRL+ALT+ESC on console) and type show interrupts.

When dealing with interrupt problems, try disabling APIC support with hint.apic.0.disabled="1" in /boot/loader.conf.

#### 11.13.2.4. 當機

Panics are relatively rare for ACPI and are the top priority to be fixed. The first step is to isolate the steps to reproduce the panic, if possible, and get a backtrace. Follow the advice for enabling options DDB and setting up a serial console in 節 25.6.4, “從序列線路 (Serial Line) 進入 DDB 除錯程式” or setting up a dump partition. To get a backtrace in DDB, use tr. When handwriting the backtrace, get at least the last five and the top five lines in the trace.

Then, try to isolate the problem by booting with ACPI disabled. If that works, isolate the ACPI subsystem by using various values of debug.acpi.disable. See acpi(4) for some examples.

#### 11.13.2.5. 系統在待機或關機後仍開機

First, try setting hw.acpi.disable_on_poweroff="0" in /boot/loader.conf. This keeps ACPI from disabling various events during the shutdown process. Some systems need this value set to 1 (the default) for the same reason. This usually fixes the problem of a system powering up spontaneously after a suspend or poweroff.

#### 11.13.2.6. BIOS 含有有問題的 Bytecode

Some BIOS vendors provide incorrect or buggy bytecode. This is usually manifested by kernel console messages like this:

ACPI-1287: *** Error: Method execution failed [\\_SB_.PCI0.LPC0.FIGD._STA] \\
(Node 0xc3f6d160), AE_NOT_FOUND

Often, these problems may be resolved by updating the BIOS to the latest revision. Most console messages are harmless, but if there are other problems, like the battery status is not working, these messages are a good place to start looking for problems.

### 11.13.3. 覆蓋預設的 AML

The BIOS bytecode, known as ACPI Machine Language (AML), is compiled from a source language called ACPI Source Language (ASL). The AML is found in the table known as the Differentiated System Description Table (DSDT).

The goal of FreeBSD is for everyone to have working ACPI without any user intervention. Workarounds are still being developed for common mistakes made by BIOS vendors. The Microsoft® interpreter (acpi.sys and acpiec.sys) does not strictly check for adherence to the standard, and thus many BIOS vendors who only test ACPI under Windows® never fix their ASL. FreeBSD developers continue to identify and document which non-standard behavior is allowed by Microsoft®'s interpreter and replicate it so that FreeBSD can work without forcing users to fix the ASL.

To help identify buggy behavior and possibly fix it manually, a copy can be made of the system's ASL. To copy the system's ASL to a specified file name, use acpidump with -t, to show the contents of the fixed tables, and -d, to disassemble the AML:

# acpidump -td > my.asl

Some AML versions assume the user is running Windows®. To override this, set hw.acpi.osname="Windows 2009" in /boot/loader.conf, using the most recent Windows® version listed in the ASL.

Other workarounds may require my.asl to be customized. If this file is edited, compile the new ASL using the following command. Warnings can usually be ignored, but errors are bugs that will usually prevent ACPI from working correctly.

# iasl -f my.asl

Including -f forces creation of the AML, even if there are errors during compilation. Some errors, such as missing return statements, are automatically worked around by the FreeBSD interpreter.

The default output filename for iasl is DSDT.aml. Load this file instead of the BIOS's buggy copy, which is still present in flash memory, by editing /boot/loader.conf as follows:

acpi_dsdt_load="YES"
acpi_dsdt_name="/boot/DSDT.aml"

Be sure to copy DSDT.aml to /boot, then reboot the system. If this fixes the problem, send a diff(1) of the old and new ASL to freebsd-acpi so that developers can work around the buggy behavior in acpica.

### 11.13.4. 取得與回報除錯資訊

Written by .
With contributions from and .

The ACPI driver has a flexible debugging facility. A set of subsystems and the level of verbosity can be specified. The subsystems to debug are specified as layers and are broken down into components (ACPI_ALL_COMPONENTS) and ACPI hardware support (ACPI_ALL_DRIVERS). The verbosity of debugging output is specified as the level and ranges from just report errors (ACPI_LV_ERROR) to everything (ACPI_LV_VERBOSE). The level is a bitmask so multiple options can be set at once, separated by spaces. In practice, a serial console should be used to log the output so it is not lost as the console message buffer flushes. A full list of the individual layers and levels is found in acpi(4).

Debugging output is not enabled by default. To enable it, add options ACPI_DEBUG to the custom kernel configuration file if ACPI is compiled into the kernel. Add ACPI_DEBUG=1 to /etc/make.conf to enable it globally. If a module is used instead of a custom kernel, recompile just the acpi.ko module as follows:

# cd /sys/modules/acpi/acpi && make clean && make ACPI_DEBUG=1

Copy the compiled acpi.ko to /boot/kernel and add the desired level and layer to /boot/loader.conf. The entries in this example enable debug messages for all ACPI components and hardware drivers and output error messages at the least verbose level:

debug.acpi.layer="ACPI_ALL_COMPONENTS ACPI_ALL_DRIVERS"
debug.acpi.level="ACPI_LV_ERROR"

If the required information is triggered by a specific event, such as a suspend and then resume, do not modify /boot/loader.conf. Instead, use sysctl to specify the layer and level after booting and preparing the system for the specific event. The variables which can be set using sysctl are named the same as the tunables in /boot/loader.conf.

Once the debugging information is gathered, it can be sent to freebsd-acpi so that it can be used by the FreeBSD ACPI maintainers to identify the root cause of the problem and to develop a solution.

### 注意:

Before submitting debugging information to this mailing list, ensure the latest BIOS version is installed and, if available, the embedded controller firmware version.

When submitting a problem report, include the following information:

• Description of the buggy behavior, including system type, model, and anything that causes the bug to appear. Note as accurately as possible when the bug began occurring if it is new.

• The output of dmesg after running boot -v, including any error messages generated by the bug.

• The dmesg output from boot -v with ACPI disabled, if disabling ACPI helps to fix the problem.

• Output from sysctl hw.acpi. This lists which features the system offers.

• The URL to a pasted version of the system's ASL. Do not send the ASL directly to the list as it can be very large. Generate a copy of the ASL by running this command:

# acpidump -dt > name-system.asl

Substitute the login name for name and manufacturer/model for system. For example, use njl-FooCo6000.asl.

Most FreeBSD developers watch the FreeBSD-CURRENT mailing list, but one should submit problems to freebsd-acpi to be sure it is seen. Be patient when waiting for a response. If the bug is not immediately apparent, submit a PR using send-pr(1). When entering a PR, include the same information as requested above. This helps developers to track the problem and resolve it. Do not send a PR without emailing freebsd-acpi first as it is likely that the problem has been reported before.

### 11.13.5. 參考文獻

• The FreeBSD ACPI Mailing List Archives (http://lists.freebsd.org/pipermail/freebsd-acpi/)

• The ACPI 2.0 Specification (http://acpi.info/spec.htm)

[2] The auto-tuning algorithm sets maxusers equal to the amount of memory in the system, with a minimum of 32, and a maximum of 384.

## 12.1. 概述

• FreeBSD 開機系統的元件以及它們如何互動。

• FreeBSD 開機程式中各元件可使用的選項，用來控制開機程序。

• 如何設定自訂的開機啟動畫面 (Splash screen)。

• 設定 Device Hints 的基礎。

• 如何開機進入單人及多人模式以及如何正確關閉 FreeBSD 系統。

## 12.2. FreeBSD 開機程序

Turning on a computer and starting the operating system poses an interesting dilemma. By definition, the computer does not know how to do anything until the operating system is started. This includes running programs from the disk. If the computer can not run a program from the disk without the operating system, and the operating system programs are on the disk, how is the operating system started?

This problem parallels one in the book The Adventures of Baron Munchausen. A character had fallen part way down a manhole, and pulled himself out by grabbing his bootstraps and lifting. In the early days of computing, the term bootstrap was applied to the mechanism used to load the operating system. It has since become shortened to booting.

On x86 hardware, the Basic Input/Output System (BIOS) is responsible for loading the operating system. The BIOS looks on the hard disk for the Master Boot Record (MBR), which must be located in a specific place on the disk. The BIOS has enough knowledge to load and run the MBR, and assumes that the MBR can then carry out the rest of the tasks involved in loading the operating system, possibly with the help of the BIOS.

### 注意:

FreeBSD provides for booting from both the older MBR standard, and the newer GUID Partition Table (GPT). GPT partitioning is often found on computers with the Unified Extensible Firmware Interface (UEFI). However, FreeBSD can boot from GPT partitions even on machines with only a legacy BIOS with gptboot(8). Work is under way to provide direct UEFI booting.

The code within the MBR is typically referred to as a boot manager, especially when it interacts with the user. The boot manager usually has more code in the first track of the disk or within the file system. Examples of boot managers include the standard FreeBSD boot manager boot0, also called Boot Easy, and Grub, which is used by many Linux® distributions.

If only one operating system is installed, the MBR searches for the first bootable (active) slice on the disk, and then runs the code on that slice to load the remainder of the operating system. When multiple operating systems are present, a different boot manager can be installed to display a list of operating systems so the user can select one to boot.

The remainder of the FreeBSD bootstrap system is divided into three stages. The first stage knows just enough to get the computer into a specific state and run the second stage. The second stage can do a little bit more, before running the third stage. The third stage finishes the task of loading the operating system. The work is split into three stages because the MBR puts limits on the size of the programs that can be run at stages one and two. Chaining the tasks together allows FreeBSD to provide a more flexible loader.

The kernel is then started and begins to probe for devices and initialize them for use. Once the kernel boot process is finished, the kernel passes control to the user process init(8), which makes sure the disks are in a usable state, starts the user-level resource configuration which mounts file systems, sets up network cards to communicate on the network, and starts the processes which have been configured to run at startup.

This section describes these stages in more detail and demonstrates how to interact with the FreeBSD boot process.

### 12.2.1. 開機管理程式

The boot manager code in the MBR is sometimes referred to as stage zero of the boot process. By default, FreeBSD uses the boot0 boot manager.

The MBR installed by the FreeBSD installer is based on /boot/boot0. The size and capability of boot0 is restricted to 446 bytes due to the slice table and 0x55AA identifier at the end of the MBR. If boot0 and multiple operating systems are installed, a message similar to this example will be displayed at boot time:

F1 Win
F2 FreeBSD

Default: F2

Other operating systems will overwrite an existing MBR if they are installed after FreeBSD. If this happens, or to replace the existing MBR with the FreeBSD MBR, use the following command:

# fdisk -B -b /boot/boot0 device

where device is the boot disk, such as ad0 for the first IDE disk, ad2 for the first IDE disk on a second IDE controller, or da0 for the first SCSI disk. To create a custom configuration of the MBR, refer to boot0cfg(8).

### 12.2.2. 階段一與階段二

Conceptually, the first and second stages are part of the same program on the same area of the disk. Because of space constraints, they have been split into two, but are always installed together. They are copied from the combined /boot/boot by the FreeBSD installer or bsdlabel.

These two stages are located outside file systems, in the first track of the boot slice, starting with the first sector. This is where boot0, or any other boot manager, expects to find a program to run which will continue the boot process.

The first stage, boot1, is very simple, since it can only be 512 bytes in size. It knows just enough about the FreeBSD bsdlabel, which stores information about the slice, to find and execute boot2.

Stage two, boot2, is slightly more sophisticated, and understands the FreeBSD file system enough to find files. It can provide a simple interface to choose the kernel or loader to run. It runs loader, which is much more sophisticated and provides a boot configuration file. If the boot process is interrupted at stage two, the following interactive screen is displayed:

>> FreeBSD/i386 BOOT
boot:

To replace the installed boot1 and boot2, use bsdlabel, where diskslice is the disk and slice to boot from, such as ad0s1 for the first slice on the first IDE disk:

# bsdlabel -B diskslice

### 警告:

If just the disk name is used, such as ad0, bsdlabel will create the disk in dangerously dedicated mode, without slices. This is probably not the desired action, so double check the diskslice before pressing Return.

### 12.2.3. 階段三

The loader is the final stage of the three-stage bootstrap process. It is located on the file system, usually as /boot/loader.

The loader is intended as an interactive method for configuration, using a built-in command set, backed up by a more powerful interpreter which has a more complex command set.

During initialization, loader will probe for a console and for disks, and figure out which disk it is booting from. It will set variables accordingly, and an interpreter is started where user commands can be passed from a script or interactively.

The loader will then read /boot/loader.rc, which by default reads in /boot/defaults/loader.conf which sets reasonable defaults for variables and reads /boot/loader.conf for local changes to those variables. loader.rc then acts on these variables, loading whichever modules and kernel are selected.

Finally, by default, loader issues a 10 second wait for key presses, and boots the kernel if it is not interrupted. If interrupted, the user is presented with a prompt which understands the command set, where the user may adjust variables, unload all modules, load modules, and then finally boot or reboot. 表格 12.1, “載入程式內建指令” lists the most commonly used loader commands. For a complete discussion of all available commands, refer to loader(8).

autoboot secondsProceeds to boot the kernel if not interrupted within the time span given, in seconds. It displays a countdown, and the default time span is 10 seconds.
boot [-options] [kernelname]Immediately proceeds to boot the kernel, with any specified options or kernel name. Providing a kernel name on the command-line is only applicable after an unload has been issued. Otherwise, the previously-loaded kernel will be used. If kernelname is not qualified it will be searched under /boot/kernel and /boot/modules.
boot-confGoes through the same automatic configuration of modules based on specified variables, most commonly kernel. This only makes sense if unload is used first, before changing some variables.
help [topic]Shows help messages read from /boot/loader.help. If the topic given is index, the list of available topics is displayed.
include filenameReads the specified file and interprets it line by line. An error immediately stops the include.
load [-t type] filenameLoads the kernel, kernel module, or file of the type given, with the specified filename. Any arguments after filename are passed to the file. If filename is not qualified it will be searched under /boot/kernel and /boot/modules.
ls [-l] [path]Displays a listing of files in the given path, or the root directory, if the path is not specified. If -l is specified, file sizes will also be shown.
lsdev [-v]Lists all of the devices from which it may be possible to load modules. If -v is specified, more details are printed.
lsmod [-v]Displays loaded modules. If -v is specified, more details are shown.
more filenameDisplays the files specified, with a pause at each LINES displayed.
rebootImmediately reboots the system.
set variable, set variable=valueSets the specified environment variables.

Here are some practical examples of loader usage. To boot the usual kernel in single-user mode :

boot -s

To unload the usual kernel and modules and then load the previous or another, specified kernel:

unload
load kernel.old

Use kernel.GENERIC to refer to the default kernel that comes with an installation, or kernel.old, to refer to the previously installed kernel before a system upgrade or before configuring a custom kernel.

Use the following to load the usual modules with another kernel:

unload
set kernel="kernel.old"
boot-conf

To load an automated kernel configuration script:

load -t userconfig_script /boot/kernel.conf

### 12.2.4. 最終階段

Once the kernel is loaded by either loader or by boot2, which bypasses loader, it examines any boot flags and adjusts its behavior as necessary. 表格 12.2, “開機時核心互動參數” lists the commonly used boot flags. Refer to boot(8) for more information on the other boot flags.

-aDuring kernel initialization, ask for the device to mount as the root file system.
-CBoot the root file system from a CDROM.
-sBoot into single-user mode.
-vBe more verbose during kernel startup.

Once the kernel has finished booting, it passes control to the user process init(8), which is located at /sbin/init, or the program path specified in the init_path variable in loader. This is the last stage of the boot process.

The boot sequence makes sure that the file systems available on the system are consistent. If a UFS file system is not, and fsck cannot fix the inconsistencies, init drops the system into single-user mode so that the system administrator can resolve the problem directly. Otherwise, the system boots into multi-user mode.

#### 12.2.4.1. 單使用者模式

A user can specify this mode by booting with -s or by setting the boot_single variable in loader. It can also be reached by running shutdown now from multi-user mode. Single-user mode begins with this message:

Enter full pathname of shell or RETURN for /bin/sh:

If the user presses Enter, the system will enter the default Bourne shell. To specify a different shell, input the full path to the shell.

Single-user mode is usually used to repair a system that will not boot due to an inconsistent file system or an error in a boot configuration file. It can also be used to reset the root password when it is unknown. These actions are possible as the single-user mode prompt gives full, local access to the system and its configuration files. There is no networking in this mode.

While single-user mode is useful for repairing a system, it poses a security risk unless the system is in a physically secure location. By default, any user who can gain physical access to a system will have full control of that system after booting into single-user mode.

If the system console is changed to insecure in /etc/ttys, the system will first prompt for the root password before initiating single-user mode. This adds a measure of security while removing the ability to reset the root password when it is unknown.

# name  getty                           type    status          comments
#
# If console is marked "insecure", then init will ask for the root password
# when going to single-user mode.
console none                            unknown off insecure

An insecure console means that physical security to the console is considered to be insecure, so only someone who knows the root password may use single-user mode.

#### 12.2.4.2. 多使用者模式

If init finds the file systems to be in order, or once the user has finished their commands in single-user mode and has typed exit to leave single-user mode, the system enters multi-user mode, in which it starts the resource configuration of the system.

The resource configuration system reads in configuration defaults from /etc/defaults/rc.conf and system-specific details from /etc/rc.conf. It then proceeds to mount the system file systems listed in /etc/fstab. It starts up networking services, miscellaneous system daemons, then the startup scripts of locally installed packages.

To learn more about the resource configuration system, refer to rc(8) and examine the scripts located in /etc/rc.d.

## 12.3. 設定開機啟動畫面

Contributed by .

Typically when a FreeBSD system boots, it displays its progress as a series of messages at the console. A boot splash screen creates an alternate boot screen that hides all of the boot probe and service startup messages. A few boot loader messages, including the boot options menu and a timed wait countdown prompt, are displayed at boot time, even when the splash screen is enabled. The display of the splash screen can be turned off by hitting any key on the keyboard during the boot process.

There are two basic environments available in FreeBSD. The first is the default legacy virtual console command line environment. After the system finishes booting, a console login prompt is presented. The second environment is a configured graphical environment. Refer to 章 5, X Window 系統 for more information on how to install and configure a graphical display manager and a graphical login manager.

Once the system has booted, the splash screen defaults to being a screen saver. After a time period of non-use, the splash screen will display and will cycle through steps of changing intensity of the image, from bright to very dark and over again. The configuration of the splash screen saver can be overridden by adding a saver= line to /etc/rc.conf. Several built-in screen savers are available and described in splash(4). The saver= option only applies to virtual consoles and has no effect on graphical display managers.

Sample splash screen files can be downloaded from the gallery at http://artwork.freebsdgr.org. By installing the sysutils/bsd-splash-changer package or port, a random splash image from a collection will display at boot.

The splash screen function supports 256-colors in the bitmap (.bmp), ZSoft PCX (.pcx), or TheDraw (.bin) formats. The .bmp, .pcx, or .bin image has to be placed on the root partition, for example in /boot. The splash image files must have a resolution of 320 by 200 pixels or less in order to work on standard VGA adapters. For the default boot display resolution of 256-colors and 320 by 200 pixels or less, add the following lines to /boot/loader.conf. Replace splash.bmp with the name of the bitmap file to use:

splash_bmp_load="YES"
bitmap_name="/boot/splash.bmp"

To use a PCX file instead of a bitmap file:

splash_pcx_load="YES"
bitmap_name="/boot/splash.pcx"

To instead use ASCII art in the https://en.wikipedia.org/wiki/TheDraw format:

splash_txt="YES"
bitmap_name="/boot/splash.bin"

To use larger images that fill the whole display screen, up to the maximum resolution of 1024 by 768 pixels, the VESA module must also be loaded during system boot. If using a custom kernel, ensure that the custom kernel configuration file includes the VESA kernel configuration option. To load the VESA module for the splash screen, add this line to /boot/loader.conf before the three lines mentioned in the above examples:

vesa_load="YES"

Other interesting loader.conf options include:

beastie_disable="YES"

This will stop the boot options menu from being displayed, but the timed wait count down prompt will still be present. Even with the display of the boot options menu disabled, entering an option selection at the timed wait count down prompt will enact the corresponding boot option.

loader_logo="beastie"

This will replace the default words FreeBSD, which are displayed to the right of the boot options menu, with the colored beastie logo.