The_Linux_Kernel_Module_Programming_Guide_2.6中文版
- 格式:pdf
- 大小:520.67 KB
- 文档页数:87
Debian Linux系统下的内核编译详细讲解1. 传统方式直接在console中编译官方内核,需要以下软件包bin86 - 16-bit assembler and loaderdiff - File comparison utilitieslibc6-dev - GNU C Library: Development Libraries and Header Files libncurses5-dev - Developer's libraries and docs for ncursespatch - Apply a diff file to an original2.使用2.4.x内核的图形界面配置程序(make xconfig,还需要tk8.4 - Tk toolkit for Tcl and X11, v8.4 - run-time files使用2.6.x内核的Qt图形界面配置程序(make xconfig,还需要libqt3-mt-dev - Qt development files (Threaded使用2.6.x内核的GTK图形界面配置程序(make gconfig,还需要libgtk2.0-dev - Development files for the GTK+ library3. 如果您想制作内核的deb包,还需要debianutils - Miscellaneous utilities specific to Debiankernel-package - A utility for building Linux kernel related Debian package ksymoops - Linux kernel oops and error message decoder内核编译/doc/manuals/reference/ch-kernel.zh-cn.htmlDebian unstable发行版中的gcc、binutils和modutils可用来编译最新的Linux 内核。
Serial Programming HOWTOLinux 串口编程中英文简体对照1.0版翻译: Carol Li原作:Gary Frerking gary@ Peter BaumannThis document describes how to program communications with devices over a serial port on a Linux box.本文档记述了如何在Linux设备上通过串口进行通信的程序开发中文简体版以英文 1.01 版为原文,同时参考了繁体中文的串口编程HOWTO1.Introduction 简介This is the Linux Serial Programming HOWTO. Allabout how to program communications with otherdevices / computers over a serial line underLinux. Different techniques are explained:Canonical I/O (only complete lines aretransmitted/received), asyncronous I/O, andwaiting for input from multiple sources.This is the first update to the initial releaseof the Linux Serial Programming HOWTO. Theprimary purpose of this update is to change theauthor information and convert the document toDocBook format. In terms of technical content,very little if anything has changed at thistime. Sweeping changes to the technical content aren't going to happen overnight, but I'll work on it as much as time allows.If you've been waiting in the wings for someone to take over this HOWTO, you've gotten yourwish. Please send me any and all feedback youhave, it'd be very much appreciated.All examples were tested using a i386 LinuxKernel 2.0.29.本文是为 Linux 串口程序编写的 HOWTO. 主要讨论如何在 Linux 环境下,编写串口与其它计算机设备进行通讯的程序。
RN_05071-R21 | October 18, 2017 Advance Information | Subject to Change Release NotesRN_05071-R21Table of Contents1.0About this Release (3)1.1Login Credentials (3)1.2Top Fixed Issues (3)2.0Known Issues (6)3.0Implementation Notes (7)3.1GStreamer 1.0 Support (7)3.2Updates to CPU Clock Frequencies and Voltages (7)3.3Fuse Devices as Late In Process as Possible (7)4.0About Earlier Releases (8)Release 21.5, 13 Jul 2016 (8)Release 21.4, 10 Jul 2015 (9)Release 21.3, 26 Feb 2015 (12)1.0The NVIDIA® Tegra® Linux Driver Package supports development of platforms running: ④NVIDIA® Tegra® K1 32 Bit series computer-on-a-chip④Linux kernel 3.10.40④Git tag for the release: tegra-l4t-r21.61.1Login CredentialsThe default Jetson TK1 login credentials are:④Username: ubuntu④Password: ubuntuNote: A debug console is available via female-to-female NULL modem cable.The console is not password protected.1.2Top Fixed IssuesThe resolved issues are as follows, for a complete list of kernel fixes, see:https:///gitweb/?p=linux-3.10.gitRefer to l4t/l4t-r21 under heads to see the complete list of kernel changes.The release tag for this release is tegra-l4t-r21.6.I/O Bus InterfaceI/O Bus interfaces related issues resolved in this release are as follows.MemoryMemory related issues resolved in this release are as follows.MultimediaMultimedia related issues resolved in this release are as follows.2.0This section provides details about issues that were discovered during development and QA but not resolved prior to this release of the Tegra Linux Driver Package.3.03.1GStreamer 1.0 SupportThis release includes Gstreamer 1.0 support. The Nvgstplayer application defaults to Gstreamer 0.1. To run the 1.0 version, use the full path to the binary.3.2Updates to CPU Clock Frequencies and VoltagesCPU clock frequencies for UCM1 and UCM2, and CPU voltages for UCM2 are updated in this release to reflect guaranteed maximum frequencies for Tegra K1 processors over the operating lifetime of the product. There are no changes to other clocks, specifications, or voltages.You must update the L4T software release to R21.5 or following. See the Jetson TK1 Datasheet for more information about these specifications.3.3Fuse Devices as Late In Process as PossibleDo not fuse for secure boot until the very end of the manufacturing process. Failure analysis by NVIDIA, as part of the RMA process, is not possible with fused devices.4.0Release 21.5, 13 Jul 2016What’s NewThis release fixes some issues that were found during continued testing and adds/enhances the following feature(s).④Updates for CPU clock frequencies (UCM1 and UCM2), and CPU voltages (UCM2). SeeUpdates to CPU Clock Frequencies and Voltages.④Added support for Hynix H5TC4G63CFR-RDA as an alternate DRAM for Jetson TK1.Updated BCT and EMC-DVFS tables are present to support this part. The updated BCT and kernel provide support for both DRAM based upon RAMCODE strapping options. Top Issues Fixed Since Last ReleaseThe following issues have been resolved in this release. for a complete list of kernel fixes, see the following web site:/gitweb/?p=linux-3.10.git;a=shortlog;h=refs/heads/l4t/l4t-r21.5System[200127047] cudaStreamAttachMemAsync bonds unified memory, memory consumption is accumulated until overflowKernel[200146488] OpenOCD JTAG debugging support needed[200141741] Kernel oops after rmmod g_ether.ko in device mode of OTG[1726087] xhci controller stops working after wireless dongle removal[1709814] Kernel crash during reboot stress with MSELECT error and kernel exception: "drivers/platform/tegra/hier_ictlr/hier_ictlr.c:54"Multimedia[200208334] Windows created by video playback using URI option of nvgstplayer-0.10 are not automatically closed[1775740] H.264 support needed for Main and High Profile in omxh264enc (gstreamer plugin)Camera[200215774] Low FPS at 1280x720 with USB camera (USB 2.0)[200204206] CSI preview launch is unsuccessful with first attempt on boot [200106274] Errors displayed while launching CSI cameraPower[200205110] Device shuts down when we wake up from Deep Sleep (LP0) by pressing power button[1679372] nvprof disables GPU rail gatingRelease 21.4, 10 Jul 2015What’s New In this ReleaseThis release fixes some issues that were found during continued testing and adds/enhances the following feature(s).④[1566270] Enabled Tegra system profiler④[1644596] Fixed gst-omx compile time errors, added README and source files④[1551864] Updated Jetson TK1 pinmux configuration④[1542346] Rework of modeswitch/vt-switch handling in X/OpenGL④[1487603] xhci firmware cfgtbl and logging enhancements④[888312] Enabled and tuned CPU frequency boost on input event④[1568275] Adds support for ABI 17, 18 and 19④[1649593] Image rotation support documentation④[1625262] Improved device tuning on Jetson TK1Top Issues Fixed Since Last ReleaseThe following issues have been resolved in this release.System④[200046014] X crashes due to segmentation fault④[200081242] System does not wake from Suspend (LP1)④[200094751] Issues with loading libcuda.so.1.1④[200084665] “N o space left on device” error displayed with enough space available ondevice④[200077334] TegraK1 GPU error displays when GPU is locked at a high frequency④[200062085 ] read_ahead_kb size of removable SDcards/MicroSDs resets to 128 from 2048after hotplug, leading to proportional drop in read performance④[200040915 ] "xHCI xhci_drop_endpoint called with disabled ep ea70d3c0" errordisplayed from xhci.c and connection is reset when connecting USB 3.0 hub to Belkin USB 3.0 hub④[200036424] System becomes unresponsive when entering Deep Sleep (LP0) when HDMIis disconnected after boot④[200032923] While pmu_destroy is running there is a possibility pmu init is scheduled ina different thread, causing exception④[200006918] Incorrect board revision present in major_revision causing board specificservices and settings to be unsuccessful④[1640551] Long delays occur in nvmap during boot④[1639229] Memory leak and performance degradation occur when changing EGLcontexts④[1599195] Need correct settings for VBR (constant QP) mode④[1596489] No support for null buffers as arguments in glDeleteBuffers()④[1581432] Need Tegra WDT FIQ function enabled④[1580265] HDMI parent clock frequency calculation incorrect in some casesKernel④Added Tegra Profiler support④Enabled Watch Dog Timer support④Fixed race condition in programming PTC flush registers. This race condition results inPTC flush not happening as intended and can cause either SMMU fault or previous stale mapping access④Improved SATA stability④Improved vic frequency scaling tuning parameter④Modified the way we load nvhost firmware④[200057068] Removed invalid gk20a memory allocation error message④[200087363] Linux kernel headers include x86 ELF files causing unsuccessful on-boardmodule compilationDisplay④[200102860] Display is blank after hot plugging HDMI after boot④[1467960] oom-killer invocation occurs with heavy graphical corruption and screenblanking in low memory situations when stress testing screen orientation changes④[200080781] Mode setting unsuccessful for some refresh rates④[200081502] MSELECT error and kernel exception display during reboot stress testing Graphics④ [200101677] Race condition in omx-il while loading EGL library④[1617701] Using EGLImage for fast CPU read/write access on textures and framebufferscauses segmentation fault④[200036737] X crashes due to invalid eventMultimedia④[200116564]Audio corruption from first aplay playback after reboot④[200107328] Added DRC support in gst-omx 1.0④[200106354] Nvgstplayer-1.0 video playback windows (created with URI option) notautomatically closed④[200102340 ] Sequential image capture using run time command (j:<count>) with a USBcamera is unsuccessful with nvgstcapture-0.10④[200100485] Decoding interlace video crashes when POC=2④[200100179] Playback of captured video (using H.264 encode and AVI container) isunsuccessful④[200099694 ] No audio heard from nvgstplayer-1.0 playback of 00001.MTS④[200098386] Support for resizing and positioning of the overlay screen with gstreamer-1.0 needed④[200091380] Playback of low bit-rate WAV audio files with nvgstplayer-0.10 and aplay isunsuccessful④[200087353] Need insertion of SPS/PPS at IDR/I frame④[1612520] Audio corruption occurs when playing video through some applications④[200078535] Multi channel audio file playback with nvgstplayer-0.10 is unsuccessful④[200078609] "Creation of video pipeline failed" message displays when stopping andresuming RTSP streams that include both audio and video④[200077258] Corruption displayed during playback of video captured with a USBcamera with MPEG4 encoder and MP4 container④[200071832] Loop-forever functionality is not working in nvgstplayer-1.0④[200062801] Audio corruption heard from long-duration MP3 RTSP streaming④[200040752] Audio plays through HDMI when audio output device selected is Speakers(tegra-rt5639), after reboot④[200025919] Need support for setting width, height and position of window innvgstplayer④[200003429] Multi-channel audio playback through audio receiver via HDMI is notproperly rendered④ [1646878] omxh264dec plugin may cause decode pipeline deadlock④[1645989J PEG Decoding to NVMM type yuv needed④[1640447] Image rotation support needed④[1628974] Memory leak in gstreamer pipeline④[1628147] Auto MIPI calibration in V4L2 driver needed④ [1618581] Nvmap buffer leak occurs in nvgstreamer decode plugin④[1611835] Need support for iframeinterval parameter in gst-omx plugin for gstreamer ④[1503770] USB headset not automatically listed as audio output device in sound settings④[1458105] RTSP stream playback unsuccessful④[1456080] nvvidconv-1.0 code cleanup and replacement for deprecated implementation ④[200077151] Fixed caps negotiation in case of nvmm to raw conversion for nvcamerasrcin gst-nvvidconv-1.0④[200074271] Segmentation fault occurs when switching to video mode in Nvgstcapture-1.0Camera④[200111272] No discernable difference between preview and capture with AEROIselected④[200081357] Capture with nvgstcapture-1.0 inside a sudo user created directory causessegmentation fault④[200080744] No nvgstcapture option to select a specific USB camera when multiple USBcamera devices are connected④[200081334] Unable to stop image capture with user interrupt on first attempt④[200080743] Corruption and grey areas occur in video and image preview and captureat 1280x720 resolution with USB HD camera④ [200074282] Running out of memory during 25000 image capture stress testing withnvgstcapture-1.0, USB camera, and hdmioverlaysink results in segmentation fault④[1581879] Camera timeout occurs with suspend and resume when the lock screen isdisabledRelease 21.3, 26 Feb 2015W hat’s New In this ReleaseThis release fixes some issues that were found during continued testing and adds/enhances the following feature(s).④Implemented skip-frames and disable-dpb properties for gst-omx plugin. See L4TMultimedia User Guide for more information.④Added encoding and scaling support in gst-nvvidconv-1.0. See L4T Multimedia UserGuide for more information.④Tegra watchdog support④Enabled ramoops debugging support④CSI_B/CSI_C support in Tegra V4L2/soc_camera driverTop Issues Fixed Since Last ReleaseThe following issues have been resolved in this release.System④[1506870] Unnecessary debug messages from NVAVP kernel code display④[1549799] Improved flashing tools compatibility with additional eMMC devices whereboot partition size differ from Jetson TK 1④[1561360] Intermittent "azx_get_response" kernel warning displays during systemtesting④[1582388] Intermittent “k ernel_warning: "hda-intel azx_get_response timeout" warningdisplays during system testing④[200015967] The error “gk20a gk20a.0: gk20a_fifo_hand le_sched_error: fifo is waiting forctx swi tch for 100 ms,ch = 3” may occur when running WebGL applications④[200054390] Support RAM sizes for 4GB or greater in U-Boot④[1551864] Updated pinmux for Jetson TK 1 devices④[200046876] Resolved memory leak in gst-openmax④[200067410] Resolved issues related to use of Tegra-profiler④[200072946] Improved system stability during extended reboot stress testing④[200020671, 200031813] Improved compatibility with HDMI TVs and resiliency forunsupported modes④[1577947, 1435870] Improved stability of gk20a GPU driver④[200048667] Removed debug messages when loading VIC firmware④[200055546] Resolved gk20a stability issues regarding “gk20a_pmu_isr: pmu halt intrnot implemente d”④[200016313] Resolved gk20a stability issues regard ing “gk20a_pmu_enable_elpg():possible elpg refcnt mismatch“④[1557711] Enabled devsleep functionality only for mSATA connectors (disable devsleepon Jetson TK 1 SATA). This resolved issues on detection of certain SATA drives④[1566598] Improved stability of Jetson TK1 on-board EthernetCamera④[200074274] Resolved preview resolution switching with USB cameras in Nvgstcapture-1.0④[200063275] Fixed issue with 1080p encoding in Nvgstcapture-0.10④[200060263] Corrected preview resolution in Nvgstcapture-0.10④[200062376] Changed default preview sink in Nvgstcapture-1.0④[200049907] Resolved pauses during video recording specific to USB webcam inNvgstcapture-0.10④[200074237] Resolved cosmetic error messages when using USB cameras inNvgstcapture-1.0Multimedia④[200053327] Resolved errors in continuous encoding and decoding in libjpeg-8bhardware acceleration④[200067781] Fixed crash in port audio④[200045113] Improved H.264 decode latency④[1575862, 1576116] Resolved crash in H.264 decoder when video stream containsmultiple segments with different resolutions.④[200057071] Resolved infrequent error of “X Error of failed request: BadIDChoice” inNvgstplayerPower and Performance④[200070160] 792 megahertz (Mhz) BCT needs to be updated has incorrect memoryswizzleNoticeALL NVIDIA DESIGN SPECIFICATIONS, REFERENCE BOARDS, FILES, DRAWINGS, DIAGNOSTICS, LISTS, AND OTHER DOCUMENTS (TOGETHER AND SEPARATELY, "MATERIALS") ARE BEING PROVIDED "AS IS." NVIDIA MAKES NO WARRANTIES, EXPRESS, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO THE MATERIALS, AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OR CONDITION OF TITLE, MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE AND ON-INFRINGEMENT, ARE HEREBY EXCLUDED TO THE MAXIMUM EXTENT PERMITTED BY LAW.Information furnished is believed to be accurate and reliable. However, NVIDIA Corporation assumes no responsibility for the consequences of use of such information or for any infringement of patents or other rights of third parties that may result from its use. No license is granted by implication or otherwise under any patent or patent rights of NVIDIA Corporation. Specifications mentioned in this publication are subject to change without notice. This publication supersedes and replaces all information previously supplied. NVIDIA Corporation products are not authorized for use as critical components in life support devices or systems without express written approval of NVIDIA Corporation.TrademarksNVIDIA and the NVIDIA logo are trademarks or registered trademarks of NVIDIA Corporation in the United States and other countries. Other company and product names may be trademarks of the respective companies with which they are associated.Copyright© 2016 NVIDIA Corporation. All rights reserved.。
实验1 Linux模块定义与操作本实验在Linux2.6内核的环境下,演示了模块的符号表导出以及模块参数机制。
1.1实验目的1. 练习简单模块的编写;2. 熟悉模块的符号表;3. 熟悉模块的参数使用方法。
1.2 实验原理1.2.1 内核编程的注意事项首先,Linux可以运行在两种模式下:用户模式(user mode)和内核模式(kernel mode)。
当我们编写一个普通程序时,常常会引用stdlib.h文件,就代表我们要使用C标准库,这是在用户空间的做法,用户空间的应用程序也要链接标准C库。
而在内核模式下不存在libc库,也就没有这些函数供我们调用,因此,我们在内核模式下编程也存在一些限制:不能使用浮点运算。
因为Linux内核在切换模式时不保存处理器的浮点状态。
不要让内核程序忙等。
Linux操作系统本身是抢占式的,但是在内核是非抢占内核,就是说用户空间的程序可以抢占运行,但是内核空间程序不可以。
在内核里一个用时1秒的循环看上去就像是把整个系统挂起了1秒,并且在这段时间里其他什么工作也做不了。
尽可能保持代码的清洁。
内核调试是一个十分痛苦的过程,因此,前期代码编写的过程中保持代码的清洁易懂,将大大方便后期的调试。
1.2.2 Linux的模块机制从2.4到2.6:Linux内核可装载模块机制的改变:1. 模块编译从2.4到2.6,外部可装载内核模块的编译、连接过程以及Makefile的书写都发生了改变。
2.4内核中,模块的编译只需内核源码头文件;需要在包含linux/modules.h之前定义MODULE;编译、连接后生成的内核模块后缀为.o。
2.6内核中,模块的编译需要配置过的内核源码;编译、连接后生成的内核模块后缀为.ko;编译过程首先会到内核源码目录下,读取顶层的Makefile文件,然后再返回模块源码所在目录。
2.6内核模块的Makefile模板:KERNELRELEASE是在内核源码的顶层Makefile中定义的一个变量,在第一次读取执行此Makefile时,KERNELRELEASE没有被定义,所以make将读取执行else之后的内容。
linux26 字符驱动笔记适用于Linux的2.6.10以后的内核。
笔记以LinuxDeviceDriver3提供的scull程序(scull目录中的main.c和scull.h)为记录主线,并以该驱动程序中的各种系统调用和函数调用流程为记录顺序。
比如,module_init( )和module_exit()为相对应的一对系统调用,一般书籍中都会放在一起讨论,但是本笔记却不会这样,而是在需要调用的时候才会涉及,因此module_init( )会放在笔记开始时,也就是刚加载module时讨论,而module_exit( )则会放在笔记结束前,也就是要卸载module时再加以讨论。
该笔记的的目的是为了对Linux Device Drvier3中提到的各个知识点作一下整理,理清一下头绪,从而能让我对Linux驱动程序加深整体或者全局上的理解。
注:个人理解,有误难免!*******************************************驱动程序module的工作流程主要分为四个部分:1、用Linux提供的命令加载驱动module2、驱动module的初始化(初始化结束后即进入“潜伏”状态,直到有系统调用)3、当操作设备时,即有系统调用时,调用驱动module提供的各个服务函数4、卸载驱动module一、驱动程序的加载Linux驱动程序分为两种形式:一种是直接编译进内核,另一种是编译成module形式,然后在需要该驱动module时手动加载。
对于前者,还有待学习。
Module形式的驱动,Linux提供了两个命令用来加载:modprobe和insmod。
其中modprobe可以解决驱动module的依赖性,即假如正加载的驱动module若引用了其他module提供的内核符号或者其他资源,则modprobe就会自动加载那些module,不过,使用modprobe时,必须把要加载的驱动module放在当前模块搜索路径中。
编译内核详解(linux-2.6.34)2010-06-20 by 李阳mail: kmalloc@ 1. 下载源代码1.1 下载到内核源码官方网站/下载或,$wget /pub/linux/kernel/v2.6/linux-2.6.34.tar.bz21.2 解压源码$cd ~/src$tar xjvf linux-2.6.34.tar.bz22. 编译软件准备(ubuntu)2.1 在ubuntu系统安装编译内核需要的软件包$sudo apt-get install build-essential kernel-package libncurses5-dev2.2 清理以前编译时留下的临时文件如果是刚刚解开的包,不需要执行这步。
如果是第二次或者是第n次编译,那么一定要执行。
$cd linux-2.6.34$make mrproper2.3 拷贝已有的配置文件$cp /boot/config-`uname -r` ./.config2.4 自动精简内核配置(将你需要用的所用硬件都插在电脑上, 这样会根据现在电脑链接的硬件进行自动配置一下,也可以省略此步)make localmodconfig3. 配置内核3.1 配置内核的工具方法一:$make menuconfig方法二:xconfig. 安装xconfig$sudo apt-get install libqt3-headers libqt3-mt-dev libqt3-compat-headers libqt3-mt. 使用xconfig配置内核$sudo make xconfig. xconfig选项意义:圆中点是编译成可以随时加人的模块(以下简称M),方块中一勾是编译进入内核(以下简称Y),空就是不要(简称N)3.2 内核配置及优化General setup --->[* ] Prompt for development and/or incomplete code/drivers <=== 显示尚在开发中或尚未完成的代码和驱动. 我不是内核或驱动开发人员。
Linux Kernel学习笔记 Table of Contents 1. 存储器寻址 2. 设备驱动程序开发 3. 字符设备驱动程序 3.1. 设备号 3.2. 设备号的分配和释放 3.3. 重要的数据结构 3.4. 读和写 4. PCI设备 5. 内核初始化优化宏 6. 访问内核参数的接口 7. 内核初始化选项 8. 内核模块编程 8.1. 入门 8.2. 为模块添加描述信息 8.3. 内核模块处理命令介绍 9. 网络子系统 9.1. sk_buff结构 9.2. sk_buff结构操作函数 9.3. net_device结构 9.4. 网络设备初始化 9.5. 网络设备与内核的沟通方式 9.6. 网络设备操作层的初始化 9.7. 内核模块加载器 9.8. 虚拟设备 9.9. 8139too.c源码分析 9.10. 内核网络数据流 10. 备忘录
Chapter 1. 存储器寻址 在80x86微处理器中,有三种存储器地址: 逻辑地址(logical address),包含在机器语言指令中用来指定一个操作数或一条指令的地址。每个逻辑地址都由一个段(segment)和一个偏移量(offset)组成。偏移量指明了从段的开始到实际地址之间的距离。 线性地址(linear address)(也称为虚拟地址,virtual address),它是一个32位无符号整数,可用以表达高达4G的地址(2的32次方)。通常以十六进制数表示,值的范围从0X00000000到0Xffffffff。 物理地址(physical address),用于存储器芯片级存储单元寻址,它们与从微处理器的地址引脚发送到存储器总线上的电信号相对应。物理地址由32位无符号整数表示。
CPU控制单元通过一种称为分段单元(segmentation unit)的硬件电路把一个逻辑地址转换成线性地址;线性地址又通过一个分页单元(paging unit)的硬件电路把一个线性地址转换成物理地址。
UIS8910DM Programming Guide声明Statement本文件所含数据和信息都属于紫光展锐所有的机密信息,紫光展锐保留所有相关权利。
本文件仅为信息参考之目的提供,不包含任何明示或默示的知识产权许可,也不表示有任何明示或默示的保证,包括但不限于满足任何特殊目的、不侵权或性能。
当您接受这份文件时,即表示您同意本文件中内容和信息属于紫光展锐机密信息,且同意在未获得紫光展锐书面同意前,不使用或复制本文件的整体或部分,也不向任何其他方披露本文件内容。
紫光展锐有权在未经事先通知的情况下,在任何时候对本文件做任何修改。
紫光展锐对本文件所含数据和信息不做任何保证,在任何情况下,紫光展锐均不负责任何与本文件相关的直接或间接的、任何伤害或损失。
All data and information contained in or disclosed by this document is confidential and proprietary information of UNISOC and all rights therein are expressly reserved. This document is provided for reference purpose, no license (express or implied, by estoppel or otherwise) to any intellectual property rights is granted by this document, and no express and implied warranties, including butwithout limitation, the implied warranties of fitness for any particular purpose, and non-infringement, as well as any performance. By accepting thismaterial, the recipient agrees that the material and the information contained therein is to be held in confidence and in trust and will not be used, copied, reproduced in whole or in part, nor its contents revealed in any manner to others without the express written permission of UNISOC. UNISOC may make any changes at any time without prior notice. Although every reasonable effort is made to present current and accurate information, UNISOC makes no guarantees of any kind with respect to the matters addressed in this document. In no event shall UNISOC be responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with the use of or reliance on any such content.CONTENTS: 1Getting Start11.1Overview (1)1.2Linux Build (2)1.3Windows Build (3)1.4Kconfig (4)1.5menuconfig (4)1.6guiconfig (5)2Architecture72.1Overview (7)2.2Bootloader (10)2.3HAL(Hardware Abstract Layer) (11)2.4OSI(OS Interface) (11)2.5libc (11)2.6Driver (11)2.7File System (12)2.8IPC/RPC (12)2.9CFW(Communication FrameWork) (12)2.10PS Interface (12)2.11TCP/IP (12)2.12COAP/LWM2M/ (12)2.13AT Receiver (12)2.14Open CPU (13)3Flash Layout153.1Overview (15)3.2Bootloader (16)3.3Application (16)3.4System FS (17)3.5Modem FS (17)3.6Factory FS (17)3.7Configurations (17)3.8Frequently Overwrite Small File (18)4Kernel(OS Interface)19i4.1Overview (20)4.2Thread (20)4.3osiEvent_t (20)4.4Thread Callback (21)4.5Thread Notify (22)4.6Semaphore (22)4.7Mutex (22)4.8Work and Work Queue (22)4.9Interrupt Latency (23)4.10ISR Programming (23)4.11Timer (24)4.12Elapsed Timer (26)4.13Power management (26)4.14Cache (28)4.15atomic (28)4.16Floating Point (28)4.17FreeRTOS Integration (29)4.18API Reference (30)5OSI Libraries735.1Overview (73)5.2Event Hub and Event Dispatch (73)5.3FIFO (74)5.4Value String Map (74)5.5Memory Recycler (74)5.6Generic List (76)5.7Event Hub and Dispatch API Reference (76)5.8FIFO API Reference (80)5.9Value String Map API Reference (83)5.10Memory Recycler API Reference (89)5.11Generic List API Reference (91)6C++Language936.1Compiling Options (93)6.2Global Object (93)6.3Static Object (94)7Clock Management957.1clk_sys Callback (96)7.2Fix clk_sys Constrain (96)7.3Hardware Minimal Clock Constrain (96)7.4Software Minimal Clock Constrain (96)7.5Hardware External RAM Access Constrain (97)7.6Hardware Clock Constrain and PM Source (97)7.7Reapply Constrains (97)7.8Thread Safe (98)7.9API Reference (98)8Memory Management103 ii8.1Overview (103)8.2Pool Type (104)8.3Reference Count (104)8.4Pattern Check (104)8.5Alignment (104)8.6Thread Safe and ISR (105)8.7Limitation (105)8.8API Reference (105)9Trace1139.1Overview (113)9.2Format String (113)9.3Trace Level (114)9.4Trace Tag (114)9.5Trace ID (115)9.6Basic and Extended (115)9.7API Reference (116)10SFFS(Small Flash File System)11910.1Overview (119)10.2Flash Block Device (120)10.3SFFS Blocks (121)10.4Power Failure Safe (121)10.5vfs_sfile_write (121)10.6Quick Format (122)10.7Memory Usage (122)10.8EBUSY (122)10.9Flash Block Device API Reference (123)10.10SFFS VFS API Reference (125)10.11SFFS API Reference (126)11CFW Event Dispatch13711.1Overview (137)11.2UTI Management (140)11.3Thread Safe (140)11.4API Reference (140)12IPC(Inter-Processor Communication)14312.1Overview (143)12.2Shared Registers (144)12.3Shared Memory Layout (144)12.4Thread Safe (145)12.5API Reference (145)13PS IPC Interface15313.1Overview (153)13.2Thread Safe (153)13.3API Reference (153)iii14RPC(Remote Procedure Call)15714.1Overview (158)14.2Function Call (160)14.3Event (160)14.4Code Generation (161)14.5XML by Example (162)14.6Event Router (166)14.7Dead Lock (166)14.8Command Queue (166)14.9API Reference (166)15AT Receiver Engine17315.1Overview (173)15.2AT Engine Process Flow (174)15.3AT Settings (176)15.4AT Command Line Parsing (176)15.5AT Command Parameter (177)15.6AT Response (177)15.7Add an AT command (178)15.8AT Command Asynchronous Context (179)15.9AT and SIM (179)15.10Speech Call (179)15.11Memory Free Later (180)15.12AT Engine API Reference (180)15.13AT Parameter API Reference (200)15.14AT Response API Reference (212)16Firmware Update21916.1Firmware Update in Application (219)16.2Firmware Update in Bootloader (220)16.3FUPDATE_RESULT_CANNT_START (220)16.4Files for Firmware Update (220)16.5API Reference (221)17IOMUX22717.1Overview (227)17.2API Reference (228)18Hardware Spinlock22918.1Overview (229)18.2API Reference (229)19GPIO23119.1Overview (231)19.2API Reference (231)20ADI bus for PMIC23520.1Overview (235)20.2API Reference (235)iv21PMIC Interrupt23721.1Overview (237)21.2API Reference (237)22SPI Flash24122.1Overview (241)22.2API Reference (241)23RTC and Alarm24723.1Overview (247)23.2API Reference (247)24Uart Driver25324.1Overview (253)24.2API Reference (253)25Axidma Driver26125.1Overview (261)25.2API Reference (261)26PMIC ADC26526.1Overview (265)26.2API Reference (265)27I2c Driver26927.1Overview (269)27.2API Reference (269)28IFC27328.1Overview (273)28.2Auto Mode (274)28.3Interrupt (274)28.4Channels (274)28.5Cache Coherence (275)28.6Thread Safe (275)28.7API Reference (275)29PPP Guides27929.1Linux (279)29.2Windows (281)30Coding Style Guide28330.1Copyright Header (284)30.2Indent (284)30.3Line Length (284)30.4File Name Convention (284)30.5Function Name Convention (284)30.6Static Functions (285)30.7Local Variable Name Convention (285)30.8Global Variable Name Convention (285)v30.9Struct Name Convention (285)30.10enum (286)30.11C++Class,Method and Member Name (286)30.12stdint,stdbool (287)30.13const,void* (287)30.14Object Oriented (287)30.15extern (287)30.16Global Variables (288)30.17Public Header (288)30.18extern“C” (288)30.19Parameter Checking (288)30.20Return bool or int (289)30.21Warning (289)31Indices and tables291 Index293viCHAPTERONEGETTING STARTContents•Overview•Linux Build–System Requirement–Build–CMake Options–Directory Convention•Windows Build–System Requirement–Build Under cmd.exe–Build Under msys2/MINGW/Cygwin/Cygwin64•Kconfig•menuconfig•guiconfig1.1OverviewThis SDK can be built on Windows and Linux.Most of the tools used during building the SDK are included in the SDK,including both Linux version and Windows ly:•GCC•cmake•ninja•nanopb1Programming Guide Documentation•Python3(Linux build will use the system version)•gperf1.2Linux Build1.2.1System RequirementOnly Ubuntu16.04is supported.The following packages are needed:$sudo apt install build-essential python3python3-tk qtbase5-dev1.2.2Build$.tools/launch.sh#select target by numerical index$cout$cmake../..-G Ninja$ninja.tools/launch.sh It will set PATH and several environment variables.Also,it can be called as.tools/ launch.sh<target_name><debug|release>for non-interactive mode.Non-interactive mode is useful in building script.cmake../..-G Ninja This SDK uses CMake as the building system.This step will generate ninja build file.Though CMake can support various generators.Only ninja is support in this SDK.It is only needed to run this step once.Afterward,when there are changes in source codes,CMakeLists.txt, Kconfig or target.config,ninja will invoke re-configuration automatically.ninja This command will build the selected target.In multi-processor system,Ninja will use available CPUs for parallel build.It is not needed to specify parallel job count.ninja clean CMake and ninja can handle dependency very well.In most cases,incremental build is enough.In case to clean build results for a clean build,ninja clean can be called.ninja unittests This SDK supports unit test framework.By default,unit tests are not built.If needed, ninja unittests can be called to build all unit testscout A function defined at.tools/launch.It will create target output directory,if not existed,and change directory to it.croot A function defined at.tools/launch.It will change directory to the root of project.2Chapter1.Getting StartProgramming Guide Documentation 1.2.3CMake OptionsThe supported CMake command line options:-DWITH_WERROR=on Waning is bad.However,-Werror makes development inconvenient.So,-Werror compile option isn’t added at build.When-DWITH_WERROR=on is added in the cmake command line, -Werror compile option will be added.It is recommended to add this option is CI,to make sure all warnings are solved.-DBUILR_REVISION=<revision_name>It defines a string of revision ually,it will be defined as the tag name.When not specified,the name is DEVEL.1.2.4Directory Convention<project_root>/out/<target_name>-<debug|release>Output directory of target.Out-of-source build is followed.That is,during build,there are no any build result will be generated in the source tree.All build result including intermediate build result will be created under the output directory. <project_root>/out/<target_name>-<debug|release>/lib Directory for libraries.<project_root>/out/<target_name>-<debug|release>/hex Directory for elf,map,bin and imagefiles.<project_root>/out/<target_name>-<debug|release>/include Directory for generated headerfiles.<project_root>/out/<target_name>-<debug|release>/rpcgen Sourcefiles generated by rpcgen.py.1.3Windows Build1.3.1System RequirementSupported Windows versions:•Windows7SP1,x64•Windows10,x64•Visual C++Redistributable for Visual Studio2015x86•Visual C++Redistributable for Visual Studio2015x641.3.2Build Under cmd.exe>call tools\l aunch.bat<target_name><debug|release>>cd out\t arget_name>>cmake..\..-G Ninja>ninja1.3.Windows Build3Programming Guide DocumentationIt is very similar to Linux build.tools\launch.bat doesn’t support interactive mode.The<target_name> is necessary,and<debug|release>is optional.When not specified,debug will be used.cmd.exe doesn’t support function as bash.So,cout and croot can’t be used.1.3.3Build Under msys2/MINGW/Cygwin/Cygwin64mintty and bash coming with msys2/MINGW/Cygwin/Cygwin64is more convenient than cmd.exe for inter-active.However,nothing from msys2/MINGW/Cygwin/Cygwin64will be used for building.$.tools/launch.sh#select target by numerical index$cout$cmake../..-G Ninja$ninjaIt is very similar to Linux build.After.tools/launch.sh is called,prebuilts/win32/python3will be added to the beginning of PATH.This python3is Windows native Python3.It it possible that it will affect msys2/Cygwin/Cygwin64 system.1.4KconfigKconfig is used as configuration system.For each target,target/<target_name>/target.config keeps the target configuration.At build,out/ <target_name>-<debug|release>/target.cmake will be generated,and the configurations will be used by CMake.Contrary to Linux build,there are no config.h will be generated.Rather,each module should use CMake configuration_file command to generate headerfile from a template.1.5menuconfigmconf under Linux source tree is great,but can’t run on Windows.Kconfiglib is used.Python script menuconfig can work well on Linux,and Windows cmd.exe.However,it can’t work well under mintty of msys2/Cygwin/Cygwin64.On Linux:$cd<project_root>#assume".tools/launch.sh"is already executed.$menuconfig.pyOn Windows msys2/Cygwin/Cygwin64:$cd<project_root>#assume".tools/launch.sh"is already executed.$tools/menuconfig.bat4Chapter1.Getting StartProgramming Guide DocumentationOn Windows cmd.exe:>cd<project_root>#assume"call tools\launch.bat<target_name>"is already˓→executed.>tools\m enuconfig.batDuring.tools/launch.sh or call tools\launch.bat,KCONFIG_CONFIG will be set to target/<target_name>/target.config.minconfig.py will strip down all default configurations,and only contain configuration value not equal to default value.The strip down version is suitable to keep in revision control.1.6guiconfigguiconfig is a Python script from Kconfiglib.On Linux/msys2/Cygwin/Cygwin64:$cd<project_root>#assume".tools/launch.sh"is already executed.$guiconfig.pyOn Windows cmd.exe:>cd<project_root>#assume"call tools\launch.bat<target_name>"is already˓→executed.>python3tools\g uiconfig.py1.6.guiconfig5Programming Guide Documentation6Chapter1.Getting StartCHAPTERTWOARCHITECTUREContents•Overview•Bootloader•HAL(Hardware Abstract Layer)•OSI(OS Interface)•libc•Driver•File System•IPC/RPC•CFW(Communication FrameWork)•PS Interface•TCP/IP•COAP/LWM2M/...•AT Receiver•Open CPU2.1OverviewThis SDK architecture can support various UNISOC IoT platforms.Currently,the followings are supported:•8955:2G•8908:NB IoT•8909:NB IoT/2G7Programming Guide Documentation•8915:LTE Cat1/2G,eMTC/2GThere are separated AP and CP in8915,and the architecture of the SDK for8915is:There is only one CPU for both application can stack in8955/8908/8909,and the architecture of the SDK for 8955/8908/8909is:8Chapter2.ArchitectureProgramming Guide DocumentationThough FreeRTOS is used in this SDK,there is OSI(OS Interface)layer to isolate RTOS and application.So,3rd party RTOS can be easily port to the SDK,and replace FreeRTOS.Also,3rd cloud SDK based on3rd party RTOS can run natively without porting.2.1.Overview9Programming Guide Documentation2.2BootloaderBootloader is the software entrance after system jump out of ROM.The main features of bootloader: Differential UpgradeThis SDK is target to platforms using NORflash,and most of the code are running on NORflash directly(XIP, eXecute In Place).And there is only one copy of codes on NORflash.So,at upgrade,it is needed to be done in bootloader.File system will be used for upgrade,for storing upgrade package.So,bootloader shall supportfile system.And thefile system layout in bootloader should be exactly the same with thefile system layout in application.UART/USB UpgradeIf enabled,bootloader will monitor UART/USB input for upgrade.The use case is an upgrade tool will running on PC.When the communication between PC upgrade tool and platform is established,PC upgrade tool can upgrade 10Chapter2.ArchitectureProgramming Guide Documentation thefirmware.Note:Not all platforms support USB upgrade.Application Signature VerificationWhen secure boot is enabled,ROM will verify the signature of bootloader.And bootloader shall verify the application signature.Note:Not all platforms support secure boot.Bootloader doesn’t support upgrade itself safely.Application doesn’t rely on any setting in bootloader,so in the life cycles,it doesn’t needed to upgrade bootloader.2.3HAL(Hardware Abstract Layer)HAL is platform deeply coupled layer.Examples:•System clock setting;•Memory setting;•Basic power setting;This layer can be shared with both bootloader and application.So,it can’t use RTOS features.Note:osiEnterCritical and osiExitCritical can be used in HAL.2.4OSI(OS Interface)Besides RTOS abstraction,OSI will provide other common system features.It is closer to programming environ-ment.2.5libcnewlib is used in this SDK.2.6DriverDrivers are various peripheral drivers.It is built on top of HAL and OSI.Full RTOS features can be used in drivers,including thread,semaphore,mutex,timer,work queue and etc.2.3.HAL(Hardware Abstract Layer)11Programming Guide Documentation2.7File SystemSFFS is afile system optimized for NORflash.All persistent information storage are usingfile system.Also,POSIXfile system APIs(such as open,read,write,and etc)are provided with prefix vfs_.2.8IPC/RPCFor platforms with separated AP and CP,IPC is the mechanism of AP/CP communication.RPC is a mechanism built on top of IPC.With RPC,any CPU can call APIs implemented in other CPUs.Though peer CPU API call is a serial of IPC communication,application can’t feel any differences with local API call. 2.9CFW(Communication FrameWork)CFW is a layer above protocol stack(2G,NB IoT,LTE Cat1,eMTC).On some platforms,CFW implementation may be located on other CPU.However,with the help of RPC,appli-cation is the same.Note:It is not supported to call CFW directly in customer development.2.10PS InterfacePS interface is a layer for PS data with protocol stack.The APIs is the same for platforms with protocol stack in the same CPU,and platforms with protocol stack in other CPU.2.11TCP/IPlwIP is used in this SDK to provide TCP/IP stack.2.12COAP/LWM2M/...There are many IoT IP based protocols in this SDK.Most of them are ported from open source projects.2.13AT ReceiverThis SDK provides AT receiver.AT commands can be received from UART,USB(CDC/ACM).12Chapter2.ArchitectureProgramming Guide Documentation 2.14Open CPUThis SDK provides open CPU features.Open CPU is an friendly development environment based on the base SDK.OSI,drivers and TCP/IP are well documented,and they can be used in development on top of the base SDK.Also, it supports:Dynamic LoaderAn easy-to-use dynamic loader mechanism is implemented in this SDK.The basic features:•Application can call exposed APIs in base SDK.•Base SDK and application can be upgraded independently.•Application can be loaded fromfiles onfile system,and can be loaded from NORflash directly.When loading from NORflash directly,application can run on NORflash directly.Some limitations:•Application can’t access global variables in base SDK directly.•Flash and RAM reserved for application shall be planned beforehand.AT Command by APIThere is a virtual AT channel in this SDK.With the virtual AT command channel,legacy application based on sending AT commands can be ported easily.RILDue to it is not supported to call CFW directly in customer development,RIL is provided.It is a bunch of simplified communication API.2.14.Open CPU13Programming Guide Documentation14Chapter2.ArchitectureCHAPTERTHREEFLASH LAYOUTContents•Overview•Bootloader•Application•System FS•Modem FS•Factory FS•Configurations•Frequently Overwrite Small File3.1OverviewThis IoT SDK is based on NORflash,and SFFS is thefile system for NVRAM,modem image and etc.Typicalflash layout for8MBflash:Partition Range Size Mount Pointbootloader0..0x1000064KBapplication0x10000..0x340000 3.2MBsystem FS0x340000..0x4a0000 1.4MB/modem FS0x4a0000..0x7e0000 3.2MB/modemfactory FS0x7e0000..0x800000128KB/factoryTypicalflash layout for16MBflash:15Programming Guide DocumentationPartition Range Size Mount Pointbootloader0..0x1000064KBapplication0x10000..0x9800009.6MBsystem FS0x980000..0xca0000 3.1MB/modem FS0xca0000..0xfe0000 3.2MB/modemfactory FS0xfe0000..0x1000000128KB/factoryThe size of each partition can be configured.However,it is not recommended to change the number and order of the partitions.The default layout leaves very large rooms for application,and the systemfile system is tight.When there are many customized data shall be stored,it can be considered to decrease application partition,and increase system file system partition.Whenfile system configurations(includingflash offset,size,erase block size and logic block size)are changed, the originalfiles onfile system will be destroyed.Though overhead offile system is highly optimized on SFFS,it should be considered atflash layout plan.3.2BootloaderAt boot,ROM will load bootloader to internal SRAM and execute on internal SRAM.ROM will only load size of0xbf40fromflash.When secure boot is enabled,the last0x260is used for signature.So,for one stage bootloader,the maximum code size is0xbce0.When0xbce0is not enough,two stage bootloader is needed.Also,when secure boot is needed,thefirst stage bootloader should verify the signature of second stage of bootloader.Currently,one stage bootloader is used. Feature list of bootloader:•Check application image,and jump to application;•When secure boot is enabled,verify application signature;•FOTA upgrade;Note:Due to ROM can support UART download,it is not needed to support download and/or upgrade in bootloader.3.3ApplicationApplication partition is not managed byfile system.It is for application,including SDK and customized applica-tion.And most of the application shall run onflash directly(XIP).16Chapter3.Flash LayoutProgramming Guide Documentation 3.4System FSThis is the partition for run time data,such as NVRAM,and managed byfile system.By default,it is mounted as read-write.Two directories are used by SDK:•/modemnvm(CONFIG_FS_MODEM_NVM_DIR)•/nvm(CONFIG_FS_AP_NVM_DIR)•/fota(CONFIG_FS_FOTA_DATA_DIR)FOTA upgrade data will be stored in this partition.So,it should ensure there are enough rooms for FOTA upgrade data.Also,this partition will be written frequently.For NORflashfile system,performance will downgrade whenfile system is close to full:•write will be much slower;•erase count will increase rapidly;Note:In case there are data will be stored frequently,flash life-cycle should be considered.Due to SFFS can handle wear-leveling well,the larger spare rooms infile system,the life-cycle offlash can be longer.FOTA data size is hard to estimate.Though FOTA data size can be very small when the code change is small, 10%of the original size is the minimum requirement.3.5Modem FSThis is the partition for modem image,and managed byfile system.By default,it is mounted as read-only to avoid overwrite accidentally.3.6Factory FSThis is the partition for factory data,such calibration data,IMEI,serial number and etc.,and managed byfile system.By default,it is mounted as read-only to avoid overwrite accidentally.3.7Configurations•CONFIG_BOOT_FLASH_OFFSET•CONFIG_BOOT_FLASH_SIZE•CONFIG_APP_FLASH_OFFSET3.4.System FS17Programming Guide Documentation•CONFIG_APP_FLASH_SIZE•CONFIG_FS_MODEM_MOUNT_POINT•CONFIG_FS_MODEM_FLASH_OFFSET•CONFIG_FS_MODEM_FLASH_SIZE•CONFIG_FS_MODEM_EB_SIZE•CONFIG_FS_MODEM_PB_SIZE•CONFIG_FS_SYS_MOUNT_POINT•CONFIG_FS_SYS_FLASH_OFFSET•CONFIG_FS_SYS_FLASH_SIZE•CONFIG_FS_SYS_EB_SIZE•CONFIG_FS_SYS_PB_SIZE•CONFIG_FS_FACTORY_MOUNT_POINT•CONFIG_FS_FACTORY_FLASH_OFFSET•CONFIG_FS_FACTORY_EB_SIZE•CONFIG_FS_FACTORY_PB_SIZE3.8Frequently Overwrite Small FileHere is an example of writing smallfile frequently.File system configuration:•flash size:1MB•erase block size:32KB•logical block size:512B•file size:200B•write every5minute,overwrite thefileAt worse case,thefile system is very close to full,each write will causeflash erase.And then there are105,120flash erase every year.At best case,thefile system is empty.Then,1950times offile write will cause oneflash erase of everyflash sectors.So,there are only54flash write every year.18Chapter3.Flash LayoutCHAPTERFOURKERNEL(OS INTERFACE)Contents•Overview•Thread•osiEvent_t•Thread Callback•Thread Notify•Semaphore•Mutex•Work and Work Queue•Interrupt Latency•ISR Programming•Timer–Timer and Sleep–Timer Stop Corner Case–Timer API inside Callback–Timer Pool•Elapsed Timer•Power management–PM Source–Wake Lock–Resume Order–Auto Sleep19Programming Guide Documentation–Callback Restriction•Cache•atomic•Floating Point•FreeRTOS Integration•API Reference4.1OverviewThis IoT SDK is based on RTOS.By design,SDK won’t access the used RTOS directly.Rather,OSI(OS Interface) layer is designed.SDK can only access OSI API.OSI can be implemented by various RTOS.Even the underlay RTOS is changed,the SDK itself can keep unchanged.OSI based on FreeRTOS is provided in the SDK.And it is possible and not hard to implement OSI based on other RTOS.4.2ThreadThread is the basic RTOS scheduling unit.Threads have independent stack.OSI thread has a bundled event queue.There are APIs to send event to thread.The basic model of OSI thread is event processing.An typical OSI thread is:void entry(void*argument){osiThread_t*thread=osiThreadCurrent();while(running){osiEvent_t event={};osiEventWait(thread,&event);_processEvent(&event);}osiThreadExit();}There no API to delete another thread.Rather,thread should be terminated by themselves,through some kinds of pre-defined inter-thread communication method.At the end of thread entry function,osiThreadExit() should be called.4.3osiEvent_tosiEvent_t is the data structure of OSI event:20Chapter4.Kernel(OS Interface)Programming Guide Documentation typedef struct osiEvent{uint32_t id;///<event identifieruint32_t param1;///<1st parameteruint32_t param2;///<2nd parameteruint32_t param3;///<3rd parameter}osiEvent_t;The message queue for OSI event is named as event queue.The most important inter-thread communication is to send and wait event.At send and wait event,the event body is copied.Three words are enough to carry event information in most cases.Then this design can reduce malloc and free function calls.The details of the event parameters are defined by each event.In case that three words are not enough,dynamic pointer can be carried as event parameter.The memory management convention is defined by each event.When dynamic memory is used,usually event sender allocate memory,event receiver free memory after process.4.4Thread CallbackThread callback is a callback to be executed inside specified thread.The implementation is based on OSI event. However,the codes will be more readable with osiThreadCallback,rather than huge switch/case of event IDs.With event ID,the codes will look like://senderosiEvent_t event={EVENT_ID,param1};osiEventSend(thread,&event);//receiverfor(;;){osiEvent_t event={};osiEventWait(thread,&event);switch(event.id){case EVENT_ID:function_call(event.param1);break;}}With thread call,the codes will look like:osiThreadCallback(thread,function_call,param1);4.4.Thread Callback21。
general setupenable loadable module supportenable the block layerprocessor type and feathurespower management and acpi optionsbus options(pci etc.)executable file formats/emulationsnetworking supportdevice driversfirmware driversfile systemkernel hackingsecurity optionscryptographic apivirtualizationlibrary routinesload an alternate configuration filesave an alternate configuration filegeneral setup(通用配置)Auditing supportEnable system-Call auditing suppRCU Subsystem --->Kernel config supportCoNaUTS namespaceIPC namespaceUser namespace (EXPERIMENTAL)PID Namespaces (EXPERIMENTAL)Network namespaceIn enable loadable module support(启用可加载模块支持)enable the block layer(使阻挡层)processor type and feathures(处理器类型和feathures的)paMemtestProcessor family (Pentium-Pro) Generic xe6 supportPentiumPro memory ordering errat HPET Timer SupportMaximum number of CPUsSMT (Hyperthreading) scheduler Multi-core scheduler support Fine granularity task level IR ReMachin Check / overheating repor Intel MCE featuresAMD MCE featuresMaToshiba Laptop supportDell laptop supportEnable X86 board specific fixups /dev/cpu/microcode - microcode s Intel microcode patch loading su AMD microcode patch loading sup /dev/cpu/*/msr - Model-specific /dev/cpu/*/cpuid - CPU informati High Memory Support (4GB) ---Memory model (Flat Memory) --Enable KSM for page mergingEnPoison pages injectorAllocate 3rd-level pagetables frChReserve low 64K of RAM on RMI/Math emulationMTRR (Memory Type Range RegisteMTRR cleanup supportMTRR cleanup enable value (0-1)MTRR cleanup spare reg num (0-7)x86 PAT supportEFI runtime service supportTikexec system callkernel crash dumpskexec jump (EXPERIMENTAL)Build a relocatable kernelSuCompat VDSO supportpower management and acpi options电源管理和ACPI选项SFI (Simple Firmware Interface) CPbus options(pci etc.)总线选项(PCI等)Support for DMA Remapping DeviceEnable DMA Remapping Devices byPCI Express supportPCI Express Hotplug driverRoot Port Advanced Error ReporPCI Express ECRC settings controPCIE AER error injector supportPCI Express ASPM support(ExperimDebug PCI Express RSPMMessage Signaled Interrupts (MSEnable deprecated pci_find_* APIPCI DebuggingPCI Stub driverInterrupts on hypertransport dePCI IOV supportISA supportEISA supportMCA supportNatSemi SCx200 supporlOnPCCard(PCMCIA/CardBus) support -executable file formats/emulations可执行文件格式/仿真networking support网络支持device drivers设备驱动程序Macintosh device drivers --->Network device support --->ISDN support --->Telephony support --->Input device support --->Character devices --->12C support --->SPI support --->PPS support --->GPDallas's 1-wire support --->Power supply class support ---Hardware Monitoring support --Generic Thermal sysfs driverWatchdog Timer Support --->Sonics Silicon Backplane --->Multifunction device drivers ->Voltage and Current Regulator SuMultimedia support --->Graphics support --->Sound card support --->HID Devices --->USB support --->Ultra Wideband devices (EXPERIMMMC/SD/SDIO card support --->LEAccessibility support --->InfinlBand support --->ReDMA Engine support ---> firmware drivers固件驱动程序file system文件系统JBJBD2 (ext4) debugging support Reiserfs supportReiserfs supportEnable reiserfs debug modeStats in /proc/fs/reiserfs ReiserFS extended attributes ReiserFS POSIX Access Control Li ReiserFS Security LabelsJFS filesystem supportJFS POSIX Access Control Lists JFS Security LabelsJFS debuggingJFS statisticsXFS filesystem supportXFS Quota supportXFS POSIX ACL supportXFS Realtime subvolume support XFS Debugging support (EXPERIME GFS2 file system supportGFS2 DLM lockingOCFS2 file system support02CB Kernelspace Clustering OCFS2 Userspace Clustering OCFS2 statisticsOCFS2 logging supportOCFS2 expensive checksOCFS2 POSIX Access Control Lists BtNILFS2 file system support (EXP Dnotify supportInotify file change notification Inotify support for userspace Quota supportReport quota messages through ne Print quota warnintts to console Old quota format supportQuota format v2 supportKeFUCharacter device in Userpace supCaches --->CD-ROM/DVD Filesystems ->DOS/FAT/NT Filesustems ->Pseudo filesystems --->Miscellaneous filesystems ---> kernel hacking内核黑客Debug shared IRq handlersDetect Soft LockupsPanic (Reboot) On Soft LockupsDetect Hung TasksPanic (Reboot) On Hung TasksCollect scheduler debugging infoCollect scheduler statisticsCollect kernel timers statisticsDebug object operationsSLOB debugging on by defaultEnable SLUB performance statistiKernel memory leak detectorRT Mutex debugging, deadlock detBuilt-in scriptable tester for rSpinlock and rw-lock debugging:Mutex debugging: basic checksLoLock usage statisticsLokobject debuggingHiCompile the kernel with debug in Debug VMDebug VM translationsDebug filesystem writers count Debug linked list manipulatio Debug SG table operationsDebug notifier call chains Debug credential management Compile the kernel with frame po Delay each boot printk message torture tests for RCUCheck for stalled CPUs delaying Kprobes sanity testsSelf test for the backtrace code FoLinux Kernel Dump Test Tool Modu Fault-injection framework Latency measuring infrastructure Sysctl checksDebug page memory allocations Tracers --->Remote debugging over FireWire e Remote debugging over FireWire w Enable dynamic printk() support Enable debugging of DMA-API usa Sample kernel code ---> KGDB: kernel debugging with remo Filter access to /dev/mem Enable verbose x86 bootup info m Early printkEarly printk via EHCI debug port Check for stack overflowsStack utilization instrumentatio Debug access to per_cpu maps Write protect kernel read-only d Testcase for the DEBUG_RODATA fe Testcase for the NX non-executab Use 4Kb for kernel stacks instea Enable IOMMU stress-test modesecurity options安全性选项cryptographic api加密APIAuthenc supportTesting moduleCCGCM/GMAC supportSequence Number IV Generator*** Block modes ***CBC supportCTR supportCTS supportECB supportLRW support (EXPERIMENTAL)PCBC supportXTS Support (EXPERIMENTAL)*** Hash modes ***HMAC SupportXCBC SupportVMAC Support*** Digest ***CRC32c CRC algorithmCRGHASH digest algorithmMD4 digest algorithmMD5 digest algorithmMichael MIC keyed digest algoritRIPEMD-128 digest algorithmRIPEMD-160 digest algorithmRIPEMD-256 digest algorithmRIPEMD-320 digest algorithmSHA1 digest algorithmSHA224 and SHA256 digest algoriSHR384 and SHA512 digest algoriTiger digest algorithmsWhirlpool digest algorithms*** Ciphers ***RES cipher algorithmsRES cipher algorithms (i586)Rnubis cipher algorithmRRC4 cipher algorithmBlowfish cipher algorithmCAST5 (CAST-128) cipher algoriCAST6 (CAST-256) cipher algoritDES and Triple DES EDE cipher alFCrypt cipher algorithmKhazad cipher algorithmSalsa20 stream cipher algorithmSEvirtualization虚拟化library routines库例程load an alternate configuration file加载备用配置文件save an alternate configuration file保存备用配置文件De一般的设置(通用配置)启用可加载模块支持使阻挡层处理器类型和feathures的电源管理和ACPI选项总线选项(PCI等)可执行文件格式/仿真网络支持设备驱动程序固件驱动程序文件系统内核黑客安全性选项加密API虚拟化库例程加载备用配置文件保存备用配置文件Prompt for development and/or incomplete code/dri Local version - append to kernel release Automatically append version information to the vers Kernel compression mode (Gzip) --->Support for paging of anonymous memory (swap) System V IPCPOSIX Message QueuesBSD Process AccountingBSD Process Accounting version 3 file formatExport task/process statistics through netlink (EXP Enable per-task delay accounting (EXPERIMENTAL) Enable extended accounting over taskstats (EXPERIMEN Enable per-task storage I/O accounting (EXPERIMENT Auditing supportEnable system-Call auditing supportRCU Subsystem --->Kernel config supportKernel loft buffer size (16 => 64KB, 17 => 12BKB) Control Group support --->enable deprecated sysfs features which may confuse o Kernel->user space relay support (formerly relayfs) Namespaces supportUTS namespaceIPC namespaceUser namespace (EXPERIMENTAL)PID Namespaces (EXPERIMENTAL)Network namespaceInitial RAM filesystem and RAM disk (initramfs/initInitramfs source file(s)Optimize for sizeConfigure standard kernel features (for small system Kernel Performance Events And Counters ---> Disable heap randomizationChoose SLAB allocator (SLUB (Unqueued Allocator)) Profiling Support (EXPERIMENTAL)OProfile system profiling (EXPERIMENTAL)OProfile RMD IBS Support (EXPERIMENTAL)OProfile multiplexing support (EXPERIMENTAL) KprobesGCOV-based kernel profiling --->Slow work debugging through debugfs--- Enable loadable module supportForced module loadingM_dule unloadingForced module unloadingM dule versioning supportSource checksum for all modules—Enable the block layerSupport for large (2TB+) block devices and files Block layer SG support v4Block layer data integrity supportIO Schedulers --->Tickless System (Dynamic Ticks)High Resolution Timer SupportSymmetric multi-processing supportSupport sparse irq numberingEnable MPS tableSupport for big SMP systems with more than 8 CPUs Support for extended (non-PC) x86 platformsSingle-depth WCHRN outputParavirtualized guest support --->paravirt-ops debuggingMemtestProcessor family (Pentium-Pro) --->Generic xe6 supportPentiumPro memory ordering errata workarouncHPET Timer SupportMaximum number of CPUsSMT (Hyperthreading) scheduler supportMulti-core scheduler supportFine granularity task level IRQ time accounting Preemption Model (Voluntary Kernel Preemption (Des Rerout for broken boot IRQsMachin Check / overheating reportingIntel MCE featuresAMD MCE featuresSupport for old Pentium 5 / WinChip machine checks Machine check injector supportToshiba Laptop supportDell laptop supportEnable X86 board specific fixups for reboot/dev/cpu/microcode - microcode supportIntel microcode patch loading supportAMD microcode patch loading support/dev/cpu/*/msr - Model-specific register support/dev/cpu/*/cpuid - CPU information supportHigh Memory Support (4GB) --->Memory model (Flat Memory) --->Enable KSM for page merging(65536) Low address space to protect from user all Enable recovery from hardware memory errorsPoison pages injectorAllocate 3rd-level pagetables from highmemCheck for low memory corruptionReserve low 64K of RAM on RMI/Phoenix BIOSerMath emulationMTRR (Memory Type Range Register) SupportMTRR cleanup supportMTRR cleanup enable value (0-1)MTRR cleanup spare reg num (0-7)x86 PAT supportEFI runtime service supportEnable seccomp to safely compute untrusted bytecodeEnable -fstack-protector buffer overflow detection (Timer frequency (250 HZ) --->kexec system callkernel crash dumpskexec jump (EXPERIMENTAL)Build a relocatable kernelAlignment value to which kernel should be alignedSupport for hot-pluggable CPUsCompat VDSO supportBuilt-in kernel command linePower Management supportPower Management Debug SupportVerbose Power Management debuggingSuspend/resume event tracingSuspend to RAM and standbyTest suspend/resume and wakealarm during bootupHibernation (aka 'suspend to disk’)Default resume partitionRun-time PM core functionalityACPI (Advanced Configuration and Power Interface)FuDeprecated /proc/acpi/eventAC AdapterBatteryButtonVideoFandirectoriesSupportDockProcessorProcessor AggregatorThDisable ACPI for systems before Jan 1stDebug StatementsPCI slot detection driverSFI (Simple Firmware Interface) Support --->APM (Advanced Power Management) BIOS support --->CPU Frequency scaling --->CPU frequency translation statisticsCPU frequency translation statistics detDefault CPUFreq governor (ondemand) --performance' governorpowersave' governoruserspace' governor for userspace frequondemand' cpufreq policy governorconservative' cpufreq governor*** CPUFreq processor drivers ***ACPI Processor P-States driverAMD Mobile K6-2/K6-3 PowerNow!AMD Mobile Athlon/Duron PowerNow)AMD Opteron/Athlon64 PowerNow!Cyrix MediaGX/NatSemi Geode Suspend ModuIntel Enhanced SpeedStep (deprecated)Built-in tables for Banias CPUsCPU idle PM supportPCI supportPCI access mode (Any) --->Support for DMA Remapping Devices (EXPERIMENTAL) Enable DMA Remapping Devices by defaultPCI Express supportPCI Express Hotplug driverRoot Port Advanced Error Reporting supportPCI Express ECRC settings controlPCIE AER error injector supportPCI Express ASPM support(Experimental)Debug PCI Express RSPMMessage Signaled Interrupts (MSI and MSI-X) Enable deprecated pci_find_* APIPCI DebuggingPCI Stub driverInterrupts on hypertransport devicesPCI IOV supportISA supportEISA supportMCA supportNatSemi SCx200 supporlNatSemi SCx200 27MHz High-Resolution Timer Support One Laptop Per Child supportPCCard(PCMCIA/CardBus) support -->Support for PCI hotplug --->Kernel support for ELF binariesWrite ELF core dumps with partial segmentsKernel support for a.out and ECOFF binariesKernel support for MISS binariesNetworking options --->Amateur Radio support --->CAN bus subsystem support --->IrDA (infrared) subsystem supportBluetooth subsystem support --->RxRPC session socketsRxRPC dynamic debuggingRxRPC Kerberos securityWireless --->WiMAX Wireless Broadband support-->RF switch subsystem support --->Plan 9 Resource Sharing Support (9P2000) (Experime Generic Driver Options --->Connector - unified userspace <-> kernelspace linker Memory Technology Device (MTD) support ---> Parallel port support --->Plug and Play support --->Block devices --->Misc devices --->RTR/RTRPI/MFM/RLL support --->SCSI device support --->Serial PTA (prod) and Parallel PTA (experimental) Multiple devices driver support (RAID and LVM) --Fusion MPT device support --->IEEE 1394 (FireWire) support --->120 device support --->Macintosh device drivers --->Network device support --->ISDN support --->Telephony support --->Input device support --->Character devices --->12C support --->SPI support --->PPS support --->GPIO Support --->Dallas's 1-wire support --->Power supply class support --->Hardware Monitoring support --->Generic Thermal sysfs driverWatchdog Timer Support --->Sonics Silicon Backplane --->Multifunction device drivers ->Voltage and Current Regulator Support--->Multimedia support --->Graphics support --->Sound card support --->HID Devices --->USB support --->Ultra Wideband devices (EXPERIMENTAL) --->MMC/SD/SDIO card support --->Sony MemoryStick card support (EXPERIMENTAL) ---> LED Support --->Accessibility support --->InfinlBand support --->EDAC (Error Detection And Correction) reporting Real Time Clock --->DMA Engine support --->Auxiliary Display support --->Userspace I/D drivers --->TI.VLYNQ --->Staging drivers --->X86 Platform Specific Device DriversBIOS Enhanced Disk Drive calls determine boot disk Sets default behavior for EDD detection to offEFI Variable Support via sysfsBIOS update support for DELL systems via sysfsDell Systems Management Base DriverExport DMI identification via sysfs to userspace iSCSI Boot Firmware Table AttributesiSCSI Boot Firmware Table Attributes moduleSecond extended fs supportExt2 extended attributesExt2 POSIX Access Control ListsExt2 Security LabelsExt2 execute in place supportExt3 journalling file system supportDefault to 'data=ordered' in ext3Ext3 extended attributesExt3 POSIX Access Control ListsExt3 Security LabelsThe Extended 4 (ext4) filesystemExt4 extended attributesExt4 POSIX Access Control ListsExt4 Security LabelsEXT4 debugging supportJBD (ext3) debugging supportJBD2 (ext4) debugging supportReiserfs supportReiserfs supportEnable reiserfs debug modeStats in /proc/fs/reiserfsReiserFS extended attributesReiserFS POSIX Access Control ListsReiserFS Security LabelsJFS filesystem supportJFS POSIX Access Control ListsJFS Security LabelsJFS debuggingJFS statisticsXFS filesystem supportXFS Quota supportXFS POSIX ACL supportXFS Realtime subvolume supportXFS Debugging support (EXPERIMENTAL)GFS2 file system supportGFS2 DLM lockingOCFS2 file system support02CB Kernelspace ClusteringOCFS2 Userspace ClusteringOCFS2 statisticsOCFS2 logging supportOCFS2 expensive checksOCFS2 POSIX Access Control ListsBtrfs filesystem (EXPERIMENTAL) Unstable disk forma Btrfs POSIX Access Control ListsNILFS2 file system support (EXPERIMENTAL)Dnotify supportInotify file change notification supportInotify support for userspaceQuota supportReport quota messages through netlink interfacePrint quota warnintts to console (OBSOLETE)Old quota format supportQuota format v2 supportKernel automounter supportKernel automounter version 4 support (also supports FUSE (Filesystem in Userspace) supportCharacter device in Userpace supportCaches --->CD-ROM/DVD Filesystems ->DOS/FAT/NT Filesustems ->Pseudo filesystems --->Miscellaneous filesystems --->Network File Systems --->Partition Types --->Native language support --->Distributed Lock Manager (DLM) --->Show timing information on printksEnable__deprecated logicEnable--must-check logic(1024) Warn for stack frames larger than (needs gC Magic SysRq Key(OxOlb6) Default mask for Magic SysRq keys on the c Strip assembler-generated symbols during link Enable unused/obsolete exported symbolsDebug FilesystemRun 'make headers_check' when building vmlinux Kernel debuggingDebug shared IRq handlersDetect Soft LockupsPanic (Reboot) On Soft LockupsDetect Hung TasksPanic (Reboot) On Hung TasksCollect scheduler debugging infoCollect scheduler statisticsCollect kernel timers statisticsDebug object operationsSLOB debugging on by defaultEnable SLUB performance statisticsKernel memory leak detectorRT Mutex debugging, deadlock detectionBuilt-in scriptable tester for rt-mutexesSpinlock and rw-lock debugging: basic checksMutex debugging: basic checksLock debugging: detect incorrect freeing of live loc Lock debugging: prove locking correctnessLock usage statisticsSpinlock debugging: sleep-inside-spinlock checking Locking API boot-time self-testskobject debuggingHighmem debuggingCompile the kernel with debug infoDebug VMDebug VM translationsDebug filesystem writers countDebug linked list manipulationDebug SG table operationsDebug notifier call chainsDebug credential managementCompile the kernel with frame pointersDelay each boot printk message by N milliseconds torture tests for RCUCheck for stalled CPUs delaying RCU grace periods Kprobes sanity testsSelf test for the backtrace codeForce extended block device numbers and spread them Force weak per-cpu definitionsLinux Kernel Dump Test Tool ModuleFault-injection frameworkLatency measuring infrastructureSysctl checksDebug page memory allocationsTracers --->Remote debugging over FireWire early on bootRemote debugging over FireWire with firewire-ohci Enable dynamic printk() supportEnable debugging of DMA-API usageSample kernel code --->KGDB: kernel debugging with remote gdb --->Filter access to /dev/memEnable verbose x86 bootup info messagesEarly printkEarly printk via EHCI debug portCheck for stack overflowsStack utilization instrumentationDebug access to per_cpu mapsWrite protect kernel read-only data structures Testcase for the DEBUG_RODATA featureTestcase for the NX non-executable stack feature Use 4Kb for kernel stacks instead of BKbEnable IOMMU stress-test modeID delay type (port 0x80 based port-IO delay [recomm Debug boot parametersCPA self-test codeAllow gcc to uninline functions marked 'inline'Enable the /pros/keys file by which keys may be view Enable different security modelsEnable the securityfs filesystemSocket and Networking Security HooksXFRM (IPSec) Networking Security HooksSecurity hooks for pathname based access controlFile POSIX CapabilitiesEnable Intel(R) Trusted Execution Technology (Int Low address space for LSM to protect from user allo NSR SELinux SupportNSR SELinux boot parameterNSR SELinux boot parameter default valueNSR SELinux runtime disableNSA SELinux Development SupportNSA SELinux AVC StatisticsNSA SELinux checkreqprot default valueNSA SELinux maximum supported policy format version TOMDYO Linux SupportIntegrity Measurement Architecture(IMA)*** Crypto core or helper ***FIPS 200 complianceCryptographic algorithm managerGF(2-128) multiplication functions (EXPERIMENTAL) Null algorithmsSoftware async crypto daemonAuthenc supportTesting module*** Authenticated Encryption with Associated Data ** CCM supportGCM/GMAC supportSequence Number IV Generator*** Block modes ***CBC supportCTR supportCTS supportECB supportLRW support (EXPERIMENTAL)PCBC supportXTS Support (EXPERIMENTAL)*** Hash modes ***HMAC SupportXCBC SupportVMAC Support*** Digest ***CRC32c CRC algorithmCRC32c INTEL hardware accelerationGHASH digest algorithmMD4 digest algorithmMD5 digest algorithmMichael MIC keyed digest algorithmRIPEMD-128 digest algorithmRIPEMD-160 digest algorithmRIPEMD-256 digest algorithmRIPEMD-320 digest algorithmSHA1 digest algorithmSHA224 and SHA256 digest algorithmSHR384 and SHA512 digest algorithmsTiger digest algorithmsWhirlpool digest algorithms*** Ciphers ***RES cipher algorithmsRES cipher algorithms (i586)Rnubis cipher algorithmRRC4 cipher algorithmBlowfish cipher algorithmCAST5 (CAST-128) cipher algorithmCAST6 (CAST-256) cipher algorithmDES and Triple DES EDE cipher algorithmsFCrypt cipher algorithmKhazad cipher algorithmSalsa20 stream cipher algorithm (EXPERIMENTAL)Salsa20 stream cipher algorithm (1586) (EXPERIMENTA SEED cipher algorithmSerpent cipher algorithmTEA, XTEA and XETA cipher algorithmsTwofish cipher algorithmTwofish cipher algorithms (1586)*** Compression ***Deflate compression algorithmlib compression algorithmLZD compression algorithm*** Random Number Generation ***Pseudo Random Number Generation for CrUotoeraohic mo Hardware crypto devices--->Kernel-based Virtual Machine (KVM) SupportKVM for Intel processors supportKVM for AMD processors supportLinux hypervisor example codePCI driver for virtio devices (EXPERIMENTAL)Virtio balloon driver (EXPERIMENTAL)CRC-CCITT functionsCRC16 functionsCRC calculation for the T10 Data Integrity Field CRC ITU-T V.41 functionsCRC32 functionsCRC7 functionsCRC32c (Castagnoli, et al) Cyclic Redundancy-Check 下面是扩展选项,因为太多了所以只列出一部分networking supportDevice Drivers->。
来自:提要:在Kernel 2.6x和以前的版本的编译方法有点区别,所以就简单的把编译过程写出来,主要是帮助初学Linux的兄弟。
Kernle 2.6x 编译比较简单,最适合我等菜鸟!!本文是以Redhat为例,内版本是2.6.0-test8一、下载二、解压1.把下载好的内核放到/usr/src目录中,比如我下载的是linux-2.6.0-test8.tar.bz2#mv linux-2.6.0-test8.tar.bz2 /usr/src#tar jxvf linux-2.6.0-test8.tar.bz22.进入相应的目录编译和安装,进入内核选项设置#cd linux-2.6.0-test8#make mrproper#make menuconfig进入内核选项卡,M是以模快方式编译,*是直接编入内核致于哪些要编入内核,哪些要编译成模块。
在文章管理器和基础讨论区的帖子中都有,自己试着找一找。
另外内核中的doc也有相应的文档3.编译和安装内核#make#sudo make install这个过程是编译和安装内核的过程,系统自动为我们做了哪些事?1]系统会在/usr/src/linux/arch/i386/boot/目录中产生bzImage,并把bzImage复制为vmlinuz-2.6.0-test8到/boot目录中,并创建议vmlinuz-2.6.0-test8的链接vmlinuz;2]在/boot目录中,系统会产生System.map-2.6.0-test8,以及创建它的链接System.map;3]在/boot目录中,自动生为initrd-2.6.0-test8.img;4]修改/etc/grub.conf 文件,加入了新内核的启动项。
[注]经大熊宝宝兄的提示,怕初学的弟兄不明白这个过程,所以就把这个过程详细的写出来,所以我也做了补充。
以上的四点都是系统自动安装内核时所做的任务。
查看一下/boot目录中的文件以及/etc/grub.conf就明白了。
Linux多线程编程和Linux 2.6下的NPTL这几天由于工作需要,琢磨了一下Linux下的多线程的相关资料。
Linux下最常用的多线程支持库为Pthread库,它是glibc库的组成部分。
但是关于Pthread的说明文档非常缺乏,特别是对POSIX多线程规范的介绍以及pthread库中多线程实现方式的介绍实在是少之又少。
而多线程编程对于系统程序员而言是必须掌握的技术,因此总是让学习中的程序员觉得头痛不以。
我自己也没有太多多线程编程的经验,在这里只是把自己收集到的一些关于Linux上多线程还算新的资料进行汇总来抛砖引玉,以便相互学习交流。
这里顺便提一下市面上有的一本介绍多线程的书《Posix 多线程编程》,它是英文版《Programming with POSIX Muiltthread》中译本,这也是半年前我所能找到的唯一专题介绍多线程编程的书。
我个人感觉这本书的前面1/3之一的内容写的还是不错的,但是后面的东西就非常晦涩并且有很多明显的文字错误。
看看这本书的翻译者是好几个人,估计每个人的翻译能力不同造成了这本书的虎头蛇尾。
因此我不建议大家去买这本书作为圣经收藏。
这本书前半步的内容主要围绕Posix的多线程,介绍的比较精彩的就是几个多线程编程模型,把多线程的互斥和同步机制介绍的挺酣畅的,推荐一看。
这些内容并非这本书首创,早在《UNIX网络编程》第二卷进程间通信就有了这些经典的介绍,但是能系统的把这些机制结合到多线程编程中来还是有可圈可点之处的。
此外毕竟《UNIX网络编程》两卷内容太老,书也太厚了,并不是大多数程序员所能坐下来细细看的。
这里我还想表达一下对微软在技术上的不足斥责。
在msdn中platform sdk部分中的windows多线程编程的内容真是简陋的可笑,只有傻兮兮的建立和退出线程的函数,关于互斥,条件的介绍一概全无。
只能在它的sample代码中自己去找,sample 代码里面的线程同步方式居然是做一个死循环来死等,也不知道它把windows卖这么多钱是干什么吃的。
如何把驱动代码加入到Linux Kernel,你需要知道怎么修改这两个文件Kconfig*Makefile1. Kconfig文件的作用”内核源码树的目录下都有两个文件Kconfig(2.4版本是Config.in)和Makefile。
分布到各目录的Kconfig构成了一个分布式的内核配置数据库,每个Kconfig 分别描述了所属目录源文件相关的内核配置菜单。
在内核配置make menuconfig(或xconfig等)时,从Kconfig中读出菜单,用户选择后保存到.config的内核配置文件中。
在内核编译时,主Makefile调用这个.config,就知道了用户的选择。
*上面的内容说明了,Kconfig就是对应着内核的配置菜单。
如果要想添加新的驱动到内核的源码中,可以修改Kconfig,这样就可以选择这个驱动,如果想使这个驱动被编译,要修改Makefileso添加新的驱动时需要修改的文件有两种(注意不只是两个)*Kconfig*Makefile要想知道怎么修改这两种文件,就要知道两种文件的语法结构2. Kconfig”每个菜单都有一个关键字标识,最常见的就是config语法:configsymbol是一个新的标记的菜单项,options是在这个新的菜单项下的属性和选项其中options部分有:1) 类型定义:每个config菜单项都要有类型定义,bool布尔类型、tristate三态:内建、模块、移除string字符串、hex十六进制、integer整型例如config HELLO_MODULEbool "hello test module"bool类型的只能选中或不选中,tristate类型的菜单项多了编译成内核模块的选项,如果选择编译成内核模块,则会在.config中生成一个CONFIG_HELLO_MODULE=m的配置,如果选择内建,就会直接编译成内,则在.config中生成一个CONFIG_HELLO_MODULE=y的配置.2) 依赖型定义depends on或requires指此菜单的出现与否依赖于另一个定义config HELLO_MODULEbool "hello test module"depends on ARCH_PXA这个例子表明HELLO_MODULE这个菜单项只对XScale处理器有效。
中英文对照外文翻译(文档含英文原文和中文翻译)Android: A Programmer’s Guide1 What Is Android1.1 Key Skills & Concepts● History of embedded device programming● Explanation of Open Handset Alliance● First look at the Android home screenIt can be said that, for a while, traditional desktop application developers have been spoiled. This is not to say that traditional desktop application development is easier than other forms of develop ment. However, as traditional desktop application developers, we have had the ability to create alm ost any kind of application we can imagine. I am including myself in this grouping because I got my start in desktop programming.One aspect that has made desktop programming more accessible is that we have had the ability to interact with the desktop operating system, and thus interact with any underlying hardware, prettyfreely (or at least with minimal exceptions). This kind of freedom to program independently, how ever, has never really been available to the small group of programmers who dared to venture int o the murky waters of cell phone development.NOTE :I refer to two different kinds of developers in this discussion: traditional desktop applicati on developers, who work in almost any language and whose end product, applications, are built to run on any “desktop” operating system; and Android developers, J ava developers who develop for the Android platform. This is not for the purposes of saying one is by any means better or wors e than the other. Rather, the distinction is made for purposes of comparing the development styles and tools of desktop operating system environments to the mobile operating system environment1.2 Brief History of Embedded Device ProgrammingFor a long time, cell phone developers comprised a small sect of a slightly larger group of developers known as embedded device developers. Seen as a less “glamorous” sibling to desktop—and later web—development, embedded device development typically got the proverbial short end of the stick as far as hardware and operating system features, because embedded device manufacturers were notoriously stingy on feature support.Embedded device manufacturers typically needed to guard their hardware secrets closely, so they gave embedded device developers few libraries to call when trying to interact with a specific device. Embedded devices differ fro m desktops in that an embedded device is typically a “computer on a chip.” For example, consider your standard television remote control; it is not really seen as an overwhelming achievement of technological complexity. When any button is pressed, a chip interprets the signal in a way that has been programmed into the device. This allows the device to know what to expect from the input device (key pad), and how to respond to those commands (for example, turn on the television). This is a simple form of embedded device programming. However, believe it or not, simple devices such as these are definitely related to the roots of early cell phone devices and development.Most embedded devices ran (and in some cases still run) proprietary operating systems. The reason for choosing to create a proprietary operating system rather than use any consumer system was really a product of necessity. Simple devices did not need very robust and optimized operating systems.As a product of device evolution, many of the more complex embedded devices, such as early PDAs, household security systems, and GPSs, moved to somewhat standardized operating system platforms about five years ago. Small-footprint operating systems such as Linux, or even an embedded version of Microsoft Windows, have become more prevalent on many embedded devices. Around this time in device evolution, cell phones branched from other embedded devices onto their own path. This branching is evident whenyou examine their architecture.Nearly since their inception, cell phones have been fringe devices insofar as they run on proprietary software—software that is owned and controlled by the manufacturer, and is almost always considered to be a “closed” system. The practice of manufacturers using proprietary operating systems began more out of necessity than any other reason. That is, cell phone manufacturers typically used hardware that was completely developed in-house, or at least hardware that was specifically developed for the purposes of running cell phone equipment. As a result, there were no openly available, off-the-shelf software packages or solutions that would reliably interact with their hardware. Since the manufacturers also wanted to guard very closely their hardware trade secrets, some of which could be revealed by allowing access to the software level of the device, the common practice was, and in most cases still is, to use completely proprietary and closed software to run their devices. The downside to this is that anyone who wanted to develop applications for cell phones needed to have intimate knowledge of the proprietary environment within which it was to run. The solution was to purchase expensive development tools directly from the manufacturer. This isolated many of the “homebrew” develo pers.NOTE:A growing culture of homebrew developers has embraced cell phone application development. The term “homebrew” refers to the fact that these developers typically do not work for a cell phone development company and generally produce small, one-off products on their own time.Another, more compelling “necessity” that kept cell phone development out of the hands of the everyday developer was the hardware manufacturers’ solution to the “memory versus need” dilemma. Until recently, cell phones did little more than execute and receive phone calls, track your contacts, and possibly send and receive short text messages; not really the “Swiss army knives” of technology they are today. Even as late as 2002, cell phones with cameras were not commonly found in the hands of consumers.By 1997, small applications such as calculators and games (Tetris, for example) crept their way onto cell phones, but the overwhelming function was still that of a phone dialer itself. Cell phones had not yet become the multiuse, multifunction personal tools they are today. No one yet saw the need for Internet browsing, MP3 playing, or any of the multitudes of functions we are accustomed to using today. It is possible that the cell phone manufacturers of 1997 did not fully perceive the need consumers would have for an all-in-one device. However, even if the need was present, a lack of device memory and storage capacity was an even bigger obstacle to overcome. More people may have wanted their devices to be all-in-one tools, but manufacturers still had to climb the memory hurdle.To put the problem simply, it takes memory to store and run applications on any device, cell phones included. Cell phones, as a device, until recently did not have the amount of memory available to them that would facilitate the inclusion of “extra” programs. Within the last two years, the price of memory has reached very low levels. Device manufacturers now have the ability to include more memory at lower prices. Many cell phones now have more standard memory than the average PC had in the mid-1990s. So, now that we have the need, and the memory, we can all jump in and develop cool applications for cell phones around the world, right? Not exactly.Device manufacturers still closely guard the operating systems that run on their devices. While a few have opened up to the point where they will allow some Java-based applications to run within a small environment on the phone, many do not allow this. Even the systems that do allow some Java apps to run do not allow the kind of access to the “core” system that standard desktop developers are accustomed to having.1.3 Open Handset Alliance and AndroidThis barrier to application development began to crumble in November of 2007 when Google, under the Open Handset Alliance, released Android. The Open Handset Alliance is a group of hardware and software developers, including Google, NTT DoCoMo, Sprint Nextel, and HTC, whose goal is to create a more open cell phone environment. The first product to be released under the alliance is the mobile device operating system, Android.With the release of Android, Google made available a host of development tools and tutorials to aid would-be developers onto the new system. Help files, the platform software development kit (SDK), and even a developers’ community can be found at Google’s Android website, This site should be your starting point, and I highly encourage you to visit the site.NOTE :Google, in promoting the new Android operating system, even went as far as to create a $10 million contest looking for new and exciting Android applications.While cell phones running Linux, Windows, and even PalmOS are easy to find, as of this writing, no hardware platforms have been announced for Android to run on. HTC, LG Electronics, Motorola, and Samsung are members of the Open Handset Alliance, under which Android has been released, so we can only hope that they have plans for a few Android-based devices in the near future. With its release in November 2007, the system itself is still in a software-only beta. This is good news for developers because it gives us a rare advance look at a future system and a chance to begin developing applications that willrun as soon as the hardware is released.NOTE:This strategy clearly gives the Open Handset Alliance a big advantage over other cell phone operating system developers, because there could be an uncountable number of applications available immediately for the first devices released to run Android.Introduction to AndroidAndroid, as a system, is a Java-based operating system that runs on the Linux 2.6 kernel. The system is very lightweight and full featured. Android applications are developed using Java and can be ported rather easily to the new platform. If you have not yet downloaded Java or are unsure about which version you need, I detail the installation of the development environment in Chapter 2. Other features of Android include an accelerated 3-D graphics engine (based on hardware support), database support powered by SQLite, and an integrated web browser.If you are familiar with Java programming or are an OOP developer of any sort, you are likely used to programmatic user interface (UI) development—that is, UI placement which is handled directly within the program code. Android, while recognizing and allowing for programmatic UI development, also supports the newer, XML-based UI layout. XML UI layout is a fairly new concept to the average desktop developer. I will cover both the XML UI layout and the programmatic UI development in the supporting chapters of this book.One of the more exciting and compelling features of Android is that, because of its architecture, third-party applications—including those that are “home grown”—are executed with the same system priority as those that are bundled with the core system. This is a major departure from most systems, which give embedded system apps a greater execution priority than the thread priority available to apps created by third-party developers. Also, each application is executed within its own thread using a very lightweight virtual machine.Aside from the very generous SDK and the well-formed libraries that are available to us to develop with, the most exciting feature for Android developers is that we now have access to anything the operating system has access to. In other words, if you want to create an application that dials the phone, you have access to the phone’s dialer; if you want to create an application that utilizes the phone’s internal GPS (if equipped), you have access to it. The potential for developers to create dynamic and intriguing applications is now wide open.On top of all the features that are available from the Android side of the equation, Google has thrown insome very tantalizing features of its own. Developers of Android applications will be able to tie their applications into existing Google offerings such as Google Maps and the omnipresent Google Search. Suppose you want to write an application that pulls up a Google map of where an incoming call is emanating from, or you want to be able to store common search results with your contacts; the doors of possibility have been flung wide open with Android.Chapter 2 begins your journey to Android development. You will learn the how’s and why’s of using specific development environments or integrated development environments (IDE), and you will download and install the Java IDE Eclipse.2 Application: Hello World2.1 Key Skills & Concepts●Creating new Android projects●Working with Views●Using a TextView●Modifying the main.xml file●Running applications on the Android EmulatorIn this chapter, you will be creating your first Android Activity. This chapter examines the application-building process from start to finish. I will show you how to create an Android project in Eclipse, add code to the initial files, and run the finished application in the Android Emulator. The resulting application will be a fully functioning program running in an Android environment.Actually, as you move through this chapter, you will be creating more than one Android Activity. Computer programming tradition dictates that your first application be the typical Hello World! application, so in the first section you will create a standard Hello World! application with just a blank background and the “Hello World!” text. Then, for the sake of enabling you to get to know the language better, the next section explains in detail the files automatically created by Android for your Hello World! application. You will create two iterations of this Activity, each using different techniques for displaying information to the screen. You will also create two different versions of a Hello World! application that will display an image that delivers the “Hello World!” message. This will give you a good introduction to the controls and inner workings of Android.NOTE:You will often see “application” and “Activity” used interchangeably. The difference between the two is that an application can be composed of multiple Activities, but one application must have at leastone Activity. Each “window” or screen of your application is a separate Activity. Therefore, if you create a fairly simple application with only one screen of data (like the Hello World! application in this chapter), that will be one Activity. In future chapters you will create applications with multiple Activities.To make sure that you get a good overall look at programming in Android, in Chapter 6 you will create both of these applications in the Android SDK command-line environment for Microsoft Windows and Linux. In other words, this chapter covers the creation process in Eclipse, and Chapter 6 covers the creation process using the command-line tools. Therefore, before continuing, you should check that your Eclipse environment is correctly configured. Review the steps in Chapter 3 for setting the PATH statement for the Android SDK. You should also ensure that the JRE is correctly in your PATH statement.TIP:If you have configuration-related issues while attempting to work with any of the command-line examples, try referring to the configuration steps in Chapters 2 and 3; and look at the Android SDK documentation.2.2 Creating Your First Android Project in EclipseTo start your first Android project, open Eclipse. When you open Eclipse for the first time, it opens to an empty development environment (see Figure 5-1), which is where you want to begin. Your first task is to set up and name the workspace for your application. Choose File | New | Android Project, which will launch the New Android Project wizard.CAUTION Do not select Java Project from the New menu. While Android applications are written in Java, and you are doing all of your development in Java projects, this option will create a standard Java application. Selecting Android Project enables you to create Android-specific applications.If you do not see the option for Android Project, this indicates that the Android plugin for Eclipse was not fully or correctly installed. Review the procedure in Chapter 3 for installing the Android plugin for Eclipse to correct this.2.3 The New Android Project wizard creates two things for youA shell application that ties into the Android SDK, using the android.jar file, and ties the project into the Android Emulator. This allows you to code using all of the Android libraries and packages, and also lets you debug your applications in the proper environment.Your first shell files for the new project. These shell files contain some of the vital application blocks upon which you will be building your programs. In much the same way as creating a Microsoft .NET application in Visual Studio generates some Windows-created program code in your files, using the Android Project wizard in Eclipse generates your initial program files and some Android-created code. Inaddition, the New Android Project wizard contains a few options, shown next, that you must set to initiate your Android project. For the Project Name field, for purposes of this example, use the title HelloWorldText. This name sufficiently distinguishes this Hello World! project from the others that you will be creating in this chapter.In the Contents area, keep the default selections: the Create New Project in Workspace radio button should be selected and the Use Default Location check box should be checked. This will allow Eclipse to create your project in your default workspace directory. The advantage of keeping the default options is that your projects are kept in a central location, which makes ordering, managing, and finding these projects quite easy. For example, if you are working in a Unix-based environment, this path points to your $HOME directory.If you are working in a Microsoft Windows environment, the workspace path will be C:/Users/<username>/workspace, as shown in the previous illustration. However, for any number of reasons, you may want to uncheck the Use Default Location check box and select a different location for your project. One reason you may want to specify a different location here is simply if you want to choose a location for this specific project that is separate from other Android projects. For example, you may want to keep the projects that you create in this book in a different location from projects that you create in the future on your own. If so, simply override the Location option to specify your own custom location directory for this project.3 Application FundamentalsAndroid applications are written in the Java programming language. The compiled Java code — along with any data and resource files required by the application — is bundled by the aapt tool into an Android package, an archive file marked by an .apk suffix. This file is the vehicle for distributing the application and installing it on mobile devices; it's the file users download to their devices. All the code in a single .apk file is considered to be one application.In many ways, each Android application lives in its own world:1. By default, every application runs in its own Linux process. Android starts the process when any of the application's code needs to be executed, and shuts down the process when it's no longer needed and system resources are required by other applications.2. Each process has its own virtual machine (VM), so application code runs in isolation from the code of all other applications.3. By default, each application is assigned a unique Linux user ID. Permissions are set so that the application's files are visible only to that user and only to the application itself — although there are ways to export them to other applications as well.It's possible to arrange for two applications to share the same user ID, in which case they will be able to see each other's files. To conserve system resources, applications with the same ID can also arrange to run in the same Linux process, sharing the same VM.3.1 Application ComponentsA central feature of Android is that one application can make use of elements of other applications (provided those applications permit it). For example, if your application needs to display a scrolling list of images and another application has developed a suitable scroller and made it available to others, you can call upon that scroller to do the work, rather than develop your own. Application have four types of components:(1)ActivitiesAn activity presents a visual user interface for one focused endeavor the user can undertake. For example, an activity might present a list of menu items users can choose from or it might display photographs along with their captions. A text messaging application might have one activity that shows a list of contacts to send messages to, a second activity to write the message to the chosen contact, and other activities to review old messages or change settings. Though they work together to form a cohesive user interface, each activity is independent of the others. Each one is implemented as a subclass of the Activity base class.An application might consist of just one activity or, like the text messaging application just mentioned, it may contain several. What the activities are, and how many there are depends, of course, on the application and its design. Typically, one of the activities is marked as the first one that should be presented to the user when the application is launched. Moving from one activity to another is accomplished by having the current activity start the next one.Each activity is given a default window to draw in. Typically, the window fills the screen, but it might be smaller than the screen and float on top of other windows. An activity can also make use of additional windows — for example, a pop-up dialog that calls for a user response in the midst of the activity, or a window that presents users with vital information when they select a particular item on-screen.The visual content of the window is provided by a hierarchy of views — objects derived from the base View class. Each view controls a particular rectangular space within the window. Parent views contain and organize the layout of their children. Leaf views (those at the bottom of the hierarchy) draw in the rectangles they control and respond to user actions directed at that space. Thus, views are where the activity's interaction with the user takes place.For example, a view might display a small image and initiate an action when the user taps that image. Android has a number of ready-made views that you can use — including buttons, text fields, scroll bars, menu items, check boxes, and more.A view hierarchy is placed within an activity's window by the Activity.setContentView() method. The content view is the View object at the root of the hierarchy. (See the separate User Interface document for more information on views and the hierarchy.)(2)ServicesA service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it. Each service extends the Service base class.A prime example is a media player playing songs from a play list. The player application would probably have one or more activities that allow the user to choose songs and start playing them. However, the musicplayback itself would not be handled by an activity because users will expect the music to keep playing even after they leave the player and begin something different. To keep the music going, the media player activity could start a service to run in the background. The system would then keep the music playback service running even after the activity that started it leaves the screen.It's possible to connect to (bind to) an ongoing service (and start the service if it's not already running). While connected, you can communicate with the service through an interface that the service exposes. For the music service, this interface might allow users to pause, rewind, stop, and restart the playback.Like activities and the other components, services run in the main thread of the application process. So that they won't block other components or the user interface, they often spawn another thread for time-consuming tasks (like music playback). See Processes and Threads, later.(3)Broadcast receiversA broadcast receiver is a component that does nothing but receive and react to broadcast announcements. Many broadcasts originate in system code — for example, announcements that the timezone has changed, that the battery is low, that a picture has been taken, or that the user changed a language preference. Applications can also initiate broadcasts — for example, to let other applications know that some data has been downloaded to the device and is available for them to use.An application can have any number of broadcast receivers to respond to any announcements it considers important. All receivers extend the BroadcastReceiver base class.Broadcast receivers do not display a user interface. However, they may start an activity in response to the information they receive, or they may use the NotificationManager to alert the user. Notifications can get the user's attention in various ways — flashing the backlight, vibrating the device, playing a sound, and so on. They typically place a persistent icon in the status bar, which users can open to get the message.(4)Content providersA content provider makes a specific set of the application's data available to other applications. The data can be stored in the file system, in an SQLite database, or in any other manner that makes sense. The content provider extends the ContentProvider base class to implement a standard set of methods that enable other applications to retrieve and store data of the type it controls. However, applications do not call these methods directly. Rather they use a ContentResolver object and call its methods instead. A ContentResolver can talk to any content provider; it cooperates with the provider to manage any interprocess communication that's involved.See the separate Content Providers document for more information on using content providers. Whenever there's a request that should be handled by a particular component, Android makes sure that the application process of the component is running, starting it if necessary, and that an appropriate instance of the component is available, creating the instance if necessary.3.2 Activating components: intentsContent providers are activated when they're targeted by a request from a ContentResolver. The other three components —activities, services, and broadcast receivers —are activated by asynchronous messages called intents. An intent is an Intent object that holds the content of the message. For activities and services, it names the action being requested and specifies the URI of the data to act on, among other things. For example, it might convey a request for an activity to present an image to the user or let the user edit some text. For broadcast receivers, theIntent object names the action being announced. For example, it might announce to interested parties that the camera button has been pressed.。
Linux系统调⽤所谓系统调⽤是指操作系统提供给⽤户程序调⽤的⼀组“特殊”接⼝,⽤户程序可以通过这组“特殊”接⼝来获得操作系统内核提供的服务。
例如⽤户可以通过进程控制相关的系统调⽤来创建进程、实现进程调度、进程管理等。
在这⾥,为什么⽤户程序不能直接访问系统内核提供的服务呢?这是由于在 Linux 中,为了更好地保护内核空间,将程序的运⾏空间分为内核空间和⽤户空间(也就是常称的内核态和⽤户态),它们分别运⾏在不同的级别上,在逻辑上是相互隔离的。
因此,⽤户进程在通常情况下不允许访问内核数据,也⽆法使⽤内核函数,它们只能在⽤户空间操作⽤户数据,调⽤⽤户空间的函数。
但是,在有些情况下,⽤户空间的进程需要获得⼀定的系统服务(调⽤内核空间程序),这时操作系统就必须利⽤系统提供给⽤户的“特殊接⼝”——系统调⽤规定⽤户进程进⼊内核空间的具体位置。
进⾏系统调⽤时,程序运⾏空间需要从⽤户空间进⼊内核空间,处理完后再返回到⽤户空间。
Linux 系统调⽤部分是⾮常精简的系统调⽤(只有 250 个左右),它继承了 UNIX 系统调⽤中最基本和最有⽤的部分。
这些系统调⽤按照功能逻辑⼤致可分为进程控制、进程间通信、⽂件系统控制、系统控制、存储管理、⽹络管理、socket 控制、⽤户管理等⼏类。
在 Linux 中对⽬录和设备的操作都等同于⽂件的操作,因此,⼤⼤简化了系统对不同设备的处理,提⾼了效率。
Linux 中的⽂件主要分为 4种:普通⽂件、⽬录⽂件、链接⽂件和设备⽂件。
那么,内核如何区分和引⽤特定的⽂件呢?这⾥⽤到的就是⼀个重要的概念——⽂件描述符。
对于 Linux ⽽⾔,所有对设备和⽂件的操作都使⽤⽂件描述符来进⾏的。
⽂件描述符是⼀个⾮负的整数,它是⼀个索引值,并指向内核中每个进程打开⽂件的记录表。
当打开⼀个现存⽂件或创建⼀个新⽂件时,内核就向进程返回⼀个⽂件描述符;当需要读写⽂件时,也需要把⽂件描述符作为参数传递给相应的函数。
The Linux Kernel Module Programming Guide
Peter Jay Salzman Michael Burian Ori Pomerantz
Copyright © 2001 Peter Jay SalzmanThe Linux Kernel Module Programming Guide is a free book; you may reproduce and/or modify it under the terms of the Open Software License, version 1.1. You can obtain a copy of this license at http://opensource.org/licenses/osl.php.
This book is distributed in the hope it will be useful, but without any warranty, without even the implied warranty of merchantability or fitness for a particular purpose.
The author encourages wide distribution of this book for personal or commercial use, provided the above copyright notice remains intact and the method adheres to the provisions of the Open Software License. In summary, you may copy and distribute this book free of charge or for a profit. No explicit permission is required from the author for reproduction of this book in any medium, physical or electronic.
Derivative works and translations of this document must be placed under the Open Software License, and the original copyright notice must remain intact. If you have contributed new material to this book, you must make the material and source code available for your revisions. Please make revisions and updates available directly to the document maintainer, Peter Jay Salzman . This will allow for the merging of updates and provide consistent revisions to the Linux community.
If you publish or distribute this book commercially, donations, royalties, and/or printed copies are greatly appreciated by the author and the Linux
Documentation Project (LDP). Contributing in this way shows your support for free software and the LDP. If you have questions or comments, please contact the address above.
Table of Contents Foreword 1. 作者声明 2. 版本和注意 3. 感谢 4. 译者注 1. Introduction 1.1. 什么是内核模块? 1.2. 内核模块是如何被调入内核工作的? 1.2.1. 在开始前 1.2.1.1. 内核模块和内核的版本问题 1.2.1.2. 使用 X 带来的问题 1.2.1.3. 编译相关和内核版本相关的问题 2. Hello World 2.1. Hello, World (part 1): 最简单的内核模块 2.1.1. 介绍 printk() 2.2. 编译内核模块 2.3. Hello World (part 2) 2.4. Hello World (part 3): 关于 __init 和 __exit 宏 2.5. Hello World (part 4): 内核模块证书和内核模块文档说明 2.6. 从命令行传递参数给内核模块 2.7. 由多个文件构成的内核模块 2.8. 为已编译的内核编译模块 3. Preliminaries 3.1. 内核模块和用户程序的比较 3.1.1. 内核模块是如何开始和结束的 3.1.2. 模块可调用的函数 3.1.3. 用户空间和内核空间 3.1.4. 命名空间 3.1.5. 代码空间 3.1.6. Device Drivers 3.1.6.1. Major and Minor Numbers 4. Character Device Files 4.1. 字符设备文件 4.1.1. 关于 file_operations 结构体 4.1.2. 关于 file 结构体 4.1.3. 注册一个设备 4.1.4. 注销一个设备 4.1.5. chardev.c 4.1.6. 为多个版本的内核编写内核模块 5. The /proc File System 5.1. 关于 /proc 文件系统 6. Using /proc For Input 6.1. 使用 /proc 作为输入 7. Talking To Device Files 7.1. 与设备文件对话 (writes and IOCTLs) 8. System Calls 8.1. 系统调用 9. Blocking Processes 9.1. 阻塞进程 9.1.1. Enter Sandman 10. Replacing Printks 10.1. 替换 printk 10.2. 让你的键盘指示灯闪起来 11. Scheduling Tasks 11.1. 任务调度 12. Interrupt Handlers 12.1. Interrupt Handlers 12.1.1. Interrupt Handlers 12.1.2. Intel 架构中的键盘 13. Symmetric Multi Processing 13.1. 对称多线程处理 14. Common Pitfalls 14.1. 注意 A. Changes: 2.0 To 2.2 A.1. 从 2.0 到 2.2 的变化 A.1.1. 从 2.0 到 2.2 的变化 B. Where To Go From Here B.1. 为什么这样写? Index List of Examples 2-1. hello-1.c 2-2. 一个基本的 Makefile 2-3. hello-2.c 2-4. 两个内核模块使用的 Makefile 2-5. hello-3.c 2-6. hello-4.c 2-7. hello-5.c 2-8. start.c 2-9. stop.c 2-10. Makefile 4-1. chardev.c 5-1. procfs.c 6-1. procfs.c 7-1. chardev.c 7-2. chardev.h 7-3. ioctl.c 8-1. syscall.c 9-1. sleep.c 10-1. print_string.c 10-2. kbleds.c 11-1. sched.c 12-1. intrpt.c
Foreword1. 作者声明《Linux 内核驱动模块编程指南》最初是由Ori Pomerantz为2.2 版本的内核编写的,后来,Ori将文档维护的任务交给了Peter Jay Salzman,Peter完成了2.4内核版本 文档的编写,毕竟Linux内核驱动模块是一个更新很快的内容。现在,Peter也无法腾 出足够的时间来完成2.6内核版本文档的编写,目前该2.6内核版本的文档由合作者Michael Burian 完成。
2. 版本和注意Linux 内核模块是一块不断更新进步的内容,在LKMPG上总有关于是否保留还是历 史版本的争论。Michael和我最终是决定为每个新的稳定版本内核建立一个新的文档 分支。也就是说LKMPG 2.4.x专注于2.4的内核,而LKMPG 2.6.x将专注于2.6的内核。我们不会在一篇文档中提供对旧版本内核的支持,对此感兴趣的读者应该寻找相关版本的文档分支。
在文档中的绝大部分源代码和讨论都应该适用于其它平台,但我无法提供任何保证。其 中的一个例外就是Chapter 12, 中断处理该章的源代码和讨论就只适用于x86平台。
3. 感谢感谢下列人士为此文档提供了他们宝贵的意见。他们是:Ignacio Martin, David Porter, Daniele Paolo,Scarpazza 和Dimo Velev。
4. 译者注我,译者,名叫田竞,目前是一名在北京邮电大学就读的通信专业的大学生。自高中起我就是Linux的爱好者并追随至今。我喜欢Linux给我带来的自由,我想大家也一样。 没有人不向往自由。
我学习内核模块编写时最初阅读的是Orelly出版社的使用2.0版本的内核的书籍,但如同我预料的一样,书中的许多事例由于内核代码的变化而无法使用。这让想亲自体验内核模块的神秘的我非常苦恼。我在Linux文档计划在上海的镜像站ldp.linuxforum.net 上找到了这篇文档。
受原作者Ori 的鼓励,基于上次完成的LKMPG 2.4的,内容有稍许的改变和扩充。应 该是目前最新的了。翻译的方式有所改变,在基于LDP认可的docbook格式上翻译,