1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * INET An implementation of the TCP/IP protocol suite for the LINUX
4 * operating system. INET is implemented using the BSD Socket
5 * interface as the means of communication with the user level.
6 *
7 * PACKET - implements raw packet sockets.
8 *
9 * Authors: Ross Biro
10 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
11 * Alan Cox, <gw4pts@gw4pts.ampr.org>
12 *
13 * Fixes:
14 * Alan Cox : verify_area() now used correctly
15 * Alan Cox : new skbuff lists, look ma no backlogs!
16 * Alan Cox : tidied skbuff lists.
17 * Alan Cox : Now uses generic datagram routines I
18 * added. Also fixed the peek/read crash
19 * from all old Linux datagram code.
20 * Alan Cox : Uses the improved datagram code.
21 * Alan Cox : Added NULL's for socket options.
22 * Alan Cox : Re-commented the code.
23 * Alan Cox : Use new kernel side addressing
24 * Rob Janssen : Correct MTU usage.
25 * Dave Platt : Counter leaks caused by incorrect
26 * interrupt locking and some slightly
27 * dubious gcc output. Can you read
28 * compiler: it said _VOLATILE_
29 * Richard Kooijman : Timestamp fixes.
30 * Alan Cox : New buffers. Use sk->mac.raw.
31 * Alan Cox : sendmsg/recvmsg support.
32 * Alan Cox : Protocol setting support
33 * Alexey Kuznetsov : Untied from IPv4 stack.
34 * Cyrus Durgin : Fixed kerneld for kmod.
35 * Michal Ostrowski : Module initialization cleanup.
36 * Ulises Alonso : Frame number limit removal and
37 * packet_set_ring memory leak.
38 * Eric Biederman : Allow for > 8 byte hardware addresses.
39 * The convention is that longer addresses
40 * will simply extend the hardware address
41 * byte arrays at the end of sockaddr_ll
42 * and packet_mreq.
43 * Johann Baudy : Added TX RING.
44 * Chetan Loke : Implemented TPACKET_V3 block abstraction
45 * layer.
46 * Copyright (C) 2011, <lokec@ccs.neu.edu>
47 */
48
49 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
50
51 #include <linux/ethtool.h>
52 #include <linux/filter.h>
53 #include <linux/types.h>
54 #include <linux/mm.h>
55 #include <linux/capability.h>
56 #include <linux/fcntl.h>
57 #include <linux/socket.h>
58 #include <linux/in.h>
59 #include <linux/inet.h>
60 #include <linux/netdevice.h>
61 #include <linux/if_packet.h>
62 #include <linux/wireless.h>
63 #include <linux/kernel.h>
64 #include <linux/kmod.h>
65 #include <linux/slab.h>
66 #include <linux/vmalloc.h>
67 #include <net/net_namespace.h>
68 #include <net/ip.h>
69 #include <net/protocol.h>
70 #include <linux/skbuff.h>
71 #include <net/sock.h>
72 #include <linux/errno.h>
73 #include <linux/timer.h>
74 #include <linux/uaccess.h>
75 #include <asm/ioctls.h>
76 #include <asm/page.h>
77 #include <asm/cacheflush.h>
78 #include <asm/io.h>
79 #include <linux/proc_fs.h>
80 #include <linux/seq_file.h>
81 #include <linux/poll.h>
82 #include <linux/module.h>
83 #include <linux/init.h>
84 #include <linux/mutex.h>
85 #include <linux/if_vlan.h>
86 #include <linux/virtio_net.h>
87 #include <linux/errqueue.h>
88 #include <linux/net_tstamp.h>
89 #include <linux/percpu.h>
90 #ifdef CONFIG_INET
91 #include <net/inet_common.h>
92 #endif
93 #include <linux/bpf.h>
94 #include <net/compat.h>
95 #include <linux/netfilter_netdev.h>
96
97 #include "internal.h"
98
99 /*
100 Assumptions:
101 - If the device has no dev->header_ops->create, there is no LL header
102 visible above the device. In this case, its hard_header_len should be 0.
103 The device may prepend its own header internally. In this case, its
104 needed_headroom should be set to the space needed for it to add its
105 internal header.
106 For example, a WiFi driver pretending to be an Ethernet driver should
107 set its hard_header_len to be the Ethernet header length, and set its
108 needed_headroom to be (the real WiFi header length - the fake Ethernet
109 header length).
110 - packet socket receives packets with pulled ll header,
111 so that SOCK_RAW should push it back.
112
113 On receive:
114 -----------
115
116 Incoming, dev_has_header(dev) == true
117 mac_header -> ll header
118 data -> data
119
120 Outgoing, dev_has_header(dev) == true
121 mac_header -> ll header
122 data -> ll header
123
124 Incoming, dev_has_header(dev) == false
125 mac_header -> data
126 However drivers often make it point to the ll header.
127 This is incorrect because the ll header should be invisible to us.
128 data -> data
129
130 Outgoing, dev_has_header(dev) == false
131 mac_header -> data. ll header is invisible to us.
132 data -> data
133
134 Resume
135 If dev_has_header(dev) == false we are unable to restore the ll header,
136 because it is invisible to us.
137
138
139 On transmit:
140 ------------
141
142 dev_has_header(dev) == true
143 mac_header -> ll header
144 data -> ll header
145
146 dev_has_header(dev) == false (ll header is invisible to us)
147 mac_header -> data
148 data -> data
149
150 We should set network_header on output to the correct position,
151 packet classifier depends on it.
152 */
153
154 /* Private packet socket structures. */
155
156 /* identical to struct packet_mreq except it has
157 * a longer address field.
158 */
159 struct packet_mreq_max {
160 int mr_ifindex;
161 unsigned short mr_type;
162 unsigned short mr_alen;
163 unsigned char mr_address[MAX_ADDR_LEN];
164 };
165
166 union tpacket_uhdr {
167 struct tpacket_hdr *h1;
168 struct tpacket2_hdr *h2;
169 struct tpacket3_hdr *h3;
170 void *raw;
171 };
172
173 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
174 int closing, int tx_ring);
175
176 #define V3_ALIGNMENT (8)
177
178 #define BLK_HDR_LEN (ALIGN(sizeof(struct tpacket_block_desc), V3_ALIGNMENT))
179
180 #define BLK_PLUS_PRIV(sz_of_priv) \
181 (BLK_HDR_LEN + ALIGN((sz_of_priv), V3_ALIGNMENT))
182
183 #define BLOCK_STATUS(x) ((x)->hdr.bh1.block_status)
184 #define BLOCK_NUM_PKTS(x) ((x)->hdr.bh1.num_pkts)
185 #define BLOCK_O2FP(x) ((x)->hdr.bh1.offset_to_first_pkt)
186 #define BLOCK_LEN(x) ((x)->hdr.bh1.blk_len)
187 #define BLOCK_SNUM(x) ((x)->hdr.bh1.seq_num)
188 #define BLOCK_O2PRIV(x) ((x)->offset_to_priv)
189
190 struct packet_sock;
191 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
192 struct packet_type *pt, struct net_device *orig_dev);
193
194 static void *packet_previous_frame(struct packet_sock *po,
195 struct packet_ring_buffer *rb,
196 int status);
197 static void packet_increment_head(struct packet_ring_buffer *buff);
198 static int prb_curr_blk_in_use(struct tpacket_block_desc *);
199 static void *prb_dispatch_next_block(struct tpacket_kbdq_core *,
200 struct packet_sock *);
201 static void prb_retire_current_block(struct tpacket_kbdq_core *,
202 struct packet_sock *, unsigned int status);
203 static int prb_queue_frozen(struct tpacket_kbdq_core *);
204 static void prb_open_block(struct tpacket_kbdq_core *,
205 struct tpacket_block_desc *);
206 static enum hrtimer_restart prb_retire_rx_blk_timer_expired(struct hrtimer *);
207 static void prb_fill_rxhash(struct tpacket_kbdq_core *, struct tpacket3_hdr *);
208 static void prb_clear_rxhash(struct tpacket_kbdq_core *,
209 struct tpacket3_hdr *);
210 static void prb_fill_vlan_info(struct tpacket_kbdq_core *,
211 struct tpacket3_hdr *);
212 static void packet_flush_mclist(struct sock *sk);
213 static u16 packet_pick_tx_queue(struct sk_buff *skb);
214
215 struct packet_skb_cb {
216 union {
217 struct sockaddr_pkt pkt;
218 union {
219 /* Trick: alias skb original length with
220 * ll.sll_family and ll.protocol in order
221 * to save room.
222 */
223 unsigned int origlen;
224 struct sockaddr_ll ll;
225 };
226 } sa;
227 };
228
229 #define vio_le() virtio_legacy_is_little_endian()
230
231 #define PACKET_SKB_CB(__skb) ((struct packet_skb_cb *)((__skb)->cb))
232
233 #define GET_PBDQC_FROM_RB(x) ((struct tpacket_kbdq_core *)(&(x)->prb_bdqc))
234 #define GET_PBLOCK_DESC(x, bid) \
235 ((struct tpacket_block_desc *)((x)->pkbdq[(bid)].buffer))
236 #define GET_CURR_PBLOCK_DESC_FROM_CORE(x) \
237 ((struct tpacket_block_desc *)((x)->pkbdq[(x)->kactive_blk_num].buffer))
238 #define GET_NEXT_PRB_BLK_NUM(x) \
239 (((x)->kactive_blk_num < ((x)->knum_blocks-1)) ? \
240 ((x)->kactive_blk_num+1) : 0)
241
242 static void __fanout_unlink(struct sock *sk, struct packet_sock *po);
243 static void __fanout_link(struct sock *sk, struct packet_sock *po);
244
245 #ifdef CONFIG_NETFILTER_EGRESS
nf_hook_direct_egress(struct sk_buff * skb)246 static noinline struct sk_buff *nf_hook_direct_egress(struct sk_buff *skb)
247 {
248 struct sk_buff *next, *head = NULL, *tail;
249 int rc;
250
251 rcu_read_lock();
252 for (; skb != NULL; skb = next) {
253 next = skb->next;
254 skb_mark_not_on_list(skb);
255
256 if (!nf_hook_egress(skb, &rc, skb->dev))
257 continue;
258
259 if (!head)
260 head = skb;
261 else
262 tail->next = skb;
263
264 tail = skb;
265 }
266 rcu_read_unlock();
267
268 return head;
269 }
270 #endif
271
packet_xmit(const struct packet_sock * po,struct sk_buff * skb)272 static int packet_xmit(const struct packet_sock *po, struct sk_buff *skb)
273 {
274 if (!packet_sock_flag(po, PACKET_SOCK_QDISC_BYPASS))
275 return dev_queue_xmit(skb);
276
277 #ifdef CONFIG_NETFILTER_EGRESS
278 if (nf_hook_egress_active()) {
279 skb = nf_hook_direct_egress(skb);
280 if (!skb)
281 return NET_XMIT_DROP;
282 }
283 #endif
284 return dev_direct_xmit(skb, packet_pick_tx_queue(skb));
285 }
286
packet_cached_dev_get(struct packet_sock * po)287 static struct net_device *packet_cached_dev_get(struct packet_sock *po)
288 {
289 struct net_device *dev;
290
291 rcu_read_lock();
292 dev = rcu_dereference(po->cached_dev);
293 dev_hold(dev);
294 rcu_read_unlock();
295
296 return dev;
297 }
298
packet_cached_dev_assign(struct packet_sock * po,struct net_device * dev)299 static void packet_cached_dev_assign(struct packet_sock *po,
300 struct net_device *dev)
301 {
302 rcu_assign_pointer(po->cached_dev, dev);
303 }
304
packet_cached_dev_reset(struct packet_sock * po)305 static void packet_cached_dev_reset(struct packet_sock *po)
306 {
307 RCU_INIT_POINTER(po->cached_dev, NULL);
308 }
309
packet_pick_tx_queue(struct sk_buff * skb)310 static u16 packet_pick_tx_queue(struct sk_buff *skb)
311 {
312 struct net_device *dev = skb->dev;
313 const struct net_device_ops *ops = dev->netdev_ops;
314 int cpu = raw_smp_processor_id();
315 u16 queue_index;
316
317 #ifdef CONFIG_XPS
318 skb->sender_cpu = cpu + 1;
319 #endif
320 skb_record_rx_queue(skb, cpu % dev->real_num_tx_queues);
321 if (ops->ndo_select_queue) {
322 queue_index = ops->ndo_select_queue(dev, skb, NULL);
323 queue_index = netdev_cap_txqueue(dev, queue_index);
324 } else {
325 queue_index = netdev_pick_tx(dev, skb, NULL);
326 }
327
328 return queue_index;
329 }
330
331 /* __register_prot_hook must be invoked through register_prot_hook
332 * or from a context in which asynchronous accesses to the packet
333 * socket is not possible (packet_create()).
334 */
__register_prot_hook(struct sock * sk)335 static void __register_prot_hook(struct sock *sk)
336 {
337 struct packet_sock *po = pkt_sk(sk);
338
339 if (!packet_sock_flag(po, PACKET_SOCK_RUNNING)) {
340 if (po->fanout)
341 __fanout_link(sk, po);
342 else
343 dev_add_pack(&po->prot_hook);
344
345 sock_hold(sk);
346 packet_sock_flag_set(po, PACKET_SOCK_RUNNING, 1);
347 }
348 }
349
register_prot_hook(struct sock * sk)350 static void register_prot_hook(struct sock *sk)
351 {
352 lockdep_assert_held_once(&pkt_sk(sk)->bind_lock);
353 __register_prot_hook(sk);
354 }
355
356 /* If the sync parameter is true, we will temporarily drop
357 * the po->bind_lock and do a synchronize_net to make sure no
358 * asynchronous packet processing paths still refer to the elements
359 * of po->prot_hook. If the sync parameter is false, it is the
360 * callers responsibility to take care of this.
361 */
__unregister_prot_hook(struct sock * sk,bool sync)362 static void __unregister_prot_hook(struct sock *sk, bool sync)
363 {
364 struct packet_sock *po = pkt_sk(sk);
365
366 lockdep_assert_held_once(&po->bind_lock);
367
368 packet_sock_flag_set(po, PACKET_SOCK_RUNNING, 0);
369
370 if (po->fanout)
371 __fanout_unlink(sk, po);
372 else
373 __dev_remove_pack(&po->prot_hook);
374
375 __sock_put(sk);
376
377 if (sync) {
378 spin_unlock(&po->bind_lock);
379 synchronize_net();
380 spin_lock(&po->bind_lock);
381 }
382 }
383
unregister_prot_hook(struct sock * sk,bool sync)384 static void unregister_prot_hook(struct sock *sk, bool sync)
385 {
386 struct packet_sock *po = pkt_sk(sk);
387
388 if (packet_sock_flag(po, PACKET_SOCK_RUNNING))
389 __unregister_prot_hook(sk, sync);
390 }
391
pgv_to_page(void * addr)392 static inline struct page * __pure pgv_to_page(void *addr)
393 {
394 if (is_vmalloc_addr(addr))
395 return vmalloc_to_page(addr);
396 return virt_to_page(addr);
397 }
398
__packet_set_status(struct packet_sock * po,void * frame,int status)399 static void __packet_set_status(struct packet_sock *po, void *frame, int status)
400 {
401 union tpacket_uhdr h;
402
403 /* WRITE_ONCE() are paired with READ_ONCE() in __packet_get_status */
404
405 h.raw = frame;
406 switch (po->tp_version) {
407 case TPACKET_V1:
408 WRITE_ONCE(h.h1->tp_status, status);
409 flush_dcache_page(pgv_to_page(&h.h1->tp_status));
410 break;
411 case TPACKET_V2:
412 WRITE_ONCE(h.h2->tp_status, status);
413 flush_dcache_page(pgv_to_page(&h.h2->tp_status));
414 break;
415 case TPACKET_V3:
416 WRITE_ONCE(h.h3->tp_status, status);
417 flush_dcache_page(pgv_to_page(&h.h3->tp_status));
418 break;
419 default:
420 WARN(1, "TPACKET version not supported.\n");
421 BUG();
422 }
423
424 smp_wmb();
425 }
426
__packet_get_status(const struct packet_sock * po,void * frame)427 static int __packet_get_status(const struct packet_sock *po, void *frame)
428 {
429 union tpacket_uhdr h;
430
431 smp_rmb();
432
433 /* READ_ONCE() are paired with WRITE_ONCE() in __packet_set_status */
434
435 h.raw = frame;
436 switch (po->tp_version) {
437 case TPACKET_V1:
438 flush_dcache_page(pgv_to_page(&h.h1->tp_status));
439 return READ_ONCE(h.h1->tp_status);
440 case TPACKET_V2:
441 flush_dcache_page(pgv_to_page(&h.h2->tp_status));
442 return READ_ONCE(h.h2->tp_status);
443 case TPACKET_V3:
444 flush_dcache_page(pgv_to_page(&h.h3->tp_status));
445 return READ_ONCE(h.h3->tp_status);
446 default:
447 WARN(1, "TPACKET version not supported.\n");
448 BUG();
449 return 0;
450 }
451 }
452
tpacket_get_timestamp(struct sk_buff * skb,struct timespec64 * ts,unsigned int flags)453 static __u32 tpacket_get_timestamp(struct sk_buff *skb, struct timespec64 *ts,
454 unsigned int flags)
455 {
456 struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
457
458 if (shhwtstamps &&
459 (flags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
460 ktime_to_timespec64_cond(shhwtstamps->hwtstamp, ts))
461 return TP_STATUS_TS_RAW_HARDWARE;
462
463 if ((flags & SOF_TIMESTAMPING_SOFTWARE) &&
464 ktime_to_timespec64_cond(skb_tstamp(skb), ts))
465 return TP_STATUS_TS_SOFTWARE;
466
467 return 0;
468 }
469
__packet_set_timestamp(struct packet_sock * po,void * frame,struct sk_buff * skb)470 static __u32 __packet_set_timestamp(struct packet_sock *po, void *frame,
471 struct sk_buff *skb)
472 {
473 union tpacket_uhdr h;
474 struct timespec64 ts;
475 __u32 ts_status;
476
477 if (!(ts_status = tpacket_get_timestamp(skb, &ts, READ_ONCE(po->tp_tstamp))))
478 return 0;
479
480 h.raw = frame;
481 /*
482 * versions 1 through 3 overflow the timestamps in y2106, since they
483 * all store the seconds in a 32-bit unsigned integer.
484 * If we create a version 4, that should have a 64-bit timestamp,
485 * either 64-bit seconds + 32-bit nanoseconds, or just 64-bit
486 * nanoseconds.
487 */
488 switch (po->tp_version) {
489 case TPACKET_V1:
490 h.h1->tp_sec = ts.tv_sec;
491 h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
492 break;
493 case TPACKET_V2:
494 h.h2->tp_sec = ts.tv_sec;
495 h.h2->tp_nsec = ts.tv_nsec;
496 break;
497 case TPACKET_V3:
498 h.h3->tp_sec = ts.tv_sec;
499 h.h3->tp_nsec = ts.tv_nsec;
500 break;
501 default:
502 WARN(1, "TPACKET version not supported.\n");
503 BUG();
504 }
505
506 /* one flush is safe, as both fields always lie on the same cacheline */
507 flush_dcache_page(pgv_to_page(&h.h1->tp_sec));
508 smp_wmb();
509
510 return ts_status;
511 }
512
packet_lookup_frame(const struct packet_sock * po,const struct packet_ring_buffer * rb,unsigned int position,int status)513 static void *packet_lookup_frame(const struct packet_sock *po,
514 const struct packet_ring_buffer *rb,
515 unsigned int position,
516 int status)
517 {
518 unsigned int pg_vec_pos, frame_offset;
519 union tpacket_uhdr h;
520
521 pg_vec_pos = position / rb->frames_per_block;
522 frame_offset = position % rb->frames_per_block;
523
524 h.raw = rb->pg_vec[pg_vec_pos].buffer +
525 (frame_offset * rb->frame_size);
526
527 if (status != __packet_get_status(po, h.raw))
528 return NULL;
529
530 return h.raw;
531 }
532
packet_current_frame(struct packet_sock * po,struct packet_ring_buffer * rb,int status)533 static void *packet_current_frame(struct packet_sock *po,
534 struct packet_ring_buffer *rb,
535 int status)
536 {
537 return packet_lookup_frame(po, rb, rb->head, status);
538 }
539
vlan_get_tci(const struct sk_buff * skb,struct net_device * dev)540 static u16 vlan_get_tci(const struct sk_buff *skb, struct net_device *dev)
541 {
542 struct vlan_hdr vhdr, *vh;
543 unsigned int header_len;
544
545 if (!dev)
546 return 0;
547
548 /* In the SOCK_DGRAM scenario, skb data starts at the network
549 * protocol, which is after the VLAN headers. The outer VLAN
550 * header is at the hard_header_len offset in non-variable
551 * length link layer headers. If it's a VLAN device, the
552 * min_header_len should be used to exclude the VLAN header
553 * size.
554 */
555 if (dev->min_header_len == dev->hard_header_len)
556 header_len = dev->hard_header_len;
557 else if (is_vlan_dev(dev))
558 header_len = dev->min_header_len;
559 else
560 return 0;
561
562 vh = skb_header_pointer(skb, skb_mac_offset(skb) + header_len,
563 sizeof(vhdr), &vhdr);
564 if (unlikely(!vh))
565 return 0;
566
567 return ntohs(vh->h_vlan_TCI);
568 }
569
vlan_get_protocol_dgram(const struct sk_buff * skb)570 static __be16 vlan_get_protocol_dgram(const struct sk_buff *skb)
571 {
572 __be16 proto = skb->protocol;
573
574 if (unlikely(eth_type_vlan(proto)))
575 proto = vlan_get_protocol_offset_inline(skb, proto,
576 skb_mac_offset(skb),
577 NULL);
578
579 return proto;
580 }
581
prb_shutdown_retire_blk_timer(struct packet_sock * po,struct sk_buff_head * rb_queue)582 static void prb_shutdown_retire_blk_timer(struct packet_sock *po,
583 struct sk_buff_head *rb_queue)
584 {
585 struct tpacket_kbdq_core *pkc;
586
587 pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
588 hrtimer_cancel(&pkc->retire_blk_timer);
589 }
590
prb_calc_retire_blk_tmo(struct packet_sock * po,int blk_size_in_bytes)591 static int prb_calc_retire_blk_tmo(struct packet_sock *po,
592 int blk_size_in_bytes)
593 {
594 struct net_device *dev;
595 unsigned int mbits, div;
596 struct ethtool_link_ksettings ecmd;
597 int err;
598
599 rtnl_lock();
600 dev = __dev_get_by_index(sock_net(&po->sk), po->ifindex);
601 if (unlikely(!dev)) {
602 rtnl_unlock();
603 return DEFAULT_PRB_RETIRE_TOV;
604 }
605 err = __ethtool_get_link_ksettings(dev, &ecmd);
606 rtnl_unlock();
607 if (err)
608 return DEFAULT_PRB_RETIRE_TOV;
609
610 /* If the link speed is so slow you don't really
611 * need to worry about perf anyways
612 */
613 if (ecmd.base.speed < SPEED_1000 ||
614 ecmd.base.speed == SPEED_UNKNOWN)
615 return DEFAULT_PRB_RETIRE_TOV;
616
617 div = ecmd.base.speed / 1000;
618 mbits = (blk_size_in_bytes * 8) / (1024 * 1024);
619
620 if (div)
621 mbits /= div;
622
623 if (div)
624 return mbits + 1;
625 return mbits;
626 }
627
prb_init_ft_ops(struct tpacket_kbdq_core * p1,union tpacket_req_u * req_u)628 static void prb_init_ft_ops(struct tpacket_kbdq_core *p1,
629 union tpacket_req_u *req_u)
630 {
631 p1->feature_req_word = req_u->req3.tp_feature_req_word;
632 }
633
init_prb_bdqc(struct packet_sock * po,struct packet_ring_buffer * rb,struct pgv * pg_vec,union tpacket_req_u * req_u)634 static void init_prb_bdqc(struct packet_sock *po,
635 struct packet_ring_buffer *rb,
636 struct pgv *pg_vec,
637 union tpacket_req_u *req_u)
638 {
639 struct tpacket_kbdq_core *p1 = GET_PBDQC_FROM_RB(rb);
640 struct tpacket_block_desc *pbd;
641
642 memset(p1, 0x0, sizeof(*p1));
643
644 p1->knxt_seq_num = 1;
645 p1->pkbdq = pg_vec;
646 pbd = (struct tpacket_block_desc *)pg_vec[0].buffer;
647 p1->pkblk_start = pg_vec[0].buffer;
648 p1->kblk_size = req_u->req3.tp_block_size;
649 p1->knum_blocks = req_u->req3.tp_block_nr;
650 p1->hdrlen = po->tp_hdrlen;
651 p1->version = po->tp_version;
652 po->stats.stats3.tp_freeze_q_cnt = 0;
653 if (req_u->req3.tp_retire_blk_tov)
654 p1->interval_ktime = ms_to_ktime(req_u->req3.tp_retire_blk_tov);
655 else
656 p1->interval_ktime = ms_to_ktime(prb_calc_retire_blk_tmo(po,
657 req_u->req3.tp_block_size));
658 p1->blk_sizeof_priv = req_u->req3.tp_sizeof_priv;
659 rwlock_init(&p1->blk_fill_in_prog_lock);
660
661 p1->max_frame_len = p1->kblk_size - BLK_PLUS_PRIV(p1->blk_sizeof_priv);
662 prb_init_ft_ops(p1, req_u);
663 hrtimer_setup(&p1->retire_blk_timer, prb_retire_rx_blk_timer_expired,
664 CLOCK_MONOTONIC, HRTIMER_MODE_REL_SOFT);
665 hrtimer_start(&p1->retire_blk_timer, p1->interval_ktime,
666 HRTIMER_MODE_REL_SOFT);
667 prb_open_block(p1, pbd);
668 }
669
670 /*
671 * With a 1MB block-size, on a 1Gbps line, it will take
672 * i) ~8 ms to fill a block + ii) memcpy etc.
673 * In this cut we are not accounting for the memcpy time.
674 *
675 * Since the tmo granularity is in msecs, it is not too expensive
676 * to refresh the timer, lets say every '8' msecs.
677 * Either the user can set the 'tmo' or we can derive it based on
678 * a) line-speed and b) block-size.
679 * prb_calc_retire_blk_tmo() calculates the tmo.
680 */
prb_retire_rx_blk_timer_expired(struct hrtimer * t)681 static enum hrtimer_restart prb_retire_rx_blk_timer_expired(struct hrtimer *t)
682 {
683 struct packet_sock *po =
684 timer_container_of(po, t, rx_ring.prb_bdqc.retire_blk_timer);
685 struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
686 unsigned int frozen;
687 struct tpacket_block_desc *pbd;
688
689 spin_lock(&po->sk.sk_receive_queue.lock);
690
691 frozen = prb_queue_frozen(pkc);
692 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
693
694 /* We only need to plug the race when the block is partially filled.
695 * tpacket_rcv:
696 * lock(); increment BLOCK_NUM_PKTS; unlock()
697 * copy_bits() is in progress ...
698 * timer fires on other cpu:
699 * we can't retire the current block because copy_bits
700 * is in progress.
701 *
702 */
703 if (BLOCK_NUM_PKTS(pbd)) {
704 /* Waiting for skb_copy_bits to finish... */
705 write_lock(&pkc->blk_fill_in_prog_lock);
706 write_unlock(&pkc->blk_fill_in_prog_lock);
707 }
708
709 if (!frozen) {
710 if (BLOCK_NUM_PKTS(pbd)) {
711 /* Not an empty block. Need retire the block. */
712 prb_retire_current_block(pkc, po, TP_STATUS_BLK_TMO);
713 prb_dispatch_next_block(pkc, po);
714 }
715 } else {
716 /* Case 1. Queue was frozen because user-space was
717 * lagging behind.
718 */
719 if (!prb_curr_blk_in_use(pbd)) {
720 /* Case 2. queue was frozen,user-space caught up,
721 * now the link went idle && the timer fired.
722 * We don't have a block to close.So we open this
723 * block and restart the timer.
724 * opening a block thaws the queue,restarts timer
725 * Thawing/timer-refresh is a side effect.
726 */
727 prb_open_block(pkc, pbd);
728 }
729 }
730
731 hrtimer_forward_now(&pkc->retire_blk_timer, pkc->interval_ktime);
732 spin_unlock(&po->sk.sk_receive_queue.lock);
733 return HRTIMER_RESTART;
734 }
735
prb_flush_block(struct tpacket_kbdq_core * pkc1,struct tpacket_block_desc * pbd1,__u32 status)736 static void prb_flush_block(struct tpacket_kbdq_core *pkc1,
737 struct tpacket_block_desc *pbd1, __u32 status)
738 {
739 /* Flush everything minus the block header */
740
741 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
742 u8 *start, *end;
743
744 start = (u8 *)pbd1;
745
746 /* Skip the block header(we know header WILL fit in 4K) */
747 start += PAGE_SIZE;
748
749 end = (u8 *)PAGE_ALIGN((unsigned long)pkc1->pkblk_end);
750 for (; start < end; start += PAGE_SIZE)
751 flush_dcache_page(pgv_to_page(start));
752
753 smp_wmb();
754 #endif
755
756 /* Now update the block status. */
757
758 BLOCK_STATUS(pbd1) = status;
759
760 /* Flush the block header */
761
762 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
763 start = (u8 *)pbd1;
764 flush_dcache_page(pgv_to_page(start));
765
766 smp_wmb();
767 #endif
768 }
769
770 /*
771 * Side effect:
772 *
773 * 1) flush the block
774 * 2) Increment active_blk_num
775 *
776 * Note:We DONT refresh the timer on purpose.
777 * Because almost always the next block will be opened.
778 */
prb_close_block(struct tpacket_kbdq_core * pkc1,struct tpacket_block_desc * pbd1,struct packet_sock * po,unsigned int stat)779 static void prb_close_block(struct tpacket_kbdq_core *pkc1,
780 struct tpacket_block_desc *pbd1,
781 struct packet_sock *po, unsigned int stat)
782 {
783 __u32 status = TP_STATUS_USER | stat;
784
785 struct tpacket3_hdr *last_pkt;
786 struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
787 struct sock *sk = &po->sk;
788
789 if (atomic_read(&po->tp_drops))
790 status |= TP_STATUS_LOSING;
791
792 last_pkt = (struct tpacket3_hdr *)pkc1->prev;
793 last_pkt->tp_next_offset = 0;
794
795 /* Get the ts of the last pkt */
796 if (BLOCK_NUM_PKTS(pbd1)) {
797 h1->ts_last_pkt.ts_sec = last_pkt->tp_sec;
798 h1->ts_last_pkt.ts_nsec = last_pkt->tp_nsec;
799 } else {
800 /* Ok, we tmo'd - so get the current time.
801 *
802 * It shouldn't really happen as we don't close empty
803 * blocks. See prb_retire_rx_blk_timer_expired().
804 */
805 struct timespec64 ts;
806 ktime_get_real_ts64(&ts);
807 h1->ts_last_pkt.ts_sec = ts.tv_sec;
808 h1->ts_last_pkt.ts_nsec = ts.tv_nsec;
809 }
810
811 smp_wmb();
812
813 /* Flush the block */
814 prb_flush_block(pkc1, pbd1, status);
815
816 sk->sk_data_ready(sk);
817
818 pkc1->kactive_blk_num = GET_NEXT_PRB_BLK_NUM(pkc1);
819 }
820
prb_thaw_queue(struct tpacket_kbdq_core * pkc)821 static void prb_thaw_queue(struct tpacket_kbdq_core *pkc)
822 {
823 pkc->reset_pending_on_curr_blk = 0;
824 }
825
826 /*
827 * prb_open_block is called by tpacket_rcv or timer callback.
828 *
829 * Reasons why NOT update hrtimer in prb_open_block:
830 * 1) It will increase complexity to distinguish the two caller scenario.
831 * 2) hrtimer_cancel and hrtimer_start need to be called if you want to update
832 * TMO of an already enqueued hrtimer, leading to complex shutdown logic.
833 *
834 * One side effect of NOT update hrtimer when called by tpacket_rcv is that
835 * a newly opened block triggered by tpacket_rcv may be retired earlier than
836 * expected. On the other hand, if timeout is updated in prb_open_block, the
837 * frequent reception of network packets that leads to prb_open_block being
838 * called may cause hrtimer to be removed and enqueued repeatedly.
839 */
prb_open_block(struct tpacket_kbdq_core * pkc1,struct tpacket_block_desc * pbd1)840 static void prb_open_block(struct tpacket_kbdq_core *pkc1,
841 struct tpacket_block_desc *pbd1)
842 {
843 struct timespec64 ts;
844 struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
845
846 smp_rmb();
847
848 /* We could have just memset this but we will lose the
849 * flexibility of making the priv area sticky
850 */
851
852 BLOCK_SNUM(pbd1) = pkc1->knxt_seq_num++;
853 BLOCK_NUM_PKTS(pbd1) = 0;
854 BLOCK_LEN(pbd1) = BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
855
856 ktime_get_real_ts64(&ts);
857
858 h1->ts_first_pkt.ts_sec = ts.tv_sec;
859 h1->ts_first_pkt.ts_nsec = ts.tv_nsec;
860
861 pkc1->pkblk_start = (char *)pbd1;
862 pkc1->nxt_offset = pkc1->pkblk_start + BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
863
864 BLOCK_O2FP(pbd1) = (__u32)BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
865 BLOCK_O2PRIV(pbd1) = BLK_HDR_LEN;
866
867 pbd1->version = pkc1->version;
868 pkc1->prev = pkc1->nxt_offset;
869 pkc1->pkblk_end = pkc1->pkblk_start + pkc1->kblk_size;
870
871 prb_thaw_queue(pkc1);
872
873 smp_wmb();
874 }
875
876 /*
877 * Queue freeze logic:
878 * 1) Assume tp_block_nr = 8 blocks.
879 * 2) At time 't0', user opens Rx ring.
880 * 3) Some time past 't0', kernel starts filling blocks starting from 0 .. 7
881 * 4) user-space is either sleeping or processing block '0'.
882 * 5) tpacket_rcv is currently filling block '7', since there is no space left,
883 * it will close block-7,loop around and try to fill block '0'.
884 * call-flow:
885 * __packet_lookup_frame_in_block
886 * prb_retire_current_block()
887 * prb_dispatch_next_block()
888 * |->(BLOCK_STATUS == USER) evaluates to true
889 * 5.1) Since block-0 is currently in-use, we just freeze the queue.
890 * 6) Now there are two cases:
891 * 6.1) Link goes idle right after the queue is frozen.
892 * But remember, the last open_block() refreshed the timer.
893 * When this timer expires,it will refresh itself so that we can
894 * re-open block-0 in near future.
895 * 6.2) Link is busy and keeps on receiving packets. This is a simple
896 * case and __packet_lookup_frame_in_block will check if block-0
897 * is free and can now be re-used.
898 */
prb_freeze_queue(struct tpacket_kbdq_core * pkc,struct packet_sock * po)899 static void prb_freeze_queue(struct tpacket_kbdq_core *pkc,
900 struct packet_sock *po)
901 {
902 pkc->reset_pending_on_curr_blk = 1;
903 po->stats.stats3.tp_freeze_q_cnt++;
904 }
905
906 #define TOTAL_PKT_LEN_INCL_ALIGN(length) (ALIGN((length), V3_ALIGNMENT))
907
908 /*
909 * If the next block is free then we will dispatch it
910 * and return a good offset.
911 * Else, we will freeze the queue.
912 * So, caller must check the return value.
913 */
prb_dispatch_next_block(struct tpacket_kbdq_core * pkc,struct packet_sock * po)914 static void *prb_dispatch_next_block(struct tpacket_kbdq_core *pkc,
915 struct packet_sock *po)
916 {
917 struct tpacket_block_desc *pbd;
918
919 smp_rmb();
920
921 /* 1. Get current block num */
922 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
923
924 /* 2. If this block is currently in_use then freeze the queue */
925 if (TP_STATUS_USER & BLOCK_STATUS(pbd)) {
926 prb_freeze_queue(pkc, po);
927 return NULL;
928 }
929
930 /*
931 * 3.
932 * open this block and return the offset where the first packet
933 * needs to get stored.
934 */
935 prb_open_block(pkc, pbd);
936 return (void *)pkc->nxt_offset;
937 }
938
prb_retire_current_block(struct tpacket_kbdq_core * pkc,struct packet_sock * po,unsigned int status)939 static void prb_retire_current_block(struct tpacket_kbdq_core *pkc,
940 struct packet_sock *po, unsigned int status)
941 {
942 struct tpacket_block_desc *pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
943
944 /* retire/close the current block */
945 if (likely(TP_STATUS_KERNEL == BLOCK_STATUS(pbd))) {
946 /*
947 * Plug the case where copy_bits() is in progress on
948 * cpu-0 and tpacket_rcv() got invoked on cpu-1, didn't
949 * have space to copy the pkt in the current block and
950 * called prb_retire_current_block()
951 *
952 * We don't need to worry about the TMO case because
953 * the timer-handler already handled this case.
954 */
955 if (!(status & TP_STATUS_BLK_TMO)) {
956 /* Waiting for skb_copy_bits to finish... */
957 write_lock(&pkc->blk_fill_in_prog_lock);
958 write_unlock(&pkc->blk_fill_in_prog_lock);
959 }
960 prb_close_block(pkc, pbd, po, status);
961 return;
962 }
963 }
964
prb_curr_blk_in_use(struct tpacket_block_desc * pbd)965 static int prb_curr_blk_in_use(struct tpacket_block_desc *pbd)
966 {
967 return TP_STATUS_USER & BLOCK_STATUS(pbd);
968 }
969
prb_queue_frozen(struct tpacket_kbdq_core * pkc)970 static int prb_queue_frozen(struct tpacket_kbdq_core *pkc)
971 {
972 return pkc->reset_pending_on_curr_blk;
973 }
974
prb_clear_blk_fill_status(struct packet_ring_buffer * rb)975 static void prb_clear_blk_fill_status(struct packet_ring_buffer *rb)
976 __releases(&pkc->blk_fill_in_prog_lock)
977 {
978 struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
979
980 read_unlock(&pkc->blk_fill_in_prog_lock);
981 }
982
prb_fill_rxhash(struct tpacket_kbdq_core * pkc,struct tpacket3_hdr * ppd)983 static void prb_fill_rxhash(struct tpacket_kbdq_core *pkc,
984 struct tpacket3_hdr *ppd)
985 {
986 ppd->hv1.tp_rxhash = skb_get_hash(pkc->skb);
987 }
988
prb_clear_rxhash(struct tpacket_kbdq_core * pkc,struct tpacket3_hdr * ppd)989 static void prb_clear_rxhash(struct tpacket_kbdq_core *pkc,
990 struct tpacket3_hdr *ppd)
991 {
992 ppd->hv1.tp_rxhash = 0;
993 }
994
prb_fill_vlan_info(struct tpacket_kbdq_core * pkc,struct tpacket3_hdr * ppd)995 static void prb_fill_vlan_info(struct tpacket_kbdq_core *pkc,
996 struct tpacket3_hdr *ppd)
997 {
998 struct packet_sock *po = container_of(pkc, struct packet_sock, rx_ring.prb_bdqc);
999
1000 if (skb_vlan_tag_present(pkc->skb)) {
1001 ppd->hv1.tp_vlan_tci = skb_vlan_tag_get(pkc->skb);
1002 ppd->hv1.tp_vlan_tpid = ntohs(pkc->skb->vlan_proto);
1003 ppd->tp_status = TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
1004 } else if (unlikely(po->sk.sk_type == SOCK_DGRAM && eth_type_vlan(pkc->skb->protocol))) {
1005 ppd->hv1.tp_vlan_tci = vlan_get_tci(pkc->skb, pkc->skb->dev);
1006 ppd->hv1.tp_vlan_tpid = ntohs(pkc->skb->protocol);
1007 ppd->tp_status = TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
1008 } else {
1009 ppd->hv1.tp_vlan_tci = 0;
1010 ppd->hv1.tp_vlan_tpid = 0;
1011 ppd->tp_status = TP_STATUS_AVAILABLE;
1012 }
1013 }
1014
prb_run_all_ft_ops(struct tpacket_kbdq_core * pkc,struct tpacket3_hdr * ppd)1015 static void prb_run_all_ft_ops(struct tpacket_kbdq_core *pkc,
1016 struct tpacket3_hdr *ppd)
1017 {
1018 ppd->hv1.tp_padding = 0;
1019 prb_fill_vlan_info(pkc, ppd);
1020
1021 if (pkc->feature_req_word & TP_FT_REQ_FILL_RXHASH)
1022 prb_fill_rxhash(pkc, ppd);
1023 else
1024 prb_clear_rxhash(pkc, ppd);
1025 }
1026
prb_fill_curr_block(char * curr,struct tpacket_kbdq_core * pkc,struct tpacket_block_desc * pbd,unsigned int len)1027 static void prb_fill_curr_block(char *curr,
1028 struct tpacket_kbdq_core *pkc,
1029 struct tpacket_block_desc *pbd,
1030 unsigned int len)
1031 __acquires(&pkc->blk_fill_in_prog_lock)
1032 {
1033 struct tpacket3_hdr *ppd;
1034
1035 ppd = (struct tpacket3_hdr *)curr;
1036 ppd->tp_next_offset = TOTAL_PKT_LEN_INCL_ALIGN(len);
1037 pkc->prev = curr;
1038 pkc->nxt_offset += TOTAL_PKT_LEN_INCL_ALIGN(len);
1039 BLOCK_LEN(pbd) += TOTAL_PKT_LEN_INCL_ALIGN(len);
1040 BLOCK_NUM_PKTS(pbd) += 1;
1041 read_lock(&pkc->blk_fill_in_prog_lock);
1042 prb_run_all_ft_ops(pkc, ppd);
1043 }
1044
1045 /* Assumes caller has the sk->rx_queue.lock */
__packet_lookup_frame_in_block(struct packet_sock * po,struct sk_buff * skb,unsigned int len)1046 static void *__packet_lookup_frame_in_block(struct packet_sock *po,
1047 struct sk_buff *skb,
1048 unsigned int len
1049 )
1050 {
1051 struct tpacket_kbdq_core *pkc;
1052 struct tpacket_block_desc *pbd;
1053 char *curr, *end;
1054
1055 pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
1056 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
1057
1058 /* Queue is frozen when user space is lagging behind */
1059 if (prb_queue_frozen(pkc)) {
1060 /*
1061 * Check if that last block which caused the queue to freeze,
1062 * is still in_use by user-space.
1063 */
1064 if (prb_curr_blk_in_use(pbd)) {
1065 /* Can't record this packet */
1066 return NULL;
1067 } else {
1068 /*
1069 * Ok, the block was released by user-space.
1070 * Now let's open that block.
1071 * opening a block also thaws the queue.
1072 * Thawing is a side effect.
1073 */
1074 prb_open_block(pkc, pbd);
1075 }
1076 }
1077
1078 smp_mb();
1079 curr = pkc->nxt_offset;
1080 pkc->skb = skb;
1081 end = (char *)pbd + pkc->kblk_size;
1082
1083 /* first try the current block */
1084 if (curr+TOTAL_PKT_LEN_INCL_ALIGN(len) < end) {
1085 prb_fill_curr_block(curr, pkc, pbd, len);
1086 return (void *)curr;
1087 }
1088
1089 /* Ok, close the current block */
1090 prb_retire_current_block(pkc, po, 0);
1091
1092 /* Now, try to dispatch the next block */
1093 curr = (char *)prb_dispatch_next_block(pkc, po);
1094 if (curr) {
1095 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
1096 prb_fill_curr_block(curr, pkc, pbd, len);
1097 return (void *)curr;
1098 }
1099
1100 /*
1101 * No free blocks are available.user_space hasn't caught up yet.
1102 * Queue was just frozen and now this packet will get dropped.
1103 */
1104 return NULL;
1105 }
1106
packet_current_rx_frame(struct packet_sock * po,struct sk_buff * skb,int status,unsigned int len)1107 static void *packet_current_rx_frame(struct packet_sock *po,
1108 struct sk_buff *skb,
1109 int status, unsigned int len)
1110 {
1111 char *curr = NULL;
1112 switch (po->tp_version) {
1113 case TPACKET_V1:
1114 case TPACKET_V2:
1115 curr = packet_lookup_frame(po, &po->rx_ring,
1116 po->rx_ring.head, status);
1117 return curr;
1118 case TPACKET_V3:
1119 return __packet_lookup_frame_in_block(po, skb, len);
1120 default:
1121 WARN(1, "TPACKET version not supported\n");
1122 BUG();
1123 return NULL;
1124 }
1125 }
1126
prb_lookup_block(const struct packet_sock * po,const struct packet_ring_buffer * rb,unsigned int idx,int status)1127 static void *prb_lookup_block(const struct packet_sock *po,
1128 const struct packet_ring_buffer *rb,
1129 unsigned int idx,
1130 int status)
1131 {
1132 struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
1133 struct tpacket_block_desc *pbd = GET_PBLOCK_DESC(pkc, idx);
1134
1135 if (status != BLOCK_STATUS(pbd))
1136 return NULL;
1137 return pbd;
1138 }
1139
prb_previous_blk_num(struct packet_ring_buffer * rb)1140 static int prb_previous_blk_num(struct packet_ring_buffer *rb)
1141 {
1142 unsigned int prev;
1143 if (rb->prb_bdqc.kactive_blk_num)
1144 prev = rb->prb_bdqc.kactive_blk_num-1;
1145 else
1146 prev = rb->prb_bdqc.knum_blocks-1;
1147 return prev;
1148 }
1149
1150 /* Assumes caller has held the rx_queue.lock */
__prb_previous_block(struct packet_sock * po,struct packet_ring_buffer * rb,int status)1151 static void *__prb_previous_block(struct packet_sock *po,
1152 struct packet_ring_buffer *rb,
1153 int status)
1154 {
1155 unsigned int previous = prb_previous_blk_num(rb);
1156 return prb_lookup_block(po, rb, previous, status);
1157 }
1158
packet_previous_rx_frame(struct packet_sock * po,struct packet_ring_buffer * rb,int status)1159 static void *packet_previous_rx_frame(struct packet_sock *po,
1160 struct packet_ring_buffer *rb,
1161 int status)
1162 {
1163 if (po->tp_version <= TPACKET_V2)
1164 return packet_previous_frame(po, rb, status);
1165
1166 return __prb_previous_block(po, rb, status);
1167 }
1168
packet_increment_rx_head(struct packet_sock * po,struct packet_ring_buffer * rb)1169 static void packet_increment_rx_head(struct packet_sock *po,
1170 struct packet_ring_buffer *rb)
1171 {
1172 switch (po->tp_version) {
1173 case TPACKET_V1:
1174 case TPACKET_V2:
1175 return packet_increment_head(rb);
1176 case TPACKET_V3:
1177 default:
1178 WARN(1, "TPACKET version not supported.\n");
1179 BUG();
1180 return;
1181 }
1182 }
1183
packet_previous_frame(struct packet_sock * po,struct packet_ring_buffer * rb,int status)1184 static void *packet_previous_frame(struct packet_sock *po,
1185 struct packet_ring_buffer *rb,
1186 int status)
1187 {
1188 unsigned int previous = rb->head ? rb->head - 1 : rb->frame_max;
1189 return packet_lookup_frame(po, rb, previous, status);
1190 }
1191
packet_increment_head(struct packet_ring_buffer * buff)1192 static void packet_increment_head(struct packet_ring_buffer *buff)
1193 {
1194 buff->head = buff->head != buff->frame_max ? buff->head+1 : 0;
1195 }
1196
packet_inc_pending(struct packet_ring_buffer * rb)1197 static void packet_inc_pending(struct packet_ring_buffer *rb)
1198 {
1199 this_cpu_inc(*rb->pending_refcnt);
1200 }
1201
packet_dec_pending(struct packet_ring_buffer * rb)1202 static void packet_dec_pending(struct packet_ring_buffer *rb)
1203 {
1204 this_cpu_dec(*rb->pending_refcnt);
1205 }
1206
packet_read_pending(const struct packet_ring_buffer * rb)1207 static unsigned int packet_read_pending(const struct packet_ring_buffer *rb)
1208 {
1209 unsigned int refcnt = 0;
1210 int cpu;
1211
1212 /* We don't use pending refcount in rx_ring. */
1213 if (rb->pending_refcnt == NULL)
1214 return 0;
1215
1216 for_each_possible_cpu(cpu)
1217 refcnt += *per_cpu_ptr(rb->pending_refcnt, cpu);
1218
1219 return refcnt;
1220 }
1221
packet_alloc_pending(struct packet_sock * po)1222 static int packet_alloc_pending(struct packet_sock *po)
1223 {
1224 po->rx_ring.pending_refcnt = NULL;
1225
1226 po->tx_ring.pending_refcnt = alloc_percpu(unsigned int);
1227 if (unlikely(po->tx_ring.pending_refcnt == NULL))
1228 return -ENOBUFS;
1229
1230 return 0;
1231 }
1232
packet_free_pending(struct packet_sock * po)1233 static void packet_free_pending(struct packet_sock *po)
1234 {
1235 free_percpu(po->tx_ring.pending_refcnt);
1236 }
1237
1238 #define ROOM_POW_OFF 2
1239 #define ROOM_NONE 0x0
1240 #define ROOM_LOW 0x1
1241 #define ROOM_NORMAL 0x2
1242
__tpacket_has_room(const struct packet_sock * po,int pow_off)1243 static bool __tpacket_has_room(const struct packet_sock *po, int pow_off)
1244 {
1245 int idx, len;
1246
1247 len = READ_ONCE(po->rx_ring.frame_max) + 1;
1248 idx = READ_ONCE(po->rx_ring.head);
1249 if (pow_off)
1250 idx += len >> pow_off;
1251 if (idx >= len)
1252 idx -= len;
1253 return packet_lookup_frame(po, &po->rx_ring, idx, TP_STATUS_KERNEL);
1254 }
1255
__tpacket_v3_has_room(const struct packet_sock * po,int pow_off)1256 static bool __tpacket_v3_has_room(const struct packet_sock *po, int pow_off)
1257 {
1258 int idx, len;
1259
1260 len = READ_ONCE(po->rx_ring.prb_bdqc.knum_blocks);
1261 idx = READ_ONCE(po->rx_ring.prb_bdqc.kactive_blk_num);
1262 if (pow_off)
1263 idx += len >> pow_off;
1264 if (idx >= len)
1265 idx -= len;
1266 return prb_lookup_block(po, &po->rx_ring, idx, TP_STATUS_KERNEL);
1267 }
1268
__packet_rcv_has_room(const struct packet_sock * po,const struct sk_buff * skb)1269 static int __packet_rcv_has_room(const struct packet_sock *po,
1270 const struct sk_buff *skb)
1271 {
1272 const struct sock *sk = &po->sk;
1273 int ret = ROOM_NONE;
1274
1275 if (po->prot_hook.func != tpacket_rcv) {
1276 int rcvbuf = READ_ONCE(sk->sk_rcvbuf);
1277 int avail = rcvbuf - atomic_read(&sk->sk_rmem_alloc)
1278 - (skb ? skb->truesize : 0);
1279
1280 if (avail > (rcvbuf >> ROOM_POW_OFF))
1281 return ROOM_NORMAL;
1282 else if (avail > 0)
1283 return ROOM_LOW;
1284 else
1285 return ROOM_NONE;
1286 }
1287
1288 if (po->tp_version == TPACKET_V3) {
1289 if (__tpacket_v3_has_room(po, ROOM_POW_OFF))
1290 ret = ROOM_NORMAL;
1291 else if (__tpacket_v3_has_room(po, 0))
1292 ret = ROOM_LOW;
1293 } else {
1294 if (__tpacket_has_room(po, ROOM_POW_OFF))
1295 ret = ROOM_NORMAL;
1296 else if (__tpacket_has_room(po, 0))
1297 ret = ROOM_LOW;
1298 }
1299
1300 return ret;
1301 }
1302
packet_rcv_has_room(struct packet_sock * po,struct sk_buff * skb)1303 static int packet_rcv_has_room(struct packet_sock *po, struct sk_buff *skb)
1304 {
1305 bool pressure;
1306 int ret;
1307
1308 ret = __packet_rcv_has_room(po, skb);
1309 pressure = ret != ROOM_NORMAL;
1310
1311 if (packet_sock_flag(po, PACKET_SOCK_PRESSURE) != pressure)
1312 packet_sock_flag_set(po, PACKET_SOCK_PRESSURE, pressure);
1313
1314 return ret;
1315 }
1316
packet_rcv_try_clear_pressure(struct packet_sock * po)1317 static void packet_rcv_try_clear_pressure(struct packet_sock *po)
1318 {
1319 if (packet_sock_flag(po, PACKET_SOCK_PRESSURE) &&
1320 __packet_rcv_has_room(po, NULL) == ROOM_NORMAL)
1321 packet_sock_flag_set(po, PACKET_SOCK_PRESSURE, false);
1322 }
1323
packet_sock_destruct(struct sock * sk)1324 static void packet_sock_destruct(struct sock *sk)
1325 {
1326 skb_queue_purge(&sk->sk_error_queue);
1327
1328 WARN_ON(atomic_read(&sk->sk_rmem_alloc));
1329 WARN_ON(refcount_read(&sk->sk_wmem_alloc));
1330
1331 if (!sock_flag(sk, SOCK_DEAD)) {
1332 pr_err("Attempt to release alive packet socket: %p\n", sk);
1333 return;
1334 }
1335 }
1336
fanout_flow_is_huge(struct packet_sock * po,struct sk_buff * skb)1337 static bool fanout_flow_is_huge(struct packet_sock *po, struct sk_buff *skb)
1338 {
1339 u32 *history = po->rollover->history;
1340 u32 victim, rxhash;
1341 int i, count = 0;
1342
1343 rxhash = skb_get_hash(skb);
1344 for (i = 0; i < ROLLOVER_HLEN; i++)
1345 if (READ_ONCE(history[i]) == rxhash)
1346 count++;
1347
1348 victim = get_random_u32_below(ROLLOVER_HLEN);
1349
1350 /* Avoid dirtying the cache line if possible */
1351 if (READ_ONCE(history[victim]) != rxhash)
1352 WRITE_ONCE(history[victim], rxhash);
1353
1354 return count > (ROLLOVER_HLEN >> 1);
1355 }
1356
fanout_demux_hash(struct packet_fanout * f,struct sk_buff * skb,unsigned int num)1357 static unsigned int fanout_demux_hash(struct packet_fanout *f,
1358 struct sk_buff *skb,
1359 unsigned int num)
1360 {
1361 return reciprocal_scale(__skb_get_hash_symmetric(skb), num);
1362 }
1363
fanout_demux_lb(struct packet_fanout * f,struct sk_buff * skb,unsigned int num)1364 static unsigned int fanout_demux_lb(struct packet_fanout *f,
1365 struct sk_buff *skb,
1366 unsigned int num)
1367 {
1368 unsigned int val = atomic_inc_return(&f->rr_cur);
1369
1370 return val % num;
1371 }
1372
fanout_demux_cpu(struct packet_fanout * f,struct sk_buff * skb,unsigned int num)1373 static unsigned int fanout_demux_cpu(struct packet_fanout *f,
1374 struct sk_buff *skb,
1375 unsigned int num)
1376 {
1377 return smp_processor_id() % num;
1378 }
1379
fanout_demux_rnd(struct packet_fanout * f,struct sk_buff * skb,unsigned int num)1380 static unsigned int fanout_demux_rnd(struct packet_fanout *f,
1381 struct sk_buff *skb,
1382 unsigned int num)
1383 {
1384 return get_random_u32_below(num);
1385 }
1386
fanout_demux_rollover(struct packet_fanout * f,struct sk_buff * skb,unsigned int idx,bool try_self,unsigned int num)1387 static unsigned int fanout_demux_rollover(struct packet_fanout *f,
1388 struct sk_buff *skb,
1389 unsigned int idx, bool try_self,
1390 unsigned int num)
1391 {
1392 struct packet_sock *po, *po_next, *po_skip = NULL;
1393 unsigned int i, j, room = ROOM_NONE;
1394
1395 po = pkt_sk(rcu_dereference(f->arr[idx]));
1396
1397 if (try_self) {
1398 room = packet_rcv_has_room(po, skb);
1399 if (room == ROOM_NORMAL ||
1400 (room == ROOM_LOW && !fanout_flow_is_huge(po, skb)))
1401 return idx;
1402 po_skip = po;
1403 }
1404
1405 i = j = min_t(int, po->rollover->sock, num - 1);
1406 do {
1407 po_next = pkt_sk(rcu_dereference(f->arr[i]));
1408 if (po_next != po_skip &&
1409 !packet_sock_flag(po_next, PACKET_SOCK_PRESSURE) &&
1410 packet_rcv_has_room(po_next, skb) == ROOM_NORMAL) {
1411 if (i != j)
1412 po->rollover->sock = i;
1413 atomic_long_inc(&po->rollover->num);
1414 if (room == ROOM_LOW)
1415 atomic_long_inc(&po->rollover->num_huge);
1416 return i;
1417 }
1418
1419 if (++i == num)
1420 i = 0;
1421 } while (i != j);
1422
1423 atomic_long_inc(&po->rollover->num_failed);
1424 return idx;
1425 }
1426
fanout_demux_qm(struct packet_fanout * f,struct sk_buff * skb,unsigned int num)1427 static unsigned int fanout_demux_qm(struct packet_fanout *f,
1428 struct sk_buff *skb,
1429 unsigned int num)
1430 {
1431 return skb_get_queue_mapping(skb) % num;
1432 }
1433
fanout_demux_bpf(struct packet_fanout * f,struct sk_buff * skb,unsigned int num)1434 static unsigned int fanout_demux_bpf(struct packet_fanout *f,
1435 struct sk_buff *skb,
1436 unsigned int num)
1437 {
1438 struct bpf_prog *prog;
1439 unsigned int ret = 0;
1440
1441 rcu_read_lock();
1442 prog = rcu_dereference(f->bpf_prog);
1443 if (prog)
1444 ret = bpf_prog_run_clear_cb(prog, skb) % num;
1445 rcu_read_unlock();
1446
1447 return ret;
1448 }
1449
fanout_has_flag(struct packet_fanout * f,u16 flag)1450 static bool fanout_has_flag(struct packet_fanout *f, u16 flag)
1451 {
1452 return f->flags & (flag >> 8);
1453 }
1454
packet_rcv_fanout(struct sk_buff * skb,struct net_device * dev,struct packet_type * pt,struct net_device * orig_dev)1455 static int packet_rcv_fanout(struct sk_buff *skb, struct net_device *dev,
1456 struct packet_type *pt, struct net_device *orig_dev)
1457 {
1458 struct packet_fanout *f = pt->af_packet_priv;
1459 unsigned int num = READ_ONCE(f->num_members);
1460 struct net *net = read_pnet(&f->net);
1461 struct packet_sock *po;
1462 unsigned int idx;
1463
1464 if (!net_eq(dev_net(dev), net) || !num) {
1465 kfree_skb(skb);
1466 return 0;
1467 }
1468
1469 if (fanout_has_flag(f, PACKET_FANOUT_FLAG_DEFRAG)) {
1470 skb = ip_check_defrag(net, skb, IP_DEFRAG_AF_PACKET);
1471 if (!skb)
1472 return 0;
1473 }
1474 switch (f->type) {
1475 case PACKET_FANOUT_HASH:
1476 default:
1477 idx = fanout_demux_hash(f, skb, num);
1478 break;
1479 case PACKET_FANOUT_LB:
1480 idx = fanout_demux_lb(f, skb, num);
1481 break;
1482 case PACKET_FANOUT_CPU:
1483 idx = fanout_demux_cpu(f, skb, num);
1484 break;
1485 case PACKET_FANOUT_RND:
1486 idx = fanout_demux_rnd(f, skb, num);
1487 break;
1488 case PACKET_FANOUT_QM:
1489 idx = fanout_demux_qm(f, skb, num);
1490 break;
1491 case PACKET_FANOUT_ROLLOVER:
1492 idx = fanout_demux_rollover(f, skb, 0, false, num);
1493 break;
1494 case PACKET_FANOUT_CBPF:
1495 case PACKET_FANOUT_EBPF:
1496 idx = fanout_demux_bpf(f, skb, num);
1497 break;
1498 }
1499
1500 if (fanout_has_flag(f, PACKET_FANOUT_FLAG_ROLLOVER))
1501 idx = fanout_demux_rollover(f, skb, idx, true, num);
1502
1503 po = pkt_sk(rcu_dereference(f->arr[idx]));
1504 return po->prot_hook.func(skb, dev, &po->prot_hook, orig_dev);
1505 }
1506
1507 DEFINE_MUTEX(fanout_mutex);
1508 EXPORT_SYMBOL_GPL(fanout_mutex);
1509 static LIST_HEAD(fanout_list);
1510 static u16 fanout_next_id;
1511
__fanout_link(struct sock * sk,struct packet_sock * po)1512 static void __fanout_link(struct sock *sk, struct packet_sock *po)
1513 {
1514 struct packet_fanout *f = po->fanout;
1515
1516 spin_lock(&f->lock);
1517 rcu_assign_pointer(f->arr[f->num_members], sk);
1518 smp_wmb();
1519 f->num_members++;
1520 if (f->num_members == 1)
1521 dev_add_pack(&f->prot_hook);
1522 spin_unlock(&f->lock);
1523 }
1524
__fanout_unlink(struct sock * sk,struct packet_sock * po)1525 static void __fanout_unlink(struct sock *sk, struct packet_sock *po)
1526 {
1527 struct packet_fanout *f = po->fanout;
1528 int i;
1529
1530 spin_lock(&f->lock);
1531 for (i = 0; i < f->num_members; i++) {
1532 if (rcu_dereference_protected(f->arr[i],
1533 lockdep_is_held(&f->lock)) == sk)
1534 break;
1535 }
1536 BUG_ON(i >= f->num_members);
1537 rcu_assign_pointer(f->arr[i],
1538 rcu_dereference_protected(f->arr[f->num_members - 1],
1539 lockdep_is_held(&f->lock)));
1540 f->num_members--;
1541 if (f->num_members == 0)
1542 __dev_remove_pack(&f->prot_hook);
1543 spin_unlock(&f->lock);
1544 }
1545
match_fanout_group(struct packet_type * ptype,struct sock * sk)1546 static bool match_fanout_group(struct packet_type *ptype, struct sock *sk)
1547 {
1548 if (sk->sk_family != PF_PACKET)
1549 return false;
1550
1551 return ptype->af_packet_priv == pkt_sk(sk)->fanout;
1552 }
1553
fanout_init_data(struct packet_fanout * f)1554 static void fanout_init_data(struct packet_fanout *f)
1555 {
1556 switch (f->type) {
1557 case PACKET_FANOUT_LB:
1558 atomic_set(&f->rr_cur, 0);
1559 break;
1560 case PACKET_FANOUT_CBPF:
1561 case PACKET_FANOUT_EBPF:
1562 RCU_INIT_POINTER(f->bpf_prog, NULL);
1563 break;
1564 }
1565 }
1566
__fanout_set_data_bpf(struct packet_fanout * f,struct bpf_prog * new)1567 static void __fanout_set_data_bpf(struct packet_fanout *f, struct bpf_prog *new)
1568 {
1569 struct bpf_prog *old;
1570
1571 spin_lock(&f->lock);
1572 old = rcu_dereference_protected(f->bpf_prog, lockdep_is_held(&f->lock));
1573 rcu_assign_pointer(f->bpf_prog, new);
1574 spin_unlock(&f->lock);
1575
1576 if (old) {
1577 synchronize_net();
1578 bpf_prog_destroy(old);
1579 }
1580 }
1581
fanout_set_data_cbpf(struct packet_sock * po,sockptr_t data,unsigned int len)1582 static int fanout_set_data_cbpf(struct packet_sock *po, sockptr_t data,
1583 unsigned int len)
1584 {
1585 struct bpf_prog *new;
1586 struct sock_fprog fprog;
1587 int ret;
1588
1589 if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
1590 return -EPERM;
1591
1592 ret = copy_bpf_fprog_from_user(&fprog, data, len);
1593 if (ret)
1594 return ret;
1595
1596 ret = bpf_prog_create_from_user(&new, &fprog, NULL, false);
1597 if (ret)
1598 return ret;
1599
1600 __fanout_set_data_bpf(po->fanout, new);
1601 return 0;
1602 }
1603
fanout_set_data_ebpf(struct packet_sock * po,sockptr_t data,unsigned int len)1604 static int fanout_set_data_ebpf(struct packet_sock *po, sockptr_t data,
1605 unsigned int len)
1606 {
1607 struct bpf_prog *new;
1608 u32 fd;
1609
1610 if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
1611 return -EPERM;
1612 if (len != sizeof(fd))
1613 return -EINVAL;
1614 if (copy_from_sockptr(&fd, data, len))
1615 return -EFAULT;
1616
1617 new = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
1618 if (IS_ERR(new))
1619 return PTR_ERR(new);
1620
1621 __fanout_set_data_bpf(po->fanout, new);
1622 return 0;
1623 }
1624
fanout_set_data(struct packet_sock * po,sockptr_t data,unsigned int len)1625 static int fanout_set_data(struct packet_sock *po, sockptr_t data,
1626 unsigned int len)
1627 {
1628 switch (po->fanout->type) {
1629 case PACKET_FANOUT_CBPF:
1630 return fanout_set_data_cbpf(po, data, len);
1631 case PACKET_FANOUT_EBPF:
1632 return fanout_set_data_ebpf(po, data, len);
1633 default:
1634 return -EINVAL;
1635 }
1636 }
1637
fanout_release_data(struct packet_fanout * f)1638 static void fanout_release_data(struct packet_fanout *f)
1639 {
1640 switch (f->type) {
1641 case PACKET_FANOUT_CBPF:
1642 case PACKET_FANOUT_EBPF:
1643 __fanout_set_data_bpf(f, NULL);
1644 }
1645 }
1646
__fanout_id_is_free(struct sock * sk,u16 candidate_id)1647 static bool __fanout_id_is_free(struct sock *sk, u16 candidate_id)
1648 {
1649 struct packet_fanout *f;
1650
1651 list_for_each_entry(f, &fanout_list, list) {
1652 if (f->id == candidate_id &&
1653 read_pnet(&f->net) == sock_net(sk)) {
1654 return false;
1655 }
1656 }
1657 return true;
1658 }
1659
fanout_find_new_id(struct sock * sk,u16 * new_id)1660 static bool fanout_find_new_id(struct sock *sk, u16 *new_id)
1661 {
1662 u16 id = fanout_next_id;
1663
1664 do {
1665 if (__fanout_id_is_free(sk, id)) {
1666 *new_id = id;
1667 fanout_next_id = id + 1;
1668 return true;
1669 }
1670
1671 id++;
1672 } while (id != fanout_next_id);
1673
1674 return false;
1675 }
1676
fanout_add(struct sock * sk,struct fanout_args * args)1677 static int fanout_add(struct sock *sk, struct fanout_args *args)
1678 {
1679 struct packet_rollover *rollover = NULL;
1680 struct packet_sock *po = pkt_sk(sk);
1681 u16 type_flags = args->type_flags;
1682 struct packet_fanout *f, *match;
1683 u8 type = type_flags & 0xff;
1684 u8 flags = type_flags >> 8;
1685 u16 id = args->id;
1686 int err;
1687
1688 switch (type) {
1689 case PACKET_FANOUT_ROLLOVER:
1690 if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
1691 return -EINVAL;
1692 break;
1693 case PACKET_FANOUT_HASH:
1694 case PACKET_FANOUT_LB:
1695 case PACKET_FANOUT_CPU:
1696 case PACKET_FANOUT_RND:
1697 case PACKET_FANOUT_QM:
1698 case PACKET_FANOUT_CBPF:
1699 case PACKET_FANOUT_EBPF:
1700 break;
1701 default:
1702 return -EINVAL;
1703 }
1704
1705 mutex_lock(&fanout_mutex);
1706
1707 err = -EALREADY;
1708 if (po->fanout)
1709 goto out;
1710
1711 if (type == PACKET_FANOUT_ROLLOVER ||
1712 (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) {
1713 err = -ENOMEM;
1714 rollover = kzalloc_obj(*rollover, GFP_KERNEL);
1715 if (!rollover)
1716 goto out;
1717 atomic_long_set(&rollover->num, 0);
1718 atomic_long_set(&rollover->num_huge, 0);
1719 atomic_long_set(&rollover->num_failed, 0);
1720 }
1721
1722 if (type_flags & PACKET_FANOUT_FLAG_UNIQUEID) {
1723 if (id != 0) {
1724 err = -EINVAL;
1725 goto out;
1726 }
1727 if (!fanout_find_new_id(sk, &id)) {
1728 err = -ENOMEM;
1729 goto out;
1730 }
1731 /* ephemeral flag for the first socket in the group: drop it */
1732 flags &= ~(PACKET_FANOUT_FLAG_UNIQUEID >> 8);
1733 }
1734
1735 match = NULL;
1736 list_for_each_entry(f, &fanout_list, list) {
1737 if (f->id == id &&
1738 read_pnet(&f->net) == sock_net(sk)) {
1739 match = f;
1740 break;
1741 }
1742 }
1743 err = -EINVAL;
1744 if (match) {
1745 if (match->flags != flags)
1746 goto out;
1747 if (args->max_num_members &&
1748 args->max_num_members != match->max_num_members)
1749 goto out;
1750 } else {
1751 if (args->max_num_members > PACKET_FANOUT_MAX)
1752 goto out;
1753 if (!args->max_num_members)
1754 /* legacy PACKET_FANOUT_MAX */
1755 args->max_num_members = 256;
1756 err = -ENOMEM;
1757 match = kvzalloc_flex(*match, arr, args->max_num_members,
1758 GFP_KERNEL);
1759 if (!match)
1760 goto out;
1761 write_pnet(&match->net, sock_net(sk));
1762 match->id = id;
1763 match->type = type;
1764 match->flags = flags;
1765 INIT_LIST_HEAD(&match->list);
1766 spin_lock_init(&match->lock);
1767 refcount_set(&match->sk_ref, 0);
1768 fanout_init_data(match);
1769 match->prot_hook.type = po->prot_hook.type;
1770 match->prot_hook.dev = po->prot_hook.dev;
1771 match->prot_hook.func = packet_rcv_fanout;
1772 match->prot_hook.af_packet_priv = match;
1773 match->prot_hook.af_packet_net = read_pnet(&match->net);
1774 match->prot_hook.id_match = match_fanout_group;
1775 match->max_num_members = args->max_num_members;
1776 match->prot_hook.ignore_outgoing = type_flags & PACKET_FANOUT_FLAG_IGNORE_OUTGOING;
1777 list_add(&match->list, &fanout_list);
1778 }
1779 err = -EINVAL;
1780
1781 spin_lock(&po->bind_lock);
1782 if (po->num &&
1783 match->type == type &&
1784 match->prot_hook.type == po->prot_hook.type &&
1785 match->prot_hook.dev == po->prot_hook.dev) {
1786 err = -ENOSPC;
1787 if (refcount_read(&match->sk_ref) < match->max_num_members) {
1788 /* Paired with packet_setsockopt(PACKET_FANOUT_DATA) */
1789 WRITE_ONCE(po->fanout, match);
1790
1791 po->rollover = rollover;
1792 rollover = NULL;
1793 refcount_set(&match->sk_ref, refcount_read(&match->sk_ref) + 1);
1794 if (packet_sock_flag(po, PACKET_SOCK_RUNNING)) {
1795 __dev_remove_pack(&po->prot_hook);
1796 __fanout_link(sk, po);
1797 }
1798 err = 0;
1799 }
1800 }
1801 spin_unlock(&po->bind_lock);
1802
1803 if (err && !refcount_read(&match->sk_ref)) {
1804 list_del(&match->list);
1805 kvfree(match);
1806 }
1807
1808 out:
1809 kfree(rollover);
1810 mutex_unlock(&fanout_mutex);
1811 return err;
1812 }
1813
1814 /* If pkt_sk(sk)->fanout->sk_ref is zero, this function removes
1815 * pkt_sk(sk)->fanout from fanout_list and returns pkt_sk(sk)->fanout.
1816 * It is the responsibility of the caller to call fanout_release_data() and
1817 * free the returned packet_fanout (after synchronize_net())
1818 */
fanout_release(struct sock * sk)1819 static struct packet_fanout *fanout_release(struct sock *sk)
1820 {
1821 struct packet_sock *po = pkt_sk(sk);
1822 struct packet_fanout *f;
1823
1824 mutex_lock(&fanout_mutex);
1825 f = po->fanout;
1826 if (f) {
1827 po->fanout = NULL;
1828
1829 if (refcount_dec_and_test(&f->sk_ref))
1830 list_del(&f->list);
1831 else
1832 f = NULL;
1833 }
1834 mutex_unlock(&fanout_mutex);
1835
1836 return f;
1837 }
1838
packet_extra_vlan_len_allowed(const struct net_device * dev,struct sk_buff * skb)1839 static bool packet_extra_vlan_len_allowed(const struct net_device *dev,
1840 struct sk_buff *skb)
1841 {
1842 /* Earlier code assumed this would be a VLAN pkt, double-check
1843 * this now that we have the actual packet in hand. We can only
1844 * do this check on Ethernet devices.
1845 */
1846 if (unlikely(dev->type != ARPHRD_ETHER))
1847 return false;
1848
1849 skb_reset_mac_header(skb);
1850 return likely(eth_hdr(skb)->h_proto == htons(ETH_P_8021Q));
1851 }
1852
1853 static const struct proto_ops packet_ops;
1854
1855 static const struct proto_ops packet_ops_spkt;
1856
packet_rcv_spkt(struct sk_buff * skb,struct net_device * dev,struct packet_type * pt,struct net_device * orig_dev)1857 static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev,
1858 struct packet_type *pt, struct net_device *orig_dev)
1859 {
1860 struct sock *sk;
1861 struct sockaddr_pkt *spkt;
1862
1863 /*
1864 * When we registered the protocol we saved the socket in the data
1865 * field for just this event.
1866 */
1867
1868 sk = pt->af_packet_priv;
1869
1870 /*
1871 * Yank back the headers [hope the device set this
1872 * right or kerboom...]
1873 *
1874 * Incoming packets have ll header pulled,
1875 * push it back.
1876 *
1877 * For outgoing ones skb->data == skb_mac_header(skb)
1878 * so that this procedure is noop.
1879 */
1880
1881 if (skb->pkt_type == PACKET_LOOPBACK)
1882 goto out;
1883
1884 if (!net_eq(dev_net(dev), sock_net(sk)))
1885 goto out;
1886
1887 skb = skb_share_check(skb, GFP_ATOMIC);
1888 if (skb == NULL)
1889 goto oom;
1890
1891 /* drop any routing info */
1892 skb_dst_drop(skb);
1893
1894 /* drop conntrack reference */
1895 nf_reset_ct(skb);
1896
1897 spkt = &PACKET_SKB_CB(skb)->sa.pkt;
1898
1899 skb_push(skb, skb->data - skb_mac_header(skb));
1900
1901 /*
1902 * The SOCK_PACKET socket receives _all_ frames.
1903 */
1904
1905 spkt->spkt_family = dev->type;
1906 strscpy(spkt->spkt_device, dev->name, sizeof(spkt->spkt_device));
1907 spkt->spkt_protocol = skb->protocol;
1908
1909 /*
1910 * Charge the memory to the socket. This is done specifically
1911 * to prevent sockets using all the memory up.
1912 */
1913
1914 if (sock_queue_rcv_skb(sk, skb) == 0)
1915 return 0;
1916
1917 out:
1918 kfree_skb(skb);
1919 oom:
1920 return 0;
1921 }
1922
packet_parse_headers(struct sk_buff * skb,struct socket * sock)1923 static void packet_parse_headers(struct sk_buff *skb, struct socket *sock)
1924 {
1925 int depth;
1926
1927 if ((!skb->protocol || skb->protocol == htons(ETH_P_ALL)) &&
1928 sock->type == SOCK_RAW) {
1929 skb_reset_mac_header(skb);
1930 skb->protocol = dev_parse_header_protocol(skb);
1931 }
1932
1933 /* Move network header to the right position for VLAN tagged packets */
1934 if (likely(skb->dev->type == ARPHRD_ETHER) &&
1935 eth_type_vlan(skb->protocol) &&
1936 vlan_get_protocol_and_depth(skb, skb->protocol, &depth) != 0)
1937 skb_set_network_header(skb, depth);
1938
1939 skb_probe_transport_header(skb);
1940 }
1941
1942 /*
1943 * Output a raw packet to a device layer. This bypasses all the other
1944 * protocol layers and you must therefore supply it with a complete frame
1945 */
1946
packet_sendmsg_spkt(struct socket * sock,struct msghdr * msg,size_t len)1947 static int packet_sendmsg_spkt(struct socket *sock, struct msghdr *msg,
1948 size_t len)
1949 {
1950 struct sock *sk = sock->sk;
1951 DECLARE_SOCKADDR(struct sockaddr_pkt *, saddr, msg->msg_name);
1952 struct sk_buff *skb = NULL;
1953 struct net_device *dev;
1954 struct sockcm_cookie sockc;
1955 __be16 proto = 0;
1956 int err;
1957 int extra_len = 0;
1958
1959 /*
1960 * Get and verify the address.
1961 */
1962
1963 if (saddr) {
1964 if (msg->msg_namelen < sizeof(struct sockaddr))
1965 return -EINVAL;
1966 if (msg->msg_namelen == sizeof(struct sockaddr_pkt))
1967 proto = saddr->spkt_protocol;
1968 } else
1969 return -ENOTCONN; /* SOCK_PACKET must be sent giving an address */
1970
1971 /*
1972 * Find the device first to size check it
1973 */
1974
1975 saddr->spkt_device[sizeof(saddr->spkt_device) - 1] = 0;
1976 retry:
1977 rcu_read_lock();
1978 dev = dev_get_by_name_rcu(sock_net(sk), saddr->spkt_device);
1979 err = -ENODEV;
1980 if (dev == NULL)
1981 goto out_unlock;
1982
1983 err = -ENETDOWN;
1984 if (!(dev->flags & IFF_UP))
1985 goto out_unlock;
1986
1987 /*
1988 * You may not queue a frame bigger than the mtu. This is the lowest level
1989 * raw protocol and you must do your own fragmentation at this level.
1990 */
1991
1992 if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
1993 if (!netif_supports_nofcs(dev)) {
1994 err = -EPROTONOSUPPORT;
1995 goto out_unlock;
1996 }
1997 extra_len = 4; /* We're doing our own CRC */
1998 }
1999
2000 err = -EMSGSIZE;
2001 if (len > dev->mtu + dev->hard_header_len + VLAN_HLEN + extra_len)
2002 goto out_unlock;
2003
2004 if (!skb) {
2005 size_t reserved = LL_RESERVED_SPACE(dev);
2006 int tlen = dev->needed_tailroom;
2007 unsigned int hhlen = dev->header_ops ? dev->hard_header_len : 0;
2008
2009 rcu_read_unlock();
2010 skb = sock_wmalloc(sk, len + reserved + tlen, 0, GFP_KERNEL);
2011 if (skb == NULL)
2012 return -ENOBUFS;
2013 /* FIXME: Save some space for broken drivers that write a hard
2014 * header at transmission time by themselves. PPP is the notable
2015 * one here. This should really be fixed at the driver level.
2016 */
2017 skb_reserve(skb, reserved);
2018 skb_reset_network_header(skb);
2019
2020 /* Try to align data part correctly */
2021 if (hhlen) {
2022 skb->data -= hhlen;
2023 skb->tail -= hhlen;
2024 if (len < hhlen)
2025 skb_reset_network_header(skb);
2026 }
2027 err = memcpy_from_msg(skb_put(skb, len), msg, len);
2028 if (err)
2029 goto out_free;
2030 goto retry;
2031 }
2032
2033 if (!dev_validate_header(dev, skb->data, len) || !skb->len) {
2034 err = -EINVAL;
2035 goto out_unlock;
2036 }
2037 if (len > (dev->mtu + dev->hard_header_len + extra_len) &&
2038 !packet_extra_vlan_len_allowed(dev, skb)) {
2039 err = -EMSGSIZE;
2040 goto out_unlock;
2041 }
2042
2043 sockcm_init(&sockc, sk);
2044 if (msg->msg_controllen) {
2045 err = sock_cmsg_send(sk, msg, &sockc);
2046 if (unlikely(err))
2047 goto out_unlock;
2048 }
2049
2050 skb->protocol = proto;
2051 skb->dev = dev;
2052 skb->priority = sockc.priority;
2053 skb->mark = sockc.mark;
2054 skb_set_delivery_type_by_clockid(skb, sockc.transmit_time, sk->sk_clockid);
2055 skb_setup_tx_timestamp(skb, &sockc);
2056
2057 if (unlikely(extra_len == 4))
2058 skb->no_fcs = 1;
2059
2060 packet_parse_headers(skb, sock);
2061
2062 dev_queue_xmit(skb);
2063 rcu_read_unlock();
2064 return len;
2065
2066 out_unlock:
2067 rcu_read_unlock();
2068 out_free:
2069 kfree_skb(skb);
2070 return err;
2071 }
2072
run_filter(struct sk_buff * skb,const struct sock * sk,unsigned int res)2073 static unsigned int run_filter(struct sk_buff *skb,
2074 const struct sock *sk,
2075 unsigned int res)
2076 {
2077 struct sk_filter *filter;
2078
2079 rcu_read_lock();
2080 filter = rcu_dereference(sk->sk_filter);
2081 if (filter != NULL)
2082 res = bpf_prog_run_clear_cb(filter->prog, skb);
2083 rcu_read_unlock();
2084
2085 return res;
2086 }
2087
packet_rcv_vnet(struct msghdr * msg,const struct sk_buff * skb,size_t * len,int vnet_hdr_sz)2088 static int packet_rcv_vnet(struct msghdr *msg, const struct sk_buff *skb,
2089 size_t *len, int vnet_hdr_sz)
2090 {
2091 struct virtio_net_hdr_mrg_rxbuf vnet_hdr = { .num_buffers = 0 };
2092
2093 if (*len < vnet_hdr_sz)
2094 return -EINVAL;
2095 *len -= vnet_hdr_sz;
2096
2097 if (virtio_net_hdr_from_skb(skb, (struct virtio_net_hdr *)&vnet_hdr, vio_le(), true, 0))
2098 return -EINVAL;
2099
2100 return memcpy_to_msg(msg, (void *)&vnet_hdr, vnet_hdr_sz);
2101 }
2102
2103 /*
2104 * This function makes lazy skb cloning in hope that most of packets
2105 * are discarded by BPF.
2106 *
2107 * Note tricky part: we DO mangle shared skb! skb->data, skb->len
2108 * and skb->cb are mangled. It works because (and until) packets
2109 * falling here are owned by current CPU. Output packets are cloned
2110 * by dev_queue_xmit_nit(), input packets are processed by net_bh
2111 * sequentially, so that if we return skb to original state on exit,
2112 * we will not harm anyone.
2113 */
2114
packet_rcv(struct sk_buff * skb,struct net_device * dev,struct packet_type * pt,struct net_device * orig_dev)2115 static int packet_rcv(struct sk_buff *skb, struct net_device *dev,
2116 struct packet_type *pt, struct net_device *orig_dev)
2117 {
2118 enum skb_drop_reason drop_reason = SKB_CONSUMED;
2119 struct sock *sk = NULL;
2120 struct sockaddr_ll *sll;
2121 struct packet_sock *po;
2122 u8 *skb_head = skb->data;
2123 int skb_len = skb->len;
2124 unsigned int snaplen, res;
2125
2126 if (skb->pkt_type == PACKET_LOOPBACK)
2127 goto drop;
2128
2129 sk = pt->af_packet_priv;
2130 po = pkt_sk(sk);
2131
2132 if (!net_eq(dev_net(dev), sock_net(sk)))
2133 goto drop;
2134
2135 skb->dev = dev;
2136
2137 if (dev_has_header(dev)) {
2138 /* The device has an explicit notion of ll header,
2139 * exported to higher levels.
2140 *
2141 * Otherwise, the device hides details of its frame
2142 * structure, so that corresponding packet head is
2143 * never delivered to user.
2144 */
2145 if (sk->sk_type != SOCK_DGRAM)
2146 skb_push(skb, skb->data - skb_mac_header(skb));
2147 else if (skb->pkt_type == PACKET_OUTGOING) {
2148 /* Special case: outgoing packets have ll header at head */
2149 skb_pull(skb, skb_network_offset(skb));
2150 }
2151 }
2152
2153 snaplen = skb_frags_readable(skb) ? skb->len : skb_headlen(skb);
2154
2155 res = run_filter(skb, sk, snaplen);
2156 if (!res)
2157 goto drop_n_restore;
2158 if (snaplen > res)
2159 snaplen = res;
2160
2161 if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
2162 goto drop_n_acct;
2163
2164 if (skb_shared(skb)) {
2165 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
2166 if (nskb == NULL)
2167 goto drop_n_acct;
2168
2169 if (skb_head != skb->data) {
2170 skb->data = skb_head;
2171 skb->len = skb_len;
2172 }
2173 consume_skb(skb);
2174 skb = nskb;
2175 }
2176
2177 sock_skb_cb_check_size(sizeof(*PACKET_SKB_CB(skb)) + MAX_ADDR_LEN - 8);
2178
2179 sll = &PACKET_SKB_CB(skb)->sa.ll;
2180 sll->sll_hatype = dev->type;
2181 sll->sll_pkttype = skb->pkt_type;
2182 if (unlikely(packet_sock_flag(po, PACKET_SOCK_ORIGDEV)))
2183 sll->sll_ifindex = orig_dev->ifindex;
2184 else
2185 sll->sll_ifindex = dev->ifindex;
2186
2187 sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
2188
2189 /* sll->sll_family and sll->sll_protocol are set in packet_recvmsg().
2190 * Use their space for storing the original skb length.
2191 */
2192 PACKET_SKB_CB(skb)->sa.origlen = skb->len;
2193
2194 if (pskb_trim(skb, snaplen))
2195 goto drop_n_acct;
2196
2197 skb_set_owner_r(skb, sk);
2198 skb->dev = NULL;
2199 skb_dst_drop(skb);
2200
2201 /* drop conntrack reference */
2202 nf_reset_ct(skb);
2203
2204 spin_lock(&sk->sk_receive_queue.lock);
2205 po->stats.stats1.tp_packets++;
2206 sock_skb_set_dropcount(sk, skb);
2207 skb_clear_delivery_time(skb);
2208 __skb_queue_tail(&sk->sk_receive_queue, skb);
2209 spin_unlock(&sk->sk_receive_queue.lock);
2210 sk->sk_data_ready(sk);
2211 return 0;
2212
2213 drop_n_acct:
2214 atomic_inc(&po->tp_drops);
2215 sk_drops_inc(sk);
2216 drop_reason = SKB_DROP_REASON_PACKET_SOCK_ERROR;
2217
2218 drop_n_restore:
2219 if (skb_head != skb->data && skb_shared(skb)) {
2220 skb->data = skb_head;
2221 skb->len = skb_len;
2222 }
2223 drop:
2224 sk_skb_reason_drop(sk, skb, drop_reason);
2225 return 0;
2226 }
2227
tpacket_rcv(struct sk_buff * skb,struct net_device * dev,struct packet_type * pt,struct net_device * orig_dev)2228 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
2229 struct packet_type *pt, struct net_device *orig_dev)
2230 {
2231 enum skb_drop_reason drop_reason = SKB_CONSUMED;
2232 struct sock *sk = NULL;
2233 struct packet_sock *po;
2234 struct sockaddr_ll *sll;
2235 union tpacket_uhdr h;
2236 u8 *skb_head = skb->data;
2237 int skb_len = skb->len;
2238 unsigned int snaplen, res;
2239 unsigned long status = TP_STATUS_USER;
2240 unsigned short macoff, hdrlen;
2241 unsigned int netoff;
2242 struct sk_buff *copy_skb = NULL;
2243 struct timespec64 ts;
2244 __u32 ts_status;
2245 unsigned int slot_id = 0;
2246 int vnet_hdr_sz = 0;
2247
2248 /* struct tpacket{2,3}_hdr is aligned to a multiple of TPACKET_ALIGNMENT.
2249 * We may add members to them until current aligned size without forcing
2250 * userspace to call getsockopt(..., PACKET_HDRLEN, ...).
2251 */
2252 BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h2)) != 32);
2253 BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h3)) != 48);
2254
2255 if (skb->pkt_type == PACKET_LOOPBACK)
2256 goto drop;
2257
2258 sk = pt->af_packet_priv;
2259 po = pkt_sk(sk);
2260
2261 if (!net_eq(dev_net(dev), sock_net(sk)))
2262 goto drop;
2263
2264 if (dev_has_header(dev)) {
2265 if (sk->sk_type != SOCK_DGRAM)
2266 skb_push(skb, skb->data - skb_mac_header(skb));
2267 else if (skb->pkt_type == PACKET_OUTGOING) {
2268 /* Special case: outgoing packets have ll header at head */
2269 skb_pull(skb, skb_network_offset(skb));
2270 }
2271 }
2272
2273 snaplen = skb_frags_readable(skb) ? skb->len : skb_headlen(skb);
2274
2275 res = run_filter(skb, sk, snaplen);
2276 if (!res)
2277 goto drop_n_restore;
2278
2279 /* If we are flooded, just give up */
2280 if (__packet_rcv_has_room(po, skb) == ROOM_NONE) {
2281 atomic_inc(&po->tp_drops);
2282 goto drop_n_restore;
2283 }
2284
2285 if (skb->ip_summed == CHECKSUM_PARTIAL)
2286 status |= TP_STATUS_CSUMNOTREADY;
2287 else if (skb->pkt_type != PACKET_OUTGOING &&
2288 skb_csum_unnecessary(skb))
2289 status |= TP_STATUS_CSUM_VALID;
2290 if (skb_is_gso(skb) && skb_is_gso_tcp(skb))
2291 status |= TP_STATUS_GSO_TCP;
2292
2293 if (snaplen > res)
2294 snaplen = res;
2295
2296 if (sk->sk_type == SOCK_DGRAM) {
2297 macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
2298 po->tp_reserve;
2299 } else {
2300 unsigned int maclen = skb_network_offset(skb);
2301 netoff = TPACKET_ALIGN(po->tp_hdrlen +
2302 (maclen < 16 ? 16 : maclen)) +
2303 po->tp_reserve;
2304 vnet_hdr_sz = READ_ONCE(po->vnet_hdr_sz);
2305 if (vnet_hdr_sz)
2306 netoff += vnet_hdr_sz;
2307 macoff = netoff - maclen;
2308 }
2309 if (netoff > USHRT_MAX) {
2310 atomic_inc(&po->tp_drops);
2311 goto drop_n_restore;
2312 }
2313 if (po->tp_version <= TPACKET_V2) {
2314 if (macoff + snaplen > po->rx_ring.frame_size) {
2315 if (READ_ONCE(po->copy_thresh) &&
2316 atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {
2317 if (skb_shared(skb)) {
2318 copy_skb = skb_clone(skb, GFP_ATOMIC);
2319 } else {
2320 copy_skb = skb_get(skb);
2321 skb_head = skb->data;
2322 }
2323 if (copy_skb) {
2324 memset(&PACKET_SKB_CB(copy_skb)->sa.ll, 0,
2325 sizeof(PACKET_SKB_CB(copy_skb)->sa.ll));
2326 skb_set_owner_r(copy_skb, sk);
2327 }
2328 }
2329 snaplen = po->rx_ring.frame_size - macoff;
2330 if ((int)snaplen < 0) {
2331 snaplen = 0;
2332 vnet_hdr_sz = 0;
2333 }
2334 }
2335 } else if (unlikely(macoff + snaplen >
2336 GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {
2337 u32 nval;
2338
2339 nval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff;
2340 pr_err_once("tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\n",
2341 snaplen, nval, macoff);
2342 snaplen = nval;
2343 if (unlikely((int)snaplen < 0)) {
2344 snaplen = 0;
2345 macoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;
2346 vnet_hdr_sz = 0;
2347 }
2348 }
2349 spin_lock(&sk->sk_receive_queue.lock);
2350 h.raw = packet_current_rx_frame(po, skb,
2351 TP_STATUS_KERNEL, (macoff+snaplen));
2352 if (!h.raw)
2353 goto drop_n_account;
2354
2355 if (po->tp_version <= TPACKET_V2) {
2356 slot_id = po->rx_ring.head;
2357 if (test_bit(slot_id, po->rx_ring.rx_owner_map))
2358 goto drop_n_account;
2359 __set_bit(slot_id, po->rx_ring.rx_owner_map);
2360 }
2361
2362 if (vnet_hdr_sz &&
2363 virtio_net_hdr_from_skb(skb, h.raw + macoff -
2364 sizeof(struct virtio_net_hdr),
2365 vio_le(), true, 0)) {
2366 if (po->tp_version == TPACKET_V3)
2367 prb_clear_blk_fill_status(&po->rx_ring);
2368 goto drop_n_account;
2369 }
2370
2371 if (po->tp_version <= TPACKET_V2) {
2372 packet_increment_rx_head(po, &po->rx_ring);
2373 /*
2374 * LOSING will be reported till you read the stats,
2375 * because it's COR - Clear On Read.
2376 * Anyways, moving it for V1/V2 only as V3 doesn't need this
2377 * at packet level.
2378 */
2379 if (atomic_read(&po->tp_drops))
2380 status |= TP_STATUS_LOSING;
2381 }
2382
2383 po->stats.stats1.tp_packets++;
2384 if (copy_skb) {
2385 status |= TP_STATUS_COPY;
2386 skb_clear_delivery_time(copy_skb);
2387 __skb_queue_tail(&sk->sk_receive_queue, copy_skb);
2388 }
2389 spin_unlock(&sk->sk_receive_queue.lock);
2390
2391 skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
2392
2393 /* Always timestamp; prefer an existing software timestamp taken
2394 * closer to the time of capture.
2395 */
2396 ts_status = tpacket_get_timestamp(skb, &ts,
2397 READ_ONCE(po->tp_tstamp) |
2398 SOF_TIMESTAMPING_SOFTWARE);
2399 if (!ts_status)
2400 ktime_get_real_ts64(&ts);
2401
2402 status |= ts_status;
2403
2404 switch (po->tp_version) {
2405 case TPACKET_V1:
2406 h.h1->tp_len = skb->len;
2407 h.h1->tp_snaplen = snaplen;
2408 h.h1->tp_mac = macoff;
2409 h.h1->tp_net = netoff;
2410 h.h1->tp_sec = ts.tv_sec;
2411 h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
2412 hdrlen = sizeof(*h.h1);
2413 break;
2414 case TPACKET_V2:
2415 h.h2->tp_len = skb->len;
2416 h.h2->tp_snaplen = snaplen;
2417 h.h2->tp_mac = macoff;
2418 h.h2->tp_net = netoff;
2419 h.h2->tp_sec = ts.tv_sec;
2420 h.h2->tp_nsec = ts.tv_nsec;
2421 if (skb_vlan_tag_present(skb)) {
2422 h.h2->tp_vlan_tci = skb_vlan_tag_get(skb);
2423 h.h2->tp_vlan_tpid = ntohs(skb->vlan_proto);
2424 status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
2425 } else if (unlikely(sk->sk_type == SOCK_DGRAM && eth_type_vlan(skb->protocol))) {
2426 h.h2->tp_vlan_tci = vlan_get_tci(skb, skb->dev);
2427 h.h2->tp_vlan_tpid = ntohs(skb->protocol);
2428 status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
2429 } else {
2430 h.h2->tp_vlan_tci = 0;
2431 h.h2->tp_vlan_tpid = 0;
2432 }
2433 memset(h.h2->tp_padding, 0, sizeof(h.h2->tp_padding));
2434 hdrlen = sizeof(*h.h2);
2435 break;
2436 case TPACKET_V3:
2437 /* tp_nxt_offset,vlan are already populated above.
2438 * So DONT clear those fields here
2439 */
2440 h.h3->tp_status |= status;
2441 h.h3->tp_len = skb->len;
2442 h.h3->tp_snaplen = snaplen;
2443 h.h3->tp_mac = macoff;
2444 h.h3->tp_net = netoff;
2445 h.h3->tp_sec = ts.tv_sec;
2446 h.h3->tp_nsec = ts.tv_nsec;
2447 memset(h.h3->tp_padding, 0, sizeof(h.h3->tp_padding));
2448 hdrlen = sizeof(*h.h3);
2449 break;
2450 default:
2451 BUG();
2452 }
2453
2454 sll = h.raw + TPACKET_ALIGN(hdrlen);
2455 sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
2456 sll->sll_family = AF_PACKET;
2457 sll->sll_hatype = dev->type;
2458 sll->sll_protocol = (sk->sk_type == SOCK_DGRAM) ?
2459 vlan_get_protocol_dgram(skb) : skb->protocol;
2460 sll->sll_pkttype = skb->pkt_type;
2461 if (unlikely(packet_sock_flag(po, PACKET_SOCK_ORIGDEV)))
2462 sll->sll_ifindex = orig_dev->ifindex;
2463 else
2464 sll->sll_ifindex = dev->ifindex;
2465
2466 smp_mb();
2467
2468 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
2469 if (po->tp_version <= TPACKET_V2) {
2470 u8 *start, *end;
2471
2472 end = (u8 *) PAGE_ALIGN((unsigned long) h.raw +
2473 macoff + snaplen);
2474
2475 for (start = h.raw; start < end; start += PAGE_SIZE)
2476 flush_dcache_page(pgv_to_page(start));
2477 }
2478 smp_wmb();
2479 #endif
2480
2481 if (po->tp_version <= TPACKET_V2) {
2482 spin_lock(&sk->sk_receive_queue.lock);
2483 __packet_set_status(po, h.raw, status);
2484 __clear_bit(slot_id, po->rx_ring.rx_owner_map);
2485 spin_unlock(&sk->sk_receive_queue.lock);
2486 sk->sk_data_ready(sk);
2487 } else if (po->tp_version == TPACKET_V3) {
2488 prb_clear_blk_fill_status(&po->rx_ring);
2489 }
2490
2491 drop_n_restore:
2492 if (skb_head != skb->data && skb_shared(skb)) {
2493 skb->data = skb_head;
2494 skb->len = skb_len;
2495 }
2496 drop:
2497 sk_skb_reason_drop(sk, skb, drop_reason);
2498 return 0;
2499
2500 drop_n_account:
2501 spin_unlock(&sk->sk_receive_queue.lock);
2502 atomic_inc(&po->tp_drops);
2503 drop_reason = SKB_DROP_REASON_PACKET_SOCK_ERROR;
2504
2505 sk->sk_data_ready(sk);
2506 sk_skb_reason_drop(sk, copy_skb, drop_reason);
2507 goto drop_n_restore;
2508 }
2509
tpacket_destruct_skb(struct sk_buff * skb)2510 static void tpacket_destruct_skb(struct sk_buff *skb)
2511 {
2512 struct packet_sock *po = pkt_sk(skb->sk);
2513
2514 if (likely(po->tx_ring.pg_vec)) {
2515 void *ph;
2516 __u32 ts;
2517
2518 ph = skb_zcopy_get_nouarg(skb);
2519 packet_dec_pending(&po->tx_ring);
2520
2521 ts = __packet_set_timestamp(po, ph, skb);
2522 __packet_set_status(po, ph, TP_STATUS_AVAILABLE | ts);
2523
2524 complete(&po->skb_completion);
2525 }
2526
2527 sock_wfree(skb);
2528 }
2529
__packet_snd_vnet_parse(struct virtio_net_hdr * vnet_hdr,size_t len)2530 static int __packet_snd_vnet_parse(struct virtio_net_hdr *vnet_hdr, size_t len)
2531 {
2532 if ((vnet_hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
2533 (__virtio16_to_cpu(vio_le(), vnet_hdr->csum_start) +
2534 __virtio16_to_cpu(vio_le(), vnet_hdr->csum_offset) + 2 >
2535 __virtio16_to_cpu(vio_le(), vnet_hdr->hdr_len)))
2536 vnet_hdr->hdr_len = __cpu_to_virtio16(vio_le(),
2537 __virtio16_to_cpu(vio_le(), vnet_hdr->csum_start) +
2538 __virtio16_to_cpu(vio_le(), vnet_hdr->csum_offset) + 2);
2539
2540 if (__virtio16_to_cpu(vio_le(), vnet_hdr->hdr_len) > len)
2541 return -EINVAL;
2542
2543 return 0;
2544 }
2545
packet_snd_vnet_parse(struct msghdr * msg,size_t * len,struct virtio_net_hdr * vnet_hdr,int vnet_hdr_sz)2546 static int packet_snd_vnet_parse(struct msghdr *msg, size_t *len,
2547 struct virtio_net_hdr *vnet_hdr, int vnet_hdr_sz)
2548 {
2549 int ret;
2550
2551 if (*len < vnet_hdr_sz)
2552 return -EINVAL;
2553 *len -= vnet_hdr_sz;
2554
2555 if (!copy_from_iter_full(vnet_hdr, sizeof(*vnet_hdr), &msg->msg_iter))
2556 return -EFAULT;
2557
2558 ret = __packet_snd_vnet_parse(vnet_hdr, *len);
2559 if (ret)
2560 return ret;
2561
2562 /* move iter to point to the start of mac header */
2563 if (vnet_hdr_sz != sizeof(struct virtio_net_hdr))
2564 iov_iter_advance(&msg->msg_iter, vnet_hdr_sz - sizeof(struct virtio_net_hdr));
2565
2566 return 0;
2567 }
2568
tpacket_fill_skb(struct packet_sock * po,struct sk_buff * skb,void * frame,struct net_device * dev,void * data,int tp_len,__be16 proto,unsigned char * addr,int hlen,int copylen,const struct sockcm_cookie * sockc)2569 static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
2570 void *frame, struct net_device *dev, void *data, int tp_len,
2571 __be16 proto, unsigned char *addr, int hlen, int copylen,
2572 const struct sockcm_cookie *sockc)
2573 {
2574 union tpacket_uhdr ph;
2575 int to_write, offset, len, nr_frags, len_max;
2576 struct socket *sock = po->sk.sk_socket;
2577 struct page *page;
2578 int err;
2579
2580 ph.raw = frame;
2581
2582 skb->protocol = proto;
2583 skb->dev = dev;
2584 skb->priority = sockc->priority;
2585 skb->mark = sockc->mark;
2586 skb_set_delivery_type_by_clockid(skb, sockc->transmit_time, po->sk.sk_clockid);
2587 skb_setup_tx_timestamp(skb, sockc);
2588 skb_zcopy_set_nouarg(skb, ph.raw);
2589
2590 skb_reserve(skb, hlen);
2591 skb_reset_network_header(skb);
2592
2593 to_write = tp_len;
2594
2595 if (sock->type == SOCK_DGRAM) {
2596 err = dev_hard_header(skb, dev, ntohs(proto), addr,
2597 NULL, tp_len);
2598 if (unlikely(err < 0))
2599 return -EINVAL;
2600 } else if (copylen) {
2601 int hdrlen = min_t(int, copylen, tp_len);
2602
2603 skb_push(skb, dev->hard_header_len);
2604 skb_put(skb, copylen - dev->hard_header_len);
2605 err = skb_store_bits(skb, 0, data, hdrlen);
2606 if (unlikely(err))
2607 return err;
2608 if (!dev_validate_header(dev, skb->data, hdrlen))
2609 return -EINVAL;
2610
2611 data += hdrlen;
2612 to_write -= hdrlen;
2613 }
2614
2615 offset = offset_in_page(data);
2616 len_max = PAGE_SIZE - offset;
2617 len = ((to_write > len_max) ? len_max : to_write);
2618
2619 skb->data_len = to_write;
2620 skb->len += to_write;
2621 skb->truesize += to_write;
2622 refcount_add(to_write, &po->sk.sk_wmem_alloc);
2623
2624 while (likely(to_write)) {
2625 nr_frags = skb_shinfo(skb)->nr_frags;
2626
2627 if (unlikely(nr_frags >= MAX_SKB_FRAGS)) {
2628 pr_err("Packet exceed the number of skb frags(%u)\n",
2629 (unsigned int)MAX_SKB_FRAGS);
2630 return -EFAULT;
2631 }
2632
2633 page = pgv_to_page(data);
2634 data += len;
2635 flush_dcache_page(page);
2636 get_page(page);
2637 skb_fill_page_desc(skb, nr_frags, page, offset, len);
2638 to_write -= len;
2639 offset = 0;
2640 len_max = PAGE_SIZE;
2641 len = ((to_write > len_max) ? len_max : to_write);
2642 }
2643
2644 packet_parse_headers(skb, sock);
2645
2646 return tp_len;
2647 }
2648
tpacket_parse_header(struct packet_sock * po,void * frame,int size_max,void ** data)2649 static int tpacket_parse_header(struct packet_sock *po, void *frame,
2650 int size_max, void **data)
2651 {
2652 union tpacket_uhdr ph;
2653 int tp_len, off;
2654
2655 ph.raw = frame;
2656
2657 switch (po->tp_version) {
2658 case TPACKET_V3:
2659 if (ph.h3->tp_next_offset != 0) {
2660 pr_warn_once("variable sized slot not supported");
2661 return -EINVAL;
2662 }
2663 tp_len = ph.h3->tp_len;
2664 break;
2665 case TPACKET_V2:
2666 tp_len = ph.h2->tp_len;
2667 break;
2668 default:
2669 tp_len = ph.h1->tp_len;
2670 break;
2671 }
2672 if (unlikely(tp_len > size_max)) {
2673 pr_err("packet size is too long (%d > %d)\n", tp_len, size_max);
2674 return -EMSGSIZE;
2675 }
2676
2677 if (unlikely(packet_sock_flag(po, PACKET_SOCK_TX_HAS_OFF))) {
2678 int off_min, off_max;
2679
2680 off_min = po->tp_hdrlen - sizeof(struct sockaddr_ll);
2681 off_max = po->tx_ring.frame_size - tp_len;
2682 if (po->sk.sk_type == SOCK_DGRAM) {
2683 switch (po->tp_version) {
2684 case TPACKET_V3:
2685 off = ph.h3->tp_net;
2686 break;
2687 case TPACKET_V2:
2688 off = ph.h2->tp_net;
2689 break;
2690 default:
2691 off = ph.h1->tp_net;
2692 break;
2693 }
2694 } else {
2695 switch (po->tp_version) {
2696 case TPACKET_V3:
2697 off = ph.h3->tp_mac;
2698 break;
2699 case TPACKET_V2:
2700 off = ph.h2->tp_mac;
2701 break;
2702 default:
2703 off = ph.h1->tp_mac;
2704 break;
2705 }
2706 }
2707 if (unlikely((off < off_min) || (off_max < off)))
2708 return -EINVAL;
2709 } else {
2710 off = po->tp_hdrlen - sizeof(struct sockaddr_ll);
2711 }
2712
2713 *data = frame + off;
2714 return tp_len;
2715 }
2716
tpacket_snd(struct packet_sock * po,struct msghdr * msg)2717 static int tpacket_snd(struct packet_sock *po, struct msghdr *msg)
2718 {
2719 struct sk_buff *skb = NULL;
2720 struct net_device *dev;
2721 struct virtio_net_hdr *vnet_hdr = NULL;
2722 struct sockcm_cookie sockc;
2723 __be16 proto;
2724 int err, reserve = 0;
2725 void *ph;
2726 DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name);
2727 bool need_wait = !(msg->msg_flags & MSG_DONTWAIT);
2728 int vnet_hdr_sz = READ_ONCE(po->vnet_hdr_sz);
2729 unsigned char *addr = NULL;
2730 int tp_len, size_max;
2731 void *data;
2732 int len_sum = 0;
2733 int status = TP_STATUS_AVAILABLE;
2734 int hlen, tlen, copylen = 0;
2735 long timeo;
2736
2737 mutex_lock(&po->pg_vec_lock);
2738
2739 /* packet_sendmsg() check on tx_ring.pg_vec was lockless,
2740 * we need to confirm it under protection of pg_vec_lock.
2741 */
2742 if (unlikely(!po->tx_ring.pg_vec)) {
2743 err = -EBUSY;
2744 goto out;
2745 }
2746 if (likely(saddr == NULL)) {
2747 dev = packet_cached_dev_get(po);
2748 proto = READ_ONCE(po->num);
2749 } else {
2750 err = -EINVAL;
2751 if (msg->msg_namelen < sizeof(struct sockaddr_ll))
2752 goto out;
2753 if (msg->msg_namelen < (saddr->sll_halen
2754 + offsetof(struct sockaddr_ll,
2755 sll_addr)))
2756 goto out;
2757 proto = saddr->sll_protocol;
2758 dev = dev_get_by_index(sock_net(&po->sk), saddr->sll_ifindex);
2759 if (po->sk.sk_socket->type == SOCK_DGRAM) {
2760 if (dev && msg->msg_namelen < dev->addr_len +
2761 offsetof(struct sockaddr_ll, sll_addr))
2762 goto out_put;
2763 addr = saddr->sll_addr;
2764 }
2765 }
2766
2767 err = -ENXIO;
2768 if (unlikely(dev == NULL))
2769 goto out;
2770 err = -ENETDOWN;
2771 if (unlikely(!(dev->flags & IFF_UP)))
2772 goto out_put;
2773
2774 sockcm_init(&sockc, &po->sk);
2775 if (msg->msg_controllen) {
2776 err = sock_cmsg_send(&po->sk, msg, &sockc);
2777 if (unlikely(err))
2778 goto out_put;
2779 }
2780
2781 if (po->sk.sk_socket->type == SOCK_RAW)
2782 reserve = dev->hard_header_len;
2783 size_max = po->tx_ring.frame_size
2784 - (po->tp_hdrlen - sizeof(struct sockaddr_ll));
2785
2786 if ((size_max > dev->mtu + reserve + VLAN_HLEN) && !vnet_hdr_sz)
2787 size_max = dev->mtu + reserve + VLAN_HLEN;
2788
2789 timeo = sock_sndtimeo(&po->sk, msg->msg_flags & MSG_DONTWAIT);
2790 reinit_completion(&po->skb_completion);
2791
2792 do {
2793 ph = packet_current_frame(po, &po->tx_ring,
2794 TP_STATUS_SEND_REQUEST);
2795 if (unlikely(ph == NULL)) {
2796 /* Note: packet_read_pending() might be slow if we
2797 * have to call it as it's per_cpu variable, but in
2798 * fast-path we don't have to call it, only when ph
2799 * is NULL, we need to check the pending_refcnt.
2800 */
2801 if (need_wait && packet_read_pending(&po->tx_ring)) {
2802 timeo = wait_for_completion_interruptible_timeout(&po->skb_completion, timeo);
2803 if (timeo <= 0) {
2804 err = !timeo ? -ETIMEDOUT : -ERESTARTSYS;
2805 goto out_put;
2806 }
2807 /* check for additional frames */
2808 continue;
2809 } else
2810 break;
2811 }
2812
2813 skb = NULL;
2814 tp_len = tpacket_parse_header(po, ph, size_max, &data);
2815 if (tp_len < 0)
2816 goto tpacket_error;
2817
2818 status = TP_STATUS_SEND_REQUEST;
2819 hlen = LL_RESERVED_SPACE(dev);
2820 tlen = dev->needed_tailroom;
2821 if (vnet_hdr_sz) {
2822 vnet_hdr = data;
2823 data += vnet_hdr_sz;
2824 tp_len -= vnet_hdr_sz;
2825 if (tp_len < 0 ||
2826 __packet_snd_vnet_parse(vnet_hdr, tp_len)) {
2827 tp_len = -EINVAL;
2828 goto tpacket_error;
2829 }
2830 copylen = __virtio16_to_cpu(vio_le(),
2831 vnet_hdr->hdr_len);
2832 }
2833 copylen = max_t(int, copylen, dev->hard_header_len);
2834 skb = sock_alloc_send_skb(&po->sk,
2835 hlen + tlen + sizeof(struct sockaddr_ll) +
2836 (copylen - dev->hard_header_len),
2837 !need_wait, &err);
2838
2839 if (unlikely(skb == NULL)) {
2840 /* we assume the socket was initially writeable ... */
2841 if (likely(len_sum > 0))
2842 err = len_sum;
2843 goto out_status;
2844 }
2845 tp_len = tpacket_fill_skb(po, skb, ph, dev, data, tp_len, proto,
2846 addr, hlen, copylen, &sockc);
2847 if (likely(tp_len >= 0) &&
2848 tp_len > dev->mtu + reserve &&
2849 !vnet_hdr_sz &&
2850 !packet_extra_vlan_len_allowed(dev, skb))
2851 tp_len = -EMSGSIZE;
2852
2853 if (unlikely(tp_len < 0)) {
2854 tpacket_error:
2855 if (packet_sock_flag(po, PACKET_SOCK_TP_LOSS)) {
2856 __packet_set_status(po, ph,
2857 TP_STATUS_AVAILABLE);
2858 packet_increment_head(&po->tx_ring);
2859 kfree_skb(skb);
2860 continue;
2861 } else {
2862 status = TP_STATUS_WRONG_FORMAT;
2863 err = tp_len;
2864 goto out_status;
2865 }
2866 }
2867
2868 if (vnet_hdr_sz) {
2869 if (virtio_net_hdr_to_skb(skb, vnet_hdr, vio_le())) {
2870 tp_len = -EINVAL;
2871 goto tpacket_error;
2872 }
2873 virtio_net_hdr_set_proto(skb, vnet_hdr);
2874 }
2875
2876 skb->destructor = tpacket_destruct_skb;
2877 __packet_set_status(po, ph, TP_STATUS_SENDING);
2878 packet_inc_pending(&po->tx_ring);
2879
2880 status = TP_STATUS_SEND_REQUEST;
2881 err = packet_xmit(po, skb);
2882 if (unlikely(err != 0)) {
2883 if (err > 0)
2884 err = net_xmit_errno(err);
2885 if (err && __packet_get_status(po, ph) ==
2886 TP_STATUS_AVAILABLE) {
2887 /* skb was destructed already */
2888 skb = NULL;
2889 goto out_status;
2890 }
2891 /*
2892 * skb was dropped but not destructed yet;
2893 * let's treat it like congestion or err < 0
2894 */
2895 err = 0;
2896 }
2897 packet_increment_head(&po->tx_ring);
2898 len_sum += tp_len;
2899 } while (1);
2900
2901 err = len_sum;
2902 goto out_put;
2903
2904 out_status:
2905 __packet_set_status(po, ph, status);
2906 kfree_skb(skb);
2907 out_put:
2908 dev_put(dev);
2909 out:
2910 mutex_unlock(&po->pg_vec_lock);
2911 return err;
2912 }
2913
packet_alloc_skb(struct sock * sk,size_t prepad,size_t reserve,size_t len,size_t linear,int noblock,int * err)2914 static struct sk_buff *packet_alloc_skb(struct sock *sk, size_t prepad,
2915 size_t reserve, size_t len,
2916 size_t linear, int noblock,
2917 int *err)
2918 {
2919 struct sk_buff *skb;
2920
2921 /* Under a page? Don't bother with paged skb. */
2922 if (prepad + len < PAGE_SIZE || !linear)
2923 linear = len;
2924
2925 if (len - linear > MAX_SKB_FRAGS * (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER))
2926 linear = len - MAX_SKB_FRAGS * (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER);
2927 skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
2928 err, PAGE_ALLOC_COSTLY_ORDER);
2929 if (!skb)
2930 return NULL;
2931
2932 skb_reserve(skb, reserve);
2933 skb_put(skb, linear);
2934 skb->data_len = len - linear;
2935 skb->len += len - linear;
2936
2937 return skb;
2938 }
2939
packet_snd(struct socket * sock,struct msghdr * msg,size_t len)2940 static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len)
2941 {
2942 struct sock *sk = sock->sk;
2943 DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name);
2944 struct sk_buff *skb;
2945 struct net_device *dev;
2946 __be16 proto;
2947 unsigned char *addr = NULL;
2948 int err, reserve = 0;
2949 struct sockcm_cookie sockc;
2950 struct virtio_net_hdr vnet_hdr = { 0 };
2951 int offset = 0;
2952 struct packet_sock *po = pkt_sk(sk);
2953 int vnet_hdr_sz = READ_ONCE(po->vnet_hdr_sz);
2954 int hlen, tlen, linear;
2955 int extra_len = 0;
2956
2957 /*
2958 * Get and verify the address.
2959 */
2960
2961 if (likely(saddr == NULL)) {
2962 dev = packet_cached_dev_get(po);
2963 proto = READ_ONCE(po->num);
2964 } else {
2965 err = -EINVAL;
2966 if (msg->msg_namelen < sizeof(struct sockaddr_ll))
2967 goto out;
2968 if (msg->msg_namelen < (saddr->sll_halen + offsetof(struct sockaddr_ll, sll_addr)))
2969 goto out;
2970 proto = saddr->sll_protocol;
2971 dev = dev_get_by_index(sock_net(sk), saddr->sll_ifindex);
2972 if (sock->type == SOCK_DGRAM) {
2973 if (dev && msg->msg_namelen < dev->addr_len +
2974 offsetof(struct sockaddr_ll, sll_addr))
2975 goto out_unlock;
2976 addr = saddr->sll_addr;
2977 }
2978 }
2979
2980 err = -ENXIO;
2981 if (unlikely(dev == NULL))
2982 goto out_unlock;
2983 err = -ENETDOWN;
2984 if (unlikely(!(dev->flags & IFF_UP)))
2985 goto out_unlock;
2986
2987 sockcm_init(&sockc, sk);
2988 if (msg->msg_controllen) {
2989 err = sock_cmsg_send(sk, msg, &sockc);
2990 if (unlikely(err))
2991 goto out_unlock;
2992 }
2993
2994 if (sock->type == SOCK_RAW)
2995 reserve = dev->hard_header_len;
2996 if (vnet_hdr_sz) {
2997 err = packet_snd_vnet_parse(msg, &len, &vnet_hdr, vnet_hdr_sz);
2998 if (err)
2999 goto out_unlock;
3000 }
3001
3002 if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
3003 if (!netif_supports_nofcs(dev)) {
3004 err = -EPROTONOSUPPORT;
3005 goto out_unlock;
3006 }
3007 extra_len = 4; /* We're doing our own CRC */
3008 }
3009
3010 err = -EMSGSIZE;
3011 if (!vnet_hdr.gso_type &&
3012 (len > dev->mtu + reserve + VLAN_HLEN + extra_len))
3013 goto out_unlock;
3014
3015 err = -ENOBUFS;
3016 hlen = LL_RESERVED_SPACE(dev);
3017 tlen = dev->needed_tailroom;
3018 linear = __virtio16_to_cpu(vio_le(), vnet_hdr.hdr_len);
3019 linear = max(linear, min_t(int, len, dev->hard_header_len));
3020 skb = packet_alloc_skb(sk, hlen + tlen, hlen, len, linear,
3021 msg->msg_flags & MSG_DONTWAIT, &err);
3022 if (skb == NULL)
3023 goto out_unlock;
3024
3025 skb_reset_network_header(skb);
3026
3027 err = -EINVAL;
3028 if (sock->type == SOCK_DGRAM) {
3029 offset = dev_hard_header(skb, dev, ntohs(proto), addr, NULL, len);
3030 if (unlikely(offset < 0))
3031 goto out_free;
3032 } else if (reserve) {
3033 skb_reserve(skb, -reserve);
3034 if (len < reserve + sizeof(struct ipv6hdr) &&
3035 dev->min_header_len != dev->hard_header_len)
3036 skb_reset_network_header(skb);
3037 }
3038
3039 /* Returns -EFAULT on error */
3040 err = skb_copy_datagram_from_iter(skb, offset, &msg->msg_iter, len);
3041 if (err)
3042 goto out_free;
3043
3044 if ((sock->type == SOCK_RAW &&
3045 !dev_validate_header(dev, skb->data, len)) || !skb->len) {
3046 err = -EINVAL;
3047 goto out_free;
3048 }
3049
3050 skb_setup_tx_timestamp(skb, &sockc);
3051
3052 if (!vnet_hdr.gso_type && (len > dev->mtu + reserve + extra_len) &&
3053 !packet_extra_vlan_len_allowed(dev, skb)) {
3054 err = -EMSGSIZE;
3055 goto out_free;
3056 }
3057
3058 skb->protocol = proto;
3059 skb->dev = dev;
3060 skb->priority = sockc.priority;
3061 skb->mark = sockc.mark;
3062 skb_set_delivery_type_by_clockid(skb, sockc.transmit_time, sk->sk_clockid);
3063
3064 if (unlikely(extra_len == 4))
3065 skb->no_fcs = 1;
3066
3067 packet_parse_headers(skb, sock);
3068
3069 if (vnet_hdr_sz) {
3070 err = virtio_net_hdr_to_skb(skb, &vnet_hdr, vio_le());
3071 if (err)
3072 goto out_free;
3073 len += vnet_hdr_sz;
3074 virtio_net_hdr_set_proto(skb, &vnet_hdr);
3075 }
3076
3077 err = packet_xmit(po, skb);
3078
3079 if (unlikely(err != 0)) {
3080 if (err > 0)
3081 err = net_xmit_errno(err);
3082 if (err)
3083 goto out_unlock;
3084 }
3085
3086 dev_put(dev);
3087
3088 return len;
3089
3090 out_free:
3091 kfree_skb(skb);
3092 out_unlock:
3093 dev_put(dev);
3094 out:
3095 return err;
3096 }
3097
packet_sendmsg(struct socket * sock,struct msghdr * msg,size_t len)3098 static int packet_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
3099 {
3100 struct sock *sk = sock->sk;
3101 struct packet_sock *po = pkt_sk(sk);
3102
3103 /* Reading tx_ring.pg_vec without holding pg_vec_lock is racy.
3104 * tpacket_snd() will redo the check safely.
3105 */
3106 if (data_race(po->tx_ring.pg_vec))
3107 return tpacket_snd(po, msg);
3108
3109 return packet_snd(sock, msg, len);
3110 }
3111
3112 /*
3113 * Close a PACKET socket. This is fairly simple. We immediately go
3114 * to 'closed' state and remove our protocol entry in the device list.
3115 */
3116
packet_release(struct socket * sock)3117 static int packet_release(struct socket *sock)
3118 {
3119 struct sock *sk = sock->sk;
3120 struct packet_sock *po;
3121 struct packet_fanout *f;
3122 struct net *net;
3123 union tpacket_req_u req_u;
3124
3125 if (!sk)
3126 return 0;
3127
3128 net = sock_net(sk);
3129 po = pkt_sk(sk);
3130
3131 mutex_lock(&net->packet.sklist_lock);
3132 sk_del_node_init_rcu(sk);
3133 mutex_unlock(&net->packet.sklist_lock);
3134
3135 sock_prot_inuse_add(net, sk->sk_prot, -1);
3136
3137 spin_lock(&po->bind_lock);
3138 unregister_prot_hook(sk, false);
3139 packet_cached_dev_reset(po);
3140
3141 if (po->prot_hook.dev) {
3142 netdev_put(po->prot_hook.dev, &po->prot_hook.dev_tracker);
3143 po->prot_hook.dev = NULL;
3144 }
3145 spin_unlock(&po->bind_lock);
3146
3147 packet_flush_mclist(sk);
3148
3149 lock_sock(sk);
3150 if (po->rx_ring.pg_vec) {
3151 memset(&req_u, 0, sizeof(req_u));
3152 packet_set_ring(sk, &req_u, 1, 0);
3153 }
3154
3155 if (po->tx_ring.pg_vec) {
3156 memset(&req_u, 0, sizeof(req_u));
3157 packet_set_ring(sk, &req_u, 1, 1);
3158 }
3159 release_sock(sk);
3160
3161 f = fanout_release(sk);
3162
3163 synchronize_net();
3164
3165 kfree(po->rollover);
3166 if (f) {
3167 fanout_release_data(f);
3168 kvfree(f);
3169 }
3170 /*
3171 * Now the socket is dead. No more input will appear.
3172 */
3173 sock_orphan(sk);
3174 sock->sk = NULL;
3175
3176 /* Purge queues */
3177
3178 skb_queue_purge(&sk->sk_receive_queue);
3179 packet_free_pending(po);
3180
3181 sock_put(sk);
3182 return 0;
3183 }
3184
3185 /*
3186 * Attach a packet hook.
3187 */
3188
packet_do_bind(struct sock * sk,const char * name,int ifindex,__be16 proto)3189 static int packet_do_bind(struct sock *sk, const char *name, int ifindex,
3190 __be16 proto)
3191 {
3192 struct packet_sock *po = pkt_sk(sk);
3193 struct net_device *dev = NULL;
3194 bool unlisted = false;
3195 bool need_rehook;
3196 int ret = 0;
3197
3198 lock_sock(sk);
3199 spin_lock(&po->bind_lock);
3200 if (!proto)
3201 proto = po->num;
3202
3203 rcu_read_lock();
3204
3205 if (po->fanout) {
3206 ret = -EINVAL;
3207 goto out_unlock;
3208 }
3209
3210 if (name) {
3211 dev = dev_get_by_name_rcu(sock_net(sk), name);
3212 if (!dev) {
3213 ret = -ENODEV;
3214 goto out_unlock;
3215 }
3216 } else if (ifindex) {
3217 dev = dev_get_by_index_rcu(sock_net(sk), ifindex);
3218 if (!dev) {
3219 ret = -ENODEV;
3220 goto out_unlock;
3221 }
3222 }
3223
3224 need_rehook = po->prot_hook.type != proto || po->prot_hook.dev != dev;
3225
3226 if (need_rehook) {
3227 dev_hold(dev);
3228 if (packet_sock_flag(po, PACKET_SOCK_RUNNING)) {
3229 rcu_read_unlock();
3230 /* prevents packet_notifier() from calling
3231 * register_prot_hook()
3232 */
3233 WRITE_ONCE(po->num, 0);
3234 __unregister_prot_hook(sk, true);
3235 rcu_read_lock();
3236 if (dev)
3237 unlisted = !dev_get_by_index_rcu(sock_net(sk),
3238 dev->ifindex);
3239 }
3240
3241 BUG_ON(packet_sock_flag(po, PACKET_SOCK_RUNNING));
3242 WRITE_ONCE(po->num, proto);
3243 po->prot_hook.type = proto;
3244
3245 netdev_put(po->prot_hook.dev, &po->prot_hook.dev_tracker);
3246
3247 if (unlikely(unlisted)) {
3248 po->prot_hook.dev = NULL;
3249 WRITE_ONCE(po->ifindex, -1);
3250 packet_cached_dev_reset(po);
3251 } else {
3252 netdev_hold(dev, &po->prot_hook.dev_tracker,
3253 GFP_ATOMIC);
3254 po->prot_hook.dev = dev;
3255 WRITE_ONCE(po->ifindex, dev ? dev->ifindex : 0);
3256 packet_cached_dev_assign(po, dev);
3257 }
3258 dev_put(dev);
3259 }
3260
3261 if (proto == 0 || !need_rehook)
3262 goto out_unlock;
3263
3264 if (!unlisted && (!dev || (dev->flags & IFF_UP))) {
3265 register_prot_hook(sk);
3266 } else {
3267 sk->sk_err = ENETDOWN;
3268 if (!sock_flag(sk, SOCK_DEAD))
3269 sk_error_report(sk);
3270 }
3271
3272 out_unlock:
3273 rcu_read_unlock();
3274 spin_unlock(&po->bind_lock);
3275 release_sock(sk);
3276 return ret;
3277 }
3278
3279 /*
3280 * Bind a packet socket to a device
3281 */
3282
packet_bind_spkt(struct socket * sock,struct sockaddr_unsized * uaddr,int addr_len)3283 static int packet_bind_spkt(struct socket *sock, struct sockaddr_unsized *uaddr,
3284 int addr_len)
3285 {
3286 struct sock *sk = sock->sk;
3287 struct sockaddr *sa = (struct sockaddr *)uaddr;
3288 char name[sizeof(sa->sa_data) + 1];
3289
3290 /*
3291 * Check legality
3292 */
3293
3294 if (addr_len != sizeof(struct sockaddr))
3295 return -EINVAL;
3296 /* uaddr->sa_data comes from the userspace, it's not guaranteed to be
3297 * zero-terminated.
3298 */
3299 memcpy(name, sa->sa_data, sizeof(sa->sa_data));
3300 name[sizeof(sa->sa_data)] = 0;
3301
3302 return packet_do_bind(sk, name, 0, 0);
3303 }
3304
packet_bind(struct socket * sock,struct sockaddr_unsized * uaddr,int addr_len)3305 static int packet_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int addr_len)
3306 {
3307 struct sockaddr_ll *sll = (struct sockaddr_ll *)uaddr;
3308 struct sock *sk = sock->sk;
3309
3310 /*
3311 * Check legality
3312 */
3313
3314 if (addr_len < sizeof(struct sockaddr_ll))
3315 return -EINVAL;
3316 if (sll->sll_family != AF_PACKET)
3317 return -EINVAL;
3318
3319 return packet_do_bind(sk, NULL, sll->sll_ifindex, sll->sll_protocol);
3320 }
3321
3322 static struct proto packet_proto = {
3323 .name = "PACKET",
3324 .owner = THIS_MODULE,
3325 .obj_size = sizeof(struct packet_sock),
3326 };
3327
3328 /*
3329 * Create a packet of type SOCK_PACKET.
3330 */
3331
packet_create(struct net * net,struct socket * sock,int protocol,int kern)3332 static int packet_create(struct net *net, struct socket *sock, int protocol,
3333 int kern)
3334 {
3335 struct sock *sk;
3336 struct packet_sock *po;
3337 __be16 proto = (__force __be16)protocol; /* weird, but documented */
3338 int err;
3339
3340 if (!ns_capable(net->user_ns, CAP_NET_RAW))
3341 return -EPERM;
3342 if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW &&
3343 sock->type != SOCK_PACKET)
3344 return -ESOCKTNOSUPPORT;
3345
3346 sock->state = SS_UNCONNECTED;
3347
3348 err = -ENOBUFS;
3349 sk = sk_alloc(net, PF_PACKET, GFP_KERNEL, &packet_proto, kern);
3350 if (sk == NULL)
3351 goto out;
3352
3353 sock->ops = &packet_ops;
3354 if (sock->type == SOCK_PACKET)
3355 sock->ops = &packet_ops_spkt;
3356
3357 po = pkt_sk(sk);
3358 err = packet_alloc_pending(po);
3359 if (err)
3360 goto out_sk_free;
3361
3362 sock_init_data(sock, sk);
3363
3364 init_completion(&po->skb_completion);
3365 sk->sk_family = PF_PACKET;
3366 po->num = proto;
3367
3368 packet_cached_dev_reset(po);
3369
3370 sk->sk_destruct = packet_sock_destruct;
3371
3372 /*
3373 * Attach a protocol block
3374 */
3375
3376 spin_lock_init(&po->bind_lock);
3377 mutex_init(&po->pg_vec_lock);
3378 po->rollover = NULL;
3379 po->prot_hook.func = packet_rcv;
3380
3381 if (sock->type == SOCK_PACKET)
3382 po->prot_hook.func = packet_rcv_spkt;
3383
3384 po->prot_hook.af_packet_priv = sk;
3385 po->prot_hook.af_packet_net = sock_net(sk);
3386
3387 if (proto) {
3388 po->prot_hook.type = proto;
3389 __register_prot_hook(sk);
3390 }
3391
3392 mutex_lock(&net->packet.sklist_lock);
3393 sk_add_node_tail_rcu(sk, &net->packet.sklist);
3394 mutex_unlock(&net->packet.sklist_lock);
3395
3396 sock_prot_inuse_add(net, &packet_proto, 1);
3397
3398 return 0;
3399 out_sk_free:
3400 sk_free(sk);
3401 out:
3402 return err;
3403 }
3404
3405 /*
3406 * Pull a packet from our receive queue and hand it to the user.
3407 * If necessary we block.
3408 */
3409
packet_recvmsg(struct socket * sock,struct msghdr * msg,size_t len,int flags)3410 static int packet_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
3411 int flags)
3412 {
3413 struct sock *sk = sock->sk;
3414 struct sk_buff *skb;
3415 int copied, err;
3416 int vnet_hdr_len = READ_ONCE(pkt_sk(sk)->vnet_hdr_sz);
3417 unsigned int origlen = 0;
3418
3419 err = -EINVAL;
3420 if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))
3421 goto out;
3422
3423 #if 0
3424 /* What error should we return now? EUNATTACH? */
3425 if (pkt_sk(sk)->ifindex < 0)
3426 return -ENODEV;
3427 #endif
3428
3429 if (flags & MSG_ERRQUEUE) {
3430 err = sock_recv_errqueue(sk, msg, len,
3431 SOL_PACKET, PACKET_TX_TIMESTAMP);
3432 goto out;
3433 }
3434
3435 /*
3436 * Call the generic datagram receiver. This handles all sorts
3437 * of horrible races and re-entrancy so we can forget about it
3438 * in the protocol layers.
3439 *
3440 * Now it will return ENETDOWN, if device have just gone down,
3441 * but then it will block.
3442 */
3443
3444 skb = skb_recv_datagram(sk, flags, &err);
3445
3446 /*
3447 * An error occurred so return it. Because skb_recv_datagram()
3448 * handles the blocking we don't see and worry about blocking
3449 * retries.
3450 */
3451
3452 if (skb == NULL)
3453 goto out;
3454
3455 packet_rcv_try_clear_pressure(pkt_sk(sk));
3456
3457 if (vnet_hdr_len) {
3458 err = packet_rcv_vnet(msg, skb, &len, vnet_hdr_len);
3459 if (err)
3460 goto out_free;
3461 }
3462
3463 /* You lose any data beyond the buffer you gave. If it worries
3464 * a user program they can ask the device for its MTU
3465 * anyway.
3466 */
3467 copied = skb->len;
3468 if (copied > len) {
3469 copied = len;
3470 msg->msg_flags |= MSG_TRUNC;
3471 }
3472
3473 err = skb_copy_datagram_msg(skb, 0, msg, copied);
3474 if (err)
3475 goto out_free;
3476
3477 if (sock->type != SOCK_PACKET) {
3478 struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
3479
3480 /* Original length was stored in sockaddr_ll fields */
3481 origlen = PACKET_SKB_CB(skb)->sa.origlen;
3482 sll->sll_family = AF_PACKET;
3483 sll->sll_protocol = (sock->type == SOCK_DGRAM) ?
3484 vlan_get_protocol_dgram(skb) : skb->protocol;
3485 }
3486
3487 sock_recv_cmsgs(msg, sk, skb);
3488
3489 if (msg->msg_name) {
3490 const size_t max_len = min(sizeof(skb->cb),
3491 sizeof(struct sockaddr_storage));
3492 int copy_len;
3493
3494 /* If the address length field is there to be filled
3495 * in, we fill it in now.
3496 */
3497 if (sock->type == SOCK_PACKET) {
3498 __sockaddr_check_size(sizeof(struct sockaddr_pkt));
3499 msg->msg_namelen = sizeof(struct sockaddr_pkt);
3500 copy_len = msg->msg_namelen;
3501 } else {
3502 struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
3503
3504 msg->msg_namelen = sll->sll_halen +
3505 offsetof(struct sockaddr_ll, sll_addr);
3506 copy_len = msg->msg_namelen;
3507 if (msg->msg_namelen < sizeof(struct sockaddr_ll)) {
3508 memset(msg->msg_name +
3509 offsetof(struct sockaddr_ll, sll_addr),
3510 0, sizeof(sll->sll_addr));
3511 msg->msg_namelen = sizeof(struct sockaddr_ll);
3512 }
3513 }
3514 if (WARN_ON_ONCE(copy_len > max_len)) {
3515 copy_len = max_len;
3516 msg->msg_namelen = copy_len;
3517 }
3518 memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa, copy_len);
3519 }
3520
3521 if (packet_sock_flag(pkt_sk(sk), PACKET_SOCK_AUXDATA)) {
3522 struct tpacket_auxdata aux;
3523
3524 aux.tp_status = TP_STATUS_USER;
3525 if (skb->ip_summed == CHECKSUM_PARTIAL)
3526 aux.tp_status |= TP_STATUS_CSUMNOTREADY;
3527 else if (skb->pkt_type != PACKET_OUTGOING &&
3528 skb_csum_unnecessary(skb))
3529 aux.tp_status |= TP_STATUS_CSUM_VALID;
3530 if (skb_is_gso(skb) && skb_is_gso_tcp(skb))
3531 aux.tp_status |= TP_STATUS_GSO_TCP;
3532
3533 aux.tp_len = origlen;
3534 aux.tp_snaplen = skb->len;
3535 aux.tp_mac = 0;
3536 aux.tp_net = skb_network_offset(skb);
3537 if (skb_vlan_tag_present(skb)) {
3538 aux.tp_vlan_tci = skb_vlan_tag_get(skb);
3539 aux.tp_vlan_tpid = ntohs(skb->vlan_proto);
3540 aux.tp_status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
3541 } else if (unlikely(sock->type == SOCK_DGRAM && eth_type_vlan(skb->protocol))) {
3542 struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
3543 struct net_device *dev;
3544
3545 rcu_read_lock();
3546 dev = dev_get_by_index_rcu(sock_net(sk), sll->sll_ifindex);
3547 if (dev) {
3548 aux.tp_vlan_tci = vlan_get_tci(skb, dev);
3549 aux.tp_vlan_tpid = ntohs(skb->protocol);
3550 aux.tp_status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
3551 } else {
3552 aux.tp_vlan_tci = 0;
3553 aux.tp_vlan_tpid = 0;
3554 }
3555 rcu_read_unlock();
3556 } else {
3557 aux.tp_vlan_tci = 0;
3558 aux.tp_vlan_tpid = 0;
3559 }
3560 put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);
3561 }
3562
3563 /*
3564 * Free or return the buffer as appropriate. Again this
3565 * hides all the races and re-entrancy issues from us.
3566 */
3567 err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);
3568
3569 out_free:
3570 skb_free_datagram(sk, skb);
3571 out:
3572 return err;
3573 }
3574
packet_getname_spkt(struct socket * sock,struct sockaddr * uaddr,int peer)3575 static int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr,
3576 int peer)
3577 {
3578 struct net_device *dev;
3579 struct sock *sk = sock->sk;
3580
3581 if (peer)
3582 return -EOPNOTSUPP;
3583
3584 uaddr->sa_family = AF_PACKET;
3585 memset(uaddr->sa_data, 0, sizeof(uaddr->sa_data));
3586 rcu_read_lock();
3587 dev = dev_get_by_index_rcu(sock_net(sk), READ_ONCE(pkt_sk(sk)->ifindex));
3588 if (dev)
3589 strscpy(uaddr->sa_data, dev->name, sizeof(uaddr->sa_data));
3590 rcu_read_unlock();
3591
3592 return sizeof(*uaddr);
3593 }
3594
packet_getname(struct socket * sock,struct sockaddr * uaddr,int peer)3595 static int packet_getname(struct socket *sock, struct sockaddr *uaddr,
3596 int peer)
3597 {
3598 struct net_device *dev;
3599 struct sock *sk = sock->sk;
3600 struct packet_sock *po = pkt_sk(sk);
3601 DECLARE_SOCKADDR(struct sockaddr_ll *, sll, uaddr);
3602 int ifindex;
3603
3604 if (peer)
3605 return -EOPNOTSUPP;
3606
3607 ifindex = READ_ONCE(po->ifindex);
3608 sll->sll_family = AF_PACKET;
3609 sll->sll_ifindex = ifindex;
3610 sll->sll_protocol = READ_ONCE(po->num);
3611 sll->sll_pkttype = 0;
3612 rcu_read_lock();
3613 dev = dev_get_by_index_rcu(sock_net(sk), ifindex);
3614 if (dev) {
3615 sll->sll_hatype = dev->type;
3616 sll->sll_halen = dev->addr_len;
3617
3618 /* Let __fortify_memcpy_chk() know the actual buffer size. */
3619 memcpy(((struct sockaddr_storage *)sll)->__data +
3620 offsetof(struct sockaddr_ll, sll_addr) -
3621 offsetofend(struct sockaddr_ll, sll_family),
3622 dev->dev_addr, dev->addr_len);
3623 } else {
3624 sll->sll_hatype = 0; /* Bad: we have no ARPHRD_UNSPEC */
3625 sll->sll_halen = 0;
3626 }
3627 rcu_read_unlock();
3628
3629 return offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen;
3630 }
3631
packet_dev_mc(struct net_device * dev,struct packet_mclist * i,int what)3632 static int packet_dev_mc(struct net_device *dev, struct packet_mclist *i,
3633 int what)
3634 {
3635 switch (i->type) {
3636 case PACKET_MR_MULTICAST:
3637 if (i->alen != dev->addr_len)
3638 return -EINVAL;
3639 if (what > 0)
3640 return dev_mc_add(dev, i->addr);
3641 else
3642 return dev_mc_del(dev, i->addr);
3643 break;
3644 case PACKET_MR_PROMISC:
3645 return dev_set_promiscuity(dev, what);
3646 case PACKET_MR_ALLMULTI:
3647 return dev_set_allmulti(dev, what);
3648 case PACKET_MR_UNICAST:
3649 if (i->alen != dev->addr_len)
3650 return -EINVAL;
3651 if (what > 0)
3652 return dev_uc_add(dev, i->addr);
3653 else
3654 return dev_uc_del(dev, i->addr);
3655 break;
3656 default:
3657 break;
3658 }
3659 return 0;
3660 }
3661
packet_dev_mclist_delete(struct net_device * dev,struct packet_mclist ** mlp,struct list_head * list)3662 static void packet_dev_mclist_delete(struct net_device *dev,
3663 struct packet_mclist **mlp,
3664 struct list_head *list)
3665 {
3666 struct packet_mclist *ml;
3667
3668 while ((ml = *mlp) != NULL) {
3669 if (ml->ifindex == dev->ifindex) {
3670 list_add(&ml->remove_list, list);
3671 *mlp = ml->next;
3672 } else
3673 mlp = &ml->next;
3674 }
3675 }
3676
packet_mc_add(struct sock * sk,struct packet_mreq_max * mreq)3677 static int packet_mc_add(struct sock *sk, struct packet_mreq_max *mreq)
3678 {
3679 struct packet_sock *po = pkt_sk(sk);
3680 struct packet_mclist *ml, *i;
3681 struct net_device *dev;
3682 int err;
3683
3684 rtnl_lock();
3685
3686 err = -ENODEV;
3687 dev = __dev_get_by_index(sock_net(sk), mreq->mr_ifindex);
3688 if (!dev)
3689 goto done;
3690
3691 err = -EINVAL;
3692 if (mreq->mr_alen > dev->addr_len)
3693 goto done;
3694
3695 err = -ENOBUFS;
3696 i = kmalloc_obj(*i, GFP_KERNEL);
3697 if (i == NULL)
3698 goto done;
3699
3700 err = 0;
3701 for (ml = po->mclist; ml; ml = ml->next) {
3702 if (ml->ifindex == mreq->mr_ifindex &&
3703 ml->type == mreq->mr_type &&
3704 ml->alen == mreq->mr_alen &&
3705 memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
3706 ml->count++;
3707 /* Free the new element ... */
3708 kfree(i);
3709 goto done;
3710 }
3711 }
3712
3713 i->type = mreq->mr_type;
3714 i->ifindex = mreq->mr_ifindex;
3715 i->alen = mreq->mr_alen;
3716 memcpy(i->addr, mreq->mr_address, i->alen);
3717 memset(i->addr + i->alen, 0, sizeof(i->addr) - i->alen);
3718 i->count = 1;
3719 INIT_LIST_HEAD(&i->remove_list);
3720 i->next = po->mclist;
3721 po->mclist = i;
3722 err = packet_dev_mc(dev, i, 1);
3723 if (err) {
3724 po->mclist = i->next;
3725 kfree(i);
3726 }
3727
3728 done:
3729 rtnl_unlock();
3730 return err;
3731 }
3732
packet_mc_drop(struct sock * sk,struct packet_mreq_max * mreq)3733 static int packet_mc_drop(struct sock *sk, struct packet_mreq_max *mreq)
3734 {
3735 struct packet_mclist *ml, **mlp;
3736
3737 rtnl_lock();
3738
3739 for (mlp = &pkt_sk(sk)->mclist; (ml = *mlp) != NULL; mlp = &ml->next) {
3740 if (ml->ifindex == mreq->mr_ifindex &&
3741 ml->type == mreq->mr_type &&
3742 ml->alen == mreq->mr_alen &&
3743 memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
3744 if (--ml->count == 0) {
3745 struct net_device *dev;
3746 *mlp = ml->next;
3747 dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3748 if (dev)
3749 packet_dev_mc(dev, ml, -1);
3750 kfree(ml);
3751 }
3752 break;
3753 }
3754 }
3755 rtnl_unlock();
3756 return 0;
3757 }
3758
packet_flush_mclist(struct sock * sk)3759 static void packet_flush_mclist(struct sock *sk)
3760 {
3761 struct packet_sock *po = pkt_sk(sk);
3762 struct packet_mclist *ml;
3763
3764 if (!po->mclist)
3765 return;
3766
3767 rtnl_lock();
3768 while ((ml = po->mclist) != NULL) {
3769 struct net_device *dev;
3770
3771 po->mclist = ml->next;
3772 dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3773 if (dev != NULL)
3774 packet_dev_mc(dev, ml, -1);
3775 kfree(ml);
3776 }
3777 rtnl_unlock();
3778 }
3779
3780 static int
packet_setsockopt(struct socket * sock,int level,int optname,sockptr_t optval,unsigned int optlen)3781 packet_setsockopt(struct socket *sock, int level, int optname, sockptr_t optval,
3782 unsigned int optlen)
3783 {
3784 struct sock *sk = sock->sk;
3785 struct packet_sock *po = pkt_sk(sk);
3786 int ret;
3787
3788 if (level != SOL_PACKET)
3789 return -ENOPROTOOPT;
3790
3791 switch (optname) {
3792 case PACKET_ADD_MEMBERSHIP:
3793 case PACKET_DROP_MEMBERSHIP:
3794 {
3795 struct packet_mreq_max mreq;
3796 int len = optlen;
3797 memset(&mreq, 0, sizeof(mreq));
3798 if (len < sizeof(struct packet_mreq))
3799 return -EINVAL;
3800 if (len > sizeof(mreq))
3801 len = sizeof(mreq);
3802 if (copy_from_sockptr(&mreq, optval, len))
3803 return -EFAULT;
3804 if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address)))
3805 return -EINVAL;
3806 if (optname == PACKET_ADD_MEMBERSHIP)
3807 ret = packet_mc_add(sk, &mreq);
3808 else
3809 ret = packet_mc_drop(sk, &mreq);
3810 return ret;
3811 }
3812
3813 case PACKET_RX_RING:
3814 case PACKET_TX_RING:
3815 {
3816 union tpacket_req_u req_u;
3817
3818 ret = -EINVAL;
3819 lock_sock(sk);
3820 switch (po->tp_version) {
3821 case TPACKET_V1:
3822 case TPACKET_V2:
3823 if (optlen < sizeof(req_u.req))
3824 break;
3825 ret = copy_from_sockptr(&req_u.req, optval,
3826 sizeof(req_u.req)) ?
3827 -EINVAL : 0;
3828 break;
3829 case TPACKET_V3:
3830 default:
3831 if (optlen < sizeof(req_u.req3))
3832 break;
3833 ret = copy_from_sockptr(&req_u.req3, optval,
3834 sizeof(req_u.req3)) ?
3835 -EINVAL : 0;
3836 break;
3837 }
3838 if (!ret)
3839 ret = packet_set_ring(sk, &req_u, 0,
3840 optname == PACKET_TX_RING);
3841 release_sock(sk);
3842 return ret;
3843 }
3844 case PACKET_COPY_THRESH:
3845 {
3846 int val;
3847
3848 if (optlen != sizeof(val))
3849 return -EINVAL;
3850 if (copy_from_sockptr(&val, optval, sizeof(val)))
3851 return -EFAULT;
3852
3853 WRITE_ONCE(pkt_sk(sk)->copy_thresh, val);
3854 return 0;
3855 }
3856 case PACKET_VERSION:
3857 {
3858 int val;
3859
3860 if (optlen != sizeof(val))
3861 return -EINVAL;
3862 if (copy_from_sockptr(&val, optval, sizeof(val)))
3863 return -EFAULT;
3864 switch (val) {
3865 case TPACKET_V1:
3866 case TPACKET_V2:
3867 case TPACKET_V3:
3868 break;
3869 default:
3870 return -EINVAL;
3871 }
3872 lock_sock(sk);
3873 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
3874 ret = -EBUSY;
3875 } else {
3876 po->tp_version = val;
3877 ret = 0;
3878 }
3879 release_sock(sk);
3880 return ret;
3881 }
3882 case PACKET_RESERVE:
3883 {
3884 unsigned int val;
3885
3886 if (optlen != sizeof(val))
3887 return -EINVAL;
3888 if (copy_from_sockptr(&val, optval, sizeof(val)))
3889 return -EFAULT;
3890 if (val > INT_MAX)
3891 return -EINVAL;
3892 lock_sock(sk);
3893 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
3894 ret = -EBUSY;
3895 } else {
3896 po->tp_reserve = val;
3897 ret = 0;
3898 }
3899 release_sock(sk);
3900 return ret;
3901 }
3902 case PACKET_LOSS:
3903 {
3904 unsigned int val;
3905
3906 if (optlen != sizeof(val))
3907 return -EINVAL;
3908 if (copy_from_sockptr(&val, optval, sizeof(val)))
3909 return -EFAULT;
3910
3911 lock_sock(sk);
3912 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
3913 ret = -EBUSY;
3914 } else {
3915 packet_sock_flag_set(po, PACKET_SOCK_TP_LOSS, val);
3916 ret = 0;
3917 }
3918 release_sock(sk);
3919 return ret;
3920 }
3921 case PACKET_AUXDATA:
3922 {
3923 int val;
3924
3925 if (optlen < sizeof(val))
3926 return -EINVAL;
3927 if (copy_from_sockptr(&val, optval, sizeof(val)))
3928 return -EFAULT;
3929
3930 packet_sock_flag_set(po, PACKET_SOCK_AUXDATA, val);
3931 return 0;
3932 }
3933 case PACKET_ORIGDEV:
3934 {
3935 int val;
3936
3937 if (optlen < sizeof(val))
3938 return -EINVAL;
3939 if (copy_from_sockptr(&val, optval, sizeof(val)))
3940 return -EFAULT;
3941
3942 packet_sock_flag_set(po, PACKET_SOCK_ORIGDEV, val);
3943 return 0;
3944 }
3945 case PACKET_VNET_HDR:
3946 case PACKET_VNET_HDR_SZ:
3947 {
3948 int val, hdr_len;
3949
3950 if (sock->type != SOCK_RAW)
3951 return -EINVAL;
3952 if (optlen < sizeof(val))
3953 return -EINVAL;
3954 if (copy_from_sockptr(&val, optval, sizeof(val)))
3955 return -EFAULT;
3956
3957 if (optname == PACKET_VNET_HDR_SZ) {
3958 if (val && val != sizeof(struct virtio_net_hdr) &&
3959 val != sizeof(struct virtio_net_hdr_mrg_rxbuf))
3960 return -EINVAL;
3961 hdr_len = val;
3962 } else {
3963 hdr_len = val ? sizeof(struct virtio_net_hdr) : 0;
3964 }
3965 lock_sock(sk);
3966 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
3967 ret = -EBUSY;
3968 } else {
3969 WRITE_ONCE(po->vnet_hdr_sz, hdr_len);
3970 ret = 0;
3971 }
3972 release_sock(sk);
3973 return ret;
3974 }
3975 case PACKET_TIMESTAMP:
3976 {
3977 int val;
3978
3979 if (optlen != sizeof(val))
3980 return -EINVAL;
3981 if (copy_from_sockptr(&val, optval, sizeof(val)))
3982 return -EFAULT;
3983
3984 WRITE_ONCE(po->tp_tstamp, val);
3985 return 0;
3986 }
3987 case PACKET_FANOUT:
3988 {
3989 struct fanout_args args = { 0 };
3990
3991 if (optlen != sizeof(int) && optlen != sizeof(args))
3992 return -EINVAL;
3993 if (copy_from_sockptr(&args, optval, optlen))
3994 return -EFAULT;
3995
3996 return fanout_add(sk, &args);
3997 }
3998 case PACKET_FANOUT_DATA:
3999 {
4000 /* Paired with the WRITE_ONCE() in fanout_add() */
4001 if (!READ_ONCE(po->fanout))
4002 return -EINVAL;
4003
4004 return fanout_set_data(po, optval, optlen);
4005 }
4006 case PACKET_IGNORE_OUTGOING:
4007 {
4008 int val;
4009
4010 if (optlen != sizeof(val))
4011 return -EINVAL;
4012 if (copy_from_sockptr(&val, optval, sizeof(val)))
4013 return -EFAULT;
4014 if (val < 0 || val > 1)
4015 return -EINVAL;
4016
4017 WRITE_ONCE(po->prot_hook.ignore_outgoing, !!val);
4018 return 0;
4019 }
4020 case PACKET_TX_HAS_OFF:
4021 {
4022 unsigned int val;
4023
4024 if (optlen != sizeof(val))
4025 return -EINVAL;
4026 if (copy_from_sockptr(&val, optval, sizeof(val)))
4027 return -EFAULT;
4028
4029 lock_sock(sk);
4030 if (!po->rx_ring.pg_vec && !po->tx_ring.pg_vec)
4031 packet_sock_flag_set(po, PACKET_SOCK_TX_HAS_OFF, val);
4032
4033 release_sock(sk);
4034 return 0;
4035 }
4036 case PACKET_QDISC_BYPASS:
4037 {
4038 int val;
4039
4040 if (optlen != sizeof(val))
4041 return -EINVAL;
4042 if (copy_from_sockptr(&val, optval, sizeof(val)))
4043 return -EFAULT;
4044
4045 packet_sock_flag_set(po, PACKET_SOCK_QDISC_BYPASS, val);
4046 return 0;
4047 }
4048 default:
4049 return -ENOPROTOOPT;
4050 }
4051 }
4052
packet_getsockopt(struct socket * sock,int level,int optname,char __user * optval,int __user * optlen)4053 static int packet_getsockopt(struct socket *sock, int level, int optname,
4054 char __user *optval, int __user *optlen)
4055 {
4056 int len;
4057 int val, lv = sizeof(val);
4058 struct sock *sk = sock->sk;
4059 struct packet_sock *po = pkt_sk(sk);
4060 void *data = &val;
4061 union tpacket_stats_u st;
4062 struct tpacket_rollover_stats rstats;
4063 int drops;
4064
4065 if (level != SOL_PACKET)
4066 return -ENOPROTOOPT;
4067
4068 if (get_user(len, optlen))
4069 return -EFAULT;
4070
4071 if (len < 0)
4072 return -EINVAL;
4073
4074 switch (optname) {
4075 case PACKET_STATISTICS:
4076 spin_lock_bh(&sk->sk_receive_queue.lock);
4077 memcpy(&st, &po->stats, sizeof(st));
4078 memset(&po->stats, 0, sizeof(po->stats));
4079 spin_unlock_bh(&sk->sk_receive_queue.lock);
4080 drops = atomic_xchg(&po->tp_drops, 0);
4081
4082 if (po->tp_version == TPACKET_V3) {
4083 lv = sizeof(struct tpacket_stats_v3);
4084 st.stats3.tp_drops = drops;
4085 st.stats3.tp_packets += drops;
4086 data = &st.stats3;
4087 } else {
4088 lv = sizeof(struct tpacket_stats);
4089 st.stats1.tp_drops = drops;
4090 st.stats1.tp_packets += drops;
4091 data = &st.stats1;
4092 }
4093
4094 break;
4095 case PACKET_AUXDATA:
4096 val = packet_sock_flag(po, PACKET_SOCK_AUXDATA);
4097 break;
4098 case PACKET_ORIGDEV:
4099 val = packet_sock_flag(po, PACKET_SOCK_ORIGDEV);
4100 break;
4101 case PACKET_VNET_HDR:
4102 val = !!READ_ONCE(po->vnet_hdr_sz);
4103 break;
4104 case PACKET_VNET_HDR_SZ:
4105 val = READ_ONCE(po->vnet_hdr_sz);
4106 break;
4107 case PACKET_COPY_THRESH:
4108 val = READ_ONCE(pkt_sk(sk)->copy_thresh);
4109 break;
4110 case PACKET_VERSION:
4111 val = po->tp_version;
4112 break;
4113 case PACKET_HDRLEN:
4114 if (len > sizeof(int))
4115 len = sizeof(int);
4116 if (len < sizeof(int))
4117 return -EINVAL;
4118 if (copy_from_user(&val, optval, len))
4119 return -EFAULT;
4120 switch (val) {
4121 case TPACKET_V1:
4122 val = sizeof(struct tpacket_hdr);
4123 break;
4124 case TPACKET_V2:
4125 val = sizeof(struct tpacket2_hdr);
4126 break;
4127 case TPACKET_V3:
4128 val = sizeof(struct tpacket3_hdr);
4129 break;
4130 default:
4131 return -EINVAL;
4132 }
4133 break;
4134 case PACKET_RESERVE:
4135 val = po->tp_reserve;
4136 break;
4137 case PACKET_LOSS:
4138 val = packet_sock_flag(po, PACKET_SOCK_TP_LOSS);
4139 break;
4140 case PACKET_TIMESTAMP:
4141 val = READ_ONCE(po->tp_tstamp);
4142 break;
4143 case PACKET_FANOUT:
4144 val = (po->fanout ?
4145 ((u32)po->fanout->id |
4146 ((u32)po->fanout->type << 16) |
4147 ((u32)po->fanout->flags << 24)) :
4148 0);
4149 break;
4150 case PACKET_IGNORE_OUTGOING:
4151 val = READ_ONCE(po->prot_hook.ignore_outgoing);
4152 break;
4153 case PACKET_ROLLOVER_STATS:
4154 if (!po->rollover)
4155 return -EINVAL;
4156 rstats.tp_all = atomic_long_read(&po->rollover->num);
4157 rstats.tp_huge = atomic_long_read(&po->rollover->num_huge);
4158 rstats.tp_failed = atomic_long_read(&po->rollover->num_failed);
4159 data = &rstats;
4160 lv = sizeof(rstats);
4161 break;
4162 case PACKET_TX_HAS_OFF:
4163 val = packet_sock_flag(po, PACKET_SOCK_TX_HAS_OFF);
4164 break;
4165 case PACKET_QDISC_BYPASS:
4166 val = packet_sock_flag(po, PACKET_SOCK_QDISC_BYPASS);
4167 break;
4168 default:
4169 return -ENOPROTOOPT;
4170 }
4171
4172 if (len > lv)
4173 len = lv;
4174 if (put_user(len, optlen))
4175 return -EFAULT;
4176 if (copy_to_user(optval, data, len))
4177 return -EFAULT;
4178 return 0;
4179 }
4180
packet_notifier(struct notifier_block * this,unsigned long msg,void * ptr)4181 static int packet_notifier(struct notifier_block *this,
4182 unsigned long msg, void *ptr)
4183 {
4184 struct net_device *dev = netdev_notifier_info_to_dev(ptr);
4185 struct net *net = dev_net(dev);
4186 struct packet_mclist *ml, *tmp;
4187 LIST_HEAD(mclist);
4188 struct sock *sk;
4189
4190 rcu_read_lock();
4191 sk_for_each_rcu(sk, &net->packet.sklist) {
4192 struct packet_sock *po = pkt_sk(sk);
4193
4194 switch (msg) {
4195 case NETDEV_UNREGISTER:
4196 if (po->mclist)
4197 packet_dev_mclist_delete(dev, &po->mclist,
4198 &mclist);
4199 fallthrough;
4200
4201 case NETDEV_DOWN:
4202 if (dev->ifindex == po->ifindex) {
4203 spin_lock(&po->bind_lock);
4204 if (packet_sock_flag(po, PACKET_SOCK_RUNNING)) {
4205 __unregister_prot_hook(sk, false);
4206 sk->sk_err = ENETDOWN;
4207 if (!sock_flag(sk, SOCK_DEAD))
4208 sk_error_report(sk);
4209 }
4210 if (msg == NETDEV_UNREGISTER) {
4211 packet_cached_dev_reset(po);
4212 WRITE_ONCE(po->ifindex, -1);
4213 netdev_put(po->prot_hook.dev,
4214 &po->prot_hook.dev_tracker);
4215 po->prot_hook.dev = NULL;
4216 }
4217 spin_unlock(&po->bind_lock);
4218 }
4219 break;
4220 case NETDEV_UP:
4221 if (dev->ifindex == po->ifindex) {
4222 spin_lock(&po->bind_lock);
4223 if (po->num)
4224 register_prot_hook(sk);
4225 spin_unlock(&po->bind_lock);
4226 }
4227 break;
4228 }
4229 }
4230 rcu_read_unlock();
4231
4232 /* packet_dev_mc might grab instance locks so can't run under rcu */
4233 list_for_each_entry_safe(ml, tmp, &mclist, remove_list) {
4234 packet_dev_mc(dev, ml, -1);
4235 kfree(ml);
4236 }
4237
4238 return NOTIFY_DONE;
4239 }
4240
4241
packet_ioctl(struct socket * sock,unsigned int cmd,unsigned long arg)4242 static int packet_ioctl(struct socket *sock, unsigned int cmd,
4243 unsigned long arg)
4244 {
4245 struct sock *sk = sock->sk;
4246
4247 switch (cmd) {
4248 case SIOCOUTQ:
4249 {
4250 int amount = sk_wmem_alloc_get(sk);
4251
4252 return put_user(amount, (int __user *)arg);
4253 }
4254 case SIOCINQ:
4255 {
4256 struct sk_buff *skb;
4257 int amount = 0;
4258
4259 spin_lock_bh(&sk->sk_receive_queue.lock);
4260 skb = skb_peek(&sk->sk_receive_queue);
4261 if (skb)
4262 amount = skb->len;
4263 spin_unlock_bh(&sk->sk_receive_queue.lock);
4264 return put_user(amount, (int __user *)arg);
4265 }
4266 #ifdef CONFIG_INET
4267 case SIOCADDRT:
4268 case SIOCDELRT:
4269 case SIOCDARP:
4270 case SIOCGARP:
4271 case SIOCSARP:
4272 case SIOCGIFADDR:
4273 case SIOCSIFADDR:
4274 case SIOCGIFBRDADDR:
4275 case SIOCSIFBRDADDR:
4276 case SIOCGIFNETMASK:
4277 case SIOCSIFNETMASK:
4278 case SIOCGIFDSTADDR:
4279 case SIOCSIFDSTADDR:
4280 case SIOCSIFFLAGS:
4281 return inet_dgram_ops.ioctl(sock, cmd, arg);
4282 #endif
4283
4284 default:
4285 return -ENOIOCTLCMD;
4286 }
4287 return 0;
4288 }
4289
packet_poll(struct file * file,struct socket * sock,poll_table * wait)4290 static __poll_t packet_poll(struct file *file, struct socket *sock,
4291 poll_table *wait)
4292 {
4293 struct sock *sk = sock->sk;
4294 struct packet_sock *po = pkt_sk(sk);
4295 __poll_t mask = datagram_poll(file, sock, wait);
4296
4297 spin_lock_bh(&sk->sk_receive_queue.lock);
4298 if (po->rx_ring.pg_vec) {
4299 if (!packet_previous_rx_frame(po, &po->rx_ring,
4300 TP_STATUS_KERNEL))
4301 mask |= EPOLLIN | EPOLLRDNORM;
4302 }
4303 packet_rcv_try_clear_pressure(po);
4304 spin_unlock_bh(&sk->sk_receive_queue.lock);
4305 spin_lock_bh(&sk->sk_write_queue.lock);
4306 if (po->tx_ring.pg_vec) {
4307 if (packet_current_frame(po, &po->tx_ring, TP_STATUS_AVAILABLE))
4308 mask |= EPOLLOUT | EPOLLWRNORM;
4309 }
4310 spin_unlock_bh(&sk->sk_write_queue.lock);
4311 return mask;
4312 }
4313
4314
4315 /* Dirty? Well, I still did not learn better way to account
4316 * for user mmaps.
4317 */
4318
packet_mm_open(struct vm_area_struct * vma)4319 static void packet_mm_open(struct vm_area_struct *vma)
4320 {
4321 struct file *file = vma->vm_file;
4322 struct socket *sock = file->private_data;
4323 struct sock *sk = sock->sk;
4324
4325 if (sk)
4326 atomic_long_inc(&pkt_sk(sk)->mapped);
4327 }
4328
packet_mm_close(struct vm_area_struct * vma)4329 static void packet_mm_close(struct vm_area_struct *vma)
4330 {
4331 struct file *file = vma->vm_file;
4332 struct socket *sock = file->private_data;
4333 struct sock *sk = sock->sk;
4334
4335 if (sk)
4336 atomic_long_dec(&pkt_sk(sk)->mapped);
4337 }
4338
4339 static const struct vm_operations_struct packet_mmap_ops = {
4340 .open = packet_mm_open,
4341 .close = packet_mm_close,
4342 };
4343
free_pg_vec(struct pgv * pg_vec,unsigned int order,unsigned int len)4344 static void free_pg_vec(struct pgv *pg_vec, unsigned int order,
4345 unsigned int len)
4346 {
4347 int i;
4348
4349 for (i = 0; i < len; i++) {
4350 if (likely(pg_vec[i].buffer)) {
4351 if (is_vmalloc_addr(pg_vec[i].buffer))
4352 vfree(pg_vec[i].buffer);
4353 else
4354 free_pages((unsigned long)pg_vec[i].buffer,
4355 order);
4356 pg_vec[i].buffer = NULL;
4357 }
4358 }
4359 kfree(pg_vec);
4360 }
4361
alloc_one_pg_vec_page(unsigned long order)4362 static char *alloc_one_pg_vec_page(unsigned long order)
4363 {
4364 char *buffer;
4365 gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
4366 __GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
4367
4368 buffer = (char *) __get_free_pages(gfp_flags, order);
4369 if (buffer)
4370 return buffer;
4371
4372 /* __get_free_pages failed, fall back to vmalloc */
4373 buffer = vzalloc(array_size((1 << order), PAGE_SIZE));
4374 if (buffer)
4375 return buffer;
4376
4377 /* vmalloc failed, lets dig into swap here */
4378 gfp_flags &= ~__GFP_NORETRY;
4379 buffer = (char *) __get_free_pages(gfp_flags, order);
4380 if (buffer)
4381 return buffer;
4382
4383 /* complete and utter failure */
4384 return NULL;
4385 }
4386
alloc_pg_vec(struct tpacket_req * req,int order)4387 static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
4388 {
4389 unsigned int block_nr = req->tp_block_nr;
4390 struct pgv *pg_vec;
4391 int i;
4392
4393 pg_vec = kzalloc_objs(struct pgv, block_nr, GFP_KERNEL | __GFP_NOWARN);
4394 if (unlikely(!pg_vec))
4395 goto out;
4396
4397 for (i = 0; i < block_nr; i++) {
4398 pg_vec[i].buffer = alloc_one_pg_vec_page(order);
4399 if (unlikely(!pg_vec[i].buffer))
4400 goto out_free_pgvec;
4401 }
4402
4403 out:
4404 return pg_vec;
4405
4406 out_free_pgvec:
4407 free_pg_vec(pg_vec, order, block_nr);
4408 pg_vec = NULL;
4409 goto out;
4410 }
4411
packet_set_ring(struct sock * sk,union tpacket_req_u * req_u,int closing,int tx_ring)4412 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
4413 int closing, int tx_ring)
4414 {
4415 struct pgv *pg_vec = NULL;
4416 struct packet_sock *po = pkt_sk(sk);
4417 unsigned long *rx_owner_map = NULL;
4418 int was_running, order = 0;
4419 struct packet_ring_buffer *rb;
4420 struct sk_buff_head *rb_queue;
4421 __be16 num;
4422 int err;
4423 /* Added to avoid minimal code churn */
4424 struct tpacket_req *req = &req_u->req;
4425
4426 rb = tx_ring ? &po->tx_ring : &po->rx_ring;
4427 rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
4428
4429 err = -EBUSY;
4430 if (!closing) {
4431 if (atomic_long_read(&po->mapped))
4432 goto out;
4433 if (packet_read_pending(rb))
4434 goto out;
4435 }
4436
4437 if (req->tp_block_nr) {
4438 unsigned int min_frame_size;
4439
4440 /* Sanity tests and some calculations */
4441 err = -EBUSY;
4442 if (unlikely(rb->pg_vec))
4443 goto out;
4444
4445 switch (po->tp_version) {
4446 case TPACKET_V1:
4447 po->tp_hdrlen = TPACKET_HDRLEN;
4448 break;
4449 case TPACKET_V2:
4450 po->tp_hdrlen = TPACKET2_HDRLEN;
4451 break;
4452 case TPACKET_V3:
4453 po->tp_hdrlen = TPACKET3_HDRLEN;
4454 break;
4455 }
4456
4457 err = -EINVAL;
4458 if (unlikely((int)req->tp_block_size <= 0))
4459 goto out;
4460 if (unlikely(!PAGE_ALIGNED(req->tp_block_size)))
4461 goto out;
4462 min_frame_size = po->tp_hdrlen + po->tp_reserve;
4463 if (po->tp_version >= TPACKET_V3 &&
4464 req->tp_block_size <
4465 BLK_PLUS_PRIV((u64)req_u->req3.tp_sizeof_priv) + min_frame_size)
4466 goto out;
4467 if (unlikely(req->tp_frame_size < min_frame_size))
4468 goto out;
4469 if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1)))
4470 goto out;
4471
4472 rb->frames_per_block = req->tp_block_size / req->tp_frame_size;
4473 if (unlikely(rb->frames_per_block == 0))
4474 goto out;
4475 if (unlikely(rb->frames_per_block > UINT_MAX / req->tp_block_nr))
4476 goto out;
4477 if (unlikely((rb->frames_per_block * req->tp_block_nr) !=
4478 req->tp_frame_nr))
4479 goto out;
4480
4481 err = -ENOMEM;
4482 order = get_order(req->tp_block_size);
4483 pg_vec = alloc_pg_vec(req, order);
4484 if (unlikely(!pg_vec))
4485 goto out;
4486 switch (po->tp_version) {
4487 case TPACKET_V3:
4488 /* Block transmit is not supported yet */
4489 if (!tx_ring) {
4490 init_prb_bdqc(po, rb, pg_vec, req_u);
4491 } else {
4492 struct tpacket_req3 *req3 = &req_u->req3;
4493
4494 if (req3->tp_retire_blk_tov ||
4495 req3->tp_sizeof_priv ||
4496 req3->tp_feature_req_word) {
4497 err = -EINVAL;
4498 goto out_free_pg_vec;
4499 }
4500 }
4501 break;
4502 default:
4503 if (!tx_ring) {
4504 rx_owner_map = bitmap_alloc(req->tp_frame_nr,
4505 GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO);
4506 if (!rx_owner_map)
4507 goto out_free_pg_vec;
4508 }
4509 break;
4510 }
4511 }
4512 /* Done */
4513 else {
4514 err = -EINVAL;
4515 if (unlikely(req->tp_frame_nr))
4516 goto out;
4517 }
4518
4519
4520 /* Detach socket from network */
4521 spin_lock(&po->bind_lock);
4522 was_running = packet_sock_flag(po, PACKET_SOCK_RUNNING);
4523 num = po->num;
4524 WRITE_ONCE(po->num, 0);
4525 if (was_running)
4526 __unregister_prot_hook(sk, false);
4527
4528 spin_unlock(&po->bind_lock);
4529
4530 synchronize_net();
4531
4532 err = -EBUSY;
4533 mutex_lock(&po->pg_vec_lock);
4534 if (closing || atomic_long_read(&po->mapped) == 0) {
4535 err = 0;
4536 spin_lock_bh(&rb_queue->lock);
4537 swap(rb->pg_vec, pg_vec);
4538 if (po->tp_version <= TPACKET_V2)
4539 swap(rb->rx_owner_map, rx_owner_map);
4540 rb->frame_max = (req->tp_frame_nr - 1);
4541 rb->head = 0;
4542 rb->frame_size = req->tp_frame_size;
4543 spin_unlock_bh(&rb_queue->lock);
4544
4545 swap(rb->pg_vec_order, order);
4546 swap(rb->pg_vec_len, req->tp_block_nr);
4547
4548 rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE;
4549 po->prot_hook.func = (po->rx_ring.pg_vec) ?
4550 tpacket_rcv : packet_rcv;
4551 skb_queue_purge(rb_queue);
4552 if (atomic_long_read(&po->mapped))
4553 pr_err("packet_mmap: vma is busy: %ld\n",
4554 atomic_long_read(&po->mapped));
4555 }
4556 mutex_unlock(&po->pg_vec_lock);
4557
4558 spin_lock(&po->bind_lock);
4559 WRITE_ONCE(po->num, num);
4560 if (was_running)
4561 register_prot_hook(sk);
4562
4563 spin_unlock(&po->bind_lock);
4564 if (pg_vec && (po->tp_version > TPACKET_V2)) {
4565 /* Because we don't support block-based V3 on tx-ring */
4566 if (!tx_ring)
4567 prb_shutdown_retire_blk_timer(po, rb_queue);
4568 }
4569
4570 out_free_pg_vec:
4571 if (pg_vec) {
4572 bitmap_free(rx_owner_map);
4573 free_pg_vec(pg_vec, order, req->tp_block_nr);
4574 }
4575 out:
4576 return err;
4577 }
4578
packet_mmap(struct file * file,struct socket * sock,struct vm_area_struct * vma)4579 static int packet_mmap(struct file *file, struct socket *sock,
4580 struct vm_area_struct *vma)
4581 {
4582 struct sock *sk = sock->sk;
4583 struct packet_sock *po = pkt_sk(sk);
4584 unsigned long size, expected_size;
4585 struct packet_ring_buffer *rb;
4586 unsigned long start;
4587 int err = -EINVAL;
4588 int i;
4589
4590 if (vma->vm_pgoff)
4591 return -EINVAL;
4592
4593 mutex_lock(&po->pg_vec_lock);
4594
4595 expected_size = 0;
4596 for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
4597 if (rb->pg_vec) {
4598 expected_size += rb->pg_vec_len
4599 * rb->pg_vec_pages
4600 * PAGE_SIZE;
4601 }
4602 }
4603
4604 if (expected_size == 0)
4605 goto out;
4606
4607 size = vma->vm_end - vma->vm_start;
4608 if (size != expected_size)
4609 goto out;
4610
4611 start = vma->vm_start;
4612 for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
4613 if (rb->pg_vec == NULL)
4614 continue;
4615
4616 for (i = 0; i < rb->pg_vec_len; i++) {
4617 struct page *page;
4618 void *kaddr = rb->pg_vec[i].buffer;
4619 int pg_num;
4620
4621 for (pg_num = 0; pg_num < rb->pg_vec_pages; pg_num++) {
4622 page = pgv_to_page(kaddr);
4623 err = vm_insert_page(vma, start, page);
4624 if (unlikely(err))
4625 goto out;
4626 start += PAGE_SIZE;
4627 kaddr += PAGE_SIZE;
4628 }
4629 }
4630 }
4631
4632 atomic_long_inc(&po->mapped);
4633 vma->vm_ops = &packet_mmap_ops;
4634 err = 0;
4635
4636 out:
4637 mutex_unlock(&po->pg_vec_lock);
4638 return err;
4639 }
4640
4641 static const struct proto_ops packet_ops_spkt = {
4642 .family = PF_PACKET,
4643 .owner = THIS_MODULE,
4644 .release = packet_release,
4645 .bind = packet_bind_spkt,
4646 .connect = sock_no_connect,
4647 .socketpair = sock_no_socketpair,
4648 .accept = sock_no_accept,
4649 .getname = packet_getname_spkt,
4650 .poll = datagram_poll,
4651 .ioctl = packet_ioctl,
4652 .gettstamp = sock_gettstamp,
4653 .listen = sock_no_listen,
4654 .shutdown = sock_no_shutdown,
4655 .sendmsg = packet_sendmsg_spkt,
4656 .recvmsg = packet_recvmsg,
4657 .mmap = sock_no_mmap,
4658 };
4659
4660 static const struct proto_ops packet_ops = {
4661 .family = PF_PACKET,
4662 .owner = THIS_MODULE,
4663 .release = packet_release,
4664 .bind = packet_bind,
4665 .connect = sock_no_connect,
4666 .socketpair = sock_no_socketpair,
4667 .accept = sock_no_accept,
4668 .getname = packet_getname,
4669 .poll = packet_poll,
4670 .ioctl = packet_ioctl,
4671 .gettstamp = sock_gettstamp,
4672 .listen = sock_no_listen,
4673 .shutdown = sock_no_shutdown,
4674 .setsockopt = packet_setsockopt,
4675 .getsockopt = packet_getsockopt,
4676 .sendmsg = packet_sendmsg,
4677 .recvmsg = packet_recvmsg,
4678 .mmap = packet_mmap,
4679 };
4680
4681 static const struct net_proto_family packet_family_ops = {
4682 .family = PF_PACKET,
4683 .create = packet_create,
4684 .owner = THIS_MODULE,
4685 };
4686
4687 static struct notifier_block packet_netdev_notifier = {
4688 .notifier_call = packet_notifier,
4689 };
4690
4691 #ifdef CONFIG_PROC_FS
4692
packet_seq_start(struct seq_file * seq,loff_t * pos)4693 static void *packet_seq_start(struct seq_file *seq, loff_t *pos)
4694 __acquires(RCU)
4695 {
4696 struct net *net = seq_file_net(seq);
4697
4698 rcu_read_lock();
4699 return seq_hlist_start_head_rcu(&net->packet.sklist, *pos);
4700 }
4701
packet_seq_next(struct seq_file * seq,void * v,loff_t * pos)4702 static void *packet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
4703 {
4704 struct net *net = seq_file_net(seq);
4705 return seq_hlist_next_rcu(v, &net->packet.sklist, pos);
4706 }
4707
packet_seq_stop(struct seq_file * seq,void * v)4708 static void packet_seq_stop(struct seq_file *seq, void *v)
4709 __releases(RCU)
4710 {
4711 rcu_read_unlock();
4712 }
4713
packet_seq_show(struct seq_file * seq,void * v)4714 static int packet_seq_show(struct seq_file *seq, void *v)
4715 {
4716 if (v == SEQ_START_TOKEN)
4717 seq_printf(seq,
4718 "%*sRefCnt Type Proto Iface R Rmem User Inode\n",
4719 IS_ENABLED(CONFIG_64BIT) ? -17 : -9, "sk");
4720 else {
4721 struct sock *s = sk_entry(v);
4722 const struct packet_sock *po = pkt_sk(s);
4723
4724 seq_printf(seq,
4725 "%pK %-6d %-4d %04x %-5d %1d %-6u %-6u %-6lu\n",
4726 s,
4727 refcount_read(&s->sk_refcnt),
4728 s->sk_type,
4729 ntohs(READ_ONCE(po->num)),
4730 READ_ONCE(po->ifindex),
4731 packet_sock_flag(po, PACKET_SOCK_RUNNING),
4732 atomic_read(&s->sk_rmem_alloc),
4733 from_kuid_munged(seq_user_ns(seq), sk_uid(s)),
4734 sock_i_ino(s));
4735 }
4736
4737 return 0;
4738 }
4739
4740 static const struct seq_operations packet_seq_ops = {
4741 .start = packet_seq_start,
4742 .next = packet_seq_next,
4743 .stop = packet_seq_stop,
4744 .show = packet_seq_show,
4745 };
4746 #endif
4747
packet_net_init(struct net * net)4748 static int __net_init packet_net_init(struct net *net)
4749 {
4750 mutex_init(&net->packet.sklist_lock);
4751 INIT_HLIST_HEAD(&net->packet.sklist);
4752
4753 #ifdef CONFIG_PROC_FS
4754 if (!proc_create_net("packet", 0, net->proc_net, &packet_seq_ops,
4755 sizeof(struct seq_net_private)))
4756 return -ENOMEM;
4757 #endif /* CONFIG_PROC_FS */
4758
4759 return 0;
4760 }
4761
packet_net_exit(struct net * net)4762 static void __net_exit packet_net_exit(struct net *net)
4763 {
4764 remove_proc_entry("packet", net->proc_net);
4765 WARN_ON_ONCE(!hlist_empty(&net->packet.sklist));
4766 }
4767
4768 static struct pernet_operations packet_net_ops = {
4769 .init = packet_net_init,
4770 .exit = packet_net_exit,
4771 };
4772
4773
packet_exit(void)4774 static void __exit packet_exit(void)
4775 {
4776 sock_unregister(PF_PACKET);
4777 proto_unregister(&packet_proto);
4778 unregister_netdevice_notifier(&packet_netdev_notifier);
4779 unregister_pernet_subsys(&packet_net_ops);
4780 }
4781
packet_init(void)4782 static int __init packet_init(void)
4783 {
4784 int rc;
4785
4786 rc = register_pernet_subsys(&packet_net_ops);
4787 if (rc)
4788 goto out;
4789 rc = register_netdevice_notifier(&packet_netdev_notifier);
4790 if (rc)
4791 goto out_pernet;
4792 rc = proto_register(&packet_proto, 0);
4793 if (rc)
4794 goto out_notifier;
4795 rc = sock_register(&packet_family_ops);
4796 if (rc)
4797 goto out_proto;
4798
4799 return 0;
4800
4801 out_proto:
4802 proto_unregister(&packet_proto);
4803 out_notifier:
4804 unregister_netdevice_notifier(&packet_netdev_notifier);
4805 out_pernet:
4806 unregister_pernet_subsys(&packet_net_ops);
4807 out:
4808 return rc;
4809 }
4810
4811 module_init(packet_init);
4812 module_exit(packet_exit);
4813 MODULE_DESCRIPTION("Packet socket support (AF_PACKET)");
4814 MODULE_LICENSE("GPL");
4815 MODULE_ALIAS_NETPROTO(PF_PACKET);
4816