usb: dwc3: gadget: free trb pool only from epnum 2
[pandora-kernel.git] / drivers / net / xen-netback / netback.c
1 /*
2  * Back-end of the driver for virtual network devices. This portion of the
3  * driver exports a 'unified' network-device interface that can be accessed
4  * by any operating system that implements a compatible front end. A
5  * reference front-end implementation can be found in:
6  *  drivers/net/xen-netfront.c
7  *
8  * Copyright (c) 2002-2005, K A Fraser
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License version 2
12  * as published by the Free Software Foundation; or, when distributed
13  * separately from the Linux kernel or incorporated into other
14  * software packages, subject to the following license:
15  *
16  * Permission is hereby granted, free of charge, to any person obtaining a copy
17  * of this source file (the "Software"), to deal in the Software without
18  * restriction, including without limitation the rights to use, copy, modify,
19  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
20  * and to permit persons to whom the Software is furnished to do so, subject to
21  * the following conditions:
22  *
23  * The above copyright notice and this permission notice shall be included in
24  * all copies or substantial portions of the Software.
25  *
26  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
31  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
32  * IN THE SOFTWARE.
33  */
34
35 #include "common.h"
36
37 #include <linux/kthread.h>
38 #include <linux/if_vlan.h>
39 #include <linux/udp.h>
40
41 #include <net/tcp.h>
42
43 #include <xen/events.h>
44 #include <xen/interface/memory.h>
45
46 #include <asm/xen/hypercall.h>
47 #include <asm/xen/page.h>
48
49 /*
50  * This is the maximum slots a skb can have. If a guest sends a skb
51  * which exceeds this limit it is considered malicious.
52  */
53 #define FATAL_SKB_SLOTS_DEFAULT 20
54 static unsigned int fatal_skb_slots = FATAL_SKB_SLOTS_DEFAULT;
55 module_param(fatal_skb_slots, uint, 0444);
56
57 /*
58  * To avoid confusion, we define XEN_NETBK_LEGACY_SLOTS_MAX indicating
59  * the maximum slots a valid packet can use. Now this value is defined
60  * to be XEN_NETIF_NR_SLOTS_MIN, which is supposed to be supported by
61  * all backend.
62  */
63 #define XEN_NETBK_LEGACY_SLOTS_MAX XEN_NETIF_NR_SLOTS_MIN
64
65 typedef unsigned int pending_ring_idx_t;
66 #define INVALID_PENDING_RING_IDX (~0U)
67
68 struct pending_tx_info {
69         struct xen_netif_tx_request req; /* coalesced tx request */
70         struct xenvif *vif;
71         pending_ring_idx_t head; /* head != INVALID_PENDING_RING_IDX
72                                   * if it is head of one or more tx
73                                   * reqs
74                                   */
75 };
76
77 struct netbk_rx_meta {
78         int id;
79         int size;
80         int gso_size;
81 };
82
83 #define MAX_PENDING_REQS 256
84
85 /* Discriminate from any valid pending_idx value. */
86 #define INVALID_PENDING_IDX 0xFFFF
87
88 #define MAX_BUFFER_OFFSET PAGE_SIZE
89
90 /* extra field used in struct page */
91 union page_ext {
92         struct {
93 #if BITS_PER_LONG < 64
94 #define IDX_WIDTH   8
95 #define GROUP_WIDTH (BITS_PER_LONG - IDX_WIDTH)
96                 unsigned int group:GROUP_WIDTH;
97                 unsigned int idx:IDX_WIDTH;
98 #else
99                 unsigned int group, idx;
100 #endif
101         } e;
102         void *mapping;
103 };
104
105 struct xen_netbk {
106         wait_queue_head_t wq;
107         struct task_struct *task;
108
109         struct sk_buff_head rx_queue;
110         struct sk_buff_head tx_queue;
111
112         struct timer_list net_timer;
113
114         struct page *mmap_pages[MAX_PENDING_REQS];
115
116         pending_ring_idx_t pending_prod;
117         pending_ring_idx_t pending_cons;
118         struct list_head net_schedule_list;
119
120         /* Protect the net_schedule_list in netif. */
121         spinlock_t net_schedule_list_lock;
122
123         atomic_t netfront_count;
124
125         struct pending_tx_info pending_tx_info[MAX_PENDING_REQS];
126         /* Coalescing tx requests before copying makes number of grant
127          * copy ops greater or equal to number of slots required. In
128          * worst case a tx request consumes 2 gnttab_copy.
129          */
130         struct gnttab_copy tx_copy_ops[2*MAX_PENDING_REQS];
131
132         u16 pending_ring[MAX_PENDING_REQS];
133
134         /*
135          * Given MAX_BUFFER_OFFSET of 4096 the worst case is that each
136          * head/fragment page uses 2 copy operations because it
137          * straddles two buffers in the frontend.
138          */
139         struct gnttab_copy grant_copy_op[2*XEN_NETIF_RX_RING_SIZE];
140         struct netbk_rx_meta meta[2*XEN_NETIF_RX_RING_SIZE];
141 };
142
143 static struct xen_netbk *xen_netbk;
144 static int xen_netbk_group_nr;
145
146 /*
147  * If head != INVALID_PENDING_RING_IDX, it means this tx request is head of
148  * one or more merged tx requests, otherwise it is the continuation of
149  * previous tx request.
150  */
151 static inline int pending_tx_is_head(struct xen_netbk *netbk, RING_IDX idx)
152 {
153         return netbk->pending_tx_info[idx].head != INVALID_PENDING_RING_IDX;
154 }
155
156 void xen_netbk_add_xenvif(struct xenvif *vif)
157 {
158         int i;
159         int min_netfront_count;
160         int min_group = 0;
161         struct xen_netbk *netbk;
162
163         min_netfront_count = atomic_read(&xen_netbk[0].netfront_count);
164         for (i = 0; i < xen_netbk_group_nr; i++) {
165                 int netfront_count = atomic_read(&xen_netbk[i].netfront_count);
166                 if (netfront_count < min_netfront_count) {
167                         min_group = i;
168                         min_netfront_count = netfront_count;
169                 }
170         }
171
172         netbk = &xen_netbk[min_group];
173
174         vif->netbk = netbk;
175         atomic_inc(&netbk->netfront_count);
176 }
177
178 void xen_netbk_remove_xenvif(struct xenvif *vif)
179 {
180         struct xen_netbk *netbk = vif->netbk;
181         vif->netbk = NULL;
182         atomic_dec(&netbk->netfront_count);
183 }
184
185 static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx,
186                                   u8 status);
187 static void make_tx_response(struct xenvif *vif,
188                              struct xen_netif_tx_request *txp,
189                              s8       st);
190 static struct xen_netif_rx_response *make_rx_response(struct xenvif *vif,
191                                              u16      id,
192                                              s8       st,
193                                              u16      offset,
194                                              u16      size,
195                                              u16      flags);
196
197 static inline unsigned long idx_to_pfn(struct xen_netbk *netbk,
198                                        u16 idx)
199 {
200         return page_to_pfn(netbk->mmap_pages[idx]);
201 }
202
203 static inline unsigned long idx_to_kaddr(struct xen_netbk *netbk,
204                                          u16 idx)
205 {
206         return (unsigned long)pfn_to_kaddr(idx_to_pfn(netbk, idx));
207 }
208
209 /* extra field used in struct page */
210 static inline void set_page_ext(struct page *pg, struct xen_netbk *netbk,
211                                 unsigned int idx)
212 {
213         unsigned int group = netbk - xen_netbk;
214         union page_ext ext = { .e = { .group = group + 1, .idx = idx } };
215
216         BUILD_BUG_ON(sizeof(ext) > sizeof(ext.mapping));
217         pg->mapping = ext.mapping;
218 }
219
220 static int get_page_ext(struct page *pg,
221                         unsigned int *pgroup, unsigned int *pidx)
222 {
223         union page_ext ext = { .mapping = pg->mapping };
224         struct xen_netbk *netbk;
225         unsigned int group, idx;
226
227         group = ext.e.group - 1;
228
229         if (group < 0 || group >= xen_netbk_group_nr)
230                 return 0;
231
232         netbk = &xen_netbk[group];
233
234         idx = ext.e.idx;
235
236         if ((idx < 0) || (idx >= MAX_PENDING_REQS))
237                 return 0;
238
239         if (netbk->mmap_pages[idx] != pg)
240                 return 0;
241
242         *pgroup = group;
243         *pidx = idx;
244
245         return 1;
246 }
247
248 /*
249  * This is the amount of packet we copy rather than map, so that the
250  * guest can't fiddle with the contents of the headers while we do
251  * packet processing on them (netfilter, routing, etc).
252  */
253 #define PKT_PROT_LEN    (ETH_HLEN + \
254                          VLAN_HLEN + \
255                          sizeof(struct iphdr) + MAX_IPOPTLEN + \
256                          sizeof(struct tcphdr) + MAX_TCP_OPTION_SPACE)
257
258 static u16 frag_get_pending_idx(skb_frag_t *frag)
259 {
260         return (u16)frag->page_offset;
261 }
262
263 static void frag_set_pending_idx(skb_frag_t *frag, u16 pending_idx)
264 {
265         frag->page_offset = pending_idx;
266 }
267
268 static inline pending_ring_idx_t pending_index(unsigned i)
269 {
270         return i & (MAX_PENDING_REQS-1);
271 }
272
273 static inline pending_ring_idx_t nr_pending_reqs(struct xen_netbk *netbk)
274 {
275         return MAX_PENDING_REQS -
276                 netbk->pending_prod + netbk->pending_cons;
277 }
278
279 static void xen_netbk_kick_thread(struct xen_netbk *netbk)
280 {
281         wake_up(&netbk->wq);
282 }
283
284 static int max_required_rx_slots(struct xenvif *vif)
285 {
286         int max = DIV_ROUND_UP(vif->dev->mtu, PAGE_SIZE);
287
288         /* XXX FIXME: RX path dependent on MAX_SKB_FRAGS */
289         if (vif->can_sg || vif->gso || vif->gso_prefix)
290                 max += MAX_SKB_FRAGS + 1; /* extra_info + frags */
291
292         return max;
293 }
294
295 int xen_netbk_rx_ring_full(struct xenvif *vif)
296 {
297         RING_IDX peek   = vif->rx_req_cons_peek;
298         RING_IDX needed = max_required_rx_slots(vif);
299
300         return ((vif->rx.sring->req_prod - peek) < needed) ||
301                ((vif->rx.rsp_prod_pvt + XEN_NETIF_RX_RING_SIZE - peek) < needed);
302 }
303
304 int xen_netbk_must_stop_queue(struct xenvif *vif)
305 {
306         if (!xen_netbk_rx_ring_full(vif))
307                 return 0;
308
309         vif->rx.sring->req_event = vif->rx_req_cons_peek +
310                 max_required_rx_slots(vif);
311         mb(); /* request notification /then/ check the queue */
312
313         return xen_netbk_rx_ring_full(vif);
314 }
315
316 /*
317  * Returns true if we should start a new receive buffer instead of
318  * adding 'size' bytes to a buffer which currently contains 'offset'
319  * bytes.
320  */
321 static bool start_new_rx_buffer(int offset, unsigned long size, int head)
322 {
323         /* simple case: we have completely filled the current buffer. */
324         if (offset == MAX_BUFFER_OFFSET)
325                 return true;
326
327         /*
328          * complex case: start a fresh buffer if the current frag
329          * would overflow the current buffer but only if:
330          *     (i)   this frag would fit completely in the next buffer
331          * and (ii)  there is already some data in the current buffer
332          * and (iii) this is not the head buffer.
333          *
334          * Where:
335          * - (i) stops us splitting a frag into two copies
336          *   unless the frag is too large for a single buffer.
337          * - (ii) stops us from leaving a buffer pointlessly empty.
338          * - (iii) stops us leaving the first buffer
339          *   empty. Strictly speaking this is already covered
340          *   by (ii) but is explicitly checked because
341          *   netfront relies on the first buffer being
342          *   non-empty and can crash otherwise.
343          *
344          * This means we will effectively linearise small
345          * frags but do not needlessly split large buffers
346          * into multiple copies tend to give large frags their
347          * own buffers as before.
348          */
349         if ((offset + size > MAX_BUFFER_OFFSET) &&
350             (size <= MAX_BUFFER_OFFSET) && offset && !head)
351                 return true;
352
353         return false;
354 }
355
356 /*
357  * Figure out how many ring slots we're going to need to send @skb to
358  * the guest. This function is essentially a dry run of
359  * netbk_gop_frag_copy.
360  */
361 unsigned int xen_netbk_count_skb_slots(struct xenvif *vif, struct sk_buff *skb)
362 {
363         unsigned int count;
364         int i, copy_off;
365
366         count = DIV_ROUND_UP(
367                         offset_in_page(skb->data)+skb_headlen(skb), PAGE_SIZE);
368
369         copy_off = skb_headlen(skb) % PAGE_SIZE;
370
371         if (skb_shinfo(skb)->gso_size)
372                 count++;
373
374         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
375                 unsigned long size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
376                 unsigned long bytes;
377                 while (size > 0) {
378                         BUG_ON(copy_off > MAX_BUFFER_OFFSET);
379
380                         if (start_new_rx_buffer(copy_off, size, 0)) {
381                                 count++;
382                                 copy_off = 0;
383                         }
384
385                         bytes = size;
386                         if (copy_off + bytes > MAX_BUFFER_OFFSET)
387                                 bytes = MAX_BUFFER_OFFSET - copy_off;
388
389                         copy_off += bytes;
390                         size -= bytes;
391                 }
392         }
393         return count;
394 }
395
396 struct netrx_pending_operations {
397         unsigned copy_prod, copy_cons;
398         unsigned meta_prod, meta_cons;
399         struct gnttab_copy *copy;
400         struct netbk_rx_meta *meta;
401         int copy_off;
402         grant_ref_t copy_gref;
403 };
404
405 static struct netbk_rx_meta *get_next_rx_buffer(struct xenvif *vif,
406                                                 struct netrx_pending_operations *npo)
407 {
408         struct netbk_rx_meta *meta;
409         struct xen_netif_rx_request *req;
410
411         req = RING_GET_REQUEST(&vif->rx, vif->rx.req_cons++);
412
413         meta = npo->meta + npo->meta_prod++;
414         meta->gso_size = 0;
415         meta->size = 0;
416         meta->id = req->id;
417
418         npo->copy_off = 0;
419         npo->copy_gref = req->gref;
420
421         return meta;
422 }
423
424 /*
425  * Set up the grant operations for this fragment. If it's a flipping
426  * interface, we also set up the unmap request from here.
427  */
428 static void netbk_gop_frag_copy(struct xenvif *vif, struct sk_buff *skb,
429                                 struct netrx_pending_operations *npo,
430                                 struct page *page, unsigned long size,
431                                 unsigned long offset, int *head)
432 {
433         struct gnttab_copy *copy_gop;
434         struct netbk_rx_meta *meta;
435         /*
436          * These variables a used iff get_page_ext returns true,
437          * in which case they are guaranteed to be initialized.
438          */
439         unsigned int uninitialized_var(group), uninitialized_var(idx);
440         int foreign = get_page_ext(page, &group, &idx);
441         unsigned long bytes;
442
443         /* Data must not cross a page boundary. */
444         BUG_ON(size + offset > PAGE_SIZE);
445
446         meta = npo->meta + npo->meta_prod - 1;
447
448         while (size > 0) {
449                 BUG_ON(npo->copy_off > MAX_BUFFER_OFFSET);
450
451                 if (start_new_rx_buffer(npo->copy_off, size, *head)) {
452                         /*
453                          * Netfront requires there to be some data in the head
454                          * buffer.
455                          */
456                         BUG_ON(*head);
457
458                         meta = get_next_rx_buffer(vif, npo);
459                 }
460
461                 bytes = size;
462                 if (npo->copy_off + bytes > MAX_BUFFER_OFFSET)
463                         bytes = MAX_BUFFER_OFFSET - npo->copy_off;
464
465                 copy_gop = npo->copy + npo->copy_prod++;
466                 copy_gop->flags = GNTCOPY_dest_gref;
467                 if (foreign) {
468                         struct xen_netbk *netbk = &xen_netbk[group];
469                         struct pending_tx_info *src_pend;
470
471                         src_pend = &netbk->pending_tx_info[idx];
472
473                         copy_gop->source.domid = src_pend->vif->domid;
474                         copy_gop->source.u.ref = src_pend->req.gref;
475                         copy_gop->flags |= GNTCOPY_source_gref;
476                 } else {
477                         void *vaddr = page_address(page);
478                         copy_gop->source.domid = DOMID_SELF;
479                         copy_gop->source.u.gmfn = virt_to_mfn(vaddr);
480                 }
481                 copy_gop->source.offset = offset;
482                 copy_gop->dest.domid = vif->domid;
483
484                 copy_gop->dest.offset = npo->copy_off;
485                 copy_gop->dest.u.ref = npo->copy_gref;
486                 copy_gop->len = bytes;
487
488                 npo->copy_off += bytes;
489                 meta->size += bytes;
490
491                 offset += bytes;
492                 size -= bytes;
493
494                 /* Leave a gap for the GSO descriptor. */
495                 if (*head && skb_shinfo(skb)->gso_size && !vif->gso_prefix)
496                         vif->rx.req_cons++;
497
498                 *head = 0; /* There must be something in this buffer now. */
499
500         }
501 }
502
503 /*
504  * Prepare an SKB to be transmitted to the frontend.
505  *
506  * This function is responsible for allocating grant operations, meta
507  * structures, etc.
508  *
509  * It returns the number of meta structures consumed. The number of
510  * ring slots used is always equal to the number of meta slots used
511  * plus the number of GSO descriptors used. Currently, we use either
512  * zero GSO descriptors (for non-GSO packets) or one descriptor (for
513  * frontend-side LRO).
514  */
515 static int netbk_gop_skb(struct sk_buff *skb,
516                          struct netrx_pending_operations *npo)
517 {
518         struct xenvif *vif = netdev_priv(skb->dev);
519         int nr_frags = skb_shinfo(skb)->nr_frags;
520         int i;
521         struct xen_netif_rx_request *req;
522         struct netbk_rx_meta *meta;
523         unsigned char *data;
524         int head = 1;
525         int old_meta_prod;
526
527         old_meta_prod = npo->meta_prod;
528
529         /* Set up a GSO prefix descriptor, if necessary */
530         if (skb_shinfo(skb)->gso_size && vif->gso_prefix) {
531                 req = RING_GET_REQUEST(&vif->rx, vif->rx.req_cons++);
532                 meta = npo->meta + npo->meta_prod++;
533                 meta->gso_size = skb_shinfo(skb)->gso_size;
534                 meta->size = 0;
535                 meta->id = req->id;
536         }
537
538         req = RING_GET_REQUEST(&vif->rx, vif->rx.req_cons++);
539         meta = npo->meta + npo->meta_prod++;
540
541         if (!vif->gso_prefix)
542                 meta->gso_size = skb_shinfo(skb)->gso_size;
543         else
544                 meta->gso_size = 0;
545
546         meta->size = 0;
547         meta->id = req->id;
548         npo->copy_off = 0;
549         npo->copy_gref = req->gref;
550
551         data = skb->data;
552         while (data < skb_tail_pointer(skb)) {
553                 unsigned int offset = offset_in_page(data);
554                 unsigned int len = PAGE_SIZE - offset;
555
556                 if (data + len > skb_tail_pointer(skb))
557                         len = skb_tail_pointer(skb) - data;
558
559                 netbk_gop_frag_copy(vif, skb, npo,
560                                     virt_to_page(data), len, offset, &head);
561                 data += len;
562         }
563
564         for (i = 0; i < nr_frags; i++) {
565                 netbk_gop_frag_copy(vif, skb, npo,
566                                     skb_frag_page(&skb_shinfo(skb)->frags[i]),
567                                     skb_frag_size(&skb_shinfo(skb)->frags[i]),
568                                     skb_shinfo(skb)->frags[i].page_offset,
569                                     &head);
570         }
571
572         return npo->meta_prod - old_meta_prod;
573 }
574
575 /*
576  * This is a twin to netbk_gop_skb.  Assume that netbk_gop_skb was
577  * used to set up the operations on the top of
578  * netrx_pending_operations, which have since been done.  Check that
579  * they didn't give any errors and advance over them.
580  */
581 static int netbk_check_gop(struct xenvif *vif, int nr_meta_slots,
582                            struct netrx_pending_operations *npo)
583 {
584         struct gnttab_copy     *copy_op;
585         int status = XEN_NETIF_RSP_OKAY;
586         int i;
587
588         for (i = 0; i < nr_meta_slots; i++) {
589                 copy_op = npo->copy + npo->copy_cons++;
590                 if (copy_op->status != GNTST_okay) {
591                         netdev_dbg(vif->dev,
592                                    "Bad status %d from copy to DOM%d.\n",
593                                    copy_op->status, vif->domid);
594                         status = XEN_NETIF_RSP_ERROR;
595                 }
596         }
597
598         return status;
599 }
600
601 static void netbk_add_frag_responses(struct xenvif *vif, int status,
602                                      struct netbk_rx_meta *meta,
603                                      int nr_meta_slots)
604 {
605         int i;
606         unsigned long offset;
607
608         /* No fragments used */
609         if (nr_meta_slots <= 1)
610                 return;
611
612         nr_meta_slots--;
613
614         for (i = 0; i < nr_meta_slots; i++) {
615                 int flags;
616                 if (i == nr_meta_slots - 1)
617                         flags = 0;
618                 else
619                         flags = XEN_NETRXF_more_data;
620
621                 offset = 0;
622                 make_rx_response(vif, meta[i].id, status, offset,
623                                  meta[i].size, flags);
624         }
625 }
626
627 struct skb_cb_overlay {
628         int meta_slots_used;
629 };
630
631 static void xen_netbk_rx_action(struct xen_netbk *netbk)
632 {
633         struct xenvif *vif = NULL, *tmp;
634         s8 status;
635         u16 irq, flags;
636         struct xen_netif_rx_response *resp;
637         struct sk_buff_head rxq;
638         struct sk_buff *skb;
639         LIST_HEAD(notify);
640         int ret;
641         int nr_frags;
642         int count;
643         unsigned long offset;
644         struct skb_cb_overlay *sco;
645
646         struct netrx_pending_operations npo = {
647                 .copy  = netbk->grant_copy_op,
648                 .meta  = netbk->meta,
649         };
650
651         skb_queue_head_init(&rxq);
652
653         count = 0;
654
655         while ((skb = skb_dequeue(&netbk->rx_queue)) != NULL) {
656                 vif = netdev_priv(skb->dev);
657                 nr_frags = skb_shinfo(skb)->nr_frags;
658
659                 sco = (struct skb_cb_overlay *)skb->cb;
660                 sco->meta_slots_used = netbk_gop_skb(skb, &npo);
661
662                 count += nr_frags + 1;
663
664                 __skb_queue_tail(&rxq, skb);
665
666                 /* Filled the batch queue? */
667                 /* XXX FIXME: RX path dependent on MAX_SKB_FRAGS */
668                 if (count + MAX_SKB_FRAGS >= XEN_NETIF_RX_RING_SIZE)
669                         break;
670         }
671
672         BUG_ON(npo.meta_prod > ARRAY_SIZE(netbk->meta));
673
674         if (!npo.copy_prod)
675                 return;
676
677         BUG_ON(npo.copy_prod > ARRAY_SIZE(netbk->grant_copy_op));
678         ret = HYPERVISOR_grant_table_op(GNTTABOP_copy, &netbk->grant_copy_op,
679                                         npo.copy_prod);
680         BUG_ON(ret != 0);
681
682         while ((skb = __skb_dequeue(&rxq)) != NULL) {
683                 sco = (struct skb_cb_overlay *)skb->cb;
684
685                 vif = netdev_priv(skb->dev);
686
687                 if (netbk->meta[npo.meta_cons].gso_size && vif->gso_prefix) {
688                         resp = RING_GET_RESPONSE(&vif->rx,
689                                                 vif->rx.rsp_prod_pvt++);
690
691                         resp->flags = XEN_NETRXF_gso_prefix | XEN_NETRXF_more_data;
692
693                         resp->offset = netbk->meta[npo.meta_cons].gso_size;
694                         resp->id = netbk->meta[npo.meta_cons].id;
695                         resp->status = sco->meta_slots_used;
696
697                         npo.meta_cons++;
698                         sco->meta_slots_used--;
699                 }
700
701
702                 vif->dev->stats.tx_bytes += skb->len;
703                 vif->dev->stats.tx_packets++;
704
705                 status = netbk_check_gop(vif, sco->meta_slots_used, &npo);
706
707                 if (sco->meta_slots_used == 1)
708                         flags = 0;
709                 else
710                         flags = XEN_NETRXF_more_data;
711
712                 if (skb->ip_summed == CHECKSUM_PARTIAL) /* local packet? */
713                         flags |= XEN_NETRXF_csum_blank | XEN_NETRXF_data_validated;
714                 else if (skb->ip_summed == CHECKSUM_UNNECESSARY)
715                         /* remote but checksummed. */
716                         flags |= XEN_NETRXF_data_validated;
717
718                 offset = 0;
719                 resp = make_rx_response(vif, netbk->meta[npo.meta_cons].id,
720                                         status, offset,
721                                         netbk->meta[npo.meta_cons].size,
722                                         flags);
723
724                 if (netbk->meta[npo.meta_cons].gso_size && !vif->gso_prefix) {
725                         struct xen_netif_extra_info *gso =
726                                 (struct xen_netif_extra_info *)
727                                 RING_GET_RESPONSE(&vif->rx,
728                                                   vif->rx.rsp_prod_pvt++);
729
730                         resp->flags |= XEN_NETRXF_extra_info;
731
732                         gso->u.gso.size = netbk->meta[npo.meta_cons].gso_size;
733                         gso->u.gso.type = XEN_NETIF_GSO_TYPE_TCPV4;
734                         gso->u.gso.pad = 0;
735                         gso->u.gso.features = 0;
736
737                         gso->type = XEN_NETIF_EXTRA_TYPE_GSO;
738                         gso->flags = 0;
739                 }
740
741                 netbk_add_frag_responses(vif, status,
742                                          netbk->meta + npo.meta_cons + 1,
743                                          sco->meta_slots_used);
744
745                 RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&vif->rx, ret);
746                 irq = vif->irq;
747                 if (ret && list_empty(&vif->notify_list))
748                         list_add_tail(&vif->notify_list, &notify);
749
750                 xenvif_notify_tx_completion(vif);
751
752                 xenvif_put(vif);
753                 npo.meta_cons += sco->meta_slots_used;
754                 dev_kfree_skb(skb);
755         }
756
757         list_for_each_entry_safe(vif, tmp, &notify, notify_list) {
758                 notify_remote_via_irq(vif->irq);
759                 list_del_init(&vif->notify_list);
760         }
761
762         /* More work to do? */
763         if (!skb_queue_empty(&netbk->rx_queue) &&
764                         !timer_pending(&netbk->net_timer))
765                 xen_netbk_kick_thread(netbk);
766 }
767
768 void xen_netbk_queue_tx_skb(struct xenvif *vif, struct sk_buff *skb)
769 {
770         struct xen_netbk *netbk = vif->netbk;
771
772         skb_queue_tail(&netbk->rx_queue, skb);
773
774         xen_netbk_kick_thread(netbk);
775 }
776
777 static void xen_netbk_alarm(unsigned long data)
778 {
779         struct xen_netbk *netbk = (struct xen_netbk *)data;
780         xen_netbk_kick_thread(netbk);
781 }
782
783 static int __on_net_schedule_list(struct xenvif *vif)
784 {
785         return !list_empty(&vif->schedule_list);
786 }
787
788 /* Must be called with net_schedule_list_lock held */
789 static void remove_from_net_schedule_list(struct xenvif *vif)
790 {
791         if (likely(__on_net_schedule_list(vif))) {
792                 list_del_init(&vif->schedule_list);
793                 xenvif_put(vif);
794         }
795 }
796
797 static struct xenvif *poll_net_schedule_list(struct xen_netbk *netbk)
798 {
799         struct xenvif *vif = NULL;
800
801         spin_lock_irq(&netbk->net_schedule_list_lock);
802         if (list_empty(&netbk->net_schedule_list))
803                 goto out;
804
805         vif = list_first_entry(&netbk->net_schedule_list,
806                                struct xenvif, schedule_list);
807         if (!vif)
808                 goto out;
809
810         xenvif_get(vif);
811
812         remove_from_net_schedule_list(vif);
813 out:
814         spin_unlock_irq(&netbk->net_schedule_list_lock);
815         return vif;
816 }
817
818 void xen_netbk_schedule_xenvif(struct xenvif *vif)
819 {
820         unsigned long flags;
821         struct xen_netbk *netbk = vif->netbk;
822
823         if (__on_net_schedule_list(vif))
824                 goto kick;
825
826         spin_lock_irqsave(&netbk->net_schedule_list_lock, flags);
827         if (!__on_net_schedule_list(vif) &&
828             likely(xenvif_schedulable(vif))) {
829                 list_add_tail(&vif->schedule_list, &netbk->net_schedule_list);
830                 xenvif_get(vif);
831         }
832         spin_unlock_irqrestore(&netbk->net_schedule_list_lock, flags);
833
834 kick:
835         smp_mb();
836         if ((nr_pending_reqs(netbk) < (MAX_PENDING_REQS/2)) &&
837             !list_empty(&netbk->net_schedule_list))
838                 xen_netbk_kick_thread(netbk);
839 }
840
841 void xen_netbk_deschedule_xenvif(struct xenvif *vif)
842 {
843         struct xen_netbk *netbk = vif->netbk;
844         spin_lock_irq(&netbk->net_schedule_list_lock);
845         remove_from_net_schedule_list(vif);
846         spin_unlock_irq(&netbk->net_schedule_list_lock);
847 }
848
849 void xen_netbk_check_rx_xenvif(struct xenvif *vif)
850 {
851         int more_to_do;
852
853         RING_FINAL_CHECK_FOR_REQUESTS(&vif->tx, more_to_do);
854
855         if (more_to_do)
856                 xen_netbk_schedule_xenvif(vif);
857 }
858
859 static void tx_add_credit(struct xenvif *vif)
860 {
861         unsigned long max_burst, max_credit;
862
863         /*
864          * Allow a burst big enough to transmit a jumbo packet of up to 128kB.
865          * Otherwise the interface can seize up due to insufficient credit.
866          */
867         max_burst = RING_GET_REQUEST(&vif->tx, vif->tx.req_cons)->size;
868         max_burst = min(max_burst, 131072UL);
869         max_burst = max(max_burst, vif->credit_bytes);
870
871         /* Take care that adding a new chunk of credit doesn't wrap to zero. */
872         max_credit = vif->remaining_credit + vif->credit_bytes;
873         if (max_credit < vif->remaining_credit)
874                 max_credit = ULONG_MAX; /* wrapped: clamp to ULONG_MAX */
875
876         vif->remaining_credit = min(max_credit, max_burst);
877 }
878
879 static void tx_credit_callback(unsigned long data)
880 {
881         struct xenvif *vif = (struct xenvif *)data;
882         tx_add_credit(vif);
883         xen_netbk_check_rx_xenvif(vif);
884 }
885
886 static void netbk_tx_err(struct xenvif *vif,
887                          struct xen_netif_tx_request *txp, RING_IDX end)
888 {
889         RING_IDX cons = vif->tx.req_cons;
890
891         do {
892                 make_tx_response(vif, txp, XEN_NETIF_RSP_ERROR);
893                 if (cons == end)
894                         break;
895                 txp = RING_GET_REQUEST(&vif->tx, cons++);
896         } while (1);
897         vif->tx.req_cons = cons;
898         xen_netbk_check_rx_xenvif(vif);
899         xenvif_put(vif);
900 }
901
902 static void netbk_fatal_tx_err(struct xenvif *vif)
903 {
904         netdev_err(vif->dev, "fatal error; disabling device\n");
905         xenvif_carrier_off(vif);
906         xenvif_put(vif);
907 }
908
909 static int netbk_count_requests(struct xenvif *vif,
910                                 struct xen_netif_tx_request *first,
911                                 struct xen_netif_tx_request *txp,
912                                 int work_to_do)
913 {
914         RING_IDX cons = vif->tx.req_cons;
915         int slots = 0;
916         int drop_err = 0;
917         int more_data;
918
919         if (!(first->flags & XEN_NETTXF_more_data))
920                 return 0;
921
922         do {
923                 struct xen_netif_tx_request dropped_tx = { 0 };
924
925                 if (slots >= work_to_do) {
926                         netdev_err(vif->dev,
927                                    "Asked for %d slots but exceeds this limit\n",
928                                    work_to_do);
929                         netbk_fatal_tx_err(vif);
930                         return -ENODATA;
931                 }
932
933                 /* This guest is really using too many slots and
934                  * considered malicious.
935                  */
936                 if (unlikely(slots >= fatal_skb_slots)) {
937                         netdev_err(vif->dev,
938                                    "Malicious frontend using %d slots, threshold %u\n",
939                                    slots, fatal_skb_slots);
940                         netbk_fatal_tx_err(vif);
941                         return -E2BIG;
942                 }
943
944                 /* Xen network protocol had implicit dependency on
945                  * MAX_SKB_FRAGS. XEN_NETBK_LEGACY_SLOTS_MAX is set to
946                  * the historical MAX_SKB_FRAGS value 18 to honor the
947                  * same behavior as before. Any packet using more than
948                  * 18 slots but less than fatal_skb_slots slots is
949                  * dropped
950                  */
951                 if (!drop_err && slots >= XEN_NETBK_LEGACY_SLOTS_MAX) {
952                         if (net_ratelimit())
953                                 netdev_dbg(vif->dev,
954                                            "Too many slots (%d) exceeding limit (%d), dropping packet\n",
955                                            slots, XEN_NETBK_LEGACY_SLOTS_MAX);
956                         drop_err = -E2BIG;
957                 }
958
959                 if (drop_err)
960                         txp = &dropped_tx;
961
962                 memcpy(txp, RING_GET_REQUEST(&vif->tx, cons + slots),
963                        sizeof(*txp));
964
965                 /* If the guest submitted a frame >= 64 KiB then
966                  * first->size overflowed and following slots will
967                  * appear to be larger than the frame.
968                  *
969                  * This cannot be fatal error as there are buggy
970                  * frontends that do this.
971                  *
972                  * Consume all slots and drop the packet.
973                  */
974                 if (!drop_err && txp->size > first->size) {
975                         if (net_ratelimit())
976                                 netdev_dbg(vif->dev,
977                                            "Invalid tx request, slot size %u > remaining size %u\n",
978                                            txp->size, first->size);
979                         drop_err = -EIO;
980                 }
981
982                 first->size -= txp->size;
983                 slots++;
984
985                 if (unlikely((txp->offset + txp->size) > PAGE_SIZE)) {
986                         netdev_err(vif->dev, "Cross page boundary, txp->offset: %x, size: %u\n",
987                                  txp->offset, txp->size);
988                         netbk_fatal_tx_err(vif);
989                         return -EINVAL;
990                 }
991
992                 more_data = txp->flags & XEN_NETTXF_more_data;
993
994                 if (!drop_err)
995                         txp++;
996
997         } while (more_data);
998
999         if (drop_err) {
1000                 netbk_tx_err(vif, first, cons + slots);
1001                 return drop_err;
1002         }
1003
1004         return slots;
1005 }
1006
1007 static struct page *xen_netbk_alloc_page(struct xen_netbk *netbk,
1008                                          u16 pending_idx)
1009 {
1010         struct page *page;
1011         page = alloc_page(GFP_KERNEL|__GFP_COLD);
1012         if (!page)
1013                 return NULL;
1014         set_page_ext(page, netbk, pending_idx);
1015         netbk->mmap_pages[pending_idx] = page;
1016         return page;
1017 }
1018
1019 static struct gnttab_copy *xen_netbk_get_requests(struct xen_netbk *netbk,
1020                                                   struct xenvif *vif,
1021                                                   struct sk_buff *skb,
1022                                                   struct xen_netif_tx_request *txp,
1023                                                   struct gnttab_copy *gop)
1024 {
1025         struct skb_shared_info *shinfo = skb_shinfo(skb);
1026         skb_frag_t *frags = shinfo->frags;
1027         u16 pending_idx = *((u16 *)skb->data);
1028         u16 head_idx = 0;
1029         int slot, start;
1030         struct page *page;
1031         pending_ring_idx_t index, start_idx = 0;
1032         uint16_t dst_offset;
1033         unsigned int nr_slots;
1034         struct pending_tx_info *first = NULL;
1035
1036         /* At this point shinfo->nr_frags is in fact the number of
1037          * slots, which can be as large as XEN_NETBK_LEGACY_SLOTS_MAX.
1038          */
1039         nr_slots = shinfo->nr_frags;
1040
1041         /* Skip first skb fragment if it is on same page as header fragment. */
1042         start = (frag_get_pending_idx(&shinfo->frags[0]) == pending_idx);
1043
1044         /* Coalesce tx requests, at this point the packet passed in
1045          * should be <= 64K. Any packets larger than 64K have been
1046          * handled in netbk_count_requests().
1047          */
1048         for (shinfo->nr_frags = slot = start; slot < nr_slots;
1049              shinfo->nr_frags++) {
1050                 struct pending_tx_info *pending_tx_info =
1051                         netbk->pending_tx_info;
1052
1053                 page = alloc_page(GFP_KERNEL|__GFP_COLD);
1054                 if (!page)
1055                         goto err;
1056
1057                 dst_offset = 0;
1058                 first = NULL;
1059                 while (dst_offset < PAGE_SIZE && slot < nr_slots) {
1060                         gop->flags = GNTCOPY_source_gref;
1061
1062                         gop->source.u.ref = txp->gref;
1063                         gop->source.domid = vif->domid;
1064                         gop->source.offset = txp->offset;
1065
1066                         gop->dest.domid = DOMID_SELF;
1067
1068                         gop->dest.offset = dst_offset;
1069                         gop->dest.u.gmfn = virt_to_mfn(page_address(page));
1070
1071                         if (dst_offset + txp->size > PAGE_SIZE) {
1072                                 /* This page can only merge a portion
1073                                  * of tx request. Do not increment any
1074                                  * pointer / counter here. The txp
1075                                  * will be dealt with in future
1076                                  * rounds, eventually hitting the
1077                                  * `else` branch.
1078                                  */
1079                                 gop->len = PAGE_SIZE - dst_offset;
1080                                 txp->offset += gop->len;
1081                                 txp->size -= gop->len;
1082                                 dst_offset += gop->len; /* quit loop */
1083                         } else {
1084                                 /* This tx request can be merged in the page */
1085                                 gop->len = txp->size;
1086                                 dst_offset += gop->len;
1087
1088                                 index = pending_index(netbk->pending_cons++);
1089
1090                                 pending_idx = netbk->pending_ring[index];
1091
1092                                 memcpy(&pending_tx_info[pending_idx].req, txp,
1093                                        sizeof(*txp));
1094                                 xenvif_get(vif);
1095
1096                                 pending_tx_info[pending_idx].vif = vif;
1097
1098                                 /* Poison these fields, corresponding
1099                                  * fields for head tx req will be set
1100                                  * to correct values after the loop.
1101                                  */
1102                                 netbk->mmap_pages[pending_idx] = (void *)(~0UL);
1103                                 pending_tx_info[pending_idx].head =
1104                                         INVALID_PENDING_RING_IDX;
1105
1106                                 if (!first) {
1107                                         first = &pending_tx_info[pending_idx];
1108                                         start_idx = index;
1109                                         head_idx = pending_idx;
1110                                 }
1111
1112                                 txp++;
1113                                 slot++;
1114                         }
1115
1116                         gop++;
1117                 }
1118
1119                 first->req.offset = 0;
1120                 first->req.size = dst_offset;
1121                 first->head = start_idx;
1122                 set_page_ext(page, netbk, head_idx);
1123                 netbk->mmap_pages[head_idx] = page;
1124                 frag_set_pending_idx(&frags[shinfo->nr_frags], head_idx);
1125         }
1126
1127         BUG_ON(shinfo->nr_frags > MAX_SKB_FRAGS);
1128
1129         return gop;
1130 err:
1131         /* Unwind, freeing all pages and sending error responses. */
1132         while (shinfo->nr_frags-- > start) {
1133                 xen_netbk_idx_release(netbk,
1134                                 frag_get_pending_idx(&frags[shinfo->nr_frags]),
1135                                 XEN_NETIF_RSP_ERROR);
1136         }
1137         /* The head too, if necessary. */
1138         if (start)
1139                 xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_ERROR);
1140
1141         return NULL;
1142 }
1143
1144 static int xen_netbk_tx_check_gop(struct xen_netbk *netbk,
1145                                   struct sk_buff *skb,
1146                                   struct gnttab_copy **gopp)
1147 {
1148         struct gnttab_copy *gop = *gopp;
1149         u16 pending_idx = *((u16 *)skb->data);
1150         struct skb_shared_info *shinfo = skb_shinfo(skb);
1151         struct pending_tx_info *tx_info;
1152         int nr_frags = shinfo->nr_frags;
1153         int i, err, start;
1154         u16 peek; /* peek into next tx request */
1155
1156         /* Check status of header. */
1157         err = gop->status;
1158         if (unlikely(err))
1159                 xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_ERROR);
1160
1161         /* Skip first skb fragment if it is on same page as header fragment. */
1162         start = (frag_get_pending_idx(&shinfo->frags[0]) == pending_idx);
1163
1164         for (i = start; i < nr_frags; i++) {
1165                 int j, newerr;
1166                 pending_ring_idx_t head;
1167
1168                 pending_idx = frag_get_pending_idx(&shinfo->frags[i]);
1169                 tx_info = &netbk->pending_tx_info[pending_idx];
1170                 head = tx_info->head;
1171
1172                 /* Check error status: if okay then remember grant handle. */
1173                 do {
1174                         newerr = (++gop)->status;
1175                         if (newerr)
1176                                 break;
1177                         peek = netbk->pending_ring[pending_index(++head)];
1178                 } while (!pending_tx_is_head(netbk, peek));
1179
1180                 if (likely(!newerr)) {
1181                         /* Had a previous error? Invalidate this fragment. */
1182                         if (unlikely(err))
1183                                 xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);
1184                         continue;
1185                 }
1186
1187                 /* Error on this fragment: respond to client with an error. */
1188                 xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_ERROR);
1189
1190                 /* Not the first error? Preceding frags already invalidated. */
1191                 if (err)
1192                         continue;
1193
1194                 /* First error: invalidate header and preceding fragments. */
1195                 pending_idx = *((u16 *)skb->data);
1196                 xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);
1197                 for (j = start; j < i; j++) {
1198                         pending_idx = frag_get_pending_idx(&shinfo->frags[j]);
1199                         xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);
1200                 }
1201
1202                 /* Remember the error: invalidate all subsequent fragments. */
1203                 err = newerr;
1204         }
1205
1206         *gopp = gop + 1;
1207         return err;
1208 }
1209
1210 static void xen_netbk_fill_frags(struct xen_netbk *netbk, struct sk_buff *skb)
1211 {
1212         struct skb_shared_info *shinfo = skb_shinfo(skb);
1213         int nr_frags = shinfo->nr_frags;
1214         int i;
1215
1216         for (i = 0; i < nr_frags; i++) {
1217                 skb_frag_t *frag = shinfo->frags + i;
1218                 struct xen_netif_tx_request *txp;
1219                 struct page *page;
1220                 u16 pending_idx;
1221
1222                 pending_idx = frag_get_pending_idx(frag);
1223
1224                 txp = &netbk->pending_tx_info[pending_idx].req;
1225                 page = virt_to_page(idx_to_kaddr(netbk, pending_idx));
1226                 __skb_fill_page_desc(skb, i, page, txp->offset, txp->size);
1227                 skb->len += txp->size;
1228                 skb->data_len += txp->size;
1229                 skb->truesize += txp->size;
1230
1231                 /* Take an extra reference to offset xen_netbk_idx_release */
1232                 get_page(netbk->mmap_pages[pending_idx]);
1233                 xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);
1234         }
1235 }
1236
1237 static int xen_netbk_get_extras(struct xenvif *vif,
1238                                 struct xen_netif_extra_info *extras,
1239                                 int work_to_do)
1240 {
1241         struct xen_netif_extra_info extra;
1242         RING_IDX cons = vif->tx.req_cons;
1243
1244         do {
1245                 if (unlikely(work_to_do-- <= 0)) {
1246                         netdev_err(vif->dev, "Missing extra info\n");
1247                         netbk_fatal_tx_err(vif);
1248                         return -EBADR;
1249                 }
1250
1251                 memcpy(&extra, RING_GET_REQUEST(&vif->tx, cons),
1252                        sizeof(extra));
1253                 if (unlikely(!extra.type ||
1254                              extra.type >= XEN_NETIF_EXTRA_TYPE_MAX)) {
1255                         vif->tx.req_cons = ++cons;
1256                         netdev_err(vif->dev,
1257                                    "Invalid extra type: %d\n", extra.type);
1258                         netbk_fatal_tx_err(vif);
1259                         return -EINVAL;
1260                 }
1261
1262                 memcpy(&extras[extra.type - 1], &extra, sizeof(extra));
1263                 vif->tx.req_cons = ++cons;
1264         } while (extra.flags & XEN_NETIF_EXTRA_FLAG_MORE);
1265
1266         return work_to_do;
1267 }
1268
1269 static int netbk_set_skb_gso(struct xenvif *vif,
1270                              struct sk_buff *skb,
1271                              struct xen_netif_extra_info *gso)
1272 {
1273         if (!gso->u.gso.size) {
1274                 netdev_err(vif->dev, "GSO size must not be zero.\n");
1275                 netbk_fatal_tx_err(vif);
1276                 return -EINVAL;
1277         }
1278
1279         /* Currently only TCPv4 S.O. is supported. */
1280         if (gso->u.gso.type != XEN_NETIF_GSO_TYPE_TCPV4) {
1281                 netdev_err(vif->dev, "Bad GSO type %d.\n", gso->u.gso.type);
1282                 netbk_fatal_tx_err(vif);
1283                 return -EINVAL;
1284         }
1285
1286         skb_shinfo(skb)->gso_size = gso->u.gso.size;
1287         skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
1288
1289         /* Header must be checked, and gso_segs computed. */
1290         skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
1291         skb_shinfo(skb)->gso_segs = 0;
1292
1293         return 0;
1294 }
1295
1296 static int checksum_setup(struct xenvif *vif, struct sk_buff *skb)
1297 {
1298         struct iphdr *iph;
1299         unsigned char *th;
1300         int err = -EPROTO;
1301         int recalculate_partial_csum = 0;
1302
1303         /*
1304          * A GSO SKB must be CHECKSUM_PARTIAL. However some buggy
1305          * peers can fail to set NETRXF_csum_blank when sending a GSO
1306          * frame. In this case force the SKB to CHECKSUM_PARTIAL and
1307          * recalculate the partial checksum.
1308          */
1309         if (skb->ip_summed != CHECKSUM_PARTIAL && skb_is_gso(skb)) {
1310                 vif->rx_gso_checksum_fixup++;
1311                 skb->ip_summed = CHECKSUM_PARTIAL;
1312                 recalculate_partial_csum = 1;
1313         }
1314
1315         /* A non-CHECKSUM_PARTIAL SKB does not require setup. */
1316         if (skb->ip_summed != CHECKSUM_PARTIAL)
1317                 return 0;
1318
1319         if (skb->protocol != htons(ETH_P_IP))
1320                 goto out;
1321
1322         iph = (void *)skb->data;
1323         th = skb->data + 4 * iph->ihl;
1324         if (th >= skb_tail_pointer(skb))
1325                 goto out;
1326
1327         skb->csum_start = th - skb->head;
1328         switch (iph->protocol) {
1329         case IPPROTO_TCP:
1330                 skb->csum_offset = offsetof(struct tcphdr, check);
1331
1332                 if (recalculate_partial_csum) {
1333                         struct tcphdr *tcph = (struct tcphdr *)th;
1334                         tcph->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr,
1335                                                          skb->len - iph->ihl*4,
1336                                                          IPPROTO_TCP, 0);
1337                 }
1338                 break;
1339         case IPPROTO_UDP:
1340                 skb->csum_offset = offsetof(struct udphdr, check);
1341
1342                 if (recalculate_partial_csum) {
1343                         struct udphdr *udph = (struct udphdr *)th;
1344                         udph->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr,
1345                                                          skb->len - iph->ihl*4,
1346                                                          IPPROTO_UDP, 0);
1347                 }
1348                 break;
1349         default:
1350                 if (net_ratelimit())
1351                         netdev_err(vif->dev,
1352                                    "Attempting to checksum a non-TCP/UDP packet, dropping a protocol %d packet\n",
1353                                    iph->protocol);
1354                 goto out;
1355         }
1356
1357         if ((th + skb->csum_offset + 2) > skb_tail_pointer(skb))
1358                 goto out;
1359
1360         err = 0;
1361
1362 out:
1363         return err;
1364 }
1365
1366 static bool tx_credit_exceeded(struct xenvif *vif, unsigned size)
1367 {
1368         unsigned long now = jiffies;
1369         unsigned long next_credit =
1370                 vif->credit_timeout.expires +
1371                 msecs_to_jiffies(vif->credit_usec / 1000);
1372
1373         /* Timer could already be pending in rare cases. */
1374         if (timer_pending(&vif->credit_timeout))
1375                 return true;
1376
1377         /* Passed the point where we can replenish credit? */
1378         if (time_after_eq(now, next_credit)) {
1379                 vif->credit_timeout.expires = now;
1380                 tx_add_credit(vif);
1381         }
1382
1383         /* Still too big to send right now? Set a callback. */
1384         if (size > vif->remaining_credit) {
1385                 vif->credit_timeout.data     =
1386                         (unsigned long)vif;
1387                 vif->credit_timeout.function =
1388                         tx_credit_callback;
1389                 mod_timer(&vif->credit_timeout,
1390                           next_credit);
1391
1392                 return true;
1393         }
1394
1395         return false;
1396 }
1397
1398 static unsigned xen_netbk_tx_build_gops(struct xen_netbk *netbk)
1399 {
1400         struct gnttab_copy *gop = netbk->tx_copy_ops, *request_gop;
1401         struct sk_buff *skb;
1402         int ret;
1403
1404         while ((nr_pending_reqs(netbk) + XEN_NETBK_LEGACY_SLOTS_MAX
1405                 < MAX_PENDING_REQS) &&
1406                 !list_empty(&netbk->net_schedule_list)) {
1407                 struct xenvif *vif;
1408                 struct xen_netif_tx_request txreq;
1409                 struct xen_netif_tx_request txfrags[XEN_NETBK_LEGACY_SLOTS_MAX];
1410                 struct page *page;
1411                 struct xen_netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX-1];
1412                 u16 pending_idx;
1413                 RING_IDX idx;
1414                 int work_to_do;
1415                 unsigned int data_len;
1416                 pending_ring_idx_t index;
1417
1418                 /* Get a netif from the list with work to do. */
1419                 vif = poll_net_schedule_list(netbk);
1420                 /* This can sometimes happen because the test of
1421                  * list_empty(net_schedule_list) at the top of the
1422                  * loop is unlocked.  Just go back and have another
1423                  * look.
1424                  */
1425                 if (!vif)
1426                         continue;
1427
1428                 if (vif->tx.sring->req_prod - vif->tx.req_cons >
1429                     XEN_NETIF_TX_RING_SIZE) {
1430                         netdev_err(vif->dev,
1431                                    "Impossible number of requests. "
1432                                    "req_prod %d, req_cons %d, size %ld\n",
1433                                    vif->tx.sring->req_prod, vif->tx.req_cons,
1434                                    XEN_NETIF_TX_RING_SIZE);
1435                         netbk_fatal_tx_err(vif);
1436                         continue;
1437                 }
1438
1439                 RING_FINAL_CHECK_FOR_REQUESTS(&vif->tx, work_to_do);
1440                 if (!work_to_do) {
1441                         xenvif_put(vif);
1442                         continue;
1443                 }
1444
1445                 idx = vif->tx.req_cons;
1446                 rmb(); /* Ensure that we see the request before we copy it. */
1447                 memcpy(&txreq, RING_GET_REQUEST(&vif->tx, idx), sizeof(txreq));
1448
1449                 /* Credit-based scheduling. */
1450                 if (txreq.size > vif->remaining_credit &&
1451                     tx_credit_exceeded(vif, txreq.size)) {
1452                         xenvif_put(vif);
1453                         continue;
1454                 }
1455
1456                 vif->remaining_credit -= txreq.size;
1457
1458                 work_to_do--;
1459                 vif->tx.req_cons = ++idx;
1460
1461                 memset(extras, 0, sizeof(extras));
1462                 if (txreq.flags & XEN_NETTXF_extra_info) {
1463                         work_to_do = xen_netbk_get_extras(vif, extras,
1464                                                           work_to_do);
1465                         idx = vif->tx.req_cons;
1466                         if (unlikely(work_to_do < 0))
1467                                 continue;
1468                 }
1469
1470                 ret = netbk_count_requests(vif, &txreq, txfrags, work_to_do);
1471                 if (unlikely(ret < 0))
1472                         continue;
1473
1474                 idx += ret;
1475
1476                 if (unlikely(txreq.size < ETH_HLEN)) {
1477                         netdev_dbg(vif->dev,
1478                                    "Bad packet size: %d\n", txreq.size);
1479                         netbk_tx_err(vif, &txreq, idx);
1480                         continue;
1481                 }
1482
1483                 /* No crossing a page as the payload mustn't fragment. */
1484                 if (unlikely((txreq.offset + txreq.size) > PAGE_SIZE)) {
1485                         netdev_err(vif->dev,
1486                                    "txreq.offset: %x, size: %u, end: %lu\n",
1487                                    txreq.offset, txreq.size,
1488                                    (txreq.offset&~PAGE_MASK) + txreq.size);
1489                         netbk_fatal_tx_err(vif);
1490                         continue;
1491                 }
1492
1493                 index = pending_index(netbk->pending_cons);
1494                 pending_idx = netbk->pending_ring[index];
1495
1496                 data_len = (txreq.size > PKT_PROT_LEN &&
1497                             ret < XEN_NETBK_LEGACY_SLOTS_MAX) ?
1498                         PKT_PROT_LEN : txreq.size;
1499
1500                 skb = alloc_skb(data_len + NET_SKB_PAD + NET_IP_ALIGN,
1501                                 GFP_ATOMIC | __GFP_NOWARN);
1502                 if (unlikely(skb == NULL)) {
1503                         netdev_dbg(vif->dev,
1504                                    "Can't allocate a skb in start_xmit.\n");
1505                         netbk_tx_err(vif, &txreq, idx);
1506                         break;
1507                 }
1508
1509                 /* Packets passed to netif_rx() must have some headroom. */
1510                 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
1511
1512                 if (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) {
1513                         struct xen_netif_extra_info *gso;
1514                         gso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1];
1515
1516                         if (netbk_set_skb_gso(vif, skb, gso)) {
1517                                 /* Failure in netbk_set_skb_gso is fatal. */
1518                                 kfree_skb(skb);
1519                                 continue;
1520                         }
1521                 }
1522
1523                 /* XXX could copy straight to head */
1524                 page = xen_netbk_alloc_page(netbk, pending_idx);
1525                 if (!page) {
1526                         kfree_skb(skb);
1527                         netbk_tx_err(vif, &txreq, idx);
1528                         continue;
1529                 }
1530
1531                 gop->source.u.ref = txreq.gref;
1532                 gop->source.domid = vif->domid;
1533                 gop->source.offset = txreq.offset;
1534
1535                 gop->dest.u.gmfn = virt_to_mfn(page_address(page));
1536                 gop->dest.domid = DOMID_SELF;
1537                 gop->dest.offset = txreq.offset;
1538
1539                 gop->len = txreq.size;
1540                 gop->flags = GNTCOPY_source_gref;
1541
1542                 gop++;
1543
1544                 memcpy(&netbk->pending_tx_info[pending_idx].req,
1545                        &txreq, sizeof(txreq));
1546                 netbk->pending_tx_info[pending_idx].vif = vif;
1547                 netbk->pending_tx_info[pending_idx].head = index;
1548                 *((u16 *)skb->data) = pending_idx;
1549
1550                 __skb_put(skb, data_len);
1551
1552                 skb_shinfo(skb)->nr_frags = ret;
1553                 if (data_len < txreq.size) {
1554                         skb_shinfo(skb)->nr_frags++;
1555                         frag_set_pending_idx(&skb_shinfo(skb)->frags[0],
1556                                              pending_idx);
1557                 } else {
1558                         frag_set_pending_idx(&skb_shinfo(skb)->frags[0],
1559                                              INVALID_PENDING_IDX);
1560                 }
1561
1562                 __skb_queue_tail(&netbk->tx_queue, skb);
1563
1564                 netbk->pending_cons++;
1565
1566                 request_gop = xen_netbk_get_requests(netbk, vif,
1567                                                      skb, txfrags, gop);
1568                 if (request_gop == NULL) {
1569                         kfree_skb(skb);
1570                         netbk_tx_err(vif, &txreq, idx);
1571                         continue;
1572                 }
1573                 gop = request_gop;
1574
1575                 vif->tx.req_cons = idx;
1576                 xen_netbk_check_rx_xenvif(vif);
1577
1578                 if ((gop-netbk->tx_copy_ops) >= ARRAY_SIZE(netbk->tx_copy_ops))
1579                         break;
1580         }
1581
1582         return gop - netbk->tx_copy_ops;
1583 }
1584
1585 static void xen_netbk_tx_submit(struct xen_netbk *netbk)
1586 {
1587         struct gnttab_copy *gop = netbk->tx_copy_ops;
1588         struct sk_buff *skb;
1589
1590         while ((skb = __skb_dequeue(&netbk->tx_queue)) != NULL) {
1591                 struct xen_netif_tx_request *txp;
1592                 struct xenvif *vif;
1593                 u16 pending_idx;
1594                 unsigned data_len;
1595
1596                 pending_idx = *((u16 *)skb->data);
1597                 vif = netbk->pending_tx_info[pending_idx].vif;
1598                 txp = &netbk->pending_tx_info[pending_idx].req;
1599
1600                 /* Check the remap error code. */
1601                 if (unlikely(xen_netbk_tx_check_gop(netbk, skb, &gop))) {
1602                         netdev_dbg(vif->dev, "netback grant failed.\n");
1603                         skb_shinfo(skb)->nr_frags = 0;
1604                         kfree_skb(skb);
1605                         continue;
1606                 }
1607
1608                 data_len = skb->len;
1609                 memcpy(skb->data,
1610                        (void *)(idx_to_kaddr(netbk, pending_idx)|txp->offset),
1611                        data_len);
1612                 if (data_len < txp->size) {
1613                         /* Append the packet payload as a fragment. */
1614                         txp->offset += data_len;
1615                         txp->size -= data_len;
1616                 } else {
1617                         /* Schedule a response immediately. */
1618                         xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY);
1619                 }
1620
1621                 if (txp->flags & XEN_NETTXF_csum_blank)
1622                         skb->ip_summed = CHECKSUM_PARTIAL;
1623                 else if (txp->flags & XEN_NETTXF_data_validated)
1624                         skb->ip_summed = CHECKSUM_UNNECESSARY;
1625
1626                 xen_netbk_fill_frags(netbk, skb);
1627
1628                 /*
1629                  * If the initial fragment was < PKT_PROT_LEN then
1630                  * pull through some bytes from the other fragments to
1631                  * increase the linear region to PKT_PROT_LEN bytes.
1632                  */
1633                 if (skb_headlen(skb) < PKT_PROT_LEN && skb_is_nonlinear(skb)) {
1634                         int target = min_t(int, skb->len, PKT_PROT_LEN);
1635                         __pskb_pull_tail(skb, target - skb_headlen(skb));
1636                 }
1637
1638                 skb->dev      = vif->dev;
1639                 skb->protocol = eth_type_trans(skb, skb->dev);
1640
1641                 if (checksum_setup(vif, skb)) {
1642                         netdev_dbg(vif->dev,
1643                                    "Can't setup checksum in net_tx_action\n");
1644                         kfree_skb(skb);
1645                         continue;
1646                 }
1647
1648                 vif->dev->stats.rx_bytes += skb->len;
1649                 vif->dev->stats.rx_packets++;
1650
1651                 xenvif_receive_skb(vif, skb);
1652         }
1653 }
1654
1655 /* Called after netfront has transmitted */
1656 static void xen_netbk_tx_action(struct xen_netbk *netbk)
1657 {
1658         unsigned nr_gops;
1659         int ret;
1660
1661         nr_gops = xen_netbk_tx_build_gops(netbk);
1662
1663         if (nr_gops == 0)
1664                 return;
1665         ret = HYPERVISOR_grant_table_op(GNTTABOP_copy,
1666                                         netbk->tx_copy_ops, nr_gops);
1667         BUG_ON(ret);
1668
1669         xen_netbk_tx_submit(netbk);
1670
1671 }
1672
1673 static void xen_netbk_idx_release(struct xen_netbk *netbk, u16 pending_idx,
1674                                   u8 status)
1675 {
1676         struct xenvif *vif;
1677         struct pending_tx_info *pending_tx_info;
1678         pending_ring_idx_t head;
1679         u16 peek; /* peek into next tx request */
1680
1681         BUG_ON(netbk->mmap_pages[pending_idx] == (void *)(~0UL));
1682
1683         /* Already complete? */
1684         if (netbk->mmap_pages[pending_idx] == NULL)
1685                 return;
1686
1687         pending_tx_info = &netbk->pending_tx_info[pending_idx];
1688
1689         vif = pending_tx_info->vif;
1690         head = pending_tx_info->head;
1691
1692         BUG_ON(!pending_tx_is_head(netbk, head));
1693         BUG_ON(netbk->pending_ring[pending_index(head)] != pending_idx);
1694
1695         do {
1696                 pending_ring_idx_t index;
1697                 pending_ring_idx_t idx = pending_index(head);
1698                 u16 info_idx = netbk->pending_ring[idx];
1699
1700                 pending_tx_info = &netbk->pending_tx_info[info_idx];
1701                 make_tx_response(vif, &pending_tx_info->req, status);
1702
1703                 /* Setting any number other than
1704                  * INVALID_PENDING_RING_IDX indicates this slot is
1705                  * starting a new packet / ending a previous packet.
1706                  */
1707                 pending_tx_info->head = 0;
1708
1709                 index = pending_index(netbk->pending_prod++);
1710                 netbk->pending_ring[index] = netbk->pending_ring[info_idx];
1711
1712                 xenvif_put(vif);
1713
1714                 peek = netbk->pending_ring[pending_index(++head)];
1715
1716         } while (!pending_tx_is_head(netbk, peek));
1717
1718         netbk->mmap_pages[pending_idx]->mapping = 0;
1719         put_page(netbk->mmap_pages[pending_idx]);
1720         netbk->mmap_pages[pending_idx] = NULL;
1721 }
1722
1723
1724 static void make_tx_response(struct xenvif *vif,
1725                              struct xen_netif_tx_request *txp,
1726                              s8       st)
1727 {
1728         RING_IDX i = vif->tx.rsp_prod_pvt;
1729         struct xen_netif_tx_response *resp;
1730         int notify;
1731
1732         resp = RING_GET_RESPONSE(&vif->tx, i);
1733         resp->id     = txp->id;
1734         resp->status = st;
1735
1736         if (txp->flags & XEN_NETTXF_extra_info)
1737                 RING_GET_RESPONSE(&vif->tx, ++i)->status = XEN_NETIF_RSP_NULL;
1738
1739         vif->tx.rsp_prod_pvt = ++i;
1740         RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&vif->tx, notify);
1741         if (notify)
1742                 notify_remote_via_irq(vif->irq);
1743 }
1744
1745 static struct xen_netif_rx_response *make_rx_response(struct xenvif *vif,
1746                                              u16      id,
1747                                              s8       st,
1748                                              u16      offset,
1749                                              u16      size,
1750                                              u16      flags)
1751 {
1752         RING_IDX i = vif->rx.rsp_prod_pvt;
1753         struct xen_netif_rx_response *resp;
1754
1755         resp = RING_GET_RESPONSE(&vif->rx, i);
1756         resp->offset     = offset;
1757         resp->flags      = flags;
1758         resp->id         = id;
1759         resp->status     = (s16)size;
1760         if (st < 0)
1761                 resp->status = (s16)st;
1762
1763         vif->rx.rsp_prod_pvt = ++i;
1764
1765         return resp;
1766 }
1767
1768 static inline int rx_work_todo(struct xen_netbk *netbk)
1769 {
1770         return !skb_queue_empty(&netbk->rx_queue);
1771 }
1772
1773 static inline int tx_work_todo(struct xen_netbk *netbk)
1774 {
1775
1776         if ((nr_pending_reqs(netbk) + XEN_NETBK_LEGACY_SLOTS_MAX
1777              < MAX_PENDING_REQS) &&
1778              !list_empty(&netbk->net_schedule_list))
1779                 return 1;
1780
1781         return 0;
1782 }
1783
1784 static int xen_netbk_kthread(void *data)
1785 {
1786         struct xen_netbk *netbk = data;
1787         while (!kthread_should_stop()) {
1788                 wait_event_interruptible(netbk->wq,
1789                                 rx_work_todo(netbk) ||
1790                                 tx_work_todo(netbk) ||
1791                                 kthread_should_stop());
1792                 cond_resched();
1793
1794                 if (kthread_should_stop())
1795                         break;
1796
1797                 if (rx_work_todo(netbk))
1798                         xen_netbk_rx_action(netbk);
1799
1800                 if (tx_work_todo(netbk))
1801                         xen_netbk_tx_action(netbk);
1802         }
1803
1804         return 0;
1805 }
1806
1807 void xen_netbk_unmap_frontend_rings(struct xenvif *vif)
1808 {
1809         if (vif->tx.sring)
1810                 xenbus_unmap_ring_vfree(xenvif_to_xenbus_device(vif),
1811                                         vif->tx.sring);
1812         if (vif->rx.sring)
1813                 xenbus_unmap_ring_vfree(xenvif_to_xenbus_device(vif),
1814                                         vif->rx.sring);
1815 }
1816
1817 int xen_netbk_map_frontend_rings(struct xenvif *vif,
1818                                  grant_ref_t tx_ring_ref,
1819                                  grant_ref_t rx_ring_ref)
1820 {
1821         void *addr;
1822         struct xen_netif_tx_sring *txs;
1823         struct xen_netif_rx_sring *rxs;
1824
1825         int err = -ENOMEM;
1826
1827         err = xenbus_map_ring_valloc(xenvif_to_xenbus_device(vif),
1828                                      tx_ring_ref, &addr);
1829         if (err)
1830                 goto err;
1831
1832         txs = (struct xen_netif_tx_sring *)addr;
1833         BACK_RING_INIT(&vif->tx, txs, PAGE_SIZE);
1834
1835         err = xenbus_map_ring_valloc(xenvif_to_xenbus_device(vif),
1836                                      rx_ring_ref, &addr);
1837         if (err)
1838                 goto err;
1839
1840         rxs = (struct xen_netif_rx_sring *)addr;
1841         BACK_RING_INIT(&vif->rx, rxs, PAGE_SIZE);
1842
1843         vif->rx_req_cons_peek = 0;
1844
1845         return 0;
1846
1847 err:
1848         xen_netbk_unmap_frontend_rings(vif);
1849         return err;
1850 }
1851
1852 static int __init netback_init(void)
1853 {
1854         int i;
1855         int rc = 0;
1856         int group;
1857
1858         if (!xen_pv_domain())
1859                 return -ENODEV;
1860
1861         if (fatal_skb_slots < XEN_NETBK_LEGACY_SLOTS_MAX) {
1862                 printk(KERN_INFO
1863                        "xen-netback: fatal_skb_slots too small (%d), bump it to XEN_NETBK_LEGACY_SLOTS_MAX (%d)\n",
1864                        fatal_skb_slots, XEN_NETBK_LEGACY_SLOTS_MAX);
1865                 fatal_skb_slots = XEN_NETBK_LEGACY_SLOTS_MAX;
1866         }
1867
1868         xen_netbk_group_nr = num_online_cpus();
1869         xen_netbk = vzalloc(sizeof(struct xen_netbk) * xen_netbk_group_nr);
1870         if (!xen_netbk) {
1871                 printk(KERN_ALERT "%s: out of memory\n", __func__);
1872                 return -ENOMEM;
1873         }
1874
1875         for (group = 0; group < xen_netbk_group_nr; group++) {
1876                 struct xen_netbk *netbk = &xen_netbk[group];
1877                 skb_queue_head_init(&netbk->rx_queue);
1878                 skb_queue_head_init(&netbk->tx_queue);
1879
1880                 init_timer(&netbk->net_timer);
1881                 netbk->net_timer.data = (unsigned long)netbk;
1882                 netbk->net_timer.function = xen_netbk_alarm;
1883
1884                 netbk->pending_cons = 0;
1885                 netbk->pending_prod = MAX_PENDING_REQS;
1886                 for (i = 0; i < MAX_PENDING_REQS; i++)
1887                         netbk->pending_ring[i] = i;
1888
1889                 init_waitqueue_head(&netbk->wq);
1890                 netbk->task = kthread_create(xen_netbk_kthread,
1891                                              (void *)netbk,
1892                                              "netback/%u", group);
1893
1894                 if (IS_ERR(netbk->task)) {
1895                         printk(KERN_ALERT "kthread_create() fails at netback\n");
1896                         del_timer(&netbk->net_timer);
1897                         rc = PTR_ERR(netbk->task);
1898                         goto failed_init;
1899                 }
1900
1901                 kthread_bind(netbk->task, group);
1902
1903                 INIT_LIST_HEAD(&netbk->net_schedule_list);
1904
1905                 spin_lock_init(&netbk->net_schedule_list_lock);
1906
1907                 atomic_set(&netbk->netfront_count, 0);
1908
1909                 wake_up_process(netbk->task);
1910         }
1911
1912         rc = xenvif_xenbus_init();
1913         if (rc)
1914                 goto failed_init;
1915
1916         return 0;
1917
1918 failed_init:
1919         while (--group >= 0) {
1920                 struct xen_netbk *netbk = &xen_netbk[group];
1921                 for (i = 0; i < MAX_PENDING_REQS; i++) {
1922                         if (netbk->mmap_pages[i])
1923                                 __free_page(netbk->mmap_pages[i]);
1924                 }
1925                 del_timer(&netbk->net_timer);
1926                 kthread_stop(netbk->task);
1927         }
1928         vfree(xen_netbk);
1929         return rc;
1930
1931 }
1932
1933 module_init(netback_init);
1934
1935 MODULE_LICENSE("Dual BSD/GPL");
1936 MODULE_ALIAS("xen-backend:vif");