20200402-01 Linux 原子鎖及驅動入門例程

註釋:文章最後是完成的代碼

設備環境說明:
1 ubuntu 18.04
2 arm-linux-gnueabihf-gcc (直接在新力得或者sudo apt install gcc-arm-linux-gnueabihf 指令下載即可)
3 使用周立功 M6Y2C 開發板進行測試
4 芯片是 Cortex-A7 Nxp imx6ul

說明

本次主要測試原子鎖

原子鎖的主要應用場景是在於整形和位操作
在實際多線程運行過程中,可能導致多條指令會被內核分成多次分開執行這就有可能產生問題,原子鎖就是將它們捆綁一體強制要求內核順序一次性將其執行完畢

線程A 線程B
A
B     
      A
      B
C   
      C
實際我們的目標
線程A 線程B
A
B
C     
      A
      B
      C

使用步驟

  1. 定義
    32bit:atmoic_t a;
    64bit:atmoic64_t a;
  2. 常見操作
函數 描述
ATOMIC_INIT(int i) //定義原子變量初始化
int atomic_read(atomic_t *v) 讀取 v 值
void atomic_set(atomic_t *v, int i) 寫入 i 值
void atomic_add(int i, atomic_t *v) 加上 i 值
void atomic_sub(int i, atomic_t *v) 減去 i 值
void atomic_inc(atomic_t *v) 加 1,自增
void atomic_dec(atomic_t *v) 減 1,自減
int atomic_dec_return(atomic_t *v) 自減 1, 並返回 v
int atomic_inc_return(atomic_t *v) 自增 1, 並返回 v
int atomic_sub_and_test(int i, atomic_t *v) 減去 i,結果爲 0 返回真,其餘返回假
int atomic_dec_and_test(atomic_t *v) 自減 1,結果爲 0 返回真,其餘返回假
int atomic_inc_and_test(atomic_t *v) 自增 1,結果爲 0 返回真,其餘返回假
int atomic_add_negative(int i, atomic_t *v) 加上 i,結果爲負返回真,其餘返回假
  1. e.g:
atomic_t v = ATMOIC_INIT(0);
atomic_set(10);
atomic_read(&v);
atomic_inc(&v); // 自增 1,11
  1. 位操作
    原子位操作,是直接對內存操作
函數 描述
void set_bit(int nr, void *p) 將 p 地址的第 nr 位 置 1
void clear_bit(int nr, void *p) 清 0
void change_bit(int nr, void *p) 反轉
void test_bit(int nr, void *p) 獲取值
void test_and_set_bit(int nr, void* p) 讀取原值,並設置爲 1
void test_and_clear_bit(int nr, void* p) 讀取原值,並清 0
void test_and_change_bit(int nr, void* p) 讀取原值,並反轉

函數解析

  1. 在初始化函數中,初始化
    atomic_set(&gpioled.lock, 1);
  2. 在 open 函數中,判斷鎖的狀態
// 檢查是否被使用  這個函數本質就是先自減 1 然後判斷是否爲0
if (!atomic_long_dec_and_test(&gpioled.lock)) {
    //這邊需要自增 1, 以確保負值變 0
    atomic_inc(&gpioled.lock);
    return -EBUSY; //返回忙的狀態
}
  1. 在 release 函數中,釋放鎖的狀態
struct gpioled_dev *dev = filp->private_data;
atomic_inc(&dev->lock);
return 0;

測試方法

./atomiclock /dev/gpioled 1 & //& 移到後臺執行
./atomiclock /dev/gpioled 0

以上就是原子鎖的實驗


源碼

atomiclock.c 驅動程序

#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/gpio.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_gpio.h>
#include <asm/mach/map.h>
#include <asm/uaccess.h>
#include <asm/io.h>


#define GPIOLED_CNT 1 //個數
#define GPIOLED_NAME "gpioled"
#define LEDOFF 0
#define LEDON  1

struct gpioled_dev {
    dev_t devid;    //設備號
    struct cdev cdev;       //cdev
    struct class *class;    //類
    struct device *device;  //設備
    int major;              //主設備號
    int minor;              //次設備號
    struct device_node *nd; //設備節點
    int led_gpio;           //led gpio 編號
    atomic_t lock;          //原子鎖
};

struct gpioled_dev gpioled;

static int led_open(struct inode* inode, struct file* filp)
{
    //檢查是否已被使用
    if (!atomic_long_dec_and_test(&gpioled.lock)) {
        atomic_inc(&gpioled.lock); //小於 0 就 +1, 使其原子變量等於 0
        return -EBUSY; //LED 被使用返回忙
    }
    filp->private_data = &gpioled;
    return 0;
}

static ssize_t led_read(struct file* filp, char __user *buf,
                        size_t cnt, loff_t* offt)
{
    return 0;
}

static ssize_t led_write(struct file* filp, const char __user* buf,
                         size_t cnt, loff_t* offt)
{
    int retvalue = 0;
    unsigned char databuf[1];
    unsigned char ledstat = 0;
    struct gpioled_dev* dev = filp->private_data;

    retvalue = copy_from_user(databuf, buf, cnt);
    if (retvalue < 0) {
        printk("kernel write failed \n");
        return -EFAULT;
    }

    ledstat = databuf[0];
    printk("gpio: %d Status: %d \n", dev->led_gpio, ledstat);
    if (LEDON == ledstat) {
        gpio_set_value(dev->led_gpio, 0); //打開LED
    } else if (LEDOFF == ledstat) {
        gpio_set_value(dev->led_gpio, 1);
    }
    return 0;
}

