一、安装内核源代码
  要编译内核,首先必须保证内核的源代码在,我们看看我们的系统有没有安装:

  # ls /usr/src/sys
  ls: /usr/src/sys: No such file or directory

  证明我们并没有安装内核源代码,好,我们就安装它。内核源代码默认是安装在了/usr/src/sys目录下的,如果不存在该目录,那么证明你没

  有安装源代码。
  我们先把我们的FreeBSD的安装光盘放进光驱,然后在FreeBSD下执行以root身份执行sysinstall, 选择Configure——>
Distributions------->src----->sys,回车后能开始安装了,一般只要几分钟就能安装好,装好了你就能查看该文件夹:

  # ls /usr/src/sys
  Makefile ddb libkern netkey pci
  alpha dev modules netnatm posix4
  amd64 fs net netncp powerpc
  arm geom net80211 netsmb rpc
  boot gnu netatalk nfs security
  cam i386 netatm nfs4client sparc64
  coda i4b netgraph nfsclient sys
  compat ia64 netinet nfsserver tools
  conf isa netinet6 opencrypto ufs
  contrib isofs netipsec pc98 vm
  crypto kern netipx pccard

  源代码安装好后,我们就可以开始我们的配置内核只旅啦。
  

  二、配置内核文件
  其实我们编译内核的关键就是配置内核文件,内核配置文件的目录是在 /usr/src/sys/i386/conf 下,我们进入改目录:

  # cd /usr/src/sys/i386/conf
  # ls
  GENERIC GENERIC.hints NOTES PAE
  Makefile OLDCARD gethints.awk

  内核配置文件就是GENERIC,我们要配置的就是它,配置包括要开启那些硬件支持,IPv6支持,网卡等等。为了防止我们配置文件配置后有问题,

  我们先把它备份一下:

  # cp GENERIC GENERIC.bak

  然后我们就用任一编辑器打开该文件,可以使用vi,或者ee打开或者nano打开,我为了方便,就使用ee来打开:

  # ee GENERIC

  打开后就有类似:

  # GENERIC -- Generic kernel configuration file for FreeBSD/i386
  #
  # For more information on this file, please read the handbook section on
  # Kernel Configuration Files:

  的内容,前面有"#"代表该内容或者选项是注释,那么假如我们要去掉什么选项,就可以在前面加上"#",当然你不需要的选项你也可删除,但是

  我推荐不需要的选项在前面加"#"。

  关于配置文件详细的修改建议参考FreeBSD中文手册关于内核配置选项的详细说明:
  http://www.freebsd.org.cn/snap/doc/zh_CN.GB2312/books/handbook/kernelconfig-config.html

  我的配置文件是这么修改的,详细我就不说明了,请查看上面的配置文件参考,应该适合大部分没有ISA,SCSI,RAID等设备的机器。
  

  GENERIC内核配置文件配置:

  freebsd# more GENERIC
#
# GENERIC -- Generic kernel configuration file for FreeBSD/i386
#
# For more information on this file, please read the config(5) manual page,
# and/or the handbook section on Kernel Configuration Files:
#
#    http://www.FreeBSD.org/doc/en_US.ISO8859- 1/books/handbook/kernelconfig-config.html
#
# The handbook is also available locally in /usr/share/doc/handbook
# if you've installed the doc distribution, otherwise always see the
# FreeBSD World Wide Web server (http://www.FreeBSD.org/) for the
# latest information.
#
# An exhaustive list of options and more detailed explanations of the
# device lines is also present in the ../../conf/NOTES and NOTES files.
# If you are in doubt as to the purpose or necessity of a line, check first
# in NOTES.
#
# $FreeBSD: src/sys/i386/conf/GENERIC,v 1.519.2.12.2.1 2010/12/21 17:09:25 kensmith Exp $

cpu             I486_CPU
cpu             I586_CPU
cpu             I686_CPU
ident           GENERIC

# To statically compile in device wiring instead of /boot/device.hints
#hints          "GENERIC.hints"         # Default places to look for devices.

# Use the following to compile in values accessible to the kernel
# through getenv() (or kenv(1) in userland). The format of the file
# is 'variable=value', see kenv(1)
#
# env           "GENERIC.env"

makeoptions     DEBUG=-g                # Build kernel with gdb(1) debug symbols

