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。
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格式上翻译,