static int led_release(struct inode *inode, struct file *filp)
{
    struct gpioled_dev *dev = filp->private_data;
    //關閉驅動文件的時候釋放原子變量
    atomic_inc(&dev->lock);
    return 0;
}

static struct file_operations gpioled_fops = {
    .owner = THIS_MODULE,
    .open = led_open,
    .read = led_read,
    .write = led_write,
    .release = led_release,
};

static int __init led_init(void)
{
    int ret = 0;

    //初始化原子變量
    atomic_set(&gpioled.lock, 1);

    gpioled.nd = of_find_node_by_path("/gpioled");
    if (gpioled.nd == NULL) {
        printk("gpioled node not find! \n");
        return -EINVAL;
    } else {
        printk("gpioled node find! \n");
    }

    gpioled.led_gpio = of_get_named_gpio(gpioled.nd, "led-gpio", 0);
    if (gpioled.led_gpio < 0) {
        printk ("can't get led-gpio \n");
        return -EINVAL;
    }
    printk("led-gpio num = %d \n", gpioled.led_gpio);

    ret = gpio_direction_output(gpioled.led_gpio, 0);
    if (ret < 0) {
        printk("can't set gpio \n");
    }

    if (gpioled.major) {
        gpioled.devid = MKDEV(gpioled.major, 0);
        register_chrdev_region(gpioled.devid, GPIOLED_CNT, GPIOLED_NAME);
    } else {
        alloc_chrdev_region(&gpioled.devid, 0, GPIOLED_CNT, GPIOLED_NAME);
        gpioled.major = MAJOR(gpioled.devid);
        gpioled.minor = MINOR(gpioled.devid);
    }
    printk("gpioled major = %d, minor = %d \n", gpioled.major, gpioled.minor);

    gpioled.cdev.owner = THIS_MODULE;
    cdev_init(&gpioled.cdev, &gpioled_fops);

    cdev_add(&gpioled.cdev, gpioled.devid, GPIOLED_CNT);

    gpioled.class = class_create(THIS_MODULE, GPIOLED_NAME);
    if (IS_ERR(gpioled.class)) {
        return PTR_ERR(gpioled.class);
    }

    gpioled.device = device_create(gpioled.class, NULL, gpioled.devid,
                                   NULL, GPIOLED_NAME);
    if (IS_ERR(gpioled.device)) {
        return PTR_ERR(gpioled.device);
    }
    return 0;
}

static void __exit led_exit(void)
{
    cdev_del(&gpioled.cdev);
    unregister_chrdev_region(gpioled.devid, GPIOLED_CNT);

    device_destroy(gpioled.class, gpioled.devid);
    class_destroy(gpioled.class);
}




module_init(led_init);
module_exit(led_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("zzz");


測試 APP

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

#define LEDOFF 0
#define LEDON  1

int main(int argc, char* argv[])
{
    int fd, retvalue;
    char* filename;
    unsigned char cnt = 0;
    unsigned char databuf[1];

    if (argc != 3) {
        printf("Error Usage! \n");
        return -1;
    }

    filename = argv[1];

    fd = open(filename, O_RDWR);
    if (fd < 0) {
        printf("file %s open failed ! \n", argv[1]);
        return -1;
    }

    databuf[0] = atoi(argv[2]);

    retvalue = write(fd, databuf, sizeof(databuf));
    if (retvalue < 0) {
        printf("LED Control Failed ! \n");
        return -1;
    }

    //模擬佔用 25s LED
    while(1) {
        sleep(5);
        cnt++;
        printf("App running times: %d \n", cnt);
        if (cnt >= 5) break;
    }
    printf("App running finished \n");

    retvalue = close(fd);
    if (retvalue < 0) {
        printf("file %s close failed !\n", argv[1]);
        return -1;
    }
    return 0;
}

Makefile

KERNELDIR := /home/x/workspace/01_linux_kernel/test/imx_4.1.15_2.0.0_ga_rc3/
CURRENT_PATH := $(shell pwd)
obj-m := atomiclock.o

build: kernel_modules

kernel_modules:
	$(MAKE) ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- EXTRA_CFLAGS=-fno-pic -C $(KERNELDIR) M=`pwd` modules 

clean:
	$(MAKE) ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- -C $(KERNELDIR) M=`pwd` clean

App 編譯指令

arm-linux-gnueabihf-gcc atomiclock_app.c -o atomiclock

設備樹配置

/ {
        gpioled {
                compatible = "atkalpha-gpioled";
                #address-cells = <1>;
                #size-cells = <1>;
                pinctrl-names = "default";
                pinctrl-0 = <&pinctrl_led>;
                led-gpio = <&gpio4 14 GPIO_ACTIVE_LOW>;
                status = "okay";
};
        };
 &iomuxc{
	        pinctrl_led: ledgrp {
	                fsl,pins = <
	                        MX6UL_PAD_NAND_CE1_B__GPIO4_IO14        0x40017059
	                >;
	        };
   		};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章