• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /asuswrt-rt-n18u-9.0.0.4.380.2695/release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/net/
1/* A network driver using virtio.
2 *
3 * Copyright 2007 Rusty Russell <rusty@rustcorp.com.au> IBM Corporation
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18 */
19//#define DEBUG
20#include <linux/netdevice.h>
21#include <linux/etherdevice.h>
22#include <linux/ethtool.h>
23#include <linux/module.h>
24#include <linux/virtio.h>
25#include <linux/virtio_net.h>
26#include <linux/scatterlist.h>
27#include <linux/if_vlan.h>
28#include <linux/slab.h>
29
30static int napi_weight = 128;
31module_param(napi_weight, int, 0444);
32
33static int csum = 1, gso = 1;
34module_param(csum, bool, 0444);
35module_param(gso, bool, 0444);
36
37#define MAX_PACKET_LEN (ETH_HLEN + VLAN_HLEN + ETH_DATA_LEN)
38#define GOOD_COPY_LEN	128
39
40#define VIRTNET_SEND_COMMAND_SG_MAX    2
41
42struct virtnet_info {
43	struct virtio_device *vdev;
44	struct virtqueue *rvq, *svq, *cvq;
45	struct net_device *dev;
46	struct napi_struct napi;
47	unsigned int status;
48
49	/* Number of input buffers, and max we've ever had. */
50	unsigned int num, max;
51
52	/* I like... big packets and I cannot lie! */
53	bool big_packets;
54
55	/* Host will merge rx buffers for big packets (shake it! shake it!) */
56	bool mergeable_rx_bufs;
57
58	/* Work struct for refilling if we run low on memory. */
59	struct delayed_work refill;
60
61	/* Chain pages by the private ptr. */
62	struct page *pages;
63
64	/* fragments + linear part + virtio header */
65	struct scatterlist rx_sg[MAX_SKB_FRAGS + 2];
66	struct scatterlist tx_sg[MAX_SKB_FRAGS + 2];
67};
68
69struct skb_vnet_hdr {
70	union {
71		struct virtio_net_hdr hdr;
72		struct virtio_net_hdr_mrg_rxbuf mhdr;
73	};
74	unsigned int num_sg;
75};
76
77struct padded_vnet_hdr {
78	struct virtio_net_hdr hdr;
79	/*
80	 * virtio_net_hdr should be in a separated sg buffer because of a
81	 * QEMU bug, and data sg buffer shares same page with this header sg.
82	 * This padding makes next sg 16 byte aligned after virtio_net_hdr.
83	 */
84	char padding[6];
85};
86
87static inline struct skb_vnet_hdr *skb_vnet_hdr(struct sk_buff *skb)
88{
89	return (struct skb_vnet_hdr *)skb->cb;
90}
91
92/*
93 * private is used to chain pages for big packets, put the whole
94 * most recent used list in the beginning for reuse
95 */
96static void give_pages(struct virtnet_info *vi, struct page *page)
97{
98	struct page *end;
99
100	/* Find end of list, sew whole thing into vi->pages. */
101	for (end = page; end->private; end = (struct page *)end->private);
102	end->private = (unsigned long)vi->pages;
103	vi->pages = page;
104}
105
106static struct page *get_a_page(struct virtnet_info *vi, gfp_t gfp_mask)
107{
108	struct page *p = vi->pages;
109
110	if (p) {
111		vi->pages = (struct page *)p->private;
112		/* clear private here, it is used to chain pages */
113		p->private = 0;
114	} else
115		p = alloc_page(gfp_mask);
116	return p;
117}
118
119static void skb_xmit_done(struct virtqueue *svq)
120{
121	struct virtnet_info *vi = svq->vdev->priv;
122
123	/* Suppress further interrupts. */
124	virtqueue_disable_cb(svq);
125
126	/* We were probably waiting for more output buffers. */
127	netif_wake_queue(vi->dev);
128}
129
130static void set_skb_frag(struct sk_buff *skb, struct page *page,
131			 unsigned int offset, unsigned int *len)
132{
133	int i = skb_shinfo(skb)->nr_frags;
134	skb_frag_t *f;
135
136	f = &skb_shinfo(skb)->frags[i];
137	f->size = min((unsigned)PAGE_SIZE - offset, *len);
138	f->page_offset = offset;
139	f->page = page;
140
141	skb->data_len += f->size;
142	skb->len += f->size;
143	skb_shinfo(skb)->nr_frags++;
144	*len -= f->size;
145}
146
147static struct sk_buff *page_to_skb(struct virtnet_info *vi,
148				   struct page *page, unsigned int len)
149{
150	struct sk_buff *skb;
151	struct skb_vnet_hdr *hdr;
152	unsigned int copy, hdr_len, offset;
153	char *p;
154
155	p = page_address(page);
156
157	/* copy small packet so we can reuse these pages for small data */
158	skb = netdev_alloc_skb_ip_align(vi->dev, GOOD_COPY_LEN);
159	if (unlikely(!skb))
160		return NULL;
161
162	hdr = skb_vnet_hdr(skb);
163
164	if (vi->mergeable_rx_bufs) {
165		hdr_len = sizeof hdr->mhdr;
166		offset = hdr_len;
167	} else {
168		hdr_len = sizeof hdr->hdr;
169		offset = sizeof(struct padded_vnet_hdr);
170	}
171
172	memcpy(hdr, p, hdr_len);
173
174	len -= hdr_len;
175	p += offset;
176
177	copy = len;
178	if (copy > skb_tailroom(skb))
179		copy = skb_tailroom(skb);
180	memcpy(skb_put(skb, copy), p, copy);
181
182	len -= copy;
183	offset += copy;
184
185	while (len) {
186		set_skb_frag(skb, page, offset, &len);
187		page = (struct page *)page->private;
188		offset = 0;
189	}
190
191	if (page)
192		give_pages(vi, page);
193
194	return skb;
195}
196
197static int receive_mergeable(struct virtnet_info *vi, struct sk_buff *skb)
198{
199	struct skb_vnet_hdr *hdr = skb_vnet_hdr(skb);
200	struct page *page;
201	int num_buf, i, len;
202
203	num_buf = hdr->mhdr.num_buffers;
204	while (--num_buf) {
205		i = skb_shinfo(skb)->nr_frags;
206		if (i >= MAX_SKB_FRAGS) {
207			pr_debug("%s: packet too long\n", skb->dev->name);
208			skb->dev->stats.rx_length_errors++;
209			return -EINVAL;
210		}
211
212		page = virtqueue_get_buf(vi->rvq, &len);
213		if (!page) {
214			pr_debug("%s: rx error: %d buffers missing\n",
215				 skb->dev->name, hdr->mhdr.num_buffers);
216			skb->dev->stats.rx_length_errors++;
217			return -EINVAL;
218		}
219		if (len > PAGE_SIZE)
220			len = PAGE_SIZE;
221
222		set_skb_frag(skb, page, 0, &len);
223
224		--vi->num;
225	}
226	return 0;
227}
228
229static void receive_buf(struct net_device *dev, void *buf, unsigned int len)
230{
231	struct virtnet_info *vi = netdev_priv(dev);
232	struct sk_buff *skb;
233	struct page *page;
234	struct skb_vnet_hdr *hdr;
235
236	if (unlikely(len < sizeof(struct virtio_net_hdr) + ETH_HLEN)) {
237		pr_debug("%s: short packet %i\n", dev->name, len);
238		dev->stats.rx_length_errors++;
239		if (vi->mergeable_rx_bufs || vi->big_packets)
240			give_pages(vi, buf);
241		else
242			dev_kfree_skb(buf);
243		return;
244	}
245
246	if (!vi->mergeable_rx_bufs && !vi->big_packets) {
247		skb = buf;
248		len -= sizeof(struct virtio_net_hdr);
249		skb_trim(skb, len);
250	} else {
251		page = buf;
252		skb = page_to_skb(vi, page, len);
253		if (unlikely(!skb)) {
254			dev->stats.rx_dropped++;
255			give_pages(vi, page);
256			return;
257		}
258		if (vi->mergeable_rx_bufs)
259			if (receive_mergeable(vi, skb)) {
260				dev_kfree_skb(skb);
261				return;
262			}
263	}
264
265	hdr = skb_vnet_hdr(skb);
266	skb->truesize += skb->data_len;
267	dev->stats.rx_bytes += skb->len;
268	dev->stats.rx_packets++;
269
270	if (hdr->hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
271		pr_debug("Needs csum!\n");
272		if (!skb_partial_csum_set(skb,
273					  hdr->hdr.csum_start,
274					  hdr->hdr.csum_offset))
275			goto frame_err;
276	}
277
278	skb->protocol = eth_type_trans(skb, dev);
279	pr_debug("Receiving skb proto 0x%04x len %i type %i\n",
280		 ntohs(skb->protocol), skb->len, skb->pkt_type);
281
282	if (hdr->hdr.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
283		pr_debug("GSO!\n");
284		switch (hdr->hdr.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
285		case VIRTIO_NET_HDR_GSO_TCPV4:
286			skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
287			break;
288		case VIRTIO_NET_HDR_GSO_UDP:
289			skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
290			break;
291		case VIRTIO_NET_HDR_GSO_TCPV6:
292			skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
293			break;
294		default:
295			if (net_ratelimit())
296				printk(KERN_WARNING "%s: bad gso type %u.\n",
297				       dev->name, hdr->hdr.gso_type);
298			goto frame_err;
299		}
300
301		if (hdr->hdr.gso_type & VIRTIO_NET_HDR_GSO_ECN)
302			skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN;
303
304		skb_shinfo(skb)->gso_size = hdr->hdr.gso_size;
305		if (skb_shinfo(skb)->gso_size == 0) {
306			if (net_ratelimit())
307				printk(KERN_WARNING "%s: zero gso size.\n",
308				       dev->name);
309			goto frame_err;
310		}
311
312		/* Header must be checked, and gso_segs computed. */
313		skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
314		skb_shinfo(skb)->gso_segs = 0;
315	}
316
317	netif_receive_skb(skb);
318	return;
319
320frame_err:
321	dev->stats.rx_frame_errors++;
322	dev_kfree_skb(skb);
323}
324
325static int add_recvbuf_small(struct virtnet_info *vi, gfp_t gfp)
326{
327	struct sk_buff *skb;
328	struct skb_vnet_hdr *hdr;
329	int err;
330
331	skb = netdev_alloc_skb_ip_align(vi->dev, MAX_PACKET_LEN);
332	if (unlikely(!skb))
333		return -ENOMEM;
334
335	skb_put(skb, MAX_PACKET_LEN);
336
337	hdr = skb_vnet_hdr(skb);
338	sg_set_buf(vi->rx_sg, &hdr->hdr, sizeof hdr->hdr);
339
340	skb_to_sgvec(skb, vi->rx_sg + 1, 0, skb->len);
341
342	err = virtqueue_add_buf_gfp(vi->rvq, vi->rx_sg, 0, 2, skb, gfp);
343	if (err < 0)
344		dev_kfree_skb(skb);
345
346	return err;
347}
348
349static int add_recvbuf_big(struct virtnet_info *vi, gfp_t gfp)
350{
351	struct page *first, *list = NULL;
352	char *p;
353	int i, err, offset;
354
355	/* page in vi->rx_sg[MAX_SKB_FRAGS + 1] is list tail */
356	for (i = MAX_SKB_FRAGS + 1; i > 1; --i) {
357		first = get_a_page(vi, gfp);
358		if (!first) {
359			if (list)
360				give_pages(vi, list);
361			return -ENOMEM;
362		}
363		sg_set_buf(&vi->rx_sg[i], page_address(first), PAGE_SIZE);
364
365		/* chain new page in list head to match sg */
366		first->private = (unsigned long)list;
367		list = first;
368	}
369
370	first = get_a_page(vi, gfp);
371	if (!first) {
372		give_pages(vi, list);
373		return -ENOMEM;
374	}
375	p = page_address(first);
376
377	/* vi->rx_sg[0], vi->rx_sg[1] share the same page */
378	/* a separated vi->rx_sg[0] for virtio_net_hdr only due to QEMU bug */
379	sg_set_buf(&vi->rx_sg[0], p, sizeof(struct virtio_net_hdr));
380
381	/* vi->rx_sg[1] for data packet, from offset */
382	offset = sizeof(struct padded_vnet_hdr);
383	sg_set_buf(&vi->rx_sg[1], p + offset, PAGE_SIZE - offset);
384
385	/* chain first in list head */
386	first->private = (unsigned long)list;
387	err = virtqueue_add_buf_gfp(vi->rvq, vi->rx_sg, 0, MAX_SKB_FRAGS + 2,
388				    first, gfp);
389	if (err < 0)
390		give_pages(vi, first);
391
392	return err;
393}
394
395static int add_recvbuf_mergeable(struct virtnet_info *vi, gfp_t gfp)
396{
397	struct page *page;
398	int err;
399
400	page = get_a_page(vi, gfp);
401	if (!page)
402		return -ENOMEM;
403
404	sg_init_one(vi->rx_sg, page_address(page), PAGE_SIZE);
405
406	err = virtqueue_add_buf_gfp(vi->rvq, vi->rx_sg, 0, 1, page, gfp);
407	if (err < 0)
408		give_pages(vi, page);
409
410	return err;
411}
412
413/* Returns false if we couldn't fill entirely (OOM). */
414static bool try_fill_recv(struct virtnet_info *vi, gfp_t gfp)
415{
416	int err;
417	bool oom;
418
419	do {
420		if (vi->mergeable_rx_bufs)
421			err = add_recvbuf_mergeable(vi, gfp);
422		else if (vi->big_packets)
423			err = add_recvbuf_big(vi, gfp);
424		else
425			err = add_recvbuf_small(vi, gfp);
426
427		oom = err == -ENOMEM;
428		if (err < 0)
429			break;
430		++vi->num;
431	} while (err > 0);
432	if (unlikely(vi->num > vi->max))
433		vi->max = vi->num;
434	virtqueue_kick(vi->rvq);
435	return !oom;
436}
437
438static void skb_recv_done(struct virtqueue *rvq)
439{
440	struct virtnet_info *vi = rvq->vdev->priv;
441	/* Schedule NAPI, Suppress further interrupts if successful. */
442	if (napi_schedule_prep(&vi->napi)) {
443		virtqueue_disable_cb(rvq);
444		__napi_schedule(&vi->napi);
445	}
446}
447
448static void virtnet_napi_enable(struct virtnet_info *vi)
449{
450	napi_enable(&vi->napi);
451
452	/* If all buffers were filled by other side before we napi_enabled, we
453	 * won't get another interrupt, so process any outstanding packets
454	 * now.  virtnet_poll wants re-enable the queue, so we disable here.
455	 * We synchronize against interrupts via NAPI_STATE_SCHED */
456	if (napi_schedule_prep(&vi->napi)) {
457		virtqueue_disable_cb(vi->rvq);
458		__napi_schedule(&vi->napi);
459	}
460}
461
462static void refill_work(struct work_struct *work)
463{
464	struct virtnet_info *vi;
465	bool still_empty;
466
467	vi = container_of(work, struct virtnet_info, refill.work);
468	napi_disable(&vi->napi);
469	still_empty = !try_fill_recv(vi, GFP_KERNEL);
470	virtnet_napi_enable(vi);
471
472	/* In theory, this can happen: if we don't get any buffers in
473	 * we will *never* try to fill again. */
474	if (still_empty)
475		schedule_delayed_work(&vi->refill, HZ/2);
476}
477
478static int virtnet_poll(struct napi_struct *napi, int budget)
479{
480	struct virtnet_info *vi = container_of(napi, struct virtnet_info, napi);
481	void *buf;
482	unsigned int len, received = 0;
483
484again:
485	while (received < budget &&
486	       (buf = virtqueue_get_buf(vi->rvq, &len)) != NULL) {
487		receive_buf(vi->dev, buf, len);
488		--vi->num;
489		received++;
490	}
491
492	if (vi->num < vi->max / 2) {
493		if (!try_fill_recv(vi, GFP_ATOMIC))
494			schedule_delayed_work(&vi->refill, 0);
495	}
496
497	/* Out of packets? */
498	if (received < budget) {
499		napi_complete(napi);
500		if (unlikely(!virtqueue_enable_cb(vi->rvq)) &&
501		    napi_schedule_prep(napi)) {
502			virtqueue_disable_cb(vi->rvq);
503			__napi_schedule(napi);
504			goto again;
505		}
506	}
507
508	return received;
509}
510
511static unsigned int free_old_xmit_skbs(struct virtnet_info *vi)
512{
513	struct sk_buff *skb;
514	unsigned int len, tot_sgs = 0;
515
516	while ((skb = virtqueue_get_buf(vi->svq, &len)) != NULL) {
517		pr_debug("Sent skb %p\n", skb);
518		vi->dev->stats.tx_bytes += skb->len;
519		vi->dev->stats.tx_packets++;
520		tot_sgs += skb_vnet_hdr(skb)->num_sg;
521		dev_kfree_skb_any(skb);
522	}
523	return tot_sgs;
524}
525
526static int xmit_skb(struct virtnet_info *vi, struct sk_buff *skb)
527{
528	struct skb_vnet_hdr *hdr = skb_vnet_hdr(skb);
529	const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest;
530
531	pr_debug("%s: xmit %p %pM\n", vi->dev->name, skb, dest);
532
533	if (skb->ip_summed == CHECKSUM_PARTIAL) {
534		hdr->hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
535		hdr->hdr.csum_start = skb->csum_start - skb_headroom(skb);
536		hdr->hdr.csum_offset = skb->csum_offset;
537	} else {
538		hdr->hdr.flags = 0;
539		hdr->hdr.csum_offset = hdr->hdr.csum_start = 0;
540	}
541
542	if (skb_is_gso(skb)) {
543		hdr->hdr.hdr_len = skb_headlen(skb);
544		hdr->hdr.gso_size = skb_shinfo(skb)->gso_size;
545		if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4)
546			hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
547		else if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6)
548			hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
549		else if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP)
550			hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP;
551		else
552			BUG();
553		if (skb_shinfo(skb)->gso_type & SKB_GSO_TCP_ECN)
554			hdr->hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
555	} else {
556		hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE;
557		hdr->hdr.gso_size = hdr->hdr.hdr_len = 0;
558	}
559
560	hdr->mhdr.num_buffers = 0;
561
562	/* Encode metadata header at front. */
563	if (vi->mergeable_rx_bufs)
564		sg_set_buf(vi->tx_sg, &hdr->mhdr, sizeof hdr->mhdr);
565	else
566		sg_set_buf(vi->tx_sg, &hdr->hdr, sizeof hdr->hdr);
567
568	hdr->num_sg = skb_to_sgvec(skb, vi->tx_sg + 1, 0, skb->len) + 1;
569	return virtqueue_add_buf(vi->svq, vi->tx_sg, hdr->num_sg,
570					0, skb);
571}
572
573static netdev_tx_t start_xmit(struct sk_buff *skb, struct net_device *dev)
574{
575	struct virtnet_info *vi = netdev_priv(dev);
576	int capacity;
577
578	/* Free up any pending old buffers before queueing new ones. */
579	free_old_xmit_skbs(vi);
580
581	/* Try to transmit */
582	capacity = xmit_skb(vi, skb);
583
584	/* This can happen with OOM and indirect buffers. */
585	if (unlikely(capacity < 0)) {
586		if (net_ratelimit()) {
587			if (likely(capacity == -ENOMEM)) {
588				dev_warn(&dev->dev,
589					 "TX queue failure: out of memory\n");
590			} else {
591				dev->stats.tx_fifo_errors++;
592				dev_warn(&dev->dev,
593					 "Unexpected TX queue failure: %d\n",
594					 capacity);
595			}
596		}
597		dev->stats.tx_dropped++;
598		kfree_skb(skb);
599		return NETDEV_TX_OK;
600	}
601	virtqueue_kick(vi->svq);
602
603	/* Don't wait up for transmitted skbs to be freed. */
604	skb_orphan(skb);
605	nf_reset(skb);
606
607	/* Apparently nice girls don't return TX_BUSY; stop the queue
608	 * before it gets out of hand.  Naturally, this wastes entries. */
609	if (capacity < 2+MAX_SKB_FRAGS) {
610		netif_stop_queue(dev);
611		if (unlikely(!virtqueue_enable_cb(vi->svq))) {
612			/* More just got used, free them then recheck. */
613			capacity += free_old_xmit_skbs(vi);
614			if (capacity >= 2+MAX_SKB_FRAGS) {
615				netif_start_queue(dev);
616				virtqueue_disable_cb(vi->svq);
617			}
618		}
619	}
620
621	return NETDEV_TX_OK;
622}
623
624static int virtnet_set_mac_address(struct net_device *dev, void *p)
625{
626	struct virtnet_info *vi = netdev_priv(dev);
627	struct virtio_device *vdev = vi->vdev;
628	int ret;
629
630	ret = eth_mac_addr(dev, p);
631	if (ret)
632		return ret;
633
634	if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC))
635		vdev->config->set(vdev, offsetof(struct virtio_net_config, mac),
636		                  dev->dev_addr, dev->addr_len);
637
638	return 0;
639}
640
641#ifdef CONFIG_NET_POLL_CONTROLLER
642static void virtnet_netpoll(struct net_device *dev)
643{
644	struct virtnet_info *vi = netdev_priv(dev);
645
646	napi_schedule(&vi->napi);
647}
648#endif
649
650static int virtnet_open(struct net_device *dev)
651{
652	struct virtnet_info *vi = netdev_priv(dev);
653
654	virtnet_napi_enable(vi);
655	return 0;
656}
657
658/*
659 * Send command via the control virtqueue and check status.  Commands
660 * supported by the hypervisor, as indicated by feature bits, should
661 * never fail unless improperly formated.
662 */
663static bool virtnet_send_command(struct virtnet_info *vi, u8 class, u8 cmd,
664				 struct scatterlist *data, int out, int in)
665{
666	struct scatterlist *s, sg[VIRTNET_SEND_COMMAND_SG_MAX + 2];
667	struct virtio_net_ctrl_hdr ctrl;
668	virtio_net_ctrl_ack status = ~0;
669	unsigned int tmp;
670	int i;
671
672	/* Caller should know better */
673	BUG_ON(!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ) ||
674		(out + in > VIRTNET_SEND_COMMAND_SG_MAX));
675
676	out++; /* Add header */
677	in++; /* Add return status */
678
679	ctrl.class = class;
680	ctrl.cmd = cmd;
681
682	sg_init_table(sg, out + in);
683
684	sg_set_buf(&sg[0], &ctrl, sizeof(ctrl));
685	for_each_sg(data, s, out + in - 2, i)
686		sg_set_buf(&sg[i + 1], sg_virt(s), s->length);
687	sg_set_buf(&sg[out + in - 1], &status, sizeof(status));
688
689	BUG_ON(virtqueue_add_buf(vi->cvq, sg, out, in, vi) < 0);
690
691	virtqueue_kick(vi->cvq);
692
693	/*
694	 * Spin for a response, the kick causes an ioport write, trapping
695	 * into the hypervisor, so the request should be handled immediately.
696	 */
697	while (!virtqueue_get_buf(vi->cvq, &tmp))
698		cpu_relax();
699
700	return status == VIRTIO_NET_OK;
701}
702
703static int virtnet_close(struct net_device *dev)
704{
705	struct virtnet_info *vi = netdev_priv(dev);
706
707	napi_disable(&vi->napi);
708
709	return 0;
710}
711
712static void virtnet_get_drvinfo(struct net_device *dev,
713				struct ethtool_drvinfo *drvinfo)
714{
715	struct virtnet_info *vi = netdev_priv(dev);
716	struct virtio_device *vdev = vi->vdev;
717
718	strncpy(drvinfo->driver, KBUILD_MODNAME, ARRAY_SIZE(drvinfo->driver));
719	strncpy(drvinfo->version, "N/A", ARRAY_SIZE(drvinfo->version));
720	strncpy(drvinfo->fw_version, "N/A", ARRAY_SIZE(drvinfo->fw_version));
721	strncpy(drvinfo->bus_info, dev_name(&vdev->dev),
722		ARRAY_SIZE(drvinfo->bus_info));
723}
724
725static int virtnet_set_tx_csum(struct net_device *dev, u32 data)
726{
727	struct virtnet_info *vi = netdev_priv(dev);
728	struct virtio_device *vdev = vi->vdev;
729
730	if (data && !virtio_has_feature(vdev, VIRTIO_NET_F_CSUM))
731		return -ENOSYS;
732
733	return ethtool_op_set_tx_hw_csum(dev, data);
734}
735
736static void virtnet_set_rx_mode(struct net_device *dev)
737{
738	struct virtnet_info *vi = netdev_priv(dev);
739	struct scatterlist sg[2];
740	u8 promisc, allmulti;
741	struct virtio_net_ctrl_mac *mac_data;
742	struct netdev_hw_addr *ha;
743	int uc_count;
744	int mc_count;
745	void *buf;
746	int i;
747
748	/* We can't dynamicaly set ndo_set_rx_mode, so return gracefully */
749	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_RX))
750		return;
751
752	promisc = ((dev->flags & IFF_PROMISC) != 0);
753	allmulti = ((dev->flags & IFF_ALLMULTI) != 0);
754
755	sg_init_one(sg, &promisc, sizeof(promisc));
756
757	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
758				  VIRTIO_NET_CTRL_RX_PROMISC,
759				  sg, 1, 0))
760		dev_warn(&dev->dev, "Failed to %sable promisc mode.\n",
761			 promisc ? "en" : "dis");
762
763	sg_init_one(sg, &allmulti, sizeof(allmulti));
764
765	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_RX,
766				  VIRTIO_NET_CTRL_RX_ALLMULTI,
767				  sg, 1, 0))
768		dev_warn(&dev->dev, "Failed to %sable allmulti mode.\n",
769			 allmulti ? "en" : "dis");
770
771	uc_count = netdev_uc_count(dev);
772	mc_count = netdev_mc_count(dev);
773	/* MAC filter - use one buffer for both lists */
774	buf = kzalloc(((uc_count + mc_count) * ETH_ALEN) +
775		      (2 * sizeof(mac_data->entries)), GFP_ATOMIC);
776	mac_data = buf;
777	if (!buf) {
778		dev_warn(&dev->dev, "No memory for MAC address buffer\n");
779		return;
780	}
781
782	sg_init_table(sg, 2);
783
784	/* Store the unicast list and count in the front of the buffer */
785	mac_data->entries = uc_count;
786	i = 0;
787	netdev_for_each_uc_addr(ha, dev)
788		memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
789
790	sg_set_buf(&sg[0], mac_data,
791		   sizeof(mac_data->entries) + (uc_count * ETH_ALEN));
792
793	/* multicast list and count fill the end */
794	mac_data = (void *)&mac_data->macs[uc_count][0];
795
796	mac_data->entries = mc_count;
797	i = 0;
798	netdev_for_each_mc_addr(ha, dev)
799		memcpy(&mac_data->macs[i++][0], ha->addr, ETH_ALEN);
800
801	sg_set_buf(&sg[1], mac_data,
802		   sizeof(mac_data->entries) + (mc_count * ETH_ALEN));
803
804	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_MAC,
805				  VIRTIO_NET_CTRL_MAC_TABLE_SET,
806				  sg, 2, 0))
807		dev_warn(&dev->dev, "Failed to set MAC fitler table.\n");
808
809	kfree(buf);
810}
811
812static void virtnet_vlan_rx_add_vid(struct net_device *dev, u16 vid)
813{
814	struct virtnet_info *vi = netdev_priv(dev);
815	struct scatterlist sg;
816
817	sg_init_one(&sg, &vid, sizeof(vid));
818
819	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
820				  VIRTIO_NET_CTRL_VLAN_ADD, &sg, 1, 0))
821		dev_warn(&dev->dev, "Failed to add VLAN ID %d.\n", vid);
822}
823
824static void virtnet_vlan_rx_kill_vid(struct net_device *dev, u16 vid)
825{
826	struct virtnet_info *vi = netdev_priv(dev);
827	struct scatterlist sg;
828
829	sg_init_one(&sg, &vid, sizeof(vid));
830
831	if (!virtnet_send_command(vi, VIRTIO_NET_CTRL_VLAN,
832				  VIRTIO_NET_CTRL_VLAN_DEL, &sg, 1, 0))
833		dev_warn(&dev->dev, "Failed to kill VLAN ID %d.\n", vid);
834}
835
836static const struct ethtool_ops virtnet_ethtool_ops = {
837	.get_drvinfo = virtnet_get_drvinfo,
838	.set_tx_csum = virtnet_set_tx_csum,
839	.set_sg = ethtool_op_set_sg,
840	.set_tso = ethtool_op_set_tso,
841	.set_ufo = ethtool_op_set_ufo,
842	.get_link = ethtool_op_get_link,
843};
844
845#define MIN_MTU 68
846#define MAX_MTU 65535
847
848static int virtnet_change_mtu(struct net_device *dev, int new_mtu)
849{
850	if (new_mtu < MIN_MTU || new_mtu > MAX_MTU)
851		return -EINVAL;
852	dev->mtu = new_mtu;
853	return 0;
854}
855
856static const struct net_device_ops virtnet_netdev = {
857	.ndo_open            = virtnet_open,
858	.ndo_stop   	     = virtnet_close,
859	.ndo_start_xmit      = start_xmit,
860	.ndo_validate_addr   = eth_validate_addr,
861	.ndo_set_mac_address = virtnet_set_mac_address,
862	.ndo_set_rx_mode     = virtnet_set_rx_mode,
863	.ndo_change_mtu	     = virtnet_change_mtu,
864	.ndo_vlan_rx_add_vid = virtnet_vlan_rx_add_vid,
865	.ndo_vlan_rx_kill_vid = virtnet_vlan_rx_kill_vid,
866#ifdef CONFIG_NET_POLL_CONTROLLER
867	.ndo_poll_controller = virtnet_netpoll,
868#endif
869};
870
871static void virtnet_update_status(struct virtnet_info *vi)
872{
873	u16 v;
874
875	if (!virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS))
876		return;
877
878	vi->vdev->config->get(vi->vdev,
879			      offsetof(struct virtio_net_config, status),
880			      &v, sizeof(v));
881
882	/* Ignore unknown (future) status bits */
883	v &= VIRTIO_NET_S_LINK_UP;
884
885	if (vi->status == v)
886		return;
887
888	vi->status = v;
889
890	if (vi->status & VIRTIO_NET_S_LINK_UP) {
891		netif_carrier_on(vi->dev);
892		netif_wake_queue(vi->dev);
893	} else {
894		netif_carrier_off(vi->dev);
895		netif_stop_queue(vi->dev);
896	}
897}
898
899static void virtnet_config_changed(struct virtio_device *vdev)
900{
901	struct virtnet_info *vi = vdev->priv;
902
903	virtnet_update_status(vi);
904}
905
906static int virtnet_probe(struct virtio_device *vdev)
907{
908	int err;
909	struct net_device *dev;
910	struct virtnet_info *vi;
911	struct virtqueue *vqs[3];
912	vq_callback_t *callbacks[] = { skb_recv_done, skb_xmit_done, NULL};
913	const char *names[] = { "input", "output", "control" };
914	int nvqs;
915
916	/* Allocate ourselves a network device with room for our info */
917	dev = alloc_etherdev(sizeof(struct virtnet_info));
918	if (!dev)
919		return -ENOMEM;
920
921	/* Set up network device as normal. */
922	dev->netdev_ops = &virtnet_netdev;
923	dev->features = NETIF_F_HIGHDMA;
924	SET_ETHTOOL_OPS(dev, &virtnet_ethtool_ops);
925	SET_NETDEV_DEV(dev, &vdev->dev);
926
927	/* Do we support "hardware" checksums? */
928	if (csum && virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) {
929		/* This opens up the world of extra features. */
930		dev->features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST;
931		if (gso && virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) {
932			dev->features |= NETIF_F_TSO | NETIF_F_UFO
933				| NETIF_F_TSO_ECN | NETIF_F_TSO6;
934		}
935		/* Individual feature bits: what can host handle? */
936		if (gso && virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4))
937			dev->features |= NETIF_F_TSO;
938		if (gso && virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6))
939			dev->features |= NETIF_F_TSO6;
940		if (gso && virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN))
941			dev->features |= NETIF_F_TSO_ECN;
942		if (gso && virtio_has_feature(vdev, VIRTIO_NET_F_HOST_UFO))
943			dev->features |= NETIF_F_UFO;
944	}
945
946	/* Configuration may specify what MAC to use.  Otherwise random. */
947	if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) {
948		vdev->config->get(vdev,
949				  offsetof(struct virtio_net_config, mac),
950				  dev->dev_addr, dev->addr_len);
951	} else
952		random_ether_addr(dev->dev_addr);
953
954	/* Set up our device-specific information */
955	vi = netdev_priv(dev);
956	netif_napi_add(dev, &vi->napi, virtnet_poll, napi_weight);
957	vi->dev = dev;
958	vi->vdev = vdev;
959	vdev->priv = vi;
960	vi->pages = NULL;
961	INIT_DELAYED_WORK(&vi->refill, refill_work);
962	sg_init_table(vi->rx_sg, ARRAY_SIZE(vi->rx_sg));
963	sg_init_table(vi->tx_sg, ARRAY_SIZE(vi->tx_sg));
964
965	/* If we can receive ANY GSO packets, we must allocate large ones. */
966	if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) ||
967	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) ||
968	    virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN))
969		vi->big_packets = true;
970
971	if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF))
972		vi->mergeable_rx_bufs = true;
973
974	/* We expect two virtqueues, receive then send,
975	 * and optionally control. */
976	nvqs = virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ) ? 3 : 2;
977
978	err = vdev->config->find_vqs(vdev, nvqs, vqs, callbacks, names);
979	if (err)
980		goto free;
981
982	vi->rvq = vqs[0];
983	vi->svq = vqs[1];
984
985	if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VQ)) {
986		vi->cvq = vqs[2];
987
988		if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_CTRL_VLAN))
989			dev->features |= NETIF_F_HW_VLAN_FILTER;
990	}
991
992	err = register_netdev(dev);
993	if (err) {
994		pr_debug("virtio_net: registering device failed\n");
995		goto free_vqs;
996	}
997
998	/* Last of all, set up some receive buffers. */
999	try_fill_recv(vi, GFP_KERNEL);
1000
1001	/* If we didn't even get one input buffer, we're useless. */
1002	if (vi->num == 0) {
1003		err = -ENOMEM;
1004		goto unregister;
1005	}
1006
1007	vi->status = VIRTIO_NET_S_LINK_UP;
1008	virtnet_update_status(vi);
1009	netif_carrier_on(dev);
1010
1011	pr_debug("virtnet: registered device %s\n", dev->name);
1012	return 0;
1013
1014unregister:
1015	unregister_netdev(dev);
1016	cancel_delayed_work_sync(&vi->refill);
1017free_vqs:
1018	vdev->config->del_vqs(vdev);
1019free:
1020	free_netdev(dev);
1021	return err;
1022}
1023
1024static void free_unused_bufs(struct virtnet_info *vi)
1025{
1026	void *buf;
1027	while (1) {
1028		buf = virtqueue_detach_unused_buf(vi->svq);
1029		if (!buf)
1030			break;
1031		dev_kfree_skb(buf);
1032	}
1033	while (1) {
1034		buf = virtqueue_detach_unused_buf(vi->rvq);
1035		if (!buf)
1036			break;
1037		if (vi->mergeable_rx_bufs || vi->big_packets)
1038			give_pages(vi, buf);
1039		else
1040			dev_kfree_skb(buf);
1041		--vi->num;
1042	}
1043	BUG_ON(vi->num != 0);
1044}
1045
1046static void __devexit virtnet_remove(struct virtio_device *vdev)
1047{
1048	struct virtnet_info *vi = vdev->priv;
1049
1050	/* Stop all the virtqueues. */
1051	vdev->config->reset(vdev);
1052
1053
1054	unregister_netdev(vi->dev);
1055	cancel_delayed_work_sync(&vi->refill);
1056
1057	/* Free unused buffers in both send and recv, if any. */
1058	free_unused_bufs(vi);
1059
1060	vdev->config->del_vqs(vi->vdev);
1061
1062	while (vi->pages)
1063		__free_pages(get_a_page(vi, GFP_KERNEL), 0);
1064
1065	free_netdev(vi->dev);
1066}
1067
1068static struct virtio_device_id id_table[] = {
1069	{ VIRTIO_ID_NET, VIRTIO_DEV_ANY_ID },
1070	{ 0 },
1071};
1072
1073static unsigned int features[] = {
1074	VIRTIO_NET_F_CSUM, VIRTIO_NET_F_GUEST_CSUM,
1075	VIRTIO_NET_F_GSO, VIRTIO_NET_F_MAC,
1076	VIRTIO_NET_F_HOST_TSO4, VIRTIO_NET_F_HOST_UFO, VIRTIO_NET_F_HOST_TSO6,
1077	VIRTIO_NET_F_HOST_ECN, VIRTIO_NET_F_GUEST_TSO4, VIRTIO_NET_F_GUEST_TSO6,
1078	VIRTIO_NET_F_GUEST_ECN, VIRTIO_NET_F_GUEST_UFO,
1079	VIRTIO_NET_F_MRG_RXBUF, VIRTIO_NET_F_STATUS, VIRTIO_NET_F_CTRL_VQ,
1080	VIRTIO_NET_F_CTRL_RX, VIRTIO_NET_F_CTRL_VLAN,
1081};
1082
1083static struct virtio_driver virtio_net_driver = {
1084	.feature_table = features,
1085	.feature_table_size = ARRAY_SIZE(features),
1086	.driver.name =	KBUILD_MODNAME,
1087	.driver.owner =	THIS_MODULE,
1088	.id_table =	id_table,
1089	.probe =	virtnet_probe,
1090	.remove =	__devexit_p(virtnet_remove),
1091	.config_changed = virtnet_config_changed,
1092};
1093
1094static int __init init(void)
1095{
1096	return register_virtio_driver(&virtio_net_driver);
1097}
1098
1099static void __exit fini(void)
1100{
1101	unregister_virtio_driver(&virtio_net_driver);
1102}
1103module_init(init);
1104module_exit(fini);
1105
1106MODULE_DEVICE_TABLE(virtio, id_table);
1107MODULE_DESCRIPTION("Virtio network driver");
1108MODULE_LICENSE("GPL");
1109