linux – 如果需要调用copy_to_user,如何使用自旋锁?
发布时间:2020-12-14 00:52:27 所属栏目:Linux 来源:网络整理
导读:我写了一个小驱动程序来读取一些数据并将其提供给用户.我的驱动程序可以被多个应用程序使用,即它是一个可重入的驱动程序,因此使用自旋锁.但我发现不应该在保持旋转锁的情况下调用copy_to_user. char_device_buf在以下代码中是共享数据;我必须保护它.除了互斥
我写了一个小驱动程序来读取一些数据并将其提供给用户.我的驱动程序可以被多个应用程序使用,即它是一个可重入的驱动程序,因此使用自旋锁.但我发现不应该在保持旋转锁的情况下调用copy_to_user. char_device_buf在以下代码中是共享数据;我必须保护它.除了互斥锁之外是否有任何机制可以使用自旋锁并使用copy_to_user?
static ssize_t char_dev_read(struct file *file,char *buf,size_t lbuf,loff_t *ppos) { int maxbytes; /* number of bytes from ppos to MAX_LENGTH */ int bytes_to_do; /* number of bytes to read */ int nbytes; /* number of bytes actually read */ maxbytes = MAX_LENGTH - *ppos; if( maxbytes > lbuf ) bytes_to_do = lbuf; else bytes_to_do = maxbytes; if( bytes_to_do == 0 ) { printk("Reached end of devicen"); return -ENOSPC; /* Causes read() to return EOF */ } /* Tesing for accidental release */ // accidental_release(); printk(KERN_DEBUG "READER: trying for critical region lock n"); spin_lock(&myspin);/*begin of critical region */ printk(KERN_DEBUG "READER : acquired lock: executing critical coden"); nbytes = bytes_to_do - copy_to_user( buf,/* to */ char_device_buf + *ppos,/* from */ bytes_to_do ); /* how many bytes */ spin_unlock(&myspin); /* end of critical region */ *ppos += nbytes; return nbytes; } 解决方法
copy_ {to,from} _user不应该在自旋锁中使用的原因是这些函数可以休眠.想象一下这种情况(在单处理器机器上):
>处理mmap()编辑文件 除非100%保证copy_ {to,from} _user不会导致段错误,否则不能使用自旋锁,但必须使用睡眠锁,例如’mutex_lock’.睡眠锁定会对调度程序产生控制,而旋转锁定则不会. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |