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