android_kernel_xiaomi_sm8450/net/ipv4/inet_connection_sock.c
Greg Kroah-Hartman 9100d24dfd This is the 5.10.215 stable release
-----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCAAdFiEEZH8oZUiU471FcZm+ONu9yGCSaT4FAmYaZdgACgkQONu9yGCS
 aT4oMxAA0pATFAq8RN5f9CmYlMg5HqHgzZ8lJv8P0/reOINhUa+F5sJb1n+x+Ch4
 WQbmiFeZRzfsKZ2qKhIdNR0Lg+9JOr/DtYXdSBZ6InfSWrTAIrQ9fjl5Warkmcgg
 O4WbgF5BVgU3vGFATgxLvnUZwhR1D7WK93oMDunzrT7+OqyncU3f1Uj53ZAu9030
 z18UNqnTxDLYH/CMGwAeRkaZqBev9gZ1HdgQWA27SVLqWQwZq0al81Cmlo+ECVmk
 5dF6V2pid4qfKGJjDDfx1NS0PVnoP68iK4By1SXyoFV9VBiSwp77nUUyDr7YsHsT
 u8GpZHr9jZvSO5/xtKv20NPLejTPCRKc06CbkwpikDRtGOocBL8em0GuVqlf8hMs
 KwDb6ZEzYhXZGPJHbJM+aRD1tq/KHw9X7TrldOszMQPr6lubBtscPbg1FCg3OlcC
 HUrtub0i275x7TH0dJeRTD8TRE9jRmF+tl7KQytEJM3JRrquFjLyhDj+/VJnZkiB
 lzj3FRf4zshzgz4+CAeqXO/8Lu8b3fGYmcW1acCmk7emjDcXUKojPj/Aig6T4l7P
 oCWDY3+w1E6eiyE8BazxY1KUa/41ld0VJnlW5JWGRaDFTJwrk0h6/rvf9qImSckw
 IGx24UezRyp6NS1op3Qm2iwHLr41pFRfKxNm9ppgH9iBPzOhe38=
 =pkLL
 -----END PGP SIGNATURE-----

Merge 5.10.215 into android12-5.10-lts

