Merge branch 'xen-netback-next'
[firefly-linux-kernel-4.4.55.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 #include <linux/highmem.h>
41
42 #include <net/tcp.h>
43
44 #include <xen/xen.h>
45 #include <xen/events.h>
46 #include <xen/interface/memory.h>
47
48 #include <asm/xen/hypercall.h>
49 #include <asm/xen/page.h>
50
51 /* Provide an option to disable split event channels at load time as
52  * event channels are limited resource. Split event channels are
53  * enabled by default.
54  */
55 bool separate_tx_rx_irq = 1;
56 module_param(separate_tx_rx_irq, bool, 0644);
57
58 /* When guest ring is filled up, qdisc queues the packets for us, but we have
59  * to timeout them, otherwise other guests' packets can get stucked there
60  */
61 unsigned int rx_drain_timeout_msecs = 10000;
62 module_param(rx_drain_timeout_msecs, uint, 0444);
63 unsigned int rx_drain_timeout_jiffies;
64
65 /*
66  * This is the maximum slots a skb can have. If a guest sends a skb
67  * which exceeds this limit it is considered malicious.
68  */
69 #define FATAL_SKB_SLOTS_DEFAULT 20
70 static unsigned int fatal_skb_slots = FATAL_SKB_SLOTS_DEFAULT;
71 module_param(fatal_skb_slots, uint, 0444);
72
73 static void xenvif_idx_release(struct xenvif *vif, u16 pending_idx,
74                                u8 status);
75
76 static void make_tx_response(struct xenvif *vif,
77                              struct xen_netif_tx_request *txp,
78                              s8       st);
79
80 static inline int tx_work_todo(struct xenvif *vif);
81 static inline int rx_work_todo(struct xenvif *vif);
82
83 static struct xen_netif_rx_response *make_rx_response(struct xenvif *vif,
84                                              u16      id,
85                                              s8       st,
86                                              u16      offset,
87                                              u16      size,
88                                              u16      flags);
89
90 static inline unsigned long idx_to_pfn(struct xenvif *vif,
91                                        u16 idx)
92 {
93         return page_to_pfn(vif->mmap_pages[idx]);
94 }
95
96 static inline unsigned long idx_to_kaddr(struct xenvif *vif,
97                                          u16 idx)
98 {
99         return (unsigned long)pfn_to_kaddr(idx_to_pfn(vif, idx));
100 }
101
102 /* Find the containing VIF's structure from a pointer in pending_tx_info array
103  */
104 static inline struct xenvif* ubuf_to_vif(struct ubuf_info *ubuf)
105 {
106         u16 pending_idx = ubuf->desc;
107         struct pending_tx_info *temp =
108                 container_of(ubuf, struct pending_tx_info, callback_struct);
109         return container_of(temp - pending_idx,
110                             struct xenvif,
111                             pending_tx_info[0]);
112 }
113
114 /* This is a miniumum size for the linear area to avoid lots of
115  * calls to __pskb_pull_tail() as we set up checksum offsets. The
116  * value 128 was chosen as it covers all IPv4 and most likely
117  * IPv6 headers.
118  */
119 #define PKT_PROT_LEN 128
120
121 static u16 frag_get_pending_idx(skb_frag_t *frag)
122 {
123         return (u16)frag->page_offset;
124 }
125
126 static void frag_set_pending_idx(skb_frag_t *frag, u16 pending_idx)
127 {
128         frag->page_offset = pending_idx;
129 }
130
131 static inline pending_ring_idx_t pending_index(unsigned i)
132 {
133         return i & (MAX_PENDING_REQS-1);
134 }
135
136 static inline pending_ring_idx_t nr_free_slots(struct xen_netif_tx_back_ring *ring)
137 {
138         return ring->nr_ents -  (ring->sring->req_prod - ring->rsp_prod_pvt);
139 }
140
141 bool xenvif_rx_ring_slots_available(struct xenvif *vif, int needed)
142 {
143         RING_IDX prod, cons;
144
145         do {
146                 prod = vif->rx.sring->req_prod;
147                 cons = vif->rx.req_cons;
148
149                 if (prod - cons >= needed)
150                         return true;
151
152                 vif->rx.sring->req_event = prod + 1;
153
154                 /* Make sure event is visible before we check prod
155                  * again.
156                  */
157                 mb();
158         } while (vif->rx.sring->req_prod != prod);
159
160         return false;
161 }
162
163 /*
164  * Returns true if we should start a new receive buffer instead of
165  * adding 'size' bytes to a buffer which currently contains 'offset'
166  * bytes.
167  */
168 static bool start_new_rx_buffer(int offset, unsigned long size, int head)
169 {
170         /* simple case: we have completely filled the current buffer. */
171         if (offset == MAX_BUFFER_OFFSET)
172                 return true;
173
174         /*
175          * complex case: start a fresh buffer if the current frag
176          * would overflow the current buffer but only if:
177          *     (i)   this frag would fit completely in the next buffer
178          * and (ii)  there is already some data in the current buffer
179          * and (iii) this is not the head buffer.
180          *
181          * Where:
182          * - (i) stops us splitting a frag into two copies
183          *   unless the frag is too large for a single buffer.
184          * - (ii) stops us from leaving a buffer pointlessly empty.
185          * - (iii) stops us leaving the first buffer
186          *   empty. Strictly speaking this is already covered
187          *   by (ii) but is explicitly checked because
188          *   netfront relies on the first buffer being
189          *   non-empty and can crash otherwise.
190          *
191          * This means we will effectively linearise small
192          * frags but do not needlessly split large buffers
193          * into multiple copies tend to give large frags their
194          * own buffers as before.
195          */
196         if ((offset + size > MAX_BUFFER_OFFSET) &&
197             (size <= MAX_BUFFER_OFFSET) && offset && !head)
198                 return true;
199
200         return false;
201 }
202
203 struct netrx_pending_operations {
204         unsigned copy_prod, copy_cons;
205         unsigned meta_prod, meta_cons;
206         struct gnttab_copy *copy;
207         struct xenvif_rx_meta *meta;
208         int copy_off;
209         grant_ref_t copy_gref;
210 };
211
212 static struct xenvif_rx_meta *get_next_rx_buffer(struct xenvif *vif,
213                                                  struct netrx_pending_operations *npo)
214 {
215         struct xenvif_rx_meta *meta;
216         struct xen_netif_rx_request *req;
217
218         req = RING_GET_REQUEST(&vif->rx, vif->rx.req_cons++);
219
220         meta = npo->meta + npo->meta_prod++;
221         meta->gso_type = XEN_NETIF_GSO_TYPE_NONE;
222         meta->gso_size = 0;
223         meta->size = 0;
224         meta->id = req->id;
225
226         npo->copy_off = 0;
227         npo->copy_gref = req->gref;
228
229         return meta;
230 }
231
232 /*
233  * Set up the grant operations for this fragment. If it's a flipping
234  * interface, we also set up the unmap request from here.
235  */
236 static void xenvif_gop_frag_copy(struct xenvif *vif, struct sk_buff *skb,
237                                  struct netrx_pending_operations *npo,
238                                  struct page *page, unsigned long size,
239                                  unsigned long offset, int *head,
240                                  struct xenvif *foreign_vif,
241                                  grant_ref_t foreign_gref)
242 {
243         struct gnttab_copy *copy_gop;
244         struct xenvif_rx_meta *meta;
245         unsigned long bytes;
246         int gso_type;
247
248         /* Data must not cross a page boundary. */
249         BUG_ON(size + offset > PAGE_SIZE<<compound_order(page));
250
251         meta = npo->meta + npo->meta_prod - 1;
252
253         /* Skip unused frames from start of page */
254         page += offset >> PAGE_SHIFT;
255         offset &= ~PAGE_MASK;
256
257         while (size > 0) {
258                 BUG_ON(offset >= PAGE_SIZE);
259                 BUG_ON(npo->copy_off > MAX_BUFFER_OFFSET);
260
261                 bytes = PAGE_SIZE - offset;
262
263                 if (bytes > size)
264                         bytes = size;
265
266                 if (start_new_rx_buffer(npo->copy_off, bytes, *head)) {
267                         /*
268                          * Netfront requires there to be some data in the head
269                          * buffer.
270                          */
271                         BUG_ON(*head);
272
273                         meta = get_next_rx_buffer(vif, npo);
274                 }
275
276                 if (npo->copy_off + bytes > MAX_BUFFER_OFFSET)
277                         bytes = MAX_BUFFER_OFFSET - npo->copy_off;
278
279                 copy_gop = npo->copy + npo->copy_prod++;
280                 copy_gop->flags = GNTCOPY_dest_gref;
281                 copy_gop->len = bytes;
282
283                 if (foreign_vif) {
284                         copy_gop->source.domid = foreign_vif->domid;
285                         copy_gop->source.u.ref = foreign_gref;
286                         copy_gop->flags |= GNTCOPY_source_gref;
287                 } else {
288                         copy_gop->source.domid = DOMID_SELF;
289                         copy_gop->source.u.gmfn =
290                                 virt_to_mfn(page_address(page));
291                 }
292                 copy_gop->source.offset = offset;
293
294                 copy_gop->dest.domid = vif->domid;
295                 copy_gop->dest.offset = npo->copy_off;
296                 copy_gop->dest.u.ref = npo->copy_gref;
297
298                 npo->copy_off += bytes;
299                 meta->size += bytes;
300
301                 offset += bytes;
302                 size -= bytes;
303
304                 /* Next frame */
305                 if (offset == PAGE_SIZE && size) {
306                         BUG_ON(!PageCompound(page));
307                         page++;
308                         offset = 0;
309                 }
310
311                 /* Leave a gap for the GSO descriptor. */
312                 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4)
313                         gso_type = XEN_NETIF_GSO_TYPE_TCPV4;
314                 else if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6)
315                         gso_type = XEN_NETIF_GSO_TYPE_TCPV6;
316                 else
317                         gso_type = XEN_NETIF_GSO_TYPE_NONE;
318
319                 if (*head && ((1 << gso_type) & vif->gso_mask))
320                         vif->rx.req_cons++;
321
322                 *head = 0; /* There must be something in this buffer now. */
323
324         }
325 }
326
327 /*
328  * Prepare an SKB to be transmitted to the frontend.
329  *
330  * This function is responsible for allocating grant operations, meta
331  * structures, etc.
332  *
333  * It returns the number of meta structures consumed. The number of
334  * ring slots used is always equal to the number of meta slots used
335  * plus the number of GSO descriptors used. Currently, we use either
336  * zero GSO descriptors (for non-GSO packets) or one descriptor (for
337  * frontend-side LRO).
338  */
339 static int xenvif_gop_skb(struct sk_buff *skb,
340                           struct netrx_pending_operations *npo)
341 {
342         struct xenvif *vif = netdev_priv(skb->dev);
343         int nr_frags = skb_shinfo(skb)->nr_frags;
344         int i;
345         struct xen_netif_rx_request *req;
346         struct xenvif_rx_meta *meta;
347         unsigned char *data;
348         int head = 1;
349         int old_meta_prod;
350         int gso_type;
351         int gso_size;
352         struct ubuf_info *ubuf = skb_shinfo(skb)->destructor_arg;
353         grant_ref_t foreign_grefs[MAX_SKB_FRAGS];
354         struct xenvif *foreign_vif = NULL;
355
356         old_meta_prod = npo->meta_prod;
357
358         if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
359                 gso_type = XEN_NETIF_GSO_TYPE_TCPV4;
360                 gso_size = skb_shinfo(skb)->gso_size;
361         } else if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6) {
362                 gso_type = XEN_NETIF_GSO_TYPE_TCPV6;
363                 gso_size = skb_shinfo(skb)->gso_size;
364         } else {
365                 gso_type = XEN_NETIF_GSO_TYPE_NONE;
366                 gso_size = 0;
367         }
368
369         /* Set up a GSO prefix descriptor, if necessary */
370         if ((1 << gso_type) & vif->gso_prefix_mask) {
371                 req = RING_GET_REQUEST(&vif->rx, vif->rx.req_cons++);
372                 meta = npo->meta + npo->meta_prod++;
373                 meta->gso_type = gso_type;
374                 meta->gso_size = gso_size;
375                 meta->size = 0;
376                 meta->id = req->id;
377         }
378
379         req = RING_GET_REQUEST(&vif->rx, vif->rx.req_cons++);
380         meta = npo->meta + npo->meta_prod++;
381
382         if ((1 << gso_type) & vif->gso_mask) {
383                 meta->gso_type = gso_type;
384                 meta->gso_size = gso_size;
385         } else {
386                 meta->gso_type = XEN_NETIF_GSO_TYPE_NONE;
387                 meta->gso_size = 0;
388         }
389
390         meta->size = 0;
391         meta->id = req->id;
392         npo->copy_off = 0;
393         npo->copy_gref = req->gref;
394
395         if ((skb_shinfo(skb)->tx_flags & SKBTX_DEV_ZEROCOPY) &&
396                  (ubuf->callback == &xenvif_zerocopy_callback)) {
397                 int i = 0;
398                 foreign_vif = ubuf_to_vif(ubuf);
399
400                 do {
401                         u16 pending_idx = ubuf->desc;
402                         foreign_grefs[i++] =
403                                 foreign_vif->pending_tx_info[pending_idx].req.gref;
404                         ubuf = (struct ubuf_info *) ubuf->ctx;
405                 } while (ubuf);
406         }
407
408         data = skb->data;
409         while (data < skb_tail_pointer(skb)) {
410                 unsigned int offset = offset_in_page(data);
411                 unsigned int len = PAGE_SIZE - offset;
412
413                 if (data + len > skb_tail_pointer(skb))
414                         len = skb_tail_pointer(skb) - data;
415
416                 xenvif_gop_frag_copy(vif, skb, npo,
417                                      virt_to_page(data), len, offset, &head,
418                                      NULL,
419                                      0);
420                 data += len;
421         }
422
423         for (i = 0; i < nr_frags; i++) {
424                 xenvif_gop_frag_copy(vif, skb, npo,
425                                      skb_frag_page(&skb_shinfo(skb)->frags[i]),
426                                      skb_frag_size(&skb_shinfo(skb)->frags[i]),
427                                      skb_shinfo(skb)->frags[i].page_offset,
428                                      &head,
429                                      foreign_vif,
430                                      foreign_grefs[i]);
431         }
432
433         return npo->meta_prod - old_meta_prod;
434 }
435
436 /*
437  * This is a twin to xenvif_gop_skb.  Assume that xenvif_gop_skb was
438  * used to set up the operations on the top of
439  * netrx_pending_operations, which have since been done.  Check that
440  * they didn't give any errors and advance over them.
441  */
442 static int xenvif_check_gop(struct xenvif *vif, int nr_meta_slots,
443                             struct netrx_pending_operations *npo)
444 {
445         struct gnttab_copy     *copy_op;
446         int status = XEN_NETIF_RSP_OKAY;
447         int i;
448
449         for (i = 0; i < nr_meta_slots; i++) {
450                 copy_op = npo->copy + npo->copy_cons++;
451                 if (copy_op->status != GNTST_okay) {
452                         netdev_dbg(vif->dev,
453                                    "Bad status %d from copy to DOM%d.\n",
454                                    copy_op->status, vif->domid);
455                         status = XEN_NETIF_RSP_ERROR;
456                 }
457         }
458
459         return status;
460 }
461
462 static void xenvif_add_frag_responses(struct xenvif *vif, int status,
463                                       struct xenvif_rx_meta *meta,
464                                       int nr_meta_slots)
465 {
466         int i;
467         unsigned long offset;
468
469         /* No fragments used */
470         if (nr_meta_slots <= 1)
471                 return;
472
473         nr_meta_slots--;
474
475         for (i = 0; i < nr_meta_slots; i++) {
476                 int flags;
477                 if (i == nr_meta_slots - 1)
478                         flags = 0;
479                 else
480                         flags = XEN_NETRXF_more_data;
481
482                 offset = 0;
483                 make_rx_response(vif, meta[i].id, status, offset,
484                                  meta[i].size, flags);
485         }
486 }
487
488 struct xenvif_rx_cb {
489         int meta_slots_used;
490 };
491
492 #define XENVIF_RX_CB(skb) ((struct xenvif_rx_cb *)(skb)->cb)
493
494 void xenvif_kick_thread(struct xenvif *vif)
495 {
496         wake_up(&vif->wq);
497 }
498
499 static void xenvif_rx_action(struct xenvif *vif)
500 {
501         s8 status;
502         u16 flags;
503         struct xen_netif_rx_response *resp;
504         struct sk_buff_head rxq;
505         struct sk_buff *skb;
506         LIST_HEAD(notify);
507         int ret;
508         unsigned long offset;
509         bool need_to_notify = false;
510
511         struct netrx_pending_operations npo = {
512                 .copy  = vif->grant_copy_op,
513                 .meta  = vif->meta,
514         };
515
516         skb_queue_head_init(&rxq);
517
518         while ((skb = skb_dequeue(&vif->rx_queue)) != NULL) {
519                 RING_IDX max_slots_needed;
520                 int i;
521
522                 /* We need a cheap worse case estimate for the number of
523                  * slots we'll use.
524                  */
525
526                 max_slots_needed = DIV_ROUND_UP(offset_in_page(skb->data) +
527                                                 skb_headlen(skb),
528                                                 PAGE_SIZE);
529                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
530                         unsigned int size;
531                         size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
532                         max_slots_needed += DIV_ROUND_UP(size, PAGE_SIZE);
533                 }
534                 if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4 ||
535                     skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6)
536                         max_slots_needed++;
537
538                 /* If the skb may not fit then bail out now */
539                 if (!xenvif_rx_ring_slots_available(vif, max_slots_needed)) {
540                         skb_queue_head(&vif->rx_queue, skb);
541                         need_to_notify = true;
542                         vif->rx_last_skb_slots = max_slots_needed;
543                         break;
544                 } else
545                         vif->rx_last_skb_slots = 0;
546
547                 XENVIF_RX_CB(skb)->meta_slots_used = xenvif_gop_skb(skb, &npo);
548                 BUG_ON(XENVIF_RX_CB(skb)->meta_slots_used > max_slots_needed);
549
550                 __skb_queue_tail(&rxq, skb);
551         }
552
553         BUG_ON(npo.meta_prod > ARRAY_SIZE(vif->meta));
554
555         if (!npo.copy_prod)
556                 goto done;
557
558         BUG_ON(npo.copy_prod > MAX_GRANT_COPY_OPS);
559         gnttab_batch_copy(vif->grant_copy_op, npo.copy_prod);
560
561         while ((skb = __skb_dequeue(&rxq)) != NULL) {
562
563                 if ((1 << vif->meta[npo.meta_cons].gso_type) &
564                     vif->gso_prefix_mask) {
565                         resp = RING_GET_RESPONSE(&vif->rx,
566                                                  vif->rx.rsp_prod_pvt++);
567
568                         resp->flags = XEN_NETRXF_gso_prefix | XEN_NETRXF_more_data;
569
570                         resp->offset = vif->meta[npo.meta_cons].gso_size;
571                         resp->id = vif->meta[npo.meta_cons].id;
572                         resp->status = XENVIF_RX_CB(skb)->meta_slots_used;
573
574                         npo.meta_cons++;
575                         XENVIF_RX_CB(skb)->meta_slots_used--;
576                 }
577
578
579                 vif->dev->stats.tx_bytes += skb->len;
580                 vif->dev->stats.tx_packets++;
581
582                 status = xenvif_check_gop(vif,
583                                           XENVIF_RX_CB(skb)->meta_slots_used,
584                                           &npo);
585
586                 if (XENVIF_RX_CB(skb)->meta_slots_used == 1)
587                         flags = 0;
588                 else
589                         flags = XEN_NETRXF_more_data;
590
591                 if (skb->ip_summed == CHECKSUM_PARTIAL) /* local packet? */
592                         flags |= XEN_NETRXF_csum_blank | XEN_NETRXF_data_validated;
593                 else if (skb->ip_summed == CHECKSUM_UNNECESSARY)
594                         /* remote but checksummed. */
595                         flags |= XEN_NETRXF_data_validated;
596
597                 offset = 0;
598                 resp = make_rx_response(vif, vif->meta[npo.meta_cons].id,
599                                         status, offset,
600                                         vif->meta[npo.meta_cons].size,
601                                         flags);
602
603                 if ((1 << vif->meta[npo.meta_cons].gso_type) &
604                     vif->gso_mask) {
605                         struct xen_netif_extra_info *gso =
606                                 (struct xen_netif_extra_info *)
607                                 RING_GET_RESPONSE(&vif->rx,
608                                                   vif->rx.rsp_prod_pvt++);
609
610                         resp->flags |= XEN_NETRXF_extra_info;
611
612                         gso->u.gso.type = vif->meta[npo.meta_cons].gso_type;
613                         gso->u.gso.size = vif->meta[npo.meta_cons].gso_size;
614                         gso->u.gso.pad = 0;
615                         gso->u.gso.features = 0;
616
617                         gso->type = XEN_NETIF_EXTRA_TYPE_GSO;
618                         gso->flags = 0;
619                 }
620
621                 xenvif_add_frag_responses(vif, status,
622                                           vif->meta + npo.meta_cons + 1,
623                                           XENVIF_RX_CB(skb)->meta_slots_used);
624
625                 RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&vif->rx, ret);
626
627                 need_to_notify |= !!ret;
628
629                 npo.meta_cons += XENVIF_RX_CB(skb)->meta_slots_used;
630                 dev_kfree_skb(skb);
631         }
632
633 done:
634         if (need_to_notify)
635                 notify_remote_via_irq(vif->rx_irq);
636 }
637
638 void xenvif_check_rx_xenvif(struct xenvif *vif)
639 {
640         int more_to_do;
641
642         RING_FINAL_CHECK_FOR_REQUESTS(&vif->tx, more_to_do);
643
644         if (more_to_do)
645                 napi_schedule(&vif->napi);
646 }
647
648 static void tx_add_credit(struct xenvif *vif)
649 {
650         unsigned long max_burst, max_credit;
651
652         /*
653          * Allow a burst big enough to transmit a jumbo packet of up to 128kB.
654          * Otherwise the interface can seize up due to insufficient credit.
655          */
656         max_burst = RING_GET_REQUEST(&vif->tx, vif->tx.req_cons)->size;
657         max_burst = min(max_burst, 131072UL);
658         max_burst = max(max_burst, vif->credit_bytes);
659
660         /* Take care that adding a new chunk of credit doesn't wrap to zero. */
661         max_credit = vif->remaining_credit + vif->credit_bytes;
662         if (max_credit < vif->remaining_credit)
663                 max_credit = ULONG_MAX; /* wrapped: clamp to ULONG_MAX */
664
665         vif->remaining_credit = min(max_credit, max_burst);
666 }
667
668 static void tx_credit_callback(unsigned long data)
669 {
670         struct xenvif *vif = (struct xenvif *)data;
671         tx_add_credit(vif);
672         xenvif_check_rx_xenvif(vif);
673 }
674
675 static void xenvif_tx_err(struct xenvif *vif,
676                           struct xen_netif_tx_request *txp, RING_IDX end)
677 {
678         RING_IDX cons = vif->tx.req_cons;
679         unsigned long flags;
680
681         do {
682                 spin_lock_irqsave(&vif->response_lock, flags);
683                 make_tx_response(vif, txp, XEN_NETIF_RSP_ERROR);
684                 spin_unlock_irqrestore(&vif->response_lock, flags);
685                 if (cons == end)
686                         break;
687                 txp = RING_GET_REQUEST(&vif->tx, cons++);
688         } while (1);
689         vif->tx.req_cons = cons;
690 }
691
692 static void xenvif_fatal_tx_err(struct xenvif *vif)
693 {
694         netdev_err(vif->dev, "fatal error; disabling device\n");
695         xenvif_carrier_off(vif);
696 }
697
698 static int xenvif_count_requests(struct xenvif *vif,
699                                  struct xen_netif_tx_request *first,
700                                  struct xen_netif_tx_request *txp,
701                                  int work_to_do)
702 {
703         RING_IDX cons = vif->tx.req_cons;
704         int slots = 0;
705         int drop_err = 0;
706         int more_data;
707
708         if (!(first->flags & XEN_NETTXF_more_data))
709                 return 0;
710
711         do {
712                 struct xen_netif_tx_request dropped_tx = { 0 };
713
714                 if (slots >= work_to_do) {
715                         netdev_err(vif->dev,
716                                    "Asked for %d slots but exceeds this limit\n",
717                                    work_to_do);
718                         xenvif_fatal_tx_err(vif);
719                         return -ENODATA;
720                 }
721
722                 /* This guest is really using too many slots and
723                  * considered malicious.
724                  */
725                 if (unlikely(slots >= fatal_skb_slots)) {
726                         netdev_err(vif->dev,
727                                    "Malicious frontend using %d slots, threshold %u\n",
728                                    slots, fatal_skb_slots);
729                         xenvif_fatal_tx_err(vif);
730                         return -E2BIG;
731                 }
732
733                 /* Xen network protocol had implicit dependency on
734                  * MAX_SKB_FRAGS. XEN_NETBK_LEGACY_SLOTS_MAX is set to
735                  * the historical MAX_SKB_FRAGS value 18 to honor the
736                  * same behavior as before. Any packet using more than
737                  * 18 slots but less than fatal_skb_slots slots is
738                  * dropped
739                  */
740                 if (!drop_err && slots >= XEN_NETBK_LEGACY_SLOTS_MAX) {
741                         if (net_ratelimit())
742                                 netdev_dbg(vif->dev,
743                                            "Too many slots (%d) exceeding limit (%d), dropping packet\n",
744                                            slots, XEN_NETBK_LEGACY_SLOTS_MAX);
745                         drop_err = -E2BIG;
746                 }
747
748                 if (drop_err)
749                         txp = &dropped_tx;
750
751                 memcpy(txp, RING_GET_REQUEST(&vif->tx, cons + slots),
752                        sizeof(*txp));
753
754                 /* If the guest submitted a frame >= 64 KiB then
755                  * first->size overflowed and following slots will
756                  * appear to be larger than the frame.
757                  *
758                  * This cannot be fatal error as there are buggy
759                  * frontends that do this.
760                  *
761                  * Consume all slots and drop the packet.
762                  */
763                 if (!drop_err && txp->size > first->size) {
764                         if (net_ratelimit())
765                                 netdev_dbg(vif->dev,
766                                            "Invalid tx request, slot size %u > remaining size %u\n",
767                                            txp->size, first->size);
768                         drop_err = -EIO;
769                 }
770
771                 first->size -= txp->size;
772                 slots++;
773
774                 if (unlikely((txp->offset + txp->size) > PAGE_SIZE)) {
775                         netdev_err(vif->dev, "Cross page boundary, txp->offset: %x, size: %u\n",
776                                  txp->offset, txp->size);
777                         xenvif_fatal_tx_err(vif);
778                         return -EINVAL;
779                 }
780
781                 more_data = txp->flags & XEN_NETTXF_more_data;
782
783                 if (!drop_err)
784                         txp++;
785
786         } while (more_data);
787
788         if (drop_err) {
789                 xenvif_tx_err(vif, first, cons + slots);
790                 return drop_err;
791         }
792
793         return slots;
794 }
795
796
797 struct xenvif_tx_cb {
798         u16 pending_idx;
799 };
800
801 #define XENVIF_TX_CB(skb) ((struct xenvif_tx_cb *)(skb)->cb)
802
803 static inline void xenvif_tx_create_gop(struct xenvif *vif,
804                                         u16 pending_idx,
805                                         struct xen_netif_tx_request *txp,
806                                         struct gnttab_map_grant_ref *gop)
807 {
808         vif->pages_to_map[gop-vif->tx_map_ops] = vif->mmap_pages[pending_idx];
809         gnttab_set_map_op(gop, idx_to_kaddr(vif, pending_idx),
810                           GNTMAP_host_map | GNTMAP_readonly,
811                           txp->gref, vif->domid);
812
813         memcpy(&vif->pending_tx_info[pending_idx].req, txp,
814                sizeof(*txp));
815 }
816
817 static inline struct sk_buff *xenvif_alloc_skb(unsigned int size)
818 {
819         struct sk_buff *skb =
820                 alloc_skb(size + NET_SKB_PAD + NET_IP_ALIGN,
821                           GFP_ATOMIC | __GFP_NOWARN);
822         if (unlikely(skb == NULL))
823                 return NULL;
824
825         /* Packets passed to netif_rx() must have some headroom. */
826         skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
827
828         /* Initialize it here to avoid later surprises */
829         skb_shinfo(skb)->destructor_arg = NULL;
830
831         return skb;
832 }
833
834 static struct gnttab_map_grant_ref *xenvif_get_requests(struct xenvif *vif,
835                                                         struct sk_buff *skb,
836                                                         struct xen_netif_tx_request *txp,
837                                                         struct gnttab_map_grant_ref *gop)
838 {
839         struct skb_shared_info *shinfo = skb_shinfo(skb);
840         skb_frag_t *frags = shinfo->frags;
841         u16 pending_idx = XENVIF_TX_CB(skb)->pending_idx;
842         int start;
843         pending_ring_idx_t index;
844         unsigned int nr_slots, frag_overflow = 0;
845
846         /* At this point shinfo->nr_frags is in fact the number of
847          * slots, which can be as large as XEN_NETBK_LEGACY_SLOTS_MAX.
848          */
849         if (shinfo->nr_frags > MAX_SKB_FRAGS) {
850                 frag_overflow = shinfo->nr_frags - MAX_SKB_FRAGS;
851                 BUG_ON(frag_overflow > MAX_SKB_FRAGS);
852                 shinfo->nr_frags = MAX_SKB_FRAGS;
853         }
854         nr_slots = shinfo->nr_frags;
855
856         /* Skip first skb fragment if it is on same page as header fragment. */
857         start = (frag_get_pending_idx(&shinfo->frags[0]) == pending_idx);
858
859         for (shinfo->nr_frags = start; shinfo->nr_frags < nr_slots;
860              shinfo->nr_frags++, txp++, gop++) {
861                 index = pending_index(vif->pending_cons++);
862                 pending_idx = vif->pending_ring[index];
863                 xenvif_tx_create_gop(vif, pending_idx, txp, gop);
864                 frag_set_pending_idx(&frags[shinfo->nr_frags], pending_idx);
865         }
866
867         if (frag_overflow) {
868                 struct sk_buff *nskb = xenvif_alloc_skb(0);
869                 if (unlikely(nskb == NULL)) {
870                         if (net_ratelimit())
871                                 netdev_err(vif->dev,
872                                            "Can't allocate the frag_list skb.\n");
873                         return NULL;
874                 }
875
876                 shinfo = skb_shinfo(nskb);
877                 frags = shinfo->frags;
878
879                 for (shinfo->nr_frags = 0; shinfo->nr_frags < frag_overflow;
880                      shinfo->nr_frags++, txp++, gop++) {
881                         index = pending_index(vif->pending_cons++);
882                         pending_idx = vif->pending_ring[index];
883                         xenvif_tx_create_gop(vif, pending_idx, txp, gop);
884                         frag_set_pending_idx(&frags[shinfo->nr_frags],
885                                              pending_idx);
886                 }
887
888                 skb_shinfo(skb)->frag_list = nskb;
889         }
890
891         return gop;
892 }
893
894 static inline void xenvif_grant_handle_set(struct xenvif *vif,
895                                            u16 pending_idx,
896                                            grant_handle_t handle)
897 {
898         if (unlikely(vif->grant_tx_handle[pending_idx] !=
899                      NETBACK_INVALID_HANDLE)) {
900                 netdev_err(vif->dev,
901                            "Trying to overwrite active handle! pending_idx: %x\n",
902                            pending_idx);
903                 BUG();
904         }
905         vif->grant_tx_handle[pending_idx] = handle;
906 }
907
908 static inline void xenvif_grant_handle_reset(struct xenvif *vif,
909                                              u16 pending_idx)
910 {
911         if (unlikely(vif->grant_tx_handle[pending_idx] ==
912                      NETBACK_INVALID_HANDLE)) {
913                 netdev_err(vif->dev,
914                            "Trying to unmap invalid handle! pending_idx: %x\n",
915                            pending_idx);
916                 BUG();
917         }
918         vif->grant_tx_handle[pending_idx] = NETBACK_INVALID_HANDLE;
919 }
920
921 static int xenvif_tx_check_gop(struct xenvif *vif,
922                                struct sk_buff *skb,
923                                struct gnttab_map_grant_ref **gopp)
924 {
925         struct gnttab_map_grant_ref *gop = *gopp;
926         u16 pending_idx = XENVIF_TX_CB(skb)->pending_idx;
927         struct skb_shared_info *shinfo = skb_shinfo(skb);
928         struct pending_tx_info *tx_info;
929         int nr_frags = shinfo->nr_frags;
930         int i, err, start;
931         struct sk_buff *first_skb = NULL;
932
933         /* Check status of header. */
934         err = gop->status;
935         if (unlikely(err))
936                 xenvif_idx_release(vif, pending_idx, XEN_NETIF_RSP_ERROR);
937         else
938                 xenvif_grant_handle_set(vif, pending_idx , gop->handle);
939
940         /* Skip first skb fragment if it is on same page as header fragment. */
941         start = (frag_get_pending_idx(&shinfo->frags[0]) == pending_idx);
942
943 check_frags:
944         for (i = start; i < nr_frags; i++) {
945                 int j, newerr;
946
947                 pending_idx = frag_get_pending_idx(&shinfo->frags[i]);
948                 tx_info = &vif->pending_tx_info[pending_idx];
949
950                 /* Check error status: if okay then remember grant handle. */
951                 newerr = (++gop)->status;
952
953                 if (likely(!newerr)) {
954                         xenvif_grant_handle_set(vif, pending_idx , gop->handle);
955                         /* Had a previous error? Invalidate this fragment. */
956                         if (unlikely(err))
957                                 xenvif_idx_unmap(vif, pending_idx);
958                         continue;
959                 }
960
961                 /* Error on this fragment: respond to client with an error. */
962                 xenvif_idx_release(vif, pending_idx, XEN_NETIF_RSP_ERROR);
963
964                 /* Not the first error? Preceding frags already invalidated. */
965                 if (err)
966                         continue;
967                 /* First error: invalidate header and preceding fragments. */
968                 if (!first_skb)
969                         pending_idx = XENVIF_TX_CB(skb)->pending_idx;
970                 else
971                         pending_idx = XENVIF_TX_CB(skb)->pending_idx;
972                 xenvif_idx_unmap(vif, pending_idx);
973                 for (j = start; j < i; j++) {
974                         pending_idx = frag_get_pending_idx(&shinfo->frags[j]);
975                         xenvif_idx_unmap(vif, pending_idx);
976                 }
977
978                 /* Remember the error: invalidate all subsequent fragments. */
979                 err = newerr;
980         }
981
982         if (skb_has_frag_list(skb)) {
983                 first_skb = skb;
984                 skb = shinfo->frag_list;
985                 shinfo = skb_shinfo(skb);
986                 nr_frags = shinfo->nr_frags;
987                 start = 0;
988
989                 goto check_frags;
990         }
991
992         /* There was a mapping error in the frag_list skb. We have to unmap
993          * the first skb's frags
994          */
995         if (first_skb && err) {
996                 int j;
997                 shinfo = skb_shinfo(first_skb);
998                 pending_idx = XENVIF_TX_CB(skb)->pending_idx;
999                 start = (frag_get_pending_idx(&shinfo->frags[0]) == pending_idx);
1000                 for (j = start; j < shinfo->nr_frags; j++) {
1001                         pending_idx = frag_get_pending_idx(&shinfo->frags[j]);
1002                         xenvif_idx_unmap(vif, pending_idx);
1003                 }
1004         }
1005
1006         *gopp = gop + 1;
1007         return err;
1008 }
1009
1010 static void xenvif_fill_frags(struct xenvif *vif, struct sk_buff *skb)
1011 {
1012         struct skb_shared_info *shinfo = skb_shinfo(skb);
1013         int nr_frags = shinfo->nr_frags;
1014         int i;
1015         u16 prev_pending_idx = INVALID_PENDING_IDX;
1016
1017         if (skb_shinfo(skb)->destructor_arg)
1018                 prev_pending_idx = XENVIF_TX_CB(skb)->pending_idx;
1019
1020         for (i = 0; i < nr_frags; i++) {
1021                 skb_frag_t *frag = shinfo->frags + i;
1022                 struct xen_netif_tx_request *txp;
1023                 struct page *page;
1024                 u16 pending_idx;
1025
1026                 pending_idx = frag_get_pending_idx(frag);
1027
1028                 /* If this is not the first frag, chain it to the previous*/
1029                 if (unlikely(prev_pending_idx == INVALID_PENDING_IDX))
1030                         skb_shinfo(skb)->destructor_arg =
1031                                 &vif->pending_tx_info[pending_idx].callback_struct;
1032                 else if (likely(pending_idx != prev_pending_idx))
1033                         vif->pending_tx_info[prev_pending_idx].callback_struct.ctx =
1034                                 &(vif->pending_tx_info[pending_idx].callback_struct);
1035
1036                 vif->pending_tx_info[pending_idx].callback_struct.ctx = NULL;
1037                 prev_pending_idx = pending_idx;
1038
1039                 txp = &vif->pending_tx_info[pending_idx].req;
1040                 page = virt_to_page(idx_to_kaddr(vif, pending_idx));
1041                 __skb_fill_page_desc(skb, i, page, txp->offset, txp->size);
1042                 skb->len += txp->size;
1043                 skb->data_len += txp->size;
1044                 skb->truesize += txp->size;
1045
1046                 /* Take an extra reference to offset network stack's put_page */
1047                 get_page(vif->mmap_pages[pending_idx]);
1048         }
1049         /* FIXME: __skb_fill_page_desc set this to true because page->pfmemalloc
1050          * overlaps with "index", and "mapping" is not set. I think mapping
1051          * should be set. If delivered to local stack, it would drop this
1052          * skb in sk_filter unless the socket has the right to use it.
1053          */
1054         skb->pfmemalloc = false;
1055 }
1056
1057 static int xenvif_get_extras(struct xenvif *vif,
1058                                 struct xen_netif_extra_info *extras,
1059                                 int work_to_do)
1060 {
1061         struct xen_netif_extra_info extra;
1062         RING_IDX cons = vif->tx.req_cons;
1063
1064         do {
1065                 if (unlikely(work_to_do-- <= 0)) {
1066                         netdev_err(vif->dev, "Missing extra info\n");
1067                         xenvif_fatal_tx_err(vif);
1068                         return -EBADR;
1069                 }
1070
1071                 memcpy(&extra, RING_GET_REQUEST(&vif->tx, cons),
1072                        sizeof(extra));
1073                 if (unlikely(!extra.type ||
1074                              extra.type >= XEN_NETIF_EXTRA_TYPE_MAX)) {
1075                         vif->tx.req_cons = ++cons;
1076                         netdev_err(vif->dev,
1077                                    "Invalid extra type: %d\n", extra.type);
1078                         xenvif_fatal_tx_err(vif);
1079                         return -EINVAL;
1080                 }
1081
1082                 memcpy(&extras[extra.type - 1], &extra, sizeof(extra));
1083                 vif->tx.req_cons = ++cons;
1084         } while (extra.flags & XEN_NETIF_EXTRA_FLAG_MORE);
1085
1086         return work_to_do;
1087 }
1088
1089 static int xenvif_set_skb_gso(struct xenvif *vif,
1090                               struct sk_buff *skb,
1091                               struct xen_netif_extra_info *gso)
1092 {
1093         if (!gso->u.gso.size) {
1094                 netdev_err(vif->dev, "GSO size must not be zero.\n");
1095                 xenvif_fatal_tx_err(vif);
1096                 return -EINVAL;
1097         }
1098
1099         switch (gso->u.gso.type) {
1100         case XEN_NETIF_GSO_TYPE_TCPV4:
1101                 skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4;
1102                 break;
1103         case XEN_NETIF_GSO_TYPE_TCPV6:
1104                 skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6;
1105                 break;
1106         default:
1107                 netdev_err(vif->dev, "Bad GSO type %d.\n", gso->u.gso.type);
1108                 xenvif_fatal_tx_err(vif);
1109                 return -EINVAL;
1110         }
1111
1112         skb_shinfo(skb)->gso_size = gso->u.gso.size;
1113         /* gso_segs will be calculated later */
1114
1115         return 0;
1116 }
1117
1118 static int checksum_setup(struct xenvif *vif, struct sk_buff *skb)
1119 {
1120         bool recalculate_partial_csum = false;
1121
1122         /* A GSO SKB must be CHECKSUM_PARTIAL. However some buggy
1123          * peers can fail to set NETRXF_csum_blank when sending a GSO
1124          * frame. In this case force the SKB to CHECKSUM_PARTIAL and
1125          * recalculate the partial checksum.
1126          */
1127         if (skb->ip_summed != CHECKSUM_PARTIAL && skb_is_gso(skb)) {
1128                 vif->rx_gso_checksum_fixup++;
1129                 skb->ip_summed = CHECKSUM_PARTIAL;
1130                 recalculate_partial_csum = true;
1131         }
1132
1133         /* A non-CHECKSUM_PARTIAL SKB does not require setup. */
1134         if (skb->ip_summed != CHECKSUM_PARTIAL)
1135                 return 0;
1136
1137         return skb_checksum_setup(skb, recalculate_partial_csum);
1138 }
1139
1140 static bool tx_credit_exceeded(struct xenvif *vif, unsigned size)
1141 {
1142         u64 now = get_jiffies_64();
1143         u64 next_credit = vif->credit_window_start +
1144                 msecs_to_jiffies(vif->credit_usec / 1000);
1145
1146         /* Timer could already be pending in rare cases. */
1147         if (timer_pending(&vif->credit_timeout))
1148                 return true;
1149
1150         /* Passed the point where we can replenish credit? */
1151         if (time_after_eq64(now, next_credit)) {
1152                 vif->credit_window_start = now;
1153                 tx_add_credit(vif);
1154         }
1155
1156         /* Still too big to send right now? Set a callback. */
1157         if (size > vif->remaining_credit) {
1158                 vif->credit_timeout.data     =
1159                         (unsigned long)vif;
1160                 vif->credit_timeout.function =
1161                         tx_credit_callback;
1162                 mod_timer(&vif->credit_timeout,
1163                           next_credit);
1164                 vif->credit_window_start = next_credit;
1165
1166                 return true;
1167         }
1168
1169         return false;
1170 }
1171
1172 static unsigned xenvif_tx_build_gops(struct xenvif *vif, int budget)
1173 {
1174         struct gnttab_map_grant_ref *gop = vif->tx_map_ops, *request_gop;
1175         struct sk_buff *skb;
1176         int ret;
1177
1178         while (xenvif_tx_pending_slots_available(vif) &&
1179                (skb_queue_len(&vif->tx_queue) < budget)) {
1180                 struct xen_netif_tx_request txreq;
1181                 struct xen_netif_tx_request txfrags[XEN_NETBK_LEGACY_SLOTS_MAX];
1182                 struct xen_netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX-1];
1183                 u16 pending_idx;
1184                 RING_IDX idx;
1185                 int work_to_do;
1186                 unsigned int data_len;
1187                 pending_ring_idx_t index;
1188
1189                 if (vif->tx.sring->req_prod - vif->tx.req_cons >
1190                     XEN_NETIF_TX_RING_SIZE) {
1191                         netdev_err(vif->dev,
1192                                    "Impossible number of requests. "
1193                                    "req_prod %d, req_cons %d, size %ld\n",
1194                                    vif->tx.sring->req_prod, vif->tx.req_cons,
1195                                    XEN_NETIF_TX_RING_SIZE);
1196                         xenvif_fatal_tx_err(vif);
1197                         continue;
1198                 }
1199
1200                 work_to_do = RING_HAS_UNCONSUMED_REQUESTS(&vif->tx);
1201                 if (!work_to_do)
1202                         break;
1203
1204                 idx = vif->tx.req_cons;
1205                 rmb(); /* Ensure that we see the request before we copy it. */
1206                 memcpy(&txreq, RING_GET_REQUEST(&vif->tx, idx), sizeof(txreq));
1207
1208                 /* Credit-based scheduling. */
1209                 if (txreq.size > vif->remaining_credit &&
1210                     tx_credit_exceeded(vif, txreq.size))
1211                         break;
1212
1213                 vif->remaining_credit -= txreq.size;
1214
1215                 work_to_do--;
1216                 vif->tx.req_cons = ++idx;
1217
1218                 memset(extras, 0, sizeof(extras));
1219                 if (txreq.flags & XEN_NETTXF_extra_info) {
1220                         work_to_do = xenvif_get_extras(vif, extras,
1221                                                        work_to_do);
1222                         idx = vif->tx.req_cons;
1223                         if (unlikely(work_to_do < 0))
1224                                 break;
1225                 }
1226
1227                 ret = xenvif_count_requests(vif, &txreq, txfrags, work_to_do);
1228                 if (unlikely(ret < 0))
1229                         break;
1230
1231                 idx += ret;
1232
1233                 if (unlikely(txreq.size < ETH_HLEN)) {
1234                         netdev_dbg(vif->dev,
1235                                    "Bad packet size: %d\n", txreq.size);
1236                         xenvif_tx_err(vif, &txreq, idx);
1237                         break;
1238                 }
1239
1240                 /* No crossing a page as the payload mustn't fragment. */
1241                 if (unlikely((txreq.offset + txreq.size) > PAGE_SIZE)) {
1242                         netdev_err(vif->dev,
1243                                    "txreq.offset: %x, size: %u, end: %lu\n",
1244                                    txreq.offset, txreq.size,
1245                                    (txreq.offset&~PAGE_MASK) + txreq.size);
1246                         xenvif_fatal_tx_err(vif);
1247                         break;
1248                 }
1249
1250                 index = pending_index(vif->pending_cons);
1251                 pending_idx = vif->pending_ring[index];
1252
1253                 data_len = (txreq.size > PKT_PROT_LEN &&
1254                             ret < XEN_NETBK_LEGACY_SLOTS_MAX) ?
1255                         PKT_PROT_LEN : txreq.size;
1256
1257                 skb = xenvif_alloc_skb(data_len);
1258                 if (unlikely(skb == NULL)) {
1259                         netdev_dbg(vif->dev,
1260                                    "Can't allocate a skb in start_xmit.\n");
1261                         xenvif_tx_err(vif, &txreq, idx);
1262                         break;
1263                 }
1264
1265                 if (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) {
1266                         struct xen_netif_extra_info *gso;
1267                         gso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1];
1268
1269                         if (xenvif_set_skb_gso(vif, skb, gso)) {
1270                                 /* Failure in xenvif_set_skb_gso is fatal. */
1271                                 kfree_skb(skb);
1272                                 break;
1273                         }
1274                 }
1275
1276                 xenvif_tx_create_gop(vif, pending_idx, &txreq, gop);
1277
1278                 gop++;
1279
1280                 XENVIF_TX_CB(skb)->pending_idx = pending_idx;
1281
1282                 __skb_put(skb, data_len);
1283
1284                 skb_shinfo(skb)->nr_frags = ret;
1285                 if (data_len < txreq.size) {
1286                         skb_shinfo(skb)->nr_frags++;
1287                         frag_set_pending_idx(&skb_shinfo(skb)->frags[0],
1288                                              pending_idx);
1289                 } else {
1290                         frag_set_pending_idx(&skb_shinfo(skb)->frags[0],
1291                                              INVALID_PENDING_IDX);
1292                 }
1293
1294                 vif->pending_cons++;
1295
1296                 request_gop = xenvif_get_requests(vif, skb, txfrags, gop);
1297                 if (request_gop == NULL) {
1298                         kfree_skb(skb);
1299                         xenvif_tx_err(vif, &txreq, idx);
1300                         break;
1301                 }
1302                 gop = request_gop;
1303
1304                 __skb_queue_tail(&vif->tx_queue, skb);
1305
1306                 vif->tx.req_cons = idx;
1307
1308                 if ((gop-vif->tx_map_ops) >= ARRAY_SIZE(vif->tx_map_ops))
1309                         break;
1310         }
1311
1312         return gop - vif->tx_map_ops;
1313 }
1314
1315 /* Consolidate skb with a frag_list into a brand new one with local pages on
1316  * frags. Returns 0 or -ENOMEM if can't allocate new pages.
1317  */
1318 static int xenvif_handle_frag_list(struct xenvif *vif, struct sk_buff *skb)
1319 {
1320         unsigned int offset = skb_headlen(skb);
1321         skb_frag_t frags[MAX_SKB_FRAGS];
1322         int i;
1323         struct ubuf_info *uarg;
1324         struct sk_buff *nskb = skb_shinfo(skb)->frag_list;
1325
1326         vif->tx_zerocopy_sent += 2;
1327         vif->tx_frag_overflow++;
1328
1329         xenvif_fill_frags(vif, nskb);
1330         /* Subtract frags size, we will correct it later */
1331         skb->truesize -= skb->data_len;
1332         skb->len += nskb->len;
1333         skb->data_len += nskb->len;
1334
1335         /* create a brand new frags array and coalesce there */
1336         for (i = 0; offset < skb->len; i++) {
1337                 struct page *page;
1338                 unsigned int len;
1339
1340                 BUG_ON(i >= MAX_SKB_FRAGS);
1341                 page = alloc_page(GFP_ATOMIC|__GFP_COLD);
1342                 if (!page) {
1343                         int j;
1344                         skb->truesize += skb->data_len;
1345                         for (j = 0; j < i; j++)
1346                                 put_page(frags[j].page.p);
1347                         return -ENOMEM;
1348                 }
1349
1350                 if (offset + PAGE_SIZE < skb->len)
1351                         len = PAGE_SIZE;
1352                 else
1353                         len = skb->len - offset;
1354                 if (skb_copy_bits(skb, offset, page_address(page), len))
1355                         BUG();
1356
1357                 offset += len;
1358                 frags[i].page.p = page;
1359                 frags[i].page_offset = 0;
1360                 skb_frag_size_set(&frags[i], len);
1361         }
1362         /* swap out with old one */
1363         memcpy(skb_shinfo(skb)->frags,
1364                frags,
1365                i * sizeof(skb_frag_t));
1366         skb_shinfo(skb)->nr_frags = i;
1367         skb->truesize += i * PAGE_SIZE;
1368
1369         /* remove traces of mapped pages and frag_list */
1370         skb_frag_list_init(skb);
1371         uarg = skb_shinfo(skb)->destructor_arg;
1372         uarg->callback(uarg, true);
1373         skb_shinfo(skb)->destructor_arg = NULL;
1374
1375         skb_shinfo(nskb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1376         kfree_skb(nskb);
1377
1378         return 0;
1379 }
1380
1381 static int xenvif_tx_submit(struct xenvif *vif)
1382 {
1383         struct gnttab_map_grant_ref *gop = vif->tx_map_ops;
1384         struct sk_buff *skb;
1385         int work_done = 0;
1386
1387         while ((skb = __skb_dequeue(&vif->tx_queue)) != NULL) {
1388                 struct xen_netif_tx_request *txp;
1389                 u16 pending_idx;
1390                 unsigned data_len;
1391
1392                 pending_idx = XENVIF_TX_CB(skb)->pending_idx;
1393                 txp = &vif->pending_tx_info[pending_idx].req;
1394
1395                 /* Check the remap error code. */
1396                 if (unlikely(xenvif_tx_check_gop(vif, skb, &gop))) {
1397                         netdev_dbg(vif->dev, "netback grant failed.\n");
1398                         skb_shinfo(skb)->nr_frags = 0;
1399                         kfree_skb(skb);
1400                         continue;
1401                 }
1402
1403                 data_len = skb->len;
1404                 memcpy(skb->data,
1405                        (void *)(idx_to_kaddr(vif, pending_idx)|txp->offset),
1406                        data_len);
1407                 vif->pending_tx_info[pending_idx].callback_struct.ctx = NULL;
1408                 if (data_len < txp->size) {
1409                         /* Append the packet payload as a fragment. */
1410                         txp->offset += data_len;
1411                         txp->size -= data_len;
1412                         skb_shinfo(skb)->destructor_arg =
1413                                 &vif->pending_tx_info[pending_idx].callback_struct;
1414                 } else {
1415                         /* Schedule a response immediately. */
1416                         xenvif_idx_unmap(vif, pending_idx);
1417                 }
1418
1419                 if (txp->flags & XEN_NETTXF_csum_blank)
1420                         skb->ip_summed = CHECKSUM_PARTIAL;
1421                 else if (txp->flags & XEN_NETTXF_data_validated)
1422                         skb->ip_summed = CHECKSUM_UNNECESSARY;
1423
1424                 xenvif_fill_frags(vif, skb);
1425
1426                 if (unlikely(skb_has_frag_list(skb))) {
1427                         if (xenvif_handle_frag_list(vif, skb)) {
1428                                 if (net_ratelimit())
1429                                         netdev_err(vif->dev,
1430                                                    "Not enough memory to consolidate frag_list!\n");
1431                                 skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1432                                 kfree_skb(skb);
1433                                 continue;
1434                         }
1435                 }
1436
1437                 if (skb_is_nonlinear(skb) && skb_headlen(skb) < PKT_PROT_LEN) {
1438                         int target = min_t(int, skb->len, PKT_PROT_LEN);
1439                         __pskb_pull_tail(skb, target - skb_headlen(skb));
1440                 }
1441
1442                 skb->dev      = vif->dev;
1443                 skb->protocol = eth_type_trans(skb, skb->dev);
1444                 skb_reset_network_header(skb);
1445
1446                 if (checksum_setup(vif, skb)) {
1447                         netdev_dbg(vif->dev,
1448                                    "Can't setup checksum in net_tx_action\n");
1449                         /* We have to set this flag to trigger the callback */
1450                         if (skb_shinfo(skb)->destructor_arg)
1451                                 skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1452                         kfree_skb(skb);
1453                         continue;
1454                 }
1455
1456                 skb_probe_transport_header(skb, 0);
1457
1458                 /* If the packet is GSO then we will have just set up the
1459                  * transport header offset in checksum_setup so it's now
1460                  * straightforward to calculate gso_segs.
1461                  */
1462                 if (skb_is_gso(skb)) {
1463                         int mss = skb_shinfo(skb)->gso_size;
1464                         int hdrlen = skb_transport_header(skb) -
1465                                 skb_mac_header(skb) +
1466                                 tcp_hdrlen(skb);
1467
1468                         skb_shinfo(skb)->gso_segs =
1469                                 DIV_ROUND_UP(skb->len - hdrlen, mss);
1470                 }
1471
1472                 vif->dev->stats.rx_bytes += skb->len;
1473                 vif->dev->stats.rx_packets++;
1474
1475                 work_done++;
1476
1477                 /* Set this flag right before netif_receive_skb, otherwise
1478                  * someone might think this packet already left netback, and
1479                  * do a skb_copy_ubufs while we are still in control of the
1480                  * skb. E.g. the __pskb_pull_tail earlier can do such thing.
1481                  */
1482                 if (skb_shinfo(skb)->destructor_arg) {
1483                         skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
1484                         vif->tx_zerocopy_sent++;
1485                 }
1486
1487                 netif_receive_skb(skb);
1488         }
1489
1490         return work_done;
1491 }
1492
1493 void xenvif_zerocopy_callback(struct ubuf_info *ubuf, bool zerocopy_success)
1494 {
1495         unsigned long flags;
1496         pending_ring_idx_t index;
1497         struct xenvif *vif = ubuf_to_vif(ubuf);
1498
1499         /* This is the only place where we grab this lock, to protect callbacks
1500          * from each other.
1501          */
1502         spin_lock_irqsave(&vif->callback_lock, flags);
1503         do {
1504                 u16 pending_idx = ubuf->desc;
1505                 ubuf = (struct ubuf_info *) ubuf->ctx;
1506                 BUG_ON(vif->dealloc_prod - vif->dealloc_cons >=
1507                         MAX_PENDING_REQS);
1508                 index = pending_index(vif->dealloc_prod);
1509                 vif->dealloc_ring[index] = pending_idx;
1510                 /* Sync with xenvif_tx_dealloc_action:
1511                  * insert idx then incr producer.
1512                  */
1513                 smp_wmb();
1514                 vif->dealloc_prod++;
1515         } while (ubuf);
1516         wake_up(&vif->dealloc_wq);
1517         spin_unlock_irqrestore(&vif->callback_lock, flags);
1518
1519         if (RING_HAS_UNCONSUMED_REQUESTS(&vif->tx) &&
1520             xenvif_tx_pending_slots_available(vif)) {
1521                 local_bh_disable();
1522                 napi_schedule(&vif->napi);
1523                 local_bh_enable();
1524         }
1525
1526         if (likely(zerocopy_success))
1527                 vif->tx_zerocopy_success++;
1528         else
1529                 vif->tx_zerocopy_fail++;
1530 }
1531
1532 static inline void xenvif_tx_dealloc_action(struct xenvif *vif)
1533 {
1534         struct gnttab_unmap_grant_ref *gop;
1535         pending_ring_idx_t dc, dp;
1536         u16 pending_idx, pending_idx_release[MAX_PENDING_REQS];
1537         unsigned int i = 0;
1538
1539         dc = vif->dealloc_cons;
1540         gop = vif->tx_unmap_ops;
1541
1542         /* Free up any grants we have finished using */
1543         do {
1544                 dp = vif->dealloc_prod;
1545
1546                 /* Ensure we see all indices enqueued by all
1547                  * xenvif_zerocopy_callback().
1548                  */
1549                 smp_rmb();
1550
1551                 while (dc != dp) {
1552                         BUG_ON(gop - vif->tx_unmap_ops > MAX_PENDING_REQS);
1553                         pending_idx =
1554                                 vif->dealloc_ring[pending_index(dc++)];
1555
1556                         pending_idx_release[gop-vif->tx_unmap_ops] =
1557                                 pending_idx;
1558                         vif->pages_to_unmap[gop-vif->tx_unmap_ops] =
1559                                 vif->mmap_pages[pending_idx];
1560                         gnttab_set_unmap_op(gop,
1561                                             idx_to_kaddr(vif, pending_idx),
1562                                             GNTMAP_host_map,
1563                                             vif->grant_tx_handle[pending_idx]);
1564                         /* Btw. already unmapped? */
1565                         xenvif_grant_handle_reset(vif, pending_idx);
1566                         ++gop;
1567                 }
1568
1569         } while (dp != vif->dealloc_prod);
1570
1571         vif->dealloc_cons = dc;
1572
1573         if (gop - vif->tx_unmap_ops > 0) {
1574                 int ret;
1575                 ret = gnttab_unmap_refs(vif->tx_unmap_ops,
1576                                         NULL,
1577                                         vif->pages_to_unmap,
1578                                         gop - vif->tx_unmap_ops);
1579                 if (ret) {
1580                         netdev_err(vif->dev, "Unmap fail: nr_ops %x ret %d\n",
1581                                    gop - vif->tx_unmap_ops, ret);
1582                         for (i = 0; i < gop - vif->tx_unmap_ops; ++i) {
1583                                 if (gop[i].status != GNTST_okay)
1584                                         netdev_err(vif->dev,
1585                                                    " host_addr: %llx handle: %x status: %d\n",
1586                                                    gop[i].host_addr,
1587                                                    gop[i].handle,
1588                                                    gop[i].status);
1589                         }
1590                         BUG();
1591                 }
1592         }
1593
1594         for (i = 0; i < gop - vif->tx_unmap_ops; ++i)
1595                 xenvif_idx_release(vif, pending_idx_release[i],
1596                                    XEN_NETIF_RSP_OKAY);
1597 }
1598
1599
1600 /* Called after netfront has transmitted */
1601 int xenvif_tx_action(struct xenvif *vif, int budget)
1602 {
1603         unsigned nr_gops;
1604         int work_done, ret;
1605
1606         if (unlikely(!tx_work_todo(vif)))
1607                 return 0;
1608
1609         nr_gops = xenvif_tx_build_gops(vif, budget);
1610
1611         if (nr_gops == 0)
1612                 return 0;
1613
1614         ret = gnttab_map_refs(vif->tx_map_ops,
1615                               NULL,
1616                               vif->pages_to_map,
1617                               nr_gops);
1618         BUG_ON(ret);
1619
1620         work_done = xenvif_tx_submit(vif);
1621
1622         return work_done;
1623 }
1624
1625 static void xenvif_idx_release(struct xenvif *vif, u16 pending_idx,
1626                                u8 status)
1627 {
1628         struct pending_tx_info *pending_tx_info;
1629         pending_ring_idx_t index;
1630         unsigned long flags;
1631
1632         pending_tx_info = &vif->pending_tx_info[pending_idx];
1633         spin_lock_irqsave(&vif->response_lock, flags);
1634         make_tx_response(vif, &pending_tx_info->req, status);
1635         index = pending_index(vif->pending_prod);
1636         vif->pending_ring[index] = pending_idx;
1637         /* TX shouldn't use the index before we give it back here */
1638         mb();
1639         vif->pending_prod++;
1640         spin_unlock_irqrestore(&vif->response_lock, flags);
1641 }
1642
1643
1644 static void make_tx_response(struct xenvif *vif,
1645                              struct xen_netif_tx_request *txp,
1646                              s8       st)
1647 {
1648         RING_IDX i = vif->tx.rsp_prod_pvt;
1649         struct xen_netif_tx_response *resp;
1650         int notify;
1651
1652         resp = RING_GET_RESPONSE(&vif->tx, i);
1653         resp->id     = txp->id;
1654         resp->status = st;
1655
1656         if (txp->flags & XEN_NETTXF_extra_info)
1657                 RING_GET_RESPONSE(&vif->tx, ++i)->status = XEN_NETIF_RSP_NULL;
1658
1659         vif->tx.rsp_prod_pvt = ++i;
1660         RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&vif->tx, notify);
1661         if (notify)
1662                 notify_remote_via_irq(vif->tx_irq);
1663 }
1664
1665 static struct xen_netif_rx_response *make_rx_response(struct xenvif *vif,
1666                                              u16      id,
1667                                              s8       st,
1668                                              u16      offset,
1669                                              u16      size,
1670                                              u16      flags)
1671 {
1672         RING_IDX i = vif->rx.rsp_prod_pvt;
1673         struct xen_netif_rx_response *resp;
1674
1675         resp = RING_GET_RESPONSE(&vif->rx, i);
1676         resp->offset     = offset;
1677         resp->flags      = flags;
1678         resp->id         = id;
1679         resp->status     = (s16)size;
1680         if (st < 0)
1681                 resp->status = (s16)st;
1682
1683         vif->rx.rsp_prod_pvt = ++i;
1684
1685         return resp;
1686 }
1687
1688 void xenvif_idx_unmap(struct xenvif *vif, u16 pending_idx)
1689 {
1690         int ret;
1691         struct gnttab_unmap_grant_ref tx_unmap_op;
1692
1693         gnttab_set_unmap_op(&tx_unmap_op,
1694                             idx_to_kaddr(vif, pending_idx),
1695                             GNTMAP_host_map,
1696                             vif->grant_tx_handle[pending_idx]);
1697         /* Btw. already unmapped? */
1698         xenvif_grant_handle_reset(vif, pending_idx);
1699
1700         ret = gnttab_unmap_refs(&tx_unmap_op, NULL,
1701                                 &vif->mmap_pages[pending_idx], 1);
1702         BUG_ON(ret);
1703
1704         xenvif_idx_release(vif, pending_idx, XEN_NETIF_RSP_OKAY);
1705 }
1706
1707 static inline int rx_work_todo(struct xenvif *vif)
1708 {
1709         return (!skb_queue_empty(&vif->rx_queue) &&
1710                xenvif_rx_ring_slots_available(vif, vif->rx_last_skb_slots)) ||
1711                vif->rx_queue_purge;
1712 }
1713
1714 static inline int tx_work_todo(struct xenvif *vif)
1715 {
1716
1717         if (likely(RING_HAS_UNCONSUMED_REQUESTS(&vif->tx)) &&
1718             xenvif_tx_pending_slots_available(vif))
1719                 return 1;
1720
1721         return 0;
1722 }
1723
1724 static void xenvif_dealloc_delay(unsigned long data)
1725 {
1726         struct xenvif *vif = (struct xenvif *)data;
1727
1728         vif->dealloc_delay_timed_out = true;
1729         wake_up(&vif->dealloc_wq);
1730 }
1731
1732 static inline bool tx_dealloc_work_todo(struct xenvif *vif)
1733 {
1734         if (vif->dealloc_cons != vif->dealloc_prod) {
1735                 if ((nr_free_slots(&vif->tx) > 2 * XEN_NETBK_LEGACY_SLOTS_MAX) &&
1736                     (vif->dealloc_prod - vif->dealloc_cons < MAX_PENDING_REQS / 4) &&
1737                     !vif->dealloc_delay_timed_out) {
1738                         if (!timer_pending(&vif->dealloc_delay)) {
1739                                 vif->dealloc_delay.function =
1740                                         xenvif_dealloc_delay;
1741                                 vif->dealloc_delay.data = (unsigned long)vif;
1742                                 mod_timer(&vif->dealloc_delay,
1743                                           jiffies + msecs_to_jiffies(1));
1744
1745                         }
1746                         return false;
1747                 }
1748                 del_timer_sync(&vif->dealloc_delay);
1749                 vif->dealloc_delay_timed_out = false;
1750                 return true;
1751         }
1752
1753         return false;
1754 }
1755
1756 void xenvif_unmap_frontend_rings(struct xenvif *vif)
1757 {
1758         if (vif->tx.sring)
1759                 xenbus_unmap_ring_vfree(xenvif_to_xenbus_device(vif),
1760                                         vif->tx.sring);
1761         if (vif->rx.sring)
1762                 xenbus_unmap_ring_vfree(xenvif_to_xenbus_device(vif),
1763                                         vif->rx.sring);
1764 }
1765
1766 int xenvif_map_frontend_rings(struct xenvif *vif,
1767                               grant_ref_t tx_ring_ref,
1768                               grant_ref_t rx_ring_ref)
1769 {
1770         void *addr;
1771         struct xen_netif_tx_sring *txs;
1772         struct xen_netif_rx_sring *rxs;
1773
1774         int err = -ENOMEM;
1775
1776         err = xenbus_map_ring_valloc(xenvif_to_xenbus_device(vif),
1777                                      tx_ring_ref, &addr);
1778         if (err)
1779                 goto err;
1780
1781         txs = (struct xen_netif_tx_sring *)addr;
1782         BACK_RING_INIT(&vif->tx, txs, PAGE_SIZE);
1783
1784         err = xenbus_map_ring_valloc(xenvif_to_xenbus_device(vif),
1785                                      rx_ring_ref, &addr);
1786         if (err)
1787                 goto err;
1788
1789         rxs = (struct xen_netif_rx_sring *)addr;
1790         BACK_RING_INIT(&vif->rx, rxs, PAGE_SIZE);
1791
1792         return 0;
1793
1794 err:
1795         xenvif_unmap_frontend_rings(vif);
1796         return err;
1797 }
1798
1799 void xenvif_stop_queue(struct xenvif *vif)
1800 {
1801         if (!vif->can_queue)
1802                 return;
1803
1804         netif_stop_queue(vif->dev);
1805 }
1806
1807 static void xenvif_start_queue(struct xenvif *vif)
1808 {
1809         if (xenvif_schedulable(vif))
1810                 netif_wake_queue(vif->dev);
1811 }
1812
1813 int xenvif_kthread_guest_rx(void *data)
1814 {
1815         struct xenvif *vif = data;
1816         struct sk_buff *skb;
1817
1818         while (!kthread_should_stop()) {
1819                 wait_event_interruptible(vif->wq,
1820                                          rx_work_todo(vif) ||
1821                                          kthread_should_stop());
1822                 if (kthread_should_stop())
1823                         break;
1824
1825                 if (vif->rx_queue_purge) {
1826                         skb_queue_purge(&vif->rx_queue);
1827                         vif->rx_queue_purge = false;
1828                 }
1829
1830                 if (!skb_queue_empty(&vif->rx_queue))
1831                         xenvif_rx_action(vif);
1832
1833                 if (skb_queue_empty(&vif->rx_queue) &&
1834                     netif_queue_stopped(vif->dev)) {
1835                         del_timer_sync(&vif->wake_queue);
1836                         xenvif_start_queue(vif);
1837                 }
1838
1839                 cond_resched();
1840         }
1841
1842         /* Bin any remaining skbs */
1843         while ((skb = skb_dequeue(&vif->rx_queue)) != NULL)
1844                 dev_kfree_skb(skb);
1845
1846         return 0;
1847 }
1848
1849 int xenvif_dealloc_kthread(void *data)
1850 {
1851         struct xenvif *vif = data;
1852
1853         while (!kthread_should_stop()) {
1854                 wait_event_interruptible(vif->dealloc_wq,
1855                                          tx_dealloc_work_todo(vif) ||
1856                                          kthread_should_stop());
1857                 if (kthread_should_stop())
1858                         break;
1859
1860                 xenvif_tx_dealloc_action(vif);
1861                 cond_resched();
1862         }
1863
1864         /* Unmap anything remaining*/
1865         if (tx_dealloc_work_todo(vif))
1866                 xenvif_tx_dealloc_action(vif);
1867
1868         return 0;
1869 }
1870
1871 static int __init netback_init(void)
1872 {
1873         int rc = 0;
1874
1875         if (!xen_domain())
1876                 return -ENODEV;
1877
1878         if (fatal_skb_slots < XEN_NETBK_LEGACY_SLOTS_MAX) {
1879                 pr_info("fatal_skb_slots too small (%d), bump it to XEN_NETBK_LEGACY_SLOTS_MAX (%d)\n",
1880                         fatal_skb_slots, XEN_NETBK_LEGACY_SLOTS_MAX);
1881                 fatal_skb_slots = XEN_NETBK_LEGACY_SLOTS_MAX;
1882         }
1883
1884         rc = xenvif_xenbus_init();
1885         if (rc)
1886                 goto failed_init;
1887
1888         rx_drain_timeout_jiffies = msecs_to_jiffies(rx_drain_timeout_msecs);
1889
1890         return 0;
1891
1892 failed_init:
1893         return rc;
1894 }
1895
1896 module_init(netback_init);
1897
1898 static void __exit netback_fini(void)
1899 {
1900         xenvif_xenbus_fini();
1901 }
1902 module_exit(netback_fini);
1903
1904 MODULE_LICENSE("Dual BSD/GPL");
1905 MODULE_ALIAS("xen-backend:vif");