clinuxmemory-managementkernel-module

kernel-module: should top-level pointer be static?


I'm writing a filter that receives keyboard events, filters some out, and lets the rest through.

It takes the form of a kernel module and plugs into the i8042 kernel module, which provides a mechanism for installing and calling this sort of filter.

At the top-level of my module (outside any function call), I define a datatype that holds info about a single key:

struct key_data {
    bool is_pressed;
    unsigned long updated_at;
};

I then declare (still at the top-level) a pointer to that type, in order to store and reference info for 128 different keys:

#define NUM_KEYS 128
#define SIZEOF_KEYS (sizeof(struct key_data) * NUM_KEYS)

struct key_data *keys;

The function that initializes the filter allocates memory accordingly:

// inside inialation function
keys = vmalloc(SIZEOF_KEYS);
if (keys)
    memset(keys, 0x00, SIZEOF_KEYS);

Similarly, the function that removes the filter frees the memory:

// inside removal function
vfree(keys);

My question is, should the keys pointer be declared static?

static struct key_data *keys;

I'm curious whether this affects memory allocation/freeing in any way.

If more context is helpful, here is a simplified version of such a filter: gist


Solution

  • Unless you have need to access your variable directly outside your module, you should always use the static keyword to your module level variables. This makes it so that only code inside your module can access it, which in turn ensures that you don't run into name-space collisions with other modules. I haven't checked, but you can imagine several other files in the Linux kernel with a variety able named keys.

    This is true in general, not just in the Linux kernel. If you don't need to expose it, then don't.

    There are places in the kernel which do expose one or more global variables, but those tend to be for very specific reasons.