GNU Linux-libre 5.15.54-gnu
[releases.git] / drivers / net / veth.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  drivers/net/veth.c
4  *
5  *  Copyright (C) 2007 OpenVZ http://openvz.org, SWsoft Inc
6  *
7  * Author: Pavel Emelianov <xemul@openvz.org>
8  * Ethtool interface from: Eric W. Biederman <ebiederm@xmission.com>
9  *
10  */
11
12 #include <linux/netdevice.h>
13 #include <linux/slab.h>
14 #include <linux/ethtool.h>
15 #include <linux/etherdevice.h>
16 #include <linux/u64_stats_sync.h>
17
18 #include <net/rtnetlink.h>
19 #include <net/dst.h>
20 #include <net/xfrm.h>
21 #include <net/xdp.h>
22 #include <linux/veth.h>
23 #include <linux/module.h>
24 #include <linux/bpf.h>
25 #include <linux/filter.h>
26 #include <linux/ptr_ring.h>
27 #include <linux/bpf_trace.h>
28 #include <linux/net_tstamp.h>
29
30 #define DRV_NAME        "veth"
31 #define DRV_VERSION     "1.0"
32
33 #define VETH_XDP_FLAG           BIT(0)
34 #define VETH_RING_SIZE          256
35 #define VETH_XDP_HEADROOM       (XDP_PACKET_HEADROOM + NET_IP_ALIGN)
36
37 #define VETH_XDP_TX_BULK_SIZE   16
38 #define VETH_XDP_BATCH          16
39
40 struct veth_stats {
41         u64     rx_drops;
42         /* xdp */
43         u64     xdp_packets;
44         u64     xdp_bytes;
45         u64     xdp_redirect;
46         u64     xdp_drops;
47         u64     xdp_tx;
48         u64     xdp_tx_err;
49         u64     peer_tq_xdp_xmit;
50         u64     peer_tq_xdp_xmit_err;
51 };
52
53 struct veth_rq_stats {
54         struct veth_stats       vs;
55         struct u64_stats_sync   syncp;
56 };
57
58 struct veth_rq {
59         struct napi_struct      xdp_napi;
60         struct napi_struct __rcu *napi; /* points to xdp_napi when the latter is initialized */
61         struct net_device       *dev;
62         struct bpf_prog __rcu   *xdp_prog;
63         struct xdp_mem_info     xdp_mem;
64         struct veth_rq_stats    stats;
65         bool                    rx_notify_masked;
66         struct ptr_ring         xdp_ring;
67         struct xdp_rxq_info     xdp_rxq;
68 };
69
70 struct veth_priv {
71         struct net_device __rcu *peer;
72         atomic64_t              dropped;
73         struct bpf_prog         *_xdp_prog;
74         struct veth_rq          *rq;
75         unsigned int            requested_headroom;
76 };
77
78 struct veth_xdp_tx_bq {
79         struct xdp_frame *q[VETH_XDP_TX_BULK_SIZE];
80         unsigned int count;
81 };
82
83 /*
84  * ethtool interface
85  */
86
87 struct veth_q_stat_desc {
88         char    desc[ETH_GSTRING_LEN];
89         size_t  offset;
90 };
91
92 #define VETH_RQ_STAT(m) offsetof(struct veth_stats, m)
93
94 static const struct veth_q_stat_desc veth_rq_stats_desc[] = {
95         { "xdp_packets",        VETH_RQ_STAT(xdp_packets) },
96         { "xdp_bytes",          VETH_RQ_STAT(xdp_bytes) },
97         { "drops",              VETH_RQ_STAT(rx_drops) },
98         { "xdp_redirect",       VETH_RQ_STAT(xdp_redirect) },
99         { "xdp_drops",          VETH_RQ_STAT(xdp_drops) },
100         { "xdp_tx",             VETH_RQ_STAT(xdp_tx) },
101         { "xdp_tx_errors",      VETH_RQ_STAT(xdp_tx_err) },
102 };
103
104 #define VETH_RQ_STATS_LEN       ARRAY_SIZE(veth_rq_stats_desc)
105
106 static const struct veth_q_stat_desc veth_tq_stats_desc[] = {
107         { "xdp_xmit",           VETH_RQ_STAT(peer_tq_xdp_xmit) },
108         { "xdp_xmit_errors",    VETH_RQ_STAT(peer_tq_xdp_xmit_err) },
109 };
110
111 #define VETH_TQ_STATS_LEN       ARRAY_SIZE(veth_tq_stats_desc)
112
113 static struct {
114         const char string[ETH_GSTRING_LEN];
115 } ethtool_stats_keys[] = {
116         { "peer_ifindex" },
117 };
118
119 static int veth_get_link_ksettings(struct net_device *dev,
120                                    struct ethtool_link_ksettings *cmd)
121 {
122         cmd->base.speed         = SPEED_10000;
123         cmd->base.duplex        = DUPLEX_FULL;
124         cmd->base.port          = PORT_TP;
125         cmd->base.autoneg       = AUTONEG_DISABLE;
126         return 0;
127 }
128
129 static void veth_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
130 {
131         strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
132         strlcpy(info->version, DRV_VERSION, sizeof(info->version));
133 }
134
135 static void veth_get_strings(struct net_device *dev, u32 stringset, u8 *buf)
136 {
137         char *p = (char *)buf;
138         int i, j;
139
140         switch(stringset) {
141         case ETH_SS_STATS:
142                 memcpy(p, &ethtool_stats_keys, sizeof(ethtool_stats_keys));
143                 p += sizeof(ethtool_stats_keys);
144                 for (i = 0; i < dev->real_num_rx_queues; i++) {
145                         for (j = 0; j < VETH_RQ_STATS_LEN; j++) {
146                                 snprintf(p, ETH_GSTRING_LEN,
147                                          "rx_queue_%u_%.18s",
148                                          i, veth_rq_stats_desc[j].desc);
149                                 p += ETH_GSTRING_LEN;
150                         }
151                 }
152                 for (i = 0; i < dev->real_num_tx_queues; i++) {
153                         for (j = 0; j < VETH_TQ_STATS_LEN; j++) {
154                                 snprintf(p, ETH_GSTRING_LEN,
155                                          "tx_queue_%u_%.18s",
156                                          i, veth_tq_stats_desc[j].desc);
157                                 p += ETH_GSTRING_LEN;
158                         }
159                 }
160                 break;
161         }
162 }
163
164 static int veth_get_sset_count(struct net_device *dev, int sset)
165 {
166         switch (sset) {
167         case ETH_SS_STATS:
168                 return ARRAY_SIZE(ethtool_stats_keys) +
169                        VETH_RQ_STATS_LEN * dev->real_num_rx_queues +
170                        VETH_TQ_STATS_LEN * dev->real_num_tx_queues;
171         default:
172                 return -EOPNOTSUPP;
173         }
174 }
175
176 static void veth_get_ethtool_stats(struct net_device *dev,
177                 struct ethtool_stats *stats, u64 *data)
178 {
179         struct veth_priv *rcv_priv, *priv = netdev_priv(dev);
180         struct net_device *peer = rtnl_dereference(priv->peer);
181         int i, j, idx;
182
183         data[0] = peer ? peer->ifindex : 0;
184         idx = 1;
185         for (i = 0; i < dev->real_num_rx_queues; i++) {
186                 const struct veth_rq_stats *rq_stats = &priv->rq[i].stats;
187                 const void *stats_base = (void *)&rq_stats->vs;
188                 unsigned int start;
189                 size_t offset;
190
191                 do {
192                         start = u64_stats_fetch_begin_irq(&rq_stats->syncp);
193                         for (j = 0; j < VETH_RQ_STATS_LEN; j++) {
194                                 offset = veth_rq_stats_desc[j].offset;
195                                 data[idx + j] = *(u64 *)(stats_base + offset);
196                         }
197                 } while (u64_stats_fetch_retry_irq(&rq_stats->syncp, start));
198                 idx += VETH_RQ_STATS_LEN;
199         }
200
201         if (!peer)
202                 return;
203
204         rcv_priv = netdev_priv(peer);
205         for (i = 0; i < peer->real_num_rx_queues; i++) {
206                 const struct veth_rq_stats *rq_stats = &rcv_priv->rq[i].stats;
207                 const void *base = (void *)&rq_stats->vs;
208                 unsigned int start, tx_idx = idx;
209                 size_t offset;
210
211                 tx_idx += (i % dev->real_num_tx_queues) * VETH_TQ_STATS_LEN;
212                 do {
213                         start = u64_stats_fetch_begin_irq(&rq_stats->syncp);
214                         for (j = 0; j < VETH_TQ_STATS_LEN; j++) {
215                                 offset = veth_tq_stats_desc[j].offset;
216                                 data[tx_idx + j] += *(u64 *)(base + offset);
217                         }
218                 } while (u64_stats_fetch_retry_irq(&rq_stats->syncp, start));
219         }
220 }
221
222 static void veth_get_channels(struct net_device *dev,
223                               struct ethtool_channels *channels)
224 {
225         channels->tx_count = dev->real_num_tx_queues;
226         channels->rx_count = dev->real_num_rx_queues;
227         channels->max_tx = dev->num_tx_queues;
228         channels->max_rx = dev->num_rx_queues;
229 }
230
231 static int veth_set_channels(struct net_device *dev,
232                              struct ethtool_channels *ch);
233
234 static const struct ethtool_ops veth_ethtool_ops = {
235         .get_drvinfo            = veth_get_drvinfo,
236         .get_link               = ethtool_op_get_link,
237         .get_strings            = veth_get_strings,
238         .get_sset_count         = veth_get_sset_count,
239         .get_ethtool_stats      = veth_get_ethtool_stats,
240         .get_link_ksettings     = veth_get_link_ksettings,
241         .get_ts_info            = ethtool_op_get_ts_info,
242         .get_channels           = veth_get_channels,
243         .set_channels           = veth_set_channels,
244 };
245
246 /* general routines */
247
248 static bool veth_is_xdp_frame(void *ptr)
249 {
250         return (unsigned long)ptr & VETH_XDP_FLAG;
251 }
252
253 static struct xdp_frame *veth_ptr_to_xdp(void *ptr)
254 {
255         return (void *)((unsigned long)ptr & ~VETH_XDP_FLAG);
256 }
257
258 static void *veth_xdp_to_ptr(struct xdp_frame *xdp)
259 {
260         return (void *)((unsigned long)xdp | VETH_XDP_FLAG);
261 }
262
263 static void veth_ptr_free(void *ptr)
264 {
265         if (veth_is_xdp_frame(ptr))
266                 xdp_return_frame(veth_ptr_to_xdp(ptr));
267         else
268                 kfree_skb(ptr);
269 }
270
271 static void __veth_xdp_flush(struct veth_rq *rq)
272 {
273         /* Write ptr_ring before reading rx_notify_masked */
274         smp_mb();
275         if (!READ_ONCE(rq->rx_notify_masked) &&
276             napi_schedule_prep(&rq->xdp_napi)) {
277                 WRITE_ONCE(rq->rx_notify_masked, true);
278                 __napi_schedule(&rq->xdp_napi);
279         }
280 }
281
282 static int veth_xdp_rx(struct veth_rq *rq, struct sk_buff *skb)
283 {
284         if (unlikely(ptr_ring_produce(&rq->xdp_ring, skb))) {
285                 dev_kfree_skb_any(skb);
286                 return NET_RX_DROP;
287         }
288
289         return NET_RX_SUCCESS;
290 }
291
292 static int veth_forward_skb(struct net_device *dev, struct sk_buff *skb,
293                             struct veth_rq *rq, bool xdp)
294 {
295         return __dev_forward_skb(dev, skb) ?: xdp ?
296                 veth_xdp_rx(rq, skb) :
297                 netif_rx(skb);
298 }
299
300 /* return true if the specified skb has chances of GRO aggregation
301  * Don't strive for accuracy, but try to avoid GRO overhead in the most
302  * common scenarios.
303  * When XDP is enabled, all traffic is considered eligible, as the xmit
304  * device has TSO off.
305  * When TSO is enabled on the xmit device, we are likely interested only
306  * in UDP aggregation, explicitly check for that if the skb is suspected
307  * - the sock_wfree destructor is used by UDP, ICMP and XDP sockets -
308  * to belong to locally generated UDP traffic.
309  */
310 static bool veth_skb_is_eligible_for_gro(const struct net_device *dev,
311                                          const struct net_device *rcv,
312                                          const struct sk_buff *skb)
313 {
314         return !(dev->features & NETIF_F_ALL_TSO) ||
315                 (skb->destructor == sock_wfree &&
316                  rcv->features & (NETIF_F_GRO_FRAGLIST | NETIF_F_GRO_UDP_FWD));
317 }
318
319 static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev)
320 {
321         struct veth_priv *rcv_priv, *priv = netdev_priv(dev);
322         struct veth_rq *rq = NULL;
323         struct net_device *rcv;
324         int length = skb->len;
325         bool use_napi = false;
326         int rxq;
327
328         rcu_read_lock();
329         rcv = rcu_dereference(priv->peer);
330         if (unlikely(!rcv) || !pskb_may_pull(skb, ETH_HLEN)) {
331                 kfree_skb(skb);
332                 goto drop;
333         }
334
335         rcv_priv = netdev_priv(rcv);
336         rxq = skb_get_queue_mapping(skb);
337         if (rxq < rcv->real_num_rx_queues) {
338                 rq = &rcv_priv->rq[rxq];
339
340                 /* The napi pointer is available when an XDP program is
341                  * attached or when GRO is enabled
342                  * Don't bother with napi/GRO if the skb can't be aggregated
343                  */
344                 use_napi = rcu_access_pointer(rq->napi) &&
345                            veth_skb_is_eligible_for_gro(dev, rcv, skb);
346         }
347
348         skb_tx_timestamp(skb);
349         if (likely(veth_forward_skb(rcv, skb, rq, use_napi) == NET_RX_SUCCESS)) {
350                 if (!use_napi)
351                         dev_lstats_add(dev, length);
352         } else {
353 drop:
354                 atomic64_inc(&priv->dropped);
355         }
356
357         if (use_napi)
358                 __veth_xdp_flush(rq);
359
360         rcu_read_unlock();
361
362         return NETDEV_TX_OK;
363 }
364
365 static u64 veth_stats_tx(struct net_device *dev, u64 *packets, u64 *bytes)
366 {
367         struct veth_priv *priv = netdev_priv(dev);
368
369         dev_lstats_read(dev, packets, bytes);
370         return atomic64_read(&priv->dropped);
371 }
372
373 static void veth_stats_rx(struct veth_stats *result, struct net_device *dev)
374 {
375         struct veth_priv *priv = netdev_priv(dev);
376         int i;
377
378         result->peer_tq_xdp_xmit_err = 0;
379         result->xdp_packets = 0;
380         result->xdp_tx_err = 0;
381         result->xdp_bytes = 0;
382         result->rx_drops = 0;
383         for (i = 0; i < dev->num_rx_queues; i++) {
384                 u64 packets, bytes, drops, xdp_tx_err, peer_tq_xdp_xmit_err;
385                 struct veth_rq_stats *stats = &priv->rq[i].stats;
386                 unsigned int start;
387
388                 do {
389                         start = u64_stats_fetch_begin_irq(&stats->syncp);
390                         peer_tq_xdp_xmit_err = stats->vs.peer_tq_xdp_xmit_err;
391                         xdp_tx_err = stats->vs.xdp_tx_err;
392                         packets = stats->vs.xdp_packets;
393                         bytes = stats->vs.xdp_bytes;
394                         drops = stats->vs.rx_drops;
395                 } while (u64_stats_fetch_retry_irq(&stats->syncp, start));
396                 result->peer_tq_xdp_xmit_err += peer_tq_xdp_xmit_err;
397                 result->xdp_tx_err += xdp_tx_err;
398                 result->xdp_packets += packets;
399                 result->xdp_bytes += bytes;
400                 result->rx_drops += drops;
401         }
402 }
403
404 static void veth_get_stats64(struct net_device *dev,
405                              struct rtnl_link_stats64 *tot)
406 {
407         struct veth_priv *priv = netdev_priv(dev);
408         struct net_device *peer;
409         struct veth_stats rx;
410         u64 packets, bytes;
411
412         tot->tx_dropped = veth_stats_tx(dev, &packets, &bytes);
413         tot->tx_bytes = bytes;
414         tot->tx_packets = packets;
415
416         veth_stats_rx(&rx, dev);
417         tot->tx_dropped += rx.xdp_tx_err;
418         tot->rx_dropped = rx.rx_drops + rx.peer_tq_xdp_xmit_err;
419         tot->rx_bytes = rx.xdp_bytes;
420         tot->rx_packets = rx.xdp_packets;
421
422         rcu_read_lock();
423         peer = rcu_dereference(priv->peer);
424         if (peer) {
425                 veth_stats_tx(peer, &packets, &bytes);
426                 tot->rx_bytes += bytes;
427                 tot->rx_packets += packets;
428
429                 veth_stats_rx(&rx, peer);
430                 tot->tx_dropped += rx.peer_tq_xdp_xmit_err;
431                 tot->rx_dropped += rx.xdp_tx_err;
432                 tot->tx_bytes += rx.xdp_bytes;
433                 tot->tx_packets += rx.xdp_packets;
434         }
435         rcu_read_unlock();
436 }
437
438 /* fake multicast ability */
439 static void veth_set_multicast_list(struct net_device *dev)
440 {
441 }
442
443 static struct sk_buff *veth_build_skb(void *head, int headroom, int len,
444                                       int buflen)
445 {
446         struct sk_buff *skb;
447
448         skb = build_skb(head, buflen);
449         if (!skb)
450                 return NULL;
451
452         skb_reserve(skb, headroom);
453         skb_put(skb, len);
454
455         return skb;
456 }
457
458 static int veth_select_rxq(struct net_device *dev)
459 {
460         return smp_processor_id() % dev->real_num_rx_queues;
461 }
462
463 static struct net_device *veth_peer_dev(struct net_device *dev)
464 {
465         struct veth_priv *priv = netdev_priv(dev);
466
467         /* Callers must be under RCU read side. */
468         return rcu_dereference(priv->peer);
469 }
470
471 static int veth_xdp_xmit(struct net_device *dev, int n,
472                          struct xdp_frame **frames,
473                          u32 flags, bool ndo_xmit)
474 {
475         struct veth_priv *rcv_priv, *priv = netdev_priv(dev);
476         int i, ret = -ENXIO, nxmit = 0;
477         struct net_device *rcv;
478         unsigned int max_len;
479         struct veth_rq *rq;
480
481         if (unlikely(flags & ~XDP_XMIT_FLAGS_MASK))
482                 return -EINVAL;
483
484         rcu_read_lock();
485         rcv = rcu_dereference(priv->peer);
486         if (unlikely(!rcv))
487                 goto out;
488
489         rcv_priv = netdev_priv(rcv);
490         rq = &rcv_priv->rq[veth_select_rxq(rcv)];
491         /* The napi pointer is set if NAPI is enabled, which ensures that
492          * xdp_ring is initialized on receive side and the peer device is up.
493          */
494         if (!rcu_access_pointer(rq->napi))
495                 goto out;
496
497         max_len = rcv->mtu + rcv->hard_header_len + VLAN_HLEN;
498
499         spin_lock(&rq->xdp_ring.producer_lock);
500         for (i = 0; i < n; i++) {
501                 struct xdp_frame *frame = frames[i];
502                 void *ptr = veth_xdp_to_ptr(frame);
503
504                 if (unlikely(frame->len > max_len ||
505                              __ptr_ring_produce(&rq->xdp_ring, ptr)))
506                         break;
507                 nxmit++;
508         }
509         spin_unlock(&rq->xdp_ring.producer_lock);
510
511         if (flags & XDP_XMIT_FLUSH)
512                 __veth_xdp_flush(rq);
513
514         ret = nxmit;
515         if (ndo_xmit) {
516                 u64_stats_update_begin(&rq->stats.syncp);
517                 rq->stats.vs.peer_tq_xdp_xmit += nxmit;
518                 rq->stats.vs.peer_tq_xdp_xmit_err += n - nxmit;
519                 u64_stats_update_end(&rq->stats.syncp);
520         }
521
522 out:
523         rcu_read_unlock();
524
525         return ret;
526 }
527
528 static int veth_ndo_xdp_xmit(struct net_device *dev, int n,
529                              struct xdp_frame **frames, u32 flags)
530 {
531         int err;
532
533         err = veth_xdp_xmit(dev, n, frames, flags, true);
534         if (err < 0) {
535                 struct veth_priv *priv = netdev_priv(dev);
536
537                 atomic64_add(n, &priv->dropped);
538         }
539
540         return err;
541 }
542
543 static void veth_xdp_flush_bq(struct veth_rq *rq, struct veth_xdp_tx_bq *bq)
544 {
545         int sent, i, err = 0, drops;
546
547         sent = veth_xdp_xmit(rq->dev, bq->count, bq->q, 0, false);
548         if (sent < 0) {
549                 err = sent;
550                 sent = 0;
551         }
552
553         for (i = sent; unlikely(i < bq->count); i++)
554                 xdp_return_frame(bq->q[i]);
555
556         drops = bq->count - sent;
557         trace_xdp_bulk_tx(rq->dev, sent, drops, err);
558
559         u64_stats_update_begin(&rq->stats.syncp);
560         rq->stats.vs.xdp_tx += sent;
561         rq->stats.vs.xdp_tx_err += drops;
562         u64_stats_update_end(&rq->stats.syncp);
563
564         bq->count = 0;
565 }
566
567 static void veth_xdp_flush(struct veth_rq *rq, struct veth_xdp_tx_bq *bq)
568 {
569         struct veth_priv *rcv_priv, *priv = netdev_priv(rq->dev);
570         struct net_device *rcv;
571         struct veth_rq *rcv_rq;
572
573         rcu_read_lock();
574         veth_xdp_flush_bq(rq, bq);
575         rcv = rcu_dereference(priv->peer);
576         if (unlikely(!rcv))
577                 goto out;
578
579         rcv_priv = netdev_priv(rcv);
580         rcv_rq = &rcv_priv->rq[veth_select_rxq(rcv)];
581         /* xdp_ring is initialized on receive side? */
582         if (unlikely(!rcu_access_pointer(rcv_rq->xdp_prog)))
583                 goto out;
584
585         __veth_xdp_flush(rcv_rq);
586 out:
587         rcu_read_unlock();
588 }
589
590 static int veth_xdp_tx(struct veth_rq *rq, struct xdp_buff *xdp,
591                        struct veth_xdp_tx_bq *bq)
592 {
593         struct xdp_frame *frame = xdp_convert_buff_to_frame(xdp);
594
595         if (unlikely(!frame))
596                 return -EOVERFLOW;
597
598         if (unlikely(bq->count == VETH_XDP_TX_BULK_SIZE))
599                 veth_xdp_flush_bq(rq, bq);
600
601         bq->q[bq->count++] = frame;
602
603         return 0;
604 }
605
606 static struct xdp_frame *veth_xdp_rcv_one(struct veth_rq *rq,
607                                           struct xdp_frame *frame,
608                                           struct veth_xdp_tx_bq *bq,
609                                           struct veth_stats *stats)
610 {
611         struct xdp_frame orig_frame;
612         struct bpf_prog *xdp_prog;
613
614         rcu_read_lock();
615         xdp_prog = rcu_dereference(rq->xdp_prog);
616         if (likely(xdp_prog)) {
617                 struct xdp_buff xdp;
618                 u32 act;
619
620                 xdp_convert_frame_to_buff(frame, &xdp);
621                 xdp.rxq = &rq->xdp_rxq;
622
623                 act = bpf_prog_run_xdp(xdp_prog, &xdp);
624
625                 switch (act) {
626                 case XDP_PASS:
627                         if (xdp_update_frame_from_buff(&xdp, frame))
628                                 goto err_xdp;
629                         break;
630                 case XDP_TX:
631                         orig_frame = *frame;
632                         xdp.rxq->mem = frame->mem;
633                         if (unlikely(veth_xdp_tx(rq, &xdp, bq) < 0)) {
634                                 trace_xdp_exception(rq->dev, xdp_prog, act);
635                                 frame = &orig_frame;
636                                 stats->rx_drops++;
637                                 goto err_xdp;
638                         }
639                         stats->xdp_tx++;
640                         rcu_read_unlock();
641                         goto xdp_xmit;
642                 case XDP_REDIRECT:
643                         orig_frame = *frame;
644                         xdp.rxq->mem = frame->mem;
645                         if (xdp_do_redirect(rq->dev, &xdp, xdp_prog)) {
646                                 frame = &orig_frame;
647                                 stats->rx_drops++;
648                                 goto err_xdp;
649                         }
650                         stats->xdp_redirect++;
651                         rcu_read_unlock();
652                         goto xdp_xmit;
653                 default:
654                         bpf_warn_invalid_xdp_action(act);
655                         fallthrough;
656                 case XDP_ABORTED:
657                         trace_xdp_exception(rq->dev, xdp_prog, act);
658                         fallthrough;
659                 case XDP_DROP:
660                         stats->xdp_drops++;
661                         goto err_xdp;
662                 }
663         }
664         rcu_read_unlock();
665
666         return frame;
667 err_xdp:
668         rcu_read_unlock();
669         xdp_return_frame(frame);
670 xdp_xmit:
671         return NULL;
672 }
673
674 /* frames array contains VETH_XDP_BATCH at most */
675 static void veth_xdp_rcv_bulk_skb(struct veth_rq *rq, void **frames,
676                                   int n_xdpf, struct veth_xdp_tx_bq *bq,
677                                   struct veth_stats *stats)
678 {
679         void *skbs[VETH_XDP_BATCH];
680         int i;
681
682         if (xdp_alloc_skb_bulk(skbs, n_xdpf,
683                                GFP_ATOMIC | __GFP_ZERO) < 0) {
684                 for (i = 0; i < n_xdpf; i++)
685                         xdp_return_frame(frames[i]);
686                 stats->rx_drops += n_xdpf;
687
688                 return;
689         }
690
691         for (i = 0; i < n_xdpf; i++) {
692                 struct sk_buff *skb = skbs[i];
693
694                 skb = __xdp_build_skb_from_frame(frames[i], skb,
695                                                  rq->dev);
696                 if (!skb) {
697                         xdp_return_frame(frames[i]);
698                         stats->rx_drops++;
699                         continue;
700                 }
701                 napi_gro_receive(&rq->xdp_napi, skb);
702         }
703 }
704
705 static struct sk_buff *veth_xdp_rcv_skb(struct veth_rq *rq,
706                                         struct sk_buff *skb,
707                                         struct veth_xdp_tx_bq *bq,
708                                         struct veth_stats *stats)
709 {
710         u32 pktlen, headroom, act, metalen, frame_sz;
711         void *orig_data, *orig_data_end;
712         struct bpf_prog *xdp_prog;
713         int mac_len, delta, off;
714         struct xdp_buff xdp;
715
716         skb_prepare_for_gro(skb);
717
718         rcu_read_lock();
719         xdp_prog = rcu_dereference(rq->xdp_prog);
720         if (unlikely(!xdp_prog)) {
721                 rcu_read_unlock();
722                 goto out;
723         }
724
725         mac_len = skb->data - skb_mac_header(skb);
726         pktlen = skb->len + mac_len;
727         headroom = skb_headroom(skb) - mac_len;
728
729         if (skb_shared(skb) || skb_head_is_locked(skb) ||
730             skb_is_nonlinear(skb) || headroom < XDP_PACKET_HEADROOM) {
731                 struct sk_buff *nskb;
732                 int size, head_off;
733                 void *head, *start;
734                 struct page *page;
735
736                 size = SKB_DATA_ALIGN(VETH_XDP_HEADROOM + pktlen) +
737                        SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
738                 if (size > PAGE_SIZE)
739                         goto drop;
740
741                 page = alloc_page(GFP_ATOMIC | __GFP_NOWARN);
742                 if (!page)
743                         goto drop;
744
745                 head = page_address(page);
746                 start = head + VETH_XDP_HEADROOM;
747                 if (skb_copy_bits(skb, -mac_len, start, pktlen)) {
748                         page_frag_free(head);
749                         goto drop;
750                 }
751
752                 nskb = veth_build_skb(head, VETH_XDP_HEADROOM + mac_len,
753                                       skb->len, PAGE_SIZE);
754                 if (!nskb) {
755                         page_frag_free(head);
756                         goto drop;
757                 }
758
759                 skb_copy_header(nskb, skb);
760                 head_off = skb_headroom(nskb) - skb_headroom(skb);
761                 skb_headers_offset_update(nskb, head_off);
762                 consume_skb(skb);
763                 skb = nskb;
764         }
765
766         /* SKB "head" area always have tailroom for skb_shared_info */
767         frame_sz = skb_end_pointer(skb) - skb->head;
768         frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
769         xdp_init_buff(&xdp, frame_sz, &rq->xdp_rxq);
770         xdp_prepare_buff(&xdp, skb->head, skb->mac_header, pktlen, true);
771
772         orig_data = xdp.data;
773         orig_data_end = xdp.data_end;
774
775         act = bpf_prog_run_xdp(xdp_prog, &xdp);
776
777         switch (act) {
778         case XDP_PASS:
779                 break;
780         case XDP_TX:
781                 get_page(virt_to_page(xdp.data));
782                 consume_skb(skb);
783                 xdp.rxq->mem = rq->xdp_mem;
784                 if (unlikely(veth_xdp_tx(rq, &xdp, bq) < 0)) {
785                         trace_xdp_exception(rq->dev, xdp_prog, act);
786                         stats->rx_drops++;
787                         goto err_xdp;
788                 }
789                 stats->xdp_tx++;
790                 rcu_read_unlock();
791                 goto xdp_xmit;
792         case XDP_REDIRECT:
793                 get_page(virt_to_page(xdp.data));
794                 consume_skb(skb);
795                 xdp.rxq->mem = rq->xdp_mem;
796                 if (xdp_do_redirect(rq->dev, &xdp, xdp_prog)) {
797                         stats->rx_drops++;
798                         goto err_xdp;
799                 }
800                 stats->xdp_redirect++;
801                 rcu_read_unlock();
802                 goto xdp_xmit;
803         default:
804                 bpf_warn_invalid_xdp_action(act);
805                 fallthrough;
806         case XDP_ABORTED:
807                 trace_xdp_exception(rq->dev, xdp_prog, act);
808                 fallthrough;
809         case XDP_DROP:
810                 stats->xdp_drops++;
811                 goto xdp_drop;
812         }
813         rcu_read_unlock();
814
815         /* check if bpf_xdp_adjust_head was used */
816         delta = orig_data - xdp.data;
817         off = mac_len + delta;
818         if (off > 0)
819                 __skb_push(skb, off);
820         else if (off < 0)
821                 __skb_pull(skb, -off);
822         skb->mac_header -= delta;
823
824         /* check if bpf_xdp_adjust_tail was used */
825         off = xdp.data_end - orig_data_end;
826         if (off != 0)
827                 __skb_put(skb, off); /* positive on grow, negative on shrink */
828         skb->protocol = eth_type_trans(skb, rq->dev);
829
830         metalen = xdp.data - xdp.data_meta;
831         if (metalen)
832                 skb_metadata_set(skb, metalen);
833 out:
834         return skb;
835 drop:
836         stats->rx_drops++;
837 xdp_drop:
838         rcu_read_unlock();
839         kfree_skb(skb);
840         return NULL;
841 err_xdp:
842         rcu_read_unlock();
843         page_frag_free(xdp.data);
844 xdp_xmit:
845         return NULL;
846 }
847
848 static int veth_xdp_rcv(struct veth_rq *rq, int budget,
849                         struct veth_xdp_tx_bq *bq,
850                         struct veth_stats *stats)
851 {
852         int i, done = 0, n_xdpf = 0;
853         void *xdpf[VETH_XDP_BATCH];
854
855         for (i = 0; i < budget; i++) {
856                 void *ptr = __ptr_ring_consume(&rq->xdp_ring);
857
858                 if (!ptr)
859                         break;
860
861                 if (veth_is_xdp_frame(ptr)) {
862                         /* ndo_xdp_xmit */
863                         struct xdp_frame *frame = veth_ptr_to_xdp(ptr);
864
865                         stats->xdp_bytes += frame->len;
866                         frame = veth_xdp_rcv_one(rq, frame, bq, stats);
867                         if (frame) {
868                                 /* XDP_PASS */
869                                 xdpf[n_xdpf++] = frame;
870                                 if (n_xdpf == VETH_XDP_BATCH) {
871                                         veth_xdp_rcv_bulk_skb(rq, xdpf, n_xdpf,
872                                                               bq, stats);
873                                         n_xdpf = 0;
874                                 }
875                         }
876                 } else {
877                         /* ndo_start_xmit */
878                         struct sk_buff *skb = ptr;
879
880                         stats->xdp_bytes += skb->len;
881                         skb = veth_xdp_rcv_skb(rq, skb, bq, stats);
882                         if (skb) {
883                                 if (skb_shared(skb) || skb_unclone(skb, GFP_ATOMIC))
884                                         netif_receive_skb(skb);
885                                 else
886                                         napi_gro_receive(&rq->xdp_napi, skb);
887                         }
888                 }
889                 done++;
890         }
891
892         if (n_xdpf)
893                 veth_xdp_rcv_bulk_skb(rq, xdpf, n_xdpf, bq, stats);
894
895         u64_stats_update_begin(&rq->stats.syncp);
896         rq->stats.vs.xdp_redirect += stats->xdp_redirect;
897         rq->stats.vs.xdp_bytes += stats->xdp_bytes;
898         rq->stats.vs.xdp_drops += stats->xdp_drops;
899         rq->stats.vs.rx_drops += stats->rx_drops;
900         rq->stats.vs.xdp_packets += done;
901         u64_stats_update_end(&rq->stats.syncp);
902
903         return done;
904 }
905
906 static int veth_poll(struct napi_struct *napi, int budget)
907 {
908         struct veth_rq *rq =
909                 container_of(napi, struct veth_rq, xdp_napi);
910         struct veth_stats stats = {};
911         struct veth_xdp_tx_bq bq;
912         int done;
913
914         bq.count = 0;
915
916         xdp_set_return_frame_no_direct();
917         done = veth_xdp_rcv(rq, budget, &bq, &stats);
918
919         if (done < budget && napi_complete_done(napi, done)) {
920                 /* Write rx_notify_masked before reading ptr_ring */
921                 smp_store_mb(rq->rx_notify_masked, false);
922                 if (unlikely(!__ptr_ring_empty(&rq->xdp_ring))) {
923                         if (napi_schedule_prep(&rq->xdp_napi)) {
924                                 WRITE_ONCE(rq->rx_notify_masked, true);
925                                 __napi_schedule(&rq->xdp_napi);
926                         }
927                 }
928         }
929
930         if (stats.xdp_tx > 0)
931                 veth_xdp_flush(rq, &bq);
932         if (stats.xdp_redirect > 0)
933                 xdp_do_flush();
934         xdp_clear_return_frame_no_direct();
935
936         return done;
937 }
938
939 static int __veth_napi_enable_range(struct net_device *dev, int start, int end)
940 {
941         struct veth_priv *priv = netdev_priv(dev);
942         int err, i;
943
944         for (i = start; i < end; i++) {
945                 struct veth_rq *rq = &priv->rq[i];
946
947                 err = ptr_ring_init(&rq->xdp_ring, VETH_RING_SIZE, GFP_KERNEL);
948                 if (err)
949                         goto err_xdp_ring;
950         }
951
952         for (i = start; i < end; i++) {
953                 struct veth_rq *rq = &priv->rq[i];
954
955                 napi_enable(&rq->xdp_napi);
956                 rcu_assign_pointer(priv->rq[i].napi, &priv->rq[i].xdp_napi);
957         }
958
959         return 0;
960
961 err_xdp_ring:
962         for (i--; i >= start; i--)
963                 ptr_ring_cleanup(&priv->rq[i].xdp_ring, veth_ptr_free);
964
965         return err;
966 }
967
968 static int __veth_napi_enable(struct net_device *dev)
969 {
970         return __veth_napi_enable_range(dev, 0, dev->real_num_rx_queues);
971 }
972
973 static void veth_napi_del_range(struct net_device *dev, int start, int end)
974 {
975         struct veth_priv *priv = netdev_priv(dev);
976         int i;
977
978         for (i = start; i < end; i++) {
979                 struct veth_rq *rq = &priv->rq[i];
980
981                 rcu_assign_pointer(priv->rq[i].napi, NULL);
982                 napi_disable(&rq->xdp_napi);
983                 __netif_napi_del(&rq->xdp_napi);
984         }
985         synchronize_net();
986
987         for (i = start; i < end; i++) {
988                 struct veth_rq *rq = &priv->rq[i];
989
990                 rq->rx_notify_masked = false;
991                 ptr_ring_cleanup(&rq->xdp_ring, veth_ptr_free);
992         }
993 }
994
995 static void veth_napi_del(struct net_device *dev)
996 {
997         veth_napi_del_range(dev, 0, dev->real_num_rx_queues);
998 }
999
1000 static bool veth_gro_requested(const struct net_device *dev)
1001 {
1002         return !!(dev->wanted_features & NETIF_F_GRO);
1003 }
1004
1005 static int veth_enable_xdp_range(struct net_device *dev, int start, int end,
1006                                  bool napi_already_on)
1007 {
1008         struct veth_priv *priv = netdev_priv(dev);
1009         int err, i;
1010
1011         for (i = start; i < end; i++) {
1012                 struct veth_rq *rq = &priv->rq[i];
1013
1014                 if (!napi_already_on)
1015                         netif_napi_add(dev, &rq->xdp_napi, veth_poll, NAPI_POLL_WEIGHT);
1016                 err = xdp_rxq_info_reg(&rq->xdp_rxq, dev, i, rq->xdp_napi.napi_id);
1017                 if (err < 0)
1018                         goto err_rxq_reg;
1019
1020                 err = xdp_rxq_info_reg_mem_model(&rq->xdp_rxq,
1021                                                  MEM_TYPE_PAGE_SHARED,
1022                                                  NULL);
1023                 if (err < 0)
1024                         goto err_reg_mem;
1025
1026                 /* Save original mem info as it can be overwritten */
1027                 rq->xdp_mem = rq->xdp_rxq.mem;
1028         }
1029         return 0;
1030
1031 err_reg_mem:
1032         xdp_rxq_info_unreg(&priv->rq[i].xdp_rxq);
1033 err_rxq_reg:
1034         for (i--; i >= start; i--) {
1035                 struct veth_rq *rq = &priv->rq[i];
1036
1037                 xdp_rxq_info_unreg(&rq->xdp_rxq);
1038                 if (!napi_already_on)
1039                         netif_napi_del(&rq->xdp_napi);
1040         }
1041
1042         return err;
1043 }
1044
1045 static void veth_disable_xdp_range(struct net_device *dev, int start, int end,
1046                                    bool delete_napi)
1047 {
1048         struct veth_priv *priv = netdev_priv(dev);
1049         int i;
1050
1051         for (i = start; i < end; i++) {
1052                 struct veth_rq *rq = &priv->rq[i];
1053
1054                 rq->xdp_rxq.mem = rq->xdp_mem;
1055                 xdp_rxq_info_unreg(&rq->xdp_rxq);
1056
1057                 if (delete_napi)
1058                         netif_napi_del(&rq->xdp_napi);
1059         }
1060 }
1061
1062 static int veth_enable_xdp(struct net_device *dev)
1063 {
1064         bool napi_already_on = veth_gro_requested(dev) && (dev->flags & IFF_UP);
1065         struct veth_priv *priv = netdev_priv(dev);
1066         int err, i;
1067
1068         if (!xdp_rxq_info_is_reg(&priv->rq[0].xdp_rxq)) {
1069                 err = veth_enable_xdp_range(dev, 0, dev->real_num_rx_queues, napi_already_on);
1070                 if (err)
1071                         return err;
1072
1073                 if (!napi_already_on) {
1074                         err = __veth_napi_enable(dev);
1075                         if (err) {
1076                                 veth_disable_xdp_range(dev, 0, dev->real_num_rx_queues, true);
1077                                 return err;
1078                         }
1079
1080                         if (!veth_gro_requested(dev)) {
1081                                 /* user-space did not require GRO, but adding XDP
1082                                  * is supposed to get GRO working
1083                                  */
1084                                 dev->features |= NETIF_F_GRO;
1085                                 netdev_features_change(dev);
1086                         }
1087                 }
1088         }
1089
1090         for (i = 0; i < dev->real_num_rx_queues; i++) {
1091                 rcu_assign_pointer(priv->rq[i].xdp_prog, priv->_xdp_prog);
1092                 rcu_assign_pointer(priv->rq[i].napi, &priv->rq[i].xdp_napi);
1093         }
1094
1095         return 0;
1096 }
1097
1098 static void veth_disable_xdp(struct net_device *dev)
1099 {
1100         struct veth_priv *priv = netdev_priv(dev);
1101         int i;
1102
1103         for (i = 0; i < dev->real_num_rx_queues; i++)
1104                 rcu_assign_pointer(priv->rq[i].xdp_prog, NULL);
1105
1106         if (!netif_running(dev) || !veth_gro_requested(dev)) {
1107                 veth_napi_del(dev);
1108
1109                 /* if user-space did not require GRO, since adding XDP
1110                  * enabled it, clear it now
1111                  */
1112                 if (!veth_gro_requested(dev) && netif_running(dev)) {
1113                         dev->features &= ~NETIF_F_GRO;
1114                         netdev_features_change(dev);
1115                 }
1116         }
1117
1118         veth_disable_xdp_range(dev, 0, dev->real_num_rx_queues, false);
1119 }
1120
1121 static int veth_napi_enable_range(struct net_device *dev, int start, int end)
1122 {
1123         struct veth_priv *priv = netdev_priv(dev);
1124         int err, i;
1125
1126         for (i = start; i < end; i++) {
1127                 struct veth_rq *rq = &priv->rq[i];
1128
1129                 netif_napi_add(dev, &rq->xdp_napi, veth_poll, NAPI_POLL_WEIGHT);
1130         }
1131
1132         err = __veth_napi_enable_range(dev, start, end);
1133         if (err) {
1134                 for (i = start; i < end; i++) {
1135                         struct veth_rq *rq = &priv->rq[i];
1136
1137                         netif_napi_del(&rq->xdp_napi);
1138                 }
1139                 return err;
1140         }
1141         return err;
1142 }
1143
1144 static int veth_napi_enable(struct net_device *dev)
1145 {
1146         return veth_napi_enable_range(dev, 0, dev->real_num_rx_queues);
1147 }
1148
1149 static void veth_disable_range_safe(struct net_device *dev, int start, int end)
1150 {
1151         struct veth_priv *priv = netdev_priv(dev);
1152
1153         if (start >= end)
1154                 return;
1155
1156         if (priv->_xdp_prog) {
1157                 veth_napi_del_range(dev, start, end);
1158                 veth_disable_xdp_range(dev, start, end, false);
1159         } else if (veth_gro_requested(dev)) {
1160                 veth_napi_del_range(dev, start, end);
1161         }
1162 }
1163
1164 static int veth_enable_range_safe(struct net_device *dev, int start, int end)
1165 {
1166         struct veth_priv *priv = netdev_priv(dev);
1167         int err;
1168
1169         if (start >= end)
1170                 return 0;
1171
1172         if (priv->_xdp_prog) {
1173                 /* these channels are freshly initialized, napi is not on there even
1174                  * when GRO is requeste
1175                  */
1176                 err = veth_enable_xdp_range(dev, start, end, false);
1177                 if (err)
1178                         return err;
1179
1180                 err = __veth_napi_enable_range(dev, start, end);
1181                 if (err) {
1182                         /* on error always delete the newly added napis */
1183                         veth_disable_xdp_range(dev, start, end, true);
1184                         return err;
1185                 }
1186         } else if (veth_gro_requested(dev)) {
1187                 return veth_napi_enable_range(dev, start, end);
1188         }
1189         return 0;
1190 }
1191
1192 static int veth_set_channels(struct net_device *dev,
1193                              struct ethtool_channels *ch)
1194 {
1195         struct veth_priv *priv = netdev_priv(dev);
1196         unsigned int old_rx_count, new_rx_count;
1197         struct veth_priv *peer_priv;
1198         struct net_device *peer;
1199         int err;
1200
1201         /* sanity check. Upper bounds are already enforced by the caller */
1202         if (!ch->rx_count || !ch->tx_count)
1203                 return -EINVAL;
1204
1205         /* avoid braking XDP, if that is enabled */
1206         peer = rtnl_dereference(priv->peer);
1207         peer_priv = peer ? netdev_priv(peer) : NULL;
1208         if (priv->_xdp_prog && peer && ch->rx_count < peer->real_num_tx_queues)
1209                 return -EINVAL;
1210
1211         if (peer && peer_priv && peer_priv->_xdp_prog && ch->tx_count > peer->real_num_rx_queues)
1212                 return -EINVAL;
1213
1214         old_rx_count = dev->real_num_rx_queues;
1215         new_rx_count = ch->rx_count;
1216         if (netif_running(dev)) {
1217                 /* turn device off */
1218                 netif_carrier_off(dev);
1219                 if (peer)
1220                         netif_carrier_off(peer);
1221
1222                 /* try to allocate new resurces, as needed*/
1223                 err = veth_enable_range_safe(dev, old_rx_count, new_rx_count);
1224                 if (err)
1225                         goto out;
1226         }
1227
1228         err = netif_set_real_num_rx_queues(dev, ch->rx_count);
1229         if (err)
1230                 goto revert;
1231
1232         err = netif_set_real_num_tx_queues(dev, ch->tx_count);
1233         if (err) {
1234                 int err2 = netif_set_real_num_rx_queues(dev, old_rx_count);
1235
1236                 /* this error condition could happen only if rx and tx change
1237                  * in opposite directions (e.g. tx nr raises, rx nr decreases)
1238                  * and we can't do anything to fully restore the original
1239                  * status
1240                  */
1241                 if (err2)
1242                         pr_warn("Can't restore rx queues config %d -> %d %d",
1243                                 new_rx_count, old_rx_count, err2);
1244                 else
1245                         goto revert;
1246         }
1247
1248 out:
1249         if (netif_running(dev)) {
1250                 /* note that we need to swap the arguments WRT the enable part
1251                  * to identify the range we have to disable
1252                  */
1253                 veth_disable_range_safe(dev, new_rx_count, old_rx_count);
1254                 netif_carrier_on(dev);
1255                 if (peer)
1256                         netif_carrier_on(peer);
1257         }
1258         return err;
1259
1260 revert:
1261         new_rx_count = old_rx_count;
1262         old_rx_count = ch->rx_count;
1263         goto out;
1264 }
1265
1266 static int veth_open(struct net_device *dev)
1267 {
1268         struct veth_priv *priv = netdev_priv(dev);
1269         struct net_device *peer = rtnl_dereference(priv->peer);
1270         int err;
1271
1272         if (!peer)
1273                 return -ENOTCONN;
1274
1275         if (priv->_xdp_prog) {
1276                 err = veth_enable_xdp(dev);
1277                 if (err)
1278                         return err;
1279         } else if (veth_gro_requested(dev)) {
1280                 err = veth_napi_enable(dev);
1281                 if (err)
1282                         return err;
1283         }
1284
1285         if (peer->flags & IFF_UP) {
1286                 netif_carrier_on(dev);
1287                 netif_carrier_on(peer);
1288         }
1289
1290         return 0;
1291 }
1292
1293 static int veth_close(struct net_device *dev)
1294 {
1295         struct veth_priv *priv = netdev_priv(dev);
1296         struct net_device *peer = rtnl_dereference(priv->peer);
1297
1298         netif_carrier_off(dev);
1299         if (peer)
1300                 netif_carrier_off(peer);
1301
1302         if (priv->_xdp_prog)
1303                 veth_disable_xdp(dev);
1304         else if (veth_gro_requested(dev))
1305                 veth_napi_del(dev);
1306
1307         return 0;
1308 }
1309
1310 static int is_valid_veth_mtu(int mtu)
1311 {
1312         return mtu >= ETH_MIN_MTU && mtu <= ETH_MAX_MTU;
1313 }
1314
1315 static int veth_alloc_queues(struct net_device *dev)
1316 {
1317         struct veth_priv *priv = netdev_priv(dev);
1318         int i;
1319
1320         priv->rq = kcalloc(dev->num_rx_queues, sizeof(*priv->rq), GFP_KERNEL);
1321         if (!priv->rq)
1322                 return -ENOMEM;
1323
1324         for (i = 0; i < dev->num_rx_queues; i++) {
1325                 priv->rq[i].dev = dev;
1326                 u64_stats_init(&priv->rq[i].stats.syncp);
1327         }
1328
1329         return 0;
1330 }
1331
1332 static void veth_free_queues(struct net_device *dev)
1333 {
1334         struct veth_priv *priv = netdev_priv(dev);
1335
1336         kfree(priv->rq);
1337 }
1338
1339 static int veth_dev_init(struct net_device *dev)
1340 {
1341         int err;
1342
1343         dev->lstats = netdev_alloc_pcpu_stats(struct pcpu_lstats);
1344         if (!dev->lstats)
1345                 return -ENOMEM;
1346
1347         err = veth_alloc_queues(dev);
1348         if (err) {
1349                 free_percpu(dev->lstats);
1350                 return err;
1351         }
1352
1353         return 0;
1354 }
1355
1356 static void veth_dev_free(struct net_device *dev)
1357 {
1358         veth_free_queues(dev);
1359         free_percpu(dev->lstats);
1360 }
1361
1362 #ifdef CONFIG_NET_POLL_CONTROLLER
1363 static void veth_poll_controller(struct net_device *dev)
1364 {
1365         /* veth only receives frames when its peer sends one
1366          * Since it has nothing to do with disabling irqs, we are guaranteed
1367          * never to have pending data when we poll for it so
1368          * there is nothing to do here.
1369          *
1370          * We need this though so netpoll recognizes us as an interface that
1371          * supports polling, which enables bridge devices in virt setups to
1372          * still use netconsole
1373          */
1374 }
1375 #endif  /* CONFIG_NET_POLL_CONTROLLER */
1376
1377 static int veth_get_iflink(const struct net_device *dev)
1378 {
1379         struct veth_priv *priv = netdev_priv(dev);
1380         struct net_device *peer;
1381         int iflink;
1382
1383         rcu_read_lock();
1384         peer = rcu_dereference(priv->peer);
1385         iflink = peer ? peer->ifindex : 0;
1386         rcu_read_unlock();
1387
1388         return iflink;
1389 }
1390
1391 static netdev_features_t veth_fix_features(struct net_device *dev,
1392                                            netdev_features_t features)
1393 {
1394         struct veth_priv *priv = netdev_priv(dev);
1395         struct net_device *peer;
1396
1397         peer = rtnl_dereference(priv->peer);
1398         if (peer) {
1399                 struct veth_priv *peer_priv = netdev_priv(peer);
1400
1401                 if (peer_priv->_xdp_prog)
1402                         features &= ~NETIF_F_GSO_SOFTWARE;
1403         }
1404         if (priv->_xdp_prog)
1405                 features |= NETIF_F_GRO;
1406
1407         return features;
1408 }
1409
1410 static int veth_set_features(struct net_device *dev,
1411                              netdev_features_t features)
1412 {
1413         netdev_features_t changed = features ^ dev->features;
1414         struct veth_priv *priv = netdev_priv(dev);
1415         int err;
1416
1417         if (!(changed & NETIF_F_GRO) || !(dev->flags & IFF_UP) || priv->_xdp_prog)
1418                 return 0;
1419
1420         if (features & NETIF_F_GRO) {
1421                 err = veth_napi_enable(dev);
1422                 if (err)
1423                         return err;
1424         } else {
1425                 veth_napi_del(dev);
1426         }
1427         return 0;
1428 }
1429
1430 static void veth_set_rx_headroom(struct net_device *dev, int new_hr)
1431 {
1432         struct veth_priv *peer_priv, *priv = netdev_priv(dev);
1433         struct net_device *peer;
1434
1435         if (new_hr < 0)
1436                 new_hr = 0;
1437
1438         rcu_read_lock();
1439         peer = rcu_dereference(priv->peer);
1440         if (unlikely(!peer))
1441                 goto out;
1442
1443         peer_priv = netdev_priv(peer);
1444         priv->requested_headroom = new_hr;
1445         new_hr = max(priv->requested_headroom, peer_priv->requested_headroom);
1446         dev->needed_headroom = new_hr;
1447         peer->needed_headroom = new_hr;
1448
1449 out:
1450         rcu_read_unlock();
1451 }
1452
1453 static int veth_xdp_set(struct net_device *dev, struct bpf_prog *prog,
1454                         struct netlink_ext_ack *extack)
1455 {
1456         struct veth_priv *priv = netdev_priv(dev);
1457         struct bpf_prog *old_prog;
1458         struct net_device *peer;
1459         unsigned int max_mtu;
1460         int err;
1461
1462         old_prog = priv->_xdp_prog;
1463         priv->_xdp_prog = prog;
1464         peer = rtnl_dereference(priv->peer);
1465
1466         if (prog) {
1467                 if (!peer) {
1468                         NL_SET_ERR_MSG_MOD(extack, "Cannot set XDP when peer is detached");
1469                         err = -ENOTCONN;
1470                         goto err;
1471                 }
1472
1473                 max_mtu = PAGE_SIZE - VETH_XDP_HEADROOM -
1474                           peer->hard_header_len -
1475                           SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1476                 if (peer->mtu > max_mtu) {
1477                         NL_SET_ERR_MSG_MOD(extack, "Peer MTU is too large to set XDP");
1478                         err = -ERANGE;
1479                         goto err;
1480                 }
1481
1482                 if (dev->real_num_rx_queues < peer->real_num_tx_queues) {
1483                         NL_SET_ERR_MSG_MOD(extack, "XDP expects number of rx queues not less than peer tx queues");
1484                         err = -ENOSPC;
1485                         goto err;
1486                 }
1487
1488                 if (dev->flags & IFF_UP) {
1489                         err = veth_enable_xdp(dev);
1490                         if (err) {
1491                                 NL_SET_ERR_MSG_MOD(extack, "Setup for XDP failed");
1492                                 goto err;
1493                         }
1494                 }
1495
1496                 if (!old_prog) {
1497                         peer->hw_features &= ~NETIF_F_GSO_SOFTWARE;
1498                         peer->max_mtu = max_mtu;
1499                 }
1500         }
1501
1502         if (old_prog) {
1503                 if (!prog) {
1504                         if (dev->flags & IFF_UP)
1505                                 veth_disable_xdp(dev);
1506
1507                         if (peer) {
1508                                 peer->hw_features |= NETIF_F_GSO_SOFTWARE;
1509                                 peer->max_mtu = ETH_MAX_MTU;
1510                         }
1511                 }
1512                 bpf_prog_put(old_prog);
1513         }
1514
1515         if ((!!old_prog ^ !!prog) && peer)
1516                 netdev_update_features(peer);
1517
1518         return 0;
1519 err:
1520         priv->_xdp_prog = old_prog;
1521
1522         return err;
1523 }
1524
1525 static int veth_xdp(struct net_device *dev, struct netdev_bpf *xdp)
1526 {
1527         switch (xdp->command) {
1528         case XDP_SETUP_PROG:
1529                 return veth_xdp_set(dev, xdp->prog, xdp->extack);
1530         default:
1531                 return -EINVAL;
1532         }
1533 }
1534
1535 static const struct net_device_ops veth_netdev_ops = {
1536         .ndo_init            = veth_dev_init,
1537         .ndo_open            = veth_open,
1538         .ndo_stop            = veth_close,
1539         .ndo_start_xmit      = veth_xmit,
1540         .ndo_get_stats64     = veth_get_stats64,
1541         .ndo_set_rx_mode     = veth_set_multicast_list,
1542         .ndo_set_mac_address = eth_mac_addr,
1543 #ifdef CONFIG_NET_POLL_CONTROLLER
1544         .ndo_poll_controller    = veth_poll_controller,
1545 #endif
1546         .ndo_get_iflink         = veth_get_iflink,
1547         .ndo_fix_features       = veth_fix_features,
1548         .ndo_set_features       = veth_set_features,
1549         .ndo_features_check     = passthru_features_check,
1550         .ndo_set_rx_headroom    = veth_set_rx_headroom,
1551         .ndo_bpf                = veth_xdp,
1552         .ndo_xdp_xmit           = veth_ndo_xdp_xmit,
1553         .ndo_get_peer_dev       = veth_peer_dev,
1554 };
1555
1556 #define VETH_FEATURES (NETIF_F_SG | NETIF_F_FRAGLIST | NETIF_F_HW_CSUM | \
1557                        NETIF_F_RXCSUM | NETIF_F_SCTP_CRC | NETIF_F_HIGHDMA | \
1558                        NETIF_F_GSO_SOFTWARE | NETIF_F_GSO_ENCAP_ALL | \
1559                        NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX | \
1560                        NETIF_F_HW_VLAN_STAG_TX | NETIF_F_HW_VLAN_STAG_RX )
1561
1562 static void veth_setup(struct net_device *dev)
1563 {
1564         ether_setup(dev);
1565
1566         dev->priv_flags &= ~IFF_TX_SKB_SHARING;
1567         dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
1568         dev->priv_flags |= IFF_NO_QUEUE;
1569         dev->priv_flags |= IFF_PHONY_HEADROOM;
1570
1571         dev->netdev_ops = &veth_netdev_ops;
1572         dev->ethtool_ops = &veth_ethtool_ops;
1573         dev->features |= NETIF_F_LLTX;
1574         dev->features |= VETH_FEATURES;
1575         dev->vlan_features = dev->features &
1576                              ~(NETIF_F_HW_VLAN_CTAG_TX |
1577                                NETIF_F_HW_VLAN_STAG_TX |
1578                                NETIF_F_HW_VLAN_CTAG_RX |
1579                                NETIF_F_HW_VLAN_STAG_RX);
1580         dev->needs_free_netdev = true;
1581         dev->priv_destructor = veth_dev_free;
1582         dev->max_mtu = ETH_MAX_MTU;
1583
1584         dev->hw_features = VETH_FEATURES;
1585         dev->hw_enc_features = VETH_FEATURES;
1586         dev->mpls_features = NETIF_F_HW_CSUM | NETIF_F_GSO_SOFTWARE;
1587 }
1588
1589 /*
1590  * netlink interface
1591  */
1592
1593 static int veth_validate(struct nlattr *tb[], struct nlattr *data[],
1594                          struct netlink_ext_ack *extack)
1595 {
1596         if (tb[IFLA_ADDRESS]) {
1597                 if (nla_len(tb[IFLA_ADDRESS]) != ETH_ALEN)
1598                         return -EINVAL;
1599                 if (!is_valid_ether_addr(nla_data(tb[IFLA_ADDRESS])))
1600                         return -EADDRNOTAVAIL;
1601         }
1602         if (tb[IFLA_MTU]) {
1603                 if (!is_valid_veth_mtu(nla_get_u32(tb[IFLA_MTU])))
1604                         return -EINVAL;
1605         }
1606         return 0;
1607 }
1608
1609 static struct rtnl_link_ops veth_link_ops;
1610
1611 static void veth_disable_gro(struct net_device *dev)
1612 {
1613         dev->features &= ~NETIF_F_GRO;
1614         dev->wanted_features &= ~NETIF_F_GRO;
1615         netdev_update_features(dev);
1616 }
1617
1618 static int veth_init_queues(struct net_device *dev, struct nlattr *tb[])
1619 {
1620         int err;
1621
1622         if (!tb[IFLA_NUM_TX_QUEUES] && dev->num_tx_queues > 1) {
1623                 err = netif_set_real_num_tx_queues(dev, 1);
1624                 if (err)
1625                         return err;
1626         }
1627         if (!tb[IFLA_NUM_RX_QUEUES] && dev->num_rx_queues > 1) {
1628                 err = netif_set_real_num_rx_queues(dev, 1);
1629                 if (err)
1630                         return err;
1631         }
1632         return 0;
1633 }
1634
1635 static int veth_newlink(struct net *src_net, struct net_device *dev,
1636                         struct nlattr *tb[], struct nlattr *data[],
1637                         struct netlink_ext_ack *extack)
1638 {
1639         int err;
1640         struct net_device *peer;
1641         struct veth_priv *priv;
1642         char ifname[IFNAMSIZ];
1643         struct nlattr *peer_tb[IFLA_MAX + 1], **tbp;
1644         unsigned char name_assign_type;
1645         struct ifinfomsg *ifmp;
1646         struct net *net;
1647
1648         /*
1649          * create and register peer first
1650          */
1651         if (data != NULL && data[VETH_INFO_PEER] != NULL) {
1652                 struct nlattr *nla_peer;
1653
1654                 nla_peer = data[VETH_INFO_PEER];
1655                 ifmp = nla_data(nla_peer);
1656                 err = rtnl_nla_parse_ifla(peer_tb,
1657                                           nla_data(nla_peer) + sizeof(struct ifinfomsg),
1658                                           nla_len(nla_peer) - sizeof(struct ifinfomsg),
1659                                           NULL);
1660                 if (err < 0)
1661                         return err;
1662
1663                 err = veth_validate(peer_tb, NULL, extack);
1664                 if (err < 0)
1665                         return err;
1666
1667                 tbp = peer_tb;
1668         } else {
1669                 ifmp = NULL;
1670                 tbp = tb;
1671         }
1672
1673         if (ifmp && tbp[IFLA_IFNAME]) {
1674                 nla_strscpy(ifname, tbp[IFLA_IFNAME], IFNAMSIZ);
1675                 name_assign_type = NET_NAME_USER;
1676         } else {
1677                 snprintf(ifname, IFNAMSIZ, DRV_NAME "%%d");
1678                 name_assign_type = NET_NAME_ENUM;
1679         }
1680
1681         net = rtnl_link_get_net(src_net, tbp);
1682         if (IS_ERR(net))
1683                 return PTR_ERR(net);
1684
1685         peer = rtnl_create_link(net, ifname, name_assign_type,
1686                                 &veth_link_ops, tbp, extack);
1687         if (IS_ERR(peer)) {
1688                 put_net(net);
1689                 return PTR_ERR(peer);
1690         }
1691
1692         if (!ifmp || !tbp[IFLA_ADDRESS])
1693                 eth_hw_addr_random(peer);
1694
1695         if (ifmp && (dev->ifindex != 0))
1696                 peer->ifindex = ifmp->ifi_index;
1697
1698         peer->gso_max_size = dev->gso_max_size;
1699         peer->gso_max_segs = dev->gso_max_segs;
1700
1701         err = register_netdevice(peer);
1702         put_net(net);
1703         net = NULL;
1704         if (err < 0)
1705                 goto err_register_peer;
1706
1707         /* keep GRO disabled by default to be consistent with the established
1708          * veth behavior
1709          */
1710         veth_disable_gro(peer);
1711         netif_carrier_off(peer);
1712
1713         err = rtnl_configure_link(peer, ifmp);
1714         if (err < 0)
1715                 goto err_configure_peer;
1716
1717         /*
1718          * register dev last
1719          *
1720          * note, that since we've registered new device the dev's name
1721          * should be re-allocated
1722          */
1723
1724         if (tb[IFLA_ADDRESS] == NULL)
1725                 eth_hw_addr_random(dev);
1726
1727         if (tb[IFLA_IFNAME])
1728                 nla_strscpy(dev->name, tb[IFLA_IFNAME], IFNAMSIZ);
1729         else
1730                 snprintf(dev->name, IFNAMSIZ, DRV_NAME "%%d");
1731
1732         err = register_netdevice(dev);
1733         if (err < 0)
1734                 goto err_register_dev;
1735
1736         netif_carrier_off(dev);
1737
1738         /*
1739          * tie the deviced together
1740          */
1741
1742         priv = netdev_priv(dev);
1743         rcu_assign_pointer(priv->peer, peer);
1744         err = veth_init_queues(dev, tb);
1745         if (err)
1746                 goto err_queues;
1747
1748         priv = netdev_priv(peer);
1749         rcu_assign_pointer(priv->peer, dev);
1750         err = veth_init_queues(peer, tb);
1751         if (err)
1752                 goto err_queues;
1753
1754         veth_disable_gro(dev);
1755         return 0;
1756
1757 err_queues:
1758         unregister_netdevice(dev);
1759 err_register_dev:
1760         /* nothing to do */
1761 err_configure_peer:
1762         unregister_netdevice(peer);
1763         return err;
1764
1765 err_register_peer:
1766         free_netdev(peer);
1767         return err;
1768 }
1769
1770 static void veth_dellink(struct net_device *dev, struct list_head *head)
1771 {
1772         struct veth_priv *priv;
1773         struct net_device *peer;
1774
1775         priv = netdev_priv(dev);
1776         peer = rtnl_dereference(priv->peer);
1777
1778         /* Note : dellink() is called from default_device_exit_batch(),
1779          * before a rcu_synchronize() point. The devices are guaranteed
1780          * not being freed before one RCU grace period.
1781          */
1782         RCU_INIT_POINTER(priv->peer, NULL);
1783         unregister_netdevice_queue(dev, head);
1784
1785         if (peer) {
1786                 priv = netdev_priv(peer);
1787                 RCU_INIT_POINTER(priv->peer, NULL);
1788                 unregister_netdevice_queue(peer, head);
1789         }
1790 }
1791
1792 static const struct nla_policy veth_policy[VETH_INFO_MAX + 1] = {
1793         [VETH_INFO_PEER]        = { .len = sizeof(struct ifinfomsg) },
1794 };
1795
1796 static struct net *veth_get_link_net(const struct net_device *dev)
1797 {
1798         struct veth_priv *priv = netdev_priv(dev);
1799         struct net_device *peer = rtnl_dereference(priv->peer);
1800
1801         return peer ? dev_net(peer) : dev_net(dev);
1802 }
1803
1804 static unsigned int veth_get_num_queues(void)
1805 {
1806         /* enforce the same queue limit as rtnl_create_link */
1807         int queues = num_possible_cpus();
1808
1809         if (queues > 4096)
1810                 queues = 4096;
1811         return queues;
1812 }
1813
1814 static struct rtnl_link_ops veth_link_ops = {
1815         .kind           = DRV_NAME,
1816         .priv_size      = sizeof(struct veth_priv),
1817         .setup          = veth_setup,
1818         .validate       = veth_validate,
1819         .newlink        = veth_newlink,
1820         .dellink        = veth_dellink,
1821         .policy         = veth_policy,
1822         .maxtype        = VETH_INFO_MAX,
1823         .get_link_net   = veth_get_link_net,
1824         .get_num_tx_queues      = veth_get_num_queues,
1825         .get_num_rx_queues      = veth_get_num_queues,
1826 };
1827
1828 /*
1829  * init/fini
1830  */
1831
1832 static __init int veth_init(void)
1833 {
1834         return rtnl_link_register(&veth_link_ops);
1835 }
1836
1837 static __exit void veth_exit(void)
1838 {
1839         rtnl_link_unregister(&veth_link_ops);
1840 }
1841
1842 module_init(veth_init);
1843 module_exit(veth_exit);
1844
1845 MODULE_DESCRIPTION("Virtual Ethernet Tunnel");
1846 MODULE_LICENSE("GPL v2");
1847 MODULE_ALIAS_RTNL_LINK(DRV_NAME);