我编写了一个小驱动程序来读取一些数据并将其提供给用户。我的驱动程序可以被多个应用程序使用,即它是一个可重入驱动程序,因此使用自旋锁。但我发现不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 device\n");
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 code\n");
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;
}