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