options         SCHED_ULE               # ULE scheduler
options         PREEMPTION              # Enable kernel thread preemption
options         INET                    # InterNETworking
options         INET6                   # IPv6 communications protocols
options         SCTP                    # Stream Control Transmission Protocol
options         FFS                     # Berkeley Fast Filesystem
options         SOFTUPDATES             # Enable FFS soft updates support
options         UFS_ACL                 # Support for access control lists
options         UFS_DIRHASH             # Improve performance on big directories
options         UFS_GJOURNAL            # Enable gjournal-based UFS journaling
options         MD_ROOT                 # MD is a potential root device
options         NFSCLIENT               # Network Filesystem Client
options         NFSSERVER               # Network Filesystem Server
options         NFSLOCKD                # Network Lock Manager
options         NFS_ROOT                # NFS usable as /, requires NFSCLIENT
options         MSDOSFS                 # MSDOS Filesystem
options         CD9660                  # ISO 9660 Filesystem
options         PROCFS                  # Process filesystem (requires PSEUDOFS)
options         PSEUDOFS                # Pseudo-filesystem framework
options         GEOM_PART_GPT           # GUID Partition Tables.
options         GEOM_LABEL              # Provides labelization
options         COMPAT_43TTY            # BSD 4.3 TTY compat (sgtty)
options         COMPAT_FREEBSD4         # Compatible with FreeBSD4
options         COMPAT_FREEBSD5         # Compatible with FreeBSD5
options         COMPAT_FREEBSD6         # Compatible with FreeBSD6
options         COMPAT_FREEBSD7         # Compatible with FreeBSD7
options         SCSI_DELAY=5000         # Delay (in ms) before probing SCSI
options         KTRACE                  # ktrace(1) support
options         STACK                   # stack(9) support
options         SYSVSHM                 # SYSV-style shared memory
options         SYSVMSG                 # SYSV-style message queues
options         SYSVSEM                 # SYSV-style semaphores
options         P1003_1B_SEMAPHORES     # POSIX-style semaphores
options         _KPOSIX_PRIORITY_SCHEDULING # POSIX P1003_1B real-time extensions
options         PRINTF_BUFR_SIZE=128    # Prevent printf output being interspersed.
options         KBD_INSTALL_CDEV        # install a CDEV entry in /dev
options         HWPMC_HOOKS             # Necessary kernel hooks for hwpmc(4)
options         AUDIT                   # Security event auditing
options         MAC                     # TrustedBSD MAC Framework
options         FLOWTABLE               # per-cpu routing cache
#options        KDTRACE_HOOKS           # Kernel DTrace hooks
options         INCLUDE_CONFIG_FILE     # Include this file in kernel

options         KDB                     # Kernel debugger related code
options         KDB_TRACE               # Print a stack trace for a panic

# To make an SMP kernel, the next two lines are needed
options         SMP                     # Symmetric MultiProcessor Kernel
device          apic                    # I/O APIC

# CPU frequency control
device          cpufreq

# Bus support.
device          acpi
device          eisa
device          pci

# Floppy drives
device          fdc

# ATA and ATAPI devices
device          ata
device          atadisk         # ATA disk drives
device          ataraid         # ATA RAID drives
device          atapicd         # ATAPI CDROM drives
device          atapifd         # ATAPI floppy drives
device          atapist         # ATAPI tape drives
options         ATA_STATIC_ID   # Static device numbering

# SCSI Controllers
device          ahb             # EISA AHA1742 family
device          ahc             # AHA2940 and onboard AIC7xxx devices
options         AHC_REG_PRETTY_PRINT    # Print register bitfields in debug
                                        # output.  Adds ~128k to driver.
device          ahd             # AHA39320/29320 and onboard AIC79xx devices
options         AHD_REG_PRETTY_PRINT    # Print register bitfields in debug
                                        # output.  Adds ~215k to driver.
device          amd             # AMD 53C974 (Tekram DC-390(T))
device          hptiop          # Highpoint RocketRaid 3xxx series
device          isp             # Qlogic family
#device         ispfw           # Firmware for QLogic HBAs- normally a module
device          mpt             # LSI-Logic MPT-Fusion
#device         ncr             # NCR/Symbios Logic
device          sym             # NCR/Symbios Logic (newer chipsets + those of `ncr')
device          trm             # Tekram DC395U/UW/F DC315U adapters

