PageRenderTime 113ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/net/core/dev.c

http://github.com/mirrors/linux
C | 10568 lines | 6899 code | 1665 blank | 2004 comment | 1201 complexity | b85658a488468d1c3f7f658206f1a07c MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0, LGPL-2.0
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * NET3 Protocol independent device support routines.
  4. *
  5. * Derived from the non IP parts of dev.c 1.0.19
  6. * Authors: Ross Biro
  7. * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
  8. * Mark Evans, <evansmp@uhura.aston.ac.uk>
  9. *
  10. * Additional Authors:
  11. * Florian la Roche <rzsfl@rz.uni-sb.de>
  12. * Alan Cox <gw4pts@gw4pts.ampr.org>
  13. * David Hinds <dahinds@users.sourceforge.net>
  14. * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
  15. * Adam Sulmicki <adam@cfar.umd.edu>
  16. * Pekka Riikonen <priikone@poesidon.pspt.fi>
  17. *
  18. * Changes:
  19. * D.J. Barrow : Fixed bug where dev->refcnt gets set
  20. * to 2 if register_netdev gets called
  21. * before net_dev_init & also removed a
  22. * few lines of code in the process.
  23. * Alan Cox : device private ioctl copies fields back.
  24. * Alan Cox : Transmit queue code does relevant
  25. * stunts to keep the queue safe.
  26. * Alan Cox : Fixed double lock.
  27. * Alan Cox : Fixed promisc NULL pointer trap
  28. * ???????? : Support the full private ioctl range
  29. * Alan Cox : Moved ioctl permission check into
  30. * drivers
  31. * Tim Kordas : SIOCADDMULTI/SIOCDELMULTI
  32. * Alan Cox : 100 backlog just doesn't cut it when
  33. * you start doing multicast video 8)
  34. * Alan Cox : Rewrote net_bh and list manager.
  35. * Alan Cox : Fix ETH_P_ALL echoback lengths.
  36. * Alan Cox : Took out transmit every packet pass
  37. * Saved a few bytes in the ioctl handler
  38. * Alan Cox : Network driver sets packet type before
  39. * calling netif_rx. Saves a function
  40. * call a packet.
  41. * Alan Cox : Hashed net_bh()
  42. * Richard Kooijman: Timestamp fixes.
  43. * Alan Cox : Wrong field in SIOCGIFDSTADDR
  44. * Alan Cox : Device lock protection.
  45. * Alan Cox : Fixed nasty side effect of device close
  46. * changes.
  47. * Rudi Cilibrasi : Pass the right thing to
  48. * set_mac_address()
  49. * Dave Miller : 32bit quantity for the device lock to
  50. * make it work out on a Sparc.
  51. * Bjorn Ekwall : Added KERNELD hack.
  52. * Alan Cox : Cleaned up the backlog initialise.
  53. * Craig Metz : SIOCGIFCONF fix if space for under
  54. * 1 device.
  55. * Thomas Bogendoerfer : Return ENODEV for dev_open, if there
  56. * is no device open function.
  57. * Andi Kleen : Fix error reporting for SIOCGIFCONF
  58. * Michael Chastain : Fix signed/unsigned for SIOCGIFCONF
  59. * Cyrus Durgin : Cleaned for KMOD
  60. * Adam Sulmicki : Bug Fix : Network Device Unload
  61. * A network device unload needs to purge
  62. * the backlog queue.
  63. * Paul Rusty Russell : SIOCSIFNAME
  64. * Pekka Riikonen : Netdev boot-time settings code
  65. * Andrew Morton : Make unregister_netdevice wait
  66. * indefinitely on dev->refcnt
  67. * J Hadi Salim : - Backlog queue sampling
  68. * - netif_rx() feedback
  69. */
  70. #include <linux/uaccess.h>
  71. #include <linux/bitops.h>
  72. #include <linux/capability.h>
  73. #include <linux/cpu.h>
  74. #include <linux/types.h>
  75. #include <linux/kernel.h>
  76. #include <linux/hash.h>
  77. #include <linux/slab.h>
  78. #include <linux/sched.h>
  79. #include <linux/sched/mm.h>
  80. #include <linux/mutex.h>
  81. #include <linux/string.h>
  82. #include <linux/mm.h>
  83. #include <linux/socket.h>
  84. #include <linux/sockios.h>
  85. #include <linux/errno.h>
  86. #include <linux/interrupt.h>
  87. #include <linux/if_ether.h>
  88. #include <linux/netdevice.h>
  89. #include <linux/etherdevice.h>
  90. #include <linux/ethtool.h>
  91. #include <linux/skbuff.h>
  92. #include <linux/bpf.h>
  93. #include <linux/bpf_trace.h>
  94. #include <net/net_namespace.h>
  95. #include <net/sock.h>
  96. #include <net/busy_poll.h>
  97. #include <linux/rtnetlink.h>
  98. #include <linux/stat.h>
  99. #include <net/dst.h>
  100. #include <net/dst_metadata.h>
  101. #include <net/pkt_sched.h>
  102. #include <net/pkt_cls.h>
  103. #include <net/checksum.h>
  104. #include <net/xfrm.h>
  105. #include <linux/highmem.h>
  106. #include <linux/init.h>
  107. #include <linux/module.h>
  108. #include <linux/netpoll.h>
  109. #include <linux/rcupdate.h>
  110. #include <linux/delay.h>
  111. #include <net/iw_handler.h>
  112. #include <asm/current.h>
  113. #include <linux/audit.h>
  114. #include <linux/dmaengine.h>
  115. #include <linux/err.h>
  116. #include <linux/ctype.h>
  117. #include <linux/if_arp.h>
  118. #include <linux/if_vlan.h>
  119. #include <linux/ip.h>
  120. #include <net/ip.h>
  121. #include <net/mpls.h>
  122. #include <linux/ipv6.h>
  123. #include <linux/in.h>
  124. #include <linux/jhash.h>
  125. #include <linux/random.h>
  126. #include <trace/events/napi.h>
  127. #include <trace/events/net.h>
  128. #include <trace/events/skb.h>
  129. #include <linux/inetdevice.h>
  130. #include <linux/cpu_rmap.h>
  131. #include <linux/static_key.h>
  132. #include <linux/hashtable.h>
  133. #include <linux/vmalloc.h>
  134. #include <linux/if_macvlan.h>
  135. #include <linux/errqueue.h>
  136. #include <linux/hrtimer.h>
  137. #include <linux/netfilter_ingress.h>
  138. #include <linux/crash_dump.h>
  139. #include <linux/sctp.h>
  140. #include <net/udp_tunnel.h>
  141. #include <linux/net_namespace.h>
  142. #include <linux/indirect_call_wrapper.h>
  143. #include <net/devlink.h>
  144. #include "net-sysfs.h"
  145. #define MAX_GRO_SKBS 8
  146. /* This should be increased if a protocol with a bigger head is added. */
  147. #define GRO_MAX_HEAD (MAX_HEADER + 128)
  148. static DEFINE_SPINLOCK(ptype_lock);
  149. static DEFINE_SPINLOCK(offload_lock);
  150. struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
  151. struct list_head ptype_all __read_mostly; /* Taps */
  152. static struct list_head offload_base __read_mostly;
  153. static int netif_rx_internal(struct sk_buff *skb);
  154. static int call_netdevice_notifiers_info(unsigned long val,
  155. struct netdev_notifier_info *info);
  156. static int call_netdevice_notifiers_extack(unsigned long val,
  157. struct net_device *dev,
  158. struct netlink_ext_ack *extack);
  159. static struct napi_struct *napi_by_id(unsigned int napi_id);
  160. /*
  161. * The @dev_base_head list is protected by @dev_base_lock and the rtnl
  162. * semaphore.
  163. *
  164. * Pure readers hold dev_base_lock for reading, or rcu_read_lock()
  165. *
  166. * Writers must hold the rtnl semaphore while they loop through the
  167. * dev_base_head list, and hold dev_base_lock for writing when they do the
  168. * actual updates. This allows pure readers to access the list even
  169. * while a writer is preparing to update it.
  170. *
  171. * To put it another way, dev_base_lock is held for writing only to
  172. * protect against pure readers; the rtnl semaphore provides the
  173. * protection against other writers.
  174. *
  175. * See, for example usages, register_netdevice() and
  176. * unregister_netdevice(), which must be called with the rtnl
  177. * semaphore held.
  178. */
  179. DEFINE_RWLOCK(dev_base_lock);
  180. EXPORT_SYMBOL(dev_base_lock);
  181. static DEFINE_MUTEX(ifalias_mutex);
  182. /* protects napi_hash addition/deletion and napi_gen_id */
  183. static DEFINE_SPINLOCK(napi_hash_lock);
  184. static unsigned int napi_gen_id = NR_CPUS;
  185. static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
  186. static seqcount_t devnet_rename_seq;
  187. static inline void dev_base_seq_inc(struct net *net)
  188. {
  189. while (++net->dev_base_seq == 0)
  190. ;
  191. }
  192. static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
  193. {
  194. unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
  195. return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
  196. }
  197. static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
  198. {
  199. return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
  200. }
  201. static inline void rps_lock(struct softnet_data *sd)
  202. {
  203. #ifdef CONFIG_RPS
  204. spin_lock(&sd->input_pkt_queue.lock);
  205. #endif
  206. }
  207. static inline void rps_unlock(struct softnet_data *sd)
  208. {
  209. #ifdef CONFIG_RPS
  210. spin_unlock(&sd->input_pkt_queue.lock);
  211. #endif
  212. }
  213. static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev,
  214. const char *name)
  215. {
  216. struct netdev_name_node *name_node;
  217. name_node = kmalloc(sizeof(*name_node), GFP_KERNEL);
  218. if (!name_node)
  219. return NULL;
  220. INIT_HLIST_NODE(&name_node->hlist);
  221. name_node->dev = dev;
  222. name_node->name = name;
  223. return name_node;
  224. }
  225. static struct netdev_name_node *
  226. netdev_name_node_head_alloc(struct net_device *dev)
  227. {
  228. struct netdev_name_node *name_node;
  229. name_node = netdev_name_node_alloc(dev, dev->name);
  230. if (!name_node)
  231. return NULL;
  232. INIT_LIST_HEAD(&name_node->list);
  233. return name_node;
  234. }
  235. static void netdev_name_node_free(struct netdev_name_node *name_node)
  236. {
  237. kfree(name_node);
  238. }
  239. static void netdev_name_node_add(struct net *net,
  240. struct netdev_name_node *name_node)
  241. {
  242. hlist_add_head_rcu(&name_node->hlist,
  243. dev_name_hash(net, name_node->name));
  244. }
  245. static void netdev_name_node_del(struct netdev_name_node *name_node)
  246. {
  247. hlist_del_rcu(&name_node->hlist);
  248. }
  249. static struct netdev_name_node *netdev_name_node_lookup(struct net *net,
  250. const char *name)
  251. {
  252. struct hlist_head *head = dev_name_hash(net, name);
  253. struct netdev_name_node *name_node;
  254. hlist_for_each_entry(name_node, head, hlist)
  255. if (!strcmp(name_node->name, name))
  256. return name_node;
  257. return NULL;
  258. }
  259. static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net,
  260. const char *name)
  261. {
  262. struct hlist_head *head = dev_name_hash(net, name);
  263. struct netdev_name_node *name_node;
  264. hlist_for_each_entry_rcu(name_node, head, hlist)
  265. if (!strcmp(name_node->name, name))
  266. return name_node;
  267. return NULL;
  268. }
  269. int netdev_name_node_alt_create(struct net_device *dev, const char *name)
  270. {
  271. struct netdev_name_node *name_node;
  272. struct net *net = dev_net(dev);
  273. name_node = netdev_name_node_lookup(net, name);
  274. if (name_node)
  275. return -EEXIST;
  276. name_node = netdev_name_node_alloc(dev, name);
  277. if (!name_node)
  278. return -ENOMEM;
  279. netdev_name_node_add(net, name_node);
  280. /* The node that holds dev->name acts as a head of per-device list. */
  281. list_add_tail(&name_node->list, &dev->name_node->list);
  282. return 0;
  283. }
  284. EXPORT_SYMBOL(netdev_name_node_alt_create);
  285. static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node)
  286. {
  287. list_del(&name_node->list);
  288. netdev_name_node_del(name_node);
  289. kfree(name_node->name);
  290. netdev_name_node_free(name_node);
  291. }
  292. int netdev_name_node_alt_destroy(struct net_device *dev, const char *name)
  293. {
  294. struct netdev_name_node *name_node;
  295. struct net *net = dev_net(dev);
  296. name_node = netdev_name_node_lookup(net, name);
  297. if (!name_node)
  298. return -ENOENT;
  299. /* lookup might have found our primary name or a name belonging
  300. * to another device.
  301. */
  302. if (name_node == dev->name_node || name_node->dev != dev)
  303. return -EINVAL;
  304. __netdev_name_node_alt_destroy(name_node);
  305. return 0;
  306. }
  307. EXPORT_SYMBOL(netdev_name_node_alt_destroy);
  308. static void netdev_name_node_alt_flush(struct net_device *dev)
  309. {
  310. struct netdev_name_node *name_node, *tmp;
  311. list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list)
  312. __netdev_name_node_alt_destroy(name_node);
  313. }
  314. /* Device list insertion */
  315. static void list_netdevice(struct net_device *dev)
  316. {
  317. struct net *net = dev_net(dev);
  318. ASSERT_RTNL();
  319. write_lock_bh(&dev_base_lock);
  320. list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
  321. netdev_name_node_add(net, dev->name_node);
  322. hlist_add_head_rcu(&dev->index_hlist,
  323. dev_index_hash(net, dev->ifindex));
  324. write_unlock_bh(&dev_base_lock);
  325. dev_base_seq_inc(net);
  326. }
  327. /* Device list removal
  328. * caller must respect a RCU grace period before freeing/reusing dev
  329. */
  330. static void unlist_netdevice(struct net_device *dev)
  331. {
  332. ASSERT_RTNL();
  333. /* Unlink dev from the device chain */
  334. write_lock_bh(&dev_base_lock);
  335. list_del_rcu(&dev->dev_list);
  336. netdev_name_node_del(dev->name_node);
  337. hlist_del_rcu(&dev->index_hlist);
  338. write_unlock_bh(&dev_base_lock);
  339. dev_base_seq_inc(dev_net(dev));
  340. }
  341. /*
  342. * Our notifier list
  343. */
  344. static RAW_NOTIFIER_HEAD(netdev_chain);
  345. /*
  346. * Device drivers call our routines to queue packets here. We empty the
  347. * queue in the local softnet handler.
  348. */
  349. DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data);
  350. EXPORT_PER_CPU_SYMBOL(softnet_data);
  351. /*******************************************************************************
  352. *
  353. * Protocol management and registration routines
  354. *
  355. *******************************************************************************/
  356. /*
  357. * Add a protocol ID to the list. Now that the input handler is
  358. * smarter we can dispense with all the messy stuff that used to be
  359. * here.
  360. *
  361. * BEWARE!!! Protocol handlers, mangling input packets,
  362. * MUST BE last in hash buckets and checking protocol handlers
  363. * MUST start from promiscuous ptype_all chain in net_bh.
  364. * It is true now, do not change it.
  365. * Explanation follows: if protocol handler, mangling packet, will
  366. * be the first on list, it is not able to sense, that packet
  367. * is cloned and should be copied-on-write, so that it will
  368. * change it and subsequent readers will get broken packet.
  369. * --ANK (980803)
  370. */
  371. static inline struct list_head *ptype_head(const struct packet_type *pt)
  372. {
  373. if (pt->type == htons(ETH_P_ALL))
  374. return pt->dev ? &pt->dev->ptype_all : &ptype_all;
  375. else
  376. return pt->dev ? &pt->dev->ptype_specific :
  377. &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
  378. }
  379. /**
  380. * dev_add_pack - add packet handler
  381. * @pt: packet type declaration
  382. *
  383. * Add a protocol handler to the networking stack. The passed &packet_type
  384. * is linked into kernel lists and may not be freed until it has been
  385. * removed from the kernel lists.
  386. *
  387. * This call does not sleep therefore it can not
  388. * guarantee all CPU's that are in middle of receiving packets
  389. * will see the new packet type (until the next received packet).
  390. */
  391. void dev_add_pack(struct packet_type *pt)
  392. {
  393. struct list_head *head = ptype_head(pt);
  394. spin_lock(&ptype_lock);
  395. list_add_rcu(&pt->list, head);
  396. spin_unlock(&ptype_lock);
  397. }
  398. EXPORT_SYMBOL(dev_add_pack);
  399. /**
  400. * __dev_remove_pack - remove packet handler
  401. * @pt: packet type declaration
  402. *
  403. * Remove a protocol handler that was previously added to the kernel
  404. * protocol handlers by dev_add_pack(). The passed &packet_type is removed
  405. * from the kernel lists and can be freed or reused once this function
  406. * returns.
  407. *
  408. * The packet type might still be in use by receivers
  409. * and must not be freed until after all the CPU's have gone
  410. * through a quiescent state.
  411. */
  412. void __dev_remove_pack(struct packet_type *pt)
  413. {
  414. struct list_head *head = ptype_head(pt);
  415. struct packet_type *pt1;
  416. spin_lock(&ptype_lock);
  417. list_for_each_entry(pt1, head, list) {
  418. if (pt == pt1) {
  419. list_del_rcu(&pt->list);
  420. goto out;
  421. }
  422. }
  423. pr_warn("dev_remove_pack: %p not found\n", pt);
  424. out:
  425. spin_unlock(&ptype_lock);
  426. }
  427. EXPORT_SYMBOL(__dev_remove_pack);
  428. /**
  429. * dev_remove_pack - remove packet handler
  430. * @pt: packet type declaration
  431. *
  432. * Remove a protocol handler that was previously added to the kernel
  433. * protocol handlers by dev_add_pack(). The passed &packet_type is removed
  434. * from the kernel lists and can be freed or reused once this function
  435. * returns.
  436. *
  437. * This call sleeps to guarantee that no CPU is looking at the packet
  438. * type after return.
  439. */
  440. void dev_remove_pack(struct packet_type *pt)
  441. {
  442. __dev_remove_pack(pt);
  443. synchronize_net();
  444. }
  445. EXPORT_SYMBOL(dev_remove_pack);
  446. /**
  447. * dev_add_offload - register offload handlers
  448. * @po: protocol offload declaration
  449. *
  450. * Add protocol offload handlers to the networking stack. The passed
  451. * &proto_offload is linked into kernel lists and may not be freed until
  452. * it has been removed from the kernel lists.
  453. *
  454. * This call does not sleep therefore it can not
  455. * guarantee all CPU's that are in middle of receiving packets
  456. * will see the new offload handlers (until the next received packet).
  457. */
  458. void dev_add_offload(struct packet_offload *po)
  459. {
  460. struct packet_offload *elem;
  461. spin_lock(&offload_lock);
  462. list_for_each_entry(elem, &offload_base, list) {
  463. if (po->priority < elem->priority)
  464. break;
  465. }
  466. list_add_rcu(&po->list, elem->list.prev);
  467. spin_unlock(&offload_lock);
  468. }
  469. EXPORT_SYMBOL(dev_add_offload);
  470. /**
  471. * __dev_remove_offload - remove offload handler
  472. * @po: packet offload declaration
  473. *
  474. * Remove a protocol offload handler that was previously added to the
  475. * kernel offload handlers by dev_add_offload(). The passed &offload_type
  476. * is removed from the kernel lists and can be freed or reused once this
  477. * function returns.
  478. *
  479. * The packet type might still be in use by receivers
  480. * and must not be freed until after all the CPU's have gone
  481. * through a quiescent state.
  482. */
  483. static void __dev_remove_offload(struct packet_offload *po)
  484. {
  485. struct list_head *head = &offload_base;
  486. struct packet_offload *po1;
  487. spin_lock(&offload_lock);
  488. list_for_each_entry(po1, head, list) {
  489. if (po == po1) {
  490. list_del_rcu(&po->list);
  491. goto out;
  492. }
  493. }
  494. pr_warn("dev_remove_offload: %p not found\n", po);
  495. out:
  496. spin_unlock(&offload_lock);
  497. }
  498. /**
  499. * dev_remove_offload - remove packet offload handler
  500. * @po: packet offload declaration
  501. *
  502. * Remove a packet offload handler that was previously added to the kernel
  503. * offload handlers by dev_add_offload(). The passed &offload_type is
  504. * removed from the kernel lists and can be freed or reused once this
  505. * function returns.
  506. *
  507. * This call sleeps to guarantee that no CPU is looking at the packet
  508. * type after return.
  509. */
  510. void dev_remove_offload(struct packet_offload *po)
  511. {
  512. __dev_remove_offload(po);
  513. synchronize_net();
  514. }
  515. EXPORT_SYMBOL(dev_remove_offload);
  516. /******************************************************************************
  517. *
  518. * Device Boot-time Settings Routines
  519. *
  520. ******************************************************************************/
  521. /* Boot time configuration table */
  522. static struct netdev_boot_setup dev_boot_setup[NETDEV_BOOT_SETUP_MAX];
  523. /**
  524. * netdev_boot_setup_add - add new setup entry
  525. * @name: name of the device
  526. * @map: configured settings for the device
  527. *
  528. * Adds new setup entry to the dev_boot_setup list. The function
  529. * returns 0 on error and 1 on success. This is a generic routine to
  530. * all netdevices.
  531. */
  532. static int netdev_boot_setup_add(char *name, struct ifmap *map)
  533. {
  534. struct netdev_boot_setup *s;
  535. int i;
  536. s = dev_boot_setup;
  537. for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
  538. if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
  539. memset(s[i].name, 0, sizeof(s[i].name));
  540. strlcpy(s[i].name, name, IFNAMSIZ);
  541. memcpy(&s[i].map, map, sizeof(s[i].map));
  542. break;
  543. }
  544. }
  545. return i >= NETDEV_BOOT_SETUP_MAX ? 0 : 1;
  546. }
  547. /**
  548. * netdev_boot_setup_check - check boot time settings
  549. * @dev: the netdevice
  550. *
  551. * Check boot time settings for the device.
  552. * The found settings are set for the device to be used
  553. * later in the device probing.
  554. * Returns 0 if no settings found, 1 if they are.
  555. */
  556. int netdev_boot_setup_check(struct net_device *dev)
  557. {
  558. struct netdev_boot_setup *s = dev_boot_setup;
  559. int i;
  560. for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++) {
  561. if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
  562. !strcmp(dev->name, s[i].name)) {
  563. dev->irq = s[i].map.irq;
  564. dev->base_addr = s[i].map.base_addr;
  565. dev->mem_start = s[i].map.mem_start;
  566. dev->mem_end = s[i].map.mem_end;
  567. return 1;
  568. }
  569. }
  570. return 0;
  571. }
  572. EXPORT_SYMBOL(netdev_boot_setup_check);
  573. /**
  574. * netdev_boot_base - get address from boot time settings
  575. * @prefix: prefix for network device
  576. * @unit: id for network device
  577. *
  578. * Check boot time settings for the base address of device.
  579. * The found settings are set for the device to be used
  580. * later in the device probing.
  581. * Returns 0 if no settings found.
  582. */
  583. unsigned long netdev_boot_base(const char *prefix, int unit)
  584. {
  585. const struct netdev_boot_setup *s = dev_boot_setup;
  586. char name[IFNAMSIZ];
  587. int i;
  588. sprintf(name, "%s%d", prefix, unit);
  589. /*
  590. * If device already registered then return base of 1
  591. * to indicate not to probe for this interface
  592. */
  593. if (__dev_get_by_name(&init_net, name))
  594. return 1;
  595. for (i = 0; i < NETDEV_BOOT_SETUP_MAX; i++)
  596. if (!strcmp(name, s[i].name))
  597. return s[i].map.base_addr;
  598. return 0;
  599. }
  600. /*
  601. * Saves at boot time configured settings for any netdevice.
  602. */
  603. int __init netdev_boot_setup(char *str)
  604. {
  605. int ints[5];
  606. struct ifmap map;
  607. str = get_options(str, ARRAY_SIZE(ints), ints);
  608. if (!str || !*str)
  609. return 0;
  610. /* Save settings */
  611. memset(&map, 0, sizeof(map));
  612. if (ints[0] > 0)
  613. map.irq = ints[1];
  614. if (ints[0] > 1)
  615. map.base_addr = ints[2];
  616. if (ints[0] > 2)
  617. map.mem_start = ints[3];
  618. if (ints[0] > 3)
  619. map.mem_end = ints[4];
  620. /* Add new entry to the list */
  621. return netdev_boot_setup_add(str, &map);
  622. }
  623. __setup("netdev=", netdev_boot_setup);
  624. /*******************************************************************************
  625. *
  626. * Device Interface Subroutines
  627. *
  628. *******************************************************************************/
  629. /**
  630. * dev_get_iflink - get 'iflink' value of a interface
  631. * @dev: targeted interface
  632. *
  633. * Indicates the ifindex the interface is linked to.
  634. * Physical interfaces have the same 'ifindex' and 'iflink' values.
  635. */
  636. int dev_get_iflink(const struct net_device *dev)
  637. {
  638. if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
  639. return dev->netdev_ops->ndo_get_iflink(dev);
  640. return dev->ifindex;
  641. }
  642. EXPORT_SYMBOL(dev_get_iflink);
  643. /**
  644. * dev_fill_metadata_dst - Retrieve tunnel egress information.
  645. * @dev: targeted interface
  646. * @skb: The packet.
  647. *
  648. * For better visibility of tunnel traffic OVS needs to retrieve
  649. * egress tunnel information for a packet. Following API allows
  650. * user to get this info.
  651. */
  652. int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
  653. {
  654. struct ip_tunnel_info *info;
  655. if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
  656. return -EINVAL;
  657. info = skb_tunnel_info_unclone(skb);
  658. if (!info)
  659. return -ENOMEM;
  660. if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
  661. return -EINVAL;
  662. return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
  663. }
  664. EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
  665. /**
  666. * __dev_get_by_name - find a device by its name
  667. * @net: the applicable net namespace
  668. * @name: name to find
  669. *
  670. * Find an interface by name. Must be called under RTNL semaphore
  671. * or @dev_base_lock. If the name is found a pointer to the device
  672. * is returned. If the name is not found then %NULL is returned. The
  673. * reference counters are not incremented so the caller must be
  674. * careful with locks.
  675. */
  676. struct net_device *__dev_get_by_name(struct net *net, const char *name)
  677. {
  678. struct netdev_name_node *node_name;
  679. node_name = netdev_name_node_lookup(net, name);
  680. return node_name ? node_name->dev : NULL;
  681. }
  682. EXPORT_SYMBOL(__dev_get_by_name);
  683. /**
  684. * dev_get_by_name_rcu - find a device by its name
  685. * @net: the applicable net namespace
  686. * @name: name to find
  687. *
  688. * Find an interface by name.
  689. * If the name is found a pointer to the device is returned.
  690. * If the name is not found then %NULL is returned.
  691. * The reference counters are not incremented so the caller must be
  692. * careful with locks. The caller must hold RCU lock.
  693. */
  694. struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
  695. {
  696. struct netdev_name_node *node_name;
  697. node_name = netdev_name_node_lookup_rcu(net, name);
  698. return node_name ? node_name->dev : NULL;
  699. }
  700. EXPORT_SYMBOL(dev_get_by_name_rcu);
  701. /**
  702. * dev_get_by_name - find a device by its name
  703. * @net: the applicable net namespace
  704. * @name: name to find
  705. *
  706. * Find an interface by name. This can be called from any
  707. * context and does its own locking. The returned handle has
  708. * the usage count incremented and the caller must use dev_put() to
  709. * release it when it is no longer needed. %NULL is returned if no
  710. * matching device is found.
  711. */
  712. struct net_device *dev_get_by_name(struct net *net, const char *name)
  713. {
  714. struct net_device *dev;
  715. rcu_read_lock();
  716. dev = dev_get_by_name_rcu(net, name);
  717. if (dev)
  718. dev_hold(dev);
  719. rcu_read_unlock();
  720. return dev;
  721. }
  722. EXPORT_SYMBOL(dev_get_by_name);
  723. /**
  724. * __dev_get_by_index - find a device by its ifindex
  725. * @net: the applicable net namespace
  726. * @ifindex: index of device
  727. *
  728. * Search for an interface by index. Returns %NULL if the device
  729. * is not found or a pointer to the device. The device has not
  730. * had its reference counter increased so the caller must be careful
  731. * about locking. The caller must hold either the RTNL semaphore
  732. * or @dev_base_lock.
  733. */
  734. struct net_device *__dev_get_by_index(struct net *net, int ifindex)
  735. {
  736. struct net_device *dev;
  737. struct hlist_head *head = dev_index_hash(net, ifindex);
  738. hlist_for_each_entry(dev, head, index_hlist)
  739. if (dev->ifindex == ifindex)
  740. return dev;
  741. return NULL;
  742. }
  743. EXPORT_SYMBOL(__dev_get_by_index);
  744. /**
  745. * dev_get_by_index_rcu - find a device by its ifindex
  746. * @net: the applicable net namespace
  747. * @ifindex: index of device
  748. *
  749. * Search for an interface by index. Returns %NULL if the device
  750. * is not found or a pointer to the device. The device has not
  751. * had its reference counter increased so the caller must be careful
  752. * about locking. The caller must hold RCU lock.
  753. */
  754. struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
  755. {
  756. struct net_device *dev;
  757. struct hlist_head *head = dev_index_hash(net, ifindex);
  758. hlist_for_each_entry_rcu(dev, head, index_hlist)
  759. if (dev->ifindex == ifindex)
  760. return dev;
  761. return NULL;
  762. }
  763. EXPORT_SYMBOL(dev_get_by_index_rcu);
  764. /**
  765. * dev_get_by_index - find a device by its ifindex
  766. * @net: the applicable net namespace
  767. * @ifindex: index of device
  768. *
  769. * Search for an interface by index. Returns NULL if the device
  770. * is not found or a pointer to the device. The device returned has
  771. * had a reference added and the pointer is safe until the user calls
  772. * dev_put to indicate they have finished with it.
  773. */
  774. struct net_device *dev_get_by_index(struct net *net, int ifindex)
  775. {
  776. struct net_device *dev;
  777. rcu_read_lock();
  778. dev = dev_get_by_index_rcu(net, ifindex);
  779. if (dev)
  780. dev_hold(dev);
  781. rcu_read_unlock();
  782. return dev;
  783. }
  784. EXPORT_SYMBOL(dev_get_by_index);
  785. /**
  786. * dev_get_by_napi_id - find a device by napi_id
  787. * @napi_id: ID of the NAPI struct
  788. *
  789. * Search for an interface by NAPI ID. Returns %NULL if the device
  790. * is not found or a pointer to the device. The device has not had
  791. * its reference counter increased so the caller must be careful
  792. * about locking. The caller must hold RCU lock.
  793. */
  794. struct net_device *dev_get_by_napi_id(unsigned int napi_id)
  795. {
  796. struct napi_struct *napi;
  797. WARN_ON_ONCE(!rcu_read_lock_held());
  798. if (napi_id < MIN_NAPI_ID)
  799. return NULL;
  800. napi = napi_by_id(napi_id);
  801. return napi ? napi->dev : NULL;
  802. }
  803. EXPORT_SYMBOL(dev_get_by_napi_id);
  804. /**
  805. * netdev_get_name - get a netdevice name, knowing its ifindex.
  806. * @net: network namespace
  807. * @name: a pointer to the buffer where the name will be stored.
  808. * @ifindex: the ifindex of the interface to get the name from.
  809. *
  810. * The use of raw_seqcount_begin() and cond_resched() before
  811. * retrying is required as we want to give the writers a chance
  812. * to complete when CONFIG_PREEMPTION is not set.
  813. */
  814. int netdev_get_name(struct net *net, char *name, int ifindex)
  815. {
  816. struct net_device *dev;
  817. unsigned int seq;
  818. retry:
  819. seq = raw_seqcount_begin(&devnet_rename_seq);
  820. rcu_read_lock();
  821. dev = dev_get_by_index_rcu(net, ifindex);
  822. if (!dev) {
  823. rcu_read_unlock();
  824. return -ENODEV;
  825. }
  826. strcpy(name, dev->name);
  827. rcu_read_unlock();
  828. if (read_seqcount_retry(&devnet_rename_seq, seq)) {
  829. cond_resched();
  830. goto retry;
  831. }
  832. return 0;
  833. }
  834. /**
  835. * dev_getbyhwaddr_rcu - find a device by its hardware address
  836. * @net: the applicable net namespace
  837. * @type: media type of device
  838. * @ha: hardware address
  839. *
  840. * Search for an interface by MAC address. Returns NULL if the device
  841. * is not found or a pointer to the device.
  842. * The caller must hold RCU or RTNL.
  843. * The returned device has not had its ref count increased
  844. * and the caller must therefore be careful about locking
  845. *
  846. */
  847. struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
  848. const char *ha)
  849. {
  850. struct net_device *dev;
  851. for_each_netdev_rcu(net, dev)
  852. if (dev->type == type &&
  853. !memcmp(dev->dev_addr, ha, dev->addr_len))
  854. return dev;
  855. return NULL;
  856. }
  857. EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
  858. struct net_device *__dev_getfirstbyhwtype(struct net *net, unsigned short type)
  859. {
  860. struct net_device *dev;
  861. ASSERT_RTNL();
  862. for_each_netdev(net, dev)
  863. if (dev->type == type)
  864. return dev;
  865. return NULL;
  866. }
  867. EXPORT_SYMBOL(__dev_getfirstbyhwtype);
  868. struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
  869. {
  870. struct net_device *dev, *ret = NULL;
  871. rcu_read_lock();
  872. for_each_netdev_rcu(net, dev)
  873. if (dev->type == type) {
  874. dev_hold(dev);
  875. ret = dev;
  876. break;
  877. }
  878. rcu_read_unlock();
  879. return ret;
  880. }
  881. EXPORT_SYMBOL(dev_getfirstbyhwtype);
  882. /**
  883. * __dev_get_by_flags - find any device with given flags
  884. * @net: the applicable net namespace
  885. * @if_flags: IFF_* values
  886. * @mask: bitmask of bits in if_flags to check
  887. *
  888. * Search for any interface with the given flags. Returns NULL if a device
  889. * is not found or a pointer to the device. Must be called inside
  890. * rtnl_lock(), and result refcount is unchanged.
  891. */
  892. struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
  893. unsigned short mask)
  894. {
  895. struct net_device *dev, *ret;
  896. ASSERT_RTNL();
  897. ret = NULL;
  898. for_each_netdev(net, dev) {
  899. if (((dev->flags ^ if_flags) & mask) == 0) {
  900. ret = dev;
  901. break;
  902. }
  903. }
  904. return ret;
  905. }
  906. EXPORT_SYMBOL(__dev_get_by_flags);
  907. /**
  908. * dev_valid_name - check if name is okay for network device
  909. * @name: name string
  910. *
  911. * Network device names need to be valid file names to
  912. * to allow sysfs to work. We also disallow any kind of
  913. * whitespace.
  914. */
  915. bool dev_valid_name(const char *name)
  916. {
  917. if (*name == '\0')
  918. return false;
  919. if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
  920. return false;
  921. if (!strcmp(name, ".") || !strcmp(name, ".."))
  922. return false;
  923. while (*name) {
  924. if (*name == '/' || *name == ':' || isspace(*name))
  925. return false;
  926. name++;
  927. }
  928. return true;
  929. }
  930. EXPORT_SYMBOL(dev_valid_name);
  931. /**
  932. * __dev_alloc_name - allocate a name for a device
  933. * @net: network namespace to allocate the device name in
  934. * @name: name format string
  935. * @buf: scratch buffer and result name string
  936. *
  937. * Passed a format string - eg "lt%d" it will try and find a suitable
  938. * id. It scans list of devices to build up a free map, then chooses
  939. * the first empty slot. The caller must hold the dev_base or rtnl lock
  940. * while allocating the name and adding the device in order to avoid
  941. * duplicates.
  942. * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
  943. * Returns the number of the unit assigned or a negative errno code.
  944. */
  945. static int __dev_alloc_name(struct net *net, const char *name, char *buf)
  946. {
  947. int i = 0;
  948. const char *p;
  949. const int max_netdevices = 8*PAGE_SIZE;
  950. unsigned long *inuse;
  951. struct net_device *d;
  952. if (!dev_valid_name(name))
  953. return -EINVAL;
  954. p = strchr(name, '%');
  955. if (p) {
  956. /*
  957. * Verify the string as this thing may have come from
  958. * the user. There must be either one "%d" and no other "%"
  959. * characters.
  960. */
  961. if (p[1] != 'd' || strchr(p + 2, '%'))
  962. return -EINVAL;
  963. /* Use one page as a bit array of possible slots */
  964. inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
  965. if (!inuse)
  966. return -ENOMEM;
  967. for_each_netdev(net, d) {
  968. if (!sscanf(d->name, name, &i))
  969. continue;
  970. if (i < 0 || i >= max_netdevices)
  971. continue;
  972. /* avoid cases where sscanf is not exact inverse of printf */
  973. snprintf(buf, IFNAMSIZ, name, i);
  974. if (!strncmp(buf, d->name, IFNAMSIZ))
  975. set_bit(i, inuse);
  976. }
  977. i = find_first_zero_bit(inuse, max_netdevices);
  978. free_page((unsigned long) inuse);
  979. }
  980. snprintf(buf, IFNAMSIZ, name, i);
  981. if (!__dev_get_by_name(net, buf))
  982. return i;
  983. /* It is possible to run out of possible slots
  984. * when the name is long and there isn't enough space left
  985. * for the digits, or if all bits are used.
  986. */
  987. return -ENFILE;
  988. }
  989. static int dev_alloc_name_ns(struct net *net,
  990. struct net_device *dev,
  991. const char *name)
  992. {
  993. char buf[IFNAMSIZ];
  994. int ret;
  995. BUG_ON(!net);
  996. ret = __dev_alloc_name(net, name, buf);
  997. if (ret >= 0)
  998. strlcpy(dev->name, buf, IFNAMSIZ);
  999. return ret;
  1000. }
  1001. /**
  1002. * dev_alloc_name - allocate a name for a device
  1003. * @dev: device
  1004. * @name: name format string
  1005. *
  1006. * Passed a format string - eg "lt%d" it will try and find a suitable
  1007. * id. It scans list of devices to build up a free map, then chooses
  1008. * the first empty slot. The caller must hold the dev_base or rtnl lock
  1009. * while allocating the name and adding the device in order to avoid
  1010. * duplicates.
  1011. * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
  1012. * Returns the number of the unit assigned or a negative errno code.
  1013. */
  1014. int dev_alloc_name(struct net_device *dev, const char *name)
  1015. {
  1016. return dev_alloc_name_ns(dev_net(dev), dev, name);
  1017. }
  1018. EXPORT_SYMBOL(dev_alloc_name);
  1019. static int dev_get_valid_name(struct net *net, struct net_device *dev,
  1020. const char *name)
  1021. {
  1022. BUG_ON(!net);
  1023. if (!dev_valid_name(name))
  1024. return -EINVAL;
  1025. if (strchr(name, '%'))
  1026. return dev_alloc_name_ns(net, dev, name);
  1027. else if (__dev_get_by_name(net, name))
  1028. return -EEXIST;
  1029. else if (dev->name != name)
  1030. strlcpy(dev->name, name, IFNAMSIZ);
  1031. return 0;
  1032. }
  1033. /**
  1034. * dev_change_name - change name of a device
  1035. * @dev: device
  1036. * @newname: name (or format string) must be at least IFNAMSIZ
  1037. *
  1038. * Change name of a device, can pass format strings "eth%d".
  1039. * for wildcarding.
  1040. */
  1041. int dev_change_name(struct net_device *dev, const char *newname)
  1042. {
  1043. unsigned char old_assign_type;
  1044. char oldname[IFNAMSIZ];
  1045. int err = 0;
  1046. int ret;
  1047. struct net *net;
  1048. ASSERT_RTNL();
  1049. BUG_ON(!dev_net(dev));
  1050. net = dev_net(dev);
  1051. /* Some auto-enslaved devices e.g. failover slaves are
  1052. * special, as userspace might rename the device after
  1053. * the interface had been brought up and running since
  1054. * the point kernel initiated auto-enslavement. Allow
  1055. * live name change even when these slave devices are
  1056. * up and running.
  1057. *
  1058. * Typically, users of these auto-enslaving devices
  1059. * don't actually care about slave name change, as
  1060. * they are supposed to operate on master interface
  1061. * directly.
  1062. */
  1063. if (dev->flags & IFF_UP &&
  1064. likely(!(dev->priv_flags & IFF_LIVE_RENAME_OK)))
  1065. return -EBUSY;
  1066. write_seqcount_begin(&devnet_rename_seq);
  1067. if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
  1068. write_seqcount_end(&devnet_rename_seq);
  1069. return 0;
  1070. }
  1071. memcpy(oldname, dev->name, IFNAMSIZ);
  1072. err = dev_get_valid_name(net, dev, newname);
  1073. if (err < 0) {
  1074. write_seqcount_end(&devnet_rename_seq);
  1075. return err;
  1076. }
  1077. if (oldname[0] && !strchr(oldname, '%'))
  1078. netdev_info(dev, "renamed from %s\n", oldname);
  1079. old_assign_type = dev->name_assign_type;
  1080. dev->name_assign_type = NET_NAME_RENAMED;
  1081. rollback:
  1082. ret = device_rename(&dev->dev, dev->name);
  1083. if (ret) {
  1084. memcpy(dev->name, oldname, IFNAMSIZ);
  1085. dev->name_assign_type = old_assign_type;
  1086. write_seqcount_end(&devnet_rename_seq);
  1087. return ret;
  1088. }
  1089. write_seqcount_end(&devnet_rename_seq);
  1090. netdev_adjacent_rename_links(dev, oldname);
  1091. write_lock_bh(&dev_base_lock);
  1092. netdev_name_node_del(dev->name_node);
  1093. write_unlock_bh(&dev_base_lock);
  1094. synchronize_rcu();
  1095. write_lock_bh(&dev_base_lock);
  1096. netdev_name_node_add(net, dev->name_node);
  1097. write_unlock_bh(&dev_base_lock);
  1098. ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
  1099. ret = notifier_to_errno(ret);
  1100. if (ret) {
  1101. /* err >= 0 after dev_alloc_name() or stores the first errno */
  1102. if (err >= 0) {
  1103. err = ret;
  1104. write_seqcount_begin(&devnet_rename_seq);
  1105. memcpy(dev->name, oldname, IFNAMSIZ);
  1106. memcpy(oldname, newname, IFNAMSIZ);
  1107. dev->name_assign_type = old_assign_type;
  1108. old_assign_type = NET_NAME_RENAMED;
  1109. goto rollback;
  1110. } else {
  1111. pr_err("%s: name change rollback failed: %d\n",
  1112. dev->name, ret);
  1113. }
  1114. }
  1115. return err;
  1116. }
  1117. /**
  1118. * dev_set_alias - change ifalias of a device
  1119. * @dev: device
  1120. * @alias: name up to IFALIASZ
  1121. * @len: limit of bytes to copy from info
  1122. *
  1123. * Set ifalias for a device,
  1124. */
  1125. int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
  1126. {
  1127. struct dev_ifalias *new_alias = NULL;
  1128. if (len >= IFALIASZ)
  1129. return -EINVAL;
  1130. if (len) {
  1131. new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
  1132. if (!new_alias)
  1133. return -ENOMEM;
  1134. memcpy(new_alias->ifalias, alias, len);
  1135. new_alias->ifalias[len] = 0;
  1136. }
  1137. mutex_lock(&ifalias_mutex);
  1138. new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
  1139. mutex_is_locked(&ifalias_mutex));
  1140. mutex_unlock(&ifalias_mutex);
  1141. if (new_alias)
  1142. kfree_rcu(new_alias, rcuhead);
  1143. return len;
  1144. }
  1145. EXPORT_SYMBOL(dev_set_alias);
  1146. /**
  1147. * dev_get_alias - get ifalias of a device
  1148. * @dev: device
  1149. * @name: buffer to store name of ifalias
  1150. * @len: size of buffer
  1151. *
  1152. * get ifalias for a device. Caller must make sure dev cannot go
  1153. * away, e.g. rcu read lock or own a reference count to device.
  1154. */
  1155. int dev_get_alias(const struct net_device *dev, char *name, size_t len)
  1156. {
  1157. const struct dev_ifalias *alias;
  1158. int ret = 0;
  1159. rcu_read_lock();
  1160. alias = rcu_dereference(dev->ifalias);
  1161. if (alias)
  1162. ret = snprintf(name, len, "%s", alias->ifalias);
  1163. rcu_read_unlock();
  1164. return ret;
  1165. }
  1166. /**
  1167. * netdev_features_change - device changes features
  1168. * @dev: device to cause notification
  1169. *
  1170. * Called to indicate a device has changed features.
  1171. */
  1172. void netdev_features_change(struct net_device *dev)
  1173. {
  1174. call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
  1175. }
  1176. EXPORT_SYMBOL(netdev_features_change);
  1177. /**
  1178. * netdev_state_change - device changes state
  1179. * @dev: device to cause notification
  1180. *
  1181. * Called to indicate a device has changed state. This function calls
  1182. * the notifier chains for netdev_chain and sends a NEWLINK message
  1183. * to the routing socket.
  1184. */
  1185. void netdev_state_change(struct net_device *dev)
  1186. {
  1187. if (dev->flags & IFF_UP) {
  1188. struct netdev_notifier_change_info change_info = {
  1189. .info.dev = dev,
  1190. };
  1191. call_netdevice_notifiers_info(NETDEV_CHANGE,
  1192. &change_info.info);
  1193. rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL);
  1194. }
  1195. }
  1196. EXPORT_SYMBOL(netdev_state_change);
  1197. /**
  1198. * netdev_notify_peers - notify network peers about existence of @dev
  1199. * @dev: network device
  1200. *
  1201. * Generate traffic such that interested network peers are aware of
  1202. * @dev, such as by generating a gratuitous ARP. This may be used when
  1203. * a device wants to inform the rest of the network about some sort of
  1204. * reconfiguration such as a failover event or virtual machine
  1205. * migration.
  1206. */
  1207. void netdev_notify_peers(struct net_device *dev)
  1208. {
  1209. rtnl_lock();
  1210. call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
  1211. call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
  1212. rtnl_unlock();
  1213. }
  1214. EXPORT_SYMBOL(netdev_notify_peers);
  1215. static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
  1216. {
  1217. const struct net_device_ops *ops = dev->netdev_ops;
  1218. int ret;
  1219. ASSERT_RTNL();
  1220. if (!netif_device_present(dev))
  1221. return -ENODEV;
  1222. /* Block netpoll from trying to do any rx path servicing.
  1223. * If we don't do this there is a chance ndo_poll_controller
  1224. * or ndo_poll may be running while we open the device
  1225. */
  1226. netpoll_poll_disable(dev);
  1227. ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
  1228. ret = notifier_to_errno(ret);
  1229. if (ret)
  1230. return ret;
  1231. set_bit(__LINK_STATE_START, &dev->state);
  1232. if (ops->ndo_validate_addr)
  1233. ret = ops->ndo_validate_addr(dev);
  1234. if (!ret && ops->ndo_open)
  1235. ret = ops->ndo_open(dev);
  1236. netpoll_poll_enable(dev);
  1237. if (ret)
  1238. clear_bit(__LINK_STATE_START, &dev->state);
  1239. else {
  1240. dev->flags |= IFF_UP;
  1241. dev_set_rx_mode(dev);
  1242. dev_activate(dev);
  1243. add_device_randomness(dev->dev_addr, dev->addr_len);
  1244. }
  1245. return ret;
  1246. }
  1247. /**
  1248. * dev_open - prepare an interface for use.
  1249. * @dev: device to open
  1250. * @extack: netlink extended ack
  1251. *
  1252. * Takes a device from down to up state. The device's private open
  1253. * function is invoked and then the multicast lists are loaded. Finally
  1254. * the device is moved into the up state and a %NETDEV_UP message is
  1255. * sent to the netdev notifier chain.
  1256. *
  1257. * Calling this function on an active interface is a nop. On a failure
  1258. * a negative errno code is returned.
  1259. */
  1260. int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
  1261. {
  1262. int ret;
  1263. if (dev->flags & IFF_UP)
  1264. return 0;
  1265. ret = __dev_open(dev, extack);
  1266. if (ret < 0)
  1267. return ret;
  1268. rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
  1269. call_netdevice_notifiers(NETDEV_UP, dev);
  1270. return ret;
  1271. }
  1272. EXPORT_SYMBOL(dev_open);
  1273. static void __dev_close_many(struct list_head *head)
  1274. {
  1275. struct net_device *dev;
  1276. ASSERT_RTNL();
  1277. might_sleep();
  1278. list_for_each_entry(dev, head, close_list) {
  1279. /* Temporarily disable netpoll until the interface is down */
  1280. netpoll_poll_disable(dev);
  1281. call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
  1282. clear_bit(__LINK_STATE_START, &dev->state);
  1283. /* Synchronize to scheduled poll. We cannot touch poll list, it
  1284. * can be even on different cpu. So just clear netif_running().
  1285. *
  1286. * dev->stop() will invoke napi_disable() on all of it's
  1287. * napi_struct instances on this device.
  1288. */
  1289. smp_mb__after_atomic(); /* Commit netif_running(). */
  1290. }
  1291. dev_deactivate_many(head);
  1292. list_for_each_entry(dev, head, close_list) {
  1293. const struct net_device_ops *ops = dev->netdev_ops;
  1294. /*
  1295. * Call the device specific close. This cannot fail.
  1296. * Only if device is UP
  1297. *
  1298. * We allow it to be called even after a DETACH hot-plug
  1299. * event.
  1300. */
  1301. if (ops->ndo_stop)
  1302. ops->ndo_stop(dev);
  1303. dev->flags &= ~IFF_UP;
  1304. netpoll_poll_enable(dev);
  1305. }
  1306. }
  1307. static void __dev_close(struct net_device *dev)
  1308. {
  1309. LIST_HEAD(single);
  1310. list_add(&dev->close_list, &single);
  1311. __dev_close_many(&single);
  1312. list_del(&single);
  1313. }
  1314. void dev_close_many(struct list_head *head, bool unlink)
  1315. {
  1316. struct net_device *dev, *tmp;
  1317. /* Remove the devices that don't need to be closed */
  1318. list_for_each_entry_safe(dev, tmp, head, close_list)
  1319. if (!(dev->flags & IFF_UP))
  1320. list_del_init(&dev->close_list);
  1321. __dev_close_many(head);
  1322. list_for_each_entry_safe(dev, tmp, head, close_list) {
  1323. rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING, GFP_KERNEL);
  1324. call_netdevice_notifiers(NETDEV_DOWN, dev);
  1325. if (unlink)
  1326. list_del_init(&dev->close_list);
  1327. }
  1328. }
  1329. EXPORT_SYMBOL(dev_close_many);
  1330. /**
  1331. * dev_close - shutdown an interface.
  1332. * @dev: device to shutdown
  1333. *
  1334. * This function moves an active device into down state. A
  1335. * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
  1336. * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
  1337. * chain.
  1338. */
  1339. void dev_close(struct net_device *dev)
  1340. {
  1341. if (dev->flags & IFF_UP) {
  1342. LIST_HEAD(single);
  1343. list_add(&dev->close_list, &single);
  1344. dev_close_many(&single, true);
  1345. list_del(&single);
  1346. }
  1347. }
  1348. EXPORT_SYMBOL(dev_close);
  1349. /**
  1350. * dev_disable_lro - disable Large Receive Offload on a device
  1351. * @dev: device
  1352. *
  1353. * Disable Large Receive Offload (LRO) on a net device. Must be
  1354. * called under RTNL. This is needed if received packets may be
  1355. * forwarded to another interface.
  1356. */
  1357. void dev_disable_lro(struct net_device *dev)
  1358. {
  1359. struct net_device *lower_dev;
  1360. struct list_head *iter;
  1361. dev->wanted_features &= ~NETIF_F_LRO;
  1362. netdev_update_features(dev);
  1363. if (unlikely(dev->features & NETIF_F_LRO))
  1364. netdev_WARN(dev, "failed to disable LRO!\n");
  1365. netdev_for_each_lower_dev(dev, lower_dev, iter)
  1366. dev_disable_lro(lower_dev);
  1367. }
  1368. EXPORT_SYMBOL(dev_disable_lro);
  1369. /**
  1370. * dev_disable_gro_hw - disable HW Generic Receive Offload on a device
  1371. * @dev: device
  1372. *
  1373. * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be
  1374. * called under RTNL. This is needed if Generic XDP is installed on
  1375. * the device.
  1376. */
  1377. static void dev_disable_gro_hw(struct net_device *dev)
  1378. {
  1379. dev->wanted_features &= ~NETIF_F_GRO_HW;
  1380. netdev_update_features(dev);
  1381. if (unlikely(dev->features & NETIF_F_GRO_HW))
  1382. netdev_WARN(dev, "failed to disable GRO_HW!\n");
  1383. }
  1384. const char *netdev_cmd_to_name(enum netdev_cmd cmd)
  1385. {
  1386. #define N(val) \
  1387. case NETDEV_##val: \
  1388. return "NETDEV_" __stringify(val);
  1389. switch (cmd) {
  1390. N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
  1391. N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
  1392. N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
  1393. N(POST_INIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN) N(CHANGEUPPER)
  1394. N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA) N(BONDING_INFO)
  1395. N(PRECHANGEUPPER) N(CHANGELOWERSTATE) N(UDP_TUNNEL_PUSH_INFO)
  1396. N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
  1397. N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
  1398. N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
  1399. N(PRE_CHANGEADDR)
  1400. }
  1401. #undef N
  1402. return "UNKNOWN_NETDEV_EVENT";
  1403. }
  1404. EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
  1405. static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
  1406. struct net_device *dev)
  1407. {
  1408. struct netdev_notifier_info info = {
  1409. .dev = dev,
  1410. };
  1411. return nb->notifier_call(nb, val, &info);
  1412. }
  1413. static int call_netdevice_register_notifiers(struct notifier_block *nb,
  1414. struct net_device *dev)
  1415. {
  1416. int err;
  1417. err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
  1418. err = notifier_to_errno(err);
  1419. if (err)
  1420. return err;
  1421. if (!(dev->flags & IFF_UP))
  1422. return 0;
  1423. call_netdevice_notifier(nb, NETDEV_UP, dev);
  1424. return 0;
  1425. }
  1426. static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
  1427. struct net_device *dev)
  1428. {
  1429. if (dev->flags & IFF_UP) {
  1430. call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
  1431. dev);
  1432. call_netdevice_notifier(nb, NETDEV_DOWN, dev);
  1433. }
  1434. call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
  1435. }
  1436. static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
  1437. struct net *net)
  1438. {
  1439. struct net_device *dev;
  1440. int err;
  1441. for_each_netdev(net, dev) {
  1442. err = call_netdevice_register_notifiers(nb, dev);
  1443. if (err)
  1444. goto rollback;
  1445. }
  1446. return 0;
  1447. rollback:
  1448. for_each_netdev_continue_reverse(net, dev)
  1449. call_netdevice_unregister_notifiers(nb, dev);
  1450. return err;
  1451. }
  1452. static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
  1453. struct net *net)
  1454. {
  1455. struct net_device *dev;
  1456. for_each_netdev(net, dev)
  1457. call_netdevice_unregister_notifiers(nb, dev);
  1458. }
  1459. static int dev_boot_phase = 1;
  1460. /**
  1461. * register_netdevice_notifier - register a network notifier block
  1462. * @nb: notifier
  1463. *
  1464. * Register a notifier to be called when network device events occur.
  1465. * The notifier passed is linked into the kernel structures and must
  1466. * not be reused until it has been unregistered. A negative errno code
  1467. * is returned on a failure.
  1468. *
  1469. * When registered all registration and up events are replayed
  1470. * to the new notifier to allow device to have a race free
  1471. * view of the network device list.
  1472. */
  1473. int register_netdevice_notifier(struct notifier_block *nb)
  1474. {
  1475. struct net *net;
  1476. int err;
  1477. /* Close race with setup_net() and cleanup_net() */
  1478. down_write(&pernet_ops_rwsem);
  1479. rtnl_lock();
  1480. err = raw_notifier_chain_register(&netdev_chain, nb);
  1481. if (err)
  1482. goto unlock;
  1483. if (dev_boot_phase)
  1484. goto unlock;
  1485. for_each_net(net) {
  1486. err = call_netdevice_register_net_notifiers(nb, net);
  1487. if (err)
  1488. goto rollback;
  1489. }
  1490. unlock:
  1491. rtnl_unlock();
  1492. up_write(&pernet_ops_rwsem);
  1493. return err;
  1494. rollback:
  1495. for_each_net_continue_reverse(net)
  1496. call_netdevice_unregister_net_notifiers(nb, net);
  1497. raw_notifier_chain_unregister(&netdev_chain, nb);
  1498. goto unlock;
  1499. }
  1500. EXPORT_SYMBOL(register_netdevice_notifier);
  1501. /**
  1502. * unregister_netdevice_notifier - unregister a network notifier block
  1503. * @nb: notifier
  1504. *
  1505. * Unregister a notifier previously registered by
  1506. * register_netdevice_notifier(). The notifier is unlinked into the
  1507. * kernel structures and may then be reused. A negative errno code
  1508. * is returned on a failure.
  1509. *
  1510. * After unregistering unregister and down device events are synthesized
  1511. * for all devices on the device list to the removed notifier to remove
  1512. * the need for special case cleanup code.
  1513. */
  1514. int unregister_netdevice_notifier(struct notifier_block *nb)
  1515. {
  1516. struct net *net;
  1517. int err;
  1518. /* Close race with setup_net() and cleanup_net() */
  1519. down_write(&pernet_ops_rwsem);
  1520. rtnl_lock();
  1521. err = raw_notifier_chain_unregister(&netdev_chain, nb);
  1522. if (err)
  1523. goto unlock;
  1524. for_each_net(net)
  1525. call_netdevice_unregister_net_notifiers(nb, net);
  1526. unlock:
  1527. rtnl_unlock();
  1528. up_write(&pernet_ops_rwsem);
  1529. return err;
  1530. }
  1531. EXPORT_SYMBOL(unregister_netdevice_notifier);
  1532. static int __register_netdevice_notifier_net(struct net *net,
  1533. struct notifier_block *nb,
  1534. bool ignore_call_fail)
  1535. {
  1536. int err;
  1537. err = raw_notifier_chain_register(&net->netdev_chain, nb);
  1538. if (err)
  1539. return err;
  1540. if (dev_boot_phase)
  1541. return 0;
  1542. err = call_netdevice_register_net_notifiers(nb, net);
  1543. if (err && !ignore_call_fail)
  1544. goto chain_unregister;
  1545. return 0;
  1546. chain_unregister:
  1547. raw_notifier_chain_unregister(&net->netdev_chain, nb);
  1548. return err;
  1549. }
  1550. static int __unregister_netdevice_notifier_net(struct net *net,
  1551. struct notifier_block *nb)
  1552. {
  1553. int err;
  1554. err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
  1555. if (err)
  1556. return err;
  1557. call_netdevice_unregister_net_notifiers(nb, net);
  1558. return 0;
  1559. }
  1560. /**
  1561. * register_netdevice_notifier_net - register a per-netns network notifier block
  1562. * @net: network namespace
  1563. * @nb: notifier
  1564. *
  1565. * Register a notifier to be called when network device events occur.
  1566. * The notifier passed is linked into the kernel structures and must
  1567. * not be reused until it has been unregistered. A negative errno code
  1568. * is returned on a failure.
  1569. *
  1570. * When registered all registration and up events are replayed
  1571. * to the new notifier to allow device to have a race free
  1572. * view of the network device list.
  1573. */
  1574. int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
  1575. {
  1576. int err;
  1577. rtnl_lock();
  1578. err = __register_netdevice_notifier_net(net, nb, false);
  1579. rtnl_unlock();
  1580. return err;
  1581. }
  1582. EXPORT_SYMBOL(register_netdevice_notifier_net);
  1583. /**
  1584. * unregister_netdevice_notifier_net - unregister a per-netns
  1585. * network notifier block
  1586. * @net: network namespace
  1587. * @nb: notifier
  1588. *
  1589. * Unregister a notifier previously registered by
  1590. * register_netdevice_notifier(). The notifier is unlinked into the
  1591. * kernel structures and may then be reused. A negative errno code
  1592. * is returned on a failure.
  1593. *
  1594. * After unregistering unregister and down device events are synthesized
  1595. * for all devices on the device list to the removed notifier to remove
  1596. * the need for special case cleanup code.
  1597. */
  1598. int unregister_netdevice_notifier_net(struct net *net,
  1599. struct notifier_block *nb)
  1600. {
  1601. int err;
  1602. rtnl_lock();
  1603. err = __unregister_netdevice_notifier_net(net, nb);
  1604. rtnl_unlock();
  1605. return err;
  1606. }
  1607. EXPORT_SYMBOL(unregister_netdevice_notifier_net);
  1608. int register_netdevice_notifier_dev_net(struct net_device *dev,
  1609. struct notifier_block *nb,
  1610. struct netdev_net_notifier *nn)
  1611. {
  1612. int err;
  1613. rtnl_lock();
  1614. err = __register_netdevice_notifier_net(dev_net(dev), nb, false);
  1615. if (!err) {
  1616. nn->nb = nb;
  1617. list_add(&nn->list, &dev->net_notifier_list);
  1618. }
  1619. rtnl_unlock();
  1620. return err;
  1621. }
  1622. EXPORT_SYMBOL(register_netdevice_notifier_dev_net);
  1623. int unregister_netdevice_notifier_dev_net(struct net_device *dev,
  1624. struct notifier_block *nb,
  1625. struct netdev_net_notifier *nn)
  1626. {
  1627. int err;
  1628. rtnl_lock();
  1629. list_del(&nn->list);
  1630. err = __unregister_netdevice_notifier_net(dev_net(dev), nb);
  1631. rtnl_unlock();
  1632. return err;
  1633. }
  1634. EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net);
  1635. static void move_netdevice_notifiers_dev_net(struct net_device *dev,
  1636. struct net *net)
  1637. {
  1638. struct netdev_net_notifier *nn;
  1639. list_for_each_entry(nn, &dev->net_notifier_list, list) {
  1640. __unregister_netdevice_notifier_net(dev_net(dev), nn->nb);
  1641. __register_netdevice_notifier_net(net, nn->nb, true);
  1642. }
  1643. }
  1644. /**
  1645. * call_netdevice_notifiers_info - call all network notifier blocks
  1646. * @val: value passed unmodified to notifier function
  1647. * @info: notifier information data
  1648. *
  1649. * Call all network notifier blocks. Parameters and return value
  1650. * are as for raw_notifier_call_chain().
  1651. */
  1652. static int call_netdevice_notifiers_info(unsigned long val,
  1653. struct netdev_notifier_info *info)
  1654. {
  1655. struct net *net = dev_net(info->dev);
  1656. int ret;
  1657. ASSERT_RTNL();
  1658. /* Run per-netns notifier block chain first, then run the global one.
  1659. * Hopefully, one day, the global one is going to be removed after
  1660. * all notifier block registrators get converted to be per-netns.
  1661. */
  1662. ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
  1663. if (ret & NOTIFY_STOP_MASK)
  1664. return ret;
  1665. return raw_notifier_call_chain(&netdev_chain, val, info);
  1666. }
  1667. static int call_netdevice_notifiers_extack(unsigned long val,
  1668. struct net_device *dev,
  1669. struct netlink_ext_ack *extack)
  1670. {
  1671. struct netdev_notifier_info info = {
  1672. .dev = dev,
  1673. .extack = extack,
  1674. };
  1675. return call_netdevice_notifiers_info(val, &info);
  1676. }
  1677. /**
  1678. * call_netdevice_notifiers - call all network notifier blocks
  1679. * @val: value passed unmodified to notifier function
  1680. * @dev: net_device pointer passed unmodified to notifier function
  1681. *
  1682. * Call all network notifier blocks. Parameters and return value
  1683. * are as for raw_notifier_call_chain().
  1684. */
  1685. int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
  1686. {
  1687. return call_netdevice_notifiers_extack(val, dev, NULL);
  1688. }
  1689. EXPORT_SYMBOL(call_netdevice_notifiers);
  1690. /**
  1691. * call_netdevice_notifiers_mtu - call all network notifier blocks
  1692. * @val: value passed unmodified to notifier function
  1693. * @dev: net_device pointer passed unmodified to notifier function
  1694. * @arg: additional u32 argument passed to the notifier function
  1695. *
  1696. * Call all network notifier blocks. Parameters and return value
  1697. * are as for raw_notifier_call_chain().
  1698. */
  1699. static int call_netdevice_notifiers_mtu(unsigned long val,
  1700. struct net_device *dev, u32 arg)
  1701. {
  1702. struct netdev_notifier_info_ext info = {
  1703. .info.dev = dev,
  1704. .ext.mtu = arg,
  1705. };
  1706. BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
  1707. return call_netdevice_notifiers_info(val, &info.info);
  1708. }
  1709. #ifdef CONFIG_NET_INGRESS
  1710. static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
  1711. void net_inc_ingress_queue(void)
  1712. {
  1713. static_branch_inc(&ingress_needed_key);
  1714. }
  1715. EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
  1716. void net_dec_ingress_queue(void)
  1717. {
  1718. static_branch_dec(&ingress_needed_key);
  1719. }
  1720. EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
  1721. #endif
  1722. #ifdef CONFIG_NET_EGRESS
  1723. static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
  1724. void net_inc_egress_queue(void)
  1725. {
  1726. static_branch_inc(&egress_needed_key);
  1727. }
  1728. EXPORT_SYMBOL_GPL(net_inc_egress_queue);
  1729. void net_dec_egress_queue(void)
  1730. {
  1731. static_branch_dec(&egress_needed_key);
  1732. }
  1733. EXPORT_SYMBOL_GPL(net_dec_egress_queue);
  1734. #endif
  1735. static DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
  1736. #ifdef CONFIG_JUMP_LABEL
  1737. static atomic_t netstamp_needed_deferred;
  1738. static atomic_t netstamp_wanted;
  1739. static void netstamp_clear(struct work_struct *work)
  1740. {
  1741. int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
  1742. int wanted;
  1743. wanted = atomic_add_return(deferred, &netstamp_wanted);
  1744. if (wanted > 0)
  1745. static_branch_enable(&netstamp_needed_key);
  1746. else
  1747. static_branch_disable(&netstamp_needed_key);
  1748. }
  1749. static DECLARE_WORK(netstamp_work, netstamp_clear);
  1750. #endif
  1751. void net_enable_timestamp(void)
  1752. {
  1753. #ifdef CONFIG_JUMP_LABEL
  1754. int wanted;
  1755. while (1) {
  1756. wanted = atomic_read(&netstamp_wanted);
  1757. if (wanted <= 0)
  1758. break;
  1759. if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted + 1) == wanted)
  1760. return;
  1761. }
  1762. atomic_inc(&netstamp_needed_deferred);
  1763. schedule_work(&netstamp_work);
  1764. #else
  1765. static_branch_inc(&netstamp_needed_key);
  1766. #endif
  1767. }
  1768. EXPORT_SYMBOL(net_enable_timestamp);
  1769. void net_disable_timestamp(void)
  1770. {
  1771. #ifdef CONFIG_JUMP_LABEL
  1772. int wanted;
  1773. while (1) {
  1774. wanted = atomic_read(&netstamp_wanted);
  1775. if (wanted <= 1)
  1776. break;
  1777. if (atomic_cmpxchg(&netstamp_wanted, wanted, wanted - 1) == wanted)
  1778. return;
  1779. }
  1780. atomic_dec(&netstamp_needed_deferred);
  1781. schedule_work(&netstamp_work);
  1782. #else
  1783. static_branch_dec(&netstamp_needed_key);
  1784. #endif
  1785. }
  1786. EXPORT_SYMBOL(net_disable_timestamp);
  1787. static inline void net_timestamp_set(struct sk_buff *skb)
  1788. {
  1789. skb->tstamp = 0;
  1790. if (static_branch_unlikely(&netstamp_needed_key))
  1791. __net_timestamp(skb);
  1792. }
  1793. #define net_timestamp_check(COND, SKB) \
  1794. if (static_branch_unlikely(&netstamp_needed_key)) { \
  1795. if ((COND) && !(SKB)->tstamp) \
  1796. __net_timestamp(SKB); \
  1797. } \
  1798. bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
  1799. {
  1800. unsigned int len;
  1801. if (!(dev->flags & IFF_UP))
  1802. return false;
  1803. len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
  1804. if (skb->len <= len)
  1805. return true;
  1806. /* if TSO is enabled, we don't care about the length as the packet
  1807. * could be forwarded without being segmented before
  1808. */
  1809. if (skb_is_gso(skb))
  1810. return true;
  1811. return false;
  1812. }
  1813. EXPORT_SYMBOL_GPL(is_skb_forwardable);
  1814. int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
  1815. {
  1816. int ret = ____dev_forward_skb(dev, skb);
  1817. if (likely(!ret)) {
  1818. skb->protocol = eth_type_trans(skb, dev);
  1819. skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
  1820. }
  1821. return ret;
  1822. }
  1823. EXPORT_SYMBOL_GPL(__dev_forward_skb);
  1824. /**
  1825. * dev_forward_skb - loopback an skb to another netif
  1826. *
  1827. * @dev: destination network device
  1828. * @skb: buffer to forward
  1829. *
  1830. * return values:
  1831. * NET_RX_SUCCESS (no congestion)
  1832. * NET_RX_DROP (packet was dropped, but freed)
  1833. *
  1834. * dev_forward_skb can be used for injecting an skb from the
  1835. * start_xmit function of one device into the receive queue
  1836. * of another device.
  1837. *
  1838. * The receiving device may be in another namespace, so
  1839. * we have to clear all information in the skb that could
  1840. * impact namespace isolation.
  1841. */
  1842. int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
  1843. {
  1844. return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
  1845. }
  1846. EXPORT_SYMBOL_GPL(dev_forward_skb);
  1847. static inline int deliver_skb(struct sk_buff *skb,
  1848. struct packet_type *pt_prev,
  1849. struct net_device *orig_dev)
  1850. {
  1851. if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
  1852. return -ENOMEM;
  1853. refcount_inc(&skb->users);
  1854. return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
  1855. }
  1856. static inline void deliver_ptype_list_skb(struct sk_buff *skb,
  1857. struct packet_type **pt,
  1858. struct net_device *orig_dev,
  1859. __be16 type,
  1860. struct list_head *ptype_list)
  1861. {
  1862. struct packet_type *ptype, *pt_prev = *pt;
  1863. list_for_each_entry_rcu(ptype, ptype_list, list) {
  1864. if (ptype->type != type)
  1865. continue;
  1866. if (pt_prev)
  1867. deliver_skb(skb, pt_prev, orig_dev);
  1868. pt_prev = ptype;
  1869. }
  1870. *pt = pt_prev;
  1871. }
  1872. static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
  1873. {
  1874. if (!ptype->af_packet_priv || !skb->sk)
  1875. return false;
  1876. if (ptype->id_match)
  1877. return ptype->id_match(ptype, skb->sk);
  1878. else if ((struct sock *)ptype->af_packet_priv == skb->sk)
  1879. return true;
  1880. return false;
  1881. }
  1882. /**
  1883. * dev_nit_active - return true if any network interface taps are in use
  1884. *
  1885. * @dev: network device to check for the presence of taps
  1886. */
  1887. bool dev_nit_active(struct net_device *dev)
  1888. {
  1889. return !list_empty(&ptype_all) || !list_empty(&dev->ptype_all);
  1890. }
  1891. EXPORT_SYMBOL_GPL(dev_nit_active);
  1892. /*
  1893. * Support routine. Sends outgoing frames to any network
  1894. * taps currently in use.
  1895. */
  1896. void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
  1897. {
  1898. struct packet_type *ptype;
  1899. struct sk_buff *skb2 = NULL;
  1900. struct packet_type *pt_prev = NULL;
  1901. struct list_head *ptype_list = &ptype_all;
  1902. rcu_read_lock();
  1903. again:
  1904. list_for_each_entry_rcu(ptype, ptype_list, list) {
  1905. if (ptype->ignore_outgoing)
  1906. continue;
  1907. /* Never send packets back to the socket
  1908. * they originated from - MvS (miquels@drinkel.ow.org)
  1909. */
  1910. if (skb_loop_sk(ptype, skb))
  1911. continue;
  1912. if (pt_prev) {
  1913. deliver_skb(skb2, pt_prev, skb->dev);
  1914. pt_prev = ptype;
  1915. continue;
  1916. }
  1917. /* need to clone skb, done only once */
  1918. skb2 = skb_clone(skb, GFP_ATOMIC);
  1919. if (!skb2)
  1920. goto out_unlock;
  1921. net_timestamp_set(skb2);
  1922. /* skb->nh should be correctly
  1923. * set by sender, so that the second statement is
  1924. * just protection against buggy protocols.
  1925. */
  1926. skb_reset_mac_header(skb2);
  1927. if (skb_network_header(skb2) < skb2->data ||
  1928. skb_network_header(skb2) > skb_tail_pointer(skb2)) {
  1929. net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
  1930. ntohs(skb2->protocol),
  1931. dev->name);
  1932. skb_reset_network_header(skb2);
  1933. }
  1934. skb2->transport_header = skb2->network_header;
  1935. skb2->pkt_type = PACKET_OUTGOING;
  1936. pt_prev = ptype;
  1937. }
  1938. if (ptype_list == &ptype_all) {
  1939. ptype_list = &dev->ptype_all;
  1940. goto again;
  1941. }
  1942. out_unlock:
  1943. if (pt_prev) {
  1944. if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
  1945. pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
  1946. else
  1947. kfree_skb(skb2);
  1948. }
  1949. rcu_read_unlock();
  1950. }
  1951. EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
  1952. /**
  1953. * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
  1954. * @dev: Network device
  1955. * @txq: number of queues available
  1956. *
  1957. * If real_num_tx_queues is changed the tc mappings may no longer be
  1958. * valid. To resolve this verify the tc mapping remains valid and if
  1959. * not NULL the mapping. With no priorities mapping to this
  1960. * offset/count pair it will no longer be used. In the worst case TC0
  1961. * is invalid nothing can be done so disable priority mappings. If is
  1962. * expected that drivers will fix this mapping if they can before
  1963. * calling netif_set_real_num_tx_queues.
  1964. */
  1965. static void netif_setup_tc(struct net_device *dev, unsigned int txq)
  1966. {
  1967. int i;
  1968. struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
  1969. /* If TC0 is invalidated disable TC mapping */
  1970. if (tc->offset + tc->count > txq) {
  1971. pr_warn("Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
  1972. dev->num_tc = 0;
  1973. return;
  1974. }
  1975. /* Invalidated prio to tc mappings set to TC0 */
  1976. for (i = 1; i < TC_BITMASK + 1; i++) {
  1977. int q = netdev_get_prio_tc_map(dev, i);
  1978. tc = &dev->tc_to_txq[q];
  1979. if (tc->offset + tc->count > txq) {
  1980. pr_warn("Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
  1981. i, q);
  1982. netdev_set_prio_tc_map(dev, i, 0);
  1983. }
  1984. }
  1985. }
  1986. int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
  1987. {
  1988. if (dev->num_tc) {
  1989. struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
  1990. int i;
  1991. /* walk through the TCs and see if it falls into any of them */
  1992. for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
  1993. if ((txq - tc->offset) < tc->count)
  1994. return i;
  1995. }
  1996. /* didn't find it, just return -1 to indicate no match */
  1997. return -1;
  1998. }
  1999. return 0;
  2000. }
  2001. EXPORT_SYMBOL(netdev_txq_to_tc);
  2002. #ifdef CONFIG_XPS
  2003. struct static_key xps_needed __read_mostly;
  2004. EXPORT_SYMBOL(xps_needed);
  2005. struct static_key xps_rxqs_needed __read_mostly;
  2006. EXPORT_SYMBOL(xps_rxqs_needed);
  2007. static DEFINE_MUTEX(xps_map_mutex);
  2008. #define xmap_dereference(P) \
  2009. rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
  2010. static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
  2011. int tci, u16 index)
  2012. {
  2013. struct xps_map *map = NULL;
  2014. int pos;
  2015. if (dev_maps)
  2016. map = xmap_dereference(dev_maps->attr_map[tci]);
  2017. if (!map)
  2018. return false;
  2019. for (pos = map->len; pos--;) {
  2020. if (map->queues[pos] != index)
  2021. continue;
  2022. if (map->len > 1) {
  2023. map->queues[pos] = map->queues[--map->len];
  2024. break;
  2025. }
  2026. RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
  2027. kfree_rcu(map, rcu);
  2028. return false;
  2029. }
  2030. return true;
  2031. }
  2032. static bool remove_xps_queue_cpu(struct net_device *dev,
  2033. struct xps_dev_maps *dev_maps,
  2034. int cpu, u16 offset, u16 count)
  2035. {
  2036. int num_tc = dev->num_tc ? : 1;
  2037. bool active = false;
  2038. int tci;
  2039. for (tci = cpu * num_tc; num_tc--; tci++) {
  2040. int i, j;
  2041. for (i = count, j = offset; i--; j++) {
  2042. if (!remove_xps_queue(dev_maps, tci, j))
  2043. break;
  2044. }
  2045. active |= i < 0;
  2046. }
  2047. return active;
  2048. }
  2049. static void reset_xps_maps(struct net_device *dev,
  2050. struct xps_dev_maps *dev_maps,
  2051. bool is_rxqs_map)
  2052. {
  2053. if (is_rxqs_map) {
  2054. static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
  2055. RCU_INIT_POINTER(dev->xps_rxqs_map, NULL);
  2056. } else {
  2057. RCU_INIT_POINTER(dev->xps_cpus_map, NULL);
  2058. }
  2059. static_key_slow_dec_cpuslocked(&xps_needed);
  2060. kfree_rcu(dev_maps, rcu);
  2061. }
  2062. static void clean_xps_maps(struct net_device *dev, const unsigned long *mask,
  2063. struct xps_dev_maps *dev_maps, unsigned int nr_ids,
  2064. u16 offset, u16 count, bool is_rxqs_map)
  2065. {
  2066. bool active = false;
  2067. int i, j;
  2068. for (j = -1; j = netif_attrmask_next(j, mask, nr_ids),
  2069. j < nr_ids;)
  2070. active |= remove_xps_queue_cpu(dev, dev_maps, j, offset,
  2071. count);
  2072. if (!active)
  2073. reset_xps_maps(dev, dev_maps, is_rxqs_map);
  2074. if (!is_rxqs_map) {
  2075. for (i = offset + (count - 1); count--; i--) {
  2076. netdev_queue_numa_node_write(
  2077. netdev_get_tx_queue(dev, i),
  2078. NUMA_NO_NODE);
  2079. }
  2080. }
  2081. }
  2082. static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
  2083. u16 count)
  2084. {
  2085. const unsigned long *possible_mask = NULL;
  2086. struct xps_dev_maps *dev_maps;
  2087. unsigned int nr_ids;
  2088. if (!static_key_false(&xps_needed))
  2089. return;
  2090. cpus_read_lock();
  2091. mutex_lock(&xps_map_mutex);
  2092. if (static_key_false(&xps_rxqs_needed)) {
  2093. dev_maps = xmap_dereference(dev->xps_rxqs_map);
  2094. if (dev_maps) {
  2095. nr_ids = dev->num_rx_queues;
  2096. clean_xps_maps(dev, possible_mask, dev_maps, nr_ids,
  2097. offset, count, true);
  2098. }
  2099. }
  2100. dev_maps = xmap_dereference(dev->xps_cpus_map);
  2101. if (!dev_maps)
  2102. goto out_no_maps;
  2103. if (num_possible_cpus() > 1)
  2104. possible_mask = cpumask_bits(cpu_possible_mask);
  2105. nr_ids = nr_cpu_ids;
  2106. clean_xps_maps(dev, possible_mask, dev_maps, nr_ids, offset, count,
  2107. false);
  2108. out_no_maps:
  2109. mutex_unlock(&xps_map_mutex);
  2110. cpus_read_unlock();
  2111. }
  2112. static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
  2113. {
  2114. netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
  2115. }
  2116. static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
  2117. u16 index, bool is_rxqs_map)
  2118. {
  2119. struct xps_map *new_map;
  2120. int alloc_len = XPS_MIN_MAP_ALLOC;
  2121. int i, pos;
  2122. for (pos = 0; map && pos < map->len; pos++) {
  2123. if (map->queues[pos] != index)
  2124. continue;
  2125. return map;
  2126. }
  2127. /* Need to add tx-queue to this CPU's/rx-queue's existing map */
  2128. if (map) {
  2129. if (pos < map->alloc_len)
  2130. return map;
  2131. alloc_len = map->alloc_len * 2;
  2132. }
  2133. /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
  2134. * map
  2135. */
  2136. if (is_rxqs_map)
  2137. new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
  2138. else
  2139. new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
  2140. cpu_to_node(attr_index));
  2141. if (!new_map)
  2142. return NULL;
  2143. for (i = 0; i < pos; i++)
  2144. new_map->queues[i] = map->queues[i];
  2145. new_map->alloc_len = alloc_len;
  2146. new_map->len = pos;
  2147. return new_map;
  2148. }
  2149. /* Must be called under cpus_read_lock */
  2150. int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
  2151. u16 index, bool is_rxqs_map)
  2152. {
  2153. const unsigned long *online_mask = NULL, *possible_mask = NULL;
  2154. struct xps_dev_maps *dev_maps, *new_dev_maps = NULL;
  2155. int i, j, tci, numa_node_id = -2;
  2156. int maps_sz, num_tc = 1, tc = 0;
  2157. struct xps_map *map, *new_map;
  2158. bool active = false;
  2159. unsigned int nr_ids;
  2160. if (dev->num_tc) {
  2161. /* Do not allow XPS on subordinate device directly */
  2162. num_tc = dev->num_tc;
  2163. if (num_tc < 0)
  2164. return -EINVAL;
  2165. /* If queue belongs to subordinate dev use its map */
  2166. dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
  2167. tc = netdev_txq_to_tc(dev, index);
  2168. if (tc < 0)
  2169. return -EINVAL;
  2170. }
  2171. mutex_lock(&xps_map_mutex);
  2172. if (is_rxqs_map) {
  2173. maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
  2174. dev_maps = xmap_dereference(dev->xps_rxqs_map);
  2175. nr_ids = dev->num_rx_queues;
  2176. } else {
  2177. maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
  2178. if (num_possible_cpus() > 1) {
  2179. online_mask = cpumask_bits(cpu_online_mask);
  2180. possible_mask = cpumask_bits(cpu_possible_mask);
  2181. }
  2182. dev_maps = xmap_dereference(dev->xps_cpus_map);
  2183. nr_ids = nr_cpu_ids;
  2184. }
  2185. if (maps_sz < L1_CACHE_BYTES)
  2186. maps_sz = L1_CACHE_BYTES;
  2187. /* allocate memory for queue storage */
  2188. for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
  2189. j < nr_ids;) {
  2190. if (!new_dev_maps)
  2191. new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
  2192. if (!new_dev_maps) {
  2193. mutex_unlock(&xps_map_mutex);
  2194. return -ENOMEM;
  2195. }
  2196. tci = j * num_tc + tc;
  2197. map = dev_maps ? xmap_dereference(dev_maps->attr_map[tci]) :
  2198. NULL;
  2199. map = expand_xps_map(map, j, index, is_rxqs_map);
  2200. if (!map)
  2201. goto error;
  2202. RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
  2203. }
  2204. if (!new_dev_maps)
  2205. goto out_no_new_maps;
  2206. if (!dev_maps) {
  2207. /* Increment static keys at most once per type */
  2208. static_key_slow_inc_cpuslocked(&xps_needed);
  2209. if (is_rxqs_map)
  2210. static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
  2211. }
  2212. for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
  2213. j < nr_ids;) {
  2214. /* copy maps belonging to foreign traffic classes */
  2215. for (i = tc, tci = j * num_tc; dev_maps && i--; tci++) {
  2216. /* fill in the new device map from the old device map */
  2217. map = xmap_dereference(dev_maps->attr_map[tci]);
  2218. RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
  2219. }
  2220. /* We need to explicitly update tci as prevous loop
  2221. * could break out early if dev_maps is NULL.
  2222. */
  2223. tci = j * num_tc + tc;
  2224. if (netif_attr_test_mask(j, mask, nr_ids) &&
  2225. netif_attr_test_online(j, online_mask, nr_ids)) {
  2226. /* add tx-queue to CPU/rx-queue maps */
  2227. int pos = 0;
  2228. map = xmap_dereference(new_dev_maps->attr_map[tci]);
  2229. while ((pos < map->len) && (map->queues[pos] != index))
  2230. pos++;
  2231. if (pos == map->len)
  2232. map->queues[map->len++] = index;
  2233. #ifdef CONFIG_NUMA
  2234. if (!is_rxqs_map) {
  2235. if (numa_node_id == -2)
  2236. numa_node_id = cpu_to_node(j);
  2237. else if (numa_node_id != cpu_to_node(j))
  2238. numa_node_id = -1;
  2239. }
  2240. #endif
  2241. } else if (dev_maps) {
  2242. /* fill in the new device map from the old device map */
  2243. map = xmap_dereference(dev_maps->attr_map[tci]);
  2244. RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
  2245. }
  2246. /* copy maps belonging to foreign traffic classes */
  2247. for (i = num_tc - tc, tci++; dev_maps && --i; tci++) {
  2248. /* fill in the new device map from the old device map */
  2249. map = xmap_dereference(dev_maps->attr_map[tci]);
  2250. RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
  2251. }
  2252. }
  2253. if (is_rxqs_map)
  2254. rcu_assign_pointer(dev->xps_rxqs_map, new_dev_maps);
  2255. else
  2256. rcu_assign_pointer(dev->xps_cpus_map, new_dev_maps);
  2257. /* Cleanup old maps */
  2258. if (!dev_maps)
  2259. goto out_no_old_maps;
  2260. for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
  2261. j < nr_ids;) {
  2262. for (i = num_tc, tci = j * num_tc; i--; tci++) {
  2263. new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
  2264. map = xmap_dereference(dev_maps->attr_map[tci]);
  2265. if (map && map != new_map)
  2266. kfree_rcu(map, rcu);
  2267. }
  2268. }
  2269. kfree_rcu(dev_maps, rcu);
  2270. out_no_old_maps:
  2271. dev_maps = new_dev_maps;
  2272. active = true;
  2273. out_no_new_maps:
  2274. if (!is_rxqs_map) {
  2275. /* update Tx queue numa node */
  2276. netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
  2277. (numa_node_id >= 0) ?
  2278. numa_node_id : NUMA_NO_NODE);
  2279. }
  2280. if (!dev_maps)
  2281. goto out_no_maps;
  2282. /* removes tx-queue from unused CPUs/rx-queues */
  2283. for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
  2284. j < nr_ids;) {
  2285. for (i = tc, tci = j * num_tc; i--; tci++)
  2286. active |= remove_xps_queue(dev_maps, tci, index);
  2287. if (!netif_attr_test_mask(j, mask, nr_ids) ||
  2288. !netif_attr_test_online(j, online_mask, nr_ids))
  2289. active |= remove_xps_queue(dev_maps, tci, index);
  2290. for (i = num_tc - tc, tci++; --i; tci++)
  2291. active |= remove_xps_queue(dev_maps, tci, index);
  2292. }
  2293. /* free map if not active */
  2294. if (!active)
  2295. reset_xps_maps(dev, dev_maps, is_rxqs_map);
  2296. out_no_maps:
  2297. mutex_unlock(&xps_map_mutex);
  2298. return 0;
  2299. error:
  2300. /* remove any maps that we added */
  2301. for (j = -1; j = netif_attrmask_next(j, possible_mask, nr_ids),
  2302. j < nr_ids;) {
  2303. for (i = num_tc, tci = j * num_tc; i--; tci++) {
  2304. new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
  2305. map = dev_maps ?
  2306. xmap_dereference(dev_maps->attr_map[tci]) :
  2307. NULL;
  2308. if (new_map && new_map != map)
  2309. kfree(new_map);
  2310. }
  2311. }
  2312. mutex_unlock(&xps_map_mutex);
  2313. kfree(new_dev_maps);
  2314. return -ENOMEM;
  2315. }
  2316. EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
  2317. int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
  2318. u16 index)
  2319. {
  2320. int ret;
  2321. cpus_read_lock();
  2322. ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, false);
  2323. cpus_read_unlock();
  2324. return ret;
  2325. }
  2326. EXPORT_SYMBOL(netif_set_xps_queue);
  2327. #endif
  2328. static void netdev_unbind_all_sb_channels(struct net_device *dev)
  2329. {
  2330. struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
  2331. /* Unbind any subordinate channels */
  2332. while (txq-- != &dev->_tx[0]) {
  2333. if (txq->sb_dev)
  2334. netdev_unbind_sb_channel(dev, txq->sb_dev);
  2335. }
  2336. }
  2337. void netdev_reset_tc(struct net_device *dev)
  2338. {
  2339. #ifdef CONFIG_XPS
  2340. netif_reset_xps_queues_gt(dev, 0);
  2341. #endif
  2342. netdev_unbind_all_sb_channels(dev);
  2343. /* Reset TC configuration of device */
  2344. dev->num_tc = 0;
  2345. memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
  2346. memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
  2347. }
  2348. EXPORT_SYMBOL(netdev_reset_tc);
  2349. int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
  2350. {
  2351. if (tc >= dev->num_tc)
  2352. return -EINVAL;
  2353. #ifdef CONFIG_XPS
  2354. netif_reset_xps_queues(dev, offset, count);
  2355. #endif
  2356. dev->tc_to_txq[tc].count = count;
  2357. dev->tc_to_txq[tc].offset = offset;
  2358. return 0;
  2359. }
  2360. EXPORT_SYMBOL(netdev_set_tc_queue);
  2361. int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
  2362. {
  2363. if (num_tc > TC_MAX_QUEUE)
  2364. return -EINVAL;
  2365. #ifdef CONFIG_XPS
  2366. netif_reset_xps_queues_gt(dev, 0);
  2367. #endif
  2368. netdev_unbind_all_sb_channels(dev);
  2369. dev->num_tc = num_tc;
  2370. return 0;
  2371. }
  2372. EXPORT_SYMBOL(netdev_set_num_tc);
  2373. void netdev_unbind_sb_channel(struct net_device *dev,
  2374. struct net_device *sb_dev)
  2375. {
  2376. struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
  2377. #ifdef CONFIG_XPS
  2378. netif_reset_xps_queues_gt(sb_dev, 0);
  2379. #endif
  2380. memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
  2381. memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
  2382. while (txq-- != &dev->_tx[0]) {
  2383. if (txq->sb_dev == sb_dev)
  2384. txq->sb_dev = NULL;
  2385. }
  2386. }
  2387. EXPORT_SYMBOL(netdev_unbind_sb_channel);
  2388. int netdev_bind_sb_channel_queue(struct net_device *dev,
  2389. struct net_device *sb_dev,
  2390. u8 tc, u16 count, u16 offset)
  2391. {
  2392. /* Make certain the sb_dev and dev are already configured */
  2393. if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
  2394. return -EINVAL;
  2395. /* We cannot hand out queues we don't have */
  2396. if ((offset + count) > dev->real_num_tx_queues)
  2397. return -EINVAL;
  2398. /* Record the mapping */
  2399. sb_dev->tc_to_txq[tc].count = count;
  2400. sb_dev->tc_to_txq[tc].offset = offset;
  2401. /* Provide a way for Tx queue to find the tc_to_txq map or
  2402. * XPS map for itself.
  2403. */
  2404. while (count--)
  2405. netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
  2406. return 0;
  2407. }
  2408. EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
  2409. int netdev_set_sb_channel(struct net_device *dev, u16 channel)
  2410. {
  2411. /* Do not use a multiqueue device to represent a subordinate channel */
  2412. if (netif_is_multiqueue(dev))
  2413. return -ENODEV;
  2414. /* We allow channels 1 - 32767 to be used for subordinate channels.
  2415. * Channel 0 is meant to be "native" mode and used only to represent
  2416. * the main root device. We allow writing 0 to reset the device back
  2417. * to normal mode after being used as a subordinate channel.
  2418. */
  2419. if (channel > S16_MAX)
  2420. return -EINVAL;
  2421. dev->num_tc = -channel;
  2422. return 0;
  2423. }
  2424. EXPORT_SYMBOL(netdev_set_sb_channel);
  2425. /*
  2426. * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
  2427. * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
  2428. */
  2429. int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
  2430. {
  2431. bool disabling;
  2432. int rc;
  2433. disabling = txq < dev->real_num_tx_queues;
  2434. if (txq < 1 || txq > dev->num_tx_queues)
  2435. return -EINVAL;
  2436. if (dev->reg_state == NETREG_REGISTERED ||
  2437. dev->reg_state == NETREG_UNREGISTERING) {
  2438. ASSERT_RTNL();
  2439. rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
  2440. txq);
  2441. if (rc)
  2442. return rc;
  2443. if (dev->num_tc)
  2444. netif_setup_tc(dev, txq);
  2445. dev->real_num_tx_queues = txq;
  2446. if (disabling) {
  2447. synchronize_net();
  2448. qdisc_reset_all_tx_gt(dev, txq);
  2449. #ifdef CONFIG_XPS
  2450. netif_reset_xps_queues_gt(dev, txq);
  2451. #endif
  2452. }
  2453. } else {
  2454. dev->real_num_tx_queues = txq;
  2455. }
  2456. return 0;
  2457. }
  2458. EXPORT_SYMBOL(netif_set_real_num_tx_queues);
  2459. #ifdef CONFIG_SYSFS
  2460. /**
  2461. * netif_set_real_num_rx_queues - set actual number of RX queues used
  2462. * @dev: Network device
  2463. * @rxq: Actual number of RX queues
  2464. *
  2465. * This must be called either with the rtnl_lock held or before
  2466. * registration of the net device. Returns 0 on success, or a
  2467. * negative error code. If called before registration, it always
  2468. * succeeds.
  2469. */
  2470. int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
  2471. {
  2472. int rc;
  2473. if (rxq < 1 || rxq > dev->num_rx_queues)
  2474. return -EINVAL;
  2475. if (dev->reg_state == NETREG_REGISTERED) {
  2476. ASSERT_RTNL();
  2477. rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
  2478. rxq);
  2479. if (rc)
  2480. return rc;
  2481. }
  2482. dev->real_num_rx_queues = rxq;
  2483. return 0;
  2484. }
  2485. EXPORT_SYMBOL(netif_set_real_num_rx_queues);
  2486. #endif
  2487. /**
  2488. * netif_get_num_default_rss_queues - default number of RSS queues
  2489. *
  2490. * This routine should set an upper limit on the number of RSS queues
  2491. * used by default by multiqueue devices.
  2492. */
  2493. int netif_get_num_default_rss_queues(void)
  2494. {
  2495. return is_kdump_kernel() ?
  2496. 1 : min_t(int, DEFAULT_MAX_NUM_RSS_QUEUES, num_online_cpus());
  2497. }
  2498. EXPORT_SYMBOL(netif_get_num_default_rss_queues);
  2499. static void __netif_reschedule(struct Qdisc *q)
  2500. {
  2501. struct softnet_data *sd;
  2502. unsigned long flags;
  2503. local_irq_save(flags);
  2504. sd = this_cpu_ptr(&softnet_data);
  2505. q->next_sched = NULL;
  2506. *sd->output_queue_tailp = q;
  2507. sd->output_queue_tailp = &q->next_sched;
  2508. raise_softirq_irqoff(NET_TX_SOFTIRQ);
  2509. local_irq_restore(flags);
  2510. }
  2511. void __netif_schedule(struct Qdisc *q)
  2512. {
  2513. if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
  2514. __netif_reschedule(q);
  2515. }
  2516. EXPORT_SYMBOL(__netif_schedule);
  2517. struct dev_kfree_skb_cb {
  2518. enum skb_free_reason reason;
  2519. };
  2520. static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
  2521. {
  2522. return (struct dev_kfree_skb_cb *)skb->cb;
  2523. }
  2524. void netif_schedule_queue(struct netdev_queue *txq)
  2525. {
  2526. rcu_read_lock();
  2527. if (!netif_xmit_stopped(txq)) {
  2528. struct Qdisc *q = rcu_dereference(txq->qdisc);
  2529. __netif_schedule(q);
  2530. }
  2531. rcu_read_unlock();
  2532. }
  2533. EXPORT_SYMBOL(netif_schedule_queue);
  2534. void netif_tx_wake_queue(struct netdev_queue *dev_queue)
  2535. {
  2536. if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
  2537. struct Qdisc *q;
  2538. rcu_read_lock();
  2539. q = rcu_dereference(dev_queue->qdisc);
  2540. __netif_schedule(q);
  2541. rcu_read_unlock();
  2542. }
  2543. }
  2544. EXPORT_SYMBOL(netif_tx_wake_queue);
  2545. void __dev_kfree_skb_irq(struct sk_buff *skb, enum skb_free_reason reason)
  2546. {
  2547. unsigned long flags;
  2548. if (unlikely(!skb))
  2549. return;
  2550. if (likely(refcount_read(&skb->users) == 1)) {
  2551. smp_rmb();
  2552. refcount_set(&skb->users, 0);
  2553. } else if (likely(!refcount_dec_and_test(&skb->users))) {
  2554. return;
  2555. }
  2556. get_kfree_skb_cb(skb)->reason = reason;
  2557. local_irq_save(flags);
  2558. skb->next = __this_cpu_read(softnet_data.completion_queue);
  2559. __this_cpu_write(softnet_data.completion_queue, skb);
  2560. raise_softirq_irqoff(NET_TX_SOFTIRQ);
  2561. local_irq_restore(flags);
  2562. }
  2563. EXPORT_SYMBOL(__dev_kfree_skb_irq);
  2564. void __dev_kfree_skb_any(struct sk_buff *skb, enum skb_free_reason reason)
  2565. {
  2566. if (in_irq() || irqs_disabled())
  2567. __dev_kfree_skb_irq(skb, reason);
  2568. else
  2569. dev_kfree_skb(skb);
  2570. }
  2571. EXPORT_SYMBOL(__dev_kfree_skb_any);
  2572. /**
  2573. * netif_device_detach - mark device as removed
  2574. * @dev: network device
  2575. *
  2576. * Mark device as removed from system and therefore no longer available.
  2577. */
  2578. void netif_device_detach(struct net_device *dev)
  2579. {
  2580. if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
  2581. netif_running(dev)) {
  2582. netif_tx_stop_all_queues(dev);
  2583. }
  2584. }
  2585. EXPORT_SYMBOL(netif_device_detach);
  2586. /**
  2587. * netif_device_attach - mark device as attached
  2588. * @dev: network device
  2589. *
  2590. * Mark device as attached from system and restart if needed.
  2591. */
  2592. void netif_device_attach(struct net_device *dev)
  2593. {
  2594. if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
  2595. netif_running(dev)) {
  2596. netif_tx_wake_all_queues(dev);
  2597. __netdev_watchdog_up(dev);
  2598. }
  2599. }
  2600. EXPORT_SYMBOL(netif_device_attach);
  2601. /*
  2602. * Returns a Tx hash based on the given packet descriptor a Tx queues' number
  2603. * to be used as a distribution range.
  2604. */
  2605. static u16 skb_tx_hash(const struct net_device *dev,
  2606. const struct net_device *sb_dev,
  2607. struct sk_buff *skb)
  2608. {
  2609. u32 hash;
  2610. u16 qoffset = 0;
  2611. u16 qcount = dev->real_num_tx_queues;
  2612. if (dev->num_tc) {
  2613. u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
  2614. qoffset = sb_dev->tc_to_txq[tc].offset;
  2615. qcount = sb_dev->tc_to_txq[tc].count;
  2616. }
  2617. if (skb_rx_queue_recorded(skb)) {
  2618. hash = skb_get_rx_queue(skb);
  2619. if (hash >= qoffset)
  2620. hash -= qoffset;
  2621. while (unlikely(hash >= qcount))
  2622. hash -= qcount;
  2623. return hash + qoffset;
  2624. }
  2625. return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
  2626. }
  2627. static void skb_warn_bad_offload(const struct sk_buff *skb)
  2628. {
  2629. static const netdev_features_t null_features;
  2630. struct net_device *dev = skb->dev;
  2631. const char *name = "";
  2632. if (!net_ratelimit())
  2633. return;
  2634. if (dev) {
  2635. if (dev->dev.parent)
  2636. name = dev_driver_string(dev->dev.parent);
  2637. else
  2638. name = netdev_name(dev);
  2639. }
  2640. skb_dump(KERN_WARNING, skb, false);
  2641. WARN(1, "%s: caps=(%pNF, %pNF)\n",
  2642. name, dev ? &dev->features : &null_features,
  2643. skb->sk ? &skb->sk->sk_route_caps : &null_features);
  2644. }
  2645. /*
  2646. * Invalidate hardware checksum when packet is to be mangled, and
  2647. * complete checksum manually on outgoing path.
  2648. */
  2649. int skb_checksum_help(struct sk_buff *skb)
  2650. {
  2651. __wsum csum;
  2652. int ret = 0, offset;
  2653. if (skb->ip_summed == CHECKSUM_COMPLETE)
  2654. goto out_set_summed;
  2655. if (unlikely(skb_shinfo(skb)->gso_size)) {
  2656. skb_warn_bad_offload(skb);
  2657. return -EINVAL;
  2658. }
  2659. /* Before computing a checksum, we should make sure no frag could
  2660. * be modified by an external entity : checksum could be wrong.
  2661. */
  2662. if (skb_has_shared_frag(skb)) {
  2663. ret = __skb_linearize(skb);
  2664. if (ret)
  2665. goto out;
  2666. }
  2667. offset = skb_checksum_start_offset(skb);
  2668. BUG_ON(offset >= skb_headlen(skb));
  2669. csum = skb_checksum(skb, offset, skb->len - offset, 0);
  2670. offset += skb->csum_offset;
  2671. BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
  2672. ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
  2673. if (ret)
  2674. goto out;
  2675. *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
  2676. out_set_summed:
  2677. skb->ip_summed = CHECKSUM_NONE;
  2678. out:
  2679. return ret;
  2680. }
  2681. EXPORT_SYMBOL(skb_checksum_help);
  2682. int skb_crc32c_csum_help(struct sk_buff *skb)
  2683. {
  2684. __le32 crc32c_csum;
  2685. int ret = 0, offset, start;
  2686. if (skb->ip_summed != CHECKSUM_PARTIAL)
  2687. goto out;
  2688. if (unlikely(skb_is_gso(skb)))
  2689. goto out;
  2690. /* Before computing a checksum, we should make sure no frag could
  2691. * be modified by an external entity : checksum could be wrong.
  2692. */
  2693. if (unlikely(skb_has_shared_frag(skb))) {
  2694. ret = __skb_linearize(skb);
  2695. if (ret)
  2696. goto out;
  2697. }
  2698. start = skb_checksum_start_offset(skb);
  2699. offset = start + offsetof(struct sctphdr, checksum);
  2700. if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
  2701. ret = -EINVAL;
  2702. goto out;
  2703. }
  2704. ret = skb_ensure_writable(skb, offset + sizeof(__le32));
  2705. if (ret)
  2706. goto out;
  2707. crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
  2708. skb->len - start, ~(__u32)0,
  2709. crc32c_csum_stub));
  2710. *(__le32 *)(skb->data + offset) = crc32c_csum;
  2711. skb->ip_summed = CHECKSUM_NONE;
  2712. skb->csum_not_inet = 0;
  2713. out:
  2714. return ret;
  2715. }
  2716. __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
  2717. {
  2718. __be16 type = skb->protocol;
  2719. /* Tunnel gso handlers can set protocol to ethernet. */
  2720. if (type == htons(ETH_P_TEB)) {
  2721. struct ethhdr *eth;
  2722. if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
  2723. return 0;
  2724. eth = (struct ethhdr *)skb->data;
  2725. type = eth->h_proto;
  2726. }
  2727. return __vlan_get_protocol(skb, type, depth);
  2728. }
  2729. /**
  2730. * skb_mac_gso_segment - mac layer segmentation handler.
  2731. * @skb: buffer to segment
  2732. * @features: features for the output path (see dev->features)
  2733. */
  2734. struct sk_buff *skb_mac_gso_segment(struct sk_buff *skb,
  2735. netdev_features_t features)
  2736. {
  2737. struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
  2738. struct packet_offload *ptype;
  2739. int vlan_depth = skb->mac_len;
  2740. __be16 type = skb_network_protocol(skb, &vlan_depth);
  2741. if (unlikely(!type))
  2742. return ERR_PTR(-EINVAL);
  2743. __skb_pull(skb, vlan_depth);
  2744. rcu_read_lock();
  2745. list_for_each_entry_rcu(ptype, &offload_base, list) {
  2746. if (ptype->type == type && ptype->callbacks.gso_segment) {
  2747. segs = ptype->callbacks.gso_segment(skb, features);
  2748. break;
  2749. }
  2750. }
  2751. rcu_read_unlock();
  2752. __skb_push(skb, skb->data - skb_mac_header(skb));
  2753. return segs;
  2754. }
  2755. EXPORT_SYMBOL(skb_mac_gso_segment);
  2756. /* openvswitch calls this on rx path, so we need a different check.
  2757. */
  2758. static inline bool skb_needs_check(struct sk_buff *skb, bool tx_path)
  2759. {
  2760. if (tx_path)
  2761. return skb->ip_summed != CHECKSUM_PARTIAL &&
  2762. skb->ip_summed != CHECKSUM_UNNECESSARY;
  2763. return skb->ip_summed == CHECKSUM_NONE;
  2764. }
  2765. /**
  2766. * __skb_gso_segment - Perform segmentation on skb.
  2767. * @skb: buffer to segment
  2768. * @features: features for the output path (see dev->features)
  2769. * @tx_path: whether it is called in TX path
  2770. *
  2771. * This function segments the given skb and returns a list of segments.
  2772. *
  2773. * It may return NULL if the skb requires no segmentation. This is
  2774. * only possible when GSO is used for verifying header integrity.
  2775. *
  2776. * Segmentation preserves SKB_GSO_CB_OFFSET bytes of previous skb cb.
  2777. */
  2778. struct sk_buff *__skb_gso_segment(struct sk_buff *skb,
  2779. netdev_features_t features, bool tx_path)
  2780. {
  2781. struct sk_buff *segs;
  2782. if (unlikely(skb_needs_check(skb, tx_path))) {
  2783. int err;
  2784. /* We're going to init ->check field in TCP or UDP header */
  2785. err = skb_cow_head(skb, 0);
  2786. if (err < 0)
  2787. return ERR_PTR(err);
  2788. }
  2789. /* Only report GSO partial support if it will enable us to
  2790. * support segmentation on this frame without needing additional
  2791. * work.
  2792. */
  2793. if (features & NETIF_F_GSO_PARTIAL) {
  2794. netdev_features_t partial_features = NETIF_F_GSO_ROBUST;
  2795. struct net_device *dev = skb->dev;
  2796. partial_features |= dev->features & dev->gso_partial_features;
  2797. if (!skb_gso_ok(skb, features | partial_features))
  2798. features &= ~NETIF_F_GSO_PARTIAL;
  2799. }
  2800. BUILD_BUG_ON(SKB_GSO_CB_OFFSET +
  2801. sizeof(*SKB_GSO_CB(skb)) > sizeof(skb->cb));
  2802. SKB_GSO_CB(skb)->mac_offset = skb_headroom(skb);
  2803. SKB_GSO_CB(skb)->encap_level = 0;
  2804. skb_reset_mac_header(skb);
  2805. skb_reset_mac_len(skb);
  2806. segs = skb_mac_gso_segment(skb, features);
  2807. if (segs != skb && unlikely(skb_needs_check(skb, tx_path) && !IS_ERR(segs)))
  2808. skb_warn_bad_offload(skb);
  2809. return segs;
  2810. }
  2811. EXPORT_SYMBOL(__skb_gso_segment);
  2812. /* Take action when hardware reception checksum errors are detected. */
  2813. #ifdef CONFIG_BUG
  2814. void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
  2815. {
  2816. if (net_ratelimit()) {
  2817. pr_err("%s: hw csum failure\n", dev ? dev->name : "<unknown>");
  2818. skb_dump(KERN_ERR, skb, true);
  2819. dump_stack();
  2820. }
  2821. }
  2822. EXPORT_SYMBOL(netdev_rx_csum_fault);
  2823. #endif
  2824. /* XXX: check that highmem exists at all on the given machine. */
  2825. static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
  2826. {
  2827. #ifdef CONFIG_HIGHMEM
  2828. int i;
  2829. if (!(dev->features & NETIF_F_HIGHDMA)) {
  2830. for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
  2831. skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
  2832. if (PageHighMem(skb_frag_page(frag)))
  2833. return 1;
  2834. }
  2835. }
  2836. #endif
  2837. return 0;
  2838. }
  2839. /* If MPLS offload request, verify we are testing hardware MPLS features
  2840. * instead of standard features for the netdev.
  2841. */
  2842. #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
  2843. static netdev_features_t net_mpls_features(struct sk_buff *skb,
  2844. netdev_features_t features,
  2845. __be16 type)
  2846. {
  2847. if (eth_p_mpls(type))
  2848. features &= skb->dev->mpls_features;
  2849. return features;
  2850. }
  2851. #else
  2852. static netdev_features_t net_mpls_features(struct sk_buff *skb,
  2853. netdev_features_t features,
  2854. __be16 type)
  2855. {
  2856. return features;
  2857. }
  2858. #endif
  2859. static netdev_features_t harmonize_features(struct sk_buff *skb,
  2860. netdev_features_t features)
  2861. {
  2862. int tmp;
  2863. __be16 type;
  2864. type = skb_network_protocol(skb, &tmp);
  2865. features = net_mpls_features(skb, features, type);
  2866. if (skb->ip_summed != CHECKSUM_NONE &&
  2867. !can_checksum_protocol(features, type)) {
  2868. features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
  2869. }
  2870. if (illegal_highdma(skb->dev, skb))
  2871. features &= ~NETIF_F_SG;
  2872. return features;
  2873. }
  2874. netdev_features_t passthru_features_check(struct sk_buff *skb,
  2875. struct net_device *dev,
  2876. netdev_features_t features)
  2877. {
  2878. return features;
  2879. }
  2880. EXPORT_SYMBOL(passthru_features_check);
  2881. static netdev_features_t dflt_features_check(struct sk_buff *skb,
  2882. struct net_device *dev,
  2883. netdev_features_t features)
  2884. {
  2885. return vlan_features_check(skb, features);
  2886. }
  2887. static netdev_features_t gso_features_check(const struct sk_buff *skb,
  2888. struct net_device *dev,
  2889. netdev_features_t features)
  2890. {
  2891. u16 gso_segs = skb_shinfo(skb)->gso_segs;
  2892. if (gso_segs > dev->gso_max_segs)
  2893. return features & ~NETIF_F_GSO_MASK;
  2894. /* Support for GSO partial features requires software
  2895. * intervention before we can actually process the packets
  2896. * so we need to strip support for any partial features now
  2897. * and we can pull them back in after we have partially
  2898. * segmented the frame.
  2899. */
  2900. if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
  2901. features &= ~dev->gso_partial_features;
  2902. /* Make sure to clear the IPv4 ID mangling feature if the
  2903. * IPv4 header has the potential to be fragmented.
  2904. */
  2905. if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
  2906. struct iphdr *iph = skb->encapsulation ?
  2907. inner_ip_hdr(skb) : ip_hdr(skb);
  2908. if (!(iph->frag_off & htons(IP_DF)))
  2909. features &= ~NETIF_F_TSO_MANGLEID;
  2910. }
  2911. return features;
  2912. }
  2913. netdev_features_t netif_skb_features(struct sk_buff *skb)
  2914. {
  2915. struct net_device *dev = skb->dev;
  2916. netdev_features_t features = dev->features;
  2917. if (skb_is_gso(skb))
  2918. features = gso_features_check(skb, dev, features);
  2919. /* If encapsulation offload request, verify we are testing
  2920. * hardware encapsulation features instead of standard
  2921. * features for the netdev
  2922. */
  2923. if (skb->encapsulation)
  2924. features &= dev->hw_enc_features;
  2925. if (skb_vlan_tagged(skb))
  2926. features = netdev_intersect_features(features,
  2927. dev->vlan_features |
  2928. NETIF_F_HW_VLAN_CTAG_TX |
  2929. NETIF_F_HW_VLAN_STAG_TX);
  2930. if (dev->netdev_ops->ndo_features_check)
  2931. features &= dev->netdev_ops->ndo_features_check(skb, dev,
  2932. features);
  2933. else
  2934. features &= dflt_features_check(skb, dev, features);
  2935. return harmonize_features(skb, features);
  2936. }
  2937. EXPORT_SYMBOL(netif_skb_features);
  2938. static int xmit_one(struct sk_buff *skb, struct net_device *dev,
  2939. struct netdev_queue *txq, bool more)
  2940. {
  2941. unsigned int len;
  2942. int rc;
  2943. if (dev_nit_active(dev))
  2944. dev_queue_xmit_nit(skb, dev);
  2945. len = skb->len;
  2946. trace_net_dev_start_xmit(skb, dev);
  2947. rc = netdev_start_xmit(skb, dev, txq, more);
  2948. trace_net_dev_xmit(skb, rc, dev, len);
  2949. return rc;
  2950. }
  2951. struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
  2952. struct netdev_queue *txq, int *ret)
  2953. {
  2954. struct sk_buff *skb = first;
  2955. int rc = NETDEV_TX_OK;
  2956. while (skb) {
  2957. struct sk_buff *next = skb->next;
  2958. skb_mark_not_on_list(skb);
  2959. rc = xmit_one(skb, dev, txq, next != NULL);
  2960. if (unlikely(!dev_xmit_complete(rc))) {
  2961. skb->next = next;
  2962. goto out;
  2963. }
  2964. skb = next;
  2965. if (netif_tx_queue_stopped(txq) && skb) {
  2966. rc = NETDEV_TX_BUSY;
  2967. break;
  2968. }
  2969. }
  2970. out:
  2971. *ret = rc;
  2972. return skb;
  2973. }
  2974. static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
  2975. netdev_features_t features)
  2976. {
  2977. if (skb_vlan_tag_present(skb) &&
  2978. !vlan_hw_offload_capable(features, skb->vlan_proto))
  2979. skb = __vlan_hwaccel_push_inside(skb);
  2980. return skb;
  2981. }
  2982. int skb_csum_hwoffload_help(struct sk_buff *skb,
  2983. const netdev_features_t features)
  2984. {
  2985. if (unlikely(skb->csum_not_inet))
  2986. return !!(features & NETIF_F_SCTP_CRC) ? 0 :
  2987. skb_crc32c_csum_help(skb);
  2988. return !!(features & NETIF_F_CSUM_MASK) ? 0 : skb_checksum_help(skb);
  2989. }
  2990. EXPORT_SYMBOL(skb_csum_hwoffload_help);
  2991. static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
  2992. {
  2993. netdev_features_t features;
  2994. features = netif_skb_features(skb);
  2995. skb = validate_xmit_vlan(skb, features);
  2996. if (unlikely(!skb))
  2997. goto out_null;
  2998. skb = sk_validate_xmit_skb(skb, dev);
  2999. if (unlikely(!skb))
  3000. goto out_null;
  3001. if (netif_needs_gso(skb, features)) {
  3002. struct sk_buff *segs;
  3003. segs = skb_gso_segment(skb, features);
  3004. if (IS_ERR(segs)) {
  3005. goto out_kfree_skb;
  3006. } else if (segs) {
  3007. consume_skb(skb);
  3008. skb = segs;
  3009. }
  3010. } else {
  3011. if (skb_needs_linearize(skb, features) &&
  3012. __skb_linearize(skb))
  3013. goto out_kfree_skb;
  3014. /* If packet is not checksummed and device does not
  3015. * support checksumming for this protocol, complete
  3016. * checksumming here.
  3017. */
  3018. if (skb->ip_summed == CHECKSUM_PARTIAL) {
  3019. if (skb->encapsulation)
  3020. skb_set_inner_transport_header(skb,
  3021. skb_checksum_start_offset(skb));
  3022. else
  3023. skb_set_transport_header(skb,
  3024. skb_checksum_start_offset(skb));
  3025. if (skb_csum_hwoffload_help(skb, features))
  3026. goto out_kfree_skb;
  3027. }
  3028. }
  3029. skb = validate_xmit_xfrm(skb, features, again);
  3030. return skb;
  3031. out_kfree_skb:
  3032. kfree_skb(skb);
  3033. out_null:
  3034. atomic_long_inc(&dev->tx_dropped);
  3035. return NULL;
  3036. }
  3037. struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
  3038. {
  3039. struct sk_buff *next, *head = NULL, *tail;
  3040. for (; skb != NULL; skb = next) {
  3041. next = skb->next;
  3042. skb_mark_not_on_list(skb);
  3043. /* in case skb wont be segmented, point to itself */
  3044. skb->prev = skb;
  3045. skb = validate_xmit_skb(skb, dev, again);
  3046. if (!skb)
  3047. continue;
  3048. if (!head)
  3049. head = skb;
  3050. else
  3051. tail->next = skb;
  3052. /* If skb was segmented, skb->prev points to
  3053. * the last segment. If not, it still contains skb.
  3054. */
  3055. tail = skb->prev;
  3056. }
  3057. return head;
  3058. }
  3059. EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
  3060. static void qdisc_pkt_len_init(struct sk_buff *skb)
  3061. {
  3062. const struct skb_shared_info *shinfo = skb_shinfo(skb);
  3063. qdisc_skb_cb(skb)->pkt_len = skb->len;
  3064. /* To get more precise estimation of bytes sent on wire,
  3065. * we add to pkt_len the headers size of all segments
  3066. */
  3067. if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
  3068. unsigned int hdr_len;
  3069. u16 gso_segs = shinfo->gso_segs;
  3070. /* mac layer + network layer */
  3071. hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
  3072. /* + transport layer */
  3073. if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
  3074. const struct tcphdr *th;
  3075. struct tcphdr _tcphdr;
  3076. th = skb_header_pointer(skb, skb_transport_offset(skb),
  3077. sizeof(_tcphdr), &_tcphdr);
  3078. if (likely(th))
  3079. hdr_len += __tcp_hdrlen(th);
  3080. } else {
  3081. struct udphdr _udphdr;
  3082. if (skb_header_pointer(skb, skb_transport_offset(skb),
  3083. sizeof(_udphdr), &_udphdr))
  3084. hdr_len += sizeof(struct udphdr);
  3085. }
  3086. if (shinfo->gso_type & SKB_GSO_DODGY)
  3087. gso_segs = DIV_ROUND_UP(skb->len - hdr_len,
  3088. shinfo->gso_size);
  3089. qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
  3090. }
  3091. }
  3092. static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
  3093. struct net_device *dev,
  3094. struct netdev_queue *txq)
  3095. {
  3096. spinlock_t *root_lock = qdisc_lock(q);
  3097. struct sk_buff *to_free = NULL;
  3098. bool contended;
  3099. int rc;
  3100. qdisc_calculate_pkt_len(skb, q);
  3101. if (q->flags & TCQ_F_NOLOCK) {
  3102. rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
  3103. qdisc_run(q);
  3104. if (unlikely(to_free))
  3105. kfree_skb_list(to_free);
  3106. return rc;
  3107. }
  3108. /*
  3109. * Heuristic to force contended enqueues to serialize on a
  3110. * separate lock before trying to get qdisc main lock.
  3111. * This permits qdisc->running owner to get the lock more
  3112. * often and dequeue packets faster.
  3113. */
  3114. contended = qdisc_is_running(q);
  3115. if (unlikely(contended))
  3116. spin_lock(&q->busylock);
  3117. spin_lock(root_lock);
  3118. if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
  3119. __qdisc_drop(skb, &to_free);
  3120. rc = NET_XMIT_DROP;
  3121. } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
  3122. qdisc_run_begin(q)) {
  3123. /*
  3124. * This is a work-conserving queue; there are no old skbs
  3125. * waiting to be sent out; and the qdisc is not running -
  3126. * xmit the skb directly.
  3127. */
  3128. qdisc_bstats_update(q, skb);
  3129. if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
  3130. if (unlikely(contended)) {
  3131. spin_unlock(&q->busylock);
  3132. contended = false;
  3133. }
  3134. __qdisc_run(q);
  3135. }
  3136. qdisc_run_end(q);
  3137. rc = NET_XMIT_SUCCESS;
  3138. } else {
  3139. rc = q->enqueue(skb, q, &to_free) & NET_XMIT_MASK;
  3140. if (qdisc_run_begin(q)) {
  3141. if (unlikely(contended)) {
  3142. spin_unlock(&q->busylock);
  3143. contended = false;
  3144. }
  3145. __qdisc_run(q);
  3146. qdisc_run_end(q);
  3147. }
  3148. }
  3149. spin_unlock(root_lock);
  3150. if (unlikely(to_free))
  3151. kfree_skb_list(to_free);
  3152. if (unlikely(contended))
  3153. spin_unlock(&q->busylock);
  3154. return rc;
  3155. }
  3156. #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
  3157. static void skb_update_prio(struct sk_buff *skb)
  3158. {
  3159. const struct netprio_map *map;
  3160. const struct sock *sk;
  3161. unsigned int prioidx;
  3162. if (skb->priority)
  3163. return;
  3164. map = rcu_dereference_bh(skb->dev->priomap);
  3165. if (!map)
  3166. return;
  3167. sk = skb_to_full_sk(skb);
  3168. if (!sk)
  3169. return;
  3170. prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
  3171. if (prioidx < map->priomap_len)
  3172. skb->priority = map->priomap[prioidx];
  3173. }
  3174. #else
  3175. #define skb_update_prio(skb)
  3176. #endif
  3177. /**
  3178. * dev_loopback_xmit - loop back @skb
  3179. * @net: network namespace this loopback is happening in
  3180. * @sk: sk needed to be a netfilter okfn
  3181. * @skb: buffer to transmit
  3182. */
  3183. int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
  3184. {
  3185. skb_reset_mac_header(skb);
  3186. __skb_pull(skb, skb_network_offset(skb));
  3187. skb->pkt_type = PACKET_LOOPBACK;
  3188. skb->ip_summed = CHECKSUM_UNNECESSARY;
  3189. WARN_ON(!skb_dst(skb));
  3190. skb_dst_force(skb);
  3191. netif_rx_ni(skb);
  3192. return 0;
  3193. }
  3194. EXPORT_SYMBOL(dev_loopback_xmit);
  3195. #ifdef CONFIG_NET_EGRESS
  3196. static struct sk_buff *
  3197. sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
  3198. {
  3199. struct mini_Qdisc *miniq = rcu_dereference_bh(dev->miniq_egress);
  3200. struct tcf_result cl_res;
  3201. if (!miniq)
  3202. return skb;
  3203. /* qdisc_skb_cb(skb)->pkt_len was already set by the caller. */
  3204. mini_qdisc_bstats_cpu_update(miniq, skb);
  3205. switch (tcf_classify(skb, miniq->filter_list, &cl_res, false)) {
  3206. case TC_ACT_OK:
  3207. case TC_ACT_RECLASSIFY:
  3208. skb->tc_index = TC_H_MIN(cl_res.classid);
  3209. break;
  3210. case TC_ACT_SHOT:
  3211. mini_qdisc_qstats_cpu_drop(miniq);
  3212. *ret = NET_XMIT_DROP;
  3213. kfree_skb(skb);
  3214. return NULL;
  3215. case TC_ACT_STOLEN:
  3216. case TC_ACT_QUEUED:
  3217. case TC_ACT_TRAP:
  3218. *ret = NET_XMIT_SUCCESS;
  3219. consume_skb(skb);
  3220. return NULL;
  3221. case TC_ACT_REDIRECT:
  3222. /* No need to push/pop skb's mac_header here on egress! */
  3223. skb_do_redirect(skb);
  3224. *ret = NET_XMIT_SUCCESS;
  3225. return NULL;
  3226. default:
  3227. break;
  3228. }
  3229. return skb;
  3230. }
  3231. #endif /* CONFIG_NET_EGRESS */
  3232. #ifdef CONFIG_XPS
  3233. static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
  3234. struct xps_dev_maps *dev_maps, unsigned int tci)
  3235. {
  3236. struct xps_map *map;
  3237. int queue_index = -1;
  3238. if (dev->num_tc) {
  3239. tci *= dev->num_tc;
  3240. tci += netdev_get_prio_tc_map(dev, skb->priority);
  3241. }
  3242. map = rcu_dereference(dev_maps->attr_map[tci]);
  3243. if (map) {
  3244. if (map->len == 1)
  3245. queue_index = map->queues[0];
  3246. else
  3247. queue_index = map->queues[reciprocal_scale(
  3248. skb_get_hash(skb), map->len)];
  3249. if (unlikely(queue_index >= dev->real_num_tx_queues))
  3250. queue_index = -1;
  3251. }
  3252. return queue_index;
  3253. }
  3254. #endif
  3255. static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
  3256. struct sk_buff *skb)
  3257. {
  3258. #ifdef CONFIG_XPS
  3259. struct xps_dev_maps *dev_maps;
  3260. struct sock *sk = skb->sk;
  3261. int queue_index = -1;
  3262. if (!static_key_false(&xps_needed))
  3263. return -1;
  3264. rcu_read_lock();
  3265. if (!static_key_false(&xps_rxqs_needed))
  3266. goto get_cpus_map;
  3267. dev_maps = rcu_dereference(sb_dev->xps_rxqs_map);
  3268. if (dev_maps) {
  3269. int tci = sk_rx_queue_get(sk);
  3270. if (tci >= 0 && tci < dev->num_rx_queues)
  3271. queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
  3272. tci);
  3273. }
  3274. get_cpus_map:
  3275. if (queue_index < 0) {
  3276. dev_maps = rcu_dereference(sb_dev->xps_cpus_map);
  3277. if (dev_maps) {
  3278. unsigned int tci = skb->sender_cpu - 1;
  3279. queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
  3280. tci);
  3281. }
  3282. }
  3283. rcu_read_unlock();
  3284. return queue_index;
  3285. #else
  3286. return -1;
  3287. #endif
  3288. }
  3289. u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
  3290. struct net_device *sb_dev)
  3291. {
  3292. return 0;
  3293. }
  3294. EXPORT_SYMBOL(dev_pick_tx_zero);
  3295. u16 dev_pick_tx_cpu_id(struct net_device *dev, struct sk_buff *skb,
  3296. struct net_device *sb_dev)
  3297. {
  3298. return (u16)raw_smp_processor_id() % dev->real_num_tx_queues;
  3299. }
  3300. EXPORT_SYMBOL(dev_pick_tx_cpu_id);
  3301. u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
  3302. struct net_device *sb_dev)
  3303. {
  3304. struct sock *sk = skb->sk;
  3305. int queue_index = sk_tx_queue_get(sk);
  3306. sb_dev = sb_dev ? : dev;
  3307. if (queue_index < 0 || skb->ooo_okay ||
  3308. queue_index >= dev->real_num_tx_queues) {
  3309. int new_index = get_xps_queue(dev, sb_dev, skb);
  3310. if (new_index < 0)
  3311. new_index = skb_tx_hash(dev, sb_dev, skb);
  3312. if (queue_index != new_index && sk &&
  3313. sk_fullsock(sk) &&
  3314. rcu_access_pointer(sk->sk_dst_cache))
  3315. sk_tx_queue_set(sk, new_index);
  3316. queue_index = new_index;
  3317. }
  3318. return queue_index;
  3319. }
  3320. EXPORT_SYMBOL(netdev_pick_tx);
  3321. struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
  3322. struct sk_buff *skb,
  3323. struct net_device *sb_dev)
  3324. {
  3325. int queue_index = 0;
  3326. #ifdef CONFIG_XPS
  3327. u32 sender_cpu = skb->sender_cpu - 1;
  3328. if (sender_cpu >= (u32)NR_CPUS)
  3329. skb->sender_cpu = raw_smp_processor_id() + 1;
  3330. #endif
  3331. if (dev->real_num_tx_queues != 1) {
  3332. const struct net_device_ops *ops = dev->netdev_ops;
  3333. if (ops->ndo_select_queue)
  3334. queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
  3335. else
  3336. queue_index = netdev_pick_tx(dev, skb, sb_dev);
  3337. queue_index = netdev_cap_txqueue(dev, queue_index);
  3338. }
  3339. skb_set_queue_mapping(skb, queue_index);
  3340. return netdev_get_tx_queue(dev, queue_index);
  3341. }
  3342. /**
  3343. * __dev_queue_xmit - transmit a buffer
  3344. * @skb: buffer to transmit
  3345. * @sb_dev: suboordinate device used for L2 forwarding offload
  3346. *
  3347. * Queue a buffer for transmission to a network device. The caller must
  3348. * have set the device and priority and built the buffer before calling
  3349. * this function. The function can be called from an interrupt.
  3350. *
  3351. * A negative errno code is returned on a failure. A success does not
  3352. * guarantee the frame will be transmitted as it may be dropped due
  3353. * to congestion or traffic shaping.
  3354. *
  3355. * -----------------------------------------------------------------------------------
  3356. * I notice this method can also return errors from the queue disciplines,
  3357. * including NET_XMIT_DROP, which is a positive value. So, errors can also
  3358. * be positive.
  3359. *
  3360. * Regardless of the return value, the skb is consumed, so it is currently
  3361. * difficult to retry a send to this method. (You can bump the ref count
  3362. * before sending to hold a reference for retry if you are careful.)
  3363. *
  3364. * When calling this method, interrupts MUST be enabled. This is because
  3365. * the BH enable code must have IRQs enabled so that it will not deadlock.
  3366. * --BLG
  3367. */
  3368. static int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
  3369. {
  3370. struct net_device *dev = skb->dev;
  3371. struct netdev_queue *txq;
  3372. struct Qdisc *q;
  3373. int rc = -ENOMEM;
  3374. bool again = false;
  3375. skb_reset_mac_header(skb);
  3376. if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
  3377. __skb_tstamp_tx(skb, NULL, skb->sk, SCM_TSTAMP_SCHED);
  3378. /* Disable soft irqs for various locks below. Also
  3379. * stops preemption for RCU.
  3380. */
  3381. rcu_read_lock_bh();
  3382. skb_update_prio(skb);
  3383. qdisc_pkt_len_init(skb);
  3384. #ifdef CONFIG_NET_CLS_ACT
  3385. skb->tc_at_ingress = 0;
  3386. # ifdef CONFIG_NET_EGRESS
  3387. if (static_branch_unlikely(&egress_needed_key)) {
  3388. skb = sch_handle_egress(skb, &rc, dev);
  3389. if (!skb)
  3390. goto out;
  3391. }
  3392. # endif
  3393. #endif
  3394. /* If device/qdisc don't need skb->dst, release it right now while
  3395. * its hot in this cpu cache.
  3396. */
  3397. if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
  3398. skb_dst_drop(skb);
  3399. else
  3400. skb_dst_force(skb);
  3401. txq = netdev_core_pick_tx(dev, skb, sb_dev);
  3402. q = rcu_dereference_bh(txq->qdisc);
  3403. trace_net_dev_queue(skb);
  3404. if (q->enqueue) {
  3405. rc = __dev_xmit_skb(skb, q, dev, txq);
  3406. goto out;
  3407. }
  3408. /* The device has no queue. Common case for software devices:
  3409. * loopback, all the sorts of tunnels...
  3410. * Really, it is unlikely that netif_tx_lock protection is necessary
  3411. * here. (f.e. loopback and IP tunnels are clean ignoring statistics
  3412. * counters.)
  3413. * However, it is possible, that they rely on protection
  3414. * made by us here.
  3415. * Check this and shot the lock. It is not prone from deadlocks.
  3416. *Either shot noqueue qdisc, it is even simpler 8)
  3417. */
  3418. if (dev->flags & IFF_UP) {
  3419. int cpu = smp_processor_id(); /* ok because BHs are off */
  3420. if (txq->xmit_lock_owner != cpu) {
  3421. if (dev_xmit_recursion())
  3422. goto recursion_alert;
  3423. skb = validate_xmit_skb(skb, dev, &again);
  3424. if (!skb)
  3425. goto out;
  3426. HARD_TX_LOCK(dev, txq, cpu);
  3427. if (!netif_xmit_stopped(txq)) {
  3428. dev_xmit_recursion_inc();
  3429. skb = dev_hard_start_xmit(skb, dev, txq, &rc);
  3430. dev_xmit_recursion_dec();
  3431. if (dev_xmit_complete(rc)) {
  3432. HARD_TX_UNLOCK(dev, txq);
  3433. goto out;
  3434. }
  3435. }
  3436. HARD_TX_UNLOCK(dev, txq);
  3437. net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
  3438. dev->name);
  3439. } else {
  3440. /* Recursion is detected! It is possible,
  3441. * unfortunately
  3442. */
  3443. recursion_alert:
  3444. net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
  3445. dev->name);
  3446. }
  3447. }
  3448. rc = -ENETDOWN;
  3449. rcu_read_unlock_bh();
  3450. atomic_long_inc(&dev->tx_dropped);
  3451. kfree_skb_list(skb);
  3452. return rc;
  3453. out:
  3454. rcu_read_unlock_bh();
  3455. return rc;
  3456. }
  3457. int dev_queue_xmit(struct sk_buff *skb)
  3458. {
  3459. return __dev_queue_xmit(skb, NULL);
  3460. }
  3461. EXPORT_SYMBOL(dev_queue_xmit);
  3462. int dev_queue_xmit_accel(struct sk_buff *skb, struct net_device *sb_dev)
  3463. {
  3464. return __dev_queue_xmit(skb, sb_dev);
  3465. }
  3466. EXPORT_SYMBOL(dev_queue_xmit_accel);
  3467. int dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
  3468. {
  3469. struct net_device *dev = skb->dev;
  3470. struct sk_buff *orig_skb = skb;
  3471. struct netdev_queue *txq;
  3472. int ret = NETDEV_TX_BUSY;
  3473. bool again = false;
  3474. if (unlikely(!netif_running(dev) ||
  3475. !netif_carrier_ok(dev)))
  3476. goto drop;
  3477. skb = validate_xmit_skb_list(skb, dev, &again);
  3478. if (skb != orig_skb)
  3479. goto drop;
  3480. skb_set_queue_mapping(skb, queue_id);
  3481. txq = skb_get_tx_queue(dev, skb);
  3482. local_bh_disable();
  3483. HARD_TX_LOCK(dev, txq, smp_processor_id());
  3484. if (!netif_xmit_frozen_or_drv_stopped(txq))
  3485. ret = netdev_start_xmit(skb, dev, txq, false);
  3486. HARD_TX_UNLOCK(dev, txq);
  3487. local_bh_enable();
  3488. if (!dev_xmit_complete(ret))
  3489. kfree_skb(skb);
  3490. return ret;
  3491. drop:
  3492. atomic_long_inc(&dev->tx_dropped);
  3493. kfree_skb_list(skb);
  3494. return NET_XMIT_DROP;
  3495. }
  3496. EXPORT_SYMBOL(dev_direct_xmit);
  3497. /*************************************************************************
  3498. * Receiver routines
  3499. *************************************************************************/
  3500. int netdev_max_backlog __read_mostly = 1000;
  3501. EXPORT_SYMBOL(netdev_max_backlog);
  3502. int netdev_tstamp_prequeue __read_mostly = 1;
  3503. int netdev_budget __read_mostly = 300;
  3504. /* Must be at least 2 jiffes to guarantee 1 jiffy timeout */
  3505. unsigned int __read_mostly netdev_budget_usecs = 2 * USEC_PER_SEC / HZ;
  3506. int weight_p __read_mostly = 64; /* old backlog weight */
  3507. int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
  3508. int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
  3509. int dev_rx_weight __read_mostly = 64;
  3510. int dev_tx_weight __read_mostly = 64;
  3511. /* Maximum number of GRO_NORMAL skbs to batch up for list-RX */
  3512. int gro_normal_batch __read_mostly = 8;
  3513. /* Called with irq disabled */
  3514. static inline void ____napi_schedule(struct softnet_data *sd,
  3515. struct napi_struct *napi)
  3516. {
  3517. list_add_tail(&napi->poll_list, &sd->poll_list);
  3518. __raise_softirq_irqoff(NET_RX_SOFTIRQ);
  3519. }
  3520. #ifdef CONFIG_RPS
  3521. /* One global table that all flow-based protocols share. */
  3522. struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
  3523. EXPORT_SYMBOL(rps_sock_flow_table);
  3524. u32 rps_cpu_mask __read_mostly;
  3525. EXPORT_SYMBOL(rps_cpu_mask);
  3526. struct static_key_false rps_needed __read_mostly;
  3527. EXPORT_SYMBOL(rps_needed);
  3528. struct static_key_false rfs_needed __read_mostly;
  3529. EXPORT_SYMBOL(rfs_needed);
  3530. static struct rps_dev_flow *
  3531. set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
  3532. struct rps_dev_flow *rflow, u16 next_cpu)
  3533. {
  3534. if (next_cpu < nr_cpu_ids) {
  3535. #ifdef CONFIG_RFS_ACCEL
  3536. struct netdev_rx_queue *rxqueue;
  3537. struct rps_dev_flow_table *flow_table;
  3538. struct rps_dev_flow *old_rflow;
  3539. u32 flow_id;
  3540. u16 rxq_index;
  3541. int rc;
  3542. /* Should we steer this flow to a different hardware queue? */
  3543. if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
  3544. !(dev->features & NETIF_F_NTUPLE))
  3545. goto out;
  3546. rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
  3547. if (rxq_index == skb_get_rx_queue(skb))
  3548. goto out;
  3549. rxqueue = dev->_rx + rxq_index;
  3550. flow_table = rcu_dereference(rxqueue->rps_flow_table);
  3551. if (!flow_table)
  3552. goto out;
  3553. flow_id = skb_get_hash(skb) & flow_table->mask;
  3554. rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
  3555. rxq_index, flow_id);
  3556. if (rc < 0)
  3557. goto out;
  3558. old_rflow = rflow;
  3559. rflow = &flow_table->flows[flow_id];
  3560. rflow->filter = rc;
  3561. if (old_rflow->filter == rflow->filter)
  3562. old_rflow->filter = RPS_NO_FILTER;
  3563. out:
  3564. #endif
  3565. rflow->last_qtail =
  3566. per_cpu(softnet_data, next_cpu).input_queue_head;
  3567. }
  3568. rflow->cpu = next_cpu;
  3569. return rflow;
  3570. }
  3571. /*
  3572. * get_rps_cpu is called from netif_receive_skb and returns the target
  3573. * CPU from the RPS map of the receiving queue for a given skb.
  3574. * rcu_read_lock must be held on entry.
  3575. */
  3576. static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
  3577. struct rps_dev_flow **rflowp)
  3578. {
  3579. const struct rps_sock_flow_table *sock_flow_table;
  3580. struct netdev_rx_queue *rxqueue = dev->_rx;
  3581. struct rps_dev_flow_table *flow_table;
  3582. struct rps_map *map;
  3583. int cpu = -1;
  3584. u32 tcpu;
  3585. u32 hash;
  3586. if (skb_rx_queue_recorded(skb)) {
  3587. u16 index = skb_get_rx_queue(skb);
  3588. if (unlikely(index >= dev->real_num_rx_queues)) {
  3589. WARN_ONCE(dev->real_num_rx_queues > 1,
  3590. "%s received packet on queue %u, but number "
  3591. "of RX queues is %u\n",
  3592. dev->name, index, dev->real_num_rx_queues);
  3593. goto done;
  3594. }
  3595. rxqueue += index;
  3596. }
  3597. /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
  3598. flow_table = rcu_dereference(rxqueue->rps_flow_table);
  3599. map = rcu_dereference(rxqueue->rps_map);
  3600. if (!flow_table && !map)
  3601. goto done;
  3602. skb_reset_network_header(skb);
  3603. hash = skb_get_hash(skb);
  3604. if (!hash)
  3605. goto done;
  3606. sock_flow_table = rcu_dereference(rps_sock_flow_table);
  3607. if (flow_table && sock_flow_table) {
  3608. struct rps_dev_flow *rflow;
  3609. u32 next_cpu;
  3610. u32 ident;
  3611. /* First check into global flow table if there is a match */
  3612. ident = sock_flow_table->ents[hash & sock_flow_table->mask];
  3613. if ((ident ^ hash) & ~rps_cpu_mask)
  3614. goto try_rps;
  3615. next_cpu = ident & rps_cpu_mask;
  3616. /* OK, now we know there is a match,
  3617. * we can look at the local (per receive queue) flow table
  3618. */
  3619. rflow = &flow_table->flows[hash & flow_table->mask];
  3620. tcpu = rflow->cpu;
  3621. /*
  3622. * If the desired CPU (where last recvmsg was done) is
  3623. * different from current CPU (one in the rx-queue flow
  3624. * table entry), switch if one of the following holds:
  3625. * - Current CPU is unset (>= nr_cpu_ids).
  3626. * - Current CPU is offline.
  3627. * - The current CPU's queue tail has advanced beyond the
  3628. * last packet that was enqueued using this table entry.
  3629. * This guarantees that all previous packets for the flow
  3630. * have been dequeued, thus preserving in order delivery.
  3631. */
  3632. if (unlikely(tcpu != next_cpu) &&
  3633. (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
  3634. ((int)(per_cpu(softnet_data, tcpu).input_queue_head -
  3635. rflow->last_qtail)) >= 0)) {
  3636. tcpu = next_cpu;
  3637. rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
  3638. }
  3639. if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
  3640. *rflowp = rflow;
  3641. cpu = tcpu;
  3642. goto done;
  3643. }
  3644. }
  3645. try_rps:
  3646. if (map) {
  3647. tcpu = map->cpus[reciprocal_scale(hash, map->len)];
  3648. if (cpu_online(tcpu)) {
  3649. cpu = tcpu;
  3650. goto done;
  3651. }
  3652. }
  3653. done:
  3654. return cpu;
  3655. }
  3656. #ifdef CONFIG_RFS_ACCEL
  3657. /**
  3658. * rps_may_expire_flow - check whether an RFS hardware filter may be removed
  3659. * @dev: Device on which the filter was set
  3660. * @rxq_index: RX queue index
  3661. * @flow_id: Flow ID passed to ndo_rx_flow_steer()
  3662. * @filter_id: Filter ID returned by ndo_rx_flow_steer()
  3663. *
  3664. * Drivers that implement ndo_rx_flow_steer() should periodically call
  3665. * this function for each installed filter and remove the filters for
  3666. * which it returns %true.
  3667. */
  3668. bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
  3669. u32 flow_id, u16 filter_id)
  3670. {
  3671. struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
  3672. struct rps_dev_flow_table *flow_table;
  3673. struct rps_dev_flow *rflow;
  3674. bool expire = true;
  3675. unsigned int cpu;
  3676. rcu_read_lock();
  3677. flow_table = rcu_dereference(rxqueue->rps_flow_table);
  3678. if (flow_table && flow_id <= flow_table->mask) {
  3679. rflow = &flow_table->flows[flow_id];
  3680. cpu = READ_ONCE(rflow->cpu);
  3681. if (rflow->filter == filter_id && cpu < nr_cpu_ids &&
  3682. ((int)(per_cpu(softnet_data, cpu).input_queue_head -
  3683. rflow->last_qtail) <
  3684. (int)(10 * flow_table->mask)))
  3685. expire = false;
  3686. }
  3687. rcu_read_unlock();
  3688. return expire;
  3689. }
  3690. EXPORT_SYMBOL(rps_may_expire_flow);
  3691. #endif /* CONFIG_RFS_ACCEL */
  3692. /* Called from hardirq (IPI) context */
  3693. static void rps_trigger_softirq(void *data)
  3694. {
  3695. struct softnet_data *sd = data;
  3696. ____napi_schedule(sd, &sd->backlog);
  3697. sd->received_rps++;
  3698. }
  3699. #endif /* CONFIG_RPS */
  3700. /*
  3701. * Check if this softnet_data structure is another cpu one
  3702. * If yes, queue it to our IPI list and return 1
  3703. * If no, return 0
  3704. */
  3705. static int rps_ipi_queued(struct softnet_data *sd)
  3706. {
  3707. #ifdef CONFIG_RPS
  3708. struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
  3709. if (sd != mysd) {
  3710. sd->rps_ipi_next = mysd->rps_ipi_list;
  3711. mysd->rps_ipi_list = sd;
  3712. __raise_softirq_irqoff(NET_RX_SOFTIRQ);
  3713. return 1;
  3714. }
  3715. #endif /* CONFIG_RPS */
  3716. return 0;
  3717. }
  3718. #ifdef CONFIG_NET_FLOW_LIMIT
  3719. int netdev_flow_limit_table_len __read_mostly = (1 << 12);
  3720. #endif
  3721. static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
  3722. {
  3723. #ifdef CONFIG_NET_FLOW_LIMIT
  3724. struct sd_flow_limit *fl;
  3725. struct softnet_data *sd;
  3726. unsigned int old_flow, new_flow;
  3727. if (qlen < (netdev_max_backlog >> 1))
  3728. return false;
  3729. sd = this_cpu_ptr(&softnet_data);
  3730. rcu_read_lock();
  3731. fl = rcu_dereference(sd->flow_limit);
  3732. if (fl) {
  3733. new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
  3734. old_flow = fl->history[fl->history_head];
  3735. fl->history[fl->history_head] = new_flow;
  3736. fl->history_head++;
  3737. fl->history_head &= FLOW_LIMIT_HISTORY - 1;
  3738. if (likely(fl->buckets[old_flow]))
  3739. fl->buckets[old_flow]--;
  3740. if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
  3741. fl->count++;
  3742. rcu_read_unlock();
  3743. return true;
  3744. }
  3745. }
  3746. rcu_read_unlock();
  3747. #endif
  3748. return false;
  3749. }
  3750. /*
  3751. * enqueue_to_backlog is called to queue an skb to a per CPU backlog
  3752. * queue (may be a remote CPU queue).
  3753. */
  3754. static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
  3755. unsigned int *qtail)
  3756. {
  3757. struct softnet_data *sd;
  3758. unsigned long flags;
  3759. unsigned int qlen;
  3760. sd = &per_cpu(softnet_data, cpu);
  3761. local_irq_save(flags);
  3762. rps_lock(sd);
  3763. if (!netif_running(skb->dev))
  3764. goto drop;
  3765. qlen = skb_queue_len(&sd->input_pkt_queue);
  3766. if (qlen <= netdev_max_backlog && !skb_flow_limit(skb, qlen)) {
  3767. if (qlen) {
  3768. enqueue:
  3769. __skb_queue_tail(&sd->input_pkt_queue, skb);
  3770. input_queue_tail_incr_save(sd, qtail);
  3771. rps_unlock(sd);
  3772. local_irq_restore(flags);
  3773. return NET_RX_SUCCESS;
  3774. }
  3775. /* Schedule NAPI for backlog device
  3776. * We can use non atomic operation since we own the queue lock
  3777. */
  3778. if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
  3779. if (!rps_ipi_queued(sd))
  3780. ____napi_schedule(sd, &sd->backlog);
  3781. }
  3782. goto enqueue;
  3783. }
  3784. drop:
  3785. sd->dropped++;
  3786. rps_unlock(sd);
  3787. local_irq_restore(flags);
  3788. atomic_long_inc(&skb->dev->rx_dropped);
  3789. kfree_skb(skb);
  3790. return NET_RX_DROP;
  3791. }
  3792. static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
  3793. {
  3794. struct net_device *dev = skb->dev;
  3795. struct netdev_rx_queue *rxqueue;
  3796. rxqueue = dev->_rx;
  3797. if (skb_rx_queue_recorded(skb)) {
  3798. u16 index = skb_get_rx_queue(skb);
  3799. if (unlikely(index >= dev->real_num_rx_queues)) {
  3800. WARN_ONCE(dev->real_num_rx_queues > 1,
  3801. "%s received packet on queue %u, but number "
  3802. "of RX queues is %u\n",
  3803. dev->name, index, dev->real_num_rx_queues);
  3804. return rxqueue; /* Return first rxqueue */
  3805. }
  3806. rxqueue += index;
  3807. }
  3808. return rxqueue;
  3809. }
  3810. static u32 netif_receive_generic_xdp(struct sk_buff *skb,
  3811. struct xdp_buff *xdp,
  3812. struct bpf_prog *xdp_prog)
  3813. {
  3814. struct netdev_rx_queue *rxqueue;
  3815. void *orig_data, *orig_data_end;
  3816. u32 metalen, act = XDP_DROP;
  3817. __be16 orig_eth_type;
  3818. struct ethhdr *eth;
  3819. bool orig_bcast;
  3820. int hlen, off;
  3821. u32 mac_len;
  3822. /* Reinjected packets coming from act_mirred or similar should
  3823. * not get XDP generic processing.
  3824. */
  3825. if (skb_is_redirected(skb))
  3826. return XDP_PASS;
  3827. /* XDP packets must be linear and must have sufficient headroom
  3828. * of XDP_PACKET_HEADROOM bytes. This is the guarantee that also
  3829. * native XDP provides, thus we need to do it here as well.
  3830. */
  3831. if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
  3832. skb_headroom(skb) < XDP_PACKET_HEADROOM) {
  3833. int hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
  3834. int troom = skb->tail + skb->data_len - skb->end;
  3835. /* In case we have to go down the path and also linearize,
  3836. * then lets do the pskb_expand_head() work just once here.
  3837. */
  3838. if (pskb_expand_head(skb,
  3839. hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
  3840. troom > 0 ? troom + 128 : 0, GFP_ATOMIC))
  3841. goto do_drop;
  3842. if (skb_linearize(skb))
  3843. goto do_drop;
  3844. }
  3845. /* The XDP program wants to see the packet starting at the MAC
  3846. * header.
  3847. */
  3848. mac_len = skb->data - skb_mac_header(skb);
  3849. hlen = skb_headlen(skb) + mac_len;
  3850. xdp->data = skb->data - mac_len;
  3851. xdp->data_meta = xdp->data;
  3852. xdp->data_end = xdp->data + hlen;
  3853. xdp->data_hard_start = skb->data - skb_headroom(skb);
  3854. orig_data_end = xdp->data_end;
  3855. orig_data = xdp->data;
  3856. eth = (struct ethhdr *)xdp->data;
  3857. orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
  3858. orig_eth_type = eth->h_proto;
  3859. rxqueue = netif_get_rxqueue(skb);
  3860. xdp->rxq = &rxqueue->xdp_rxq;
  3861. act = bpf_prog_run_xdp(xdp_prog, xdp);
  3862. /* check if bpf_xdp_adjust_head was used */
  3863. off = xdp->data - orig_data;
  3864. if (off) {
  3865. if (off > 0)
  3866. __skb_pull(skb, off);
  3867. else if (off < 0)
  3868. __skb_push(skb, -off);
  3869. skb->mac_header += off;
  3870. skb_reset_network_header(skb);
  3871. }
  3872. /* check if bpf_xdp_adjust_tail was used. it can only "shrink"
  3873. * pckt.
  3874. */
  3875. off = orig_data_end - xdp->data_end;
  3876. if (off != 0) {
  3877. skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
  3878. skb->len -= off;
  3879. }
  3880. /* check if XDP changed eth hdr such SKB needs update */
  3881. eth = (struct ethhdr *)xdp->data;
  3882. if ((orig_eth_type != eth->h_proto) ||
  3883. (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
  3884. __skb_push(skb, ETH_HLEN);
  3885. skb->protocol = eth_type_trans(skb, skb->dev);
  3886. }
  3887. switch (act) {
  3888. case XDP_REDIRECT:
  3889. case XDP_TX:
  3890. __skb_push(skb, mac_len);
  3891. break;
  3892. case XDP_PASS:
  3893. metalen = xdp->data - xdp->data_meta;
  3894. if (metalen)
  3895. skb_metadata_set(skb, metalen);
  3896. break;
  3897. default:
  3898. bpf_warn_invalid_xdp_action(act);
  3899. /* fall through */
  3900. case XDP_ABORTED:
  3901. trace_xdp_exception(skb->dev, xdp_prog, act);
  3902. /* fall through */
  3903. case XDP_DROP:
  3904. do_drop:
  3905. kfree_skb(skb);
  3906. break;
  3907. }
  3908. return act;
  3909. }
  3910. /* When doing generic XDP we have to bypass the qdisc layer and the
  3911. * network taps in order to match in-driver-XDP behavior.
  3912. */
  3913. void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
  3914. {
  3915. struct net_device *dev = skb->dev;
  3916. struct netdev_queue *txq;
  3917. bool free_skb = true;
  3918. int cpu, rc;
  3919. txq = netdev_core_pick_tx(dev, skb, NULL);
  3920. cpu = smp_processor_id();
  3921. HARD_TX_LOCK(dev, txq, cpu);
  3922. if (!netif_xmit_stopped(txq)) {
  3923. rc = netdev_start_xmit(skb, dev, txq, 0);
  3924. if (dev_xmit_complete(rc))
  3925. free_skb = false;
  3926. }
  3927. HARD_TX_UNLOCK(dev, txq);
  3928. if (free_skb) {
  3929. trace_xdp_exception(dev, xdp_prog, XDP_TX);
  3930. kfree_skb(skb);
  3931. }
  3932. }
  3933. static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
  3934. int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff *skb)
  3935. {
  3936. if (xdp_prog) {
  3937. struct xdp_buff xdp;
  3938. u32 act;
  3939. int err;
  3940. act = netif_receive_generic_xdp(skb, &xdp, xdp_prog);
  3941. if (act != XDP_PASS) {
  3942. switch (act) {
  3943. case XDP_REDIRECT:
  3944. err = xdp_do_generic_redirect(skb->dev, skb,
  3945. &xdp, xdp_prog);
  3946. if (err)
  3947. goto out_redir;
  3948. break;
  3949. case XDP_TX:
  3950. generic_xdp_tx(skb, xdp_prog);
  3951. break;
  3952. }
  3953. return XDP_DROP;
  3954. }
  3955. }
  3956. return XDP_PASS;
  3957. out_redir:
  3958. kfree_skb(skb);
  3959. return XDP_DROP;
  3960. }
  3961. EXPORT_SYMBOL_GPL(do_xdp_generic);
  3962. static int netif_rx_internal(struct sk_buff *skb)
  3963. {
  3964. int ret;
  3965. net_timestamp_check(netdev_tstamp_prequeue, skb);
  3966. trace_netif_rx(skb);
  3967. #ifdef CONFIG_RPS
  3968. if (static_branch_unlikely(&rps_needed)) {
  3969. struct rps_dev_flow voidflow, *rflow = &voidflow;
  3970. int cpu;
  3971. preempt_disable();
  3972. rcu_read_lock();
  3973. cpu = get_rps_cpu(skb->dev, skb, &rflow);
  3974. if (cpu < 0)
  3975. cpu = smp_processor_id();
  3976. ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
  3977. rcu_read_unlock();
  3978. preempt_enable();
  3979. } else
  3980. #endif
  3981. {
  3982. unsigned int qtail;
  3983. ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
  3984. put_cpu();
  3985. }
  3986. return ret;
  3987. }
  3988. /**
  3989. * netif_rx - post buffer to the network code
  3990. * @skb: buffer to post
  3991. *
  3992. * This function receives a packet from a device driver and queues it for
  3993. * the upper (protocol) levels to process. It always succeeds. The buffer
  3994. * may be dropped during processing for congestion control or by the
  3995. * protocol layers.
  3996. *
  3997. * return values:
  3998. * NET_RX_SUCCESS (no congestion)
  3999. * NET_RX_DROP (packet was dropped)
  4000. *
  4001. */
  4002. int netif_rx(struct sk_buff *skb)
  4003. {
  4004. int ret;
  4005. trace_netif_rx_entry(skb);
  4006. ret = netif_rx_internal(skb);
  4007. trace_netif_rx_exit(ret);
  4008. return ret;
  4009. }
  4010. EXPORT_SYMBOL(netif_rx);
  4011. int netif_rx_ni(struct sk_buff *skb)
  4012. {
  4013. int err;
  4014. trace_netif_rx_ni_entry(skb);
  4015. preempt_disable();
  4016. err = netif_rx_internal(skb);
  4017. if (local_softirq_pending())
  4018. do_softirq();
  4019. preempt_enable();
  4020. trace_netif_rx_ni_exit(err);
  4021. return err;
  4022. }
  4023. EXPORT_SYMBOL(netif_rx_ni);
  4024. static __latent_entropy void net_tx_action(struct softirq_action *h)
  4025. {
  4026. struct softnet_data *sd = this_cpu_ptr(&softnet_data);
  4027. if (sd->completion_queue) {
  4028. struct sk_buff *clist;
  4029. local_irq_disable();
  4030. clist = sd->completion_queue;
  4031. sd->completion_queue = NULL;
  4032. local_irq_enable();
  4033. while (clist) {
  4034. struct sk_buff *skb = clist;
  4035. clist = clist->next;
  4036. WARN_ON(refcount_read(&skb->users));
  4037. if (likely(get_kfree_skb_cb(skb)->reason == SKB_REASON_CONSUMED))
  4038. trace_consume_skb(skb);
  4039. else
  4040. trace_kfree_skb(skb, net_tx_action);
  4041. if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
  4042. __kfree_skb(skb);
  4043. else
  4044. __kfree_skb_defer(skb);
  4045. }
  4046. __kfree_skb_flush();
  4047. }
  4048. if (sd->output_queue) {
  4049. struct Qdisc *head;
  4050. local_irq_disable();
  4051. head = sd->output_queue;
  4052. sd->output_queue = NULL;
  4053. sd->output_queue_tailp = &sd->output_queue;
  4054. local_irq_enable();
  4055. while (head) {
  4056. struct Qdisc *q = head;
  4057. spinlock_t *root_lock = NULL;
  4058. head = head->next_sched;
  4059. if (!(q->flags & TCQ_F_NOLOCK)) {
  4060. root_lock = qdisc_lock(q);
  4061. spin_lock(root_lock);
  4062. }
  4063. /* We need to make sure head->next_sched is read
  4064. * before clearing __QDISC_STATE_SCHED
  4065. */
  4066. smp_mb__before_atomic();
  4067. clear_bit(__QDISC_STATE_SCHED, &q->state);
  4068. qdisc_run(q);
  4069. if (root_lock)
  4070. spin_unlock(root_lock);
  4071. }
  4072. }
  4073. xfrm_dev_backlog(sd);
  4074. }
  4075. #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
  4076. /* This hook is defined here for ATM LANE */
  4077. int (*br_fdb_test_addr_hook)(struct net_device *dev,
  4078. unsigned char *addr) __read_mostly;
  4079. EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
  4080. #endif
  4081. static inline struct sk_buff *
  4082. sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
  4083. struct net_device *orig_dev)
  4084. {
  4085. #ifdef CONFIG_NET_CLS_ACT
  4086. struct mini_Qdisc *miniq = rcu_dereference_bh(skb->dev->miniq_ingress);
  4087. struct tcf_result cl_res;
  4088. /* If there's at least one ingress present somewhere (so
  4089. * we get here via enabled static key), remaining devices
  4090. * that are not configured with an ingress qdisc will bail
  4091. * out here.
  4092. */
  4093. if (!miniq)
  4094. return skb;
  4095. if (*pt_prev) {
  4096. *ret = deliver_skb(skb, *pt_prev, orig_dev);
  4097. *pt_prev = NULL;
  4098. }
  4099. qdisc_skb_cb(skb)->pkt_len = skb->len;
  4100. skb->tc_at_ingress = 1;
  4101. mini_qdisc_bstats_cpu_update(miniq, skb);
  4102. switch (tcf_classify_ingress(skb, miniq->block, miniq->filter_list,
  4103. &cl_res, false)) {
  4104. case TC_ACT_OK:
  4105. case TC_ACT_RECLASSIFY:
  4106. skb->tc_index = TC_H_MIN(cl_res.classid);
  4107. break;
  4108. case TC_ACT_SHOT:
  4109. mini_qdisc_qstats_cpu_drop(miniq);
  4110. kfree_skb(skb);
  4111. return NULL;
  4112. case TC_ACT_STOLEN:
  4113. case TC_ACT_QUEUED:
  4114. case TC_ACT_TRAP:
  4115. consume_skb(skb);
  4116. return NULL;
  4117. case TC_ACT_REDIRECT:
  4118. /* skb_mac_header check was done by cls/act_bpf, so
  4119. * we can safely push the L2 header back before
  4120. * redirecting to another netdev
  4121. */
  4122. __skb_push(skb, skb->mac_len);
  4123. skb_do_redirect(skb);
  4124. return NULL;
  4125. case TC_ACT_CONSUMED:
  4126. return NULL;
  4127. default:
  4128. break;
  4129. }
  4130. #endif /* CONFIG_NET_CLS_ACT */
  4131. return skb;
  4132. }
  4133. /**
  4134. * netdev_is_rx_handler_busy - check if receive handler is registered
  4135. * @dev: device to check
  4136. *
  4137. * Check if a receive handler is already registered for a given device.
  4138. * Return true if there one.
  4139. *
  4140. * The caller must hold the rtnl_mutex.
  4141. */
  4142. bool netdev_is_rx_handler_busy(struct net_device *dev)
  4143. {
  4144. ASSERT_RTNL();
  4145. return dev && rtnl_dereference(dev->rx_handler);
  4146. }
  4147. EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
  4148. /**
  4149. * netdev_rx_handler_register - register receive handler
  4150. * @dev: device to register a handler for
  4151. * @rx_handler: receive handler to register
  4152. * @rx_handler_data: data pointer that is used by rx handler
  4153. *
  4154. * Register a receive handler for a device. This handler will then be
  4155. * called from __netif_receive_skb. A negative errno code is returned
  4156. * on a failure.
  4157. *
  4158. * The caller must hold the rtnl_mutex.
  4159. *
  4160. * For a general description of rx_handler, see enum rx_handler_result.
  4161. */
  4162. int netdev_rx_handler_register(struct net_device *dev,
  4163. rx_handler_func_t *rx_handler,
  4164. void *rx_handler_data)
  4165. {
  4166. if (netdev_is_rx_handler_busy(dev))
  4167. return -EBUSY;
  4168. if (dev->priv_flags & IFF_NO_RX_HANDLER)
  4169. return -EINVAL;
  4170. /* Note: rx_handler_data must be set before rx_handler */
  4171. rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
  4172. rcu_assign_pointer(dev->rx_handler, rx_handler);
  4173. return 0;
  4174. }
  4175. EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
  4176. /**
  4177. * netdev_rx_handler_unregister - unregister receive handler
  4178. * @dev: device to unregister a handler from
  4179. *
  4180. * Unregister a receive handler from a device.
  4181. *
  4182. * The caller must hold the rtnl_mutex.
  4183. */
  4184. void netdev_rx_handler_unregister(struct net_device *dev)
  4185. {
  4186. ASSERT_RTNL();
  4187. RCU_INIT_POINTER(dev->rx_handler, NULL);
  4188. /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
  4189. * section has a guarantee to see a non NULL rx_handler_data
  4190. * as well.
  4191. */
  4192. synchronize_net();
  4193. RCU_INIT_POINTER(dev->rx_handler_data, NULL);
  4194. }
  4195. EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
  4196. /*
  4197. * Limit the use of PFMEMALLOC reserves to those protocols that implement
  4198. * the special handling of PFMEMALLOC skbs.
  4199. */
  4200. static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
  4201. {
  4202. switch (skb->protocol) {
  4203. case htons(ETH_P_ARP):
  4204. case htons(ETH_P_IP):
  4205. case htons(ETH_P_IPV6):
  4206. case htons(ETH_P_8021Q):
  4207. case htons(ETH_P_8021AD):
  4208. return true;
  4209. default:
  4210. return false;
  4211. }
  4212. }
  4213. static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
  4214. int *ret, struct net_device *orig_dev)
  4215. {
  4216. if (nf_hook_ingress_active(skb)) {
  4217. int ingress_retval;
  4218. if (*pt_prev) {
  4219. *ret = deliver_skb(skb, *pt_prev, orig_dev);
  4220. *pt_prev = NULL;
  4221. }
  4222. rcu_read_lock();
  4223. ingress_retval = nf_hook_ingress(skb);
  4224. rcu_read_unlock();
  4225. return ingress_retval;
  4226. }
  4227. return 0;
  4228. }
  4229. static int __netif_receive_skb_core(struct sk_buff *skb, bool pfmemalloc,
  4230. struct packet_type **ppt_prev)
  4231. {
  4232. struct packet_type *ptype, *pt_prev;
  4233. rx_handler_func_t *rx_handler;
  4234. struct net_device *orig_dev;
  4235. bool deliver_exact = false;
  4236. int ret = NET_RX_DROP;
  4237. __be16 type;
  4238. net_timestamp_check(!netdev_tstamp_prequeue, skb);
  4239. trace_netif_receive_skb(skb);
  4240. orig_dev = skb->dev;
  4241. skb_reset_network_header(skb);
  4242. if (!skb_transport_header_was_set(skb))
  4243. skb_reset_transport_header(skb);
  4244. skb_reset_mac_len(skb);
  4245. pt_prev = NULL;
  4246. another_round:
  4247. skb->skb_iif = skb->dev->ifindex;
  4248. __this_cpu_inc(softnet_data.processed);
  4249. if (static_branch_unlikely(&generic_xdp_needed_key)) {
  4250. int ret2;
  4251. preempt_disable();
  4252. ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog), skb);
  4253. preempt_enable();
  4254. if (ret2 != XDP_PASS)
  4255. return NET_RX_DROP;
  4256. skb_reset_mac_len(skb);
  4257. }
  4258. if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
  4259. skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
  4260. skb = skb_vlan_untag(skb);
  4261. if (unlikely(!skb))
  4262. goto out;
  4263. }
  4264. if (skb_skip_tc_classify(skb))
  4265. goto skip_classify;
  4266. if (pfmemalloc)
  4267. goto skip_taps;
  4268. list_for_each_entry_rcu(ptype, &ptype_all, list) {
  4269. if (pt_prev)
  4270. ret = deliver_skb(skb, pt_prev, orig_dev);
  4271. pt_prev = ptype;
  4272. }
  4273. list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
  4274. if (pt_prev)
  4275. ret = deliver_skb(skb, pt_prev, orig_dev);
  4276. pt_prev = ptype;
  4277. }
  4278. skip_taps:
  4279. #ifdef CONFIG_NET_INGRESS
  4280. if (static_branch_unlikely(&ingress_needed_key)) {
  4281. skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev);
  4282. if (!skb)
  4283. goto out;
  4284. if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
  4285. goto out;
  4286. }
  4287. #endif
  4288. skb_reset_redirect(skb);
  4289. skip_classify:
  4290. if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
  4291. goto drop;
  4292. if (skb_vlan_tag_present(skb)) {
  4293. if (pt_prev) {
  4294. ret = deliver_skb(skb, pt_prev, orig_dev);
  4295. pt_prev = NULL;
  4296. }
  4297. if (vlan_do_receive(&skb))
  4298. goto another_round;
  4299. else if (unlikely(!skb))
  4300. goto out;
  4301. }
  4302. rx_handler = rcu_dereference(skb->dev->rx_handler);
  4303. if (rx_handler) {
  4304. if (pt_prev) {
  4305. ret = deliver_skb(skb, pt_prev, orig_dev);
  4306. pt_prev = NULL;
  4307. }
  4308. switch (rx_handler(&skb)) {
  4309. case RX_HANDLER_CONSUMED:
  4310. ret = NET_RX_SUCCESS;
  4311. goto out;
  4312. case RX_HANDLER_ANOTHER:
  4313. goto another_round;
  4314. case RX_HANDLER_EXACT:
  4315. deliver_exact = true;
  4316. case RX_HANDLER_PASS:
  4317. break;
  4318. default:
  4319. BUG();
  4320. }
  4321. }
  4322. if (unlikely(skb_vlan_tag_present(skb))) {
  4323. check_vlan_id:
  4324. if (skb_vlan_tag_get_id(skb)) {
  4325. /* Vlan id is non 0 and vlan_do_receive() above couldn't
  4326. * find vlan device.
  4327. */
  4328. skb->pkt_type = PACKET_OTHERHOST;
  4329. } else if (skb->protocol == cpu_to_be16(ETH_P_8021Q) ||
  4330. skb->protocol == cpu_to_be16(ETH_P_8021AD)) {
  4331. /* Outer header is 802.1P with vlan 0, inner header is
  4332. * 802.1Q or 802.1AD and vlan_do_receive() above could
  4333. * not find vlan dev for vlan id 0.
  4334. */
  4335. __vlan_hwaccel_clear_tag(skb);
  4336. skb = skb_vlan_untag(skb);
  4337. if (unlikely(!skb))
  4338. goto out;
  4339. if (vlan_do_receive(&skb))
  4340. /* After stripping off 802.1P header with vlan 0
  4341. * vlan dev is found for inner header.
  4342. */
  4343. goto another_round;
  4344. else if (unlikely(!skb))
  4345. goto out;
  4346. else
  4347. /* We have stripped outer 802.1P vlan 0 header.
  4348. * But could not find vlan dev.
  4349. * check again for vlan id to set OTHERHOST.
  4350. */
  4351. goto check_vlan_id;
  4352. }
  4353. /* Note: we might in the future use prio bits
  4354. * and set skb->priority like in vlan_do_receive()
  4355. * For the time being, just ignore Priority Code Point
  4356. */
  4357. __vlan_hwaccel_clear_tag(skb);
  4358. }
  4359. type = skb->protocol;
  4360. /* deliver only exact match when indicated */
  4361. if (likely(!deliver_exact)) {
  4362. deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
  4363. &ptype_base[ntohs(type) &
  4364. PTYPE_HASH_MASK]);
  4365. }
  4366. deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
  4367. &orig_dev->ptype_specific);
  4368. if (unlikely(skb->dev != orig_dev)) {
  4369. deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
  4370. &skb->dev->ptype_specific);
  4371. }
  4372. if (pt_prev) {
  4373. if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
  4374. goto drop;
  4375. *ppt_prev = pt_prev;
  4376. } else {
  4377. drop:
  4378. if (!deliver_exact)
  4379. atomic_long_inc(&skb->dev->rx_dropped);
  4380. else
  4381. atomic_long_inc(&skb->dev->rx_nohandler);
  4382. kfree_skb(skb);
  4383. /* Jamal, now you will not able to escape explaining
  4384. * me how you were going to use this. :-)
  4385. */
  4386. ret = NET_RX_DROP;
  4387. }
  4388. out:
  4389. return ret;
  4390. }
  4391. static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
  4392. {
  4393. struct net_device *orig_dev = skb->dev;
  4394. struct packet_type *pt_prev = NULL;
  4395. int ret;
  4396. ret = __netif_receive_skb_core(skb, pfmemalloc, &pt_prev);
  4397. if (pt_prev)
  4398. ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
  4399. skb->dev, pt_prev, orig_dev);
  4400. return ret;
  4401. }
  4402. /**
  4403. * netif_receive_skb_core - special purpose version of netif_receive_skb
  4404. * @skb: buffer to process
  4405. *
  4406. * More direct receive version of netif_receive_skb(). It should
  4407. * only be used by callers that have a need to skip RPS and Generic XDP.
  4408. * Caller must also take care of handling if ``(page_is_)pfmemalloc``.
  4409. *
  4410. * This function may only be called from softirq context and interrupts
  4411. * should be enabled.
  4412. *
  4413. * Return values (usually ignored):
  4414. * NET_RX_SUCCESS: no congestion
  4415. * NET_RX_DROP: packet was dropped
  4416. */
  4417. int netif_receive_skb_core(struct sk_buff *skb)
  4418. {
  4419. int ret;
  4420. rcu_read_lock();
  4421. ret = __netif_receive_skb_one_core(skb, false);
  4422. rcu_read_unlock();
  4423. return ret;
  4424. }
  4425. EXPORT_SYMBOL(netif_receive_skb_core);
  4426. static inline void __netif_receive_skb_list_ptype(struct list_head *head,
  4427. struct packet_type *pt_prev,
  4428. struct net_device *orig_dev)
  4429. {
  4430. struct sk_buff *skb, *next;
  4431. if (!pt_prev)
  4432. return;
  4433. if (list_empty(head))
  4434. return;
  4435. if (pt_prev->list_func != NULL)
  4436. INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
  4437. ip_list_rcv, head, pt_prev, orig_dev);
  4438. else
  4439. list_for_each_entry_safe(skb, next, head, list) {
  4440. skb_list_del_init(skb);
  4441. pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
  4442. }
  4443. }
  4444. static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
  4445. {
  4446. /* Fast-path assumptions:
  4447. * - There is no RX handler.
  4448. * - Only one packet_type matches.
  4449. * If either of these fails, we will end up doing some per-packet
  4450. * processing in-line, then handling the 'last ptype' for the whole
  4451. * sublist. This can't cause out-of-order delivery to any single ptype,
  4452. * because the 'last ptype' must be constant across the sublist, and all
  4453. * other ptypes are handled per-packet.
  4454. */
  4455. /* Current (common) ptype of sublist */
  4456. struct packet_type *pt_curr = NULL;
  4457. /* Current (common) orig_dev of sublist */
  4458. struct net_device *od_curr = NULL;
  4459. struct list_head sublist;
  4460. struct sk_buff *skb, *next;
  4461. INIT_LIST_HEAD(&sublist);
  4462. list_for_each_entry_safe(skb, next, head, list) {
  4463. struct net_device *orig_dev = skb->dev;
  4464. struct packet_type *pt_prev = NULL;
  4465. skb_list_del_init(skb);
  4466. __netif_receive_skb_core(skb, pfmemalloc, &pt_prev);
  4467. if (!pt_prev)
  4468. continue;
  4469. if (pt_curr != pt_prev || od_curr != orig_dev) {
  4470. /* dispatch old sublist */
  4471. __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
  4472. /* start new sublist */
  4473. INIT_LIST_HEAD(&sublist);
  4474. pt_curr = pt_prev;
  4475. od_curr = orig_dev;
  4476. }
  4477. list_add_tail(&skb->list, &sublist);
  4478. }
  4479. /* dispatch final sublist */
  4480. __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
  4481. }
  4482. static int __netif_receive_skb(struct sk_buff *skb)
  4483. {
  4484. int ret;
  4485. if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
  4486. unsigned int noreclaim_flag;
  4487. /*
  4488. * PFMEMALLOC skbs are special, they should
  4489. * - be delivered to SOCK_MEMALLOC sockets only
  4490. * - stay away from userspace
  4491. * - have bounded memory usage
  4492. *
  4493. * Use PF_MEMALLOC as this saves us from propagating the allocation
  4494. * context down to all allocation sites.
  4495. */
  4496. noreclaim_flag = memalloc_noreclaim_save();
  4497. ret = __netif_receive_skb_one_core(skb, true);
  4498. memalloc_noreclaim_restore(noreclaim_flag);
  4499. } else
  4500. ret = __netif_receive_skb_one_core(skb, false);
  4501. return ret;
  4502. }
  4503. static void __netif_receive_skb_list(struct list_head *head)
  4504. {
  4505. unsigned long noreclaim_flag = 0;
  4506. struct sk_buff *skb, *next;
  4507. bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
  4508. list_for_each_entry_safe(skb, next, head, list) {
  4509. if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
  4510. struct list_head sublist;
  4511. /* Handle the previous sublist */
  4512. list_cut_before(&sublist, head, &skb->list);
  4513. if (!list_empty(&sublist))
  4514. __netif_receive_skb_list_core(&sublist, pfmemalloc);
  4515. pfmemalloc = !pfmemalloc;
  4516. /* See comments in __netif_receive_skb */
  4517. if (pfmemalloc)
  4518. noreclaim_flag = memalloc_noreclaim_save();
  4519. else
  4520. memalloc_noreclaim_restore(noreclaim_flag);
  4521. }
  4522. }
  4523. /* Handle the remaining sublist */
  4524. if (!list_empty(head))
  4525. __netif_receive_skb_list_core(head, pfmemalloc);
  4526. /* Restore pflags */
  4527. if (pfmemalloc)
  4528. memalloc_noreclaim_restore(noreclaim_flag);
  4529. }
  4530. static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
  4531. {
  4532. struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
  4533. struct bpf_prog *new = xdp->prog;
  4534. int ret = 0;
  4535. switch (xdp->command) {
  4536. case XDP_SETUP_PROG:
  4537. rcu_assign_pointer(dev->xdp_prog, new);
  4538. if (old)
  4539. bpf_prog_put(old);
  4540. if (old && !new) {
  4541. static_branch_dec(&generic_xdp_needed_key);
  4542. } else if (new && !old) {
  4543. static_branch_inc(&generic_xdp_needed_key);
  4544. dev_disable_lro(dev);
  4545. dev_disable_gro_hw(dev);
  4546. }
  4547. break;
  4548. case XDP_QUERY_PROG:
  4549. xdp->prog_id = old ? old->aux->id : 0;
  4550. break;
  4551. default:
  4552. ret = -EINVAL;
  4553. break;
  4554. }
  4555. return ret;
  4556. }
  4557. static int netif_receive_skb_internal(struct sk_buff *skb)
  4558. {
  4559. int ret;
  4560. net_timestamp_check(netdev_tstamp_prequeue, skb);
  4561. if (skb_defer_rx_timestamp(skb))
  4562. return NET_RX_SUCCESS;
  4563. rcu_read_lock();
  4564. #ifdef CONFIG_RPS
  4565. if (static_branch_unlikely(&rps_needed)) {
  4566. struct rps_dev_flow voidflow, *rflow = &voidflow;
  4567. int cpu = get_rps_cpu(skb->dev, skb, &rflow);
  4568. if (cpu >= 0) {
  4569. ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
  4570. rcu_read_unlock();
  4571. return ret;
  4572. }
  4573. }
  4574. #endif
  4575. ret = __netif_receive_skb(skb);
  4576. rcu_read_unlock();
  4577. return ret;
  4578. }
  4579. static void netif_receive_skb_list_internal(struct list_head *head)
  4580. {
  4581. struct sk_buff *skb, *next;
  4582. struct list_head sublist;
  4583. INIT_LIST_HEAD(&sublist);
  4584. list_for_each_entry_safe(skb, next, head, list) {
  4585. net_timestamp_check(netdev_tstamp_prequeue, skb);
  4586. skb_list_del_init(skb);
  4587. if (!skb_defer_rx_timestamp(skb))
  4588. list_add_tail(&skb->list, &sublist);
  4589. }
  4590. list_splice_init(&sublist, head);
  4591. rcu_read_lock();
  4592. #ifdef CONFIG_RPS
  4593. if (static_branch_unlikely(&rps_needed)) {
  4594. list_for_each_entry_safe(skb, next, head, list) {
  4595. struct rps_dev_flow voidflow, *rflow = &voidflow;
  4596. int cpu = get_rps_cpu(skb->dev, skb, &rflow);
  4597. if (cpu >= 0) {
  4598. /* Will be handled, remove from list */
  4599. skb_list_del_init(skb);
  4600. enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
  4601. }
  4602. }
  4603. }
  4604. #endif
  4605. __netif_receive_skb_list(head);
  4606. rcu_read_unlock();
  4607. }
  4608. /**
  4609. * netif_receive_skb - process receive buffer from network
  4610. * @skb: buffer to process
  4611. *
  4612. * netif_receive_skb() is the main receive data processing function.
  4613. * It always succeeds. The buffer may be dropped during processing
  4614. * for congestion control or by the protocol layers.
  4615. *
  4616. * This function may only be called from softirq context and interrupts
  4617. * should be enabled.
  4618. *
  4619. * Return values (usually ignored):
  4620. * NET_RX_SUCCESS: no congestion
  4621. * NET_RX_DROP: packet was dropped
  4622. */
  4623. int netif_receive_skb(struct sk_buff *skb)
  4624. {
  4625. int ret;
  4626. trace_netif_receive_skb_entry(skb);
  4627. ret = netif_receive_skb_internal(skb);
  4628. trace_netif_receive_skb_exit(ret);
  4629. return ret;
  4630. }
  4631. EXPORT_SYMBOL(netif_receive_skb);
  4632. /**
  4633. * netif_receive_skb_list - process many receive buffers from network
  4634. * @head: list of skbs to process.
  4635. *
  4636. * Since return value of netif_receive_skb() is normally ignored, and
  4637. * wouldn't be meaningful for a list, this function returns void.
  4638. *
  4639. * This function may only be called from softirq context and interrupts
  4640. * should be enabled.
  4641. */
  4642. void netif_receive_skb_list(struct list_head *head)
  4643. {
  4644. struct sk_buff *skb;
  4645. if (list_empty(head))
  4646. return;
  4647. if (trace_netif_receive_skb_list_entry_enabled()) {
  4648. list_for_each_entry(skb, head, list)
  4649. trace_netif_receive_skb_list_entry(skb);
  4650. }
  4651. netif_receive_skb_list_internal(head);
  4652. trace_netif_receive_skb_list_exit(0);
  4653. }
  4654. EXPORT_SYMBOL(netif_receive_skb_list);
  4655. DEFINE_PER_CPU(struct work_struct, flush_works);
  4656. /* Network device is going away, flush any packets still pending */
  4657. static void flush_backlog(struct work_struct *work)
  4658. {
  4659. struct sk_buff *skb, *tmp;
  4660. struct softnet_data *sd;
  4661. local_bh_disable();
  4662. sd = this_cpu_ptr(&softnet_data);
  4663. local_irq_disable();
  4664. rps_lock(sd);
  4665. skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
  4666. if (skb->dev->reg_state == NETREG_UNREGISTERING) {
  4667. __skb_unlink(skb, &sd->input_pkt_queue);
  4668. kfree_skb(skb);
  4669. input_queue_head_incr(sd);
  4670. }
  4671. }
  4672. rps_unlock(sd);
  4673. local_irq_enable();
  4674. skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
  4675. if (skb->dev->reg_state == NETREG_UNREGISTERING) {
  4676. __skb_unlink(skb, &sd->process_queue);
  4677. kfree_skb(skb);
  4678. input_queue_head_incr(sd);
  4679. }
  4680. }
  4681. local_bh_enable();
  4682. }
  4683. static void flush_all_backlogs(void)
  4684. {
  4685. unsigned int cpu;
  4686. get_online_cpus();
  4687. for_each_online_cpu(cpu)
  4688. queue_work_on(cpu, system_highpri_wq,
  4689. per_cpu_ptr(&flush_works, cpu));
  4690. for_each_online_cpu(cpu)
  4691. flush_work(per_cpu_ptr(&flush_works, cpu));
  4692. put_online_cpus();
  4693. }
  4694. /* Pass the currently batched GRO_NORMAL SKBs up to the stack. */
  4695. static void gro_normal_list(struct napi_struct *napi)
  4696. {
  4697. if (!napi->rx_count)
  4698. return;
  4699. netif_receive_skb_list_internal(&napi->rx_list);
  4700. INIT_LIST_HEAD(&napi->rx_list);
  4701. napi->rx_count = 0;
  4702. }
  4703. /* Queue one GRO_NORMAL SKB up for list processing. If batch size exceeded,
  4704. * pass the whole batch up to the stack.
  4705. */
  4706. static void gro_normal_one(struct napi_struct *napi, struct sk_buff *skb)
  4707. {
  4708. list_add_tail(&skb->list, &napi->rx_list);
  4709. if (++napi->rx_count >= gro_normal_batch)
  4710. gro_normal_list(napi);
  4711. }
  4712. INDIRECT_CALLABLE_DECLARE(int inet_gro_complete(struct sk_buff *, int));
  4713. INDIRECT_CALLABLE_DECLARE(int ipv6_gro_complete(struct sk_buff *, int));
  4714. static int napi_gro_complete(struct napi_struct *napi, struct sk_buff *skb)
  4715. {
  4716. struct packet_offload *ptype;
  4717. __be16 type = skb->protocol;
  4718. struct list_head *head = &offload_base;
  4719. int err = -ENOENT;
  4720. BUILD_BUG_ON(sizeof(struct napi_gro_cb) > sizeof(skb->cb));
  4721. if (NAPI_GRO_CB(skb)->count == 1) {
  4722. skb_shinfo(skb)->gso_size = 0;
  4723. goto out;
  4724. }
  4725. rcu_read_lock();
  4726. list_for_each_entry_rcu(ptype, head, list) {
  4727. if (ptype->type != type || !ptype->callbacks.gro_complete)
  4728. continue;
  4729. err = INDIRECT_CALL_INET(ptype->callbacks.gro_complete,
  4730. ipv6_gro_complete, inet_gro_complete,
  4731. skb, 0);
  4732. break;
  4733. }
  4734. rcu_read_unlock();
  4735. if (err) {
  4736. WARN_ON(&ptype->list == head);
  4737. kfree_skb(skb);
  4738. return NET_RX_SUCCESS;
  4739. }
  4740. out:
  4741. gro_normal_one(napi, skb);
  4742. return NET_RX_SUCCESS;
  4743. }
  4744. static void __napi_gro_flush_chain(struct napi_struct *napi, u32 index,
  4745. bool flush_old)
  4746. {
  4747. struct list_head *head = &napi->gro_hash[index].list;
  4748. struct sk_buff *skb, *p;
  4749. list_for_each_entry_safe_reverse(skb, p, head, list) {
  4750. if (flush_old && NAPI_GRO_CB(skb)->age == jiffies)
  4751. return;
  4752. skb_list_del_init(skb);
  4753. napi_gro_complete(napi, skb);
  4754. napi->gro_hash[index].count--;
  4755. }
  4756. if (!napi->gro_hash[index].count)
  4757. __clear_bit(index, &napi->gro_bitmask);
  4758. }
  4759. /* napi->gro_hash[].list contains packets ordered by age.
  4760. * youngest packets at the head of it.
  4761. * Complete skbs in reverse order to reduce latencies.
  4762. */
  4763. void napi_gro_flush(struct napi_struct *napi, bool flush_old)
  4764. {
  4765. unsigned long bitmask = napi->gro_bitmask;
  4766. unsigned int i, base = ~0U;
  4767. while ((i = ffs(bitmask)) != 0) {
  4768. bitmask >>= i;
  4769. base += i;
  4770. __napi_gro_flush_chain(napi, base, flush_old);
  4771. }
  4772. }
  4773. EXPORT_SYMBOL(napi_gro_flush);
  4774. static struct list_head *gro_list_prepare(struct napi_struct *napi,
  4775. struct sk_buff *skb)
  4776. {
  4777. unsigned int maclen = skb->dev->hard_header_len;
  4778. u32 hash = skb_get_hash_raw(skb);
  4779. struct list_head *head;
  4780. struct sk_buff *p;
  4781. head = &napi->gro_hash[hash & (GRO_HASH_BUCKETS - 1)].list;
  4782. list_for_each_entry(p, head, list) {
  4783. unsigned long diffs;
  4784. NAPI_GRO_CB(p)->flush = 0;
  4785. if (hash != skb_get_hash_raw(p)) {
  4786. NAPI_GRO_CB(p)->same_flow = 0;
  4787. continue;
  4788. }
  4789. diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev;
  4790. diffs |= skb_vlan_tag_present(p) ^ skb_vlan_tag_present(skb);
  4791. if (skb_vlan_tag_present(p))
  4792. diffs |= skb_vlan_tag_get(p) ^ skb_vlan_tag_get(skb);
  4793. diffs |= skb_metadata_dst_cmp(p, skb);
  4794. diffs |= skb_metadata_differs(p, skb);
  4795. if (maclen == ETH_HLEN)
  4796. diffs |= compare_ether_header(skb_mac_header(p),
  4797. skb_mac_header(skb));
  4798. else if (!diffs)
  4799. diffs = memcmp(skb_mac_header(p),
  4800. skb_mac_header(skb),
  4801. maclen);
  4802. NAPI_GRO_CB(p)->same_flow = !diffs;
  4803. }
  4804. return head;
  4805. }
  4806. static void skb_gro_reset_offset(struct sk_buff *skb)
  4807. {
  4808. const struct skb_shared_info *pinfo = skb_shinfo(skb);
  4809. const skb_frag_t *frag0 = &pinfo->frags[0];
  4810. NAPI_GRO_CB(skb)->data_offset = 0;
  4811. NAPI_GRO_CB(skb)->frag0 = NULL;
  4812. NAPI_GRO_CB(skb)->frag0_len = 0;
  4813. if (!skb_headlen(skb) && pinfo->nr_frags &&
  4814. !PageHighMem(skb_frag_page(frag0))) {
  4815. NAPI_GRO_CB(skb)->frag0 = skb_frag_address(frag0);
  4816. NAPI_GRO_CB(skb)->frag0_len = min_t(unsigned int,
  4817. skb_frag_size(frag0),
  4818. skb->end - skb->tail);
  4819. }
  4820. }
  4821. static void gro_pull_from_frag0(struct sk_buff *skb, int grow)
  4822. {
  4823. struct skb_shared_info *pinfo = skb_shinfo(skb);
  4824. BUG_ON(skb->end - skb->tail < grow);
  4825. memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
  4826. skb->data_len -= grow;
  4827. skb->tail += grow;
  4828. skb_frag_off_add(&pinfo->frags[0], grow);
  4829. skb_frag_size_sub(&pinfo->frags[0], grow);
  4830. if (unlikely(!skb_frag_size(&pinfo->frags[0]))) {
  4831. skb_frag_unref(skb, 0);
  4832. memmove(pinfo->frags, pinfo->frags + 1,
  4833. --pinfo->nr_frags * sizeof(pinfo->frags[0]));
  4834. }
  4835. }
  4836. static void gro_flush_oldest(struct napi_struct *napi, struct list_head *head)
  4837. {
  4838. struct sk_buff *oldest;
  4839. oldest = list_last_entry(head, struct sk_buff, list);
  4840. /* We are called with head length >= MAX_GRO_SKBS, so this is
  4841. * impossible.
  4842. */
  4843. if (WARN_ON_ONCE(!oldest))
  4844. return;
  4845. /* Do not adjust napi->gro_hash[].count, caller is adding a new
  4846. * SKB to the chain.
  4847. */
  4848. skb_list_del_init(oldest);
  4849. napi_gro_complete(napi, oldest);
  4850. }
  4851. INDIRECT_CALLABLE_DECLARE(struct sk_buff *inet_gro_receive(struct list_head *,
  4852. struct sk_buff *));
  4853. INDIRECT_CALLABLE_DECLARE(struct sk_buff *ipv6_gro_receive(struct list_head *,
  4854. struct sk_buff *));
  4855. static enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
  4856. {
  4857. u32 hash = skb_get_hash_raw(skb) & (GRO_HASH_BUCKETS - 1);
  4858. struct list_head *head = &offload_base;
  4859. struct packet_offload *ptype;
  4860. __be16 type = skb->protocol;
  4861. struct list_head *gro_head;
  4862. struct sk_buff *pp = NULL;
  4863. enum gro_result ret;
  4864. int same_flow;
  4865. int grow;
  4866. if (netif_elide_gro(skb->dev))
  4867. goto normal;
  4868. gro_head = gro_list_prepare(napi, skb);
  4869. rcu_read_lock();
  4870. list_for_each_entry_rcu(ptype, head, list) {
  4871. if (ptype->type != type || !ptype->callbacks.gro_receive)
  4872. continue;
  4873. skb_set_network_header(skb, skb_gro_offset(skb));
  4874. skb_reset_mac_len(skb);
  4875. NAPI_GRO_CB(skb)->same_flow = 0;
  4876. NAPI_GRO_CB(skb)->flush = skb_is_gso(skb) || skb_has_frag_list(skb);
  4877. NAPI_GRO_CB(skb)->free = 0;
  4878. NAPI_GRO_CB(skb)->encap_mark = 0;
  4879. NAPI_GRO_CB(skb)->recursion_counter = 0;
  4880. NAPI_GRO_CB(skb)->is_fou = 0;
  4881. NAPI_GRO_CB(skb)->is_atomic = 1;
  4882. NAPI_GRO_CB(skb)->gro_remcsum_start = 0;
  4883. /* Setup for GRO checksum validation */
  4884. switch (skb->ip_summed) {
  4885. case CHECKSUM_COMPLETE:
  4886. NAPI_GRO_CB(skb)->csum = skb->csum;
  4887. NAPI_GRO_CB(skb)->csum_valid = 1;
  4888. NAPI_GRO_CB(skb)->csum_cnt = 0;
  4889. break;
  4890. case CHECKSUM_UNNECESSARY:
  4891. NAPI_GRO_CB(skb)->csum_cnt = skb->csum_level + 1;
  4892. NAPI_GRO_CB(skb)->csum_valid = 0;
  4893. break;
  4894. default:
  4895. NAPI_GRO_CB(skb)->csum_cnt = 0;
  4896. NAPI_GRO_CB(skb)->csum_valid = 0;
  4897. }
  4898. pp = INDIRECT_CALL_INET(ptype->callbacks.gro_receive,
  4899. ipv6_gro_receive, inet_gro_receive,
  4900. gro_head, skb);
  4901. break;
  4902. }
  4903. rcu_read_unlock();
  4904. if (&ptype->list == head)
  4905. goto normal;
  4906. if (PTR_ERR(pp) == -EINPROGRESS) {
  4907. ret = GRO_CONSUMED;
  4908. goto ok;
  4909. }
  4910. same_flow = NAPI_GRO_CB(skb)->same_flow;
  4911. ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
  4912. if (pp) {
  4913. skb_list_del_init(pp);
  4914. napi_gro_complete(napi, pp);
  4915. napi->gro_hash[hash].count--;
  4916. }
  4917. if (same_flow)
  4918. goto ok;
  4919. if (NAPI_GRO_CB(skb)->flush)
  4920. goto normal;
  4921. if (unlikely(napi->gro_hash[hash].count >= MAX_GRO_SKBS)) {
  4922. gro_flush_oldest(napi, gro_head);
  4923. } else {
  4924. napi->gro_hash[hash].count++;
  4925. }
  4926. NAPI_GRO_CB(skb)->count = 1;
  4927. NAPI_GRO_CB(skb)->age = jiffies;
  4928. NAPI_GRO_CB(skb)->last = skb;
  4929. skb_shinfo(skb)->gso_size = skb_gro_len(skb);
  4930. list_add(&skb->list, gro_head);
  4931. ret = GRO_HELD;
  4932. pull:
  4933. grow = skb_gro_offset(skb) - skb_headlen(skb);
  4934. if (grow > 0)
  4935. gro_pull_from_frag0(skb, grow);
  4936. ok:
  4937. if (napi->gro_hash[hash].count) {
  4938. if (!test_bit(hash, &napi->gro_bitmask))
  4939. __set_bit(hash, &napi->gro_bitmask);
  4940. } else if (test_bit(hash, &napi->gro_bitmask)) {
  4941. __clear_bit(hash, &napi->gro_bitmask);
  4942. }
  4943. return ret;
  4944. normal:
  4945. ret = GRO_NORMAL;
  4946. goto pull;
  4947. }
  4948. struct packet_offload *gro_find_receive_by_type(__be16 type)
  4949. {
  4950. struct list_head *offload_head = &offload_base;
  4951. struct packet_offload *ptype;
  4952. list_for_each_entry_rcu(ptype, offload_head, list) {
  4953. if (ptype->type != type || !ptype->callbacks.gro_receive)
  4954. continue;
  4955. return ptype;
  4956. }
  4957. return NULL;
  4958. }
  4959. EXPORT_SYMBOL(gro_find_receive_by_type);
  4960. struct packet_offload *gro_find_complete_by_type(__be16 type)
  4961. {
  4962. struct list_head *offload_head = &offload_base;
  4963. struct packet_offload *ptype;
  4964. list_for_each_entry_rcu(ptype, offload_head, list) {
  4965. if (ptype->type != type || !ptype->callbacks.gro_complete)
  4966. continue;
  4967. return ptype;
  4968. }
  4969. return NULL;
  4970. }
  4971. EXPORT_SYMBOL(gro_find_complete_by_type);
  4972. static void napi_skb_free_stolen_head(struct sk_buff *skb)
  4973. {
  4974. skb_dst_drop(skb);
  4975. skb_ext_put(skb);
  4976. kmem_cache_free(skbuff_head_cache, skb);
  4977. }
  4978. static gro_result_t napi_skb_finish(struct napi_struct *napi,
  4979. struct sk_buff *skb,
  4980. gro_result_t ret)
  4981. {
  4982. switch (ret) {
  4983. case GRO_NORMAL:
  4984. gro_normal_one(napi, skb);
  4985. break;
  4986. case GRO_DROP:
  4987. kfree_skb(skb);
  4988. break;
  4989. case GRO_MERGED_FREE:
  4990. if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
  4991. napi_skb_free_stolen_head(skb);
  4992. else
  4993. __kfree_skb(skb);
  4994. break;
  4995. case GRO_HELD:
  4996. case GRO_MERGED:
  4997. case GRO_CONSUMED:
  4998. break;
  4999. }
  5000. return ret;
  5001. }
  5002. gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
  5003. {
  5004. gro_result_t ret;
  5005. skb_mark_napi_id(skb, napi);
  5006. trace_napi_gro_receive_entry(skb);
  5007. skb_gro_reset_offset(skb);
  5008. ret = napi_skb_finish(napi, skb, dev_gro_receive(napi, skb));
  5009. trace_napi_gro_receive_exit(ret);
  5010. return ret;
  5011. }
  5012. EXPORT_SYMBOL(napi_gro_receive);
  5013. static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
  5014. {
  5015. if (unlikely(skb->pfmemalloc)) {
  5016. consume_skb(skb);
  5017. return;
  5018. }
  5019. __skb_pull(skb, skb_headlen(skb));
  5020. /* restore the reserve we had after netdev_alloc_skb_ip_align() */
  5021. skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN - skb_headroom(skb));
  5022. __vlan_hwaccel_clear_tag(skb);
  5023. skb->dev = napi->dev;
  5024. skb->skb_iif = 0;
  5025. /* eth_type_trans() assumes pkt_type is PACKET_HOST */
  5026. skb->pkt_type = PACKET_HOST;
  5027. skb->encapsulation = 0;
  5028. skb_shinfo(skb)->gso_type = 0;
  5029. skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
  5030. skb_ext_reset(skb);
  5031. napi->skb = skb;
  5032. }
  5033. struct sk_buff *napi_get_frags(struct napi_struct *napi)
  5034. {
  5035. struct sk_buff *skb = napi->skb;
  5036. if (!skb) {
  5037. skb = napi_alloc_skb(napi, GRO_MAX_HEAD);
  5038. if (skb) {
  5039. napi->skb = skb;
  5040. skb_mark_napi_id(skb, napi);
  5041. }
  5042. }
  5043. return skb;
  5044. }
  5045. EXPORT_SYMBOL(napi_get_frags);
  5046. static gro_result_t napi_frags_finish(struct napi_struct *napi,
  5047. struct sk_buff *skb,
  5048. gro_result_t ret)
  5049. {
  5050. switch (ret) {
  5051. case GRO_NORMAL:
  5052. case GRO_HELD:
  5053. __skb_push(skb, ETH_HLEN);
  5054. skb->protocol = eth_type_trans(skb, skb->dev);
  5055. if (ret == GRO_NORMAL)
  5056. gro_normal_one(napi, skb);
  5057. break;
  5058. case GRO_DROP:
  5059. napi_reuse_skb(napi, skb);
  5060. break;
  5061. case GRO_MERGED_FREE:
  5062. if (NAPI_GRO_CB(skb)->free == NAPI_GRO_FREE_STOLEN_HEAD)
  5063. napi_skb_free_stolen_head(skb);
  5064. else
  5065. napi_reuse_skb(napi, skb);
  5066. break;
  5067. case GRO_MERGED:
  5068. case GRO_CONSUMED:
  5069. break;
  5070. }
  5071. return ret;
  5072. }
  5073. /* Upper GRO stack assumes network header starts at gro_offset=0
  5074. * Drivers could call both napi_gro_frags() and napi_gro_receive()
  5075. * We copy ethernet header into skb->data to have a common layout.
  5076. */
  5077. static struct sk_buff *napi_frags_skb(struct napi_struct *napi)
  5078. {
  5079. struct sk_buff *skb = napi->skb;
  5080. const struct ethhdr *eth;
  5081. unsigned int hlen = sizeof(*eth);
  5082. napi->skb = NULL;
  5083. skb_reset_mac_header(skb);
  5084. skb_gro_reset_offset(skb);
  5085. if (unlikely(skb_gro_header_hard(skb, hlen))) {
  5086. eth = skb_gro_header_slow(skb, hlen, 0);
  5087. if (unlikely(!eth)) {
  5088. net_warn_ratelimited("%s: dropping impossible skb from %s\n",
  5089. __func__, napi->dev->name);
  5090. napi_reuse_skb(napi, skb);
  5091. return NULL;
  5092. }
  5093. } else {
  5094. eth = (const struct ethhdr *)skb->data;
  5095. gro_pull_from_frag0(skb, hlen);
  5096. NAPI_GRO_CB(skb)->frag0 += hlen;
  5097. NAPI_GRO_CB(skb)->frag0_len -= hlen;
  5098. }
  5099. __skb_pull(skb, hlen);
  5100. /*
  5101. * This works because the only protocols we care about don't require
  5102. * special handling.
  5103. * We'll fix it up properly in napi_frags_finish()
  5104. */
  5105. skb->protocol = eth->h_proto;
  5106. return skb;
  5107. }
  5108. gro_result_t napi_gro_frags(struct napi_struct *napi)
  5109. {
  5110. gro_result_t ret;
  5111. struct sk_buff *skb = napi_frags_skb(napi);
  5112. if (!skb)
  5113. return GRO_DROP;
  5114. trace_napi_gro_frags_entry(skb);
  5115. ret = napi_frags_finish(napi, skb, dev_gro_receive(napi, skb));
  5116. trace_napi_gro_frags_exit(ret);
  5117. return ret;
  5118. }
  5119. EXPORT_SYMBOL(napi_gro_frags);
  5120. /* Compute the checksum from gro_offset and return the folded value
  5121. * after adding in any pseudo checksum.
  5122. */
  5123. __sum16 __skb_gro_checksum_complete(struct sk_buff *skb)
  5124. {
  5125. __wsum wsum;
  5126. __sum16 sum;
  5127. wsum = skb_checksum(skb, skb_gro_offset(skb), skb_gro_len(skb), 0);
  5128. /* NAPI_GRO_CB(skb)->csum holds pseudo checksum */
  5129. sum = csum_fold(csum_add(NAPI_GRO_CB(skb)->csum, wsum));
  5130. /* See comments in __skb_checksum_complete(). */
  5131. if (likely(!sum)) {
  5132. if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
  5133. !skb->csum_complete_sw)
  5134. netdev_rx_csum_fault(skb->dev, skb);
  5135. }
  5136. NAPI_GRO_CB(skb)->csum = wsum;
  5137. NAPI_GRO_CB(skb)->csum_valid = 1;
  5138. return sum;
  5139. }
  5140. EXPORT_SYMBOL(__skb_gro_checksum_complete);
  5141. static void net_rps_send_ipi(struct softnet_data *remsd)
  5142. {
  5143. #ifdef CONFIG_RPS
  5144. while (remsd) {
  5145. struct softnet_data *next = remsd->rps_ipi_next;
  5146. if (cpu_online(remsd->cpu))
  5147. smp_call_function_single_async(remsd->cpu, &remsd->csd);
  5148. remsd = next;
  5149. }
  5150. #endif
  5151. }
  5152. /*
  5153. * net_rps_action_and_irq_enable sends any pending IPI's for rps.
  5154. * Note: called with local irq disabled, but exits with local irq enabled.
  5155. */
  5156. static void net_rps_action_and_irq_enable(struct softnet_data *sd)
  5157. {
  5158. #ifdef CONFIG_RPS
  5159. struct softnet_data *remsd = sd->rps_ipi_list;
  5160. if (remsd) {
  5161. sd->rps_ipi_list = NULL;
  5162. local_irq_enable();
  5163. /* Send pending IPI's to kick RPS processing on remote cpus. */
  5164. net_rps_send_ipi(remsd);
  5165. } else
  5166. #endif
  5167. local_irq_enable();
  5168. }
  5169. static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
  5170. {
  5171. #ifdef CONFIG_RPS
  5172. return sd->rps_ipi_list != NULL;
  5173. #else
  5174. return false;
  5175. #endif
  5176. }
  5177. static int process_backlog(struct napi_struct *napi, int quota)
  5178. {
  5179. struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
  5180. bool again = true;
  5181. int work = 0;
  5182. /* Check if we have pending ipi, its better to send them now,
  5183. * not waiting net_rx_action() end.
  5184. */
  5185. if (sd_has_rps_ipi_waiting(sd)) {
  5186. local_irq_disable();
  5187. net_rps_action_and_irq_enable(sd);
  5188. }
  5189. napi->weight = dev_rx_weight;
  5190. while (again) {
  5191. struct sk_buff *skb;
  5192. while ((skb = __skb_dequeue(&sd->process_queue))) {
  5193. rcu_read_lock();
  5194. __netif_receive_skb(skb);
  5195. rcu_read_unlock();
  5196. input_queue_head_incr(sd);
  5197. if (++work >= quota)
  5198. return work;
  5199. }
  5200. local_irq_disable();
  5201. rps_lock(sd);
  5202. if (skb_queue_empty(&sd->input_pkt_queue)) {
  5203. /*
  5204. * Inline a custom version of __napi_complete().
  5205. * only current cpu owns and manipulates this napi,
  5206. * and NAPI_STATE_SCHED is the only possible flag set
  5207. * on backlog.
  5208. * We can use a plain write instead of clear_bit(),
  5209. * and we dont need an smp_mb() memory barrier.
  5210. */
  5211. napi->state = 0;
  5212. again = false;
  5213. } else {
  5214. skb_queue_splice_tail_init(&sd->input_pkt_queue,
  5215. &sd->process_queue);
  5216. }
  5217. rps_unlock(sd);
  5218. local_irq_enable();
  5219. }
  5220. return work;
  5221. }
  5222. /**
  5223. * __napi_schedule - schedule for receive
  5224. * @n: entry to schedule
  5225. *
  5226. * The entry's receive function will be scheduled to run.
  5227. * Consider using __napi_schedule_irqoff() if hard irqs are masked.
  5228. */
  5229. void __napi_schedule(struct napi_struct *n)
  5230. {
  5231. unsigned long flags;
  5232. local_irq_save(flags);
  5233. ____napi_schedule(this_cpu_ptr(&softnet_data), n);
  5234. local_irq_restore(flags);
  5235. }
  5236. EXPORT_SYMBOL(__napi_schedule);
  5237. /**
  5238. * napi_schedule_prep - check if napi can be scheduled
  5239. * @n: napi context
  5240. *
  5241. * Test if NAPI routine is already running, and if not mark
  5242. * it as running. This is used as a condition variable
  5243. * insure only one NAPI poll instance runs. We also make
  5244. * sure there is no pending NAPI disable.
  5245. */
  5246. bool napi_schedule_prep(struct napi_struct *n)
  5247. {
  5248. unsigned long val, new;
  5249. do {
  5250. val = READ_ONCE(n->state);
  5251. if (unlikely(val & NAPIF_STATE_DISABLE))
  5252. return false;
  5253. new = val | NAPIF_STATE_SCHED;
  5254. /* Sets STATE_MISSED bit if STATE_SCHED was already set
  5255. * This was suggested by Alexander Duyck, as compiler
  5256. * emits better code than :
  5257. * if (val & NAPIF_STATE_SCHED)
  5258. * new |= NAPIF_STATE_MISSED;
  5259. */
  5260. new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
  5261. NAPIF_STATE_MISSED;
  5262. } while (cmpxchg(&n->state, val, new) != val);
  5263. return !(val & NAPIF_STATE_SCHED);
  5264. }
  5265. EXPORT_SYMBOL(napi_schedule_prep);
  5266. /**
  5267. * __napi_schedule_irqoff - schedule for receive
  5268. * @n: entry to schedule
  5269. *
  5270. * Variant of __napi_schedule() assuming hard irqs are masked
  5271. */
  5272. void __napi_schedule_irqoff(struct napi_struct *n)
  5273. {
  5274. ____napi_schedule(this_cpu_ptr(&softnet_data), n);
  5275. }
  5276. EXPORT_SYMBOL(__napi_schedule_irqoff);
  5277. bool napi_complete_done(struct napi_struct *n, int work_done)
  5278. {
  5279. unsigned long flags, val, new;
  5280. /*
  5281. * 1) Don't let napi dequeue from the cpu poll list
  5282. * just in case its running on a different cpu.
  5283. * 2) If we are busy polling, do nothing here, we have
  5284. * the guarantee we will be called later.
  5285. */
  5286. if (unlikely(n->state & (NAPIF_STATE_NPSVC |
  5287. NAPIF_STATE_IN_BUSY_POLL)))
  5288. return false;
  5289. if (n->gro_bitmask) {
  5290. unsigned long timeout = 0;
  5291. if (work_done)
  5292. timeout = n->dev->gro_flush_timeout;
  5293. /* When the NAPI instance uses a timeout and keeps postponing
  5294. * it, we need to bound somehow the time packets are kept in
  5295. * the GRO layer
  5296. */
  5297. napi_gro_flush(n, !!timeout);
  5298. if (timeout)
  5299. hrtimer_start(&n->timer, ns_to_ktime(timeout),
  5300. HRTIMER_MODE_REL_PINNED);
  5301. }
  5302. gro_normal_list(n);
  5303. if (unlikely(!list_empty(&n->poll_list))) {
  5304. /* If n->poll_list is not empty, we need to mask irqs */
  5305. local_irq_save(flags);
  5306. list_del_init(&n->poll_list);
  5307. local_irq_restore(flags);
  5308. }
  5309. do {
  5310. val = READ_ONCE(n->state);
  5311. WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
  5312. new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED);
  5313. /* If STATE_MISSED was set, leave STATE_SCHED set,
  5314. * because we will call napi->poll() one more time.
  5315. * This C code was suggested by Alexander Duyck to help gcc.
  5316. */
  5317. new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
  5318. NAPIF_STATE_SCHED;
  5319. } while (cmpxchg(&n->state, val, new) != val);
  5320. if (unlikely(val & NAPIF_STATE_MISSED)) {
  5321. __napi_schedule(n);
  5322. return false;
  5323. }
  5324. return true;
  5325. }
  5326. EXPORT_SYMBOL(napi_complete_done);
  5327. /* must be called under rcu_read_lock(), as we dont take a reference */
  5328. static struct napi_struct *napi_by_id(unsigned int napi_id)
  5329. {
  5330. unsigned int hash = napi_id % HASH_SIZE(napi_hash);
  5331. struct napi_struct *napi;
  5332. hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
  5333. if (napi->napi_id == napi_id)
  5334. return napi;
  5335. return NULL;
  5336. }
  5337. #if defined(CONFIG_NET_RX_BUSY_POLL)
  5338. #define BUSY_POLL_BUDGET 8
  5339. static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock)
  5340. {
  5341. int rc;
  5342. /* Busy polling means there is a high chance device driver hard irq
  5343. * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
  5344. * set in napi_schedule_prep().
  5345. * Since we are about to call napi->poll() once more, we can safely
  5346. * clear NAPI_STATE_MISSED.
  5347. *
  5348. * Note: x86 could use a single "lock and ..." instruction
  5349. * to perform these two clear_bit()
  5350. */
  5351. clear_bit(NAPI_STATE_MISSED, &napi->state);
  5352. clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
  5353. local_bh_disable();
  5354. /* All we really want here is to re-enable device interrupts.
  5355. * Ideally, a new ndo_busy_poll_stop() could avoid another round.
  5356. */
  5357. rc = napi->poll(napi, BUSY_POLL_BUDGET);
  5358. /* We can't gro_normal_list() here, because napi->poll() might have
  5359. * rearmed the napi (napi_complete_done()) in which case it could
  5360. * already be running on another CPU.
  5361. */
  5362. trace_napi_poll(napi, rc, BUSY_POLL_BUDGET);
  5363. netpoll_poll_unlock(have_poll_lock);
  5364. if (rc == BUSY_POLL_BUDGET) {
  5365. /* As the whole budget was spent, we still own the napi so can
  5366. * safely handle the rx_list.
  5367. */
  5368. gro_normal_list(napi);
  5369. __napi_schedule(napi);
  5370. }
  5371. local_bh_enable();
  5372. }
  5373. void napi_busy_loop(unsigned int napi_id,
  5374. bool (*loop_end)(void *, unsigned long),
  5375. void *loop_end_arg)
  5376. {
  5377. unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
  5378. int (*napi_poll)(struct napi_struct *napi, int budget);
  5379. void *have_poll_lock = NULL;
  5380. struct napi_struct *napi;
  5381. restart:
  5382. napi_poll = NULL;
  5383. rcu_read_lock();
  5384. napi = napi_by_id(napi_id);
  5385. if (!napi)
  5386. goto out;
  5387. preempt_disable();
  5388. for (;;) {
  5389. int work = 0;
  5390. local_bh_disable();
  5391. if (!napi_poll) {
  5392. unsigned long val = READ_ONCE(napi->state);
  5393. /* If multiple threads are competing for this napi,
  5394. * we avoid dirtying napi->state as much as we can.
  5395. */
  5396. if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
  5397. NAPIF_STATE_IN_BUSY_POLL))
  5398. goto count;
  5399. if (cmpxchg(&napi->state, val,
  5400. val | NAPIF_STATE_IN_BUSY_POLL |
  5401. NAPIF_STATE_SCHED) != val)
  5402. goto count;
  5403. have_poll_lock = netpoll_poll_lock(napi);
  5404. napi_poll = napi->poll;
  5405. }
  5406. work = napi_poll(napi, BUSY_POLL_BUDGET);
  5407. trace_napi_poll(napi, work, BUSY_POLL_BUDGET);
  5408. gro_normal_list(napi);
  5409. count:
  5410. if (work > 0)
  5411. __NET_ADD_STATS(dev_net(napi->dev),
  5412. LINUX_MIB_BUSYPOLLRXPACKETS, work);
  5413. local_bh_enable();
  5414. if (!loop_end || loop_end(loop_end_arg, start_time))
  5415. break;
  5416. if (unlikely(need_resched())) {
  5417. if (napi_poll)
  5418. busy_poll_stop(napi, have_poll_lock);
  5419. preempt_enable();
  5420. rcu_read_unlock();
  5421. cond_resched();
  5422. if (loop_end(loop_end_arg, start_time))
  5423. return;
  5424. goto restart;
  5425. }
  5426. cpu_relax();
  5427. }
  5428. if (napi_poll)
  5429. busy_poll_stop(napi, have_poll_lock);
  5430. preempt_enable();
  5431. out:
  5432. rcu_read_unlock();
  5433. }
  5434. EXPORT_SYMBOL(napi_busy_loop);
  5435. #endif /* CONFIG_NET_RX_BUSY_POLL */
  5436. static void napi_hash_add(struct napi_struct *napi)
  5437. {
  5438. if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state) ||
  5439. test_and_set_bit(NAPI_STATE_HASHED, &napi->state))
  5440. return;
  5441. spin_lock(&napi_hash_lock);
  5442. /* 0..NR_CPUS range is reserved for sender_cpu use */
  5443. do {
  5444. if (unlikely(++napi_gen_id < MIN_NAPI_ID))
  5445. napi_gen_id = MIN_NAPI_ID;
  5446. } while (napi_by_id(napi_gen_id));
  5447. napi->napi_id = napi_gen_id;
  5448. hlist_add_head_rcu(&napi->napi_hash_node,
  5449. &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
  5450. spin_unlock(&napi_hash_lock);
  5451. }
  5452. /* Warning : caller is responsible to make sure rcu grace period
  5453. * is respected before freeing memory containing @napi
  5454. */
  5455. bool napi_hash_del(struct napi_struct *napi)
  5456. {
  5457. bool rcu_sync_needed = false;
  5458. spin_lock(&napi_hash_lock);
  5459. if (test_and_clear_bit(NAPI_STATE_HASHED, &napi->state)) {
  5460. rcu_sync_needed = true;
  5461. hlist_del_rcu(&napi->napi_hash_node);
  5462. }
  5463. spin_unlock(&napi_hash_lock);
  5464. return rcu_sync_needed;
  5465. }
  5466. EXPORT_SYMBOL_GPL(napi_hash_del);
  5467. static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
  5468. {
  5469. struct napi_struct *napi;
  5470. napi = container_of(timer, struct napi_struct, timer);
  5471. /* Note : we use a relaxed variant of napi_schedule_prep() not setting
  5472. * NAPI_STATE_MISSED, since we do not react to a device IRQ.
  5473. */
  5474. if (napi->gro_bitmask && !napi_disable_pending(napi) &&
  5475. !test_and_set_bit(NAPI_STATE_SCHED, &napi->state))
  5476. __napi_schedule_irqoff(napi);
  5477. return HRTIMER_NORESTART;
  5478. }
  5479. static void init_gro_hash(struct napi_struct *napi)
  5480. {
  5481. int i;
  5482. for (i = 0; i < GRO_HASH_BUCKETS; i++) {
  5483. INIT_LIST_HEAD(&napi->gro_hash[i].list);
  5484. napi->gro_hash[i].count = 0;
  5485. }
  5486. napi->gro_bitmask = 0;
  5487. }
  5488. void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
  5489. int (*poll)(struct napi_struct *, int), int weight)
  5490. {
  5491. INIT_LIST_HEAD(&napi->poll_list);
  5492. hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
  5493. napi->timer.function = napi_watchdog;
  5494. init_gro_hash(napi);
  5495. napi->skb = NULL;
  5496. INIT_LIST_HEAD(&napi->rx_list);
  5497. napi->rx_count = 0;
  5498. napi->poll = poll;
  5499. if (weight > NAPI_POLL_WEIGHT)
  5500. netdev_err_once(dev, "%s() called with weight %d\n", __func__,
  5501. weight);
  5502. napi->weight = weight;
  5503. list_add(&napi->dev_list, &dev->napi_list);
  5504. napi->dev = dev;
  5505. #ifdef CONFIG_NETPOLL
  5506. napi->poll_owner = -1;
  5507. #endif
  5508. set_bit(NAPI_STATE_SCHED, &napi->state);
  5509. napi_hash_add(napi);
  5510. }
  5511. EXPORT_SYMBOL(netif_napi_add);
  5512. void napi_disable(struct napi_struct *n)
  5513. {
  5514. might_sleep();
  5515. set_bit(NAPI_STATE_DISABLE, &n->state);
  5516. while (test_and_set_bit(NAPI_STATE_SCHED, &n->state))
  5517. msleep(1);
  5518. while (test_and_set_bit(NAPI_STATE_NPSVC, &n->state))
  5519. msleep(1);
  5520. hrtimer_cancel(&n->timer);
  5521. clear_bit(NAPI_STATE_DISABLE, &n->state);
  5522. }
  5523. EXPORT_SYMBOL(napi_disable);
  5524. static void flush_gro_hash(struct napi_struct *napi)
  5525. {
  5526. int i;
  5527. for (i = 0; i < GRO_HASH_BUCKETS; i++) {
  5528. struct sk_buff *skb, *n;
  5529. list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
  5530. kfree_skb(skb);
  5531. napi->gro_hash[i].count = 0;
  5532. }
  5533. }
  5534. /* Must be called in process context */
  5535. void netif_napi_del(struct napi_struct *napi)
  5536. {
  5537. might_sleep();
  5538. if (napi_hash_del(napi))
  5539. synchronize_net();
  5540. list_del_init(&napi->dev_list);
  5541. napi_free_frags(napi);
  5542. flush_gro_hash(napi);
  5543. napi->gro_bitmask = 0;
  5544. }
  5545. EXPORT_SYMBOL(netif_napi_del);
  5546. static int napi_poll(struct napi_struct *n, struct list_head *repoll)
  5547. {
  5548. void *have;
  5549. int work, weight;
  5550. list_del_init(&n->poll_list);
  5551. have = netpoll_poll_lock(n);
  5552. weight = n->weight;
  5553. /* This NAPI_STATE_SCHED test is for avoiding a race
  5554. * with netpoll's poll_napi(). Only the entity which
  5555. * obtains the lock and sees NAPI_STATE_SCHED set will
  5556. * actually make the ->poll() call. Therefore we avoid
  5557. * accidentally calling ->poll() when NAPI is not scheduled.
  5558. */
  5559. work = 0;
  5560. if (test_bit(NAPI_STATE_SCHED, &n->state)) {
  5561. work = n->poll(n, weight);
  5562. trace_napi_poll(n, work, weight);
  5563. }
  5564. WARN_ON_ONCE(work > weight);
  5565. if (likely(work < weight))
  5566. goto out_unlock;
  5567. /* Drivers must not modify the NAPI state if they
  5568. * consume the entire weight. In such cases this code
  5569. * still "owns" the NAPI instance and therefore can
  5570. * move the instance around on the list at-will.
  5571. */
  5572. if (unlikely(napi_disable_pending(n))) {
  5573. napi_complete(n);
  5574. goto out_unlock;
  5575. }
  5576. if (n->gro_bitmask) {
  5577. /* flush too old packets
  5578. * If HZ < 1000, flush all packets.
  5579. */
  5580. napi_gro_flush(n, HZ >= 1000);
  5581. }
  5582. gro_normal_list(n);
  5583. /* Some drivers may have called napi_schedule
  5584. * prior to exhausting their budget.
  5585. */
  5586. if (unlikely(!list_empty(&n->poll_list))) {
  5587. pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
  5588. n->dev ? n->dev->name : "backlog");
  5589. goto out_unlock;
  5590. }
  5591. list_add_tail(&n->poll_list, repoll);
  5592. out_unlock:
  5593. netpoll_poll_unlock(have);
  5594. return work;
  5595. }
  5596. static __latent_entropy void net_rx_action(struct softirq_action *h)
  5597. {
  5598. struct softnet_data *sd = this_cpu_ptr(&softnet_data);
  5599. unsigned long time_limit = jiffies +
  5600. usecs_to_jiffies(netdev_budget_usecs);
  5601. int budget = netdev_budget;
  5602. LIST_HEAD(list);
  5603. LIST_HEAD(repoll);
  5604. local_irq_disable();
  5605. list_splice_init(&sd->poll_list, &list);
  5606. local_irq_enable();
  5607. for (;;) {
  5608. struct napi_struct *n;
  5609. if (list_empty(&list)) {
  5610. if (!sd_has_rps_ipi_waiting(sd) && list_empty(&repoll))
  5611. goto out;
  5612. break;
  5613. }
  5614. n = list_first_entry(&list, struct napi_struct, poll_list);
  5615. budget -= napi_poll(n, &repoll);
  5616. /* If softirq window is exhausted then punt.
  5617. * Allow this to run for 2 jiffies since which will allow
  5618. * an average latency of 1.5/HZ.
  5619. */
  5620. if (unlikely(budget <= 0 ||
  5621. time_after_eq(jiffies, time_limit))) {
  5622. sd->time_squeeze++;
  5623. break;
  5624. }
  5625. }
  5626. local_irq_disable();
  5627. list_splice_tail_init(&sd->poll_list, &list);
  5628. list_splice_tail(&repoll, &list);
  5629. list_splice(&list, &sd->poll_list);
  5630. if (!list_empty(&sd->poll_list))
  5631. __raise_softirq_irqoff(NET_RX_SOFTIRQ);
  5632. net_rps_action_and_irq_enable(sd);
  5633. out:
  5634. __kfree_skb_flush();
  5635. }
  5636. struct netdev_adjacent {
  5637. struct net_device *dev;
  5638. /* upper master flag, there can only be one master device per list */
  5639. bool master;
  5640. /* lookup ignore flag */
  5641. bool ignore;
  5642. /* counter for the number of times this device was added to us */
  5643. u16 ref_nr;
  5644. /* private field for the users */
  5645. void *private;
  5646. struct list_head list;
  5647. struct rcu_head rcu;
  5648. };
  5649. static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
  5650. struct list_head *adj_list)
  5651. {
  5652. struct netdev_adjacent *adj;
  5653. list_for_each_entry(adj, adj_list, list) {
  5654. if (adj->dev == adj_dev)
  5655. return adj;
  5656. }
  5657. return NULL;
  5658. }
  5659. static int ____netdev_has_upper_dev(struct net_device *upper_dev, void *data)
  5660. {
  5661. struct net_device *dev = data;
  5662. return upper_dev == dev;
  5663. }
  5664. /**
  5665. * netdev_has_upper_dev - Check if device is linked to an upper device
  5666. * @dev: device
  5667. * @upper_dev: upper device to check
  5668. *
  5669. * Find out if a device is linked to specified upper device and return true
  5670. * in case it is. Note that this checks only immediate upper device,
  5671. * not through a complete stack of devices. The caller must hold the RTNL lock.
  5672. */
  5673. bool netdev_has_upper_dev(struct net_device *dev,
  5674. struct net_device *upper_dev)
  5675. {
  5676. ASSERT_RTNL();
  5677. return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
  5678. upper_dev);
  5679. }
  5680. EXPORT_SYMBOL(netdev_has_upper_dev);
  5681. /**
  5682. * netdev_has_upper_dev_all - Check if device is linked to an upper device
  5683. * @dev: device
  5684. * @upper_dev: upper device to check
  5685. *
  5686. * Find out if a device is linked to specified upper device and return true
  5687. * in case it is. Note that this checks the entire upper device chain.
  5688. * The caller must hold rcu lock.
  5689. */
  5690. bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
  5691. struct net_device *upper_dev)
  5692. {
  5693. return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
  5694. upper_dev);
  5695. }
  5696. EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
  5697. /**
  5698. * netdev_has_any_upper_dev - Check if device is linked to some device
  5699. * @dev: device
  5700. *
  5701. * Find out if a device is linked to an upper device and return true in case
  5702. * it is. The caller must hold the RTNL lock.
  5703. */
  5704. bool netdev_has_any_upper_dev(struct net_device *dev)
  5705. {
  5706. ASSERT_RTNL();
  5707. return !list_empty(&dev->adj_list.upper);
  5708. }
  5709. EXPORT_SYMBOL(netdev_has_any_upper_dev);
  5710. /**
  5711. * netdev_master_upper_dev_get - Get master upper device
  5712. * @dev: device
  5713. *
  5714. * Find a master upper device and return pointer to it or NULL in case
  5715. * it's not there. The caller must hold the RTNL lock.
  5716. */
  5717. struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
  5718. {
  5719. struct netdev_adjacent *upper;
  5720. ASSERT_RTNL();
  5721. if (list_empty(&dev->adj_list.upper))
  5722. return NULL;
  5723. upper = list_first_entry(&dev->adj_list.upper,
  5724. struct netdev_adjacent, list);
  5725. if (likely(upper->master))
  5726. return upper->dev;
  5727. return NULL;
  5728. }
  5729. EXPORT_SYMBOL(netdev_master_upper_dev_get);
  5730. static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
  5731. {
  5732. struct netdev_adjacent *upper;
  5733. ASSERT_RTNL();
  5734. if (list_empty(&dev->adj_list.upper))
  5735. return NULL;
  5736. upper = list_first_entry(&dev->adj_list.upper,
  5737. struct netdev_adjacent, list);
  5738. if (likely(upper->master) && !upper->ignore)
  5739. return upper->dev;
  5740. return NULL;
  5741. }
  5742. /**
  5743. * netdev_has_any_lower_dev - Check if device is linked to some device
  5744. * @dev: device
  5745. *
  5746. * Find out if a device is linked to a lower device and return true in case
  5747. * it is. The caller must hold the RTNL lock.
  5748. */
  5749. static bool netdev_has_any_lower_dev(struct net_device *dev)
  5750. {
  5751. ASSERT_RTNL();
  5752. return !list_empty(&dev->adj_list.lower);
  5753. }
  5754. void *netdev_adjacent_get_private(struct list_head *adj_list)
  5755. {
  5756. struct netdev_adjacent *adj;
  5757. adj = list_entry(adj_list, struct netdev_adjacent, list);
  5758. return adj->private;
  5759. }
  5760. EXPORT_SYMBOL(netdev_adjacent_get_private);
  5761. /**
  5762. * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
  5763. * @dev: device
  5764. * @iter: list_head ** of the current position
  5765. *
  5766. * Gets the next device from the dev's upper list, starting from iter
  5767. * position. The caller must hold RCU read lock.
  5768. */
  5769. struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
  5770. struct list_head **iter)
  5771. {
  5772. struct netdev_adjacent *upper;
  5773. WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
  5774. upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
  5775. if (&upper->list == &dev->adj_list.upper)
  5776. return NULL;
  5777. *iter = &upper->list;
  5778. return upper->dev;
  5779. }
  5780. EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
  5781. static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
  5782. struct list_head **iter,
  5783. bool *ignore)
  5784. {
  5785. struct netdev_adjacent *upper;
  5786. upper = list_entry((*iter)->next, struct netdev_adjacent, list);
  5787. if (&upper->list == &dev->adj_list.upper)
  5788. return NULL;
  5789. *iter = &upper->list;
  5790. *ignore = upper->ignore;
  5791. return upper->dev;
  5792. }
  5793. static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
  5794. struct list_head **iter)
  5795. {
  5796. struct netdev_adjacent *upper;
  5797. WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
  5798. upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
  5799. if (&upper->list == &dev->adj_list.upper)
  5800. return NULL;
  5801. *iter = &upper->list;
  5802. return upper->dev;
  5803. }
  5804. static int __netdev_walk_all_upper_dev(struct net_device *dev,
  5805. int (*fn)(struct net_device *dev,
  5806. void *data),
  5807. void *data)
  5808. {
  5809. struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
  5810. struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
  5811. int ret, cur = 0;
  5812. bool ignore;
  5813. now = dev;
  5814. iter = &dev->adj_list.upper;
  5815. while (1) {
  5816. if (now != dev) {
  5817. ret = fn(now, data);
  5818. if (ret)
  5819. return ret;
  5820. }
  5821. next = NULL;
  5822. while (1) {
  5823. udev = __netdev_next_upper_dev(now, &iter, &ignore);
  5824. if (!udev)
  5825. break;
  5826. if (ignore)
  5827. continue;
  5828. next = udev;
  5829. niter = &udev->adj_list.upper;
  5830. dev_stack[cur] = now;
  5831. iter_stack[cur++] = iter;
  5832. break;
  5833. }
  5834. if (!next) {
  5835. if (!cur)
  5836. return 0;
  5837. next = dev_stack[--cur];
  5838. niter = iter_stack[cur];
  5839. }
  5840. now = next;
  5841. iter = niter;
  5842. }
  5843. return 0;
  5844. }
  5845. int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
  5846. int (*fn)(struct net_device *dev,
  5847. void *data),
  5848. void *data)
  5849. {
  5850. struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
  5851. struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
  5852. int ret, cur = 0;
  5853. now = dev;
  5854. iter = &dev->adj_list.upper;
  5855. while (1) {
  5856. if (now != dev) {
  5857. ret = fn(now, data);
  5858. if (ret)
  5859. return ret;
  5860. }
  5861. next = NULL;
  5862. while (1) {
  5863. udev = netdev_next_upper_dev_rcu(now, &iter);
  5864. if (!udev)
  5865. break;
  5866. next = udev;
  5867. niter = &udev->adj_list.upper;
  5868. dev_stack[cur] = now;
  5869. iter_stack[cur++] = iter;
  5870. break;
  5871. }
  5872. if (!next) {
  5873. if (!cur)
  5874. return 0;
  5875. next = dev_stack[--cur];
  5876. niter = iter_stack[cur];
  5877. }
  5878. now = next;
  5879. iter = niter;
  5880. }
  5881. return 0;
  5882. }
  5883. EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
  5884. static bool __netdev_has_upper_dev(struct net_device *dev,
  5885. struct net_device *upper_dev)
  5886. {
  5887. ASSERT_RTNL();
  5888. return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
  5889. upper_dev);
  5890. }
  5891. /**
  5892. * netdev_lower_get_next_private - Get the next ->private from the
  5893. * lower neighbour list
  5894. * @dev: device
  5895. * @iter: list_head ** of the current position
  5896. *
  5897. * Gets the next netdev_adjacent->private from the dev's lower neighbour
  5898. * list, starting from iter position. The caller must hold either hold the
  5899. * RTNL lock or its own locking that guarantees that the neighbour lower
  5900. * list will remain unchanged.
  5901. */
  5902. void *netdev_lower_get_next_private(struct net_device *dev,
  5903. struct list_head **iter)
  5904. {
  5905. struct netdev_adjacent *lower;
  5906. lower = list_entry(*iter, struct netdev_adjacent, list);
  5907. if (&lower->list == &dev->adj_list.lower)
  5908. return NULL;
  5909. *iter = lower->list.next;
  5910. return lower->private;
  5911. }
  5912. EXPORT_SYMBOL(netdev_lower_get_next_private);
  5913. /**
  5914. * netdev_lower_get_next_private_rcu - Get the next ->private from the
  5915. * lower neighbour list, RCU
  5916. * variant
  5917. * @dev: device
  5918. * @iter: list_head ** of the current position
  5919. *
  5920. * Gets the next netdev_adjacent->private from the dev's lower neighbour
  5921. * list, starting from iter position. The caller must hold RCU read lock.
  5922. */
  5923. void *netdev_lower_get_next_private_rcu(struct net_device *dev,
  5924. struct list_head **iter)
  5925. {
  5926. struct netdev_adjacent *lower;
  5927. WARN_ON_ONCE(!rcu_read_lock_held());
  5928. lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
  5929. if (&lower->list == &dev->adj_list.lower)
  5930. return NULL;
  5931. *iter = &lower->list;
  5932. return lower->private;
  5933. }
  5934. EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
  5935. /**
  5936. * netdev_lower_get_next - Get the next device from the lower neighbour
  5937. * list
  5938. * @dev: device
  5939. * @iter: list_head ** of the current position
  5940. *
  5941. * Gets the next netdev_adjacent from the dev's lower neighbour
  5942. * list, starting from iter position. The caller must hold RTNL lock or
  5943. * its own locking that guarantees that the neighbour lower
  5944. * list will remain unchanged.
  5945. */
  5946. void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
  5947. {
  5948. struct netdev_adjacent *lower;
  5949. lower = list_entry(*iter, struct netdev_adjacent, list);
  5950. if (&lower->list == &dev->adj_list.lower)
  5951. return NULL;
  5952. *iter = lower->list.next;
  5953. return lower->dev;
  5954. }
  5955. EXPORT_SYMBOL(netdev_lower_get_next);
  5956. static struct net_device *netdev_next_lower_dev(struct net_device *dev,
  5957. struct list_head **iter)
  5958. {
  5959. struct netdev_adjacent *lower;
  5960. lower = list_entry((*iter)->next, struct netdev_adjacent, list);
  5961. if (&lower->list == &dev->adj_list.lower)
  5962. return NULL;
  5963. *iter = &lower->list;
  5964. return lower->dev;
  5965. }
  5966. static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
  5967. struct list_head **iter,
  5968. bool *ignore)
  5969. {
  5970. struct netdev_adjacent *lower;
  5971. lower = list_entry((*iter)->next, struct netdev_adjacent, list);
  5972. if (&lower->list == &dev->adj_list.lower)
  5973. return NULL;
  5974. *iter = &lower->list;
  5975. *ignore = lower->ignore;
  5976. return lower->dev;
  5977. }
  5978. int netdev_walk_all_lower_dev(struct net_device *dev,
  5979. int (*fn)(struct net_device *dev,
  5980. void *data),
  5981. void *data)
  5982. {
  5983. struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
  5984. struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
  5985. int ret, cur = 0;
  5986. now = dev;
  5987. iter = &dev->adj_list.lower;
  5988. while (1) {
  5989. if (now != dev) {
  5990. ret = fn(now, data);
  5991. if (ret)
  5992. return ret;
  5993. }
  5994. next = NULL;
  5995. while (1) {
  5996. ldev = netdev_next_lower_dev(now, &iter);
  5997. if (!ldev)
  5998. break;
  5999. next = ldev;
  6000. niter = &ldev->adj_list.lower;
  6001. dev_stack[cur] = now;
  6002. iter_stack[cur++] = iter;
  6003. break;
  6004. }
  6005. if (!next) {
  6006. if (!cur)
  6007. return 0;
  6008. next = dev_stack[--cur];
  6009. niter = iter_stack[cur];
  6010. }
  6011. now = next;
  6012. iter = niter;
  6013. }
  6014. return 0;
  6015. }
  6016. EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
  6017. static int __netdev_walk_all_lower_dev(struct net_device *dev,
  6018. int (*fn)(struct net_device *dev,
  6019. void *data),
  6020. void *data)
  6021. {
  6022. struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
  6023. struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
  6024. int ret, cur = 0;
  6025. bool ignore;
  6026. now = dev;
  6027. iter = &dev->adj_list.lower;
  6028. while (1) {
  6029. if (now != dev) {
  6030. ret = fn(now, data);
  6031. if (ret)
  6032. return ret;
  6033. }
  6034. next = NULL;
  6035. while (1) {
  6036. ldev = __netdev_next_lower_dev(now, &iter, &ignore);
  6037. if (!ldev)
  6038. break;
  6039. if (ignore)
  6040. continue;
  6041. next = ldev;
  6042. niter = &ldev->adj_list.lower;
  6043. dev_stack[cur] = now;
  6044. iter_stack[cur++] = iter;
  6045. break;
  6046. }
  6047. if (!next) {
  6048. if (!cur)
  6049. return 0;
  6050. next = dev_stack[--cur];
  6051. niter = iter_stack[cur];
  6052. }
  6053. now = next;
  6054. iter = niter;
  6055. }
  6056. return 0;
  6057. }
  6058. struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
  6059. struct list_head **iter)
  6060. {
  6061. struct netdev_adjacent *lower;
  6062. lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
  6063. if (&lower->list == &dev->adj_list.lower)
  6064. return NULL;
  6065. *iter = &lower->list;
  6066. return lower->dev;
  6067. }
  6068. EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
  6069. static u8 __netdev_upper_depth(struct net_device *dev)
  6070. {
  6071. struct net_device *udev;
  6072. struct list_head *iter;
  6073. u8 max_depth = 0;
  6074. bool ignore;
  6075. for (iter = &dev->adj_list.upper,
  6076. udev = __netdev_next_upper_dev(dev, &iter, &ignore);
  6077. udev;
  6078. udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
  6079. if (ignore)
  6080. continue;
  6081. if (max_depth < udev->upper_level)
  6082. max_depth = udev->upper_level;
  6083. }
  6084. return max_depth;
  6085. }
  6086. static u8 __netdev_lower_depth(struct net_device *dev)
  6087. {
  6088. struct net_device *ldev;
  6089. struct list_head *iter;
  6090. u8 max_depth = 0;
  6091. bool ignore;
  6092. for (iter = &dev->adj_list.lower,
  6093. ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
  6094. ldev;
  6095. ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
  6096. if (ignore)
  6097. continue;
  6098. if (max_depth < ldev->lower_level)
  6099. max_depth = ldev->lower_level;
  6100. }
  6101. return max_depth;
  6102. }
  6103. static int __netdev_update_upper_level(struct net_device *dev, void *data)
  6104. {
  6105. dev->upper_level = __netdev_upper_depth(dev) + 1;
  6106. return 0;
  6107. }
  6108. static int __netdev_update_lower_level(struct net_device *dev, void *data)
  6109. {
  6110. dev->lower_level = __netdev_lower_depth(dev) + 1;
  6111. return 0;
  6112. }
  6113. int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
  6114. int (*fn)(struct net_device *dev,
  6115. void *data),
  6116. void *data)
  6117. {
  6118. struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
  6119. struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
  6120. int ret, cur = 0;
  6121. now = dev;
  6122. iter = &dev->adj_list.lower;
  6123. while (1) {
  6124. if (now != dev) {
  6125. ret = fn(now, data);
  6126. if (ret)
  6127. return ret;
  6128. }
  6129. next = NULL;
  6130. while (1) {
  6131. ldev = netdev_next_lower_dev_rcu(now, &iter);
  6132. if (!ldev)
  6133. break;
  6134. next = ldev;
  6135. niter = &ldev->adj_list.lower;
  6136. dev_stack[cur] = now;
  6137. iter_stack[cur++] = iter;
  6138. break;
  6139. }
  6140. if (!next) {
  6141. if (!cur)
  6142. return 0;
  6143. next = dev_stack[--cur];
  6144. niter = iter_stack[cur];
  6145. }
  6146. now = next;
  6147. iter = niter;
  6148. }
  6149. return 0;
  6150. }
  6151. EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
  6152. /**
  6153. * netdev_lower_get_first_private_rcu - Get the first ->private from the
  6154. * lower neighbour list, RCU
  6155. * variant
  6156. * @dev: device
  6157. *
  6158. * Gets the first netdev_adjacent->private from the dev's lower neighbour
  6159. * list. The caller must hold RCU read lock.
  6160. */
  6161. void *netdev_lower_get_first_private_rcu(struct net_device *dev)
  6162. {
  6163. struct netdev_adjacent *lower;
  6164. lower = list_first_or_null_rcu(&dev->adj_list.lower,
  6165. struct netdev_adjacent, list);
  6166. if (lower)
  6167. return lower->private;
  6168. return NULL;
  6169. }
  6170. EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
  6171. /**
  6172. * netdev_master_upper_dev_get_rcu - Get master upper device
  6173. * @dev: device
  6174. *
  6175. * Find a master upper device and return pointer to it or NULL in case
  6176. * it's not there. The caller must hold the RCU read lock.
  6177. */
  6178. struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
  6179. {
  6180. struct netdev_adjacent *upper;
  6181. upper = list_first_or_null_rcu(&dev->adj_list.upper,
  6182. struct netdev_adjacent, list);
  6183. if (upper && likely(upper->master))
  6184. return upper->dev;
  6185. return NULL;
  6186. }
  6187. EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
  6188. static int netdev_adjacent_sysfs_add(struct net_device *dev,
  6189. struct net_device *adj_dev,
  6190. struct list_head *dev_list)
  6191. {
  6192. char linkname[IFNAMSIZ+7];
  6193. sprintf(linkname, dev_list == &dev->adj_list.upper ?
  6194. "upper_%s" : "lower_%s", adj_dev->name);
  6195. return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
  6196. linkname);
  6197. }
  6198. static void netdev_adjacent_sysfs_del(struct net_device *dev,
  6199. char *name,
  6200. struct list_head *dev_list)
  6201. {
  6202. char linkname[IFNAMSIZ+7];
  6203. sprintf(linkname, dev_list == &dev->adj_list.upper ?
  6204. "upper_%s" : "lower_%s", name);
  6205. sysfs_remove_link(&(dev->dev.kobj), linkname);
  6206. }
  6207. static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
  6208. struct net_device *adj_dev,
  6209. struct list_head *dev_list)
  6210. {
  6211. return (dev_list == &dev->adj_list.upper ||
  6212. dev_list == &dev->adj_list.lower) &&
  6213. net_eq(dev_net(dev), dev_net(adj_dev));
  6214. }
  6215. static int __netdev_adjacent_dev_insert(struct net_device *dev,
  6216. struct net_device *adj_dev,
  6217. struct list_head *dev_list,
  6218. void *private, bool master)
  6219. {
  6220. struct netdev_adjacent *adj;
  6221. int ret;
  6222. adj = __netdev_find_adj(adj_dev, dev_list);
  6223. if (adj) {
  6224. adj->ref_nr += 1;
  6225. pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
  6226. dev->name, adj_dev->name, adj->ref_nr);
  6227. return 0;
  6228. }
  6229. adj = kmalloc(sizeof(*adj), GFP_KERNEL);
  6230. if (!adj)
  6231. return -ENOMEM;
  6232. adj->dev = adj_dev;
  6233. adj->master = master;
  6234. adj->ref_nr = 1;
  6235. adj->private = private;
  6236. adj->ignore = false;
  6237. dev_hold(adj_dev);
  6238. pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
  6239. dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
  6240. if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
  6241. ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
  6242. if (ret)
  6243. goto free_adj;
  6244. }
  6245. /* Ensure that master link is always the first item in list. */
  6246. if (master) {
  6247. ret = sysfs_create_link(&(dev->dev.kobj),
  6248. &(adj_dev->dev.kobj), "master");
  6249. if (ret)
  6250. goto remove_symlinks;
  6251. list_add_rcu(&adj->list, dev_list);
  6252. } else {
  6253. list_add_tail_rcu(&adj->list, dev_list);
  6254. }
  6255. return 0;
  6256. remove_symlinks:
  6257. if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
  6258. netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
  6259. free_adj:
  6260. kfree(adj);
  6261. dev_put(adj_dev);
  6262. return ret;
  6263. }
  6264. static void __netdev_adjacent_dev_remove(struct net_device *dev,
  6265. struct net_device *adj_dev,
  6266. u16 ref_nr,
  6267. struct list_head *dev_list)
  6268. {
  6269. struct netdev_adjacent *adj;
  6270. pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
  6271. dev->name, adj_dev->name, ref_nr);
  6272. adj = __netdev_find_adj(adj_dev, dev_list);
  6273. if (!adj) {
  6274. pr_err("Adjacency does not exist for device %s from %s\n",
  6275. dev->name, adj_dev->name);
  6276. WARN_ON(1);
  6277. return;
  6278. }
  6279. if (adj->ref_nr > ref_nr) {
  6280. pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
  6281. dev->name, adj_dev->name, ref_nr,
  6282. adj->ref_nr - ref_nr);
  6283. adj->ref_nr -= ref_nr;
  6284. return;
  6285. }
  6286. if (adj->master)
  6287. sysfs_remove_link(&(dev->dev.kobj), "master");
  6288. if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
  6289. netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
  6290. list_del_rcu(&adj->list);
  6291. pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
  6292. adj_dev->name, dev->name, adj_dev->name);
  6293. dev_put(adj_dev);
  6294. kfree_rcu(adj, rcu);
  6295. }
  6296. static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
  6297. struct net_device *upper_dev,
  6298. struct list_head *up_list,
  6299. struct list_head *down_list,
  6300. void *private, bool master)
  6301. {
  6302. int ret;
  6303. ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
  6304. private, master);
  6305. if (ret)
  6306. return ret;
  6307. ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
  6308. private, false);
  6309. if (ret) {
  6310. __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
  6311. return ret;
  6312. }
  6313. return 0;
  6314. }
  6315. static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
  6316. struct net_device *upper_dev,
  6317. u16 ref_nr,
  6318. struct list_head *up_list,
  6319. struct list_head *down_list)
  6320. {
  6321. __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
  6322. __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
  6323. }
  6324. static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
  6325. struct net_device *upper_dev,
  6326. void *private, bool master)
  6327. {
  6328. return __netdev_adjacent_dev_link_lists(dev, upper_dev,
  6329. &dev->adj_list.upper,
  6330. &upper_dev->adj_list.lower,
  6331. private, master);
  6332. }
  6333. static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
  6334. struct net_device *upper_dev)
  6335. {
  6336. __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
  6337. &dev->adj_list.upper,
  6338. &upper_dev->adj_list.lower);
  6339. }
  6340. static int __netdev_upper_dev_link(struct net_device *dev,
  6341. struct net_device *upper_dev, bool master,
  6342. void *upper_priv, void *upper_info,
  6343. struct netlink_ext_ack *extack)
  6344. {
  6345. struct netdev_notifier_changeupper_info changeupper_info = {
  6346. .info = {
  6347. .dev = dev,
  6348. .extack = extack,
  6349. },
  6350. .upper_dev = upper_dev,
  6351. .master = master,
  6352. .linking = true,
  6353. .upper_info = upper_info,
  6354. };
  6355. struct net_device *master_dev;
  6356. int ret = 0;
  6357. ASSERT_RTNL();
  6358. if (dev == upper_dev)
  6359. return -EBUSY;
  6360. /* To prevent loops, check if dev is not upper device to upper_dev. */
  6361. if (__netdev_has_upper_dev(upper_dev, dev))
  6362. return -EBUSY;
  6363. if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
  6364. return -EMLINK;
  6365. if (!master) {
  6366. if (__netdev_has_upper_dev(dev, upper_dev))
  6367. return -EEXIST;
  6368. } else {
  6369. master_dev = __netdev_master_upper_dev_get(dev);
  6370. if (master_dev)
  6371. return master_dev == upper_dev ? -EEXIST : -EBUSY;
  6372. }
  6373. ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
  6374. &changeupper_info.info);
  6375. ret = notifier_to_errno(ret);
  6376. if (ret)
  6377. return ret;
  6378. ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
  6379. master);
  6380. if (ret)
  6381. return ret;
  6382. ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
  6383. &changeupper_info.info);
  6384. ret = notifier_to_errno(ret);
  6385. if (ret)
  6386. goto rollback;
  6387. __netdev_update_upper_level(dev, NULL);
  6388. __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
  6389. __netdev_update_lower_level(upper_dev, NULL);
  6390. __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
  6391. NULL);
  6392. return 0;
  6393. rollback:
  6394. __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
  6395. return ret;
  6396. }
  6397. /**
  6398. * netdev_upper_dev_link - Add a link to the upper device
  6399. * @dev: device
  6400. * @upper_dev: new upper device
  6401. * @extack: netlink extended ack
  6402. *
  6403. * Adds a link to device which is upper to this one. The caller must hold
  6404. * the RTNL lock. On a failure a negative errno code is returned.
  6405. * On success the reference counts are adjusted and the function
  6406. * returns zero.
  6407. */
  6408. int netdev_upper_dev_link(struct net_device *dev,
  6409. struct net_device *upper_dev,
  6410. struct netlink_ext_ack *extack)
  6411. {
  6412. return __netdev_upper_dev_link(dev, upper_dev, false,
  6413. NULL, NULL, extack);
  6414. }
  6415. EXPORT_SYMBOL(netdev_upper_dev_link);
  6416. /**
  6417. * netdev_master_upper_dev_link - Add a master link to the upper device
  6418. * @dev: device
  6419. * @upper_dev: new upper device
  6420. * @upper_priv: upper device private
  6421. * @upper_info: upper info to be passed down via notifier
  6422. * @extack: netlink extended ack
  6423. *
  6424. * Adds a link to device which is upper to this one. In this case, only
  6425. * one master upper device can be linked, although other non-master devices
  6426. * might be linked as well. The caller must hold the RTNL lock.
  6427. * On a failure a negative errno code is returned. On success the reference
  6428. * counts are adjusted and the function returns zero.
  6429. */
  6430. int netdev_master_upper_dev_link(struct net_device *dev,
  6431. struct net_device *upper_dev,
  6432. void *upper_priv, void *upper_info,
  6433. struct netlink_ext_ack *extack)
  6434. {
  6435. return __netdev_upper_dev_link(dev, upper_dev, true,
  6436. upper_priv, upper_info, extack);
  6437. }
  6438. EXPORT_SYMBOL(netdev_master_upper_dev_link);
  6439. /**
  6440. * netdev_upper_dev_unlink - Removes a link to upper device
  6441. * @dev: device
  6442. * @upper_dev: new upper device
  6443. *
  6444. * Removes a link to device which is upper to this one. The caller must hold
  6445. * the RTNL lock.
  6446. */
  6447. void netdev_upper_dev_unlink(struct net_device *dev,
  6448. struct net_device *upper_dev)
  6449. {
  6450. struct netdev_notifier_changeupper_info changeupper_info = {
  6451. .info = {
  6452. .dev = dev,
  6453. },
  6454. .upper_dev = upper_dev,
  6455. .linking = false,
  6456. };
  6457. ASSERT_RTNL();
  6458. changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
  6459. call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
  6460. &changeupper_info.info);
  6461. __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
  6462. call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
  6463. &changeupper_info.info);
  6464. __netdev_update_upper_level(dev, NULL);
  6465. __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
  6466. __netdev_update_lower_level(upper_dev, NULL);
  6467. __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
  6468. NULL);
  6469. }
  6470. EXPORT_SYMBOL(netdev_upper_dev_unlink);
  6471. static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
  6472. struct net_device *lower_dev,
  6473. bool val)
  6474. {
  6475. struct netdev_adjacent *adj;
  6476. adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
  6477. if (adj)
  6478. adj->ignore = val;
  6479. adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
  6480. if (adj)
  6481. adj->ignore = val;
  6482. }
  6483. static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
  6484. struct net_device *lower_dev)
  6485. {
  6486. __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
  6487. }
  6488. static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
  6489. struct net_device *lower_dev)
  6490. {
  6491. __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
  6492. }
  6493. int netdev_adjacent_change_prepare(struct net_device *old_dev,
  6494. struct net_device *new_dev,
  6495. struct net_device *dev,
  6496. struct netlink_ext_ack *extack)
  6497. {
  6498. int err;
  6499. if (!new_dev)
  6500. return 0;
  6501. if (old_dev && new_dev != old_dev)
  6502. netdev_adjacent_dev_disable(dev, old_dev);
  6503. err = netdev_upper_dev_link(new_dev, dev, extack);
  6504. if (err) {
  6505. if (old_dev && new_dev != old_dev)
  6506. netdev_adjacent_dev_enable(dev, old_dev);
  6507. return err;
  6508. }
  6509. return 0;
  6510. }
  6511. EXPORT_SYMBOL(netdev_adjacent_change_prepare);
  6512. void netdev_adjacent_change_commit(struct net_device *old_dev,
  6513. struct net_device *new_dev,
  6514. struct net_device *dev)
  6515. {
  6516. if (!new_dev || !old_dev)
  6517. return;
  6518. if (new_dev == old_dev)
  6519. return;
  6520. netdev_adjacent_dev_enable(dev, old_dev);
  6521. netdev_upper_dev_unlink(old_dev, dev);
  6522. }
  6523. EXPORT_SYMBOL(netdev_adjacent_change_commit);
  6524. void netdev_adjacent_change_abort(struct net_device *old_dev,
  6525. struct net_device *new_dev,
  6526. struct net_device *dev)
  6527. {
  6528. if (!new_dev)
  6529. return;
  6530. if (old_dev && new_dev != old_dev)
  6531. netdev_adjacent_dev_enable(dev, old_dev);
  6532. netdev_upper_dev_unlink(new_dev, dev);
  6533. }
  6534. EXPORT_SYMBOL(netdev_adjacent_change_abort);
  6535. /**
  6536. * netdev_bonding_info_change - Dispatch event about slave change
  6537. * @dev: device
  6538. * @bonding_info: info to dispatch
  6539. *
  6540. * Send NETDEV_BONDING_INFO to netdev notifiers with info.
  6541. * The caller must hold the RTNL lock.
  6542. */
  6543. void netdev_bonding_info_change(struct net_device *dev,
  6544. struct netdev_bonding_info *bonding_info)
  6545. {
  6546. struct netdev_notifier_bonding_info info = {
  6547. .info.dev = dev,
  6548. };
  6549. memcpy(&info.bonding_info, bonding_info,
  6550. sizeof(struct netdev_bonding_info));
  6551. call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
  6552. &info.info);
  6553. }
  6554. EXPORT_SYMBOL(netdev_bonding_info_change);
  6555. static void netdev_adjacent_add_links(struct net_device *dev)
  6556. {
  6557. struct netdev_adjacent *iter;
  6558. struct net *net = dev_net(dev);
  6559. list_for_each_entry(iter, &dev->adj_list.upper, list) {
  6560. if (!net_eq(net, dev_net(iter->dev)))
  6561. continue;
  6562. netdev_adjacent_sysfs_add(iter->dev, dev,
  6563. &iter->dev->adj_list.lower);
  6564. netdev_adjacent_sysfs_add(dev, iter->dev,
  6565. &dev->adj_list.upper);
  6566. }
  6567. list_for_each_entry(iter, &dev->adj_list.lower, list) {
  6568. if (!net_eq(net, dev_net(iter->dev)))
  6569. continue;
  6570. netdev_adjacent_sysfs_add(iter->dev, dev,
  6571. &iter->dev->adj_list.upper);
  6572. netdev_adjacent_sysfs_add(dev, iter->dev,
  6573. &dev->adj_list.lower);
  6574. }
  6575. }
  6576. static void netdev_adjacent_del_links(struct net_device *dev)
  6577. {
  6578. struct netdev_adjacent *iter;
  6579. struct net *net = dev_net(dev);
  6580. list_for_each_entry(iter, &dev->adj_list.upper, list) {
  6581. if (!net_eq(net, dev_net(iter->dev)))
  6582. continue;
  6583. netdev_adjacent_sysfs_del(iter->dev, dev->name,
  6584. &iter->dev->adj_list.lower);
  6585. netdev_adjacent_sysfs_del(dev, iter->dev->name,
  6586. &dev->adj_list.upper);
  6587. }
  6588. list_for_each_entry(iter, &dev->adj_list.lower, list) {
  6589. if (!net_eq(net, dev_net(iter->dev)))
  6590. continue;
  6591. netdev_adjacent_sysfs_del(iter->dev, dev->name,
  6592. &iter->dev->adj_list.upper);
  6593. netdev_adjacent_sysfs_del(dev, iter->dev->name,
  6594. &dev->adj_list.lower);
  6595. }
  6596. }
  6597. void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
  6598. {
  6599. struct netdev_adjacent *iter;
  6600. struct net *net = dev_net(dev);
  6601. list_for_each_entry(iter, &dev->adj_list.upper, list) {
  6602. if (!net_eq(net, dev_net(iter->dev)))
  6603. continue;
  6604. netdev_adjacent_sysfs_del(iter->dev, oldname,
  6605. &iter->dev->adj_list.lower);
  6606. netdev_adjacent_sysfs_add(iter->dev, dev,
  6607. &iter->dev->adj_list.lower);
  6608. }
  6609. list_for_each_entry(iter, &dev->adj_list.lower, list) {
  6610. if (!net_eq(net, dev_net(iter->dev)))
  6611. continue;
  6612. netdev_adjacent_sysfs_del(iter->dev, oldname,
  6613. &iter->dev->adj_list.upper);
  6614. netdev_adjacent_sysfs_add(iter->dev, dev,
  6615. &iter->dev->adj_list.upper);
  6616. }
  6617. }
  6618. void *netdev_lower_dev_get_private(struct net_device *dev,
  6619. struct net_device *lower_dev)
  6620. {
  6621. struct netdev_adjacent *lower;
  6622. if (!lower_dev)
  6623. return NULL;
  6624. lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
  6625. if (!lower)
  6626. return NULL;
  6627. return lower->private;
  6628. }
  6629. EXPORT_SYMBOL(netdev_lower_dev_get_private);
  6630. /**
  6631. * netdev_lower_change - Dispatch event about lower device state change
  6632. * @lower_dev: device
  6633. * @lower_state_info: state to dispatch
  6634. *
  6635. * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
  6636. * The caller must hold the RTNL lock.
  6637. */
  6638. void netdev_lower_state_changed(struct net_device *lower_dev,
  6639. void *lower_state_info)
  6640. {
  6641. struct netdev_notifier_changelowerstate_info changelowerstate_info = {
  6642. .info.dev = lower_dev,
  6643. };
  6644. ASSERT_RTNL();
  6645. changelowerstate_info.lower_state_info = lower_state_info;
  6646. call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
  6647. &changelowerstate_info.info);
  6648. }
  6649. EXPORT_SYMBOL(netdev_lower_state_changed);
  6650. static void dev_change_rx_flags(struct net_device *dev, int flags)
  6651. {
  6652. const struct net_device_ops *ops = dev->netdev_ops;
  6653. if (ops->ndo_change_rx_flags)
  6654. ops->ndo_change_rx_flags(dev, flags);
  6655. }
  6656. static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
  6657. {
  6658. unsigned int old_flags = dev->flags;
  6659. kuid_t uid;
  6660. kgid_t gid;
  6661. ASSERT_RTNL();
  6662. dev->flags |= IFF_PROMISC;
  6663. dev->promiscuity += inc;
  6664. if (dev->promiscuity == 0) {
  6665. /*
  6666. * Avoid overflow.
  6667. * If inc causes overflow, untouch promisc and return error.
  6668. */
  6669. if (inc < 0)
  6670. dev->flags &= ~IFF_PROMISC;
  6671. else {
  6672. dev->promiscuity -= inc;
  6673. pr_warn("%s: promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n",
  6674. dev->name);
  6675. return -EOVERFLOW;
  6676. }
  6677. }
  6678. if (dev->flags != old_flags) {
  6679. pr_info("device %s %s promiscuous mode\n",
  6680. dev->name,
  6681. dev->flags & IFF_PROMISC ? "entered" : "left");
  6682. if (audit_enabled) {
  6683. current_uid_gid(&uid, &gid);
  6684. audit_log(audit_context(), GFP_ATOMIC,
  6685. AUDIT_ANOM_PROMISCUOUS,
  6686. "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
  6687. dev->name, (dev->flags & IFF_PROMISC),
  6688. (old_flags & IFF_PROMISC),
  6689. from_kuid(&init_user_ns, audit_get_loginuid(current)),
  6690. from_kuid(&init_user_ns, uid),
  6691. from_kgid(&init_user_ns, gid),
  6692. audit_get_sessionid(current));
  6693. }
  6694. dev_change_rx_flags(dev, IFF_PROMISC);
  6695. }
  6696. if (notify)
  6697. __dev_notify_flags(dev, old_flags, IFF_PROMISC);
  6698. return 0;
  6699. }
  6700. /**
  6701. * dev_set_promiscuity - update promiscuity count on a device
  6702. * @dev: device
  6703. * @inc: modifier
  6704. *
  6705. * Add or remove promiscuity from a device. While the count in the device
  6706. * remains above zero the interface remains promiscuous. Once it hits zero
  6707. * the device reverts back to normal filtering operation. A negative inc
  6708. * value is used to drop promiscuity on the device.
  6709. * Return 0 if successful or a negative errno code on error.
  6710. */
  6711. int dev_set_promiscuity(struct net_device *dev, int inc)
  6712. {
  6713. unsigned int old_flags = dev->flags;
  6714. int err;
  6715. err = __dev_set_promiscuity(dev, inc, true);
  6716. if (err < 0)
  6717. return err;
  6718. if (dev->flags != old_flags)
  6719. dev_set_rx_mode(dev);
  6720. return err;
  6721. }
  6722. EXPORT_SYMBOL(dev_set_promiscuity);
  6723. static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
  6724. {
  6725. unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
  6726. ASSERT_RTNL();
  6727. dev->flags |= IFF_ALLMULTI;
  6728. dev->allmulti += inc;
  6729. if (dev->allmulti == 0) {
  6730. /*
  6731. * Avoid overflow.
  6732. * If inc causes overflow, untouch allmulti and return error.
  6733. */
  6734. if (inc < 0)
  6735. dev->flags &= ~IFF_ALLMULTI;
  6736. else {
  6737. dev->allmulti -= inc;
  6738. pr_warn("%s: allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n",
  6739. dev->name);
  6740. return -EOVERFLOW;
  6741. }
  6742. }
  6743. if (dev->flags ^ old_flags) {
  6744. dev_change_rx_flags(dev, IFF_ALLMULTI);
  6745. dev_set_rx_mode(dev);
  6746. if (notify)
  6747. __dev_notify_flags(dev, old_flags,
  6748. dev->gflags ^ old_gflags);
  6749. }
  6750. return 0;
  6751. }
  6752. /**
  6753. * dev_set_allmulti - update allmulti count on a device
  6754. * @dev: device
  6755. * @inc: modifier
  6756. *
  6757. * Add or remove reception of all multicast frames to a device. While the
  6758. * count in the device remains above zero the interface remains listening
  6759. * to all interfaces. Once it hits zero the device reverts back to normal
  6760. * filtering operation. A negative @inc value is used to drop the counter
  6761. * when releasing a resource needing all multicasts.
  6762. * Return 0 if successful or a negative errno code on error.
  6763. */
  6764. int dev_set_allmulti(struct net_device *dev, int inc)
  6765. {
  6766. return __dev_set_allmulti(dev, inc, true);
  6767. }
  6768. EXPORT_SYMBOL(dev_set_allmulti);
  6769. /*
  6770. * Upload unicast and multicast address lists to device and
  6771. * configure RX filtering. When the device doesn't support unicast
  6772. * filtering it is put in promiscuous mode while unicast addresses
  6773. * are present.
  6774. */
  6775. void __dev_set_rx_mode(struct net_device *dev)
  6776. {
  6777. const struct net_device_ops *ops = dev->netdev_ops;
  6778. /* dev_open will call this function so the list will stay sane. */
  6779. if (!(dev->flags&IFF_UP))
  6780. return;
  6781. if (!netif_device_present(dev))
  6782. return;
  6783. if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
  6784. /* Unicast addresses changes may only happen under the rtnl,
  6785. * therefore calling __dev_set_promiscuity here is safe.
  6786. */
  6787. if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
  6788. __dev_set_promiscuity(dev, 1, false);
  6789. dev->uc_promisc = true;
  6790. } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
  6791. __dev_set_promiscuity(dev, -1, false);
  6792. dev->uc_promisc = false;
  6793. }
  6794. }
  6795. if (ops->ndo_set_rx_mode)
  6796. ops->ndo_set_rx_mode(dev);
  6797. }
  6798. void dev_set_rx_mode(struct net_device *dev)
  6799. {
  6800. netif_addr_lock_bh(dev);
  6801. __dev_set_rx_mode(dev);
  6802. netif_addr_unlock_bh(dev);
  6803. }
  6804. /**
  6805. * dev_get_flags - get flags reported to userspace
  6806. * @dev: device
  6807. *
  6808. * Get the combination of flag bits exported through APIs to userspace.
  6809. */
  6810. unsigned int dev_get_flags(const struct net_device *dev)
  6811. {
  6812. unsigned int flags;
  6813. flags = (dev->flags & ~(IFF_PROMISC |
  6814. IFF_ALLMULTI |
  6815. IFF_RUNNING |
  6816. IFF_LOWER_UP |
  6817. IFF_DORMANT)) |
  6818. (dev->gflags & (IFF_PROMISC |
  6819. IFF_ALLMULTI));
  6820. if (netif_running(dev)) {
  6821. if (netif_oper_up(dev))
  6822. flags |= IFF_RUNNING;
  6823. if (netif_carrier_ok(dev))
  6824. flags |= IFF_LOWER_UP;
  6825. if (netif_dormant(dev))
  6826. flags |= IFF_DORMANT;
  6827. }
  6828. return flags;
  6829. }
  6830. EXPORT_SYMBOL(dev_get_flags);
  6831. int __dev_change_flags(struct net_device *dev, unsigned int flags,
  6832. struct netlink_ext_ack *extack)
  6833. {
  6834. unsigned int old_flags = dev->flags;
  6835. int ret;
  6836. ASSERT_RTNL();
  6837. /*
  6838. * Set the flags on our device.
  6839. */
  6840. dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
  6841. IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
  6842. IFF_AUTOMEDIA)) |
  6843. (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
  6844. IFF_ALLMULTI));
  6845. /*
  6846. * Load in the correct multicast list now the flags have changed.
  6847. */
  6848. if ((old_flags ^ flags) & IFF_MULTICAST)
  6849. dev_change_rx_flags(dev, IFF_MULTICAST);
  6850. dev_set_rx_mode(dev);
  6851. /*
  6852. * Have we downed the interface. We handle IFF_UP ourselves
  6853. * according to user attempts to set it, rather than blindly
  6854. * setting it.
  6855. */
  6856. ret = 0;
  6857. if ((old_flags ^ flags) & IFF_UP) {
  6858. if (old_flags & IFF_UP)
  6859. __dev_close(dev);
  6860. else
  6861. ret = __dev_open(dev, extack);
  6862. }
  6863. if ((flags ^ dev->gflags) & IFF_PROMISC) {
  6864. int inc = (flags & IFF_PROMISC) ? 1 : -1;
  6865. unsigned int old_flags = dev->flags;
  6866. dev->gflags ^= IFF_PROMISC;
  6867. if (__dev_set_promiscuity(dev, inc, false) >= 0)
  6868. if (dev->flags != old_flags)
  6869. dev_set_rx_mode(dev);
  6870. }
  6871. /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
  6872. * is important. Some (broken) drivers set IFF_PROMISC, when
  6873. * IFF_ALLMULTI is requested not asking us and not reporting.
  6874. */
  6875. if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
  6876. int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
  6877. dev->gflags ^= IFF_ALLMULTI;
  6878. __dev_set_allmulti(dev, inc, false);
  6879. }
  6880. return ret;
  6881. }
  6882. void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
  6883. unsigned int gchanges)
  6884. {
  6885. unsigned int changes = dev->flags ^ old_flags;
  6886. if (gchanges)
  6887. rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC);
  6888. if (changes & IFF_UP) {
  6889. if (dev->flags & IFF_UP)
  6890. call_netdevice_notifiers(NETDEV_UP, dev);
  6891. else
  6892. call_netdevice_notifiers(NETDEV_DOWN, dev);
  6893. }
  6894. if (dev->flags & IFF_UP &&
  6895. (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
  6896. struct netdev_notifier_change_info change_info = {
  6897. .info = {
  6898. .dev = dev,
  6899. },
  6900. .flags_changed = changes,
  6901. };
  6902. call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
  6903. }
  6904. }
  6905. /**
  6906. * dev_change_flags - change device settings
  6907. * @dev: device
  6908. * @flags: device state flags
  6909. * @extack: netlink extended ack
  6910. *
  6911. * Change settings on device based state flags. The flags are
  6912. * in the userspace exported format.
  6913. */
  6914. int dev_change_flags(struct net_device *dev, unsigned int flags,
  6915. struct netlink_ext_ack *extack)
  6916. {
  6917. int ret;
  6918. unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
  6919. ret = __dev_change_flags(dev, flags, extack);
  6920. if (ret < 0)
  6921. return ret;
  6922. changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
  6923. __dev_notify_flags(dev, old_flags, changes);
  6924. return ret;
  6925. }
  6926. EXPORT_SYMBOL(dev_change_flags);
  6927. int __dev_set_mtu(struct net_device *dev, int new_mtu)
  6928. {
  6929. const struct net_device_ops *ops = dev->netdev_ops;
  6930. if (ops->ndo_change_mtu)
  6931. return ops->ndo_change_mtu(dev, new_mtu);
  6932. /* Pairs with all the lockless reads of dev->mtu in the stack */
  6933. WRITE_ONCE(dev->mtu, new_mtu);
  6934. return 0;
  6935. }
  6936. EXPORT_SYMBOL(__dev_set_mtu);
  6937. int dev_validate_mtu(struct net_device *dev, int new_mtu,
  6938. struct netlink_ext_ack *extack)
  6939. {
  6940. /* MTU must be positive, and in range */
  6941. if (new_mtu < 0 || new_mtu < dev->min_mtu) {
  6942. NL_SET_ERR_MSG(extack, "mtu less than device minimum");
  6943. return -EINVAL;
  6944. }
  6945. if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
  6946. NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
  6947. return -EINVAL;
  6948. }
  6949. return 0;
  6950. }
  6951. /**
  6952. * dev_set_mtu_ext - Change maximum transfer unit
  6953. * @dev: device
  6954. * @new_mtu: new transfer unit
  6955. * @extack: netlink extended ack
  6956. *
  6957. * Change the maximum transfer size of the network device.
  6958. */
  6959. int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
  6960. struct netlink_ext_ack *extack)
  6961. {
  6962. int err, orig_mtu;
  6963. if (new_mtu == dev->mtu)
  6964. return 0;
  6965. err = dev_validate_mtu(dev, new_mtu, extack);
  6966. if (err)
  6967. return err;
  6968. if (!netif_device_present(dev))
  6969. return -ENODEV;
  6970. err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
  6971. err = notifier_to_errno(err);
  6972. if (err)
  6973. return err;
  6974. orig_mtu = dev->mtu;
  6975. err = __dev_set_mtu(dev, new_mtu);
  6976. if (!err) {
  6977. err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
  6978. orig_mtu);
  6979. err = notifier_to_errno(err);
  6980. if (err) {
  6981. /* setting mtu back and notifying everyone again,
  6982. * so that they have a chance to revert changes.
  6983. */
  6984. __dev_set_mtu(dev, orig_mtu);
  6985. call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
  6986. new_mtu);
  6987. }
  6988. }
  6989. return err;
  6990. }
  6991. int dev_set_mtu(struct net_device *dev, int new_mtu)
  6992. {
  6993. struct netlink_ext_ack extack;
  6994. int err;
  6995. memset(&extack, 0, sizeof(extack));
  6996. err = dev_set_mtu_ext(dev, new_mtu, &extack);
  6997. if (err && extack._msg)
  6998. net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
  6999. return err;
  7000. }
  7001. EXPORT_SYMBOL(dev_set_mtu);
  7002. /**
  7003. * dev_change_tx_queue_len - Change TX queue length of a netdevice
  7004. * @dev: device
  7005. * @new_len: new tx queue length
  7006. */
  7007. int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
  7008. {
  7009. unsigned int orig_len = dev->tx_queue_len;
  7010. int res;
  7011. if (new_len != (unsigned int)new_len)
  7012. return -ERANGE;
  7013. if (new_len != orig_len) {
  7014. dev->tx_queue_len = new_len;
  7015. res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
  7016. res = notifier_to_errno(res);
  7017. if (res)
  7018. goto err_rollback;
  7019. res = dev_qdisc_change_tx_queue_len(dev);
  7020. if (res)
  7021. goto err_rollback;
  7022. }
  7023. return 0;
  7024. err_rollback:
  7025. netdev_err(dev, "refused to change device tx_queue_len\n");
  7026. dev->tx_queue_len = orig_len;
  7027. return res;
  7028. }
  7029. /**
  7030. * dev_set_group - Change group this device belongs to
  7031. * @dev: device
  7032. * @new_group: group this device should belong to
  7033. */
  7034. void dev_set_group(struct net_device *dev, int new_group)
  7035. {
  7036. dev->group = new_group;
  7037. }
  7038. EXPORT_SYMBOL(dev_set_group);
  7039. /**
  7040. * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
  7041. * @dev: device
  7042. * @addr: new address
  7043. * @extack: netlink extended ack
  7044. */
  7045. int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
  7046. struct netlink_ext_ack *extack)
  7047. {
  7048. struct netdev_notifier_pre_changeaddr_info info = {
  7049. .info.dev = dev,
  7050. .info.extack = extack,
  7051. .dev_addr = addr,
  7052. };
  7053. int rc;
  7054. rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
  7055. return notifier_to_errno(rc);
  7056. }
  7057. EXPORT_SYMBOL(dev_pre_changeaddr_notify);
  7058. /**
  7059. * dev_set_mac_address - Change Media Access Control Address
  7060. * @dev: device
  7061. * @sa: new address
  7062. * @extack: netlink extended ack
  7063. *
  7064. * Change the hardware (MAC) address of the device
  7065. */
  7066. int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
  7067. struct netlink_ext_ack *extack)
  7068. {
  7069. const struct net_device_ops *ops = dev->netdev_ops;
  7070. int err;
  7071. if (!ops->ndo_set_mac_address)
  7072. return -EOPNOTSUPP;
  7073. if (sa->sa_family != dev->type)
  7074. return -EINVAL;
  7075. if (!netif_device_present(dev))
  7076. return -ENODEV;
  7077. err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
  7078. if (err)
  7079. return err;
  7080. err = ops->ndo_set_mac_address(dev, sa);
  7081. if (err)
  7082. return err;
  7083. dev->addr_assign_type = NET_ADDR_SET;
  7084. call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
  7085. add_device_randomness(dev->dev_addr, dev->addr_len);
  7086. return 0;
  7087. }
  7088. EXPORT_SYMBOL(dev_set_mac_address);
  7089. /**
  7090. * dev_change_carrier - Change device carrier
  7091. * @dev: device
  7092. * @new_carrier: new value
  7093. *
  7094. * Change device carrier
  7095. */
  7096. int dev_change_carrier(struct net_device *dev, bool new_carrier)
  7097. {
  7098. const struct net_device_ops *ops = dev->netdev_ops;
  7099. if (!ops->ndo_change_carrier)
  7100. return -EOPNOTSUPP;
  7101. if (!netif_device_present(dev))
  7102. return -ENODEV;
  7103. return ops->ndo_change_carrier(dev, new_carrier);
  7104. }
  7105. EXPORT_SYMBOL(dev_change_carrier);
  7106. /**
  7107. * dev_get_phys_port_id - Get device physical port ID
  7108. * @dev: device
  7109. * @ppid: port ID
  7110. *
  7111. * Get device physical port ID
  7112. */
  7113. int dev_get_phys_port_id(struct net_device *dev,
  7114. struct netdev_phys_item_id *ppid)
  7115. {
  7116. const struct net_device_ops *ops = dev->netdev_ops;
  7117. if (!ops->ndo_get_phys_port_id)
  7118. return -EOPNOTSUPP;
  7119. return ops->ndo_get_phys_port_id(dev, ppid);
  7120. }
  7121. EXPORT_SYMBOL(dev_get_phys_port_id);
  7122. /**
  7123. * dev_get_phys_port_name - Get device physical port name
  7124. * @dev: device
  7125. * @name: port name
  7126. * @len: limit of bytes to copy to name
  7127. *
  7128. * Get device physical port name
  7129. */
  7130. int dev_get_phys_port_name(struct net_device *dev,
  7131. char *name, size_t len)
  7132. {
  7133. const struct net_device_ops *ops = dev->netdev_ops;
  7134. int err;
  7135. if (ops->ndo_get_phys_port_name) {
  7136. err = ops->ndo_get_phys_port_name(dev, name, len);
  7137. if (err != -EOPNOTSUPP)
  7138. return err;
  7139. }
  7140. return devlink_compat_phys_port_name_get(dev, name, len);
  7141. }
  7142. EXPORT_SYMBOL(dev_get_phys_port_name);
  7143. /**
  7144. * dev_get_port_parent_id - Get the device's port parent identifier
  7145. * @dev: network device
  7146. * @ppid: pointer to a storage for the port's parent identifier
  7147. * @recurse: allow/disallow recursion to lower devices
  7148. *
  7149. * Get the devices's port parent identifier
  7150. */
  7151. int dev_get_port_parent_id(struct net_device *dev,
  7152. struct netdev_phys_item_id *ppid,
  7153. bool recurse)
  7154. {
  7155. const struct net_device_ops *ops = dev->netdev_ops;
  7156. struct netdev_phys_item_id first = { };
  7157. struct net_device *lower_dev;
  7158. struct list_head *iter;
  7159. int err;
  7160. if (ops->ndo_get_port_parent_id) {
  7161. err = ops->ndo_get_port_parent_id(dev, ppid);
  7162. if (err != -EOPNOTSUPP)
  7163. return err;
  7164. }
  7165. err = devlink_compat_switch_id_get(dev, ppid);
  7166. if (!err || err != -EOPNOTSUPP)
  7167. return err;
  7168. if (!recurse)
  7169. return -EOPNOTSUPP;
  7170. netdev_for_each_lower_dev(dev, lower_dev, iter) {
  7171. err = dev_get_port_parent_id(lower_dev, ppid, recurse);
  7172. if (err)
  7173. break;
  7174. if (!first.id_len)
  7175. first = *ppid;
  7176. else if (memcmp(&first, ppid, sizeof(*ppid)))
  7177. return -ENODATA;
  7178. }
  7179. return err;
  7180. }
  7181. EXPORT_SYMBOL(dev_get_port_parent_id);
  7182. /**
  7183. * netdev_port_same_parent_id - Indicate if two network devices have
  7184. * the same port parent identifier
  7185. * @a: first network device
  7186. * @b: second network device
  7187. */
  7188. bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
  7189. {
  7190. struct netdev_phys_item_id a_id = { };
  7191. struct netdev_phys_item_id b_id = { };
  7192. if (dev_get_port_parent_id(a, &a_id, true) ||
  7193. dev_get_port_parent_id(b, &b_id, true))
  7194. return false;
  7195. return netdev_phys_item_id_same(&a_id, &b_id);
  7196. }
  7197. EXPORT_SYMBOL(netdev_port_same_parent_id);
  7198. /**
  7199. * dev_change_proto_down - update protocol port state information
  7200. * @dev: device
  7201. * @proto_down: new value
  7202. *
  7203. * This info can be used by switch drivers to set the phys state of the
  7204. * port.
  7205. */
  7206. int dev_change_proto_down(struct net_device *dev, bool proto_down)
  7207. {
  7208. const struct net_device_ops *ops = dev->netdev_ops;
  7209. if (!ops->ndo_change_proto_down)
  7210. return -EOPNOTSUPP;
  7211. if (!netif_device_present(dev))
  7212. return -ENODEV;
  7213. return ops->ndo_change_proto_down(dev, proto_down);
  7214. }
  7215. EXPORT_SYMBOL(dev_change_proto_down);
  7216. /**
  7217. * dev_change_proto_down_generic - generic implementation for
  7218. * ndo_change_proto_down that sets carrier according to
  7219. * proto_down.
  7220. *
  7221. * @dev: device
  7222. * @proto_down: new value
  7223. */
  7224. int dev_change_proto_down_generic(struct net_device *dev, bool proto_down)
  7225. {
  7226. if (proto_down)
  7227. netif_carrier_off(dev);
  7228. else
  7229. netif_carrier_on(dev);
  7230. dev->proto_down = proto_down;
  7231. return 0;
  7232. }
  7233. EXPORT_SYMBOL(dev_change_proto_down_generic);
  7234. u32 __dev_xdp_query(struct net_device *dev, bpf_op_t bpf_op,
  7235. enum bpf_netdev_command cmd)
  7236. {
  7237. struct netdev_bpf xdp;
  7238. if (!bpf_op)
  7239. return 0;
  7240. memset(&xdp, 0, sizeof(xdp));
  7241. xdp.command = cmd;
  7242. /* Query must always succeed. */
  7243. WARN_ON(bpf_op(dev, &xdp) < 0 && cmd == XDP_QUERY_PROG);
  7244. return xdp.prog_id;
  7245. }
  7246. static int dev_xdp_install(struct net_device *dev, bpf_op_t bpf_op,
  7247. struct netlink_ext_ack *extack, u32 flags,
  7248. struct bpf_prog *prog)
  7249. {
  7250. bool non_hw = !(flags & XDP_FLAGS_HW_MODE);
  7251. struct bpf_prog *prev_prog = NULL;
  7252. struct netdev_bpf xdp;
  7253. int err;
  7254. if (non_hw) {
  7255. prev_prog = bpf_prog_by_id(__dev_xdp_query(dev, bpf_op,
  7256. XDP_QUERY_PROG));
  7257. if (IS_ERR(prev_prog))
  7258. prev_prog = NULL;
  7259. }
  7260. memset(&xdp, 0, sizeof(xdp));
  7261. if (flags & XDP_FLAGS_HW_MODE)
  7262. xdp.command = XDP_SETUP_PROG_HW;
  7263. else
  7264. xdp.command = XDP_SETUP_PROG;
  7265. xdp.extack = extack;
  7266. xdp.flags = flags;
  7267. xdp.prog = prog;
  7268. err = bpf_op(dev, &xdp);
  7269. if (!err && non_hw)
  7270. bpf_prog_change_xdp(prev_prog, prog);
  7271. if (prev_prog)
  7272. bpf_prog_put(prev_prog);
  7273. return err;
  7274. }
  7275. static void dev_xdp_uninstall(struct net_device *dev)
  7276. {
  7277. struct netdev_bpf xdp;
  7278. bpf_op_t ndo_bpf;
  7279. /* Remove generic XDP */
  7280. WARN_ON(dev_xdp_install(dev, generic_xdp_install, NULL, 0, NULL));
  7281. /* Remove from the driver */
  7282. ndo_bpf = dev->netdev_ops->ndo_bpf;
  7283. if (!ndo_bpf)
  7284. return;
  7285. memset(&xdp, 0, sizeof(xdp));
  7286. xdp.command = XDP_QUERY_PROG;
  7287. WARN_ON(ndo_bpf(dev, &xdp));
  7288. if (xdp.prog_id)
  7289. WARN_ON(dev_xdp_install(dev, ndo_bpf, NULL, xdp.prog_flags,
  7290. NULL));
  7291. /* Remove HW offload */
  7292. memset(&xdp, 0, sizeof(xdp));
  7293. xdp.command = XDP_QUERY_PROG_HW;
  7294. if (!ndo_bpf(dev, &xdp) && xdp.prog_id)
  7295. WARN_ON(dev_xdp_install(dev, ndo_bpf, NULL, xdp.prog_flags,
  7296. NULL));
  7297. }
  7298. /**
  7299. * dev_change_xdp_fd - set or clear a bpf program for a device rx path
  7300. * @dev: device
  7301. * @extack: netlink extended ack
  7302. * @fd: new program fd or negative value to clear
  7303. * @expected_fd: old program fd that userspace expects to replace or clear
  7304. * @flags: xdp-related flags
  7305. *
  7306. * Set or clear a bpf program for a device
  7307. */
  7308. int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
  7309. int fd, int expected_fd, u32 flags)
  7310. {
  7311. const struct net_device_ops *ops = dev->netdev_ops;
  7312. enum bpf_netdev_command query;
  7313. u32 prog_id, expected_id = 0;
  7314. bpf_op_t bpf_op, bpf_chk;
  7315. struct bpf_prog *prog;
  7316. bool offload;
  7317. int err;
  7318. ASSERT_RTNL();
  7319. offload = flags & XDP_FLAGS_HW_MODE;
  7320. query = offload ? XDP_QUERY_PROG_HW : XDP_QUERY_PROG;
  7321. bpf_op = bpf_chk = ops->ndo_bpf;
  7322. if (!bpf_op && (flags & (XDP_FLAGS_DRV_MODE | XDP_FLAGS_HW_MODE))) {
  7323. NL_SET_ERR_MSG(extack, "underlying driver does not support XDP in native mode");
  7324. return -EOPNOTSUPP;
  7325. }
  7326. if (!bpf_op || (flags & XDP_FLAGS_SKB_MODE))
  7327. bpf_op = generic_xdp_install;
  7328. if (bpf_op == bpf_chk)
  7329. bpf_chk = generic_xdp_install;
  7330. prog_id = __dev_xdp_query(dev, bpf_op, query);
  7331. if (flags & XDP_FLAGS_REPLACE) {
  7332. if (expected_fd >= 0) {
  7333. prog = bpf_prog_get_type_dev(expected_fd,
  7334. BPF_PROG_TYPE_XDP,
  7335. bpf_op == ops->ndo_bpf);
  7336. if (IS_ERR(prog))
  7337. return PTR_ERR(prog);
  7338. expected_id = prog->aux->id;
  7339. bpf_prog_put(prog);
  7340. }
  7341. if (prog_id != expected_id) {
  7342. NL_SET_ERR_MSG(extack, "Active program does not match expected");
  7343. return -EEXIST;
  7344. }
  7345. }
  7346. if (fd >= 0) {
  7347. if (!offload && __dev_xdp_query(dev, bpf_chk, XDP_QUERY_PROG)) {
  7348. NL_SET_ERR_MSG(extack, "native and generic XDP can't be active at the same time");
  7349. return -EEXIST;
  7350. }
  7351. if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && prog_id) {
  7352. NL_SET_ERR_MSG(extack, "XDP program already attached");
  7353. return -EBUSY;
  7354. }
  7355. prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
  7356. bpf_op == ops->ndo_bpf);
  7357. if (IS_ERR(prog))
  7358. return PTR_ERR(prog);
  7359. if (!offload && bpf_prog_is_dev_bound(prog->aux)) {
  7360. NL_SET_ERR_MSG(extack, "using device-bound program without HW_MODE flag is not supported");
  7361. bpf_prog_put(prog);
  7362. return -EINVAL;
  7363. }
  7364. /* prog->aux->id may be 0 for orphaned device-bound progs */
  7365. if (prog->aux->id && prog->aux->id == prog_id) {
  7366. bpf_prog_put(prog);
  7367. return 0;
  7368. }
  7369. } else {
  7370. if (!prog_id)
  7371. return 0;
  7372. prog = NULL;
  7373. }
  7374. err = dev_xdp_install(dev, bpf_op, extack, flags, prog);
  7375. if (err < 0 && prog)
  7376. bpf_prog_put(prog);
  7377. return err;
  7378. }
  7379. /**
  7380. * dev_new_index - allocate an ifindex
  7381. * @net: the applicable net namespace
  7382. *
  7383. * Returns a suitable unique value for a new device interface
  7384. * number. The caller must hold the rtnl semaphore or the
  7385. * dev_base_lock to be sure it remains unique.
  7386. */
  7387. static int dev_new_index(struct net *net)
  7388. {
  7389. int ifindex = net->ifindex;
  7390. for (;;) {
  7391. if (++ifindex <= 0)
  7392. ifindex = 1;
  7393. if (!__dev_get_by_index(net, ifindex))
  7394. return net->ifindex = ifindex;
  7395. }
  7396. }
  7397. /* Delayed registration/unregisteration */
  7398. static LIST_HEAD(net_todo_list);
  7399. DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
  7400. static void net_set_todo(struct net_device *dev)
  7401. {
  7402. list_add_tail(&dev->todo_list, &net_todo_list);
  7403. dev_net(dev)->dev_unreg_count++;
  7404. }
  7405. static void rollback_registered_many(struct list_head *head)
  7406. {
  7407. struct net_device *dev, *tmp;
  7408. LIST_HEAD(close_head);
  7409. BUG_ON(dev_boot_phase);
  7410. ASSERT_RTNL();
  7411. list_for_each_entry_safe(dev, tmp, head, unreg_list) {
  7412. /* Some devices call without registering
  7413. * for initialization unwind. Remove those
  7414. * devices and proceed with the remaining.
  7415. */
  7416. if (dev->reg_state == NETREG_UNINITIALIZED) {
  7417. pr_debug("unregister_netdevice: device %s/%p never was registered\n",
  7418. dev->name, dev);
  7419. WARN_ON(1);
  7420. list_del(&dev->unreg_list);
  7421. continue;
  7422. }
  7423. dev->dismantle = true;
  7424. BUG_ON(dev->reg_state != NETREG_REGISTERED);
  7425. }
  7426. /* If device is running, close it first. */
  7427. list_for_each_entry(dev, head, unreg_list)
  7428. list_add_tail(&dev->close_list, &close_head);
  7429. dev_close_many(&close_head, true);
  7430. list_for_each_entry(dev, head, unreg_list) {
  7431. /* And unlink it from device chain. */
  7432. unlist_netdevice(dev);
  7433. dev->reg_state = NETREG_UNREGISTERING;
  7434. }
  7435. flush_all_backlogs();
  7436. synchronize_net();
  7437. list_for_each_entry(dev, head, unreg_list) {
  7438. struct sk_buff *skb = NULL;
  7439. /* Shutdown queueing discipline. */
  7440. dev_shutdown(dev);
  7441. dev_xdp_uninstall(dev);
  7442. /* Notify protocols, that we are about to destroy
  7443. * this device. They should clean all the things.
  7444. */
  7445. call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
  7446. if (!dev->rtnl_link_ops ||
  7447. dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
  7448. skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
  7449. GFP_KERNEL, NULL, 0);
  7450. /*
  7451. * Flush the unicast and multicast chains
  7452. */
  7453. dev_uc_flush(dev);
  7454. dev_mc_flush(dev);
  7455. netdev_name_node_alt_flush(dev);
  7456. netdev_name_node_free(dev->name_node);
  7457. if (dev->netdev_ops->ndo_uninit)
  7458. dev->netdev_ops->ndo_uninit(dev);
  7459. if (skb)
  7460. rtmsg_ifinfo_send(skb, dev, GFP_KERNEL);
  7461. /* Notifier chain MUST detach us all upper devices. */
  7462. WARN_ON(netdev_has_any_upper_dev(dev));
  7463. WARN_ON(netdev_has_any_lower_dev(dev));
  7464. /* Remove entries from kobject tree */
  7465. netdev_unregister_kobject(dev);
  7466. #ifdef CONFIG_XPS
  7467. /* Remove XPS queueing entries */
  7468. netif_reset_xps_queues_gt(dev, 0);
  7469. #endif
  7470. }
  7471. synchronize_net();
  7472. list_for_each_entry(dev, head, unreg_list)
  7473. dev_put(dev);
  7474. }
  7475. static void rollback_registered(struct net_device *dev)
  7476. {
  7477. LIST_HEAD(single);
  7478. list_add(&dev->unreg_list, &single);
  7479. rollback_registered_many(&single);
  7480. list_del(&single);
  7481. }
  7482. static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
  7483. struct net_device *upper, netdev_features_t features)
  7484. {
  7485. netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
  7486. netdev_features_t feature;
  7487. int feature_bit;
  7488. for_each_netdev_feature(upper_disables, feature_bit) {
  7489. feature = __NETIF_F_BIT(feature_bit);
  7490. if (!(upper->wanted_features & feature)
  7491. && (features & feature)) {
  7492. netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
  7493. &feature, upper->name);
  7494. features &= ~feature;
  7495. }
  7496. }
  7497. return features;
  7498. }
  7499. static void netdev_sync_lower_features(struct net_device *upper,
  7500. struct net_device *lower, netdev_features_t features)
  7501. {
  7502. netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
  7503. netdev_features_t feature;
  7504. int feature_bit;
  7505. for_each_netdev_feature(upper_disables, feature_bit) {
  7506. feature = __NETIF_F_BIT(feature_bit);
  7507. if (!(features & feature) && (lower->features & feature)) {
  7508. netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
  7509. &feature, lower->name);
  7510. lower->wanted_features &= ~feature;
  7511. netdev_update_features(lower);
  7512. if (unlikely(lower->features & feature))
  7513. netdev_WARN(upper, "failed to disable %pNF on %s!\n",
  7514. &feature, lower->name);
  7515. }
  7516. }
  7517. }
  7518. static netdev_features_t netdev_fix_features(struct net_device *dev,
  7519. netdev_features_t features)
  7520. {
  7521. /* Fix illegal checksum combinations */
  7522. if ((features & NETIF_F_HW_CSUM) &&
  7523. (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
  7524. netdev_warn(dev, "mixed HW and IP checksum settings.\n");
  7525. features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
  7526. }
  7527. /* TSO requires that SG is present as well. */
  7528. if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
  7529. netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
  7530. features &= ~NETIF_F_ALL_TSO;
  7531. }
  7532. if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
  7533. !(features & NETIF_F_IP_CSUM)) {
  7534. netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
  7535. features &= ~NETIF_F_TSO;
  7536. features &= ~NETIF_F_TSO_ECN;
  7537. }
  7538. if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
  7539. !(features & NETIF_F_IPV6_CSUM)) {
  7540. netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
  7541. features &= ~NETIF_F_TSO6;
  7542. }
  7543. /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
  7544. if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
  7545. features &= ~NETIF_F_TSO_MANGLEID;
  7546. /* TSO ECN requires that TSO is present as well. */
  7547. if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
  7548. features &= ~NETIF_F_TSO_ECN;
  7549. /* Software GSO depends on SG. */
  7550. if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
  7551. netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
  7552. features &= ~NETIF_F_GSO;
  7553. }
  7554. /* GSO partial features require GSO partial be set */
  7555. if ((features & dev->gso_partial_features) &&
  7556. !(features & NETIF_F_GSO_PARTIAL)) {
  7557. netdev_dbg(dev,
  7558. "Dropping partially supported GSO features since no GSO partial.\n");
  7559. features &= ~dev->gso_partial_features;
  7560. }
  7561. if (!(features & NETIF_F_RXCSUM)) {
  7562. /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
  7563. * successfully merged by hardware must also have the
  7564. * checksum verified by hardware. If the user does not
  7565. * want to enable RXCSUM, logically, we should disable GRO_HW.
  7566. */
  7567. if (features & NETIF_F_GRO_HW) {
  7568. netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
  7569. features &= ~NETIF_F_GRO_HW;
  7570. }
  7571. }
  7572. /* LRO/HW-GRO features cannot be combined with RX-FCS */
  7573. if (features & NETIF_F_RXFCS) {
  7574. if (features & NETIF_F_LRO) {
  7575. netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
  7576. features &= ~NETIF_F_LRO;
  7577. }
  7578. if (features & NETIF_F_GRO_HW) {
  7579. netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
  7580. features &= ~NETIF_F_GRO_HW;
  7581. }
  7582. }
  7583. return features;
  7584. }
  7585. int __netdev_update_features(struct net_device *dev)
  7586. {
  7587. struct net_device *upper, *lower;
  7588. netdev_features_t features;
  7589. struct list_head *iter;
  7590. int err = -1;
  7591. ASSERT_RTNL();
  7592. features = netdev_get_wanted_features(dev);
  7593. if (dev->netdev_ops->ndo_fix_features)
  7594. features = dev->netdev_ops->ndo_fix_features(dev, features);
  7595. /* driver might be less strict about feature dependencies */
  7596. features = netdev_fix_features(dev, features);
  7597. /* some features can't be enabled if they're off an an upper device */
  7598. netdev_for_each_upper_dev_rcu(dev, upper, iter)
  7599. features = netdev_sync_upper_features(dev, upper, features);
  7600. if (dev->features == features)
  7601. goto sync_lower;
  7602. netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
  7603. &dev->features, &features);
  7604. if (dev->netdev_ops->ndo_set_features)
  7605. err = dev->netdev_ops->ndo_set_features(dev, features);
  7606. else
  7607. err = 0;
  7608. if (unlikely(err < 0)) {
  7609. netdev_err(dev,
  7610. "set_features() failed (%d); wanted %pNF, left %pNF\n",
  7611. err, &features, &dev->features);
  7612. /* return non-0 since some features might have changed and
  7613. * it's better to fire a spurious notification than miss it
  7614. */
  7615. return -1;
  7616. }
  7617. sync_lower:
  7618. /* some features must be disabled on lower devices when disabled
  7619. * on an upper device (think: bonding master or bridge)
  7620. */
  7621. netdev_for_each_lower_dev(dev, lower, iter)
  7622. netdev_sync_lower_features(dev, lower, features);
  7623. if (!err) {
  7624. netdev_features_t diff = features ^ dev->features;
  7625. if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
  7626. /* udp_tunnel_{get,drop}_rx_info both need
  7627. * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
  7628. * device, or they won't do anything.
  7629. * Thus we need to update dev->features
  7630. * *before* calling udp_tunnel_get_rx_info,
  7631. * but *after* calling udp_tunnel_drop_rx_info.
  7632. */
  7633. if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
  7634. dev->features = features;
  7635. udp_tunnel_get_rx_info(dev);
  7636. } else {
  7637. udp_tunnel_drop_rx_info(dev);
  7638. }
  7639. }
  7640. if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
  7641. if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
  7642. dev->features = features;
  7643. err |= vlan_get_rx_ctag_filter_info(dev);
  7644. } else {
  7645. vlan_drop_rx_ctag_filter_info(dev);
  7646. }
  7647. }
  7648. if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
  7649. if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
  7650. dev->features = features;
  7651. err |= vlan_get_rx_stag_filter_info(dev);
  7652. } else {
  7653. vlan_drop_rx_stag_filter_info(dev);
  7654. }
  7655. }
  7656. dev->features = features;
  7657. }
  7658. return err < 0 ? 0 : 1;
  7659. }
  7660. /**
  7661. * netdev_update_features - recalculate device features
  7662. * @dev: the device to check
  7663. *
  7664. * Recalculate dev->features set and send notifications if it
  7665. * has changed. Should be called after driver or hardware dependent
  7666. * conditions might have changed that influence the features.
  7667. */
  7668. void netdev_update_features(struct net_device *dev)
  7669. {
  7670. if (__netdev_update_features(dev))
  7671. netdev_features_change(dev);
  7672. }
  7673. EXPORT_SYMBOL(netdev_update_features);
  7674. /**
  7675. * netdev_change_features - recalculate device features
  7676. * @dev: the device to check
  7677. *
  7678. * Recalculate dev->features set and send notifications even
  7679. * if they have not changed. Should be called instead of
  7680. * netdev_update_features() if also dev->vlan_features might
  7681. * have changed to allow the changes to be propagated to stacked
  7682. * VLAN devices.
  7683. */
  7684. void netdev_change_features(struct net_device *dev)
  7685. {
  7686. __netdev_update_features(dev);
  7687. netdev_features_change(dev);
  7688. }
  7689. EXPORT_SYMBOL(netdev_change_features);
  7690. /**
  7691. * netif_stacked_transfer_operstate - transfer operstate
  7692. * @rootdev: the root or lower level device to transfer state from
  7693. * @dev: the device to transfer operstate to
  7694. *
  7695. * Transfer operational state from root to device. This is normally
  7696. * called when a stacking relationship exists between the root
  7697. * device and the device(a leaf device).
  7698. */
  7699. void netif_stacked_transfer_operstate(const struct net_device *rootdev,
  7700. struct net_device *dev)
  7701. {
  7702. if (rootdev->operstate == IF_OPER_DORMANT)
  7703. netif_dormant_on(dev);
  7704. else
  7705. netif_dormant_off(dev);
  7706. if (netif_carrier_ok(rootdev))
  7707. netif_carrier_on(dev);
  7708. else
  7709. netif_carrier_off(dev);
  7710. }
  7711. EXPORT_SYMBOL(netif_stacked_transfer_operstate);
  7712. static int netif_alloc_rx_queues(struct net_device *dev)
  7713. {
  7714. unsigned int i, count = dev->num_rx_queues;
  7715. struct netdev_rx_queue *rx;
  7716. size_t sz = count * sizeof(*rx);
  7717. int err = 0;
  7718. BUG_ON(count < 1);
  7719. rx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
  7720. if (!rx)
  7721. return -ENOMEM;
  7722. dev->_rx = rx;
  7723. for (i = 0; i < count; i++) {
  7724. rx[i].dev = dev;
  7725. /* XDP RX-queue setup */
  7726. err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i);
  7727. if (err < 0)
  7728. goto err_rxq_info;
  7729. }
  7730. return 0;
  7731. err_rxq_info:
  7732. /* Rollback successful reg's and free other resources */
  7733. while (i--)
  7734. xdp_rxq_info_unreg(&rx[i].xdp_rxq);
  7735. kvfree(dev->_rx);
  7736. dev->_rx = NULL;
  7737. return err;
  7738. }
  7739. static void netif_free_rx_queues(struct net_device *dev)
  7740. {
  7741. unsigned int i, count = dev->num_rx_queues;
  7742. /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
  7743. if (!dev->_rx)
  7744. return;
  7745. for (i = 0; i < count; i++)
  7746. xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
  7747. kvfree(dev->_rx);
  7748. }
  7749. static void netdev_init_one_queue(struct net_device *dev,
  7750. struct netdev_queue *queue, void *_unused)
  7751. {
  7752. /* Initialize queue lock */
  7753. spin_lock_init(&queue->_xmit_lock);
  7754. lockdep_set_class(&queue->_xmit_lock, &dev->qdisc_xmit_lock_key);
  7755. queue->xmit_lock_owner = -1;
  7756. netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
  7757. queue->dev = dev;
  7758. #ifdef CONFIG_BQL
  7759. dql_init(&queue->dql, HZ);
  7760. #endif
  7761. }
  7762. static void netif_free_tx_queues(struct net_device *dev)
  7763. {
  7764. kvfree(dev->_tx);
  7765. }
  7766. static int netif_alloc_netdev_queues(struct net_device *dev)
  7767. {
  7768. unsigned int count = dev->num_tx_queues;
  7769. struct netdev_queue *tx;
  7770. size_t sz = count * sizeof(*tx);
  7771. if (count < 1 || count > 0xffff)
  7772. return -EINVAL;
  7773. tx = kvzalloc(sz, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
  7774. if (!tx)
  7775. return -ENOMEM;
  7776. dev->_tx = tx;
  7777. netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
  7778. spin_lock_init(&dev->tx_global_lock);
  7779. return 0;
  7780. }
  7781. void netif_tx_stop_all_queues(struct net_device *dev)
  7782. {
  7783. unsigned int i;
  7784. for (i = 0; i < dev->num_tx_queues; i++) {
  7785. struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
  7786. netif_tx_stop_queue(txq);
  7787. }
  7788. }
  7789. EXPORT_SYMBOL(netif_tx_stop_all_queues);
  7790. static void netdev_register_lockdep_key(struct net_device *dev)
  7791. {
  7792. lockdep_register_key(&dev->qdisc_tx_busylock_key);
  7793. lockdep_register_key(&dev->qdisc_running_key);
  7794. lockdep_register_key(&dev->qdisc_xmit_lock_key);
  7795. lockdep_register_key(&dev->addr_list_lock_key);
  7796. }
  7797. static void netdev_unregister_lockdep_key(struct net_device *dev)
  7798. {
  7799. lockdep_unregister_key(&dev->qdisc_tx_busylock_key);
  7800. lockdep_unregister_key(&dev->qdisc_running_key);
  7801. lockdep_unregister_key(&dev->qdisc_xmit_lock_key);
  7802. lockdep_unregister_key(&dev->addr_list_lock_key);
  7803. }
  7804. void netdev_update_lockdep_key(struct net_device *dev)
  7805. {
  7806. lockdep_unregister_key(&dev->addr_list_lock_key);
  7807. lockdep_register_key(&dev->addr_list_lock_key);
  7808. lockdep_set_class(&dev->addr_list_lock, &dev->addr_list_lock_key);
  7809. }
  7810. EXPORT_SYMBOL(netdev_update_lockdep_key);
  7811. /**
  7812. * register_netdevice - register a network device
  7813. * @dev: device to register
  7814. *
  7815. * Take a completed network device structure and add it to the kernel
  7816. * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
  7817. * chain. 0 is returned on success. A negative errno code is returned
  7818. * on a failure to set up the device, or if the name is a duplicate.
  7819. *
  7820. * Callers must hold the rtnl semaphore. You may want
  7821. * register_netdev() instead of this.
  7822. *
  7823. * BUGS:
  7824. * The locking appears insufficient to guarantee two parallel registers
  7825. * will not get the same name.
  7826. */
  7827. int register_netdevice(struct net_device *dev)
  7828. {
  7829. int ret;
  7830. struct net *net = dev_net(dev);
  7831. BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
  7832. NETDEV_FEATURE_COUNT);
  7833. BUG_ON(dev_boot_phase);
  7834. ASSERT_RTNL();
  7835. might_sleep();
  7836. /* When net_device's are persistent, this will be fatal. */
  7837. BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
  7838. BUG_ON(!net);
  7839. ret = ethtool_check_ops(dev->ethtool_ops);
  7840. if (ret)
  7841. return ret;
  7842. spin_lock_init(&dev->addr_list_lock);
  7843. lockdep_set_class(&dev->addr_list_lock, &dev->addr_list_lock_key);
  7844. ret = dev_get_valid_name(net, dev, dev->name);
  7845. if (ret < 0)
  7846. goto out;
  7847. ret = -ENOMEM;
  7848. dev->name_node = netdev_name_node_head_alloc(dev);
  7849. if (!dev->name_node)
  7850. goto out;
  7851. /* Init, if this function is available */
  7852. if (dev->netdev_ops->ndo_init) {
  7853. ret = dev->netdev_ops->ndo_init(dev);
  7854. if (ret) {
  7855. if (ret > 0)
  7856. ret = -EIO;
  7857. goto err_free_name;
  7858. }
  7859. }
  7860. if (((dev->hw_features | dev->features) &
  7861. NETIF_F_HW_VLAN_CTAG_FILTER) &&
  7862. (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
  7863. !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
  7864. netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
  7865. ret = -EINVAL;
  7866. goto err_uninit;
  7867. }
  7868. ret = -EBUSY;
  7869. if (!dev->ifindex)
  7870. dev->ifindex = dev_new_index(net);
  7871. else if (__dev_get_by_index(net, dev->ifindex))
  7872. goto err_uninit;
  7873. /* Transfer changeable features to wanted_features and enable
  7874. * software offloads (GSO and GRO).
  7875. */
  7876. dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
  7877. dev->features |= NETIF_F_SOFT_FEATURES;
  7878. if (dev->netdev_ops->ndo_udp_tunnel_add) {
  7879. dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
  7880. dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
  7881. }
  7882. dev->wanted_features = dev->features & dev->hw_features;
  7883. if (!(dev->flags & IFF_LOOPBACK))
  7884. dev->hw_features |= NETIF_F_NOCACHE_COPY;
  7885. /* If IPv4 TCP segmentation offload is supported we should also
  7886. * allow the device to enable segmenting the frame with the option
  7887. * of ignoring a static IP ID value. This doesn't enable the
  7888. * feature itself but allows the user to enable it later.
  7889. */
  7890. if (dev->hw_features & NETIF_F_TSO)
  7891. dev->hw_features |= NETIF_F_TSO_MANGLEID;
  7892. if (dev->vlan_features & NETIF_F_TSO)
  7893. dev->vlan_features |= NETIF_F_TSO_MANGLEID;
  7894. if (dev->mpls_features & NETIF_F_TSO)
  7895. dev->mpls_features |= NETIF_F_TSO_MANGLEID;
  7896. if (dev->hw_enc_features & NETIF_F_TSO)
  7897. dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
  7898. /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
  7899. */
  7900. dev->vlan_features |= NETIF_F_HIGHDMA;
  7901. /* Make NETIF_F_SG inheritable to tunnel devices.
  7902. */
  7903. dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
  7904. /* Make NETIF_F_SG inheritable to MPLS.
  7905. */
  7906. dev->mpls_features |= NETIF_F_SG;
  7907. ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
  7908. ret = notifier_to_errno(ret);
  7909. if (ret)
  7910. goto err_uninit;
  7911. ret = netdev_register_kobject(dev);
  7912. if (ret) {
  7913. dev->reg_state = NETREG_UNREGISTERED;
  7914. goto err_uninit;
  7915. }
  7916. dev->reg_state = NETREG_REGISTERED;
  7917. __netdev_update_features(dev);
  7918. /*
  7919. * Default initial state at registry is that the
  7920. * device is present.
  7921. */
  7922. set_bit(__LINK_STATE_PRESENT, &dev->state);
  7923. linkwatch_init_dev(dev);
  7924. dev_init_scheduler(dev);
  7925. dev_hold(dev);
  7926. list_netdevice(dev);
  7927. add_device_randomness(dev->dev_addr, dev->addr_len);
  7928. /* If the device has permanent device address, driver should
  7929. * set dev_addr and also addr_assign_type should be set to
  7930. * NET_ADDR_PERM (default value).
  7931. */
  7932. if (dev->addr_assign_type == NET_ADDR_PERM)
  7933. memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
  7934. /* Notify protocols, that a new device appeared. */
  7935. ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
  7936. ret = notifier_to_errno(ret);
  7937. if (ret) {
  7938. rollback_registered(dev);
  7939. rcu_barrier();
  7940. dev->reg_state = NETREG_UNREGISTERED;
  7941. }
  7942. /*
  7943. * Prevent userspace races by waiting until the network
  7944. * device is fully setup before sending notifications.
  7945. */
  7946. if (!dev->rtnl_link_ops ||
  7947. dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
  7948. rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
  7949. out:
  7950. return ret;
  7951. err_uninit:
  7952. if (dev->netdev_ops->ndo_uninit)
  7953. dev->netdev_ops->ndo_uninit(dev);
  7954. if (dev->priv_destructor)
  7955. dev->priv_destructor(dev);
  7956. err_free_name:
  7957. netdev_name_node_free(dev->name_node);
  7958. goto out;
  7959. }
  7960. EXPORT_SYMBOL(register_netdevice);
  7961. /**
  7962. * init_dummy_netdev - init a dummy network device for NAPI
  7963. * @dev: device to init
  7964. *
  7965. * This takes a network device structure and initialize the minimum
  7966. * amount of fields so it can be used to schedule NAPI polls without
  7967. * registering a full blown interface. This is to be used by drivers
  7968. * that need to tie several hardware interfaces to a single NAPI
  7969. * poll scheduler due to HW limitations.
  7970. */
  7971. int init_dummy_netdev(struct net_device *dev)
  7972. {
  7973. /* Clear everything. Note we don't initialize spinlocks
  7974. * are they aren't supposed to be taken by any of the
  7975. * NAPI code and this dummy netdev is supposed to be
  7976. * only ever used for NAPI polls
  7977. */
  7978. memset(dev, 0, sizeof(struct net_device));
  7979. /* make sure we BUG if trying to hit standard
  7980. * register/unregister code path
  7981. */
  7982. dev->reg_state = NETREG_DUMMY;
  7983. /* NAPI wants this */
  7984. INIT_LIST_HEAD(&dev->napi_list);
  7985. /* a dummy interface is started by default */
  7986. set_bit(__LINK_STATE_PRESENT, &dev->state);
  7987. set_bit(__LINK_STATE_START, &dev->state);
  7988. /* napi_busy_loop stats accounting wants this */
  7989. dev_net_set(dev, &init_net);
  7990. /* Note : We dont allocate pcpu_refcnt for dummy devices,
  7991. * because users of this 'device' dont need to change
  7992. * its refcount.
  7993. */
  7994. return 0;
  7995. }
  7996. EXPORT_SYMBOL_GPL(init_dummy_netdev);
  7997. /**
  7998. * register_netdev - register a network device
  7999. * @dev: device to register
  8000. *
  8001. * Take a completed network device structure and add it to the kernel
  8002. * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
  8003. * chain. 0 is returned on success. A negative errno code is returned
  8004. * on a failure to set up the device, or if the name is a duplicate.
  8005. *
  8006. * This is a wrapper around register_netdevice that takes the rtnl semaphore
  8007. * and expands the device name if you passed a format string to
  8008. * alloc_netdev.
  8009. */
  8010. int register_netdev(struct net_device *dev)
  8011. {
  8012. int err;
  8013. if (rtnl_lock_killable())
  8014. return -EINTR;
  8015. err = register_netdevice(dev);
  8016. rtnl_unlock();
  8017. return err;
  8018. }
  8019. EXPORT_SYMBOL(register_netdev);
  8020. int netdev_refcnt_read(const struct net_device *dev)
  8021. {
  8022. int i, refcnt = 0;
  8023. for_each_possible_cpu(i)
  8024. refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
  8025. return refcnt;
  8026. }
  8027. EXPORT_SYMBOL(netdev_refcnt_read);
  8028. /**
  8029. * netdev_wait_allrefs - wait until all references are gone.
  8030. * @dev: target net_device
  8031. *
  8032. * This is called when unregistering network devices.
  8033. *
  8034. * Any protocol or device that holds a reference should register
  8035. * for netdevice notification, and cleanup and put back the
  8036. * reference if they receive an UNREGISTER event.
  8037. * We can get stuck here if buggy protocols don't correctly
  8038. * call dev_put.
  8039. */
  8040. static void netdev_wait_allrefs(struct net_device *dev)
  8041. {
  8042. unsigned long rebroadcast_time, warning_time;
  8043. int refcnt;
  8044. linkwatch_forget_dev(dev);
  8045. rebroadcast_time = warning_time = jiffies;
  8046. refcnt = netdev_refcnt_read(dev);
  8047. while (refcnt != 0) {
  8048. if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
  8049. rtnl_lock();
  8050. /* Rebroadcast unregister notification */
  8051. call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
  8052. __rtnl_unlock();
  8053. rcu_barrier();
  8054. rtnl_lock();
  8055. if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
  8056. &dev->state)) {
  8057. /* We must not have linkwatch events
  8058. * pending on unregister. If this
  8059. * happens, we simply run the queue
  8060. * unscheduled, resulting in a noop
  8061. * for this device.
  8062. */
  8063. linkwatch_run_queue();
  8064. }
  8065. __rtnl_unlock();
  8066. rebroadcast_time = jiffies;
  8067. }
  8068. msleep(250);
  8069. refcnt = netdev_refcnt_read(dev);
  8070. if (refcnt && time_after(jiffies, warning_time + 10 * HZ)) {
  8071. pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
  8072. dev->name, refcnt);
  8073. warning_time = jiffies;
  8074. }
  8075. }
  8076. }
  8077. /* The sequence is:
  8078. *
  8079. * rtnl_lock();
  8080. * ...
  8081. * register_netdevice(x1);
  8082. * register_netdevice(x2);
  8083. * ...
  8084. * unregister_netdevice(y1);
  8085. * unregister_netdevice(y2);
  8086. * ...
  8087. * rtnl_unlock();
  8088. * free_netdev(y1);
  8089. * free_netdev(y2);
  8090. *
  8091. * We are invoked by rtnl_unlock().
  8092. * This allows us to deal with problems:
  8093. * 1) We can delete sysfs objects which invoke hotplug
  8094. * without deadlocking with linkwatch via keventd.
  8095. * 2) Since we run with the RTNL semaphore not held, we can sleep
  8096. * safely in order to wait for the netdev refcnt to drop to zero.
  8097. *
  8098. * We must not return until all unregister events added during
  8099. * the interval the lock was held have been completed.
  8100. */
  8101. void netdev_run_todo(void)
  8102. {
  8103. struct list_head list;
  8104. /* Snapshot list, allow later requests */
  8105. list_replace_init(&net_todo_list, &list);
  8106. __rtnl_unlock();
  8107. /* Wait for rcu callbacks to finish before next phase */
  8108. if (!list_empty(&list))
  8109. rcu_barrier();
  8110. while (!list_empty(&list)) {
  8111. struct net_device *dev
  8112. = list_first_entry(&list, struct net_device, todo_list);
  8113. list_del(&dev->todo_list);
  8114. if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
  8115. pr_err("network todo '%s' but state %d\n",
  8116. dev->name, dev->reg_state);
  8117. dump_stack();
  8118. continue;
  8119. }
  8120. dev->reg_state = NETREG_UNREGISTERED;
  8121. netdev_wait_allrefs(dev);
  8122. /* paranoia */
  8123. BUG_ON(netdev_refcnt_read(dev));
  8124. BUG_ON(!list_empty(&dev->ptype_all));
  8125. BUG_ON(!list_empty(&dev->ptype_specific));
  8126. WARN_ON(rcu_access_pointer(dev->ip_ptr));
  8127. WARN_ON(rcu_access_pointer(dev->ip6_ptr));
  8128. #if IS_ENABLED(CONFIG_DECNET)
  8129. WARN_ON(dev->dn_ptr);
  8130. #endif
  8131. if (dev->priv_destructor)
  8132. dev->priv_destructor(dev);
  8133. if (dev->needs_free_netdev)
  8134. free_netdev(dev);
  8135. /* Report a network device has been unregistered */
  8136. rtnl_lock();
  8137. dev_net(dev)->dev_unreg_count--;
  8138. __rtnl_unlock();
  8139. wake_up(&netdev_unregistering_wq);
  8140. /* Free network device */
  8141. kobject_put(&dev->dev.kobj);
  8142. }
  8143. }
  8144. /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
  8145. * all the same fields in the same order as net_device_stats, with only
  8146. * the type differing, but rtnl_link_stats64 may have additional fields
  8147. * at the end for newer counters.
  8148. */
  8149. void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
  8150. const struct net_device_stats *netdev_stats)
  8151. {
  8152. #if BITS_PER_LONG == 64
  8153. BUILD_BUG_ON(sizeof(*stats64) < sizeof(*netdev_stats));
  8154. memcpy(stats64, netdev_stats, sizeof(*netdev_stats));
  8155. /* zero out counters that only exist in rtnl_link_stats64 */
  8156. memset((char *)stats64 + sizeof(*netdev_stats), 0,
  8157. sizeof(*stats64) - sizeof(*netdev_stats));
  8158. #else
  8159. size_t i, n = sizeof(*netdev_stats) / sizeof(unsigned long);
  8160. const unsigned long *src = (const unsigned long *)netdev_stats;
  8161. u64 *dst = (u64 *)stats64;
  8162. BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
  8163. for (i = 0; i < n; i++)
  8164. dst[i] = src[i];
  8165. /* zero out counters that only exist in rtnl_link_stats64 */
  8166. memset((char *)stats64 + n * sizeof(u64), 0,
  8167. sizeof(*stats64) - n * sizeof(u64));
  8168. #endif
  8169. }
  8170. EXPORT_SYMBOL(netdev_stats_to_stats64);
  8171. /**
  8172. * dev_get_stats - get network device statistics
  8173. * @dev: device to get statistics from
  8174. * @storage: place to store stats
  8175. *
  8176. * Get network statistics from device. Return @storage.
  8177. * The device driver may provide its own method by setting
  8178. * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
  8179. * otherwise the internal statistics structure is used.
  8180. */
  8181. struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
  8182. struct rtnl_link_stats64 *storage)
  8183. {
  8184. const struct net_device_ops *ops = dev->netdev_ops;
  8185. if (ops->ndo_get_stats64) {
  8186. memset(storage, 0, sizeof(*storage));
  8187. ops->ndo_get_stats64(dev, storage);
  8188. } else if (ops->ndo_get_stats) {
  8189. netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
  8190. } else {
  8191. netdev_stats_to_stats64(storage, &dev->stats);
  8192. }
  8193. storage->rx_dropped += (unsigned long)atomic_long_read(&dev->rx_dropped);
  8194. storage->tx_dropped += (unsigned long)atomic_long_read(&dev->tx_dropped);
  8195. storage->rx_nohandler += (unsigned long)atomic_long_read(&dev->rx_nohandler);
  8196. return storage;
  8197. }
  8198. EXPORT_SYMBOL(dev_get_stats);
  8199. struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
  8200. {
  8201. struct netdev_queue *queue = dev_ingress_queue(dev);
  8202. #ifdef CONFIG_NET_CLS_ACT
  8203. if (queue)
  8204. return queue;
  8205. queue = kzalloc(sizeof(*queue), GFP_KERNEL);
  8206. if (!queue)
  8207. return NULL;
  8208. netdev_init_one_queue(dev, queue, NULL);
  8209. RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
  8210. queue->qdisc_sleeping = &noop_qdisc;
  8211. rcu_assign_pointer(dev->ingress_queue, queue);
  8212. #endif
  8213. return queue;
  8214. }
  8215. static const struct ethtool_ops default_ethtool_ops;
  8216. void netdev_set_default_ethtool_ops(struct net_device *dev,
  8217. const struct ethtool_ops *ops)
  8218. {
  8219. if (dev->ethtool_ops == &default_ethtool_ops)
  8220. dev->ethtool_ops = ops;
  8221. }
  8222. EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
  8223. void netdev_freemem(struct net_device *dev)
  8224. {
  8225. char *addr = (char *)dev - dev->padded;
  8226. kvfree(addr);
  8227. }
  8228. /**
  8229. * alloc_netdev_mqs - allocate network device
  8230. * @sizeof_priv: size of private data to allocate space for
  8231. * @name: device name format string
  8232. * @name_assign_type: origin of device name
  8233. * @setup: callback to initialize device
  8234. * @txqs: the number of TX subqueues to allocate
  8235. * @rxqs: the number of RX subqueues to allocate
  8236. *
  8237. * Allocates a struct net_device with private data area for driver use
  8238. * and performs basic initialization. Also allocates subqueue structs
  8239. * for each queue on the device.
  8240. */
  8241. struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
  8242. unsigned char name_assign_type,
  8243. void (*setup)(struct net_device *),
  8244. unsigned int txqs, unsigned int rxqs)
  8245. {
  8246. struct net_device *dev;
  8247. unsigned int alloc_size;
  8248. struct net_device *p;
  8249. BUG_ON(strlen(name) >= sizeof(dev->name));
  8250. if (txqs < 1) {
  8251. pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
  8252. return NULL;
  8253. }
  8254. if (rxqs < 1) {
  8255. pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
  8256. return NULL;
  8257. }
  8258. alloc_size = sizeof(struct net_device);
  8259. if (sizeof_priv) {
  8260. /* ensure 32-byte alignment of private area */
  8261. alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
  8262. alloc_size += sizeof_priv;
  8263. }
  8264. /* ensure 32-byte alignment of whole construct */
  8265. alloc_size += NETDEV_ALIGN - 1;
  8266. p = kvzalloc(alloc_size, GFP_KERNEL | __GFP_RETRY_MAYFAIL);
  8267. if (!p)
  8268. return NULL;
  8269. dev = PTR_ALIGN(p, NETDEV_ALIGN);
  8270. dev->padded = (char *)dev - (char *)p;
  8271. dev->pcpu_refcnt = alloc_percpu(int);
  8272. if (!dev->pcpu_refcnt)
  8273. goto free_dev;
  8274. if (dev_addr_init(dev))
  8275. goto free_pcpu;
  8276. dev_mc_init(dev);
  8277. dev_uc_init(dev);
  8278. dev_net_set(dev, &init_net);
  8279. netdev_register_lockdep_key(dev);
  8280. dev->gso_max_size = GSO_MAX_SIZE;
  8281. dev->gso_max_segs = GSO_MAX_SEGS;
  8282. dev->upper_level = 1;
  8283. dev->lower_level = 1;
  8284. INIT_LIST_HEAD(&dev->napi_list);
  8285. INIT_LIST_HEAD(&dev->unreg_list);
  8286. INIT_LIST_HEAD(&dev->close_list);
  8287. INIT_LIST_HEAD(&dev->link_watch_list);
  8288. INIT_LIST_HEAD(&dev->adj_list.upper);
  8289. INIT_LIST_HEAD(&dev->adj_list.lower);
  8290. INIT_LIST_HEAD(&dev->ptype_all);
  8291. INIT_LIST_HEAD(&dev->ptype_specific);
  8292. INIT_LIST_HEAD(&dev->net_notifier_list);
  8293. #ifdef CONFIG_NET_SCHED
  8294. hash_init(dev->qdisc_hash);
  8295. #endif
  8296. dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
  8297. setup(dev);
  8298. if (!dev->tx_queue_len) {
  8299. dev->priv_flags |= IFF_NO_QUEUE;
  8300. dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
  8301. }
  8302. dev->num_tx_queues = txqs;
  8303. dev->real_num_tx_queues = txqs;
  8304. if (netif_alloc_netdev_queues(dev))
  8305. goto free_all;
  8306. dev->num_rx_queues = rxqs;
  8307. dev->real_num_rx_queues = rxqs;
  8308. if (netif_alloc_rx_queues(dev))
  8309. goto free_all;
  8310. strcpy(dev->name, name);
  8311. dev->name_assign_type = name_assign_type;
  8312. dev->group = INIT_NETDEV_GROUP;
  8313. if (!dev->ethtool_ops)
  8314. dev->ethtool_ops = &default_ethtool_ops;
  8315. nf_hook_ingress_init(dev);
  8316. return dev;
  8317. free_all:
  8318. free_netdev(dev);
  8319. return NULL;
  8320. free_pcpu:
  8321. free_percpu(dev->pcpu_refcnt);
  8322. free_dev:
  8323. netdev_freemem(dev);
  8324. return NULL;
  8325. }
  8326. EXPORT_SYMBOL(alloc_netdev_mqs);
  8327. /**
  8328. * free_netdev - free network device
  8329. * @dev: device
  8330. *
  8331. * This function does the last stage of destroying an allocated device
  8332. * interface. The reference to the device object is released. If this
  8333. * is the last reference then it will be freed.Must be called in process
  8334. * context.
  8335. */
  8336. void free_netdev(struct net_device *dev)
  8337. {
  8338. struct napi_struct *p, *n;
  8339. might_sleep();
  8340. netif_free_tx_queues(dev);
  8341. netif_free_rx_queues(dev);
  8342. kfree(rcu_dereference_protected(dev->ingress_queue, 1));
  8343. /* Flush device addresses */
  8344. dev_addr_flush(dev);
  8345. list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
  8346. netif_napi_del(p);
  8347. free_percpu(dev->pcpu_refcnt);
  8348. dev->pcpu_refcnt = NULL;
  8349. free_percpu(dev->xdp_bulkq);
  8350. dev->xdp_bulkq = NULL;
  8351. netdev_unregister_lockdep_key(dev);
  8352. /* Compatibility with error handling in drivers */
  8353. if (dev->reg_state == NETREG_UNINITIALIZED) {
  8354. netdev_freemem(dev);
  8355. return;
  8356. }
  8357. BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
  8358. dev->reg_state = NETREG_RELEASED;
  8359. /* will free via device release */
  8360. put_device(&dev->dev);
  8361. }
  8362. EXPORT_SYMBOL(free_netdev);
  8363. /**
  8364. * synchronize_net - Synchronize with packet receive processing
  8365. *
  8366. * Wait for packets currently being received to be done.
  8367. * Does not block later packets from starting.
  8368. */
  8369. void synchronize_net(void)
  8370. {
  8371. might_sleep();
  8372. if (rtnl_is_locked())
  8373. synchronize_rcu_expedited();
  8374. else
  8375. synchronize_rcu();
  8376. }
  8377. EXPORT_SYMBOL(synchronize_net);
  8378. /**
  8379. * unregister_netdevice_queue - remove device from the kernel
  8380. * @dev: device
  8381. * @head: list
  8382. *
  8383. * This function shuts down a device interface and removes it
  8384. * from the kernel tables.
  8385. * If head not NULL, device is queued to be unregistered later.
  8386. *
  8387. * Callers must hold the rtnl semaphore. You may want
  8388. * unregister_netdev() instead of this.
  8389. */
  8390. void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
  8391. {
  8392. ASSERT_RTNL();
  8393. if (head) {
  8394. list_move_tail(&dev->unreg_list, head);
  8395. } else {
  8396. rollback_registered(dev);
  8397. /* Finish processing unregister after unlock */
  8398. net_set_todo(dev);
  8399. }
  8400. }
  8401. EXPORT_SYMBOL(unregister_netdevice_queue);
  8402. /**
  8403. * unregister_netdevice_many - unregister many devices
  8404. * @head: list of devices
  8405. *
  8406. * Note: As most callers use a stack allocated list_head,
  8407. * we force a list_del() to make sure stack wont be corrupted later.
  8408. */
  8409. void unregister_netdevice_many(struct list_head *head)
  8410. {
  8411. struct net_device *dev;
  8412. if (!list_empty(head)) {
  8413. rollback_registered_many(head);
  8414. list_for_each_entry(dev, head, unreg_list)
  8415. net_set_todo(dev);
  8416. list_del(head);
  8417. }
  8418. }
  8419. EXPORT_SYMBOL(unregister_netdevice_many);
  8420. /**
  8421. * unregister_netdev - remove device from the kernel
  8422. * @dev: device
  8423. *
  8424. * This function shuts down a device interface and removes it
  8425. * from the kernel tables.
  8426. *
  8427. * This is just a wrapper for unregister_netdevice that takes
  8428. * the rtnl semaphore. In general you want to use this and not
  8429. * unregister_netdevice.
  8430. */
  8431. void unregister_netdev(struct net_device *dev)
  8432. {
  8433. rtnl_lock();
  8434. unregister_netdevice(dev);
  8435. rtnl_unlock();
  8436. }
  8437. EXPORT_SYMBOL(unregister_netdev);
  8438. /**
  8439. * dev_change_net_namespace - move device to different nethost namespace
  8440. * @dev: device
  8441. * @net: network namespace
  8442. * @pat: If not NULL name pattern to try if the current device name
  8443. * is already taken in the destination network namespace.
  8444. *
  8445. * This function shuts down a device interface and moves it
  8446. * to a new network namespace. On success 0 is returned, on
  8447. * a failure a netagive errno code is returned.
  8448. *
  8449. * Callers must hold the rtnl semaphore.
  8450. */
  8451. int dev_change_net_namespace(struct net_device *dev, struct net *net, const char *pat)
  8452. {
  8453. struct net *net_old = dev_net(dev);
  8454. int err, new_nsid, new_ifindex;
  8455. ASSERT_RTNL();
  8456. /* Don't allow namespace local devices to be moved. */
  8457. err = -EINVAL;
  8458. if (dev->features & NETIF_F_NETNS_LOCAL)
  8459. goto out;
  8460. /* Ensure the device has been registrered */
  8461. if (dev->reg_state != NETREG_REGISTERED)
  8462. goto out;
  8463. /* Get out if there is nothing todo */
  8464. err = 0;
  8465. if (net_eq(net_old, net))
  8466. goto out;
  8467. /* Pick the destination device name, and ensure
  8468. * we can use it in the destination network namespace.
  8469. */
  8470. err = -EEXIST;
  8471. if (__dev_get_by_name(net, dev->name)) {
  8472. /* We get here if we can't use the current device name */
  8473. if (!pat)
  8474. goto out;
  8475. err = dev_get_valid_name(net, dev, pat);
  8476. if (err < 0)
  8477. goto out;
  8478. }
  8479. /*
  8480. * And now a mini version of register_netdevice unregister_netdevice.
  8481. */
  8482. /* If device is running close it first. */
  8483. dev_close(dev);
  8484. /* And unlink it from device chain */
  8485. unlist_netdevice(dev);
  8486. synchronize_net();
  8487. /* Shutdown queueing discipline. */
  8488. dev_shutdown(dev);
  8489. /* Notify protocols, that we are about to destroy
  8490. * this device. They should clean all the things.
  8491. *
  8492. * Note that dev->reg_state stays at NETREG_REGISTERED.
  8493. * This is wanted because this way 8021q and macvlan know
  8494. * the device is just moving and can keep their slaves up.
  8495. */
  8496. call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
  8497. rcu_barrier();
  8498. new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
  8499. /* If there is an ifindex conflict assign a new one */
  8500. if (__dev_get_by_index(net, dev->ifindex))
  8501. new_ifindex = dev_new_index(net);
  8502. else
  8503. new_ifindex = dev->ifindex;
  8504. rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
  8505. new_ifindex);
  8506. /*
  8507. * Flush the unicast and multicast chains
  8508. */
  8509. dev_uc_flush(dev);
  8510. dev_mc_flush(dev);
  8511. /* Send a netdev-removed uevent to the old namespace */
  8512. kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
  8513. netdev_adjacent_del_links(dev);
  8514. /* Move per-net netdevice notifiers that are following the netdevice */
  8515. move_netdevice_notifiers_dev_net(dev, net);
  8516. /* Actually switch the network namespace */
  8517. dev_net_set(dev, net);
  8518. dev->ifindex = new_ifindex;
  8519. /* Send a netdev-add uevent to the new namespace */
  8520. kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
  8521. netdev_adjacent_add_links(dev);
  8522. /* Fixup kobjects */
  8523. err = device_rename(&dev->dev, dev->name);
  8524. WARN_ON(err);
  8525. /* Adapt owner in case owning user namespace of target network
  8526. * namespace is different from the original one.
  8527. */
  8528. err = netdev_change_owner(dev, net_old, net);
  8529. WARN_ON(err);
  8530. /* Add the device back in the hashes */
  8531. list_netdevice(dev);
  8532. /* Notify protocols, that a new device appeared. */
  8533. call_netdevice_notifiers(NETDEV_REGISTER, dev);
  8534. /*
  8535. * Prevent userspace races by waiting until the network
  8536. * device is fully setup before sending notifications.
  8537. */
  8538. rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL);
  8539. synchronize_net();
  8540. err = 0;
  8541. out:
  8542. return err;
  8543. }
  8544. EXPORT_SYMBOL_GPL(dev_change_net_namespace);
  8545. static int dev_cpu_dead(unsigned int oldcpu)
  8546. {
  8547. struct sk_buff **list_skb;
  8548. struct sk_buff *skb;
  8549. unsigned int cpu;
  8550. struct softnet_data *sd, *oldsd, *remsd = NULL;
  8551. local_irq_disable();
  8552. cpu = smp_processor_id();
  8553. sd = &per_cpu(softnet_data, cpu);
  8554. oldsd = &per_cpu(softnet_data, oldcpu);
  8555. /* Find end of our completion_queue. */
  8556. list_skb = &sd->completion_queue;
  8557. while (*list_skb)
  8558. list_skb = &(*list_skb)->next;
  8559. /* Append completion queue from offline CPU. */
  8560. *list_skb = oldsd->completion_queue;
  8561. oldsd->completion_queue = NULL;
  8562. /* Append output queue from offline CPU. */
  8563. if (oldsd->output_queue) {
  8564. *sd->output_queue_tailp = oldsd->output_queue;
  8565. sd->output_queue_tailp = oldsd->output_queue_tailp;
  8566. oldsd->output_queue = NULL;
  8567. oldsd->output_queue_tailp = &oldsd->output_queue;
  8568. }
  8569. /* Append NAPI poll list from offline CPU, with one exception :
  8570. * process_backlog() must be called by cpu owning percpu backlog.
  8571. * We properly handle process_queue & input_pkt_queue later.
  8572. */
  8573. while (!list_empty(&oldsd->poll_list)) {
  8574. struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
  8575. struct napi_struct,
  8576. poll_list);
  8577. list_del_init(&napi->poll_list);
  8578. if (napi->poll == process_backlog)
  8579. napi->state = 0;
  8580. else
  8581. ____napi_schedule(sd, napi);
  8582. }
  8583. raise_softirq_irqoff(NET_TX_SOFTIRQ);
  8584. local_irq_enable();
  8585. #ifdef CONFIG_RPS
  8586. remsd = oldsd->rps_ipi_list;
  8587. oldsd->rps_ipi_list = NULL;
  8588. #endif
  8589. /* send out pending IPI's on offline CPU */
  8590. net_rps_send_ipi(remsd);
  8591. /* Process offline CPU's input_pkt_queue */
  8592. while ((skb = __skb_dequeue(&oldsd->process_queue))) {
  8593. netif_rx_ni(skb);
  8594. input_queue_head_incr(oldsd);
  8595. }
  8596. while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
  8597. netif_rx_ni(skb);
  8598. input_queue_head_incr(oldsd);
  8599. }
  8600. return 0;
  8601. }
  8602. /**
  8603. * netdev_increment_features - increment feature set by one
  8604. * @all: current feature set
  8605. * @one: new feature set
  8606. * @mask: mask feature set
  8607. *
  8608. * Computes a new feature set after adding a device with feature set
  8609. * @one to the master device with current feature set @all. Will not
  8610. * enable anything that is off in @mask. Returns the new feature set.
  8611. */
  8612. netdev_features_t netdev_increment_features(netdev_features_t all,
  8613. netdev_features_t one, netdev_features_t mask)
  8614. {
  8615. if (mask & NETIF_F_HW_CSUM)
  8616. mask |= NETIF_F_CSUM_MASK;
  8617. mask |= NETIF_F_VLAN_CHALLENGED;
  8618. all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
  8619. all &= one | ~NETIF_F_ALL_FOR_ALL;
  8620. /* If one device supports hw checksumming, set for all. */
  8621. if (all & NETIF_F_HW_CSUM)
  8622. all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
  8623. return all;
  8624. }
  8625. EXPORT_SYMBOL(netdev_increment_features);
  8626. static struct hlist_head * __net_init netdev_create_hash(void)
  8627. {
  8628. int i;
  8629. struct hlist_head *hash;
  8630. hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
  8631. if (hash != NULL)
  8632. for (i = 0; i < NETDEV_HASHENTRIES; i++)
  8633. INIT_HLIST_HEAD(&hash[i]);
  8634. return hash;
  8635. }
  8636. /* Initialize per network namespace state */
  8637. static int __net_init netdev_init(struct net *net)
  8638. {
  8639. BUILD_BUG_ON(GRO_HASH_BUCKETS >
  8640. 8 * sizeof_field(struct napi_struct, gro_bitmask));
  8641. if (net != &init_net)
  8642. INIT_LIST_HEAD(&net->dev_base_head);
  8643. net->dev_name_head = netdev_create_hash();
  8644. if (net->dev_name_head == NULL)
  8645. goto err_name;
  8646. net->dev_index_head = netdev_create_hash();
  8647. if (net->dev_index_head == NULL)
  8648. goto err_idx;
  8649. RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
  8650. return 0;
  8651. err_idx:
  8652. kfree(net->dev_name_head);
  8653. err_name:
  8654. return -ENOMEM;
  8655. }
  8656. /**
  8657. * netdev_drivername - network driver for the device
  8658. * @dev: network device
  8659. *
  8660. * Determine network driver for device.
  8661. */
  8662. const char *netdev_drivername(const struct net_device *dev)
  8663. {
  8664. const struct device_driver *driver;
  8665. const struct device *parent;
  8666. const char *empty = "";
  8667. parent = dev->dev.parent;
  8668. if (!parent)
  8669. return empty;
  8670. driver = parent->driver;
  8671. if (driver && driver->name)
  8672. return driver->name;
  8673. return empty;
  8674. }
  8675. static void __netdev_printk(const char *level, const struct net_device *dev,
  8676. struct va_format *vaf)
  8677. {
  8678. if (dev && dev->dev.parent) {
  8679. dev_printk_emit(level[1] - '0',
  8680. dev->dev.parent,
  8681. "%s %s %s%s: %pV",
  8682. dev_driver_string(dev->dev.parent),
  8683. dev_name(dev->dev.parent),
  8684. netdev_name(dev), netdev_reg_state(dev),
  8685. vaf);
  8686. } else if (dev) {
  8687. printk("%s%s%s: %pV",
  8688. level, netdev_name(dev), netdev_reg_state(dev), vaf);
  8689. } else {
  8690. printk("%s(NULL net_device): %pV", level, vaf);
  8691. }
  8692. }
  8693. void netdev_printk(const char *level, const struct net_device *dev,
  8694. const char *format, ...)
  8695. {
  8696. struct va_format vaf;
  8697. va_list args;
  8698. va_start(args, format);
  8699. vaf.fmt = format;
  8700. vaf.va = &args;
  8701. __netdev_printk(level, dev, &vaf);
  8702. va_end(args);
  8703. }
  8704. EXPORT_SYMBOL(netdev_printk);
  8705. #define define_netdev_printk_level(func, level) \
  8706. void func(const struct net_device *dev, const char *fmt, ...) \
  8707. { \
  8708. struct va_format vaf; \
  8709. va_list args; \
  8710. \
  8711. va_start(args, fmt); \
  8712. \
  8713. vaf.fmt = fmt; \
  8714. vaf.va = &args; \
  8715. \
  8716. __netdev_printk(level, dev, &vaf); \
  8717. \
  8718. va_end(args); \
  8719. } \
  8720. EXPORT_SYMBOL(func);
  8721. define_netdev_printk_level(netdev_emerg, KERN_EMERG);
  8722. define_netdev_printk_level(netdev_alert, KERN_ALERT);
  8723. define_netdev_printk_level(netdev_crit, KERN_CRIT);
  8724. define_netdev_printk_level(netdev_err, KERN_ERR);
  8725. define_netdev_printk_level(netdev_warn, KERN_WARNING);
  8726. define_netdev_printk_level(netdev_notice, KERN_NOTICE);
  8727. define_netdev_printk_level(netdev_info, KERN_INFO);
  8728. static void __net_exit netdev_exit(struct net *net)
  8729. {
  8730. kfree(net->dev_name_head);
  8731. kfree(net->dev_index_head);
  8732. if (net != &init_net)
  8733. WARN_ON_ONCE(!list_empty(&net->dev_base_head));
  8734. }
  8735. static struct pernet_operations __net_initdata netdev_net_ops = {
  8736. .init = netdev_init,
  8737. .exit = netdev_exit,
  8738. };
  8739. static void __net_exit default_device_exit(struct net *net)
  8740. {
  8741. struct net_device *dev, *aux;
  8742. /*
  8743. * Push all migratable network devices back to the
  8744. * initial network namespace
  8745. */
  8746. rtnl_lock();
  8747. for_each_netdev_safe(net, dev, aux) {
  8748. int err;
  8749. char fb_name[IFNAMSIZ];
  8750. /* Ignore unmoveable devices (i.e. loopback) */
  8751. if (dev->features & NETIF_F_NETNS_LOCAL)
  8752. continue;
  8753. /* Leave virtual devices for the generic cleanup */
  8754. if (dev->rtnl_link_ops)
  8755. continue;
  8756. /* Push remaining network devices to init_net */
  8757. snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
  8758. if (__dev_get_by_name(&init_net, fb_name))
  8759. snprintf(fb_name, IFNAMSIZ, "dev%%d");
  8760. err = dev_change_net_namespace(dev, &init_net, fb_name);
  8761. if (err) {
  8762. pr_emerg("%s: failed to move %s to init_net: %d\n",
  8763. __func__, dev->name, err);
  8764. BUG();
  8765. }
  8766. }
  8767. rtnl_unlock();
  8768. }
  8769. static void __net_exit rtnl_lock_unregistering(struct list_head *net_list)
  8770. {
  8771. /* Return with the rtnl_lock held when there are no network
  8772. * devices unregistering in any network namespace in net_list.
  8773. */
  8774. struct net *net;
  8775. bool unregistering;
  8776. DEFINE_WAIT_FUNC(wait, woken_wake_function);
  8777. add_wait_queue(&netdev_unregistering_wq, &wait);
  8778. for (;;) {
  8779. unregistering = false;
  8780. rtnl_lock();
  8781. list_for_each_entry(net, net_list, exit_list) {
  8782. if (net->dev_unreg_count > 0) {
  8783. unregistering = true;
  8784. break;
  8785. }
  8786. }
  8787. if (!unregistering)
  8788. break;
  8789. __rtnl_unlock();
  8790. wait_woken(&wait, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
  8791. }
  8792. remove_wait_queue(&netdev_unregistering_wq, &wait);
  8793. }
  8794. static void __net_exit default_device_exit_batch(struct list_head *net_list)
  8795. {
  8796. /* At exit all network devices most be removed from a network
  8797. * namespace. Do this in the reverse order of registration.
  8798. * Do this across as many network namespaces as possible to
  8799. * improve batching efficiency.
  8800. */
  8801. struct net_device *dev;
  8802. struct net *net;
  8803. LIST_HEAD(dev_kill_list);
  8804. /* To prevent network device cleanup code from dereferencing
  8805. * loopback devices or network devices that have been freed
  8806. * wait here for all pending unregistrations to complete,
  8807. * before unregistring the loopback device and allowing the
  8808. * network namespace be freed.
  8809. *
  8810. * The netdev todo list containing all network devices
  8811. * unregistrations that happen in default_device_exit_batch
  8812. * will run in the rtnl_unlock() at the end of
  8813. * default_device_exit_batch.
  8814. */
  8815. rtnl_lock_unregistering(net_list);
  8816. list_for_each_entry(net, net_list, exit_list) {
  8817. for_each_netdev_reverse(net, dev) {
  8818. if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
  8819. dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
  8820. else
  8821. unregister_netdevice_queue(dev, &dev_kill_list);
  8822. }
  8823. }
  8824. unregister_netdevice_many(&dev_kill_list);
  8825. rtnl_unlock();
  8826. }
  8827. static struct pernet_operations __net_initdata default_device_ops = {
  8828. .exit = default_device_exit,
  8829. .exit_batch = default_device_exit_batch,
  8830. };
  8831. /*
  8832. * Initialize the DEV module. At boot time this walks the device list and
  8833. * unhooks any devices that fail to initialise (normally hardware not
  8834. * present) and leaves us with a valid list of present and active devices.
  8835. *
  8836. */
  8837. /*
  8838. * This is called single threaded during boot, so no need
  8839. * to take the rtnl semaphore.
  8840. */
  8841. static int __init net_dev_init(void)
  8842. {
  8843. int i, rc = -ENOMEM;
  8844. BUG_ON(!dev_boot_phase);
  8845. if (dev_proc_init())
  8846. goto out;
  8847. if (netdev_kobject_init())
  8848. goto out;
  8849. INIT_LIST_HEAD(&ptype_all);
  8850. for (i = 0; i < PTYPE_HASH_SIZE; i++)
  8851. INIT_LIST_HEAD(&ptype_base[i]);
  8852. INIT_LIST_HEAD(&offload_base);
  8853. if (register_pernet_subsys(&netdev_net_ops))
  8854. goto out;
  8855. /*
  8856. * Initialise the packet receive queues.
  8857. */
  8858. for_each_possible_cpu(i) {
  8859. struct work_struct *flush = per_cpu_ptr(&flush_works, i);
  8860. struct softnet_data *sd = &per_cpu(softnet_data, i);
  8861. INIT_WORK(flush, flush_backlog);
  8862. skb_queue_head_init(&sd->input_pkt_queue);
  8863. skb_queue_head_init(&sd->process_queue);
  8864. #ifdef CONFIG_XFRM_OFFLOAD
  8865. skb_queue_head_init(&sd->xfrm_backlog);
  8866. #endif
  8867. INIT_LIST_HEAD(&sd->poll_list);
  8868. sd->output_queue_tailp = &sd->output_queue;
  8869. #ifdef CONFIG_RPS
  8870. sd->csd.func = rps_trigger_softirq;
  8871. sd->csd.info = sd;
  8872. sd->cpu = i;
  8873. #endif
  8874. init_gro_hash(&sd->backlog);
  8875. sd->backlog.poll = process_backlog;
  8876. sd->backlog.weight = weight_p;
  8877. }
  8878. dev_boot_phase = 0;
  8879. /* The loopback device is special if any other network devices
  8880. * is present in a network namespace the loopback device must
  8881. * be present. Since we now dynamically allocate and free the
  8882. * loopback device ensure this invariant is maintained by
  8883. * keeping the loopback device as the first device on the
  8884. * list of network devices. Ensuring the loopback devices
  8885. * is the first device that appears and the last network device
  8886. * that disappears.
  8887. */
  8888. if (register_pernet_device(&loopback_net_ops))
  8889. goto out;
  8890. if (register_pernet_device(&default_device_ops))
  8891. goto out;
  8892. open_softirq(NET_TX_SOFTIRQ, net_tx_action);
  8893. open_softirq(NET_RX_SOFTIRQ, net_rx_action);
  8894. rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
  8895. NULL, dev_cpu_dead);
  8896. WARN_ON(rc < 0);
  8897. rc = 0;
  8898. out:
  8899. return rc;
  8900. }
  8901. subsys_initcall(net_dev_init);