1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2012 GCT Semiconductor, Inc. All rights reserved. */
4 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
6 #include <linux/export.h>
7 #include <linux/mutex.h>
8 #include <linux/etherdevice.h>
9 #include <linux/netlink.h>
10 #include <asm/byteorder.h>
13 #include "netlink_k.h"
15 static DEFINE_MUTEX(netlink_mutex);
17 #define ND_MAX_GROUP 30
18 #define ND_IFINDEX_LEN sizeof(int)
19 #define ND_NLMSG_SPACE(len) (NLMSG_SPACE(len) + ND_IFINDEX_LEN)
20 #define ND_NLMSG_DATA(nlh) ((void *)((char *)NLMSG_DATA(nlh) + \
22 #define ND_NLMSG_S_LEN(len) (len + ND_IFINDEX_LEN)
23 #define ND_NLMSG_R_LEN(nlh) (nlh->nlmsg_len - ND_IFINDEX_LEN)
24 #define ND_NLMSG_IFIDX(nlh) NLMSG_DATA(nlh)
25 #define ND_MAX_MSG_LEN (1024 * 32)
27 static void (*rcv_cb)(struct net_device *dev, u16 type, void *msg, int len);
29 static void netlink_rcv_cb(struct sk_buff *skb)
32 struct net_device *dev;
38 pr_err("nl cb - unregistered\n");
42 if (skb->len < NLMSG_HDRLEN) {
43 pr_err("nl cb - invalid skb length\n");
47 nlh = (struct nlmsghdr *)skb->data;
49 if (skb->len < nlh->nlmsg_len || nlh->nlmsg_len > ND_MAX_MSG_LEN) {
50 pr_err("nl cb - invalid length (%d,%d)\n",
51 skb->len, nlh->nlmsg_len);
55 memcpy(&ifindex, ND_NLMSG_IFIDX(nlh), ND_IFINDEX_LEN);
56 msg = ND_NLMSG_DATA(nlh);
57 mlen = ND_NLMSG_R_LEN(nlh);
59 dev = dev_get_by_index(&init_net, ifindex);
61 rcv_cb(dev, nlh->nlmsg_type, msg, mlen);
64 pr_err("nl cb - dev (%d) not found\n", ifindex);
68 static void netlink_rcv(struct sk_buff *skb)
70 mutex_lock(&netlink_mutex);
72 mutex_unlock(&netlink_mutex);
75 struct sock *netlink_init(int unit,
76 void (*cb)(struct net_device *dev, u16 type,
80 struct netlink_kernel_cfg cfg = {
84 sock = netlink_kernel_create(&init_net, unit, &cfg);
92 int netlink_send(struct sock *sock, int group, u16 type, void *msg, int len,
93 struct net_device *dev)
96 struct sk_buff *skb = NULL;
100 if (group > ND_MAX_GROUP)
103 if (!netlink_has_listeners(sock, group + 1))
106 skb = alloc_skb(NLMSG_SPACE(len), GFP_ATOMIC);
112 nlh = nlmsg_put(skb, 0, seq, type, len, 0);
113 memcpy(NLMSG_DATA(nlh), msg, len);
114 NETLINK_CB(skb).portid = 0;
115 NETLINK_CB(skb).dst_group = 0;
117 ret = netlink_broadcast(sock, skb, 0, group + 1, GFP_ATOMIC);
122 netdev_err(dev, "nl broadcast g=%d, t=%d, l=%d, r=%d\n",
123 group, type, len, ret);
124 else if (netlink_has_listeners(sock, group + 1))