简体   繁体   中英

how to access value of physical memory and store the value via making file in linux kernel

I'm a kernel newbie and have a bad English.

I have an STM32 board. STM32 board has a unique Id.

I want to access a physical memory address that stores unique Id and takes a value of the address.

And then I want to store value to buffer because of making files consist of unique Id.

My final Destination is making a file that contains the Unique Id of the board.

Below is my code.

u8 buf_uniqueId[12];
void __iomem *Unique_Id = ioremap(0x5C005234, 12);

if(Unique_Id == NULL){
    printk(KERN_INFO "count not found UniqueId\n");
    return 1;
}

printk(KERN_INFO "This is UniqueId\n");


struct file *unique = filp_open("/Unique_Id", O_WRONLY|O_CREAT, 0644);

if(unique == -1){
    printk("[!] Can't crate the dstfile");
    return 2;
}
else{
    fs = get_fs();
    set_fs(get_ds());
    for(i=0;i<12;i++){
        buf_uniqueId[i]=readb(Unique_Id+i);
        
        printk(KERN_DEBUG "value of buffer is %02x\n", buf_uniqueId[i]);
        printk("%02x ", readb(Unique_Id+i));
    }
    vfs_write(unique, buf_uniqueId, strlen(buf_uniqueId), &unique->f_pos);
}

The reading value of physical memory works well.

But storing the value to the buffer is failed.

Please give me advice.

Thank you.

Although the definition for buf_uniqueId is missing, storing to a valid array with at least 12 elements should work OK. Consider readb() possibly returning a zero. Instead of calling strlen() and expecting a NULL-terminated string, the write size should be one of sizeof() or fixed at 12, depending on buf_uniqueId allocation. You might replace each 12 with a #define symbol.

Suggest removing the get_fs() and set_fs() lines, along with replacing vfs_write() with a call to kernel_write() and check the result; also note the old_fs restoration within kernel_write()

The compiler should complain about comparing pointer and integer: (unique == -1) ; filp_open() could return various error codes; follow the source code from filp_open() to see various error related macros, eg IS_ERR()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM