Set initial device address using a random ethernet address.
[cascardo/kernel/samples/netdev/.git] / ndeth.c
1 /*
2  *  Copyright (C) 2010  Thadeu Lima de Souza Cascardo <cascardo@holoscopio.com>
3  *
4  *  This program is free software; you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation; either version 2 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License along
15  *  with this program; if not, write to the Free Software Foundation, Inc.,
16  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19
20 #include <linux/module.h>
21 #include <linux/netdevice.h>
22 #include <linux/etherdevice.h>
23 #include <linux/workqueue.h>
24
25 MODULE_LICENSE("GPL");
26
27 static void work_ndeth(struct work_struct *work)
28 {
29         printk(KERN_DEBUG "doing ndeth work\n");
30 }
31
32 static DECLARE_DELAYED_WORK(ndeth_work, work_ndeth);
33
34 static int ndeth_open(struct net_device *dev)
35 {
36         printk(KERN_DEBUG "ndeth open\n");
37         schedule_delayed_work(&ndeth_work, 4 * HZ);
38         return 0;
39 }
40
41 static int ndeth_stop(struct net_device *dev)
42 {
43         printk(KERN_DEBUG "ndeth stop\n");
44         cancel_delayed_work_sync(&ndeth_work);
45         return 0;
46 }
47
48 static int ndeth_tx(struct sk_buff *skb, struct net_device *dev)
49 {
50         dev_kfree_skb(skb);
51         return NETDEV_TX_OK;
52 }
53
54 static const struct net_device_ops ndeth_ops = {
55         .ndo_open = ndeth_open,
56         .ndo_stop = ndeth_stop,
57         .ndo_start_xmit = ndeth_tx,
58 };
59
60 struct net_device *ndeth;
61
62 static __init int ndeth_init(void)
63 {
64         int r = -ENOMEM;
65         char addr[ETH_ALEN];
66         ndeth = alloc_etherdev(0);
67         if (!ndeth)
68                 goto out;
69         ndeth->netdev_ops = &ndeth_ops;
70         random_ether_addr(addr);
71         memcpy(ndeth->dev_addr, addr, ETH_ALEN);
72         r = register_netdev(ndeth);
73         if (r)
74                 goto reg_out;
75         return 0;
76 reg_out:
77         free_netdev(ndeth);
78 out:
79         return r;
80 }
81
82 static __exit void ndeth_exit(void)
83 {
84         unregister_netdev(ndeth);
85         free_netdev(ndeth);
86 }
87
88 module_init(ndeth_init);
89 module_exit(ndeth_exit);