Changes in 5.10.215
	amdkfd: use calloc instead of kzalloc to avoid integer overflow
	Documentation/hw-vuln: Update spectre doc
	x86/cpu: Support AMD Automatic IBRS
	x86/bugs: Use sysfs_emit()
	timers: Update kernel-doc for various functions
	timers: Use del_timer_sync() even on UP
	timers: Rename del_timer_sync() to timer_delete_sync()
	wifi: brcmfmac: Fix use-after-free bug in brcmf_cfg80211_detach
	media: staging: ipu3-imgu: Set fields before media_entity_pads_init()
	clk: qcom: gcc-sdm845: Add soft dependency on rpmhpd
	smack: Set SMACK64TRANSMUTE only for dirs in smack_inode_setxattr()
	smack: Handle SMACK64TRANSMUTE in smack_inode_setsecurity()
	arm: dts: marvell: Fix maxium->maxim typo in brownstone dts
	drm/vmwgfx: stop using ttm_bo_create v2
	drm/vmwgfx: switch over to the new pin interface v2
	drm/vmwgfx/vmwgfx_cmdbuf_res: Remove unused variable 'ret'
	drm/vmwgfx: Fix some static checker warnings
	drm/vmwgfx: Fix possible null pointer derefence with invalid contexts
	serial: max310x: fix NULL pointer dereference in I2C instantiation
	media: xc4000: Fix atomicity violation in xc4000_get_frequency
	KVM: Always flush async #PF workqueue when vCPU is being destroyed
	sparc64: NMI watchdog: fix return value of __setup handler
	sparc: vDSO: fix return value of __setup handler
	crypto: qat - fix double free during reset
	crypto: qat - resolve race condition during AER recovery
	selftests/mqueue: Set timeout to 180 seconds
	ext4: correct best extent lstart adjustment logic
	block: introduce zone_write_granularity limit
	block: Clear zone limits for a non-zoned stacked queue
	bounds: support non-power-of-two CONFIG_NR_CPUS
	fat: fix uninitialized field in nostale filehandles
	ubifs: Set page uptodate in the correct place
	ubi: Check for too small LEB size in VTBL code
	ubi: correct the calculation of fastmap size
	mtd: rawnand: meson: fix scrambling mode value in command macro
	parisc: Avoid clobbering the C/B bits in the PSW with tophys and tovirt macros
	parisc: Fix ip_fast_csum
	parisc: Fix csum_ipv6_magic on 32-bit systems
	parisc: Fix csum_ipv6_magic on 64-bit systems
	parisc: Strip upper 32 bit of sum in csum_ipv6_magic for 64-bit builds
	PM: suspend: Set mem_sleep_current during kernel command line setup
	clk: qcom: gcc-ipq6018: fix terminating of frequency table arrays
	clk: qcom: gcc-ipq8074: fix terminating of frequency table arrays
	clk: qcom: mmcc-apq8084: fix terminating of frequency table arrays
	clk: qcom: mmcc-msm8974: fix terminating of frequency table arrays
	powerpc/fsl: Fix mfpmr build errors with newer binutils
	USB: serial: ftdi_sio: add support for GMC Z216C Adapter IR-USB
	USB: serial: add device ID for VeriFone adapter
	USB: serial: cp210x: add ID for MGP Instruments PDS100
	USB: serial: option: add MeiG Smart SLM320 product
	USB: serial: cp210x: add pid/vid for TDK NC0110013M and MM0110113M
	PM: sleep: wakeirq: fix wake irq warning in system suspend
	mmc: tmio: avoid concurrent runs of mmc_request_done()
	fuse: fix root lookup with nonzero generation
	fuse: don't unhash root
	usb: typec: ucsi: Clean up UCSI_CABLE_PROP macros
	printk/console: Split out code that enables default console
	serial: Lock console when calling into driver before registration
	btrfs: fix off-by-one chunk length calculation at contains_pending_extent()
	PCI: Drop pci_device_remove() test of pci_dev->driver
	PCI/PM: Drain runtime-idle callbacks before driver removal
	PCI/ERR: Cache RCEC EA Capability offset in pci_init_capabilities()
	PCI: Cache PCIe Device Capabilities register
	PCI: Work around Intel I210 ROM BAR overlap defect
	PCI/ASPM: Make Intel DG2 L1 acceptable latency unlimited
	PCI/DPC: Quirk PIO log size for certain Intel Root Ports
	PCI/DPC: Quirk PIO log size for Intel Raptor Lake Root Ports
	Revert "Revert "md/raid5: Wait for MD_SB_CHANGE_PENDING in raid5d""
	dm-raid: fix lockdep waring in "pers->hot_add_disk"
	mac802154: fix llsec key resources release in mac802154_llsec_key_del
	mm: swap: fix race between free_swap_and_cache() and swapoff()
	mmc: core: Fix switch on gp3 partition
	drm/etnaviv: Restore some id values
	hwmon: (amc6821) add of_match table
	ext4: fix corruption during on-line resize
	nvmem: meson-efuse: fix function pointer type mismatch
	slimbus: core: Remove usage of the deprecated ida_simple_xx() API
	phy: tegra: xusb: Add API to retrieve the port number of phy
	usb: gadget: tegra-xudc: Use dev_err_probe()
	usb: gadget: tegra-xudc: Fix USB3 PHY retrieval logic
	speakup: Fix 8bit characters from direct synth
	PCI/ERR: Clear AER status only when we control AER
	PCI/AER: Block runtime suspend when handling errors
	nfs: fix UAF in direct writes
	kbuild: Move -Wenum-{compare-conditional,enum-conversion} into W=1
	PCI: dwc: endpoint: Fix advertised resizable BAR size
	vfio/platform: Disable virqfds on cleanup
	ring-buffer: Fix waking up ring buffer readers
	ring-buffer: Do not set shortest_full when full target is hit
	ring-buffer: Fix resetting of shortest_full
	ring-buffer: Fix full_waiters_pending in poll
	soc: fsl: qbman: Always disable interrupts when taking cgr_lock
	soc: fsl: qbman: Add helper for sanity checking cgr ops
	soc: fsl: qbman: Add CGR update function
	soc: fsl: qbman: Use raw spinlock for cgr_lock
	s390/zcrypt: fix reference counting on zcrypt card objects
	drm/panel: do not return negative error codes from drm_panel_get_modes()
	drm/exynos: do not return negative values from .get_modes()
	drm/imx/ipuv3: do not return negative values from .get_modes()
	drm/vc4: hdmi: do not return negative values from .get_modes()
	memtest: use {READ,WRITE}_ONCE in memory scanning
	nilfs2: fix failure to detect DAT corruption in btree and direct mappings
	nilfs2: prevent kernel bug at submit_bh_wbc()
	cpufreq: dt: always allocate zeroed cpumask
	x86/CPU/AMD: Update the Zenbleed microcode revisions
	net: hns3: tracing: fix hclgevf trace event strings
	wireguard: netlink: check for dangling peer via is_dead instead of empty list
	wireguard: netlink: access device through ctx instead of peer
	ahci: asm1064: correct count of reported ports
	ahci: asm1064: asm1166: don't limit reported ports
	drm/amd/display: Return the correct HDCP error code
	drm/amd/display: Fix noise issue on HDMI AV mute
	dm snapshot: fix lockup in dm_exception_table_exit
	vxge: remove unnecessary cast in kfree()
	x86/stackprotector/32: Make the canary into a regular percpu variable
	x86/pm: Work around false positive kmemleak report in msr_build_context()
	scripts: kernel-doc: Fix syntax error due to undeclared args variable
	comedi: comedi_test: Prevent timers rescheduling during deletion
	cpufreq: brcmstb-avs-cpufreq: fix up "add check for cpufreq_cpu_get's return value"
	netfilter: nf_tables: mark set as dead when unbinding anonymous set with timeout
	netfilter: nf_tables: disallow anonymous set with timeout flag
	netfilter: nf_tables: reject constant set with timeout
	Drivers: hv: vmbus: Calculate ring buffer size for more efficient use of memory
	xfrm: Avoid clang fortify warning in copy_to_user_tmpl()
	KVM: SVM: Flush pages under kvm->lock to fix UAF in svm_register_enc_region()
	ALSA: hda/realtek - Fix headset Mic no show at resume back for Lenovo ALC897 platform
	USB: usb-storage: Prevent divide-by-0 error in isd200_ata_command
	usb: gadget: ncm: Fix handling of zero block length packets
	usb: port: Don't try to peer unused USB ports based on location
	tty: serial: fsl_lpuart: avoid idle preamble pending if CTS is enabled
	mei: me: add arrow lake point S DID
	mei: me: add arrow lake point H DID
	vt: fix unicode buffer corruption when deleting characters
	fs/aio: Check IOCB_AIO_RW before the struct aio_kiocb conversion
	tee: optee: Fix kernel panic caused by incorrect error handling
	xen/events: close evtchn after mapping cleanup
	printk: Update @console_may_schedule in console_trylock_spinning()
	btrfs: allocate btrfs_ioctl_defrag_range_args on stack
	x86/asm: Add _ASM_RIP() macro for x86-64 (%rip) suffix
	x86/bugs: Add asm helpers for executing VERW
	x86/entry_64: Add VERW just before userspace transition
	x86/entry_32: Add VERW just before userspace transition
	x86/bugs: Use ALTERNATIVE() instead of mds_user_clear static key
	KVM/VMX: Use BT+JNC, i.e. EFLAGS.CF to select VMRESUME vs. VMLAUNCH
	KVM/VMX: Move VERW closer to VMentry for MDS mitigation
	x86/mmio: Disable KVM mitigation when X86_FEATURE_CLEAR_CPU_BUF is set
	Documentation/hw-vuln: Add documentation for RFDS
	x86/rfds: Mitigate Register File Data Sampling (RFDS)
	KVM/x86: Export RFDS_NO and RFDS_CLEAR to guests
	perf/core: Fix reentry problem in perf_output_read_group()
	efivarfs: Request at most 512 bytes for variable names
	powerpc: xor_vmx: Add '-mhard-float' to CFLAGS
	serial: sc16is7xx: convert from _raw_ to _noinc_ regmap functions for FIFO
	mm/memory-failure: fix an incorrect use of tail pages
	mm/migrate: set swap entry values of THP tail pages properly.
	init: open /initrd.image with O_LARGEFILE
	wifi: mac80211: check/clear fast rx for non-4addr sta VLAN changes
	exec: Fix NOMMU linux_binprm::exec in transfer_args_to_stack()
	hexagon: vmlinux.lds.S: handle attributes section
	mmc: core: Initialize mmc_blk_ioc_data
	mmc: core: Avoid negative index with array access
	net: ll_temac: platform_get_resource replaced by wrong function
	usb: cdc-wdm: close race between read and workqueue
	ALSA: sh: aica: reorder cleanup operations to avoid UAF bugs
	scsi: core: Fix unremoved procfs host directory regression
	staging: vc04_services: changen strncpy() to strscpy_pad()
	staging: vc04_services: fix information leak in create_component()
	USB: core: Add hub_get() and hub_put() routines
	usb: dwc2: host: Fix remote wakeup from hibernation
	usb: dwc2: host: Fix hibernation flow
	usb: dwc2: host: Fix ISOC flow in DDMA mode
	usb: dwc2: gadget: LPM flow fix
	usb: udc: remove warning when queue disabled ep
	usb: typec: ucsi: Ack unsupported commands
	usb: typec: ucsi: Clear UCSI_CCI_RESET_COMPLETE before reset
	scsi: qla2xxx: Split FCE|EFT trace control
	scsi: qla2xxx: Fix command flush on cable pull
	scsi: qla2xxx: Delay I/O Abort on PCI error
	x86/cpu: Enable STIBP on AMD if Automatic IBRS is enabled
	PCI/DPC: Quirk PIO log size for Intel Ice Lake Root Ports
	scsi: lpfc: Correct size for wqe for memset()
	USB: core: Fix deadlock in usb_deauthorize_interface()
	nfc: nci: Fix uninit-value in nci_dev_up and nci_ntf_packet
	ixgbe: avoid sleeping allocation in ixgbe_ipsec_vf_add_sa()
	tcp: properly terminate timers for kernel sockets
	ACPICA: debugger: check status of acpi_evaluate_object() in acpi_db_walk_for_fields()
	bpf: Protect against int overflow for stack access size
	Octeontx2-af: fix pause frame configuration in GMP mode
	dm integrity: fix out-of-range warning
	r8169: fix issue caused by buggy BIOS on certain boards with RTL8168d
	x86/cpufeatures: Add new word for scattered features
	Bluetooth: hci_event: set the conn encrypted before conn establishes
	Bluetooth: Fix TOCTOU in HCI debugfs implementation
	netfilter: nf_tables: disallow timeout for anonymous sets
	net/rds: fix possible cp null dereference
	vfio/pci: Disable auto-enable of exclusive INTx IRQ
	vfio/pci: Lock external INTx masking ops
	vfio: Introduce interface to flush virqfd inject workqueue
	vfio/pci: Create persistent INTx handler
	vfio/platform: Create persistent IRQ handlers
	vfio/fsl-mc: Block calling interrupt handler without trigger
	io_uring: ensure '0' is returned on file registration success
	Revert "x86/mm/ident_map: Use gbpages only where full GB page should be mapped."
	mm, vmscan: prevent infinite loop for costly GFP_NOIO | __GFP_RETRY_MAYFAIL allocations
	x86/srso: Add SRSO mitigation for Hygon processors
	block: add check that partition length needs to be aligned with block size
	netfilter: nf_tables: reject new basechain after table flag update
	netfilter: nf_tables: flush pending destroy work before exit_net release
	netfilter: nf_tables: Fix potential data-race in __nft_flowtable_type_get()
	netfilter: validate user input for expected length
	vboxsf: Avoid an spurious warning if load_nls_xxx() fails
	bpf, sockmap: Prevent lock inversion deadlock in map delete elem
	net/sched: act_skbmod: prevent kernel-infoleak
	net: stmmac: fix rx queue priority assignment
	erspan: make sure erspan_base_hdr is present in skb->head
	selftests: reuseaddr_conflict: add missing new line at the end of the output
	ipv6: Fix infinite recursion in fib6_dump_done().
	udp: do not transition UDP GRO fraglist partial checksums to unnecessary
	octeontx2-pf: check negative error code in otx2_open()
	i40e: fix i40e_count_filters() to count only active/new filters
	i40e: fix vf may be used uninitialized in this function warning
	scsi: qla2xxx: Update manufacturer details
	scsi: qla2xxx: Update manufacturer detail
	Revert "usb: phy: generic: Get the vbus supply"
	udp: do not accept non-tunnel GSO skbs landing in a tunnel
	net: ravb: Always process TX descriptor ring
	arm64: dts: qcom: sc7180: Remove clock for bluetooth on Trogdor
	arm64: dts: qcom: sc7180-trogdor: mark bluetooth address as broken
	ASoC: ops: Fix wraparound for mask in snd_soc_get_volsw
	ata: sata_sx4: fix pdc20621_get_from_dimm() on 64-bit
	scsi: mylex: Fix sysfs buffer lengths
	ata: sata_mv: Fix PCI device ID table declaration compilation warning
	ALSA: hda/realtek: Update Panasonic CF-SZ6 quirk to support headset with microphone
	driver core: Introduce device_link_wait_removal()
	of: dynamic: Synchronize of_changeset_destroy() with the devlink removals
	x86/mce: Make sure to grab mce_sysfs_mutex in set_bank()
	s390/entry: align system call table on 8 bytes
	riscv: Fix spurious errors from __get/put_kernel_nofault
	x86/bugs: Fix the SRSO mitigation on Zen3/4
	x86/retpoline: Do the necessary fixup to the Zen3/4 srso return thunk for !SRSO
	mptcp: don't account accept() of non-MPC client as fallback to TCP
	x86/cpufeatures: Add CPUID_LNX_5 to track recently added Linux-defined word
	objtool: Add asm version of STACK_FRAME_NON_STANDARD
	wifi: ath9k: fix LNA selection in ath_ant_try_scan()
	VMCI: Fix memcpy() run-time warning in dg_dispatch_as_host()
	panic: Flush kernel log buffer at the end
	arm64: dts: rockchip: fix rk3328 hdmi ports node
	arm64: dts: rockchip: fix rk3399 hdmi ports node
	ionic: set adminq irq affinity
	pstore/zone: Add a null pointer check to the psz_kmsg_read
	tools/power x86_energy_perf_policy: Fix file leak in get_pkg_num()
	btrfs: handle chunk tree lookup error in btrfs_relocate_sys_chunks()
	btrfs: export: handle invalid inode or root reference in btrfs_get_parent()
	btrfs: send: handle path ref underflow in header iterate_inode_ref()
	net/smc: reduce rtnl pressure in smc_pnet_create_pnetids_list()
	Bluetooth: btintel: Fix null ptr deref in btintel_read_version
	Input: synaptics-rmi4 - fail probing if memory allocation for "phys" fails
	pinctrl: renesas: checker: Limit cfg reg enum checks to provided IDs
	sysv: don't call sb_bread() with pointers_lock held
	scsi: lpfc: Fix possible memory leak in lpfc_rcv_padisc()
	isofs: handle CDs with bad root inode but good Joliet root directory
	media: sta2x11: fix irq handler cast
	ext4: add a hint for block bitmap corrupt state in mb_groups
	ext4: forbid commit inconsistent quota data when errors=remount-ro
	drm/amd/display: Fix nanosec stat overflow
	SUNRPC: increase size of rpc_wait_queue.qlen from unsigned short to unsigned int
	Revert "ACPI: PM: Block ASUS B1400CEAE from suspend to idle by default"
	libperf evlist: Avoid out-of-bounds access
	block: prevent division by zero in blk_rq_stat_sum()
	RDMA/cm: add timeout to cm_destroy_id wait
	Input: allocate keycode for Display refresh rate toggle
	platform/x86: touchscreen_dmi: Add an extra entry for a variant of the Chuwi Vi8 tablet
	ktest: force $buildonly = 1 for 'make_warnings_file' test type
	ring-buffer: use READ_ONCE() to read cpu_buffer->commit_page in concurrent environment
	tools: iio: replace seekdir() in iio_generic_buffer
	usb: typec: tcpci: add generic tcpci fallback compatible
	usb: sl811-hcd: only defined function checkdone if QUIRK2 is defined
	fbdev: viafb: fix typo in hw_bitblt_1 and hw_bitblt_2
	drivers/nvme: Add quirks for device 126f:2262
	fbmon: prevent division by zero in fb_videomode_from_videomode()
	netfilter: nf_tables: release batch on table validation from abort path
	netfilter: nf_tables: release mutex after nft_gc_seq_end from abort path
	netfilter: nf_tables: discard table flag update with pending basechain deletion
	tty: n_gsm: require CAP_NET_ADMIN to attach N_GSM0710 ldisc
	virtio: reenable config if freezing device failed
	x86/mm/pat: fix VM_PAT handling in COW mappings
	drm/i915/gt: Reset queue_priority_hint on parking
	Bluetooth: btintel: Fixe build regression
	VMCI: Fix possible memcpy() run-time warning in vmci_datagram_invoke_guest_handler()
	kbuild: dummy-tools: adjust to stricter stackprotector check
	scsi: sd: Fix wrong zone_write_granularity value during revalidate
	x86/retpoline: Add NOENDBR annotation to the SRSO dummy return thunk
	x86/head/64: Re-enable stack protection
	Linux 5.10.215

