Question

Based on my accademic project my current task is to generate 10 random numbers using a kernel module and my user space program(c program) should be able to display those numbers. I hav been learning about kernel space and user space programs. And i came across the creation of character devices. I created a device using this command.

mknod /dev/my_device c 222 0

From what i understood this device stands as an intermediatary between the user space and kernel space programs. So i created a kernel module wich registers and unregisters my character device.Saved as my_dev.c

#include<linux/module.h>
#include<linux/init.h>
#include"my_dev.h"

MODULE_AUTHOR("Krishna");
MODULE_DESCRIPTION("A simple char device");

static int r_init(void);
static void r_cleanup(void);

module_init(r_init);
module_exit(r_cleanup);


static int r_init(void)
{
printk("<1>hi\n");
if(register_chrdev(222,"my_device",&my_fops)){
    printk("<1>failed to register");
}
return 0;
}
static void r_cleanup(void)
{
printk("<1>bye\n");
unregister_chrdev(222,"my_device");
return ;
}

My Make file for compling this module is

obj-m += my_dev.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

This kernel module is compiled and loaded into memory using insmod command.

Here is a program which writes to and reads some text to user bufer saved as my_dev.h.

/*
 * my device header file 
 */
#ifndef _MY_DEVICE_H
#define _MY_DEVICE_H

#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <asm/current.h>
#include <asm/segment.h>
#include <asm/uaccess.h>

char my_data[80]="heloooo"; /* our device */

int my_open(struct inode *inode,struct file *filep);
int my_release(struct inode *inode,struct file *filep);
ssize_t my_read(struct file *filep,char *buff,size_t count,loff_t *offp );
ssize_t my_write(struct file *filep,const char *buff,size_t count,loff_t *offp );

struct file_operations my_fops={
    open: my_open,
    read: my_read,
write: my_write,
release:my_release,
};

int my_open(struct inode *inode,struct file *filep)
{  
    /*MOD_INC_USE_COUNT;*/ /* increments usage count of module */
return 0;
}

int my_release(struct inode *inode,struct file *filep)
{
/*MOD_DEC_USE_COUNT;*/ /* decrements usage count of module */
return 0;
}
ssize_t my_read(struct file *filep,char *buff,size_t count,loff_t *offp )
{
/* function to copy kernel space buffer to user space*/
if ( copy_to_user(buff,my_data,strlen(my_data)) != 0 )
    printk( "Kernel -> userspace copy failed!\n" );
return strlen(my_data);

}
ssize_t my_write(struct file *filep,const char *buff,size_t count,loff_t *offp )
{
/* function to copy user space buffer to kernel space*/
if ( copy_from_user(my_data,buff,count) != 0 )
    printk( "Userspace -> kernel copy failed!\n" );
return 0;
}
#endif

Here is my user space program acs.c which upon running prints "heloooo" by reading the text from kernel buffer from the above program.

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

int main()
{
int fd=0,ret=0;
char buff[80]="";

fd=open("/dev/my_device",O_RDONLY);

printf("fd :%d\n",fd);

ret=read(fd,buff,10);
buff[ret]='\0';

printf("buff: %s ;length: %d bytes\n",buff,ret);
close(fd);
}

Now my issue is i need to write a user space program which up on running prints 10 random numbers. But these numbers should be generated using a kernel module. So Basically above three codes worls properly and prints "helooo" . what i need to do is instead of the "helooo" i need to get random numbers as output.

Here is a memory module which generates some random numbers using linear congruential generator algorithm. LCG.c

#include <linux/module.h>   /* Needed by all modules */
#include <linux/kernel.h>   /* Needed for KERN_INFO */

int init_module(void)
{
int M = 8;  //Modulus,    M>0
    int a = 9;  //Multiplier, 0 <= a < M.
    int c = 3;  //Increment,  0 <= c < M.
    int X = 1;  //seed value, 0 <= X(0) < M
    int i;      //iterator,   i < M 
    for(i=0; i<8; i++)
    {
            X = (a * X + c) % M;
            printk(KERN_INFO "%d\n",X);

    }
    return 0;
}
void cleanup_module(void)
{
printk(KERN_INFO "Task Done ! :D.\n");
}

I have all the codes. But i dont know how to fit this random number generator code in my charecter device invokation code . When i run the program acs.c i need to get the output of the memory module LCG.c by making use of character device. Please help me to find a solution.

Was it helpful?

Solution

Try with these changes, I've just added the changes:

Refactor LCG.C so that the random number generator is a separate function and make sure this function is not static. You should also need to export this SYMBOL.

void generate_random_lcg(char* output_str)
{
    static const int M = 8;  //Modulus,    M>0
    static const int a = 9;  //Multiplier, 0 <= a < M.
    static const int c = 3;  //Increment,  0 <= c < M.
    static int X = 1;  //seed value, 0 <= X(0) < M

    int i;      //iterator,   i < M 
    ssize_t index = 0;
    for(i=0; i<8; i++)
    {
        X = (a * X + c) % M;
        index += sprintf(output_str + index, "%d\n", X);
    }
    output_str[index] = '\0';
}

EXPORT_SYMBOL(generate_random_lcg);

This way, the function can be directly invoked by the the LCG module as well as from outside.

Now to invoke this function from your module my_dev, and to return the output, you need these changes:

my_dev.c:

static int r_init(void)
{                                                                 
    printk("<1>hi\n");
    if(register_chrdev(222,"my_device",&my_fops)){                
            printk("<1>failed to register");                      
    }  

    memset(output_str, 0, MAX_SIZE);                              

    return 0;                                                     
}

In my_dev.h

extern void generate_random_lcg(char* output_str);

#define MAX_SIZE 1024
static char output_str[MAX_SIZE];

ssize_t my_read(struct file *filep,char *buff,size_t count,loff_t *offp )
{
    ssize_t output_str_size = 0;
    generate_random_lcg(output_str);
    output_str_size = strlen(output_str);
    /* function to copy kernel space buffer to user space*/
    if (copy_to_user(buff,output_str,output_str_size) != 0 )
    {
        printk( "Kernel -> userspace copy failed!\n" );
        return 0;
    }   
    return output_str_size;
}

Few things to keep in mind:

  • Update the value of MAX_SIZE as per your needs. If the number gets really big, you could think of using kmalloc instead to get the memory.
  • It is a really bad coding practice to define function implementations within .h files except for inline functions.
  • When copy_from_user or copy_to_user fails return 0 instead of the output from strlen.

The above is just a very crude implementaiton, you might also need extra checks to check for buffer overflows when printing the string using sprintf.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top