FreeBSD 使用手冊

FreeBSD 文件計劃

Revision: 49235

版權

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. 的註冊商標。

Adaptec 是 Adaptec, Inc. 的註冊商標。

Adobe, Acrobat, Acrobat Reader, Flash 以及 PostScript 是 Adobe Systems Incorporated 在美國和/或其他國家的商標或註冊商標。

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

Android 是 Google 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 Project 本身廣所人知的商標,後面將以 ® 符號來標示。

Last modified on 2016-08-09 03:14:22Z by wblock.
摘要

歡迎使用 FreeBSD! 本使用手冊涵蓋範圍包括了 FreeBSD 9.3-RELEASEFreeBSD 10.3-RELEASE。 這份使用手冊是很多人的集體創作,而且仍然『持續不斷』的進行中。 許多章節仍未完成,已完成的部份也有些需要更新。 如果您有興趣協助本計畫的話,請寄電子郵件至 FreeBSD 文件專案郵遞論壇

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

[ 章節模式 / 完整模式 ]

內容目錄
I. 入門
1. 簡介
1.1. 概述
1.2. 歡迎使用 FreeBSD!
1.3. 關於 FreeBSD 計劃
2. 安裝 FreeBSD
2.1. 概述
2.2. 最低硬體需求
2.3. 安裝前準備工作
2.4. 開始安裝
2.5. 使用 bsdinstall
2.6. 配置磁碟空間
2.7. 確認安裝
2.8. 安裝後注意事項
2.9. 疑難排解
2.10. 使用 Live CD
3. FreeBSD Basics
3.1. 概述
3.2. 虛擬 Console 與終端機
3.3. 使用者與基礎帳號管理
3.4. 權限
3.5. 目錄結構
3.6. 磁碟組織
3.7. 掛載與缷載檔案系組
3.8. 程序與 Daemon
3.9. Shell
3.10. 文字編輯器
3.11. 裝置及裝置節點
3.12. 操作手冊
4. 安裝應用程式: 套件與 Ports
4.1. 概述
4.2. 安裝軟體的概要
4.3. 搜尋軟體
4.4. 使用 pkg 管理 Binary 套件
4.5. 使用 Ports 套件集
4.6. 使用 Poudriere 編譯套件
4.7. 安裝後的注意事項
4.8. 處理損壞的 Ports
5. X Window 系統
5.1. 概述
5.2. 術語
5.3. 安裝 Xorg
5.4. Xorg 設定
5.5. 在 Xorg 使用字型
5.6. X 顯示管理程式
5.7. 桌面環境
5.8. 安裝 Compiz Fusion
5.9. 疑難排解
II. 一般作業
6. 桌面應用程式
6.1. 概述
6.2. 瀏覽器
6.3. 辦工工具
6.4. 文件閱覽程式
6.5. 財務
7. 多媒體
7.1. 概述
7.2. 設定音效卡
7.3. MP3 音樂
7.4. 影片播放
7.5. 電視卡
7.6. MythTV
7.7. 影像掃描器
8. 設定 FreeBSD 核心
8.1. 概述
8.2. 為何要編譯自訂的核心?
8.3. 偵測系統硬體
8.4. 設定檔
8.5. 編譯與安裝自訂核心
8.6. 如果發生錯誤
9. 列印
9.1. 快速開始
9.2. 印表機連線
9.3. 常見的頁面描述語言
9.4. 直接列印
9.5. LPD (行列式印表機 Daemon)
9.6. 其他列印系統
10. Linux® Binary 相容性
10.1. 概述
10.2. 設定 Linux® Binary 相容性
10.3. 進階主題
III. 系統管理
11. 設定與調校
11.1. 概述
11.2. 啟動服務
11.3. 設定 cron(8)
11.4. 管理 FreeBSD 中的服務
11.5. 設定網路介面卡
11.6. 虛擬主機
11.7. 設定系統日誌
11.8. 設定檔
11.9. 使用 sysctl(8) 調校
11.10. 調校磁碟
11.11. 調校核心限制
11.12. 增加交換空間
11.13. 電源與資源管理
12. FreeBSD 開機程序
12.1. 概述
12.2. FreeBSD 開機程序
12.3. 設定開機啟動畫面
12.4. Device Hints
12.5. 關機程序
13. 安全性
13.1. 概述
13.2. 簡介
13.3. 一次性密碼
13.4. TCP Wrapper
13.5. Kerberos
13.6. OpenSSL
13.7. VPN over IPsec
13.8. OpenSSH
13.9. 存取控制清單
13.10. 監視第三方安全性問題
13.11. FreeBSD 安全報告
13.12. 程序追蹤
13.13. 限制資源
13.14. 使用 Sudo 分享管理權限
14. Jails
14.1. 概述
14.2. Jail 相關術語
14.3. 建立和控制 Jail
14.4. 調校與管理
14.5. 更新多個 Jail
14.6. 使用 ezjail 管理 Jail
15. 強制存取控制 (MAC)
15.1. 概述
15.2. 關鍵詞
15.3. 了解 MAC 標籤
15.4. 規劃安全架構
15.5. 可用的 MAC 管理政策
15.6. User Lock Down
15.7. 在 MAC Jail 中使用 Nagios
15.8. MAC 架構疑難排解
16. 安全事件稽查
16.1. 概述
16.2. 關鍵詞
16.3. 稽查設定
16.4. 查看稽查線索
17. 儲存設備
17.1. 概述
17.2. 加入磁碟
17.3. 重設大小與擴增磁碟
17.4. USB 儲存裝置
17.5. 建立與使用 CD 媒體
17.6. 建立與使用 DVD 媒體
17.7. 建立與使用軟碟
17.8. 備份基礎概念
17.9. 記憶體磁碟
17.10. 檔案系統快照
17.11. 磁碟配額
17.12. 磁碟分割區加密
17.13. 交換空間加密
17.14. 高可用存儲空間 (HAST)
18. GEOM: Modular Disk Transformation Framework
18.1. 概述
18.2. RAID0 - 分散 (Striping)
18.3. RAID1 - 鏡射 (Mirroring)
18.4. RAID3 - 位元級分散儲存與獨立奇偶校驗
18.5. 軟體 RAID 裝置
18.6. GEOM Gate Network
18.7. 磁碟裝置標籤
18.8. UFS Journaling 透過 GEOM
19. Z 檔案系統 (ZFS)
19.1. 什麼使 ZFS 與眾不同
19.2. 快速入門指南
19.3. zpool 管理
19.4. zfs 管理
19.5. 委託管理
19.6. 進階主題
19.7. 其他資源
19.8. ZFS 特色與術語
20. 其他檔案系統
20.1. 概述
20.2. Linux® 檔案系統
21. 虛擬化
21.1. 概述
21.2. 在 Mac OS® X 的 Parallels 安裝 FreeBSD 為客端
21.3. 在 Windows® 的 Virtual PC 安裝 FreeBSD 為客端
21.4. 在 Mac OS® 的 VMware Fusion 安裝 FreeBSD 為客端
21.5. 安裝 VirtualBox™ Guest Additions 於 FreeBSD 客端
21.6. 以 FreeBSD 作為主端安裝 VirtualBox
21.7. 以 FreeBSD 作為主端安裝 bhyve
22. 在地化 - i18n/L10n 使用與安裝
22.1. 概述
22.2. 使用語系
22.3. 尋找 i18n 應用程式
22.4. 特定語言的語系設定
23. 更新與升級 FreeBSD
23.1. 概述
23.2. FreeBSD 更新
23.3. 更新文件集
23.4. 追蹤開發分支
23.5. Updating FreeBSD from Source
23.6. 多部機器追蹤
24. DTrace
24.1. 概述
24.2. 實作差異
24.3. 開啟 DTrace 支援
24.4. 使用 DTrace
IV. 網路通訊
25. 序列通訊
25.1. 概述
25.2. 序列術語與硬體
25.3. 終端機
25.4. 撥入服務
25.5. 撥出服務
25.6. 設定序列 Console
26. PPP
26.1. 概述
26.2. 設定 PPP
26.3. PPP 連線疑難排解
26.4. 在乙太網路使用 PPP (PPPoE)
26.5. 在 ATM 使用 PPP (PPPoA)
27. 電子郵件
27.1. 概述
27.2. 郵件組成
27.3. Sendmail 設定檔
27.4. 更改郵件傳輸代理程式
27.5. 疑難排解
27.6. 進階主題
27.7. 寄件設定
27.8. 在撥號連線使用郵件
27.9. SMTP 認證
27.10. 郵件使用者代理程式
27.11. 使用 fetchmail
27.12. 使用 procmail
28. 網路伺服器
28.1. 概述
28.2. inetd 超級伺服器
28.3. 網路檔案系統 (NFS)
28.4. 網路資訊系統 (NIS)
28.5. 輕量級目錄存取協定 (LDAP)
28.6. 動態主機設定協定 (DHCP)
28.7. 網域名稱系統 (DNS)
28.8. Apache HTTP 伺服器
28.9. 檔案傳輸協定 (FTP)
28.10. Microsoft® Windows® 用戶端檔案與列印服務 (Samba)
28.11. NTP 時間校對
28.12. iSCSI Initiator 與 Target 設定
29. 防火牆
29.1. 概述
29.2. 防火牆概念
29.3. PF
29.4. IPFW
29.5. IPFILTER (IPF)
30. 進階網路設定
30.1. 概述
30.2. 通訊閘與路由
30.3. 無線網路
30.4. USB 網路共享
30.5. 藍牙
30.6. 橋接
30.7. Link Aggregation 與容錯移轉
30.8. PXE 無磁碟作業
30.9. IPv6
30.10. 共用位址備援協定 (CARP)
V. 附錄
A. 取得 FreeBSD
A.1. CDDVD 合集
A.2. FTP
A.3. 使用 Subversion
A.4. 使用 rsync
B. 參考書目
B.1. FreeBSD 相關書籍
B.2. 使用指南
B.3. 管理指南
B.4. 開發指南
B.5. 深入作業系統
B.6. 安全性參考文獻
B.7. 硬體參考文獻
B.8. UNIX® 歷史
B.9. 期刊與雜誌
C. 網路資源
C.1. 網站
C.2. 郵遞論壇 (Mailing List)
C.3. Usenet 新聞群組
C.4. 官方鏡像站
D. OpenPGP 金鑰
D.1. 人員
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 Dumps
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. Ports 套件集中可用的 Console
22.4. 可用的輸入法
23.1. FreeBSD Versions and Repository Paths
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. 磁碟、Slice 及分割區命名範例
3.13. 磁碟的概念模型
5.1. 在單檔中選擇 Intel® 影像驅動程式
5.2. 在單檔中選擇 Radeon 影像驅動程式
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. 乙太網路與無線介面間的容錯移轉模式

給讀者的話

若您是第一次接觸 FreeBSD 的新手,可以在本書第一部分找到 FreeBSD 的安裝方法,同時會逐步介紹 UNIX® 的基礎概念與一些常用、共通的東西。而閱讀這部分並不難,只需要您有探索的精神和接受新概念。

讀完這些之後,手冊中的第二部分花很長篇幅介紹的各種廣泛主題,相當值得系統管理者去注意。 在閱讀這些章節的內容時所需要的背景知識,都註釋在該章的大綱裡面,若不熟的話,可在閱讀前先預習一番。

延伸閱讀方面,可參閱 附錄 B, 參考書目

自第三版後的主要修訂

您目前看到的這本手冊代表著上百位貢獻者歷時 10 年所累積的心血之作。以下為自 2014 年發佈的兩冊第三版後所做的主要修訂:

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

您目前看到的這本手冊第三版是 FreeBSD 文件計劃的成員歷時兩年完成的心血之作。因文件內容成長到一定大小,印刷版需要分成兩冊發佈。新版的主要修訂部分如下:

  • 章 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)

本手冊的第二版是 FreeBSD 文件計劃的成員歷時兩年完成的心血之作。第二版包的主要變動如下︰

本書架構

本書主要分為五大部分,第一部份入門:介紹 FreeBSD 的安裝、基本操作。 讀者可根據自己的程度,循序或者跳過一些熟悉的主題來閱讀; 第二部分一般作業:介紹 FreeBSD 常用功能,這部分可以不按順序來讀。 每章前面都會有概述,概述會描述本章節涵蓋的內容和讀者應該已知的, 這主要是讓讀者可以挑喜歡的章節閱讀; 第三部分系統管理:介紹 FreeBSD 老手所感興趣的各種主題部分; 第四部分網路通訊:則包括網路和各式伺服器主題;而第五部分則為附錄包含各種有關 FreeBSD 的資源。

章 1, 簡介

向新手介紹 FreeBSD。該篇說明了 FreeBSD 計劃的歷史、目標和開發模式。

章 2, 安裝 FreeBSD

帶領使用者走一次使用 bsdinstall 在 FreeBSD 9.x 及之後版本的完整安裝流程。

章 3, FreeBSD Basics

涵蓋 FreeBSD 作業系統的基礎指令及功能。若您熟悉 Linux® 或其他類 UNIX® 系統,您則可跳過此章。

章 4, 安裝應用程式: 套件與 Ports

涵蓋如何使用 FreeBSD 獨創的 Ports 套件集 與標準 Binary 套件安裝第三方軟體。

章 5, X Window 系統

介紹 X Windows 系統概要及在 FreeBSD 上使用 X11,同時也會介紹常用的桌面環境如 KDEGNOME

章 6, 桌面應用程式

列出一些常用的桌面應用程式,例如:網頁瀏覽器、辦工工具並介紹如何安裝這些應用程式到 FreeBSD。

章 7, 多媒體

示範如何在您的系統設定音效及影像播放支援,同時會介紹幾個代表性的音訊及視訊應用程式。

章 8, 設定 FreeBSD 核心

說明為何需要設定新的核心並會提供設定、編譯與安裝的詳細操作說明。

章 9, 列印

介紹如何在 FreeBSD 管理印表機,包含橫幅頁面、列印帳務以及初始設定等資訊。

章 10, Linux® Binary 相容性

介紹 FreeBSD 的 Linux® 相容性功能,同時提供許多熱門的 Linux® 應用程式詳細的安裝操作說明,例如 Oracle®Mathematica®

章 11, 設定與調校

介紹可供系統管理者用來調校 FreeBSD 系統的可用參數來最佳化效率,同時也介紹 FreeBSD 用到的各種設定檔以及到何處尋找這些設定檔。

章 12, FreeBSD 開機程序

介紹 FreeBSD 開機流程並說明如何使用設定選項控制開機流程。

章 13, 安全性

介紹許多可讓您的 FreeBSD 系統更安全的各種工具,包含 Kerberos, IPsec 及 OpenSSH。

章 14, Jails

Describes the jails framework, and the improvements of jails over the traditional chroot support of FreeBSD.

章 15, 強制存取控制 (MAC)

Explains what Mandatory Access Control (MAC) is and how this mechanism can be used to secure a FreeBSD system.

章 16, 安全事件稽查

Describes what FreeBSD Event Auditing is, how it can be installed, configured, and how audit trails can be inspected or monitored.

章 17, 儲存設備

Describes how to manage storage media and filesystems with FreeBSD. This includes physical disks, RAID arrays, optical and tape media, memory-backed disks, and network filesystems.

章 18, GEOM: Modular Disk Transformation Framework

Describes what the GEOM framework in FreeBSD is and how to configure various supported RAID levels.

章 20, 其他檔案系統

Examines support of non-native file systems in FreeBSD, like the Z File System from Sun™.

章 21, 虛擬化

Describes what virtualization systems offer, and how they can be used with FreeBSD.

章 22, 在地化 - i18n/L10n 使用與安裝

Describes how to use FreeBSD in languages other than English. Covers both system and application level localization.

章 23, 更新與升級 FreeBSD

Explains the differences between FreeBSD-STABLE, FreeBSD-CURRENT, and FreeBSD releases. Describes which users would benefit from tracking a development system and outlines that process. Covers the methods users may take to update their system to the latest security release.

章 24, DTrace

Describes how to configure and use the DTrace tool from Sun™ in FreeBSD. Dynamic tracing can help locate performance issues, by performing real time system analysis.

章 25, 序列通訊

Explains how to connect terminals and modems to your FreeBSD system for both dial in and dial out connections.

章 26, PPP

Describes how to use PPP to connect to remote systems with FreeBSD.

章 27, 電子郵件

Explains the different components of an email server and dives into simple configuration topics for the most popular mail server software: sendmail.

章 28, 網路伺服器

Provides detailed instructions and example configuration files to set up your FreeBSD machine as a network filesystem server, domain name server, network information system server, or time synchronization server.

章 29, 防火牆

Explains the philosophy behind software-based firewalls and provides detailed information about the configuration of the different firewalls available for FreeBSD.

章 30, 進階網路設定

Describes many networking topics, including sharing an Internet connection with other computers on your LAN, advanced routing topics, wireless networking, Bluetooth®, ATM, IPv6, and much more.

附錄 A, 取得 FreeBSD

Lists different sources for obtaining FreeBSD media on CDROM or DVD as well as different sites on the Internet that allow you to download and install FreeBSD.

附錄 B, 參考書目

This book touches on many different subjects that may leave you hungry for a more detailed explanation. The bibliography lists many excellent books that are referenced in the text.

附錄 C, 網路資源

Describes the many forums available for FreeBSD users to post questions and engage in technical conversations about FreeBSD.

附錄 D, OpenPGP 金鑰

Lists the PGP fingerprints of several FreeBSD Developers.

本書的編排體裁

為方便閱讀本書,以下是一些本書所遵循的編排體裁:

文字編排體裁

斜體字

斜體字用於:檔名、目錄、網址(URL)、 強調語氣、以及第一次提及的技術詞彙。

等寬字

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

粗體字

粗體字表示:應用程式、命令、按鍵。

使用者輸入

