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