kernel crash when trying to free the skb with `nlmsg_free(skb_out)`

c, linux-kernel

Solution

You're not allowed to free the skb after you've sent it. `nlmsg_unicast()` will take care of that.

The reason is fairly simple: once you send the message it can be queued in the netlink socket for a while before anyone reads it. Just because `nlmsg_unicast()` returned it doesn't mean that the other side of the socket already got the message. If you free it before it's received you end up with a freed message in the queue, which causes the crash when the kernel tries to deliver it.

Simply allocate a new skb for every message.

Problem

I'm developing a kernel module which send messages to user space via netlink. To create a message (message to send): `skb_out = nlmsg_new(msg_size,0);`. After sending the first message and before sending the second one, I tried to free the skb_out with `nlmsg_free(skb_out)` but this function cause a kernel crash. - How to fix this crash ? or - Are there any other alternative to fre the skb_out after the send of the message? here after the source code: ``` skb_out = nlmsg_new(msg_size,0); if(!skb_out) { printk(KERN_ERR "Failed to allocate new skb\n"); return; } nlh=nlmsg_put(skb_out,0,0,NLMSG_DONE,msg_size,0); NETLINK_CB(skb_out).dst_group = 0; /* not in mcast group */ strncpy(nlmsg_data(nlh),msg,msg_size); res=nlmsg_unicast(nl_sk,skb_out,pid); if(res<0) { printk(KERN_INFO "Error while sending bak to user\n"); } nlmsg_free(skb_out); ```

Original source