鍵盤輸入以粗體字表示,以便與一般文字做區隔。 組合鍵是指同時按下一些按鍵,我們以 `+' 來表示連接,像是:

Ctrl+Alt+Del

是說,一起按 CtrlAlt 以及 Del 鍵。

若要逐一按鍵,那麼會以逗號(,)來表示,像是:

Ctrl+X, Ctrl+S

是說:先同時按下 CtrlX 鍵, 然後放開後再同時按 CtrlS 鍵。

範例

範例以 C:\> 為開頭代表 MS-DOS® 的指令。 若沒有特殊情況的話,這些指令應該是在 Microsoft® Windows® 環境的 命令提示字元(Command Prompt) 視窗內執行。

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

範例以 # 為開頭代表在 FreeBSD 中以超級使用者權限來執行的指令。 你可以先以 root 登入系統並下指令,或是以你自己的帳號登入再使用 su(1) 來取得超級使用者權限。

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

範例以 % 為開頭代表在 FreeBSD 中以一般使用者帳號執行的指令。 除非有提到其他用法,否則都是預設為 C-shell 語法,用來設定環境變數以及下其他指令的意思。

% top

銘謝

您所看到的這本書是經過數百個分散在世界各地的人所努力而來的結果。 無論他們只是糾正一些錯誤或提交完整的章節,所有的點滴貢獻都是非常寶貴有用的。

也有一些公司透過提供資金讓作者專注於撰稿、提供出版資金等模式來支持文件的寫作。 其中,BSDi (之後併入 Wind River Systems) 資助 FreeBSD 文件計劃成員來專職改善這本書直到 2000 年 3 月第一版的出版。(ISBN 1-57176-241-8) Wind River Systems 同時資助其他作者來對輸出架構做很多改進,以及給文章增加一些附加章節。這項工作結束於 2001 年 11 月第二版。(ISBN 1-57176-303-1) 在 2003-2004 兩年中,FreeBSD Mall, Inc 把報酬支付給改進這本手冊以使第三版印刷版本能夠出版的志工。

部 I. 入門

章 1. 簡介

Restructured, reorganized, and parts rewritten by Jim Mock.

1.1. 概述

非常感謝您對 FreeBSD 感興趣!以下章節涵蓋 FreeBSD 計劃的各方面:比如它的歷史、目標、開發模式等等。

讀完這章,您將了解︰

  • 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 的 ports套件 管理機制來取得。 不再需要費心到網路上到處搜尋所需要的軟體。

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

  • 需要時才置換的 虛擬記憶體merged VM/buffer cache 的設計, 這點在系統中有用去大量記憶體的程式執行時,仍然有不錯的效率表現。

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

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

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

  • 廣泛且豐富的 線上文件

  • 當然囉,還不止如此!

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

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

由於每個人都可以取得 FreeBSD 的原始程式碼, 這個系統可以被量身訂做成能執行任何原本完全無法想像的功能或計劃, 而對於從各廠商取得的作業系統通常沒有辦法這樣地被修改。 以下提供一些人們使用 FreeBSD 的例子:

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

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

    • IPv4 及 IPv6 路由

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

    • 檔案傳輸協定伺服器

    • 電子郵件伺服器

    • 還有更多...

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

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

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

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

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

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

你可以經由燒錄 CD-ROM、DVD 或是從 FTP 站上抓回 FreeBSD。 詳情請參閱 附錄 A, 取得 FreeBSD 取得 FreeBSD。

1.2.2. 誰在用 FreeBSD?

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

  • Apache - The Apache Software Foundation runs most of its public facing infrastructure, including possibly one of the largest SVN repositories in the world with over 1.4 million commits, on FreeBSD.

  • Apple - OS X borrows heavily from FreeBSD for the network stack, virtual file system, and many userland components. Apple iOS also contains elements borrowed from FreeBSD.

  • Cisco - IronPort network security and anti-spam appliances run a modified FreeBSD kernel.

  • Citrix - The NetScaler line of security appliances provide layer 4-7 load balancing, content caching, application firewall, secure VPN, and mobile cloud network access, along with the power of a FreeBSD shell.

  • Dell KACE - The KACE system management appliances run FreeBSD because of its reliability, scalability, and the community that supports its continued development.

  • Experts Exchange - All public facing web servers are powered by FreeBSD and they make extensive use of jails to isolate development and testing environments without the overhead of virtualization.

  • Isilon - Isilon's enterprise storage appliances are based on FreeBSD. The extremely liberal FreeBSD license allowed Isilon to integrate their intellectual property throughout the kernel and focus on building their product instead of an operating system.

  • iXsystems - The TrueNAS line of unified storage appliances is based on FreeBSD. In addition to their commercial products, iXsystems also manages development of the open source projects PC-BSD and FreeNAS.

  • Juniper - The JunOS operating system that powers all Juniper networking gear (including routers, switches, security, and networking appliances) is based on FreeBSD. Juniper is one of many vendors that showcases the symbiotic relationship between the project and vendors of commercial products. Improvements generated at Juniper are upstreamed into FreeBSD to reduce the complexity of integrating new features from FreeBSD back into JunOS in the future.

  • McAfee - SecurOS, the basis of McAfee enterprise firewall products including Sidewinder is based on FreeBSD.

  • NetApp - The Data ONTAP GX line of storage appliances are based on FreeBSD. In addition, NetApp has contributed back many features, including the new BSD licensed hypervisor, bhyve.

  • Netflix - The OpenConnect appliance that Netflix uses to stream movies to its customers is based on FreeBSD. Netflix has made extensive contributions to the codebase and works to maintain a zero delta from mainline FreeBSD. Netflix OpenConnect appliances are responsible for delivering more than 32% of all Internet traffic in North America.

  • Sandvine - Sandvine uses FreeBSD as the basis of their high performance realtime network processing platforms that make up their intelligent network policy control products.

  • Sony - The PlayStation 4 gaming console runs a modified version of FreeBSD.

  • Sophos - The Sophos Email Appliance product is based on a hardened FreeBSD and scans inbound mail for spam and viruses, while also monitoring outbound mail for malware as well as the accidental loss of sensitive information.

  • Spectra Logic - The nTier line of archive grade storage appliances run FreeBSD and OpenZFS.

  • The Weather Channel - The IntelliStar appliance that is installed at each local cable providers headend and is responsible for injecting local weather forecasts into the cable TV network's programming runs FreeBSD.

  • Verisign - Verisign is responsible for operating the .com and .net root domain registries as well as the accompanying DNS infrastructure. They rely on a number of different network operating systems including FreeBSD to ensure there is no common point of failure in their infrastructure.

  • Voxer - Voxer powers their mobile voice messaging platform with ZFS on FreeBSD. Voxer switched from a Solaris derivative to FreeBSD because of its superior documentation, larger and more active community, and more developer friendly environment. In addition to critical features like ZFS and DTrace, FreeBSD also offers TRIM support for ZFS.

  • WhatsApp - When WhatsApp needed a platform that would be able to handle more than 1 million concurrent TCP connections per server, they chose FreeBSD. They then proceeded to scale past 2.5 million connections per server.

  • Wheel Systems - The FUDO security appliance allows enterprises to monitor, control, record, and audit contractors and administrators who work on their systems. Based on all of the best security features of FreeBSD including ZFS, GELI, Capsicum, HAST, and auditdistd.

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

  • BSD Router - A FreeBSD based replacement for large enterprise routers designed to run on standard PC hardware.

  • FreeNAS - A customized FreeBSD designed to be used as a network file server appliance. Provides a python based web interface to simplify the management of both the UFS and ZFS file systems. Includes support for NFS, SMB/CIFS, AFP, FTP, and iSCSI. Includes an extensible plugin system based on FreeBSD jails.

  • GhostBSD - A desktop oriented distribution of FreeBSD bundled with the Gnome desktop environment.

  • mfsBSD - A toolkit for building a FreeBSD system image that runs entirely from memory.

  • NAS4Free - A file server distribution based on FreeBSD with a PHP powered web interface.

  • OPNSense - OPNsense is an open source, easy-to-use and easy-to-build FreeBSD based firewall and routing platform. OPNsense includes most of the features available in expensive commercial firewalls, and more in many cases. It brings the rich feature set of commercial offerings with the benefits of open and verifiable sources.

  • PC-BSD - A customized version of FreeBSD geared towards desktop users with graphical utilities to exposing the power of FreeBSD to all users. Designed to ease the transition of Windows and OS X users.

  • pfSense - A firewall distribution based on FreeBSD with a huge array of features and extensive IPv6 support.

  • ZRouter - An open source alternative firmware for embedded devices based on FreeBSD. Designed to replace the proprietary firmware on off-the-shelf routers.

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

還有許多的應用。維基百科也維護了一份 以 FreeBSD 為基礎的產品

1.3. 關於 FreeBSD 計劃

接下來講的是 FreeBSD 計劃的背景,包含歷史、計劃目標以及開發模式。

1.3.1. FreeBSD 歷史簡介

FreeBSD 計畫的想法是在 1993 年初所形成的, 那是源自於維護一組『非官方 386BSD 的修正工具』計劃的三個協調維護人 Nate Williams,Rod Grimes 和 Jordan Hubbard。

最初的目標是做出一份 386BSD 綜合修正的 snapshot 版,以便修正當時一堆 patchkit 都不容易解決的問題。有些人可能還記得早期的計劃名稱叫做 386BSD 0.5 或 386BSD Interim 就是這個原因。

386BSD 是 Bill Jolitz 的作業系統,在當時就已有約一年的分裂討論。 當該修正工具 (patchkit) 日漸龐雜得令人不舒服,我們無異議地同意要作一些事了, 並決定提供一份臨時性的 淨化版(cleanup) 來幫助 Bill。 然而,由於 Bill Jolitz 忽然決定取消其對該計劃的認可,且沒有明確指出未來的打算, 所以該計劃便突然面臨斷炊危機。

不久我們便決定在即使沒有 Bill 的支持下,讓該計劃仍然繼續下去, 最後我們採用 David Greenman 丟銅板決定的名字,也就是『FreeBSD』。 在詢問了當時的一些使用者意見之後,就開始決定了最初的目標, 當該計劃開始實施一切就要成真時,一切就變得更清楚了。 我跟 Walnut Creek CD-ROM 討論發行 CD-ROM 這樣子不便上網的人就可以用比較簡單的方式取得 FreeBSD。 Walnut Creek CD-ROM 不只贊成以 CD-ROM 來發行 FreeBSD 的想法,同時提供了一台機器以及快速的網際網路的頻寬。 如果不是 Walnut Creek CD-ROM 幾乎是空前的信任這個剛開始還是完全默默無聞的計劃, 那麼很可能 FreeBSD 不會如此快速的成長到今日這樣的規模。

第一張以 CD-ROM (及網路)發行的 FreeBSD 1.0 是在 1993 年十二月。 該版本是基於由 U.C. Berkeley 以磁帶方式發行的 4.3BSD-Lite (Net/2)以及許多來自於 386BSD 和自由軟體基金會的軟體。對於第一次發行而言還算成功, 我們又接著於 1994 年 5 月發行了相當成功的 FreeBSD 1.1。

然而此後不久,另一個意外的風暴在 Novell 和 U.C. Berkeley 關於 Berkeley Net/2 磁帶之法律地位的訴訟確定之後形成。 U.C. Berkeley 接受大部份的 Net/2 的程式碼都是侵佔來的且是屬於 Novell 的財產 -- 事實上是當時不久前從 AT&T 取得的。 Berkeley 得到的是 Novell 對於 4.4BSD-Lite 的祝福,最後當 4.4BSD-Lite 終於發行之後,便不再是侵佔行為。 而所有現有 Net/2 使用者都被強烈建議更換新版本,這包括了 FreeBSD。 於是,我們被要求於 1994 年 6 月底前停止散佈基於 Net/2 的產品。在此前提之下,本計劃被允許在期限以前作最後一次發行,也就是 FreeBSD 1.1.5.1。

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

自那時以來,FreeBSD 在每一次對先前版本改進穩定性、速度及功能時便會發佈一個新的發佈版本。

目前,長期的開發計畫繼續在 10.X-CURRENT (trunk) 分支中進行,而 10.X 的 snapshot 版本可以在 Snapshot 伺服器 取得。

1.3.2. FreeBSD 計劃目標

Contributed by Jordan Hubbard.

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

我們程式碼樹中,有若干是以 GNU 通用公共授權條款 (GPL) 或者 GNU Lesser General Public License (LGPL) 發佈的那些程式碼帶有少許的附加限制,還好只是強制性的要求開放程式碼而不是別的。 由於使用 GPL 的軟體在商業用途上會增加若干複雜性,因此,如果可以選擇的話, 我們會比較喜歡使用限制相對更寬鬆的 BSD 版權來發佈軟體。

1.3.3. FreeBSD 開發模式

Contributed by Satoshi Asami.

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

無論是單獨開發者或者封閉式的團隊合作,多瞭解 FreeBSD 計劃和它的開發過程會是不錯的︰

SVN 檔案庫

過去數年來 FreeBSD 的中央原始碼樹 (Source tree) 一直是以 CVS (Concurrent Versions System) 來維護的, 它是一套免費的原始碼控管工具。 從 2008 年 6 月起, FreeBSD 計劃開始改用 SVN (Subversion)。 這是一個必要的更換動作,因為隨著原始碼樹及歷史版本儲存的數量不斷快速擴張,CVS 先天的技術限制越來越明顯。 文件計劃與 Ports 套件集檔案庫也同樣於 2012 年 5 月及 2012 年 7 月由 CVS 改為 SVN。請參考 同步您的原始碼樹 一節來取得有關如何取得 FreeBSD src/ 檔案庫的更多資訊,以及 使用 Ports 套件集 了解如何取得 FreeBSD Ports 套件集。

提交者名單

所謂的 提交者 (Committers) 指的是對 Subversion 原始碼樹有 寫入 權限的人, 並且被授予修改 FreeBSD 原始碼的權限。 (committer 一詞源自版本管理系統中的 commit 指令,該指令是用來把新的修改提交給檔案庫)。 任何人都可以回報問題到 Bug Database,在回報問題之前,可以使用 FreeBSD 郵遞清單、IRC 頻道或論壇來確認問題真的是一個錯誤 (Bug)。

FreeBSD 核心團隊

如果把 FreeBSD 看成是一家公司的話, FreeBSD 核心團隊 就相當於董事會。 核心團隊的主要職責在於確保此計劃有良好的架構,以朝著正確的方向發展。 此外,邀請熱血且負責的軟體開發者加入提交者的行列, 以在若干成員離去時得以補充新血。 目前的核心團隊是在 2014 年 7 月從提交者候選人之中選出來的,這個選舉每兩年會舉辦一次。

注意:

如同多數的開發者,核心團隊大部分成員加入 FreeBSD 開發都是志工性質而已, 並未從本計劃中獲得任何薪酬,所以這只是一個 承諾 不應該被誤解為 保證支援 才對。 前面用 董事會 來舉例可能不是很恰當,或許我們應該說: 他們是一群自願放棄原本的優渥生活、個人其他領域成就, 而選擇投入 FreeBSD 開發的熱血有為者才對!

非官方貢獻者

最後一點,但這點絕非最不重要的, 最大的開發者團隊就是持續為我們提供回饋以及錯誤修正的使用者自己。 與 FreeBSD 非核心開發者互動的主要方式,便是透過訂閱 FreeBSD 技術討論郵遞論壇 來進行溝通,這方面可參考,請參閱 附錄 C, 網路資源 以瞭解各式不同的 FreeBSD 郵遞論壇。

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

提供原始碼並非為這個計劃做貢獻的唯一方式; 需要大家投入的完整工作清單請參閱 FreeBSD 計畫網站

總而言之,我們的開發模式像是由鬆散的同心圓所組織。這個集中模式的設計為的是讓 FreeBSD 的使用者更便利,可以很容易的追蹤同一個中央的程式庫,避免把潛在的貢獻者排除在外!而我們的目標是提供一個穩定的作業系統,並有大量相關的 應用程式,讓使用者能夠輕鬆的安裝與使用 — 而這個開發模式對我們要完成這個目標來說運作的非常好。

我們對於那些想要加入 FreeBSD 開發者的期待是: 請保持如同前人一樣的投入,以確保繼續成功!

1.3.4. 第三方程式

In addition to the base distributions, FreeBSD offers a ported software collection with thousands of commonly sought-after programs. At the time of this writing, there were over 24,000 ports! The list of ports ranges from http servers, to games, languages, editors, and almost everything in between. The entire Ports Collection requires approximately 500 MB. To compile a port, you simply change to the directory of the program you wish to install, type make install, and let the system do the rest. The full original distribution for each port you build is retrieved dynamically so you need only enough disk space to build the ports you want. Almost every port is also provided as a pre-compiled package, which can be installed with a simple command (pkg install) by those who do not wish to compile their own ports from source. More information on packages and ports can be found in 章 4, 安裝應用程式: 套件與 Ports.

1.3.5. 其他文件

All recent FreeBSD versions provide an option in the installer (either sysinstall(8) or bsdinstall(8)) to install additional documentation under /usr/local/share/doc/freebsd during the initial system setup. Documentation may also be installed at any later time using packages as described in 節 23.3.2, “自 Ports 更新說明文件”. You may view the locally installed manuals with any HTML capable browser using the following URLs:

此外,可在下列網址找到最新版 (也是更新最頻繁的版本):http://www.FreeBSD.org/

章 2. 安裝 FreeBSD

Restructured, reorganized, and parts rewritten by Jim Mock.
Updated for bsdinstall by Gavin Atkinson and Warren Block.
Updated for root-on-ZFS by Allan Jude.

2.1. 概述

自從 FreeBSD 9.0-RELEASE 開始, FreeBSD 提供一個易用,文字介面的安裝程式 bsdinstall。 本章描述如何用 bsdinstall 來安裝 FreeBSD。

一般來說,本章所寫的安裝說明是針對 i386™ 和 AMD64 架構。如果可以用於其他平台,將會列表說明。 安裝程式和本章所敘述的內容可能會有些微差異,所以請將本章視為通用的指引,而不是完全照著來做。

注意:

喜歡用圖形化安裝程式安裝 FreeBSD 的使用者, 可能會對 pc-sysinstall 有興趣,這是 PC-BSD 計畫所使用的。 他可以用來安裝圖形化桌面 (PC-BSD) 或是指令列版本的 FreeBSD。 細節請參考 PC-BSD 使用者 Handbook (http://wiki.pcbsd.org/index.php/Colophon)。

讀完這章,您將了解︰

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

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

  • 如何開始執行 bsdinstall

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

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

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

在開始閱讀這章之前,您需要︰

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

2.2. 最低硬體需求

安裝 FreeBSD 的硬體需求隨 FreeBSD 的版本和硬體架構而不同。 FreeBSD 發行版支援的硬體架構和裝置可在 FreeBSD 網站 (http://www.FreeBSD.org/releases/index.html)的發行資訊頁面找到。

FreeBSD 最小安裝需要至少 64 MB 的 RAM 和 1.5 GB 的可用硬碟空間 但是這真的是 最小,幾乎沒有剩下多餘的空間。 RAM 的需求視實際使用而訂,經特殊處理過後的 FreeBSD 系統可只使用 128MB RAM,圖形化環境最少需要 4 GB 的 RAM

每一種架構的處理器需求概述如下:

amd64

這桌上型電腦與筆記型電腦是最常見的處理器類型,有些廠商可能會稱之為 x86-64

主要有兩個廠商提供 amd64 處理器:Intel® (生產 Intel64 級處理器) 以及 AMD (生產 AMD64)。

與 amd64 相容的處理器包含:AMD Athlon™64, AMD Opteron™, 多核心 Intel® Xeon™ 以及 Intel® Core™ 2 與之後的處理器。

i386

這個架構即為 32-bit x86 架構。

幾乎所有含浮點運算單元的 i386 相容處理器都有支援。所有 Intel® 486 或是更高階的處理器也有支援。

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

ia64

目前支援的處理器是 Itanium® 和 Itanium® 2。支援的晶片組包括 HP zx1, Intel® 460GX 和 Intel® E8870。 單處理器 (Uniprocessor, UP) 和對稱多處理器 (Symmetric Multi-processor, SMP)的設定都有支援。

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 系列也有支援。

不支援高解析度模式。NEC PC-98XA/XL/RL/XL^2 和 NEC PC-H98 系列只支援正常 (PC-9801 相容) 模式。 FreeBSD 對稱多處理器 SMP 相關功能並不支援。 PC-H98, SV-H98 和FC-H98 新延伸標準架構 (NESA) 匯流排不支援。

powerpc

所有內建 USB 的 New World ROM Apple® Mac® 系統都有支援。 SMP 在多 CPU 的機器都有支援。

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

sparc64

FreeBSD/sparc64 支援的系統列在 FreeBSD/sparc64 計劃 (http://www.freebsd.org/platforms/sparc.html)。

所有超過一個處理器的系統都有支援 SMP。需要專用的磁碟系統,因為此時無法和其他作業系統共用磁碟。

2.3. 安裝前準備工作

一旦確定系統符合安裝 FreeBSD 的最低硬體需求,就可以下載安裝檔案並準備安裝的媒體。 做這些之前,先檢查以下核對清單的項目是否準備好了:

  1. 備份重要資料

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

  2. 決定 FreeBSD 安裝在哪裡

    如果 FreeBSD 是唯一要安裝的作業系統,這個步驟可以略過。 但是假如 FreeBSD 將和其他作業系統分享磁碟空間的話,要決定 FreeBSD 要安裝在哪個磁碟或是哪個分割區。

    在 i386 和 amd64 平台,磁碟可以使用兩種分割區配置之一來分割成多個分割區。 傳統的主開機紀錄 (Master Boot Record, MBR) 有一個分割區表定義最多到 主分割區。 因為歷史性的理由, FreeBSD 稱這些主分割區為 slices。 其中一個主分割區可以分成一個 延伸分割區 ,他包含多個 邏輯分割區。 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 , 需要從區域網路管理者或是網際網路服務商取得以下系統的網路資訊:

    需要的網路資訊
    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. 準備安裝的媒體

The FreeBSD installer is not an application that can be run from within another operating system. Instead, download a FreeBSD installation file, burn it to the media associated with its file type and size (CD, DVD, or USB), and boot the system to install from the inserted media.

FreeBSD installation files are available at www.freebsd.org/where.html#download. Each installation file's name includes the release version of FreeBSD, the architecture, and the type of file. For example, to install FreeBSD 10.2 on an amd64 system from a DVD, download FreeBSD-10.2-RELEASE-amd64-dvd1.iso, burn this file to a DVD, and boot the system with the DVD inserted.

Installation files are available in several formats. The formats vary depending on computer architecture and media type.

Additional installation files are included for computers that boot with UEFI (Unified Extensible Firmware Interface). The names of these files include the string uefi.

File types:

  • -bootonly.iso: This is the smallest installation file as it only contains the installer. A working Internet connection is required during installation as the installer will download the files it needs to complete the FreeBSD installation. This file should be burned to a CD using a CD burning application.

  • -disc1.iso: This file contains all of the files needed to install FreeBSD, its source, and the Ports Collection. It should be burned to a CD using a CD burning application.

  • -dvd1.iso: This file contains all of the files needed to install FreeBSD, its source, and the Ports Collection. It also contains a set of popular binary packages for installing a window manager and some applications so that a complete system can be installed from media without requiring a connection to the Internet. This file should be burned to a DVD using a DVD burning application.

  • -memstick.img: This file contains all of the files needed to install FreeBSD, its source, and the Ports Collection. It should be burned to a USB stick using the instructions below.

After downloading the image file, download CHECKSUM.SHA256 from the same directory. Calculate a checksum for the image file. FreeBSD provides sha256(1) for this, used as sha256 imagefilename. Other operating systems have similar programs.

Compare the calculated checksum with the one shown in CHECKSUM.SHA256. The checksums must match exactly. If the checksums do not match, the image file is corrupt and must be downloaded again.

2.3.1.1. 寫入映象檔到 USB

The *.img file is an image of the complete contents of a memory stick. It cannot be copied to the target device as a file. Several applications are available for writing the *.img to a USB stick. This section describes two of these utilities.

重要:

在繼續之前,請先備份 USB 上的重要資料,這個程序會清除在隨身碟上既有的資料。

過程 2.1. 使用 dd 來寫入映像檔

警告:

This example uses /dev/da0 as the target device where the image will be written. Be very careful that the correct device is used as this command will destroy the existing data on the specified target device.

  • The dd(1) command-line utility is available on BSD, Linux®, and Mac OS® systems. To burn the image using dd, insert the USB stick and determine its device name. Then, specify the name of the downloaded installation file and the device name for the USB stick. This example burns the amd64 installation image to the first USB device on an existing FreeBSD system.

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

    If this command fails, verify that the USB stick is not mounted and that the device name is for the disk, not a partition. Some operating systems might require this command to be run with sudo(8). Systems like Linux® might buffer writes. To force all writes to complete, use sync(8).

過程 2.2. 使用 Windows® 來寫入映象檔

警告:

Be sure to give the correct drive letter as the existing data on the specified drive will be overwritten and destroyed.

  1. 取得 Image Writer Windows® 版

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

  2. 用 Image Writer 寫入映象檔

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

您現在可以開始安裝 FreeBSD 。

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?

在這個警告訊息之前可以隨時中止安裝,若有任何設定錯誤的疑慮,只需在此時關閉電腦,將不會對系統磁碟做任何更改。

This section describes how to boot the system from the installation media which was prepared using the instructions in 節 2.3.1, “準備安裝的媒體”. When using a bootable USB stick, plug in the USB stick before turning on the computer. When booting from CD or DVD, turn on the computer and insert the media at the first opportunity. How to configure the system to boot from the inserted media depends upon the architecture.

2.4.1. 在 i386™ 及 amd64 開機

These architectures provide a BIOS menu for selecting the boot device. Depending upon the installation media being used, select the CD/DVD or USB device as the first boot device. Most systems also provide a key for selecting the boot device during startup without having to enter the BIOS. Typically, the key is either F10, F11, F12, or Escape.

If the computer loads the existing operating system instead of the FreeBSD installer, then either:

  1. The installation media was not inserted early enough in the boot process. Leave the media inserted and try restarting the computer.

  2. The BIOS changes were incorrect or not saved. Double-check that the right boot device is selected as the first boot device.

  3. This system is too old to support booting from the chosen media. In this case, the Plop Boot Manager (http://www.plop.at/en/bootmanagers.html) can be used to boot the system from the selected media.

2.4.2. 在 PowerPC® 開機

On most machines, holding C on the keyboard during boot will boot from the CD. Otherwise, hold Command+Option+O+F, or Windows+Alt+O+F on non-Apple® keyboards. At the 0 > prompt, enter

boot cd:,\ppc\loader cd:0

2.4.3. 在 SPARC64® 開機

Most SPARC64® systems are set up to boot automatically from disk. To install FreeBSD from a CD requires a break into the PROM.

To do this, reboot the system and wait until the boot message appears. The message depends on the model, but should look something like this:

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

If the system proceeds to boot from disk at this point, press L1+A or Stop+A on the keyboard, or send a BREAK over the serial console. When using tip or cu, ~# will issue a BREAK. The PROM prompt will be ok on systems with one CPU and ok {0} on SMP systems, where the digit indicates the number of the active CPU.

At this point, place the CD into the drive and type boot cdrom from the PROM prompt.

2.4.4. FreeBSD 開機選單

Once the system boots from the installation media, a menu similar to the following will be displayed:

圖形 2.1. FreeBSD 開機載入程式選單
FreeBSD 開機載入程式選單

By default, the menu will wait ten seconds for user input before booting into the FreeBSD installer or, if FreeBSD is already installed, before booting into FreeBSD. To pause the boot timer in order to review the selections, press Space. To select an option, press its highlighted number, character, or key. The following options are available.

  • Boot Multi User: This will continue the FreeBSD boot process. If the boot timer has been paused, press 1, upper- or lower-case B, or Enter.

  • Boot Single User: This mode can be used to fix an existing FreeBSD installation as described in 節 12.2.4.1, “單使用者模式”. Press 2 or the upper- or lower-case S to enter this mode.

  • Escape to loader prompt: This will boot the system into a repair prompt that contains a limited number of low-level commands. This prompt is described in 節 12.2.3, “階段三”. Press 3 or Esc to boot into this prompt.

  • Reboot: Reboots the system.

  • Configure Boot Options: Opens the menu shown in, and described under, 圖形 2.2, “FreeBSD 開機選項選單”.

圖形 2.2. FreeBSD 開機選項選單
FreeBSD 開機選項選單

The boot options menu is divided into two sections. The first section can be used to either return to the main boot menu or to reset any toggled options back to their defaults.

The next section is used to toggle the available options to On or Off by pressing the option's highlighted number or character. The system will always boot using the settings for these options until they are modified. Several options can be toggled using this menu:

  • ACPI Support: If the system hangs during boot, try toggling this option to Off.

  • Safe Mode: If the system still hangs during boot even with ACPI Support set to Off, try setting this option to On.

  • Single User: Toggle this option to On to fix an existing FreeBSD installation as described in 節 12.2.4.1, “單使用者模式”. Once the problem is fixed, set it back to Off.

  • Verbose: Toggle this option to On to see more detailed messages during the boot process. This can be useful when troubleshooting a piece of hardware.

After making the needed selections, press 1 or Backspace to return to the main boot menu, then press Enter to continue booting into FreeBSD. A series of boot messages will appear as FreeBSD carries out its hardware device probes and loads the installation program. Once the boot is complete, the welcome menu shown in 圖形 2.3, “歡迎選單” will be displayed.

圖形 2.3. 歡迎選單
歡迎選單

Press Enter to select the default of [ Install ] to enter the installer. The rest of this chapter describes how to use this installer. Otherwise, use the right or left arrows or the colorized letter to select the desired menu item. The [ Shell ] can be used to access a FreeBSD shell in order to use command line utilities to prepare the disks before installation. The [ Live CD ] option can be used to try out FreeBSD before installing it. The live version is described in 節 2.10, “使用 Live CD.

提示:

To review the boot messages, including the hardware device probe, press the upper- or lower-case S and then Enter to access a shell. At the shell prompt, type more /var/run/dmesg.boot and use the space bar to scroll through the messages. When finished, type exit to return to the welcome menu.

2.5. 使用 bsdinstall

This section shows the order of the bsdinstall menus and the type of information that will be asked before the system is installed. Use the arrow keys to highlight a menu option, then Space to select or deselect that menu item. When finished, press Enter to save the selection and move onto the next screen.

2.5.1. 選擇鍵盤對應表選單

Depending on the system console being used, bsdinstall may initially display the menu shown in 圖形 2.4, “鍵盤對應表選擇”.

圖形 2.4. 鍵盤對應表選擇
鍵盤對應表選擇

To configure the keyboard layout, press Enter with [ YES ] selected, which will display the menu shown in 圖形 2.5, “選擇鍵盤選單”. To instead use the default layout, use the arrow key to select [ NO ] and press Enter to skip this menu screen.

圖形 2.5. 選擇鍵盤選單
選擇鍵盤選單

When configuring the keyboard layout, use the up and down arrows to select the keymap that most closely represents the mapping of the keyboard attached to the system. Press Enter to save the selection.

注意:

Pressing Esc will exit this menu and use the default keymap. If the choice of keymap is not clear, United States of America ISO-8859-1 is also a safe option.

In FreeBSD 10.0-RELEASE and later, this menu has been enhanced. The full selection of keymaps is shown, with the default preselected. In addition, when selecting a different keymap, a dialog is displayed that allows the user to try the keymap and ensure it is correct before proceeding.

圖形 2.6. 改進後的鍵盤對應表選單
改進後的鍵盤對應表選單

2.5.2. 設定主機名稱

The next bsdinstall menu is used to set the hostname for the newly installed system.

圖形 2.7. 設定主機名稱
設定主機名稱

Type in a hostname that is unique for the network. It should be a fully-qualified hostname, such as machine3.example.com.

2.5.3. 選擇要安裝的元件

Next, bsdinstall will prompt to select optional components to install.

圖形 2.8. 選擇要安裝的元件
選擇要安裝的元件

Deciding which components to install will depend largely on the intended use of the system and the amount of disk space available. The FreeBSD kernel and userland, collectively known as the base system, are always installed. Depending on the architecture, some of these components may not appear:

  • doc - Additional documentation, mostly of historical interest, to install into /usr/share/doc. The documentation provided by the FreeBSD Documentation Project may be installed later using the instructions in 節 23.3, “更新文件集”.

  • games - Several traditional BSD games, including fortune, rot13, and others.

  • lib32 - Compatibility libraries for running 32-bit applications on a 64-bit version of FreeBSD.

  • ports - The FreeBSD Ports Collection is a collection of files which automates the downloading, compiling and installation of third-party software packages. 章 4, 安裝應用程式: 套件與 Ports discusses how to use the Ports Collection.

    警告:

    The installation program does not check for adequate disk space. Select this option only if sufficient hard disk space is available. The FreeBSD Ports Collection takes up about 500 MB of disk space.

  • src - The complete FreeBSD source code for both the kernel and the userland. Although not required for the majority of applications, it may be required to build device drivers, kernel modules, or some applications from the Ports Collection. It is also used for developing FreeBSD itself. The full source tree requires 1 GB of disk space and recompiling the entire FreeBSD system requires an additional 5 GB of space.

2.5.4. 從網路安裝

The menu shown in 圖形 2.9, “從網路安裝” only appears when installing from a -bootonly.iso CD as this installation media does not hold copies of the installation files. Since the installation files must be retrieved over a network connection, this menu indicates that the network interface must be first configured.

圖形 2.9. 從網路安裝
從網路安裝

To configure the network connection, press Enter and follow the instructions in 節 2.8.2, “設定網路介面”. Once the interface is configured, select a mirror site that is located in the same region of the world as the computer on which FreeBSD is being installed. Files can be retrieved more quickly when the mirror is close to the target computer, reducing installation time.

圖形 2.10. 選擇鏡像站
選擇鏡像站

Installation will then continue as if the installation files were located on the local installation media.

2.6. 配置磁碟空間

The next menu is used to determine the method for allocating disk space. The options available in the menu depend upon the version of FreeBSD being installed.

圖形 2.11. FreeBSD 9.x 的分割區選擇
FreeBSD 9.x 的分割區選擇

圖形 2.12. FreeBSD 10.x 或更新版本的磁碟分割選項
FreeBSD 10.x 或更新版本的磁碟分割選項

Guided partitioning automatically sets up the disk partitions, Manual partitioning allows advanced users to create customized partitions from menu options, and Shell opens a shell prompt where advanced users can create customized partitions using command-line utilities like gpart(8), fdisk(8), and bsdlabel(8). ZFS partitioning, only available in FreeBSD 10 and later, creates an optionally encrypted root-on-ZFS system with support for boot environments.

This section describes what to consider when laying out the disk partitions. It then demonstrates how to use the different partitioning methods.

2.6.1. 規劃分割區配置

When laying out file systems, remember that hard drives transfer data faster from the outer tracks to the inner. Thus, smaller and heavier-accessed file systems should be closer to the outside of the drive, while larger partitions like /usr should be placed toward the inner parts of the disk. It is a good idea to create partitions in an order similar to: /, swap, /var, and /usr.

The size of the /var partition reflects the intended machine's usage. This partition is used to hold mailboxes, log files, and printer spools. Mailboxes and log files can grow to unexpected sizes depending on the number of users and how long log files are kept. On average, most users rarely need more than about a gigabyte of free disk space in /var.

注意:

Sometimes, a lot of disk space is required in /var/tmp. When new software is installed, the packaging tools extract a temporary copy of the packages under /var/tmp. Large software packages, like Firefox, Apache OpenOffice or LibreOffice may be tricky to install if there is not enough disk space under /var/tmp.

The /usr partition holds many of the files which support the system, including the FreeBSD Ports Collection and system source code. At least 2 gigabytes is recommended for this partition.

When selecting partition sizes, keep the space requirements in mind. Running out of space in one partition while barely using another can be a hassle.

As a rule of thumb, the swap partition should be about double the size of physical memory (RAM). Systems with minimal RAM may perform better with more swap. Configuring too little swap can lead to inefficiencies in the VM page scanning code and might create issues later if more memory is added.

On larger systems with multiple SCSI disks or multiple IDE disks operating on different controllers, it is recommended that swap be configured on each drive, up to four drives. The swap partitions should be approximately the same size. The kernel can handle arbitrary sizes but internal data structures scale to 4 times the largest swap partition. Keeping the swap partitions near the same size will allow the kernel to optimally stripe swap space across disks. Large swap sizes are fine, even if swap is not used much. It might be easier to recover from a runaway program before being forced to reboot.

By properly partitioning a system, fragmentation introduced in the smaller write heavy partitions will not bleed over into the mostly read partitions. Keeping the write loaded partitions closer to the disk's edge will increase I/O performance in the partitions where it occurs the most. While I/O performance in the larger partitions may be needed, shifting them more toward the edge of the disk will not lead to a significant performance improvement over moving /var to the edge.

2.6.2. 引導式磁碟分割

When this method is selected, a menu will display the available disk(s). If multiple disks are connected, choose the one where FreeBSD is to be installed.

圖形 2.13. 自多個磁碟選擇
自多個磁碟選擇

Once the disk is selected, the next menu prompts to install to either the entire disk or to create a partition using free space. If [ Entire Disk ] is chosen, a general partition layout filling the whole disk is automatically created. Selecting [ Partition ] creates a partition layout from the unused space on the disk.

圖形 2.14. 選擇完整磁碟或分割區
選擇完整磁碟或分割區

After the partition layout has been created, review it to ensure it meets the needs of the installation. Selecting [ Revert ] will reset the partitions to their original values and pressing [ Auto ] will recreate the automatic FreeBSD partitions. Partitions can also be manually created, modified, or deleted. When the partitioning is correct, select [ Finish ] to continue with the installation.

圖形 2.15. 確認已建立的分割區
確認已建立的分割區

2.6.3. 手動磁碟分割

Selecting this method opens the partition editor:

圖形 2.16. 手動建立分割區
手動建立分割區

Highlight the installation drive (ada0 in this example) and select [ Create ] to display a menu of available partition schemes:

圖形 2.17. 手動建立分割區
手動建立分割區

GPT is usually the most appropriate choice for amd64 computers. Older computers that are not compatible with GPT should use MBR. The other partition schemes are generally used for uncommon or older computers.

表格 2.1. 磁碟分割格式
縮寫說明
APMApple Partition Map, used by PowerPC®.
BSDBSD label without an MBR, sometimes called dangerously dedicated mode as non-BSD disk utilities may not recognize it.
GPTGUID Partition Table (http://en.wikipedia.org/wiki/GUID_Partition_Table).
MBRMaster Boot Record (http://en.wikipedia.org/wiki/Master_boot_record).
PC98MBR variant used by NEC PC-98 computers (http://en.wikipedia.org/wiki/Pc9801).
VTOC8Volume Table Of Contents used by Sun SPARC64 and UltraSPARC computers.

After the partitioning scheme has been selected and created, select [ Create ] again to create the partitions.

圖形 2.18. 手動建立分割區
手動建立分割區

A standard FreeBSD GPT installation uses at least three partitions:

  • freebsd-boot - Holds the FreeBSD boot code.

  • freebsd-ufs - A FreeBSD UFS file system.

  • freebsd-swap - FreeBSD swap space.

Another partition type worth noting is freebsd-zfs, used for partitions that will contain a FreeBSD ZFS file system (章 19, Z 檔案系統 (ZFS)). Refer to gpart(8) for descriptions of the available GPT partition types.

Multiple file system partitions can be created and some people prefer a traditional layout with separate partitions for /, /var, /tmp, and /usr. See 範例 2.1, “建立傳統分割的檔案系統分割區” for an example.

The Size may be entered with common abbreviations: K for kilobytes, M for megabytes, or G for gigabytes.

提示:

Proper sector alignment provides the best performance, and making partition sizes even multiples of 4K bytes helps to ensure alignment on drives with either 512-byte or 4K-byte sectors. Generally, using partition sizes that are even multiples of 1M or 1G is the easiest way to make sure every partition starts at an even multiple of 4K. There is one exception: the freebsd-boot partition should be no larger than 512K due to current boot code limitations.

A Mountpoint is needed if the partition will contain a file system. If only a single UFS partition will be created, the mountpoint should be /.

The Label is a name by which the partition will be known. Drive names or numbers can change if the drive is connected to a different controller or port, but the partition label does not change. Referring to labels instead of drive names and partition numbers in files like /etc/fstab makes the system more tolerant to hardware changes. GPT labels appear in /dev/gpt/ when a disk is attached. Other partitioning schemes have different label capabilities and their labels appear in different directories in /dev/.

提示:

Use a unique label on every partition to avoid conflicts from identical labels. A few letters from the computer's name, use, or location can be added to the label. For instance, use labroot or rootfslab for the UFS root partition on the computer named lab.

範例 2.1. 建立傳統分割的檔案系統分割區

For a traditional partition layout where the /, /var, /tmp, and /usr directories are separate file systems on their own partitions, create a GPT partitioning scheme, then create the partitions as shown. Partition sizes shown are typical for a 20G target disk. If more space is available on the target disk, larger swap or /var partitions may be useful. Labels shown here are prefixed with ex for example, but readers should use other unique label values as described above.

By default, FreeBSD's gptboot expects the first UFS partition to be the / partition.

Partition TypeSizeMountpointLabel
freebsd-boot512K  
freebsd-ufs2G/exrootfs
freebsd-swap4G exswap
freebsd-ufs2G/varexvarfs
freebsd-ufs1G/tmpextmpfs
freebsd-ufsaccept the default (remainder of the disk)/usrexusrfs

After the custom partitions have been created, select [ Finish ] to continue with the installation.

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

Support for automatic creation of root-on-ZFS installations was added in FreeBSD 10.0-RELEASE. This partitioning mode only works with whole disks and will erase the contents of the entire disk. The installer will automatically create partitions aligned to 4k boundaries and force ZFS to use 4k sectors. This is safe even with 512 byte sector disks, and has the added benefit of ensuring that pools created on 512 byte disks will be able to have 4k sector disks added in the future, either as additional storage space or as replacements for failed disks. The installer can also optionally employ GELI disk encryption as described in 節 17.12.2, “使用 geli 做磁碟加密”. If encryption is enabled, a 2 GB unencrypted boot pool containing the /boot directory is created. It holds the kernel and other files necessary to boot the system. A swap partition of a user selectable size is also created, and all remaining space is used for the ZFS pool.

The main ZFS configuration menu offers a number of options to control the creation of the pool.

圖形 2.19. ZFS 分割區選單
ZFS 分割區選單

Select T to configure the Pool Type and the disk(s) that will constitute the pool. The automatic ZFS installer currently only supports the creation of a single top level vdev, except in stripe mode. To create more complex pools, use the instructions in 節 2.6.5, “Shell 模式磁碟分割” to create the pool. The installer supports the creation of various pool types, including stripe (not recommended, no redundancy), mirror (best performance, least usable space), and RAID-Z 1, 2, and 3 (with the capability to withstand the concurrent failure of 1, 2, and 3 disks, respectively). while selecting the pool type, a tooltip is displayed across the bottom of the screen with advice about the number of required disks, and in the case of RAID-Z, the optimal number of disks for each configuration.

圖形 2.20. ZFS 儲存池類型
ZFS 儲存池類型

Once a Pool Type has been selected, a list of available disks is displayed, and the user is prompted to select one or more disks to make up the pool. The configuration is then validated, to ensure enough disks are selected. If not, select <Change Selection> to return to the list of disks, or <Cancel> to change the pool type.

圖形 2.21. 磁碟選擇
磁碟選擇

圖形 2.22. 無效的選擇
無效的選擇

If one or more disks are missing from the list, or if disks were attached after the installer was started, select - Rescan Devices to repopulate the list of available disks. To ensure that the correct disks are selected, so as not to accidently destroy the wrong disks, the - Disk Info menu can be used to inspect each disk, including its partition table and various other information such as the device model number and serial number, if available.

圖形 2.23. 分析磁碟
分析磁碟

The main ZFS configuration menu also allows the user to enter a pool name, disable forcing 4k sectors, enable or disable encryption, switch between GPT (recommended) and MBR partition table types, and select the amount of swap space. Once all options have been set to the desired values, select the >>> Install option at the top of the menu.

If GELI disk encryption was enabled, the installer will prompt twice for the passphrase to be used to encrypt the disks.

圖形 2.24. 磁碟加密密碼
磁碟加密密碼

The installer then offers a last chance to cancel before the contents of the selected drives are destroyed to create the ZFS pool.

圖形 2.25. 最後修改
最後修改

The installation then proceeds normally.

2.6.5. Shell 模式磁碟分割

When creating advanced installations, the bsdinstall paritioning menus may not provide the level of flexibility required. Advanced users can select the Shell option from the partitioning menu in order to manually partition the drives, create the file system(s), populate /tmp/bsdinstall_etc/fstab, and mount the file systems under /mnt. Once this is done, type exit to return to bsdinstall and continue the installation.

2.7. 確認安裝

Once the disks are configured, the next menu provides the last chance to make changes before the selected hard drive(s) are formatted. If changes need to be made, select [ Back ] to return to the main partitioning menu. [ Revert & Exit ] will exit the installer without making any changes to the hard drive.

圖形 2.26. 最後確認
最後確認

To instead start the actual installation, select [ Commit ] and press Enter.

Installation time will vary depending on the distributions chosen, installation media, and speed of the computer. A series of messages will indicate the progress.

First, the installer formats the selected disk(s) and initializes the partitions. Next, in the case of a bootonly media, it downloads the selected components:

圖形 2.27. 取得發佈版本檔案
取得發佈版本檔案

Next, the integrity of the distribution files is verified to ensure they have not been corrupted during download or misread from the installation media:

圖形 2.28. 檢驗發佈版本檔案
檢驗發佈版本檔案

Finally, the verified distribution files are extracted to the disk:

圖形 2.29. 解開發佈版本檔案
解開發佈版本檔案

Once all requested distribution files have been extracted, bsdinstall displays the first post-installation configuration screen. The available post-configuration options are described in the next section.

2.8. 安裝後注意事項

Once FreeBSD is installed, bsdinstall will prompt to configure several options before booting into the newly installed system. This section describes these configuration options.

提示:

Once the system has booted, bsdconfig provides a menu-driven method for configuring the system using these and additional options.

2.8.1. 設定 root 密碼

First, the root password must be set. While entering the password, the characters being typed are not displayed on the screen. After the password has been entered, it must be entered again. This helps prevent typing errors.

圖形 2.30. 設定 root 密碼
設定 root 密碼

2.8.2. 設定網路介面

Next, a list of the network interfaces found on the computer is shown. Select the interface to configure.

注意:

The network configuration menus will be skipped if the network was previously configured as part of a bootonly installation.

圖形 2.31. 選擇網路介面
選擇網路介面

If an Ethernet interface is selected, the installer will skip ahead to the menu shown in 圖形 2.35, “選擇 IPv4 網路”. If a wireless network interface is chosen, the system will instead scan for wireless access points:

圖形 2.32. 掃描無線網路存取點
掃描無線網路存取點

Wireless networks are identified by a Service Set Identifier (SSID), a short, unique name given to each network. SSIDs found during the scan are listed, followed by a description of the encryption types available for that network. If the desired SSID does not appear in the list, select [ Rescan ] to scan again. If the desired network still does not appear, check for problems with antenna connections or try moving the computer closer to the access point. Rescan after each change is made.

圖形 2.33. 選擇無線網路
選擇無線網路

Next, enter the encryption information for connecting to the selected wireless network. WPA2 encryption is strongly recommended as older encryption types, like WEP, offer little security. If the network uses WPA2, input the password, also known as the Pre-Shared Key (PSK). For security reasons, the characters typed into the input box are displayed as asterisks.

圖形 2.34. WPA2 設定
WPA2 設定

Next, choose whether or not an IPv4 address should be configured on the Ethernet or wireless interface:

圖形 2.35. 選擇 IPv4 網路
選擇 IPv4 網路

There are two methods of IPv4 configuration. DHCP will automatically configure the network interface correctly and should be used if the network provides a DHCP server. Otherwise, the addressing information needs to be input manually as a static configuration.

注意:

Do not enter random network information as it will not work. If a DHCP server is not available, obtain the information listed in 需要的網路資訊 from the network administrator or Internet service provider.

If a DHCP server is available, select [ Yes ] in the next menu to automatically configure the network interface. The installer will appear to pause for a minute or so as it finds the DHCP server and obtains the addressing information for the system.

圖形 2.36. 選擇 IPv4 DHCP 設定
選擇 IPv4 DHCP 設定

If a DHCP server is not available, select [ No ] and input the following addressing information in this menu:

圖形 2.37. IPv4 靜態位置設定
IPv4 靜態位置設定

  • IP Address - The IPv4 address assigned to this computer. The address must be unique and not already in use by another piece of equipment on the local network.

  • Subnet Mask - The subnet mask for the network.

  • Default Router - The IP address of the network's default gateway.

The next screen will ask if the interface should be configured for IPv6. If IPv6 is available and desired, choose [ Yes ] to select it.

圖形 2.38. 選擇 IPv6 網路
選擇 IPv6 網路

IPv6 also has two methods of configuration. StateLess Address AutoConfiguration (SLAAC) will automatically request the correct configuration information from a local router. Refer to http://tools.ietf.org/html/rfc4862 for more information. Static configuration requires manual entry of network information.

If an IPv6 router is available, select [ Yes ] in the next menu to automatically configure the network interface. The installer will appear to pause for a minute or so as it finds the router and obtains the addressing information for the system.

圖形 2.39. 選擇 IPv6 SLAAC 設定
選擇 IPv6 SLAAC 設定

If an IPv6 router is not available, select [ No ] and input the following addressing information in this menu:

圖形 2.40. IPv6 靜態位置設定
IPv6 靜態位置設定

  • IPv6 Address - The IPv6 address assigned to this computer. The address must be unique and not already in use by another piece of equipment on the local network.

  • Default Router - The IPv6 address of the network's default gateway.

The last network configuration menu is used to configure the Domain Name System (DNS) resolver, which converts hostnames to and from network addresses. If DHCP or SLAAC was used to autoconfigure the network interface, the Resolver Configuration values may already be filled in. Otherwise, enter the local network's domain name in the Search field. DNS #1 and DNS #2 are the IPv4 and/or IPv6 addresses of the DNS servers. At least one DNS server is required.

圖形 2.41. DNS 設定
DNS 設定

2.8.3. 設定時區

The next menu asks if the system clock uses UTC or local time. When in doubt, select [ No ] to choose the more commonly-used local time.

圖形 2.42. 選擇本地或 UTC 時鐘
選擇本地或 UTC 時鐘

The next series of menus are used to determine the correct local time by selecting the geographic region, country, and time zone. Setting the time zone allows the system to automatically correct for regional time changes, such as daylight savings time, and perform other time zone related functions properly.

The example shown here is for a machine located in the Eastern time zone of the United States. The selections will vary according to the geographical location.

圖形 2.43. 選擇區域
選擇區域

The appropriate region is selected using the arrow keys and then pressing Enter.

圖形 2.44. 選擇城市
選擇城市

Select the appropriate country using the arrow keys and press Enter.

圖形 2.45. 選擇時區
選擇時區

The appropriate time zone is selected using the arrow keys and pressing Enter.

圖形 2.46. 確認時區
確認時區

Confirm the abbreviation for the time zone is correct. If it is, press Enter to continue with the post-installation configuration.

2.8.4. 開啟服務

The next menu is used to configure which system services will be started whenever the system boots. All of these services are optional. Only start the services that are needed for the system to function.

圖形 2.47. 選擇要開啟的其他服務
選擇要開啟的其他服務

Here is a summary of the services which can be enabled in this menu:

  • sshd - The Secure Shell (SSH) daemon is used to remotely access a system over an encrypted connection. Only enable this service if the system should be available for remote logins.

  • moused - Enable this service if the mouse will be used from the command-line system console.

  • ntpd - The Network Time Protocol (NTP) daemon for automatic clock synchronization. Enable this service if there is a Windows®, Kerberos, or LDAP server on the network.

  • powerd - System power control utility for power control and energy saving.

2.8.5. 開啟 Crash Dumps

The next menu is used to configure whether or not crash dumps should be enabled. Enabling crash dumps can be useful in debugging issues with the system, so users are encouraged to enable crash dumps.

圖形 2.48. 開啟 Crash Dumps
開啟 Crash Dumps

2.8.6. 新增使用者

The next menu prompts to create at least one user account. It is recommended to login to the system using a user account rather than as root. When logged in as root, there are essentially no limits or protection on what can be done. Logging in as a normal user is safer and more secure.

Select [ Yes ] to add new users.

圖形 2.49. 新增使用者帳號
新增使用者帳號

Follow the prompts and input the requested information for the user account. The example shown in 圖形 2.50, “輸入使用者資訊” creates the asample user account.

圖形 2.50. 輸入使用者資訊
輸入使用者資訊

Here is a summary of the information to input:

  • Username - The name the user will enter to log in. A common convention is to use the first letter of the first name combined with the last name, as long as each username is unique for the system. The username is case sensitive and should not contain any spaces.

  • Full name - The user's full name. This can contain spaces and is used as a description for the user account.

  • Uid - User ID. Typically, this is left blank so the system will assign a value.

  • Login group - The user's group. Typically this is left blank to accept the default.

  • Invite user into other groups? - Additional groups to which the user will be added as a member. If the user needs administrative access, type wheel here.

  • Login class - Typically left blank for the default.

  • Shell - Type in one of the listed values to set the interactive shell for the user. Refer to 節 3.9, “Shell” for more information about shells.

  • Home directory - The user's home directory. The default is usually correct.

  • Home directory permissions - Permissions on the user's home directory. The default is usually correct.

  • Use password-based authentication? - Typically yes so that the user is prompted to input their password at login.

  • Use an empty password? - Typically no as it is insecure to have a blank password.

  • Use a random password? - Typically no so that the user can set their own password in the next prompt.

  • Enter password - The password for this user. Characters typed will not show on the screen.

  • Enter password again - The password must be typed again for verification.

  • Lock out the account after creation? - Typically no so that the user can login.

After entering everything, a summary is shown for review. If a mistake was made, enter no and try again. If everything is correct, enter yes to create the new user.

圖形 2.51. 離開使用者與群組管理
離開使用者與群組管理

If there are more users to add, answer the Add another user? question with yes. Enter no to finish adding users and continue the installation.

For more information on adding users and user management, see 節 3.3, “使用者與基礎帳號管理”.

2.8.7. 最後設定

After everything has been installed and configured, a final chance is provided to modify settings.

圖形 2.52. 最後設定
最後設定

Use this menu to make any changes or do any additional configuration before completing the installation.

After any final configuration is complete, select Exit.

圖形 2.53. 手動設定
手動設定

bsdinstall will prompt if there are any additional configuration that needs to be done before rebooting into the new system. Select [ Yes ] to exit to a shell within the new system or [ No ] to proceed to the last step of the installation.

圖形 2.54. 完成安裝
完成安裝

If further configuration or special setup is needed, select [ Live CD ] to boot the install media into Live CD mode.

If the installation is complete, select [ Reboot ] to reboot the computer and start the new FreeBSD system. Do not forget to remove the FreeBSD install media or the computer may boot from it again.

As FreeBSD boots, informational messages are displayed. After the system finishes booting, a login prompt is displayed. At the login: prompt, enter the username added during the installation. Avoid logging in as root. Refer to 節 3.3.1.3, “超級使用者帳號” for instructions on how to become the superuser when administrative access is needed.

The messages that appeared during boot can be reviewed by pressing Scroll-Lock to turn on the scroll-back buffer. The PgUp, PgDn, and arrow keys can be used to scroll back through the messages. When finished, press Scroll-Lock again to unlock the display and return to the console. To review these messages once the system has been up for some time, type less /var/run/dmesg.boot from a command prompt. Press q to return to the command line after viewing.

If sshd was enabled in 圖形 2.47, “選擇要開啟的其他服務”, the first boot may be a bit slower as the system will generate the RSA and DSA keys. Subsequent boots will be faster. The fingerprints of the keys will be displayed, as seen in this example:

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.

Refer to 節 13.8, “OpenSSH” for more information about fingerprints and SSH.

FreeBSD does not install a graphical environment by default. Refer to 章 5, X Window 系統 for more information about installing and configuring a graphical window manager.

Proper shutdown of a FreeBSD computer helps protect data and hardware from damage. Do not turn off the power before the system has been properly shut down! If the user is a member of the wheel group, become the superuser by typing su at the command line and entering the root password. Then, type shutdown -p now and the system will shut down cleanly, and if the hardware supports it, turn itself off.

2.9. 疑難排解

This section covers basic installation troubleshooting, such as common problems people have reported.

Check the Hardware Notes (http://www.freebsd.org/releases/index.html) document for the version of FreeBSD to make sure the hardware is supported. If the hardware is supported and lock-ups or other problems occur, build a custom kernel using the instructions in 章 8, 設定 FreeBSD 核心 to add support for devices which are not present in the GENERIC kernel. The default kernel assumes that most hardware devices are in their factory default configuration in terms of IRQs, I/O addresses, and DMA channels. If the hardware has been reconfigured, a custom kernel configuration file can tell FreeBSD where to find things.

注意:

Some installation problems can be avoided or alleviated by updating the firmware on various hardware components, most notably the motherboard. Motherboard firmware is usually referred to as the BIOS. Most motherboard and computer manufacturers have a website for upgrades and upgrade information.

Manufacturers generally advise against upgrading the motherboard BIOS unless there is a good reason for doing so, like a critical update. The upgrade process can go wrong, leaving the BIOS incomplete and the computer inoperative.

If the system hangs while probing hardware during boot, or it behaves strangely during install, ACPI may be the culprit. FreeBSD makes extensive use of the system ACPI service on the i386, amd64, and ia64 platforms to aid in system configuration if it is detected during boot. Unfortunately, some bugs still exist in both the ACPI driver and within system motherboards and BIOS firmware. ACPI can be disabled by setting the hint.acpi.0.disabled hint in the third stage boot loader:

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

This is reset each time the system is booted, so it is necessary to add hint.acpi.0.disabled="1" to the file /boot/loader.conf. More information about the boot loader can be found in 節 12.1, “概述”.

2.10. 使用 Live CD

The welcome menu of bsdinstall, shown in 圖形 2.3, “歡迎選單”, provides a [ Live CD ] option. This is useful for those who are still wondering whether FreeBSD is the right operating system for them and want to test some of the features before installing.

The following points should be noted before using the [ Live CD ]:

  • To gain access to the system, authentication is required. The username is root and the password is blank.

  • As the system runs directly from the installation media, performance will be significantly slower than that of a system installed on a hard disk.

  • This option only provides a command prompt and not a graphical interface.

章 3. FreeBSD Basics

3.1. 概述

接下來的這一章將涵蓋 FreeBSD 作業系統的基本指令及功能。 大部份的內容在 UNIX®-like 作業系統中都是相通的。 如果您對這些內容熟悉的話,可以放心的跳過。 如果您剛接觸 FreeBSD,那您一定要仔細的讀完這章。

讀完這章,您將了解︰

  • 如何使用 FreeBSD 的虛擬 Console。

  • How to create and manage users and groups on FreeBSD.

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

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

  • FreeBSD 的磁碟組織。

  • 如何掛載(mount)、卸載(umount)檔案系統。

  • 什麼是程序、Daemon 以及 Signal。

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

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

  • 什麼是 Devices 和 Device node 。

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

3.2. 虛擬 Console 與終端機

如果您沒有將 FreeBSD 設定成開機時自動進入圖形化模式,系統會進入指令登入提示像是這樣的東西:

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

login:

第一行包含了剛開機完系統的資訊,amd64 代表此範例所使用的系統是執行 64-位元版本的 FreeBSD,這台主機的名稱是 pc3.example.orgttyv0 代表這是個 系統 Console。第二行則是登人的提示訊息。

FreeBSD 是一個多使用者的系統,需要一套可以分辨不同使用者的方法。因此所有的使用者在執行程式之前必須先“登入”系統以取得系統內程式的存取權限。每個使用者都有一組獨特的帳號名稱 (username) 及個人密碼 (password)。

要登入系統 Console 需輸入在系統安裝時設定的使用者名稱,請參考 節 2.8.6, “新增使用者”,並按下 Enter。 接著輸入該使用者名稱的密碼按下 Enter。 輸入的密碼為了安全起見不會顯示在畫面上。

如果您輸入了正確的密碼,您應該會看到今日訊息 (Message of the day, MOTD),後面接著顯示指令提示字元,依使用者建立時所選擇的 Shell 會有不同的提示字元可能為 #, $ 或者 %。 看到指令提示代表使用者現在已經登入 FreeBSD 系統 Console 且已經準備好可以下指令。

3.2.1. 虛擬 Console

雖然系統 Console 已經可以用來與系統互動,但使用鍵盤來下指令使用 FreeBSD 系統的使用者通常會使用虛擬 Console 登入。 因為系統訊息預設會顯示在系統 Console,這些訊些會在使用者作業的過程中不斷出現,讓使用者難以專心作業。

FreeBSD 預設提供多個虛擬 Console 可輸入指令,每個虛擬 Console 都有自己的登入提示及 Shell 並且可以輕易的在虛擬 Console 間切換。 這實際上讓指令輸入有了類似於圖型化環境中可以同時開啟多個視窗的功能。

組合鍵 Alt+F1Alt+F8 被 FreeBSD 保留用來切換虛擬 Console,使用 Alt+F1 可切換至系統 Console (ttyv0),Alt+F2 可存取第一個虛擬 Console (ttyv1),Alt+F3 可存取第二個虛擬 Console (ttyv2),以此類推。

當您從一個 Console 切換到下一個的時候,FreeBSD 會切換畫面顯示的內容, 這就好像有很多虛擬的螢幕和鍵盤可以讓您輸入指令到 FreeBSD 執行。 在某一個虛擬 Console 上執行的程式並不會因為使用者切到別的 Console 而停止執行。

請參考 kbdcontrol(1), vidcontrol(1), atkbd(4), syscons(4) 以及 vt(4) 來取得更多有關 FreeBSD Console 及鍵盤驅動程式的技術說明。

FreeBSD 中虛擬 Console 的數量設定在 /etc/ttys 檔案中的下列章節:

# name    getty                         type  status comments
#
ttyv0   "/usr/libexec/getty Pc"         xterm   on  secure
# Virtual terminals
ttyv1   "/usr/libexec/getty Pc"         xterm   on  secure
ttyv2   "/usr/libexec/getty Pc"         xterm   on  secure
ttyv3   "/usr/libexec/getty Pc"         xterm   on  secure
ttyv4   "/usr/libexec/getty Pc"         xterm   on  secure
ttyv5   "/usr/libexec/getty Pc"         xterm   on  secure
ttyv6   "/usr/libexec/getty Pc"         xterm   on  secure
ttyv7   "/usr/libexec/getty Pc"         xterm   on  secure
ttyv8   "/usr/X11R6/bin/xdm -nodaemon"  xterm   off secure

要關閉虛擬 Console 只要在指定的虛擬 Console 該行設定的一開始加上註解符號 (#)。 例如要將虛擬 Console 的數量由 8 個改為 4 個,則可將 # 加在代表虛擬 Console 的 ttyv5ttyv8 的最後四行一開始。 請勿將系統 Console ttyv0 加上註解符號。 注意,若有依照 章 5, X Window 系統 安裝並設定 Xorg 時,會用到最後一個虛擬 Console (ttyv8)。

有關各欄位的設定以及其他選項,請參閱 ttys(5) 說明。

3.2.2. 單使用者模式

FreeBSD 開機選單會提供一個選項為 Boot Single User,若選擇該項目,系統將會進入所謂 單使用者模式 的特殊模式。 此模式通常用在修復系統無法開機或重設已忘掉的 root 密碼。 在當使用者模式中無法使用網路及其他虛擬 Console,但有完整 root 對系統的存取權限,而且預設是不須要輸入 root 密碼。 也因此,要能透過實體鍵盤操作才能進入此模式,在考量 FreeBSD 系統安全時須要限制可操作實體鍵盤的人員。

有關單使用者模式的設定可在 /etc/ttys 中的以下章節中找到:

# 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  secure

預設狀態為安全 (secure),這代表誰能夠操作實體鍵盤不是不重要就是已受到實體安全規範管制。 若設定更該為不安全(insecure) 則代表主機所在的環境不安全,因為任何人皆可接觸鍵盤。 當此行設定更改為不安全 (insecure) 時,當使用擇選擇單使用者模式時,FreeBSD 將會要求輸入 root 的密碼。

注意:

請審慎考慮是否要改為 insecure! 因為萬一忘記 root 密碼的話,雖然還是有其他辦法可以登入單使用者模式,只是對不熟 FreeBSD 開機程序的人可就麻煩了。

3.2.3. 更改 Console 影像模式

FreeBSD Console 預設顯示大小可以調整為 1024x768、1280x1024 或其他顯示卡與螢幕有支援的解析度大小。 要使用不同的影像模式需載入 VESA 模組:

# kldload vesa

要偵測硬體支援的影像模式,可使用 vidcontrol(1)。 要取得支援的影像模式清單可輸入以下指令:

# vidcontrol -i mode

該指令會顯示硬體所支援的影像模式清單,要採用新的影像模式需以 root 使用者執行 vidcontrol(1) 指令:

# vidcontrol MODE_279

若可接受新的影像模式,可以在 /etc/rc.conf 加入設定,讓每次重開機後會自動生效:

allscreens_flags="MODE_279"

3.3. 使用者與基礎帳號管理

FreeBSD allows multiple users to use the computer at the same time. While only one user can sit in front of the screen and use the keyboard at any one time, any number of users can log in to the system through the network. To use the system, each user should have their own user account.

This chapter describes:

  • The different types of user accounts on a FreeBSD system.

  • How to add, remove, and modify user accounts.

  • How to set limits to control the resources that users and groups are allowed to access.

  • How to create groups and add users as members of a group.

3.3.1. 帳號類型

Since all access to the FreeBSD system is achieved using accounts and all processes are run by users, user and account management is important.

There are three main types of accounts: system accounts, user accounts, and the superuser account.

3.3.1.1. 系統帳號

System accounts are used to run services such as DNS, mail, and web servers. The reason for this is security; if all services ran as the superuser, they could act without restriction.

Examples of system accounts are daemon, operator, bind, news, and www.

nobody is the generic unprivileged system account. However, the more services that use nobody, the more files and processes that user will become associated with, and hence the more privileged that user becomes.

3.3.1.2. 使用者帳號

User accounts are assigned to real people and are used to log in and use the system. Every person accessing the system should have a unique user account. This allows the administrator to find out who is doing what and prevents users from clobbering the settings of other users.

Each user can set up their own environment to accommodate their use of the system, by configuring their default shell, editor, key bindings, and language settings.

Every user account on a FreeBSD system has certain information associated with it:

User name

The user name is typed at the login: prompt. Each user must have a unique user name. There are a number of rules for creating valid user names which are documented in passwd(5). It is recommended to use user names that consist of eight or fewer, all lower case characters in order to maintain backwards compatibility with applications.

Password

Each account has an associated password.

User ID (UID)

The User ID (UID) is a number used to uniquely identify the user to the FreeBSD system. Commands that allow a user name to be specified will first convert it to the UID. It is recommended to use a UID less than 65535, since higher values may cause compatibility issues with some software.

Group ID (GID)

The Group ID (GID) is a number used to uniquely identify the primary group that the user belongs to. Groups are a mechanism for controlling access to resources based on a user's GID rather than their UID. This can significantly reduce the size of some configuration files and allows users to be members of more than one group. It is recommended to use a GID of 65535 or lower as higher GIDs may break some software.

Login class

Login classes are an extension to the group mechanism that provide additional flexibility when tailoring the system to different users. Login classes are discussed further in 節 13.13.1, “設定登入類別”.

Password change time

By default, passwords do not expire. However, password expiration can be enabled on a per-user basis, forcing some or all users to change their passwords after a certain amount of time has elapsed.

Account expiration time

By default, FreeBSD does not expire accounts. When creating accounts that need a limited lifespan, such as student accounts in a school, specify the account expiry date using pw(8). After the expiry time has elapsed, the account cannot be used to log in to the system, although the account's directories and files will remain.

User's full name

The user name uniquely identifies the account to FreeBSD, but does not necessarily reflect the user's real name. Similar to a comment, this information can contain spaces, uppercase characters, and be more than 8 characters long.

Home directory

The home directory is the full path to a directory on the system. This is the user's starting directory when the user logs in. A common convention is to put all user home directories under /home/username or /usr/home/username. Each user stores their personal files and subdirectories in their own home directory.

User shell

The shell provides the user's default environment for interacting with the system. There are many different kinds of shells and experienced users will have their own preferences, which can be reflected in their account settings.

3.3.1.3. 超級使用者帳號

The superuser account, usually called root, is used to manage the system with no limitations on privileges. For this reason, it should not be used for day-to-day tasks like sending and receiving mail, general exploration of the system, or programming.

The superuser, unlike other user accounts, can operate without limits, and misuse of the superuser account may result in spectacular disasters. User accounts are unable to destroy the operating system by mistake, so it is recommended to login as a user account and to only become the superuser when a command requires extra privilege.

Always double and triple-check any commands issued as the superuser, since an extra space or missing character can mean irreparable data loss.

There are several ways to gain superuser privilege. While one can log in as root, this is highly discouraged.

Instead, use su(1) to become the superuser. If - is specified when running this command, the user will also inherit the root user's environment. The user running this command must be in the wheel group or else the command will fail. The user must also know the password for the root user account.

In this example, the user only becomes superuser in order to run make install as this step requires superuser privilege. Once the command completes, the user types exit to leave the superuser account and return to the privilege of their user account.

範例 3.1. 以超級使用者的身份安裝程式
% configure
% make
% su -
Password:
# make install
# exit
%

The built-in su(1) framework works well for single systems or small networks with just one system administrator. An alternative is to install the security/sudo package or port. This software provides activity logging and allows the administrator to configure which users can run which commands as the superuser.

3.3.2. 管理帳號

FreeBSD provides a variety of different commands to manage user accounts. The most common commands are summarized in 表格 3.1, “管理使用者帳號的工具”, followed by some examples of their usage. See the manual page for each utility for more details and usage examples.

表格 3.1. 管理使用者帳號的工具
指令摘要
adduser(8)The recommended command-line application for adding new users.
rmuser(8)The recommended command-line application for removing users.
chpass(1)A flexible tool for changing user database information.
passwd(1)The command-line tool to change user passwords.
pw(8)A powerful and flexible tool for modifying all aspects of user accounts.

3.3.2.1. adduser

The recommended program for adding new users is adduser(8). When a new user is added, this program automatically updates /etc/passwd and /etc/group. It also creates a home directory for the new user, copies in the default configuration files from /usr/share/skel, and can optionally mail the new user a welcome message. This utility must be run as the superuser.

The adduser(8) utility is interactive and walks through the steps for creating a new user account. As seen in 範例 3.2, “在 FreeBSD 新增使用者”, either input the required information or press Return to accept the default value shown in square brackets. In this example, the user has been invited into the wheel group, allowing them to become the superuser with su(1). When finished, the utility will prompt to either create another user or to exit.

範例 3.2. 在 FreeBSD 新增使用者
# adduser
Username: jru
Full name: J. Random User
Uid (Leave empty for default):
Login group [jru]:
Login group is jru. Invite jru into other groups? []: wheel
Login class [default]:
Shell (sh csh tcsh zsh nologin) [sh]: zsh
Home directory [/home/jru]:
Home directory permissions (Leave empty for default):
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]:
Enter password:
Enter password again:
Lock out the account after creation? [no]:
Username   : jru
Password   : ****
Full Name  : J. Random User
Uid        : 1001
Class      :
Groups     : jru wheel
Home       : /home/jru
Shell      : /usr/local/bin/zsh
Locked     : no
OK? (yes/no): yes
adduser: INFO: Successfully added (jru) to the user database.
Add another user? (yes/no): no
Goodbye!
#

注意:

Since the password is not echoed when typed, be careful to not mistype the password when creating the user account.

3.3.2.2. rmuser

To completely remove a user from the system, run rmuser(8) as the superuser. This command performs the following steps:

  1. Removes the user's crontab(1) entry, if one exists.

  2. Removes any at(1) jobs belonging to the user.

  3. Kills all processes owned by the user.

  4. Removes the user from the system's local password file.

  5. Optionally removes the user's home directory, if it is owned by the user.

  6. Removes the incoming mail files belonging to the user from /var/mail.

  7. Removes all files owned by the user from temporary file storage areas such as /tmp.

  8. Finally, removes the username from all groups to which it belongs in /etc/group. If a group becomes empty and the group name is the same as the username, the group is removed. This complements the per-user unique groups created by adduser(8).

rmuser(8) cannot be used to remove superuser accounts since that is almost always an indication of massive destruction.

By default, an interactive mode is used, as shown in the following example.

範例 3.3. rmuser 互動式帳號移除
# rmuser jru
Matching password entry:
jru:*:1001:1001::0:0:J. Random User:/home/jru:/usr/local/bin/zsh
Is this the entry you wish to remove? y
Remove user's home directory (/home/jru)? y
Removing user (jru): mailspool home passwd.
#

3.3.2.3. chpass

Any user can use chpass(1) to change their default shell and personal information associated with their user account. The superuser can use this utility to change additional account information for any user.

When passed no options, aside from an optional username, chpass(1) displays an editor containing user information. When the user exits from the editor, the user database is updated with the new information.

注意:

This utility will prompt for the user's password when exiting the editor, unless the utility is run as the superuser.

In 範例 3.4, “以超級使用者的身份使用 chpass, the superuser has typed chpass jru and is now viewing the fields that can be changed for this user. If jru runs this command instead, only the last six fields will be displayed and available for editing. This is shown in 範例 3.5, “以一般使用者的身份使用 chpass.

範例 3.4. 以超級使用者的身份使用 chpass
#Changing user database information for jru.
Login: jru
Password: *
Uid [#]: 1001
Gid [# or name]: 1001
Change [month day year]:
Expire [month day year]:
Class:
Home directory: /home/jru
Shell: /usr/local/bin/zsh
Full Name: J. Random User
Office Location:
Office Phone:
Home Phone:
Other information:

範例 3.5. 以一般使用者的身份使用 chpass
#Changing user database information for jru.
Shell: /usr/local/bin/zsh
Full Name: J. Random User
Office Location:
Office Phone:
Home Phone:
Other information:

注意:

The commands chfn(1) and chsh(1) are links to chpass(1), as are ypchpass(1), ypchfn(1), and ypchsh(1). Since NIS support is automatic, specifying the yp before the command is not necessary. How to configure NIS is covered in 章 28, 網路伺服器.

3.3.2.4. passwd

Any user can easily change their password using passwd(1). To prevent accidental or unauthorized changes, this command will prompt for the user's original password before a new password can be set:

範例 3.6. 更改您的密碼
% passwd
Changing local password for jru.
Old password:
New password:
Retype new password:
passwd: updating the database...
passwd: done

The superuser can change any user's password by specifying the username when running passwd(1). When this utility is run as the superuser, it will not prompt for the user's current password. This allows the password to be changed when a user cannot remember the original password.

範例 3.7. 以超級使用者的身份更改其他使用者的密碼
# passwd jru
Changing local password for jru.
New password:
Retype new password:
passwd: updating the database...
passwd: done

注意:

As with chpass(1), yppasswd(1) is a link to passwd(1), so NIS works with either command.

3.3.2.5. pw

The pw(8) utility can create, remove, modify, and display users and groups. It functions as a front end to the system user and group files. pw(8) has a very powerful set of command line options that make it suitable for use in shell scripts, but new users may find it more complicated than the other commands presented in this section.

3.3.3. 管理群組

A group is a list of users. A group is identified by its group name and GID. In FreeBSD, the kernel uses the UID of a process, and the list of groups it belongs to, to determine what the process is allowed to do. Most of the time, the GID of a user or process usually means the first group in the list.

The group name to GID mapping is listed in /etc/group. This is a plain text file with four colon-delimited fields. The first field is the group name, the second is the encrypted password, the third the GID, and the fourth the comma-delimited list of members. For a more complete description of the syntax, refer to group(5).

The superuser can modify /etc/group using a text editor. Alternatively, pw(8) can be used to add and edit groups. For example, to add a group called teamtwo and then confirm that it exists:

範例 3.8. 使用 pw(8) 新增群組
# pw groupadd teamtwo
# pw groupshow teamtwo
teamtwo:*:1100:

In this example, 1100 is the GID of teamtwo. Right now, teamtwo has no members. This command will add jru as a member of teamtwo.

範例 3.9. 使用 pw(8) 加入使用者帳號到新的群組
# pw groupmod teamtwo -M jru
# pw groupshow teamtwo
teamtwo:*:1100:jru

The argument to -M is a comma-delimited list of users to be added to a new (empty) group or to replace the members of an existing group. To the user, this group membership is different from (and in addition to) the user's primary group listed in the password file. This means that the user will not show up as a member when using groupshow with pw(8), but will show up when the information is queried via id(1) or a similar tool. When pw(8) is used to add a user to a group, it only manipulates /etc/group and does not attempt to read additional data from /etc/passwd.

範例 3.10. 使用 pw(8) 加入新成員到群組
# pw groupmod teamtwo -m db
# pw groupshow teamtwo
teamtwo:*:1100:jru,db

In this example, the argument to -m is a comma-delimited list of users who are to be added to the group. Unlike the previous example, these users are appended to the group and do not replace existing users in the group.

範例 3.11. 使用 id(1) 來查看所屬群組
% id jru
uid=1001(jru) gid=1001(jru) groups=1001(jru), 1100(teamtwo)

In this example, jru is a member of the groups jru and teamtwo.

For more information about this command and the format of /etc/group, refer to pw(8) and group(5).

3.4. 權限

In FreeBSD, every file and directory has an associated set of permissions and several utilities are available for viewing and modifying these permissions. Understanding how permissions work is necessary to make sure that users are able to access the files that they need and are unable to improperly access the files used by the operating system or owned by other users.

This section discusses the traditional UNIX® permissions used in FreeBSD. For finer grained file system access control, refer to 節 13.9, “存取控制清單”.

In UNIX®, basic permissions are assigned using three types of access: read, write, and execute. These access types are used to determine file access to the file's owner, group, and others (everyone else). The read, write, and execute permissions can be represented as the letters r, w, and x. They can also be represented as binary numbers as each permission is either on or off (0). When represented as a number, the order is always read as rwx, where r has an on value of 4, w has an on value of 2 and x has an on value of 1.

Table 4.1 summarizes the possible numeric and alphabetic possibilities. When reading the Directory Listing column, a - is used to represent a permission that is set to off.

表格 3.2. UNIX® 權限
數值權限目錄標示
0不可讀取, 不可寫入, 不可執行---
1不可讀取, 不可寫入, 可執行--x
2不可讀取, 可寫入, 不可執行-w-
3不可讀取, 可寫入, 可執行-wx
4可讀取, 不可寫入, 不可執行r--
5可讀取, 不可寫入, 可執行r-x
6可讀取, 可寫入, 不可執行rw-
7可讀取, 可寫入, 可執行rwx

使用 ls(1) 指令時,可以加上 -l 參數, 來檢視詳細的目錄清單。 清單中欄位的資訊包含檔案對所有者、群組及其他人的權限。 在任一個目錄底下執行 ls -l,會顯示如下的結果:

% ls -l
total 530
-rw-r--r--  1 root  wheel     512 Sep  5 12:31 myfile
-rw-r--r--  1 root  wheel     512 Sep  5 12:31 otherfile
-rw-r--r--  1 root  wheel    7680 Sep  5 12:31 email.txt

第一個 (最左邊) 的字元用來表示這個檔案的類型為何,除標準檔案以外,尚有目錄、特殊字元裝置、Socket 及其他特殊虛擬檔案裝置, 在此例當中,- 表示該檔案為一個標準的檔案。 範例中接下來的三個字元中,rw- 代表所有者對檔案擁有的權限。 再接下來的三個字元, r-- 則代表群組對檔案擁有的權限, 最後三個字元,r-- 則代表其他人對檔案擁有的權限。 破折號 (-) 表示沒有權限,範例中的這個檔案的權限, 只允許所有者讀取、寫入檔案,群組以及其他人僅能讀取檔案。 根據以上的表格,此種權限的檔案可以使用 644 來表示, 每組數字分別代表檔案的三種權限。

那系統如何控制裝置的權限? 實際上 FreeBSD 對大多的硬碟裝置就如同檔案,程式可以開啟、讀取以及寫入資料如一般檔案。 這些特殊裝置檔案都儲存於 /dev/ 目錄中。

目錄也同如檔案,擁有讀取、寫入及執行的權限, 但在執行權限上與檔案有明顯的差異。 當目錄被標示為可執行時,代表可以使用 cd(1) 指令切換進入該目錄。 也代表能夠存取在此目錄之中的已知檔名的檔案,但仍會受限於檔案本身所設定的權限。

要能夠列出目錄內容,必須擁有目錄的讀取權限。 要刪除已知檔名的檔案,必須擁有檔案所在目錄的寫入 以及 執行的權限。

還有一些權限位元,但這些權限主要在特殊情況使用,如 setuid binaries 及 sticky directories。 如果您還想知道更多檔案權限的資訊及使用方法,請務必參閱 chmod(1)

3.4.1. 權限符號

Contributed by Tom Rhodes.

權限符號可稱做符號表示,使用字元的方式來取代使用數值來設定檔案或目錄的權限。 符號表示的格式依序為 (某人)(動作)(權限),可使用的符號如下:

項目字母代表意義
(某人)u使用者
(某人)g群組所有者
(某人)o其他
(某人)a全部 (world)
(動作)+ 增加權限
(動作)-移除權限
(動作)=指定權限
(權限)r讀取
(權限)wWrite
(權限)x寫入
(權限)tSticky bit
(權限)s Set UID 或 GID

如先前同樣使用 chmod(1) 指令來設定,但使用的參數為這些字元。 例如,您可以使用下列指令禁止其他使用者存取檔案 FILE:

% chmod go= FILE

若有兩個以上的符號表示可以使用逗號 (,) 區隔。 例如,下列指令將會移除群組及其他人對檔案 FILE 的寫入權限, 並使全部人 (world) 對該檔有執行權限。

% chmod go-w,a+x FILE

3.4.2. FreeBSD 檔案旗標

Contributed by Tom Rhodes.

除了前面提到的檔案權限外,FreeBSD 支援使用 檔案旗標。 這些旗標增加了檔案的安全性及管理性,但不包含目錄。有了檔案旗標可確保在某些時候 root 不會意外將檔案修改或移除。

修改的檔案 flag 僅需要使用擁有簡易的介面的 chflags(1) 工具。 例如,標示系統禁止刪除的旗標於檔案 file1,使用下列指令:

# chflags sunlink file1

若要移除系統禁止刪除的旗標,只需要簡單在 sunlink 前加上 no,例如:

# chflags nosunlink file1

使用 ls(1) 及參數 -lo 可檢視檔案目前的旗標:

# ls -lo file1
-rw-r--r--  1 trhodes  trhodes  sunlnk 0 Mar  1 05:54 file1

多數的旗標僅能由 root 使用者來標示或移除,而部份旗標可由檔案所有者設定。 我們建議系統管理者可閱讀 chflags(1)chflags(2) 說明以瞭解相關細節。

3.4.3. setuidsetgidsticky 權限

Contributed by Tom Rhodes.

Other than the permissions already discussed, there are three other specific settings that all administrators should know about. They are the setuid, setgid, and sticky permissions.

These settings are important for some UNIX® operations as they provide functionality not normally granted to normal users. To understand them, the difference between the real user ID and effective user ID must be noted.

The real user ID is the UID who owns or starts the process. The effective UID is the user ID the process runs as. As an example, passwd(1) runs with the real user ID when a user changes their password. However, in order to update the password database, the command runs as the effective ID of the root user. This allows users to change their passwords without seeing a Permission Denied error.

The setuid permission may be set by prefixing a permission set with the number four (4) as shown in the following example:

# chmod 4755 suidexample.sh

The permissions on suidexample.sh now look like the following:

-rwsr-xr-x   1 trhodes  trhodes    63 Aug 29 06:36 suidexample.sh

Note that a s is now part of the permission set designated for the file owner, replacing the executable bit. This allows utilities which need elevated permissions, such as passwd(1).

注意:

The nosuid mount(8) option will cause such binaries to silently fail without alerting the user. That option is not completely reliable as a nosuid wrapper may be able to circumvent it.

To view this in real time, open two terminals. On one, type passwd as a normal user. While it waits for a new password, check the process table and look at the user information for passwd(1):

In terminal A:

Changing local password for trhodes
Old Password:

In terminal B:

# ps aux | grep passwd
trhodes  5232  0.0  0.2  3420  1608   0  R+    2:10AM   0:00.00 grep passwd
root     5211  0.0  0.2  3620  1724   2  I+    2:09AM   0:00.01 passwd

Although passwd(1) is run as a normal user, it is using the effective UID of root.

The setgid permission performs the same function as the setuid permission; except that it alters the group settings. When an application or utility executes with this setting, it will be granted the permissions based on the group that owns the file, not the user who started the process.

To set the setgid permission on a file, provide chmod(1) with a leading two (2):

# chmod 2755 sgidexample.sh

In the following listing, notice that the s is now in the field designated for the group permission settings:

-rwxr-sr-x   1 trhodes  trhodes    44 Aug 31 01:49 sgidexample.sh

注意:

In these examples, even though the shell script in question is an executable file, it will not run with a different EUID or effective user ID. This is because shell scripts may not access the setuid(2) system calls.

The setuid and setgid permission bits may lower system security, by allowing for elevated permissions. The third special permission, the sticky bit, can strengthen the security of a system.

When the sticky bit is set on a directory, it allows file deletion only by the file owner. This is useful to prevent file deletion in public directories, such as /tmp, by users who do not own the file. To utilize this permission, prefix the permission set with a one (1):

# chmod 1777 /tmp

The sticky bit permission will display as a t at the very end of the permission set:

# ls -al / | grep tmp
drwxrwxrwt  10 root  wheel         512 Aug 31 01:49 tmp

3.5. 目錄結構

認識 FreeBSD 的目錄架構,就可對系統有概略的基礎理解。 最重要的莫過於整個目錄的根目錄,就是 / 目錄, 該目錄會在開機時最先掛載 (mount),裡面會有開機所會用到必備檔案。 此外,根目錄還有紀錄其他檔案系統的掛載點相關設定。

「掛載點」就是讓新增的檔案系統,能接到上層的檔案系統 (通常就是「根目錄」檔案系統) 的目錄。 在 節 3.6, “磁碟組織” 這邊對此有更詳細介紹。 標準的掛載點包括了 /usr/, /var/, /tmp/, /mnt/ 以及 /cdrom/。 這些目錄通常會記錄在 /etc/fstab 設定檔內。 /etc/fstab 是記錄各檔案系統及相關掛載點的表格。 大部分在 /etc/fstab 有記錄的檔案系統,會在開機時由 rc(8) Script 來自動掛載,除非它們有設定 noauto 選項。 其中細節說明可參閱 節 3.7.1, “fstab 檔”

有關檔案系統架構的完整說明可參閱 hier(7)。 現在呢,讓我們大致先一窺常見的目錄有哪些吧。

目錄說明
/檔案系統的根目錄。
/bin/single-user、multi-user 兩種模式皆可使用的基本工具 。
/boot/作業系統開機過程會用到的程式、設定檔。
/boot/defaults/預設的開機啟動設定檔,詳情請參閱 loader.conf(5)
/dev/Device nodes,詳情請參閱 intro(4)
/etc/系統設定檔及一些 script 檔。
/etc/defaults/預設的系統設定檔,詳情請參閱 rc(8)
/etc/mail/MTA(Mail Transport Agent)的相關設定檔,像是 sendmail(8)
/etc/namedb/named(8) 設定檔。
/etc/periodic/每日、每週、每月透過 cron(8),執行的定期排程 script,詳情請參閱 periodic(8)
/etc/ppp/ppp(8) 設定檔。
/mnt/系統管理者慣用充當臨時掛載點的空目錄。
/proc/Process 檔案系統,詳情請參閱 procfs(5)mount_procfs(8)
/rescue/緊急救援用途的一些 statically linked 程式,詳情請參閱 rescue(8)
/root/root 帳號的家目錄。
/sbin/供 single-user 及 multi-user 環境使用的系統程式及管理工具 。
/tmp/臨時檔案。 一般而言,重開機之後 /tmp 內的東西會被清除掉。 而通常會將 memory-based 檔案系統掛載在 /tmp 上。 這些瑣事可透過 tmpmfs 相關的 rc.conf(5) 環境變數來自動完成 。(或是在 /etc/fstab 內做設定, 詳情請參閱 mdmfs(8))。
/usr/主要是使用者所安裝的工具程式、應用程式存放處。
/usr/bin/常用工具、開發工具、應用軟體。
/usr/include/標準 C include 檔案。
/usr/lib/程式庫存放處。
/usr/libdata/其他各式工具的資料檔。
/usr/libexec/系統 Daemon 及系統工具程式 (透過其他程式來執行)。
/usr/local/存放一些自行安裝的執行檔、程式庫等等。 同時,也是 FreeBSD ports 架構的預設安裝目錄。 /usr/local 內的目錄架構大致與 /usr 相同,詳情請參閱 hier(7) 說明。 但 man 目錄例外,它們是直接放在 /usr/local 底下,而非 /usr/local/share,而 ports 所安裝的說明文件則在 share/doc/port
/usr/obj/在編譯 /usr/src 目錄時所產生的相關架構目地檔。
/usr/ports/FreeBSD Ports 套件集 (選用)。
/usr/sbin/由使用者執行的系統 Daemon 及系統工具。
/usr/share/各架構皆共通的檔案。
/usr/src/BSD 原始碼 (或自行新增的)。
/var/存放各種用途的日誌(log)檔、臨時或暫時存放、列印或郵件的 spool 檔案。有時候,memory-based 檔案系統也會掛載在 /var。 這些瑣事可透過 varmfs 相關的 rc.conf(5) 環境變數來自動完成。(或是在 /etc/fstab 內做設定,相關細節請參閱 mdmfs(8))。
/var/log/各項系統記錄的日誌(log)檔。
/var/mail/各使用者的郵件(mailbox)檔案。
/var/spool/各種印表機、郵件系統的 spool 目錄。
/var/tmp/臨時檔案。 這些檔案在重開機後通常仍會保留,除非 /var 是屬於 memory-based 檔案系統。
/var/yp/NIS 對應表。

3.6. 磁碟組織

FreeBSD 用來尋找檔案的最小單位就是檔案的名稱了。 檔案的名稱有大小寫之分,所以說 readme.txtREADME.TXT 是兩個不同的檔案。 FreeBSD 並不使用副檔名 (.txt) 來判別這是一個程式檔、文件檔或是其他類型的檔案。

檔案存在目錄裡面。 一個目錄中可能沒有任何檔案,也可能有好幾百個檔案。 目錄之中也可以包含其他的目錄; 您可以建立階層式的目錄以便資料的管理。

檔案或目錄的對應是藉由給定的檔案或目錄名稱,然後加上正斜線符號 (/);之後再視需要加上其他的目錄名稱。 如果您有一個目錄 foo ,裡面有一個目錄叫作 bar,這個目錄中又包含了一個叫 readme.txt 的檔案,那麼這個檔案的全名,或者說檔案的路徑就是 foo/bar/readme.txt。Note that this is different from Windows® which uses \ to separate file and directory names. FreeBSD does not use drive letters, or other drive names in the path. For example, one would not type c:\foo\bar\readme.txt on FreeBSD.

目錄及檔案儲存在檔案系統之中。 每個檔案系統都有唯一一個最上層的目錄,叫做根目錄 (root directory)。 然後在這個根目錄下面才能有其他的目錄。One file system is designated the root file system or /. Every other file system is mounted under the root file system. No matter how many disks are on the FreeBSD system, every directory appears to be part of the same disk.

假設您有三個檔案系統,分別叫作 A, BC。 每個檔案系統都包含兩個目錄,叫做 A1, A2 (依此類推得 B1, B2C1, C2)。

A 為主要的檔案系統;如果您用 ls(1) 指令查看此目錄的內容,您會看到兩個子目錄: A1A2,如下所示:

一個檔案系統必須以目錄形式掛載於另一個檔案系統上。 因此,假設您將 B 掛載於 A1 之上,則 B 的根目錄就變成了 A1,而在 B 之下的任何目錄的路徑也隨之改變:

B1B2 目錄中的任何檔案必須經由路徑 /A1/B1/A1/B2 才能達到。 所有原來在 /A1 中的檔案會暫時被隱藏起來,直到 B移除後才會再顯現出來。

如果 B 掛載在 A2 之上,則會變成:

上面的路徑分別為 /A2/B1/A2/B2

檔案系統可以掛在其他檔案系統的目錄之上。 延續之前的例子,C 檔案系統可以掛在檔案系統 BB1 目錄之上,如圖所示:

或者 C 直接掛載於 AA1 目錄之上:

您完全可以使用單一的一個大的根檔案系統 (root file system) 而不建立其他的檔案系統。 這樣有好處也有有壞處。

使用多個檔案系統的好處
  • 不同的檔案系統在掛上的時候可以有不同的 掛載參數。 舉例來說,為求謹慎您可以將根檔案系統設成唯讀, 以避免不小心刪除或修改掉重要的檔案。 將使用者可寫入的檔案系統 (例如 /home) 獨立出來也可以讓他們用 nosuid 的參數掛載,此選項可以讓在這個檔案系統中執行檔的 suid/guid bits 失效,也許可以讓系統更安全。

  • FreeBSD 會自動根據您檔案系統的使用方式來做最佳的檔案配置方式。 因此,一個有很多小檔案、 常常寫入的檔案系統跟只有幾個較大的檔案的檔案系統配置是不一樣的。 如果您只有單一一個大的檔案系統,這部分就沒用了。

  • FreeBSD 的檔案系統在停電的時候很穩固。 然而,在某些重要的時候停電仍然會對檔案系統結構造成損害。 分割成許多個檔案系統的話在系統在停電後比較能夠正常啟動, 以便您在需要的時候將備份資料回存回來。

使用單一檔案系統的好處
  • 檔案系統的大小是固定的。 您當初安裝 FreeBSD 的時候應該會給定一個大小,可是後來您可能會想把空間加大。 如果沒有備份的話是很難達成的; 您必須將檔案系統重新建立為您需要的大小,然後將備份回存回來。

    重要:

    FreeBSD 的 growfs(8) 指令可以突破此限制直接變更檔案系統的大小。

檔案系統包含在分割區裡面。 因為 FreeBSD 承襲 UNIX® 架構,這邊講的分割區和一般提到的分割區 (例如 MS-DOS® 分割區) 不同。 每一個分割區由一個代號(字母)表示,從 ah。 每個分割區只能包含一個檔案系統。 因此除了說常見到用檔案系統同的掛載點來表示檔案系統外, 也可以用包含他的分割區代號來表示。

FreeBSD 也會拿磁碟空間來當 swap space。 Swap space 給 FreeBSD 當作虛擬記憶體用。 這讓您的電腦好像擁有比實際更多的記憶體。 當 FreeBSD 的記憶體用完的時候,它會把一些目前沒用到的資料移到 swap space,然後在用到的時候移回去 (同時移出部份沒用到的)。

某些分割區有慣例的使用方式如下:

分割區慣例
a通常包含根檔案系統 (root file system)
b通常是 swap space
c通常和整個 slice 的大小一樣,給一些會用到整個 slice 的工具程式 (例如硬碟壞軌檢查工具) 來使用。 一般來說您應該不會把檔案系統建立在這個分割區。
d分割區 d 曾經有代表特殊意義,但是已經不再使用。 所以現在 d 就和其他一般的分割區相同了。

每個包含有檔案系統的分割區是存在所謂的 slice 裡面。 FreeBSD 的 slice 就是指平常我們在 Windows® 稱為分割區 (partition) 的東西一樣有自己的檔案系統,用單字標示,編號從 1 號到 4 號。

slice 號碼跟在裝置名稱後面,先接一個字母 s,然後從 1 號開始編下去。 因此 da0s1 就是指第一個 SCSI 硬碟的第一個 slice。 一個磁碟上只能有四個實體的 slice,但是在實體的 slice 中您可以塞進適當類型的邏輯 slice。 這些延伸的 slice 編號從 5 開始,所以 ada0s5 是第一個 SATA 硬碟上的第一個延伸 slice。 檔案系統在裝置 (device) 裡就是在一個 slice 之中。

Slices、dangerously dedicated 模式的實體磁碟機,以及其他包含分割區(partition) 的磁碟都是以字母 ah 的編號來表示。 編號是接在裝置名稱的後面的,因此 da0a is the a 是磁碟機 da 上的第一個 dangerously dedicated 模式之分割區。 而 ada1s3e 則是第二顆 SATA 硬碟上第三個 slice 的第五個分割區。

最後,我們就可以把系統上的每個磁碟都區分出來了。 一個磁碟的名稱會有一個代碼來表示這個磁碟的類型,接著是一個數字, 表示這是哪一個磁碟。 這邊跟 slice 每個磁碟編號從 0 開始不一樣。 常見的代碼可以參考 表格 表格 3.3, “磁碟裝置名稱”

當要參照一個分割區的時候,需包含磁碟機名稱 s 加上 slice 編號,最後再輸入分割區字母代號。 範例可以參考 範例 3.12, “磁碟、Slice 及分割區命名範例”

範例 3.13, “磁碟的概念模型” 示範了一個基本的磁碟配置,相信對您有些幫助。

要安裝 FreeBSD,您必須先建置磁碟的 slice,接著於 slice 中建立要給 FreeBSD 用的分割區。 最後在這些分割區中建立檔案系統 (或 swap space) 並決定要將這些檔案系統掛載於哪裡。

表格 3.3. 磁碟裝置名稱
磁碟機類型磁碟機裝置稱
SATAIDE 硬碟adaad
SCSI 硬碟與 USB 儲存裝置da
SATAIDE CD-ROM 光碟機cdacd
SCSI CD-ROM 光碟機cd
軟碟機fd
各種非標準 CD-ROM 光碟機mcd 代表 Mitsumi CD-ROM 以及 scd 代表 Sony CD-ROM 光碟機
SCSI 磁帶機sa
IDE 磁帶機ast
RAID 磁碟機範例包含 aacd 代表 Adaptec® AdvancedRAID,mlxdmlyd 代表 Mylex®,amrd 代表 AMI MegaRAID®,idad 代表 Compaq Smart RAID,twed 代表 3ware® RAID.

範例 3.12. 磁碟、Slice 及分割區命名範例
名稱意義
ada0s1a第一個 SATA 硬碟 (ada0) 上第一個 slice (s1)的第一個分割區(a) 。
da1s2e第二個 SCSI 硬碟 (da1) 上第二個 slice (s2) 的第五個分割區 (e) 。

範例 3.13. 磁碟的概念模型

此圖顯示 FreeBSD 中接到系統的第一個 SATA 磁碟機內部配置圖。 假設這個磁碟的容量是 250 GB,並且包含了一個 80 GB 的 slice 及一個 170 GB 的 slice (MS-DOS® 的分割區)。 第一個 slice 是 Windows® NTFS 檔案系統的 C: 磁碟機,第二個則安裝了 FreeBSD。 本範例的 FreeBSD 有三個分割區以及一個 swap 分割區。

這四個分割區每個都是一個檔案系統。 a 分割是根 (root) 檔案系統;分割 d/var/;分割 e/tmp/,而 f 分割是 /usr/ 目錄結構。Partition letter c refers to the entire slice, and so is not used for ordinary partitions.


3.7. 掛載與缷載檔案系組

檔案系統就像一顆樹。/ 就像是樹根,而 /dev/usr 以及其他在根目錄下的目錄就像是樹枝,而這些樹枝上面又還有分支,像是 /usr/local 等。

因為某些原因,我們會將一些目錄分別放在不同的檔案系統上。 如 /var 包含了可能會滿出來的 log/spool/ 等目錄以及各式各樣的暫存檔。 把根檔案系統塞到滿出來顯然不是個好主意,所以我們往往會比較傾向把 /var/ 中拉出來。

另一個常見到把某些目錄放在不同檔案系統上的理由是: 這些檔案在不同的實體或虛擬磁碟機上。 像是網路檔案系統 (Network File System) 詳情可參考 節 28.3, “網路檔案系統 (NFS)” 或是光碟機。

3.7.1. fstab

/etc/fstab 裡面有設定的檔案系統會在開機(章 12, FreeBSD 開機程序)的過程中自動地被掛載 (除非該檔案系統有被加上 noauto 參數)。檔案內容的格式如下:

device       /mount-point fstype     options      dumpfreq     passno
device

已存在的裝置名稱,詳情請參閱 表格 3.3, “磁碟裝置名稱”

mount-point

檔案系統要掛載到的目錄 (該目錄必須存在)。

fstype

檔案系統類型,這是要傳給 mount(8) 的參數。 FreeBSD 預設的檔案系統是 ufs

options

可讀可寫(Read-Write)的檔案系統用 rw,而唯讀(Read-Only)的檔案系統則是用 ro,後面視需要還可以加其他選項。 常見的選項如 noauto 是用在不要於開機過程中自動的掛載的檔案系統。 其他選項可參閱 mount(8) 說明。

dumpfreq

dump(8) 由此項目決定那些檔案系統需要傾印。 如果這格空白則以零為預設值。

passno

這個項目決定檔案系統檢查的順序。 對於要跳過檢查的檔案系統,它們的 passno 值要設為零。 根檔案系統的 passno 值應設為一 (因為需要比所有其他的還要先檢查),而其他的檔案系統的 passno 值應該要設得比一大。 若有多個檔案系統具有相同的 passno 值,則 fsck(8) 會試著平行地 (如果可能的話) 檢查這些檔案系統。

更多關於 /etc/fstab 檔案格式及選項的資訊請參閱 fstab(5) 說明文件。

3.7.2. 使用 mount(8)

mount(8) 指令是拿來掛載檔案系統用的。基本的操作指令格式如下:

# mount device mountpoint

mount(8) 裡面有提到一大堆的選項,不過最常用的就是這些:

掛載選項
-a

把 /etc/fstab 裡面所有還沒有被掛載、沒有被標記成 /etc/fstab 而且沒有用 -t 排除的檔案系統掛載起來。

-d

執行所有的動作,但是不真的去呼叫掛載的 system call。 這個選項和 -v 搭配拿來推測 mount(8) 將要做什麼動作時很好用。

-f

強迫掛載不乾淨的檔案系統 (危險),或是用來強制取消寫入權限 (把檔案系統的掛載狀態從可存取變成唯讀)。

-r

用唯讀的方式掛載檔案系統。 這個選項和在 -o 選項中指定 ro 參數是一樣的。

-t fstype

用指定的檔案系統型態來掛載指定的檔案系統,或是在有 -a 選項時只掛載指定型態的檔案系統。預設的檔案系統類型為 ufs

-u

更新檔案系統的掛載選項。

-v

顯示詳細資訊。

-w

以可讀寫的模式掛載檔案系統。

-o 選項後面會接著以逗號分隔的參數:

nosuid

不解析檔案系統上的 setuid 或 setgid 旗標, 這也是一個蠻有用的安全選項。

3.7.3. 使用 umount(8)

要缺載檔案系統可使用 umount(8) 指令。該指令需要一個參數可以是掛載點 (mountpoint),裝置名稱,以及 -a 或是 -A 等選項。

加上 -f 可以強制卸載,加上 -v 則是會顯示詳細資訊。 要注意的是一般來說用 -f 並不是個好主意,強制卸載檔案系統有可能會造成電腦當機, 或者損壞檔案系統內的資料。

-a-A 是用來卸載所有已掛載的檔案系統,另外還可以用 -t 來指定要卸載的是哪些種類的檔案系統。 要注意的是 -A 並不會試圖卸載根檔案系統。

3.8. 程序與 Daemon

FreeBSD 是一個多工的作業系統,也就是說在同一時間內可以跑超過一個程式。 每一個正在花時間跑的程式就叫做 程序 (process)。 您下的每個指令都至少會開啟一個新的程序, 而有些系統程序是一直在跑以維持系統正常運作的。

每一個程序都有一個獨一無二的數字叫做 程序代號 (Process ID, PID),而且就像檔案一樣,每一個程序也有擁有者及群組。 擁有者及群組的資訊是用來決定什麼檔案或裝置是這個程序可以開啟的 (前面有提到過檔案權限)。 大部份的程序都有父程序。 父程序是開啟這個程序的程序,例如:您對 shell 輸入指令,shell 本身就是一個程序,而您執行的指令也是程序。 每一個您用這種方式跑的程序的父程序都是 shell。 有一個特別的程序叫做 init(8) 是個例外,在 FreeBSD 開機的時候 init 會自動地被開啟,init 永遠是第一個程序,所以他的 PID 一直都會是 1

有些程式並不是設計成一直在接收使用者的輸入的, 而是在開始執行的時候就從中斷與終端機的連線。 例如說, 網頁伺服器整天都在回應網頁方面的要求,它通常不需要您輸入任何東西。 另外,像是把信從一個站傳送到另一個站的程式,也是這種類型的應用程式。我們把這種程式稱作 Daemon。 Daemon 一詞是來自是希臘神話中的角色:祂們既不屬於善良陣營或邪惡陣營,祂們在背地裡做一些有用的事情。這也就是為何 BSD 的吉祥物,是一隻穿著帆布鞋拿著三叉耙的快樂小惡魔的原因。

通常來說做為 Deamon 執行的程式名字後面都會加一個字母 dBIND 是 Berkeley Internet Name Domain 的縮寫,但實際上執行的程式名稱是 namedApache 網頁伺服器的程式名稱是 httpd、行列式印表機暫存服務(Line Printer Spooling) Daemon 是 lpd,依此類推。 但這是習慣用法,並沒有硬性規定,例如 Sendmail 主要的寄信 Daemon 是叫做 sendmail 而不是 maild

3.8.1. 檢視程序

要看系統執行中的程序,有兩個相當有用的指令可用: ps(1) 以及 top(1)ps(1) 指令是用來列出正在執行之程序,而且可以顯示它們的 PID、用了多少記憶體、執行的指令名稱及其後之參數是什麼等等。 top(1) 指令則是顯示所有正在執行的程序, 並且數秒鐘更新一次。因此您可以互動式的觀看您的電腦正在做什麼。

在預設的情況下,ps(1) 指令只會顯示使用者所擁有的的程序。 例如:

% ps
 PID TT  STAT    TIME COMMAND
8203  0  Ss   0:00.59 /bin/csh
8895  0  R+   0:00.00 ps

在這個範例裡可以看到 ps(1) 的輸出分成好幾個欄位。 PID 就是前面有提到的程序代號。 PID 的分配是從 1 開始一直到 99999,如果用完的話又會繞回來重頭開始分配 (若該 PID 已經在用了,則 PID 不會重新分配)。 TT 欄位是指這個程式在哪個 Console (tty) 上執行,在這裡可以先忽略不管。STAT 是程式的狀態,也可以先不要管。TIME 是這個程式在 CPU 上執行的時間—這通常不是程式總共花的時間, 因為當您開始執行程式後,大部份的程式在 CPU 上執行前會先花上不少時間等待 。 最後,COMMAND 是執行這個程式的指令。

有幾個不同的選項組合可以用來變更顯示出來的資訊,其中一個最有用的組合是 auxwwa 可以顯示所有正在跑的程序的指令,不只是您自已的。 u 則是顯示程序的擁有者名稱以及記憶體使用情況。 x 可以把 daemon 程序顯示出來, 而 ww 可讓 ps(1) 顯示出每個程序完整的內容, 而不致因過長而被螢幕截掉了。

top(1) 也有類似的輸出。 一般的情況看像是這樣:

% top
last pid:  9609;  load averages:  0.56,  0.45,  0.36              up 0+00:20:03  10:21:46
107 processes: 2 running, 104 sleeping, 1 zombie
CPU:  6.2% user,  0.1% nice,  8.2% system,  0.4% interrupt, 85.1% idle
Mem: 541M Active, 450M Inact, 1333M Wired, 4064K Cache, 1498M Free
ARC: 992M Total, 377M MFU, 589M MRU, 250K Anon, 5280K Header, 21M Other
Swap: 2048M Total, 2048M Free

  PID USERNAME    THR PRI NICE   SIZE    RES STATE   C   TIME   WCPU COMMAND
  557 root          1 -21  r31   136M 42296K select  0   2:20  9.96% Xorg
 8198 dru           2  52    0   449M 82736K select  3   0:08  5.96% kdeinit4
 8311 dru          27  30    0  1150M   187M uwait   1   1:37  0.98% firefox
  431 root          1  20    0 14268K  1728K select  0   0:06  0.98% moused
 9551 dru           1  21    0 16600K  2660K CPU3    3   0:01  0.98% top
 2357 dru           4  37    0   718M   141M select  0   0:21  0.00% kdeinit4
 8705 dru           4  35    0   480M    98M select  2   0:20  0.00% kdeinit4
 8076 dru           6  20    0   552M   113M uwait   0   0:12  0.00% soffice.bin
 2623 root          1  30   10 12088K  1636K select  3   0:09  0.00% powerd
 2338 dru           1  20    0   440M 84532K select  1   0:06  0.00% kwin
 1427 dru           5  22    0   605M 86412K select  1   0:05  0.00% kdeinit4

輸出的資訊分成兩個部份。開頭 (前五行或六行) 顯示出最近一個程序的 PID、系統平均負載 (系統有多忙錄的測試)、系統的開機時間 (從上次重開算起) 以及現在的時間等。 在開頭裡面的其他數字分別是在講有多少程序正在執行、有多少記憶體及 swap 空間被占用了,還有就是系統分別花了多少時間在不同的 CPU 狀態上。If the ZFS file system module has been loaded, an ARC line indicates how much data was read from the memory cache instead of from disk.

接下來的部份是由好幾個欄位所構成,和 ps(1) 輸出的資訊類似。 就如同前例,您可以看到 PID、使用者名稱、CPU 花費的時間以及正在執行的指令。 top(1) 在預設的情況下還會告訴您程序用掉了多少的記憶體空間。 在這邊會分成兩欄,一個是總用量 (total size),另一個是實際用量 (resident size)——總用量是指這個應用程式需要的記憶體空間,而實際用量則是指目前實際上該程式的記憶體使用量。

top(1) 每隔 2 秒鐘會自動更新顯示內容,可用 -s 選項來改變間隔的時間。

3.8.2. 終止程序

要與執行中的程序或 Daemon 溝通唯一的方法是透過 kill(1) 指令傳送信號 (signal)。 信號有很多種,有些有特定的意義,有些則是會由應用程式來解讀,應用程式的說明文件會告訴您該程式是如何解讀信號。 使用者只能送信號給自己所擁有的程序,送信號給其他人的程序會出現權限不足的錯誤。 唯一的例外是 root使用者,他可以送信號給任何人的程序。

作業系統在某些情況也會送信號給應用程式。 假設有個應用程式寫得不好,企圖要存取它不該碰的記憶體的時候,FreeBSD 會送一個 Segmentation Violation 信號 (SIGSEGV) 給這個程序。 如果有一個應用程式用了 alarm(3) 的 system call 要求系統在過一段時間之後發出通知,時間到了的時候系統就會發出通知信號 (SIGALRM) 給該程式。

SIGTERMSIGKILL 這兩個信號可以拿來終止程序。 用 SIGTERM 結束程序是比較有禮貌的方式,該程序收到信號後可以把自已所使用的日誌檔關閉及其他要在結束前要做的事完成, 然後在關掉程序之前結束掉手邊的工作。 在某些情況下程序有可能會忽略 SIGTERM,如它正在做一些不能中斷的工作的話。

SIGKILL 就沒有辦法被程序忽略。 傳送 SIGKILL 信號給程序通常會將程序直接中止[1]

其他常用的信號有:SIGHUP, SIGUSR1SIGUSR2。 這些是通用的信號,對不同的應用程式會有不同的反應。

舉例來說,當您更動了網頁伺服器的設定檔,您想要叫網頁伺服器去重新讀取設定。 重新啟動 httpd 會造成網頁伺服器暫停服務一段時間,我們可以傳送 SIGHUP 信號來取代關掉重開。 不同的 Daemon 會有不同的行為,所以使用前請先參考 Deamon 的說明文件查看是否可以達到想要的結果。

過程 3.1. 送信號給程序

這個範例將會示範如何送一個信號給 inetd(8)inetd(8) 的設定檔是 /etc/inetd.conf,而 inetd(8) 會在收到 SIGHUP 的時候重新讀取這個設定檔。

  1. 使用 pgrep(1) 來查詢要傳送信號的目標程序。 在這個例子中 inetd(8)PID 為 198:

    % pgrep -l inetd
    198  inetd -wW
  2. 使用 kill(1) 來發送信號。因為 inetd(8)root 所有,因此必須先用 su(1) 切換成 root 先。

    % su
    Password:
    # /bin/kill -s HUP 198

    對大多數 UNIX® 指令來講,kill(1) 執行成功時並不會輸出任何訊息。 假設您送一個信號給某個不是使用者所擁有的程序, 那麼就會顯示這個錯誤訊息: kill: PID: Operation not permitted。 若打錯 PID 的話,那就會把信號送給錯誤的程序,並把該程序關閉,或者是把信號送給一個非使用中的 PID,那您就會看到錯誤:kill: PID: No such process

    為何要使用 /bin/kill? :

    多數 shell 都有提供內建的 kill 指令。 也就是說這種 shell 會直接發送信號,而不是執行 /bin/kill。 但要小心不同的 shell 會有不同的語法來指定信號的名稱等。 與其嘗試去把它們通通學會,不如就單純的直接用 /bin/kill

要送其他的信號的話也是非常類似,就視需要把指令中的 TERMKILL 替換成其他信號的名稱即可。

重要:

隨便抓一個系統中的程序然後把他砍掉並不是個好主意。 特別是 init(8)PID 1 是一個非常特別的程序。 執行 /bin/kill -s KILL 1 的結果就是系統立刻關機。 因此在您按下 Return 要執行 kill(1) 之前, 請一定要記得再次確認您下的參數。

3.9. Shell

Shell 提供了指令列介面可用來與作業系統互動,Shell 負責從輸入的頻道接收指令並執行它們。 多數 Shell 也內建一些有助於日常工作的功能,像是檔案管理、檔案搜尋、指令列編輯、指令巨集以及環境變數等。 FreeBSD 有內附了幾個 Shell,包含 Bourne Shell (sh(1)),與改良版的 C-shell (tcsh(1))。 還有許多其他的 Shell 可以從 FreeBSD Ports 套件集中取得,像是 zsh 以及 bash 等。

要用哪個 Shell 牽涉到每個人的喜好。 如果您是一個 C 程式設計師,那對於使用像是 tcsh(1) 這種 C-like 的 shell 可能會感到較容易上手。 如果是 Linux® 的使用者,那您也許會想要用 bash。 每一個 Shell 都有自已獨特之處,至於這些特點能不能符合使用者的喜好,就是您選擇 shell 的重點了。

常見的 Shell 功能之一就是檔名自動補齊。 首先輸入指令或檔案的前幾個字母,然後按下 Tab 鍵,Shell 就會自動把指令或是檔案名稱剩餘的部份補齊。 假設您有兩個檔案分別叫作 foobarfootball。 要刪掉 foobar,那麼可以輸入 rm foo 然後按下 Tab 來補齊檔名。

但 Shell 只顯示了 rm foo,這代表它沒有辦法完全自動補齊檔名,因為有不只一個檔名符合條件。 foobarfootball 都是 foo 開頭的檔名。 有一些 Shell 會有嗶的音效或者顯示所有符符條件的檔名。 使用者只需要多打幾個字元來分辦想要的檔名。 輸入 t 然後再按 Tab 一次,那 Shell 就能夠替您把剩下的檔名填滿了。

Shell 的另一項特點是使用了環境變數。 環境變數是以變數與鍵值 (variable/key) 的對應關係儲存於 Shell 的環境,任何由該 Shell 所產生的程序都可以讀取此環境變數, 因此環境變數儲存了許多程序的設定。 表格 3.4, “常用環境變數” 提供了常見的環境變數與其涵義的清單。 請注意環境變數的名稱永遠以大寫表示。

表格 3.4. 常用環境變數
變數說明
USER目前登入的使用者名稱。
PATH以冒號 (:) 隔開的目錄列表,用以搜尋執行檔的路徑。
DISPLAY若存在這個環境變數,則代表 Xorg 顯示器的網路名稱。
SHELL目前使用的 Shell。
TERM使用者終端機類型的名稱,用來判斷終端機有那些功能。
TERMCAPDatabase entry of the terminal escape codes to perform various terminal functions.
OSTYPE作業系統的類型。
MACHTYPE系統的 CPU 架構。
EDITOR使用者偏好的文字編輯器。
PAGER使用者偏好的文字分頁檢視工具。
MANPATH以冒號 (:) 隔開的目錄列表,用以搜尋使用手冊的路徑。

在不同的 shell 底下設定環境變數的方式也有所不同。 在 tcsh(1)csh(1),使用 setenv 來設定環境變數。 在 sh(1)bash, use export,則使用 export 來設定目前環境的變數。 以下範例將 tcsh(1) 下的 EDITOR 環境變數從預設值更改為 /usr/local/bin/emacs

% setenv EDITOR /usr/local/bin/emacs

相同功能的指令在 bash 下則是:

% export EDITOR="/usr/local/bin/emacs"

要展開以顯示目前環境變數中的值,只要在指令列輸入環境變數之前加上 $ 字元。 舉例來說,echo $TERM 會顯示出目前 $TERM 的設定值。

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

為了避免 Shell 轉譯這些特殊字元,我們可以在這些特殊字元前放一個反斜線 (\) 字元使他們跳脫(escape) Shell 的轉譯。舉例來說,echo $TERM 會印出你目前終端機的設定, echo \$TERM 則會直接印出 $TERM 這幾個字。

3.9.1. 變更 Shell

永久變更 Shell 最簡單的方法就是透過 chsh 命令。 執行 chsh 將會使用環境變數中 EDITOR 指定的文字編輯器,如果沒有設定,則預設是 vi(1)。 請修改 Shell: 為新的 Shell 的完整路徑。

或者,使用 chsh -s, 來直接設定 Shell 而不開啟文字編輯器。 例如, 假設想把 Shell 更改為 bash

% chsh -s /usr/local/bin/bash

注意:

新的 Shell 必須已列於 /etc/shells 裡頭。 若是依 章 4, 安裝應用程式: 套件與 Ports 說明由 Ports 套件集來裝的 Shell, 那就會自動列入至該檔案裡。 若仍缺少,請使用以下指令加入檔案 (請將路徑替換為新的 Shell 的路徑):

# echo /usr/local/bin/bash >> /etc/shells

然後重新執行 chsh(1)

3.9.2. 進階 Shell 技巧

Written by Tom Rhodes.

The UNIX® shell is not just a command interpreter, it acts as a powerful tool which allows users to execute commands, redirect their output, redirect their input and chain commands together to improve the final command output. When this functionality is mixed with built in commands, the user is provided with an environment that can maximize efficiency.

Shell redirection is the action of sending the output or the input of a command into another command or into a file. To capture the output of the ls(1) command, for example, into a file, redirect the output:

% ls > directory_listing.txt

The directory contents will now be listed in directory_listing.txt. Some commands can be used to read input, such as sort(1). To sort this listing, redirect the input:

% sort < directory_listing.txt

The input will be sorted and placed on the screen. To redirect that input into another file, one could redirect the output of sort(1) by mixing the direction:

% sort < directory_listing.txt > sorted.txt

In all of the previous examples, the commands are performing redirection using file descriptors. Every UNIX® system has file descriptors, which include standard input (stdin), standard output (stdout), and standard error (stderr). Each one has a purpose, where input could be a keyboard or a mouse, something that provides input. Output could be a screen or paper in a printer. And error would be anything that is used for diagnostic or error messages. All three are considered I/O based file descriptors and sometimes considered streams.

Through the use of these descriptors, the shell allows output and input to be passed around through various commands and redirected to or from a file. Another method of redirection is the pipe operator.

The UNIX® pipe operator, | allows the output of one command to be directly passed or directed to another program. Basically, a pipe allows the standard output of a command to be passed as standard input to another command, for example:

% cat directory_listing.txt | sort | less

In that example, the contents of directory_listing.txt will be sorted and the output passed to less(1). This allows the user to scroll through the output at their own pace and prevent it from scrolling off the screen.

3.10. 文字編輯器

在 FreeBSD 中有許多設定必須透過編輯文字檔完成。 因此,若能熟悉文字編輯器是再好不過的。 FreeBSD 本身就內建幾種文字編輯器, 您也可以透過 Ports 套件集來安裝其他的文字編輯器。

最簡單易學的文字編輯器叫做 ee(1),意為簡易的編輯器(Easy Editor)。 要開始使用這個編輯器, 只需輸入 ee filename,其中 filename 代表你想要編輯的檔案名稱。 在編輯器中, 所有編輯器的功能與操作都顯示在螢幕的上方。 其中的插入符號 (^) 代表鍵盤上的 Ctrl 鍵,所以 ^e 代表的是 Ctrl+e。 若要結束 ee(1),請按下 Esc 鍵,接著選擇 leave editor 即可。 此時如果該檔案有修改過,編輯器會提醒你是否要存檔。

FreeBSD 同時也內建功能強大的文字編輯器,像是vi(1)。 其他編輯器如 editors/emacseditors/vim 則由 FreeBSD Ports 套件集提供。 這些編輯器提供更強的功能,但是也比較難學習。 長期來看學習 vimEmacs 會在日後為您省下更多的時間。

Many applications which modify files or require typed input will automatically open a text editor. To change the default editor, set the EDITOR environment variable as described in 節 3.9, “Shell”.

3.11. 裝置及裝置節點

裝置(Device)一詞大多是跟硬體比較有關的術語,包括磁碟、印表機、顯示卡和鍵盤。 FreeBSD 開機過程當中,開機訊息(Boot Message)中主要是會列出偵測到的硬體裝置,開機訊息的複本也會存放在 /var/run/dmesg.boot

每一個裝置都有一個裝置名稱及編號,舉例來說 ada0 是第一台 SATA 硬碟,而 kbd0 則代表鍵盤。

在 FreeBSD 中大多數的裝置必須透過裝置節點(Device Node)的特殊檔案來存取,這些檔案會放置在 /dev

3.12. 操作手冊

在 FreeBSD 中,最詳細的文件莫過於操作手冊。 幾乎在系統上所有程式都會有簡短的操作手冊來介紹該程式的基本操作以及可用的參數。 這些操作手冊可以使用 man 指令來檢視:

% man command

其中 command 想要瞭解指令的名稱。 舉例,要知道 ls(1) 的詳細用法,就可以打:

% man ls

操作手冊被分成很多個章節,每個章節有不同的主題。 在 FreeBSD 中操作手冊有以下章節:

  1. 使用者指令。

  2. 系統呼叫(System call)與錯誤編號。

  3. C 程式庫函數。

  4. 裝置驅動程式。

  5. 檔案格式。

  6. 遊戲及其他程式。

  7. 其他資訊。

  8. 系統維護與操作指令。

  9. 系統核心介面。

有些情況會有同樣主題會同時出現在不同章節。 舉個例子,系統內會有 chmod 使用者指令,但同時也有 chmod() 系統呼叫。 在這種情況,要告訴 man(1) 要查詢的章節編號:

% man 1 chmod

如此一來就會查詢使用者指令 chmod(1)。 通常在寫文件時會把有參考到特定章節的號碼寫在括號內。 所以 chmod(1) 就是指使用者指令,而 chmod(2) 則是指系統呼叫。

若不曉得操作手冊的名稱,可以使用 man -k 來以關鍵字查詢所有操作手冊的描述:

% man -k mail

這個指令會顯示所有描述中有使用到關鍵字 mail 的指令。 這等同使用 apropos(1)

想要閱讀所有在 /usr/bin 底下的指令說明則可輸入:

% cd /usr/bin
% man -f * | more

% cd /usr/bin
% whatis * |more

3.12.1. GNU Info 檔

FreeBSD 有許多應用程式與工具來自自由軟體基金會(Free Software Foundation, FSF)。 除了操作手冊之外,這些程式提供了另外一種更具有彈性的超文字文件叫做 info 檔。 這些檔案可以使用 info(1) 指令來閱讀,或者若有裝 editors/emacs 亦可透過 emacs 的 info 模式閱讀。

要使用 info(1) 指令,只需輸入:

% info

要查詢簡單說明請按 h 鍵,若要查訊快速指令參考請按 ? 鍵。



[1] 還是有少數東西不能被中斷。 例如有個程序正在從網路上的別的電腦讀一個檔案, 而那部電腦因為某些理由連不到,那這個程序就是一個 不能中斷的 程序。 通常在經過 2 分鐘左右之後這個程序會逾時。 當發生逾時的時候這個程序就會被結束掉了。

章 4. 安裝應用程式: 套件與 Ports

4.1. 概述

FreeBSD 已內建豐富的系統工具,此外 FreeBSD 提供了 2 種安裝第三方軟體的套件管理技術︰由原始碼安的 FreeBSD Ports 套件集,以及由預先編譯好的 Binary 安裝的 Binary 套件集。 無論要用哪一種方式,都可由本地的媒體或網路來安裝軟體。

讀完這章,您將了解︰

  • Binary 套件集與 Ports 的差別。

  • 如何找到已移植到 FreeBSD 的第三方軟體。

  • 如何使用 pkg 管理 Binary 套件。

  • 如何編譯來自 Ports 套件集的第三方軟體原始碼。

  • 如何找到應用程式已安裝的檔案來完成安裝後的設定。

  • 若軟體安裝失敗要如何處理。

4.2. 安裝軟體的概要

通常要在 UNIX® 系統上安裝第三方軟體時,有幾個步驟要作:

  1. 找到並且下載軟體,該軟體有可能以原始碼或 Binary 格式發佈。

  2. 解壓縮軟體。 發佈的格式通常會使用 tarball 並以 compress(1), gzip(1)bzip2(1) 壓縮。

  3. 找到位於 INSTALL, README 或者 doc/ 子目錄底下的檔案閱讀如何安裝該軟體。

  4. 若軟體是以原始碼的格式發佈則需要編譯該軟體。 這可能會需要修改 Makefile 或執行 configure Script。

  5. 測試並安裝該軟體。

如果軟體套件未被特意移植到 FreeBSD 或測試是否可運作。 那可能需要修改一下該軟體的原始碼才能正常使用。 在搛寫此篇文章時候, 已經有超過 24,000 個第三方應用程式已經被移植到 FreeBSD。

FreeBSD Binary 套件中包含了應用程式預先編譯好的指令、設定檔及文件。 套件可以使用 pkg 指令來管理,如 pkg install

FreeBSD Port 套件則包含了已設計好從原始碼編譯成應用程式的自動化程序。 Port 套件中的檔案包含自動下載、解壓縮、修補、編譯及安裝應用程式流程中所有需要的資訊。

Ports 系統可以透過 FreeBSD 套件管理指令來產生套件。

不論是 Binary 套件或者 Ports 套件都有相依的功能,若以 Binary 或 Port 套件安裝應用程式,且該應用程式有相依的程式庫尚未被安裝,則會自動先安裝該程式庫。

雖然兩種技術非常相似,但 Binary 套件及 Ports 套件有各自的優點。 要視您要安裝的應用程式需求來選擇。

Binary 套件優點
  • 應用程式壓縮 Binary 套件的 tarball 會比壓縮原始碼的 tarball 還要小。

  • 安裝 Binary 套件不需要編譯的時間,對於較慢的電腦要安裝大型的應用程式如 Mozilla, KDEGNOME 這點顯的相當重要。

  • Binary 套件不需要了解在 FreeBSD 上編譯軟體的流程。

Port 套件優點
  • 由於 Binary 套件必須盡可能在大多數系統上執行,通常會採用較通用的編譯選項來編譯,由 Port 來編輯可更改編譯選項。

  • 部份應用程式編譯期選項會與要安裝的功能有關,舉例來說 Apache 便有大量不同的內建選項可以設定。

    在某些情況,同樣的應用程式會存在多個不同的 Binary 套件,如 Ghostscriptghostscriptghostscript-nox11 兩種 Binary 套件,用來區別是否有安裝 Xorg。 若應用程式有一個以上的編譯期選項便無法用這個方式來區別 Binary 套件。

  • 部份軟體的授權條款中禁止以 Binary 格式發佈。 這種軟體必須以原始碼發佈並由終端使用者編譯。

  • 部份人並不相信 Binary 發佈版本,寧願閱讀原始碼來查看是否潛藏的問題。

  • 原始碼可套用自訂的修補。

要持續追蹤 Ports 的更新可以訂閱 FreeBSD Ports 郵遞論壇FreeBSD Ports 問題郵遞論壇

警告:

在安裝任何應用程式之前,請先查看 http://vuxml.freebsd.org/ 是否有與該應用程式相關的安全性問題或輸入 pkg audit -F 來檢查所有已安裝的應用程式是否有已知的漏洞。

本章接下來的部份將說明如何在 FreeBSD 使用 Binary 套件及 Ports 套件安裝與管理第三方軟體。

4.3. 搜尋軟體

FreeBSD 上可安裝的軟體清單不斷在增加, 有幾種方式可以來找你想安裝的軟體:

  • FreeBSD 網站有維護一份可搜尋的最新應用程式清單,在 http://www.FreeBSD.org/ports/。 可以依應用程式名稱或軟體分類來搜尋 Ports。

  • 由 Dan Langille 維護的 FreshPorts.org,提供完整的搜尋工具並且可追蹤在 Ports 套件集中的應用程式變更。註冊的使用者可以建立自訂的監視清單會自動寄發電子郵件通知 Ports 的更新資訊。

  • 若找不到指定的應用程式,可以先到網站 SourceForge.netGitHub.com 搜尋,後然再回到 FreeBSD 網站 檢查該應用程式是否已被移植。

  • 要搜尋 Binary 套件檔案庫中的應用程式可:

    # pkg search subversion
    git-subversion-1.9.2
    java-subversion-1.8.8_2
    p5-subversion-1.8.8_2
    py27-hgsubversion-1.6
    py27-subversion-1.8.8_2
    ruby-subversion-1.8.8_2
    subversion-1.8.8_2
    subversion-book-4515
    subversion-static-1.8.8_2
    subversion16-1.6.23_4
    subversion17-1.7.16_2

    套件名稱包含版本編號,且若 Ports 使用 Python 為基礎,也會包含用來編譯該套件的 Python 版本。有些 Ports 會有多個版本可使用,如 subversion ,因編譯選項不同,有多個版本可用,這個例子中即指靜態連結版本的 subversion。在指定要安裝的套件時,最好使用 Ports 來源來指定該應用程式,Ports 來源是指應用程式在 Ports 樹中的路徑。再輸入一次 pkg search 並加上 -o 來列出每個套件來源:

    # pkg search -o subversion
    devel/git-subversion
    java/java-subversion
    devel/p5-subversion
    devel/py-hgsubversion
    devel/py-subversion
    devel/ruby-subversion
    devel/subversion16
    devel/subversion17
    devel/subversion
    devel/subversion-book
    devel/subversion-static

    pkg search 支援使用 Shell 萬手字元(globs)、正規表示法、描述或檔案庫中的其他其他內容。在安裝 ports-mgmt/pkgports-mgmt/pkg-devel 之後,可參考 pkg-search(8) 以取得更多詳細資訊。

  • 若 Ports 套件集已安裝,有數個方法可以查詢 Ports 樹中的本地版本。要找到 Port 所在的分類,可輸入 whereis file,其中 file 是要安裝的程式:

    # whereis lsof
    lsof: /usr/ports/sysutils/lsof
  • 另一個方法是使用 Ports 套件集內建的搜尋機制來找軟體。要使用搜尋的功能需先 cd/usr/ports 然後執行 make search name=program-name,其中 program-name 代表軟體的名稱。舉例搜尋 lsof

    # cd /usr/ports
    # make search name=lsof
    Port:   lsof-4.88.d,8
    Path:   /usr/ports/sysutils/lsof
    Info:   Lists information about open files (similar to fstat(1))
    Maint:  ler@lerctr.org
    Index:  sysutils
    B-deps:
    R-deps: 

    提示:

    內建的搜尋機制會使用索引檔內的資訊。若出現訊息指出需要 INDEX 檔,可執行 make fetchindex 來下載最新的索引檔。當 INDEX 檔存在時,make search 方可執行請求的搜尋動作。

    Path: 此行代表 Ports 的所在位置。

    若不要接受這麼多資訊,可使用 quicksearch 功能:

    # cd /usr/ports
    # make quicksearch name=lsof
    Port:   lsof-4.88.d,8
    Path:   /usr/ports/sysutils/lsof
    Info:   Lists information about open files (similar to fstat(1))

    若要進行更有深度的搜尋,使用 make search key=stringmake quicksearch key=string 其中 string 是要搜尋的文字。該文字可以是一部份的註解、描述或相依套件,當不清楚程式的名稱時可以找到與特定主題相關的 Ports。

    當使用 searchquicksearch 時,搜尋的字串不分大小寫。 搜尋 LSOF 會與搜尋 lsof 產生相同的結果。

4.4. 使用 pkg 管理 Binary 套件

pkg is the FreeBSD package management tool, offering many features that make dealing with binary packages fast and easy.

4.4.1. 開始使用 pkg

FreeBSD 內建啟動(Bootstrap)工具可用來下載並安裝 pkg 及其操作手冊。

要啟動(Bootstrap)系統請執行:

# /usr/sbin/pkg

要安裝 Port 套件,請執行:

# cd /usr/ports/ports-mgmt/pkg
# make
# make install clean

預設 pkg 會使用 FreeBSD 套件鏡像站。若要取得有關編譯自訂套件檔案庫的資訊,請參考 節 4.6, “使用 Poudriere 編譯套件”

其他 pkg 設定選項說明請參考 pkg.conf(5)

pkg 的用法資訊可在 pkg(8) 操作手冊或不加任何參數執行 pkg 來取得。

每個 pkg 指令參數皆記庫在指令操件手冊。要閱讀 pkg install 的操作手冊,可執行以下指令:

# pkg help install
# man pkg-install

The rest of this section demonstrates common binary package management tasks which can be performed using pkg. Each command provides many switches to customize its use. Refer to a command's help or man page for details and more examples.

4.4.2. 取得有關已安裝套件的資訊

有關已安裝在系統的套件資訊可透過執行 pkg info 來檢視,若執行時未指定任何參數,將會列出所有已安裝或指定的套件版本。

例如,要查看已安裝的 pkg 版本可執行:

# pkg info pkg
pkg-1.1.4_1

4.4.3. 安裝與移除套件

要安裝 Binary 套件可使用以下指令,其中 packagename 為要安裝的套件名稱:

# pkg install packagename

這個指令會使用檔案庫的資料來決定要安裝的軟體版本以及是否有任何未安裝的相依。例如,要安裝 curl

# pkg install curl
Updating repository catalogue
/usr/local/tmp/All/curl-7.31.0_1.txz          100% of 1181 kB 1380 kBps 00m01s

/usr/local/tmp/All/ca_root_nss-3.15.1_1.txz   100% of  288 kB 1700 kBps 00m00s

Updating repository catalogue
The following 2 packages will be installed:

        Installing ca_root_nss: 3.15.1_1
        Installing curl: 7.31.0_1

The installation will require 3 MB more space

0 B to be downloaded

Proceed with installing packages [y/N]: y
Checking integrity... done
[1/2] Installing ca_root_nss-3.15.1_1... done
[2/2] Installing curl-7.31.0_1... done
Cleaning up cache files...Done

新的套件以及任何做為相依安裝的額外套件可在已安裝的套件清單中看到:

# pkg info
ca_root_nss-3.15.1_1	The root certificate bundle from the Mozilla Project
curl-7.31.0_1	Non-interactive tool to get files from FTP, GOPHER, HTTP(S) servers
pkg-1.1.4_6	New generation package manager

不再需要的套件可以使用 pkg delete 來移除,例如:

# pkg delete curl
The following packages will be deleted:

	curl-7.31.0_1

The deletion will free 3 MB

Proceed with deleting packages [y/N]: y
[1/1] Deleting curl-7.31.0_1... done

4.4.4. 升級已安裝套件

執行以下指令,可將已安裝的套件升級到最新版本:

# pkg upgrade

這個指令將會比對已安裝的版本與在檔案庫分類中的版本,並從檔案庫升級這些套件。

4.4.5. 稽查已安裝套件

偶爾可能會在第三方的應用程式中發現軟體漏洞,要找出這些程式,可使用 pkg 內建的稽查機制。要查詢已安裝在系統上的軟體是否有任何已知的漏洞可執行:

# pkg audit -F

4.4.6. 自動移除不使用的相依

移除一個套件可能會留下不再需要使用的相依套件。不再需要的相依套件可以使用以下指令自動偵測並移除:

# pkg autoremove
Packages to be autoremoved:
	ca_root_nss-3.15.1_1

The autoremoval will free 723 kB

Proceed with autoremoval of packages [y/N]: y
Deinstalling ca_root_nss-3.15.1_1... done

4.4.7. 還原套件資料庫

pkg includes its own package database backup mechanism. This functionality is enabled by default.

提示:

To disable periodic backups of the package database, set daily_backup_pkgdb_enable="NO" in periodic.conf(5).

To restore the contents of a previous package database backup, run this command replacing /path/to/pkg.sql with the location of the backup:

# pkg backup -r /path/to/pkg.sql

注意:

If restoring a backup made by the periodic script, it must be decompressed prior to being restored.

To create a manual backup of the pkg database, run the following command, replacing /path/to/pkg.sql with a suitable file name and location:

# pkg backup -d /path/to/pkg.sql

4.4.8. 移除過時的套件

預設 pkg 會儲存 Binary 套件在快取目錄定義在 pkg.conf(5) 中的 PKG_CACHEDIR,只會保留最後安裝的套件複本。較舊版的 pkg 會保留所有先前的套件,若要移除這些過時的 Binary 套件,可執行:

# pkg clean

The entire cache can be cleared by running:

# pkg clean -a

4.4.9. 修改套件 Metadata

在 FreeBSD Ports 套件集中的軟體可能會經歷主要版號的修改,要解決這個問題可使用 pkg 內建的指令來更新套件來源。這非常有用,例如 lang/php5 重新命名為 lang/php53 因此 lang/php5 從此之後代表版本 5.4

要更改上述例子中的套件來源,可執行:

# pkg set -o lang/php5:lang/php53

再一個例子,要更新 lang/ruby18lang/ruby19,可執行:

# pkg set -o lang/ruby18:lang/ruby19

最後一個例子,要更改 libglut 共用程式庫的來源從 graphics/libglut 改成 graphics/freeglut 可執行:

# pkg set -o graphics/libglut:graphics/freeglut

注意:

在更改套件來源之後,很重要的一件事是要重新安裝套件,來讓相依的套件也同時使用修改後的來源。要強制重新安裝相依套件,可執行:

# pkg install -Rf graphics/freeglut

4.5. 使用 Ports 套件集

Ports 套件集是指一系列儲存在 /usr/portsMakefiles、修補及描述檔,這一系列檔案用來編譯與安裝在 FreeBSD 上的應用程式。在使用 Port 安裝應用程式前,必須先安裝 Ports 套件集,若未在安裝 FreeBSD 的過程式中安裝,可使用下列其中一種方法來安裝:

過程 4.1. Portsnap 方法

FreeBSD 的基礎系統內含 Portsnap,這是一個可用來取得 Ports 套件集簡單又快速的工具,較建議多數使用者使用這個方式。此工具會連線到 FreeBSD 的網站,驗証密鑰,然後下載 Ports 套件集的新複本。該金鑰是要用來檢驗所有已下載檔案的完整性。

  1. 要下載壓縮後的 Ports 套件集快照 (Snapshot) 到 /var/db/portsnap

    # portsnap fetch
  2. 當第一次執行 Portsnap 時,要先解壓縮快照到 /usr/ports

    # portsnap extract
  3. 在完成上述第一次使用 Portsnap 的動作之後,往後可隨需要執行以下指令來更新 /usr/ports

    # portsnap fetch
    # portsnap update

    當使用 fetch 時也可同時執行 extractupdate 如:

    # portsnap fetch update
過程 4.2. Subversion 方法

若要取得更多對 Ports 樹的控制,或若有本地的變更需要維護,可以使用 Subversion 來取得 Ports 套件集。請參考 Subversion Primer 來取得 Subversion 的詳細說明。

  1. 必須安裝 Subversion 才可用來取出 (Check out) Ports 樹。若已存在 Ports 樹的複本,可使用此方式安裝 Subversion

    # cd /usr/ports/devel/subversion
    # make install clean

    若尚無法使用 Ports 樹,或已經使用 pkg 來管理套件,可使用套件來安裝 Subversion

    # pkg install subversion
  2. 取出 Ports 樹的複本:

    # svn checkout https://svn.FreeBSD.org/ports/head /usr/ports
  3. 若需要,在第一次 Subversion 取出後可使用以下指令更新 /usr/ports

    # svn update /usr/ports

Ports 套件集會安裝一系列代表軟體分類的目錄,每個分類底下的子目錄代表每隻應用程式。 這些子目錄又稱做 Ports Skeleton,裡面檔案是用來告訴 FreeBSD 如何編譯與安裝該程式,每個 Port Skeleton 會含有以下檔案及目錄:

  • Makefile: 內含用來說明應用程式要如何編譯、要安裝該程式到那的敘述句。

  • distinfo: 內含編譯 Port 必須下載的檔案名稱以及校驗碼 (Checksums)。

  • files/: 此目錄含有編譯與安裝程式到 FreeBSD 時所需的修補檔。此目錄也可能含有其他用來編譯 Ports 的檔案。

  • pkg-descr: 提供程式更詳細的說明。

  • pkg-plist: Port 安裝的所有檔案清單,也同時會告訴 Ports 系統解除安裝時要移除那一些檔案。

部份 Ports 含有 pkg-message 或其他檔案用來處理特殊情況。要取得有關這些檔案的詳細資訊,以及 Ports 的概要可參考 FreeBSD Porter's Handbook

Port 中並不含實際的原始碼,即為 distfile,在編譯 Port 解壓縮時會自動下載的原始碼到 /usr/ports/distfiles

4.5.1. 安裝 Ports

下面我們會介紹如何使用 Ports 套件集來安裝、移除軟體的基本用法。 make 可用的目標及環境變數詳細說明可參閱 ports(7)

警告:

在編譯任何 Port 套件前,請先確認已經如前章節所敘述之方法更新 Ports 套件集。安裝任何第三方軟體皆可能會導致安全性漏洞,建議在安裝前先閱讀 http://vuxml.freebsd.org/ 了解 Port 已知的安全性問題。或者在每次安裝新 Port 前執行 pkg audit -F。此指令可以設定在每日系統安全性檢查時自動完成安全性稽查以及更新漏洞資料庫。要取得更多資訊,請參考 pkg-audit(8)periodic(8)

使用 Ports 套件集會假設您擁有可正常連線的網路,同時也會需要超級使用者的權限。

要編譯並安裝 Port,需切換目錄到要安裝的 Port 底下,然後輸入 make install,訊息中會顯示安裝的進度:

# cd /usr/ports/sysutils/lsof
# make install
>> lsof_4.88D.freebsd.tar.gz doesn't seem to exist in /usr/ports/distfiles/.
>> Attempting to fetch from ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/.
===>  Extracting for lsof-4.88
...
[extraction output snipped]
...
>> Checksum OK for lsof_4.88D.freebsd.tar.gz.
===>  Patching for lsof-4.88.d,8
===>  Applying FreeBSD patches for lsof-4.88.d,8
===>  Configuring for lsof-4.88.d,8
...
[configure output snipped]
...
===>  Building for lsof-4.88.d,8
...
[compilation output snipped]
...

===>  Installing for lsof-4.88.d,8
...
[installation output snipped]
...
===>   Generating temporary packing list
===>   Compressing manual pages for lsof-4.88.d,8
===>   Registering installation for lsof-4.88.d,8
===>  SECURITY NOTE:
      This port has installed the following binaries which execute with
      increased privileges.
/usr/local/sbin/lsof
#

lsof 是需要進階權限才有辦法執行的程式,因此當該程式安裝完成時會顯示安全性警告。一旦安裝完成便會顯示指令提示。

有些 Shell 會將 PATH 環境變數中所列目錄中可用的指令做快取,來增加在執行指這些指令時的查詢速度。tcsh Shell 的使用者應輸入 rehash 來讓新安裝的指令不須指定完整路徑便可使用。若在 sh Shell 則使用 hash -r。請參考 Shell 的說明文件以取得更多資訊。

安裝過程中會建立工作用的子目錄用來儲存編譯時暫存的檔案。可移除此目錄來節省磁碟空間並漸少往後升級新版 Port 時造成問題:

# make clean
===>  Cleaning for lsof-88.d,8
#

注意:

若想要少做這個額外的步驟,可以編譯 Port 時使用 make install clean

4.5.1.1. 自訂 Ports 安裝

部份 Ports 提供編譯選項,可用來開啟或關閉應用程式中的元件、安全選項、或其他允許自訂的項目。這類的應用程式例子包括 www/firefox, security/gpgme 以及 mail/sylpheed-claws。若 Port 相依的其他 Port 有可設定的選項時,預設的模式會提示使用者選擇選單中的選項,這可能會讓安裝的過程暫停讓使用者操作數次。要避免這個情況,可在 Port skeleton 中執行 make config-recursive 來一次設定所有選項。然後再執行 make install [clean] 編譯與安裝該 Port。

提示:

使用 config-recursive 時,會使用 all-depends-list Target 來收集所有要設定 Port 清單。建議執行 make config-recursive 直到所有相依的 Port 選項都已定義,直到 Ports 的選項畫面不會再出現,來確定所有相依的選項都已經設定。

有許多方式可以重新進入 Port 的編譯選項清單,以便在編譯 Port 之後加入、移除或更改這些選項。方法之一是 cd 進入含有 Port 的目錄並輸入 make config。還有另一個方法是使用 make showconfig。最後一個方法是執行 make rmconfig 來移除所有曾選擇過的選項,讓您能夠重新設定。這些方法在 ports(7) 中都有詳細的說明。

Ports 系統使用 fetch(1) 來下載檔案,它支援許多的環境變數可設定。若 FreeBSD 系統在防火牆或 FTP/HTTP 代理伺服器後面,可以設定 FTP_PASSIVE_MODE, FTP_PROXY 以及 FTP_PASSWORD 變數。請參考 fetch(3) 取得完整支援的變數清單。

對於那些無法一直連線到網際網路的使用者,可在 /usr/ports 下執行 make fetch 來下載所有的 distfiles,或是可在某個分類的目錄中,例如 /usr/ports/net,或指定的 Port Skeleton 中執行。要注意的是,若 Port 有任何的相依,在分類或 Ports Skeleton 中執行此指令並 不會 下載相依在其他分類的 Port distfiles。可使用 make fetch-recursive 來下載所有相依 Port 的 distfiles。

在部份少數情況,例如當公司或組織有自己的本地 distfiles 檔案庫,可使用 MASTER_SITES 變數來覆蓋在 Makefile 中指定的下載位址。當要指定替代的位址時可:

# cd /usr/ports/directory
# make MASTER_SITE_OVERRIDE= \
ftp://ftp.organization.org/pub/FreeBSD/ports/distfiles/ fetch

也可使用 WRKDIRPREFIXPREFIX 變數來覆蓋預設的工作及目標目錄。例如:

# make WRKDIRPREFIX=/usr/home/example/ports install

會編譯在 /usr/home/example/ports 的 Port 並安裝所有東西到 /usr/local 下。

# make PREFIX=/usr/home/example/local install

會編譯在 /usr/ports Port 並安裝到 /usr/home/example/local。然後:

# make WRKDIRPREFIX=../ports PREFIX=../local install

來同時設定工作及目標目錄。

這些變數也可做為環境變數設定,請參考您使用的 Shell 操作手冊來取得如何設定環境變數的說明。

4.5.2. 移除已安裝的 Ports

安裝的 Ports 可以使用 pkg delete 解除安裝。 使用這個指令的範例可以在 pkg-delete(8) 操作手冊找到。

或者,可在 Port 的目錄下執行 make deinstall

# cd /usr/ports/sysutils/lsof
make deinstall
===>  Deinstalling for sysutils/lsof
===>   Deinstalling
Deinstallation has been requested for the following 1 packages:

	lsof-4.88.d,8

The deinstallation will free 229 kB
[1/1] Deleting lsof-4.88.d,8... done

建議閱讀 Port 解除安裝後的訊息,若有任何相依該 Port 的應用程式,這些資訊會被顯示出來,但解除安裝的程序仍會繼續。在這種情況下最好重新安裝應用程式來避免破壞相依性。

4.5.3. 升級 Ports

隨著時間推移,Ports 套件集中會有新版的軟體可用。本節將說明如何檢查是否有可以升級的軟體及如何升級。

要檢查已安裝 Ports 是否有新版可用,請先確定已安裝最新版本的 Ports 樹,使用 過程 4.1, “Portsnap 方法”過程 4.2, “Subversion 方法” 中說明的指令來更新。在 FreeBSD 10 與更新的版本,或若套件系統已轉換為 pkg,可以使用下列指令列出已經安裝的 Ports 中有那些已過時:

# pkg version -l "<"

在 FreeBSD 9.X 與較舊的版本,可以使用下列指令列出已經安裝的 Ports 中有那些已過時:

# pkg_version -l "<"

重要:

在嘗試升級之前,請先從檔首閱讀 /usr/ports/UPDATING 來取得最近有那些 Ports 已升級或系統已安裝。這個檔案中會說明各種問題及在升級 Port 時可能會需要使用者執行的額外步驟,例如檔案格式更改、設定檔位置更改、或任何與先前版本不相容的問題。留意那些與您要升級 Ports 相關的指示,並依照這些指示執行升級。

要執行實際的升級,可使用 PortmasterPortupgrade

4.5.3.1. 使用 Portmaster 升級 Ports

ports-mgmt/portmaster 是可用來升級已安裝 Port 的小巧工具,它可不需要相依其他 Ports 或資料庫便可在 FreeBSD 使用,要使用 Port 安裝此工具可:

# cd /usr/ports/ports-mgmt/portmaster
# make install clean

Portmaster 將 Ports 定義成四種類型:

  • 根 Port:沒有相依且也不被任何其他 Ports 相依。

  • 主幹 Port:沒有相依,但被其他 Ports 相依。

  • 分支 Port:有相依,且其被其他 Ports 相依。

  • 枝 Port:有相依,但沒有被其他 Ports 相依。

要列出這幾個分類並搜尋是否有新版:

# portmaster -L
===>>> Root ports (No dependencies, not depended on)
===>>> ispell-3.2.06_18
===>>> screen-4.0.3
        ===>>> New version available: screen-4.0.3_1
===>>> tcpflow-0.21_1
===>>> 7 root ports
...
===>>> Branch ports (Have dependencies, are depended on)
===>>> apache22-2.2.3
        ===>>> New version available: apache22-2.2.8
...
===>>> Leaf ports (Have dependencies, not depended on)
===>>> automake-1.9.6_2
===>>> bash-3.1.17
        ===>>> New version available: bash-3.2.33
...
===>>> 32 leaf ports

===>>> 137 total installed ports
        ===>>> 83 have new versions available

此指令用來升級所有過時的 Port:

# portmaster -a

注意:

預設 Portmaster 會在刪除已存在的 Port 前備份套件,若成功安裝新版 Portmaster 會刪除該備份。使用 -b 來讓 Portmaster 不會自動刪除備份。加入 -i 可啟動 Portmaster 的互動模式,會在升級每個 Port 前提示訊息。尚有許多可用的其他選項,請閱讀 portmaster(8) 的操作手冊來取得詳細的用法。

若升級的過程發生錯誤,可加入 -f 來升級並重新編譯所有 Ports:

# portmaster -af

Portmaster 也可用來安裝新的 Ports 到系統,在編譯及安裝新 Port 前升級所有相依模組。要使用這個功能,要指定 Port 位於 Ports 套件集中的位置:

# portmaster shells/bash

4.5.3.2. 使用 Portupgrade 升級 Ports

另一個可以用來升級 Ports 的工具是 Portupgrade,可在 ports-mgmt/portupgrade 取得套件或 Ports,此工具會安裝一套可以用來管理 Ports 的應用程式,但是它需要相依 Ruby。要安裝該 Port:

# cd /usr/ports/ports-mgmt/portupgrade
# make install clean

在執行升級之前使用此工具,建議使用 pkgdb -F 掃描已安裝的 Ports 並修正該指令回報的所有資訊不一致的套件。

要升級所有安裝在系統上過時的 Ports,可使用 portupgrade -a,或者加上 -i 會在每個套件升級時詢問確認:

# portupgrade -ai

要升級指定的應用程式而非所有可用 Ports 可使用 portupgrade pkgname,非常重要的是,要加上 -R 來先升級指定應用程式所有相依的 Ports:

# portupgrade -R firefox

若使用 -PPortupgrade 會先在 PKG_PATH 清單中的本地目錄中搜尋可用的套件。若本地沒有可用的套件,則會從遠端下載。若套件無法在本地或遠端找到,Portupgrade 則會使用 Ports 來安裝。要避免完全使用 Ports 安裝,可使用 -PP,這個選項會告訴 Portupgrade 若沒有套件可用時放棄安裝:

# portupgrade -PP gnome3

若只想要下載 Port distfiles 或套件,使用 -P 參數。若不要編譯或安裝任何東西,使用 -F。請參考 portupgrade 的操作手冊來取得所有可用選項的更多資訊。

4.5.4. Ports 與磁碟空間

使用 Ports 套件集會隨著時間消耗磁碟空間。在編譯與安裝 Port 完之後,在 Ports Skeleton 中執行 make clean 可清除暫存的 work 目錄。若使用 Portmaster 來安裝 Port,則會自動移除該目錄,除非使用 -K。若有安裝 Portupgrade,此指令將會移除所有在 Ports 套件集的本地複本中找到的 work 目錄:

# portsclean -C

除此之外,許多過時的原始碼發行檔案會儲存在 /usr/ports/distfiles。若有安裝 Portupgrade,此指令將會刪除所有不再被任何 Ports 所引用的 distfiles:

# portsclean -D

要使用 Portupgrade 來移除所有未被任何安裝在系統上的 Port 所引用的 distfiles:

# portsclean -DD

若有安裝 Portmaster,則可使用:

# portmaster --clean-distfiles

預設這個指令會互動的方式詢問使用者確認是否要刪除 distfile。

除了以上指令外,ports-mgmt/pkg_cutleaves 套件或 Port 可自動移除不再需要使用的 Ports。

4.6. 使用 Poudriere 編譯套件

Poudriere 是一個使用 BSD 授權條款用來建立與測試 FreeBSD 套件的工具。它使用 FreeBSD Jail 來建置獨立的編譯環境,這些 Jail 可以用來編譯與目前所在系統不同 FreeBSD 版本的套件,也同樣可以在主機為 amd64 的系統上編譯供 i386 使用的套件。套件編譯完成後的目錄配置會與官方鏡像站完全相同。這些套件可由 pkg(8) 及其他套件管理工具使用。

Poudriere 可使用 ports-mgmt/poudriere 套件或 Ports 安裝。安裝完成後會有一個範例的設定檔 /usr/local/etc/poudriere.conf.sample。複製此檔案到 /usr/local/etc/poudriere.conf,編輯複製的檔案來配合本地的設定。

While ZFS is not required on the system running poudriere, it is beneficial. When ZFS is used, ZPOOL must be specified in /usr/local/etc/poudriere.conf and FREEBSD_HOST should be set to a nearby mirror. Defining CCACHE_DIR enables the use of devel/ccache to cache compilation and reduce build times for frequently-compiled code. It may be convenient to put poudriere datasets in an isolated tree mounted at /poudriere. Defaults for the other configuration values are adequate.

The number of processor cores detected is used to define how many builds should run in parallel. Supply enough virtual memory, either with RAM or swap space. If virtual memory runs out, compiling jails will stop and be torn down, resulting in weird error messages.

4.6.1. 初始化 Jails 與 Port 樹

After configuration, initialize poudriere so that it installs a jail with the required FreeBSD tree and a ports tree. Specify a name for the jail using -j and the FreeBSD version with -v. On systems running FreeBSD/amd64, the architecture can be set with -a to either i386 or amd64. The default is the architecture shown by uname.

# poudriere jail -c -j 10amd64 -v 10.0-RELEASE
====>> Creating 10amd64 fs... done
====>> Fetching base.txz for FreeBSD 10.0-RELEASE amd64
/poudriere/jails/10amd64/fromftp/base.txz      100% of   59 MB 1470 kBps 00m42s
====>> Extracting base.txz... done
====>> Fetching src.txz for FreeBSD 10.0-RELEASE amd64
/poudriere/jails/10amd64/fromftp/src.txz       100% of  107 MB 1476 kBps 01m14s
====>> Extracting src.txz... done
====>> Fetching games.txz for FreeBSD 10.0-RELEASE amd64
/poudriere/jails/10amd64/fromftp/games.txz     100% of  865 kB  734 kBps 00m01s
====>> Extracting games.txz... done
====>> Fetching lib32.txz for FreeBSD 10.0-RELEASE amd64
/poudriere/jails/10amd64/fromftp/lib32.txz     100% of   14 MB 1316 kBps 00m12s
====>> Extracting lib32.txz... done
====>> Cleaning up... done
====>> Jail 10amd64 10.0-RELEASE amd64 is ready to be used
# poudriere ports -c -p local
====>> Creating local fs... done
====>> Extracting portstree "local"...
Looking up portsnap.FreeBSD.org mirrors... 7 mirrors found.
Fetching public key from ec2-eu-west-1.portsnap.freebsd.org... done.
Fetching snapshot tag from ec2-eu-west-1.portsnap.freebsd.org... done.
Fetching snapshot metadata... done.
Fetching snapshot generated at Tue Feb 11 01:07:15 CET 2014:
94a3431f0ce567f6452ffde4fd3d7d3c6e1da143efec76100% of   69 MB 1246 kBps 00m57s
Extracting snapshot... done.
Verifying snapshot integrity... done.
Fetching snapshot tag from ec2-eu-west-1.portsnap.freebsd.org... done.
Fetching snapshot metadata... done.
Updating from Tue Feb 11 01:07:15 CET 2014 to Tue Feb 11 16:05:20 CET 2014.
Fetching 4 metadata patches... done.
Applying metadata patches... done.
Fetching 0 metadata files... done.
Fetching 48 patches.
(48/48) 100.00%  done.
done.
Applying patches...
done.
Fetching 1 new ports or files... done.
/poudriere/ports/tester/CHANGES
/poudriere/ports/tester/COPYRIGHT

[...]

Building new INDEX files... done.

On a single computer, poudriere can build ports with multiple configurations, in multiple jails, and from different port trees. Custom configurations for these combinations are called sets. See the CUSTOMIZATION section of poudriere(8) for details after ports-mgmt/poudriere or ports-mgmt/poudriere-devel is installed.

The basic configuration shown here puts a single jail-, port-, and set-specific make.conf in /usr/local/etc/poudriere.d. The filename in this example is created by combining the jail name, port name, and set name: 10amd64-local-workstation-make.conf. The system make.conf and this new file are combined at build time to create the make.conf used by the build jail.

Packages to be built are entered in 10amd64-local-workstation-pkglist:

editors/emacs
devel/git
ports-mgmt/pkg
...

Options and dependencies for the specified ports are configured:

# poudriere options -j 10amd64 -p local -z workstation -f 10amd64-local-workstation-pkglist

Finally, packages are built and a package repository is created:

# poudriere bulk -j 10amd64 -p local -z workstation -f 10amd64-local-workstation-pkglist

Ctrl+t displays the current state of the build. Poudriere also builds files in /poudriere/logs/bulk/jailname that can be used with a web server to display build information.

Packages are now available for installation from the poudriere repository.

For more information on using poudriere, see poudriere(8) and the main web site, https://github.com/freebsd/poudriere/wiki.

4.6.2. 設定 pkg 客戶端使用 Poudriere 檔案庫

While it is possible to use both a custom repository along side of the official repository, sometimes it is useful to disable the official repository. This is done by creating a configuration file that overrides and disables the official configuration file. Create /usr/local/etc/pkg/repos/FreeBSD.conf that contains the following:

FreeBSD: {
	enabled: no
}

Usually it is easiest to serve a poudriere repository to the client machines via HTTP. Setup a webserver to serve up the package directory, usually something like: /usr/local/poudriere/data/packages/10amd64. Where 10amd64 is the name of the build.

If the URL to the package repository is: http://pkg.example.com/10amd64, then the repository configuration file in /usr/local/etc/pkg/repos/custom.conf would look like:

custom: {
	url: "http://pkg.example.com/10amd64",
	enabled: yes,
}

4.7. 安裝後的注意事項

不論軟體是從套件或 Port 安裝,大部份的第三方應用程式安裝完後需要做某種程度的設定,下列指令與位置可以用來協助找到應用程式安裝了什麼。

  • 大部份應用程式安裝會在 /usr/local/etc 安裝至少一個預設的設定檔,在應用程式有大量設定檔的情況會建立一個子目錄來存放這些設定檔。範例的設定檔名通常會使用 .sample 結尾,應要檢查這些檔案的內容,並可能要做一些編輯讓設定檔符合系統的需求,要編輯設定檔範本前需先複製該檔案並去除 .sample 副檔名。

  • 應用程式提供的文件會安裝到 /usr/local/share/doc,且許多應用程式也同時會安裝操作手冊,在繼續使用應用程式前應先查看這些文件。

  • 部份應用程式會以服務的方式執行,在啟動應用程式前前需要加入設定到 /etc/rc.conf。這些應用程式通常會安裝啟動 Script 到 /usr/local/etc/rc.d,請參考 啟動服務 來取得更多資訊。

  • csh(1) 的使用者應要執行 rehash 來更新已知 Binary 清單到 Shell 的 PATH

  • 使用 pkg info 來了解應用程式安裝了那些檔案、操作手冊以及 Binary。

4.8. 處理損壞的 Ports

當發現某個 Port 無法順利編譯或安裝,可以嘗試以下幾種方法解決:

  1. 搜尋 問題回報資料庫 看該 Port 有沒有待審核的修正,若有的話可以使用該修正來修正問題。

  2. 尋求維護人員的協助,在 Ports Skeleton 目錄中輸入 make maintainer 或閱讀 Port 的 Makefile 來取得維護人員的電子郵件位址。寄給維護人員的郵件內容請記得要包含 Port 的 Makefile 中的 $FreeBSD: 一整行及輸出的錯誤訊息。

    注意:

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

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

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

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

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

章 5. X Window 系統

5.1. 概述

使用 bsdinstall 安裝 FreeBSD 並不會自動安裝圖型化使用者介面。本章將說明如何安裝並設定 Xorg,該應用程式提供開放源碼的 X Window 系統來提供圖型化環境。接著會說明如何找到並安裝桌面環境或視窗管理程式。

注意:

偏好安裝時會自動設定 Xorg 並且在安裝過程提供視窗管理程式選項的使用者請參考 pcbsd.org 網站。

更多有關 Xorg 支援影像硬體資訊,請參考 x.org 網站。

讀完這章,您將了解︰

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

  • 如何安裝並設定 Xorg

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

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

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

在開始閱讀這章之前,您需要︰

5.2. 術語

雖然 X 各元件的所有細節及運作方式,並不是必須要知道的。 但對它們有些基本概念會更容易上手。

X 伺服器(X Server)

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

X 客戶端(X Client)

每個 X 應用程式,如 XTermFirefox 都是 客戶端。 客戶端會傳訊息到伺服器,例如:請在這些座標畫一個視窗,接著伺服器會傳回訊息,如:使用者剛點選了確定按鈕

在家庭或小型辦公室環境,通常 X 伺服器跟 X 客戶端都是在同一台電腦上執行。也可以在比較慢的電腦上執行 X 伺服器, 並在比較強、比較貴的系統上執行 X 應用程式。 在這種情景,X 客戶端與伺服器之間的溝通就需透過網路來進行。

視窗管理程式(Window Manager)

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

每個視窗管理程式也各有其不同的設定機制,有些需要手動修改設定檔, 而有的則可透過圖型化工具來完成大部分的設定工作。

桌面環境(Desktop Environment)

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

聚焦政策(Focus Policy)

視窗管理程式負責滑鼠指標的聚焦政策。 聚焦政策指的是如何決定使用中及接收鍵盤輸入的視窗。

通常較為人熟悉的聚焦政策叫做 click-to-focus,這個模式中,滑鼠點選到的視窗便會處於作用中(Active)的狀態。在 focus-follows-mouse 模式滑鼠指標所在的視窗便是作用中的視窗,只要把滑鼠移到其他視窗就可以改變作用中的視窗,若滑鼠移到根視窗(Root Window),則會聚焦在根視窗。在 sloppy-focus 模式,既使滑鼠移到根視窗,仍然會聚焦在最後聚焦的視窗上,此模式只有當滑鼠進入新的視窗時才會聚焦於該視窗,而非離開目前視窗時。click-to-focus 模式用滑鼠點擊來決定作用中的視窗,且該視窗會被置頂到所有其他視窗之前,即使滑鼠移到其他視窗,所有的鍵盤輸入仍會由該視窗所接收。

不同的視窗管理程式支援不同的聚焦模式,全部都支援 click-to-focus 且其中大部份支援其他模式,請查看視窗管理程式的說明文件來了解可用的聚焦模式。

視窗元件(Widget)

視窗元件指的是在所有在使用者介面上可被點選或操作的項目,這包括按鈕、核選方塊、單選按鈕、圖示及清單。 視窗元件工具包(Widget toolkit)是指用來建立圖型化應用程式的一系列的視窗元件。目前有數個有名的視窗元件工具包,包含 KDE 所使用的 Qt、GNOME 所使用的 GTK+。 因此應用程式會依其開發時所選用的視窗元件工具包而有不同的外觀。

5.3. 安裝 Xorg

On FreeBSD, Xorg can be installed as a package or port.

To build and install from the Ports Collection:

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

The binary package can be installed more quickly but with fewer options for customization:

# pkg install xorg

Either of these installations results in the complete Xorg system being installed. This is the best option for most users.

A smaller version of the X system suitable for experienced users is available in x11/xorg-minimal. Most of the documents, libraries, and applications will not be installed. Some applications require these additional components to function.

5.4. Xorg 設定

Warren Block

5.4.1. 快速開始

Xorg supports most common video cards, keyboards, and pointing devices. These devices are automatically detected and do not require any manual configuration.

  1. If Xorg has been used on this computer before, move or remove any existing configuration files:

    # mv /etc/X11/xorg.conf ~/xorg.conf.etc
    # mv /usr/local/etc/X11/xorg.conf ~/xorg.conf.localetc
  2. Add the user who will run Xorg to the video or wheel group to enable 3D acceleration when available. To add user jru to whichever group is available:

    # pw groupmod video -m jru || pw groupmod wheel -m jru
  3. The TWM window manager is included by default. It is started when Xorg starts:

    % startx
  4. On some older versions of FreeBSD, the system console must be set to vt(4) before switching back to the text console will work properly. See 節 5.4.3, “核心模式設定 (Kernel Mode Setting, KMS)”.

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

Access to /dev/dri is needed to allow 3D acceleration on video cards. It is usually simplest to add the user who will be running X to either the video or wheel group. Here, pw(8) is used to add user slurms to the video group, or to the wheel group if there is no video group:

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

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

When the computer switches from displaying the console to a higher screen resolution for X, it must set the video output mode. Recent versions of Xorg use a system inside the kernel to do these mode changes more efficiently. Older versions of FreeBSD use sc(4), which is not aware of the KMS system. The end result is that after closing X, the system console is blank, even though it is still working. The newer vt(4) console avoids this problem.

Add this line to /boot/loader.conf to enable vt(4):

kern.vty=vt

5.4.4. 設定檔

5.4.4.1. 目錄

Xorg looks in several directories for configuration files. /usr/local/etc/X11/ is the recommended directory for these files on FreeBSD. Using this directory helps keep application files separate from operating system files.

Storing configuration files in the legacy /etc/X11/ still works. However, this mixes application files with the base FreeBSD files and is not recommended.

5.4.4.2. 單檔或多檔

It is easier to use multiple files that each configure a specific setting than the traditional single xorg.conf. These files are stored in the xorg.conf.d/ subdirectory of the main configuration file directory. The full path is typically /usr/local/etc/X11/xorg.conf.d/.

Examples of these files are shown later in this section.

The traditional single xorg.conf still works, but is neither as clear nor as flexible as multiple files in the xorg.conf.d/ subdirectory.

5.4.5. 顯示卡

Intel®

3D acceleration is supported on most Intel® graphics up to Ivy Bridge (HD Graphics 2500, 4000, and P4000), including Iron Lake (HD Graphics) and Sandy Bridge (HD Graphics 2000).

Driver name: intel

For reference, see https://en.wikipedia.org/wiki/List_of_Intel_graphics_processing_units.

AMD® Radeon

2D and 3D acceleration is supported on Radeon cards up to and including the HD6000 series.

Driver name: radeon

For reference, see https://en.wikipedia.org/wiki/List_of_AMD_graphics_processing_units.

NVIDIA

Several NVIDIA drivers are available in the x11 category of the Ports Collection. Install the driver that matches the video card.

For reference, see https://en.wikipedia.org/wiki/List_of_Nvidia_graphics_processing_units.

Hybrid Combination Graphics

Some notebook computers add additional graphics processing units to those built into the chipset or processor. Optimus combines Intel® and NVIDIA hardware. Switchable Graphics or Hybrid Graphics are a combination of an Intel® or AMD® processor and an AMD® Radeon GPU.

Implementations of these hybrid graphics systems vary, and Xorg on FreeBSD is not able to drive all versions of them.

Some computers provide a BIOS option to disable one of the graphics adapters or select a discrete mode which can be used with one of the standard video card drivers. For example, it is sometimes possible to disable the NVIDIA GPU in an Optimus system. The Intel® video can then be used with an Intel® driver.

BIOS settings depend on the model of computer. In some situations, both GPUs can be left enabled, but creating a configuration file that only uses the main GPU in the Device section is enough to make such a system functional.

Other Video Cards

Drivers for some less-common video cards can be found in the x11-drivers directory of the Ports Collection.

Cards that are not supported by a specific driver might still be usable with the x11-drivers/xf86-video-vesa driver. This driver is installed by x11/xorg. It can also be installed manually as x11-drivers/xf86-video-vesa. Xorg attempts to use this driver when a specific driver is not found for the video card.

x11-drivers/xf86-video-scfb is a similar nonspecialized video driver that works on many UEFI and ARM® computers.

Setting the Video Driver in a File

To set the Intel® driver in a configuration file:

範例 5.1. 在單檔中選擇 Intel® 影像驅動程式

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

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

If more than one video card is present, the BusID identifier can be uncommented and set to select the desired card. A list of video card bus IDs can be displayed with pciconf -lv | grep -B3 display.


To set the Radeon driver in a configuration file:

範例 5.2. 在單檔中選擇 Radeon 影像驅動程式

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

Section "Device"
	Identifier "Card0"
	Driver     "radeon"
EndSection

To set the VESA driver in a configuration file:

範例 5.3. 在單檔中選擇 VESA 影像驅動程式

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

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

To set the scfb driver for use with a UEFI or ARM® computer:

範例 5.4. 在單檔中選擇 scfb 影像驅動程式

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

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

5.4.6. 顯示器

Almost all monitors support the Extended Display Identification Data standard (EDID). Xorg uses EDID to communicate with the monitor and detect the supported resolutions and refresh rates. Then it selects the most appropriate combination of settings to use with that monitor.

Other resolutions supported by the monitor can be chosen by setting the desired resolution in configuration files, or after the X server has been started with xrandr(1).

Using xrandr(1)

Run xrandr(1) without any parameters to see a list of video outputs and detected monitor modes:

% 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)

This shows that the DVI-0 output is being used to display a screen resolution of 1920x1200 pixels at a refresh rate of about 60 Hz. Monitors are not attached to the DisplayPort-0 and HDMI-0 connectors.

Any of the other display modes can be selected with xrandr(1). For example, to switch to 1280x1024 at 60 Hz:

% xrandr --mode 1280x1024 --rate 60

A common task is using the external video output on a notebook computer for a video projector.

The type and quantity of output connectors varies between devices, and the name given to each output varies from driver to driver. What one driver calls HDMI-1, another might call HDMI1. So the first step is to run xrandr(1) to list all the available outputs:

% 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)

Four outputs were found: the built-in panel LVDS1, and external VGA1, HDMI1, and DP1 connectors.

The projector has been connected to the VGA1 output. xrandr(1) is now used to set that output to the native resolution of the projector and add the additional space to the right side of the desktop:

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

--auto chooses the resolution and refresh rate detected by EDID. If the resolution is not correctly detected, a fixed value can be given with --mode instead of the --auto statement. For example, most projectors can be used with a 1024x768 resolution, which is set with --mode 1024x768.

xrandr(1) is often run from .xinitrc to set the appropriate mode when X starts.

Setting Monitor Resolution in a File

To set a screen resolution of 1024x768 in a configuration file:

範例 5.5. 在單檔中設定螢幕解析度

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

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

The few monitors that do not have EDID can be configured by setting HorizSync and VertRefresh to the range of frequencies supported by the monitor.

範例 5.6. 手動設定顯示器頻率

/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. 鍵盤

Keyboard Layout

The standardized location of keys on a keyboard is called a layout. Layouts and other adjustable parameters are listed in xkeyboard-config(7).

A United States layout is the default. To select an alternate layout, set the XkbLayout and XkbVariant options in an InputClass. This will be applied to all input devices that match the class.

This example selects a French keyboard layout with the oss variant.

範例 5.7. 設定鍵盤配置

/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

範例 5.8. 設定多個鍵盤配置

Set United States, Spanish, and Ukrainian keyboard layouts. Cycle through these layouts by pressing Alt+Shift. x11/xxkb or x11/sbxkb can be used for improved layout switching control and current layout indicators.

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

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

Closing Xorg From the Keyboard

X can be closed with a combination of keys. By default, that key combination is not set because it conflicts with keyboard commands for some applications. Enabling this option requires changes to the keyboard InputDevice section:

範例 5.9. 開啟鍵盤離開 X 功能

/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. 滑鼠與指標裝置

Many mouse parameters can be adjusted with configuration options. See mousedrv(4) for a full list.

Mouse Buttons

The number of buttons on a mouse can be set in the mouse InputDevice section of xorg.conf. To set the number of buttons to 7:

範例 5.10. 設定滑鼠按鍵編號

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

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

5.4.8. 手動設定

In some cases, Xorg autoconfiguration does not work with particular hardware, or a different configuration is desired. For these cases, a custom configuration file can be created.

A configuration file can be generated by Xorg based on the detected hardware. This file is often a useful starting point for custom configurations.

Generating an xorg.conf:

# Xorg -configure

The configuration file is saved to /root/xorg.conf.new. Make any changes desired, then test that file with:

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

After the new configuration has been adjusted and tested, it can be split into smaller files in the normal location, /usr/local/etc/X11/xorg.conf.d/.

5.5. 在 Xorg 使用字型

5.5.1. Type1 字型

The default fonts that ship with Xorg are less than ideal for typical desktop publishing applications. Large presentation fonts show up jagged and unprofessional looking, and small fonts are almost completely unintelligible. However, there are several free, high quality Type1 (PostScript®) fonts available which can be readily used with Xorg. For instance, the URW font collection (x11-fonts/urwfonts) includes high quality versions of standard type1 fonts (Times Roman®, Helvetica®, Palatino® and others). The Freefonts collection (x11-fonts/freefonts) includes many more fonts, but most of them are intended for use in graphics software such as the Gimp, and are not complete enough to serve as screen fonts. In addition, Xorg can be configured to use TrueType® fonts with a minimum of effort. For more details on this, see the X(7) manual page or 節 5.5.2, “TrueType® 字型”.

To install the above Type1 font collections from the Ports Collection, run the following commands:

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

And likewise with the freefont or other collections. To have the X server detect these fonts, add an appropriate line to the X server configuration file (/etc/X11/xorg.conf), which reads:

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

Alternatively, at the command line in the X session run:

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

This will work but will be lost when the X session is closed, unless it is added to the startup file (~/.xinitrc for a normal startx session, or ~/.xsession when logging in through a graphical login manager like XDM). A third way is to use the new /usr/local/etc/fonts/local.conf as demonstrated in 節 5.5.3, “反鋸齒字型”.

5.5.2. TrueType® 字型

Xorg has built in support for rendering TrueType® fonts. There are two different modules that can enable this functionality. The freetype module is used in this example because it is more consistent with the other font rendering back-ends. To enable the freetype module just add the following line to the "Module" section of /etc/X11/xorg.conf.

Load  "freetype"

Now make a directory for the TrueType® fonts (for example, /usr/local/share/fonts/TrueType) and copy all of the TrueType® fonts into this directory. Keep in mind that TrueType® fonts cannot be directly taken from an Apple® Mac®; they must be in UNIX®/MS-DOS®/Windows® format for use by Xorg. Once the files have been copied into this directory, use mkfontdir to create a fonts.dir, so that the X font renderer knows that these new files have been installed. mkfontdir can be installed as a package:

# pkg install mkfontdir

Then create an index of X font files in a directory:

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

Now add the TrueType® directory to the font path. This is just the same as described in 節 5.5.1, “Type1 字型”:

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

or add a FontPath line to xorg.conf.

Now Gimp, Apache OpenOffice, and all of the other X applications should now recognize the installed TrueType® fonts. Extremely small fonts (as with text in a high resolution display on a web page) and extremely large fonts (within StarOffice) will look much better now.

5.5.3. 反鋸齒字型

All fonts in Xorg that are found in /usr/local/share/fonts/ and ~/.fonts/ are automatically made available for anti-aliasing to Xft-aware applications. Most recent applications are Xft-aware, including KDE, GNOME, and Firefox.

In order to control which fonts are anti-aliased, or to configure anti-aliasing properties, create (or edit, if it already exists) the file /usr/local/etc/fonts/local.conf. Several advanced features of the Xft font system can be tuned using this file; this section describes only some simple possibilities. For more details, please see fonts-conf(5).

This file must be in XML format. Pay careful attention to case, and make sure all tags are properly closed. The file begins with the usual XML header followed by a DOCTYPE definition, and then the <fontconfig> tag:

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

As previously stated, all fonts in /usr/local/share/fonts/ as well as ~/.fonts/ are already made available to Xft-aware applications. If you wish to add another directory outside of these two directory trees, add a line similar to the following to /usr/local/etc/fonts/local.conf:

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

After adding new fonts, and especially new font directories, you should run the following command to rebuild the font caches:

# fc-cache -f

Anti-aliasing makes borders slightly fuzzy, which makes very small text more readable and removes staircases from large text, but can cause eyestrain if applied to normal text. To exclude font sizes smaller than 14 point from anti-aliasing, include these lines:

        <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>

Spacing for some monospaced fonts may also be inappropriate with anti-aliasing. This seems to be an issue with KDE, in particular. One possible fix for this is to force the spacing for such fonts to be 100. Add the following lines:

       <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>

(this aliases the other common names for fixed fonts as "mono"), and then add:

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

Certain fonts, such as Helvetica, may have a problem when anti-aliased. Usually this manifests itself as a font that seems cut in half vertically. At worst, it may cause applications to crash. To avoid this, consider adding the following to local.conf:

         <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>        

Once you have finished editing local.conf make sure you end the file with the </fontconfig> tag. Not doing this will cause your changes to be ignored.

Finally, users can add their own settings via their personal .fonts.conf files. To do this, each user should simply create a ~/.fonts.conf. This file must also be in XML format.

One last point: with an LCD screen, sub-pixel sampling may be desired. This basically treats the (horizontally separated) red, green and blue components separately to improve the horizontal resolution; the results can be dramatic. To enable this, add the line somewhere in local.conf:

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

注意:

Depending on the sort of display, rgb may need to be changed to bgr, vrgb or vbgr: experiment and see which works best.

5.6. X 顯示管理程式

Contributed by Seth Kingsley.

Xorg provides an X Display Manager, XDM, which can be used for login session management. XDM provides a graphical interface for choosing which display server to connect to and for entering authorization information such as a login and password combination.

This section demonstrates how to configure the X Display Manager on FreeBSD. Some desktop environments provide their own graphical login manager. Refer to 節 5.7.1, “GNOME” for instructions on how to configure the GNOME Display Manager and 節 5.7.2, “KDE” for instructions on how to configure the KDE Display Manager.

5.6.1. 設定 XDM

To install XDM, use the x11/xdm package or port. Once installed, XDM can be configured to run when the machine boots up by editing this entry in /etc/ttys:

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

Change the off to on and save the edit. The ttyv8 in this entry indicates that XDM will run on the ninth virtual terminal.

The XDM configuration directory is located in /usr/local/lib/X11/xdm. This directory contains several files used to change the behavior and appearance of XDM, as well as a few scripts and programs used to set up the desktop when XDM is running. 表格 5.1, “XDM 設定檔” summarizes the function of each of these files. The exact syntax and usage of these files is described in xdm(1).

表格 5.1. XDM 設定檔
檔案說明
XaccessThe protocol for connecting to XDM is called the X Display Manager Connection Protocol (XDMCP) This file is a client authorization ruleset for controlling XDMCP connections from remote machines. By default, this file does not allow any remote clients to connect.
XresourcesThis file controls the look and feel of the XDM display chooser and login screens. The default configuration is a simple rectangular login window with the hostname of the machine displayed at the top in a large font and Login: and Password: prompts below. The format of this file is identical to the app-defaults file described in the Xorg documentation.
XserversThe list of local and remote displays the chooser should provide as login choices.
XsessionDefault session script for logins which is run by XDM after a user has logged in. Normally each user will have a customized session script in ~/.xsession that overrides this script
Xsetup_*Script to automatically launch applications before displaying the chooser or login interfaces. There is a script for each display being used, named Xsetup_*, where * is the local display number. Typically these scripts run one or two programs in the background such as xconsole.
xdm-configGlobal configuration for all displays running on this machine.
xdm-errorsContains errors generated by the server program. If a display that XDM is trying to start hangs, look at this file for error messages. These messages are also written to the user's ~/.xsession-errors on a per-session basis.
xdm-pidThe running process ID of XDM.

5.6.2. 設定遠端存取

By default, only users on the same system can login using XDM. To enable users on other systems to connect to the display server, edit the access control rules and enable the connection listener.

To configure XDM to listen for any remote connection, comment out the DisplayManager.requestPort line in /usr/local/lib/X11/xdm/xdm-config by putting a ! in front of it:

! 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

Save the edits and restart XDM. To restrict remote access, look at the example entries in /usr/local/lib/X11/xdm/Xaccess and refer to xdm(1) for further information.

5.7. 桌面環境

Contributed by Valentino Vaschetto.

This section describes how to install three popular desktop environments on a FreeBSD system. A desktop environment can range from a simple window manager to a complete suite of desktop applications. Over a hundred desktop environments are available in the x11-wm category of the Ports Collection.

5.7.1. GNOME

GNOME is a user-friendly desktop environment. It includes a panel for starting applications and displaying status, a desktop, a set of tools and applications, and a set of conventions that make it easy for applications to cooperate and be consistent with each other. More information regarding GNOME on FreeBSD can be found at http://www.FreeBSD.org/gnome. That web site contains additional documentation about installing, configuring, and managing GNOME on FreeBSD.

This desktop environment can be installed from a package:

# pkg install gnome3

To instead build GNOME from ports, use the following command. GNOME is a large application and will take some time to compile, even on a fast computer.

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

GNOME requires /proc to be mounted. Add this line to /etc/fstab to mount this file system automatically during system startup:

proc           /proc       procfs  rw  0   0

GNOME uses D-Bus and HAL for a message bus and hardware abstraction. These applications are automatically installed as dependencies of GNOME. Enable them in /etc/rc.conf so they will be started when the system boots:

dbus_enable="YES"
hald_enable="YES"

After installation, configure Xorg to start GNOME. The easiest way to do this is to enable the GNOME Display Manager, GDM, which is installed as part of the GNOME package or port. It can be enabled by adding this line to /etc/rc.conf:

gdm_enable="YES"

It is often desirable to also start all GNOME services. To achieve this, add a second line to /etc/rc.conf:

gnome_enable="YES"

GDM will start automatically when the system boots.

A second method for starting GNOME is to type startx from the command-line after configuring ~/.xinitrc. If this file already exists, replace the line that starts the current window manager with one that starts /usr/local/bin/gnome-session. If this file does not exist, create it with this command:

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

A third method is to use XDM as the display manager. In this case, create an executable ~/.xsession:

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

5.7.2. KDE

KDE is another easy-to-use desktop environment. This desktop provides a suite of applications with a consistent look and feel, a standardized menu and toolbars, keybindings, color-schemes, internationalization, and a centralized, dialog-driven desktop configuration. More information on KDE can be found at http://www.kde.org/. For FreeBSD-specific information, consult http://freebsd.kde.org.

To install the KDE package, type:

# pkg install x11/kde4

To instead build the KDE port, use the following command. Installing the port will provide a menu for selecting which components to install. KDE is a large application and will take some time to compile, even on a fast computer.

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

KDE requires /proc to be mounted. Add this line to /etc/fstab to mount this file system automatically during system startup:

proc           /proc       procfs  rw  0   0

KDE uses D-Bus and HAL for a message bus and hardware abstraction. These applications are automatically installed as dependencies of KDE. Enable them in /etc/rc.conf so they will be started when the system boots:

dbus_enable="YES"
hald_enable="YES"

The installation of KDE includes the KDE Display Manager, KDM. To enable this display manager, add this line to /etc/rc.conf:

kdm4_enable="YES"

A second method for launching KDE is to type startx from the command line. For this to work, the following line is needed in ~/.xinitrc:

exec /usr/local/bin/startkde

A third method for starting KDE is through XDM. To do so, create an executable ~/.xsession as follows:

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

Once KDE is started, refer to its built-in help system for more information on how to use its various menus and applications.

5.7.3. Xfce

Xfce is a desktop environment based on the GTK+ toolkit used by GNOME. However, it is more lightweight and provides a simple, efficient, easy-to-use desktop. It is fully configurable, has a main panel with menus, applets, and application launchers, provides a file manager and sound manager, and is themeable. Since it is fast, light, and efficient, it is ideal for older or slower machines with memory limitations. More information on Xfce can be found at http://www.xfce.org.

To install the Xfce package:

# pkg install xfce

Alternatively, to build the port:

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

Unlike GNOME or KDE, Xfce does not provide its own login manager. In order to start Xfce from the command line by typing startx, first add its entry to ~/.xinitrc:

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

An alternate method is to use XDM. To configure this method, create an executable ~/.xsession:

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

5.8. 安裝 Compiz Fusion

One way to make using a desktop computer more pleasant is with nice 3D effects.

Installing the Compiz Fusion package is easy, but configuring it requires a few steps that are not described in the port's documentation.

5.8.1. 設定 FreeBSD nVidia 驅動程式

Desktop effects can cause quite a load on the graphics card. For an nVidia-based graphics card, the proprietary driver is required for good performance. Users of other graphics cards can skip this section and continue with the xorg.conf configuration.

To determine which nVidia driver is needed see the FAQ question on the subject.

Having determined the correct driver to use for your card, installation is as simple as installing any other package.

For example, to install the latest driver:

# pkg install x11/nvidia-driver

The driver will create a kernel module, which needs to be loaded at system startup. Add the following line to /boot/loader.conf:

nvidia_load="YES"

注意:

To immediately load the kernel module into the running kernel by issuing a command like kldload nvidia, however it has been noted that the some versions of Xorg will not function properly if the driver is not loaded at boot time. After editing /boot/loader.conf, a reboot is recommended.

With the kernel module loaded, you normally only need to change a single line in xorg.conf to enable the proprietary driver:

Find the following line in /etc/X11/xorg.conf:

Driver      "nv"

and change it to:

Driver      "nvidia"

Start the GUI as usual, and you should be greeted by the nVidia splash. Everything should work as usual.

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

To enable Compiz Fusion, /etc/X11/xorg.conf needs to be modified:

Add the following section to enable composite effects:

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

Locate the Screen section which should look similar to the one below:

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

and add the following two lines (after Monitor will do):

DefaultDepth    24
Option         "AddARGBGLXVisuals" "True"

Locate the Subsection that refers to the screen resolution that you wish to use. For example, if you wish to use 1280x1024, locate the section that follows. If the desired resolution does not appear in any subsection, you may add the relevant entry by hand:

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

A color depth of 24 bits is needed for desktop composition, change the above subsection to:

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

Finally, confirm that the glx and extmod modules are loaded in the Module section:

Section "Module"
    Load           "extmod"
    Load           "glx"
    ...

The preceding can be done automatically with x11/nvidia-xconfig by running (as root):

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

5.8.3. 安裝與設定 Compiz Fusion

Installing Compiz Fusion is as simple as any other package:

# pkg install x11-wm/compiz-fusion

When the installation is finished, start your graphic desktop and at a terminal, enter the following commands (as a normal user):

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

Your screen will flicker for a few seconds, as your window manager (e.g. Metacity if you are using GNOME) is replaced by Compiz Fusion. Emerald takes care of the window decorations (i.e. close, minimize, maximize buttons, title bars and so on).

You may convert this to a trivial script and have it run at startup automatically (e.g. by adding to Sessions in a GNOME desktop):

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

Save this in your home directory as, for example, start-compiz and make it executable:

% chmod +x ~/start-compiz

Then use the GUI to add it to Startup Programs (located in System, Preferences, Sessions on a GNOME desktop).

To actually select all the desired effects and their settings, execute (again as a normal user) the Compiz Config Settings Manager:

% ccsm

注意:

In GNOME, this can also be found in the System, Preferences menu.

If you have selected gconf support during the build, you will also be able to view these settings using gconf-editor under apps/compiz.

5.9. 疑難排解

If the mouse does not work, you will need to first configure it before proceeding. In recent Xorg versions, the InputDevice sections in xorg.conf are ignored in favor of the autodetected devices. To restore the old behavior, add the following line to the ServerLayout or ServerFlags section of this file:

Option "AutoAddDevices" "false"

Input devices may then be configured as in previous versions, along with any other options needed (e.g., keyboard layout switching).

注意:

As previously explained the hald daemon will, by default, automatically detect your keyboard. There are chances that your keyboard layout or model will not be correct, desktop environments like GNOME, KDE or Xfce provide tools to configure the keyboard. However, it is possible to set the keyboard properties directly either with the help of the setxkbmap(1) utility or with a hald's configuration rule.

For example if, one wants to use a PC 102 keys keyboard coming with a french layout, we have to create a keyboard configuration file for hald called x11-input.fdi and saved in the /usr/local/etc/hal/fdi/policy directory. This file should contain the following lines:

<?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>

If this file already exists, just copy and add to your file the lines regarding the keyboard configuration.

You will have to reboot your machine to force hald to read this file.

It is possible to do the same configuration from an X terminal or a script with this command line:

% setxkbmap -model pc102 -layout fr

/usr/local/share/X11/xkb/rules/base.lst lists the various keyboard, layouts and options available.

The xorg.conf.new configuration file may now be tuned to taste. Open the file in a text editor such as emacs(1) or ee(1). If the monitor is an older or unusual model that does not support autodetection of sync frequencies, those settings can be added to xorg.conf.new under the "Monitor" section:

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

Most monitors support sync frequency autodetection, making manual entry of these values unnecessary. For the few monitors that do not support autodetection, avoid potential damage by only entering values provided by the manufacturer.

X allows DPMS (Energy Star) features to be used with capable monitors. The xset(1) program controls the time-outs and can force standby, suspend, or off modes. If you wish to enable DPMS features for your monitor, you must add the following line to the monitor section:

Option       "DPMS"

While the xorg.conf.new configuration file is still open in an editor, select the default resolution and color depth desired. This is defined in the "Screen" section:

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

The DefaultDepth keyword describes the color depth to run at by default. This can be overridden with the -depth command line switch to Xorg(1). The Modes keyword describes the resolution to run at for the given color depth. Note that only VESA standard modes are supported as defined by the target system's graphics hardware. In the example above, the default color depth is twenty-four bits per pixel. At this color depth, the accepted resolution is 1024 by 768 pixels.

Finally, write the configuration file and test it using the test mode given above.

注意:

One of the tools available to assist you during troubleshooting process are the Xorg log files, which contain information on each device that the Xorg server attaches to. Xorg log file names are in the format of /var/log/Xorg.0.log. The exact name of the log can vary from Xorg.0.log to Xorg.8.log and so forth.

If all is well, the configuration file needs to be installed in a common location where Xorg(1) can find it. This is typically /etc/X11/xorg.conf or /usr/local/etc/X11/xorg.conf.

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

The Xorg configuration process is now complete. Xorg may be now started with the startx(1) utility. The Xorg server may also be started with the use of xdm(1).

5.9.1. 設定 Intel® i810 繪圖晶片組

Configuration with Intel® i810 integrated chipsets requires the agpgart AGP programming interface for Xorg to drive the card. See the agp(4) driver manual page for more information.

This will allow configuration of the hardware as any other graphics board. Note on systems without the agp(4) driver compiled in the kernel, trying to load the module with kldload(8) will not work. This driver has to be in the kernel at boot time through being compiled in or using /boot/loader.conf.

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

This section assumes a bit of advanced configuration knowledge. If attempts to use the standard configuration tools above have not resulted in a working configuration, there is information enough in the log files to be of use in getting the setup working. Use of a text editor will be necessary.

Current widescreen (WSXGA, WSXGA+, WUXGA, WXGA, WXGA+, et.al.) formats support 16:10 and 10:9 formats or aspect ratios that can be problematic. Examples of some common screen resolutions for 16:10 aspect ratios are:

  • 2560x1600

  • 1920x1200

  • 1680x1050

  • 1440x900

  • 1280x800

At some point, it will be as easy as adding one of these resolutions as a possible Mode in the Section "Screen" as such:

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

Xorg is smart enough to pull the resolution information from the widescreen via I2C/DDC information so it knows what the monitor can handle as far as frequencies and resolutions.

If those ModeLines do not exist in the drivers, one might need to give Xorg a little hint. Using /var/log/Xorg.0.log one can extract enough information to manually create a ModeLine that will work. Simply look for information resembling this:

(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

This information is called EDID information. Creating a ModeLine from this is just a matter of putting the numbers in the correct order:

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

So that the ModeLine in Section "Monitor" for this example would look like this:

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

Now having completed these simple editing steps, X should start on your new widescreen monitor.

5.9.3. Compiz Fusion 疑難排解

5.9.3.1. I have installed Compiz Fusion, and after running the commands you mention, my windows are left without title bars and buttons. What is wrong?
5.9.3.2. When I run the command to start Compiz Fusion, the X server crashes and I am back at the console. What is wrong?

5.9.3.1.

I have installed Compiz Fusion, and after running the commands you mention, my windows are left without title bars and buttons. What is wrong?

You are probably missing a setting in /etc/X11/xorg.conf. Review this file carefully and check especially the DefaultDepth and AddARGBGLXVisuals directives.

5.9.3.2.

When I run the command to start Compiz Fusion, the X server crashes and I am back at the console. What is wrong?

If you check /var/log/Xorg.0.log, you will probably find error messages during the X startup. The most common would be:

(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.

This is usually the case when you upgrade Xorg. You will need to reinstall the x11/nvidia-driver package so glx is built again.

部 II. 一般作業

既然基礎的部分已經提過了,接下來的這個部分將會討論一些常會用到的 FreeBSD 的特色,這些章節包括:

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

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

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

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

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

這些章節中有些需要您預先閱讀些相關文件,在各章節開頭的概要內會提及。

章 6. 桌面應用程式

6.1. 概述

隨著 FreeBSD 優越的效能及穩定性越來越熱門,它同時適合作為每日使用的桌面系統。FreeBSD 套件或 Ports 有超過 24,000 個可用的應用程式,可以簡單的建立一個自訂的桌面環境來執行各種不同的桌面應用程式。本章將示範如何安裝數個桌面應用程式,包含網頁瀏覽器、辦工軟體、文件閱覽程式以及財務軟體。

注意:

比起重頭設定,更偏好安裝預先編譯好桌面環境的 FreeBSD 版本的使用者可參考 pcbsd.org 網站

在閱讀這章之前,你必須了解如何:

要取得有關如何設定多媒體環境的資訊,請參考 章 7, 多媒體

6.2. 瀏覽器

在 FreeBSD 中並未預先安裝好網頁瀏覽器。 但在 Ports 套件集中的 www 分類中有許多瀏覽器可以採 Binary 套件安裝或自 Ports 套件集編譯的方式安裝。

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

有一些輕量化的瀏覽器可使用,包含 www/dillo2, www/links 以及 www/w3m

本章節將示範如何安裝下列常見的網頁瀏覽器並說明該應用程式是否需要用到大量資源、花費大量時間自 Ports 編譯或何主要的相依套件。

應用程式名稱所需資源自 Ports 安裝時間說明
Firefox有 FreeBSD 、 Linux® 及在地化版本
Opera有 FreeBSD 、 Linux® 版本
Konqueror需要 KDE 程式庫
Chromium需要 Gtk+ 程式庫

6.2.1. Firefox

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

要安裝最新釋出版本的 Firefox 套件可輸入:

# pkg install firefox

要安裝延長支援發佈 (Extended Support Release, ESR) 版本的 Firefox,可使用:

# pkg install firefox-esr

在地化的版本可在 www/firefox-i18nwww/firefox-esr-i18n 取得。

使用 Ports 套件地可以用原始碼編譯成您想要的 Firefox 版本。此範例編譯 www/firefox,其中 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

編譯 Port 時使用預設設定選項。

安裝完成時,啟動 firefox,在網址列輸入 about:plugins 並按 Enter 鍵。 會出現一個頁面列出已安裝的附加元件。 Java 附加元件應該會列在其中。

If the browser is unable to find the plugin, each user will have to run the following command and relaunch the browser:

% 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® 附加元件

Swfdec is a decoder and renderer for Flash® animations. Swfdec-Mozilla is a plugin for Firefox browsers that uses the Swfdec library for playing SWF files.

要安裝套件可:

# pkg install swfdec-plugin

If the package is not available, compile and install it from the Ports Collection:

# cd /usr/ports/www/swfdec-plugin
# make install clean

Restart the browser to activate this plugin.

6.2.2. Opera

Opera 是個具備完整功能、符合標準且輕量、執行速度快的瀏覽器。 它同時也具備了內建的郵件、新聞閱讀器、IRC 客戶端、RSS/Atom 來源閱讀器等。 可用的版本有兩種原生的 FreeBSD 版本及 Linux® 模擬模式下執行的版本。

以下指令可安裝 FreeBSD Binary 套件版本的 Opera,替換 operalinux-opera 則可改安裝 Linux® 版本。

# pkg install opera

或者,可安裝 Ports 套件集中的版本,以下範例會編譯原生的版本。

# 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 is an open source browser project that aims to build a safer, faster, and more stable web browsing experience. Chromium features tabbed browsing, popup blocking, extensions, and much more. Chromium is the open source project upon which the Google Chrome web browser is based.

Chromium can be installed as a package by typing:

# pkg install chromium

Alternatively, Chromium can be compiled from source using the Ports Collection:

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

注意:

The executable for Chromium is /usr/local/bin/chrome, not /usr/local/bin/chromium.

6.2.4.1. Chromium 與 Java™ 附加元件

The installation of Chromium does not include Java™ support. To install Java™ plugin support, follow the instructions in 節 6.2.1.1, “Firefox 與 Java™ 附加元件”.

Once Java™ support is installed, start Chromium and enter about:plugins in the address bar. IcedTea-Web should be listed as one of the installed plugins.

If Chromium does not display the IcedTea-Web plugin, run the following commands and restart the web browser:

# 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® 附加元件

Configuring Chromium and Adobe® Flash® is similar to the instructions in 節 6.2.1.2, “Firefox 與 Adobe® Flash® 附加元件”. No additional configuration should be necessary, since Chromium is able to use some plugins from other browsers.

6.3. 辦工工具

當開始進行辦公,新的使用者通常會去找好用的辦公室軟體或是好上手的文件處理程式。 雖然有些 桌面環境 像是 KDE 已經提供了辦公軟體組合的套件,FreeBSD 預設未提供任何辦工工具。 不論是否有安裝視窗管理程式,FreeBSD 可安裝多套辦公軟體以及圖型化文件處理程式。

本章節元範如何安裝以下熱門的辦工軟體以及說明該應用程式所需的資源、自 Ports 編譯的時間或者是否有其他主要相依套件。

應用程式名稱所需資源自 Ports 安裝時間主要相依套件
CalligraKDE
AbiWordGtk+GNOME
The GimpGtk+
Apache OpenOffice非常多JDKMozilla
LibreOffice有點多非常多Gtk+KDE/ GNOMEJDK

6.3.1. Calligra

The KDE desktop environment includes an office suite which can be installed separately from KDE. Calligra includes standard components that can be found in other office suites. Words is the word processor, Sheets is the spreadsheet program, Stage manages slide presentations, and Karbon is used to draw graphical documents.

In FreeBSD, editors/calligra can be installed as a package or a port. To install the package:

# pkg install calligra

If the package is not available, use the Ports Collection instead:

# cd /usr/ports/editors/calligra
# make install clean

6.3.2. AbiWord

AbiWord 是一個免費的文件處理軟體,外觀和感覺都近似於 Microsoft® Word。 它非常快速,包含了許多功能而且非常容易上手。

AbiWord 可以輸入或輸出許多檔案格式, 包括一些有專利的格式,例如 Microsoft® .rtf 格式。

要安裝 AbiWord Binary 套件,可使用下列指令:

# pkg install abiword

若沒有 Binary 套件版本,也可以從 Ports 套件集中編譯安裝:

# cd /usr/ports/editors/abiword
# make install clean

6.3.3. The GIMP

對於影像的編輯及修改來說,The GIMP 是非常精緻的影像處理軟體。 它可以當作簡單的繪圖軟體或是高品質的相片處理軟體。 它支援為數眾多的外掛程式及指令稿 (script-fu) 介面。 The GIMP 可以讀寫許多檔案格式。 它也支援掃描器和手寫板。

要安裝套件可:

# pkg install gimp

或使用 Ports 套件集安裝:

# cd /usr/ports/graphics/gimp
# make install clean

在 Ports 套件集的 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 is a free software office suite developed by documentfoundation.org. It is compatible with other major office suites and available on a variety of platforms. It is a rebranded fork of Apache OpenOffice and includes applications found in a complete office productivity suite: a word processor, spreadsheet, presentation manager, drawing program, database management program, and a tool for creating and editing mathematical formulæ. It is available in a number of different languages and internationalization has been extended to interfaces, spell checkers, and dictionaries.

The word processor of LibreOffice uses a native XML file format for increased portability and flexibility. The spreadsheet program features a macro language which can be interfaced with external databases. LibreOffice is stable and runs natively on Windows®, Linux®, FreeBSD, and Mac OS® X. More information about LibreOffice can be found at libreoffice.org.

To install the English version of the LibreOffice package:

# pkg install libreoffice

The editors category (freebsd.org/ports/editors.html) of the Ports Collection contains several localizations for LibreOffice. When installing a localized package, replace libreoffice with the name of the localized package.

Once the package is installed, type the following command to run LibreOffice:

% libreoffice

During the first launch, some questions will be asked and a .libreoffice folder will be created in the user's home directory.

If the desired LibreOffice package is not available, compiling the port is still an option. However, this requires a lot of disk space and a fairly long time to compile. This example compiles the English version:

# cd /usr/ports/editors/libreoffice
# make install clean

注意:

To build a localized version, cd into the port directory of the desired language. Supported languages can be found in the editors category (freebsd.org/ports/editors.html) of the Ports Collection.

6.4. 文件閱覽程式

Some new document formats have gained popularity since the advent of UNIX® and the viewers they require may not be available in the base system. This section demonstrates how to install the following document viewers:

應用程式名稱所需資源自 Ports 安裝時間主要相依套件
XpdfFreeType
gvXaw3d
GeeqieGtk+GNOME
ePDFViewGtk+
OkularKDE

6.4.1. Xpdf

如果你想要一個小型的 FreeBSD PDF 閱覽軟體, Xpdf 是個輕量級而且有效率的閱覽器。 它只需要非常少的資源而且十分穩定。 它只使用標準的 X 字型且不需要額外的工具包(Toolkit)。

安裝 Xpdf 套件:

# pkg install xpdf

若沒有可用的套件版本,可使用 Ports 套件集安裝:

# cd /usr/ports/graphics/xpdf
# make install clean

完成安裝後,執行 xpdf 並使用滑鼠右鍵開啟選單。

6.4.2. gv

gvPostScript® 和 PDF 的閱覽器。 它建構於 ghostview 的基礎上,不過因為使用 Xaw3d 視窗元件工具包,所以外觀看起來比較漂亮。 gv 有許多可設定的功能,比如說紙張方向、紙張大小、縮放比例、和反鋸齒(Anti-aliasing)等。 而且幾乎所有的使用都可以從鍵盤或滑鼠來完成。

安裝 gv 套件:

# pkg install gv

若沒有可用的套件版本,可使用 Ports 套件集安裝:

# cd /usr/ports/print/gv
# make install clean

6.4.3. Geeqie

Geeqie 是由已經停止維護的 GQView 專案所衍伸出來的分支,並致力開發新功能並整合已有的修補。Geeqie 是一套影像管理軟體,支援單鍵閱覽檔案、啟動外部編輯器、縮圖預覽等功能。 它也有幻燈片模式及一些基本的檔案操作的功能,能輕鬆的管理大量影像並找出重複的檔案。 Geeqie 也支援使用全螢幕閱覽以及國際化。

安裝 Geeqie 套件:

# pkg install geeqie

若沒有可用的套件版本,可使用 Ports 套件集安裝:

# cd /usr/ports/graphics/geeqie
# make install clean

6.4.4. ePDFView

ePDFView is a lightweight PDF document viewer that only uses the Gtk+ and Poppler libraries. It is currently under development, but already opens most PDF files (even encrypted), save copies of documents, and has support for printing using CUPS.

To install ePDFView as a package:

# pkg install epdfview

若沒有可用的套件版本,可使用 Ports 套件集安裝:

# cd /usr/ports/graphics/epdfview
# make install clean

6.4.5. Okular

Okular is a universal document viewer based on KPDF for KDE. It can open many document formats, including PDF, PostScript®, DjVu, CHM, XPS, and ePub.

To install Okular as a package:

# pkg install okular

若沒有可用的套件版本,可使用 Ports 套件集安裝:

# cd /usr/ports/graphics/okular
# make install clean

6.5. 財務

如果有任何理由你想要在你的 FreeBSD 桌面環境上管理你的個人財務, 這裡有一些功能強大、使用簡單的應用程式可供安裝。 這些財務管理軟體之中有些是相容於流行的 QuickenExcel 文件。

這節涵蓋了下面這些軟體:

應用程式名稱所需資源自 Ports 安裝時間主要相依套件
GnuCashGNOME
GnumericGNOME
KMyMoneyKDE

6.5.1. GnuCash

GnuCashGNOME 團隊努力成果中的一部分, GNOME 團隊主要提供親切而強大的桌面應用程式給終端使用者。使用 GnuCash 可以持續追蹤記錄收入與花費、銀行帳戶以及股票證券等。 它的特性是介面直覺但功能仍非常專業。

GnuCash 提供了智慧的計數器、多階層帳戶系統以及快速鍵及自動完成功能。 它也能分開單一的報表至數個詳細的部份。 GnuCash 也能夠匯入及合併 Quicken QIF 檔案。 它也能處理大部分國際的日期及通用貨幣之格式。

安裝 GnuCash 套件:

# pkg install gnucash

若沒有可用的套件版本,可使用 Ports 套件集安裝:

# cd /usr/ports/finance/gnucash
# make install clean

6.5.2. Gnumeric

GnumericGNOME 社群所開發的試算表程式。 它的特點是擁有能夠根據儲存格格式 「猜出」使用者的輸入來自動補齊的系統。 它也能夠匯入許多熱門的檔案格式,像是 Excel, Lotus 1-2-3 以及 Quattro Pro。 它有大量內建的函數而且能夠使用常用的儲存格格式,像是:數字、貨幣、日期、時間及其他格式等。

安裝 Gnumeric 套件:

# pkg install gnumeric

若沒有可用的套件版本,可使用 Ports 套件集安裝:

# cd /usr/ports/math/gnumeric
# make install clean

6.5.3. KMyMoney

KMyMoney is a personal finance application created by the KDE community. KMyMoney aims to provide the important features found in commercial personal finance manager applications. It also highlights ease-of-use and proper double-entry accounting among its features. KMyMoney imports from standard Quicken QIF files, tracks investments, handles multiple currencies, and provides a wealth of reports.

To install KMyMoney as a package:

# pkg install kmymoney-kde4

若沒有可用的套件版本,可使用 Ports 套件集安裝:

# cd /usr/ports/finance/kmymoney-kde4
# make install clean

章 7. 多媒體

Edited by Ross Lippert.

7.1. 概述

FreeBSD 廣泛地支援各種音效卡, 讓您可以享受來自電腦上的高傳真音質(Hi-Fi), 此外還包括了錄製和播放 MPEG Audio Layer 3 (MP3)、 Waveform Audio File (WAV)、Ogg Vorbis 以及其他許多種格式聲音的能力。同時 FreeBSD Ports 套件集也包含了許多可讓您可以錄音、編修音效以及控制 MIDI 配備的應用程式。

FreeBSD 也能播放一般的視訊檔和 DVD。 FreeBSD Ports 套件集中含有可編碼、轉換以及播放格種影像媒體的應用程式。

本章會說明如何設定 FreeBSD 上的音效卡、影像播放器、電視卡及掃描器。同時會說明有那些應用程式可以使用這些裝置。

讀完這章,您將了解:

  • 設定 FreeBSD 上的音效卡。

  • 音效設定疑難排解。

  • 播放、錄製 MP3 及其他聲音檔案格式。

  • FreeBSD 系統播放影像的準備工具。

  • 播放 DVD.mpg.avi 檔。

  • 擷取(Rip) CDDVD的內容至檔案。

  • 設定電視卡。

  • 在 FreeBSD 安裝 MythTV 。

  • 設定影像掃描機。

在開始閱讀這章之前,您需要︰

7.2. 設定音效卡

Contributed by Moses Moore.
Enhanced by Marc Fonvieille.

開始設定之前,必須先知道你的音效卡型號、晶片為何。 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 Munish Chopra.

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 Josef El-Rayes.

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 Chern Lee.

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 Ross Lippert.

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. 可處理影像的 Ports 與套件

This section introduces some of the software available from the FreeBSD Ports Collection which can be used for video playback.

7.4.2.1. MPlayerMEncoder

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 Josef El-Rayes.
Enhanced and adapted by Marc Fonvieille.

電視卡(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 Marc Fonvieille.

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 核心沒有提供的硬體支援。

Before building a custom kernel, consider the reason for doing so. If there is a need for specific hardware support, it may already exist as a module.

Kernel modules exist in /boot/kernel and may be dynamically loaded into the running kernel using kldload(8). Most kernel drivers have a loadable module and manual page. For example, the ath(4) wireless Ethernet driver has the following information in its manual page:

Alternatively, to load the driver as a module at boot time, place the
following line in loader.conf(5):

    if_ath_load="YES"

Adding if_ath_load="YES" to /boot/loader.conf will load this module dynamically at boot time.

In some cases, there is no associated module in /boot/kernel. This is mostly true for certain subsystems.

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 Warren Block.

Putting information on paper is a vital function, despite many attempts to eliminate it. Printing has two basic components. The data must be delivered to the printer, and must be in a form that the printer can understand.

9.1. 快速開始

Basic printing can be set up quickly. The printer must be capable of printing plain ASCII text. For printing to other types of files, see 節 9.5.3, “過濾器”.

  1. Create a directory to store files while they are being printed:

    # mkdir -p /var/spool/lpd/lp
    # chown daemon:daemon /var/spool/lpd/lp
    # chmod 770 /var/spool/lpd/lp
  2. As root, create /etc/printcap with these contents:

    lp:\
    	:lp=/dev/unlpt0:\  1
    	:sh:\
    	:mx#0:\
    	:sd=/var/spool/lpd/lp:\
    	:lf=/var/log/lpd-errs:

    1

    This line is for a printer connected to a USB port.

    For a printer connected to a parallel or printer port, use:

    :lp=/dev/lpt0:\

    For a printer connected directly to a network, use:

    :lp=:rm=network-printer-name:rp=raw:\

    Replace network-printer-name with the DNS host name of the network printer.

  3. Enable lpd by editing /etc/rc.conf, adding this line:

    lpd_enable="YES"

    Start the service:

    # service lpd start
    Starting lpd.
  4. Print a test:

    # printf "1. This printer can print.\n2. This is the second line.\n" | lpr

    提示:

    If both lines do not start at the left border, but stairstep instead, see 節 9.5.3.1, “避免在純文字印表機階梯狀列印”.

    Text files can now be printed with lpr. Give the filename on the command line, or pipe output directly into lpr.

    % lpr textfile.txt
    % ls -lh | lpr

9.2. 印表機連線

Printers are connected to computer systems in a variety of ways. Small desktop printers are usually connected directly to a computer's USB port. Older printers are connected to a parallel or printer port. Some printers are directly connected to a network, making it easy for multiple computers to share them. A few printers use a rare serial port connection.

FreeBSD can communicate with all of these types of printers.

USB

USB printers can be connected to any available USB port on the computer.

When FreeBSD detects a USB printer, two device entries are created: /dev/ulpt0 and /dev/unlpt0. Data sent to either device will be relayed to the printer. After each print job, ulpt0 resets the USB port. Resetting the port can cause problems with some printers, so the unlpt0 device is usually used instead. unlpt0 does not reset the USB port at all.

Parallel (IEEE-1284)

The parallel port device is /dev/lpt0. This device appears whether a printer is attached or not, it is not autodetected.

Vendors have largely moved away from these legacy ports, and many computers no longer have them. Adapters can be used to connect a parallel printer to a USB port. With such an adapter, the printer can be treated as if it were actually a USB printer. Devices called print servers can also be used to connect parallel printers directly to a network.

Serial (RS-232)

Serial ports are another legacy port, rarely used for printers except in certain niche applications. Cables, connectors, and required wiring vary widely.

For serial ports built into a motherboard, the serial device name is /dev/cuau0 or /dev/cuau1. Serial USB adapters can also be used, and these will appear as /dev/cuaU0.

Several communication parameters must be known to communicate with a serial printer. The most important are baud rate or BPS (Bits Per Second) and parity. Values vary, but typical serial printers use a baud rate of 9600 and no parity.

Network

Network printers are connected directly to the local computer network.

The DNS hostname of the printer must be known. If the printer is assigned a dynamic address by DHCP, DNS should be dynamically updated so that the host name always has the correct IP address. Network printers are often given static IP addresses to avoid this problem.

Most network printers understand print jobs sent with the LPD protocol. A print queue name can also be specified. Some printers process data differently depending on which queue is used. For example, a raw queue prints the data unchanged, while the text queue adds carriage returns to plain text.

Many network printers can also print data sent directly to port 9100.

9.2.1. 摘要

Wired network connections are usually the easiest to set up and give the fastest printing. For direct connection to the computer, USB is preferred for speed and simplicity. Parallel connections work but have limitations on cable length and speed. Serial connections are more difficult to configure. Cable wiring differs between models, and communication parameters like baud rate and parity bits must add to the complexity. Fortunately, serial printers are rare.

9.3. 常見的頁面描述語言

Data sent to a printer must be in a language that the printer can understand. These languages are called Page Description Languages, or PDLs.

ASCII

Plain ASCII text is the simplest way to send data to a printer. Characters correspond one to one with what will be printed: an A in the data prints an A on the page. Very little formatting is available. There is no way to select a font or proportional spacing. The forced simplicity of plain ASCII means that text can be printed straight from the computer with little or no encoding or translation. The printed output corresponds directly with what was sent.

Some inexpensive printers cannot print plain ASCII text. This makes them more difficult to set up, but it is usually still possible.

PostScript®

PostScript® is almost the opposite of ASCII. Rather than simple text, a PostScript® program is a set of instructions that draw the final document. Different fonts and graphics can be used. However, this power comes at a price. The program that draws the page must be written. Usually this program is generated by application software, so the process is invisible to the user.

Inexpensive printers sometimes leave out PostScript® compatibility as a cost-saving measure.

PCL (Printer Command Language)

PCL is an extension of ASCII, adding escape sequences for formatting, font selection, and printing graphics. Many printers provide PCL5 support. Some support the newer PCL6 or PCLXL. These later versions are supersets of PCL5 and can provide faster printing.

Host-Based

Manufacturers can reduce the cost of a printer by giving it a simple processor and very little memory. These printers are not capable of printing plain text. Instead, bitmaps of text and graphics are drawn by a driver on the host computer and then sent to the printer. These are called host-based printers.

Communication between the driver and a host-based printer is often through proprietary or undocumented protocols, making them functional only on the most common operating systems.

9.3.1. 轉換 PostScript® 至其他 PDL

Many applications from the Ports Collection and FreeBSD utilities produce PostScript® output. This table shows the utilities available to convert that into other common PDLs:

表格 9.1. 輸出 PDL 格式
Output PDLGenerated By說明
PCL or PCL5print/ghostscript9-sDEVICE=ljet4 for monochrome, -sDEVICE=cljet5 for color
PCLXL or PCL6print/ghostscript9-sDEVICE=pxlmono for monochrome, -sDEVICE=pxlcolor for color
ESC/P2print/ghostscript9-sDEVICE=uniprint
XQXprint/foo2zjs 

9.3.2. 摘要

For the easiest printing, choose a printer that supports PostScript®. Printers that support PCL are the next preferred. With print/ghostscript, these printers can be used as if they understood PostScript® natively. Printers that support PostScript® or PCL directly almost always support direct printing of plain ASCII text files also.

Line-based printers like typical inkjets usually do not support PostScript® or PCL. They often can print plain ASCII text files. print/ghostscript supports the PDLs used by some of these printers. However, printing an entire graphic-based page on these printers is often very slow due to the large amount of data to be transferred and printed.

Host-based printers are often more difficult to set up. Some cannot be used at all because of proprietary PDLs. Avoid these printers when possible.

Descriptions of many PDLs can be found at http://www.undocprint.org/formats/page_description_languages. The particular PDL used by various models of printers can be found at http://www.openprinting.org/printers.

9.4. 直接列印

For occasional printing, files can be sent directly to a printer device without any setup. For example, a file called sample.txt can be sent to a USB printer:

# cp sample.txt /dev/unlpt0

Direct printing to network printers depends on the abilities of the printer, but most accept print jobs on port 9100, and nc(1) can be used with them. To print the same file to a printer with the DNS hostname of netlaser:

# nc netlaser 9100 < sample.txt

9.5. LPD (行列式印表機 Daemon)

Printing a file in the background is called spooling. A spooler allows the user to continue with other programs on the computer without waiting for the printer to slowly complete the print job.

FreeBSD includes a spooler called lpd(8). Print jobs are submitted with lpr(1).

9.5.1. 初始設定

A directory for storing print jobs is created, ownership is set, and the permissions are set to prevent other users from viewing the contents of those files:

# mkdir -p /var/spool/lpd/lp
# chown daemon:daemon /var/spool/lpd/lp
# chmod 770 /var/spool/lpd/lp

Printers are defined in /etc/printcap. An entry for each printer includes details like a name, the port where it is attached, and various other settings. Create /etc/printcap with these contents:

lp:\				1
	:lp=/dev/unlpt0:\	2
	:sh:\			3
	:mx#0:\			4
	:sd=/var/spool/lpd/lp:\	5
	:lf=/var/log/lpd-errs:	6

1

The name of this printer. lpr(1) sends print jobs to the lp printer unless another printer is specified with -P, so the default printer should be named lp.

2

The device where the printer is connected. Replace this line with the appropriate one for the connection type shown here.

Connection TypeDevice Entry in /etc/printcap
USB
:lp=/dev/unlpt0:\

This is the non-resetting USB printer device. If problems are experienced, use ulpt0 instead, which resets the USB port on each use.

Parallel
:lp=/dev/lpt0:\
Network

For a printer supporting the LPD protocol:

:lp=:rm=network-printer-name:rp=raw:\

For printers supporting port 9100 printing:

:lp=9100@network-printer-name:\

For both types, replace network-printer-name with the DNS host name of the network printer.

Serial
:lp=/dev/cuau0:br=9600:pa=none:\

These values are for a typical serial printer connected to a motherboard serial port. The baud rate is 9600, and no parity is used.

3

Suppress the printing of a header page at the start of a print job.

4

Do not limit the maximum size of a print job.

5

The path to the spooling directory for this printer. Each printer uses its own spooling directory.

6

The log file where errors on this printer will be reported.

After creating /etc/printcap, use chkprintcap(8) to test it for errors:

# chkprintcap

Fix any reported problems before continuing.

Enable lpd(8) in /etc/rc.conf:

lpd_enable="YES"

Start the service:

# 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:\   1
	:lf=/var/log/lpd-errs:

1

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/enscriptPostScript® 印表機美化純文字內容

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
#
IFS="" read -r first_line
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 Jim Mock.
Originally contributed by Brian N. Handy and Rich Murphey.

10.1. 概述

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

然而,部份 Linux® 作業系統的特色在 FreeBSD 並未支援。 例如,如果 Linux® Binary 過度使用 i386™ 特定的呼叫,像是啟動虛擬 8086 模式,將無法在 FreeBSD 執行。此外,64 位元 Linux® Binary 目前也尚未支援。

讀完這章,您將了解︰

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

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

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

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

在開始閱讀這章之前,您需要︰

10.2. 設定 Linux® Binary 相容性

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

在嘗試編譯 Port 前,要載入 Linux® 核心模組,否則編譯會失敗:

# kldload linux

確認模組已載入:

% kldstat
      Id Refs Address    Size     Name
      1    2 0xc0100000 16bdb8   kernel
      7    1 0xc24db000 d000     linux.ko

在 FreeBSD 安裝基本的 Linux® 程式庫和 Binary 最簡單的方式是安裝 emulators/linux_base-c6 套件或是 Port 。要安裝 Port:

# 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® 相容性,可以加入這行到 /etc/rc.conf

linux_enable="YES"

想要靜態連結 Linux® Binary 相容性到自訂核心的使用者應加入 options COMPAT_LINUX 到自訂核心設定檔。 編譯並安裝新核心的方法,如 章 8, 設定 FreeBSD 核心 所述。

10.2.1. 手動安裝其他程式庫

若有 Linux® 應用程式在設定 Linux® Binary 相容性後出現缺少共用程式庫的情況,確認這個 Linux® Binary 需要哪個共用程式庫並手動安裝。

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

然後,複製所有 Linux® 系統輸出結果中最後一欄的檔案到 FreeBSD 系統的 /compat/linux。 複製完後,建立符號連結 (Symbolic link) 至輸出結果第一欄的名稱。以這個例子會在 FreeBSD 系統產生以下檔案:

/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 輸出結果第一欄的主要修訂版號,則不需要複製該行最後一欄的檔案,使用既有的程式庫應可運作。若有較新的版本建議仍要複製共用程式庫,只要符號連結指向新版的程式庫,舊版便可移除。

例如,以下程式庫已存在 FreeBSD 系統:

/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

雖然既有的程式庫只有在最後一碼過時一或兩個版本,程式應該仍可使用稍微舊的版本執行,雖然如此,保險起見還替換既有的 libc.so 為較新的版本:

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

一般來說,只有在安裝 Linux® 程式到 FreeBSD 完的前幾次會需要查看 Linux® Binary 相依的共用程式庫。之後系統便有足夠的 Linux® 共用程式庫能夠執行新安裝的 Linux® Binary,便不再需要額外的動作。

10.2.2. 安裝 Linux® ELF Binary

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

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

要協助 FreeBSD 核心區別是 FreeBSD ELF Binary 還是 Linux® Binary,可使用 brandelf(1)

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

由於 GNU 工具鏈會自動放置適當的商標資訊到 ELF Binary,通常不需要這個步驟。

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

要安裝 Linux® RPM 為基礎的應用程式,需先安裝 archivers/rpm4 套件或 Port。安裝完成之後,root 可以使用這個指令安裝 .rpm

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

如果需要, brandelf 已安裝的 ELF Binary。注意,這將會無法乾淨地解除安裝。

10.2.4. 設定主機名稱解析器

如果 DNS 無法運作或出現這個錯誤:

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

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

order hosts, bind
multi on

這指定先搜尋 /etc/hosts,其次為 DNS。 當 /compat/linux/etc/host.conf 不存在, Linux® 應用程式會使用 /etc/host.conf 並會警告不相容的 FreeBSD 語法。如果名稱伺服器未設定使用 /etc/resolv.conf 的話,則可移除 bind

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. 系統管理

FreeBSD 使用手冊剩下的這些章節涵蓋了全方位的 FreeBSD 系統管理。 每個章節的開頭會先描述在該您讀完該章節後您會學到什麼,也會詳述在您在看這些資料時應該要有的一些背景知識。

這些章節是讓您在需要查資料的時候翻閱用的。 您不需要依照特定的順序來讀,也不需要將這些章節全部過讀之後才開始用 FreeBSD。

內容目錄
11. 設定與調校
11.1. 概述
11.2. 啟動服務
11.3. 設定 cron(8)
11.4. 管理 FreeBSD 中的服務
11.5. 設定網路介面卡
11.6. 虛擬主機
11.7. 設定系統日誌
11.8. 設定檔
11.9. 使用 sysctl(8) 調校
11.10. 調校磁碟
11.11. 調校核心限制
11.12. 增加交換空間
11.13. 電源與資源管理
12. FreeBSD 開機程序
12.1. 概述
12.2. FreeBSD 開機程序
12.3. 設定開機啟動畫面
12.4. Device Hints
12.5. 關機程序
13. 安全性
13.1. 概述
13.2. 簡介
13.3. 一次性密碼
13.4. TCP Wrapper
13.5. Kerberos
13.6. OpenSSL
13.7. VPN over IPsec
13.8. OpenSSH
13.9. 存取控制清單
13.10. 監視第三方安全性問題
13.11. FreeBSD 安全報告
13.12. 程序追蹤
13.13. 限制資源
13.14. 使用 Sudo 分享管理權限
14. Jails
14.1. 概述
14.2. Jail 相關術語
14.3. 建立和控制 Jail
14.4. 調校與管理
14.5. 更新多個 Jail
14.6. 使用 ezjail 管理 Jail
15. 強制存取控制 (MAC)
15.1. 概述
15.2. 關鍵詞
15.3. 了解 MAC 標籤
15.4. 規劃安全架構
15.5. 可用的 MAC 管理政策
15.6. User Lock Down
15.7. 在 MAC Jail 中使用 Nagios
15.8. MAC 架構疑難排解
16. 安全事件稽查
16.1. 概述
16.2. 關鍵詞
16.3. 稽查設定
16.4. 查看稽查線索
17. 儲存設備
17.1. 概述
17.2. 加入磁碟
17.3. 重設大小與擴增磁碟
17.4. USB 儲存裝置
17.5. 建立與使用 CD 媒體
17.6. 建立與使用 DVD 媒體
17.7. 建立與使用軟碟
17.8. 備份基礎概念
17.9. 記憶體磁碟
17.10. 檔案系統快照
17.11. 磁碟配額
17.12. 磁碟分割區加密
17.13. 交換空間加密
17.14. 高可用存儲空間 (HAST)
18. GEOM: Modular Disk Transformation Framework
18.1. 概述
18.2. RAID0 - 分散 (Striping)
18.3. RAID1 - 鏡射 (Mirroring)
18.4. RAID3 - 位元級分散儲存與獨立奇偶校驗
18.5. 軟體 RAID 裝置
18.6. GEOM Gate Network
18.7. 磁碟裝置標籤
18.8. UFS Journaling 透過 GEOM
19. Z 檔案系統 (ZFS)
19.1. 什麼使 ZFS 與眾不同
19.2. 快速入門指南
19.3. zpool 管理
19.4. zfs 管理
19.5. 委託管理
19.6. 進階主題
19.7. 其他資源
19.8. ZFS 特色與術語
20. 其他檔案系統
20.1. 概述
20.2. Linux® 檔案系統
21. 虛擬化
21.1. 概述
21.2. 在 Mac OS® X 的 Parallels 安裝 FreeBSD 為客端
21.3. 在 Windows® 的 Virtual PC 安裝 FreeBSD 為客端
21.4. 在 Mac OS® 的 VMware Fusion 安裝 FreeBSD 為客端
21.5. 安裝 VirtualBox™ Guest Additions 於 FreeBSD 客端
21.6. 以 FreeBSD 作為主端安裝 VirtualBox
21.7. 以 FreeBSD 作為主端安裝 bhyve
22. 在地化 - i18n/L10n 使用與安裝
22.1. 概述
22.2. 使用語系
22.3. 尋找 i18n 應用程式
22.4. 特定語言的語系設定
23. 更新與升級 FreeBSD
23.1. 概述
23.2. FreeBSD 更新
23.3. 更新文件集
23.4. 追蹤開發分支
23.5. Updating FreeBSD from Source
23.6. 多部機器追蹤
24. DTrace
24.1. 概述
24.2. 實作差異
24.3. 開啟 DTrace 支援
24.4. 使用 DTrace

章 11. 設定與調校

Written by Chern Lee.
Based on a tutorial written by Mike Smith.
Also based on tuning(7) written by Matt Dillon.

11.1. 概述

在 FreeBSD 使用過程中,相當重要的環節之一就是如何正確設定系統。 本章著重於介紹 FreeBSD 的設定流程,包括一些可以調整 FreeBSD 效能的參數設定。

讀完這章,您將了解︰

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

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

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

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

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

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

在開始閱讀這章之前,您需要︰

11.2. 啟動服務

Contributed by Tom Rhodes.

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 Tom Rhodes.

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 49235 2016-08-09 03:14:22Z wblock $
# 1
SHELL=/bin/sh
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin 2
#
#minute	hour	mday	month	wday	who	command 3
#
*/5	*	*	*	*	root	/usr/libexec/atrun 4

1

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.

2

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.

3

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.

4

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 Tom Rhodes.

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 Marc Fonvieille.

Adding and configuring a network interface card (NIC) is a common task for any FreeBSD administrator.

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
dc0: Ethernet address: 00:a0:cc:da:da:da
dc0: [ITHREAD]
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: Ethernet address: 00:a0:cc:da:da:db
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: Ethernet address: 0a:b1:2c:d3:4e:f5
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
        options=80008<VLAN_MTU,LINKSTATE>
        ether 00:a0:cc:da:da:da
        inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255
        media: Ethernet autoselect (100baseTX <full-duplex>)
        status: active
dc1: flags=8802<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> metric 0 mtu 1500
        options=80008<VLAN_MTU,LINKSTATE>
        ether 00:a0:cc:da:da:db
        inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255
        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
        inet 127.0.0.1 netmask 0xff000000
        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
	options=80008<VLAN_MTU,LINKSTATE>
	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_alias0="inet 10.1.1.2 netmask 255.255.255.255"
ifconfig_fxp0_alias1="inet 10.1.1.3 netmask 255.255.255.255"
ifconfig_fxp0_alias2="inet 10.1.1.4 netmask 255.255.255.255"
ifconfig_fxp0_alias3="inet 10.1.1.5 netmask 255.255.255.255"
ifconfig_fxp0_alias4="inet 202.0.75.17 netmask 255.255.255.240"
ifconfig_fxp0_alias5="inet 202.0.75.18 netmask 255.255.255.255"
ifconfig_fxp0_alias6="inet 202.0.75.19 netmask 255.255.255.255"
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 Niclas Zeising.

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 49235 2016-08-09 03:14:22Z 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 49235 2016-08-09 03:14:22Z 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 Tom Rhodes.

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.

範例 11.1. 日誌伺服器設定範例
+logclient.example.com
*.*     /var/log/logclient.log

When adding multiple log clients, add a similar two-line entry for each client. More information about the available facilities may be found in syslog.conf(5).

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:

/etcGeneric system-specific configuration information.
/etc/defaultsDefault versions of system configuration files.
/etc/mailExtra sendmail(8) configuration and other MTA configuration files.
/etc/pppConfiguration for both user- and kernel-ppp programs.
/etc/namedbDefault location for named(8) data. Normally named.conf and zone files are stored here.
/usr/local/etcConfiguration files for installed applications. May contain per-application subdirectories.
/usr/local/etc/rc.drc(8) scripts for installed applications.
/var/dbAutomatically 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:

nameserverThe IP address of a name server the resolver should query. The servers are queried in the order listed with a maximum of three.
searchSearch list for hostname lookup. This is normally determined by the domain of the local hostname.
domainThe 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 49235 2016-08-09 03:14:22Z 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

Consult hosts(5) for more information.

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.

To view all readable variables:

% 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 Tom Rhodes.

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.

For more information, refer to ata(4).

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.

範例 11.2. 建立交換檔於 FreeBSD 10.X 及以後版本
  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

範例 11.3. 建立交換檔於 FreeBSD 9.X 及先前版本
  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 Hiten Pandya and Tom Rhodes.

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 Nate Lawson.
With contributions from Peter Schultz and Tom Rhodes.

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. 參考文獻

More information about ACPI may be found in the following locations:



[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. FreeBSD 開機程序

12.1. 概述

從開啟電腦到載入作業系統的這段流程稱為開機程序 (Bootstrap process) 或開機 (booting)。FreeBSD 的開機程序提供大量的客製化彈性,包含可選擇安裝在同電腦的其他的作業系統、不同版本的作業系統或不同核心的作業系統的功能。

本章會詳細說明可以設定的選項。示範如何自訂 FreeBSD 開機流程,包含其中所有會發生的事,直到啟動 FreeBSD 核心、偵測裝置及啟動 init(8)。這些事會發生在開機訊息的文字顏色會從亮白變成灰色之間。

在閱讀本章之後,您會了解:

  • FreeBSD 開機系統的元件以及它們如何互動。

  • FreeBSD 開機程式中各元件可使用的選項,用來控制開機程序。

  • 如何設定自訂的開機啟動畫面 (Splash screen)。

  • 設定 Device Hints 的基礎。

  • 如何開機進入單人及多人模式以及如何正確關閉 FreeBSD 系統。

注意:

本章僅說明 FreeBSD 在 x86 及 amd64 系統上執行的開機流程。

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: