發表文章

目前顯示的是 3月, 2022的文章

如何撰寫Driver支援sysfs檔案系統

圖片
  前言 在現在Linux的系統中,有一個新的虛擬檔案系統,叫做sysfs,它只要是來管理Linux系統中的週邊元件,及配合使用公用程式來自動產生device node。其實它是一個虛擬的記憶體檔案系統,它是由proc所變化而來的,它是由各個driver所產生,換另一句話就是要Driver有撰寫才會有這樣的功能,它是繼承kobject的資料結構,另外其檔名及內容都是driver自行解決,目前主要都是來設定driver自己本身的一些功能,這樣可以讓驅動程式更多元化,或者可以讀取驅動程式現在的情形為何,這可以來維護系統的運作,現在有很多驅動程式已經支援這個功能,所以有許多的系統管理程式,也是透過這個介面來管理系統核心。現在我們來介紹如何在driver中撰這些程式碼。   如何啓動這個目錄 因為它是一個虛擬的記憶體檔案系統,所以將使用Linux系統中管理檔案系統一樣的方法,就是使用mount的指令將其掛載在作業系統的檔案系統中,以下為單獨載入的指令:   > mount  –t  sysfs  sysfs  /sys   另外在kernel的選項中必須要啓動以下選項:   CONFIG_SYSFS=y   系統驅動程式結構 我們先來了解一下linux kernel其中驅動程式的結構,在linux kernel的驅動程式中會將各種元件給予分門別類,並且在各種類別中會給予建構一個管理層的驅動程式,其主要目的是要建立和應用程式之間的標準介面,並且管理相同類別中的各家不同的硬體廠商,如此一來即可規範硬體廠商如何撰寫廠商,避免因不同的廠商而產生不同的驅動程式的撰寫格式不同,或者造成應用程式的介面,進而造成使用者因不同的廠商而要修改軟體。其架構圖如下:     圖一:驅動程式系統架構   以圖一中來看將會有一個RTC class產生,它將會統籌管理系統中所有的RTC元件,而系統中所有的RTC將會和它來做一個註冊,如此會產生一個RTC的class及其底下的RTC0, RTC1 ….. RTCn,其會在/sys/class之下會建立一個RTC的目錄,而每一個註冊的RTC元件將會在RTC class目錄之下產生RTC0至RTCn的子目錄,而每一個子目錄將會各...

kernel driver 使用 gpio

圖片
  Kernel Level Allocate memory to GPIO line, can be achieved by doing  gpio_request() err = gpio_request(30, "sample_name"); Depending on the requirement set GPIO as input or output pin then set gpio value as high or low. Setting the GPIO pin 30 as input gpio_direction_input(30); Make pin 30 as output and set the value as high. gpio_direction_output(30, 1); Exporting that particular pin (30) to sysfs entry then use this API gpio_export(30, true); Get value from GPIO pin gpio_get_value(30); 檢查GPIO被使用掉哪些 # cat /sys/kernel/debug/gpio User Space - Sysfs control Enable GPIO sysfs support in kernel configuration and build the kernel Device Drivers --- > GPIO Support --- > /sys/class/gpio/... (sysfs interface) Sysfs entries Export the particular GPIO pin for user control. GPIO30 is taken as example. $ echo 30 > /sys/class/gpio/export Change the GPIO pin direction to in/out $ echo "out" > /sys/class/gpio/gpio30/direction or $ echo "in" > /sys/clas...

linux kernel module 基礎

  1.3  What Is A Kernel Module? So, you want to write a kernel module. You know C, you have written a few normal programs to run as processes, and now you want to get to where the real action is, to where a single wild pointer can wipe out your file system and a core dump means a reboot. What exactly is a kernel module? Modules are pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel without the need to reboot the system.  kernel module 是段能夠被載入並且卸除的程式,可以為 kernel 增加功能但不必重啟系統 For example, one type of module is the device driver, which allows the kernel to access hardware connected to the system.  Without modules, we would have to build monolithic kernels and add new functionality directly into the kernel image. Besides having larger kernels, this has the disadvantage of requiring us to rebuild and reboot the kernel every time we want new functionality. 如不使用module就須將driver build進整個kernel image即花費大量時間編譯 1...