在Linux内核驱动中,构建一个结构体指针数组,其中存放的是定义如下的结构体struct msg { u16 module_id; u16 cmd_id; u16 cmd_subid; u16 complete; u8 data[128]; };,请你给出操作这个结构体指针数组的功能函数,分别为:初始化,加入数组,出数组等;再写两个函数,函数一构建msg,除msg中的data数组外,其他成员赋值为常数,并将两个unsigned int 类型的值使用移位的方式放入data数组中,并向数组中放置msg,使用usleep_range()函数等待函数二将msg的complete成员设置为1后,再退出函数;函数二将msg从队列中取出来,解析msg中的module_id,如果该值不为0x1,则报错,否则使用switch函数解析cmd_id,并根据不同的cmd_id再解析cmd_subid,将msg内data数组中放入的两个unsigned int值还原,并将其作为两个参数用在下列函数前两个参数中,static unsigned int phytuart_msg_cmd_set_txim(unsigned int im, unsigned int txim, struct pokemon_uart_port *pup) { if (txim == 0) { im &= ~REG_IMSC_TXIM; pokemon_uart_write(im, pup, REG_IMSC); } else{ im |= REG_IMSC_TXIM; pokemon_uart_write(im, pup, REG_IMSC); } return im; }并将msg中的complete成员设置为1,函数一和函数二需要使用队列的操作函数,注意函数一中将msg放进数组后,需要调用函数二解析,请给出详细代码
时间: 2024-03-15 18:44:42 浏览: 126
以下是操作结构体指针数组的功能函数:
```c
#define MAX_MSG_ARRAY_SIZE 100
struct msg *msg_array[MAX_MSG_ARRAY_SIZE];
int msg_array_tail = 0;
void init_msg_array() {
int i;
for (i = 0; i < MAX_MSG_ARRAY_SIZE; i++) {
msg_array[i] = NULL;
}
msg_array_tail = 0;
}
int add_msg_to_array(struct msg *msg) {
if (msg_array_tail >= MAX_MSG_ARRAY_SIZE) {
return -1;
}
msg_array[msg_array_tail++] = msg;
return 0;
}
struct msg *get_msg_from_array() {
if (msg_array_tail <= 0) {
return NULL;
}
struct msg *msg = msg_array[0];
int i;
for (i = 1; i < msg_array_tail; i++) {
msg_array[i - 1] = msg_array[i];
}
msg_array[msg_array_tail - 1] = NULL;
msg_array_tail--;
return msg;
}
```
以下是函数一和函数二的代码:
```c
#define MSG_DATA_SIZE 128
struct msg *build_msg(unsigned int module_id, unsigned int cmd_id, unsigned int cmd_subid) {
struct msg *msg = (struct msg *) kmalloc(sizeof(struct msg), GFP_KERNEL);
msg->module_id = module_id;
msg->cmd_id = cmd_id;
msg->cmd_subid = cmd_subid;
msg->complete = 0;
unsigned int *data = (unsigned int *) msg->data;
data[0] = (module_id << 16) | cmd_id;
data[1] = cmd_subid;
return msg;
}
void wait_for_complete(struct msg *msg) {
while (msg->complete == 0) {
usleep_range(10000, 11000);
}
}
void set_msg_complete(struct msg *msg) {
msg->complete = 1;
}
void handle_msg(struct msg *msg) {
if (msg->module_id != 0x1) {
printk(KERN_ERR "Invalid module id!\n");
return;
}
unsigned int *data = (unsigned int *) msg->data;
unsigned int cmd = data[0];
unsigned int cmd_subid = data[1];
struct pokemon_uart_port *pup = get_pokemon_uart_port();
unsigned int im = pup->im;
switch (cmd) {
case 0x100:
switch (cmd_subid) {
case 0x1:
im = phytuart_msg_cmd_set_txim(im, data[2], data[3], pup);
break;
// Other cmd_subid cases
}
break;
// Other cmd cases
}
pup->im = im;
set_msg_complete(msg);
}
```
需要注意的是,上述代码中的 `phytuart_msg_cmd_set_txim()` 函数并未给出,需要自行实现。另外,为了正确使用 `kmalloc()` 函数分配内存,需要在代码文件的开头包含 `<linux/slab.h>` 头文件。
阅读全文