device          adv             # Advansys SCSI adapters
device          adw             # Advansys wide SCSI adapters
device          aha             # Adaptec 154x SCSI adapters
device          aic             # Adaptec 15[012]x SCSI adapters, AIC-6[23]60.
device          bt              # Buslogic/Mylex MultiMaster SCSI adapters

device          ncv             # NCR 53C500
device          nsp             # Workbit Ninja SCSI-3
device          stg             # TMC 18C30/18C50

# SCSI peripherals
device          scbus           # SCSI bus (required for SCSI)
device          ch              # SCSI media changers
device          da              # Direct Access (disks)
device          sa              # Sequential Access (tape etc)
device          cd              # CD
device          pass            # Passthrough device (direct SCSI access)
device          ses             # SCSI Environmental Services (and SAF-TE)

# RAID controllers interfaced to the SCSI subsystem
device          amr             # AMI MegaRAID
device          arcmsr          # Areca SATA II RAID
device          asr             # DPT SmartRAID V, VI and Adaptec SCSI RAID
device          ciss            # Compaq Smart RAID 5*
device          dpt             # DPT Smartcache III, IV - See NOTES for options
device          hptmv           # Highpoint RocketRAID 182x
device          hptrr           # Highpoint RocketRAID 17xx, 22xx, 23xx, 25xx
device          iir             # Intel Integrated RAID
device          ips             # IBM (Adaptec) ServeRAID
device          mly             # Mylex AcceleRAID/eXtremeRAID
device          twa             # 3ware 9000 series PATA/SATA RAID

# RAID controllers
device          aac             # Adaptec FSA RAID
device          aacp            # SCSI passthrough for aac (requires CAM)
device          ida             # Compaq Smart RAID
device          mfi             # LSI MegaRAID SAS
device          mlx             # Mylex DAC960 family
device          pst             # Promise Supertrak SX6000
device          twe             # 3ware ATA RAID

# atkbdc0 controls both the keyboard and the PS/2 mouse
device          atkbdc          # AT keyboard controller
device          atkbd           # AT keyboard
device          psm             # PS/2 mouse

device          kbdmux          # keyboard multiplexer

device          vga             # VGA video card driver

device          splash          # Splash screen and screen saver support

# syscons is the default console driver, resembling an SCO console
device          sc

device          agp             # support several AGP chipsets

# Power management support (see NOTES for more options)
#device         apm
# Add suspend/resume support for the i8254.
device          pmtimer

# PCCARD (PCMCIA) support
# PCMCIA and cardbus bridge support
device          cbb             # cardbus (yenta) bridge
device          pccard          # PC Card (16-bit) bus
device          cardbus         # CardBus (32-bit) bus

# Serial (COM) ports
device          uart            # Generic UART driver

# Parallel port
device          ppc
device          ppbus           # Parallel port bus (required)
device          lpt             # Printer
device          plip            # TCP/IP over parallel
device          ppi             # Parallel port interface device
#device         vpo             # Requires scbus and da

# If you've got a "dumb" serial or parallel PCI card that is
# supported by the puc(4) glue driver, uncomment the following
# line to enable it (connects to sio, uart and/or ppc drivers):
#device         puc

# PCI Ethernet NICs.
device          de              # DEC/Intel DC21x4x (``Tulip'')
device          em              # Intel PRO/1000 Gigabit Ethernet Family
device          igb             # Intel PRO/1000 PCIE Server Gigabit Family
device          ixgb            # Intel PRO/10GbE Ethernet Card
device          le              # AMD Am7900 LANCE and Am79C9xx PCnet
device          ti              # Alteon Networks Tigon I/II gigabit Ethernet
device          txp             # 3Com 3cR990 (``Typhoon'')
device          vx              # 3Com 3c590, 3c595 (``Vortex'')