Change-Id: I45a0a9c4a0683ff5ef97315690f1f884f666e1b5
Signed-off-by: Greg Kroah-Hartman <gregkh@google.com>
2024-06-01 11:03:55 +00:00

1155 lines
32 KiB
C

// SPDX-License-Identifier: GPL-2.0-or-later
/*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* Support for INET connection oriented protocols.
*
* Authors: See the TCP sources
*/
#include <linux/module.h>
#include <linux/jhash.h>
#include <net/inet_connection_sock.h>
#include <net/inet_hashtables.h>
#include <net/inet_timewait_sock.h>
#include <net/ip.h>
#include <net/route.h>
#include <net/tcp_states.h>
#include <net/xfrm.h>
#include <net/tcp.h>
#include <net/sock_reuseport.h>
#include <net/addrconf.h>
#if IS_ENABLED(CONFIG_IPV6)
/* match_sk*_wildcard == true: IPV6_ADDR_ANY equals to any IPv6 addresses
* if IPv6 only, and any IPv4 addresses
* if not IPv6 only
* match_sk*_wildcard == false: addresses must be exactly the same, i.e.
* IPV6_ADDR_ANY only equals to IPV6_ADDR_ANY,
* and 0.0.0.0 equals to 0.0.0.0 only
*/
static bool ipv6_rcv_saddr_equal(const struct in6_addr *sk1_rcv_saddr6,
const struct in6_addr *sk2_rcv_saddr6,
__be32 sk1_rcv_saddr, __be32 sk2_rcv_saddr,
bool sk1_ipv6only, bool sk2_ipv6only,
bool match_sk1_wildcard,
bool match_sk2_wildcard)
{
int addr_type = ipv6_addr_type(sk1_rcv_saddr6);
int addr_type2 = sk2_rcv_saddr6 ? ipv6_addr_type(sk2_rcv_saddr6) : IPV6_ADDR_MAPPED;
/* if both are mapped, treat as IPv4 */
if (addr_type == IPV6_ADDR_MAPPED && addr_type2 == IPV6_ADDR_MAPPED) {
if (!sk2_ipv6only) {
if (sk1_rcv_saddr == sk2_rcv_saddr)
return true;
return (match_sk1_wildcard && !sk1_rcv_saddr) ||
(match_sk2_wildcard && !sk2_rcv_saddr);
}
return false;
}
if (addr_type == IPV6_ADDR_ANY && addr_type2 == IPV6_ADDR_ANY)
return true;
if (addr_type2 == IPV6_ADDR_ANY && match_sk2_wildcard &&
!(sk2_ipv6only && addr_type == IPV6_ADDR_MAPPED))
return true;
if (addr_type == IPV6_ADDR_ANY && match_sk1_wildcard &&
!(sk1_ipv6only && addr_type2 == IPV6_ADDR_MAPPED))
return true;
if (sk2_rcv_saddr6 &&
ipv6_addr_equal(sk1_rcv_saddr6, sk2_rcv_saddr6))
return true;
return false;
}
#endif
/* match_sk*_wildcard == true: 0.0.0.0 equals to any IPv4 addresses
* match_sk*_wildcard == false: addresses must be exactly the same, i.e.
* 0.0.0.0 only equals to 0.0.0.0
*/
static bool ipv4_rcv_saddr_equal(__be32 sk1_rcv_saddr, __be32 sk2_rcv_saddr,
bool sk2_ipv6only, bool match_sk1_wildcard,
bool match_sk2_wildcard)
{
if (!sk2_ipv6only) {
if (sk1_rcv_saddr == sk2_rcv_saddr)
return true;
return (match_sk1_wildcard && !sk1_rcv_saddr) ||
(match_sk2_wildcard && !sk2_rcv_saddr);
}
return false;
}
bool inet_rcv_saddr_equal(const struct sock *sk, const struct sock *sk2,
bool match_wildcard)
{
#if IS_ENABLED(CONFIG_IPV6)
if (sk->sk_family == AF_INET6)
return ipv6_rcv_saddr_equal(&sk->sk_v6_rcv_saddr,
inet6_rcv_saddr(sk2),
sk->sk_rcv_saddr,
sk2->sk_rcv_saddr,
ipv6_only_sock(sk),
ipv6_only_sock(sk2),
match_wildcard,
match_wildcard);
#endif
return ipv4_rcv_saddr_equal(sk->sk_rcv_saddr, sk2->sk_rcv_saddr,
ipv6_only_sock(sk2), match_wildcard,
match_wildcard);
}
EXPORT_SYMBOL(inet_rcv_saddr_equal);
bool inet_rcv_saddr_any(const struct sock *sk)
{
#if IS_ENABLED(CONFIG_IPV6)
if (sk->sk_family == AF_INET6)
return ipv6_addr_any(&sk->sk_v6_rcv_saddr);
#endif
return !sk->sk_rcv_saddr;
}
void inet_get_local_port_range(struct net *net, int *low, int *high)
{
unsigned int seq;
do {
seq = read_seqbegin(&net->ipv4.ip_local_ports.lock);
*low = net->ipv4.ip_local_ports.range[0];
*high = net->ipv4.ip_local_ports.range[1];
} while (read_seqretry(&net->ipv4.ip_local_ports.lock, seq));
}
EXPORT_SYMBOL(inet_get_local_port_range);
static int inet_csk_bind_conflict(const struct sock *sk,
const struct inet_bind_bucket *tb,
bool relax, bool reuseport_ok)
{
struct sock *sk2;
bool reuse = sk->sk_reuse;
bool reuseport = !!sk->sk_reuseport;
kuid_t uid = sock_i_uid((struct sock *)sk);
/*
* Unlike other sk lookup places we do not check
* for sk_net here, since _all_ the socks listed
* in tb->owners list belong to the same net - the
* one this bucket belongs to.
*/
sk_for_each_bound(sk2, &tb->owners) {
int bound_dev_if2;
if (sk == sk2)
continue;
bound_dev_if2 = READ_ONCE(sk2->sk_bound_dev_if);
if ((!sk->sk_bound_dev_if ||
!bound_dev_if2 ||
sk->sk_bound_dev_if == bound_dev_if2)) {
if (reuse && sk2->sk_reuse &&
sk2->sk_state != TCP_LISTEN) {
if ((!relax ||
(!reuseport_ok &&
reuseport && sk2->sk_reuseport &&
!rcu_access_pointer(sk->sk_reuseport_cb) &&
(sk2->sk_state == TCP_TIME_WAIT ||
uid_eq(uid, sock_i_uid(sk2))))) &&
inet_rcv_saddr_equal(sk, sk2, true))
break;
} else if (!reuseport_ok ||
!reuseport || !sk2->sk_reuseport ||
rcu_access_pointer(sk->sk_reuseport_cb) ||
(sk2->sk_state != TCP_TIME_WAIT &&
!uid_eq(uid, sock_i_uid(sk2)))) {
if (inet_rcv_saddr_equal(sk, sk2, true))
break;
}
}
}
return sk2 != NULL;
}
/*
* Find an open port number for the socket. Returns with the
* inet_bind_hashbucket lock held.
*/
static struct inet_bind_hashbucket *
inet_csk_find_open_port(struct sock *sk, struct inet_bind_bucket **tb_ret, int *port_ret)
{
struct inet_hashinfo *hinfo = sk->sk_prot->h.hashinfo;
int port = 0;
struct inet_bind_hashbucket *head;
struct net *net = sock_net(sk);
bool relax = false;
int i, low, high, attempt_half;
struct inet_bind_bucket *tb;
u32 remaining, offset;
int l3mdev;
l3mdev = inet_sk_bound_l3mdev(sk);
ports_exhausted:
attempt_half = (sk->sk_reuse == SK_CAN_REUSE) ? 1 : 0;
other_half_scan:
inet_get_local_port_range(net, &low, &high);
high++; /* [32768, 60999] -> [32768, 61000[ */
if (high - low < 4)
attempt_half = 0;
if (attempt_half) {
int half = low + (((high - low) >> 2) << 1);
if (attempt_half == 1)
high = half;
else
low = half;
}
remaining = high - low;
if (likely(remaining > 1))
remaining &= ~1U;
offset = prandom_u32() % remaining;
/* __inet_hash_connect() favors ports having @low parity
* We do the opposite to not pollute connect() users.
*/
offset |= 1U;
other_parity_scan:
port = low + offset;
for (i = 0; i < remaining; i += 2, port += 2) {
if (unlikely(port >= high))
port -= remaining;
if (inet_is_local_reserved_port(net, port))
continue;
head = &hinfo->bhash[inet_bhashfn(net, port,
hinfo->bhash_size)];
spin_lock_bh(&head->lock);
inet_bind_bucket_for_each(tb, &head->chain)
if (net_eq(ib_net(tb), net) && tb->l3mdev == l3mdev &&
tb->port == port) {
if (!inet_csk_bind_conflict(sk, tb, relax, false))
goto success;
goto next_port;
}
tb = NULL;
goto success;
next_port:
spin_unlock_bh(&head->lock);
cond_resched();
}
offset--;
if (!(offset & 1))
goto other_parity_scan;
if (attempt_half == 1) {
/* OK we now try the upper half of the range */
attempt_half = 2;
goto other_half_scan;
}
if (READ_ONCE(net->ipv4.sysctl_ip_autobind_reuse) && !relax) {
/* We still have a chance to connect to different destinations */
relax = true;
goto ports_exhausted;
}
return NULL;
success:
*port_ret = port;
*tb_ret = tb;
return head;
}
static inline int sk_reuseport_match(struct inet_bind_bucket *tb,
struct sock *sk)
{
kuid_t uid = sock_i_uid(sk);
if (tb->fastreuseport <= 0)
return 0;
if (!sk->sk_reuseport)
return 0;
if (rcu_access_pointer(sk->sk_reuseport_cb))
return 0;
if (!uid_eq(tb->fastuid, uid))
return 0;
/* We only need to check the rcv_saddr if this tb was once marked
* without fastreuseport and then was reset, as we can only know that
* the fast_*rcv_saddr doesn't have any conflicts with the socks on the
* owners list.
*/
if (tb->fastreuseport == FASTREUSEPORT_ANY)
return 1;
#if IS_ENABLED(CONFIG_IPV6)
if (tb->fast_sk_family == AF_INET6)
return ipv6_rcv_saddr_equal(&tb->fast_v6_rcv_saddr,
inet6_rcv_saddr(sk),
tb->fast_rcv_saddr,
sk->sk_rcv_saddr,
tb->fast_ipv6_only,
ipv6_only_sock(sk), true, false);
#endif
return ipv4_rcv_saddr_equal(tb->fast_rcv_saddr, sk->sk_rcv_saddr,
ipv6_only_sock(sk), true, false);
}
void inet_csk_update_fastreuse(struct inet_bind_bucket *tb,
struct sock *sk)
{
kuid_t uid = sock_i_uid(sk);
bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN;
if (hlist_empty(&tb->owners)) {
tb->fastreuse = reuse;
if (sk->sk_reuseport) {
tb->fastreuseport = FASTREUSEPORT_ANY;
tb->fastuid = uid;
tb->fast_rcv_saddr = sk->sk_rcv_saddr;
tb->fast_ipv6_only = ipv6_only_sock(sk);
tb->fast_sk_family = sk->sk_family;
#if IS_ENABLED(CONFIG_IPV6)
tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
#endif
} else {
tb->fastreuseport = 0;
}
} else {
if (!reuse)
tb->fastreuse = 0;
if (sk->sk_reuseport) {
/* We didn't match or we don't have fastreuseport set on
* the tb, but we have sk_reuseport set on this socket
* and we know that there are no bind conflicts with
* this socket in this tb, so reset our tb's reuseport
* settings so that any subsequent sockets that match
* our current socket will be put on the fast path.
*
* If we reset we need to set FASTREUSEPORT_STRICT so we
* do extra checking for all subsequent sk_reuseport
* socks.
*/
if (!sk_reuseport_match(tb, sk)) {
tb->fastreuseport = FASTREUSEPORT_STRICT;
tb->fastuid = uid;
tb->fast_rcv_saddr = sk->sk_rcv_saddr;
tb->fast_ipv6_only = ipv6_only_sock(sk);
tb->fast_sk_family = sk->sk_family;
#if IS_ENABLED(CONFIG_IPV6)
tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
#endif
}
} else {
tb->fastreuseport = 0;
}
}
}
/* Obtain a reference to a local port for the given sock,
* if snum is zero it means select any available local port.
* We try to allocate an odd port (and leave even ports for connect())
*/
int inet_csk_get_port(struct sock *sk, unsigned short snum)
{
bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN;
struct inet_hashinfo *hinfo = sk->sk_prot->h.hashinfo;
int ret = 1, port = snum;
struct inet_bind_hashbucket *head;
struct net *net = sock_net(sk);
struct inet_bind_bucket *tb = NULL;
int l3mdev;
l3mdev = inet_sk_bound_l3mdev(sk);
if (!port) {
head = inet_csk_find_open_port(sk, &tb, &port);
if (!head)
return ret;
if (!tb)
goto tb_not_found;
goto success;
}
head = &hinfo->bhash[inet_bhashfn(net, port,
hinfo->bhash_size)];
spin_lock_bh(&head->lock);
inet_bind_bucket_for_each(tb, &head->chain)
if (net_eq(ib_net(tb), net) && tb->l3mdev == l3mdev &&
tb->port == port)
goto tb_found;
tb_not_found:
tb = inet_bind_bucket_create(hinfo->bind_bucket_cachep,
net, head, port, l3mdev);
if (!tb)
goto fail_unlock;
tb_found:
if (!hlist_empty(&tb->owners)) {
if (sk->sk_reuse == SK_FORCE_REUSE)
goto success;
if ((tb->fastreuse > 0 && reuse) ||
sk_reuseport_match(tb, sk))
goto success;
if (inet_csk_bind_conflict(sk, tb, true, true))
goto fail_unlock;
}
success:
inet_csk_update_fastreuse(tb, sk);
if (!inet_csk(sk)->icsk_bind_hash)
inet_bind_hash(sk, tb, port);
WARN_ON(inet_csk(sk)->icsk_bind_hash != tb);
ret = 0;
fail_unlock:
spin_unlock_bh(&head->lock);
return ret;
}
EXPORT_SYMBOL_GPL(inet_csk_get_port);
/*
* Wait for an incoming connection, avoid race conditions. This must be called
* with the socket locked.
*/
static int inet_csk_wait_for_connect(struct sock *sk, long timeo)
{
struct inet_connection_sock *icsk = inet_csk(sk);
DEFINE_WAIT(wait);
int err;
/*
* True wake-one mechanism for incoming connections: only
* one process gets woken up, not the 'whole herd'.
* Since we do not 'race & poll' for established sockets
* anymore, the common case will execute the loop only once.
*
* Subtle issue: "add_wait_queue_exclusive()" will be added
* after any current non-exclusive waiters, and we know that
* it will always _stay_ after any new non-exclusive waiters
* because all non-exclusive waiters are added at the
* beginning of the wait-queue. As such, it's ok to "drop"
* our exclusiveness temporarily when we get woken up without
* having to remove and re-insert us on the wait queue.
*/
for (;;) {
prepare_to_wait_exclusive(sk_sleep(sk), &wait,
TASK_INTERRUPTIBLE);
release_sock(sk);
if (reqsk_queue_empty(&icsk->icsk_accept_queue))
timeo = schedule_timeout(timeo);
sched_annotate_sleep();
lock_sock(sk);
err = 0;
if (!reqsk_queue_empty(&icsk->icsk_accept_queue))
break;
err = -EINVAL;
if (sk->sk_state != TCP_LISTEN)
break;
err = sock_intr_errno(timeo);
if (signal_pending(current))
break;
err = -EAGAIN;
if (!timeo)
break;
}
finish_wait(sk_sleep(sk), &wait);
return err;
}
/*
* This will accept the next outstanding connection.
*/
struct sock *inet_csk_accept(struct sock *sk, int flags, int *err, bool kern)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct request_sock_queue *queue = &icsk->icsk_accept_queue;
struct request_sock *req;
struct sock *newsk;
int error;
lock_sock(sk);
/* We need to make sure that this socket is listening,
* and that it has something pending.
*/
error = -EINVAL;
if (sk->sk_state != TCP_LISTEN)
goto out_err;
/* Find already established connection */
if (reqsk_queue_empty(queue)) {
long timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
/* If this is a non blocking socket don't sleep */
error = -EAGAIN;
if (!timeo)
goto out_err;
error = inet_csk_wait_for_connect(sk, timeo);
if (error)
goto out_err;
}
req = reqsk_queue_remove(queue, sk);
newsk = req->sk;
if (sk->sk_protocol == IPPROTO_TCP &&
tcp_rsk(req)->tfo_listener) {
spin_lock_bh(&queue->fastopenq.lock);
if (tcp_rsk(req)->tfo_listener) {
/* We are still waiting for the final ACK from 3WHS
* so can't free req now. Instead, we set req->sk to
* NULL to signify that the child socket is taken
* so reqsk_fastopen_remove() will free the req
* when 3WHS finishes (or is aborted).
*/
req->sk = NULL;
req = NULL;
}
spin_unlock_bh(&queue->fastopenq.lock);
}
out:
release_sock(sk);
if (newsk && mem_cgroup_sockets_enabled) {
int amt;
/* atomically get the memory usage, set and charge the
* newsk->sk_memcg.
*/
lock_sock(newsk);
/* The socket has not been accepted yet, no need to look at
* newsk->sk_wmem_queued.
*/
amt = sk_mem_pages(newsk->sk_forward_alloc +
atomic_read(&newsk->sk_rmem_alloc));
mem_cgroup_sk_alloc(newsk);
if (newsk->sk_memcg && amt)
mem_cgroup_charge_skmem(newsk->sk_memcg, amt);
release_sock(newsk);
}
if (req)
reqsk_put(req);
if (newsk)
inet_init_csk_locks(newsk);
return newsk;
out_err:
newsk = NULL;
req = NULL;
*err = error;
goto out;
}
EXPORT_SYMBOL(inet_csk_accept);
/*
* Using different timers for retransmit, delayed acks and probes
* We may wish use just one timer maintaining a list of expire jiffies
* to optimize.
*/
void inet_csk_init_xmit_timers(struct sock *sk,
void (*retransmit_handler)(struct timer_list *t),
void (*delack_handler)(struct timer_list *t),
void (*keepalive_handler)(struct timer_list *t))
{
struct inet_connection_sock *icsk = inet_csk(sk);
timer_setup(&icsk->icsk_retransmit_timer, retransmit_handler, 0);
timer_setup(&icsk->icsk_delack_timer, delack_handler, 0);
timer_setup(&sk->sk_timer, keepalive_handler, 0);
icsk->icsk_pending = icsk->icsk_ack.pending = 0;
}
EXPORT_SYMBOL(inet_csk_init_xmit_timers);
void inet_csk_clear_xmit_timers(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
icsk->icsk_pending = icsk->icsk_ack.pending = 0;
sk_stop_timer(sk, &icsk->icsk_retransmit_timer);
sk_stop_timer(sk, &icsk->icsk_delack_timer);
sk_stop_timer(sk, &sk->sk_timer);
}
EXPORT_SYMBOL(inet_csk_clear_xmit_timers);
void inet_csk_clear_xmit_timers_sync(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
/* ongoing timer handlers need to acquire socket lock. */
sock_not_owned_by_me(sk);
icsk->icsk_pending = icsk->icsk_ack.pending = 0;
sk_stop_timer_sync(sk, &icsk->icsk_retransmit_timer);
sk_stop_timer_sync(sk, &icsk->icsk_delack_timer);
sk_stop_timer_sync(sk, &sk->sk_timer);
}
void inet_csk_delete_keepalive_timer(struct sock *sk)
{
sk_stop_timer(sk, &sk->sk_timer);
}
EXPORT_SYMBOL(inet_csk_delete_keepalive_timer);
void inet_csk_reset_keepalive_timer(struct sock *sk, unsigned long len)
{
sk_reset_timer(sk, &sk->sk_timer, jiffies + len);
}
EXPORT_SYMBOL(inet_csk_reset_keepalive_timer);
struct dst_entry *inet_csk_route_req(const struct sock *sk,
struct flowi4 *fl4,
const struct request_sock *req)
{
const struct inet_request_sock *ireq = inet_rsk(req);
struct net *net = read_pnet(&ireq->ireq_net);
struct ip_options_rcu *opt;
struct rtable *rt;
rcu_read_lock();
opt = rcu_dereference(ireq->ireq_opt);
flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
sk->sk_protocol, inet_sk_flowi_flags(sk),
(opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
ireq->ir_loc_addr, ireq->ir_rmt_port,
htons(ireq->ir_num), sk->sk_uid);
security_req_classify_flow(req, flowi4_to_flowi_common(fl4));
rt = ip_route_output_flow(net, fl4, sk);
if (IS_ERR(rt))
goto no_route;
if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
goto route_err;
rcu_read_unlock();
return &rt->dst;
route_err:
ip_rt_put(rt);
no_route:
rcu_read_unlock();
__IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
return NULL;
}
EXPORT_SYMBOL_GPL(inet_csk_route_req);
struct dst_entry *inet_csk_route_child_sock(const struct sock *sk,
struct sock *newsk,
const struct request_sock *req)
{
const struct inet_request_sock *ireq = inet_rsk(req);
struct net *net = read_pnet(&ireq->ireq_net);
struct inet_sock *newinet = inet_sk(newsk);
struct ip_options_rcu *opt;
struct flowi4 *fl4;
struct rtable *rt;
opt = rcu_dereference(ireq->ireq_opt);
fl4 = &newinet->cork.fl.u.ip4;
flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
sk->sk_protocol, inet_sk_flowi_flags(sk),
(opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
ireq->ir_loc_addr, ireq->ir_rmt_port,
htons(ireq->ir_num), sk->sk_uid);
security_req_classify_flow(req, flowi4_to_flowi_common(fl4));
rt = ip_route_output_flow(net, fl4, sk);
if (IS_ERR(rt))
goto no_route;
if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
goto route_err;
return &rt->dst;
route_err:
ip_rt_put(rt);
no_route:
__IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
return NULL;
}
EXPORT_SYMBOL_GPL(inet_csk_route_child_sock);
/* Decide when to expire the request and when to resend SYN-ACK */
static void syn_ack_recalc(struct request_sock *req,
const int max_syn_ack_retries,
const u8 rskq_defer_accept,
int *expire, int *resend)
{
if (!rskq_defer_accept) {
*expire = req->num_timeout >= max_syn_ack_retries;
*resend = 1;
return;
}
*expire = req->num_timeout >= max_syn_ack_retries &&
(!inet_rsk(req)->acked || req->num_timeout >= rskq_defer_accept);
/* Do not resend while waiting for data after ACK,
* start to resend on end of deferring period to give
* last chance for data or ACK to create established socket.
*/
*resend = !inet_rsk(req)->acked ||
req->num_timeout >= rskq_defer_accept - 1;
}
int inet_rtx_syn_ack(const struct sock *parent, struct request_sock *req)
{
int err = req->rsk_ops->rtx_syn_ack(parent, req);
if (!err)
req->num_retrans++;
return err;
}
EXPORT_SYMBOL(inet_rtx_syn_ack);
/* return true if req was found in the ehash table */
static bool reqsk_queue_unlink(struct request_sock *req)
{
struct inet_hashinfo *hashinfo = req_to_sk(req)->sk_prot->h.hashinfo;
bool found = false;
if (sk_hashed(req_to_sk(req))) {
spinlock_t *lock = inet_ehash_lockp(hashinfo, req->rsk_hash);
spin_lock(lock);
found = __sk_nulls_del_node_init_rcu(req_to_sk(req));
spin_unlock(lock);
}
if (timer_pending(&req->rsk_timer) && del_timer_sync(&req->rsk_timer))
reqsk_put(req);
return found;
}
bool inet_csk_reqsk_queue_drop(struct sock *sk, struct request_sock *req)
{
bool unlinked = reqsk_queue_unlink(req);
if (unlinked) {
reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
reqsk_put(req);
}
return unlinked;
}
EXPORT_SYMBOL(inet_csk_reqsk_queue_drop);
void inet_csk_reqsk_queue_drop_and_put(struct sock *sk, struct request_sock *req)
{
inet_csk_reqsk_queue_drop(sk, req);
reqsk_put(req);
}
EXPORT_SYMBOL(inet_csk_reqsk_queue_drop_and_put);
static void reqsk_timer_handler(struct timer_list *t)
{
struct request_sock *req = from_timer(req, t, rsk_timer);
struct sock *sk_listener = req->rsk_listener;
struct net *net = sock_net(sk_listener);
struct inet_connection_sock *icsk = inet_csk(sk_listener);
struct request_sock_queue *queue = &icsk->icsk_accept_queue;
int max_syn_ack_retries, qlen, expire = 0, resend = 0;
if (inet_sk_state_load(sk_listener) != TCP_LISTEN)
goto drop;
max_syn_ack_retries = icsk->icsk_syn_retries ? : net->ipv4.sysctl_tcp_synack_retries;
/* Normally all the openreqs are young and become mature
* (i.e. converted to established socket) for first timeout.
* If synack was not acknowledged for 1 second, it means
* one of the following things: synack was lost, ack was lost,
* rtt is high or nobody planned to ack (i.e. synflood).
* When server is a bit loaded, queue is populated with old
* open requests, reducing effective size of queue.
* When server is well loaded, queue size reduces to zero
* after several minutes of work. It is not synflood,
* it is normal operation. The solution is pruning
* too old entries overriding normal timeout, when
* situation becomes dangerous.
*
* Essentially, we reserve half of room for young
* embrions; and abort old ones without pity, if old
* ones are about to clog our table.
*/
qlen = reqsk_queue_len(queue);
if ((qlen << 1) > max(8U, READ_ONCE(sk_listener->sk_max_ack_backlog))) {
int young = reqsk_queue_len_young(queue) << 1;
while (max_syn_ack_retries > 2) {
if (qlen < young)
break;
max_syn_ack_retries--;
young <<= 1;
}
}
syn_ack_recalc(req, max_syn_ack_retries, READ_ONCE(queue->rskq_defer_accept),
&expire, &resend);
req->rsk_ops->syn_ack_timeout(req);
if (!expire &&
(!resend ||
!inet_rtx_syn_ack(sk_listener, req) ||
inet_rsk(req)->acked)) {
unsigned long timeo;
if (req->num_timeout++ == 0)
atomic_dec(&queue->young);
timeo = min(TCP_TIMEOUT_INIT << req->num_timeout, TCP_RTO_MAX);
mod_timer(&req->rsk_timer, jiffies + timeo);
return;
}
drop:
inet_csk_reqsk_queue_drop_and_put(sk_listener, req);
}
static void reqsk_queue_hash_req(struct request_sock *req,
unsigned long timeout)
{
timer_setup(&req->rsk_timer, reqsk_timer_handler, TIMER_PINNED);
mod_timer(&req->rsk_timer, jiffies + timeout);
inet_ehash_insert(req_to_sk(req), NULL, NULL);
/* before letting lookups find us, make sure all req fields
* are committed to memory and refcnt initialized.
*/
smp_wmb();
refcount_set(&req->rsk_refcnt, 2 + 1);
}
void inet_csk_reqsk_queue_hash_add(struct sock *sk, struct request_sock *req,
unsigned long timeout)
{
reqsk_queue_hash_req(req, timeout);
inet_csk_reqsk_queue_added(sk);
}
EXPORT_SYMBOL_GPL(inet_csk_reqsk_queue_hash_add);
static void inet_clone_ulp(const struct request_sock *req, struct sock *newsk,
const gfp_t priority)
{
struct inet_connection_sock *icsk = inet_csk(newsk);
if (!icsk->icsk_ulp_ops)
return;
if (icsk->icsk_ulp_ops->clone)
icsk->icsk_ulp_ops->clone(req, newsk, priority);
}
/**
* inet_csk_clone_lock - clone an inet socket, and lock its clone
* @sk: the socket to clone
* @req: request_sock
* @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
*
* Caller must unlock socket even in error path (bh_unlock_sock(newsk))
*/
struct sock *inet_csk_clone_lock(const struct sock *sk,
const struct request_sock *req,
const gfp_t priority)
{
struct sock *newsk = sk_clone_lock(sk, priority);
if (newsk) {
struct inet_connection_sock *newicsk = inet_csk(newsk);
inet_sk_set_state(newsk, TCP_SYN_RECV);
newicsk->icsk_bind_hash = NULL;
inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;
inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;
inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);
/* listeners have SOCK_RCU_FREE, not the children */
sock_reset_flag(newsk, SOCK_RCU_FREE);
inet_sk(newsk)->mc_list = NULL;
newsk->sk_mark = inet_rsk(req)->ir_mark;
atomic64_set(&newsk->sk_cookie,
atomic64_read(&inet_rsk(req)->ir_cookie));
newicsk->icsk_retransmits = 0;
newicsk->icsk_backoff = 0;
newicsk->icsk_probes_out = 0;
newicsk->icsk_probes_tstamp = 0;
/* Deinitialize accept_queue to trap illegal accesses. */
memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
inet_clone_ulp(req, newsk, priority);
security_inet_csk_clone(newsk, req);
}
return newsk;
}
EXPORT_SYMBOL_GPL(inet_csk_clone_lock);
/*
* At this point, there should be no process reference to this
* socket, and thus no user references at all. Therefore we
* can assume the socket waitqueue is inactive and nobody will
* try to jump onto it.
*/
void inet_csk_destroy_sock(struct sock *sk)
{
WARN_ON(sk->sk_state != TCP_CLOSE);
WARN_ON(!sock_flag(sk, SOCK_DEAD));
/* It cannot be in hash table! */
WARN_ON(!sk_unhashed(sk));
/* If it has not 0 inet_sk(sk)->inet_num, it must be bound */
WARN_ON(inet_sk(sk)->inet_num && !inet_csk(sk)->icsk_bind_hash);
sk->sk_prot->destroy(sk);
sk_stream_kill_queues(sk);
xfrm_sk_free_policy(sk);
sk_refcnt_debug_release(sk);
percpu_counter_dec(sk->sk_prot->orphan_count);
sock_put(sk);
}
EXPORT_SYMBOL(inet_csk_destroy_sock);
/* This function allows to force a closure of a socket after the call to
* tcp/dccp_create_openreq_child().
*/
void inet_csk_prepare_forced_close(struct sock *sk)
__releases(&sk->sk_lock.slock)
{
/* sk_clone_lock locked the socket and set refcnt to 2 */
bh_unlock_sock(sk);
sock_put(sk);
inet_csk_prepare_for_destroy_sock(sk);
inet_sk(sk)->inet_num = 0;
}
EXPORT_SYMBOL(inet_csk_prepare_forced_close);
static int inet_ulp_can_listen(const struct sock *sk)
{
const struct inet_connection_sock *icsk = inet_csk(sk);
if (icsk->icsk_ulp_ops && !icsk->icsk_ulp_ops->clone)
return -EINVAL;
return 0;
}
int inet_csk_listen_start(struct sock *sk, int backlog)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct inet_sock *inet = inet_sk(sk);
int err;
err = inet_ulp_can_listen(sk);
if (unlikely(err))
return err;
reqsk_queue_alloc(&icsk->icsk_accept_queue);
sk->sk_ack_backlog = 0;
inet_csk_delack_init(sk);
/* There is race window here: we announce ourselves listening,
* but this transition is still not validated by get_port().
* It is OK, because this socket enters to hash table only
* after validation is complete.
*/
err = -EADDRINUSE;
inet_sk_state_store(sk, TCP_LISTEN);
if (!sk->sk_prot->get_port(sk, inet->inet_num)) {
inet->inet_sport = htons(inet->inet_num);
sk_dst_reset(sk);
err = sk->sk_prot->hash(sk);
if (likely(!err))
return 0;
}
inet_sk_set_state(sk, TCP_CLOSE);
return err;
}
EXPORT_SYMBOL_GPL(inet_csk_listen_start);
static void inet_child_forget(struct sock *sk, struct request_sock *req,
struct sock *child)
{
sk->sk_prot->disconnect(child, O_NONBLOCK);
sock_orphan(child);
percpu_counter_inc(sk->sk_prot->orphan_count);
if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(req)->tfo_listener) {
BUG_ON(rcu_access_pointer(tcp_sk(child)->fastopen_rsk) != req);
BUG_ON(sk != req->rsk_listener);
/* Paranoid, to prevent race condition if
* an inbound pkt destined for child is
* blocked by sock lock in tcp_v4_rcv().
* Also to satisfy an assertion in
* tcp_v4_destroy_sock().
*/
RCU_INIT_POINTER(tcp_sk(child)->fastopen_rsk, NULL);
}
inet_csk_destroy_sock(child);
}
struct sock *inet_csk_reqsk_queue_add(struct sock *sk,
struct request_sock *req,
struct sock *child)
{
struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
spin_lock(&queue->rskq_lock);
if (unlikely(sk->sk_state != TCP_LISTEN)) {
inet_child_forget(sk, req, child);
child = NULL;
} else {
req->sk = child;
req->dl_next = NULL;
if (queue->rskq_accept_head == NULL)
WRITE_ONCE(queue->rskq_accept_head, req);
else
queue->rskq_accept_tail->dl_next = req;
queue->rskq_accept_tail = req;
sk_acceptq_added(sk);
}
spin_unlock(&queue->rskq_lock);
return child;
}
EXPORT_SYMBOL(inet_csk_reqsk_queue_add);
struct sock *inet_csk_complete_hashdance(struct sock *sk, struct sock *child,
struct request_sock *req, bool own_req)
{
if (own_req) {
inet_csk_reqsk_queue_drop(sk, req);
reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
if (inet_csk_reqsk_queue_add(sk, req, child))
return child;
}
/* Too bad, another child took ownership of the request, undo. */
bh_unlock_sock(child);
sock_put(child);
return NULL;
}
EXPORT_SYMBOL(inet_csk_complete_hashdance);
/*
* This routine closes sockets which have been at least partially
* opened, but not yet accepted.
*/
void inet_csk_listen_stop(struct sock *sk)
{
struct inet_connection_sock *icsk = inet_csk(sk);
struct request_sock_queue *queue = &icsk->icsk_accept_queue;
struct request_sock *next, *req;
/* Following specs, it would be better either to send FIN
* (and enter FIN-WAIT-1, it is normal close)
* or to send active reset (abort).
* Certainly, it is pretty dangerous while synflood, but it is
* bad justification for our negligence 8)
* To be honest, we are not able to make either
* of the variants now. --ANK
*/
while ((req = reqsk_queue_remove(queue, sk)) != NULL) {
struct sock *child = req->sk;
local_bh_disable();
bh_lock_sock(child);
WARN_ON(sock_owned_by_user(child));
sock_hold(child);
inet_child_forget(sk, req, child);
reqsk_put(req);
bh_unlock_sock(child);
local_bh_enable();
sock_put(child);
cond_resched();
}
if (queue->fastopenq.rskq_rst_head) {
/* Free all the reqs queued in rskq_rst_head. */
spin_lock_bh(&queue->fastopenq.lock);
req = queue->fastopenq.rskq_rst_head;
queue->fastopenq.rskq_rst_head = NULL;
spin_unlock_bh(&queue->fastopenq.lock);
while (req != NULL) {
next = req->dl_next;
reqsk_put(req);
req = next;
}
}
WARN_ON_ONCE(sk->sk_ack_backlog);
}
EXPORT_SYMBOL_GPL(inet_csk_listen_stop);
void inet_csk_addr2sockaddr(struct sock *sk, struct sockaddr *uaddr)
{
struct sockaddr_in *sin = (struct sockaddr_in *)uaddr;
const struct inet_sock *inet = inet_sk(sk);
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = inet->inet_daddr;
sin->sin_port = inet->inet_dport;
}
EXPORT_SYMBOL_GPL(inet_csk_addr2sockaddr);
static struct dst_entry *inet_csk_rebuild_route(struct sock *sk, struct flowi *fl)
{
const struct inet_sock *inet = inet_sk(sk);
const struct ip_options_rcu *inet_opt;
__be32 daddr = inet->inet_daddr;
struct flowi4 *fl4;
struct rtable *rt;
rcu_read_lock();
inet_opt = rcu_dereference(inet->inet_opt);
if (inet_opt && inet_opt->opt.srr)
daddr = inet_opt->opt.faddr;
fl4 = &fl->u.ip4;
rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr,
inet->inet_saddr, inet->inet_dport,
inet->inet_sport, sk->sk_protocol,
RT_CONN_FLAGS(sk), sk->sk_bound_dev_if);
if (IS_ERR(rt))
rt = NULL;
if (rt)
sk_setup_caps(sk, &rt->dst);
rcu_read_unlock();
return &rt->dst;
}
struct dst_entry *inet_csk_update_pmtu(struct sock *sk, u32 mtu)
{
struct dst_entry *dst = __sk_dst_check(sk, 0);
struct inet_sock *inet = inet_sk(sk);
if (!dst) {
dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
if (!dst)
goto out;
}
dst->ops->update_pmtu(dst, sk, NULL, mtu, true);
dst = __sk_dst_check(sk, 0);
if (!dst)
dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
out:
return dst;
}
EXPORT_SYMBOL_GPL(inet_csk_update_pmtu);