0
votes

I have to keep a track of KeyStates, I want to use the following enum,

typedef enum{
KeyOn,
KeyOff,
}State; 

I want to pass this to the userspace program. I am not sure how my copy_to_user() function should be written. How do i pass the state of the key press to the userspace?

1
You cant pass the "enum". You can only pass the number which in the source code level represents the enum member name. - 0___________
Please don't use enum as the public interface, the size of the datatype changes depending on the values and the compiler. Between the kernel and userspace, you should be using types such as u32. - ephemient
@ephemient, how can u32 be passed using copy_to_user, I don't understand how copy_to_user exactly works on different cases - claw107
What's Key? For key buttons kernel has a good long established interface. - 0andriy
@0andriy, I want a custom driver for a 4x4 keypad (stackoverflow.com/questions/45382982/…), i am using the fops read to pass the status of the keys. - claw107

1 Answers

1
votes

Let's first address the issue of what copy_to_user does and why is it needed?

Modern computers work with a mechanism that's called Virtual Memory. This is a mechanism that allows 2 main things - The separation of memory between different processes, and the allocation of more virtual memory than there is physical memory on the machine.

For each process, there's a a distinct virtual memory space, and different processes could have the same Virtual Address point to different Physical addresses.

The kernel maps between the Virtual address spaces of processes to their Physical addresses. But what happens when you pass the Kernel a pointer?

The pointer you pass to the kernel is a virtual address in the user space processes virtual memory. The kernel needs to translate that address into the corresponding physical address in order to fill that address with the result. For that operation copy_to_user was created - It takes a pointer in the Kernel's address space and copies it into a pointer in the user processes address space.

From all written above you should already understand that your question is invalid - an Enum value is not a pointer, so there's no need to call copy_to_user on it, you can just return it as is.

The next thing we need to discuss is what's an ENUM. An enum is a syntactic sugar provided by many modern languages to allow the definition of values as human-readable identifiers. The enum keys don't exist past-compilation, there's just integer values passed between functions. They are translated much like #define into their value, and the named key doesn't matter anymore.

The only thing you need to do when returning an ENUM from the kernel, is make sure you #include the proper header in the user program so that you can translate the numbers which the enum keys represent correctly in your program. In runtime - numbers are all that's being passed.