天天看點

自旋鎖

自旋鎖(擷取自旋鎖->臨界區->釋放自旋鎖)

自旋鎖的名稱源于它的工作原理:嘗試擷取一個自旋鎖,如果鎖空閑就擷取該自旋鎖并繼續向下執行;如果鎖已被占用就循環檢測該鎖是否被釋放(原地打轉直到鎖被釋放) 

隻有在占用鎖的時間極短的情況下使用;不能遞歸使用一個自旋鎖(形成死鎖);占用鎖時不能使用可能引起程序排程的函數,如copy_xx_user()、kmalloc()、msleep()… 

自旋鎖主要針對SMP或單CPU搶占核心的情況,而對于單CPU非搶占核心自旋鎖退化為空操作 

自旋鎖不能阻止中斷對臨界區的通路,但可以使用帶關中斷功能的變體解決這一問題 

           

自旋鎖的使用流程:

自旋鎖接口函數:

#include <linux/spinlock.h> //自旋鎖頭檔案 

定義自旋鎖變量 

    struct spinlock my_spinlock; 或 

    spinlock_t my_spinlock; 

    spin_lock_init(&my_spinlock); //自旋鎖初始化 

獲得自旋鎖(可自旋等待,可被軟、硬體中斷) 

    void spin_lock(spinlock_t *my_spinlock); 

獲得自旋鎖(可自旋等待,儲存中斷狀态并 關閉軟、硬體中斷) 

    void spin_lock_irqsave(spinlock_t  *my_spinlock,unsigned long flags); 

釋放自旋鎖,退出臨界區 

    void spin_unlock(spinlock_t *lock) 

    void spin_unlock_irqrestore(spinlock_t *lock,unsigned long flags) 

嘗試獲得自旋鎖(不自旋等待,成功傳回1、失敗則傳回0) 

int spin_trylock(spinlock_t *lock)

           

總結:

執行個體代碼:

驅動端:

#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <mach/gpio.h>
#include <linux/delay.h>
#include <mach/regs-gpio.h>  /*S5PV210_GPH3_BASE*/
 
#define EINT_DEVICE_ID            1
 
#define DRIVER_NAME                "key_eint_race"
#define err(msg)                 printk(KERN_ERR "%s: " msg "\n", DRIVER_NAME)
#define __debug(fmt, arg...)    printk(KERN_DEBUG fmt, ##arg)
 
#define GPH3CON                    (unsigned long)(S5PV210_GPH3_BASE+ 0x00)
#define GPH3DAT                    (unsigned long)(S5PV210_GPH3_BASE + 0x04)
#define GPH2UP                    (unsigned long)(S5PV210_GPH2_BASE + 0x08)
 
static int major = 0;        /* Driver Major Number */
static int minor = 0;        /* Driver Minor Number */
struct class *key_class;
static struct device *key_device;
 
static unsigned int key;
 
static spinlock_t my_spin_lock; //
 
static unsigned int deal_key_value(unsigned int data)
{
    key = data;
    udelay(1000);
    return key;
}
 
static unsigned int deal_key_value_excl(unsigned int data)
{
    unsigned int value;
    unsigned long flag;
    /*
    *    自旋鎖解決了SMP多處理的并發問題,對于核心的搶占也可以起到關閉的作用,
    *   可仍沒有解決中斷産生的并發問題,但是不用擔心,我們可以采用spin_lock
    *   的變體spin_lock_irqsave函數完成同時關中斷的功能
    *
    *   注意:此處用自旋鎖并不合理,因為我們的臨界區udelay了1ms(時間很長),
    *   但我們本例子的目的是驗證自旋鎖的作用,在實際程式設計中要特别注意
    */
    spin_lock_irqsave(&my_spin_lock,flag);        //擷取自旋鎖
    value =deal_key_value(data);
    spin_unlock_irqrestore(&my_spin_lock,flag);        //釋放自旋鎖
    
    return value;
}
 
irqreturn_t buttons_interrupt(int irq, void *dev_id)
{    
    deal_key_value_excl((unsigned int)dev_id);
    //__debug("in eint function...\n");
    return IRQ_HANDLED;
}
 
static void key_io_port_init(void)
{
    unsigned long reg_val;
    
    reg_val = readl(GPH3CON);
    reg_val &= ~((0x0f<<0) | (0x0f<<4));
    reg_val |= ((0x01<<0) | (0x01<<4));
    writel(reg_val, GPH3CON);
 
    reg_val = readl(GPH3DAT);
    reg_val &= ~((0x01<<0) | (0x01<<1));
    writel(reg_val, GPH3DAT);
 
    reg_val = readl(GPH2UP);
    reg_val &= ~(0x03<<8);
    reg_val |= 0x02<<8;
    writel(reg_val, GPH2UP);
}
 
static ssize_t key_read(struct file *filp, char *buf, size_t count, loff_t *f_pos)
{
    int key_num;
    int cpy_len;
    int retval;
    
    key_num = deal_key_value_excl(current->pid);
    
    cpy_len = min(sizeof(key_num), count);
    retval = copy_to_user(buf, &key_num, cpy_len);
    
    return (cpy_len - retval);
}
 
/* Driver Operation structure */
static struct file_operations key_fops = {
    .owner = THIS_MODULE,
    .read = key_read,
};
 
 
static int __init key_eint_init(void)
{
    int retval;
    
    key_io_port_init();
    
    spin_lock_init(&my_spin_lock);
 
    
    //__debug("in key_eint_init\n");
    
    retval = set_irq_type(IRQ_EINT(20),IRQ_TYPE_EDGE_FALLING);
    if(retval){
        err("IRQ_EINT20 set irq type failed");
        goto error;
    }
    
    retval = request_irq(IRQ_EINT(20), buttons_interrupt, IRQF_DISABLED, 
            "KEY1", (void *)EINT_DEVICE_ID);
    if(retval){
        err("request eint20 failed");
        goto error;
    }
    
    /* Driver register */
    major = register_chrdev(major, DRIVER_NAME, &key_fops);
    if(major < 0){
        err("register char device fail");
        retval = major;
        goto error_register;
    }
    key_class=class_create(THIS_MODULE,DRIVER_NAME);
    if(IS_ERR(key_class)){
        err("class create failed!");
        retval =  PTR_ERR(key_class);
        goto error_class;
    }
    key_device=device_create(key_class,NULL, MKDEV(major, minor), NULL,DRIVER_NAME);
    if(IS_ERR(key_device)){
        err("device create failed!");
        retval = PTR_ERR(key_device);
        goto error_device;
    }
    __debug("register myDriver OK! Major = %d\n", major);
    return 0;
 
error_device:
    class_destroy(key_class);
error_class:
    unregister_chrdev(major, DRIVER_NAME);
error_register:
    free_irq(IRQ_EINT(20), (void *)EINT_DEVICE_ID);
error:
    return retval;
}
 
static void __exit key_eint_exit(void)
{
    //__debug("in key_eint_exit\n");
    
    free_irq(IRQ_EINT(20), (void *)EINT_DEVICE_ID);
 
    unregister_chrdev(major, DRIVER_NAME);
    device_destroy(key_class,MKDEV(major, minor));
    class_destroy(key_class);
 
    return;
}
 
module_init(key_eint_init);
module_exit(key_eint_exit);
 
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Eric");


           

應用層:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
 
/*Linux核心是搶占式核心,在一個系統調用未結束前,另一個系統調用也可以進入程序上下文,通路同一緩沖區*/
int main(void)
{    
    int status;
    pid_t pid;
    
    //打開檔案raceStation
    int fd_driver;
    if((fd_driver = open("/dev/key_eint_race", O_RDWR)) < 0){
        printf("file open error\n");
        exit(1);
    }
    //建立子程序
     if((pid = fork()) < 0){
        perror("fork:");
        exit(1);
    }
    else if(pid == 0){                    //判斷如果是子程序
        int num;
        while(1){
            read(fd_driver,&num,sizeof(num));    
            printf("the num value is <son-%d>: %d\n",getpid(), num);
 
        //    usleep(50*1000);
        }
        close(fd_driver);
    }else{                                //判斷如果是父程序
        int num;
        while(1){    
            read(fd_driver,&num,sizeof(num));    
            printf("the num value is <father-%d>: %d\n",getpid(), num);
 
        //    usleep(50*1000);
        }
        pid = wait(&status);
        close(fd_driver);
    }
}           

————————————————