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