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