# PCI Ethernet NICs that use the common MII bus controller code.
# NOTE: Be sure to keep the 'device miibus' line in order to use these NICs!
device          miibus          # MII bus support
device          ae              # Attansic/Atheros L2 FastEthernet
device          age             # Attansic/Atheros L1 Gigabit Ethernet
device          alc             # Atheros AR8131/AR8132 Ethernet
device          ale             # Atheros AR8121/AR8113/AR8114 Ethernet
device          bce             # Broadcom BCM5706/BCM5708 Gigabit Ethernet
device          bfe             # Broadcom BCM440x 10/100 Ethernet
device          bge             # Broadcom BCM570xx Gigabit Ethernet
device          dc              # DEC/Intel 21143 and various workalikes
device          et              # Agere ET1310 10/100/Gigabit Ethernet
device          fxp             # Intel EtherExpress PRO/100B (82557, 82558)
device          jme             # JMicron JMC250 Gigabit/JMC260 Fast Ethernet
device          lge             # Level 1 LXT1001 gigabit Ethernet
device          msk             # Marvell/SysKonnect Yukon II Gigabit Ethernet
device          nfe             # nVidia nForce MCP on-board Ethernet
device          nge             # NatSemi DP83820 gigabit Ethernet
#device         nve             # nVidia nForce MCP on-board Ethernet Networking
device          pcn             # AMD Am79C97x PCI 10/100 (precedence over 'le')
device          re              # RealTek 8139C+/8169/8169S/8110S
device          rl              # RealTek 8129/8139
device          sf              # Adaptec AIC-6915 (``Starfire'')
device          sge             # Silicon Integrated Systems SiS190/191
device          sis             # Silicon Integrated Systems SiS 900/SiS 7016
device          sk              # SysKonnect SK-984x & SK-982x gigabit Ethernet
device          ste             # Sundance ST201 (D-Link DFE-550TX)
device          stge            # Sundance/Tamarack TC9021 gigabit Ethernet
device          tl              # Texas Instruments ThunderLAN
device          tx              # SMC EtherPower II (83c170 ``EPIC'')
device          vge             # VIA VT612x gigabit Ethernet
device          vr              # VIA Rhine, Rhine II
device          wb              # Winbond W89C840F
device          xl              # 3Com 3c90x (``Boomerang'', ``Cyclone'')

# ISA Ethernet NICs.  pccard NICs included.
device          cs              # Crystal Semiconductor CS89x0 NIC
# 'device ed' requires 'device miibus'
device          ed              # NE[12]000, SMC Ultra, 3c503, DS8390 cards
device          ex              # Intel EtherExpress Pro/10 and Pro/10+
device          ep              # Etherlink III based cards
device          fe              # Fujitsu MB8696x based cards
device          ie              # EtherExpress 8/16, 3C507, StarLAN 10 etc.
device          sn              # SMC's 9000 series of Ethernet chips
device          xe              # Xircom pccard Ethernet

# Wireless NIC cards
device          wlan            # 802.11 support
options         IEEE80211_DEBUG # enable debug msgs
options         IEEE80211_AMPDU_AGE # age frames in AMPDU reorder q's
options         IEEE80211_SUPPORT_MESH  # enable 802.11s draft support
device          wlan_wep        # 802.11 WEP support
device          wlan_ccmp       # 802.11 CCMP support
device          wlan_tkip       # 802.11 TKIP support
device          wlan_amrr       # AMRR transmit rate control algorithm
device          an              # Aironet 4500/4800 802.11 wireless NICs.
device          ath             # Atheros pci/cardbus NIC's
device          ath_hal         # pci/cardbus chip support
options         AH_SUPPORT_AR5416       # enable AR5416 tx/rx descriptors
device          ath_rate_sample # SampleRate tx rate control for ath
device          ral             # Ralink Technology RT2500 wireless NICs.
device          wi              # WaveLAN/Intersil/Symbol 802.11 wireless NICs.
#device         wl              # Older non 802.11 Wavelan wireless NIC.

# Pseudo devices.
device          loop            # Network loopback
device          random          # Entropy device
device          ether           # Ethernet support
device          vlan            # 802.1Q VLAN support
device          tun             # Packet tunnel.
device          pty             # BSD-style compatibility pseudo ttys
device          md              # Memory "disks"
device          gif             # IPv6 and IPv4 tunneling
device          faith           # IPv6-to-IPv4 relaying (translation)
device          firmware        # firmware assist module

# The `bpf' device enables the Berkeley Packet Filter.
# Be aware of the administrative consequences of enabling this!
# Note that 'bpf' is required for DHCP.
device          bpf             # Berkeley packet filter

