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