Now that you understand how to copy data between user and kernel space (and the reverse), let's write another device driver (ch1/miscdrv_rdwr) based on our previous skeleton (ch1/miscdrv/) miscellaneous driver. The key difference is that we use a few global data items (within a structure) throughout, and actually perform some I/O in the form of reads and writes. Here, let's introduce the notion of a driver context or private driver data structure; the idea is to have a conveniently accessible data structure that contains all relevant information in one place. Here, we name this structure struct drv_ctx (see it in the code listing that follows). On driver initialization, we allocate memory to and initialize it.
Okay, there's no real secret here, it just makes it sound interesting. One of the members within this driver context data structure of ours is a so-called secret message (it's the drv_ctx.oursecret member, along with some (fake) statistics and config words). This is the simple "driver context" or private data structure we propose using:
// ch1/miscdrv_rdwr/miscdrv_rdwr.c
[ ... ]
/* The driver 'context' (or private) data structure;
* all relevant 'state info' reg the driver is here. */
struct drv_ctx {
struct device *dev;
int tx, rx, err, myword;
u32 config1, config2;
u64 config3;
#define MAXBYTES 128 /* Must match the userspace app; we should actually
* use a common header file for things like this */
char oursecret[MAXBYTES];
};
static struct drv_ctx *ctx;
Great; now let's move on to seeing and understanding the code.