简单易懂又实用
There is a way to get notified by the network core when a new network namespace is created or destroyed. For example, as a device driver developer or some other kernel code developer your module wants to get notified by the network core when a new network namespace created or destroyed. For this you need to create an object of struct pernet_operations and have to register with the network subsytem using the register_pernet_subsys() function. In your driver you may want to store some driver private data in the struct net object which is an object of a network namespace, and want to access that private data whenever you are notified about the namespace events. This is just like having a driver private data in net_device object.
So what you can do is, in the pernet_operations structure there are two fields, 'id' and 'size'. id is a pointer to an integer and size is an integer. You need to have a global integer variable in your driver and store that address in the 'id' field of the structure and tell the size of the private data that you want.
for example this way:
static struct pernet_operations bond_net_ops = {
.init = bond_net_init,
.exit = bond_net_exit,
.id = &bond_net_id,
.size = sizeof(struct bond_net),
};
After this when you call the register_pernet_subsys() function to register with the network subsystem, network subsytem allocates the required size of memory and maintains internally in the struct net structure. And creates a unique id and stores that in the pointer where 'id' points, that means in the bond_net_id in the above case. This id is like an anchor to your private data allocated.
After this whenever you want to access pointer to your private data you can call the net_generic() function, which returns the start of the allocated memory. for example in the above case this way;
static void __net_exit bond_net_exit(struct net *net)
{
struct bond_net *bn = net_generic(net, bond_net_id);
}
You can refer the driver drivers/net/bonding/bond_main.c.