# USB support
options         USB_DEBUG       # enable debug msgs
device          uhci            # UHCI PCI->USB interface
device          ohci            # OHCI PCI->USB interface
device          ehci            # EHCI PCI->USB interface (USB 2.0)
device          usb             # USB Bus (required)
#device         udbp            # USB Double Bulk Pipe devices
device          uhid            # "Human Interface Devices"
device          ukbd            # Keyboard
device          ulpt            # Printer
device          umass           # Disks/Mass storage - Requires scbus and da
device          ums             # Mouse
device          urio            # Diamond Rio 500 MP3 player
# USB Serial devices
device          u3g             # USB-based 3G modems (Option, Huawei, Sierra)
device          uark            # Technologies ARK3116 based serial adapters
device          ubsa            # Belkin F5U103 and compatible serial adapters
device          uftdi           # For FTDI usb serial adapters
device          uipaq           # Some WinCE based devices
device          uplcom          # Prolific PL-2303 serial adapters
device          uslcom          # SI Labs CP2101/CP2102 serial adapters
device          uvisor          # Visor and Palm devices
device          uvscom          # USB serial support for DDI pocket's PHS
# USB Ethernet, requires miibus
device          aue             # ADMtek USB Ethernet
device          axe             # ASIX Electronics USB Ethernet
device          cdce            # Generic USB over Ethernet
device          cue             # CATC USB Ethernet
device          kue             # Kawasaki LSI USB Ethernet
device          rue             # RealTek RTL8150 USB Ethernet
device          udav            # Davicom DM9601E USB
# USB Wireless
device          rum             # Ralink Technology RT2501USB wireless NICs
device          uath            # Atheros AR5523 wireless NICs
device          ural            # Ralink Technology RT2500USB wireless NICs
device          zyd             # ZyDAS zb1211/zb1211b wireless NICs

# FireWire support
device          firewire        # FireWire bus code
#device         sbp             # SCSI over FireWire (Requires scbus and da)
device          fwe             # Ethernet over FireWire (non-standard!)
device          fwip            # IP over FireWire (RFC 2734,3146)
device          dcons           # Dumb console driver
device          dcons_crom      # Configuration ROM for dcons
freebsd#

配置完成后,按ESC键,然后提示按"a"后再按"a"就能够把配置文件保存。

  

  三、编译内核:

  内核文件配置好以后就能够进行内核的编译了,一般有两种编译的方式,我们采取传统的编译方式。  
  # cd /usr/src/sys/i386/conf

  运行config命令来产生内核源代码。

  # /usr/sbin/config GENERIC

  切换到建立内核的目录。

  # cd ../compile/GENERIC

  编译内核

  # make depend
  # make

  安装新内核。

  # make install

OK,到这里,如果中间没有出现任何错误的话,那么我们的内核心就已经安装成功了,reboot后就能够使用我们的新编译的内核了。如果出现了

错误,那么请检查你的步骤是否跟上面的步骤一致,同时要检查你的内核配置文件配置的是否正确,一般编译不成功都是内核文件配置的问题请仔细检查。

  

  四、新内核无法启动:

  如果你编译的内核无法启动,那么可以使用以前的内核来启动。一般编译一次内核后,都会把把旧内核备份,一般/boot/kernel.old就是旧内

  核的备份,出现问题就能够使用久内核来启动。

  具体实现方法是:
  你可以在系统启动进行10计数的时候按Enter以外的任何键, 接着键入unload命令,再键入boot kernel.old,或者任何能正常启动的内核名字

  ,然后就能够正常启动系统,进入系统后再重新进行内核的配置工作。

  注意: 你不能仅依靠kernel.old,因为当你安装一个新内核时, kernel.old会被上一次安装的内核所覆盖,所以你要么自己手动备份一个能

  正常启动的内核,或者注意你的kernel.old是否能正常启动的内核。

  

  结束

  好,到这里,我们的编译内核的工作就完成了,来然我们来看看我们的内核是否已经减小了:

  # ls -l /boot/kernel/kernel
  -r-xr-xr-x 1 root wheel 3090929 Sep 1 21:30 /boot/kernel/kernel

  呵呵,明显把原来的5940286变成了现在的3090929,虽然没有变小一倍,但是也变小好多啦,以后系统又更快啦!

  FreeBSD中文手册: http://www.freebsd.org.cn/snap/doc/zh_CN.GB2312/books/handbook/index.html
  内核配置参考: http://www.freebsd.org.cn/snap/doc/zh_CN.GB2312/bos/handbook/kernelconfig.html