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