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