3

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);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
MOHAMED
  • 41,599
  • 58
  • 163
  • 268

1 Answers1

13

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.

Kristof Provost
  • 26,018
  • 2
  • 26
  • 28
  • I need your help: http://stackoverflow.com/questions/23852866/netlink-giving-kernel-panic – gangadhars May 26 '14 at 06:37
  • @kristof-provost what if for any reason nlmsg_unicast() fails in sending the message? If you have a module that produces a burst of packets, sometimes nlmsg_unicast() fails with -EAGAIN. How to handle such cases? – Alessandro Dec 06 '19 at 10:15