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