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