#include <net/sock.h>
#include <linux/netlink.h>
#include <linux/skbuff.h>
#include "netlink_kernel_space.h"
MODULE_LICENSE("GPL");
#define NETLINK_USER 31

struct sock *nl_sk = NULL;
struct nlmsghdr *nlh;
struct sk_buff *skb_out;

typedef struct data_pack{
    unsigned long long int int_address;
    char str_data[100];
} struct_data_pack;
struct_data_pack s_data; 
int msg_size = sizeof(s_data);


int pid  = -1;
int res = -1;


void data_update(unsigned long long int addr, char text[100])
{       /* 
         * updating s_data
        */

        strcpy(s_data.str_data, text);
        s_data.int_address = addr;

}


		/* 
		 * This function sends message to the user-space
        */
void kernel_space_sender(unsigned long long int addr)
{
		/* 
		 * updating s_data
        */
		data_update(addr, "KERNER SPACE MESSAGE"); 
		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);  
		/* not in mcast group */
		NETLINK_CB(skb_out).dst_group = 0; 
		memcpy(nlmsg_data(nlh), &s_data, msg_size);
		pid = 1;
		res=nlmsg_unicast(nl_sk,skb_out,pid);
		if(res<0)
    		printk(KERN_INFO "Error while sending to user\n");

}


		/* 
		 * This function receives message from the user-space.
        */
void kernel_space_receiver(struct sk_buff *skb) 
{
		/* 
		 * updating s_data
        */
		struct_data_pack *xy;
		nlh=(struct nlmsghdr*)skb->data;
 		xy = (struct_data_pack *)NLMSG_DATA(nlh);
		printk(KERN_INFO "Received message payload in Kernel  from USER: %lld - %s\n",  xy->int_address, xy->str_data);
		//msleep(1000);
		//kernel_space_sender(xy->int_address*2);
}

		/* 
		 * This function creates the socket for kernel-user spaces and communication.
        */
void create_socket(unsigned long long int addr)
{
		struct netlink_kernel_cfg cfg = {
    	.input = kernel_space_receiver,
		};
		nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, &cfg);
		if(!nl_sk) {
				printk(KERN_ALERT "Error creating socket.\n");
		}
		//when I remove this wait the code does not work
		msleep(3000);
		/* 
		 * sending the guest physical address to the user space by calling the following function
        */
		kernel_space_sender(addr);
		netlink_kernel_release(nl_sk);
		
		return;

}
