From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=100.103.45.18 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796040552; b=P7TMsuQvP4SgNoFBi6Gb0QpQjb0NR+vqBf7bRnsu3I0BXo2+uwja4pENZ0FVbExeF4OI 4EZPMbSIy0oCUn6bn/vM6TOCdEf5c8I0OHO8mfc+fealnbUTIrvkkk4Kbjjt6po5B3zD6 KV6I6FpNwzXW+nnK8Z0HgRc1kLT0XrSCWSfytDFxgJuCBVSiRIrxLoeSwHRFKD7ljl8ck VAuiIEbqpcS/oDIah2/snGJzlVuyjtesWDZZm+WNhnbGDCbJlJDRSXqaEi5+IjKny8q5k gk+JHB6RQGLrp05SMf1Jl8qRV4h68W0yFrE6Pnvc2GG+cjSOkru5/G4RSSk9kexICIw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796040552; h=Received:DKIM-Signature:From:To:Cc:Subject:Date:Message-ID:X-Mailer: In-Reply-To:References:MIME-Version:Content-Type: Content-Transfer-Encoding; bh=bOMC2/VIBNm6PEPfCwZssT5VD2C/cfWHtQzuB08wIx8=; b=N/7X+FnYY7AmDgtahLufUNNTD+yrlTFIRXmu/NEzXCLdYKYUMnK6qksuOThm14tL5eXJ MX+5GiNTFpNRnr4+zP04cy1+AqRMKqpbeG2LvAHIVbAaUz8rO8aMAFnvY+E85CRq5/A8q FarfOkBmBBDIin3uWtNZPmxZbRzR3gPEn7fkeLl8+HJ1aaZOx/VawCSBFzhBGl0OV1/gU xL0UBzPy8+Z91hJY0Gu9jzq1FMPsMtjz30C1kvBekhkVpO/dhsJvxpkw5snwZ8AMRGADI dwd6Rc3h80ZlRStr2k8F3QNWW1Ww5TmJCDiKDZ4Lkwx3XlzFazbj/H1DjFC6T79n92Q== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dkim=pass header.d=linuxfoundation.org header.i=@linuxfoundation.org header.a=rsa-sha256 header.s=korg header.b=ZFrFKSCU; arc=none smtp.remote-ip=100.103.45.18 Received: from smtp.kernel.org (quasi.space.kernel.org [100.103.45.18]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (prime256v1)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 3C391606A327; Mon, 30 Nov 2026 12:09:11 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; dkim=pass (1024-bit key) header.d=linuxfoundation.org header.i=@linuxfoundation.org header.a=rsa-sha256 header.s=korg header.b=ZFrFKSCU Received: by smtp.kernel.org (Postfix) with ESMTPSA id 1D4F21F000C1; Mon, 30 Nov 2026 12:09:09 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linuxfoundation.org; s=korg; t=1796040551; bh=bOMC2/VIBNm6PEPfCwZssT5VD2C/cfWHtQzuB08wIx8=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=ZFrFKSCUAVWjHhb/H4tJhBd/CtVT+GojSEFOt5RuVRCkylH0wRcSRaWO3m15Xp+gF Kr1MoW2xNXcZBwhOTOPu/usL5sDfbjyEKyOtToOeqoL7k9EnWcyahc89BSthEDtarN 9Cjg1cS6EGi4ZRV2SGHNtNk38G6WxZ+R8Ch3pxOw= From: Greg Kroah-Hartman To: linux-kernel@vger.kernel.org, akpm@linux-foundation.org, torvalds@linux-foundation.org, stable@vger.kernel.org Cc: lwn@lwn.net, jslaby@suse.cz, Greg Kroah-Hartman Subject: Re: Linux 6.18.66 Date: Mon, 30 Nov 2026 13:08:56 +0100 Message-ID: <2026113056-visitor-thinly-e1da@gregkh> X-Mailer: git-send-email 2.56.1 In-Reply-To: <2026113056-tumbling-apostle-afbb@gregkh> References: <2026113056-tumbling-apostle-afbb@gregkh> X-Mailing-List: stable@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit diff --git a/Documentation/arch/arm64/gcs.rst b/Documentation/arch/arm64/gcs.rst index 226c0b008456..1e0424f915dc 100644 --- a/Documentation/arch/arm64/gcs.rst +++ b/Documentation/arch/arm64/gcs.rst @@ -179,9 +179,8 @@ intended to be exhaustive. When returning from a signal handler: -* If there is a gcs_context record in the signal frame then the GCS flags - and GCSPR_EL0 will be restored from that context prior to further - validation. +* If there is a gcs_context record in the signal frame then GCSPR_EL0 + will be restored from that context prior to further validation. * If there is no gcs_context record in the signal frame then the GCS configuration will be unchanged. @@ -190,12 +189,8 @@ When returning from a signal handler: point to a valid GCS signal cap record, this will be popped from the GCS prior to signal return. -* If the GCS configuration is locked when returning from a signal then any - attempt to change the GCS configuration will be treated as an error. This - is true even if GCS was not enabled prior to signal entry. - -* GCS may be disabled via signal return but any attempt to enable GCS via - signal return will be rejected. +* The features_enabled in the signal return context will be ignored; any + changes made using the prctl() in the signal handler will be preserved. 6. ptrace extensions diff --git a/Documentation/arch/arm64/silicon-errata.rst b/Documentation/arch/arm64/silicon-errata.rst index 75c6ba532c20..a611981466d3 100644 --- a/Documentation/arch/arm64/silicon-errata.rst +++ b/Documentation/arch/arm64/silicon-errata.rst @@ -162,8 +162,12 @@ stable kernels. +----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A715 | #2645198 | ARM64_ERRATUM_2645198 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Cortex-A715 | #2738462 | ARM64_ERRATUM_2738461 | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A715 | #3456084 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ +| ARM | Cortex-A720 | #2738461 | ARM64_ERRATUM_2738461 | ++----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A720 | #3456091 | ARM64_ERRATUM_3194386 | +----------------+-----------------+-----------------+-----------------------------+ | ARM | Cortex-A725 | #3456106 | ARM64_ERRATUM_3194386 | diff --git a/Documentation/block/ublk.rst b/Documentation/block/ublk.rst index 8c4030bcabb6..e14200c8dc25 100644 --- a/Documentation/block/ublk.rst +++ b/Documentation/block/ublk.rst @@ -126,6 +126,13 @@ managing and controlling ublk devices with help of several control commands: ublk server will release resources (such as destroying I/O handler threads & io_uring). + If a server has ``/dev/ublkc*`` open, its fetched I/O commands complete with + ``UBLK_IO_RES_ABORT``. Until it closes ``/dev/ublkc*``, new + ``UBLK_IO_FETCH_REQ`` and ``UBLK_U_IO_PREP_IO_CMDS`` commands complete with + ``UBLK_IO_RES_ABORT`` too, and ``UBLK_CMD_START_DEV`` fails with ``-EBUSY``, + even if the server hadn't fetched anything. The device can be started again + by a server that opens ``/dev/ublkc*`` after that. + - ``UBLK_CMD_DEL_DEV`` Remove ``/dev/ublkc*``. When this command returns, the allocated ublk device diff --git a/Documentation/core-api/kho/concepts.rst b/Documentation/core-api/kho/concepts.rst index 36d5c05cfb30..d626d1dbd678 100644 --- a/Documentation/core-api/kho/concepts.rst +++ b/Documentation/core-api/kho/concepts.rst @@ -70,5 +70,5 @@ in the FDT. That state is called the KHO finalization phase. Public API ========== -.. kernel-doc:: kernel/kexec_handover.c +.. kernel-doc:: kernel/liveupdate/kexec_handover.c :export: diff --git a/Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml b/Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml index 5c08d8b6e995..de7480954381 100644 --- a/Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml +++ b/Documentation/devicetree/bindings/iio/adc/aspeed,ast2600-adc.yaml @@ -62,6 +62,11 @@ properties: description: Inform the driver that last channel will be used to sensor battery. + aspeed,trim-syscon: + $ref: /schemas/types.yaml#/definitions/phandle + description: + Phandle to the SCU holding the ADC's reference-voltage trimming data. + required: - compatible - reg @@ -69,6 +74,18 @@ required: - resets - "#io-channel-cells" +allOf: + - if: + properties: + compatible: + contains: + enum: + - aspeed,ast2700-adc0 + - aspeed,ast2700-adc1 + then: + required: + - aspeed,trim-syscon + additionalProperties: false examples: diff --git a/Documentation/devicetree/bindings/sound/qcom,q6dsp-lpass-ports.yaml b/Documentation/devicetree/bindings/sound/qcom,q6dsp-lpass-ports.yaml index 08c618e7e428..2b27d6c8f58f 100644 --- a/Documentation/devicetree/bindings/sound/qcom,q6dsp-lpass-ports.yaml +++ b/Documentation/devicetree/bindings/sound/qcom,q6dsp-lpass-ports.yaml @@ -126,13 +126,16 @@ patternProperties: reg: contains: # MI2S DAI ID range PRIMARY_MI2S_RX - QUATERNARY_MI2S_TX and - # QUINARY_MI2S_RX - QUINARY_MI2S_TX + # QUINARY_MI2S_RX - QUINARY_MI2S_TX and + # LPI_MI2S_RX_0 - SENARY_MI2S_TX items: oneOf: - minimum: 16 maximum: 23 - minimum: 127 maximum: 128 + - minimum: 137 + maximum: 148 then: required: - qcom,sd-lines diff --git a/Documentation/filesystems/9p.rst b/Documentation/filesystems/9p.rst index be3504ca034a..e80dae4dd62b 100644 --- a/Documentation/filesystems/9p.rst +++ b/Documentation/filesystems/9p.rst @@ -231,13 +231,18 @@ Options any v9fs does single attach and performs all operations as one user - clien + client ACL based access check on the 9p client side for access validation cachetag cache tag to use the specified persistent cache. cache tags for existing cache sessions can be listed at /sys/fs/9p/caches. (applies only to cache=fscache) + + negtimeout the duration (in milliseconds) that negative dentries (paths + that do not actually exist) are retained in the cache. If + set to a negative value, those entries are kept indefinitely + until evicted by the buffer cache management system ============= =============================================================== Behavior diff --git a/Documentation/gpu/xe/xe_firmware.rst b/Documentation/gpu/xe/xe_firmware.rst index 5d23e9f27391..9c15a300bc62 100644 --- a/Documentation/gpu/xe/xe_firmware.rst +++ b/Documentation/gpu/xe/xe_firmware.rst @@ -31,6 +31,9 @@ GuC Power Conservation (PC) .. kernel-doc:: drivers/gpu/drm/xe/xe_guc_pc.c :doc: GuC Power Conservation (PC) +.. kernel-doc:: drivers/gpu/drm/xe/xe_guc_rc.c + :doc: GuC Render C-states (GuC RC) + PCIe Gen5 Limitations ===================== diff --git a/Documentation/networking/net_cachelines/tcp_sock.rst b/Documentation/networking/net_cachelines/tcp_sock.rst index 26f32dbcf6ec..48fbc27044bf 100644 --- a/Documentation/networking/net_cachelines/tcp_sock.rst +++ b/Documentation/networking/net_cachelines/tcp_sock.rst @@ -13,16 +13,16 @@ u16 tcp_header_len read_mostly read_m u16 gso_segs read_mostly tcp_xmit_size_goal __be32 pred_flags read_write read_mostly tcp_select_window(tx);tcp_rcv_established(rx) u64 bytes_received read_write tcp_rcv_nxt_update(rx) -u32 segs_in read_write tcp_v6_rcv(rx) +u32 segs_in read_write read_write tcp_segs_in(),tcp_v6_rcv(rx),tcp_v4_rcv() u32 data_segs_in read_write tcp_v6_rcv(rx) u32 rcv_nxt read_mostly read_write tcp_cleanup_rbuf,tcp_send_ack,tcp_inq_hint,tcp_transmit_skb,tcp_receive_window(tx);tcp_v6_do_rcv,tcp_rcv_established,tcp_data_queue,tcp_receive_window,tcp_rcv_nxt_update(write)(rx) u32 copied_seq read_mostly tcp_cleanup_rbuf,tcp_rcv_space_adjust,tcp_inq_hint u32 rcv_wup read_write __tcp_cleanup_rbuf,tcp_receive_window,tcp_receive_established u32 snd_nxt read_write read_mostly tcp_rate_check_app_limited,__tcp_transmit_skb,tcp_event_new_data_sent(write)(tx);tcp_rcv_established,tcp_ack,tcp_clean_rtx_queue(rx) -u32 segs_out read_write __tcp_transmit_skb +u32 segs_out read_write read_write __tcp_transmit_skb u32 data_segs_out read_write __tcp_transmit_skb,tcp_update_skb_after_send u64 bytes_sent read_write __tcp_transmit_skb -u64 bytes_acked read_write tcp_snd_una_update/tcp_ack +u64 bytes_acked read_write tcp_snd_una_update/tcp_ack u32 dsack_dups u32 snd_una read_mostly read_write tcp_wnd_end,tcp_urg_mode,tcp_minshall_check,tcp_cwnd_validate(tx);tcp_ack,tcp_may_update_window,tcp_clean_rtx_queue(write),tcp_ack_tstamp(rx) u32 snd_sml read_write tcp_minshall_check,tcp_minshall_update @@ -99,12 +99,14 @@ u32 snd_cwnd_stamp u32 prior_cwnd u32 prr_delivered u32 prr_out read_mostly read_mostly tcp_rate_skb_sent,tcp_newly_delivered(tx);tcp_ack,tcp_rate_gen,tcp_clean_rtx_queue(rx) -u32 delivered read_mostly read_write tcp_rate_skb_sent, tcp_newly_delivered(tx);tcp_ack, tcp_rate_gen, tcp_clean_rtx_queue (rx) -u32 delivered_ce read_mostly read_write tcp_rate_skb_sent(tx);tcp_rate_gen(rx) +u32 delivered read_write tcp_rate_skb_sent, tcp_newly_delivered(tx);tcp_ack, tcp_rate_gen, tcp_clean_rtx_queue (rx) +u32 delivered_ce read_write tcp_rate_skb_sent(tx);tcp_rate_gen(rx) u32 received_ce read_mostly read_write u32[3] received_ecn_bytes read_mostly read_write u8:4 received_ce_pending read_mostly read_write u32[3] delivered_ecn_bytes read_write +u16 pkts_acked_ewma read_write +u32 rcv_collapse_credit read_write tcp_queue_rcv,tcp_data_queue_ofo,tcp_prune_queue u8:2 syn_ect_snt write_mostly read_write u8:2 syn_ect_rcv read_mostly read_write u8:2 accecn_minlen write_mostly read_write diff --git a/Documentation/networking/tls-offload.rst b/Documentation/networking/tls-offload.rst index 7354d48cdf92..7ed28e40f170 100644 --- a/Documentation/networking/tls-offload.rst +++ b/Documentation/networking/tls-offload.rst @@ -76,12 +76,16 @@ During driver initialization device sets the ``NETIF_F_HW_TLS_RX`` and pointer in the :c:member:`tlsdev_ops` member of the :c:type:`struct net_device `. -When TLS cryptographic connection state is installed on a ``ktls`` socket -(note that it is done twice, once for RX and once for TX direction, -and the two are completely independent), the kernel checks if the underlying -network device is offload-capable and attempts the offload. In case offload -fails the connection is handled entirely in software using the same mechanism -as if the offload was never tried. +TLS cryptographic connection state is installed separately for RX and TX +on a ``ktls`` socket. For each direction, the kernel checks if the underlying +network device is offload-capable and attempts the offload. If offload fails, +that direction is handled in software as if offload had never been tried. + +Both hardware directions share one device binding. Once one direction is +offloaded, the other direction must use the same device. If a route change +selects a different device, or ``NETDEV_DOWN`` has cleared the binding, +hardware offload of the other direction is declined and it uses software +instead. Offload request is performed via the :c:member:`tls_dev_add` callback of :c:type:`struct tlsdev_ops `: diff --git a/Documentation/trace/kprobes.rst b/Documentation/trace/kprobes.rst index 5e606730cec6..0b19d82d7d4c 100644 --- a/Documentation/trace/kprobes.rst +++ b/Documentation/trace/kprobes.rst @@ -31,7 +31,7 @@ can trap at almost any kernel code address [1]_, specifying a handler routine to be invoked when the breakpoint is hit. .. [1] some parts of the kernel code can not be trapped, see - :ref:`kprobes_blacklist`) + :ref:`kprobes_blacklist` There are currently two types of probes: kprobes, and kretprobes (also called return probes). A kprobe can be inserted on virtually diff --git a/MAINTAINERS b/MAINTAINERS index 5821d97ae330..41b87ea892e0 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -13818,7 +13818,7 @@ S: Maintained F: Documentation/admin-guide/mm/kho.rst F: Documentation/core-api/kho/* F: include/linux/kexec_handover.h -F: kernel/kexec_handover* +F: kernel/liveupdate/kexec_handover* F: lib/test_kho.c F: tools/testing/selftests/kho/ diff --git a/Makefile b/Makefile index 2166fc675d1f..3f78c46f7aa7 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ # SPDX-License-Identifier: GPL-2.0 VERSION = 6 PATCHLEVEL = 18 -SUBLEVEL = 65 +SUBLEVEL = 66 EXTRAVERSION = NAME = Baby Opossum Posse diff --git a/arch/alpha/include/uapi/asm/socket.h b/arch/alpha/include/uapi/asm/socket.h index 5ef57f88df6b..946a5fad2691 100644 --- a/arch/alpha/include/uapi/asm/socket.h +++ b/arch/alpha/include/uapi/asm/socket.h @@ -155,6 +155,8 @@ #define SO_INQ 84 #define SCM_INQ SO_INQ +#define SO_RIGHTS_NOTRUNC 85 + #if !defined(__KERNEL__) #if __BITS_PER_LONG == 64 diff --git a/arch/arc/include/asm/cmpxchg.h b/arch/arc/include/asm/cmpxchg.h index 66b3743c9400..93f7153eb267 100644 --- a/arch/arc/include/asm/cmpxchg.h +++ b/arch/arc/include/asm/cmpxchg.h @@ -59,6 +59,8 @@ _prev_; \ }) +#define arch_cmpxchg_local arch_cmpxchg_relaxed + #else #define arch_cmpxchg(ptr, old, new) \ @@ -80,6 +82,8 @@ _prev_; \ }) +#define arch_cmpxchg_local arch_cmpxchg + #endif /* diff --git a/arch/arm/kernel/perf_regs.c b/arch/arm/kernel/perf_regs.c index 0529f90395c9..d575a4c3ca56 100644 --- a/arch/arm/kernel/perf_regs.c +++ b/arch/arm/kernel/perf_regs.c @@ -31,9 +31,3 @@ u64 perf_reg_abi(struct task_struct *task) return PERF_SAMPLE_REGS_ABI_32; } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} diff --git a/arch/arm64/Kconfig b/arch/arm64/Kconfig index 66b7284ce751..a57349bf9351 100644 --- a/arch/arm64/Kconfig +++ b/arch/arm64/Kconfig @@ -1057,6 +1057,38 @@ config ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT # making it unreliable. As a result, AMU users should treat it as # unavailable rather than relying on misleading counter values. +config ARM64_WORKAROUND_BROKEN_AMU_CORECNT + bool + # Targeting errata affecting AMEVCNTR00, the AMU core cycle counter. + # On affected CPUs the counter may continue incrementing while core + # remains in WFE with the clocks enabled. + # This may lead to readings of said counter being unreliable. + # How much though depends on the sampling intervals. + +config ARM64_ERRATUM_2738461 + bool "Cortex-A715/Cortex-A720: workaround for AMEVCNTR00 incrementing incorrectly" + depends on ARM64_AMU_EXTN + select ARM64_WORKAROUND_BROKEN_AMU_CORECNT + default y + help + This option adds the workaround for the following errata: + + * ARM Cortex-A715 erratum 2738462 + * ARM Cortex-A720 erratum 2738461 + + On affected cores the AMEVCNTR00 counter (AMU core frequency cycles + counter) may continue incrementing while the core remains in WFE + with the clocks being enabled. + This may result in inaccurate counter readings, with the magnitude + of the discrepancy depending on the sampling interval. + + With this workaround, reads of the affected counter return 0 in + the relevant paths. This causes users of the counter to treat it + as unavailable and is functionally equivalent to firmware disabling + the affected counter. + + If unsure, say Y. + config ARM64_ERRATUM_2457168 bool "Cortex-A510: 2457168: workaround for AMEVCNTR01 incrementing incorrectly" depends on ARM64_AMU_EXTN diff --git a/arch/arm64/boot/dts/qcom/lemans-evk.dts b/arch/arm64/boot/dts/qcom/lemans-evk.dts index c7dc9b8f4457..5cac85b782d6 100644 --- a/arch/arm64/boot/dts/qcom/lemans-evk.dts +++ b/arch/arm64/boot/dts/qcom/lemans-evk.dts @@ -646,7 +646,8 @@ &sdhc { }; &serdes0 { - phy-supply = <&vreg_l5a>; + vdda-0p9-supply = <&vreg_l4a>; + vdda-1p2-supply = <&vreg_l1c>; status = "okay"; }; diff --git a/arch/arm64/boot/dts/qcom/x1e80100-asus-vivobook-s15.dts b/arch/arm64/boot/dts/qcom/x1e80100-asus-vivobook-s15.dts index f2960953e608..7abd519f38a4 100644 --- a/arch/arm64/boot/dts/qcom/x1e80100-asus-vivobook-s15.dts +++ b/arch/arm64/boot/dts/qcom/x1e80100-asus-vivobook-s15.dts @@ -742,6 +742,7 @@ &smb2360_1_eusb2_repeater { &tlmm { gpio-reserved-ranges = <34 2>, /* Unused */ <44 4>, /* SPI (TPM) */ + <65 1>, /* EC reset */ <238 1>; /* UFS Reset */ edp_reg_en: edp-reg-en-state { diff --git a/arch/arm64/include/asm/suspend.h b/arch/arm64/include/asm/suspend.h index 2cc5fb405769..a991e31739f5 100644 --- a/arch/arm64/include/asm/suspend.h +++ b/arch/arm64/include/asm/suspend.h @@ -2,7 +2,7 @@ #ifndef __ASM_SUSPEND_H #define __ASM_SUSPEND_H -#define NR_CTX_REGS 15 +#define NR_CTX_REGS 18 #define NR_CALLEE_SAVED_REGS 12 /* diff --git a/arch/arm64/kernel/cpu_errata.c b/arch/arm64/kernel/cpu_errata.c index 516a1e37a51f..7af916facaba 100644 --- a/arch/arm64/kernel/cpu_errata.c +++ b/arch/arm64/kernel/cpu_errata.c @@ -367,6 +367,18 @@ static const struct midr_range workaround_amu_constcnt_list[] = { }; #endif /* CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT */ +#ifdef CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT +static const struct midr_range workaround_amu_corecnt_list[] = { +#ifdef CONFIG_ARM64_ERRATUM_2738461 + /* Cortex-A715 r0p0 - r1p3 */ + MIDR_RANGE(MIDR_CORTEX_A715, 0, 0, 1, 3), + /* Cortex-A720 r0p0 - r0p1 */ + MIDR_RANGE(MIDR_CORTEX_A720, 0, 0, 0, 1), +#endif + {} +}; +#endif /* CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT */ + #ifdef CONFIG_CAVIUM_ERRATUM_23154 static const struct midr_range cavium_erratum_23154_cpus[] = { MIDR_ALL_VERSIONS(MIDR_THUNDERX), @@ -891,6 +903,14 @@ const struct arm64_cpu_capabilities arm64_errata[] = { CAP_MIDR_RANGE_LIST(workaround_amu_constcnt_list) }, #endif +#ifdef CONFIG_ARM64_WORKAROUND_BROKEN_AMU_CORECNT + { + .desc = "Broken AMU AMEVCNTR00 (core cycle counter)", + .capability = ARM64_WORKAROUND_BROKEN_AMU_CORECNT, + .type = ARM64_CPUCAP_WEAK_LOCAL_CPU_FEATURE, + CAP_MIDR_RANGE_LIST(workaround_amu_corecnt_list) + }, +#endif #ifdef CONFIG_ARM64_ERRATUM_2038923 { .desc = "ARM erratum 2038923", diff --git a/arch/arm64/kernel/cpufeature.c b/arch/arm64/kernel/cpufeature.c index bb73d05318a9..13933aa3be5e 100644 --- a/arch/arm64/kernel/cpufeature.c +++ b/arch/arm64/kernel/cpufeature.c @@ -2054,7 +2054,8 @@ static void cpu_amu_enable(struct arm64_cpu_capabilities const *cap) cpumask_set_cpu(smp_processor_id(), &amu_cpus); /* 0 reference values signal broken/disabled counters */ - if (!this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT)) + if (!this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CONSTCNT) && + !this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CORECNT)) update_freq_counters_refs(); } } diff --git a/arch/arm64/kernel/kexec_image.c b/arch/arm64/kernel/kexec_image.c index b70f4df15a1a..46a30cc0000f 100644 --- a/arch/arm64/kernel/kexec_image.c +++ b/arch/arm64/kernel/kexec_image.c @@ -82,6 +82,13 @@ static void *image_load(struct kimage *image, kbuf.mem = KEXEC_BUF_MEM_UNKNOWN; kbuf.memsz = le64_to_cpu(h->image_size); text_offset = le64_to_cpu(h->text_offset); + /* + * A CMA segment is loaded and mapped through page_address(cma), which + * is the CMA base and cannot represent the text_offset adjustment + * below. Load images with a non-zero text_offset from normal memory. + */ + if (text_offset) + image->no_cma = true; kbuf.buf_align = MIN_KIMG_ALIGN; /* Adjust kernel segment with TEXT_OFFSET */ diff --git a/arch/arm64/kernel/perf_regs.c b/arch/arm64/kernel/perf_regs.c index b4eece3eb17d..70e2f13f587f 100644 --- a/arch/arm64/kernel/perf_regs.c +++ b/arch/arm64/kernel/perf_regs.c @@ -98,9 +98,3 @@ u64 perf_reg_abi(struct task_struct *task) return PERF_SAMPLE_REGS_ABI_64; } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} diff --git a/arch/arm64/kernel/ptrace.c b/arch/arm64/kernel/ptrace.c index 8e7f8dedb1cc..e2ecd19554c6 100644 --- a/arch/arm64/kernel/ptrace.c +++ b/arch/arm64/kernel/ptrace.c @@ -573,8 +573,12 @@ static void update_syscall_orig_x0_after_ptrace(struct task_struct *target) if (regs->syscallno == NO_SYSCALL) return; - /* We should only be called when target is in a ptrace stop */ - if (WARN_ON_ONCE(!info)) + /* + * For exit-stops, info is always non-NULL, but that's not true for other + * stops such as non-seized group-stops. In those cases, just return early + * as there's no need to update orig_x0 anyway. + */ + if (!info) return; /* diff --git a/arch/arm64/kernel/signal.c b/arch/arm64/kernel/signal.c index 6a06a4e352b1..80398ac83c3b 100644 --- a/arch/arm64/kernel/signal.c +++ b/arch/arm64/kernel/signal.c @@ -741,36 +741,16 @@ static int preserve_gcs_context(struct gcs_context __user *ctx) static int restore_gcs_context(struct user_ctxs *user) { - u64 gcspr, enabled; + u64 gcspr; int err = 0; if (user->gcs_size != sizeof(*user->gcs)) return -EINVAL; __get_user_error(gcspr, &user->gcs->gcspr, err); - __get_user_error(enabled, &user->gcs->features_enabled, err); if (err) return err; - /* Don't allow unknown modes */ - if (enabled & ~PR_SHADOW_STACK_SUPPORTED_STATUS_MASK) - return -EINVAL; - - err = gcs_check_locked(current, enabled); - if (err != 0) - return err; - - /* Don't allow enabling */ - if (!task_gcs_el0_enabled(current) && - (enabled & PR_SHADOW_STACK_ENABLE)) - return -EINVAL; - - /* If we are disabling disable everything */ - if (!(enabled & PR_SHADOW_STACK_ENABLE)) - enabled = 0; - - current->thread.gcs_el0_mode = enabled; - /* * We let userspace set GCSPR_EL0 to anything here, we will * validate later in gcs_restore_signal(). diff --git a/arch/arm64/kernel/topology.c b/arch/arm64/kernel/topology.c index 415891ffa62e..3a83098d80de 100644 --- a/arch/arm64/kernel/topology.c +++ b/arch/arm64/kernel/topology.c @@ -420,7 +420,8 @@ static void cpu_read_corecnt(void *val) * counter read is properly handled as an error case by the users of the * counter. */ - *(u64 *)val = read_corecnt(); + *(u64 *)val = this_cpu_has_cap(ARM64_WORKAROUND_BROKEN_AMU_CORECNT) ? + 0UL : read_corecnt(); } static void cpu_read_constcnt(void *val) diff --git a/arch/arm64/mm/proc.S b/arch/arm64/mm/proc.S index 5e7bc1a8d9ca..42426c2705b7 100644 --- a/arch/arm64/mm/proc.S +++ b/arch/arm64/mm/proc.S @@ -107,6 +107,16 @@ alternative_else_nop_endif alternative_if ARM64_SME mrs_s x2, SYS_TPIDR2_EL0 str x2, [x0, #112] +alternative_else_nop_endif +alternative_if ARM64_HAS_S1POE + mrs x2, REG_POR_EL0 + str x2, [x0, #120] +alternative_else_nop_endif +alternative_if ARM64_HAS_GCS + mrs x2, REG_GCSPR_EL0 + str x2, [x0, #128] + mrs x2, REG_GCSCRE0_EL1 + str x2, [x0, #136] alternative_else_nop_endif ret SYM_FUNC_END(cpu_do_suspend) @@ -150,6 +160,16 @@ alternative_if ARM64_SME ldr x2, [x0, #112] msr_s SYS_TPIDR2_EL0, x2 alternative_else_nop_endif +alternative_if ARM64_HAS_S1POE + ldr x2, [x0, #120] + msr REG_POR_EL0, x2 +alternative_else_nop_endif +alternative_if ARM64_HAS_GCS + ldr x2, [x0, #128] + msr REG_GCSPR_EL0, x2 + ldr x2, [x0, #136] + msr REG_GCSCRE0_EL1, x2 +alternative_else_nop_endif msr sctlr_el1, x12 set_this_cpu_offset x13 diff --git a/arch/arm64/tools/cpucaps b/arch/arm64/tools/cpucaps index 3e2c5c1914d8..efccc7f371a7 100644 --- a/arch/arm64/tools/cpucaps +++ b/arch/arm64/tools/cpucaps @@ -122,3 +122,4 @@ WORKAROUND_SPECULATIVE_AT WORKAROUND_SPECULATIVE_SSBS WORKAROUND_SPECULATIVE_UNPRIV_LOAD WORKAROUND_BROKEN_AMU_CONSTCNT +WORKAROUND_BROKEN_AMU_CORECNT diff --git a/arch/csky/kernel/perf_regs.c b/arch/csky/kernel/perf_regs.c index 09b7f88a2d6a..94601f37b596 100644 --- a/arch/csky/kernel/perf_regs.c +++ b/arch/csky/kernel/perf_regs.c @@ -31,9 +31,3 @@ u64 perf_reg_abi(struct task_struct *task) return PERF_SAMPLE_REGS_ABI_32; } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} diff --git a/arch/hexagon/include/asm/cmpxchg.h b/arch/hexagon/include/asm/cmpxchg.h index 9c58fb81f7fd..e6114e713db9 100644 --- a/arch/hexagon/include/asm/cmpxchg.h +++ b/arch/hexagon/include/asm/cmpxchg.h @@ -8,6 +8,8 @@ #ifndef _ASM_CMPXCHG_H #define _ASM_CMPXCHG_H +#include + /* * __arch_xchg - atomically exchange a register and a memory location * @x: value to swap @@ -72,4 +74,8 @@ __arch_xchg(unsigned long x, volatile void *ptr, int size) __oldval; \ }) +#define arch_cmpxchg_local(ptr, o, n) \ + ((__typeof__(*(ptr)))__generic_cmpxchg_local((ptr), \ + (unsigned long)(o), (unsigned long)(n), sizeof(*(ptr)))) + #endif /* _ASM_CMPXCHG_H */ diff --git a/arch/loongarch/kernel/machine_kexec.c b/arch/loongarch/kernel/machine_kexec.c index 1883cae93bc3..19ccc91b6f2a 100644 --- a/arch/loongarch/kernel/machine_kexec.c +++ b/arch/loongarch/kernel/machine_kexec.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -56,6 +57,7 @@ int machine_kexec_prepare(struct kimage *kimage) */ memcpy((void *)KEXEC_CMDLINE_ADDR, (void *)kimage->arch.cmdline_ptr, strlen((char *)kimage->arch.cmdline_ptr) + 1); + kfree((void *)kimage->arch.cmdline_ptr); kimage->arch.cmdline_ptr = (unsigned long)KEXEC_CMDLINE_ADDR; } else { /* Find the command line */ diff --git a/arch/loongarch/kernel/machine_kexec_file.c b/arch/loongarch/kernel/machine_kexec_file.c index fb57026f5f25..f5c844496adf 100644 --- a/arch/loongarch/kernel/machine_kexec_file.c +++ b/arch/loongarch/kernel/machine_kexec_file.c @@ -182,6 +182,10 @@ int load_other_segments(struct kimage *image, vfree(headers); goto out_err; } + + if (unlikely(image->elf_headers)) + vfree(image->elf_headers); + image->elf_headers = headers; image->elf_load_addr = kbuf.mem; image->elf_headers_sz = headers_sz; diff --git a/arch/loongarch/kernel/perf_regs.c b/arch/loongarch/kernel/perf_regs.c index 263ac4ab5af6..8dd604f01745 100644 --- a/arch/loongarch/kernel/perf_regs.c +++ b/arch/loongarch/kernel/perf_regs.c @@ -45,9 +45,3 @@ u64 perf_reg_value(struct pt_regs *regs, int idx) return regs->regs[idx]; } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} diff --git a/arch/loongarch/kvm/intc/pch_pic.c b/arch/loongarch/kvm/intc/pch_pic.c index d01978818519..f61f79e85383 100644 --- a/arch/loongarch/kvm/intc/pch_pic.c +++ b/arch/loongarch/kvm/intc/pch_pic.c @@ -273,16 +273,25 @@ static int kvm_pch_pic_init(struct kvm_device *dev, u64 addr) struct kvm_io_device *device; struct loongarch_pch_pic *s = dev->kvm->arch.pch_pic; - s->pch_pic_base = addr; device = &s->device; + mutex_lock(&kvm->slots_lock); + if (s->device.ops) { + ret = -EEXIST; + goto out; + } + s->pch_pic_base = addr; /* init device by pch pic writing and reading ops */ kvm_iodevice_init(device, &kvm_pch_pic_ops); - mutex_lock(&kvm->slots_lock); /* register pch pic device */ ret = kvm_io_bus_register_dev(kvm, KVM_MMIO_BUS, addr, PCH_PIC_SIZE, device); + if (ret) { + s->pch_pic_base = 0; + s->device.ops = NULL; + } +out: mutex_unlock(&kvm->slots_lock); - return (ret < 0) ? -EFAULT : 0; + return ret; } /* used by user space to get or set pch pic registers */ @@ -436,7 +445,7 @@ static int kvm_pch_pic_create(struct kvm_device *dev, u32 type) ret = kvm_setup_default_irq_routing(kvm); if (ret) - return -ENOMEM; + return ret; s = kzalloc(sizeof(struct loongarch_pch_pic), GFP_KERNEL); if (!s) diff --git a/arch/loongarch/power/hibernate.c b/arch/loongarch/power/hibernate.c index e7b7346592cb..8406f2baba88 100644 --- a/arch/loongarch/power/hibernate.c +++ b/arch/loongarch/power/hibernate.c @@ -59,6 +59,12 @@ extern int swsusp_asm_resume(void); int swsusp_arch_resume(void) { +#ifdef CONFIG_KFENCE + struct pbe *pbe; + + for (pbe = restore_pblist; pbe; pbe = pbe->next) + pbe->orig_address = __va(virt_to_phys(pbe->orig_address)); +#endif /* Avoid TLB mismatch during and after kernel resume */ local_flush_tlb_all(); return swsusp_asm_resume(); diff --git a/arch/mips/Kconfig b/arch/mips/Kconfig index fadaeafae98e..cefaa55ff8bd 100644 --- a/arch/mips/Kconfig +++ b/arch/mips/Kconfig @@ -81,7 +81,7 @@ config MIPS select HAVE_IRQ_TIME_ACCOUNTING select HAVE_KPROBES select HAVE_KRETPROBES - select HAVE_LD_DEAD_CODE_DATA_ELIMINATION + select HAVE_LD_DEAD_CODE_DATA_ELIMINATION if !FTRACE_MCOUNT_USE_RECORDMCOUNT select HAVE_MOD_ARCH_SPECIFIC select HAVE_NMI select HAVE_PAGE_SIZE_4KB if !CPU_LOONGSON2EF && !CPU_LOONGSON64 diff --git a/arch/mips/alchemy/common/prom.c b/arch/mips/alchemy/common/prom.c index 20d30f6265cd..c4aefeb78871 100644 --- a/arch/mips/alchemy/common/prom.c +++ b/arch/mips/alchemy/common/prom.c @@ -46,6 +46,11 @@ int prom_argc; char **prom_argv; char **prom_envp; +static char prom_ethaddr[6] __initdata; +static bool prom_ethaddr_valid __initdata; + +static void __init prom_init_ethernet_addr(void); + void __init prom_init_cmdline(void) { int i; @@ -95,6 +100,9 @@ void __init prom_init(void) if (!memsize_str || kstrtoul(memsize_str, 0, &memsize)) memsize = SZ_64M; /* minimum memsize is 64MB RAM */ + /* Save the MAC before the allocator can reuse the PROM environment. */ + prom_init_ethernet_addr(); + memblock_add(0, memsize); } @@ -125,7 +133,7 @@ static inline void str2eaddr(unsigned char *ea, unsigned char *str) } } -int __init prom_get_ethernet_addr(char *ethernet_addr) +static void __init prom_init_ethernet_addr(void) { char *ethaddr_str; @@ -135,12 +143,21 @@ int __init prom_get_ethernet_addr(char *ethernet_addr) /* Check command line */ ethaddr_str = strstr(arcs_cmdline, "ethaddr="); if (!ethaddr_str) - return -1; + return; ethaddr_str += strlen("ethaddr="); } - str2eaddr(ethernet_addr, ethaddr_str); + str2eaddr(prom_ethaddr, ethaddr_str); + prom_ethaddr_valid = true; +} + +int __init prom_get_ethernet_addr(char *ethernet_addr) +{ + if (!prom_ethaddr_valid) + return -1; + + memcpy(ethernet_addr, prom_ethaddr, sizeof(prom_ethaddr)); return 0; } diff --git a/arch/mips/cobalt/pci.c b/arch/mips/cobalt/pci.c index 85ec9cc31d66..29fd052766b2 100644 --- a/arch/mips/cobalt/pci.c +++ b/arch/mips/cobalt/pci.c @@ -14,6 +14,8 @@ #include +#include + extern struct pci_ops gt64xxx_pci0_ops; static struct resource cobalt_mem_resource = { @@ -24,7 +26,7 @@ static struct resource cobalt_mem_resource = { }; static struct resource cobalt_io_resource = { - .start = 0x1000, + .start = 0, .end = 0xffffffUL, .name = "PCI I/O", .flags = IORESOURCE_IO, @@ -38,11 +40,8 @@ static struct pci_controller cobalt_pci_controller = { .io_map_base = CKSEG1ADDR(GT_DEF_PCI0_IO_BASE), }; -static int __init cobalt_pci_init(void) +void __init cobalt_pci_init(void) { + PCIBIOS_MIN_IO = 0x1000; register_pci_controller(&cobalt_pci_controller); - - return 0; } - -arch_initcall(cobalt_pci_init); diff --git a/arch/mips/cobalt/setup.c b/arch/mips/cobalt/setup.c index 9a266bf78339..502acc92969b 100644 --- a/arch/mips/cobalt/setup.c +++ b/arch/mips/cobalt/setup.c @@ -83,9 +83,11 @@ void __init plat_mem_setup(void) /* I/O port resource */ ioport_resource.end = 0x01ffffff; + cobalt_pci_init(); + /* These resources have been reserved by VIA SuperI/O chip. */ for (i = 0; i < ARRAY_SIZE(cobalt_reserved_resources); i++) - request_resource(&ioport_resource, cobalt_reserved_resources + i); + insert_resource(&ioport_resource, cobalt_reserved_resources + i); } /* diff --git a/arch/mips/configs/ip30_defconfig b/arch/mips/configs/ip30_defconfig index 718f3060d9fa..4f3fa1d49cd4 100644 --- a/arch/mips/configs/ip30_defconfig +++ b/arch/mips/configs/ip30_defconfig @@ -40,7 +40,6 @@ CONFIG_INET6_AH=m CONFIG_INET6_ESP=m CONFIG_INET6_IPCOMP=m CONFIG_IPV6_MIP6=m -CONFIG_IPV6_SIT=m CONFIG_IPV6_SIT_6RD=y CONFIG_IPV6_TUNNEL=m CONFIG_IPV6_MULTIPLE_TABLES=y @@ -130,11 +129,14 @@ CONFIG_SERIAL_8250_IOC3=y CONFIG_NOZOMI=m CONFIG_HW_RANDOM_TIMERIOMEM=m # CONFIG_PTP_1588_CLOCK is not set +CONFIG_W1=y +CONFIG_W1_MASTER_SGI=y +CONFIG_W1_SLAVE_DS250X=y # CONFIG_HWMON is not set CONFIG_THERMAL=y CONFIG_SGI_MFD_IOC3=y CONFIG_RTC_CLASS=y -CONFIG_RTC_DRV_M48T35=y +CONFIG_RTC_DRV_DS1685_FAMILY=y CONFIG_UIO=y CONFIG_UIO_AEC=m CONFIG_UIO_SERCOS3=m @@ -163,17 +165,14 @@ CONFIG_NFS_FS=y CONFIG_SECURITYFS=y CONFIG_CRYPTO_CRYPTD=m CONFIG_CRYPTO_BLOWFISH=m -CONFIG_CRYPTO_CAMELLIA=m CONFIG_CRYPTO_CAST5=m CONFIG_CRYPTO_CAST6=m CONFIG_CRYPTO_FCRYPT=m CONFIG_CRYPTO_SERPENT=m CONFIG_CRYPTO_TWOFISH=m -CONFIG_CRYPTO_CTS=m CONFIG_CRYPTO_LRW=m CONFIG_CRYPTO_PCBC=m CONFIG_CRYPTO_XTS=m -CONFIG_CRYPTO_HMAC=y CONFIG_CRYPTO_MD4=m CONFIG_CRYPTO_RMD160=m CONFIG_CRYPTO_WP512=m diff --git a/arch/mips/include/asm/mach-cobalt/cobalt.h b/arch/mips/include/asm/mach-cobalt/cobalt.h index 97f9d5e9446d..c7a8607cd651 100644 --- a/arch/mips/include/asm/mach-cobalt/cobalt.h +++ b/arch/mips/include/asm/mach-cobalt/cobalt.h @@ -19,6 +19,7 @@ extern int cobalt_board_id; #define COBALT_BRD_ID_QUBE2 0x5 #define COBALT_BRD_ID_RAQ2 0x6 +void cobalt_pci_init(void); void cobalt_machine_halt(void); void cobalt_machine_restart(char *command); diff --git a/arch/mips/include/uapi/asm/socket.h b/arch/mips/include/uapi/asm/socket.h index 72fb1b006da9..f1641dde135f 100644 --- a/arch/mips/include/uapi/asm/socket.h +++ b/arch/mips/include/uapi/asm/socket.h @@ -166,6 +166,8 @@ #define SO_INQ 84 #define SCM_INQ SO_INQ +#define SO_RIGHTS_NOTRUNC 85 + #if !defined(__KERNEL__) #if __BITS_PER_LONG == 64 diff --git a/arch/mips/kernel/perf_regs.c b/arch/mips/kernel/perf_regs.c index e686780d1647..7736d3c5ebd2 100644 --- a/arch/mips/kernel/perf_regs.c +++ b/arch/mips/kernel/perf_regs.c @@ -60,9 +60,3 @@ u64 perf_reg_value(struct pt_regs *regs, int idx) return (s64)v; /* Sign extend if 32-bit. */ } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} diff --git a/arch/mips/sibyte/sb1250/irq.c b/arch/mips/sibyte/sb1250/irq.c index 2f08ad267a11..d7a656cd7ec0 100644 --- a/arch/mips/sibyte/sb1250/irq.c +++ b/arch/mips/sibyte/sb1250/irq.c @@ -76,6 +76,8 @@ static int sb1250_set_affinity(struct irq_data *d, const struct cpumask *mask, unsigned long flags; i = cpumask_first_and(mask, cpu_online_mask); + if (i >= nr_cpu_ids) + return -EINVAL; /* Convert logical CPU to physical CPU */ cpu = cpu_logical_map(i); @@ -103,6 +105,7 @@ static int sb1250_set_affinity(struct irq_data *d, const struct cpumask *mask, ____raw_writeq(cur_ints, IOADDR(A_IMR_MAPPER(cpu) + R_IMR_INTERRUPT_MASK)); } + irq_data_update_effective_affinity(d, cpumask_of(i)); raw_spin_unlock_irqrestore(&sb1250_imr_lock, flags); return 0; diff --git a/arch/openrisc/include/asm/cmpxchg.h b/arch/openrisc/include/asm/cmpxchg.h index 8ee151c072e4..fcf1bc8db8fe 100644 --- a/arch/openrisc/include/asm/cmpxchg.h +++ b/arch/openrisc/include/asm/cmpxchg.h @@ -140,6 +140,8 @@ static inline unsigned long __cmpxchg(volatile void *ptr, unsigned long old, sizeof(*(ptr))); \ }) +#define arch_cmpxchg_local arch_cmpxchg + /* * This function doesn't exist, so you'll get a linker error if * something tries to do an invalidly-sized xchg(). diff --git a/arch/parisc/include/uapi/asm/socket.h b/arch/parisc/include/uapi/asm/socket.h index c16ec36dfee6..f3a3815c7dc2 100644 --- a/arch/parisc/include/uapi/asm/socket.h +++ b/arch/parisc/include/uapi/asm/socket.h @@ -147,6 +147,8 @@ #define SO_INQ 0x4052 #define SCM_INQ SO_INQ +#define SO_RIGHTS_NOTRUNC 0x4053 + #if !defined(__KERNEL__) #if __BITS_PER_LONG == 64 diff --git a/arch/parisc/kernel/perf_regs.c b/arch/parisc/kernel/perf_regs.c index 68458e2f6197..87e6990569a7 100644 --- a/arch/parisc/kernel/perf_regs.c +++ b/arch/parisc/kernel/perf_regs.c @@ -53,9 +53,3 @@ u64 perf_reg_abi(struct task_struct *task) return PERF_SAMPLE_REGS_ABI_64; } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} diff --git a/arch/powerpc/include/asm/interrupt.h b/arch/powerpc/include/asm/interrupt.h index eb0e4a20b818..af8c7df0ab9d 100644 --- a/arch/powerpc/include/asm/interrupt.h +++ b/arch/powerpc/include/asm/interrupt.h @@ -72,6 +72,7 @@ #include #include #include +#include #include #ifdef CONFIG_PPC_IRQ_SOFT_MASK_DEBUG @@ -326,7 +327,7 @@ static inline void interrupt_nmi_enter_prepare(struct pt_regs *regs, struct inte */ if (IS_ENABLED(CONFIG_PPC_BOOK3S_64) && firmware_has_feature(FW_FEATURE_LPAR) && - !radix_enabled()) + !early_radix_enabled()) return; /* @@ -355,7 +356,7 @@ static inline void interrupt_nmi_exit_prepare(struct pt_regs *regs, struct inter nmi_exit(); } else if (IS_ENABLED(CONFIG_PPC_BOOK3S_64) && firmware_has_feature(FW_FEATURE_LPAR) && - !radix_enabled()) { + !early_radix_enabled()) { // no nmi_exit for a pseries hash guest taking a real mode exception } else if (IS_ENABLED(CONFIG_KASAN)) { // no nmi_exit for KASAN in real mode diff --git a/arch/powerpc/kernel/watchdog.c b/arch/powerpc/kernel/watchdog.c index 2429cb1c7baa..b3b052026194 100644 --- a/arch/powerpc/kernel/watchdog.c +++ b/arch/powerpc/kernel/watchdog.c @@ -482,6 +482,9 @@ static void start_watchdog(void *arg) if (!(watchdog_enabled & WATCHDOG_HARDLOCKUP_ENABLED)) return; + if (!watchdog_thresh) + return; + if (!cpumask_test_cpu(cpu, &watchdog_cpumask)) return; diff --git a/arch/powerpc/net/bpf_jit.h b/arch/powerpc/net/bpf_jit.h index ae2c92a8b6e7..4d9cd2151057 100644 --- a/arch/powerpc/net/bpf_jit.h +++ b/arch/powerpc/net/bpf_jit.h @@ -203,10 +203,11 @@ int bpf_jit_emit_func_call_rel(u32 *image, u32 *fimage, struct codegen_context * int bpf_jit_build_body(struct bpf_prog *fp, u32 *image, u32 *fimage, struct codegen_context *ctx, u32 *addrs, int pass, bool extra_pass); void bpf_jit_build_prologue(u32 *image, struct codegen_context *ctx); -void bpf_jit_build_epilogue(u32 *image, struct codegen_context *ctx); -void bpf_jit_build_fentry_stubs(u32 *image, struct codegen_context *ctx); +void bpf_jit_build_epilogue(u32 *image, u32 *fimage, struct codegen_context *ctx); +void bpf_jit_build_fentry_stubs(u32 *image, u32 *fimage, struct codegen_context *ctx); void bpf_jit_realloc_regs(struct codegen_context *ctx); -int bpf_jit_emit_exit_insn(u32 *image, struct codegen_context *ctx, int tmp_reg, long exit_addr); +int bpf_jit_emit_exit_insn(u32 *image, u32 *fimage, struct codegen_context *ctx, int tmp_reg, + long exit_addr); int bpf_add_extable_entry(struct bpf_prog *fp, u32 *image, u32 *fimage, int pass, struct codegen_context *ctx, int insn_idx, diff --git a/arch/powerpc/net/bpf_jit_comp.c b/arch/powerpc/net/bpf_jit_comp.c index 829b60ae485f..f23ed48c4e32 100644 --- a/arch/powerpc/net/bpf_jit_comp.c +++ b/arch/powerpc/net/bpf_jit_comp.c @@ -49,11 +49,35 @@ asm ( " .popsection ;" ); -void bpf_jit_build_fentry_stubs(u32 *image, struct codegen_context *ctx) +void bpf_jit_build_fentry_stubs(u32 *image, u32 *fimage, struct codegen_context *ctx) { int ool_stub_idx, long_branch_stub_idx; + int stub_sz; /* + * The dummy_tramp_addr field is placed at bottom of Long branch stub. + * Align the mis-aligned dummy_tramp_addr field in the fimage. + * The alignment NOP must appear before OOL stub, to make + * ool_stub_idx & long_branch_stub_idx constant from end. + * + * The fimage can be non 8-byte aligned, so final alignment depends + * on start of fimage and the stub's instruction count. The + * stubs block has 11 instructions (with CONFIG_PPC_FTRACE_OUT_OF_LINE) + * or 10 instructions (without) before dummy_tramp_addr field. Emit a + * NOP if the address of dummy_tramp_addr is non aligned. + * + * In pass=0 when image==NULL, conservatively account for space + * required to accommodate alignment NOP. In case final pass skips + * emitting alignment NOP, the image buffer have 4 spare bytes and + * jited_len signifies correct program size. + */ + + stub_sz = IS_ENABLED(CONFIG_PPC_FTRACE_OUT_OF_LINE) ? 44 : 40; + if (!image || !IS_ALIGNED((unsigned long)fimage + ctx->idx*4 + stub_sz, SZL)) + EMIT(PPC_RAW_NOP()); + + /* + * nop // optional, for alignment of dummy_tramp_addr * Out-of-line stub: * mflr r0 * [b|bl] tramp @@ -70,34 +94,37 @@ void bpf_jit_build_fentry_stubs(u32 *image, struct codegen_context *ctx) /* * Long branch stub: - * .long * mflr r11 * bcl 20,31,$+4 - * mflr r12 - * ld r12, -8-SZL(r12) + * mflr r12 // lr/r12 stores pc of current(this) inst. + * ld r12, 20(r12) // offset(dummy_tramp_addr) from prev inst. is 20 * mtctr r12 - * mtlr r11 // needed to retain ftrace ABI + * mtlr r11 // needed to retain ftrace ABI * bctr + * .long // SZL bytes aligned */ - if (image) - *((unsigned long *)&image[ctx->idx]) = (unsigned long)dummy_tramp; - ctx->idx += SZL / 4; long_branch_stub_idx = ctx->idx; EMIT(PPC_RAW_MFLR(_R11)); EMIT(PPC_RAW_BCL4()); EMIT(PPC_RAW_MFLR(_R12)); - EMIT(PPC_RAW_LL(_R12, _R12, -8-SZL)); + EMIT(PPC_RAW_LL(_R12, _R12, 20)); EMIT(PPC_RAW_MTCTR(_R12)); EMIT(PPC_RAW_MTLR(_R11)); EMIT(PPC_RAW_BCTR()); + if (image) + *((unsigned long *)&image[ctx->idx]) = (unsigned long)dummy_tramp; + + ctx->idx += SZL / 4; + if (!bpf_jit_ool_stub) { bpf_jit_ool_stub = (ctx->idx - ool_stub_idx) * 4; bpf_jit_long_branch_stub = (ctx->idx - long_branch_stub_idx) * 4; } } -int bpf_jit_emit_exit_insn(u32 *image, struct codegen_context *ctx, int tmp_reg, long exit_addr) +int bpf_jit_emit_exit_insn(u32 *image, u32 *fimage, struct codegen_context *ctx, + int tmp_reg, long exit_addr) { if (exit_addr && is_offset_in_branch_range(exit_addr - (long)(ctx->idx * 4))) { PPC_JMP(exit_addr); @@ -106,7 +133,7 @@ int bpf_jit_emit_exit_insn(u32 *image, struct codegen_context *ctx, int tmp_reg, PPC_JMP(ctx->alt_exit_addr); } else { ctx->alt_exit_addr = ctx->idx * 4; - bpf_jit_build_epilogue(image, ctx); + bpf_jit_build_epilogue(image, fimage, ctx); } return 0; @@ -237,7 +264,7 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_prog *fp) */ bpf_jit_build_prologue(NULL, &cgctx); addrs[fp->len] = cgctx.idx * 4; - bpf_jit_build_epilogue(NULL, &cgctx); + bpf_jit_build_epilogue(NULL, NULL, &cgctx); fixup_len = fp->aux->num_exentries * BPF_FIXUP_LEN * 4; extable_len = fp->aux->num_exentries * sizeof(struct exception_table_entry); @@ -276,7 +303,7 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_prog *fp) goto out_addrs; } addrs[fp->len] = cgctx.idx * 4; - bpf_jit_build_epilogue(code_base, &cgctx); + bpf_jit_build_epilogue(code_base, fcode_base, &cgctx); proglen = cgctx.idx * 4; @@ -1103,6 +1130,7 @@ static void do_isync(void *info __maybe_unused) * bpf_func: * [nop|b] ool_stub * 2. Out-of-line stub: + * nop // optional nop for alignment * ool_stub: * mflr r0 * [b|bl] / @@ -1110,14 +1138,14 @@ static void do_isync(void *info __maybe_unused) * b bpf_func + 4 * 3. Long branch stub: * long_branch_stub: - * .long / * mflr r11 * bcl 20,31,$+4 * mflr r12 - * ld r12, -16(r12) + * ld r12, 20(r12) * mtctr r12 * mtlr r11 // needed to retain ftrace ABI * bctr + * .long / * * dummy_tramp is used to reduce synchronization requirements. * @@ -1217,10 +1245,12 @@ int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type poke_type, * 1. Update the address in the long branch stub: * If new_addr is out of range, we will have to use the long branch stub, so patch new_addr * here. Otherwise, revert to dummy_tramp, but only if we had patched old_addr here. + * + * dummy_tramp_addr moved to bottom of long branch stub. */ if ((new_addr && !is_offset_in_branch_range(new_addr - ip)) || (old_addr && !is_offset_in_branch_range(old_addr - ip))) - ret = patch_ulong((void *)(bpf_func_end - bpf_jit_long_branch_stub - SZL), + ret = patch_ulong((void *)(bpf_func_end - SZL), /* SZL: dummy_tramp_addr offset */ (new_addr && !is_offset_in_branch_range(new_addr - ip)) ? (unsigned long)new_addr : (unsigned long)dummy_tramp); if (ret) diff --git a/arch/powerpc/net/bpf_jit_comp32.c b/arch/powerpc/net/bpf_jit_comp32.c index 3087e744fb25..4b78dd8cfb45 100644 --- a/arch/powerpc/net/bpf_jit_comp32.c +++ b/arch/powerpc/net/bpf_jit_comp32.c @@ -194,7 +194,7 @@ static void bpf_jit_emit_common_epilogue(u32 *image, struct codegen_context *ctx } -void bpf_jit_build_epilogue(u32 *image, struct codegen_context *ctx) +void bpf_jit_build_epilogue(u32 *image, u32 *fimage, struct codegen_context *ctx) { EMIT(PPC_RAW_MR(_R3, bpf_to_ppc(BPF_REG_0))); @@ -202,7 +202,7 @@ void bpf_jit_build_epilogue(u32 *image, struct codegen_context *ctx) EMIT(PPC_RAW_BLR()); - bpf_jit_build_fentry_stubs(image, ctx); + bpf_jit_build_fentry_stubs(image, fimage, ctx); } /* Relative offset needs to be calculated based on final image location */ @@ -1114,7 +1114,8 @@ int bpf_jit_build_body(struct bpf_prog *fp, u32 *image, u32 *fimage, struct code * we'll just fall through to the epilogue. */ if (i != flen - 1) { - ret = bpf_jit_emit_exit_insn(image, ctx, _R0, exit_addr); + ret = bpf_jit_emit_exit_insn(image, fimage, + ctx, _R0, exit_addr); if (ret) return ret; } diff --git a/arch/powerpc/net/bpf_jit_comp64.c b/arch/powerpc/net/bpf_jit_comp64.c index 94f3f031d039..be79bd555e21 100644 --- a/arch/powerpc/net/bpf_jit_comp64.c +++ b/arch/powerpc/net/bpf_jit_comp64.c @@ -209,7 +209,7 @@ static void bpf_jit_emit_common_epilogue(u32 *image, struct codegen_context *ctx } } -void bpf_jit_build_epilogue(u32 *image, struct codegen_context *ctx) +void bpf_jit_build_epilogue(u32 *image, u32 *fimage, struct codegen_context *ctx) { bpf_jit_emit_common_epilogue(image, ctx); @@ -218,7 +218,7 @@ void bpf_jit_build_epilogue(u32 *image, struct codegen_context *ctx) EMIT(PPC_RAW_BLR()); - bpf_jit_build_fentry_stubs(image, ctx); + bpf_jit_build_fentry_stubs(image, fimage, ctx); } int bpf_jit_emit_func_call_rel(u32 *image, u32 *fimage, struct codegen_context *ctx, u64 func) @@ -1461,7 +1461,8 @@ int bpf_jit_build_body(struct bpf_prog *fp, u32 *image, u32 *fimage, struct code * we'll just fall through to the epilogue. */ if (i != flen - 1) { - ret = bpf_jit_emit_exit_insn(image, ctx, tmp1_reg, exit_addr); + ret = bpf_jit_emit_exit_insn(image, fimage, ctx, + tmp1_reg, exit_addr); if (ret) return ret; } diff --git a/arch/riscv/kernel/perf_regs.c b/arch/riscv/kernel/perf_regs.c index fd304a248de6..3bba8deababb 100644 --- a/arch/riscv/kernel/perf_regs.c +++ b/arch/riscv/kernel/perf_regs.c @@ -35,9 +35,3 @@ u64 perf_reg_abi(struct task_struct *task) #endif } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} diff --git a/arch/sparc/include/uapi/asm/socket.h b/arch/sparc/include/uapi/asm/socket.h index 71befa109e1c..7907f3b1f0ee 100644 --- a/arch/sparc/include/uapi/asm/socket.h +++ b/arch/sparc/include/uapi/asm/socket.h @@ -148,6 +148,8 @@ #define SO_INQ 0x005d #define SCM_INQ SO_INQ +#define SO_RIGHTS_NOTRUNC 0x005e + #if !defined(__KERNEL__) diff --git a/arch/um/drivers/vector_transports.c b/arch/um/drivers/vector_transports.c index 0794d23f07cb..92a127b5d54c 100644 --- a/arch/um/drivers/vector_transports.c +++ b/arch/um/drivers/vector_transports.c @@ -209,6 +209,7 @@ static int raw_verify_header( if ((vheader->flags & VIRTIO_NET_HDR_F_DATA_VALID) > 0) return 1; + skb_set_network_header(skb, ETH_HLEN); virtio_net_hdr_to_skb(skb, vheader, virtio_legacy_is_little_endian()); return 0; } diff --git a/arch/x86/events/amd/ibs.c b/arch/x86/events/amd/ibs.c index 23d834e7b565..d57b34a72ddd 100644 --- a/arch/x86/events/amd/ibs.c +++ b/arch/x86/events/amd/ibs.c @@ -1339,6 +1339,56 @@ static int perf_ibs_handle_irq(struct perf_ibs *perf_ibs, struct pt_regs *iregs) throttle = perf_event_account_interrupt(event); goto out; } + + /* + * IBS captured RIP is out of sync with NMI pt_regs due to NMI + * delivery latency. Use NMI pt_regs for PERF_SAMPLE_REGS_USER. + * + * Note: Valid user regs are required for PERF_SAMPLE_STACK_USER. + */ + if (event->attr.sample_type & (PERF_SAMPLE_REGS_USER | + PERF_SAMPLE_STACK_USER)) { + perf_sample_regs_user(&data.regs_user, iregs); + + /* + * Don't update dyn_size if user has not requested for + * PERF_SAMPLE_REGS_USER. + */ + if (event->attr.sample_type & PERF_SAMPLE_REGS_USER) { + /* regs dump ABI info */ + int size = sizeof(u64); + + if (data.regs_user.regs) { + u64 mask = event->attr.sample_regs_user; + size += hweight64(mask) * sizeof(u64); + } + + data.dyn_size += size; + } + + data.sample_flags |= PERF_SAMPLE_REGS_USER; + } + + /* + * IBS captured RIP is out of sync with NMI pt_regs due to NMI + * delivery latency. Use NMI pt_regs for PERF_SAMPLE_REGS_INTR. + */ + if (event->attr.sample_type & PERF_SAMPLE_REGS_INTR) { + /* regs dump ABI info */ + int size = sizeof(u64); + + perf_sample_regs_intr(&data.regs_intr, iregs, + event->attr.exclude_kernel); + + if (data.regs_intr.regs) { + u64 mask = event->attr.sample_regs_intr; + size += hweight64(mask) * sizeof(u64); + } + + data.dyn_size += size; + data.sample_flags |= PERF_SAMPLE_REGS_INTR; + } + /* * Prevent leaking physical addresses to unprivileged users. Skip * PERF_SAMPLE_PHYS_ADDR check since generic code prevents it for diff --git a/arch/x86/events/amd/uncore.c b/arch/x86/events/amd/uncore.c index c96048122272..8714e4b36ff3 100644 --- a/arch/x86/events/amd/uncore.c +++ b/arch/x86/events/amd/uncore.c @@ -609,7 +609,7 @@ static void amd_uncore_ctx_move(struct amd_uncore *uncore, unsigned int cpu) for (i = 0; i < uncore->num_pmus; i++) { pmu = &uncore->pmus[i]; curr = *per_cpu_ptr(pmu->ctx, cpu); - if (!curr) + if (!curr || curr->cpu != cpu) continue; /* Migrate to a shared sibling if possible */ diff --git a/arch/x86/kernel/cpu/amd.c b/arch/x86/kernel/cpu/amd.c index ef55c76a3906..fc5d217d20aa 100644 --- a/arch/x86/kernel/cpu/amd.c +++ b/arch/x86/kernel/cpu/amd.c @@ -1370,7 +1370,8 @@ static __init int print_s5_reset_status_mmio(void) u32 value; int i; - if (!cpu_feature_enabled(X86_FEATURE_ZEN)) + if (!cpu_feature_enabled(X86_FEATURE_ZEN) || + cpu_feature_enabled(X86_FEATURE_HYPERVISOR)) return 0; addr = ioremap(FCH_PM_BASE + FCH_PM_S5_RESET_STATUS, sizeof(value)); diff --git a/arch/x86/kernel/ldt.c b/arch/x86/kernel/ldt.c index 0f19ef355f5f..329daba099b2 100644 --- a/arch/x86/kernel/ldt.c +++ b/arch/x86/kernel/ldt.c @@ -43,7 +43,7 @@ void load_mm_ldt(struct mm_struct *mm) { struct ldt_struct *ldt; - /* READ_ONCE synchronizes with smp_store_release */ + /* Pairs with WRITE_ONCE() in install_ldt() */ ldt = READ_ONCE(mm->context.ldt); /* @@ -422,8 +422,14 @@ static void install_ldt(struct mm_struct *mm, struct ldt_struct *ldt) { mutex_lock(&mm->context.lock); - /* Synchronizes with READ_ONCE in load_mm_ldt. */ - smp_store_release(&mm->context.ldt, ldt); + /* + * Ensure that new mm user CPUs either see the new LDT value + * or get an IPI. Make the store visible before reading + * mm_cpumask(). New mm users make their mm_cpumask() writes + * visible before reading mm->context.ldt. + */ + WRITE_ONCE(mm->context.ldt, ldt); + smp_mb(); /* Activate the LDT for all CPUs using currents mm. */ on_each_cpu_mask(mm_cpumask(mm), flush_ldt, mm, true); diff --git a/arch/x86/kernel/perf_regs.c b/arch/x86/kernel/perf_regs.c index 624703af80a1..81204cb7f723 100644 --- a/arch/x86/kernel/perf_regs.c +++ b/arch/x86/kernel/perf_regs.c @@ -100,12 +100,6 @@ u64 perf_reg_abi(struct task_struct *task) return PERF_SAMPLE_REGS_ABI_32; } -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} #else /* CONFIG_X86_64 */ #define REG_NOSUPPORT ((1ULL << PERF_REG_X86_DS) | \ (1ULL << PERF_REG_X86_ES) | \ diff --git a/arch/x86/kvm/Kconfig b/arch/x86/kvm/Kconfig index 278f08194ec8..d916bd766c94 100644 --- a/arch/x86/kvm/Kconfig +++ b/arch/x86/kvm/Kconfig @@ -37,6 +37,7 @@ config KVM_X86 select SCHED_INFO select PERF_EVENTS select GUEST_PERF_EVENTS + select PERF_GUEST_MEDIATED_PMU select HAVE_KVM_MSI select HAVE_KVM_CPU_RELAX_INTERCEPT select HAVE_KVM_NO_POLL diff --git a/arch/x86/kvm/vmx/tdx.c b/arch/x86/kvm/vmx/tdx.c index 43d6b20dfbb1..0a0fd87fd53e 100644 --- a/arch/x86/kvm/vmx/tdx.c +++ b/arch/x86/kvm/vmx/tdx.c @@ -2058,7 +2058,7 @@ int tdx_complete_emulated_msr(struct kvm_vcpu *vcpu, int err) } -int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath) +static int __tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath) { struct vcpu_tdx *tdx = to_tdx(vcpu); u64 vp_enter_ret = tdx->vp_enter_ret; @@ -2159,6 +2159,8 @@ int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath) case EXIT_REASON_NOTIFY: /* NMI blocking state is handled by TDX module */ return __vt_handle_notify(vcpu, vmx_get_exit_qual(vcpu)); + case EXIT_REASON_BUS_LOCK: + return vt_handle_bus_lock_vmexit(vcpu); default: break; } @@ -2172,6 +2174,22 @@ int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath) return 0; } +int tdx_handle_exit(struct kvm_vcpu *vcpu, fastpath_t fastpath) +{ + int ret = __tdx_handle_exit(vcpu, fastpath); + + /* Exit to user space when bus lock was detected */ + if (vmx_get_exit_reason(vcpu).bus_lock_detected) { + if (ret > 0) { + vcpu->run->exit_reason = KVM_EXIT_X86_BUS_LOCK; + ret = 0; + } + + vcpu->run->flags |= KVM_RUN_X86_BUS_LOCK; + } + return ret; +} + void tdx_get_exit_info(struct kvm_vcpu *vcpu, u32 *reason, u64 *info1, u64 *info2, u32 *intr_info, u32 *error_code) { @@ -3167,6 +3185,10 @@ static int tdx_vcpu_init(struct kvm_vcpu *vcpu, struct kvm_tdx_cmd *cmd) vcpu->kvm->arch.notify_window); } + if (vcpu->kvm->arch.bus_lock_detection_enabled) + td_vmcs_setbit32(tdx, SECONDARY_VM_EXEC_CONTROL, + SECONDARY_EXEC_BUS_LOCK_DETECTION); + tdx->state = VCPU_TD_STATE_INITIALIZED; return 0; diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c index 39cf6974e11e..86f50102f8b7 100644 --- a/arch/x86/net/bpf_jit_comp.c +++ b/arch/x86/net/bpf_jit_comp.c @@ -2421,6 +2421,18 @@ st: if (is_imm8(insn->off)) } if (!imm32) return -EINVAL; + if (func == (u8 *)arch_bpf_timed_may_goto) { + u32 fp = priv_frame_ptr ? X86_REG_R9 : BPF_REG_FP; + + /* + * AX has the offset of count and timestamp + * in the stack. Turn it into a pointer. + * add r10, rbp or add r10, r9 + */ + maybe_emit_mod(&prog, BPF_REG_AX, fp, true); + EMIT2(0x01, add_2reg(0xC0, BPF_REG_AX, fp)); + ip += 3; + } if (priv_frame_ptr) { push_r9(&prog); ip += 2; diff --git a/arch/x86/net/bpf_timed_may_goto.S b/arch/x86/net/bpf_timed_may_goto.S index 54c690cae190..6c6e03f725a3 100644 --- a/arch/x86/net/bpf_timed_may_goto.S +++ b/arch/x86/net/bpf_timed_may_goto.S @@ -11,12 +11,6 @@ SYM_FUNC_START(arch_bpf_timed_may_goto) ANNOTATE_NOENDBR - /* - * r10 passes us stack depth, load the pointer to count and timestamp - * into r10 by adding it to BPF frame pointer. - */ - leaq (%rbp, %r10, 1), %r10 - /* Setup frame. */ pushq %rbp movq %rsp, %rbp @@ -30,8 +24,8 @@ SYM_FUNC_START(arch_bpf_timed_may_goto) pushq %r8 /* - * r10 has the pointer to count and timestamp, pass it as first - * argument. + * r10 has the pointer to count and timestamp. JIT added the frame + * pointer to the offset. Pass it as first argument. */ movq %r10, %rdi diff --git a/arch/x86/video/video-common.c b/arch/x86/video/video-common.c index e5fb3cf885fb..3482efa4045e 100644 --- a/arch/x86/video/video-common.c +++ b/arch/x86/video/video-common.c @@ -45,7 +45,7 @@ bool video_is_primary_device(struct device *dev) #ifdef CONFIG_SCREEN_INFO numres = screen_info_resources(si, res, ARRAY_SIZE(res)); - if (numres > 0) { + if (numres > 0 && __screen_info_has_lfb(screen_info_video_type(si))) { for (i = 0; i < numres; ++i) { if (!(res[i].flags & IORESOURCE_MEM)) continue; diff --git a/block/blk-cgroup.c b/block/blk-cgroup.c index 610ea63ad386..36e6fdad93bd 100644 --- a/block/blk-cgroup.c +++ b/block/blk-cgroup.c @@ -917,7 +917,11 @@ int blkg_conf_prep(struct blkcg *blkcg, const struct blkcg_policy *pol, parent = blkcg_parent(parent); } - /* Drop locks to do new blkg allocation with GFP_KERNEL. */ + /* + * Drop the spinlock to allocate the new blkg. rq_qos_mutex and + * blkcg_mutex stay held, and both are taken with the queue + * frozen elsewhere: GFP_NOIO. + */ spin_unlock_irq(&q->queue_lock); new_blkg = blkg_alloc(pos, disk, GFP_NOIO); @@ -926,7 +930,7 @@ int blkg_conf_prep(struct blkcg *blkcg, const struct blkcg_policy *pol, goto fail_exit; } - if (radix_tree_preload(GFP_KERNEL)) { + if (radix_tree_preload(GFP_NOIO)) { blkg_free(new_blkg); ret = -ENOMEM; goto fail_exit; @@ -1646,7 +1650,8 @@ int blkcg_activate_policy(struct gendisk *disk, const struct blkcg_policy *pol) if (!pd) { /* * GFP_NOWAIT failed. Free the existing one and - * prealloc for @blkg w/ GFP_KERNEL. + * prealloc for @blkg w/ GFP_NOIO: blkcg_mutex is held, + * and a bio based queue has not been frozen above. */ if (pinned_blkg) blkg_put(pinned_blkg); @@ -1658,7 +1663,7 @@ int blkcg_activate_policy(struct gendisk *disk, const struct blkcg_policy *pol) if (pd_prealloc) pol->pd_free_fn(pd_prealloc); pd_prealloc = pol->pd_alloc_fn(disk, blkg->blkcg, - GFP_KERNEL); + GFP_NOIO); if (pd_prealloc) goto retry; else diff --git a/block/blk-core.c b/block/blk-core.c index c2300b201d4f..0eba4243ebfd 100644 --- a/block/blk-core.c +++ b/block/blk-core.c @@ -463,6 +463,7 @@ struct request_queue *blk_alloc_queue(struct queue_limits *lim, int node_id) fs_reclaim_release(GFP_KERNEL); q->nr_requests = BLKDEV_DEFAULT_RQ; + q->async_depth = BLKDEV_DEFAULT_RQ; return q; diff --git a/block/blk-iocost.c b/block/blk-iocost.c index a05e5cfd0ac0..6c3ba6209047 100644 --- a/block/blk-iocost.c +++ b/block/blk-iocost.c @@ -2982,11 +2982,12 @@ static int blk_iocost_init(struct gendisk *disk) struct ioc *ioc; int i, cpu, ret; - ioc = kzalloc(sizeof(*ioc), GFP_KERNEL); + /* The caller holds rq_qos_mutex, which is taken with the queue frozen */ + ioc = kzalloc(sizeof(*ioc), GFP_NOIO); if (!ioc) return -ENOMEM; - ioc->pcpu_stat = alloc_percpu(struct ioc_pcpu_stat); + ioc->pcpu_stat = alloc_percpu_gfp(struct ioc_pcpu_stat, GFP_NOIO); if (!ioc->pcpu_stat) { kfree(ioc); return -ENOMEM; diff --git a/block/blk-iolatency.c b/block/blk-iolatency.c index 741c804c217b..3e0c9ec5df36 100644 --- a/block/blk-iolatency.c +++ b/block/blk-iolatency.c @@ -761,7 +761,8 @@ static int blk_iolatency_init(struct gendisk *disk) struct blk_iolatency *blkiolat; int ret; - blkiolat = kzalloc(sizeof(*blkiolat), GFP_KERNEL); + /* The caller holds rq_qos_mutex, which is taken with the queue frozen */ + blkiolat = kzalloc(sizeof(*blkiolat), GFP_NOIO); if (!blkiolat) return -ENOMEM; diff --git a/block/blk-mq-dma.c b/block/blk-mq-dma.c index b7c26599f6b0..fef1448453f8 100644 --- a/block/blk-mq-dma.c +++ b/block/blk-mq-dma.c @@ -177,6 +177,8 @@ static bool blk_dma_map_iter_start(struct request *req, struct device *dma_dev, bio_integrity(req->bio)->bip_flags |= BIP_P2P_DMA; else req->cmd_flags |= REQ_P2PDMA; + /* don't leave the state of an earlier mapping to the caller */ + memset(state, 0, sizeof(*state)); return blk_dma_map_bus(iter, &vec); case PCI_P2PDMA_MAP_THRU_HOST_BRIDGE: /* diff --git a/block/blk-mq-sched.c b/block/blk-mq-sched.c index 128f2be9d420..d18175ffa1b1 100644 --- a/block/blk-mq-sched.c +++ b/block/blk-mq-sched.c @@ -374,7 +374,7 @@ bool blk_mq_sched_try_insert_merge(struct request_queue *q, struct request *rq, } EXPORT_SYMBOL_GPL(blk_mq_sched_try_insert_merge); -/* called in queue's release handler, tagset has gone away */ +/* Clear scheduler tags and reset queue state. */ static void blk_mq_sched_tags_teardown(struct request_queue *q, unsigned int flags) { struct blk_mq_hw_ctx *hctx; @@ -385,6 +385,10 @@ static void blk_mq_sched_tags_teardown(struct request_queue *q, unsigned int fla if (blk_mq_is_shared_tags(flags)) q->sched_shared_tags = NULL; + + blk_queue_flag_clear(QUEUE_FLAG_SQ_SCHED, q); + q->nr_requests = q->tag_set->queue_depth; + q->async_depth = q->tag_set->queue_depth; } void blk_mq_sched_reg_debugfs(struct request_queue *q) diff --git a/block/blk-mq.c b/block/blk-mq.c index 7bdc9b1d7b74..50c5c53e940f 100644 --- a/block/blk-mq.c +++ b/block/blk-mq.c @@ -4348,7 +4348,10 @@ static void blk_mq_del_queue_tag_set(struct request_queue *q) lockdep_assert_held(&set->tag_list_lock); + /* blk_mq_unquiesce_tagset() runs the hctxs, which are not RCU freed */ + spin_lock(&set->quiesce_lock); list_del_rcu(&q->tag_set_list); + spin_unlock(&set->quiesce_lock); if (list_is_singular(&set->tag_list)) { /* just transitioned to unshared */ set->flags &= ~BLK_MQ_F_TAG_QUEUE_SHARED; @@ -4704,6 +4707,7 @@ int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set, spin_lock_init(&q->requeue_lock); q->nr_requests = set->queue_depth; + q->async_depth = set->queue_depth; blk_mq_init_cpu_queues(q, set->nr_hw_queues); blk_mq_map_swqueue(q); @@ -5083,6 +5087,11 @@ struct elevator_tags *blk_mq_update_nr_requests(struct request_queue *q, q->elevator->et = et; } + /* + * Preserve relative value, both nr and async_depth are at most 16 bit + * value, no need to worry about overflow. + */ + q->async_depth = max(q->async_depth * nr / q->nr_requests, 1); q->nr_requests = nr; if (q->elevator && q->elevator->type->ops.depth_updated) q->elevator->type->ops.depth_updated(q); diff --git a/block/blk-sysfs.c b/block/blk-sysfs.c index af12526d866a..2b251460db45 100644 --- a/block/blk-sysfs.c +++ b/block/blk-sysfs.c @@ -133,6 +133,46 @@ queue_requests_store(struct gendisk *disk, const char *page, size_t count) return ret; } +static ssize_t queue_async_depth_show(struct gendisk *disk, char *page) +{ + guard(mutex)(&disk->queue->elevator_lock); + + return queue_var_show(disk->queue->async_depth, page); +} + +static ssize_t +queue_async_depth_store(struct gendisk *disk, const char *page, size_t count) +{ + struct request_queue *q = disk->queue; + unsigned int memflags; + unsigned long nr; + int ret; + + if (!queue_is_mq(q)) + return -EINVAL; + + ret = queue_var_store(&nr, page, count); + if (ret < 0) + return ret; + + if (nr == 0) + return -EINVAL; + + memflags = blk_mq_freeze_queue(q); + scoped_guard(mutex, &q->elevator_lock) { + if (q->elevator) { + q->async_depth = min(q->nr_requests, nr); + if (q->elevator->type->ops.depth_updated) + q->elevator->type->ops.depth_updated(q); + } else { + ret = -EINVAL; + } + } + blk_mq_unfreeze_queue(q, memflags); + + return ret; +} + static ssize_t queue_ra_show(struct gendisk *disk, char *page) { ssize_t ret; @@ -538,6 +578,7 @@ static struct queue_sysfs_entry _prefix##_entry = { \ } QUEUE_RW_ENTRY(queue_requests, "nr_requests"); +QUEUE_RW_ENTRY(queue_async_depth, "async_depth"); QUEUE_RW_ENTRY(queue_ra, "read_ahead_kb"); QUEUE_LIM_RW_ENTRY(queue_max_sectors, "max_sectors_kb"); QUEUE_LIM_RO_ENTRY(queue_max_hw_sectors, "max_hw_sectors_kb"); @@ -760,6 +801,7 @@ static struct attribute *blk_mq_queue_attrs[] = { */ &elv_iosched_entry.attr, &queue_requests_entry.attr, + &queue_async_depth_entry.attr, #ifdef CONFIG_BLK_WBT &queue_wb_lat_entry.attr, #endif diff --git a/block/blk-throttle.c b/block/blk-throttle.c index 36f8dc324d79..faf53bf75995 100644 --- a/block/blk-throttle.c +++ b/block/blk-throttle.c @@ -1327,7 +1327,8 @@ static int blk_throtl_init(struct gendisk *disk) unsigned int memflags; int ret; - td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node); + /* The caller holds rq_qos_mutex, which is taken with the queue frozen */ + td = kzalloc_node(sizeof(*td), GFP_NOIO, q->node); if (!td) return -ENOMEM; diff --git a/block/elevator.c b/block/elevator.c index 7a97998cd8bd..3bcd37c2aa34 100644 --- a/block/elevator.c +++ b/block/elevator.c @@ -589,6 +589,7 @@ static int elevator_switch(struct request_queue *q, struct elv_change_ctx *ctx) blk_queue_flag_clear(QUEUE_FLAG_SQ_SCHED, q); q->elevator = NULL; q->nr_requests = q->tag_set->queue_depth; + q->async_depth = q->tag_set->queue_depth; } blk_add_trace_msg(q, "elv switch: %s", ctx->name); diff --git a/block/genhd.c b/block/genhd.c index 6ba0e22ce9df..2bba931bd10a 100644 --- a/block/genhd.c +++ b/block/genhd.c @@ -1146,7 +1146,7 @@ static ssize_t disk_discard_alignment_show(struct device *dev, { struct gendisk *disk = dev_to_disk(dev); - return sysfs_emit(buf, "%d\n", bdev_alignment_offset(disk->part0)); + return sysfs_emit(buf, "%u\n", bdev_discard_alignment(disk->part0)); } static ssize_t diskseq_show(struct device *dev, diff --git a/block/partitions/efi.c b/block/partitions/efi.c index 7acba66eed48..d88321f6400a 100644 --- a/block/partitions/efi.c +++ b/block/partitions/efi.c @@ -461,6 +461,7 @@ static inline int is_pte_valid(const gpt_entry *pte, const u64 lastlba) { if ((!efi_guidcmp(pte->partition_type_guid, NULL_GUID)) || + le64_to_cpu(pte->starting_lba) > le64_to_cpu(pte->ending_lba) || le64_to_cpu(pte->starting_lba) > lastlba || le64_to_cpu(pte->ending_lba) > lastlba) return 0; diff --git a/crypto/essiv.c b/crypto/essiv.c index a47a3eab6935..3505b2769d93 100644 --- a/crypto/essiv.c +++ b/crypto/essiv.c @@ -250,7 +250,7 @@ static int essiv_aead_crypt(struct aead_request *req, bool enc) err = enc ? crypto_aead_encrypt(subreq) : crypto_aead_decrypt(subreq); - if (rctx->assoc && err != -EINPROGRESS && err != -EBUSY) + if (err != -EINPROGRESS && err != -EBUSY) kfree(rctx->assoc); return err; } diff --git a/drivers/accel/amdxdna/aie2_ctx.c b/drivers/accel/amdxdna/aie2_ctx.c index a87b24654c36..fb411887b647 100644 --- a/drivers/accel/amdxdna/aie2_ctx.c +++ b/drivers/accel/amdxdna/aie2_ctx.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -62,7 +63,7 @@ static void aie2_hwctx_status_restore(struct amdxdna_hwctx *hwctx) static void aie2_hwctx_stop(struct amdxdna_dev *xdna, struct amdxdna_hwctx *hwctx, struct drm_sched_job *bad_job) { - drm_sched_stop(&hwctx->priv->sched, bad_job); + drm_sched_stop(hwctx->priv->sched, bad_job); aie2_destroy_context(xdna->dev_handle, hwctx); } @@ -96,7 +97,7 @@ static int aie2_hwctx_restart(struct amdxdna_dev *xdna, struct amdxdna_hwctx *hw } out: - drm_sched_start(&hwctx->priv->sched, 0); + drm_sched_start(hwctx->priv->sched, 0); XDNA_DBG(xdna, "%s restarted, ret %d", hwctx->name, ret); return ret; } @@ -528,10 +529,19 @@ static void aie2_ctx_syncobj_destroy(struct amdxdna_hwctx *hwctx) drm_syncobj_put(hwctx->priv->syncobj); } -int aie2_hwctx_init(struct amdxdna_hwctx *hwctx) +void aie2_hwctx_sched_fini(struct amdxdna_dev_hdl *ndev) { - struct amdxdna_client *client = hwctx->client; - struct amdxdna_dev *xdna = client->xdna; + int i; + + for (i = 0; i < ndev->priv->hwctx_limit; i++) + drm_sched_fini(&ndev->hwctx_sched[i]); + + ida_destroy(&ndev->hwctx_sched_ida); +} + +int aie2_hwctx_sched_init(struct amdxdna_dev_hdl *ndev) +{ + struct amdxdna_dev *xdna = ndev->xdna; const struct drm_sched_init_args args = { .ops = &sched_ops, .num_rqs = DRM_SCHED_PRIORITY_COUNT, @@ -540,10 +550,57 @@ int aie2_hwctx_init(struct amdxdna_hwctx *hwctx) .name = "amdxdna_js", .dev = xdna->ddev.dev, }; - struct drm_gpu_scheduler *sched; + int i, ret; + + ndev->hwctx_sched = drmm_kcalloc(&xdna->ddev, ndev->priv->hwctx_limit, + sizeof(*ndev->hwctx_sched), GFP_KERNEL); + if (!ndev->hwctx_sched) + return -ENOMEM; + + for (i = 0; i < ndev->priv->hwctx_limit; i++) { + ret = drm_sched_init(&ndev->hwctx_sched[i], &args); + if (ret) { + XDNA_ERR(xdna, "Failed to init DRM scheduler. ret %d", ret); + goto fini_sched; + } + } + + ida_init(&ndev->hwctx_sched_ida); + + return 0; + +fini_sched: + while (--i >= 0) + drm_sched_fini(&ndev->hwctx_sched[i]); + + return ret; +} + +static struct drm_gpu_scheduler *aie2_hwctx_sched_alloc(struct amdxdna_dev_hdl *ndev) +{ + int ret; + + ret = ida_alloc_range(&ndev->hwctx_sched_ida, 0, + ndev->priv->hwctx_limit - 1, GFP_KERNEL); + if (ret < 0) + return ERR_PTR(ret); + + return &ndev->hwctx_sched[ret]; +} + +static void aie2_hwctx_sched_free(struct amdxdna_dev_hdl *ndev, + struct drm_gpu_scheduler *sched) +{ + ida_free(&ndev->hwctx_sched_ida, sched - ndev->hwctx_sched); +} + +int aie2_hwctx_init(struct amdxdna_hwctx *hwctx) +{ + struct amdxdna_client *client = hwctx->client; + struct amdxdna_dev *xdna = client->xdna; + struct amdxdna_dev_hdl *ndev = xdna->dev_handle; struct amdxdna_hwctx_priv *priv; struct amdxdna_gem_obj *heap; - struct amdxdna_dev_hdl *ndev; int i, ret; priv = kzalloc(sizeof(*hwctx->priv), GFP_KERNEL); @@ -551,13 +608,26 @@ int aie2_hwctx_init(struct amdxdna_hwctx *hwctx) return -ENOMEM; hwctx->priv = priv; + priv->sched = aie2_hwctx_sched_alloc(ndev); + if (IS_ERR(priv->sched)) { + ret = PTR_ERR(priv->sched); + goto free_priv; + } + + ret = drm_sched_entity_init(&priv->entity, DRM_SCHED_PRIORITY_NORMAL, + &priv->sched, 1, NULL); + if (ret) { + XDNA_ERR(xdna, "Failed to initial sched entity. ret %d", ret); + goto free_sched; + } + mutex_lock(&client->mm_lock); heap = client->dev_heap; if (!heap) { XDNA_ERR(xdna, "The client dev heap object not exist"); mutex_unlock(&client->mm_lock); ret = -ENOENT; - goto free_priv; + goto free_entity; } drm_gem_object_get(to_gobj(heap)); mutex_unlock(&client->mm_lock); @@ -590,30 +660,16 @@ int aie2_hwctx_init(struct amdxdna_hwctx *hwctx) priv->cmd_buf[i] = abo; } - sched = &priv->sched; mutex_init(&priv->io_lock); fs_reclaim_acquire(GFP_KERNEL); might_lock(&priv->io_lock); fs_reclaim_release(GFP_KERNEL); - ret = drm_sched_init(sched, &args); - if (ret) { - XDNA_ERR(xdna, "Failed to init DRM scheduler. ret %d", ret); - goto free_cmd_bufs; - } - - ret = drm_sched_entity_init(&priv->entity, DRM_SCHED_PRIORITY_NORMAL, - &sched, 1, NULL); - if (ret) { - XDNA_ERR(xdna, "Failed to initial sched entiry. ret %d", ret); - goto free_sched; - } - ret = aie2_hwctx_col_list(hwctx); if (ret) { XDNA_ERR(xdna, "Create col list failed, ret %d", ret); - goto free_entity; + goto free_cmd_bufs; } ret = amdxdna_pm_resume_get(xdna); @@ -641,7 +697,6 @@ int aie2_hwctx_init(struct amdxdna_hwctx *hwctx) amdxdna_pm_suspend_put(xdna); hwctx->status = HWCTX_STAT_INIT; - ndev = xdna->dev_handle; ndev->hwctx_num++; init_waitqueue_head(&priv->job_free_wq); @@ -655,10 +710,6 @@ int aie2_hwctx_init(struct amdxdna_hwctx *hwctx) amdxdna_pm_suspend_put(xdna); free_col_list: kfree(hwctx->col_list); -free_entity: - drm_sched_entity_destroy(&priv->entity); -free_sched: - drm_sched_fini(&priv->sched); free_cmd_bufs: for (i = 0; i < ARRAY_SIZE(priv->cmd_buf); i++) { if (!priv->cmd_buf[i]) @@ -668,6 +719,10 @@ int aie2_hwctx_init(struct amdxdna_hwctx *hwctx) amdxdna_gem_unpin(heap); put_heap: drm_gem_object_put(to_gobj(heap)); +free_entity: + drm_sched_entity_destroy(&priv->entity); +free_sched: + aie2_hwctx_sched_free(ndev, priv->sched); free_priv: kfree(priv); return ret; @@ -687,10 +742,10 @@ void aie2_hwctx_fini(struct amdxdna_hwctx *hwctx) aie2_hwctx_wait_for_idle(hwctx); /* Request fw to destroy hwctx and cancel the rest pending requests */ - drm_sched_stop(&hwctx->priv->sched, NULL); + drm_sched_stop(hwctx->priv->sched, NULL); aie2_release_resource(hwctx); hwctx->status = HWCTX_STAT_STOP; - drm_sched_start(&hwctx->priv->sched, 0); + drm_sched_start(hwctx->priv->sched, 0); mutex_unlock(&xdna->dev_lock); drm_sched_entity_destroy(&hwctx->priv->entity); @@ -701,7 +756,7 @@ void aie2_hwctx_fini(struct amdxdna_hwctx *hwctx) atomic64_read(&hwctx->job_free_cnt)); mutex_lock(&xdna->dev_lock); - drm_sched_fini(&hwctx->priv->sched); + aie2_hwctx_sched_free(ndev, hwctx->priv->sched); aie2_ctx_syncobj_destroy(hwctx); for (idx = 0; idx < ARRAY_SIZE(hwctx->priv->cmd_buf); idx++) diff --git a/drivers/accel/amdxdna/aie2_pci.c b/drivers/accel/amdxdna/aie2_pci.c index 4a7d1feac6a5..5a030da5b9d4 100644 --- a/drivers/accel/amdxdna/aie2_pci.c +++ b/drivers/accel/amdxdna/aie2_pci.c @@ -502,11 +502,15 @@ static int aie2_init(struct amdxdna_dev *xdna) ndev->priv = xdna->dev_info->dev_priv; ndev->xdna = xdna; + ret = aie2_hwctx_sched_init(ndev); + if (ret) + return ret; + ret = request_firmware(&fw, ndev->priv->fw_path, &pdev->dev); if (ret) { XDNA_ERR(xdna, "failed to request_firmware %s, ret %d", ndev->priv->fw_path, ret); - return ret; + goto free_hwctx_sched; } ret = pcim_enable_device(pdev); @@ -597,6 +601,8 @@ static int aie2_init(struct amdxdna_dev *xdna) aie2_hw_stop(xdna); release_fw: release_firmware(fw); +free_hwctx_sched: + aie2_hwctx_sched_fini(ndev); return ret; } @@ -605,6 +611,7 @@ static void aie2_fini(struct amdxdna_dev *xdna) { amdxdna_pm_fini(xdna); aie2_hw_stop(xdna); + aie2_hwctx_sched_fini(xdna->dev_handle); } static int aie2_get_aie_status(struct amdxdna_client *client, diff --git a/drivers/accel/amdxdna/aie2_pci.h b/drivers/accel/amdxdna/aie2_pci.h index 7d56f4bca3d6..a3f66e87d0a5 100644 --- a/drivers/accel/amdxdna/aie2_pci.h +++ b/drivers/accel/amdxdna/aie2_pci.h @@ -133,7 +133,7 @@ struct amdxdna_hwctx_priv { struct amdxdna_gem_obj *heap; void *mbox_chann; - struct drm_gpu_scheduler sched; + struct drm_gpu_scheduler *sched; struct drm_sched_entity entity; struct mutex io_lock; /* protect seq and cmd order */ @@ -173,6 +173,8 @@ struct amdxdna_dev_hdl { u32 total_col; struct aie_version version; struct aie_metadata metadata; + struct drm_gpu_scheduler *hwctx_sched; + struct ida hwctx_sched_ida; /* power management and clock*/ enum amdxdna_power_mode_type pw_mode; @@ -293,6 +295,8 @@ int aie2_sync_bo(struct amdxdna_hwctx *hwctx, struct amdxdna_sched_job *job, /* aie2_hwctx.c */ int aie2_hwctx_init(struct amdxdna_hwctx *hwctx); void aie2_hwctx_fini(struct amdxdna_hwctx *hwctx); +int aie2_hwctx_sched_init(struct amdxdna_dev_hdl *ndev); +void aie2_hwctx_sched_fini(struct amdxdna_dev_hdl *ndev); int aie2_hwctx_config(struct amdxdna_hwctx *hwctx, u32 type, u64 value, void *buf, u32 size); void aie2_hwctx_suspend(struct amdxdna_client *client); int aie2_hwctx_resume(struct amdxdna_client *client); diff --git a/drivers/accel/amdxdna/amdxdna_gem.c b/drivers/accel/amdxdna/amdxdna_gem.c index 412b48f49fa2..cc22981d7359 100644 --- a/drivers/accel/amdxdna/amdxdna_gem.c +++ b/drivers/accel/amdxdna/amdxdna_gem.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include "amdxdna_ctx.h" @@ -106,13 +107,16 @@ static bool amdxdna_hmm_invalidate(struct mmu_interval_notifier *mni, struct amdxdna_gem_obj *abo = mapp->abo; struct amdxdna_dev *xdna; + if (!mmu_notifier_range_blockable(range)) + return false; + + if (mapp->unmapped) + return true; + xdna = to_xdna_dev(to_gobj(abo)->dev); XDNA_DBG(xdna, "Invalidating range 0x%lx, 0x%lx, type %d", mapp->range.start, mapp->range.end, abo->type); - if (!mmu_notifier_range_blockable(range)) - return false; - down_write(&xdna->notifier_lock); abo->mem.map_invalid = true; mapp->invalid = true; @@ -123,10 +127,8 @@ static bool amdxdna_hmm_invalidate(struct mmu_interval_notifier *mni, if (range->event == MMU_NOTIFY_UNMAP) { down_write(&xdna->notifier_lock); - if (!mapp->unmapped) { - queue_work(xdna->notifier_wq, &mapp->hmm_unreg_work); - mapp->unmapped = true; - } + mapp->unmapped = true; + queue_work(xdna->notifier_wq, &abo->hmm_unreg_work); up_write(&xdna->notifier_lock); } @@ -153,33 +155,42 @@ static void amdxdna_hmm_unregister(struct amdxdna_gem_obj *abo, down_write(&xdna->notifier_lock); list_for_each_entry(mapp, &abo->mem.umap_list, node) { - if (!vma || compare_range(mapp, vma->vm_mm, vma->vm_start, vma->vm_end)) { - if (!mapp->unmapped) { - queue_work(xdna->notifier_wq, &mapp->hmm_unreg_work); - mapp->unmapped = true; - } - if (vma) - break; - } + if (!compare_range(mapp, vma->vm_mm, vma->vm_start, vma->vm_end)) + continue; + + mapp->unmapped = true; + queue_work(xdna->notifier_wq, &abo->hmm_unreg_work); } up_write(&xdna->notifier_lock); } -static void amdxdna_umap_release(struct kref *ref) +static void amdxdna_hmm_unreg_umaps(struct amdxdna_gem_obj *abo, bool force) { - struct amdxdna_umap *mapp = container_of(ref, struct amdxdna_umap, refcnt); - struct amdxdna_gem_obj *abo = mapp->abo; - struct amdxdna_dev *xdna; - - mmu_interval_notifier_remove(&mapp->notifier); + struct amdxdna_dev *xdna = to_xdna_dev(to_gobj(abo)->dev); + struct amdxdna_umap *mapp, *tmp; + LIST_HEAD(dead); - xdna = to_xdna_dev(to_gobj(mapp->abo)->dev); down_write(&xdna->notifier_lock); - list_del(&mapp->node); + list_for_each_entry_safe(mapp, tmp, &abo->mem.umap_list, node) { + if (!force && !mapp->unmapped) + continue; + + mapp->unmapped = true; + list_move(&mapp->node, &dead); + } if (list_empty(&abo->mem.umap_list)) abo->mem.userptr = AMDXDNA_INVALID_ADDR; up_write(&xdna->notifier_lock); + list_for_each_entry_safe(mapp, tmp, &dead, node) + amdxdna_umap_put(mapp); +} + +static void amdxdna_umap_release(struct kref *ref) +{ + struct amdxdna_umap *mapp = container_of(ref, struct amdxdna_umap, refcnt); + + mmu_interval_notifier_remove(&mapp->notifier); kvfree(mapp->range.hmm_pfns); kfree(mapp); } @@ -191,10 +202,10 @@ void amdxdna_umap_put(struct amdxdna_umap *mapp) static void amdxdna_hmm_unreg_work(struct work_struct *work) { - struct amdxdna_umap *mapp = container_of(work, struct amdxdna_umap, - hmm_unreg_work); + struct amdxdna_gem_obj *abo = container_of(work, struct amdxdna_gem_obj, + hmm_unreg_work); - amdxdna_umap_put(mapp); + amdxdna_hmm_unreg_umaps(abo, false); } static int amdxdna_hmm_register(struct amdxdna_gem_obj *abo, @@ -246,8 +257,6 @@ static int amdxdna_hmm_register(struct amdxdna_gem_obj *abo, mapp->abo = abo; kref_init(&mapp->refcnt); - INIT_WORK(&mapp->hmm_unreg_work, amdxdna_hmm_unreg_work); - ret = mmu_interval_notifier_insert_locked(&mapp->notifier, current->mm, addr, @@ -309,16 +318,16 @@ static int amdxdna_insert_pages(struct amdxdna_gem_obj *abo, { struct amdxdna_dev *xdna = to_xdna_dev(to_gobj(abo)->dev); unsigned long num_pages = vma_pages(vma); - unsigned long offset = 0; int ret; - if (!is_import_bo(abo)) { - ret = drm_gem_shmem_mmap(&abo->base, vma); - if (ret) { - XDNA_ERR(xdna, "Failed shmem mmap %d", ret); - return ret; - } - } else { + /* + * Until today there is not any use case to mmap with non-zero + * offset. Put an explicit check here. + */ + if (vma->vm_pgoff - drm_vma_node_start(&to_gobj(abo)->vma_node)) + return -EINVAL; + + if (is_import_bo(abo)) { vma->vm_private_data = NULL; vma->vm_ops = NULL; ret = dma_buf_mmap(abo->dma_buf, vma, 0); @@ -327,23 +336,28 @@ static int amdxdna_insert_pages(struct amdxdna_gem_obj *abo, return ret; } + amdxdna_mark_mapp_invalid(abo, vma); + /* Drop the reference drm_gem_mmap_obj() acquired.*/ drm_gem_object_put(to_gobj(abo)); + return 0; } - do { - vm_fault_t fault_ret; - - fault_ret = handle_mm_fault(vma, vma->vm_start + offset, - FAULT_FLAG_WRITE, NULL); - if (fault_ret & VM_FAULT_ERROR) { - XDNA_ERR(xdna, "Fault in page failed"); - amdxdna_mark_mapp_invalid(abo, vma); - break; - } + ret = drm_gem_shmem_mmap(&abo->base, vma); + if (ret) { + XDNA_ERR(xdna, "Failed shmem mmap %d", ret); + return ret; + } - offset += PAGE_SIZE; - } while (--num_pages); + vm_flags_mod(vma, VM_MIXEDMAP, VM_PFNMAP); + ret = vm_insert_pages(vma, vma->vm_start, abo->base.pages, &num_pages); + if (ret) { + XDNA_ERR(xdna, "Failed to insert pages %d", ret); + dma_resv_lock(to_gobj(abo)->resv, NULL); + drm_gem_shmem_put_pages_locked(&abo->base); + dma_resv_unlock(to_gobj(abo)->resv); + return ret; + } return 0; } @@ -355,6 +369,10 @@ static int amdxdna_gem_obj_mmap(struct drm_gem_object *gobj, struct amdxdna_gem_obj *abo = to_xdna_obj(gobj); int ret; + XDNA_DBG(xdna, "BO map_offset 0x%llx type %d userptr 0x%lx size 0x%lx", + drm_vma_node_offset_addr(&gobj->vma_node), abo->type, + vma->vm_start, gobj->size); + ret = amdxdna_hmm_register(abo, vma); if (ret) return ret; @@ -365,9 +383,6 @@ static int amdxdna_gem_obj_mmap(struct drm_gem_object *gobj, goto hmm_unreg; } - XDNA_DBG(xdna, "BO map_offset 0x%llx type %d userptr 0x%lx size 0x%lx", - drm_vma_node_offset_addr(&gobj->vma_node), abo->type, - vma->vm_start, gobj->size); return 0; hmm_unreg: @@ -375,14 +390,99 @@ static int amdxdna_gem_obj_mmap(struct drm_gem_object *gobj, return ret; } +/* + * VM operations for amdxdna shmem VMAs that use VM_MIXEDMAP. + * + * drm_gem_shmem_vm_ops cannot be used on VM_MIXEDMAP VMAs because its fault + * handler calls vmf_insert_pfn() → vmf_insert_pfn_prot() which contains: + * BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn)) + * All amdxdna shmem pages are ordinary struct pages so pfn_valid() is always + * true, making the combination fatal. + * + * These ops use vmf_insert_page() (struct-page based) instead, which is the + * correct API for VM_MIXEDMAP VMAs backed by real struct pages. The open and + * close handlers replicate drm_gem_shmem_vm_open/close using only exported + * symbols. + */ +static vm_fault_t amdxdna_gem_mixedmap_fault(struct vm_fault *vmf) +{ + struct vm_area_struct *vma = vmf->vma; + struct drm_gem_object *gobj = vma->vm_private_data; + struct drm_gem_shmem_object *shmem = to_drm_gem_shmem_obj(gobj); + loff_t num_pages = gobj->size >> PAGE_SHIFT; + vm_fault_t ret = VM_FAULT_SIGBUS; + pgoff_t page_offset; + struct page *page; + + /* + * Partial free of vma is unexpected. Otherwise, the wrong page + * will be faulted in and the user application may crash itself. + */ + page_offset = (vmf->address - vma->vm_start) >> PAGE_SHIFT; + + dma_resv_lock(gobj->resv, NULL); + + if (!shmem->pages || shmem->madv < 0 || page_offset >= num_pages) + goto out; + + page = shmem->pages[page_offset]; + if (WARN_ON_ONCE(!page)) + goto out; + + /* + * Use vmf_insert_page() (struct-page path) not vmf_insert_pfn() + * (PFN path) because this VMA carries VM_MIXEDMAP. + */ + ret = vmf_insert_page(vma, vmf->address, page); + if (ret == VM_FAULT_NOPAGE) + folio_mark_accessed(page_folio(page)); + +out: + dma_resv_unlock(gobj->resv); + return ret; +} + +static void amdxdna_gem_mixedmap_vm_open(struct vm_area_struct *vma) +{ + struct drm_gem_object *gobj = vma->vm_private_data; + struct drm_gem_shmem_object *shmem = to_drm_gem_shmem_obj(gobj); + + /* + * Bump pages_use_count so the page array stays alive for the new + * mapping copy created by fork(). Mirrors drm_gem_shmem_vm_open(). + */ + dma_resv_lock(gobj->resv, NULL); + drm_WARN_ON_ONCE(gobj->dev, !refcount_inc_not_zero(&shmem->pages_use_count)); + dma_resv_unlock(gobj->resv); + + drm_gem_vm_open(vma); +} + +static void amdxdna_gem_mixedmap_vm_close(struct vm_area_struct *vma) +{ + struct drm_gem_object *gobj = vma->vm_private_data; + struct drm_gem_shmem_object *shmem = to_drm_gem_shmem_obj(gobj); + + dma_resv_lock(gobj->resv, NULL); + drm_gem_shmem_put_pages_locked(shmem); + dma_resv_unlock(gobj->resv); + + drm_gem_vm_close(vma); +} + +static const struct vm_operations_struct amdxdna_gem_mixedmap_vm_ops = { + .fault = amdxdna_gem_mixedmap_fault, + .open = amdxdna_gem_mixedmap_vm_open, + .close = amdxdna_gem_mixedmap_vm_close, +}; + static int amdxdna_gem_dmabuf_mmap(struct dma_buf *dma_buf, struct vm_area_struct *vma) { struct drm_gem_object *gobj = dma_buf->priv; struct amdxdna_gem_obj *abo = to_xdna_obj(gobj); - unsigned long num_pages = vma_pages(vma); int ret; - vma->vm_ops = &drm_gem_shmem_vm_ops; + vma->vm_ops = &amdxdna_gem_mixedmap_vm_ops; vma->vm_private_data = gobj; drm_gem_object_get(gobj); @@ -392,16 +492,9 @@ static int amdxdna_gem_dmabuf_mmap(struct dma_buf *dma_buf, struct vm_area_struc /* The buffer is based on memory pages. Fix the flag. */ vm_flags_mod(vma, VM_MIXEDMAP, VM_PFNMAP); - ret = vm_insert_pages(vma, vma->vm_start, abo->base.pages, - &num_pages); - if (ret) - goto close_vma; return 0; -close_vma: - vma->vm_ops->close(vma); - return ret; put_obj: drm_gem_object_put(gobj); return ret; @@ -482,8 +575,9 @@ static void amdxdna_gem_obj_free(struct drm_gem_object *gobj) XDNA_DBG(xdna, "BO type %d xdna_addr 0x%llx", abo->type, abo->mem.dev_addr); - amdxdna_hmm_unregister(abo, NULL); - flush_workqueue(xdna->notifier_wq); + /* No notifier survives this, so no new work can be queued. */ + amdxdna_hmm_unreg_umaps(abo, true); + cancel_work_sync(&abo->hmm_unreg_work); if (abo->pinned) amdxdna_gem_unpin(abo); @@ -515,7 +609,7 @@ static const struct drm_gem_object_funcs amdxdna_gem_shmem_funcs = { .vmap = drm_gem_shmem_object_vmap, .vunmap = drm_gem_shmem_object_vunmap, .mmap = amdxdna_gem_obj_mmap, - .vm_ops = &drm_gem_shmem_vm_ops, + .vm_ops = &amdxdna_gem_mixedmap_vm_ops, .export = amdxdna_gem_prime_export, }; @@ -536,6 +630,7 @@ amdxdna_gem_create_obj(struct drm_device *dev, size_t size) abo->mem.dev_addr = AMDXDNA_INVALID_ADDR; abo->mem.size = size; INIT_LIST_HEAD(&abo->mem.umap_list); + INIT_WORK(&abo->hmm_unreg_work, amdxdna_hmm_unreg_work); return abo; } diff --git a/drivers/accel/amdxdna/amdxdna_gem.h b/drivers/accel/amdxdna/amdxdna_gem.h index b3c814c0bb7e..b6573ffe8d7c 100644 --- a/drivers/accel/amdxdna/amdxdna_gem.h +++ b/drivers/accel/amdxdna/amdxdna_gem.h @@ -11,7 +11,6 @@ struct amdxdna_umap { struct mmu_interval_notifier notifier; struct hmm_range range; - struct work_struct hmm_unreg_work; struct amdxdna_gem_obj *abo; struct list_head node; struct kref refcnt; @@ -37,6 +36,7 @@ struct amdxdna_gem_obj { bool pinned; struct mutex lock; /* Protects: pinned */ struct amdxdna_mem mem; + struct work_struct hmm_unreg_work; /* Below members is uninitialized when needed */ struct drm_mm mm; /* For AMDXDNA_BO_DEV_HEAP */ diff --git a/drivers/accel/ivpu/ivpu_pm.c b/drivers/accel/ivpu/ivpu_pm.c index 457ccf09df54..7e0e7c78cb13 100644 --- a/drivers/accel/ivpu/ivpu_pm.c +++ b/drivers/accel/ivpu/ivpu_pm.c @@ -148,8 +148,8 @@ static void ivpu_pm_reset_complete(struct ivpu_device *vdev) up_write(&vdev->pm->reset_lock); atomic_set(&vdev->pm->reset_pending, 0); - pm_runtime_mark_last_busy(vdev->drm.dev); pm_runtime_enable(vdev->drm.dev); + pm_request_autosuspend(vdev->drm.dev); } static void ivpu_pm_recovery_work(struct work_struct *work) @@ -403,6 +403,7 @@ void ivpu_pm_init(struct ivpu_device *vdev) atomic_set(&pm->reset_counter, 0); INIT_WORK(&pm->recovery_work, ivpu_pm_recovery_work); + disable_work(&pm->recovery_work); INIT_DELAYED_WORK(&pm->job_timeout_work, ivpu_job_timeout_work); if (ivpu_disable_recovery) @@ -427,6 +428,12 @@ void ivpu_pm_enable(struct ivpu_device *vdev) { struct device *dev = vdev->drm.dev; + enable_work(&vdev->pm->recovery_work); + if (atomic_read(&vdev->pm->reset_pending)) { + queue_work(system_dfl_wq, &vdev->pm->recovery_work); + flush_work(&vdev->pm->recovery_work); + } + pm_runtime_allow(dev); pm_runtime_mark_last_busy(dev); pm_runtime_put_autosuspend(dev); diff --git a/drivers/acpi/acpi_pcc.c b/drivers/acpi/acpi_pcc.c index 683924a708ba..04bb23260396 100644 --- a/drivers/acpi/acpi_pcc.c +++ b/drivers/acpi/acpi_pcc.c @@ -55,6 +55,19 @@ acpi_pcc_address_space_setup(acpi_handle region_handle, u32 function, struct pcc_mbox_chan *pcc_chan; acpi_status ret; + if (function == ACPI_REGION_DEACTIVATE) { + data = *region_context; + if (data) { + pcc_mbox_free_channel(data->pcc_chan); + kfree(data); + *region_context = NULL; + } + return AE_OK; + } + + if (function != ACPI_REGION_ACTIVATE) + return AE_BAD_PARAMETER; + data = kzalloc(sizeof(*data), GFP_KERNEL); if (!data) return AE_NO_MEMORY; diff --git a/drivers/acpi/acpi_platform.c b/drivers/acpi/acpi_platform.c index 62ab6d7f3721..49c2d6734de5 100644 --- a/drivers/acpi/acpi_platform.c +++ b/drivers/acpi/acpi_platform.c @@ -108,18 +108,15 @@ static unsigned int acpi_platform_adjust_resources(struct acpi_device *adev, return count; } -static void acpi_platform_fill_resource(struct acpi_device *adev, - const struct resource *src, struct resource *dest) +static void acpi_platform_fill_resource(struct device *parent, + const struct resource *src, + struct resource *dest) { - struct device *parent; - *dest = *src; - /* * If the device has parent we need to take its resources into * account as well because this device might consume part of those. */ - parent = acpi_get_first_physical_node(acpi_dev_parent(adev)); if (parent && dev_is_pci(parent)) dest->parent = pci_find_resource(to_pci_dev(parent), dest); } @@ -147,7 +144,8 @@ static unsigned int acpi_platform_resource_count(struct acpi_resource *ares, voi struct platform_device *acpi_create_platform_device(struct acpi_device *adev, const struct property_entry *properties) { - struct acpi_device *parent = acpi_dev_parent(adev); + struct acpi_device *p = acpi_dev_parent(adev); + struct device *parent __free(put_device) = acpi_bus_get_primary_device(p); struct platform_device *pdev = NULL; struct platform_device_info pdevinfo; const struct acpi_device_id *match; @@ -193,7 +191,7 @@ struct platform_device *acpi_create_platform_device(struct acpi_device *adev, rentry->res, resources, count); - acpi_platform_fill_resource(adev, rentry->res, + acpi_platform_fill_resource(parent, rentry->res, &resources[count++]); } acpi_dev_free_resource_list(&resource_list); @@ -206,7 +204,7 @@ struct platform_device *acpi_create_platform_device(struct acpi_device *adev, * attached to it, that physical device should be the parent of the * platform device we are about to create. */ - pdevinfo.parent = parent ? acpi_get_first_physical_node(parent) : NULL; + pdevinfo.parent = parent; pdevinfo.name = dev_name(&adev->dev); pdevinfo.id = PLATFORM_DEVID_NONE; pdevinfo.res = resources; diff --git a/drivers/acpi/apei/ghes.c b/drivers/acpi/apei/ghes.c index b81d5ed50d43..c10b440c6cab 100644 --- a/drivers/acpi/apei/ghes.c +++ b/drivers/acpi/apei/ghes.c @@ -899,6 +899,28 @@ int cxl_cper_kfifo_get(struct cxl_cper_work_data *wd) } EXPORT_SYMBOL_NS_GPL(cxl_cper_kfifo_get, "CXL"); +/* + * The fields from "extended" on are absent from the 73-byte UEFI 2.1/2.2 + * layout that older firmware still emits. Return the length needed for the + * fields the validation bits claim, so over-claiming is rejected without + * rejecting an honest short record. + */ +static u32 ghes_mem_err_min_len(u64 validation_bits) +{ + u32 len = sizeof(struct cper_sec_mem_err_old); + + if (validation_bits & (CPER_MEM_VALID_ROW_EXT | CPER_MEM_VALID_CHIP_ID)) + len = offsetof(struct cper_sec_mem_err, rank); + if (validation_bits & CPER_MEM_VALID_RANK_NUMBER) + len = offsetof(struct cper_sec_mem_err, mem_array_handle); + if (validation_bits & CPER_MEM_VALID_CARD_HANDLE) + len = offsetof(struct cper_sec_mem_err, mem_dev_handle); + if (validation_bits & CPER_MEM_VALID_MODULE_HANDLE) + len = sizeof(struct cper_sec_mem_err); + + return len; +} + static void ghes_do_proc(struct ghes *ghes, const struct acpi_hest_generic_status *estatus) { @@ -923,6 +945,25 @@ static void ghes_do_proc(struct ghes *ghes, if (guid_equal(sec_type, &CPER_SEC_PLATFORM_MEM)) { struct cper_sec_mem_err *mem_err = acpi_hest_get_payload(gdata); + /* + * Check once for all three consumers below. The 73-byte + * UEFI 2.1/2.2 layout is the floor, matching + * cper_estatus_print_section() and making + * validation_bits safe to read. + */ + if (gdata->error_data_length < + sizeof(struct cper_sec_mem_err_old)) + continue; + + /* Then require what the claimed fields actually need. */ + if (gdata->error_data_length < + ghes_mem_err_min_len(mem_err->validation_bits)) { + pr_warn_ratelimited(FW_WARN GHES_PFX + "memory error section too small (%u) for the fields it claims\n", + gdata->error_data_length); + continue; + } + atomic_notifier_call_chain(&ghes_report_chain, sev, mem_err); arch_apei_report_mem_error(sev, mem_err); diff --git a/drivers/acpi/glue.c b/drivers/acpi/glue.c index e2a40847d24b..f915a7c0e7cc 100644 --- a/drivers/acpi/glue.c +++ b/drivers/acpi/glue.c @@ -243,31 +243,25 @@ static void acpi_physnode_link_name(char *buf, unsigned int node_id) int acpi_bind_one(struct device *dev, struct acpi_device *acpi_dev) { struct acpi_device_physical_node *physical_node, *pn; + struct acpi_device *comp_dev = ACPI_COMPANION(dev); char physical_node_name[PHYSICAL_NODE_NAME_SIZE]; struct list_head *physnode_list; unsigned int node_id; int retval = -EINVAL; - if (has_acpi_companion(dev)) { - if (acpi_dev) { - dev_warn(dev, "ACPI companion already set\n"); + if (!acpi_dev) { + if (!comp_dev) return -EINVAL; - } else { - acpi_dev = ACPI_COMPANION(dev); - } - } - if (!acpi_dev) - return -EINVAL; - acpi_dev_get(acpi_dev); - get_device(dev); - physical_node = kzalloc(sizeof(*physical_node), GFP_KERNEL); - if (!physical_node) { - retval = -ENOMEM; - goto err; + /* If the companion has been set upfront, pick it up. */ + acpi_dev = comp_dev; + } else if (comp_dev && acpi_dev != comp_dev) { + dev_warn(dev, "ACPI companion already set to %s which is not %s\n", + acpi_dev_name(comp_dev), acpi_dev_name(acpi_dev)); + return -EEXIST; } - mutex_lock(&acpi_dev->physical_node_lock); + guard(mutex)(&acpi_dev->physical_node_lock); /* * Keep the list sorted by node_id so that the IDs of removed nodes can @@ -278,15 +272,12 @@ int acpi_bind_one(struct device *dev, struct acpi_device *acpi_dev) list_for_each_entry(pn, &acpi_dev->physical_node_list, node) { /* Sanity check. */ if (pn->dev == dev) { - mutex_unlock(&acpi_dev->physical_node_lock); - - dev_warn(dev, "Already associated with ACPI node\n"); - kfree(physical_node); - if (ACPI_COMPANION(dev) != acpi_dev) - goto err; - - put_device(dev); - acpi_dev_put(acpi_dev); + if (!comp_dev) { + /* Really unexpected. */ + ACPI_COMPANION_SET(dev, acpi_dev); + dev_warn(&acpi_dev->dev, + "Physical device list corruption fixed up\n"); + } return 0; } if (pn->node_id == node_id) { @@ -295,12 +286,19 @@ int acpi_bind_one(struct device *dev, struct acpi_device *acpi_dev) } } + physical_node = kzalloc(sizeof(*physical_node), GFP_KERNEL); + if (!physical_node) + return -ENOMEM; + + acpi_dev_get(acpi_dev); + get_device(dev); + physical_node->node_id = node_id; physical_node->dev = dev; list_add(&physical_node->node, physnode_list); acpi_dev->physical_node_count++; - if (!has_acpi_companion(dev)) + if (!comp_dev) ACPI_COMPANION_SET(dev, acpi_dev); acpi_physnode_link_name(physical_node_name, node_id); @@ -316,18 +314,10 @@ int acpi_bind_one(struct device *dev, struct acpi_device *acpi_dev) dev_err(dev, "Failed to create link firmware_node (%d)\n", retval); - mutex_unlock(&acpi_dev->physical_node_lock); - if (acpi_dev->wakeup.flags.valid) device_set_wakeup_capable(dev, true); return 0; - - err: - ACPI_COMPANION_SET(dev, NULL); - put_device(dev); - acpi_dev_put(acpi_dev); - return retval; } EXPORT_SYMBOL_GPL(acpi_bind_one); diff --git a/drivers/acpi/power.c b/drivers/acpi/power.c index 6d16740e1d70..4a67e9afdd7f 100644 --- a/drivers/acpi/power.c +++ b/drivers/acpi/power.c @@ -1126,6 +1126,44 @@ static const struct dmi_system_id dmi_leave_unused_power_resources_on[] = { } }, + { + /* + * Acer Swift 3 SF314-56G with NVIDIA MX250 suffers from the + * same ACPI power resource regression as the Thunderobot ZERO. + * The power resource controlling the dGPU is incorrectly turned off + * during initialization, causing the GPU to fall off the bus (D3cold). + */ + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Acer"), + DMI_MATCH(DMI_PRODUCT_NAME, "Swift SF314-56G"), + } + + }, + { + /* + * CASPER EXCALIBUR G900 laptop: Keep unused ACPI power + * resources on to prevent the NVIDIA dGPU and NVMe #2 + * from becoming inaccessible. + */ + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "CASPER BILGISAYAR SISTEMLERI"), + DMI_MATCH(DMI_PRODUCT_NAME, "EXCALIBUR G900"), + DMI_MATCH(DMI_BOARD_NAME, "NLCC 001"), + }, + }, + { + /* + * Acer Aspire A515-53G: Two SSDTs both define power resources + * for the dGPU root port RP05 ('PC01' and 'PCRP'). Only PC01 ends + * up in RP05's _PR0/_PR3, so 'PCRP' is shut down on + * initialization, cutting power to the NVIDIA dGPU behind the + * back of 'PC01' and making the dGPU unavailable. + */ + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Acer"), + DMI_MATCH(DMI_PRODUCT_NAME, "Aspire A515-53G"), + }, + }, {} }; diff --git a/drivers/acpi/scan.c b/drivers/acpi/scan.c index 3893e44005f4..ab8382c812e8 100644 --- a/drivers/acpi/scan.c +++ b/drivers/acpi/scan.c @@ -114,11 +114,7 @@ bool acpi_scan_is_offline(struct acpi_device *adev, bool uevent) bool offline = true; char *envp[] = { "EVENT=offline", NULL }; - /* - * acpi_container_offline() calls this for all of the container's - * children under the container's physical_node_lock lock. - */ - mutex_lock_nested(&adev->physical_node_lock, SINGLE_DEPTH_NESTING); + mutex_lock(&adev->physical_node_lock); list_for_each_entry(pn, &adev->physical_node_list, node) if (device_supports_offline(pn->dev) && !pn->dev->offline) { @@ -133,6 +129,59 @@ bool acpi_scan_is_offline(struct acpi_device *adev, bool uevent) return offline; } +static struct acpi_device_physical_node * +acpi_find_physical_node(struct acpi_device *adev, struct device *dev) +{ + struct acpi_device_physical_node *pn; + + lockdep_assert_held(&adev->physical_node_lock); + + list_for_each_entry(pn, &adev->physical_node_list, node) + if (pn->dev == dev) + return pn; + + return NULL; +} + +static struct device *acpi_next_offline_pending(struct acpi_device *adev) +{ + struct acpi_device_physical_node *pn; + + lockdep_assert_held(&adev->physical_node_lock); + + /* + * Find the first physical node that is still to be offlined, clear its + * offline_pending flag and return its device with a reference held. + */ + list_for_each_entry(pn, &adev->physical_node_list, node) + if (pn->offline_pending) { + pn->offline_pending = false; + return get_device(pn->dev); + } + + return NULL; +} + +static struct device *acpi_next_put_online(struct acpi_device *adev) +{ + struct acpi_device_physical_node *pn; + + lockdep_assert_held(&adev->physical_node_lock); + + /* + * Find the first physical node that has been offlined by + * acpi_bus_offline(), clear its put_online flag and return its device + * with a reference held. + */ + list_for_each_entry(pn, &adev->physical_node_list, node) + if (pn->put_online) { + pn->put_online = false; + return get_device(pn->dev); + } + + return NULL; +} + static acpi_status acpi_bus_offline(acpi_handle handle, u32 lvl, void *data, void **ret_p) { @@ -140,6 +189,7 @@ static acpi_status acpi_bus_offline(acpi_handle handle, u32 lvl, void *data, struct acpi_device_physical_node *pn; bool second_pass = (bool)data; acpi_status status = AE_OK; + struct device *dev; if (!device) return AE_OK; @@ -152,25 +202,43 @@ static acpi_status acpi_bus_offline(acpi_handle handle, u32 lvl, void *data, mutex_lock(&device->physical_node_lock); list_for_each_entry(pn, &device->physical_node_list, node) { - int ret; - if (second_pass) { /* Skip devices offlined by the first pass. */ - if (pn->put_online) - continue; + pn->offline_pending = !pn->put_online; } else { + pn->offline_pending = true; pn->put_online = false; } - ret = device_offline(pn->dev); + } + + /* + * Drop physical_node_lock around device_offline(), because the latter + * acquires locks, like the CPU hotplug ones, that must not nest under + * it. + */ + while ((dev = acpi_next_offline_pending(device))) { + int ret; + + mutex_unlock(&device->physical_node_lock); + ret = device_offline(dev); + mutex_lock(&device->physical_node_lock); + if (ret >= 0) { - pn->put_online = !ret; + /* The device may have been unbound in the meantime. */ + pn = acpi_find_physical_node(device, dev); + if (pn) + pn->put_online = !ret; } else { - *ret_p = pn->dev; + *ret_p = &device->dev; if (second_pass) { + dev_warn(dev, "Offline failed.\n"); status = AE_ERROR; - break; } } + + put_device(dev); + if (ACPI_FAILURE(status)) + break; } mutex_unlock(&device->physical_node_lock); @@ -182,18 +250,19 @@ static acpi_status acpi_bus_online(acpi_handle handle, u32 lvl, void *data, void **ret_p) { struct acpi_device *device = acpi_fetch_acpi_dev(handle); - struct acpi_device_physical_node *pn; + struct device *dev; if (!device) return AE_OK; mutex_lock(&device->physical_node_lock); - list_for_each_entry(pn, &device->physical_node_list, node) - if (pn->put_online) { - device_online(pn->dev); - pn->put_online = false; - } + while ((dev = acpi_next_put_online(device))) { + mutex_unlock(&device->physical_node_lock); + device_online(dev); + mutex_lock(&device->physical_node_lock); + put_device(dev); + } mutex_unlock(&device->physical_node_lock); @@ -235,7 +304,6 @@ static int acpi_scan_try_to_offline(struct acpi_device *device) (void **)&errdev); if (errdev) { - dev_warn(errdev, "Offline failed.\n"); acpi_bus_online(handle, 0, NULL, NULL); acpi_walk_namespace(ACPI_TYPE_ANY, handle, ACPI_UINT32_MAX, acpi_bus_online, diff --git a/drivers/ata/libata-core.c b/drivers/ata/libata-core.c index 29394d18e7e8..209bd48ee861 100644 --- a/drivers/ata/libata-core.c +++ b/drivers/ata/libata-core.c @@ -2046,6 +2046,10 @@ void ata_dev_power_set_standby(struct ata_device *dev) struct ata_taskfile tf; unsigned int err_mask; + /* Issue STANDBY IMMEDIATE command only if supported by the device */ + if (!ata_dev_power_init_tf(dev, &tf, false)) + return; + /* If the device is already sleeping or in standby, do nothing. */ if ((dev->flags & ATA_DFLAG_SLEEPING) || !ata_dev_power_is_active(dev)) @@ -2064,10 +2068,6 @@ void ata_dev_power_set_standby(struct ata_device *dev) system_entering_hibernation()) return; - /* Issue STANDBY IMMEDIATE command only if supported by the device */ - if (!ata_dev_power_init_tf(dev, &tf, false)) - return; - ata_dev_notice(dev, "Entering standby power mode\n"); err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0); diff --git a/drivers/ata/libata-eh.c b/drivers/ata/libata-eh.c index 9d35b4f8d392..1e5946c0a743 100644 --- a/drivers/ata/libata-eh.c +++ b/drivers/ata/libata-eh.c @@ -4061,8 +4061,20 @@ void ata_eh_finish(struct ata_port *ap) ata_eh_qc_complete(qc); } } else { - if (qc->flags & ATA_QCFLAG_SENSE_VALID || - qc->flags & ATA_QCFLAG_EH_SUCCESS_CMD) { + if (qc->flags & ATA_QCFLAG_SENSE_VALID && + qc->flags & ATA_QCFLAG_RETRY) { + /* + * The sense data asks for a retry, see + * ata_eh_analyze_tf(). ata_eh_link_autopsy() + * cleared qc->err_mask, so ata_eh_qc_retry() + * would increment scmd->allowed. Leave + * scmd->allowed alone, so that upper layer + * only retries the command if it has not + * already been retried too many times. + */ + __ata_eh_qc_complete(qc); + } else if (qc->flags & ATA_QCFLAG_SENSE_VALID || + qc->flags & ATA_QCFLAG_EH_SUCCESS_CMD) { ata_eh_qc_complete(qc); } else { /* feed zero TF to sense generation */ diff --git a/drivers/ata/libata-sata.c b/drivers/ata/libata-sata.c index 9b374e8f9938..9eb28dab4619 100644 --- a/drivers/ata/libata-sata.c +++ b/drivers/ata/libata-sata.c @@ -1287,7 +1287,7 @@ int ata_change_queue_depth(struct ata_port *ap, struct scsi_device *sdev, spin_lock_irqsave(ap->lock, flags); dev = ata_scsi_find_dev(ap, sdev); - if (!dev || queue_depth < 1 || queue_depth == sdev->queue_depth) { + if (!dev || queue_depth < 1) { spin_unlock_irqrestore(ap->lock, flags); return sdev->queue_depth; } diff --git a/drivers/ata/libata-scsi.c b/drivers/ata/libata-scsi.c index ce206f90d8bc..5defffb9a3e0 100644 --- a/drivers/ata/libata-scsi.c +++ b/drivers/ata/libata-scsi.c @@ -4055,14 +4055,22 @@ static unsigned int ata_scsi_zbc_out_xlat(struct ata_queued_cmd *qc) /** * ata_mselect_caching - Simulate MODE SELECT for caching info page * @qc: Storage for translated ATA taskfile - * @buf: input buffer - * @len: number of valid bytes in the input buffer - * @fp: out parameter for the failed field on error + * @buf: Mode page, starting with the mode page header + * @len: Length of the mode page, including the mode page header + * @fp: Out parameter, offset in @buf of the first invalid byte on error * * Prepare a taskfile to modify caching information for the device. * + * The caller has stripped the mode parameter header and the block + * descriptors, so @buf points at the mode page header, like the buffer + * filled by the ata_msense_*() functions, and offsets in @buf, including + * the one returned in @fp, are the byte numbers of the mode page. + * * LOCKING: * None. + * + * RETURNS: + * 0 if a taskfile was prepared, -EINVAL if the mode page is invalid. */ static int ata_mselect_caching(struct ata_queued_cmd *qc, const u8 *buf, int len, u16 *fp) @@ -4073,26 +4081,19 @@ static int ata_mselect_caching(struct ata_queued_cmd *qc, u8 wce; int i; - /* - * The first two bytes of def_cache_mpage are a header, so offsets - * in mpage are off by 2 compared to buf. Same for len. - */ - - if (len != CACHE_MPAGE_LEN - 2) { - *fp = min(len, CACHE_MPAGE_LEN - 2); + if (len != CACHE_MPAGE_LEN) { + *fp = 1; return -EINVAL; } - wce = buf[0] & (1 << 2); + wce = buf[2] & (1 << 2); /* * Check that read-only bits are not modified. */ ata_msense_caching(dev->id, mpage, false); - for (i = 0; i < CACHE_MPAGE_LEN - 2; i++) { - if (i == 0) - continue; - if (mpage[i + 2] != buf[i]) { + for (i = 3; i < CACHE_MPAGE_LEN; i++) { + if (mpage[i] != buf[i]) { *fp = i; return -EINVAL; } @@ -4106,8 +4107,26 @@ static int ata_mselect_caching(struct ata_queued_cmd *qc, return 0; } -/* - * Simulate MODE SELECT control mode page, sub-page 0. +/** + * ata_mselect_control_spg0 - Simulate MODE SELECT for control sub-page 0 + * @qc: Storage for translated ATA taskfile + * @buf: Mode page, starting with the mode page header + * @len: Length of the mode page, including the mode page header + * @fp: Out parameter, offset in @buf of the first invalid byte on error + * + * Simulate MODE SELECT control mode page, sub-page 0. + * + * The caller has stripped the mode parameter header and the block + * descriptors, so @buf points at the mode page header, like the buffer + * filled by the ata_msense_*() functions, and offsets in @buf, including + * the one returned in @fp, are the byte numbers of the mode page. + * + * LOCKING: + * None. + * + * RETURNS: + * 0, as no ATA command needs to be sent, or -EINVAL if the mode page is + * invalid. */ static int ata_mselect_control_spg0(struct ata_queued_cmd *qc, const u8 *buf, int len, u16 *fp) @@ -4117,26 +4136,19 @@ static int ata_mselect_control_spg0(struct ata_queued_cmd *qc, u8 d_sense; int i; - /* - * The first two bytes of def_control_mpage are a header, so offsets - * in mpage are off by 2 compared to buf. Same for len. - */ - - if (len != CONTROL_MPAGE_LEN - 2) { - *fp = min(len, CONTROL_MPAGE_LEN - 2); + if (len != CONTROL_MPAGE_LEN) { + *fp = 1; return -EINVAL; } - d_sense = buf[0] & (1 << 2); + d_sense = buf[2] & (1 << 2); /* * Check that read-only bits are not modified. */ ata_msense_control_spg0(dev, mpage, false); - for (i = 0; i < CONTROL_MPAGE_LEN - 2; i++) { - if (i == 0) - continue; - if (mpage[2 + i] != buf[i]) { + for (i = 3; i < CONTROL_MPAGE_LEN; i++) { + if (mpage[i] != buf[i]) { *fp = i; return -EINVAL; } @@ -4148,9 +4160,27 @@ static int ata_mselect_control_spg0(struct ata_queued_cmd *qc, return 0; } -/* - * Translate MODE SELECT control mode page, sub-page f2h (ATA feature mode - * page) into a SET FEATURES command. +/** + * ata_mselect_control_ata_feature - Translate ATA Feature Control page + * @qc: Storage for translated ATA taskfile + * @buf: Mode page, starting with the mode page header + * @len: Length of the mode page, including the mode page header + * @fp: Out parameter, offset in @buf of the first invalid byte on error + * + * Translate MODE SELECT control mode page, sub-page f2h (ATA feature mode + * page) into a SET FEATURES command. + * + * The caller has stripped the mode parameter header and the block + * descriptors, so @buf points at the mode page header, like the buffer + * filled by the ata_msense_*() functions, and offsets in @buf, including + * the one returned in @fp, are the byte numbers of the mode page. + * + * LOCKING: + * None. + * + * RETURNS: + * 1 if a taskfile was prepared, -EINVAL if the mode page is invalid or if + * CDL cannot be enabled. */ static int ata_mselect_control_ata_feature(struct ata_queued_cmd *qc, const u8 *buf, int len, u16 *fp) @@ -4159,17 +4189,13 @@ static int ata_mselect_control_ata_feature(struct ata_queued_cmd *qc, struct ata_taskfile *tf = &qc->tf; u8 cdl_action; - /* - * The first four bytes of ATA Feature Control mode page are a header, - * so offsets in mpage are off by 4 compared to buf. Same for len. - */ - if (len != ATA_FEATURE_SUB_MPAGE_LEN - 4) { - *fp = min(len, ATA_FEATURE_SUB_MPAGE_LEN - 4); + if (len != ATA_FEATURE_SUB_MPAGE_LEN) { + *fp = 2; return -EINVAL; } /* Check cdl_ctrl */ - switch (buf[0] & 0x03) { + switch (buf[4] & 0x03) { case 0: /* Disable CDL */ ata_dev_dbg(dev, "Disabling CDL\n"); @@ -4184,6 +4210,7 @@ static int ata_mselect_control_ata_feature(struct ata_queued_cmd *qc, if (dev->flags & ATA_DFLAG_NCQ_PRIO_ENABLED) { ata_dev_err(dev, "NCQ priority must be disabled to enable CDL\n"); + *fp = 4; return -EINVAL; } ata_dev_dbg(dev, "Enabling CDL\n"); @@ -4191,7 +4218,7 @@ static int ata_mselect_control_ata_feature(struct ata_queued_cmd *qc, dev->flags |= ATA_DFLAG_CDL_ENABLED; break; default: - *fp = 0; + *fp = 4; return -EINVAL; } @@ -4207,15 +4234,24 @@ static int ata_mselect_control_ata_feature(struct ata_queued_cmd *qc, /** * ata_mselect_control - Simulate MODE SELECT for control page * @qc: Storage for translated ATA taskfile - * @spg: target sub-page of the control page - * @buf: input buffer - * @len: number of valid bytes in the input buffer - * @fp: out parameter for the failed field on error + * @spg: Sub-page of the control page, 0 or ATA_FEATURE_SUB_MPAGE + * @buf: Mode page, starting with the mode page header + * @len: Length of the mode page, including the mode page header + * @fp: Out parameter, offset in @buf of the first invalid byte on error * - * Prepare a taskfile to modify caching information for the device. + * Call the handler of sub-page @spg of the control mode page. + * + * The caller has stripped the mode parameter header and the block + * descriptors, so @buf points at the mode page header, like the buffer + * filled by the ata_msense_*() functions, and offsets in @buf, including + * the one returned in @fp, are the byte numbers of the mode page. * * LOCKING: * None. + * + * RETURNS: + * 0 if no ATA command needs to be sent, 1 if a taskfile was prepared, + * -EINVAL if the mode page is invalid. */ static int ata_mselect_control(struct ata_queued_cmd *qc, u8 spg, const u8 *buf, int len, u16 *fp) @@ -4302,7 +4338,6 @@ static unsigned int ata_scsi_mode_select_xlat(struct ata_queued_cmd *qc) goto invalid_param_len; if (bd_len != 0 && bd_len != 8) { fp = (six_byte) ? 3 : 6; - fp += bd_len + hdr_len; goto invalid_param; } @@ -4317,48 +4352,56 @@ static unsigned int ata_scsi_mode_select_xlat(struct ata_queued_cmd *qc) if (len < 4) goto invalid_param_len; + /* + * Mode pages with subpage code 00h use the page_0 format: SAT + * defines the SPF bit of the Caching and Control mode pages, + * for subpage code 00h, as not changeable and set to zero. + */ spg = p[1]; - pg_len = get_unaligned_be16(&p[2]); - p += 4; - len -= 4; + if (!spg) { + fp = hdr_len + bd_len; + goto invalid_param; + } + + pg_len = get_unaligned_be16(&p[2]) + 4; } else { if (len < 2) goto invalid_param_len; spg = 0; - pg_len = p[1]; - p += 2; - len -= 2; + pg_len = p[1] + 2; } /* - * Supported subpages: all subpages and ATA feature sub-page f2h of - * the control page. + * The only supported subpage is the ATA feature sub-page f2h of the + * control page. */ if (spg) { switch (spg) { - case ALL_SUB_MPAGES: - /* All subpages is not supported for the control page */ - if (pg == CONTROL_MPAGE) { - fp = (p[0] & 0x40) ? 1 : 0; - fp += hdr_len + bd_len; - goto invalid_param; - } - break; case ATA_FEATURE_SUB_MPAGE: if (qc->dev->flags & ATA_DFLAG_CDL && pg == CONTROL_MPAGE) break; fallthrough; default: - fp = (p[0] & 0x40) ? 1 : 0; - fp += hdr_len + bd_len; + fp = hdr_len + bd_len + 1; goto invalid_param; } } if (pg_len > len) goto invalid_param_len; + /* + * A MODE SELECT command is translated into at most one ATA command, so + * only one mode page per command is supported. Reject any data after + * the mode page before calling the mode page handlers, which may + * already update the device flags. + */ + if (len > pg_len) { + fp = p - buffer + pg_len; + goto invalid_param; + } + switch (pg) { case CACHE_MPAGE: if (ata_mselect_caching(qc, p, pg_len, &fp) < 0) { @@ -4381,13 +4424,6 @@ static unsigned int ata_scsi_mode_select_xlat(struct ata_queued_cmd *qc) goto invalid_param; } - /* - * Only one page has changeable data, so we only support setting one - * page at a time. - */ - if (len > pg_len) - goto invalid_param; - return 0; invalid_fld: diff --git a/drivers/base/power/runtime.c b/drivers/base/power/runtime.c index 04f620e340b3..427d45e663a4 100644 --- a/drivers/base/power/runtime.c +++ b/drivers/base/power/runtime.c @@ -822,6 +822,12 @@ static int rpm_resume(struct device *dev, int rpmflags) pm_runtime_deactivate_timer(dev); if (dev->power.runtime_status == RPM_ACTIVE) { + /* + * The attempt to resume the device means that it is needed for + * something, so update its last_busy timestamp as in the case + * in which it actually resumes below. + */ + pm_runtime_mark_last_busy(dev); retval = 1; goto out; } @@ -1900,7 +1906,7 @@ void pm_runtime_reinit(struct device *dev) void pm_runtime_remove(struct device *dev) { __pm_runtime_disable(dev, false); - flush_work(&dev->power.work); + cancel_work_sync(&dev->power.work); pm_runtime_reinit(dev); } diff --git a/drivers/base/swnode.c b/drivers/base/swnode.c index 1e08492935ee..1d3ff221196c 100644 --- a/drivers/base/swnode.c +++ b/drivers/base/swnode.c @@ -29,6 +29,8 @@ struct swnode { struct fwnode_handle fwnode; const struct software_node *node; int id; + /* Device the managed node's lifetime is tied to. */ + struct device *owner; /* hierarchy */ struct ida child_ids; @@ -37,7 +39,6 @@ struct swnode { struct swnode *parent; unsigned int allocated:1; - unsigned int managed:1; }; static DEFINE_IDA(swnode_root_ids); @@ -1060,7 +1061,7 @@ int device_create_managed_software_node(struct device *dev, if (IS_ERR(fwnode)) return PTR_ERR(fwnode); - to_swnode(fwnode)->managed = true; + to_swnode(fwnode)->owner = dev; set_secondary_fwnode(dev, fwnode); if (device_is_registered(dev)) @@ -1103,7 +1104,7 @@ void software_node_notify_remove(struct device *dev) sysfs_remove_link(&dev->kobj, "software_node"); kobject_put(&swnode->kobj); - if (swnode->managed) { + if (swnode->owner == dev) { set_secondary_fwnode(dev, NULL); kobject_put(&swnode->kobj); } diff --git a/drivers/block/null_blk/zoned.c b/drivers/block/null_blk/zoned.c index 48d0f30694c7..ed0f066c7f78 100644 --- a/drivers/block/null_blk/zoned.c +++ b/drivers/block/null_blk/zoned.c @@ -311,10 +311,8 @@ static blk_status_t null_check_open(struct nullb_device *dev) return BLK_STS_OK; if (dev->nr_zones_imp_open) { - if (null_check_active(dev) == BLK_STS_OK) { - null_close_imp_open_zone(dev); - return BLK_STS_OK; - } + null_close_imp_open_zone(dev); + return BLK_STS_OK; } return BLK_STS_ZONE_OPEN_RESOURCE; @@ -330,8 +328,11 @@ static blk_status_t null_check_open(struct nullb_device *dev) * * ZBC states that an implicit open zone shall be closed only if there is not * room within the open limit. However, with the addition of an active limit, - * it is not certain that closing an implicit open zone will allow a new zone - * to be opened, since we might already be at the active limit capacity. + * it is not certain that closing an implicit open zone will allow an empty + * zone to be opened, since we might already be at the active limit capacity. + * Therefore, the active limit is checked first for an empty zone. A closed + * zone already holds an active zone resource, so only the open limit has to + * be checked for a closed zone. */ static blk_status_t null_check_zone_resources(struct nullb_device *dev, struct nullb_zone *zone) @@ -742,6 +743,33 @@ blk_status_t null_process_zoned_cmd(struct nullb_cmd *cmd, enum req_op op, } } +/* + * Release the zone resources held by a zone, before changing the condition of + * the zone to a condition that does not hold any zone resources. + */ +static void null_release_zone_resources(struct nullb_device *dev, + struct nullb_zone *zone) +{ + if (!dev->need_zone_res_mgmt) + return; + + spin_lock(&dev->zone_res_lock); + switch (zone->cond) { + case BLK_ZONE_COND_IMP_OPEN: + dev->nr_zones_imp_open--; + break; + case BLK_ZONE_COND_EXP_OPEN: + dev->nr_zones_exp_open--; + break; + case BLK_ZONE_COND_CLOSED: + dev->nr_zones_closed--; + break; + default: + break; + } + spin_unlock(&dev->zone_res_lock); +} + /* * Set a zone in the read-only or offline condition. */ @@ -758,8 +786,8 @@ static void null_set_zone_cond(struct nullb_device *dev, * If the read-only condition is requested again to zones already in * read-only condition, restore back normal empty condition. Do the same * if the offline condition is requested for offline zones. Otherwise, - * set the specified zone condition to the zones. Finish the zones - * beforehand to free up zone resources. + * set the specified zone condition to the zones. Release the zone + * resources held by the zones beforehand. */ if (zone->cond == cond) { zone->cond = BLK_ZONE_COND_EMPTY; @@ -767,9 +795,7 @@ static void null_set_zone_cond(struct nullb_device *dev, if (dev->memory_backed) null_handle_discard(dev, zone->start, zone->len); } else { - if (zone->cond != BLK_ZONE_COND_READONLY && - zone->cond != BLK_ZONE_COND_OFFLINE) - null_finish_zone(dev, zone); + null_release_zone_resources(dev, zone); zone->cond = cond; zone->wp = NULL_ZONE_INVALID_WP; } diff --git a/drivers/block/ublk_drv.c b/drivers/block/ublk_drv.c index 8db1f9d9272c..a955a3ea471d 100644 --- a/drivers/block/ublk_drv.c +++ b/drivers/block/ublk_drv.c @@ -220,6 +220,8 @@ struct ublk_device { #define UB_STATE_OPEN 0 #define UB_STATE_USED 1 #define UB_STATE_DELETED 2 +/* STOP_DEV canceled the server's commands, until its release */ +#define UB_STATE_STOPPING 3 unsigned long state; int ub_number; @@ -233,6 +235,8 @@ struct ublk_device { u32 nr_io_ready; bool unprivileged_daemons; struct mutex cancel_mutex; + /* the open /dev/ublkcN, protected by cancel_mutex */ + struct file *ch_file; /* * A cancel started in this FETCH round. Set by ublk_set_canceling(), * cleared only by ublk_reset_ch_dev() when a new round starts. While @@ -1632,6 +1636,9 @@ static int ublk_ch_open(struct inode *inode, struct file *filp) return -EBUSY; filp->private_data = ub; ub->ublksrv_tgid = current->tgid; + mutex_lock(&ub->cancel_mutex); + ub->ch_file = filp; + mutex_unlock(&ub->cancel_mutex); return 0; } @@ -1652,6 +1659,7 @@ static void ublk_reset_ch_dev(struct ublk_device *ub) ub->nr_io_ready = 0; ub->unprivileged_daemons = false; ub->ublksrv_tgid = -1; + clear_bit(UB_STATE_STOPPING, &ub->state); } static struct gendisk *ublk_get_disk(struct ublk_device *ub) @@ -1856,6 +1864,9 @@ static int ublk_ch_release(struct inode *inode, struct file *filp) { struct ublk_device *ub = filp->private_data; + mutex_lock(&ub->cancel_mutex); + ub->ch_file = NULL; + mutex_unlock(&ub->cancel_mutex); /* * Grab ublk device reference, so it won't be gone until we are * really released from work function. @@ -2151,13 +2162,54 @@ static void ublk_stop_dev_unlocked(struct ublk_device *ub) put_disk(disk); } +static struct file *ublk_get_ch_file(struct ublk_device *ub) +{ + struct file *file; + + mutex_lock(&ub->cancel_mutex); + file = ub->ch_file; + if (file && !file_ref_get(&file->f_ref)) + file = NULL; + mutex_unlock(&ub->cancel_mutex); + return file; +} + static void ublk_stop_dev(struct ublk_device *ub) { + struct file *file; + + /* + * FETCH, PREP and START_DEV take ub->mutex. If a server has + * /dev/ublkcN open, set STOPPING, which turns it away, and hold a + * reference on the file: the server's release, whose reset clears + * STOPPING and lets a new server attach, can't run before we drop it. + * So the cancel can run after the unlock and only meets this server's + * commands; it has to: io_uring_cmd_done() may take uring_lock, under + * which FETCH takes ub->mutex. + */ mutex_lock(&ub->mutex); ublk_stop_dev_unlocked(ub); - mutex_unlock(&ub->mutex); cancel_work_sync(&ub->partition_scan_work); + file = ublk_get_ch_file(ub); + if (file) { + /* + * The server has to close /dev/ublkcN before this device can + * be started again: the reset in its release clears STOPPING. + */ + set_bit(UB_STATE_STOPPING, &ub->state); + /* for wake_up_var() below, see wake_up_bit() */ + smp_mb__after_atomic(); + } + mutex_unlock(&ub->mutex); + + /* no server: nothing to cancel */ + if (!file) + return; + + /* wake a START_DEV waiting for the device to get ready */ + wake_up_var(&ub->nr_io_ready); ublk_cancel_dev(ub); + __fput_sync(file); } /* reset ublk io_uring queue & io flags */ @@ -2417,6 +2469,11 @@ static int ublk_fetch(struct io_uring_cmd *cmd, struct ublk_device *ub, if (ret) goto out; + if (test_bit(UB_STATE_STOPPING, &ub->state)) { + ret = UBLK_IO_RES_ABORT; + goto out; + } + /* UBLK_IO_FETCH_REQ is only allowed before dev is setup */ if (ublk_dev_ready(ub)) { ret = -EBUSY; @@ -2905,14 +2962,18 @@ static int ublk_alloc_dev_number(struct ublk_device *ub, int idx) int i = idx; int err; + /* + * Only reserve the id: the device is published by + * ublk_publish_dev_number() once it is fully set up. + */ spin_lock(&ublk_idr_lock); /* allocate id, if @id >= 0, we're requesting that specific id */ if (i >= 0) { - err = idr_alloc(&ublk_index_idr, ub, i, i + 1, GFP_NOWAIT); + err = idr_alloc(&ublk_index_idr, NULL, i, i + 1, GFP_NOWAIT); if (err == -ENOSPC) err = -EEXIST; } else { - err = idr_alloc(&ublk_index_idr, ub, 0, UBLK_MAX_UBLKS, + err = idr_alloc(&ublk_index_idr, NULL, 0, UBLK_MAX_UBLKS, GFP_NOWAIT); } spin_unlock(&ublk_idr_lock); @@ -2923,6 +2984,19 @@ static int ublk_alloc_dev_number(struct ublk_device *ub, int idx) return err; } +/* + * Make the device visible to control commands by its id. Before its char + * device is added, DEL_DEV could find it and remove a char device that was + * never added, and drop the reference that ublk_add_chdev() drops on + * failure. + */ +static void ublk_publish_dev_number(struct ublk_device *ub) +{ + spin_lock(&ublk_idr_lock); + WARN_ON_ONCE(idr_replace(&ublk_index_idr, ub, ub->ub_number) != NULL); + spin_unlock(&ublk_idr_lock); +} + static void ublk_free_dev_number(struct ublk_device *ub) { spin_lock(&ublk_idr_lock); @@ -3029,22 +3103,27 @@ static bool ublk_validate_user_pid(struct ublk_device *ub, pid_t ublksrv_pid) return ub->ublksrv_tgid == ublksrv_pid; } +static bool ublk_dev_ready_or_stopping(const struct ublk_device *ub) +{ + return ublk_dev_ready(ub) || test_bit(UB_STATE_STOPPING, &ub->state); +} + /* - * Wait until all queues have fetched their I/O commands, and return with - * ub->mutex held and readiness guaranteed. The queues stay canceling if - * this round saw a cancel, see ublk_reset_io_flags(). Ready may regress - * between wakeup and mutex_lock() (daemon death), so re-check it under - * the mutex and wait again. + * Wait until all queues have fetched their I/O commands, or STOP_DEV set + * UB_STATE_STOPPING, and return with ub->mutex held. The queues stay + * canceling if this round saw a cancel, see ublk_reset_io_flags(). Ready + * may regress between wakeup and mutex_lock() (daemon death), so re-check + * it under the mutex and wait again. */ static int ublk_wait_dev_ready_and_lock(struct ublk_device *ub) { while (true) { if (wait_var_event_interruptible(&ub->nr_io_ready, - ublk_dev_ready(ub))) + ublk_dev_ready_or_stopping(ub))) return -EINTR; mutex_lock(&ub->mutex); - if (ublk_dev_ready(ub)) + if (ublk_dev_ready_or_stopping(ub)) return 0; mutex_unlock(&ub->mutex); } @@ -3127,6 +3206,10 @@ static int ublk_ctrl_start_dev(struct ublk_device *ub, ret = -EEXIST; goto out_unlock; } + if (test_bit(UB_STATE_STOPPING, &ub->state)) { + ret = -EBUSY; + goto out_unlock; + } disk = blk_mq_alloc_disk(&ub->tag_set, &lim, NULL); if (IS_ERR(disk)) { @@ -3409,6 +3492,8 @@ static int ublk_ctrl_add_dev(const struct ublksrv_ctrl_cmd *header) * ublk_add_chdev() will cleanup everything if it fails. */ ret = ublk_add_chdev(ub); + if (!ret) + ublk_publish_dev_number(ub); goto out_unlock; out_deinit_queues: diff --git a/drivers/block/virtio_blk.c b/drivers/block/virtio_blk.c index feb4dab8eac7..8ee96de51239 100644 --- a/drivers/block/virtio_blk.c +++ b/drivers/block/virtio_blk.c @@ -331,18 +331,25 @@ static inline u8 virtblk_vbr_status(struct virtblk_req *vbr) return *((u8 *)&vbr->in_hdr + vbr->in_hdr_len - 1); } +static inline void virtblk_update_zone_append_sector(struct request *req, + struct virtblk_req *vbr) +{ + struct virtio_blk *vblk = req->mq_hctx->queue->queuedata; + + if (req_op(req) == REQ_OP_ZONE_APPEND) + req->__sector = virtio64_to_cpu(vblk->vdev, + vbr->in_hdr.zone_append.sector); +} + static inline void virtblk_request_done(struct request *req) { struct virtblk_req *vbr = blk_mq_rq_to_pdu(req); blk_status_t status = virtblk_result(virtblk_vbr_status(vbr)); - struct virtio_blk *vblk = req->mq_hctx->queue->queuedata; virtblk_unmap_data(req, vbr); virtblk_cleanup_cmd(req); - if (req_op(req) == REQ_OP_ZONE_APPEND) - req->__sector = virtio64_to_cpu(vblk->vdev, - vbr->in_hdr.zone_append.sector); + virtblk_update_zone_append_sector(req, vbr); blk_mq_end_request(req, status); } @@ -1020,6 +1027,30 @@ static int init_vq(struct virtio_blk *vblk) goto out; for (i = 0; i < num_vqs; i++) { + unsigned int ring_size = virtqueue_get_vring_size(vqs[i]); + /* + * Each request consumes 2 extra descriptors (out_hdr and + * in_hdr) in addition to the data segments. + * + * At initial probe (!vblk->disk), each virtqueue must fit at + * least 1 data segment + 2 header descriptors (3). + * On resume/recovery (vblk->disk), each virtqueue must fit the + * existing queue_max_segments() + 2 header descriptors. + */ + unsigned int min_ring_size = 3; + + if (vblk->disk) + min_ring_size = queue_max_segments(vblk->disk->queue) + 2; + + if (ring_size < min_ring_size) { + dev_err(&vdev->dev, + "virtqueue %u ring size %u is smaller than minimum %u\n", + i, ring_size, min_ring_size); + vdev->config->del_vqs(vdev); + err = -EINVAL; + goto out; + } + spin_lock_init(&vblk->vqs[i].lock); vblk->vqs[i].vq = vqs[i]; } @@ -1189,8 +1220,11 @@ static void virtblk_complete_batch(struct io_comp_batch *iob) struct request *req; rq_list_for_each(&iob->req_list, req) { - virtblk_unmap_data(req, blk_mq_rq_to_pdu(req)); + struct virtblk_req *vbr = blk_mq_rq_to_pdu(req); + + virtblk_unmap_data(req, vbr); virtblk_cleanup_cmd(req); + virtblk_update_zone_append_sector(req, vbr); } blk_mq_end_request_batch(iob); } @@ -1247,7 +1281,7 @@ static int virtblk_read_limits(struct virtio_blk *vblk, u16 min_io_size; u8 physical_block_exp, alignment_offset; size_t max_dma_size; - int err; + int err, i; /* We need to know how many segments before we allocate. */ err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SEG_MAX, @@ -1261,6 +1295,23 @@ static int virtblk_read_limits(struct virtio_blk *vblk, /* Prevent integer overflows and honor max vq size */ sg_elems = min_t(u32, sg_elems, VIRTIO_BLK_MAX_SG_ELEMS - 2); + /* + * virtblk_add_req() uses separate outgoing and incoming header + * descriptors (out_hdr and in_hdr), consuming 2 extra descriptors + * per request in addition to the data segments. + * + * Per virtio specification (2.7.5.3.1), a driver MUST NOT create a + * descriptor chain longer than the Queue Size of the device. + * + * Clamp max_segments to (ring_size - 2) across all virtqueues so + * that a request never exceeds the ring size of any queue. + */ + for (i = 0; i < vblk->num_vqs; i++) { + u32 ring_size = virtqueue_get_vring_size(vblk->vqs[i].vq); + + sg_elems = min_t(u32, sg_elems, ring_size - 2); + } + /* We can handle whatever the host told us to handle. */ lim->max_segments = sg_elems; @@ -1460,6 +1511,7 @@ static int virtblk_probe(struct virtio_device *vdev) mutex_init(&vblk->vdev_mutex); vblk->vdev = vdev; + vblk->disk = NULL; INIT_WORK(&vblk->config_work, virtblk_config_changed_work); @@ -1541,6 +1593,7 @@ static int virtblk_probe(struct virtio_device *vdev) return 0; out_cleanup_disk: + virtio_reset_device(vdev); put_disk(vblk->disk); out_free_tags: blk_mq_free_tag_set(&vblk->tag_set); diff --git a/drivers/block/zloop.c b/drivers/block/zloop.c index 9986cfff47d6..8c80231c0873 100644 --- a/drivers/block/zloop.c +++ b/drivers/block/zloop.c @@ -865,7 +865,8 @@ static int zloop_init_zone(struct zloop_device *zlo, struct zloop_options *opts, if (restore && file_sectors != zlo->zone_size) { pr_err("Invalid conventional zone %u file size (%llu sectors != %llu)\n", - zone_no, file_sectors, zlo->zone_capacity); + zone_no, file_sectors, zlo->zone_size); + ret = -EINVAL; goto out_fput; } @@ -1024,8 +1025,8 @@ static int zloop_ctl_add(struct zloop_options *opts) zlo->disk = blk_mq_alloc_disk(&zlo->tag_set, &lim, zlo); if (IS_ERR(zlo->disk)) { - pr_err("blk_mq_alloc_disk failed (err=%d)\n", ret); ret = PTR_ERR(zlo->disk); + pr_err("blk_mq_alloc_disk failed (err=%d)\n", ret); goto out_cleanup_tags; } zlo->disk->flags = GENHD_FL_NO_PART; diff --git a/drivers/block/zram/zram_drv.c b/drivers/block/zram/zram_drv.c index ea5a9b81a310..1ef4a1594768 100644 --- a/drivers/block/zram/zram_drv.c +++ b/drivers/block/zram/zram_drv.c @@ -1134,72 +1134,73 @@ static void zram_debugfs_destroy(void) debugfs_remove_recursive(zram_debugfs_root); } -static ssize_t read_block_state(struct file *file, char __user *buf, - size_t count, loff_t *ppos) +static void *zram_block_state_start(struct seq_file *seq, loff_t *pos) { - char *kbuf; - ssize_t index, written = 0; - struct zram *zram = file->private_data; + struct zram *zram = seq->private; unsigned long nr_pages; - kbuf = kvmalloc(count, GFP_KERNEL); - if (!kbuf) - return -ENOMEM; - down_read(&zram->init_lock); - if (!init_done(zram)) { - up_read(&zram->init_lock); - kvfree(kbuf); - return -EINVAL; - } + if (!init_done(zram)) + return ERR_PTR(-EINVAL); nr_pages = zram->disksize >> PAGE_SHIFT; + if (*pos >= nr_pages) + return NULL; - for (index = *ppos; index < nr_pages; index++) { - int copied; - struct timespec64 ts; + return pos; +} - zram_slot_lock(zram, index); - if (!zram_allocated(zram, index)) - goto next; +static void *zram_block_state_next(struct seq_file *seq, void *v, loff_t *pos) +{ + struct zram *zram = seq->private; + unsigned long nr_pages = zram->disksize >> PAGE_SHIFT; - ts = ktime_to_timespec64(zram->table[index].ac_time); - copied = snprintf(kbuf + written, count, - "%12zd %12lld.%06lu %c%c%c%c%c%c\n", - index, (s64)ts.tv_sec, - ts.tv_nsec / NSEC_PER_USEC, - zram_test_flag(zram, index, ZRAM_SAME) ? 's' : '.', - zram_test_flag(zram, index, ZRAM_WB) ? 'w' : '.', - zram_test_flag(zram, index, ZRAM_HUGE) ? 'h' : '.', - zram_test_flag(zram, index, ZRAM_IDLE) ? 'i' : '.', - zram_get_priority(zram, index) ? 'r' : '.', - zram_test_flag(zram, index, - ZRAM_INCOMPRESSIBLE) ? 'n' : '.'); - - if (count <= copied) { - zram_slot_unlock(zram, index); - break; - } - written += copied; - count -= copied; -next: - zram_slot_unlock(zram, index); - *ppos += 1; - } + ++*pos; + if (*pos >= nr_pages) + return NULL; + + return pos; +} + +static void zram_block_state_stop(struct seq_file *seq, void *v) +{ + struct zram *zram = seq->private; up_read(&zram->init_lock); - if (copy_to_user(buf, kbuf, written)) - written = -EFAULT; - kvfree(kbuf); +} - return written; +static int zram_block_state_show(struct seq_file *seq, void *v) +{ + struct zram *zram = seq->private; + unsigned long index = *(loff_t *)v; + struct timespec64 ts; + + zram_slot_lock(zram, index); + if (zram_allocated(zram, index)) { + ts = ktime_to_timespec64(zram->table[index].ac_time); + seq_printf(seq, "%12lu %12lld.%06lu %c%c%c%c%c%c\n", + index, (s64)ts.tv_sec, + ts.tv_nsec / NSEC_PER_USEC, + zram_test_flag(zram, index, ZRAM_SAME) ? 's' : '.', + zram_test_flag(zram, index, ZRAM_WB) ? 'w' : '.', + zram_test_flag(zram, index, ZRAM_HUGE) ? 'h' : '.', + zram_test_flag(zram, index, ZRAM_IDLE) ? 'i' : '.', + zram_get_priority(zram, index) ? 'r' : '.', + zram_test_flag(zram, index, + ZRAM_INCOMPRESSIBLE) ? 'n' : '.'); + } + zram_slot_unlock(zram, index); + + return 0; } -static const struct file_operations proc_zram_block_state_op = { - .open = simple_open, - .read = read_block_state, - .llseek = default_llseek, +static const struct seq_operations zram_block_state_sops = { + .start = zram_block_state_start, + .next = zram_block_state_next, + .stop = zram_block_state_stop, + .show = zram_block_state_show, }; +DEFINE_SEQ_ATTRIBUTE(zram_block_state); static void zram_debugfs_register(struct zram *zram) { @@ -1209,7 +1210,7 @@ static void zram_debugfs_register(struct zram *zram) zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name, zram_debugfs_root); debugfs_create_file("block_state", 0400, zram->debugfs_dir, - zram, &proc_zram_block_state_op); + zram, &zram_block_state_fops); } static void zram_debugfs_unregister(struct zram *zram) diff --git a/drivers/bluetooth/btintel.c b/drivers/bluetooth/btintel.c index f56a4ebd26ed..86c3b319ae2a 100644 --- a/drivers/bluetooth/btintel.c +++ b/drivers/bluetooth/btintel.c @@ -1089,7 +1089,29 @@ static int btintel_download_firmware_payload(struct hci_dev *hdev, err = -EINVAL; while (fw_ptr - fw->data < fw->size) { - struct hci_command_hdr *cmd = (void *)(fw_ptr + frag_len); + struct hci_command_hdr *cmd; + size_t remain = fw->size - (fw_ptr - fw->data); + + /* Ensure the header fits before dereferencing */ + if (frag_len + sizeof(*cmd) > remain) { + bt_dev_err(hdev, + "Firmware buffer overrun at header (frag_len %u, need %zu, remain %zu)", + frag_len, frag_len + sizeof(*cmd), remain); + err = -EINVAL; + goto done; + } + + cmd = (void *)(fw_ptr + frag_len); + + /* Ensure the full command (header + payload) fits before use */ + if (frag_len + sizeof(*cmd) + cmd->plen > remain) { + bt_dev_err(hdev, + "Firmware buffer overrun at payload (frag_len %u, plen %u, need %zu, remain %zu)", + frag_len, cmd->plen, + frag_len + sizeof(*cmd) + cmd->plen, remain); + err = -EINVAL; + goto done; + } frag_len += sizeof(*cmd) + cmd->plen; diff --git a/drivers/bluetooth/btintel_pcie.c b/drivers/bluetooth/btintel_pcie.c index 3e8c894fbf64..3799e5b20d5f 100644 --- a/drivers/bluetooth/btintel_pcie.c +++ b/drivers/bluetooth/btintel_pcie.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -63,8 +64,6 @@ struct btintel_pcie_dev_recovery { #define BTINTEL_PCIE_HCI_EVT_PKT 0x00000004 #define BTINTEL_PCIE_HCI_ISO_PKT 0x00000005 -#define BTINTEL_PCIE_MAGIC_NUM 0xA5A5A5A5 - #define BTINTEL_PCIE_BLZR_HWEXP_SIZE 1024 #define BTINTEL_PCIE_BLZR_HWEXP_DMP_ADDR 0xB00A7C00 @@ -2582,10 +2581,12 @@ static int btintel_pcie_suspend_late(struct device *dev, pm_message_t mesg) data = pci_get_drvdata(pdev); - dxstate = (mesg.event == PM_EVENT_SUSPEND ? - BTINTEL_PCIE_STATE_D3_HOT : BTINTEL_PCIE_STATE_D3_COLD); - - data->pm_sx_event = mesg.event; + /* S0ix (s2idle) uses D3_HOT; S3, freeze and hibernate use D3_COLD. */ + if (mesg.event == PM_EVENT_SUSPEND && + pm_suspend_target_state == PM_SUSPEND_TO_IDLE) + dxstate = BTINTEL_PCIE_STATE_D3_HOT; + else + dxstate = BTINTEL_PCIE_STATE_D3_COLD; data->gp0_received = false; @@ -2624,7 +2625,7 @@ static int btintel_pcie_freeze(struct device *dev) return btintel_pcie_suspend_late(dev, PMSG_FREEZE); } -static int btintel_pcie_resume(struct device *dev) +static int btintel_pcie_resume_event(struct device *dev, pm_message_t mesg) { struct pci_dev *pdev = to_pci_dev(dev); struct btintel_pcie_data *data; @@ -2636,15 +2637,12 @@ static int btintel_pcie_resume(struct device *dev) start = ktime_get(); - /* When the system enters S4 (hibernate) mode, bluetooth device loses - * power, which results in the erasure of its loaded firmware. - * Consequently, function level reset (flr) is required on system - * resume to bring the controller back into an operational state by - * initiating a new firmware download. + /* S3 and S4 may cut power, erasing the firmware. Force FLR to recover + * instead of a normal D0 transition. */ - - if (data->pm_sx_event == PM_EVENT_FREEZE || - data->pm_sx_event == PM_EVENT_HIBERNATE) { + if (mesg.event == PM_EVENT_RESTORE || + (mesg.event == PM_EVENT_RESUME && + pm_suspend_target_state == PM_SUSPEND_MEM)) { set_bit(BTINTEL_PCIE_CORE_HALTED, &data->flags); btintel_pcie_reset(data->hdev); return 0; @@ -2687,13 +2685,28 @@ static int btintel_pcie_resume(struct device *dev) return 0; } +static int btintel_pcie_resume(struct device *dev) +{ + return btintel_pcie_resume_event(dev, PMSG_RESUME); +} + +static int btintel_pcie_restore(struct device *dev) +{ + return btintel_pcie_resume_event(dev, PMSG_RESTORE); +} + +static int btintel_pcie_thaw(struct device *dev) +{ + return btintel_pcie_resume_event(dev, PMSG_THAW); +} + static const struct dev_pm_ops btintel_pcie_pm_ops = { .suspend = btintel_pcie_suspend, .resume = btintel_pcie_resume, .freeze = btintel_pcie_freeze, - .thaw = btintel_pcie_resume, + .thaw = btintel_pcie_thaw, .poweroff = btintel_pcie_hibernate, - .restore = btintel_pcie_resume, + .restore = btintel_pcie_restore, }; static struct pci_driver btintel_pcie_driver = { diff --git a/drivers/bluetooth/btintel_pcie.h b/drivers/bluetooth/btintel_pcie.h index 481de85456e2..43be595d20b6 100644 --- a/drivers/bluetooth/btintel_pcie.h +++ b/drivers/bluetooth/btintel_pcie.h @@ -461,7 +461,6 @@ struct btintel_pcie_dump_header { * @txq: TX Queue struct * @rxq: RX Queue struct * @alive_intr_ctxt: Alive interrupt context - * @pm_sx_event: PM event on which system got suspended */ struct btintel_pcie_data { struct pci_dev *pdev; @@ -511,7 +510,6 @@ struct btintel_pcie_data { u32 alive_intr_ctxt; struct btintel_pcie_dbgc dbgc; struct btintel_pcie_dump_header dmp_hdr; - u8 pm_sx_event; }; static inline u32 btintel_pcie_rd_reg32(struct btintel_pcie_data *data, diff --git a/drivers/bluetooth/btmtk.c b/drivers/bluetooth/btmtk.c index 961a47a9c8c4..50e0ff30e8db 100644 --- a/drivers/bluetooth/btmtk.c +++ b/drivers/bluetooth/btmtk.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -24,7 +25,7 @@ #define MTK_SEC_MAP_NEED_SEND_SIZE 52 /* It is for mt79xx iso data transmission setting */ -#define MTK_ISO_THRESHOLD 264 +#define MTK_ISO_THRESHOLD 342 struct btmtk_patch_header { u8 datetime[16]; @@ -1167,8 +1168,15 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count) struct btmtk_data *btmtk_data = hci_get_priv(hdev); struct sk_buff *skb; unsigned long flags; + unsigned int iso_mtu; int err = 0; + /* The controller reports the largest Data_Total_Length it will send in + * LE Read Buffer Size [v2]. Fall back to HCI_MAX_ISO_SIZE while that + * command has not completed yet. + */ + iso_mtu = hdev->iso_mtu ? hdev->iso_mtu : HCI_MAX_ISO_SIZE; + spin_lock_irqsave(&btmtk_data->isorxlock, flags); skb = btmtk_data->isopkt_skb; @@ -1176,7 +1184,16 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count) int len; if (!skb) { - skb = bt_skb_alloc(HCI_MAX_ISO_SIZE, GFP_ATOMIC); + /* Drop the endpoint's zero-filled padding before + * allocating an skb for it; a zero Data_Total_Length + * check below would miss a padding remainder + * shorter than an ISO header. + */ + if (mem_is_zero(buffer, count)) + break; + + skb = bt_skb_alloc(HCI_ISO_HDR_SIZE + iso_mtu, + GFP_ATOMIC); if (!skb) { err = -ENOMEM; break; @@ -1199,7 +1216,24 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count) /* Complete ISO header */ hci_skb_expect(skb) = __le16_to_cpu(dlen); - if (skb_tailroom(skb) < hci_skb_expect(skb)) { + if (!hci_skb_expect(skb)) { + /* Zero padding was ruled out above, so a + * zero Data_Total_Length here is invalid. + */ + kfree_skb(skb); + skb = NULL; + + err = -EILSEQ; + break; + } + + /* Reject a length the controller said it would never + * send. The skb_tailroom() test is kept because a + * fragment started before hdev->iso_mtu was populated + * sits in a smaller skb than iso_mtu now allows. + */ + if (hci_skb_expect(skb) > iso_mtu || + skb_tailroom(skb) < hci_skb_expect(skb)) { kfree_skb(skb); skb = NULL; @@ -1318,13 +1352,15 @@ static int btmtk_submit_intr_urb(struct hci_dev *hdev, gfp_t mem_flags) static int btmtk_usb_isointf_init(struct hci_dev *hdev) { struct btmtk_data *btmtk_data = hci_get_priv(hdev); - u8 iso_param[2] = { 0x08, 0x01 }; + __le16 iso_param = cpu_to_le16(MTK_ISO_THRESHOLD); struct sk_buff *skb; int err; spin_lock_init(&btmtk_data->isorxlock); - __set_mtk_intr_interface(hdev); + err = __set_mtk_intr_interface(hdev); + if (err < 0) + return err; err = btmtk_submit_intr_urb(hdev, GFP_KERNEL); if (err < 0) { @@ -1333,9 +1369,10 @@ static int btmtk_usb_isointf_init(struct hci_dev *hdev) return err; } - skb = __hci_cmd_sync(hdev, 0xfd98, sizeof(iso_param), iso_param, + skb = __hci_cmd_sync(hdev, 0xfd98, sizeof(iso_param), &iso_param, HCI_INIT_TIMEOUT); if (IS_ERR(skb)) { + usb_kill_anchored_urbs(&btmtk_data->isopkt_anchor); bt_dev_err(hdev, "Failed to apply iso setting (%ld)", PTR_ERR(skb)); return PTR_ERR(skb); } diff --git a/drivers/bluetooth/btqca.c b/drivers/bluetooth/btqca.c index 4215522e62a2..ba0b8869b3f6 100644 --- a/drivers/bluetooth/btqca.c +++ b/drivers/bluetooth/btqca.c @@ -948,6 +948,7 @@ int qca_uart_setup(struct hci_dev *hdev, uint8_t baudrate, switch (soc_type) { case QCA_QCA2066: case QCA_QCA6390: + case QCA_WCN3950: case QCA_WCN3991: case QCA_WCN6750: case QCA_WCN6855: diff --git a/drivers/bluetooth/hci_qca.c b/drivers/bluetooth/hci_qca.c index b3b267e77e4f..51123a6e5fe7 100644 --- a/drivers/bluetooth/hci_qca.c +++ b/drivers/bluetooth/hci_qca.c @@ -162,6 +162,7 @@ struct qca_data { struct delayed_work ctrl_memdump_timeout; struct qca_memdump_info *qca_memdump; unsigned long flags; + struct dentry *debugfs_ibs_dir; struct completion drop_ev_comp; wait_queue_head_t suspend_wait_q; enum qca_memdump_states memdump_state; @@ -667,6 +668,7 @@ static void qca_debugfs_init(struct hci_dev *hdev) return; ibs_dir = debugfs_create_dir("ibs", hdev->debugfs); + qca->debugfs_ibs_dir = ibs_dir; /* read only */ mode = 0444; @@ -742,6 +744,9 @@ static int qca_close(struct hci_uart *hu) hu->priv = NULL; + debugfs_remove_recursive(qca->debugfs_ibs_dir); + qca->debugfs_ibs_dir = NULL; + kfree(qca); return 0; diff --git a/drivers/char/tpm/eventlog/acpi.c b/drivers/char/tpm/eventlog/acpi.c index cf02ec646f46..50770cafa835 100644 --- a/drivers/char/tpm/eventlog/acpi.c +++ b/drivers/char/tpm/eventlog/acpi.c @@ -167,10 +167,8 @@ int tpm_read_log_acpi(struct tpm_chip *chip) } ret = devm_add_action(&chip->dev, tpm_bios_log_free, log->bios_event_log); - if (ret) { - log->bios_event_log = NULL; + if (ret) goto err; - } return format; diff --git a/drivers/char/tpm/eventlog/tpm1.c b/drivers/char/tpm/eventlog/tpm1.c index 0397e3361020..f93a358a706e 100644 --- a/drivers/char/tpm/eventlog/tpm1.c +++ b/drivers/char/tpm/eventlog/tpm1.c @@ -178,6 +178,10 @@ static int get_event_name(char *dest, struct tcpa_event *event, } break; case EVENT_TAG: + if (do_endian_conversion(event->event_size) < + sizeof(pc_event->event_id)) + break; + pc_event = (struct tcpa_pc_event *)event_entry; /* ToDo Row data -> Base64 */ @@ -203,6 +207,9 @@ static int get_event_name(char *dest, struct tcpa_event *event, name = tcpa_pc_event_id_strings[do_endian_conversion (pc_event->event_id)]; n_len = strlen(name); + if (do_endian_conversion(event->event_size) < + sizeof(struct tcpa_pc_event) + 20) + break; for (i = 0; i < 20; i++) d_len += sprintf(&data[2*i], "%02x", pc_event->event_data[i]); diff --git a/drivers/char/tpm/tpm-dev-common.c b/drivers/char/tpm/tpm-dev-common.c index a856b4ddbdc2..c77fee400116 100644 --- a/drivers/char/tpm/tpm-dev-common.c +++ b/drivers/char/tpm/tpm-dev-common.c @@ -132,6 +132,7 @@ ssize_t tpm_common_read(struct file *file, char __user *buf, { struct file_priv *priv = file->private_data; ssize_t ret_size = 0; + bool flush = false; int rc; if (!size) @@ -164,9 +165,18 @@ ssize_t tpm_common_read(struct file *file, char __user *buf, if (!priv->response_length) { *off = 0; timer_delete_sync(&priv->user_read_timer); - flush_work(&priv->timeout_work); + flush = true; } mutex_unlock(&priv->buffer_mutex); + + /* + * tpm_timeout_work() takes buffer_mutex, so flush it after dropping + * the mutex to avoid a deadlock; the timer is deleted above, so no new + * timeout work can be queued once the mutex is released. + */ + if (flush) + flush_work(&priv->timeout_work); + return ret_size; } diff --git a/drivers/char/tpm/tpm2-sessions.c b/drivers/char/tpm/tpm2-sessions.c index c330f3bae8b2..a9edff9194a1 100644 --- a/drivers/char/tpm/tpm2-sessions.c +++ b/drivers/char/tpm/tpm2-sessions.c @@ -535,7 +535,9 @@ static int tpm_buf_append_salt(struct tpm_buf *buf, struct tpm_chip *chip, } crypto_ecdh_encode_key(encoded_key, buf_len, &p); /* this generates a random private key */ - crypto_kpp_set_secret(kpp, encoded_key, buf_len); + rc = crypto_kpp_set_secret(kpp, encoded_key, buf_len); + if (rc) + goto err_free_kpp; /* salt is now the public point of this private key */ req = kpp_request_alloc(kpp, GFP_KERNEL); diff --git a/drivers/comedi/drivers/addi_apci_1500.c b/drivers/comedi/drivers/addi_apci_1500.c index c94c78588889..b4f5d9cea0b2 100644 --- a/drivers/comedi/drivers/addi_apci_1500.c +++ b/drivers/comedi/drivers/addi_apci_1500.c @@ -696,7 +696,7 @@ static int apci1500_timer_insn_config(struct comedi_device *dev, return -EINVAL; val = z8536_read(dev, Z8536_CT_MODE_REG(chan)); - val &= Z8536_CT_MODE_EGE; + val &= ~Z8536_CT_MODE_EGE; if (data[1] == 1) val |= Z8536_CT_MODE_EGE; else if (data[1] > 1) diff --git a/drivers/comedi/drivers/ni_660x.c b/drivers/comedi/drivers/ni_660x.c index 0679bc39e0bc..38bb703a748e 100644 --- a/drivers/comedi/drivers/ni_660x.c +++ b/drivers/comedi/drivers/ni_660x.c @@ -459,7 +459,8 @@ static int ni_660x_input_poll(struct comedi_device *dev, /* lock to avoid race with comedi_poll */ spin_lock_irqsave(&devpriv->interrupt_lock, flags); - mite_sync_dma(counter->mite_chan, s); + if (counter->mite_chan) + mite_sync_dma(counter->mite_chan, s); spin_unlock_irqrestore(&devpriv->interrupt_lock, flags); return comedi_buf_read_n_available(s); } diff --git a/drivers/comedi/drivers/ni_tio.c b/drivers/comedi/drivers/ni_tio.c index da6826d77e60..98b5b44416cf 100644 --- a/drivers/comedi/drivers/ni_tio.c +++ b/drivers/comedi/drivers/ni_tio.c @@ -800,7 +800,7 @@ static int ni_tio_set_clock_src(struct ni_gpct *counter, GI_PRESCALE_X2(counter_dev->variant) | GI_PRESCALE_X8(counter_dev->variant), bits); } - counter->clock_period_ps = period_ns * 1000; + counter->clock_period_ps = (u64)period_ns * 1000; ni_tio_set_sync_mode(counter); return 0; } diff --git a/drivers/comedi/drivers/vmk80xx.c b/drivers/comedi/drivers/vmk80xx.c index 84dce5184a77..ddb12b48c8a4 100644 --- a/drivers/comedi/drivers/vmk80xx.c +++ b/drivers/comedi/drivers/vmk80xx.c @@ -151,7 +151,7 @@ struct vmk80xx_private { enum vmk80xx_model model; }; -static void vmk80xx_do_bulk_msg(struct comedi_device *dev) +static int vmk80xx_do_bulk_msg(struct comedi_device *dev) { struct vmk80xx_private *devpriv = dev->private; struct usb_device *usb = comedi_to_usb_dev(dev); @@ -161,6 +161,7 @@ static void vmk80xx_do_bulk_msg(struct comedi_device *dev) unsigned int rx_pipe; size_t tx_size; size_t rx_size; + int ret; tx_addr = devpriv->ep_tx->bEndpointAddress; rx_addr = devpriv->ep_rx->bEndpointAddress; @@ -169,11 +170,13 @@ static void vmk80xx_do_bulk_msg(struct comedi_device *dev) tx_size = usb_endpoint_maxp(devpriv->ep_tx); rx_size = usb_endpoint_maxp(devpriv->ep_rx); - usb_bulk_msg(usb, tx_pipe, devpriv->usb_tx_buf, tx_size, NULL, - PACKET_TIMEOUT); + ret = usb_bulk_msg(usb, tx_pipe, devpriv->usb_tx_buf, tx_size, NULL, + PACKET_TIMEOUT); + if (ret) + return ret; - usb_bulk_msg(usb, rx_pipe, devpriv->usb_rx_buf, rx_size, NULL, - PACKET_TIMEOUT); + return usb_bulk_msg(usb, rx_pipe, devpriv->usb_rx_buf, rx_size, NULL, + PACKET_TIMEOUT); } static int vmk80xx_read_packet(struct comedi_device *dev) @@ -183,10 +186,8 @@ static int vmk80xx_read_packet(struct comedi_device *dev) struct usb_endpoint_descriptor *ep; unsigned int pipe; - if (devpriv->model == VMK8061_MODEL) { - vmk80xx_do_bulk_msg(dev); - return 0; - } + if (devpriv->model == VMK8061_MODEL) + return vmk80xx_do_bulk_msg(dev); ep = devpriv->ep_rx; pipe = usb_rcvintpipe(usb, ep->bEndpointAddress); @@ -204,10 +205,8 @@ static int vmk80xx_write_packet(struct comedi_device *dev, int cmd) devpriv->usb_tx_buf[0] = cmd; - if (devpriv->model == VMK8061_MODEL) { - vmk80xx_do_bulk_msg(dev); - return 0; - } + if (devpriv->model == VMK8061_MODEL) + return vmk80xx_do_bulk_msg(dev); ep = devpriv->ep_tx; pipe = usb_sndintpipe(usb, ep->bEndpointAddress); diff --git a/drivers/cpufreq/acpi-cpufreq.c b/drivers/cpufreq/acpi-cpufreq.c index 083d8369a591..0e3840da24b1 100644 --- a/drivers/cpufreq/acpi-cpufreq.c +++ b/drivers/cpufreq/acpi-cpufreq.c @@ -197,14 +197,13 @@ static unsigned extract_io(struct cpufreq_policy *policy, u32 value) { struct acpi_cpufreq_data *data = policy->driver_data; struct acpi_processor_performance *perf; - int i; + struct cpufreq_frequency_table *pos; perf = to_perf_data(data); - for (i = 0; i < perf->state_count; i++) { - if (value == perf->states[i].status) - return policy->freq_table[i].frequency; - } + cpufreq_for_each_entry(pos, policy->freq_table) + if (value == perf->states[pos->driver_data].status) + return pos->frequency; return 0; } diff --git a/drivers/cpufreq/cpufreq.c b/drivers/cpufreq/cpufreq.c index ec577a20567b..962faa2463db 100644 --- a/drivers/cpufreq/cpufreq.c +++ b/drivers/cpufreq/cpufreq.c @@ -35,6 +35,9 @@ static LIST_HEAD(cpufreq_policy_list); /* Macros to iterate over CPU policies */ +#define for_each_policy(__policy) \ + list_for_each_entry(__policy, &cpufreq_policy_list, policy_list) + #define for_each_suitable_policy(__policy, __active) \ list_for_each_entry(__policy, &cpufreq_policy_list, policy_list) \ if ((__active) == !policy_is_inactive(__policy)) @@ -506,8 +509,8 @@ static unsigned int __resolve_freq(struct cpufreq_policy *policy, idx = cpufreq_frequency_table_target(policy, target_freq, min, max, relation); policy->cached_resolved_idx = idx; - policy->cached_target_freq = target_freq; - return policy->freq_table[idx].frequency; + policy->cached_target_freq = policy->freq_table[idx].frequency; + return policy->cached_target_freq; } /** @@ -597,6 +600,8 @@ static int policy_set_boost(struct cpufreq_policy *policy, bool enable) { int ret; + lockdep_assert_held_write(&policy->rwsem); + if (policy->boost_enabled == enable) return 0; @@ -1631,6 +1636,8 @@ static int cpufreq_online(unsigned int cpu) */ if (cpufreq_driver->set_boost && policy->boost_supported && (new_policy || !cpufreq_boost_enabled())) { + guard(cpufreq_policy_write)(policy); + ret = policy_set_boost(policy, cpufreq_boost_enabled()); if (ret) { /* If the set_boost fails, the online operation is not affected */ @@ -1958,6 +1965,14 @@ int cpufreq_generic_suspend(struct cpufreq_policy *policy) } EXPORT_SYMBOL(cpufreq_generic_suspend); +static void cpufreq_suspend_policy(struct cpufreq_policy *policy) +{ + guard(cpufreq_policy_write)(policy); + + cpufreq_stop_governor(policy); + policy->suspended = true; +} + /** * cpufreq_suspend() - Suspend CPUFreq governors. * @@ -1980,11 +1995,8 @@ void cpufreq_suspend(void) pr_debug("%s: Suspending Governors\n", __func__); for_each_active_policy(policy) { - if (has_target()) { - scoped_guard(cpufreq_policy_write, policy) { - cpufreq_stop_governor(policy); - } - } + if (has_target()) + cpufreq_suspend_policy(policy); if (cpufreq_driver->suspend && cpufreq_driver->suspend(policy)) pr_err("%s: Failed to suspend driver: %s\n", __func__, @@ -1996,6 +2008,32 @@ void cpufreq_suspend(void) cpus_read_unlock(); } +static void cpufreq_resume_policy(struct cpufreq_policy *policy, bool start) +{ + guard(cpufreq_policy_write)(policy); + + if (!policy->suspended) + return; + + policy->suspended = false; + + if (policy_is_inactive(policy)) { + /* + * The policy was active when it was suspended, so its governor + * is still there. Let the governor go. + */ + cpufreq_exit_governor(policy); + return; + } + + if (!start) + return; + + if (cpufreq_start_governor(policy)) + pr_err("%s: Failed to start governor for CPU%u's policy\n", + __func__, policy->cpu); +} + /** * cpufreq_resume() - Resume CPUFreq governors. * @@ -2005,11 +2043,12 @@ void cpufreq_suspend(void) void cpufreq_resume(void) { struct cpufreq_policy *policy; - int ret; if (!cpufreq_driver) return; + guard(cpus_read_lock)(); + if (unlikely(!cpufreq_suspended)) return; @@ -2020,19 +2059,18 @@ void cpufreq_resume(void) pr_debug("%s: Resuming Governors\n", __func__); - for_each_active_policy(policy) { - if (cpufreq_driver->resume && cpufreq_driver->resume(policy)) { - pr_err("%s: Failed to resume driver: %s\n", __func__, - cpufreq_driver->name); - } else if (has_target()) { - scoped_guard(cpufreq_policy_write, policy) { - ret = cpufreq_start_governor(policy); - } + for_each_policy(policy) { + int ret = 0; + if (cpufreq_driver->resume && !policy_is_inactive(policy)) { + ret = cpufreq_driver->resume(policy); if (ret) - pr_err("%s: Failed to start governor for CPU%u's policy\n", - __func__, policy->cpu); + pr_err("%s: Failed to resume driver: %s\n", __func__, + cpufreq_driver->name); } + + if (has_target()) + cpufreq_resume_policy(policy, ret == 0); } } @@ -2406,12 +2444,17 @@ __weak struct cpufreq_governor *cpufreq_fallback_governor(void) return NULL; } +static bool cpufreq_is_suspended(struct cpufreq_policy *policy) +{ + return cpufreq_suspended || policy->suspended; +} + static int cpufreq_init_governor(struct cpufreq_policy *policy) { int ret; - /* Don't start any governor operations if we are entering suspend */ - if (cpufreq_suspended) + /* Don't start any governor operations for suspended policies. */ + if (cpufreq_is_suspended(policy)) return 0; /* * Governor might not be initiated here if ACPI _PPC changed @@ -2454,7 +2497,7 @@ static int cpufreq_init_governor(struct cpufreq_policy *policy) static void cpufreq_exit_governor(struct cpufreq_policy *policy) { - if (cpufreq_suspended || !policy->governor) + if (cpufreq_is_suspended(policy) || !policy->governor) return; pr_debug("%s: for CPU %u\n", __func__, policy->cpu); @@ -2469,7 +2512,7 @@ int cpufreq_start_governor(struct cpufreq_policy *policy) { int ret; - if (cpufreq_suspended) + if (cpufreq_is_suspended(policy)) return 0; if (!policy->governor) @@ -2493,7 +2536,7 @@ int cpufreq_start_governor(struct cpufreq_policy *policy) void cpufreq_stop_governor(struct cpufreq_policy *policy) { - if (cpufreq_suspended || !policy->governor) + if (cpufreq_is_suspended(policy) || !policy->governor) return; pr_debug("%s: for CPU %u\n", __func__, policy->cpu); @@ -2504,7 +2547,7 @@ void cpufreq_stop_governor(struct cpufreq_policy *policy) static void cpufreq_governor_limits(struct cpufreq_policy *policy) { - if (cpufreq_suspended || !policy->governor) + if (cpufreq_is_suspended(policy) || !policy->governor) return; pr_debug("%s: for CPU %u\n", __func__, policy->cpu); @@ -2732,7 +2775,8 @@ static void cpufreq_policy_refresh(struct cpufreq_policy *policy) * -> ask driver for current freq and notify governors about a change */ if (cpufreq_driver->get && has_target() && - (cpufreq_suspended || WARN_ON(!cpufreq_verify_current_freq(policy, false)))) + (cpufreq_is_suspended(policy) || + WARN_ON(!cpufreq_verify_current_freq(policy, false)))) return; refresh_frequency_limits(policy); @@ -2801,11 +2845,16 @@ int cpufreq_boost_set_sw(struct cpufreq_policy *policy, int state) } EXPORT_SYMBOL_GPL(cpufreq_boost_set_sw); +static DEFINE_MUTEX(cpufreq_boost_mutex); + static int cpufreq_boost_trigger_state(int state) { struct cpufreq_policy *policy; unsigned long flags; - int ret = 0; + bool boost_enabled; + int ret = -EOPNOTSUPP; + + guard(mutex)(&cpufreq_boost_mutex); /* * Don't compare 'cpufreq_driver->boost_enabled' with 'state' here to @@ -2813,6 +2862,7 @@ static int cpufreq_boost_trigger_state(int state) */ write_lock_irqsave(&cpufreq_driver_lock, flags); + boost_enabled = cpufreq_driver->boost_enabled; cpufreq_driver->boost_enabled = state; write_unlock_irqrestore(&cpufreq_driver_lock, flags); @@ -2821,10 +2871,16 @@ static int cpufreq_boost_trigger_state(int state) if (!policy->boost_supported) continue; + guard(cpufreq_policy_write)(policy); + ret = policy_set_boost(policy, state); if (ret) goto err_reset_state; } + + if (ret) + goto err_reset_state; + cpus_read_unlock(); return 0; @@ -2833,7 +2889,7 @@ static int cpufreq_boost_trigger_state(int state) cpus_read_unlock(); write_lock_irqsave(&cpufreq_driver_lock, flags); - cpufreq_driver->boost_enabled = !state; + cpufreq_driver->boost_enabled = boost_enabled; write_unlock_irqrestore(&cpufreq_driver_lock, flags); pr_err("%s: Cannot %s BOOST\n", diff --git a/drivers/cpufreq/intel_pstate.c b/drivers/cpufreq/intel_pstate.c index a498d66883b5..fcc41591a3d3 100644 --- a/drivers/cpufreq/intel_pstate.c +++ b/drivers/cpufreq/intel_pstate.c @@ -3412,10 +3412,11 @@ static void intel_cpufreq_cpu_exit(struct cpufreq_policy *policy) static int intel_cpufreq_suspend(struct cpufreq_policy *policy) { + struct cpudata *cpu = all_cpu_data[policy->cpu]; + intel_pstate_suspend(policy); if (hwp_active) { - struct cpudata *cpu = all_cpu_data[policy->cpu]; u64 value = READ_ONCE(cpu->hwp_req_cached); /* @@ -3426,6 +3427,17 @@ static int intel_cpufreq_suspend(struct cpufreq_policy *policy) value &= ~HWP_DESIRED_PERF(~0L); wrmsrq_on_cpu(cpu->cpu, MSR_HWP_REQUEST, value); WRITE_ONCE(cpu->hwp_req_cached, value); + } else { + /* + * Invalidate the cached P-state value that may be stale when + * the governor is started again during resume and may prevent + * MSR_IA32_PERF_CTL from being updated. + * + * This does not require synchronization because the core + * prevents frequency updates for suspended policies from + * occurring. + */ + cpu->pstate.current_pstate = 0; } return 0; @@ -3671,12 +3683,12 @@ static struct acpi_platform_list plat_info[] __initdata = { static bool __init intel_pstate_platform_pwr_mgmt_exists(void) { const struct x86_cpu_id *id; - u64 misc_pwr; + u64 misc_pwr = 0; int idx; id = x86_match_cpu(intel_pstate_cpu_oob_ids); if (id) { - rdmsrq(MSR_MISC_PWR_MGMT, misc_pwr); + rdmsrq_safe(MSR_MISC_PWR_MGMT, &misc_pwr); if (misc_pwr & BITMASK_OOB) { pr_debug("Bit 8 or 18 in the MISC_PWR_MGMT MSR set\n"); pr_debug("P states are controlled in Out of Band mode by the firmware/hardware\n"); diff --git a/drivers/crypto/caam/caampkc.c b/drivers/crypto/caam/caampkc.c index ac515ed8c575..2082adaae585 100644 --- a/drivers/crypto/caam/caampkc.c +++ b/drivers/crypto/caam/caampkc.c @@ -880,7 +880,7 @@ static void caam_rsa_free_key(struct caam_rsa_key *key) static void caam_rsa_drop_leading_zeros(const u8 **ptr, size_t *nbytes) { - while (!**ptr && *nbytes) { + while (*nbytes && !**ptr) { (*ptr)++; (*nbytes)--; } @@ -896,22 +896,22 @@ static void caam_rsa_drop_leading_zeros(const u8 **ptr, size_t *nbytes) * @ptr : pointer to {dP, dQ, qInv} CRT member * @nbytes: length in bytes of {dP, dQ, qInv} CRT member * @dstlen: length in bytes of corresponding p or q prime factor + * @dst : pointer to the zero-padded output buffer */ -static u8 *caam_read_rsa_crt(const u8 *ptr, size_t nbytes, size_t dstlen) +static int caam_read_rsa_crt(const u8 *ptr, size_t nbytes, size_t dstlen, + u8 **dst) { - u8 *dst; - caam_rsa_drop_leading_zeros(&ptr, &nbytes); - if (!nbytes) - return NULL; + if (!nbytes || nbytes > dstlen) + return -EINVAL; - dst = kzalloc(dstlen, GFP_KERNEL); - if (!dst) - return NULL; + *dst = kzalloc(dstlen, GFP_KERNEL); + if (!*dst) + return -ENOMEM; - memcpy(dst + (dstlen - nbytes), ptr, nbytes); + memcpy(*dst + (dstlen - nbytes), ptr, nbytes); - return dst; + return 0; } /** @@ -991,6 +991,7 @@ static int caam_rsa_set_priv_key_form(struct caam_rsa_ctx *ctx, size_t p_sz = raw_key->p_sz; size_t q_sz = raw_key->q_sz; unsigned aligned_size; + int ret; rsa_key->p = caam_read_raw_data(raw_key->p, &p_sz); if (!rsa_key->p) @@ -999,57 +1000,39 @@ static int caam_rsa_set_priv_key_form(struct caam_rsa_ctx *ctx, rsa_key->q = caam_read_raw_data(raw_key->q, &q_sz); if (!rsa_key->q) - goto free_p; + return -ENOMEM; rsa_key->q_sz = q_sz; aligned_size = ALIGN(raw_key->p_sz, dma_get_cache_alignment()); rsa_key->tmp1 = kzalloc(aligned_size, GFP_KERNEL); if (!rsa_key->tmp1) - goto free_q; + return -ENOMEM; aligned_size = ALIGN(raw_key->q_sz, dma_get_cache_alignment()); rsa_key->tmp2 = kzalloc(aligned_size, GFP_KERNEL); if (!rsa_key->tmp2) - goto free_tmp1; + return -ENOMEM; rsa_key->priv_form = FORM2; - rsa_key->dp = caam_read_rsa_crt(raw_key->dp, raw_key->dp_sz, p_sz); - if (!rsa_key->dp) - goto free_tmp2; + ret = caam_read_rsa_crt(raw_key->dp, raw_key->dp_sz, p_sz, + &rsa_key->dp); + if (ret) + return ret; - rsa_key->dq = caam_read_rsa_crt(raw_key->dq, raw_key->dq_sz, q_sz); - if (!rsa_key->dq) - goto free_dp; + ret = caam_read_rsa_crt(raw_key->dq, raw_key->dq_sz, q_sz, + &rsa_key->dq); + if (ret) + return ret; - rsa_key->qinv = caam_read_rsa_crt(raw_key->qinv, raw_key->qinv_sz, - q_sz); - if (!rsa_key->qinv) - goto free_dq; + ret = caam_read_rsa_crt(raw_key->qinv, raw_key->qinv_sz, p_sz, + &rsa_key->qinv); + if (ret) + return ret; rsa_key->priv_form = FORM3; return 0; - -free_dq: - kfree_sensitive(rsa_key->dq); - rsa_key->dq = NULL; -free_dp: - kfree_sensitive(rsa_key->dp); - rsa_key->dp = NULL; -free_tmp2: - kfree_sensitive(rsa_key->tmp2); - rsa_key->tmp2 = NULL; -free_tmp1: - kfree_sensitive(rsa_key->tmp1); - rsa_key->tmp1 = NULL; -free_q: - kfree_sensitive(rsa_key->q); - rsa_key->q = NULL; -free_p: - kfree_sensitive(rsa_key->p); - rsa_key->p = NULL; - return -ENOMEM; } static int caam_rsa_set_priv_key(struct crypto_akcipher *tfm, const void *key, @@ -1067,6 +1050,8 @@ static int caam_rsa_set_priv_key(struct crypto_akcipher *tfm, const void *key, if (ret) return ret; + ret = -ENOMEM; + /* Copy key in DMA zone */ rsa_key->d = kmemdup(raw_key.d, raw_key.d_sz, GFP_KERNEL); if (!rsa_key->d) @@ -1103,7 +1088,7 @@ static int caam_rsa_set_priv_key(struct crypto_akcipher *tfm, const void *key, err: caam_rsa_free_key(rsa_key); - return -ENOMEM; + return ret; } static unsigned int caam_rsa_max_size(struct crypto_akcipher *tfm) diff --git a/drivers/crypto/inside-secure/safexcel_hash.c b/drivers/crypto/inside-secure/safexcel_hash.c index ef0ba4832928..7231e9773bde 100644 --- a/drivers/crypto/inside-secure/safexcel_hash.c +++ b/drivers/crypto/inside-secure/safexcel_hash.c @@ -1993,6 +1993,7 @@ static int safexcel_xcbcmac_setkey(struct crypto_ahash *tfm, const u8 *key, ret = aes_expandkey(ctx->aes, (u8 *)key_tmp + 2 * AES_BLOCK_SIZE, AES_MIN_KEY_SIZE); + memzero_explicit(key_tmp, sizeof(key_tmp)); if (ret) return ret; @@ -2104,6 +2105,8 @@ static int safexcel_cmac_setkey(struct crypto_ahash *tfm, const u8 *key, } ctx->cbcmac = false; + memzero_explicit(consts, sizeof(consts)); + memzero_explicit(_const, sizeof(_const)); return 0; } diff --git a/drivers/crypto/intel/qat/qat_common/adf_cfg.c b/drivers/crypto/intel/qat/qat_common/adf_cfg.c index 7180dd2b504a..f60034387fd5 100644 --- a/drivers/crypto/intel/qat/qat_common/adf_cfg.c +++ b/drivers/crypto/intel/qat/qat_common/adf_cfg.c @@ -1,6 +1,5 @@ // SPDX-License-Identifier: (BSD-3-Clause OR GPL-2.0-only) /* Copyright(c) 2014 - 2020 Intel Corporation */ -#include #include #include #include @@ -9,13 +8,11 @@ #include "adf_cfg.h" #include "adf_common_drv.h" -static DEFINE_MUTEX(qat_cfg_read_lock); - static void *qat_dev_cfg_start(struct seq_file *sfile, loff_t *pos) { struct adf_cfg_device_data *dev_cfg = sfile->private; - mutex_lock(&qat_cfg_read_lock); + down_read(&dev_cfg->lock); return seq_list_start(&dev_cfg->sec_list, *pos); } @@ -43,7 +40,9 @@ static void *qat_dev_cfg_next(struct seq_file *sfile, void *v, loff_t *pos) static void qat_dev_cfg_stop(struct seq_file *sfile, void *v) { - mutex_unlock(&qat_cfg_read_lock); + struct adf_cfg_device_data *dev_cfg = sfile->private; + + up_read(&dev_cfg->lock); } static const struct seq_operations qat_dev_cfg_sops = { @@ -272,13 +271,10 @@ int adf_cfg_add_key_value_param(struct adf_accel_dev *accel_dev, enum adf_cfg_val_type type) { struct adf_cfg_device_data *cfg = accel_dev->cfg; + struct adf_cfg_section *section; struct adf_cfg_key_val *key_val; - struct adf_cfg_section *section = adf_cfg_sec_find(accel_dev, - section_name); char temp_val[ADF_CFG_MAX_VAL_LEN_IN_BYTES]; - - if (!section) - return -EFAULT; + int ret = 0; key_val = kzalloc(sizeof(*key_val), GFP_KERNEL); if (!key_val) @@ -308,20 +304,28 @@ int adf_cfg_add_key_value_param(struct adf_accel_dev *accel_dev, * anything (the newly created key_val is freed). */ down_write(&cfg->lock); + + section = adf_cfg_sec_find(accel_dev, section_name); + if (!section) { + kfree(key_val); + ret = -ENOENT; + goto unlock; + } + if (!adf_cfg_key_val_get(accel_dev, section_name, key, temp_val)) { if (strncmp(temp_val, key_val->val, sizeof(temp_val))) { adf_cfg_keyval_remove(key, section); } else { kfree(key_val); - goto out; + goto unlock; } } adf_cfg_keyval_add(key_val, section); -out: +unlock: up_write(&cfg->lock); - return 0; + return ret; } EXPORT_SYMBOL_GPL(adf_cfg_add_key_value_param); @@ -339,21 +343,26 @@ EXPORT_SYMBOL_GPL(adf_cfg_add_key_value_param); int adf_cfg_section_add(struct adf_accel_dev *accel_dev, const char *name) { struct adf_cfg_device_data *cfg = accel_dev->cfg; - struct adf_cfg_section *sec = adf_cfg_sec_find(accel_dev, name); + struct adf_cfg_section *sec; + int ret = 0; - if (sec) - return 0; + down_write(&cfg->lock); + + if (adf_cfg_sec_find(accel_dev, name)) + goto unlock; sec = kzalloc(sizeof(*sec), GFP_KERNEL); - if (!sec) - return -ENOMEM; + if (!sec) { + ret = -ENOMEM; + goto unlock; + } strscpy(sec->name, name); INIT_LIST_HEAD(&sec->param_head); - down_write(&cfg->lock); list_add_tail(&sec->list, &cfg->sec_list); +unlock: up_write(&cfg->lock); - return 0; + return ret; } EXPORT_SYMBOL_GPL(adf_cfg_section_add); diff --git a/drivers/cxl/core/cdat.c b/drivers/cxl/core/cdat.c index c4bd6e8a0cf0..abb12d45af11 100644 --- a/drivers/cxl/core/cdat.c +++ b/drivers/cxl/core/cdat.c @@ -633,9 +633,9 @@ static int cxl_endpoint_gather_bandwidth(struct cxl_region *cxlr, struct cxl_port *endpoint = to_cxl_port(cxled->cxld.dev.parent); struct cxl_port *parent_port = to_cxl_port(endpoint->dev.parent); struct cxl_port *gp_port = to_cxl_port(parent_port->dev.parent); - struct access_coordinate pci_coord[ACCESS_COORDINATE_MAX]; - struct access_coordinate sw_coord[ACCESS_COORDINATE_MAX]; - struct access_coordinate ep_coord[ACCESS_COORDINATE_MAX]; + struct access_coordinate pci_coord[ACCESS_COORDINATE_MAX] = { }; + struct access_coordinate sw_coord[ACCESS_COORDINATE_MAX] = { }; + struct access_coordinate ep_coord[ACCESS_COORDINATE_MAX] = { }; struct cxl_memdev *cxlmd = cxled_to_memdev(cxled); struct cxl_dev_state *cxlds = cxlmd->cxlds; struct pci_dev *pdev = to_pci_dev(cxlds->dev); @@ -757,7 +757,7 @@ static struct xarray *cxl_switch_gather_bandwidth(struct cxl_region *cxlr, { struct xarray *res_xa __free(free_perf_xa) = kzalloc(sizeof(*res_xa), GFP_KERNEL); - struct access_coordinate coords[ACCESS_COORDINATE_MAX]; + struct access_coordinate coords[ACCESS_COORDINATE_MAX] = { }; struct cxl_perf_ctx *ctx, *us_ctx; unsigned long index, us_index; int dev_count = 0; diff --git a/drivers/cxl/core/port.c b/drivers/cxl/core/port.c index b9a585f64b8a..9c9fcea02816 100644 --- a/drivers/cxl/core/port.c +++ b/drivers/cxl/core/port.c @@ -1383,7 +1383,7 @@ static int add_ep(struct cxl_ep *new) { struct cxl_port *port = new->dport->port; - guard(device)(&port->dev); + device_lock_assert(&port->dev); if (port->dead) return -ENXIO; @@ -1399,6 +1399,11 @@ static int add_ep(struct cxl_ep *new) * Intermediate CXL ports are scanned based on the arrival of endpoints. * When those endpoints depart the port can be destroyed once all * endpoints that care about that port have been removed. + * + * Context: Caller must hold the device lock of @dport->port, which pins + * @dport, across the lookup of @dport and this call. @dport->port + * is never the CXL root port, whose dports are pinned by its + * uport_dev instead. */ static int cxl_add_ep(struct cxl_dport *dport, struct device *ep_dev) { @@ -1727,13 +1732,15 @@ static struct cxl_dport *probe_dport(struct cxl_port *port, return drv->add_dport(port, dport_dev); } -static struct cxl_dport *devm_cxl_create_port(struct device *ep_dev, - struct cxl_port *parent_port, - struct cxl_dport *parent_dport, - struct device *uport_dev, - struct device *dport_dev) +static int devm_cxl_create_port(struct device *ep_dev, + struct cxl_port *parent_port, + struct cxl_dport *parent_dport, + struct device *uport_dev, + struct device *dport_dev) { resource_size_t component_reg_phys; + struct cxl_dport *dport; + int rc; device_lock_assert(&parent_port->dev); if (!parent_port->dev.driver) { @@ -1750,7 +1757,7 @@ static struct cxl_dport *devm_cxl_create_port(struct device *ep_dev, port = devm_cxl_add_port(&parent_port->dev, uport_dev, component_reg_phys, parent_dport); if (IS_ERR(port)) - return ERR_CAST(port); + return PTR_ERR(port); /* * retry to make sure a port is found. a port device @@ -1758,7 +1765,7 @@ static struct cxl_dport *devm_cxl_create_port(struct device *ep_dev, */ port = find_cxl_port_by_uport(uport_dev); if (!port) - return ERR_PTR(-ENODEV); + return -ENODEV; dev_dbg(ep_dev, "created port %s:%s\n", dev_name(&port->dev), dev_name(port->uport_dev)); @@ -1767,11 +1774,25 @@ static struct cxl_dport *devm_cxl_create_port(struct device *ep_dev, * Port was created before right before this function is * called. Signal the caller to deal with it. */ - return ERR_PTR(-EAGAIN); + return -EAGAIN; } + /* @dport is only valid while @port's lock is held */ guard(device)(&port->dev); - return probe_dport(port, dport_dev); + dport = probe_dport(port, dport_dev); + if (IS_ERR(dport)) + return PTR_ERR(dport); + + rc = cxl_add_ep(dport, ep_dev); + if (rc == -EBUSY) { + /* + * "can't" happen, but this error code means + * something to the caller, so translate it. + */ + rc = -ENXIO; + } + + return rc; } static int add_port_attach_ep(struct cxl_memdev *cxlmd, @@ -1779,7 +1800,7 @@ static int add_port_attach_ep(struct cxl_memdev *cxlmd, struct device *dport_dev) { struct device *dparent = grandparent(dport_dev); - struct cxl_dport *dport, *parent_dport; + struct cxl_dport *parent_dport; int rc; if (is_cxl_host_bridge(dparent)) { @@ -1808,46 +1829,51 @@ static int add_port_attach_ep(struct cxl_memdev *cxlmd, return PTR_ERR(parent_dport); } - dport = devm_cxl_create_port(&cxlmd->dev, parent_port, - parent_dport, uport_dev, - dport_dev); - if (IS_ERR(dport)) { - /* Port or dport already exists, restart iteration */ - if (PTR_ERR(dport) == -EAGAIN || PTR_ERR(dport) == -EBUSY) - return 0; - return PTR_ERR(dport); - } + rc = devm_cxl_create_port(&cxlmd->dev, parent_port, + parent_dport, uport_dev, dport_dev); } - rc = cxl_add_ep(dport, &cxlmd->dev); - if (rc == -EBUSY) { - /* - * "can't" happen, but this error code means - * something to the caller, so translate it. - */ - rc = -ENXIO; - } + /* Port or dport already exists, restart iteration */ + if (rc == -EAGAIN || rc == -EBUSY) + return 0; return rc; } -static struct cxl_dport *find_or_add_dport(struct cxl_port *port, - struct device *dport_dev) +static int find_or_add_dport_attach_ep(struct cxl_memdev *cxlmd, + struct cxl_port *port, + struct device *dport_dev) { struct cxl_dport *dport; + int rc; - device_lock_assert(&port->dev); + guard(device)(&port->dev); dport = cxl_find_dport_by_dev(port, dport_dev); if (!dport) { dport = probe_dport(port, dport_dev); if (IS_ERR(dport)) - return dport; + return PTR_ERR(dport); /* New dport added, restart iteration */ - return ERR_PTR(-EAGAIN); + return -EAGAIN; } - return dport; + /* @dport is only valid while @port's lock is held */ + rc = cxl_add_ep(dport, &cxlmd->dev); + + /* + * If the endpoint already exists in the port's list, + * that's ok, it was added on a previous pass. + * Otherwise, retry in add_port_attach_ep() after taking + * the parent_port lock as the current port may be being + * reaped. + */ + if (rc && rc != -EBUSY) + return rc; + + cxl_gpf_port_setup(dport); + + return 0; } int devm_cxl_enumerate_ports(struct cxl_memdev *cxlmd) @@ -1876,7 +1902,6 @@ int devm_cxl_enumerate_ports(struct cxl_memdev *cxlmd) for (iter = dev; iter; iter = grandparent(iter)) { struct device *dport_dev = grandparent(iter); struct device *uport_dev; - struct cxl_dport *dport; if (is_cxl_host_bridge(dport_dev)) return 0; @@ -1903,29 +1928,13 @@ int devm_cxl_enumerate_ports(struct cxl_memdev *cxlmd) * RP port enumerated by cxl_acpi without dport will * have the dport added here. */ - scoped_guard(device, &port->dev) { - dport = find_or_add_dport(port, dport_dev); - if (IS_ERR(dport)) { - if (PTR_ERR(dport) == -EAGAIN) - goto retry; - return PTR_ERR(dport); - } - } - - rc = cxl_add_ep(dport, &cxlmd->dev); - - /* - * If the endpoint already exists in the port's list, - * that's ok, it was added on a previous pass. - * Otherwise, retry in add_port_attach_ep() after taking - * the parent_port lock as the current port may be being - * reaped. - */ - if (rc && rc != -EBUSY) + rc = find_or_add_dport_attach_ep(cxlmd, port, + dport_dev); + if (rc == -EAGAIN) + goto retry; + if (rc) return rc; - cxl_gpf_port_setup(dport); - /* Any more ports to add between this one and the root? */ if (!dev_is_cxl_root_child(&port->dev)) continue; diff --git a/drivers/cxl/core/region.c b/drivers/cxl/core/region.c index 46fc6644c8a7..7df6139f83ef 100644 --- a/drivers/cxl/core/region.c +++ b/drivers/cxl/core/region.c @@ -3306,12 +3306,14 @@ static int devm_cxl_add_pmem_region(struct cxl_region *cxlr) dev_name(dev)); scoped_guard(device, &cxl_nvb->dev) { - if (cxl_nvb->dev.driver) + if (cxl_nvb->dev.driver) { rc = devm_add_action_or_reset(&cxl_nvb->dev, cxlr_pmem_unregister, cxlr_pmem); - else + } else { rc = -ENXIO; + cxlr_pmem_unregister(cxlr_pmem); + } } if (rc) diff --git a/drivers/dma/ste_dma40.c b/drivers/dma/ste_dma40.c index 21469034495d..6699689deeca 100644 --- a/drivers/dma/ste_dma40.c +++ b/drivers/dma/ste_dma40.c @@ -69,6 +69,9 @@ struct stedma40_platform_data { /* Maximum iterations taken before giving up suspending a channel */ #define D40_SUSPEND_MAX_IT 500 +/* Maximum attempts to sample a stable cyclic residue position */ +#define D40_RESIDUE_MAX_ATTEMPTS 3 + /* Milliseconds */ #define DMA40_AUTOSUSPEND_DELAY 100 @@ -368,11 +371,17 @@ struct d40_lli_pool { * @lli_len: Number of llis of current descriptor. * @lli_current: Number of transferred llis. * @lcla_alloc: Number of LCLA entries allocated. + * @cyclic_dma_addr: Start address of the cyclic buffer. + * @cyclic_buf_len: Length of the cyclic buffer. + * @cyclic_residue: Last valid cyclic residue sample. + * @cyclic_period_len: Length of one cyclic period. + * @cyclic_callback_pos: Position after the callbacks already queued. * @txd: DMA engine struct. Used for among other things for communication * during a transfer. * @node: List entry. * @is_in_client_list: true if the client owns this descriptor. * @cyclic: true if this is a cyclic job + * @cyclic_callback_pos_valid: Whether cyclic_callback_pos is reliable. * * This descriptor is used for both logical and physical transfers. */ @@ -386,12 +395,18 @@ struct d40_desc { int lli_len; int lli_current; int lcla_alloc; + dma_addr_t cyclic_dma_addr; + size_t cyclic_buf_len; + size_t cyclic_residue; + size_t cyclic_period_len; + size_t cyclic_callback_pos; struct dma_async_tx_descriptor txd; struct list_head node; bool is_in_client_list; bool cyclic; + bool cyclic_callback_pos_valid; }; /** @@ -494,7 +509,7 @@ struct d40_chan { u32 src_def_cfg; u32 dst_def_cfg; struct d40_def_lcsp log_def; - struct d40_log_lli_full *lcpa; + struct d40_log_lli_full __iomem *lcpa; /* Runtime reconfiguration */ dma_addr_t runtime_addr; enum dma_transfer_direction runtime_direction; @@ -602,7 +617,7 @@ struct d40_base { /* Physical half channels */ struct d40_phy_res *phy_res; struct d40_lcla_pool lcla_pool; - void *lcpa_base; + void __iomem *lcpa_base; dma_addr_t phy_lcpa; resource_size_t lcpa_size; struct kmem_cache *desc_slab; @@ -1412,6 +1427,119 @@ static u32 d40_residue(struct d40_chan *d40c) return num_elt * d40c->dma_cfg.dst_info.data_width; } +static bool d40_current_addr(struct d40_chan *d40c, dma_addr_t *addr) +{ + bool dst = d40c->dma_cfg.dir == DMA_DEV_TO_MEM; + void __iomem *high_reg; + void __iomem *low_reg; + u32 low; + u32 high; + u32 check; + int i; + + if (chan_is_physical(d40c)) { + *addr = readl(chan_base(d40c) + + (dst ? D40_CHAN_REG_SDPTR : D40_CHAN_REG_SSPTR)); + return true; + } + + if (dst) { + low_reg = &d40c->lcpa->lcsp2; + high_reg = &d40c->lcpa->lcsp3; + } else { + low_reg = &d40c->lcpa->lcsp0; + high_reg = &d40c->lcpa->lcsp1; + } + + for (i = 0; i < D40_RESIDUE_MAX_ATTEMPTS; i++) { + high = readl(high_reg) & D40_MEM_LCSP1_SPTR_MASK; + low = readl(low_reg) & D40_MEM_LCSP0_SPTR_MASK; + check = readl(high_reg) & D40_MEM_LCSP1_SPTR_MASK; + if (high == check) { + *addr = low | high; + return true; + } + } + + return false; +} + +static bool d40_cyclic_offset(struct d40_chan *d40c, struct d40_desc *d40d, + size_t *offset) +{ + dma_addr_t current_addr; + dma_addr_t current_offset; + int i; + + for (i = 0; i < D40_RESIDUE_MAX_ATTEMPTS; i++) { + if (!d40_current_addr(d40c, ¤t_addr)) + continue; + + current_offset = current_addr - d40d->cyclic_dma_addr; + if (current_offset <= d40d->cyclic_buf_len) { + *offset = current_offset; + return true; + } + } + + return false; +} + +static unsigned int d40_cyclic_periods_elapsed(struct d40_chan *d40c, + struct d40_desc *d40d) +{ + size_t current_pos; + size_t delta; + size_t offset; + unsigned int periods; + + if (!d40d->cyclic_period_len) + return 1; + + if (!d40_cyclic_offset(d40c, d40d, &offset)) { + d40d->cyclic_callback_pos_valid = false; + return 1; + } + + current_pos = rounddown(offset, d40d->cyclic_period_len); + if (!d40_residue(d40c) && current_pos != offset) + current_pos += d40d->cyclic_period_len; + if (current_pos == d40d->cyclic_buf_len) + current_pos = 0; + + if (!d40d->cyclic_callback_pos_valid) { + /* + * The previous interrupt was reported without a pointer + * sample. Resynchronize without using the stale position, + * which would count that callback again. + */ + d40d->cyclic_callback_pos = current_pos; + d40d->cyclic_callback_pos_valid = true; + return 1; + } + + /* + * The pointer wraps with the cyclic buffer, so its displacement is + * only the minimum number of elapsed periods. Complete buffer laps + * are not observable. + */ + delta = (current_pos + d40d->cyclic_buf_len - + d40d->cyclic_callback_pos) % d40d->cyclic_buf_len; + periods = delta / d40d->cyclic_period_len; + if (!periods) { + /* + * The TC status is a single latched bit. An unchanged pointer + * cannot distinguish a complete lap from a repeated interrupt, + * so do not amplify it into a buffer's worth of callbacks. + */ + periods = 1; + } + + d40d->cyclic_callback_pos = current_pos; + + return periods; +} + static bool d40_tx_is_linked(struct d40_chan *d40c) { bool is_link; @@ -1559,6 +1687,7 @@ static struct d40_desc *d40_queue_start(struct d40_chan *d40c) static void dma_tc_handle(struct d40_chan *d40c) { struct d40_desc *d40d; + unsigned int callbacks = 1; /* Get first active entry from list */ d40d = d40_first_active_get(d40c); @@ -1583,6 +1712,8 @@ static void dma_tc_handle(struct d40_chan *d40c) if (d40d->lli_current == d40d->lli_len) d40d->lli_current = 0; } + + callbacks = d40_cyclic_periods_elapsed(d40c, d40d); } else { d40_lcla_free_all(d40c, d40d); @@ -1603,7 +1734,7 @@ static void dma_tc_handle(struct d40_chan *d40c) } } - d40c->pending_tx++; + d40c->pending_tx += callbacks; tasklet_schedule(&d40c->tasklet); } @@ -2202,15 +2333,26 @@ static bool d40_is_paused(struct d40_chan *d40c) } -static u32 stedma40_residue(struct dma_chan *chan) +static u32 stedma40_residue(struct dma_chan *chan, dma_cookie_t cookie) { struct d40_chan *d40c = container_of(chan, struct d40_chan, chan); + struct d40_desc *d40d; + size_t offset; u32 bytes_left; unsigned long flags; spin_lock_irqsave(&d40c->lock, flags); - bytes_left = d40_residue(d40c); + d40d = d40_first_active_get(d40c); + if (d40d && d40d->txd.cookie == cookie && d40d->cyclic && + d40d->cyclic_buf_len) { + if (d40_cyclic_offset(d40c, d40d, &offset)) + d40d->cyclic_residue = d40d->cyclic_buf_len - offset; + bytes_left = d40d->cyclic_residue; + } else { + bytes_left = d40_residue(d40c); + } + spin_unlock_irqrestore(&d40c->lock, flags); return bytes_left; @@ -2346,8 +2488,13 @@ d40_prep_sg(struct dma_chan *dchan, struct scatterlist *sg_src, if (desc == NULL) goto unlock; - if (sg_next(&sg_src[sg_len - 1]) == sg_src) + if (sg_next(&sg_src[sg_len - 1]) == sg_src) { desc->cyclic = true; + if (desc->lli_len != sg_len) { + chan_err(chan, "Cyclic periods must fit in one LLI\n"); + goto free_desc; + } + } src_dev_addr = 0; dst_dev_addr = 0; @@ -2630,11 +2777,18 @@ dma40_prep_dma_cyclic(struct dma_chan *chan, dma_addr_t dma_addr, size_t buf_len, size_t period_len, enum dma_transfer_direction direction, unsigned long flags) { - unsigned int periods = buf_len / period_len; + unsigned int periods; struct dma_async_tx_descriptor *txd; + struct d40_desc *desc; struct scatterlist *sg; + dma_addr_t buf_addr = dma_addr; int i; + if (!buf_len || !period_len || buf_len % period_len) + return NULL; + + periods = buf_len / period_len; + sg = kcalloc(periods + 1, sizeof(struct scatterlist), GFP_NOWAIT); if (!sg) return NULL; @@ -2649,6 +2803,15 @@ dma40_prep_dma_cyclic(struct dma_chan *chan, dma_addr_t dma_addr, txd = d40_prep_sg(chan, sg, sg, periods, direction, DMA_PREP_INTERRUPT); + if (txd) { + desc = container_of(txd, struct d40_desc, txd); + desc->cyclic_dma_addr = buf_addr; + desc->cyclic_buf_len = buf_len; + desc->cyclic_residue = buf_len; + desc->cyclic_period_len = period_len; + desc->cyclic_callback_pos = 0; + desc->cyclic_callback_pos_valid = true; + } kfree(sg); @@ -2669,7 +2832,7 @@ static enum dma_status d40_tx_status(struct dma_chan *chan, ret = dma_cookie_status(chan, cookie, txstate); if (ret != DMA_COMPLETE && txstate) - dma_set_residue(txstate, stedma40_residue(chan)); + dma_set_residue(txstate, stedma40_residue(chan, cookie)); if (d40_is_paused(d40c)) ret = DMA_PAUSED; diff --git a/drivers/dma/ste_dma40_ll.c b/drivers/dma/ste_dma40_ll.c index 4c489b126cb2..3be7f5b1abb0 100644 --- a/drivers/dma/ste_dma40_ll.c +++ b/drivers/dma/ste_dma40_ll.c @@ -333,10 +333,10 @@ static void d40_log_lli_link(struct d40_log_lli *lli_dst, (dlos << D40_MEM_LCSP1_SLOS_POS); } -void d40_log_lli_lcpa_write(struct d40_log_lli_full *lcpa, - struct d40_log_lli *lli_dst, - struct d40_log_lli *lli_src, - int next, unsigned int flags) +void d40_log_lli_lcpa_write(struct d40_log_lli_full __iomem *lcpa, + struct d40_log_lli *lli_dst, + struct d40_log_lli *lli_src, + int next, unsigned int flags) { d40_log_lli_link(lli_dst, lli_src, next, flags); diff --git a/drivers/dma/ste_dma40_ll.h b/drivers/dma/ste_dma40_ll.h index 55090cb31057..ca9d07649361 100644 --- a/drivers/dma/ste_dma40_ll.h +++ b/drivers/dma/ste_dma40_ll.h @@ -455,7 +455,7 @@ int d40_log_sg_to_lli(struct scatterlist *sg, u32 lcsp13, /* src or dst*/ u32 data_width1, u32 data_width2); -void d40_log_lli_lcpa_write(struct d40_log_lli_full *lcpa, +void d40_log_lli_lcpa_write(struct d40_log_lli_full __iomem *lcpa, struct d40_log_lli *lli_dst, struct d40_log_lli *lli_src, int next, unsigned int flags); diff --git a/drivers/dma/xilinx/zynqmp_dma.c b/drivers/dma/xilinx/zynqmp_dma.c index 1f6bb492be6a..17bd0cce6833 100644 --- a/drivers/dma/xilinx/zynqmp_dma.c +++ b/drivers/dma/xilinx/zynqmp_dma.c @@ -484,8 +484,10 @@ static int zynqmp_dma_alloc_chan_resources(struct dma_chan *dchan) chan->sw_desc_pool = kcalloc(ZYNQMP_DMA_NUM_DESCS, sizeof(*desc), GFP_KERNEL); - if (!chan->sw_desc_pool) - return -ENOMEM; + if (!chan->sw_desc_pool) { + ret = -ENOMEM; + goto err_pm; + } chan->idle = true; chan->desc_free_cnt = ZYNQMP_DMA_NUM_DESCS; @@ -503,8 +505,10 @@ static int zynqmp_dma_alloc_chan_resources(struct dma_chan *dchan) (2 * ZYNQMP_DMA_DESC_SIZE(chan) * ZYNQMP_DMA_NUM_DESCS), &chan->desc_pool_p, GFP_KERNEL); - if (!chan->desc_pool_v) - return -ENOMEM; + if (!chan->desc_pool_v) { + ret = -ENOMEM; + goto err_free_sw_desc_pool; + } for (i = 0; i < ZYNQMP_DMA_NUM_DESCS; i++) { desc = chan->sw_desc_pool + i; @@ -517,6 +521,13 @@ static int zynqmp_dma_alloc_chan_resources(struct dma_chan *dchan) } return ZYNQMP_DMA_NUM_DESCS; + +err_free_sw_desc_pool: + kfree(chan->sw_desc_pool); + chan->sw_desc_pool = NULL; +err_pm: + pm_runtime_put_autosuspend(chan->dev); + return ret; } /** diff --git a/drivers/dpll/dpll_core.c b/drivers/dpll/dpll_core.c index 0a8db4dc2578..aaa576562ae4 100644 --- a/drivers/dpll/dpll_core.c +++ b/drivers/dpll/dpll_core.c @@ -999,7 +999,8 @@ int dpll_pin_ref_sync_pair_add(struct dpll_pin *pin, mutex_lock(&dpll_lock); ret = xa_insert(&pin->ref_sync_pins, ref_sync_pin->id, ref_sync_pin, GFP_KERNEL); - __dpll_pin_change_ntf(pin); + if (!ret) + __dpll_pin_change_ntf(pin); mutex_unlock(&dpll_lock); return ret; diff --git a/drivers/dpll/zl3073x/dpll.c b/drivers/dpll/zl3073x/dpll.c index c2ea96df3bcb..75a8584e6368 100644 --- a/drivers/dpll/zl3073x/dpll.c +++ b/drivers/dpll/zl3073x/dpll.c @@ -771,7 +771,7 @@ zl3073x_dpll_output_pin_esync_get(const struct dpll_pin *dpll_pin, const struct zl3073x_synth *synth; const struct zl3073x_out *out; u32 synth_freq, out_freq; - u8 clock_type, out_id; + u8 out_id; out_id = zl3073x_output_pin_out_get(pin->id); out = zl3073x_out_state_get(zldev, out_id); @@ -794,8 +794,7 @@ zl3073x_dpll_output_pin_esync_get(const struct dpll_pin *dpll_pin, esync->range = esync_freq_ranges; esync->range_num = ARRAY_SIZE(esync_freq_ranges); - clock_type = FIELD_GET(ZL_OUTPUT_MODE_CLOCK_TYPE, out->mode); - if (clock_type != ZL_OUTPUT_MODE_CLOCK_TYPE_ESYNC) { + if (!zl3073x_out_esync_is_enabled(out)) { /* No need to read esync data if it is not enabled */ esync->freq = 0; esync->pulse = 0; @@ -811,7 +810,7 @@ zl3073x_dpll_output_pin_esync_get(const struct dpll_pin *dpll_pin, * Note that half pulse width is in units of half synth cycles, which * is why it reduces down to be output_div. */ - esync->pulse = (50 * out->esync_n_width) / out->div; + esync->pulse = div_u64(mul_u32_u32(50, out->esync_n_width), out->div); return 0; } @@ -828,7 +827,7 @@ zl3073x_dpll_output_pin_esync_set(const struct dpll_pin *dpll_pin, struct zl3073x_dpll_pin *pin = pin_priv; const struct zl3073x_synth *synth; struct zl3073x_out out; - u8 clock_type, out_id; + u8 out_id; u32 synth_freq; out_id = zl3073x_output_pin_out_get(pin->id); @@ -841,36 +840,18 @@ zl3073x_dpll_output_pin_esync_set(const struct dpll_pin *dpll_pin, if (zl3073x_out_is_ndiv(&out)) return -EOPNOTSUPP; - /* Select clock type */ - if (freq) - clock_type = ZL_OUTPUT_MODE_CLOCK_TYPE_ESYNC; - else - clock_type = ZL_OUTPUT_MODE_CLOCK_TYPE_NORMAL; - - /* Update clock type in output mode */ - out.mode &= ~ZL_OUTPUT_MODE_CLOCK_TYPE; - out.mode |= FIELD_PREP(ZL_OUTPUT_MODE_CLOCK_TYPE, clock_type); - - /* If esync is being disabled just write mailbox and finish */ - if (!freq) - goto write_mailbox; + if (!freq) { + zl3073x_out_esync_disable(&out); + return zl3073x_out_state_set(zldev, out_id, &out); + } /* Get attached synth frequency */ synth = zl3073x_synth_state_get(zldev, zl3073x_out_synth_get(&out)); synth_freq = zl3073x_synth_freq_get(synth); - /* Compute and update esync period */ - out.esync_n_period = synth_freq / (u32)freq / out.div; - - /* Half of the period in units of 1/2 synth cycle can be represented by - * the output_div. To get the supported esync pulse width of 25% of the - * period the output_div can just be divided by 2. Note that this - * assumes that output_div is even, otherwise some resolution will be - * lost. - */ - out.esync_n_width = out.div / 2; + /* Enable 1PPS eSync for this pin frequency */ + zl3073x_out_esync_enable(&out, synth_freq / out.div); -write_mailbox: /* Commit output configuration */ return zl3073x_out_state_set(zldev, out_id, &out); } @@ -924,6 +905,23 @@ zl3073x_dpll_output_pin_frequency_set(const struct dpll_pin *dpll_pin, /* For 50/50 duty cycle the divisor is equal to width */ out.width = new_div; + /* The embedded sync period and width are computed relative to + * the output carrier so they have to be adjusted to follow the + * new frequency. + */ + if (zl3073x_out_esync_is_enabled(&out)) { + if (frequency == 1) { + /* eSync cannot work on a 1 Hz carrier */ + zl3073x_out_esync_disable(&out); + } else { + /* Update esync period and width according to + * the new frequency. + */ + zl3073x_out_esync_enable(&out, + synth_freq / out.div); + } + } + /* Commit output configuration */ return zl3073x_out_state_set(zldev, out_id, &out); } diff --git a/drivers/dpll/zl3073x/out.h b/drivers/dpll/zl3073x/out.h index 318f9bb8da3a..1f2cda4d37fc 100644 --- a/drivers/dpll/zl3073x/out.h +++ b/drivers/dpll/zl3073x/out.h @@ -107,4 +107,44 @@ static inline u8 zl3073x_out_synth_get(const struct zl3073x_out *out) return FIELD_GET(ZL_OUTPUT_CTRL_SYNTH_SEL, out->ctrl); } +static inline bool zl3073x_out_esync_is_enabled(const struct zl3073x_out *out) +{ + u8 clock_type = FIELD_GET(ZL_OUTPUT_MODE_CLOCK_TYPE, out->mode); + + return clock_type == ZL_OUTPUT_MODE_CLOCK_TYPE_ESYNC; +} + +static inline +void zl3073x_out_esync_enable(struct zl3073x_out *out, u32 base_freq) +{ + /* Period is expressed as the number of output divider clock cycles. + * So for 1 Hz the period is equal to base frequency. + */ + out->esync_n_period = base_freq; + + /* Half of the period in units of 1/2 synth cycle can be represented by + * the output_div. To get the supported esync pulse width of 25% of the + * period the output_div can just be divided by 2. Note that this + * assumes that output_div is even, otherwise some resolution will be + * lost. + */ + out->esync_n_width = out->div / 2; + + /* Update the clock type */ + out->mode &= ~ZL_OUTPUT_MODE_CLOCK_TYPE; + out->mode |= FIELD_PREP(ZL_OUTPUT_MODE_CLOCK_TYPE, + ZL_OUTPUT_MODE_CLOCK_TYPE_ESYNC); +} + +static inline +void zl3073x_out_esync_disable(struct zl3073x_out *out) +{ + /* Just update the clock type. The eSync period and width are + * ignored for this clock type. + */ + out->mode &= ~ZL_OUTPUT_MODE_CLOCK_TYPE; + out->mode |= FIELD_PREP(ZL_OUTPUT_MODE_CLOCK_TYPE, + ZL_OUTPUT_MODE_CLOCK_TYPE_NORMAL); +} + #endif /* _ZL3073X_OUT_H */ diff --git a/drivers/firmware/cirrus/cs_dsp.c b/drivers/firmware/cirrus/cs_dsp.c index 15710c97f9fb..0e20f72cfdfc 100644 --- a/drivers/firmware/cirrus/cs_dsp.c +++ b/drivers/firmware/cirrus/cs_dsp.c @@ -2745,6 +2745,7 @@ int cs_dsp_power_up(struct cs_dsp *dsp, const struct firmware *coeff_firmware, const char *coeff_filename, const char *fw_name) { + struct cs_dsp_coeff_ctl *ctl; int ret; mutex_lock(&dsp->pwr_lock); @@ -2789,6 +2790,11 @@ int cs_dsp_power_up(struct cs_dsp *dsp, return 0; err_ena: + list_for_each_entry(ctl, &dsp->ctl_list, list) + ctl->enabled = 0; + + cs_dsp_free_alg_regions(dsp); + if (dsp->ops->disable_core) dsp->ops->disable_core(dsp); err_mem: diff --git a/drivers/gpio/gpio-aspeed.c b/drivers/gpio/gpio-aspeed.c index 3da37a0fda3f..6e252a6f48be 100644 --- a/drivers/gpio/gpio-aspeed.c +++ b/drivers/gpio/gpio-aspeed.c @@ -1045,6 +1045,17 @@ static void aspeed_g4_reg_bit_set(struct aspeed_gpio *gpio, unsigned int offset, void __iomem *addr = aspeed_gpio_g4_bank_reg(gpio, bank, reg); u32 temp; + /* + * The interrupt status register is write-1-to-clear. Write only this + * line's bit so that interrupts pending on the other lines of the bank + * stay latched. + */ + if (reg == reg_irq_status) { + if (val) + iowrite32(GPIO_BIT(offset), addr); + return; + } + if (reg == reg_val) temp = gpio->dcache[GPIO_BANK(offset)]; else @@ -1161,7 +1172,13 @@ static void aspeed_g7_reg_bit_set(struct aspeed_gpio *gpio, unsigned int offset, u32 write_val; if (mask) { - write_val = (ioread32(addr) & ~(mask)) | field_prep(mask, val); + /* + * The interrupt status bit is write-1-to-clear. Keep it zero + * unless it is the field being written, so that updating any + * other field leaves a pending interrupt latched. + */ + write_val = ioread32(addr) & ~(mask | GPIO_G7_CTRL_IRQ_STS); + write_val |= field_prep(mask, val); iowrite32(write_val, addr); } } diff --git a/drivers/gpio/gpio-brcmstb.c b/drivers/gpio/gpio-brcmstb.c index f0cb1991b326..ba83b4aaf295 100644 --- a/drivers/gpio/gpio-brcmstb.c +++ b/drivers/gpio/gpio-brcmstb.c @@ -486,6 +486,7 @@ static int brcmstb_gpio_irq_setup(struct platform_device *pdev, out_free_domain: irq_domain_remove(priv->irq_domain); + priv->irq_domain = NULL; return err; } diff --git a/drivers/gpio/gpio-mpc8xxx.c b/drivers/gpio/gpio-mpc8xxx.c index bfe828734ee1..4a5636de08db 100644 --- a/drivers/gpio/gpio-mpc8xxx.c +++ b/drivers/gpio/gpio-mpc8xxx.c @@ -320,6 +320,14 @@ static const struct of_device_id mpc8xxx_gpio_ids[] = { {} }; +static void mpc8xxx_irq_domain_remove(void *data) +{ + struct mpc8xxx_gpio_chip *mpc8xxx_gc = data; + + if (mpc8xxx_gc->irq) + irq_domain_remove(mpc8xxx_gc->irq); +} + static int mpc8xxx_probe(struct platform_device *pdev) { const struct mpc8xxx_gpio_devtype *devtype = NULL; @@ -406,6 +414,11 @@ static int mpc8xxx_probe(struct platform_device *pdev) mpc8xxx_gc->regs + GPIO_DIR); } + /* GPIO chip cleanup still needs the IRQ domain. */ + ret = devm_add_action_or_reset(dev, mpc8xxx_irq_domain_remove, mpc8xxx_gc); + if (ret) + return ret; + ret = devm_gpiochip_add_data(dev, gc, mpc8xxx_gc); if (ret) { dev_err(dev, @@ -438,7 +451,7 @@ static int mpc8xxx_probe(struct platform_device *pdev) if (ret) { dev_err(dev, "failed to devm_request_irq(%d), ret = %d\n", mpc8xxx_gc->irqn, ret); - goto err; + return ret; } ret = devm_device_init_wakeup(dev); @@ -446,19 +459,14 @@ static int mpc8xxx_probe(struct platform_device *pdev) return dev_err_probe(dev, ret, "Failed to init wakeup\n"); return 0; -err: - irq_domain_remove(mpc8xxx_gc->irq); - return ret; } static void mpc8xxx_remove(struct platform_device *pdev) { struct mpc8xxx_gpio_chip *mpc8xxx_gc = platform_get_drvdata(pdev); - if (mpc8xxx_gc->irq) { + if (mpc8xxx_gc->irq) irq_set_chained_handler_and_data(mpc8xxx_gc->irqn, NULL, NULL); - irq_domain_remove(mpc8xxx_gc->irq); - } } static int mpc8xxx_suspend(struct device *dev) diff --git a/drivers/gpio/gpio-mpsse.c b/drivers/gpio/gpio-mpsse.c index dac478ef33e1..880a4da02e12 100644 --- a/drivers/gpio/gpio-mpsse.c +++ b/drivers/gpio/gpio-mpsse.c @@ -677,6 +677,10 @@ static int gpio_mpsse_probe(struct usb_interface *interface, if (err) return err; + /* Every read carries two status bytes ahead of the data */ + if (usb_endpoint_maxp(priv->bulk_in) < 3) + return -EINVAL; + priv->bulk_in_buf = devm_kmalloc(dev, usb_endpoint_maxp(priv->bulk_in), GFP_KERNEL); if (!priv->bulk_in_buf) diff --git a/drivers/gpio/gpio-omap.c b/drivers/gpio/gpio-omap.c index 8693544304fa..2ebef18c37ab 100644 --- a/drivers/gpio/gpio-omap.c +++ b/drivers/gpio/gpio-omap.c @@ -814,8 +814,11 @@ static int omap_gpio_request(struct gpio_chip *chip, unsigned offset) { struct gpio_bank *bank = gpiochip_get_data(chip); unsigned long flags; + int ret; - pm_runtime_get_sync(chip->parent); + ret = pm_runtime_resume_and_get(chip->parent); + if (ret < 0) + return ret; raw_spin_lock_irqsave(&bank->lock, flags); omap_enable_gpio_module(bank, offset); @@ -1469,7 +1472,13 @@ static int omap_gpio_probe(struct platform_device *pdev) platform_set_drvdata(pdev, bank); pm_runtime_enable(dev); - pm_runtime_get_sync(dev); + ret = pm_runtime_resume_and_get(dev); + if (ret < 0) { + pm_runtime_disable(dev); + if (bank->dbck_flag) + clk_unprepare(bank->dbck); + return ret; + } if (bank->is_mpuio) omap_mpuio_init(bank); diff --git a/drivers/gpio/gpio-regmap.c b/drivers/gpio/gpio-regmap.c index c64805dcb9f8..066a5be7f8e9 100644 --- a/drivers/gpio/gpio-regmap.c +++ b/drivers/gpio/gpio-regmap.c @@ -31,6 +31,7 @@ struct gpio_regmap { unsigned int reg_clr_base; unsigned int reg_dir_in_base; unsigned int reg_dir_out_base; + unsigned long *fixed_direction_mask; unsigned long *fixed_direction_output; #ifdef CONFIG_REGMAP_IRQ @@ -128,6 +129,20 @@ static int gpio_regmap_set_with_clear(struct gpio_chip *chip, return regmap_write(gpio->regmap, reg, mask); } +static bool gpio_regmap_fixed_direction(struct gpio_regmap *gpio, + unsigned int offset) +{ + if (!gpio->fixed_direction_output) + return false; + + /* In this case only some GPIOs are fixed as input/output */ + if (gpio->fixed_direction_mask && + !test_bit(offset, gpio->fixed_direction_mask)) + return false; + + return true; +} + static int gpio_regmap_get_direction(struct gpio_chip *chip, unsigned int offset) { @@ -135,7 +150,7 @@ static int gpio_regmap_get_direction(struct gpio_chip *chip, unsigned int base, val, reg, mask; int invert, ret; - if (gpio->fixed_direction_output) { + if (gpio_regmap_fixed_direction(gpio, offset)) { if (test_bit(offset, gpio->fixed_direction_output)) return GPIO_LINE_DIRECTION_OUT; else @@ -292,12 +307,23 @@ struct gpio_regmap *gpio_regmap_register(const struct gpio_regmap_config *config goto err_free_gpio; } + if (config->fixed_direction_mask) { + gpio->fixed_direction_mask = bitmap_alloc(chip->ngpio, + GFP_KERNEL); + if (!gpio->fixed_direction_mask) { + ret = -ENOMEM; + goto err_free_gpio; + } + bitmap_copy(gpio->fixed_direction_mask, + config->fixed_direction_mask, chip->ngpio); + } + if (config->fixed_direction_output) { gpio->fixed_direction_output = bitmap_alloc(chip->ngpio, GFP_KERNEL); if (!gpio->fixed_direction_output) { ret = -ENOMEM; - goto err_free_gpio; + goto err_free_bitmap_dirmask; } bitmap_copy(gpio->fixed_direction_output, config->fixed_direction_output, chip->ngpio); @@ -319,7 +345,7 @@ struct gpio_regmap *gpio_regmap_register(const struct gpio_regmap_config *config ret = gpiochip_add_data(chip, gpio); if (ret < 0) - goto err_free_bitmap; + goto err_free_bitmap_output; #ifdef CONFIG_REGMAP_IRQ if (config->regmap_irq_chip) { @@ -345,8 +371,15 @@ struct gpio_regmap *gpio_regmap_register(const struct gpio_regmap_config *config err_remove_gpiochip: gpiochip_remove(chip); -err_free_bitmap: + +#ifdef CONFIG_REGMAP_IRQ + if (gpio->irq_chip_data) + regmap_del_irq_chip(gpio->regmap_irq_line, gpio->irq_chip_data); +#endif +err_free_bitmap_output: bitmap_free(gpio->fixed_direction_output); +err_free_bitmap_dirmask: + bitmap_free(gpio->fixed_direction_mask); err_free_gpio: kfree(gpio); return ERR_PTR(ret); @@ -366,6 +399,7 @@ void gpio_regmap_unregister(struct gpio_regmap *gpio) gpiochip_remove(&gpio->gpio_chip); bitmap_free(gpio->fixed_direction_output); + bitmap_free(gpio->fixed_direction_mask); kfree(gpio); } EXPORT_SYMBOL_GPL(gpio_regmap_unregister); diff --git a/drivers/gpio/gpio-rockchip.c b/drivers/gpio/gpio-rockchip.c index 46dd9085d9c8..ac5af4cbd35e 100644 --- a/drivers/gpio/gpio-rockchip.c +++ b/drivers/gpio/gpio-rockchip.c @@ -201,20 +201,25 @@ static int rockchip_gpio_set_debounce(struct gpio_chip *gc, { struct rockchip_pin_bank *bank = gpiochip_get_data(gc); const struct rockchip_gpio_regs *reg = bank->gpio_regs; - unsigned long flags, div_reg, freq, max_debounce; + unsigned long flags, div_reg, freq; bool div_debounce_support; unsigned int cur_div_reg; - u64 div; + u64 div, max_debounce; if (bank->gpio_type == GPIO_TYPE_V2 && !IS_ERR(bank->db_clk)) { div_debounce_support = true; freq = clk_get_rate(bank->db_clk); - max_debounce = (GENMASK(23, 0) + 1) * 2 * 1000000 / freq; + if (!freq) + return -EINVAL; + + div = (u64)(GENMASK(23, 0) + 1) * 2 * USEC_PER_SEC; + max_debounce = div64_u64(div, freq); if (debounce > max_debounce) return -EINVAL; - div = debounce * freq; - div_reg = DIV_ROUND_CLOSEST_ULL(div, 2 * USEC_PER_SEC) - 1; + div = (u64)debounce * freq; + div_reg = DIV_ROUND_CLOSEST_ULL(div, 2 * USEC_PER_SEC); + div_reg = div_reg ? div_reg - 1 : 0; } else { div_debounce_support = false; } diff --git a/drivers/gpio/gpio-sodaville.c b/drivers/gpio/gpio-sodaville.c index 37c133837729..5198608ef930 100644 --- a/drivers/gpio/gpio-sodaville.c +++ b/drivers/gpio/gpio-sodaville.c @@ -166,9 +166,12 @@ static int sdv_register_irqsupport(struct sdv_gpio_chip_data *sd, ct->chip.irq_eoi = irq_gc_eoi; ct->chip.irq_set_type = sdv_gpio_pub_set_type; - irq_setup_generic_chip(sd->gc, IRQ_MSK(SDV_NUM_PUB_GPIOS), - IRQ_GC_INIT_MASK_CACHE, IRQ_NOREQUEST, - IRQ_LEVEL | IRQ_NOPROBE); + ret = devm_irq_setup_generic_chip(&pdev->dev, sd->gc, + IRQ_MSK(SDV_NUM_PUB_GPIOS), + IRQ_GC_INIT_MASK_CACHE, IRQ_NOREQUEST, + IRQ_LEVEL | IRQ_NOPROBE); + if (ret) + return ret; sd->id = irq_domain_create_legacy(dev_fwnode(&pdev->dev), SDV_NUM_PUB_GPIOS, sd->irq_base, 0, &irq_domain_sdv_ops, sd); diff --git a/drivers/gpio/gpio-virtuser.c b/drivers/gpio/gpio-virtuser.c index ce7ada0f1798..2735a9e711ee 100644 --- a/drivers/gpio/gpio-virtuser.c +++ b/drivers/gpio/gpio-virtuser.c @@ -58,9 +58,9 @@ struct gpio_virtuser_line_array_data { struct gpio_virtuser_line_data { struct gpio_virtuser_attr_data ad; char consumer[GPIO_VIRTUSER_NAME_BUF_LEN]; - struct mutex consumer_lock; + struct mutex lock; unsigned int debounce; - atomic_t irq; + int irq; atomic_t irq_count; }; @@ -612,7 +612,7 @@ static ssize_t gpio_virtuser_consumer_read(struct file *file, memset(buf, 0x0, sizeof(buf)); - scoped_guard(mutex, &data->consumer_lock) + scoped_guard(mutex, &data->lock) ret = snprintf(buf, sizeof(buf), "%s\n", data->consumer); return simple_read_from_buffer(user_buf, size, ppos, buf, ret); @@ -640,7 +640,7 @@ static ssize_t gpio_virtuser_consumer_write(struct file *file, if (ret) return ret; - scoped_guard(mutex, &data->consumer_lock) + scoped_guard(mutex, &data->lock) strscpy(data->consumer, buf, sizeof(data->consumer)); return count; @@ -680,7 +680,12 @@ static int gpio_virtuser_interrupts_set(void *data, u64 val) if (val > 1) return -EINVAL; + guard(mutex)(&ld->lock); + if (val) { + if (ld->irq >= 0) + return -EBUSY; + irq = gpiod_to_irq(ld->ad.desc); if (irq < 0) return irq; @@ -694,11 +699,13 @@ static int gpio_virtuser_interrupts_set(void *data, u64 val) if (ret) return ret; - atomic_set(&ld->irq, irq); + ld->irq = irq; } else { - irq = atomic_xchg(&ld->irq, 0); - if (irq) - free_irq(irq, ld); + if (ld->irq < 0) + return -EBUSY; + + free_irq(ld->irq, ld); + ld->irq = -1; } return 0; @@ -798,6 +805,14 @@ static int gpio_virtuser_dbgfs_init_line_array_attrs(struct device *dev, data->ad.dbgfs_dir, data); } +static void gpio_virtuser_free_irq(void *data) +{ + struct gpio_virtuser_line_data *ld = data; + + if (ld->irq >= 0) + free_irq(ld->irq, ld); +} + static int gpio_virtuser_dbgfs_init_line_attrs(struct device *dev, struct gpio_desc *desc, const char *id, @@ -814,14 +829,18 @@ static int gpio_virtuser_dbgfs_init_line_attrs(struct device *dev, data->ad.desc = desc; strscpy(data->consumer, id); - atomic_set(&data->irq, 0); + data->irq = -1; atomic_set(&data->irq_count, 0); + ret = devm_add_action_or_reset(dev, gpio_virtuser_free_irq, data); + if (ret) + return ret; + name = devm_kasprintf(dev, GFP_KERNEL, "gpiod:%s:%u", id, index); if (!name) return -ENOMEM; - ret = devm_mutex_init(dev, &data->consumer_lock); + ret = devm_mutex_init(dev, &data->lock); if (ret) return ret; @@ -932,38 +951,50 @@ static int gpio_virtuser_probe(struct platform_device *pdev) "Failed to get the IDs of GPIOs to request\n"); dbgfs_entry = debugfs_create_dir(dev_name(dev), gpio_virtuser_dbg_root); - ret = devm_add_action_or_reset(dev, gpio_virtuser_debugfs_remove, - dbgfs_entry); - if (ret) - return ret; for (i = 0; i < num_ids; i++) { descs = devm_gpiod_get_array(dev, ids[i], GPIOD_ASIS); - if (IS_ERR(descs)) - return dev_err_probe(dev, PTR_ERR(descs), - "Failed to request the '%s' GPIOs\n", - ids[i]); + if (IS_ERR(descs)) { + ret = dev_err_probe(dev, PTR_ERR(descs), + "Failed to request the '%s' GPIOs\n", + ids[i]); + goto err_remove_debugfs; + } ret = gpio_virtuser_dbgfs_init_line_array_attrs(dev, descs, ids[i], dbgfs_entry); - if (ret) - return dev_err_probe(dev, ret, - "Failed to setup the debugfs array interface for the '%s' GPIOs\n", - ids[i]); + if (ret) { + dev_err_probe(dev, ret, + "Failed to setup the debugfs array interface for the '%s' GPIOs\n", + ids[i]); + goto err_remove_debugfs; + } for (j = 0; j < descs->ndescs; j++) { ret = gpio_virtuser_dbgfs_init_line_attrs(dev, descs->desc[j], ids[i], j, dbgfs_entry); - if (ret) - return dev_err_probe(dev, ret, - "Failed to setup the debugfs line interface for the '%s' GPIOs\n", - ids[i]); + if (ret) { + dev_err_probe(dev, ret, + "Failed to setup the debugfs line interface for the '%s' GPIOs\n", + ids[i]); + goto err_remove_debugfs; + } } } - return 0; + /* + * The debugfs files point to the devres-managed line data allocated + * above. Register the removal last so that it runs first on unbind, + * before any of that data is released. + */ + return devm_add_action_or_reset(dev, gpio_virtuser_debugfs_remove, + dbgfs_entry); + +err_remove_debugfs: + debugfs_remove_recursive(dbgfs_entry); + return ret; } static const struct of_device_id gpio_virtuser_of_match[] = { diff --git a/drivers/gpio/gpiolib-of.h b/drivers/gpio/gpiolib-of.h index 2257f7a498a1..4778b46256bb 100644 --- a/drivers/gpio/gpiolib-of.h +++ b/drivers/gpio/gpiolib-of.h @@ -42,7 +42,7 @@ static inline bool of_gpiochip_instance_match(struct gpio_chip *gc, static inline int of_gpio_count(const struct fwnode_handle *fwnode, const char *con_id) { - return 0; + return -ENOENT; } #endif /* CONFIG_OF_GPIO */ diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index fa2ab0f90dbd..a41219961778 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -5042,21 +5042,21 @@ struct gpio_descs *__must_check gpiod_get_array(struct device *dev, if (!descs) return ERR_PTR(-ENOMEM); - for (descs->ndescs = 0; descs->ndescs < count; descs->ndescs++) { - desc = gpiod_get_index(dev, con_id, descs->ndescs, flags); + for (int i = 0; i < count; i++) { + desc = gpiod_get_index(dev, con_id, i, flags); if (IS_ERR(desc)) { gpiod_put_array(descs); return ERR_CAST(desc); } - descs->desc[descs->ndescs] = desc; + descs->desc[descs->ndescs++] = desc; gdev = gpiod_to_gpio_device(desc); /* * If pin hardware number of array member 0 is also 0, select * its chip as a candidate for fast bitmap processing path. */ - if (descs->ndescs == 0 && gpiod_hwgpio(desc) == 0) { + if (i == 0 && gpiod_hwgpio(desc) == 0) { struct gpio_descs *array; bitmap_size = BITS_TO_LONGS(gdev->ngpio > count ? @@ -5081,10 +5081,8 @@ struct gpio_descs *__must_check gpiod_get_array(struct device *dev, array_info->desc = descs->desc; array_info->size = count; array_info->gdev = gdev; - bitmap_set(array_info->get_mask, descs->ndescs, - count - descs->ndescs); - bitmap_set(array_info->set_mask, descs->ndescs, - count - descs->ndescs); + bitmap_set(array_info->get_mask, 0, count); + bitmap_set(array_info->set_mask, 0, count); descs->info = array_info; } @@ -5094,38 +5092,35 @@ struct gpio_descs *__must_check gpiod_get_array(struct device *dev, /* Unmark array members which don't belong to the 'fast' chip */ if (array_info->gdev != gdev) { - __clear_bit(descs->ndescs, array_info->get_mask); - __clear_bit(descs->ndescs, array_info->set_mask); + __clear_bit(i, array_info->get_mask); + __clear_bit(i, array_info->set_mask); } /* * Detect array members which belong to the 'fast' chip * but their pins are not in hardware order. */ - else if (gpiod_hwgpio(desc) != descs->ndescs) { + else if (gpiod_hwgpio(desc) != i) { /* * Don't use fast path if all array members processed so * far belong to the same chip as this one but its pin * hardware number is different from its array index. */ - if (bitmap_full(array_info->get_mask, descs->ndescs)) { + if (bitmap_full(array_info->get_mask, i)) { + descs->info = NULL; array_info = NULL; } else { - __clear_bit(descs->ndescs, - array_info->get_mask); - __clear_bit(descs->ndescs, - array_info->set_mask); + __clear_bit(i, array_info->get_mask); + __clear_bit(i, array_info->set_mask); } } else { dflags = READ_ONCE(desc->flags); /* Exclude open drain or open source from fast output */ if (test_bit(GPIOD_FLAG_OPEN_DRAIN, &dflags) || test_bit(GPIOD_FLAG_OPEN_SOURCE, &dflags)) - __clear_bit(descs->ndescs, - array_info->set_mask); + __clear_bit(i, array_info->set_mask); /* Identify 'fast' pins which require invertion */ if (gpiod_is_active_low(desc)) - __set_bit(descs->ndescs, - array_info->invert_mask); + __set_bit(i, array_info->invert_mask); } } if (array_info) diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c index c9614a99b40d..bedb5997ec02 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c @@ -526,12 +526,16 @@ static int amdgpu_vm_init_entities(struct amdgpu_device *adev, r = drm_sched_entity_init(&vm->immediate, DRM_SCHED_PRIORITY_NORMAL, adev->vm_manager.vm_pte_scheds, adev->vm_manager.vm_pte_num_scheds, NULL); + if (r) + return r; + + r = drm_sched_entity_init(&vm->delayed, DRM_SCHED_PRIORITY_NORMAL, + adev->vm_manager.vm_pte_scheds, + adev->vm_manager.vm_pte_num_scheds, NULL); if (r) goto error; - return drm_sched_entity_init(&vm->delayed, DRM_SCHED_PRIORITY_NORMAL, - adev->vm_manager.vm_pte_scheds, - adev->vm_manager.vm_pte_num_scheds, NULL); + return 0; error: drm_sched_entity_destroy(&vm->immediate); diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_chardev.c b/drivers/gpu/drm/amd/amdkfd/kfd_chardev.c index e4a6100d036a..1702021f7a08 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_chardev.c +++ b/drivers/gpu/drm/amd/amdkfd/kfd_chardev.c @@ -1996,7 +1996,9 @@ static int criu_checkpoint_bos(struct kfd_process *p, bo_bucket->offset = amdgpu_bo_mmap_offset(dumper_bo); for (i = 0; i < p->n_pdds; i++) { - if (amdgpu_amdkfd_bo_mapped_to_dev(p->pdds[i]->drm_priv, kgd_mem)) + /* nothing is mapped on a GPU without a VM */ + if (p->pdds[i]->drm_priv && + amdgpu_amdkfd_bo_mapped_to_dev(p->pdds[i]->drm_priv, kgd_mem)) bo_priv->mapped_gpuids[dev_idx++] = p->pdds[i]->user_gpu_id; } diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_trace.h b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_trace.h index a8f52c35a94d..ec8b39b8342f 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_trace.h +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_trace.h @@ -311,36 +311,32 @@ DEFINE_EVENT(amdgpu_dm_plane_state_template, amdgpu_dm_atomic_update_cursor, TP_PROTO(const struct drm_plane_state *state), TP_ARGS(state)); -TRACE_EVENT(amdgpu_dm_atomic_state_template, - TP_PROTO(const struct drm_atomic_state *state), - TP_ARGS(state), - - TP_STRUCT__entry( - __field(const struct drm_atomic_state *, state) - __field(bool, allow_modeset) - __field(bool, legacy_cursor_update) - __field(bool, async_update) - __field(bool, duplicated) - __field(int, num_connector) - __field(int, num_private_objs) - ), - - TP_fast_assign( - __entry->state = state; - __entry->allow_modeset = state->allow_modeset; - __entry->legacy_cursor_update = state->legacy_cursor_update; - __entry->async_update = state->async_update; - __entry->duplicated = state->duplicated; - __entry->num_connector = state->num_connector; - __entry->num_private_objs = state->num_private_objs; - ), - - TP_printk("state=%p allow_modeset=%d legacy_cursor_update=%d " - "async_update=%d duplicated=%d num_connector=%d " - "num_private_objs=%d", - __entry->state, __entry->allow_modeset, __entry->legacy_cursor_update, - __entry->async_update, __entry->duplicated, __entry->num_connector, - __entry->num_private_objs) +DECLARE_EVENT_CLASS(amdgpu_dm_atomic_state_template, + TP_PROTO(const struct drm_atomic_state *state), + TP_ARGS(state), + TP_STRUCT__entry(__field(const struct drm_atomic_state *, state) + __field(bool, allow_modeset) + __field(bool, legacy_cursor_update) + __field(bool, async_update) + __field(bool, duplicated) + __field(int, num_connector) + __field(int, num_private_objs) + ), + TP_fast_assign(__entry->state = state; + __entry->allow_modeset = state->allow_modeset; + __entry->legacy_cursor_update = state->legacy_cursor_update; + __entry->async_update = state->async_update; + __entry->duplicated = state->duplicated; + __entry->num_connector = state->num_connector; + __entry->num_private_objs = state->num_private_objs; + ), + TP_printk("state=%p allow_modeset=%d legacy_cursor_update=%d " + "async_update=%d duplicated=%d num_connector=%d " + "num_private_objs=%d", + __entry->state, __entry->allow_modeset, + __entry->legacy_cursor_update, __entry->async_update, + __entry->duplicated, __entry->num_connector, + __entry->num_private_objs) ); DEFINE_EVENT(amdgpu_dm_atomic_state_template, amdgpu_dm_atomic_commit_tail_begin, diff --git a/drivers/gpu/drm/amd/pm/swsmu/smu11/smu_v11_0.c b/drivers/gpu/drm/amd/pm/swsmu/smu11/smu_v11_0.c index 48bf000f12e5..42a4ba996508 100644 --- a/drivers/gpu/drm/amd/pm/swsmu/smu11/smu_v11_0.c +++ b/drivers/gpu/drm/amd/pm/swsmu/smu11/smu_v11_0.c @@ -1559,7 +1559,25 @@ int smu_v11_0_set_azalia_d3_pme(struct smu_context *smu) int smu_v11_0_baco_set_armd3_sequence(struct smu_context *smu, enum smu_baco_seq baco_seq) { - return smu_cmn_send_smc_msg_with_param(smu, SMU_MSG_ArmD3, baco_seq, NULL); + struct smu_baco_context *smu_baco = &smu->smu_baco; + int ret; + + ret = smu_cmn_send_smc_msg_with_param(smu, SMU_MSG_ArmD3, baco_seq, NULL); + if (ret) + return ret; + + /* + * PMFW owns the BACO transition once armed, so keep the driver's view + * in sync. Otherwise smu_v11_0_get_bamaco_support() falls back to the + * live BACO feature bit, which PMFW clears when armed, and the runtime + * resume wrongly concludes BACO is unsupported and skips the exit. + */ + if (baco_seq == BACO_SEQ_BAMACO || baco_seq == BACO_SEQ_BACO) + smu_baco->state = SMU_BACO_STATE_ENTER; + else + smu_baco->state = SMU_BACO_STATE_EXIT; + + return 0; } int smu_v11_0_get_bamaco_support(struct smu_context *smu) diff --git a/drivers/gpu/drm/amd/pm/swsmu/smu13/smu_v13_0_0_ppt.c b/drivers/gpu/drm/amd/pm/swsmu/smu13/smu_v13_0_0_ppt.c index 9d2d630bba24..4ed3bbc3effe 100644 --- a/drivers/gpu/drm/amd/pm/swsmu/smu13/smu_v13_0_0_ppt.c +++ b/drivers/gpu/drm/amd/pm/swsmu/smu13/smu_v13_0_0_ppt.c @@ -62,6 +62,9 @@ static void smu_v13_0_0_get_od_setting_limits(struct smu_context *smu, int od_feature_bit, int32_t *min, int32_t *max); +static int +smu_v13_0_0_upload_overdrive_table(struct smu_context *smu, + OverDriveTableExternal_t *od_table); #define FEATURE_MASK(feature) (1ULL << feature) #define SMC_DPM_FEATURE ( \ @@ -1096,6 +1099,93 @@ static bool smu_v13_0_0_is_od_feature_supported(struct smu_context *smu, return feature_enabled; } +static u32 +smu_v13_0_0_filter_od_feature_mask(struct smu_context *smu, u32 feature_mask) +{ + PPTable_t *pptable = smu->smu_table.driver_pptable; + u32 supported_mask = + pptable->SkuTable.OverDriveLimitsBasicMax.FeatureCtrlMask; + + return feature_mask & supported_mask; +} + +static bool smu_v13_0_0_fan_is_default(const OverDriveTable_t *od, + const OverDriveTable_t *boot) +{ + return !memcmp(od->FanLinearPwmPoints, boot->FanLinearPwmPoints, + sizeof(od->FanLinearPwmPoints)) && + !memcmp(od->FanLinearTempPoints, boot->FanLinearTempPoints, + sizeof(od->FanLinearTempPoints)) && + od->FanMinimumPwm == boot->FanMinimumPwm && + od->AcousticTargetRpmThreshold == boot->AcousticTargetRpmThreshold && + od->AcousticLimitRpmThreshold == boot->AcousticLimitRpmThreshold && + od->FanTargetTemperature == boot->FanTargetTemperature && + od->FanMode == boot->FanMode; +} + +static bool smu_v13_0_0_zero_fan_is_default(const OverDriveTable_t *od, + const OverDriveTable_t *boot) +{ + return od->FanZeroRpmEnable == boot->FanZeroRpmEnable && + od->FanZeroRpmStopTemp == boot->FanZeroRpmStopTemp; +} + +static u32 smu_v13_0_0_normalize_feature_mask(const OverDriveTable_t *od, + const OverDriveTable_t *boot, + u32 feature_mask) +{ + if (od->GfxclkFmin == boot->GfxclkFmin && + od->GfxclkFmax == boot->GfxclkFmax) + feature_mask &= ~BIT(PP_OD_FEATURE_GFXCLK_BIT); + if (od->UclkFmin == boot->UclkFmin && + od->UclkFmax == boot->UclkFmax) + feature_mask &= ~BIT(PP_OD_FEATURE_UCLK_BIT); + if (!memcmp(od->VoltageOffsetPerZoneBoundary, + boot->VoltageOffsetPerZoneBoundary, + sizeof(od->VoltageOffsetPerZoneBoundary))) + feature_mask &= ~BIT(PP_OD_FEATURE_GFX_VF_CURVE_BIT); + if (smu_v13_0_0_fan_is_default(od, boot)) + feature_mask &= ~BIT(PP_OD_FEATURE_FAN_CURVE_BIT); + if (smu_v13_0_0_zero_fan_is_default(od, boot)) + feature_mask &= ~BIT(PP_OD_FEATURE_ZERO_FAN_BIT); + if (!od->Ppt) + feature_mask &= ~BIT(PP_OD_FEATURE_PPT_BIT); + + return feature_mask; +} + +static int +smu_v13_0_0_upload_ppt_overdrive_table(struct smu_context *smu, s16 ppt) +{ + struct smu_table_context *table_context = &smu->smu_table; + OverDriveTableExternal_t *od_table = table_context->overdrive_table; + OverDriveTableExternal_t *user_od_table = table_context->user_overdrive_table; + OverDriveTableExternal_t upload_table; + u32 next_mask = table_context->user_od_feature_mask; + int ret; + + /* Do not commit OD settings staged after the last c operation. */ + memcpy(&upload_table, user_od_table, sizeof(upload_table)); + upload_table.OverDriveTable.Ppt = ppt; + if (ppt) + next_mask |= BIT(PP_OD_FEATURE_PPT_BIT); + else + next_mask &= ~BIT(PP_OD_FEATURE_PPT_BIT); + upload_table.OverDriveTable.FeatureCtrlMask = + smu_v13_0_0_filter_od_feature_mask(smu, next_mask); + + ret = smu_v13_0_0_upload_overdrive_table(smu, &upload_table); + if (ret) + return ret; + + table_context->user_od_feature_mask = + upload_table.OverDriveTable.FeatureCtrlMask; + od_table->OverDriveTable.Ppt = ppt; + user_od_table->OverDriveTable.Ppt = ppt; + + return 0; +} + static void smu_v13_0_0_get_od_setting_limits(struct smu_context *smu, int od_feature_bit, int32_t *min, @@ -1588,41 +1678,30 @@ static int smu_v13_0_0_od_restore_table_single(struct smu_context *smu, long inp boot_overdrive_table->OverDriveTable.FanLinearPwmPoints[i]; } od_table->OverDriveTable.FanMode = FAN_MODE_AUTO; - od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_FAN_CURVE_BIT); break; case PP_OD_EDIT_ACOUSTIC_LIMIT: od_table->OverDriveTable.AcousticLimitRpmThreshold = boot_overdrive_table->OverDriveTable.AcousticLimitRpmThreshold; - od_table->OverDriveTable.FanMode = FAN_MODE_AUTO; - od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_FAN_CURVE_BIT); break; case PP_OD_EDIT_ACOUSTIC_TARGET: od_table->OverDriveTable.AcousticTargetRpmThreshold = boot_overdrive_table->OverDriveTable.AcousticTargetRpmThreshold; - od_table->OverDriveTable.FanMode = FAN_MODE_AUTO; - od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_FAN_CURVE_BIT); break; case PP_OD_EDIT_FAN_TARGET_TEMPERATURE: od_table->OverDriveTable.FanTargetTemperature = boot_overdrive_table->OverDriveTable.FanTargetTemperature; - od_table->OverDriveTable.FanMode = FAN_MODE_AUTO; - od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_FAN_CURVE_BIT); break; case PP_OD_EDIT_FAN_MINIMUM_PWM: od_table->OverDriveTable.FanMinimumPwm = boot_overdrive_table->OverDriveTable.FanMinimumPwm; - od_table->OverDriveTable.FanMode = FAN_MODE_AUTO; - od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_FAN_CURVE_BIT); break; case PP_OD_EDIT_FAN_ZERO_RPM_ENABLE: od_table->OverDriveTable.FanZeroRpmEnable = boot_overdrive_table->OverDriveTable.FanZeroRpmEnable; - od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_ZERO_FAN_BIT); break; case PP_OD_EDIT_FAN_ZERO_RPM_STOP_TEMP: od_table->OverDriveTable.FanZeroRpmStopTemp = boot_overdrive_table->OverDriveTable.FanZeroRpmStopTemp; - od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_ZERO_FAN_BIT); break; default: dev_info(adev->dev, "Invalid table index: %ld\n", input); @@ -1640,9 +1719,17 @@ static int smu_v13_0_0_od_edit_dpm_table(struct smu_context *smu, struct smu_table_context *table_context = &smu->smu_table; OverDriveTableExternal_t *od_table = (OverDriveTableExternal_t *)table_context->overdrive_table; + OverDriveTableExternal_t *user_od_table = + (OverDriveTableExternal_t *)table_context->user_overdrive_table; + OverDriveTableExternal_t *boot_od_table = + (OverDriveTableExternal_t *)table_context->boot_overdrive_table; + OverDriveTableExternal_t upload_table; + OverDriveTable_t *od = &od_table->OverDriveTable; + OverDriveTable_t *boot = &boot_od_table->OverDriveTable; struct amdgpu_device *adev = smu->adev; uint32_t offset_of_voltageoffset; int32_t minimum, maximum; + u32 next_mask; int i, ret = 0; switch (type) { @@ -1966,36 +2053,41 @@ static int smu_v13_0_0_od_edit_dpm_table(struct smu_context *smu, } else { memcpy(od_table, table_context->boot_overdrive_table, - sizeof(OverDriveTableExternal_t)); + sizeof(OverDriveTableExternal_t)); od_table->OverDriveTable.FeatureCtrlMask = 0; - table_context->user_od_feature_mask = 0; } fallthrough; case PP_OD_COMMIT_DPM_TABLE: - table_context->user_od_feature_mask = - od_table->OverDriveTable.FeatureCtrlMask; offset_of_voltageoffset = offsetof(OverDriveTable_t, VoltageOffsetPerZoneBoundary); - if (memcmp((u8 *)od_table + offset_of_voltageoffset, - table_context->user_overdrive_table + offset_of_voltageoffset, - sizeof(OverDriveTableExternal_t) - offset_of_voltageoffset)) { - smu_v13_0_0_dump_od_table(smu, od_table); + next_mask = smu_v13_0_0_filter_od_feature_mask(smu, + table_context->user_od_feature_mask | + od->FeatureCtrlMask); + next_mask = smu_v13_0_0_normalize_feature_mask(od, boot, + next_mask); - ret = smu_v13_0_0_upload_overdrive_table(smu, od_table); + if (memcmp((u8 *)od_table + offset_of_voltageoffset, + (u8 *)user_od_table + offset_of_voltageoffset, + sizeof(OverDriveTableExternal_t) - offset_of_voltageoffset) || + next_mask != table_context->user_od_feature_mask) { + memcpy(&upload_table, od_table, sizeof(upload_table)); + upload_table.OverDriveTable.FeatureCtrlMask = next_mask; + smu_v13_0_0_dump_od_table(smu, &upload_table); + + ret = smu_v13_0_0_upload_overdrive_table(smu, &upload_table); if (ret) { dev_err(adev->dev, "Failed to upload overdrive table!\n"); return ret; } - memcpy(table_context->user_overdrive_table + offset_of_voltageoffset, + table_context->user_od_feature_mask = next_mask; + od_table->OverDriveTable.FeatureCtrlMask = 0; + memcpy((u8 *)user_od_table + offset_of_voltageoffset, (u8 *)od_table + offset_of_voltageoffset, sizeof(OverDriveTableExternal_t) - offset_of_voltageoffset); + user_od_table->OverDriveTable.FeatureCtrlMask = 0; - if (!memcmp(table_context->user_overdrive_table, - table_context->boot_overdrive_table, - sizeof(OverDriveTableExternal_t))) - smu->user_dpm_profile.user_od = false; - else - smu->user_dpm_profile.user_od = true; + smu->user_dpm_profile.user_od = + !!(next_mask & ~BIT(PP_OD_FEATURE_PPT_BIT)); } break; @@ -2254,6 +2346,7 @@ static int smu_v13_0_0_set_default_od_settings(struct smu_context *smu) memcpy(od_table, boot_od_table, sizeof(OverDriveTableExternal_t)); + od_table->OverDriveTable.FeatureCtrlMask = 0; /* * For S3/S4/Runpm resume, we need to setup those overdrive tables again, @@ -2263,6 +2356,7 @@ static int smu_v13_0_0_set_default_od_settings(struct smu_context *smu) memcpy(user_od_table, boot_od_table, sizeof(OverDriveTableExternal_t)); + user_od_table->OverDriveTable.FeatureCtrlMask = 0; smu->user_dpm_profile.user_od = false; smu->smu_table.user_od_feature_mask = 0; } else if (smu->user_dpm_profile.user_od) { @@ -2301,6 +2395,14 @@ static int smu_v13_0_0_set_default_od_settings(struct smu_context *smu) user_od_table_bak.OverDriveTable.FanZeroRpmEnable; user_od_table->OverDriveTable.FanZeroRpmStopTemp = user_od_table_bak.OverDriveTable.FanZeroRpmStopTemp; + user_od_table->OverDriveTable.FanMode = + user_od_table_bak.OverDriveTable.FanMode; + user_od_table->OverDriveTable.FeatureCtrlMask = 0; + } + if (smu->adev->in_suspend) { + user_od_table->OverDriveTable.Ppt = 0; + smu->smu_table.user_od_feature_mask &= + ~BIT(PP_OD_FEATURE_PPT_BIT); } smu_v13_0_0_set_supported_od_feature_mask(smu); @@ -2313,13 +2415,22 @@ static int smu_v13_0_0_restore_user_od_settings(struct smu_context *smu) struct smu_table_context *table_context = &smu->smu_table; OverDriveTableExternal_t *od_table = table_context->overdrive_table; OverDriveTableExternal_t *user_od_table = table_context->user_overdrive_table; + OverDriveTableExternal_t upload_table; + u32 next_mask; int res; - user_od_table->OverDriveTable.FeatureCtrlMask = - table_context->user_od_feature_mask; - res = smu_v13_0_0_upload_overdrive_table(smu, user_od_table); - user_od_table->OverDriveTable.FeatureCtrlMask = 0; - if (res == 0) + + next_mask = smu_v13_0_0_filter_od_feature_mask(smu, + table_context->user_od_feature_mask); + memcpy(&upload_table, user_od_table, sizeof(upload_table)); + upload_table.OverDriveTable.FeatureCtrlMask = next_mask; + res = smu_v13_0_0_upload_overdrive_table(smu, &upload_table); + if (res == 0) { + table_context->user_od_feature_mask = next_mask; + smu->user_dpm_profile.user_od = + !!(next_mask & ~BIT(PP_OD_FEATURE_PPT_BIT)); memcpy(od_table, user_od_table, sizeof(OverDriveTableExternal_t)); + od_table->OverDriveTable.FeatureCtrlMask = 0; + } return res; } @@ -3109,9 +3220,7 @@ static int smu_v13_0_0_set_power_limit(struct smu_context *smu, PPTable_t *pptable = smu->smu_table.driver_pptable; SkuTable_t *skutable = &pptable->SkuTable; uint32_t msg_limit = skutable->MsgLimits.Power[PPT_THROTTLER_PPT0][POWER_SOURCE_AC]; - struct smu_table_context *table_context = &smu->smu_table; - OverDriveTableExternal_t *od_table = - (OverDriveTableExternal_t *)table_context->overdrive_table; + s16 ppt; int ret = 0; if (limit_type != SMU_DEFAULT_PPT_LIMIT) @@ -3119,12 +3228,7 @@ static int smu_v13_0_0_set_power_limit(struct smu_context *smu, if (limit <= msg_limit) { if (smu->current_power_limit > msg_limit) { - od_table->OverDriveTable.Ppt = 0; - table_context->user_od_feature_mask &= - ~(1U << PP_OD_FEATURE_PPT_BIT); - od_table->OverDriveTable.FeatureCtrlMask = - table_context->user_od_feature_mask; - ret = smu_v13_0_0_upload_overdrive_table(smu, od_table); + ret = smu_v13_0_0_upload_ppt_overdrive_table(smu, 0); if (ret) { dev_err(smu->adev->dev, "Failed to upload overdrive table!\n"); return ret; @@ -3136,11 +3240,8 @@ static int smu_v13_0_0_set_power_limit(struct smu_context *smu, if (ret) return ret; - od_table->OverDriveTable.Ppt = (limit * 100) / msg_limit - 100; - table_context->user_od_feature_mask |= 1U << PP_OD_FEATURE_PPT_BIT; - od_table->OverDriveTable.FeatureCtrlMask = - table_context->user_od_feature_mask; - ret = smu_v13_0_0_upload_overdrive_table(smu, od_table); + ppt = (limit * 100) / msg_limit - 100; + ret = smu_v13_0_0_upload_ppt_overdrive_table(smu, ppt); if (ret) { dev_err(smu->adev->dev, "Failed to upload overdrive table!\n"); return ret; diff --git a/drivers/gpu/drm/amd/pm/swsmu/smu13/smu_v13_0_7_ppt.c b/drivers/gpu/drm/amd/pm/swsmu/smu13/smu_v13_0_7_ppt.c index 5df28b89cb69..dab5514b1832 100644 --- a/drivers/gpu/drm/amd/pm/swsmu/smu13/smu_v13_0_7_ppt.c +++ b/drivers/gpu/drm/amd/pm/swsmu/smu13/smu_v13_0_7_ppt.c @@ -62,6 +62,9 @@ static void smu_v13_0_7_get_od_setting_limits(struct smu_context *smu, int od_feature_bit, int32_t *min, int32_t *max); +static int +smu_v13_0_7_upload_overdrive_table(struct smu_context *smu, + OverDriveTableExternal_t *od_table); #define FEATURE_MASK(feature) (1ULL << feature) #define SMC_DPM_FEATURE ( \ @@ -80,6 +83,7 @@ static void smu_v13_0_7_get_od_setting_limits(struct smu_context *smu, #define PP_OD_FEATURE_GFXCLK_FMAX 1 #define PP_OD_FEATURE_UCLK_FMIN 2 #define PP_OD_FEATURE_UCLK_FMAX 3 + #define PP_OD_FEATURE_GFX_VF_CURVE 4 #define PP_OD_FEATURE_FAN_CURVE_TEMP 5 #define PP_OD_FEATURE_FAN_CURVE_PWM 6 @@ -1085,6 +1089,93 @@ static bool smu_v13_0_7_is_od_feature_supported(struct smu_context *smu, return feature_enabled; } +static u32 +smu_v13_0_7_filter_od_feature_mask(struct smu_context *smu, u32 feature_mask) +{ + PPTable_t *pptable = smu->smu_table.driver_pptable; + u32 supported_mask = + pptable->SkuTable.OverDriveLimitsBasicMax.FeatureCtrlMask; + + return feature_mask & supported_mask; +} + +static bool smu_v13_0_7_fan_is_default(const OverDriveTable_t *od, + const OverDriveTable_t *boot) +{ + return !memcmp(od->FanLinearPwmPoints, boot->FanLinearPwmPoints, + sizeof(od->FanLinearPwmPoints)) && + !memcmp(od->FanLinearTempPoints, boot->FanLinearTempPoints, + sizeof(od->FanLinearTempPoints)) && + od->FanMinimumPwm == boot->FanMinimumPwm && + od->AcousticTargetRpmThreshold == boot->AcousticTargetRpmThreshold && + od->AcousticLimitRpmThreshold == boot->AcousticLimitRpmThreshold && + od->FanTargetTemperature == boot->FanTargetTemperature && + od->FanMode == boot->FanMode; +} + +static bool smu_v13_0_7_zero_fan_is_default(const OverDriveTable_t *od, + const OverDriveTable_t *boot) +{ + return od->FanZeroRpmEnable == boot->FanZeroRpmEnable && + od->FanZeroRpmStopTemp == boot->FanZeroRpmStopTemp; +} + +static u32 smu_v13_0_7_normalize_feature_mask(const OverDriveTable_t *od, + const OverDriveTable_t *boot, + u32 feature_mask) +{ + if (od->GfxclkFmin == boot->GfxclkFmin && + od->GfxclkFmax == boot->GfxclkFmax) + feature_mask &= ~BIT(PP_OD_FEATURE_GFXCLK_BIT); + if (od->UclkFmin == boot->UclkFmin && + od->UclkFmax == boot->UclkFmax) + feature_mask &= ~BIT(PP_OD_FEATURE_UCLK_BIT); + if (!memcmp(od->VoltageOffsetPerZoneBoundary, + boot->VoltageOffsetPerZoneBoundary, + sizeof(od->VoltageOffsetPerZoneBoundary))) + feature_mask &= ~BIT(PP_OD_FEATURE_GFX_VF_CURVE_BIT); + if (smu_v13_0_7_fan_is_default(od, boot)) + feature_mask &= ~BIT(PP_OD_FEATURE_FAN_CURVE_BIT); + if (smu_v13_0_7_zero_fan_is_default(od, boot)) + feature_mask &= ~BIT(PP_OD_FEATURE_ZERO_FAN_BIT); + if (!od->Ppt) + feature_mask &= ~BIT(PP_OD_FEATURE_PPT_BIT); + + return feature_mask; +} + +static int +smu_v13_0_7_upload_ppt_overdrive_table(struct smu_context *smu, s16 ppt) +{ + struct smu_table_context *table_context = &smu->smu_table; + OverDriveTableExternal_t *od_table = table_context->overdrive_table; + OverDriveTableExternal_t *user_od_table = table_context->user_overdrive_table; + OverDriveTableExternal_t upload_table; + u32 next_mask = table_context->user_od_feature_mask; + int ret; + + /* Do not commit OD settings staged after the last c operation. */ + memcpy(&upload_table, user_od_table, sizeof(upload_table)); + upload_table.OverDriveTable.Ppt = ppt; + if (ppt) + next_mask |= BIT(PP_OD_FEATURE_PPT_BIT); + else + next_mask &= ~BIT(PP_OD_FEATURE_PPT_BIT); + upload_table.OverDriveTable.FeatureCtrlMask = + smu_v13_0_7_filter_od_feature_mask(smu, next_mask); + + ret = smu_v13_0_7_upload_overdrive_table(smu, &upload_table); + if (ret) + return ret; + + table_context->user_od_feature_mask = + upload_table.OverDriveTable.FeatureCtrlMask; + od_table->OverDriveTable.Ppt = ppt; + user_od_table->OverDriveTable.Ppt = ppt; + + return 0; +} + static void smu_v13_0_7_get_od_setting_limits(struct smu_context *smu, int od_feature_bit, int32_t *min, @@ -1576,41 +1667,30 @@ static int smu_v13_0_7_od_restore_table_single(struct smu_context *smu, long inp boot_overdrive_table->OverDriveTable.FanLinearPwmPoints[i]; } od_table->OverDriveTable.FanMode = FAN_MODE_AUTO; - od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_FAN_CURVE_BIT); break; case PP_OD_EDIT_ACOUSTIC_LIMIT: od_table->OverDriveTable.AcousticLimitRpmThreshold = boot_overdrive_table->OverDriveTable.AcousticLimitRpmThreshold; - od_table->OverDriveTable.FanMode = FAN_MODE_AUTO; - od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_FAN_CURVE_BIT); break; case PP_OD_EDIT_ACOUSTIC_TARGET: od_table->OverDriveTable.AcousticTargetRpmThreshold = boot_overdrive_table->OverDriveTable.AcousticTargetRpmThreshold; - od_table->OverDriveTable.FanMode = FAN_MODE_AUTO; - od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_FAN_CURVE_BIT); break; case PP_OD_EDIT_FAN_TARGET_TEMPERATURE: od_table->OverDriveTable.FanTargetTemperature = boot_overdrive_table->OverDriveTable.FanTargetTemperature; - od_table->OverDriveTable.FanMode = FAN_MODE_AUTO; - od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_FAN_CURVE_BIT); break; case PP_OD_EDIT_FAN_MINIMUM_PWM: od_table->OverDriveTable.FanMinimumPwm = boot_overdrive_table->OverDriveTable.FanMinimumPwm; - od_table->OverDriveTable.FanMode = FAN_MODE_AUTO; - od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_FAN_CURVE_BIT); break; case PP_OD_EDIT_FAN_ZERO_RPM_ENABLE: od_table->OverDriveTable.FanZeroRpmEnable = boot_overdrive_table->OverDriveTable.FanZeroRpmEnable; - od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_ZERO_FAN_BIT); break; case PP_OD_EDIT_FAN_ZERO_RPM_STOP_TEMP: od_table->OverDriveTable.FanZeroRpmStopTemp = boot_overdrive_table->OverDriveTable.FanZeroRpmStopTemp; - od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_ZERO_FAN_BIT); break; default: dev_info(adev->dev, "Invalid table index: %ld\n", input); @@ -1628,9 +1708,17 @@ static int smu_v13_0_7_od_edit_dpm_table(struct smu_context *smu, struct smu_table_context *table_context = &smu->smu_table; OverDriveTableExternal_t *od_table = (OverDriveTableExternal_t *)table_context->overdrive_table; + OverDriveTableExternal_t *user_od_table = + (OverDriveTableExternal_t *)table_context->user_overdrive_table; + OverDriveTableExternal_t *boot_od_table = + (OverDriveTableExternal_t *)table_context->boot_overdrive_table; + OverDriveTableExternal_t upload_table; + OverDriveTable_t *od = &od_table->OverDriveTable; + OverDriveTable_t *boot = &boot_od_table->OverDriveTable; struct amdgpu_device *adev = smu->adev; uint32_t offset_of_voltageoffset; int32_t minimum, maximum; + u32 next_mask; int i, ret = 0; switch (type) { @@ -1956,35 +2044,40 @@ static int smu_v13_0_7_od_edit_dpm_table(struct smu_context *smu, table_context->boot_overdrive_table, sizeof(OverDriveTableExternal_t)); od_table->OverDriveTable.FeatureCtrlMask = 0; - table_context->user_od_feature_mask = 0; } fallthrough; case PP_OD_COMMIT_DPM_TABLE: - table_context->user_od_feature_mask = - od_table->OverDriveTable.FeatureCtrlMask; offset_of_voltageoffset = offsetof(OverDriveTable_t, VoltageOffsetPerZoneBoundary); - if (memcmp((u8 *)od_table + offset_of_voltageoffset, - table_context->user_overdrive_table + offset_of_voltageoffset, - sizeof(OverDriveTableExternal_t) - offset_of_voltageoffset)) { - smu_v13_0_7_dump_od_table(smu, od_table); + next_mask = smu_v13_0_7_filter_od_feature_mask(smu, + table_context->user_od_feature_mask | + od->FeatureCtrlMask); + next_mask = smu_v13_0_7_normalize_feature_mask(od, boot, + next_mask); - ret = smu_v13_0_7_upload_overdrive_table(smu, od_table); + if (memcmp((u8 *)od_table + offset_of_voltageoffset, + (u8 *)user_od_table + offset_of_voltageoffset, + sizeof(OverDriveTableExternal_t) - offset_of_voltageoffset) || + next_mask != table_context->user_od_feature_mask) { + memcpy(&upload_table, od_table, sizeof(upload_table)); + upload_table.OverDriveTable.FeatureCtrlMask = next_mask; + smu_v13_0_7_dump_od_table(smu, &upload_table); + + ret = smu_v13_0_7_upload_overdrive_table(smu, &upload_table); if (ret) { dev_err(adev->dev, "Failed to upload overdrive table!\n"); return ret; } - memcpy(table_context->user_overdrive_table + offset_of_voltageoffset, + table_context->user_od_feature_mask = next_mask; + od_table->OverDriveTable.FeatureCtrlMask = 0; + memcpy((u8 *)user_od_table + offset_of_voltageoffset, (u8 *)od_table + offset_of_voltageoffset, sizeof(OverDriveTableExternal_t) - offset_of_voltageoffset); + user_od_table->OverDriveTable.FeatureCtrlMask = 0; - if (!memcmp(table_context->user_overdrive_table, - table_context->boot_overdrive_table, - sizeof(OverDriveTableExternal_t))) - smu->user_dpm_profile.user_od = false; - else - smu->user_dpm_profile.user_od = true; + smu->user_dpm_profile.user_od = + !!(next_mask & ~BIT(PP_OD_FEATURE_PPT_BIT)); } break; @@ -2237,6 +2330,7 @@ static int smu_v13_0_7_set_default_od_settings(struct smu_context *smu) memcpy(od_table, boot_od_table, sizeof(OverDriveTableExternal_t)); + od_table->OverDriveTable.FeatureCtrlMask = 0; /* * For S3/S4/Runpm resume, we need to setup those overdrive tables again, @@ -2246,6 +2340,7 @@ static int smu_v13_0_7_set_default_od_settings(struct smu_context *smu) memcpy(user_od_table, boot_od_table, sizeof(OverDriveTableExternal_t)); + user_od_table->OverDriveTable.FeatureCtrlMask = 0; smu->user_dpm_profile.user_od = false; smu->smu_table.user_od_feature_mask = 0; } else if (smu->user_dpm_profile.user_od) { @@ -2284,6 +2379,14 @@ static int smu_v13_0_7_set_default_od_settings(struct smu_context *smu) user_od_table_bak.OverDriveTable.FanZeroRpmEnable; user_od_table->OverDriveTable.FanZeroRpmStopTemp = user_od_table_bak.OverDriveTable.FanZeroRpmStopTemp; + user_od_table->OverDriveTable.FanMode = + user_od_table_bak.OverDriveTable.FanMode; + user_od_table->OverDriveTable.FeatureCtrlMask = 0; + } + if (smu->adev->in_suspend) { + user_od_table->OverDriveTable.Ppt = 0; + smu->smu_table.user_od_feature_mask &= + ~BIT(PP_OD_FEATURE_PPT_BIT); } smu_v13_0_7_set_supported_od_feature_mask(smu); @@ -2296,14 +2399,22 @@ static int smu_v13_0_7_restore_user_od_settings(struct smu_context *smu) struct smu_table_context *table_context = &smu->smu_table; OverDriveTableExternal_t *od_table = table_context->overdrive_table; OverDriveTableExternal_t *user_od_table = table_context->user_overdrive_table; + OverDriveTableExternal_t upload_table; + u32 next_mask; int res; - user_od_table->OverDriveTable.FeatureCtrlMask = - table_context->user_od_feature_mask; - res = smu_v13_0_7_upload_overdrive_table(smu, user_od_table); - user_od_table->OverDriveTable.FeatureCtrlMask = 0; - if (res == 0) + next_mask = smu_v13_0_7_filter_od_feature_mask(smu, + table_context->user_od_feature_mask); + memcpy(&upload_table, user_od_table, sizeof(upload_table)); + upload_table.OverDriveTable.FeatureCtrlMask = next_mask; + res = smu_v13_0_7_upload_overdrive_table(smu, &upload_table); + if (res == 0) { + table_context->user_od_feature_mask = next_mask; + smu->user_dpm_profile.user_od = + !!(next_mask & ~BIT(PP_OD_FEATURE_PPT_BIT)); memcpy(od_table, user_od_table, sizeof(OverDriveTableExternal_t)); + od_table->OverDriveTable.FeatureCtrlMask = 0; + } return res; } @@ -2706,9 +2817,7 @@ static int smu_v13_0_7_set_power_limit(struct smu_context *smu, PPTable_t *pptable = smu->smu_table.driver_pptable; SkuTable_t *skutable = &pptable->SkuTable; uint32_t msg_limit = skutable->MsgLimits.Power[PPT_THROTTLER_PPT0][POWER_SOURCE_AC]; - struct smu_table_context *table_context = &smu->smu_table; - OverDriveTableExternal_t *od_table = - (OverDriveTableExternal_t *)table_context->overdrive_table; + s16 ppt; int ret = 0; if (limit_type != SMU_DEFAULT_PPT_LIMIT) @@ -2716,13 +2825,7 @@ static int smu_v13_0_7_set_power_limit(struct smu_context *smu, if (limit <= msg_limit) { if (smu->current_power_limit > msg_limit) { - od_table->OverDriveTable.Ppt = 0; - table_context->user_od_feature_mask &= - ~(1U << PP_OD_FEATURE_PPT_BIT); - od_table->OverDriveTable.FeatureCtrlMask = - table_context->user_od_feature_mask; - - ret = smu_v13_0_7_upload_overdrive_table(smu, od_table); + ret = smu_v13_0_7_upload_ppt_overdrive_table(smu, 0); if (ret) { dev_err(smu->adev->dev, "Failed to upload overdrive table!\n"); return ret; @@ -2734,12 +2837,8 @@ static int smu_v13_0_7_set_power_limit(struct smu_context *smu, if (ret) return ret; - od_table->OverDriveTable.Ppt = (limit * 100) / msg_limit - 100; - table_context->user_od_feature_mask |= 1U << PP_OD_FEATURE_PPT_BIT; - od_table->OverDriveTable.FeatureCtrlMask = - table_context->user_od_feature_mask; - - ret = smu_v13_0_7_upload_overdrive_table(smu, od_table); + ppt = (limit * 100) / msg_limit - 100; + ret = smu_v13_0_7_upload_ppt_overdrive_table(smu, ppt); if (ret) { dev_err(smu->adev->dev, "Failed to upload overdrive table!\n"); return ret; diff --git a/drivers/gpu/drm/bridge/sii902x.c b/drivers/gpu/drm/bridge/sii902x.c index 1f0aba28ad1e..9c1566263ed9 100644 --- a/drivers/gpu/drm/bridge/sii902x.c +++ b/drivers/gpu/drm/bridge/sii902x.c @@ -891,9 +891,15 @@ static int sii902x_audio_codec_init(struct sii902x *sii902x, } codec_data.max_i2s_channels = 2 * num_lanes; - for (i = 0; i < num_lanes; i++) + for (i = 0; i < num_lanes; i++) { + if (lanes[i] >= ARRAY_SIZE(i2s_lane_id)) + return dev_err_probe(dev, -EINVAL, + "invalid sil,i2s-data-lanes value %u\n", + lanes[i]); + sii902x->audio.i2s_fifo_sequence[i] |= audio_fifo_id[i] | i2s_lane_id[lanes[i]] | SII902X_TPI_I2S_FIFO_ENABLE; + } sii902x->audio.mclk = devm_clk_get_optional(dev, "mclk"); if (IS_ERR(sii902x->audio.mclk)) { diff --git a/drivers/gpu/drm/drm_connector.c b/drivers/gpu/drm/drm_connector.c index 0326b9adb5f1..3e40efc2298a 100644 --- a/drivers/gpu/drm/drm_connector.c +++ b/drivers/gpu/drm/drm_connector.c @@ -612,8 +612,11 @@ int drmm_connector_hdmi_init(struct drm_device *dev, * drm_connector_attach_max_bpc_property() requires the * connector to have a state. */ - if (connector->funcs->reset) + if (connector->funcs->reset) { connector->funcs->reset(connector); + if (!connector->state) + return -ENOMEM; + } drm_connector_attach_max_bpc_property(connector, 8, max_bpc); connector->max_bpc = max_bpc; diff --git a/drivers/gpu/drm/i915/display/intel_dp.c b/drivers/gpu/drm/i915/display/intel_dp.c index 84fca860c93e..27bd54c4b4e6 100644 --- a/drivers/gpu/drm/i915/display/intel_dp.c +++ b/drivers/gpu/drm/i915/display/intel_dp.c @@ -490,9 +490,9 @@ bool intel_dp_has_joiner(struct intel_dp *intel_dp) if (intel_dp->mso_link_count) return false; - return DISPLAY_VER(display) >= 12 || + return ((DISPLAY_VER(display) >= 12 && DISPLAY_VERx100(display) != 3002) || (DISPLAY_VER(display) == 11 && - encoder->port != PORT_A); + encoder->port != PORT_A)); } static int dg2_max_source_rate(struct intel_dp *intel_dp) diff --git a/drivers/gpu/drm/imagination/pvr_rogue_fwif.h b/drivers/gpu/drm/imagination/pvr_rogue_fwif.h index 5d590c4c2566..2f8daa93c9e6 100644 --- a/drivers/gpu/drm/imagination/pvr_rogue_fwif.h +++ b/drivers/gpu/drm/imagination/pvr_rogue_fwif.h @@ -2174,7 +2174,7 @@ struct rogue_fwif_hwrtdata { bool geom_caches_need_zeroing __aligned(4); struct rogue_fwif_cleanup_ctl cleanup_state __aligned(64); -} __aligned(8); +} __aligned(64); /* ****************************************************************************** diff --git a/drivers/gpu/drm/msm/adreno/a5xx_gpu.c b/drivers/gpu/drm/msm/adreno/a5xx_gpu.c index 4a04dc43a8e6..3d123f6e51ab 100644 --- a/drivers/gpu/drm/msm/adreno/a5xx_gpu.c +++ b/drivers/gpu/drm/msm/adreno/a5xx_gpu.c @@ -1338,9 +1338,14 @@ static const u32 a5xx_registers[] = { 0xE800, 0xE806, 0xE810, 0xE89A, 0xE8A0, 0xE8A4, 0xE8AA, 0xE8EB, 0xE900, 0xE905, 0xEB80, 0xEB8F, 0xEBB0, 0xEBB0, 0xEC00, 0xEC05, 0xEC08, 0xECE9, 0xECF0, 0xECF0, 0xEA80, 0xEA80, 0xEA82, 0xEAA3, - 0xEAA5, 0xEAC2, 0xA800, 0xA800, 0xA820, 0xA828, 0xA840, 0xA87D, - 0XA880, 0xA88D, 0xA890, 0xA8A3, 0xA8D0, 0xA8D8, 0xA8E0, 0xA8F5, - 0xAC60, 0xAC60, ~0, + 0xEAA5, 0xEAC2, ~0, +}; + +/* GPMU registers, only valid on parts with a GPMU (a530/a540) */ +static const u32 a5xx_gpmu_registers[] = { + 0xA800, 0xA800, 0xA820, 0xA828, 0xA840, 0xA87D, 0xA880, 0xA88D, + 0xA890, 0xA8A3, 0xA8D0, 0xA8D8, 0xA8E0, 0xA8F5, 0xAC60, 0xAC60, + ~0, }; static void a5xx_dump(struct msm_gpu *gpu) @@ -1451,6 +1456,7 @@ struct a5xx_crashdumper { struct a5xx_gpu_state { struct msm_gpu_state base; u32 *hlsqregs; + u32 *gpmuregs; }; static int a5xx_crashdumper_init(struct msm_gpu *gpu, @@ -1568,8 +1574,30 @@ static void a5xx_gpu_state_get_hlsq_regs(struct msm_gpu *gpu, msm_gem_kernel_put(dumper.bo, gpu->vm); } +static void a5xx_gpu_state_get_gpmu_regs(struct msm_gpu *gpu, + struct a5xx_gpu_state *a5xx_state) +{ + u32 count = 0, pos = 0; + int i; + + for (i = 0; a5xx_gpmu_registers[i] != ~0; i += 2) + count += a5xx_gpmu_registers[i + 1] - a5xx_gpmu_registers[i] + 1; + + a5xx_state->gpmuregs = kcalloc(count, sizeof(u32), GFP_KERNEL); + if (!a5xx_state->gpmuregs) + return; + + for (i = 0; a5xx_gpmu_registers[i] != ~0; i += 2) { + u32 addr; + + for (addr = a5xx_gpmu_registers[i]; addr <= a5xx_gpmu_registers[i + 1]; addr++) + a5xx_state->gpmuregs[pos++] = gpu_read(gpu, addr); + } +} + static struct msm_gpu_state *a5xx_gpu_state_get(struct msm_gpu *gpu) { + struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu); struct a5xx_gpu_state *a5xx_state = kzalloc(sizeof(*a5xx_state), GFP_KERNEL); bool stalled = !!(gpu_read(gpu, REG_A5XX_RBBM_STATUS3) & BIT(24)); @@ -1585,6 +1613,9 @@ static struct msm_gpu_state *a5xx_gpu_state_get(struct msm_gpu *gpu) a5xx_state->base.rbbm_status = gpu_read(gpu, REG_A5XX_RBBM_STATUS); + if (adreno_is_a530(adreno_gpu) || adreno_is_a540(adreno_gpu)) + a5xx_gpu_state_get_gpmu_regs(gpu, a5xx_state); + /* * Get the HLSQ regs with the help of the crashdumper, but only if * we are not stalled in an iommu fault (in which case the crashdumper @@ -1606,6 +1637,7 @@ static void a5xx_gpu_state_destroy(struct kref *kref) struct a5xx_gpu_state, base); kfree(a5xx_state->hlsqregs); + kfree(a5xx_state->gpmuregs); adreno_gpu_state_destroy(state); kfree(a5xx_state); @@ -1634,6 +1666,17 @@ static void a5xx_show(struct msm_gpu *gpu, struct msm_gpu_state *state, adreno_show(gpu, state, p); + if (a5xx_state->gpmuregs) { + u32 o, pos = 0; + + drm_printf(p, "registers-gpmu:\n"); + + for (i = 0; a5xx_gpmu_registers[i] != ~0; i += 2) + for (o = a5xx_gpmu_registers[i]; o <= a5xx_gpmu_registers[i + 1]; o++) + drm_printf(p, " - { offset: 0x%04x, value: 0x%08x }\n", + o << 2, a5xx_state->gpmuregs[pos++]); + } + /* Dump the additional a5xx HLSQ registers */ if (!a5xx_state->hlsqregs) return; diff --git a/drivers/gpu/drm/nouveau/nouveau_drm.c b/drivers/gpu/drm/nouveau/nouveau_drm.c index d05da2db94a4..d4fe0e4f0798 100644 --- a/drivers/gpu/drm/nouveau/nouveau_drm.c +++ b/drivers/gpu/drm/nouveau/nouveau_drm.c @@ -336,6 +336,7 @@ static void nouveau_accel_ce_init(struct nouveau_drm *drm) { struct nvif_device *device = &drm->client.device; + bool priv; u64 runm; int ret = 0; @@ -348,7 +349,11 @@ nouveau_accel_ce_init(struct nouveau_drm *drm) return; } - ret = nouveau_channel_new(&drm->client, true, runm, NvDmaFB, NvDmaTT, &drm->cechan); + /* priv copy engine only works on kepler and newer. */ + priv = device->info.family >= NV_DEVICE_INFO_V0_KEPLER; + + ret = nouveau_channel_new(&drm->client, priv, runm, NvDmaFB, NvDmaTT, + &drm->cechan); if (ret) NV_ERROR(drm, "failed to create ce channel, %d\n", ret); } diff --git a/drivers/gpu/drm/nouveau/nvkm/engine/fifo/gk104.c b/drivers/gpu/drm/nouveau/nvkm/engine/fifo/gk104.c index 5655eda52a7b..912eb6c3a13d 100644 --- a/drivers/gpu/drm/nouveau/nvkm/engine/fifo/gk104.c +++ b/drivers/gpu/drm/nouveau/nvkm/engine/fifo/gk104.c @@ -180,6 +180,19 @@ gk104_ectx_ctor(struct nvkm_engn *engn, struct nvkm_vctx *vctx) struct gf100_vmm_map_v0 args = { .priv = 1 }; int ret; + /* The video falcons access their context with non-privileged + * requests, and fault with PRIV_VIOLATION on a privileged mapping. + */ + switch (engn->engine->subdev.type) { + case NVKM_ENGINE_MSVLD: + case NVKM_ENGINE_MSPDEC: + case NVKM_ENGINE_MSPPP: + args.priv = 0; + break; + default: + break; + } + ret = nvkm_vmm_get(vctx->vmm, 12, vctx->inst->size, &vctx->vma); if (ret) return ret; diff --git a/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c b/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c index 186e09ea0cb1..5368e705e7fd 100644 --- a/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c +++ b/drivers/gpu/drm/nouveau/nvkm/subdev/devinit/gf100.c @@ -27,7 +27,6 @@ #include #include #include -#include int gf100_devinit_pll_set(struct nvkm_devinit *init, u32 type, u32 freq) @@ -100,25 +99,6 @@ gf100_devinit_preinit(struct nvkm_devinit *base) * can use it as a reliable way to know whether we should run devinit. */ base->post = ((nvkm_rd32(device, 0x2240c) & BIT(1)) == 0); - - /* - * However some VBIOS init sequences miss this bit. So fall back to - * the nv50 method of checking if the bit is not set. Running the - * VBIOS multiple times may have detrimental effects. - */ - if (base->post) { - u64 disable = nvkm_devinit_disable(base); - /* magic to detect whether or not x86 vbios code has - * executed the devinit scripts to initialise the - * board. only works if there's a display engine. - */ - if (!(disable & (1ULL << NVKM_ENGINE_DISP))) { - if (nvkm_rdvgac(device, 0, 0x00) || - nvkm_rdvgac(device, 0, 0x1a)) { - base->post = false; - } - } - } } static const struct nvkm_devinit_func diff --git a/drivers/gpu/drm/panel/panel-visionox-r66451.c b/drivers/gpu/drm/panel/panel-visionox-r66451.c index 690cccedd438..d2cbc60af117 100644 --- a/drivers/gpu/drm/panel/panel-visionox-r66451.c +++ b/drivers/gpu/drm/panel/panel-visionox-r66451.c @@ -36,7 +36,7 @@ static void visionox_r66451_reset(struct visionox_r66451 *ctx) gpiod_set_value_cansleep(ctx->reset_gpio, 1); usleep_range(10000, 10100); gpiod_set_value_cansleep(ctx->reset_gpio, 0); - usleep_range(10000, 10100); + usleep_range(20000, 21000); } static int visionox_r66451_on(struct visionox_r66451 *ctx) @@ -227,7 +227,7 @@ static int visionox_r66451_bl_update_status(struct backlight_device *bl) struct mipi_dsi_device *dsi = bl_get_data(bl); u16 brightness = backlight_get_brightness(bl); - return mipi_dsi_dcs_set_display_brightness(dsi, brightness); + return mipi_dsi_dcs_set_display_brightness_large(dsi, brightness); } static const struct backlight_ops visionox_r66451_bl_ops = { diff --git a/drivers/gpu/drm/panfrost/panfrost_drv.c b/drivers/gpu/drm/panfrost/panfrost_drv.c index a31c5395de18..2d49edaa9467 100644 --- a/drivers/gpu/drm/panfrost/panfrost_drv.c +++ b/drivers/gpu/drm/panfrost/panfrost_drv.c @@ -761,6 +761,11 @@ static int panfrost_probe(struct platform_device *pdev) goto err_out0; } + /* The reason we must manually set the PM status and usage counter is + * we have just powered the device up but did not go through the PM + * runtime resume callback, so we need to update these ourselves. + */ + pm_runtime_get_noresume(pfdev->dev); pm_runtime_set_active(pfdev->dev); pm_runtime_mark_last_busy(pfdev->dev); pm_runtime_enable(pfdev->dev); @@ -779,14 +784,18 @@ static int panfrost_probe(struct platform_device *pdev) if (err) goto err_out2; + pm_runtime_put_autosuspend(pfdev->dev); + return 0; err_out2: drm_dev_unregister(ddev); err_out1: + pm_runtime_dont_use_autosuspend(pfdev->dev); pm_runtime_disable(pfdev->dev); panfrost_device_fini(pfdev); pm_runtime_set_suspended(pfdev->dev); + pm_runtime_put_noidle(pfdev->dev); err_out0: drm_dev_put(ddev); return err; @@ -801,9 +810,11 @@ static void panfrost_remove(struct platform_device *pdev) panfrost_gem_shrinker_cleanup(ddev); pm_runtime_get_sync(pfdev->dev); + pm_runtime_dont_use_autosuspend(pfdev->dev); pm_runtime_disable(pfdev->dev); panfrost_device_fini(pfdev); pm_runtime_set_suspended(pfdev->dev); + pm_runtime_put_noidle(pfdev->dev); drm_dev_put(ddev); } diff --git a/drivers/gpu/drm/panthor/panthor_gpu.c b/drivers/gpu/drm/panthor/panthor_gpu.c index 7f2dc65386fd..6be62672a3be 100644 --- a/drivers/gpu/drm/panthor/panthor_gpu.c +++ b/drivers/gpu/drm/panthor/panthor_gpu.c @@ -259,34 +259,30 @@ int panthor_gpu_l2_power_on(struct panthor_device *ptdev) int panthor_gpu_flush_caches(struct panthor_device *ptdev, u32 l2, u32 lsc, u32 other) { - unsigned long flags; int ret = 0; /* Serialize cache flush operations. */ guard(mutex)(&ptdev->gpu->cache_flush_lock); - spin_lock_irqsave(&ptdev->gpu->reqs_lock, flags); - if (!(ptdev->gpu->pending_reqs & GPU_IRQ_CLEAN_CACHES_COMPLETED)) { - ptdev->gpu->pending_reqs |= GPU_IRQ_CLEAN_CACHES_COMPLETED; - gpu_write(ptdev, GPU_CMD, GPU_FLUSH_CACHES(l2, lsc, other)); - } else { - ret = -EIO; + scoped_guard(spinlock, &ptdev->gpu->reqs_lock) { + if (!(ptdev->gpu->pending_reqs & GPU_IRQ_CLEAN_CACHES_COMPLETED)) { + ptdev->gpu->pending_reqs |= GPU_IRQ_CLEAN_CACHES_COMPLETED; + gpu_write(ptdev, GPU_CMD, GPU_FLUSH_CACHES(l2, lsc, other)); + } else { + return -EIO; + } } - spin_unlock_irqrestore(&ptdev->gpu->reqs_lock, flags); - - if (ret) - return ret; if (!wait_event_timeout(ptdev->gpu->reqs_acked, !(ptdev->gpu->pending_reqs & GPU_IRQ_CLEAN_CACHES_COMPLETED), msecs_to_jiffies(100))) { - spin_lock_irqsave(&ptdev->gpu->reqs_lock, flags); - if ((ptdev->gpu->pending_reqs & GPU_IRQ_CLEAN_CACHES_COMPLETED) != 0 && - !(gpu_read(ptdev, GPU_INT_RAWSTAT) & GPU_IRQ_CLEAN_CACHES_COMPLETED)) - ret = -ETIMEDOUT; - else - ptdev->gpu->pending_reqs &= ~GPU_IRQ_CLEAN_CACHES_COMPLETED; - spin_unlock_irqrestore(&ptdev->gpu->reqs_lock, flags); + scoped_guard(spinlock, &ptdev->gpu->reqs_lock) { + if ((ptdev->gpu->pending_reqs & GPU_IRQ_CLEAN_CACHES_COMPLETED) != 0 && + !(gpu_read(ptdev, GPU_INT_RAWSTAT) & GPU_IRQ_CLEAN_CACHES_COMPLETED)) + ret = -ETIMEDOUT; + else + ptdev->gpu->pending_reqs &= ~GPU_IRQ_CLEAN_CACHES_COMPLETED; + } } if (ret) { @@ -306,27 +302,26 @@ int panthor_gpu_flush_caches(struct panthor_device *ptdev, int panthor_gpu_soft_reset(struct panthor_device *ptdev) { bool timedout = false; - unsigned long flags; - spin_lock_irqsave(&ptdev->gpu->reqs_lock, flags); - if (!drm_WARN_ON(&ptdev->base, - ptdev->gpu->pending_reqs & GPU_IRQ_RESET_COMPLETED)) { - ptdev->gpu->pending_reqs |= GPU_IRQ_RESET_COMPLETED; - gpu_write(ptdev, GPU_INT_CLEAR, GPU_IRQ_RESET_COMPLETED); - gpu_write(ptdev, GPU_CMD, GPU_SOFT_RESET); + scoped_guard(spinlock, &ptdev->gpu->reqs_lock) { + if (!drm_WARN_ON(&ptdev->base, + ptdev->gpu->pending_reqs & GPU_IRQ_RESET_COMPLETED)) { + ptdev->gpu->pending_reqs |= GPU_IRQ_RESET_COMPLETED; + gpu_write(ptdev, GPU_INT_CLEAR, GPU_IRQ_RESET_COMPLETED); + gpu_write(ptdev, GPU_CMD, GPU_SOFT_RESET); + } } - spin_unlock_irqrestore(&ptdev->gpu->reqs_lock, flags); if (!wait_event_timeout(ptdev->gpu->reqs_acked, !(ptdev->gpu->pending_reqs & GPU_IRQ_RESET_COMPLETED), msecs_to_jiffies(100))) { - spin_lock_irqsave(&ptdev->gpu->reqs_lock, flags); - if ((ptdev->gpu->pending_reqs & GPU_IRQ_RESET_COMPLETED) != 0 && - !(gpu_read(ptdev, GPU_INT_RAWSTAT) & GPU_IRQ_RESET_COMPLETED)) - timedout = true; - else - ptdev->gpu->pending_reqs &= ~GPU_IRQ_RESET_COMPLETED; - spin_unlock_irqrestore(&ptdev->gpu->reqs_lock, flags); + scoped_guard(spinlock, &ptdev->gpu->reqs_lock) { + if ((ptdev->gpu->pending_reqs & GPU_IRQ_RESET_COMPLETED) != 0 && + !(gpu_read(ptdev, GPU_INT_RAWSTAT) & GPU_IRQ_RESET_COMPLETED)) + timedout = true; + else + ptdev->gpu->pending_reqs &= ~GPU_IRQ_RESET_COMPLETED; + } } if (timedout) { diff --git a/drivers/gpu/drm/xe/Kconfig b/drivers/gpu/drm/xe/Kconfig index c34be1be155b..d1f3981f0c19 100644 --- a/drivers/gpu/drm/xe/Kconfig +++ b/drivers/gpu/drm/xe/Kconfig @@ -11,6 +11,7 @@ config DRM_XE # the shmem_readpage() which depends upon tmpfs select SHMEM select TMPFS + select CONFIGFS_FS select DRM_BUDDY select DRM_CLIENT_SELECTION select DRM_KMS_HELPER diff --git a/drivers/gpu/drm/xe/Makefile b/drivers/gpu/drm/xe/Makefile index c5fc8cc71149..57346b1085c7 100644 --- a/drivers/gpu/drm/xe/Makefile +++ b/drivers/gpu/drm/xe/Makefile @@ -74,6 +74,7 @@ xe-y += xe_bb.o \ xe_guc_klv_helpers.o \ xe_guc_log.o \ xe_guc_pc.o \ + xe_guc_rc.o \ xe_guc_submit.o \ xe_guc_tlb_inval.o \ xe_heci_gsc.o \ diff --git a/drivers/gpu/drm/xe/regs/xe_lrc_layout.h b/drivers/gpu/drm/xe/regs/xe_lrc_layout.h index b5eff383902c..1b101edb838b 100644 --- a/drivers/gpu/drm/xe/regs/xe_lrc_layout.h +++ b/drivers/gpu/drm/xe/regs/xe_lrc_layout.h @@ -40,4 +40,7 @@ #define INDIRECT_CTX_RING_START_UDW (0x08 + 1) #define INDIRECT_CTX_RING_CTL (0x0a + 1) +#define CTX_INDIRECT_CTX_OFFSET_MASK REG_GENMASK(15, 6) +#define CTX_INDIRECT_CTX_OFFSET_DEFAULT REG_FIELD_PREP(CTX_INDIRECT_CTX_OFFSET_MASK, 0xd) + #endif diff --git a/drivers/gpu/drm/xe/xe_configfs.h b/drivers/gpu/drm/xe/xe_configfs.h index 08cce375ae0f..11970dfcc4a8 100644 --- a/drivers/gpu/drm/xe/xe_configfs.h +++ b/drivers/gpu/drm/xe/xe_configfs.h @@ -12,7 +12,6 @@ struct pci_dev; -#if IS_ENABLED(CONFIG_CONFIGFS_FS) int xe_configfs_init(void); void xe_configfs_exit(void); void xe_configfs_check_device(struct pci_dev *pdev); @@ -25,19 +24,5 @@ u32 xe_configfs_get_ctx_restore_mid_bb(struct pci_dev *pdev, u32 xe_configfs_get_ctx_restore_post_bb(struct pci_dev *pdev, enum xe_engine_class class, const u32 **cs); -#else -static inline int xe_configfs_init(void) { return 0; } -static inline void xe_configfs_exit(void) { } -static inline void xe_configfs_check_device(struct pci_dev *pdev) { } -static inline bool xe_configfs_get_survivability_mode(struct pci_dev *pdev) { return false; } -static inline u64 xe_configfs_get_engines_allowed(struct pci_dev *pdev) { return U64_MAX; } -static inline bool xe_configfs_get_psmi_enabled(struct pci_dev *pdev) { return false; } -static inline u32 xe_configfs_get_ctx_restore_mid_bb(struct pci_dev *pdev, - enum xe_engine_class class, - const u32 **cs) { return 0; } -static inline u32 xe_configfs_get_ctx_restore_post_bb(struct pci_dev *pdev, - enum xe_engine_class class, - const u32 **cs) { return 0; } -#endif #endif diff --git a/drivers/gpu/drm/xe/xe_force_wake.c b/drivers/gpu/drm/xe/xe_force_wake.c index c59a9b330697..76e054f314ee 100644 --- a/drivers/gpu/drm/xe/xe_force_wake.c +++ b/drivers/gpu/drm/xe/xe_force_wake.c @@ -166,6 +166,13 @@ static int domain_sleep_wait(struct xe_gt *gt, * xe_force_wake_ref_has_domain() function. Caller must call * xe_force_wake_put() function to decrease incremented refcounts. * + * When possible, scope-based forcewake (through CLASS(xe_force_wake, ...) or + * xe_with_force_wake()) should be used instead of direct calls to this + * function. Direct usage of get/put should only be used when the function + * has goto-based flows that can interfere with scope-based cleanup, or when + * the lifetime of the forcewake reference does not match a specific scope + * (e.g., forcewake obtained in one function and released in a different one). + * * Return: opaque reference to woken domains or zero if none of requested * domains were awake. */ diff --git a/drivers/gpu/drm/xe/xe_force_wake.h b/drivers/gpu/drm/xe/xe_force_wake.h index 0e3e84bfa51c..1e2198f6a007 100644 --- a/drivers/gpu/drm/xe/xe_force_wake.h +++ b/drivers/gpu/drm/xe/xe_force_wake.h @@ -61,4 +61,44 @@ xe_force_wake_ref_has_domain(unsigned int fw_ref, enum xe_force_wake_domains dom return fw_ref & domain; } +struct xe_force_wake_ref { + struct xe_force_wake *fw; + unsigned int domains; +}; + +static struct xe_force_wake_ref +xe_force_wake_constructor(struct xe_force_wake *fw, unsigned int domains) +{ + struct xe_force_wake_ref fw_ref = { .fw = fw }; + + fw_ref.domains = xe_force_wake_get(fw, domains); + + return fw_ref; +} + +DEFINE_CLASS(xe_force_wake, struct xe_force_wake_ref, + xe_force_wake_put(_T.fw, _T.domains), + xe_force_wake_constructor(fw, domains), + struct xe_force_wake *fw, unsigned int domains); + +/* + * Scoped helper for the forcewake class, using the same trick as scoped_guard() + * to bind the lifetime to the next statement/block. + */ +#define __xe_with_force_wake(ref, fw, domains, done) \ + for (CLASS(xe_force_wake, ref)(fw, domains), *(done) = NULL; \ + !(done); (done) = (void *)1) + +#define xe_with_force_wake(ref, fw, domains) \ + __xe_with_force_wake(ref, fw, domains, __UNIQUE_ID(done)) + +/* + * Used when xe_force_wake_constructor() has already been called by another + * function and the current function is responsible for releasing the forcewake + * reference in all possible cases and error paths. + */ +DEFINE_CLASS(xe_force_wake_release_only, struct xe_force_wake_ref, + if (_T.fw) xe_force_wake_put(_T.fw, _T.domains), fw_ref, + struct xe_force_wake_ref fw_ref); + #endif diff --git a/drivers/gpu/drm/xe/xe_gt.c b/drivers/gpu/drm/xe/xe_gt.c index 109933529847..f0d7b2290010 100644 --- a/drivers/gpu/drm/xe/xe_gt.c +++ b/drivers/gpu/drm/xe/xe_gt.c @@ -40,6 +40,7 @@ #include "xe_gt_topology.h" #include "xe_guc_exec_queue_types.h" #include "xe_guc_pc.h" +#include "xe_guc_rc.h" #include "xe_guc_submit.h" #include "xe_hw_fence.h" #include "xe_hw_engine_class_sysfs.h" @@ -889,7 +890,7 @@ static int gt_reset(struct xe_gt *gt) if (IS_SRIOV_PF(gt_to_xe(gt))) xe_gt_sriov_pf_stop_prepare(gt); - xe_uc_gucrc_disable(>->uc); + xe_guc_rc_disable(>->uc.guc); xe_uc_stop_prepare(>->uc); xe_gt_pagefault_reset(gt); diff --git a/drivers/gpu/drm/xe/xe_guc.c b/drivers/gpu/drm/xe/xe_guc.c index ae0c88da422b..1092af807d3e 100644 --- a/drivers/gpu/drm/xe/xe_guc.c +++ b/drivers/gpu/drm/xe/xe_guc.c @@ -33,6 +33,7 @@ #include "xe_guc_klv_helpers.h" #include "xe_guc_log.h" #include "xe_guc_pc.h" +#include "xe_guc_rc.h" #include "xe_guc_relay.h" #include "xe_guc_submit.h" #include "xe_memirq.h" @@ -204,9 +205,6 @@ static u32 guc_ctl_wa_flags(struct xe_guc *guc) !xe_hw_engine_mask_per_class(gt, XE_ENGINE_CLASS_RENDER)) flags |= GUC_WA_RCS_REGS_IN_CCS_REGS_LIST; - if (XE_GT_WA(gt, 1509372804)) - flags |= GUC_WA_RENDER_RST_RC6_EXIT; - if (XE_GT_WA(gt, 14018913170)) flags |= GUC_WA_ENABLE_TSC_CHECK_ON_RC6; @@ -852,6 +850,10 @@ int xe_guc_init_post_hwconfig(struct xe_guc *guc) if (ret) return ret; + ret = xe_guc_rc_init(guc); + if (ret) + return ret; + ret = xe_guc_engine_activity_init(guc); if (ret) return ret; diff --git a/drivers/gpu/drm/xe/xe_guc_pc.c b/drivers/gpu/drm/xe/xe_guc_pc.c index a3e9796e6430..da2661e46f12 100644 --- a/drivers/gpu/drm/xe/xe_guc_pc.c +++ b/drivers/gpu/drm/xe/xe_guc_pc.c @@ -90,6 +90,17 @@ * Render-C states is also a GuC PC feature that is now enabled in Xe for * all platforms. * + * Implementation details: + * ----------------------- + * The implementation for GuC Power Management features is split as follows: + * + * xe_guc_rc: Logic for handling GuC RC + * xe_gt_idle: Host side logic for RC6 and Coarse Power gating (CPG) + * xe_guc_pc: Logic for all other SLPC related features + * + * There is some cross interaction between these where host C6 will need to be + * enabled when we plan to skip GuC RC. Also, the GuC RC mode is currently + * overridden through 0x3003 which is an SLPC H2G call. */ static struct xe_guc *pc_to_guc(struct xe_guc_pc *pc) @@ -270,20 +281,35 @@ static int pc_action_unset_param(struct xe_guc_pc *pc, u8 id) return ret; } -static int pc_action_setup_gucrc(struct xe_guc_pc *pc, u32 mode) +/** + * xe_guc_pc_action_set_param() - Set value of SLPC param + * @pc: Xe_GuC_PC instance + * @id: Param id + * @value: Value to set + * + * This function can be used to set any SLPC param. + * + * Return: 0 on Success + */ +int xe_guc_pc_action_set_param(struct xe_guc_pc *pc, u8 id, u32 value) { - struct xe_guc_ct *ct = pc_to_ct(pc); - u32 action[] = { - GUC_ACTION_HOST2GUC_SETUP_PC_GUCRC, - mode, - }; - int ret; + xe_device_assert_mem_access(pc_to_xe(pc)); + return pc_action_set_param(pc, id, value); +} - ret = xe_guc_ct_send(ct, action, ARRAY_SIZE(action), 0, 0); - if (ret && !(xe_device_wedged(pc_to_xe(pc)) && ret == -ECANCELED)) - xe_gt_err(pc_to_gt(pc), "GuC RC enable mode=%u failed: %pe\n", - mode, ERR_PTR(ret)); - return ret; +/** + * xe_guc_pc_action_unset_param() - Revert to default value + * @pc: Xe_GuC_PC instance + * @id: Param id + * + * This function can be used revert any SLPC param to its default value. + * + * Return: 0 on Success + */ +int xe_guc_pc_action_unset_param(struct xe_guc_pc *pc, u8 id) +{ + xe_device_assert_mem_access(pc_to_xe(pc)); + return pc_action_unset_param(pc, id); } static u32 decode_freq(u32 raw) @@ -348,7 +374,7 @@ static int pc_set_min_freq(struct xe_guc_pc *pc, u32 freq) * Our goal is to have the admin choices respected. */ pc_action_set_param(pc, SLPC_PARAM_IGNORE_EFFICIENT_FREQUENCY, - freq < pc->rpe_freq); + freq < xe_guc_pc_get_rpe_freq(pc)); return pc_action_set_param(pc, SLPC_PARAM_GLOBAL_MIN_GT_UNSLICE_FREQ_MHZ, @@ -393,7 +419,7 @@ static void mtl_update_rpa_value(struct xe_guc_pc *pc) pc->rpa_freq = decode_freq(REG_FIELD_GET(MTL_RPA_MASK, reg)); } -static void mtl_update_rpe_value(struct xe_guc_pc *pc) +static u32 mtl_get_rpe_freq(struct xe_guc_pc *pc) { struct xe_gt *gt = pc_to_gt(pc); u32 reg; @@ -403,7 +429,7 @@ static void mtl_update_rpe_value(struct xe_guc_pc *pc) else reg = xe_mmio_read32(>->mmio, MTL_GT_RPE_FREQUENCY); - pc->rpe_freq = decode_freq(REG_FIELD_GET(MTL_RPE_MASK, reg)); + return decode_freq(REG_FIELD_GET(MTL_RPE_MASK, reg)); } static void tgl_update_rpa_value(struct xe_guc_pc *pc) @@ -426,24 +452,29 @@ static void tgl_update_rpa_value(struct xe_guc_pc *pc) } } -static void tgl_update_rpe_value(struct xe_guc_pc *pc) +static u32 pvc_get_rpe_freq(struct xe_guc_pc *pc) { struct xe_gt *gt = pc_to_gt(pc); - struct xe_device *xe = gt_to_xe(gt); u32 reg; /* * For PVC we still need to use fused RP1 as the approximation for RPe - * For other platforms than PVC we get the resolved RPe directly from + */ + reg = xe_mmio_read32(>->mmio, PVC_RP_STATE_CAP); + return REG_FIELD_GET(RP1_MASK, reg) * GT_FREQUENCY_MULTIPLIER; +} + +static u32 tgl_get_rpe_freq(struct xe_guc_pc *pc) +{ + struct xe_gt *gt = pc_to_gt(pc); + u32 reg; + + /* + * For other platforms than PVC, we get the resolved RPe directly from * PCODE at a different register */ - if (xe->info.platform == XE_PVC) { - reg = xe_mmio_read32(>->mmio, PVC_RP_STATE_CAP); - pc->rpe_freq = REG_FIELD_GET(RP1_MASK, reg) * GT_FREQUENCY_MULTIPLIER; - } else { - reg = xe_mmio_read32(>->mmio, FREQ_INFO_REC); - pc->rpe_freq = REG_FIELD_GET(RPE_MASK, reg) * GT_FREQUENCY_MULTIPLIER; - } + reg = xe_mmio_read32(>->mmio, FREQ_INFO_REC); + return REG_FIELD_GET(RPE_MASK, reg) * GT_FREQUENCY_MULTIPLIER; } static void pc_update_rp_values(struct xe_guc_pc *pc) @@ -451,20 +482,10 @@ static void pc_update_rp_values(struct xe_guc_pc *pc) struct xe_gt *gt = pc_to_gt(pc); struct xe_device *xe = gt_to_xe(gt); - if (GRAPHICS_VERx100(xe) >= 1270) { + if (GRAPHICS_VERx100(xe) >= 1270) mtl_update_rpa_value(pc); - mtl_update_rpe_value(pc); - } else { + else tgl_update_rpa_value(pc); - tgl_update_rpe_value(pc); - } - - /* - * RPe is decided at runtime by PCODE. In the rare case where that's - * smaller than the fused min, we will trust the PCODE and use that - * as our minimum one. - */ - pc->rpn_freq = min(pc->rpn_freq, pc->rpe_freq); } /** @@ -528,21 +549,17 @@ u32 xe_guc_pc_get_cur_freq_fw(struct xe_guc_pc *pc) int xe_guc_pc_get_cur_freq(struct xe_guc_pc *pc, u32 *freq) { struct xe_gt *gt = pc_to_gt(pc); - unsigned int fw_ref; /* * GuC SLPC plays with cur freq request when GuCRC is enabled * Block RC6 for a more reliable read. */ - fw_ref = xe_force_wake_get(gt_to_fw(gt), XE_FW_GT); - if (!xe_force_wake_ref_has_domain(fw_ref, XE_FW_GT)) { - xe_force_wake_put(gt_to_fw(gt), fw_ref); + CLASS(xe_force_wake, fw_ref)(gt_to_fw(gt), XE_FW_GT); + if (!xe_force_wake_ref_has_domain(fw_ref.domains, XE_FW_GT)) return -ETIMEDOUT; - } *freq = get_cur_freq(gt); - xe_force_wake_put(gt_to_fw(gt), fw_ref); return 0; } @@ -578,9 +595,17 @@ u32 xe_guc_pc_get_rpa_freq(struct xe_guc_pc *pc) */ u32 xe_guc_pc_get_rpe_freq(struct xe_guc_pc *pc) { - pc_update_rp_values(pc); + struct xe_device *xe = pc_to_xe(pc); + u32 freq; - return pc->rpe_freq; + if (GRAPHICS_VERx100(xe) == 1260) + freq = pvc_get_rpe_freq(pc); + else if (GRAPHICS_VERx100(xe) >= 1270) + freq = mtl_get_rpe_freq(pc); + else + freq = tgl_get_rpe_freq(pc); + + return freq; } /** @@ -1039,7 +1064,7 @@ static int pc_set_mert_freq_cap(struct xe_guc_pc *pc) /* * Ensure min and max are bound by MERT_FREQ_CAP until driver loads. */ - ret = pc_set_min_freq(pc, min(pc->rpe_freq, pc_max_freq_cap(pc))); + ret = pc_set_min_freq(pc, min(xe_guc_pc_get_rpe_freq(pc), pc_max_freq_cap(pc))); if (!ret) ret = pc_set_max_freq(pc, min(pc->rp0_freq, pc_max_freq_cap(pc))); @@ -1069,65 +1094,6 @@ int xe_guc_pc_restore_stashed_freq(struct xe_guc_pc *pc) return ret; } -/** - * xe_guc_pc_gucrc_disable - Disable GuC RC - * @pc: Xe_GuC_PC instance - * - * Disables GuC RC by taking control of RC6 back from GuC. - * - * Return: 0 on success, negative error code on error. - */ -int xe_guc_pc_gucrc_disable(struct xe_guc_pc *pc) -{ - struct xe_device *xe = pc_to_xe(pc); - struct xe_gt *gt = pc_to_gt(pc); - int ret = 0; - - if (xe->info.skip_guc_pc) - return 0; - - ret = pc_action_setup_gucrc(pc, GUCRC_HOST_CONTROL); - if (ret) - return ret; - - return xe_gt_idle_disable_c6(gt); -} - -/** - * xe_guc_pc_override_gucrc_mode - override GUCRC mode - * @pc: Xe_GuC_PC instance - * @mode: new value of the mode. - * - * Return: 0 on success, negative error code on error - */ -int xe_guc_pc_override_gucrc_mode(struct xe_guc_pc *pc, enum slpc_gucrc_mode mode) -{ - int ret; - - xe_pm_runtime_get(pc_to_xe(pc)); - ret = pc_action_set_param(pc, SLPC_PARAM_PWRGATE_RC_MODE, mode); - xe_pm_runtime_put(pc_to_xe(pc)); - - return ret; -} - -/** - * xe_guc_pc_unset_gucrc_mode - unset GUCRC mode override - * @pc: Xe_GuC_PC instance - * - * Return: 0 on success, negative error code on error - */ -int xe_guc_pc_unset_gucrc_mode(struct xe_guc_pc *pc) -{ - int ret; - - xe_pm_runtime_get(pc_to_xe(pc)); - ret = pc_action_unset_param(pc, SLPC_PARAM_PWRGATE_RC_MODE); - xe_pm_runtime_put(pc_to_xe(pc)); - - return ret; -} - static void pc_init_pcode_freq(struct xe_guc_pc *pc) { u32 min = DIV_ROUND_CLOSEST(pc->rpn_freq, GT_FREQUENCY_MULTIPLIER); @@ -1215,7 +1181,7 @@ int xe_guc_pc_set_power_profile(struct xe_guc_pc *pc, const char *buf) return -EINVAL; guard(mutex)(&pc->freq_lock); - xe_pm_runtime_get_noresume(pc_to_xe(pc)); + guard(xe_pm_runtime_noresume)(pc_to_xe(pc)); ret = pc_action_set_param(pc, SLPC_PARAM_POWER_PROFILE, @@ -1226,8 +1192,6 @@ int xe_guc_pc_set_power_profile(struct xe_guc_pc *pc, const char *buf) else pc->power_profile = val; - xe_pm_runtime_put(pc_to_xe(pc)); - return ret; } @@ -1270,27 +1234,19 @@ int xe_guc_pc_start(struct xe_guc_pc *pc) struct xe_device *xe = pc_to_xe(pc); struct xe_gt *gt = pc_to_gt(pc); u32 size = PAGE_ALIGN(sizeof(struct slpc_shared_data)); - unsigned int fw_ref; ktime_t earlier; int ret; xe_gt_assert(gt, xe_device_uc_enabled(xe)); - fw_ref = xe_force_wake_get(gt_to_fw(gt), XE_FW_GT); - if (!xe_force_wake_ref_has_domain(fw_ref, XE_FW_GT)) { - xe_force_wake_put(gt_to_fw(gt), fw_ref); + CLASS(xe_force_wake, fw_ref)(gt_to_fw(gt), XE_FW_GT); + if (!xe_force_wake_ref_has_domain(fw_ref.domains, XE_FW_GT)) return -ETIMEDOUT; - } if (xe->info.skip_guc_pc) { - if (xe->info.platform != XE_PVC) - xe_gt_idle_enable_c6(gt); - /* Request max possible since dynamic freq mgmt is not enabled */ pc_set_cur_freq(pc, UINT_MAX); - - ret = 0; - goto out; + return 0; } xe_map_memset(xe, &pc->bo->vmap, 0, 0, size); @@ -1299,7 +1255,7 @@ int xe_guc_pc_start(struct xe_guc_pc *pc) earlier = ktime_get(); ret = pc_action_reset(pc); if (ret) - goto out; + return ret; if (wait_for_pc_state(pc, SLPC_GLOBAL_STATE_RUNNING, SLPC_RESET_TIMEOUT_MS)) { @@ -1310,8 +1266,7 @@ int xe_guc_pc_start(struct xe_guc_pc *pc) if (wait_for_pc_state(pc, SLPC_GLOBAL_STATE_RUNNING, SLPC_RESET_EXTENDED_TIMEOUT_MS)) { xe_gt_err(gt, "GuC PC Start failed: Dynamic GT frequency control and GT sleep states are now disabled.\n"); - ret = -EIO; - goto out; + return -EIO; } xe_gt_warn(gt, "GuC PC excessive start time: %lldms", @@ -1324,21 +1279,11 @@ int xe_guc_pc_start(struct xe_guc_pc *pc) ret = pc_init_freqs(pc); if (ret) - goto out; + return ret; ret = pc_set_mert_freq_cap(pc); if (ret) - goto out; - - if (xe->info.platform == XE_PVC) { - xe_guc_pc_gucrc_disable(pc); - ret = 0; - goto out; - } - - ret = pc_action_setup_gucrc(pc, GUCRC_FIRMWARE_CONTROL); - if (ret) - goto out; + return ret; /* Enable SLPC Optimized Strategy for compute */ ret = pc_action_set_strategy(pc, SLPC_OPTIMIZED_STRATEGY_COMPUTE); @@ -1348,8 +1293,6 @@ int xe_guc_pc_start(struct xe_guc_pc *pc) if (unlikely(ret)) xe_gt_err(gt, "Failed to set SLPC power profile: %pe\n", ERR_PTR(ret)); -out: - xe_force_wake_put(gt_to_fw(gt), fw_ref); return ret; } @@ -1361,10 +1304,8 @@ int xe_guc_pc_stop(struct xe_guc_pc *pc) { struct xe_device *xe = pc_to_xe(pc); - if (xe->info.skip_guc_pc) { - xe_gt_idle_disable_c6(pc_to_gt(pc)); + if (xe->info.skip_guc_pc) return 0; - } mutex_lock(&pc->freq_lock); pc->freq_ready = false; @@ -1381,19 +1322,15 @@ static void xe_guc_pc_fini_hw(void *arg) { struct xe_guc_pc *pc = arg; struct xe_device *xe = pc_to_xe(pc); - unsigned int fw_ref; if (xe_device_wedged(xe)) return; - fw_ref = xe_force_wake_get(gt_to_fw(pc_to_gt(pc)), XE_FORCEWAKE_ALL); - xe_guc_pc_gucrc_disable(pc); + CLASS(xe_force_wake, fw_ref)(gt_to_fw(pc_to_gt(pc)), XE_FORCEWAKE_ALL); XE_WARN_ON(xe_guc_pc_stop(pc)); /* Bind requested freq to mert_freq_cap before unload */ - pc_set_cur_freq(pc, min(pc_max_freq_cap(pc), pc->rpe_freq)); - - xe_force_wake_put(gt_to_fw(pc_to_gt(pc)), fw_ref); + pc_set_cur_freq(pc, min(pc_max_freq_cap(pc), xe_guc_pc_get_rpe_freq(pc))); } /** diff --git a/drivers/gpu/drm/xe/xe_guc_pc.h b/drivers/gpu/drm/xe/xe_guc_pc.h index 0e31396f103c..0678a4e787b3 100644 --- a/drivers/gpu/drm/xe/xe_guc_pc.h +++ b/drivers/gpu/drm/xe/xe_guc_pc.h @@ -9,16 +9,14 @@ #include struct xe_guc_pc; -enum slpc_gucrc_mode; struct drm_printer; int xe_guc_pc_init(struct xe_guc_pc *pc); int xe_guc_pc_start(struct xe_guc_pc *pc); int xe_guc_pc_stop(struct xe_guc_pc *pc); -int xe_guc_pc_gucrc_disable(struct xe_guc_pc *pc); -int xe_guc_pc_override_gucrc_mode(struct xe_guc_pc *pc, enum slpc_gucrc_mode mode); -int xe_guc_pc_unset_gucrc_mode(struct xe_guc_pc *pc); void xe_guc_pc_print(struct xe_guc_pc *pc, struct drm_printer *p); +int xe_guc_pc_action_set_param(struct xe_guc_pc *pc, u8 id, u32 value); +int xe_guc_pc_action_unset_param(struct xe_guc_pc *pc, u8 id); u32 xe_guc_pc_get_act_freq(struct xe_guc_pc *pc); int xe_guc_pc_get_cur_freq(struct xe_guc_pc *pc, u32 *freq); diff --git a/drivers/gpu/drm/xe/xe_guc_pc_types.h b/drivers/gpu/drm/xe/xe_guc_pc_types.h index 5e4ea53fbee6..f27c05d81706 100644 --- a/drivers/gpu/drm/xe/xe_guc_pc_types.h +++ b/drivers/gpu/drm/xe/xe_guc_pc_types.h @@ -21,8 +21,6 @@ struct xe_guc_pc { u32 rp0_freq; /** @rpa_freq: HW RPa frequency - The Achievable one */ u32 rpa_freq; - /** @rpe_freq: HW RPe frequency - The Efficient one */ - u32 rpe_freq; /** @rpn_freq: HW RPN frequency - The Minimum one */ u32 rpn_freq; /** @user_requested_min: Stash the minimum requested freq by user */ diff --git a/drivers/gpu/drm/xe/xe_guc_rc.c b/drivers/gpu/drm/xe/xe_guc_rc.c new file mode 100644 index 000000000000..99fa127b261f --- /dev/null +++ b/drivers/gpu/drm/xe/xe_guc_rc.c @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: MIT +/* + * Copyright © 2026 Intel Corporation + */ + +#include + +#include "abi/guc_actions_slpc_abi.h" +#include "xe_device.h" +#include "xe_force_wake.h" +#include "xe_gt.h" +#include "xe_gt_idle.h" +#include "xe_gt_printk.h" +#include "xe_guc.h" +#include "xe_guc_ct.h" +#include "xe_guc_pc.h" +#include "xe_guc_rc.h" +#include "xe_pm.h" + +/** + * DOC: GuC RC (Render C-states) + * + * GuC handles the GT transition to deeper C-states in conjunction with Pcode. + * GuC RC can be enabled independently of the frequency component in SLPC, + * which is also controlled by GuC. + * + * This file will contain all H2G related logic for handling Render C-states. + * There are some calls to xe_gt_idle, where we enable host C6 when GuC RC is + * skipped. GuC RC is mostly independent of xe_guc_pc with the exception of + * functions that override the mode for which we have to rely on the SLPC H2G + * calls. + */ + +static int guc_action_setup_gucrc(struct xe_guc *guc, u32 control) +{ + u32 action[] = { + GUC_ACTION_HOST2GUC_SETUP_PC_GUCRC, + control, + }; + int ret; + + ret = xe_guc_ct_send(&guc->ct, action, ARRAY_SIZE(action), 0, 0); + if (ret && !(xe_device_wedged(guc_to_xe(guc)) && ret == -ECANCELED)) + xe_gt_err(guc_to_gt(guc), + "GuC RC setup %s(%u) failed (%pe)\n", + control == GUCRC_HOST_CONTROL ? "HOST_CONTROL" : + control == GUCRC_FIRMWARE_CONTROL ? "FIRMWARE_CONTROL" : + "UNKNOWN", control, ERR_PTR(ret)); + return ret; +} + +/** + * xe_guc_rc_disable() - Disable GuC RC + * @guc: Xe GuC instance + * + * Disables GuC RC by taking control of RC6 back from GuC. + */ +void xe_guc_rc_disable(struct xe_guc *guc) +{ + struct xe_device *xe = guc_to_xe(guc); + struct xe_gt *gt = guc_to_gt(guc); + + if (!xe->info.skip_guc_pc && xe->info.platform != XE_PVC) + if (guc_action_setup_gucrc(guc, GUCRC_HOST_CONTROL)) + return; + + xe_gt_WARN_ON(gt, xe_gt_idle_disable_c6(gt)); +} + +static void xe_guc_rc_fini_hw(void *arg) +{ + struct xe_guc *guc = arg; + struct xe_device *xe = guc_to_xe(guc); + struct xe_gt *gt = guc_to_gt(guc); + + if (xe_device_wedged(xe)) + return; + + CLASS(xe_force_wake, fw_ref)(gt_to_fw(gt), XE_FW_GT); + xe_guc_rc_disable(guc); +} + +/** + * xe_guc_rc_init() - Init GuC RC + * @guc: Xe GuC instance + * + * Add callback action for GuC RC + * + * Return: 0 on success, negative error code on error. + */ +int xe_guc_rc_init(struct xe_guc *guc) +{ + struct xe_device *xe = guc_to_xe(guc); + struct xe_gt *gt = guc_to_gt(guc); + + xe_gt_assert(gt, xe_device_uc_enabled(xe)); + + return devm_add_action_or_reset(xe->drm.dev, xe_guc_rc_fini_hw, guc); +} + +/** + * xe_guc_rc_enable() - Enable GuC RC feature if applicable + * @guc: Xe GuC instance + * + * Enables GuC RC feature. + * + * Return: 0 on success, negative error code on error. + */ +int xe_guc_rc_enable(struct xe_guc *guc) +{ + struct xe_device *xe = guc_to_xe(guc); + struct xe_gt *gt = guc_to_gt(guc); + + xe_gt_assert(gt, xe_device_uc_enabled(xe)); + + CLASS(xe_force_wake, fw_ref)(gt_to_fw(gt), XE_FW_GT); + if (!xe_force_wake_ref_has_domain(fw_ref.domains, XE_FW_GT)) + return -ETIMEDOUT; + + if (xe->info.platform == XE_PVC) { + xe_guc_rc_disable(guc); + return 0; + } + + if (xe->info.skip_guc_pc) { + xe_gt_idle_enable_c6(gt); + return 0; + } + + return guc_action_setup_gucrc(guc, GUCRC_FIRMWARE_CONTROL); +} diff --git a/drivers/gpu/drm/xe/xe_guc_rc.h b/drivers/gpu/drm/xe/xe_guc_rc.h new file mode 100644 index 000000000000..b083fc364dd4 --- /dev/null +++ b/drivers/gpu/drm/xe/xe_guc_rc.h @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Copyright © 2026 Intel Corporation + */ + +#ifndef _XE_GUC_RC_H_ +#define _XE_GUC_RC_H_ + +struct xe_guc; +enum slpc_gucrc_mode; + +int xe_guc_rc_init(struct xe_guc *guc); +int xe_guc_rc_enable(struct xe_guc *guc); +void xe_guc_rc_disable(struct xe_guc *guc); + +#endif diff --git a/drivers/gpu/drm/xe/xe_hw_engine.c b/drivers/gpu/drm/xe/xe_hw_engine.c index 2cc8fe677dec..cf5e42dddacf 100644 --- a/drivers/gpu/drm/xe/xe_hw_engine.c +++ b/drivers/gpu/drm/xe/xe_hw_engine.c @@ -276,11 +276,22 @@ static const struct engine_info engine_infos[] = { static void hw_engine_fini(void *arg) { struct xe_hw_engine *hwe = arg; + struct xe_gt *gt = hwe->gt; + + if (gt) { + struct xe_device *xe = gt_to_xe(gt); + unsigned long flags; - if (hwe->exl_port) - xe_execlist_port_destroy(hwe->exl_port); + if (hwe->exl_port) + xe_execlist_port_destroy(hwe->exl_port); - hwe->gt = NULL; + spin_lock_irqsave(&xe->irq.lock, flags); + hwe->name = NULL; + hwe->gt = NULL; + spin_unlock_irqrestore(&xe->irq.lock, flags); + } else { + hwe->name = NULL; + } } /** diff --git a/drivers/gpu/drm/xe/xe_hw_error.c b/drivers/gpu/drm/xe/xe_hw_error.c index 8c65291f36fc..0cf3c6d7b373 100644 --- a/drivers/gpu/drm/xe/xe_hw_error.c +++ b/drivers/gpu/drm/xe/xe_hw_error.c @@ -12,6 +12,7 @@ #include "xe_device.h" #include "xe_hw_error.h" #include "xe_mmio.h" +#include "xe_pm.h" #include "xe_survivability_mode.h" #define HEC_UNCORR_FW_ERR_BITS 4 @@ -55,11 +56,9 @@ static void csc_hw_error_work(struct work_struct *work) { struct xe_tile *tile = container_of(work, typeof(*tile), csc_hw_error_work); struct xe_device *xe = tile_to_xe(tile); - int ret; - ret = xe_survivability_mode_runtime_enable(xe); - if (ret) - drm_err(&xe->drm, "Failed to enable runtime survivability mode\n"); + guard(xe_pm_runtime)(xe); + xe_survivability_mode_runtime_enable(xe); } static void csc_hw_error_handler(struct xe_tile *tile, const enum hardware_error hw_err) diff --git a/drivers/gpu/drm/xe/xe_irq.c b/drivers/gpu/drm/xe/xe_irq.c index 06976cc77918..f49dfa208346 100644 --- a/drivers/gpu/drm/xe/xe_irq.c +++ b/drivers/gpu/drm/xe/xe_irq.c @@ -855,6 +855,7 @@ static irqreturn_t xe_irq_msix_default_hwe_handler(int irq, void *arg) struct xe_hw_engine *hwe; enum xe_hw_engine_id id; struct xe_tile *tile; + unsigned long flags; struct xe_gt *gt; if (!atomic_read(&xe->irq.enabled)) @@ -869,8 +870,10 @@ static irqreturn_t xe_irq_msix_default_hwe_handler(int irq, void *arg) if (gt->tile != tile) continue; + spin_lock_irqsave(&xe->irq.lock, flags); for_each_hw_engine(hwe, gt, id) xe_memirq_hwe_handler(memirq, hwe); + spin_unlock_irqrestore(&xe->irq.lock, flags); } } diff --git a/drivers/gpu/drm/xe/xe_late_bind_fw.c b/drivers/gpu/drm/xe/xe_late_bind_fw.c index 768442ca7da6..1bddfaf0fb9f 100644 --- a/drivers/gpu/drm/xe/xe_late_bind_fw.c +++ b/drivers/gpu/drm/xe/xe_late_bind_fw.c @@ -335,19 +335,19 @@ static int __xe_late_bind_fw_init(struct xe_late_bind *late_bind, u32 fw_id) if (fw->size > XE_LB_MAX_PAYLOAD_SIZE) { drm_err(&xe->drm, "Firmware %s size %zu is larger than max pay load size %u\n", lb_fw->blob_path, fw->size, XE_LB_MAX_PAYLOAD_SIZE); - release_firmware(fw); - return -ENODATA; + ret = -ENODATA; + goto release_fw; } ret = parse_lb_layout(lb_fw, fw->data, fw->size, "LTES"); if (ret) - return ret; + goto release_fw; lb_fw->payload_size = fw->size; lb_fw->payload = drmm_kzalloc(&xe->drm, lb_fw->payload_size, GFP_KERNEL); if (!lb_fw->payload) { - release_firmware(fw); - return -ENOMEM; + ret = -ENOMEM; + goto release_fw; } drm_info(&xe->drm, "Using %s firmware from %s version %u.%u.%u.%u\n", @@ -356,10 +356,11 @@ static int __xe_late_bind_fw_init(struct xe_late_bind *late_bind, u32 fw_id) lb_fw->version.hotfix, lb_fw->version.build); memcpy((void *)lb_fw->payload, fw->data, lb_fw->payload_size); - release_firmware(fw); INIT_WORK(&lb_fw->work, xe_late_bind_work); - return 0; +release_fw: + release_firmware(fw); + return ret; } static int xe_late_bind_fw_init(struct xe_late_bind *late_bind) diff --git a/drivers/gpu/drm/xe/xe_lrc.c b/drivers/gpu/drm/xe/xe_lrc.c index 53eadea8ab38..29a30e83f988 100644 --- a/drivers/gpu/drm/xe/xe_lrc.c +++ b/drivers/gpu/drm/xe/xe_lrc.c @@ -1371,15 +1371,15 @@ setup_indirect_ctx(struct xe_lrc *lrc, struct xe_hw_engine *hwe) finish_bo(&state); kfree(state.buffer); - /* - * Enable INDIRECT_CTX leaving INDIRECT_CTX_OFFSET at its default: it - * varies per engine class, but the default is good enough - */ xe_lrc_write_ctx_reg(lrc, CTX_CS_INDIRECT_CTX, (xe_bo_ggtt_addr(lrc->bo) + state.offset) | /* Size in CLs. */ (state.written * sizeof(u32) / 64)); + if (GRAPHICS_VER(lrc_to_xe(lrc)) < 20) + xe_lrc_write_ctx_reg(lrc, + CTX_CS_INDIRECT_CTX_OFFSET, + CTX_INDIRECT_CTX_OFFSET_DEFAULT); return 0; } diff --git a/drivers/gpu/drm/xe/xe_memirq.c b/drivers/gpu/drm/xe/xe_memirq.c index 49c45ec3e83c..da8a7feb56ec 100644 --- a/drivers/gpu/drm/xe/xe_memirq.c +++ b/drivers/gpu/drm/xe/xe_memirq.c @@ -473,6 +473,7 @@ void xe_memirq_handler(struct xe_memirq *memirq) struct xe_hw_engine *hwe; enum xe_hw_engine_id id; struct iosys_map map; + unsigned long flags; unsigned int gtid; struct xe_gt *gt; @@ -487,8 +488,10 @@ void xe_memirq_handler(struct xe_memirq *memirq) if (gt->tile != tile) continue; + spin_lock_irqsave(&xe->irq.lock, flags); for_each_hw_engine(hwe, gt, id) xe_memirq_hwe_handler(memirq, hwe); + spin_unlock_irqrestore(&xe->irq.lock, flags); } /* GuC and media GuC (if present) must be checked separately */ diff --git a/drivers/gpu/drm/xe/xe_oa.c b/drivers/gpu/drm/xe/xe_oa.c index b88d3d39aea6..e7861f135f55 100644 --- a/drivers/gpu/drm/xe/xe_oa.c +++ b/drivers/gpu/drm/xe/xe_oa.c @@ -29,7 +29,7 @@ #include "xe_gt.h" #include "xe_gt_mcr.h" #include "xe_gt_printk.h" -#include "xe_guc_pc.h" +#include "xe_guc_rc.h" #include "xe_macros.h" #include "xe_mmio.h" #include "xe_oa.h" @@ -875,10 +875,6 @@ static void xe_oa_stream_destroy(struct xe_oa_stream *stream) xe_force_wake_put(gt_to_fw(gt), XE_FORCEWAKE_ALL); xe_pm_runtime_put(stream->oa->xe); - /* Wa_1509372804:pvc: Unset the override of GUCRC mode to enable rc6 */ - if (stream->override_gucrc) - xe_gt_WARN_ON(gt, xe_guc_pc_unset_gucrc_mode(>->uc.guc.pc)); - xe_oa_free_configs(stream); xe_file_put(stream->xef); } @@ -1778,19 +1774,6 @@ static int xe_oa_stream_init(struct xe_oa_stream *stream, goto exit; } - /* - * GuC reset of engines causes OA to lose configuration - * state. Prevent this by overriding GUCRC mode. - */ - if (XE_GT_WA(stream->gt, 1509372804)) { - ret = xe_guc_pc_override_gucrc_mode(>->uc.guc.pc, - SLPC_GUCRC_MODE_GUCRC_NO_RC6); - if (ret) - goto err_free_configs; - - stream->override_gucrc = true; - } - /* Take runtime pm ref and forcewake to disable RC6 */ xe_pm_runtime_get(stream->oa->xe); fw_ref = xe_force_wake_get(gt_to_fw(gt), XE_FORCEWAKE_ALL); @@ -1841,9 +1824,6 @@ static int xe_oa_stream_init(struct xe_oa_stream *stream, err_fw_put: xe_force_wake_put(gt_to_fw(gt), fw_ref); xe_pm_runtime_put(stream->oa->xe); - if (stream->override_gucrc) - xe_gt_WARN_ON(gt, xe_guc_pc_unset_gucrc_mode(>->uc.guc.pc)); -err_free_configs: xe_oa_free_configs(stream); exit: xe_file_put(stream->xef); diff --git a/drivers/gpu/drm/xe/xe_oa_types.h b/drivers/gpu/drm/xe/xe_oa_types.h index 48f9520f560c..468b23d333e1 100644 --- a/drivers/gpu/drm/xe/xe_oa_types.h +++ b/drivers/gpu/drm/xe/xe_oa_types.h @@ -241,9 +241,6 @@ struct xe_oa_stream { /** @poll_period_ns: hrtimer period for checking OA buffer for available data */ u64 poll_period_ns; - /** @override_gucrc: GuC RC has been overridden for the OA stream */ - bool override_gucrc; - /** @oa_status: temporary storage for oa_status register value */ u32 oa_status; diff --git a/drivers/gpu/drm/xe/xe_pci.c b/drivers/gpu/drm/xe/xe_pci.c index 10c5d852cf2b..e907751e9e3a 100644 --- a/drivers/gpu/drm/xe/xe_pci.c +++ b/drivers/gpu/drm/xe/xe_pci.c @@ -149,6 +149,8 @@ static const struct xe_ip graphics_ips[] = { { 3000, "Xe3_LPG", &graphics_xe2 }, { 3001, "Xe3_LPG", &graphics_xe2 }, { 3003, "Xe3_LPG", &graphics_xe2 }, + { 3004, "Xe3_LPG", &graphics_xe2 }, + { 3005, "Xe3_LPG", &graphics_xe2 }, }; /* Pre-GMDID Media IPs */ @@ -1057,6 +1059,9 @@ static int xe_pci_runtime_resume(struct device *dev) struct xe_device *xe = pdev_to_xe_device(pdev); int err; + if (xe->d3cold.allowed) + d3cold_toggle(pdev, D3COLD_DISABLE); + err = pci_set_power_state(pdev, PCI_D0); if (err) return err; diff --git a/drivers/gpu/drm/xe/xe_survivability_mode.c b/drivers/gpu/drm/xe/xe_survivability_mode.c index 1662bfddd4bc..2494d743ed79 100644 --- a/drivers/gpu/drm/xe/xe_survivability_mode.c +++ b/drivers/gpu/drm/xe/xe_survivability_mode.c @@ -19,8 +19,6 @@ #include "xe_pcode_api.h" #include "xe_vsec.h" -#define MAX_SCRATCH_MMIO 8 - /** * DOC: Survivability Mode * @@ -48,19 +46,38 @@ * * Refer :ref:`xe_configfs` for more details on how to use configfs * - * Survivability mode is indicated by the below admin-only readable sysfs which provides additional - * debug information:: + * Survivability mode is indicated by the below admin-only readable sysfs entry. It + * provides information about the type of survivability mode (Boot/Runtime). + * + * .. code-block:: shell + * + * # cat /sys/bus/pci/devices//survivability_mode + * Boot + * + * + * Any additional debug information if present will be visible under the directory + * ``survivability_info``:: + * + * /sys/bus/pci/devices//survivability_info/ + * ├── aux_info0 + * ├── aux_info1 + * ├── aux_info2 + * ├── aux_info3 + * ├── aux_info4 + * ├── capability_info + * ├── fdo_mode + * ├── postcode_trace + * └── postcode_trace_overflow + * + * This directory has the following attributes * - * /sys/bus/pci/devices//survivability_mode + * - ``capability_info`` : Indicates Boot status and support for additional information * - * Capability Information: - * Provides boot status - * Postcode Information: - * Provides information about the failure - * Overflow Information - * Provides history of previous failures - * Auxiliary Information - * Certain failures may have information in addition to postcode information + * - ``postcode_trace``, ``postcode_trace_overflow`` : Each postcode is a 8bit value and + * represents a boot failure event. When a new failure event is logged by PCODE the + * existing postcodes are shifted left. These entries provide a history of 8 postcodes. + * + * - ``aux_info`` : Some failures have additional debug information * * Runtime Survivability * ===================== @@ -68,61 +85,70 @@ * Certain runtime firmware errors can cause the device to enter a wedged state * (:ref:`xe-device-wedging`) requiring a firmware flash to restore normal operation. * Runtime Survivability Mode indicates that a firmware flash is necessary to recover the device and - * is indicated by the presence of survivability mode sysfs:: + * is indicated by the presence of survivability mode sysfs. + * Survivability mode sysfs provides information about the type of survivability mode. * - * /sys/bus/pci/devices//survivability_mode + * .. code-block:: shell * - * Survivability mode sysfs provides information about the type of survivability mode. + * # cat /sys/bus/pci/devices//survivability_mode + * Runtime * * When such errors occur, userspace is notified with the drm device wedged uevent and runtime * survivability mode. User can then initiate a firmware flash using userspace tools like fwupd * to restore device to normal operation. */ -static u32 aux_history_offset(u32 reg_value) +static const char * const reg_map[] = { + [CAPABILITY_INFO] = "Capability Info", + [POSTCODE_TRACE] = "Postcode trace", + [POSTCODE_TRACE_OVERFLOW] = "Postcode trace overflow", + [AUX_INFO0] = "Auxiliary Info 0", + [AUX_INFO1] = "Auxiliary Info 1", + [AUX_INFO2] = "Auxiliary Info 2", + [AUX_INFO3] = "Auxiliary Info 3", + [AUX_INFO4] = "Auxiliary Info 4", +}; + +struct xe_survivability_attribute { + struct device_attribute attr; + u8 index; +}; + +static struct +xe_survivability_attribute *dev_attr_to_survivability_attr(struct device_attribute *attr) { - return REG_FIELD_GET(AUXINFO_HISTORY_OFFSET, reg_value); + return container_of(attr, struct xe_survivability_attribute, attr); } -static void set_survivability_info(struct xe_mmio *mmio, struct xe_survivability_info *info, - int id, char *name) +static void set_survivability_info(struct xe_mmio *mmio, u32 *info, int id) { - strscpy(info[id].name, name, sizeof(info[id].name)); - info[id].reg = PCODE_SCRATCH(id).raw; - info[id].value = xe_mmio_read32(mmio, PCODE_SCRATCH(id)); + info[id] = xe_mmio_read32(mmio, PCODE_SCRATCH(id)); } static void populate_survivability_info(struct xe_device *xe) { struct xe_survivability *survivability = &xe->survivability; - struct xe_survivability_info *info = survivability->info; + u32 *info = survivability->info; struct xe_mmio *mmio; u32 id = 0, reg_value; - char name[NAME_MAX]; - int index; mmio = xe_root_tile_mmio(xe); - set_survivability_info(mmio, info, id, "Capability Info"); - reg_value = info[id].value; + set_survivability_info(mmio, info, CAPABILITY_INFO); + reg_value = info[CAPABILITY_INFO]; if (reg_value & HISTORY_TRACKING) { - id++; - set_survivability_info(mmio, info, id, "Postcode Info"); + set_survivability_info(mmio, info, POSTCODE_TRACE); - if (reg_value & OVERFLOW_SUPPORT) { - id = REG_FIELD_GET(OVERFLOW_REG_OFFSET, reg_value); - set_survivability_info(mmio, info, id, "Overflow Info"); - } + if (reg_value & OVERFLOW_SUPPORT) + set_survivability_info(mmio, info, POSTCODE_TRACE_OVERFLOW); } + /* Traverse the linked list of aux info registers */ if (reg_value & AUXINFO_SUPPORT) { - id = REG_FIELD_GET(AUXINFO_REG_OFFSET, reg_value); - - for (index = 0; id && reg_value; index++, reg_value = info[id].value, - id = aux_history_offset(reg_value)) { - snprintf(name, NAME_MAX, "Auxiliary Info %d", index); - set_survivability_info(mmio, info, id, name); - } + for (id = REG_FIELD_GET(AUXINFO_REG_OFFSET, reg_value); + id >= AUX_INFO0 && id < MAX_SCRATCH_REG; + id = REG_FIELD_GET(AUXINFO_HISTORY_OFFSET, info[id])) + set_survivability_info(mmio, info, id); } } @@ -130,15 +156,14 @@ static void log_survivability_info(struct pci_dev *pdev) { struct xe_device *xe = pdev_to_xe_device(pdev); struct xe_survivability *survivability = &xe->survivability; - struct xe_survivability_info *info = survivability->info; + u32 *info = survivability->info; int id; dev_info(&pdev->dev, "Survivability Boot Status : Critical Failure (%d)\n", survivability->boot_status); - for (id = 0; id < MAX_SCRATCH_MMIO; id++) { - if (info[id].reg) - dev_info(&pdev->dev, "%s: 0x%x - 0x%x\n", info[id].name, - info[id].reg, info[id].value); + for (id = 0; id < MAX_SCRATCH_REG; id++) { + if (info[id]) + dev_info(&pdev->dev, "%s: 0x%x\n", reg_map[id], info[id]); } } @@ -156,25 +181,38 @@ static ssize_t survivability_mode_show(struct device *dev, struct pci_dev *pdev = to_pci_dev(dev); struct xe_device *xe = pdev_to_xe_device(pdev); struct xe_survivability *survivability = &xe->survivability; - struct xe_survivability_info *info = survivability->info; - int index = 0, count = 0; - count += sysfs_emit_at(buff, count, "Survivability mode type: %s\n", - survivability->type ? "Runtime" : "Boot"); + return sysfs_emit(buff, "%s\n", survivability->type ? "Runtime" : "Boot"); +} - if (!check_boot_failure(xe)) - return count; +static DEVICE_ATTR_ADMIN_RO(survivability_mode); - for (index = 0; index < MAX_SCRATCH_MMIO; index++) { - if (info[index].reg) - count += sysfs_emit_at(buff, count, "%s: 0x%x - 0x%x\n", info[index].name, - info[index].reg, info[index].value); - } +static ssize_t survivability_info_show(struct device *dev, + struct device_attribute *attr, char *buff) +{ + struct xe_survivability_attribute *sa = dev_attr_to_survivability_attr(attr); + struct pci_dev *pdev = to_pci_dev(dev); + struct xe_device *xe = pdev_to_xe_device(pdev); + struct xe_survivability *survivability = &xe->survivability; + u32 *info = survivability->info; - return count; + return sysfs_emit(buff, "0x%x\n", info[sa->index]); } -static DEVICE_ATTR_ADMIN_RO(survivability_mode); +#define SURVIVABILITY_ATTR_RO(name, _index) \ + struct xe_survivability_attribute attr_##name = { \ + .attr = __ATTR(name, 0400, survivability_info_show, NULL), \ + .index = _index, \ + } + +SURVIVABILITY_ATTR_RO(capability_info, CAPABILITY_INFO); +SURVIVABILITY_ATTR_RO(postcode_trace, POSTCODE_TRACE); +SURVIVABILITY_ATTR_RO(postcode_trace_overflow, POSTCODE_TRACE_OVERFLOW); +SURVIVABILITY_ATTR_RO(aux_info0, AUX_INFO0); +SURVIVABILITY_ATTR_RO(aux_info1, AUX_INFO1); +SURVIVABILITY_ATTR_RO(aux_info2, AUX_INFO2); +SURVIVABILITY_ATTR_RO(aux_info3, AUX_INFO3); +SURVIVABILITY_ATTR_RO(aux_info4, AUX_INFO4); static void xe_survivability_mode_fini(void *arg) { @@ -182,17 +220,48 @@ static void xe_survivability_mode_fini(void *arg) struct pci_dev *pdev = to_pci_dev(xe->drm.dev); struct device *dev = &pdev->dev; - sysfs_remove_file(&dev->kobj, &dev_attr_survivability_mode.attr); + device_remove_file(dev, &dev_attr_survivability_mode); +} + +static umode_t survivability_info_attrs_visible(struct kobject *kobj, struct attribute *attr, + int idx) +{ + struct xe_device *xe = kdev_to_xe_device(kobj_to_dev(kobj)); + struct xe_survivability *survivability = &xe->survivability; + u32 *info = survivability->info; + + if (info[idx]) + return 0400; + + return 0; } +/* Attributes are ordered according to enum scratch_reg */ +static struct attribute *survivability_info_attrs[] = { + &attr_capability_info.attr.attr, + &attr_postcode_trace.attr.attr, + &attr_postcode_trace_overflow.attr.attr, + &attr_aux_info0.attr.attr, + &attr_aux_info1.attr.attr, + &attr_aux_info2.attr.attr, + &attr_aux_info3.attr.attr, + &attr_aux_info4.attr.attr, + NULL, +}; + +static const struct attribute_group survivability_info_group = { + .name = "survivability_info", + .attrs = survivability_info_attrs, + .is_visible = survivability_info_attrs_visible, +}; + static int create_survivability_sysfs(struct pci_dev *pdev) { struct device *dev = &pdev->dev; struct xe_device *xe = pdev_to_xe_device(pdev); int ret; - /* create survivability mode sysfs */ - ret = sysfs_create_file(&dev->kobj, &dev_attr_survivability_mode.attr); + ret = device_create_file(dev, &dev_attr_survivability_mode); if (ret) { dev_warn(dev, "Failed to create survivability sysfs files\n"); return ret; @@ -203,6 +272,12 @@ static int create_survivability_sysfs(struct pci_dev *pdev) if (ret) return ret; + if (check_boot_failure(xe)) { + ret = devm_device_add_group(dev, &survivability_info_group); + if (ret) + return ret; + } + return 0; } @@ -239,25 +314,6 @@ static int enable_boot_survivability_mode(struct pci_dev *pdev) return ret; } -static int init_survivability_mode(struct xe_device *xe) -{ - struct xe_survivability *survivability = &xe->survivability; - struct xe_survivability_info *info; - - survivability->size = MAX_SCRATCH_MMIO; - - info = devm_kcalloc(xe->drm.dev, survivability->size, sizeof(*info), - GFP_KERNEL); - if (!info) - return -ENOMEM; - - survivability->info = info; - - populate_survivability_info(xe); - - return 0; -} - /** * xe_survivability_mode_is_boot_enabled- check if boot survivability mode is enabled * @xe: xe device instance @@ -311,27 +367,21 @@ bool xe_survivability_mode_is_requested(struct xe_device *xe) * Runtime survivability mode is enabled when certain errors cause the device to be * in non-recoverable state. The device is declared wedged with the appropriate * recovery method and survivability mode sysfs exposed to userspace - * - * Return: 0 if runtime survivability mode is enabled, negative error code otherwise. */ -int xe_survivability_mode_runtime_enable(struct xe_device *xe) +void xe_survivability_mode_runtime_enable(struct xe_device *xe) { struct xe_survivability *survivability = &xe->survivability; struct pci_dev *pdev = to_pci_dev(xe->drm.dev); - int ret; if (!IS_DGFX(xe) || IS_SRIOV_VF(xe) || xe->info.platform < XE_BATTLEMAGE) { dev_err(&pdev->dev, "Runtime Survivability Mode not supported\n"); - return -EINVAL; + return; } - ret = init_survivability_mode(xe); - if (ret) - return ret; + populate_survivability_info(xe); - ret = create_survivability_sysfs(pdev); - if (ret) - dev_err(&pdev->dev, "Failed to create survivability mode sysfs\n"); + if (create_survivability_sysfs(pdev)) + dev_err(&pdev->dev, "Failed to create survivability sysfs\n"); survivability->type = XE_SURVIVABILITY_TYPE_RUNTIME; dev_err(&pdev->dev, "Runtime Survivability mode enabled\n"); @@ -339,8 +389,6 @@ int xe_survivability_mode_runtime_enable(struct xe_device *xe) xe_device_set_wedged_method(xe, DRM_WEDGE_RECOVERY_VENDOR); xe_device_declare_wedged(xe); dev_err(&pdev->dev, "Firmware flash required, Please refer to the userspace documentation for more details!\n"); - - return 0; } /** @@ -356,14 +404,11 @@ int xe_survivability_mode_boot_enable(struct xe_device *xe) { struct xe_survivability *survivability = &xe->survivability; struct pci_dev *pdev = to_pci_dev(xe->drm.dev); - int ret; if (!xe_survivability_mode_is_requested(xe)) return 0; - ret = init_survivability_mode(xe); - if (ret) - return ret; + populate_survivability_info(xe); /* Log breadcrumbs but do not enter survivability mode for Critical boot errors */ if (survivability->boot_status == CRITICAL_FAILURE) { diff --git a/drivers/gpu/drm/xe/xe_survivability_mode.h b/drivers/gpu/drm/xe/xe_survivability_mode.h index 1cc94226aa82..cd040e4d18bb 100644 --- a/drivers/gpu/drm/xe/xe_survivability_mode.h +++ b/drivers/gpu/drm/xe/xe_survivability_mode.h @@ -11,7 +11,7 @@ struct xe_device; int xe_survivability_mode_boot_enable(struct xe_device *xe); -int xe_survivability_mode_runtime_enable(struct xe_device *xe); +void xe_survivability_mode_runtime_enable(struct xe_device *xe); bool xe_survivability_mode_is_boot_enabled(struct xe_device *xe); bool xe_survivability_mode_is_requested(struct xe_device *xe); diff --git a/drivers/gpu/drm/xe/xe_survivability_mode_types.h b/drivers/gpu/drm/xe/xe_survivability_mode_types.h index cd65a5d167c9..f31b3907d933 100644 --- a/drivers/gpu/drm/xe/xe_survivability_mode_types.h +++ b/drivers/gpu/drm/xe/xe_survivability_mode_types.h @@ -9,23 +9,29 @@ #include #include +enum scratch_reg { + CAPABILITY_INFO, + POSTCODE_TRACE, + POSTCODE_TRACE_OVERFLOW, + AUX_INFO0, + AUX_INFO1, + AUX_INFO2, + AUX_INFO3, + AUX_INFO4, + MAX_SCRATCH_REG, +}; + enum xe_survivability_type { XE_SURVIVABILITY_TYPE_BOOT, XE_SURVIVABILITY_TYPE_RUNTIME, }; -struct xe_survivability_info { - char name[NAME_MAX]; - u32 reg; - u32 value; -}; - /** * struct xe_survivability: Contains survivability mode information */ struct xe_survivability { - /** @info: struct that holds survivability info from scratch registers */ - struct xe_survivability_info *info; + /** @info: survivability debug info */ + u32 info[MAX_SCRATCH_REG]; /** @size: number of scratch registers */ u32 size; diff --git a/drivers/gpu/drm/xe/xe_tuning.c b/drivers/gpu/drm/xe/xe_tuning.c index a524170a04d0..84e99f6474e6 100644 --- a/drivers/gpu/drm/xe/xe_tuning.c +++ b/drivers/gpu/drm/xe/xe_tuning.c @@ -100,7 +100,7 @@ static const struct xe_rtp_entry_sr engine_tunings[] = { }, { XE_RTP_NAME("Tuning: Disable NULL query for Anyhit Shader"), XE_RTP_RULES(GRAPHICS_VERSION_RANGE(2000, XE_RTP_END_VERSION_UNDEFINED), - FUNC(xe_rtp_match_first_render_or_compute)), + ENGINE_CLASS(RENDER)), XE_RTP_ACTIONS(SET(RT_CTRL, DIS_NULL_QUERY)) }, }; diff --git a/drivers/gpu/drm/xe/xe_uc.c b/drivers/gpu/drm/xe/xe_uc.c index b799efc83801..367e05354c38 100644 --- a/drivers/gpu/drm/xe/xe_uc.c +++ b/drivers/gpu/drm/xe/xe_uc.c @@ -14,6 +14,7 @@ #include "xe_gt_sriov_vf.h" #include "xe_guc.h" #include "xe_guc_pc.h" +#include "xe_guc_rc.h" #include "xe_guc_engine_activity.h" #include "xe_guc_submit.h" #include "xe_huc.h" @@ -219,6 +220,10 @@ int xe_uc_load_hw(struct xe_uc *uc) if (ret) goto err_out; + ret = xe_guc_rc_enable(&uc->guc); + if (ret) + goto err_out; + xe_guc_engine_activity_enable_stats(&uc->guc); /* We don't fail the driver load if HuC fails to auth, but let's warn */ @@ -244,11 +249,6 @@ int xe_uc_reset_prepare(struct xe_uc *uc) return xe_guc_reset_prepare(&uc->guc); } -void xe_uc_gucrc_disable(struct xe_uc *uc) -{ - XE_WARN_ON(xe_guc_pc_gucrc_disable(&uc->guc.pc)); -} - void xe_uc_stop_prepare(struct xe_uc *uc) { xe_gsc_stop_prepare(&uc->gsc); diff --git a/drivers/gpu/drm/xe/xe_uc.h b/drivers/gpu/drm/xe/xe_uc.h index 21c9306098cf..df6b62ddd85e 100644 --- a/drivers/gpu/drm/xe/xe_uc.h +++ b/drivers/gpu/drm/xe/xe_uc.h @@ -12,7 +12,6 @@ int xe_uc_init_noalloc(struct xe_uc *uc); int xe_uc_init(struct xe_uc *uc); int xe_uc_init_post_hwconfig(struct xe_uc *uc); int xe_uc_load_hw(struct xe_uc *uc); -void xe_uc_gucrc_disable(struct xe_uc *uc); int xe_uc_reset_prepare(struct xe_uc *uc); void xe_uc_stop_prepare(struct xe_uc *uc); void xe_uc_stop(struct xe_uc *uc); diff --git a/drivers/gpu/drm/xe/xe_vm.c b/drivers/gpu/drm/xe/xe_vm.c index 94a62b4256b4..b6d660875879 100644 --- a/drivers/gpu/drm/xe/xe_vm.c +++ b/drivers/gpu/drm/xe/xe_vm.c @@ -258,8 +258,15 @@ int xe_vm_add_compute_exec_queue(struct xe_vm *vm, struct xe_exec_queue *q) * Check to see if a preemption on VM is in flight or userptr * invalidation, if so trigger this preempt fence to sync state with * other preempt fences on the VM. + * + * Also trigger it if eviction or rebinding is pending. BOs evicted + * before the first exec queue was added had no preempt fence to + * trigger. Suspend this queue until the rebind worker restores + * the mappings. */ - wait = __xe_vm_userptr_needs_repin(vm) || preempt_fences_waiting(vm); + wait = __xe_vm_userptr_needs_repin(vm) || preempt_fences_waiting(vm) || + !list_empty(&vm->gpuvm.evict.list) || + !list_empty(&vm->rebind_list); if (wait) dma_fence_enable_sw_signaling(pfence); diff --git a/drivers/gpu/drm/xe/xe_wa.c b/drivers/gpu/drm/xe/xe_wa.c index 51c5985830b1..52f7da9e9248 100644 --- a/drivers/gpu/drm/xe/xe_wa.c +++ b/drivers/gpu/drm/xe/xe_wa.c @@ -475,11 +475,6 @@ static const struct xe_rtp_entry_sr engine_was[] = { ENGINE_CLASS(COMPUTE)), XE_RTP_ACTIONS(SET(RING_HWSTAM(RENDER_RING_BASE), ~0)) }, - { XE_RTP_NAME("14014999345"), - XE_RTP_RULES(PLATFORM(PVC), ENGINE_CLASS(COMPUTE), - GRAPHICS_STEP(B0, C0)), - XE_RTP_ACTIONS(SET(CACHE_MODE_SS, DISABLE_ECC)) - }, /* Xe_LPG */ @@ -675,18 +670,19 @@ static const struct xe_rtp_entry_sr engine_was[] = { }, { XE_RTP_NAME("13012615864"), XE_RTP_RULES(GRAPHICS_VERSION_RANGE(3000, 3001), OR, - GRAPHICS_VERSION(3003), + GRAPHICS_VERSION_RANGE(3003, 3005), FUNC(xe_rtp_match_first_render_or_compute)), XE_RTP_ACTIONS(SET(TDL_TSL_CHICKEN, RES_CHK_SPR_DIS)) }, { XE_RTP_NAME("16023105232"), - XE_RTP_RULES(MEDIA_VERSION_RANGE(1301, 3000), OR, - GRAPHICS_VERSION_RANGE(2001, 3001)), + /* IP versions need to be in sync with the respective entry in xe_wa_oob.rules. */ + XE_RTP_RULES(MEDIA_VERSION_RANGE(1301, 3002), OR, + GRAPHICS_VERSION_RANGE(2001, 3005)), XE_RTP_ACTIONS(SET(RING_PSMI_CTL(0), RC_SEMA_IDLE_MSG_DISABLE, XE_RTP_ACTION_FLAG(ENGINE_BASE))) }, { XE_RTP_NAME("14021402888"), - XE_RTP_RULES(GRAPHICS_VERSION(3003), FUNC(xe_rtp_match_first_render_or_compute)), + XE_RTP_RULES(GRAPHICS_VERSION_RANGE(3003, 3005), FUNC(xe_rtp_match_first_render_or_compute)), XE_RTP_ACTIONS(SET(HALF_SLICE_CHICKEN7, CLEAR_OPTIMIZATION_DISABLE)) }, { XE_RTP_NAME("18041344222"), @@ -912,7 +908,7 @@ static const struct xe_rtp_entry_sr lrc_was[] = { DIS_AUTOSTRIP)) }, { XE_RTP_NAME("22021007897"), - XE_RTP_RULES(GRAPHICS_VERSION_RANGE(3000, 3003), ENGINE_CLASS(RENDER)), + XE_RTP_RULES(GRAPHICS_VERSION_RANGE(3000, 3005), ENGINE_CLASS(RENDER)), XE_RTP_ACTIONS(SET(COMMON_SLICE_CHICKEN4, SBE_PUSH_CONSTANT_BEHIND_FIX_ENABLE)) }, { XE_RTP_NAME("14024681466"), diff --git a/drivers/gpu/drm/xe/xe_wa_oob.rules b/drivers/gpu/drm/xe/xe_wa_oob.rules index 1d32fa1c3b2d..598e11ee0ed1 100644 --- a/drivers/gpu/drm/xe/xe_wa_oob.rules +++ b/drivers/gpu/drm/xe/xe_wa_oob.rules @@ -9,7 +9,6 @@ 22012727685 SUBPLATFORM(DG2, G11) 22016596838 PLATFORM(PVC) 18020744125 PLATFORM(PVC) -1509372804 PLATFORM(PVC), GRAPHICS_STEP(A0, C0) 1409600907 GRAPHICS_VERSION_RANGE(1200, 1250) 14016763929 SUBPLATFORM(DG2, G10) SUBPLATFORM(DG2, G12) @@ -31,17 +30,9 @@ MEDIA_VERSION(2000) 16022287689 GRAPHICS_VERSION(2001) GRAPHICS_VERSION(2004) -13011645652 GRAPHICS_VERSION(2004) - GRAPHICS_VERSION_RANGE(3000, 3001) - GRAPHICS_VERSION(3003) -14022293748 GRAPHICS_VERSION_RANGE(2001, 2002) - GRAPHICS_VERSION(2004) - GRAPHICS_VERSION_RANGE(3000, 3001) - GRAPHICS_VERSION(3003) -22019794406 GRAPHICS_VERSION_RANGE(2001, 2002) - GRAPHICS_VERSION(2004) - GRAPHICS_VERSION_RANGE(3000, 3001) - GRAPHICS_VERSION(3003) +13011645652 GRAPHICS_VERSION_RANGE(2004, 3005) +14022293748 GRAPHICS_VERSION_RANGE(2001, 3005) +22019794406 GRAPHICS_VERSION_RANGE(2001, 3005) 22019338487 MEDIA_VERSION(2000) GRAPHICS_VERSION(2001), FUNC(xe_rtp_match_not_sriov_vf) MEDIA_VERSION(3000), MEDIA_STEP(A0, B0), FUNC(xe_rtp_match_not_sriov_vf) @@ -59,19 +50,13 @@ 18013179988 GRAPHICS_VERSION(1255) GRAPHICS_VERSION_RANGE(1270, 1274) 1508761755 GRAPHICS_VERSION(1255) - GRAPHICS_VERSION(1260), GRAPHICS_STEP(A0, B0) -16023105232 GRAPHICS_VERSION_RANGE(2001, 3001) - MEDIA_VERSION_RANGE(1301, 3000) - MEDIA_VERSION(3002) - GRAPHICS_VERSION(3003) -16026508708 GRAPHICS_VERSION_RANGE(1200, 3001) - MEDIA_VERSION_RANGE(1300, 3000) - MEDIA_VERSION(3002) - GRAPHICS_VERSION(3003) +# IP versions need to be in sync with the respective entry in xe_wa.c. +16023105232 GRAPHICS_VERSION_RANGE(2001, 3005) + MEDIA_VERSION_RANGE(1301, 3002) +16026508708 GRAPHICS_VERSION_RANGE(1200, 3005) + MEDIA_VERSION_RANGE(1300, 3002) 14020001231 GRAPHICS_VERSION_RANGE(2001,2004), FUNC(xe_rtp_match_psmi_enabled) - MEDIA_VERSION(2000), FUNC(xe_rtp_match_psmi_enabled) - MEDIA_VERSION(3000), FUNC(xe_rtp_match_psmi_enabled) - MEDIA_VERSION(3002), FUNC(xe_rtp_match_psmi_enabled) + MEDIA_VERSION_RANGE(2000, 3002), FUNC(xe_rtp_match_psmi_enabled) 16023683509 MEDIA_VERSION(2000), FUNC(xe_rtp_match_psmi_enabled) MEDIA_VERSION(3000), MEDIA_STEP(A0, B0), FUNC(xe_rtp_match_psmi_enabled) diff --git a/drivers/hwmon/aht10.c b/drivers/hwmon/aht10.c index 7ba00bafb57d..400f0b76bb03 100644 --- a/drivers/hwmon/aht10.c +++ b/drivers/hwmon/aht10.c @@ -229,7 +229,7 @@ static int aht10_read_values(struct aht10_data *data) static ssize_t aht10_interval_write(struct aht10_data *data, long val) { - data->min_poll_interval = ms_to_ktime(clamp_val(val, 2000, LONG_MAX)); + data->min_poll_interval = ms_to_ktime(clamp_val(val, 2000, INT_MAX)); return 0; } diff --git a/drivers/hwmon/gpio-fan.c b/drivers/hwmon/gpio-fan.c index 34986266180e..15e2c8a8c8bb 100644 --- a/drivers/hwmon/gpio-fan.c +++ b/drivers/hwmon/gpio-fan.c @@ -531,8 +531,6 @@ static void gpio_fan_stop(void *data) mutex_lock(&fan_data->lock); set_fan_speed(data, 0); mutex_unlock(&fan_data->lock); - - pm_runtime_disable(fan_data->dev); } static int gpio_fan_probe(struct platform_device *pdev) @@ -560,6 +558,11 @@ static int gpio_fan_probe(struct platform_device *pdev) return dev_err_probe(dev, PTR_ERR(fan_data->supply), "Failed to get fan-supply"); + pm_runtime_set_suspended(dev); + err = devm_pm_runtime_enable(dev); + if (err) + return err; + /* Configure control GPIOs if available. */ if (fan_data->gpios && fan_data->num_gpios > 0) { if (!fan_data->speed || fan_data->num_speed <= 1) @@ -567,6 +570,12 @@ static int gpio_fan_probe(struct platform_device *pdev) err = fan_ctrl_init(fan_data); if (err) return err; + /* If current GPIO state is active, mark RPM as active as well */ + if (fan_data->speed_index > 0) { + err = pm_runtime_resume_and_get(dev); + if (err) + return err; + } err = devm_add_action_or_reset(dev, gpio_fan_stop, fan_data); if (err) return err; @@ -587,17 +596,6 @@ static int gpio_fan_probe(struct platform_device *pdev) return err; } - pm_runtime_set_suspended(&pdev->dev); - pm_runtime_enable(&pdev->dev); - /* If current GPIO state is active, mark RPM as active as well */ - if (fan_data->speed_index > 0) { - int ret; - - ret = pm_runtime_resume_and_get(&pdev->dev); - if (ret) - return ret; - } - /* Optional cooling device register for Device tree platforms */ fan_data->cdev = devm_thermal_of_cooling_device_register(dev, np, "gpio-fan", fan_data, &gpio_fan_cool_ops); diff --git a/drivers/hwmon/max31760.c b/drivers/hwmon/max31760.c index 127e31ca3c87..d71472f36096 100644 --- a/drivers/hwmon/max31760.c +++ b/drivers/hwmon/max31760.c @@ -27,8 +27,8 @@ #define REG_TACH(ch) (0x52 + (ch) * 2) #define REG_TEMP_INPUT(ch) (0x56 + (ch) * 2) -#define REG_TEMP_MAX(ch) (0x06 + (ch) * 2) -#define REG_TEMP_CRIT(ch) (0x0A + (ch) * 2) +#define REG_TEMP_MAX(ch) ((ch) ? 0x0C : 0x06) +#define REG_TEMP_CRIT(ch) ((ch) ? 0x08 : 0x0A) #define TEMP11_FROM_REG(reg) ((reg) / 32 * 125) #define TEMP11_TO_REG(val) (DIV_ROUND_CLOSEST(clamp_val((val), -128000, \ @@ -68,8 +68,9 @@ static const int max31760_pwm_freq[] = {33, 150, 1500, 25000}; static int tach_to_rpm(u16 tach) { + /* The count is 0 until the first measurement */ if (tach == 0) - tach = 1; + return 0; return 60 * 100000 / tach / 2; } @@ -533,8 +534,9 @@ static int max31760_probe(struct i2c_client *client) dev_set_drvdata(dev, state); - /* Set alert output to comparator mode */ - ret = regmap_set_bits(state->regmap, REG_CR2, CR2_ALERTS); + /* Leave standby mode, set alert output to comparator mode */ + ret = regmap_update_bits(state->regmap, REG_CR2, CR2_STBY | CR2_ALERTS, + CR2_ALERTS); if (ret) return dev_err_probe(dev, ret, "cannot write register\n"); diff --git a/drivers/hwmon/pmbus/mp2975.c b/drivers/hwmon/pmbus/mp2975.c index d0bc47b12cb0..8dd75dca5eb2 100644 --- a/drivers/hwmon/pmbus/mp2975.c +++ b/drivers/hwmon/pmbus/mp2975.c @@ -110,10 +110,7 @@ struct mp2975_data { int vout_scale; int max_phases[MP2975_PAGE_NUM]; int vid_step[MP2975_PAGE_NUM]; - int vref[MP2975_PAGE_NUM]; - int vref_off[MP2975_PAGE_NUM]; int vout_max[MP2975_PAGE_NUM]; - int vout_ov_fixed[MP2975_PAGE_NUM]; int curr_sense_gain[MP2975_PAGE_NUM]; }; @@ -466,12 +463,77 @@ static int mp2973_write_word_data(struct i2c_client *client, int page, return pmbus_write_word_data(client, 0, PMBUS_SMBALERT_MASK, ret); } +/* + * Let the PMBus core change the page, so that the page it caches matches the + * device. The core does not issue PAGE commands for a single rail + * configuration, thus change the page directly then. + */ +static int +mp2975_page_set(struct i2c_client *client, struct mp2975_data *data, int page) +{ + if (data->info.pages > 1) + return pmbus_set_page(client, page, 0xff); + + return i2c_smbus_write_byte_data(client, PMBUS_PAGE, page); +} + +/* + * Voltage reference is available on page 3 only. The callers read a register + * of the rail through the core first, thus the core caches the rail page. + */ +static int +mp2975_vref_get(struct i2c_client *client, struct mp2975_data *data, int page) +{ + int ret, vref; + + ret = mp2975_page_set(client, data, 3); + if (ret < 0) + return ret; + + vref = i2c_smbus_read_word_data(client, page ? MP2975_MFR_READ_VREF_R2 : + MP2975_MFR_READ_VREF_R1); + + ret = mp2975_page_set(client, data, page); + if (ret < 0) + return ret; + + return (vref < 0) ? vref : vref * data->vid_step[page]; +} + +static int +mp2975_ovp2_offset_get(int ovp_th_set) +{ + switch ((ovp_th_set & GENMASK(5, 3)) >> 3) { + case 1: + return 140; + case 2: + return 220; + case 4: + return 400; + default: + return -EINVAL; + } +} + +static int +mp2975_vout_ovp2_get(struct i2c_client *client, struct mp2975_data *data, + int page, int vref_off) +{ + int vref; + + vref = mp2975_vref_get(client, data, page); + if (vref < 0) + return vref; + + return vref + DIV_ROUND_CLOSEST(vref_off * data->vout_scale, 10); +} + static int mp2975_read_word_data(struct i2c_client *client, int page, int phase, int reg) { const struct pmbus_driver_info *info = pmbus_get_driver_info(client); struct mp2975_data *data = to_mp2975_data(info); - int ret; + int ret, ovp1, vref_off, uv_off; switch (reg) { case PMBUS_OT_FAULT_LIMIT: @@ -488,19 +550,35 @@ static int mp2975_read_word_data(struct i2c_client *client, int page, break; case PMBUS_VOUT_OV_FAULT_LIMIT: /* - * Register provides two values for over-voltage protection - * threshold for fixed (ovp2) and tracking (ovp1) modes. The - * minimum of these two values is provided as over-voltage - * fault alarm. + * Device provides dual over-voltage protection. OVP1 is + * referred to the maximum reference voltage, while OVP2 is + * referred to the current voltage reference, which is changed + * at runtime. Protection is tripped by any of them, thus the + * minimum of the two is exposed as over-voltage fault alarm, + * and OVP2 is obtained on each read. */ ret = mp2975_read_word_helper(client, page, phase, MP2975_MFR_OVP_TH_SET, - GENMASK(2, 0)); + GENMASK(5, 0)); if (ret < 0) return ret; - ret = min_t(int, data->vout_max[page] + 50 * (ret + 1), - data->vout_ov_fixed[page]); + ovp1 = data->vout_max[page] + 50 * ((ret & GENMASK(2, 0)) + 1); + + /* OVP1 still applies if the OVP2 threshold is unknown. */ + vref_off = mp2975_ovp2_offset_get(ret); + if (vref_off < 0) { + dev_warn_once(&client->dev, + "unsupported OVP2 selector, reporting OVP1 threshold\n"); + ret = ovp1; + break; + } + + ret = mp2975_vout_ovp2_get(client, data, page, vref_off); + if (ret < 0) + return ret; + + ret = min_t(int, ovp1, ret); break; case PMBUS_VOUT_UV_FAULT_LIMIT: ret = mp2975_read_word_helper(client, page, phase, @@ -509,8 +587,17 @@ static int mp2975_read_word_data(struct i2c_client *client, int page, if (ret < 0) return ret; - ret = DIV_ROUND_CLOSEST(data->vref[page] * 10 - 50 * - (ret + 1) * data->vout_scale, 10); + uv_off = 50 * (ret + 1) * data->vout_scale; + + ret = mp2975_vref_get(client, data, page); + if (ret < 0) + return ret; + + /* + * Offset can exceed the voltage reference, while a negative + * value would be reported as a read error. + */ + ret = max_t(int, DIV_ROUND_CLOSEST(ret * 10 - uv_off, 10), 0); break; case PMBUS_VIRT_READ_POUT_MAX: ret = mp2975_read_word_helper(client, page, phase, @@ -759,60 +846,6 @@ mp2975_current_sense_gain_get(struct i2c_client *client, return 0; } -static int -mp2975_vref_get(struct i2c_client *client, struct mp2975_data *data, - struct pmbus_driver_info *info) -{ - int ret; - - ret = i2c_smbus_write_byte_data(client, PMBUS_PAGE, 3); - if (ret < 0) - return ret; - - /* Get voltage reference value for rail 1. */ - ret = i2c_smbus_read_word_data(client, MP2975_MFR_READ_VREF_R1); - if (ret < 0) - return ret; - - data->vref[0] = ret * data->vid_step[0]; - - /* Get voltage reference value for rail 2, if connected. */ - if (data->info.pages == MP2975_PAGE_NUM) { - ret = i2c_smbus_read_word_data(client, MP2975_MFR_READ_VREF_R2); - if (ret < 0) - return ret; - - data->vref[1] = ret * data->vid_step[1]; - } - return 0; -} - -static int -mp2975_vref_offset_get(struct i2c_client *client, struct mp2975_data *data, - int page) -{ - int ret; - - ret = i2c_smbus_read_word_data(client, MP2975_MFR_OVP_TH_SET); - if (ret < 0) - return ret; - - switch ((ret & GENMASK(5, 3)) >> 3) { - case 1: - data->vref_off[page] = 140; - break; - case 2: - data->vref_off[page] = 220; - break; - case 4: - data->vref_off[page] = 400; - break; - default: - return -EINVAL; - } - return 0; -} - static int mp2975_vout_max_get(struct i2c_client *client, struct mp2975_data *data, struct pmbus_driver_info *info, int page) @@ -917,25 +950,6 @@ mp2975_vout_per_rail_config_get(struct i2c_client *client, ret = mp2975_vout_max_get(client, data, info, i); if (ret < 0) return ret; - - /* Skip if reading Vref is unsupported */ - if (data->chip_id != mp2975) - continue; - - /* Obtain voltage reference offsets. */ - ret = mp2975_vref_offset_get(client, data, i); - if (ret < 0) - return ret; - - /* - * Set over-voltage fixed value. Thresholds are provided as - * fixed value, and tracking value. The minimum of them are - * exposed as over-voltage critical threshold. - */ - data->vout_ov_fixed[i] = data->vref[i] + - DIV_ROUND_CLOSEST(data->vref_off[i] * - data->vout_scale, - 10); } return 0; @@ -1049,11 +1063,6 @@ static int mp2975_probe(struct i2c_client *client) if (ret) return ret; - /* Obtain voltage reference values. */ - ret = mp2975_vref_get(client, data, info); - if (ret) - return ret; - /* Obtain vout over-voltage scales. */ ret = mp2975_vout_ov_scale_get(client, data, info); if (ret < 0) @@ -1070,7 +1079,21 @@ static int mp2975_probe(struct i2c_client *client) if (ret) return ret; - return pmbus_do_probe(client, info); + ret = pmbus_do_probe(client, info); + if (ret) + return ret; + + /* + * Vout over- and under-voltage fault limits are relative to the + * voltage reference, which is changed at runtime. Do not allow the + * PMBus core to cache them. + */ + if (data->chip_id == mp2975) { + pmbus_set_update(client, PMBUS_VOUT_OV_FAULT_LIMIT, true); + pmbus_set_update(client, PMBUS_VOUT_UV_FAULT_LIMIT, true); + } + + return 0; } static const struct of_device_id mp2975_of_match[] = { diff --git a/drivers/hwmon/scmi-hwmon.c b/drivers/hwmon/scmi-hwmon.c index 364199b332c0..92aa2f37b10d 100644 --- a/drivers/hwmon/scmi-hwmon.c +++ b/drivers/hwmon/scmi-hwmon.c @@ -228,8 +228,8 @@ static int scmi_thermal_sensor_register(struct device *dev, static int scmi_hwmon_probe(struct scmi_device *sdev) { - int i, idx; u16 nr_sensors; + int i, idx, ret; enum hwmon_sensor_types type; struct scmi_sensors *scmi_sensors; const struct scmi_sensor_info *sensor; @@ -297,8 +297,12 @@ static int scmi_hwmon_probe(struct scmi_device *sdev) if (!nr_count[type]) continue; - scmi_hwmon_add_chan_info(scmi_hwmon_chan, dev, nr_count[type], - type, hwmon_attributes[type]); + ret = scmi_hwmon_add_chan_info(scmi_hwmon_chan, dev, + nr_count[type], type, + hwmon_attributes[type]); + if (ret) + return ret; + *ptr_scmi_ci++ = scmi_hwmon_chan++; scmi_sensors->info[type] = @@ -333,8 +337,6 @@ static int scmi_hwmon_probe(struct scmi_device *sdev) return PTR_ERR(hwdev); for (i = 0; i < nr_count_temp; i++) { - int ret; - sensor = *(scmi_sensors->info[hwmon_temp] + i); if (!sensor) continue; diff --git a/drivers/hwmon/sy7636a-hwmon.c b/drivers/hwmon/sy7636a-hwmon.c index d51daaf63d63..f01f368d68e5 100644 --- a/drivers/hwmon/sy7636a-hwmon.c +++ b/drivers/hwmon/sy7636a-hwmon.c @@ -29,7 +29,7 @@ static int sy7636a_read(struct device *dev, enum hwmon_sensor_types type, if (ret) return ret; - *temp = reg_val * 1000; + *temp = (s8)reg_val * 1000; return 0; } diff --git a/drivers/i3c/master/mipi-i3c-hci/dma.c b/drivers/i3c/master/mipi-i3c-hci/dma.c index 15a34429197b..8fe607af45d7 100644 --- a/drivers/i3c/master/mipi-i3c-hci/dma.c +++ b/drivers/i3c/master/mipi-i3c-hci/dma.c @@ -631,25 +631,24 @@ static void hci_dma_recycle_ibi_slot(struct i3c_hci *hci, i3c_generic_ibi_recycle_slot(dev_ibi->pool, slot); } -static void hci_dma_process_ibi(struct i3c_hci *hci, struct hci_rh_data *rh) +static bool hci_dma_process_ibi(struct i3c_hci *hci, struct hci_rh_data *rh, + u32 *op1_val, unsigned int enq_ptr) { struct hci_rings_data *rings = hci->io_data; struct i3c_dev_desc *dev; struct i3c_hci_dev_data *dev_data; struct hci_dma_dev_ibi_data *dev_ibi; struct i3c_ibi_slot *slot; - u32 op1_val, op2_val, ibi_status_error; - unsigned int ptr, enq_ptr, deq_ptr; + u32 ibi_status_error; + unsigned int ptr, deq_ptr; unsigned int ibi_size, ibi_chunks, ibi_data_offset, first_part; int ibi_addr, last_ptr; void *ring_ibi_data; dma_addr_t ring_ibi_data_dma; - op1_val = rh_reg_read(RING_OPERATION1); - deq_ptr = FIELD_GET(RING_OP1_IBI_DEQ_PTR, op1_val); - - op2_val = rh_reg_read(RING_OPERATION2); - enq_ptr = FIELD_GET(RING_OP2_IBI_ENQ_PTR, op2_val); + deq_ptr = FIELD_GET(RING_OP1_IBI_DEQ_PTR, *op1_val); + if (deq_ptr == enq_ptr) + return false; ibi_status_error = 0; ibi_addr = -1; @@ -699,7 +698,7 @@ static void hci_dma_process_ibi(struct i3c_hci *hci, struct hci_rh_data *rh) dev_dbg(&hci->master.dev, "no LAST_STATUS available (e=%d d=%d)", enq_ptr, deq_ptr); - return; + return false; } deq_ptr = last_ptr + 1; deq_ptr %= rh->ibi_status_entries; @@ -780,10 +779,10 @@ static void hci_dma_process_ibi(struct i3c_hci *hci, struct hci_rh_data *rh) done: /* take care to update the ibi dequeue pointer atomically */ spin_lock(&hci->lock); - op1_val = rh_reg_read(RING_OPERATION1); - op1_val &= ~RING_OP1_IBI_DEQ_PTR; - op1_val |= FIELD_PREP(RING_OP1_IBI_DEQ_PTR, deq_ptr); - rh_reg_write(RING_OPERATION1, op1_val); + *op1_val = rh_reg_read(RING_OPERATION1); + *op1_val &= ~RING_OP1_IBI_DEQ_PTR; + *op1_val |= FIELD_PREP(RING_OP1_IBI_DEQ_PTR, deq_ptr); + rh_reg_write(RING_OPERATION1, *op1_val); spin_unlock(&hci->lock); /* update the chunk pointer */ @@ -792,6 +791,19 @@ static void hci_dma_process_ibi(struct i3c_hci *hci, struct hci_rh_data *rh) /* and tell the hardware about freed chunks */ rh_reg_write(CHUNK_CONTROL, rh_reg_read(CHUNK_CONTROL) + ibi_chunks); + + return true; +} + +static void hci_dma_drain_ibi_ring(struct i3c_hci *hci, struct hci_rh_data *rh) +{ + u32 op1_val = rh_reg_read(RING_OPERATION1); + u32 op2_val = rh_reg_read(RING_OPERATION2); + unsigned int enq_ptr = FIELD_GET(RING_OP2_IBI_ENQ_PTR, op2_val); + + /* Loop is bounded by enq_ptr. Further IBIs will re-assert INTR_IBI_READY */ + while (hci_dma_process_ibi(hci, rh, &op1_val, enq_ptr)) + ; } static bool hci_dma_irq_handler(struct i3c_hci *hci) @@ -813,7 +825,7 @@ static bool hci_dma_irq_handler(struct i3c_hci *hci) rh_reg_write(INTR_STATUS, status); if (status & INTR_IBI_READY) - hci_dma_process_ibi(hci, rh); + hci_dma_drain_ibi_ring(hci, rh); if (status & (INTR_TRANSFER_COMPLETION | INTR_TRANSFER_ERR)) hci_dma_xfer_done(hci, rh); if (status & INTR_RING_OP) diff --git a/drivers/iio/accel/Kconfig b/drivers/iio/accel/Kconfig index 8c3f7cf55d5f..0f61caf129bc 100644 --- a/drivers/iio/accel/Kconfig +++ b/drivers/iio/accel/Kconfig @@ -32,6 +32,8 @@ config ADIS16209 config ADXL313 tristate + select IIO_BUFFER + select IIO_KFIFO_BUF config ADXL313_I2C tristate "Analog Devices ADXL313 3-Axis Digital Accelerometer I2C Driver" diff --git a/drivers/iio/accel/adxl380.c b/drivers/iio/accel/adxl380.c index c1188d3b06d4..0eefa89e5734 100644 --- a/drivers/iio/accel/adxl380.c +++ b/drivers/iio/accel/adxl380.c @@ -341,8 +341,11 @@ static int adxl380_set_act_inact_threshold(struct iio_dev *indio_dev, return ret; ret = adxl380_write_act_inact_threshold(st, act, th); - if (ret) + if (ret) { + /* Leave standby also if the value was refused */ + adxl380_set_measure_en(st, true); return ret; + } return adxl380_set_measure_en(st, true); } @@ -709,6 +712,12 @@ static int adxl380_set_range(struct adxl380_state *st, u8 range) guard(mutex)(&st->lock); + /* The thresholds are rescaled: see that they fit before any change */ + if (mult_frac(max(st->act_threshold, st->inact_threshold), + adxl380_range_scale_factor_tbl[st->range], + adxl380_range_scale_factor_tbl[range]) > ADXL380_THRESH_MAX) + return -EINVAL; + ret = adxl380_set_measure_en(st, false); if (ret) return ret; diff --git a/drivers/iio/accel/kxsd9.c b/drivers/iio/accel/kxsd9.c index 7ac885d94d7f..27adcdd31201 100644 --- a/drivers/iio/accel/kxsd9.c +++ b/drivers/iio/accel/kxsd9.c @@ -478,8 +478,8 @@ void kxsd9_common_remove(struct device *dev) struct iio_dev *indio_dev = dev_get_drvdata(dev); struct kxsd9_state *st = iio_priv(indio_dev); - iio_triggered_buffer_cleanup(indio_dev); iio_device_unregister(indio_dev); + iio_triggered_buffer_cleanup(indio_dev); pm_runtime_get_sync(dev); pm_runtime_put_noidle(dev); pm_runtime_disable(dev); diff --git a/drivers/iio/adc/ad7780.c b/drivers/iio/adc/ad7780.c index 24d2dcad8f4d..f28150a3bcfc 100644 --- a/drivers/iio/adc/ad7780.c +++ b/drivers/iio/adc/ad7780.c @@ -318,7 +318,9 @@ static int ad7780_probe(struct spi_device *spi) st = iio_priv(indio_dev); st->gain = 1; - ad_sd_init(&st->sd, indio_dev, spi, &ad7780_sigma_delta_info); + ret = ad_sd_init(&st->sd, indio_dev, spi, &ad7780_sigma_delta_info); + if (ret) + return ret; st->chip_info = &ad7780_chip_info_tbl[spi_get_device_id(spi)->driver_data]; diff --git a/drivers/iio/adc/ad7791.c b/drivers/iio/adc/ad7791.c index 041fc25e3209..a16c7e45c03f 100644 --- a/drivers/iio/adc/ad7791.c +++ b/drivers/iio/adc/ad7791.c @@ -436,7 +436,9 @@ static int ad7791_probe(struct spi_device *spi) return ret; st->info = &ad7791_chip_infos[spi_get_device_id(spi)->driver_data]; - ad_sd_init(&st->sd, indio_dev, spi, &ad7791_sigma_delta_info); + ret = ad_sd_init(&st->sd, indio_dev, spi, &ad7791_sigma_delta_info); + if (ret) + return ret; indio_dev->name = spi_get_device_id(spi)->name; indio_dev->modes = INDIO_DIRECT_MODE; diff --git a/drivers/iio/adc/ad7793.c b/drivers/iio/adc/ad7793.c index ccf18ce48e34..15fdaca9f831 100644 --- a/drivers/iio/adc/ad7793.c +++ b/drivers/iio/adc/ad7793.c @@ -796,7 +796,9 @@ static int ad7793_probe(struct spi_device *spi) st = iio_priv(indio_dev); - ad_sd_init(&st->sd, indio_dev, spi, &ad7793_sigma_delta_info); + ret = ad_sd_init(&st->sd, indio_dev, spi, &ad7793_sigma_delta_info); + if (ret) + return ret; if (pdata->refsel != AD7793_REFSEL_INTERNAL) { ret = devm_regulator_get_enable_read_voltage(&spi->dev, "refin"); diff --git a/drivers/iio/adc/max11205.c b/drivers/iio/adc/max11205.c index e8404973b01a..4649bfe7c250 100644 --- a/drivers/iio/adc/max11205.c +++ b/drivers/iio/adc/max11205.c @@ -114,7 +114,9 @@ static int max11205_probe(struct spi_device *spi) st = iio_priv(indio_dev); - ad_sd_init(&st->sd, indio_dev, spi, &max11205_sigma_delta_info); + ret = ad_sd_init(&st->sd, indio_dev, spi, &max11205_sigma_delta_info); + if (ret) + return ret; st->chip_info = spi_get_device_match_data(spi); if (!st->chip_info) diff --git a/drivers/iio/addac/ad74413r.c b/drivers/iio/addac/ad74413r.c index a20b4d48c5f7..585f775f232a 100644 --- a/drivers/iio/addac/ad74413r.c +++ b/drivers/iio/addac/ad74413r.c @@ -313,7 +313,7 @@ static int ad74413r_gpio_set_multiple(struct gpio_chip *chip, return ret; real_mask |= BIT(real_offset); - if (*bits & offset) + if (test_bit(offset, bits)) real_bits |= BIT(real_offset); } diff --git a/drivers/iio/afe/iio-rescale.c b/drivers/iio/afe/iio-rescale.c index ecaf59278c6f..2467f5e316fb 100644 --- a/drivers/iio/afe/iio-rescale.c +++ b/drivers/iio/afe/iio-rescale.c @@ -304,7 +304,8 @@ static int rescale_configure_channel(struct device *dev, chan->info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE); - if (rescale->offset) + if (rescale->offset || + iio_channel_has_info(schan, IIO_CHAN_INFO_OFFSET)) chan->info_mask_separate |= BIT(IIO_CHAN_INFO_OFFSET); /* diff --git a/drivers/iio/chemical/atlas-ezo-sensor.c b/drivers/iio/chemical/atlas-ezo-sensor.c index 59f3a4fa9e9f..0e8d6fd79ff1 100644 --- a/drivers/iio/chemical/atlas-ezo-sensor.c +++ b/drivers/iio/chemical/atlas-ezo-sensor.c @@ -117,9 +117,6 @@ static int atlas_ezo_read_raw(struct iio_dev *indio_dev, struct atlas_ezo_data *data = iio_priv(indio_dev); struct i2c_client *client = data->client; - if (chan->type != IIO_CONCENTRATION) - return -EINVAL; - switch (mask) { case IIO_CHAN_INFO_RAW: { int ret; diff --git a/drivers/iio/common/hid-sensors/hid-sensor-attributes.c b/drivers/iio/common/hid-sensors/hid-sensor-attributes.c index a61428bfdce3..2e3f3f41fdaa 100644 --- a/drivers/iio/common/hid-sensors/hid-sensor-attributes.c +++ b/drivers/iio/common/hid-sensors/hid-sensor-attributes.c @@ -38,6 +38,8 @@ static const struct { {HID_USAGE_SENSOR_COMPASS_3D, 0, 0, 1000000}, {HID_USAGE_SENSOR_COMPASS_3D, HID_USAGE_SENSOR_UNITS_GAUSS, 1, 0}, + {HID_USAGE_SENSOR_ORIENT_COMP_MAGN_NORTH, 0, 1, 0}, + {HID_USAGE_SENSOR_INCLINOMETER_3D, 0, 0, 17453293}, {HID_USAGE_SENSOR_INCLINOMETER_3D, HID_USAGE_SENSOR_UNITS_DEGREES, 0, 17453293}, @@ -97,9 +99,14 @@ static void simple_div(int dividend, int divisor, int *whole, static void split_micro_fraction(unsigned int no, int exp, int *val1, int *val2) { int divisor = int_pow(10, exp); + unsigned int rem; *val1 = no / divisor; - *val2 = no % divisor * int_pow(10, 6 - exp); + rem = no % divisor; + if (exp > 6) + *val2 = rem / (unsigned int)int_pow(10, exp - 6); + else + *val2 = rem * int_pow(10, 6 - exp); } /* @@ -141,7 +148,10 @@ static u32 convert_to_vtf_format(int size, int exp, int val1, int val2) if (val1 < 0 || val2 < 0) sign = -1; exp = hid_sensor_convert_exponent(exp); - if (exp < 0) { + if (exp < -6) { + value = abs(val1) * int_pow(10, -exp); + value += abs(val2) * int_pow(10, -exp - 6); + } else if (exp < 0) { divisor = int_pow(10, 6 + exp); value = abs(val1) * int_pow(10, -exp); value += abs(val2) / divisor; diff --git a/drivers/iio/common/scmi_sensors/scmi_iio.c b/drivers/iio/common/scmi_sensors/scmi_iio.c index 39c61c47022a..1aa4c0598d8b 100644 --- a/drivers/iio/common/scmi_sensors/scmi_iio.c +++ b/drivers/iio/common/scmi_sensors/scmi_iio.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -71,8 +72,7 @@ static int scmi_iio_sensor_update_cb(struct notifier_block *nb, tstamp_scale = sensor->sensor_info->tstamp_scale + const_ilog2(NSEC_PER_SEC) / const_ilog2(10); if (tstamp_scale < 0) { - do_div(time, int_pow(10, abs(tstamp_scale))); - time_ns = time; + time_ns = div64_u64(time, int_pow(10, abs(tstamp_scale))); } else { time_ns = time * int_pow(10, tstamp_scale); } @@ -163,7 +163,7 @@ static int scmi_iio_set_odr_val(struct iio_dev *iio_dev, int val, int val2) mult = scnprintf(buf, sizeof(buf), "%llu", sf) - 1; sec = int_pow(10, mult) * MICROHZ_PER_HZ; - do_div(sec, uHz); + sec = div64_u64(sec, uHz); if (sec == 0) { dev_err(&iio_dev->dev, "Trying to set invalid sensor update value for sensor %s", @@ -238,13 +238,10 @@ static int scmi_iio_read_avail(struct iio_dev *iio_dev, static void convert_ns_to_freq(u64 interval_ns, u64 *hz, u64 *uhz) { - u64 rem, freq; + u64 rem; - freq = NSEC_PER_SEC; - rem = do_div(freq, interval_ns); - *hz = freq; - *uhz = rem * 1000000UL; - do_div(*uhz, interval_ns); + *hz = div64_u64_rem(HZ_PER_GHZ, interval_ns, &rem); + *uhz = div64_u64(rem * MICROHZ_PER_HZ, interval_ns); } static int scmi_iio_get_odr_val(struct iio_dev *iio_dev, int *val, int *val2) @@ -270,7 +267,8 @@ static int scmi_iio_get_odr_val(struct iio_dev *iio_dev, int *val, int *val2) mult = SCMI_SENS_CFG_GET_UPDATE_EXP(sensor_config); if (mult < 0) { sensor_interval_mult = int_pow(10, abs(mult)); - do_div(sensor_update_interval, sensor_interval_mult); + sensor_update_interval = div64_u64(sensor_update_interval, + sensor_interval_mult); } else { sensor_interval_mult = int_pow(10, mult); sensor_update_interval = @@ -396,9 +394,9 @@ static ssize_t scmi_iio_get_raw_available(struct iio_dev *iio_dev, */ exponent = exponent - scale; if (exponent < 0) { - rem = do_div(resolution, - int_pow(10, abs(exponent)) - ); + resolution = div64_u64_rem(resolution, + int_pow(10, abs(exponent)), + &rem); len = sysfs_emit(buf, "[%lld %llu.%llu %lld]\n", min_range, resolution, rem, max_range); @@ -503,7 +501,8 @@ static u64 scmi_iio_convert_interval_to_ns(u32 val) mult = SCMI_SENS_INTVL_GET_EXP(val); if (mult < 0) { sensor_interval_mult = int_pow(10, abs(mult)); - do_div(sensor_update_interval, sensor_interval_mult); + sensor_update_interval = div64_u64(sensor_update_interval, + sensor_interval_mult); } else { sensor_interval_mult = int_pow(10, mult); sensor_update_interval = diff --git a/drivers/iio/dac/mcp4725.c b/drivers/iio/dac/mcp4725.c index 23b9e3a09ec8..81182f38fe45 100644 --- a/drivers/iio/dac/mcp4725.c +++ b/drivers/iio/dac/mcp4725.c @@ -357,6 +357,8 @@ static int mcp4725_write_raw(struct iio_dev *indio_dev, switch (mask) { case IIO_CHAN_INFO_RAW: ret = mcp4725_set_value(indio_dev, val); + if (ret) + return ret; data->dac_value = val; break; default: diff --git a/drivers/iio/gyro/bmg160_core.c b/drivers/iio/gyro/bmg160_core.c index d611341a0e2a..0b5621455216 100644 --- a/drivers/iio/gyro/bmg160_core.c +++ b/drivers/iio/gyro/bmg160_core.c @@ -761,7 +761,7 @@ static int bmg160_write_event_config(struct iio_dev *indio_dev, struct bmg160_data *data = iio_priv(indio_dev); int ret; - if (state && data->ev_enable_state) + if (state == data->ev_enable_state) return 0; mutex_lock(&data->mutex); diff --git a/drivers/iio/humidity/am2315.c b/drivers/iio/humidity/am2315.c index 02ca23eb8991..3725f8566980 100644 --- a/drivers/iio/humidity/am2315.c +++ b/drivers/iio/humidity/am2315.c @@ -113,6 +113,7 @@ static int am2315_read_data(struct am2315_data *data, */ u8 rx_buf[8]; u16 crc; + u16 temp_raw; /* First wake up the device. */ am2315_ping(data->client); @@ -144,8 +145,15 @@ static int am2315_read_data(struct am2315_data *data, sensor_data->hum_data = (rx_buf[AM2315_HUM_OFFSET] << 8) | rx_buf[AM2315_HUM_OFFSET + 1]; - sensor_data->temp_data = (rx_buf[AM2315_TEMP_OFFSET] << 8) | - rx_buf[AM2315_TEMP_OFFSET + 1]; + + /* + * Temperature is sign-magnitude, not two's complement: + * bit 15 is the sign, bits 14-0 are the magnitude (x0.1 degC). + */ + temp_raw = (rx_buf[AM2315_TEMP_OFFSET] << 8) | + rx_buf[AM2315_TEMP_OFFSET + 1]; + sensor_data->temp_data = (temp_raw & 0x8000) ? + -(temp_raw & 0x7fff) : temp_raw; return ret; diff --git a/drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c b/drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c index 2c3e41a24b33..451bf89e3b9a 100644 --- a/drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c +++ b/drivers/iio/imu/inv_icm42600/inv_icm42600_buffer.c @@ -513,22 +513,20 @@ int inv_icm42600_buffer_fifo_parse(struct inv_icm42600_state *st) ts = &gyro_st->ts; inv_sensors_timestamp_interrupt(ts, st->fifo.watermark.eff_gyro, st->timestamp.gyro); - ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro); - if (ret) - return ret; } + ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro); + if (ret) + return ret; + /* handle accelerometer timestamp and FIFO data parsing */ if (st->fifo.nb.accel > 0) { ts = &accel_st->ts; inv_sensors_timestamp_interrupt(ts, st->fifo.watermark.eff_accel, st->timestamp.accel); - ret = inv_icm42600_accel_parse_fifo(st->indio_accel); - if (ret) - return ret; } - return 0; + return inv_icm42600_accel_parse_fifo(st->indio_accel); } int inv_icm42600_buffer_hwfifo_flush(struct inv_icm42600_state *st, @@ -553,20 +551,18 @@ int inv_icm42600_buffer_hwfifo_flush(struct inv_icm42600_state *st, if (st->fifo.nb.gyro > 0) { ts = &gyro_st->ts; inv_sensors_timestamp_interrupt(ts, st->fifo.nb.gyro, gyro_ts); - ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro); - if (ret) - return ret; } + ret = inv_icm42600_gyro_parse_fifo(st->indio_gyro); + if (ret) + return ret; + if (st->fifo.nb.accel > 0) { ts = &accel_st->ts; inv_sensors_timestamp_interrupt(ts, st->fifo.nb.accel, accel_ts); - ret = inv_icm42600_accel_parse_fifo(st->indio_accel); - if (ret) - return ret; } - return 0; + return inv_icm42600_accel_parse_fifo(st->indio_accel); } int inv_icm42600_buffer_init(struct inv_icm42600_state *st) diff --git a/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c b/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c index 5796896d54cd..3bdcf92472e8 100644 --- a/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c +++ b/drivers/iio/imu/inv_mpu6050/inv_mpu_core.c @@ -149,7 +149,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6050, .fifo_size = 1024, .temp = {INV_MPU6050_TEMP_OFFSET, INV_MPU6050_TEMP_SCALE}, - .startup_time = {INV_MPU6050_GYRO_STARTUP_TIME, INV_MPU6050_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6050_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6050_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6500_WHOAMI_VALUE, @@ -158,7 +161,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6515_WHOAMI_VALUE, @@ -167,7 +173,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6880_WHOAMI_VALUE, @@ -176,7 +185,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4096, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU6000_WHOAMI_VALUE, @@ -185,7 +197,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6050, .fifo_size = 1024, .temp = {INV_MPU6050_TEMP_OFFSET, INV_MPU6050_TEMP_SCALE}, - .startup_time = {INV_MPU6050_GYRO_STARTUP_TIME, INV_MPU6050_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6050_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6050_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU9150_WHOAMI_VALUE, @@ -194,7 +209,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6050, .fifo_size = 1024, .temp = {INV_MPU6050_TEMP_OFFSET, INV_MPU6050_TEMP_SCALE}, - .startup_time = {INV_MPU6050_GYRO_STARTUP_TIME, INV_MPU6050_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6050_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6050_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU9250_WHOAMI_VALUE, @@ -203,7 +221,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_MPU9255_WHOAMI_VALUE, @@ -212,7 +233,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_MPU6500_TEMP_OFFSET, INV_MPU6500_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20608_WHOAMI_VALUE, @@ -221,7 +245,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20608D_WHOAMI_VALUE, @@ -230,7 +257,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20609_WHOAMI_VALUE, @@ -239,7 +269,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20689_WHOAMI_VALUE, @@ -248,7 +281,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20600_WHOAMI_VALUE, @@ -257,7 +293,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 1008, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_ICM20602_GYRO_STARTUP_TIME, INV_ICM20602_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_ICM20602_ACCEL_STARTUP_TIME, + .gyro = INV_ICM20602_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20602_WHOAMI_VALUE, @@ -266,7 +305,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 1008, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_ICM20602_GYRO_STARTUP_TIME, INV_ICM20602_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_ICM20602_ACCEL_STARTUP_TIME, + .gyro = INV_ICM20602_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_ICM20690_WHOAMI_VALUE, @@ -275,7 +317,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_ICM20690_GYRO_STARTUP_TIME, INV_ICM20690_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_ICM20690_ACCEL_STARTUP_TIME, + .gyro = INV_ICM20690_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20380_WHOAMI_VALUE, .name = "IAM20380", @@ -283,7 +328,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20680_WHOAMI_VALUE, @@ -292,7 +340,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 512, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20680HP_WHOAMI_VALUE, @@ -301,7 +352,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, { .whoami = INV_IAM20680HT_WHOAMI_VALUE, @@ -310,7 +364,10 @@ static const struct inv_mpu6050_hw hw_info[] = { .config = &chip_config_6500, .fifo_size = 4 * 1024, .temp = {INV_ICM20608_TEMP_OFFSET, INV_ICM20608_TEMP_SCALE}, - .startup_time = {INV_MPU6500_GYRO_STARTUP_TIME, INV_MPU6500_ACCEL_STARTUP_TIME}, + .startup_time = { + .accel = INV_MPU6500_ACCEL_STARTUP_TIME, + .gyro = INV_MPU6500_GYRO_STARTUP_TIME, + }, }, }; @@ -1574,6 +1631,8 @@ static const unsigned long inv_mpu_scan_masks[] = { .type = IIO_MAGN, \ .modified = 1, \ .channel2 = _chan2, \ + /* index of the axis in magn_raw_to_gauss[] */ \ + .address = (_chan2) - IIO_MOD_X, \ .info_mask_separate = BIT(IIO_CHAN_INFO_SCALE) | \ BIT(IIO_CHAN_INFO_RAW), \ .scan_index = _index, \ diff --git a/drivers/iio/imu/kmx61.c b/drivers/iio/imu/kmx61.c index 3cd91d8a89ee..22d2a84fedf8 100644 --- a/drivers/iio/imu/kmx61.c +++ b/drivers/iio/imu/kmx61.c @@ -942,7 +942,7 @@ static int kmx61_write_event_config(struct iio_dev *indio_dev, struct kmx61_data *data = kmx61_get_data(indio_dev); int ret = 0; - if (state && data->ev_enable_state) + if (state == data->ev_enable_state) return 0; mutex_lock(&data->lock); diff --git a/drivers/iio/industrialio-acpi.c b/drivers/iio/industrialio-acpi.c index d67a43843799..c77926f6db62 100644 --- a/drivers/iio/industrialio-acpi.c +++ b/drivers/iio/industrialio-acpi.c @@ -6,6 +6,7 @@ #include #include #include +#include /** * iio_read_acpi_mount_matrix() - Read accelerometer mount matrix info from ACPI @@ -63,6 +64,14 @@ bool iio_read_acpi_mount_matrix(struct device *dev, } str = elements[i].string.pointer; + /* + * Microsoft's example separates the values with spaces, "0 1 0". + * Some BIOSes use commas instead, with or without spaces around + * them: "0, 1, 0", "0, -1 , 0", "1, 0,0". The string lives in + * the buffer allocated for us above, so turn the commas into + * spaces in place before parsing. + */ + strreplace(str, ',', ' '); if (sscanf(str, "%d %d %d", &val[0], &val[1], &val[2]) != 3) { dev_err(dev, "Incorrect ACPI mount matrix string format\n"); goto out_free_buffer; diff --git a/drivers/iio/industrialio-trigger.c b/drivers/iio/industrialio-trigger.c index 68e92eac2b77..52fd028cb108 100644 --- a/drivers/iio/industrialio-trigger.c +++ b/drivers/iio/industrialio-trigger.c @@ -105,9 +105,8 @@ void iio_trigger_unregister(struct iio_trigger *trig_info) scoped_guard(mutex, &iio_trigger_list_lock) list_del(&trig_info->list); - ida_free(&iio_trigger_ida, trig_info->id); - /* Possible issue in here */ device_del(&trig_info->dev); + ida_free(&iio_trigger_ida, trig_info->id); } EXPORT_SYMBOL(iio_trigger_unregister); @@ -293,6 +292,7 @@ int iio_trigger_attach_poll_func(struct iio_trigger *trig, if (pf->irq < 0) { pr_err("Could not find an available irq for trigger %s, CONFIG_IIO_CONSUMERS_PER_TRIGGER=%d limit might be exceeded\n", trig->name, CONFIG_IIO_CONSUMERS_PER_TRIGGER); + ret = pf->irq; goto out_put_module; } diff --git a/drivers/iio/light/tsl2591.c b/drivers/iio/light/tsl2591.c index c5ccd833dde6..8d98a7d1403e 100644 --- a/drivers/iio/light/tsl2591.c +++ b/drivers/iio/light/tsl2591.c @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -425,6 +426,10 @@ static int tsl2591_wait_adc_complete(struct tsl2591_chip *chip) * Scale values to get more representative value of lux i.e. * lux = ((C0DATA - C1DATA) * (1000 - ((C1DATA * 1000) / C0DATA))) / CPL * + * CPL is not computed on its own: at 1x gain it is below 1 for integration + * times under 500 ms, so the division by LUX DF is folded into the final + * division instead. + * * Channel 0 = IR + Visible * Channel 1 = IR only */ @@ -436,8 +441,10 @@ static int tsl2591_read_channel_data(struct iio_dev *indio_dev, struct tsl2591_als_settings *settings = &chip->als_settings; struct i2c_client *client = chip->client; u8 als_data[TSL2591_NUM_DATA_REGISTERS]; - int counts_per_lux, int_time_fval, gain_multi, lux; + int int_time_fval, gain_multi; u16 als_ch0, als_ch1; + u64 lux; + u32 rem; int ret; ret = tsl2591_wait_adc_complete(chip); @@ -473,23 +480,28 @@ static int tsl2591_read_channel_data(struct iio_dev *indio_dev, return gain_multi; } - int_time_fval = TSL2591_FVAL_TO_MSEC(settings->als_int_time); - /* Calculate counts per lux value */ - counts_per_lux = (int_time_fval * gain_multi) / TSL2591_LUX_COEFFICIENT; + /* No visible light, this also catches C0DATA == 0 */ + if (als_ch0 <= als_ch1) { + *val = 0; + *val2 = 0; + break; + } - dev_dbg(&client->dev, "Counts Per Lux: %d\n", counts_per_lux); + int_time_fval = TSL2591_FVAL_TO_MSEC(settings->als_int_time); /* Calculate lux value */ - lux = ((als_ch0 - als_ch1) * - (1000 - ((als_ch1 * 1000) / als_ch0))) / counts_per_lux; + lux = (u64)(als_ch0 - als_ch1) * + (1000 - ((als_ch1 * 1000) / als_ch0)) * + TSL2591_LUX_COEFFICIENT; + lux = div_u64(lux, int_time_fval * gain_multi); - dev_dbg(&client->dev, "Raw lux calculation: %d\n", lux); + dev_dbg(&client->dev, "Raw lux calculation: %llu\n", lux); /* Divide by 1000 to get real lux value before scaling */ - *val = lux / 1000; + *val = div_u64_rem(lux, 1000, &rem); /* Get the decimal part of lux reading */ - *val2 = (lux - (*val * 1000)) * 1000; + *val2 = rem * 1000; break; default: diff --git a/drivers/iio/light/vcnl4035.c b/drivers/iio/light/vcnl4035.c index 16aeb17067bc..d73d04b46595 100644 --- a/drivers/iio/light/vcnl4035.c +++ b/drivers/iio/light/vcnl4035.c @@ -44,8 +44,8 @@ #define VCNL4035_DEV_ID_MASK GENMASK(7, 0) /* Default values */ -#define VCNL4035_MODE_ALS_ENABLE BIT(0) -#define VCNL4035_MODE_ALS_DISABLE 0x00 +#define VCNL4035_MODE_ALS_ENABLE 0x00 +#define VCNL4035_MODE_ALS_DISABLE BIT(0) #define VCNL4035_MODE_ALS_INT_ENABLE BIT(1) #define VCNL4035_MODE_ALS_INT_DISABLE 0 #define VCNL4035_DEV_ID_VAL 0x80 diff --git a/drivers/iio/magnetometer/mmc35240.c b/drivers/iio/magnetometer/mmc35240.c index f3d48d03f7c3..5efedee1a3ab 100644 --- a/drivers/iio/magnetometer/mmc35240.c +++ b/drivers/iio/magnetometer/mmc35240.c @@ -533,14 +533,13 @@ static int mmc35240_resume(struct device *dev) struct mmc35240_data *data = iio_priv(indio_dev); int ret; + regcache_cache_only(data->regmap, false); regcache_mark_dirty(data->regmap); ret = regcache_sync_region(data->regmap, MMC35240_REG_CTRL0, MMC35240_REG_CTRL1); if (ret < 0) dev_err(dev, "Failed to restore control registers\n"); - regcache_cache_only(data->regmap, false); - return 0; } diff --git a/drivers/iio/magnetometer/tlv493d.c b/drivers/iio/magnetometer/tlv493d.c index e5e050af2b74..fa3b075e6526 100644 --- a/drivers/iio/magnetometer/tlv493d.c +++ b/drivers/iio/magnetometer/tlv493d.c @@ -300,11 +300,11 @@ static int tlv493d_read_raw(struct iio_dev *indio_dev, switch (chan->type) { case IIO_MAGN: /* - * Magnetic field scale: 0.0098 mTesla (i.e. 9.8 µT) - * Magnetic field in Gauss: mT * 10 = 0.098. + * Magnetic field scale: 0.098 mTesla (i.e. 98 µT) per LSB. + * In Gauss (1 mT = 10 G): 0.98 G per LSB. */ *val = 98; - *val2 = 1000; + *val2 = 100; return IIO_VAL_FRACTIONAL; case IIO_TEMP: /* diff --git a/drivers/iio/proximity/sx9310.c b/drivers/iio/proximity/sx9310.c index fb02eac78ed4..c3e22c842e6b 100644 --- a/drivers/iio/proximity/sx9310.c +++ b/drivers/iio/proximity/sx9310.c @@ -892,7 +892,7 @@ static int sx9310_check_whoami(struct device *dev, if (ret) return ret; - ddata = device_get_match_data(dev); + ddata = i2c_get_match_data(data->client); if (ddata->whoami != whoami) return -ENODEV; diff --git a/drivers/iio/proximity/sx9324.c b/drivers/iio/proximity/sx9324.c index 01aff1b584b7..6c95dc87ccc0 100644 --- a/drivers/iio/proximity/sx9324.c +++ b/drivers/iio/proximity/sx9324.c @@ -280,11 +280,20 @@ static const struct { { 0, 250000 }, /* 11111: 4 s */ }; +/* + * The scan period of the SX9324 is selected by the 5-bit wide + * SX9324_REG_GNRL_CTRL0_SCANPERIOD field. The values below are the scan + * periods in ms of the corresponding sx9324_samp_freq_table[] entries. + */ static const unsigned int sx9324_scan_period_table[] = { - 2, 15, 30, 45, 60, 90, 120, 200, - 400, 600, 800, 1000, 2000, 3000, 4000, 5000, + 1, 2, 4, 6, 8, 10, 14, 18, /* 0x00 - 0x07 */ + 22, 26, 30, 34, 38, 42, 46, 50, /* 0x08 - 0x0f */ + 56, 62, 68, 74, 80, 90, 100, 200, /* 0x10 - 0x17 */ + 300, 400, 600, 800, 1000, 2000, 3000, 4000, /* 0x18 - 0x1f */ }; +static_assert(ARRAY_SIZE(sx9324_scan_period_table) == ARRAY_SIZE(sx9324_samp_freq_table)); + static const struct regmap_range sx9324_writable_reg_ranges[] = { /* * To set COMPSTAT for compensation, even if datasheet says register is diff --git a/drivers/iio/proximity/sx9500.c b/drivers/iio/proximity/sx9500.c index 6c67bae7488c..0309cd492620 100644 --- a/drivers/iio/proximity/sx9500.c +++ b/drivers/iio/proximity/sx9500.c @@ -548,6 +548,12 @@ static int sx9500_write_event_config(struct iio_dev *indio_dev, mutex_lock(&data->mutex); + /* The user counts must only change when the state does. */ + if (data->event_enabled[chan->channel] == state) { + ret = 0; + goto out_unlock; + } + if (state) { ret = sx9500_inc_chan_users(data, chan->channel); if (ret < 0) diff --git a/drivers/iio/temperature/mlx90614.c b/drivers/iio/temperature/mlx90614.c index 8a44a00bfd5e..d698d124adc6 100644 --- a/drivers/iio/temperature/mlx90614.c +++ b/drivers/iio/temperature/mlx90614.c @@ -569,7 +569,7 @@ static int mlx90614_probe_num_ir_sensors(struct i2c_client *client) const struct mlx_chip_info *chip_info = data->chip_info; s32 ret; - if (chip_info->dual_channel) + if (!chip_info->dual_channel) return 0; ret = i2c_smbus_read_word_data(client, chip_info->op_eeprom_config1); diff --git a/drivers/infiniband/core/rdma_core.c b/drivers/infiniband/core/rdma_core.c index 18918f463361..9503c7e90bd8 100644 --- a/drivers/infiniband/core/rdma_core.c +++ b/drivers/infiniband/core/rdma_core.c @@ -688,6 +688,7 @@ void rdma_assign_uobject(struct ib_uobject *to_uobj, struct ib_uobject *new_uobj * If this fails then the uobject is still completely valid (though with * a new ID) and we leak it until context close. */ + uverbs_get_cleared_udata(attrs); uverbs_destroy_uobject(to_uobj, RDMA_REMOVE_DESTROY, attrs); } @@ -703,6 +704,7 @@ void rdma_alloc_abort_uobject(struct ib_uobject *uobj, int ret; if (hw_obj_valid) { + uverbs_get_cleared_udata(attrs); ret = uobj->uapi_object->type_class->destroy_hw( uobj, RDMA_REMOVE_ABORT, attrs); /* diff --git a/drivers/infiniband/hw/bnxt_re/bnxt_re.h b/drivers/infiniband/hw/bnxt_re/bnxt_re.h index 3485e495ac6a..ce3a1fd8aa83 100644 --- a/drivers/infiniband/hw/bnxt_re/bnxt_re.h +++ b/drivers/infiniband/hw/bnxt_re/bnxt_re.h @@ -222,6 +222,10 @@ struct bnxt_re_dev { unsigned long event_bitmap; struct bnxt_qplib_cc_param cc_param; struct workqueue_struct *dcb_wq; + /* Protects dcb_wq against bnxt_re_uninit_dcb_wq() destroying it + * concurrently with bnxt_re_async_notifier() queuing work on it. + */ + spinlock_t dcb_lock; struct dentry *cc_config; struct bnxt_re_dbg_cc_config_params *cc_config_params; #define BNXT_VPD_FLD_LEN 32 diff --git a/drivers/infiniband/hw/bnxt_re/main.c b/drivers/infiniband/hw/bnxt_re/main.c index e8a4befd6ca0..690b261b581a 100644 --- a/drivers/infiniband/hw/bnxt_re/main.c +++ b/drivers/infiniband/hw/bnxt_re/main.c @@ -367,9 +367,15 @@ static int bnxt_re_init_dcb_wq(struct bnxt_re_dev *rdev) static void bnxt_re_uninit_dcb_wq(struct bnxt_re_dev *rdev) { - if (!rdev->dcb_wq) - return; - destroy_workqueue(rdev->dcb_wq); + struct workqueue_struct *dcb_wq; + + spin_lock_bh(&rdev->dcb_lock); + dcb_wq = rdev->dcb_wq; + rdev->dcb_wq = NULL; + spin_unlock_bh(&rdev->dcb_lock); + + if (dcb_wq) + destroy_workqueue(dcb_wq); } static void bnxt_re_dcb_wq_task(struct work_struct *work) @@ -424,14 +430,23 @@ static void bnxt_re_async_notifier(void *handle, struct hwrm_async_event_cmpl *c switch (event_id) { case ASYNC_EVENT_CMPL_EVENT_ID_DCB_CONFIG_CHANGE: + spin_lock(&rdev->dcb_lock); + if (!rdev->dcb_wq) { + spin_unlock(&rdev->dcb_lock); + break; + } + dcb_work = kzalloc(sizeof(*dcb_work), GFP_ATOMIC); - if (!dcb_work) + if (!dcb_work) { + spin_unlock(&rdev->dcb_lock); break; + } dcb_work->rdev = rdev; memcpy(&dcb_work->cmpl, cmpl, sizeof(*cmpl)); INIT_WORK(&dcb_work->work, bnxt_re_dcb_wq_task); queue_work(rdev->dcb_wq, &dcb_work->work); + spin_unlock(&rdev->dcb_lock); break; default: break; @@ -1446,6 +1461,7 @@ static struct bnxt_re_dev *bnxt_re_dev_add(struct auxiliary_device *adev, INIT_LIST_HEAD(&rdev->qp_list); mutex_init(&rdev->qp_lock); mutex_init(&rdev->pacing.dbq_lock); + spin_lock_init(&rdev->dcb_lock); atomic_set(&rdev->stats.res.qp_count, 0); atomic_set(&rdev->stats.res.cq_count, 0); atomic_set(&rdev->stats.res.srq_count, 0); diff --git a/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c b/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c index 4dad0cfcfa98..a70aa6a83da3 100644 --- a/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c +++ b/drivers/infiniband/hw/bnxt_re/qplib_rcfw.c @@ -638,6 +638,10 @@ static int bnxt_qplib_process_qp_event(struct bnxt_qplib_rcfw *rcfw, err_event = (struct creq_qp_error_notification *)qp_event; qp_id = le32_to_cpu(err_event->xid); spin_lock(&rcfw->tbl_lock); + if (!rcfw->qp_tbl) { + spin_unlock(&rcfw->tbl_lock); + break; + } tbl_indx = map_qp_id_to_tbl_indx(qp_id, rcfw); qp = rcfw->qp_tbl[tbl_indx].qp_handle; if (!qp) { diff --git a/drivers/infiniband/hw/bnxt_re/qplib_res.c b/drivers/infiniband/hw/bnxt_re/qplib_res.c index d92db77e7ed5..5948e1f11384 100644 --- a/drivers/infiniband/hw/bnxt_re/qplib_res.c +++ b/drivers/infiniband/hw/bnxt_re/qplib_res.c @@ -867,7 +867,15 @@ int bnxt_qplib_init_res(struct bnxt_qplib_res *res) void bnxt_qplib_free_res(struct bnxt_qplib_res *res) { - kfree(res->rcfw->qp_tbl); + struct bnxt_qplib_rcfw *rcfw = res->rcfw; + struct bnxt_qplib_qp_node *qp_tbl; + + /* The CREQ tasklet may still be running; unpublish the table first */ + spin_lock_bh(&rcfw->tbl_lock); + qp_tbl = rcfw->qp_tbl; + rcfw->qp_tbl = NULL; + spin_unlock_bh(&rcfw->tbl_lock); + kvfree(qp_tbl); bnxt_qplib_free_sgid_tbl(res, &res->sgid_tbl); bnxt_qplib_free_pd_tbl(&res->pd_tbl); bnxt_qplib_free_dpi_tbl(res, &res->dpi_tbl); @@ -884,8 +892,8 @@ int bnxt_qplib_alloc_res(struct bnxt_qplib_res *res, struct net_device *netdev) /* Allocate one extra to hold the QP1 entries */ rcfw->qp_tbl_size = max_t(u32, BNXT_RE_MAX_QPC_COUNT + 1, dev_attr->max_qp); - rcfw->qp_tbl = kcalloc(rcfw->qp_tbl_size, sizeof(struct bnxt_qplib_qp_node), - GFP_KERNEL); + rcfw->qp_tbl = kvcalloc(rcfw->qp_tbl_size, sizeof(struct bnxt_qplib_qp_node), + GFP_KERNEL); if (!rcfw->qp_tbl) return -ENOMEM; diff --git a/drivers/infiniband/hw/mlx5/fs.c b/drivers/infiniband/hw/mlx5/fs.c index b67994df98f2..af3fd7781e68 100644 --- a/drivers/infiniband/hw/mlx5/fs.c +++ b/drivers/infiniband/hw/mlx5/fs.c @@ -2999,6 +2999,9 @@ static int UVERBS_HANDLER(MLX5_IB_METHOD_STEERING_ANCHOR_CREATE)( if (err) return err; + if (priority > MLX5_IB_FLOW_LAST_PRIO) + return -EINVAL; + obj = kzalloc(sizeof(*obj), GFP_KERNEL); if (!obj) return -ENOMEM; diff --git a/drivers/infiniband/hw/mlx5/qp.c b/drivers/infiniband/hw/mlx5/qp.c index 865000d1a2c5..5a6aede3f138 100644 --- a/drivers/infiniband/hw/mlx5/qp.c +++ b/drivers/infiniband/hw/mlx5/qp.c @@ -1599,6 +1599,8 @@ static int create_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, if (err) return err; + sq->base.container_mibqp = qp; + sq->base.mqp.event = mlx5_ib_qp_event; err = create_raw_packet_qp_sq(dev, udata, sq, in, pd, to_mcq(init_attr->send_cq)); if (err) @@ -1610,9 +1612,6 @@ static int create_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, resp->sqn = sq->base.mqp.qpn; resp->comp_mask |= MLX5_IB_CREATE_QP_RESP_MASK_SQN; } - - sq->base.container_mibqp = qp; - sq->base.mqp.event = mlx5_ib_qp_event; } if (qp->rq.wqe_cnt) { @@ -2062,13 +2061,13 @@ static int create_xrc_tgt_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, } base = &qp->trans_qp.base; + base->container_mibqp = qp; + base->mqp.event = mlx5_ib_qp_event; err = mlx5_qpc_create_qp(dev, &base->mqp, in, inlen, out); kvfree(in); if (err) return err; - base->container_mibqp = qp; - base->mqp.event = mlx5_ib_qp_event; if (MLX5_CAP_GEN(mdev, ece_support)) params->resp.ece_options = MLX5_GET(create_qp_out, out, ece); @@ -2206,14 +2205,14 @@ static int create_dci(struct mlx5_ib_dev *dev, struct ib_pd *pd, qp->flags &= ~IB_QP_CREATE_PCI_WRITE_END_PADDING; } + base->container_mibqp = qp; + base->mqp.event = mlx5_ib_qp_event; err = mlx5_qpc_create_qp(dev, &base->mqp, in, inlen, out); kvfree(in); if (err) goto err_create; - base->container_mibqp = qp; - base->mqp.event = mlx5_ib_qp_event; if (MLX5_CAP_GEN(mdev, ece_support)) params->resp.ece_options = MLX5_GET(create_qp_out, out, ece); @@ -2402,6 +2401,8 @@ static int create_user_qp(struct mlx5_ib_dev *dev, struct ib_pd *pd, qp->flags &= ~IB_QP_CREATE_PCI_WRITE_END_PADDING; } + base->container_mibqp = qp; + base->mqp.event = mlx5_ib_qp_event; if (init_attr->qp_type == IB_QPT_RAW_PACKET || qp->flags & IB_QP_CREATE_SOURCE_QPN) { qp->raw_packet_qp.sq.ubuffer.buf_addr = ucmd->sq_buf_addr; @@ -2415,8 +2416,6 @@ static int create_user_qp(struct mlx5_ib_dev *dev, struct ib_pd *pd, if (err) goto err_create; - base->container_mibqp = qp; - base->mqp.event = mlx5_ib_qp_event; if (MLX5_CAP_GEN(mdev, ece_support)) params->resp.ece_options = MLX5_GET(create_qp_out, out, ece); @@ -2545,14 +2544,13 @@ static int create_kernel_qp(struct mlx5_ib_dev *dev, struct ib_pd *pd, MLX5_CAP_GEN(mdev, go_back_n)) MLX5_SET(qpc, qpc, retry_mode, MLX5_QP_RM_GO_BACK_N); + base->container_mibqp = qp; + base->mqp.event = mlx5_ib_qp_event; err = mlx5_qpc_create_qp(dev, &base->mqp, in, inlen, out); kvfree(in); if (err) goto err_create; - base->container_mibqp = qp; - base->mqp.event = mlx5_ib_qp_event; - get_cqs(qp->type, attr->send_cq, attr->recv_cq, &send_cq, &recv_cq); spin_lock_irqsave(&dev->reset_flow_resource_lock, flags); diff --git a/drivers/infiniband/hw/mlx5/qpc.c b/drivers/infiniband/hw/mlx5/qpc.c index 67ed45f3ae17..9272e1ef8113 100644 --- a/drivers/infiniband/hw/mlx5/qpc.c +++ b/drivers/infiniband/hw/mlx5/qpc.c @@ -146,6 +146,8 @@ static int rsc_event_notifier(struct notifier_block *nb, case MLX5_RES_RQ: case MLX5_RES_SQ: qp = (struct mlx5_core_qp *)common; + if (WARN_ON_ONCE(!qp->event)) + goto out; qp->event(qp, event_type); /* Need to put resource in event handler */ return NOTIFY_OK; @@ -258,6 +260,14 @@ int mlx5_qpc_create_qp(struct mlx5_ib_dev *dev, struct mlx5_core_qp *qp, qp->uid = MLX5_GET(create_qp_in, in, uid); qp->qpn = MLX5_GET(create_qp_out, out, qpn); + /* Set ibqp.qp_num before create_resource_common() inserts the QP into + * the radix tree and makes it visible to EQE processing. The + * assignment in create_qp() happens only after this function returns, + * leaving a window where an arriving EQE would observe qp_num == 0. + * create_qp() still overrides this with 0/1 for QP0/QP1, and sets it + * independently for DCT (which does not go through this function). + */ + to_mibqp(qp)->ibqp.qp_num = qp->qpn; err = create_resource_common(dev, qp, MLX5_RES_QP); if (err) diff --git a/drivers/infiniband/hw/vmw_pvrdma/pvrdma_qp.c b/drivers/infiniband/hw/vmw_pvrdma/pvrdma_qp.c index 98b2a0090bf2..3017a4080235 100644 --- a/drivers/infiniband/hw/vmw_pvrdma/pvrdma_qp.c +++ b/drivers/infiniband/hw/vmw_pvrdma/pvrdma_qp.c @@ -270,7 +270,8 @@ int pvrdma_create_qp(struct ib_qp *ibqp, struct ib_qp_init_attr *init_attr, /* set qp->sq.wqe_cnt, shift, buf_size.. */ qp->rumem = ib_umem_get(ibqp->device, ucmd.rbuf_addr, - ucmd.rbuf_size, 0); + ucmd.rbuf_size, + IB_ACCESS_LOCAL_WRITE); if (IS_ERR(qp->rumem)) { ret = PTR_ERR(qp->rumem); goto err_qp; @@ -282,7 +283,8 @@ int pvrdma_create_qp(struct ib_qp *ibqp, struct ib_qp_init_attr *init_attr, } qp->sumem = ib_umem_get(ibqp->device, ucmd.sbuf_addr, - ucmd.sbuf_size, 0); + ucmd.sbuf_size, + IB_ACCESS_LOCAL_WRITE); if (IS_ERR(qp->sumem)) { if (!is_srq) ib_umem_release(qp->rumem); diff --git a/drivers/infiniband/hw/vmw_pvrdma/pvrdma_srq.c b/drivers/infiniband/hw/vmw_pvrdma/pvrdma_srq.c index bdc2703532c6..99748f0f296d 100644 --- a/drivers/infiniband/hw/vmw_pvrdma/pvrdma_srq.c +++ b/drivers/infiniband/hw/vmw_pvrdma/pvrdma_srq.c @@ -146,7 +146,8 @@ int pvrdma_create_srq(struct ib_srq *ibsrq, struct ib_srq_init_attr *init_attr, goto err_srq; } - srq->umem = ib_umem_get(ibsrq->device, ucmd.buf_addr, ucmd.buf_size, 0); + srq->umem = ib_umem_get(ibsrq->device, ucmd.buf_addr, ucmd.buf_size, + IB_ACCESS_LOCAL_WRITE); if (IS_ERR(srq->umem)) { ret = PTR_ERR(srq->umem); goto err_srq; diff --git a/drivers/infiniband/ulp/rtrs/rtrs-clt.c b/drivers/infiniband/ulp/rtrs/rtrs-clt.c index dbce23eabcfd..3525508fe032 100644 --- a/drivers/infiniband/ulp/rtrs/rtrs-clt.c +++ b/drivers/infiniband/ulp/rtrs/rtrs-clt.c @@ -582,25 +582,21 @@ static struct ib_cqe io_comp_cqe = { .done = rtrs_clt_rdma_done }; -/* - * Post x2 empty WRs: first is for this RDMA with IMM, - * second is for RECV with INV, which happened earlier. - */ -static int rtrs_post_recv_empty_x2(struct rtrs_con *con, struct ib_cqe *cqe) +static int rtrs_clt_repost_recv(struct rtrs_clt_con *con) { - struct ib_recv_wr wr_arr[2], *wr; - int i; + struct rtrs_clt_path *clt_path = to_clt_path(con->c.path); + int err; - memset(wr_arr, 0, sizeof(wr_arr)); - for (i = 0; i < ARRAY_SIZE(wr_arr); i++) { - wr = &wr_arr[i]; - wr->wr_cqe = cqe; - if (i) - /* Chain backwards */ - wr->next = &wr_arr[i - 1]; - } + if (READ_ONCE(clt_path->state) != RTRS_CLT_CONNECTED) + return 0; - return ib_post_recv(con->qp, wr, NULL); + err = rtrs_post_recv_empty(&con->c, &io_comp_cqe); + if (err) { + rtrs_err(con->c.path, "rtrs_post_recv_empty(): %pe\n", + ERR_PTR(err)); + rtrs_rdma_error_recovery(con); + } + return err; } static void rtrs_clt_rdma_done(struct ib_cq *cq, struct ib_wc *wc) @@ -661,19 +657,7 @@ static void rtrs_clt_rdma_done(struct ib_cq *cq, struct ib_wc *wc) rtrs_wrn(con->c.path, "Unknown IMM type %u\n", imm_type); } - if (w_inval) - /* - * Post x2 empty WRs: first is for this RDMA with IMM, - * second is for RECV with INV, which happened earlier. - */ - err = rtrs_post_recv_empty_x2(&con->c, &io_comp_cqe); - else - err = rtrs_post_recv_empty(&con->c, &io_comp_cqe); - if (err) { - rtrs_err(con->c.path, "rtrs_post_recv_empty(): %d\n", - err); - rtrs_rdma_error_recovery(con); - } + rtrs_clt_repost_recv(con); break; case IB_WC_RECV: /* @@ -689,6 +673,7 @@ static void rtrs_clt_rdma_done(struct ib_cq *cq, struct ib_wc *wc) return rtrs_clt_rkey_rsp_done(con, wc); } + rtrs_clt_repost_recv(con); break; case IB_WC_RDMA_WRITE: /* @@ -1710,7 +1695,7 @@ static int create_con_cq_qp(struct rtrs_clt_con *con) /* QD * (REQ + RSP + FR REGS or INVS) + drain */ clt_path->queue_depth * 4 + 1); max_recv_wr = min_t(int, wr_limit, - clt_path->queue_depth * 3 + 1); + clt_path->queue_depth * 2 + 1); max_send_sge = 2; } atomic_set(&con->c.sq_wr_avail, max_send_wr); diff --git a/drivers/input/ff-core.c b/drivers/input/ff-core.c index 66f7ffe8c7e0..34fb744ec50c 100644 --- a/drivers/input/ff-core.c +++ b/drivers/input/ff-core.c @@ -339,7 +339,7 @@ EXPORT_SYMBOL_GPL(input_ff_create); * * This function is only needed in error path as input core will * automatically free force feedback structures when device is - * destroyed. + * unregistered or destroyed. */ void input_ff_destroy(struct input_dev *dev) { diff --git a/drivers/input/ff-memless.c b/drivers/input/ff-memless.c index e0c1c61aae71..ba910b08ceb9 100644 --- a/drivers/input/ff-memless.c +++ b/drivers/input/ff-memless.c @@ -483,15 +483,7 @@ static void ml_ff_destroy(struct ff_device *ff) { struct ml_device *ml = ff->private; - /* - * Even though we stop all playing effects when tearing down - * an input device (via input_device_flush() that calls into - * input_ff_flush() that stops and erases all effects), we - * do not actually stop the timer, and therefore we should - * do it here. - */ - timer_delete_sync(&ml->timer); - + timer_shutdown_sync(&ml->timer); kfree(ml->private); } diff --git a/drivers/input/input.c b/drivers/input/input.c index 9907dd9ec880..8df346f1ca42 100644 --- a/drivers/input/input.c +++ b/drivers/input/input.c @@ -2196,6 +2196,8 @@ static void __input_unregister_device(struct input_dev *dev) } device_del(&dev->dev); + + input_ff_destroy(dev); } static void devm_input_device_unregister(struct device *dev, void *res) diff --git a/drivers/iommu/amd/init.c b/drivers/iommu/amd/init.c index c4694ff364db..3768be55b8e6 100644 --- a/drivers/iommu/amd/init.c +++ b/drivers/iommu/amd/init.c @@ -3486,6 +3486,7 @@ static __init void iommu_snp_enable(void) return; disable_snp: + amd_iommu_snp_en = false; cc_platform_clear(CC_ATTR_HOST_SEV_SNP); #endif } diff --git a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c index 84dff2f06bcd..8a678910a18c 100644 --- a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +++ b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c @@ -3535,6 +3535,9 @@ static int arm_smmu_insert_master(struct arm_smmu_device *smmu, return -ENOMEM; master->num_streams = fwspec->num_ids; + for (i = 0; i < fwspec->num_ids; i++) + RB_CLEAR_NODE(&master->streams[i].node); + mutex_lock(&smmu->streams_mutex); for (i = 0; i < fwspec->num_ids; i++) { struct arm_smmu_stream *new_stream = &master->streams[i]; @@ -3570,7 +3573,9 @@ static int arm_smmu_insert_master(struct arm_smmu_device *smmu, if (ret) { for (i--; i >= 0; i--) - rb_erase(&master->streams[i].node, &smmu->streams); + if (!RB_EMPTY_NODE(&master->streams[i].node)) + rb_erase(&master->streams[i].node, + &smmu->streams); kfree(master->streams); } mutex_unlock(&smmu->streams_mutex); @@ -3589,7 +3594,8 @@ static void arm_smmu_remove_master(struct arm_smmu_master *master) mutex_lock(&smmu->streams_mutex); for (i = 0; i < fwspec->num_ids; i++) - rb_erase(&master->streams[i].node, &smmu->streams); + if (!RB_EMPTY_NODE(&master->streams[i].node)) + rb_erase(&master->streams[i].node, &smmu->streams); mutex_unlock(&smmu->streams_mutex); kfree(master->streams); diff --git a/drivers/irqchip/irq-mst-intc.c b/drivers/irqchip/irq-mst-intc.c index 7f760f555a76..d380030eda93 100644 --- a/drivers/irqchip/irq-mst-intc.c +++ b/drivers/irqchip/irq-mst-intc.c @@ -263,6 +263,9 @@ static int __init mst_intc_of_init(struct device_node *dn, of_property_read_u32_index(dn, "mstar,irqs-map-range", 1, &irq_end)) return -EINVAL; + if (irq_end < irq_start || irq_end - irq_start >= MST_INTC_MAX_IRQS) + return -EINVAL; + cd = kzalloc(sizeof(*cd), GFP_KERNEL); if (!cd) return -ENOMEM; diff --git a/drivers/irqchip/irq-sifive-plic.c b/drivers/irqchip/irq-sifive-plic.c index ca70641982ed..0995e1fdd5b4 100644 --- a/drivers/irqchip/irq-sifive-plic.c +++ b/drivers/irqchip/irq-sifive-plic.c @@ -97,7 +97,7 @@ static int plic_irq_set_type(struct irq_data *d, unsigned int type); static void __plic_toggle(void __iomem *enable_base, int hwirq, int enable) { u32 __iomem *reg = enable_base + (hwirq / 32) * sizeof(u32); - u32 hwirq_mask = 1 << (hwirq % 32); + u32 hwirq_mask = BIT(hwirq % 32); if (enable) writel(readl(reg) | hwirq_mask, reg); diff --git a/drivers/md/dm-cache-metadata.c b/drivers/md/dm-cache-metadata.c index db77ba58f64a..ab7d11d8e7ba 100644 --- a/drivers/md/dm-cache-metadata.c +++ b/drivers/md/dm-cache-metadata.c @@ -766,6 +766,7 @@ static struct dm_cache_metadata *metadata_open(struct block_device *bdev, return ERR_PTR(-ENOMEM); } + INIT_LIST_HEAD(&cmd->list); cmd->version = metadata_version; refcount_set(&cmd->ref_count, 1); init_rwsem(&cmd->root_lock); @@ -1432,7 +1433,8 @@ static int __load_mappings(struct dm_cache_metadata *cmd, from_cblock(cmd->cache_blocks), &cmd->dirty_cursor); if (r) { - dm_array_cursor_end(&cmd->hint_cursor); + if (hints_valid) + dm_array_cursor_end(&cmd->hint_cursor); dm_array_cursor_end(&cmd->mapping_cursor); return r; } diff --git a/drivers/md/dm-cache-target.c b/drivers/md/dm-cache-target.c index 849c4866e632..663b1c0fa41d 100644 --- a/drivers/md/dm-cache-target.c +++ b/drivers/md/dm-cache-target.c @@ -2550,6 +2550,7 @@ static int cache_create(struct cache_args *ca, struct cache **result) if (IS_ERR(cache->copier)) { *error = "could not create kcopyd client"; r = PTR_ERR(cache->copier); + cache->copier = NULL; goto bad; } diff --git a/drivers/md/dm-crypt.c b/drivers/md/dm-crypt.c index 893355ee7d8e..d8e9791079b3 100644 --- a/drivers/md/dm-crypt.c +++ b/drivers/md/dm-crypt.c @@ -2039,8 +2039,9 @@ static void kcryptd_crypt_write_io_submit(struct dm_crypt_io *io, int async) /* crypt_convert should have filled the clone bio */ BUG_ON(io->ctx.iter_out.bi_size); - if ((likely(!async) && test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags)) || - test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags)) { + if (likely(!async) && + (test_bit(DM_CRYPT_NO_OFFLOAD, &cc->flags) || + test_bit(DM_CRYPT_NO_WRITE_WORKQUEUE, &cc->flags))) { dm_submit_bio_remap(io->base_bio, clone); return; } @@ -2905,8 +2906,11 @@ static int crypt_ctr_auth_cipher(struct crypt_config *cc, char *cipher_api) char *start, *end, *mac_alg = NULL; struct crypto_ahash *mac; - if (!strstarts(cipher_api, "authenc(")) + if (!strstarts(cipher_api, "authenc(")) { + if (test_bit(CRYPT_KEY_MAC_SIZE_SET, &cc->cipher_flags)) + return -EINVAL; return 0; + } start = strchr(cipher_api, '('); end = strchr(cipher_api, ','); @@ -3287,6 +3291,14 @@ static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv) ti->error = "Cannot allocate encryption context"; return -ENOMEM; } + + ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL); + if (ret < 0) { + ti->error = "Cannot initialize page counter"; + kfree_sensitive(cc); + return ret; + } + cc->key_size = key_size; cc->sector_size = (1 << SECTOR_SHIFT); cc->sector_shift = 0; @@ -3298,10 +3310,6 @@ static int crypt_ctr(struct dm_target *ti, unsigned int argc, char **argv) crypt_calculate_pages_per_client(); spin_unlock(&dm_crypt_clients_lock); - ret = percpu_counter_init(&cc->n_allocated_pages, 0, GFP_KERNEL); - if (ret < 0) - goto bad; - /* Optional parameters need to be read before cipher constructor */ if (argc > 5) { ret = crypt_ctr_optional(ti, argc - 5, &argv[5]); diff --git a/drivers/md/dm-integrity.c b/drivers/md/dm-integrity.c index 400bb77f33ed..ca50115035fc 100644 --- a/drivers/md/dm-integrity.c +++ b/drivers/md/dm-integrity.c @@ -2906,6 +2906,11 @@ static void integrity_commit(struct work_struct *w) spin_lock_irq(&ic->endio_wait.lock); flushes = bio_list_get(&ic->flush_bio_list); + if (unlikely(dm_integrity_failed(ic))) { + wake_up_locked(&ic->endio_wait); + spin_unlock_irq(&ic->endio_wait.lock); + goto release_flush_bios; + } if (unlikely(ic->mode != 'J')) { spin_unlock_irq(&ic->endio_wait.lock); dm_integrity_flush_buffers(ic, true); @@ -3886,6 +3891,24 @@ static bool superblock_changed(struct dm_integrity_c *ic) memcmp(ic->sb->salt, ic->sb_copy->salt, SALT_SIZE) != 0; } +/* + * The superblock is authenticated only if fix_hmac and journal_mac are used, + * so SB_FLAG_DIRTY_BITMAP may have been set by someone who doesn't know the + * key. Apply the policy that the constructor applies to SB_FLAG_RECALCULATING. + */ +static bool dm_integrity_may_recalc_dirty_bitmap(struct dm_integrity_c *ic) +{ + if (!ic->internal_hash) { + DMERR("Dirty bitmap found, but internal_hash is not used"); + return false; + } + if (dm_integrity_disable_recalculate(ic)) { + DMERR("Dirty bitmap found, but HMAC recalculation requires \"legacy_recalculate\""); + return false; + } + return true; +} + static void dm_integrity_resume(struct dm_target *ti) { struct dm_integrity_c *ic = ti->private; @@ -3975,8 +3998,10 @@ static void dm_integrity_resume(struct dm_target *ti) if (!(ic->sb->log2_blocks_per_bitmap_bit == ic->log2_blocks_per_bitmap_bit && block_bitmap_op(ic, ic->journal, 0, ic->provided_data_sectors, BITMAP_OP_TEST_ALL_CLEAR)) || ic->reset_recalculate_flag) { - ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING); - ic->sb->recalc_sector = cpu_to_le64(0); + if (dm_integrity_may_recalc_dirty_bitmap(ic)) { + ic->sb->flags |= cpu_to_le32(SB_FLAG_RECALCULATING); + ic->sb->recalc_sector = cpu_to_le64(0); + } } init_journal(ic, 0, ic->journal_sections, 0); replay_journal(ic); @@ -5398,7 +5423,6 @@ static int dm_integrity_ctr(struct dm_target *ti, unsigned int argc, char **argv r = create_journal(ic, &ti->error); if (r) goto bad; - } if (ic->mode == 'B') { diff --git a/drivers/md/dm-log-userspace-base.c b/drivers/md/dm-log-userspace-base.c index 40e21bec4792..7cccf0150acb 100644 --- a/drivers/md/dm-log-userspace-base.c +++ b/drivers/md/dm-log-userspace-base.c @@ -294,9 +294,11 @@ static int userspace_ctr(struct dm_dirty_log *log, struct dm_target *ti, } r = dm_get_device(ti, devices_rdata, dm_table_get_mode(ti->table), &lc->log_dev); - if (r) + if (r) { DMERR("Failed to register %s with device-mapper", devices_rdata); + goto out; + } } if (lc->integrated_flush) { @@ -315,6 +317,8 @@ static int userspace_ctr(struct dm_dirty_log *log, struct dm_target *ti, out: kfree(devices_rdata); if (r) { + if (lc->log_dev) + dm_put_device(lc->ti, lc->log_dev); mempool_exit(&lc->flush_entry_pool); kfree(lc); kfree(ctr_str); diff --git a/drivers/md/dm-mpath.c b/drivers/md/dm-mpath.c index 3a25ec2993dc..c8416f9f16e2 100644 --- a/drivers/md/dm-mpath.c +++ b/drivers/md/dm-mpath.c @@ -803,7 +803,8 @@ static void queue_if_no_path_timeout_work(struct timer_list *t) static void enable_nopath_timeout(struct multipath *m) { unsigned long queue_if_no_path_timeout = - READ_ONCE(queue_if_no_path_timeout_secs) * HZ; + min_t(unsigned long, READ_ONCE(queue_if_no_path_timeout_secs), + MAX_JIFFY_OFFSET / HZ) * HZ; lockdep_assert_held(&m->lock); @@ -1084,8 +1085,9 @@ static int parse_hw_handler(struct dm_arg_set *as, struct multipath *m) if (hw_argc > 1) { char *p; - int i, j, len = 4; + int i, j, len; + len = snprintf(NULL, 0, "%d", hw_argc - 1) + 1; for (i = 0; i <= hw_argc - 2; i++) len += strlen(as->argv[i]) + 1; p = m->hw_handler_params = kzalloc(len, GFP_KERNEL); diff --git a/drivers/md/dm-pcache/backing_dev.c b/drivers/md/dm-pcache/backing_dev.c index 7165fc0364bb..0c15bb01068e 100644 --- a/drivers/md/dm-pcache/backing_dev.c +++ b/drivers/md/dm-pcache/backing_dev.c @@ -336,9 +336,9 @@ struct pcache_backing_dev_req *backing_dev_req_create(struct pcache_backing_dev return backing_req; } -void backing_dev_flush(struct pcache_backing_dev *backing_dev) +int backing_dev_flush(struct pcache_backing_dev *backing_dev) { - blkdev_issue_flush(backing_dev->dm_dev->bdev); + return blkdev_issue_flush(backing_dev->dm_dev->bdev); } int pcache_backing_init(void) diff --git a/drivers/md/dm-pcache/backing_dev.h b/drivers/md/dm-pcache/backing_dev.h index b371cba483b9..8422e5e76e29 100644 --- a/drivers/md/dm-pcache/backing_dev.h +++ b/drivers/md/dm-pcache/backing_dev.h @@ -120,7 +120,7 @@ struct pcache_backing_dev_req *backing_dev_req_alloc(struct pcache_backing_dev * struct pcache_backing_dev_req_opts *opts); void backing_dev_req_init(struct pcache_backing_dev_req *backing_req, struct pcache_backing_dev_req_opts *opts); -void backing_dev_flush(struct pcache_backing_dev *backing_dev); +int backing_dev_flush(struct pcache_backing_dev *backing_dev); int pcache_backing_init(void); void pcache_backing_exit(void); diff --git a/drivers/md/dm-pcache/cache_writeback.c b/drivers/md/dm-pcache/cache_writeback.c index c8a4c8110a58..e09560f172dd 100644 --- a/drivers/md/dm-pcache/cache_writeback.c +++ b/drivers/md/dm-pcache/cache_writeback.c @@ -18,12 +18,18 @@ static void writeback_ctx_end(struct pcache_cache *cache, int ret) return; if (!cache->writeback_ctx.ret) { - backing_dev_flush(cache->backing_dev); - - mutex_lock(&cache->dirty_tail_lock); - cache_pos_advance(&cache->dirty_tail, cache->writeback_ctx.advance); - cache_encode_dirty_tail(cache); - mutex_unlock(&cache->dirty_tail_lock); + ret = backing_dev_flush(cache->backing_dev); + if (ret) { + pcache_dev_err(CACHE_TO_PCACHE(cache), + "failed to flush backing device: %d", ret); + cache->writeback_ctx.ret = ret; + } else { + mutex_lock(&cache->dirty_tail_lock); + cache_pos_advance(&cache->dirty_tail, + cache->writeback_ctx.advance); + cache_encode_dirty_tail(cache); + mutex_unlock(&cache->dirty_tail_lock); + } } queue_delayed_work(cache_get_wq(cache), &cache->writeback_work, 0); } @@ -76,8 +82,16 @@ static inline bool is_cache_clean(struct pcache_cache *cache, struct pcache_cach void cache_writeback_exit(struct pcache_cache *cache) { + int ret; + cancel_delayed_work_sync(&cache->writeback_work); - backing_dev_flush(cache->backing_dev); + + ret = backing_dev_flush(cache->backing_dev); + if (ret) + pcache_dev_err(CACHE_TO_PCACHE(cache), + "failed to flush backing device during exit: %d", + ret); + cache_tree_exit(&cache->writeback_key_tree); } diff --git a/drivers/md/dm-raid.c b/drivers/md/dm-raid.c index 9eee490c029e..5d81882be9a5 100644 --- a/drivers/md/dm-raid.c +++ b/drivers/md/dm-raid.c @@ -2420,7 +2420,8 @@ static int super_init_validation(struct raid_set *rs, struct md_rdev *rdev) */ if (!test_bit(FirstUse, &r->flags) && (r->raid_disk >= 0)) { role = le32_to_cpu(sb2->array_position); - if (role < 0) + /* Bound @role before it indexes the failed_devices stack bitmap. */ + if (role < 0 || role >= rs->raid_disks) continue; if (role != r->raid_disk) { @@ -3333,7 +3334,7 @@ static void raid_dtr(struct dm_target *ti) rs->md.dm_gendisk = NULL; mddev_unlock(&rs->md); - if (work_pending(&rs->md.event_work)) + if (rs->md.event_work.func) flush_work(&rs->md.event_work); raid_set_free(rs); } diff --git a/drivers/md/dm-snap.c b/drivers/md/dm-snap.c index c04e570756ef..b44d9d10b142 100644 --- a/drivers/md/dm-snap.c +++ b/drivers/md/dm-snap.c @@ -1364,8 +1364,10 @@ static int snapshot_ctr(struct dm_target *ti, unsigned int argc, char **argv) ti->private = s; ti->num_flush_bios = num_flush_bios; - if (s->discard_zeroes_cow) + if (s->discard_zeroes_cow) { ti->num_discard_bios = (s->discard_passdown_origin ? 2 : 1); + ti->max_discard_granularity = true; + } ti->per_io_data_size = sizeof(struct dm_snap_tracked_chunk); /* Add snapshot to the list of snapshots for this origin */ @@ -1952,8 +1954,8 @@ static void zero_exception(struct dm_snapshot *s, struct dm_exception *e, static bool io_overlaps_chunk(struct dm_snapshot *s, struct bio *bio) { - return bio->bi_iter.bi_size == - (s->store->chunk_size << SECTOR_SHIFT); + return bio->bi_iter.bi_size == (s->store->chunk_size << SECTOR_SHIFT) && + !(bio->bi_iter.bi_sector & s->store->chunk_mask); } static int snapshot_map(struct dm_target *ti, struct bio *bio) @@ -2013,11 +2015,13 @@ static int snapshot_map(struct dm_target *ti, struct bio *bio) e = dm_lookup_exception(&s->complete, chunk); if (e) { remap_exception(s, e, bio, chunk); - if (unlikely(bio_op(bio) == REQ_OP_DISCARD) && - io_overlaps_chunk(s, bio)) { + if (unlikely(bio_op(bio) == REQ_OP_DISCARD)) { dm_exception_table_unlock(&lock); up_read(&s->lock); - zero_exception(s, e, bio, chunk); + if (io_overlaps_chunk(s, bio)) + zero_exception(s, e, bio, chunk); + else + bio_endio(bio); r = DM_MAPIO_SUBMITTED; /* discard is not issued */ goto out; } @@ -2420,7 +2424,7 @@ static void snapshot_io_hints(struct dm_target *ti, struct queue_limits *limits) snap = snap_src; /* All discards are split on chunk_size boundary */ - limits->discard_granularity = snap->store->chunk_size; + limits->discard_granularity = snap->store->chunk_size << SECTOR_SHIFT; limits->max_hw_discard_sectors = snap->store->chunk_size; up_read(&_origins_lock); diff --git a/drivers/md/dm-sysfs.c b/drivers/md/dm-sysfs.c index bfaef27ca79f..7eb32941cf7f 100644 --- a/drivers/md/dm-sysfs.c +++ b/drivers/md/dm-sysfs.c @@ -132,9 +132,20 @@ static const struct kobj_type dm_ktype = { */ int dm_sysfs_init(struct mapped_device *md) { - return kobject_init_and_add(dm_kobject(md), &dm_ktype, - &disk_to_dev(dm_disk(md))->kobj, - "%s", "dm"); + struct kobject *kobj = dm_kobject(md); + int r; + + /* The kobject must be zeroed before calling kobject_init */ + memset(kobj, 0, sizeof(struct kobject)); + r = kobject_init_and_add(kobj, &dm_ktype, + &disk_to_dev(dm_disk(md))->kobj, + "%s", "dm"); + if (unlikely(r)) { + /* Weird semantics - we must call kobject_put on failure */ + dm_sysfs_exit(md); + return r; + } + return 0; } /* diff --git a/drivers/md/dm-thin-metadata.c b/drivers/md/dm-thin-metadata.c index 9224d91fca71..6db67118339a 100644 --- a/drivers/md/dm-thin-metadata.c +++ b/drivers/md/dm-thin-metadata.c @@ -1225,10 +1225,13 @@ static int __create_snap(struct dm_pool_metadata *pmd, __close_device(td); if (r) - goto bad; + goto bad2; return 0; +bad2: + list_del(&td->list); + kfree(td); bad: dm_btree_remove(&pmd->tl_info, pmd->root, &key, &pmd->root); dm_btree_remove(&pmd->details_info, pmd->details_root, diff --git a/drivers/md/dm-thin.c b/drivers/md/dm-thin.c index c84149ba4e38..0ff98c93b4aa 100644 --- a/drivers/md/dm-thin.c +++ b/drivers/md/dm-thin.c @@ -1705,6 +1705,7 @@ static void break_up_discard_bio(struct thin_c *tc, dm_block_t begin, dm_block_t (void) build_key(tc->td, PHYSICAL, data_begin, data_begin + len, &data_key); if (bio_detain(tc->pool, &data_key, NULL, &data_cell)) { /* contention, we'll give up with this range */ + virt_begin += len; data_begin += len; continue; } @@ -2544,7 +2545,9 @@ static void set_pool_mode(struct pool *pool, enum pool_mode new_mode) struct pool_c *pt = pool->ti->private; bool needs_check = dm_pool_metadata_needs_check(pool->pmd); enum pool_mode old_mode = get_pool_mode(pool); - unsigned long no_space_timeout = READ_ONCE(no_space_timeout_secs) * HZ; + unsigned long no_space_timeout = + min_t(unsigned long, READ_ONCE(no_space_timeout_secs), + MAX_JIFFY_OFFSET / HZ) * HZ; /* * Never allow the pool to transition to PM_WRITE mode if user @@ -3148,7 +3151,7 @@ static int parse_pool_features(struct dm_arg_set *as, struct pool_features *pf, const char *arg_name; static const struct dm_arg _args[] = { - {0, 4, "Invalid number of pool feature arguments"}, + {0, 5, "Invalid number of pool feature arguments"}, }; /* diff --git a/drivers/md/dm-verity-target.c b/drivers/md/dm-verity-target.c index 2c754144e929..995cb0abd3b2 100644 --- a/drivers/md/dm-verity-target.c +++ b/drivers/md/dm-verity-target.c @@ -155,6 +155,15 @@ static void verity_hash_at_level(struct dm_verity *v, sector_t block, int level, *offset = idx << (v->hash_dev_block_bits - v->hash_per_block_bits); } +/* + * Skip verity work in response to I/O error when system is shutting down. + */ +static inline bool verity_is_system_shutting_down(void) +{ + return system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF + || system_state == SYSTEM_RESTART; +} + /* * Handle verification errors. */ @@ -204,6 +213,15 @@ static int verity_handle_err(struct dm_verity *v, enum verity_block_type type, if (v->mode == DM_VERITY_MODE_LOGGING) return 0; + /* + * Devices may already be quiesced (e.g. UFS set offline by its + * shutdown hook), so a failure here does not imply corruption. Fail + * the I/O but do not restart or panic, which would also override the + * reboot reason of the shutdown already in progress. + */ + if (verity_is_system_shutting_down()) + return 1; + if (v->mode == DM_VERITY_MODE_RESTART) kernel_restart("dm-verity device corrupted"); @@ -523,15 +541,6 @@ static int verity_verify_io(struct dm_verity_io *io) return 0; } -/* - * Skip verity work in response to I/O error when system is shutting down. - */ -static inline bool verity_is_system_shutting_down(void) -{ - return system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF - || system_state == SYSTEM_RESTART; -} - static void restart_io_error(struct work_struct *w) { kernel_restart("dm-verity device has I/O error"); diff --git a/drivers/md/dm-zone.c b/drivers/md/dm-zone.c index 046609b2eea0..716bd6f35411 100644 --- a/drivers/md/dm-zone.c +++ b/drivers/md/dm-zone.c @@ -33,6 +33,8 @@ static int dm_blk_do_report_zones(struct mapped_device *md, struct dm_table *t, nr_zones - args->zone_idx); if (ret < 0) return ret; + if (!ret) + return -EIO; } while (args->zone_idx < nr_zones && args->next_sector < get_capacity(md->disk)); diff --git a/drivers/md/dm-zoned-reclaim.c b/drivers/md/dm-zoned-reclaim.c index 76e2c6868548..a80c3be5bd7a 100644 --- a/drivers/md/dm-zoned-reclaim.c +++ b/drivers/md/dm-zoned-reclaim.c @@ -290,7 +290,13 @@ static int dmz_reclaim_rnd_data(struct dmz_reclaim *zrc, struct dm_zone *dzone) again: szone = dmz_alloc_zone(zmd, zrc->dev_idx, alloc_flags | DMZ_ALLOC_RECLAIM); - if (!szone && alloc_flags == DMZ_ALLOC_SEQ && dmz_nr_cache_zones(zmd)) { + /* + * If no free sequential zone is available, a cache zone can still be + * moved into a free random zone of the zoned device, which frees cache + * space. Do not do this for a random zone: moving it into another + * random zone frees nothing and, on an idle target, repeats forever. + */ + if (!szone && alloc_flags == DMZ_ALLOC_SEQ && dmz_is_cache(dzone)) { alloc_flags = DMZ_ALLOC_RND; goto again; } @@ -539,6 +545,16 @@ static void dmz_reclaim_work(struct work_struct *work) dmz_nr_rnd_zones(zmd, zrc->dev_idx)); ret = dmz_do_reclaim(zrc); + if (ret == -ENOSPC || ret == -EBUSY) { + /* + * No zone to copy into (-ENOSPC) or no zone to reclaim + * (-EBUSY): retrying at once cannot make progress and would + * spin. Poll again after the idle period instead, without + * postponing work that an allocation has already queued. + */ + queue_delayed_work(zrc->wq, &zrc->work, DMZ_IDLE_PERIOD); + return; + } if (ret && ret != -EINTR) { if (!dmz_check_dev(zmd)) return; diff --git a/drivers/md/dm.c b/drivers/md/dm.c index 077bf8b16a0b..bc5c501a294c 100644 --- a/drivers/md/dm.c +++ b/drivers/md/dm.c @@ -983,7 +983,7 @@ static void __dm_io_complete(struct dm_io *io, bool first_stage) if (requeued) return; - if (unlikely(requeue_flush_with_data)) { + if (unlikely(requeue_flush_with_data) && !io_error) { /* * Preflush done for flush with data, reissue * without REQ_PREFLUSH. @@ -991,7 +991,7 @@ static void __dm_io_complete(struct dm_io *io, bool first_stage) bio->bi_opf &= ~REQ_PREFLUSH; queue_io(md, bio); } else { - /* done with normal IO or empty flush */ + /* done with normal IO, empty flush or failed preflush */ if (io_error) bio->bi_status = io_error; bio_endio(bio); @@ -1924,8 +1924,13 @@ static blk_status_t __send_zone_reset_all(struct clone_info *ci) break; } - /* Release the reference that alloc_io() took for submission. */ - atomic_sub(1, &ci->io->io_count); + /* + * Release the reference that alloc_io() took for submission. On error, + * that reference was not consumed: dm_split_and_process_bio() releases + * it on the error path, so do not release it here a second time. + */ + if (sts == BLK_STS_OK) + atomic_dec(&ci->io->io_count); return sts; } @@ -2591,13 +2596,17 @@ int dm_setup_md_queue(struct mapped_device *md, struct dm_table *t) WARN_ON_ONCE(type == DM_TYPE_NONE); + /* A failed setup may have left the queue initialized or the disk dead. */ + if (md->tag_set || test_bit(GD_DEAD, &md->disk->state)) + return -ENODEV; + if (type == DM_TYPE_REQUEST_BASED) { - md->disk->fops = &dm_rq_blk_dops; r = dm_mq_init_request_queue(md, t); if (r) { DMERR("Cannot initialize queue for request-based dm mapped device"); return r; } + md->disk->fops = &dm_rq_blk_dops; } r = dm_calculate_queue_limits(t, &limits); diff --git a/drivers/md/persistent-data/dm-btree-remove.c b/drivers/md/persistent-data/dm-btree-remove.c index aeec5b9a1dd5..19ba265181c4 100644 --- a/drivers/md/persistent-data/dm-btree-remove.c +++ b/drivers/md/persistent-data/dm-btree-remove.c @@ -253,7 +253,9 @@ static int __rebalance2(struct dm_btree_info *info, struct btree_node *parent, /* * Merge */ - node_copy(left, right, -nr_right); + ret = node_copy(left, right, -nr_right); + if (unlikely(ret)) + return ret; left->header.nr_entries = cpu_to_le32(nr_left + nr_right); delete_at(parent, r->index); @@ -315,13 +317,16 @@ static int delete_center_node(struct dm_btree_info *info, struct btree_node *par { uint32_t max_entries = le32_to_cpu(left->header.max_entries); unsigned int shift = min(max_entries - nr_left, nr_center); + int ret; if (nr_left + shift > max_entries) { DMERR("node shift out of bounds"); return -EINVAL; } - node_copy(left, center, -shift); + ret = node_copy(left, center, -shift); + if (unlikely(ret)) + return ret; left->header.nr_entries = cpu_to_le32(nr_left + shift); if (shift != nr_center) { @@ -333,7 +338,9 @@ static int delete_center_node(struct dm_btree_info *info, struct btree_node *par } node_shift(right, shift); - node_copy(center, right, shift); + ret = node_copy(center, right, shift); + if (unlikely(ret)) + return ret; right->header.nr_entries = cpu_to_le32(nr_right + shift); } *key_ptr(parent, r->index) = right->keys[0]; diff --git a/drivers/md/persistent-data/dm-btree.c b/drivers/md/persistent-data/dm-btree.c index 0c7a2e8d1846..727d13f81882 100644 --- a/drivers/md/persistent-data/dm-btree.c +++ b/drivers/md/persistent-data/dm-btree.c @@ -1582,7 +1582,13 @@ int dm_btree_cursor_begin(struct dm_btree_info *info, dm_block_t root, if (r) return r; - return find_leaf(c); + r = find_leaf(c); + if (unlikely(r)) { + dm_btree_cursor_end(c); + return r; + } + + return 0; } EXPORT_SYMBOL_GPL(dm_btree_cursor_begin); diff --git a/drivers/md/persistent-data/dm-space-map-common.c b/drivers/md/persistent-data/dm-space-map-common.c index 22a551c407da..833aefb0ab99 100644 --- a/drivers/md/persistent-data/dm-space-map-common.c +++ b/drivers/md/persistent-data/dm-space-map-common.c @@ -1190,17 +1190,20 @@ static dm_block_t disk_ll_max_entries(struct ll_disk *ll) static int disk_ll_commit(struct ll_disk *ll) { - int r = 0; + int r; unsigned int i; for (i = 0; i < IE_CACHE_SIZE; i++) { struct ie_cache *iec = ll->ie_cache + i; - if (iec->valid && iec->dirty) + if (iec->valid && iec->dirty) { r = ie_cache_writeback(ll, iec); + if (unlikely(r)) + return r; + } } - return r; + return 0; } int sm_ll_new_disk(struct ll_disk *ll, struct dm_transaction_manager *tm) diff --git a/drivers/media/rc/rc-main.c b/drivers/media/rc/rc-main.c index 2f1684a81eb1..be53f1bdc9c7 100644 --- a/drivers/media/rc/rc-main.c +++ b/drivers/media/rc/rc-main.c @@ -17,9 +17,8 @@ #include #include "rc-core-priv.h" -/* Sizes are in bytes, 256 bytes allows for 32 entries on x64 */ -#define IR_TAB_MIN_SIZE 256 -#define IR_TAB_MAX_SIZE 8192 +#define IR_TAB_MIN_ENTRIES 32 +#define IR_TAB_MAX_ENTRIES 1024 static const struct { const char *name; @@ -105,7 +104,6 @@ static struct rc_map_list *seek_rc_map(const char *name) struct rc_map *rc_map_get(const char *name) { - struct rc_map_list *map; map = seek_rc_map(name); @@ -202,7 +200,7 @@ static int scancode_to_u64(const struct input_keymap_entry *ke, u64 *scancode) * ir_create_table() - initializes a scancode table * @dev: the rc_dev device * @rc_map: the rc_map to initialize - * @name: name to assign to the table + * @map_name: name to assign to the table * @rc_proto: ir type to assign to the new table * @size: initial size of the table * @@ -212,23 +210,33 @@ static int scancode_to_u64(const struct input_keymap_entry *ke, u64 *scancode) * return: zero on success or a negative error code */ static int ir_create_table(struct rc_dev *dev, struct rc_map *rc_map, - const char *name, u64 rc_proto, size_t size) + const char *map_name, u64 rc_proto, size_t size) { - rc_map->name = kstrdup(name, GFP_KERNEL); - if (!rc_map->name) + struct rc_map_table *scan; + unsigned int alloc; + char *name; + + name = kstrdup(map_name, GFP_KERNEL); + if (!name) return -ENOMEM; - rc_map->rc_proto = rc_proto; - rc_map->alloc = roundup_pow_of_two(size * sizeof(struct rc_map_table)); - rc_map->size = rc_map->alloc / sizeof(struct rc_map_table); - rc_map->scan = kmalloc(rc_map->alloc, GFP_KERNEL); - if (!rc_map->scan) { - kfree(rc_map->name); - rc_map->name = NULL; + + alloc = roundup_pow_of_two(size); + scan = kmalloc_objs(struct rc_map_table, alloc, GFP_KERNEL); + if (!scan) { + kfree(name); return -ENOMEM; } - dev_dbg(&dev->dev, "Allocated space for %u keycode entries (%u bytes)\n", - rc_map->size, rc_map->alloc); + scoped_guard(spinlock_irqsave, &rc_map->lock) { + rc_map->name = name; + rc_map->scan = scan; + rc_map->rc_proto = rc_proto; + rc_map->len = 0; + rc_map->size = alloc; + } + + dev_dbg(&dev->dev, "Allocated space for %u keycode entries (%zu bytes)\n", + alloc, alloc * sizeof(struct rc_map_table)); return 0; } @@ -236,16 +244,26 @@ static int ir_create_table(struct rc_dev *dev, struct rc_map *rc_map, * ir_free_table() - frees memory allocated by a scancode table * @rc_map: the table whose mappings need to be freed * - * This routine will free memory alloctaed for key mappings used by given + * This routine will free memory allocated for key mappings used by given * scancode table. */ static void ir_free_table(struct rc_map *rc_map) { - rc_map->size = 0; - kfree(rc_map->name); - rc_map->name = NULL; - kfree(rc_map->scan); - rc_map->scan = NULL; + struct rc_map_table *scan; + const char *name; + + scoped_guard(spinlock_irqsave, &rc_map->lock) { + name = rc_map->name; + scan = rc_map->scan; + + rc_map->size = 0; + rc_map->len = 0; + rc_map->name = NULL; + rc_map->scan = NULL; + } + + kfree(name); + kfree(scan); } /** @@ -262,38 +280,38 @@ static void ir_free_table(struct rc_map *rc_map) static int ir_resize_table(struct rc_dev *dev, struct rc_map *rc_map, gfp_t gfp_flags) { - unsigned int oldalloc = rc_map->alloc; - unsigned int newalloc = oldalloc; - struct rc_map_table *oldscan = rc_map->scan; + unsigned int newsize = rc_map->size; struct rc_map_table *newscan; + lockdep_assert_held(&rc_map->lock); + if (rc_map->size == rc_map->len) { /* All entries in use -> grow keytable */ - if (rc_map->alloc >= IR_TAB_MAX_SIZE) + if (newsize >= IR_TAB_MAX_ENTRIES) return -ENOMEM; - newalloc *= 2; - dev_dbg(&dev->dev, "Growing table to %u bytes\n", newalloc); + newsize *= 2; + + dev_dbg(&dev->dev, "Growing table to %u entries\n", newsize); } - if ((rc_map->len * 3 < rc_map->size) && (oldalloc > IR_TAB_MIN_SIZE)) { + if (rc_map->len * 3 < rc_map->size && rc_map->size > IR_TAB_MIN_ENTRIES) { /* Less than 1/3 of entries in use -> shrink keytable */ - newalloc /= 2; - dev_dbg(&dev->dev, "Shrinking table to %u bytes\n", newalloc); + newsize /= 2; + dev_dbg(&dev->dev, "Shrinking table to %u entries\n", newsize); } - if (newalloc == oldalloc) + if (newsize == rc_map->size) return 0; - newscan = kmalloc(newalloc, gfp_flags); + newscan = krealloc_array(rc_map->scan, newsize, + sizeof(struct rc_map_table), gfp_flags); if (!newscan) return -ENOMEM; - memcpy(newscan, rc_map->scan, rc_map->len * sizeof(struct rc_map_table)); rc_map->scan = newscan; - rc_map->alloc = newalloc; - rc_map->size = rc_map->alloc / sizeof(struct rc_map_table); - kfree(oldscan); + rc_map->size = newsize; + return 0; } @@ -318,6 +336,8 @@ static unsigned int ir_update_mapping(struct rc_dev *dev, int old_keycode = rc_map->scan[index].keycode; int i; + lockdep_assert_held(&rc_map->lock); + /* Did the user wish to remove the mapping? */ if (new_keycode == KEY_RESERVED || new_keycode == KEY_UNKNOWN) { dev_dbg(&dev->dev, "#%d: Deleting scan 0x%04llx\n", @@ -373,6 +393,8 @@ static unsigned int ir_establish_scancode(struct rc_dev *dev, { unsigned int i; + lockdep_assert_held(&rc_map->lock); + /* * Unfortunately, some hardware-based IR decoders don't provide * all bits for the complete IR code. In general, they provide only @@ -397,7 +419,7 @@ static unsigned int ir_establish_scancode(struct rc_dev *dev, /* No previous mapping found, we might need to grow the table */ if (rc_map->size == rc_map->len) { if (!resize || ir_resize_table(dev, rc_map, GFP_ATOMIC)) - return -1U; + return UINT_MAX; } /* i is the proper index to insert our new keycode */ @@ -479,16 +501,18 @@ static int ir_setkeytable(struct rc_dev *dev, const struct rc_map *from) if (rc) return rc; - for (i = 0; i < from->size; i++) { - index = ir_establish_scancode(dev, rc_map, - from->scan[i].scancode, false); - if (index >= rc_map->len) { - rc = -ENOMEM; - break; - } + scoped_guard(spinlock_irqsave, &rc_map->lock) { + for (i = 0; i < from->size; i++) { + index = ir_establish_scancode(dev, rc_map, + from->scan[i].scancode, false); + if (index >= rc_map->len) { + rc = -ENOMEM; + break; + } - ir_update_mapping(dev, rc_map, index, - from->scan[i].keycode); + ir_update_mapping(dev, rc_map, index, + from->scan[i].keycode); + } } if (rc) @@ -524,6 +548,8 @@ static unsigned int ir_lookup_by_scancode(const struct rc_map *rc_map, { struct rc_map_table *res; + lockdep_assert_held(&rc_map->lock); + res = bsearch(&scancode, rc_map->scan, rc_map->len, sizeof(struct rc_map_table), rc_map_cmp); if (!res) @@ -1989,7 +2015,8 @@ int rc_register_device(struct rc_dev *dev) scoped_guard(mutex, &dev->lock) dev->registered = false; out_free_table: - ir_free_table(&dev->rc_map); + if (dev->driver_type != RC_DRIVER_IR_RAW_TX) + ir_free_table(&dev->rc_map); out_raw: ir_raw_event_free(dev); out_minor: diff --git a/drivers/mfd/cs42l43-i2c.c b/drivers/mfd/cs42l43-i2c.c index a2ab001a600a..f0ad4002652d 100644 --- a/drivers/mfd/cs42l43-i2c.c +++ b/drivers/mfd/cs42l43-i2c.c @@ -56,6 +56,13 @@ static int cs42l43_i2c_probe(struct i2c_client *i2c) return cs42l43_dev_probe(cs42l43); } +static void cs42l43_i2c_remove(struct i2c_client *i2c) +{ + struct cs42l43 *cs42l43 = dev_get_drvdata(&i2c->dev); + + cs42l43_dev_remove(cs42l43); +} + #if IS_ENABLED(CONFIG_OF) static const struct of_device_id cs42l43_of_match[] = { { .compatible = "cirrus,cs42l43", }, @@ -81,6 +88,7 @@ static struct i2c_driver cs42l43_i2c_driver = { }, .probe = cs42l43_i2c_probe, + .remove = cs42l43_i2c_remove, }; module_i2c_driver(cs42l43_i2c_driver); diff --git a/drivers/mfd/cs42l43-sdw.c b/drivers/mfd/cs42l43-sdw.c index 023f7e1a30f8..3938d48039c4 100644 --- a/drivers/mfd/cs42l43-sdw.c +++ b/drivers/mfd/cs42l43-sdw.c @@ -187,6 +187,15 @@ static int cs42l43_sdw_probe(struct sdw_slave *sdw, const struct sdw_device_id * return cs42l43_dev_probe(cs42l43); } +static int cs42l43_sdw_remove(struct sdw_slave *sdw) +{ + struct cs42l43 *cs42l43 = dev_get_drvdata(&sdw->dev); + + cs42l43_dev_remove(cs42l43); + + return 0; +} + static const struct sdw_device_id cs42l43_sdw_id[] = { SDW_SLAVE_ENTRY(0x01FA, 0x4243, 0), {} @@ -200,6 +209,7 @@ static struct sdw_driver cs42l43_sdw_driver = { }, .probe = cs42l43_sdw_probe, + .remove = cs42l43_sdw_remove, .id_table = cs42l43_sdw_id, .ops = &cs42l43_sdw_ops, }; diff --git a/drivers/mfd/cs42l43.c b/drivers/mfd/cs42l43.c index 13d446755fe2..e875154e8d81 100644 --- a/drivers/mfd/cs42l43.c +++ b/drivers/mfd/cs42l43.c @@ -1037,15 +1037,19 @@ static int cs42l43_power_down(struct cs42l43 *cs42l43) return 0; } -static void cs42l43_dev_remove(void *data) +static void cs42l43_dev_power_down(void *data) { struct cs42l43 *cs42l43 = data; - cancel_work_sync(&cs42l43->boot_work); - cs42l43_power_down(cs42l43); } +void cs42l43_dev_remove(struct cs42l43 *cs42l43) +{ + flush_work(&cs42l43->boot_work); +} +EXPORT_SYMBOL_NS_GPL(cs42l43_dev_remove, "MFD_CS42L43"); + int cs42l43_dev_probe(struct cs42l43 *cs42l43) { int i, ret; @@ -1092,7 +1096,7 @@ int cs42l43_dev_probe(struct cs42l43 *cs42l43) if (ret) return ret; - ret = devm_add_action_or_reset(cs42l43->dev, cs42l43_dev_remove, cs42l43); + ret = devm_add_action_or_reset(cs42l43->dev, cs42l43_dev_power_down, cs42l43); if (ret) return ret; diff --git a/drivers/mfd/cs42l43.h b/drivers/mfd/cs42l43.h index f3da783930f5..8d1b1b0f5a47 100644 --- a/drivers/mfd/cs42l43.h +++ b/drivers/mfd/cs42l43.h @@ -25,5 +25,6 @@ bool cs42l43_precious_register(struct device *dev, unsigned int reg); bool cs42l43_volatile_register(struct device *dev, unsigned int reg); int cs42l43_dev_probe(struct cs42l43 *cs42l43); +void cs42l43_dev_remove(struct cs42l43 *cs42l43); #endif /* CS42L43_CORE_INT_H */ diff --git a/drivers/misc/bcm-vk/bcm_vk_sg.c b/drivers/misc/bcm-vk/bcm_vk_sg.c index d309216ee181..62ef58b56fb4 100644 --- a/drivers/misc/bcm-vk/bcm_vk_sg.c +++ b/drivers/misc/bcm-vk/bcm_vk_sg.c @@ -80,7 +80,8 @@ static int bcm_vk_dma_alloc(struct device *dev, dma->nr_pages = (err >= 0) ? err : 0; dev_err(dev, "get_user_pages_fast, err=%d [%d]\n", err, dma->nr_pages); - return err < 0 ? err : -EINVAL; + err = err < 0 ? err : -EINVAL; + goto err_pages; } /* Max size of sg list is 1 per mapped page + fields at start */ @@ -92,8 +93,10 @@ static int bcm_vk_dma_alloc(struct device *dev, dma->sglen, &dma->handle, GFP_KERNEL); - if (!dma->sglist) - return -ENOMEM; + if (!dma->sglist) { + err = -ENOMEM; + goto err_pages; + } dma->sglist[SGLIST_NUM_SG] = 0; dma->sglist[SGLIST_TOTALSIZE] = vkdata->size; @@ -110,8 +113,8 @@ static int bcm_vk_dma_alloc(struct device *dev, dma->direction); transfer_size = size; if (unlikely(dma_mapping_error(dev, sg_addr))) { - __free_page(dma->pages[0]); - return -EIO; + err = -EIO; + goto err_sglist; } for (i = 1; i < dma->nr_pages; i++) { @@ -123,8 +126,8 @@ static int bcm_vk_dma_alloc(struct device *dev, size, dma->direction); if (unlikely(dma_mapping_error(dev, addr))) { - __free_page(dma->pages[i]); - return -EIO; + err = -EIO; + goto err_unmap; } /* @@ -169,6 +172,32 @@ static int bcm_vk_dma_alloc(struct device *dev, #endif return 0; + +err_unmap: + /* + * Unmap completed SG entries and the in-progress DMA range, + * which has not been written to the SG list yet. + */ + sgdata = (struct _vk_data *)&dma->sglist[SGLIST_VKDATA_START]; + for (i = 0; i < dma->sglist[SGLIST_NUM_SG]; i++) { + size = sgdata[i].size; + addr = get_unaligned(&sgdata[i].address); + dma_unmap_page(dev, addr, size, dma->direction); + } + dma_unmap_page(dev, sg_addr, transfer_size, dma->direction); + +err_sglist: + dma_free_coherent(dev, dma->sglen, dma->sglist, dma->handle); + +err_pages: + for (i = 0; i < dma->nr_pages; i++) + put_page(dma->pages[i]); + kfree(dma->pages); + dma->pages = NULL; + dma->sglist = NULL; + dma->sglen = 0; + dma->nr_pages = 0; + return err; } int bcm_vk_sg_alloc(struct device *dev, diff --git a/drivers/misc/fastrpc.c b/drivers/misc/fastrpc.c index 9d596f4fd4dc..3f32e1bf73f8 100644 --- a/drivers/misc/fastrpc.c +++ b/drivers/misc/fastrpc.c @@ -46,8 +46,6 @@ #define ADSP_MMAP_HEAP_ADDR 4 /* MAP static DMA buffer on DSP User PD */ #define ADSP_MMAP_DMA_BUFFER 6 -/* Add memory to static PD pool protection thru hypervisor */ -#define ADSP_MMAP_REMOTE_HEAP_ADDR 8 /* Add memory to userPD pool, for user heap */ #define ADSP_MMAP_ADD_PAGES 0x1000 /* Add memory to userPD pool, for LLC heap */ @@ -270,10 +268,14 @@ struct fastrpc_channel_ctx { struct kref refcount; /* Flag if dsp attributes are cached */ bool valid_attributes; + /* Flag if audio PD init mem was allocated */ + bool audio_init_mem; + /* Audio PD reserved remote heap region */ + phys_addr_t remote_heap_addr; + u64 remote_heap_size; u32 dsp_attributes[FASTRPC_MAX_DSP_ATTRIBUTES]; struct fastrpc_device *secure_fdevice; struct fastrpc_device *fdevice; - struct fastrpc_buf *remote_heap; struct list_head invoke_interrupted_mmaps; bool secure; bool unsigned_support; @@ -1317,15 +1319,24 @@ static int fastrpc_init_create_static_process(struct fastrpc_user *fl, struct fastrpc_init_create_static init; struct fastrpc_invoke_args *args; struct fastrpc_phy_page pages[1]; + struct fastrpc_channel_ctx *cctx = fl->cctx; char *name; int err; - bool scm_done = false; struct { int client_id; u32 namelen; u32 pageslen; } inbuf; u32 sc; + unsigned long flags; + bool sent_heap = false; + + if (!cctx->remote_heap_addr || !cctx->remote_heap_size) { + err = -ENOMEM; + dev_err(fl->sctx->dev, + "remote heap memory region is not added\n"); + return err; + } args = kcalloc(FASTRPC_CREATE_STATIC_PROCESS_NARGS, sizeof(*args), GFP_KERNEL); if (!args) @@ -1349,31 +1360,6 @@ static int fastrpc_init_create_static_process(struct fastrpc_user *fl, inbuf.client_id = fl->client_id; inbuf.namelen = init.namelen; inbuf.pageslen = 0; - if (!fl->cctx->remote_heap) { - err = fastrpc_remote_heap_alloc(fl, fl->sctx->dev, init.memlen, - &fl->cctx->remote_heap); - if (err) - goto err_name; - - /* Map if we have any heap VMIDs associated with this ADSP Static Process. */ - if (fl->cctx->vmcount) { - u64 src_perms = BIT(QCOM_SCM_VMID_HLOS); - - err = qcom_scm_assign_mem(fl->cctx->remote_heap->dma_addr, - (u64)fl->cctx->remote_heap->size, - &src_perms, - fl->cctx->vmperms, fl->cctx->vmcount); - if (err) { - dev_err(fl->sctx->dev, - "Failed to assign memory with dma_addr %pad size 0x%llx err %d\n", - &fl->cctx->remote_heap->dma_addr, - fl->cctx->remote_heap->size, err); - goto err_map; - } - scm_done = true; - inbuf.pageslen = 1; - } - } fl->pd = USER_PD; @@ -1385,8 +1371,25 @@ static int fastrpc_init_create_static_process(struct fastrpc_user *fl, args[1].length = inbuf.namelen; args[1].fd = -1; - pages[0].addr = fl->cctx->remote_heap->dma_addr; - pages[0].size = fl->cctx->remote_heap->size; + /* + * Audio PD is a static PD and retains the remote heap + * information across daemon restarts. Therefore only + * the first attach should provide heap information to + * DSP. Subsequent attaches reuse the previously + * initialized memory pool. + */ + spin_lock_irqsave(&cctx->lock, flags); + if (!cctx->audio_init_mem) { + pages[0].addr = cctx->remote_heap_addr; + pages[0].size = cctx->remote_heap_size; + cctx->audio_init_mem = true; + inbuf.pageslen = 1; + sent_heap = true; + } else { + pages[0].addr = 0; + pages[0].size = 0; + } + spin_unlock_irqrestore(&cctx->lock, flags); args[2].ptr = (u64)(uintptr_t) pages; args[2].length = sizeof(*pages); @@ -1404,27 +1407,11 @@ static int fastrpc_init_create_static_process(struct fastrpc_user *fl, return 0; err_invoke: - if (fl->cctx->vmcount && scm_done) { - u64 src_perms = 0; - struct qcom_scm_vmperm dst_perms; - u32 i; - - for (i = 0; i < fl->cctx->vmcount; i++) - src_perms |= BIT(fl->cctx->vmperms[i].vmid); - - dst_perms.vmid = QCOM_SCM_VMID_HLOS; - dst_perms.perm = QCOM_SCM_PERM_RWX; - err = qcom_scm_assign_mem(fl->cctx->remote_heap->dma_addr, - (u64)fl->cctx->remote_heap->size, - &src_perms, &dst_perms, 1); - if (err) - dev_err(fl->sctx->dev, "Failed to assign memory dma_addr %pad size 0x%llx err %d\n", - &fl->cctx->remote_heap->dma_addr, fl->cctx->remote_heap->size, err); + if (sent_heap) { + spin_lock_irqsave(&cctx->lock, flags); + cctx->audio_init_mem = false; + spin_unlock_irqrestore(&cctx->lock, flags); } -err_map: - fastrpc_buf_free(fl->cctx->remote_heap); - fl->cctx->remote_heap = NULL; -err_name: kfree(name); err: kfree(args); @@ -1920,7 +1907,7 @@ static int fastrpc_req_mmap(struct fastrpc_user *fl, char __user *argp) if (copy_from_user(&req, argp, sizeof(req))) return -EFAULT; - if (req.flags != ADSP_MMAP_ADD_PAGES && req.flags != ADSP_MMAP_REMOTE_HEAP_ADDR) { + if (req.flags != ADSP_MMAP_ADD_PAGES) { dev_err(dev, "flag not supported 0x%x\n", req.flags); return -EINVAL; @@ -1931,10 +1918,7 @@ static int fastrpc_req_mmap(struct fastrpc_user *fl, char __user *argp) return -EINVAL; } - if (req.flags == ADSP_MMAP_REMOTE_HEAP_ADDR) - err = fastrpc_remote_heap_alloc(fl, dev, req.size, &buf); - else - err = fastrpc_buf_alloc(fl, dev, req.size, &buf); + err = fastrpc_buf_alloc(fl, dev, req.size, &buf); if (err) { dev_err(dev, "failed to allocate buffer\n"); @@ -1973,20 +1957,6 @@ static int fastrpc_req_mmap(struct fastrpc_user *fl, char __user *argp) /* let the client know the address to use */ req.vaddrout = rsp_msg.vaddr; - /* Add memory to static PD pool, protection thru hypervisor */ - if (req.flags == ADSP_MMAP_REMOTE_HEAP_ADDR && fl->cctx->vmcount) { - u64 src_perms = BIT(QCOM_SCM_VMID_HLOS); - - err = qcom_scm_assign_mem(buf->dma_addr, (u64)buf->size, - &src_perms, fl->cctx->vmperms, fl->cctx->vmcount); - if (err) { - dev_err(fl->sctx->dev, - "Failed to assign memory dma_addr %pad size 0x%llx err %d", - &buf->dma_addr, buf->size, err); - goto err_assign; - } - } - spin_lock(&fl->lock); list_add_tail(&buf->node, &fl->mmaps); spin_unlock(&fl->lock); @@ -2322,6 +2292,45 @@ static int fastrpc_get_domain_id(const char *domain) return -EINVAL; } +static int fastrpc_init_reserved_mem(struct fastrpc_channel_ctx *cctx, + struct device *rdev, u32 domain_id) +{ + struct resource res; + u64 src_perms; + int err; + + /* Only SDSP and ADSP domains use a reserved remote heap region */ + if (domain_id != SDSP_DOMAIN_ID && domain_id != ADSP_DOMAIN_ID) + return 0; + + err = of_reserved_mem_region_to_resource(rdev->of_node, 0, &res); + if (err) { + /* + * The reserved-memory region is optional at probe time. For + * the Audio PD (ADSP) domain its absence is validated later in + * fastrpc_init_create_static_process(), so keep probing here. + */ + return 0; + } + + /* + * Audio PD (ADSP) is a static PD: cache the region so its lifetime + * is tied to the rpmsg channel instead of being controlled by + * userspace. + */ + if (domain_id == ADSP_DOMAIN_ID) { + cctx->remote_heap_addr = res.start; + cctx->remote_heap_size = resource_size(&res); + } + + if (!cctx->vmcount) + return 0; + + src_perms = BIT(QCOM_SCM_VMID_HLOS); + return qcom_scm_assign_mem(res.start, resource_size(&res), &src_perms, + cctx->vmperms, cctx->vmcount); +} + static int fastrpc_rpmsg_probe(struct rpmsg_device *rpdev) { struct device *rdev = &rpdev->dev; @@ -2366,21 +2375,9 @@ static int fastrpc_rpmsg_probe(struct rpmsg_device *rpdev) } } - if (domain_id == SDSP_DOMAIN_ID) { - struct resource res; - u64 src_perms; - - err = of_reserved_mem_region_to_resource(rdev->of_node, 0, &res); - if (!err) { - src_perms = BIT(QCOM_SCM_VMID_HLOS); - - err = qcom_scm_assign_mem(res.start, resource_size(&res), &src_perms, - data->vmperms, data->vmcount); - if (err) - goto err_free_data; - } - - } + err = fastrpc_init_reserved_mem(data, rdev, domain_id); + if (err) + goto err_free_data; secure_dsp = !(of_property_read_bool(rdev->of_node, "qcom,non-secure-domain")); data->secure = secure_dsp; @@ -2476,8 +2473,25 @@ static void fastrpc_rpmsg_remove(struct rpmsg_device *rpdev) list_for_each_entry_safe(buf, b, &cctx->invoke_interrupted_mmaps, node) list_del(&buf->node); - if (cctx->remote_heap) - fastrpc_buf_free(cctx->remote_heap); + if (cctx->remote_heap_size && cctx->vmcount) { + u64 src_perms = 0; + int err, i; + struct qcom_scm_vmperm dst_perms; + + for (i = 0; i < cctx->vmcount; i++) + src_perms |= BIT(cctx->vmperms[i].vmid); + + dst_perms.vmid = QCOM_SCM_VMID_HLOS; + dst_perms.perm = QCOM_SCM_PERM_RWX; + + err = qcom_scm_assign_mem(cctx->remote_heap_addr, + cctx->remote_heap_size, &src_perms, + &dst_perms, 1); + if (err) + dev_err(&rpdev->dev, + "Failed to assign memory back to HLOS: addr %pa size %#llx err %d\n", + &cctx->remote_heap_addr, cctx->remote_heap_size, err); + } of_platform_depopulate(&rpdev->dev); diff --git a/drivers/misc/ibmvmc.c b/drivers/misc/ibmvmc.c index b26ee0d3626f..2c55831a1afe 100644 --- a/drivers/misc/ibmvmc.c +++ b/drivers/misc/ibmvmc.c @@ -2365,14 +2365,6 @@ static int __init ibmvmc_module_init(void) ibmvmc.state = ibmvmc_state_initial; pr_info("ibmvmc: version %s\n", IBMVMC_DRIVER_VERSION); - rc = misc_register(&ibmvmc_miscdev); - if (rc) { - pr_err("ibmvmc: misc registration failed\n"); - goto misc_register_failed; - } - pr_info("ibmvmc: node %d:%d\n", MISC_MAJOR, - ibmvmc_miscdev.minor); - /* Initialize data structures */ memset(hmcs, 0, sizeof(struct ibmvmc_hmc) * MAX_HMCS); for (i = 0; i < MAX_HMCS; i++) { @@ -2382,6 +2374,14 @@ static int __init ibmvmc_module_init(void) hmcs[i].queue_outbound_msgs[j] = VMC_INVALID_BUFFER_ID; } + rc = misc_register(&ibmvmc_miscdev); + if (rc) { + pr_err("ibmvmc: misc registration failed\n"); + goto misc_register_failed; + } + pr_info("ibmvmc: node %d:%d\n", MISC_MAJOR, + ibmvmc_miscdev.minor); + /* Sanity check module parms */ ibmvmc_scrub_module_parms(); diff --git a/drivers/misc/vmw_vmci/vmci_event.c b/drivers/misc/vmw_vmci/vmci_event.c index 89ab9f05b88c..dcfe639abcb5 100644 --- a/drivers/misc/vmw_vmci/vmci_event.c +++ b/drivers/misc/vmw_vmci/vmci_event.c @@ -213,7 +213,12 @@ int vmci_event_unsubscribe(u32 sub_id) if (!s) return VMCI_ERROR_NOT_FOUND; - kvfree_rcu_mightsleep(s); + /* + * Wait for event_deliver(): the caller is going to free what the + * callback works on. + */ + synchronize_rcu(); + kfree(s); return VMCI_SUCCESS; } diff --git a/drivers/mmc/host/jz4740_mmc.c b/drivers/mmc/host/jz4740_mmc.c index 6a0d0250d47b..5f4121bdd653 100644 --- a/drivers/mmc/host/jz4740_mmc.c +++ b/drivers/mmc/host/jz4740_mmc.c @@ -1151,12 +1151,13 @@ static void jz4740_mmc_remove(struct platform_device *pdev) { struct jz4740_mmc_host *host = platform_get_drvdata(pdev); + /* The card's driver may still send commands as it goes */ + mmc_remove_host(host->mmc); + timer_delete_sync(&host->timeout_timer); jz4740_mmc_set_irq_enabled(host, 0xff, false); jz4740_mmc_reset(host); - mmc_remove_host(host->mmc); - free_irq(host->irq, host); if (host->use_dma) diff --git a/drivers/mmc/host/meson-gx-mmc.c b/drivers/mmc/host/meson-gx-mmc.c index 694bb443d5f3..c93fef2f7d15 100644 --- a/drivers/mmc/host/meson-gx-mmc.c +++ b/drivers/mmc/host/meson-gx-mmc.c @@ -125,6 +125,7 @@ #define SD_EMMC_CFG_RESP_TIMEOUT 256 /* in clock cycles */ #define SD_EMMC_CMD_TIMEOUT 1024 /* in ms */ #define SD_EMMC_CMD_TIMEOUT_DATA 4096 /* in ms */ +#define SD_EMMC_CMD_TIMEOUT_MAX 32768 /* in ms, 2^15: limit of CMD_CFG_TIMEOUT_MASK */ #define SD_EMMC_CFG_CMD_GAP 16 /* in clock cycles */ #define SD_EMMC_DESC_BUF_LEN PAGE_SIZE @@ -211,7 +212,21 @@ static unsigned int meson_mmc_get_timeout_msecs(struct mmc_data *data) timeout = roundup_pow_of_two(timeout); - return min(timeout, 32768U); /* max. 2^15 ms */ + return min_t(unsigned int, timeout, SD_EMMC_CMD_TIMEOUT_MAX); +} + +/* For R1b the controller waits for busy to be released within this timeout. */ +static unsigned int meson_mmc_get_cmd_timeout_msecs(struct mmc_command *cmd) +{ + unsigned int timeout = cmd->busy_timeout; + + if (!timeout) + return SD_EMMC_CMD_TIMEOUT; + + timeout = clamp_t(unsigned int, timeout, SD_EMMC_CMD_TIMEOUT, + SD_EMMC_CMD_TIMEOUT_MAX); + + return roundup_pow_of_two(timeout); } static struct mmc_command *meson_mmc_get_next_command(struct mmc_command *cmd) @@ -840,7 +855,7 @@ static void meson_mmc_start_cmd(struct mmc_host *mmc, struct mmc_command *cmd) cmd_data = host->bounce_dma_addr & CMD_DATA_MASK; } else { cmd_cfg |= FIELD_PREP(CMD_CFG_TIMEOUT_MASK, - ilog2(SD_EMMC_CMD_TIMEOUT)); + ilog2(meson_mmc_get_cmd_timeout_msecs(cmd))); } /* Last descriptor */ @@ -1079,8 +1094,8 @@ static int meson_mmc_card_busy(struct mmc_host *mmc) regval = readl(host->regs + SD_EMMC_STATUS); - /* We are only interrested in lines 0 to 3, so mask the other ones */ - return !(FIELD_GET(STATUS_DATI, regval) & 0xf); + /* The card signals busy on DAT0 alone. */ + return !(FIELD_GET(STATUS_DATI, regval) & BIT(0)); } static int meson_mmc_voltage_switch(struct mmc_host *mmc, struct mmc_ios *ios) @@ -1166,6 +1181,9 @@ static int meson_mmc_probe(struct platform_device *pdev) mmc->caps |= MMC_CAP_CMD23; + /* The longest busy wait the CMD_CFG timeout field can hold. */ + mmc->max_busy_timeout = SD_EMMC_CMD_TIMEOUT_MAX; + if (mmc->caps & MMC_CAP_SDIO_IRQ) mmc->caps2 |= MMC_CAP2_SDIO_IRQ_NOTHREAD; diff --git a/drivers/mmc/host/mmci.c b/drivers/mmc/host/mmci.c index 416bdb184ed4..4db5c55b2700 100644 --- a/drivers/mmc/host/mmci.c +++ b/drivers/mmc/host/mmci.c @@ -2477,11 +2477,13 @@ static int mmci_probe(struct amba_device *dev, ret = mmc_add_host(mmc); if (ret) - goto clk_disable; + goto dma_release; pm_runtime_put(&dev->dev); return 0; +dma_release: + mmci_dma_release(host); clk_disable: clk_disable_unprepare(host->clk); return ret; diff --git a/drivers/mmc/host/omap.c b/drivers/mmc/host/omap.c index 52ac3f128a1c..b498e91c493a 100644 --- a/drivers/mmc/host/omap.c +++ b/drivers/mmc/host/omap.c @@ -214,7 +214,7 @@ static void mmc_omap_select_slot(struct mmc_omap_slot *slot, int claimed) host->mmc = slot->mmc; spin_unlock_irqrestore(&host->slot_lock, flags); no_claim: - timer_delete(&host->clk_timer); + timer_delete_sync(&host->clk_timer); if (host->current_slot != slot || !claimed) mmc_omap_fclk_offdelay(host->current_slot); @@ -273,7 +273,7 @@ static void mmc_omap_release_slot(struct mmc_omap_slot *slot, int clk_enabled) /* Keeps clock running for at least 8 cycles on valid freq */ mod_timer(&host->clk_timer, jiffies + HZ/10); else { - timer_delete(&host->clk_timer); + timer_delete_sync(&host->clk_timer); mmc_omap_fclk_offdelay(slot); mmc_omap_fclk_enable(host, 0); } diff --git a/drivers/mmc/host/sdhci-esdhc-imx.c b/drivers/mmc/host/sdhci-esdhc-imx.c index aa2a1eeedffa..a4e95aee3595 100644 --- a/drivers/mmc/host/sdhci-esdhc-imx.c +++ b/drivers/mmc/host/sdhci-esdhc-imx.c @@ -1131,6 +1131,20 @@ static void esdhc_reset_tuning(struct sdhci_host *host) } } +static void sdhci_esdhc_imx_set_ios(struct mmc_host *mmc, struct mmc_ios *ios) +{ + /* + * This controller has no driver-type control: esdhc_writew_le() + * discards the driver-type field when writing SDHCI_HOST_CONTROL2. + * The programmed value is therefore irrelevant, but SDHCI rejects + * non-SD values such as 4 (eMMC 40 ohm, from fixed-emmc-driver-type). + * Force an always-valid Type B. + */ + ios->drv_type = MMC_SET_DRIVER_TYPE_B; + + sdhci_set_ios(mmc, ios); +} + static void usdhc_init_card(struct mmc_host *mmc, struct mmc_card *card) { struct sdhci_host *host = mmc_priv(mmc); @@ -1929,6 +1943,9 @@ static int sdhci_esdhc_imx_probe(struct platform_device *pdev) host->max_timeout_count = 0xF; } + /* No SDHCI driver type control */ + host->mmc_host_ops.set_ios = sdhci_esdhc_imx_set_ios; + if (imx_data->socdata->flags & ESDHC_FLAG_MAN_TUNING) sdhci_esdhc_ops.platform_execute_tuning = esdhc_executing_tuning; diff --git a/drivers/mmc/host/sunxi-mmc.c b/drivers/mmc/host/sunxi-mmc.c index 8dbcff53a631..05e3275dab9d 100644 --- a/drivers/mmc/host/sunxi-mmc.c +++ b/drivers/mmc/host/sunxi-mmc.c @@ -1355,8 +1355,13 @@ static int sunxi_mmc_resource_request(struct sunxi_mmc_host *host, goto error_disable_mmc; } - return devm_request_threaded_irq(&pdev->dev, host->irq, sunxi_mmc_irq, - sunxi_mmc_handle_manual_stop, 0, "sunxi-mmc", host); + ret = devm_request_threaded_irq(&pdev->dev, host->irq, sunxi_mmc_irq, + sunxi_mmc_handle_manual_stop, 0, + "sunxi-mmc", host); + if (ret) + goto error_disable_mmc; + + return 0; error_disable_mmc: sunxi_mmc_disable(host); @@ -1386,9 +1391,11 @@ static int sunxi_mmc_probe(struct platform_device *pdev) host->sg_cpu = dma_alloc_coherent(&pdev->dev, PAGE_SIZE, &host->sg_dma, GFP_KERNEL); - if (!host->sg_cpu) - return dev_err_probe(&pdev->dev, -ENOMEM, - "Failed to allocate DMA descriptor mem\n"); + if (!host->sg_cpu) { + ret = dev_err_probe(&pdev->dev, -ENOMEM, + "Failed to allocate DMA descriptor mem\n"); + goto error_disable_mmc; + } if (host->cfg->ccu_has_timings_switch) { /* @@ -1468,7 +1475,7 @@ static int sunxi_mmc_probe(struct platform_device *pdev) ret = mmc_add_host(mmc); if (ret) - goto error_free_dma; + goto error_disable_rpm; dev_info(&pdev->dev, "initialized, max. request size: %u KB%s\n", mmc->max_req_size >> 10, @@ -1476,8 +1483,13 @@ static int sunxi_mmc_probe(struct platform_device *pdev) return 0; +error_disable_rpm: + pm_runtime_disable(&pdev->dev); error_free_dma: dma_free_coherent(&pdev->dev, PAGE_SIZE, host->sg_cpu, host->sg_dma); +error_disable_mmc: + disable_irq(host->irq); + sunxi_mmc_disable(host); return ret; } diff --git a/drivers/mtd/mtdcore.c b/drivers/mtd/mtdcore.c index f84e4213b678..3bb86fd9fb33 100644 --- a/drivers/mtd/mtdcore.c +++ b/drivers/mtd/mtdcore.c @@ -1082,6 +1082,7 @@ static int mtd_otp_nvmem_add(struct mtd_info *mtd) err: nvmem_unregister(mtd->otp_user_nvmem); + mtd->otp_user_nvmem = NULL; /* Don't report error if OTP is not supported. */ if (err == -EOPNOTSUPP) return 0; diff --git a/drivers/net/amt.c b/drivers/net/amt.c index 96cde820237d..e577b205f37b 100644 --- a/drivers/net/amt.c +++ b/drivers/net/amt.c @@ -2134,13 +2134,12 @@ static void amt_mldv1_leave_handler(struct amt_dev *amt, struct sk_buff *skb, struct amt_tunnel_list *tunnel) { struct mld_msg *mld = (struct mld_msg *)icmp6_hdr(skb); - struct iphdr *iph = ip_hdr(skb); + struct ipv6hdr *ip6h = ipv6_hdr(skb); struct amt_group_node *gnode; union amt_addr group, host; memcpy(&group.ip6, &mld->mld_mca, sizeof(struct in6_addr)); - memset(&host, 0, sizeof(union amt_addr)); - host.ip4 = iph->saddr; + memcpy(&host.ip6, &ip6h->saddr, sizeof(struct in6_addr)); gnode = amt_lookup_group(tunnel, &group, &host, true); if (gnode) { @@ -3383,22 +3382,6 @@ static struct rtnl_link_ops amt_link_ops __read_mostly = { .fill_info = amt_fill_info, }; -static struct net_device *amt_lookup_upper_dev(struct net_device *dev) -{ - struct net_device *upper_dev; - struct amt_dev *amt; - - for_each_netdev(dev_net(dev), upper_dev) { - if (netif_is_amt(upper_dev)) { - amt = netdev_priv(upper_dev); - if (amt->stream_dev == dev) - return upper_dev; - } - } - - return NULL; -} - static int amt_device_event(struct notifier_block *unused, unsigned long event, void *ptr) { @@ -3408,26 +3391,34 @@ static int amt_device_event(struct notifier_block *unused, LIST_HEAD(list); int new_mtu; - upper_dev = amt_lookup_upper_dev(dev); - if (!upper_dev) - return NOTIFY_DONE; - amt = netdev_priv(upper_dev); + /* amt_dellink() leaves each device on the netns device list until + * unregister_netdevice_many(), so the walk stays valid. + */ + for_each_netdev(dev_net(dev), upper_dev) { + if (!netif_is_amt(upper_dev)) + continue; + amt = netdev_priv(upper_dev); + if (amt->stream_dev != dev) + continue; - switch (event) { - case NETDEV_UNREGISTER: - amt_dellink(amt->dev, &list); - unregister_netdevice_many(&list); - break; - case NETDEV_CHANGEMTU: - if (amt->mode == AMT_MODE_RELAY) - new_mtu = dev->mtu - AMT_RELAY_HLEN; - else - new_mtu = dev->mtu - AMT_GW_HLEN; + switch (event) { + case NETDEV_UNREGISTER: + amt_dellink(amt->dev, &list); + break; + case NETDEV_CHANGEMTU: + if (amt->mode == AMT_MODE_RELAY) + new_mtu = dev->mtu - AMT_RELAY_HLEN; + else + new_mtu = dev->mtu - AMT_GW_HLEN; - dev_set_mtu(amt->dev, new_mtu); - break; + dev_set_mtu(amt->dev, new_mtu); + break; + } } + if (event == NETDEV_UNREGISTER) + unregister_netdevice_many(&list); + return NOTIFY_DONE; } diff --git a/drivers/net/bonding/bond_main.c b/drivers/net/bonding/bond_main.c index 2e9e1b4d74da..9b46eabf2eba 100644 --- a/drivers/net/bonding/bond_main.c +++ b/drivers/net/bonding/bond_main.c @@ -789,6 +789,10 @@ int bond_set_carrier(struct bonding *bond) * values are invalid, set speed and duplex to -1, * and return. Return 1 if speed or duplex settings are * UNKNOWN; 0 otherwise. + * + * Caller must hold the slave's netdev ops lock. The notifier path + * (bond_netdev_event NETDEV_CHANGE/UP) reaches us with the slave's ops + * lock held; other call sites take it explicitly. */ static int bond_update_speed_duplex(struct slave *slave) { @@ -796,7 +800,7 @@ static int bond_update_speed_duplex(struct slave *slave) struct ethtool_link_ksettings ecmd; int res; - res = __ethtool_get_link_ksettings(slave_dev, &ecmd); + res = netif_get_link_ksettings(slave_dev, &ecmd); if (res < 0) goto speed_duplex_unknown; if (ecmd.base.speed == 0 || ecmd.base.speed == ((__u32)-1)) @@ -2114,8 +2118,10 @@ int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev, new_slave->delay = 0; new_slave->link_failure_count = 0; - if (bond_update_speed_duplex(new_slave) && - bond_needs_speed_duplex(bond)) + netdev_lock_ops(slave_dev); + res = bond_update_speed_duplex(new_slave); + netdev_unlock_ops(slave_dev); + if (res && bond_needs_speed_duplex(bond)) new_slave->link = BOND_LINK_DOWN; new_slave->last_rx = jiffies - @@ -2301,7 +2307,7 @@ int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev, SLAVE_NL_ERR(bond_dev, slave_dev, extack, "Slave does not support XDP"); res = -EOPNOTSUPP; - goto err_sysfs_del; + goto err_dec_slave_cnt; } } else if (bond->xdp_prog) { struct netdev_bpf xdp = { @@ -2315,14 +2321,14 @@ int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev, SLAVE_NL_ERR(bond_dev, slave_dev, extack, "Slave has XDP program loaded, please unload before enslaving"); res = -EOPNOTSUPP; - goto err_sysfs_del; + goto err_dec_slave_cnt; } res = dev_xdp_propagate(slave_dev, &xdp); if (res < 0) { /* ndo_bpf() sets extack error message */ slave_dbg(bond_dev, slave_dev, "Error %d calling ndo_bpf\n", res); - goto err_sysfs_del; + goto err_dec_slave_cnt; } if (bond->xdp_prog) bpf_prog_inc(bond->xdp_prog); @@ -2344,6 +2350,9 @@ int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev, return 0; /* Undo stages on error */ +err_dec_slave_cnt: + WRITE_ONCE(bond->slave_cnt, bond->slave_cnt - 1); + err_sysfs_del: bond_sysfs_slave_del(new_slave); @@ -2775,11 +2784,33 @@ static void bond_miimon_link_change(struct bonding *bond, } } +static bool bond_miimon_slave_down(struct bonding *bond, + struct slave *slave) +{ + if (slave->link_failure_count < UINT_MAX) + slave->link_failure_count++; + + bond_set_slave_link_state(slave, BOND_LINK_DOWN, + BOND_SLAVE_NOTIFY_NOW); + + if (BOND_MODE(bond) == BOND_MODE_ACTIVEBACKUP || + BOND_MODE(bond) == BOND_MODE_8023AD) + bond_set_slave_inactive_flags(slave, + BOND_SLAVE_NOTIFY_NOW); + + slave_info(bond->dev, slave->dev, "link status definitely down, disabling slave\n"); + + bond_miimon_link_change(bond, slave, BOND_LINK_DOWN); + + return slave == rcu_access_pointer(bond->curr_active_slave); +} + static void bond_miimon_commit(struct bonding *bond) { struct slave *slave, *primary, *active; bool do_failover = false; struct list_head *iter; + int err; ASSERT_RTNL(); @@ -2798,12 +2829,26 @@ static void bond_miimon_commit(struct bonding *bond) continue; case BOND_LINK_UP: - if (bond_update_speed_duplex(slave) && - bond_needs_speed_duplex(bond)) { - slave->link = BOND_LINK_DOWN; + netdev_lock_ops(slave->dev); + err = bond_update_speed_duplex(slave); + netdev_unlock_ops(slave->dev); + if (err && bond_needs_speed_duplex(bond)) { if (net_ratelimit()) slave_warn(bond->dev, slave->dev, "failed to get link speed/duplex\n"); + /* Coming from FAIL/UP, the slave may still be + * in use and may be curr_active_slave, so take + * it through the full down path. Coming from + * DOWN/BACK, it was never brought up, so just + * revert it to DOWN. + */ + if (slave->link == BOND_LINK_FAIL || + slave->link == BOND_LINK_UP) { + if (bond_miimon_slave_down(bond, slave)) + do_failover = true; + continue; + } + slave->link = BOND_LINK_DOWN; continue; } bond_set_slave_link_state(slave, BOND_LINK_UP, @@ -2832,28 +2877,13 @@ static void bond_miimon_commit(struct bonding *bond) continue; case BOND_LINK_DOWN: - if (slave->link_failure_count < UINT_MAX) - slave->link_failure_count++; - - bond_set_slave_link_state(slave, BOND_LINK_DOWN, - BOND_SLAVE_NOTIFY_NOW); - - if (BOND_MODE(bond) == BOND_MODE_ACTIVEBACKUP || - BOND_MODE(bond) == BOND_MODE_8023AD) - bond_set_slave_inactive_flags(slave, - BOND_SLAVE_NOTIFY_NOW); - - slave_info(bond->dev, slave->dev, "link status definitely down, disabling slave\n"); - - bond_miimon_link_change(bond, slave, BOND_LINK_DOWN); - - if (slave == rcu_access_pointer(bond->curr_active_slave)) + if (bond_miimon_slave_down(bond, slave)) do_failover = true; - continue; case BOND_LINK_FAIL: case BOND_LINK_BACK: + bond_commit_link_state(slave, BOND_SLAVE_NOTIFY_LATER); slave_dbg(bond->dev, slave->dev, "link_new_state %d on slave\n", slave->link_new_state); continue; @@ -2887,8 +2917,6 @@ static void bond_mii_monitor(struct work_struct *work) { struct bonding *bond = container_of(work, struct bonding, mii_work.work); - struct list_head *iter; - struct slave *slave; unsigned long delay; bool commit; @@ -2910,13 +2938,8 @@ static void bond_mii_monitor(struct work_struct *work) goto re_arm; } - if (commit) { - bond_for_each_slave(bond, slave, iter) { - bond_commit_link_state(slave, - BOND_SLAVE_NOTIFY_LATER); - } + if (commit) bond_miimon_commit(bond); - } if (bond->send_peer_notif) bond_peer_notify_may_events(bond, true); @@ -3964,18 +3987,13 @@ static int bond_slave_netdev_event(unsigned long event, case NETDEV_CHANGE: /* For 802.3ad mode only: * Getting invalid Speed/Duplex values here will put slave - * in weird state. Mark it as link-fail if the link was - * previously up or link-down if it hasn't yet come up, and - * let link-monitoring (miimon) set it right when correct - * speeds/duplex are available. + * in weird state. Mark an up slave as link-fail and let + * miimon set it right when correct speed/duplex are available. */ if (bond_update_speed_duplex(slave) && - BOND_MODE(bond) == BOND_MODE_8023AD) { - if (slave->last_link_up) - slave->link = BOND_LINK_FAIL; - else - slave->link = BOND_LINK_DOWN; - } + BOND_MODE(bond) == BOND_MODE_8023AD && + slave->link == BOND_LINK_UP) + slave->link = BOND_LINK_FAIL; if (BOND_MODE(bond) == BOND_MODE_8023AD) bond_3ad_adapter_speed_duplex_changed(slave); @@ -5862,7 +5880,9 @@ static int bond_ethtool_get_link_ksettings(struct net_device *bond_dev, */ bond_for_each_slave(bond, slave, iter) { if (bond_slave_can_tx(slave)) { + netdev_lock_ops(slave->dev); bond_update_speed_duplex(slave); + netdev_unlock_ops(slave->dev); if (slave->speed != SPEED_UNKNOWN) { if (BOND_MODE(bond) == BOND_MODE_BROADCAST) speed = bond_mode_bcast_speed(slave, diff --git a/drivers/net/can/dev/skb.c b/drivers/net/can/dev/skb.c index b643995fc536..a39cfdce341c 100644 --- a/drivers/net/can/dev/skb.c +++ b/drivers/net/can/dev/skb.c @@ -61,7 +61,7 @@ int can_put_echo_skb(struct sk_buff *skb, struct net_device *dev, (skb->protocol != htons(ETH_P_CAN) && skb->protocol != htons(ETH_P_CANFD) && skb->protocol != htons(ETH_P_CANXL))) { - kfree_skb(skb); + dev_kfree_skb_any(skb); return 0; } @@ -87,7 +87,7 @@ int can_put_echo_skb(struct sk_buff *skb, struct net_device *dev, } else { /* locking problem with netif_stop_queue() ?? */ netdev_err(dev, "%s: BUG! echo_skb %d is occupied!\n", __func__, idx); - kfree_skb(skb); + dev_kfree_skb_any(skb); return -EBUSY; } @@ -368,7 +368,7 @@ bool can_dropped_invalid_skb(struct net_device *dev, struct sk_buff *skb) return false; inval_skb: - kfree_skb(skb); + dev_kfree_skb_any(skb); dev->stats.tx_dropped++; return true; } diff --git a/drivers/net/dsa/b53/b53_common.c b/drivers/net/dsa/b53/b53_common.c index 508b46237011..137bc55b86d6 100644 --- a/drivers/net/dsa/b53/b53_common.c +++ b/drivers/net/dsa/b53/b53_common.c @@ -816,6 +816,59 @@ void b53_brcm_hdr_setup(struct dsa_switch *ds, int port) } EXPORT_SYMBOL(b53_brcm_hdr_setup); +int b53_enable_mcast_snooping(struct b53_device *dev) +{ + u16 val16; + u32 val; + int ret; + + /* Older switches use different IGMP controls, not HL_PRTC_CTRL. */ + if (is5325(dev) || is5365(dev) || dev->chip_id == BCM5389_DEVICE_ID || + is5397_98(dev) || is63xx(dev)) + return 0; + + /* IGMPv2 and MLDv1 reports use the group's destination MAC. Once + * the first listener is offloaded, ordinary multicast forwarding + * can keep subsequent reports from reaching the bridge CPU. + */ + + /* BCM5395 has a narrower register and a single IGMP classifier. + * Its ICMPv6 classifier also covers MLD. + */ + if (dev->chip_id == BCM5395_DEVICE_ID) { + ret = b53_read16(dev, B53_MGMT_PAGE, B53_HL_PRTC_CTRL, &val16); + if (ret) + return ret; + + val16 |= HL_PRTC_IGMP_IP_EN_5395 | HL_PRTC_ICMPV6_EN; + /* Zero forwarding modes copy control traffic to the CPU + * independently of the ARL lookup, retaining L2 forwarding. + */ + val16 &= ~(HL_PRTC_IGMP_FWD_MODE_5395 | + HL_PRTC_ICMPV6_FWD_MODE); + + return b53_write16(dev, B53_MGMT_PAGE, B53_HL_PRTC_CTRL, + val16); + } + + ret = b53_read32(dev, B53_MGMT_PAGE, B53_HL_PRTC_CTRL, &val); + if (ret) + return ret; + + val |= HL_PRTC_IGMP_RPTLVE_EN | HL_PRTC_IGMP_QRY_EN | + HL_PRTC_IGMP_UKN_EN | HL_PRTC_MLD_RPTDONE_EN | + HL_PRTC_MLD_QRY_EN; + /* Zero forwarding modes copy control traffic to the CPU + * independently of the ARL lookup, retaining L2 forwarding. + */ + val &= ~(HL_PRTC_IGMP_RPTLVE_FWD_MODE | HL_PRTC_IGMP_QRY_FWD_MODE | + HL_PRTC_IGMP_UKN_FWD_MODE | HL_PRTC_MLD_RPTDONE_FWD_MODE | + HL_PRTC_MLD_QRY_FWD_MODE); + + return b53_write32(dev, B53_MGMT_PAGE, B53_HL_PRTC_CTRL, val); +} +EXPORT_SYMBOL(b53_enable_mcast_snooping); + static void b53_enable_cpu_port(struct b53_device *dev, int port) { u8 port_ctrl; @@ -1316,6 +1369,10 @@ static int b53_setup(struct dsa_switch *ds) b53_disable_port(ds, port); } + ret = b53_enable_mcast_snooping(dev); + if (ret) + return ret; + return b53_setup_devlink_resources(ds); } @@ -1645,9 +1702,15 @@ static void b53_phylink_mac_link_up(struct phylink_config *config, } if (mode == MLO_AN_FIXED) { - /* Force flow control on BCM5301x's CPU port */ - if (is5301x(dev) && dsa_is_cpu_port(ds, port)) - tx_pause = rx_pause = true; + /* Force flow control and 2Gbits/sec on BCM5301x and NSP CPU + * ports + */ + if ((is5301x(dev) || dev->chip_id == BCM58XX_DEVICE_ID) && + dsa_is_cpu_port(ds, port)) { + tx_pause = true; + rx_pause = true; + speed = 2000; + } b53_force_port_config(dev, port, speed, duplex, tx_pause, rx_pause); diff --git a/drivers/net/dsa/b53/b53_priv.h b/drivers/net/dsa/b53/b53_priv.h index bd6849e5bb93..dce06110deb8 100644 --- a/drivers/net/dsa/b53/b53_priv.h +++ b/drivers/net/dsa/b53/b53_priv.h @@ -490,6 +490,7 @@ static inline int b53_switch_get_reset_gpio(struct b53_device *dev) /* Exported functions towards other drivers */ void b53_imp_vlan_setup(struct dsa_switch *ds, int cpu_port); int b53_configure_vlan(struct dsa_switch *ds); +int b53_enable_mcast_snooping(struct b53_device *dev); void b53_get_strings(struct dsa_switch *ds, int port, u32 stringset, uint8_t *data); void b53_get_ethtool_stats(struct dsa_switch *ds, int port, uint64_t *data); diff --git a/drivers/net/dsa/b53/b53_regs.h b/drivers/net/dsa/b53/b53_regs.h index b6fe7d207a2c..a9414851ea28 100644 --- a/drivers/net/dsa/b53/b53_regs.h +++ b/drivers/net/dsa/b53/b53_regs.h @@ -270,6 +270,23 @@ /* Revision ID register (8 bit) */ #define B53_REV_ID 0x40 +/* High-level protocol control (16 bit on BCM5395, otherwise 32 bit) */ +#define B53_HL_PRTC_CTRL 0x50 +#define HL_PRTC_ICMPV6_EN BIT(4) +#define HL_PRTC_ICMPV6_FWD_MODE BIT(5) +#define HL_PRTC_IGMP_IP_EN_5395 BIT(6) +#define HL_PRTC_IGMP_FWD_MODE_5395 BIT(8) +#define HL_PRTC_IGMP_RPTLVE_EN BIT(9) +#define HL_PRTC_IGMP_RPTLVE_FWD_MODE BIT(10) +#define HL_PRTC_IGMP_QRY_EN BIT(11) +#define HL_PRTC_IGMP_QRY_FWD_MODE BIT(12) +#define HL_PRTC_IGMP_UKN_EN BIT(13) +#define HL_PRTC_IGMP_UKN_FWD_MODE BIT(14) +#define HL_PRTC_MLD_RPTDONE_EN BIT(15) +#define HL_PRTC_MLD_RPTDONE_FWD_MODE BIT(16) +#define HL_PRTC_MLD_QRY_EN BIT(17) +#define HL_PRTC_MLD_QRY_FWD_MODE BIT(18) + /* Broadcom header RX control (16 bit) */ #define B53_BRCM_HDR_RX_DIS 0x60 diff --git a/drivers/net/dsa/bcm_sf2.c b/drivers/net/dsa/bcm_sf2.c index de3efa3ce9a7..f3b56ea87b07 100644 --- a/drivers/net/dsa/bcm_sf2.c +++ b/drivers/net/dsa/bcm_sf2.c @@ -1059,6 +1059,7 @@ static int bcm_sf2_sw_setup(struct dsa_switch *ds) { struct bcm_sf2_priv *priv = bcm_sf2_to_priv(ds); unsigned int port; + int ret; /* Enable all valid ports and disable those unused */ for (port = 0; port < priv->hw_params.num_ports; port++) { @@ -1074,6 +1075,10 @@ static int bcm_sf2_sw_setup(struct dsa_switch *ds) b53_configure_vlan(ds); bcm_sf2_enable_acb(ds); + ret = b53_enable_mcast_snooping(priv->dev); + if (ret) + return ret; + return b53_setup_devlink_resources(ds); } diff --git a/drivers/net/dsa/microchip/ksz_common.c b/drivers/net/dsa/microchip/ksz_common.c index 0c10351fe5eb..b1d973b1c9b4 100644 --- a/drivers/net/dsa/microchip/ksz_common.c +++ b/drivers/net/dsa/microchip/ksz_common.c @@ -5418,6 +5418,7 @@ int ksz_switch_register(struct ksz_device *dev) mutex_init(&dev->regmap_mutex); mutex_init(&dev->alu_mutex); mutex_init(&dev->vlan_mutex); + mutex_init(&dev->lock_irq); ret = ksz_switch_detect(dev); if (ret) diff --git a/drivers/net/ethernet/amazon/ena/ena_netdev.c b/drivers/net/ethernet/amazon/ena/ena_netdev.c index e35eef9f6ce1..f5b738ddb49e 100644 --- a/drivers/net/ethernet/amazon/ena/ena_netdev.c +++ b/drivers/net/ethernet/amazon/ena/ena_netdev.c @@ -986,7 +986,7 @@ static struct sk_buff *ena_rx_skb(struct ena_ring *rx_ring, page_offset = rx_info->page_offset; buf_addr = page_address(rx_info->page) + page_offset; - if (len <= rx_ring->rx_copybreak) { + if (len <= rx_ring->rx_copybreak && likely(descs == 1)) { skb = ena_alloc_skb(rx_ring, NULL, len); if (unlikely(!skb)) return NULL; @@ -1009,6 +1009,10 @@ static struct sk_buff *ena_rx_skb(struct ena_ring *rx_ring, buf_len = SKB_DATA_ALIGN(len + buf_offset + tailroom); + skb = ena_alloc_skb(rx_ring, buf_addr, buf_len); + if (unlikely(!skb)) + return NULL; + /* If XDP isn't loaded try to reuse part of the RX buffer */ reuse_rx_buf_page = !is_xdp_loaded && ena_try_rx_buf_page_reuse(rx_info, buf_len, len, pkt_offset); @@ -1016,10 +1020,6 @@ static struct sk_buff *ena_rx_skb(struct ena_ring *rx_ring, if (!reuse_rx_buf_page) ena_unmap_rx_buff_attrs(rx_ring, rx_info, DMA_ATTR_SKIP_CPU_SYNC); - skb = ena_alloc_skb(rx_ring, buf_addr, buf_len); - if (unlikely(!skb)) - return NULL; - /* Populate skb's linear part */ skb_reserve(skb, buf_offset); skb_put(skb, len); @@ -1293,7 +1293,8 @@ static int ena_clean_rx_irq(struct ena_ring *rx_ring, struct napi_struct *napi, skb_record_rx_queue(skb, rx_ring->qid); - if (rx_ring->ena_bufs[0].len <= rx_ring->rx_copybreak) + if (rx_ring->ena_bufs[0].len <= rx_ring->rx_copybreak && + ena_rx_ctx.descs == 1) rx_copybreak_pkt++; total_len += skb->len; diff --git a/drivers/net/ethernet/broadcom/bgmac-platform.c b/drivers/net/ethernet/broadcom/bgmac-platform.c index 4e266ce41180..4880b1890481 100644 --- a/drivers/net/ethernet/broadcom/bgmac-platform.c +++ b/drivers/net/ethernet/broadcom/bgmac-platform.c @@ -243,7 +243,8 @@ static int bgmac_probe(struct platform_device *pdev) bgmac->phy_connect = platform_phy_connect; } else { bgmac->phy_connect = bgmac_phy_connect_direct; - bgmac->feature_flags |= BGMAC_FEAT_FORCE_SPEED_2500; + if (of_machine_is_compatible("brcm,nsp")) + bgmac->feature_flags |= BGMAC_FEAT_FORCE_SPEED_2500; } return bgmac_enet_probe(bgmac); diff --git a/drivers/net/ethernet/broadcom/bgmac.c b/drivers/net/ethernet/broadcom/bgmac.c index b3f0ecc583fd..409155fe8df0 100644 --- a/drivers/net/ethernet/broadcom/bgmac.c +++ b/drivers/net/ethernet/broadcom/bgmac.c @@ -1428,11 +1428,15 @@ void bgmac_adjust_link(struct net_device *net_dev) { struct bgmac *bgmac = netdev_priv(net_dev); struct phy_device *phy_dev = net_dev->phydev; + int speed = phy_dev->speed; bool update = false; + if (bgmac->feature_flags & BGMAC_FEAT_FORCE_SPEED_2500) + speed = SPEED_2500; + if (phy_dev->link) { - if (phy_dev->speed != bgmac->mac_speed) { - bgmac->mac_speed = phy_dev->speed; + if (speed != bgmac->mac_speed) { + bgmac->mac_speed = speed; update = true; } diff --git a/drivers/net/ethernet/broadcom/bnge/bnge_netdev.c b/drivers/net/ethernet/broadcom/bnge/bnge_netdev.c index 02be751f3d8f..d1c55ac9318f 100644 --- a/drivers/net/ethernet/broadcom/bnge/bnge_netdev.c +++ b/drivers/net/ethernet/broadcom/bnge/bnge_netdev.c @@ -1670,18 +1670,19 @@ static bool bnge_uc_list_updated(struct bnge_net *bn) struct bnge_vnic_info *vnic = &bn->vnic_info[BNGE_VNIC_DEFAULT]; struct net_device *dev = bn->netdev; struct netdev_hw_addr *ha; - int off = 0; - - if (netdev_uc_count(dev) != (vnic->uc_filter_count - 1)) - return true; + int off = 0, count = 0; netdev_for_each_uc_addr(ha, dev) { + if (ether_addr_equal(ha->addr, dev->dev_addr)) + continue; + if (count >= vnic->uc_filter_count - 1) + return true; if (!ether_addr_equal(ha->addr, vnic->uc_list + off)) return true; - off += ETH_ALEN; + count++; } - return false; + return count != vnic->uc_filter_count - 1; } static bool bnge_promisc_ok(struct bnge_net *bn) @@ -1693,9 +1694,9 @@ static int bnge_cfg_def_vnic(struct bnge_net *bn) { struct bnge_vnic_info *vnic = &bn->vnic_info[BNGE_VNIC_DEFAULT]; struct net_device *dev = bn->netdev; + int i, off = 0, rc, uc_count = 0; struct bnge_dev *bd = bn->bd; struct netdev_hw_addr *ha; - int i, off = 0, rc; bool uc_update; netif_addr_lock_bh(dev); @@ -1715,10 +1716,20 @@ static int bnge_cfg_def_vnic(struct bnge_net *bn) vnic->uc_filter_count = 1; netif_addr_lock_bh(dev); - if (netdev_uc_count(dev) > (BNGE_MAX_UC_ADDRS - 1)) { + /* dev_addr is already programmed as L2 filter 0, so it takes neither a + * uc_list slot nor an l2_filters[] slot. Count only the entries that + * will actually be programmed so the overflow check matches the fill + * loop below (and bnge_uc_list_updated()). + */ + netdev_for_each_uc_addr(ha, dev) + if (!ether_addr_equal(ha->addr, dev->dev_addr)) + uc_count++; + if (uc_count > BNGE_MAX_UC_ADDRS - 1) { vnic->rx_mask |= CFA_L2_SET_RX_MASK_REQ_MASK_PROMISCUOUS; } else { netdev_for_each_uc_addr(ha, dev) { + if (ether_addr_equal(ha->addr, dev->dev_addr)) + continue; memcpy(vnic->uc_list + off, ha->addr, ETH_ALEN); off += ETH_ALEN; vnic->uc_filter_count++; diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt.c b/drivers/net/ethernet/broadcom/bnxt/bnxt.c index 414da981a3e5..2b1567616f51 100644 --- a/drivers/net/ethernet/broadcom/bnxt/bnxt.c +++ b/drivers/net/ethernet/broadcom/bnxt/bnxt.c @@ -11374,6 +11374,7 @@ static int bnxt_change_msix(struct bnxt *bp, int total) map.index = i - 1; map.virq = bp->irq_tbl[i - 1].vector; pci_msix_free_irq(bp->pdev, map); + bp->irq_tbl[i - 1].vector = 0; bp->total_irqs--; } return bp->total_irqs; @@ -11551,8 +11552,23 @@ int bnxt_reserve_rings(struct bnxt *bp, bool irq_re_init) int irqs_required; int rc; - if (!bnxt_need_reserve_rings(bp)) + if (!bnxt_need_reserve_rings(bp)) { + /* FW may already hold the reservation from an earlier + * reservation that was not followed by growing the dynamic + * MSI-X vectors, e.g. because the allocation failed. + */ + if (irq_re_init && BNXT_NEW_RM(bp) && bp->irq_tbl && + pci_msix_can_alloc_dyn(bp->pdev)) { + irqs_required = bnxt_get_num_msix(bp); + if (irqs_required > bp->total_irqs && + bnxt_change_msix(bp, irqs_required) != irqs_required) { + netdev_err(bp->dev, "Unable to allocate %d MSIX vectors, maximum available %d\n", + irqs_required, bp->total_irqs); + return -ENOSPC; + } + } return 0; + } if (BNXT_NEW_RM(bp) && !bnxt_ulp_registered(edev)) { int ulp_msix = bnxt_get_avail_msix(bp, bp->ulp_num_msix_want); @@ -11578,6 +11594,10 @@ int bnxt_reserve_rings(struct bnxt *bp, bool irq_re_init) rc = bnxt_init_int_mode(bp); bnxt_ulp_irq_restart(bp, rc); } else if (irq_change && !rc) { + /* Size the vectors from what FW actually reserved, which + * can be less than what was requested. + */ + irqs_required = bnxt_get_num_msix(bp); if (bnxt_change_msix(bp, irqs_required) != irqs_required) rc = -ENOSPC; } @@ -14567,8 +14587,12 @@ static int bnxt_get_registered_vfs(struct bnxt *bp) void bnxt_fw_reset(struct bnxt *bp) { bnxt_ulp_stop(bp); - clear_bit(BNXT_STATE_IN_SP_TASK, &bp->state); - netdev_lock(bp->dev); + if (BNXT_PF(bp)) { + bnxt_rtnl_lock_sp(bp); + } else { + clear_bit(BNXT_STATE_IN_SP_TASK, &bp->state); + netdev_lock(bp->dev); + } if (test_bit(BNXT_STATE_OPEN, &bp->state) && !test_bit(BNXT_STATE_IN_FW_RESET, &bp->state)) { struct bnxt_ptp_cfg *ptp = bp->ptp_cfg; @@ -14614,8 +14638,12 @@ void bnxt_fw_reset(struct bnxt *bp) bnxt_queue_fw_reset_work(bp, tmo); } fw_reset_exit: - set_bit(BNXT_STATE_IN_SP_TASK, &bp->state); - netdev_unlock(bp->dev); + if (BNXT_PF(bp)) { + bnxt_rtnl_unlock_sp(bp); + } else { + set_bit(BNXT_STATE_IN_SP_TASK, &bp->state); + netdev_unlock(bp->dev); + } } static void bnxt_chk_missed_irq(struct bnxt *bp) @@ -14867,6 +14895,7 @@ int bnxt_check_rings(struct bnxt *bp, int tx, int rx, bool sh, int tcs, hwr.cp = min_t(int, hwr.cp, bnxt_get_max_func_irqs(bp)); } if (hwr.cp > bp->total_irqs) { + int old_total = bp->total_irqs; int total_msix = bnxt_change_msix(bp, hwr.cp); if (total_msix < hwr.cp) { @@ -14874,6 +14903,17 @@ int bnxt_check_rings(struct bnxt *bp, int tx, int rx, bool sh, int tcs, hwr.cp, total_msix); rc = -ENOSPC; } + /* FW has not reserved the new vectors yet, and writes to + * MSI-X table entries beyond the reserved IRQs don't + * stick (seen on BCM57508). Free them again; + * bnxt_reserve_rings() allocates them after + * __bnxt_reserve_rings(). Without the new resource + * manager there is no IRQ reservation and + * bnxt_reserve_rings() does not grow the vectors, so + * keep them. + */ + if (BNXT_NEW_RM(bp)) + bnxt_change_msix(bp, old_total); } } return rc; @@ -15268,9 +15308,8 @@ static void bnxt_fw_reset_task(struct work_struct *work) bp->fw_reset_timestamp = jiffies; netdev_lock(bp->dev); if (test_bit(BNXT_STATE_ABORT_ERR, &bp->state)) { - bnxt_fw_reset_abort(bp, rc); netdev_unlock(bp->dev); - goto ulp_start; + goto fw_reset_abort; } bnxt_fw_reset_close(bp); if (bp->fw_cap & BNXT_FW_CAP_ERR_RECOVER_RELOAD) { @@ -15403,9 +15442,11 @@ static void bnxt_fw_reset_task(struct work_struct *work) netdev_err(bp->dev, "fw_health_status 0x%x\n", sts); } fw_reset_abort: + rtnl_lock(); netdev_lock(bp->dev); bnxt_fw_reset_abort(bp, rc); netdev_unlock(bp->dev); + rtnl_unlock(); ulp_start: if (!rc) bnxt_ulp_start(bp); diff --git a/drivers/net/ethernet/cadence/macb.h b/drivers/net/ethernet/cadence/macb.h index a6602aae3f9d..008d7dc67009 100644 --- a/drivers/net/ethernet/cadence/macb.h +++ b/drivers/net/ethernet/cadence/macb.h @@ -1458,7 +1458,6 @@ struct macb_platform_data { * @start_time_mask: Bitmask representing the start time for the queue * @on_time_bytes: "on" time nsec expressed in bytes * @off_time_bytes: "off" time nsec expressed in bytes - * @queue_id: Identifier for the queue * * This structure holds the configuration parameters for an ENST queue, * used to control time-based transmission scheduling in the MACB driver. @@ -1467,7 +1466,6 @@ struct macb_queue_enst_config { u32 start_time_mask; u32 on_time_bytes; u32 off_time_bytes; - u8 queue_id; }; #endif /* _MACB_H */ diff --git a/drivers/net/ethernet/cadence/macb_main.c b/drivers/net/ethernet/cadence/macb_main.c index 1eaf9be48315..112b1785e817 100644 --- a/drivers/net/ethernet/cadence/macb_main.c +++ b/drivers/net/ethernet/cadence/macb_main.c @@ -4232,7 +4232,8 @@ static int macb_taprio_setup_replace(struct net_device *ndev, struct macb *bp = netdev_priv(ndev); struct ethtool_link_ksettings kset; struct macb_queue *queue; - size_t i; + size_t i, q; + u8 queue_id; int err; if (conf->num_entries > bp->num_queues) { @@ -4260,7 +4261,7 @@ static int macb_taprio_setup_replace(struct net_device *ndev, return -EINVAL; } - enst_queue = kcalloc(conf->num_entries, sizeof(*enst_queue), GFP_KERNEL); + enst_queue = kcalloc(bp->num_queues, sizeof(*enst_queue), GFP_KERNEL); if (unlikely(!enst_queue)) return -ENOMEM; @@ -4318,13 +4319,14 @@ static int macb_taprio_setup_replace(struct net_device *ndev, goto cleanup; } - enst_queue[i].queue_id = order_base_2(entry->gate_mask); - enst_queue[i].start_time_mask = + /* Map the hardware queue to its index in bp->queues (the mask may be sparse) */ + queue_id = hweight32(bp->queue_mask & (entry->gate_mask - 1)); + enst_queue[queue_id].start_time_mask = (start_time_sec << GEM_START_TIME_SEC_OFFSET) | start_time_nsec; - enst_queue[i].on_time_bytes = + enst_queue[queue_id].on_time_bytes = enst_ns_to_hw_units(entry->interval, speed); - enst_queue[i].off_time_bytes = + enst_queue[queue_id].off_time_bytes = enst_ns_to_hw_units(conf->cycle_time - entry->interval, speed); configured_queues |= entry->gate_mask; @@ -4349,15 +4351,14 @@ static int macb_taprio_setup_replace(struct net_device *ndev, gem_writel(bp, ENST_CONTROL, bp->queue_mask << GEM_ENST_DISABLE_QUEUE_OFFSET); - for (i = 0; i < conf->num_entries; i++) { - queue = &bp->queues[enst_queue[i].queue_id]; + for (q = 0, queue = bp->queues; q < bp->num_queues; ++q, ++queue) { /* Configure queue timing registers */ queue_writel(queue, ENST_START_TIME, - enst_queue[i].start_time_mask); + enst_queue[q].start_time_mask); queue_writel(queue, ENST_ON_TIME, - enst_queue[i].on_time_bytes); + enst_queue[q].on_time_bytes); queue_writel(queue, ENST_OFF_TIME, - enst_queue[i].off_time_bytes); + enst_queue[q].off_time_bytes); } /* Enable ENST for all configured queues in one write */ diff --git a/drivers/net/ethernet/intel/i40e/i40e_xsk.c b/drivers/net/ethernet/intel/i40e/i40e_xsk.c index 9f47388eaba5..e48fee2a4229 100644 --- a/drivers/net/ethernet/intel/i40e/i40e_xsk.c +++ b/drivers/net/ethernet/intel/i40e/i40e_xsk.c @@ -318,22 +318,19 @@ static struct sk_buff *i40e_construct_skb_zc(struct i40e_ring *rx_ring, goto out; for (int i = 0; i < nr_frags; i++) { - struct skb_shared_info *skinfo = skb_shinfo(skb); skb_frag_t *frag = &sinfo->frags[i]; + unsigned int frag_size = skb_frag_size(frag); struct page *page; - void *addr; page = dev_alloc_page(); if (!page) { dev_kfree_skb(skb); - return NULL; + skb = NULL; + goto out; } - addr = page_to_virt(page); - memcpy(addr, skb_frag_page(frag), skb_frag_size(frag)); - - __skb_fill_page_desc_noacc(skinfo, skinfo->nr_frags++, - addr, 0, skb_frag_size(frag)); + memcpy(page_to_virt(page), skb_frag_address(frag), frag_size); + skb_add_rx_frag(skb, i, page, 0, frag_size, PAGE_SIZE); } out: @@ -459,16 +456,24 @@ int i40e_clean_rx_irq_zc(struct i40e_ring *rx_ring, int budget) xsk_buff_set_size(bi, size); xsk_buff_dma_sync_for_cpu(bi); - if (!first) + if (++next_to_process == count) + next_to_process = 0; + + if (!first) { first = bi; - else if (!xsk_buff_add_frag(first, bi)) { + } else if (!xsk_buff_add_frag(first, bi)) { + /* Drop what has been gathered so far. xp_free() skips + * @bi if it duplicates a buffer that is already on a + * pool list. Remaining buffers of this packet, if any, + * will be processed as a new packet. + */ xsk_buff_free(first); - break; + xsk_buff_free(bi); + next_to_clean = next_to_process; + first = NULL; + continue; } - if (++next_to_process == count) - next_to_process = 0; - if (i40e_is_non_eop(rx_ring, rx_desc)) continue; diff --git a/drivers/net/ethernet/intel/ice/ice_adapter.c b/drivers/net/ethernet/intel/ice/ice_adapter.c index 0a8a48cd4bce..8d0a4f6653cf 100644 --- a/drivers/net/ethernet/intel/ice/ice_adapter.c +++ b/drivers/net/ethernet/intel/ice/ice_adapter.c @@ -6,6 +6,7 @@ #include #include #include +#include #include #include "ice_adapter.h" #include "ice.h" @@ -54,26 +55,34 @@ static unsigned long ice_adapter_xa_index(struct pci_dev *pdev) static struct ice_adapter *ice_adapter_new(struct pci_dev *pdev) { struct ice_adapter *adapter; + int err; adapter = kzalloc(sizeof(*adapter), GFP_KERNEL); if (!adapter) return NULL; + err = init_srcu_struct(&adapter->ports.srcu); + if (err) { + kfree(adapter); + return NULL; + } + adapter->index = ice_adapter_index(pdev); spin_lock_init(&adapter->ptp_gltsyn_time_lock); spin_lock_init(&adapter->txq_ctx_lock); refcount_set(&adapter->refcount, 1); - mutex_init(&adapter->ports.lock); - INIT_LIST_HEAD(&adapter->ports.ports); + spin_lock_init(&adapter->ports.lock); + INIT_LIST_HEAD(&adapter->ports.list); return adapter; } static void ice_adapter_free(struct ice_adapter *adapter) { - WARN_ON(!list_empty(&adapter->ports.ports)); - mutex_destroy(&adapter->ports.lock); + WARN_ON(!list_empty(&adapter->ports.list)); + + cleanup_srcu_struct(&adapter->ports.srcu); kfree(adapter); } diff --git a/drivers/net/ethernet/intel/ice/ice_adapter.h b/drivers/net/ethernet/intel/ice/ice_adapter.h index e95266c7f20b..636ee05f110a 100644 --- a/drivers/net/ethernet/intel/ice/ice_adapter.h +++ b/drivers/net/ethernet/intel/ice/ice_adapter.h @@ -5,6 +5,7 @@ #define _ICE_ADAPTER_H_ #include +#include #include #include @@ -14,15 +15,19 @@ struct ice_pf; /** * struct ice_port_list - data used to store the list of adapter ports * - * This structure contains data used to maintain a list of adapter ports + * This structure contains data used to maintain a list of adapter ports. + * Writers modifying the list *must* acquire the lock, and use SRCU safe list + * operations. Readers should use srcu_read_lock() on the provided domain. * - * @ports: list of ports - * @lock: protect access to the ports list + * @list: list of ports + * @lock: protect write access to the list + * @srcu: Sleepable RCU domain for this adapter */ struct ice_port_list { - struct list_head ports; - /* To synchronize the ports list operations */ - struct mutex lock; + struct list_head list; + /* To synchronize write operations on the port list */ + spinlock_t lock; + struct srcu_struct srcu; }; /** diff --git a/drivers/net/ethernet/intel/ice/ice_ptp.c b/drivers/net/ethernet/intel/ice/ice_ptp.c index d33cd5f5f21c..09e9550096a0 100644 --- a/drivers/net/ethernet/intel/ice/ice_ptp.c +++ b/drivers/net/ethernet/intel/ice/ice_ptp.c @@ -1,6 +1,9 @@ // SPDX-License-Identifier: GPL-2.0 /* Copyright (C) 2021, Intel Corporation. */ +#include +#include +#include #include "ice.h" #include "ice_lib.h" #include "ice_trace.h" @@ -674,20 +677,37 @@ static void ice_ptp_process_tx_tstamp(struct ice_ptp_tx *tx) } } +static void ice_ptp_release_port_srcu(struct kref *ref) +{ + /* wake_up_var() requires full ordering but kref_put only provides + * release ordering. + */ + smp_mb__after_atomic(); + wake_up_var(ref); +} + static void ice_ptp_tx_tstamp_owner(struct ice_pf *pf) { + struct ice_port_list *ports = &pf->adapter->ports; struct ice_ptp_port *port; + int srcu_idx; - mutex_lock(&pf->adapter->ports.lock); - list_for_each_entry(port, &pf->adapter->ports.ports, list_node) { + srcu_idx = srcu_read_lock(&ports->srcu); + list_for_each_entry_srcu(port, &ports->list, list_node, + srcu_read_lock_held(&ports->srcu)) { struct ice_ptp_tx *tx = &port->tx; - if (!tx || !tx->init) + if (!tx->init) + continue; + + if (!kref_get_unless_zero(&port->ref)) continue; ice_ptp_process_tx_tstamp(tx); + + kref_put(&port->ref, ice_ptp_release_port_srcu); } - mutex_unlock(&pf->adapter->ports.lock); + srcu_read_unlock(&ports->srcu, srcu_idx); } /** @@ -807,10 +827,19 @@ ice_ptp_mark_tx_tracker_stale(struct ice_ptp_tx *tx) static void ice_ptp_flush_all_tx_tracker(struct ice_pf *pf) { + struct ice_port_list *ports = &pf->adapter->ports; struct ice_ptp_port *port; + int srcu_idx; - list_for_each_entry(port, &pf->adapter->ports.ports, list_node) + srcu_idx = srcu_read_lock(&ports->srcu); + list_for_each_entry_srcu(port, &ports->list, list_node, + srcu_read_lock_held(&ports->srcu)) { + if (!kref_get_unless_zero(&port->ref)) + continue; ice_ptp_flush_tx_tracker(ptp_port_to_pf(port), &port->tx); + kref_put(&port->ref, ice_ptp_release_port_srcu); + } + srcu_read_unlock(&ports->srcu, srcu_idx); } /** @@ -1403,16 +1432,22 @@ static void ice_ptp_reset_phy_timestamping(struct ice_pf *pf) */ static void ice_ptp_restart_all_phy(struct ice_pf *pf) { - struct list_head *entry; + struct ice_port_list *ports = &pf->adapter->ports; + struct ice_ptp_port *port; + int srcu_idx; - list_for_each(entry, &pf->adapter->ports.ports) { - struct ice_ptp_port *port = list_entry(entry, - struct ice_ptp_port, - list_node); + srcu_idx = srcu_read_lock(&ports->srcu); + list_for_each_entry_srcu(port, &ports->list, list_node, + srcu_read_lock_held(&ports->srcu)) { + if (!kref_get_unless_zero(&port->ref)) + continue; if (port->link_up) ice_ptp_port_phy_restart(port); + + kref_put(&port->ref, ice_ptp_release_port_srcu); } + srcu_read_unlock(&ports->srcu, srcu_idx); } /** @@ -2672,19 +2707,28 @@ static bool ice_port_has_timestamps(struct ice_ptp_tx *tx) static bool ice_any_port_has_timestamps(struct ice_pf *pf) { + struct ice_port_list *ports = &pf->adapter->ports; + bool have_tstamps = false; struct ice_ptp_port *port; + int srcu_idx; - scoped_guard(mutex, &pf->adapter->ports.lock) { - list_for_each_entry(port, &pf->adapter->ports.ports, - list_node) { - struct ice_ptp_tx *tx = &port->tx; + srcu_idx = srcu_read_lock(&ports->srcu); + list_for_each_entry_srcu(port, &ports->list, list_node, + srcu_read_lock_held(&ports->srcu)) { + if (!kref_get_unless_zero(&port->ref)) + continue; - if (ice_port_has_timestamps(tx)) - return true; - } + if (ice_port_has_timestamps(&port->tx)) + have_tstamps = true; + + kref_put(&port->ref, ice_ptp_release_port_srcu); + + if (have_tstamps) + break; } + srcu_read_unlock(&ports->srcu, srcu_idx); - return false; + return have_tstamps; } bool ice_ptp_tx_tstamps_pending(struct ice_pf *pf) @@ -2868,14 +2912,18 @@ void ice_ptp_queue_work(struct ice_pf *pf) static void ice_ptp_prepare_rebuild_sec(struct ice_pf *pf, bool rebuild, enum ice_reset_req reset_type) { - struct list_head *entry; + struct ice_port_list *ports = &pf->adapter->ports; + struct ice_ptp_port *port; + int srcu_idx; - list_for_each(entry, &pf->adapter->ports.ports) { - struct ice_ptp_port *port = list_entry(entry, - struct ice_ptp_port, - list_node); + srcu_idx = srcu_read_lock(&ports->srcu); + list_for_each_entry_srcu(port, &ports->list, list_node, + srcu_read_lock_held(&ports->srcu)) { struct ice_pf *peer_pf = ptp_port_to_pf(port); + if (!kref_get_unless_zero(&port->ref)) + continue; + if (!ice_is_primary(&peer_pf->hw)) { if (rebuild) { /* TODO: When implementing rebuild=true: @@ -2887,7 +2935,10 @@ static void ice_ptp_prepare_rebuild_sec(struct ice_pf *pf, bool rebuild, ice_ptp_prepare_for_reset(peer_pf, reset_type); } } + + kref_put(&port->ref, ice_ptp_release_port_srcu); } + srcu_read_unlock(&ports->srcu, srcu_idx); } /** @@ -3069,24 +3120,34 @@ static int ice_ptp_setup_pf(struct ice_pf *pf) return -ENODEV; INIT_LIST_HEAD(&ptp->port.list_node); - mutex_lock(&pf->adapter->ports.lock); + kref_init(&ptp->port.ref); - list_add(&ptp->port.list_node, - &pf->adapter->ports.ports); - mutex_unlock(&pf->adapter->ports.lock); + spin_lock(&pf->adapter->ports.lock); + list_add_rcu(&ptp->port.list_node, &pf->adapter->ports.list); + spin_unlock(&pf->adapter->ports.lock); return 0; } static void ice_ptp_cleanup_pf(struct ice_pf *pf) { + struct ice_port_list *ports = &pf->adapter->ports; struct ice_ptp *ptp = &pf->ptp; + struct kref *ref; - if (pf->hw.mac_type != ICE_MAC_UNKNOWN) { - mutex_lock(&pf->adapter->ports.lock); - list_del(&ptp->port.list_node); - mutex_unlock(&pf->adapter->ports.lock); - } + if (pf->hw.mac_type == ICE_MAC_UNKNOWN) + return; + + spin_lock(&ports->lock); + list_del_rcu(&ptp->port.list_node); + spin_unlock(&ports->lock); + + ref = &ptp->port.ref; + kref_put(ref, ice_ptp_release_port_srcu); + + wait_var_event(ref, !kref_read(ref)); + + synchronize_srcu(&ports->srcu); } /** diff --git a/drivers/net/ethernet/intel/ice/ice_ptp.h b/drivers/net/ethernet/intel/ice/ice_ptp.h index 0a5a1db66d61..1a1ea1891245 100644 --- a/drivers/net/ethernet/intel/ice/ice_ptp.h +++ b/drivers/net/ethernet/intel/ice/ice_ptp.h @@ -5,6 +5,8 @@ #define _ICE_PTP_H_ #include +#include +#include #include #include "ice_ptp_hw.h" @@ -138,6 +140,7 @@ struct ice_ptp_tx { * and determine when the port's PHY offset is valid. * * @list_node: list member structure + * @ref: reference counter for use with adapter ports list * @tx: Tx timestamp tracking for this port * @ov_work: delayed work task for tracking when PHY offset is valid * @ps_lock: mutex used to protect the overall PTP PHY start procedure @@ -147,6 +150,7 @@ struct ice_ptp_tx { */ struct ice_ptp_port { struct list_head list_node; + struct kref ref; struct ice_ptp_tx tx; struct kthread_delayed_work ov_work; struct mutex ps_lock; /* protects overall PTP PHY start procedure */ diff --git a/drivers/net/ethernet/intel/ice/ice_xsk.c b/drivers/net/ethernet/intel/ice/ice_xsk.c index 102631398af3..9840522d65da 100644 --- a/drivers/net/ethernet/intel/ice/ice_xsk.c +++ b/drivers/net/ethernet/intel/ice/ice_xsk.c @@ -494,6 +494,11 @@ static int ice_xmit_xdp_tx_zc(struct xdp_buff *xdp, tx_desc->cmd_type_offset_bsz |= cpu_to_le64(ICE_TX_DESC_CMD_EOP << ICE_TXD_QW1_CMD_S); + /* Each frag is now freed via its own Tx buffer. Completing the head + * must not release what is on the pool's frag list at that time. + */ + xdp_buff_clear_frags_flag(head); + return ICE_XDP_TX; busy: @@ -593,6 +598,7 @@ int ice_clean_rx_irq_zc(struct ice_rx_ring *rx_ring, struct sk_buff *skb; u16 stat_err_bits; u16 vlan_tci; + u32 xdp_len; rx_desc = ICE_RX_DESC(rx_ring, ntc); @@ -619,8 +625,11 @@ int ice_clean_rx_irq_zc(struct ice_rx_ring *rx_ring, if (!first) { first = xdp; - } else if (likely(size) && !xsk_buff_add_frag(first, xdp)) { + } else if (unlikely(!size)) { + xsk_buff_free(xdp); + } else if (!xsk_buff_add_frag(first, xdp)) { xsk_buff_free(first); + xsk_buff_free(xdp); first = NULL; } @@ -632,6 +641,7 @@ int ice_clean_rx_irq_zc(struct ice_rx_ring *rx_ring, ((struct libeth_xdp_buff *)first)->desc = rx_desc; + xdp_len = xdp_get_buff_len(first); xdp_res = ice_run_xdp_zc(rx_ring, first, xdp_prog, xdp_ring, xsk_pool); if (likely(xdp_res & (ICE_XDP_TX | ICE_XDP_REDIR))) { @@ -646,7 +656,7 @@ int ice_clean_rx_irq_zc(struct ice_rx_ring *rx_ring, goto construct_skb; } - total_rx_bytes += xdp_get_buff_len(first); + total_rx_bytes += xdp_len; total_rx_packets++; first = NULL; @@ -903,6 +913,11 @@ void ice_xsk_clean_rx_ring(struct ice_rx_ring *rx_ring) if (xdp_rxq_info_is_reg(&rx_ring->xdp_rxq)) xdp_rxq_info_unreg(&rx_ring->xdp_rxq); + if (rx_ring->xsk) { + xsk_buff_free(&rx_ring->xsk->base); + rx_ring->xsk = NULL; + } + while (ntc != ntu) { struct xdp_buff *xdp = *ice_xdp_buf(rx_ring, ntc); diff --git a/drivers/net/ethernet/intel/idpf/xsk.c b/drivers/net/ethernet/intel/idpf/xsk.c index fd2cc43ab43c..463c6852f8c9 100644 --- a/drivers/net/ethernet/intel/idpf/xsk.c +++ b/drivers/net/ethernet/intel/idpf/xsk.c @@ -132,6 +132,11 @@ void idpf_xsk_clear_queue(void *q, enum virtchnl2_queue_type type) if (!idpf_queue_has_clear(XSK, rxq)) return; + if (rxq->xsk) { + libeth_xsk_buff_free_slow(rxq->xsk); + rxq->xsk = NULL; + } + rxq->pool = NULL; break; case VIRTCHNL2_QUEUE_TYPE_RX_BUFFER: diff --git a/drivers/net/ethernet/mediatek/mtk_ppe.c b/drivers/net/ethernet/mediatek/mtk_ppe.c index bb01a7355932..fc1362cd821c 100644 --- a/drivers/net/ethernet/mediatek/mtk_ppe.c +++ b/drivers/net/ethernet/mediatek/mtk_ppe.c @@ -754,8 +754,7 @@ void __mtk_ppe_check_skb(struct mtk_ppe *ppe, struct sk_buff *skb, u16 hash) hlist_for_each_entry_safe(entry, n, head, list) { if (entry->type == MTK_FLOW_TYPE_L2_SUBFLOW) { - if (unlikely(FIELD_GET(MTK_FOE_IB1_STATE, hwe->ib1) == - MTK_FOE_STATE_BIND)) + if (entry->hash != hash) continue; entry->hash = 0xffff; @@ -764,7 +763,7 @@ void __mtk_ppe_check_skb(struct mtk_ppe *ppe, struct sk_buff *skb, u16 hash) } if (found || !mtk_flow_entry_match(ppe->eth, entry, hwe)) { - if (entry->hash != 0xffff) + if (entry->hash == hash) entry->hash = 0xffff; continue; } diff --git a/drivers/net/ethernet/mediatek/mtk_wed.c b/drivers/net/ethernet/mediatek/mtk_wed.c index fdb487e5d46e..03829017dc49 100644 --- a/drivers/net/ethernet/mediatek/mtk_wed.c +++ b/drivers/net/ethernet/mediatek/mtk_wed.c @@ -257,7 +257,7 @@ mtk_wdma_rx_reset(struct mtk_wed_device *dev) wdma_w32(dev, MTK_WDMA_RESET_IDX, 0); for (i = 0; i < ARRAY_SIZE(dev->rx_wdma); i++) { - if (dev->rx_wdma[i].desc) + if (!dev->rx_wdma[i].desc) continue; wdma_w32(dev, @@ -949,6 +949,14 @@ mtk_wed_free_ring(struct mtk_wed_device *dev, struct mtk_wed_ring *ring) static void mtk_wed_free_rx_rings(struct mtk_wed_device *dev) { + int i; + + for (i = 0; i < ARRAY_SIZE(dev->rx_ring); i++) + mtk_wed_free_ring(dev, &dev->rx_ring[i]); + + for (i = 0; i < ARRAY_SIZE(dev->tx_wdma); i++) + mtk_wed_free_ring(dev, &dev->tx_wdma[i]); + mtk_wed_free_rx_buffer(dev); mtk_wed_free_ring(dev, &dev->rro.ring); } @@ -1938,7 +1946,7 @@ mtk_wed_wdma_tx_ring_setup(struct mtk_wed_device *dev, int idx, int size, wdma_w32(dev, MTK_WDMA_RING_TX(idx) + MTK_WED_RING_OFS_CPU_IDX, 0); wdma_w32(dev, MTK_WDMA_RING_TX(idx) + MTK_WED_RING_OFS_DMA_IDX, 0); - if (reset) + if (!mtk_wed_is_v3_or_greater(dev->hw) && reset) mtk_wed_ring_reset(wdma, MTK_WED_WDMA_RING_SIZE, true); if (!idx) { @@ -2337,7 +2345,20 @@ mtk_wed_start(struct mtk_wed_device *dev, u32 irq_mask) for (i = 0; i < ARRAY_SIZE(dev->rx_wdma); i++) if (!dev->rx_wdma[i].desc) - mtk_wed_wdma_rx_ring_setup(dev, i, 16, false); + if (mtk_wed_wdma_rx_ring_setup(dev, i, 16, false)) { + dev_err(dev->hw->dev, "wdma rx ring %d setup failed\n", i); + return; + } + + /* + * non-DBDC MT7986 allocates only rx_ring[1] and tx_wdma[1] during setup + * but tx_wdma[0] is also needed for WED to function. + */ + if (mtk_wed_is_v2(dev->hw) && !dev->rx_ring[0].desc) + if (mtk_wed_wdma_tx_ring_setup(dev, 0, MTK_WED_WDMA_RING_SIZE, !!dev->tx_wdma[0].desc)) { + dev_err(dev->hw->dev, "wdma tx ring 0 setup failed\n"); + return; + } if (dev->wlan.hw_rro) { for (i = 0; i < MTK_WED_RX_PAGE_QUEUES; i++) { diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en/params.c b/drivers/net/ethernet/mellanox/mlx5/core/en/params.c index c9bdee9a8b30..b8af6fa297e8 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en/params.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en/params.c @@ -873,10 +873,11 @@ static void mlx5e_build_rx_cq_param(struct mlx5_core_dev *mdev, static u8 rq_end_pad_mode(struct mlx5_core_dev *mdev, struct mlx5e_params *params) { - bool lro_en = params->packet_merge.type == MLX5E_PACKET_MERGE_LRO; + bool no_pad = params->packet_merge.type == MLX5E_PACKET_MERGE_LRO || + params->packet_merge.type == MLX5E_PACKET_MERGE_SHAMPO; bool ro = MLX5_CAP_GEN(mdev, relaxed_ordering_write); - return ro && lro_en ? + return ro && no_pad ? MLX5_WQ_END_PAD_MODE_NONE : MLX5_WQ_END_PAD_MODE_ALIGN; } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.c b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.c index 2874a50bead6..611876f20413 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.c @@ -775,12 +775,20 @@ static int mlx5e_xfrm_add_state(struct net_device *dev, { struct mlx5e_ipsec_sa_entry *sa_entry = NULL; bool allow_tunnel_mode = false; + struct mlx5_core_dev *mdev; struct mlx5e_ipsec *ipsec; struct mlx5e_priv *priv; gfp_t gfp; int err; priv = netdev_priv(dev); + /* Profile cleanup can memset an already NULL mdev. */ + mdev = data_race(READ_ONCE(priv->mdev)); + /* NULL only during a profile change, which is an eswitch operation. */ + if (!mdev) { + NL_SET_ERR_MSG_MOD(extack, "Eswitch busy, can't add state"); + return -EBUSY; + } if (!priv->ipsec) return -EOPNOTSUPP; @@ -799,16 +807,16 @@ static int mlx5e_xfrm_add_state(struct net_device *dev, return 0; } - err = mlx5e_xfrm_validate_state(priv->mdev, x, extack); + err = mlx5e_xfrm_validate_state(mdev, x, extack); if (err) goto err_xfrm; - if (!mlx5_eswitch_block_ipsec(priv->mdev)) { + if (!mlx5_eswitch_block_ipsec(mdev)) { err = -EBUSY; goto err_xfrm; } - err = mlx5_eswitch_block_mode(priv->mdev); + err = mlx5_eswitch_block_mode(mdev); if (err) goto unblock_ipsec; @@ -876,9 +884,9 @@ static int mlx5e_xfrm_add_state(struct net_device *dev, x->xso.offload_handle = (unsigned long)sa_entry; if (allow_tunnel_mode) - mlx5_eswitch_unblock_encap(priv->mdev); + mlx5_eswitch_unblock_encap(mdev); - mlx5_eswitch_unblock_mode(priv->mdev); + mlx5_eswitch_unblock_mode(mdev); return 0; @@ -894,11 +902,11 @@ static int mlx5e_xfrm_add_state(struct net_device *dev, kfree(sa_entry->work); unblock_encap: if (allow_tunnel_mode) - mlx5_eswitch_unblock_encap(priv->mdev); + mlx5_eswitch_unblock_encap(mdev); unblock_mode: - mlx5_eswitch_unblock_mode(priv->mdev); + mlx5_eswitch_unblock_mode(mdev); unblock_ipsec: - mlx5_eswitch_unblock_ipsec(priv->mdev); + mlx5_eswitch_unblock_ipsec(mdev); err_xfrm: kfree(sa_entry); NL_SET_ERR_MSG_WEAK_MOD(extack, "Device failed to offload this state"); @@ -1267,16 +1275,24 @@ static int mlx5e_xfrm_add_policy(struct xfrm_policy *x, { struct net_device *netdev = x->xdo.dev; struct mlx5e_ipsec_pol_entry *pol_entry; + struct mlx5_core_dev *mdev; struct mlx5e_priv *priv; int err; priv = netdev_priv(netdev); + /* Profile cleanup can memset an already NULL mdev. */ + mdev = data_race(READ_ONCE(priv->mdev)); + if (!mdev) { + NL_SET_ERR_MSG_MOD(extack, "Eswitch busy, can't add policy"); + return -EBUSY; + } + if (!priv->ipsec) { NL_SET_ERR_MSG_MOD(extack, "Device doesn't support IPsec packet offload"); return -EOPNOTSUPP; } - err = mlx5e_xfrm_validate_policy(priv->mdev, x, extack); + err = mlx5e_xfrm_validate_policy(mdev, x, extack); if (err) return err; @@ -1287,7 +1303,7 @@ static int mlx5e_xfrm_add_policy(struct xfrm_policy *x, pol_entry->x = x; pol_entry->ipsec = priv->ipsec; - if (!mlx5_eswitch_block_ipsec(priv->mdev)) { + if (!mlx5_eswitch_block_ipsec(mdev)) { err = -EBUSY; goto ipsec_busy; } @@ -1301,7 +1317,7 @@ static int mlx5e_xfrm_add_policy(struct xfrm_policy *x, return 0; err_fs: - mlx5_eswitch_unblock_ipsec(priv->mdev); + mlx5_eswitch_unblock_ipsec(mdev); ipsec_busy: kfree(pol_entry); NL_SET_ERR_MSG_MOD(extack, "Device failed to offload this policy"); diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec_fs.c b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec_fs.c index d8325c0f97c1..1046627d4080 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec_fs.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec_fs.c @@ -720,6 +720,16 @@ static void ipsec_rx_sa_selector_destroy(struct mlx5_core_dev *mdev, mlx5_destroy_flow_table(rx->ft.sa_sel); } +static void +ipsec_rx_status_pass_dest_put(struct mlx5e_ipsec *ipsec, + struct mlx5e_ipsec_rx *rx, + u32 family) +{ + mlx5_ipsec_fs_roce_rx_destroy(ipsec->roce, family, ipsec->mdev); + if (rx == ipsec->rx_esw) + mlx5_esw_ipsec_rx_status_pass_dest_put(ipsec); +} + static void rx_destroy(struct mlx5_core_dev *mdev, struct mlx5e_ipsec *ipsec, struct mlx5e_ipsec_rx *rx, u32 family) { @@ -739,13 +749,7 @@ static void rx_destroy(struct mlx5_core_dev *mdev, struct mlx5e_ipsec *ipsec, ipsec_rx_policy_destroy(rx); - mlx5_ipsec_fs_roce_rx_destroy(ipsec->roce, family, mdev); - -#ifdef CONFIG_MLX5_ESWITCH - if (rx == ipsec->rx_esw) - mlx5_chains_put_table(esw_chains(ipsec->mdev->priv.eswitch), - 0, 1, 0); -#endif + ipsec_rx_status_pass_dest_put(ipsec, rx, family); } static void ipsec_rx_create_attr_set(struct mlx5e_ipsec *ipsec, @@ -1115,7 +1119,7 @@ static int rx_create(struct mlx5_core_dev *mdev, struct mlx5e_ipsec *ipsec, err_fs_ft_sa_sel: mlx5_destroy_flow_table(rx->ft.status); err_fs_ft_status: - mlx5_ipsec_fs_roce_rx_destroy(ipsec->roce, family, mdev); + ipsec_rx_status_pass_dest_put(ipsec, rx, family); return err; } @@ -2183,7 +2187,6 @@ static int tx_add_rule(struct mlx5e_ipsec_sa_entry *sa_entry) } setup_fte_no_frags(spec); - setup_fte_upper_proto_match(spec, &attrs->upspec); switch (attrs->type) { case XFRM_DEV_OFFLOAD_CRYPTO: @@ -2196,6 +2199,7 @@ static int tx_add_rule(struct mlx5e_ipsec_sa_entry *sa_entry) setup_fte_reg_a(spec); break; case XFRM_DEV_OFFLOAD_PACKET: + setup_fte_upper_proto_match(spec, &attrs->upspec); setup_fte_reg_c4(spec, attrs->reqid); err = setup_pkt_reformat(ipsec, attrs, &flow_act); if (err) @@ -2574,45 +2578,26 @@ void mlx5e_accel_ipsec_fs_read_stats(struct mlx5e_priv *priv, void *ipsec_stats) } } -#ifdef CONFIG_MLX5_ESWITCH static int mlx5e_ipsec_block_tc_offload(struct mlx5_core_dev *mdev) { - struct mlx5_eswitch *esw = mdev->priv.eswitch; - int err = 0; - - if (esw) { - err = mlx5_esw_lock(esw); - if (err) - return err; - } - - if (mdev->num_block_ipsec) { - err = -EBUSY; - goto unlock; - } - - mdev->num_block_tc++; - -unlock: - if (esw) - mlx5_esw_unlock(esw); + int ret = 0; - return err; -} -#else -static int mlx5e_ipsec_block_tc_offload(struct mlx5_core_dev *mdev) -{ - if (mdev->num_block_ipsec) - return -EBUSY; + spin_lock_bh(&mdev->offload_block.lock); + if (mdev->offload_block.num_block_ipsec) + ret = -EBUSY; + else + mdev->offload_block.num_block_tc++; + spin_unlock_bh(&mdev->offload_block.lock); - mdev->num_block_tc++; - return 0; + return ret; } -#endif static void mlx5e_ipsec_unblock_tc_offload(struct mlx5_core_dev *mdev) { - mdev->num_block_tc--; + spin_lock_bh(&mdev->offload_block.lock); + if (!WARN_ON_ONCE(!mdev->offload_block.num_block_tc)) + mdev->offload_block.num_block_tc--; + spin_unlock_bh(&mdev->offload_block.lock); } int mlx5e_accel_ipsec_fs_add_rule(struct mlx5e_ipsec_sa_entry *sa_entry) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c index 3bbb19712a58..637fe1203a3e 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c @@ -5413,7 +5413,7 @@ static void mlx5e_get_queue_stats_rx(struct net_device *dev, int i, struct mlx5e_rq_stats *xskrq_stats; struct mlx5e_rq_stats *rq_stats; - if (mlx5e_is_uplink_rep(priv) || !mlx5e_stats_nch_read(priv)) + if (mlx5e_is_uplink_rep(priv) || i >= mlx5e_stats_nch_read(priv)) return; channel_stats = priv->channel_stats[i]; @@ -5440,6 +5440,9 @@ static void mlx5e_get_queue_stats_tx(struct net_device *dev, int i, * inactive sqs. */ sq_stats = priv->txq2sq_stats[i]; + if (!sq_stats) + return; + stats->packets = sq_stats->packets; stats->bytes = sq_stats->bytes; } @@ -6205,7 +6208,7 @@ int mlx5e_priv_init(struct mlx5e_priv *priv, node = dev_to_node(mlx5_core_dma_dev(mdev)); /* priv init */ - priv->mdev = mdev; + WRITE_ONCE(priv->mdev, mdev); priv->netdev = netdev; priv->max_nch = nch; priv->max_opened_tc = 1; @@ -6298,6 +6301,8 @@ void mlx5e_priv_cleanup(struct mlx5e_priv *priv) mlx5e_mqprio_rl_free(priv->mqprio_rl); } + /* Clear atomically before memset() for lockless XFRM readers. */ + WRITE_ONCE(priv->mdev, NULL); memset(priv, 0, sizeof(*priv)); if (destroying) /* restore destroying bit, to allow unload */ set_bit(MLX5E_STATE_DESTROYING, &priv->state); diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c b/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c index a47fef49ada9..8e2ee08907a9 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_rep.c @@ -239,6 +239,7 @@ static MLX5E_DECLARE_STATS_GRP_OP_UPDATE_STATS(vport_rep) MLX5_GET_CTR(out, transmitted_ib_unicast.octets) + MLX5_GET_CTR(out, transmitted_eth_unicast.octets) + MLX5_GET_CTR(out, transmitted_ib_multicast.octets) + + MLX5_GET_CTR(out, transmitted_eth_multicast.octets) + MLX5_GET_CTR(out, transmitted_eth_broadcast.octets); rep_stats->vport_tx_bytes = diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c b/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c index e2de3a9a647c..9308fb8da7d7 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_tc.c @@ -4013,6 +4013,7 @@ parse_branch_ctrl(struct flow_action_entry *act, struct mlx5e_tc_act *tc_act, err_branch_false: free_branch_attr(flow, attr->branch_true); + attr->branch_true = NULL; out_err: return err; } @@ -4796,16 +4797,19 @@ static bool is_tc_ipsec_order_check_needed(struct net_device *filter, struct mlx static int mlx5e_tc_block_ipsec_offload(struct net_device *filter, struct mlx5e_priv *priv) { struct mlx5_core_dev *mdev = priv->mdev; + int ret = 0; if (!is_tc_ipsec_order_check_needed(filter, priv)) return 0; - if (mdev->num_block_tc) - return -EBUSY; - - mdev->num_block_ipsec++; + spin_lock_bh(&mdev->offload_block.lock); + if (mdev->offload_block.num_block_tc) + ret = -EBUSY; + else + mdev->offload_block.num_block_ipsec++; + spin_unlock_bh(&mdev->offload_block.lock); - return 0; + return ret; } static void mlx5e_tc_unblock_ipsec_offload(struct net_device *filter, struct mlx5e_priv *priv) @@ -4813,7 +4817,10 @@ static void mlx5e_tc_unblock_ipsec_offload(struct net_device *filter, struct mlx if (!is_tc_ipsec_order_check_needed(filter, priv)) return; - priv->mdev->num_block_ipsec--; + spin_lock_bh(&priv->mdev->offload_block.lock); + if (!WARN_ON_ONCE(!priv->mdev->offload_block.num_block_ipsec)) + priv->mdev->offload_block.num_block_ipsec--; + spin_unlock_bh(&priv->mdev->offload_block.lock); } int mlx5e_configure_flower(struct net_device *dev, struct mlx5e_priv *priv, diff --git a/drivers/net/ethernet/mellanox/mlx5/core/esw/bridge.c b/drivers/net/ethernet/mellanox/mlx5/core/esw/bridge.c index 88487e1a5887..744f5cf9eb78 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/esw/bridge.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/esw/bridge.c @@ -1867,26 +1867,27 @@ int mlx5_esw_bridge_port_mdb_add(struct net_device *dev, u16 vport_num, u16 esw_ port = mlx5_esw_bridge_port_lookup(vport_num, esw_owner_vhca_id, br_offloads); if (!port) { - esw_warn(br_offloads->esw->dev, + /* MDB is added asynchronously from the switchdev deferred + * queue while port might have been deleted concurrently. + */ + esw_info(br_offloads->esw->dev, "Failed to lookup bridge port to add MDB (MAC=%pM,vport=%u)\n", addr, vport_num); - NL_SET_ERR_MSG_FMT_MOD(extack, - "Failed to lookup bridge port to add MDB (MAC=%pM,vport=%u)", - addr, vport_num); - return -EINVAL; + return -EOPNOTSUPP; } bridge = port->bridge; if (bridge->flags & MLX5_ESW_BRIDGE_VLAN_FILTERING_FLAG && vid) { vlan = mlx5_esw_bridge_vlan_lookup(vid, port); if (!vlan) { - esw_warn(br_offloads->esw->dev, + /* MDB is added asynchronously from the switchdev + * deferred queue while vlan might have been deleted + * concurrently. + */ + esw_info(br_offloads->esw->dev, "Failed to lookup bridge port vlan metadata to create MDB (MAC=%pM,vid=%u,vport=%u)\n", addr, vid, vport_num); - NL_SET_ERR_MSG_FMT_MOD(extack, - "Failed to lookup vlan metadata for MDB (MAC=%pM,vid=%u,vport=%u)", - addr, vid, vport_num); - return -EINVAL; + return -EOPNOTSUPP; } } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.c b/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.c index ab50d2c734ed..f8c97954b6ea 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.c @@ -34,12 +34,23 @@ void mlx5_esw_ipsec_rx_create_attr_set(struct mlx5e_ipsec *ipsec, int mlx5_esw_ipsec_rx_status_pass_dest_get(struct mlx5e_ipsec *ipsec, struct mlx5_flow_destination *dest) { - dest->type = MLX5_FLOW_DESTINATION_TYPE_FLOW_TABLE; - dest->ft = mlx5_chains_get_table(esw_chains(ipsec->mdev->priv.eswitch), 0, 1, 0); + struct mlx5_flow_table *ft; + + ft = mlx5_chains_get_table(esw_chains(ipsec->mdev->priv.eswitch), + 0, 1, 0); + if (IS_ERR(ft)) + return PTR_ERR(ft); + dest->type = MLX5_FLOW_DESTINATION_TYPE_FLOW_TABLE; + dest->ft = ft; return 0; } +void mlx5_esw_ipsec_rx_status_pass_dest_put(struct mlx5e_ipsec *ipsec) +{ + mlx5_chains_put_table(esw_chains(ipsec->mdev->priv.eswitch), 0, 1, 0); +} + int mlx5_esw_ipsec_rx_setup_modify_header(struct mlx5e_ipsec_sa_entry *sa_entry, struct mlx5_flow_act *flow_act) { diff --git a/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.h b/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.h index 514c15258b1d..bb6f2423078b 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/esw/ipsec_fs.h @@ -12,6 +12,7 @@ void mlx5_esw_ipsec_rx_create_attr_set(struct mlx5e_ipsec *ipsec, struct mlx5e_ipsec_rx_create_attr *attr); int mlx5_esw_ipsec_rx_status_pass_dest_get(struct mlx5e_ipsec *ipsec, struct mlx5_flow_destination *dest); +void mlx5_esw_ipsec_rx_status_pass_dest_put(struct mlx5e_ipsec *ipsec); int mlx5_esw_ipsec_rx_setup_modify_header(struct mlx5e_ipsec_sa_entry *sa_entry, struct mlx5_flow_act *flow_act); void mlx5_esw_ipsec_rx_id_mapping_remove(struct mlx5e_ipsec_sa_entry *sa_entry); @@ -32,6 +33,11 @@ static inline int mlx5_esw_ipsec_rx_status_pass_dest_get(struct mlx5e_ipsec *ips return -EINVAL; } +static inline +void mlx5_esw_ipsec_rx_status_pass_dest_put(struct mlx5e_ipsec *ipsec) +{ +} + static inline int mlx5_esw_ipsec_rx_setup_modify_header(struct mlx5e_ipsec_sa_entry *sa_entry, struct mlx5_flow_act *flow_act) { diff --git a/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib.h b/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib.h index 2ab6437a1c49..944549f8c2f6 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib.h @@ -82,7 +82,7 @@ void mlx5i_pkey_qpn_ht_cleanup(struct net_device *netdev); int mlx5i_pkey_add_qpn(struct net_device *netdev, u32 qpn); int mlx5i_pkey_del_qpn(struct net_device *netdev, u32 qpn); -/* Get the net-device corresponding to the given underlay QPN */ +/* Get the net-device for a QPN. Caller must hold rcu_read_lock(). */ struct net_device *mlx5i_pkey_get_netdev(struct net_device *netdev, u32 qpn); /* Shared ndo functions */ diff --git a/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib_vlan.c b/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib_vlan.c index 028a76944d82..dd42633c5230 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib_vlan.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/ipoib/ipoib_vlan.c @@ -31,6 +31,7 @@ */ #include +#include #include "ipoib.h" #define MLX5I_MAX_LOG_PKEY_SUP 7 @@ -39,11 +40,12 @@ struct qpn_to_netdev { struct net_device *netdev; struct hlist_node hlist; u32 underlay_qpn; + struct rcu_head rcu; }; struct mlx5i_pkey_qpn_ht { struct hlist_head buckets[1 << MLX5I_MAX_LOG_PKEY_SUP]; - spinlock_t ht_lock; /* Synchronise with NAPI */ + spinlock_t ht_lock; /* Serialize hash table updates */ }; int mlx5i_pkey_qpn_ht_init(struct net_device *netdev) @@ -68,13 +70,14 @@ void mlx5i_pkey_qpn_ht_cleanup(struct net_device *netdev) kfree(ipriv->qpn_htbl); } -static struct qpn_to_netdev *mlx5i_find_qpn_to_netdev_node(struct hlist_head *buckets, - u32 qpn) +static struct qpn_to_netdev * +mlx5i_find_qpn_to_netdev_node(struct mlx5i_pkey_qpn_ht *ht, u32 qpn) { - struct hlist_head *h = &buckets[hash_32(qpn, MLX5I_MAX_LOG_PKEY_SUP)]; + struct hlist_head *h = &ht->buckets[hash_32(qpn, MLX5I_MAX_LOG_PKEY_SUP)]; struct qpn_to_netdev *node; - hlist_for_each_entry(node, h, hlist) { + hlist_for_each_entry_rcu(node, h, hlist, + lockdep_is_held(&ht->ht_lock)) { if (node->underlay_qpn == qpn) return node; } @@ -96,7 +99,7 @@ int mlx5i_pkey_add_qpn(struct net_device *netdev, u32 qpn) new_node->netdev = netdev; new_node->underlay_qpn = qpn; spin_lock_bh(&ht->ht_lock); - hlist_add_head(&new_node->hlist, &ht->buckets[key]); + hlist_add_head_rcu(&new_node->hlist, &ht->buckets[key]); spin_unlock_bh(&ht->ht_lock); return 0; @@ -109,16 +112,17 @@ int mlx5i_pkey_del_qpn(struct net_device *netdev, u32 qpn) struct mlx5i_pkey_qpn_ht *ht = ipriv->qpn_htbl; struct qpn_to_netdev *node; - node = mlx5i_find_qpn_to_netdev_node(ht->buckets, qpn); + spin_lock_bh(&ht->ht_lock); + node = mlx5i_find_qpn_to_netdev_node(ht, qpn); if (!node) { + spin_unlock_bh(&ht->ht_lock); mlx5_core_warn(epriv->mdev, "QPN to netdev delete from HT failed\n"); return -EINVAL; } - spin_lock_bh(&ht->ht_lock); - hlist_del_init(&node->hlist); + hlist_del_rcu(&node->hlist); spin_unlock_bh(&ht->ht_lock); - kfree(node); + kfree_rcu(node, rcu); return 0; } @@ -128,7 +132,7 @@ struct net_device *mlx5i_pkey_get_netdev(struct net_device *netdev, u32 qpn) struct mlx5i_priv *ipriv = netdev_priv(netdev); struct qpn_to_netdev *node; - node = mlx5i_find_qpn_to_netdev_node(ipriv->qpn_htbl->buckets, qpn); + node = mlx5i_find_qpn_to_netdev_node(ipriv->qpn_htbl, qpn); if (!node) return NULL; diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c b/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c index 17b9a5078f6c..778f0208dc5c 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c @@ -832,7 +832,6 @@ int mlx5_deactivate_lag(struct mlx5_lag *ldev) "Failed to deactivate VF LAG; driver restart required\n" "Make sure all VFs are unbound prior to VF LAG activation or deactivation\n"); } - return err; } if (test_bit(MLX5_LAG_MODE_FLAG_HASH_BASED, &flags)) { @@ -842,7 +841,7 @@ int mlx5_deactivate_lag(struct mlx5_lag *ldev) if (mlx5_lag_has_drop_rule(ldev)) mlx5_lag_drop_rule_cleanup(ldev); - return 0; + return err; } bool mlx5_lag_check_prereq(struct mlx5_lag *ldev) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lag/mpesw.c b/drivers/net/ethernet/mellanox/mlx5/core/lag/mpesw.c index 567e51f0e5da..6dd97cc372ff 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lag/mpesw.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/lag/mpesw.c @@ -172,7 +172,7 @@ static int mlx5_lag_mpesw_queue_work(struct mlx5_core_dev *dev, int err = 0; if (!ldev) - return 0; + return -EOPNOTSUPP; work = kzalloc(sizeof(*work), GFP_KERNEL); if (!work) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.c b/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.c index 29e7fa09c32c..e3e9d6a9c9c6 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.c @@ -80,6 +80,7 @@ enum { }; struct mlx5_clock_dev_state { + bool loaded; struct mlx5_core_dev *mdev; struct mlx5_devcom_comp_dev *compdev; struct mlx5_nb pps_nb; @@ -89,7 +90,7 @@ struct mlx5_clock_dev_state { struct mlx5_clock_priv { struct mlx5_clock clock; struct mlx5_core_dev *mdev; - struct mutex lock; /* protect mdev and used in PTP callbacks */ + struct mutex lock; /* protect mdev and serialize hardware callbacks */ struct mlx5_core_dev *event_mdev; }; @@ -100,9 +101,6 @@ static struct mlx5_clock_priv *clock_priv(struct mlx5_clock *clock) static void mlx5_clock_lockdep_assert(struct mlx5_clock *clock) { - if (!clock->shared) - return; - lockdep_assert(lockdep_is_held(&clock_priv(clock)->lock)); } @@ -115,20 +113,24 @@ static struct mlx5_core_dev *mlx5_clock_mdev_get(struct mlx5_clock *clock) static void mlx5_clock_lock(struct mlx5_clock *clock) { - if (!clock->shared) - return; - mutex_lock(&clock_priv(clock)->lock); } static void mlx5_clock_unlock(struct mlx5_clock *clock) { - if (!clock->shared) - return; - mutex_unlock(&clock_priv(clock)->lock); } +static struct mlx5_core_dev * +mlx5_clock_active_mdev_get(struct mlx5_clock *clock) +{ + struct mlx5_clock_priv *cpriv = clock_priv(clock); + + mlx5_clock_lockdep_assert(clock); + + return cpriv->mdev->clock_state->loaded ? cpriv->mdev : NULL; +} + static bool mlx5_real_time_mode(struct mlx5_core_dev *mdev) { return (mlx5_is_real_time_rq(mdev) || mlx5_is_real_time_sq(mdev)); @@ -332,7 +334,11 @@ static int mlx5_ptp_getcrosststamp(struct ptp_clock_info *ptp, int err; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } if (!mlx5_is_ptm_source_time_available(mdev)) { err = -EBUSY; @@ -358,7 +364,11 @@ static int mlx5_ptp_getcrosscycles(struct ptp_clock_info *ptp, int err; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } if (!mlx5_is_ptm_source_time_available(mdev)) { err = -EBUSY; @@ -410,6 +420,12 @@ static u64 read_internal_timer(struct cyclecounter *cc) return mlx5_read_time(mdev, NULL, false) & cc->mask; } +static void mlx5_timer_snapshot(struct mlx5_timer *timer) +{ + timer->saved_phc_ns = timer->tc.nsec; + timer->saved_boot_ns = ktime_get_boottime_ns(); +} + static void mlx5_update_clock_info_page(struct mlx5_core_dev *mdev) { struct mlx5_ib_clock_info *clock_info = mdev->clock_info; @@ -417,6 +433,9 @@ static void mlx5_update_clock_info_page(struct mlx5_core_dev *mdev) struct mlx5_timer *timer; u32 sign; + timer = &clock->timer; + mlx5_timer_snapshot(timer); + if (!clock_info) return; @@ -424,7 +443,6 @@ static void mlx5_update_clock_info_page(struct mlx5_core_dev *mdev) smp_store_mb(clock_info->sign, sign | MLX5_IB_CLOCK_INFO_KERNEL_UPDATING); - timer = &clock->timer; clock_info->cycles = timer->tc.cycle_last; clock_info->mult = timer->cycles.mult; clock_info->nsec = timer->tc.nsec; @@ -470,10 +488,9 @@ static long mlx5_timestamp_overflow(struct ptp_clock_info *ptp_info) clock = container_of(ptp_info, struct mlx5_clock, ptp_info); mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); timer = &clock->timer; - - if (mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR) + if (!mdev || mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR) goto out; write_seqlock_irqsave(&clock->lock, flags); @@ -530,8 +547,13 @@ static int mlx5_ptp_settime(struct ptp_clock_info *ptp, const struct timespec64 int err; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } err = mlx5_clock_settime(mdev, clock, ts); +unlock: mlx5_clock_unlock(clock); return err; @@ -549,26 +571,40 @@ struct timespec64 mlx5_ptp_gettimex_real_time(struct mlx5_core_dev *mdev, return ts; } -static int mlx5_ptp_gettimex(struct ptp_clock_info *ptp, struct timespec64 *ts, - struct ptp_system_timestamp *sts) +static void mlx5_clock_gettimex(struct mlx5_core_dev *mdev, + struct mlx5_clock *clock, struct timespec64 *ts, + struct ptp_system_timestamp *sts) { - struct mlx5_clock *clock = container_of(ptp, struct mlx5_clock, ptp_info); - struct mlx5_core_dev *mdev; u64 cycles, ns; - mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); if (mlx5_real_time_mode(mdev)) { *ts = mlx5_ptp_gettimex_real_time(mdev, sts); - goto out; + return; } cycles = mlx5_read_time(mdev, sts, false); ns = mlx5_timecounter_cyc2time(clock, cycles); *ts = ns_to_timespec64(ns); -out: +} + +static int mlx5_ptp_gettimex(struct ptp_clock_info *ptp, struct timespec64 *ts, + struct ptp_system_timestamp *sts) +{ + struct mlx5_clock *clock = + container_of(ptp, struct mlx5_clock, ptp_info); + struct mlx5_core_dev *mdev; + int err = 0; + + mlx5_clock_lock(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } + mlx5_clock_gettimex(mdev, clock, ts, sts); +unlock: mlx5_clock_unlock(clock); - return 0; + return err; } static int mlx5_ptp_getcyclesx(struct ptp_clock_info *ptp, @@ -579,14 +615,20 @@ static int mlx5_ptp_getcyclesx(struct ptp_clock_info *ptp, ptp_info); struct mlx5_core_dev *mdev; u64 cycles; + int err = 0; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } cycles = mlx5_read_time(mdev, sts, false); *ts = ns_to_timespec64(cycles); +unlock: mlx5_clock_unlock(clock); - return 0; + return err; } static int mlx5_ptp_adjtime_real_time(struct mlx5_core_dev *mdev, s64 delta) @@ -619,7 +661,11 @@ static int mlx5_ptp_adjtime(struct ptp_clock_info *ptp, s64 delta) int err = 0; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } if (mlx5_modify_mtutc_allowed(mdev)) { err = mlx5_ptp_adjtime_real_time(mdev, delta); @@ -629,6 +675,7 @@ static int mlx5_ptp_adjtime(struct ptp_clock_info *ptp, s64 delta) } write_seqlock_irqsave(&clock->lock, flags); + timecounter_read(&timer->tc); timecounter_adjtime(&timer->tc, delta); mlx5_update_clock_info_page(mdev); write_sequnlock_irqrestore(&clock->lock, flags); @@ -645,8 +692,13 @@ static int mlx5_ptp_adjphase(struct ptp_clock_info *ptp, s32 delta) int err; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } err = mlx5_ptp_adjtime_real_time(mdev, delta); +unlock: mlx5_clock_unlock(clock); return err; @@ -682,7 +734,11 @@ static int mlx5_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm) u32 mult; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } if (mlx5_modify_mtutc_allowed(mdev)) { err = mlx5_ptp_freq_adj_real_time(mdev, scaled_ppm); @@ -743,7 +799,11 @@ static int mlx5_extts_configure(struct ptp_clock_info *ptp, } mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } if (!MLX5_PPS_CAP(mdev)) { err = -EOPNOTSUPP; @@ -916,7 +976,11 @@ static int mlx5_perout_configure(struct ptp_clock_info *ptp, return -EBUSY; mlx5_clock_lock(clock); - mdev = mlx5_clock_mdev_get(clock); + mdev = mlx5_clock_active_mdev_get(clock); + if (!mdev) { + err = -EAGAIN; + goto unlock; + } rt_mode = mlx5_real_time_mode(mdev); if (!MLX5_PPS_CAP(mdev)) { @@ -1151,7 +1215,7 @@ static u64 perout_conf_next_event_timer(struct mlx5_core_dev *mdev, struct timespec64 ts; s64 target_ns; - mlx5_ptp_gettimex(&clock->ptp_info, &ts, NULL); + mlx5_clock_gettimex(mdev, clock, &ts, NULL); ts_next_sec(&ts); target_ns = timespec64_to_ns(&ts); @@ -1222,8 +1286,8 @@ static void mlx5_timecounter_init(struct mlx5_core_dev *mdev) timer->nominal_c_mult = timer->cycles.mult; timer->cycles.mask = CLOCKSOURCE_MASK(41); - timecounter_init(&timer->tc, &timer->cycles, - ktime_to_ns(ktime_get_real())); + timecounter_init(&timer->tc, &timer->cycles, ktime_get_real_ns()); + mlx5_timer_snapshot(timer); } static void mlx5_init_overflow_period(struct mlx5_core_dev *mdev) @@ -1370,9 +1434,6 @@ static void mlx5_init_clock_dev(struct mlx5_core_dev *mdev) clock->ptp); clock->ptp = NULL; } - - if (clock->ptp) - ptp_schedule_worker(clock->ptp, 0); } static void mlx5_destroy_clock_dev(struct mlx5_core_dev *mdev) @@ -1517,22 +1578,53 @@ static void mlx5_clock_arm_pps_in_event(struct mlx5_clock *clock, !clock->pps_info.pin_armed[i]) continue; - if (new_mdev) { + if (new_mdev) mlx5_set_mtppse(new_mdev, i, 0, MLX5_EVENT_MODE_REPETETIVE); - cpriv->event_mdev = new_mdev; - } else { - cpriv->event_mdev = NULL; - } if (old_mdev) mlx5_set_mtppse(old_mdev, i, 0, MLX5_EVENT_MODE_DISABLE); } + cpriv->event_mdev = new_mdev; +} + +static void mlx5_set_timecounter(struct mlx5_core_dev *mdev, u64 ns) +{ + struct mlx5_clock *clock = mdev->clock; + struct mlx5_timer *timer; + unsigned long flags; + + timer = &clock->timer; + mlx5_clock_lockdep_assert(clock); + + write_seqlock_irqsave(&clock->lock, flags); + timecounter_init(&timer->tc, &timer->cycles, ns); + mlx5_update_clock_info_page(mdev); + write_sequnlock_irqrestore(&clock->lock, flags); +} + +static void mlx5_save_timecounter(struct mlx5_core_dev *mdev) +{ + struct mlx5_clock *clock = mdev->clock; + struct mlx5_timer *timer; + unsigned long flags; + + timer = &clock->timer; + mlx5_clock_lockdep_assert(clock); + + if (mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR) + return; + + write_seqlock_irqsave(&clock->lock, flags); + timecounter_read(&timer->tc); + mlx5_update_clock_info_page(mdev); + write_sequnlock_irqrestore(&clock->lock, flags); } void mlx5_clock_load(struct mlx5_core_dev *mdev) { struct mlx5_clock *clock = mdev->clock; struct mlx5_clock_priv *cpriv; + bool start; if (!MLX5_CAP_GEN(mdev, device_frequency_khz)) return; @@ -1541,18 +1633,32 @@ void mlx5_clock_load(struct mlx5_core_dev *mdev) MLX5_NB_INIT(&mdev->clock_state->pps_nb, mlx5_pps_event, PPS_EVENT); mlx5_eq_notifier_register(mdev, &mdev->clock_state->pps_nb); - if (!clock->shared) { - mlx5_clock_arm_pps_in_event(clock, mdev, NULL); - return; - } - cpriv = clock_priv(clock); - mlx5_devcom_comp_lock(mdev->clock_state->compdev); + if (clock->shared) + mlx5_devcom_comp_lock(mdev->clock_state->compdev); mlx5_clock_lock(clock); - if (mdev == cpriv->mdev && mdev != cpriv->event_mdev) + start = !cpriv->mdev->clock_state->loaded; + mdev->clock_state->loaded = true; + if (start) { + struct mlx5_timer *timer = &clock->timer; + u64 ns; + + cpriv->mdev = mdev; + if (mlx5_real_time_mode(mdev)) + ns = mlx5_read_time(mdev, NULL, true); + else + ns = timer->saved_phc_ns + + ktime_get_boottime_ns() - timer->saved_boot_ns; + + mlx5_set_timecounter(mdev, ns); mlx5_clock_arm_pps_in_event(clock, mdev, cpriv->event_mdev); + } mlx5_clock_unlock(clock); - mlx5_devcom_comp_unlock(mdev->clock_state->compdev); + + if (start && clock->ptp) + ptp_schedule_worker(clock->ptp, 0); + if (clock->shared) + mlx5_devcom_comp_unlock(mdev->clock_state->compdev); } void mlx5_clock_unload(struct mlx5_core_dev *mdev) @@ -1560,30 +1666,42 @@ void mlx5_clock_unload(struct mlx5_core_dev *mdev) struct mlx5_core_dev *peer_dev, *next = NULL; struct mlx5_clock *clock = mdev->clock; struct mlx5_devcom_comp_dev *pos; + struct mlx5_clock_priv *cpriv; + bool stop; if (!MLX5_CAP_GEN(mdev, device_frequency_khz)) return; - if (!clock->shared) { - mlx5_clock_arm_pps_in_event(clock, NULL, mdev); - goto out; - } - - mlx5_devcom_comp_lock(mdev->clock_state->compdev); - mlx5_devcom_for_each_peer_entry(mdev->clock_state->compdev, peer_dev, pos) { - if (peer_dev->clock && peer_dev != mdev) { - next = peer_dev; - break; + if (clock->shared) { + mlx5_devcom_comp_lock(mdev->clock_state->compdev); + mlx5_devcom_for_each_peer_entry(mdev->clock_state->compdev, + peer_dev, pos) { + if (peer_dev->clock == clock && + peer_dev->clock_state->loaded) { + next = peer_dev; + break; + } } } mlx5_clock_lock(clock); - if (mdev == clock_priv(clock)->event_mdev) + cpriv = clock_priv(clock); + mdev->clock_state->loaded = false; + if (mdev == cpriv->mdev && next) + cpriv->mdev = next; + if (mdev == cpriv->event_mdev) mlx5_clock_arm_pps_in_event(clock, next, mdev); + stop = !cpriv->mdev->clock_state->loaded; + if (!mlx5_real_time_mode(cpriv->mdev)) + mlx5_save_timecounter(cpriv->mdev); mlx5_clock_unlock(clock); - mlx5_devcom_comp_unlock(mdev->clock_state->compdev); -out: + /* Keep devcom locked to prevent a peer from restarting the worker. */ + if (stop && clock->ptp) + ptp_cancel_worker_sync(clock->ptp); + if (clock->shared) + mlx5_devcom_comp_unlock(mdev->clock_state->compdev); + mlx5_eq_notifier_unregister(mdev, &mdev->clock_state->pps_nb); cancel_work_sync(&mdev->clock_state->out_work); } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.h b/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.h index c18a652c0faa..d57c5c213e38 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/lib/clock.h @@ -50,6 +50,8 @@ struct mlx5_timer { struct timecounter tc; u32 nominal_c_mult; unsigned long overflow_period; + u64 saved_phc_ns; + u64 saved_boot_ns; }; struct mlx5_clock { diff --git a/drivers/net/ethernet/mellanox/mlx5/core/lib/macsec_fs.c b/drivers/net/ethernet/mellanox/mlx5/core/lib/macsec_fs.c index e6be2f01daf4..77e4b406e242 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/lib/macsec_fs.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/lib/macsec_fs.c @@ -94,6 +94,7 @@ struct mlx5_fs_id { refcount_t refcnt; sci_t sci; struct rhash_head hash; + struct rcu_head rcu; }; struct mlx5_macsec_device { @@ -684,7 +685,7 @@ static void macsec_fs_id_del(struct list_head *macsec_devices_list, u32 fs_id, xa_erase(fs_id_xa, fs_id); - kfree(fs_id_found); + kfree_rcu(fs_id_found, rcu); if (macsec_fs_is_macsec_device_empty(macsec_device)) { list_del(&macsec_device->macsec_devices_list_entry); @@ -763,13 +764,9 @@ static int macsec_fs_id_add(struct list_head *macsec_devices_list, u32 fs_id, return err; } -static void macsec_fs_tx_del_rule(struct mlx5_macsec_fs *macsec_fs, - struct mlx5_macsec_tx_rule *tx_rule, - void *macdev) +static void macsec_fs_tx_free_rule(struct mlx5_macsec_fs *macsec_fs, + struct mlx5_macsec_tx_rule *tx_rule) { - macsec_fs_id_del(&macsec_fs->macsec_devices_list, tx_rule->fs_id, macdev, - &macsec_fs->sci_hash, true); - if (tx_rule->rule) { mlx5_del_flow_rules(tx_rule->rule); tx_rule->rule = NULL; @@ -790,6 +787,15 @@ static void macsec_fs_tx_del_rule(struct mlx5_macsec_fs *macsec_fs, macsec_fs_tx_ft_put(macsec_fs); } +static void macsec_fs_tx_del_rule(struct mlx5_macsec_fs *macsec_fs, + struct mlx5_macsec_tx_rule *tx_rule, + void *macdev) +{ + macsec_fs_id_del(&macsec_fs->macsec_devices_list, tx_rule->fs_id, macdev, + &macsec_fs->sci_hash, true); + macsec_fs_tx_free_rule(macsec_fs, tx_rule); +} + #define MLX5_REFORMAT_PARAM_ADD_MACSEC_OFFSET_4_BYTES 1 static union mlx5_macsec_rule * @@ -882,7 +888,7 @@ macsec_fs_tx_add_rule(struct mlx5_macsec_fs *macsec_fs, goto out_spec; err: - macsec_fs_tx_del_rule(macsec_fs, tx_rule, macsec_ctx->secy->netdev); + macsec_fs_tx_free_rule(macsec_fs, tx_rule); macsec_rule = NULL; out_spec: kvfree(spec); @@ -1647,15 +1653,11 @@ static void macsec_fs_rx_ft_put(struct mlx5_macsec_fs *macsec_fs) macsec_fs_rx_destroy(macsec_fs); } -static void macsec_fs_rx_del_rule(struct mlx5_macsec_fs *macsec_fs, - struct mlx5_macsec_rx_rule *rx_rule, - void *macdev, u32 fs_id) +static void macsec_fs_rx_free_rule(struct mlx5_macsec_fs *macsec_fs, + struct mlx5_macsec_rx_rule *rx_rule) { int i; - macsec_fs_id_del(&macsec_fs->macsec_devices_list, fs_id, macdev, - &macsec_fs->fs_id_hash, false); - for (i = 0; i < RX_NUM_OF_RULES_PER_SA; ++i) { if (rx_rule->rule[i]) { mlx5_del_flow_rules(rx_rule->rule[i]); @@ -1673,6 +1675,15 @@ static void macsec_fs_rx_del_rule(struct mlx5_macsec_fs *macsec_fs, macsec_fs_rx_ft_put(macsec_fs); } +static void macsec_fs_rx_del_rule(struct mlx5_macsec_fs *macsec_fs, + struct mlx5_macsec_rx_rule *rx_rule, + void *macdev, u32 fs_id) +{ + macsec_fs_id_del(&macsec_fs->macsec_devices_list, fs_id, macdev, + &macsec_fs->fs_id_hash, false); + macsec_fs_rx_free_rule(macsec_fs, rx_rule); +} + static void macsec_fs_rx_setup_fte(struct mlx5_flow_spec *spec, struct mlx5_flow_act *flow_act, struct mlx5_macsec_rule_attrs *attrs, @@ -1832,7 +1843,7 @@ macsec_fs_rx_add_rule(struct mlx5_macsec_fs *macsec_fs, return macsec_rule; err: - macsec_fs_rx_del_rule(macsec_fs, rx_rule, macsec_ctx->secy->netdev, fs_id); + macsec_fs_rx_free_rule(macsec_fs, rx_rule); macsec_rule = NULL; out_spec: kvfree(spec); diff --git a/drivers/net/ethernet/mellanox/mlx5/core/main.c b/drivers/net/ethernet/mellanox/mlx5/core/main.c index 42bc553d034b..b6878b33cea1 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/main.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/main.c @@ -1833,6 +1833,7 @@ int mlx5_mdev_init(struct mlx5_core_dev *dev, int profile_idx) lockdep_register_key(&dev->lock_key); mutex_init(&dev->intf_state_mutex); lockdep_set_class(&dev->intf_state_mutex, &dev->lock_key); + spin_lock_init(&dev->offload_block.lock); mutex_init(&dev->mlx5e_res.uplink_netdev_lock); mutex_init(&dev->wc_state_lock); diff --git a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c index 6a5068ff013a..7b677653be5b 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c @@ -523,13 +523,13 @@ mlx5_fs_get_action_aso_meter(struct mlx5_fs_hws_context *fs_ctx, } static void mlx5_fs_put_action_aso_meter(struct mlx5_fs_hws_context *fs_ctx, - struct mlx5_exe_aso *exe_aso) + u32 base_id) { struct mlx5_fs_hws_data *meter_hws_data; struct xarray *meters_xa; meters_xa = &fs_ctx->hws_pool.aso_meters; - meter_hws_data = xa_load(meters_xa, exe_aso->base_id); + meter_hws_data = xa_load(meters_xa, base_id); if (!meter_hws_data) return; return mlx5_fs_put_hws_action(meter_hws_data); @@ -704,7 +704,7 @@ static void mlx5_fs_destroy_fs_action(struct mlx5_flow_root_namespace *ns, mlx5_fc_put_hws_action(fs_action->counter); break; case MLX5HWS_ACTION_TYP_ASO_METER: - mlx5_fs_put_action_aso_meter(fs_ctx, fs_action->exe_aso); + mlx5_fs_put_action_aso_meter(fs_ctx, fs_action->aso_base_id); break; case MLX5HWS_ACTION_TYP_SAMPLER: mlx5_fs_put_dest_action_sampler(fs_ctx, fs_action->sampler_id); @@ -939,7 +939,7 @@ static int mlx5_fs_fte_get_hws_actions(struct mlx5_flow_root_namespace *ns, fte_action->exe_aso.flow_meter.init_color; (*ractions)[num_actions++].action = tmp_action; fs_actions[num_fs_actions].action = tmp_action; - fs_actions[num_fs_actions++].exe_aso = &fte_action->exe_aso; + fs_actions[num_fs_actions++].aso_base_id = fte_action->exe_aso.base_id; } if (fte_action->action & MLX5_FLOW_CONTEXT_ACTION_DROP) { diff --git a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.h b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.h index 344c80112ab7..8f7730b50c07 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.h @@ -57,7 +57,7 @@ struct mlx5_fs_hws_rule_action { struct mlx5hws_action *action; union { struct mlx5_fc *counter; - struct mlx5_exe_aso *exe_aso; + u32 aso_base_id; u32 sampler_id; }; }; diff --git a/drivers/net/ethernet/meta/fbnic/fbnic.h b/drivers/net/ethernet/meta/fbnic/fbnic.h index ca465282b53f..dbc3ff5659b4 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic.h +++ b/drivers/net/ethernet/meta/fbnic/fbnic.h @@ -34,7 +34,7 @@ struct fbnic_dev { u32 __iomem *uc_addr4; const struct fbnic_mac *mac; unsigned int fw_msix_vector; - unsigned int pcs_msix_vector; + unsigned int mac_msix_vector; unsigned short num_irqs; struct { @@ -83,6 +83,10 @@ struct fbnic_dev { /* Last @time_high refresh time in jiffies (to catch stalls) */ unsigned long last_read; + /* PMD specific data */ + unsigned long end_of_pmd_training; + u8 pmd_state; + /* Local copy of hardware statistics */ struct fbnic_hw_stats hw_stats; @@ -180,8 +184,8 @@ void fbnic_fw_free_mbx(struct fbnic_dev *fbd); void fbnic_hwmon_register(struct fbnic_dev *fbd); void fbnic_hwmon_unregister(struct fbnic_dev *fbd); -int fbnic_pcs_request_irq(struct fbnic_dev *fbd); -void fbnic_pcs_free_irq(struct fbnic_dev *fbd); +int fbnic_mac_request_irq(struct fbnic_dev *fbd); +void fbnic_mac_free_irq(struct fbnic_dev *fbd); void fbnic_napi_name_irqs(struct fbnic_dev *fbd); int fbnic_napi_request_irq(struct fbnic_dev *fbd, diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_csr.h b/drivers/net/ethernet/meta/fbnic/fbnic_csr.h index 00c76708f233..e93f9ff6f4d1 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_csr.h +++ b/drivers/net/ethernet/meta/fbnic/fbnic_csr.h @@ -456,6 +456,7 @@ enum { #define FBNIC_TMI_SOP_PROT_CTRL 0x04400 /* 0x11000 */ #define FBNIC_TMI_DROP_CTRL 0x04401 /* 0x11004 */ #define FBNIC_TMI_DROP_CTRL_EN CSR_BIT(0) +#define FBNIC_TMI_DROP_CTRL_CMPL_DIS CSR_BIT(1) #define FBNIC_TMI_DROP_PKTS 0x04402 /* 0x11008 */ #define FBNIC_TMI_DROP_BYTE_L 0x04403 /* 0x1100c */ #define FBNIC_TMI_ILLEGAL_PTP_REQS 0x04409 /* 0x11024 */ @@ -787,6 +788,8 @@ enum { /* MAC PCS registers */ #define FBNIC_CSR_START_PCS 0x10000 /* CSR section delimiter */ +#define FBNIC_PCS_PAGE(n) (0x10000 + 0x400 * (n)) /* 0x40000 + 1024*n */ +#define FBNIC_PCS(reg, n) ((reg) + FBNIC_PCS_PAGE(n)) #define FBNIC_CSR_END_PCS 0x10668 /* CSR section delimiter */ #define FBNIC_CSR_START_RSFEC 0x10800 /* CSR section delimiter */ @@ -957,6 +960,10 @@ enum { /* PUL User Registers */ #define FBNIC_CSR_START_PUL_USER 0x31000 /* CSR section delimiter */ +#define FBNIC_PUL_USER_IP_LINK_RST_STATUS \ + 0x31030 /* 0xc40c0 */ +#define FBNIC_PUL_USER_IP_LINK_RST_STATUS_AW_FLUSH_DONE CSR_BIT(7) +#define FBNIC_PUL_USER_IP_LINK_RST_STATUS_AR_FLUSH_DONE CSR_BIT(8) #define FBNIC_PUL_OB_TLP_HDR_AW_CFG 0x3103d /* 0xc40f4 */ #define FBNIC_PUL_OB_TLP_HDR_AW_CFG_FLUSH_MODE CSR_BIT(20) #define FBNIC_PUL_OB_TLP_HDR_AW_CFG_FLUSH CSR_BIT(19) diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_fw.c b/drivers/net/ethernet/meta/fbnic/fbnic_fw.c index 36607840de1e..e642bedd2ffa 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_fw.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_fw.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include "fbnic.h" @@ -176,10 +177,25 @@ static void fbnic_mbx_unmap_and_free_msg(struct fbnic_dev *fbd, int mbx_idx, static void fbnic_mbx_clean_desc_ring(struct fbnic_dev *fbd, int mbx_idx) { + u32 flush_done, val; int i; fbnic_mbx_reset_desc_ring(fbd, mbx_idx); + /* Arming the flush only starts it. Wait for the outbound path to + * retire the requests it still holds before the buffers they may + * target are unmapped and freed. A lost link reads back as all ones, + * which ends the poll on the first pass. + */ + flush_done = mbx_idx == FBNIC_IPC_MBX_RX_IDX ? + FBNIC_PUL_USER_IP_LINK_RST_STATUS_AW_FLUSH_DONE : + FBNIC_PUL_USER_IP_LINK_RST_STATUS_AR_FLUSH_DONE; + if (read_poll_timeout_atomic(fbnic_rd32, val, val & flush_done, 2, + 1000, false, fbd, + FBNIC_PUL_USER_IP_LINK_RST_STATUS)) + dev_warn(fbd->dev, "Outbound flush did not complete: %08x\n", + val); + for (i = FBNIC_IPC_MBX_DESC_LEN; i--;) fbnic_mbx_unmap_and_free_msg(fbd, mbx_idx, i); } diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_irq.c b/drivers/net/ethernet/meta/fbnic/fbnic_irq.c index 1c88a2bf3a7a..9b068b82f30a 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_irq.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_irq.c @@ -118,12 +118,12 @@ void fbnic_fw_free_mbx(struct fbnic_dev *fbd) fbd->fw_msix_vector = 0; } -static irqreturn_t fbnic_pcs_msix_intr(int __always_unused irq, void *data) +static irqreturn_t fbnic_mac_msix_intr(int __always_unused irq, void *data) { struct fbnic_dev *fbd = data; struct fbnic_net *fbn; - if (fbd->mac->pcs_get_link_event(fbd) == FBNIC_LINK_EVENT_NONE) { + if (fbd->mac->get_link_event(fbd) == FBNIC_LINK_EVENT_NONE) { fbnic_wr32(fbd, FBNIC_INTR_MASK_CLEAR(0), 1u << FBNIC_PCS_MSIX_ENTRY); return IRQ_HANDLED; @@ -131,26 +131,28 @@ static irqreturn_t fbnic_pcs_msix_intr(int __always_unused irq, void *data) fbn = netdev_priv(fbd->netdev); - phylink_pcs_change(&fbn->phylink_pcs, false); + /* Record link down events */ + if (!fbd->mac->get_link(fbd, fbn->aui, fbn->fec)) + phylink_pcs_change(&fbn->phylink_pcs, false); return IRQ_HANDLED; } /** - * fbnic_pcs_request_irq - Configure the PCS to enable it to advertise link + * fbnic_mac_request_irq - Configure the MAC to enable it to advertise link * @fbd: Pointer to device to initialize * - * This function provides basic bringup for the MAC/PCS IRQ. For now the IRQ + * This function provides basic bringup for the MAC/PHY IRQ. For now the IRQ * will remain disabled until we start the MAC/PCS/PHY logic via phylink. * * Return: non-zero on failure. **/ -int fbnic_pcs_request_irq(struct fbnic_dev *fbd) +int fbnic_mac_request_irq(struct fbnic_dev *fbd) { struct pci_dev *pdev = to_pci_dev(fbd->dev); int vector, err; - WARN_ON(fbd->pcs_msix_vector); + WARN_ON(fbd->mac_msix_vector); vector = pci_irq_vector(pdev, FBNIC_PCS_MSIX_ENTRY); if (vector < 0) @@ -159,7 +161,7 @@ int fbnic_pcs_request_irq(struct fbnic_dev *fbd) /* Request the IRQ for PCS link vector. * Map PCS cause to it, and unmask it */ - err = request_irq(vector, &fbnic_pcs_msix_intr, 0, + err = request_irq(vector, &fbnic_mac_msix_intr, 0, fbd->netdev->name, fbd); if (err) return err; @@ -168,22 +170,22 @@ int fbnic_pcs_request_irq(struct fbnic_dev *fbd) fbnic_wr32(fbd, FBNIC_INTR_MSIX_CTRL(FBNIC_INTR_MSIX_CTRL_PCS_IDX), FBNIC_PCS_MSIX_ENTRY | FBNIC_INTR_MSIX_CTRL_ENABLE); - fbd->pcs_msix_vector = vector; + fbd->mac_msix_vector = vector; return 0; } /** - * fbnic_pcs_free_irq - Teardown the PCS IRQ to prepare for stopping + * fbnic_mac_free_irq - Teardown the MAC IRQ to prepare for stopping * @fbd: Pointer to device that is stopping * - * This function undoes the work done in fbnic_pcs_request_irq and prepares + * This function undoes the work done in fbnic_mac_request_irq and prepares * the device to no longer receive traffic on the host interface. **/ -void fbnic_pcs_free_irq(struct fbnic_dev *fbd) +void fbnic_mac_free_irq(struct fbnic_dev *fbd) { /* Vector has already been freed */ - if (!fbd->pcs_msix_vector) + if (!fbd->mac_msix_vector) return; /* Disable interrupt */ @@ -192,14 +194,14 @@ void fbnic_pcs_free_irq(struct fbnic_dev *fbd) fbnic_wrfl(fbd); /* Synchronize IRQ to prevent race that would unmask vector */ - synchronize_irq(fbd->pcs_msix_vector); + synchronize_irq(fbd->mac_msix_vector); /* Mask the vector */ fbnic_wr32(fbd, FBNIC_INTR_MASK_SET(0), 1u << FBNIC_PCS_MSIX_ENTRY); /* Free the vector */ - free_irq(fbd->pcs_msix_vector, fbd); - fbd->pcs_msix_vector = 0; + free_irq(fbd->mac_msix_vector, fbd); + fbd->mac_msix_vector = 0; } void fbnic_synchronize_irq(struct fbnic_dev *fbd, int nr) diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_mac.c b/drivers/net/ethernet/meta/fbnic/fbnic_mac.c index 2a84bd1d7e26..fc7abea4ef5b 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_mac.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_mac.c @@ -434,14 +434,14 @@ static void fbnic_mac_tx_pause_config(struct fbnic_dev *fbd, bool tx_pause) wr32(fbd, FBNIC_RXB_PAUSE_DROP_CTRL, rxb_pause_ctrl); } -static int fbnic_pcs_get_link_event_asic(struct fbnic_dev *fbd) +static int fbnic_mac_get_link_event(struct fbnic_dev *fbd) { - u32 pcs_intr_mask = rd32(fbd, FBNIC_SIG_PCS_INTR_STS); + u32 intr_mask = rd32(fbd, FBNIC_SIG_PCS_INTR_STS); - if (pcs_intr_mask & FBNIC_SIG_PCS_INTR_LINK_DOWN) + if (intr_mask & FBNIC_SIG_PCS_INTR_LINK_DOWN) return FBNIC_LINK_EVENT_DOWN; - return (pcs_intr_mask & FBNIC_SIG_PCS_INTR_LINK_UP) ? + return (intr_mask & FBNIC_SIG_PCS_INTR_LINK_UP) ? FBNIC_LINK_EVENT_UP : FBNIC_LINK_EVENT_NONE; } @@ -466,9 +466,8 @@ static u32 __fbnic_mac_cmd_config_asic(struct fbnic_dev *fbd, return command_config; } -static bool fbnic_mac_get_pcs_link_status(struct fbnic_dev *fbd) +static bool fbnic_mac_get_link_status(struct fbnic_dev *fbd, u8 aui, u8 fec) { - struct fbnic_net *fbn = netdev_priv(fbd->netdev); u32 pcs_status, lane_mask = ~0; pcs_status = rd32(fbd, FBNIC_SIG_PCS_OUT0); @@ -476,7 +475,7 @@ static bool fbnic_mac_get_pcs_link_status(struct fbnic_dev *fbd) return false; /* Define the expected lane mask for the status bits we need to check */ - switch (fbn->aui) { + switch (aui) { case FBNIC_AUI_100GAUI2: lane_mask = 0xf; break; @@ -484,7 +483,7 @@ static bool fbnic_mac_get_pcs_link_status(struct fbnic_dev *fbd) lane_mask = 3; break; case FBNIC_AUI_LAUI2: - switch (fbn->fec) { + switch (fec) { case FBNIC_FEC_OFF: lane_mask = 0x63; break; @@ -502,7 +501,7 @@ static bool fbnic_mac_get_pcs_link_status(struct fbnic_dev *fbd) } /* Use an XOR to remove the bits we expect to see set */ - switch (fbn->fec) { + switch (fec) { case FBNIC_FEC_OFF: lane_mask ^= FIELD_GET(FBNIC_SIG_PCS_OUT0_BLOCK_LOCK, pcs_status); @@ -521,7 +520,46 @@ static bool fbnic_mac_get_pcs_link_status(struct fbnic_dev *fbd) return !lane_mask; } -static bool fbnic_pcs_get_link_asic(struct fbnic_dev *fbd) +static bool fbnic_pmd_update_state(struct fbnic_dev *fbd, bool signal_detect) +{ + /* Delay link up for 4 seconds to allow for link training. + * The state transitions for this are as follows: + * + * All states have the following two transitions in common: + * Loss of signal -> FBNIC_PMD_INITIALIZE + * The condition handled below (!signal) + * Reconfiguration -> FBNIC_PMD_INITIALIZE + * Occurs when mac_prepare starts a PHY reconfig + * FBNIC_PMD_TRAINING: + * signal still detected && 4s have passed -> Report link up + * When link is brought up in link_up -> FBNIC_PMD_SEND_DATA + * FBNIC_PMD_INITIALIZE: + * signal detected -> FBNIC_PMD_TRAINING + */ + if (!signal_detect) { + fbd->pmd_state = FBNIC_PMD_INITIALIZE; + return false; + } + + switch (fbd->pmd_state) { + case FBNIC_PMD_TRAINING: + return time_before(fbd->end_of_pmd_training, jiffies); + case FBNIC_PMD_LINK_READY: + case FBNIC_PMD_SEND_DATA: + return true; + } + + fbd->end_of_pmd_training = jiffies + 4 * HZ; + + /* Ensure end_of_training is visible before the state change */ + smp_wmb(); + + fbd->pmd_state = FBNIC_PMD_TRAINING; + + return false; +} + +static bool fbnic_mac_get_link(struct fbnic_dev *fbd, u8 aui, u8 fec) { bool link; @@ -538,7 +576,8 @@ static bool fbnic_pcs_get_link_asic(struct fbnic_dev *fbd) wr32(fbd, FBNIC_SIG_PCS_INTR_STS, FBNIC_SIG_PCS_INTR_LINK_DOWN | FBNIC_SIG_PCS_INTR_LINK_UP); - link = fbnic_mac_get_pcs_link_status(fbd); + link = fbnic_mac_get_link_status(fbd, aui, fec); + link = fbnic_pmd_update_state(fbd, link); /* Enable interrupt to only capture changes in link state */ wr32(fbd, FBNIC_SIG_PCS_INTR_MASK, @@ -586,20 +625,15 @@ void fbnic_mac_get_fw_settings(struct fbnic_dev *fbd, u8 *aui, u8 *fec) } } -static int fbnic_pcs_enable_asic(struct fbnic_dev *fbd) +static void fbnic_mac_prepare(struct fbnic_dev *fbd, u8 aui, u8 fec) { /* Mask and clear the PCS interrupt, will be enabled by link handler */ wr32(fbd, FBNIC_SIG_PCS_INTR_MASK, ~0); wr32(fbd, FBNIC_SIG_PCS_INTR_STS, ~0); - return 0; -} - -static void fbnic_pcs_disable_asic(struct fbnic_dev *fbd) -{ - /* Mask and clear the PCS interrupt */ - wr32(fbd, FBNIC_SIG_PCS_INTR_MASK, ~0); - wr32(fbd, FBNIC_SIG_PCS_INTR_STS, ~0); + /* If we don't have link tear it all down and start over */ + if (!fbnic_mac_get_link_status(fbd, aui, fec)) + fbd->pmd_state = FBNIC_PMD_INITIALIZE; } static void fbnic_mac_link_down_asic(struct fbnic_dev *fbd) @@ -867,10 +901,9 @@ static int fbnic_mac_get_sensor_asic(struct fbnic_dev *fbd, int id, static const struct fbnic_mac fbnic_mac_asic = { .init_regs = fbnic_mac_init_regs, - .pcs_enable = fbnic_pcs_enable_asic, - .pcs_disable = fbnic_pcs_disable_asic, - .pcs_get_link = fbnic_pcs_get_link_asic, - .pcs_get_link_event = fbnic_pcs_get_link_event_asic, + .get_link = fbnic_mac_get_link, + .get_link_event = fbnic_mac_get_link_event, + .prepare = fbnic_mac_prepare, .get_fec_stats = fbnic_mac_get_fec_stats, .get_pcs_stats = fbnic_mac_get_pcs_stats, .get_eth_mac_stats = fbnic_mac_get_eth_mac_stats, diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_mac.h b/drivers/net/ethernet/meta/fbnic/fbnic_mac.h index ede5ff0dae22..9b4fb0586dff 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_mac.h +++ b/drivers/net/ethernet/meta/fbnic/fbnic_mac.h @@ -10,6 +10,24 @@ struct fbnic_dev; #define FBNIC_MAX_JUMBO_FRAME_SIZE 9742 +/* States loosely based on section 136.8.11.7.5 of IEEE 802.3-2022 Ethernet + * Standard. These are needed to track the state of the PHY as it has a delay + * of several seconds from the time link comes up until it has completed + * training that we need to wait to report the link. + * + * Currently we treat training as a single block as this is managed by the + * firmware. + * + * We have FBNIC_PMD_SEND_DATA set to 0 as the expected default at driver load + * and we initialize the structure containing it to zero at allocation. + */ +enum { + FBNIC_PMD_SEND_DATA = 0x0, + FBNIC_PMD_INITIALIZE = 0x1, + FBNIC_PMD_TRAINING = 0x2, + FBNIC_PMD_LINK_READY = 0x3, +}; + enum { FBNIC_LINK_EVENT_NONE = 0, FBNIC_LINK_EVENT_UP = 1, @@ -55,15 +73,15 @@ enum fbnic_sensor_id { * void (*init_regs)(struct fbnic_dev *fbd); * Initialize MAC registers to enable Tx/Rx paths and FIFOs. * - * void (*pcs_enable)(struct fbnic_dev *fbd); - * Configure and enable PCS to enable link if not already enabled - * void (*pcs_disable)(struct fbnic_dev *fbd); - * Shutdown the link if we are the only consumer of it. - * bool (*pcs_get_link)(struct fbnic_dev *fbd); - * Check PCS link status - * int (*pcs_get_link_event)(struct fbnic_dev *fbd) + * int (*get_link_event)(struct fbnic_dev *fbd) * Get the current link event status, reports true if link has * changed to either FBNIC_LINK_EVENT_DOWN or FBNIC_LINK_EVENT_UP + * bool (*get_link)(struct fbnic_dev *fbd, u8 aui, u8 fec); + * Check link status + * + * void (*prepare)(struct fbnic_dev *fbd, u8 aui, u8 fec); + * Prepare PHY for init by fetching settings, disabling interrupts, + * and sending an updated PHY config to FW if needed. * * void (*link_down)(struct fbnic_dev *fbd); * Configure MAC for link down event @@ -74,10 +92,10 @@ enum fbnic_sensor_id { struct fbnic_mac { void (*init_regs)(struct fbnic_dev *fbd); - int (*pcs_enable)(struct fbnic_dev *fbd); - void (*pcs_disable)(struct fbnic_dev *fbd); - bool (*pcs_get_link)(struct fbnic_dev *fbd); - int (*pcs_get_link_event)(struct fbnic_dev *fbd); + int (*get_link_event)(struct fbnic_dev *fbd); + bool (*get_link)(struct fbnic_dev *fbd, u8 aui, u8 fec); + + void (*prepare)(struct fbnic_dev *fbd, u8 aui, u8 fec); void (*get_fec_stats)(struct fbnic_dev *fbd, bool reset, struct fbnic_fec_stats *fec_stats); diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_netdev.c b/drivers/net/ethernet/meta/fbnic/fbnic_netdev.c index fe995632a42c..8e97c4e7f32b 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_netdev.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_netdev.c @@ -44,7 +44,7 @@ int __fbnic_open(struct fbnic_net *fbn) if (err) goto time_stop; - err = fbnic_pcs_request_irq(fbd); + err = fbnic_mac_request_irq(fbd); if (err) goto time_stop; @@ -86,10 +86,10 @@ static int fbnic_stop(struct net_device *netdev) { struct fbnic_net *fbn = netdev_priv(netdev); - phylink_suspend(fbn->phylink, fbnic_bmc_present(fbn->fbd)); - fbnic_down(fbn); - fbnic_pcs_free_irq(fbn->fbd); + + fbnic_mac_free_irq(fbn->fbd); + phylink_suspend(fbn->phylink, fbnic_bmc_present(fbn->fbd)); fbnic_time_stop(fbn); fbnic_fw_xmit_ownership_msg(fbn->fbd, false); diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_netdev.h b/drivers/net/ethernet/meta/fbnic/fbnic_netdev.h index a05fc55221ab..6da8a37c2738 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_netdev.h +++ b/drivers/net/ethernet/meta/fbnic/fbnic_netdev.h @@ -111,7 +111,7 @@ int fbnic_phylink_ethtool_ksettings_get(struct net_device *netdev, int fbnic_phylink_get_fecparam(struct net_device *netdev, struct ethtool_fecparam *fecparam); int fbnic_phylink_init(struct net_device *netdev); - +void fbnic_phylink_pmd_training_complete_notify(struct net_device *netdev); bool fbnic_check_split_frames(struct bpf_prog *prog, unsigned int mtu, u32 hds_threshold); #endif /* _FBNIC_NETDEV_H_ */ diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_pci.c b/drivers/net/ethernet/meta/fbnic/fbnic_pci.c index 0ae0f0cf24ad..caa7cc1ddb6b 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_pci.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_pci.c @@ -211,6 +211,10 @@ static void fbnic_service_task(struct work_struct *work) { struct fbnic_dev *fbd = container_of(to_delayed_work(work), struct fbnic_dev, service_task); + struct net_device *netdev = fbd->netdev; + + if (netif_running(netdev)) + fbnic_phylink_pmd_training_complete_notify(netdev); rtnl_lock(); @@ -218,18 +222,25 @@ static void fbnic_service_task(struct work_struct *work) fbnic_fw_check_heartbeat(fbd); - fbnic_health_check(fbd); - - fbnic_bmc_rpc_check(fbd); - if (netif_carrier_ok(fbd->netdev)) { netdev_lock(fbd->netdev); fbnic_napi_depletion_check(fbd->netdev); netdev_unlock(fbd->netdev); } - if (netif_running(fbd->netdev)) + /* fbnic_service_task_stop() does not wait for a pass that is already + * blocked on RTNL, so one can run after ndo_stop. Leave host state + * alone in that case, and do not re-arm; __fbnic_open() reclaims and + * rebuilds it. The PM path calls ndo_stop with the device detached but + * still running; fbnic_up() starts the task again on resume. + */ + if (netif_running(netdev) && netif_device_present(netdev)) { + fbnic_health_check(fbd); + + fbnic_bmc_rpc_check(fbd); + schedule_delayed_work(&fbd->service_task, HZ); + } rtnl_unlock(); } @@ -439,6 +450,12 @@ static int fbnic_pm_suspend(struct device *dev) netdev_unlock(netdev); rtnl_unlock(); + /* ndo_stop could not wait for a pass already blocked on RTNL. That + * pass no longer re-arms, but wait for it to finish before the + * mailbox, IRQs and MMIO go away. + */ + cancel_delayed_work_sync(&fbd->service_task); + null_uc_addr: fbnic_fw_log_disable(fbd); @@ -539,19 +556,26 @@ static void __fbnic_pm_attach(struct device *dev) struct net_device *netdev = fbd->netdev; struct fbnic_net *fbn; - rtnl_lock(); - fbnic_reset_hw_stats(fbd); - rtnl_unlock(); - if (fbnic_init_failure(fbd)) return; fbn = netdev_priv(netdev); + /* Hold RTNL until the device is attached, so the service task pass + * fbnic_up() schedules cannot run until it will see it present. + */ + rtnl_lock(); + netdev_lock(netdev); + + fbnic_reset_hw_stats(fbd); + if (netif_running(netdev)) fbnic_up(fbn); netif_device_attach(netdev); + + netdev_unlock(netdev); + rtnl_unlock(); } static int __maybe_unused fbnic_pm_resume(struct device *dev) diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_phylink.c b/drivers/net/ethernet/meta/fbnic/fbnic_phylink.c index 62701923cfe9..20f88c8dcc79 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_phylink.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_phylink.c @@ -132,25 +132,9 @@ fbnic_phylink_pcs_get_state(struct phylink_pcs *pcs, unsigned int neg_mode, state->duplex = DUPLEX_FULL; - state->link = fbd->mac->pcs_get_link(fbd); -} - -static int -fbnic_phylink_pcs_enable(struct phylink_pcs *pcs) -{ - struct fbnic_net *fbn = fbnic_pcs_to_net(pcs); - struct fbnic_dev *fbd = fbn->fbd; - - return fbd->mac->pcs_enable(fbd); -} - -static void -fbnic_phylink_pcs_disable(struct phylink_pcs *pcs) -{ - struct fbnic_net *fbn = fbnic_pcs_to_net(pcs); - struct fbnic_dev *fbd = fbn->fbd; - - return fbd->mac->pcs_disable(fbd); + state->link = (fbd->pmd_state == FBNIC_PMD_SEND_DATA) && + (rd32(fbd, FBNIC_PCS(MDIO_STAT1, 0)) & + MDIO_STAT1_LSTATUS); } static int @@ -164,8 +148,6 @@ fbnic_phylink_pcs_config(struct phylink_pcs *pcs, unsigned int neg_mode, static const struct phylink_pcs_ops fbnic_phylink_pcs_ops = { .pcs_config = fbnic_phylink_pcs_config, - .pcs_enable = fbnic_phylink_pcs_enable, - .pcs_disable = fbnic_phylink_pcs_disable, .pcs_get_state = fbnic_phylink_pcs_get_state, }; @@ -179,12 +161,39 @@ fbnic_phylink_mac_select_pcs(struct phylink_config *config, return &fbn->phylink_pcs; } +static int +fbnic_phylink_mac_prepare(struct phylink_config *config, unsigned int mode, + phy_interface_t iface) +{ + struct net_device *netdev = to_net_dev(config->dev); + struct fbnic_net *fbn = netdev_priv(netdev); + struct fbnic_dev *fbd = fbn->fbd; + + fbd->mac->prepare(fbd, fbn->aui, fbn->fec); + + return 0; +} + static void fbnic_phylink_mac_config(struct phylink_config *config, unsigned int mode, const struct phylink_link_state *state) { } +static int +fbnic_phylink_mac_finish(struct phylink_config *config, unsigned int mode, + phy_interface_t iface) +{ + struct net_device *netdev = to_net_dev(config->dev); + struct fbnic_net *fbn = netdev_priv(netdev); + struct fbnic_dev *fbd = fbn->fbd; + + /* Retest the link state and restart interrupts */ + fbd->mac->get_link(fbd, fbn->aui, fbn->fec); + + return 0; +} + static void fbnic_phylink_mac_link_down(struct phylink_config *config, unsigned int mode, phy_interface_t interface) @@ -216,7 +225,9 @@ fbnic_phylink_mac_link_up(struct phylink_config *config, static const struct phylink_mac_ops fbnic_phylink_mac_ops = { .mac_select_pcs = fbnic_phylink_mac_select_pcs, + .mac_prepare = fbnic_phylink_mac_prepare, .mac_config = fbnic_phylink_mac_config, + .mac_finish = fbnic_phylink_mac_finish, .mac_link_down = fbnic_phylink_mac_link_down, .mac_link_up = fbnic_phylink_mac_link_up, }; @@ -257,3 +268,52 @@ int fbnic_phylink_init(struct net_device *netdev) return 0; } + +/** + * fbnic_phylink_pmd_training_complete_notify - PMD training complete notifier + * @netdev: Netdev struct phylink device attached to + * + * When the link first comes up the PMD will have a period of 2 to 3 seconds + * where the link will flutter due to link training. To avoid spamming the + * kernel log with messages about this we add a delay of 4 seconds from the + * time of the last PCS report of link so that we can guarantee we are unlikely + * to see any further link loss events due to link training. + **/ +void fbnic_phylink_pmd_training_complete_notify(struct net_device *netdev) +{ + struct fbnic_net *fbn = netdev_priv(netdev); + struct fbnic_dev *fbd = fbn->fbd; + + if (fbd->pmd_state != FBNIC_PMD_TRAINING) + return; + + /* Prevent reading end_of_pmd_training until we verified state */ + smp_rmb(); + + if (!time_before(READ_ONCE(fbd->end_of_pmd_training), jiffies)) + return; + + /* At this point we have verified that the link has been up for + * the full training duration. As a first step we will try + * transitioning to link ready. + */ + if (cmpxchg(&fbd->pmd_state, FBNIC_PMD_TRAINING, + FBNIC_PMD_LINK_READY) != FBNIC_PMD_TRAINING) + return; + + /* Perform a follow-up check to verify that the link didn't flap + * just before our transition by rechecking the training timer. + */ + if (!time_before(READ_ONCE(fbd->end_of_pmd_training), jiffies)) + return; + + /* The training timeout has been completed. We are good to swap out + * link_ready for send_data assuming no other events have occurred + * that would have pulled us back into initialization or training. + */ + if (cmpxchg(&fbd->pmd_state, FBNIC_PMD_LINK_READY, + FBNIC_PMD_SEND_DATA) != FBNIC_PMD_LINK_READY) + return; + + phylink_pcs_change(&fbn->phylink_pcs, false); +} diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c index d7ca0216155b..0a278f2a2ee7 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c @@ -2290,15 +2290,19 @@ void fbnic_disable(struct fbnic_net *fbn) static void fbnic_tx_flush(struct fbnic_dev *fbd) { + u32 drop_ctrl = FBNIC_TMI_DROP_CTRL_EN | FBNIC_TMI_DROP_CTRL_CMPL_DIS; + netdev_warn(fbd->netdev, "triggering Tx flush\n"); - fbnic_rmw32(fbd, FBNIC_TMI_DROP_CTRL, FBNIC_TMI_DROP_CTRL_EN, - FBNIC_TMI_DROP_CTRL_EN); + /* Drop packets and retire their PTP completions */ + fbnic_rmw32(fbd, FBNIC_TMI_DROP_CTRL, drop_ctrl, drop_ctrl); } static void fbnic_tx_flush_off(struct fbnic_dev *fbd) { - fbnic_rmw32(fbd, FBNIC_TMI_DROP_CTRL, FBNIC_TMI_DROP_CTRL_EN, 0); + u32 drop_ctrl = FBNIC_TMI_DROP_CTRL_EN | FBNIC_TMI_DROP_CTRL_CMPL_DIS; + + fbnic_rmw32(fbd, FBNIC_TMI_DROP_CTRL, drop_ctrl, 0); } struct fbnic_idle_regs { diff --git a/drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c b/drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c index 11a341fc4577..6dad3c019f01 100644 --- a/drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c +++ b/drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c @@ -354,6 +354,12 @@ static void lan966x_fdma_tx_clear_buf(struct lan966x *lan966x, int weight) if (!fdma_db_is_done(db)) continue; + /* XDP and page pool APIs can't be used with a budget of 0. + * Leave these buffers for the next NAPI poll. + */ + if (!weight && !dcb_buf->use_skb) + continue; + dcb_buf->dev->stats.tx_packets++; dcb_buf->dev->stats.tx_bytes += dcb_buf->len; diff --git a/drivers/net/ethernet/microchip/sparx5/sparx5_ptp.c b/drivers/net/ethernet/microchip/sparx5/sparx5_ptp.c index 2826e48af103..9f61692b243b 100644 --- a/drivers/net/ethernet/microchip/sparx5/sparx5_ptp.c +++ b/drivers/net/ethernet/microchip/sparx5/sparx5_ptp.c @@ -204,9 +204,10 @@ static void sparx5_ptp_classify(struct sparx5_port *port, struct sk_buff *skb, *rew_op = IFH_REW_OP_TWO_STEP_PTP; } -static void sparx5_ptp_txtstamp_old_release(struct sparx5_port *port) +static unsigned int sparx5_ptp_txtstamp_old_release(struct sparx5_port *port) { struct sk_buff *skb, *skb_tmp; + unsigned int purged = 0; unsigned long flags; spin_lock_irqsave(&port->tx_skbs.lock, flags); @@ -217,8 +218,11 @@ static void sparx5_ptp_txtstamp_old_release(struct sparx5_port *port) __skb_unlink(skb, &port->tx_skbs); dev_kfree_skb_any(skb); + purged++; } spin_unlock_irqrestore(&port->tx_skbs.lock, flags); + + return purged; } int sparx5_ptp_txtstamp_request(struct sparx5_port *port, @@ -226,6 +230,7 @@ int sparx5_ptp_txtstamp_request(struct sparx5_port *port, { struct sparx5 *sparx5 = port->sparx5; u8 rew_op, pdu_type, pdu_w16_offset; + unsigned int purged; unsigned long flags; sparx5_ptp_classify(port, skb, &rew_op, &pdu_type, &pdu_w16_offset); @@ -236,9 +241,10 @@ int sparx5_ptp_txtstamp_request(struct sparx5_port *port, if (rew_op != IFH_REW_OP_TWO_STEP_PTP) return 0; - sparx5_ptp_txtstamp_old_release(port); + purged = sparx5_ptp_txtstamp_old_release(port); spin_lock_irqsave(&sparx5->ptp_ts_id_lock, flags); + sparx5->ptp_skbs -= purged; if (sparx5->ptp_skbs == SPARX5_MAX_PTP_ID) { spin_unlock_irqrestore(&sparx5->ptp_ts_id_lock, flags); return -EBUSY; diff --git a/drivers/net/ethernet/microsoft/mana/mana_en.c b/drivers/net/ethernet/microsoft/mana/mana_en.c index befeb20fb7d5..fb895df97fc4 100644 --- a/drivers/net/ethernet/microsoft/mana/mana_en.c +++ b/drivers/net/ethernet/microsoft/mana/mana_en.c @@ -1978,10 +1978,9 @@ static void mana_rx_skb(void *buf_va, bool from_pool, skb_checksum_none_assert(skb); skb_record_rx_queue(skb, rxq_idx); - if ((ndev->features & NETIF_F_RXCSUM) && cqe->rx_iphdr_csum_succeed) { - if (cqe->rx_tcp_csum_succeed || cqe->rx_udp_csum_succeed) - skb->ip_summed = CHECKSUM_UNNECESSARY; - } + if ((ndev->features & NETIF_F_RXCSUM) && + (cqe->rx_tcp_csum_succeed || cqe->rx_udp_csum_succeed)) + skb->ip_summed = CHECKSUM_UNNECESSARY; if (cqe->rx_hashtype != 0 && (ndev->features & NETIF_F_RXHASH)) { hash_value = cqe->ppi[0].pkt_hash; diff --git a/drivers/net/ethernet/realtek/8139cp.c b/drivers/net/ethernet/realtek/8139cp.c index 9016527e229a..8f81dc7deef1 100644 --- a/drivers/net/ethernet/realtek/8139cp.c +++ b/drivers/net/ethernet/realtek/8139cp.c @@ -600,11 +600,11 @@ static irqreturn_t cp_interrupt (int irq, void *dev_instance) goto out_unlock; } - if (status & (RxOK | RxErr | RxEmpty | RxFIFOOvr)) - if (napi_schedule_prep(&cp->napi)) { - cpw16_f(IntrMask, cp_norx_intr_mask); + if (status & (RxOK | RxErr | RxEmpty | RxFIFOOvr)) { + cpw16_f(IntrMask, cp_norx_intr_mask); + if (napi_schedule_prep(&cp->napi)) __napi_schedule(&cp->napi); - } + } if (status & (TxOK | TxErr | TxEmpty | SWInt)) cp_tx(cp); diff --git a/drivers/net/ethernet/sfc/ptp.c b/drivers/net/ethernet/sfc/ptp.c index 4c7222bf26be..66a5342660a8 100644 --- a/drivers/net/ethernet/sfc/ptp.c +++ b/drivers/net/ethernet/sfc/ptp.c @@ -36,6 +36,7 @@ #include #include #include +#include #include #include #include "net_driver.h" @@ -267,11 +268,12 @@ struct efx_ptp_rxfilter { * @evt_frag_idx: Current fragment number * @evt_code: Last event code * @start: Address at which MC indicates ready for synchronisation - * @host_time_pps: Host time at last PPS * @adjfreq_ppb_shift: Shift required to convert scaled parts-per-billion * frequency adjustment into a fixed point fractional nanosecond format. * @current_adjfreq: Current ppb adjustment. * @phc_clock: Pointer to registered phc device (if primary function) + * @phc_lock: Serializes PHC commands and synchronization, and protects + * @current_adjfreq * @phc_clock_info: Registration structure for phc device * @pps_work: pps work task for handling pps events * @pps_workwq: pps work queue @@ -327,10 +329,10 @@ struct efx_ptp_data { int evt_frag_idx; int evt_code; struct efx_buffer start; - struct pps_event_time host_time_pps; unsigned int adjfreq_ppb_shift; s64 current_adjfreq; struct ptp_clock *phc_clock; + struct mutex phc_lock; struct ptp_clock_info phc_clock_info; struct work_struct pps_work; struct workqueue_struct *pps_workwq; @@ -908,7 +910,8 @@ static void efx_ptp_read_timeset(MCDI_DECLARE_STRUCT_PTR(data), static int efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf), size_t response_length, - const struct pps_event_time *last_time) + const struct pps_event_time *last_time, + struct pps_event_time *host_time_pps) { unsigned number_readings = MCDI_VAR_ARRAY_LEN(response_length, @@ -986,6 +989,10 @@ efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf), "PTP bad synchronisation seconds\n"); return -EAGAIN; } + + if (!host_time_pps) + return 0; + delta.tv_sec = (last_sec - start_sec) & 1; delta.tv_nsec = last_time->ts_real.tv_nsec - @@ -1002,14 +1009,22 @@ efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf), delta.tv_nsec += ktime_to_timespec64(mc_time).tv_nsec; /* Set PPS timestamp to match NIC top of second */ - ptp->host_time_pps = *last_time; - pps_sub_ts(&ptp->host_time_pps, delta); + *host_time_pps = *last_time; + pps_sub_ts(host_time_pps, delta); return 0; } -/* Synchronize times between the host and the MC */ -static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings) +/* Synchronize times between the host and the MC. + * + * The MC serializes PTP requests, so MC_CMD_PTP_OP_ADJUST cannot be applied + * while MC_CMD_PTP_OP_SYNCHRONIZE is collecting timesets. This holds across + * functions of a controller, which share the clock but adjust it only through + * the function that registered it, so a secondary function can capture here + * without serializing against the primary. + */ +static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings, + struct pps_event_time *host_time_pps) { struct efx_ptp_data *ptp = efx->ptp_data; MCDI_DECLARE_BUF(synch_buf, MC_CMD_PTP_OUT_SYNCHRONIZE_LENMAX); @@ -1027,11 +1042,14 @@ static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings) MCDI_SET_QWORD(synch_buf, PTP_IN_SYNCHRONIZE_START_ADDR, ptp->start.dma_addr); + mutex_lock(&ptp->phc_lock); + /* Clear flag that signals MC ready */ WRITE_ONCE(*start, 0); rc = efx_mcdi_rpc_start(efx, MC_CMD_PTP, synch_buf, MC_CMD_PTP_IN_SYNCHRONIZE_LEN); - EFX_WARN_ON_ONCE_PARANOID(rc); + if (rc) + goto out; /* Wait for start from MCDI (or timeout) */ timeout = jiffies + msecs_to_jiffies(MAX_SYNCHRONISE_WAIT_MS); @@ -1055,18 +1073,20 @@ static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings) &response_length); if (rc == 0) { rc = efx_ptp_process_times(efx, synch_buf, response_length, - &last_time); + &last_time, host_time_pps); if (rc == 0) ++ptp->good_syncs; else ++ptp->no_time_syncs; } +out: /* Increment the bad syncs counter if the synchronize fails, whatever * the reason. */ if (rc != 0) ++ptp->bad_syncs; + mutex_unlock(&ptp->phc_lock); return rc; } @@ -1446,7 +1466,6 @@ static int efx_ptp_start(struct efx_nic *efx) goto fail; ptp->evt_frag_idx = 0; - ptp->current_adjfreq = 0; return 0; @@ -1486,14 +1505,15 @@ static void efx_ptp_pps_worker(struct work_struct *work) { struct efx_ptp_data *ptp = container_of(work, struct efx_ptp_data, pps_work); + struct pps_event_time host_time_pps = {}; struct efx_nic *efx = ptp->efx; struct ptp_clock_event ptp_evt; - if (efx_ptp_synchronize(efx, PTP_SYNC_ATTEMPTS)) + if (efx_ptp_synchronize(efx, PTP_SYNC_ATTEMPTS, &host_time_pps)) return; ptp_evt.type = PTP_CLOCK_PPSUSR; - ptp_evt.pps_times = ptp->host_time_pps; + ptp_evt.pps_times = host_time_pps; ptp_clock_event(ptp->phc_clock, &ptp_evt); } @@ -1570,6 +1590,7 @@ int efx_ptp_probe(struct efx_nic *efx, struct efx_channel *channel) if (!efx->ptp_data) return -ENOMEM; + mutex_init(&ptp->phc_lock); ptp->efx = efx; ptp->channel = channel; @@ -1641,6 +1662,7 @@ int efx_ptp_probe(struct efx_nic *efx, struct efx_channel *channel) efx_nic_free_buffer(efx, &ptp->start); fail1: + mutex_destroy(&ptp->phc_lock); kfree(efx->ptp_data); efx->ptp_data = NULL; @@ -1695,6 +1717,7 @@ void efx_ptp_remove(struct efx_nic *efx) destroy_workqueue(efx->ptp_data->workwq); efx_nic_free_buffer(efx, &efx->ptp_data->start); + mutex_destroy(&efx->ptp_data->phc_lock); kfree(efx->ptp_data); efx->ptp_data = NULL; } @@ -1826,7 +1849,8 @@ int efx_ptp_change_mode(struct efx_nic *efx, bool enable_wanted, rc = efx_ptp_start(efx); if (rc == 0) { rc = efx_ptp_synchronize(efx, - PTP_SYNC_ATTEMPTS * 2); + PTP_SYNC_ATTEMPTS * 2, + NULL); if (rc != 0) efx_ptp_stop(efx); } @@ -2106,23 +2130,23 @@ static int efx_phc_adjfine(struct ptp_clock_info *ptp, long scaled_ppm) MCDI_SET_QWORD(inadj, PTP_IN_ADJUST_FREQ, adjustment_ns); MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_SECONDS, 0); MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_NANOSECONDS, 0); + mutex_lock(&ptp_data->phc_lock); rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inadj, sizeof(inadj), NULL, 0, NULL); - if (rc != 0) - return rc; - - ptp_data->current_adjfreq = adjustment_ns; - return 0; + if (!rc) + ptp_data->current_adjfreq = adjustment_ns; + mutex_unlock(&ptp_data->phc_lock); + return rc; } -static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta) +static int _efx_phc_adjtime(struct efx_ptp_data *ptp_data, s64 delta) + __must_hold(&ptp_data->phc_lock) { - u32 nic_major, nic_minor; - struct efx_ptp_data *ptp_data = container_of(ptp, - struct efx_ptp_data, - phc_clock_info); - struct efx_nic *efx = ptp_data->efx; MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_ADJUST_LEN); + struct efx_nic *efx = ptp_data->efx; + u32 nic_major, nic_minor; + + lockdep_assert_held(&ptp_data->phc_lock); efx->ptp_data->ns_to_nic_time(delta, &nic_major, &nic_minor); @@ -2135,6 +2159,18 @@ static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta) NULL, 0, NULL); } +static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta) +{ + struct efx_ptp_data *ptp_data = container_of(ptp, struct efx_ptp_data, + phc_clock_info); + int rc; + + mutex_lock(&ptp_data->phc_lock); + rc = _efx_phc_adjtime(ptp_data, delta); + mutex_unlock(&ptp_data->phc_lock); + return rc; +} + static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec64 *ts) { struct efx_ptp_data *ptp_data = container_of(ptp, @@ -2166,23 +2202,21 @@ static int efx_phc_settime(struct ptp_clock_info *ptp, { /* Get the current NIC time, efx_phc_gettime. * Subtract from the desired time to get the offset - * call efx_phc_adjtime with the offset + * call _efx_phc_adjtime with the offset */ + struct efx_ptp_data *ptp_data = container_of(ptp, struct efx_ptp_data, + phc_clock_info); + struct timespec64 time_now, delta; int rc; - struct timespec64 time_now; - struct timespec64 delta; + mutex_lock(&ptp_data->phc_lock); rc = efx_phc_gettime(ptp, &time_now); - if (rc != 0) - return rc; - - delta = timespec64_sub(*e_ts, time_now); - - rc = efx_phc_adjtime(ptp, timespec64_to_ns(&delta)); - if (rc != 0) - return rc; - - return 0; + if (!rc) { + delta = timespec64_sub(*e_ts, time_now); + rc = _efx_phc_adjtime(ptp_data, timespec64_to_ns(&delta)); + } + mutex_unlock(&ptp_data->phc_lock); + return rc; } static int efx_phc_enable(struct ptp_clock_info *ptp, diff --git a/drivers/net/ethernet/stmicro/stmmac/enh_desc.c b/drivers/net/ethernet/stmicro/stmmac/enh_desc.c index 963579518405..9833db1fed0c 100644 --- a/drivers/net/ethernet/stmicro/stmmac/enh_desc.c +++ b/drivers/net/ethernet/stmicro/stmmac/enh_desc.c @@ -210,7 +210,7 @@ static int enh_desc_get_rx_status(struct stmmac_extra_stats *x, if (unlikely(!(rdes0 & RDES0_LAST_DESCRIPTOR))) { x->rx_length++; - return discard_frame; + return discard_frame | rx_not_ls; } if (unlikely(rdes0 & RDES0_ERROR_SUMMARY)) { diff --git a/drivers/net/ethernet/stmicro/stmmac/norm_desc.c b/drivers/net/ethernet/stmicro/stmmac/norm_desc.c index 68a7cfcb1d8f..c08846da03eb 100644 --- a/drivers/net/ethernet/stmicro/stmmac/norm_desc.c +++ b/drivers/net/ethernet/stmicro/stmmac/norm_desc.c @@ -77,7 +77,7 @@ static int ndesc_get_rx_status(struct stmmac_extra_stats *x, if (unlikely(!(rdes0 & RDES0_LAST_DESCRIPTOR))) { x->rx_length++; - return discard_frame; + return discard_frame | rx_not_ls; } if (unlikely(rdes0 & RDES0_ERROR_SUMMARY)) { diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac.h b/drivers/net/ethernet/stmicro/stmmac/stmmac.h index 61e182278d15..7cb09679a0d9 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac.h +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac.h @@ -282,6 +282,12 @@ struct stmmac_priv { /* Protect est parameters */ struct mutex est_lock; struct stmmac_est *est; + + struct { + bool enabled; + u32 num_tx_queues; + } xmit_qdisc; + struct dma_features dma_cap; struct stmmac_counters mmc; int hw_cap_support; diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_ethtool.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_ethtool.c index 741e3864f509..3d501be64619 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_ethtool.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_ethtool.c @@ -832,7 +832,8 @@ static int __stmmac_get_coalesce(struct net_device *dev, if (queue < tx_cnt) { ec->tx_coalesce_usecs = priv->tx_coal_timer[queue]; - ec->tx_max_coalesced_frames = priv->tx_coal_frames[queue]; + ec->tx_max_coalesced_frames = + READ_ONCE(priv->tx_coal_frames[queue]); } else { ec->tx_coalesce_usecs = 0; ec->tx_max_coalesced_frames = 0; @@ -921,14 +922,14 @@ static int __stmmac_set_coalesce(struct net_device *dev, int i; for (i = 0; i < tx_cnt; i++) { - priv->tx_coal_frames[i] = - ec->tx_max_coalesced_frames; + WRITE_ONCE(priv->tx_coal_frames[i], + ec->tx_max_coalesced_frames); priv->tx_coal_timer[i] = ec->tx_coalesce_usecs; } } else if (queue < tx_cnt) { - priv->tx_coal_frames[queue] = - ec->tx_max_coalesced_frames; + WRITE_ONCE(priv->tx_coal_frames[queue], + ec->tx_max_coalesced_frames); priv->tx_coal_timer[queue] = ec->tx_coalesce_usecs; } diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c index 98e6d2cc544c..c4053684dec3 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c @@ -1939,6 +1939,9 @@ static void __free_dma_rx_desc_resources(struct stmmac_priv *priv, else dma_free_rx_skbufs(priv, dma_conf, queue); + dev_kfree_skb_any(rx_q->state.skb); + rx_q->state.skb = NULL; + rx_q->state_saved = false; rx_q->buf_alloc_num = 0; rx_q->xsk_pool = NULL; @@ -2521,7 +2524,8 @@ static bool stmmac_xdp_xmit_zc(struct stmmac_priv *priv, u32 queue, u32 budget) struct stmmac_metadata_request meta_req; struct xsk_tx_metadata *meta = NULL; dma_addr_t dma_addr; - bool set_ic; + bool set_ic = false; + u32 tx_coal; /* We are sharing with slow path and stop XSK TX desc submission when * available TX ring is less than threshold. @@ -2572,12 +2576,9 @@ static bool stmmac_xdp_xmit_zc(struct stmmac_priv *priv, u32 queue, u32 budget) tx_q->tx_count_frames++; - if (!priv->tx_coal_frames[queue]) - set_ic = false; - else if (tx_q->tx_count_frames % priv->tx_coal_frames[queue] == 0) + tx_coal = READ_ONCE(priv->tx_coal_frames[queue]); + if (tx_coal && !(tx_q->tx_count_frames % tx_coal)) set_ic = true; - else - set_ic = false; meta_req.priv = priv; meta_req.tx_desc = tx_desc; @@ -3176,7 +3177,7 @@ static void stmmac_init_coalesce(struct stmmac_priv *priv) for (chan = 0; chan < tx_channel_count; chan++) { struct stmmac_tx_queue *tx_q = &priv->dma_conf.tx_queue[chan]; - priv->tx_coal_frames[chan] = STMMAC_TX_FRAMES; + WRITE_ONCE(priv->tx_coal_frames[chan], STMMAC_TX_FRAMES); priv->tx_coal_timer[chan] = STMMAC_COAL_TX_TIMER; hrtimer_setup(&tx_q->txtimer, stmmac_tx_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); @@ -3551,7 +3552,7 @@ static int stmmac_hw_setup(struct net_device *dev) /* Configure real RX and TX queues */ netif_set_real_num_rx_queues(dev, priv->plat->rx_queues_to_use); - netif_set_real_num_tx_queues(dev, priv->plat->tx_queues_to_use); + netif_set_real_num_tx_queues(dev, priv->xmit_qdisc.num_tx_queues); /* Start the ball rolling... */ stmmac_start_all_dma(priv); @@ -4265,9 +4266,9 @@ static netdev_tx_t stmmac_tso_xmit(struct sk_buff *skb, struct net_device *dev) struct stmmac_priv *priv = netdev_priv(dev); unsigned int first_entry, entry, tx_packets; struct stmmac_txq_stats *txq_stats; + u32 tx_coal, pay_len, mss, queue; int i, first_tx, nfrags, ndesc; struct stmmac_tx_queue *tx_q; - u32 pay_len, mss, queue; u8 proto_hdr_len, hdr; dma_addr_t des; bool set_ic; @@ -4405,16 +4406,16 @@ static netdev_tx_t stmmac_tso_xmit(struct sk_buff *skb, struct net_device *dev) tx_packets = (tx_q->cur_tx + 1) - first_tx; tx_q->tx_count_frames += tx_packets; + tx_coal = READ_ONCE(priv->tx_coal_frames[queue]); if ((skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP) && priv->hwts_tx_en) set_ic = true; - else if (!priv->tx_coal_frames[queue]) + else if (!tx_coal) set_ic = false; else if (!netdev_xmit_more()) set_ic = true; - else if (tx_packets > priv->tx_coal_frames[queue]) + else if (tx_packets > tx_coal) set_ic = true; - else if ((tx_q->tx_count_frames % - priv->tx_coal_frames[queue]) < tx_packets) + else if ((tx_q->tx_count_frames % tx_coal) < tx_packets) set_ic = true; else set_ic = false; @@ -4560,7 +4561,7 @@ static netdev_tx_t stmmac_xmit(struct sk_buff *skb, struct net_device *dev) bool has_vlan, set_ic; int entry, first_tx; dma_addr_t des; - u32 sdu_len; + u32 tx_coal, sdu_len; tx_q = &priv->dma_conf.tx_queue[queue]; txq_stats = &priv->xstats.txq_stats[queue]; @@ -4694,16 +4695,16 @@ static netdev_tx_t stmmac_xmit(struct sk_buff *skb, struct net_device *dev) tx_packets = (entry + 1) - first_tx; tx_q->tx_count_frames += tx_packets; + tx_coal = READ_ONCE(priv->tx_coal_frames[queue]); if ((skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP) && priv->hwts_tx_en) set_ic = true; - else if (!priv->tx_coal_frames[queue]) + else if (!tx_coal) set_ic = false; else if (!netdev_xmit_more()) set_ic = true; - else if (tx_packets > priv->tx_coal_frames[queue]) + else if (tx_packets > tx_coal) set_ic = true; - else if ((tx_q->tx_count_frames % - priv->tx_coal_frames[queue]) < tx_packets) + else if ((tx_q->tx_count_frames % tx_coal) < tx_packets) set_ic = true; else set_ic = false; @@ -4829,22 +4830,35 @@ static netdev_features_t stmmac_features_check(struct sk_buff *skb, return vlan_features_check(skb, features); } -static void stmmac_rx_vlan(struct net_device *dev, struct sk_buff *skb) +static int stmmac_rx_vlan(struct net_device *dev, struct sk_buff *skb) { - struct vlan_ethhdr *veth = skb_vlan_eth_hdr(skb); - __be16 vlan_proto = veth->h_vlan_proto; - u16 vlanid; + struct vlan_ethhdr *veth; + + if (!pskb_may_pull(skb, ETH_HLEN)) + return -EINVAL; - if ((vlan_proto == htons(ETH_P_8021Q) && + veth = skb_vlan_eth_hdr(skb); + if ((veth->h_vlan_proto == htons(ETH_P_8021Q) && dev->features & NETIF_F_HW_VLAN_CTAG_RX) || - (vlan_proto == htons(ETH_P_8021AD) && + (veth->h_vlan_proto == htons(ETH_P_8021AD) && dev->features & NETIF_F_HW_VLAN_STAG_RX)) { + __be16 vlan_proto = veth->h_vlan_proto; + u8 meta_len = skb_metadata_len(skb); + u16 vlanid; + /* pop the vlan tag */ + if (!pskb_may_pull(skb, VLAN_ETH_HLEN)) + return -EINVAL; + + veth = skb_vlan_eth_hdr(skb); vlanid = ntohs(veth->h_vlan_TCI); - memmove(skb->data + VLAN_HLEN, veth, ETH_ALEN * 2); + memmove(skb->data - meta_len + VLAN_HLEN, + skb->data - meta_len, meta_len + ETH_ALEN * 2); skb_pull(skb, VLAN_HLEN); __vlan_hwaccel_put_tag(skb, vlan_proto, vlanid); } + + return 0; } /** @@ -4992,7 +5006,7 @@ static int stmmac_xdp_xmit_xdpf(struct stmmac_priv *priv, int queue, unsigned int entry = tx_q->cur_tx; struct dma_desc *tx_desc; dma_addr_t dma_addr; - bool set_ic; + u32 tx_coal; if (stmmac_tx_avail(priv, queue) < STMMAC_TX_THRESH(priv)) return STMMAC_XDP_CONSUMED; @@ -5045,12 +5059,8 @@ static int stmmac_xdp_xmit_xdpf(struct stmmac_priv *priv, int queue, tx_q->tx_count_frames++; - if (tx_q->tx_count_frames % priv->tx_coal_frames[queue] == 0) - set_ic = true; - else - set_ic = false; - - if (set_ic) { + tx_coal = READ_ONCE(priv->tx_coal_frames[queue]); + if (tx_coal && !(tx_q->tx_count_frames % tx_coal)) { tx_q->tx_count_frames = 0; stmmac_set_tx_ic(priv, tx_desc); u64_stats_update_begin(&txq_stats->q_syncp); @@ -5198,7 +5208,8 @@ static struct sk_buff *stmmac_construct_skb_zc(struct stmmac_channel *ch, return NULL; skb_reserve(skb, xdp->data - xdp->data_hard_start); - memcpy(__skb_put(skb, datasize), xdp->data, datasize); + __skb_put(skb, datasize); + memcpy(skb->data - metasize, xdp->data_meta, datasize + metasize); if (metasize) skb_metadata_set(skb, metasize); @@ -5224,12 +5235,15 @@ static void stmmac_dispatch_skb_zc(struct stmmac_priv *priv, u32 queue, } stmmac_get_rx_hwtstamp(priv, p, np, skb); - if (priv->hw->hw_vlan_en) + if (priv->hw->hw_vlan_en) { /* MAC level stripping. */ stmmac_rx_hw_vlan(priv, priv->hw, p, skb); - else - /* Driver level stripping. */ - stmmac_rx_vlan(priv->dev, skb); + } else if (stmmac_rx_vlan(priv->dev, skb)) { + dev_kfree_skb_any(skb); + priv->xstats.rx_dropped++; + return; + } + skb->protocol = eth_type_trans(skb, priv->dev); if (unlikely(!coe) || !stmmac_has_ip_ethertype(skb)) @@ -5244,7 +5258,7 @@ static void stmmac_dispatch_skb_zc(struct stmmac_priv *priv, u32 queue, napi_gro_receive(&ch->rxtx_napi, skb); u64_stats_update_begin(&rxq_stats->napi_syncp); - u64_stats_inc(&rxq_stats->napi.rx_pkt_n); + u64_stats_inc(&rxq_stats->napi.rx_packets); u64_stats_add(&rxq_stats->napi.rx_bytes, len); u64_stats_update_end(&rxq_stats->napi_syncp); } @@ -5324,12 +5338,12 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) unsigned int count = 0, error = 0, len = 0; int dirty = stmmac_rx_dirty(priv, queue); unsigned int next_entry = rx_q->cur_rx; + bool in_progress = rx_q->state_saved; u32 rx_errors = 0, rx_dropped = 0; unsigned int desc_size; struct bpf_prog *prog; bool failure = false; int xdp_status = 0; - int status = 0; if (netif_msg_rx_status(priv)) { void *rx_head; @@ -5346,23 +5360,25 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) stmmac_display_ring(priv, rx_head, priv->dma_conf.dma_rx_size, true, rx_q->dma_rx_phy, desc_size); } + + if (rx_q->state_saved) { + error = rx_q->state.error; + len = rx_q->state.len; + rx_q->state_saved = false; + } + while (count < limit) { struct stmmac_rx_buffer *buf; struct stmmac_xdp_buff *ctx; unsigned int buf1_len = 0; struct dma_desc *np, *p; - int entry; + int entry, status; int res; - if (!count && rx_q->state_saved) { - error = rx_q->state.error; - len = rx_q->state.len; - } else { - rx_q->state_saved = false; + if (!in_progress) { error = 0; len = 0; } - read_again: if (count >= limit) break; @@ -5407,6 +5423,8 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) if (!buf->xdp) break; + in_progress = status & rx_not_ls; + if (priv->extend_desc) { /* Read the extended status after the own bit */ dma_rmb(); @@ -5414,18 +5432,21 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) &rx_q->dma_erx[entry], status); } - if (unlikely(status == discard_frame)) { - xsk_buff_free(buf->xdp); - buf->xdp = NULL; - dirty++; + + if (unlikely(!error && (status & discard_frame))) { error = 1; if (!priv->hwts_rx_en) rx_errors++; } - if (unlikely(error && (status & rx_not_ls))) - goto read_again; if (unlikely(error)) { + xsk_buff_free(buf->xdp); + buf->xdp = NULL; + dirty++; + + if (status & rx_not_ls) + goto read_again; + count++; continue; } @@ -5434,8 +5455,9 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) if (likely(status & rx_not_ls)) { xsk_buff_free(buf->xdp); buf->xdp = NULL; + rx_dropped++; + error = 1; dirty++; - count++; goto read_again; } @@ -5483,7 +5505,7 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) count++; } - if (status & rx_not_ls) { + if (in_progress) { rx_q->state_saved = true; rx_q->state.error = error; rx_q->state.len = len; @@ -5525,9 +5547,10 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) struct stmmac_rx_queue *rx_q = &priv->dma_conf.rx_queue[queue]; struct stmmac_channel *ch = &priv->channel[queue]; unsigned int count = 0, error = 0, len = 0; - int status = 0, coe = priv->hw->rx_csum; unsigned int next_entry = rx_q->cur_rx; + bool in_progress = rx_q->state_saved; enum dma_data_direction dma_dir; + int coe = priv->hw->rx_csum; unsigned int desc_size; struct sk_buff *skb = NULL; struct stmmac_xdp_buff ctx; @@ -5553,25 +5576,28 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) stmmac_display_ring(priv, rx_head, priv->dma_conf.dma_rx_size, true, rx_q->dma_rx_phy, desc_size); } + + if (rx_q->state_saved) { + skb = rx_q->state.skb; + error = rx_q->state.error; + len = rx_q->state.len; + rx_q->state.skb = NULL; + rx_q->state_saved = false; + } + while (count < limit) { unsigned int buf1_len = 0, buf2_len = 0; enum pkt_hash_types hash_type; struct stmmac_rx_buffer *buf; struct dma_desc *np, *p; - int entry; + int entry, status; u32 hash; - if (!count && rx_q->state_saved) { - skb = rx_q->state.skb; - error = rx_q->state.error; - len = rx_q->state.len; - } else { - rx_q->state_saved = false; + if (!in_progress) { skb = NULL; error = 0; len = 0; } - read_again: if (count >= limit) break; @@ -5606,6 +5632,8 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) prefetch(np); + in_progress = status & rx_not_ls; + if (priv->extend_desc) { /* Read the extended status after the own bit */ dma_rmb(); @@ -5613,21 +5641,26 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) &rx_q->dma_erx[entry], status); } - if (unlikely(status == discard_frame)) { - page_pool_put_page(rx_q->page_pool, buf->page, 0, true); - buf->page = NULL; + + if (unlikely(!error && (status & discard_frame))) { error = 1; if (!priv->hwts_rx_en) rx_errors++; } - if (unlikely(error && (status & rx_not_ls))) - goto read_again; + /* We do not support SG in XDP mode */ + if (unlikely(!error && (status & rx_not_ls) && + stmmac_xdp_is_enabled(priv))) { + rx_dropped++; + error = 1; + } + if (unlikely(error)) { + if (status & rx_not_ls) + goto read_again; + dev_kfree_skb(skb); - skb = NULL; - count++; - continue; + goto next; } /* Buffer is good. Go on. */ @@ -5637,13 +5670,19 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) buf2_len = stmmac_rx_buf2_len(priv, p, status, len); len += buf2_len; + /* Drop the packet if it is split over buf1 and buf2 on a + * single descriptor if the interface is running in XDP mode. + */ + if (unlikely(stmmac_xdp_is_enabled(priv) && buf2_len)) { + rx_dropped++; + goto next; + } + /* ACS is disabled; strip manually. */ if (likely(!(status & rx_not_ls))) len -= ETH_FCS_LEN; if (!skb) { - unsigned int pre_len, sync_len; - /* Each frame starts here: reset the FCS handling */ fcs_stripped = false; @@ -5661,55 +5700,32 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) xdp_prepare_buff(&ctx.xdp, page_address(buf->page), buf->page_offset, buf1_len, true); - pre_len = ctx.xdp.data_end - ctx.xdp.data_hard_start - - buf->page_offset; - ctx.priv = priv; ctx.desc = p; ctx.ndesc = np; skb = stmmac_xdp_run_prog(priv, &ctx.xdp); - /* Due xdp_adjust_tail: DMA sync for_device - * cover max len CPU touch - */ - sync_len = ctx.xdp.data_end - ctx.xdp.data_hard_start - - buf->page_offset; - sync_len = max(sync_len, pre_len); - /* For Not XDP_PASS verdict */ if (IS_ERR(skb)) { unsigned int xdp_res = -PTR_ERR(skb); if (xdp_res & STMMAC_XDP_CONSUMED) { - page_pool_put_page(rx_q->page_pool, - virt_to_head_page(ctx.xdp.data), - sync_len, true); + page_pool_recycle_direct(rx_q->page_pool, + virt_to_head_page(ctx.xdp.data)); buf->page = NULL; rx_dropped++; - - /* Clear skb as it was set as - * status by XDP program. - */ - skb = NULL; - - if (unlikely((status & rx_not_ls))) - goto read_again; - - count++; - continue; + goto next; } else if (xdp_res & (STMMAC_XDP_TX | STMMAC_XDP_REDIRECT)) { xdp_status |= xdp_res; buf->page = NULL; - skb = NULL; - count++; - continue; + goto next; } } } if (!skb) { - unsigned int head_pad_len; + unsigned int metasize; /* XDP program may expand or reduce tail */ buf1_len = ctx.xdp.data_end - ctx.xdp.data; @@ -5726,10 +5742,14 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) } /* XDP program may adjust header */ - head_pad_len = ctx.xdp.data - ctx.xdp.data_hard_start; - skb_reserve(skb, head_pad_len); + skb_reserve(skb, + ctx.xdp.data - ctx.xdp.data_hard_start); skb_put(skb, buf1_len); skb_mark_for_recycle(skb); + + metasize = ctx.xdp.data - ctx.xdp.data_meta; + if (metasize) + skb_metadata_set(skb, metasize); buf->page = NULL; } else if (buf1_len) { dma_sync_single_for_cpu(priv->device, buf->addr, @@ -5760,20 +5780,20 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) /* Remove FCS if needed */ if (!fcs_stripped && pskb_trim(skb, len)) { dev_kfree_skb_any(skb); - skb = NULL; rx_dropped++; - count++; - continue; + goto next; } stmmac_get_rx_hwtstamp(priv, p, np, skb); - if (priv->hw->hw_vlan_en) + if (priv->hw->hw_vlan_en) { /* MAC level stripping. */ stmmac_rx_hw_vlan(priv, priv->hw, p, skb); - else - /* Driver level stripping. */ - stmmac_rx_vlan(priv->dev, skb); + } else if (stmmac_rx_vlan(priv->dev, skb)) { + dev_kfree_skb_any(skb); + rx_dropped++; + goto next; + } skb->protocol = eth_type_trans(skb, priv->dev); @@ -5788,14 +5808,15 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) skb_record_rx_queue(skb, queue); napi_gro_receive(&ch->rx_napi, skb); - skb = NULL; - rx_packets++; rx_bytes += len; +next: + in_progress = false; + skb = NULL; count++; } - if (status & rx_not_ls || skb) { + if (in_progress || skb) { rx_q->state_saved = true; rx_q->state.skb = skb; rx_q->state.error = error; @@ -7463,6 +7484,10 @@ int stmmac_reinit_queues(struct net_device *dev, u32 rx_cnt, u32 tx_cnt) struct stmmac_priv *priv = netdev_priv(dev); int ret = 0, i; + if (priv->xmit_qdisc.enabled && + tx_cnt < priv->xmit_qdisc.num_tx_queues) + return -EINVAL; + if (netif_running(dev)) stmmac_release(dev); @@ -7470,6 +7495,9 @@ int stmmac_reinit_queues(struct net_device *dev, u32 rx_cnt, u32 tx_cnt) priv->plat->rx_queues_to_use = rx_cnt; priv->plat->tx_queues_to_use = tx_cnt; + if (!priv->xmit_qdisc.enabled) + priv->xmit_qdisc.num_tx_queues = tx_cnt; + if (!netif_is_rxfh_configured(dev)) for (i = 0; i < ARRAY_SIZE(priv->rss.table); i++) priv->rss.table[i] = ethtool_rxfh_indir_default(i, @@ -7661,6 +7689,9 @@ int stmmac_dvr_probe(struct device *device, ndev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT | NETDEV_XDP_ACT_XSK_ZEROCOPY; + /* Default qdisc num_tx_queues */ + priv->xmit_qdisc.num_tx_queues = priv->plat->tx_queues_to_use; + ret = stmmac_tc_init(priv, priv); if (!ret) { ndev->hw_features |= NETIF_F_HW_TC; @@ -7948,6 +7979,9 @@ static void stmmac_reset_rx_queue(struct stmmac_priv *priv, u32 queue) { struct stmmac_rx_queue *rx_q = &priv->dma_conf.rx_queue[queue]; + dev_kfree_skb_any(rx_q->state.skb); + rx_q->state.skb = NULL; + rx_q->state_saved = false; rx_q->cur_rx = 0; rx_q->dirty_rx = 0; } diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c index 0e4481127dc0..d569cf572c11 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_ptp.c @@ -302,6 +302,7 @@ const struct ptp_clock_info stmmac_ptp_clock_ops = { .n_per_out = 0, /* will be overwritten in stmmac_ptp_register */ .n_pins = 0, .pps = 0, + .supported_extts_flags = PTP_RISING_EDGE | PTP_STRICT_FLAGS, .adjfine = stmmac_adjust_freq, .adjtime = stmmac_adjust_time, .gettime64 = stmmac_get_time, @@ -319,6 +320,7 @@ const struct ptp_clock_info dwmac1000_ptp_clock_ops = { .n_per_out = 0, .n_pins = 0, .pps = 0, + .supported_extts_flags = PTP_RISING_EDGE | PTP_STRICT_FLAGS, .adjfine = stmmac_adjust_freq, .adjtime = stmmac_adjust_time, .gettime64 = stmmac_get_time, diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c index 49161241d032..a254644bc7b8 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c @@ -1242,6 +1242,9 @@ static int stmmac_reset_tc_mqprio(struct net_device *ndev, { struct stmmac_priv *priv = netdev_priv(ndev); + priv->xmit_qdisc.num_tx_queues = priv->plat->tx_queues_to_use; + priv->xmit_qdisc.enabled = false; + netdev_reset_tc(ndev); netif_set_real_num_tx_queues(ndev, priv->plat->tx_queues_to_use); @@ -1261,6 +1264,15 @@ static int tc_setup_dwmac510_mqprio(struct stmmac_priv *priv, if (!num_tc) return stmmac_reset_tc_mqprio(ndev, extack); + for (u32 tc = 0; tc < num_tc; tc++) { + if (qopt->offset[tc] + qopt->count[tc] > + priv->plat->tx_queues_to_use) { + NL_SET_ERR_MSG_MOD(extack, + "Queues exceed hw TX queues"); + return -EINVAL; + } + } + err = netdev_set_num_tc(ndev, num_tc); if (err) return err; @@ -1268,7 +1280,7 @@ static int tc_setup_dwmac510_mqprio(struct stmmac_priv *priv, for (u32 tc = 0; tc < num_tc; tc++) { offset = qopt->offset[tc]; count = qopt->count[tc]; - num_stack_tx_queues += count; + num_stack_tx_queues = max(num_stack_tx_queues, offset + count); err = netdev_set_tc_queue(ndev, tc, count, offset); if (err) @@ -1284,6 +1296,9 @@ static int tc_setup_dwmac510_mqprio(struct stmmac_priv *priv, if (err) goto err_reset_tc; + priv->xmit_qdisc.num_tx_queues = num_stack_tx_queues; + priv->xmit_qdisc.enabled = true; + return 0; err_reset_tc: diff --git a/drivers/net/ethernet/ti/am65-cpts.c b/drivers/net/ethernet/ti/am65-cpts.c index 73adb822bc07..e87bb01f9aed 100644 --- a/drivers/net/ethernet/ti/am65-cpts.c +++ b/drivers/net/ethernet/ti/am65-cpts.c @@ -176,6 +176,9 @@ struct am65_cpts { struct mutex ptp_clk_lock; /* PHC access sync */ u64 timestamp; u32 genf_enable; + bool genf_neg_adj; + u32 genf_ppm_hi; + u32 genf_ppm_low; u32 hw_ts_enable; u32 estf_enable; struct sk_buff_head txq; @@ -436,9 +439,11 @@ static int am65_cpts_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm) { struct am65_cpts *cpts = container_of(ptp, struct am65_cpts, ptp_info); u32 estf_ctrl_val = 0, estf_ppm_hi = 0, estf_ppm_low = 0; + u32 genf_ctrl_val[AM65_CPTS_GENF_MAX_NUM]; + u32 genf_ppm_hi, genf_ppm_low; s32 ppb = scaled_ppm_to_ppb(scaled_ppm); int pps_index = cpts->pps_genf_idx; - u64 adj_period, pps_adj_period; + u64 adj_period, genf_adj_period; u32 ctrl_val, ppm_hi, ppm_low; unsigned long flags; int neg_adj = 0, i; @@ -470,20 +475,33 @@ static int am65_cpts_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm) ppm_hi = upper_32_bits(adj_period) & 0x3FF; ppm_low = lower_32_bits(adj_period); + /* GenF PPM will do correction using cpts refclk tick which is + * (cpts->ts_add_val + 1) ns, so GenF length PPM adj period + * need to be corrected. + */ + genf_adj_period = adj_period * (cpts->ts_add_val + 1); + genf_ppm_hi = upper_32_bits(genf_adj_period) & 0x3FF; + genf_ppm_low = lower_32_bits(genf_adj_period); + cpts->genf_neg_adj = neg_adj; + cpts->genf_ppm_hi = genf_ppm_hi; + cpts->genf_ppm_low = genf_ppm_low; + + for (i = 0; i < AM65_CPTS_GENF_MAX_NUM; i++) { + if (cpts->genf_enable & BIT(i)) { + genf_ctrl_val[i] = am65_cpts_read32(cpts, + genf[i].control); + if (neg_adj) + genf_ctrl_val[i] &= ~BIT(1); + else + genf_ctrl_val[i] |= BIT(1); + } + } + if (cpts->pps_enabled) { - estf_ctrl_val = am65_cpts_read32(cpts, genf[pps_index].control); - if (neg_adj) - estf_ctrl_val &= ~BIT(1); - else - estf_ctrl_val |= BIT(1); - - /* GenF PPM will do correction using cpts refclk tick which is - * (cpts->ts_add_val + 1) ns, so GenF length PPM adj period - * need to be corrected. - */ - pps_adj_period = adj_period * (cpts->ts_add_val + 1); - estf_ppm_hi = upper_32_bits(pps_adj_period) & 0x3FF; - estf_ppm_low = lower_32_bits(pps_adj_period); + /* am65_cpts_perout_enable_hw() sets pps_index in genf_enable */ + estf_ctrl_val = genf_ctrl_val[pps_index]; + estf_ppm_hi = genf_ppm_hi; + estf_ppm_low = genf_ppm_low; } spin_lock_irqsave(&cpts->lock, flags); @@ -500,10 +518,13 @@ static int am65_cpts_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm) am65_cpts_write32(cpts, ppm_hi, ts_ppm_hi); am65_cpts_write32(cpts, ppm_low, ts_ppm_low); - if (cpts->pps_enabled) { - am65_cpts_write32(cpts, estf_ctrl_val, genf[pps_index].control); - am65_cpts_write32(cpts, estf_ppm_hi, genf[pps_index].ppm_hi); - am65_cpts_write32(cpts, estf_ppm_low, genf[pps_index].ppm_low); + for (i = 0; i < AM65_CPTS_GENF_MAX_NUM; i++) { + if (cpts->genf_enable & BIT(i)) { + am65_cpts_write32(cpts, genf_ctrl_val[i], + genf[i].control); + am65_cpts_write32(cpts, genf_ppm_hi, genf[i].ppm_hi); + am65_cpts_write32(cpts, genf_ppm_low, genf[i].ppm_low); + } } for (i = 0; i < AM65_CPTS_ESTF_MAX_NUM; i++) { @@ -513,7 +534,6 @@ static int am65_cpts_ptp_adjfine(struct ptp_clock_info *ptp, long scaled_ppm) am65_cpts_write32(cpts, estf_ppm_low, estf[i].ppm_low); } } - /* All GenF/EstF can be updated here the same way */ spin_unlock_irqrestore(&cpts->lock, flags); mutex_unlock(&cpts->ptp_clk_lock); @@ -679,9 +699,12 @@ static void am65_cpts_perout_enable_hw(struct am65_cpts *cpts, val = lower_32_bits(cycles); am65_cpts_write32(cpts, val, genf[req->index].length); - am65_cpts_write32(cpts, 0, genf[req->index].control); - am65_cpts_write32(cpts, 0, genf[req->index].ppm_hi); - am65_cpts_write32(cpts, 0, genf[req->index].ppm_low); + am65_cpts_write32(cpts, cpts->genf_neg_adj ? 0 : BIT(1), + genf[req->index].control); + am65_cpts_write32(cpts, cpts->genf_ppm_hi, + genf[req->index].ppm_hi); + am65_cpts_write32(cpts, cpts->genf_ppm_low, + genf[req->index].ppm_low); cpts->genf_enable |= BIT(req->index); } else { diff --git a/drivers/net/gtp.c b/drivers/net/gtp.c index f27d3f891a74..52e68ce50bc8 100644 --- a/drivers/net/gtp.c +++ b/drivers/net/gtp.c @@ -560,16 +560,19 @@ static int gtp0_handle_echo_resp(struct gtp_dev *gtp, struct sk_buff *skb) msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (!msg) - return -ENOMEM; + return -1; ret = gtp_genl_fill_echo(msg, 0, 0, 0, GTP_CMD_ECHOREQ, echo); if (ret < 0) { nlmsg_free(msg); - return ret; + return -1; } - return genlmsg_multicast_netns(>p_genl_family, dev_net(gtp->dev), - msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC); + genlmsg_multicast_netns(>p_genl_family, dev_net(gtp->dev), + msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC); + consume_skb(skb); + + return 0; } static int gtp_proto_to_family(__u16 proto) @@ -747,16 +750,19 @@ static int gtp1u_handle_echo_resp(struct gtp_dev *gtp, struct sk_buff *skb) msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (!msg) - return -ENOMEM; + return -1; ret = gtp_genl_fill_echo(msg, 0, 0, 0, GTP_CMD_ECHOREQ, echo); if (ret < 0) { nlmsg_free(msg); - return ret; + return -1; } - return genlmsg_multicast_netns(>p_genl_family, dev_net(gtp->dev), - msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC); + genlmsg_multicast_netns(>p_genl_family, dev_net(gtp->dev), + msg, 0, GTP_GENL_MCGRP, GFP_ATOMIC); + consume_skb(skb); + + return 0; } static int gtp_parse_exthdrs(struct sk_buff *skb, unsigned int *hdrlen) diff --git a/drivers/net/hamradio/bpqether.c b/drivers/net/hamradio/bpqether.c index f30616d915fd..202bdfc15cc6 100644 --- a/drivers/net/hamradio/bpqether.c +++ b/drivers/net/hamradio/bpqether.c @@ -104,6 +104,7 @@ struct bpqdev { struct net_device *axdev; /* bpq device (bpq#) */ char dest_addr[6]; /* ether destination address */ char acpt_addr[6]; /* accept ether frames from this address only */ + bool reopen; /* closed because the ether device went down */ }; static LIST_HEAD(bpq_devices); @@ -237,12 +238,24 @@ static netdev_tx_t bpq_xmit(struct sk_buff *skb, struct net_device *dev) skb_pull(skb, 1); /* Drop KISS byte */ size = skb->len; + bpq = netdev_priv(dev); + + orig_dev = dev; + dev = bpq_get_ether_dev(dev); + if (!dev) { + orig_dev->stats.tx_dropped++; + kfree_skb(skb); + return NETDEV_TX_OK; + } + /* * We're about to mess with the skb which may still shared with the * generic networking code so unshare and ensure it's got enough - * space for the BPQ headers. + * space for the length bytes and for the link layer header of the + * Ethernet device. That header can be longer than an Ethernet + * header, e.g. on a VLAN device that inserts the tag itself. */ - if (skb_cow(skb, AX25_BPQ_HEADER_LEN)) { + if (skb_cow(skb, LL_RESERVED_SPACE(dev) + 2)) { if (net_ratelimit()) pr_err("bpqether: out of memory\n"); kfree_skb(skb); @@ -255,15 +268,6 @@ static netdev_tx_t bpq_xmit(struct sk_buff *skb, struct net_device *dev) *ptr++ = (size + 5) % 256; *ptr++ = (size + 5) / 256; - bpq = netdev_priv(dev); - - orig_dev = dev; - if ((dev = bpq_get_ether_dev(dev)) == NULL) { - orig_dev->stats.tx_dropped++; - kfree_skb(skb); - return NETDEV_TX_OK; - } - skb->protocol = ax25_type_trans(skb, dev); skb_reset_network_header(skb); dev_hard_header(skb, dev, ETH_P_BPQ, bpq->dest_addr, NULL, 0); @@ -296,8 +300,8 @@ static int bpq_set_mac_address(struct net_device *dev, void *addr) static int bpq_siocdevprivate(struct net_device *dev, struct ifreq *ifr, void __user *data, int cmd) { - struct bpq_ethaddr __user *ethaddr = data; struct bpqdev *bpq = netdev_priv(dev); + struct bpq_ethaddr ethaddr; struct bpq_req req; if (!capable(CAP_NET_ADMIN)) @@ -317,10 +321,10 @@ static int bpq_siocdevprivate(struct net_device *dev, struct ifreq *ifr, break; case SIOCSBPQETHADDR: - if (copy_from_user(bpq->dest_addr, ethaddr->destination, ETH_ALEN)) - return -EFAULT; - if (copy_from_user(bpq->acpt_addr, ethaddr->accept, ETH_ALEN)) + if (copy_from_user(ðaddr, data, sizeof(ethaddr))) return -EFAULT; + memcpy(bpq->dest_addr, ethaddr.destination, ETH_ALEN); + memcpy(bpq->acpt_addr, ethaddr.accept, ETH_ALEN); break; default: @@ -335,6 +339,11 @@ static int bpq_siocdevprivate(struct net_device *dev, struct ifreq *ifr, */ static int bpq_open(struct net_device *dev) { + struct bpqdev *bpq = netdev_priv(dev); + + if (!netif_running(bpq->ethdev)) + return -ENETDOWN; + netif_start_queue(dev); return 0; } @@ -510,6 +519,8 @@ static int bpq_device_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); + struct net_device *axdev; + struct bpqdev *bpq; if (!net_eq(dev_net(dev), &init_net)) return NOTIFY_DONE; @@ -518,14 +529,27 @@ static int bpq_device_event(struct notifier_block *this, return NOTIFY_DONE; switch (event) { - case NETDEV_UP: /* new ethernet device -> new BPQ interface */ - if (bpq_get_ax25_dev(dev) == NULL) + case NETDEV_UP: + axdev = bpq_get_ax25_dev(dev); + if (!axdev) { /* new ethernet device -> new BPQ interface */ bpq_new_device(dev); + break; + } + /* reopen a BPQ interface closed when the device went down */ + bpq = netdev_priv(axdev); + if (bpq->reopen) { + bpq->reopen = false; + dev_open(axdev, NULL); + } break; case NETDEV_DOWN: /* ethernet device closed -> close BPQ interface */ - if ((dev = bpq_get_ax25_dev(dev)) != NULL) - dev_close(dev); + axdev = bpq_get_ax25_dev(dev); + if (axdev && netif_running(axdev)) { + dev_close(axdev); + bpq = netdev_priv(axdev); + bpq->reopen = true; + } break; case NETDEV_UNREGISTER: /* ethernet device removed -> free BPQ interface */ diff --git a/drivers/net/hyperv/rndis_filter.c b/drivers/net/hyperv/rndis_filter.c index c35f9685b6bf..f82832a65463 100644 --- a/drivers/net/hyperv/rndis_filter.c +++ b/drivers/net/hyperv/rndis_filter.c @@ -401,12 +401,12 @@ static inline void *rndis_get_ppi(struct net_device *ndev, /* Validate ppi_offset and ppi_size */ if (ppi->size > len) { netdev_err(ndev, "Invalid ppi size: %u\n", ppi->size); - continue; + return NULL; } if (ppi->ppi_offset >= ppi->size) { netdev_err(ndev, "Invalid ppi_offset: %u\n", ppi->ppi_offset); - continue; + return NULL; } if (ppi->type == type && ppi->internal == internal) { @@ -414,7 +414,7 @@ static inline void *rndis_get_ppi(struct net_device *ndev, if (ppi->size - ppi->ppi_offset < ppi_size) { netdev_err(ndev, "Invalid ppi: size %u ppi_offset %u\n", ppi->size, ppi->ppi_offset); - continue; + return NULL; } return (void *)((ulong)ppi + ppi->ppi_offset); } diff --git a/drivers/net/ipa/ipa_interrupt.c b/drivers/net/ipa/ipa_interrupt.c index 245a06997055..dc5315ce31d3 100644 --- a/drivers/net/ipa/ipa_interrupt.c +++ b/drivers/net/ipa/ipa_interrupt.c @@ -261,10 +261,8 @@ int ipa_interrupt_config(struct ipa *ipa) interrupt->enabled = 0; interrupt->suspend_enabled = bitmap_zalloc(ipa->endpoint_count, GFP_KERNEL); - if (!interrupt->suspend_enabled) { - ret = -ENOMEM; - goto err_kfree; - } + if (!interrupt->suspend_enabled) + return -ENOMEM; /* Disable IPA interrupt types */ reg = ipa_reg(ipa, IPA_IRQ_EN); @@ -290,8 +288,6 @@ int ipa_interrupt_config(struct ipa *ipa) goto err_disable_wakeup; } - ipa->interrupt = interrupt; - return 0; err_disable_wakeup: @@ -300,8 +296,6 @@ int ipa_interrupt_config(struct ipa *ipa) free_irq(interrupt->irq, interrupt); err_free_bitmap: bitmap_free(interrupt->suspend_enabled); -err_kfree: - kfree(interrupt); return ret; } @@ -312,8 +306,6 @@ void ipa_interrupt_deconfig(struct ipa *ipa) struct ipa_interrupt *interrupt = ipa->interrupt; struct device *dev = ipa->dev; - ipa->interrupt = NULL; - dev_pm_clear_wake_irq(dev); (void)device_init_wakeup(dev, false); free_irq(interrupt->irq, interrupt); diff --git a/drivers/net/ipvlan/ipvlan_core.c b/drivers/net/ipvlan/ipvlan_core.c index 6c6677ded82e..18f03d59ea48 100644 --- a/drivers/net/ipvlan/ipvlan_core.c +++ b/drivers/net/ipvlan/ipvlan_core.c @@ -425,7 +425,8 @@ static noinline_for_stack int ipvlan_process_v4_outbound(struct sk_buff *skb) .flowi4_mark = skb->mark, }; - if (!pskb_network_may_pull(skb, sizeof(struct iphdr))) + if (!pskb_network_may_pull(skb, sizeof(struct iphdr)) || + skb_cow_head(skb, 0)) goto err; ip4h = ip_hdr(skb); @@ -491,7 +492,8 @@ static int ipvlan_process_v6_outbound(struct sk_buff *skb) struct net_device *dev = skb->dev; int err, ret = NET_XMIT_DROP; - if (!pskb_network_may_pull(skb, sizeof(struct ipv6hdr))) { + if (!pskb_network_may_pull(skb, sizeof(struct ipv6hdr)) || + skb_cow_head(skb, 0)) { DEV_STATS_INC(dev, tx_errors); kfree_skb(skb); return ret; diff --git a/drivers/net/macsec.c b/drivers/net/macsec.c index 20497bc2bb8c..c05b9e778a27 100644 --- a/drivers/net/macsec.c +++ b/drivers/net/macsec.c @@ -403,8 +403,10 @@ static bool macsec_validate_skb(struct sk_buff *skb, u16 icv_len, bool xpn) int len = skb->len - 2 * ETH_ALEN; int extra_len = macsec_extra_len(!!(h->tci_an & MACSEC_TCI_SC)) + icv_len; - /* a) It comprises at least 17 octets */ - if (skb->len <= 16) + /* a) It comprises at least 17 octets. The SecTAG and ICV must + * also leave a complete Ethernet header. + */ + if (skb->len < ETH_HLEN + extra_len) return false; /* b) MACsec EtherType: already checked */ @@ -1326,9 +1328,12 @@ static rx_handler_result_t macsec_handle_frame(struct sk_buff **pskb) nosci: /* 10.6.1 if the SC is not found */ cbit = !!(hdr->tci_an & MACSEC_TCI_C); - if (!cbit) - macsec_finalize_skb(skb, MACSEC_DEFAULT_ICV_LEN, - macsec_extra_len(macsec_skb_cb(skb)->has_sci)); + if (!cbit) { + len = macsec_extra_len(macsec_skb_cb(skb)->has_sci); + if (skb->len < ETH_HLEN + len + MACSEC_DEFAULT_ICV_LEN) + goto drop_nosc; + macsec_finalize_skb(skb, MACSEC_DEFAULT_ICV_LEN, len); + } list_for_each_entry_rcu(macsec, &rxd->secys, secys) { struct sk_buff *nskb; diff --git a/drivers/net/mctp/mctp-i3c.c b/drivers/net/mctp/mctp-i3c.c index 1d9d0c1418eb..22376ea460f1 100644 --- a/drivers/net/mctp/mctp-i3c.c +++ b/drivers/net/mctp/mctp-i3c.c @@ -111,8 +111,7 @@ static int mctp_i3c_read(struct mctp_i3c_device *mi) mi->mrl + sizeof(struct mctp_i3c_internal_hdr)); if (!skb) { stats->rx_dropped++; - rc = -ENOMEM; - goto err; + return -ENOMEM; } skb->protocol = htons(ETH_P_MCTP); diff --git a/drivers/net/phy/phy-c45.c b/drivers/net/phy/phy-c45.c index d2e36e460cc7..db1ae54c6273 100644 --- a/drivers/net/phy/phy-c45.c +++ b/drivers/net/phy/phy-c45.c @@ -103,6 +103,36 @@ int genphy_c45_pma_baset1_setup_master_slave(struct phy_device *phydev) } EXPORT_SYMBOL_GPL(genphy_c45_pma_baset1_setup_master_slave); +/* Type selection value for the BASE-T1 PMA/PMD control register (1.2100, + * 802.3-2022 Table 45-178) matching the forced speed. 10 Mbit/s is ambiguous + * between 10BASE-T1L and 10BASE-T1S, so the supported link modes decide. + * 2.5G, 5G and 10GBASE-T1 are not handled as there are no link modes for them + * yet. + */ +static int genphy_c45_baset1_type_sel(struct phy_device *phydev) +{ + switch (phydev->speed) { + case SPEED_10: + if (linkmode_test_bit(ETHTOOL_LINK_MODE_10baseT1L_Full_BIT, + phydev->supported)) + return MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_10BT1L; + if (linkmode_test_bit(ETHTOOL_LINK_MODE_10baseT1S_Full_BIT, + phydev->supported) || + linkmode_test_bit(ETHTOOL_LINK_MODE_10baseT1S_Half_BIT, + phydev->supported) || + linkmode_test_bit(ETHTOOL_LINK_MODE_10baseT1S_P2MP_Half_BIT, + phydev->supported)) + return MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_10BT1S; + return -EINVAL; + case SPEED_100: + return MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_100BT1; + case SPEED_1000: + return MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_1000BT1; + default: + return -EINVAL; + } +} + /** * genphy_c45_pma_setup_forced - configures a forced speed * @phydev: target phy_device struct @@ -165,6 +195,16 @@ int genphy_c45_pma_setup_forced(struct phy_device *phydev) return -EINVAL; } + /* Resolve the type before the first write, so a speed without a + * matching type leaves the PHY untouched. + */ + bt1_ctrl = 0; + if (genphy_c45_baset1_able(phydev)) { + bt1_ctrl = genphy_c45_baset1_type_sel(phydev); + if (bt1_ctrl < 0) + return bt1_ctrl; + } + ret = phy_write_mmd(phydev, MDIO_MMD_PMAPMD, MDIO_CTRL1, ctrl1); if (ret < 0) return ret; @@ -178,12 +218,8 @@ int genphy_c45_pma_setup_forced(struct phy_device *phydev) if (ret < 0) return ret; - bt1_ctrl = 0; - if (phydev->speed == SPEED_1000) - bt1_ctrl = MDIO_PMA_PMD_BT1_CTRL_STRAP_B1000; - ret = phy_modify_mmd(phydev, MDIO_MMD_PMAPMD, MDIO_PMA_PMD_BT1_CTRL, - MDIO_PMA_PMD_BT1_CTRL_STRAP, bt1_ctrl); + MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL, bt1_ctrl); if (ret < 0) return ret; } diff --git a/drivers/net/team/team_core.c b/drivers/net/team/team_core.c index 7a189f32c865..f1d45e157efc 100644 --- a/drivers/net/team/team_core.c +++ b/drivers/net/team/team_core.c @@ -1257,11 +1257,8 @@ static int team_port_add(struct team *team, struct net_device *port_dev, /* set allmulti level to new slave */ if (dev->flags & IFF_ALLMULTI) { err = dev_set_allmulti(port_dev, 1); - if (err) { - if (dev->flags & IFF_PROMISC) - dev_set_promiscuity(port_dev, -1); - goto err_set_slave_promisc; - } + if (err) + goto err_set_slave_allmulti; } err = team_dev_type_check_change(dev, port_dev); @@ -1287,6 +1284,11 @@ static int team_port_add(struct team *team, struct net_device *port_dev, return 0; err_set_dev_type: + if (dev->flags & IFF_ALLMULTI) + dev_set_allmulti(port_dev, -1); +err_set_slave_allmulti: + if (dev->flags & IFF_PROMISC) + dev_set_promiscuity(port_dev, -1); err_set_slave_promisc: __team_option_inst_del_port(team, port); diff --git a/drivers/net/tun.c b/drivers/net/tun.c index afb02752b257..b244ae7f4d5e 100644 --- a/drivers/net/tun.c +++ b/drivers/net/tun.c @@ -607,7 +607,7 @@ static void __tun_detach(struct tun_file *tfile, bool clean) } synchronize_net(); - tun_flow_delete_by_queue(tun, tun->numqueues + 1); + tun_flow_delete_by_queue(tun, tun->numqueues); /* Drop read queue */ tun_queue_purge(tfile); tun_set_real_num_queues(tun); @@ -1419,6 +1419,12 @@ static struct sk_buff *tun_napi_alloc_frags(struct tun_file *tfile, if (!skb) return ERR_PTR(-ENOMEM); + /* An skb recycled by napi_reuse_skb() keeps the protocol of a + * previous frame. eth_type_trans() sets it after the virtio + * header checks, which must not see a stale one. + */ + skb->protocol = 0; + linear = iov_iter_single_seg_count(it); err = __skb_grow(skb, linear); if (err) @@ -1824,12 +1830,7 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile, } } - if (tun_vnet_hdr_tnl_to_skb(tun->flags, features, skb, &hdr)) { - atomic_long_inc(&tun->rx_frame_errors); - err = -EINVAL; - goto free_skb; - } - + skb->dev = tun->dev; switch (tun->flags & TUN_TYPE_MASK) { case IFF_TUN: if (tun->flags & IFF_NO_PI) { @@ -1854,9 +1855,8 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile, } } - skb_reset_mac_header(skb); + skb_reset_network_header(skb); skb->protocol = pi.proto; - skb->dev = tun->dev; break; case IFF_TAP: if (!pskb_may_pull(skb, ETH_HLEN)) { @@ -1864,10 +1864,20 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile, drop_reason = SKB_DROP_REASON_HDR_TRUNC; goto drop; } - skb->protocol = eth_type_trans(skb, tun->dev); + skb_set_network_header(skb, ETH_HLEN); break; } + if (tun_vnet_hdr_tnl_to_skb(tun->flags, features, skb, &hdr, + (tun->flags & TUN_TYPE_MASK) == IFF_TAP)) { + atomic_long_inc(&tun->rx_frame_errors); + err = -EINVAL; + goto free_skb; + } + + if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) + skb->protocol = eth_type_trans(skb, tun->dev); + /* copy skb_ubuf_info for callback when skb has no error */ if (zerocopy) { skb_zcopy_init(skb, msg_control); @@ -2481,7 +2491,13 @@ static int tun_xdp_one(struct tun_struct *tun, features = tun_vnet_hdr_guest_features(READ_ONCE(tun->vnet_hdr_sz)); tnl_hdr = (struct virtio_net_hdr_v1_hash_tunnel *)gso; - if (tun_vnet_hdr_tnl_to_skb(tun->flags, features, skb, tnl_hdr)) { + skb->dev = tun->dev; + skb_set_network_header(skb, ETH_HLEN); + /* Frames always start with an Ethernet header here, as the + * eth_type_trans() call below expects. + */ + if (tun_vnet_hdr_tnl_to_skb(tun->flags, features, skb, tnl_hdr, + true)) { atomic_long_inc(&tun->rx_frame_errors); kfree_skb(skb); ret = -EINVAL; @@ -3219,6 +3235,10 @@ static long __tun_chr_ioctl(struct file *file, unsigned int cmd, netif_info(tun, drv, tun->dev, "Linktype set failed because interface is up\n"); ret = -EBUSY; + } else if ((unsigned short)arg == ARPHRD_IEEE802154 || + (unsigned short)arg == ARPHRD_IEEE802154_MONITOR || + (unsigned short)arg == ARPHRD_6LOWPAN) { + ret = -EINVAL; } else { ret = call_netdevice_notifiers(NETDEV_PRE_TYPE_CHANGE, tun->dev); diff --git a/drivers/net/tun_vnet.h b/drivers/net/tun_vnet.h index fa5cab9d3e55..7fff1ae89cac 100644 --- a/drivers/net/tun_vnet.h +++ b/drivers/net/tun_vnet.h @@ -197,9 +197,10 @@ static inline netdev_features_t tun_vnet_hdr_guest_features(int vnet_hdr_sz) static inline int tun_vnet_hdr_tnl_to_skb(unsigned int flags, netdev_features_t features, struct sk_buff *skb, - const struct virtio_net_hdr_v1_hash_tunnel *hdr) + const struct virtio_net_hdr_v1_hash_tunnel *hdr, + bool has_eth) { - return virtio_net_hdr_tnl_to_skb(skb, hdr, + return virtio_net_hdr_tnl_to_skb(skb, hdr, has_eth, features & NETIF_F_GSO_UDP_TUNNEL, features & NETIF_F_GSO_UDP_TUNNEL_CSUM, tun_vnet_is_little_endian(flags)); diff --git a/drivers/net/usb/cdc_ncm.c b/drivers/net/usb/cdc_ncm.c index ca06525892ac..5ecd6d951a35 100644 --- a/drivers/net/usb/cdc_ncm.c +++ b/drivers/net/usb/cdc_ncm.c @@ -1125,7 +1125,7 @@ static struct usb_cdc_ncm_ndp16 *cdc_ncm_ndp16(struct cdc_ncm_ctx *ctx, struct s cdc_ncm_align_tail(skb, ctx->tx_ndp_modulus, 0, ctx->tx_curr_size); /* verify that there is room for the NDP and the datagram (reserve) */ - if ((ctx->tx_curr_size - skb->len - reserve) < ctx->max_ndp_size) + if (skb->len + reserve + ctx->max_ndp_size > ctx->tx_curr_size) return NULL; /* link to it */ @@ -1180,7 +1180,7 @@ static struct usb_cdc_ncm_ndp32 *cdc_ncm_ndp32(struct cdc_ncm_ctx *ctx, struct s cdc_ncm_align_tail(skb, ctx->tx_ndp_modulus, 0, ctx->tx_curr_size); /* verify that there is room for the NDP and the datagram (reserve) */ - if ((ctx->tx_curr_size - skb->len - reserve) < ctx->max_ndp_size) + if (skb->len + reserve + ctx->max_ndp_size > ctx->tx_curr_size) return NULL; /* link to it */ diff --git a/drivers/net/usb/lan78xx.c b/drivers/net/usb/lan78xx.c index 133ea3638814..36fccfdf0659 100644 --- a/drivers/net/usb/lan78xx.c +++ b/drivers/net/usb/lan78xx.c @@ -4594,13 +4594,12 @@ static void lan78xx_disconnect(struct usb_interface *intf) udev = interface_to_usbdev(intf); net = dev->net; + unregister_netdev(net); + rtnl_lock(); - phylink_stop(dev->phylink); phylink_disconnect_phy(dev->phylink); rtnl_unlock(); - unregister_netdev(net); - timer_shutdown_sync(&dev->stat_monitor); set_bit(EVENT_DEV_DISCONNECT, &dev->flags); cancel_delayed_work_sync(&dev->wq); @@ -5377,6 +5376,12 @@ static int lan78xx_resume(struct usb_interface *intf) out: mutex_unlock(&dev->dev_mutex); + if (!ret && dev_open) { + rtnl_lock(); + phylink_resume(dev->phylink); + rtnl_unlock(); + } + return ret; } @@ -5391,15 +5396,7 @@ static int lan78xx_reset_resume(struct usb_interface *intf) if (ret < 0) return ret; - ret = lan78xx_resume(intf); - if (ret < 0) - return ret; - - rtnl_lock(); - phylink_resume(dev->phylink); - rtnl_unlock(); - - return 0; + return lan78xx_resume(intf); } static const struct usb_device_id products[] = { diff --git a/drivers/net/virtio_net.c b/drivers/net/virtio_net.c index ea83313caf36..254f7ff30439 100644 --- a/drivers/net/virtio_net.c +++ b/drivers/net/virtio_net.c @@ -805,19 +805,32 @@ static unsigned int mergeable_ctx_to_truesize(void *mrg_ctx) return (unsigned long)mrg_ctx & ((1 << MRG_CTX_HEADER_SHIFT) - 1); } -static int check_mergeable_len(struct net_device *dev, void *mrg_ctx, - unsigned int len) +/* Length of the mergeable buffer that add_recvbuf_mergeable() posted. */ +static unsigned int mergeable_ctx_to_buflen(void *mrg_ctx) { - unsigned int headroom, tailroom, room, truesize; + unsigned int headroom, tailroom, room; - truesize = mergeable_ctx_to_truesize(mrg_ctx); headroom = mergeable_ctx_to_headroom(mrg_ctx); tailroom = headroom ? sizeof(struct skb_shared_info) : 0; room = SKB_DATA_ALIGN(headroom + tailroom); - if (len > truesize - room) { - pr_debug("%s: rx error: len %u exceeds truesize %lu\n", - dev->name, len, (unsigned long)(truesize - room)); + return mergeable_ctx_to_truesize(mrg_ctx) - room; +} + +/* Length of the small buffer that add_recvbuf_small() posts. */ +static unsigned int small_buflen(const struct virtnet_info *vi) +{ + return vi->hdr_len + GOOD_PACKET_LEN; +} + +static int check_mergeable_len(struct net_device *dev, void *mrg_ctx, + unsigned int len) +{ + unsigned int buflen = mergeable_ctx_to_buflen(mrg_ctx); + + if (len > buflen) { + pr_debug("%s: rx error: len %u exceeds buffer length %u\n", + dev->name, len, buflen); DEV_STATS_INC(dev, rx_length_errors); return -1; } @@ -974,13 +987,25 @@ static void virtnet_rq_unmap(struct receive_queue *rq, void *buf, u32 len) static void *virtnet_rq_get_buf(struct receive_queue *rq, u32 *len, void **ctx) { struct virtnet_info *vi = rq->vq->vdev->priv; + void *buf_ctx; + u32 buflen; void *buf; BUG_ON(vi->big_packets && !vi->mergeable_rx_bufs); - buf = virtqueue_get_buf_ctx(rq->vq, len, ctx); - if (buf) - virtnet_rq_unmap(rq, buf, *len); + buf = virtqueue_get_buf_ctx(rq->vq, len, &buf_ctx); + if (!buf) + return NULL; + + /* The device chooses *len. Sync only the buffer that was posted, so + * that a larger *len cannot copy over the buffers next to it. + */ + buflen = vi->mergeable_rx_bufs ? mergeable_ctx_to_buflen(buf_ctx) : + small_buflen(vi); + virtnet_rq_unmap(rq, buf, min(*len, buflen)); + + if (ctx) + *ctx = buf_ctx; return buf; } @@ -2602,7 +2627,9 @@ static void virtnet_receive_done(struct virtnet_info *vi, struct receive_queue * goto frame_err; } - if (virtio_net_hdr_tnl_to_skb(skb, &hdr->tnl_hdr, vi->rx_tnl, + skb->dev = dev; + skb_set_network_header(skb, ETH_HLEN); + if (virtio_net_hdr_tnl_to_skb(skb, &hdr->tnl_hdr, true, vi->rx_tnl, vi->rx_tnl_csum, virtio_is_little_endian(vi->vdev))) { net_warn_ratelimited("%s: bad gso: type: %x, size: %u, flags %x tunnel %d tnl csum %d\n", @@ -2696,7 +2723,7 @@ static int add_recvbuf_small(struct virtnet_info *vi, struct receive_queue *rq, buf += VIRTNET_RX_PAD + xdp_headroom; - virtnet_rq_init_one_sg(rq, buf, vi->hdr_len + GOOD_PACKET_LEN); + virtnet_rq_init_one_sg(rq, buf, small_buflen(vi)); err = virtqueue_add_inbuf_premapped(rq->vq, rq->sg, 1, buf, ctx, gfp); if (err < 0) { diff --git a/drivers/net/wireless/ath/ath10k/core.c b/drivers/net/wireless/ath/ath10k/core.c index 9ae3595fb698..f57105ad0975 100644 --- a/drivers/net/wireless/ath/ath10k/core.c +++ b/drivers/net/wireless/ath/ath10k/core.c @@ -2986,6 +2986,7 @@ int ath10k_core_start(struct ath10k *ar, enum ath10k_firmware_mode mode, clear_bit(ATH10K_FLAG_CRASH_FLUSH, &ar->dev_flags); ar->running_fw = fw; + ar->thermal.broken = false; if (!test_bit(ATH10K_FW_FEATURE_NON_BMI, ar->running_fw->fw_file.fw_features)) { diff --git a/drivers/net/wireless/ath/ath10k/thermal.c b/drivers/net/wireless/ath/ath10k/thermal.c index 8b15ec07b107..9b81f9ae58d7 100644 --- a/drivers/net/wireless/ath/ath10k/thermal.c +++ b/drivers/net/wireless/ath/ath10k/thermal.c @@ -75,6 +75,12 @@ static ssize_t ath10k_thermal_show_temp(struct device *dev, goto out; } + /* Don't stall every read on firmware that never answers */ + if (ar->thermal.broken) { + ret = -EOPNOTSUPP; + goto out; + } + reinit_completion(&ar->thermal.wmi_sync); ret = ath10k_wmi_pdev_get_temperature(ar); if (ret) { @@ -90,7 +96,8 @@ static ssize_t ath10k_thermal_show_temp(struct device *dev, time_left = wait_for_completion_timeout(&ar->thermal.wmi_sync, ATH10K_THERMAL_SYNC_TIMEOUT_HZ); if (!time_left) { - ath10k_warn(ar, "failed to synchronize thermal read\n"); + ath10k_warn(ar, "failed to synchronize thermal read, not asking again until the firmware restarts\n"); + ar->thermal.broken = true; ret = -ETIMEDOUT; goto out; } diff --git a/drivers/net/wireless/ath/ath10k/thermal.h b/drivers/net/wireless/ath/ath10k/thermal.h index 1f4de9fbf2b3..d1fb5b958c37 100644 --- a/drivers/net/wireless/ath/ath10k/thermal.h +++ b/drivers/net/wireless/ath/ath10k/thermal.h @@ -19,6 +19,8 @@ struct ath10k_thermal { /* protected by conf_mutex */ u32 throttle_state; u32 quiet_period; + /* the running firmware did not answer a temperature request */ + bool broken; /* temperature value in Celsius degree * protected by data_lock */ diff --git a/drivers/net/wireless/ath/ath12k/ahb.c b/drivers/net/wireless/ath/ath12k/ahb.c index af68d5cd6a9d..39cb9901dbd7 100644 --- a/drivers/net/wireless/ath/ath12k/ahb.c +++ b/drivers/net/wireless/ath/ath12k/ahb.c @@ -183,6 +183,26 @@ static void __ath12k_ahb_ext_irq_disable(struct ath12k_base *ab) } } +static void ath12k_ahb_free_napi_for_group(struct ath12k_ext_irq_grp *irq_grp) +{ + netif_napi_del(&irq_grp->napi); + free_netdev(irq_grp->napi_ndev); + irq_grp->napi_ndev = NULL; +} + +static void ath12k_ahb_free_napi(struct ath12k_base *ab, int num_ext_irq_grp) +{ + int i; + + for (i = 0; i < num_ext_irq_grp; i++) + ath12k_ahb_free_napi_for_group(&ab->ext_irq_grp[i]); +} + +static void ath12k_ahb_free_ext_napi(struct ath12k_base *ab) +{ + ath12k_ahb_free_napi(ab, ATH12K_EXT_IRQ_GRP_NUM_MAX); +} + static void ath12k_ahb_ext_grp_enable(struct ath12k_ext_irq_grp *irq_grp) { int i; @@ -537,8 +557,8 @@ static int ath12k_ahb_ext_grp_napi_poll(struct napi_struct *napi, int budget) work_done = ath12k_dp_service_srng(ab, irq_grp, budget); if (work_done < budget) { - napi_complete_done(napi, work_done); - ath12k_ahb_ext_grp_enable(irq_grp); + if (likely(napi_complete_done(napi, work_done))) + ath12k_ahb_ext_grp_enable(irq_grp); } if (work_done > budget) @@ -554,9 +574,10 @@ static irqreturn_t ath12k_ahb_ext_interrupt_handler(int irq, void *arg) /* last interrupt received for this group */ irq_grp->timestamp = jiffies; - ath12k_ahb_ext_grp_disable(irq_grp); - - napi_schedule(&irq_grp->napi); + if (napi_schedule_prep(&irq_grp->napi)) { + ath12k_ahb_ext_grp_disable(irq_grp); + __napi_schedule(&irq_grp->napi); + } return IRQ_HANDLED; } @@ -579,8 +600,10 @@ static int ath12k_ahb_config_ext_irq(struct ath12k_base *ab) irq_grp->grp_id = i; irq_grp->napi_ndev = alloc_netdev_dummy(0); - if (!irq_grp->napi_ndev) - return -ENOMEM; + if (!irq_grp->napi_ndev) { + ret = -ENOMEM; + goto free_napi_ndev; + } netif_napi_add(irq_grp->napi_ndev, &irq_grp->napi, ath12k_ahb_ext_grp_napi_poll); @@ -627,12 +650,19 @@ static int ath12k_ahb_config_ext_irq(struct ath12k_base *ab) ath12k_ahb_ext_interrupt_handler, IRQF_TRIGGER_RISING, irq_name[irq_idx], irq_grp); - if (ret) + if (ret) { ath12k_warn(ab, "failed request_irq for %d\n", irq); + ath12k_ahb_free_napi_for_group(irq_grp); + goto free_napi_ndev; + } } } return 0; + +free_napi_ndev: + ath12k_ahb_free_napi(ab, i); + return ret; } static int ath12k_ahb_config_irq(struct ath12k_base *ab) @@ -1070,11 +1100,14 @@ static int ath12k_ahb_probe(struct platform_device *pdev) ret = ath12k_core_init(ab); if (ret) { ath12k_err(ab, "failed to init core: %d\n", ret); - goto err_rproc_deconfigure; + goto err_free_ext_napi; } return 0; +err_free_ext_napi: + ath12k_ahb_free_ext_napi(ab); + err_rproc_deconfigure: ath12k_ahb_deconfigure_rproc(ab); @@ -1114,6 +1147,7 @@ static void ath12k_ahb_free_resources(struct ath12k_base *ab) { struct platform_device *pdev = ab->pdev; + ath12k_ahb_free_ext_napi(ab); ath12k_hal_srng_deinit(ab); ath12k_ce_free_pipes(ab); ath12k_ahb_resource_deinit(ab); diff --git a/drivers/net/wireless/ath/ath12k/core.c b/drivers/net/wireless/ath/ath12k/core.c index dc969b2516ea..28269f5d77cf 100644 --- a/drivers/net/wireless/ath/ath12k/core.c +++ b/drivers/net/wireless/ath/ath12k/core.c @@ -1468,8 +1468,7 @@ static void ath12k_core_pre_reconfigure_recovery(struct ath12k_base *ab) complete_all(&ar->regd_update_completed); wake_up(&ar->dp.tx_empty_waitq); - idr_for_each(&ar->txmgmt_idr, - ath12k_mac_tx_mgmt_pending_free, ar); + ath12k_mac_tx_mgmt_pending_free(ar); idr_destroy(&ar->txmgmt_idr); wake_up(&ar->txmgmt_empty_waitq); @@ -1944,7 +1943,8 @@ static struct ath12k_hw_group *ath12k_core_hw_group_assign(struct ath12k_base *a goto invalid_group; } - ab->device_id = ag->num_probed++; + ag->num_probed++; + ab->device_id = wsi->index; ag->ab[ab->device_id] = ab; ab->ag = ag; diff --git a/drivers/net/wireless/ath/ath12k/dp_mon.c b/drivers/net/wireless/ath/ath12k/dp_mon.c index 4aaaccca9412..2cb4e0bb0221 100644 --- a/drivers/net/wireless/ath/ath12k/dp_mon.c +++ b/drivers/net/wireless/ath/ath12k/dp_mon.c @@ -1860,24 +1860,23 @@ ath12k_dp_rx_mon_buf_done(struct ath12k_base *ab, struct hal_srng *srng, return DP_MON_STATUS_REPLINISH; } -static u32 ath12k_dp_mon_comp_ppduid(u32 msdu_ppdu_id, u32 *ppdu_id) +static bool ath12k_dp_mon_comp_ppduid(u32 msdu_ppdu_id, u32 *ppdu_id) { - u32 ret = 0; - if ((*ppdu_id < msdu_ppdu_id) && ((msdu_ppdu_id - *ppdu_id) < DP_NOT_PPDU_ID_WRAP_AROUND)) { /* Hold on mon dest ring, and reap mon status ring. */ *ppdu_id = msdu_ppdu_id; - ret = msdu_ppdu_id; - } else if ((*ppdu_id > msdu_ppdu_id) && - ((*ppdu_id - msdu_ppdu_id) > DP_NOT_PPDU_ID_WRAP_AROUND)) { + return true; + } + if ((*ppdu_id > msdu_ppdu_id) && + ((*ppdu_id - msdu_ppdu_id) > DP_NOT_PPDU_ID_WRAP_AROUND)) { /* PPDU ID has exceeded the maximum value and will * restart from 0. */ *ppdu_id = msdu_ppdu_id; - ret = msdu_ppdu_id; + return true; } - return ret; + return false; } static @@ -4130,6 +4129,8 @@ ath12k_dp_rx_mon_mpdu_pop(struct ath12k *ar, int mac_id, if (pmon->mon_last_linkdesc_paddr == paddr) { pmon->rx_mon_stats.dup_mon_linkdesc_cnt++; spin_unlock_bh(&pmon->mon_lock); + kfree_skb_list(*head_msdu); + *head_msdu = NULL; return rx_bufs_used; } @@ -4173,7 +4174,6 @@ ath12k_dp_rx_mon_mpdu_pop(struct ath12k *ar, int mac_id, i, (unsigned long)rxcb->paddr, (unsigned long)msdu_list.paddr[i]); drop_mpdu = true; - continue; } if (!rxcb->unmapped) { dma_unmap_single(ar->ab->dev, rxcb->paddr, @@ -4253,7 +4253,7 @@ ath12k_dp_rx_mon_mpdu_pop(struct ath12k *ar, int mac_id, if (last) last->next = NULL; - *tail_msdu = msdu; + *tail_msdu = last; if (msdu_cnt == 0) *npackets = 1; @@ -4277,7 +4277,6 @@ static void ath12k_dp_rx_mon_dest_process(struct ath12k *ar, int mac_id, struct ath12k_dp *dp = &ar->ab->dp; struct ath12k_base *ab = ar->ab; void *ring_entry, *mon_dst_srng; - struct dp_mon_mpdu *tmp_mpdu; LIST_HEAD(rx_desc_used_list); struct hal_srng *srng; @@ -4340,18 +4339,16 @@ static void ath12k_dp_rx_mon_dest_process(struct ath12k *ar, int mac_id, } if (head_msdu && tail_msdu) { - tmp_mpdu = kzalloc(sizeof(*tmp_mpdu), GFP_ATOMIC); - if (!tmp_mpdu) - break; - - tmp_mpdu->head = head_msdu; - tmp_mpdu->tail = tail_msdu; - tmp_mpdu->err_bitmap = pmon->err_bitmap; - tmp_mpdu->decap_format = pmon->decap_format; - ath12k_dp_mon_rx_deliver(ar, tmp_mpdu, + struct dp_mon_mpdu tmp_mpdu = { + .head = head_msdu, + .tail = tail_msdu, + .err_bitmap = pmon->err_bitmap, + .decap_format = pmon->decap_format, + }; + + ath12k_dp_mon_rx_deliver(ar, &tmp_mpdu, &pmon->mon_ppdu_info, napi); rx_mon_stats->dest_mpdu_done++; - kfree(tmp_mpdu); } ring_entry = ath12k_hal_srng_dst_get_next_entry(ar->ab, @@ -4390,18 +4387,23 @@ __ath12k_dp_mon_process_ring(struct ath12k *ar, int mac_id, goto exit; while ((skb = __skb_dequeue(&skb_list))) { - memset(ppdu_info, 0, sizeof(*ppdu_info)); - ppdu_info->peer_id = HAL_INVALID_PEERID; + if (!ppdu_info->ppdu_continuation) + ath12k_dp_mon_rx_memset_ppdu_info(ppdu_info); hal_status = ath12k_dp_mon_parse_rx_dest(ar, pmon, skb); - if (ar->monitor_started && - pmon->mon_ppdu_status == DP_PPDU_STATUS_START && - hal_status == HAL_TLV_STATUS_PPDU_DONE) { - rx_mon_stats->status_ppdu_done++; - pmon->mon_ppdu_status = DP_PPDU_STATUS_DONE; - ath12k_dp_rx_mon_dest_process(ar, mac_id, *budget, napi); - pmon->mon_ppdu_status = DP_PPDU_STATUS_START; + if (hal_status == HAL_TLV_STATUS_PPDU_DONE) { + ppdu_info->ppdu_continuation = false; + if (ar->monitor_started && + pmon->mon_ppdu_status == DP_PPDU_STATUS_START) { + rx_mon_stats->status_ppdu_done++; + pmon->mon_ppdu_status = DP_PPDU_STATUS_DONE; + ath12k_dp_rx_mon_dest_process(ar, mac_id, + *budget, napi); + pmon->mon_ppdu_status = DP_PPDU_STATUS_START; + } + } else { + ppdu_info->ppdu_continuation = true; } dev_kfree_skb_any(skb); diff --git a/drivers/net/wireless/ath/ath12k/dp_tx.c b/drivers/net/wireless/ath/ath12k/dp_tx.c index abc84ca8467a..ed8c82346608 100644 --- a/drivers/net/wireless/ath/ath12k/dp_tx.c +++ b/drivers/net/wireless/ath/ath12k/dp_tx.c @@ -115,7 +115,7 @@ static void ath12k_hal_tx_cmd_ext_desc_setup(struct ath12k_base *ab, { tcl_ext_cmd->info0 = le32_encode_bits(ti->paddr, HAL_TX_MSDU_EXT_INFO0_BUF_PTR_LO); - tcl_ext_cmd->info1 = le32_encode_bits(0x0, + tcl_ext_cmd->info1 = le32_encode_bits((u64)ti->paddr >> HAL_ADDR_MSB_REG_SHIFT, HAL_TX_MSDU_EXT_INFO1_BUF_PTR_HI) | le32_encode_bits(ti->data_len, HAL_TX_MSDU_EXT_INFO1_BUF_LEN); @@ -667,7 +667,8 @@ ath12k_dp_tx_process_htt_tx_complete(struct ath12k_base *ab, void *desc, wbm_status = le32_get_bits(status_desc->info0, HTT_TX_WBM_COMP_INFO0_STATUS); - ab->device_stats.fw_tx_status[wbm_status]++; + if (likely(wbm_status < MAX_FW_TX_STATUS)) + ab->device_stats.fw_tx_status[wbm_status]++; switch (wbm_status) { case HAL_WBM_REL_HTT_TX_COMP_STATUS_OK: @@ -1071,11 +1072,17 @@ void ath12k_dp_tx_completion_handler(struct ath12k_base *ab, int ring_id) /* Find the HAL_WBM_RELEASE_INFO0_REL_SRC_MODULE value */ buf_rel_source = le32_get_bits(tx_status->info0, HAL_WBM_RELEASE_INFO0_REL_SRC_MODULE); - ab->device_stats.tx_wbm_rel_source[buf_rel_source]++; + if (likely(buf_rel_source < HAL_WBM_REL_SRC_MODULE_MAX)) + ab->device_stats.tx_wbm_rel_source[buf_rel_source]++; + else + WARN_ON_ONCE(1); rel_status = le32_get_bits(tx_status->info0, HAL_WBM_COMPL_TX_INFO0_TQM_RELEASE_REASON); - ab->device_stats.tqm_rel_reason[rel_status]++; + if (likely(rel_status < MAX_TQM_RELEASE_REASON)) + ab->device_stats.tqm_rel_reason[rel_status]++; + else + WARN_ON_ONCE(1); /* Release descriptor as soon as extracting necessary info * to reduce contention diff --git a/drivers/net/wireless/ath/ath12k/mac.c b/drivers/net/wireless/ath/ath12k/mac.c index e10a3366cd84..e644922f17cd 100644 --- a/drivers/net/wireless/ath/ath12k/mac.c +++ b/drivers/net/wireless/ath/ath12k/mac.c @@ -533,6 +533,30 @@ ath12k_mac_max_he_nss(const u16 he_mcs_mask[NL80211_HE_NSS_MAX]) return 1; } +static u32 +ath12k_mac_max_eht_nss(const u16 eht_mcs_mask[NL80211_EHT_NSS_MAX]) +{ + int nss; + + for (nss = NL80211_EHT_NSS_MAX - 1; nss >= 0; nss--) + if (eht_mcs_mask[nss]) + return nss + 1; + + return 1; +} + +static u32 +ath12k_mac_max_eht_mcs_nss(const u8 *eht_mcs, int eht_mcs_set_size) +{ + int i; + u8 nss = 0; + + for (i = 0; i < eht_mcs_set_size; i++) + nss = max(nss, u8_get_bits(eht_mcs[i], IEEE80211_EHT_MCS_NSS_RX)); + + return nss; +} + static u8 ath12k_parse_mpdudensity(u8 mpdudensity) { /* From IEEE Std 802.11-2020 defined values for "Minimum MPDU Start Spacing": @@ -1363,6 +1387,13 @@ static int ath12k_mac_monitor_start(struct ath12k *ar) return ret; } + /* + * A previous monitor session may have stopped mid-PPDU, leaving + * ppdu_continuation set. Clear it so the first status buffer of + * this session is not merged with stale state from before. + */ + ar->dp.mon_data.mon_ppdu_info.ppdu_continuation = false; + ar->monitor_started = true; ar->num_started_vdevs++; @@ -3004,6 +3035,18 @@ static enum wmi_phy_mode ath12k_mac_get_phymode_eht(struct ath12k *ar, return MODE_UNKNOWN; } +static bool +ath12k_peer_assoc_h_eht_masked(const u16 eht_mcs_mask[NL80211_EHT_NSS_MAX]) +{ + int nss; + + for (nss = 0; nss < NL80211_EHT_NSS_MAX; nss++) + if (eht_mcs_mask[nss]) + return false; + + return true; +} + static void ath12k_peer_assoc_h_phymode(struct ath12k *ar, struct ath12k_link_vif *arvif, struct ath12k_link_sta *arsta, @@ -3015,6 +3058,7 @@ static void ath12k_peer_assoc_h_phymode(struct ath12k *ar, const u8 *ht_mcs_mask; const u16 *vht_mcs_mask; const u16 *he_mcs_mask; + const u16 *eht_mcs_mask; enum wmi_phy_mode phymode = MODE_UNKNOWN; lockdep_assert_wiphy(ath12k_ar_to_hw(ar)->wiphy); @@ -3029,6 +3073,7 @@ static void ath12k_peer_assoc_h_phymode(struct ath12k *ar, ht_mcs_mask = arvif->bitrate_mask.control[band].ht_mcs; vht_mcs_mask = arvif->bitrate_mask.control[band].vht_mcs; he_mcs_mask = arvif->bitrate_mask.control[band].he_mcs; + eht_mcs_mask = arvif->bitrate_mask.control[band].eht_mcs; link_sta = ath12k_mac_get_link_sta(arsta); if (!link_sta) { @@ -3039,7 +3084,8 @@ static void ath12k_peer_assoc_h_phymode(struct ath12k *ar, switch (band) { case NL80211_BAND_2GHZ: - if (link_sta->eht_cap.has_eht) { + if (link_sta->eht_cap.has_eht && + !ath12k_peer_assoc_h_eht_masked(eht_mcs_mask)) { if (link_sta->bandwidth == IEEE80211_STA_RX_BW_40) phymode = MODE_11BE_EHT40_2G; else @@ -3102,37 +3148,50 @@ static void ath12k_peer_assoc_h_phymode(struct ath12k *ar, WARN_ON(phymode == MODE_UNKNOWN); } +#define ATH12K_EHT_MCS_7_ENABLED 0x00FF +#define ATH12K_EHT_MCS_9_ENABLED 0x0300 +#define ATH12K_EHT_MCS_11_ENABLED 0x0C00 +#define ATH12K_EHT_MCS_13_ENABLED 0x3000 + static void ath12k_mac_set_eht_mcs(u8 rx_tx_mcs7, u8 rx_tx_mcs9, u8 rx_tx_mcs11, u8 rx_tx_mcs13, - u32 *rx_mcs, u32 *tx_mcs) -{ - *rx_mcs = 0; - u32p_replace_bits(rx_mcs, - u8_get_bits(rx_tx_mcs7, IEEE80211_EHT_MCS_NSS_RX), - WMI_EHT_MCS_NSS_0_7); - u32p_replace_bits(rx_mcs, - u8_get_bits(rx_tx_mcs9, IEEE80211_EHT_MCS_NSS_RX), - WMI_EHT_MCS_NSS_8_9); - u32p_replace_bits(rx_mcs, - u8_get_bits(rx_tx_mcs11, IEEE80211_EHT_MCS_NSS_RX), - WMI_EHT_MCS_NSS_10_11); - u32p_replace_bits(rx_mcs, - u8_get_bits(rx_tx_mcs13, IEEE80211_EHT_MCS_NSS_RX), - WMI_EHT_MCS_NSS_12_13); - - *tx_mcs = 0; - u32p_replace_bits(tx_mcs, - u8_get_bits(rx_tx_mcs7, IEEE80211_EHT_MCS_NSS_TX), - WMI_EHT_MCS_NSS_0_7); - u32p_replace_bits(tx_mcs, - u8_get_bits(rx_tx_mcs9, IEEE80211_EHT_MCS_NSS_TX), - WMI_EHT_MCS_NSS_8_9); - u32p_replace_bits(tx_mcs, - u8_get_bits(rx_tx_mcs11, IEEE80211_EHT_MCS_NSS_TX), - WMI_EHT_MCS_NSS_10_11); - u32p_replace_bits(tx_mcs, - u8_get_bits(rx_tx_mcs13, IEEE80211_EHT_MCS_NSS_TX), - WMI_EHT_MCS_NSS_12_13); + u32 *rx_mcs, u32 *tx_mcs, + const u16 eht_mcs_limit[NL80211_EHT_NSS_MAX]) +{ + int nss; + u8 mcs_7 = 0, mcs_9 = 0, mcs_11 = 0, mcs_13 = 0; + u8 peer_mcs_7, peer_mcs_9, peer_mcs_11, peer_mcs_13; + + for (nss = 0; nss < NL80211_EHT_NSS_MAX; nss++) { + if (eht_mcs_limit[nss] & ATH12K_EHT_MCS_7_ENABLED) + mcs_7++; + if (eht_mcs_limit[nss] & ATH12K_EHT_MCS_9_ENABLED) + mcs_9++; + if (eht_mcs_limit[nss] & ATH12K_EHT_MCS_11_ENABLED) + mcs_11++; + if (eht_mcs_limit[nss] & ATH12K_EHT_MCS_13_ENABLED) + mcs_13++; + } + + peer_mcs_7 = u8_get_bits(rx_tx_mcs7, IEEE80211_EHT_MCS_NSS_RX); + peer_mcs_9 = u8_get_bits(rx_tx_mcs9, IEEE80211_EHT_MCS_NSS_RX); + peer_mcs_11 = u8_get_bits(rx_tx_mcs11, IEEE80211_EHT_MCS_NSS_RX); + peer_mcs_13 = u8_get_bits(rx_tx_mcs13, IEEE80211_EHT_MCS_NSS_RX); + + *rx_mcs = u32_encode_bits(min(peer_mcs_7, mcs_7), WMI_EHT_MCS_NSS_0_7) | + u32_encode_bits(min(peer_mcs_9, mcs_9), WMI_EHT_MCS_NSS_8_9) | + u32_encode_bits(min(peer_mcs_11, mcs_11), WMI_EHT_MCS_NSS_10_11) | + u32_encode_bits(min(peer_mcs_13, mcs_13), WMI_EHT_MCS_NSS_12_13); + + peer_mcs_7 = u8_get_bits(rx_tx_mcs7, IEEE80211_EHT_MCS_NSS_TX); + peer_mcs_9 = u8_get_bits(rx_tx_mcs9, IEEE80211_EHT_MCS_NSS_TX); + peer_mcs_11 = u8_get_bits(rx_tx_mcs11, IEEE80211_EHT_MCS_NSS_TX); + peer_mcs_13 = u8_get_bits(rx_tx_mcs13, IEEE80211_EHT_MCS_NSS_TX); + + *tx_mcs = u32_encode_bits(min(peer_mcs_7, mcs_7), WMI_EHT_MCS_NSS_0_7) | + u32_encode_bits(min(peer_mcs_9, mcs_9), WMI_EHT_MCS_NSS_8_9) | + u32_encode_bits(min(peer_mcs_11, mcs_11), WMI_EHT_MCS_NSS_10_11) | + u32_encode_bits(min(peer_mcs_13, mcs_13), WMI_EHT_MCS_NSS_12_13); } static void ath12k_mac_set_eht_ppe_threshold(const u8 *ppe_thres, @@ -3171,13 +3230,23 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar, struct ath12k_wmi_peer_assoc_arg *arg) { struct ieee80211_sta *sta = ath12k_ahsta_to_sta(arsta->ahsta); + struct ieee80211_vif *vif = ath12k_ahvif_to_vif(arvif->ahvif); + const struct ieee80211_eht_mcs_nss_supp *own_eht_mcs_nss_supp; const struct ieee80211_eht_mcs_nss_supp_20mhz_only *bw_20; + const struct ieee80211_sta_eht_cap *eht_cap, *own_eht_cap; + const struct ieee80211_sband_iftype_data *iftd; const struct ieee80211_eht_mcs_nss_supp_bw *bw; - const struct ieee80211_sta_eht_cap *eht_cap; const struct ieee80211_sta_he_cap *he_cap; struct ieee80211_link_sta *link_sta; struct ieee80211_bss_conf *link_conf; + struct cfg80211_chan_def def; + bool user_rate_valid = true; + enum nl80211_band band; + int eht_nss, nss_idx; u32 *rx_mcs, *tx_mcs; + u16 *eht_mcs_mask; + u8 max_nss = 0; + u8 mcs15; lockdep_assert_wiphy(ath12k_ar_to_hw(ar)->wiphy); @@ -3199,6 +3268,22 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar, if (!he_cap->has_he || !eht_cap->has_eht) return; + if (WARN_ON(ath12k_mac_vif_link_chan(vif, arvif->link_id, &def))) + return; + + band = def.chan->band; + eht_mcs_mask = arvif->bitrate_mask.control[band].eht_mcs; + + iftd = ieee80211_get_sband_iftype_data(&ar->mac.sbands[band], vif->type); + if (!iftd) { + ath12k_warn(ar->ab, + "unable to access iftype_data in struct ieee80211_supported_band\n"); + return; + } + + own_eht_cap = &iftd->eht_cap; + own_eht_mcs_nss_supp = &own_eht_cap->eht_mcs_nss_supp; + arg->eht_flag = true; if ((eht_cap->eht_cap_elem.phy_cap_info[5] & @@ -3212,9 +3297,41 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar, memcpy(arg->peer_eht_cap_phy, eht_cap->eht_cap_elem.phy_cap_info, sizeof(eht_cap->eht_cap_elem.phy_cap_info)); + /* + * Firmware rate control enables EHT-MCS15 based only on the peer's + * MCS15 support bits, so keep only the ones we support ourselves. + */ + mcs15 = u8_get_bits(eht_cap->eht_cap_elem.phy_cap_info[6] & + own_eht_cap->eht_cap_elem.phy_cap_info[6], + IEEE80211_EHT_PHY_CAP6_MCS15_SUPP_MASK); + u8p_replace_bits(&((u8 *)arg->peer_eht_cap_phy)[6], mcs15, + IEEE80211_EHT_PHY_CAP6_MCS15_SUPP_MASK); + rx_mcs = arg->peer_eht_rx_mcs_set; tx_mcs = arg->peer_eht_tx_mcs_set; + eht_nss = ath12k_mac_max_eht_mcs_nss((void *)own_eht_mcs_nss_supp, + sizeof(*own_eht_mcs_nss_supp)); + if (eht_nss > link_sta->rx_nss) { + user_rate_valid = false; + for (nss_idx = (link_sta->rx_nss - 1); nss_idx >= 0; nss_idx--) { + if (eht_mcs_mask[nss_idx]) { + user_rate_valid = true; + break; + } + } + } + + if (!user_rate_valid) { + ath12k_dbg(ar->ab, ATH12K_DBG_MAC, + "Setting eht range MCS value to peer supported nss %d for peer %pM\n", + link_sta->rx_nss, arsta->addr); + eht_mcs_mask[link_sta->rx_nss - 1] = eht_mcs_mask[eht_nss - 1]; + } + + bw_20 = &eht_cap->eht_mcs_nss_supp.only_20mhz; + bw = &eht_cap->eht_mcs_nss_supp.bw._80; + switch (link_sta->bandwidth) { case IEEE80211_STA_RX_BW_320: bw = &eht_cap->eht_mcs_nss_supp.bw._320; @@ -3223,7 +3340,8 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar, bw->rx_tx_mcs11_max_nss, bw->rx_tx_mcs13_max_nss, &rx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_320], - &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_320]); + &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_320], + eht_mcs_mask); arg->peer_eht_mcs_count++; fallthrough; case IEEE80211_STA_RX_BW_160: @@ -3233,15 +3351,15 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar, bw->rx_tx_mcs11_max_nss, bw->rx_tx_mcs13_max_nss, &rx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_160], - &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_160]); + &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_160], + eht_mcs_mask); arg->peer_eht_mcs_count++; fallthrough; default: - if ((he_cap->he_cap_elem.phy_cap_info[0] & - (IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_IN_2G | - IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_80MHZ_IN_5G | - IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_160MHZ_IN_5G | - IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_80PLUS80_MHZ_IN_5G)) == 0) { + if ((vif->type == NL80211_IFTYPE_AP || + vif->type == NL80211_IFTYPE_MESH_POINT) && + !(link_sta->he_cap.he_cap_elem.phy_cap_info[0] & + IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_MASK_ALL)) { bw_20 = &eht_cap->eht_mcs_nss_supp.only_20mhz; ath12k_mac_set_eht_mcs(bw_20->rx_tx_mcs7_max_nss, @@ -3249,7 +3367,8 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar, bw_20->rx_tx_mcs11_max_nss, bw_20->rx_tx_mcs13_max_nss, &rx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_80], - &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_80]); + &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_80], + eht_mcs_mask); } else { bw = &eht_cap->eht_mcs_nss_supp.bw._80; ath12k_mac_set_eht_mcs(bw->rx_tx_mcs9_max_nss, @@ -3257,7 +3376,8 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar, bw->rx_tx_mcs11_max_nss, bw->rx_tx_mcs13_max_nss, &rx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_80], - &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_80]); + &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_80], + eht_mcs_mask); } arg->peer_eht_mcs_count++; @@ -3266,6 +3386,43 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar, arg->punct_bitmap = ~arvif->punct_bitmap; arg->eht_disable_mcs15 = link_conf->eht_disable_mcs15; + + if ((vif->type == NL80211_IFTYPE_AP || + vif->type == NL80211_IFTYPE_MESH_POINT) && + !(link_sta->he_cap.he_cap_elem.phy_cap_info[0] & + IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_MASK_ALL)) { + if (bw_20->rx_tx_mcs13_max_nss) + max_nss = max(max_nss, u8_get_bits(bw_20->rx_tx_mcs13_max_nss, + IEEE80211_EHT_MCS_NSS_RX)); + if (bw_20->rx_tx_mcs11_max_nss) + max_nss = max(max_nss, u8_get_bits(bw_20->rx_tx_mcs11_max_nss, + IEEE80211_EHT_MCS_NSS_RX)); + if (bw_20->rx_tx_mcs9_max_nss) + max_nss = max(max_nss, u8_get_bits(bw_20->rx_tx_mcs9_max_nss, + IEEE80211_EHT_MCS_NSS_RX)); + if (bw_20->rx_tx_mcs7_max_nss) + max_nss = max(max_nss, u8_get_bits(bw_20->rx_tx_mcs7_max_nss, + IEEE80211_EHT_MCS_NSS_RX)); + } else { + if (bw->rx_tx_mcs13_max_nss) + max_nss = max(max_nss, u8_get_bits(bw->rx_tx_mcs13_max_nss, + IEEE80211_EHT_MCS_NSS_RX)); + if (bw->rx_tx_mcs11_max_nss) + max_nss = max(max_nss, u8_get_bits(bw->rx_tx_mcs11_max_nss, + IEEE80211_EHT_MCS_NSS_RX)); + if (bw->rx_tx_mcs9_max_nss) + max_nss = max(max_nss, u8_get_bits(bw->rx_tx_mcs9_max_nss, + IEEE80211_EHT_MCS_NSS_RX)); + } + + max_nss = min(max_nss, (uint8_t)eht_nss); + + arg->peer_nss = min(link_sta->rx_nss, max_nss); + + ath12k_dbg(ar->ab, ATH12K_DBG_MAC, + "mac eht peer %pM nss %d mcs cnt %d ru_punct_bitmap 0x%x\n", + arsta->addr, arg->peer_nss, arg->peer_eht_mcs_count, + arg->punct_bitmap); } static void ath12k_peer_assoc_h_mlo(struct ath12k_link_sta *arsta, @@ -3875,6 +4032,8 @@ static void ath12k_mac_init_arvif(struct ath12k_vif *ahvif, sizeof(arvif->bitrate_mask.control[i].vht_mcs)); memset(arvif->bitrate_mask.control[i].he_mcs, 0xff, sizeof(arvif->bitrate_mask.control[i].he_mcs)); + memset(arvif->bitrate_mask.control[i].eht_mcs, 0xff, + sizeof(arvif->bitrate_mask.control[i].eht_mcs)); } /* Handle MLO related assignments */ @@ -5722,6 +5881,20 @@ ath12k_mac_bitrate_mask_num_he_rates(struct ath12k *ar, return num_rates; } +static int +ath12k_mac_bitrate_mask_num_eht_rates(struct ath12k *ar, + enum nl80211_band band, + const struct cfg80211_bitrate_mask *mask) +{ + int num_rates = 0; + int i; + + for (i = 0; i < ARRAY_SIZE(mask->control[band].eht_mcs); i++) + num_rates += hweight16(mask->control[band].eht_mcs[i]); + + return num_rates; +} + static int ath12k_mac_set_peer_vht_fixed_rate(struct ath12k_link_vif *arvif, struct ath12k_link_sta *arsta, @@ -8307,13 +8480,13 @@ static void ath12k_mac_tx_mgmt_free(struct ath12k *ar, int buf_id) ath12k_mgmt_over_wmi_tx_drop(ar, msdu); } -int ath12k_mac_tx_mgmt_pending_free(int buf_id, void *skb, void *ctx) +void ath12k_mac_tx_mgmt_pending_free(struct ath12k *ar) { - struct ath12k *ar = ctx; - - ath12k_mac_tx_mgmt_free(ar, buf_id); + struct sk_buff *msdu; + int buf_id; - return 0; + idr_for_each_entry(&ar->txmgmt_idr, msdu, buf_id) + ath12k_mac_tx_mgmt_free(ar, buf_id); } static void ath12k_mac_vif_txmgmt_cleanup(struct ath12k *ar, @@ -11925,6 +12098,9 @@ ath12k_mac_has_single_legacy_rate(struct ath12k *ar, if (ath12k_mac_bitrate_mask_num_he_rates(ar, band, mask)) return false; + if (ath12k_mac_bitrate_mask_num_eht_rates(ar, band, mask)) + return false; + return num_rates == 1; } @@ -11947,11 +12123,15 @@ ath12k_mac_bitrate_mask_get_single_nss(struct ath12k *ar, { struct ieee80211_supported_band *sband = &ar->mac.sbands[band]; u16 vht_mcs_map = le16_to_cpu(sband->vht_cap.vht_mcs.tx_mcs_map); + const struct ieee80211_sband_iftype_data *data; const struct ieee80211_sta_he_cap *he_cap; u16 he_mcs_map = 0; + u16 eht_mcs_map = 0; u8 ht_nss_mask = 0; u8 vht_nss_mask = 0; u8 he_nss_mask = 0; + u8 eht_nss_mask = 0; + u8 mcs_nss_len; int i; /* No need to consider legacy here. Basic rates are always present @@ -11995,7 +12175,60 @@ ath12k_mac_bitrate_mask_get_single_nss(struct ath12k *ar, return false; } - if (ht_nss_mask != vht_nss_mask || ht_nss_mask != he_nss_mask) + data = ieee80211_get_sband_iftype_data(sband, vif->type); + + mcs_nss_len = ieee80211_eht_mcs_nss_size(&data->he_cap.he_cap_elem, + &data->eht_cap.eht_cap_elem, + false); + if (mcs_nss_len == 4) { + /* 20 MHz only STA case */ + const struct ieee80211_eht_mcs_nss_supp_20mhz_only *eht_mcs_nss = + &data->eht_cap.eht_mcs_nss_supp.only_20mhz; + if (eht_mcs_nss->rx_tx_mcs13_max_nss) + eht_mcs_map = 0x1fff; + else if (eht_mcs_nss->rx_tx_mcs11_max_nss) + eht_mcs_map = 0x07ff; + else if (eht_mcs_nss->rx_tx_mcs9_max_nss) + eht_mcs_map = 0x01ff; + else + eht_mcs_map = 0x007f; + } else { + const struct ieee80211_eht_mcs_nss_supp_bw *eht_mcs_nss; + + switch (mcs_nss_len) { + case 9: + eht_mcs_nss = &data->eht_cap.eht_mcs_nss_supp.bw._320; + break; + case 6: + eht_mcs_nss = &data->eht_cap.eht_mcs_nss_supp.bw._160; + break; + case 3: + eht_mcs_nss = &data->eht_cap.eht_mcs_nss_supp.bw._80; + break; + default: + return false; + } + + if (eht_mcs_nss->rx_tx_mcs13_max_nss) + eht_mcs_map = 0x1fff; + else if (eht_mcs_nss->rx_tx_mcs11_max_nss) + eht_mcs_map = 0x7ff; + else + eht_mcs_map = 0x1ff; + } + + for (i = 0; i < ARRAY_SIZE(mask->control[band].eht_mcs); i++) { + if (mask->control[band].eht_mcs[i] == 0) + continue; + + if (mask->control[band].eht_mcs[i] < eht_mcs_map) + eht_nss_mask |= BIT(i); + else + return false; + } + + if (ht_nss_mask != vht_nss_mask || ht_nss_mask != he_nss_mask || + ht_nss_mask != eht_nss_mask) return false; if (ht_nss_mask == 0) @@ -12043,55 +12276,57 @@ ath12k_mac_get_single_legacy_rate(struct ath12k *ar, } static int -ath12k_mac_set_fixed_rate_gi_ltf(struct ath12k_link_vif *arvif, u8 he_gi, u8 he_ltf) +ath12k_mac_set_fixed_rate_gi_ltf(struct ath12k_link_vif *arvif, u8 gi, u8 ltf) { struct ath12k *ar = arvif->ar; - int ret; + int param, ret; lockdep_assert_wiphy(ath12k_ar_to_hw(ar)->wiphy); /* 0.8 = 0, 1.6 = 2 and 3.2 = 3. */ - if (he_gi && he_gi != 0xFF) - he_gi += 1; + if (gi && gi != 0xFF) + gi += 1; ret = ath12k_wmi_vdev_set_param_cmd(ar, arvif->vdev_id, - WMI_VDEV_PARAM_SGI, he_gi); + WMI_VDEV_PARAM_SGI, gi); if (ret) { - ath12k_warn(ar->ab, "failed to set HE GI:%d, error:%d\n", - he_gi, ret); + ath12k_warn(ar->ab, "failed to set GI:%d, error:%d\n", + gi, ret); return ret; } /* start from 1 */ - if (he_ltf != 0xFF) - he_ltf += 1; + if (ltf != 0xFF) + ltf += 1; + + param = WMI_VDEV_PARAM_HE_LTF; ret = ath12k_wmi_vdev_set_param_cmd(ar, arvif->vdev_id, - WMI_VDEV_PARAM_HE_LTF, he_ltf); + param, ltf); if (ret) { - ath12k_warn(ar->ab, "failed to set HE LTF:%d, error:%d\n", - he_ltf, ret); + ath12k_warn(ar->ab, "failed to set LTF:%d, error:%d\n", + ltf, ret); return ret; } return 0; } static int -ath12k_mac_set_auto_rate_gi_ltf(struct ath12k_link_vif *arvif, u16 he_gi, u8 he_ltf) +ath12k_mac_set_auto_rate_gi_ltf(struct ath12k_link_vif *arvif, u16 gi, u8 ltf) { struct ath12k *ar = arvif->ar; int ret; - u32 he_ar_gi_ltf; + u32 ar_gi_ltf; - if (he_gi != 0xFF) { - switch (he_gi) { - case NL80211_RATE_INFO_HE_GI_0_8: - he_gi = WMI_AUTORATE_800NS_GI; + if (gi != 0xFF) { + switch (gi) { + case ATH12K_RATE_INFO_GI_0_8: + gi = WMI_AUTORATE_800NS_GI; break; - case NL80211_RATE_INFO_HE_GI_1_6: - he_gi = WMI_AUTORATE_1600NS_GI; + case ATH12K_RATE_INFO_GI_1_6: + gi = WMI_AUTORATE_1600NS_GI; break; - case NL80211_RATE_INFO_HE_GI_3_2: - he_gi = WMI_AUTORATE_3200NS_GI; + case ATH12K_RATE_INFO_GI_3_2: + gi = WMI_AUTORATE_3200NS_GI; break; default: ath12k_warn(ar->ab, "Invalid GI\n"); @@ -12099,16 +12334,16 @@ ath12k_mac_set_auto_rate_gi_ltf(struct ath12k_link_vif *arvif, u16 he_gi, u8 he_ } } - if (he_ltf != 0xFF) { - switch (he_ltf) { - case NL80211_RATE_INFO_HE_1XLTF: - he_ltf = WMI_HE_AUTORATE_LTF_1X; + if (ltf != 0xFF) { + switch (ltf) { + case ATH12K_RATE_INFO_1XLTF: + ltf = WMI_AUTORATE_LTF_1X; break; - case NL80211_RATE_INFO_HE_2XLTF: - he_ltf = WMI_HE_AUTORATE_LTF_2X; + case ATH12K_RATE_INFO_2XLTF: + ltf = WMI_AUTORATE_LTF_2X; break; - case NL80211_RATE_INFO_HE_4XLTF: - he_ltf = WMI_HE_AUTORATE_LTF_4X; + case ATH12K_RATE_INFO_4XLTF: + ltf = WMI_AUTORATE_LTF_4X; break; default: ath12k_warn(ar->ab, "Invalid LTF\n"); @@ -12116,15 +12351,15 @@ ath12k_mac_set_auto_rate_gi_ltf(struct ath12k_link_vif *arvif, u16 he_gi, u8 he_ } } - he_ar_gi_ltf = he_gi | he_ltf; + ar_gi_ltf = gi | ltf; ret = ath12k_wmi_vdev_set_param_cmd(ar, arvif->vdev_id, WMI_VDEV_PARAM_AUTORATE_MISC_CFG, - he_ar_gi_ltf); + ar_gi_ltf); if (ret) { ath12k_warn(ar->ab, - "failed to set HE autorate GI:%u, LTF:%u params, error:%d\n", - he_gi, he_ltf, ret); + "failed to set autorate GI:%u, LTF:%u params, error:%d\n", + gi, ltf, ret); return ret; } @@ -12145,14 +12380,15 @@ static u32 ath12k_mac_nlgi_to_wmigi(enum nl80211_txrate_gi gi) static int ath12k_mac_set_rate_params(struct ath12k_link_vif *arvif, u32 rate, u8 nss, u8 sgi, u8 ldpc, - u8 he_gi, u8 he_ltf, bool he_fixed_rate) + u8 he_gi, u8 he_ltf, bool he_fixed_rate, + bool eht_fixed_rate) { struct ieee80211_bss_conf *link_conf; struct ath12k *ar = arvif->ar; + bool he_support, eht_support, gi_ltf_set = false; u32 vdev_param; u32 param_value; int ret; - bool he_support; lockdep_assert_wiphy(ath12k_ar_to_hw(ar)->wiphy); @@ -12161,6 +12397,7 @@ static int ath12k_mac_set_rate_params(struct ath12k_link_vif *arvif, return -EINVAL; he_support = link_conf->he_support; + eht_support = link_conf->eht_support; ath12k_dbg(ar->ab, ATH12K_DBG_MAC, "mac set rate params vdev %i rate 0x%02x nss 0x%02x sgi 0x%02x ldpc 0x%02x\n", @@ -12170,7 +12407,10 @@ static int ath12k_mac_set_rate_params(struct ath12k_link_vif *arvif, "he_gi 0x%02x he_ltf 0x%02x he_fixed_rate %d\n", he_gi, he_ltf, he_fixed_rate); - if (!he_support) { + ath12k_dbg(ar->ab, ATH12K_DBG_MAC, "eht_fixed_rate %d\n", + eht_fixed_rate); + + if (!he_support && !eht_support) { vdev_param = WMI_VDEV_PARAM_FIXED_RATE; ret = ath12k_wmi_vdev_set_param_cmd(ar, arvif->vdev_id, vdev_param, rate); @@ -12206,7 +12446,10 @@ static int ath12k_mac_set_rate_params(struct ath12k_link_vif *arvif, ret = ath12k_mac_set_auto_rate_gi_ltf(arvif, he_gi, he_ltf); if (ret) return ret; - } else { + gi_ltf_set = true; + } + + if (!gi_ltf_set) { vdev_param = WMI_VDEV_PARAM_SGI; param_value = ath12k_mac_nlgi_to_wmigi(sgi); ret = ath12k_wmi_vdev_set_param_cmd(ar, arvif->vdev_id, @@ -12325,15 +12568,16 @@ ath12k_mac_validate_fixed_rate_settings(struct ath12k *ar, enum nl80211_band ban const struct cfg80211_bitrate_mask *mask, unsigned int link_id) { - bool he_fixed_rate = false, vht_fixed_rate = false; - const u16 *vht_mcs_mask, *he_mcs_mask; + bool eht_fixed_rate = false, he_fixed_rate = false, vht_fixed_rate = false; + const u16 *vht_mcs_mask, *he_mcs_mask, *eht_mcs_mask; struct ieee80211_link_sta *link_sta; struct ath12k_peer *peer, *tmp; - u8 vht_nss, he_nss; + u8 vht_nss, he_nss, eht_nss; int ret = true; vht_mcs_mask = mask->control[band].vht_mcs; he_mcs_mask = mask->control[band].he_mcs; + eht_mcs_mask = mask->control[band].eht_mcs; if (ath12k_mac_bitrate_mask_num_vht_rates(ar, band, mask) == 1) vht_fixed_rate = true; @@ -12341,11 +12585,15 @@ ath12k_mac_validate_fixed_rate_settings(struct ath12k *ar, enum nl80211_band ban if (ath12k_mac_bitrate_mask_num_he_rates(ar, band, mask) == 1) he_fixed_rate = true; - if (!vht_fixed_rate && !he_fixed_rate) + if (ath12k_mac_bitrate_mask_num_eht_rates(ar, band, mask) == 1) + eht_fixed_rate = true; + + if (!vht_fixed_rate && !he_fixed_rate && !eht_fixed_rate) return true; vht_nss = ath12k_mac_max_vht_nss(vht_mcs_mask); he_nss = ath12k_mac_max_he_nss(he_mcs_mask); + eht_nss = ath12k_mac_max_eht_nss(eht_mcs_mask); rcu_read_lock(); spin_lock_bh(&ar->ab->base_lock); @@ -12367,6 +12615,11 @@ ath12k_mac_validate_fixed_rate_settings(struct ath12k *ar, enum nl80211_band ban ret = false; goto exit; } + if (eht_fixed_rate && (!link_sta->eht_cap.has_eht || + link_sta->rx_nss < eht_nss)) { + ret = false; + goto exit; + } } } exit: @@ -12398,6 +12651,7 @@ ath12k_mac_op_set_bitrate_mask(struct ieee80211_hw *hw, int ret; int num_rates; bool he_fixed_rate = false; + bool eht_fixed_rate = false; lockdep_assert_wiphy(hw->wiphy); @@ -12522,7 +12776,7 @@ ath12k_mac_op_set_bitrate_mask(struct ieee80211_hw *hw, } ret = ath12k_mac_set_rate_params(arvif, rate, nss, sgi, ldpc, he_gi, - he_ltf, he_fixed_rate); + he_ltf, he_fixed_rate, eht_fixed_rate); if (ret) { ath12k_warn(ar->ab, "failed to set rate params on vdev %i: %d\n", arvif->vdev_id, ret); @@ -13727,7 +13981,7 @@ static struct wiphy_iftype_ext_capab ath12k_iftypes_ext_capa[] = { static void ath12k_mac_cleanup_unregister(struct ath12k *ar) { - idr_for_each(&ar->txmgmt_idr, ath12k_mac_tx_mgmt_pending_free, ar); + ath12k_mac_tx_mgmt_pending_free(ar); idr_destroy(&ar->txmgmt_idr); kfree(ar->mac.sbands[NL80211_BAND_2GHZ].channels); diff --git a/drivers/net/wireless/ath/ath12k/mac.h b/drivers/net/wireless/ath/ath12k/mac.h index c05af40bd7a2..0d75fae5c7bf 100644 --- a/drivers/net/wireless/ath/ath12k/mac.h +++ b/drivers/net/wireless/ath/ath12k/mac.h @@ -1,7 +1,7 @@ /* SPDX-License-Identifier: BSD-3-Clause-Clear */ /* * Copyright (c) 2018-2021 The Linux Foundation. All rights reserved. - * Copyright (c) 2021-2025 Qualcomm Innovation Center, Inc. All rights reserved. + * Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries. */ #ifndef ATH12K_MAC_H @@ -84,6 +84,18 @@ enum ath12k_supported_bw { ATH12K_BW_320 = 4, }; +enum ath12k_gi { + ATH12K_RATE_INFO_GI_0_8, + ATH12K_RATE_INFO_GI_1_6, + ATH12K_RATE_INFO_GI_3_2, +}; + +enum ath12k_ltf { + ATH12K_RATE_INFO_1XLTF, + ATH12K_RATE_INFO_2XLTF, + ATH12K_RATE_INFO_4XLTF, +}; + struct ath12k_mac_get_any_chanctx_conf_arg { struct ath12k *ar; struct ieee80211_chanctx_conf *chanctx_conf; @@ -160,7 +172,7 @@ struct ath12k *ath12k_mac_get_ar_by_pdev_id(struct ath12k_base *ab, u32 pdev_id) void ath12k_mac_drain_tx(struct ath12k *ar); void ath12k_mac_peer_cleanup_all(struct ath12k *ar); -int ath12k_mac_tx_mgmt_pending_free(int buf_id, void *skb, void *ctx); +void ath12k_mac_tx_mgmt_pending_free(struct ath12k *ar); enum rate_info_bw ath12k_mac_bw_to_mac80211_bw(enum ath12k_supported_bw bw); enum ath12k_supported_bw ath12k_mac_mac80211_bw_to_ath12k_bw(enum rate_info_bw bw); enum hal_encrypt_type ath12k_dp_tx_get_encrypt_type(u32 cipher); diff --git a/drivers/net/wireless/ath/ath12k/wmi.h b/drivers/net/wireless/ath/ath12k/wmi.h index 6468d9738639..fdb17363a65c 100644 --- a/drivers/net/wireless/ath/ath12k/wmi.h +++ b/drivers/net/wireless/ath/ath12k/wmi.h @@ -223,15 +223,15 @@ enum WMI_HOST_WLAN_BAND { }; /* Parameters used for WMI_VDEV_PARAM_AUTORATE_MISC_CFG command. - * Used only for HE auto rate mode. + * Used for HE and EHT auto rate mode. */ enum { - /* HE LTF related configuration */ - WMI_HE_AUTORATE_LTF_1X = BIT(0), - WMI_HE_AUTORATE_LTF_2X = BIT(1), - WMI_HE_AUTORATE_LTF_4X = BIT(2), + /* LTF related configuration */ + WMI_AUTORATE_LTF_1X = BIT(0), + WMI_AUTORATE_LTF_2X = BIT(1), + WMI_AUTORATE_LTF_4X = BIT(2), - /* HE GI related configuration */ + /* GI related configuration */ WMI_AUTORATE_400NS_GI = BIT(8), WMI_AUTORATE_800NS_GI = BIT(9), WMI_AUTORATE_1600NS_GI = BIT(10), diff --git a/drivers/net/wireless/ath/ath9k/htc_drv_main.c b/drivers/net/wireless/ath/ath9k/htc_drv_main.c index 0d6272ac0dac..6578114a4019 100644 --- a/drivers/net/wireless/ath/ath9k/htc_drv_main.c +++ b/drivers/net/wireless/ath/ath9k/htc_drv_main.c @@ -1098,11 +1098,8 @@ static int ath9k_htc_add_interface(struct ieee80211_hw *hw, ath9k_htc_set_opmode(priv); - if ((priv->ah->opmode == NL80211_IFTYPE_AP) && - !test_bit(ATH_OP_ANI_RUN, &common->op_flags)) { + if (priv->ah->opmode == NL80211_IFTYPE_AP) ath9k_hw_set_tsfadjust(priv->ah, true); - ath9k_htc_start_ani(priv); - } ath_dbg(common, CONFIG, "Attach a VIF of type: %d at idx: %d\n", vif->type, avp->index); @@ -1554,6 +1551,9 @@ static void ath9k_htc_bss_info_changed(struct ieee80211_hw *hw, ath9k_htc_set_tsfadjust(priv, vif); priv->cur_beacon_conf.enable_beacon = 1; ath9k_htc_beacon_config(priv, vif); + if (priv->ah->opmode == NL80211_IFTYPE_AP && + !test_bit(ATH_OP_ANI_RUN, &common->op_flags)) + ath9k_htc_start_ani(priv); } if ((changed & BSS_CHANGED_BEACON_ENABLED) && !bss_conf->enable_beacon) { diff --git a/drivers/net/wireless/mediatek/mt76/mt7921/init.c b/drivers/net/wireless/mediatek/mt76/mt7921/init.c index b9098a7331b1..67a3b3dcf60a 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7921/init.c +++ b/drivers/net/wireless/mediatek/mt76/mt7921/init.c @@ -67,7 +67,7 @@ mt7921_regd_channel_update(struct wiphy *wiphy, struct mt792x_dev *dev) (!(dev->phy.clc_chan_conf & BIT(idx)) && (cfreq) >= (sfreq) && (cfreq) <= (efreq)) struct ieee80211_supported_band *sband; struct mt76_dev *mdev = &dev->mt76; - struct device_node *np, *band_np; + struct device_node *np, *band_np, *chan_np; struct ieee80211_channel *ch; int i, cfreq; @@ -79,28 +79,39 @@ mt7921_regd_channel_update(struct wiphy *wiphy, struct mt792x_dev *dev) ch = &sband->channels[i]; cfreq = ch->center_freq; - if (np && (!band_np || !mt76_find_channel_node(band_np, ch))) { - ch->flags |= IEEE80211_CHAN_DISABLED; - continue; + if (np) { + chan_np = band_np ? + mt76_find_channel_node(band_np, ch) : NULL; + of_node_put(chan_np); + if (!chan_np) { + ch->flags |= IEEE80211_CHAN_DISABLED; + continue; + } } /* UNII-4 */ if (IS_UNII_INVALID(0, 5845, 5925)) ch->flags |= IEEE80211_CHAN_DISABLED; } + of_node_put(band_np); sband = wiphy->bands[NL80211_BAND_6GHZ]; if (!sband) - return; + goto out; band_np = np ? of_get_child_by_name(np, "txpower-6g") : NULL; for (i = 0; i < sband->n_channels; i++) { ch = &sband->channels[i]; cfreq = ch->center_freq; - if (np && (!band_np || !mt76_find_channel_node(band_np, ch))) { - ch->flags |= IEEE80211_CHAN_DISABLED; - continue; + if (np) { + chan_np = band_np ? + mt76_find_channel_node(band_np, ch) : NULL; + of_node_put(chan_np); + if (!chan_np) { + ch->flags |= IEEE80211_CHAN_DISABLED; + continue; + } } /* UNII-5/6/7/8 */ @@ -110,6 +121,10 @@ mt7921_regd_channel_update(struct wiphy *wiphy, struct mt792x_dev *dev) IS_UNII_INVALID(4, 6875, 7125)) ch->flags |= IEEE80211_CHAN_DISABLED; } + of_node_put(band_np); + +out: + of_node_put(np); } void mt7921_regd_update(struct mt792x_dev *dev) diff --git a/drivers/net/wireless/mediatek/mt76/mt7921/mcu.c b/drivers/net/wireless/mediatek/mt76/mt7921/mcu.c index 7363a553a007..5e6e3cb4d5e1 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7921/mcu.c +++ b/drivers/net/wireless/mediatek/mt76/mt7921/mcu.c @@ -3,6 +3,7 @@ #include #include +#include #include "mt7921.h" #include "mcu.h" #include "../mt76_connac2_mac.h" @@ -1361,6 +1362,7 @@ int __mt7921_mcu_set_clc(struct mt792x_dev *dev, u8 *alpha2, .acpi_conf = mt792x_acpi_get_flags(&dev->phy), .mtcl_conf = mt792x_acpi_get_mtcl_conf(&dev->phy, alpha2), }; + struct device_node *np; int ret, valid_cnt = 0; u32 buf_len = 0; u8 *pos; @@ -1370,8 +1372,11 @@ int __mt7921_mcu_set_clc(struct mt792x_dev *dev, u8 *alpha2, if (dev->phy.chip_cap & MT792x_CHIP_CAP_CLC_EVT_EN) req.cap |= CLC_CAP_EVT_EN; - if (mt76_find_power_limits_node(&dev->mt76)) + + np = mt76_find_power_limits_node(&dev->mt76); + if (np) req.cap |= CLC_CAP_DTS_EN; + of_node_put(np); buf_len = le32_to_cpu(clc->len) - sizeof(*clc); pos = clc->data; diff --git a/drivers/net/wireless/mediatek/mt76/mt7996/main.c b/drivers/net/wireless/mediatek/mt76/mt7996/main.c index fa0fe117e8f3..02ffd5b1c0ca 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7996/main.c +++ b/drivers/net/wireless/mediatek/mt76/mt7996/main.c @@ -1056,8 +1056,10 @@ mt7996_mac_sta_init_link(struct mt7996_dev *dev, mt7996_sta_init_txq_wcid(sta, idx); } else { msta_link = kzalloc(sizeof(*msta_link), GFP_KERNEL); - if (!msta_link) + if (!msta_link) { + mt76_wcid_mask_clear(dev->mt76.wcid_mask, idx); return -ENOMEM; + } if (msta->seclink_id == msta->deflink_id && (sta->valid_links & ~BIT(msta->deflink_id))) diff --git a/drivers/net/wireless/realtek/rtl8xxxu/core.c b/drivers/net/wireless/realtek/rtl8xxxu/core.c index 0f3f10dbfc54..5ba4a72f86be 100644 --- a/drivers/net/wireless/realtek/rtl8xxxu/core.c +++ b/drivers/net/wireless/realtek/rtl8xxxu/core.c @@ -57,10 +57,12 @@ MODULE_PARM_DESC(dma_agg_pages, "Set DMA aggregation pages (range 1-127, 0 to di #define USB_VENDOR_ID_REALTEK 0x0bda #define RTL8XXXU_RX_URBS 32 #define RTL8XXXU_RX_URB_PENDING_WATER 8 +#define RTL8XXXU_RX_URB_RETRY_DELAY_MS 100 #define RTL8XXXU_TX_URBS 64 #define RTL8XXXU_TX_URB_LOW_WATER 25 #define RTL8XXXU_TX_URB_HIGH_WATER 32 +static void rtl8xxxu_stop(struct ieee80211_hw *hw, bool suspend); static int rtl8xxxu_submit_rx_urb(struct rtl8xxxu_priv *priv, struct rtl8xxxu_rx_urb *rx_urb); @@ -5880,10 +5882,31 @@ static void rtl8xxxu_free_rx_resources(struct rtl8xxxu_priv *priv) spin_unlock_irqrestore(&priv->rx_urb_lock, flags); } +static int rtl8xxxu_alloc_rx_urbs(struct rtl8xxxu_priv *priv) +{ + struct rtl8xxxu_rx_urb *rx_urb; + int i; + + /* No RX work is active until the complete pool has been allocated. */ + for (i = 0; i < RTL8XXXU_RX_URBS; i++) { + rx_urb = kmalloc(sizeof(struct rtl8xxxu_rx_urb), GFP_KERNEL); + if (!rx_urb) + return -ENOMEM; + + usb_init_urb(&rx_urb->urb); + INIT_LIST_HEAD(&rx_urb->list); + rx_urb->hw = priv->hw; + + list_add_tail(&rx_urb->list, &priv->rx_urb_pending_list); + priv->rx_urb_pending_count++; + } + + return 0; +} + static void rtl8xxxu_queue_rx_urb(struct rtl8xxxu_priv *priv, - struct rtl8xxxu_rx_urb *rx_urb) + struct rtl8xxxu_rx_urb *rx_urb, bool defer_schedule) { - struct sk_buff *skb; unsigned long flags; spin_lock_irqsave(&priv->rx_urb_lock, flags); @@ -5891,61 +5914,66 @@ static void rtl8xxxu_queue_rx_urb(struct rtl8xxxu_priv *priv, if (!priv->shutdown) { list_add_tail(&rx_urb->list, &priv->rx_urb_pending_list); priv->rx_urb_pending_count++; - /* - * Arm the worker under rx_urb_lock so this is atomic with the - * shutdown check: moving it out of the lock would let a - * completion arm the work after rtl8xxxu_stop() canceled it. - */ - if (priv->rx_urb_pending_count > RTL8XXXU_RX_URB_PENDING_WATER) - schedule_work(&priv->rx_urb_wq); + /* Serialize scheduling with the shutdown check and cancellation. */ + if (defer_schedule) + schedule_delayed_work(&priv->rx_urb_wq, + msecs_to_jiffies(RTL8XXXU_RX_URB_RETRY_DELAY_MS)); + else if (priv->rx_urb_pending_count > RTL8XXXU_RX_URB_PENDING_WATER) + mod_delayed_work(system_percpu_wq, &priv->rx_urb_wq, 0); } else { - skb = (struct sk_buff *)rx_urb->urb.context; - dev_kfree_skb_irq(skb); usb_free_urb(&rx_urb->urb); } spin_unlock_irqrestore(&priv->rx_urb_lock, flags); } -static void rtl8xxxu_rx_urb_work(struct work_struct *work) +static int rtl8xxxu_submit_rx_urbs(struct rtl8xxxu_priv *priv, bool startup) { - struct rtl8xxxu_priv *priv; struct rtl8xxxu_rx_urb *rx_urb, *tmp; - struct list_head local; unsigned long flags; + LIST_HEAD(local); int ret; - priv = container_of(work, struct rtl8xxxu_priv, rx_urb_wq); - INIT_LIST_HEAD(&local); - spin_lock_irqsave(&priv->rx_urb_lock, flags); - list_splice_init(&priv->rx_urb_pending_list, &local); priv->rx_urb_pending_count = 0; - spin_unlock_irqrestore(&priv->rx_urb_lock, flags); list_for_each_entry_safe(rx_urb, tmp, &local, list) { list_del_init(&rx_urb->list); ret = rtl8xxxu_submit_rx_urb(priv, rx_urb); - /* - * If out of memory or temporary error, put it back on the - * queue and try again. Otherwise the device is dead/gone - * and we should drop it. - */ switch (ret) { case 0: break; case -ENOMEM: case -EAGAIN: - rtl8xxxu_queue_rx_urb(priv, rx_urb); + rtl8xxxu_queue_rx_urb(priv, rx_urb, true); break; default: + usb_free_urb(&rx_urb->urb); + if (startup) + goto free_remaining; dev_warn(&priv->udev->dev, "failed to requeue urb with error %i\n", ret); - usb_free_urb(&rx_urb->urb); } } + + return 0; + +free_remaining: + list_for_each_entry_safe(rx_urb, tmp, &local, list) { + list_del(&rx_urb->list); + usb_free_urb(&rx_urb->urb); + } + return ret; +} + +static void rtl8xxxu_rx_urb_work(struct work_struct *work) +{ + struct rtl8xxxu_priv *priv = container_of(to_delayed_work(work), + struct rtl8xxxu_priv, rx_urb_wq); + + rtl8xxxu_submit_rx_urbs(priv, false); } /* @@ -6599,10 +6627,24 @@ static void rtl8xxxu_rx_complete(struct urb *urb) skb = NULL; rx_urb->urb.context = NULL; - rtl8xxxu_queue_rx_urb(priv, rx_urb); + rtl8xxxu_queue_rx_urb(priv, rx_urb, false); } else { dev_dbg(dev, "%s: status %i\n", __func__, urb->status); - goto cleanup; + + switch (urb->status) { + case -EPROTO: + case -EILSEQ: + case -ETIME: + case -EOVERFLOW: + case -ECOMM: + case -ENOSR: + dev_kfree_skb(skb); + urb->context = NULL; + rtl8xxxu_queue_rx_urb(priv, rx_urb, true); + return; + default: + goto cleanup; + } } return; @@ -7452,7 +7494,6 @@ static void rtl8xxxu_watchdog_callback(struct work_struct *work) static int rtl8xxxu_start(struct ieee80211_hw *hw) { struct rtl8xxxu_priv *priv = hw->priv; - struct rtl8xxxu_rx_urb *rx_urb; struct rtl8xxxu_tx_urb *tx_urb; unsigned long flags; int ret, i; @@ -7467,14 +7508,13 @@ static int rtl8xxxu_start(struct ieee80211_hw *hw) if (priv->usb_interrupts) { ret = rtl8xxxu_submit_int_urb(hw); if (ret) - goto exit; + goto error_out; } for (i = 0; i < RTL8XXXU_TX_URBS; i++) { tx_urb = kmalloc(sizeof(struct rtl8xxxu_tx_urb), GFP_KERNEL); if (!tx_urb) { - if (!i) - ret = -ENOMEM; + ret = -ENOMEM; goto error_out; } @@ -7485,31 +7525,21 @@ static int rtl8xxxu_start(struct ieee80211_hw *hw) priv->tx_urb_free_count++; } + ret = rtl8xxxu_alloc_rx_urbs(priv); + if (ret) + goto error_out; + priv->tx_stopped = false; spin_lock_irqsave(&priv->rx_urb_lock, flags); priv->shutdown = false; spin_unlock_irqrestore(&priv->rx_urb_lock, flags); - for (i = 0; i < RTL8XXXU_RX_URBS; i++) { - rx_urb = kmalloc(sizeof(struct rtl8xxxu_rx_urb), GFP_KERNEL); - if (!rx_urb) { - if (!i) - ret = -ENOMEM; - - goto error_out; - } - usb_init_urb(&rx_urb->urb); - INIT_LIST_HEAD(&rx_urb->list); - rx_urb->hw = hw; - - ret = rtl8xxxu_submit_rx_urb(priv, rx_urb); - if (ret) - rtl8xxxu_queue_rx_urb(priv, rx_urb); - } + ret = rtl8xxxu_submit_rx_urbs(priv, true); + if (ret) + goto error_out; schedule_delayed_work(&priv->ra_watchdog, 2 * HZ); -exit: /* * Accept all data and mgmt frames */ @@ -7522,13 +7552,7 @@ static int rtl8xxxu_start(struct ieee80211_hw *hw) return ret; error_out: - rtl8xxxu_free_tx_resources(priv); - /* - * Disable all data and mgmt frames - */ - rtl8xxxu_write16(priv, REG_RXFLTMAP2, 0x0000); - rtl8xxxu_write16(priv, REG_RXFLTMAP0, 0x0000); - + rtl8xxxu_stop(hw, false); return ret; } @@ -7551,7 +7575,7 @@ static void rtl8xxxu_stop(struct ieee80211_hw *hw, bool suspend) * it drained via rtl8xxxu_submit_rx_urb(), so a worker still running * after the kill could submit a URB that escapes it. */ - cancel_work_sync(&priv->rx_urb_wq); + cancel_delayed_work_sync(&priv->rx_urb_wq); usb_kill_anchored_urbs(&priv->rx_anchor); usb_kill_anchored_urbs(&priv->tx_anchor); @@ -7865,7 +7889,7 @@ static int rtl8xxxu_probe(struct usb_interface *interface, spin_lock_init(&priv->tx_urb_lock); INIT_LIST_HEAD(&priv->rx_urb_pending_list); spin_lock_init(&priv->rx_urb_lock); - INIT_WORK(&priv->rx_urb_wq, rtl8xxxu_rx_urb_work); + INIT_DELAYED_WORK(&priv->rx_urb_wq, rtl8xxxu_rx_urb_work); INIT_DELAYED_WORK(&priv->ra_watchdog, rtl8xxxu_watchdog_callback); INIT_DELAYED_WORK(&priv->update_beacon_work, rtl8xxxu_update_beacon_work_callback); skb_queue_head_init(&priv->c2hcmd_queue); diff --git a/drivers/net/wireless/realtek/rtl8xxxu/rtl8xxxu.h b/drivers/net/wireless/realtek/rtl8xxxu/rtl8xxxu.h index f42463e595cc..c6a4a58a9251 100644 --- a/drivers/net/wireless/realtek/rtl8xxxu/rtl8xxxu.h +++ b/drivers/net/wireless/realtek/rtl8xxxu/rtl8xxxu.h @@ -1803,7 +1803,7 @@ struct rtl8xxxu_priv { struct list_head rx_urb_pending_list; int rx_urb_pending_count; bool shutdown; - struct work_struct rx_urb_wq; + struct delayed_work rx_urb_wq; u8 mac_addr[ETH_ALEN]; char chip_name[8]; diff --git a/drivers/net/wireless/realtek/rtw89/rtw8851bu.c b/drivers/net/wireless/realtek/rtw89/rtw8851bu.c index 10fcfade6151..f9078923bbaa 100644 --- a/drivers/net/wireless/realtek/rtw89/rtw8851bu.c +++ b/drivers/net/wireless/realtek/rtw89/rtw8851bu.c @@ -32,10 +32,16 @@ static const struct usb_device_id rtw_8851bu_id_table[] = { }; MODULE_DEVICE_TABLE(usb, rtw_8851bu_id_table); +static int rtw8851bu_probe(struct usb_interface *intf, + const struct usb_device_id *id) +{ + return rtw89_usb_probe(intf, id, &rtw89_8851bu_info); +} + static struct usb_driver rtw_8851bu_driver = { .name = KBUILD_MODNAME, .id_table = rtw_8851bu_id_table, - .probe = rtw89_usb_probe, + .probe = rtw8851bu_probe, .disconnect = rtw89_usb_disconnect, }; module_usb_driver(rtw_8851bu_driver); diff --git a/drivers/net/wireless/realtek/rtw89/rtw8852bu.c b/drivers/net/wireless/realtek/rtw89/rtw8852bu.c index add5987110b3..fbeb3f5b7375 100644 --- a/drivers/net/wireless/realtek/rtw89/rtw8852bu.c +++ b/drivers/net/wireless/realtek/rtw89/rtw8852bu.c @@ -46,10 +46,16 @@ static const struct usb_device_id rtw_8852bu_id_table[] = { }; MODULE_DEVICE_TABLE(usb, rtw_8852bu_id_table); +static int rtw8852bu_probe(struct usb_interface *intf, + const struct usb_device_id *id) +{ + return rtw89_usb_probe(intf, id, &rtw89_8852bu_info); +} + static struct usb_driver rtw_8852bu_driver = { .name = KBUILD_MODNAME, .id_table = rtw_8852bu_id_table, - .probe = rtw89_usb_probe, + .probe = rtw8852bu_probe, .disconnect = rtw89_usb_disconnect, }; module_usb_driver(rtw_8852bu_driver); diff --git a/drivers/net/wireless/realtek/rtw89/usb.c b/drivers/net/wireless/realtek/rtw89/usb.c index 512a46dd9d06..faf1e471e304 100644 --- a/drivers/net/wireless/realtek/rtw89/usb.c +++ b/drivers/net/wireless/realtek/rtw89/usb.c @@ -931,7 +931,8 @@ static void rtw89_usb_intf_deinit(struct rtw89_dev *rtwdev, } int rtw89_usb_probe(struct usb_interface *intf, - const struct usb_device_id *id) + const struct usb_device_id *id, + const struct rtw89_driver_info *default_info) { const struct rtw89_driver_info *info; struct rtw89_dev *rtwdev; @@ -939,6 +940,8 @@ int rtw89_usb_probe(struct usb_interface *intf, int ret; info = (const struct rtw89_driver_info *)id->driver_info; + if (!info) + info = default_info; rtwdev = rtw89_alloc_ieee80211_hw(&intf->dev, sizeof(struct rtw89_usb), diff --git a/drivers/net/wireless/realtek/rtw89/usb.h b/drivers/net/wireless/realtek/rtw89/usb.h index c1b4bfa20979..fe0f86dc7794 100644 --- a/drivers/net/wireless/realtek/rtw89/usb.h +++ b/drivers/net/wireless/realtek/rtw89/usb.h @@ -59,7 +59,8 @@ static inline struct rtw89_usb *rtw89_usb_priv(struct rtw89_dev *rtwdev) } int rtw89_usb_probe(struct usb_interface *intf, - const struct usb_device_id *id); + const struct usb_device_id *id, + const struct rtw89_driver_info *default_info); void rtw89_usb_disconnect(struct usb_interface *intf); #endif diff --git a/drivers/nvme/common/.kunitconfig b/drivers/nvme/common/.kunitconfig new file mode 100644 index 000000000000..60a038dc9423 --- /dev/null +++ b/drivers/nvme/common/.kunitconfig @@ -0,0 +1,6 @@ +CONFIG_KUNIT=y +CONFIG_PCI=y +CONFIG_BLOCK=y +CONFIG_BLK_DEV_NVME=y +CONFIG_NVME_HOST_AUTH=y +CONFIG_NVME_AUTH_KUNIT_TEST=y diff --git a/drivers/nvme/common/Kconfig b/drivers/nvme/common/Kconfig index da963e4f3f1f..1ec507d1f9b5 100644 --- a/drivers/nvme/common/Kconfig +++ b/drivers/nvme/common/Kconfig @@ -13,3 +13,13 @@ config NVME_AUTH select CRYPTO_DH select CRYPTO_DH_RFC7919_GROUPS select CRYPTO_HKDF + select CRYPTO_LIB_SHA256 + select CRYPTO_LIB_SHA512 + +config NVME_AUTH_KUNIT_TEST + tristate "KUnit tests for NVMe authentication" if !KUNIT_ALL_TESTS + depends on KUNIT && NVME_AUTH + default KUNIT_ALL_TESTS + help + Enable KUnit tests for some of the common code for NVMe over Fabrics + In-Band Authentication. diff --git a/drivers/nvme/common/Makefile b/drivers/nvme/common/Makefile index 681514cf2e2f..fd9d01a60946 100644 --- a/drivers/nvme/common/Makefile +++ b/drivers/nvme/common/Makefile @@ -7,3 +7,5 @@ obj-$(CONFIG_NVME_KEYRING) += nvme-keyring.o nvme-auth-y += auth.o nvme-keyring-y += keyring.o + +obj-$(CONFIG_NVME_AUTH_KUNIT_TEST) += tests/auth_kunit.o diff --git a/drivers/nvme/common/auth.c b/drivers/nvme/common/auth.c index 1f51fbebd9fa..1fdceba737f7 100644 --- a/drivers/nvme/common/auth.c +++ b/drivers/nvme/common/auth.c @@ -12,11 +12,10 @@ #include #include #include +#include #include #include -#define HKDF_MAX_HASHLEN 64 - static u32 nvme_dhchap_seqnum; static DEFINE_MUTEX(nvme_dhchap_mutex); @@ -161,11 +160,10 @@ u32 nvme_auth_key_struct_size(u32 key_len) } EXPORT_SYMBOL_GPL(nvme_auth_key_struct_size); -struct nvme_dhchap_key *nvme_auth_extract_key(unsigned char *secret, - u8 key_hash) +struct nvme_dhchap_key *nvme_auth_extract_key(const char *secret, u8 key_hash) { struct nvme_dhchap_key *key; - unsigned char *p; + const char *p; u32 crc; int ret, key_len; size_t allocated_len = strlen(secret); @@ -183,14 +181,14 @@ struct nvme_dhchap_key *nvme_auth_extract_key(unsigned char *secret, pr_debug("base64 key decoding error %d\n", key_len); ret = key_len; - goto out_free_secret; + goto out_free_key; } if (key_len != 36 && key_len != 52 && key_len != 68) { pr_err("Invalid key len %d\n", key_len); ret = -EINVAL; - goto out_free_secret; + goto out_free_key; } /* The last four bytes is the CRC in little-endian format */ @@ -205,12 +203,12 @@ struct nvme_dhchap_key *nvme_auth_extract_key(unsigned char *secret, pr_err("key crc mismatch (key %08x, crc %08x)\n", get_unaligned_le32(key->key + key_len), crc); ret = -EKEYREJECTED; - goto out_free_secret; + goto out_free_key; } key->len = key_len; key->hash = key_hash; return key; -out_free_secret: +out_free_key: nvme_auth_free_key(key); return ERR_PTR(ret); } @@ -237,8 +235,104 @@ void nvme_auth_free_key(struct nvme_dhchap_key *key) } EXPORT_SYMBOL_GPL(nvme_auth_free_key); +/* + * Start computing an HMAC value, given the algorithm ID and raw key. + * + * The context should be zeroized at the end of its lifetime. The caller can do + * that implicitly by calling nvme_auth_hmac_final(), or explicitly (needed when + * a context is abandoned without finalizing it) by calling memzero_explicit(). + */ +int nvme_auth_hmac_init(struct nvme_auth_hmac_ctx *hmac, u8 hmac_id, + const u8 *key, size_t key_len) +{ + hmac->hmac_id = hmac_id; + switch (hmac_id) { + case NVME_AUTH_HASH_SHA256: + hmac_sha256_init_usingrawkey(&hmac->sha256, key, key_len); + return 0; + case NVME_AUTH_HASH_SHA384: + hmac_sha384_init_usingrawkey(&hmac->sha384, key, key_len); + return 0; + case NVME_AUTH_HASH_SHA512: + hmac_sha512_init_usingrawkey(&hmac->sha512, key, key_len); + return 0; + } + pr_warn("%s: invalid hash algorithm %d\n", __func__, hmac_id); + return -EINVAL; +} +EXPORT_SYMBOL_GPL(nvme_auth_hmac_init); + +void nvme_auth_hmac_update(struct nvme_auth_hmac_ctx *hmac, const u8 *data, + size_t data_len) +{ + switch (hmac->hmac_id) { + case NVME_AUTH_HASH_SHA256: + hmac_sha256_update(&hmac->sha256, data, data_len); + return; + case NVME_AUTH_HASH_SHA384: + hmac_sha384_update(&hmac->sha384, data, data_len); + return; + case NVME_AUTH_HASH_SHA512: + hmac_sha512_update(&hmac->sha512, data, data_len); + return; + } + /* Unreachable because nvme_auth_hmac_init() validated hmac_id */ + WARN_ON_ONCE(1); +} +EXPORT_SYMBOL_GPL(nvme_auth_hmac_update); + +/* Finish computing an HMAC value. Note that this zeroizes the HMAC context. */ +void nvme_auth_hmac_final(struct nvme_auth_hmac_ctx *hmac, u8 *out) +{ + switch (hmac->hmac_id) { + case NVME_AUTH_HASH_SHA256: + hmac_sha256_final(&hmac->sha256, out); + return; + case NVME_AUTH_HASH_SHA384: + hmac_sha384_final(&hmac->sha384, out); + return; + case NVME_AUTH_HASH_SHA512: + hmac_sha512_final(&hmac->sha512, out); + return; + } + /* Unreachable because nvme_auth_hmac_init() validated hmac_id */ + WARN_ON_ONCE(1); +} +EXPORT_SYMBOL_GPL(nvme_auth_hmac_final); + +static int nvme_auth_hmac(u8 hmac_id, const u8 *key, size_t key_len, + const u8 *data, size_t data_len, u8 *out) +{ + struct nvme_auth_hmac_ctx hmac; + int ret; + + ret = nvme_auth_hmac_init(&hmac, hmac_id, key, key_len); + if (ret == 0) { + nvme_auth_hmac_update(&hmac, data, data_len); + nvme_auth_hmac_final(&hmac, out); + } + return ret; +} + +static int nvme_auth_hash(u8 hmac_id, const u8 *data, size_t data_len, u8 *out) +{ + switch (hmac_id) { + case NVME_AUTH_HASH_SHA256: + sha256(data, data_len, out); + return 0; + case NVME_AUTH_HASH_SHA384: + sha384(data, data_len, out); + return 0; + case NVME_AUTH_HASH_SHA512: + sha512(data, data_len, out); + return 0; + } + pr_warn("%s: invalid hash algorithm %d\n", __func__, hmac_id); + return -EINVAL; +} + struct nvme_dhchap_key *nvme_auth_transform_key( - struct nvme_dhchap_key *key, char *nqn) + const struct nvme_dhchap_key *key, const char *nqn) { const char *hmac_name; struct crypto_shash *key_tfm; @@ -304,72 +398,29 @@ struct nvme_dhchap_key *nvme_auth_transform_key( } EXPORT_SYMBOL_GPL(nvme_auth_transform_key); -static int nvme_auth_hash_skey(int hmac_id, u8 *skey, size_t skey_len, u8 *hkey) -{ - const char *digest_name; - struct crypto_shash *tfm; - int ret; - - digest_name = nvme_auth_digest_name(hmac_id); - if (!digest_name) { - pr_debug("%s: failed to get digest for %d\n", __func__, - hmac_id); - return -EINVAL; - } - tfm = crypto_alloc_shash(digest_name, 0, 0); - if (IS_ERR(tfm)) - return -ENOMEM; - - ret = crypto_shash_tfm_digest(tfm, skey, skey_len, hkey); - if (ret < 0) - pr_debug("%s: Failed to hash digest len %zu\n", __func__, - skey_len); - - crypto_free_shash(tfm); - return ret; -} - -int nvme_auth_augmented_challenge(u8 hmac_id, u8 *skey, size_t skey_len, - u8 *challenge, u8 *aug, size_t hlen) +/** + * nvme_auth_augmented_challenge() - Compute the augmented DH-HMAC-CHAP challenge + * @hmac_id: Hash algorithm identifier + * @skey: Session key + * @skey_len: Length of @skey + * @challenge: Challenge value + * @aug: Output buffer for the augmented challenge + * @hlen: Hash output length (length of @challenge and @aug) + * + * NVMe base specification 8.3.5.5.4: The augmented challenge is computed + * applying the HMAC function using the hash function H() selected by the + * HashID parameter ... with the hash of the ephemeral DH key ... as HMAC key + * to the challenge C (i.e., Ca = HMAC(H(g^xy mod p), C)). + * + * As the session key skey is already H(g^xy mod p) per section 8.3.5.5.9, use + * it directly as the HMAC key without additional hashing. + * + * Return: 0 on success, negative errno on failure. + */ +int nvme_auth_augmented_challenge(u8 hmac_id, const u8 *skey, size_t skey_len, + const u8 *challenge, u8 *aug, size_t hlen) { - struct crypto_shash *tfm; - u8 *hashed_key; - const char *hmac_name; - int ret; - - hashed_key = kmalloc(hlen, GFP_KERNEL); - if (!hashed_key) - return -ENOMEM; - - ret = nvme_auth_hash_skey(hmac_id, skey, - skey_len, hashed_key); - if (ret < 0) - goto out_free_key; - - hmac_name = nvme_auth_hmac_name(hmac_id); - if (!hmac_name) { - pr_warn("%s: invalid hash algorithm %d\n", - __func__, hmac_id); - ret = -EINVAL; - goto out_free_key; - } - - tfm = crypto_alloc_shash(hmac_name, 0, 0); - if (IS_ERR(tfm)) { - ret = PTR_ERR(tfm); - goto out_free_key; - } - - ret = crypto_shash_setkey(tfm, hashed_key, hlen); - if (ret) - goto out_free_hash; - - ret = crypto_shash_tfm_digest(tfm, challenge, hlen, aug); -out_free_hash: - crypto_free_shash(tfm); -out_free_key: - kfree_sensitive(hashed_key); - return ret; + return nvme_auth_hmac(hmac_id, skey, skey_len, challenge, hlen, aug); } EXPORT_SYMBOL_GPL(nvme_auth_augmented_challenge); @@ -410,35 +461,78 @@ int nvme_auth_gen_pubkey(struct crypto_kpp *dh_tfm, } EXPORT_SYMBOL_GPL(nvme_auth_gen_pubkey); -int nvme_auth_gen_shared_secret(struct crypto_kpp *dh_tfm, - u8 *ctrl_key, size_t ctrl_key_len, - u8 *sess_key, size_t sess_key_len) +/** + * nvme_auth_gen_session_key() - Generate an ephemeral session key + * @dh_tfm: Diffie-Hellman transform with local private key already set + * @public_key: Peer's public key + * @public_key_len: Length of @public_key + * @sess_key: Output buffer for the session key + * @sess_key_len: Size of @sess_key buffer + * @hash_id: Hash algorithm identifier + * + * NVMe base specification 8.3.5.5.9: The session key Ks shall be computed from + * the ephemeral DH key (i.e., g^xy mod p) ... by applying the hash function + * H() selected by the HashID parameter ... (i.e., Ks = H(g^xy mod p)). + * + * Return: 0 on success, negative errno on failure. + */ +int nvme_auth_gen_session_key(struct crypto_kpp *dh_tfm, + const u8 *public_key, size_t public_key_len, + u8 *sess_key, size_t sess_key_len, u8 hash_id) { struct kpp_request *req; struct crypto_wait wait; struct scatterlist src, dst; + u8 *dh_secret; + size_t dh_secret_len, hash_len; int ret; - req = kpp_request_alloc(dh_tfm, GFP_KERNEL); - if (!req) + hash_len = nvme_auth_hmac_hash_len(hash_id); + if (!hash_len) { + pr_warn("%s: invalid hash algorithm %d\n", __func__, hash_id); + return -EINVAL; + } + + if (sess_key_len != hash_len) { + pr_warn("%s: sess_key buffer missized (%zu != %zu)\n", + __func__, sess_key_len, hash_len); + return -EINVAL; + } + + dh_secret_len = crypto_kpp_maxsize(dh_tfm); + dh_secret = kzalloc(dh_secret_len, GFP_KERNEL); + if (!dh_secret) return -ENOMEM; + req = kpp_request_alloc(dh_tfm, GFP_KERNEL); + if (!req) { + ret = -ENOMEM; + goto out_free_secret; + } + crypto_init_wait(&wait); - sg_init_one(&src, ctrl_key, ctrl_key_len); - kpp_request_set_input(req, &src, ctrl_key_len); - sg_init_one(&dst, sess_key, sess_key_len); - kpp_request_set_output(req, &dst, sess_key_len); + sg_init_one(&src, public_key, public_key_len); + kpp_request_set_input(req, &src, public_key_len); + sg_init_one(&dst, dh_secret, dh_secret_len); + kpp_request_set_output(req, &dst, dh_secret_len); kpp_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG, crypto_req_done, &wait); ret = crypto_wait_req(crypto_kpp_compute_shared_secret(req), &wait); - kpp_request_free(req); + + if (ret) + goto out_free_secret; + + ret = nvme_auth_hash(hash_id, dh_secret, dh_secret_len, sess_key); + +out_free_secret: + kfree_sensitive(dh_secret); return ret; } -EXPORT_SYMBOL_GPL(nvme_auth_gen_shared_secret); +EXPORT_SYMBOL_GPL(nvme_auth_gen_session_key); -int nvme_auth_generate_key(u8 *secret, struct nvme_dhchap_key **ret_key) +int nvme_auth_generate_key(const char *secret, struct nvme_dhchap_key **ret_key) { struct nvme_dhchap_key *key; u8 key_hash; @@ -486,8 +580,9 @@ EXPORT_SYMBOL_GPL(nvme_auth_generate_key); * Returns 0 on success with a valid generated PSK pointer in @ret_psk and * the length of @ret_psk in @ret_len, or a negative error number otherwise. */ -int nvme_auth_generate_psk(u8 hmac_id, u8 *skey, size_t skey_len, - u8 *c1, u8 *c2, size_t hash_len, u8 **ret_psk, size_t *ret_len) +int nvme_auth_generate_psk(u8 hmac_id, const u8 *skey, size_t skey_len, + const u8 *c1, const u8 *c2, size_t hash_len, + u8 **ret_psk, size_t *ret_len) { struct crypto_shash *tfm; SHASH_DESC_ON_STACK(shash, tfm); @@ -584,12 +679,14 @@ EXPORT_SYMBOL_GPL(nvme_auth_generate_psk); * Returns 0 on success with a valid digest pointer in @ret_digest, or a * negative error number on failure. */ -int nvme_auth_generate_digest(u8 hmac_id, u8 *psk, size_t psk_len, - char *subsysnqn, char *hostnqn, u8 **ret_digest) +int nvme_auth_generate_digest(u8 hmac_id, const u8 *psk, size_t psk_len, + const char *subsysnqn, const char *hostnqn, + char **ret_digest) { struct crypto_shash *tfm; SHASH_DESC_ON_STACK(shash, tfm); - u8 *digest, *enc; + u8 *digest; + char *enc; const char *hmac_name; size_t digest_len, hmac_len; int ret; @@ -763,16 +860,16 @@ static int hkdf_expand_label(struct crypto_shash *hmac_tfm, * Returns 0 on success with a valid psk pointer in @ret_psk or a negative * error number otherwise. */ -int nvme_auth_derive_tls_psk(int hmac_id, u8 *psk, size_t psk_len, - u8 *psk_digest, u8 **ret_psk) +int nvme_auth_derive_tls_psk(int hmac_id, const u8 *psk, size_t psk_len, + const char *psk_digest, u8 **ret_psk) { struct crypto_shash *hmac_tfm; const char *hmac_name; const char *label = "nvme-tls-psk"; - static const char default_salt[HKDF_MAX_HASHLEN]; + static const u8 default_salt[NVME_AUTH_MAX_DIGEST_SIZE]; size_t prk_len; const char *ctx; - unsigned char *prk, *tls_key; + u8 *prk, *tls_key; int ret; hmac_name = nvme_auth_hmac_name(hmac_id); @@ -798,7 +895,7 @@ int nvme_auth_derive_tls_psk(int hmac_id, u8 *psk, size_t psk_len, goto out_free_shash; } - if (WARN_ON(prk_len > HKDF_MAX_HASHLEN)) { + if (WARN_ON(prk_len > NVME_AUTH_MAX_DIGEST_SIZE)) { ret = -EINVAL; goto out_free_prk; } diff --git a/drivers/nvme/common/tests/auth_kunit.c b/drivers/nvme/common/tests/auth_kunit.c new file mode 100644 index 000000000000..28b8dd1e3b18 --- /dev/null +++ b/drivers/nvme/common/tests/auth_kunit.c @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Unit tests for NVMe authentication functions + * + * Copyright 2026 Google LLC + */ + +#include +#include +#include +#include +#include + +struct nvme_auth_test_values { + u8 hmac_id; + size_t hash_len; + u8 expected_psk[NVME_AUTH_MAX_DIGEST_SIZE]; + char *expected_psk_digest; + u8 expected_tls_psk[NVME_AUTH_MAX_DIGEST_SIZE]; +}; + +static void kfree_action(void *ptr) +{ + kfree(ptr); +} + +static void kunit_add_kfree_action(struct kunit *test, void *ptr) +{ + KUNIT_ASSERT_EQ(test, 0, + kunit_add_action_or_reset(test, kfree_action, ptr)); +} + +/* + * Test the derivation of a TLS PSK from the initial skey. The vals parameter + * gives the expected value of tls_psk as well as the intermediate values psk + * and psk_digest. The inputs are implicitly the fixed values set below. + */ +static void +test_nvme_auth_derive_tls_psk(struct kunit *test, + const struct nvme_auth_test_values *vals) +{ + const u8 hmac_id = vals->hmac_id; + const size_t hash_len = vals->hash_len; + const size_t skey_len = hash_len; + u8 skey[NVME_AUTH_MAX_DIGEST_SIZE]; + u8 c1[NVME_AUTH_MAX_DIGEST_SIZE]; + u8 c2[NVME_AUTH_MAX_DIGEST_SIZE]; + const char *subsysnqn = "subsysnqn"; + const char *hostnqn = "hostnqn"; + u8 *psk = NULL, *tls_psk = NULL; + char *psk_digest = NULL; + size_t psk_len; + int ret; + + for (int i = 0; i < NVME_AUTH_MAX_DIGEST_SIZE; i++) { + skey[i] = 'A' + i; + c1[i] = i; + c2[i] = 0xff - i; + } + + ret = nvme_auth_generate_psk(hmac_id, skey, skey_len, c1, c2, hash_len, + &psk, &psk_len); + kunit_add_kfree_action(test, psk); + KUNIT_ASSERT_EQ(test, 0, ret); + KUNIT_ASSERT_EQ(test, hash_len, psk_len); + KUNIT_ASSERT_MEMEQ(test, vals->expected_psk, psk, psk_len); + + ret = nvme_auth_generate_digest(hmac_id, psk, psk_len, subsysnqn, + hostnqn, &psk_digest); + kunit_add_kfree_action(test, psk_digest); + if (vals->expected_psk_digest == NULL) { + /* + * Algorithm has an ID assigned but is not supported by + * nvme_auth_generate_digest(). + */ + KUNIT_ASSERT_EQ(test, -EINVAL, ret); + return; + } + KUNIT_ASSERT_EQ(test, 0, ret); + KUNIT_ASSERT_STREQ(test, vals->expected_psk_digest, psk_digest); + + ret = nvme_auth_derive_tls_psk(hmac_id, psk, psk_len, psk_digest, + &tls_psk); + kunit_add_kfree_action(test, tls_psk); + KUNIT_ASSERT_EQ(test, 0, ret); + KUNIT_ASSERT_MEMEQ(test, vals->expected_tls_psk, tls_psk, psk_len); +} + +static void test_nvme_auth_derive_tls_psk_hmac_sha256(struct kunit *test) +{ + static const struct nvme_auth_test_values vals = { + .hmac_id = NVME_AUTH_HASH_SHA256, + .hash_len = SHA256_DIGEST_SIZE, + .expected_psk = { + 0x17, 0x33, 0xc5, 0x9f, 0xa7, 0xf4, 0x8f, 0xcf, + 0x37, 0xf5, 0xf2, 0x6f, 0xc4, 0xff, 0x02, 0x68, + 0xad, 0x4f, 0x78, 0xe0, 0x30, 0xf4, 0xf3, 0xb0, + 0xbf, 0xd1, 0xd4, 0x7e, 0x7b, 0xb1, 0x44, 0x7a, + }, + .expected_psk_digest = "OldoKuTfKddMuyCznAZojkWD7P4D9/AtzDzLimtOxqI=", + .expected_tls_psk = { + 0x3c, 0x17, 0xda, 0x62, 0x84, 0x74, 0xa0, 0x4d, + 0x22, 0x47, 0xc4, 0xca, 0xb4, 0x79, 0x68, 0xc9, + 0x15, 0x38, 0x81, 0x93, 0xf7, 0xc0, 0x71, 0xbd, + 0x94, 0x89, 0xcc, 0x36, 0x66, 0xcd, 0x7c, 0xc8, + }, + }; + + test_nvme_auth_derive_tls_psk(test, &vals); +} + +static void test_nvme_auth_derive_tls_psk_hmac_sha384(struct kunit *test) +{ + static const struct nvme_auth_test_values vals = { + .hmac_id = NVME_AUTH_HASH_SHA384, + .hash_len = SHA384_DIGEST_SIZE, + .expected_psk = { + 0xf1, 0x4b, 0x2d, 0xd3, 0x23, 0x4c, 0x45, 0x96, + 0x94, 0xd3, 0xbc, 0x63, 0xf8, 0x96, 0x8b, 0xd6, + 0xb3, 0x7c, 0x2c, 0x6d, 0xe8, 0x49, 0xe2, 0x2e, + 0x11, 0x87, 0x49, 0x00, 0x1c, 0xe4, 0xbb, 0xe8, + 0x64, 0x0b, 0x9e, 0x3a, 0x74, 0x8c, 0xb1, 0x1c, + 0xe4, 0xb1, 0xd7, 0x1d, 0x35, 0x9c, 0xce, 0x39, + }, + .expected_psk_digest = "cffMWk8TSS7HOQebjgYEIkrPrjWPV4JE5cdPB8WhEvY4JBW5YynKyv66XscN4A9n", + .expected_tls_psk = { + 0x27, 0x74, 0x75, 0x32, 0x33, 0x53, 0x7b, 0x3f, + 0xa5, 0x0e, 0xb7, 0xd1, 0x6a, 0x8e, 0x43, 0x45, + 0x7d, 0x85, 0xf4, 0x90, 0x6c, 0x00, 0x5b, 0x22, + 0x36, 0x61, 0x6c, 0x5d, 0x80, 0x93, 0x9d, 0x08, + 0x98, 0xff, 0xf1, 0x5b, 0xb8, 0xb7, 0x71, 0x19, + 0xd2, 0xbe, 0x0a, 0xac, 0x42, 0x3e, 0x75, 0x90, + }, + }; + + test_nvme_auth_derive_tls_psk(test, &vals); +} + +static void test_nvme_auth_derive_tls_psk_hmac_sha512(struct kunit *test) +{ + static const struct nvme_auth_test_values vals = { + .hmac_id = NVME_AUTH_HASH_SHA512, + .hash_len = SHA512_DIGEST_SIZE, + .expected_psk = { + 0x9c, 0x9f, 0x08, 0x9a, 0x61, 0x8b, 0x47, 0xd2, + 0xd7, 0x5f, 0x4b, 0x6c, 0x28, 0x07, 0x04, 0x24, + 0x48, 0x7b, 0x44, 0x5d, 0xd9, 0x6e, 0x70, 0xc4, + 0xc0, 0x9b, 0x55, 0xe8, 0xb6, 0x00, 0x01, 0x52, + 0xa3, 0x36, 0x3c, 0x34, 0x54, 0x04, 0x3f, 0x38, + 0xf0, 0xb8, 0x50, 0x36, 0xde, 0xd4, 0x06, 0x55, + 0x35, 0x0a, 0xa8, 0x7b, 0x8b, 0x6a, 0x28, 0x2b, + 0x5c, 0x1a, 0xca, 0xe1, 0x62, 0x33, 0xdd, 0x5b, + }, + /* nvme_auth_generate_digest() doesn't support SHA-512 yet. */ + .expected_psk_digest = NULL, + }; + + test_nvme_auth_derive_tls_psk(test, &vals); +} + +static struct kunit_case nvme_auth_test_cases[] = { + KUNIT_CASE(test_nvme_auth_derive_tls_psk_hmac_sha256), + KUNIT_CASE(test_nvme_auth_derive_tls_psk_hmac_sha384), + KUNIT_CASE(test_nvme_auth_derive_tls_psk_hmac_sha512), + {}, +}; + +static struct kunit_suite nvme_auth_test_suite = { + .name = "nvme-auth", + .test_cases = nvme_auth_test_cases, +}; +kunit_test_suite(nvme_auth_test_suite); + +MODULE_DESCRIPTION("Unit tests for NVMe authentication functions"); +MODULE_LICENSE("GPL"); diff --git a/drivers/nvme/host/auth.c b/drivers/nvme/host/auth.c index 38506314248f..a64ca50e925f 100644 --- a/drivers/nvme/host/auth.c +++ b/drivers/nvme/host/auth.c @@ -39,9 +39,9 @@ struct nvme_dhchap_queue_context { u8 hash_id; u8 sc_c; size_t hash_len; - u8 c1[64]; - u8 c2[64]; - u8 response[64]; + u8 c1[NVME_AUTH_MAX_DIGEST_SIZE]; + u8 c2[NVME_AUTH_MAX_DIGEST_SIZE]; + u8 response[NVME_AUTH_MAX_DIGEST_SIZE]; u8 *ctrl_key; u8 *host_key; u8 *sess_key; @@ -652,7 +652,7 @@ static int nvme_auth_dhchap_exponential(struct nvme_ctrl *ctrl, } gen_sesskey: - chap->sess_key_len = chap->host_key_len; + chap->sess_key_len = chap->hash_len; chap->sess_key = kmalloc(chap->sess_key_len, GFP_KERNEL); if (!chap->sess_key) { chap->sess_key_len = 0; @@ -660,16 +660,17 @@ static int nvme_auth_dhchap_exponential(struct nvme_ctrl *ctrl, return -ENOMEM; } - ret = nvme_auth_gen_shared_secret(chap->dh_tfm, - chap->ctrl_key, chap->ctrl_key_len, - chap->sess_key, chap->sess_key_len); + ret = nvme_auth_gen_session_key(chap->dh_tfm, + chap->ctrl_key, chap->ctrl_key_len, + chap->sess_key, chap->sess_key_len, + chap->hash_id); if (ret) { dev_dbg(ctrl->device, - "failed to generate shared secret, error %d\n", ret); + "failed to generate session key, error %d\n", ret); chap->status = NVME_AUTH_DHCHAP_FAILURE_INCORRECT_PAYLOAD; return ret; } - dev_dbg(ctrl->device, "shared secret %*ph\n", + dev_dbg(ctrl->device, "session key %*ph\n", (int)chap->sess_key_len, chap->sess_key); return 0; } @@ -722,7 +723,8 @@ EXPORT_SYMBOL_GPL(nvme_auth_revoke_tls_key); static int nvme_auth_secure_concat(struct nvme_ctrl *ctrl, struct nvme_dhchap_queue_context *chap) { - u8 *psk, *digest, *tls_psk; + u8 *psk, *tls_psk; + char *digest; struct key *tls_key; size_t psk_len; int ret = 0; diff --git a/drivers/nvme/host/core.c b/drivers/nvme/host/core.c index f822547be6e2..b034866abc53 100644 --- a/drivers/nvme/host/core.c +++ b/drivers/nvme/host/core.c @@ -3317,7 +3317,11 @@ static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id) return 0; out_put_subsystem: + if (!found) + list_del_init(&subsys->entry); + mutex_unlock(&nvme_subsystems_lock); nvme_put_subsystem(subsys); + return ret; out_unlock: mutex_unlock(&nvme_subsystems_lock); return ret; diff --git a/drivers/nvme/host/tcp.c b/drivers/nvme/host/tcp.c index 72afdd73939f..e25cc8e55cf4 100644 --- a/drivers/nvme/host/tcp.c +++ b/drivers/nvme/host/tcp.c @@ -154,6 +154,9 @@ enum nvme_tcp_queue_flags { NVME_TCP_Q_IO_CPU_SET = 3, }; +#define NVME_TCP_OPT_NR_QUEUES(opts) ((opts)->nr_io_queues + \ + (opts)->nr_write_queues + (opts)->nr_poll_queues + 1) + enum nvme_tcp_recv_state { NVME_TCP_RECV_PDU = 0, NVME_TCP_RECV_DATA, @@ -221,6 +224,7 @@ struct nvme_tcp_ctrl { struct delayed_work connect_work; struct nvme_tcp_request async_req; u32 io_queues[HCTX_MAX_TYPES]; + unsigned int nr_allocated_queues; struct net *net; }; @@ -1547,14 +1551,22 @@ static void nvme_tcp_free_queue(struct nvme_ctrl *nctrl, int qid) page_frag_cache_drain(&queue->pf_cache); noreclaim_flag = memalloc_noreclaim_save(); + /* + * Clear queue->sock under the queue lock so that a sysfs reader in + * nvme_tcp_get_address() either observes the NVME_TCP_Q_LIVE bit + * cleared or a still valid socket. The queue lock itself is owned + * by the controller and only destroyed when the controller is + * freed, so readers blocked on it cannot race its teardown. + */ + mutex_lock(&queue->queue_lock); /* ->sock will be released by fput() */ fput(queue->sock->file); queue->sock = NULL; + mutex_unlock(&queue->queue_lock); memalloc_noreclaim_restore(noreclaim_flag); kfree(queue->pdu); mutex_destroy(&queue->send_mutex); - mutex_destroy(&queue->queue_lock); mutex_destroy(&queue->pf_cache_lock); } @@ -1986,7 +1998,6 @@ static int nvme_tcp_alloc_queue(struct nvme_ctrl *nctrl, int qid, int ret, rcv_pdu_size; struct file *sock_file; - mutex_init(&queue->queue_lock); queue->ctrl = ctrl; init_llist_head(&queue->req_list); INIT_LIST_HEAD(&queue->send_list); @@ -2124,7 +2135,6 @@ static int nvme_tcp_alloc_queue(struct nvme_ctrl *nctrl, int qid, queue->sock = NULL; err_destroy_mutex: mutex_destroy(&queue->send_mutex); - mutex_destroy(&queue->queue_lock); mutex_destroy(&queue->pf_cache_lock); return ret; } @@ -2772,6 +2782,7 @@ static void nvme_tcp_stop_ctrl(struct nvme_ctrl *ctrl) static void nvme_tcp_free_ctrl(struct nvme_ctrl *nctrl) { struct nvme_tcp_ctrl *ctrl = to_tcp_ctrl(nctrl); + unsigned int i; if (list_empty(&ctrl->list)) goto free_ctrl; @@ -2783,6 +2794,8 @@ static void nvme_tcp_free_ctrl(struct nvme_ctrl *nctrl) nvmf_free_options(nctrl->opts); free_ctrl: put_net(ctrl->net); + for (i = 0; i < ctrl->nr_allocated_queues; i++) + mutex_destroy(&ctrl->queues[i].queue_lock); kfree(ctrl->queues); kfree(ctrl); } @@ -3035,17 +3048,18 @@ static int nvme_tcp_get_address(struct nvme_ctrl *ctrl, char *buf, int size) len = nvmf_get_address(ctrl, buf, size); - if (!test_bit(NVME_TCP_Q_LIVE, &queue->flags)) - return len; - mutex_lock(&queue->queue_lock); - ret = kernel_getsockname(queue->sock, (struct sockaddr *)&src_addr); - if (ret > 0) { - if (len > 0) - len--; /* strip trailing newline */ - len += scnprintf(buf + len, size - len, "%ssrc_addr=%pISc\n", - (len) ? "," : "", &src_addr); + if (test_bit(NVME_TCP_Q_LIVE, &queue->flags)) { + ret = kernel_getsockname(queue->sock, + (struct sockaddr *)&src_addr); + if (ret > 0) { + if (len > 0) + len--; /* strip trailing newline */ + len += scnprintf(buf + len, size - len, + "%ssrc_addr=%pISc\n", + (len) ? "," : "", &src_addr); + } } mutex_unlock(&queue->queue_lock); @@ -3111,7 +3125,7 @@ static struct nvme_tcp_ctrl *nvme_tcp_alloc_ctrl(struct device *dev, struct nvmf_ctrl_options *opts) { struct nvme_tcp_ctrl *ctrl; - int ret; + int ret, i; ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL); if (!ctrl) @@ -3119,8 +3133,7 @@ static struct nvme_tcp_ctrl *nvme_tcp_alloc_ctrl(struct device *dev, INIT_LIST_HEAD(&ctrl->list); ctrl->ctrl.opts = opts; - ctrl->ctrl.queue_count = opts->nr_io_queues + opts->nr_write_queues + - opts->nr_poll_queues + 1; + ctrl->ctrl.queue_count = NVME_TCP_OPT_NR_QUEUES(opts); ctrl->ctrl.sqsize = opts->queue_size - 1; ctrl->ctrl.kato = opts->kato; @@ -3172,13 +3185,22 @@ static struct nvme_tcp_ctrl *nvme_tcp_alloc_ctrl(struct device *dev, goto out_free_ctrl; } - ctrl->queues = kcalloc(ctrl->ctrl.queue_count, sizeof(*ctrl->queues), + ctrl->nr_allocated_queues = ctrl->ctrl.queue_count; + ctrl->queues = kcalloc(ctrl->nr_allocated_queues, sizeof(*ctrl->queues), GFP_KERNEL); if (!ctrl->queues) { ret = -ENOMEM; goto out_free_ctrl; } + /* + * The queue locks are owned by the controller, not the queues: + * they outlive the per-queue connect/disconnect cycles so that + * sysfs readers can never race their destruction. + */ + for (i = 0; i < ctrl->nr_allocated_queues; i++) + mutex_init(&ctrl->queues[i].queue_lock); + ctrl->net = get_net(current->nsproxy->net_ns); ret = nvme_init_ctrl(&ctrl->ctrl, dev, &nvme_tcp_ctrl_ops, 0); diff --git a/drivers/nvme/target/Kconfig b/drivers/nvme/target/Kconfig index 4904097dfd49..69bde270115e 100644 --- a/drivers/nvme/target/Kconfig +++ b/drivers/nvme/target/Kconfig @@ -117,6 +117,15 @@ config NVME_TARGET_AUTH If unsure, say N. +config NVME_TARGET_AUTH_DEBUG + bool "NVMe over Fabrics In-band Authentication debug messages" + depends on NVME_TARGET_AUTH + help + This enables additional debug messages including the generated + DH-HMAC-CHAP secrets to help debugging authentication failures. + + If unsure, say N. + config NVME_TARGET_PCI_EPF tristate "NVMe PCI Endpoint Function target support" depends on NVME_TARGET && PCI_ENDPOINT diff --git a/drivers/nvme/target/admin-cmd.c b/drivers/nvme/target/admin-cmd.c index 007029eaca39..c8c7961beadb 100644 --- a/drivers/nvme/target/admin-cmd.c +++ b/drivers/nvme/target/admin-cmd.c @@ -1341,7 +1341,7 @@ static u16 nvmet_set_feat_arbitration(struct nvmet_req *req) .hpw = (cdw11 >> 24) & 0xff, .mpw = (cdw11 >> 16) & 0xff, .lpw = (cdw11 >> 8) & 0xff, - .ab = cdw11 & 0x3, + .ab = cdw11 & 0x7, }; if (!ctrl->ops->set_feature) { @@ -1496,7 +1496,7 @@ static u16 nvmet_get_feat_arbitration(struct nvmet_req *req) ((u32)arb.hpw << 24) | ((u32)arb.mpw << 16) | ((u32)arb.lpw << 8) | - (arb.ab & 0x3)); + (arb.ab & 0x7)); return NVME_SC_SUCCESS; } diff --git a/drivers/nvme/target/auth.c b/drivers/nvme/target/auth.c index eb2b6c7a8083..1ad1754a9551 100644 --- a/drivers/nvme/target/auth.c +++ b/drivers/nvme/target/auth.c @@ -145,6 +145,7 @@ u8 nvmet_setup_auth(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq, bool reset) int ret = 0; struct nvmet_host_link *p; struct nvmet_host *host = NULL; + struct nvme_dhchap_key *host_key, *ctrl_key = NULL; down_read(&nvmet_config_sem); if (nvmet_is_disc_subsys(ctrl->subsys)) @@ -154,7 +155,6 @@ u8 nvmet_setup_auth(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq, bool reset) goto out_unlock; list_for_each_entry(p, &ctrl->subsys->hosts, entry) { - pr_debug("check %s\n", nvmet_host_name(p->host)); if (strcmp(nvmet_host_name(p->host), ctrl->hostnqn)) continue; host = p->host; @@ -183,53 +183,41 @@ u8 nvmet_setup_auth(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq, bool reset) goto out_unlock; } - if (host->dhchap_hash_id == ctrl->shash_id) { - pr_debug("Re-use existing hash ID %d\n", - ctrl->shash_id); - } else { - ctrl->shash_id = host->dhchap_hash_id; - } - - /* Skip the 'DHHC-1:XX:' prefix */ - nvme_auth_free_key(ctrl->host_key); - ctrl->host_key = nvme_auth_extract_key(host->dhchap_secret + 10, - host->dhchap_key_hash); - if (IS_ERR(ctrl->host_key)) { + /* + * Skip the 'DHHC-1:XX:' prefix. Keep the old keys until the new ones + * are there: a controller without a host key needs no authentication. + */ + host_key = nvme_auth_extract_key(host->dhchap_secret + 10, + host->dhchap_key_hash); + if (IS_ERR(host_key)) { ret = NVME_AUTH_DHCHAP_FAILURE_NOT_USABLE; - ctrl->host_key = NULL; - goto out_free_hash; + goto out_unlock; + } + if (host->dhchap_ctrl_secret) { + ctrl_key = nvme_auth_extract_key(host->dhchap_ctrl_secret + 10, + host->dhchap_ctrl_key_hash); + if (IS_ERR(ctrl_key)) { + nvme_auth_free_key(host_key); + ret = NVME_AUTH_DHCHAP_FAILURE_NOT_USABLE; + goto out_unlock; + } } + nvme_auth_free_key(ctrl->host_key); + ctrl->host_key = host_key; + nvme_auth_free_key(ctrl->ctrl_key); + ctrl->ctrl_key = ctrl_key; + ctrl->shash_id = host->dhchap_hash_id; +#ifdef CONFIG_NVME_TARGET_AUTH_DEBUG pr_debug("%s: using hash %s key %*ph\n", __func__, ctrl->host_key->hash > 0 ? nvme_auth_hmac_name(ctrl->host_key->hash) : "none", (int)ctrl->host_key->len, ctrl->host_key->key); - - nvme_auth_free_key(ctrl->ctrl_key); - if (!host->dhchap_ctrl_secret) { - ctrl->ctrl_key = NULL; - goto out_unlock; - } - - ctrl->ctrl_key = nvme_auth_extract_key(host->dhchap_ctrl_secret + 10, - host->dhchap_ctrl_key_hash); - if (IS_ERR(ctrl->ctrl_key)) { - ret = NVME_AUTH_DHCHAP_FAILURE_NOT_USABLE; - ctrl->ctrl_key = NULL; - goto out_free_hash; - } - pr_debug("%s: using ctrl hash %s key %*ph\n", __func__, - ctrl->ctrl_key->hash > 0 ? - nvme_auth_hmac_name(ctrl->ctrl_key->hash) : "none", - (int)ctrl->ctrl_key->len, ctrl->ctrl_key->key); - -out_free_hash: - if (ret) { - if (ctrl->host_key) { - nvme_auth_free_key(ctrl->host_key); - ctrl->host_key = NULL; - } - ctrl->shash_id = 0; - } + if (ctrl->ctrl_key) + pr_debug("%s: using ctrl hash %s key %*ph\n", __func__, + ctrl->ctrl_key->hash > 0 ? + nvme_auth_hmac_name(ctrl->ctrl_key->hash) : "none", + (int)ctrl->ctrl_key->len, ctrl->ctrl_key->key); +#endif out_unlock: up_read(&nvmet_config_sem); @@ -355,7 +343,6 @@ int nvmet_auth_host_hash(struct nvmet_req *req, u8 *response, if (ret) goto out; } - pr_debug("ctrl %d qid %d host response seq %u transaction %d\n", ctrl->cntlid, req->sq->qid, req->sq->dhchap_s1, req->sq->dhchap_tid); @@ -531,41 +518,46 @@ int nvmet_auth_ctrl_exponential(struct nvmet_req *req, ret = -EINVAL; } else { memcpy(buf, ctrl->dh_key, buf_size); +#ifdef CONFIG_NVME_TARGET_AUTH_DEBUG pr_debug("%s: ctrl %d public key %*ph\n", __func__, ctrl->cntlid, (int)buf_size, buf); +#endif } return ret; } int nvmet_auth_ctrl_sesskey(struct nvmet_req *req, - u8 *pkey, int pkey_size) + const u8 *pkey, int pkey_size) { struct nvmet_ctrl *ctrl = req->sq->ctrl; int ret; - req->sq->dhchap_skey_len = ctrl->dh_keysize; + req->sq->dhchap_skey_len = nvme_auth_hmac_hash_len(ctrl->shash_id); req->sq->dhchap_skey = kzalloc(req->sq->dhchap_skey_len, GFP_KERNEL); if (!req->sq->dhchap_skey) return -ENOMEM; - ret = nvme_auth_gen_shared_secret(ctrl->dh_tfm, - pkey, pkey_size, - req->sq->dhchap_skey, - req->sq->dhchap_skey_len); + ret = nvme_auth_gen_session_key(ctrl->dh_tfm, + pkey, pkey_size, + req->sq->dhchap_skey, + req->sq->dhchap_skey_len, + ctrl->shash_id); if (ret) - pr_debug("failed to compute shared secret, err %d\n", ret); + pr_debug("failed to compute session key, err %d\n", ret); +#ifdef CONFIG_NVME_TARGET_AUTH_DEBUG else - pr_debug("%s: shared secret %*ph\n", __func__, + pr_debug("%s: session key %*ph\n", __func__, (int)req->sq->dhchap_skey_len, req->sq->dhchap_skey); - +#endif return ret; } void nvmet_auth_insert_psk(struct nvmet_sq *sq) { int hash_len = nvme_auth_hmac_hash_len(sq->ctrl->shash_id); - u8 *psk, *digest, *tls_psk; + u8 *psk, *tls_psk; + char *digest; size_t psk_len; int ret; #ifdef CONFIG_NVME_TARGET_TCP_TLS diff --git a/drivers/nvme/target/loop.c b/drivers/nvme/target/loop.c index 13bb80582b57..ed1c48472e01 100644 --- a/drivers/nvme/target/loop.c +++ b/drivers/nvme/target/loop.c @@ -272,7 +272,6 @@ static void nvme_loop_destroy_admin_queue(struct nvme_loop_ctrl *ctrl) nvmet_sq_destroy(&ctrl->queues[0].nvme_sq); nvmet_cq_put(&ctrl->queues[0].nvme_cq); - nvme_remove_admin_tag_set(&ctrl->ctrl); } static void nvme_loop_free_ctrl(struct nvme_ctrl *nctrl) @@ -373,25 +372,18 @@ static int nvme_loop_configure_admin_queue(struct nvme_loop_ctrl *ctrl) } ctrl->ctrl.queue_count = 1; - error = nvme_alloc_admin_tag_set(&ctrl->ctrl, &ctrl->admin_tag_set, - &nvme_loop_admin_mq_ops, - sizeof(struct nvme_loop_iod) + - NVME_INLINE_SG_CNT * sizeof(struct scatterlist)); - if (error) - goto out_free_sq; - /* reset stopped state for the fresh admin queue */ clear_bit(NVME_CTRL_ADMIN_Q_STOPPED, &ctrl->ctrl.flags); error = nvmf_connect_admin_queue(&ctrl->ctrl); if (error) - goto out_cleanup_tagset; + goto out_free_sq; set_bit(NVME_LOOP_Q_LIVE, &ctrl->queues[0].flags); error = nvme_enable_ctrl(&ctrl->ctrl); if (error) - goto out_cleanup_tagset; + goto out_free_sq; ctrl->ctrl.max_hw_sectors = (NVME_LOOP_MAX_SEGMENTS - 1) << PAGE_SECTORS_SHIFT; @@ -400,14 +392,12 @@ static int nvme_loop_configure_admin_queue(struct nvme_loop_ctrl *ctrl) error = nvme_init_ctrl_finish(&ctrl->ctrl, false); if (error) - goto out_cleanup_tagset; + goto out_free_sq; return 0; -out_cleanup_tagset: - clear_bit(NVME_LOOP_Q_LIVE, &ctrl->queues[0].flags); - nvme_remove_admin_tag_set(&ctrl->ctrl); out_free_sq: + clear_bit(NVME_LOOP_Q_LIVE, &ctrl->queues[0].flags); nvmet_sq_destroy(&ctrl->queues[0].nvme_sq); nvmet_cq_put(&ctrl->queues[0].nvme_cq); return error; @@ -432,6 +422,9 @@ static void nvme_loop_shutdown_ctrl(struct nvme_loop_ctrl *ctrl) static void nvme_loop_delete_ctrl_host(struct nvme_ctrl *ctrl) { nvme_loop_shutdown_ctrl(to_loop_ctrl(ctrl)); + /* Left quiesced if a failed reset has left no admin queue behind */ + nvme_unquiesce_admin_queue(ctrl); + nvme_remove_admin_tag_set(ctrl); } static void nvme_loop_delete_ctrl(struct nvmet_ctrl *nctrl) @@ -495,7 +488,7 @@ static void nvme_loop_reset_ctrl_work(struct work_struct *work) nvme_loop_destroy_admin_queue(ctrl); out_disable: dev_warn(ctrl->ctrl.device, "Removing after reset failure\n"); - nvme_uninit_ctrl(&ctrl->ctrl); + nvme_delete_ctrl(&ctrl->ctrl); } static const struct nvme_ctrl_ops nvme_loop_ctrl_ops = { @@ -595,10 +588,17 @@ static struct nvme_ctrl *nvme_loop_create_ctrl(struct device *dev, if (!ctrl->queues) goto out_uninit_ctrl; - ret = nvme_loop_configure_admin_queue(ctrl); + ret = nvme_alloc_admin_tag_set(&ctrl->ctrl, &ctrl->admin_tag_set, + &nvme_loop_admin_mq_ops, + sizeof(struct nvme_loop_iod) + + NVME_INLINE_SG_CNT * sizeof(struct scatterlist)); if (ret) goto out_free_queues; + ret = nvme_loop_configure_admin_queue(ctrl); + if (ret) + goto out_remove_admin_tagset; + if (opts->queue_size > ctrl->ctrl.maxcmd) { /* warn if maxcmd is lower than queue_size */ dev_warn(ctrl->ctrl.device, @@ -634,6 +634,8 @@ static struct nvme_ctrl *nvme_loop_create_ctrl(struct device *dev, nvme_quiesce_admin_queue(&ctrl->ctrl); nvme_cancel_admin_tagset(&ctrl->ctrl); nvme_loop_destroy_admin_queue(ctrl); +out_remove_admin_tagset: + nvme_remove_admin_tag_set(&ctrl->ctrl); out_free_queues: kfree(ctrl->queues); out_uninit_ctrl: diff --git a/drivers/nvme/target/nvmet.h b/drivers/nvme/target/nvmet.h index 9abf67fae188..232768f1b24f 100644 --- a/drivers/nvme/target/nvmet.h +++ b/drivers/nvme/target/nvmet.h @@ -932,7 +932,7 @@ static inline bool nvmet_has_auth(struct nvmet_ctrl *ctrl, struct nvmet_sq *sq) int nvmet_auth_ctrl_exponential(struct nvmet_req *req, u8 *buf, int buf_size); int nvmet_auth_ctrl_sesskey(struct nvmet_req *req, - u8 *buf, int buf_size); + const u8 *pkey, int pkey_size); void nvmet_auth_insert_psk(struct nvmet_sq *sq); #else static inline u8 nvmet_setup_auth(struct nvmet_ctrl *ctrl, diff --git a/drivers/nvme/target/rdma.c b/drivers/nvme/target/rdma.c index 20e574a4eac6..7cbba255de20 100644 --- a/drivers/nvme/target/rdma.c +++ b/drivers/nvme/target/rdma.c @@ -1197,13 +1197,18 @@ static void nvmet_rdma_free_dev(struct kref *ref) struct nvmet_rdma_device *ndev = container_of(ref, struct nvmet_rdma_device, ref); + nvmet_rdma_destroy_srqs(ndev); + ib_dealloc_pd(ndev->pd); + + /* + * Only delete from the device list once all RDMA resources are torn + * down because nvmet_rdma_remove_one waits for the release work only + * if the device still is on the list. + */ mutex_lock(&device_list_mutex); list_del(&ndev->entry); mutex_unlock(&device_list_mutex); - nvmet_rdma_destroy_srqs(ndev); - ib_dealloc_pd(ndev->pd); - kfree(ndev); } @@ -1691,7 +1696,7 @@ static void nvmet_rdma_queue_established(struct nvmet_rdma_queue *queue) static void __nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue) { - bool disconnect = false; + bool disconnect = false, live = false; unsigned long flags; pr_debug("cm_id= %p queue->state= %d\n", queue->cm_id, queue->state); @@ -1710,6 +1715,7 @@ static void __nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue) } fallthrough; case NVMET_RDMA_Q_LIVE: + live = queue->state == NVMET_RDMA_Q_LIVE; queue->state = NVMET_RDMA_Q_DISCONNECTING; disconnect = true; break; @@ -1719,24 +1725,34 @@ static void __nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue) spin_unlock_irqrestore(&queue->state_lock, flags); if (disconnect) { - rdma_disconnect(queue->cm_id); + /* + * Over iWARP rdma_disconnect() sleeps until the CM has handled + * the ESTABLISHED event of this connection. The CM handles the + * events of all connections one at a time, and our handler + * takes nvmet_rdma_queue_mutex, which callers of this function + * hold. So a queue that has not seen the event is left to the + * release work: ib_drain_qp() moves the queue pair to the error + * state, which ends the connection. + */ + if (live) + rdma_disconnect(queue->cm_id); queue_work(nvmet_wq, &queue->release_work); } } static void nvmet_rdma_queue_disconnect(struct nvmet_rdma_queue *queue) { - bool disconnect = false; - + /* + * Queue the release work with &nvmet_rdma_queue_mutex held, so that + * nvmet_rdma_remove_one() either finds the queue on the list or the + * work has already been queued. + */ mutex_lock(&nvmet_rdma_queue_mutex); if (!list_empty(&queue->queue_list)) { list_del_init(&queue->queue_list); - disconnect = true; + __nvmet_rdma_queue_disconnect(queue); } mutex_unlock(&nvmet_rdma_queue_mutex); - - if (disconnect) - __nvmet_rdma_queue_disconnect(queue); } static void nvmet_rdma_queue_connect_fail(struct rdma_cm_id *cm_id, @@ -1763,10 +1779,13 @@ static void nvmet_rdma_queue_connect_fail(struct rdma_cm_id *cm_id, * queue cm_id and/or a device bound listener cm_id (where in this * case queue will be null). * - * We registered an ib_client to handle device removal for queues, - * so we only need to handle the listening port cm_ids. In this case - * we nullify the priv to prevent double cm_id destruction and destroying - * the cm_id implicitly by returning a non-zero rc to the callout. + * The RDMA CM waits until each cm_id of the device is destroyed, so a queue + * has to go now. Our ib_client also removes the queues, but it cannot be + * relied on here: built in, it is called after the RDMA CM's client. + * + * For a listening port cm_id we nullify the priv to prevent double cm_id + * destruction and destroying the cm_id implicitly by returning a non-zero + * rc to the callout. */ static int nvmet_rdma_device_removal(struct rdma_cm_id *cm_id, struct nvmet_rdma_queue *queue) @@ -1774,11 +1793,7 @@ static int nvmet_rdma_device_removal(struct rdma_cm_id *cm_id, struct nvmet_rdma_port *port; if (queue) { - /* - * This is a queue cm_id. we have registered - * an ib_client to handle queues removal - * so don't interfere and just return. - */ + nvmet_rdma_queue_disconnect(queue); return 0; } diff --git a/drivers/nvme/target/tcp.c b/drivers/nvme/target/tcp.c index 6f8d5c268a22..72e928c38aa2 100644 --- a/drivers/nvme/target/tcp.c +++ b/drivers/nvme/target/tcp.c @@ -102,6 +102,7 @@ MODULE_PARM_DESC(tls_handshake_timeout, #define NVMET_TCP_RECV_BUDGET 8 #define NVMET_TCP_SEND_BUDGET 8 #define NVMET_TCP_IO_WORK_BUDGET 64 +#define NVMET_TCP_ACCEPT_BUDGET 16 enum nvmet_tcp_send_state { NVMET_TCP_SEND_DATA_PDU, @@ -1324,6 +1325,11 @@ static int nvmet_tcp_try_recv_data(struct nvmet_tcp_queue *queue) int len, ret; while (msg_data_left(&cmd->recv_msg)) { + if (queue->tls_pskid) { + /* The last receive has used it up */ + cmd->recv_msg.msg_control = cmd->recv_cbuf; + cmd->recv_msg.msg_controllen = sizeof(cmd->recv_cbuf); + } len = sock_recvmsg(cmd->queue->sock, &cmd->recv_msg, cmd->recv_msg.msg_flags); if (len <= 0) @@ -2090,9 +2096,9 @@ static void nvmet_tcp_accept_work(struct work_struct *w) struct nvmet_tcp_port *port = container_of(w, struct nvmet_tcp_port, accept_work); struct socket *newsock; - int ret; + int ret, i; - while (true) { + for (i = 0; i < NVMET_TCP_ACCEPT_BUDGET; i++) { ret = kernel_accept(port->sock, &newsock, O_NONBLOCK); if (ret < 0) { if (ret != -EAGAIN) @@ -2101,6 +2107,9 @@ static void nvmet_tcp_accept_work(struct work_struct *w) } nvmet_tcp_alloc_queue(port, newsock); } + + /* There may be more. Come to an end for those who flush nvmet_wq. */ + queue_work(nvmet_wq, &port->accept_work); } static void nvmet_tcp_listen_data_ready(struct sock *sk) diff --git a/drivers/phy/samsung/phy-exynos5-usbdrd.c b/drivers/phy/samsung/phy-exynos5-usbdrd.c index 93ac302de1eb..966a894d91b7 100644 --- a/drivers/phy/samsung/phy-exynos5-usbdrd.c +++ b/drivers/phy/samsung/phy-exynos5-usbdrd.c @@ -418,7 +418,7 @@ struct exynos5_usbdrd_phy; struct exynos5_usbdrd_phy_config { u32 id; void (*phy_isol)(struct phy_usb_instance *inst, bool isolate); - void (*phy_init)(struct exynos5_usbdrd_phy *phy_drd); + int (*phy_init)(struct exynos5_usbdrd_phy *phy_drd); unsigned int (*set_refclk)(struct phy_usb_instance *inst); }; @@ -655,7 +655,7 @@ exynos5_usbdrd_apply_phy_tunes(struct exynos5_usbdrd_phy *phy_drd, } } -static void exynos5_usbdrd_pipe3_init(struct exynos5_usbdrd_phy *phy_drd) +static int exynos5_usbdrd_pipe3_init(struct exynos5_usbdrd_phy *phy_drd) { u32 reg; @@ -668,6 +668,8 @@ static void exynos5_usbdrd_pipe3_init(struct exynos5_usbdrd_phy *phy_drd) reg = readl(phy_drd->reg_phy + EXYNOS5_DRD_PHYTEST); reg &= ~PHYTEST_POWERDOWN_SSP; writel(reg, phy_drd->reg_phy + EXYNOS5_DRD_PHYTEST); + + return 0; } static void @@ -778,7 +780,7 @@ exynos5_usbdrd_usbdp_g2_v4_pma_check_pll_lock(struct exynos5_usbdrd_phy *phy_drd return err; } -static void +static int exynos5_usbdrd_usbdp_g2_v4_pma_check_cdr_lock(struct exynos5_usbdrd_phy *phy_drd) { static const unsigned int timeout_us = 40000; @@ -804,9 +806,11 @@ exynos5_usbdrd_usbdp_g2_v4_pma_check_cdr_lock(struct exynos5_usbdrd_phy *phy_drd ((phy_drd->orientation == TYPEC_ORIENTATION_NORMAL) ? 0 : 2), reg); + + return err; } -static void exynos5_usbdrd_utmi_init(struct exynos5_usbdrd_phy *phy_drd) +static int exynos5_usbdrd_utmi_init(struct exynos5_usbdrd_phy *phy_drd) { u32 reg; @@ -828,6 +832,8 @@ static void exynos5_usbdrd_utmi_init(struct exynos5_usbdrd_phy *phy_drd) reg = readl(phy_drd->reg_phy + EXYNOS5_DRD_PHYTEST); reg &= ~PHYTEST_POWERDOWN_HSP; writel(reg, phy_drd->reg_phy + EXYNOS5_DRD_PHYTEST); + + return 0; } static int exynos5_usbdrd_phy_init(struct phy *phy) @@ -864,7 +870,9 @@ static int exynos5_usbdrd_phy_init(struct phy *phy) writel(reg, phy_drd->reg_phy + EXYNOS5_DRD_PHYUTMICLKSEL); /* UTMI or PIPE3 specific init */ - inst->phy_cfg->phy_init(phy_drd); + ret = inst->phy_cfg->phy_init(phy_drd); + if (ret) + goto disable_clks; /* reference clock settings */ reg = inst->phy_cfg->set_refclk(inst); @@ -887,9 +895,10 @@ static int exynos5_usbdrd_phy_init(struct phy *phy) reg &= ~PHYCLKRST_PORTRESET; writel(reg, phy_drd->reg_phy + EXYNOS5_DRD_PHYCLKRST); +disable_clks: clk_bulk_disable_unprepare(phy_drd->drv_data->n_clks, phy_drd->clks); - return 0; + return ret; } static int exynos5_usbdrd_phy_exit(struct phy *phy) @@ -1150,7 +1159,7 @@ static void exynos7870_usbdrd_phy_isol(struct phy_usb_instance *inst, EXYNOS7870_USB2PHY_ENABLE, val); } -static void exynos7870_usbdrd_utmi_init(struct exynos5_usbdrd_phy *phy_drd) +static int exynos7870_usbdrd_utmi_init(struct exynos5_usbdrd_phy *phy_drd) { u32 reg; @@ -1238,6 +1247,8 @@ static void exynos7870_usbdrd_utmi_init(struct exynos5_usbdrd_phy *phy_drd) if (phy_drd->drv_data->phy_tunes) exynos5_usbdrd_apply_phy_tunes(phy_drd, PTS_UTMI_POSTINIT); + + return 0; } static int exynos7870_usbdrd_phy_init(struct phy *phy) @@ -1251,11 +1262,11 @@ static int exynos7870_usbdrd_phy_init(struct phy *phy) return ret; /* UTMI or PIPE3 specific init */ - inst->phy_cfg->phy_init(phy_drd); + ret = inst->phy_cfg->phy_init(phy_drd); clk_bulk_disable_unprepare(phy_drd->drv_data->n_clks, phy_drd->clks); - return 0; + return ret; } static int exynos7870_usbdrd_phy_exit(struct phy *phy) @@ -1302,10 +1313,12 @@ static const struct phy_ops exynos7870_usbdrd_phy_ops = { .owner = THIS_MODULE, }; -static void exynos2200_usbdrd_utmi_init(struct exynos5_usbdrd_phy *phy_drd) +static int exynos2200_usbdrd_utmi_init(struct exynos5_usbdrd_phy *phy_drd) { /* Configure non-Samsung IP PHY, responsible for UTMI */ phy_init(phy_drd->hs_phy); + + return 0; } static void exynos2200_usbdrd_link_init(struct exynos5_usbdrd_phy *phy_drd) @@ -1405,11 +1418,11 @@ static int exynos2200_usbdrd_phy_init(struct phy *phy) exynos2200_usbdrd_link_attach_detach_pipe3_phy(inst); /* UTMI or PIPE3 specific init */ - inst->phy_cfg->phy_init(phy_drd); + ret = inst->phy_cfg->phy_init(phy_drd); clk_bulk_disable_unprepare(phy_drd->drv_data->n_clks, phy_drd->clks); - return 0; + return ret; } static int exynos2200_usbdrd_phy_exit(struct phy *phy) @@ -1463,7 +1476,7 @@ exynos5_usbdrd_usb_v3p1_pipe_override(struct exynos5_usbdrd_phy *phy_drd) writel(reg, regs_base + EXYNOS850_DRD_SECPMACTL); } -static void exynos850_usbdrd_utmi_init(struct exynos5_usbdrd_phy *phy_drd) +static int exynos850_usbdrd_utmi_init(struct exynos5_usbdrd_phy *phy_drd) { void __iomem *regs_base = phy_drd->reg_phy; u32 reg; @@ -1569,6 +1582,8 @@ static void exynos850_usbdrd_utmi_init(struct exynos5_usbdrd_phy *phy_drd) if (ss_ports) exynos5_usbdrd_usb_v3p1_pipe_override(phy_drd); + + return 0; } static int exynos850_usbdrd_phy_init(struct phy *phy) @@ -1582,12 +1597,13 @@ static int exynos850_usbdrd_phy_init(struct phy *phy) return ret; /* UTMI or PIPE3 specific init */ + ret = 0; scoped_guard(mutex, &phy_drd->phy_mutex) - inst->phy_cfg->phy_init(phy_drd); + ret = inst->phy_cfg->phy_init(phy_drd); clk_bulk_disable_unprepare(phy_drd->drv_data->n_clks, phy_drd->clks); - return 0; + return ret; } static int exynos850_usbdrd_phy_exit(struct phy *phy) @@ -1636,11 +1652,12 @@ static const struct phy_ops exynos850_usbdrd_phy_ops = { .owner = THIS_MODULE, }; -static void exynos5_usbdrd_gs101_pipe3_init(struct exynos5_usbdrd_phy *phy_drd) +static int exynos5_usbdrd_gs101_pipe3_init(struct exynos5_usbdrd_phy *phy_drd) { void __iomem *regs_pma = phy_drd->reg_pma; void __iomem *regs_phy = phy_drd->reg_phy; u32 reg; + int ret; exynos5_usbdrd_usbdp_g2_v4_ctrl_pma_ready(phy_drd); @@ -1662,8 +1679,11 @@ static void exynos5_usbdrd_gs101_pipe3_init(struct exynos5_usbdrd_phy *phy_drd) SECPMACTL_PMA_INIT_SW_RST); writel(reg, regs_phy + EXYNOS850_DRD_SECPMACTL); - if (!exynos5_usbdrd_usbdp_g2_v4_pma_check_pll_lock(phy_drd)) - exynos5_usbdrd_usbdp_g2_v4_pma_check_cdr_lock(phy_drd); + ret = exynos5_usbdrd_usbdp_g2_v4_pma_check_pll_lock(phy_drd); + if (ret) + return ret; + + return exynos5_usbdrd_usbdp_g2_v4_pma_check_cdr_lock(phy_drd); } static int exynos5_usbdrd_gs101_phy_init(struct phy *phy) @@ -1688,7 +1708,15 @@ static int exynos5_usbdrd_gs101_phy_init(struct phy *phy) */ exynos5_usbdrd_phy_isol(inst, false); - return exynos850_usbdrd_phy_init(phy); + ret = exynos850_usbdrd_phy_init(phy); + if (ret) { + exynos5_usbdrd_phy_isol(inst, true); + if (inst->phy_cfg->id == EXYNOS5_DRDPHY_UTMI) + regulator_bulk_disable(phy_drd->drv_data->n_regulators, + phy_drd->regulators); + } + + return ret; } static int exynos5_usbdrd_gs101_phy_exit(struct phy *phy) diff --git a/drivers/pinctrl/stm32/pinctrl-stm32.c b/drivers/pinctrl/stm32/pinctrl-stm32.c index 384fdc13a504..8f9935d07e43 100644 --- a/drivers/pinctrl/stm32/pinctrl-stm32.c +++ b/drivers/pinctrl/stm32/pinctrl-stm32.c @@ -82,7 +82,7 @@ #define gpio_range_to_bank(chip) \ container_of(chip, struct stm32_gpio_bank, range) -#define HWSPNLCK_TIMEOUT 1000 /* usec */ +#define HWSPNLCK_TIMEOUT_MS 1 static const char * const stm32_gpio_functions[] = { "gpio", "af0", "af1", @@ -559,7 +559,7 @@ static int stm32_gpio_domain_activate(struct irq_domain *d, if (pctl->hwlock) { ret = hwspin_lock_timeout_in_atomic(pctl->hwlock, - HWSPNLCK_TIMEOUT); + HWSPNLCK_TIMEOUT_MS); if (ret) { dev_err(pctl->dev, "Can't get hwspinlock\n"); return ret; @@ -896,7 +896,7 @@ static int stm32_pmx_set_mode(struct stm32_gpio_bank *bank, if (pctl->hwlock) { err = hwspin_lock_timeout_in_atomic(pctl->hwlock, - HWSPNLCK_TIMEOUT); + HWSPNLCK_TIMEOUT_MS); if (err) { dev_err(pctl->dev, "Can't get hwspinlock\n"); goto unlock; @@ -1033,7 +1033,7 @@ static int stm32_pconf_set_driving(struct stm32_gpio_bank *bank, if (pctl->hwlock) { err = hwspin_lock_timeout_in_atomic(pctl->hwlock, - HWSPNLCK_TIMEOUT); + HWSPNLCK_TIMEOUT_MS); if (err) { dev_err(pctl->dev, "Can't get hwspinlock\n"); goto unlock; @@ -1084,7 +1084,7 @@ static int stm32_pconf_set_speed(struct stm32_gpio_bank *bank, if (pctl->hwlock) { err = hwspin_lock_timeout_in_atomic(pctl->hwlock, - HWSPNLCK_TIMEOUT); + HWSPNLCK_TIMEOUT_MS); if (err) { dev_err(pctl->dev, "Can't get hwspinlock\n"); goto unlock; @@ -1135,7 +1135,7 @@ static int stm32_pconf_set_bias(struct stm32_gpio_bank *bank, if (pctl->hwlock) { err = hwspin_lock_timeout_in_atomic(pctl->hwlock, - HWSPNLCK_TIMEOUT); + HWSPNLCK_TIMEOUT_MS); if (err) { dev_err(pctl->dev, "Can't get hwspinlock\n"); goto unlock; diff --git a/drivers/platform/x86/intel/pmt/class.c b/drivers/platform/x86/intel/pmt/class.c index 9ec843617e3c..ebb5071334e5 100644 --- a/drivers/platform/x86/intel/pmt/class.c +++ b/drivers/platform/x86/intel/pmt/class.c @@ -99,7 +99,7 @@ intel_pmt_read(struct file *filp, struct kobject *kobj, if (count > entry->size - off) count = entry->size - off; - count = pmt_telem_read_mmio(entry->ep->dev, entry->cb, entry->header.guid, buf, + count = pmt_telem_read_mmio(entry->dev, entry->cb, entry->header.guid, buf, entry->base, off, count); return count; @@ -283,10 +283,10 @@ static int intel_pmt_populate_entry(struct intel_pmt_entry *entry, return -EINVAL; } - entry->pcidev = pci_dev; entry->guid = header->guid; entry->size = header->size; entry->cb = ivdev->priv_data; + entry->dev = ivdev->dev; return 0; } diff --git a/drivers/platform/x86/intel/pmt/class.h b/drivers/platform/x86/intel/pmt/class.h index 1ae56a5baad2..1d66681d1472 100644 --- a/drivers/platform/x86/intel/pmt/class.h +++ b/drivers/platform/x86/intel/pmt/class.h @@ -20,7 +20,6 @@ #define GET_ADDRESS(v) ((v) & GENMASK(31, 3)) struct device; -struct pci_dev; extern struct class intel_pmt_class; struct telem_endpoint { @@ -41,7 +40,7 @@ struct intel_pmt_header { struct intel_pmt_entry { struct telem_endpoint *ep; - struct pci_dev *pcidev; + struct device *dev; struct intel_pmt_header header; struct bin_attribute pmt_bin_attr; const struct attribute_group *attr_grp; diff --git a/drivers/platform/x86/intel/pmt/discovery.c b/drivers/platform/x86/intel/pmt/discovery.c index c482368bfaae..f4203d240f54 100644 --- a/drivers/platform/x86/intel/pmt/discovery.c +++ b/drivers/platform/x86/intel/pmt/discovery.c @@ -609,7 +609,7 @@ void intel_pmt_get_features(struct intel_pmt_entry *entry) mutex_lock(&feature_list_lock); list_for_each_entry(feature, &pmt_feature_list, list) { - if (feature->priv->parent != entry->ep->dev) + if (feature->priv->parent != entry->dev) continue; pmt_get_features(entry, feature); diff --git a/drivers/power/sequencing/pwrseq-qcom-wcn.c b/drivers/power/sequencing/pwrseq-qcom-wcn.c index 663d9a537065..4720cf0ffb66 100644 --- a/drivers/power/sequencing/pwrseq-qcom-wcn.c +++ b/drivers/power/sequencing/pwrseq-qcom-wcn.c @@ -324,7 +324,7 @@ static const char *const pwrseq_wcn7850_vregs[] = { static const struct pwrseq_qcom_wcn_pdata pwrseq_wcn7850_of_data = { .vregs = pwrseq_wcn7850_vregs, .num_vregs = ARRAY_SIZE(pwrseq_wcn7850_vregs), - .pwup_delay_ms = 50, + .pwup_delay_ms = 100, .targets = pwrseq_qcom_wcn_targets, }; diff --git a/drivers/ptp/ptp_clock.c b/drivers/ptp/ptp_clock.c index ef020599b771..8b27c749aebe 100644 --- a/drivers/ptp/ptp_clock.c +++ b/drivers/ptp/ptp_clock.c @@ -494,6 +494,11 @@ static int unregister_vclock(struct device *dev, void *data) int ptp_clock_unregister(struct ptp_clock *ptp) { + /* + * Stop and drain virtual-clock creation and deletion before walking the + * children. Do not hold n_vclocks_mux while waiting for sysfs callbacks. + */ + ptp_vclock_remove_sysfs(ptp); if (ptp_vclock_in_use(ptp)) { device_for_each_child(&ptp->dev, NULL, unregister_vclock); } diff --git a/drivers/ptp/ptp_kvm_x86.c b/drivers/ptp/ptp_kvm_x86.c index 6cea4fe39bcf..811758bd8b0d 100644 --- a/drivers/ptp/ptp_kvm_x86.c +++ b/drivers/ptp/ptp_kvm_x86.c @@ -36,7 +36,7 @@ int kvm_arch_ptp_init(void) clock_pair = page_address(p); ret = set_memory_decrypted((unsigned long)clock_pair, 1); if (ret) { - __free_page(p); + /* The page may be left shared, so leak it. */ clock_pair = NULL; goto nofree; } @@ -68,8 +68,9 @@ int kvm_arch_ptp_init(void) void kvm_arch_ptp_exit(void) { if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) { - WARN_ON(set_memory_encrypted((unsigned long)clock_pair, 1)); - free_page((unsigned long)clock_pair); + /* Leak the page if it cannot be made private again. */ + if (!WARN_ON(set_memory_encrypted((unsigned long)clock_pair, 1))) + free_page((unsigned long)clock_pair); clock_pair = NULL; } } diff --git a/drivers/ptp/ptp_private.h b/drivers/ptp/ptp_private.h index db4039d642b4..99e7eb241336 100644 --- a/drivers/ptp/ptp_private.h +++ b/drivers/ptp/ptp_private.h @@ -81,7 +81,11 @@ struct ptp_vclock { struct hlist_node vclock_hash_node; struct cyclecounter cc; struct timecounter tc; - struct mutex lock; /* protects tc/cc */ + u64 cycles; + struct mutex lock; /* protects tc/cc and the cached sample */ + /* Owned by the auxiliary worker. */ + unsigned long retry_delay; + unsigned long refresh_deadline; }; /* @@ -169,6 +173,7 @@ extern const struct attribute_group *ptp_groups[]; int ptp_populate_pin_groups(struct ptp_clock *ptp); void ptp_cleanup_pin_groups(struct ptp_clock *ptp); +void ptp_vclock_remove_sysfs(struct ptp_clock *ptp); struct ptp_vclock *ptp_vclock_register(struct ptp_clock *pclock); void ptp_vclock_unregister(struct ptp_vclock *vclock); diff --git a/drivers/ptp/ptp_sysfs.c b/drivers/ptp/ptp_sysfs.c index 0d4b081daf63..de073b21f1f7 100644 --- a/drivers/ptp/ptp_sysfs.c +++ b/drivers/ptp/ptp_sysfs.c @@ -228,8 +228,10 @@ static ssize_t n_vclocks_store(struct device *dev, if (num > ptp->n_vclocks) { for (i = 0; i < num - ptp->n_vclocks; i++) { vclock = ptp_vclock_register(ptp); - if (!vclock) - goto out; + if (IS_ERR(vclock)) { + err = PTR_ERR(vclock); + goto err_register; + } *(ptp->vclock_index + ptp->n_vclocks + i) = vclock->clock->index; @@ -261,12 +263,24 @@ static ssize_t n_vclocks_store(struct device *dev, mutex_unlock(&ptp->n_vclocks_mux); return count; +err_register: + num = i; + if (num) + device_for_each_child_reverse(dev, &num, unregister_vclock); + for (num = 0; num < i; num++) + ptp->vclock_index[ptp->n_vclocks + num] = -1; out: mutex_unlock(&ptp->n_vclocks_mux); return err; } static DEVICE_ATTR_RW(n_vclocks); +void ptp_vclock_remove_sysfs(struct ptp_clock *ptp) +{ + if (!ptp->is_virtual_clock) + device_remove_file(&ptp->dev, &dev_attr_n_vclocks); +} + static ssize_t max_vclocks_show(struct device *dev, struct device_attribute *attr, char *page) { diff --git a/drivers/ptp/ptp_vclock.c b/drivers/ptp/ptp_vclock.c index 295a64bdd846..0ecd63eb729a 100644 --- a/drivers/ptp/ptp_vclock.c +++ b/drivers/ptp/ptp_vclock.c @@ -4,6 +4,7 @@ * * Copyright 2021 NXP */ +#include #include #include #include "ptp_private.h" @@ -13,6 +14,7 @@ #define PTP_VCLOCK_FADJ_SHIFT 9 #define PTP_VCLOCK_FADJ_DENOMINATOR 15625ULL #define PTP_VCLOCK_REFRESH_INTERVAL (HZ * 2) +#define PTP_VCLOCK_RETRY_INTERVAL msecs_to_jiffies(10) /* protects vclock_hash addition/deletion */ static DEFINE_SPINLOCK(vclock_hash_lock); @@ -42,21 +44,39 @@ static void ptp_vclock_hash_del(struct ptp_vclock *vclock) synchronize_srcu(&vclock_srcu); } +/* The caller holds vclock->lock, or has not published the clock yet. */ +static int ptp_vclock_sample(struct ptp_vclock *vclock) +{ + struct ptp_clock *ptp = vclock->pclock; + struct timespec64 ts; + int err; + + err = ptp->info->getcycles64(ptp->info, &ts); + if (!err) + vclock->cycles = timespec64_to_ns(&ts); + + return err; +} + static int ptp_vclock_adjfine(struct ptp_clock_info *ptp, long scaled_ppm) { struct ptp_vclock *vclock = info_to_vclock(ptp); s64 adj; + int err; adj = (s64)scaled_ppm << PTP_VCLOCK_FADJ_SHIFT; adj = div_s64(adj, PTP_VCLOCK_FADJ_DENOMINATOR); if (mutex_lock_interruptible(&vclock->lock)) return -EINTR; - timecounter_read(&vclock->tc); - vclock->cc.mult = PTP_VCLOCK_CC_MULT + adj; + err = ptp_vclock_sample(vclock); + if (!err) { + timecounter_read(&vclock->tc); + vclock->cc.mult = PTP_VCLOCK_CC_MULT + adj; + } mutex_unlock(&vclock->lock); - return 0; + return err; } static int ptp_vclock_adjtime(struct ptp_clock_info *ptp, s64 delta) @@ -75,15 +95,16 @@ static int ptp_vclock_gettime(struct ptp_clock_info *ptp, struct timespec64 *ts) { struct ptp_vclock *vclock = info_to_vclock(ptp); - u64 ns; + int err; if (mutex_lock_interruptible(&vclock->lock)) return -EINTR; - ns = timecounter_read(&vclock->tc); + err = ptp_vclock_sample(vclock); + if (!err) + *ts = ns_to_timespec64(timecounter_read(&vclock->tc)); mutex_unlock(&vclock->lock); - *ts = ns_to_timespec64(ns); - return 0; + return err; } static int ptp_vclock_gettimex(struct ptp_clock_info *ptp, @@ -94,20 +115,18 @@ static int ptp_vclock_gettimex(struct ptp_clock_info *ptp, struct ptp_clock *pptp = vclock->pclock; struct timespec64 pts; int err; - u64 ns; - - err = pptp->info->getcyclesx64(pptp->info, &pts, sts); - if (err) - return err; if (mutex_lock_interruptible(&vclock->lock)) return -EINTR; - ns = timecounter_cyc2time(&vclock->tc, timespec64_to_ns(&pts)); - mutex_unlock(&vclock->lock); + err = pptp->info->getcyclesx64(pptp->info, &pts, sts); + if (!err) { + u64 ns = timecounter_cyc2time(&vclock->tc, timespec64_to_ns(&pts)); - *ts = ns_to_timespec64(ns); + *ts = ns_to_timespec64(ns); + } + mutex_unlock(&vclock->lock); - return 0; + return err; } static int ptp_vclock_settime(struct ptp_clock_info *ptp, @@ -115,13 +134,16 @@ static int ptp_vclock_settime(struct ptp_clock_info *ptp, { struct ptp_vclock *vclock = info_to_vclock(ptp); u64 ns = timespec64_to_ns(ts); + int err; if (mutex_lock_interruptible(&vclock->lock)) return -EINTR; - timecounter_init(&vclock->tc, &vclock->cc, ns); + err = ptp_vclock_sample(vclock); + if (!err) + timecounter_init(&vclock->tc, &vclock->cc, ns); mutex_unlock(&vclock->lock); - return 0; + return err; } static int ptp_vclock_getcrosststamp(struct ptp_clock_info *ptp, @@ -130,20 +152,18 @@ static int ptp_vclock_getcrosststamp(struct ptp_clock_info *ptp, struct ptp_vclock *vclock = info_to_vclock(ptp); struct ptp_clock *pptp = vclock->pclock; int err; - u64 ns; - - err = pptp->info->getcrosscycles(pptp->info, xtstamp); - if (err) - return err; if (mutex_lock_interruptible(&vclock->lock)) return -EINTR; - ns = timecounter_cyc2time(&vclock->tc, ktime_to_ns(xtstamp->device)); - mutex_unlock(&vclock->lock); + err = pptp->info->getcrosscycles(pptp->info, xtstamp); + if (!err) { + u64 ns = timecounter_cyc2time(&vclock->tc, ktime_to_ns(xtstamp->device)); - xtstamp->device = ns_to_ktime(ns); + xtstamp->device = ns_to_ktime(ns); + } + mutex_unlock(&vclock->lock); - return 0; + return err; } static long ptp_vclock_refresh(struct ptp_clock_info *ptp) @@ -151,8 +171,24 @@ static long ptp_vclock_refresh(struct ptp_clock_info *ptp) struct ptp_vclock *vclock = info_to_vclock(ptp); struct timespec64 ts; - ptp_vclock_gettime(&vclock->info, &ts); + /* Retry transient failures promptly, but back off during long outages. */ + if (ptp_vclock_gettime(&vclock->info, &ts)) { + unsigned long now = jiffies; + + /* Retries must not postpone the next regular refresh attempt. */ + if (!vclock->retry_delay || time_after_eq(now, vclock->refresh_deadline)) + vclock->refresh_deadline = now + PTP_VCLOCK_REFRESH_INTERVAL; + + if (!vclock->retry_delay) + vclock->retry_delay = PTP_VCLOCK_RETRY_INTERVAL; + else + vclock->retry_delay = min_t(unsigned long, + vclock->retry_delay * 2, + PTP_VCLOCK_REFRESH_INTERVAL); + return min(vclock->retry_delay, vclock->refresh_deadline - now); + } + vclock->retry_delay = 0; return PTP_VCLOCK_REFRESH_INTERVAL; } @@ -174,12 +210,9 @@ static const struct ptp_clock_info ptp_vclock_info = { static u64 ptp_vclock_read(struct cyclecounter *cc) { struct ptp_vclock *vclock = cc_to_vclock(cc); - struct ptp_clock *ptp = vclock->pclock; - struct timespec64 ts = {}; - ptp->info->getcycles64(ptp->info, &ts); - - return timespec64_to_ns(&ts); + /* The cyclecounter callback cannot report a failed PHC read. */ + return vclock->cycles; } static const struct cyclecounter ptp_vclock_cc = { @@ -192,10 +225,11 @@ static const struct cyclecounter ptp_vclock_cc = { struct ptp_vclock *ptp_vclock_register(struct ptp_clock *pclock) { struct ptp_vclock *vclock; + int err; vclock = kzalloc(sizeof(*vclock), GFP_KERNEL); if (!vclock) - return NULL; + return ERR_PTR(-ENOMEM); vclock->pclock = pclock; vclock->info = ptp_vclock_info; @@ -214,20 +248,29 @@ struct ptp_vclock *ptp_vclock_register(struct ptp_clock *pclock) mutex_init(&vclock->lock); + err = ptp_vclock_sample(vclock); + if (err) + goto free_vclock; + timecounter_init(&vclock->tc, &vclock->cc, 0); + vclock->clock = ptp_clock_register(&vclock->info, &pclock->dev); - if (IS_ERR_OR_NULL(vclock->clock)) { - kfree(vclock); - return NULL; + if (IS_ERR(vclock->clock)) { + err = PTR_ERR(vclock->clock); + goto free_vclock; } ptp_vclock_set_subclass(vclock->clock); - timecounter_init(&vclock->tc, &vclock->cc, 0); - ptp_schedule_worker(vclock->clock, PTP_VCLOCK_REFRESH_INTERVAL); + /* The initial sample predates registration; refresh without more delay. */ + ptp_schedule_worker(vclock->clock, 0); ptp_vclock_hash_add(vclock); return vclock; + +free_vclock: + kfree(vclock); + return ERR_PTR(err); } void ptp_vclock_unregister(struct ptp_vclock *vclock) @@ -283,6 +326,8 @@ ktime_t ptp_convert_timestamp(const ktime_t *hwtstamp, int vclock_index) u64 ns; ns = ktime_to_ns(*hwtstamp); + if (!ns) + return 0; srcu_idx = srcu_read_lock(&vclock_srcu); diff --git a/drivers/regulator/Kconfig b/drivers/regulator/Kconfig index d84f3d054c59..a504a20f994f 100644 --- a/drivers/regulator/Kconfig +++ b/drivers/regulator/Kconfig @@ -1149,6 +1149,7 @@ config REGULATOR_QCOM_SMD_RPM config REGULATOR_QCOM_SPMI tristate "Qualcomm SPMI regulator driver" depends on SPMI || COMPILE_TEST + select REGMAP_MMIO help If you say yes to this option, support will be included for the regulators found in Qualcomm SPMI PMICs. diff --git a/drivers/regulator/qcom_spmi-regulator.c b/drivers/regulator/qcom_spmi-regulator.c index c1a41ce70b36..a04ddb1eac94 100644 --- a/drivers/regulator/qcom_spmi-regulator.c +++ b/drivers/regulator/qcom_spmi-regulator.c @@ -12,13 +12,13 @@ #include #include #include +#include #include #include #include #include #include #include -#include #include /* Pin control enable input pins. */ @@ -1335,6 +1335,14 @@ static irqreturn_t spmi_regulator_vs_ocp_isr(int irq, void *data) static struct regmap *saw_regmap; +static const struct regmap_config saw_regmap_config = { + .name = "saw", + .reg_bits = 32, + .val_bits = 32, + .reg_stride = 4, + .use_raw_spinlock = true, +}; + static void spmi_saw_set_vdd(void *data) { u32 vctl, data3, avs_ctl, pmic_sts; @@ -2504,7 +2512,8 @@ static int qcom_spmi_regulator_probe(struct platform_device *pdev) const char *name; struct device *dev = &pdev->dev; struct device_node *node = pdev->dev.of_node; - struct device_node *syscon, *reg_node; + struct device_node *saw, *reg_node; + void __iomem *saw_base; struct property *reg_prop; int ret, lenp; struct list_head *vreg_list; @@ -2523,12 +2532,22 @@ static int qcom_spmi_regulator_probe(struct platform_device *pdev) if (!reg) return -ENODEV; - syscon = of_parse_phandle(node, "qcom,saw-reg", 0); - if (syscon) { - saw_regmap = syscon_node_to_regmap(syscon); - of_node_put(syscon); - if (IS_ERR(saw_regmap)) - dev_err(dev, "ERROR reading SAW regmap\n"); + saw = of_parse_phandle(node, "qcom,saw-reg", 0); + if (saw) { + saw_base = devm_of_iomap(dev, saw, 0, NULL); + of_node_put(saw); + if (IS_ERR(saw_base)) + return dev_err_probe(dev, PTR_ERR(saw_base), + "failed to map the SAW\n"); + + saw_regmap = devm_regmap_init_mmio(dev, saw_base, + &saw_regmap_config); + if (IS_ERR(saw_regmap)) { + ret = PTR_ERR(saw_regmap); + saw_regmap = NULL; + return dev_err_probe(dev, ret, + "failed to set the SAW regmap up\n"); + } } for (; reg->name; reg++) { diff --git a/drivers/s390/block/dasd_eckd.c b/drivers/s390/block/dasd_eckd.c index 8947fbd2797a..545446b3818f 100644 --- a/drivers/s390/block/dasd_eckd.c +++ b/drivers/s390/block/dasd_eckd.c @@ -2594,7 +2594,8 @@ dasd_eckd_build_check_tcw(struct dasd_device *base, struct format_data_t *fdata, return cqr; out_err: - dasd_sfree_request(cqr, startdev); + start_priv->count--; + dasd_ffree_request(cqr, startdev); return ERR_PTR(rc); } diff --git a/drivers/s390/block/dasd_ioctl.c b/drivers/s390/block/dasd_ioctl.c index a9edc0468a31..fe136652b509 100644 --- a/drivers/s390/block/dasd_ioctl.c +++ b/drivers/s390/block/dasd_ioctl.c @@ -304,7 +304,9 @@ static int dasd_ioctl_check_format(struct block_device *bdev, void __user *argp) goto out_err; } - if (copy_from_user(&cdata, argp, sizeof(cdata))) { + /* copy only input fields, clear the rest */ + memset(&cdata, 0, sizeof(cdata)); + if (copy_from_user(&cdata.expect, argp, sizeof(cdata.expect))) { rc = -EFAULT; goto out_err; } diff --git a/drivers/s390/crypto/zcrypt_api.c b/drivers/s390/crypto/zcrypt_api.c index eff9ad7aa14e..bcdfb7cb2fd5 100644 --- a/drivers/s390/crypto/zcrypt_api.c +++ b/drivers/s390/crypto/zcrypt_api.c @@ -854,7 +854,7 @@ static long _zcrypt_send_cprb(u32 xflags, struct ap_perms *perms, struct ica_xcRB *xcrb) { bool userspace = xflags & ZCRYPT_XFLAG_USERSPACE; - unsigned int domain, func_code = 0; + unsigned int card, domain, _dom, func_code = 0; unsigned int wgt = 0, pref_wgt = 0; struct zcrypt_queue *zq, *pref_zq; struct zcrypt_card *zc, *pref_zc; @@ -877,10 +877,17 @@ static long _zcrypt_send_cprb(u32 xflags, struct ap_perms *perms, print_hex_dump_debug("ccareq: ", DUMP_PREFIX_ADDRESS, 16, 1, ap_msg.msg, ap_msg.len, false); + /* Check domain for either AUTOSEL_DOM or in range 0...AP_DOMAINS-1 */ + if (domain != AUTOSEL_DOM && domain >= AP_DOMAINS) { + rc = -EINVAL; + goto out; + } + /* Spectre-v1: sanitize domain unconditionally for later use */ + _dom = array_index_nospec(domain, AP_DOMAINS); + if (perms != &ap_perms && domain < AP_DOMAINS) { if (ap_msg.flags & AP_MSG_FLAG_ADMIN) { - domain = array_index_nospec(domain, AP_DOMAINS); - if (!test_bit_inv(domain, perms->adm)) { + if (!test_bit_inv(_dom, perms->adm)) { rc = -ENODEV; goto out; } @@ -893,13 +900,15 @@ static long _zcrypt_send_cprb(u32 xflags, struct ap_perms *perms, * If a valid target domain is set and this domain is NOT a usage * domain but a control only domain, autoselect target domain. */ - if (domain < AP_DOMAINS && - !ap_test_config_usage_domain(domain) && - ap_test_config_ctrl_domain(domain)) - domain = AUTOSEL_DOM; + if (domain < AP_DOMAINS) { + if (!ap_test_config_usage_domain(_dom) && + ap_test_config_ctrl_domain(_dom)) + domain = AUTOSEL_DOM; + } pref_zc = NULL; pref_zq = NULL; + card = xcrb->user_defined; spin_lock(&zcrypt_list_lock); for_each_zcrypt_card(zc) { /* Check for usable CCA card */ @@ -907,8 +916,7 @@ static long _zcrypt_send_cprb(u32 xflags, struct ap_perms *perms, !zc->card->hwinfo.cca) continue; /* Check for user selected CCA card */ - if (xcrb->user_defined != AUTOSELECT && - xcrb->user_defined != zc->card->id) + if (card != AUTOSELECT && card != zc->card->id) continue; /* check if request size exceeds card max msg size */ if (ap_msg.len > zc->card->maxmsgsize) @@ -952,7 +960,7 @@ static long _zcrypt_send_cprb(u32 xflags, struct ap_perms *perms, if (!pref_zq) { pr_debug("no match for address %02x.%04x => ENODEV\n", - xcrb->user_defined, domain); + card, domain); rc = -ENODEV; goto out; } @@ -1040,7 +1048,7 @@ static long _zcrypt_send_ep11_cprb(u32 xflags, struct ap_perms *perms, struct ep11_target_dev *targets = NULL; unsigned short target_num; unsigned int wgt = 0, pref_wgt = 0; - unsigned int func_code = 0, domain; + unsigned int func_code = 0, domain, _dom; struct ap_message ap_msg; int cpen, qpen, qid = 0, rc; struct module *mod; @@ -1077,10 +1085,17 @@ static long _zcrypt_send_ep11_cprb(u32 xflags, struct ap_perms *perms, print_hex_dump_debug("ep11req: ", DUMP_PREFIX_ADDRESS, 16, 1, ap_msg.msg, ap_msg.len, false); + /* Check domain for either AUTOSEL_DOM or in range 0...AP_DOMAINS-1 */ + if (domain != AUTOSEL_DOM && domain >= AP_DOMAINS) { + rc = -EINVAL; + goto out; + } + /* Spectre-v1: sanitize domain unconditionally for later use */ + _dom = array_index_nospec(domain, AP_DOMAINS); + if (perms != &ap_perms && domain < AP_DOMAINS) { if (ap_msg.flags & AP_MSG_FLAG_ADMIN) { - domain = array_index_nospec(domain, AP_DOMAINS); - if (!test_bit_inv(domain, perms->adm)) { + if (!test_bit_inv(_dom, perms->adm)) { rc = -ENODEV; goto out; } diff --git a/drivers/s390/crypto/zcrypt_error.h b/drivers/s390/crypto/zcrypt_error.h index 46e27b43a8af..fd10302e68d3 100644 --- a/drivers/s390/crypto/zcrypt_error.h +++ b/drivers/s390/crypto/zcrypt_error.h @@ -78,9 +78,13 @@ struct error_hdr { static inline int convert_error(struct zcrypt_queue *zq, struct ap_message *reply) { - struct error_hdr *ehdr = reply->msg; - int card = AP_QID_CARD(zq->queue->qid); int queue = AP_QID_QUEUE(zq->queue->qid); + int card = AP_QID_CARD(zq->queue->qid); + struct error_hdr *ehdr = reply->msg; + struct { + struct type86_hdr hdr; + struct type86_fmt2_ext fmt2; + } __packed * t86hdr = reply->msg; switch (ehdr->reply_code) { case REP82_ERROR_INVALID_MSG_LEN: /* 0x23 */ @@ -100,19 +104,12 @@ static inline int convert_error(struct zcrypt_queue *zq, /* RY indicates malformed request */ if (ehdr->reply_code == REP82_ERROR_FILTERED_BY_HYPERVISOR && ehdr->type == TYPE86_RSP_CODE) { - struct { - struct type86_hdr hdr; - struct type86_fmt2_ext fmt2; - } __packed * head = reply->msg; - unsigned int apfs = *((u32 *)head->fmt2.apfs); - ZCRYPT_DBF_WARN("%s dev=%02x.%04x RY=0x%02x apfs=0x%x => rc=EINVAL\n", __func__, card, queue, - ehdr->reply_code, apfs); + ehdr->reply_code, t86hdr->fmt2.apfs); } else { ZCRYPT_DBF_WARN("%s dev=%02x.%04x RY=0x%02x => rc=EINVAL\n", - __func__, card, queue, - ehdr->reply_code); + __func__, card, queue, ehdr->reply_code); } return -EINVAL; case REP82_ERROR_MACHINE_FAILURE: /* 0x10 */ @@ -125,15 +122,10 @@ static inline int convert_error(struct zcrypt_queue *zq, /* For type 86 response show the apfs value (failure reason) */ if (ehdr->reply_code == REP82_ERROR_TRANSPORT_FAIL && ehdr->type == TYPE86_RSP_CODE) { - struct { - struct type86_hdr hdr; - struct type86_fmt2_ext fmt2; - } __packed * head = reply->msg; - unsigned int apfs = *((u32 *)head->fmt2.apfs); - ZCRYPT_DBF_WARN( "%s dev=%02x.%04x RY=0x%02x apfs=0x%x => bus rescan, rc=EAGAIN\n", - __func__, card, queue, ehdr->reply_code, apfs); + __func__, card, queue, ehdr->reply_code, + t86hdr->fmt2.apfs); } else { ZCRYPT_DBF_WARN("%s dev=%02x.%04x RY=0x%02x => bus rescan, rc=EAGAIN\n", __func__, card, queue, diff --git a/drivers/s390/crypto/zcrypt_msgtype50.c b/drivers/s390/crypto/zcrypt_msgtype50.c index fc0a2a053dc2..fecc93f73b45 100644 --- a/drivers/s390/crypto/zcrypt_msgtype50.c +++ b/drivers/s390/crypto/zcrypt_msgtype50.c @@ -153,6 +153,11 @@ struct type80_hdr { unsigned char reserved3[8]; } __packed; +struct type80_reply { + struct type80_hdr hdr; + char data[]; +} __packed; + int get_rsa_modex_fc(struct ica_rsa_modexpo *mex, int *fcode) { if (!mex->inputdatalength) @@ -341,32 +346,43 @@ static int ICACRT_msg_to_type50CRT_msg(struct zcrypt_queue *zq, * @data: pointer to user output data * @length: size of user output data * - * Returns 0 on success or -EFAULT. + * Returns 0 on success or neg. errno value on failure. */ static int convert_type80(struct zcrypt_queue *zq, struct ap_message *reply, char __user *outputdata, unsigned int outputdatalength) { - struct type80_hdr *t80h = reply->msg; - unsigned char *data; + struct type80_reply *msg = reply->msg; + size_t payload_len; + + /* + * reply->len is always >= sizeof(struct type80_reply) here and + * outputdatalength (the modulus size) is guaranteed to be equal to + * inputdatalength and 0 < outputdatalength <= CEX3A_MAX_MOD_SIZE, + * also payload size may be >= outputdatalength. + */ + + payload_len = reply->len - sizeof(msg->hdr); - if (t80h->len < sizeof(*t80h) + outputdatalength) { - /* The result is too short, the CEXxA card may not do that.. */ + if (outputdatalength > payload_len) { + /* We expect at least outputdatalength bytes, broken card ? */ zq->online = 0; pr_err("Crypto dev=%02x.%04x code=0x%02x => online=0 rc=EAGAIN\n", AP_QID_CARD(zq->queue->qid), - AP_QID_QUEUE(zq->queue->qid), t80h->code); + AP_QID_QUEUE(zq->queue->qid), msg->hdr.code); ZCRYPT_DBF_ERR("%s dev=%02x.%04x code=0x%02x => online=0 rc=EAGAIN\n", __func__, AP_QID_CARD(zq->queue->qid), - AP_QID_QUEUE(zq->queue->qid), t80h->code); + AP_QID_QUEUE(zq->queue->qid), msg->hdr.code); ap_send_online_uevent(&zq->queue->ap_dev, zq->online); return -EAGAIN; } - BUG_ON(t80h->len > CEX3A_MAX_RESPONSE_SIZE); - data = reply->msg + t80h->len - outputdatalength; - if (copy_to_user(outputdata, data, outputdatalength)) + + if (copy_to_user(outputdata, + msg->data + payload_len - outputdatalength, + outputdatalength)) return -EFAULT; + return 0; } @@ -375,14 +391,19 @@ static int convert_response(struct zcrypt_queue *zq, char __user *outputdata, unsigned int outputdatalength) { - /* Response type byte is the second byte in the response. */ - unsigned char rtype = ((unsigned char *)reply->msg)[1]; + struct type80_reply *msg = reply->msg; + + /* reply->len is always >= sizeof(struct error_hdr) here */ - switch (rtype) { + switch (msg->hdr.type) { case TYPE82_RSP_CODE: case TYPE88_RSP_CODE: return convert_error(zq, reply); case TYPE80_RSP_CODE: + if (msg->hdr.code) + return convert_error(zq, reply); + if (reply->len < sizeof(struct type80_reply)) + return -EINVAL; return convert_type80(zq, reply, outputdata, outputdatalength); default: /* Unknown response type, this should NEVER EVER happen */ @@ -390,11 +411,11 @@ static int convert_response(struct zcrypt_queue *zq, pr_err("Crypto dev=%02x.%04x unknown response type 0x%02x => online=0 rc=EAGAIN\n", AP_QID_CARD(zq->queue->qid), AP_QID_QUEUE(zq->queue->qid), - (int)rtype); + (int)msg->hdr.type); ZCRYPT_DBF_ERR( "%s dev=%02x.%04x unknown response type 0x%02x => online=0 rc=EAGAIN\n", __func__, AP_QID_CARD(zq->queue->qid), - AP_QID_QUEUE(zq->queue->qid), (int)rtype); + AP_QID_QUEUE(zq->queue->qid), (int)msg->hdr.type); ap_send_online_uevent(&zq->queue->ap_dev, zq->online); return -EAGAIN; } @@ -417,26 +438,46 @@ static void zcrypt_msgtype50_receive(struct ap_queue *aq, .reply_code = REP82_ERROR_MACHINE_FAILURE, }; struct type80_hdr *t80h; - int len; + size_t len; /* Copy the reply message to the request message buffer. */ if (!reply) goto out; /* ap_msg->rc indicates the error */ + t80h = reply->msg; - if (t80h->type == TYPE80_RSP_CODE) { - len = t80h->len; - if (len > reply->bufsize || len > msg->bufsize || - len != reply->len) { - pr_debug("len mismatch => EMSGSIZE\n"); - msg->rc = -EMSGSIZE; + + if (reply->len < sizeof(*t80h) || + t80h->type != TYPE80_RSP_CODE) { + if (reply->len < sizeof(error_reply)) { + /* total broken reply, use static error reply instead */ + memcpy(msg->msg, &error_reply, sizeof(error_reply)); + msg->len = sizeof(error_reply); goto out; + } else { + /* malformed reply, convert function will handle this */ + len = reply->len; + goto copy_len_and_out; } - memcpy(msg->msg, reply->msg, len); - msg->len = len; - } else { - memcpy(msg->msg, reply->msg, sizeof(error_reply)); - msg->len = sizeof(error_reply); } + + len = t80h->len; + +copy_len_and_out: + if (len != reply->len) { + msg->rc = -EMSGSIZE; + pr_debug("len %zu rpl.len %zu mismatch, msg.rc=%d\n", + len, reply->len, msg->rc); + goto out; + } + if (len > reply->bufsize || len > msg->bufsize) { + msg->rc = -EMSGSIZE; + pr_debug("len %zu exceeds buf %zu/%zu, msg.rc=%d\n", + len, reply->bufsize, msg->bufsize, msg->rc); + goto out; + } + memcpy(msg->msg, reply->msg, len); + msg->len = len; + out: complete(&msg->response.work); } diff --git a/drivers/s390/crypto/zcrypt_msgtype6.c b/drivers/s390/crypto/zcrypt_msgtype6.c index f0ad39a33fb0..44fe50396d96 100644 --- a/drivers/s390/crypto/zcrypt_msgtype6.c +++ b/drivers/s390/crypto/zcrypt_msgtype6.c @@ -768,6 +768,15 @@ static int convert_type86_rng(struct zcrypt_queue *zq, if (msg->cprbx.ccp_rtcode != 0 || msg->cprbx.ccp_rscode != 0) return -EINVAL; + /* + * Note that offset2 and count2 have already been checked in + * zcrypt_msgtype6_receive(). So only check for valid count2 + * and for not exceeding the hard coded rng buffer size. + */ + if (!msg->fmt2.count2) + return -EINVAL; + if (msg->fmt2.count2 > ZCRYPT_RNG_BUFFER_SIZE) + return -EMSGSIZE; memcpy(buffer, data + msg->fmt2.offset2, msg->fmt2.count2); return msg->fmt2.count2; } @@ -779,11 +788,17 @@ static int convert_response_ica(struct zcrypt_queue *zq, { struct type86x_reply *msg = reply->msg; + /* reply->len is always >= sizeof(struct error_hdr) here */ + switch (msg->hdr.type) { case TYPE82_RSP_CODE: case TYPE88_RSP_CODE: return convert_error(zq, reply); case TYPE86_RSP_CODE: + if (msg->hdr.reply_code) + return convert_error(zq, reply); + if (reply->len < sizeof(struct type86x_reply)) + return -EINVAL; if (msg->cprbx.ccp_rtcode && msg->cprbx.ccp_rscode == 0x14f && outputdatalength > 256) { @@ -794,8 +809,6 @@ static int convert_response_ica(struct zcrypt_queue *zq, return -EINVAL; } } - if (msg->hdr.reply_code) - return convert_error(zq, reply); if (msg->cprbx.cprb_ver_id == 0x02) return convert_type86_ica(zq, reply, outputdata, outputdatalength); @@ -822,6 +835,8 @@ static int convert_response_xcrb(bool userspace, struct zcrypt_queue *zq, { struct type86x_reply *msg = reply->msg; + /* reply->len is always >= sizeof(struct error_hdr) here */ + switch (msg->hdr.type) { case TYPE82_RSP_CODE: case TYPE88_RSP_CODE: @@ -829,9 +844,16 @@ static int convert_response_xcrb(bool userspace, struct zcrypt_queue *zq, return convert_error(zq, reply); case TYPE86_RSP_CODE: if (msg->hdr.reply_code) { - memcpy(&xcrb->status, msg->fmt2.apfs, sizeof(u32)); + if (reply->len < sizeof(struct type86_fmt2_msg)) + xcrb->status = 0x0008044DL; + else + xcrb->status = msg->fmt2.apfs; return convert_error(zq, reply); } + if (reply->len < sizeof(struct type86_fmt2_msg) + + offsetof(struct CPRBX, cprb_ver_id) + + sizeof(msg->cprbx.cprb_ver_id)) + return -EINVAL; if (msg->cprbx.cprb_ver_id == 0x02) return convert_type86_xcrb(userspace, zq, reply, xcrb); fallthrough; /* wrong cprb version is an unknown response */ @@ -856,6 +878,8 @@ static int convert_response_ep11_xcrb(bool userspace, struct zcrypt_queue *zq, { struct type86_ep11_reply *msg = reply->msg; + /* reply->len is always >= sizeof(struct error_hdr) here */ + switch (msg->hdr.type) { case TYPE82_RSP_CODE: case TYPE87_RSP_CODE: @@ -863,6 +887,8 @@ static int convert_response_ep11_xcrb(bool userspace, struct zcrypt_queue *zq, case TYPE86_RSP_CODE: if (msg->hdr.reply_code) return convert_error(zq, reply); + if (reply->len < sizeof(struct type86_ep11_reply)) + return -EINVAL; if (msg->cprbx.cprb_ver_id == 0x04) return convert_type86_ep11_xcrb(userspace, zq, reply, xcrb); fallthrough; /* wrong cprb version is an unknown resp */ @@ -887,6 +913,8 @@ static int convert_response_rng(struct zcrypt_queue *zq, { struct type86x_reply *msg = reply->msg; + /* reply->len is always >= sizeof(struct error_hdr) here */ + switch (msg->hdr.type) { case TYPE82_RSP_CODE: case TYPE88_RSP_CODE: @@ -894,6 +922,8 @@ static int convert_response_rng(struct zcrypt_queue *zq, case TYPE86_RSP_CODE: if (msg->hdr.reply_code) return -EINVAL; + if (reply->len < sizeof(struct type86x_reply)) + return -EINVAL; if (msg->cprbx.cprb_ver_id == 0x02) return convert_type86_rng(zq, reply, data); fallthrough; /* wrong cprb version is an unknown response */ @@ -930,48 +960,85 @@ static void zcrypt_msgtype6_receive(struct ap_queue *aq, }; struct ap_response_type *resp_type = &msg->response; struct type86x_reply *t86r; - int len; + size_t minlen, len; /* Copy the reply message to the request message buffer. */ if (!reply) goto out; /* ap_msg->rc indicates the error */ + t86r = reply->msg; - if (t86r->hdr.type == TYPE86_RSP_CODE && - t86r->cprbx.cprb_ver_id == 0x02) { - switch (resp_type->type) { - case CEXXC_RESPONSE_TYPE_ICA: - len = sizeof(struct type86x_reply) + t86r->length; - if (len > reply->bufsize || len > msg->bufsize || - len != reply->len) { - pr_debug("len mismatch => EMSGSIZE\n"); - msg->rc = -EMSGSIZE; - goto out; - } - memcpy(msg->msg, reply->msg, len); - msg->len = len; - break; - case CEXXC_RESPONSE_TYPE_XCRB: - if (t86r->fmt2.count2) - len = t86r->fmt2.offset2 + t86r->fmt2.count2; - else - len = t86r->fmt2.offset1 + t86r->fmt2.count1; - if (len > reply->bufsize || len > msg->bufsize || - len != reply->len) { - pr_debug("len mismatch => EMSGSIZE\n"); + minlen = sizeof(t86r->hdr) + sizeof(t86r->fmt2) + + offsetof(struct CPRBX, cprb_ver_id) + + sizeof(t86r->cprbx.cprb_ver_id); + + if (reply->len < minlen || + t86r->hdr.type != TYPE86_RSP_CODE || + t86r->cprbx.cprb_ver_id != 0x02) { + if (reply->len < sizeof(error_reply)) { + /* total broken reply, use static error reply instead */ + memcpy(msg->msg, &error_reply, sizeof(error_reply)); + msg->len = sizeof(error_reply); + goto out; + } else { + /* malformed reply, convert function will handle this */ + len = reply->len; + goto copy_len_and_out; + } + } + + switch (resp_type->type) { + case CEXXC_RESPONSE_TYPE_ICA: + if (reply->len < sizeof(struct type86x_reply)) { + msg->rc = -EMSGSIZE; + pr_debug("rpl.len %zu < struct type86_reply, msg.rc=%d\n", + reply->len, msg->rc); + goto out; + } + len = sizeof(struct type86x_reply) + (size_t)t86r->length; + break; + case CEXXC_RESPONSE_TYPE_XCRB: + len = (size_t)t86r->fmt2.offset1 + (size_t)t86r->fmt2.count1; + if (len > reply->len) { + msg->rc = -EMSGSIZE; + pr_debug("offset1 %u count1 %u rpl.len %zu mismatch, msg.rc=%d\n", + t86r->fmt2.offset1, t86r->fmt2.count1, + reply->len, msg->rc); + goto out; + } + if (t86r->fmt2.count2) { + len = (size_t)t86r->fmt2.offset2 + + (size_t)t86r->fmt2.count2; + if (len > reply->len) { msg->rc = -EMSGSIZE; + pr_debug("offset2 %u count2 %u rpl.len %zu mismatch, msg.rc=%d\n", + t86r->fmt2.offset2, t86r->fmt2.count2, + reply->len, msg->rc); goto out; } - memcpy(msg->msg, reply->msg, len); - msg->len = len; - break; - default: - memcpy(msg->msg, &error_reply, sizeof(error_reply)); - msg->len = sizeof(error_reply); } - } else { - memcpy(msg->msg, reply->msg, sizeof(error_reply)); + break; + default: + memcpy(msg->msg, &error_reply, sizeof(error_reply)); msg->len = sizeof(error_reply); + goto out; + } + +copy_len_and_out: + if (len != reply->len) { + msg->rc = -EMSGSIZE; + pr_debug("len %zu rpl.len %zu mismatch, msg.rc=%d\n", + len, reply->len, msg->rc); + goto out; + } + if (len > reply->bufsize || len > msg->bufsize) { + msg->rc = -EMSGSIZE; + pr_debug("len %zu exceeds buf %zu/%zu, msg.rc=%d\n", + len, reply->bufsize, msg->bufsize, msg->rc); + goto out; } + memcpy(msg->msg, reply->msg, len); + msg->len = len; + out: complete(&resp_type->work); } @@ -994,34 +1061,65 @@ static void zcrypt_msgtype6_receive_ep11(struct ap_queue *aq, }; struct ap_response_type *resp_type = &msg->response; struct type86_ep11_reply *t86r; - int len; + size_t minlen, len; /* Copy the reply message to the request message buffer. */ if (!reply) goto out; /* ap_msg->rc indicates the error */ + t86r = reply->msg; - if (t86r->hdr.type == TYPE86_RSP_CODE && - t86r->cprbx.cprb_ver_id == 0x04) { - switch (resp_type->type) { - case CEXXC_RESPONSE_TYPE_EP11: - len = t86r->fmt2.offset1 + t86r->fmt2.count1; - if (len > reply->bufsize || len > msg->bufsize || - len != reply->len) { - pr_debug("len mismatch => EMSGSIZE\n"); - msg->rc = -EMSGSIZE; - goto out; - } - memcpy(msg->msg, reply->msg, len); - msg->len = len; - break; - default: + minlen = sizeof(t86r->hdr) + sizeof(t86r->fmt2) + + offsetof(struct ep11_cprb, cprb_ver_id) + + sizeof(t86r->cprbx.cprb_ver_id); + + if (reply->len < minlen || + t86r->hdr.type != TYPE86_RSP_CODE || + t86r->cprbx.cprb_ver_id != 0x04) { + if (reply->len < sizeof(error_reply)) { + /* total broken reply, use static error reply instead */ memcpy(msg->msg, &error_reply, sizeof(error_reply)); msg->len = sizeof(error_reply); + goto out; + } else { + /* malformed reply, convert function will handle this */ + len = reply->len; + goto copy_len_and_out; } - } else { - memcpy(msg->msg, reply->msg, sizeof(error_reply)); + } + + switch (resp_type->type) { + case CEXXC_RESPONSE_TYPE_EP11: + len = (size_t)t86r->fmt2.offset1 + (size_t)t86r->fmt2.count1; + if (len > reply->len) { + msg->rc = -EMSGSIZE; + pr_debug("offset1 %u count1 %u rpl.len %zu mismatch, msg.rc=%d\n", + t86r->fmt2.offset1, t86r->fmt2.count1, + reply->len, msg->rc); + goto out; + } + break; + default: + memcpy(msg->msg, &error_reply, sizeof(error_reply)); msg->len = sizeof(error_reply); + goto out; + } + +copy_len_and_out: + if (len != reply->len) { + msg->rc = -EMSGSIZE; + pr_debug("len %zu rpl.len %zu mismatch, msg.rc=%d\n", + len, reply->len, msg->rc); + goto out; + } + if (len > reply->bufsize || len > msg->bufsize) { + msg->rc = -EMSGSIZE; + pr_debug("len %zu exceeds buf %zu/%zu, msg.rc=%d\n", + len, reply->bufsize, msg->bufsize, msg->rc); + goto out; } + memcpy(msg->msg, reply->msg, len); + msg->len = len; + out: complete(&resp_type->work); } diff --git a/drivers/s390/crypto/zcrypt_msgtype6.h b/drivers/s390/crypto/zcrypt_msgtype6.h index 9cbe6e2b2d33..8cc227df55c8 100644 --- a/drivers/s390/crypto/zcrypt_msgtype6.h +++ b/drivers/s390/crypto/zcrypt_msgtype6.h @@ -34,7 +34,7 @@ struct type6_hdr { unsigned char right[4]; /* 0x00000000 */ unsigned char reserved3[2]; /* 0x0000 */ unsigned char reserved4[2]; /* 0x0000 */ - unsigned char apfs[4]; /* 0x00000000 */ + unsigned int apfs; /* 0x00000000 */ unsigned int offset1; /* 0x00000058 (offset to CPRB) */ unsigned int offset2; /* 0x00000000 */ unsigned int offset3; /* 0x00000000 */ @@ -83,7 +83,7 @@ struct type86_hdr { struct type86_fmt2_ext { unsigned char reserved[4]; /* 0x00000000 */ - unsigned char apfs[4]; /* final status */ + unsigned int apfs; /* final status */ unsigned int count1; /* length of CPRB + parameters */ unsigned int offset1; /* offset to CPRB */ unsigned int count2; /* 0x00000000 */ diff --git a/drivers/scsi/aha1542.c b/drivers/scsi/aha1542.c index 371e8300f029..8760556de568 100644 --- a/drivers/scsi/aha1542.c +++ b/drivers/scsi/aha1542.c @@ -271,8 +271,6 @@ static void aha1542_free_cmd(struct scsi_cmnd *cmd) buf += bv.bv_len; } } - - scsi_dma_unmap(cmd); } static irqreturn_t aha1542_interrupt(int irq, void *dev_id) diff --git a/drivers/scsi/aic7xxx/aic7xxx_core.c b/drivers/scsi/aic7xxx/aic7xxx_core.c index d747d0b72a13..989e8c9bda4a 100644 --- a/drivers/scsi/aic7xxx/aic7xxx_core.c +++ b/drivers/scsi/aic7xxx/aic7xxx_core.c @@ -1097,7 +1097,7 @@ ahc_handle_seqint(struct ahc_softc *ahc, u_int intstat) sc->byte2 = SCB_GET_LUN(scb) << 5; sc->unused[0] = 0; sc->unused[1] = 0; - sc->length = sg->len; + sc->length = ahc_get_sense_bufsize(ahc, scb); sc->control = 0; /* diff --git a/drivers/scsi/scsi_debug.c b/drivers/scsi/scsi_debug.c index ebb651a6d7c0..e740ec54420e 100644 --- a/drivers/scsi/scsi_debug.c +++ b/drivers/scsi/scsi_debug.c @@ -3904,6 +3904,17 @@ static int check_zbc_access_params(struct scsi_cmnd *scp, UNALIGNED_WRITE_ASCQ); return check_condition_result; } + /* + * Writes must end on a physical block boundary, that is, the + * transfer length must be a multiple of the physical block + * size. + */ + if (!IS_ALIGNED(lba + num, 1U << sdebug_physblk_exp)) { + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LBA_OUT_OF_RANGE, + UNALIGNED_WRITE_ASCQ); + return check_condition_result; + } } /* Handle implicit open of closed and empty zones */ @@ -4187,6 +4198,8 @@ static int do_device_access(struct sdeb_store_info *sip, struct scsi_cmnd *scp, u64 block; enum dma_data_direction dir; struct scsi_data_buffer *sdb = &scp->sdb; + struct scsi_device *sdp = scp->device; + struct sdebug_dev_info *devip = (struct sdebug_dev_info *)sdp->hostdata; u8 *fsp; int i, total = 0; @@ -4214,6 +4227,25 @@ static int do_device_access(struct sdeb_store_info *sip, struct scsi_cmnd *scp, fsp = sip->storep; + /* + * A write to a sequential write required zone has to end on a physical + * block boundary, so if the data-out buffer does not hold all of the + * data that the command asks for, write up to the last whole physical + * block that it does hold. What is left over is reported as part of + * the residual. + */ + if (do_write && sdebug_dev_is_zoned(devip)) { + struct sdeb_zone_state *zsp = zbc_zone(devip, lba); + + if (zsp->z_type == ZBC_ZTYPE_SWR) { + u32 avail = (sdb->length - sg_skip) + >> ilog2(sdebug_sector_size); + + if (avail < num) + num = round_down(avail, 1U << sdebug_physblk_exp); + } + } + block = do_div(lba, sdebug_store_sectors); /* Only allow 1x atomic write or multiple non-atomic writes at any given time */ @@ -5002,6 +5034,9 @@ static int resp_write_dt0(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) "%s: write: cdb indicated=%u, IO sent=%d bytes\n", my_name, num * sdebug_sector_size, ret); + if (ret < scsi_bufflen(scp)) + scsi_set_resid(scp, scsi_bufflen(scp) - ret); + if (unlikely((sdebug_opts & SDEBUG_OPT_RECOV_DIF_DIX) && atomic_read(&sdeb_inject_pending))) { if (sdebug_opts & SDEBUG_OPT_RECOVERED_ERR) { @@ -5072,8 +5107,10 @@ static int resp_write_scat(struct scsi_cmnd *scp, "Unprotected WR to DIF device\n"); } } - if ((num_lrd == 0) || (bt_len == 0)) + if (num_lrd == 0 || bt_len == 0) { + scsi_set_resid(scp, scsi_bufflen(scp)); return 0; /* T10 says these do-nothings are not errors */ + } if (lbdof == 0) { if (sdebug_verbose) sdev_printk(KERN_INFO, scp->device, @@ -5169,6 +5206,8 @@ static int resp_write_scat(struct scsi_cmnd *scp, if (unlikely((sdebug_opts & SDEBUG_OPT_RECOV_DIF_DIX) && atomic_read(&sdeb_inject_pending))) { + /* This range has been written */ + sg_off += num_by; if (sdebug_opts & SDEBUG_OPT_RECOVERED_ERR) { mk_sense_buffer(scp, RECOVERED_ERROR, THRESHOLD_EXCEEDED, 0); atomic_set(&sdeb_inject_pending, 0); @@ -5192,6 +5231,13 @@ static int resp_write_scat(struct scsi_cmnd *scp, } ret = 0; err_out_unlock: + /* + * sg_off counts what the command asked for, which can exceed the + * buffer: lbdof is not validated against it, and a range is counted + * in full even if do_device_access() copied less. + */ + if (scsi_bufflen(scp) > sg_off) + scsi_set_resid(scp, scsi_bufflen(scp) - sg_off); sdeb_meta_write_unlock(sip); err_out: kfree(lrdp); @@ -6066,6 +6112,9 @@ static int resp_atomic_write(struct scsi_cmnd *scp, return DID_ERROR << 16; if (unlikely(ret != len * sdebug_sector_size)) return DID_ERROR << 16; + + if (ret < scsi_bufflen(scp)) + scsi_set_resid(scp, scsi_bufflen(scp) - ret); return 0; } @@ -8713,6 +8762,7 @@ static void __exit scsi_debug_exit(void) sdebug_erase_all_stores(false); xa_destroy(per_store_ap); + async_synchronize_full_domain(&sdebug_async_domain); debugfs_remove(sdebug_debugfs_root); } diff --git a/drivers/soundwire/dmi-quirks.c b/drivers/soundwire/dmi-quirks.c index 768255dd12db..f9183e0e63bf 100644 --- a/drivers/soundwire/dmi-quirks.c +++ b/drivers/soundwire/dmi-quirks.c @@ -111,6 +111,25 @@ static const struct adr_remap ghost_realtek[] = { {} }; +/* + * The Microsoft Surface Pro 11 (Intel) describes its single physical RT1320 + * amplifier twice on link 0, as two _ADR entries differing only in SDCA class + * id and sharing the same unique id. Only the class 1 entry enumerates; the + * class 0 entry is a ghost. + * + * Matched on the product SKU rather than the product name: a later batch of the + * same model could carry a different RT1320 version, which would change the + * _ADR. Keying on the SKU keeps this remap to the hardware it was verified on. + */ +static const struct adr_remap microsoft_sp11_intel[] = { + /* ghost rt1320 on link0 */ + { + 0x000030025d132000ull, + 0x0000000000000000ull + }, + {} +}; + static const struct dmi_system_id adr_remap_quirk_table[] = { /* TGL devices */ { @@ -214,6 +233,13 @@ static const struct dmi_system_id adr_remap_quirk_table[] = { }, .driver_data = (void *)ghost_realtek, }, + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), + DMI_MATCH(DMI_PRODUCT_NAME, "83QM"), + }, + .driver_data = (void *)ghost_realtek, + }, { .matches = { DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), @@ -228,6 +254,22 @@ static const struct dmi_system_id adr_remap_quirk_table[] = { }, .driver_data = (void *)ghost_realtek, }, + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"), + DMI_MATCH(DMI_PRODUCT_NAME, "83U9"), + }, + .driver_data = (void *)ghost_realtek, + }, + /* LNL devices */ + { + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, + "Surface_Pro_11th_Edition_With_Intel_For_Business_2103") + }, + .driver_data = (void *)microsoft_sp11_intel, + }, {} }; diff --git a/drivers/spi/spi-cadence-quadspi.c b/drivers/spi/spi-cadence-quadspi.c index 441426bc232e..f74abed42eab 100644 --- a/drivers/spi/spi-cadence-quadspi.c +++ b/drivers/spi/spi-cadence-quadspi.c @@ -957,11 +957,11 @@ static int cqspi_versal_indirect_read_dma(struct cqspi_flash_pdata *f_pdata, writel(CQSPI_REG_VERSAL_DMA_DST_CTRL_VAL, reg_base + CQSPI_REG_VERSAL_DMA_DST_CTRL); + reinit_completion(&cqspi->transfer_complete); + writel(CQSPI_REG_INDIRECTRD_START_MASK, reg_base + CQSPI_REG_INDIRECTRD); - reinit_completion(&cqspi->transfer_complete); - if (!wait_for_completion_timeout(&cqspi->transfer_complete, msecs_to_jiffies(max_t(size_t, bytes_to_dma, 500)))) { ret = -ETIMEDOUT; diff --git a/drivers/spi/spi-pic32-sqi.c b/drivers/spi/spi-pic32-sqi.c index a6b5a0ed99c9..6061e425d09c 100644 --- a/drivers/spi/spi-pic32-sqi.c +++ b/drivers/spi/spi-pic32-sqi.c @@ -297,7 +297,7 @@ static int pic32_sqi_one_transfer(struct pic32_sqi *sqi, /* get ring descriptor */ rdesc = ring_desc_get(sqi); if (!rdesc) - break; + return -ENOMEM; bd = rdesc->bd; @@ -387,6 +387,7 @@ static int pic32_sqi_one_message(struct spi_controller *host, ret = pic32_sqi_one_transfer(sqi, msg, xfer); if (ret) { dev_err(&spi->dev, "xfer %p err\n", xfer); + msg->status = ret; goto xfer_out; } } diff --git a/drivers/spi/spi-tegra210-quad.c b/drivers/spi/spi-tegra210-quad.c index 543f13503df3..b91d0131acc5 100644 --- a/drivers/spi/spi-tegra210-quad.c +++ b/drivers/spi/spi-tegra210-quad.c @@ -215,6 +215,17 @@ struct tegra_qspi { bool is_packed; bool use_dma; + /* + * Set while a streaming mapping created by + * tegra_qspi_dma_map_xfer() is outstanding, together with the + * length that was handed to dma_map_single(). is_curr_dma_xfer + * only records that the last armed chunk took the DMA path, + * which is not the same thing: a chunk whose mapping failed + * leaves the DMA path flagged with nothing mapped. + */ + bool is_dma_mapped; + unsigned int dma_map_len; + u32 command1_reg; u32 dma_control_reg; u32 def_command1_reg; @@ -584,24 +595,32 @@ static int tegra_qspi_dma_map_xfer(struct tegra_qspi *tqspi, struct spi_transfer if (t->rx_buf) { t->rx_dma = dma_map_single(tqspi->rx_dma_dev, (void *)rx_buf, len, DMA_FROM_DEVICE); if (dma_mapping_error(tqspi->rx_dma_dev, t->rx_dma)) { - dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma, len, DMA_TO_DEVICE); + if (t->tx_buf) + dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma, + len, DMA_TO_DEVICE); return -ENOMEM; } } + tqspi->dma_map_len = len; + tqspi->is_dma_mapped = true; + return 0; } static void tegra_qspi_dma_unmap_xfer(struct tegra_qspi *tqspi, struct spi_transfer *t) { - unsigned int len; - - len = DIV_ROUND_UP(tqspi->curr_dma_words * tqspi->bytes_per_word, 4) * 4; + if (!tqspi->is_dma_mapped) + return; if (t->tx_buf) - dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma, len, DMA_TO_DEVICE); + dma_unmap_single(tqspi->tx_dma_dev, t->tx_dma, + tqspi->dma_map_len, DMA_TO_DEVICE); if (t->rx_buf) - dma_unmap_single(tqspi->rx_dma_dev, t->rx_dma, len, DMA_FROM_DEVICE); + dma_unmap_single(tqspi->rx_dma_dev, t->rx_dma, + tqspi->dma_map_len, DMA_FROM_DEVICE); + + tqspi->is_dma_mapped = false; } static int tegra_qspi_start_dma_based_transfer(struct tegra_qspi *tqspi, struct spi_transfer *t) diff --git a/drivers/spi/spi-virtio.c b/drivers/spi/spi-virtio.c index c92ea1988118..acf903983954 100644 --- a/drivers/spi/spi-virtio.c +++ b/drivers/spi/spi-virtio.c @@ -320,10 +320,8 @@ static int virtio_spi_find_vqs(struct virtio_spi_priv *priv) } /* Function must not be called before virtio_spi_find_vqs() has been run */ -static void virtio_spi_del_vq(void *data) +static void virtio_spi_del_vq(struct virtio_device *vdev) { - struct virtio_device *vdev = data; - virtio_reset_device(vdev); vdev->config->del_vqs(vdev); } @@ -354,21 +352,26 @@ static int virtio_spi_probe(struct virtio_device *vdev) if (ret) return dev_err_probe(&vdev->dev, ret, "Cannot setup virtqueues\n"); - /* Register cleanup for virtqueues using devm */ - ret = devm_add_action_or_reset(&vdev->dev, virtio_spi_del_vq, vdev); - if (ret) - return dev_err_probe(&vdev->dev, ret, "Cannot register virtqueue cleanup\n"); - virtio_device_ready(vdev); - /* Use devm version to register controller */ - ret = devm_spi_register_controller(&vdev->dev, ctrl); - if (ret) + ret = spi_register_controller(ctrl); + if (ret) { + virtio_spi_del_vq(vdev); return dev_err_probe(&vdev->dev, ret, "Cannot register controller\n"); + } return 0; } +static void virtio_spi_remove(struct virtio_device *vdev) +{ + struct spi_controller *ctrl = dev_get_drvdata(&vdev->dev); + + spi_unregister_controller(ctrl); + + virtio_spi_del_vq(vdev); +} + static int virtio_spi_freeze(struct device *dev) { struct spi_controller *ctrl = dev_get_drvdata(dev); @@ -422,6 +425,7 @@ static struct virtio_driver virtio_spi_driver = { }, .id_table = virtio_spi_id_table, .probe = virtio_spi_probe, + .remove = virtio_spi_remove, }; module_virtio_driver(virtio_spi_driver); diff --git a/drivers/spi/spi.c b/drivers/spi/spi.c index b8db8f5fd285..b678e202b384 100644 --- a/drivers/spi/spi.c +++ b/drivers/spi/spi.c @@ -2601,9 +2601,9 @@ EXPORT_SYMBOL_GPL(spi_new_ancillary_device); #ifdef CONFIG_ACPI struct acpi_spi_lookup { struct spi_controller *ctlr; + acpi_handle device_handle; u32 max_speed_hz; u32 mode; - int irq; u8 bits_per_word; u8 chip_select; int n; @@ -2695,7 +2695,7 @@ static int acpi_spi_add_resource(struct acpi_resource *ares, void *data) if (lookup->index != -1 && lookup->n++ != lookup->index) return 1; - status = acpi_get_handle(NULL, + status = acpi_get_handle(lookup->device_handle, sb->resource_source.string_ptr, &parent_handle); @@ -2746,17 +2746,25 @@ static int acpi_spi_add_resource(struct acpi_resource *ares, void *data) if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH) lookup->mode |= SPI_CS_HIGH; } - } else if (lookup->irq < 0) { - struct resource r; - - if (acpi_dev_resource_interrupt(ares, 0, &r)) - lookup->irq = r.start; } /* Always tell the ACPI core to skip this resource */ return 1; } +static int acpi_spi_add_irq_resource(struct acpi_resource *ares, void *data) +{ + int *irq = data; + struct resource r; + + if (*irq < 0 && ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS && + acpi_dev_resource_interrupt(ares, 0, &r)) + *irq = r.start; + + /* Always tell the ACPI core to skip this resource */ + return 1; +} + /** * acpi_spi_device_alloc - Allocate a spi device, and fill it in with ACPI information * @ctlr: controller to which the spi device belongs @@ -2781,13 +2789,14 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr, struct list_head resource_list; struct acpi_spi_lookup lookup = {}; struct spi_device *spi; + int irq = -1; int ret; if (!ctlr && index == -1) return ERR_PTR(-EINVAL); lookup.ctlr = ctlr; - lookup.irq = -1; + lookup.device_handle = acpi_device_handle(adev); lookup.index = index; lookup.n = 0; @@ -2810,6 +2819,19 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr, if (!lookup.max_speed_hz) return ERR_PTR(-ENODEV); + /* + * Only look up the IRQ once we know this is an SPI device for us. + * Parsing an interrupt resource maps its GSI, which must not be done + * for every unrelated ACPI device walked during enumeration. + */ + INIT_LIST_HEAD(&resource_list); + ret = acpi_dev_get_resources(adev, &resource_list, + acpi_spi_add_irq_resource, &irq); + if (ret < 0) + return ERR_PTR(ret); + + acpi_dev_free_resource_list(&resource_list); + spi = spi_alloc_device(lookup.ctlr); if (!spi) { dev_err(&lookup.ctlr->dev, "failed to allocate SPI device for %s\n", @@ -2822,7 +2844,7 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr, ACPI_COMPANION_SET(&spi->dev, adev); spi->max_speed_hz = lookup.max_speed_hz; spi->mode |= lookup.mode; - spi->irq = lookup.irq; + spi->irq = irq; spi->bits_per_word = lookup.bits_per_word; /* * By default spi->chip_select[0] will hold the physical CS number, diff --git a/drivers/staging/greybus/raw.c b/drivers/staging/greybus/raw.c index e668438e1a2c..d0fd15af22ba 100644 --- a/drivers/staging/greybus/raw.c +++ b/drivers/staging/greybus/raw.c @@ -21,6 +21,8 @@ struct gb_raw { struct list_head list; int list_data; struct mutex list_lock; + struct rw_semaphore disconnect_lock; + bool disconnected; struct cdev cdev; struct device dev; }; @@ -200,6 +202,7 @@ static int gb_raw_probe(struct gb_bundle *bundle, INIT_LIST_HEAD(&raw->list); mutex_init(&raw->list_lock); + init_rwsem(&raw->disconnect_lock); raw->connection = connection; greybus_set_drvdata(bundle, raw); @@ -235,6 +238,11 @@ static void gb_raw_disconnect(struct gb_bundle *bundle) struct raw_data *temp; cdev_device_del(&raw->cdev, &raw->dev); + + down_write(&raw->disconnect_lock); + raw->disconnected = true; + up_write(&raw->disconnect_lock); + gb_connection_disable(connection); gb_connection_destroy(connection); @@ -277,11 +285,22 @@ static ssize_t raw_write(struct file *file, const char __user *buf, if (count > MAX_PACKET_SIZE) return -E2BIG; + down_read(&raw->disconnect_lock); + + if (raw->disconnected) { + retval = -ENODEV; + goto exit; + } + retval = gb_raw_send(raw, count, buf); if (retval) - return retval; + goto exit; - return count; + retval = count; +exit: + up_read(&raw->disconnect_lock); + + return retval; } static ssize_t raw_read(struct file *file, char __user *buf, size_t count, diff --git a/drivers/staging/media/atomisp/pci/sh_css_param_dvs.c b/drivers/staging/media/atomisp/pci/sh_css_param_dvs.c index 7fa4aab35b06..19c82464b686 100644 --- a/drivers/staging/media/atomisp/pci/sh_css_param_dvs.c +++ b/drivers/staging/media/atomisp/pci/sh_css_param_dvs.c @@ -4,6 +4,7 @@ * Copyright (c) 2015, Intel Corporation. */ +#include #include "sh_css_param_dvs.h" #include #include @@ -49,7 +50,7 @@ alloc_dvs_6axis_table(const struct ia_css_resolution *frame_res, } /* Generate Y buffers */ - dvs_config->xcoords_y = kvmalloc(width_y * height_y * sizeof(uint32_t), + dvs_config->xcoords_y = kvmalloc(array3_size(width_y, height_y, sizeof(uint32_t)), GFP_KERNEL); if (!dvs_config->xcoords_y) { IA_CSS_ERROR("out of memory"); @@ -57,7 +58,7 @@ alloc_dvs_6axis_table(const struct ia_css_resolution *frame_res, goto exit; } - dvs_config->ycoords_y = kvmalloc(width_y * height_y * sizeof(uint32_t), + dvs_config->ycoords_y = kvmalloc(array3_size(width_y, height_y, sizeof(uint32_t)), GFP_KERNEL); if (!dvs_config->ycoords_y) { IA_CSS_ERROR("out of memory"); @@ -68,7 +69,8 @@ alloc_dvs_6axis_table(const struct ia_css_resolution *frame_res, /* Generate UV buffers */ IA_CSS_LOG("UV W %d H %d", width_uv, height_uv); - dvs_config->xcoords_uv = kvmalloc(width_uv * height_uv * sizeof(uint32_t), + dvs_config->xcoords_uv = kvmalloc(array3_size(width_uv, height_uv, + sizeof(uint32_t)), GFP_KERNEL); if (!dvs_config->xcoords_uv) { IA_CSS_ERROR("out of memory"); @@ -76,7 +78,8 @@ alloc_dvs_6axis_table(const struct ia_css_resolution *frame_res, goto exit; } - dvs_config->ycoords_uv = kvmalloc(width_uv * height_uv * sizeof(uint32_t), + dvs_config->ycoords_uv = kvmalloc(array3_size(width_uv, height_uv, + sizeof(uint32_t)), GFP_KERNEL); if (!dvs_config->ycoords_uv) { IA_CSS_ERROR("out of memory"); diff --git a/drivers/staging/media/atomisp/pci/sh_css_param_shading.c b/drivers/staging/media/atomisp/pci/sh_css_param_shading.c index 513e272f2fdc..cbe703f0f7be 100644 --- a/drivers/staging/media/atomisp/pci/sh_css_param_shading.c +++ b/drivers/staging/media/atomisp/pci/sh_css_param_shading.c @@ -4,6 +4,7 @@ * Copyright (c) 2015, Intel Corporation. */ +#include #include #include @@ -339,7 +340,8 @@ ia_css_shading_table_alloc( me->fraction_bits = 0; for (i = 0; i < IA_CSS_SC_NUM_COLORS; i++) { me->data[i] = - kvmalloc(width * height * sizeof(*me->data[0]), + kvmalloc(array3_size(width, height, + sizeof(*me->data[0])), GFP_KERNEL); if (!me->data[i]) { unsigned int j; diff --git a/drivers/staging/media/atomisp/pci/sh_css_params.c b/drivers/staging/media/atomisp/pci/sh_css_params.c index 11d62313c908..dda55369b5bb 100644 --- a/drivers/staging/media/atomisp/pci/sh_css_params.c +++ b/drivers/staging/media/atomisp/pci/sh_css_params.c @@ -4,6 +4,7 @@ * Copyright (c) 2015, Intel Corporation. */ +#include #include #include "gdc_device.h" /* gdc_lut_store(), ... */ @@ -1381,11 +1382,11 @@ struct ia_css_morph_table *ia_css_morph_table_allocate( } for (i = 0; i < IA_CSS_MORPH_TABLE_NUM_PLANES; i++) { - me->coordinates_x[i] = kvmalloc(height * width * - sizeof(*me->coordinates_x[i]), + me->coordinates_x[i] = kvmalloc(array3_size(height, width, + sizeof(*me->coordinates_x[i])), GFP_KERNEL); - me->coordinates_y[i] = kvmalloc(height * width * - sizeof(*me->coordinates_y[i]), + me->coordinates_y[i] = kvmalloc(array3_size(height, width, + sizeof(*me->coordinates_y[i])), GFP_KERNEL); if ((!me->coordinates_x[i]) || @@ -4206,13 +4207,17 @@ ia_css_dvs_statistics_allocate(const struct ia_css_dvs_grid_info *grid) goto err; me->grid = *grid; - me->hor_proj = kvmalloc(grid->height * IA_CSS_DVS_NUM_COEF_TYPES * - sizeof(*me->hor_proj), GFP_KERNEL); + me->hor_proj = kvmalloc(array3_size(grid->height, + IA_CSS_DVS_NUM_COEF_TYPES, + sizeof(*me->hor_proj)), + GFP_KERNEL); if (!me->hor_proj) goto err; - me->ver_proj = kvmalloc(grid->width * IA_CSS_DVS_NUM_COEF_TYPES * - sizeof(*me->ver_proj), GFP_KERNEL); + me->ver_proj = kvmalloc(array3_size(grid->width, + IA_CSS_DVS_NUM_COEF_TYPES, + sizeof(*me->ver_proj)), + GFP_KERNEL); if (!me->ver_proj) goto err; @@ -4479,24 +4484,26 @@ ia_css_dvs2_6axis_config_allocate(const struct ia_css_stream *stream) params->pipe_dvs_6axis_config[IA_CSS_PIPE_ID_VIDEO]->height_uv; IA_CSS_LOG("table Y: W %d H %d", width_y, height_y); IA_CSS_LOG("table UV: W %d H %d", width_uv, height_uv); - dvs_config->xcoords_y = kvmalloc(width_y * height_y * sizeof(uint32_t), + dvs_config->xcoords_y = kvmalloc(array3_size(width_y, height_y, + sizeof(uint32_t)), GFP_KERNEL); if (!dvs_config->xcoords_y) goto err; - dvs_config->ycoords_y = kvmalloc(width_y * height_y * sizeof(uint32_t), + dvs_config->ycoords_y = kvmalloc(array3_size(width_y, height_y, + sizeof(uint32_t)), GFP_KERNEL); if (!dvs_config->ycoords_y) goto err; - dvs_config->xcoords_uv = kvmalloc(width_uv * height_uv * - sizeof(uint32_t), + dvs_config->xcoords_uv = kvmalloc(array3_size(width_uv, height_uv, + sizeof(uint32_t)), GFP_KERNEL); if (!dvs_config->xcoords_uv) goto err; - dvs_config->ycoords_uv = kvmalloc(width_uv * height_uv * - sizeof(uint32_t), + dvs_config->ycoords_uv = kvmalloc(array3_size(width_uv, height_uv, + sizeof(uint32_t)), GFP_KERNEL); if (!dvs_config->ycoords_uv) goto err; diff --git a/drivers/target/target_core_pr.c b/drivers/target/target_core_pr.c index f18085d8345f..24b240786f88 100644 --- a/drivers/target/target_core_pr.c +++ b/drivers/target/target_core_pr.c @@ -3220,10 +3220,11 @@ core_scsi3_emulate_pro_register_and_move(struct se_cmd *cmd, u64 res_key, transport_kunmap_data_sg(cmd); buf = NULL; - if ((tid_len + 24) != cmd->data_length) { - pr_err("SPC-3 PR: Illegal tid_len: %u + 24 byte header" - " does not equal CDB data_length: %u\n", tid_len, - cmd->data_length); + /* TransportID is at least 24 bytes. buf[24] is its first byte. */ + if (tid_len < 24 || + tid_len != cmd->data_length - 24) { + pr_err("SPC-3 PR: Illegal tid_len: %u for data_length: %u\n", + tid_len, cmd->data_length); ret = TCM_INVALID_PARAMETER_LIST; goto out_put_pr_reg; } diff --git a/drivers/thermal/airoha_thermal.c b/drivers/thermal/airoha_thermal.c index 829a7327fc40..a971c0b986ac 100644 --- a/drivers/thermal/airoha_thermal.c +++ b/drivers/thermal/airoha_thermal.c @@ -437,18 +437,6 @@ static int airoha_thermal_probe(struct platform_device *pdev) of_address_to_resource(chip_scu_np, 0, &priv->scu_adc_res); of_node_put(chip_scu_np); - irq = platform_get_irq(pdev, 0); - if (irq < 0) - return irq; - - ret = devm_request_threaded_irq(&pdev->dev, irq, NULL, - airoha_thermal_irq, IRQF_ONESHOT, - pdev->name, priv); - if (ret) { - dev_err(dev, "Can't get interrupt working.\n"); - return ret; - } - airoha_thermal_setup_monitor(priv); airoha_thermal_setup_adc_val(dev, priv); @@ -461,6 +449,19 @@ static int airoha_thermal_probe(struct platform_device *pdev) platform_set_drvdata(pdev, priv); + /* After zone registration: the handler uses priv->tz */ + irq = platform_get_irq(pdev, 0); + if (irq < 0) + return irq; + + ret = devm_request_threaded_irq(&pdev->dev, irq, NULL, + airoha_thermal_irq, IRQF_ONESHOT, + pdev->name, priv); + if (ret) { + dev_err(dev, "Can't get interrupt working.\n"); + return ret; + } + /* Enable LOW and HIGH interrupt */ writel(EN7581_HOFSINTEN0 | EN7581_LOFSINTEN0, priv->base + EN7581_TEMPMONINT); diff --git a/drivers/tty/serial/8250/8250.h b/drivers/tty/serial/8250/8250.h index 0076eb28661c..e1feed8b4d51 100644 --- a/drivers/tty/serial/8250/8250.h +++ b/drivers/tty/serial/8250/8250.h @@ -188,6 +188,7 @@ static unsigned int __maybe_unused serial_icr_read(struct uart_8250_port *up, void serial8250_clear_fifos(struct uart_8250_port *p); void serial8250_clear_and_reinit_fifos(struct uart_8250_port *p); void serial8250_fifo_wait_for_lsr_thre(struct uart_8250_port *up, unsigned int count); +void serial8250_wait_for_xmitr(struct uart_8250_port *up, int bits); void serial8250_rpm_get(struct uart_8250_port *p); void serial8250_rpm_put(struct uart_8250_port *p); diff --git a/drivers/tty/serial/8250/8250_lpss.c b/drivers/tty/serial/8250/8250_lpss.c index 325e587ae2c4..aaf50ac1aee5 100644 --- a/drivers/tty/serial/8250/8250_lpss.c +++ b/drivers/tty/serial/8250/8250_lpss.c @@ -82,6 +82,9 @@ static void byt_set_termios(struct uart_port *p, struct ktermios *termios, /* Gracefully handle the B0 case: fall back to B9600 */ fuart = fuart ? fuart : 9600 * 16; + /* Fuart <= Fref: leave it to the core to refuse a higher baud rate */ + fuart = min(fuart, fref); + /* Get Fuart closer to Fref */ fuart *= rounddown_pow_of_two(fref / fuart); diff --git a/drivers/tty/serial/8250/8250_mid.c b/drivers/tty/serial/8250/8250_mid.c index 82656645b8a6..47f820fcd1a4 100644 --- a/drivers/tty/serial/8250/8250_mid.c +++ b/drivers/tty/serial/8250/8250_mid.c @@ -7,6 +7,7 @@ */ #include +#include #include #include #include @@ -209,6 +210,7 @@ static void mid8250_set_termios(struct uart_port *p, struct ktermios *termios, const struct ktermios *old) { unsigned int baud = tty_termios_baud_rate(termios); + struct uart_8250_port *up = up_to_u8250p(p); struct mid8250 *mid = p->private_data; unsigned short ps = 16; unsigned long fuart = baud * ps; @@ -231,11 +233,16 @@ static void mid8250_set_termios(struct uart_port *p, struct ktermios *termios, } rational_best_approximation(fuart, mid->board->freq, w, w, &mul, &div); - p->uartclk = fuart * 16 / ps; /* core uses ps = 16 always */ - writel(ps, p->membase + INTEL_MID_UART_PS); /* set PS */ - writel(mul, p->membase + INTEL_MID_UART_MUL); /* set MUL */ - writel(div, p->membase + INTEL_MID_UART_DIV); + scoped_guard(spinlock_irq, &p->lock) { + p->uartclk = fuart * 16 / ps; /* core uses ps = 16 always */ + + serial8250_wait_for_xmitr(up, UART_LSR_BOTH_EMPTY); + + writel(ps, p->membase + INTEL_MID_UART_PS); /* set PS */ + writel(mul, p->membase + INTEL_MID_UART_MUL); /* set MUL */ + writel(div, p->membase + INTEL_MID_UART_DIV); + } serial8250_do_set_termios(p, termios, old); } @@ -408,3 +415,4 @@ module_pci_driver(mid8250_pci_driver); MODULE_AUTHOR("Intel Corporation"); MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("Intel MID UART driver"); +MODULE_IMPORT_NS("SERIAL_8250"); diff --git a/drivers/tty/serial/8250/8250_port.c b/drivers/tty/serial/8250/8250_port.c index 455d55827ada..4f50e83254f8 100644 --- a/drivers/tty/serial/8250/8250_port.c +++ b/drivers/tty/serial/8250/8250_port.c @@ -1993,7 +1993,7 @@ static bool wait_for_lsr(struct uart_8250_port *up, int bits) } /* Wait for transmitter and holding register to empty with timeout */ -static void wait_for_xmitr(struct uart_8250_port *up, int bits) +void serial8250_wait_for_xmitr(struct uart_8250_port *up, int bits) { unsigned int tmout; @@ -2017,6 +2017,7 @@ static void wait_for_xmitr(struct uart_8250_port *up, int bits) } } } +EXPORT_SYMBOL_NS_GPL(serial8250_wait_for_xmitr, "SERIAL_8250"); #ifdef CONFIG_CONSOLE_POLL /* @@ -2060,7 +2061,7 @@ static void serial8250_put_poll_char(struct uart_port *port, ier = serial_port_in(port, UART_IER); serial8250_clear_IER(up); - wait_for_xmitr(up, UART_LSR_BOTH_EMPTY); + serial8250_wait_for_xmitr(up, UART_LSR_BOTH_EMPTY); /* * Send the character out. */ @@ -2070,7 +2071,7 @@ static void serial8250_put_poll_char(struct uart_port *port, * Finally, wait for transmitter to become empty * and restore the IER */ - wait_for_xmitr(up, UART_LSR_BOTH_EMPTY); + serial8250_wait_for_xmitr(up, UART_LSR_BOTH_EMPTY); serial_port_out(port, UART_IER, ier); } @@ -2185,7 +2186,7 @@ static void serial8250_THRE_test(struct uart_port *port) * Synchronize UART_IER access against the console. */ scoped_guard(uart_port_lock_irqsave, port) { - wait_for_xmitr(up, UART_LSR_THRE); + serial8250_wait_for_xmitr(up, UART_LSR_THRE); serial_port_out_sync(port, UART_IER, UART_IER_THRI); udelay(1); /* allow THRE to set */ iir_noint1 = serial_port_in(port, UART_IIR) & UART_IIR_NO_INT; @@ -3245,7 +3246,7 @@ static void serial8250_console_wait_putchar(struct uart_port *port, unsigned cha { struct uart_8250_port *up = up_to_u8250p(port); - wait_for_xmitr(up, UART_LSR_THRE); + serial8250_wait_for_xmitr(up, UART_LSR_THRE); serial8250_console_putchar(port, ch); } @@ -3386,7 +3387,7 @@ void serial8250_console_write(struct uart_8250_port *up, const char *s, * Finally, wait for transmitter to become empty * and restore the IER */ - wait_for_xmitr(up, UART_LSR_BOTH_EMPTY); + serial8250_wait_for_xmitr(up, UART_LSR_BOTH_EMPTY); if (em485) { mdelay(port->rs485.delay_rts_after_send); diff --git a/drivers/tty/serial/rda-uart.c b/drivers/tty/serial/rda-uart.c index 87fa30d68687..9c1785771cbb 100644 --- a/drivers/tty/serial/rda-uart.c +++ b/drivers/tty/serial/rda-uart.c @@ -471,6 +471,8 @@ static void rda_uart_shutdown(struct uart_port *port) rda_uart_write(port, val, RDA_UART_CTRL); uart_port_unlock_irqrestore(port, flags); + + free_irq(port->irq, port); } static const char *rda_uart_type(struct uart_port *port) diff --git a/drivers/tty/serial/samsung_tty.c b/drivers/tty/serial/samsung_tty.c index 59d58fb743a3..d8887a441d48 100644 --- a/drivers/tty/serial/samsung_tty.c +++ b/drivers/tty/serial/samsung_tty.c @@ -736,14 +736,13 @@ static irqreturn_t s3c24xx_serial_rx_chars_dma(struct s3c24xx_uart_port *ourport s3c24xx_serial_rx_drain_fifo(ourport); - if (tty) { + if (tty) tty_flip_buffer_push(t); - tty_kref_put(tty); - } wr_regl(port, S3C2410_UTRSTAT, S3C2410_UTRSTAT_TIMEOUT); finish: + tty_kref_put(tty); uart_port_unlock(port); return IRQ_HANDLED; @@ -1499,11 +1498,14 @@ static void s3c24xx_serial_set_termios(struct uart_port *port, if (!IS_ERR(ourport->baudclk)) { clk_disable_unprepare(ourport->baudclk); + clk_put(ourport->baudclk); ourport->baudclk = ERR_PTR(-EINVAL); } ourport->baudclk = clk; ourport->baudclk_rate = clk ? clk_get_rate(clk) : 0; + } else { + clk_put(clk); } if (ourport->info->has_divslot) { diff --git a/drivers/tty/serial/serial_core.c b/drivers/tty/serial/serial_core.c index 71c47736a467..ae42a067f20d 100644 --- a/drivers/tty/serial/serial_core.c +++ b/drivers/tty/serial/serial_core.c @@ -135,17 +135,11 @@ static void uart_stop(struct tty_struct *tty) uart_port_unlock_deref(port, flags); } -static void __uart_start(struct uart_state *state) +static void uart_port_start_tx(struct uart_port *port) { - struct uart_port *port = state->uart_port; - struct serial_port_device *port_dev; + struct serial_port_device *port_dev = port->port_dev; int err; - if (!port || port->flags & UPF_DEAD || uart_tx_stopped(port)) - return; - - port_dev = port->port_dev; - /* Increment the runtime PM usage count for the active check below */ err = pm_runtime_get(&port_dev->dev); if (err < 0 && err != -EINPROGRESS) { @@ -164,6 +158,16 @@ static void __uart_start(struct uart_state *state) pm_runtime_put_autosuspend(&port_dev->dev); } +static void __uart_start(struct uart_state *state) +{ + struct uart_port *port = state->uart_port; + + if (!port || port->flags & UPF_DEAD || uart_tx_stopped(port)) + return; + + uart_port_start_tx(port); +} + static void uart_start(struct tty_struct *tty) { struct uart_state *state = tty->driver_data; @@ -722,8 +726,9 @@ static void uart_send_xchar(struct tty_struct *tty, u8 ch) else { guard(uart_port_lock_irqsave)(port); port->x_char = ch; - if (ch) - port->ops->start_tx(port); + /* It goes out even if the transmission is stopped */ + if (ch && !(port->flags & UPF_DEAD)) + uart_port_start_tx(port); } uart_port_deref(port); } diff --git a/drivers/tty/serial/serial_port.c b/drivers/tty/serial/serial_port.c index 2fc48cd63f6c..f2f7cdd3a54c 100644 --- a/drivers/tty/serial/serial_port.c +++ b/drivers/tty/serial/serial_port.c @@ -23,8 +23,8 @@ /* Only considers pending TX for now. Caller must take care of locking */ static int __serial_port_busy(struct uart_port *port) { - return !uart_tx_stopped(port) && - !kfifo_is_empty(&port->state->port.xmit_fifo); + return port->x_char || (!uart_tx_stopped(port) && + !kfifo_is_empty(&port->state->port.xmit_fifo)); } static int serial_port_runtime_resume(struct device *dev) diff --git a/drivers/tty/tty_io.c b/drivers/tty/tty_io.c index 07e6bf5f8c6f..b9f9f731dda0 100644 --- a/drivers/tty/tty_io.c +++ b/drivers/tty/tty_io.c @@ -2996,8 +2996,7 @@ static long tty_compat_ioctl(struct file *file, unsigned int cmd, if (ld->ops->compat_ioctl) retval = ld->ops->compat_ioctl(tty, cmd, arg); if (retval == -ENOIOCTLCMD && ld->ops->ioctl) - retval = ld->ops->ioctl(tty, (unsigned long)compat_ptr(cmd), - arg); + retval = ld->ops->ioctl(tty, cmd, (unsigned long)compat_ptr(arg)); tty_ldisc_deref(ld); return retval; diff --git a/drivers/tty/vt/keyboard.c b/drivers/tty/vt/keyboard.c index d9d8e91c09c9..5ca8ab1566fa 100644 --- a/drivers/tty/vt/keyboard.c +++ b/drivers/tty/vt/keyboard.c @@ -321,15 +321,20 @@ int kbd_rate(struct kbd_repeat *rpt) /* * Helper Functions. + * + * A flip buffer allows one producer at a time, and respond_string() in vt.c + * feeds the same one under the console lock. So take the lock of the port. */ static void put_queue(struct vc_data *vc, int ch) { + guard(spinlock_irqsave)(&vc->port.lock); tty_insert_flip_char(&vc->port, ch, 0); tty_flip_buffer_push(&vc->port); } static void puts_queue(struct vc_data *vc, const char *cp) { + guard(spinlock_irqsave)(&vc->port.lock); tty_insert_flip_string(&vc->port, cp, strlen(cp)); tty_flip_buffer_push(&vc->port); } @@ -589,6 +594,7 @@ static void fn_inc_console(struct vc_data *vc) static void fn_send_intr(struct vc_data *vc) { + guard(spinlock_irqsave)(&vc->port.lock); tty_insert_flip_char(&vc->port, 0, TTY_BREAK); tty_flip_buffer_push(&vc->port); } diff --git a/drivers/tty/vt/vt.c b/drivers/tty/vt/vt.c index 8306744bee4d..8d651028bd41 100644 --- a/drivers/tty/vt/vt.c +++ b/drivers/tty/vt/vt.c @@ -1830,6 +1830,8 @@ static void csi_m(struct vc_data *vc) static void respond_string(const char *p, size_t len, struct tty_port *port) { + /* The keyboard handler feeds the same flip buffer. */ + guard(spinlock_irqsave)(&port->lock); tty_insert_flip_string(port, p, len); tty_flip_buffer_push(port); } diff --git a/drivers/usb/class/cdc-acm.c b/drivers/usb/class/cdc-acm.c index 990482982a28..2191f56598f4 100644 --- a/drivers/usb/class/cdc-acm.c +++ b/drivers/usb/class/cdc-acm.c @@ -294,6 +294,7 @@ static void acm_process_notification(struct acm *acm, unsigned char *buf) unsigned long flags; struct usb_cdc_notification *dr = (struct usb_cdc_notification *)buf; unsigned char *data = buf + sizeof(struct usb_cdc_notification); + struct tty_struct *tty; switch (dr->bNotificationType) { case USB_CDC_NOTIFY_NETWORK_CONNECTION: @@ -320,12 +321,17 @@ static void acm_process_notification(struct acm *acm, unsigned char *buf) difference = acm->ctrlin ^ newctrl; - if ((difference & USB_CDC_SERIAL_STATE_DCD) && acm->port.tty) { - struct tty_ldisc *ld = tty_ldisc_ref(acm->port.tty); - if (ld) { - if (ld->ops->dcd_change) - ld->ops->dcd_change(acm->port.tty, newctrl & USB_CDC_SERIAL_STATE_DCD); - tty_ldisc_deref(ld); + if (difference & USB_CDC_SERIAL_STATE_DCD) { + tty = tty_port_tty_get(&acm->port); + if (tty) { + struct tty_ldisc *ld = tty_ldisc_ref(tty); + + if (ld) { + if (ld->ops->dcd_change) + ld->ops->dcd_change(tty, newctrl & USB_CDC_SERIAL_STATE_DCD); + tty_ldisc_deref(ld); + } + tty_kref_put(tty); } } diff --git a/drivers/usb/dwc3/core.h b/drivers/usb/dwc3/core.h index 7d310c56fe08..b3ff3dec8422 100644 --- a/drivers/usb/dwc3/core.h +++ b/drivers/usb/dwc3/core.h @@ -772,6 +772,7 @@ struct dwc3_ep { #define DWC3_EP_TXFIFO_RESIZED BIT(12) #define DWC3_EP_DELAY_STOP BIT(13) #define DWC3_EP_RESOURCE_ALLOCATED BIT(14) +#define DWC3_EP_PENDING_NOOP_START BIT(15) /* This last one is specific to EP0 */ #define DWC3_EP0_DIR_IN BIT(31) @@ -1687,7 +1688,8 @@ int dwc3_send_gadget_ep_cmd(struct dwc3_ep *dep, unsigned int cmd, int dwc3_send_gadget_generic_command(struct dwc3 *dwc, unsigned int cmd, u32 param); void dwc3_gadget_clear_tx_fifos(struct dwc3 *dwc); -void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status); +void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status, + bool interrupt); #else static inline int dwc3_gadget_init(struct dwc3 *dwc) { return 0; } diff --git a/drivers/usb/dwc3/dwc3-xilinx.c b/drivers/usb/dwc3/dwc3-xilinx.c index c2b8573c2567..8897fbe55474 100644 --- a/drivers/usb/dwc3/dwc3-xilinx.c +++ b/drivers/usb/dwc3/dwc3-xilinx.c @@ -395,13 +395,26 @@ static int __maybe_unused dwc3_xlnx_runtime_idle(struct device *dev) static int __maybe_unused dwc3_xlnx_suspend(struct device *dev) { struct dwc3_xlnx *priv_data = dev_get_drvdata(dev); + int ret; - phy_exit(priv_data->usb3_phy); + ret = phy_power_off(priv_data->usb3_phy); + if (ret < 0) + return ret; + + ret = phy_exit(priv_data->usb3_phy); + if (ret < 0) + goto err_phy_power_on; /* Disable the clocks */ clk_bulk_disable(priv_data->num_clocks, priv_data->clks); return 0; + +err_phy_power_on: + if (phy_power_on(priv_data->usb3_phy)) + dev_err(dev, "failed to restore PHY power after suspend error\n"); + + return ret; } static int __maybe_unused dwc3_xlnx_resume(struct device *dev) @@ -415,15 +428,20 @@ static int __maybe_unused dwc3_xlnx_resume(struct device *dev) ret = phy_init(priv_data->usb3_phy); if (ret < 0) - return ret; + goto err_clk_disable; ret = phy_power_on(priv_data->usb3_phy); if (ret < 0) { phy_exit(priv_data->usb3_phy); - return ret; + goto err_clk_disable; } return 0; + +err_clk_disable: + clk_bulk_disable(priv_data->num_clocks, priv_data->clks); + + return ret; } static const struct dev_pm_ops dwc3_xlnx_dev_pm_ops = { diff --git a/drivers/usb/dwc3/ep0.c b/drivers/usb/dwc3/ep0.c index 5000de8446dc..c44ec40e704a 100644 --- a/drivers/usb/dwc3/ep0.c +++ b/drivers/usb/dwc3/ep0.c @@ -315,7 +315,7 @@ void dwc3_ep0_out_start(struct dwc3 *dwc) if (dwc->connected) dwc3_stop_active_transfer(dwc3_ep, false, true); else - dwc3_remove_requests(dwc, dwc3_ep, -ESHUTDOWN); + dwc3_remove_requests(dwc, dwc3_ep, -ESHUTDOWN, false); } } diff --git a/drivers/usb/dwc3/gadget.c b/drivers/usb/dwc3/gadget.c index ed9f759c9575..96a9930a20d8 100644 --- a/drivers/usb/dwc3/gadget.c +++ b/drivers/usb/dwc3/gadget.c @@ -906,6 +906,54 @@ static int dwc3_gadget_resize_tx_fifos(struct dwc3_ep *dep) return 0; } +static int dwc3_gadget_ep_start_noop_transfer(struct dwc3_ep *dep) +{ + struct dwc3_gadget_ep_cmd_params params; + struct dwc3 *dwc = dep->dwc; + struct dwc3_trb *trb; + dma_addr_t trb_dma; + u32 cmd; + int ret; + + memset(¶ms, 0, sizeof(params)); + trb = &dep->trb_pool[0]; + trb_dma = dwc3_trb_dma_offset(dep, trb); + + params.param0 = upper_32_bits(trb_dma); + params.param1 = lower_32_bits(trb_dma); + + cmd = DWC3_DEPCMD_STARTTRANSFER; + + ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms); + if (ret < 0) + return ret; + + /* + * For streams, at start, there maybe a race where the host primes the + * endpoint before the function driver queues a request to initiate a + * stream. In that case, the controller will not see the prime to + * generate the ERDY and start stream. To workaround this, issue a + * no-op TRB as normal, but end it immediately. As a result, when the + * function driver queues the request, the next START_TRANSFER command + * will cause the controller to generate an ERDY to initiate the + * stream. + */ + dwc3_stop_active_transfer(dep, false, true); + + /* + * All stream eps will reinitiate stream on NoStream rejection. + * + * However, if the controller is capable of TXF_FLUSH_BYPASS, then IN + * direction endpoints will automatically restart the stream without + * the driver initiation. + */ + if (!dep->direction || + !(dwc->hwparams.hwparams9 & DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS)) + dep->flags |= DWC3_EP_FORCE_RESTART_STREAM; + + return 0; +} + /** * __dwc3_gadget_ep_enable - initializes a hw endpoint * @dep: endpoint to be initialized @@ -971,54 +1019,14 @@ static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action) * Issue StartTransfer here with no-op TRB so we can always rely on No * Response Update Transfer command. */ - if (usb_endpoint_xfer_bulk(desc) || - usb_endpoint_xfer_int(desc)) { - struct dwc3_gadget_ep_cmd_params params; - struct dwc3_trb *trb; - dma_addr_t trb_dma; - u32 cmd; - - memset(¶ms, 0, sizeof(params)); - trb = &dep->trb_pool[0]; - trb_dma = dwc3_trb_dma_offset(dep, trb); - - params.param0 = upper_32_bits(trb_dma); - params.param1 = lower_32_bits(trb_dma); - - cmd = DWC3_DEPCMD_STARTTRANSFER; - - ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms); - if (ret < 0) - return ret; - - if (dep->stream_capable) { - /* - * For streams, at start, there maybe a race where the - * host primes the endpoint before the function driver - * queues a request to initiate a stream. In that case, - * the controller will not see the prime to generate the - * ERDY and start stream. To workaround this, issue a - * no-op TRB as normal, but end it immediately. As a - * result, when the function driver queues the request, - * the next START_TRANSFER command will cause the - * controller to generate an ERDY to initiate the - * stream. - */ - dwc3_stop_active_transfer(dep, false, true); - - /* - * All stream eps will reinitiate stream on NoStream - * rejection. - * - * However, if the controller is capable of - * TXF_FLUSH_BYPASS, then IN direction endpoints will - * automatically restart the stream without the driver - * initiation. - */ - if (!dep->direction || - !(dwc->hwparams.hwparams9 & - DWC3_GHWPARAMS9_DEV_TXF_FLUSH_BYPASS)) - dep->flags |= DWC3_EP_FORCE_RESTART_STREAM; + if (dep->stream_capable) { + if (dep->flags & (DWC3_EP_END_TRANSFER_PENDING | + DWC3_EP_DELAY_STOP)) { + dep->flags |= DWC3_EP_PENDING_NOOP_START; + } else { + ret = dwc3_gadget_ep_start_noop_transfer(dep); + if (ret < 0) + return ret; } } @@ -1028,16 +1036,21 @@ static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep, unsigned int action) return 0; } -void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status) +void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep, int status, + bool interrupt) { struct dwc3_request *req; - dwc3_stop_active_transfer(dep, false, false); + dwc3_stop_active_transfer(dep, false, interrupt); /* If endxfer is delayed, avoid unmapping requests */ if (dep->flags & DWC3_EP_DELAY_STOP) return; + /* Give the controller time to stop accessing the request buffers */ + if (dep->flags & DWC3_EP_END_TRANSFER_PENDING) + mdelay(1); + /* - giveback all requests to gadget driver */ while (!list_empty(&dep->started_list)) { req = next_request(&dep->started_list); @@ -1084,7 +1097,9 @@ static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep) reg &= ~DWC3_DALEPENA_EP(dep->number); dwc3_writel(dwc, DWC3_DALEPENA, reg); - dwc3_remove_requests(dwc, dep, -ESHUTDOWN); + dep->flags &= ~DWC3_EP_ENABLED; + + dwc3_remove_requests(dwc, dep, -ESHUTDOWN, true); dep->stream_capable = false; dep->type = 0; @@ -1096,6 +1111,15 @@ static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep) */ if (dep->flags & DWC3_EP_DELAY_STOP) mask |= (DWC3_EP_DELAY_STOP | DWC3_EP_TRANSFER_STARTED); + + /* + * The End Transfer command is still in progress. Do not clear the + * flags, so that the ep is only rearmed once the command completes. + */ + if (dep->flags & DWC3_EP_END_TRANSFER_PENDING) + mask |= (DWC3_EP_END_TRANSFER_PENDING | + DWC3_EP_TRANSFER_STARTED); + dep->flags &= mask; /* Clear out the ep descriptors for non-ep0 */ @@ -1751,6 +1775,8 @@ static int __dwc3_gadget_get_frame(struct dwc3 *dwc) return DWC3_DSTS_SOFFN(reg); } +static void dwc3_schedule_err_recovery(struct dwc3 *dwc); + /** * __dwc3_stop_active_transfer - stop the current active transfer * @dep: isoc endpoint @@ -1794,11 +1820,14 @@ static int __dwc3_stop_active_transfer(struct dwc3_ep *dep, bool force, bool int dev_err_ratelimited(dep->dwc->dev, "end transfer failed: %d\n", ret); + if (ret == -ETIMEDOUT && dep->dwc->err_state == DWC3_ERR_NONE) + dwc3_schedule_err_recovery(dep->dwc); + dep->resource_index = 0; - if (!interrupt) + if (!interrupt || (ret && ret != -ETIMEDOUT)) dep->flags &= ~DWC3_EP_TRANSFER_STARTED; - else if (!ret) + else dep->flags |= DWC3_EP_END_TRANSFER_PENDING; dep->flags &= ~DWC3_EP_DELAY_STOP; @@ -1990,7 +2019,8 @@ static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req) { struct dwc3 *dwc = dep->dwc; - if (!dep->endpoint.desc || !dwc->pullups_connected || !dwc->connected) { + if (!(dep->flags & DWC3_EP_ENABLED) || !dep->endpoint.desc || + !dwc->pullups_connected || !dwc->connected) { dev_dbg(dwc->dev, "%s: can't queue to disabled endpoint\n", dep->name); return -ESHUTDOWN; @@ -2547,7 +2577,7 @@ static void dwc3_stop_active_transfers(struct dwc3 *dwc) if (!dep) continue; - dwc3_remove_requests(dwc, dep, -ESHUTDOWN); + dwc3_remove_requests(dwc, dep, -ESHUTDOWN, false); } } @@ -2947,6 +2977,7 @@ static int __dwc3_gadget_start(struct dwc3 *dwc) { struct dwc3_ep *dep; int ret = 0; + u32 epnum; u32 reg; /* @@ -3004,6 +3035,15 @@ static int __dwc3_gadget_start(struct dwc3 *dwc) return ret; } + for (epnum = 2; epnum < dwc->num_eps; epnum++) { + dep = dwc->eps[epnum]; + if (!dep) + continue; + + dep->flags &= (DWC3_EP_TXFIFO_RESIZED | + DWC3_EP_RESOURCE_ALLOCATED); + } + dep = dwc->eps[0]; dep->flags = 0; ret = __dwc3_gadget_ep_enable(dep, DWC3_DEPCFG_ACTION_INIT); @@ -3861,6 +3901,7 @@ static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep, if (dep->stream_capable) dep->flags |= DWC3_EP_IGNORE_NEXT_NOSTREAM; + dep->flags &= ~DWC3_EP_DELAY_STOP; dep->flags &= ~DWC3_EP_END_TRANSFER_PENDING; dep->flags &= ~DWC3_EP_TRANSFER_STARTED; dwc3_gadget_ep_cleanup_cancelled_requests(dep); @@ -3883,7 +3924,16 @@ static void dwc3_gadget_endpoint_command_complete(struct dwc3_ep *dep, dwc3_ep0_send_delayed_status(dwc); } + if (dep->flags & DWC3_EP_PENDING_NOOP_START) { + dep->flags &= ~DWC3_EP_PENDING_NOOP_START; + + if (!(dep->flags & DWC3_EP_DELAY_START) && + (dep->flags & DWC3_EP_ENABLED)) + dwc3_gadget_ep_start_noop_transfer(dep); + } + if ((dep->flags & DWC3_EP_DELAY_START) && + (dep->flags & DWC3_EP_ENABLED) && !usb_endpoint_xfer_isoc(dep->endpoint.desc)) __dwc3_gadget_kick_transfer(dep); diff --git a/drivers/usb/gadget/function/f_mass_storage.c b/drivers/usb/gadget/function/f_mass_storage.c index 584e7ba31603..572015591b81 100644 --- a/drivers/usb/gadget/function/f_mass_storage.c +++ b/drivers/usb/gadget/function/f_mass_storage.c @@ -2668,8 +2668,9 @@ static ssize_t nofua_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct fsg_lun *curlun = fsg_lun_from_dev(dev); + struct rw_semaphore *filesem = dev_get_drvdata(dev); - return fsg_store_nofua(curlun, buf, count); + return fsg_store_nofua(curlun, filesem, buf, count); } static ssize_t file_store(struct device *dev, struct device_attribute *attr, @@ -3247,7 +3248,10 @@ static ssize_t fsg_lun_opts_nofua_show(struct config_item *item, char *page) static ssize_t fsg_lun_opts_nofua_store(struct config_item *item, const char *page, size_t len) { - return fsg_store_nofua(to_fsg_lun_opts(item)->lun, page, len); + struct fsg_lun_opts *opts = to_fsg_lun_opts(item); + struct fsg_opts *fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent); + + return fsg_store_nofua(opts->lun, &fsg_opts->common->filesem, page, len); } CONFIGFS_ATTR(fsg_lun_opts_, nofua); diff --git a/drivers/usb/gadget/function/f_midi.c b/drivers/usb/gadget/function/f_midi.c index e1d1d2b16eaf..e747b7142095 100644 --- a/drivers/usb/gadget/function/f_midi.c +++ b/drivers/usb/gadget/function/f_midi.c @@ -420,6 +420,7 @@ static void f_midi_disable(struct usb_function *f) struct f_midi *midi = func_to_midi(f); struct usb_composite_dev *cdev = f->config->cdev; struct usb_request *req = NULL; + unsigned long flags; DBG(cdev, "disable\n"); @@ -431,8 +432,10 @@ static void f_midi_disable(struct usb_function *f) usb_ep_disable(midi->out_ep); /* release IN requests */ + spin_lock_irqsave(&midi->transmit_lock, flags); while (kfifo_get(&midi->in_req_fifo, &req)) free_ep_req(midi->in_ep, req); + spin_unlock_irqrestore(&midi->transmit_lock, flags); f_midi_drop_out_substreams(midi); } @@ -661,6 +664,7 @@ static int f_midi_do_transmit(struct f_midi *midi, struct usb_ep *ep) ERROR(midi, "%s failed to queue req: %d\n", midi->in_ep->name, err); req->length = 0; /* Re-use request next time. */ + return err; } else { /* Upon success, put request at the back of the queue. */ kfifo_skip(&midi->in_req_fifo); diff --git a/drivers/usb/gadget/function/f_ncm.c b/drivers/usb/gadget/function/f_ncm.c index cc435680db68..587838d6e65b 100644 --- a/drivers/usb/gadget/function/f_ncm.c +++ b/drivers/usb/gadget/function/f_ncm.c @@ -1148,6 +1148,7 @@ static enum hrtimer_restart ncm_tx_timeout(struct hrtimer *data) { struct f_ncm *ncm = container_of(data, struct f_ncm, task_timer); struct net_device *netdev = READ_ONCE(ncm->netdev); + netdev_tx_t ret; if (netdev) { /* XXX This allowance of a NULL skb argument to ndo_start_xmit @@ -1158,7 +1159,11 @@ static enum hrtimer_restart ncm_tx_timeout(struct hrtimer *data) * * This will call directly into u_ether's eth_start_xmit() */ - netdev->netdev_ops->ndo_start_xmit(NULL, netdev); + ret = netdev->netdev_ops->ndo_start_xmit(NULL, netdev); + if (ret == NETDEV_TX_BUSY) { + hrtimer_forward_now(data, TX_TIMEOUT_NSECS); + return HRTIMER_RESTART; + } } return HRTIMER_NORESTART; } diff --git a/drivers/usb/gadget/function/storage_common.c b/drivers/usb/gadget/function/storage_common.c index 75831f2c7abe..51a70f2abe57 100644 --- a/drivers/usb/gadget/function/storage_common.c +++ b/drivers/usb/gadget/function/storage_common.c @@ -415,7 +415,8 @@ ssize_t fsg_store_ro(struct fsg_lun *curlun, struct rw_semaphore *filesem, } EXPORT_SYMBOL_GPL(fsg_store_ro); -ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count) +ssize_t fsg_store_nofua(struct fsg_lun *curlun, struct rw_semaphore *filesem, + const char *buf, size_t count) { bool nofua; int ret; @@ -425,8 +426,10 @@ ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count) return ret; /* Sync data when switching from async mode to sync */ - if (!nofua && curlun->nofua) + if (!nofua && curlun->nofua) { + guard(rwsem_read)(filesem); fsg_lun_fsync_sub(curlun); + } curlun->nofua = nofua; diff --git a/drivers/usb/gadget/function/storage_common.h b/drivers/usb/gadget/function/storage_common.h index 11ac785d5eee..347a86b8d6e4 100644 --- a/drivers/usb/gadget/function/storage_common.h +++ b/drivers/usb/gadget/function/storage_common.h @@ -210,7 +210,8 @@ ssize_t fsg_show_cdrom(struct fsg_lun *curlun, char *buf); ssize_t fsg_show_removable(struct fsg_lun *curlun, char *buf); ssize_t fsg_store_ro(struct fsg_lun *curlun, struct rw_semaphore *filesem, const char *buf, size_t count); -ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count); +ssize_t fsg_store_nofua(struct fsg_lun *curlun, struct rw_semaphore *filesem, + const char *buf, size_t count); ssize_t fsg_store_file(struct fsg_lun *curlun, struct rw_semaphore *filesem, const char *buf, size_t count); ssize_t fsg_store_cdrom(struct fsg_lun *curlun, struct rw_semaphore *filesem, diff --git a/drivers/usb/gadget/function/u_serial.c b/drivers/usb/gadget/function/u_serial.c index 1cce5317181a..e466552d4921 100644 --- a/drivers/usb/gadget/function/u_serial.c +++ b/drivers/usb/gadget/function/u_serial.c @@ -70,10 +70,28 @@ * gserial->ioport == usb_ep->driver_data ... gs_port * gs_port->port_usb ... gserial * - * gs_port <---> tty_struct ... links will be null when the TTY file - * isn't opened; managed by gs_open()/gs_close() - * gserial->port_tty ... tty_struct - * tty_struct->driver_data ... gserial + * gs_port <---> tty_struct: + * tty->driver_data refers to gs_port from install through cleanup, + * pinning the port via tty_port reference counting. + * gs_port->port.tty exists only while the port is open. + * + * Each entry in ports[] is guarded by ports[i].lock and models three states: + * - Free: !port && !reserved + * - Published: port && reserved + * - Retiring: !port && reserved + * + * A minor remains reserved until gs_port_destruct() runs upon final tty_port + * release, preventing minor reuse while cleanup of the installed TTY is still + * underway. The owner reference is retained through device unregister so the + * destructor releases the reservation only after device teardown is complete. + * + * open_close_failures tracks failed gs_open() calls where port->port.count + * was not incremented. The TTY core calls gs_close() on open failure to tear + * down the tty; tracking failures as aggregate credits allows gs_close() to + * consume a credit and exit without decrementing port->port.count. Credits + * are aggregate rather than paired with individual files (another gs_close() + * can consume a failed open's credit before that file's own close runs). + * It is protected by tty_lock. */ /* RX and TX queues can buffer QUEUE_SIZE packets before they hit the @@ -128,6 +146,7 @@ struct gs_port { wait_queue_head_t close_wait; bool suspended; /* port suspended */ bool start_delayed; /* delay start when suspended */ + unsigned int open_close_failures; /* protected by tty_lock */ struct async_icount icount; /* REVISIT this state ... */ @@ -135,8 +154,9 @@ struct gs_port { }; static struct portmaster { - struct mutex lock; /* protect open/close */ + struct mutex lock; /* protect open/close and port slot */ struct gs_port *port; + bool reserved; } ports[MAX_U_SERIAL_PORTS]; #define GS_CLOSE_TIMEOUT 15 /* seconds */ @@ -603,22 +623,60 @@ static int gserial_wakeup_host(struct gserial *gser) /* TTY Driver */ +static int gs_install(struct tty_driver *driver, struct tty_struct *tty) +{ + struct gs_port *port; + struct tty_port *tport; + int ret; + + mutex_lock(&ports[tty->index].lock); + port = ports[tty->index].port; + if (!port) { + mutex_unlock(&ports[tty->index].lock); + return -ENODEV; + } + + tport = tty_port_get(&port->port); + if (!tport) { + mutex_unlock(&ports[tty->index].lock); + return -ENODEV; + } + + ret = tty_port_install(tport, driver, tty); + if (ret) { + mutex_unlock(&ports[tty->index].lock); + tty_port_put(tport); + return ret; + } + + tty->driver_data = port; + mutex_unlock(&ports[tty->index].lock); + + return 0; +} + +static void gs_cleanup(struct tty_struct *tty) +{ + tty_port_put(tty->port); +} + /* - * gs_open sets up the link between a gs_port and its associated TTY. - * That link is broken *only* by TTY close(), and all driver methods - * know that. + * gs_open associates an open TTY with its gs_port. + * + * There are two TTY-to-port relationships: port->port.tty exists from the + * first successful open until final close, while tty->driver_data is assigned + * during gs_install() and remains valid through gs_cleanup(). */ static int gs_open(struct tty_struct *tty, struct file *file) { int port_num = tty->index; - struct gs_port *port; + struct gs_port *port = tty->driver_data; int status = 0; mutex_lock(&ports[port_num].lock); - port = ports[port_num].port; - if (!port) { + if (ports[port_num].port != port) { status = -ENODEV; - goto out; + goto fail_unlock; } spin_lock_irq(&port->port_lock); @@ -638,7 +696,7 @@ static int gs_open(struct tty_struct *tty, struct file *file) if (status) { pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n", port_num, tty, file); - goto out; + goto fail_unlock; } spin_lock_irq(&port->port_lock); @@ -648,7 +706,6 @@ static int gs_open(struct tty_struct *tty, struct file *file) if (port->port.count++) goto exit_unlock_port; - tty->driver_data = port; port->port.tty = tty; /* if connected, start the I/O stream */ @@ -672,7 +729,11 @@ static int gs_open(struct tty_struct *tty, struct file *file) exit_unlock_port: spin_unlock_irq(&port->port_lock); -out: + mutex_unlock(&ports[port_num].lock); + return status; + +fail_unlock: + port->open_close_failures++; mutex_unlock(&ports[port_num].lock); return status; } @@ -695,6 +756,14 @@ static void gs_close(struct tty_struct *tty, struct file *file) struct gs_port *port = tty->driver_data; struct gserial *gser; + if (!port) + return; + + if (port->open_close_failures > 0) { + port->open_close_failures--; + return; + } + spin_lock_irq(&port->port_lock); if (port->port.count != 1) { @@ -909,8 +978,10 @@ static int gs_get_icount(struct tty_struct *tty, } static const struct tty_operations gs_tty_ops = { + .install = gs_install, .open = gs_open, .close = gs_close, + .cleanup = gs_cleanup, .write = gs_write, .put_char = gs_put_char, .flush_chars = gs_flush_chars, @@ -1203,14 +1274,41 @@ static void gs_console_exit(struct gs_port *port) #endif -static int +static void gs_port_destruct(struct tty_port *tport) +{ + struct gs_port *port = container_of(tport, struct gs_port, port); + unsigned int port_num = port->port_num; + + mutex_lock(&ports[port_num].lock); + if (WARN_ON(ports[port_num].port)) + ports[port_num].port = NULL; + WARN_ON(!ports[port_num].reserved); + if (gs_tty_driver) + gs_tty_driver->ports[port_num] = NULL; + ports[port_num].reserved = false; + mutex_unlock(&ports[port_num].lock); + + kfifo_free(&port->port_write_buf); + kfree(port); +} + +static const struct tty_port_operations gs_port_ops = { + .destruct = gs_port_destruct, +}; + +static struct gs_port * gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding) { struct gs_port *port; int ret = 0; mutex_lock(&ports[port_num].lock); - if (ports[port_num].port) { + if (WARN_ON_ONCE(ports[port_num].port && !ports[port_num].reserved)) { + ret = -EBUSY; + goto out; + } + + if (ports[port_num].reserved) { ret = -EBUSY; goto out; } @@ -1222,6 +1320,7 @@ gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding) } tty_port_init(&port->port); + port->port.ops = &gs_port_ops; spin_lock_init(&port->port_lock); init_waitqueue_head(&port->drain_wait); init_waitqueue_head(&port->close_wait); @@ -1235,10 +1334,14 @@ gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding) port->port_num = port_num; port->port_line_coding = *coding; + ports[port_num].reserved = true; ports[port_num].port = port; + mutex_unlock(&ports[port_num].lock); + return port; + out: mutex_unlock(&ports[port_num].lock); - return ret; + return ERR_PTR(ret); } static int gs_closed(struct gs_port *port) @@ -1258,8 +1361,7 @@ static void gserial_free_port(struct gs_port *port) /* wait for old opens to finish */ wait_event(port->close_wait, gs_closed(port)); WARN_ON(port->port_usb != NULL); - tty_port_destroy(&port->port); - kfree(port); + tty_port_put(&port->port); } void gserial_free_line(unsigned char port_num) @@ -1276,15 +1378,15 @@ void gserial_free_line(unsigned char port_num) ports[port_num].port = NULL; mutex_unlock(&ports[port_num].lock); - gserial_free_port(port); tty_unregister_device(gs_tty_driver, port_num); + gserial_free_port(port); } EXPORT_SYMBOL_GPL(gserial_free_line); int gserial_alloc_line_no_console(unsigned char *line_num) { struct usb_cdc_line_coding coding; - struct gs_port *port; + struct gs_port *port = ERR_PTR(-EBUSY); struct device *tty_dev; int ret; int port_num; @@ -1295,19 +1397,20 @@ int gserial_alloc_line_no_console(unsigned char *line_num) coding.bDataBits = USB_CDC_1_STOP_BITS; for (port_num = 0; port_num < MAX_U_SERIAL_PORTS; port_num++) { - ret = gs_port_alloc(port_num, &coding); - if (ret == -EBUSY) - continue; - if (ret) + port = gs_port_alloc(port_num, &coding); + if (IS_ERR(port)) { + ret = PTR_ERR(port); + if (ret == -EBUSY) + continue; return ret; + } break; } - if (ret) - return ret; + if (IS_ERR(port)) + return PTR_ERR(port); /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */ - port = ports[port_num].port; tty_dev = tty_port_register_device(&port->port, gs_tty_driver, port_num, NULL); if (IS_ERR(tty_dev)) { @@ -1316,14 +1419,15 @@ int gserial_alloc_line_no_console(unsigned char *line_num) ret = PTR_ERR(tty_dev); mutex_lock(&ports[port_num].lock); + WARN_ON(ports[port_num].port != port); ports[port_num].port = NULL; mutex_unlock(&ports[port_num].lock); - gserial_free_port(port); - goto err; + tty_port_put(&port->port); + return ret; } + *line_num = port_num; -err: - return ret; + return 0; } EXPORT_SYMBOL_GPL(gserial_alloc_line_no_console); diff --git a/drivers/usb/host/pci-quirks.c b/drivers/usb/host/pci-quirks.c index ba158d63bb8b..1363c3502f98 100644 --- a/drivers/usb/host/pci-quirks.c +++ b/drivers/usb/host/pci-quirks.c @@ -1194,10 +1194,11 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) && pdev->device == 0x0014)) { val = (val | XHCI_HC_OS_OWNED) & ~XHCI_HC_BIOS_OWNED; writel(val, base + ext_cap_offset); - } - - /* If the BIOS owns the HC, signal that the OS wants it, and wait */ - if (val & XHCI_HC_BIOS_OWNED) { + } else { + /* + * Perform the standard handoff and leave OS ownership set to + * keep the BIOS at bay during subsequent suspends. + */ writel(val | XHCI_HC_OS_OWNED, base + ext_cap_offset); /* Wait for 1 second with 10 microsecond polling interval */ @@ -1209,7 +1210,9 @@ static void quirk_usb_handoff_xhci(struct pci_dev *pdev) dev_warn(&pdev->dev, "xHCI BIOS handoff failed (BIOS bug ?) %08x\n", val); - writel(val & ~XHCI_HC_BIOS_OWNED, base + ext_cap_offset); + writel((val | XHCI_HC_OS_OWNED) & + ~XHCI_HC_BIOS_OWNED, + base + ext_cap_offset); } } diff --git a/drivers/usb/host/xhci.c b/drivers/usb/host/xhci.c index b894ba988a3d..5a870aec94c8 100644 --- a/drivers/usb/host/xhci.c +++ b/drivers/usb/host/xhci.c @@ -4299,7 +4299,7 @@ int xhci_alloc_dev(struct usb_hcd *hcd, struct usb_device *udev) return 1; disable_slot: - xhci_disable_and_free_slot(xhci, udev->slot_id); + xhci_disable_and_free_slot(xhci, slot_id); return 0; } diff --git a/drivers/usb/misc/usbtest.c b/drivers/usb/misc/usbtest.c index a015fbe4fc35..7ebbe2aaff41 100644 --- a/drivers/usb/misc/usbtest.c +++ b/drivers/usb/misc/usbtest.c @@ -466,6 +466,9 @@ static int simple_io( int retval = 0; unsigned long expire; + if (vary && !max) + return -EINVAL; + urb->context = &completion; while (retval == 0 && iterations-- > 0) { init_completion(&completion); diff --git a/drivers/usb/serial/garmin_gps.c b/drivers/usb/serial/garmin_gps.c index 614de0c2f5f2..f1b90d348d4a 100644 --- a/drivers/usb/serial/garmin_gps.c +++ b/drivers/usb/serial/garmin_gps.c @@ -749,11 +749,7 @@ static int nat_receive(struct garmin_data *garmin_data_p, len = GARMIN_PKTHDR_LENGTH; if (len >= GPS_IN_BUFSIZ) { - /* seems to be an invalid packet, ignore rest - of input */ - dev_dbg(&garmin_data_p->port->dev, - "%s - packet size too large: %d\n", - __func__, len); + /* should never end up here given the dlen check below */ garmin_data_p->insize = 0; count = 0; result = -EINVPKT; @@ -772,8 +768,17 @@ static int nat_receive(struct garmin_data *garmin_data_p, /* do we have a complete packet ? */ if (garmin_data_p->insize >= GARMIN_PKTHDR_LENGTH) { - len = GARMIN_PKTHDR_LENGTH+ - getDataLength(garmin_data_p->inbuffer); + u32 dlen = getDataLength(garmin_data_p->inbuffer); + + if (dlen >= GPS_IN_BUFSIZ - GARMIN_PKTHDR_LENGTH) { + /* invalid packet, ignore rest of input */ + dev_dbg(&garmin_data_p->port->dev, "%s - invalid length: %u\n", + __func__, dlen); + garmin_data_p->insize = 0; + result = -EINVPKT; + break; + } + len = GARMIN_PKTHDR_LENGTH + dlen; if (garmin_data_p->insize >= len) { garmin_write_bulk(garmin_data_p->port, garmin_data_p->inbuffer, @@ -821,10 +826,9 @@ static void priv_status_resp(struct usb_serial_port *port) * Garmin specific driver functions ******************************************************************************/ -static int process_resetdev_request(struct usb_serial_port *port) +static void process_resetdev_request(struct usb_serial_port *port) { unsigned long flags; - int status; struct garmin_data *garmin_data_p = usb_get_serial_port_data(port); spin_lock_irqsave(&garmin_data_p->lock, flags); @@ -833,13 +837,8 @@ static int process_resetdev_request(struct usb_serial_port *port) garmin_data_p->serial_num = 0; spin_unlock_irqrestore(&garmin_data_p->lock, flags); - usb_kill_urb(port->interrupt_in_urb); - dev_dbg(&port->dev, "%s - usb_reset_device\n", __func__); - status = usb_reset_device(port->serial->dev); - if (status) - dev_dbg(&port->dev, "%s - usb_reset_device failed: %d\n", - __func__, status); - return status; + dev_dbg(&port->dev, "%s - usb_queue_reset_device\n", __func__); + usb_queue_reset_device(port->serial->interface); } diff --git a/drivers/usb/serial/io_edgeport.c b/drivers/usb/serial/io_edgeport.c index 9b8fb8467b53..f03465bef02f 100644 --- a/drivers/usb/serial/io_edgeport.c +++ b/drivers/usb/serial/io_edgeport.c @@ -168,6 +168,7 @@ struct edgeport_port { struct urb *write_urb; /* write URB for this port */ bool write_in_progress; /* 'true' while a write URB is outstanding */ spinlock_t ep_lock; + struct mutex mutex; __u8 shadowLCR; /* last LCR value received */ __u8 shadowMCR; /* last MCR value received */ @@ -225,6 +226,7 @@ struct edgeport_serial { __u8 rxStatusParam; /* the receive status parameter */ __s16 rxBytesRemaining; /* the number of port bytes left to read */ struct usb_serial *serial; /* loop back to the owner of this object */ + struct usb_anchor cmd_anchor; }; /* baud rate information */ @@ -261,9 +263,6 @@ static const struct divisor_table_entry divisor_table[] = { { 230400, 1}, }; -/* Number of outstanding Command Write Urbs */ -static atomic_t CmdUrbs = ATOMIC_INIT(0); - /* function prototypes */ @@ -281,8 +280,7 @@ static void handle_new_lsr(struct edgeport_port *edge_port, __u8 lsrData, static int send_iosp_ext_cmd(struct edgeport_port *edge_port, __u8 command, __u8 param); static int calc_baud_rate_divisor(struct device *dev, int baud_rate, int *divisor); -static void change_port_settings(struct tty_struct *tty, - struct edgeport_port *edge_port, +static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port, const struct ktermios *old_termios); static int send_cmd_write_uart_register(struct edgeport_port *edge_port, __u8 regNum, __u8 regValue); @@ -777,11 +775,6 @@ static void edge_bulk_out_cmd_callback(struct urb *urb) struct device *dev = &urb->dev->dev; int status = urb->status; - atomic_dec(&CmdUrbs); - dev_dbg(dev, "%s - FREE URB %p (outstanding %d)\n", __func__, urb, - atomic_read(&CmdUrbs)); - - /* clean up the transfer buffer */ kfree(urb->transfer_buffer); @@ -877,22 +870,22 @@ static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) } } - /* initialize our wait queues */ - init_waitqueue_head(&edge_port->wait_open); - init_waitqueue_head(&edge_port->wait_chase); - init_waitqueue_head(&edge_port->wait_command); - /* initialize our port settings */ + spin_lock_irq(&edge_port->ep_lock); edge_port->txCredits = 0; /* Can't send any data yet */ + edge_port->maxTxCredits = 0; + edge_port->openPending = true; + spin_unlock_irq(&edge_port->ep_lock); + /* Must always set this bit to enable ints! */ + mutex_lock(&edge_port->mutex); edge_port->shadowMCR = MCR_MASTER_IE; + mutex_unlock(&edge_port->mutex); + edge_port->chaseResponsePending = false; /* send a open port command */ - edge_port->openPending = true; - edge_port->open = false; response = send_iosp_ext_cmd(edge_port, IOSP_CMD_OPEN_PORT, 0); - if (response < 0) { dev_err(dev, "%s - error sending open port command\n", __func__); edge_port->openPending = false; @@ -902,8 +895,7 @@ static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) /* now wait for the port to be completely opened */ wait_event_timeout(edge_port->wait_open, !edge_port->openPending, OPEN_TIMEOUT); - - if (!edge_port->open) { + if (edge_port->openPending) { /* open timed out */ dev_dbg(dev, "%s - open timeout\n", __func__); edge_port->openPending = false; @@ -931,6 +923,13 @@ static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) return -ENOMEM; } + if (tty) + edge_set_termios(tty, port, NULL); + + spin_lock_irq(&edge_port->ep_lock); + edge_port->open = true; + spin_unlock_irq(&edge_port->ep_lock); + dev_dbg(dev, "%s - Initialize TX fifo to %d bytes\n", __func__, edge_port->maxTxCredits); @@ -1090,7 +1089,9 @@ static void edge_close(struct usb_serial_port *port) /* port->close = true; */ edge_port->closePending = false; + spin_lock_irq(&edge_port->ep_lock); edge_port->open = false; + spin_unlock_irq(&edge_port->ep_lock); edge_port->openPending = false; usb_kill_urb(edge_port->write_urb); @@ -1132,6 +1133,12 @@ static int edge_write(struct tty_struct *tty, struct usb_serial_port *port, spin_lock_irqsave(&edge_port->ep_lock, flags); + /* avoid accessing freed fifo if tty_wakeup() races with close() */ + if (!edge_port->open) { + spin_unlock_irqrestore(&edge_port->ep_lock, flags); + return 0; + } + /* calculate number of bytes to put in fifo */ copySize = min_t(unsigned int, count, (edge_port->txCredits - fifo->count)); @@ -1395,9 +1402,11 @@ static void edge_throttle(struct tty_struct *tty) /* if we are implementing RTS/CTS, toggle that line */ if (C_CRTSCTS(tty)) { + mutex_lock(&edge_port->mutex); edge_port->shadowMCR &= ~MCR_RTS; status = send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); if (status != 0) return; } @@ -1432,37 +1441,15 @@ static void edge_unthrottle(struct tty_struct *tty) } /* if we are implementing RTS/CTS, toggle that line */ if (C_CRTSCTS(tty)) { + mutex_lock(&edge_port->mutex); edge_port->shadowMCR |= MCR_RTS; send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); } } -/***************************************************************************** - * SerialSetTermios - * this function is called by the tty driver when it wants to change - * the termios structure - *****************************************************************************/ -static void edge_set_termios(struct tty_struct *tty, - struct usb_serial_port *port, - const struct ktermios *old_termios) -{ - struct edgeport_port *edge_port = usb_get_serial_port_data(port); - - if (edge_port == NULL) - return; - - if (!edge_port->open) { - dev_dbg(&port->dev, "%s - port not opened\n", __func__); - return; - } - - /* change the port settings to the new ones specified */ - change_port_settings(tty, edge_port, old_termios); -} - - /***************************************************************************** * get_lsr_info - get line status register info * @@ -1499,6 +1486,7 @@ static int edge_tiocmset(struct tty_struct *tty, struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned int mcr; + mutex_lock(&edge_port->mutex); mcr = edge_port->shadowMCR; if (set & TIOCM_RTS) mcr |= MCR_RTS; @@ -1517,6 +1505,7 @@ static int edge_tiocmset(struct tty_struct *tty, edge_port->shadowMCR = mcr; send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); return 0; } @@ -1530,6 +1519,7 @@ static int edge_tiocmget(struct tty_struct *tty) unsigned int mcr; msr = edge_port->shadowMSR; + mutex_lock(&edge_port->mutex); mcr = edge_port->shadowMCR; result = ((mcr & MCR_DTR) ? TIOCM_DTR: 0) /* 0x002 */ | ((mcr & MCR_RTS) ? TIOCM_RTS: 0) /* 0x004 */ @@ -1537,6 +1527,7 @@ static int edge_tiocmget(struct tty_struct *tty) | ((msr & EDGEPORT_MSR_CD) ? TIOCM_CAR: 0) /* 0x040 */ | ((msr & EDGEPORT_MSR_RI) ? TIOCM_RI: 0) /* 0x080 */ | ((msr & EDGEPORT_MSR_DSR) ? TIOCM_DSR: 0); /* 0x100 */ + mutex_unlock(&edge_port->mutex); return result; } @@ -1752,9 +1743,9 @@ static void process_rcvd_status(struct edgeport_serial *edge_serial, { struct usb_serial_port *port; struct edgeport_port *edge_port; - struct tty_struct *tty; struct device *dev; __u8 code = edge_serial->rxStatusCode; + unsigned long flags; /* switch the port pointer to the one being currently talked about */ if (edge_serial->rxPort >= edge_serial->serial->num_ports) @@ -1798,24 +1789,22 @@ static void process_rcvd_status(struct edgeport_serial *edge_serial, } if (code == IOSP_STATUS_OPEN_RSP) { + spin_lock_irqsave(&edge_port->ep_lock, flags); + /* reject stray open responses to avoid FIFO corruption */ + if (!edge_port->openPending) { + spin_unlock_irqrestore(&edge_port->ep_lock, flags); + return; + } edge_port->txCredits = GET_TX_BUFFER_SIZE(byte3); edge_port->maxTxCredits = edge_port->txCredits; dev_dbg(dev, "%s - Port %u Open Response Initial MSR = %02x TxBufferSize = %d\n", __func__, edge_serial->rxPort, byte2, edge_port->txCredits); handle_new_msr(edge_port, byte2); - /* send the current line settings to the port so we are - in sync with any further termios calls */ - tty = tty_port_tty_get(&edge_port->port->port); - if (tty) { - change_port_settings(tty, - edge_port, &tty->termios); - tty_kref_put(tty); - } - /* we have completed the open */ edge_port->openPending = false; - edge_port->open = true; + spin_unlock_irqrestore(&edge_port->ep_lock, flags); + wake_up(&edge_port->wait_open); return; } @@ -2143,24 +2132,21 @@ static int write_cmd_usb(struct edgeport_port *edge_port, if (!urb) return -ENOMEM; - atomic_inc(&CmdUrbs); - dev_dbg(dev, "%s - ALLOCATE URB %p (outstanding %d)\n", - __func__, urb, atomic_read(&CmdUrbs)); - usb_fill_bulk_urb(urb, edge_serial->serial->dev, usb_sndbulkpipe(edge_serial->serial->dev, edge_serial->bulk_out_endpoint), buffer, length, edge_bulk_out_cmd_callback, edge_port); edge_port->commandPending = true; + usb_anchor_urb(urb, &edge_serial->cmd_anchor); status = usb_submit_urb(urb, GFP_ATOMIC); if (status) { /* something went wrong */ dev_err(dev, "%s - usb_submit_urb(write command) failed, status = %d\n", __func__, status); + usb_unanchor_urb(urb); usb_free_urb(urb); - atomic_dec(&CmdUrbs); return status; } @@ -2325,18 +2311,12 @@ static int send_cmd_write_uart_register(struct edgeport_port *edge_port, } -/***************************************************************************** - * change_port_settings - * This routine is called to set the UART on the device to match the - * specified new settings. - *****************************************************************************/ - -static void change_port_settings(struct tty_struct *tty, - struct edgeport_port *edge_port, const struct ktermios *old_termios) +static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port, + const struct ktermios *old_termios) { - struct device *dev = &edge_port->port->dev; - struct edgeport_serial *edge_serial = - usb_get_serial_data(edge_port->port->serial); + struct edgeport_serial *edge_serial = usb_get_serial_data(port->serial); + struct edgeport_port *edge_port = usb_get_serial_port_data(port); + struct device *dev = &port->dev; int baud; unsigned cflag; __u8 mask = 0xff; @@ -2347,12 +2327,6 @@ static void change_port_settings(struct tty_struct *tty, __u8 txFlow; int status; - if (!edge_port->open && - !edge_port->openPending) { - dev_dbg(dev, "%s - port not opened\n", __func__); - return; - } - cflag = tty->termios.c_cflag; switch (cflag & CSIZE) { @@ -2468,12 +2442,14 @@ static void change_port_settings(struct tty_struct *tty, return; /* set up the MCR register and send it to the EdgePort */ + mutex_lock(&edge_port->mutex); edge_port->shadowMCR = MCR_MASTER_IE; if (cflag & CBAUD) edge_port->shadowMCR |= (MCR_DTR | MCR_RTS); status = send_cmd_write_uart_register(edge_port, MCR, edge_port->shadowMCR); + mutex_unlock(&edge_port->mutex); if (status != 0) return; @@ -2486,7 +2462,7 @@ static void change_port_settings(struct tty_struct *tty, dev_dbg(dev, "%s - baud rate = %d\n", __func__, baud); status = send_cmd_write_baud_rate(edge_port, baud); - if (status == -1) { + if (status == -1 && old_termios) { /* Speed change was not possible - put back the old speed */ baud = tty_termios_baud_rate(old_termios); tty_encode_baud_rate(tty, baud, baud); @@ -2724,6 +2700,7 @@ static int edge_startup(struct usb_serial *serial) spin_lock_init(&edge_serial->es_lock); edge_serial->serial = serial; + init_usb_anchor(&edge_serial->cmd_anchor); usb_set_serial_data(serial, edge_serial); /* get the name for the device from the device */ @@ -2928,6 +2905,8 @@ static void edge_disconnect(struct usb_serial *serial) { struct edgeport_serial *edge_serial = usb_get_serial_data(serial); + usb_kill_anchored_urbs(&edge_serial->cmd_anchor); + if (edge_serial->is_epic) { usb_kill_urb(edge_serial->interrupt_read_urb); usb_kill_urb(edge_serial->read_urb); @@ -2965,6 +2944,12 @@ static int edge_port_probe(struct usb_serial_port *port) return -ENOMEM; spin_lock_init(&edge_port->ep_lock); + mutex_init(&edge_port->mutex); + + init_waitqueue_head(&edge_port->wait_open); + init_waitqueue_head(&edge_port->wait_chase); + init_waitqueue_head(&edge_port->wait_command); + edge_port->port = port; usb_set_serial_port_data(port, edge_port); diff --git a/drivers/usb/serial/oti6858.c b/drivers/usb/serial/oti6858.c index bd206cb9cc08..487ba53eceb1 100644 --- a/drivers/usb/serial/oti6858.c +++ b/drivers/usb/serial/oti6858.c @@ -251,7 +251,7 @@ static void setup_line(struct work_struct *work) dev_dbg(&port->dev, "%s(): submitting interrupt urb\n", __func__); result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL); - if (result != 0) { + if (result != 0 && result != -EPERM) { dev_err(&port->dev, "%s(): usb_submit_urb() failed with error %d\n", __func__, result); } @@ -303,7 +303,7 @@ static void send_data(struct work_struct *work) dev_dbg(&port->dev, "%s(): submitting interrupt urb\n", __func__); result = usb_submit_urb(port->interrupt_in_urb, GFP_NOIO); - if (result != 0) { + if (result != 0 && result != -EPERM) { dev_err(&port->dev, "%s(): usb_submit_urb() failed with error %d\n", __func__, result); } @@ -564,6 +564,13 @@ static void oti6858_close(struct usb_serial_port *port) dev_dbg(&port->dev, "%s(): after buf_clear()\n", __func__); + /* + * The interrupt urb schedules the works, and the works and the bulk + * urbs resubmit the interrupt urb: keep it from being submitted until + * all of them are gone. + */ + usb_poison_urb(port->interrupt_in_urb); + /* cancel scheduled setup */ cancel_delayed_work_sync(&priv->delayed_setup_work); cancel_delayed_work_sync(&priv->delayed_write_work); @@ -572,7 +579,8 @@ static void oti6858_close(struct usb_serial_port *port) dev_dbg(&port->dev, "%s(): shutting down urbs\n", __func__); usb_kill_urb(port->write_urb); usb_kill_urb(port->read_urb); - usb_kill_urb(port->interrupt_in_urb); + + usb_unpoison_urb(port->interrupt_in_urb); } static int oti6858_tiocmset(struct tty_struct *tty, @@ -829,7 +837,7 @@ static void oti6858_write_bulk_callback(struct urb *urb) /* schedule the interrupt urb if we are still open */ dev_dbg(&port->dev, "%s(): submitting interrupt urb\n", __func__); result = usb_submit_urb(port->interrupt_in_urb, GFP_ATOMIC); - if (result != 0) { + if (result != 0 && result != -EPERM) { dev_err(&port->dev, "%s(): failed submitting int urb," " error %d\n", __func__, result); } diff --git a/drivers/usb/serial/sierra.c b/drivers/usb/serial/sierra.c index bac926cfee28..b56c5c80e231 100644 --- a/drivers/usb/serial/sierra.c +++ b/drivers/usb/serial/sierra.c @@ -575,12 +575,24 @@ static void sierra_instat_callback(struct urb *urb) __func__); return; } + if (urb->actual_length < sizeof(*req_pkt)) { + dev_err(&port->dev, "%s: short transfer\n", + __func__); + return; + } if ((req_pkt->bRequestType == 0xA1) && (req_pkt->bRequest == 0x20)) { int old_dcd_state; - unsigned char signals = *((unsigned char *) - urb->transfer_buffer + - sizeof(struct usb_ctrlrequest)); + unsigned char signals; + + if (urb->actual_length < sizeof(*req_pkt) + 1) { + dev_err(&port->dev, + "%s: short interrupt transfer\n", + __func__); + return; + } + signals = *((unsigned char *)urb->transfer_buffer + + sizeof(*req_pkt)); dev_dbg(&port->dev, "%s: signal x%x\n", __func__, signals); diff --git a/drivers/usb/serial/upd78f0730.c b/drivers/usb/serial/upd78f0730.c index 15a17bf111f1..a28cd6660174 100644 --- a/drivers/usb/serial/upd78f0730.c +++ b/drivers/usb/serial/upd78f0730.c @@ -201,10 +201,9 @@ static int upd78f0730_tiocmget(struct tty_struct *tty) return res; } -static int upd78f0730_tiocmset(struct tty_struct *tty, +static int upd78f0730_port_tiocmset(struct usb_serial_port *port, unsigned int set, unsigned int clear) { - struct usb_serial_port *port = tty->driver_data; struct upd78f0730_port_private *private; struct upd78f0730_set_dtr_rts request; struct device *dev = &port->dev; @@ -238,6 +237,13 @@ static int upd78f0730_tiocmset(struct tty_struct *tty, return res; } +static int upd78f0730_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear) +{ + struct usb_serial_port *port = tty->driver_data; + + return upd78f0730_port_tiocmset(port, set, clear); +} + static int upd78f0730_break_ctl(struct tty_struct *tty, int break_state) { struct upd78f0730_port_private *private; @@ -267,7 +273,6 @@ static int upd78f0730_break_ctl(struct tty_struct *tty, int break_state) static void upd78f0730_dtr_rts(struct usb_serial_port *port, int on) { - struct tty_struct *tty = port->port.tty; unsigned int set = 0; unsigned int clear = 0; @@ -276,7 +281,7 @@ static void upd78f0730_dtr_rts(struct usb_serial_port *port, int on) else clear = TIOCM_DTR | TIOCM_RTS; - upd78f0730_tiocmset(tty, set, clear); + upd78f0730_port_tiocmset(port, set, clear); } static speed_t upd78f0730_get_baud_rate(struct tty_struct *tty) diff --git a/drivers/usb/storage/uas-detect.h b/drivers/usb/storage/uas-detect.h index 4d3b49e5b87a..523a17cf0a3c 100644 --- a/drivers/usb/storage/uas-detect.h +++ b/drivers/usb/storage/uas-detect.h @@ -78,6 +78,8 @@ static int uas_use_uas_driver(struct usb_interface *intf, * ASM1051 - with broken (*) uas support * ASM1053 - with working uas support, but problems with large xfers * ASM1153 - with working uas support + * ASMT135x - broken uas support, shares the ASM1153 MaxPower == 0 + * signature, identify it by its product string * * Devices with these chips re-use a number of device-ids over the * entire line, so the device-id is useless to determine if we're @@ -99,7 +101,11 @@ static int uas_use_uas_driver(struct usb_interface *intf, (le16_to_cpu(udev->descriptor.idProduct) == 0x5106 || le16_to_cpu(udev->descriptor.idProduct) == 0x55aa)) { if (udev->actconfig->desc.bMaxPower == 0) { - /* ASM1153, do nothing */ + if (udev->product && strstr(udev->product, "ASMT135")) { + /* ASMT135x, broken uas */ + flags |= US_FL_IGNORE_UAS; + } + /* else ASM1153, do nothing */ } else if (udev->speed < USB_SPEED_SUPER) { /* No streams info, assume ASM1051 */ flags |= US_FL_IGNORE_UAS; diff --git a/drivers/usb/typec/mux/fsa4480.c b/drivers/usb/typec/mux/fsa4480.c index c54e42c7e6a1..c8a0b6807dfd 100644 --- a/drivers/usb/typec/mux/fsa4480.c +++ b/drivers/usb/typec/mux/fsa4480.c @@ -93,16 +93,9 @@ static int fsa4480_set(struct fsa4480 *fsa) sel = FSA4480_SEL_USB; } else if (fsa->svid) { switch (fsa->mode) { - /* DP Only */ case TYPEC_DP_STATE_C: - case TYPEC_DP_STATE_E: - enable |= FSA4480_ENABLE_SBU; - if (reverse) - sel = FSA4480_SEL_SBU_REVERSE; - break; - - /* DP + USB */ case TYPEC_DP_STATE_D: + case TYPEC_DP_STATE_E: case TYPEC_DP_STATE_F: enable |= FSA4480_ENABLE_USB | FSA4480_ENABLE_SBU; sel = FSA4480_SEL_USB; diff --git a/drivers/usb/typec/mux/nb7vpq904m.c b/drivers/usb/typec/mux/nb7vpq904m.c index b57b6c9c40fe..7942cd37761c 100644 --- a/drivers/usb/typec/mux/nb7vpq904m.c +++ b/drivers/usb/typec/mux/nb7vpq904m.c @@ -396,6 +396,7 @@ static int nb7vpq904m_probe(struct i2c_client *client) return -ENOMEM; nb7->client = client; + i2c_set_clientdata(client, nb7); nb7->regmap = devm_regmap_init_i2c(client, &nb7_regmap); if (IS_ERR(nb7->regmap)) { diff --git a/drivers/usb/typec/ucsi/ucsi.c b/drivers/usb/typec/ucsi/ucsi.c index 4c8f23826d45..29ec586f3895 100644 --- a/drivers/usb/typec/ucsi/ucsi.c +++ b/drivers/usb/typec/ucsi/ucsi.c @@ -2041,6 +2041,14 @@ static int ucsi_init(struct ucsi *ucsi) goto err_unregister; } + /* + * Set ucsi->connector before enabling notifications. A connector + * change event can be handled as soon as the notifications are + * enabled below, and ucsi_connector_change() indexes into + * ucsi->connector, so it must not be NULL at that point. + */ + ucsi->connector = connector; + /* Enable all supported notifications */ ntfy = ucsi_get_supported_notifications(ucsi); command = UCSI_SET_NOTIFICATION_ENABLE | ntfy; @@ -2048,7 +2056,6 @@ static int ucsi_init(struct ucsi *ucsi) if (ret < 0) goto err_unregister; - ucsi->connector = connector; ucsi->ntfy = ntfy; mutex_lock(&ucsi->ppm_lock); @@ -2062,6 +2069,7 @@ static int ucsi_init(struct ucsi *ucsi) return 0; err_unregister: + ucsi->connector = NULL; for (con = connector; con->port; con++) ucsi_unregister_port(con); for (i = 0; i < ucsi->cap.num_connectors; i++) diff --git a/drivers/vdpa/mlx5/net/mlx5_vnet.c b/drivers/vdpa/mlx5/net/mlx5_vnet.c index c49167d760a6..6cf55ce8ad4a 100644 --- a/drivers/vdpa/mlx5/net/mlx5_vnet.c +++ b/drivers/vdpa/mlx5/net/mlx5_vnet.c @@ -3048,7 +3048,15 @@ static int mlx5_vdpa_change_map(struct mlx5_vdpa_dev *mvdev, bool teardown = !is_resumable(ndev); int err; - suspend_vqs(ndev, 0, ndev->cur_num_vqs); + if ((mvdev->status & VIRTIO_CONFIG_S_DRIVER_OK) && !mvdev->suspended) { + err = suspend_vqs(ndev, 0, ndev->cur_num_vqs); + if (err && !teardown) { + for (int i = 0; i < ndev->cur_num_vqs; i++) + resume_vqs(ndev, i, 1); + mlx5_vdpa_put_mr(mvdev, new_mr); + return err; + } + } if (teardown) { err = save_channels_info(ndev); if (err) { diff --git a/drivers/vdpa/vdpa.c b/drivers/vdpa/vdpa.c index caf0ee5d6856..3d25238873af 100644 --- a/drivers/vdpa/vdpa.c +++ b/drivers/vdpa/vdpa.c @@ -1314,15 +1314,16 @@ static int vdpa_nl_cmd_dev_config_get_doit(struct sk_buff *skb, struct genl_info } err = vdpa_dev_config_fill(vdev, msg, info->snd_portid, info->snd_seq, 0, info->extack); - if (!err) + if (!err) { err = genlmsg_reply(msg, info); + msg = NULL; + } mdev_err: put_device(dev); dev_err: up_read(&vdpa_dev_lock); - if (err) - nlmsg_free(msg); + nlmsg_free(msg); return err; } diff --git a/drivers/vdpa/vdpa_sim/vdpa_sim.c b/drivers/vdpa/vdpa_sim/vdpa_sim.c index 44055778b694..aeed6bab3e17 100644 --- a/drivers/vdpa/vdpa_sim/vdpa_sim.c +++ b/drivers/vdpa/vdpa_sim/vdpa_sim.c @@ -641,6 +641,7 @@ static int vdpasim_set_map(struct vdpa_device *vdpa, unsigned int asid, if (asid >= vdpasim->dev_attr.nas) return -EINVAL; + mutex_lock(&vdpasim->mutex); spin_lock(&vdpasim->iommu_lock); iommu = &vdpasim->iommu[asid]; @@ -655,11 +656,13 @@ static int vdpasim_set_map(struct vdpa_device *vdpa, unsigned int asid, goto err; } spin_unlock(&vdpasim->iommu_lock); + mutex_unlock(&vdpasim->mutex); return 0; err: vhost_iotlb_reset(iommu); spin_unlock(&vdpasim->iommu_lock); + mutex_unlock(&vdpasim->mutex); return ret; } @@ -716,6 +719,7 @@ static int vdpasim_dma_map(struct vdpa_device *vdpa, unsigned int asid, if (asid >= vdpasim->dev_attr.nas) return -EINVAL; + mutex_lock(&vdpasim->mutex); spin_lock(&vdpasim->iommu_lock); if (vdpasim->iommu_pt[asid]) { vhost_iotlb_reset(&vdpasim->iommu[asid]); @@ -724,6 +728,7 @@ static int vdpasim_dma_map(struct vdpa_device *vdpa, unsigned int asid, ret = vhost_iotlb_add_range_ctx(&vdpasim->iommu[asid], iova, iova + size - 1, pa, perm, opaque); spin_unlock(&vdpasim->iommu_lock); + mutex_unlock(&vdpasim->mutex); return ret; } @@ -736,6 +741,7 @@ static int vdpasim_dma_unmap(struct vdpa_device *vdpa, unsigned int asid, if (asid >= vdpasim->dev_attr.nas) return -EINVAL; + mutex_lock(&vdpasim->mutex); spin_lock(&vdpasim->iommu_lock); if (vdpasim->iommu_pt[asid]) { vhost_iotlb_reset(&vdpasim->iommu[asid]); @@ -743,6 +749,7 @@ static int vdpasim_dma_unmap(struct vdpa_device *vdpa, unsigned int asid, } vhost_iotlb_del_range(&vdpasim->iommu[asid], iova, iova + size - 1); spin_unlock(&vdpasim->iommu_lock); + mutex_unlock(&vdpasim->mutex); return 0; } diff --git a/drivers/vdpa/vdpa_user/vduse_dev.c b/drivers/vdpa/vdpa_user/vduse_dev.c index f9547ede71be..d68858acc5d9 100644 --- a/drivers/vdpa/vdpa_user/vduse_dev.c +++ b/drivers/vdpa/vdpa_user/vduse_dev.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -1239,14 +1240,10 @@ static void vduse_vq_update_effective_cpu(struct vduse_virtqueue *vq) { int curr_cpu = vq->irq_effective_cpu; - while (true) { - curr_cpu = cpumask_next(curr_cpu, &vq->irq_affinity); - if (cpu_online(curr_cpu)) - break; - - if (curr_cpu >= nr_cpu_ids) - curr_cpu = IRQ_UNBOUND; - } + curr_cpu = cpumask_next_and_wrap(curr_cpu, &vq->irq_affinity, + cpu_online_mask); + if (curr_cpu >= nr_cpu_ids) + curr_cpu = IRQ_UNBOUND; vq->irq_effective_cpu = curr_cpu; } @@ -1427,10 +1424,12 @@ static long vduse_dev_ioctl(struct file *file, unsigned int cmd, ret = 0; index = array_index_nospec(index, dev->vq_num); if (!vduse_vq_signal_irqfd(dev->vqs[index])) { + cpus_read_lock(); vduse_vq_update_effective_cpu(dev->vqs[index]); ret = vduse_dev_queue_irq_work(dev, &dev->vqs[index]->inject, dev->vqs[index]->irq_effective_cpu); + cpus_read_unlock(); } break; } diff --git a/drivers/vhost/scsi.c b/drivers/vhost/scsi.c index fac400b25dad..e1ea548a651b 100644 --- a/drivers/vhost/scsi.c +++ b/drivers/vhost/scsi.c @@ -607,6 +607,16 @@ vhost_scsi_do_evt_work(struct vhost_scsi *vs, struct vhost_scsi_evt *evt) return; } + /* + * Eventq buffers are device-writable only. A nonzero in count + * guarantees that out is within the bounds of vq->iov. + */ + if (unlikely(out || !in)) { + vq_err(vq, "Invalid event buffer: out %u, in %u\n", out, in); + vs->vs_events_missed = true; + return; + } + if ((vq->iov[out].iov_len != sizeof(struct virtio_scsi_event))) { vq_err(vq, "Expecting virtio_scsi_event, got %zu bytes\n", vq->iov[out].iov_len); @@ -629,19 +639,26 @@ vhost_scsi_do_evt_work(struct vhost_scsi *vs, struct vhost_scsi_evt *evt) vhost_scsi_log_write(vq, vq_log, log_num); } -static void vhost_scsi_complete_events(struct vhost_scsi *vs, bool drop) +/* Caller must hold the event virtqueue mutex. */ +static void __vhost_scsi_complete_events(struct vhost_scsi *vs, bool drop) { - struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq; struct vhost_scsi_evt *evt, *t; struct llist_node *llnode; - mutex_lock(&vq->mutex); - llnode = llist_del_all(&vs->vs_event_list); + llnode = llist_reverse_order(llist_del_all(&vs->vs_event_list)); llist_for_each_entry_safe(evt, t, llnode, list) { if (!drop) vhost_scsi_do_evt_work(vs, evt); vhost_scsi_free_evt(vs, evt); } +} + +static void vhost_scsi_complete_events(struct vhost_scsi *vs, bool drop) +{ + struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq; + + mutex_lock(&vq->mutex); + __vhost_scsi_complete_events(vs, drop); mutex_unlock(&vq->mutex); } @@ -852,11 +869,16 @@ vhost_scsi_map_to_sgl(struct vhost_scsi_cmd *cmd, vhost_scsi_revert_map_iov_to_sgl(iter, *sgl, sg); iov_iter_revert(iter, bytes); + /* + * pages[npages] is the first page not added to the SG list. + * The remaining data starts at offset in that page. + */ while (bytes) { - n = min_t(unsigned int, PAGE_SIZE, bytes); + n = min_t(unsigned int, PAGE_SIZE - offset, bytes); put_page(pages[npages++]); bytes -= n; + offset = 0; } return -EINVAL; @@ -1509,9 +1531,17 @@ vhost_scsi_handle_vq(struct vhost_scsi *vs, struct vhost_virtqueue *vq) * vhost_scsi_queue_data_in() and vhost_scsi_queue_status() */ cmd->tvc_vq_desc = vc.head; + /* + * vhost_scsi_mapal() maps the PI bytes into cmd->prot_table. + * It maps the remaining exp_data_len bytes into cmd->table, + * which is the data SGL passed to the target core. Its + * expected length must therefore exclude prot_bytes. + * + * sbc_check_prot() derives the data length for protected READ + * and WRITE commands from the CDB. + */ vhost_scsi_target_queue_cmd(nexus, cmd, cdb, lun, task_attr, - data_direction, - exp_data_len + prot_bytes); + data_direction, exp_data_len); ret = 0; err: /* @@ -1835,7 +1865,7 @@ vhost_scsi_send_evt(struct vhost_scsi *vs, struct vhost_virtqueue *vq, llist_add(&evt->list, &vs->vs_event_list); if (!vhost_vq_work_queue(vq, &vs->vs_event_work)) - vhost_scsi_complete_events(vs, true); + __vhost_scsi_complete_events(vs, true); } static void vhost_scsi_evt_handle_kick(struct vhost_work *work) @@ -2084,6 +2114,9 @@ vhost_scsi_set_endpoint(struct vhost_scsi *vs, for (i = 0; i < vs->dev.nvqs; i++) { vq = &vs->vqs[i].vq; + if (i >= VHOST_SCSI_VQ_IO && !vs->vqs[i].scsi_cmds) + continue; + mutex_lock(&vq->mutex); vhost_vq_set_backend(vq, vs_tpg); vhost_vq_init_access(vq); @@ -2453,10 +2486,16 @@ vhost_scsi_ioctl(struct file *f, default: mutex_lock(&vs->dev.mutex); r = vhost_dev_ioctl(&vs->dev, ioctl, argp); - if (r == -ENOIOCTLCMD) - r = vhost_vring_ioctl(&vs->dev, ioctl, argp); - else + if (r == -ENOIOCTLCMD) { + if (vs->vs_tpg && + (ioctl == VHOST_SET_VRING_NUM || + ioctl == VHOST_SET_VRING_ADDR)) + r = -EBUSY; + else + r = vhost_vring_ioctl(&vs->dev, ioctl, argp); + } else { vhost_scsi_flush(vs); + } mutex_unlock(&vs->dev.mutex); return r; } diff --git a/drivers/vhost/test.c b/drivers/vhost/test.c index 42c955a5b211..997f86928437 100644 --- a/drivers/vhost/test.c +++ b/drivers/vhost/test.c @@ -281,6 +281,10 @@ static long vhost_test_set_backend(struct vhost_test *n, unsigned index, int fd) r = -EFAULT; goto err_vq; } + if (enable && !vq->kick) { + r = -EINVAL; + goto err_vq; + } if (!enable) { vhost_poll_stop(&vq->poll); backend = vhost_vq_get_backend(vq); diff --git a/drivers/vhost/vdpa.c b/drivers/vhost/vdpa.c index e4ddaf0e5abc..9014ee30861f 100644 --- a/drivers/vhost/vdpa.c +++ b/drivers/vhost/vdpa.c @@ -765,13 +765,46 @@ static long vhost_vdpa_vring_ioctl(struct vhost_vdpa *v, unsigned int cmd, if (ops->get_status(vdpa) & VIRTIO_CONFIG_S_DRIVER_OK) vhost_vdpa_unsetup_vq_irq(v, idx); + /* + * The parent caches call_ctx.ctx in cb.trigger without + * holding a reference, so it has to stop using it + * before vhost_vring_ioctl() drops the last one. + */ + cb.callback = NULL; + cb.private = NULL; + cb.trigger = NULL; + ops->set_vq_cb(vdpa, idx, &cb); + + /* + * A parent interrupt handler that loaded the callback + * before that store can still be running, so wait for + * it to finish with the context too. + */ + if (ops->get_vq_irq) { + int irq = ops->get_vq_irq(vdpa, idx); + + if (irq >= 0) + synchronize_irq(irq); + } } break; } r = vhost_vring_ioctl(&v->vdev, cmd, argp); - if (r) + if (r) { + /* + * A failure here means the swap never happened and the old + * context is still installed, so give the parent back the + * callback that was torn down above. + */ + if (cmd == VHOST_SET_VRING_CALL && vq->call_ctx.ctx) { + cb.callback = vhost_vdpa_virtqueue_cb; + cb.private = vq; + cb.trigger = vq->call_ctx.ctx; + ops->set_vq_cb(vdpa, idx, &cb); + } return r; + } switch (cmd) { case VHOST_SET_VRING_ADDR: @@ -974,6 +1007,8 @@ static void vhost_vdpa_pa_unmap(struct vhost_vdpa *v, struct vhost_iotlb *iotlb, unsigned long pfn, pinned; while ((map = vhost_iotlb_itree_first(iotlb, start, last)) != NULL) { + /* Stop device access before releasing the pinned pages. */ + vhost_vdpa_general_unmap(v, map, asid); pinned = PFN_DOWN(map->size); for (pfn = PFN_DOWN(map->addr); pinned > 0; pfn++, pinned--) { @@ -983,7 +1018,6 @@ static void vhost_vdpa_pa_unmap(struct vhost_vdpa *v, struct vhost_iotlb *iotlb, unpin_user_page(page); } atomic64_sub(PFN_DOWN(map->size), &dev->mm->pinned_vm); - vhost_vdpa_general_unmap(v, map, asid); vhost_iotlb_map_free(iotlb, map); } } @@ -995,10 +1029,10 @@ static void vhost_vdpa_va_unmap(struct vhost_vdpa *v, struct vhost_iotlb *iotlb, struct vdpa_map_file *map_file; while ((map = vhost_iotlb_itree_first(iotlb, start, last)) != NULL) { + vhost_vdpa_general_unmap(v, map, asid); map_file = (struct vdpa_map_file *)map->opaque; fput(map_file->file); kfree(map_file); - vhost_vdpa_general_unmap(v, map, asid); vhost_iotlb_map_free(iotlb, map); } } @@ -1072,21 +1106,39 @@ static int vhost_vdpa_map(struct vhost_vdpa *v, struct vhost_iotlb *iotlb, return 0; } -static void vhost_vdpa_unmap(struct vhost_vdpa *v, - struct vhost_iotlb *iotlb, - u64 iova, u64 size) +static int vhost_vdpa_unmap(struct vhost_vdpa *v, + struct vhost_iotlb *iotlb, + u64 iova, u64 size) { struct vdpa_device *vdpa = v->vdpa; const struct vdpa_config_ops *ops = vdpa->config; + struct vhost_iotlb_map *map; + struct vhost_iotlb new_iotlb; u32 asid = iotlb_to_asid(iotlb); + u64 last = iova + size - 1; + int ret; - vhost_vdpa_iotlb_unmap(v, iotlb, iova, iova + size - 1, asid); + if (ops->set_map && !ops->dma_map) { + vhost_iotlb_init(&new_iotlb, iotlb->limit, iotlb->flags); + list_for_each_entry(map, &iotlb->list, link) { + if (map->start <= last && map->last >= iova) + continue; + ret = vhost_iotlb_add_range_ctx(&new_iotlb, map->start, + map->last, map->addr, + map->perm, map->opaque); + if (ret) + goto reset; + } - if (ops->set_map) { - if (!v->in_batch) - ops->set_map(vdpa, asid, iotlb); + ret = ops->set_map(vdpa, asid, &new_iotlb); +reset: + vhost_iotlb_reset(&new_iotlb); + if (ret) + return ret; } + vhost_vdpa_iotlb_unmap(v, iotlb, iova, last, asid); + return 0; } static int vhost_vdpa_va_map(struct vhost_vdpa *v, @@ -1336,7 +1388,11 @@ static int vhost_vdpa_process_iotlb_msg(struct vhost_dev *dev, u32 asid, r = vhost_vdpa_process_iotlb_update(v, iotlb, msg); break; case VHOST_IOTLB_INVALIDATE: - vhost_vdpa_unmap(v, iotlb, msg->iova, msg->size); + if (!msg->size || msg->iova > U64_MAX - msg->size + 1) { + r = -EINVAL; + break; + } + r = vhost_vdpa_unmap(v, iotlb, msg->iova, msg->size); break; case VHOST_IOTLB_BATCH_BEGIN: v->batch_asid = asid; @@ -1649,7 +1705,7 @@ static int vhost_vdpa_probe(struct vdpa_device *vdpa) return minor; } - atomic_set(&v->opened, 0); + atomic_set(&v->opened, 1); spin_lock_init(&v->config_lock); v->minor = minor; v->vdpa = vdpa; @@ -1673,16 +1729,17 @@ static int vhost_vdpa_probe(struct vdpa_device *vdpa) cdev_init(&v->cdev, &vhost_vdpa_fops); v->cdev.owner = THIS_MODULE; + init_completion(&v->completion); + for (i = 0; i < VHOST_VDPA_IOTLB_BUCKETS; i++) + INIT_HLIST_HEAD(&v->as[i]); r = cdev_device_add(&v->cdev, &v->dev); if (r) goto err; - init_completion(&v->completion); vdpa_set_drvdata(vdpa, v); - for (i = 0; i < VHOST_VDPA_IOTLB_BUCKETS; i++) - INIT_HLIST_HEAD(&v->as[i]); + atomic_set_release(&v->opened, 0); return 0; diff --git a/drivers/vhost/vhost.c b/drivers/vhost/vhost.c index 78cee55cedf8..f8fc0c1a1000 100644 --- a/drivers/vhost/vhost.c +++ b/drivers/vhost/vhost.c @@ -1734,7 +1734,8 @@ ssize_t vhost_chr_write_iter(struct vhost_dev *dev, goto done; } - if (msg.type == VHOST_IOTLB_UPDATE && msg.size == 0) { + if (msg.type == VHOST_IOTLB_UPDATE && + (!msg.size || !msg.perm || (msg.perm & ~VHOST_ACCESS_RW))) { ret = -EINVAL; goto done; } @@ -3136,7 +3137,6 @@ static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq, return -EINVAL; start = vq->last_used_idx & (vq->num - 1); - used = vq->used->ring + start; for (i = 0; i < count; i++) { if (vhost_put_used(vq, &heads[i], start, 1)) { @@ -3149,14 +3149,31 @@ static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq, } if (unlikely(vq->log_used)) { + unsigned int log_count = 0; + int log_start = 0, next; + /* Make sure data is seen before log. */ smp_wmb(); - /* Log used ring entry write. */ - log_used(vq, ((void __user *)used - (void __user *)vq->used), - (vq->num - start) * sizeof *used); - if (start + count > vq->num) - log_used(vq, 0, - (start + count - vq->num) * sizeof *used); + /* Log contiguous runs of used ring entries that were written. */ + start = vq->last_used_idx & (vq->num - 1); + for (i = 0; i < count; i++) { + if (!log_count) + log_start = start; + log_count++; + + next = start + nheads[i]; + if (next >= vq->num) + next -= vq->num; + if (i + 1 == count || next != start + 1) { + used = vq->used->ring + log_start; + log_used(vq, + ((void __user *)used - + (void __user *)vq->used), + log_count * sizeof(*used)); + log_count = 0; + } + start = next; + } } old = vq->last_used_idx; diff --git a/drivers/video/fbdev/core/fbmem.c b/drivers/video/fbdev/core/fbmem.c index 1533d43a0a0c..8f9aa1045343 100644 --- a/drivers/video/fbdev/core/fbmem.c +++ b/drivers/video/fbdev/core/fbmem.c @@ -246,8 +246,11 @@ fb_set_var(struct fb_info *info, struct fb_var_screeninfo *var) ret = fb_mode_is_equal(&mode1, &mode2); if (!ret) { ret = fbcon_mode_deleted(info, &mode1); - if (!ret) + if (!ret) { + if (info->mode && fb_mode_is_equal(info->mode, &mode1)) + info->mode = NULL; fb_delete_videomode(&mode1, &info->modelist); + } } return ret ? -EINVAL : 0; diff --git a/drivers/video/fbdev/core/fbsysfs.c b/drivers/video/fbdev/core/fbsysfs.c index d363f94207c3..c32dd71a38e1 100644 --- a/drivers/video/fbdev/core/fbsysfs.c +++ b/drivers/video/fbdev/core/fbsysfs.c @@ -13,27 +13,35 @@ #include "fb_internal.h" #include "fbcon.h" +static int activate_locked(struct fb_info *fb_info, + struct fb_var_screeninfo *var) +{ + var->activate |= FB_ACTIVATE_FORCE; + return fb_set_var_from_user(fb_info, var); +} + static int activate(struct fb_info *fb_info, struct fb_var_screeninfo *var) { int err; - var->activate |= FB_ACTIVATE_FORCE; console_lock(); lock_fb_info(fb_info); - err = fb_set_var_from_user(fb_info, var); + err = activate_locked(fb_info, var); unlock_fb_info(fb_info); console_unlock(); - if (err) - return err; - return 0; + + return err; } -static int mode_string(char *buf, unsigned int offset, +static int mode_string(char *buf, size_t size, unsigned int offset, const struct fb_videomode *mode) { char m = 'U'; char v = 'p'; + if (offset >= size) + return 0; + if (mode->flag & FB_MODE_IS_DETAILED) m = 'D'; if (mode->flag & FB_MODE_IS_VESA) @@ -46,7 +54,7 @@ static int mode_string(char *buf, unsigned int offset, if (mode->vmode & FB_VMODE_DOUBLE) v = 'd'; - return snprintf(&buf[offset], PAGE_SIZE - offset, "%c:%dx%d%c-%d\n", + return scnprintf(&buf[offset], size - offset, "%c:%dx%d%c-%d\n", m, mode->xres, mode->yres, v, mode->refresh); } @@ -63,19 +71,32 @@ static ssize_t store_mode(struct device *device, struct device_attribute *attr, memset(&var, 0, sizeof(var)); + console_lock(); + lock_fb_info(fb_info); + list_for_each_entry(modelist, &fb_info->modelist, list) { mode = &modelist->mode; - i = mode_string(mstr, 0, mode); + i = mode_string(mstr, sizeof(mstr), 0, mode); if (strncmp(mstr, buf, max(count, i)) == 0) { var = fb_info->var; fb_videomode_to_var(&var, mode); - if ((err = activate(fb_info, &var))) + err = activate_locked(fb_info, &var); + if (err) { + unlock_fb_info(fb_info); + console_unlock(); return err; + } fb_info->mode = mode; + unlock_fb_info(fb_info); + console_unlock(); return count; } } + + unlock_fb_info(fb_info); + console_unlock(); + return -EINVAL; } @@ -83,11 +104,20 @@ static ssize_t show_mode(struct device *device, struct device_attribute *attr, char *buf) { struct fb_info *fb_info = dev_get_drvdata(device); + struct fb_videomode mode; + bool have_mode = false; + + lock_fb_info(fb_info); + if (fb_info->mode) { + mode = *fb_info->mode; + have_mode = true; + } + unlock_fb_info(fb_info); - if (!fb_info->mode) + if (!have_mode) return 0; - return mode_string(buf, 0, fb_info->mode); + return mode_string(buf, PAGE_SIZE, 0, &mode); } static ssize_t store_modes(struct device *device, @@ -135,10 +165,15 @@ static ssize_t show_modes(struct device *device, struct device_attribute *attr, const struct fb_videomode *mode; i = 0; + lock_fb_info(fb_info); list_for_each_entry(modelist, &fb_info->modelist, list) { mode = &modelist->mode; - i += mode_string(buf, i, mode); + i += mode_string(buf, PAGE_SIZE, i, mode); + if (i >= PAGE_SIZE - 1) + break; } + unlock_fb_info(fb_info); + return i; } diff --git a/drivers/virtio/virtio_balloon.c b/drivers/virtio/virtio_balloon.c index 0386e7b459bb..cf53c1cf674b 100644 --- a/drivers/virtio/virtio_balloon.c +++ b/drivers/virtio/virtio_balloon.c @@ -963,6 +963,7 @@ static int virtballoon_probe(struct virtio_device *vdev) INIT_WORK(&vb->update_balloon_stats_work, update_balloon_stats_func); INIT_WORK(&vb->update_balloon_size_work, update_balloon_size_func); spin_lock_init(&vb->stop_update_lock); + spin_lock_init(&vb->wakeup_lock); mutex_init(&vb->balloon_lock); init_waitqueue_head(&vb->acked); vb->vdev = vdev; @@ -1068,8 +1069,6 @@ static int virtballoon_probe(struct virtio_device *vdev) goto out_unregister_oom; } - spin_lock_init(&vb->wakeup_lock); - /* * The virtio balloon itself can't wake up the device, but it is * responsible for processing wakeup events passed up from the transport diff --git a/drivers/virtio/virtio_pci_common.c b/drivers/virtio/virtio_pci_common.c index 64806d042dbb..9d4f0f0d7087 100644 --- a/drivers/virtio/virtio_pci_common.c +++ b/drivers/virtio/virtio_pci_common.c @@ -636,7 +636,7 @@ static bool vp_supports_pm_no_reset(struct device *dev) pci_read_config_word(pci_dev, pci_dev->pm_cap + PCI_PM_CTRL, &pmcsr); if (PCI_POSSIBLE_ERROR(pmcsr)) { - dev_err(dev, "Unable to query pmcsr"); + dev_err(dev, "Unable to query pmcsr\n"); return false; } diff --git a/drivers/w1/masters/ds2482.c b/drivers/w1/masters/ds2482.c index e91c7b0f3617..211d3390ec7a 100644 --- a/drivers/w1/masters/ds2482.c +++ b/drivers/w1/masters/ds2482.c @@ -103,6 +103,7 @@ struct ds2482_data; struct ds2482_w1_chan { struct ds2482_data *pdev; u8 channel; + bool spu; /* strong pullup after the next byte */ struct w1_bus_master w1_bm; }; @@ -336,6 +337,19 @@ static void ds2482_w1_write_byte(void *data, u8 byte) if (pdev->w1_count > 1) ds2482_set_channel(pdev, pchan->channel); + if (pchan->spu) { + pchan->spu = false; + /* the wait above and this one are crucial, otherwise devices + * might not be powered long enough, causing e.g. a w1_therm + * sensor to provide wrong conversion results + */ + /* note: it seems like both SPU and APU have to be set! */ + ds2482_send_cmd_data(pdev, DS2482_CMD_WRITE_CONFIG, + ds2482_calculate_config(DS2482_REG_CFG_SPU | + DS2482_REG_CFG_APU)); + ds2482_wait_1wire_idle(pdev); + } + /* Send the write byte command */ ds2482_send_cmd_data(pdev, DS2482_CMD_1WIRE_WRITE_BYTE, byte); @@ -420,27 +434,19 @@ static u8 ds2482_w1_reset_bus(void *data) static u8 ds2482_w1_set_pullup(void *data, int delay) { struct ds2482_w1_chan *pchan = data; - struct ds2482_data *pdev = pchan->pdev; - u8 retval = 1; /* if delay is non-zero activate the pullup, * the strong pullup will be automatically deactivated * by the master, so do not explicitly deactive it + * + * The setting is used up by the next byte on any channel of the chip: + * ds2482_w1_write_byte() makes it, in one go with the byte. */ - if (delay) { - /* both waits are crucial, otherwise devices might not be - * powered long enough, causing e.g. a w1_therm sensor to - * provide wrong conversion results - */ - ds2482_wait_1wire_idle(pdev); - /* note: it seems like both SPU and APU have to be set! */ - retval = ds2482_send_cmd_data(pdev, DS2482_CMD_WRITE_CONFIG, - ds2482_calculate_config(DS2482_REG_CFG_SPU | - DS2482_REG_CFG_APU)); - ds2482_wait_1wire_idle(pdev); - } + if (!delay) + return 1; - return retval; + pchan->spu = true; + return 0; } diff --git a/drivers/w1/slaves/w1_ds2805.c b/drivers/w1/slaves/w1_ds2805.c index 9c86b7985d0b..bfcc02ecbdb9 100644 --- a/drivers/w1/slaves/w1_ds2805.c +++ b/drivers/w1/slaves/w1_ds2805.c @@ -102,7 +102,7 @@ static ssize_t w1_f0d_read_bin(struct file *filp, struct kobject *kobj, if (count == 0) return 0; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); /* read directly from the EEPROM in chunks of W1_F0D_READ_MAXLEN */ while (todo > 0) { @@ -123,7 +123,7 @@ static ssize_t w1_f0d_read_bin(struct file *filp, struct kobject *kobj, off += W1_F0D_READ_MAXLEN; } - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } @@ -211,7 +211,7 @@ static ssize_t w1_f0d_write_bin(struct file *filp, struct kobject *kobj, if (count == 0) return 0; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); /* Can only write data in blocks of the size of the scratchpad */ addr = off; @@ -256,7 +256,7 @@ static ssize_t w1_f0d_write_bin(struct file *filp, struct kobject *kobj, } out_up: - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } diff --git a/drivers/w1/slaves/w1_ds28e04.c b/drivers/w1/slaves/w1_ds28e04.c index c577b5973032..f1d7a64fed14 100644 --- a/drivers/w1/slaves/w1_ds28e04.c +++ b/drivers/w1/slaves/w1_ds28e04.c @@ -123,7 +123,7 @@ static ssize_t eeprom_read(struct file *filp, struct kobject *kobj, if (count == 0) return 0; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); if (w1_enable_crccheck) { min_page = (off >> W1_PAGE_BITS); @@ -140,7 +140,7 @@ static ssize_t eeprom_read(struct file *filp, struct kobject *kobj, } out_up: - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } @@ -253,7 +253,7 @@ static ssize_t eeprom_write(struct file *filp, struct kobject *kobj, } } - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); /* Can only write data to one page at a time */ idx = 0; @@ -271,7 +271,7 @@ static ssize_t eeprom_write(struct file *filp, struct kobject *kobj, } out_up: - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } @@ -290,9 +290,9 @@ static ssize_t pio_read(struct file *filp, struct kobject *kobj, if (off != 0 || count != 1 || buf == NULL) return -EINVAL; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); ret = w1_f1C_read(sl, W1_1C_REG_LOGIC_STATE, count, buf); - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return ret; } @@ -310,11 +310,11 @@ static ssize_t pio_write(struct file *filp, struct kobject *kobj, if (off != 0 || count != 1 || buf == NULL) return -EINVAL; - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); /* Write the PIO data */ if (w1_reset_select_slave(sl)) { - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return -1; } @@ -328,7 +328,7 @@ static ssize_t pio_write(struct file *filp, struct kobject *kobj, w1_read_block(sl->master, &ack, sizeof(ack)); - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); /* check for acknowledgement */ if (ack != 0xAA) diff --git a/drivers/w1/slaves/w1_therm.c b/drivers/w1/slaves/w1_therm.c index 832e3da94b20..8e0e6f122b08 100644 --- a/drivers/w1/slaves/w1_therm.c +++ b/drivers/w1/slaves/w1_therm.c @@ -906,6 +906,19 @@ static inline bool bulk_read_support(struct w1_slave *sl) return false; /* No device family */ } +/** + * bulk_read_slave() - check if a slave of the bus takes part in a bulk read + * @sl: any slave on the list of the master + * + * The family data of the slaves of other families is none of our business. + * + * Return: true if it is one of our devices and supports bulk read + */ +static bool bulk_read_slave(struct w1_slave *sl) +{ + return device_family(sl) && sl->family_data && bulk_read_support(sl); +} + /** * conversion_time() - get the Tconv for the slave * @sl: device to get the conversion time @@ -1497,9 +1510,7 @@ static int trigger_bulk_read(struct w1_master *dev_master) * so we can apply a strong pullup if required */ list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (!sl->family_data) - goto error; - if (bulk_read_support(sl)) { + if (bulk_read_slave(sl)) { int t_cur = conversion_time(sl); t_conv = max(t_cur, t_conv); @@ -1537,7 +1548,7 @@ static int trigger_bulk_read(struct w1_master *dev_master) /* set a flag to instruct that converT pending */ list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (bulk_read_support(sl)) + if (bulk_read_slave(sl)) SLAVE_CONVERT_TRIGGERED(sl) = -1; } @@ -1566,7 +1577,7 @@ static int trigger_bulk_read(struct w1_master *dev_master) set_flag: /* set a flag to register convsersion is done */ list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (bulk_read_support(sl)) + if (bulk_read_slave(sl)) SLAVE_CONVERT_TRIGGERED(sl) = 1; } error: @@ -1934,16 +1945,14 @@ static ssize_t therm_bulk_read_show(struct device *device, int ret = 0; list_for_each_entry(sl, &dev_master->slist, w1_slave_entry) { - if (sl->family_data) { - if (bulk_read_support(sl)) { - if (SLAVE_CONVERT_TRIGGERED(sl) == -1) { - ret = -1; - goto show_result; - } - if (SLAVE_CONVERT_TRIGGERED(sl) == 1) - /* continue to check other slaves */ - ret = 1; + if (bulk_read_slave(sl)) { + if (SLAVE_CONVERT_TRIGGERED(sl) == -1) { + ret = -1; + goto show_result; } + if (SLAVE_CONVERT_TRIGGERED(sl) == 1) + /* continue to check other slaves */ + ret = 1; } } show_result: diff --git a/drivers/w1/w1.c b/drivers/w1/w1.c index 47e5a3f38ca3..ddedc7a163e8 100644 --- a/drivers/w1/w1.c +++ b/drivers/w1/w1.c @@ -116,7 +116,7 @@ static ssize_t rw_write(struct file *filp, struct kobject *kobj, { struct w1_slave *sl = kobj_to_w1_slave(kobj); - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); if (w1_reset_select_slave(sl)) { count = 0; goto out_up; @@ -125,7 +125,7 @@ static ssize_t rw_write(struct file *filp, struct kobject *kobj, w1_write_block(sl->master, buf, count); out_up: - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } @@ -135,9 +135,9 @@ static ssize_t rw_read(struct file *filp, struct kobject *kobj, { struct w1_slave *sl = kobj_to_w1_slave(kobj); - mutex_lock(&sl->master->mutex); + mutex_lock(&sl->master->bus_mutex); w1_read_block(sl->master, buf, count); - mutex_unlock(&sl->master->mutex); + mutex_unlock(&sl->master->bus_mutex); return count; } @@ -776,16 +776,24 @@ int w1_unref_slave(struct w1_slave *sl) { struct w1_master *dev = sl->master; int refcnt; + + /* + * Once it is off the list nobody can find the slave and take a new + * reference. The lock must not be held any longer than that: the rest + * waits for sysfs callbacks and for users of the family data. + */ mutex_lock(&dev->list_mutex); refcnt = atomic_sub_return(1, &sl->refcnt); + if (refcnt == 0) + list_del(&sl->w1_slave_entry); + mutex_unlock(&dev->list_mutex); + if (refcnt == 0) { struct w1_netlink_msg msg; dev_dbg(&sl->dev, "%s: detaching %s [%p].\n", __func__, sl->name, sl); - list_del(&sl->w1_slave_entry); - memset(&msg, 0, sizeof(msg)); memcpy(msg.id.id, &sl->reg_num, sizeof(msg.id)); msg.type = W1_SLAVE_REMOVE; @@ -799,7 +807,6 @@ int w1_unref_slave(struct w1_slave *sl) kfree(sl); } atomic_dec(&dev->refcnt); - mutex_unlock(&dev->list_mutex); return refcnt; } diff --git a/drivers/w1/w1_int.c b/drivers/w1/w1_int.c index 19a0ea28e9f3..3fcc9ee56727 100644 --- a/drivers/w1/w1_int.c +++ b/drivers/w1/w1_int.c @@ -176,6 +176,13 @@ void __w1_remove_master_device(struct w1_master *dev) mutex_unlock(&w1_mlock); set_bit(W1_ABORT_SEARCH, &dev->flags); + + /* + * This waits for the callbacks, which take the locks below. One of + * them wakes the thread up. + */ + w1_destroy_master_attributes(dev); + kthread_stop(dev->thread); mutex_lock(&dev->mutex); @@ -185,7 +192,6 @@ void __w1_remove_master_device(struct w1_master *dev) w1_slave_detach(sl); mutex_lock(&dev->list_mutex); } - w1_destroy_master_attributes(dev); mutex_unlock(&dev->list_mutex); mutex_unlock(&dev->mutex); atomic_dec(&dev->refcnt); diff --git a/drivers/w1/w1_netlink.c b/drivers/w1/w1_netlink.c index e6b59d921076..40fbb96a793e 100644 --- a/drivers/w1/w1_netlink.c +++ b/drivers/w1/w1_netlink.c @@ -478,15 +478,17 @@ static void w1_process_cb(struct w1_master *dev, struct w1_async_cmd *async_cmd) if (!cmd || err) w1_netlink_queue_status(node->block, node->msg, cmd, err); + dev->priv = NULL; + mutex_unlock(&dev->bus_mutex); + /* ref taken in w1_search_slave or w1_search_master_id when building - * the block + * the block. If it is the last one, the slave is removed, which waits + * for users of the bus. */ if (sl) w1_unref_slave(sl); else atomic_dec(&dev->refcnt); - dev->priv = NULL; - mutex_unlock(&dev->bus_mutex); mutex_lock(&dev->list_mutex); list_del(&async_cmd->async_entry); diff --git a/drivers/watchdog/npcm_wdt.c b/drivers/watchdog/npcm_wdt.c index e62ea054bc61..aff1ea1e6b62 100644 --- a/drivers/watchdog/npcm_wdt.c +++ b/drivers/watchdog/npcm_wdt.c @@ -63,13 +63,11 @@ static int npcm_wdt_ping(struct watchdog_device *wdd) return 0; } -static int npcm_wdt_start(struct watchdog_device *wdd) +static void __npcm_wdt_start(struct watchdog_device *wdd) { struct npcm_wdt *wdt = to_npcm_wdt(wdd); u32 val; - clk_prepare_enable(wdt->clk); - if (wdd->timeout < 2) val = 0x800; else if (wdd->timeout < 3) @@ -94,6 +92,15 @@ static int npcm_wdt_start(struct watchdog_device *wdd) val |= NPCM_WTRE | NPCM_WTE | NPCM_WTR | NPCM_WTIE; writel(val, wdt->reg); +} + +static int npcm_wdt_start(struct watchdog_device *wdd) +{ + struct npcm_wdt *wdt = to_npcm_wdt(wdd); + + clk_prepare_enable(wdt->clk); + + __npcm_wdt_start(wdd); return 0; } @@ -134,7 +141,7 @@ static int npcm_wdt_set_timeout(struct watchdog_device *wdd, wdd->timeout = 2750; if (watchdog_active(wdd)) - npcm_wdt_start(wdd); + __npcm_wdt_start(wdd); return 0; } diff --git a/drivers/xen/gntdev.c b/drivers/xen/gntdev.c index 02ebbdba8610..5ff783dbe036 100644 --- a/drivers/xen/gntdev.c +++ b/drivers/xen/gntdev.c @@ -676,15 +676,19 @@ static long gntdev_ioctl_map_grant_ref(struct gntdev_priv *priv, mutex_lock(&priv->lock); gntdev_add_map(priv, map); op.index = map->index << PAGE_SHIFT; + mutex_unlock(&priv->lock); if (copy_to_user(u, &op, sizeof(op)) != 0) { - list_del(&map->next); + mutex_lock(&priv->lock); + map = gntdev_find_map_index(priv, op.index >> PAGE_SHIFT, + op.count); + if (map) + list_del(&map->next); mutex_unlock(&priv->lock); gntdev_put_map(priv, map); return -EFAULT; } - mutex_unlock(&priv->lock); return 0; } diff --git a/drivers/xen/grant-table.c b/drivers/xen/grant-table.c index 478d2ad725ac..823bd755a472 100644 --- a/drivers/xen/grant-table.c +++ b/drivers/xen/grant-table.c @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -1095,6 +1096,24 @@ int gnttab_dma_alloc_pages(struct gnttab_dma_alloc_args *args) ret = xenmem_reservation_decrease(args->nr_pages, args->frames); if (ret != args->nr_pages) { pr_debug("Failed to decrease reservation for DMA buffer\n"); + if (ret >= 0) { + /* Free the part where decrease didn't work. */ + size_t done = ret << PAGE_SHIFT; + + if (args->coherent) + dma_free_coherent(args->dev, size - done, + args->vaddr + done, + args->dev_bus_addr + done); + else + dma_free_wc(args->dev, size - done, + args->vaddr + done, + args->dev_bus_addr + done); + + if (!ret) /* Nothing else to do? */ + return -EFAULT; + + args->nr_pages = ret; + } ret = -EFAULT; goto fail; } @@ -1128,7 +1147,12 @@ int gnttab_dma_free_pages(struct gnttab_dma_alloc_args *args) ret = xenmem_reservation_increase(args->nr_pages, args->frames); if (ret != args->nr_pages) { pr_debug("Failed to increase reservation for DMA buffer\n"); - ret = -EFAULT; + /* Can only free what has been re-filled. */ + if (!ret) + return -ENOMEM; + if (ret > 0) + args->nr_pages = ret; + ret = -ENOMEM; } else { ret = 0; } @@ -1360,12 +1384,21 @@ static void unmap_refs_callback(int result, int gnttab_unmap_refs_sync(struct gntab_unmap_queue_data *item) { struct unmap_refs_callback_data data; + bool on_stack = object_is_on_stack(item); init_completion(&data.completion); item->data = &data; item->done = &unmap_refs_callback; - gnttab_unmap_refs_async(item); + /* blkback keeps @item, and so its retry work, on the stack. */ + if (on_stack) + INIT_DELAYED_WORK_ONSTACK(&item->gnttab_work, gnttab_unmap_work); + else + INIT_DELAYED_WORK(&item->gnttab_work, gnttab_unmap_work); + item->age = 0; + __gnttab_unmap_refs_async(item); wait_for_completion(&data.completion); + if (on_stack) + destroy_delayed_work_on_stack(&item->gnttab_work); return data.result; } diff --git a/drivers/xen/privcmd.c b/drivers/xen/privcmd.c index fc21473672d4..b676b0fd8e33 100644 --- a/drivers/xen/privcmd.c +++ b/drivers/xen/privcmd.c @@ -901,10 +901,25 @@ struct privcmd_kernel_irqfd { poll_table pt; }; +static bool irqfd_is_active(struct privcmd_kernel_irqfd *kirqfd) +{ + lockdep_assert_held(&irqfds_lock); + + return !list_empty(&kirqfd->list); +} + static void irqfd_deactivate(struct privcmd_kernel_irqfd *kirqfd) { lockdep_assert_held(&irqfds_lock); + /* + * Both the deassign ioctl and the eventfd wakeup path can reach + * this function. list_del_init() marks the irqfd inactive, so + * only the first caller may queue the shutdown work. + */ + if (!irqfd_is_active(kirqfd)) + return; + list_del_init(&kirqfd->list); queue_work(irqfd_cleanup_wq, &kirqfd->shutdown); } diff --git a/drivers/xen/pvcalls-back.c b/drivers/xen/pvcalls-back.c index fd7ed65e0197..fe36a87212b4 100644 --- a/drivers/xen/pvcalls-back.c +++ b/drivers/xen/pvcalls-back.c @@ -337,7 +337,7 @@ static struct sock_mapping *pvcalls_new_active_socket( ret = xenbus_map_ring_valloc(fedata->dev, &ref, 1, &page); if (ret < 0) - goto out; + goto out_map; map->ring = page; map->ring_order = map->ring->ring_order; /* first read the order, then map the data ring */ @@ -345,19 +345,19 @@ static struct sock_mapping *pvcalls_new_active_socket( if (map->ring_order > MAX_RING_ORDER) { pr_warn("%s frontend requested ring_order %u, which is > MAX (%u)\n", __func__, map->ring_order, MAX_RING_ORDER); - goto out; + goto out_unmap_ring; } ret = xenbus_map_ring_valloc(fedata->dev, map->ring->ref, (1 << map->ring_order), &page); if (ret < 0) - goto out; + goto out_unmap_ring; map->bytes = page; ret = bind_interdomain_evtchn_to_irqhandler_lateeoi( fedata->dev, evtchn, pvcalls_back_conn_event, 0, "pvcalls-backend", map); if (ret < 0) - goto out; + goto out_unmap_bytes; map->irq = ret; map->data.in = map->bytes; @@ -365,7 +365,7 @@ static struct sock_mapping *pvcalls_new_active_socket( map->ioworker.wq = alloc_ordered_workqueue("pvcalls_io", 0); if (!map->ioworker.wq) - goto out; + goto out_unbind; atomic_set(&map->io, 1); INIT_WORK(&map->ioworker.register_work, pvcalls_back_ioworker); @@ -381,11 +381,16 @@ static struct sock_mapping *pvcalls_new_active_socket( write_unlock_bh(&map->sock->sk->sk_callback_lock); return map; -out: - down(&fedata->socket_lock); - list_del(&map->list); - pvcalls_back_release_active(fedata->dev, fedata, map); - up(&fedata->socket_lock); + +out_unbind: + unbind_from_irqhandler(map->irq, map); +out_unmap_bytes: + xenbus_unmap_ring_vfree(fedata->dev, map->bytes); +out_unmap_ring: + xenbus_unmap_ring_vfree(fedata->dev, (void *)map->ring); +out_map: + sock_release(sock); + kfree(map); return NULL; } @@ -447,6 +452,7 @@ static int pvcalls_back_release_active(struct xenbus_device *dev, atomic_set(&map->release, 1); flush_work(&map->ioworker.register_work); + destroy_workqueue(map->ioworker.wq); xenbus_unmap_ring_vfree(dev, map->bytes); xenbus_unmap_ring_vfree(dev, (void *)map->ring); diff --git a/fs/9p/fid.c b/fs/9p/fid.c index f84412290a30..76242d450aa7 100644 --- a/fs/9p/fid.c +++ b/fs/9p/fid.c @@ -20,7 +20,9 @@ static inline void __add_fid(struct dentry *dentry, struct p9_fid *fid) { - hlist_add_head(&fid->dlist, (struct hlist_head *)&dentry->d_fsdata); + struct v9fs_dentry *v9fs_dentry = to_v9fs_dentry(dentry); + + hlist_add_head(&fid->dlist, &v9fs_dentry->head); } @@ -112,6 +114,7 @@ void v9fs_open_fid_add(struct inode *inode, struct p9_fid **pfid) static struct p9_fid *v9fs_fid_find(struct dentry *dentry, kuid_t uid, int any) { + struct v9fs_dentry *v9fs_dentry = to_v9fs_dentry(dentry); struct p9_fid *fid, *ret; p9_debug(P9_DEBUG_VFS, " dentry: %pd (%p) uid %d any %d\n", @@ -119,11 +122,9 @@ static struct p9_fid *v9fs_fid_find(struct dentry *dentry, kuid_t uid, int any) any); ret = NULL; /* we'll recheck under lock if there's anything to look in */ - if (dentry->d_fsdata) { - struct hlist_head *h = (struct hlist_head *)&dentry->d_fsdata; - + if (!hlist_empty(&v9fs_dentry->head)) { spin_lock(&dentry->d_lock); - hlist_for_each_entry(fid, h, dlist) { + hlist_for_each_entry(fid, &v9fs_dentry->head, dlist) { if (any || uid_eq(fid->uid, uid)) { ret = fid; p9_fid_get(ret); diff --git a/fs/9p/v9fs.c b/fs/9p/v9fs.c index 20dc6a03826a..190be7187b41 100644 --- a/fs/9p/v9fs.c +++ b/fs/9p/v9fs.c @@ -13,7 +13,8 @@ #include #include #include -#include +#include +#include #include #include #include @@ -34,8 +35,12 @@ struct kmem_cache *v9fs_inode_cache; */ enum { + /* Mount-point source, we need to handle this explicitly because + * the code below accepts unknown args and the vfs layer only handles + * source if we rejected it as EINVAL */ + Opt_source, /* Options that take integer arguments */ - Opt_debug, Opt_dfltuid, Opt_dfltgid, Opt_afid, + Opt_debug, Opt_dfltuid, Opt_dfltgid, Opt_afid, Opt_negtimeout, /* String options */ Opt_uname, Opt_remotename, Opt_cache, Opt_cachetag, /* Options that take no arguments */ @@ -44,55 +49,82 @@ enum { Opt_access, Opt_posixacl, /* Lock timeout option */ Opt_locktimeout, - /* Error token */ - Opt_err + + /* Client options */ + Opt_msize, Opt_trans, Opt_legacy, Opt_version, + + /* fd transport options */ + /* Options that take integer arguments */ + Opt_rfdno, Opt_wfdno, + /* Options that take no arguments */ + + /* rdma transport options */ + /* Options that take integer arguments */ + Opt_rq_depth, Opt_sq_depth, Opt_timeout, + + /* Options for both fd and rdma transports */ + Opt_port, Opt_privport, }; -static const match_table_t tokens = { - {Opt_debug, "debug=%x"}, - {Opt_dfltuid, "dfltuid=%u"}, - {Opt_dfltgid, "dfltgid=%u"}, - {Opt_afid, "afid=%u"}, - {Opt_uname, "uname=%s"}, - {Opt_remotename, "aname=%s"}, - {Opt_nodevmap, "nodevmap"}, - {Opt_noxattr, "noxattr"}, - {Opt_directio, "directio"}, - {Opt_ignoreqv, "ignoreqv"}, - {Opt_cache, "cache=%s"}, - {Opt_cachetag, "cachetag=%s"}, - {Opt_access, "access=%s"}, - {Opt_posixacl, "posixacl"}, - {Opt_locktimeout, "locktimeout=%u"}, - {Opt_err, NULL} +static const struct constant_table p9_versions[] = { + { "9p2000", p9_proto_legacy }, + { "9p2000.u", p9_proto_2000u }, + { "9p2000.L", p9_proto_2000L }, + {} }; -/* Interpret mount options for cache mode */ -static int get_cache_mode(char *s) -{ - int version = -EINVAL; - - if (!strcmp(s, "loose")) { - version = CACHE_SC_LOOSE; - p9_debug(P9_DEBUG_9P, "Cache mode: loose\n"); - } else if (!strcmp(s, "fscache")) { - version = CACHE_SC_FSCACHE; - p9_debug(P9_DEBUG_9P, "Cache mode: fscache\n"); - } else if (!strcmp(s, "mmap")) { - version = CACHE_SC_MMAP; - p9_debug(P9_DEBUG_9P, "Cache mode: mmap\n"); - } else if (!strcmp(s, "readahead")) { - version = CACHE_SC_READAHEAD; - p9_debug(P9_DEBUG_9P, "Cache mode: readahead\n"); - } else if (!strcmp(s, "none")) { - version = CACHE_SC_NONE; - p9_debug(P9_DEBUG_9P, "Cache mode: none\n"); - } else if (kstrtoint(s, 0, &version) != 0) { - version = -EINVAL; - pr_info("Unknown Cache mode or invalid value %s\n", s); - } - return version; -} +static const struct constant_table p9_cache_mode[] = { + { "loose", CACHE_SC_LOOSE }, + { "fscache", CACHE_SC_FSCACHE }, + { "mmap", CACHE_SC_MMAP }, + { "readahead", CACHE_SC_READAHEAD }, + { "none", CACHE_SC_NONE }, + {} +}; + +/* + * This structure contains all parameters used for the core code, + * the client, and all the transports. + */ +const struct fs_parameter_spec v9fs_param_spec[] = { + fsparam_string ("source", Opt_source), + fsparam_u32hex ("debug", Opt_debug), + fsparam_uid ("dfltuid", Opt_dfltuid), + fsparam_gid ("dfltgid", Opt_dfltgid), + fsparam_u32 ("afid", Opt_afid), + fsparam_string ("uname", Opt_uname), + fsparam_string ("aname", Opt_remotename), + fsparam_flag ("nodevmap", Opt_nodevmap), + fsparam_flag ("noxattr", Opt_noxattr), + fsparam_flag ("directio", Opt_directio), + fsparam_flag ("ignoreqv", Opt_ignoreqv), + fsparam_enum ("cache", Opt_cache, p9_cache_mode), + fsparam_string ("cachetag", Opt_cachetag), + fsparam_string ("access", Opt_access), + fsparam_flag ("posixacl", Opt_posixacl), + fsparam_u32 ("locktimeout", Opt_locktimeout), + fsparam_s32 ("negtimeout", Opt_negtimeout), + + /* client options */ + fsparam_u32 ("msize", Opt_msize), + fsparam_flag ("noextend", Opt_legacy), + fsparam_string ("trans", Opt_trans), + fsparam_enum ("version", Opt_version, p9_versions), + + /* fd transport options */ + fsparam_u32 ("rfdno", Opt_rfdno), + fsparam_u32 ("wfdno", Opt_wfdno), + + /* rdma transport options */ + fsparam_u32 ("sq", Opt_sq_depth), + fsparam_u32 ("rq", Opt_rq_depth), + fsparam_u32 ("timeout", Opt_timeout), + + /* fd and rdma transprt options */ + fsparam_u32 ("port", Opt_port), + fsparam_flag ("privport", Opt_privport), + {} +}; /* * Display the mount options in /proc/mounts. @@ -111,6 +143,9 @@ int v9fs_show_options(struct seq_file *m, struct dentry *root) from_kgid_munged(&init_user_ns, v9ses->dfltgid)); if (v9ses->afid != ~0) seq_printf(m, ",afid=%u", v9ses->afid); + if (v9ses->flags & V9FS_NDENTRY_TIMEOUT_SET) + seq_printf(m, ",negtimeout=%d", + (int)v9ses->ndentry_timeout_ms); if (strcmp(v9ses->uname, V9FS_DEFUSER) != 0) seq_printf(m, ",uname=%s", v9ses->uname); if (strcmp(v9ses->aname, V9FS_DEFANAME) != 0) @@ -154,267 +189,267 @@ int v9fs_show_options(struct seq_file *m, struct dentry *root) } /** - * v9fs_parse_options - parse mount options into session structure - * @v9ses: existing v9fs session information - * @opts: The mount option string + * v9fs_parse_param - parse a mount option into the filesystem context + * @fc: the filesystem context + * @param: the parameter to parse * * Return 0 upon success, -ERRNO upon failure. */ - -static int v9fs_parse_options(struct v9fs_session_info *v9ses, char *opts) +int v9fs_parse_param(struct fs_context *fc, struct fs_parameter *param) { - char *options, *tmp_options; - substring_t args[MAX_OPT_ARGS]; - char *p; - int option = 0; + struct v9fs_context *ctx = fc->fs_private; + struct fs_parse_result result; char *s; - int ret = 0; - - /* setup defaults */ - v9ses->afid = ~0; - v9ses->debug = 0; - v9ses->cache = CACHE_NONE; -#ifdef CONFIG_9P_FSCACHE - v9ses->cachetag = NULL; -#endif - v9ses->session_lock_timeout = P9_LOCK_TIMEOUT; - - if (!opts) - return 0; + int r; + int opt; + struct p9_client_opts *clnt = &ctx->client_opts; + struct p9_fd_opts *fd_opts = &ctx->fd_opts; + struct p9_rdma_opts *rdma_opts = &ctx->rdma_opts; + struct p9_session_opts *session_opts = &ctx->session_opts; + + opt = fs_parse(fc, v9fs_param_spec, param, &result); + if (opt < 0) { + /* + * We might like to report bad mount options here, but + * traditionally 9p has ignored unknown mount options + */ + if (opt == -ENOPARAM) + return 0; - tmp_options = kstrdup(opts, GFP_KERNEL); - if (!tmp_options) { - ret = -ENOMEM; - goto fail_option_alloc; + return opt; } - options = tmp_options; - - while ((p = strsep(&options, ",")) != NULL) { - int token, r; - - if (!*p) - continue; - - token = match_token(p, tokens, args); - switch (token) { - case Opt_debug: - r = match_int(&args[0], &option); - if (r < 0) { - p9_debug(P9_DEBUG_ERROR, - "integer field, but no integer?\n"); - ret = r; - } else { - v9ses->debug = option; + + switch (opt) { + case Opt_source: + if (fc->source) { + pr_info("p9: multiple sources not supported\n"); + return -EINVAL; + } + fc->source = param->string; + param->string = NULL; + break; + case Opt_debug: + session_opts->debug = result.uint_32; #ifdef CONFIG_NET_9P_DEBUG - p9_debug_level = option; + p9_debug_level = result.uint_32; #endif - } - break; - - case Opt_dfltuid: - r = match_int(&args[0], &option); - if (r < 0) { - p9_debug(P9_DEBUG_ERROR, - "integer field, but no integer?\n"); - ret = r; - continue; - } - v9ses->dfltuid = make_kuid(current_user_ns(), option); - if (!uid_valid(v9ses->dfltuid)) { - p9_debug(P9_DEBUG_ERROR, - "uid field, but not a uid?\n"); - ret = -EINVAL; - } - break; - case Opt_dfltgid: - r = match_int(&args[0], &option); - if (r < 0) { - p9_debug(P9_DEBUG_ERROR, - "integer field, but no integer?\n"); - ret = r; - continue; - } - v9ses->dfltgid = make_kgid(current_user_ns(), option); - if (!gid_valid(v9ses->dfltgid)) { - p9_debug(P9_DEBUG_ERROR, - "gid field, but not a gid?\n"); - ret = -EINVAL; - } - break; - case Opt_afid: - r = match_int(&args[0], &option); - if (r < 0) { - p9_debug(P9_DEBUG_ERROR, - "integer field, but no integer?\n"); - ret = r; - } else { - v9ses->afid = option; - } - break; - case Opt_uname: - kfree(v9ses->uname); - v9ses->uname = match_strdup(&args[0]); - if (!v9ses->uname) { - ret = -ENOMEM; - goto free_and_return; - } - break; - case Opt_remotename: - kfree(v9ses->aname); - v9ses->aname = match_strdup(&args[0]); - if (!v9ses->aname) { - ret = -ENOMEM; - goto free_and_return; - } - break; - case Opt_nodevmap: - v9ses->nodev = 1; - break; - case Opt_noxattr: - v9ses->flags |= V9FS_NO_XATTR; - break; - case Opt_directio: - v9ses->flags |= V9FS_DIRECT_IO; - break; - case Opt_ignoreqv: - v9ses->flags |= V9FS_IGNORE_QV; - break; - case Opt_cachetag: + break; + + case Opt_dfltuid: + session_opts->dfltuid = result.uid; + break; + case Opt_dfltgid: + session_opts->dfltgid = result.gid; + break; + case Opt_afid: + session_opts->afid = result.uint_32; + break; + case Opt_uname: + kfree(session_opts->uname); + session_opts->uname = param->string; + param->string = NULL; + break; + case Opt_remotename: + kfree(session_opts->aname); + session_opts->aname = param->string; + param->string = NULL; + break; + case Opt_nodevmap: + session_opts->nodev = 1; + break; + case Opt_noxattr: + session_opts->flags |= V9FS_NO_XATTR; + break; + case Opt_directio: + session_opts->flags |= V9FS_DIRECT_IO; + break; + case Opt_ignoreqv: + session_opts->flags |= V9FS_IGNORE_QV; + break; + case Opt_cachetag: #ifdef CONFIG_9P_FSCACHE - kfree(v9ses->cachetag); - v9ses->cachetag = match_strdup(&args[0]); - if (!v9ses->cachetag) { - ret = -ENOMEM; - goto free_and_return; - } + kfree(session_opts->cachetag); + session_opts->cachetag = param->string; + param->string = NULL; #endif - break; - case Opt_cache: - s = match_strdup(&args[0]); - if (!s) { - ret = -ENOMEM; - p9_debug(P9_DEBUG_ERROR, - "problem allocating copy of cache arg\n"); - goto free_and_return; - } - r = get_cache_mode(s); - if (r < 0) - ret = r; - else - v9ses->cache = r; - - kfree(s); - break; - - case Opt_access: - s = match_strdup(&args[0]); - if (!s) { - ret = -ENOMEM; - p9_debug(P9_DEBUG_ERROR, - "problem allocating copy of access arg\n"); - goto free_and_return; + break; + case Opt_cache: + session_opts->cache = result.uint_32; + p9_debug(P9_DEBUG_9P, "Cache mode: %s\n", param->string); + break; + case Opt_access: + s = param->string; + session_opts->flags &= ~V9FS_ACCESS_MASK; + if (strcmp(s, "user") == 0) { + session_opts->flags |= V9FS_ACCESS_USER; + } else if (strcmp(s, "any") == 0) { + session_opts->flags |= V9FS_ACCESS_ANY; + } else if (strcmp(s, "client") == 0) { + session_opts->flags |= V9FS_ACCESS_CLIENT; + } else { + uid_t uid; + + session_opts->flags |= V9FS_ACCESS_SINGLE; + r = kstrtouint(s, 10, &uid); + if (r) { + pr_info("Unknown access argument %s: %d\n", + param->string, r); + return r; } - - v9ses->flags &= ~V9FS_ACCESS_MASK; - if (strcmp(s, "user") == 0) - v9ses->flags |= V9FS_ACCESS_USER; - else if (strcmp(s, "any") == 0) - v9ses->flags |= V9FS_ACCESS_ANY; - else if (strcmp(s, "client") == 0) { - v9ses->flags |= V9FS_ACCESS_CLIENT; - } else { - uid_t uid; - - v9ses->flags |= V9FS_ACCESS_SINGLE; - r = kstrtouint(s, 10, &uid); - if (r) { - ret = r; - pr_info("Unknown access argument %s: %d\n", - s, r); - kfree(s); - continue; - } - v9ses->uid = make_kuid(current_user_ns(), uid); - if (!uid_valid(v9ses->uid)) { - ret = -EINVAL; - pr_info("Unknown uid %s\n", s); - } + session_opts->uid = make_kuid(current_user_ns(), uid); + if (!uid_valid(session_opts->uid)) { + pr_info("Unknown uid %s\n", s); + return -EINVAL; } + } + break; - kfree(s); - break; - - case Opt_posixacl: + case Opt_posixacl: #ifdef CONFIG_9P_FS_POSIX_ACL - v9ses->flags |= V9FS_POSIX_ACL; + session_opts->flags |= V9FS_POSIX_ACL; #else - p9_debug(P9_DEBUG_ERROR, - "Not defined CONFIG_9P_FS_POSIX_ACL. Ignoring posixacl option\n"); + p9_debug(P9_DEBUG_ERROR, + "Not defined CONFIG_9P_FS_POSIX_ACL. Ignoring posixacl option\n"); #endif - break; - - case Opt_locktimeout: - r = match_int(&args[0], &option); - if (r < 0) { - p9_debug(P9_DEBUG_ERROR, - "integer field, but no integer?\n"); - ret = r; - continue; - } - if (option < 1) { - p9_debug(P9_DEBUG_ERROR, - "locktimeout must be a greater than zero integer.\n"); - ret = -EINVAL; - continue; - } - v9ses->session_lock_timeout = (long)option * HZ; - break; + break; - default: - continue; + case Opt_locktimeout: + if (result.uint_32 < 1) { + p9_debug(P9_DEBUG_ERROR, + "locktimeout must be a greater than zero integer.\n"); + return -EINVAL; } + session_opts->session_lock_timeout = (long)result.uint_32 * HZ; + break; + + case Opt_negtimeout: + session_opts->flags |= V9FS_NDENTRY_TIMEOUT_SET; + if (result.int_32 < 0) { + session_opts->ndentry_timeout_ms = + NDENTRY_TIMEOUT_NEVER; + } else { + session_opts->ndentry_timeout_ms = result.int_32; + } + break; + + /* Options for client */ + case Opt_msize: + if (result.uint_32 < 4096) { + p9_debug(P9_DEBUG_ERROR, "msize should be at least 4k\n"); + return -EINVAL; + } + if (result.uint_32 > INT_MAX) { + p9_debug(P9_DEBUG_ERROR, "msize too big\n"); + return -EINVAL; + } + clnt->msize = result.uint_32; + break; + case Opt_trans: + v9fs_put_trans(clnt->trans_mod); + clnt->trans_mod = v9fs_get_trans_by_name(param->string); + if (!clnt->trans_mod) { + pr_info("Could not find request transport: %s\n", + param->string); + return -EINVAL; + } + break; + case Opt_legacy: + clnt->proto_version = p9_proto_legacy; + break; + case Opt_version: + clnt->proto_version = result.uint_32; + p9_debug(P9_DEBUG_9P, "Protocol version: %s\n", param->string); + break; + /* Options for fd transport */ + case Opt_rfdno: + fd_opts->rfd = result.uint_32; + break; + case Opt_wfdno: + fd_opts->wfd = result.uint_32; + break; + /* Options for rdma transport */ + case Opt_sq_depth: + rdma_opts->sq_depth = result.uint_32; + break; + case Opt_rq_depth: + rdma_opts->rq_depth = result.uint_32; + break; + case Opt_timeout: + rdma_opts->timeout = result.uint_32; + break; + /* Options for both fd and rdma transports */ + case Opt_port: + fd_opts->port = result.uint_32; + rdma_opts->port = result.uint_32; + break; + case Opt_privport: + fd_opts->privport = true; + rdma_opts->privport = true; + break; } -free_and_return: - kfree(tmp_options); -fail_option_alloc: - return ret; + return 0; +} + +static void v9fs_apply_options(struct v9fs_session_info *v9ses, + struct fs_context *fc) +{ + struct v9fs_context *ctx = fc->fs_private; + + v9ses->debug = ctx->session_opts.debug; + v9ses->dfltuid = ctx->session_opts.dfltuid; + v9ses->dfltgid = ctx->session_opts.dfltgid; + v9ses->afid = ctx->session_opts.afid; + v9ses->uname = ctx->session_opts.uname; + ctx->session_opts.uname = NULL; + v9ses->aname = ctx->session_opts.aname; + ctx->session_opts.aname = NULL; + v9ses->nodev = ctx->session_opts.nodev; + /* + * Note that we must |= flags here as session_init already + * set basic flags. This adds in flags from parsed options. + * Default access flags must be cleared if session options + * changes them to avoid mangling the setting. + */ + if (ctx->session_opts.flags & V9FS_ACCESS_MASK) + v9ses->flags &= ~V9FS_ACCESS_MASK; + v9ses->flags |= ctx->session_opts.flags; +#ifdef CONFIG_9P_FSCACHE + v9ses->cachetag = ctx->session_opts.cachetag; + ctx->session_opts.cachetag = NULL; +#endif + v9ses->cache = ctx->session_opts.cache; + v9ses->uid = ctx->session_opts.uid; + v9ses->session_lock_timeout = ctx->session_opts.session_lock_timeout; + v9ses->ndentry_timeout_ms = ctx->session_opts.ndentry_timeout_ms; } /** * v9fs_session_init - initialize session * @v9ses: session information structure - * @dev_name: device being mounted - * @data: options + * @fc: the filesystem mount context * */ struct p9_fid *v9fs_session_init(struct v9fs_session_info *v9ses, - const char *dev_name, char *data) + struct fs_context *fc) { struct p9_fid *fid; int rc = -ENOMEM; - v9ses->uname = kstrdup(V9FS_DEFUSER, GFP_KERNEL); - if (!v9ses->uname) - goto err_names; - - v9ses->aname = kstrdup(V9FS_DEFANAME, GFP_KERNEL); - if (!v9ses->aname) - goto err_names; init_rwsem(&v9ses->rename_sem); - v9ses->uid = INVALID_UID; - v9ses->dfltuid = V9FS_DEFUID; - v9ses->dfltgid = V9FS_DEFGID; - - v9ses->clnt = p9_client_create(dev_name, data); + v9ses->clnt = p9_client_create(fc); if (IS_ERR(v9ses->clnt)) { rc = PTR_ERR(v9ses->clnt); p9_debug(P9_DEBUG_ERROR, "problem initializing 9p client\n"); goto err_names; } + /* + * Initialize flags on the real v9ses. v9fs_apply_options below + * will |= the additional flags from parsed options. + */ v9ses->flags = V9FS_ACCESS_USER; if (p9_is_proto_dotl(v9ses->clnt)) { @@ -424,9 +459,7 @@ struct p9_fid *v9fs_session_init(struct v9fs_session_info *v9ses, v9ses->flags |= V9FS_PROTO_2000U; } - rc = v9fs_parse_options(v9ses, data); - if (rc < 0) - goto err_clnt; + v9fs_apply_options(v9ses, fc); v9ses->maxdata = v9ses->clnt->msize - P9_IOHDRSZ; @@ -472,7 +505,7 @@ struct p9_fid *v9fs_session_init(struct v9fs_session_info *v9ses, #ifdef CONFIG_9P_FSCACHE /* register the session for caching */ if (v9ses->cache & CACHE_FSCACHE) { - rc = v9fs_cache_session_get_cookie(v9ses, dev_name); + rc = v9fs_cache_session_get_cookie(v9ses, fc->source); if (rc < 0) goto err_clnt; } diff --git a/fs/9p/v9fs.h b/fs/9p/v9fs.h index f28bc763847a..9a730d2d9d87 100644 --- a/fs/9p/v9fs.h +++ b/fs/9p/v9fs.h @@ -10,6 +10,9 @@ #include #include +#include +#include +#include /** * enum p9_session_flags - option flags for each 9P session @@ -18,30 +21,43 @@ * @V9FS_ACCESS_SINGLE: only the mounting user can access the hierarchy * @V9FS_ACCESS_USER: a new attach will be issued for every user (default) * @V9FS_ACCESS_CLIENT: Just like user, but access check is performed on client. - * @V9FS_ACCESS_ANY: use a single attach for all users - * @V9FS_ACCESS_MASK: bit mask of different ACCESS options * @V9FS_POSIX_ACL: POSIX ACLs are enforced + * @V9FS_NO_XATTR: do not offer xattr functions on this mount + * @V9FS_IGNORE_QV: ignore qid.version==0 as a marker to disable data cache + * @V9FS_DIRECT_IO: disable data read/write cache + * @V9FS_SYNC: disable data write cache + * @V9FS_NDENTRY_TIMEOUT_SET: Has negative dentry timeout retention time been + * overridden by negtimeout mount option * * Session flags reflect options selected by users at mount time */ +enum p9_session_flags { + V9FS_PROTO_2000U = 0x01, + V9FS_PROTO_2000L = 0x02, + V9FS_ACCESS_SINGLE = 0x04, + V9FS_ACCESS_USER = 0x08, + V9FS_ACCESS_CLIENT = 0x10, + V9FS_POSIX_ACL = 0x20, + V9FS_NO_XATTR = 0x40, + V9FS_IGNORE_QV = 0x80, /* ignore qid.version for cache hints */ + V9FS_DIRECT_IO = 0x100, + V9FS_SYNC = 0x200, + V9FS_NDENTRY_TIMEOUT_SET = 0x400, +}; + +/** + * V9FS_ACCESS_ANY - use a single attach for all users + */ #define V9FS_ACCESS_ANY (V9FS_ACCESS_SINGLE | \ V9FS_ACCESS_USER | \ V9FS_ACCESS_CLIENT) + +/** + * V9FS_ACCESS_MASK - bit mask of different ACCESS options + */ #define V9FS_ACCESS_MASK V9FS_ACCESS_ANY -#define V9FS_ACL_MASK V9FS_POSIX_ACL -enum p9_session_flags { - V9FS_PROTO_2000U = 0x01, - V9FS_PROTO_2000L = 0x02, - V9FS_ACCESS_SINGLE = 0x04, - V9FS_ACCESS_USER = 0x08, - V9FS_ACCESS_CLIENT = 0x10, - V9FS_POSIX_ACL = 0x20, - V9FS_NO_XATTR = 0x40, - V9FS_IGNORE_QV = 0x80, /* ignore qid.version for cache hints */ - V9FS_DIRECT_IO = 0x100, - V9FS_SYNC = 0x200 -}; +#define V9FS_ACL_MASK V9FS_POSIX_ACL /** * enum p9_cache_shortcuts - human readable cache preferences @@ -88,6 +104,7 @@ enum p9_cache_bits { * @debug: debug level * @afid: authentication handle * @cache: cache mode of type &p9_cache_bits + * @ndentry_timeout: Negative dentry lookup cache retention time in ms * @cachetag: the tag of the cache associated with this session * @fscache: session cookie associated with FS-Cache * @uname: string user name to mount hierarchy as @@ -98,6 +115,7 @@ enum p9_cache_bits { * @uid: if %V9FS_ACCESS_SINGLE, the numeric uid which mounted the hierarchy * @clnt: reference to 9P network client instantiated for this session * @slist: reference to list of registered 9p sessions + * @ndentry_timeout_ms: Negative dentry caching retention time * * This structure holds state for each session instance established during * a sys_mount() . @@ -113,6 +131,7 @@ struct v9fs_session_info { unsigned short debug; unsigned int afid; unsigned int cache; + unsigned int ndentry_timeout_ms; #ifdef CONFIG_9P_FSCACHE char *cachetag; struct fscache_volume *fscache; @@ -128,8 +147,11 @@ struct v9fs_session_info { struct list_head slist; /* list of sessions registered with v9fs */ struct rw_semaphore rename_sem; long session_lock_timeout; /* retry interval for blocking locks */ + struct rcu_head rcu; /* v9fs_vfs_get_link_dotl() reads ->cache in rcu pathwalk */ }; +#define NDENTRY_TIMEOUT_NEVER (-1U) + /* cache_validity flags */ #define V9FS_INO_INVALID_ATTR 0x01 @@ -163,11 +185,13 @@ static inline struct fscache_volume *v9fs_session_cache(struct v9fs_session_info #endif } +extern const struct fs_parameter_spec v9fs_param_spec[]; +extern int v9fs_parse_param(struct fs_context *fc, struct fs_parameter *param); extern int v9fs_show_options(struct seq_file *m, struct dentry *root); struct p9_fid *v9fs_session_init(struct v9fs_session_info *v9ses, - const char *dev_name, char *data); + struct fs_context *fc); extern void v9fs_session_close(struct v9fs_session_info *v9ses); extern void v9fs_session_cancel(struct v9fs_session_info *v9ses); extern void v9fs_session_begin_cancel(struct v9fs_session_info *v9ses); diff --git a/fs/9p/v9fs_vfs.h b/fs/9p/v9fs_vfs.h index d3aefbec4de6..83c2335f438d 100644 --- a/fs/9p/v9fs_vfs.h +++ b/fs/9p/v9fs_vfs.h @@ -28,6 +28,19 @@ /* flags for v9fs_stat2inode() & v9fs_stat2inode_dotl() */ #define V9FS_STAT2INODE_KEEP_ISIZE 1 +/** + * struct v9fs_dentry - v9fs specific dentry data + * @head: List of fid associated with this dentry + * @expire_time: Lookup cache expiration time for negative dentries + * @rcu: used by kfree_rcu to schedule clean up job + */ +struct v9fs_dentry { + struct hlist_head head; + u64 expire_time; + struct rcu_head rcu; +}; +#define to_v9fs_dentry(d) ((struct v9fs_dentry *)((d)->d_fsdata)) + extern struct file_system_type v9fs_fs_type; extern const struct address_space_operations v9fs_addr_operations; extern const struct file_operations v9fs_file_operations; @@ -35,6 +48,8 @@ extern const struct file_operations v9fs_file_operations_dotl; extern const struct file_operations v9fs_dir_operations; extern const struct file_operations v9fs_dir_operations_dotl; extern const struct dentry_operations v9fs_dentry_operations; +extern void v9fs_ndentry_refresh_timeout(struct dentry *dentry); +extern void v9fs_dentry_fid_remove(struct dentry *dentry); extern const struct dentry_operations v9fs_cached_dentry_operations; extern struct kmem_cache *v9fs_inode_cache; diff --git a/fs/9p/vfs_addr.c b/fs/9p/vfs_addr.c index 6bf5973445b6..de2b1f8cdc0e 100644 --- a/fs/9p/vfs_addr.c +++ b/fs/9p/vfs_addr.c @@ -97,11 +97,35 @@ static void v9fs_issue_read(struct netfs_io_subrequest *subreq) { struct netfs_io_request *rreq = subreq->rreq; struct p9_fid *fid = rreq->netfs_priv; + char *target; unsigned long long pos = subreq->start + subreq->transferred; - int total, err; - - total = p9_client_read(fid, pos, &subreq->io_iter, &err); + int total = 0, err, len, n; + size_t to_read = iov_iter_count(&subreq->io_iter); + + if (S_ISLNK(rreq->inode->i_mode)) { + /* p9_client_readlink() must not be called for legacy protocols + * 9p2000 or 9p2000.u. + */ + BUG_ON(!p9_is_proto_dotl(fid->clnt)); + if (WARN_ON_ONCE(pos)) { + /* reading a link at a non null offset should + * not happen + */ + err = -EIO; + goto fill_subreq; + } + err = p9_client_readlink(fid, &target); + if (err != 0) + goto fill_subreq; + len = strlen(target); + n = copy_to_iter(target, len, &subreq->io_iter); + kfree(target); + total = n; + } else { + total = p9_client_read(fid, pos, &subreq->io_iter, &err); + } +fill_subreq: /* if we just extended the file size, any portion not in * cache won't be on server and is zeroes */ if (subreq->rreq->origin != NETFS_UNBUFFERED_READ && @@ -109,6 +133,8 @@ static void v9fs_issue_read(struct netfs_io_subrequest *subreq) __set_bit(NETFS_SREQ_CLEAR_TAIL, &subreq->flags); if (pos + total >= i_size_read(rreq->inode)) __set_bit(NETFS_SREQ_HIT_EOF, &subreq->flags); + if (!err && !total && to_read) + __set_bit(NETFS_SREQ_HIT_EOF, &subreq->flags); if (!err && total) { subreq->transferred += total; __set_bit(NETFS_SREQ_MADE_PROGRESS, &subreq->flags); @@ -126,6 +152,7 @@ static void v9fs_issue_read(struct netfs_io_subrequest *subreq) static int v9fs_init_request(struct netfs_io_request *rreq, struct file *file) { struct p9_fid *fid; + struct dentry *dentry; bool writing = (rreq->origin == NETFS_READ_FOR_WRITE || rreq->origin == NETFS_WRITETHROUGH || rreq->origin == NETFS_UNBUFFERED_WRITE || @@ -142,6 +169,14 @@ static int v9fs_init_request(struct netfs_io_request *rreq, struct file *file) if (!fid) goto no_fid; p9_fid_get(fid); + } else if (S_ISLNK(rreq->inode->i_mode)) { + dentry = d_find_any_alias(rreq->inode); + if (!dentry) + goto no_fid; + fid = v9fs_fid_lookup(dentry); + dput(dentry); + if (IS_ERR(fid)) + goto no_fid; } else { fid = v9fs_fid_find_inode(rreq->inode, writing, INVALID_UID, true); if (!fid) diff --git a/fs/9p/vfs_dentry.c b/fs/9p/vfs_dentry.c index c1acbc98465d..a14821c1206f 100644 --- a/fs/9p/vfs_dentry.c +++ b/fs/9p/vfs_dentry.c @@ -23,6 +23,46 @@ #include "v9fs_vfs.h" #include "fid.h" +/** + * v9fs_ndentry_is_expired - Check if negative dentry lookup has expired + * + * This should be called to know if a negative dentry should be removed from + * cache. + * + * @dentry: dentry in question + * + */ +static bool v9fs_ndentry_is_expired(struct dentry const *dentry) +{ + struct v9fs_session_info *v9ses = v9fs_dentry2v9ses(dentry); + struct v9fs_dentry *v9fs_dentry = to_v9fs_dentry(dentry); + + if (v9ses->ndentry_timeout_ms == NDENTRY_TIMEOUT_NEVER) + return false; + + return time_before_eq64(v9fs_dentry->expire_time, get_jiffies_64()); +} + +/** + * v9fs_ndentry_refresh_timeout - Refresh negative dentry lookup cache timeout + * + * This should be called when a look up yields a negative entry. + * + * @dentry: dentry in question + * + */ +void v9fs_ndentry_refresh_timeout(struct dentry *dentry) +{ + struct v9fs_session_info *v9ses = v9fs_dentry2v9ses(dentry); + struct v9fs_dentry *v9fs_dentry = to_v9fs_dentry(dentry); + + if (v9ses->ndentry_timeout_ms == NDENTRY_TIMEOUT_NEVER) + return; + + v9fs_dentry->expire_time = get_jiffies_64() + + msecs_to_jiffies(v9ses->ndentry_timeout_ms); +} + /** * v9fs_cached_dentry_delete - called when dentry refcount equals 0 * @dentry: dentry in question @@ -33,20 +73,15 @@ static int v9fs_cached_dentry_delete(const struct dentry *dentry) p9_debug(P9_DEBUG_VFS, " dentry: %pd (%p)\n", dentry, dentry); - /* Don't cache negative dentries */ - if (d_really_is_negative(dentry)) - return 1; - return 0; -} + if (!d_really_is_negative(dentry)) + return 0; -/** - * v9fs_dentry_release - called when dentry is going to be freed - * @dentry: dentry that is being release - * - */ + return v9fs_ndentry_is_expired(dentry); +} -static void v9fs_dentry_release(struct dentry *dentry) +static void __v9fs_dentry_fid_remove(struct dentry *dentry) { + struct v9fs_dentry *v9fs_dentry = to_v9fs_dentry(dentry); struct hlist_node *p, *n; struct hlist_head head; @@ -54,13 +89,54 @@ static void v9fs_dentry_release(struct dentry *dentry) dentry, dentry); spin_lock(&dentry->d_lock); - hlist_move_list((struct hlist_head *)&dentry->d_fsdata, &head); + hlist_move_list(&v9fs_dentry->head, &head); spin_unlock(&dentry->d_lock); hlist_for_each_safe(p, n, &head) p9_fid_put(hlist_entry(p, struct p9_fid, dlist)); } +/** + * v9fs_dentry_fid_remove - Release all dentry's fids + * @dentry: dentry in question + * + */ +void v9fs_dentry_fid_remove(struct dentry *dentry) +{ + __v9fs_dentry_fid_remove(dentry); +} + +/** + * v9fs_dentry_init - Initialize v9fs dentry data + * @dentry: dentry in question + * + */ +static int v9fs_dentry_init(struct dentry *dentry) +{ + struct v9fs_dentry *v9fs_dentry = kzalloc(sizeof(*v9fs_dentry), + GFP_KERNEL); + + if (!v9fs_dentry) + return -ENOMEM; + + INIT_HLIST_HEAD(&v9fs_dentry->head); + dentry->d_fsdata = (void *)v9fs_dentry; + return 0; +} + +/** + * v9fs_dentry_release - called when dentry is going to be freed + * @dentry: dentry that is being released + * + */ +static void v9fs_dentry_release(struct dentry *dentry) +{ + struct v9fs_dentry *v9fs_dentry = to_v9fs_dentry(dentry); + + __v9fs_dentry_fid_remove(dentry); + kfree_rcu(v9fs_dentry, rcu); +} + static int __v9fs_lookup_revalidate(struct dentry *dentry, unsigned int flags) { struct p9_fid *fid; @@ -72,7 +148,7 @@ static int __v9fs_lookup_revalidate(struct dentry *dentry, unsigned int flags) inode = d_inode(dentry); if (!inode) - goto out_valid; + return !v9fs_ndentry_is_expired(dentry); v9inode = V9FS_I(inode); if (v9inode->cache_validity & V9FS_INO_INVALID_ATTR) { @@ -113,7 +189,6 @@ static int __v9fs_lookup_revalidate(struct dentry *dentry, unsigned int flags) return retval; } } -out_valid: p9_debug(P9_DEBUG_VFS, "dentry: %pd (%p) is valid\n", dentry, dentry); return 1; } @@ -140,12 +215,14 @@ const struct dentry_operations v9fs_cached_dentry_operations = { .d_revalidate = v9fs_lookup_revalidate, .d_weak_revalidate = __v9fs_lookup_revalidate, .d_delete = v9fs_cached_dentry_delete, + .d_init = v9fs_dentry_init, .d_release = v9fs_dentry_release, .d_unalias_trylock = v9fs_dentry_unalias_trylock, .d_unalias_unlock = v9fs_dentry_unalias_unlock, }; const struct dentry_operations v9fs_dentry_operations = { + .d_init = v9fs_dentry_init, .d_release = v9fs_dentry_release, .d_unalias_trylock = v9fs_dentry_unalias_trylock, .d_unalias_unlock = v9fs_dentry_unalias_unlock, diff --git a/fs/9p/vfs_dir.c b/fs/9p/vfs_dir.c index 323f85352f6a..733ec42258bc 100644 --- a/fs/9p/vfs_dir.c +++ b/fs/9p/vfs_dir.c @@ -196,8 +196,12 @@ static int v9fs_dir_readdir_dotl(struct file *file, struct dir_context *ctx) if (!dir_emit(ctx, curdirent.d_name, strlen(curdirent.d_name), QID2INO(&curdirent.qid), - curdirent.d_type)) + curdirent.d_type)) { + kfree(curdirent.d_name); return 0; + } + + kfree(curdirent.d_name); ctx->pos = curdirent.d_off; rdir->head += err; diff --git a/fs/9p/vfs_inode.c b/fs/9p/vfs_inode.c index 34fda75c7760..32a2b45743f0 100644 --- a/fs/9p/vfs_inode.c +++ b/fs/9p/vfs_inode.c @@ -302,10 +302,12 @@ int v9fs_init_inode(struct v9fs_session_info *v9ses, goto error; } - if (v9fs_proto_dotl(v9ses)) + if (v9fs_proto_dotl(v9ses)) { inode->i_op = &v9fs_symlink_inode_operations_dotl; - else + inode_nohighmem(inode); + } else { inode->i_op = &v9fs_symlink_inode_operations; + } break; case S_IFDIR: @@ -566,7 +568,7 @@ static int v9fs_remove(struct inode *dir, struct dentry *dentry, int flags) /* invalidate all fids associated with dentry */ /* NOTE: This will not include open fids */ - dentry->d_op->d_release(dentry); + v9fs_dentry_fid_remove(dentry); } return retval; } @@ -742,14 +744,16 @@ struct dentry *v9fs_vfs_lookup(struct inode *dir, struct dentry *dentry, name = dentry->d_name.name; fid = p9_client_walk(dfid, 1, &name, 1); p9_fid_put(dfid); - if (fid == ERR_PTR(-ENOENT)) + if (fid == ERR_PTR(-ENOENT)) { inode = NULL; - else if (IS_ERR(fid)) + v9fs_ndentry_refresh_timeout(dentry); + } else if (IS_ERR(fid)) { inode = ERR_CAST(fid); - else if (v9ses->cache & (CACHE_META|CACHE_LOOSE)) + } else if (v9ses->cache & (CACHE_META|CACHE_LOOSE)) { inode = v9fs_get_inode_from_fid(v9ses, fid, dir->i_sb); - else + } else { inode = v9fs_get_new_inode_from_fid(v9ses, fid, dir->i_sb); + } /* * If we had a rename on the server and a parallel lookup * for the new name, then make sure we instantiate with @@ -807,6 +811,16 @@ v9fs_vfs_atomic_open(struct inode *dir, struct dentry *dentry, v9fs_invalidate_inode_attr(dir); inode = d_inode(dentry); v9inode = V9FS_I(inode); + if (!S_ISREG(inode->i_mode)) { + /* + * Not a regular file. v9fs_create() already stored the + * unopened fid on the dentry. Clunk the opened fid from + * the create and let the VFS call ->open. + */ + p9_fid_put(fid); + file->f_mode |= FMODE_CREATED; + return finish_no_open(file, NULL); + } err = finish_open(file, dentry, generic_file_open); if (unlikely(err)) { p9_fid_put(fid); diff --git a/fs/9p/vfs_inode_dotl.c b/fs/9p/vfs_inode_dotl.c index cbc72a17b01a..4240b3588c53 100644 --- a/fs/9p/vfs_inode_dotl.c +++ b/fs/9p/vfs_inode_dotl.c @@ -313,20 +313,40 @@ v9fs_vfs_atomic_open_dotl(struct inode *dir, struct dentry *dentry, v9fs_fid_add(dentry, &fid); d_instantiate(dentry, inode); + if (!S_ISREG(inode->i_mode)) { + /* + * Not a regular file. The unopened fid is already on the + * dentry. Clunk the opened create fid and let the VFS call + * ->open. + */ + p9_fid_put(ofid); + ofid = NULL; + file->f_mode |= FMODE_CREATED; + err = finish_no_open(file, NULL); + goto out; + } /* Since we are opening a file, assign the open fid to the file */ err = finish_open(file, dentry, generic_file_open); if (err) goto out; - file->private_data = ofid; + /* + * Special files have type-specific fops that own + * file->private_data. The create fid is unused + * there: leave it for p9_fid_put() on the out + * path so it is clunked before we return. + */ + if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode)) { + file->private_data = ofid; #ifdef CONFIG_9P_FSCACHE - if (v9ses->cache & CACHE_FSCACHE) { - struct v9fs_inode *v9inode = V9FS_I(inode); - fscache_use_cookie(v9fs_inode_cookie(v9inode), - file->f_mode & FMODE_WRITE); - } + if (v9ses->cache & CACHE_FSCACHE) { + struct v9fs_inode *v9inode = V9FS_I(inode); + fscache_use_cookie(v9fs_inode_cookie(v9inode), + file->f_mode & FMODE_WRITE); + } #endif - v9fs_fid_add_modes(ofid, v9ses->flags, v9ses->cache, flags); - v9fs_open_fid_add(inode, &ofid); + v9fs_fid_add_modes(ofid, v9ses->flags, v9ses->cache, flags); + v9fs_open_fid_add(inode, &ofid); + } file->f_mode |= FMODE_CREATED; out: p9_fid_put(dfid); @@ -686,9 +706,11 @@ v9fs_vfs_symlink_dotl(struct mnt_idmap *idmap, struct inode *dir, int err; kgid_t gid; const unsigned char *name; + struct v9fs_session_info *v9ses; struct p9_qid qid; struct p9_fid *dfid; struct p9_fid *fid = NULL; + struct inode *inode; name = dentry->d_name.name; p9_debug(P9_DEBUG_VFS, "%lu,%s,%s\n", dir->i_ino, name, symname); @@ -712,6 +734,26 @@ v9fs_vfs_symlink_dotl(struct mnt_idmap *idmap, struct inode *dir, v9fs_invalidate_inode_attr(dir); + /* instantiate inode and assign the unopened fid to the dentry */ + fid = p9_client_walk(dfid, 1, &name, 1); + if (IS_ERR(fid)) { + err = PTR_ERR(fid); + p9_debug(P9_DEBUG_VFS, "p9_client_walk failed %d\n", + err); + goto error; + } + + v9ses = v9fs_inode2v9ses(dir); + inode = v9fs_get_new_inode_from_fid(v9ses, fid, dir->i_sb); + if (IS_ERR(inode)) { + err = PTR_ERR(inode); + p9_debug(P9_DEBUG_VFS, "inode creation failed %d\n", + err); + goto error; + } + v9fs_fid_add(dentry, &fid); + d_instantiate(dentry, inode); + err = 0; error: p9_fid_put(fid); p9_fid_put(dfid); @@ -853,16 +895,18 @@ v9fs_vfs_mknod_dotl(struct mnt_idmap *idmap, struct inode *dir, } /** - * v9fs_vfs_get_link_dotl - follow a symlink path + * v9fs_vfs_get_link_nocache_dotl - Resolve a symlink directly. + * + * To be used when symlink caching is not enabled. + * * @dentry: dentry for symlink * @inode: inode for symlink * @done: destructor for return value */ - static const char * -v9fs_vfs_get_link_dotl(struct dentry *dentry, - struct inode *inode, - struct delayed_call *done) +v9fs_vfs_get_link_nocache_dotl(struct dentry *dentry, + struct inode *inode, + struct delayed_call *done) { struct p9_fid *fid; char *target; @@ -884,6 +928,26 @@ v9fs_vfs_get_link_dotl(struct dentry *dentry, return target; } +/** + * v9fs_vfs_get_link_dotl - follow a symlink path + * @dentry: dentry for symlink + * @inode: inode for symlink + * @done: destructor for return value + */ +static const char * +v9fs_vfs_get_link_dotl(struct dentry *dentry, + struct inode *inode, + struct delayed_call *done) +{ + struct v9fs_session_info *v9ses; + + v9ses = v9fs_inode2v9ses(inode); + if (v9ses->cache & (CACHE_META|CACHE_LOOSE)) + return page_get_link(dentry, inode, done); + + return v9fs_vfs_get_link_nocache_dotl(dentry, inode, done); +} + int v9fs_refresh_inode_dotl(struct p9_fid *fid, struct inode *inode) { struct p9_stat_dotl *st; diff --git a/fs/9p/vfs_super.c b/fs/9p/vfs_super.c index 1581ebac5bb4..d3c4eade1135 100644 --- a/fs/9p/vfs_super.c +++ b/fs/9p/vfs_super.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -30,32 +31,10 @@ static const struct super_operations v9fs_super_ops, v9fs_super_ops_dotl; -/** - * v9fs_set_super - set the superblock - * @s: super block - * @data: file system specific data - * - */ - -static int v9fs_set_super(struct super_block *s, void *data) -{ - s->s_fs_info = data; - return set_anon_super(s, data); -} - -/** - * v9fs_fill_super - populate superblock with info - * @sb: superblock - * @v9ses: session information - * @flags: flags propagated from v9fs_mount() - * - */ - -static int -v9fs_fill_super(struct super_block *sb, struct v9fs_session_info *v9ses, - int flags) +static int v9fs_fill_super(struct super_block *sb) { int ret; + struct v9fs_session_info *v9ses = v9ses = sb->s_fs_info; sb->s_maxbytes = MAX_LFS_FILESIZE; sb->s_blocksize_bits = fls(v9ses->maxdata - 1); @@ -95,16 +74,12 @@ v9fs_fill_super(struct super_block *sb, struct v9fs_session_info *v9ses, } /** - * v9fs_mount - mount a superblock - * @fs_type: file system type - * @flags: mount flags - * @dev_name: device name that was mounted - * @data: mount options + * v9fs_get_tree - create the mountable root and superblock + * @fc: the filesystem context * */ -static struct dentry *v9fs_mount(struct file_system_type *fs_type, int flags, - const char *dev_name, void *data) +static int v9fs_get_tree(struct fs_context *fc) { struct super_block *sb = NULL; struct inode *inode = NULL; @@ -117,20 +92,21 @@ static struct dentry *v9fs_mount(struct file_system_type *fs_type, int flags, v9ses = kzalloc(sizeof(struct v9fs_session_info), GFP_KERNEL); if (!v9ses) - return ERR_PTR(-ENOMEM); + return -ENOMEM; - fid = v9fs_session_init(v9ses, dev_name, data); + fid = v9fs_session_init(v9ses, fc); if (IS_ERR(fid)) { retval = PTR_ERR(fid); goto free_session; } - sb = sget(fs_type, NULL, v9fs_set_super, flags, v9ses); + fc->s_fs_info = v9ses; + sb = sget_fc(fc, NULL, set_anon_super_fc); if (IS_ERR(sb)) { retval = PTR_ERR(sb); goto clunk_fid; } - retval = v9fs_fill_super(sb, v9ses, flags); + retval = v9fs_fill_super(sb); if (retval) goto release_sb; @@ -159,14 +135,15 @@ static struct dentry *v9fs_mount(struct file_system_type *fs_type, int flags, v9fs_fid_add(root, &fid); p9_debug(P9_DEBUG_VFS, " simple set mount, return 0\n"); - return dget(sb->s_root); + fc->root = dget(sb->s_root); + return 0; clunk_fid: p9_fid_put(fid); v9fs_session_close(v9ses); free_session: kfree(v9ses); - return ERR_PTR(retval); + return retval; release_sb: /* @@ -177,7 +154,7 @@ static struct dentry *v9fs_mount(struct file_system_type *fs_type, int flags, */ p9_fid_put(fid); deactivate_locked_super(sb); - return ERR_PTR(retval); + return retval; } /** @@ -196,8 +173,8 @@ static void v9fs_kill_super(struct super_block *s) v9fs_session_cancel(v9ses); v9fs_session_close(v9ses); - kfree(v9ses); - s->s_fs_info = NULL; + /* v9fs_vfs_get_link_dotl() may still read ->cache in rcu pathwalk */ + kfree_rcu(v9ses, rcu); p9_debug(P9_DEBUG_VFS, "exiting kill_super\n"); } @@ -303,11 +280,87 @@ static const struct super_operations v9fs_super_ops_dotl = { .write_inode = v9fs_write_inode_dotl, }; +static void v9fs_free_fc(struct fs_context *fc) +{ + struct v9fs_context *ctx = fc->fs_private; + + if (!ctx) + return; + + /* These should be NULL by now but guard against leaks */ + kfree(ctx->session_opts.uname); + kfree(ctx->session_opts.aname); +#ifdef CONFIG_9P_FSCACHE + kfree(ctx->session_opts.cachetag); +#endif + if (ctx->client_opts.trans_mod) + v9fs_put_trans(ctx->client_opts.trans_mod); + kfree(ctx); +} + +static const struct fs_context_operations v9fs_context_ops = { + .parse_param = v9fs_parse_param, + .get_tree = v9fs_get_tree, + .free = v9fs_free_fc, +}; + +static int v9fs_init_fs_context(struct fs_context *fc) +{ + struct v9fs_context *ctx; + + ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); + if (!ctx) + return -ENOMEM; + + fc->ops = &v9fs_context_ops; + fc->fs_private = ctx; + + /* initialize core options */ + ctx->session_opts.afid = ~0; + ctx->session_opts.cache = CACHE_NONE; + ctx->session_opts.session_lock_timeout = P9_LOCK_TIMEOUT; + ctx->session_opts.uname = kstrdup(V9FS_DEFUSER, GFP_KERNEL); + if (!ctx->session_opts.uname) + goto error; + + ctx->session_opts.aname = kstrdup(V9FS_DEFANAME, GFP_KERNEL); + if (!ctx->session_opts.aname) + goto error; + + ctx->session_opts.uid = INVALID_UID; + ctx->session_opts.dfltuid = V9FS_DEFUID; + ctx->session_opts.dfltgid = V9FS_DEFGID; + ctx->session_opts.ndentry_timeout_ms = 0; + + /* initialize client options */ + ctx->client_opts.proto_version = p9_proto_2000L; + ctx->client_opts.msize = DEFAULT_MSIZE; + + /* initialize fd transport options */ + ctx->fd_opts.port = P9_FD_PORT; + ctx->fd_opts.rfd = ~0; + ctx->fd_opts.wfd = ~0; + ctx->fd_opts.privport = false; + + /* initialize rdma transport options */ + ctx->rdma_opts.port = P9_RDMA_PORT; + ctx->rdma_opts.sq_depth = P9_RDMA_SQ_DEPTH; + ctx->rdma_opts.rq_depth = P9_RDMA_RQ_DEPTH; + ctx->rdma_opts.timeout = P9_RDMA_TIMEOUT; + ctx->rdma_opts.privport = false; + + return 0; +error: + fc->need_free = 1; + return -ENOMEM; +} + struct file_system_type v9fs_fs_type = { .name = "9p", - .mount = v9fs_mount, .kill_sb = v9fs_kill_super, .owner = THIS_MODULE, .fs_flags = FS_RENAME_DOES_D_MOVE, + .init_fs_context = v9fs_init_fs_context, + .parameters = v9fs_param_spec, }; MODULE_ALIAS_FS("9p"); diff --git a/fs/adfs/dir_fplus.c b/fs/adfs/dir_fplus.c index 4a15924014da..c68c301d8903 100644 --- a/fs/adfs/dir_fplus.c +++ b/fs/adfs/dir_fplus.c @@ -192,6 +192,8 @@ adfs_fplus_getnext(struct adfs_dir *dir, struct object_info *obj) obj->indaddr = le32_to_cpu(bde.bigdirindaddr); obj->attr = le32_to_cpu(bde.bigdirattr); obj->name_len = le32_to_cpu(bde.bigdirobnamelen); + if (obj->name_len > ADFS_MAX_NAME_LEN - 4) /* leave room for ,xyz suffix */ + return -EIO; offset = adfs_fplus_offset(h, le32_to_cpu(h->bigdirentries)); offset += le32_to_cpu(bde.bigdirobnameptr); diff --git a/fs/aio.c b/fs/aio.c index e06fa57b05ca..d196ef37bcbf 100644 --- a/fs/aio.c +++ b/fs/aio.c @@ -369,7 +369,8 @@ static int aio_ring_mremap(struct vm_area_struct *vma) ctx = rcu_dereference(table->table[i]); if (ctx && ctx->aio_ring_file == file) { - if (!atomic_read(&ctx->dead)) { + if (!atomic_read(&ctx->dead) && + (ctx->mmap_size == (vma->vm_end - vma->vm_start))) { ctx->user_id = ctx->mmap_base = vma->vm_start; res = 0; } @@ -909,7 +910,7 @@ void exit_aio(struct mm_struct *mm) if (!table) return; - atomic_set(&wait.count, table->nr); + atomic_set(&wait.count, table->nr + 1); init_completion(&wait.comp); skipped = 0; @@ -933,7 +934,7 @@ void exit_aio(struct mm_struct *mm) kill_ioctx(mm, ctx, &wait); } - if (!atomic_sub_and_test(skipped, &wait.count)) { + if (!atomic_sub_and_test(skipped + 1, &wait.count)) { /* Wait until all IO for the context are done. */ wait_for_completion(&wait.comp); } diff --git a/fs/backing-file.c b/fs/backing-file.c index ed8e793564c3..82696dbde5f8 100644 --- a/fs/backing-file.c +++ b/fs/backing-file.c @@ -114,8 +114,13 @@ struct backing_aio { static struct kmem_cache *backing_aio_cachep; +/* + * RWF_NOAPPEND stays set in ki_flags. Pass it on, because the backing file is + * in append mode as well and a new kiocb for it starts with IOCB_APPEND. + */ #define BACKING_IOCB_MASK \ - (IOCB_NOWAIT | IOCB_HIPRI | IOCB_DSYNC | IOCB_SYNC | IOCB_APPEND) + (IOCB_NOWAIT | IOCB_HIPRI | IOCB_DSYNC | IOCB_SYNC | IOCB_APPEND | \ + (__force int) RWF_NOAPPEND) static rwf_t iocb_to_rw_flags(int flags) { diff --git a/fs/btrfs/bio.c b/fs/btrfs/bio.c index d13a14314922..48fc32009660 100644 --- a/fs/btrfs/bio.c +++ b/fs/btrfs/bio.c @@ -624,6 +624,8 @@ static void run_one_async_done(struct btrfs_work *work, bool do_free) /* If an error occurred we just want to clean up the bio and move on. */ if (bio->bi_status) { + btrfs_put_bioc(async->bioc); + btrfs_bio_counter_dec(async->bbio->inode->root->fs_info); btrfs_bio_end_io(async->bbio, bio->bi_status); return; } @@ -759,6 +761,7 @@ static bool btrfs_submit_chunk(struct btrfs_bio *bbio, int mirror_num) split = btrfs_split_bio(fs_info, bbio, map_length); if (IS_ERR(split)) { status = errno_to_blk_status(PTR_ERR(split)); + btrfs_put_bioc(bioc); btrfs_bio_counter_dec(fs_info); goto end_bbio; } @@ -820,6 +823,7 @@ static bool btrfs_submit_chunk(struct btrfs_bio *bbio, int mirror_num) return map_length == length; fail: + btrfs_put_bioc(bioc); btrfs_bio_counter_dec(fs_info); /* * We have split the original bbio, now we have to end both the current diff --git a/fs/btrfs/fiemap.c b/fs/btrfs/fiemap.c index 30a0f66c9c9e..5fb7342a616d 100644 --- a/fs/btrfs/fiemap.c +++ b/fs/btrfs/fiemap.c @@ -228,7 +228,8 @@ static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo, * * 3) Share same flags */ - if (cache->offset + cache->len == offset && + if (!(flags & FIEMAP_EXTENT_ENCODED) && + cache->offset + cache->len == offset && cache->phys + cache->len == phys && cache->flags == flags) { cache->len += len; diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c index fdf37653907c..a924eeb7a661 100644 --- a/fs/btrfs/scrub.c +++ b/fs/btrfs/scrub.c @@ -3174,7 +3174,6 @@ int btrfs_scrub_dev(struct btrfs_fs_info *fs_info, u64 devid, u64 start, memalloc_nofs_restore(nofs_flag); atomic_dec(&fs_info->scrubs_running); - wake_up(&fs_info->scrub_pause_wait); if (progress) memcpy(progress, &sctx->stat, sizeof(*progress)); @@ -3187,6 +3186,13 @@ int btrfs_scrub_dev(struct btrfs_fs_info *fs_info, u64 devid, u64 start, dev->scrub_ctx = NULL; mutex_unlock(&fs_info->scrub_lock); + /* + * We have set dev->scrub_ctx to NULL, now do the wakeup as a concurrent + * scrub cancel (btrfs_scrub_cancel_dev()) waits for dev->scrub_ctx to + * be set to NULL. + */ + wake_up(&fs_info->scrub_pause_wait); + scrub_workers_put(fs_info); scrub_put_ctx(sctx); diff --git a/fs/btrfs/verity.c b/fs/btrfs/verity.c index bb2d2fc47ee9..0a8df39e82e4 100644 --- a/fs/btrfs/verity.c +++ b/fs/btrfs/verity.c @@ -609,7 +609,7 @@ static int btrfs_begin_enable_verity(struct file *filp) set_bit(BTRFS_INODE_VERITY_IN_PROGRESS, &inode->runtime_flags); btrfs_end_transaction(trans); - return 0; + return ret; } /* diff --git a/fs/btrfs/volumes.h b/fs/btrfs/volumes.h index b3b9329f4cf9..eeb0c506acfb 100644 --- a/fs/btrfs/volumes.h +++ b/fs/btrfs/volumes.h @@ -712,9 +712,8 @@ static inline enum btrfs_map_op btrfs_op(const struct bio *bio) static inline unsigned long btrfs_chunk_item_size(int num_stripes) { - ASSERT(num_stripes); - return sizeof(struct btrfs_chunk) + - sizeof(struct btrfs_stripe) * (num_stripes - 1); + return offsetof(struct btrfs_chunk, stripe) + + sizeof(struct btrfs_stripe) * num_stripes; } /* diff --git a/fs/btrfs/zoned.c b/fs/btrfs/zoned.c index 88559307bac7..a7f1a1b90864 100644 --- a/fs/btrfs/zoned.c +++ b/fs/btrfs/zoned.c @@ -642,6 +642,11 @@ struct btrfs_zoned_device_info *btrfs_clone_dev_zone_info(struct btrfs_device *o if (!zone_info) return NULL; + /* Don't let the error path free the bitmaps still owned by @orig_dev. */ + zone_info->seq_zones = NULL; + zone_info->empty_zones = NULL; + zone_info->active_zones = NULL; + zone_info->seq_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL); if (!zone_info->seq_zones) goto out; @@ -1121,11 +1126,13 @@ u64 btrfs_find_allocatable_zones(struct btrfs_device *device, u64 hole_start, return pos; } -static bool btrfs_dev_set_active_zone(struct btrfs_device *device, u64 pos) +static bool btrfs_dev_set_active_zone(struct btrfs_device *device, u64 pos, bool *new) { struct btrfs_zoned_device_info *zone_info = device->zone_info; unsigned int zno = (pos >> zone_info->zone_size_shift); + *new = false; + /* We can use any number of zones */ if (zone_info->max_active_zones == 0) return true; @@ -1137,23 +1144,29 @@ static bool btrfs_dev_set_active_zone(struct btrfs_device *device, u64 pos) if (test_and_set_bit(zno, zone_info->active_zones)) { /* Someone already set the bit */ atomic_inc(&zone_info->active_zones_left); + } else { + *new = true; } } return true; } -static void btrfs_dev_clear_active_zone(struct btrfs_device *device, u64 pos) +static bool btrfs_dev_clear_active_zone(struct btrfs_device *device, u64 pos) { struct btrfs_zoned_device_info *zone_info = device->zone_info; unsigned int zno = (pos >> zone_info->zone_size_shift); /* We can use any number of zones */ if (zone_info->max_active_zones == 0) - return; + return false; - if (test_and_clear_bit(zno, zone_info->active_zones)) + if (test_and_clear_bit(zno, zone_info->active_zones)) { atomic_inc(&zone_info->active_zones_left); + return true; + } + + return false; } int btrfs_reset_device_zone(struct btrfs_device *device, u64 physical, @@ -1365,11 +1378,13 @@ static int btrfs_load_zone_info(struct btrfs_fs_info *fs_info, int zone_idx, return 0; } + ASSERT(!test_bit(BTRFS_FS_OPEN, &fs_info->flags)); + up_read(&dev_replace->rwsem); + nofs_flag = memalloc_nofs_save(); ret = btrfs_get_dev_zone(device, info->physical, &zone); memalloc_nofs_restore(nofs_flag); if (ret) { - up_read(&dev_replace->rwsem); if (ret != -EIO && ret != -EOPNOTSUPP) return ret; info->alloc_offset = WP_MISSING_DEV; @@ -1381,7 +1396,6 @@ static int btrfs_load_zone_info(struct btrfs_fs_info *fs_info, int zone_idx, "zoned: unexpected conventional zone %llu on device %s (devid %llu)", zone.start << SECTOR_SHIFT, rcu_dereference(device->name), device->devid); - up_read(&dev_replace->rwsem); return -EIO; } @@ -1409,8 +1423,6 @@ static int btrfs_load_zone_info(struct btrfs_fs_info *fs_info, int zone_idx, break; } - up_read(&dev_replace->rwsem); - return 0; } @@ -2379,6 +2391,7 @@ bool btrfs_zone_activate(struct btrfs_block_group *block_group) u64 physical; const bool is_data = (block_group->flags & BTRFS_BLOCK_GROUP_DATA); bool ret; + bool new; int i; if (!btrfs_is_zoned(block_group->fs_info)) @@ -2429,12 +2442,12 @@ bool btrfs_zone_activate(struct btrfs_block_group *block_group) goto out_unlock; } - if (!btrfs_dev_set_active_zone(device, physical)) { + if (!btrfs_dev_set_active_zone(device, physical, &new)) { /* Cannot activate the zone */ ret = false; goto out_unlock; } - if (!is_data) + if (!is_data && new) zinfo->reserved_active_zones--; } @@ -2468,8 +2481,16 @@ static void wait_eb_writebacks(struct btrfs_block_group *block_group) continue; if (eb->start >= end) break; + /* + * Skip if we can't get the refcount for the extent buffer, + * i.e. because it was already written back. Otherwise an eb + * disappering underneath us can cause a use-after-free. + */ + if (!refcount_inc_not_zero(&eb->refs)) + continue; rcu_read_unlock(); wait_on_extent_buffer_writeback(eb); + free_extent_buffer(eb); rcu_read_lock(); } rcu_read_unlock(); @@ -2481,6 +2502,7 @@ static int call_zone_finish(struct btrfs_block_group *block_group, struct btrfs_device *device = stripe->dev; const u64 physical = stripe->physical; struct btrfs_zoned_device_info *zinfo = device->zone_info; + bool cleared; int ret; if (!device->bdev) @@ -2502,9 +2524,9 @@ static int call_zone_finish(struct btrfs_block_group *block_group, return ret; } - if (!(block_group->flags & BTRFS_BLOCK_GROUP_DATA)) + cleared = btrfs_dev_clear_active_zone(device, physical); + if (!(block_group->flags & BTRFS_BLOCK_GROUP_DATA) && cleared) zinfo->reserved_active_zones++; - btrfs_dev_clear_active_zone(device, physical); return 0; } @@ -2552,9 +2574,10 @@ static int do_zone_finish(struct btrfs_block_group *block_group, bool fully_writ /* Ensure all writes in this block group finish */ btrfs_wait_block_group_reservations(block_group); - /* No need to wait for NOCOW writers. Zoned mode does not allow that */ - btrfs_wait_ordered_roots(fs_info, U64_MAX, block_group); - /* Wait for extent buffers to be written. */ + /* + * No need to wait for NOCOW writers, as zoned mode does not + * allow that, only wait for extent buffers to be written. + */ if (is_metadata) wait_eb_writebacks(block_group); @@ -3084,6 +3107,8 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num { struct btrfs_fs_info *fs_info = space_info->fs_info; const sector_t zone_size_sectors = fs_info->zone_size >> SECTOR_SHIFT; + LIST_HEAD(retry_list); + int ret = 0; if (!btrfs_is_zoned(fs_info)) return 0; @@ -3125,11 +3150,10 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num } if (!found) { spin_unlock(&fs_info->unused_bgs_lock); - return 0; + goto out; } list_del_init(&bg->bg_list); - btrfs_put_block_group(bg); spin_unlock(&fs_info->unused_bgs_lock); /* @@ -3143,7 +3167,6 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num for (int i = 0; i < map->num_stripes; i++) { struct btrfs_io_stripe *stripe = &map->stripes[i]; unsigned int nofs_flags; - int ret; nofs_flags = memalloc_nofs_save(); ret = blkdev_zone_mgmt(stripe->dev->bdev, REQ_OP_ZONE_RESET, @@ -3153,7 +3176,7 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num if (ret) { up_read(&fs_info->dev_replace.rwsem); - return ret; + goto requeue; } } up_read(&fs_info->dev_replace.rwsem); @@ -3164,7 +3187,7 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num if (bg->ro) { spin_unlock(&bg->lock); spin_unlock(&space_info->lock); - continue; + goto requeue; } reclaimed = bg->alloc_offset; @@ -3192,10 +3215,26 @@ int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num btrfs_return_free_space(space_info, reclaimed); spin_unlock(&space_info->lock); + btrfs_put_block_group(bg); + if (num_bytes <= reclaimed) break; num_bytes -= reclaimed; + continue; + +requeue: + list_add_tail(&bg->bg_list, &retry_list); + + if (ret) + goto out; } - return 0; +out: + if (!list_empty(&retry_list)) { + spin_lock(&fs_info->unused_bgs_lock); + list_splice_tail(&retry_list, &fs_info->unused_bgs); + spin_unlock(&fs_info->unused_bgs_lock); + } + + return ret; } diff --git a/fs/btrfs/zstd.c b/fs/btrfs/zstd.c index baaf3c143632..ced6406425f9 100644 --- a/fs/btrfs/zstd.c +++ b/fs/btrfs/zstd.c @@ -347,7 +347,8 @@ void zstd_put_workspace(struct btrfs_fs_info *fs_info, struct list_head *ws) /* A node is only taken off the lru if we are the corresponding level */ if (clip_level(workspace->req_level) == workspace->level) { /* Hide a max level workspace from reclaim */ - if (list_empty(&zwsm->idle_ws[ZSTD_BTRFS_MAX_LEVEL - 1])) { + if (workspace->level == ZSTD_BTRFS_MAX_LEVEL - 1 && + list_empty(&zwsm->idle_ws[ZSTD_BTRFS_MAX_LEVEL - 1])) { INIT_LIST_HEAD(&workspace->lru_list); } else { workspace->last_used = jiffies; diff --git a/fs/coda/file.c b/fs/coda/file.c index a390b5d21196..33104af2c7f5 100644 --- a/fs/coda/file.c +++ b/fs/coda/file.c @@ -71,6 +71,7 @@ coda_file_write_iter(struct kiocb *iocb, struct iov_iter *to) struct file *host_file = cfi->cfi_container; loff_t ki_pos = iocb->ki_pos; size_t count = iov_iter_count(to); + rwf_t flags = (iocb->ki_flags & IOCB_APPEND) ? RWF_APPEND : RWF_NOAPPEND; ssize_t ret; ret = venus_access_intent(coda_inode->i_sb, coda_i2f(coda_inode), @@ -80,7 +81,7 @@ coda_file_write_iter(struct kiocb *iocb, struct iov_iter *to) goto finish_write; inode_lock(coda_inode); - ret = vfs_iter_write(cfi->cfi_container, to, &iocb->ki_pos, 0); + ret = vfs_iter_write(cfi->cfi_container, to, &iocb->ki_pos, flags); coda_inode->i_size = file_inode(host_file)->i_size; coda_inode->i_blocks = (coda_inode->i_size + 511) >> 9; inode_set_mtime_to_ts(coda_inode, inode_set_ctime_current(coda_inode)); diff --git a/fs/dcache.c b/fs/dcache.c index 77792a9e8673..affb972f483e 100644 --- a/fs/dcache.c +++ b/fs/dcache.c @@ -1437,21 +1437,25 @@ int path_has_submounts(const struct path *parent) } EXPORT_SYMBOL(path_has_submounts); +/* odd while d_set_mounted() runs, d_invalidate() waits on it */ +static __cacheline_aligned_in_smp DEFINE_SEQLOCK(d_set_mounted_lock); + /* * Called by mount code to set a mountpoint and check if the mountpoint is * reachable (e.g. NFS can unhash a directory dentry and then the complete * subtree can become unreachable). * * Only one of d_invalidate() and d_set_mounted() must succeed. For - * this reason take rename_lock and d_lock on dentry and ancestors. - * Likewise for dont_mount() which marks a dentry that is being removed - * under d_lock. + * this reason take rename_lock, d_set_mounted_lock and d_lock on dentry + * and ancestors. Likewise for dont_mount() which marks a dentry that + * is being removed under d_lock. */ int d_set_mounted(struct dentry *dentry) { struct dentry *p; int ret = -ENOENT; read_seqlock_excl(&rename_lock); + write_seqlock(&d_set_mounted_lock); for (p = dentry->d_parent; !IS_ROOT(p); p = p->d_parent) { /* Need exclusion wrt. d_invalidate() */ spin_lock(&p->d_lock); @@ -1469,8 +1473,9 @@ int d_set_mounted(struct dentry *dentry) ret = 0; } } - spin_unlock(&dentry->d_lock); + spin_unlock(&dentry->d_lock); out: + write_sequnlock(&d_set_mounted_lock); read_sequnlock_excl(&rename_lock); return ret; } @@ -1658,6 +1663,7 @@ static enum d_walk_ret find_submount(void *_data, struct dentry *dentry) void d_invalidate(struct dentry *dentry) { bool had_submounts = false; + unsigned seq; spin_lock(&dentry->d_lock); if (d_unhashed(dentry)) { spin_unlock(&dentry->d_lock); @@ -1670,6 +1676,11 @@ void d_invalidate(struct dentry *dentry) if (!dentry->d_inode) return; + /* wait for a d_set_mounted() that saw us hashed to set its flag */ + do { + seq = read_seqbegin(&d_set_mounted_lock); + } while (read_seqretry(&d_set_mounted_lock, seq)); + shrink_dcache_parent(dentry); for (;;) { struct dentry *victim = NULL; diff --git a/fs/dlm/config.c b/fs/dlm/config.c index 0db5ce43425c..8ea193017ee9 100644 --- a/fs/dlm/config.c +++ b/fs/dlm/config.c @@ -857,10 +857,17 @@ static ssize_t node_weight_show(struct config_item *item, char *buf) static ssize_t node_weight_store(struct config_item *item, const char *buf, size_t len) { - int rc = kstrtoint(buf, 0, &config_item_to_node(item)->weight); + struct dlm_node *node = config_item_to_node(item); + int weight; + int rc; + rc = kstrtoint(buf, 0, &weight); if (rc) return rc; + if (weight < 0) + return -EINVAL; + + node->weight = weight; return len; } diff --git a/fs/dlm/member.c b/fs/dlm/member.c index c0f557a80a75..c33782235d1b 100644 --- a/fs/dlm/member.c +++ b/fs/dlm/member.c @@ -406,7 +406,7 @@ void dlm_clear_members_gone(struct dlm_ls *ls) clear_memb_list(&ls->ls_nodes_gone, NULL); } -static void make_member_array(struct dlm_ls *ls) +static int make_member_array(struct dlm_ls *ls) { struct dlm_member *memb; int i, w, x = 0, total = 0, all_zero = 0, *array; @@ -415,8 +415,8 @@ static void make_member_array(struct dlm_ls *ls) ls->ls_node_array = NULL; list_for_each_entry(memb, &ls->ls_nodes, list) { - if (memb->weight) - total += memb->weight; + if (check_add_overflow(total, memb->weight, &total)) + return -EOVERFLOW; } /* all nodes revert to weight of 1 if all have weight 0 */ @@ -426,10 +426,9 @@ static void make_member_array(struct dlm_ls *ls) all_zero = 1; } - ls->ls_total_weight = total; array = kmalloc_array(total, sizeof(*array), GFP_NOFS); if (!array) - return; + return -ENOMEM; list_for_each_entry(memb, &ls->ls_nodes, list) { if (!all_zero && !memb->weight) @@ -446,7 +445,10 @@ static void make_member_array(struct dlm_ls *ls) array[x++] = memb->nodeid; } + ls->ls_total_weight = total; ls->ls_node_array = array; + + return 0; } /* send a status request to all members just to establish comms connections */ @@ -621,7 +623,10 @@ int dlm_recover_members(struct dlm_ls *ls, struct dlm_recover *rv, int *neg_out) } ls->ls_low_nodeid = low; - make_member_array(ls); + error = make_member_array(ls); + if (error) + return error; + *neg_out = neg; error = ping_members(ls, rv->seq); diff --git a/fs/eventpoll.c b/fs/eventpoll.c index 206b91a539a1..25eaddff3570 100644 --- a/fs/eventpoll.c +++ b/fs/eventpoll.c @@ -2088,10 +2088,17 @@ static int ep_send_events(struct eventpoll *ep, /* * Always short-circuit for fatal signals to allow threads to make a * timely exit without the chance of finding more events available and - * fetching repeatedly. + * fetching repeatedly. The wakeup that got us here may have been the + * only one for the events on ->rdllist, so pass it on to the next + * waiter, as ep_done_scan() would have. */ - if (fatal_signal_pending(current)) + if (fatal_signal_pending(current)) { + spin_lock_irq(&ep->lock); + if (!list_empty(&ep->rdllist)) + wake_up(&ep->wq); + spin_unlock_irq(&ep->lock); return -EINTR; + } init_poll_funcptr(&pt, NULL); diff --git a/fs/exfat/fatent.c b/fs/exfat/fatent.c index 825083634ba2..87c7823efa71 100644 --- a/fs/exfat/fatent.c +++ b/fs/exfat/fatent.c @@ -355,19 +355,22 @@ int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc, struct super_block *sb = inode->i_sb; struct exfat_sb_info *sbi = EXFAT_SB(sb); + mutex_lock(&sbi->bitmap_lock); + total_cnt = EXFAT_DATA_CLUSTER_COUNT(sbi); if (unlikely(total_cnt < sbi->used_clusters)) { exfat_fs_error_ratelimit(sb, "%s: invalid used clusters(t:%u,u:%u)\n", __func__, total_cnt, sbi->used_clusters); - return -EIO; + ret = -EIO; + goto unlock; } - if (num_alloc > total_cnt - sbi->used_clusters) - return -ENOSPC; - - mutex_lock(&sbi->bitmap_lock); + if (num_alloc > total_cnt - sbi->used_clusters) { + ret = -ENOSPC; + goto unlock; + } hint_clu = p_chain->dir; /* find new cluster */ @@ -431,15 +434,14 @@ int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc, } } p_chain->size++; + sbi->used_clusters++; last_clu = new_clu; if (p_chain->size == num_alloc) { sbi->clu_srch_ptr = hint_clu; - sbi->used_clusters += num_alloc; - - mutex_unlock(&sbi->bitmap_lock); - return 0; + ret = 0; + goto unlock; } hint_clu = new_clu + 1; diff --git a/fs/ext2/dir.c b/fs/ext2/dir.c index b07b3b369710..3143983f3128 100644 --- a/fs/ext2/dir.c +++ b/fs/ext2/dir.c @@ -441,6 +441,9 @@ static int ext2_handle_dirsync(struct inode *dir) { int err; + if (!IS_DIRSYNC(dir)) + return 0; + err = filemap_write_and_wait(dir->i_mapping); if (!err) err = sync_inode_metadata(dir, 1); diff --git a/fs/file.c b/fs/file.c index 28743b742e3c..a02de41c6a18 100644 --- a/fs/file.c +++ b/fs/file.c @@ -1210,14 +1210,18 @@ static inline bool file_needs_f_pos_lock(struct file *file) bool file_seek_cur_needs_f_lock(struct file *file) { - if (!(file->f_mode & FMODE_ATOMIC_POS) && !file->f_op->iterate_shared) - return false; - /* + * Files that go through f_pos_lock when they are shared, i.e. + * FMODE_ATOMIC_POS files and directories, don't need f_lock for a + * SEEK_CUR. Everything else does, since nothing else serializes + * the f_pos update. + * * Note that we are not guaranteed to be called after fdget_pos() on * this file obj, in which case the caller is expected to provide the * appropriate locking. */ + if ((file->f_mode & FMODE_ATOMIC_POS) || file->f_op->iterate_shared) + return false; return true; } diff --git a/fs/fs-writeback.c b/fs/fs-writeback.c index a390cb6b14c6..47bce548278c 100644 --- a/fs/fs-writeback.c +++ b/fs/fs-writeback.c @@ -488,6 +488,23 @@ static bool inode_do_switch_wbs(struct inode *inode, return switched; } +static inline void cgroup_writeback_pin(struct super_block *sb) +{ + atomic_inc(&sb->s_isw_nr_in_flight); +} + +static inline void cgroup_writeback_unpin(struct super_block *sb) +{ + if (atomic_dec_and_test(&sb->s_isw_nr_in_flight)) + wake_up_var(&sb->s_isw_nr_in_flight); +} + +static inline void cgroup_writeback_drain(struct super_block *sb) +{ + wait_var_event(&sb->s_isw_nr_in_flight, + !atomic_read(&sb->s_isw_nr_in_flight)); +} + static void process_inode_switch_wbs(struct bdi_writeback *new_wb, struct inode_switch_wbs_context *isw) { @@ -546,8 +563,12 @@ static void process_inode_switch_wbs(struct bdi_writeback *new_wb, wb_put_many(old_wb, nr_switched); } - for (inodep = isw->inodes; *inodep; inodep++) + for (inodep = isw->inodes; *inodep; inodep++) { + struct super_block *sb = (*inodep)->i_sb; + iput(*inodep); + cgroup_writeback_unpin(sb); + } wb_put(new_wb); kfree(isw); atomic_dec(&isw_nr_in_flight); @@ -590,16 +611,19 @@ void inode_switch_wbs_work_fn(struct work_struct *work) static bool inode_prepare_wbs_switch(struct inode *inode, struct bdi_writeback *new_wb) { + /* Avoid the atomic_inc/smp_mb dance once SB_ACTIVE is gone. */ + if (!(inode->i_sb->s_flags & SB_ACTIVE)) + return false; + /* - * Paired with smp_mb() in cgroup_writeback_umount(). - * isw_nr_in_flight must be increased before checking SB_ACTIVE and - * grabbing an inode, otherwise isw_nr_in_flight can be observed as 0 - * in cgroup_writeback_umount() and the isw_wq will be not flushed. + * Pairs with smp_mb() in cgroup_writeback_umount(): the umounter either + * sees a non-zero counter and waits, or we see SB_ACTIVE clear below. */ + cgroup_writeback_pin(inode->i_sb); smp_mb(); if (IS_DAX(inode)) - return false; + goto out_unpin; /* while holding I_WB_SWITCH, no one else can update the association */ spin_lock(&inode->i_lock); @@ -607,13 +631,17 @@ static bool inode_prepare_wbs_switch(struct inode *inode, inode->i_state & (I_WB_SWITCH | I_FREEING | I_WILL_FREE) || inode_to_wb(inode) == new_wb) { spin_unlock(&inode->i_lock); - return false; + goto out_unpin; } inode->i_state |= I_WB_SWITCH; __iget(inode); spin_unlock(&inode->i_lock); return true; + +out_unpin: + cgroup_writeback_unpin(inode->i_sb); + return false; } static void wb_queue_isw(struct bdi_writeback *wb, @@ -652,19 +680,12 @@ static void inode_switch_wbs(struct inode *inode, int new_wb_id) atomic_inc(&isw_nr_in_flight); - /* - * Paired with synchronize_rcu() in cgroup_writeback_umount(): - * holding rcu_read_lock across inode_prepare_wbs_switch() - * (covering the SB_ACTIVE check and the inode grab) and - * wb_queue_isw() ensures synchronize_rcu() cannot return until - * the work is queued, so the subsequent flush_workqueue() will - * wait for the switch. - */ - rcu_read_lock(); /* find and pin the new wb */ + rcu_read_lock(); memcg_css = css_from_id(new_wb_id, &memory_cgrp_subsys); if (memcg_css && !css_tryget(memcg_css)) memcg_css = NULL; + rcu_read_unlock(); if (!memcg_css) goto out_free; @@ -680,11 +701,9 @@ static void inode_switch_wbs(struct inode *inode, int new_wb_id) trace_inode_switch_wbs_queue(inode->i_wb, new_wb, 1); wb_queue_isw(new_wb, isw); - rcu_read_unlock(); return; out_free: - rcu_read_unlock(); atomic_dec(&isw_nr_in_flight); if (new_wb) wb_put(new_wb); @@ -765,14 +784,6 @@ bool cleanup_offline_cgwb(struct bdi_writeback *wb) * moved ones. Exclude syncs as process_inode_switch_wbs() does. */ down_read(&wb->bdi->wb_switch_rwsem); - /* - * Paired with synchronize_rcu() in cgroup_writeback_umount(). - * Holding rcu_read_lock across the SB_ACTIVE check, the inode grab - * and wb_queue_isw() ensures synchronize_rcu() cannot return until - * the work is queued, so the subsequent flush_workqueue() will wait - * for the switch. - */ - rcu_read_lock(); spin_lock(&wb->list_lock); /* * In addition to the inodes that have completed writeback, also switch @@ -791,7 +802,6 @@ bool cleanup_offline_cgwb(struct bdi_writeback *wb) /* no attached inodes? bail out */ if (nr == 0) { - rcu_read_unlock(); atomic_dec(&isw_nr_in_flight); wb_put(new_wb); kfree(isw); @@ -800,7 +810,6 @@ bool cleanup_offline_cgwb(struct bdi_writeback *wb) trace_inode_switch_wbs_queue(wb, new_wb, nr); wb_queue_isw(new_wb, isw); - rcu_read_unlock(); return restart; } @@ -1228,39 +1237,27 @@ int cgroup_writeback_by_id(u64 bdi_id, int memcg_id, } /** - * cgroup_writeback_umount - flush inode wb switches for umount + * cgroup_writeback_umount - wait for in-flight inode wb switches on @sb * @sb: target super_block * - * This function is called when a super_block is about to be destroyed and - * flushes in-flight inode wb switches. An inode wb switch goes through - * RCU and then workqueue, so the two need to be flushed in order to ensure - * that all previously scheduled switches are finished. As wb switches are - * rare occurrences and synchronize_rcu() can take a while, perform - * flushing iff wb switches are in flight. + * Wait until every inode wb switch that already passed the SB_ACTIVE + * check on this superblock has been completed by the worker. Since + * SB_ACTIVE is cleared before this is called, no new switches can start + * for @sb, so s_isw_nr_in_flight will monotonically drop to zero. */ void cgroup_writeback_umount(struct super_block *sb) { - if (!(sb->s_bdi->capabilities & BDI_CAP_WRITEBACK)) return; /* - * SB_ACTIVE should be reliably cleared before checking - * isw_nr_in_flight, see generic_shutdown_super(). + * Pairs with smp_mb() in inode_prepare_wbs_switch(): we either observe + * a non-zero counter and wait, or the switcher sees SB_ACTIVE clear + * (cleared by generic_shutdown_super()) and bails before grabbing the + * inode. */ smp_mb(); - - if (atomic_read(&isw_nr_in_flight)) { - /* - * Paired with rcu_read_lock() in inode_switch_wbs() and - * cleanup_offline_cgwb(). synchronize_rcu() waits for any - * in-flight switcher that already passed the SB_ACTIVE check - * to finish queueing its work, so flush_workqueue() below - * will then drain it. - */ - synchronize_rcu(); - flush_workqueue(isw_wq); - } + cgroup_writeback_drain(sb); } static int __init cgroup_writeback_init(void) diff --git a/fs/fuse/dev.c b/fs/fuse/dev.c index 0f9ef3ca9824..56bc4381c287 100644 --- a/fs/fuse/dev.c +++ b/fs/fuse/dev.c @@ -1129,17 +1129,10 @@ static int fuse_ref_folio(struct fuse_copy_state *cs, struct folio *folio, * done atomically */ static int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop, - unsigned offset, unsigned count, int zeroing) + unsigned offset, unsigned count) { int err; struct folio *folio = *foliop; - size_t size; - - if (folio) { - size = folio_size(folio); - if (zeroing && count < size) - folio_zero_range(folio, 0, size); - } while (count) { if (cs->write && cs->pipebufs && folio) { @@ -1156,7 +1149,7 @@ static int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop, } } else if (!cs->len) { if (cs->move_folios && folio && - offset == 0 && count == size) { + offset == 0 && count == folio_size(folio)) { err = fuse_try_move_folio(cs, foliop); if (err <= 0) return err; @@ -1197,10 +1190,25 @@ static int fuse_copy_folios(struct fuse_copy_state *cs, unsigned nbytes, for (i = 0; i < ap->num_folios && (nbytes || zeroing); i++) { int err; + struct folio *folio = ap->folios[i]; unsigned int offset = ap->descs[i].offset; - unsigned int count = min(nbytes, ap->descs[i].length); + unsigned int length = ap->descs[i].length; + unsigned int count = min(nbytes, length); + + /* + * The reply may be shorter than what was asked for. The full + * descs[i].length is reported as read, so the tail bytes the + * server did not send are about to be marked uptodate and need + * to be zeroed. + * + * Only [offset, offset + length) can be touched since the + * rest of the folio can hold blocks that are already uptodate + * or dirty, and clearing those would lose data. + */ + if (folio && zeroing && count < length) + folio_zero_range(folio, offset + count, length - count); - err = fuse_copy_folio(cs, &ap->folios[i], offset, count, zeroing); + err = fuse_copy_folio(cs, &ap->folios[i], offset, count); if (err) return err; @@ -1835,7 +1843,7 @@ static int fuse_notify_store(struct fuse_conn *fc, unsigned int size, nr_bytes = min_t(unsigned, num, folio_size(folio) - folio_offset); nr_pages = (offset + nr_bytes + PAGE_SIZE - 1) >> PAGE_SHIFT; - err = fuse_copy_folio(cs, &folio, folio_offset, nr_bytes, 0); + err = fuse_copy_folio(cs, &folio, folio_offset, nr_bytes); if (!folio_test_uptodate(folio) && !err && offset == 0 && (nr_bytes == folio_size(folio) || file_size == end)) { folio_zero_segment(folio, nr_bytes, folio_size(folio)); diff --git a/fs/fuse/file.c b/fs/fuse/file.c index dc61efd829cc..238de178611b 100644 --- a/fs/fuse/file.c +++ b/fs/fuse/file.c @@ -668,7 +668,7 @@ static void fuse_aio_complete(struct fuse_io_priv *io, int err, ssize_t pos) if (!left && !io->blocking) { ssize_t res = fuse_get_res_by_io(io); - if (res >= 0) { + if (res >= 0 && io->write) { struct inode *inode = file_inode(io->iocb->ki_filp); struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_inode *fi = get_fuse_inode(inode); diff --git a/fs/fuse/notify.c b/fs/fuse/notify.c index 7cd63502e124..f21ba27f0f82 100644 --- a/fs/fuse/notify.c +++ b/fs/fuse/notify.c @@ -184,7 +184,7 @@ static int fuse_notify_store(struct fuse_conn *fc, unsigned int size, folio_offset = offset_in_folio(folio, pos); nr_bytes = min(num, folio_size(folio) - folio_offset); - err = fuse_copy_folio(cs, &folio, folio_offset, nr_bytes, 0); + err = fuse_copy_folio(cs, &folio, folio_offset, nr_bytes); if (!folio_test_uptodate(folio) && !err && folio_offset == 0 && (nr_bytes == folio_size(folio) || file_size == end)) { folio_zero_segment(folio, nr_bytes, folio_size(folio)); diff --git a/fs/inode.c b/fs/inode.c index b60111fad771..a5333c9ff761 100644 --- a/fs/inode.c +++ b/fs/inode.c @@ -2741,9 +2741,10 @@ struct timespec64 timestamp_truncate(struct timespec64 t, struct inode *inode) { struct super_block *sb = inode->i_sb; unsigned int gran = sb->s_time_gran; + time64_t seconds = t.tv_sec; t.tv_sec = clamp(t.tv_sec, sb->s_time_min, sb->s_time_max); - if (unlikely(t.tv_sec == sb->s_time_max || t.tv_sec == sb->s_time_min)) + if (unlikely(t.tv_sec != seconds)) t.tv_nsec = 0; /* Avoid division in the common cases 1 ns and 1 s. */ diff --git a/fs/isofs/util.c b/fs/isofs/util.c index 42f479da0b28..6f9a90e58a89 100644 --- a/fs/isofs/util.c +++ b/fs/isofs/util.c @@ -25,7 +25,7 @@ struct timespec64 iso_date(u8 *p, int flags) year = (p[0] - '0') * 1000 + (p[1] - '0') * 100 + (p[2] - '0') * 10 + - (p[3] - '0') - 1900; + (p[3] - '0'); month = ((p[4] - '0') * 10 + (p[5] - '0')); day = ((p[6] - '0') * 10 + (p[7] - '0')); hour = ((p[8] - '0') * 10 + (p[9] - '0')); @@ -34,7 +34,7 @@ struct timespec64 iso_date(u8 *p, int flags) ts.tv_nsec = ((p[14] - '0') * 10 + (p[15] - '0')) * 10000000; tz = p[16]; } else { - year = p[0]; + year = p[0] + 1900; month = p[1]; day = p[2]; hour = p[3]; @@ -45,10 +45,10 @@ struct timespec64 iso_date(u8 *p, int flags) tz = flags & ISO_DATE_HIGH_SIERRA ? 0 : p[6]; } - if (year < 0) { + if (year < 1) { ts.tv_sec = 0; } else { - ts.tv_sec = mktime64(year+1900, month, day, hour, minute, second); + ts.tv_sec = mktime64(year, month, day, hour, minute, second); /* sign extend */ if (tz & 0x80) diff --git a/fs/libfs.c b/fs/libfs.c index 52f00bfc8f7b..373677e2540b 100644 --- a/fs/libfs.c +++ b/fs/libfs.c @@ -264,17 +264,18 @@ static long dentry2offset(struct dentry *dentry) return (long)dentry->d_fsdata; } -static struct lock_class_key simple_offset_lock_class; - /** * simple_offset_init - initialize an offset_ctx * @octx: directory offset map to be initialized + * @dir: the directory @octx belongs to * + * The directory's i_rwsem is the lock of the offset map. Writers hold it + * exclusive, offset_readdir() holds it shared. */ -void simple_offset_init(struct offset_ctx *octx) +void simple_offset_init(struct offset_ctx *octx, struct inode *dir) { - mt_init_flags(&octx->mt, MT_FLAGS_ALLOC_RANGE); - lockdep_set_class(&octx->mt.ma_lock, &simple_offset_lock_class); + mt_init_flags(&octx->mt, MT_FLAGS_ALLOC_RANGE | MT_FLAGS_LOCK_EXTERN); + mt_set_external_lock(&octx->mt, &dir->i_rwsem); octx->next_offset = DIR_OFFSET_MIN; } @@ -291,12 +292,13 @@ int simple_offset_add(struct offset_ctx *octx, struct dentry *dentry) unsigned long offset; int ret; + MA_STATE(mas, &octx->mt, 0, 0); + if (dentry2offset(dentry) != 0) return -EBUSY; - ret = mtree_alloc_cyclic(&octx->mt, &offset, dentry, DIR_OFFSET_MIN, - DIR_OFFSET_MAX, &octx->next_offset, - GFP_KERNEL); + ret = mas_alloc_cyclic(&mas, &offset, dentry, DIR_OFFSET_MIN, + DIR_OFFSET_MAX, &octx->next_offset, GFP_KERNEL); if (unlikely(ret < 0)) return ret == -EBUSY ? -ENOSPC : ret; @@ -309,7 +311,9 @@ static int simple_offset_replace(struct offset_ctx *octx, struct dentry *dentry, { int ret; - ret = mtree_store(&octx->mt, offset, dentry, GFP_KERNEL); + MA_STATE(mas, &octx->mt, offset, offset); + + ret = mas_store_gfp(&mas, dentry, GFP_KERNEL); if (ret) return ret; offset_set(dentry, offset); @@ -324,13 +328,14 @@ static int simple_offset_replace(struct offset_ctx *octx, struct dentry *dentry, */ void simple_offset_remove(struct offset_ctx *octx, struct dentry *dentry) { - long offset; + long offset = dentry2offset(dentry); + + MA_STATE(mas, &octx->mt, offset, offset); - offset = dentry2offset(dentry); if (offset == 0) return; - mtree_erase(&octx->mt, offset); + mas_erase(&mas); offset_set(dentry, 0); } @@ -388,16 +393,20 @@ int simple_offset_rename_exchange(struct inode *old_dir, long new_index = dentry2offset(new_dentry); int ret; + MA_STATE(old_mas, &old_ctx->mt, old_index, old_index); + MA_STATE(new_mas, &new_ctx->mt, new_index, new_index); + if (WARN_ON(!old_index || !new_index)) return -EINVAL; - ret = mtree_store(&new_ctx->mt, new_index, old_dentry, GFP_KERNEL); + ret = mas_store_gfp(&new_mas, old_dentry, GFP_KERNEL); if (WARN_ON(ret)) return ret; - ret = mtree_store(&old_ctx->mt, old_index, new_dentry, GFP_KERNEL); + ret = mas_store_gfp(&old_mas, new_dentry, GFP_KERNEL); if (WARN_ON(ret)) { - mtree_store(&new_ctx->mt, new_index, new_dentry, GFP_KERNEL); + mas_set(&new_mas, new_index); + mas_store_gfp(&new_mas, new_dentry, GFP_KERNEL); return ret; } @@ -412,11 +421,14 @@ int simple_offset_rename_exchange(struct inode *old_dir, * @octx: directory offset ctx that is about to be destroyed * * During fs teardown (eg. umount), a directory's offset map might still - * contain entries. xa_destroy() cleans out anything that remains. + * contain entries. __mt_destroy() cleans out anything that remains. + * Nothing can reach the map of a directory that is being destroyed, so + * this runs without the directory's i_rwsem. */ void simple_offset_destroy(struct offset_ctx *octx) { - mtree_destroy(&octx->mt); + mt_on_stack(octx->mt); + __mt_destroy(&octx->mt); } /** diff --git a/fs/netfs/read_retry.c b/fs/netfs/read_retry.c index 2b42758e01ec..a2150676bd98 100644 --- a/fs/netfs/read_retry.c +++ b/fs/netfs/read_retry.c @@ -28,6 +28,7 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq) struct netfs_io_subrequest *subreq; struct netfs_io_stream *stream = &rreq->io_streams[0]; struct list_head *next; + int ret; _enter("R=%x", rreq->debug_id); @@ -140,8 +141,11 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq) /* Renegotiate max_len (rsize) */ stream->sreq_max_len = subreq->len; - if (rreq->netfs_ops->prepare_read && - rreq->netfs_ops->prepare_read(subreq) < 0) { + ret = 0; + if (rreq->netfs_ops->prepare_read) + ret = rreq->netfs_ops->prepare_read(subreq); + if (ret < 0) { + subreq->error = ret; trace_netfs_sreq(subreq, netfs_sreq_trace_reprep_failed); __set_bit(NETFS_SREQ_FAILED, &subreq->flags); goto abandon; @@ -222,7 +226,9 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq) part = netfs_limit_iter(&source, 0, part, stream->sreq_max_segs); netfs_stat(&netfs_n_rh_download); - if (rreq->netfs_ops->prepare_read(subreq) < 0) { + ret = rreq->netfs_ops->prepare_read(subreq); + if (ret < 0) { + subreq->error = ret; trace_netfs_sreq(subreq, netfs_sreq_trace_reprep_failed); __set_bit(NETFS_SREQ_FAILED, &subreq->flags); goto abandon; @@ -258,10 +264,13 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq) if (!test_bit(NETFS_SREQ_FAILED, &subreq->flags) && !test_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags)) continue; - subreq->error = -ENOMEM; + if (!subreq->error || + !test_bit(NETFS_SREQ_FAILED, &subreq->flags)) + subreq->error = -ENOMEM; __set_bit(NETFS_SREQ_FAILED, &subreq->flags); __clear_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags); } + netfs_wake_collector(rreq); } /* diff --git a/fs/netfs/write_issue.c b/fs/netfs/write_issue.c index 3fd8908c251b..3644eba452db 100644 --- a/fs/netfs/write_issue.c +++ b/fs/netfs/write_issue.c @@ -252,7 +252,9 @@ void netfs_reissue_write(struct netfs_io_stream *stream, iov_iter_truncate(&subreq->io_iter, size); subreq->retry_count++; - subreq->error = 0; + /* Keep prepare_write() errno; do_issue_write() terminates FAILED. */ + if (!test_bit(NETFS_SREQ_FAILED, &subreq->flags)) + subreq->error = 0; __clear_bit(NETFS_SREQ_MADE_PROGRESS, &subreq->flags); __set_bit(NETFS_SREQ_IN_PROGRESS, &subreq->flags); netfs_stat(&netfs_n_wh_retry_write_subreq); diff --git a/fs/nfs/dir.c b/fs/nfs/dir.c index 4dc91428c79c..bd35069ffe5c 100644 --- a/fs/nfs/dir.c +++ b/fs/nfs/dir.c @@ -1255,6 +1255,8 @@ static int nfs_readdir(struct file *file, struct dir_context *ctx) spin_lock(&file->f_lock); desc->dir_cookie = dir_ctx->dir_cookie; desc->folio_index = dir_ctx->page_index; + desc->current_index = (loff_t)desc->folio_index * + nfs_readdir_array_maxentries(); desc->last_cookie = dir_ctx->last_cookie; desc->attr_gencount = dir_ctx->attr_gencount; desc->eof = dir_ctx->eof; @@ -2687,7 +2689,7 @@ static bool nfs_rename_is_unsafe_cross_dir(struct dentry *old_dentry, { struct nfs_server *server = NFS_SB(old_dentry->d_sb); - if (old_dentry->d_parent != new_dentry->d_parent) + if (old_dentry->d_parent == new_dentry->d_parent) return false; if (server->fh_expire_type & NFS_FH_RENAME_UNSAFE) return !(server->fh_expire_type & NFS_FH_NOEXPIRE_WITH_OPEN); diff --git a/fs/nfs/inode.c b/fs/nfs/inode.c index 970e67768d67..f985bf55a4d5 100644 --- a/fs/nfs/inode.c +++ b/fs/nfs/inode.c @@ -662,7 +662,7 @@ static void nfs_set_timestamps_to_ts(struct inode *inode, struct iattr *attr) inode_maybe_inc_iversion(inode, updated); cache_flags |= NFS_INO_INVALID_CTIME | NFS_INO_INVALID_MTIME; } - if (attr->ia_valid & ATTR_ATIME_SET) { + if (attr->ia_valid & ATTR_ATIME) { inode_set_atime_to_ts(inode, attr->ia_atime); cache_flags |= NFS_INO_INVALID_ATIME; } @@ -758,14 +758,7 @@ nfs_setattr(struct mnt_idmap *idmap, struct dentry *dentry, } else if (nfs_have_delegated_atime(inode) && attr->ia_valid & ATTR_ATIME && !(attr->ia_valid & ATTR_MTIME)) { - if (attr->ia_valid & ATTR_ATIME_SET) { - if (uid_eq(task_uid, owner_uid)) { - spin_lock(&inode->i_lock); - nfs_set_timestamps_to_ts(inode, attr); - spin_unlock(&inode->i_lock); - attr->ia_valid &= ~(ATTR_ATIME|ATTR_ATIME_SET); - } - } else { + if (!(attr->ia_valid & (ATTR_ATIME_SET | ATTR_TIMES_SET))) { nfs_update_delegated_atime(inode); attr->ia_valid &= ~ATTR_ATIME; } diff --git a/fs/nfs/localio.c b/fs/nfs/localio.c index 3138439d1910..f4bd5922e6ba 100644 --- a/fs/nfs/localio.c +++ b/fs/nfs/localio.c @@ -204,15 +204,22 @@ void nfs_local_probe_async_work(struct work_struct *work) struct nfs_client *clp = container_of(work, struct nfs_client, cl_local_probe_work); - if (!refcount_inc_not_zero(&clp->cl_count)) - return; nfs_local_probe(clp); + /* The reference nfs_local_probe_async() took for this work */ nfs_put_client(clp); } +/* + * The work is part of the client, so it holds a reference on the client + * from when it is queued until it has run: the last nfs_put_client() + * cannot free the client under a queued probe. + */ void nfs_local_probe_async(struct nfs_client *clp) { - queue_work(nfsiod_workqueue, &clp->cl_local_probe_work); + if (!refcount_inc_not_zero(&clp->cl_count)) + return; + if (!queue_work(nfsiod_workqueue, &clp->cl_local_probe_work)) + nfs_put_client(clp); /* already queued, with its reference */ } EXPORT_SYMBOL_GPL(nfs_local_probe_async); diff --git a/fs/nfs/nfs4proc.c b/fs/nfs/nfs4proc.c index 1e8c1fe993aa..4b689334705f 100644 --- a/fs/nfs/nfs4proc.c +++ b/fs/nfs/nfs4proc.c @@ -1775,6 +1775,8 @@ static void nfs_set_open_stateid_locked(struct nfs4_state *state, { DEFINE_WAIT(wait); int status = 0; + unsigned long deadline = jiffies + 5 * HZ; + signed long remaining; for (;;) { if (nfs_stateid_is_sequential(state, stateid)) @@ -1809,7 +1811,8 @@ static void nfs_set_open_stateid_locked(struct nfs4_state *state, if (!fatal_signal_pending(current) && !nfs_current_task_exiting()) { - if (schedule_timeout(5*HZ) == 0) + remaining = (long)(deadline - jiffies); + if (remaining <= 0 || schedule_timeout(remaining) == 0) status = -EAGAIN; else status = 0; diff --git a/fs/nfs/pnfs.c b/fs/nfs/pnfs.c index 3d2d219a24e4..e389fb5159d6 100644 --- a/fs/nfs/pnfs.c +++ b/fs/nfs/pnfs.c @@ -2059,7 +2059,7 @@ static bool pnfs_within_mdsthreshold(struct nfs_open_context *ctx, break; } if (size_set && io_set) { - if (size && io) + if (size || io) ret = true; } else if (size || io) ret = true; diff --git a/fs/nfsd/nfs4state.c b/fs/nfsd/nfs4state.c index 44ca5746911c..5b97986ec244 100644 --- a/fs/nfsd/nfs4state.c +++ b/fs/nfsd/nfs4state.c @@ -88,6 +88,8 @@ static void nfsd4_end_grace(struct nfsd_net *nn); static void _free_cpntf_state_locked(struct nfsd_net *nn, struct nfs4_cpntf_state *cps); static void nfsd4_file_hash_remove(struct nfs4_file *fi); static void deleg_reaper(struct nfsd_net *nn); +static void nfsd4_drop_revoked_stid(struct nfs4_stid *s) + __releases(&s->sc_client->cl_lock); /* Locking: */ @@ -1258,6 +1260,9 @@ alloc_init_deleg(struct nfs4_client *clp, struct nfs4_file *fp, dp->dl_type = dl_type; dp->dl_retries = 1; dp->dl_recalled = false; + dp->dl_recall_rejected = false; + dp->dl_recall_grant.valid = false; + dp->dl_recall_grant.retired_at_send = false; nfsd4_init_cb(&dp->dl_recall, dp->dl_stid.sc_client, &nfsd4_cb_recall_ops, NFSPROC4_CLNT_CB_RECALL); nfsd4_init_cb(&dp->dl_cb_fattr.ncf_getattr, dp->dl_stid.sc_client, @@ -1476,27 +1481,22 @@ static void destroy_delegation(struct nfs4_delegation *dp) } /** - * revoke_delegation - perform nfs4 delegation structure cleanup - * @dp: pointer to the delegation + * revoke_delegation - dispose of a delegation the server has revoked + * @dp: delegation to dispose of + * + * The caller holds a reference on @dp, which this function consumes. + * On NFSv4.1 and newer, @dp's sc_status must already carry + * SC_STATUS_REVOKED or SC_STATUS_ADMIN_REVOKED. * - * This function assumes that it's called either from the administrative - * interface (nfsd4_revoke_states()) that's revoking a specific delegation - * stateid or it's called from a laundromat thread (nfsd4_landromat()) that - * determined that this specific state has expired and needs to be revoked - * (both mark state with the appropriate stid sc_status mode). It is also - * assumed that a reference was taken on the @dp state. This function - * consumes that reference. + * @dp is parked on the client's cl_revoked list to await a FREE_STATEID. + * Where none can arrive, @dp is destroyed here instead: FREE_STATEID has + * already freed it, or the client rejected the recall with + * NFS4ERR_BADHANDLE or NFS4ERR_BAD_STATEID and holds no record of the + * delegation. NFS4ERR_ADMIN_REVOKED still prompts one, so an + * administrative revoke waits on cl_revoked. * - * If this function finds that the @dp state is SC_STATUS_FREED it means - * that a FREE_STATEID operation for this stateid has been processed and - * we can proceed to removing it from recalled list. However, if @dp state - * isn't marked SC_STATUS_FREED, it means we need place it on the cl_revoked - * list and wait for the FREE_STATEID to arrive from the client. At the same - * time, we need to mark it as SC_STATUS_FREEABLE to indicate to the - * nfsd4_free_stateid() function that this stateid has already been added - * to the cl_revoked list and that nfsd4_free_stateid() is now responsible - * for removing it from the list. Inspection of where the delegation state - * in the revocation process is protected by the clp->cl_lock. + * Context: Takes and releases the client's cl_lock; may sleep after + * dropping it. */ static void revoke_delegation(struct nfs4_delegation *dp) { @@ -1514,6 +1514,19 @@ static void revoke_delegation(struct nfs4_delegation *dp) list_del_init(&dp->dl_recall_lru); goto out; } + if (dp->dl_recall_rejected && + !(dp->dl_stid.sc_status & SC_STATUS_ADMIN_REVOKED)) { + /* + * SC_STATUS_CLOSED, set under cl_lock, makes a racing + * FREE_STATEID bail out rather than drop this reference + * too. The put releases what cl_revoked would have held. + */ + dp->dl_stid.sc_status |= SC_STATUS_CLOSED; + spin_unlock(&clp->cl_lock); + nfs4_put_stid(&dp->dl_stid); + destroy_unhashed_deleg(dp); + return; + } list_add(&dp->dl_recall_lru, &clp->cl_revoked); dp->dl_stid.sc_status |= SC_STATUS_FREEABLE; out: @@ -2637,11 +2650,18 @@ __destroy_client(struct nfs4_client *clp) list_del_init(&dp->dl_recall_lru); destroy_unhashed_deleg(dp); } + /* + * A CB_RECALL reply can release revoked delegations concurrently: + * nfsd4_shutdown_callback() has not run yet. + */ + spin_lock(&clp->cl_lock); while (!list_empty(&clp->cl_revoked)) { dp = list_entry(clp->cl_revoked.next, struct nfs4_delegation, dl_recall_lru); - list_del_init(&dp->dl_recall_lru); - nfs4_put_stid(&dp->dl_stid); + /* this function drops ->cl_lock */ + nfsd4_drop_revoked_stid(&dp->dl_stid); + spin_lock(&clp->cl_lock); } + spin_unlock(&clp->cl_lock); while (!list_empty(&clp->cl_openowners)) { oo = list_entry(clp->cl_openowners.next, struct nfs4_openowner, oo_perclient); nfs4_get_stateowner(&oo->oo_owner); @@ -5618,6 +5638,60 @@ bool nfsd_wait_for_delegreturn(struct svc_rqst *rqstp, struct inode *inode) return timeo > 0; } +static bool nfsd4_recall_grant_slot_retired(struct nfs4_delegation *dp) +{ + struct nfs4_client *clp = dp->dl_stid.sc_client; + struct nfsd_net *nn = net_generic(clp->net, nfsd_net_id); + struct nfsd4_session *ses; + struct nfsd4_sessionid sid; + bool retired = false; + void *entry; + + if (!dp->dl_recall_grant.valid) + return false; + + /* + * gen_sessionid() composes a sessionid from the client's clientid + * and a sequence counter, so the sequence alone identifies the + * granting session. + */ + sid.clientid = clp->cl_clientid; + sid.sequence = dp->dl_recall_grant.sessionid_seq; + sid.reserved = 0; + + /* + * A missing session does not prove the client saw the grant: a + * DESTROY_SESSION unhashes its own session before the reply to + * that compound is encoded. + */ + spin_lock(&nn->client_lock); + ses = __find_in_sessionid_hashtbl((struct nfs4_sessionid *)&sid, + clp->net); + entry = ses ? xa_load(&ses->se_slots, dp->dl_recall_grant.slotid) : NULL; + if (xa_is_value(entry)) { + /* + * A slot is freed only once the client has acknowledged + * the smaller slot table, which it cannot do while a + * request on that slot is outstanding. + */ + retired = true; + } else if (entry) { + struct nfsd4_slot *slot = entry; + + /* + * A reactivated slot was freed and rebuilt, so the same + * acknowledgment applies. The seqid test errs toward + * revoking: a rebuilt slot restarting at seqid 1 matches + * an old grant. + */ + retired = (slot->sl_flags & NFSD4_SLOT_REUSED) || + ((slot->sl_flags & NFSD4_SLOT_INITIALIZED) && + slot->sl_seqid != dp->dl_recall_grant.seqid); + } + spin_unlock(&nn->client_lock); + return retired; +} + static void nfsd4_cb_recall_prepare(struct nfsd4_callback *cb) { struct nfs4_delegation *dp = cb_to_delegation(cb); @@ -5639,6 +5713,34 @@ static void nfsd4_cb_recall_prepare(struct nfsd4_callback *cb) list_add_tail(&dp->dl_recall_lru, &nn->del_recall_lru); } spin_unlock(&nn->deleg_lock); + + dp->dl_recall_grant.retired_at_send = + nfsd4_recall_grant_slot_retired(dp); +} + +/* + * cl_lock orders this against a laundromat reaping @dp: either + * revoke_delegation() observes dl_recall_rejected and destroys @dp, or + * it reached cl_revoked first and @dp is released here instead. + */ +static void nfsd4_deleg_recall_rejected(struct nfs4_delegation *dp) +{ + struct nfs4_client *clp = dp->dl_stid.sc_client; + + spin_lock(&clp->cl_lock); + if (dp->dl_stid.sc_status & (SC_STATUS_CLOSED | SC_STATUS_FREED | + SC_STATUS_ADMIN_REVOKED)) { + spin_unlock(&clp->cl_lock); + return; + } + if (dp->dl_stid.sc_status & SC_STATUS_FREEABLE) { + dp->dl_stid.sc_status |= SC_STATUS_CLOSED; + /* this function drops ->cl_lock */ + nfsd4_drop_revoked_stid(&dp->dl_stid); + return; + } + dp->dl_recall_rejected = true; + spin_unlock(&clp->cl_lock); } static int nfsd4_cb_recall_done(struct nfsd4_callback *cb, @@ -5648,27 +5750,33 @@ static int nfsd4_cb_recall_done(struct nfsd4_callback *cb, trace_nfsd_cb_recall_done(&dp->dl_stid.sc_stateid, task); - if (dp->dl_stid.sc_status) - /* CLOSED or REVOKED */ - return 1; - switch (task->tk_status) { case 0: return 1; case -NFS4ERR_DELAY: + if (dp->dl_stid.sc_status) + /* CLOSED or REVOKED */ + return 1; rpc_delay(task, 2 * HZ); return 0; case -EBADHANDLE: case -NFS4ERR_BAD_STATEID: /* - * Race: client probably got cb_recall before open reply - * granting delegation. + * Retirement of the granting slot proves the client saw + * the grant. Trust the rejection only if the slot had + * retired when this recall was sent. */ - if (dp->dl_retries--) { + if (dp->dl_recall_grant.retired_at_send) { + nfsd4_deleg_recall_rejected(dp); + return 1; + } + if (!dp->dl_stid.sc_status && dp->dl_retries--) { + dp->dl_recall_grant.retired_at_send = + nfsd4_recall_grant_slot_retired(dp); rpc_delay(task, 2 * HZ); return 0; } - fallthrough; + return 1; default: return 1; } @@ -6246,9 +6354,25 @@ static bool nfsd4_want_deleg_timestamps(const struct nfsd4_open *open) } #endif /* CONFIG NFSD_V4_DELEG_TIMESTAMPS */ +static void +nfs4_delegation_record_grant_slot(struct nfs4_delegation *dp, + const struct nfsd4_compound_state *cstate) +{ + const struct nfsd4_sessionid *sid; + + if (!cstate->session) + return; + sid = (struct nfsd4_sessionid *)cstate->session->se_sessionid.data; + dp->dl_recall_grant.sessionid_seq = sid->sequence; + dp->dl_recall_grant.slotid = cstate->slot->sl_index; + dp->dl_recall_grant.seqid = cstate->slot->sl_seqid; + dp->dl_recall_grant.valid = true; +} + static struct nfs4_delegation * -nfs4_set_delegation(struct nfsd4_open *open, struct nfs4_ol_stateid *stp, - struct svc_fh *parent) +nfs4_set_delegation(struct nfsd4_open *open, + const struct nfsd4_compound_state *cstate, + struct nfs4_ol_stateid *stp, struct svc_fh *parent) { bool deleg_ts = nfsd4_want_deleg_timestamps(open); struct nfs4_client *clp = stp->st_stid.sc_client; @@ -6338,6 +6462,13 @@ nfs4_set_delegation(struct nfsd4_open *open, struct nfs4_ol_stateid *stp, if (!dp) goto out_delegees; + /* + * Record the granting slot before kernel_setlease() makes @dp + * visible to lease breakers. A conflicting open can drive + * CB_RECALL to completion from that point on. + */ + nfs4_delegation_record_grant_slot(dp, cstate); + fl = nfs4_alloc_init_lease(dp); if (!fl) goto out_clnt_odstate; @@ -6498,6 +6629,7 @@ nfs4_open_delegation(struct svc_rqst *rqstp, struct nfsd4_open *open, struct nfs4_ol_stateid *stp, struct svc_fh *currentfh, struct svc_fh *fh) { + struct nfsd4_compoundres *resp = rqstp->rq_resp; struct nfs4_openowner *oo = openowner(stp->st_stateowner); bool deleg_ts = nfsd4_want_deleg_timestamps(open); struct nfs4_client *clp = stp->st_stid.sc_client; @@ -6534,7 +6666,7 @@ nfs4_open_delegation(struct svc_rqst *rqstp, struct nfsd4_open *open, default: goto out_no_deleg; } - dp = nfs4_set_delegation(open, stp, parent); + dp = nfs4_set_delegation(open, &resp->cstate, stp, parent); if (IS_ERR(dp)) goto out_no_deleg; diff --git a/fs/nfsd/state.h b/fs/nfsd/state.h index fd61bac52721..f7f91393e2e1 100644 --- a/fs/nfsd/state.h +++ b/fs/nfsd/state.h @@ -206,7 +206,8 @@ struct nfs4_cb_fattr { * If the server attempts to recall a delegation and the client doesn't do so * before a timeout, the server may also revoke the delegation. In that case, * the object will either be destroyed (v4.0) or moved to a per-client list of - * revoked delegations (v4.1+). + * revoked delegations (v4.1+). A v4.1+ client that rejects the recall holds + * no record of the delegation, so the object is destroyed rather than listed. * * This object is a superset of the nfs4_stid. */ @@ -222,12 +223,22 @@ struct nfs4_delegation { int dl_retries; struct nfsd4_callback dl_recall; bool dl_recalled; + bool dl_recall_rejected; bool dl_written; bool dl_setattr; /* for CB_GETATTR */ struct nfs4_cb_fattr dl_cb_fattr; + /* Forward-channel slot that carried the granting request */ + struct { + u32 sessionid_seq; + u32 slotid; + u32 seqid; + bool valid; + bool retired_at_send; + } dl_recall_grant; + /* For delegated timestamps */ struct timespec64 dl_atime; struct timespec64 dl_mtime; diff --git a/fs/notify/fanotify/fanotify.h b/fs/notify/fanotify/fanotify.h index 775f55080dd4..aa19675452d7 100644 --- a/fs/notify/fanotify/fanotify.h +++ b/fs/notify/fanotify/fanotify.h @@ -443,7 +443,7 @@ struct fanotify_perm_event { struct fanotify_event fae; struct path path; loff_t pos; /* FANOTIFY_NO_RANGE if unavailable */ - size_t count; + u64 count; u32 response; /* userspace answer to the event */ unsigned short state; /* state of the event */ unsigned short watchdog_cnt; /* already scanned by watchdog? */ diff --git a/fs/notify/fsnotify.c b/fs/notify/fsnotify.c index cae0adce6d47..f081bfba4dd9 100644 --- a/fs/notify/fsnotify.c +++ b/fs/notify/fsnotify.c @@ -210,7 +210,7 @@ static inline __u32 fsnotify_object_watched(struct inode *inode, __u32 mnt_mask, /* Report pre-content event with optional range info */ int fsnotify_pre_content(const struct path *path, const loff_t *ppos, - size_t count) + u64 count) { struct file_range range; diff --git a/fs/ntfs3/index.c b/fs/ntfs3/index.c index 97cbe176a83e..88a5f336d904 100644 --- a/fs/ntfs3/index.c +++ b/fs/ntfs3/index.c @@ -2691,18 +2691,28 @@ int indx_delete_entry(struct ntfs_index *indx, struct ntfs_inode *ni, err = attr_set_size(ni, ATTR_ALLOC, in->name, in->name_len, &indx->alloc_run, 0, NULL, false, NULL); + if (err) + goto out; + if (in->name == I30_NAME) i_size_write(&ni->vfs_inode, 0); err = ni_remove_attr(ni, ATTR_ALLOC, in->name, in->name_len, false, NULL); run_close(&indx->alloc_run); + if (err) + goto out; err = attr_set_size(ni, ATTR_BITMAP, in->name, in->name_len, &indx->bitmap_run, 0, NULL, false, NULL); + if (err) + goto out; + err = ni_remove_attr(ni, ATTR_BITMAP, in->name, in->name_len, false, NULL); run_close(&indx->bitmap_run); + if (err) + goto out; root = indx_get_root(indx, ni, &attr, &mi); if (!root) { diff --git a/fs/overlayfs/namei.c b/fs/overlayfs/namei.c index 3d03e0312561..6a8c977d6e5c 100644 --- a/fs/overlayfs/namei.c +++ b/fs/overlayfs/namei.c @@ -38,13 +38,12 @@ static int ovl_check_redirect(const struct path *path, struct ovl_lookup_data *d char *buf; struct ovl_fs *ofs = OVL_FS(d->sb); - d->absolute_redirect = false; buf = ovl_get_redirect_xattr(ofs, path, prelen + strlen(post)); if (IS_ERR_OR_NULL(buf)) return PTR_ERR(buf); - if (buf[0] == '/') { - d->absolute_redirect = true; + d->absolute_redirect = buf[0] == '/'; + if (d->absolute_redirect) { /* * One of the ancestor path elements in an absolute path * lookup in ovl_lookup_layer() could have been opaque and @@ -1048,6 +1047,14 @@ static int ovl_maybe_lookup_lowerdata(struct dentry *dentry) out_err: pr_warn_ratelimited("lazy lowerdata lookup failed (%pd2, err=%i)\n", dentry, err); + /* + * The data of a metacopy file is missing or is not a regular file in + * the data-only layers: the layers are corrupted. Do not return the + * error of the lookup (e.g. ENOENT) to the caller, it would make the + * file look like it does not exist. + */ + if (err != -ENOMEM) + err = -EIO; goto out; } diff --git a/fs/overlayfs/overlayfs.h b/fs/overlayfs/overlayfs.h index 7bd69773f33c..c3a0eb0bfd1f 100644 --- a/fs/overlayfs/overlayfs.h +++ b/fs/overlayfs/overlayfs.h @@ -74,9 +74,13 @@ enum ovl_entry_flag { }; enum { - OVL_REDIRECT_OFF, /* "off" mode is never used. In effect */ - OVL_REDIRECT_FOLLOW, /* ...it translates to either "follow" */ - OVL_REDIRECT_NOFOLLOW, /* ...or "nofollow". */ + /* + * "off" mode is never used after mount options are verified. In effect + * it translates to either "follow" or "nofollow". + */ + OVL_REDIRECT_OFF, + OVL_REDIRECT_FOLLOW, + OVL_REDIRECT_NOFOLLOW, OVL_REDIRECT_ON, }; @@ -575,6 +579,7 @@ static inline int ovl_set_impure_dir(struct dentry *dentry) bool ovl_inuse_trylock(struct dentry *dentry); void ovl_inuse_unlock(struct dentry *dentry); bool ovl_is_inuse(struct dentry *dentry); +void ovl_inuse_unlock_all(struct ovl_fs *ofs); bool ovl_need_index(struct dentry *dentry); int ovl_nlink_start(struct dentry *dentry); void ovl_nlink_end(struct dentry *dentry); diff --git a/fs/overlayfs/ovl_entry.h b/fs/overlayfs/ovl_entry.h index 80cad4ea96a3..04c9ddf6f357 100644 --- a/fs/overlayfs/ovl_entry.h +++ b/fs/overlayfs/ovl_entry.h @@ -24,6 +24,8 @@ struct ovl_config { struct ovl_sb { struct super_block *sb; dev_t pseudo_dev; + /* Idmap of the first lower layer on this fs */ + const struct mnt_idmap *lower_idmap; /* Unusable (conflicting) uuid */ bool bad_uuid; /* Used as a lower layer (but maybe also as upper) */ diff --git a/fs/overlayfs/params.c b/fs/overlayfs/params.c index 7d8bc6d3863c..588a50e33340 100644 --- a/fs/overlayfs/params.c +++ b/fs/overlayfs/params.c @@ -112,18 +112,28 @@ const struct constant_table ovl_parameter_redirect_dir[] = { {} }; +static const char *ovl_redirect_mode_name(int redirect_mode) +{ + return ovl_parameter_redirect_dir[redirect_mode].name; +} + static const char *ovl_redirect_mode(struct ovl_config *config) { - return ovl_parameter_redirect_dir[config->redirect_mode].name; + return ovl_redirect_mode_name(config->redirect_mode); } -static int ovl_redirect_mode_def(void) +static int ovl_redirect_follow_mode(void) { - return ovl_redirect_dir_def ? OVL_REDIRECT_ON : - ovl_redirect_always_follow ? OVL_REDIRECT_FOLLOW : + return ovl_redirect_always_follow ? OVL_REDIRECT_FOLLOW : OVL_REDIRECT_NOFOLLOW; } +static int ovl_redirect_mode_def(void) +{ + return ovl_redirect_dir_def ? OVL_REDIRECT_ON : + ovl_redirect_follow_mode(); +} + static const struct constant_table ovl_parameter_verity[] = { { "off", OVL_VERITY_OFF }, { "on", OVL_VERITY_ON }, @@ -656,11 +666,6 @@ static int ovl_parse_param(struct fs_context *fc, struct fs_parameter *param) break; case Opt_redirect_dir: config->redirect_mode = result.uint_32; - if (config->redirect_mode == OVL_REDIRECT_OFF) { - config->redirect_mode = ovl_redirect_always_follow ? - OVL_REDIRECT_FOLLOW : - OVL_REDIRECT_NOFOLLOW; - } ctx->set.redirect = true; break; case Opt_index: @@ -816,7 +821,13 @@ int ovl_init_fs_context(struct fs_context *fc) if (!ofs) goto out_err; - ofs->config.redirect_mode = ovl_redirect_mode_def(); + /* + * The module default determines only if new redirects are created in + * upper dir. If they are not, the redirect follow mode will be + * determined after parsing mount options. + */ + ofs->config.redirect_mode = ovl_redirect_dir_def ? + OVL_REDIRECT_ON : OVL_REDIRECT_OFF; ofs->config.index = ovl_index_def; ofs->config.uuid = ovl_uuid_def(); ofs->config.nfs_export = ovl_nfs_export_def; @@ -842,15 +853,12 @@ void ovl_free_fs(struct ovl_fs *ofs) struct vfsmount **mounts; unsigned i; + ovl_inuse_unlock_all(ofs); iput(ofs->workbasedir_trap); iput(ofs->workdir_trap); dput(ofs->whiteout); dput(ofs->workdir); - if (ofs->workdir_locked) - ovl_inuse_unlock(ofs->workbasedir); dput(ofs->workbasedir); - if (ofs->upperdir_locked) - ovl_inuse_unlock(ovl_upper_mnt(ofs)->mnt_root); /* Reuse ofs->config.lowerdirs as a vfsmount array before freeing it */ mounts = (struct vfsmount **) ofs->config.lowerdirs; @@ -877,6 +885,8 @@ int ovl_fs_params_verify(const struct ovl_fs_context *ctx, struct ovl_config *config) { struct ovl_opt_set set = ctx->set; + /* The requested redirect_dir=, for reporting conflicts with it */ + int redirect_opt = config->redirect_mode; /* Workdir/index are useless in non-upper mount */ if (!config->upperdir) { @@ -903,6 +913,10 @@ int ovl_fs_params_verify(const struct ovl_fs_context *ctx, config->uuid = OVL_UUID_NULL; } + /* Resolve redirect_dir=off to the default redirect follow mode */ + if (config->redirect_mode == OVL_REDIRECT_OFF) + config->redirect_mode = ovl_redirect_follow_mode(); + /* * This is to make the logic below simpler. It doesn't make any other * difference, since redirect_dir=on is only used for upper. @@ -914,7 +928,7 @@ int ovl_fs_params_verify(const struct ovl_fs_context *ctx, if (config->metacopy && config->redirect_mode != OVL_REDIRECT_ON) { if (set.metacopy && set.redirect) { pr_err("conflicting options: metacopy=on,redirect_dir=%s\n", - ovl_redirect_mode(config)); + ovl_redirect_mode_name(redirect_opt)); return -EINVAL; } if (set.redirect) { @@ -923,7 +937,7 @@ int ovl_fs_params_verify(const struct ovl_fs_context *ctx, * in this conflict. */ pr_info("disabling metacopy due to redirect_dir=%s\n", - ovl_redirect_mode(config)); + ovl_redirect_mode_name(redirect_opt)); config->metacopy = false; } else { /* Automatically enable redirect otherwise. */ @@ -931,6 +945,16 @@ int ovl_fs_params_verify(const struct ovl_fs_context *ctx, } } + /* Resolve nfs_export -> !data-only layers dependency */ + if (config->nfs_export && ctx->nr_data) { + if (set.nfs_export) { + pr_err("NFS export is not supported with data-only layers\n"); + return -EINVAL; + } + pr_info("disabling nfs_export due to data-only layers\n"); + config->nfs_export = false; + } + /* Resolve nfs_export -> index dependency */ if (config->nfs_export && !config->index) { if (!config->upperdir && @@ -990,7 +1014,7 @@ int ovl_fs_params_verify(const struct ovl_fs_context *ctx, if (set.redirect && config->redirect_mode != OVL_REDIRECT_NOFOLLOW) { pr_err("conflicting options: userxattr,redirect_dir=%s\n", - ovl_redirect_mode(config)); + ovl_redirect_mode_name(redirect_opt)); return -EINVAL; } if (config->metacopy && set.metacopy) { diff --git a/fs/overlayfs/super.c b/fs/overlayfs/super.c index 52d6f32a5a7c..4c19b204e53d 100644 --- a/fs/overlayfs/super.c +++ b/fs/overlayfs/super.c @@ -1124,6 +1124,29 @@ static int ovl_get_layers(struct super_block *sb, struct ovl_fs *ofs, return err; } + /* + * Lower file handles identify the lower fs, but not the layer, + * so with different idmaps on the same lower fs, index and + * nfs_export may decode a file handle through a layer with the + * wrong idmap. Following copy up origin without index is only + * used for st_ino, which does not depend on the idmap. + */ + if (i < nr_merged_lower && + (ofs->config.index || ofs->config.nfs_export)) { + const struct mnt_idmap *idmap = mnt_idmap(mnt); + struct ovl_sb *fs = &ofs->fs[fsid]; + + if (!fs->lower_idmap) { + fs->lower_idmap = idmap; + } else if (fs->lower_idmap != idmap) { + pr_err("lower layer '%pd2' conflicts with idmap of another lower layer on the same fs, mount with '-o index=off,nfs_export=off' to override.\n", + l->path.dentry); + iput(trap); + kern_unmount(mnt); + return -EINVAL; + } + } + /* * Make lower layers R/O. That way fchmod/fchown on lower file * will fail instead of modifying lower fs. @@ -1606,13 +1629,23 @@ int ovl_fill_super(struct super_block *sb, struct fs_context *fc) return err; } +static void ovl_kill_sb(struct super_block *sb) +{ + struct ovl_fs *ofs = OVL_FS(sb); + + /* Nothing can modify them now, do not hold them across the sync */ + if (ofs) + ovl_inuse_unlock_all(ofs); + kill_anon_super(sb); +} + struct file_system_type ovl_fs_type = { .owner = THIS_MODULE, .name = "overlay", .init_fs_context = ovl_init_fs_context, .parameters = ovl_parameter_spec, .fs_flags = FS_USERNS_MOUNT, - .kill_sb = kill_anon_super, + .kill_sb = ovl_kill_sb, }; MODULE_ALIAS_FS("overlay"); diff --git a/fs/overlayfs/util.c b/fs/overlayfs/util.c index f75e8009fb15..27928c9ea0eb 100644 --- a/fs/overlayfs/util.c +++ b/fs/overlayfs/util.c @@ -1064,6 +1064,18 @@ bool ovl_is_inuse(struct dentry *dentry) return inuse; } +void ovl_inuse_unlock_all(struct ovl_fs *ofs) +{ + if (ofs->workdir_locked) { + ovl_inuse_unlock(ofs->workbasedir); + ofs->workdir_locked = false; + } + if (ofs->upperdir_locked) { + ovl_inuse_unlock(ovl_upper_mnt(ofs)->mnt_root); + ofs->upperdir_locked = false; + } +} + /* * Does this overlay dentry need to be indexed on copy up? */ diff --git a/fs/pidfs.c b/fs/pidfs.c index a014db891aaa..19ffb1f0bd27 100644 --- a/fs/pidfs.c +++ b/fs/pidfs.c @@ -440,6 +440,10 @@ static long pidfd_info(struct file *file, unsigned int cmd, unsigned long arg) } copy_out: + /* Only report fields that fit into the caller's struct. */ + if (usize < PIDFD_INFO_SIZE_VER1) + kinfo.mask &= ~PIDFD_INFO_COREDUMP; + /* * If userspace and the kernel have the same struct size it can just * be copied. If userspace provides an older struct, only the bits that @@ -509,6 +513,14 @@ static long pidfd_ioctl(struct file *file, unsigned int cmd, unsigned long arg) if (arg) return -EINVAL; + /* + * Require the target to be visible in the caller's pid namespace + * for operations that grant access to its resources, mirroring + * procfs and PIDFD_GET_INFO. + */ + if (!pid_in_current_pidns(pidfd_pid(file))) + return -EREMOTE; + /* * We're trying to open a file descriptor to the namespace so perform a * filesystem cred ptrace check. Hold @task's exec_update_lock for the diff --git a/fs/proc/proc_sysctl.c b/fs/proc/proc_sysctl.c index 49ab74e0bfde..5c609c0d5c8f 100644 --- a/fs/proc/proc_sysctl.c +++ b/fs/proc/proc_sysctl.c @@ -557,6 +557,8 @@ static ssize_t proc_sys_call_handler(struct kiocb *iocb, struct iov_iter *iter, struct ctl_table_header *head = grab_header(inode); const struct ctl_table *table = PROC_I(inode)->sysctl_entry; size_t count = iov_iter_count(iter); + /* ->write_iter() must never report more than the iterator held */ + size_t orig_count = count; char *kbuf; ssize_t error; @@ -607,7 +609,8 @@ static ssize_t proc_sys_call_handler(struct kiocb *iocb, struct iov_iter *iter, goto out_free_buf; } - error = count; + /* the write path consumed at most the original iterator length */ + error = write ? min(count, orig_count) : count; out_free_buf: kvfree(kbuf); out: diff --git a/fs/read_write.c b/fs/read_write.c index 011fe55c94cd..96528614d4f3 100644 --- a/fs/read_write.c +++ b/fs/read_write.c @@ -331,13 +331,15 @@ loff_t default_llseek(struct file *file, loff_t offset, int whence) { struct inode *inode = file_inode(file); loff_t retval; + loff_t eof; retval = inode_lock_killable(inode); if (retval) return retval; + eof = i_size_read(inode); switch (whence) { case SEEK_END: - offset += i_size_read(inode); + offset += eof; break; case SEEK_CUR: if (offset == 0) { @@ -352,7 +354,7 @@ loff_t default_llseek(struct file *file, loff_t offset, int whence) * long as offset isn't at the end of the file then the * offset is data. */ - if (offset >= inode->i_size) { + if ((unsigned long long)offset >= eof) { retval = -ENXIO; goto out; } @@ -363,11 +365,11 @@ loff_t default_llseek(struct file *file, loff_t offset, int whence) * as long as offset isn't i_size or larger, return * i_size. */ - if (offset >= inode->i_size) { + if ((unsigned long long)offset >= eof) { retval = -ENXIO; goto out; } - offset = inode->i_size; + offset = eof; break; } retval = -EINVAL; diff --git a/fs/smb/client/cifsacl.c b/fs/smb/client/cifsacl.c index bb4a258b2c17..9dcda4c244c3 100644 --- a/fs/smb/client/cifsacl.c +++ b/fs/smb/client/cifsacl.c @@ -1061,7 +1061,10 @@ static void populate_new_aces(char *nacl_base, * updated in the inode. */ - if (!memcmp(pownersid, pgrpsid, sizeof(struct smb_sid))) { + if (pownersid->num_subauth == pgrpsid->num_subauth && + !memcmp(pownersid, pgrpsid, + CIFS_SID_BASE_SIZE + + pownersid->num_subauth * sizeof(__le32))) { /* * Case when owner and group SIDs are the same. * Set the more restrictive of the two modes. diff --git a/fs/smb/client/cifsacl.h b/fs/smb/client/cifsacl.h index 31b51a8fc256..ebc1b7c08c6a 100644 --- a/fs/smb/client/cifsacl.h +++ b/fs/smb/client/cifsacl.h @@ -93,18 +93,4 @@ struct owner_group_sids { struct owner_sid group; } __packed; -/* - * Minimum security identifier can be one for system defined Users - * and Groups such as NULL SID and World or Built-in accounts such - * as Administrator and Guest and consists of - * Revision + Num (Sub)Auths + Authority + Domain (one Subauthority) - */ -#define MIN_SID_LEN (1 + 1 + 6 + 4) /* in bytes */ - -/* - * Minimum security descriptor can be one without any SACL and DACL and can - * consist of revision, type, and two sids of minimum size for owner and group - */ -#define MIN_SEC_DESC_LEN (sizeof(struct smb_ntsd) + (2 * MIN_SID_LEN)) - #endif /* _CIFSACL_H */ diff --git a/fs/smb/client/cifsfs.c b/fs/smb/client/cifsfs.c index 3da0fc08ffd9..2c60e3079666 100644 --- a/fs/smb/client/cifsfs.c +++ b/fs/smb/client/cifsfs.c @@ -198,6 +198,7 @@ struct workqueue_struct *cifsoplockd_wq; struct workqueue_struct *deferredclose_wq; struct workqueue_struct *serverclose_wq; struct workqueue_struct *cfid_put_wq; +struct workqueue_struct *cifs_writeback_wq; __u32 cifs_lock_secret; /* @@ -2076,9 +2077,16 @@ init_cifs(void) goto out_destroy_serverclose_wq; } + cifs_writeback_wq = alloc_workqueue("cifswritebackd", + WQ_UNBOUND | WQ_MEM_RECLAIM, 0); + if (!cifs_writeback_wq) { + rc = -ENOMEM; + goto out_destroy_cfid_put_wq; + } + rc = cifs_init_inodecache(); if (rc) - goto out_destroy_cfid_put_wq; + goto out_destroy_writeback_wq; rc = cifs_init_netfs(); if (rc) @@ -2149,6 +2157,8 @@ init_cifs(void) cifs_destroy_netfs(); out_destroy_inodecache: cifs_destroy_inodecache(); +out_destroy_writeback_wq: + destroy_workqueue(cifs_writeback_wq); out_destroy_cfid_put_wq: destroy_workqueue(cfid_put_wq); out_destroy_serverclose_wq: @@ -2194,6 +2204,7 @@ exit_cifs(void) destroy_workqueue(fileinfo_put_wq); destroy_workqueue(serverclose_wq); destroy_workqueue(cfid_put_wq); + destroy_workqueue(cifs_writeback_wq); destroy_workqueue(cifsiod_wq); } diff --git a/fs/smb/client/cifsglob.h b/fs/smb/client/cifsglob.h index 2d5a4a26c931..ea6533d057ac 100644 --- a/fs/smb/client/cifsglob.h +++ b/fs/smb/client/cifsglob.h @@ -2108,6 +2108,7 @@ extern struct workqueue_struct *cifsoplockd_wq; extern struct workqueue_struct *deferredclose_wq; extern struct workqueue_struct *serverclose_wq; extern struct workqueue_struct *cfid_put_wq; +extern struct workqueue_struct *cifs_writeback_wq; extern __u32 cifs_lock_secret; extern mempool_t *cifs_sm_req_poolp; diff --git a/fs/smb/client/connect.c b/fs/smb/client/connect.c index b4e139471e86..4864fe6b19e3 100644 --- a/fs/smb/client/connect.c +++ b/fs/smb/client/connect.c @@ -2178,7 +2178,8 @@ void __cifs_put_smb_ses(struct cifs_ses *ses) kref_put(&ses->chans[i].iface->refcount, release_iface); ses->chans[i].iface = NULL; } - cifs_put_tcp_session(ses->chans[i].server, 0); + if (ses->chans[i].server) + cifs_put_tcp_session(ses->chans[i].server, 0); ses->chans[i].server = NULL; } diff --git a/fs/smb/client/dfs.c b/fs/smb/client/dfs.c index f65a8a90ba27..87486e67c9a1 100644 --- a/fs/smb/client/dfs.c +++ b/fs/smb/client/dfs.c @@ -33,7 +33,7 @@ int dfs_parse_target_referral(const char *full_path, const struct dfs_info3_para if (WARN_ON_ONCE(!ref->node_name || ref->path_consumed < 0)) return -EINVAL; - if (strlen(full_path) - ref->path_consumed) { + if ((size_t)ref->path_consumed < strlen(full_path)) { prepath = full_path + ref->path_consumed; /* skip initial delimiter */ if (*prepath == '/' || *prepath == '\\') @@ -103,6 +103,7 @@ static int setup_dfs_ref(struct dfs_info3_param *tgt, struct dfs_ref_walk *rw) struct cifs_sb_info *cifs_sb = rw->mnt_ctx->cifs_sb; struct smb3_fs_context *ctx = rw->mnt_ctx->fs_ctx; char *ref_path, *full_path; + const char *raw_path; int rc; set_root_smb_session(rw->mnt_ctx); @@ -114,9 +115,10 @@ static int setup_dfs_ref(struct dfs_info3_param *tgt, struct dfs_ref_walk *rw) if (!tgt || (tgt->server_type == DFS_TYPE_LINK && DFS_INTERLINK(tgt->flags))) - ref_path = dfs_get_path(cifs_sb, ctx->UNC); + raw_path = ctx->UNC; else - ref_path = dfs_get_path(cifs_sb, full_path); + raw_path = full_path; + ref_path = dfs_get_path(cifs_sb, raw_path); if (IS_ERR(ref_path)) { rc = PTR_ERR(ref_path); kfree(full_path); @@ -125,9 +127,7 @@ static int setup_dfs_ref(struct dfs_info3_param *tgt, struct dfs_ref_walk *rw) ref_walk_path(rw) = ref_path; ref_walk_fpath(rw) = full_path; - return dfs_get_referral(rw->mnt_ctx, - ref_walk_path(rw) + 1, - ref_walk_tl(rw)); + return dfs_get_referral(rw->mnt_ctx, raw_path + 1, ref_walk_tl(rw)); } static int __dfs_referral_walk(struct dfs_ref_walk *rw) diff --git a/fs/smb/client/file.c b/fs/smb/client/file.c index 35f6c1cebd1a..652206fead33 100644 --- a/fs/smb/client/file.c +++ b/fs/smb/client/file.c @@ -106,10 +106,16 @@ static void cifs_prepare_write(struct netfs_io_subrequest *subreq) #endif } +static bool cifs_writeback_dying(struct netfs_io_subrequest *subreq) +{ + return subreq->rreq->origin == NETFS_WRITEBACK && + fatal_signal_pending(current); +} + /* * Issue a subrequest to upload to the server. */ -static void cifs_issue_write(struct netfs_io_subrequest *subreq) +static void __cifs_issue_write(struct netfs_io_subrequest *subreq) { struct cifs_io_subrequest *wdata = container_of(subreq, struct cifs_io_subrequest, subreq); @@ -134,15 +140,35 @@ static void cifs_issue_write(struct netfs_io_subrequest *subreq) return; fail: - if (rc == -EAGAIN) + if (rc == -EAGAIN) { trace_netfs_sreq(subreq, netfs_sreq_trace_retry); - else + __set_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags); + } else { trace_netfs_sreq(subreq, netfs_sreq_trace_fail); + } add_credits_and_wake_if(wdata->server, &wdata->credits, 0); cifs_write_subrequest_terminated(wdata, rc); goto out; } +static void cifs_issue_write_worker(struct work_struct *work) +{ + struct netfs_io_subrequest *subreq; + + subreq = container_of(work, struct netfs_io_subrequest, work); + __cifs_issue_write(subreq); +} + +static void cifs_issue_write(struct netfs_io_subrequest *subreq) +{ + if (unlikely(cifs_writeback_dying(subreq))) { + subreq->work.func = cifs_issue_write_worker; + WARN_ON_ONCE(!queue_work(cifs_writeback_wq, &subreq->work)); + return; + } + __cifs_issue_write(subreq); +} + static void cifs_netfs_invalidate_cache(struct netfs_io_request *wreq) { cifs_invalidate_cache(wreq->inode, 0); @@ -2206,7 +2232,7 @@ cifs_get_hardlink_path(struct cifs_tcon *tcon, struct inode *inode, spin_lock(&cinode->open_file_lock); list_for_each_entry(open_file, &cinode->openFileList, flist) { - if (file->f_flags == open_file->f_flags) { + if (open_file->dentry != file_dentry(file)) { rc = -EINVAL; break; } @@ -2778,6 +2804,45 @@ cifs_get_readable_path(struct cifs_tcon *tcon, const char *name, return -ENOENT; } +static int cifs_wait_writeback_killable(struct address_space *mapping, + loff_t start, loff_t end) +{ + pgoff_t end_index = end >> PAGE_SHIFT; + pgoff_t index = start >> PAGE_SHIFT; + struct folio_batch fbatch; + int rc = 0; + + folio_batch_init(&fbatch); + while (!rc && + filemap_get_folios_tag(mapping, &index, end_index, + PAGECACHE_TAG_WRITEBACK, &fbatch)) { + for (unsigned int i = 0; + !rc && i < folio_batch_count(&fbatch); i++) + rc = folio_wait_writeback_killable(fbatch.folios[i]); + folio_batch_release(&fbatch); + cond_resched(); + } + return rc; +} + +static int cifs_file_write_and_wait_killable(struct file *file, + loff_t start, loff_t end) +{ + struct address_space *mapping = file->f_mapping; + int rc, rc2; + + if (end < start) + return 0; + + rc = filemap_fdatawrite_range(mapping, start, end); + if (cifs_wait_writeback_killable(mapping, start, end)) + return -EINTR; + rc2 = file_check_and_advance_wb_err(file); + if (!rc) + rc = rc2; + return rc; +} + /* * Flush data on a strict file. */ @@ -2789,7 +2854,7 @@ int cifs_strict_fsync(struct file *file, loff_t start, loff_t end, unsigned int xid; int rc; - rc = file_write_and_wait_range(file, start, end); + rc = cifs_file_write_and_wait_killable(file, start, end); if (rc) { trace_cifs_fsync_err(inode->i_ino, rc); return rc; @@ -2821,7 +2886,7 @@ int cifs_fsync(struct file *file, loff_t start, loff_t end, int datasync) struct inode *inode = file_inode(file); struct cifs_sb_info *cifs_sb = CIFS_FILE_SB(file); - rc = file_write_and_wait_range(file, start, end); + rc = cifs_file_write_and_wait_killable(file, start, end); if (rc) { trace_cifs_fsync_err(file_inode(file)->i_ino, rc); return rc; @@ -2862,11 +2927,19 @@ int cifs_fsync(struct file *file, loff_t start, loff_t end, int datasync) */ int cifs_flush(struct file *file, fl_owner_t id) { + struct address_space *mapping = file->f_mapping; struct inode *inode = file_inode(file); - int rc = 0; + int rc = 0, rc2; - if (file->f_mode & FMODE_WRITE) - rc = filemap_write_and_wait(inode->i_mapping); + if (file->f_mode & FMODE_WRITE) { + rc = filemap_fdatawrite(mapping); + if (fatal_signal_pending(current) || + cifs_wait_writeback_killable(mapping, 0, LLONG_MAX)) + return 0; + rc2 = filemap_check_errors(mapping); + if (!rc) + rc = rc2; + } cifs_dbg(FYI, "Flush inode %p file %p rc %d\n", inode, file, rc); if (rc) { @@ -3237,6 +3310,14 @@ void cifs_oplock_break(struct work_struct *work) __u64 persistent_fid, volatile_fid; __u16 net_fid; + /* + * Dropping the handle reference below also drops the dentry + * reference that pins this inode, and cinode is still needed to + * acknowledge the break and to report it as complete. Hold the inode + * until that is done. + */ + ihold(inode); + wait_on_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS, TASK_UNINTERRUPTIBLE); @@ -3312,6 +3393,7 @@ void cifs_oplock_break(struct work_struct *work) cifs_put_tlink(tlink); out: cifs_done_oplock_break(cinode); + iput(inode); } static int cifs_swap_activate(struct swap_info_struct *sis, diff --git a/fs/smb/client/sess.c b/fs/smb/client/sess.c index 042dcca4c3e8..d87be5896777 100644 --- a/fs/smb/client/sess.c +++ b/fs/smb/client/sess.c @@ -934,8 +934,8 @@ int decode_ntlmssp_challenge(char *bcc_ptr, int blob_len, } if (memcmp(pblob->Signature, "NTLMSSP", 8)) { - cifs_dbg(VFS, "blob signature incorrect %s\n", - pblob->Signature); + cifs_dbg(VFS, "%s: blob signature incorrect: %8phN\n", + __func__, pblob->Signature); return -EINVAL; } if (pblob->MessageType != NtLmChallenge) { diff --git a/fs/smb/client/smb2pdu.c b/fs/smb/client/smb2pdu.c index 3302923f9889..7b95493b9464 100644 --- a/fs/smb/client/smb2pdu.c +++ b/fs/smb/client/smb2pdu.c @@ -3354,11 +3354,12 @@ SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server, char *in_data, u32 indatalen, __u32 max_response_size) { - struct smb2_ioctl_req *req; struct kvec *iov = rqst->rq_iov; + struct smb2_ioctl_req *req; + u32 in_buf_len = indatalen; unsigned int total_len; - int rc; char *in_data_buf; + int rc; rc = smb2_ioctl_req_init(opcode, tcon, server, (void **) &req, &total_len); @@ -3366,15 +3367,18 @@ SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server, return rc; if (indatalen) { + if (smb3_encryption_required(tcon)) + in_buf_len = ALIGN(indatalen, 8); /* * indatalen is usually small at a couple of bytes max, so * just allocate through generic pool */ - in_data_buf = kmemdup(in_data, indatalen, GFP_NOFS); + in_data_buf = kzalloc(in_buf_len, GFP_NOFS); if (!in_data_buf) { cifs_small_buf_release(req); return -ENOMEM; } + memcpy(in_data_buf, in_data, indatalen); } req->CtlCode = cpu_to_le32(opcode); @@ -3398,7 +3402,7 @@ SMB2_ioctl_init(struct cifs_tcon *tcon, struct TCP_Server_Info *server, rqst->rq_nvec = 2; iov[0].iov_len = total_len - 1; iov[1].iov_base = in_data_buf; - iov[1].iov_len = indatalen; + iov[1].iov_len = in_buf_len; } else { rqst->rq_nvec = 1; iov[0].iov_len = total_len; @@ -3936,6 +3940,14 @@ query_info(const unsigned int xid, struct cifs_tcon *tcon, ses->Suid, info_class, (__u32)info_type); if (dlen) { + rc = smb2_validate_iov(le16_to_cpu(rsp->OutputBufferOffset), + le32_to_cpu(rsp->OutputBufferLength), + &rsp_iov, min_len); + if (rc) { + *dlen = 0; + goto qinf_exit; + } + *dlen = le32_to_cpu(rsp->OutputBufferLength); if (!*data) { *data = kmalloc(*dlen, GFP_KERNEL); @@ -4008,7 +4020,8 @@ SMB2_query_acl(const unsigned int xid, struct cifs_tcon *tcon, return query_info(xid, tcon, persistent_fid, volatile_fid, 0, SMB2_O_INFO_SECURITY, extra_info, - SMB2_MAX_BUFFER_SIZE, MIN_SEC_DESC_LEN, data, plen); + SMB2_MAX_BUFFER_SIZE, sizeof(struct smb_ntsd), + data, plen); } int diff --git a/fs/smb/server/mgmt/share_config.c b/fs/smb/server/mgmt/share_config.c index 8813a81ca662..5fbc2235ab8d 100644 --- a/fs/smb/server/mgmt/share_config.c +++ b/fs/smb/server/mgmt/share_config.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -50,6 +51,7 @@ static void kill_share(struct ksmbd_share_config *share) path_put(&share->vfs_path); kfree(share->name); kfree(share->path); + kfree(share->real_path); kfree(share); } @@ -124,6 +126,43 @@ static int parse_veto_list(struct ksmbd_share_config *share, return 0; } +static int share_config_resolve_path(struct ksmbd_share_config *share) +{ + char *buf, *path; + int ret; + + ret = kern_path(share->path, 0, &share->vfs_path); + if (ret) + return ret; + + buf = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP); + if (!buf) { + ret = -ENOMEM; + goto out; + } + + path = d_path(&share->vfs_path, buf, PATH_MAX); + if (IS_ERR(path)) { + ret = PTR_ERR(path); + goto out_buf; + } + + path = kstrdup(path, KSMBD_DEFAULT_GFP); + if (!path) { + ret = -ENOMEM; + goto out_buf; + } + + share->real_path = path; + share->real_path_sz = strlen(path); +out_buf: + kfree(buf); +out: + if (ret) + path_put(&share->vfs_path); + return ret; +} + static struct ksmbd_share_config *share_config_request(struct ksmbd_work *work, const char *name) { @@ -212,12 +251,12 @@ static struct ksmbd_share_config *share_config_request(struct ksmbd_work *work, goto out; } - ret = kern_path(share->path, 0, &share->vfs_path); + ret = share_config_resolve_path(share); ksmbd_revert_fsids(work); if (ret) { ksmbd_debug(SMB, "failed to access '%s'\n", share->path); - /* Avoid put_path() */ + /* No path reference is retained on failure. */ kfree(share->path); share->path = NULL; } diff --git a/fs/smb/server/mgmt/share_config.h b/fs/smb/server/mgmt/share_config.h index d4ac2dd4de20..baa9f9ed91cd 100644 --- a/fs/smb/server/mgmt/share_config.h +++ b/fs/smb/server/mgmt/share_config.h @@ -16,8 +16,10 @@ struct ksmbd_work; struct ksmbd_share_config { char *name; char *path; + char *real_path; unsigned int path_sz; + unsigned int real_path_sz; unsigned int flags; struct list_head veto_list; diff --git a/fs/smb/server/smb2pdu.c b/fs/smb/server/smb2pdu.c index 94a18e0ee9c2..aae6e9adf2e8 100644 --- a/fs/smb/server/smb2pdu.c +++ b/fs/smb/server/smb2pdu.c @@ -555,7 +555,8 @@ int smb2_allocate_rsp_buf(struct ksmbd_work *work) req = smb_get_msg(work->request_buf); if ((req->InfoType == SMB2_O_INFO_FILE && (req->FileInfoClass == FILE_FULL_EA_INFORMATION || - req->FileInfoClass == FILE_ALL_INFORMATION)) || + req->FileInfoClass == FILE_ALL_INFORMATION || + req->FileInfoClass == FILE_STREAM_INFORMATION)) || req->InfoType == SMB2_O_INFO_SECURITY) sz = large_sz; } @@ -2453,6 +2454,11 @@ static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len, if (!eabuf->EaNameLength) goto next; + if (eabuf->name[eabuf->EaNameLength]) { + rc = -EBADMSG; + break; + } + ksmbd_debug(SMB, "name : <%s>, name_len : %u, value_len : %u, next : %u\n", eabuf->name, eabuf->EaNameLength, @@ -3935,6 +3941,8 @@ int smb2_open(struct ksmbd_work *work) if (rc) { if (rc == -EINVAL) rsp->hdr.Status = STATUS_INVALID_PARAMETER; + else if (rc == -EBADMSG) + rsp->hdr.Status = STATUS_EA_LIST_INCONSISTENT; else if (rc == -EOPNOTSUPP) rsp->hdr.Status = STATUS_NOT_SUPPORTED; else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV) { @@ -5248,41 +5256,107 @@ static void get_file_alternate_info(struct ksmbd_work *work, cpu_to_le32(struct_size(file_info, FileName, conv_len)); } +struct smb2_stream_info_buffer { + struct smb2_query_info_rsp *rsp; + struct smb2_file_stream_info *last; + const struct nls_table *local_nls; + unsigned int length; + unsigned int capacity; +}; + +static int smb2_add_stream_info(struct smb2_stream_info_buffer *buf, + const char *name, loff_t size, u64 allocation_size) +{ + struct smb2_file_stream_info *file_info; + __le16 *utf16_name; + size_t name_len = strlen(name); + unsigned int offset = ALIGN(buf->length, 8), name_bytes; + int conv_len, ret = 0; + + if (offset > buf->capacity || + buf->capacity - offset < sizeof(*file_info)) + return -ENOSPC; + + utf16_name = kmalloc_array(name_len + 1, sizeof(*utf16_name), + KSMBD_DEFAULT_GFP); + if (!utf16_name) + return -ENOMEM; + + conv_len = smbConvertToUTF16(utf16_name, name, name_len, + buf->local_nls, 0); + if (conv_len < 0) { + ret = conv_len; + goto out; + } + + name_bytes = conv_len * sizeof(*utf16_name); + if (name_bytes > buf->capacity - offset - sizeof(*file_info)) { + ret = -ENOSPC; + goto out; + } + + file_info = (struct smb2_file_stream_info *)&buf->rsp->Buffer[offset]; + if (buf->last) { + memset(&buf->rsp->Buffer[buf->length], 0, offset - buf->length); + buf->last->NextEntryOffset = + cpu_to_le32((char *)file_info - (char *)buf->last); + } + file_info->NextEntryOffset = 0; + file_info->StreamNameLength = cpu_to_le32(name_bytes); + file_info->StreamSize = cpu_to_le64(size); + file_info->StreamAllocationSize = cpu_to_le64(allocation_size); + memcpy(file_info->StreamName, utf16_name, name_bytes); + + buf->last = file_info; + buf->length = offset + sizeof(*file_info) + name_bytes; +out: + kfree(utf16_name); + return ret; +} + static int get_file_stream_info(struct ksmbd_work *work, + struct smb2_query_info_req *req, struct smb2_query_info_rsp *rsp, - struct ksmbd_file *fp, - void *rsp_org) + struct ksmbd_file *fp) { - struct ksmbd_conn *conn = work->conn; - struct smb2_file_stream_info *file_info; + struct smb2_stream_info_buffer buf = { + .rsp = rsp, + .local_nls = work->conn->local_nls, + }; char *stream_name, *xattr_list = NULL, *stream_buf; struct kstat stat; const struct path *path = &fp->filp->f_path; ssize_t xattr_list_len; ssize_t slen; loff_t ssize; - int nbytes = 0, streamlen, stream_name_len, next, idx = 0; + unsigned int req_output_len = le32_to_cpu(req->OutputBufferLength); + int streamlen, idx = 0; int buf_free_len; int ret; + if (req_output_len < FILE_STREAM_INFORMATION_SIZE) { + rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH; + return -EINVAL; + } + + buf_free_len = smb2_calc_max_out_buf_len(work, + offsetof(struct smb2_query_info_rsp, Buffer), + req_output_len); + if (buf_free_len < 0) + return buf_free_len; + buf.capacity = buf_free_len; + ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS, AT_STATX_SYNC_AS_STAT); if (ret) return ret; - file_info = (struct smb2_file_stream_info *)rsp->Buffer; - - buf_free_len = smb2_resp_buf_len(work, - offsetof(struct smb2_query_info_rsp, Buffer)); - if (buf_free_len < 0) - goto out; - xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list); if (xattr_list_len < 0) { - goto out; + goto default_stream; } else if (!xattr_list_len) { ksmbd_debug(SMB, "empty xattr in the file\n"); - goto out; + goto default_stream; } while (idx < xattr_list_len) { @@ -5292,69 +5366,49 @@ static int get_file_stream_info(struct ksmbd_work *work, ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen); - if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN], - STREAM_PREFIX, STREAM_PREFIX_LEN)) + if (strncmp(stream_name, XATTR_NAME_STREAM, + XATTR_NAME_STREAM_LEN)) continue; - stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN + - STREAM_PREFIX_LEN); - streamlen = stream_name_len; - - /* plus : size */ - streamlen += 1; - stream_buf = kmalloc(streamlen + 1, KSMBD_DEFAULT_GFP); - if (!stream_buf) - break; - - streamlen = snprintf(stream_buf, streamlen + 1, - ":%s", &stream_name[XATTR_NAME_STREAM_LEN]); - - next = sizeof(struct smb2_file_stream_info) + streamlen * 2; - /* smbConvertToUTF16() also writes a terminating UTF-16 unit. */ - if (next + sizeof(__le16) > buf_free_len) { - kfree(stream_buf); - break; + stream_buf = kasprintf(KSMBD_DEFAULT_GFP, ":%s", + &stream_name[XATTR_NAME_STREAM_LEN]); + if (!stream_buf) { + ret = -ENOMEM; + goto out; } - - file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes]; - streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName, - stream_buf, streamlen, - conn->local_nls, 0); - streamlen *= 2; - kfree(stream_buf); - file_info->StreamNameLength = cpu_to_le32(streamlen); slen = ksmbd_vfs_xattr_len(file_mnt_idmap(fp->filp), path->dentry, stream_name); ssize = slen < 0 ? 0 : (loff_t)slen; - file_info->StreamSize = cpu_to_le64(ssize); - file_info->StreamAllocationSize = cpu_to_le64(ssize); + ret = smb2_add_stream_info(&buf, stream_buf, ssize, ssize); + kfree(stream_buf); + if (ret == -ENOSPC) + goto overflow; + if (ret) + goto out; + } - nbytes += next; - buf_free_len -= next; - file_info->NextEntryOffset = cpu_to_le32(next); +default_stream: + if (!S_ISDIR(stat.mode)) { + ret = smb2_add_stream_info(&buf, "::$DATA", stat.size, + stat.blocks << 9); + if (ret == -ENOSPC) + goto overflow; + if (ret) + goto out; } + ret = 0; + goto out; + +overflow: + rsp->hdr.Status = STATUS_BUFFER_OVERFLOW; + /* An empty overflow needs an SMB2 error response. */ + ret = buf.length ? 0 : -EOVERFLOW; out: - if (!S_ISDIR(stat.mode) && - buf_free_len >= sizeof(struct smb2_file_stream_info) + (7 + 1) * 2) { - file_info = (struct smb2_file_stream_info *) - &rsp->Buffer[nbytes]; - streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName, - "::$DATA", 7, conn->local_nls, 0); - streamlen *= 2; - file_info->StreamNameLength = cpu_to_le32(streamlen); - file_info->StreamSize = cpu_to_le64(stat.size); - file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9); - nbytes += sizeof(struct smb2_file_stream_info) + streamlen; - } - - /* last entry offset should be 0 */ - file_info->NextEntryOffset = 0; + if (!ret) + rsp->OutputBufferLength = cpu_to_le32(buf.length); kvfree(xattr_list); - - rsp->OutputBufferLength = cpu_to_le32(nbytes); - - return 0; + return ret; } static int get_file_internal_info(struct smb2_query_info_rsp *rsp, @@ -5639,7 +5693,7 @@ static int smb2_get_info_file(struct ksmbd_work *work, break; case FILE_STREAM_INFORMATION: - rc = get_file_stream_info(work, rsp, fp, work->response_buf); + rc = get_file_stream_info(work, req, rsp, fp); break; case FILE_INTERNAL_INFORMATION: @@ -6769,7 +6823,6 @@ static int set_file_mode_info(struct ksmbd_file *fp, * @share: ksmbd_share_config pointer * * Return: 0 on success, otherwise error - * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH */ static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp, struct smb2_set_info_req *req, @@ -6782,14 +6835,14 @@ static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp, case FILE_BASIC_INFORMATION: { if (buf_len < sizeof(struct smb2_file_basic_info)) - return -EINVAL; + return -EMSGSIZE; return set_file_basic_info(fp, (struct smb2_file_basic_info *)buffer, share); } case FILE_ALLOCATION_INFORMATION: { if (buf_len < sizeof(struct smb2_file_alloc_info)) - return -EINVAL; + return -EMSGSIZE; return set_file_allocation_info(work, fp, (struct smb2_file_alloc_info *)buffer); @@ -6797,7 +6850,7 @@ static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp, case FILE_END_OF_FILE_INFORMATION: { if (buf_len < sizeof(struct smb2_file_eof_info)) - return -EINVAL; + return -EMSGSIZE; return set_end_of_file_info(work, fp, (struct smb2_file_eof_info *)buffer); @@ -6805,7 +6858,7 @@ static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp, case FILE_RENAME_INFORMATION: { if (buf_len < sizeof(struct smb2_file_rename_info)) - return -EINVAL; + return -EMSGSIZE; return set_rename_info(work, fp, (struct smb2_file_rename_info *)buffer, @@ -6816,7 +6869,7 @@ static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp, struct smb2_file_link_info *file_info; if (buf_len < sizeof(struct smb2_file_link_info)) - return -EINVAL; + return -EMSGSIZE; file_info = (struct smb2_file_link_info *)buffer; if (file_info->ReplaceIfExists && !(fp->daccess & FILE_DELETE_LE)) { @@ -6831,7 +6884,7 @@ static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp, case FILE_DISPOSITION_INFORMATION: { if (buf_len < sizeof(struct smb2_file_disposition_info)) - return -EINVAL; + return -EMSGSIZE; return set_file_disposition_info(work, fp, (struct smb2_file_disposition_info *)buffer); @@ -6845,7 +6898,7 @@ static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp, } if (buf_len < sizeof(struct smb2_ea_info)) - return -EINVAL; + return -EMSGSIZE; return smb2_set_ea((struct smb2_ea_info *)buffer, buf_len, &fp->filp->f_path, true); @@ -6853,14 +6906,14 @@ static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp, case FILE_POSITION_INFORMATION: { if (buf_len < sizeof(struct smb2_file_pos_info)) - return -EINVAL; + return -EMSGSIZE; return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer); } case FILE_MODE_INFORMATION: { if (buf_len < sizeof(struct smb2_file_mode_info)) - return -EINVAL; + return -EMSGSIZE; return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer); } @@ -6968,6 +7021,10 @@ int smb2_set_info(struct ksmbd_work *work) rsp->hdr.Status = STATUS_ACCESS_DENIED; else if (rc == -EINVAL) rsp->hdr.Status = STATUS_INVALID_PARAMETER; + else if (rc == -EBADMSG) + rsp->hdr.Status = STATUS_EA_LIST_INCONSISTENT; + else if (rc == -EMSGSIZE) + rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH; else if (rc == -ESHARE) rsp->hdr.Status = STATUS_SHARING_VIOLATION; else if (rc == -ENOENT) @@ -9641,6 +9698,12 @@ int smb3_decrypt_req(struct ksmbd_work *work) return -ECONNABORTED; } + if (tr_hdr->Flags != cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED)) { + pr_err_ratelimited("Invalid transform flags 0x%04x\n", + le16_to_cpu(tr_hdr->Flags)); + return -ECONNABORTED; + } + if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) { pr_err("Transform message is broken\n"); return -ECONNABORTED; diff --git a/fs/smb/server/vfs.c b/fs/smb/server/vfs.c index a3db77b3c272..466a0853dc48 100644 --- a/fs/smb/server/vfs.c +++ b/fs/smb/server/vfs.c @@ -82,12 +82,13 @@ static int ksmbd_vfs_path_lookup(struct ksmbd_share_config *share_conf, if (do_lock) return -EINVAL; - pathname = share_conf->path; - root_share_path = NULL; - } else { - flags |= LOOKUP_BENEATH; + *path = share_conf->vfs_path; + path_get(path); + return 0; } + flags |= LOOKUP_BENEATH; + filename = getname_kernel(pathname); if (IS_ERR(filename)) return PTR_ERR(filename); diff --git a/fs/smb/server/vfs_cache.c b/fs/smb/server/vfs_cache.c index 2621d2cffe61..52389fff3d4a 100644 --- a/fs/smb/server/vfs_cache.c +++ b/fs/smb/server/vfs_cache.c @@ -1355,6 +1355,8 @@ void ksmbd_free_global_file_table(void) int ksmbd_validate_name_reconnect(struct ksmbd_share_config *share, struct ksmbd_file *fp, char *name) { + const char *share_path = share->real_path; + size_t share_path_sz = share->real_path_sz; char *pathname, *ab_pathname; int ret = 0; @@ -1371,14 +1373,18 @@ int ksmbd_validate_name_reconnect(struct ksmbd_share_config *share, if (name) { size_t len = strlen(ab_pathname); - if (len == share->path_sz && !strncmp(ab_pathname, share->path, len)) { + if (len == share_path_sz && !strncmp(ab_pathname, share_path, len)) { /* the durable fp is the share root itself */ if (name[0]) ret = -EINVAL; - } else if (len <= share->path_sz || - strncmp(ab_pathname, share->path, share->path_sz) || - ab_pathname[share->path_sz] != '/' || - strcmp(&ab_pathname[share->path_sz + 1], name)) { + } else if (share_path_sz == 1 && share_path[0] == '/') { + if (ab_pathname[0] != '/' || + strcmp(ab_pathname + 1, name)) + ret = -EINVAL; + } else if (len <= share_path_sz || + strncmp(ab_pathname, share_path, share_path_sz) || + ab_pathname[share_path_sz] != '/' || + strcmp(&ab_pathname[share_path_sz + 1], name)) { ret = -EINVAL; } if (ret) diff --git a/fs/splice.c b/fs/splice.c index 0c38b36df399..aa2086da9594 100644 --- a/fs/splice.c +++ b/fs/splice.c @@ -739,9 +739,12 @@ iter_file_splice_write(struct pipe_inode_info *pipe, struct file *out, sd.pos = kiocb.ki_pos; if (ret <= 0) break; - WARN_ONCE(ret > sd.total_len - left, - "Splice Exceeded! ret=%zd tot=%zu left=%zu\n", - ret, sd.total_len, left); + if (unlikely(ret > sd.total_len - left)) { + WARN_ONCE(1, + "Splice Exceeded! ret=%zd tot=%zu left=%zu\n", + ret, sd.total_len, left); + ret = sd.total_len - left; + } sd.num_spliced += ret; sd.total_len -= ret; @@ -865,9 +868,9 @@ ssize_t splice_to_socket(struct pipe_inode_info *pipe, struct file *out, bvec_set_page(&bvec[bc++], buf->page, seg, buf->offset); remain -= seg; + tail++; if (remain == 0 || bc >= ARRAY_SIZE(bvec)) break; - tail++; } if (!bc) diff --git a/fs/stat.c b/fs/stat.c index 3bc049f0bc3d..484b61ccc115 100644 --- a/fs/stat.c +++ b/fs/stat.c @@ -718,8 +718,7 @@ cp_statx(const struct kstat *stat, struct statx __user *buffer) /* STATX_CHANGE_COOKIE is kernel-only for now */ tmp.stx_mask = stat->result_mask & ~STATX_CHANGE_COOKIE; tmp.stx_blksize = stat->blksize; - /* STATX_ATTR_CHANGE_MONOTONIC is kernel-only for now */ - tmp.stx_attributes = stat->attributes & ~STATX_ATTR_CHANGE_MONOTONIC; + tmp.stx_attributes = stat->attributes & ~STATX_ATTR_INTERNAL_MASK; tmp.stx_nlink = stat->nlink; tmp.stx_uid = from_kuid_munged(current_user_ns(), stat->uid); tmp.stx_gid = from_kgid_munged(current_user_ns(), stat->gid); @@ -727,7 +726,8 @@ cp_statx(const struct kstat *stat, struct statx __user *buffer) tmp.stx_ino = stat->ino; tmp.stx_size = stat->size; tmp.stx_blocks = stat->blocks; - tmp.stx_attributes_mask = stat->attributes_mask; + tmp.stx_attributes_mask = stat->attributes_mask & + ~STATX_ATTR_INTERNAL_MASK; tmp.stx_atime.tv_sec = stat->atime.tv_sec; tmp.stx_atime.tv_nsec = stat->atime.tv_nsec; tmp.stx_btime.tv_sec = stat->btime.tv_sec; diff --git a/fs/udf/super.c b/fs/udf/super.c index 8d3d758714da..09905f6c9ee1 100644 --- a/fs/udf/super.c +++ b/fs/udf/super.c @@ -1319,10 +1319,21 @@ static int udf_load_vat(struct super_block *sb, int p_index, int type1_index) if (map->s_partition_type == UDF_VIRTUAL_MAP15) { map->s_type_specific.s_virtual.s_start_offset = 0; + if (sbi->s_vat_inode->i_size < 36) { + udf_err(sb, "Too short VAT inode size %lld\n", + sbi->s_vat_inode->i_size); + return -EFSCORRUPTED; + } map->s_type_specific.s_virtual.s_num_entries = (sbi->s_vat_inode->i_size - 36) >> 2; } else if (map->s_partition_type == UDF_VIRTUAL_MAP20) { vati = UDF_I(sbi->s_vat_inode); + if (sbi->s_vat_inode->i_size < + sizeof(struct virtualAllocationTable20)) { + udf_err(sb, "Too short VAT inode size %lld\n", + sbi->s_vat_inode->i_size); + return -EFSCORRUPTED; + } if (vati->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) { int err = 0; @@ -1340,8 +1351,12 @@ static int udf_load_vat(struct super_block *sb, int p_index, int type1_index) map->s_type_specific.s_virtual.s_start_offset = le16_to_cpu(vat20->lengthHeader); - if (map->s_type_specific.s_virtual.s_start_offset - > sbi->s_vat_inode->i_size) { + if (map->s_type_specific.s_virtual.s_start_offset < + sizeof(struct virtualAllocationTable20) || + map->s_type_specific.s_virtual.s_start_offset > + sb->s_blocksize || + map->s_type_specific.s_virtual.s_start_offset > + sbi->s_vat_inode->i_size) { udf_err(sb, "Corrupted VAT header length %u (VAT inode size %lld)\n", map->s_type_specific.s_virtual.s_start_offset, sbi->s_vat_inode->i_size); diff --git a/fs/userfaultfd.c b/fs/userfaultfd.c index 02ff11cf42bd..1b33c92bae9e 100644 --- a/fs/userfaultfd.c +++ b/fs/userfaultfd.c @@ -1505,6 +1505,8 @@ static int userfaultfd_unregister(struct userfaultfd_ctx *ctx, ret = 0; for_each_vma_range(vmi, vma, end) { + struct userfaultfd_wake_range range; + cond_resched(); /* VMA not registered with userfaultfd. */ @@ -1522,18 +1524,14 @@ static int userfaultfd_unregister(struct userfaultfd_ctx *ctx, /* Prevent new userfaults from being queued after the wakeup. */ vma_start_write(vma); - if (userfaultfd_missing(vma)) { - /* - * Wake any concurrent pending userfault while - * we unregister, so they will not hang - * permanently and it avoids userland to call - * UFFDIO_WAKE explicitly. - */ - struct userfaultfd_wake_range range; - range.start = start; - range.len = vma_end - start; - wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range); - } + /* + * Wake any concurrent pending userfault while we unregister, + * so they will not hang permanently and it avoids userland to + * call UFFDIO_WAKE explicitly. + */ + range.start = start; + range.len = vma_end - start; + wake_userfault(ctx, &range); vma = userfaultfd_clear_vma(&vmi, prev, vma, start, vma_end); diff --git a/fs/xfs/xfs_inode.c b/fs/xfs/xfs_inode.c index 36b39539e561..c5afc8997fb4 100644 --- a/fs/xfs/xfs_inode.c +++ b/fs/xfs/xfs_inode.c @@ -1048,7 +1048,8 @@ xfs_itruncate_extents_flags( xfs_assert_ilocked(ip, XFS_ILOCK_EXCL); if (icount_read(VFS_I(ip))) xfs_assert_ilocked(ip, XFS_IOLOCK_EXCL); - ASSERT(new_size <= XFS_ISIZE(ip)); + if (whichfork == XFS_DATA_FORK) + ASSERT(new_size <= XFS_ISIZE(ip)); ASSERT(tp->t_flags & XFS_TRANS_PERM_LOG_RES); ASSERT(ip->i_itemp != NULL); ASSERT(ip->i_itemp->ili_lock_flags == 0); diff --git a/include/acpi/acpi_bus.h b/include/acpi/acpi_bus.h index d6b449c6ecd3..f568089194ab 100644 --- a/include/acpi/acpi_bus.h +++ b/include/acpi/acpi_bus.h @@ -363,6 +363,7 @@ struct acpi_device_physical_node { struct device *dev; unsigned int node_id; bool put_online:1; + bool offline_pending:1; }; struct acpi_device_properties { diff --git a/include/dt-bindings/sound/qcom,q6dsp-lpass-ports.h b/include/dt-bindings/sound/qcom,q6dsp-lpass-ports.h index 6d1ce7f5da51..45850f2d4342 100644 --- a/include/dt-bindings/sound/qcom,q6dsp-lpass-ports.h +++ b/include/dt-bindings/sound/qcom,q6dsp-lpass-ports.h @@ -140,6 +140,18 @@ #define DISPLAY_PORT_RX_6 134 #define DISPLAY_PORT_RX_7 135 #define USB_RX 136 +#define LPI_MI2S_RX_0 137 +#define LPI_MI2S_TX_0 138 +#define LPI_MI2S_RX_1 139 +#define LPI_MI2S_TX_1 140 +#define LPI_MI2S_RX_2 141 +#define LPI_MI2S_TX_2 142 +#define LPI_MI2S_RX_3 143 +#define LPI_MI2S_TX_3 144 +#define LPI_MI2S_RX_4 145 +#define LPI_MI2S_TX_4 146 +#define SENARY_MI2S_RX 147 +#define SENARY_MI2S_TX 148 #define LPASS_CLK_ID_PRI_MI2S_IBIT 1 #define LPASS_CLK_ID_PRI_MI2S_EBIT 2 diff --git a/include/linux/blk-mq.h b/include/linux/blk-mq.h index 451c2fc5b46c..7eec82e42758 100644 --- a/include/linux/blk-mq.h +++ b/include/linux/blk-mq.h @@ -522,7 +522,8 @@ enum hctx_type { * @tag_list: List of the request queues that use this tag set. See also * request_queue.tag_set_list. * @quiesce_lock: Serializes blk_mq_[un]quiesce_tagset() against each other - * and against a request queue being added to @tag_list. + * and against a request queue being added to or removed from + * @tag_list. * @quiesce_depth: How often blk_mq_quiesce_tagset() has been called without * blk_mq_unquiesce_tagset(). * @srcu: Use as lock when type of the request queue is blocking diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h index 0299d62886ed..620093f1e544 100644 --- a/include/linux/blkdev.h +++ b/include/linux/blkdev.h @@ -545,7 +545,8 @@ struct request_queue { /* * queue settings */ - unsigned long nr_requests; /* Max # of requests */ + unsigned int nr_requests; /* Max # of requests */ + unsigned int async_depth; /* Max # of async requests */ #ifdef CONFIG_BLK_INLINE_ENCRYPTION struct blk_crypto_profile *crypto_profile; diff --git a/include/linux/bpf.h b/include/linux/bpf.h index d840ec32d95b..2d8cb15fb9ba 100644 --- a/include/linux/bpf.h +++ b/include/linux/bpf.h @@ -1619,19 +1619,19 @@ struct bpf_prog_aux { bool offload_requested; /* Program is bound and offloaded to the netdev. */ bool attach_btf_trace; /* true if attaching to BTF-enabled raw tp */ bool attach_tracing_prog; /* true if tracing another tracing program */ + bool sleepable_async_cb; /* has a bpf_wq or bpf_task_work callback */ bool func_proto_unreliable; bool tail_call_reachable; bool xdp_has_frags; bool exception_cb; bool exception_boundary; - bool is_extended; /* true if extended by freplace program */ bool jits_use_priv_stack; bool priv_stack_requested; bool changes_pkt_data; bool might_sleep; bool kprobe_write_ctx; u64 prog_array_member_cnt; /* counts how many times as member of prog_array */ - struct mutex ext_mutex; /* mutex for is_extended and prog_array_member_cnt */ + struct mutex ext_mutex; /* mutex for freplace_link_cnt and prog_array_member_cnt */ struct bpf_arena *arena; void (*recursion_detected)(struct bpf_prog *prog); /* callback if recursion is detected */ /* BTF_KIND_FUNC_PROTO for valid attach_btf_id */ @@ -1662,6 +1662,7 @@ struct bpf_prog_aux { struct bpf_map *cgroup_storage[MAX_BPF_CGROUP_STORAGE_TYPE]; char name[BPF_OBJ_NAME_LEN]; u64 (*bpf_exception_cb)(u64 cookie, u64 sp, u64 bp, u64, u64); + u16 freplace_link_cnt; /* counts freplace links extending this prog */ #ifdef CONFIG_SECURITY void *security; #endif @@ -1741,6 +1742,15 @@ struct bpf_prog { }; }; +/* + * Does the program, or a callback of it, run under RCU Tasks Trace protection + * only, outside of any RCU read side critical section? + */ +static inline bool bpf_prog_runs_sleepable(const struct bpf_prog *prog) +{ + return prog->sleepable || prog->aux->sleepable_async_cb; +} + struct bpf_array_aux { /* Programs with direct jumps into programs part of this array. */ struct list_head poke_progs; @@ -2546,6 +2556,8 @@ static inline void bpf_map_dec_elem_count(struct bpf_map *map) this_cpu_dec(*map->elem_count); } +s64 bpf_map_sum_elem_count(const struct bpf_map *map); + extern int sysctl_unprivileged_bpf_disabled; bool bpf_token_capable(const struct bpf_token *token, int cap); diff --git a/include/linux/can/dev.h b/include/linux/can/dev.h index a2229a61ccde..dbf9684c1a9d 100644 --- a/include/linux/can/dev.h +++ b/include/linux/can/dev.h @@ -103,7 +103,7 @@ static inline bool can_dev_dropped_skb(struct net_device *dev, struct sk_buff *s if (priv->ctrlmode & CAN_CTRLMODE_LISTENONLY) { netdev_info_once(dev, "interface in listen only mode, dropping skb\n"); - kfree_skb(skb); + dev_kfree_skb_any(skb); dev->stats.tx_dropped++; return true; } diff --git a/include/linux/can/skb.h b/include/linux/can/skb.h index 27d0ca115c6c..1f0c3e8cde90 100644 --- a/include/linux/can/skb.h +++ b/include/linux/can/skb.h @@ -92,12 +92,12 @@ static inline struct sk_buff *can_create_echo_skb(struct sk_buff *skb) nskb = skb_clone(skb, GFP_ATOMIC); if (unlikely(!nskb)) { - kfree_skb(skb); + dev_kfree_skb_any(skb); return NULL; } can_skb_set_owner(nskb, skb->sk); - consume_skb(skb); + dev_consume_skb_any(skb); return nskb; } diff --git a/include/linux/ceph/ceph_fs.h b/include/linux/ceph/ceph_fs.h index 08e5dbe15ca4..69ac3e55a3fe 100644 --- a/include/linux/ceph/ceph_fs.h +++ b/include/linux/ceph/ceph_fs.h @@ -89,8 +89,9 @@ struct ceph_dir_layout { } __attribute__ ((packed)); /* crypto algorithms */ -#define CEPH_CRYPTO_NONE 0x0 -#define CEPH_CRYPTO_AES 0x1 +#define CEPH_CRYPTO_NONE 0x0 +#define CEPH_CRYPTO_AES 0x1 +#define CEPH_CRYPTO_AES256KRB5 0x2 /* AES256-CTS-HMAC384-192 */ #define CEPH_AES_IV "cephsageyudagreg" diff --git a/include/linux/compiler.h b/include/linux/compiler.h index 5b45ea7dff3e..2911b9e62292 100644 --- a/include/linux/compiler.h +++ b/include/linux/compiler.h @@ -248,10 +248,13 @@ void ftrace_likely_update(struct ftrace_likely_data *f, int val, #endif /* __KERNEL__ */ -#if defined(CONFIG_CFI) && !defined(__DISABLE_EXPORTS) && !defined(BUILD_VDSO) +#if defined(CONFIG_CFI) && !defined(__DISABLE_EXPORTS) && !defined(BUILD_VDSO) && \ + !defined(MODULE) /* * Force a reference to the external symbol so the compiler generates - * __kcfi_typid. + * __kcfi_typid. Only vmlinux needs it, as that is where the assembly + * using the typeid lives; in a module it would only add a reference to + * the symbol, which fails modpost if the symbol is GPL-only. */ #define KCFI_REFERENCE(sym) __ADDRESSABLE(sym) #else diff --git a/include/linux/cpufreq.h b/include/linux/cpufreq.h index fd26b3a4aa28..69034172a755 100644 --- a/include/linux/cpufreq.h +++ b/include/linux/cpufreq.h @@ -145,6 +145,9 @@ struct cpufreq_policy { /* Per policy boost supported flag. */ bool boost_supported; + /* The policy has been suspended. */ + bool suspended; + /* Cached frequency lookup from cpufreq_driver_resolve_freq. */ unsigned int cached_target_freq; unsigned int cached_resolved_idx; diff --git a/include/linux/ethtool.h b/include/linux/ethtool.h index 5c9162193d26..8c850fb53530 100644 --- a/include/linux/ethtool.h +++ b/include/linux/ethtool.h @@ -285,6 +285,8 @@ struct ethtool_link_ksettings { extern int __ethtool_get_link_ksettings(struct net_device *dev, struct ethtool_link_ksettings *link_ksettings); +int netif_get_link_ksettings(struct net_device *dev, + struct ethtool_link_ksettings *link_ksettings); struct ethtool_keee { __ETHTOOL_DECLARE_LINK_MODE_MASK(supported); diff --git a/include/linux/fs.h b/include/linux/fs.h index 09cbcfbf295f..e5e36d0bc9c4 100644 --- a/include/linux/fs.h +++ b/include/linux/fs.h @@ -1660,6 +1660,14 @@ struct super_block { spinlock_t s_inode_wblist_lock; struct list_head s_inodes_wb; /* writeback inodes */ + +#ifdef CONFIG_CGROUP_WRITEBACK + /* + * Number of in-flight inode wb switches for this sb. Drained by + * cgroup_writeback_umount() before tear-down. + */ + atomic_t s_isw_nr_in_flight; +#endif } __randomize_layout; static inline struct user_namespace *i_user_ns(const struct inode *inode) @@ -3773,7 +3781,7 @@ struct offset_ctx { unsigned long next_offset; }; -void simple_offset_init(struct offset_ctx *octx); +void simple_offset_init(struct offset_ctx *octx, struct inode *dir); int simple_offset_add(struct offset_ctx *octx, struct dentry *dentry); void simple_offset_remove(struct offset_ctx *octx, struct dentry *dentry); void simple_offset_rename(struct inode *old_dir, struct dentry *old_dentry, diff --git a/include/linux/fs_parser.h b/include/linux/fs_parser.h index 5a0e897cae80..5e8a3b546033 100644 --- a/include/linux/fs_parser.h +++ b/include/linux/fs_parser.h @@ -120,6 +120,8 @@ static inline bool fs_validate_description(const char *name, #define fsparam_u32(NAME, OPT) __fsparam(fs_param_is_u32, NAME, OPT, 0, NULL) #define fsparam_u32oct(NAME, OPT) \ __fsparam(fs_param_is_u32, NAME, OPT, 0, (void *)8) +#define fsparam_u32hex(NAME, OPT) \ + __fsparam(fs_param_is_u32, NAME, OPT, 0, (void *)16) #define fsparam_s32(NAME, OPT) __fsparam(fs_param_is_s32, NAME, OPT, 0, NULL) #define fsparam_u64(NAME, OPT) __fsparam(fs_param_is_u64, NAME, OPT, 0, NULL) #define fsparam_enum(NAME, OPT, array) __fsparam(fs_param_is_enum, NAME, OPT, 0, array) diff --git a/include/linux/fsnotify.h b/include/linux/fsnotify.h index 28a9cb13fbfa..c4461411dc55 100644 --- a/include/linux/fsnotify.h +++ b/include/linux/fsnotify.h @@ -135,7 +135,7 @@ int fsnotify_open_perm_and_set_mode(struct file *file); * fsnotify_file_area_perm - permission hook before access to file range */ static inline int fsnotify_file_area_perm(struct file *file, int perm_mask, - const loff_t *ppos, size_t count) + const loff_t *ppos, u64 count) { /* * filesystem may be modified in the context of permission events @@ -213,7 +213,7 @@ static inline int fsnotify_open_perm_and_set_mode(struct file *file) } static inline int fsnotify_file_area_perm(struct file *file, int perm_mask, - const loff_t *ppos, size_t count) + const loff_t *ppos, u64 count) { return 0; } diff --git a/include/linux/fsnotify_backend.h b/include/linux/fsnotify_backend.h index d67a893d75fa..042f0e7f159d 100644 --- a/include/linux/fsnotify_backend.h +++ b/include/linux/fsnotify_backend.h @@ -322,7 +322,7 @@ struct fs_error_report { struct file_range { const struct path *path; loff_t pos; - size_t count; + u64 count; }; static inline const struct path *file_range_path(const struct file_range *range) @@ -922,12 +922,12 @@ static inline void fsnotify_init_event(struct fsnotify_event *event) INIT_LIST_HEAD(&event->list); } int fsnotify_pre_content(const struct path *path, const loff_t *ppos, - size_t count); + u64 count); #else static inline int fsnotify_pre_content(const struct path *path, - const loff_t *ppos, size_t count) + const loff_t *ppos, u64 count) { return 0; } diff --git a/include/linux/gpio/regmap.h b/include/linux/gpio/regmap.h index 87983a5f3681..a23e1c2b933a 100644 --- a/include/linux/gpio/regmap.h +++ b/include/linux/gpio/regmap.h @@ -38,6 +38,12 @@ struct regmap; * offset to a register/bitmask pair. If not * given the default gpio_regmap_simple_xlate() * is used. + * @fixed_direction_mask: + * (Optional) Bitmap representing the GPIO lines that + * make use of the @fixed_direction_output list to + * enforce direction of the GPIO. If this is NULL + * and @fixed_direction_output is defined, ALL GPIOs + * are assumed to be fixed direction (out or in). * @fixed_direction_output: * (Optional) Bitmap representing the fixed direction of * the GPIO lines. Useful when there are GPIO lines with a @@ -89,6 +95,7 @@ struct gpio_regmap_config { int reg_stride; int ngpio_per_reg; struct irq_domain *irq_domain; + unsigned long *fixed_direction_mask; unsigned long *fixed_direction_output; #ifdef CONFIG_REGMAP_IRQ diff --git a/include/linux/key.h b/include/linux/key.h index e40b5267658f..77efb30bb73c 100644 --- a/include/linux/key.h +++ b/include/linux/key.h @@ -37,6 +37,9 @@ struct net; #undef KEY_DEBUGGING +/* Maximum length of a key description, including the trailing NUL */ +#define KEY_MAX_DESC_SIZE 4096 + #define KEY_POS_VIEW 0x01000000 /* possessor can view a key's attributes */ #define KEY_POS_READ 0x02000000 /* possessor can read key payload / view keyring */ #define KEY_POS_WRITE 0x04000000 /* possessor can update key payload / add link to keyring */ diff --git a/include/linux/mlx5/driver.h b/include/linux/mlx5/driver.h index 647dcf144ae9..14b5fea30da3 100644 --- a/include/linux/mlx5/driver.h +++ b/include/linux/mlx5/driver.h @@ -780,8 +780,12 @@ struct mlx5_core_dev { u32 vsc_addr; struct mlx5_hv_vhca *hv_vhca; struct mlx5_hwmon *hwmon; - u64 num_block_tc; - u64 num_block_ipsec; + struct { + /* Protects the fields below. */ + spinlock_t lock; + u64 num_block_tc; + u64 num_block_ipsec; + } offload_block; #ifdef CONFIG_MLX5_MACSEC struct mlx5_macsec_fs *macsec_fs; /* MACsec notifier chain to sync MACsec core and IB database */ diff --git a/include/linux/mmzone.h b/include/linux/mmzone.h index 7fb7331c5725..d547641fa7c8 100644 --- a/include/linux/mmzone.h +++ b/include/linux/mmzone.h @@ -1710,7 +1710,8 @@ extern struct zone *next_zone(struct zone *zone); static inline struct zone *zonelist_zone(struct zoneref *zoneref) { - return zoneref->zone; + /* Memory hotplug rewrites zonelists in place. */ + return READ_ONCE(zoneref->zone); } static inline int zonelist_zone_idx(const struct zoneref *zoneref) diff --git a/include/linux/netdevice.h b/include/linux/netdevice.h index f08d17f1d2e0..d367760b902f 100644 --- a/include/linux/netdevice.h +++ b/include/linux/netdevice.h @@ -2497,6 +2497,11 @@ struct net_device { /* protected by rtnl_lock */ struct bpf_xdp_entity xdp_state[__MAX_XDP_MODE]; +#ifdef CONFIG_XDP_SOCKETS + /** @xsk_pools: assigned AF_XDP pools, ops protected */ + struct hlist_head xsk_pools; +#endif + u8 dev_addr_shadow[MAX_ADDR_LEN]; netdevice_tracker linkwatch_dev_tracker; netdevice_tracker watchdog_dev_tracker; diff --git a/include/linux/netdevice_xmit.h b/include/linux/netdevice_xmit.h index 813a19122ebb..b4ce469cee74 100644 --- a/include/linux/netdevice_xmit.h +++ b/include/linux/netdevice_xmit.h @@ -11,8 +11,8 @@ struct netdev_xmit { #if IS_ENABLED(CONFIG_NET_ACT_MIRRED) u8 sched_mirred_nest; #endif -#if IS_ENABLED(CONFIG_NF_DUP_NETDEV) - u8 nf_dup_skb_recursion; +#if IS_ENABLED(CONFIG_NETFILTER) + u8 nf_xmit_skb_recursion; #endif }; diff --git a/include/linux/nvme-auth.h b/include/linux/nvme-auth.h index 60e069a6757f..ef6d0b79e6a0 100644 --- a/include/linux/nvme-auth.h +++ b/include/linux/nvme-auth.h @@ -7,6 +7,7 @@ #define _NVME_AUTH_H #include +#include struct nvme_dhchap_key { size_t len; @@ -23,29 +24,42 @@ const char *nvme_auth_hmac_name(u8 hmac_id); const char *nvme_auth_digest_name(u8 hmac_id); size_t nvme_auth_hmac_hash_len(u8 hmac_id); u8 nvme_auth_hmac_id(const char *hmac_name); +struct nvme_auth_hmac_ctx { + u8 hmac_id; + union { + struct hmac_sha256_ctx sha256; + struct hmac_sha384_ctx sha384; + struct hmac_sha512_ctx sha512; + }; +}; +int nvme_auth_hmac_init(struct nvme_auth_hmac_ctx *hmac, u8 hmac_id, + const u8 *key, size_t key_len); +void nvme_auth_hmac_update(struct nvme_auth_hmac_ctx *hmac, const u8 *data, + size_t data_len); +void nvme_auth_hmac_final(struct nvme_auth_hmac_ctx *hmac, u8 *out); u32 nvme_auth_key_struct_size(u32 key_len); -struct nvme_dhchap_key *nvme_auth_extract_key(unsigned char *secret, - u8 key_hash); +struct nvme_dhchap_key *nvme_auth_extract_key(const char *secret, u8 key_hash); void nvme_auth_free_key(struct nvme_dhchap_key *key); struct nvme_dhchap_key *nvme_auth_alloc_key(u32 len, u8 hash); struct nvme_dhchap_key *nvme_auth_transform_key( - struct nvme_dhchap_key *key, char *nqn); -int nvme_auth_generate_key(u8 *secret, struct nvme_dhchap_key **ret_key); -int nvme_auth_augmented_challenge(u8 hmac_id, u8 *skey, size_t skey_len, - u8 *challenge, u8 *aug, size_t hlen); + const struct nvme_dhchap_key *key, const char *nqn); +int nvme_auth_generate_key(const char *secret, struct nvme_dhchap_key **ret_key); +int nvme_auth_augmented_challenge(u8 hmac_id, const u8 *skey, size_t skey_len, + const u8 *challenge, u8 *aug, size_t hlen); int nvme_auth_gen_privkey(struct crypto_kpp *dh_tfm, u8 dh_gid); int nvme_auth_gen_pubkey(struct crypto_kpp *dh_tfm, u8 *host_key, size_t host_key_len); -int nvme_auth_gen_shared_secret(struct crypto_kpp *dh_tfm, - u8 *ctrl_key, size_t ctrl_key_len, - u8 *sess_key, size_t sess_key_len); -int nvme_auth_generate_psk(u8 hmac_id, u8 *skey, size_t skey_len, - u8 *c1, u8 *c2, size_t hash_len, +int nvme_auth_gen_session_key(struct crypto_kpp *dh_tfm, + const u8 *public_key, size_t public_key_len, + u8 *sess_key, size_t sess_key_len, u8 hash_id); +int nvme_auth_generate_psk(u8 hmac_id, const u8 *skey, size_t skey_len, + const u8 *c1, const u8 *c2, size_t hash_len, u8 **ret_psk, size_t *ret_len); -int nvme_auth_generate_digest(u8 hmac_id, u8 *psk, size_t psk_len, - char *subsysnqn, char *hostnqn, u8 **ret_digest); -int nvme_auth_derive_tls_psk(int hmac_id, u8 *psk, size_t psk_len, - u8 *psk_digest, u8 **ret_psk); +int nvme_auth_generate_digest(u8 hmac_id, const u8 *psk, size_t psk_len, + const char *subsysnqn, const char *hostnqn, + char **ret_digest); +int nvme_auth_derive_tls_psk(int hmac_id, const u8 *psk, size_t psk_len, + const char *psk_digest, u8 **ret_psk); #endif /* _NVME_AUTH_H */ diff --git a/include/linux/nvme.h b/include/linux/nvme.h index 2a5d2d941d84..8aa83abc7863 100644 --- a/include/linux/nvme.h +++ b/include/linux/nvme.h @@ -1837,6 +1837,11 @@ enum { NVME_AUTH_HASH_INVALID = 0xff, }; +/* Maximum digest size for any NVME_AUTH_HASH_* value */ +enum { + NVME_AUTH_MAX_DIGEST_SIZE = 64, +}; + /* Defined Diffie-Hellman group identifiers for DH-HMAC-CHAP authentication */ enum { NVME_AUTH_DHGROUP_NULL = 0x00, diff --git a/include/linux/perf_event.h b/include/linux/perf_event.h index c8acdb026c62..23444b1b2503 100644 --- a/include/linux/perf_event.h +++ b/include/linux/perf_event.h @@ -305,6 +305,8 @@ struct perf_event_pmu_context; #define PERF_PMU_CAP_EXTENDED_HW_TYPE 0x0100 #define PERF_PMU_CAP_AUX_PAUSE 0x0200 #define PERF_PMU_CAP_AUX_PREFER_LARGE 0x0400 +#define PERF_PMU_CAP_MEDIATED_VPMU 0x0800 +#define PERF_PMU_CAP_SIMD_REGS 0x1000 /** * pmu::scope @@ -1527,6 +1529,27 @@ perf_event__output_id_sample(struct perf_event *event, extern void perf_log_lost_samples(struct perf_event *event, u64 lost); +static inline bool event_has_simd_regs(struct perf_event *event) +{ + struct perf_event_attr *attr = &event->attr; + + if (!(event->attr.sample_type & + (PERF_SAMPLE_REGS_INTR | PERF_SAMPLE_REGS_USER))) + return false; + + return attr->sample_simd_regs_enabled != 0; +} + +static inline bool event_has_extended_regs(struct perf_event *event) +{ + struct perf_event_attr *attr = &event->attr; + + return ((attr->sample_type & PERF_SAMPLE_REGS_USER) && + (attr->sample_regs_user & PERF_REG_EXTENDED_MASK)) || + ((attr->sample_type & PERF_SAMPLE_REGS_INTR) && + (attr->sample_regs_intr & PERF_REG_EXTENDED_MASK)); +} + static inline bool event_has_any_exclude_flag(struct perf_event *event) { struct perf_event_attr *attr = &event->attr; @@ -1806,6 +1829,12 @@ extern unsigned long perf_misc_flags(struct perf_event *event, struct pt_regs *r extern unsigned long perf_instruction_pointer(struct perf_event *event, struct pt_regs *regs); +extern void perf_sample_regs_user(struct perf_regs *regs_user, + struct pt_regs *regs); +extern void perf_sample_regs_intr(struct perf_regs *regs_intr, + struct pt_regs *regs, + bool exclude_kernel); + #ifndef perf_arch_misc_flags # define perf_arch_misc_flags(regs) \ (user_mode(regs) ? PERF_RECORD_MISC_USER : PERF_RECORD_MISC_KERNEL) @@ -1915,6 +1944,11 @@ extern int perf_event_account_interrupt(struct perf_event *event); extern int perf_event_period(struct perf_event *event, u64 value); extern u64 perf_event_pause(struct perf_event *event, bool reset); +#ifdef CONFIG_PERF_GUEST_MEDIATED_PMU +int perf_create_mediated_pmu(void); +void perf_release_mediated_pmu(void); +#endif + #else /* !CONFIG_PERF_EVENTS: */ static inline void * diff --git a/include/linux/perf_regs.h b/include/linux/perf_regs.h index f632c5725f16..518f28c6a7d4 100644 --- a/include/linux/perf_regs.h +++ b/include/linux/perf_regs.h @@ -9,6 +9,16 @@ struct perf_regs { struct pt_regs *regs; }; +u64 perf_reg_value(struct pt_regs *regs, int idx); +int perf_reg_validate(u64 mask); +u64 perf_reg_abi(struct task_struct *task); +void perf_get_regs_user(struct perf_regs *regs_user, + struct pt_regs *regs); +int perf_simd_reg_validate(u16 vec_qwords, u64 vec_mask, + u16 pred_qwords, u32 pred_mask); +u64 perf_simd_reg_value(struct pt_regs *regs, int idx, + u16 qwords_idx, bool pred); + #ifdef CONFIG_HAVE_PERF_REGS #include @@ -16,35 +26,9 @@ struct perf_regs { #define PERF_REG_EXTENDED_MASK 0 #endif -u64 perf_reg_value(struct pt_regs *regs, int idx); -int perf_reg_validate(u64 mask); -u64 perf_reg_abi(struct task_struct *task); -void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs); #else #define PERF_REG_EXTENDED_MASK 0 -static inline u64 perf_reg_value(struct pt_regs *regs, int idx) -{ - return 0; -} - -static inline int perf_reg_validate(u64 mask) -{ - return mask ? -ENOSYS : 0; -} - -static inline u64 perf_reg_abi(struct task_struct *task) -{ - return PERF_SAMPLE_REGS_ABI_NONE; -} - -static inline void perf_get_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) -{ - regs_user->regs = task_pt_regs(current); - regs_user->abi = perf_reg_abi(current); -} #endif /* CONFIG_HAVE_PERF_REGS */ #endif /* _LINUX_PERF_REGS_H */ diff --git a/include/linux/ptp_clock_kernel.h b/include/linux/ptp_clock_kernel.h index 884364596dd3..d199ac4ec1c8 100644 --- a/include/linux/ptp_clock_kernel.h +++ b/include/linux/ptp_clock_kernel.h @@ -495,7 +495,7 @@ int ptp_get_vclocks_index(int pclock_index, int **vclock_index); * @hwtstamp: timestamp * @vclock_index: phc index of ptp vclock. * - * Returns: converted timestamp, or 0 on error. + * Returns: converted timestamp, or 0 if @hwtstamp is zero or on error. */ ktime_t ptp_convert_timestamp(const ktime_t *hwtstamp, int vclock_index); #else diff --git a/include/linux/sched.h b/include/linux/sched.h index 51b80e816fec..d3e1262da435 100644 --- a/include/linux/sched.h +++ b/include/linux/sched.h @@ -681,20 +681,22 @@ struct sched_dl_entity { * * @dl_server tells if this is a server entity. * - * @dl_defer tells if this is a deferred or regular server. For - * now only defer server exists. - * - * @dl_defer_armed tells if the deferrable server is waiting - * for the replenishment timer to activate it. - * * @dl_server_active tells if the dlserver is active(started). * dlserver is started on first cfs enqueue on an idle runqueue * and is stopped when a dequeue results in 0 cfs tasks on the * runqueue. In other words, dlserver is active only when cpu's * runqueue has atleast one cfs task. * + * @dl_defer tells if this is a deferred or regular server. For + * now only defer server exists. + * + * @dl_defer_armed tells if the deferrable server is waiting + * for the replenishment timer to activate it. + * * @dl_defer_running tells if the deferrable server is actually * running, skipping the defer phase. + * + * @dl_defer_idle tracks idle state */ unsigned int dl_throttled : 1; unsigned int dl_yielded : 1; @@ -705,6 +707,7 @@ struct sched_dl_entity { unsigned int dl_defer : 1; unsigned int dl_defer_armed : 1; unsigned int dl_defer_running : 1; + unsigned int dl_defer_idle : 1; /* * Bandwidth enforcement timer. Each -deadline task has its @@ -1912,7 +1915,6 @@ static inline int task_nice(const struct task_struct *p) extern int can_nice(const struct task_struct *p, const int nice); extern int task_curr(const struct task_struct *p); extern int idle_cpu(int cpu); -extern int available_idle_cpu(int cpu); extern int sched_setscheduler(struct task_struct *, int, const struct sched_param *); extern int sched_setscheduler_nocheck(struct task_struct *, int, const struct sched_param *); extern void sched_set_fifo(struct task_struct *p); diff --git a/include/linux/stat.h b/include/linux/stat.h index e3d00e7bb26d..3f4364808b7f 100644 --- a/include/linux/stat.h +++ b/include/linux/stat.h @@ -69,4 +69,7 @@ struct kstat { /* file attribute values */ #define STATX_ATTR_CHANGE_MONOTONIC 0x8000000000000000ULL /* version monotonically increases */ +/* mask of STATX_ATTR_* bits that is private to the kernel */ +#define STATX_ATTR_INTERNAL_MASK (STATX_ATTR_CHANGE_MONOTONIC) + #endif diff --git a/include/linux/tcp.h b/include/linux/tcp.h index 8e1266cf8ef6..7cc2ddcd9bc0 100644 --- a/include/linux/tcp.h +++ b/include/linux/tcp.h @@ -179,6 +179,9 @@ struct tcp_request_sock { u8 ao_rcv_next; bool used_tcp_ao; #endif +#if IS_ENABLED(CONFIG_IPV6) + __be32 syn_flowlabel; +#endif }; static inline struct tcp_request_sock *tcp_rsk(const struct request_sock *req) @@ -256,15 +259,20 @@ struct tcp_sock { /* TX read-write hotpath cache lines */ __cacheline_group_begin(tcp_sock_write_tx) ____cacheline_aligned; - u32 segs_out; /* RFC4898 tcpEStatsPerfSegsOut - * The total number of segments sent. - */ - u32 data_segs_out; /* RFC4898 tcpEStatsPerfDataSegsOut - * total number of data segments sent. + u32 delivered; /* Total data packets delivered incl. rexmits */ + u32 delivered_ce; /* Like the above but only ECE marked packets */ + u64 bytes_acked; /* RFC4898 tcpEStatsAppHCThruOctetsAcked + * sum(delta(snd_una)), or how many bytes + * were acked. */ u64 bytes_sent; /* RFC4898 tcpEStatsPerfHCDataOctetsOut * total number of data bytes sent. */ + u64 first_tx_mstamp; /* start of window send phase */ + u64 delivered_mstamp; /* time we reached "delivered" */ + u32 data_segs_out; /* RFC4898 tcpEStatsPerfDataSegsOut + * total number of data segments sent. + */ u32 snd_sml; /* Last byte of the most recently transmitted small packet */ u8 chrono_type; /* current chronograph type */ u32 chrono_start; /* Start time in jiffies of a TCP chrono */ @@ -309,8 +317,6 @@ struct tcp_sock { u32 srtt_us; /* smoothed round trip time << 3 in usecs */ u32 packets_out; /* Packets which are "in flight" */ u32 snd_up; /* Urgent pointer */ - u32 delivered; /* Total data packets delivered incl. rexmits */ - u32 delivered_ce; /* Like the above but only ECE marked packets */ u32 received_ce; /* Like the above but for rcvd CE marked pkts */ u32 received_ecn_bytes[3]; /* received byte counters for three ECN * types: INET_ECN_ECT_1, INET_ECN_ECT_0, @@ -323,6 +329,12 @@ struct tcp_sock { * Options received (usually on last packet, some only on SYN packets). */ struct tcp_options_received rx_opt; + u32 segs_in; /* RFC4898 tcpEStatsPerfSegsIn + * total number of segments in. + */ + u32 segs_out; /* RFC4898 tcpEStatsPerfSegsOut + * The total number of segments sent. + */ __cacheline_group_end(tcp_sock_write_txrx); /* RX read-write hotpath cache lines */ @@ -332,9 +344,6 @@ struct tcp_sock { * sum(delta(rcv_nxt)), or how many bytes * were acked. */ - u32 segs_in; /* RFC4898 tcpEStatsPerfSegsIn - * total number of segments in. - */ u32 data_segs_in; /* RFC4898 tcpEStatsPerfDataSegsIn * total number of data segments in. */ @@ -345,12 +354,8 @@ struct tcp_sock { u32 rate_interval_us; /* saved rate sample: time elapsed */ u32 rcv_rtt_last_tsecr; u32 delivered_ecn_bytes[3]; - u64 first_tx_mstamp; /* start of window send phase */ - u64 delivered_mstamp; /* time we reached "delivered" */ - u64 bytes_acked; /* RFC4898 tcpEStatsAppHCThruOctetsAcked - * sum(delta(snd_una)), or how many bytes - * were acked. - */ + u16 pkts_acked_ewma;/* Pkts acked EWMA for AccECN cep heuristic */ + u32 rcv_collapse_credit; /* memory queued since last collapse */ struct { u32 rtt_us; u32 seq; diff --git a/include/linux/uio.h b/include/linux/uio.h index 5b127043a151..5678520f0bfb 100644 --- a/include/linux/uio.h +++ b/include/linux/uio.h @@ -362,11 +362,11 @@ struct iovec *iovec_from_user(const struct iovec __user *uvector, unsigned long nr_segs, unsigned long fast_segs, struct iovec *fast_iov, bool compat); ssize_t import_iovec(int type, const struct iovec __user *uvec, - unsigned nr_segs, unsigned fast_segs, struct iovec **iovp, - struct iov_iter *i); + unsigned long nr_segs, unsigned int fast_segs, + struct iovec **iovp, struct iov_iter *i); ssize_t __import_iovec(int type, const struct iovec __user *uvec, - unsigned nr_segs, unsigned fast_segs, struct iovec **iovp, - struct iov_iter *i, bool compat); + unsigned long nr_segs, unsigned int fast_segs, + struct iovec **iovp, struct iov_iter *i, bool compat); int import_ubuf(int type, void __user *buf, size_t len, struct iov_iter *i); static inline void iov_iter_ubuf(struct iov_iter *i, unsigned int direction, diff --git a/include/linux/virtio_net.h b/include/linux/virtio_net.h index c381b916c1b5..fc9667176f23 100644 --- a/include/linux/virtio_net.h +++ b/include/linux/virtio_net.h @@ -5,7 +5,10 @@ #include #include #include +#include #include +#include +#include #include #include #include @@ -48,6 +51,145 @@ static inline int virtio_net_hdr_set_proto(struct sk_buff *skb, return 0; } +/* TODO: nothing virtio specific here, move to ip.h */ + +/* + * Pull and minimally validate the IPv4 header at @nhoff. + * Returns the header and stores the transport header offset in + * @thoff, or NULL if truncated or malformed. The whole header, + * options included, is guaranteed linear on return. + */ +static inline struct iphdr *virtio_net_ip4_parse(struct sk_buff *skb, + unsigned int nhoff, + unsigned int *thoff) +{ + unsigned int ihl; + struct iphdr *iph; + + if (!pskb_may_pull(skb, nhoff + sizeof(struct iphdr))) + return NULL; + + iph = (struct iphdr *)(skb->data + nhoff); + if (iph->version != 4 || + iph->ihl < sizeof(struct iphdr) / sizeof(u32)) + return NULL; + + ihl = iph->ihl * sizeof(u32); + *thoff = nhoff + ihl; + /* Pull the options as well: the transport header offset + * returned above must be within the linear data. iph goes + * stale across the pull. + */ + if (!pskb_may_pull(skb, nhoff + ihl)) + return NULL; + + return (struct iphdr *)(skb->data + nhoff); +} + +/* Where does the L3 header start, and what protocol is it? + * With @has_eth, the frame starts with an Ethernet header, possibly + * followed by VLAN tags. Otherwise the L3 header starts at the network + * header offset the caller set up. + * + * The caller knows how the frame will be parsed later: the device + * type does not tell, as tun can change it with TUNSETLINK. + */ +static inline bool +virtio_net_l3_start(struct sk_buff *skb, bool has_eth, int *nhoff, + __be16 *proto) +{ + if (has_eth) { + __be16 h_proto; + + if (!pskb_may_pull(skb, ETH_HLEN)) + return false; + h_proto = eth_hdr(skb)->h_proto; + /* skb->protocol is a sender claim, and parts of the + * stack parse the packet per it: when it disagrees with + * the frame we do not know which view the packet will + * be parsed as, so do not validate. + */ + if (skb->protocol && skb->protocol != h_proto) + return false; + *nhoff = ETH_HLEN; + *proto = h_proto; + if (eth_type_vlan(*proto)) { + *proto = __vlan_get_protocol(skb, *proto, nhoff); + if (!*proto) + return false; + } + } else { + const struct iphdr *iph; + + *nhoff = skb_network_offset(skb); + /* An unset network header shows up as an offset + * outside of the packet. + */ + if (*nhoff < 0 || (unsigned int)*nhoff >= skb->len) + return false; + /* No L2 header to cross-check with: take the protocol + * from the IP version at the network header. + */ + if (!pskb_may_pull(skb, *nhoff + 1)) + return false; + iph = (const struct iphdr *)(skb->data + *nhoff); + if (iph->version == 4) + *proto = htons(ETH_P_IP); + else if (iph->version == 6) + *proto = htons(ETH_P_IPV6); + else + return false; + if (skb->protocol && skb->protocol != *proto) + return false; + } + return true; +} + +/* Walk the L3 header at @nhoff: where does its transport header + * start, and which protocol is it? Returns false if the header + * is truncated, malformed or fragmented. + */ +static inline bool +virtio_net_l4_start(struct sk_buff *skb, unsigned int nhoff, __be16 proto, + unsigned int *thoff, int *ip_proto) +{ + if (proto == htons(ETH_P_IP)) { + const struct iphdr *iph = virtio_net_ip4_parse(skb, nhoff, thoff); + + if (!iph || ip_is_fragment(iph)) + return false; + *ip_proto = iph->protocol; + return true; + } + + if (proto == htons(ETH_P_IPV6)) { + const struct ipv6hdr *iph; + int flags = IP6_FH_F_AUTH; + + if (!pskb_may_pull(skb, nhoff + sizeof(*iph))) + return false; + iph = (const void *)(skb->data + nhoff); + if (iph->version != 6) + return false; + *thoff = nhoff + sizeof(*iph); + *ip_proto = iph->nexthdr; + if (*ip_proto != IPPROTO_TCP && *ip_proto != IPPROTO_UDP) { + *thoff = nhoff; + /* Find the transport header behind any + * extension headers. IP6_FH_F_AUTH stops + * the walk at AH, so frames with AH are rejected. + */ + *ip_proto = ipv6_find_hdr(skb, thoff, -1, NULL, + &flags); + if (*ip_proto < 0 || flags & IP6_FH_F_FRAG) + return false; + } + return true; + } + + return false; +} + static inline int __virtio_net_hdr_to_skb(struct sk_buff *skb, const struct virtio_net_hdr *hdr, bool little_endian, u8 hdr_gso_type) @@ -111,48 +253,38 @@ static inline int __virtio_net_hdr_to_skb(struct sk_buff *skb, p_off = nh_min_len + thlen; if (!pskb_may_pull(skb, p_off)) return -EINVAL; - } else { + } else if (gso_type) { /* gso packets without NEEDS_CSUM do not set transport_offset. * probe and drop if does not match one of the above types. */ - if (gso_type && skb->network_header) { - struct flow_keys_basic keys; - - if (!skb->protocol) { - __be16 protocol = dev_parse_header_protocol(skb); - - if (!protocol) - virtio_net_hdr_set_proto(skb, hdr); - else if (!virtio_net_hdr_match_proto(protocol, - hdr_gso_type)) - return -EINVAL; - else - skb->protocol = protocol; - } + struct flow_keys_basic keys; + + if (!skb->protocol) { + skb->protocol = dev_parse_header_protocol(skb); + if (!skb->protocol) + virtio_net_hdr_set_proto(skb, hdr); + } retry: - if (!skb_flow_dissect_flow_keys_basic(NULL, skb, &keys, - NULL, 0, 0, 0, - 0)) { - /* UFO does not specify ipv4 or 6: try both */ - if (gso_type & SKB_GSO_UDP && - skb->protocol == htons(ETH_P_IP)) { - skb->protocol = htons(ETH_P_IPV6); - goto retry; - } - return -EINVAL; + if (!skb_flow_dissect_flow_keys_basic(NULL, skb, &keys, + NULL, 0, 0, 0, + 0)) { + /* UFO does not specify ipv4 or 6: try both */ + if (gso_type & SKB_GSO_UDP && + skb->protocol == htons(ETH_P_IP)) { + skb->protocol = htons(ETH_P_IPV6); + goto retry; } + return -EINVAL; + } - p_off = keys.control.thoff + thlen; - if (!pskb_may_pull(skb, p_off) || - keys.basic.ip_proto != ip_proto) - return -EINVAL; + p_off = keys.control.thoff + thlen; + if (!pskb_may_pull(skb, p_off) || + keys.basic.ip_proto != ip_proto || + !virtio_net_hdr_match_proto(keys.basic.n_proto, + hdr_gso_type)) + return -EINVAL; - skb_set_transport_header(skb, keys.control.thoff); - } else if (gso_type) { - p_off = nh_min_len + thlen; - if (!pskb_may_pull(skb, p_off)) - return -EINVAL; - } + skb_set_transport_header(skb, keys.control.thoff); } if (hdr_gso_type != VIRTIO_NET_HDR_GSO_NONE) { @@ -292,9 +424,33 @@ static inline unsigned int virtio_l3min(bool is_ipv6) return is_ipv6 ? sizeof(struct ipv6hdr) : sizeof(struct iphdr); } +/* Do the tunnel offsets match the outer headers in the frame? + * The L3 header the tunnel claims must be the one the frame + * carries, with UDP following it at @outer_th. + */ +static inline bool +virtio_net_tnl_offsets_ok(struct sk_buff *skb, bool has_eth, bool outer_isv6, + unsigned int outer_th) +{ + int nhoff; + __be16 proto; + unsigned int thoff; + int ip_proto; + + if (!virtio_net_l3_start(skb, has_eth, &nhoff, &proto)) + return false; + if (outer_isv6 != (proto == htons(ETH_P_IPV6))) + return false; + if (!virtio_net_l4_start(skb, nhoff, proto, &thoff, &ip_proto)) + return false; + + return ip_proto == IPPROTO_UDP && outer_th == thoff; +} + static inline int virtio_net_hdr_tnl_to_skb(struct sk_buff *skb, const struct virtio_net_hdr_v1_hash_tunnel *vhdr, + bool has_eth, bool tnl_hdr_negotiated, bool tnl_csum_negotiated, bool little_endian) @@ -348,6 +504,9 @@ virtio_net_hdr_tnl_to_skb(struct sk_buff *skb, if (ret) return ret; + if (!virtio_net_tnl_offsets_ok(skb, has_eth, outer_isv6, outer_th)) + return -EINVAL; + /* In case of USO, the inner protocol is still unknown and * `inner_isv6` is just a guess, additional parsing is needed. * The previous validation ensures that accessing an ipv4 inner @@ -463,7 +622,10 @@ virtio_net_hdr_tnl_from_skb(const struct sk_buff *skb, if (feature_hdrlen && hdr->hdr_len) __virtio_net_set_tnl_hdrlen(skb, hdr); - if (skb->protocol == htons(ETH_P_IPV6)) + /* skb->protocol is the VLAN protocol when the tag is in the + * packet data. + */ + if (vlan_get_protocol(skb) == htons(ETH_P_IPV6)) hdr->gso_type |= VIRTIO_NET_HDR_GSO_UDP_TUNNEL_IPV6; else hdr->gso_type |= VIRTIO_NET_HDR_GSO_UDP_TUNNEL_IPV4; @@ -471,8 +633,11 @@ virtio_net_hdr_tnl_from_skb(const struct sk_buff *skb, if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_TUNNEL_CSUM) hdr->flags |= VIRTIO_NET_HDR_F_UDP_TUNNEL_CSUM; - inner_nh = skb->inner_network_header - skb_headroom(skb); - outer_th = skb->transport_header - skb_headroom(skb); + /* Like csum_start, the offsets must account for a VLAN tag + * the caller inserts in the frame. + */ + inner_nh = skb->inner_network_header - skb_headroom(skb) + vlan_hlen; + outer_th = skb->transport_header - skb_headroom(skb) + vlan_hlen; vhdr->inner_nh_offset = cpu_to_le16(inner_nh); vhdr->outer_th_offset = cpu_to_le16(outer_th); return 0; diff --git a/include/media/rc-map.h b/include/media/rc-map.h index d95ed3e96de2..f167c37179c8 100644 --- a/include/media/rc-map.h +++ b/include/media/rc-map.h @@ -148,7 +148,6 @@ struct rc_map_table { * @scan: pointer to struct &rc_map_table * @size: Max number of entries * @len: Number of entries that are in use - * @alloc: size of \*scan, in bytes * @rc_proto: type of the remote controller protocol, as defined at * enum &rc_proto * @name: name of the key map table @@ -158,7 +157,6 @@ struct rc_map { struct rc_map_table *scan; unsigned int size; unsigned int len; - unsigned int alloc; enum rc_proto rc_proto; const char *name; spinlock_t lock; diff --git a/include/net/9p/client.h b/include/net/9p/client.h index 4f785098c67a..0a1de81c8cd8 100644 --- a/include/net/9p/client.h +++ b/include/net/9p/client.h @@ -16,6 +16,12 @@ /* Number of requests per row */ #define P9_ROW_MAXTAG 255 +/* DEFAULT MSIZE = 32 pages worth of payload + P9_HDRSZ + + * room for write (16 extra) or read (11 extra) operands. + */ + +#define DEFAULT_MSIZE ((128 * 1024) + P9_IOHDRSZ) + /** enum p9_proto_versions - 9P protocol versions * @p9_proto_legacy: 9P Legacy mode, pre-9P2000.u * @p9_proto_2000u: 9P2000.u extension @@ -126,6 +132,98 @@ struct p9_client { char name[__NEW_UTS_LEN + 1]; }; +/** + * struct p9_fd_opts - holds client options during parsing + * @msize: maximum data size negotiated by protocol + * @prot-Oversion: 9P protocol version to use + * @trans_mod: module API instantiated with this client + * + * These parsed options get transferred into client in + * apply_client_options() + */ +struct p9_client_opts { + unsigned int msize; + unsigned char proto_version; + struct p9_trans_module *trans_mod; +}; + +/** + * struct p9_fd_opts - per-transport options for fd transport + * @rfd: file descriptor for reading (trans=fd) + * @wfd: file descriptor for writing (trans=fd) + * @port: port to connect to (trans=tcp) + * @privport: port is privileged + */ +struct p9_fd_opts { + int rfd; + int wfd; + u16 port; + bool privport; +}; + +/** + * struct p9_rdma_opts - Collection of mount options for rdma transport + * @port: port of connection + * @privport: Whether a privileged port may be used + * @sq_depth: The requested depth of the SQ. This really doesn't need + * to be any deeper than the number of threads used in the client + * @rq_depth: The depth of the RQ. Should be greater than or equal to SQ depth + * @timeout: Time to wait in msecs for CM events + */ +struct p9_rdma_opts { + short port; + bool privport; + int sq_depth; + int rq_depth; + long timeout; +}; + +/** + * struct p9_session_opts - holds parsed options for v9fs_session_info + * @flags: session options of type &p9_session_flags + * @nodev: set to 1 to disable device mapping + * @debug: debug level + * @afid: authentication handle + * @cache: cache mode of type &p9_cache_bits + * @cachetag: the tag of the cache associated with this session + * @uname: string user name to mount hierarchy as + * @aname: mount specifier for remote hierarchy + * @dfltuid: default numeric userid to mount hierarchy as + * @dfltgid: default numeric groupid to mount hierarchy as + * @uid: if %V9FS_ACCESS_SINGLE, the numeric uid which mounted the hierarchy + * @session_lock_timeout: retry interval for blocking locks + * @ndentry_timeout_ms: Negative dentry lookup cache retention time in ms + * + * This strucure holds options which are parsed and will be transferred + * to the v9fs_session_info structure when mounted, and therefore largely + * duplicates struct v9fs_session_info. + */ +struct p9_session_opts { + unsigned int flags; + unsigned char nodev; + unsigned short debug; + unsigned int afid; + unsigned int cache; + unsigned int ndentry_timeout_ms; +#ifdef CONFIG_9P_FSCACHE + char *cachetag; +#endif + char *uname; + char *aname; + kuid_t dfltuid; + kgid_t dfltgid; + kuid_t uid; + long session_lock_timeout; +}; + +/* Used by mount API to store parsed mount options */ +struct v9fs_context { + struct p9_client_opts client_opts; + struct p9_fd_opts fd_opts; + struct p9_rdma_opts rdma_opts; + struct p9_session_opts session_opts; +}; + /** * struct p9_fid - file system entity handle * @clnt: back pointer to instantiating &p9_client @@ -172,7 +270,7 @@ struct p9_dirent { struct p9_qid qid; u64 d_off; unsigned char d_type; - char d_name[256]; + char *d_name; }; struct iov_iter; @@ -183,7 +281,7 @@ int p9_client_rename(struct p9_fid *fid, struct p9_fid *newdirfid, const char *name); int p9_client_renameat(struct p9_fid *olddirfid, const char *old_name, struct p9_fid *newdirfid, const char *new_name); -struct p9_client *p9_client_create(const char *dev_name, char *options); +struct p9_client *p9_client_create(struct fs_context *fc); void p9_client_destroy(struct p9_client *clnt); void p9_client_disconnect(struct p9_client *clnt); void p9_client_begin_disconnect(struct p9_client *clnt); diff --git a/include/net/9p/transport.h b/include/net/9p/transport.h index 766ec07c9599..e53f312191b6 100644 --- a/include/net/9p/transport.h +++ b/include/net/9p/transport.h @@ -14,6 +14,13 @@ #define P9_DEF_MIN_RESVPORT (665U) #define P9_DEF_MAX_RESVPORT (1023U) +#define P9_FD_PORT 564 + +#define P9_RDMA_PORT 5640 +#define P9_RDMA_SQ_DEPTH 32 +#define P9_RDMA_RQ_DEPTH 32 +#define P9_RDMA_TIMEOUT 30000 /* 30 seconds */ + /** * struct p9_trans_module - transport module interface * @list: used to maintain a list of currently available transports @@ -46,7 +53,7 @@ struct p9_trans_module { int def; /* this transport should be default */ struct module *owner; int (*create)(struct p9_client *client, - const char *devname, char *args); + struct fs_context *fc); void (*close)(struct p9_client *client); int (*request)(struct p9_client *client, struct p9_req_t *req); int (*cancel)(struct p9_client *client, struct p9_req_t *req); diff --git a/include/net/af_unix.h b/include/net/af_unix.h index 34f53dde65ce..bb1b3dee02e8 100644 --- a/include/net/af_unix.h +++ b/include/net/af_unix.h @@ -49,6 +49,7 @@ struct unix_sock { struct scm_stat scm_stat; int inq_len; bool recvmsg_inq; + bool scm_rights_notrunc; #if IS_ENABLED(CONFIG_AF_UNIX_OOB) struct sk_buff *oob_skb; #endif diff --git a/include/net/bluetooth/hci_core.h b/include/net/bluetooth/hci_core.h index c416f7f2af6a..d244fd50345e 100644 --- a/include/net/bluetooth/hci_core.h +++ b/include/net/bluetooth/hci_core.h @@ -2271,8 +2271,6 @@ static inline struct smp_irk *hci_get_irk(struct hci_dev *hdev, static inline int hci_check_conn_params(u16 min, u16 max, u16 latency, u16 to_multiplier) { - u16 max_latency; - if (min > max) { BT_WARN("min %d > max %d", min, max); return -EINVAL; @@ -2298,19 +2296,14 @@ static inline int hci_check_conn_params(u16 min, u16 max, u16 latency, return -EINVAL; } - if (max >= to_multiplier * 8) { - BT_WARN("max %d >= to_multiplier %d * 8", max, to_multiplier); - return -EINVAL; - } - - max_latency = (to_multiplier * 4 / max) - 1; if (latency > 499) { BT_WARN("latency %d > 499", latency); return -EINVAL; } - if (latency > max_latency) { - BT_WARN("latency %d > max_latency %d", latency, max_latency); + if ((latency + 1) * max >= to_multiplier * 4) { + BT_WARN("latency %d, max %d and timeout %d are incompatible", + latency, max, to_multiplier); return -EINVAL; } @@ -2330,6 +2323,8 @@ void hci_send_sco(struct hci_conn *conn, struct sk_buff *skb); void hci_send_iso(struct hci_conn *conn, struct sk_buff *skb); void *hci_sent_cmd_data(struct hci_dev *hdev, __u16 opcode); +void *hci_sent_cmd_data_len(struct hci_dev *hdev, __u16 opcode, + size_t *len); void *hci_recv_event_data(struct hci_dev *hdev, __u8 event); u32 hci_conn_get_phy(struct hci_conn *conn); diff --git a/include/net/dst.h b/include/net/dst.h index 307073eae7f8..dbedfe72e1fd 100644 --- a/include/net/dst.h +++ b/include/net/dst.h @@ -455,7 +455,8 @@ static inline unsigned int dst_dev_overhead(struct dst_entry *dst, struct sk_buff *skb) { if (likely(dst)) - return LL_RESERVED_SPACE(dst->dev); + return max_t(unsigned int, skb->mac_len, + LL_RESERVED_SPACE(dst->dev)); return skb->mac_len; } diff --git a/include/net/dst_metadata.h b/include/net/dst_metadata.h index f45d1e3163f0..02fffbb85099 100644 --- a/include/net/dst_metadata.h +++ b/include/net/dst_metadata.h @@ -116,6 +116,8 @@ static inline int skb_metadata_dst_cmp(const struct sk_buff *skb_a, return memcmp(&a->u.port_info, &b->u.port_info, sizeof(a->u.port_info)); case METADATA_IP_TUNNEL: + if (a->u.tun_info.options_len != b->u.tun_info.options_len) + return 1; return memcmp(&a->u.tun_info, &b->u.tun_info, sizeof(a->u.tun_info) + a->u.tun_info.options_len); diff --git a/include/net/gro.h b/include/net/gro.h index e3affb2e2ca8..e3b8ac573f73 100644 --- a/include/net/gro.h +++ b/include/net/gro.h @@ -160,9 +160,19 @@ static inline bool skb_gro_may_pull(const struct sk_buff *skb, return likely(hlen <= NAPI_GRO_CB(skb)->frag0_len); } +/* A pull can release the page fragment frag0 points to, or reallocate + * skb->head, even if it fails. Call this before the pull, to make sure later + * skb_gro_header() and skb_gro_network_header() calls no longer use frag0. + */ +static inline void skb_gro_frag0_invalidate(struct sk_buff *skb) +{ + NAPI_GRO_CB(skb)->frag0_len = 0; +} + static inline void *skb_gro_header_slow(struct sk_buff *skb, unsigned int hlen, unsigned int offset) { + skb_gro_frag0_invalidate(skb); if (!pskb_may_pull(skb, hlen)) return NULL; @@ -351,7 +361,13 @@ static inline void skb_gro_remcsum_cleanup(struct sk_buff *skb, void *ptr; size_t plen = grc->offset + sizeof(u16); - if (!grc->delta) + /* Once merged, grc->offset can not be trusted: the frags or head + * of this skb now belong to the GRO packet, or skb->data was pulled + * past the headers before adding it to a frag_list. + * skb_gro_receive_list() does not merge packets with an adjusted + * checksum, other merged packets do not use their headers anymore. + */ + if (!grc->delta || NAPI_GRO_CB(skb)->same_flow) return; ptr = skb_gro_header(skb, plen, grc->offset); diff --git a/include/net/gso.h b/include/net/gso.h index 0749230d414e..e311a8f5b5a7 100644 --- a/include/net/gso.h +++ b/include/net/gso.h @@ -19,7 +19,7 @@ struct skb_gso_cb { int encap_level; __wsum csum; __u16 csum_start; - /* Number of IPv4/IPv6 GSO handler entries for this packet. */ + /* Number of IPv4/IPv6/NSH GSO handler entries for this packet. */ u8 recursion_counter; }; #define SKB_GSO_CB_OFFSET 32 diff --git a/include/net/inet_connection_sock.h b/include/net/inet_connection_sock.h index 39ccb785dd4c..24e0b62143f5 100644 --- a/include/net/inet_connection_sock.h +++ b/include/net/inet_connection_sock.h @@ -95,6 +95,7 @@ struct inet_connection_sock { u32 icsk_rto_max; __u32 icsk_delack_max; __u32 icsk_pmtu_cookie; + unsigned char unhashed_state; const struct tcp_congestion_ops *icsk_ca_ops; const struct inet_connection_sock_af_ops *icsk_af_ops; const struct tcp_ulp_ops *icsk_ulp_ops; diff --git a/include/net/inet_frag.h b/include/net/inet_frag.h index 6aea2d1ac376..c1fb419a9cf0 100644 --- a/include/net/inet_frag.h +++ b/include/net/inet_frag.h @@ -173,6 +173,7 @@ extern const u8 ip_frag_ecn_table[16]; #define IPFRAG_OK 0 #define IPFRAG_DUP 1 #define IPFRAG_OVERLAP 2 +#define IPFRAG_MIXED_SECPATH 3 #define IPFRAG_TOOBIG 4 /* Max sum of the truesize of fragments in a queue. This keeps the sums diff --git a/include/net/iw_handler.h b/include/net/iw_handler.h index b80e474cb0aa..632618d9ff93 100644 --- a/include/net/iw_handler.h +++ b/include/net/iw_handler.h @@ -201,6 +201,8 @@ #include /* IOCTL user space API */ #include +struct net; + /***************************** VERSION *****************************/ /* * This constant is used to know which version of the driver API is @@ -411,10 +413,10 @@ struct iw_spy_data { void wireless_send_event(struct net_device *dev, unsigned int cmd, union iwreq_data *wrqu, const char *extra); #ifdef CONFIG_WEXT_CORE -/* flush all previous wext events - if work is done from netdev notifiers */ -void wireless_nlevent_flush(void); +/* Flush previous wext events in this netns from netdev notifiers. */ +void wireless_nlevent_flush(struct net *net); #else -static inline void wireless_nlevent_flush(void) {} +static inline void wireless_nlevent_flush(struct net *net) {} #endif /* We may need a function to send a stream of events to user space. diff --git a/include/net/libeth/xsk.h b/include/net/libeth/xsk.h index 3d77e72a8cc8..edc0eba471c4 100644 --- a/include/net/libeth/xsk.h +++ b/include/net/libeth/xsk.h @@ -77,11 +77,17 @@ libeth_xsk_tx_queue_bulk(struct libeth_xdp_tx_bulk *bq, if (!libeth_xsk_tx_queue_head(bq, xdp)) goto out; - for (const struct libeth_xdp_buff *head = xdp; ; ) { + for (struct libeth_xdp_buff *head = xdp; ; ) { xdp = container_of(xsk_buff_get_frag(&head->base), typeof(*xdp), base); - if (!xdp) + if (!xdp) { + /* Each frag is now freed via its own SQE. Freeing + * the head must not release what is on the pool's + * frag list at that time. + */ + xdp_buff_clear_frags_flag(&head->base); break; + } if (unlikely(bq->count == LIBETH_XDP_TX_BULK) && unlikely(!flush_bulk(bq, LIBETH_XDP_TX_XSK))) { diff --git a/include/net/netfilter/nf_conntrack_helper.h b/include/net/netfilter/nf_conntrack_helper.h index 24cf3d2d9745..5b76fa57fd76 100644 --- a/include/net/netfilter/nf_conntrack_helper.h +++ b/include/net/netfilter/nf_conntrack_helper.h @@ -105,6 +105,7 @@ void nf_ct_helper_init(struct nf_conntrack_helper *helper, int nf_conntrack_helper_register(struct nf_conntrack_helper *); void nf_conntrack_helper_unregister(struct nf_conntrack_helper *); +void nf_conntrack_helper_release(struct nf_conntrack_helper *); int nf_conntrack_helpers_register(struct nf_conntrack_helper *, unsigned int); void nf_conntrack_helpers_unregister(struct nf_conntrack_helper *, diff --git a/include/net/netfilter/nf_dup_netdev.h b/include/net/netfilter/nf_dup_netdev.h index f6b05bd80c3f..a39411264614 100644 --- a/include/net/netfilter/nf_dup_netdev.h +++ b/include/net/netfilter/nf_dup_netdev.h @@ -9,41 +9,6 @@ void nf_dup_netdev_egress(const struct nft_pktinfo *pkt, int oif); void nf_fwd_netdev_egress(const struct nft_pktinfo *pkt, int oif); -#define NF_RECURSION_LIMIT 2 - -#ifndef CONFIG_PREEMPT_RT -static inline bool nf_dev_xmit_recursion(void) -{ - return unlikely(__this_cpu_read(softnet_data.xmit.nf_dup_skb_recursion) > - NF_RECURSION_LIMIT); -} - -static inline void nf_dev_xmit_recursion_inc(void) -{ - __this_cpu_inc(softnet_data.xmit.nf_dup_skb_recursion); -} - -static inline void nf_dev_xmit_recursion_dec(void) -{ - __this_cpu_dec(softnet_data.xmit.nf_dup_skb_recursion); -} -#else -static inline bool nf_dev_xmit_recursion(void) -{ - return unlikely(current->net_xmit.nf_dup_skb_recursion > NF_RECURSION_LIMIT); -} - -static inline void nf_dev_xmit_recursion_inc(void) -{ - current->net_xmit.nf_dup_skb_recursion++; -} - -static inline void nf_dev_xmit_recursion_dec(void) -{ - current->net_xmit.nf_dup_skb_recursion--; -} -#endif - struct nft_offload_ctx; struct nft_flow_rule; diff --git a/include/net/netfilter/nf_queue.h b/include/net/netfilter/nf_queue.h index fc3e81c07364..039622d48905 100644 --- a/include/net/netfilter/nf_queue.h +++ b/include/net/netfilter/nf_queue.h @@ -23,6 +23,7 @@ struct nf_queue_entry { struct net_device *physout; #endif struct nf_hook_state state; + bool in_nf_duplicate; bool nf_ct_is_unconfirmed; u16 size; /* sizeof(entry) + saved route keys */ diff --git a/include/net/netfilter/nf_recursion.h b/include/net/netfilter/nf_recursion.h new file mode 100644 index 000000000000..1ac65f7793f1 --- /dev/null +++ b/include/net/netfilter/nf_recursion.h @@ -0,0 +1,42 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _NF_RECURSION_H_ +#define _NF_RECURSION_H_ + +#include + +#define NF_RECURSION_LIMIT 2 + +#ifndef CONFIG_PREEMPT_RT +static inline bool nf_dev_xmit_recursion(void) +{ + return unlikely(__this_cpu_read(softnet_data.xmit.nf_xmit_skb_recursion) > + NF_RECURSION_LIMIT); +} + +static inline void nf_dev_xmit_recursion_inc(void) +{ + __this_cpu_inc(softnet_data.xmit.nf_xmit_skb_recursion); +} + +static inline void nf_dev_xmit_recursion_dec(void) +{ + __this_cpu_dec(softnet_data.xmit.nf_xmit_skb_recursion); +} +#else +static inline bool nf_dev_xmit_recursion(void) +{ + return unlikely(current->net_xmit.nf_xmit_skb_recursion > NF_RECURSION_LIMIT); +} + +static inline void nf_dev_xmit_recursion_inc(void) +{ + current->net_xmit.nf_xmit_skb_recursion++; +} + +static inline void nf_dev_xmit_recursion_dec(void) +{ + current->net_xmit.nf_xmit_skb_recursion--; +} +#endif + +#endif /* _NF_RECURSION_H_ */ diff --git a/include/net/scm.h b/include/net/scm.h index c52519669349..86ae6bc109ec 100644 --- a/include/net/scm.h +++ b/include/net/scm.h @@ -50,8 +50,8 @@ struct scm_cookie { #endif }; -void scm_detach_fds(struct msghdr *msg, struct scm_cookie *scm); -void scm_detach_fds_compat(struct msghdr *msg, struct scm_cookie *scm); +void scm_detach_fds(struct msghdr *msg, struct scm_cookie *scm, bool notrunc); +void scm_detach_fds_compat(struct msghdr *msg, struct scm_cookie *scm, bool notrunc); int __scm_send(struct socket *sock, struct msghdr *msg, struct scm_cookie *scm); void __scm_destroy(struct scm_cookie *scm); struct scm_fp_list *scm_fp_dup(struct scm_fp_list *fpl); @@ -107,13 +107,8 @@ void scm_recv(struct socket *sock, struct msghdr *msg, void scm_recv_unix(struct socket *sock, struct msghdr *msg, struct scm_cookie *scm, int flags); -static inline int scm_recv_one_fd(struct file *f, int __user *ufd, - unsigned int flags) -{ - if (!ufd) - return -EFAULT; - return receive_fd(f, ufd, flags); -} +int scm_recv_one_fd(struct file *f, int __user *ufd, unsigned int flags, + bool notrunc); #endif /* __LINUX_NET_SCM_H */ diff --git a/include/net/sock.h b/include/net/sock.h index fb91d72a955d..dd728a89c10f 100644 --- a/include/net/sock.h +++ b/include/net/sock.h @@ -2176,10 +2176,13 @@ sk_dst_get(const struct sock *sk) static inline void __dst_negative_advice(struct sock *sk) { - struct dst_entry *dst = __sk_dst_get(sk); + struct dst_entry *dst; + rcu_read_lock(); + dst = __sk_dst_get(sk); if (dst && dst->ops->negative_advice) dst->ops->negative_advice(sk, dst); + rcu_read_unlock(); } static inline void dst_negative_advice(struct sock *sk) @@ -2228,6 +2231,14 @@ struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie); struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie); +/* This helper checks if a socket is a full socket, + * ie _not_ a timewait or request socket. + */ +static inline bool sk_fullsock(const struct sock *sk) +{ + return (1 << sk->sk_state) & ~(TCPF_TIME_WAIT | TCPF_NEW_SYN_RECV); +} + static inline void sk_dst_confirm(struct sock *sk) { if (!READ_ONCE(sk->sk_dst_pending_confirm)) @@ -2239,7 +2250,8 @@ static inline void sock_confirm_neigh(struct sk_buff *skb, struct neighbour *n) if (skb_get_dst_pending_confirm(skb)) { struct sock *sk = skb->sk; - if (sk && READ_ONCE(sk->sk_dst_pending_confirm)) + if (sk && sk_fullsock(sk) && + READ_ONCE(sk->sk_dst_pending_confirm)) WRITE_ONCE(sk->sk_dst_pending_confirm, 0); neigh_confirm(n); } @@ -2963,14 +2975,6 @@ skb_sk_is_prefetched(struct sk_buff *skb) #endif /* CONFIG_INET */ } -/* This helper checks if a socket is a full socket, - * ie _not_ a timewait or request socket. - */ -static inline bool sk_fullsock(const struct sock *sk) -{ - return (1 << sk->sk_state) & ~(TCPF_TIME_WAIT | TCPF_NEW_SYN_RECV); -} - static inline bool sk_is_refcounted(struct sock *sk) { diff --git a/include/net/tcp.h b/include/net/tcp.h index f9bcfa8773a3..3bf508ceae7b 100644 --- a/include/net/tcp.h +++ b/include/net/tcp.h @@ -1430,6 +1430,15 @@ static inline unsigned int tcp_packets_in_flight(const struct tcp_sock *tp) #define TCP_INFINITE_SSTHRESH 0x7fffffff +/* Default and maximum snd_cwnd_clamp, in packets. + * A peer can not advertise more than 65535 << 14 bytes, so a larger + * cwnd is useless with any MSS of 1024 bytes or more. + * Congestion control modules multiply cwnd by u32 factors up to 2047 + * (cwnd * (BICTCP_BETA_SCALE + beta) in CUBIC), and CUBIC's + * bictcp_update() expects cwnd to stay below about one million packets. + */ +#define TCP_MAX_SND_CWND (1U << 20) + static inline u32 tcp_snd_cwnd(const struct tcp_sock *tp) { return tp->snd_cwnd; diff --git a/include/net/tcp_ao.h b/include/net/tcp_ao.h index df655ce6987d..bcd7d15a36c0 100644 --- a/include/net/tcp_ao.h +++ b/include/net/tcp_ao.h @@ -287,7 +287,8 @@ static inline enum skb_drop_reason tcp_inbound_ao_hash(struct sock *sk, const struct request_sock *req, int l3index, const struct tcp_ao_hdr *aoh) { - return SKB_NOT_DROPPED_YET; + NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAOKEYNOTFOUND); + return SKB_DROP_REASON_TCP_AOUNEXPECTED; } static inline struct tcp_ao_key *tcp_ao_do_lookup(const struct sock *sk, diff --git a/include/net/xdp_sock_drv.h b/include/net/xdp_sock_drv.h index 21c3b757bb88..e87d081e8e05 100644 --- a/include/net/xdp_sock_drv.h +++ b/include/net/xdp_sock_drv.h @@ -156,15 +156,18 @@ static inline void xsk_buff_free(struct xdp_buff *xdp) static inline bool xsk_buff_add_frag(struct xdp_buff *head, struct xdp_buff *xdp) { + struct xdp_buff_xsk *frag = container_of(xdp, struct xdp_buff_xsk, xdp); const void *data = xdp->data; - struct xdp_buff_xsk *frag; + + /* Duplicate fill ring entries map to the same xskb in aligned mode */ + if (unlikely(xdp == head || !list_empty(&frag->list_node))) + return false; if (!__xdp_buff_add_frag(head, virt_to_netmem(data), offset_in_page(data), xdp->data_end - data, xdp->frame_sz, false)) return false; - frag = container_of(xdp, struct xdp_buff_xsk, xdp); list_add_tail(&frag->list_node, &frag->pool->xskb_list); return true; diff --git a/include/net/xfrm.h b/include/net/xfrm.h index af0869c14a25..7479fe2ca5f5 100644 --- a/include/net/xfrm.h +++ b/include/net/xfrm.h @@ -1189,6 +1189,23 @@ secpath_reset(struct sk_buff *skb) #endif } +static inline bool +secpath_equal(const struct sk_buff *skb1, const struct sk_buff *skb2) +{ + const struct sec_path *sp1 = skb_sec_path(skb1); + const struct sec_path *sp2 = skb_sec_path(skb2); + int i; + + if (!sp1 || !sp2) + return sp1 == sp2; + if (sp1->len != sp2->len) + return false; + for (i = 0; i < sp1->len; i++) + if (sp1->xvec[i] != sp2->xvec[i]) + return false; + return true; +} + static inline int xfrm_addr_any(const xfrm_address_t *addr, unsigned short family) { diff --git a/include/net/xsk_buff_pool.h b/include/net/xsk_buff_pool.h index a461bb63761b..93b60d7294af 100644 --- a/include/net/xsk_buff_pool.h +++ b/include/net/xsk_buff_pool.h @@ -48,6 +48,8 @@ struct xsk_buff_pool { struct device *dev; struct net_device *netdev; struct list_head xsk_tx_list; + /* Assigned pools, including deferred releases; ops protected. */ + struct hlist_node dev_node; /* Protects modifications to the xsk_tx_list */ spinlock_t xsk_tx_list_lock; refcount_t users; @@ -124,6 +126,7 @@ bool xp_put_pool(struct xsk_buff_pool *pool); void xp_clear_dev(struct xsk_buff_pool *pool); void xp_add_xsk(struct xsk_buff_pool *pool, struct xdp_sock *xs); void xp_del_xsk(struct xsk_buff_pool *pool, struct xdp_sock *xs); +void xp_clear_dev_all(struct net_device *dev); /* AF_XDP, and XDP core. */ void xp_free(struct xdp_buff_xsk *xskb); diff --git a/include/trace/events/huge_memory.h b/include/trace/events/huge_memory.h index 1464d45c90ab..6b2e08f4a6be 100644 --- a/include/trace/events/huge_memory.h +++ b/include/trace/events/huge_memory.h @@ -54,10 +54,10 @@ SCAN_STATUS TRACE_EVENT(mm_khugepaged_scan_pmd, - TP_PROTO(struct mm_struct *mm, struct folio *folio, + TP_PROTO(struct mm_struct *mm, unsigned long pfn, int referenced, int none_or_zero, int status, int unmapped), - TP_ARGS(mm, folio, referenced, none_or_zero, status, unmapped), + TP_ARGS(mm, pfn, referenced, none_or_zero, status, unmapped), TP_STRUCT__entry( __field(struct mm_struct *, mm) @@ -70,7 +70,7 @@ TRACE_EVENT(mm_khugepaged_scan_pmd, TP_fast_assign( __entry->mm = mm; - __entry->pfn = folio ? folio_pfn(folio) : -1; + __entry->pfn = pfn; __entry->referenced = referenced; __entry->none_or_zero = none_or_zero; __entry->status = status; diff --git a/include/trace/events/oom.h b/include/trace/events/oom.h index 9f0a5d1482c4..cbcf6fe4cc61 100644 --- a/include/trace/events/oom.h +++ b/include/trace/events/oom.h @@ -33,7 +33,7 @@ TRACE_EVENT(oom_score_adj_update, TRACE_EVENT(reclaim_retry_zone, - TP_PROTO(struct zoneref *zoneref, + TP_PROTO(struct zone *zone, int order, unsigned long reclaimable, unsigned long available, @@ -41,7 +41,7 @@ TRACE_EVENT(reclaim_retry_zone, int no_progress_loops, bool wmark_check), - TP_ARGS(zoneref, order, reclaimable, available, min_wmark, no_progress_loops, wmark_check), + TP_ARGS(zone, order, reclaimable, available, min_wmark, no_progress_loops, wmark_check), TP_STRUCT__entry( __field( int, node) @@ -55,8 +55,8 @@ TRACE_EVENT(reclaim_retry_zone, ), TP_fast_assign( - __entry->node = zonelist_node_idx(zoneref); - __entry->zone_idx = zonelist_zone_idx(zoneref); + __entry->node = zone_to_nid(zone); + __entry->zone_idx = zone_idx(zone); __entry->order = order; __entry->reclaimable = reclaimable; __entry->available = available; diff --git a/include/uapi/asm-generic/socket.h b/include/uapi/asm-generic/socket.h index 53b5a8c002b1..84ea7b92936e 100644 --- a/include/uapi/asm-generic/socket.h +++ b/include/uapi/asm-generic/socket.h @@ -150,6 +150,8 @@ #define SO_INQ 84 #define SCM_INQ SO_INQ +#define SO_RIGHTS_NOTRUNC 85 + #if !defined(__KERNEL__) #if __BITS_PER_LONG == 64 || (defined(__x86_64__) && defined(__ILP32__)) diff --git a/include/uapi/linux/mdio.h b/include/uapi/linux/mdio.h index 6975f182b22c..d194b8182a25 100644 --- a/include/uapi/linux/mdio.h +++ b/include/uapi/linux/mdio.h @@ -383,8 +383,17 @@ #define MDIO_AN_10BT1_AN_STAT_LPA_EEE_T1L 0x4000 /* 10BASE-T1L LP EEE ability advertisement */ /* BASE-T1 PMA/PMD control register */ -#define MDIO_PMA_PMD_BT1_CTRL_STRAP 0x000F /* Type selection (Strap) */ -#define MDIO_PMA_PMD_BT1_CTRL_STRAP_B1000 0x0001 /* Select 1000BASE-T1 */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL 0x000F /* Type selection */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_100BT1 0x0000 /* Select 100BASE-T1 */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_1000BT1 0x0001 /* Select 1000BASE-T1 */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_10BT1L 0x0002 /* Select 10BASE-T1L */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_10BT1S 0x0003 /* Select 10BASE-T1S */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_2P5GBT1 0x0004 /* Select 2.5GBASE-T1 */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_5GBT1 0x0005 /* Select 5GBASE-T1 */ +#define MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_10GBT1 0x0006 /* Select 10GBASE-T1 */ +/* Legacy names, kept for userspace */ +#define MDIO_PMA_PMD_BT1_CTRL_STRAP MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL +#define MDIO_PMA_PMD_BT1_CTRL_STRAP_B1000 MDIO_PMA_PMD_BT1_CTRL_TYPE_SEL_1000BT1 #define MDIO_PMA_PMD_BT1_CTRL_CFG_MST 0x4000 /* MASTER-SLAVE config value */ /* 1000BASE-T1 PCS control register */ diff --git a/include/uapi/linux/perf_event.h b/include/uapi/linux/perf_event.h index 78a362b80027..97c1de3707a2 100644 --- a/include/uapi/linux/perf_event.h +++ b/include/uapi/linux/perf_event.h @@ -314,8 +314,9 @@ enum { */ enum perf_sample_regs_abi { PERF_SAMPLE_REGS_ABI_NONE = 0, - PERF_SAMPLE_REGS_ABI_32 = 1, - PERF_SAMPLE_REGS_ABI_64 = 2, + PERF_SAMPLE_REGS_ABI_32 = (1 << 0), + PERF_SAMPLE_REGS_ABI_64 = (1 << 1), + PERF_SAMPLE_REGS_ABI_SIMD = (1 << 2), }; /* @@ -382,6 +383,8 @@ enum perf_event_read_format { #define PERF_ATTR_SIZE_VER6 120 /* Add: aux_sample_size */ #define PERF_ATTR_SIZE_VER7 128 /* Add: sig_data */ #define PERF_ATTR_SIZE_VER8 136 /* Add: config3 */ +#define PERF_ATTR_SIZE_VER9 144 /* add: config4 */ +#define PERF_ATTR_SIZE_VER10 176 /* Add: sample_simd_{vec|pred}_reg_* */ /* * 'struct perf_event_attr' contains various attributes that define @@ -543,6 +546,30 @@ struct perf_event_attr { __u64 sig_data; __u64 config3; /* extension of config2 */ + __u64 config4; /* extension of config3 */ + + /* + * Defines the sampling SIMD/PRED(predicate) registers bitmap and + * qwords (8 bytes) length. + * + * sample_simd_regs_enabled != 0 indicates there are SIMD/PRED + * registers to be sampled, the SIMD/PRED registers bitmap and + * qwords length are represented in + * sample_simd_{vec|pred}_reg_{intr|user} and + * sample_simd_{vec|pred}_reg_qwords fields separately. + * + * sample_simd_regs_enabled == 0 indicates no SIMD/PRED registers + * are sampled. + */ + __u16 sample_simd_regs_enabled; + __u16 sample_simd_pred_reg_qwords; + __u16 sample_simd_vec_reg_qwords; + __u16 __reserved_4; + + __u32 sample_simd_pred_reg_intr; + __u32 sample_simd_pred_reg_user; + __u64 sample_simd_vec_reg_intr; + __u64 sample_simd_vec_reg_user; }; /* @@ -1016,7 +1043,15 @@ enum perf_event_type { * } && PERF_SAMPLE_BRANCH_STACK * * { u64 abi; # enum perf_sample_regs_abi - * u64 regs[weight(mask)]; } && PERF_SAMPLE_REGS_USER + * u64 regs[weight(mask)]; + * struct { + * u64 nr_vectors; # 0 ... weight(sample_simd_vec_reg_user) + * u64 vector_qwords; # 0 ... sample_simd_vec_reg_qwords + * u64 nr_pred; # 0 ... weight(sample_simd_pred_reg_user) + * u64 pred_qwords; # 0 ... sample_simd_pred_reg_qwords + * u64 data[nr_vectors * vector_qwords + nr_pred * pred_qwords]; + * } && (abi & PERF_SAMPLE_REGS_ABI_SIMD) + * } && PERF_SAMPLE_REGS_USER * * { u64 size; * char data[size]; @@ -1043,7 +1078,15 @@ enum perf_event_type { * { u64 data_src; } && PERF_SAMPLE_DATA_SRC * { u64 transaction; } && PERF_SAMPLE_TRANSACTION * { u64 abi; # enum perf_sample_regs_abi - * u64 regs[weight(mask)]; } && PERF_SAMPLE_REGS_INTR + * u64 regs[weight(mask)]; + * struct { + * u64 nr_vectors; # 0 ... weight(sample_simd_vec_reg_intr) + * u64 vector_qwords; # 0 ... sample_simd_vec_reg_qwords + * u64 nr_pred; # 0 ... weight(sample_simd_pred_reg_intr) + * u64 pred_qwords; # 0 ... sample_simd_pred_reg_qwords + * u64 data[nr_vectors * vector_qwords + nr_pred * pred_qwords]; + * } && (abi & PERF_SAMPLE_REGS_ABI_SIMD) + * } && PERF_SAMPLE_REGS_INTR * { u64 phys_addr;} && PERF_SAMPLE_PHYS_ADDR * { u64 cgroup;} && PERF_SAMPLE_CGROUP * { u64 data_page_size;} && PERF_SAMPLE_DATA_PAGE_SIZE diff --git a/include/uapi/linux/virtio_spi.h b/include/uapi/linux/virtio_spi.h index 8ab3c970cdd3..459c2276c938 100644 --- a/include/uapi/linux/virtio_spi.h +++ b/include/uapi/linux/virtio_spi.h @@ -73,7 +73,7 @@ * @max_cs_hold_ns: the maximum delay supported before chipselect is deasserted, * in ns unit, 0 means delay is not supported to introduce before chipselect * is deasserted. - * @max_cs_incative_ns: maximum delay supported after chipselect is deasserted, + * @max_cs_inactive_ns: maximum delay supported after chipselect is deasserted, * in ns unit, 0 means delay is not supported to introduce after chipselect is * deasserted. */ diff --git a/init/Kconfig b/init/Kconfig index 1858e55bfd7c..97603e51026c 100644 --- a/init/Kconfig +++ b/init/Kconfig @@ -2018,6 +2018,10 @@ config GUEST_PERF_EVENTS bool depends on HAVE_PERF_EVENTS +config PERF_GUEST_MEDIATED_PMU + bool + depends on GUEST_PERF_EVENTS + config PERF_USE_VMALLOC bool help @@ -2147,6 +2151,8 @@ config TRACEPOINTS source "kernel/Kconfig.kexec" +source "kernel/liveupdate/Kconfig" + endmenu # General setup source "arch/Kconfig" diff --git a/init/do_mounts_rd.c b/init/do_mounts_rd.c index 19d9f33dcacf..fb7897d879b0 100644 --- a/init/do_mounts_rd.c +++ b/init/do_mounts_rd.c @@ -268,6 +268,11 @@ int __init rd_load_image(char *from) fput(in_file); noclose_input: fput(out_file); + /* + * The image only reaches the ramdisk when the deferred __fput() + * syncs the block device. Flush it before mount_root() reads it. + */ + init_flush_fput(); out: kfree(buf); init_unlink("/dev/ram"); diff --git a/io_uring/futex.c b/io_uring/futex.c index 6f756de08705..5986ce2a121e 100644 --- a/io_uring/futex.c +++ b/io_uring/futex.c @@ -104,6 +104,7 @@ static bool __io_futex_cancel(struct io_kiocb *req) } hlist_del_init(&req->hash_node); + req_set_fail(req); io_req_set_res(req, -ECANCELED, 0); io_req_task_work_add(req); return true; diff --git a/io_uring/io-wq.c b/io_uring/io-wq.c index fd53297af26e..0d74e365d54a 100644 --- a/io_uring/io-wq.c +++ b/io_uring/io-wq.c @@ -731,6 +731,34 @@ static bool io_worker_retire(struct io_wq_acct *acct, struct io_worker *worker) return false; } +/* + * The CPUs a worker of @wq runs on: those of the io-wq affinity that the + * worker's cpuset allows, or the cpuset if they have none in common, as the + * scheduler does with a task's requested affinity when its cpuset changes. + * Read the cpuset each time: it can change while the io-wq exists. + */ +static void io_wq_worker_cpus(struct io_wq *wq, struct task_struct *tsk, + struct cpumask *cpus) +{ + cpuset_cpus_allowed(tsk, cpus); + if (cpumask_intersects(cpus, wq->cpu_mask)) + cpumask_and(cpus, cpus, wq->cpu_mask); +} + +/* Is the current worker on a CPU that a new worker would not get? */ +static bool io_wq_worker_off_cpus(struct io_wq *wq) +{ + cpumask_var_t cpus; + bool off; + + if (!alloc_cpumask_var(&cpus, GFP_KERNEL)) + return false; + io_wq_worker_cpus(wq, current, cpus); + off = !cpumask_test_cpu(raw_smp_processor_id(), cpus); + free_cpumask_var(cpus); + return off; +} + static int io_wq_worker(void *data) { struct io_worker *worker = data; @@ -809,8 +837,7 @@ static int io_wq_worker(void *data) } if (!ret) { last_timeout = true; - exit_mask = !cpumask_test_cpu(raw_smp_processor_id(), - wq->cpu_mask); + exit_mask = io_wq_worker_off_cpus(wq); } } @@ -860,9 +887,16 @@ void io_wq_worker_sleeping(struct task_struct *tsk) static void io_init_new_worker(struct io_wq *wq, struct io_wq_acct *acct, struct io_worker *worker, struct task_struct *tsk) { + cpumask_var_t cpus; + tsk->worker_private = worker; worker->task = tsk; - set_cpus_allowed_ptr(tsk, wq->cpu_mask); + /* Without a mask, the worker keeps its creator's CPUs. */ + if (alloc_cpumask_var(&cpus, GFP_KERNEL)) { + io_wq_worker_cpus(wq, tsk, cpus); + set_cpus_allowed_ptr(tsk, cpus); + free_cpumask_var(cpus); + } raw_spin_lock(&acct->workers_lock); hlist_nulls_add_head_rcu(&worker->nulls_node, &acct->free_list); @@ -1361,7 +1395,7 @@ struct io_wq *io_wq_create(unsigned bounded, struct io_wq_data *data) if (!alloc_cpumask_var(&wq->cpu_mask, GFP_KERNEL)) goto err; - cpuset_cpus_allowed(data->task, wq->cpu_mask); + cpumask_copy(wq->cpu_mask, cpu_possible_mask); wq->acct[IO_WQ_ACCT_BOUND].max_workers = bounded; wq->acct[IO_WQ_ACCT_UNBOUND].max_workers = task_rlimit(current, RLIMIT_NPROC); @@ -1545,7 +1579,7 @@ int io_wq_cpu_affinity(struct io_uring_task *tctx, cpumask_var_t mask) else ret = -EINVAL; } else { - cpumask_copy(tctx->io_wq->cpu_mask, allowed_mask); + cpumask_copy(tctx->io_wq->cpu_mask, cpu_possible_mask); } rcu_read_unlock(); diff --git a/io_uring/io_uring.c b/io_uring/io_uring.c index 4a9f3a0fe506..df5f33a0f937 100644 --- a/io_uring/io_uring.c +++ b/io_uring/io_uring.c @@ -1971,9 +1971,11 @@ static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags) ret = __io_issue_sqe(req, issue_flags, def); if (ret == IOU_COMPLETE) { - /* not all handlers take care of the internal restart codes */ - if (unlikely(req->cqe.res <= -ERESTARTSYS)) - req->cqe.res = io_fixup_restart_res(req->cqe.res); + if (unlikely(req->cqe.res < 0)) { + if (req->cqe.res <= -ERESTARTSYS) + req->cqe.res = io_fixup_restart_res(req->cqe.res); + req_set_fail(req); + } if (issue_flags & IO_URING_F_COMPLETE_DEFER) io_req_complete_defer(req); else diff --git a/io_uring/io_uring.h b/io_uring/io_uring.h index 922bdf68aec8..4f1d20d28f72 100644 --- a/io_uring/io_uring.h +++ b/io_uring/io_uring.h @@ -113,6 +113,7 @@ struct io_wait_queue { #ifdef CONFIG_NET_RX_BUSY_POLL ktime_t napi_busy_poll_dt; + ktime_t napi_busy_poll_end; bool napi_prefer_busy_poll; #endif }; diff --git a/io_uring/kbuf.c b/io_uring/kbuf.c index c091c3c462e1..6659f56e91fc 100644 --- a/io_uring/kbuf.c +++ b/io_uring/kbuf.c @@ -355,6 +355,7 @@ int io_buffers_select(struct io_kiocb *req, struct buf_sel_arg *arg, req->flags |= REQ_F_BUF_MORE; } } else { + arg->out_len = arg->max_len; ret = io_provided_buffers_select(req, &arg->out_len, sel->buf_list, arg->iovs); } out_unlock: diff --git a/io_uring/napi.c b/io_uring/napi.c index 45180b172bec..46f5854f05ef 100644 --- a/io_uring/napi.c +++ b/io_uring/napi.c @@ -128,19 +128,15 @@ static inline void io_napi_remove_stale(struct io_ring_ctx *ctx, bool is_stale) __io_napi_remove_stale(ctx); } -static inline bool io_napi_busy_loop_timeout(ktime_t start_time, - ktime_t bp) +static inline bool io_napi_busy_loop_timeout(struct io_wait_queue *iowq) { - if (bp) { - ktime_t end_time = ktime_add(start_time, bp); - ktime_t now = net_to_ktime(busy_loop_current_time()); - - return ktime_after(now, end_time); - } - - return true; + if (!iowq->napi_busy_poll_dt) + return true; + return ktime_after(net_to_ktime(busy_loop_current_time()), + iowq->napi_busy_poll_end); } +/* Uses an absolute deadline, so the napi loop can be re-entered */ static bool io_napi_busy_loop_should_end(void *data, unsigned long start_time) { @@ -150,8 +146,7 @@ static bool io_napi_busy_loop_should_end(void *data, return true; if (io_should_wake(iowq) || io_has_work(iowq->ctx)) return true; - if (io_napi_busy_loop_timeout(net_to_ktime(start_time), - iowq->napi_busy_poll_dt)) + if (io_napi_busy_loop_timeout(iowq)) return true; return false; @@ -204,13 +199,16 @@ __io_napi_do_busy_loop(struct io_ring_ctx *ctx, static void io_napi_blocking_busy_loop(struct io_ring_ctx *ctx, struct io_wait_queue *iowq) { - unsigned long start_time = busy_loop_current_time(); + ktime_t now = net_to_ktime(busy_loop_current_time()); bool (*loop_end)(void *, unsigned long) = NULL; void *loop_end_arg = NULL; bool is_stale = false; - /* Singular lists use a different napi loop end check function and are - * only executed once. + iowq->napi_busy_poll_end = ktime_add(now, iowq->napi_busy_poll_dt); + + /* + * A single NAPI is held by __napi_busy_loop() for the whole spin. It + * may return early on need_resched(), loop until our own deadline. */ if (list_is_singular(&ctx->napi_list)) { loop_end = io_napi_busy_loop_should_end; @@ -221,8 +219,7 @@ static void io_napi_blocking_busy_loop(struct io_ring_ctx *ctx, do { is_stale = __io_napi_do_busy_loop(ctx, loop_end, loop_end_arg); - } while (!io_napi_busy_loop_should_end(iowq, start_time) && - !loop_end_arg); + } while (!io_napi_busy_loop_should_end(iowq, 0)); } io_napi_remove_stale(ctx, is_stale); diff --git a/io_uring/rsrc.c b/io_uring/rsrc.c index 7170b3f001d4..36a9bc279e74 100644 --- a/io_uring/rsrc.c +++ b/io_uring/rsrc.c @@ -237,9 +237,6 @@ static int __io_sqe_files_update(struct io_ring_ctx *ctx, continue; i = up->offset + done; - if (io_reset_rsrc_node(ctx, &ctx->file_table.data, i)) - io_file_bitmap_clear(&ctx->file_table, i); - if (fd != -1) { struct file *file = fget(fd); struct io_rsrc_node *node; @@ -262,11 +259,15 @@ static int __io_sqe_files_update(struct io_ring_ctx *ctx, fput(file); break; } + if (io_reset_rsrc_node(ctx, &ctx->file_table.data, i)) + io_file_bitmap_clear(&ctx->file_table, i); ctx->file_table.data.nodes[i] = node; if (tag) node->tag = tag; io_fixed_file_set(node, file); io_file_bitmap_set(&ctx->file_table, i); + } else if (io_reset_rsrc_node(ctx, &ctx->file_table.data, i)) { + io_file_bitmap_clear(&ctx->file_table, i); } } return done ? done : err; diff --git a/io_uring/rw.c b/io_uring/rw.c index f46d08bbe9d8..48ef87b4697b 100644 --- a/io_uring/rw.c +++ b/io_uring/rw.c @@ -618,8 +618,10 @@ static void io_complete_rw_iopoll(struct kiocb *kiocb, long res) if (res == -EAGAIN && io_rw_should_reissue(req)) req->flags |= REQ_F_REISSUE | REQ_F_BL_NO_RECYCLE; - else if (unlikely(final_res != req->cqe.res)) + else if (unlikely(final_res != req->cqe.res)) { + req_set_fail(req); req->cqe.res = final_res; + } /* order with io_iopoll_complete() checking ->iopoll_completed */ smp_store_release(&req->iopoll_completed, 1); diff --git a/io_uring/timeout.c b/io_uring/timeout.c index 2637c8bb61a0..36c8f3dae27a 100644 --- a/io_uring/timeout.c +++ b/io_uring/timeout.c @@ -76,7 +76,8 @@ static void io_timeout_complete(struct io_tw_req tw_req, io_tw_token_t tw) struct io_ring_ctx *ctx = req->ctx; if (!io_timeout_finish(timeout, data)) { - if (io_req_post_cqe(req, -ETIME, IORING_CQE_F_MORE)) { + if (!tw.cancel && + io_req_post_cqe(req, -ETIME, IORING_CQE_F_MORE)) { /* re-arm timer */ raw_spin_lock_irq(&ctx->timeout_lock); list_add(&timeout->list, ctx->timeout_list.prev); diff --git a/kernel/Kconfig.kexec b/kernel/Kconfig.kexec index cc6743137946..15632358bcf7 100644 --- a/kernel/Kconfig.kexec +++ b/kernel/Kconfig.kexec @@ -94,40 +94,6 @@ config KEXEC_JUMP Jump between original kernel and kexeced kernel and invoke code in physical address mode via KEXEC -config KEXEC_HANDOVER - bool "kexec handover" - depends on ARCH_SUPPORTS_KEXEC_HANDOVER && ARCH_SUPPORTS_KEXEC_FILE - depends on !DEFERRED_STRUCT_PAGE_INIT - select MEMBLOCK_KHO_SCRATCH - select KEXEC_FILE - select LIBFDT - select CMA - help - Allow kexec to hand over state across kernels by generating and - passing additional metadata to the target kernel. This is useful - to keep data or state alive across the kexec. For this to work, - both source and target kernels need to have this option enabled. - -config KEXEC_HANDOVER_DEBUG - bool "Enable Kexec Handover debug checks" - depends on KEXEC_HANDOVER - help - This option enables extra sanity checks for the Kexec Handover - subsystem. Since, KHO performance is crucial in live update - scenarios and the extra code might be adding overhead it is - only optionally enabled. - -config KEXEC_HANDOVER_DEBUGFS - bool "kexec handover debugfs interface" - default KEXEC_HANDOVER - depends on KEXEC_HANDOVER - select DEBUG_FS - help - Allow to control kexec handover device tree via debugfs - interface, i.e. finalize the state or aborting the finalization. - Also, enables inspecting the KHO fdt trees with the debugfs binary - blobs. - config CRASH_DUMP bool "kernel crash dumps" default ARCH_DEFAULT_CRASH_DUMP diff --git a/kernel/Makefile b/kernel/Makefile index 2cf7909a74e5..e83669841b8c 100644 --- a/kernel/Makefile +++ b/kernel/Makefile @@ -52,6 +52,7 @@ obj-y += printk/ obj-y += irq/ obj-y += rcu/ obj-y += livepatch/ +obj-y += liveupdate/ obj-y += dma/ obj-y += entry/ obj-y += unwind/ @@ -82,9 +83,6 @@ obj-$(CONFIG_CRASH_DUMP_KUNIT_TEST) += crash_core_test.o obj-$(CONFIG_KEXEC) += kexec.o obj-$(CONFIG_KEXEC_FILE) += kexec_file.o obj-$(CONFIG_KEXEC_ELF) += kexec_elf.o -obj-$(CONFIG_KEXEC_HANDOVER) += kexec_handover.o -obj-$(CONFIG_KEXEC_HANDOVER_DEBUG) += kexec_handover_debug.o -obj-$(CONFIG_KEXEC_HANDOVER_DEBUGFS) += kexec_handover_debugfs.o obj-$(CONFIG_BACKTRACE_SELF_TEST) += backtracetest.o obj-$(CONFIG_COMPAT) += compat.o obj-$(CONFIG_CGROUPS) += cgroup/ diff --git a/kernel/bpf/arena.c b/kernel/bpf/arena.c index 51227c8d2b1e..3d3bad292bad 100644 --- a/kernel/bpf/arena.c +++ b/kernel/bpf/arena.c @@ -333,7 +333,7 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long ad if (pgoff) return -EINVAL; - if (len > SZ_4G) + if (len > (u64)map->max_entries * PAGE_SIZE) return -E2BIG; /* if user_vm_start was specified at arena creation time */ @@ -349,11 +349,11 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long ad ret = mm_get_unmapped_area(current->mm, filp, addr, len * 2, 0, flags); if (IS_ERR_VALUE(ret)) return ret; + if (!ret) + /* user_vm_start == 0 means that the user range is not set yet */ + return -EINVAL; if ((ret >> 32) == ((ret + len - 1) >> 32)) return ret; - if (WARN_ON_ONCE(arena->user_vm_start)) - /* checks at map creation time should prevent this */ - return -EFAULT; return round_up(ret, SZ_4G); } @@ -378,7 +378,7 @@ static int arena_map_mmap(struct bpf_map *map, struct vm_area_struct *vma) return -EBUSY; /* Earlier checks should prevent this */ - if (WARN_ON_ONCE(vma->vm_end - vma->vm_start > SZ_4G || vma->vm_pgoff)) + if (WARN_ON_ONCE(vma_pages(vma) > map->max_entries || vma->vm_pgoff)) return -EFAULT; if (remember_vma(arena, vma)) diff --git a/kernel/bpf/arraymap.c b/kernel/bpf/arraymap.c index 248ab6854cf2..859fb807ea89 100644 --- a/kernel/bpf/arraymap.c +++ b/kernel/bpf/arraymap.c @@ -967,7 +967,7 @@ static void *prog_fd_array_get_ptr(struct bpf_map *map, } mutex_lock(&prog->aux->ext_mutex); - is_extended = prog->aux->is_extended; + is_extended = prog->aux->freplace_link_cnt > 0; if (!is_extended) prog->aux->prog_array_member_cnt++; mutex_unlock(&prog->aux->ext_mutex); diff --git a/kernel/bpf/bpf_local_storage.c b/kernel/bpf/bpf_local_storage.c index b931fbceb54d..9fb26ae066f5 100644 --- a/kernel/bpf/bpf_local_storage.c +++ b/kernel/bpf/bpf_local_storage.c @@ -890,7 +890,7 @@ void bpf_local_storage_map_free(struct bpf_map *map, struct bpf_local_storage_elem, map_node))) { if (busy_counter) this_cpu_inc(*busy_counter); - bpf_selem_unlink(selem, true); + bpf_selem_unlink(selem, false); if (busy_counter) this_cpu_dec(*busy_counter); cond_resched_rcu(); diff --git a/kernel/bpf/cgroup.c b/kernel/bpf/cgroup.c index c652ba01bc8b..14521bd99c7a 100644 --- a/kernel/bpf/cgroup.c +++ b/kernel/bpf/cgroup.c @@ -1125,9 +1125,14 @@ static struct bpf_prog_list *find_detach_entry(struct hlist_head *progs, return ERR_PTR(-ENOENT); /* to maintain backward compatibility NONE and OVERRIDE cgroups - * allow detaching with invalid FD (prog==NULL) in legacy mode + * allow detaching with invalid FD (prog==NULL) in legacy mode. + * Without the FD of the attached program the caller needs + * CAP_NET_ADMIN or CAP_SYS_ADMIN in the initial user namespace. */ - return hlist_entry(progs->first, typeof(*pl), node); + pl = hlist_entry(progs->first, typeof(*pl), node); + if (pl->prog != prog && !bpf_net_capable()) + return ERR_PTR(-EPERM); + return pl; } if (!prog && !link) @@ -1625,7 +1630,7 @@ int __cgroup_bpf_run_filter_skb(struct sock *sk, struct sk_buff *skb, enum cgroup_bpf_attach_type atype) { - unsigned int offset = -skb_network_offset(skb); + int offset = skb_network_offset(skb); struct sock *save_sk; void *saved_data_end; struct cgroup *cgrp; @@ -1637,7 +1642,15 @@ int __cgroup_bpf_run_filter_skb(struct sock *sk, cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data); save_sk = skb->sk; skb->sk = sk; - __skb_push(skb, offset); + + /* + * The program sees the packet from its network header on, on + * whichever side of skb->data that header lies. + */ + if (offset > 0) + __skb_pull(skb, offset); + else + __skb_push(skb, -offset); /* compute pointers for the bpf prog */ bpf_compute_and_save_data_end(skb, &saved_data_end); @@ -1679,7 +1692,10 @@ int __cgroup_bpf_run_filter_skb(struct sock *sk, ret = -EFAULT; } bpf_restore_data_end(skb, saved_data_end); - __skb_pull(skb, offset); + if (offset > 0) + __skb_push(skb, offset); + else + __skb_pull(skb, -offset); skb->sk = save_sk; return ret; diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c index 346588a32a85..59c87eeb07cd 100644 --- a/kernel/bpf/core.c +++ b/kernel/bpf/core.c @@ -206,7 +206,9 @@ void bpf_prog_jit_attempt_done(struct bpf_prog *prog) * here is relative to the prog itself instead of the main prog. * This array has one entry for each xlated bpf insn. * - * jited_off is the byte off to the end of the jited insn. + * jited_off is the byte off to the end of the jited insn, counted from + * the start of the jited image, which is cfi_get_offset() bytes before + * prog->bpf_func. * * Hence, with * insn_start: @@ -220,7 +222,7 @@ void bpf_prog_jit_attempt_done(struct bpf_prog *prog) * * For i > linfo_idx, * - * jited_linfo[i] = prog->bpf_func + + * jited_linfo[i] = prog->bpf_func - cfi_get_offset() + * insn_to_jit_off[linfo[i].insn_off - insn_start - 1] */ void bpf_prog_fill_jited_linfo(struct bpf_prog *prog, @@ -248,7 +250,7 @@ void bpf_prog_fill_jited_linfo(struct bpf_prog *prog, /* The verifier ensures that linfo[i].insn_off is * strictly increasing */ - jited_linfo[i] = prog->bpf_func + + jited_linfo[i] = prog->bpf_func - cfi_get_offset() + insn_to_jit_off[linfo[i].insn_off - insn_start - 1]; } @@ -2906,7 +2908,7 @@ void __bpf_free_used_maps(struct bpf_prog_aux *aux, bool sleepable; u32 i; - sleepable = aux->prog->sleepable; + sleepable = bpf_prog_runs_sleepable(aux->prog); for (i = 0; i < len; i++) { map = used_maps[i]; if (map->ops->map_poke_untrack) diff --git a/kernel/bpf/hashtab.c b/kernel/bpf/hashtab.c index 23c9e54f92e1..95e9a760a7be 100644 --- a/kernel/bpf/hashtab.c +++ b/kernel/bpf/hashtab.c @@ -96,10 +96,10 @@ struct bpf_htab { struct bpf_lru lru; }; struct htab_elem *__percpu *extra_elems; - /* number of elements in non-preallocated hashtable are kept - * in either pcount or count + /* number of elements in non-preallocated hashtable. With + * use_percpu_counter it only follows map.elem_count in steps of + * PERCPU_COUNTER_BATCH, see is_map_full() */ - struct percpu_counter pcount; atomic_t count; bool use_percpu_counter; u32 n_buckets; /* number of hash buckets */ @@ -628,29 +628,20 @@ static struct bpf_map *htab_map_alloc(union bpf_attr *attr) htab_init_buckets(htab); -/* compute_batch_value() computes batch value as num_online_cpus() * 2 - * and __percpu_counter_compare() needs - * htab->max_entries - cur_number_of_elems to be more than batch * num_online_cpus() - * for percpu_counter to be faster than atomic_t. In practice the average bpf - * hash map size is 10k, which means that a system with 64 cpus will fill - * hashmap to 20% of 10k before percpu_counter becomes ineffective. Therefore - * define our own batch count as 32 then 10k hash map can be filled up to 80%: +/* is_map_full() needs htab->max_entries - cur_number_of_elems to be more than + * batch * nr_cpu_ids for the percpu counter to be faster than atomic_t. In + * practice the average bpf hash map size is 10k. With batch count of 32 a 10k + * hash map on a system with 64 cpus can be filled up to 80%: * 10k - 8k > 32 _batch_ * 64 _cpus_ - * and __percpu_counter_compare() will still be fast. At that point hash map + * and is_map_full() will still be fast. At that point hash map * collisions will dominate its performance anyway. Assume that hash map filled * to 50+% isn't going to be O(1) and use the following formula to choose - * between percpu_counter and atomic_t. + * between the percpu counter and atomic_t. The batch has to be a power of 2. */ #define PERCPU_COUNTER_BATCH 32 - if (attr->max_entries / 2 > num_online_cpus() * PERCPU_COUNTER_BATCH) + if (attr->max_entries / 2 > nr_cpu_ids * PERCPU_COUNTER_BATCH) htab->use_percpu_counter = true; - if (htab->use_percpu_counter) { - err = percpu_counter_init(&htab->pcount, 0, GFP_KERNEL); - if (err) - goto free_map_locked; - } - if (prealloc) { err = prealloc_init(htab); if (err) @@ -678,8 +669,6 @@ static struct bpf_map *htab_map_alloc(union bpf_attr *attr) free_prealloc: prealloc_destroy(htab); free_map_locked: - if (htab->use_percpu_counter) - percpu_counter_destroy(&htab->pcount); bpf_map_area_free(htab->buckets); bpf_mem_alloc_destroy(&htab->pcpu_ma); bpf_mem_alloc_destroy(&htab->ma); @@ -988,30 +977,33 @@ static void htab_put_fd_value(struct bpf_htab *htab, struct htab_elem *l) static bool is_map_full(struct bpf_htab *htab) { - if (htab->use_percpu_counter) - return __percpu_counter_compare(&htab->pcount, htab->map.max_entries, - PERCPU_COUNTER_BATCH) >= 0; - return atomic_read(&htab->count) >= htab->map.max_entries; + s64 count = atomic_read(&htab->count); + + /* each cpu's elem_count is ahead of count by less than the batch */ + if (htab->use_percpu_counter && + count + nr_cpu_ids * PERCPU_COUNTER_BATCH >= htab->map.max_entries) + count = bpf_map_sum_elem_count(&htab->map); + return count >= htab->map.max_entries; } static void inc_elem_count(struct bpf_htab *htab) { - bpf_map_inc_elem_count(&htab->map); + s64 cnt = this_cpu_inc_return(*htab->map.elem_count); - if (htab->use_percpu_counter) - percpu_counter_add_batch(&htab->pcount, 1, PERCPU_COUNTER_BATCH); - else + if (!htab->use_percpu_counter) atomic_inc(&htab->count); + else if (!(cnt & (PERCPU_COUNTER_BATCH - 1))) + atomic_add(PERCPU_COUNTER_BATCH, &htab->count); } static void dec_elem_count(struct bpf_htab *htab) { - bpf_map_dec_elem_count(&htab->map); + s64 cnt = this_cpu_dec_return(*htab->map.elem_count); - if (htab->use_percpu_counter) - percpu_counter_add_batch(&htab->pcount, -1, PERCPU_COUNTER_BATCH); - else + if (!htab->use_percpu_counter) atomic_dec(&htab->count); + else if (!((cnt + 1) & (PERCPU_COUNTER_BATCH - 1))) + atomic_sub(PERCPU_COUNTER_BATCH, &htab->count); } @@ -1093,11 +1085,17 @@ static struct htab_elem *alloc_htab_elem(struct bpf_htab *htab, void *key, if (prealloc) { if (old_elem) { /* if we're updating the existing element, - * use per-cpu extra elems to avoid freelist_pop/push + * use per-cpu extra elems to avoid freelist_pop/push. + * The caller puts old_elem into the slot once it is + * unlinked. Until then the slot is empty for an NMI + * or a kprobe that updates this map on this cpu. */ pl_new = this_cpu_ptr(htab->extra_elems); - l_new = *pl_new; - *pl_new = old_elem; + l_new = READ_ONCE(*pl_new); + do { + if (!l_new) + return ERR_PTR(-EBUSY); + } while (!try_cmpxchg_local(pl_new, &l_new, NULL)); } else { struct pcpu_freelist_node *l; @@ -1259,11 +1257,15 @@ static long htab_map_update_elem(struct bpf_map *map, void *key, void *value, if (l_old) { hlist_nulls_del_rcu(&l_old->hash_node); - /* l_old has already been stashed in htab->extra_elems, free - * its special fields before it is available for reuse. + /* + * l_old replaces the extra element that alloc_htab_elem() took. + * Free its special fields first: once it is in the + * slot, the next update on this cpu can reuse it. */ - if (htab_is_prealloc(htab)) + if (htab_is_prealloc(htab)) { check_and_free_fields(htab, l_old); + WRITE_ONCE(*this_cpu_ptr(htab->extra_elems), l_old); + } } htab_unlock_bucket(b, flags); if (l_old && !htab_is_prealloc(htab)) @@ -1641,8 +1643,6 @@ static void htab_map_free(struct bpf_map *map) bpf_map_area_free(htab->buckets); bpf_mem_alloc_destroy(&htab->pcpu_ma); bpf_mem_alloc_destroy(&htab->ma); - if (htab->use_percpu_counter) - percpu_counter_destroy(&htab->pcount); bpf_map_area_free(htab); } @@ -2342,9 +2342,7 @@ static u64 htab_map_mem_usage(const struct bpf_map *map) } else { #define LLIST_NODE_SZ sizeof(struct llist_node) - num_entries = htab->use_percpu_counter ? - percpu_counter_sum(&htab->pcount) : - atomic_read(&htab->count); + num_entries = bpf_map_sum_elem_count(map); usage += (htab->elem_size + LLIST_NODE_SZ) * num_entries; if (percpu) { usage += (LLIST_NODE_SZ + sizeof(void *)) * num_entries; diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c index 31afbb74a052..5271bc5178ea 100644 --- a/kernel/bpf/helpers.c +++ b/kernel/bpf/helpers.c @@ -1214,18 +1214,21 @@ static void bpf_wq_work(struct work_struct *work) BTF_TYPE_EMIT(struct bpf_wq); + /* keeps the program that callback_fn belongs to */ + rcu_read_lock_trace(); + callback_fn = READ_ONCE(cb->callback_fn); if (!callback_fn) - return; + goto out; key = map_key_from_value(map, value, &idx); - rcu_read_lock_trace(); - migrate_disable(); + migrate_disable(); callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0); migrate_enable(); +out: rcu_read_unlock_trace(); } @@ -3915,8 +3918,13 @@ __bpf_kfunc int bpf_verify_pkcs7_signature(struct bpf_dynptr *data_p, data_len = __bpf_dynptr_size(data_ptr); data = __bpf_dynptr_data(data_ptr, data_len); + if (!data) + return -EINVAL; + sig_len = __bpf_dynptr_size(sig_ptr); sig = __bpf_dynptr_data(sig_ptr, sig_len); + if (!sig) + return -EINVAL; return verify_pkcs7_signature(data, data_len, sig, sig_len, trusted_keyring->key, diff --git a/kernel/bpf/stackmap.c b/kernel/bpf/stackmap.c index 02b6b0e9cb6c..aa87e8d2d7d2 100644 --- a/kernel/bpf/stackmap.c +++ b/kernel/bpf/stackmap.c @@ -386,7 +386,7 @@ get_callchain_entry_for_task(struct task_struct *task, u32 max_depth) struct stackid { struct stack_map_bucket *bucket; - u64 *ips; + const u64 *ips; u32 nr; u32 len; u32 hash; @@ -395,21 +395,23 @@ struct stackid { }; static int stackid_init(struct stackid *stackid, struct bpf_map *map, - struct perf_callchain_entry *trace, u64 flags) + const struct perf_callchain_entry *trace, u32 trace_nr, u64 flags) { struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map); u32 skip = flags & BPF_F_SKIP_FIELD_MASK; u32 max_depth; - if (trace->nr <= skip) + max_depth = stack_map_calculate_max_depth(map->value_size, stack_map_data_size(map), flags); + /* trace_nr can be above max_depth and max_depth below skip: clamp first */ + trace_nr = min_t(u32, trace_nr, max_depth); + if (trace_nr <= skip) /* skipping more than usable stack trace */ return -EFAULT; - max_depth = stack_map_calculate_max_depth(map->value_size, stack_map_data_size(map), flags); - stackid->nr = min_t(u32, trace->nr - skip, max_depth - skip); + stackid->nr = trace_nr - skip; stackid->len = stackid->nr * sizeof(u64); stackid->ips = trace->ip + skip; - stackid->hash = jhash2((u32 *)stackid->ips, stackid->len / sizeof(u32), 0); + stackid->hash = jhash2((const u32 *)stackid->ips, stackid->len / sizeof(u32), 0); stackid->id = stackid->hash & (smap->n_buckets - 1); stackid->bucket = READ_ONCE(smap->buckets[stackid->id]); stackid->hash_matches = stackid->bucket && stackid->bucket->hash == stackid->hash; @@ -417,11 +419,12 @@ static int stackid_init(struct stackid *stackid, struct bpf_map *map, } static int stackid_fastpath(struct stackid *stackid, struct bpf_map *map, - struct perf_callchain_entry *trace, u64 flags) + const struct perf_callchain_entry *trace, u32 trace_nr, + u64 flags) { int err; - err = stackid_init(stackid, map, trace, flags); + err = stackid_init(stackid, map, trace, trace_nr, flags); if (err) return err; @@ -520,7 +523,8 @@ BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map, /* couldn't fetch the stack trace */ return -EFAULT; - err = stackid_fastpath(&stackid, map, trace, flags); + /* the entry is released already, an NMI can change trace->nr */ + err = stackid_fastpath(&stackid, map, trace, READ_ONCE(trace->nr), flags); if (err != -ENOENT) return err; @@ -541,7 +545,7 @@ const struct bpf_func_proto bpf_get_stackid_proto = { .arg3_type = ARG_ANYTHING, }; -static __u64 count_kernel_ip(struct perf_callchain_entry *trace) +static __u64 count_kernel_ip(const struct perf_callchain_entry *trace) { __u64 nr_kernel = 0; @@ -556,12 +560,13 @@ static __u64 count_kernel_ip(struct perf_callchain_entry *trace) BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx, struct bpf_map *, map, u64, flags) { + const struct perf_callchain_entry *trace; struct perf_event *event = ctx->event; struct stack_map_bucket *new_bucket; - struct perf_callchain_entry *trace; struct stackid stackid; bool kernel, user; __u64 nr_kernel; + u32 trace_nr; int ret; /* perf_sample_data doesn't have callchain, use bpf_get_stackid */ @@ -581,13 +586,13 @@ BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx, return -EFAULT; nr_kernel = count_kernel_ip(trace); - __u64 nr = trace->nr; /* save original */ if (kernel) { - trace->nr = nr_kernel; + trace_nr = nr_kernel; } else { /* user */ u64 skip = flags & BPF_F_SKIP_FIELD_MASK; + trace_nr = trace->nr; skip += nr_kernel; if (skip > BPF_F_SKIP_FIELD_MASK) return -EFAULT; @@ -595,21 +600,14 @@ BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx, flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip; } - ret = stackid_fastpath(&stackid, map, trace, flags); + ret = stackid_fastpath(&stackid, map, trace, trace_nr, flags); if (ret != -ENOENT) - goto out; + return ret; new_bucket = stackid_new_bucket(&stackid, map); - if (new_bucket) { - trace->nr = nr; + if (new_bucket) return stackid_install(&stackid, map, new_bucket, flags); - } - ret = -ENOMEM; - -out: - /* restore nr */ - trace->nr = nr; - return ret; + return -ENOMEM; } const struct bpf_func_proto bpf_get_stackid_proto_pe = { @@ -621,15 +619,15 @@ const struct bpf_func_proto bpf_get_stackid_proto_pe = { .arg3_type = ARG_ANYTHING, }; -static u32 callchain_store(struct perf_callchain_entry *trace, void *buf, - u32 elem_size, u64 flags) +static u32 callchain_store(const struct perf_callchain_entry *trace, u32 trace_nr, + void *buf, u32 elem_size, u64 flags) { bool user_build_id = flags & BPF_F_USER_BUILD_ID; u32 skip = flags & BPF_F_SKIP_FIELD_MASK; - u32 trace_nr, copy_len; - u64 *ips; + const u64 *ips; + u32 copy_len; - trace_nr = trace->nr - skip; + trace_nr = trace_nr - skip; copy_len = trace_nr * elem_size; ips = trace->ip + skip; @@ -706,14 +704,20 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task, crosstask, false); } - if (unlikely(!trace) || trace->nr < skip) { - if (may_fault) - rcu_read_unlock(); - preempt_enable(); - goto err_fault; - } + if (unlikely(!trace)) + goto err_unlock; - trace_nr = callchain_store(trace, buf, elem_size, flags); + /* + * trace->nr can be above max_depth. The per-CPU entry is released + * already: a tracing program or an NMI which takes a callchain in the + * same context before the copy below reuses it. And the unwinders of + * PowerPC store context markers on top of max_depth. + */ + trace_nr = min_t(u32, READ_ONCE(trace->nr), max_depth); + if (trace_nr < skip) + goto err_unlock; + + trace_nr = callchain_store(trace, trace_nr, buf, elem_size, flags); /* trace should not be dereferenced after this point */ if (may_fault) @@ -722,6 +726,10 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task, return callchain_finalize(buf, size, trace_nr, elem_size, flags, may_fault); +err_unlock: + if (may_fault) + rcu_read_unlock(); + preempt_enable(); err_fault: err = -EFAULT; clear: @@ -817,8 +825,8 @@ const struct bpf_func_proto bpf_get_task_stack_sleepable_proto = { .arg4_type = ARG_ANYTHING, }; -static int __bpf_get_stack_pe(struct perf_callchain_entry *trace, void *buf, u32 size, - u64 flags) +static int __bpf_get_stack_pe(const struct perf_callchain_entry *trace, u32 trace_nr, + void *buf, u32 size, u64 flags) { bool user_build_id = flags & BPF_F_USER_BUILD_ID; u64 skip = flags & BPF_F_SKIP_FIELD_MASK; @@ -834,12 +842,12 @@ static int __bpf_get_stack_pe(struct perf_callchain_entry *trace, void *buf, u32 return -EINVAL; max_depth = stack_map_calculate_max_depth(size, elem_size, flags); - trace->nr = min_t(u32, trace->nr, max_depth); + trace_nr = min_t(u32, trace_nr, max_depth); - if (trace->nr < skip) + if (trace_nr < skip) return -EFAULT; - nr_trace = callchain_store(trace, buf, elem_size, flags); + nr_trace = callchain_store(trace, trace_nr, buf, elem_size, flags); return callchain_finalize(buf, size, nr_trace, elem_size, flags, false /* !may_fault */); } @@ -847,8 +855,8 @@ BPF_CALL_4(bpf_get_stack_pe, struct bpf_perf_event_data_kern *, ctx, void *, buf, u32, size, u64, flags) { struct pt_regs *regs = (struct pt_regs *)(ctx->regs); + const struct perf_callchain_entry *trace; struct perf_event *event = ctx->event; - struct perf_callchain_entry *trace; bool kernel, user; int err = -EINVAL; __u64 nr_kernel; @@ -871,13 +879,7 @@ BPF_CALL_4(bpf_get_stack_pe, struct bpf_perf_event_data_kern *, ctx, nr_kernel = count_kernel_ip(trace); if (kernel) { - __u64 nr = trace->nr; - - trace->nr = nr_kernel; - err = __bpf_get_stack_pe(trace, buf, size, flags); - - /* restore nr */ - trace->nr = nr; + err = __bpf_get_stack_pe(trace, nr_kernel, buf, size, flags); } else { /* user */ u64 skip = flags & BPF_F_SKIP_FIELD_MASK; @@ -885,7 +887,7 @@ BPF_CALL_4(bpf_get_stack_pe, struct bpf_perf_event_data_kern *, ctx, if (skip > BPF_F_SKIP_FIELD_MASK) goto clear; flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip; - err = __bpf_get_stack_pe(trace, buf, size, flags); + err = __bpf_get_stack_pe(trace, trace->nr, buf, size, flags); } clear: diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c index 79668e844141..a076c1bc41ac 100644 --- a/kernel/bpf/syscall.c +++ b/kernel/bpf/syscall.c @@ -2403,7 +2403,7 @@ static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred) btf_put(prog->aux->attach_btf); if (deferred) { - if (prog->sleepable) + if (bpf_prog_runs_sleepable(prog)) call_rcu_tasks_trace(&prog->aux->rcu, __bpf_prog_put_rcu); else call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu); @@ -6124,7 +6124,7 @@ static int bpf_prog_bind_map(union bpf_attr *attr) /* The bpf program will not access the bpf map, but for the sake of * simplicity, increase sleepable_refcnt for sleepable program as well. */ - if (prog->sleepable) + if (bpf_prog_runs_sleepable(prog)) atomic64_inc(&map->sleepable_refcnt); memcpy(used_maps_new, used_maps_old, sizeof(used_maps_old[0]) * prog->aux->used_map_cnt); diff --git a/kernel/bpf/trampoline.c b/kernel/bpf/trampoline.c index ccb943b7ac2c..98704c030a20 100644 --- a/kernel/bpf/trampoline.c +++ b/kernel/bpf/trampoline.c @@ -532,7 +532,7 @@ static enum bpf_tramp_prog_type bpf_attach_type_to_tramp(struct bpf_prog *prog) } } -static int bpf_freplace_check_tgt_prog(struct bpf_prog *tgt_prog) +static int bpf_freplace_link_tgt_prog(struct bpf_prog *tgt_prog) { struct bpf_prog_aux *aux = tgt_prog->aux; @@ -546,7 +546,7 @@ static int bpf_freplace_check_tgt_prog(struct bpf_prog *tgt_prog) */ return -EBUSY; - aux->is_extended = true; + aux->freplace_link_cnt++; return 0; } @@ -573,12 +573,19 @@ static int __bpf_trampoline_link_prog(struct bpf_tramp_link *link, /* Cannot attach extension if fentry/fexit are in use. */ if (cnt) return -EBUSY; - err = bpf_freplace_check_tgt_prog(tgt_prog); + err = bpf_freplace_link_tgt_prog(tgt_prog); if (err) return err; + err = bpf_arch_text_poke(tr->func.addr, BPF_MOD_JUMP, NULL, + link->link.prog->bpf_func); + if (err) { + /* Undo the claim from bpf_freplace_link_tgt_prog(). */ + guard(mutex)(&tgt_prog->aux->ext_mutex); + tgt_prog->aux->freplace_link_cnt--; + return err; + } tr->extension_prog = link->link.prog; - return bpf_arch_text_poke(tr->func.addr, BPF_MOD_JUMP, NULL, - link->link.prog->bpf_func); + return 0; } if (cnt >= BPF_MAX_TRAMP_LINKS) return -E2BIG; @@ -628,7 +635,7 @@ static int __bpf_trampoline_unlink_prog(struct bpf_tramp_link *link, tr->extension_prog->bpf_func, NULL); tr->extension_prog = NULL; guard(mutex)(&tgt_prog->aux->ext_mutex); - tgt_prog->aux->is_extended = false; + tgt_prog->aux->freplace_link_cnt--; return err; } hlist_del_init(&link->tramp_hlist); diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 139671b393a0..a004c9596963 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -573,6 +573,19 @@ static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn return false; } +/* From here on the maps of the program count it as a sleepable user. */ +static void mark_sleepable_async_cb(struct bpf_verifier_env *env) +{ + int i; + + if (bpf_prog_runs_sleepable(env->prog)) + return; + + env->prog->aux->sleepable_async_cb = true; + for (i = 0; i < env->used_map_cnt; i++) + atomic64_inc(&env->used_maps[i]->sleepable_refcnt); +} + static bool is_may_goto_insn(struct bpf_insn *insn) { return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; @@ -5230,7 +5243,6 @@ static int check_stack_write_fixed_off(struct bpf_verifier_env *env, bpf_mark_stack_write(env, state->frameno, BIT(spi)); } - check_fastcall_stack_contract(env, state, insn_idx, off); mark_stack_slot_scratched(env, spi); if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { bool reg_value_fits; @@ -5349,7 +5361,6 @@ static int check_stack_write_var_off(struct bpf_verifier_env *env, return err; } - check_fastcall_stack_contract(env, state, insn_idx, min_off); /* Variable offset writes destroy any spilled pointers in range. */ for (i = min_off; i < max_off; i++) { u8 new_type, *stype; @@ -5493,7 +5504,6 @@ static int check_stack_read_fixed_off(struct bpf_verifier_env *env, reg = ®_state->stack[spi].spilled_ptr; mark_stack_slot_scratched(env, spi); - check_fastcall_stack_contract(env, state, env->insn_idx, off); err = bpf_mark_stack_read(env, reg_state->frameno, env->insn_idx, BIT(spi)); if (err) return err; @@ -5511,11 +5521,11 @@ static int check_stack_read_fixed_off(struct bpf_verifier_env *env, return -EACCES; } - if (dst_regno < 0) - return 0; - if (size <= spill_size && bpf_stack_narrow_access_ok(off, size, spill_size)) { + if (dst_regno < 0) + return 0; + /* The earlier check_reg_arg() has decided the * subreg_def for this insn. Save it first. */ @@ -5551,6 +5561,9 @@ static int check_stack_read_fixed_off(struct bpf_verifier_env *env, return -EACCES; } + if (dst_regno < 0) + return 0; + if (spill_cnt == size && tnum_is_const(reg->var_off) && reg->var_off.value == 0) { __mark_reg_const_zero(env, &state->regs[dst_regno]); @@ -5652,7 +5665,6 @@ static int check_stack_read_var_off(struct bpf_verifier_env *env, min_off = reg->smin_value + off; max_off = reg->smax_value + off; mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); - check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); return 0; } @@ -7688,6 +7700,15 @@ static int check_stack_access_within_bounds( return err; } + /* + * Every stack access passes through here, including buffers passed to + * helpers and kfuncs and accesses into a caller's frame, so check the + * fastcall contract of the frame that owns the slots once for all of + * them. Zero-sized accesses touch no stack and keep the rewrite enabled. + */ + if (access_size) + check_fastcall_stack_contract(env, state, env->insn_idx, min_off); + /* Note that there is no stack access with offset zero, so the needed stack * size is -min_off, not -min_off+1. */ @@ -8310,7 +8331,12 @@ static int check_stack_range_initialized( goto mark; } - if (is_spilled_reg(&state->stack[spi]) && + /* + * Only the bytes marked STACK_SPILL hold the spilled register. + * The rest of a narrowly spilled slot keeps its previous type + * and must be initialized on its own. + */ + if (*stype == STACK_SPILL && (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || env->allow_ptr_leaks)) { if (clobber) { @@ -10878,8 +10904,10 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins is_async_cb_sleepable(env, insn)); if (IS_ERR(async_cb)) return PTR_ERR(async_cb); + if (is_async_cb_sleepable(env, insn)) + mark_sleepable_async_cb(env); callee = async_cb->frame[0]; - callee->async_entry_cnt = caller->async_entry_cnt + 1; + callee->async_entry_cnt = state->frame[0]->async_entry_cnt + 1; /* Convert bpf_timer_set_callback() args into timer callback args */ err = set_callee_state_cb(env, caller, callee, insn_idx); @@ -18443,7 +18471,9 @@ static int visit_insn(int t, struct bpf_verifier_env *env) */ if (ret == 0 && fp->might_sleep) mark_subprog_might_sleep(env, t); - if (bpf_helper_changes_pkt_data(insn->imm)) + /* nobody knows yet whether the dynptr is that of an skb */ + if (bpf_helper_changes_pkt_data(insn->imm) || + insn->imm == BPF_FUNC_dynptr_write) mark_subprog_changes_pkt_data(env, t); } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { struct bpf_kfunc_call_arg_meta meta; @@ -20012,10 +20042,10 @@ static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) continue; if (sl->state.branches) { - struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; + struct bpf_func_state *frame = sl->state.frame[0]; if (frame->in_async_callback_fn && - frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { + frame->async_entry_cnt != cur->frame[0]->async_entry_cnt) { /* Different async_entry_cnt means that the verifier is * processing another entry into async callback. * Seeing the same state is not an indication of infinite @@ -20067,8 +20097,9 @@ static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) */ if (is_iter_next_insn(env, insn_idx)) { if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { - struct bpf_func_state *cur_frame; + struct bpf_func_state *cur_frame, *old_frame; struct bpf_reg_state *iter_state, *iter_reg; + struct bpf_reg_state *old_iter; int spi; cur_frame = cur->frame[cur->curframe]; @@ -20082,7 +20113,16 @@ static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) */ spi = __get_spi(iter_reg->off + iter_reg->var_off.value); iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; - if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { + old_frame = sl->state.frame[iter_reg->frameno]; + old_iter = &old_frame->stack[spi].spilled_ptr; + /* + * states_equal() matches ids through idmap. + * The loop converged only if it's the same + * iterator. The one that was destroyed and + * created again starts from the beginning. + */ + if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE && + iter_state->ref_obj_id == old_iter->ref_obj_id) { loop = true; goto hit; } @@ -21163,7 +21203,7 @@ static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map) if (err) return err; - if (env->prog->sleepable) + if (bpf_prog_runs_sleepable(env->prog)) atomic64_inc(&map->sleepable_refcnt); /* hold the map. If the program is rejected by verifier, @@ -21466,6 +21506,44 @@ static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 of return new_prog; } +/* + * insn was moved down by delta insns inside its own patch. Operands relative + * to the pc that point in front of the old position did not move with it. + */ +static int bpf_adj_moved_insn(struct bpf_insn *insn, u32 delta) +{ + u8 class = BPF_CLASS(insn->code), op = BPF_OP(insn->code); + s64 off = insn->imm, off_min = S32_MIN; + bool is_imm = true; + + if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) { + /* subprog that started at the old position starts with the patch */ + if (off >= 0) + return 0; + } else if ((class == BPF_JMP || class == BPF_JMP32) && + op != BPF_CALL && op != BPF_EXIT) { + if (insn->code != (BPF_JMP32 | BPF_JA)) { + off = insn->off; + off_min = S16_MIN; + is_imm = false; + } + /* jump to itself stays */ + if (off >= -1) + return 0; + } else { + return 0; + } + + off -= delta; + if (off < off_min) + return -ERANGE; + if (is_imm) + insn->imm = off; + else + insn->off = off; + return 0; +} + /* * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the * jump offset by 'delta'. @@ -21547,6 +21625,9 @@ static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, * in adjust_btf_func() - no need to adjust */ } + /* The exception callback is live, so it cannot sit inside the removed range. */ + if (env->exception_callback_subprog >= j) + env->exception_callback_subprog -= j - i; } else { /* convert i from "first prog to remove" to "first to adjust" */ if (env->subprog_info[i].start == off) @@ -21957,7 +22038,13 @@ static int convert_ctx_accesses(struct bpf_verifier_env *env) struct bpf_insn *patch = insn_buf; *patch++ = BPF_ST_NOSPEC(); - *patch++ = *insn; + *patch = *insn; + ret = bpf_adj_moved_insn(patch++, 1); + if (ret) { + verbose(env, "insn %d cannot be patched due to 16-bit range\n", + env->insn_aux_data[i + delta].orig_idx); + return ret; + } cnt = patch - insn_buf; new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) @@ -22686,6 +22773,30 @@ static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *pat return 0; } +/* + * Expand may_goto: load the count from the stack, jump to the target of + * may_goto when it is zero, then the tail that updates the count. + * Use gotol when the target is too far for 16-bit offset of a conditional jump. + */ +static int may_goto_expand(struct bpf_insn *insn_buf, int off, int stack_off, + const struct bpf_insn *tail, int tail_cnt) +{ + int cnt = 0; + + /* Forward jump has to step over the tail */ + off = off >= 0 ? off + tail_cnt : off - 1; + + insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off); + if (off == (s16)off) { + insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, off); + } else { + insn_buf[cnt++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 1); + insn_buf[cnt++] = BPF_JMP32_A(off >= 0 ? off : off - 1); + } + memcpy(insn_buf + cnt, tail, tail_cnt * sizeof(*tail)); + return cnt + tail_cnt; +} + /* Do various post-verification rewrites in a single program pass. * These rewrites simplify JIT and interpreter implementations. */ @@ -22966,6 +23077,18 @@ static int do_misc_fixups(struct bpf_verifier_env *env) if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) { int stack_off_cnt = -stack_depth - 16; + /* + * AX is used as an argument to pass in stack_off_cnt + * (to add to r10/fp), and also as the return value of + * the call to arch_bpf_timed_may_goto. + */ + struct bpf_insn tail[] = { + BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1), + BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2), + BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt), + BPF_EMIT_CALL(arch_bpf_timed_may_goto), + BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt), + }; /* * Two 8 byte slots, depth-16 stores the count, and @@ -22982,22 +23105,8 @@ static int do_misc_fixups(struct bpf_verifier_env *env) * after subtraction, rinse and repeat. */ stack_depth_extra = 16; - insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt); - if (insn->off >= 0) - insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5); - else - insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1); - insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); - insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2); - /* - * AX is used as an argument to pass in stack_off_cnt - * (to add to r10/fp), and also as the return value of - * the call to arch_bpf_timed_may_goto. - */ - insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt); - insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto); - insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt); - cnt = 7; + cnt = may_goto_expand(insn_buf, insn->off, stack_off_cnt, + tail, ARRAY_SIZE(tail)); new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) @@ -23009,16 +23118,14 @@ static int do_misc_fixups(struct bpf_verifier_env *env) goto next_insn; } else if (is_may_goto_insn(insn)) { int stack_off = -stack_depth - 8; + struct bpf_insn tail[] = { + BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1), + BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off), + }; stack_depth_extra = 8; - insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off); - if (insn->off >= 0) - insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2); - else - insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1); - insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); - insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off); - cnt = 4; + cnt = may_goto_expand(insn_buf, insn->off, stack_off, + tail, ARRAY_SIZE(tail)); new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) @@ -23071,6 +23178,10 @@ static int do_misc_fixups(struct bpf_verifier_env *env) if (!allow_tail_call_in_subprogs(env)) prog->aux->stack_depth = MAX_BPF_STACK; prog->aux->max_pkt_offset = MAX_PACKET_OFF; + prog->aux->max_rdonly_access = U32_MAX; + prog->aux->max_rdwr_access = U32_MAX; + if (prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE) + prog->aux->max_tp_access = U32_MAX; /* mark bpf_tail_call as different opcode to avoid * conditional branch in the interpreter for every normal @@ -23364,7 +23475,7 @@ static int do_misc_fixups(struct bpf_verifier_env *env) /* Load nr_args from ctx - 8 */ insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); - insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); + insn_buf[2] = BPF_ALU32_IMM(BPF_LSH, BPF_REG_2, 3); insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); @@ -23571,7 +23682,14 @@ static int do_misc_fixups(struct bpf_verifier_env *env) BPF_MAX_LOOPS); } /* Copy first actual insn to preserve it */ - insn_buf[cnt++] = env->prog->insnsi[subprog_start]; + insn_buf[cnt] = env->prog->insnsi[subprog_start]; + ret = bpf_adj_moved_insn(&insn_buf[cnt], cnt); + if (ret) { + verbose(env, "insn %d cannot be patched due to 16-bit range\n", + env->insn_aux_data[subprog_start].orig_idx); + return ret; + } + cnt++; new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt); if (!new_prog) @@ -23888,8 +24006,12 @@ static int do_check_common(struct bpf_verifier_env *env, int subprog) reg->type = SCALAR_VALUE; mark_reg_unknown(env, regs, i); } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { - /* assume unspecial LOCAL dynptr type */ - __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); + /* + * The callers may hand in a dynptr of any type. + * Take it for that of an skb, so that a write + * through it and its slices are treated with care. + */ + __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_SKB, true, ++env->id_gen); } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { reg->type = PTR_TO_MEM; reg->type |= arg->arg_type & diff --git a/kernel/cgroup/cpuset-internal.h b/kernel/cgroup/cpuset-internal.h index 0eb9ebd4fcb9..89acf907e735 100644 --- a/kernel/cgroup/cpuset-internal.h +++ b/kernel/cgroup/cpuset-internal.h @@ -161,6 +161,11 @@ struct cpuset { /* partition root state */ int partition_root_state; + /* + * Set to true when a remote partition is undergoing update. + */ + bool remote_partition_updating; + /* * number of SCHED_DEADLINE tasks attached to this cpuset, so that we * know when to rebuild associated root domain bandwidth information. diff --git a/kernel/cgroup/cpuset.c b/kernel/cgroup/cpuset.c index e90fb48cf0f9..9bd1753dbcbe 100644 --- a/kernel/cgroup/cpuset.c +++ b/kernel/cgroup/cpuset.c @@ -170,15 +170,6 @@ static inline bool cs_is_member(const struct cpuset *cs) return cs->partition_root_state == PRS_MEMBER; } -/* - * Callers should hold callback_lock to modify partition_root_state. - */ -static inline void make_partition_invalid(struct cpuset *cs) -{ - if (cs->partition_root_state > 0) - cs->partition_root_state = -cs->partition_root_state; -} - /* * Send notification event of whenever partition_root_state changes. */ @@ -1348,6 +1339,16 @@ static void reset_partition_data(struct cpuset *cs) cpumask_copy(cs->effective_cpus, parent->effective_cpus); } +static inline bool is_remote_partition(struct cpuset *cs) +{ + return !list_empty(&cs->remote_sibling); +} + +static inline bool is_local_partition(struct cpuset *cs) +{ + return is_partition_valid(cs) && !is_remote_partition(cs); +} + /* * isolated_cpus_update - Update the isolated_cpus mask * @old_prs: old partition_root_state @@ -1363,6 +1364,45 @@ static void isolated_cpus_update(int old_prs, int new_prs, struct cpumask *xcpus cpumask_andnot(isolated_cpus, isolated_cpus, xcpus); } +/* + * isolated_cpus_release - Remove the relevant CPUs in @xcpus from isolated_cpus + * @cs: the current cpuset + * @xcpus: the set of effective xcpus to be considered for removal + * + * This function is called when an isolated partition is invalidated or when + * some of its effective xcpus are to be removed from isolated_cpus due to + * changes in parent cpuset. The given @xcpus must be modifiable as the function + * will update its value to determine the right set of CPUs to be removed. + */ +static void isolated_cpus_release(struct cpuset *cs, struct cpumask *xcpus) +{ + struct cpuset *ancestor = parent_cs(cs); + struct cpuset *iancestor = NULL; + + /* + * Search the furthest isolated partition root ancestor available + * until top_cpuset or a remote partition root is hit. + */ + for (; ancestor; ancestor = parent_cs(ancestor)) { + if (ancestor->partition_root_state == PRS_ISOLATED) + iancestor = ancestor; + if (is_remote_partition(ancestor)) + break; + } + + /* + * If a furthest isolated partition acnestor is found, use it to + * determine which of the CPUs in @xcpus should be removed from + * isolated_cpus. Otherwise, all of them will be removed. + */ + if (iancestor && !cpumask_andnot(xcpus, xcpus, iancestor->effective_xcpus)) + return; /* No CPU should be removed from isolated_cpus */ + + spin_lock_irq(&callback_lock); + isolated_cpus_update(PRS_ISOLATED, PRS_ROOT, xcpus); + spin_unlock_irq(&callback_lock); +} + /* * partition_xcpus_add - Add new exclusive CPUs to partition * @new_prs: new partition_root_state @@ -1428,64 +1468,98 @@ static bool partition_xcpus_del(int old_prs, struct cpuset *parent, } /* - * isolated_cpus_can_update - check for isolated & nohz_full conflicts - * @add_cpus: cpu mask for cpus that are going to be isolated - * @del_cpus: cpu mask for cpus that are no longer isolated, can be NULL - * Return: false if there is conflict, true otherwise - * - * If nohz_full is enabled and we have isolated CPUs, their combination must - * still leave housekeeping CPUs. + * prstate_housekeeping_conflict - check for partition & housekeeping conflicts + * @new_prs: new partition root state to be checked + * @parent_prs: Parent partition root state + * @new_cpus: the set of new effective xcpus in the current cpuset + * @del_cpus: old CPUs going to be removed from current cpuset, can be NULL + * Return: true if there is conflict, false otherwise * - * TBD: Should consider merging this function into - * prstate_housekeeping_conflict(). + * There are two different housekeeping conflicts to be checked: + * 1) If new_prs is PRS_ROOT, none of the @new_cpus can be a boot-time isolated + * CPU. IOW, the whole @new_cpus must be a subset of boot_hk_cpus. + * 2) If nohz_full is enabled and we have isolated CPUs, their combination must + * still leave housekeeping CPUs. This check is only needed if new_prs + * differs from parent_prs and one of them is PRS_ISOLATED. */ -static bool isolated_cpus_can_update(struct cpumask *add_cpus, - struct cpumask *del_cpus) +static bool prstate_housekeeping_conflict(int new_prs, int parent_prs, + struct cpumask *new_cpus, + struct cpumask *del_cpus) { cpumask_var_t full_hk_cpus; - int res = true; + int res; - if (!housekeeping_enabled(HK_TYPE_KERNEL_NOISE)) - return true; + WARN_ON_ONCE(parent_prs <= 0); + if (!new_prs) + return false; + + /* + * For a currently invalid partition root state, do the check assuming + * that it may be converted back to valid. + * + * There are code paths where an invalid partition may be reverted back + * to a valid partition but we still need to run the housekeeping check + * before the conversion happens to make sure the switch is valid. We + * can either do the negative to positive PRS switch individually in all + * these code paths or do it here which I think will make the code a bit + * easier to read. + */ + if (new_prs < 0) + new_prs = -new_prs; - if (del_cpus && cpumask_weight_and(del_cpus, - housekeeping_cpumask(HK_TYPE_KERNEL_NOISE))) + if (have_boot_isolcpus && (new_prs == PRS_ROOT) && + !cpumask_subset(new_cpus, boot_hk_cpus)) return true; - if (!alloc_cpumask_var(&full_hk_cpus, GFP_KERNEL)) + if (del_cpus && cpumask_empty(del_cpus)) + del_cpus = NULL; + + /* + * Exit 2nd check early and return false if + * 1) there is no boot time isolated nohz_full CPU + * 2) parent and child has the same partition state + * 3) new_prs is PRS_ROOT, parent_prs is PRS_ISOLATED and no CPU will + * be returned back to the parent. + */ + if (!housekeeping_enabled(HK_TYPE_KERNEL_NOISE) || + (new_prs == parent_prs) || (!del_cpus && (new_prs == PRS_ROOT))) return false; + /* + * Now make sure that @new_cpus contains new CPUs to be isolated and + * @del_cpus contains isolated CPUs to be un-isolated. + * With the guards above, @new_cpus can't be NULL after the swap. + */ + if (parent_prs == PRS_ISOLATED) + swap(new_cpus, del_cpus); + + if (!alloc_cpumask_var(&full_hk_cpus, GFP_KERNEL)) + return true; + + /* + * Check if del_cpus may contain a CPU that can become an active + * housekeeping CPU again. + */ + if (del_cpus) { + cpumask_and(full_hk_cpus, housekeeping_cpumask(HK_TYPE_KERNEL_NOISE), + have_boot_isolcpus ? boot_hk_cpus : cpu_possible_mask); + if (cpumask_first_and_and(del_cpus, full_hk_cpus, + cpu_active_mask) < nr_cpu_ids) { + res = false; + goto out; + } + } + cpumask_and(full_hk_cpus, housekeeping_cpumask(HK_TYPE_KERNEL_NOISE), housekeeping_cpumask(HK_TYPE_DOMAIN)); cpumask_andnot(full_hk_cpus, full_hk_cpus, isolated_cpus); cpumask_and(full_hk_cpus, full_hk_cpus, cpu_active_mask); - if (!cpumask_weight_andnot(full_hk_cpus, add_cpus)) - res = false; - + res = !cpumask_weight_andnot(full_hk_cpus, new_cpus); +out: free_cpumask_var(full_hk_cpus); return res; } -/* - * prstate_housekeeping_conflict - check for partition & housekeeping conflicts - * @prstate: partition root state to be checked - * @new_cpus: cpu mask - * Return: true if there is conflict, false otherwise - * - * CPUs outside of boot_hk_cpus, if defined, can only be used in an - * isolated partition. - */ -static bool prstate_housekeeping_conflict(int prstate, struct cpumask *new_cpus) -{ - if (!have_boot_isolcpus) - return false; - - if ((prstate != PRS_ISOLATED) && !cpumask_subset(new_cpus, boot_hk_cpus)) - return true; - - return false; -} - static void update_isolation_cpumasks(bool isolcpus_updated) { int ret; @@ -1598,16 +1672,6 @@ static int compute_trialcs_excpus(struct cpuset *trialcs, struct cpuset *cs) return rm_siblings_excl_cpus(parent, cs, excpus); } -static inline bool is_remote_partition(struct cpuset *cs) -{ - return !list_empty(&cs->remote_sibling); -} - -static inline bool is_local_partition(struct cpuset *cs) -{ - return is_partition_valid(cs) && !is_remote_partition(cs); -} - /* * remote_partition_enable - Enable current cpuset as a remote partition root * @cs: the cpuset to update @@ -1645,9 +1709,7 @@ static int remote_partition_enable(struct cpuset *cs, int new_prs, return PERR_INVCPUS; if (cpumask_intersects(tmp->new_cpus, subpartitions_cpus)) return PERR_NOCPUS; - if (((new_prs == PRS_ISOLATED) && - !isolated_cpus_can_update(tmp->new_cpus, NULL)) || - prstate_housekeeping_conflict(new_prs, tmp->new_cpus)) + if (prstate_housekeeping_conflict(new_prs, PRS_ROOT, tmp->new_cpus, NULL)) return PERR_HKEEPING; spin_lock_irq(&callback_lock); @@ -1755,13 +1817,14 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus, else if (cpumask_intersects(tmp->addmask, subpartitions_cpus) || cpumask_subset(top_cpuset.effective_cpus, tmp->addmask)) WRITE_ONCE(cs->prs_err, PERR_NOCPUS); - else if ((prs == PRS_ISOLATED) && - !isolated_cpus_can_update(tmp->addmask, tmp->delmask)) + else if (prstate_housekeeping_conflict(prs, PRS_ROOT, + excpus, tmp->delmask)) WRITE_ONCE(cs->prs_err, PERR_HKEEPING); if (cs->prs_err) goto invalidate; } + cs->remote_partition_updating = true; spin_lock_irq(&callback_lock); if (adding) isolcpus_updated += partition_xcpus_add(prs, NULL, tmp->addmask); @@ -1784,6 +1847,7 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus, */ cpuset_update_tasks_cpumask(&top_cpuset, tmp->new_cpus); update_sibling_cpumasks(&top_cpuset, NULL, tmp); + cs->remote_partition_updating = false; return; invalidate: @@ -1794,7 +1858,7 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus, * update_parent_effective_cpumask - update effective_cpus mask of parent cpuset * @cs: The cpuset that requests change in partition root state * @cmd: Partition root state change command - * @newmask: Optional new cpumask for partcmd_update + * @newmask: Optional new effective xcpus for partcmd_update * @tmp: Temporary addmask and delmask * Return: 0 or a partition root state error code * @@ -1809,11 +1873,11 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus, * given back to parent's effective_cpus. 0 will always be returned. * * For partcmd_update, if the optional newmask is specified, the cpu list is - * to be changed from effective_xcpus to newmask. Otherwise, effective_xcpus is - * assumed to remain the same. The cpuset should either be a valid or invalid - * partition root. The partition root state may change from valid to invalid - * or vice versa. An error code will be returned if transitioning from - * invalid to valid violates the exclusivity rule. + * to be changed from effective_xcpus to newmask. Otherwise, effective_xcpus + * will be computed and a valid partition will be invalidated if it is the new + * cpumask is empty. The cpuset should either be a valid or invalid partition + * root. The partition root state may change from valid to invalid or vice + * versa. * * For partcmd_invalidate, the current partition will be made invalid. * @@ -1881,34 +1945,30 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd, if (!newmask && xcpus_empty(cs)) return PERR_CPUSEMPTY; - nocpu = tasks_nocpu_error(parent, cs, xcpus); + /* + * Except for partcmd_disable and non-NULL newmask, use delmask + * to compute the current effective xcpus value and use it for + * tasks_nocpu_error check. + */ + if ((cmd != partcmd_disable) && !newmask) { + compute_excpus(cs, tmp->delmask); + nocpu = tasks_nocpu_error(parent, cs, tmp->delmask); + } if ((cmd == partcmd_enable) || (cmd == partcmd_enablei)) { - /* - * Need to call compute_excpus() in case - * exclusive_cpus not set. Sibling conflict should only happen - * if exclusive_cpus isn't set. - */ - xcpus = tmp->delmask; - if (compute_excpus(cs, xcpus)) - WARN_ON_ONCE(!cpumask_empty(cs->exclusive_cpus)); new_prs = (cmd == partcmd_enable) ? PRS_ROOT : PRS_ISOLATED; /* * Enabling partition root is not allowed if its * effective_xcpus is empty. */ - if (cpumask_empty(xcpus)) + if (cpumask_empty(tmp->delmask)) return PERR_INVCPUS; - if (prstate_housekeeping_conflict(new_prs, xcpus)) - return PERR_HKEEPING; - - if ((new_prs == PRS_ISOLATED) && (new_prs != parent_prs) && - !isolated_cpus_can_update(xcpus, NULL)) + if (prstate_housekeeping_conflict(new_prs, parent_prs, tmp->delmask, NULL)) return PERR_HKEEPING; - if (tasks_nocpu_error(parent, cs, xcpus)) + if (nocpu) return PERR_NOCPUS; /* @@ -1920,17 +1980,15 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd, * * Warn if it is not the case. */ - cpumask_and(tmp->new_cpus, xcpus, cpu_active_mask); + cpumask_and(tmp->new_cpus, tmp->delmask, cpu_active_mask); WARN_ON_ONCE(!cpumask_subset(tmp->new_cpus, parent->effective_cpus)); - deleting = true; subparts_delta++; } else if (cmd == partcmd_disable) { /* * May need to add cpus back to parent's effective_cpus * (and maybe removed from subpartitions_cpus/isolated_cpus) - * for valid partition root. xcpus may contain CPUs that - * shouldn't be removed from the two global cpumasks. + * for valid partition root. */ if (is_partition_valid(cs)) { cpumask_copy(tmp->addmask, cs->effective_xcpus); @@ -1947,8 +2005,8 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd, goto write_error; } - /* Check newmask again, whether cpus are available for parent/cs */ - nocpu |= tasks_nocpu_error(parent, cs, newmask); + /* Check newmask whether cpus are available for parent/cs */ + nocpu = tasks_nocpu_error(parent, cs, newmask); /* * partcmd_update with newmask: @@ -1979,22 +2037,6 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd, parent->effective_xcpus); } - /* - * TBD: Invalidate a currently valid child root partition may - * still break isolated_cpus_can_update() rule if parent is an - * isolated partition. - */ - if (is_partition_valid(cs) && (old_prs != parent_prs)) { - if ((parent_prs == PRS_ROOT) && - /* Adding to parent means removing isolated CPUs */ - !isolated_cpus_can_update(tmp->delmask, tmp->addmask)) - part_error = PERR_HKEEPING; - if ((parent_prs == PRS_ISOLATED) && - /* Adding to parent means adding isolated CPUs */ - !isolated_cpus_can_update(tmp->addmask, tmp->delmask)) - part_error = PERR_HKEEPING; - } - /* * The new CPUs to be removed from parent's effective CPUs * must be present. @@ -2019,7 +2061,7 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd, /* * partcmd_update w/o newmask * - * delmask = effective_xcpus & parent->effective_cpus + * delmask = newly computed effective xcpus value * * This can be called from: * 1) update_cpumasks_hier() @@ -2030,38 +2072,64 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd, * * A partition error happens when parent has tasks and all * its effective CPUs will have to be distributed out. + * + * For an isolated partition with a shrunk root partition parent + * we may need to return some or all of its isolated CPUs. */ + nocpu |= cpumask_empty(tmp->delmask); + if ((parent_prs == PRS_ROOT) && (old_prs == PRS_ISOLATED)) { + cpumask_clear(tmp->addmask); + if (nocpu) + cpumask_copy(tmp->addmask, cs->effective_xcpus); + else if (!cpumask_subset(cs->effective_xcpus, parent->effective_xcpus)) + cpumask_andnot(tmp->addmask, cs->effective_xcpus, + parent->effective_xcpus); + if (!cpumask_empty(tmp->addmask)) + isolated_cpus_release(cs, tmp->addmask); + } if (nocpu) { part_error = PERR_NOCPUS; if (is_partition_valid(cs)) adding = cpumask_and(tmp->addmask, xcpus, parent->effective_xcpus); - } else if (is_partition_invalid(cs) && !cpumask_empty(xcpus) && - cpumask_subset(xcpus, parent->effective_xcpus)) { + } else if (is_partition_invalid(cs)) { struct cgroup_subsys_state *css; struct cpuset *child; bool exclusive = true; /* - * Convert invalid partition to valid has to - * pass the cpu exclusivity test. + * Convert invalid partition to valid has to pass the + * cpu exclusivity test when cpuset.cpus.exclusive is + * empty as well as the housekeeping check. */ - rcu_read_lock(); - cpuset_for_each_child(child, css, parent) { - if (child == cs) - continue; - if (!cpusets_are_exclusive(cs, child)) { - exclusive = false; - break; + if (prstate_housekeeping_conflict(cs->partition_root_state, + parent_prs, tmp->delmask, NULL)) { + part_error = PERR_HKEEPING; + goto write_error; + } + if (cpumask_empty(cs->exclusive_cpus)) { + rcu_read_lock(); + cpuset_for_each_child(child, css, parent) { + if (child == cs) + continue; + if (!cpusets_are_exclusive(cs, child)) { + exclusive = false; + break; + } } + rcu_read_unlock(); } - rcu_read_unlock(); if (exclusive) - deleting = cpumask_and(tmp->delmask, - xcpus, parent->effective_cpus); + deleting = !cpumask_empty(tmp->delmask); else part_error = PERR_NOTEXCL; } + /* + * When both cs and parent remain valid, parent's + * compute_partition_effective_cpumask() call would have removed + * cs's effective_xcpus from the parent's effective_cpus. So + * there is no need to adjust parent's effective_cpus here. + */ } write_error: @@ -2171,8 +2239,6 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd, * or update_cpumasks_hier() where parent and children are modified * successively, we don't need to call update_parent_effective_cpumask() * and the child's effective_cpus will be updated in later iterations. - * - * Note that rcu_read_lock() is assumed to be held. */ static void compute_partition_effective_cpumask(struct cpuset *cs, struct cpumask *new_ecpus) @@ -2184,15 +2250,16 @@ static void compute_partition_effective_cpumask(struct cpuset *cs, WARN_ON_ONCE(!is_partition_valid(cs)); /* - * Check child partition roots to see if they should be - * invalidated when - * 1) child effective_xcpus not a subset of new - * excluisve_cpus - * 2) All the effective_cpus will be used up and cp - * has tasks + * Check child partition roots to see if they should be invalidated + * when all the effective_cpus will be used up and cs is populated. + * It is better to sacrifice a child partition root than invalidating + * the whole subtree. + * + * Return early if the effective_cpus is already empty. */ compute_excpus(cs, new_ecpus); - cpumask_and(new_ecpus, new_ecpus, cpu_active_mask); + if (!cpumask_and(new_ecpus, new_ecpus, cpu_active_mask)) + return; rcu_read_lock(); cpuset_for_each_child(child, css, cs) { @@ -2204,22 +2271,20 @@ static void compute_partition_effective_cpumask(struct cpuset *cs, * partition root. */ WARN_ON_ONCE(is_remote_partition(child)); - WRITE_ONCE(child->prs_err, 0); - if (!cpumask_subset(child->effective_xcpus, - cs->effective_xcpus)) - WRITE_ONCE(child->prs_err, PERR_INVCPUS); - else if (populated && - cpumask_subset(new_ecpus, child->effective_xcpus)) - WRITE_ONCE(child->prs_err, PERR_NOCPUS); - - if (child->prs_err) { + if (populated && cpumask_subset(new_ecpus, child->effective_xcpus)) { int old_prs = child->partition_root_state; + int parent_prs = cs->partition_root_state; /* - * Invalidate child partition + * Invalidate child partition and update isolated_cpus + * if necessary. */ spin_lock_irq(&callback_lock); - make_partition_invalid(child); + WRITE_ONCE(child->prs_err, PERR_NOCPUS); + if ((old_prs == PRS_ISOLATED) && (parent_prs == PRS_ROOT)) + isolated_cpus_update(PRS_ISOLATED, PRS_ROOT, + child->effective_xcpus); + child->partition_root_state = -old_prs; cs->nr_subparts--; child->nr_subparts = 0; spin_unlock_irq(&callback_lock); @@ -2262,16 +2327,19 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp, old_prs = new_prs = cp->partition_root_state; /* - * For child remote partition root (!= cs), we need to call - * remote_cpus_update() if effective_xcpus will be changed. - * Otherwise, we can skip the whole subtree. + * For a child remote partition with remote_partition_updating + * set, we can skip the whole subtree as the this function will + * be called eventually. We can also skip the subtree if the + * effective_xcpus isn't going to be changed. Otherwise, we + * will have to call remote_cpus_update(). * * remote_cpus_update() will reuse tmp->new_cpus only after * its value is being processed. */ if (remote && (cp != cs)) { compute_excpus(cp, tmp->new_cpus); - if (cpumask_equal(cp->effective_xcpus, tmp->new_cpus)) { + if (cp->remote_partition_updating || + cpumask_equal(cp->effective_xcpus, tmp->new_cpus)) { pos_css = css_rightmost_descendant(pos_css); continue; } @@ -2334,7 +2402,9 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp, * cpuset if the parent's effective_cpus changes. */ if ((cp != cs) && old_prs) { - switch (parent->partition_root_state) { + int parent_prs = parent->partition_root_state; + + switch (parent_prs) { case PRS_ROOT: case PRS_ISOLATED: update_parent = true; @@ -2342,12 +2412,20 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp, default: /* - * When parent is not a partition root or is - * invalid, child partition roots become - * invalid too. + * When parent is not a valid partition root, + * child partition roots become invalid too. + * + * For a to be invalidated isolated partition, + * call return_isolated_cpus() to remove the + * relevant CPUs from isolated_cpus. */ if (is_partition_valid(cp)) - new_prs = -cp->partition_root_state; + new_prs = -old_prs; + + if (old_prs == PRS_ISOLATED) { + cpumask_copy(tmp->delmask, cp->effective_xcpus); + isolated_cpus_release(cp, tmp->delmask); + } WRITE_ONCE(cp->prs_err, is_partition_invalid(parent) ? PERR_INVPARENT : PERR_NOTPART); @@ -2512,10 +2590,6 @@ static enum prs_errcode validate_partition(struct cpuset *cs, struct cpuset *tri if (cpumask_empty(trialcs->effective_xcpus)) return PERR_INVCPUS; - if (prstate_housekeeping_conflict(trialcs->partition_root_state, - trialcs->effective_xcpus)) - return PERR_HKEEPING; - if (tasks_nocpu_error(parent, cs, trialcs->effective_xcpus)) return PERR_NOCPUS; @@ -2569,14 +2643,36 @@ static int cpus_allowed_validate_change(struct cpuset *cs, struct cpuset *trialc * CPU modifications may cause a partition to be disabled or require state updates. */ static void partition_cpus_change(struct cpuset *cs, struct cpuset *trialcs, - struct tmpmasks *tmp) + struct tmpmasks *tmp) { enum prs_errcode prs_err; + int parent_prs = is_remote_partition(cs) + ? PRS_ROOT : parent_cs(cs)->partition_root_state; if (cs_is_member(cs)) return; prs_err = validate_partition(cs, trialcs); + if (!prs_err && (parent_prs > 0) && + !cpumask_empty(trialcs->effective_xcpus)) { + int prs = cs->partition_root_state; + + /* + * Check for housekeeping conflict by passing the whole + * effective_xcpus as well as those CPUs that are to be + * removed from cs as delmask. + */ + if (prs > 0) + cpumask_andnot(tmp->delmask, cs->effective_xcpus, + trialcs->effective_xcpus); + else + cpumask_clear(tmp->delmask); + + if (prstate_housekeeping_conflict(prs, parent_prs, + trialcs->effective_xcpus, tmp->delmask)) + prs_err = PERR_HKEEPING; + } + if (prs_err) { WRITE_ONCE(cs->prs_err, prs_err); trialcs->prs_err = prs_err; @@ -3074,6 +3170,7 @@ static int update_prstate(struct cpuset *cs, int new_prs) struct cpuset *parent = parent_cs(cs); struct tmpmasks tmpmask; bool isolcpus_updated = false; + bool disable_partition = false; if (old_prs == new_prs) return 0; @@ -3126,21 +3223,29 @@ static int update_prstate(struct cpuset *cs, int new_prs) err = remote_partition_enable(cs, new_prs, &tmpmask); } } else if (old_prs && new_prs) { + int parent_prs = is_remote_partition(cs) + ? PRS_ROOT : parent->partition_root_state; + /* * A change in load balance state only, no change in cpumasks. * Need to update isolated_cpus. */ - if (((new_prs == PRS_ISOLATED) && - !isolated_cpus_can_update(cs->effective_xcpus, NULL)) || - prstate_housekeeping_conflict(new_prs, cs->effective_xcpus)) + if (prstate_housekeeping_conflict(new_prs, parent_prs, + cs->effective_xcpus, NULL)) { + disable_partition = true; err = PERR_HKEEPING; - else + } else { isolcpus_updated = true; + } } else { /* * Switching back to member is always allowed even if it * disables child partitions. */ + disable_partition = true; + } + + if (disable_partition) { if (is_remote_partition(cs)) remote_partition_disable(cs, &tmpmask); else @@ -3149,7 +3254,7 @@ static int update_prstate(struct cpuset *cs, int new_prs) /* * Invalidation of child partitions will be done in - * update_cpumasks_hier(). + * update_cpumasks_hier() below. */ } out: @@ -3172,8 +3277,8 @@ static int update_prstate(struct cpuset *cs, int new_prs) spin_unlock_irq(&callback_lock); update_isolation_cpumasks(isolcpus_updated); - /* Force update if switching back to member & update effective_xcpus */ - update_cpumasks_hier(cs, &tmpmask, !new_prs); + /* Force update if partition is disabled & update effective_xcpus */ + update_cpumasks_hier(cs, &tmpmask, disable_partition); /* A newly created partition must have effective_xcpus set */ WARN_ON_ONCE(!old_prs && (new_prs > 0) @@ -4059,10 +4164,10 @@ static void cpuset_hotplug_update_tasks(struct cpuset *cs, struct tmpmasks *tmp) partcmd = partcmd_invalidate; /* * On the other hand, an invalid partition root may be transitioned - * back to a regular one with a non-empty effective xcpus. + * back to a regular one if its effective xcpus has an active CPU. */ else if (is_partition_valid(parent) && is_partition_invalid(cs) && - !cpumask_empty(cs->effective_xcpus)) + cpumask_intersects(cs->effective_xcpus, cpu_active_mask)) partcmd = partcmd_update; if (partcmd >= 0) { diff --git a/kernel/dma/direct.c b/kernel/dma/direct.c index cc334eb94b33..11960210266f 100644 --- a/kernel/dma/direct.c +++ b/kernel/dma/direct.c @@ -181,6 +181,21 @@ static struct page *dma_direct_alloc_from_pool(struct device *dev, size_t size, return page; } +/* + * Check if the allocation can skip the kernel mapping and return the page + * pointer as the cookie. + */ +static bool dma_direct_use_no_mapping(struct device *dev, unsigned long attrs) +{ + if (!(attrs & DMA_ATTR_NO_KERNEL_MAPPING)) + return false; + if (force_dma_unencrypted(dev) || is_swiotlb_for_alloc(dev)) + return false; + if (IS_ENABLED(CONFIG_ARCH_HAS_DMA_ALLOC) && !dev_is_dma_coherent(dev)) + return false; + return true; +} + static void *dma_direct_alloc_no_mapping(struct device *dev, size_t size, dma_addr_t *dma_handle, gfp_t gfp) { @@ -210,8 +225,7 @@ void *dma_direct_alloc(struct device *dev, size_t size, if (attrs & DMA_ATTR_NO_WARN) gfp |= __GFP_NOWARN; - if ((attrs & DMA_ATTR_NO_KERNEL_MAPPING) && - !force_dma_unencrypted(dev) && !is_swiotlb_for_alloc(dev)) + if (dma_direct_use_no_mapping(dev, attrs)) return dma_direct_alloc_no_mapping(dev, size, dma_handle, gfp); if (!dev_is_dma_coherent(dev)) { @@ -314,8 +328,7 @@ void dma_direct_free(struct device *dev, size_t size, { unsigned int page_order = get_order(size); - if ((attrs & DMA_ATTR_NO_KERNEL_MAPPING) && - !force_dma_unencrypted(dev) && !is_swiotlb_for_alloc(dev)) { + if (dma_direct_use_no_mapping(dev, attrs)) { /* cpu_addr is a struct page cookie, not a kernel address */ dma_free_contiguous(dev, cpu_addr, size); return; diff --git a/kernel/events/core.c b/kernel/events/core.c index f6045a7f8328..eea5cab38bc8 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -971,8 +971,13 @@ static void perf_cgroup_switch(struct task_struct *task) * must not be done before ctxswout due * to update_cgrp_time_from_cpuctx() in * ctx_sched_out() + * + * ctx_sched_out() can consume a pending disable and drop the last cgroup + * event, which clear the cpuctx->cgrp. Cgroup tracking follow active cgroup + * event, so do not resurrect it */ - cpuctx->cgrp = cgrp; + if (cpuctx->ctx.nr_cgroups) + cpuctx->cgrp = cgrp; /* * set cgrp before ctxsw in to allow * perf_cgroup_set_timestamp() in ctx_sched_in() @@ -1231,14 +1236,19 @@ static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc) return 0; } -static int perf_mux_hrtimer_restart_ipi(void *arg) +static __always_inline struct perf_cpu_pmu_context *this_cpc(struct pmu *pmu) { - return perf_mux_hrtimer_restart(arg); + return *this_cpu_ptr(pmu->cpu_pmu_context); } -static __always_inline struct perf_cpu_pmu_context *this_cpc(struct pmu *pmu) +static int perf_mux_hrtimer_interval_ipi(void *arg) { - return *this_cpu_ptr(pmu->cpu_pmu_context); + struct pmu *pmu = arg; + struct perf_cpu_pmu_context *cpc = this_cpc(pmu); + int ms = pmu->hrtimer_interval_ms; + + cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * ms); + return perf_mux_hrtimer_restart(cpc); } void perf_pmu_disable(struct pmu *pmu) @@ -5674,6 +5684,8 @@ static void __free_event(struct perf_event *event) call_rcu(&event->rcu_head, free_event_rcu); } +static void mediated_pmu_unaccount_event(struct perf_event *event); + DEFINE_FREE(__free_event, struct perf_event *, if (_T) __free_event(_T)) /* vs perf_event_alloc() success */ @@ -5683,6 +5695,7 @@ static void _free_event(struct perf_event *event) irq_work_sync(&event->pending_disable_irq); unaccount_event(event); + mediated_pmu_unaccount_event(event); security_perf_event_free(event); @@ -6207,6 +6220,84 @@ u64 perf_event_pause(struct perf_event *event, bool reset) } EXPORT_SYMBOL_GPL(perf_event_pause); +#ifdef CONFIG_PERF_GUEST_MEDIATED_PMU +static atomic_t nr_include_guest_events __read_mostly; + +static atomic_t nr_mediated_pmu_vms __read_mostly; +static DEFINE_MUTEX(perf_mediated_pmu_mutex); + +/* !exclude_guest event of PMU with PERF_PMU_CAP_MEDIATED_VPMU */ +static inline bool is_include_guest_event(struct perf_event *event) +{ + if (!event->pmu) + return false; + + if ((event->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU) && + !event->attr.exclude_guest) + return true; + + return false; +} + +static int mediated_pmu_account_event(struct perf_event *event) +{ + if (!is_include_guest_event(event)) + return 0; + + guard(mutex)(&perf_mediated_pmu_mutex); + + if (atomic_read(&nr_mediated_pmu_vms)) + return -EOPNOTSUPP; + + atomic_inc(&nr_include_guest_events); + return 0; +} + +static void mediated_pmu_unaccount_event(struct perf_event *event) +{ + if (!is_include_guest_event(event)) + return; + + atomic_dec(&nr_include_guest_events); +} + +/* + * Currently invoked at VM creation to + * - Check whether there are existing !exclude_guest events of PMU with + * PERF_PMU_CAP_MEDIATED_VPMU + * - Set nr_mediated_pmu_vms to prevent !exclude_guest event creation on + * PMUs with PERF_PMU_CAP_MEDIATED_VPMU + * + * No impact for the PMU without PERF_PMU_CAP_MEDIATED_VPMU. The perf + * still owns all the PMU resources. + */ +int perf_create_mediated_pmu(void) +{ + guard(mutex)(&perf_mediated_pmu_mutex); + if (atomic_inc_not_zero(&nr_mediated_pmu_vms)) + return 0; + + if (atomic_read(&nr_include_guest_events)) + return -EBUSY; + + atomic_inc(&nr_mediated_pmu_vms); + return 0; +} +EXPORT_SYMBOL_GPL(perf_create_mediated_pmu); + +void perf_release_mediated_pmu(void) +{ + if (WARN_ON_ONCE(!atomic_read(&nr_mediated_pmu_vms))) + return; + + atomic_dec(&nr_mediated_pmu_vms); +} +EXPORT_SYMBOL_GPL(perf_release_mediated_pmu); +#else +static int mediated_pmu_account_event(struct perf_event *event) { return 0; } +static void mediated_pmu_unaccount_event(struct perf_event *event) {} +#endif + /* * Holding the top-level event's child_mutex means that any * descendant process that has inherited this event will block @@ -7528,24 +7619,84 @@ unsigned long perf_instruction_pointer(struct perf_event *event, 0 : perf_arch_instruction_pointer(regs); } +u64 __weak perf_reg_value(struct pt_regs *regs, int idx) +{ + return 0; +} + +int __weak perf_reg_validate(u64 mask) +{ + return mask ? -ENOSYS : 0; +} + +u64 __weak perf_reg_abi(struct task_struct *task) +{ + return PERF_SAMPLE_REGS_ABI_NONE; +} + +void __weak perf_get_regs_user(struct perf_regs *regs_user, + struct pt_regs *regs) +{ + regs_user->regs = task_pt_regs(current); + regs_user->abi = perf_reg_abi(current); +} + +#define word_for_each_set_bit(bit, val) \ + for (unsigned long long __v = (val); \ + __v && ((bit = __builtin_ctzll(__v)), 1); \ + __v &= __v - 1) + static void perf_output_sample_regs(struct perf_output_handle *handle, struct pt_regs *regs, u64 mask) { int bit; - DECLARE_BITMAP(_mask, 64); - - bitmap_from_u64(_mask, mask); - for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) { - u64 val; - val = perf_reg_value(regs, bit); + word_for_each_set_bit(bit, mask) { + u64 val = perf_reg_value(regs, bit); perf_output_put(handle, val); } } -static void perf_sample_regs_user(struct perf_regs *regs_user, - struct pt_regs *regs) +static void +perf_output_sample_simd_regs(struct perf_output_handle *handle, + struct perf_event *event, + struct pt_regs *regs, + u64 mask, u32 pred_mask) +{ + u64 pred_qwords = event->attr.sample_simd_pred_reg_qwords; + u64 vec_qwords = event->attr.sample_simd_vec_reg_qwords; + u64 nr_vectors = hweight64(mask); + u64 nr_pred = hweight32(pred_mask); + int bit; + + perf_output_put(handle, nr_vectors); + perf_output_put(handle, vec_qwords); + perf_output_put(handle, nr_pred); + perf_output_put(handle, pred_qwords); + + if (nr_vectors) { + word_for_each_set_bit(bit, mask) { + for (int i = 0; i < vec_qwords; i++) { + u64 val = perf_simd_reg_value(regs, bit, + i, false); + perf_output_put(handle, val); + } + } + } + if (nr_pred) { + word_for_each_set_bit(bit, pred_mask) { + for (int i = 0; i < pred_qwords; i++) { + u64 val = perf_simd_reg_value(regs, bit, + i, true); + perf_output_put(handle, val); + } + } + } +} + +void perf_sample_regs_user(struct perf_regs *regs_user, + struct pt_regs *regs) { if (user_mode(regs)) { regs_user->abi = perf_reg_abi(current); @@ -7558,9 +7709,9 @@ static void perf_sample_regs_user(struct perf_regs *regs_user, } } -static void perf_sample_regs_intr(struct perf_regs *regs_intr, - struct pt_regs *regs, - bool exclude_kernel) +void perf_sample_regs_intr(struct perf_regs *regs_intr, + struct pt_regs *regs, + bool exclude_kernel) { /* * Hardware skid can lead to a scenario where a PMI is @@ -7577,6 +7728,17 @@ static void perf_sample_regs_intr(struct perf_regs *regs_intr, } } +int __weak perf_simd_reg_validate(u16 vec_qwords, u64 vec_mask, + u16 pred_qwords, u32 pred_mask) +{ + return -EINVAL; +} + +u64 __weak perf_simd_reg_value(struct pt_regs *regs, int idx, + u16 qwords_idx, bool pred) +{ + return 0; +} /* * Get remaining task size from user stack pointer. @@ -8114,10 +8276,17 @@ void perf_output_sample(struct perf_output_handle *handle, perf_output_put(handle, abi); if (abi) { - u64 mask = event->attr.sample_regs_user; + struct perf_event_attr *attr = &event->attr; + u64 mask = attr->sample_regs_user; perf_output_sample_regs(handle, data->regs_user.regs, mask); + if (abi & PERF_SAMPLE_REGS_ABI_SIMD) { + perf_output_sample_simd_regs(handle, event, + data->regs_user.regs, + attr->sample_simd_vec_reg_user, + attr->sample_simd_pred_reg_user); + } } } @@ -8145,11 +8314,18 @@ void perf_output_sample(struct perf_output_handle *handle, perf_output_put(handle, abi); if (abi) { - u64 mask = event->attr.sample_regs_intr; + struct perf_event_attr *attr = &event->attr; + u64 mask = attr->sample_regs_intr; perf_output_sample_regs(handle, data->regs_intr.regs, mask); + if (abi & PERF_SAMPLE_REGS_ABI_SIMD) { + perf_output_sample_simd_regs(handle, event, + data->regs_intr.regs, + attr->sample_simd_vec_reg_intr, + attr->sample_simd_pred_reg_intr); + } } } @@ -8342,6 +8518,29 @@ static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d) return d * !!(flags & s); } +static u64 perf_update_xregs_size(struct perf_event *event, bool intr) +{ + u16 pred_qwords = event->attr.sample_simd_pred_reg_qwords; + u16 vec_qwords = event->attr.sample_simd_vec_reg_qwords; + u64 pred_mask; + u64 mask; + int size; + + if (intr) { + mask = event->attr.sample_simd_vec_reg_intr; + pred_mask = event->attr.sample_simd_pred_reg_intr; + } else { + mask = event->attr.sample_simd_vec_reg_user; + pred_mask = event->attr.sample_simd_pred_reg_user; + } + + size = sizeof(u64) * 4; + size += (hweight64(mask) * vec_qwords + + hweight64(pred_mask) * pred_qwords) * sizeof(u64); + + return size; +} + void perf_prepare_sample(struct perf_sample_data *data, struct perf_event *event, struct pt_regs *regs) @@ -8404,7 +8603,12 @@ void perf_prepare_sample(struct perf_sample_data *data, if (data->regs_user.regs) { u64 mask = event->attr.sample_regs_user; + size += hweight64(mask) * sizeof(u64); + if (event_has_simd_regs(event)) { + size += perf_update_xregs_size(event, false); + data->regs_user.abi |= PERF_SAMPLE_REGS_ABI_SIMD; + } } data->dyn_size += size; @@ -8469,6 +8673,10 @@ void perf_prepare_sample(struct perf_sample_data *data, u64 mask = event->attr.sample_regs_intr; size += hweight64(mask) * sizeof(u64); + if (event_has_simd_regs(event)) { + size += perf_update_xregs_size(event, true); + data->regs_intr.abi |= PERF_SAMPLE_REGS_ABI_SIMD; + } } data->dyn_size += size; @@ -12258,13 +12466,8 @@ perf_event_mux_interval_ms_store(struct device *dev, /* update all cpuctx for this PMU */ cpus_read_lock(); - for_each_online_cpu(cpu) { - struct perf_cpu_pmu_context *cpc; - cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu); - cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer); - - cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc); - } + for_each_online_cpu(cpu) + cpu_function_call(cpu, perf_mux_hrtimer_interval_ipi, pmu); cpus_read_unlock(); mutex_unlock(&mux_interval_mutex); @@ -12589,6 +12792,7 @@ static void __pmu_detach_event(struct pmu *pmu, struct perf_event *event, exclusive_event_destroy(event); module_put(pmu->module); + mediated_pmu_unaccount_event(event); event->pmu = NULL; /* force fault instead of UAF */ } @@ -12692,12 +12896,6 @@ int perf_pmu_unregister(struct pmu *pmu) } EXPORT_SYMBOL_GPL(perf_pmu_unregister); -static inline bool has_extended_regs(struct perf_event *event) -{ - return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) || - (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK); -} - static int perf_try_init_event(struct pmu *pmu, struct perf_event *event) { struct perf_event_context *ctx = NULL; @@ -12731,8 +12929,14 @@ static int perf_try_init_event(struct pmu *pmu, struct perf_event *event) if (ret) goto err_pmu; + if (!(pmu->capabilities & PERF_PMU_CAP_SIMD_REGS) && + event_has_simd_regs(event)) { + ret = -EOPNOTSUPP; + goto err_destroy; + } + if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) && - has_extended_regs(event)) { + event_has_extended_regs(event)) { ret = -EOPNOTSUPP; goto err_destroy; } @@ -13182,6 +13386,10 @@ perf_event_alloc(struct perf_event_attr *attr, int cpu, if (err) return ERR_PTR(err); + err = mediated_pmu_account_event(event); + if (err) + return ERR_PTR(err); + /* symmetric to unaccount_event() in _free_event() */ account_event(event); @@ -13223,7 +13431,8 @@ static int perf_copy_attr(struct perf_event_attr __user *uattr, attr->size = size; - if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3) + if (attr->__reserved_1 || attr->__reserved_2 || + attr->__reserved_3 || attr->__reserved_4) return -EINVAL; if (attr->sample_type & ~(PERF_SAMPLE_MAX-1)) @@ -13272,6 +13481,14 @@ static int perf_copy_attr(struct perf_event_attr __user *uattr, ret = perf_reg_validate(attr->sample_regs_user); if (ret) return ret; + if (attr->sample_simd_regs_enabled) { + ret = perf_simd_reg_validate(attr->sample_simd_vec_reg_qwords, + attr->sample_simd_vec_reg_user, + attr->sample_simd_pred_reg_qwords, + attr->sample_simd_pred_reg_user); + if (ret) + return ret; + } } if (attr->sample_type & PERF_SAMPLE_STACK_USER) { @@ -13292,8 +13509,19 @@ static int perf_copy_attr(struct perf_event_attr __user *uattr, if (!attr->sample_max_stack) attr->sample_max_stack = sysctl_perf_event_max_stack; - if (attr->sample_type & PERF_SAMPLE_REGS_INTR) + if (attr->sample_type & PERF_SAMPLE_REGS_INTR) { ret = perf_reg_validate(attr->sample_regs_intr); + if (ret) + return ret; + if (attr->sample_simd_regs_enabled) { + ret = perf_simd_reg_validate(attr->sample_simd_vec_reg_qwords, + attr->sample_simd_vec_reg_intr, + attr->sample_simd_pred_reg_qwords, + attr->sample_simd_pred_reg_intr); + if (ret) + return ret; + } + } #ifndef CONFIG_CGROUP_PERF if (attr->sample_type & PERF_SAMPLE_CGROUP) diff --git a/kernel/events/hw_breakpoint.c b/kernel/events/hw_breakpoint.c index 8ec2cb688903..81d5ba91fa14 100644 --- a/kernel/events/hw_breakpoint.c +++ b/kernel/events/hw_breakpoint.c @@ -967,8 +967,7 @@ static int hw_breakpoint_event_init(struct perf_event *bp) static int hw_breakpoint_add(struct perf_event *bp, int flags) { - if (!(flags & PERF_EF_START)) - bp->hw.state = PERF_HES_STOPPED; + bp->hw.state = (flags & PERF_EF_START) ? 0 : PERF_HES_STOPPED; if (is_sampling_event(bp)) { bp->hw.last_period = bp->hw.sample_period; diff --git a/kernel/kexec_handover.c b/kernel/kexec_handover.c deleted file mode 100644 index e503573e0319..000000000000 --- a/kernel/kexec_handover.c +++ /dev/null @@ -1,1494 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -/* - * kexec_handover.c - kexec handover metadata processing - * Copyright (C) 2023 Alexander Graf - * Copyright (C) 2025 Microsoft Corporation, Mike Rapoport - * Copyright (C) 2025 Google LLC, Changyuan Lyu - */ - -#define pr_fmt(fmt) "KHO: " fmt - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "kexec_handover_internal.h" -/* - * KHO is tightly coupled with mm init and needs access to some of mm - * internal APIs. - */ -#include "../mm/internal.h" -#include "kexec_internal.h" -#include "kexec_handover_internal.h" - -#define KHO_FDT_COMPATIBLE "kho-v1" -#define PROP_PRESERVED_MEMORY_MAP "preserved-memory-map" -#define PROP_SUB_FDT "fdt" - -#define KHO_PAGE_MAGIC 0x4b484f50U /* ASCII for 'KHOP' */ - -/* - * KHO uses page->private, which is an unsigned long, to store page metadata. - * Use it to store both the magic and the order. - */ -union kho_page_info { - unsigned long page_private; - struct { - unsigned int order; - unsigned int magic; - }; -}; - -static_assert(sizeof(union kho_page_info) == sizeof(((struct page *)0)->private)); - -static bool kho_enable __ro_after_init; - -bool kho_is_enabled(void) -{ - return kho_enable; -} -EXPORT_SYMBOL_GPL(kho_is_enabled); - -static int __init kho_parse_enable(char *p) -{ - return kstrtobool(p, &kho_enable); -} -early_param("kho", kho_parse_enable); - -/* - * Keep track of memory that is to be preserved across KHO. - * - * The serializing side uses two levels of xarrays to manage chunks of per-order - * PAGE_SIZE byte bitmaps. For instance if PAGE_SIZE = 4096, the entire 1G order - * of a 8TB system would fit inside a single 4096 byte bitmap. For order 0 - * allocations each bitmap will cover 128M of address space. Thus, for 16G of - * memory at most 512K of bitmap memory will be needed for order 0. - * - * This approach is fully incremental, as the serialization progresses folios - * can continue be aggregated to the tracker. The final step, immediately prior - * to kexec would serialize the xarray information into a linked list for the - * successor kernel to parse. - */ - -#define PRESERVE_BITS (PAGE_SIZE * 8) - -struct kho_mem_phys_bits { - DECLARE_BITMAP(preserve, PRESERVE_BITS); -}; - -static_assert(sizeof(struct kho_mem_phys_bits) == PAGE_SIZE); - -struct kho_mem_phys { - /* - * Points to kho_mem_phys_bits, a sparse bitmap array. Each bit is sized - * to order. - */ - struct xarray phys_bits; -}; - -struct kho_mem_track { - /* Points to kho_mem_phys, each order gets its own bitmap tree */ - struct xarray orders; -}; - -struct khoser_mem_chunk; - -struct kho_serialization { - struct page *fdt; - struct kho_mem_track track; - /* First chunk of serialized preserved memory map */ - struct khoser_mem_chunk *preserved_mem_map; -}; - -struct kho_out { - struct blocking_notifier_head chain_head; - struct mutex lock; /* protects KHO FDT finalization */ - struct kho_serialization ser; - bool finalized; - struct kho_debugfs dbg; -}; - -static struct kho_out kho_out = { - .chain_head = BLOCKING_NOTIFIER_INIT(kho_out.chain_head), - .lock = __MUTEX_INITIALIZER(kho_out.lock), - .ser = { - .track = { - .orders = XARRAY_INIT(kho_out.ser.track.orders, 0), - }, - }, - .finalized = false, -}; - -static void *xa_load_or_alloc(struct xarray *xa, unsigned long index) -{ - void *res = xa_load(xa, index); - - if (res) - return res; - - void *elm __free(free_page) = (void *)get_zeroed_page(GFP_KERNEL); - - if (!elm) - return ERR_PTR(-ENOMEM); - - if (WARN_ON(kho_scratch_overlap(virt_to_phys(elm), PAGE_SIZE))) - return ERR_PTR(-EINVAL); - - res = xa_cmpxchg(xa, index, NULL, elm, GFP_KERNEL); - if (xa_is_err(res)) - return ERR_PTR(xa_err(res)); - else if (res) - return res; - - return no_free_ptr(elm); -} - -static void __kho_unpreserve(struct kho_mem_track *track, unsigned long pfn, - unsigned long end_pfn) -{ - struct kho_mem_phys_bits *bits; - struct kho_mem_phys *physxa; - - while (pfn < end_pfn) { - const unsigned int order = - min(count_trailing_zeros(pfn), ilog2(end_pfn - pfn)); - const unsigned long pfn_high = pfn >> order; - - physxa = xa_load(&track->orders, order); - if (WARN_ON_ONCE(!physxa)) - return; - - bits = xa_load(&physxa->phys_bits, pfn_high / PRESERVE_BITS); - if (WARN_ON_ONCE(!bits)) - return; - - clear_bit(pfn_high % PRESERVE_BITS, bits->preserve); - - pfn += 1 << order; - } -} - -static int __kho_preserve_order(struct kho_mem_track *track, unsigned long pfn, - unsigned int order) -{ - struct kho_mem_phys_bits *bits; - struct kho_mem_phys *physxa, *new_physxa; - const unsigned long pfn_high = pfn >> order; - - might_sleep(); - - if (kho_out.finalized) - return -EBUSY; - - physxa = xa_load(&track->orders, order); - if (!physxa) { - int err; - - new_physxa = kzalloc(sizeof(*physxa), GFP_KERNEL); - if (!new_physxa) - return -ENOMEM; - - xa_init(&new_physxa->phys_bits); - physxa = xa_cmpxchg(&track->orders, order, NULL, new_physxa, - GFP_KERNEL); - - err = xa_err(physxa); - if (err || physxa) { - xa_destroy(&new_physxa->phys_bits); - kfree(new_physxa); - - if (err) - return err; - } else { - physxa = new_physxa; - } - } - - bits = xa_load_or_alloc(&physxa->phys_bits, pfn_high / PRESERVE_BITS); - if (IS_ERR(bits)) - return PTR_ERR(bits); - - set_bit(pfn_high % PRESERVE_BITS, bits->preserve); - - return 0; -} - -static struct page *kho_restore_page(phys_addr_t phys) -{ - struct page *page = pfn_to_online_page(PHYS_PFN(phys)); - union kho_page_info info; - unsigned int nr_pages; - - if (!page) - return NULL; - - info.page_private = page->private; - /* - * deserialize_bitmap() only sets the magic on the head page. This magic - * check also implicitly makes sure phys is order-aligned since for - * non-order-aligned phys addresses, magic will never be set. - */ - if (WARN_ON_ONCE(info.magic != KHO_PAGE_MAGIC || info.order > MAX_PAGE_ORDER)) - return NULL; - nr_pages = (1 << info.order); - - /* Clear private to make sure later restores on this page error out. */ - page->private = 0; - /* Head page gets refcount of 1. */ - set_page_count(page, 1); - - /* For higher order folios, tail pages get a page count of zero. */ - for (unsigned int i = 1; i < nr_pages; i++) - set_page_count(page + i, 0); - - if (info.order > 0) - prep_compound_page(page, info.order); - - adjust_managed_page_count(page, nr_pages); - return page; -} - -/** - * kho_restore_folio - recreates the folio from the preserved memory. - * @phys: physical address of the folio. - * - * Return: pointer to the struct folio on success, NULL on failure. - */ -struct folio *kho_restore_folio(phys_addr_t phys) -{ - struct page *page = kho_restore_page(phys); - - return page ? page_folio(page) : NULL; -} -EXPORT_SYMBOL_GPL(kho_restore_folio); - -/** - * kho_restore_pages - restore list of contiguous order 0 pages. - * @phys: physical address of the first page. - * @nr_pages: number of pages. - * - * Restore a contiguous list of order 0 pages that was preserved with - * kho_preserve_pages(). - * - * Return: 0 on success, error code on failure - */ -struct page *kho_restore_pages(phys_addr_t phys, unsigned int nr_pages) -{ - const unsigned long start_pfn = PHYS_PFN(phys); - const unsigned long end_pfn = start_pfn + nr_pages; - unsigned long pfn = start_pfn; - - while (pfn < end_pfn) { - const unsigned int order = - min(count_trailing_zeros(pfn), ilog2(end_pfn - pfn)); - struct page *page = kho_restore_page(PFN_PHYS(pfn)); - - if (!page) - return NULL; - split_page(page, order); - pfn += 1 << order; - } - - return pfn_to_page(start_pfn); -} -EXPORT_SYMBOL_GPL(kho_restore_pages); - -/* Serialize and deserialize struct kho_mem_phys across kexec - * - * Record all the bitmaps in a linked list of pages for the next kernel to - * process. Each chunk holds bitmaps of the same order and each block of bitmaps - * starts at a given physical address. This allows the bitmaps to be sparse. The - * xarray is used to store them in a tree while building up the data structure, - * but the KHO successor kernel only needs to process them once in order. - * - * All of this memory is normal kmalloc() memory and is not marked for - * preservation. The successor kernel will remain isolated to the scratch space - * until it completes processing this list. Once processed all the memory - * storing these ranges will be marked as free. - */ - -struct khoser_mem_bitmap_ptr { - phys_addr_t phys_start; - DECLARE_KHOSER_PTR(bitmap, struct kho_mem_phys_bits *); -}; - -struct khoser_mem_chunk_hdr { - DECLARE_KHOSER_PTR(next, struct khoser_mem_chunk *); - unsigned int order; - unsigned int num_elms; -}; - -#define KHOSER_BITMAP_SIZE \ - ((PAGE_SIZE - sizeof(struct khoser_mem_chunk_hdr)) / \ - sizeof(struct khoser_mem_bitmap_ptr)) - -struct khoser_mem_chunk { - struct khoser_mem_chunk_hdr hdr; - struct khoser_mem_bitmap_ptr bitmaps[KHOSER_BITMAP_SIZE]; -}; - -static_assert(sizeof(struct khoser_mem_chunk) == PAGE_SIZE); - -static struct khoser_mem_chunk *new_chunk(struct khoser_mem_chunk *cur_chunk, - unsigned long order) -{ - struct khoser_mem_chunk *chunk __free(free_page) = NULL; - - chunk = (void *)get_zeroed_page(GFP_KERNEL); - if (!chunk) - return ERR_PTR(-ENOMEM); - - if (WARN_ON(kho_scratch_overlap(virt_to_phys(chunk), PAGE_SIZE))) - return ERR_PTR(-EINVAL); - - chunk->hdr.order = order; - if (cur_chunk) - KHOSER_STORE_PTR(cur_chunk->hdr.next, chunk); - return no_free_ptr(chunk); -} - -static void kho_mem_ser_free(struct khoser_mem_chunk *first_chunk) -{ - struct khoser_mem_chunk *chunk = first_chunk; - - while (chunk) { - struct khoser_mem_chunk *tmp = chunk; - - chunk = KHOSER_LOAD_PTR(chunk->hdr.next); - free_page((unsigned long)tmp); - } -} - -static int kho_mem_serialize(struct kho_serialization *ser) -{ - struct khoser_mem_chunk *first_chunk = NULL; - struct khoser_mem_chunk *chunk = NULL; - struct kho_mem_phys *physxa; - unsigned long order; - int err = -ENOMEM; - - xa_for_each(&ser->track.orders, order, physxa) { - struct kho_mem_phys_bits *bits; - unsigned long phys; - - chunk = new_chunk(chunk, order); - if (IS_ERR(chunk)) { - err = PTR_ERR(chunk); - goto err_free; - } - - if (!first_chunk) - first_chunk = chunk; - - xa_for_each(&physxa->phys_bits, phys, bits) { - struct khoser_mem_bitmap_ptr *elm; - - if (chunk->hdr.num_elms == ARRAY_SIZE(chunk->bitmaps)) { - chunk = new_chunk(chunk, order); - if (IS_ERR(chunk)) { - err = PTR_ERR(chunk); - goto err_free; - } - } - - elm = &chunk->bitmaps[chunk->hdr.num_elms]; - chunk->hdr.num_elms++; - elm->phys_start = (phys * PRESERVE_BITS) - << (order + PAGE_SHIFT); - KHOSER_STORE_PTR(elm->bitmap, bits); - } - } - - ser->preserved_mem_map = first_chunk; - - return 0; - -err_free: - kho_mem_ser_free(first_chunk); - return err; -} - -static void __init deserialize_bitmap(unsigned int order, - struct khoser_mem_bitmap_ptr *elm) -{ - struct kho_mem_phys_bits *bitmap = KHOSER_LOAD_PTR(elm->bitmap); - unsigned long bit; - - for_each_set_bit(bit, bitmap->preserve, PRESERVE_BITS) { - u64 sz = 1UL << (order + PAGE_SHIFT); - phys_addr_t phys = - elm->phys_start + (bit << (order + PAGE_SHIFT)); - struct page *page = phys_to_page(phys); - union kho_page_info info; - - memblock_reserve(phys, sz); - memblock_reserved_mark_noinit(phys, sz); - info.magic = KHO_PAGE_MAGIC; - info.order = order; - page->private = info.page_private; - } -} - -static void __init kho_mem_deserialize(const void *fdt) -{ - struct khoser_mem_chunk *chunk; - const phys_addr_t *mem; - int len; - - mem = fdt_getprop(fdt, 0, PROP_PRESERVED_MEMORY_MAP, &len); - - if (!mem || len != sizeof(*mem)) { - pr_err("failed to get preserved memory bitmaps\n"); - return; - } - - chunk = *mem ? phys_to_virt(*mem) : NULL; - while (chunk) { - unsigned int i; - - for (i = 0; i != chunk->hdr.num_elms; i++) - deserialize_bitmap(chunk->hdr.order, - &chunk->bitmaps[i]); - chunk = KHOSER_LOAD_PTR(chunk->hdr.next); - } -} - -/* - * With KHO enabled, memory can become fragmented because KHO regions may - * be anywhere in physical address space. The scratch regions give us a - * safe zones that we will never see KHO allocations from. This is where we - * can later safely load our new kexec images into and then use the scratch - * area for early allocations that happen before page allocator is - * initialized. - */ -struct kho_scratch *kho_scratch; -unsigned int kho_scratch_cnt; - -/* - * The scratch areas are scaled by default as percent of memory allocated from - * memblock. A user can override the scale with command line parameter: - * - * kho_scratch=N% - * - * It is also possible to explicitly define size for a lowmem, a global and - * per-node scratch areas: - * - * kho_scratch=l[KMG],n[KMG],m[KMG] - * - * The explicit size definition takes precedence over scale definition. - */ -static unsigned int scratch_scale __initdata = 200; -static phys_addr_t scratch_size_global __initdata; -static phys_addr_t scratch_size_pernode __initdata; -static phys_addr_t scratch_size_lowmem __initdata; - -static int __init kho_parse_scratch_size(char *p) -{ - size_t len; - unsigned long sizes[3]; - size_t total_size = 0; - int i; - - if (!p) - return -EINVAL; - - len = strlen(p); - if (!len) - return -EINVAL; - - /* parse nn% */ - if (p[len - 1] == '%') { - /* unsigned int max is 4,294,967,295, 10 chars */ - char s_scale[11] = {}; - int ret = 0; - - if (len > ARRAY_SIZE(s_scale)) - return -EINVAL; - - memcpy(s_scale, p, len - 1); - ret = kstrtouint(s_scale, 10, &scratch_scale); - if (!ret) - pr_notice("scratch scale is %d%%\n", scratch_scale); - return ret; - } - - /* parse ll[KMG],mm[KMG],nn[KMG] */ - for (i = 0; i < ARRAY_SIZE(sizes); i++) { - char *endp = p; - - if (i > 0) { - if (*p != ',') - return -EINVAL; - p += 1; - } - - sizes[i] = memparse(p, &endp); - if (endp == p) - return -EINVAL; - p = endp; - total_size += sizes[i]; - } - - if (!total_size) - return -EINVAL; - - /* The string should be fully consumed by now. */ - if (*p) - return -EINVAL; - - scratch_size_lowmem = sizes[0]; - scratch_size_global = sizes[1]; - scratch_size_pernode = sizes[2]; - scratch_scale = 0; - - pr_notice("scratch areas: lowmem: %lluMiB global: %lluMiB pernode: %lldMiB\n", - (u64)(scratch_size_lowmem >> 20), - (u64)(scratch_size_global >> 20), - (u64)(scratch_size_pernode >> 20)); - - return 0; -} -early_param("kho_scratch", kho_parse_scratch_size); - -static void __init scratch_size_update(void) -{ - /* - * If fixed sizes are not provided via command line, calculate them - * now. - */ - if (scratch_scale) { - phys_addr_t size; - - size = memblock_reserved_kern_size(ARCH_LOW_ADDRESS_LIMIT, - NUMA_NO_NODE); - size = size * scratch_scale / 100; - scratch_size_lowmem = size; - - size = memblock_reserved_kern_size(MEMBLOCK_ALLOC_ANYWHERE, - NUMA_NO_NODE); - size = size * scratch_scale / 100 - scratch_size_lowmem; - scratch_size_global = size; - } - - /* - * Scratch areas are released as MIGRATE_CMA. Round them up to the right - * size. - */ - scratch_size_lowmem = round_up(scratch_size_lowmem, CMA_MIN_ALIGNMENT_BYTES); - scratch_size_global = round_up(scratch_size_global, CMA_MIN_ALIGNMENT_BYTES); -} - -static phys_addr_t __init scratch_size_node(int nid) -{ - phys_addr_t size; - - if (scratch_scale) { - size = memblock_reserved_kern_size(MEMBLOCK_ALLOC_ANYWHERE, - nid); - size = size * scratch_scale / 100; - } else { - size = scratch_size_pernode; - } - - return round_up(size, CMA_MIN_ALIGNMENT_BYTES); -} - -/** - * kho_reserve_scratch - Reserve a contiguous chunk of memory for kexec - * - * With KHO we can preserve arbitrary pages in the system. To ensure we still - * have a large contiguous region of memory when we search the physical address - * space for target memory, let's make sure we always have a large CMA region - * active. This CMA region will only be used for movable pages which are not a - * problem for us during KHO because we can just move them somewhere else. - */ -static void __init kho_reserve_scratch(void) -{ - phys_addr_t addr, size; - int nid, i = 0; - - if (!kho_enable) - return; - - scratch_size_update(); - - /* FIXME: deal with node hot-plug/remove */ - kho_scratch_cnt = nodes_weight(node_states[N_MEMORY]) + 2; - size = kho_scratch_cnt * sizeof(*kho_scratch); - kho_scratch = memblock_alloc(size, PAGE_SIZE); - if (!kho_scratch) - goto err_disable_kho; - - /* - * reserve scratch area in low memory for lowmem allocations in the - * next kernel - */ - size = scratch_size_lowmem; - addr = memblock_phys_alloc_range(size, CMA_MIN_ALIGNMENT_BYTES, 0, - ARCH_LOW_ADDRESS_LIMIT); - if (!addr) - goto err_free_scratch_desc; - - kho_scratch[i].addr = addr; - kho_scratch[i].size = size; - i++; - - /* reserve large contiguous area for allocations without nid */ - size = scratch_size_global; - addr = memblock_phys_alloc(size, CMA_MIN_ALIGNMENT_BYTES); - if (!addr) - goto err_free_scratch_areas; - - kho_scratch[i].addr = addr; - kho_scratch[i].size = size; - i++; - - /* - * Loop over nodes that have both memory and are online. Skip - * memoryless nodes, as we can not allocate scratch areas there. - */ - for_each_node_state(nid, N_MEMORY) { - size = scratch_size_node(nid); - addr = memblock_alloc_range_nid(size, CMA_MIN_ALIGNMENT_BYTES, - 0, MEMBLOCK_ALLOC_ACCESSIBLE, - nid, true); - if (!addr) - goto err_free_scratch_areas; - - kho_scratch[i].addr = addr; - kho_scratch[i].size = size; - i++; - } - - return; - -err_free_scratch_areas: - for (i--; i >= 0; i--) - memblock_phys_free(kho_scratch[i].addr, kho_scratch[i].size); -err_free_scratch_desc: - memblock_free(kho_scratch, kho_scratch_cnt * sizeof(*kho_scratch)); -err_disable_kho: - pr_warn("Failed to reserve scratch area, disabling kexec handover\n"); - kho_enable = false; -} - -/** - * kho_add_subtree - record the physical address of a sub FDT in KHO root tree. - * @ser: serialization control object passed by KHO notifiers. - * @name: name of the sub tree. - * @fdt: the sub tree blob. - * - * Creates a new child node named @name in KHO root FDT and records - * the physical address of @fdt. The pages of @fdt must also be preserved - * by KHO for the new kernel to retrieve it after kexec. - * - * A debugfs blob entry is also created at - * ``/sys/kernel/debug/kho/out/sub_fdts/@name`` when kernel is configured with - * CONFIG_KEXEC_HANDOVER_DEBUGFS - * - * Return: 0 on success, error code on failure - */ -int kho_add_subtree(struct kho_serialization *ser, const char *name, void *fdt) -{ - int err = 0; - u64 phys = (u64)virt_to_phys(fdt); - void *root = page_to_virt(ser->fdt); - - err |= fdt_begin_node(root, name); - err |= fdt_property(root, PROP_SUB_FDT, &phys, sizeof(phys)); - err |= fdt_end_node(root); - - if (err) - return err; - - return kho_debugfs_fdt_add(&kho_out.dbg, name, fdt, false); -} -EXPORT_SYMBOL_GPL(kho_add_subtree); - -int register_kho_notifier(struct notifier_block *nb) -{ - return blocking_notifier_chain_register(&kho_out.chain_head, nb); -} -EXPORT_SYMBOL_GPL(register_kho_notifier); - -int unregister_kho_notifier(struct notifier_block *nb) -{ - return blocking_notifier_chain_unregister(&kho_out.chain_head, nb); -} -EXPORT_SYMBOL_GPL(unregister_kho_notifier); - -/** - * kho_preserve_folio - preserve a folio across kexec. - * @folio: folio to preserve. - * - * Instructs KHO to preserve the whole folio across kexec. The order - * will be preserved as well. - * - * Return: 0 on success, error code on failure - */ -int kho_preserve_folio(struct folio *folio) -{ - const unsigned long pfn = folio_pfn(folio); - const unsigned int order = folio_order(folio); - struct kho_mem_track *track = &kho_out.ser.track; - - if (WARN_ON(kho_scratch_overlap(pfn << PAGE_SHIFT, PAGE_SIZE << order))) - return -EINVAL; - - return __kho_preserve_order(track, pfn, order); -} -EXPORT_SYMBOL_GPL(kho_preserve_folio); - -/** - * kho_preserve_pages - preserve contiguous pages across kexec - * @page: first page in the list. - * @nr_pages: number of pages. - * - * Preserve a contiguous list of order 0 pages. Must be restored using - * kho_restore_pages() to ensure the pages are restored properly as order 0. - * - * Return: 0 on success, error code on failure - */ -int kho_preserve_pages(struct page *page, unsigned int nr_pages) -{ - struct kho_mem_track *track = &kho_out.ser.track; - const unsigned long start_pfn = page_to_pfn(page); - const unsigned long end_pfn = start_pfn + nr_pages; - unsigned long pfn = start_pfn; - unsigned long failed_pfn = 0; - int err = 0; - - if (WARN_ON(kho_scratch_overlap(start_pfn << PAGE_SHIFT, - nr_pages << PAGE_SHIFT))) { - return -EINVAL; - } - - while (pfn < end_pfn) { - const unsigned int order = - min(count_trailing_zeros(pfn), ilog2(end_pfn - pfn)); - - err = __kho_preserve_order(track, pfn, order); - if (err) { - failed_pfn = pfn; - break; - } - - pfn += 1 << order; - } - - if (err) - __kho_unpreserve(track, start_pfn, failed_pfn); - - return err; -} -EXPORT_SYMBOL_GPL(kho_preserve_pages); - -struct kho_vmalloc_hdr { - DECLARE_KHOSER_PTR(next, struct kho_vmalloc_chunk *); -}; - -#define KHO_VMALLOC_SIZE \ - ((PAGE_SIZE - sizeof(struct kho_vmalloc_hdr)) / \ - sizeof(phys_addr_t)) - -struct kho_vmalloc_chunk { - struct kho_vmalloc_hdr hdr; - phys_addr_t phys[KHO_VMALLOC_SIZE]; -}; - -static_assert(sizeof(struct kho_vmalloc_chunk) == PAGE_SIZE); - -/* vmalloc flags KHO supports */ -#define KHO_VMALLOC_SUPPORTED_FLAGS (VM_ALLOC | VM_ALLOW_HUGE_VMAP) - -/* KHO internal flags for vmalloc preservations */ -#define KHO_VMALLOC_ALLOC 0x0001 -#define KHO_VMALLOC_HUGE_VMAP 0x0002 - -static unsigned short vmalloc_flags_to_kho(unsigned int vm_flags) -{ - unsigned short kho_flags = 0; - - if (vm_flags & VM_ALLOC) - kho_flags |= KHO_VMALLOC_ALLOC; - if (vm_flags & VM_ALLOW_HUGE_VMAP) - kho_flags |= KHO_VMALLOC_HUGE_VMAP; - - return kho_flags; -} - -static unsigned int kho_flags_to_vmalloc(unsigned short kho_flags) -{ - unsigned int vm_flags = 0; - - if (kho_flags & KHO_VMALLOC_ALLOC) - vm_flags |= VM_ALLOC; - if (kho_flags & KHO_VMALLOC_HUGE_VMAP) - vm_flags |= VM_ALLOW_HUGE_VMAP; - - return vm_flags; -} - -static struct kho_vmalloc_chunk *new_vmalloc_chunk(struct kho_vmalloc_chunk *cur) -{ - struct kho_vmalloc_chunk *chunk; - int err; - - chunk = (struct kho_vmalloc_chunk *)get_zeroed_page(GFP_KERNEL); - if (!chunk) - return NULL; - - err = kho_preserve_pages(virt_to_page(chunk), 1); - if (err) - goto err_free; - if (cur) - KHOSER_STORE_PTR(cur->hdr.next, chunk); - return chunk; - -err_free: - free_page((unsigned long)chunk); - return NULL; -} - -static void kho_vmalloc_unpreserve_chunk(struct kho_vmalloc_chunk *chunk, - unsigned short order) -{ - struct kho_mem_track *track = &kho_out.ser.track; - unsigned long pfn = PHYS_PFN(virt_to_phys(chunk)); - - __kho_unpreserve(track, pfn, pfn + 1); - - for (int i = 0; i < ARRAY_SIZE(chunk->phys) && chunk->phys[i]; i++) { - pfn = PHYS_PFN(chunk->phys[i]); - __kho_unpreserve(track, pfn, pfn + (1 << order)); - } -} - -static void kho_vmalloc_free_chunks(struct kho_vmalloc *kho_vmalloc) -{ - struct kho_vmalloc_chunk *chunk = KHOSER_LOAD_PTR(kho_vmalloc->first); - - while (chunk) { - struct kho_vmalloc_chunk *tmp = chunk; - - kho_vmalloc_unpreserve_chunk(chunk, kho_vmalloc->order); - - chunk = KHOSER_LOAD_PTR(chunk->hdr.next); - free_page((unsigned long)tmp); - } -} - -/** - * kho_preserve_vmalloc - preserve memory allocated with vmalloc() across kexec - * @ptr: pointer to the area in vmalloc address space - * @preservation: placeholder for preservation metadata - * - * Instructs KHO to preserve the area in vmalloc address space at @ptr. The - * physical pages mapped at @ptr will be preserved and on successful return - * @preservation will hold the physical address of a structure that describes - * the preservation. - * - * NOTE: The memory allocated with vmalloc_node() variants cannot be reliably - * restored on the same node - * - * Return: 0 on success, error code on failure - */ -int kho_preserve_vmalloc(void *ptr, struct kho_vmalloc *preservation) -{ - struct kho_vmalloc_chunk *chunk; - struct vm_struct *vm = find_vm_area(ptr); - unsigned int order, flags, nr_contig_pages; - unsigned int idx = 0; - int err; - - if (!vm) - return -EINVAL; - - if (vm->flags & ~KHO_VMALLOC_SUPPORTED_FLAGS) - return -EOPNOTSUPP; - - flags = vmalloc_flags_to_kho(vm->flags); - order = get_vm_area_page_order(vm); - - chunk = new_vmalloc_chunk(NULL); - if (!chunk) - return -ENOMEM; - KHOSER_STORE_PTR(preservation->first, chunk); - - nr_contig_pages = (1 << order); - for (int i = 0; i < vm->nr_pages; i += nr_contig_pages) { - phys_addr_t phys = page_to_phys(vm->pages[i]); - - err = kho_preserve_pages(vm->pages[i], nr_contig_pages); - if (err) - goto err_free; - - chunk->phys[idx++] = phys; - if (idx == ARRAY_SIZE(chunk->phys)) { - chunk = new_vmalloc_chunk(chunk); - if (!chunk) - goto err_free; - idx = 0; - } - } - - preservation->total_pages = vm->nr_pages; - preservation->flags = flags; - preservation->order = order; - - return 0; - -err_free: - kho_vmalloc_free_chunks(preservation); - return err; -} -EXPORT_SYMBOL_GPL(kho_preserve_vmalloc); - -/** - * kho_restore_vmalloc - recreates and populates an area in vmalloc address - * space from the preserved memory. - * @preservation: preservation metadata. - * - * Recreates an area in vmalloc address space and populates it with memory that - * was preserved using kho_preserve_vmalloc(). - * - * Return: pointer to the area in the vmalloc address space, NULL on failure. - */ -void *kho_restore_vmalloc(const struct kho_vmalloc *preservation) -{ - struct kho_vmalloc_chunk *chunk = KHOSER_LOAD_PTR(preservation->first); - unsigned int align, order, shift, vm_flags; - unsigned long total_pages, contig_pages; - unsigned long addr, size; - struct vm_struct *area; - struct page **pages; - unsigned int idx = 0; - int err; - - vm_flags = kho_flags_to_vmalloc(preservation->flags); - if (vm_flags & ~KHO_VMALLOC_SUPPORTED_FLAGS) - return NULL; - - total_pages = preservation->total_pages; - pages = kvmalloc_array(total_pages, sizeof(*pages), GFP_KERNEL); - if (!pages) - return NULL; - order = preservation->order; - contig_pages = (1 << order); - shift = PAGE_SHIFT + order; - align = 1 << shift; - - while (chunk) { - struct page *page; - - for (int i = 0; i < ARRAY_SIZE(chunk->phys) && chunk->phys[i]; i++) { - phys_addr_t phys = chunk->phys[i]; - - if (idx + contig_pages > total_pages) - goto err_free_pages_array; - - page = kho_restore_pages(phys, contig_pages); - if (!page) - goto err_free_pages_array; - - for (int j = 0; j < contig_pages; j++) - pages[idx++] = page; - - phys += contig_pages * PAGE_SIZE; - } - - page = kho_restore_pages(virt_to_phys(chunk), 1); - if (!page) - goto err_free_pages_array; - chunk = KHOSER_LOAD_PTR(chunk->hdr.next); - __free_page(page); - } - - if (idx != total_pages) - goto err_free_pages_array; - - area = __get_vm_area_node(total_pages * PAGE_SIZE, align, shift, - vm_flags, VMALLOC_START, VMALLOC_END, - NUMA_NO_NODE, GFP_KERNEL, - __builtin_return_address(0)); - if (!area) - goto err_free_pages_array; - - addr = (unsigned long)area->addr; - size = get_vm_area_size(area); - err = vmap_pages_range(addr, addr + size, PAGE_KERNEL, pages, shift); - if (err) - goto err_free_vm_area; - - area->nr_pages = total_pages; - area->pages = pages; - - return area->addr; - -err_free_vm_area: - free_vm_area(area); -err_free_pages_array: - kvfree(pages); - return NULL; -} -EXPORT_SYMBOL_GPL(kho_restore_vmalloc); - -static int __kho_abort(void) -{ - int err; - unsigned long order; - struct kho_mem_phys *physxa; - - xa_for_each(&kho_out.ser.track.orders, order, physxa) { - struct kho_mem_phys_bits *bits; - unsigned long phys; - - xa_for_each(&physxa->phys_bits, phys, bits) - free_page((unsigned long)bits); - - xa_destroy(&physxa->phys_bits); - kfree(physxa); - } - xa_destroy(&kho_out.ser.track.orders); - - if (kho_out.ser.preserved_mem_map) { - kho_mem_ser_free(kho_out.ser.preserved_mem_map); - kho_out.ser.preserved_mem_map = NULL; - } - - err = blocking_notifier_call_chain(&kho_out.chain_head, KEXEC_KHO_ABORT, - NULL); - err = notifier_to_errno(err); - - if (err) - pr_err("Failed to abort KHO finalization: %d\n", err); - - return err; -} - -int kho_abort(void) -{ - int ret = 0; - - if (!kho_enable) - return -EOPNOTSUPP; - - guard(mutex)(&kho_out.lock); - if (!kho_out.finalized) - return -ENOENT; - - ret = __kho_abort(); - if (ret) - return ret; - - kho_out.finalized = false; - kho_debugfs_cleanup(&kho_out.dbg); - - return 0; -} - -static int __kho_finalize(void) -{ - int err = 0; - u64 *preserved_mem_map; - void *fdt = page_to_virt(kho_out.ser.fdt); - - err |= fdt_create(fdt, PAGE_SIZE); - err |= fdt_finish_reservemap(fdt); - err |= fdt_begin_node(fdt, ""); - err |= fdt_property_string(fdt, "compatible", KHO_FDT_COMPATIBLE); - /** - * Reserve the preserved-memory-map property in the root FDT, so - * that all property definitions will precede subnodes created by - * KHO callers. - */ - err |= fdt_property_placeholder(fdt, PROP_PRESERVED_MEMORY_MAP, - sizeof(*preserved_mem_map), - (void **)&preserved_mem_map); - if (err) - goto abort; - - err = kho_preserve_folio(page_folio(kho_out.ser.fdt)); - if (err) - goto abort; - - err = blocking_notifier_call_chain(&kho_out.chain_head, - KEXEC_KHO_FINALIZE, &kho_out.ser); - err = notifier_to_errno(err); - if (err) - goto abort; - - err = kho_mem_serialize(&kho_out.ser); - if (err) - goto abort; - - *preserved_mem_map = (u64)virt_to_phys(kho_out.ser.preserved_mem_map); - - err |= fdt_end_node(fdt); - err |= fdt_finish(fdt); - -abort: - if (err) { - pr_err("Failed to convert KHO state tree: %d\n", err); - __kho_abort(); - } - - return err; -} - -int kho_finalize(void) -{ - int ret; - - if (!kho_enable) - return -EOPNOTSUPP; - - guard(mutex)(&kho_out.lock); - if (kho_out.finalized) - return -EEXIST; - - ret = __kho_finalize(); - if (ret) - return ret; - - kho_out.finalized = true; - - return kho_debugfs_fdt_add(&kho_out.dbg, "fdt", - page_to_virt(kho_out.ser.fdt), true); -} - -bool kho_finalized(void) -{ - guard(mutex)(&kho_out.lock); - return kho_out.finalized; -} - -struct kho_in { - phys_addr_t fdt_phys; - phys_addr_t scratch_phys; - struct kho_debugfs dbg; -}; - -static struct kho_in kho_in = { -}; - -static const void *kho_get_fdt(void) -{ - return kho_in.fdt_phys ? phys_to_virt(kho_in.fdt_phys) : NULL; -} - -/** - * is_kho_boot - check if current kernel was booted via KHO-enabled - * kexec - * - * This function checks if the current kernel was loaded through a kexec - * operation with KHO enabled, by verifying that a valid KHO FDT - * was passed. - * - * Note: This function returns reliable results only after - * kho_populate() has been called during early boot. Before that, - * it may return false even if KHO data is present. - * - * Return: true if booted via KHO-enabled kexec, false otherwise - */ -bool is_kho_boot(void) -{ - return !!kho_get_fdt(); -} -EXPORT_SYMBOL_GPL(is_kho_boot); - -/** - * kho_retrieve_subtree - retrieve a preserved sub FDT by its name. - * @name: the name of the sub FDT passed to kho_add_subtree(). - * @phys: if found, the physical address of the sub FDT is stored in @phys. - * - * Retrieve a preserved sub FDT named @name and store its physical - * address in @phys. - * - * Return: 0 on success, error code on failure - */ -int kho_retrieve_subtree(const char *name, phys_addr_t *phys) -{ - const void *fdt = kho_get_fdt(); - const u64 *val; - int offset, len; - - if (!fdt) - return -ENOENT; - - if (!phys) - return -EINVAL; - - offset = fdt_subnode_offset(fdt, 0, name); - if (offset < 0) - return -ENOENT; - - val = fdt_getprop(fdt, offset, PROP_SUB_FDT, &len); - if (!val || len != sizeof(*val)) - return -EINVAL; - - *phys = (phys_addr_t)*val; - - return 0; -} -EXPORT_SYMBOL_GPL(kho_retrieve_subtree); - -static __init int kho_init(void) -{ - int err = 0; - const void *fdt = kho_get_fdt(); - - if (!kho_enable) - return 0; - - kho_out.ser.fdt = alloc_page(GFP_KERNEL); - if (!kho_out.ser.fdt) { - err = -ENOMEM; - goto err_free_scratch; - } - - err = kho_debugfs_init(); - if (err) - goto err_free_fdt; - - err = kho_out_debugfs_init(&kho_out.dbg); - if (err) - goto err_free_fdt; - - if (fdt) { - kho_in_debugfs_init(&kho_in.dbg, fdt); - return 0; - } - - for (int i = 0; i < kho_scratch_cnt; i++) { - unsigned long base_pfn = PHYS_PFN(kho_scratch[i].addr); - unsigned long count = kho_scratch[i].size >> PAGE_SHIFT; - unsigned long pfn; - - for (pfn = base_pfn; pfn < base_pfn + count; - pfn += pageblock_nr_pages) - init_cma_reserved_pageblock(pfn_to_page(pfn)); - } - - return 0; - -err_free_fdt: - put_page(kho_out.ser.fdt); - kho_out.ser.fdt = NULL; -err_free_scratch: - for (int i = 0; i < kho_scratch_cnt; i++) { - void *start = __va(kho_scratch[i].addr); - void *end = start + kho_scratch[i].size; - - free_reserved_area(start, end, -1, ""); - } - kho_enable = false; - return err; -} -late_initcall(kho_init); - -static void __init kho_release_scratch(void) -{ - phys_addr_t start, end; - u64 i; - - memmap_init_kho_scratch_pages(); - - /* - * Mark scratch mem as CMA before we return it. That way we - * ensure that no kernel allocations happen on it. That means - * we can reuse it as scratch memory again later. - */ - __for_each_mem_range(i, &memblock.memory, NULL, NUMA_NO_NODE, - MEMBLOCK_KHO_SCRATCH, &start, &end, NULL) { - ulong start_pfn = pageblock_start_pfn(PFN_DOWN(start)); - ulong end_pfn = pageblock_align(PFN_UP(end)); - ulong pfn; - - for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) - init_pageblock_migratetype(pfn_to_page(pfn), - MIGRATE_CMA, false); - } -} - -void __init kho_memory_init(void) -{ - struct folio *folio; - - if (is_kdump_kernel()) { - kho_enable = false; - pr_info("disabled in the kdump kernel\n"); - return; - } - - if (kho_in.scratch_phys) { - kho_scratch = phys_to_virt(kho_in.scratch_phys); - kho_release_scratch(); - - kho_mem_deserialize(kho_get_fdt()); - folio = kho_restore_folio(kho_in.fdt_phys); - if (!folio) - pr_warn("failed to restore folio for KHO fdt\n"); - } else { - kho_reserve_scratch(); - } -} - -void __init kho_populate(phys_addr_t fdt_phys, u64 fdt_len, - phys_addr_t scratch_phys, u64 scratch_len) -{ - void *fdt = NULL; - struct kho_scratch *scratch = NULL; - int err = 0; - unsigned int scratch_cnt = scratch_len / sizeof(*kho_scratch); - - /* Validate the input FDT */ - fdt = early_memremap(fdt_phys, fdt_len); - if (!fdt) { - pr_warn("setup: failed to memremap FDT (0x%llx)\n", fdt_phys); - err = -EFAULT; - goto out; - } - err = fdt_check_header(fdt); - if (err) { - pr_warn("setup: handover FDT (0x%llx) is invalid: %d\n", - fdt_phys, err); - err = -EINVAL; - goto out; - } - err = fdt_node_check_compatible(fdt, 0, KHO_FDT_COMPATIBLE); - if (err) { - pr_warn("setup: handover FDT (0x%llx) is incompatible with '%s': %d\n", - fdt_phys, KHO_FDT_COMPATIBLE, err); - err = -EINVAL; - goto out; - } - - scratch = early_memremap(scratch_phys, scratch_len); - if (!scratch) { - pr_warn("setup: failed to memremap scratch (phys=0x%llx, len=%lld)\n", - scratch_phys, scratch_len); - err = -EFAULT; - goto out; - } - - /* - * We pass a safe contiguous blocks of memory to use for early boot - * purporses from the previous kernel so that we can resize the - * memblock array as needed. - */ - for (int i = 0; i < scratch_cnt; i++) { - struct kho_scratch *area = &scratch[i]; - u64 size = area->size; - - memblock_add(area->addr, size); - err = memblock_mark_kho_scratch(area->addr, size); - if (WARN_ON(err)) { - pr_warn("failed to mark the scratch region 0x%pa+0x%pa: %d", - &area->addr, &size, err); - goto out; - } - pr_debug("Marked 0x%pa+0x%pa as scratch", &area->addr, &size); - } - - memblock_reserve(scratch_phys, scratch_len); - - /* - * Now that we have a viable region of scratch memory, let's tell - * the memblocks allocator to only use that for any allocations. - * That way we ensure that nothing scribbles over in use data while - * we initialize the page tables which we will need to ingest all - * memory reservations from the previous kernel. - */ - memblock_set_kho_scratch_only(); - - kho_in.fdt_phys = fdt_phys; - kho_in.scratch_phys = scratch_phys; - kho_scratch_cnt = scratch_cnt; - pr_info("found kexec handover data. Will skip init for some devices\n"); - -out: - if (fdt) - early_memunmap(fdt, fdt_len); - if (scratch) - early_memunmap(scratch, scratch_len); - if (err) - pr_warn("disabling KHO revival: %d\n", err); -} - -/* Helper functions for kexec_file_load */ - -int kho_fill_kimage(struct kimage *image) -{ - ssize_t scratch_size; - int err = 0; - struct kexec_buf scratch; - - if (!kho_out.finalized) - return 0; - - image->kho.fdt = page_to_phys(kho_out.ser.fdt); - - scratch_size = sizeof(*kho_scratch) * kho_scratch_cnt; - scratch = (struct kexec_buf){ - .image = image, - .buffer = kho_scratch, - .bufsz = scratch_size, - .mem = KEXEC_BUF_MEM_UNKNOWN, - .memsz = scratch_size, - .buf_align = SZ_64K, /* Makes it easier to map */ - .buf_max = ULONG_MAX, - .top_down = true, - }; - err = kexec_add_buffer(&scratch); - if (err) - return err; - image->kho.scratch = &image->segment[image->nr_segments - 1]; - - return 0; -} - -static int kho_walk_scratch(struct kexec_buf *kbuf, - int (*func)(struct resource *, void *)) -{ - int ret = 0; - int i; - - for (i = 0; i < kho_scratch_cnt; i++) { - struct resource res = { - .start = kho_scratch[i].addr, - .end = kho_scratch[i].addr + kho_scratch[i].size - 1, - }; - - /* Try to fit the kimage into our KHO scratch region */ - ret = func(&res, kbuf); - if (ret) - break; - } - - return ret; -} - -int kho_locate_mem_hole(struct kexec_buf *kbuf, - int (*func)(struct resource *, void *)) -{ - int ret; - - if (!kho_enable || kbuf->image->type == KEXEC_TYPE_CRASH) - return 1; - - ret = kho_walk_scratch(kbuf, func); - - return ret == 1 ? 0 : -EADDRNOTAVAIL; -} diff --git a/kernel/kexec_handover_debug.c b/kernel/kexec_handover_debug.c deleted file mode 100644 index 6efb696f5426..000000000000 --- a/kernel/kexec_handover_debug.c +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -/* - * kexec_handover_debug.c - kexec handover optional debug functionality - * Copyright (C) 2025 Google LLC, Pasha Tatashin - */ - -#define pr_fmt(fmt) "KHO: " fmt - -#include "kexec_handover_internal.h" - -bool kho_scratch_overlap(phys_addr_t phys, size_t size) -{ - phys_addr_t scratch_start, scratch_end; - unsigned int i; - - for (i = 0; i < kho_scratch_cnt; i++) { - scratch_start = kho_scratch[i].addr; - scratch_end = kho_scratch[i].addr + kho_scratch[i].size; - - if (phys < scratch_end && (phys + size) > scratch_start) - return true; - } - - return false; -} diff --git a/kernel/kexec_handover_debugfs.c b/kernel/kexec_handover_debugfs.c deleted file mode 100644 index a91b279f1b23..000000000000 --- a/kernel/kexec_handover_debugfs.c +++ /dev/null @@ -1,216 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -/* - * kexec_handover_debugfs.c - kexec handover debugfs interfaces - * Copyright (C) 2023 Alexander Graf - * Copyright (C) 2025 Microsoft Corporation, Mike Rapoport - * Copyright (C) 2025 Google LLC, Changyuan Lyu - * Copyright (C) 2025 Google LLC, Pasha Tatashin - */ - -#define pr_fmt(fmt) "KHO: " fmt - -#include -#include -#include -#include -#include "kexec_handover_internal.h" - -static struct dentry *debugfs_root; - -struct fdt_debugfs { - struct list_head list; - struct debugfs_blob_wrapper wrapper; - struct dentry *file; -}; - -static int __kho_debugfs_fdt_add(struct list_head *list, struct dentry *dir, - const char *name, const void *fdt) -{ - struct fdt_debugfs *f; - struct dentry *file; - - f = kmalloc(sizeof(*f), GFP_KERNEL); - if (!f) - return -ENOMEM; - - f->wrapper.data = (void *)fdt; - f->wrapper.size = fdt_totalsize(fdt); - - file = debugfs_create_blob(name, 0400, dir, &f->wrapper); - if (IS_ERR(file)) { - kfree(f); - return PTR_ERR(file); - } - - f->file = file; - list_add(&f->list, list); - - return 0; -} - -int kho_debugfs_fdt_add(struct kho_debugfs *dbg, const char *name, - const void *fdt, bool root) -{ - struct dentry *dir; - - if (root) - dir = dbg->dir; - else - dir = dbg->sub_fdt_dir; - - return __kho_debugfs_fdt_add(&dbg->fdt_list, dir, name, fdt); -} - -void kho_debugfs_cleanup(struct kho_debugfs *dbg) -{ - struct fdt_debugfs *ff, *tmp; - - list_for_each_entry_safe(ff, tmp, &dbg->fdt_list, list) { - debugfs_remove(ff->file); - list_del(&ff->list); - kfree(ff); - } -} - -static int kho_out_finalize_get(void *data, u64 *val) -{ - *val = kho_finalized(); - - return 0; -} - -static int kho_out_finalize_set(void *data, u64 val) -{ - if (val) - return kho_finalize(); - else - return kho_abort(); -} - -DEFINE_DEBUGFS_ATTRIBUTE(kho_out_finalize_fops, kho_out_finalize_get, - kho_out_finalize_set, "%llu\n"); - -static int scratch_phys_show(struct seq_file *m, void *v) -{ - for (int i = 0; i < kho_scratch_cnt; i++) - seq_printf(m, "0x%llx\n", kho_scratch[i].addr); - - return 0; -} -DEFINE_SHOW_ATTRIBUTE(scratch_phys); - -static int scratch_len_show(struct seq_file *m, void *v) -{ - for (int i = 0; i < kho_scratch_cnt; i++) - seq_printf(m, "0x%llx\n", kho_scratch[i].size); - - return 0; -} -DEFINE_SHOW_ATTRIBUTE(scratch_len); - -__init void kho_in_debugfs_init(struct kho_debugfs *dbg, const void *fdt) -{ - struct dentry *dir, *sub_fdt_dir; - int err, child; - - INIT_LIST_HEAD(&dbg->fdt_list); - - dir = debugfs_create_dir("in", debugfs_root); - if (IS_ERR(dir)) { - err = PTR_ERR(dir); - goto err_out; - } - - sub_fdt_dir = debugfs_create_dir("sub_fdts", dir); - if (IS_ERR(sub_fdt_dir)) { - err = PTR_ERR(sub_fdt_dir); - goto err_rmdir; - } - - err = __kho_debugfs_fdt_add(&dbg->fdt_list, dir, "fdt", fdt); - if (err) - goto err_rmdir; - - fdt_for_each_subnode(child, fdt, 0) { - int len = 0; - const char *name = fdt_get_name(fdt, child, NULL); - const u64 *fdt_phys; - - fdt_phys = fdt_getprop(fdt, child, "fdt", &len); - if (!fdt_phys) - continue; - if (len != sizeof(*fdt_phys)) { - pr_warn("node %s prop fdt has invalid length: %d\n", - name, len); - continue; - } - err = __kho_debugfs_fdt_add(&dbg->fdt_list, sub_fdt_dir, name, - phys_to_virt(*fdt_phys)); - if (err) { - pr_warn("failed to add fdt %s to debugfs: %d\n", name, - err); - continue; - } - } - - dbg->dir = dir; - dbg->sub_fdt_dir = sub_fdt_dir; - - return; -err_rmdir: - debugfs_remove_recursive(dir); -err_out: - /* - * Failure to create /sys/kernel/debug/kho/in does not prevent - * reviving state from KHO and setting up KHO for the next - * kexec. - */ - if (err) - pr_err("failed exposing handover FDT in debugfs: %d\n", err); -} - -__init int kho_out_debugfs_init(struct kho_debugfs *dbg) -{ - struct dentry *dir, *f, *sub_fdt_dir; - - INIT_LIST_HEAD(&dbg->fdt_list); - - dir = debugfs_create_dir("out", debugfs_root); - if (IS_ERR(dir)) - return -ENOMEM; - - sub_fdt_dir = debugfs_create_dir("sub_fdts", dir); - if (IS_ERR(sub_fdt_dir)) - goto err_rmdir; - - f = debugfs_create_file("scratch_phys", 0400, dir, NULL, - &scratch_phys_fops); - if (IS_ERR(f)) - goto err_rmdir; - - f = debugfs_create_file("scratch_len", 0400, dir, NULL, - &scratch_len_fops); - if (IS_ERR(f)) - goto err_rmdir; - - f = debugfs_create_file("finalize", 0600, dir, NULL, - &kho_out_finalize_fops); - if (IS_ERR(f)) - goto err_rmdir; - - dbg->dir = dir; - dbg->sub_fdt_dir = sub_fdt_dir; - return 0; - -err_rmdir: - debugfs_remove_recursive(dir); - return -ENOENT; -} - -__init int kho_debugfs_init(void) -{ - debugfs_root = debugfs_create_dir("kho", NULL); - if (IS_ERR(debugfs_root)) - return -ENOENT; - return 0; -} diff --git a/kernel/kexec_handover_internal.h b/kernel/kexec_handover_internal.h deleted file mode 100644 index 217b8b25a542..000000000000 --- a/kernel/kexec_handover_internal.h +++ /dev/null @@ -1,55 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0 */ -#ifndef LINUX_KEXEC_HANDOVER_INTERNAL_H -#define LINUX_KEXEC_HANDOVER_INTERNAL_H - -#include -#include -#include - -#ifdef CONFIG_KEXEC_HANDOVER_DEBUGFS -#include - -struct kho_debugfs { - struct dentry *dir; - struct dentry *sub_fdt_dir; - struct list_head fdt_list; -}; - -#else -struct kho_debugfs {}; -#endif - -extern struct kho_scratch *kho_scratch; -extern unsigned int kho_scratch_cnt; - -bool kho_finalized(void); -int kho_finalize(void); -int kho_abort(void); - -#ifdef CONFIG_KEXEC_HANDOVER_DEBUGFS -int kho_debugfs_init(void); -void kho_in_debugfs_init(struct kho_debugfs *dbg, const void *fdt); -int kho_out_debugfs_init(struct kho_debugfs *dbg); -int kho_debugfs_fdt_add(struct kho_debugfs *dbg, const char *name, - const void *fdt, bool root); -void kho_debugfs_cleanup(struct kho_debugfs *dbg); -#else -static inline int kho_debugfs_init(void) { return 0; } -static inline void kho_in_debugfs_init(struct kho_debugfs *dbg, - const void *fdt) { } -static inline int kho_out_debugfs_init(struct kho_debugfs *dbg) { return 0; } -static inline int kho_debugfs_fdt_add(struct kho_debugfs *dbg, const char *name, - const void *fdt, bool root) { return 0; } -static inline void kho_debugfs_cleanup(struct kho_debugfs *dbg) {} -#endif /* CONFIG_KEXEC_HANDOVER_DEBUGFS */ - -#ifdef CONFIG_KEXEC_HANDOVER_DEBUG -bool kho_scratch_overlap(phys_addr_t phys, size_t size); -#else -static inline bool kho_scratch_overlap(phys_addr_t phys, size_t size) -{ - return false; -} -#endif /* CONFIG_KEXEC_HANDOVER_DEBUG */ - -#endif /* LINUX_KEXEC_HANDOVER_INTERNAL_H */ diff --git a/kernel/kprobes.c b/kernel/kprobes.c index 0b0e2fc2e078..a180911d31d5 100644 --- a/kernel/kprobes.c +++ b/kernel/kprobes.c @@ -1478,52 +1478,61 @@ _kprobe_addr(kprobe_opcode_t *addr, const char *symbol_name, return addr; } -static kprobe_opcode_t *kprobe_addr(struct kprobe *p) -{ - bool on_func_entry; - - return _kprobe_addr(p->addr, p->symbol_name, p->offset, &on_func_entry); -} - /* * Check the 'p' is valid and return the aggregator kprobe * at the same address. */ -static struct kprobe *__get_valid_kprobe(struct kprobe *p) +static struct kprobe *__get_valid_kprobe_at(struct kprobe *p, kprobe_opcode_t *addr) { + struct hlist_head *head; struct kprobe *ap, *list_p; lockdep_assert_held(&kprobe_mutex); - ap = get_kprobe(p->addr); - if (unlikely(!ap)) + if (unlikely(!addr)) return NULL; - if (p == ap) - return ap; - - list_for_each_entry(list_p, &ap->list, list) - if (list_p == p) - /* kprobe p is a valid probe */ + head = &kprobe_table[hash_ptr(addr, KPROBE_HASH_BITS)]; + hlist_for_each_entry_rcu(ap, head, hlist, + lockdep_is_held(&kprobe_mutex)) { + if (ap == p) { + p->addr = addr; return ap; + } + if (ap->addr == addr && kprobe_aggrprobe(ap)) { + list_for_each_entry(list_p, &ap->list, list) { + if (list_p == p) { + p->addr = addr; + return ap; + } + } + } + } return NULL; } -/* - * Warn and return error if the kprobe is being re-registered since - * there must be a software bug. - */ -static inline int warn_kprobe_rereg(struct kprobe *p) +static inline struct kprobe *__get_valid_kprobe(struct kprobe *p) +{ + return __get_valid_kprobe_at(p, p->addr); +} + +/* Return error if the kprobe is being re-registered */ +static inline int check_kprobe_rereg_at(struct kprobe *p, kprobe_opcode_t *addr) { guard(mutex)(&kprobe_mutex); - if (WARN_ON_ONCE(__get_valid_kprobe(p))) + if (__get_valid_kprobe_at(p, addr)) return -EINVAL; return 0; } +static inline int check_kprobe_rereg(struct kprobe *p) +{ + return check_kprobe_rereg_at(p, p->addr); +} + static int check_ftrace_location(struct kprobe *p) { unsigned long addr = (unsigned long)p->addr; @@ -1631,6 +1640,8 @@ static int __register_kprobe(struct kprobe *p) if (ret) { hlist_del_rcu(&p->hlist); synchronize_rcu(); + arch_remove_kprobe(p); + return ret; } } @@ -1652,7 +1663,7 @@ int register_kprobe(struct kprobe *p) return PTR_ERR(addr); p->addr = addr; - ret = warn_kprobe_rereg(p); + ret = check_kprobe_rereg(p); if (ret) return ret; @@ -2188,20 +2199,19 @@ int register_kretprobe(struct kretprobe *rp) int ret; int i; void *addr; + bool on_func_entry; - ret = kprobe_on_func_entry(rp->kp.addr, rp->kp.symbol_name, rp->kp.offset); - if (ret) - return ret; + addr = _kprobe_addr(rp->kp.addr, rp->kp.symbol_name, rp->kp.offset, &on_func_entry); + if (IS_ERR(addr)) + return PTR_ERR(addr); - /* If only 'rp->kp.addr' is specified, check reregistering kprobes */ - if (rp->kp.addr && warn_kprobe_rereg(&rp->kp)) + if (!on_func_entry) return -EINVAL; - if (kretprobe_blacklist_size) { - addr = kprobe_addr(&rp->kp); - if (IS_ERR(addr)) - return PTR_ERR(addr); + if (check_kprobe_rereg_at(&rp->kp, addr)) + return -EINVAL; + if (kretprobe_blacklist_size) { for (i = 0; kretprobe_blacklist[i].name != NULL; i++) { if (kretprobe_blacklist[i].addr == addr) return -EINVAL; @@ -2288,8 +2298,10 @@ void unregister_kretprobes(struct kretprobe **rps, int num) for (i = 0; i < num; i++) { guard(mutex)(&kprobe_mutex); - if (__unregister_kprobe_top(&rps[i]->kp) < 0) + if (__unregister_kprobe_top(&rps[i]->kp) < 0) { rps[i]->kp.addr = NULL; + continue; + } #ifdef CONFIG_KRETPROBE_ON_RETHOOK rethook_free(rps[i]->rh); #else @@ -2301,7 +2313,9 @@ void unregister_kretprobes(struct kretprobe **rps, int num) for (i = 0; i < num; i++) { if (rps[i]->kp.addr) { __unregister_kprobe_bottom(&rps[i]->kp); -#ifndef CONFIG_KRETPROBE_ON_RETHOOK +#ifdef CONFIG_KRETPROBE_ON_RETHOOK + rps[i]->rh = NULL; +#else free_rp_inst(rps[i]); #endif } diff --git a/kernel/liveupdate/Kconfig b/kernel/liveupdate/Kconfig new file mode 100644 index 000000000000..eae428309332 --- /dev/null +++ b/kernel/liveupdate/Kconfig @@ -0,0 +1,40 @@ +# SPDX-License-Identifier: GPL-2.0-only + +menu "Live Update and Kexec HandOver" + depends on !DEFERRED_STRUCT_PAGE_INIT + +config KEXEC_HANDOVER + bool "kexec handover" + depends on ARCH_SUPPORTS_KEXEC_HANDOVER && ARCH_SUPPORTS_KEXEC_FILE + depends on !DEFERRED_STRUCT_PAGE_INIT + select MEMBLOCK_KHO_SCRATCH + select KEXEC_FILE + select LIBFDT + select CMA + help + Allow kexec to hand over state across kernels by generating and + passing additional metadata to the target kernel. This is useful + to keep data or state alive across the kexec. For this to work, + both source and target kernels need to have this option enabled. + +config KEXEC_HANDOVER_DEBUG + bool "Enable Kexec Handover debug checks" + depends on KEXEC_HANDOVER + help + This option enables extra sanity checks for the Kexec Handover + subsystem. Since, KHO performance is crucial in live update + scenarios and the extra code might be adding overhead it is + only optionally enabled. + +config KEXEC_HANDOVER_DEBUGFS + bool "kexec handover debugfs interface" + default KEXEC_HANDOVER + depends on KEXEC_HANDOVER + select DEBUG_FS + help + Allow to control kexec handover device tree via debugfs + interface, i.e. finalize the state or aborting the finalization. + Also, enables inspecting the KHO fdt trees with the debugfs binary + blobs. + +endmenu diff --git a/kernel/liveupdate/Makefile b/kernel/liveupdate/Makefile new file mode 100644 index 000000000000..f52ce1ebcf86 --- /dev/null +++ b/kernel/liveupdate/Makefile @@ -0,0 +1,5 @@ +# SPDX-License-Identifier: GPL-2.0 + +obj-$(CONFIG_KEXEC_HANDOVER) += kexec_handover.o +obj-$(CONFIG_KEXEC_HANDOVER_DEBUG) += kexec_handover_debug.o +obj-$(CONFIG_KEXEC_HANDOVER_DEBUGFS) += kexec_handover_debugfs.o diff --git a/kernel/liveupdate/kexec_handover.c b/kernel/liveupdate/kexec_handover.c new file mode 100644 index 000000000000..e36f23286e7b --- /dev/null +++ b/kernel/liveupdate/kexec_handover.c @@ -0,0 +1,1494 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * kexec_handover.c - kexec handover metadata processing + * Copyright (C) 2023 Alexander Graf + * Copyright (C) 2025 Microsoft Corporation, Mike Rapoport + * Copyright (C) 2025 Google LLC, Changyuan Lyu + */ + +#define pr_fmt(fmt) "KHO: " fmt + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "kexec_handover_internal.h" +/* + * KHO is tightly coupled with mm init and needs access to some of mm + * internal APIs. + */ +#include "../../mm/internal.h" +#include "../kexec_internal.h" +#include "kexec_handover_internal.h" + +#define KHO_FDT_COMPATIBLE "kho-v1" +#define PROP_PRESERVED_MEMORY_MAP "preserved-memory-map" +#define PROP_SUB_FDT "fdt" + +#define KHO_PAGE_MAGIC 0x4b484f50U /* ASCII for 'KHOP' */ + +/* + * KHO uses page->private, which is an unsigned long, to store page metadata. + * Use it to store both the magic and the order. + */ +union kho_page_info { + unsigned long page_private; + struct { + unsigned int order; + unsigned int magic; + }; +}; + +static_assert(sizeof(union kho_page_info) == sizeof(((struct page *)0)->private)); + +static bool kho_enable __ro_after_init; + +bool kho_is_enabled(void) +{ + return kho_enable; +} +EXPORT_SYMBOL_GPL(kho_is_enabled); + +static int __init kho_parse_enable(char *p) +{ + return kstrtobool(p, &kho_enable); +} +early_param("kho", kho_parse_enable); + +/* + * Keep track of memory that is to be preserved across KHO. + * + * The serializing side uses two levels of xarrays to manage chunks of per-order + * PAGE_SIZE byte bitmaps. For instance if PAGE_SIZE = 4096, the entire 1G order + * of a 8TB system would fit inside a single 4096 byte bitmap. For order 0 + * allocations each bitmap will cover 128M of address space. Thus, for 16G of + * memory at most 512K of bitmap memory will be needed for order 0. + * + * This approach is fully incremental, as the serialization progresses folios + * can continue be aggregated to the tracker. The final step, immediately prior + * to kexec would serialize the xarray information into a linked list for the + * successor kernel to parse. + */ + +#define PRESERVE_BITS (PAGE_SIZE * 8) + +struct kho_mem_phys_bits { + DECLARE_BITMAP(preserve, PRESERVE_BITS); +}; + +static_assert(sizeof(struct kho_mem_phys_bits) == PAGE_SIZE); + +struct kho_mem_phys { + /* + * Points to kho_mem_phys_bits, a sparse bitmap array. Each bit is sized + * to order. + */ + struct xarray phys_bits; +}; + +struct kho_mem_track { + /* Points to kho_mem_phys, each order gets its own bitmap tree */ + struct xarray orders; +}; + +struct khoser_mem_chunk; + +struct kho_serialization { + struct page *fdt; + struct kho_mem_track track; + /* First chunk of serialized preserved memory map */ + struct khoser_mem_chunk *preserved_mem_map; +}; + +struct kho_out { + struct blocking_notifier_head chain_head; + struct mutex lock; /* protects KHO FDT finalization */ + struct kho_serialization ser; + bool finalized; + struct kho_debugfs dbg; +}; + +static struct kho_out kho_out = { + .chain_head = BLOCKING_NOTIFIER_INIT(kho_out.chain_head), + .lock = __MUTEX_INITIALIZER(kho_out.lock), + .ser = { + .track = { + .orders = XARRAY_INIT(kho_out.ser.track.orders, 0), + }, + }, + .finalized = false, +}; + +static void *xa_load_or_alloc(struct xarray *xa, unsigned long index) +{ + void *res = xa_load(xa, index); + + if (res) + return res; + + void *elm __free(free_page) = (void *)get_zeroed_page(GFP_KERNEL); + + if (!elm) + return ERR_PTR(-ENOMEM); + + if (WARN_ON(kho_scratch_overlap(virt_to_phys(elm), PAGE_SIZE))) + return ERR_PTR(-EINVAL); + + res = xa_cmpxchg(xa, index, NULL, elm, GFP_KERNEL); + if (xa_is_err(res)) + return ERR_PTR(xa_err(res)); + else if (res) + return res; + + return no_free_ptr(elm); +} + +static void __kho_unpreserve(struct kho_mem_track *track, unsigned long pfn, + unsigned long end_pfn) +{ + struct kho_mem_phys_bits *bits; + struct kho_mem_phys *physxa; + + while (pfn < end_pfn) { + const unsigned int order = + min(count_trailing_zeros(pfn), ilog2(end_pfn - pfn)); + const unsigned long pfn_high = pfn >> order; + + physxa = xa_load(&track->orders, order); + if (WARN_ON_ONCE(!physxa)) + return; + + bits = xa_load(&physxa->phys_bits, pfn_high / PRESERVE_BITS); + if (WARN_ON_ONCE(!bits)) + return; + + clear_bit(pfn_high % PRESERVE_BITS, bits->preserve); + + pfn += 1 << order; + } +} + +static int __kho_preserve_order(struct kho_mem_track *track, unsigned long pfn, + unsigned int order) +{ + struct kho_mem_phys_bits *bits; + struct kho_mem_phys *physxa, *new_physxa; + const unsigned long pfn_high = pfn >> order; + + might_sleep(); + + if (kho_out.finalized) + return -EBUSY; + + physxa = xa_load(&track->orders, order); + if (!physxa) { + int err; + + new_physxa = kzalloc(sizeof(*physxa), GFP_KERNEL); + if (!new_physxa) + return -ENOMEM; + + xa_init(&new_physxa->phys_bits); + physxa = xa_cmpxchg(&track->orders, order, NULL, new_physxa, + GFP_KERNEL); + + err = xa_err(physxa); + if (err || physxa) { + xa_destroy(&new_physxa->phys_bits); + kfree(new_physxa); + + if (err) + return err; + } else { + physxa = new_physxa; + } + } + + bits = xa_load_or_alloc(&physxa->phys_bits, pfn_high / PRESERVE_BITS); + if (IS_ERR(bits)) + return PTR_ERR(bits); + + set_bit(pfn_high % PRESERVE_BITS, bits->preserve); + + return 0; +} + +static struct page *kho_restore_page(phys_addr_t phys) +{ + struct page *page = pfn_to_online_page(PHYS_PFN(phys)); + union kho_page_info info; + unsigned int nr_pages; + + if (!page) + return NULL; + + info.page_private = page->private; + /* + * deserialize_bitmap() only sets the magic on the head page. This magic + * check also implicitly makes sure phys is order-aligned since for + * non-order-aligned phys addresses, magic will never be set. + */ + if (WARN_ON_ONCE(info.magic != KHO_PAGE_MAGIC || info.order > MAX_PAGE_ORDER)) + return NULL; + nr_pages = (1 << info.order); + + /* Clear private to make sure later restores on this page error out. */ + page->private = 0; + /* Head page gets refcount of 1. */ + set_page_count(page, 1); + + /* For higher order folios, tail pages get a page count of zero. */ + for (unsigned int i = 1; i < nr_pages; i++) + set_page_count(page + i, 0); + + if (info.order > 0) + prep_compound_page(page, info.order); + + adjust_managed_page_count(page, nr_pages); + return page; +} + +/** + * kho_restore_folio - recreates the folio from the preserved memory. + * @phys: physical address of the folio. + * + * Return: pointer to the struct folio on success, NULL on failure. + */ +struct folio *kho_restore_folio(phys_addr_t phys) +{ + struct page *page = kho_restore_page(phys); + + return page ? page_folio(page) : NULL; +} +EXPORT_SYMBOL_GPL(kho_restore_folio); + +/** + * kho_restore_pages - restore list of contiguous order 0 pages. + * @phys: physical address of the first page. + * @nr_pages: number of pages. + * + * Restore a contiguous list of order 0 pages that was preserved with + * kho_preserve_pages(). + * + * Return: 0 on success, error code on failure + */ +struct page *kho_restore_pages(phys_addr_t phys, unsigned int nr_pages) +{ + const unsigned long start_pfn = PHYS_PFN(phys); + const unsigned long end_pfn = start_pfn + nr_pages; + unsigned long pfn = start_pfn; + + while (pfn < end_pfn) { + const unsigned int order = + min(count_trailing_zeros(pfn), ilog2(end_pfn - pfn)); + struct page *page = kho_restore_page(PFN_PHYS(pfn)); + + if (!page) + return NULL; + split_page(page, order); + pfn += 1 << order; + } + + return pfn_to_page(start_pfn); +} +EXPORT_SYMBOL_GPL(kho_restore_pages); + +/* Serialize and deserialize struct kho_mem_phys across kexec + * + * Record all the bitmaps in a linked list of pages for the next kernel to + * process. Each chunk holds bitmaps of the same order and each block of bitmaps + * starts at a given physical address. This allows the bitmaps to be sparse. The + * xarray is used to store them in a tree while building up the data structure, + * but the KHO successor kernel only needs to process them once in order. + * + * All of this memory is normal kmalloc() memory and is not marked for + * preservation. The successor kernel will remain isolated to the scratch space + * until it completes processing this list. Once processed all the memory + * storing these ranges will be marked as free. + */ + +struct khoser_mem_bitmap_ptr { + phys_addr_t phys_start; + DECLARE_KHOSER_PTR(bitmap, struct kho_mem_phys_bits *); +}; + +struct khoser_mem_chunk_hdr { + DECLARE_KHOSER_PTR(next, struct khoser_mem_chunk *); + unsigned int order; + unsigned int num_elms; +}; + +#define KHOSER_BITMAP_SIZE \ + ((PAGE_SIZE - sizeof(struct khoser_mem_chunk_hdr)) / \ + sizeof(struct khoser_mem_bitmap_ptr)) + +struct khoser_mem_chunk { + struct khoser_mem_chunk_hdr hdr; + struct khoser_mem_bitmap_ptr bitmaps[KHOSER_BITMAP_SIZE]; +}; + +static_assert(sizeof(struct khoser_mem_chunk) == PAGE_SIZE); + +static struct khoser_mem_chunk *new_chunk(struct khoser_mem_chunk *cur_chunk, + unsigned long order) +{ + struct khoser_mem_chunk *chunk __free(free_page) = NULL; + + chunk = (void *)get_zeroed_page(GFP_KERNEL); + if (!chunk) + return ERR_PTR(-ENOMEM); + + if (WARN_ON(kho_scratch_overlap(virt_to_phys(chunk), PAGE_SIZE))) + return ERR_PTR(-EINVAL); + + chunk->hdr.order = order; + if (cur_chunk) + KHOSER_STORE_PTR(cur_chunk->hdr.next, chunk); + return no_free_ptr(chunk); +} + +static void kho_mem_ser_free(struct khoser_mem_chunk *first_chunk) +{ + struct khoser_mem_chunk *chunk = first_chunk; + + while (chunk) { + struct khoser_mem_chunk *tmp = chunk; + + chunk = KHOSER_LOAD_PTR(chunk->hdr.next); + free_page((unsigned long)tmp); + } +} + +static int kho_mem_serialize(struct kho_serialization *ser) +{ + struct khoser_mem_chunk *first_chunk = NULL; + struct khoser_mem_chunk *chunk = NULL; + struct kho_mem_phys *physxa; + unsigned long order; + int err = -ENOMEM; + + xa_for_each(&ser->track.orders, order, physxa) { + struct kho_mem_phys_bits *bits; + unsigned long phys; + + chunk = new_chunk(chunk, order); + if (IS_ERR(chunk)) { + err = PTR_ERR(chunk); + goto err_free; + } + + if (!first_chunk) + first_chunk = chunk; + + xa_for_each(&physxa->phys_bits, phys, bits) { + struct khoser_mem_bitmap_ptr *elm; + + if (chunk->hdr.num_elms == ARRAY_SIZE(chunk->bitmaps)) { + chunk = new_chunk(chunk, order); + if (IS_ERR(chunk)) { + err = PTR_ERR(chunk); + goto err_free; + } + } + + elm = &chunk->bitmaps[chunk->hdr.num_elms]; + chunk->hdr.num_elms++; + elm->phys_start = (phys * PRESERVE_BITS) + << (order + PAGE_SHIFT); + KHOSER_STORE_PTR(elm->bitmap, bits); + } + } + + ser->preserved_mem_map = first_chunk; + + return 0; + +err_free: + kho_mem_ser_free(first_chunk); + return err; +} + +static void __init deserialize_bitmap(unsigned int order, + struct khoser_mem_bitmap_ptr *elm) +{ + struct kho_mem_phys_bits *bitmap = KHOSER_LOAD_PTR(elm->bitmap); + unsigned long bit; + + for_each_set_bit(bit, bitmap->preserve, PRESERVE_BITS) { + u64 sz = 1UL << (order + PAGE_SHIFT); + phys_addr_t phys = + elm->phys_start + (bit << (order + PAGE_SHIFT)); + struct page *page = phys_to_page(phys); + union kho_page_info info; + + memblock_reserve(phys, sz); + memblock_reserved_mark_noinit(phys, sz); + info.magic = KHO_PAGE_MAGIC; + info.order = order; + page->private = info.page_private; + } +} + +static void __init kho_mem_deserialize(const void *fdt) +{ + struct khoser_mem_chunk *chunk; + const phys_addr_t *mem; + int len; + + mem = fdt_getprop(fdt, 0, PROP_PRESERVED_MEMORY_MAP, &len); + + if (!mem || len != sizeof(*mem)) { + pr_err("failed to get preserved memory bitmaps\n"); + return; + } + + chunk = *mem ? phys_to_virt(*mem) : NULL; + while (chunk) { + unsigned int i; + + for (i = 0; i != chunk->hdr.num_elms; i++) + deserialize_bitmap(chunk->hdr.order, + &chunk->bitmaps[i]); + chunk = KHOSER_LOAD_PTR(chunk->hdr.next); + } +} + +/* + * With KHO enabled, memory can become fragmented because KHO regions may + * be anywhere in physical address space. The scratch regions give us a + * safe zones that we will never see KHO allocations from. This is where we + * can later safely load our new kexec images into and then use the scratch + * area for early allocations that happen before page allocator is + * initialized. + */ +struct kho_scratch *kho_scratch; +unsigned int kho_scratch_cnt; + +/* + * The scratch areas are scaled by default as percent of memory allocated from + * memblock. A user can override the scale with command line parameter: + * + * kho_scratch=N% + * + * It is also possible to explicitly define size for a lowmem, a global and + * per-node scratch areas: + * + * kho_scratch=l[KMG],n[KMG],m[KMG] + * + * The explicit size definition takes precedence over scale definition. + */ +static unsigned int scratch_scale __initdata = 200; +static phys_addr_t scratch_size_global __initdata; +static phys_addr_t scratch_size_pernode __initdata; +static phys_addr_t scratch_size_lowmem __initdata; + +static int __init kho_parse_scratch_size(char *p) +{ + size_t len; + unsigned long sizes[3]; + size_t total_size = 0; + int i; + + if (!p) + return -EINVAL; + + len = strlen(p); + if (!len) + return -EINVAL; + + /* parse nn% */ + if (p[len - 1] == '%') { + /* unsigned int max is 4,294,967,295, 10 chars */ + char s_scale[11] = {}; + int ret = 0; + + if (len > ARRAY_SIZE(s_scale)) + return -EINVAL; + + memcpy(s_scale, p, len - 1); + ret = kstrtouint(s_scale, 10, &scratch_scale); + if (!ret) + pr_notice("scratch scale is %d%%\n", scratch_scale); + return ret; + } + + /* parse ll[KMG],mm[KMG],nn[KMG] */ + for (i = 0; i < ARRAY_SIZE(sizes); i++) { + char *endp = p; + + if (i > 0) { + if (*p != ',') + return -EINVAL; + p += 1; + } + + sizes[i] = memparse(p, &endp); + if (endp == p) + return -EINVAL; + p = endp; + total_size += sizes[i]; + } + + if (!total_size) + return -EINVAL; + + /* The string should be fully consumed by now. */ + if (*p) + return -EINVAL; + + scratch_size_lowmem = sizes[0]; + scratch_size_global = sizes[1]; + scratch_size_pernode = sizes[2]; + scratch_scale = 0; + + pr_notice("scratch areas: lowmem: %lluMiB global: %lluMiB pernode: %lldMiB\n", + (u64)(scratch_size_lowmem >> 20), + (u64)(scratch_size_global >> 20), + (u64)(scratch_size_pernode >> 20)); + + return 0; +} +early_param("kho_scratch", kho_parse_scratch_size); + +static void __init scratch_size_update(void) +{ + /* + * If fixed sizes are not provided via command line, calculate them + * now. + */ + if (scratch_scale) { + phys_addr_t size; + + size = memblock_reserved_kern_size(ARCH_LOW_ADDRESS_LIMIT, + NUMA_NO_NODE); + size = size * scratch_scale / 100; + scratch_size_lowmem = size; + + size = memblock_reserved_kern_size(MEMBLOCK_ALLOC_ANYWHERE, + NUMA_NO_NODE); + size = size * scratch_scale / 100 - scratch_size_lowmem; + scratch_size_global = size; + } + + /* + * Scratch areas are released as MIGRATE_CMA. Round them up to the right + * size. + */ + scratch_size_lowmem = round_up(scratch_size_lowmem, CMA_MIN_ALIGNMENT_BYTES); + scratch_size_global = round_up(scratch_size_global, CMA_MIN_ALIGNMENT_BYTES); +} + +static phys_addr_t __init scratch_size_node(int nid) +{ + phys_addr_t size; + + if (scratch_scale) { + size = memblock_reserved_kern_size(MEMBLOCK_ALLOC_ANYWHERE, + nid); + size = size * scratch_scale / 100; + } else { + size = scratch_size_pernode; + } + + return round_up(size, CMA_MIN_ALIGNMENT_BYTES); +} + +/** + * kho_reserve_scratch - Reserve a contiguous chunk of memory for kexec + * + * With KHO we can preserve arbitrary pages in the system. To ensure we still + * have a large contiguous region of memory when we search the physical address + * space for target memory, let's make sure we always have a large CMA region + * active. This CMA region will only be used for movable pages which are not a + * problem for us during KHO because we can just move them somewhere else. + */ +static void __init kho_reserve_scratch(void) +{ + phys_addr_t addr, size; + int nid, i = 0; + + if (!kho_enable) + return; + + scratch_size_update(); + + /* FIXME: deal with node hot-plug/remove */ + kho_scratch_cnt = nodes_weight(node_states[N_MEMORY]) + 2; + size = kho_scratch_cnt * sizeof(*kho_scratch); + kho_scratch = memblock_alloc(size, PAGE_SIZE); + if (!kho_scratch) + goto err_disable_kho; + + /* + * reserve scratch area in low memory for lowmem allocations in the + * next kernel + */ + size = scratch_size_lowmem; + addr = memblock_phys_alloc_range(size, CMA_MIN_ALIGNMENT_BYTES, 0, + ARCH_LOW_ADDRESS_LIMIT); + if (!addr) + goto err_free_scratch_desc; + + kho_scratch[i].addr = addr; + kho_scratch[i].size = size; + i++; + + /* reserve large contiguous area for allocations without nid */ + size = scratch_size_global; + addr = memblock_phys_alloc(size, CMA_MIN_ALIGNMENT_BYTES); + if (!addr) + goto err_free_scratch_areas; + + kho_scratch[i].addr = addr; + kho_scratch[i].size = size; + i++; + + /* + * Loop over nodes that have both memory and are online. Skip + * memoryless nodes, as we can not allocate scratch areas there. + */ + for_each_node_state(nid, N_MEMORY) { + size = scratch_size_node(nid); + addr = memblock_alloc_range_nid(size, CMA_MIN_ALIGNMENT_BYTES, + 0, MEMBLOCK_ALLOC_ACCESSIBLE, + nid, true); + if (!addr) + goto err_free_scratch_areas; + + kho_scratch[i].addr = addr; + kho_scratch[i].size = size; + i++; + } + + return; + +err_free_scratch_areas: + for (i--; i >= 0; i--) + memblock_phys_free(kho_scratch[i].addr, kho_scratch[i].size); +err_free_scratch_desc: + memblock_free(kho_scratch, kho_scratch_cnt * sizeof(*kho_scratch)); +err_disable_kho: + pr_warn("Failed to reserve scratch area, disabling kexec handover\n"); + kho_enable = false; +} + +/** + * kho_add_subtree - record the physical address of a sub FDT in KHO root tree. + * @ser: serialization control object passed by KHO notifiers. + * @name: name of the sub tree. + * @fdt: the sub tree blob. + * + * Creates a new child node named @name in KHO root FDT and records + * the physical address of @fdt. The pages of @fdt must also be preserved + * by KHO for the new kernel to retrieve it after kexec. + * + * A debugfs blob entry is also created at + * ``/sys/kernel/debug/kho/out/sub_fdts/@name`` when kernel is configured with + * CONFIG_KEXEC_HANDOVER_DEBUGFS + * + * Return: 0 on success, error code on failure + */ +int kho_add_subtree(struct kho_serialization *ser, const char *name, void *fdt) +{ + int err = 0; + u64 phys = (u64)virt_to_phys(fdt); + void *root = page_to_virt(ser->fdt); + + err |= fdt_begin_node(root, name); + err |= fdt_property(root, PROP_SUB_FDT, &phys, sizeof(phys)); + err |= fdt_end_node(root); + + if (err) + return err; + + return kho_debugfs_fdt_add(&kho_out.dbg, name, fdt, false); +} +EXPORT_SYMBOL_GPL(kho_add_subtree); + +int register_kho_notifier(struct notifier_block *nb) +{ + return blocking_notifier_chain_register(&kho_out.chain_head, nb); +} +EXPORT_SYMBOL_GPL(register_kho_notifier); + +int unregister_kho_notifier(struct notifier_block *nb) +{ + return blocking_notifier_chain_unregister(&kho_out.chain_head, nb); +} +EXPORT_SYMBOL_GPL(unregister_kho_notifier); + +/** + * kho_preserve_folio - preserve a folio across kexec. + * @folio: folio to preserve. + * + * Instructs KHO to preserve the whole folio across kexec. The order + * will be preserved as well. + * + * Return: 0 on success, error code on failure + */ +int kho_preserve_folio(struct folio *folio) +{ + const unsigned long pfn = folio_pfn(folio); + const unsigned int order = folio_order(folio); + struct kho_mem_track *track = &kho_out.ser.track; + + if (WARN_ON(kho_scratch_overlap(pfn << PAGE_SHIFT, PAGE_SIZE << order))) + return -EINVAL; + + return __kho_preserve_order(track, pfn, order); +} +EXPORT_SYMBOL_GPL(kho_preserve_folio); + +/** + * kho_preserve_pages - preserve contiguous pages across kexec + * @page: first page in the list. + * @nr_pages: number of pages. + * + * Preserve a contiguous list of order 0 pages. Must be restored using + * kho_restore_pages() to ensure the pages are restored properly as order 0. + * + * Return: 0 on success, error code on failure + */ +int kho_preserve_pages(struct page *page, unsigned int nr_pages) +{ + struct kho_mem_track *track = &kho_out.ser.track; + const unsigned long start_pfn = page_to_pfn(page); + const unsigned long end_pfn = start_pfn + nr_pages; + unsigned long pfn = start_pfn; + unsigned long failed_pfn = 0; + int err = 0; + + if (WARN_ON(kho_scratch_overlap(start_pfn << PAGE_SHIFT, + nr_pages << PAGE_SHIFT))) { + return -EINVAL; + } + + while (pfn < end_pfn) { + const unsigned int order = + min(count_trailing_zeros(pfn), ilog2(end_pfn - pfn)); + + err = __kho_preserve_order(track, pfn, order); + if (err) { + failed_pfn = pfn; + break; + } + + pfn += 1 << order; + } + + if (err) + __kho_unpreserve(track, start_pfn, failed_pfn); + + return err; +} +EXPORT_SYMBOL_GPL(kho_preserve_pages); + +struct kho_vmalloc_hdr { + DECLARE_KHOSER_PTR(next, struct kho_vmalloc_chunk *); +}; + +#define KHO_VMALLOC_SIZE \ + ((PAGE_SIZE - sizeof(struct kho_vmalloc_hdr)) / \ + sizeof(phys_addr_t)) + +struct kho_vmalloc_chunk { + struct kho_vmalloc_hdr hdr; + phys_addr_t phys[KHO_VMALLOC_SIZE]; +}; + +static_assert(sizeof(struct kho_vmalloc_chunk) == PAGE_SIZE); + +/* vmalloc flags KHO supports */ +#define KHO_VMALLOC_SUPPORTED_FLAGS (VM_ALLOC | VM_ALLOW_HUGE_VMAP) + +/* KHO internal flags for vmalloc preservations */ +#define KHO_VMALLOC_ALLOC 0x0001 +#define KHO_VMALLOC_HUGE_VMAP 0x0002 + +static unsigned short vmalloc_flags_to_kho(unsigned int vm_flags) +{ + unsigned short kho_flags = 0; + + if (vm_flags & VM_ALLOC) + kho_flags |= KHO_VMALLOC_ALLOC; + if (vm_flags & VM_ALLOW_HUGE_VMAP) + kho_flags |= KHO_VMALLOC_HUGE_VMAP; + + return kho_flags; +} + +static unsigned int kho_flags_to_vmalloc(unsigned short kho_flags) +{ + unsigned int vm_flags = 0; + + if (kho_flags & KHO_VMALLOC_ALLOC) + vm_flags |= VM_ALLOC; + if (kho_flags & KHO_VMALLOC_HUGE_VMAP) + vm_flags |= VM_ALLOW_HUGE_VMAP; + + return vm_flags; +} + +static struct kho_vmalloc_chunk *new_vmalloc_chunk(struct kho_vmalloc_chunk *cur) +{ + struct kho_vmalloc_chunk *chunk; + int err; + + chunk = (struct kho_vmalloc_chunk *)get_zeroed_page(GFP_KERNEL); + if (!chunk) + return NULL; + + err = kho_preserve_pages(virt_to_page(chunk), 1); + if (err) + goto err_free; + if (cur) + KHOSER_STORE_PTR(cur->hdr.next, chunk); + return chunk; + +err_free: + free_page((unsigned long)chunk); + return NULL; +} + +static void kho_vmalloc_unpreserve_chunk(struct kho_vmalloc_chunk *chunk, + unsigned short order) +{ + struct kho_mem_track *track = &kho_out.ser.track; + unsigned long pfn = PHYS_PFN(virt_to_phys(chunk)); + + __kho_unpreserve(track, pfn, pfn + 1); + + for (int i = 0; i < ARRAY_SIZE(chunk->phys) && chunk->phys[i]; i++) { + pfn = PHYS_PFN(chunk->phys[i]); + __kho_unpreserve(track, pfn, pfn + (1 << order)); + } +} + +static void kho_vmalloc_free_chunks(struct kho_vmalloc *kho_vmalloc) +{ + struct kho_vmalloc_chunk *chunk = KHOSER_LOAD_PTR(kho_vmalloc->first); + + while (chunk) { + struct kho_vmalloc_chunk *tmp = chunk; + + kho_vmalloc_unpreserve_chunk(chunk, kho_vmalloc->order); + + chunk = KHOSER_LOAD_PTR(chunk->hdr.next); + free_page((unsigned long)tmp); + } +} + +/** + * kho_preserve_vmalloc - preserve memory allocated with vmalloc() across kexec + * @ptr: pointer to the area in vmalloc address space + * @preservation: placeholder for preservation metadata + * + * Instructs KHO to preserve the area in vmalloc address space at @ptr. The + * physical pages mapped at @ptr will be preserved and on successful return + * @preservation will hold the physical address of a structure that describes + * the preservation. + * + * NOTE: The memory allocated with vmalloc_node() variants cannot be reliably + * restored on the same node + * + * Return: 0 on success, error code on failure + */ +int kho_preserve_vmalloc(void *ptr, struct kho_vmalloc *preservation) +{ + struct kho_vmalloc_chunk *chunk; + struct vm_struct *vm = find_vm_area(ptr); + unsigned int order, flags, nr_contig_pages; + unsigned int idx = 0; + int err; + + if (!vm) + return -EINVAL; + + if (vm->flags & ~KHO_VMALLOC_SUPPORTED_FLAGS) + return -EOPNOTSUPP; + + flags = vmalloc_flags_to_kho(vm->flags); + order = get_vm_area_page_order(vm); + + chunk = new_vmalloc_chunk(NULL); + if (!chunk) + return -ENOMEM; + KHOSER_STORE_PTR(preservation->first, chunk); + + nr_contig_pages = (1 << order); + for (int i = 0; i < vm->nr_pages; i += nr_contig_pages) { + phys_addr_t phys = page_to_phys(vm->pages[i]); + + err = kho_preserve_pages(vm->pages[i], nr_contig_pages); + if (err) + goto err_free; + + chunk->phys[idx++] = phys; + if (idx == ARRAY_SIZE(chunk->phys)) { + chunk = new_vmalloc_chunk(chunk); + if (!chunk) + goto err_free; + idx = 0; + } + } + + preservation->total_pages = vm->nr_pages; + preservation->flags = flags; + preservation->order = order; + + return 0; + +err_free: + kho_vmalloc_free_chunks(preservation); + return err; +} +EXPORT_SYMBOL_GPL(kho_preserve_vmalloc); + +/** + * kho_restore_vmalloc - recreates and populates an area in vmalloc address + * space from the preserved memory. + * @preservation: preservation metadata. + * + * Recreates an area in vmalloc address space and populates it with memory that + * was preserved using kho_preserve_vmalloc(). + * + * Return: pointer to the area in the vmalloc address space, NULL on failure. + */ +void *kho_restore_vmalloc(const struct kho_vmalloc *preservation) +{ + struct kho_vmalloc_chunk *chunk = KHOSER_LOAD_PTR(preservation->first); + unsigned int align, order, shift, vm_flags; + unsigned long total_pages, contig_pages; + unsigned long addr, size; + struct vm_struct *area; + struct page **pages; + unsigned int idx = 0; + int err; + + vm_flags = kho_flags_to_vmalloc(preservation->flags); + if (vm_flags & ~KHO_VMALLOC_SUPPORTED_FLAGS) + return NULL; + + total_pages = preservation->total_pages; + pages = kvmalloc_array(total_pages, sizeof(*pages), GFP_KERNEL); + if (!pages) + return NULL; + order = preservation->order; + contig_pages = (1 << order); + shift = PAGE_SHIFT + order; + align = 1 << shift; + + while (chunk) { + struct page *page; + + for (int i = 0; i < ARRAY_SIZE(chunk->phys) && chunk->phys[i]; i++) { + phys_addr_t phys = chunk->phys[i]; + + if (idx + contig_pages > total_pages) + goto err_free_pages_array; + + page = kho_restore_pages(phys, contig_pages); + if (!page) + goto err_free_pages_array; + + for (int j = 0; j < contig_pages; j++) + pages[idx++] = page; + + phys += contig_pages * PAGE_SIZE; + } + + page = kho_restore_pages(virt_to_phys(chunk), 1); + if (!page) + goto err_free_pages_array; + chunk = KHOSER_LOAD_PTR(chunk->hdr.next); + __free_page(page); + } + + if (idx != total_pages) + goto err_free_pages_array; + + area = __get_vm_area_node(total_pages * PAGE_SIZE, align, shift, + vm_flags, VMALLOC_START, VMALLOC_END, + NUMA_NO_NODE, GFP_KERNEL, + __builtin_return_address(0)); + if (!area) + goto err_free_pages_array; + + addr = (unsigned long)area->addr; + size = get_vm_area_size(area); + err = vmap_pages_range(addr, addr + size, PAGE_KERNEL, pages, shift); + if (err) + goto err_free_vm_area; + + area->nr_pages = total_pages; + area->pages = pages; + + return area->addr; + +err_free_vm_area: + free_vm_area(area); +err_free_pages_array: + kvfree(pages); + return NULL; +} +EXPORT_SYMBOL_GPL(kho_restore_vmalloc); + +static int __kho_abort(void) +{ + int err; + unsigned long order; + struct kho_mem_phys *physxa; + + xa_for_each(&kho_out.ser.track.orders, order, physxa) { + struct kho_mem_phys_bits *bits; + unsigned long phys; + + xa_for_each(&physxa->phys_bits, phys, bits) + free_page((unsigned long)bits); + + xa_destroy(&physxa->phys_bits); + kfree(physxa); + } + xa_destroy(&kho_out.ser.track.orders); + + if (kho_out.ser.preserved_mem_map) { + kho_mem_ser_free(kho_out.ser.preserved_mem_map); + kho_out.ser.preserved_mem_map = NULL; + } + + err = blocking_notifier_call_chain(&kho_out.chain_head, KEXEC_KHO_ABORT, + NULL); + err = notifier_to_errno(err); + + if (err) + pr_err("Failed to abort KHO finalization: %d\n", err); + + return err; +} + +int kho_abort(void) +{ + int ret = 0; + + if (!kho_enable) + return -EOPNOTSUPP; + + guard(mutex)(&kho_out.lock); + if (!kho_out.finalized) + return -ENOENT; + + ret = __kho_abort(); + if (ret) + return ret; + + kho_out.finalized = false; + kho_debugfs_cleanup(&kho_out.dbg); + + return 0; +} + +static int __kho_finalize(void) +{ + int err = 0; + u64 *preserved_mem_map; + void *fdt = page_to_virt(kho_out.ser.fdt); + + err |= fdt_create(fdt, PAGE_SIZE); + err |= fdt_finish_reservemap(fdt); + err |= fdt_begin_node(fdt, ""); + err |= fdt_property_string(fdt, "compatible", KHO_FDT_COMPATIBLE); + /** + * Reserve the preserved-memory-map property in the root FDT, so + * that all property definitions will precede subnodes created by + * KHO callers. + */ + err |= fdt_property_placeholder(fdt, PROP_PRESERVED_MEMORY_MAP, + sizeof(*preserved_mem_map), + (void **)&preserved_mem_map); + if (err) + goto abort; + + err = kho_preserve_folio(page_folio(kho_out.ser.fdt)); + if (err) + goto abort; + + err = blocking_notifier_call_chain(&kho_out.chain_head, + KEXEC_KHO_FINALIZE, &kho_out.ser); + err = notifier_to_errno(err); + if (err) + goto abort; + + err = kho_mem_serialize(&kho_out.ser); + if (err) + goto abort; + + *preserved_mem_map = (u64)virt_to_phys(kho_out.ser.preserved_mem_map); + + err |= fdt_end_node(fdt); + err |= fdt_finish(fdt); + +abort: + if (err) { + pr_err("Failed to convert KHO state tree: %d\n", err); + __kho_abort(); + } + + return err; +} + +int kho_finalize(void) +{ + int ret; + + if (!kho_enable) + return -EOPNOTSUPP; + + guard(mutex)(&kho_out.lock); + if (kho_out.finalized) + return -EEXIST; + + ret = __kho_finalize(); + if (ret) + return ret; + + kho_out.finalized = true; + + return kho_debugfs_fdt_add(&kho_out.dbg, "fdt", + page_to_virt(kho_out.ser.fdt), true); +} + +bool kho_finalized(void) +{ + guard(mutex)(&kho_out.lock); + return kho_out.finalized; +} + +struct kho_in { + phys_addr_t fdt_phys; + phys_addr_t scratch_phys; + struct kho_debugfs dbg; +}; + +static struct kho_in kho_in = { +}; + +static const void *kho_get_fdt(void) +{ + return kho_in.fdt_phys ? phys_to_virt(kho_in.fdt_phys) : NULL; +} + +/** + * is_kho_boot - check if current kernel was booted via KHO-enabled + * kexec + * + * This function checks if the current kernel was loaded through a kexec + * operation with KHO enabled, by verifying that a valid KHO FDT + * was passed. + * + * Note: This function returns reliable results only after + * kho_populate() has been called during early boot. Before that, + * it may return false even if KHO data is present. + * + * Return: true if booted via KHO-enabled kexec, false otherwise + */ +bool is_kho_boot(void) +{ + return !!kho_in.fdt_phys; +} +EXPORT_SYMBOL_GPL(is_kho_boot); + +/** + * kho_retrieve_subtree - retrieve a preserved sub FDT by its name. + * @name: the name of the sub FDT passed to kho_add_subtree(). + * @phys: if found, the physical address of the sub FDT is stored in @phys. + * + * Retrieve a preserved sub FDT named @name and store its physical + * address in @phys. + * + * Return: 0 on success, error code on failure + */ +int kho_retrieve_subtree(const char *name, phys_addr_t *phys) +{ + const void *fdt = kho_get_fdt(); + const u64 *val; + int offset, len; + + if (!fdt) + return -ENOENT; + + if (!phys) + return -EINVAL; + + offset = fdt_subnode_offset(fdt, 0, name); + if (offset < 0) + return -ENOENT; + + val = fdt_getprop(fdt, offset, PROP_SUB_FDT, &len); + if (!val || len != sizeof(*val)) + return -EINVAL; + + *phys = (phys_addr_t)*val; + + return 0; +} +EXPORT_SYMBOL_GPL(kho_retrieve_subtree); + +static __init int kho_init(void) +{ + int err = 0; + const void *fdt = kho_get_fdt(); + + if (!kho_enable) + return 0; + + kho_out.ser.fdt = alloc_page(GFP_KERNEL); + if (!kho_out.ser.fdt) { + err = -ENOMEM; + goto err_free_scratch; + } + + err = kho_debugfs_init(); + if (err) + goto err_free_fdt; + + err = kho_out_debugfs_init(&kho_out.dbg); + if (err) + goto err_free_fdt; + + if (fdt) { + kho_in_debugfs_init(&kho_in.dbg, fdt); + return 0; + } + + for (int i = 0; i < kho_scratch_cnt; i++) { + unsigned long base_pfn = PHYS_PFN(kho_scratch[i].addr); + unsigned long count = kho_scratch[i].size >> PAGE_SHIFT; + unsigned long pfn; + + for (pfn = base_pfn; pfn < base_pfn + count; + pfn += pageblock_nr_pages) + init_cma_reserved_pageblock(pfn_to_page(pfn)); + } + + return 0; + +err_free_fdt: + put_page(kho_out.ser.fdt); + kho_out.ser.fdt = NULL; +err_free_scratch: + for (int i = 0; i < kho_scratch_cnt; i++) { + void *start = __va(kho_scratch[i].addr); + void *end = start + kho_scratch[i].size; + + free_reserved_area(start, end, -1, ""); + } + kho_enable = false; + return err; +} +late_initcall(kho_init); + +static void __init kho_release_scratch(void) +{ + phys_addr_t start, end; + u64 i; + + memmap_init_kho_scratch_pages(); + + /* + * Mark scratch mem as CMA before we return it. That way we + * ensure that no kernel allocations happen on it. That means + * we can reuse it as scratch memory again later. + */ + __for_each_mem_range(i, &memblock.memory, NULL, NUMA_NO_NODE, + MEMBLOCK_KHO_SCRATCH, &start, &end, NULL) { + ulong start_pfn = pageblock_start_pfn(PFN_DOWN(start)); + ulong end_pfn = pageblock_align(PFN_UP(end)); + ulong pfn; + + for (pfn = start_pfn; pfn < end_pfn; pfn += pageblock_nr_pages) + init_pageblock_migratetype(pfn_to_page(pfn), + MIGRATE_CMA, false); + } +} + +void __init kho_memory_init(void) +{ + struct folio *folio; + + if (is_kdump_kernel()) { + kho_enable = false; + pr_info("disabled in the kdump kernel\n"); + return; + } + + if (kho_in.scratch_phys) { + kho_scratch = phys_to_virt(kho_in.scratch_phys); + kho_release_scratch(); + + kho_mem_deserialize(kho_get_fdt()); + folio = kho_restore_folio(kho_in.fdt_phys); + if (!folio) + pr_warn("failed to restore folio for KHO fdt\n"); + } else { + kho_reserve_scratch(); + } +} + +void __init kho_populate(phys_addr_t fdt_phys, u64 fdt_len, + phys_addr_t scratch_phys, u64 scratch_len) +{ + void *fdt = NULL; + struct kho_scratch *scratch = NULL; + int err = 0; + unsigned int scratch_cnt = scratch_len / sizeof(*kho_scratch); + + /* Validate the input FDT */ + fdt = early_memremap(fdt_phys, fdt_len); + if (!fdt) { + pr_warn("setup: failed to memremap FDT (0x%llx)\n", fdt_phys); + err = -EFAULT; + goto out; + } + err = fdt_check_header(fdt); + if (err) { + pr_warn("setup: handover FDT (0x%llx) is invalid: %d\n", + fdt_phys, err); + err = -EINVAL; + goto out; + } + err = fdt_node_check_compatible(fdt, 0, KHO_FDT_COMPATIBLE); + if (err) { + pr_warn("setup: handover FDT (0x%llx) is incompatible with '%s': %d\n", + fdt_phys, KHO_FDT_COMPATIBLE, err); + err = -EINVAL; + goto out; + } + + scratch = early_memremap(scratch_phys, scratch_len); + if (!scratch) { + pr_warn("setup: failed to memremap scratch (phys=0x%llx, len=%lld)\n", + scratch_phys, scratch_len); + err = -EFAULT; + goto out; + } + + /* + * We pass a safe contiguous blocks of memory to use for early boot + * purporses from the previous kernel so that we can resize the + * memblock array as needed. + */ + for (int i = 0; i < scratch_cnt; i++) { + struct kho_scratch *area = &scratch[i]; + u64 size = area->size; + + memblock_add(area->addr, size); + err = memblock_mark_kho_scratch(area->addr, size); + if (WARN_ON(err)) { + pr_warn("failed to mark the scratch region 0x%pa+0x%pa: %d", + &area->addr, &size, err); + goto out; + } + pr_debug("Marked 0x%pa+0x%pa as scratch", &area->addr, &size); + } + + memblock_reserve(scratch_phys, scratch_len); + + /* + * Now that we have a viable region of scratch memory, let's tell + * the memblocks allocator to only use that for any allocations. + * That way we ensure that nothing scribbles over in use data while + * we initialize the page tables which we will need to ingest all + * memory reservations from the previous kernel. + */ + memblock_set_kho_scratch_only(); + + kho_in.fdt_phys = fdt_phys; + kho_in.scratch_phys = scratch_phys; + kho_scratch_cnt = scratch_cnt; + pr_info("found kexec handover data. Will skip init for some devices\n"); + +out: + if (fdt) + early_memunmap(fdt, fdt_len); + if (scratch) + early_memunmap(scratch, scratch_len); + if (err) + pr_warn("disabling KHO revival: %d\n", err); +} + +/* Helper functions for kexec_file_load */ + +int kho_fill_kimage(struct kimage *image) +{ + ssize_t scratch_size; + int err = 0; + struct kexec_buf scratch; + + if (!kho_out.finalized) + return 0; + + image->kho.fdt = page_to_phys(kho_out.ser.fdt); + + scratch_size = sizeof(*kho_scratch) * kho_scratch_cnt; + scratch = (struct kexec_buf){ + .image = image, + .buffer = kho_scratch, + .bufsz = scratch_size, + .mem = KEXEC_BUF_MEM_UNKNOWN, + .memsz = scratch_size, + .buf_align = SZ_64K, /* Makes it easier to map */ + .buf_max = ULONG_MAX, + .top_down = true, + }; + err = kexec_add_buffer(&scratch); + if (err) + return err; + image->kho.scratch = &image->segment[image->nr_segments - 1]; + + return 0; +} + +static int kho_walk_scratch(struct kexec_buf *kbuf, + int (*func)(struct resource *, void *)) +{ + int ret = 0; + int i; + + for (i = 0; i < kho_scratch_cnt; i++) { + struct resource res = { + .start = kho_scratch[i].addr, + .end = kho_scratch[i].addr + kho_scratch[i].size - 1, + }; + + /* Try to fit the kimage into our KHO scratch region */ + ret = func(&res, kbuf); + if (ret) + break; + } + + return ret; +} + +int kho_locate_mem_hole(struct kexec_buf *kbuf, + int (*func)(struct resource *, void *)) +{ + int ret; + + if (!kho_enable || kbuf->image->type == KEXEC_TYPE_CRASH) + return 1; + + ret = kho_walk_scratch(kbuf, func); + + return ret == 1 ? 0 : -EADDRNOTAVAIL; +} diff --git a/kernel/liveupdate/kexec_handover_debug.c b/kernel/liveupdate/kexec_handover_debug.c new file mode 100644 index 000000000000..6efb696f5426 --- /dev/null +++ b/kernel/liveupdate/kexec_handover_debug.c @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * kexec_handover_debug.c - kexec handover optional debug functionality + * Copyright (C) 2025 Google LLC, Pasha Tatashin + */ + +#define pr_fmt(fmt) "KHO: " fmt + +#include "kexec_handover_internal.h" + +bool kho_scratch_overlap(phys_addr_t phys, size_t size) +{ + phys_addr_t scratch_start, scratch_end; + unsigned int i; + + for (i = 0; i < kho_scratch_cnt; i++) { + scratch_start = kho_scratch[i].addr; + scratch_end = kho_scratch[i].addr + kho_scratch[i].size; + + if (phys < scratch_end && (phys + size) > scratch_start) + return true; + } + + return false; +} diff --git a/kernel/liveupdate/kexec_handover_debugfs.c b/kernel/liveupdate/kexec_handover_debugfs.c new file mode 100644 index 000000000000..a91b279f1b23 --- /dev/null +++ b/kernel/liveupdate/kexec_handover_debugfs.c @@ -0,0 +1,216 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * kexec_handover_debugfs.c - kexec handover debugfs interfaces + * Copyright (C) 2023 Alexander Graf + * Copyright (C) 2025 Microsoft Corporation, Mike Rapoport + * Copyright (C) 2025 Google LLC, Changyuan Lyu + * Copyright (C) 2025 Google LLC, Pasha Tatashin + */ + +#define pr_fmt(fmt) "KHO: " fmt + +#include +#include +#include +#include +#include "kexec_handover_internal.h" + +static struct dentry *debugfs_root; + +struct fdt_debugfs { + struct list_head list; + struct debugfs_blob_wrapper wrapper; + struct dentry *file; +}; + +static int __kho_debugfs_fdt_add(struct list_head *list, struct dentry *dir, + const char *name, const void *fdt) +{ + struct fdt_debugfs *f; + struct dentry *file; + + f = kmalloc(sizeof(*f), GFP_KERNEL); + if (!f) + return -ENOMEM; + + f->wrapper.data = (void *)fdt; + f->wrapper.size = fdt_totalsize(fdt); + + file = debugfs_create_blob(name, 0400, dir, &f->wrapper); + if (IS_ERR(file)) { + kfree(f); + return PTR_ERR(file); + } + + f->file = file; + list_add(&f->list, list); + + return 0; +} + +int kho_debugfs_fdt_add(struct kho_debugfs *dbg, const char *name, + const void *fdt, bool root) +{ + struct dentry *dir; + + if (root) + dir = dbg->dir; + else + dir = dbg->sub_fdt_dir; + + return __kho_debugfs_fdt_add(&dbg->fdt_list, dir, name, fdt); +} + +void kho_debugfs_cleanup(struct kho_debugfs *dbg) +{ + struct fdt_debugfs *ff, *tmp; + + list_for_each_entry_safe(ff, tmp, &dbg->fdt_list, list) { + debugfs_remove(ff->file); + list_del(&ff->list); + kfree(ff); + } +} + +static int kho_out_finalize_get(void *data, u64 *val) +{ + *val = kho_finalized(); + + return 0; +} + +static int kho_out_finalize_set(void *data, u64 val) +{ + if (val) + return kho_finalize(); + else + return kho_abort(); +} + +DEFINE_DEBUGFS_ATTRIBUTE(kho_out_finalize_fops, kho_out_finalize_get, + kho_out_finalize_set, "%llu\n"); + +static int scratch_phys_show(struct seq_file *m, void *v) +{ + for (int i = 0; i < kho_scratch_cnt; i++) + seq_printf(m, "0x%llx\n", kho_scratch[i].addr); + + return 0; +} +DEFINE_SHOW_ATTRIBUTE(scratch_phys); + +static int scratch_len_show(struct seq_file *m, void *v) +{ + for (int i = 0; i < kho_scratch_cnt; i++) + seq_printf(m, "0x%llx\n", kho_scratch[i].size); + + return 0; +} +DEFINE_SHOW_ATTRIBUTE(scratch_len); + +__init void kho_in_debugfs_init(struct kho_debugfs *dbg, const void *fdt) +{ + struct dentry *dir, *sub_fdt_dir; + int err, child; + + INIT_LIST_HEAD(&dbg->fdt_list); + + dir = debugfs_create_dir("in", debugfs_root); + if (IS_ERR(dir)) { + err = PTR_ERR(dir); + goto err_out; + } + + sub_fdt_dir = debugfs_create_dir("sub_fdts", dir); + if (IS_ERR(sub_fdt_dir)) { + err = PTR_ERR(sub_fdt_dir); + goto err_rmdir; + } + + err = __kho_debugfs_fdt_add(&dbg->fdt_list, dir, "fdt", fdt); + if (err) + goto err_rmdir; + + fdt_for_each_subnode(child, fdt, 0) { + int len = 0; + const char *name = fdt_get_name(fdt, child, NULL); + const u64 *fdt_phys; + + fdt_phys = fdt_getprop(fdt, child, "fdt", &len); + if (!fdt_phys) + continue; + if (len != sizeof(*fdt_phys)) { + pr_warn("node %s prop fdt has invalid length: %d\n", + name, len); + continue; + } + err = __kho_debugfs_fdt_add(&dbg->fdt_list, sub_fdt_dir, name, + phys_to_virt(*fdt_phys)); + if (err) { + pr_warn("failed to add fdt %s to debugfs: %d\n", name, + err); + continue; + } + } + + dbg->dir = dir; + dbg->sub_fdt_dir = sub_fdt_dir; + + return; +err_rmdir: + debugfs_remove_recursive(dir); +err_out: + /* + * Failure to create /sys/kernel/debug/kho/in does not prevent + * reviving state from KHO and setting up KHO for the next + * kexec. + */ + if (err) + pr_err("failed exposing handover FDT in debugfs: %d\n", err); +} + +__init int kho_out_debugfs_init(struct kho_debugfs *dbg) +{ + struct dentry *dir, *f, *sub_fdt_dir; + + INIT_LIST_HEAD(&dbg->fdt_list); + + dir = debugfs_create_dir("out", debugfs_root); + if (IS_ERR(dir)) + return -ENOMEM; + + sub_fdt_dir = debugfs_create_dir("sub_fdts", dir); + if (IS_ERR(sub_fdt_dir)) + goto err_rmdir; + + f = debugfs_create_file("scratch_phys", 0400, dir, NULL, + &scratch_phys_fops); + if (IS_ERR(f)) + goto err_rmdir; + + f = debugfs_create_file("scratch_len", 0400, dir, NULL, + &scratch_len_fops); + if (IS_ERR(f)) + goto err_rmdir; + + f = debugfs_create_file("finalize", 0600, dir, NULL, + &kho_out_finalize_fops); + if (IS_ERR(f)) + goto err_rmdir; + + dbg->dir = dir; + dbg->sub_fdt_dir = sub_fdt_dir; + return 0; + +err_rmdir: + debugfs_remove_recursive(dir); + return -ENOENT; +} + +__init int kho_debugfs_init(void) +{ + debugfs_root = debugfs_create_dir("kho", NULL); + if (IS_ERR(debugfs_root)) + return -ENOENT; + return 0; +} diff --git a/kernel/liveupdate/kexec_handover_internal.h b/kernel/liveupdate/kexec_handover_internal.h new file mode 100644 index 000000000000..217b8b25a542 --- /dev/null +++ b/kernel/liveupdate/kexec_handover_internal.h @@ -0,0 +1,55 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef LINUX_KEXEC_HANDOVER_INTERNAL_H +#define LINUX_KEXEC_HANDOVER_INTERNAL_H + +#include +#include +#include + +#ifdef CONFIG_KEXEC_HANDOVER_DEBUGFS +#include + +struct kho_debugfs { + struct dentry *dir; + struct dentry *sub_fdt_dir; + struct list_head fdt_list; +}; + +#else +struct kho_debugfs {}; +#endif + +extern struct kho_scratch *kho_scratch; +extern unsigned int kho_scratch_cnt; + +bool kho_finalized(void); +int kho_finalize(void); +int kho_abort(void); + +#ifdef CONFIG_KEXEC_HANDOVER_DEBUGFS +int kho_debugfs_init(void); +void kho_in_debugfs_init(struct kho_debugfs *dbg, const void *fdt); +int kho_out_debugfs_init(struct kho_debugfs *dbg); +int kho_debugfs_fdt_add(struct kho_debugfs *dbg, const char *name, + const void *fdt, bool root); +void kho_debugfs_cleanup(struct kho_debugfs *dbg); +#else +static inline int kho_debugfs_init(void) { return 0; } +static inline void kho_in_debugfs_init(struct kho_debugfs *dbg, + const void *fdt) { } +static inline int kho_out_debugfs_init(struct kho_debugfs *dbg) { return 0; } +static inline int kho_debugfs_fdt_add(struct kho_debugfs *dbg, const char *name, + const void *fdt, bool root) { return 0; } +static inline void kho_debugfs_cleanup(struct kho_debugfs *dbg) {} +#endif /* CONFIG_KEXEC_HANDOVER_DEBUGFS */ + +#ifdef CONFIG_KEXEC_HANDOVER_DEBUG +bool kho_scratch_overlap(phys_addr_t phys, size_t size); +#else +static inline bool kho_scratch_overlap(phys_addr_t phys, size_t size) +{ + return false; +} +#endif /* CONFIG_KEXEC_HANDOVER_DEBUG */ + +#endif /* LINUX_KEXEC_HANDOVER_INTERNAL_H */ diff --git a/kernel/locking/osq_lock.c b/kernel/locking/osq_lock.c index b4233dc2c2b0..2bcc148eb2dd 100644 --- a/kernel/locking/osq_lock.c +++ b/kernel/locking/osq_lock.c @@ -59,7 +59,7 @@ osq_wait_next(struct optimistic_spin_queue *lock, for (;;) { if (atomic_read(&lock->tail) == curr && - atomic_cmpxchg_acquire(&lock->tail, curr, old_cpu) == curr) { + atomic_cmpxchg_release(&lock->tail, curr, old_cpu) == curr) { /* * We were the last queued, we moved @lock back. @prev * will now observe @lock and will complete its @@ -90,6 +90,49 @@ osq_wait_next(struct optimistic_spin_queue *lock, } } +/* + * Set prev->next; this is the counterpart of osq_wait_next() in that + * by setting ->next the wait is terminated and progress is resumed. + */ +static inline void osq_link_next(struct optimistic_spin_node *prev, + struct optimistic_spin_node *next) +{ + /* + * Suppose: + * + * tail + * | + * V + * CPU1 -> CPU2 -> CPU3: + * n: 2 n: 3 n: nil + * p: nil p: 1 p: 2 + * + * And this is CPU2 doing the self-unqueue concurrent against CPU1s + * unlock()/unqueue(). Since 'prev->next == NULL' and CPU1 will be + * stuck in osq_wait_next() until the below store of 'prev->next'. + * + * CPU2 CPU1 + * + * next->prev = prev; osq_wait_next() + * WMB MB + * prev->next = next; next->prev = prev + * + * Without the WMB it would be possible to have conflicting stores + * like: + * + * CPU2 CPU1 + * + * prev->next = next // CPU1.n = 3 + * next = osq_wait_next() // = 3 + * next->prev = prev // CPU3.p = nil + * next->prev = prev // CPU3.p = 1 + * + * Which would result in list corruption. + */ + smp_wmb(); + WRITE_ONCE(prev->next, next); +} + bool osq_lock(struct optimistic_spin_queue *lock) { struct optimistic_spin_node *node = this_cpu_ptr(&osq_node); @@ -113,20 +156,7 @@ bool osq_lock(struct optimistic_spin_queue *lock) prev = decode_cpu(old); node->prev = prev; - - /* - * osq_lock() unqueue - * - * node->prev = prev osq_wait_next() - * WMB MB - * prev->next = node next->prev = prev // unqueue-C - * - * Here 'node->prev' and 'next->prev' are the same variable and we need - * to ensure these stores happen in-order to avoid corrupting the list. - */ - smp_wmb(); - - WRITE_ONCE(prev->next, node); + osq_link_next(prev, node); /* * Normally @prev is untouchable after the above store; because at that @@ -202,7 +232,7 @@ bool osq_lock(struct optimistic_spin_queue *lock) */ WRITE_ONCE(next->prev, prev); - WRITE_ONCE(prev->next, next); + osq_link_next(prev, next); return false; } diff --git a/kernel/printk/printk.c b/kernel/printk/printk.c index d555d05ffa8d..124e7790f844 100644 --- a/kernel/printk/printk.c +++ b/kernel/printk/printk.c @@ -3747,6 +3747,13 @@ static struct syscore printk_syscore = { * If appropriate, start nbcon kthreads and set @printk_kthreads_running. * If any kthreads fail to start, those consoles are unregistered. * + * Called after consoles are registered or unregistered. + * + * This MUST NOT be called within an hlist_for_each_entry_safe(console_list) + * loop because it can unregister multiple consoles if any kthreads fail to + * start. That would lead to use-after-free scenarios within the + * hlist_for_each_entry_safe(console_list) loop of the caller. + * * Must be called under console_list_lock(). */ static void printk_kthreads_check_locked(void) @@ -4188,7 +4195,20 @@ void register_console(struct console *newcon) } EXPORT_SYMBOL(register_console); -/* Must be called under console_list_lock(). */ +/* + * Unregister the specified console. + * + * This can be called safely from within an + * hlist_for_each_entry_safe(console_list) loop because it unregisters + * _only_ the specified console. + * + * Afterwards the caller should call printk_kthreads_check_locked() since + * unregistering a console may require printer threads to start/stop. Note + * that printk_kthreads_check_locked() cannot be called safely from within + * an hlist_for_each_entry_safe(console_list) loop. + * + * Must be called under console_list_lock(). + */ static int unregister_console_locked(struct console *console) { bool use_device_lock = (console->flags & CON_NBCON) && console->write_atomic; @@ -4280,9 +4300,6 @@ static int unregister_console_locked(struct console *console) if (console->exit) res = console->exit(console); - /* Changed console list, may require printer threads to start/stop. */ - printk_kthreads_check_locked(); - return res; } @@ -4291,7 +4308,12 @@ int unregister_console(struct console *console) int res; console_list_lock(); + res = unregister_console_locked(console); + + /* Changed console list, may require printer threads to start/stop. */ + printk_kthreads_check_locked(); + console_list_unlock(); return res; } @@ -4415,6 +4437,10 @@ static int __init printk_late_init(void) unregister_console_locked(con); } } + + /* Changed console list, may require printer threads to start/stop. */ + printk_kthreads_check_locked(); + console_list_unlock(); ret = cpuhp_setup_state_nocalls(CPUHP_PRINTK_DEAD, "printk:dead", NULL, diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c index 0180758d90af..1c677016115a 100644 --- a/kernel/sched/deadline.c +++ b/kernel/sched/deadline.c @@ -1171,8 +1171,17 @@ static enum hrtimer_restart dl_server_timer(struct hrtimer *timer, struct sched_ sched_clock_tick(); update_rq_clock(rq); - if (!dl_se->dl_runtime) + /* + * Make sure current has propagated its pending runtime into + * any relevant server through calling dl_server_update() and + * friends. + */ + rq->donor->sched_class->update_curr(rq); + + if (dl_se->dl_defer_idle) { + dl_server_stop(dl_se); return HRTIMER_NORESTART; + } if (dl_se->dl_defer_armed) { /* @@ -1421,10 +1430,11 @@ s64 dl_scaled_delta_exec(struct rq *rq, struct sched_dl_entity *dl_se, s64 delta } static inline void -update_stats_dequeue_dl(struct dl_rq *dl_rq, struct sched_dl_entity *dl_se, - int flags); +update_stats_dequeue_dl(struct dl_rq *dl_rq, struct sched_dl_entity *dl_se, int flags); + static void update_curr_dl_se(struct rq *rq, struct sched_dl_entity *dl_se, s64 delta_exec) { + bool idle = idle_rq(rq); s64 scaled_delta_exec; if (unlikely(delta_exec <= 0)) { @@ -1445,6 +1455,9 @@ static void update_curr_dl_se(struct rq *rq, struct sched_dl_entity *dl_se, s64 dl_se->runtime -= scaled_delta_exec; + if (dl_se->dl_defer_idle && !idle) + dl_se->dl_defer_idle = 0; + /* * The fair server can consume its runtime while throttled (not queued/ * running as regular CFS). @@ -1454,6 +1467,29 @@ static void update_curr_dl_se(struct rq *rq, struct sched_dl_entity *dl_se, s64 * starting a new period, pushing the activation. */ if (dl_se->dl_defer && dl_se->dl_throttled && dl_runtime_exceeded(dl_se)) { + /* + * Non-servers would never get time accounted while throttled. + */ + WARN_ON_ONCE(!dl_server(dl_se)); + + /* + * While the server is marked idle, do not push out the + * activation further, instead wait for the period timer + * to lapse and stop the server. + */ + if (dl_se->dl_defer_idle && idle) { + /* + * The timer is at the zero-laxity point, this means + * dl_server_stop() / dl_server_start() can happen + * while now < deadline. This means update_dl_entity() + * will not replenish. Additionally start_dl_timer() + * will be set for 'deadline - runtime'. Negative + * runtime will not do. + */ + dl_se->runtime = 0; + return; + } + /* * If the server was previously activated - the starving condition * took place, it this point it went away because the fair scheduler @@ -1466,6 +1502,9 @@ static void update_curr_dl_se(struct rq *rq, struct sched_dl_entity *dl_se, s64 replenish_dl_new_period(dl_se, dl_se->rq); + if (idle) + dl_se->dl_defer_idle = 1; + /* * Not being able to start the timer seems problematic. If it could not * be started for whatever reason, we need to "unthrottle" the DL server @@ -1548,35 +1587,16 @@ static void update_curr_dl_se(struct rq *rq, struct sched_dl_entity *dl_se, s64 * as time available for the fair server, avoiding a penalty for the * rt scheduler that did not consumed that time. */ -void dl_server_update_idle_time(struct rq *rq, struct task_struct *p) +void dl_server_update_idle(struct sched_dl_entity *dl_se, s64 delta_exec) { - s64 delta_exec; - - if (!rq->fair_server.dl_defer) - return; - - /* no need to discount more */ - if (rq->fair_server.runtime < 0) - return; - - delta_exec = rq_clock_task(rq) - p->se.exec_start; - if (delta_exec < 0) - return; - - rq->fair_server.runtime -= delta_exec; - - if (rq->fair_server.runtime < 0) { - rq->fair_server.dl_defer_running = 0; - rq->fair_server.runtime = 0; - } - - p->se.exec_start = rq_clock_task(rq); + if (dl_se->dl_server_active && dl_se->dl_runtime && dl_se->dl_defer) + update_curr_dl_se(dl_se->rq, dl_se, delta_exec); } void dl_server_update(struct sched_dl_entity *dl_se, s64 delta_exec) { /* 0 runtime = fair server disabled */ - if (dl_se->dl_runtime) + if (dl_se->dl_server_active && dl_se->dl_runtime) update_curr_dl_se(dl_se->rq, dl_se, delta_exec); } @@ -1597,8 +1617,8 @@ void dl_server_update(struct sched_dl_entity *dl_se, s64 delta_exec) * | 8 | B:zero_laxity-wait | | | * | | | <---+ | * | +--------------------------------+ | - * | | ^ ^ 2 | - * | | 7 | 2 +--------------------+ + * | | ^ ^ 2 | + * | | 7 | 2, 1 +----------------+ * | v | * | +-------------+ | * +-- | C:idle-wait | -+ @@ -1643,8 +1663,11 @@ void dl_server_update(struct sched_dl_entity *dl_se, s64 delta_exec) * dl_defer_idle = 0 * * - * [1] A->B, A->D + * [1] A->B, A->D, C->B * dl_server_start() + * dl_defer_idle = 0; + * if (dl_server_active) + * return; // [B] * dl_server_active = 1; * enqueue_dl_entity() * update_dl_entity(WAKEUP) @@ -1759,6 +1782,7 @@ void dl_server_update(struct sched_dl_entity *dl_se, s64 delta_exec) * "B:zero_laxity-wait" -> "C:idle-wait" [label="7:dl_server_update_idle"] * "B:zero_laxity-wait" -> "D:running" [label="3:dl_server_timer"] * "C:idle-wait" -> "A:init" [label="8:dl_server_timer"] + * "C:idle-wait" -> "B:zero_laxity-wait" [label="1:dl_server_start"] * "C:idle-wait" -> "B:zero_laxity-wait" [label="2:dl_server_update"] * "C:idle-wait" -> "C:idle-wait" [label="7:dl_server_update_idle"] * "D:running" -> "A:init" [label="4:pick_task_dl"] @@ -1784,9 +1808,15 @@ void dl_server_start(struct sched_dl_entity *dl_se) { struct rq *rq = dl_se->rq; + dl_se->dl_defer_idle = 0; if (!dl_server(dl_se) || dl_se->dl_server_active) return; + /* + * Update the current task to 'now'. + */ + rq->donor->sched_class->update_curr(rq); + if (WARN_ON_ONCE(!cpu_online(cpu_of(rq)))) return; @@ -1805,6 +1835,7 @@ void dl_server_stop(struct sched_dl_entity *dl_se) hrtimer_try_to_cancel(&dl_se->dl_timer); dl_se->dl_defer_armed = 0; dl_se->dl_throttled = 0; + dl_se->dl_defer_idle = 0; dl_se->dl_server_active = 0; } diff --git a/kernel/sched/ext.c b/kernel/sched/ext.c index af5828f09304..b3a6d6070940 100644 --- a/kernel/sched/ext.c +++ b/kernel/sched/ext.c @@ -7013,7 +7013,6 @@ BTF_ID_FLAGS(func, scx_bpf_error_bstr, KF_TRUSTED_ARGS) BTF_ID_FLAGS(func, scx_bpf_dump_bstr, KF_TRUSTED_ARGS) BTF_ID_FLAGS(func, scx_bpf_cpuperf_cap) BTF_ID_FLAGS(func, scx_bpf_cpuperf_cur) -BTF_ID_FLAGS(func, scx_bpf_cpuperf_set) BTF_ID_FLAGS(func, scx_bpf_nr_node_ids) BTF_ID_FLAGS(func, scx_bpf_nr_cpu_ids) BTF_ID_FLAGS(func, scx_bpf_get_possible_cpumask, KF_ACQUIRE) @@ -7036,6 +7035,25 @@ static const struct btf_kfunc_id_set scx_kfunc_set_any = { .set = &scx_kfunc_ids_any, }; +/* + * Kfuncs which may take the rq lock on their unlocked path. + * + * A tracing program can execute in any kernel context, including ones which + * already hold the rq lock (e.g. sched_switch). scx_locked_rq() only tracks + * rq locks taken for SCX callbacks, so from such a context it returns NULL + * and these kfuncs would acquire the already held rq lock again and deadlock + * the CPU. They cannot be made safe for tracing programs, so keep them off + * the tracing hook. + */ +BTF_KFUNCS_START(scx_kfunc_ids_no_tracing) +BTF_ID_FLAGS(func, scx_bpf_cpuperf_set) +BTF_KFUNCS_END(scx_kfunc_ids_no_tracing) + +static const struct btf_kfunc_id_set scx_kfunc_set_no_tracing = { + .owner = THIS_MODULE, + .set = &scx_kfunc_ids_no_tracing, +}; + static int __init scx_init(void) { int ret; @@ -7065,6 +7083,10 @@ static int __init scx_init(void) &scx_kfunc_set_any)) || (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &scx_kfunc_set_any)) || + (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, + &scx_kfunc_set_no_tracing)) || + (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, + &scx_kfunc_set_no_tracing)) || (ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_SYSCALL, &scx_kfunc_set_any))) { pr_err("sched_ext: Failed to register kfunc sets (%d)\n", ret); diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c index a063e302fbf8..4052ed6e1330 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -1325,8 +1325,7 @@ static void update_curr(struct cfs_rq *cfs_rq) * against fair_server such that it can account for this time * and possibly avoid running this period. */ - if (dl_server_active(&rq->fair_server)) - dl_server_update(&rq->fair_server, delta_exec); + dl_server_update(&rq->fair_server, delta_exec); } account_cfs_rq_runtime(cfs_rq, delta_exec); @@ -7176,12 +7175,8 @@ enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) h_nr_idle = 1; } - if (!rq_h_nr_queued && rq->cfs.h_nr_queued) { - /* Account for idle runtime */ - if (!rq->nr_running) - dl_server_update_idle_time(rq, rq->curr); + if (!rq_h_nr_queued && rq->cfs.h_nr_queued) dl_server_start(&rq->fair_server); - } /* At this point se is NULL and we are at root level*/ add_nr_running(rq, 1); diff --git a/kernel/sched/idle.c b/kernel/sched/idle.c index d5607b2150ba..5dd4d1de1864 100644 --- a/kernel/sched/idle.c +++ b/kernel/sched/idle.c @@ -473,9 +473,11 @@ static void wakeup_preempt_idle(struct rq *rq, struct task_struct *p, int flags) resched_curr(rq); } +static void update_curr_idle(struct rq *rq); + static void put_prev_task_idle(struct rq *rq, struct task_struct *prev, struct task_struct *next) { - dl_server_update_idle_time(rq, prev); + update_curr_idle(rq); scx_update_idle(rq, false, true); } @@ -523,6 +525,7 @@ dequeue_task_idle(struct rq *rq, struct task_struct *p, int flags) */ static void task_tick_idle(struct rq *rq, struct task_struct *curr, int queued) { + update_curr_idle(rq); } static void switching_to_idle(struct rq *rq, struct task_struct *p) @@ -538,6 +541,17 @@ prio_changed_idle(struct rq *rq, struct task_struct *p, int oldprio) static void update_curr_idle(struct rq *rq) { + struct sched_entity *se = &rq->idle->se; + u64 now = rq_clock_task(rq); + s64 delta_exec; + + delta_exec = now - se->exec_start; + if (unlikely(delta_exec <= 0)) + return; + + se->exec_start = now; + + dl_server_update_idle(&rq->fair_server, delta_exec); } /* diff --git a/kernel/sched/pelt.c b/kernel/sched/pelt.c index fa83bbaf4f3e..75a48236ec46 100644 --- a/kernel/sched/pelt.c +++ b/kernel/sched/pelt.c @@ -99,7 +99,7 @@ static u32 __accumulate_pelt_segments(u64 periods, u32 d1, u32 d3) * d1 y^p + 1024 \Sum y^n + d3 y^0 (Step 2) * n=1 */ -static __always_inline u32 +static __always_inline u64 accumulate_sum(u64 delta, struct sched_avg *sa, unsigned long load, unsigned long runnable, int running) { diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h index 81ccbfbb8152..ad7b72317f0f 100644 --- a/kernel/sched/sched.h +++ b/kernel/sched/sched.h @@ -405,6 +405,7 @@ extern s64 dl_scaled_delta_exec(struct rq *rq, struct sched_dl_entity *dl_se, s6 * naturally thottled to once per period, avoiding high context switch * workloads from spamming the hrtimer program/cancel paths. */ +extern void dl_server_update_idle(struct sched_dl_entity *dl_se, s64 delta_exec); extern void dl_server_update(struct sched_dl_entity *dl_se, s64 delta_exec); extern void dl_server_start(struct sched_dl_entity *dl_se); extern void dl_server_stop(struct sched_dl_entity *dl_se); @@ -412,8 +413,6 @@ extern void dl_server_init(struct sched_dl_entity *dl_se, struct rq *rq, dl_server_pick_f pick_task); extern void sched_init_dl_servers(void); -extern void dl_server_update_idle_time(struct rq *rq, - struct task_struct *p); extern void fair_server_init(struct rq *rq); extern void __dl_server_attach_root(struct sched_dl_entity *dl_se, struct rq *rq); extern int dl_server_apply_params(struct sched_dl_entity *dl_se, @@ -1362,6 +1361,28 @@ static inline u32 sched_rng(void) #define cpu_curr(cpu) (cpu_rq(cpu)->curr) #define raw_rq() raw_cpu_ptr(&runqueues) +static inline bool idle_rq(struct rq *rq) +{ + return rq->curr == rq->idle && !rq->nr_running && !rq->ttwu_pending; +} + +/** + * available_idle_cpu - is a given CPU idle for enqueuing work. + * @cpu: the CPU in question. + * + * Return: 1 if the CPU is currently idle. 0 otherwise. + */ +static inline bool available_idle_cpu(int cpu) +{ + if (!idle_rq(cpu_rq(cpu))) + return 0; + + if (vcpu_is_preempted(cpu)) + return 0; + + return 1; +} + #ifdef CONFIG_SCHED_PROXY_EXEC static inline void rq_set_donor(struct rq *rq, struct task_struct *t) { diff --git a/kernel/sched/syscalls.c b/kernel/sched/syscalls.c index b044a3aa4a0a..1be22414b413 100644 --- a/kernel/sched/syscalls.c +++ b/kernel/sched/syscalls.c @@ -190,35 +190,7 @@ int task_prio(const struct task_struct *p) */ int idle_cpu(int cpu) { - struct rq *rq = cpu_rq(cpu); - - if (rq->curr != rq->idle) - return 0; - - if (rq->nr_running) - return 0; - - if (rq->ttwu_pending) - return 0; - - return 1; -} - -/** - * available_idle_cpu - is a given CPU idle for enqueuing work. - * @cpu: the CPU in question. - * - * Return: 1 if the CPU is currently idle. 0 otherwise. - */ -int available_idle_cpu(int cpu) -{ - if (!idle_cpu(cpu)) - return 0; - - if (vcpu_is_preempted(cpu)) - return 0; - - return 1; + return idle_rq(cpu_rq(cpu)); } /** @@ -356,8 +328,8 @@ static inline void __setscheduler_dl_pi(int newprio, int policy, static int uclamp_validate(struct task_struct *p, const struct sched_attr *attr) { - int util_min = p->uclamp_req[UCLAMP_MIN].value; - int util_max = p->uclamp_req[UCLAMP_MAX].value; + unsigned int util_min = p->uclamp_req[UCLAMP_MIN].value; + unsigned int util_max = p->uclamp_req[UCLAMP_MAX].value; if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN) { util_min = attr->sched_util_min; @@ -666,7 +638,7 @@ int __sched_setscheduler(struct task_struct *p, * the entire root_domain to become SCHED_DEADLINE. We * will also fail if there's no bandwidth available. */ - if (!cpumask_subset(span, p->cpus_ptr) || + if (!cpumask_subset(span, &p->cpus_mask) || rq->rd->dl_bw.bw == 0) { retval = -EPERM; goto unlock; @@ -678,8 +650,10 @@ int __sched_setscheduler(struct task_struct *p, if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) { policy = oldpolicy = -1; task_rq_unlock(rq, p, &rf); - if (cpuset_locked) + if (cpuset_locked) { cpuset_unlock(); + cpuset_locked = false; + } goto recheck; } diff --git a/kernel/sched/topology.c b/kernel/sched/topology.c index 35478aa2536f..e3bf754e081c 100644 --- a/kernel/sched/topology.c +++ b/kernel/sched/topology.c @@ -2714,13 +2714,25 @@ int __init sched_init_domains(const struct cpumask *cpu_map) static void detach_destroy_domains(const struct cpumask *cpu_map) { unsigned int cpu = cpumask_any(cpu_map); + bool has_cluster = false; int i; if (rcu_access_pointer(per_cpu(sd_asym_cpucapacity, cpu))) static_branch_dec_cpuslocked(&sched_asym_cpucapacity); - if (static_branch_unlikely(&sched_cluster_active)) - static_branch_dec_cpuslocked(&sched_cluster_active); + if (static_branch_unlikely(&sched_cluster_active)) { + rcu_read_lock(); + for_each_cpu(i, cpu_map) { + if (lowest_flag_domain(i, SD_CLUSTER)) { + has_cluster = true; + break; + } + } + rcu_read_unlock(); + + if (has_cluster) + static_branch_dec_cpuslocked(&sched_cluster_active); + } rcu_read_lock(); for_each_cpu(i, cpu_map) diff --git a/kernel/time/timekeeping.c b/kernel/time/timekeeping.c index bf25112b0156..82709c7d6814 100644 --- a/kernel/time/timekeeping.c +++ b/kernel/time/timekeeping.c @@ -1503,6 +1503,7 @@ static int __timekeeping_inject_offset(struct tk_data *tkd, const struct timespe struct tk_read_base *tkr_mono = &tks->tkr_mono; ktime_t now, offs; + tk_update_ktime_data(tks); /* Get the current time */ now = ktime_add_ns(tkr_mono->base, timekeeping_get_ns(tkr_mono)); /* Add the relative offset change */ @@ -2419,7 +2420,13 @@ void update_wall_time(void) void getboottime64(struct timespec64 *ts) { struct timekeeper *tk = &tk_core.timekeeper; - ktime_t t = ktime_sub(tk->offs_real, tk->offs_boot); + unsigned int seq; + ktime_t t; + + do { + seq = read_seqcount_begin(&tk_core.seq); + t = ktime_sub(tk->offs_real, tk->offs_boot); + } while (read_seqcount_retry(&tk_core.seq, seq)); *ts = ktime_to_timespec64(t); } diff --git a/kernel/trace/trace_eprobe.c b/kernel/trace/trace_eprobe.c index 8296da33672f..b9d9b3fe7804 100644 --- a/kernel/trace/trace_eprobe.c +++ b/kernel/trace/trace_eprobe.c @@ -89,14 +89,18 @@ static int eprobe_dyn_event_show(struct seq_file *m, struct dyn_event *ev) static int unregister_trace_eprobe(struct trace_eprobe *ep) { - /* If other probes are on the event, just unregister eprobe */ - if (trace_probe_has_sibling(&ep->tp)) - goto unreg; - /* Enabled event can not be unregistered */ if (trace_probe_is_enabled(&ep->tp)) return -EBUSY; + /* If there's a reference to the dynamic event */ + if (trace_event_dyn_busy(trace_probe_event_call(&ep->tp))) + return -EBUSY; + + /* If other probes are on the event, just unregister eprobe */ + if (trace_probe_has_sibling(&ep->tp)) + goto unreg; + /* Will fail if probe is being used by ftrace or perf */ if (trace_probe_unregister_event_call(&ep->tp)) return -EBUSY; @@ -328,21 +332,21 @@ get_event_field(struct fetch_insn *code, void *rec) switch (field->size) { case 1: if (field->is_signed) - val = *(char *)addr; + val = *(s8 *)addr; else - val = *(unsigned char *)addr; + val = *(u8 *)addr; break; case 2: if (field->is_signed) - val = *(short *)addr; + val = *(s16 *)addr; else - val = *(unsigned short *)addr; + val = *(u16 *)addr; break; case 4: if (field->is_signed) - val = *(int *)addr; + val = *(s32 *)addr; else - val = *(unsigned int *)addr; + val = *(u32 *)addr; break; default: if (field->size == sizeof(long)) { @@ -642,37 +646,32 @@ static int enable_trace_eprobe(struct trace_event_call *call, { struct trace_probe *tp; struct trace_eprobe *ep; - bool enabled; int ret = 0; int cnt = 0; + if (WARN_ON_ONCE(!file)) + return -EINVAL; + tp = trace_probe_primary_from_call(call); if (WARN_ON_ONCE(!tp)) return -ENODEV; - enabled = trace_probe_is_enabled(tp); /* This also changes "enabled" state */ - if (file) { - ret = trace_probe_add_file(tp, file); - if (ret) - return ret; - } else - trace_probe_set_flag(tp, TP_FLAG_PROFILE); - - if (enabled) - return 0; + ret = trace_probe_add_file(tp, file); + if (ret) + return ret; + /* The trigger lives in the instance of the file, add it for each file */ for_each_trace_eprobe_tp(ep, tp) { ret = enable_eprobe(ep, file); if (ret) break; - enabled = true; cnt++; } if (ret) { /* Failed to enable one of them. Roll back all */ - if (enabled) { + if (cnt) { /* * It's a bug if one failed for something other than memory * not being available but another eprobe succeeded. @@ -685,10 +684,7 @@ static int enable_trace_eprobe(struct trace_event_call *call, break; } } - if (file) - trace_probe_remove_file(tp, file); - else - trace_probe_clear_flag(tp, TP_FLAG_PROFILE); + trace_probe_remove_file(tp, file); } return ret; @@ -700,33 +696,21 @@ static int disable_trace_eprobe(struct trace_event_call *call, struct trace_probe *tp; struct trace_eprobe *ep; + if (WARN_ON_ONCE(!file)) + return -EINVAL; + tp = trace_probe_primary_from_call(call); if (WARN_ON_ONCE(!tp)) return -ENODEV; - if (file) { - if (!trace_probe_get_file_link(tp, file)) - return -ENOENT; - if (!trace_probe_has_single_file(tp)) - goto out; - trace_probe_clear_flag(tp, TP_FLAG_TRACE); - } else - trace_probe_clear_flag(tp, TP_FLAG_PROFILE); + if (!trace_probe_get_file_link(tp, file)) + return -ENOENT; - if (!trace_probe_is_enabled(tp)) { - for_each_trace_eprobe_tp(ep, tp) - disable_eprobe(ep, file->tr); - } + for_each_trace_eprobe_tp(ep, tp) + disable_eprobe(ep, file->tr); - out: - if (file) - /* - * Synchronization is done in below function. For perf event, - * file == NULL and perf_trace_event_unreg() calls - * tracepoint_synchronize_unregister() to ensure synchronize - * event. We don't need to care about it. - */ - trace_probe_remove_file(tp, file); + /* Synchronization is done in below function. */ + trace_probe_remove_file(tp, file); return 0; } @@ -776,7 +760,8 @@ find_and_get_event(const char *system, const char *event_name) (TRACE_EVENT_FL_IGNORE_ENABLE | TRACE_EVENT_FL_KPROBE | TRACE_EVENT_FL_UPROBE | - TRACE_EVENT_FL_EPROBE)) + TRACE_EVENT_FL_EPROBE | + TRACE_EVENT_FL_FPROBE)) continue; if (!tp_event->class->system || strcmp(system, tp_event->class->system)) diff --git a/kernel/trace/trace_event_perf.c b/kernel/trace/trace_event_perf.c index 5b272856e5ab..a549897ee408 100644 --- a/kernel/trace/trace_event_perf.c +++ b/kernel/trace/trace_event_perf.c @@ -354,8 +354,7 @@ int perf_trace_add(struct perf_event *p_event, int flags) struct trace_event_call *tp_event = p_event->tp_event; struct hw_perf_event *hwc = &p_event->hw; - if (!(flags & PERF_EF_START)) - p_event->hw.state = PERF_HES_STOPPED; + hwc->state = (flags & PERF_EF_START) ? 0 : PERF_HES_STOPPED; if (is_sampling_event(p_event)) { hwc->last_period = hwc->sample_period; diff --git a/kernel/trace/trace_fprobe.c b/kernel/trace/trace_fprobe.c index f7eb875811be..331e59a55d91 100644 --- a/kernel/trace/trace_fprobe.c +++ b/kernel/trace/trace_fprobe.c @@ -857,10 +857,6 @@ static void __unregister_trace_fprobe(struct trace_fprobe *tf) /* Unregister a trace_probe and probe_event */ static int unregister_trace_fprobe(struct trace_fprobe *tf) { - /* If other probes are on the event, just unregister fprobe */ - if (trace_probe_has_sibling(&tf->tp)) - goto unreg; - /* Enabled event can not be unregistered */ if (trace_probe_is_enabled(&tf->tp)) return -EBUSY; @@ -869,6 +865,10 @@ static int unregister_trace_fprobe(struct trace_fprobe *tf) if (trace_event_dyn_busy(trace_probe_event_call(&tf->tp))) return -EBUSY; + /* If other probes are on the event, just unregister fprobe */ + if (trace_probe_has_sibling(&tf->tp)) + goto unreg; + /* Will fail if probe is being used by ftrace or perf */ if (unregister_fprobe_event(tf)) return -EBUSY; @@ -937,7 +937,10 @@ static int append_trace_fprobe_event(struct trace_fprobe *tf, struct trace_fprob if (ret) return ret; - ret = trace_fprobe_verify_target(tf); + if (trace_probe_is_enabled(&tf->tp)) + ret = __register_trace_fprobe(tf); + else + ret = trace_fprobe_verify_target(tf); if (ret) trace_probe_unlink(&tf->tp); else @@ -1522,13 +1525,8 @@ static int disable_trace_fprobe(struct trace_event_call *call, trace_probe_clear_flag(tp, TP_FLAG_PROFILE); if (!trace_probe_is_enabled(tp)) { - list_for_each_entry(tf, trace_probe_probe_list(tp), tp.list) { - unregister_fprobe(&tf->fp); - if (tf->tuser) { - tracepoint_user_put(tf->tuser); - tf->tuser = NULL; - } - } + list_for_each_entry(tf, trace_probe_probe_list(tp), tp.list) + __unregister_trace_fprobe(tf); } out: diff --git a/kernel/trace/trace_kprobe.c b/kernel/trace/trace_kprobe.c index ee8171b19bee..c47921aee073 100644 --- a/kernel/trace/trace_kprobe.c +++ b/kernel/trace/trace_kprobe.c @@ -538,10 +538,6 @@ static void __unregister_trace_kprobe(struct trace_kprobe *tk) /* Unregister a trace_probe and probe_event */ static int unregister_trace_kprobe(struct trace_kprobe *tk) { - /* If other probes are on the event, just unregister kprobe */ - if (trace_probe_has_sibling(&tk->tp)) - goto unreg; - /* Enabled event can not be unregistered */ if (trace_probe_is_enabled(&tk->tp)) return -EBUSY; @@ -550,6 +546,10 @@ static int unregister_trace_kprobe(struct trace_kprobe *tk) if (trace_event_dyn_busy(trace_probe_event_call(&tk->tp))) return -EBUSY; + /* If other probes are on the event, just unregister kprobe */ + if (trace_probe_has_sibling(&tk->tp)) + goto unreg; + /* Will fail if probe is being used by ftrace or perf */ if (unregister_kprobe_event(tk)) return -EBUSY; @@ -1995,6 +1995,9 @@ static __init void setup_boot_kprobe_events(void) char *p, *cmd = kprobe_boot_events_buf; int ret; + if (!kprobe_boot_events_buf[0]) + return; + strreplace(kprobe_boot_events_buf, ',', ' '); while (cmd && *cmd != '\0') { diff --git a/kernel/trace/trace_probe.c b/kernel/trace/trace_probe.c index 7202fb4aced1..ac31528b981b 100644 --- a/kernel/trace/trace_probe.c +++ b/kernel/trace/trace_probe.c @@ -356,6 +356,9 @@ static bool btf_type_is_char_ptr(struct btf *btf, const struct btf_type *type) const struct btf_type *real_type; u32 intdata; + if (BTF_INFO_KIND(type->info) != BTF_KIND_PTR) + return false; + real_type = btf_type_skip_modifiers(btf, type->type, NULL); if (!real_type) return false; @@ -380,6 +383,11 @@ static bool btf_type_is_char_array(struct btf *btf, const struct btf_type *type) array = (const struct btf_array *)(type + 1); real_type = btf_type_skip_modifiers(btf, array->type, NULL); + if (!real_type) + return false; + + if (BTF_INFO_KIND(real_type->info) != BTF_KIND_INT) + return false; intdata = btf_type_int(real_type); return !(BTF_INT_ENCODING(intdata) & BTF_INT_SIGNED) @@ -1476,6 +1484,8 @@ static int finalize_fetch_insn(struct fetch_insn *code, /* Store operation */ if (parg->type->is_string) { + bool is_uderef; + /* Check bad combination of the type and the last fetch_insn. */ if (!strcmp(parg->type->name, "symstr")) { if (code->op != FETCH_OP_REG && code->op != FETCH_OP_STACK && @@ -1495,6 +1505,7 @@ static int finalize_fetch_insn(struct fetch_insn *code, } } + is_uderef = (code->op == FETCH_OP_UDEREF); if (!strcmp(parg->type->name, "symstr") || (code->op == FETCH_OP_IMM || code->op == FETCH_OP_COMM || code->op == FETCH_OP_DATA) || code->op == FETCH_OP_TP_ARG || @@ -1507,6 +1518,12 @@ static int finalize_fetch_insn(struct fetch_insn *code, * For the symstr, it doesn't need to dereference, thus * it just get the value. */ + if (parg->count && (code->op != FETCH_OP_DEREF && + code->op != FETCH_OP_UDEREF)) { + trace_probe_log_err(ctx->offset + type_offset, + BAD_STRING); + return -EINVAL; + } code++; if (code->op != FETCH_OP_NOP) { trace_probe_log_err(ctx->offset, TOO_MANY_OPS); @@ -1515,8 +1532,7 @@ static int finalize_fetch_insn(struct fetch_insn *code, } /* If op == DEREF, replace it with STRING */ - if (!strcmp(parg->type->name, "ustring") || - code->op == FETCH_OP_UDEREF) + if (!strcmp(parg->type->name, "ustring") || is_uderef) code->op = FETCH_OP_ST_USTRING; else if (!strcmp(parg->type->name, "symstr")) code->op = FETCH_OP_ST_SYMSTR; diff --git a/kernel/trace/trace_probe_tmpl.h b/kernel/trace/trace_probe_tmpl.h index f39b37fcdb3b..636e0a52383f 100644 --- a/kernel/trace/trace_probe_tmpl.h +++ b/kernel/trace/trace_probe_tmpl.h @@ -87,15 +87,27 @@ fetch_store_symstrlen(unsigned long addr) static nokprobe_inline int fetch_store_symstring(unsigned long addr, void *dest, void *base) { + char namebuf[KSYM_SYMBOL_LEN]; int maxlen = get_loc_len(*(u32 *)dest); void *__dest; + int len; if (unlikely(!maxlen)) return -ENOMEM; __dest = get_loc_data(dest, base); + len = sprint_symbol(namebuf, addr); + if (len < 0) { + *(u32 *)dest = make_data_loc(0, __dest - base); + return 0; + } + + len = min(len, maxlen - 1); + memcpy(__dest, namebuf, len); + ((char *)__dest)[len] = '\0'; + *(u32 *)dest = make_data_loc(len + 1, __dest - base); - return sprint_symbol(__dest, addr); + return len + 1; } /* common part of process_fetch_insn*/ diff --git a/kernel/trace/trace_uprobe.c b/kernel/trace/trace_uprobe.c index 430d09c49462..bc88cae15fbd 100644 --- a/kernel/trace/trace_uprobe.c +++ b/kernel/trace/trace_uprobe.c @@ -396,13 +396,17 @@ static int unregister_trace_uprobe(struct trace_uprobe *tu) { int ret; - if (trace_probe_has_sibling(&tu->tp)) - goto unreg; + /* Enabled event can not be unregistered */ + if (trace_probe_is_enabled(&tu->tp)) + return -EBUSY; /* If there's a reference to the dynamic event */ if (trace_event_dyn_busy(trace_probe_event_call(&tu->tp))) return -EBUSY; + if (trace_probe_has_sibling(&tu->tp)) + goto unreg; + ret = unregister_uprobe_event(tu); if (ret) return ret; @@ -443,6 +447,28 @@ static bool trace_uprobe_has_same_uprobe(struct trace_uprobe *orig, return false; } +typedef bool (*filter_func_t)(struct uprobe_consumer *self, struct mm_struct *mm); + +#ifdef CONFIG_PERF_EVENTS +static bool uprobe_perf_filter(struct uprobe_consumer *uc, struct mm_struct *mm); +#else +#define uprobe_perf_filter NULL +#endif + +static int trace_uprobe_enable(struct trace_uprobe *tu, filter_func_t filter) +{ + struct inode *inode = d_real_inode(tu->path.dentry); + struct uprobe *uprobe; + + tu->consumer.filter = filter; + uprobe = uprobe_register(inode, tu->offset, tu->ref_ctr_offset, &tu->consumer); + if (IS_ERR(uprobe)) + return PTR_ERR(uprobe); + + tu->uprobe = uprobe; + return 0; +} + static int append_trace_uprobe(struct trace_uprobe *tu, struct trace_uprobe *to) { int ret; @@ -462,10 +488,22 @@ static int append_trace_uprobe(struct trace_uprobe *tu, struct trace_uprobe *to) /* Append to existing event */ ret = trace_probe_append(&tu->tp, &to->tp); - if (!ret) - dyn_event_add(&tu->devent, trace_probe_event_call(&tu->tp)); + if (ret) + return ret; - return ret; + if (trace_probe_is_enabled(&tu->tp)) { + ret = trace_uprobe_enable(tu, + trace_probe_test_flag(&tu->tp, TP_FLAG_PROFILE) ? + uprobe_perf_filter : NULL); + if (ret) { + trace_probe_unlink(&tu->tp); + return ret; + } + } + + dyn_event_add(&tu->devent, trace_probe_event_call(&tu->tp)); + + return 0; } /* @@ -666,7 +704,7 @@ static int __trace_uprobe_create(int argc, const char **argv) } if (!event) { - char *tail; + char *tail __free(kfree) = NULL; char *ptr; tail = kstrdup(kbasename(filename), GFP_KERNEL); @@ -682,7 +720,6 @@ static int __trace_uprobe_create(int argc, const char **argv) goto fail_mem; snprintf(buf, MAX_EVENT_NAME_LEN, "%c_%s_0x%lx", 'p', tail, offset); event = buf; - kfree(tail); } argc -= 2; @@ -1115,22 +1152,6 @@ print_uprobe_event(struct trace_iterator *iter, int flags, struct trace_event *e return trace_handle_return(s); } -typedef bool (*filter_func_t)(struct uprobe_consumer *self, struct mm_struct *mm); - -static int trace_uprobe_enable(struct trace_uprobe *tu, filter_func_t filter) -{ - struct inode *inode = d_real_inode(tu->path.dentry); - struct uprobe *uprobe; - - tu->consumer.filter = filter; - uprobe = uprobe_register(inode, tu->offset, tu->ref_ctr_offset, &tu->consumer); - if (IS_ERR(uprobe)) - return PTR_ERR(uprobe); - - tu->uprobe = uprobe; - return 0; -} - static void __probe_event_disable(struct trace_probe *tp) { struct trace_uprobe *tu; diff --git a/kernel/tsacct.c b/kernel/tsacct.c index 6ea2f6363b90..ed5accc15734 100644 --- a/kernel/tsacct.c +++ b/kernel/tsacct.c @@ -24,7 +24,7 @@ void bacct_add_tsk(struct user_namespace *user_ns, const struct cred *tcred; u64 utime, stime, utimescaled, stimescaled; u64 now_ns, delta; - time64_t btime; + struct timespec64 btime; BUILD_BUG_ON(TS_COMM_LEN < TASK_COMM_LEN); @@ -39,9 +39,11 @@ void bacct_add_tsk(struct user_namespace *user_ns, do_div(delta, NSEC_PER_USEC); stats->ac_etime = delta; /* Convert to seconds for btime (note y2106 limit) */ - btime = ktime_get_real_seconds() - div_u64(delta, USEC_PER_SEC); - stats->ac_btime = clamp_t(time64_t, btime, 0, U32_MAX); - stats->ac_btime64 = btime; + getboottime64(&btime); + btime = timespec64_add(btime, ns_to_timespec64(tsk->start_boottime)); + stats->ac_btime = clamp_t(time64_t, btime.tv_sec, 0, U32_MAX); + /* Setting the clock back after suspend can make btime negative. */ + stats->ac_btime64 = max_t(time64_t, btime.tv_sec, 0); if (tsk->flags & PF_EXITING) stats->ac_exitcode = tsk->exit_code; diff --git a/lib/bootconfig.c b/lib/bootconfig.c index b4e8e17e2915..ae36ccef21e6 100644 --- a/lib/bootconfig.c +++ b/lib/bootconfig.c @@ -302,9 +302,9 @@ int __init xbc_node_compose_key_after(struct xbc_node *root, node = xbc_node_get_parent(node); while (node && node != root) { - keys[depth++] = xbc_node_index(node); if (depth == XBC_DEPTH_MAX) return -ERANGE; + keys[depth++] = xbc_node_index(node); node = xbc_node_get_parent(node); } if (!node && root) @@ -652,16 +652,17 @@ static int __init __xbc_parse_value(char **__v, char **__n) return xbc_parse_error("No value delimiter", p); if (*p) p++; - break; + goto skip_trim; } if (strchr(",;\n#}", c)) { *p++ = '\0'; - v = strim(v); break; } } if (quotes) return xbc_parse_error("No closing quotes", p); + v = strim(v); +skip_trim: if (c == '#') { p = skip_comment(p); c = '\n'; /* A comment must be treated as a newline */ diff --git a/lib/errseq.c b/lib/errseq.c index 13a2581c5a87..ea4ff9cc2166 100644 --- a/lib/errseq.c +++ b/lib/errseq.c @@ -162,7 +162,8 @@ EXPORT_SYMBOL(errseq_check); * points to. If it does, then just return 0. * * If it doesn't, then the value has changed. Set the "seen" flag, and try to - * swap it into place as the new eseq value. Then, set that value as the new + * swap it into place as the new eseq value. If the swap fails because the + * value changed, retry with the new value. Then, set that value as the new * "since" value, and return whatever the error portion is set to. * * Note that no locking is provided here for concurrent updates to the "since" @@ -184,24 +185,30 @@ int errseq_check_and_advance(errseq_t *eseq, errseq_t *since) * to take the lock that protects the "since" value. */ old = READ_ONCE(*eseq); - if (old != *since) { + while (old != *since) { /* * Set the flag and try to swap it into place if it has * changed. * - * We don't care about the outcome of the swap here. If the - * swap doesn't occur, then it has either been updated by a - * writer who is altering the value in some way (updating - * counter or resetting the error), or another reader who is - * just setting the "seen" flag. Either outcome is OK, and we - * can advance "since" and return an error based on what we - * have. + * If the swap fails, a writer or another reader changed the + * value under us, so retry with the new value. "since" must + * only ever be set to a value that was stored with the SEEN + * flag: errseq_set() does not bump the counter while the + * flag is clear, so an unstored value could come back later + * and hide the errors that were recorded in the meantime. */ new = old | ERRSEQ_SEEN; - if (new != old) - cmpxchg(eseq, old, new); + if (new != old) { + errseq_t cur = cmpxchg(eseq, old, new); + + if (cur != old) { + old = cur; + continue; + } + } *since = new; err = -(new & ERRNO_MASK); + break; } return err; } diff --git a/lib/iov_iter.c b/lib/iov_iter.c index b2eb629497a9..a9918931055a 100644 --- a/lib/iov_iter.c +++ b/lib/iov_iter.c @@ -1354,8 +1354,8 @@ static ssize_t __import_iovec_ubuf(int type, const struct iovec __user *uvec, } ssize_t __import_iovec(int type, const struct iovec __user *uvec, - unsigned nr_segs, unsigned fast_segs, struct iovec **iovp, - struct iov_iter *i, bool compat) + unsigned long nr_segs, unsigned int fast_segs, + struct iovec **iovp, struct iov_iter *i, bool compat) { ssize_t total_len = 0; unsigned long seg; @@ -1426,7 +1426,7 @@ ssize_t __import_iovec(int type, const struct iovec __user *uvec, * Return: Negative error code on error, bytes imported on success */ ssize_t import_iovec(int type, const struct iovec __user *uvec, - unsigned nr_segs, unsigned fast_segs, + unsigned long nr_segs, unsigned int fast_segs, struct iovec **iovp, struct iov_iter *i) { return __import_iovec(type, uvec, nr_segs, fast_segs, iovp, i, diff --git a/mm/internal.h b/mm/internal.h index 4a27dac7a42a..7504592042b2 100644 --- a/mm/internal.h +++ b/mm/internal.h @@ -1322,12 +1322,11 @@ unsigned int reclaim_clean_pages_from_list(struct zone *zone, #define ALLOC_OOM ALLOC_NO_WATERMARKS #endif -#define ALLOC_NON_BLOCK 0x10 /* Caller cannot block. Allow access - * to 25% of the min watermark or - * 62.5% if __GFP_HIGH is set. - */ +#define ALLOC_NON_BLOCK 0x10 /* Caller cannot block. */ #define ALLOC_MIN_RESERVE 0x20 /* __GFP_HIGH set. Allow access to 50% - * of the min watermark. + * of the min watermark, or 62.5% if + * the caller cannot block either + * (ALLOC_NON_BLOCK). */ #define ALLOC_CPUSET 0x40 /* check for correct cpuset */ #define ALLOC_CMA 0x80 /* allow allocations from CMA areas */ @@ -1341,7 +1340,7 @@ unsigned int reclaim_clean_pages_from_list(struct zone *zone, #define ALLOC_KSWAPD 0x800 /* allow waking of kswapd, __GFP_KSWAPD_RECLAIM set */ /* Flags that allow allocations below the min watermark. */ -#define ALLOC_RESERVES (ALLOC_NON_BLOCK|ALLOC_MIN_RESERVE|ALLOC_HIGHATOMIC|ALLOC_OOM) +#define ALLOC_RESERVES (ALLOC_MIN_RESERVE|ALLOC_HIGHATOMIC|ALLOC_OOM) /* Flags that mean GFP_ATOMIC */ #define ALLOC_MASK_ATOMIC (ALLOC_NON_BLOCK|ALLOC_MIN_RESERVE) diff --git a/mm/khugepaged.c b/mm/khugepaged.c index 7ca1772c5aa8..1acef234d22c 100644 --- a/mm/khugepaged.c +++ b/mm/khugepaged.c @@ -1254,6 +1254,7 @@ static int hpage_collapse_scan_pmd(struct mm_struct *mm, int none_or_zero = 0, shared = 0; struct page *page = NULL; struct folio *folio = NULL; + unsigned long failed_pfn = -1; unsigned long addr; spinlock_t *ptl; int node = NUMA_NO_NODE, unmapped = 0; @@ -1330,6 +1331,7 @@ static int hpage_collapse_scan_pmd(struct mm_struct *mm, if (!folio_test_anon(folio)) { result = SCAN_PAGE_ANON; + failed_pfn = folio_pfn(folio); goto out_unmap; } @@ -1342,6 +1344,7 @@ static int hpage_collapse_scan_pmd(struct mm_struct *mm, if (cc->is_khugepaged && shared > khugepaged_max_ptes_shared) { result = SCAN_EXCEED_SHARED_PTE; + failed_pfn = folio_pfn(folio); count_vm_event(THP_SCAN_EXCEED_SHARED_PTE); goto out_unmap; } @@ -1356,15 +1359,18 @@ static int hpage_collapse_scan_pmd(struct mm_struct *mm, node = folio_nid(folio); if (hpage_collapse_scan_abort(node, cc)) { result = SCAN_SCAN_ABORT; + failed_pfn = folio_pfn(folio); goto out_unmap; } cc->node_load[node]++; if (!folio_test_lru(folio)) { result = SCAN_PAGE_LRU; + failed_pfn = folio_pfn(folio); goto out_unmap; } if (folio_test_locked(folio)) { result = SCAN_PAGE_LOCK; + failed_pfn = folio_pfn(folio); goto out_unmap; } @@ -1380,6 +1386,7 @@ static int hpage_collapse_scan_pmd(struct mm_struct *mm, */ if (folio_expected_ref_count(folio) != folio_ref_count(folio)) { result = SCAN_PAGE_COUNT; + failed_pfn = folio_pfn(folio); goto out_unmap; } @@ -1409,7 +1416,7 @@ static int hpage_collapse_scan_pmd(struct mm_struct *mm, *mmap_locked = false; } out: - trace_mm_khugepaged_scan_pmd(mm, folio, referenced, + trace_mm_khugepaged_scan_pmd(mm, failed_pfn, referenced, none_or_zero, result, unmapped); return result; } diff --git a/mm/ksm.c b/mm/ksm.c index 78dc71763381..e6ddd74397b0 100644 --- a/mm/ksm.c +++ b/mm/ksm.c @@ -1419,6 +1419,10 @@ static int replace_page(struct vm_area_struct *vma, struct page *page, if (pte_soft_dirty(orig_pte)) newpte = pte_mksoft_dirty(newpte); + /* Preserve uffd-wp when replacing the page. */ + if (pte_uffd_wp(orig_pte)) + newpte = pte_mkuffd_wp(newpte); + flush_cache_page(vma, addr, pte_pfn(ptep_get(ptep))); /* * No need to notify as we are replacing a read only page with another diff --git a/mm/memory_hotplug.c b/mm/memory_hotplug.c index 9fdfb2d31765..bdc064c026ec 100644 --- a/mm/memory_hotplug.c +++ b/mm/memory_hotplug.c @@ -389,6 +389,7 @@ EXPORT_SYMBOL_GPL(pfn_to_online_page); int __add_pages(int nid, unsigned long pfn, unsigned long nr_pages, struct mhp_params *params) { + const unsigned long start_pfn = pfn; const unsigned long end_pfn = pfn + nr_pages; unsigned long cur_nr_pages; int err; @@ -422,8 +423,10 @@ int __add_pages(int nid, unsigned long pfn, unsigned long nr_pages, SECTION_ALIGN_UP(pfn + 1) - pfn); err = sparse_add_section(nid, pfn, cur_nr_pages, altmap, params->pgmap); - if (err) + if (err) { + __remove_pages(start_pfn, pfn - start_pfn, altmap); break; + } cond_resched(); } vmemmap_populate_print_last(); @@ -476,6 +479,22 @@ static unsigned long find_biggest_section_pfn(int nid, struct zone *zone, return 0; } +/* + * The page allocator checks pages against the span of their zone while the + * zone is resized, see page_outside_zone_boundaries(). It must not see the + * new value of one field together with the old value of the other one. + */ +static void zone_set_span(struct zone *zone, unsigned long start_pfn, + unsigned long spanned_pages) +{ + unsigned long flags; + + write_seqlock_irqsave(&zone->span_seqlock, flags); + zone->zone_start_pfn = start_pfn; + zone->spanned_pages = spanned_pages; + write_sequnlock_irqrestore(&zone->span_seqlock, flags); +} + static void shrink_zone_span(struct zone *zone, unsigned long start_pfn, unsigned long end_pfn) { @@ -491,13 +510,10 @@ static void shrink_zone_span(struct zone *zone, unsigned long start_pfn, */ pfn = find_smallest_section_pfn(nid, zone, end_pfn, zone_end_pfn(zone)); - if (pfn) { - zone->spanned_pages = zone_end_pfn(zone) - pfn; - zone->zone_start_pfn = pfn; - } else { - zone->zone_start_pfn = 0; - zone->spanned_pages = 0; - } + if (pfn) + zone_set_span(zone, pfn, zone_end_pfn(zone) - pfn); + else + zone_set_span(zone, 0, 0); } else if (zone_end_pfn(zone) == end_pfn) { /* * If the section is biggest section in the zone, it need @@ -508,11 +524,10 @@ static void shrink_zone_span(struct zone *zone, unsigned long start_pfn, pfn = find_biggest_section_pfn(nid, zone, zone->zone_start_pfn, start_pfn); if (pfn) - zone->spanned_pages = pfn - zone->zone_start_pfn + 1; - else { - zone->zone_start_pfn = 0; - zone->spanned_pages = 0; - } + zone_set_span(zone, zone->zone_start_pfn, + pfn - zone->zone_start_pfn + 1); + else + zone_set_span(zone, 0, 0); } } @@ -703,12 +718,12 @@ static void online_pages_range(unsigned long start_pfn, unsigned long nr_pages) static void __meminit resize_zone_range(struct zone *zone, unsigned long start_pfn, unsigned long nr_pages) { - unsigned long old_end_pfn = zone_end_pfn(zone); + unsigned long end_pfn = max(start_pfn + nr_pages, zone_end_pfn(zone)); - if (zone_is_empty(zone) || start_pfn < zone->zone_start_pfn) - zone->zone_start_pfn = start_pfn; + if (!zone_is_empty(zone) && start_pfn > zone->zone_start_pfn) + start_pfn = zone->zone_start_pfn; - zone->spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - zone->zone_start_pfn; + zone_set_span(zone, start_pfn, end_pfn - start_pfn); } static void __meminit resize_pgdat_range(struct pglist_data *pgdat, unsigned long start_pfn, diff --git a/mm/mempolicy.c b/mm/mempolicy.c index 5a9743c2c00f..c2d9773022b4 100644 --- a/mm/mempolicy.c +++ b/mm/mempolicy.c @@ -2088,6 +2088,7 @@ unsigned int mempolicy_slab_node(void) case MPOL_PREFERRED_MANY: { struct zoneref *z; + struct zone *zone; /* * Follow bind policy behavior and start allocation at the @@ -2098,7 +2099,8 @@ unsigned int mempolicy_slab_node(void) zonelist = &NODE_DATA(node)->node_zonelists[ZONELIST_FALLBACK]; z = first_zones_zonelist(zonelist, highest_zoneidx, &policy->nodes); - return zonelist_zone(z) ? zonelist_node_idx(z) : node; + zone = zonelist_zone(z); + return zone ? zone_to_nid(zone) : node; } case MPOL_LOCAL: return node; diff --git a/mm/page_alloc.c b/mm/page_alloc.c index 2578475dd5d3..074178f4d7a0 100644 --- a/mm/page_alloc.c +++ b/mm/page_alloc.c @@ -1608,6 +1608,8 @@ static void free_one_page(struct zone *zone, struct page *page, llist_for_each_entry_safe(p, tmp, llnode, pcp_llist) { unsigned int p_order = p->private; + /* It may end up as a tail of the merged free page. */ + p->private = 0; split_large_buddy(zone, p, page_to_pfn(p), p_order, fpi_flags); __count_vm_events(PGFREE, 1 << p_order); } @@ -3793,12 +3795,21 @@ get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags, { struct zoneref *z; struct zone *zone; + struct zone *preferred_zone; struct pglist_data *last_pgdat = NULL; bool last_pgdat_dirty_ok = false; bool no_fallback; bool skip_kswapd_nodes = nr_online_nodes > 1; bool skipped_kswapd_nodes = false; + /* + * A concurrent zonelist rebuild can NULL or replace this slot. Zones + * are never freed, so reading it once keeps a usable zone. + */ + preferred_zone = zonelist_zone(ac->preferred_zoneref); + if (!preferred_zone) + return NULL; + retry: /* * Scan zonelist, looking for a zone with enough free. @@ -3845,7 +3856,7 @@ get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags, } if (no_fallback && !defrag_mode && nr_online_nodes > 1 && - zone != zonelist_zone(ac->preferred_zoneref)) { + zone != preferred_zone) { int local_nid; /* @@ -3853,7 +3864,7 @@ get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags, * fragmenting fallbacks. Locality is more important * than fragmentation avoidance. */ - local_nid = zonelist_node_idx(ac->preferred_zoneref); + local_nid = zone_to_nid(preferred_zone); if (zone_to_nid(zone) != local_nid) { alloc_flags &= ~ALLOC_NOFRAGMENT; goto retry; @@ -3917,7 +3928,7 @@ get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags, goto try_this_zone; if (!node_reclaim_enabled() || - !zone_allows_reclaim(zonelist_zone(ac->preferred_zoneref), zone)) + !zone_allows_reclaim(preferred_zone, zone)) continue; ret = node_reclaim(zone->zone_pgdat, gfp_mask, order); @@ -3939,7 +3950,7 @@ get_page_from_freelist(gfp_t gfp_mask, unsigned int order, int alloc_flags, } try_this_zone: - page = rmqueue(zonelist_zone(ac->preferred_zoneref), zone, order, + page = rmqueue(preferred_zone, zone, order, gfp_mask, alloc_flags, ac->migratetype); if (page) { prep_new_page(page, order, gfp_mask, alloc_flags); @@ -4416,7 +4427,7 @@ static DEFINE_SEQLOCK(zonelist_update_seq); static unsigned int zonelist_iter_begin(void) { - if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE)) + if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG)) return read_seqbegin(&zonelist_update_seq); return 0; @@ -4424,7 +4435,7 @@ static unsigned int zonelist_iter_begin(void) static unsigned int check_retry_zonelist(unsigned int seq) { - if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE)) + if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG)) return read_seqretry(&zonelist_update_seq, seq); return seq; @@ -4674,7 +4685,7 @@ should_reclaim_retry(gfp_t gfp_mask, unsigned order, */ wmark = __zone_watermark_ok(zone, order, min_wmark, ac->highest_zoneidx, alloc_flags, available); - trace_reclaim_retry_zone(z, order, reclaimable, + trace_reclaim_retry_zone(zone, order, reclaimable, available, min_wmark, *no_progress_loops, wmark); if (wmark) { ret = true; @@ -4738,10 +4749,10 @@ static inline struct page * __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order, struct alloc_context *ac) { - bool can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM; - bool can_compact = gfp_compaction_allowed(gfp_mask); - bool nofail = gfp_mask & __GFP_NOFAIL; const bool costly_order = order > PAGE_ALLOC_COSTLY_ORDER; + bool can_direct_reclaim; + bool can_compact; + bool nofail; struct page *page = NULL; unsigned int alloc_flags; unsigned long did_some_progress; @@ -4753,6 +4764,18 @@ __alloc_pages_slowpath(gfp_t gfp_mask, unsigned int order, unsigned int zonelist_iter_cookie; int reserve_flags; + /* + * Costly __GFP_NORETRY callers have a cheap fallback, so don't stall + * them in reclaim or compaction. __GFP_THISNODE callers are exempt. + */ + if (costly_order && (gfp_mask & __GFP_NORETRY) && + !(gfp_mask & __GFP_THISNODE)) + gfp_mask &= ~__GFP_DIRECT_RECLAIM; + + can_direct_reclaim = gfp_mask & __GFP_DIRECT_RECLAIM; + can_compact = gfp_compaction_allowed(gfp_mask); + nofail = gfp_mask & __GFP_NOFAIL; + if (unlikely(nofail)) { /* * We most definitely don't want callers attempting to @@ -5144,6 +5167,7 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid, struct page *page; unsigned long __maybe_unused UP_flags; struct zone *zone; + struct zone *preferred_zone; struct zoneref *z; struct per_cpu_pages *pcp; struct list_head *pcp_list; @@ -5194,6 +5218,11 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid, goto out; gfp = alloc_gfp; + /* Read once; see get_page_from_freelist(). */ + preferred_zone = zonelist_zone(ac.preferred_zoneref); + if (!preferred_zone) + goto failed; + /* Find an allowed local zone that meets the low watermark. */ z = ac.preferred_zoneref; for_next_zone_zonelist_nodemask(zone, z, ac.highest_zoneidx, ac.nodemask) { @@ -5204,8 +5233,8 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid, continue; } - if (nr_online_nodes > 1 && zone != zonelist_zone(ac.preferred_zoneref) && - zone_to_nid(zone) != zonelist_node_idx(ac.preferred_zoneref)) { + if (nr_online_nodes > 1 && zone != preferred_zone && + zone_to_nid(zone) != zone_to_nid(preferred_zone)) { goto failed; } @@ -5213,7 +5242,7 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid, retry_this_zone: mark = wmark_pages(zone, alloc_flags & ALLOC_WMARK_MASK) + nr_pages; if (zone_watermark_fast(zone, 0, mark, - zonelist_zone_idx(ac.preferred_zoneref), + zone_idx(preferred_zone), alloc_flags, gfp)) { break; } @@ -5272,7 +5301,7 @@ unsigned long alloc_pages_bulk_noprof(gfp_t gfp, int preferred_nid, pcp_trylock_finish(UP_flags); __count_zid_vm_events(PGALLOC, zone_idx(zone), nr_account); - zone_statistics(zonelist_zone(ac.preferred_zoneref), zone, nr_account); + zone_statistics(preferred_zone, zone, nr_account); out: return nr_populated; @@ -6198,6 +6227,10 @@ void __meminit setup_zone_pageset(struct zone *zone) { int cpu; + /* The zone has been populated before, see zone_pcp_reset(). */ + if (zone->per_cpu_pageset != &boot_pageset) + return; + /* Size may be 0 on !SMP && !NUMA */ if (sizeof(struct per_cpu_zonestat) > 0) zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat); @@ -6291,6 +6324,10 @@ void __init setup_per_cpu_pageset(void) __meminit void zone_pcp_init(struct zone *zone) { + /* This initialization only needs to be done once */ + if (zone->per_cpu_pageset) + return; + /* * per cpu subsystem is not up at this point. The following code * relies on the ability of the linker to provide the @@ -7092,9 +7129,13 @@ int alloc_contig_range_noprof(unsigned long start, unsigned long end, * put back to page allocator so that buddy can use them. */ + /* + * On failure this has undone its own isolation, and any other + * isolated blocks in the range belong to someone else, e.g. offline. + */ ret = start_isolate_page_range(start, end, mode); if (ret) - goto done; + return ret; drain_all_pages(cc.zone); @@ -7328,6 +7369,12 @@ void zone_pcp_enable(struct zone *zone) mutex_unlock(&pcp_batch_high_lock); } +/* + * The zone has become empty. Its pagesets and zonestats are not freed: nothing + * keeps somebody who found the zone populated, such as refresh_cpu_vm_stats() + * or drain_all_pages(), from still using them. They are used again when the + * zone gets memory again. + */ void zone_pcp_reset(struct zone *zone) { int cpu; @@ -7338,12 +7385,6 @@ void zone_pcp_reset(struct zone *zone) pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu); drain_zonestat(zone, pzstats); } - free_percpu(zone->per_cpu_pageset); - zone->per_cpu_pageset = &boot_pageset; - if (zone->per_cpu_zonestats != &boot_zonestats) { - free_percpu(zone->per_cpu_zonestats); - zone->per_cpu_zonestats = &boot_zonestats; - } } } diff --git a/mm/page_frag_cache.c b/mm/page_frag_cache.c index d2423f30577e..40cfd5bebf5c 100644 --- a/mm/page_frag_cache.c +++ b/mm/page_frag_cache.c @@ -119,15 +119,20 @@ void *__page_frag_alloc_align(struct page_frag_cache *nc, size = PAGE_SIZE << encoded_page_decode_order(encoded_page); offset = __ALIGN_KERNEL_MASK(nc->offset, ~align_mask); if (unlikely(offset + fragsz > size)) { - if (unlikely(fragsz > PAGE_SIZE)) { + if (unlikely(fragsz > size)) { /* - * The caller is trying to allocate a fragment - * with fragsz > PAGE_SIZE but the cache isn't big - * enough to satisfy the request, this may - * happen in low memory conditions. - * We don't release the cache page because - * it could make memory pressure worse - * so we simply return NULL here. + * The caller is trying to allocate a fragment that's + * larger than the whole cache page. + * + * Either fragsz is larger than PAGE_FRAG_CACHE_MAX_SIZE + * so this cannot ever succeed. + * + * Or the refill has fallen back to order-0 due to a low + * memory condition. Then we don't want to release the + * cache page to attempt a new large-size refill because + * it could make memory pressure worse. + * + * So in both cases we simply return NULL here. */ return NULL; } diff --git a/mm/shmem.c b/mm/shmem.c index 82216c44f67d..ab6b2e5f4416 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -3183,7 +3183,7 @@ static struct inode *__shmem_get_inode(struct mnt_idmap *idmap, inode->i_size = 2 * BOGO_DIRENT_SIZE; inode->i_op = &shmem_dir_inode_operations; inode->i_fop = &simple_offset_dir_operations; - simple_offset_init(shmem_get_offset_ctx(inode)); + simple_offset_init(shmem_get_offset_ctx(inode), inode); break; case S_IFLNK: /* diff --git a/mm/slub.c b/mm/slub.c index 8fdbe531a0cb..d49b6f69136c 100644 --- a/mm/slub.c +++ b/mm/slub.c @@ -462,6 +462,7 @@ struct node_barn { spinlock_t lock; struct list_head sheaves_full; struct list_head sheaves_empty; + struct slab_sheaf *sheaf_partial; unsigned int nr_full; unsigned int nr_empty; }; @@ -3047,6 +3048,7 @@ static void barn_init(struct node_barn *barn) spin_lock_init(&barn->lock); INIT_LIST_HEAD(&barn->sheaves_full); INIT_LIST_HEAD(&barn->sheaves_empty); + barn->sheaf_partial = NULL; barn->nr_full = 0; barn->nr_empty = 0; } @@ -3067,6 +3069,10 @@ static void barn_shrink(struct kmem_cache *s, struct node_barn *barn) barn->nr_full = 0; list_splice_init(&barn->sheaves_empty, &empty_list); barn->nr_empty = 0; + if (barn->sheaf_partial) { + list_add(&barn->sheaf_partial->barn_list, &full_list); + barn->sheaf_partial = NULL; + } spin_unlock_irqrestore(&barn->lock, flags); @@ -5381,6 +5387,78 @@ void *kmem_cache_alloc_node_noprof(struct kmem_cache *s, gfp_t gfpflags, int nod } EXPORT_SYMBOL(kmem_cache_alloc_node_noprof); +/* + * Refill @sheaf from the barn: from its partial sheaf first, then from its full + * sheaves. A sheaf that objects were copied from stays in the barn as the + * partial sheaf if it still holds objects, or goes on the empty list if it is + * empty. + * + * Returns true if the sheaf is now full, at s->sheaf_capacity. + * Returns false if the sheaf is still not full. + */ +static bool refill_sheaf_from_barn(struct kmem_cache *s, + struct slab_sheaf *sheaf) +{ + struct node_barn *barn = get_barn(s); + struct slab_sheaf *src; + unsigned int to_move; + unsigned long flags; + + if (!barn) + return false; + + if (!data_race(barn->nr_full) && !data_race(barn->sheaf_partial)) + return false; + + spin_lock_irqsave(&barn->lock, flags); + + /* + * The partial sheaf can hold fewer objects than @sheaf needs to + * reach capacity, and a sheaf on the full list is not necessarily + * full (see the comment in rcu_free_sheaf()), so keep taking from + * the barn until @sheaf is full or nothing is left. + */ + while (sheaf->size < s->sheaf_capacity) { + src = barn->sheaf_partial; + barn->sheaf_partial = NULL; + if (!src) { + if (!barn->nr_full) + break; + src = list_first_entry(&barn->sheaves_full, + struct slab_sheaf, barn_list); + list_del(&src->barn_list); + barn->nr_full--; + } + + to_move = min(s->sheaf_capacity - sheaf->size, src->size); + src->size -= to_move; + memcpy(&sheaf->objects[sheaf->size], &src->objects[src->size], + to_move * sizeof(void *)); + sheaf->size += to_move; + + if (src->size) { + barn->sheaf_partial = src; + } else { + /* + * No empty-limit check: the sheaf put on the empty list + * was already in the barn, so the barn holds no more + * sheaves than before. barn_replace_empty_sheaf() skips + * the check for the same reason. + */ + list_add(&src->barn_list, &barn->sheaves_empty); + barn->nr_empty++; + } + } + + spin_unlock_irqrestore(&barn->lock, flags); + + if (sheaf->size < s->sheaf_capacity) + return false; + + stat(s, BARN_GET); + return true; +} + /* * returns a sheaf that has at least the requested size * when prefilling is needed, do so with given gfp flags @@ -5452,7 +5530,8 @@ kmem_cache_prefill_sheaf(struct kmem_cache *s, gfp_t gfp, unsigned int size) sheaf = alloc_empty_sheaf(s, gfp); if (sheaf && sheaf->size < size) { - if (refill_sheaf(s, sheaf, gfp)) { + if (!refill_sheaf_from_barn(s, sheaf) && + refill_sheaf(s, sheaf, gfp)) { sheaf_flush_unused(s, sheaf); free_empty_sheaf(s, sheaf); sheaf = NULL; @@ -5546,8 +5625,11 @@ int kmem_cache_refill_sheaf(struct kmem_cache *s, gfp_t gfp, return 0; if (likely(sheaf->capacity >= size)) { - if (likely(sheaf->capacity == s->sheaf_capacity)) + if (likely(sheaf->capacity == s->sheaf_capacity)) { + if (refill_sheaf_from_barn(s, sheaf)) + return 0; return refill_sheaf(s, sheaf, gfp); + } if (!__kmem_cache_alloc_bulk(s, gfp, sheaf->capacity - sheaf->size, &sheaf->objects[sheaf->size])) { diff --git a/net/9p/client.c b/net/9p/client.c index 75aac636b20e..5d0ed3e5797f 100644 --- a/net/9p/client.c +++ b/net/9p/client.c @@ -20,8 +20,8 @@ #include #include #include -#include #include +#include #include #include #include "protocol.h" @@ -29,32 +29,10 @@ #define CREATE_TRACE_POINTS #include -/* DEFAULT MSIZE = 32 pages worth of payload + P9_HDRSZ + - * room for write (16 extra) or read (11 extra) operands. - */ - -#define DEFAULT_MSIZE ((128 * 1024) + P9_IOHDRSZ) - /* Client Option Parsing (code inspired by NFS code) * - a little lazy - parse all client options */ -enum { - Opt_msize, - Opt_trans, - Opt_legacy, - Opt_version, - Opt_err, -}; - -static const match_table_t tokens = { - {Opt_msize, "msize=%u"}, - {Opt_legacy, "noextend"}, - {Opt_trans, "trans=%s"}, - {Opt_version, "version=%s"}, - {Opt_err, NULL}, -}; - inline int p9_is_proto_dotl(struct p9_client *clnt) { return clnt->proto_version == p9_proto_2000L; @@ -103,124 +81,16 @@ static int safe_errno(int err) return err; } -/* Interpret mount option for protocol version */ -static int get_protocol_version(char *s) -{ - int version = -EINVAL; - - if (!strcmp(s, "9p2000")) { - version = p9_proto_legacy; - p9_debug(P9_DEBUG_9P, "Protocol version: Legacy\n"); - } else if (!strcmp(s, "9p2000.u")) { - version = p9_proto_2000u; - p9_debug(P9_DEBUG_9P, "Protocol version: 9P2000.u\n"); - } else if (!strcmp(s, "9p2000.L")) { - version = p9_proto_2000L; - p9_debug(P9_DEBUG_9P, "Protocol version: 9P2000.L\n"); - } else { - pr_info("Unknown protocol version %s\n", s); - } - - return version; -} - -/** - * parse_opts - parse mount options into client structure - * @opts: options string passed from mount - * @clnt: existing v9fs client information - * - * Return 0 upon success, -ERRNO upon failure - */ - -static int parse_opts(char *opts, struct p9_client *clnt) +static int apply_client_options(struct p9_client *clnt, struct fs_context *fc) { - char *options, *tmp_options; - char *p; - substring_t args[MAX_OPT_ARGS]; - int option; - char *s; - int ret = 0; + struct v9fs_context *ctx = fc->fs_private; - clnt->proto_version = p9_proto_2000L; - clnt->msize = DEFAULT_MSIZE; + clnt->msize = ctx->client_opts.msize; + clnt->trans_mod = ctx->client_opts.trans_mod; + ctx->client_opts.trans_mod = NULL; + clnt->proto_version = ctx->client_opts.proto_version; - if (!opts) - return 0; - - tmp_options = kstrdup(opts, GFP_KERNEL); - if (!tmp_options) - return -ENOMEM; - options = tmp_options; - - while ((p = strsep(&options, ",")) != NULL) { - int token, r; - - if (!*p) - continue; - token = match_token(p, tokens, args); - switch (token) { - case Opt_msize: - r = match_int(&args[0], &option); - if (r < 0) { - p9_debug(P9_DEBUG_ERROR, - "integer field, but no integer?\n"); - ret = r; - continue; - } - if (option < 4096) { - p9_debug(P9_DEBUG_ERROR, - "msize should be at least 4k\n"); - ret = -EINVAL; - continue; - } - clnt->msize = option; - break; - case Opt_trans: - s = match_strdup(&args[0]); - if (!s) { - ret = -ENOMEM; - p9_debug(P9_DEBUG_ERROR, - "problem allocating copy of trans arg\n"); - goto free_and_return; - } - - v9fs_put_trans(clnt->trans_mod); - clnt->trans_mod = v9fs_get_trans_by_name(s); - if (!clnt->trans_mod) { - pr_info("Could not find request transport: %s\n", - s); - ret = -EINVAL; - } - kfree(s); - break; - case Opt_legacy: - clnt->proto_version = p9_proto_legacy; - break; - case Opt_version: - s = match_strdup(&args[0]); - if (!s) { - ret = -ENOMEM; - p9_debug(P9_DEBUG_ERROR, - "problem allocating copy of version arg\n"); - goto free_and_return; - } - r = get_protocol_version(s); - if (r < 0) - ret = r; - else - clnt->proto_version = r; - kfree(s); - break; - default: - continue; - } - } - -free_and_return: - if (ret) - v9fs_put_trans(clnt->trans_mod); - kfree(tmp_options); - return ret; + return 0; } static int p9_fcall_init(struct p9_client *c, struct p9_fcall *fc, @@ -976,7 +846,7 @@ static int p9_client_version(struct p9_client *c) return err; } -struct p9_client *p9_client_create(const char *dev_name, char *options) +struct p9_client *p9_client_create(struct fs_context *fc) { int err; static atomic_t seqno = ATOMIC_INIT(0); @@ -999,8 +869,8 @@ struct p9_client *p9_client_create(const char *dev_name, char *options) idr_init(&clnt->fids); idr_init(&clnt->reqs); - err = parse_opts(options, clnt); - if (err < 0) + err = apply_client_options(clnt, fc); + if (err) goto free_client; if (!clnt->trans_mod) @@ -1016,7 +886,7 @@ struct p9_client *p9_client_create(const char *dev_name, char *options) p9_debug(P9_DEBUG_MUX, "clnt %p trans %p msize %d protocol %d\n", clnt, clnt->trans_mod, clnt->msize, clnt->proto_version); - err = clnt->trans_mod->create(clnt, dev_name, options); + err = clnt->trans_mod->create(clnt, fc); if (err) goto put_trans; diff --git a/net/9p/mod.c b/net/9p/mod.c index 55576c1866fa..85160b52da55 100644 --- a/net/9p/mod.c +++ b/net/9p/mod.c @@ -16,7 +16,6 @@ #include #include #include -#include #include #include #include @@ -171,6 +170,7 @@ void v9fs_put_trans(struct p9_trans_module *m) if (m) module_put(m->owner); } +EXPORT_SYMBOL(v9fs_put_trans); /** * init_p9 - Initialize module diff --git a/net/9p/protocol.c b/net/9p/protocol.c index 0e6603b1ec90..0a97b4de243a 100644 --- a/net/9p/protocol.c +++ b/net/9p/protocol.c @@ -771,7 +771,7 @@ int p9dirent_read(struct p9_client *clnt, char *buf, int len, { struct p9_fcall fake_pdu; int ret; - char *nameptr; + char *nameptr = NULL; fake_pdu.size = len; fake_pdu.capacity = len; @@ -786,15 +786,7 @@ int p9dirent_read(struct p9_client *clnt, char *buf, int len, return ret; } - ret = strscpy(dirent->d_name, nameptr, sizeof(dirent->d_name)); - if (ret < 0) { - p9_debug(P9_DEBUG_ERROR, - "On the wire dirent name too long: %s\n", - nameptr); - kfree(nameptr); - return ret; - } - kfree(nameptr); + dirent->d_name = nameptr; return fake_pdu.offset; } diff --git a/net/9p/trans_fd.c b/net/9p/trans_fd.c index a516745f732f..780d4ee397f8 100644 --- a/net/9p/trans_fd.c +++ b/net/9p/trans_fd.c @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include #include #include @@ -31,48 +31,12 @@ #include /* killme */ -#define P9_PORT 564 #define MAX_SOCK_BUF (1024*1024) #define MAXPOLLWADDR 2 static struct p9_trans_module p9_tcp_trans; static struct p9_trans_module p9_fd_trans; -/** - * struct p9_fd_opts - per-transport options - * @rfd: file descriptor for reading (trans=fd) - * @wfd: file descriptor for writing (trans=fd) - * @port: port to connect to (trans=tcp) - * @privport: port is privileged - */ - -struct p9_fd_opts { - int rfd; - int wfd; - u16 port; - bool privport; -}; - -/* - * Option Parsing (code inspired by NFS code) - * - a little lazy - parse all fd-transport options - */ - -enum { - /* Options that take integer arguments */ - Opt_port, Opt_rfdno, Opt_wfdno, Opt_err, - /* Options that take no arguments */ - Opt_privport, -}; - -static const match_table_t tokens = { - {Opt_port, "port=%u"}, - {Opt_rfdno, "rfdno=%u"}, - {Opt_wfdno, "wfdno=%u"}, - {Opt_privport, "privport"}, - {Opt_err, NULL}, -}; - enum { Rworksched = 1, /* read work scheduled or running */ Rpending = 2, /* can read */ @@ -742,7 +706,7 @@ static int p9_fd_cancelled(struct p9_client *client, struct p9_req_t *req) static int p9_fd_show_options(struct seq_file *m, struct p9_client *clnt) { if (clnt->trans_mod == &p9_tcp_trans) { - if (clnt->trans_opts.tcp.port != P9_PORT) + if (clnt->trans_opts.tcp.port != P9_FD_PORT) seq_printf(m, ",port=%u", clnt->trans_opts.tcp.port); } else if (clnt->trans_mod == &p9_fd_trans) { if (clnt->trans_opts.fd.rfd != ~0) @@ -753,73 +717,6 @@ static int p9_fd_show_options(struct seq_file *m, struct p9_client *clnt) return 0; } -/** - * parse_opts - parse mount options into p9_fd_opts structure - * @params: options string passed from mount - * @opts: fd transport-specific structure to parse options into - * - * Returns 0 upon success, -ERRNO upon failure - */ - -static int parse_opts(char *params, struct p9_fd_opts *opts) -{ - char *p; - substring_t args[MAX_OPT_ARGS]; - int option; - char *options, *tmp_options; - - opts->port = P9_PORT; - opts->rfd = ~0; - opts->wfd = ~0; - opts->privport = false; - - if (!params) - return 0; - - tmp_options = kstrdup(params, GFP_KERNEL); - if (!tmp_options) { - p9_debug(P9_DEBUG_ERROR, - "failed to allocate copy of option string\n"); - return -ENOMEM; - } - options = tmp_options; - - while ((p = strsep(&options, ",")) != NULL) { - int token; - int r; - if (!*p) - continue; - token = match_token(p, tokens, args); - if ((token != Opt_err) && (token != Opt_privport)) { - r = match_int(&args[0], &option); - if (r < 0) { - p9_debug(P9_DEBUG_ERROR, - "integer field, but no integer?\n"); - continue; - } - } - switch (token) { - case Opt_port: - opts->port = option; - break; - case Opt_rfdno: - opts->rfd = option; - break; - case Opt_wfdno: - opts->wfd = option; - break; - case Opt_privport: - opts->privport = true; - break; - default: - continue; - } - } - - kfree(tmp_options); - return 0; -} - static int p9_fd_open(struct p9_client *client, int rfd, int wfd) { struct p9_trans_fd *ts = kzalloc(sizeof(struct p9_trans_fd), @@ -974,24 +871,25 @@ static int p9_bind_privport(struct socket *sock) } static int -p9_fd_create_tcp(struct p9_client *client, const char *addr, char *args) +p9_fd_create_tcp(struct p9_client *client, struct fs_context *fc) { + const char *addr = fc->source; + struct v9fs_context *ctx = fc->fs_private; int err; char port_str[6]; struct socket *csocket; struct sockaddr_storage stor = { 0 }; struct p9_fd_opts opts; - err = parse_opts(args, &opts); - if (err < 0) - return err; + /* opts are already parsed in context */ + opts = ctx->fd_opts; if (!addr) return -EINVAL; sprintf(port_str, "%u", opts.port); - err = inet_pton_with_scope(current->nsproxy->net_ns, AF_UNSPEC, addr, - port_str, &stor); + err = inet_pton_with_scope(fc->net_ns, AF_UNSPEC, addr, port_str, + &stor); if (err < 0) return err; @@ -999,8 +897,8 @@ p9_fd_create_tcp(struct p9_client *client, const char *addr, char *args) client->trans_opts.tcp.port = opts.port; client->trans_opts.tcp.privport = opts.privport; - err = __sock_create(current->nsproxy->net_ns, stor.ss_family, - SOCK_STREAM, IPPROTO_TCP, &csocket, 1); + err = __sock_create(fc->net_ns, stor.ss_family, SOCK_STREAM, + IPPROTO_TCP, &csocket, 1); if (err) { pr_err("%s (%d): problem creating socket\n", __func__, task_pid_nr(current)); @@ -1031,8 +929,9 @@ p9_fd_create_tcp(struct p9_client *client, const char *addr, char *args) } static int -p9_fd_create_unix(struct p9_client *client, const char *addr, char *args) +p9_fd_create_unix(struct p9_client *client, struct fs_context *fc) { + const char *addr = fc->source; int err; struct socket *csocket; struct sockaddr_un sun_server; @@ -1042,16 +941,13 @@ p9_fd_create_unix(struct p9_client *client, const char *addr, char *args) if (!addr || !strlen(addr)) return -EINVAL; - if (strlen(addr) >= UNIX_PATH_MAX) { + sun_server.sun_family = PF_UNIX; + if (strscpy(sun_server.sun_path, addr) < 0) { pr_err("%s (%d): address too long: %s\n", __func__, task_pid_nr(current), addr); return -ENAMETOOLONG; } - - sun_server.sun_family = PF_UNIX; - strcpy(sun_server.sun_path, addr); - err = __sock_create(current->nsproxy->net_ns, PF_UNIX, - SOCK_STREAM, 0, &csocket, 1); + err = __sock_create(fc->net_ns, PF_UNIX, SOCK_STREAM, 0, &csocket, 1); if (err < 0) { pr_err("%s (%d): problem creating socket\n", __func__, task_pid_nr(current)); @@ -1071,14 +967,12 @@ p9_fd_create_unix(struct p9_client *client, const char *addr, char *args) } static int -p9_fd_create(struct p9_client *client, const char *addr, char *args) +p9_fd_create(struct p9_client *client, struct fs_context *fc) { + struct v9fs_context *ctx = fc->fs_private; + struct p9_fd_opts opts = ctx->fd_opts; int err; - struct p9_fd_opts opts; - err = parse_opts(args, &opts); - if (err < 0) - return err; client->trans_opts.fd.rfd = opts.rfd; client->trans_opts.fd.wfd = opts.wfd; diff --git a/net/9p/trans_rdma.c b/net/9p/trans_rdma.c index d9f53f1da2c2..e5c5575849d6 100644 --- a/net/9p/trans_rdma.c +++ b/net/9p/trans_rdma.c @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include #include #include @@ -32,14 +32,10 @@ #include #include -#define P9_PORT 5640 -#define P9_RDMA_SQ_DEPTH 32 -#define P9_RDMA_RQ_DEPTH 32 #define P9_RDMA_SEND_SGE 4 #define P9_RDMA_RECV_SGE 4 #define P9_RDMA_IRD 0 #define P9_RDMA_ORD 0 -#define P9_RDMA_TIMEOUT 30000 /* 30 seconds */ #define P9_RDMA_MAXSIZE (1024*1024) /* 1MB */ /** @@ -110,48 +106,11 @@ struct p9_rdma_context { }; }; -/** - * struct p9_rdma_opts - Collection of mount options - * @port: port of connection - * @privport: Whether a privileged port may be used - * @sq_depth: The requested depth of the SQ. This really doesn't need - * to be any deeper than the number of threads used in the client - * @rq_depth: The depth of the RQ. Should be greater than or equal to SQ depth - * @timeout: Time to wait in msecs for CM events - */ -struct p9_rdma_opts { - short port; - bool privport; - int sq_depth; - int rq_depth; - long timeout; -}; - -/* - * Option Parsing (code inspired by NFS code) - */ -enum { - /* Options that take integer arguments */ - Opt_port, Opt_rq_depth, Opt_sq_depth, Opt_timeout, - /* Options that take no argument */ - Opt_privport, - Opt_err, -}; - -static match_table_t tokens = { - {Opt_port, "port=%u"}, - {Opt_sq_depth, "sq=%u"}, - {Opt_rq_depth, "rq=%u"}, - {Opt_timeout, "timeout=%u"}, - {Opt_privport, "privport"}, - {Opt_err, NULL}, -}; - static int p9_rdma_show_options(struct seq_file *m, struct p9_client *clnt) { struct p9_trans_rdma *rdma = clnt->trans; - if (rdma->port != P9_PORT) + if (rdma->port != P9_RDMA_PORT) seq_printf(m, ",port=%u", rdma->port); if (rdma->sq_depth != P9_RDMA_SQ_DEPTH) seq_printf(m, ",sq=%u", rdma->sq_depth); @@ -164,77 +123,6 @@ static int p9_rdma_show_options(struct seq_file *m, struct p9_client *clnt) return 0; } -/** - * parse_opts - parse mount options into rdma options structure - * @params: options string passed from mount - * @opts: rdma transport-specific structure to parse options into - * - * Returns 0 upon success, -ERRNO upon failure - */ -static int parse_opts(char *params, struct p9_rdma_opts *opts) -{ - char *p; - substring_t args[MAX_OPT_ARGS]; - int option; - char *options, *tmp_options; - - opts->port = P9_PORT; - opts->sq_depth = P9_RDMA_SQ_DEPTH; - opts->rq_depth = P9_RDMA_RQ_DEPTH; - opts->timeout = P9_RDMA_TIMEOUT; - opts->privport = false; - - if (!params) - return 0; - - tmp_options = kstrdup(params, GFP_KERNEL); - if (!tmp_options) { - p9_debug(P9_DEBUG_ERROR, - "failed to allocate copy of option string\n"); - return -ENOMEM; - } - options = tmp_options; - - while ((p = strsep(&options, ",")) != NULL) { - int token; - int r; - if (!*p) - continue; - token = match_token(p, tokens, args); - if ((token != Opt_err) && (token != Opt_privport)) { - r = match_int(&args[0], &option); - if (r < 0) { - p9_debug(P9_DEBUG_ERROR, - "integer field, but no integer?\n"); - continue; - } - } - switch (token) { - case Opt_port: - opts->port = option; - break; - case Opt_sq_depth: - opts->sq_depth = option; - break; - case Opt_rq_depth: - opts->rq_depth = option; - break; - case Opt_timeout: - opts->timeout = option; - break; - case Opt_privport: - opts->privport = true; - break; - default: - continue; - } - } - /* RQ must be at least as large as the SQ */ - opts->rq_depth = max(opts->rq_depth, opts->sq_depth); - kfree(tmp_options); - return 0; -} - static int p9_cm_event_handler(struct rdma_cm_id *id, struct rdma_cm_event *event) { @@ -643,14 +531,15 @@ static int p9_rdma_bind_privport(struct p9_trans_rdma *rdma) /** * rdma_create_trans - Transport method for creating a transport instance * @client: client instance - * @addr: IP address string - * @args: Mount options string + * @fc: The filesystem context */ static int -rdma_create_trans(struct p9_client *client, const char *addr, char *args) +rdma_create_trans(struct p9_client *client, struct fs_context *fc) { + const char *addr = fc->source; + struct v9fs_context *ctx = fc->fs_private; + struct p9_rdma_opts opts = ctx->rdma_opts; int err; - struct p9_rdma_opts opts; struct p9_trans_rdma *rdma; struct rdma_conn_param conn_param; struct ib_qp_init_attr qp_attr; @@ -658,10 +547,8 @@ rdma_create_trans(struct p9_client *client, const char *addr, char *args) if (addr == NULL) return -EINVAL; - /* Parse the transport specific mount options */ - err = parse_opts(args, &opts); - if (err < 0) - return err; + /* options are already parsed, in the fs context */ + opts = ctx->rdma_opts; /* Create and initialize the RDMA transport structure */ rdma = alloc_rdma(&opts); @@ -669,7 +556,7 @@ rdma_create_trans(struct p9_client *client, const char *addr, char *args) return -ENOMEM; /* Create the RDMA CM ID */ - rdma->cm_id = rdma_create_id(&init_net, p9_cm_event_handler, client, + rdma->cm_id = rdma_create_id(fc->net_ns, p9_cm_event_handler, client, RDMA_PS_TCP, IB_QPT_RC); if (IS_ERR(rdma->cm_id)) goto error; diff --git a/net/9p/trans_usbg.c b/net/9p/trans_usbg.c index 938e3130ab81..79735bbe739a 100644 --- a/net/9p/trans_usbg.c +++ b/net/9p/trans_usbg.c @@ -27,6 +27,7 @@ #include #include #include +#include #include #include @@ -392,8 +393,9 @@ enable_usb9pfs(struct usb_composite_dev *cdev, struct f_usb9pfs *usb9pfs) return ret; } -static int p9_usbg_create(struct p9_client *client, const char *devname, char *args) +static int p9_usbg_create(struct p9_client *client, struct fs_context *fc) { + const char *devname = fc->source; struct f_usb9pfs_dev *dev; struct f_usb9pfs *usb9pfs; int ret = -ENOENT; @@ -458,6 +460,11 @@ static void usb9pfs_clear_tx(struct f_usb9pfs *usb9pfs) if (!req || !client) return; + usb9pfs->in_req->context = NULL; + + if (!usb9pfs->client) + return; + if (!req->t_err) req->t_err = -ECONNRESET; @@ -481,6 +488,7 @@ static void p9_usbg_close(struct p9_client *client) client->status = Disconnected; usb9pfs_clear_tx(usb9pfs); + usb9pfs->client = NULL; opts = container_of(usb9pfs->function.fi, struct f_usb9pfs_opts, func_inst); @@ -751,8 +759,6 @@ static void usb9pfs_free_func(struct usb_function *f) struct f_usb9pfs *usb9pfs = func_to_usb9pfs(f); struct f_usb9pfs_opts *opts; - kfree(usb9pfs); - opts = container_of(f->fi, struct f_usb9pfs_opts, func_inst); mutex_lock(&opts->lock); @@ -760,6 +766,8 @@ static void usb9pfs_free_func(struct usb_function *f) mutex_unlock(&opts->lock); usb_free_all_descriptors(f); + + kfree(usb9pfs); } static int usb9pfs_set_alt(struct usb_function *f, diff --git a/net/9p/trans_virtio.c b/net/9p/trans_virtio.c index d1a680f69911..6c2a134e7d85 100644 --- a/net/9p/trans_virtio.c +++ b/net/9p/trans_virtio.c @@ -26,7 +26,7 @@ #include #include #include -#include +#include #include #include #include @@ -684,8 +684,7 @@ static int p9_virtio_probe(struct virtio_device *vdev) /** * p9_virtio_create - allocate a new virtio channel * @client: client instance invoking this transport - * @devname: string identifying the channel to connect to (unused) - * @args: args passed from sys_mount() for per-transport options (unused) + * @fc: the filesystem context * * This sets up a transport channel for 9p communication. Right now * we only match the first available channel, but eventually we could look up @@ -696,8 +695,9 @@ static int p9_virtio_probe(struct virtio_device *vdev) */ static int -p9_virtio_create(struct p9_client *client, const char *devname, char *args) +p9_virtio_create(struct p9_client *client, struct fs_context *fc) { + const char *devname = fc->source; struct virtio_chan *chan; int ret = -ENOENT; int found = 0; diff --git a/net/9p/trans_xen.c b/net/9p/trans_xen.c index ef9bac5f4a24..95f314f0285e 100644 --- a/net/9p/trans_xen.c +++ b/net/9p/trans_xen.c @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -66,8 +67,9 @@ static int p9_xen_cancel(struct p9_client *client, struct p9_req_t *req) return 1; } -static int p9_xen_create(struct p9_client *client, const char *addr, char *args) +static int p9_xen_create(struct p9_client *client, struct fs_context *fc) { + const char *addr = fc->source; struct xen_9pfs_front_priv *priv; if (addr == NULL) diff --git a/net/ax25/ax25_in.c b/net/ax25/ax25_in.c index fd8669e5b731..068f0c6c54ce 100644 --- a/net/ax25/ax25_in.c +++ b/net/ax25/ax25_in.c @@ -87,16 +87,26 @@ static int ax25_rx_fragment(ax25_cb *ax25, struct sk_buff *skb) return 1; } } - } else { - /* First fragment received */ - if (*skb->data & AX25_SEG_FIRST) { - skb_queue_purge(&ax25->frag_queue); - ax25->fragno = *skb->data & AX25_SEG_REM; - skb_pull(skb, 1); /* skip fragno */ - ax25->fraglen = skb->len; - skb_queue_tail(&ax25->frag_queue, skb); - return 1; - } + + /* + * A new first segment, or a segment out of order: the message + * being reassembled can no longer be completed. Drop it, or + * fragno would never come back to 0 and every later segmented + * message of this connection would be thrown away as well. + */ + skb_queue_purge(&ax25->frag_queue); + ax25->fragno = 0; + ax25->fraglen = 0; + } + + /* First fragment received */ + if (*skb->data & AX25_SEG_FIRST) { + skb_queue_purge(&ax25->frag_queue); + ax25->fragno = *skb->data & AX25_SEG_REM; + skb_pull(skb, 1); /* skip fragno */ + ax25->fraglen = skb->len; + skb_queue_tail(&ax25->frag_queue, skb); + return 1; } return 0; diff --git a/net/ax25/ax25_std_in.c b/net/ax25/ax25_std_in.c index d0269ece4fc5..92d89d4df0f8 100644 --- a/net/ax25/ax25_std_in.c +++ b/net/ax25/ax25_std_in.c @@ -190,7 +190,12 @@ static int ax25_std_state3_machine(ax25_cb *ax25, struct sk_buff *skb, int frame if (type == AX25_COMMAND && pf) ax25_std_enquiry_response(ax25); if (ax25_validate_nr(ax25, nr)) { + int progress = nr != ax25->va; + ax25_check_iframes_acked(ax25, nr); + /* Frames got through: end any REJ recovery count. */ + if (progress) + ax25->n2count = 0; } else { ax25_std_nr_error_recovery(ax25); ax25->state = AX25_STATE_1; @@ -202,8 +207,17 @@ static int ax25_std_state3_machine(ax25_cb *ax25, struct sk_buff *skb, int frame if (type == AX25_COMMAND && pf) ax25_std_enquiry_response(ax25); if (ax25_validate_nr(ax25, nr)) { + int progress = nr != ax25->va; + ax25_frames_acked(ax25, nr); ax25_calculate_rtt(ax25); + /* + * Only REJs that make no progress count towards N2: + * a REJ whose N(R) acknowledges new frames shows the + * link is getting data through. + */ + if (progress) + ax25->n2count = 0; /* * REJ triggers an immediate go-back-N retransmit, * deliberately bypassing the T1/N2 backoff that @@ -224,10 +238,11 @@ static int ax25_std_state3_machine(ax25_cb *ax25, struct sk_buff *skb, int frame * once N2 of them have failed to make it through, * fall back to the normal paced state 4 enquiry * (which will genuinely give up and disconnect after - * N2 further tries if the link stays bad). A single - * frame accepted in sequence resets the counter (see - * the AX25_I case below), so an isolated REJ during - * otherwise healthy traffic never gets close to N2. + * N2 further tries if the link stays bad). A frame + * accepted in sequence (see the AX25_I case below) or + * an RR/RNR/REJ that acknowledges new frames resets + * the counter, so an isolated REJ during otherwise + * healthy traffic never gets close to N2. */ if (ax25->n2count == ax25->n2) { ax25->n2count = 1; diff --git a/net/batman-adv/bat_iv_ogm.c b/net/batman-adv/bat_iv_ogm.c index 38320f6a1dd1..26f2795fbc18 100644 --- a/net/batman-adv/bat_iv_ogm.c +++ b/net/batman-adv/bat_iv_ogm.c @@ -1298,7 +1298,7 @@ batadv_iv_ogm_update_seqnos(const struct ethhdr *ethhdr, return BATADV_NO_DUP; orig_ifinfo = batadv_orig_ifinfo_new(orig_node, if_outgoing); - if (WARN_ON(!orig_ifinfo)) { + if (!orig_ifinfo) { batadv_orig_node_put(orig_node); return 0; } diff --git a/net/bluetooth/6lowpan.c b/net/bluetooth/6lowpan.c index 64dffdc8125b..9515b82cda68 100644 --- a/net/bluetooth/6lowpan.c +++ b/net/bluetooth/6lowpan.c @@ -913,18 +913,29 @@ static int bt_6lowpan_connect(bdaddr_t *addr, u8 dst_type) static int bt_6lowpan_disconnect(struct l2cap_conn *conn, u8 dst_type) { struct lowpan_peer *peer; + struct l2cap_chan *chan; BT_DBG("conn %p dst type %u", conn, dst_type); + spin_lock(&devices_lock); + peer = lookup_peer(conn); - if (!peer) + if (!peer) { + spin_unlock(&devices_lock); return -ENOENT; + } + + chan = peer->chan; + l2cap_chan_hold(chan); + + spin_unlock(&devices_lock); - BT_DBG("peer %p chan %p", peer, peer->chan); + BT_DBG("peer %p chan %p", peer, chan); - l2cap_chan_lock(peer->chan); - l2cap_chan_close(peer->chan, ENOENT); - l2cap_chan_unlock(peer->chan); + l2cap_chan_lock(chan); + l2cap_chan_close(chan, ENOENT); + l2cap_chan_unlock(chan); + l2cap_chan_put(chan); return 0; } diff --git a/net/bluetooth/hci_conn.c b/net/bluetooth/hci_conn.c index 32cabe83351a..29e13da00950 100644 --- a/net/bluetooth/hci_conn.c +++ b/net/bluetooth/hci_conn.c @@ -330,8 +330,10 @@ static int hci_enhanced_setup_sync(struct hci_dev *hdev, void *data) cp.out_pcm_sample_payload_msb_pos = 0; cp.in_data_path = conn->codec.data_path; cp.out_data_path = conn->codec.data_path; - cp.in_transport_unit_size = 1; - cp.out_transport_unit_size = 1; + if (conn->codec.data_path) { + cp.in_transport_unit_size = 1; + cp.out_transport_unit_size = 1; + } break; case BT_CODEC_TRANSPARENT: @@ -356,8 +358,10 @@ static int hci_enhanced_setup_sync(struct hci_dev *hdev, void *data) cp.out_pcm_sample_payload_msb_pos = 0; cp.in_data_path = conn->codec.data_path; cp.out_data_path = conn->codec.data_path; - cp.in_transport_unit_size = 1; - cp.out_transport_unit_size = 1; + if (conn->codec.data_path) { + cp.in_transport_unit_size = 1; + cp.out_transport_unit_size = 1; + } break; case BT_CODEC_CVSD: @@ -387,8 +391,10 @@ static int hci_enhanced_setup_sync(struct hci_dev *hdev, void *data) cp.out_pcm_sample_payload_msb_pos = 0; cp.in_data_path = conn->codec.data_path; cp.out_data_path = conn->codec.data_path; - cp.in_transport_unit_size = 16; - cp.out_transport_unit_size = 16; + if (conn->codec.data_path) { + cp.in_transport_unit_size = 16; + cp.out_transport_unit_size = 16; + } break; default: goto unlock; @@ -1488,8 +1494,9 @@ static int hci_explicit_conn_params_set(struct hci_dev *hdev, if (!params) return -ENOMEM; - /* If we created new params, mark them to be deleted in - * hci_connect_le_scan_cleanup. It's different case than + /* If we created new params, mark them to be deleted once the + * explicit connect is done, see le_conn_complete_evt() and + * hci_connect_le_scan_cleanup(). It's different case than * existing disabled params, those will stay after cleanup. */ params->auto_connect = HCI_AUTO_CONN_EXPLICIT; diff --git a/net/bluetooth/hci_core.c b/net/bluetooth/hci_core.c index bb5bbeefcc67..54a8942a022e 100644 --- a/net/bluetooth/hci_core.c +++ b/net/bluetooth/hci_core.c @@ -1111,17 +1111,16 @@ struct link_key *hci_find_link_key(struct hci_dev *hdev, bdaddr_t *bdaddr) rcu_read_lock(); list_for_each_entry_rcu(k, &hdev->link_keys, list) { if (bacmp(bdaddr, &k->bdaddr) == 0) { - rcu_read_unlock(); - if (hci_is_blocked_key(hdev, HCI_BLOCKED_KEY_TYPE_LINKKEY, k->val)) { bt_dev_warn_ratelimited(hdev, "Link key blocked for %pMR", &k->bdaddr); - return NULL; + k = NULL; } + rcu_read_unlock(); return k; } } @@ -1288,7 +1287,6 @@ struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, key = kzalloc(sizeof(*key), GFP_KERNEL); if (!key) return NULL; - list_add_rcu(&key->list, &hdev->link_keys); } BT_DBG("%s key for %pMR type %u", hdev->name, bdaddr, type); @@ -1312,6 +1310,9 @@ struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn, else key->type = type; + if (!old_key) + list_add_rcu(&key->list, &hdev->link_keys); + if (persistent) *persistent = hci_persistent_key(hdev, conn, type, old_key_type); @@ -1333,7 +1334,6 @@ struct smp_ltk *hci_add_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr, key = kzalloc(sizeof(*key), GFP_KERNEL); if (!key) return NULL; - list_add_rcu(&key->list, &hdev->long_term_keys); } bacpy(&key->bdaddr, bdaddr); @@ -1345,15 +1345,19 @@ struct smp_ltk *hci_add_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr, key->enc_size = enc_size; key->type = type; + if (!old_key) + list_add_rcu(&key->list, &hdev->long_term_keys); + return key; } struct smp_irk *hci_add_irk(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 addr_type, u8 val[16], bdaddr_t *rpa) { - struct smp_irk *irk; + struct smp_irk *irk, *old_irk; - irk = hci_find_irk_by_addr(hdev, bdaddr, addr_type); + old_irk = hci_find_irk_by_addr(hdev, bdaddr, addr_type); + irk = old_irk; if (!irk) { irk = kzalloc(sizeof(*irk), GFP_KERNEL); if (!irk) @@ -1362,12 +1366,14 @@ struct smp_irk *hci_add_irk(struct hci_dev *hdev, bdaddr_t *bdaddr, bacpy(&irk->bdaddr, bdaddr); irk->addr_type = addr_type; - list_add_rcu(&irk->list, &hdev->identity_resolving_keys); } memcpy(irk->val, val, 16); bacpy(&irk->rpa, rpa); + if (!old_irk) + list_add_rcu(&irk->list, &hdev->identity_resolving_keys); + return irk; } @@ -1730,6 +1736,9 @@ struct adv_info *hci_add_adv_instance(struct hci_dev *hdev, u8 instance, if (!adv) return ERR_PTR(-ENOMEM); + INIT_DELAYED_WORK(&adv->rpa_expired_cb, + adv_instance_rpa_expired); + adv->pending = true; adv->instance = instance; @@ -1766,8 +1775,6 @@ struct adv_info *hci_add_adv_instance(struct hci_dev *hdev, u8 instance, else adv->duration = duration; - INIT_DELAYED_WORK(&adv->rpa_expired_cb, adv_instance_rpa_expired); - BT_DBG("%s for %dMR", hdev->name, instance); return adv; @@ -2933,8 +2940,14 @@ int hci_recv_frame(struct hci_dev *hdev, struct sk_buff *skb) { u8 dev_pkt_type; + /* Pairs with synchronize_rcu() in hci_dev_close_sync(), so rx_work is + * not queued once the workqueue is being drained. + */ + rcu_read_lock(); + if (!hdev || (!test_bit(HCI_UP, &hdev->flags) && !test_bit(HCI_INIT, &hdev->flags))) { + rcu_read_unlock(); kfree_skb(skb); return -ENXIO; } @@ -2969,6 +2982,7 @@ int hci_recv_frame(struct hci_dev *hdev, struct sk_buff *skb) case HCI_DRV_PKT: break; default: + rcu_read_unlock(); kfree_skb(skb); return -EINVAL; } @@ -2982,6 +2996,8 @@ int hci_recv_frame(struct hci_dev *hdev, struct sk_buff *skb) skb_queue_tail(&hdev->rx_q, skb); queue_work(hdev->workqueue, &hdev->rx_work); + rcu_read_unlock(); + return 0; } EXPORT_SYMBOL(hci_recv_frame); @@ -3159,7 +3175,8 @@ int __hci_cmd_send(struct hci_dev *hdev, u16 opcode, u32 plen, EXPORT_SYMBOL(__hci_cmd_send); /* Get data from the previously sent command */ -static void *hci_cmd_data(struct sk_buff *skb, __u16 opcode) +static void *hci_cmd_data(struct sk_buff *skb, __u16 opcode, + size_t *len) { struct hci_command_hdr *hdr; @@ -3171,23 +3188,32 @@ static void *hci_cmd_data(struct sk_buff *skb, __u16 opcode) if (hdr->opcode != cpu_to_le16(opcode)) return NULL; + if (len) + *len = skb->len - HCI_COMMAND_HDR_SIZE; + return skb->data + HCI_COMMAND_HDR_SIZE; } /* Get data from the previously sent command */ -void *hci_sent_cmd_data(struct hci_dev *hdev, __u16 opcode) +void *hci_sent_cmd_data_len(struct hci_dev *hdev, __u16 opcode, size_t *len) { void *data; /* Check if opcode matches last sent command */ - data = hci_cmd_data(hdev->sent_cmd, opcode); + data = hci_cmd_data(hdev->sent_cmd, opcode, len); if (!data) /* Check if opcode matches last request */ - data = hci_cmd_data(hdev->req_skb, opcode); + data = hci_cmd_data(hdev->req_skb, opcode, len); return data; } +/* Get data from the previously sent command */ +void *hci_sent_cmd_data(struct hci_dev *hdev, __u16 opcode) +{ + return hci_sent_cmd_data_len(hdev, opcode, NULL); +} + /* Get data from last received event */ void *hci_recv_event_data(struct hci_dev *hdev, __u8 event) { diff --git a/net/bluetooth/hci_event.c b/net/bluetooth/hci_event.c index 572f195f09c1..797b86f57c6d 100644 --- a/net/bluetooth/hci_event.c +++ b/net/bluetooth/hci_event.c @@ -792,9 +792,7 @@ static u8 hci_cc_read_local_commands(struct hci_dev *hdev, void *data, if (rp->status) return rp->status; - if (hci_dev_test_flag(hdev, HCI_SETUP) || - hci_dev_test_flag(hdev, HCI_CONFIG)) - memcpy(hdev->commands, rp->commands, sizeof(hdev->commands)); + memcpy(hdev->commands, rp->commands, sizeof(hdev->commands)); return rp->status; } @@ -1770,6 +1768,8 @@ static void store_pending_adv_report(struct hci_dev *hdev, bdaddr_t *bdaddr, static void le_set_scan_enable_complete(struct hci_dev *hdev, u8 enable) { + bool timeout_pending; + hci_dev_lock(hdev); switch (enable) { @@ -1799,10 +1799,18 @@ static void le_set_scan_enable_complete(struct hci_dev *hdev, u8 enable) /* Cancel this timer so that we don't try to disable scanning * when it's already disabled. */ - cancel_delayed_work(&hdev->le_scan_disable); + timeout_pending = cancel_delayed_work(&hdev->le_scan_disable); hci_dev_clear_flag(hdev, HCI_LE_SCAN); + /* The scan of a discovery was disabled before its timeout, + * for example by a Stop Discovery that timed out and still + * completed, so nothing else would end the discovery. + */ + if (timeout_pending && + hdev->discovery.state == DISCOVERY_FINDING) + hci_discovery_set_state(hdev, DISCOVERY_STOPPED); + if (hdev->discovery.type == DISCOV_TYPE_INTERLEAVED && hci_test_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY) && !test_bit(HCI_INQUIRY, &hdev->flags) && @@ -2933,6 +2941,22 @@ static void hci_cs_le_read_remote_features(struct hci_dev *hdev, u8 status) conn = hci_conn_hash_lookup_handle(hdev, __le16_to_cpu(cp->handle)); if (conn) { if (conn->state == BT_CONFIG) { + /* If the local controller supports peripheral-initiated + * features exchange, but the remote controller does not, + * then the controller may already return the error code + * 0x1a for unsupported remote feature in the command + * status. + * + * Handle it as hci_le_remote_feat_complete_evt() does and + * allow the connection to transition into connected state. + */ + if (!conn->out && + status == HCI_ERROR_UNSUPPORTED_REMOTE_FEATURE && + (hdev->le_features[0] & HCI_LE_PERIPHERAL_FEATURES)) { + conn->state = BT_CONNECTED; + status = 0x00; + } + hci_connect_cfm(conn, status); hci_conn_drop(conn); } @@ -3853,13 +3877,16 @@ static u8 hci_cc_le_set_cig_params(struct hci_dev *hdev, void *data, struct hci_conn *conn; u8 status = rp->status; bool pending = false; + size_t len; int i; bt_dev_dbg(hdev, "status 0x%2.2x", rp->status); - cp = hci_sent_cmd_data(hdev, HCI_OP_LE_SET_CIG_PARAMS); + cp = hci_sent_cmd_data_len(hdev, HCI_OP_LE_SET_CIG_PARAMS, &len); if (!rp->status && - (!cp || rp->num_handles != cp->num_cis || + (!cp || len < sizeof(*cp) || + len < struct_size(cp, cis, cp->num_cis) || + rp->num_handles != cp->num_cis || rp->cig_id != cp->cig_id || skb->len < array_size(rp->num_handles, sizeof(*rp->handle)))) { bt_dev_err(hdev, "unexpected Set CIG Parameters response data"); @@ -4303,6 +4330,7 @@ static void hci_cs_le_create_cis(struct hci_dev *hdev, u8 status) { struct hci_cp_le_create_cis *cp; bool pending = false; + size_t len; int i; bt_dev_dbg(hdev, "status 0x%2.2x", status); @@ -4310,10 +4338,14 @@ static void hci_cs_le_create_cis(struct hci_dev *hdev, u8 status) if (!status) return; - cp = hci_sent_cmd_data(hdev, HCI_OP_LE_CREATE_CIS); + cp = hci_sent_cmd_data_len(hdev, HCI_OP_LE_CREATE_CIS, &len); if (!cp) return; + if (len < sizeof(*cp) || + len < struct_size(cp, cis, cp->num_cis)) + return; + hci_dev_lock(hdev); /* Remove connection if command failed */ @@ -5870,6 +5902,28 @@ static void le_conn_complete_evt(struct hci_dev *hdev, u8 status, hci_conn_put(params->conn); params->conn = NULL; } + + /* An explicit connect request is complete once connected, so + * clean it up here: hci_connect_le_scan_cleanup() no longer + * finds the params since they have just been removed from + * pend_le_conns. + */ + if (params->explicit_connect) { + params->explicit_connect = false; + + switch (params->auto_connect) { + case HCI_AUTO_CONN_EXPLICIT: + hci_conn_params_del(hdev, &conn->dst, + conn->dst_type); + break; + case HCI_AUTO_CONN_REPORT: + hci_pend_le_list_add(params, + &hdev->pend_le_reports); + break; + default: + break; + } + } } unlock: diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c index 6967da50aef0..ba5add3292e3 100644 --- a/net/bluetooth/hci_sync.c +++ b/net/bluetooth/hci_sync.c @@ -376,8 +376,18 @@ static void le_scan_disable(struct work_struct *work) bt_dev_dbg(hdev, ""); hci_dev_lock(hdev); - if (!hci_dev_test_flag(hdev, HCI_LE_SCAN)) + if (!hci_dev_test_flag(hdev, HCI_LE_SCAN)) { + /* The scan of a discovery can be disabled while this work + * waits for the lock, for example by a Stop Discovery that + * timed out and still completed, so end the discovery as + * le_set_scan_enable_complete() does when it cancels this + * work. + */ + if (hdev->discovery.state == DISCOVERY_FINDING) + goto discov_stopped; + goto _return; + } status = hci_cmd_sync_queue(hdev, scan_disable_sync, NULL, NULL); if (status) { @@ -2469,15 +2479,17 @@ static int hci_le_del_resolve_list_sync(struct hci_dev *hdev, bdaddr_t *bdaddr, u8 bdaddr_type) { struct hci_cp_le_del_from_resolv_list cp; - struct bdaddr_list_with_irk *entry; + bool exists; if (!ll_privacy_capable(hdev)) return 0; /* Check if the IRK has been programmed */ - entry = hci_bdaddr_list_lookup_with_irk(&hdev->le_resolv_list, bdaddr, - bdaddr_type); - if (!entry) + hci_dev_lock(hdev); + exists = hci_bdaddr_list_lookup_with_irk(&hdev->le_resolv_list, + bdaddr, bdaddr_type); + hci_dev_unlock(hdev); + if (!exists) return 0; cp.bdaddr_type = bdaddr_type; @@ -2533,8 +2545,8 @@ static int hci_le_add_resolve_list_sync(struct hci_dev *hdev, { struct hci_cp_le_add_to_resolv_list cp; struct smp_irk *irk; - struct bdaddr_list_with_irk *entry; struct hci_conn_params *p; + bool exists; if (!ll_privacy_capable(hdev)) return 0; @@ -2552,20 +2564,28 @@ static int hci_le_add_resolve_list_sync(struct hci_dev *hdev, } else if (!(params->flags & HCI_CONN_FLAG_ADDRESS_RESOLUTION)) return 0; + rcu_read_lock(); + irk = hci_find_irk_by_addr(hdev, ¶ms->addr, params->addr_type); - if (!irk) + if (!irk) { + rcu_read_unlock(); return 0; + } + + memcpy(cp.peer_irk, irk->val, 16); + + rcu_read_unlock(); /* Check if the IK has _not_ been programmed yet. */ - entry = hci_bdaddr_list_lookup_with_irk(&hdev->le_resolv_list, - ¶ms->addr, - params->addr_type); - if (entry) + hci_dev_lock(hdev); + exists = hci_bdaddr_list_lookup_with_irk( + &hdev->le_resolv_list, ¶ms->addr, params->addr_type); + hci_dev_unlock(hdev); + if (exists) return 0; cp.bdaddr_type = params->addr_type; bacpy(&cp.bdaddr, ¶ms->addr); - memcpy(cp.peer_irk, irk->val, 16); /* Default privacy mode is always Network */ params->privacy_mode = HCI_NETWORK_PRIVACY; @@ -2906,6 +2926,31 @@ static struct conn_params *conn_params_copy(struct list_head *list, size_t *n) return p; } +static struct conn_params *le_accept_list_copy(struct hci_dev *hdev, + size_t *n) +{ + struct bdaddr_list *entry; + struct conn_params *params; + size_t i = 0; + + hci_dev_lock(hdev); + + *n = list_count_nodes(&hdev->le_accept_list); + params = kvzalloc_objs(struct conn_params, *n); + if (!params) + goto unlock; + + list_for_each_entry(entry, &hdev->le_accept_list, list) { + bacpy(¶ms[i].addr, &entry->bdaddr); + params[i].addr_type = entry->bdaddr_type; + i++; + } + +unlock: + hci_dev_unlock(hdev); + return params; +} + /* Clear LE Accept List */ static int hci_le_clear_accept_list_sync(struct hci_dev *hdev) { @@ -2936,7 +2981,6 @@ static int hci_le_clear_accept_list_sync(struct hci_dev *hdev) static u8 hci_update_accept_list_sync(struct hci_dev *hdev) { struct conn_params *params; - struct bdaddr_list *b, *t; u8 num_entries = 0; bool pend_conn, pend_report; u8 filter_policy; @@ -3001,20 +3045,27 @@ static u8 hci_update_accept_list_sync(struct hci_dev *hdev) * report. If not present in either list, then remove it from * the controller. */ - list_for_each_entry_safe(b, t, &hdev->le_accept_list, list) { + params = le_accept_list_copy(hdev, &n); + if (!params) { + err = -ENOMEM; + goto done; + } + + for (i = 0; i < n; i++) { rcu_read_lock(); - if (hci_conn_hash_lookup_le(hdev, &b->bdaddr, b->bdaddr_type)) { + if (hci_conn_hash_lookup_le(hdev, ¶ms[i].addr, + params[i].addr_type)) { rcu_read_unlock(); continue; } pend_conn = hci_pend_le_action_lookup(&hdev->pend_le_conns, - &b->bdaddr, - b->bdaddr_type); - pend_report = hci_pend_le_action_lookup(&hdev->pend_le_reports, - &b->bdaddr, - b->bdaddr_type); + ¶ms[i].addr, + params[i].addr_type); + pend_report = hci_pend_le_action_lookup( + &hdev->pend_le_reports, ¶ms[i].addr, + params[i].addr_type); rcu_read_unlock(); @@ -3022,14 +3073,16 @@ static u8 hci_update_accept_list_sync(struct hci_dev *hdev) * remove it from the acceptlist. */ if (!pend_conn && !pend_report) { - hci_le_del_accept_list_sync(hdev, &b->bdaddr, - b->bdaddr_type); + hci_le_del_accept_list_sync(hdev, ¶ms[i].addr, + params[i].addr_type); continue; } num_entries++; } + kvfree(params); + /* Since all no longer valid accept list entries have been * removed, walk through the list of pending connections * and ensure that any new device gets programmed into @@ -5503,6 +5556,11 @@ int hci_dev_close_sync(struct hci_dev *hdev) return err; } + /* Wait for hci_recv_frame() callers that still saw HCI_UP, so that + * none of them queues rx_work while the workqueue is drained below. + */ + synchronize_rcu(); + hci_leds_update_powered(hdev, false); /* Flush RX and TX works */ @@ -5714,11 +5772,15 @@ int hci_stop_discovery_sync(struct hci_dev *hdev) } if (hci_dev_test_flag(hdev, HCI_LE_SCAN)) { - cancel_delayed_work(&hdev->le_scan_disable); - err = hci_scan_disable_sync(hdev); if (err) return err; + + /* Only cancel the LE scan timeout once the scan is + * disabled, so that the discovery still ends if + * stopping it failed. + */ + cancel_delayed_work(&hdev->le_scan_disable); } } else { @@ -6353,6 +6415,12 @@ static int hci_pause_discovery_sync(struct hci_dev *hdev) return 0; hci_discovery_set_state(hdev, DISCOVERY_STOPPING); + + /* Cancel the LE scan timeout first, so that it does not run while + * suspended if the scan cannot be disabled. + */ + cancel_delayed_work(&hdev->le_scan_disable); + err = hci_stop_discovery_sync(hdev); if (err) return err; diff --git a/net/bluetooth/l2cap_core.c b/net/bluetooth/l2cap_core.c index 2df5d25bfee6..eef49a65084b 100644 --- a/net/bluetooth/l2cap_core.c +++ b/net/bluetooth/l2cap_core.c @@ -3914,6 +3914,7 @@ void __l2cap_le_connect_rsp_defer(struct l2cap_chan *chan) l2cap_send_cmd(conn, chan->ident, L2CAP_LE_CONN_RSP, sizeof(rsp), &rsp); + chan->ident = 0; } static void l2cap_ecred_list_defer(struct l2cap_chan *chan, void *data) @@ -5162,10 +5163,10 @@ static int l2cap_le_connect_req(struct l2cap_conn *conn, __set_chan_timer(chan, chan->ops->get_sndtimeo(chan)); - chan->ident = cmd->ident; chan->mode = L2CAP_MODE_LE_FLOWCTL; if (test_bit(FLAG_DEFER_SETUP, &chan->flags)) { + chan->ident = cmd->ident; l2cap_state_change(chan, BT_CONNECT2); /* The following result value is actually not defined * for LE CoC but we use it to let the function know @@ -5395,10 +5396,10 @@ static inline int l2cap_ecred_conn_req(struct l2cap_conn *conn, __set_chan_timer(chan, chan->ops->get_sndtimeo(chan)); - chan->ident = cmd->ident; chan->mode = L2CAP_MODE_EXT_FLOWCTL; if (test_bit(FLAG_DEFER_SETUP, &chan->flags)) { + chan->ident = cmd->ident; l2cap_state_change(chan, BT_CONNECT2); defer = true; chan->ops->defer(chan); diff --git a/net/bluetooth/l2cap_sock.c b/net/bluetooth/l2cap_sock.c index b85c6a11334e..39580db38fec 100644 --- a/net/bluetooth/l2cap_sock.c +++ b/net/bluetooth/l2cap_sock.c @@ -1289,7 +1289,8 @@ static int l2cap_sock_recvmsg(struct socket *sock, struct msghdr *msg, * available. This avoids resending large numbers of * frames. */ - if (test_bit(CONN_LOCAL_BUSY, &pi->chan->conn_state) && + if (sk->sk_state == BT_CONNECTED && + test_bit(CONN_LOCAL_BUSY, &pi->chan->conn_state) && atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf >> 1) l2cap_chan_busy(pi->chan, 0); diff --git a/net/bluetooth/mgmt.c b/net/bluetooth/mgmt.c index 5058fa2ed9a9..b16b70a3cab6 100644 --- a/net/bluetooth/mgmt.c +++ b/net/bluetooth/mgmt.c @@ -304,6 +304,10 @@ static u8 mgmt_errno_status(int err) return MGMT_STATUS_ALREADY_CONNECTED; case -ENOTCONN: return MGMT_STATUS_DISCONNECTED; + case -ECANCELED: + return MGMT_STATUS_CANCELLED; + case -ERFKILL: + return MGMT_STATUS_RFKILLED; } return MGMT_STATUS_FAILED; @@ -5614,8 +5618,18 @@ static void mgmt_remove_adv_monitor_complete(struct hci_dev *hdev, struct mgmt_pending_cmd *cmd = data; struct mgmt_cp_remove_adv_monitor *cp; - if (status == -ECANCELED) + /* Reply to a cancelled command so bluetoothd's serialised mgmt queue + * is not blocked. + */ + if (status == -ECANCELED) { + cp = cmd->param; + rp.monitor_handle = cp->monitor_handle; + + mgmt_cmd_complete(cmd->sk, cmd->hdev->id, cmd->opcode, + mgmt_status(status), &rp, sizeof(rp)); + mgmt_pending_free(cmd); return; + } hci_dev_lock(hdev); @@ -6228,12 +6242,29 @@ static void stop_discovery_complete(struct hci_dev *hdev, void *data, int err) bt_dev_dbg(hdev, "err %d", err); + hci_dev_lock(hdev); + + /* Change the state before replying, so that a client acting on the + * reply sees it, and only while the discovery is still stopping, as + * Inquiry Cancel may already have stopped it and a new Start Discovery + * may have followed. Go back to DISCOVERY_FINDING when stopping failed + * while the inquiry or the active LE scan of the discovery is still + * running, so that it can be stopped again. + */ + if (hdev->discovery.state == DISCOVERY_STOPPING) { + if (err && (test_bit(HCI_INQUIRY, &hdev->flags) || + (hci_dev_test_flag(hdev, HCI_LE_SCAN) && + hdev->le_scan_type == LE_SCAN_ACTIVE))) + hci_discovery_set_state(hdev, DISCOVERY_FINDING); + else + hci_discovery_set_state(hdev, DISCOVERY_STOPPED); + } + + hci_dev_unlock(hdev); + mgmt_cmd_complete(cmd->sk, cmd->hdev->id, cmd->opcode, mgmt_status(err), cmd->param, 1); mgmt_pending_free(cmd); - - if (!err) - hci_discovery_set_state(hdev, DISCOVERY_STOPPED); } static int stop_discovery_sync(struct hci_dev *hdev, void *data) @@ -8151,7 +8182,11 @@ static int load_conn_param(struct sock *sk, struct hci_dev *hdev, void *data, hci_dev_lock(hdev); - if (param_count > 1) + /* A single entry may be an update for one device, so keep the other + * disabled parameters then, but clear them otherwise, including when + * no entries are loaded. + */ + if (param_count != 1) hci_conn_params_clear_disabled(hdev); for (i = 0; i < param_count; i++) { diff --git a/net/bridge/br_arp_nd_proxy.c b/net/bridge/br_arp_nd_proxy.c index 3203706d02b8..e5ee03f6faee 100644 --- a/net/bridge/br_arp_nd_proxy.c +++ b/net/bridge/br_arp_nd_proxy.c @@ -262,6 +262,7 @@ static void br_nd_send(struct net_bridge *br, struct net_bridge_port *p, struct sk_buff *reply; struct ipv6hdr *pip6; int na_olen = 8; /* opt hdr + ETH_ALEN for target */ + int headroom; int ns_olen; int i, len; u8 *daddr; @@ -271,7 +272,8 @@ static void br_nd_send(struct net_bridge *br, struct net_bridge_port *p, if (!dev || skb_linearize(request)) return; - len = LL_RESERVED_SPACE(dev) + sizeof(struct ipv6hdr) + + headroom = LL_RESERVED_SPACE(dev); + len = headroom + sizeof(struct ipv6hdr) + sizeof(*na) + na_olen + dev->needed_tailroom; reply = alloc_skb(len, GFP_ATOMIC); @@ -280,7 +282,7 @@ static void br_nd_send(struct net_bridge *br, struct net_bridge_port *p, reply->protocol = htons(ETH_P_IPV6); reply->dev = dev; - skb_reserve(reply, LL_RESERVED_SPACE(dev)); + skb_reserve(reply, headroom); skb_push(reply, sizeof(struct ethhdr)); skb_set_mac_header(reply, 0); diff --git a/net/bridge/br_if.c b/net/bridge/br_if.c index 5bcd1acc5da9..63d9e28c0eda 100644 --- a/net/bridge/br_if.c +++ b/net/bridge/br_if.c @@ -339,13 +339,13 @@ static void del_nbp(struct net_bridge_port *p) nbp_delete_promisc(p); + br_mrp_port_del(br, p); + br_cfm_port_del(br, p); + spin_lock_bh(&br->lock); br_stp_disable_port(p); spin_unlock_bh(&br->lock); - br_mrp_port_del(br, p); - br_cfm_port_del(br, p); - br_ifinfo_notify(RTM_DELLINK, NULL, p); list_del_rcu(&p->list); diff --git a/net/bridge/br_vlan.c b/net/bridge/br_vlan.c index 021f2470bcaa..786c8a0e6bb6 100644 --- a/net/bridge/br_vlan.c +++ b/net/bridge/br_vlan.c @@ -387,12 +387,12 @@ static int __vlan_add(struct net_bridge_vlan *v, u16 flags, goto out; } -static int __vlan_del(struct net_bridge_vlan *v) +static void __vlan_del(struct net_bridge_vlan *v) { struct net_bridge_vlan *masterv = v; struct net_bridge_vlan_group *vg; struct net_bridge_port *p = NULL; - int err = 0; + int err; if (br_vlan_is_master(v)) { vg = br_vlan_group(v->br); @@ -406,12 +406,16 @@ static int __vlan_del(struct net_bridge_vlan *v) if (p) { err = __vlan_vid_del(p->dev, p->br, v); if (err) - goto out; + br_warn(p->br, + "port %u(%s) failed to delete vlan %u from switchdev: %pe\n", + (unsigned int)p->port_no, p->dev->name, + v->vid, ERR_PTR(err)); } else { err = br_switchdev_port_vlan_del(v->br->dev, v->vid); if (err && err != -EOPNOTSUPP) - goto out; - err = 0; + br_warn(v->br, + "failed to delete bridge vlan %u from switchdev: %pe\n", + v->vid, ERR_PTR(err)); } if (br_vlan_should_use(v)) { @@ -431,8 +435,6 @@ static int __vlan_del(struct net_bridge_vlan *v) } br_vlan_put_master(masterv); -out: - return err; } static void __vlan_group_free(struct net_bridge_vlan_group *vg) @@ -449,7 +451,6 @@ static void __vlan_flush(const struct net_bridge *br, { struct net_bridge_vlan *vlan, *tmp; u16 v_start = 0, v_end = 0; - int err; __vlan_delete_pvid(vg, vg->pvid); list_for_each_entry_safe(vlan, tmp, &vg->vlan_list, vlist) { @@ -463,13 +464,7 @@ static void __vlan_flush(const struct net_bridge *br, } v_end = vlan->vid; - err = __vlan_del(vlan); - if (err) { - br_err(br, - "port %u(%s) failed to delete vlan %d: %pe\n", - (unsigned int) p->port_no, p->dev->name, - vlan->vid, ERR_PTR(err)); - } + __vlan_del(vlan); } /* notify about the last/whole vlan range */ @@ -837,8 +832,9 @@ int br_vlan_delete(struct net_bridge *br, u16 vid) br_fdb_delete_by_port(br, NULL, vid, 0); vlan_tunnel_info_del(vg, v); + __vlan_del(v); - return __vlan_del(v); + return 0; } void br_vlan_flush(struct net_bridge *br) @@ -1368,8 +1364,9 @@ int nbp_vlan_delete(struct net_bridge_port *port, u16 vid) return -ENOENT; br_fdb_find_delete_local(port->br, port, port->dev->dev_addr, vid); br_fdb_delete_by_port(port->br, port, vid, 0); + __vlan_del(v); - return __vlan_del(v); + return 0; } void nbp_vlan_flush(struct net_bridge_port *port) diff --git a/net/bridge/netfilter/nf_conntrack_bridge.c b/net/bridge/netfilter/nf_conntrack_bridge.c index b17962672ebf..e7603a144538 100644 --- a/net/bridge/netfilter/nf_conntrack_bridge.c +++ b/net/bridge/netfilter/nf_conntrack_bridge.c @@ -359,7 +359,7 @@ nf_ct_bridge_refrag(struct sk_buff *skb, const struct nf_hook_state *state, nf_br_ip6_fragment(state->net, state->sk, skb, &data, output); break; default: - WARN_ON_ONCE(1); + DEBUG_NET_WARN_ON_ONCE(1); return NF_DROP; } diff --git a/net/ceph/Kconfig b/net/ceph/Kconfig index ea60e3ef0834..7e2528cde4b9 100644 --- a/net/ceph/Kconfig +++ b/net/ceph/Kconfig @@ -6,6 +6,7 @@ config CEPH_LIB select CRYPTO_AES select CRYPTO_CBC select CRYPTO_GCM + select CRYPTO_KRB5 select CRYPTO_LIB_SHA256 select CRYPTO select KEYS diff --git a/net/ceph/auth_x.c b/net/ceph/auth_x.c index f805a813308f..9350e1a9daf8 100644 --- a/net/ceph/auth_x.c +++ b/net/ceph/auth_x.c @@ -17,6 +17,22 @@ #include "auth_x.h" #include "auth_x_protocol.h" +static const u32 ticket_key_usages[] = { + CEPHX_KEY_USAGE_TICKET_SESSION_KEY, + CEPHX_KEY_USAGE_TICKET_BLOB, + CEPHX_KEY_USAGE_AUTH_CONNECTION_SECRET +}; + +static const u32 authorizer_key_usages[] = { + CEPHX_KEY_USAGE_AUTHORIZE, + CEPHX_KEY_USAGE_AUTHORIZE_CHALLENGE, + CEPHX_KEY_USAGE_AUTHORIZE_REPLY +}; + +static const u32 client_key_usages[] = { + CEPHX_KEY_USAGE_TICKET_SESSION_KEY +}; + static void ceph_x_validate_tickets(struct ceph_auth_client *ac, int *pneed); static int ceph_x_is_authenticated(struct ceph_auth_client *ac) @@ -44,28 +60,41 @@ static int ceph_x_should_authenticate(struct ceph_auth_client *ac) return !!need; } -static int ceph_x_encrypt_offset(void) +static int __ceph_x_encrypt_offset(const struct ceph_crypto_key *key) +{ + return ceph_crypt_data_offset(key) + + sizeof(struct ceph_x_encrypt_header); +} + +static int ceph_x_encrypt_offset(const struct ceph_crypto_key *key) { - return sizeof(u32) + sizeof(struct ceph_x_encrypt_header); + return sizeof(u32) + __ceph_x_encrypt_offset(key); } -static int ceph_x_encrypt_buflen(int ilen) +/* + * AES: ciphertext_len | hdr | data... | padding + * AES256KRB5: ciphertext_len | confounder | hdr | data... | hmac + */ +static int ceph_x_encrypt_buflen(const struct ceph_crypto_key *key, + int data_len) { - return ceph_x_encrypt_offset() + ilen + 16; + int encrypt_len = sizeof(struct ceph_x_encrypt_header) + data_len; + return sizeof(u32) + ceph_crypt_buflen(key, encrypt_len); } -static int ceph_x_encrypt(struct ceph_crypto_key *secret, void *buf, - int buf_len, int plaintext_len) +static int ceph_x_encrypt(const struct ceph_crypto_key *key, int usage_slot, + void *buf, int buf_len, int plaintext_len) { - struct ceph_x_encrypt_header *hdr = buf + sizeof(u32); + struct ceph_x_encrypt_header *hdr; int ciphertext_len; int ret; + hdr = buf + sizeof(u32) + ceph_crypt_data_offset(key); hdr->struct_v = 1; hdr->magic = cpu_to_le64(CEPHX_ENC_MAGIC); - ret = ceph_crypt(secret, true, buf + sizeof(u32), buf_len - sizeof(u32), - plaintext_len + sizeof(struct ceph_x_encrypt_header), + ret = ceph_crypt(key, usage_slot, true, buf + sizeof(u32), + buf_len - sizeof(u32), plaintext_len + sizeof(*hdr), &ciphertext_len); if (ret) return ret; @@ -74,15 +103,15 @@ static int ceph_x_encrypt(struct ceph_crypto_key *secret, void *buf, return sizeof(u32) + ciphertext_len; } -static int __ceph_x_decrypt(struct ceph_crypto_key *secret, void *p, - int ciphertext_len) +static int __ceph_x_decrypt(const struct ceph_crypto_key *key, int usage_slot, + void *p, int ciphertext_len) { - struct ceph_x_encrypt_header *hdr = p; + struct ceph_x_encrypt_header *hdr; int plaintext_len; int ret; - ret = ceph_crypt(secret, false, p, ciphertext_len, ciphertext_len, - &plaintext_len); + ret = ceph_crypt(key, usage_slot, false, p, ciphertext_len, + ciphertext_len, &plaintext_len); if (ret) return ret; @@ -91,6 +120,7 @@ static int __ceph_x_decrypt(struct ceph_crypto_key *secret, void *p, return -EINVAL; } + hdr = p + ceph_crypt_data_offset(key); if (le64_to_cpu(hdr->magic) != CEPHX_ENC_MAGIC) { pr_err("%s bad magic\n", __func__); return -EINVAL; @@ -99,7 +129,8 @@ static int __ceph_x_decrypt(struct ceph_crypto_key *secret, void *p, return plaintext_len - sizeof(*hdr); } -static int ceph_x_decrypt(struct ceph_crypto_key *secret, void **p, void *end) +static int ceph_x_decrypt(const struct ceph_crypto_key *key, int usage_slot, + void **p, void *end) { int ciphertext_len; int ret; @@ -107,7 +138,7 @@ static int ceph_x_decrypt(struct ceph_crypto_key *secret, void **p, void *end) ceph_decode_32_safe(p, end, ciphertext_len, e_inval); ceph_decode_need(p, end, ciphertext_len, e_inval); - ret = __ceph_x_decrypt(secret, *p, ciphertext_len); + ret = __ceph_x_decrypt(key, usage_slot, *p, ciphertext_len); if (ret < 0) return ret; @@ -198,8 +229,10 @@ static int process_one_ticket(struct ceph_auth_client *ac, } /* blob for me */ - dp = *p + ceph_x_encrypt_offset(); - ret = ceph_x_decrypt(secret, p, end); + dp = *p + ceph_x_encrypt_offset(secret); + ret = ceph_x_decrypt(secret, + 0 /* CEPHX_KEY_USAGE_TICKET_SESSION_KEY */, + p, end); if (ret < 0) goto out; dout(" decrypted %d bytes\n", ret); @@ -213,6 +246,11 @@ static int process_one_ticket(struct ceph_auth_client *ac, if (ret) goto out; + ret = ceph_crypto_key_prepare(&new_session_key, ticket_key_usages, + ARRAY_SIZE(ticket_key_usages)); + if (ret) + goto out; + ceph_decode_need(&dp, dend, sizeof(struct ceph_timespec), bad); ceph_decode_timespec64(&validity, dp); dp += sizeof(struct ceph_timespec); @@ -225,8 +263,10 @@ static int process_one_ticket(struct ceph_auth_client *ac, ceph_decode_8_safe(p, end, is_enc, bad); if (is_enc) { /* encrypted */ - tp = *p + ceph_x_encrypt_offset(); - ret = ceph_x_decrypt(&th->session_key, p, end); + tp = *p + ceph_x_encrypt_offset(&th->session_key); + ret = ceph_x_decrypt(&th->session_key, + 1 /* CEPHX_KEY_USAGE_TICKET_BLOB */, + p, end); if (ret < 0) goto out; dout(" encrypted ticket, decrypted %d bytes\n", ret); @@ -317,7 +357,7 @@ static int encrypt_authorizer(struct ceph_x_authorizer *au, p = (void *)(msg_a + 1) + le32_to_cpu(msg_a->ticket_blob.blob_len); end = au->buf->vec.iov_base + au->buf->vec.iov_len; - msg_b = p + ceph_x_encrypt_offset(); + msg_b = p + ceph_x_encrypt_offset(&au->session_key); msg_b->struct_v = 2; msg_b->nonce = cpu_to_le64(au->nonce); if (server_challenge) { @@ -329,7 +369,9 @@ static int encrypt_authorizer(struct ceph_x_authorizer *au, msg_b->server_challenge_plus_one = 0; } - ret = ceph_x_encrypt(&au->session_key, p, end - p, sizeof(*msg_b)); + ret = ceph_x_encrypt(&au->session_key, + 0 /* CEPHX_KEY_USAGE_AUTHORIZE */, + p, end - p, sizeof(*msg_b)); if (ret < 0) return ret; @@ -372,8 +414,13 @@ static int ceph_x_build_authorizer(struct ceph_auth_client *ac, if (ret) goto out_au; + ret = ceph_crypto_key_prepare(&au->session_key, authorizer_key_usages, + ARRAY_SIZE(authorizer_key_usages)); + if (ret) + goto out_au; + maxlen = sizeof(*msg_a) + ticket_blob_len + - ceph_x_encrypt_buflen(sizeof(*msg_b)); + ceph_x_encrypt_buflen(&au->session_key, sizeof(*msg_b)); dout(" need len %d\n", maxlen); if (au->buf && au->buf->alloc_len < maxlen) { ceph_buffer_put(au->buf); @@ -511,8 +558,7 @@ static int ceph_x_build_request(struct ceph_auth_client *ac, if (need & CEPH_ENTITY_TYPE_AUTH) { struct ceph_x_authenticate *auth = (void *)(head + 1); void *enc_buf = xi->auth_authorizer.enc_buf; - struct ceph_x_challenge_blob *blob = enc_buf + - ceph_x_encrypt_offset(); + struct ceph_x_challenge_blob *blob; u64 *u; p = auth + 1; @@ -522,14 +568,29 @@ static int ceph_x_build_request(struct ceph_auth_client *ac, dout(" get_auth_session_key\n"); head->op = cpu_to_le16(CEPHX_GET_AUTH_SESSION_KEY); - /* encrypt and hash */ + if (xi->secret.type == CEPH_CRYPTO_AES) { + blob = enc_buf + ceph_x_encrypt_offset(&xi->secret); + } else { + BUILD_BUG_ON(SHA256_DIGEST_SIZE + sizeof(*blob) > + CEPHX_AU_ENC_BUF_LEN); + blob = enc_buf + SHA256_DIGEST_SIZE; + } + get_random_bytes(&auth->client_challenge, sizeof(u64)); blob->client_challenge = auth->client_challenge; blob->server_challenge = cpu_to_le64(xi->server_challenge); - ret = ceph_x_encrypt(&xi->secret, enc_buf, CEPHX_AU_ENC_BUF_LEN, - sizeof(*blob)); - if (ret < 0) - return ret; + + if (xi->secret.type == CEPH_CRYPTO_AES) { + ret = ceph_x_encrypt(&xi->secret, 0 /* dummy */, + enc_buf, CEPHX_AU_ENC_BUF_LEN, + sizeof(*blob)); + if (ret < 0) + return ret; + } else { + ceph_hmac_sha256(&xi->secret, blob, sizeof(*blob), + enc_buf); + ret = SHA256_DIGEST_SIZE; + } auth->struct_v = 3; /* nautilus+ */ auth->key = 0; @@ -639,8 +700,10 @@ static int handle_auth_session_key(struct ceph_auth_client *ac, u64 global_id, ceph_decode_need(p, end, len, e_inval); dout("%s connection secret blob len %d\n", __func__, len); if (len > 0) { - dp = *p + ceph_x_encrypt_offset(); - ret = ceph_x_decrypt(&th->session_key, p, *p + len); + dp = *p + ceph_x_encrypt_offset(&th->session_key); + ret = ceph_x_decrypt(&th->session_key, + 2 /* CEPHX_KEY_USAGE_AUTH_CONNECTION_SECRET */, + p, *p + len); if (ret < 0) return ret; @@ -811,12 +874,14 @@ static int decrypt_authorizer_challenge(struct ceph_crypto_key *secret, int ret; /* no leading len */ - ret = __ceph_x_decrypt(secret, challenge, challenge_len); + ret = __ceph_x_decrypt(secret, + 1 /* CEPHX_KEY_USAGE_AUTHORIZE_CHALLENGE */, + challenge, challenge_len); if (ret < 0) return ret; dout("%s decrypted %d bytes\n", __func__, ret); - dp = challenge + sizeof(struct ceph_x_encrypt_header); + dp = challenge + __ceph_x_encrypt_offset(secret); dend = dp + ret; ceph_decode_skip_8(&dp, dend, e_inval); /* struct_v */ @@ -863,8 +928,9 @@ static int decrypt_authorizer_reply(struct ceph_crypto_key *secret, u8 struct_v; int ret; - dp = *p + ceph_x_encrypt_offset(); - ret = ceph_x_decrypt(secret, p, end); + dp = *p + ceph_x_encrypt_offset(secret); + ret = ceph_x_decrypt(secret, 2 /* CEPHX_KEY_USAGE_AUTHORIZE_REPLY */, + p, end); if (ret < 0) return ret; @@ -986,7 +1052,8 @@ static int calc_signature(struct ceph_x_authorizer *au, struct ceph_msg *msg, __le32 front_crc; __le32 middle_crc; __le32 data_crc; - } __packed *sigblock = enc_buf + ceph_x_encrypt_offset(); + } __packed *sigblock = enc_buf + + ceph_x_encrypt_offset(&au->session_key); sigblock->len = cpu_to_le32(4*sizeof(u32)); sigblock->header_crc = msg->hdr.crc; @@ -994,8 +1061,9 @@ static int calc_signature(struct ceph_x_authorizer *au, struct ceph_msg *msg, sigblock->middle_crc = msg->footer.middle_crc; sigblock->data_crc = msg->footer.data_crc; - ret = ceph_x_encrypt(&au->session_key, enc_buf, - CEPHX_AU_ENC_BUF_LEN, sizeof(*sigblock)); + ret = ceph_x_encrypt(&au->session_key, 0 /* dummy */, + enc_buf, CEPHX_AU_ENC_BUF_LEN, + sizeof(*sigblock)); if (ret < 0) return ret; @@ -1010,11 +1078,19 @@ static int calc_signature(struct ceph_x_authorizer *au, struct ceph_msg *msg, __le32 data_crc; __le32 data_len; __le32 seq_lower_word; - } __packed *sigblock = enc_buf; + } __packed *sigblock; struct { __le64 a, b, c, d; } __packed *penc = enc_buf; - int ciphertext_len; + + if (au->session_key.type == CEPH_CRYPTO_AES) { + /* no leading len, no ceph_x_encrypt_header */ + sigblock = enc_buf; + } else { + BUILD_BUG_ON(SHA256_DIGEST_SIZE + sizeof(*sigblock) > + CEPHX_AU_ENC_BUF_LEN); + sigblock = enc_buf + SHA256_DIGEST_SIZE; + } sigblock->header_crc = msg->hdr.crc; sigblock->front_crc = msg->footer.front_crc; @@ -1025,12 +1101,18 @@ static int calc_signature(struct ceph_x_authorizer *au, struct ceph_msg *msg, sigblock->data_len = msg->hdr.data_len; sigblock->seq_lower_word = *(__le32 *)&msg->hdr.seq; - /* no leading len, no ceph_x_encrypt_header */ - ret = ceph_crypt(&au->session_key, true, enc_buf, - CEPHX_AU_ENC_BUF_LEN, sizeof(*sigblock), - &ciphertext_len); - if (ret) - return ret; + if (au->session_key.type == CEPH_CRYPTO_AES) { + int ciphertext_len; /* unused */ + + ret = ceph_crypt(&au->session_key, 0 /* dummy */, + true, enc_buf, CEPHX_AU_ENC_BUF_LEN, + sizeof(*sigblock), &ciphertext_len); + if (ret) + return ret; + } else { + ceph_hmac_sha256(&au->session_key, sigblock, + sizeof(*sigblock), enc_buf); + } *psig = penc->a ^ penc->b ^ penc->c ^ penc->d; } @@ -1104,21 +1186,27 @@ int ceph_x_init(struct ceph_auth_client *ac) int ret; dout("ceph_x_init %p\n", ac); - ret = -ENOMEM; xi = kzalloc(sizeof(*xi), GFP_NOFS); if (!xi) - goto out; + return -ENOMEM; ret = -EINVAL; if (!ac->key) { pr_err("no secret set (for auth_x protocol)\n"); - goto out_nomem; + goto err_xi; } ret = ceph_crypto_key_clone(&xi->secret, ac->key); if (ret < 0) { pr_err("cannot clone key: %d\n", ret); - goto out_nomem; + goto err_xi; + } + + ret = ceph_crypto_key_prepare(&xi->secret, client_key_usages, + ARRAY_SIZE(client_key_usages)); + if (ret) { + pr_err("cannot prepare key: %d\n", ret); + goto err_secret; } xi->starting = true; @@ -1129,8 +1217,9 @@ int ceph_x_init(struct ceph_auth_client *ac) ac->ops = &ceph_x_ops; return 0; -out_nomem: +err_secret: + ceph_crypto_key_destroy(&xi->secret); +err_xi: kfree(xi); -out: return ret; } diff --git a/net/ceph/auth_x_protocol.h b/net/ceph/auth_x_protocol.h index 9c60feeb1bcb..d097b3651c99 100644 --- a/net/ceph/auth_x_protocol.h +++ b/net/ceph/auth_x_protocol.h @@ -6,6 +6,44 @@ #define CEPHX_GET_PRINCIPAL_SESSION_KEY 0x0200 #define CEPHX_GET_ROTATING_KEY 0x0400 +/* Client <-> AuthMonitor */ +/* + * The AUTH session's connection secret: encrypted with the AUTH + * ticket session key + */ +#define CEPHX_KEY_USAGE_AUTH_CONNECTION_SECRET 0x03 +/* + * The ticket's blob for the client ("blob for me", contains the + * session key): encrypted with the client's secret key in case of + * the AUTH ticket and the AUTH ticket session key in case of other + * service tickets + */ +#define CEPHX_KEY_USAGE_TICKET_SESSION_KEY 0x04 +/* + * The ticket's blob for the service (ceph_x_ticket_blob): possibly + * encrypted with the old AUTH ticket session key in case of the AUTH + * ticket and not encrypted in case of other service tickets + */ +#define CEPHX_KEY_USAGE_TICKET_BLOB 0x05 + +/* Client <-> Service */ +/* + * The client's authorization request (ceph_x_authorize_b): + * encrypted with the service ticket session key + */ +#define CEPHX_KEY_USAGE_AUTHORIZE 0x10 +/* + * The service's challenge (ceph_x_authorize_challenge): + * encrypted with the service ticket session key + */ +#define CEPHX_KEY_USAGE_AUTHORIZE_CHALLENGE 0x11 +/* + * The service's final reply (ceph_x_authorize_reply + the service + * session's connection secret): encrypted with the service ticket + * session key + */ +#define CEPHX_KEY_USAGE_AUTHORIZE_REPLY 0x12 + /* common bits */ struct ceph_x_ticket_blob { __u8 struct_v; diff --git a/net/ceph/crypto.c b/net/ceph/crypto.c index 5601732cf4fa..b2067ea6c38a 100644 --- a/net/ceph/crypto.c +++ b/net/ceph/crypto.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -16,65 +17,102 @@ #include #include "crypto.h" -/* - * Set ->key and ->tfm. The rest of the key should be filled in before - * this function is called. - */ -static int set_secret(struct ceph_crypto_key *key, void *buf) +static int set_aes_tfm(struct ceph_crypto_key *key) { unsigned int noio_flag; int ret; - key->key = NULL; - key->tfm = NULL; - - switch (key->type) { - case CEPH_CRYPTO_NONE: - return 0; /* nothing to do */ - case CEPH_CRYPTO_AES: - break; - default: - return -ENOTSUPP; - } - - key->key = kmemdup(buf, key->len, GFP_NOIO); - if (!key->key) { - ret = -ENOMEM; - goto fail; - } - - /* crypto_alloc_sync_skcipher() allocates with GFP_KERNEL */ noio_flag = memalloc_noio_save(); - key->tfm = crypto_alloc_sync_skcipher("cbc(aes)", 0, 0); + key->aes_tfm = crypto_alloc_sync_skcipher("cbc(aes)", 0, 0); memalloc_noio_restore(noio_flag); - if (IS_ERR(key->tfm)) { - ret = PTR_ERR(key->tfm); - key->tfm = NULL; - goto fail; + if (IS_ERR(key->aes_tfm)) { + ret = PTR_ERR(key->aes_tfm); + key->aes_tfm = NULL; + return ret; } - ret = crypto_sync_skcipher_setkey(key->tfm, key->key, key->len); + ret = crypto_sync_skcipher_setkey(key->aes_tfm, key->key, key->len); if (ret) - goto fail; + return ret; return 0; +} + +static int set_krb5_tfms(struct ceph_crypto_key *key, const u32 *key_usages, + int key_usage_cnt) +{ + struct krb5_buffer TK = { .len = key->len, .data = key->key }; + unsigned int noio_flag; + int ret = 0; + int i; + + if (WARN_ON_ONCE(key_usage_cnt > ARRAY_SIZE(key->krb5_tfms))) + return -EINVAL; + + key->krb5_type = crypto_krb5_find_enctype( + KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192); + if (!key->krb5_type) + return -ENOPKG; -fail: - ceph_crypto_key_destroy(key); + /* + * Despite crypto_krb5_prepare_encryption() taking a gfp mask, + * crypto_alloc_aead() inside of it allocates with GFP_KERNEL. + */ + noio_flag = memalloc_noio_save(); + for (i = 0; i < key_usage_cnt; i++) { + key->krb5_tfms[i] = crypto_krb5_prepare_encryption( + key->krb5_type, &TK, key_usages[i], + GFP_NOIO); + if (IS_ERR(key->krb5_tfms[i])) { + ret = PTR_ERR(key->krb5_tfms[i]); + key->krb5_tfms[i] = NULL; + goto out_flag; + } + } + +out_flag: + memalloc_noio_restore(noio_flag); return ret; } +int ceph_crypto_key_prepare(struct ceph_crypto_key *key, + const u32 *key_usages, int key_usage_cnt) +{ + switch (key->type) { + case CEPH_CRYPTO_NONE: + return 0; /* nothing to do */ + case CEPH_CRYPTO_AES: + return set_aes_tfm(key); + case CEPH_CRYPTO_AES256KRB5: + hmac_sha256_preparekey(&key->hmac_key, key->key, key->len); + return set_krb5_tfms(key, key_usages, key_usage_cnt); + default: + return -ENOTSUPP; + } +} + +/* + * @dst should be zeroed before this function is called. + */ int ceph_crypto_key_clone(struct ceph_crypto_key *dst, const struct ceph_crypto_key *src) { - memcpy(dst, src, sizeof(struct ceph_crypto_key)); - return set_secret(dst, src->key); + dst->type = src->type; + dst->created = src->created; + dst->len = src->len; + + dst->key = kmemdup(src->key, src->len, GFP_NOIO); + if (!dst->key) + return -ENOMEM; + + return 0; } +/* + * @key should be zeroed before this function is called. + */ int ceph_crypto_key_decode(struct ceph_crypto_key *key, void **p, void *end) { - int ret; - ceph_decode_need(p, end, 2*sizeof(u16) + sizeof(key->created), bad); key->type = ceph_decode_16(p); ceph_decode_copy(p, &key->created, sizeof(key->created)); @@ -85,10 +123,13 @@ int ceph_crypto_key_decode(struct ceph_crypto_key *key, void **p, void *end) return -EINVAL; } - ret = set_secret(key, *p); + key->key = kmemdup(*p, key->len, GFP_NOIO); + if (!key->key) + return -ENOMEM; + memzero_explicit(*p, key->len); *p += key->len; - return ret; + return 0; bad: dout("failed to decode crypto key\n"); @@ -124,12 +165,26 @@ int ceph_crypto_key_unarmor(struct ceph_crypto_key *key, const char *inkey) void ceph_crypto_key_destroy(struct ceph_crypto_key *key) { - if (key) { - kfree_sensitive(key->key); - key->key = NULL; - if (key->tfm) { - crypto_free_sync_skcipher(key->tfm); - key->tfm = NULL; + int i; + + if (!key) + return; + + kfree_sensitive(key->key); + key->key = NULL; + + if (key->type == CEPH_CRYPTO_AES) { + if (key->aes_tfm) { + crypto_free_sync_skcipher(key->aes_tfm); + key->aes_tfm = NULL; + } + } else if (key->type == CEPH_CRYPTO_AES256KRB5) { + memzero_explicit(&key->hmac_key, sizeof(key->hmac_key)); + for (i = 0; i < ARRAY_SIZE(key->krb5_tfms); i++) { + if (key->krb5_tfms[i]) { + crypto_free_aead(key->krb5_tfms[i]); + key->krb5_tfms[i] = NULL; + } } } } @@ -209,7 +264,7 @@ static void teardown_sgtable(struct sg_table *sgt) static int ceph_aes_crypt(const struct ceph_crypto_key *key, bool encrypt, void *buf, int buf_len, int in_len, int *pout_len) { - SYNC_SKCIPHER_REQUEST_ON_STACK(req, key->tfm); + SYNC_SKCIPHER_REQUEST_ON_STACK(req, key->aes_tfm); struct sg_table sgt; struct scatterlist prealloc_sg; char iv[AES_BLOCK_SIZE] __aligned(8); @@ -225,7 +280,7 @@ static int ceph_aes_crypt(const struct ceph_crypto_key *key, bool encrypt, return ret; memcpy(iv, aes_iv, AES_BLOCK_SIZE); - skcipher_request_set_sync_tfm(req, key->tfm); + skcipher_request_set_sync_tfm(req, key->aes_tfm); skcipher_request_set_callback(req, 0, NULL, NULL); skcipher_request_set_crypt(req, sgt.sgl, sgt.sgl, crypt_len, iv); @@ -270,7 +325,68 @@ static int ceph_aes_crypt(const struct ceph_crypto_key *key, bool encrypt, return ret; } -int ceph_crypt(const struct ceph_crypto_key *key, bool encrypt, +static int ceph_krb5_encrypt(const struct ceph_crypto_key *key, int usage_slot, + void *buf, int buf_len, int in_len, int *pout_len) +{ + struct sg_table sgt; + struct scatterlist prealloc_sg; + int ret; + + if (WARN_ON_ONCE(usage_slot >= ARRAY_SIZE(key->krb5_tfms))) + return -EINVAL; + + ret = setup_sgtable(&sgt, &prealloc_sg, buf, buf_len); + if (ret) + return ret; + + ret = crypto_krb5_encrypt(key->krb5_type, key->krb5_tfms[usage_slot], + sgt.sgl, sgt.nents, buf_len, AES_BLOCK_SIZE, + in_len, false); + if (ret < 0) { + pr_err("%s encrypt failed: %d\n", __func__, ret); + goto out_sgt; + } + + *pout_len = ret; + ret = 0; + +out_sgt: + teardown_sgtable(&sgt); + return ret; +} + +static int ceph_krb5_decrypt(const struct ceph_crypto_key *key, int usage_slot, + void *buf, int buf_len, int in_len, int *pout_len) +{ + struct sg_table sgt; + struct scatterlist prealloc_sg; + size_t data_off = 0; + size_t data_len = in_len; + int ret; + + if (WARN_ON_ONCE(usage_slot >= ARRAY_SIZE(key->krb5_tfms))) + return -EINVAL; + + ret = setup_sgtable(&sgt, &prealloc_sg, buf, in_len); + if (ret) + return ret; + + ret = crypto_krb5_decrypt(key->krb5_type, key->krb5_tfms[usage_slot], + sgt.sgl, sgt.nents, &data_off, &data_len); + if (ret) { + pr_err("%s decrypt failed: %d\n", __func__, ret); + goto out_sgt; + } + + WARN_ON(data_off != AES_BLOCK_SIZE); + *pout_len = data_len; + +out_sgt: + teardown_sgtable(&sgt); + return ret; +} + +int ceph_crypt(const struct ceph_crypto_key *key, int usage_slot, bool encrypt, void *buf, int buf_len, int in_len, int *pout_len) { switch (key->type) { @@ -280,11 +396,64 @@ int ceph_crypt(const struct ceph_crypto_key *key, bool encrypt, case CEPH_CRYPTO_AES: return ceph_aes_crypt(key, encrypt, buf, buf_len, in_len, pout_len); + case CEPH_CRYPTO_AES256KRB5: + return encrypt ? + ceph_krb5_encrypt(key, usage_slot, buf, buf_len, in_len, + pout_len) : + ceph_krb5_decrypt(key, usage_slot, buf, buf_len, in_len, + pout_len); default: return -ENOTSUPP; } } +int ceph_crypt_data_offset(const struct ceph_crypto_key *key) +{ + switch (key->type) { + case CEPH_CRYPTO_NONE: + case CEPH_CRYPTO_AES: + return 0; + case CEPH_CRYPTO_AES256KRB5: + /* confounder */ + return AES_BLOCK_SIZE; + default: + BUG(); + } +} + +int ceph_crypt_buflen(const struct ceph_crypto_key *key, int data_len) +{ + switch (key->type) { + case CEPH_CRYPTO_NONE: + return data_len; + case CEPH_CRYPTO_AES: + /* PKCS#7 padding at the end */ + return data_len + AES_BLOCK_SIZE - + (data_len & (AES_BLOCK_SIZE - 1)); + case CEPH_CRYPTO_AES256KRB5: + /* confounder at the beginning and 192-bit HMAC at the end */ + return AES_BLOCK_SIZE + data_len + 24; + default: + BUG(); + } +} + +void ceph_hmac_sha256(const struct ceph_crypto_key *key, const void *buf, + int buf_len, u8 hmac[SHA256_DIGEST_SIZE]) +{ + switch (key->type) { + case CEPH_CRYPTO_NONE: + case CEPH_CRYPTO_AES: + memset(hmac, 0, SHA256_DIGEST_SIZE); + return; + case CEPH_CRYPTO_AES256KRB5: + hmac_sha256(&key->hmac_key, buf, buf_len, hmac); + return; + default: + BUG(); + } +} + static int ceph_key_preparse(struct key_preparsed_payload *prep) { struct ceph_crypto_key *ckey; @@ -297,7 +466,7 @@ static int ceph_key_preparse(struct key_preparsed_payload *prep) goto err; ret = -ENOMEM; - ckey = kmalloc(sizeof(*ckey), GFP_KERNEL); + ckey = kzalloc(sizeof(*ckey), GFP_KERNEL); if (!ckey) goto err; diff --git a/net/ceph/crypto.h b/net/ceph/crypto.h index a20bad6d1e96..3a2ade15abbc 100644 --- a/net/ceph/crypto.h +++ b/net/ceph/crypto.h @@ -2,10 +2,11 @@ #ifndef _FS_CEPH_CRYPTO_H #define _FS_CEPH_CRYPTO_H +#include #include #include -#define CEPH_MAX_KEY_LEN 16 +#define CEPH_MAX_KEY_LEN 32 #define CEPH_MAX_CON_SECRET_LEN 64 /* @@ -16,9 +17,19 @@ struct ceph_crypto_key { struct ceph_timespec created; int len; void *key; - struct crypto_sync_skcipher *tfm; + + union { + struct crypto_sync_skcipher *aes_tfm; + struct { + struct hmac_sha256_key hmac_key; + const struct krb5_enctype *krb5_type; + struct crypto_aead *krb5_tfms[3]; + }; + }; }; +int ceph_crypto_key_prepare(struct ceph_crypto_key *key, + const u32 *key_usages, int key_usage_cnt); int ceph_crypto_key_clone(struct ceph_crypto_key *dst, const struct ceph_crypto_key *src); int ceph_crypto_key_decode(struct ceph_crypto_key *key, void **p, void *end); @@ -26,8 +37,12 @@ int ceph_crypto_key_unarmor(struct ceph_crypto_key *key, const char *in); void ceph_crypto_key_destroy(struct ceph_crypto_key *key); /* crypto.c */ -int ceph_crypt(const struct ceph_crypto_key *key, bool encrypt, +int ceph_crypt(const struct ceph_crypto_key *key, int usage_slot, bool encrypt, void *buf, int buf_len, int in_len, int *pout_len); +int ceph_crypt_data_offset(const struct ceph_crypto_key *key); +int ceph_crypt_buflen(const struct ceph_crypto_key *key, int data_len); +void ceph_hmac_sha256(const struct ceph_crypto_key *key, const void *buf, + int buf_len, u8 hmac[SHA256_DIGEST_SIZE]); int ceph_crypto_init(void); void ceph_crypto_shutdown(void); diff --git a/net/ceph/messenger_v2.c b/net/ceph/messenger_v2.c index 4bb238eb8606..d5300c66258d 100644 --- a/net/ceph/messenger_v2.c +++ b/net/ceph/messenger_v2.c @@ -778,9 +778,9 @@ static int setup_crypto(struct ceph_connection *con, return 0; /* auth_x, secure mode */ } -static void ceph_hmac_sha256(struct ceph_connection *con, - const struct kvec *kvecs, int kvec_cnt, - u8 hmac[SHA256_DIGEST_SIZE]) +static void con_hmac_sha256(struct ceph_connection *con, + const struct kvec *kvecs, int kvec_cnt, + u8 hmac[SHA256_DIGEST_SIZE]) { struct hmac_sha256_ctx ctx; int i; @@ -1437,8 +1437,8 @@ static int prepare_auth_signature(struct ceph_connection *con) if (!buf) return -ENOMEM; - ceph_hmac_sha256(con, con->v2.in_sign_kvecs, con->v2.in_sign_kvec_cnt, - CTRL_BODY(buf)); + con_hmac_sha256(con, con->v2.in_sign_kvecs, con->v2.in_sign_kvec_cnt, + CTRL_BODY(buf)); return prepare_control(con, FRAME_TAG_AUTH_SIGNATURE, buf, SHA256_DIGEST_SIZE); @@ -2441,8 +2441,8 @@ static int process_auth_signature(struct ceph_connection *con, return -EINVAL; } - ceph_hmac_sha256(con, con->v2.out_sign_kvecs, con->v2.out_sign_kvec_cnt, - hmac); + con_hmac_sha256(con, con->v2.out_sign_kvecs, con->v2.out_sign_kvec_cnt, + hmac); ceph_decode_need(&p, end, SHA256_DIGEST_SIZE, bad); if (crypto_memneq(p, hmac, SHA256_DIGEST_SIZE)) { diff --git a/net/compat.c b/net/compat.c index 485db8ee9b28..996a8110b3c9 100644 --- a/net/compat.c +++ b/net/compat.c @@ -287,7 +287,7 @@ static int scm_max_fds_compat(struct msghdr *msg) return (msg->msg_controllen - sizeof(struct compat_cmsghdr)) / sizeof(int); } -void scm_detach_fds_compat(struct msghdr *msg, struct scm_cookie *scm) +void scm_detach_fds_compat(struct msghdr *msg, struct scm_cookie *scm, bool notrunc) { struct compat_cmsghdr __user *cm = (struct compat_cmsghdr __user *)msg->msg_control_user; @@ -297,7 +297,7 @@ void scm_detach_fds_compat(struct msghdr *msg, struct scm_cookie *scm) int err = 0, i; for (i = 0; i < fdmax; i++) { - err = scm_recv_one_fd(scm->fp->fp[i], cmsg_data + i, o_flags); + err = scm_recv_one_fd(scm->fp->fp[i], cmsg_data + i, o_flags, notrunc); if (err < 0) break; } diff --git a/net/core/dev.c b/net/core/dev.c index e4216b78a1a4..91da33c29aa1 100644 --- a/net/core/dev.c +++ b/net/core/dev.c @@ -4045,6 +4045,18 @@ static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device if (unlikely(!skb)) goto out_null; + /* Only fraglist GSO, whose segments already carry valid checksums, + * can be handed to a device as CHECKSUM_UNNECESSARY. Any other GSO + * skb has no csum_start for the device to segment from. NONE means + * the same on transmit, but makes netif_needs_gso() send it to the + * GSO code, which turns TCP into CHECKSUM_PARTIAL for TSO and + * segments anything the device cannot offload in software. + */ + if (unlikely(skb->ip_summed == CHECKSUM_UNNECESSARY && + skb_is_gso(skb) && + !(skb_shinfo(skb)->gso_type & SKB_GSO_FRAGLIST))) + skb->ip_summed = CHECKSUM_NONE; + features = netif_skb_features(skb); skb = validate_xmit_vlan(skb, features); if (unlikely(!skb)) diff --git a/net/core/devmem.c b/net/core/devmem.c index 16ce197cb0fa..9b937d426cb9 100644 --- a/net/core/devmem.c +++ b/net/core/devmem.c @@ -180,6 +180,7 @@ net_devmem_bind_dmabuf(struct net_device *dev, struct device *dma_dev, enum dma_data_direction direction, unsigned int dmabuf_fd, struct netdev_nl_sock *priv, + const struct sock *nl_sk, struct netlink_ext_ack *extack) { struct net_devmem_dmabuf_binding *binding; @@ -207,6 +208,8 @@ net_devmem_bind_dmabuf(struct net_device *dev, } binding->dev = dev; + write_pnet(&binding->net, sock_net(nl_sk)); + binding->uid = sk_uid(nl_sk); xa_init_flags(&binding->bound_rxqs, XA_FLAGS_ALLOC); refcount_set(&binding->ref, 1); @@ -374,7 +377,9 @@ struct net_devmem_dmabuf_binding *net_devmem_get_binding(struct sock *sk, int err = 0; binding = net_devmem_lookup_dmabuf(dmabuf_id); - if (!binding || !binding->tx_vec) { + if (!binding || !binding->tx_vec || + !net_eq(sock_net(sk), read_pnet(&binding->net)) || + !uid_eq(sk_uid(sk), binding->uid)) { err = -EINVAL; goto out_err; } diff --git a/net/core/devmem.h b/net/core/devmem.h index 101150d761af..674279180dc8 100644 --- a/net/core/devmem.h +++ b/net/core/devmem.h @@ -10,6 +10,7 @@ #ifndef _NET_DEVMEM_H #define _NET_DEVMEM_H +#include #include #include @@ -21,6 +22,8 @@ struct net_devmem_dmabuf_binding { struct sg_table *sgt; struct net_device *dev; struct gen_pool *chunk_pool; + possible_net_t net; + kuid_t uid; /* Protect dev */ struct mutex lock; @@ -88,6 +91,7 @@ net_devmem_bind_dmabuf(struct net_device *dev, struct device *dma_dev, enum dma_data_direction direction, unsigned int dmabuf_fd, struct netdev_nl_sock *priv, + const struct sock *nl_sk, struct netlink_ext_ack *extack); struct net_devmem_dmabuf_binding *net_devmem_lookup_dmabuf(u32 id); void net_devmem_unbind_dmabuf(struct net_devmem_dmabuf_binding *binding); @@ -175,6 +179,7 @@ net_devmem_bind_dmabuf(struct net_device *dev, enum dma_data_direction direction, unsigned int dmabuf_fd, struct netdev_nl_sock *priv, + const struct sock *nl_sk, struct netlink_ext_ack *extack) { return ERR_PTR(-EOPNOTSUPP); diff --git a/net/core/filter.c b/net/core/filter.c index 8f92e2bf8551..8b76dd120103 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -3330,6 +3330,10 @@ static void bpf_skb_change_protocol(struct sk_buff *skb, u16 proto) static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len) { + /* The bytes in front of @off are moved with skb->data. */ + if (unlikely(off > skb->len || !pskb_may_pull(skb, off))) + return -ENOMEM; + /* Caller already did skb_cow() with meta_len+len as headroom, * so no need to do it here. */ @@ -3350,9 +3354,10 @@ static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len) void *old_data; /* skb_ensure_writable() is not needed here, as we're - * already working on an uncloned skb. + * already working on an uncloned skb. The first test + * keeps off + len from wrapping. */ - if (unlikely(!pskb_may_pull(skb, off + len))) + if (unlikely(off > skb->len || !pskb_may_pull(skb, off + len))) return -ENOMEM; old_data = skb->data; @@ -3363,9 +3368,25 @@ static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len) return 0; } +/* + * bpf_skb_net_hdr_push() inserts bytes at @off, bpf_skb_net_hdr_pop() removes + * bytes at @off. Both move the bytes in front of @off together with skb->data, + * and leave the rest of the packet where it is. Return true if the transport + * header is in the part that moves. A transport header that is equal to the + * network header stays equal to it. + */ +static bool bpf_skb_trans_hdr_moves(const struct sk_buff *skb, u32 off) +{ + if (skb->transport_header == skb->network_header) + return true; + + return skb_transport_header_was_set(skb) && + (u32)skb_transport_offset(skb) < off; +} + static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len) { - bool trans_same = skb->transport_header == skb->network_header; + bool trans_moves = bpf_skb_trans_hdr_moves(skb, off); int ret; /* There's no need for __skb_push()/__skb_pull() pair to @@ -3376,8 +3397,8 @@ static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len) if (likely(!ret)) { skb->mac_header -= len; skb->network_header -= len; - if (trans_same) - skb->transport_header = skb->network_header; + if (trans_moves) + skb->transport_header -= len; } return ret; @@ -3385,7 +3406,7 @@ static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len) static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len) { - bool trans_same = skb->transport_header == skb->network_header; + bool trans_moves = bpf_skb_trans_hdr_moves(skb, off); int ret; /* Same here, __skb_push()/__skb_pull() pair not needed. */ @@ -3393,8 +3414,17 @@ static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len) if (likely(!ret)) { skb->mac_header += len; skb->network_header += len; - if (trans_same) - skb->transport_header = skb->network_header; + if (trans_moves) { + skb->transport_header += len; + } else if (skb_transport_header_was_set(skb) && + skb_transport_offset(skb) < (int)off) { + /* It was in the removed bytes or before skb->data. */ + skb_set_transport_header(skb, off); + } + /* Do not leave the inner transport header in front of @off. */ + if (skb->encapsulation && + skb_inner_transport_offset(skb) < (int)off) + skb_set_inner_transport_header(skb, off); } return ret; @@ -3701,6 +3731,14 @@ static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff, return -ENOTSUPP; } + /* + * The MSS is raised by len_diff. It has 16 bits, and GSO_BY_FRAGS is + * not a size. + */ + if (skb_is_gso(skb) && !(flags & BPF_F_ADJ_ROOM_FIXED_GSO) && + skb_shinfo(skb)->gso_size + len_diff >= GSO_BY_FRAGS) + return -ENOTSUPP; + ret = skb_unclone(skb, GFP_ATOMIC); if (unlikely(ret < 0)) return ret; @@ -5460,11 +5498,12 @@ static int bpf_sol_tcp_setsockopt(struct sock *sk, int optname, case TCP_BPF_IW: if (val <= 0 || tp->data_segs_out > tp->syn_data) return -EINVAL; - tcp_snd_cwnd_set(tp, val); + tcp_snd_cwnd_set(tp, min_t(u32, val, tp->snd_cwnd_clamp)); break; case TCP_BPF_SNDCWND_CLAMP: if (val <= 0) return -EINVAL; + val = min_t(u32, val, TCP_MAX_SND_CWND); tp->snd_cwnd_clamp = val; WRITE_ONCE(tp->snd_ssthresh, val); break; @@ -6603,11 +6642,15 @@ static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len if (!seg6_validate_srh(srh, len, false)) return -EINVAL; + /* + * The encap mode names IPv6 as the inner protocol, and neither mode + * updates skb->protocol. + */ + if (skb->protocol != htons(ETH_P_IPV6)) + return -EBADMSG; + switch (type) { case BPF_LWT_ENCAP_SEG6_INLINE: - if (skb->protocol != htons(ETH_P_IPV6)) - return -EBADMSG; - err = seg6_do_srh_inline(skb, srh); break; case BPF_LWT_ENCAP_SEG6: @@ -6696,12 +6739,13 @@ BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset, this_cpu_ptr(&seg6_bpf_srh_states); struct ipv6_sr_hdr *srh = srh_state->srh; void *srh_tlvs, *srh_end, *ptr; - int srhoff = 0; + int srhoff; lockdep_assert_held(&srh_state->bh_lock); if (srh == NULL) return -EINVAL; + srhoff = (unsigned char *)srh - skb->data; srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4)); srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen); @@ -6714,8 +6758,7 @@ BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset, if (unlikely(bpf_try_make_writable(skb, offset + len))) return -EFAULT; - if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) - return -EINVAL; + /* The head may have moved. */ srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff); memcpy(skb->data + offset, from, len); @@ -6831,16 +6874,18 @@ BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset, { struct seg6_bpf_srh_state *srh_state = this_cpu_ptr(&seg6_bpf_srh_states); + bool mac_set = skb_mac_header_was_set(skb); struct ipv6_sr_hdr *srh = srh_state->srh; void *srh_end, *srh_tlvs, *ptr; struct ipv6hdr *hdr; - int srhoff = 0; + int srhoff; int ret; lockdep_assert_held(&srh_state->bh_lock); if (unlikely(srh == NULL)) return -EINVAL; + srhoff = (unsigned char *)srh - skb->data; srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) + ((srh->first_segment + 1) << 4)); srh_end = (void *)((unsigned char *)srh + sizeof(*srh) + @@ -6851,26 +6896,46 @@ BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset, return -EFAULT; if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end)) return -EFAULT; + /* The length field of the SRH has 8 bits, in units of 8 bytes. */ + if (unlikely(len > (U8_MAX << 3) - srh_state->hdrlen)) + return -EFAULT; + /* + * skb->data is the network header here. The MAC header is in front of + * it, so bpf_skb_net_hdr_push() and bpf_skb_net_hdr_pop() do not move + * it with the other headers. + */ if (len > 0) { - ret = skb_cow_head(skb, len); + ret = skb_cow_head(skb, len + skb->mac_len); if (unlikely(ret < 0)) return ret; + /* The push can write over the MAC header, so move it first. */ + if (mac_set) + memmove(skb->data - len - skb->mac_len, + skb_mac_header(skb), skb->mac_len); ret = bpf_skb_net_hdr_push(skb, offset, len); } else { ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len); + /* The pop has added -len to skb->mac_header. */ + if (likely(!ret) && mac_set) + memmove(skb->data - skb->mac_len, + skb_mac_header(skb) + len, skb->mac_len); } bpf_compute_data_pointers(skb); if (unlikely(ret < 0)) return ret; + if (mac_set) + skb_set_mac_header(skb, -skb->mac_len); + else + skb_unset_mac_header(skb); + hdr = (struct ipv6hdr *)skb->data; hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr)); - if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) - return -EINVAL; + /* The bytes in front of offset have moved together with skb->data. */ srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff); srh_state->hdrlen += len; srh_state->valid = false; diff --git a/net/core/gro.c b/net/core/gro.c index a7b3fdc1f7ba..87ccc393721e 100644 --- a/net/core/gro.c +++ b/net/core/gro.c @@ -243,6 +243,14 @@ int skb_gro_receive_list(struct sk_buff *p, struct sk_buff *skb) NAPI_GRO_CB(skb)->flush)) return -E2BIG; + /* Fraglist members keep their own headers. Their checksum can not + * be right both for a forwarded packet and for a decapsulated one, + * if remote checksum offload adjusted it. + */ + if (unlikely(skb->remcsum_offload)) + return -EINVAL; + + skb_gro_frag0_invalidate(skb); if (!pskb_may_pull(skb, skb_gro_offset(skb))) { NAPI_GRO_CB(skb)->flush = 1; return -ENOMEM; @@ -379,6 +387,7 @@ static void gro_list_prepare(const struct list_head *head, } diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev; + diffs |= p->protocol != skb->protocol; diffs |= p->vlan_all ^ skb->vlan_all; diffs |= skb_metadata_differs(p, skb); if (maclen == ETH_HLEN) @@ -418,7 +427,8 @@ static inline void skb_gro_reset_offset(struct sk_buff *skb, u32 nhoff) headlen = skb_headlen(skb); NAPI_GRO_CB(skb)->frag0 = skb->data; NAPI_GRO_CB(skb)->frag0_len = headlen; - if (headlen) + /* Shared fragments must be pulled into the linear head before parsing. */ + if (headlen || skb_has_shared_frag(skb)) return; pinfo = skb_shinfo(skb); @@ -455,12 +465,19 @@ static void gro_pull_from_frag0(struct sk_buff *skb, int grow) } } -static void gro_try_pull_from_frag0(struct sk_buff *skb) +static bool gro_try_pull_from_frag0(struct sk_buff *skb) { int grow = skb_gro_offset(skb) - skb_headlen(skb); - if (grow > 0) + if (grow <= 0) + return true; + + /* frag0 can only be used if no pull happened. */ + if (likely(NAPI_GRO_CB(skb)->frag0_len)) { gro_pull_from_frag0(skb, grow); + return true; + } + return pskb_may_pull(skb, skb_gro_offset(skb)); } static void gro_flush_oldest(struct gro_node *gro, struct list_head *head) @@ -562,13 +579,17 @@ static enum gro_result dev_gro_receive(struct gro_node *gro, if (NAPI_GRO_CB(skb)->flush) goto normal; + /* Must be called before setting NAPI_GRO_CB(skb)->{age|last}. + * A held packet must have its headers in the linear part. + */ + if (unlikely(!gro_try_pull_from_frag0(skb))) + goto normal; + if (unlikely(gro_list->count >= MAX_GRO_SKBS)) gro_flush_oldest(gro, &gro_list->list); else gro_list->count++; - /* Must be called before setting NAPI_GRO_CB(skb)->{age|last} */ - gro_try_pull_from_frag0(skb); NAPI_GRO_CB(skb)->age = jiffies; NAPI_GRO_CB(skb)->last = skb; if (!skb_is_gso(skb)) diff --git a/net/core/lwt_bpf.c b/net/core/lwt_bpf.c index 953237bca36b..6d29da9f5460 100644 --- a/net/core/lwt_bpf.c +++ b/net/core/lwt_bpf.c @@ -86,6 +86,32 @@ static int run_lwt_bpf(struct sk_buff *skb, struct bpf_lwt_prog *lwt, return ret; } +/* + * skb->cb still describes the IP header that was the first one before the + * prog ran. The option offsets in IPCB(skb)->opt are wrong for a pushed + * header, and a header of the other family needs the other layout. iif + * stays: behind a VRF skb->skb_iif is the L3 master and not the port. + * bpf_lwt_push_encap() cannot do this, because bpf_prog_run_save_cb() can + * restore skb->cb after the prog. + */ +static void bpf_lwt_reset_cb(struct sk_buff *skb, __be16 proto) +{ + int iif; + + if (skb->protocol == proto) { + if (proto == htons(ETH_P_IP)) + memset(&IPCB(skb)->opt, 0, sizeof(IPCB(skb)->opt)); + } else if (skb->protocol == htons(ETH_P_IP)) { + iif = IP6CB(skb)->iif; + memset(IPCB(skb), 0, sizeof(*IPCB(skb))); + IPCB(skb)->iif = iif; + } else { + iif = IPCB(skb)->iif; + memset(IP6CB(skb), 0, sizeof(*IP6CB(skb))); + IP6CB(skb)->iif = iif; + } +} + static int bpf_lwt_input_reroute(struct sk_buff *skb) { enum skb_drop_reason reason; @@ -120,6 +146,8 @@ static int bpf_lwt_input_reroute(struct sk_buff *skb) static int bpf_input(struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); + __be16 proto = skb->protocol; + unsigned int len = skb->len; struct bpf_lwt *bpf; int ret; @@ -128,8 +156,21 @@ static int bpf_input(struct sk_buff *skb) ret = run_lwt_bpf(skb, &bpf->in, dst, NO_REDIRECT); if (ret < 0) return ret; + /* An lwt_in prog can change the length only with a push. */ + if (skb->len != len) + bpf_lwt_reset_cb(skb, proto); if (ret == BPF_LWT_REROUTE) return bpf_lwt_input_reroute(skb); + /* + * orig_input() is for the old protocol only, see bpf_xmit(). + * It also needs a dst of the old family. BPF_LWT_ENCAP_SEG6 + * puts an IPv6 dst into the skb. + */ + if (skb->protocol != proto || + skb_dst(skb)->ops->family != dst->ops->family) { + kfree_skb(skb); + return -EINVAL; + } } if (unlikely(!dst->lwtstate->orig_input)) { @@ -300,13 +341,17 @@ static int bpf_xmit(struct sk_buff *skb) * made before LWT xmit. */ ret = xmit_check_headroom(skb, hroom); - if (unlikely(ret)) + if (unlikely(ret)) { + kfree_skb(skb); return ret; + } return LWTUNNEL_XMIT_CONTINUE; case BPF_REDIRECT: return LWTUNNEL_XMIT_DONE; case BPF_LWT_REROUTE: + /* An lwt_xmit prog can also write to the options. */ + bpf_lwt_reset_cb(skb, proto); return bpf_lwt_xmit_reroute(skb); default: return ret; @@ -645,6 +690,14 @@ int bpf_lwt_push_ip_encap(struct sk_buff *skb, void *hdr, u32 len, bool ingress) if (ingress) skb_postpush_rcsum(skb, iph, len); skb_reset_network_header(skb); + /* + * The new header goes over the MAC header. On ingress move it first. + * On egress the packet gets a new one, so forget the old one. + */ + if (ingress) + skb_mac_header_rebuild(skb); + else + skb_unset_mac_header(skb); if (is_udp_tunnel) { size_t iph_sz = ipv4 ? iph->ihl * 4 : sizeof(struct ipv6hdr); diff --git a/net/core/net-sysfs.c b/net/core/net-sysfs.c index 3a3a92f3a314..e408f0b6786b 100644 --- a/net/core/net-sysfs.c +++ b/net/core/net-sysfs.c @@ -1101,6 +1101,14 @@ static ssize_t store_rps_dev_flow_table_cnt(struct netdev_rx_queue *queue, */ while ((mask | (mask >> 1)) != mask) mask |= (mask >> 1); + + /* Require at least two entries. A one-entry table rounds up + * to mask == 0, which encodes log == 0 in the tag. + * get_rps_cpu() then computes hash_32(hash, 0), a shift by 32. + */ + if (!mask) + return -EINVAL; + /* On 64 bit arches, must check mask fits in table->mask (u32), * and on 32bit arches, must check * RPS_DEV_FLOW_TABLE_SIZE(mask + 1) doesn't overflow. diff --git a/net/core/netdev-genl.c b/net/core/netdev-genl.c index 77042ac6d042..d42e4c4d7a7d 100644 --- a/net/core/netdev-genl.c +++ b/net/core/netdev-genl.c @@ -1004,7 +1004,8 @@ int netdev_nl_bind_rx_doit(struct sk_buff *skb, struct genl_info *info) } binding = net_devmem_bind_dmabuf(netdev, dma_dev, DMA_FROM_DEVICE, - dmabuf_fd, priv, info->extack); + dmabuf_fd, priv, NETLINK_CB(skb).sk, + info->extack); if (IS_ERR(binding)) { err = PTR_ERR(binding); goto err_rxq_bitmap; @@ -1097,7 +1098,8 @@ int netdev_nl_bind_tx_doit(struct sk_buff *skb, struct genl_info *info) dma_dev = netdev_queue_get_dma_dev(netdev, 0); binding = net_devmem_bind_dmabuf(netdev, dma_dev, DMA_TO_DEVICE, - dmabuf_fd, priv, info->extack); + dmabuf_fd, priv, NETLINK_CB(skb).sk, + info->extack); if (IS_ERR(binding)) { err = PTR_ERR(binding); goto err_unlock_netdev; diff --git a/net/core/scm.c b/net/core/scm.c index 66eaee783e8b..938f9616a59c 100644 --- a/net/core/scm.c +++ b/net/core/scm.c @@ -353,7 +353,31 @@ static int scm_max_fds(struct msghdr *msg) return (msg->msg_controllen - sizeof(struct cmsghdr)) / sizeof(int); } -void scm_detach_fds(struct msghdr *msg, struct scm_cookie *scm) +int scm_recv_one_fd(struct file *f, int __user *ufd, unsigned int flags, + bool notrunc) +{ + int error; + + if (!ufd) + return -EFAULT; + + error = security_file_receive(f); + if (error) + return notrunc ? put_user(error, ufd) : error; + + FD_PREPARE(fdf, flags, get_file(f)); + if (fdf.err) + return fdf.err; + + error = put_user(fd_prepare_fd(fdf), ufd); + if (error) + return error; + + __receive_sock(fd_prepare_file(fdf)); + return fd_publish(fdf); +} + +void scm_detach_fds(struct msghdr *msg, struct scm_cookie *scm, bool notrunc) { struct cmsghdr __user *cm = (__force struct cmsghdr __user *)msg->msg_control_user; @@ -367,12 +391,12 @@ void scm_detach_fds(struct msghdr *msg, struct scm_cookie *scm) return; if (msg->msg_flags & MSG_CMSG_COMPAT) { - scm_detach_fds_compat(msg, scm); + scm_detach_fds_compat(msg, scm, notrunc); return; } for (i = 0; i < fdmax; i++) { - err = scm_recv_one_fd(scm->fp->fp[i], cmsg_data + i, o_flags); + err = scm_recv_one_fd(scm->fp->fp[i], cmsg_data + i, o_flags, notrunc); if (err < 0) break; } @@ -525,9 +549,6 @@ static bool __scm_recv_common(struct sock *sk, struct msghdr *msg, scm_passec(sk, msg, scm); - if (scm->fp) - scm_detach_fds(msg, scm); - return true; } @@ -547,6 +568,13 @@ void scm_recv_unix(struct socket *sock, struct msghdr *msg, if (!__scm_recv_common(sock->sk, msg, scm, flags)) return; + if (scm->fp) { + struct unix_sock *u; + + u = unix_sk(sock->sk); + scm_detach_fds(msg, scm, READ_ONCE(u->scm_rights_notrunc)); + } + if (sock->sk->sk_scm_pidfd) scm_pidfd_recv(msg, scm); diff --git a/net/core/skbuff.c b/net/core/skbuff.c index e28802a46fd2..07df2030ccf2 100644 --- a/net/core/skbuff.c +++ b/net/core/skbuff.c @@ -934,6 +934,7 @@ int skb_pp_cow_data(struct page_pool *pool, struct sk_buff **pskb, skb_reserve(nskb, headroom); skb_copy_header(nskb, skb); + nskb->mac_len = skb->mac_len; skb_mark_for_recycle(nskb); err = skb_copy_bits(skb, 0, nskb->data, size); @@ -1458,6 +1459,10 @@ void napi_skb_free_stolen_head(struct sk_buff *skb) skb_orphan(skb); skb->slow_gro = 0; } + if (skb->fclone != SKB_FCLONE_UNAVAILABLE) { + kfree_skbmem(skb); + return; + } napi_skb_cache_put(skb); } @@ -1854,6 +1859,7 @@ int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb, struct ubuf_info *uarg, struct net_devmem_dmabuf_binding *binding) { + unsigned int orig_truesize = skb->truesize; int err, orig_len = skb->len; if (uarg->ops->link_skb) { @@ -1874,12 +1880,18 @@ int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb, err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len, binding); if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) { + u32 delta_truesize = skb->truesize - orig_truesize; struct sock *save_sk = skb->sk; /* Streams do not free skb on error. Reset to prev state. */ iov_iter_revert(&msg->msg_iter, skb->len - orig_len); skb->sk = sk; - ___pskb_trim(skb, orig_len); + if (!___pskb_trim(skb, orig_len)) { + skb->truesize -= delta_truesize; + sk_wmem_queued_add(sk, -delta_truesize); + if (!skb_zcopy_pure(skb)) + sk_mem_uncharge(sk, delta_truesize); + } skb->sk = save_sk; return err; } @@ -6126,7 +6138,7 @@ void kfree_skb_partial(struct sk_buff *skb, bool head_stolen) { if (head_stolen) { skb_release_head_state(skb); - kmem_cache_free(net_hotdata.skbuff_cache, skb); + kfree_skbmem(skb); } else { __kfree_skb(skb); } @@ -6713,7 +6725,7 @@ int skb_mpls_dec_ttl(struct sk_buff *skb) lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry); ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT; - if (!--ttl) + if (!ttl || !--ttl) return -EINVAL; lse &= ~MPLS_LS_TTL_MASK; diff --git a/net/core/sock_reuseport.c b/net/core/sock_reuseport.c index 4211710393a8..eb8d24964e2f 100644 --- a/net/core/sock_reuseport.c +++ b/net/core/sock_reuseport.c @@ -6,6 +6,7 @@ * selecting the socket index from the array of available sockets. */ +#include #include #include #include @@ -124,10 +125,10 @@ static int reuseport_sock_index(struct sock *sk, static void __reuseport_add_sock(struct sock *sk, struct sock_reuseport *reuse) { - reuse->socks[reuse->num_socks] = sk; + WRITE_ONCE(reuse->socks[reuse->num_socks], sk); /* paired with smp_rmb() in reuseport_(select|migrate)_sock() */ smp_wmb(); - reuse->num_socks++; + WRITE_ONCE(reuse->num_socks, reuse->num_socks + 1); reuseport_get_incoming_cpu(sk, reuse); } @@ -139,8 +140,8 @@ static bool __reuseport_detach_sock(struct sock *sk, if (i == -1) return false; - reuse->socks[i] = reuse->socks[reuse->num_socks - 1]; - reuse->num_socks--; + WRITE_ONCE(reuse->socks[i], reuse->socks[reuse->num_socks - 1]); + WRITE_ONCE(reuse->num_socks, reuse->num_socks - 1); reuseport_put_incoming_cpu(sk, reuse); return true; @@ -149,7 +150,7 @@ static bool __reuseport_detach_sock(struct sock *sk, static void __reuseport_add_closed_sock(struct sock *sk, struct sock_reuseport *reuse) { - reuse->socks[reuse->max_socks - reuse->num_closed_socks - 1] = sk; + WRITE_ONCE(reuse->socks[reuse->max_socks - reuse->num_closed_socks - 1], sk); /* paired with READ_ONCE() in inet_csk_bind_conflict() */ WRITE_ONCE(reuse->num_closed_socks, reuse->num_closed_socks + 1); reuseport_get_incoming_cpu(sk, reuse); @@ -163,7 +164,8 @@ static bool __reuseport_detach_closed_sock(struct sock *sk, if (i == -1) return false; - reuse->socks[i] = reuse->socks[reuse->max_socks - reuse->num_closed_socks]; + WRITE_ONCE(reuse->socks[i], + reuse->socks[reuse->max_socks - reuse->num_closed_socks]); /* paired with READ_ONCE() in inet_csk_bind_conflict() */ WRITE_ONCE(reuse->num_closed_socks, reuse->num_closed_socks - 1); reuseport_put_incoming_cpu(sk, reuse); @@ -521,7 +523,7 @@ static struct sock *run_bpf_filter(struct sock_reuseport *reuse, u16 socks, if (index >= socks) return NULL; - return reuse->socks[index]; + return READ_ONCE(reuse->socks[index]); } static struct sock *reuseport_select_sock_by_hash(struct sock_reuseport *reuse, @@ -532,7 +534,7 @@ static struct sock *reuseport_select_sock_by_hash(struct sock_reuseport *reuse, i = j = reciprocal_scale(hash, num_socks); do { - struct sock *sk = reuse->socks[i]; + struct sock *sk = READ_ONCE(reuse->socks[i]); if (sk->sk_state != TCP_ESTABLISHED) { /* Paired with WRITE_ONCE() in __reuseport_(get|put)_incoming_cpu(). */ @@ -691,6 +693,14 @@ int reuseport_attach_prog(struct sock *sk, struct bpf_prog *prog) if (!sk->sk_reuseport) return -EINVAL; + /* Do not put a shutdown()ed TCP listener back into the + * listening section of a reuseport group while it is in + * TCP_CLOSE: requests can still migrate to it. + */ + if (sk_is_tcp(sk) && + inet_csk(sk)->unhashed_state == TCP_LISTEN) + return -EINVAL; + err = reuseport_alloc(sk, false); if (err) return err; diff --git a/net/ethtool/ioctl.c b/net/ethtool/ioctl.c index 9431e305b233..cb5d91084458 100644 --- a/net/ethtool/ioctl.c +++ b/net/ethtool/ioctl.c @@ -435,10 +435,10 @@ struct ethtool_link_usettings { }; /* Internal kernel helper to query a device ethtool_link_settings. */ -int __ethtool_get_link_ksettings(struct net_device *dev, - struct ethtool_link_ksettings *link_ksettings) +int netif_get_link_ksettings(struct net_device *dev, + struct ethtool_link_ksettings *link_ksettings) { - ASSERT_RTNL(); + /* once callers fixed - assert ops locked */ if (!dev->ethtool_ops->get_link_ksettings) return -EOPNOTSUPP; @@ -449,6 +449,17 @@ int __ethtool_get_link_ksettings(struct net_device *dev, memset(link_ksettings, 0, sizeof(*link_ksettings)); return dev->ethtool_ops->get_link_ksettings(dev, link_ksettings); } +EXPORT_SYMBOL(netif_get_link_ksettings); + +/* Convenience helper for callers that hold only rtnl_lock(). */ +int __ethtool_get_link_ksettings(struct net_device *dev, + struct ethtool_link_ksettings *link_ksettings) +{ + ASSERT_RTNL(); + + /* once callers fixed - take the ops lock around this call */ + return netif_get_link_ksettings(dev, link_ksettings); +} EXPORT_SYMBOL(__ethtool_get_link_ksettings); /* convert ethtool_link_usettings in user space to a kernel internal diff --git a/net/ethtool/linkinfo.c b/net/ethtool/linkinfo.c index 30b8ce275159..2d729acdaf03 100644 --- a/net/ethtool/linkinfo.c +++ b/net/ethtool/linkinfo.c @@ -34,7 +34,7 @@ static int linkinfo_prepare_data(const struct ethnl_req_info *req_base, ret = ethnl_ops_begin(dev); if (ret < 0) return ret; - ret = __ethtool_get_link_ksettings(dev, &data->ksettings); + ret = netif_get_link_ksettings(dev, &data->ksettings); if (ret < 0) GENL_SET_ERR_MSG(info, "failed to retrieve link settings"); ethnl_ops_complete(dev); @@ -104,7 +104,7 @@ ethnl_set_linkinfo(struct ethnl_req_info *req_info, struct genl_info *info) bool mod = false; int ret; - ret = __ethtool_get_link_ksettings(dev, &ksettings); + ret = netif_get_link_ksettings(dev, &ksettings); if (ret < 0) { GENL_SET_ERR_MSG(info, "failed to retrieve link settings"); return ret; diff --git a/net/ethtool/linkmodes.c b/net/ethtool/linkmodes.c index 259cd9ef1f2a..4ce4f29d2a7a 100644 --- a/net/ethtool/linkmodes.c +++ b/net/ethtool/linkmodes.c @@ -39,7 +39,7 @@ static int linkmodes_prepare_data(const struct ethnl_req_info *req_base, if (ret < 0) return ret; - ret = __ethtool_get_link_ksettings(dev, &data->ksettings); + ret = netif_get_link_ksettings(dev, &data->ksettings); if (ret < 0) { GENL_SET_ERR_MSG(info, "failed to retrieve link settings"); goto out; @@ -324,7 +324,7 @@ ethnl_set_linkmodes(struct ethnl_req_info *req_info, struct genl_info *info) bool mod = false; int ret; - ret = __ethtool_get_link_ksettings(dev, &ksettings); + ret = netif_get_link_ksettings(dev, &ksettings); if (ret < 0) { GENL_SET_ERR_MSG(info, "failed to retrieve link settings"); return ret; diff --git a/net/ipv4/esp4_offload.c b/net/ipv4/esp4_offload.c index abd77162f5e7..2309468cfc3d 100644 --- a/net/ipv4/esp4_offload.c +++ b/net/ipv4/esp4_offload.c @@ -37,6 +37,7 @@ static struct sk_buff *esp4_gro_receive(struct list_head *head, __be32 seq; __be32 spi; + skb_gro_frag0_invalidate(skb); if (!pskb_pull(skb, offset)) return NULL; diff --git a/net/ipv4/fib_trie.c b/net/ipv4/fib_trie.c index 77a3598d3385..ebf26aae32d5 100644 --- a/net/ipv4/fib_trie.c +++ b/net/ipv4/fib_trie.c @@ -61,6 +61,7 @@ #include #include #include +#include #include #include #include @@ -961,6 +962,8 @@ static struct key_vector *fib_find_node(struct trie *t, break; } + index = array_index_nospec(index, 1ul << n->bits); + /* keep searching until we find a perfect match leaf or NULL */ } while (IS_TNODE(n)); @@ -1466,6 +1469,8 @@ int fib_table_lookup(struct fib_table *tb, const struct flowi4 *flp, if (IS_LEAF(n)) goto found; + index = array_index_nospec(index, 1ul << n->bits); + /* only record pn and cindex if we are going to be chopping * bits later. Otherwise we are just wasting cycles. */ @@ -1766,6 +1771,8 @@ static struct key_vector *leaf_walk_rcu(struct key_vector **tn, t_key key) if (cindex >> pn->bits) break; + cindex = array_index_nospec(cindex, 1ul << pn->bits); + /* descend into the next child */ n = get_child_rcu(pn, cindex++); if (!n) @@ -1787,6 +1794,8 @@ static struct key_vector *leaf_walk_rcu(struct key_vector **tn, t_key key) continue; } + cindex = array_index_nospec(cindex, 1ul << pn->bits); + /* grab the next available node */ n = get_child_rcu(pn, cindex++); if (!n) @@ -2438,7 +2447,10 @@ static struct key_vector *fib_trie_get_next(struct fib_trie_iter *iter) while (!IS_TRIE(pn)) { while (cindex < child_length(pn)) { - struct key_vector *n = get_child_rcu(pn, cindex++); + struct key_vector *n; + + cindex = array_index_nospec(cindex, child_length(pn)); + n = get_child_rcu(pn, cindex++); if (!n) continue; diff --git a/net/ipv4/fou_core.c b/net/ipv4/fou_core.c index fc930274a1fd..ab0f337b59fa 100644 --- a/net/ipv4/fou_core.c +++ b/net/ipv4/fou_core.c @@ -364,6 +364,18 @@ static struct sk_buff *gue_gro_receive(struct sock *sk, default: goto out; } + + /* Match the encapsulation format and IP version. */ + list_for_each_entry(p, head, list) { + const struct iphdr *iph2; + + if (!NAPI_GRO_CB(p)->same_flow) + continue; + + iph2 = (const struct iphdr *)(p->data + off); + if (iph2->version != ((struct iphdr *)guehdr)->version) + NAPI_GRO_CB(p)->same_flow = 0; + } goto next_proto; default: goto out; @@ -1062,6 +1074,9 @@ static int fou_build_header(struct sk_buff *skb, struct ip_tunnel_encap *e, __be16 sport; int err; + if (skb_cow_head(skb, fou_encap_hlen(e))) + return -ENOMEM; + err = __fou_build_header(skb, e, protocol, &sport, type); if (err) return err; @@ -1074,16 +1089,24 @@ static int fou_build_header(struct sk_buff *skb, struct ip_tunnel_encap *e, static int gue_build_header(struct sk_buff *skb, struct ip_tunnel_encap *e, u8 *protocol, struct flowi4 *fl4) { - int type = e->flags & TUNNEL_ENCAP_FLAG_CSUM ? SKB_GSO_UDP_TUNNEL_CSUM : - SKB_GSO_UDP_TUNNEL; + struct ip_tunnel_encap encap = { + .flags = READ_ONCE(e->flags), + .sport = READ_ONCE(e->sport), + .dport = READ_ONCE(e->dport), + }; + int type = encap.flags & TUNNEL_ENCAP_FLAG_CSUM ? + SKB_GSO_UDP_TUNNEL_CSUM : SKB_GSO_UDP_TUNNEL; __be16 sport; int err; - err = __gue_build_header(skb, e, protocol, &sport, type); + if (skb_cow_head(skb, gue_encap_hlen(&encap))) + return -ENOMEM; + + err = __gue_build_header(skb, &encap, protocol, &sport, type); if (err) return err; - fou_build_udp(skb, e, fl4, protocol, sport); + fou_build_udp(skb, &encap, fl4, protocol, sport); return 0; } diff --git a/net/ipv4/igmp.c b/net/ipv4/igmp.c index 2846c2cee31c..1c0c3b195af4 100644 --- a/net/ipv4/igmp.c +++ b/net/ipv4/igmp.c @@ -2446,6 +2446,8 @@ int ip_mc_leave_group(struct sock *sk, struct ip_mreqn *imr) iml->multi.imr_address.s_addr) continue; + /* The drop request may not resolve to the joined device. */ + in_dev = inetdev_by_index(net, iml->multi.imr_ifindex); (void) ip_mc_leave_src(sk, iml, in_dev); *imlp = iml->next_rcu; diff --git a/net/ipv4/inet_connection_sock.c b/net/ipv4/inet_connection_sock.c index 2db9ceda0456..1f75a4a94cad 100644 --- a/net/ipv4/inet_connection_sock.c +++ b/net/ipv4/inet_connection_sock.c @@ -684,7 +684,7 @@ struct sock *inet_csk_accept(struct sock *sk, struct proto_accept_arg *arg) newsk = req->sk; if (sk->sk_protocol == IPPROTO_TCP && - tcp_rsk(req)->tfo_listener) { + tcp_sk(newsk)->syn_fastopen_child) { spin_lock_bh(&queue->fastopenq.lock); if (tcp_rsk(req)->tfo_listener) { /* We are still waiting for the final ACK from 3WHS @@ -1284,6 +1284,7 @@ struct sock *inet_csk_clone_lock(const struct sock *sk, memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue)); + newicsk->unhashed_state = 0; inet_sk_set_state(newsk, TCP_SYN_RECV); inet_clone_ulp(req, newsk, priority); @@ -1548,17 +1549,15 @@ void inet_csk_listen_stop(struct sock *sk) if (!has_current_bpf_ctx()) 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; - } + /* 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); } diff --git a/net/ipv4/inet_fragment.c b/net/ipv4/inet_fragment.c index 4d55444a6f30..1f0327f07faa 100644 --- a/net/ipv4/inet_fragment.c +++ b/net/ipv4/inet_fragment.c @@ -24,6 +24,7 @@ #include #include #include +#include #include "../core/sock_destructor.h" @@ -448,6 +449,10 @@ int inet_frag_queue_insert(struct inet_frag_queue *q, struct sk_buff *skb, if (skb->truesize > INET_FRAG_MAX_TRUESIZE - q->truesize) return IPFRAG_TOOBIG; + /* The reassembled skb keeps the first fragment's secpath. */ + if (last && !secpath_equal(last, skb)) + return IPFRAG_MIXED_SECPATH; + /* An IP fragment is never a GSO packet, but an untrusted source * (virtio_net_hdr) may have attached GSO metadata to it. Do not let * that reach the reassembled skb, whose head keeps the first diff --git a/net/ipv4/inet_hashtables.c b/net/ipv4/inet_hashtables.c index c0accacdc3eb..030276cde581 100644 --- a/net/ipv4/inet_hashtables.c +++ b/net/ipv4/inet_hashtables.c @@ -791,6 +791,11 @@ int inet_hash(struct sock *sk) return 0; } WARN_ON(!sk_unhashed(sk)); + + if (unlikely(inet_csk(sk)->unhashed_state && + inet_csk(sk)->unhashed_state != TCP_LISTEN)) + return -EINVAL; + ilb2 = inet_lhash2_bucket_sk(hashinfo, sk); spin_lock(&ilb2->lock); @@ -821,6 +826,9 @@ void inet_unhash(struct sock *sk) return; sock_rps_delete_flow(sk); + + inet_csk(sk)->unhashed_state = sk->sk_state; + if (sk->sk_state == TCP_LISTEN) { struct inet_listen_hashbucket *ilb2; @@ -1050,6 +1058,9 @@ int __inet_hash_connect(struct inet_timewait_death_row *death_row, int step, l3mdev; u32 index; + if (unlikely(inet_csk(sk)->unhashed_state == TCP_LISTEN)) + return -EINVAL; + if (port) { local_bh_disable(); ret = check_established(death_row, sk, port, NULL, false, diff --git a/net/ipv4/inet_timewait_sock.c b/net/ipv4/inet_timewait_sock.c index 8997cc9db752..aa6b25210ce1 100644 --- a/net/ipv4/inet_timewait_sock.c +++ b/net/ipv4/inet_timewait_sock.c @@ -111,11 +111,13 @@ void inet_twsk_hashdance_schedule(struct inet_timewait_sock *tw, struct inet_hashinfo *hashinfo, int timeo) { - const struct inet_sock *inet = inet_sk(sk); - const struct inet_connection_sock *icsk = inet_csk(sk); struct inet_ehash_bucket *ehead = inet_ehash_bucket(hashinfo, sk->sk_hash); + struct inet_connection_sock *icsk = inet_csk(sk); spinlock_t *lock = inet_ehash_lockp(hashinfo, sk->sk_hash); struct inet_bind_hashbucket *bhead, *bhead2; + const struct inet_sock *inet = inet_sk(sk); + + icsk->unhashed_state = sk->sk_state; /* Step 1: Put TW into bind hash. Original socket stays there too. Note, that any socket with inet->num != 0 MUST be bound in diff --git a/net/ipv4/ip_fragment.c b/net/ipv4/ip_fragment.c index 03e19a29df05..ef7fd61284a3 100644 --- a/net/ipv4/ip_fragment.c +++ b/net/ipv4/ip_fragment.c @@ -378,8 +378,9 @@ static int ip_frag_queue(struct ipq *qp, struct sk_buff *skb, int *refs) err = -EINVAL; goto err; } + if (err == IPFRAG_OVERLAP) + __IP_INC_STATS(net, IPSTATS_MIB_REASM_OVERLAPS); err = -EINVAL; - __IP_INC_STATS(net, IPSTATS_MIB_REASM_OVERLAPS); discard_qp: inet_frag_kill(&qp->q, refs); __IP_INC_STATS(net, IPSTATS_MIB_REASMFAILS); diff --git a/net/ipv4/ip_output.c b/net/ipv4/ip_output.c index a76910e1d117..536335a1bf44 100644 --- a/net/ipv4/ip_output.c +++ b/net/ipv4/ip_output.c @@ -1151,16 +1151,16 @@ static int __ip_append_data(struct sock *sk, */ skb->ip_summed = csummode; skb->csum = 0; - skb_reserve(skb, hh_len); + skb_reserve(skb, hh_len + exthdrlen); /* * Find where to start putting bytes. */ - data = skb_put(skb, fraglen + exthdrlen - pagedlen); - skb_set_network_header(skb, exthdrlen); + data = skb_put(skb, fraglen - pagedlen); + skb_reset_network_header(skb); skb->transport_header = (skb->network_header + fragheaderlen); - data += fragheaderlen + exthdrlen; + data += fragheaderlen; if (fraggap) { skb->csum = skb_copy_and_csum_bits( diff --git a/net/ipv4/ip_tunnel.c b/net/ipv4/ip_tunnel.c index 41867ac981b6..3b3b51b82da4 100644 --- a/net/ipv4/ip_tunnel.c +++ b/net/ipv4/ip_tunnel.c @@ -604,6 +604,7 @@ void ip_md_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, if (ip_tunnel_encap(skb, &tun_info->encap, &proto, &fl4) < 0) goto tx_error; + inner_iph = (const struct iphdr *)skb_inner_network_header(skb); use_cache = ip_tunnel_dst_cache_usable(skb, tun_info); if (use_cache) @@ -746,6 +747,8 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, } tos = tnl_params->tos; + df = tnl_params->frag_off; + ttl = tnl_params->ttl; if (tos & 0x1) { tos &= ~0x1; if (payload_protocol == htons(ETH_P_IP)) { @@ -764,6 +767,7 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, if (ip_tunnel_encap(skb, &tunnel->encap, &protocol, &fl4) < 0) goto tx_error; + inner_iph = (const struct iphdr *)skb_inner_network_header(skb); if (connected && md) { use_cache = ip_tunnel_dst_cache_usable(skb, tun_info); @@ -796,7 +800,6 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, goto tx_error; } - df = tnl_params->frag_off; if (payload_protocol == htons(ETH_P_IP) && !tunnel->ignore_df) df |= (inner_iph->frag_off & htons(IP_DF)); @@ -816,7 +819,6 @@ void ip_tunnel_xmit(struct sk_buff *skb, struct net_device *dev, } tos = ip_tunnel_ecn_encap(tos, inner_iph, skb); - ttl = tnl_params->ttl; if (ttl == 0) { if (payload_protocol == htons(ETH_P_IP)) ttl = inner_iph->ttl; diff --git a/net/ipv4/netfilter/arp_tables.c b/net/ipv4/netfilter/arp_tables.c index 0ea513bf77fb..197d1dfa07d6 100644 --- a/net/ipv4/netfilter/arp_tables.c +++ b/net/ipv4/netfilter/arp_tables.c @@ -372,11 +372,12 @@ static int mark_source_chains(const struct xt_table_info *newinfo, e->counters.pcnt = pos; pos += size; } else { - int newpos = t->verdict; + int newpos; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && - newpos >= 0) { + t->verdict >= 0) { + newpos = t->verdict; /* This a jump; chase it. */ if (!xt_find_jump_offset(offsets, newpos, newinfo->number)) diff --git a/net/ipv4/netfilter/ip_tables.c b/net/ipv4/netfilter/ip_tables.c index ca8ff0ae6cdb..b7749048e146 100644 --- a/net/ipv4/netfilter/ip_tables.c +++ b/net/ipv4/netfilter/ip_tables.c @@ -422,11 +422,12 @@ mark_source_chains(const struct xt_table_info *newinfo, e->counters.pcnt = pos; pos += size; } else { - int newpos = t->verdict; + int newpos; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && - newpos >= 0) { + t->verdict >= 0) { + newpos = t->verdict; /* This a jump; chase it. */ if (!xt_find_jump_offset(offsets, newpos, newinfo->number)) diff --git a/net/ipv4/netfilter/nf_reject_ipv4.c b/net/ipv4/netfilter/nf_reject_ipv4.c index 7cb33af671e2..4082fa184af8 100644 --- a/net/ipv4/netfilter/nf_reject_ipv4.c +++ b/net/ipv4/netfilter/nf_reject_ipv4.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -336,7 +337,18 @@ void nf_send_reset(struct net *net, struct sock *sk, struct sk_buff *oldskb, dev_queue_xmit(nskb); } else #endif + { + local_bh_disable(); + if (nf_dev_xmit_recursion()) { + local_bh_enable(); + goto free_nskb; + } + + nf_dev_xmit_recursion_inc(); ip_local_out(net, nskb->sk, nskb); + nf_dev_xmit_recursion_dec(); + local_bh_enable(); + } return; diff --git a/net/ipv4/raw.c b/net/ipv4/raw.c index 5735ae7cba01..076fb2226a0f 100644 --- a/net/ipv4/raw.c +++ b/net/ipv4/raw.c @@ -184,18 +184,19 @@ static int raw_v4_input(struct net *net, struct sk_buff *skb, iph->saddr, iph->daddr, dif, sdif)) continue; - if (atomic_read(&sk->sk_rmem_alloc) >= - READ_ONCE(sk->sk_rcvbuf)) { - sk_drops_inc(sk); - continue; - } - delivered = 1; if ((iph->protocol != IPPROTO_ICMP || !icmp_filter(sk, skb)) && ip_mc_sf_allow(sk, iph->daddr, iph->saddr, skb->dev->ifindex, sdif)) { - struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC); + struct sk_buff *clone; + + if (atomic_read(&sk->sk_rmem_alloc) >= + READ_ONCE(sk->sk_rcvbuf)) { + sk_drops_inc(sk); + continue; + } + clone = skb_clone(skb, GFP_ATOMIC); /* Not releasing hash table! */ if (clone) raw_rcv(sk, clone); diff --git a/net/ipv4/route.c b/net/ipv4/route.c index e6276896f3ad..ef1a3395be44 100644 --- a/net/ipv4/route.c +++ b/net/ipv4/route.c @@ -573,6 +573,17 @@ static void ip_rt_build_flow_key(struct flowi4 *fl4, const struct sock *sk, static DEFINE_SPINLOCK(fnhe_lock); +/* Other CPUs may still be using @rt, so don't dst_dev_put() it. + * rt_flush_dev() handles it if its device is unregistered. + * Marking it dead makes ipv4_dst_check() fail for users that cached it. + */ +static void fnhe_retire_route(struct rtable *rt) +{ + WRITE_ONCE(rt->dst.obsolete, DST_OBSOLETE_DEAD); + rt_add_uncached_list(rt); + dst_release(&rt->dst); +} + static void fnhe_flush_routes(struct fib_nh_exception *fnhe) { struct rtable *rt; @@ -580,14 +591,12 @@ static void fnhe_flush_routes(struct fib_nh_exception *fnhe) rt = rcu_dereference(fnhe->fnhe_rth_input); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_input, NULL); - dst_dev_put(&rt->dst); - dst_release(&rt->dst); + fnhe_retire_route(rt); } rt = rcu_dereference(fnhe->fnhe_rth_output); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_output, NULL); - dst_dev_put(&rt->dst); - dst_release(&rt->dst); + fnhe_retire_route(rt); } } @@ -1502,10 +1511,8 @@ static bool rt_bind_exception(struct rtable *rt, struct fib_nh_exception *fnhe, if (do_cache) { dst_hold(&rt->dst); rcu_assign_pointer(*porig, rt); - if (orig) { - dst_dev_put(&orig->dst); - dst_release(&orig->dst); - } + if (orig) + fnhe_retire_route(orig); ret = true; } @@ -2485,6 +2492,8 @@ ip_route_input_slow(struct sk_buff *skb, __be32 daddr, __be32 saddr, if (unlikely(!rt_cache_route(nhc, rth))) rt_add_uncached_list(rth); + } else { + rt_add_uncached_list(rth); } skb_dst_set(skb, &rth->dst); reason = SKB_NOT_DROPPED_YET; diff --git a/net/ipv4/tcp.c b/net/ipv4/tcp.c index aa860cbd3a44..4d41f16bd610 100644 --- a/net/ipv4/tcp.c +++ b/net/ipv4/tcp.c @@ -472,7 +472,7 @@ void tcp_init_sock(struct sock *sk) * initialization of these values. */ tp->snd_ssthresh = TCP_INFINITE_SSTHRESH; - tp->snd_cwnd_clamp = ~0; + tp->snd_cwnd_clamp = TCP_MAX_SND_CWND; tp->mss_cache = TCP_MSS_DEFAULT; tp->reordering = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reordering); @@ -3426,6 +3426,7 @@ int tcp_disconnect(struct sock *sk, int flags) tcp_accecn_init_counters(tp); tp->prev_ecnfield = 0; tp->accecn_opt_tstamp = 0; + tp->pkts_acked_ewma = 0; if (icsk->icsk_ca_initialized && icsk->icsk_ca_ops->release) icsk->icsk_ca_ops->release(sk); memset(icsk->icsk_ca_priv, 0, sizeof(icsk->icsk_ca_priv)); @@ -3476,6 +3477,7 @@ int tcp_disconnect(struct sock *sk, int flags) tp->rx_opt.dsack = 0; tp->rx_opt.num_sacks = 0; tp->rcv_ooopack = 0; + tp->rcv_collapse_credit = 0; /* Clean up fastopen related fields */ @@ -4963,7 +4965,8 @@ tcp_inbound_md5_hash(const struct sock *sk, const struct sk_buff *skb, const void *saddr, const void *daddr, int family, int l3index, const __u8 *hash_location) { - return SKB_NOT_DROPPED_YET; + NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMD5UNEXPECTED); + return SKB_DROP_REASON_TCP_MD5UNEXPECTED; } #endif @@ -5195,9 +5198,13 @@ static void __init tcp_struct_check(void) CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_read_rx, snd_ssthresh); /* TX read-write hotpath cache lines */ - CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, segs_out); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, data_segs_out); + CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, delivered); + CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, delivered_ce); + CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, bytes_acked); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, bytes_sent); + CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, first_tx_mstamp); + CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, delivered_mstamp); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, snd_sml); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, chrono_start); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_tx, chrono_stat); @@ -5223,18 +5230,17 @@ static void __init tcp_struct_check(void) CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, srtt_us); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, packets_out); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, snd_up); - CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, delivered); - CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, delivered_ce); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, received_ce); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, received_ecn_bytes); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, app_limited); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, rcv_wnd); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, rcv_tstamp); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, rx_opt); + CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, segs_in); + CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_txrx, segs_out); /* RX read-write hotpath cache lines */ CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, bytes_received); - CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, segs_in); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, data_segs_in); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcv_wup); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, max_packets_out); @@ -5243,9 +5249,8 @@ static void __init tcp_struct_check(void) CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rate_interval_us); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcv_rtt_last_tsecr); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, delivered_ecn_bytes); - CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, first_tx_mstamp); - CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, delivered_mstamp); - CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, bytes_acked); + CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, pkts_acked_ewma); + CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcv_collapse_credit); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcv_rtt_est); CACHELINE_ASSERT_GROUP_MEMBER(struct tcp_sock, tcp_sock_write_rx, rcvq_space); } diff --git a/net/ipv4/tcp_fastopen.c b/net/ipv4/tcp_fastopen.c index dbd97df1b442..1b0f367f9dfc 100644 --- a/net/ipv4/tcp_fastopen.c +++ b/net/ipv4/tcp_fastopen.c @@ -456,6 +456,8 @@ bool tcp_fastopen_defer_connect(struct sock *sk, int *err) if (tp->fastopen_connect && !tp->fastopen_req) { if (tcp_fastopen_cookie_check(sk, &mss, &cookie)) { + WRITE_ONCE(tp->snd_una, tp->write_seq); + WRITE_ONCE(tp->snd_nxt, tp->write_seq); inet_set_bit(DEFER_CONNECT, sk); return true; } diff --git a/net/ipv4/tcp_input.c b/net/ipv4/tcp_input.c index 28db1353445b..41db56f936f0 100644 --- a/net/ipv4/tcp_input.c +++ b/net/ipv4/tcp_input.c @@ -107,7 +107,8 @@ int sysctl_tcp_max_orphans __read_mostly = NR_FILE; #define FLAG_TS_PROGRESS 0x40000 /* Positive timestamp delta */ #define FLAG_ACKED (FLAG_DATA_ACKED|FLAG_SYN_ACKED) -#define FLAG_NOT_DUP (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED) +#define FLAG_NOT_DUP (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED| \ + FLAG_SND_UNA_ADVANCED) #define FLAG_CA_ALERT (FLAG_DATA_SACKED|FLAG_ECE|FLAG_DSACKING_ACK) #define FLAG_FORWARD_PROGRESS (FLAG_ACKED|FLAG_DATA_SACKED) @@ -488,6 +489,10 @@ static void tcp_count_delivered(struct tcp_sock *tp, u32 delivered, tcp_count_delivered_ce(tp, delivered); } +#define PKTS_ACKED_WEIGHT 6 +#define PKTS_ACKED_PREC 6 +#define ACK_COMP_THRESH 4 + /* Returns the ECN CE delta */ static u32 __tcp_accecn_process(struct sock *sk, const struct sk_buff *skb, u32 delivered_pkts, u32 delivered_bytes, @@ -499,6 +504,7 @@ static u32 __tcp_accecn_process(struct sock *sk, const struct sk_buff *skb, u32 delta, safe_delta, d_ceb; bool opt_deltas_valid; u32 corrected_ace; + u32 ewma; /* Reordered ACK or uncertain due to lack of data to send and ts */ if (!(flag & (FLAG_FORWARD_PROGRESS | FLAG_TS_PROGRESS))) @@ -507,6 +513,18 @@ static u32 __tcp_accecn_process(struct sock *sk, const struct sk_buff *skb, opt_deltas_valid = tcp_accecn_process_option(tp, skb, delivered_bytes, flag); + if (delivered_pkts) { + if (!tp->pkts_acked_ewma) { + ewma = delivered_pkts << PKTS_ACKED_PREC; + } else { + ewma = tp->pkts_acked_ewma; + ewma = (((ewma << PKTS_ACKED_WEIGHT) - ewma) + + (delivered_pkts << PKTS_ACKED_PREC)) >> + PKTS_ACKED_WEIGHT; + } + tp->pkts_acked_ewma = min_t(u32, ewma, 0xFFFFU); + } + if (!(flag & FLAG_SLOWPATH)) { /* AccECN counter might overflow on large ACKs */ if (delivered_pkts <= TCP_ACCECN_CEP_ACE_MASK) @@ -555,7 +573,8 @@ static u32 __tcp_accecn_process(struct sock *sk, const struct sk_buff *skb, if (d_ceb < safe_delta * tp->mss_cache >> TCP_ACCECN_SAFETY_SHIFT) return delta; - } + } else if (tp->pkts_acked_ewma > (ACK_COMP_THRESH << PKTS_ACKED_PREC)) + return delta; return safe_delta; } @@ -3741,11 +3760,11 @@ static int tcp_ack_update_window(struct sock *sk, const struct sk_buff *skb, u32 nwin <<= tp->rx_opt.snd_wscale; if (tcp_may_update_window(tp, ack, ack_seq, nwin)) { - flag |= FLAG_WIN_UPDATE; tcp_update_wl(tp, ack_seq); if (tp->snd_wnd != nwin) { tp->snd_wnd = nwin; + flag |= FLAG_WIN_UPDATE; /* Note, it is the only place, where * fast path is recovered for sending TCP. @@ -4093,7 +4112,6 @@ static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag) */ tcp_update_wl(tp, ack_seq); tcp_snd_una_update(tp, ack); - flag |= FLAG_WIN_UPDATE; NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPHPACKS); } else { @@ -5045,6 +5063,10 @@ static bool tcp_try_coalesce(struct sock *sk, if (!tcp_skb_can_collapse_rx(to, from)) return false; + /* Nothing follows a FIN. */ + if (unlikely(TCP_SKB_CB(to)->tcp_flags & TCPHDR_FIN)) + return false; + if (!skb_try_coalesce(to, from, fragstolen, &delta)) return false; @@ -5166,6 +5188,20 @@ static int tcp_try_rmem_schedule(struct sock *sk, const struct sk_buff *skb, return 0; } +/* Credit the memory added to the receive queues since @rmem was sampled + * toward the next allowed collapse. Saturate at sk_rcvbuf, not at the goal + * checked in tcp_prune_queue(): sk_rcvbuf (and the goal) can grow later, + * for instance in tcp_clamp_window(). + */ +static void tcp_collapse_credit_add(struct sock *sk, int rmem) +{ + struct tcp_sock *tp = tcp_sk(sk); + int delta = atomic_read(&sk->sk_rmem_alloc) - rmem; + + if (delta > 0 && tp->rcv_collapse_credit < (u32)sk->sk_rcvbuf) + tp->rcv_collapse_credit += delta; +} + static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); @@ -5173,6 +5209,7 @@ static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb) struct sk_buff *skb1; u32 seq, end_seq; bool fragstolen; + int rmem; tcp_save_lrcv_flowlabel(sk, skb); tcp_data_ecn_check(sk, skb); @@ -5183,6 +5220,8 @@ static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb) tcp_drop_reason(sk, skb, SKB_DROP_REASON_PROTO_MEM); return; } + /* Sampled after tcp_try_rmem_schedule(), which can prune. */ + rmem = atomic_read(&sk->sk_rmem_alloc); tcp_measure_rcv_mss(sk, skb); /* Disable header prediction. */ @@ -5312,6 +5351,10 @@ static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb) skb_condense(skb); skb_set_owner_r(skb, sk); } + /* Net growth: coalescing can charge nothing, and covered skbs + * were freed. + */ + tcp_collapse_credit_add(sk, rmem); /* do not grow rcvbuf for not-yet-accepted or orphaned sockets. */ if (sk->sk_socket) tcp_rcvbuf_grow(sk, tp->rcvq_space.space); @@ -5320,8 +5363,9 @@ static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb) static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb, bool *fragstolen) { - int eaten; + int rmem = atomic_read(&sk->sk_rmem_alloc); struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue); + int eaten; eaten = (tail && tcp_try_coalesce(sk, tail, @@ -5331,6 +5375,7 @@ static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb, tcp_add_receive_queue(sk, skb); skb_set_owner_r(skb, sk); } + tcp_collapse_credit_add(sk, rmem); return eaten; } @@ -5646,6 +5691,10 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root, __skb_queue_before(list, skb, nskb); else __skb_queue_tail(&tmp, nskb); /* defer rbtree insertion */ + /* nskb is charged before the skbs it replaces are freed. + * Make sure sk->sk_forward_alloc can not become negative. + */ + sk_forced_mem_schedule(sk, nskb->truesize); skb_set_owner_r(nskb, sk); mptcp_skb_ext_move(nskb, skb); @@ -5814,18 +5863,28 @@ static int tcp_prune_queue(struct sock *sk, const struct sk_buff *in_skb) if (tcp_can_ingest(sk, in_skb)) return 0; - tcp_collapse_ofo_queue(sk); - if (!skb_queue_empty(&sk->sk_receive_queue)) - tcp_collapse(sk, &sk->sk_receive_queue, NULL, - skb_peek(&sk->sk_receive_queue), - NULL, - tp->copied_seq, tp->rcv_nxt); + /* Collapsing walks both queues and is expensive, and can free + * almost nothing. Require at least 1/8 of sk_rcvbuf of new memory + * in the receive queues since the previous collapse, otherwise + * a stream of segments could trigger one collapse per packet. + */ + if (tp->rcv_collapse_credit >= (u32)sk->sk_rcvbuf >> 3) { + tp->rcv_collapse_credit = 0; - if (tcp_can_ingest(sk, in_skb)) - return 0; + tcp_collapse_ofo_queue(sk); + if (!skb_queue_empty(&sk->sk_receive_queue)) + tcp_collapse(sk, &sk->sk_receive_queue, NULL, + skb_peek(&sk->sk_receive_queue), + NULL, + tp->copied_seq, tp->rcv_nxt); - /* Collapsing did not help, destructive actions follow. - * This must not ever occur. */ + if (tcp_can_ingest(sk, in_skb)) + return 0; + } + + /* Collapsing did not help (or was not allowed), + * destructive actions follow. + */ tcp_prune_ofo_queue(sk, in_skb); @@ -6993,6 +7052,15 @@ tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb) goto discard; case TCP_SYN_SENT: + /* We sent nothing yet, so no segment belongs to this connection. + * Send no RST: it would be built from this socket, whose TCP-AO + * keys are not set up either. + */ + if (unlikely(inet_test_bit(DEFER_CONNECT, sk))) { + SKB_DR_SET(reason, NOT_SPECIFIED); + goto discard; + } + tp->rx_opt.saw_tstamp = 0; tcp_mstamp_refresh(tp); queued = tcp_rcv_synsent_state_process(sk, skb, th); diff --git a/net/ipv4/tcp_ipv4.c b/net/ipv4/tcp_ipv4.c index b5517f9af546..09ef6012ab14 100644 --- a/net/ipv4/tcp_ipv4.c +++ b/net/ipv4/tcp_ipv4.c @@ -546,7 +546,7 @@ int tcp_v4_err(struct sk_buff *skb, u32 info) if (!(type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)) __NET_INC_STATS(net, LINUX_MIB_LOCKDROPPEDICMPS); } - if (sk->sk_state == TCP_CLOSE) + if (sk->sk_state == TCP_CLOSE || inet_test_bit(DEFER_CONNECT, sk)) goto out; if (static_branch_unlikely(&ip4_min_ttl)) { @@ -2084,6 +2084,8 @@ bool tcp_add_backlog(struct sock *sk, struct sk_buff *skb, ((TCP_SKB_CB(tail)->tcp_flags ^ TCP_SKB_CB(skb)->tcp_flags) & (TCPHDR_ECE | TCPHDR_CWR | TCPHDR_AE)) || + /* Nothing follows a FIN, see tcp_try_coalesce() */ + (TCP_SKB_CB(tail)->tcp_flags & TCPHDR_FIN) || !tcp_skb_can_collapse_rx(tail, skb) || thtail->doff != th->doff || memcmp(thtail + 1, th + 1, hdrlen - sizeof(*th)) || @@ -3700,6 +3702,7 @@ static int __net_init tcp_sk_init(struct net *net) static void __net_exit tcp_sk_exit_batch(struct list_head *net_exit_list) { + bool synced = false; struct net *net; /* make sure concurrent calls to tcp_sk_exit_batch from net_cleanup_work @@ -3714,9 +3717,27 @@ static void __net_exit tcp_sk_exit_batch(struct list_head *net_exit_list) tcp_twsk_purge(net_exit_list); + /* inet_twsk_kill() unhashes a twsk before it is done with ehash + * and bhash, and before it drops its tw_refcount reference, + * so tcp_twsk_purge() can miss it. Such callers run with BH + * disabled: wait for them before freeing a private ehash. + */ + list_for_each_entry(net, net_exit_list, exit_list) { + if (net->ipv4.tcp_death_row.hashinfo->pernet) { + synchronize_net(); + synced = true; + break; + } + } + list_for_each_entry(net, net_exit_list, exit_list) { inet_pernet_hashinfo_free(net->ipv4.tcp_death_row.hashinfo); - WARN_ON_ONCE(!refcount_dec_and_test(&net->ipv4.tcp_death_row.tw_refcount)); + /* Without a grace period, a concurrent inet_twsk_kill() might + * still hold a tw_refcount reference. Let it drop it: struct net + * is freed by a later cleanup_net(), after an RCU grace period. + */ + if (!refcount_dec_if_one(&net->ipv4.tcp_death_row.tw_refcount)) + WARN_ON_ONCE(synced); tcp_fastopen_ctx_destroy(net); } diff --git a/net/ipv4/tcp_metrics.c b/net/ipv4/tcp_metrics.c index 276127902f15..5a83f09cdbd7 100644 --- a/net/ipv4/tcp_metrics.c +++ b/net/ipv4/tcp_metrics.c @@ -495,7 +495,8 @@ void tcp_init_metrics(struct sock *sk) } if (tcp_metric_locked(tm, TCP_METRIC_CWND)) - tp->snd_cwnd_clamp = tcp_metric_get(tm, TCP_METRIC_CWND); + tp->snd_cwnd_clamp = min(tcp_metric_get(tm, TCP_METRIC_CWND), + TCP_MAX_SND_CWND); val = READ_ONCE(net->ipv4.sysctl_tcp_no_ssthresh_metrics_save) ? 0 : tcp_metric_get(tm, TCP_METRIC_SSTHRESH); diff --git a/net/ipv4/tcp_minisocks.c b/net/ipv4/tcp_minisocks.c index ebcd78ad13ef..accd276830e2 100644 --- a/net/ipv4/tcp_minisocks.c +++ b/net/ipv4/tcp_minisocks.c @@ -980,7 +980,7 @@ struct sock *tcp_check_req(struct sock *sk, struct sk_buff *skb, tcp_reset(sk, skb); } if (!fastopen) { - bool unlinked = inet_csk_reqsk_queue_drop(sk, req); + bool unlinked = inet_csk_reqsk_queue_drop(req->rsk_listener, req); if (unlinked) __NET_INC_STATS(sock_net(sk), LINUX_MIB_EMBRYONICRSTS); diff --git a/net/ipv4/udp.c b/net/ipv4/udp.c index a7ae0d098f2c..62cdc8d8f9fb 100644 --- a/net/ipv4/udp.c +++ b/net/ipv4/udp.c @@ -2933,8 +2933,11 @@ enum skb_drop_reason udp_v4_early_demux(struct sk_buff *skb) skb->destructor = sock_pfree; dst = rcu_dereference(sk->sk_rx_dst); - if (dst) + /* A dual-stack socket can cache an IPv6 dst. */ + if (dst && dst->ops->family == AF_INET) dst = dst_check(dst, 0); + else + dst = NULL; if (dst) { u32 itag = 0; diff --git a/net/ipv4/udp_offload.c b/net/ipv4/udp_offload.c index 4f7ae02df8d3..d313661d6942 100644 --- a/net/ipv4/udp_offload.c +++ b/net/ipv4/udp_offload.c @@ -515,9 +515,14 @@ struct sk_buff *__udp_gso_segment(struct sk_buff *gso_skb, } if (skb_shinfo(gso_skb)->gso_type & SKB_GSO_FRAGLIST) { - /* Detect modified geometry and pass those to skb_segment. */ + /* Detect modified geometry and pass those to skb_segment. + * SKB_GSO_UDP_L4 is used by both IPv4 and IPv6: also make sure + * the frag_list skbs still have the IP family we segment for, + * as their network headers are not rebuilt. + */ if ((skb_pagelen(gso_skb) - sizeof(*uh) == skb_shinfo(gso_skb)->gso_size) && - !(skb_shinfo(gso_skb)->gso_type & SKB_GSO_DODGY)) + !(skb_shinfo(gso_skb)->gso_type & SKB_GSO_DODGY) && + ip_hdr(skb_shinfo(gso_skb)->frag_list)->version == (is_ipv6 ? 6 : 4)) return __udp_gso_segment_list(gso_skb, features, is_ipv6); ret = __skb_linearize(gso_skb); @@ -754,6 +759,7 @@ static struct sk_buff *udp_gro_receive_segment(struct list_head *head, pp = p; } else { if (NAPI_GRO_CB(skb)->is_flist) { + skb_gro_frag0_invalidate(skb); if (!pskb_may_pull(skb, skb_gro_offset(skb))) { NAPI_GRO_CB(skb)->flush = 1; return NULL; diff --git a/net/ipv4/udp_tunnel_core.c b/net/ipv4/udp_tunnel_core.c index 54386e06a813..4f7e7d24594a 100644 --- a/net/ipv4/udp_tunnel_core.c +++ b/net/ipv4/udp_tunnel_core.c @@ -62,10 +62,10 @@ EXPORT_SYMBOL(udp_sock_create4); static bool sk_saddr_any(struct sock *sk) { #if IS_ENABLED(CONFIG_IPV6) - return ipv6_addr_any(&sk->sk_v6_rcv_saddr); -#else - return !sk->sk_rcv_saddr; + if (sk->sk_family == AF_INET6) + return ipv6_addr_any(&sk->sk_v6_rcv_saddr); #endif + return !sk->sk_rcv_saddr; } void setup_udp_tunnel_sock(struct net *net, struct socket *sock, diff --git a/net/ipv6/calipso.c b/net/ipv6/calipso.c index 5775ab1c39c0..ae0cf6520f21 100644 --- a/net/ipv6/calipso.c +++ b/net/ipv6/calipso.c @@ -1220,7 +1220,7 @@ static int calipso_req_setattr(struct request_sock *req, if (IS_ERR(new)) return PTR_ERR(new); - txopts = ipv6_renew_options(sk, req_inet->ipv6_opt, IPV6_HOPOPTS, new); + txopts = ipv6_renew_options(NULL, req_inet->ipv6_opt, IPV6_HOPOPTS, new); kfree(new); @@ -1228,10 +1228,8 @@ static int calipso_req_setattr(struct request_sock *req, return PTR_ERR(txopts); txopts = xchg(&req_inet->ipv6_opt, txopts); - if (txopts) { - atomic_sub(txopts->tot_len, &sk->sk_omem_alloc); + if (txopts) txopt_put(txopts); - } return 0; } @@ -1261,14 +1259,12 @@ static void calipso_req_delattr(struct request_sock *req) if (calipso_opt_del(req_inet->ipv6_opt->hopopt, &new)) return; /* Nothing to do */ - txopts = ipv6_renew_options(sk, req_inet->ipv6_opt, IPV6_HOPOPTS, new); + txopts = ipv6_renew_options(NULL, req_inet->ipv6_opt, IPV6_HOPOPTS, new); if (!IS_ERR(txopts)) { txopts = xchg(&req_inet->ipv6_opt, txopts); - if (txopts) { - atomic_sub(txopts->tot_len, &sk->sk_omem_alloc); + if (txopts) txopt_put(txopts); - } } kfree(new); } diff --git a/net/ipv6/esp6_offload.c b/net/ipv6/esp6_offload.c index 22895521a57d..ca947cb94fb7 100644 --- a/net/ipv6/esp6_offload.c +++ b/net/ipv6/esp6_offload.c @@ -64,6 +64,7 @@ static struct sk_buff *esp6_gro_receive(struct list_head *head, if (NAPI_GRO_CB(skb)->proto == IPPROTO_UDP) encap_type = UDP_ENCAP_ESPINUDP; + skb_gro_frag0_invalidate(skb); if (!pskb_pull(skb, offset)) return NULL; diff --git a/net/ipv6/exthdrs.c b/net/ipv6/exthdrs.c index 38f15948237c..f680df587769 100644 --- a/net/ipv6/exthdrs.c +++ b/net/ipv6/exthdrs.c @@ -1284,7 +1284,7 @@ static void ipv6_renew_option(int renewtype, * not copied into the new set of options. * * The new set of options is allocated from the socket option memory - * buffer of @sk. + * buffer of @sk, or with kmalloc() if @sk is NULL. */ struct ipv6_txoptions * ipv6_renew_options(struct sock *sk, struct ipv6_txoptions *opt, @@ -1312,7 +1312,8 @@ ipv6_renew_options(struct sock *sk, struct ipv6_txoptions *opt, return NULL; tot_len += sizeof(*opt2); - opt2 = sock_kmalloc(sk, tot_len, GFP_ATOMIC); + opt2 = sk ? sock_kmalloc(sk, tot_len, GFP_ATOMIC) : + kmalloc(tot_len, GFP_ATOMIC); if (!opt2) return ERR_PTR(-ENOBUFS); diff --git a/net/ipv6/exthdrs_core.c b/net/ipv6/exthdrs_core.c index 4a9748338cf4..764c694fb417 100644 --- a/net/ipv6/exthdrs_core.c +++ b/net/ipv6/exthdrs_core.c @@ -138,9 +138,6 @@ int ipv6_find_tlv(const struct sk_buff *skb, int offset, int type) int opttype = nh[offset]; int optlen; - if (opttype == type) - return offset; - switch (opttype) { case IPV6_TLV_PAD1: optlen = 1; @@ -153,6 +150,10 @@ int ipv6_find_tlv(const struct sk_buff *skb, int offset, int type) goto bad; break; } + /* Some callers read the option, so it must be in the header. */ + if (opttype == type) + return offset; + offset += optlen; len -= optlen; } diff --git a/net/ipv6/icmp.c b/net/ipv6/icmp.c index 9cf0557d0ed2..3164e7ddb629 100644 --- a/net/ipv6/icmp.c +++ b/net/ipv6/icmp.c @@ -339,7 +339,12 @@ static void mip6_addr_swap(struct sk_buff *skb, const struct inet6_skb_parm *opt if (likely(off >= 0)) { hao = (struct ipv6_destopt_hao *) (skb_network_header(skb) + off); - swap(iph->saddr, hao->addr); + /* + * The header can have moved or changed after + * ipv6_dest_hao() checked the length. + */ + if (hao->length == 16) + swap(iph->saddr, hao->addr); } } } diff --git a/net/ipv6/ip6_fib.c b/net/ipv6/ip6_fib.c index 9fc2d2677b74..0ec46c65ee0b 100644 --- a/net/ipv6/ip6_fib.c +++ b/net/ipv6/ip6_fib.c @@ -89,6 +89,40 @@ static void fib6_walker_unlink(struct net *net, struct fib6_walker *w) write_unlock_bh(&net->ipv6.fib6_walker_lock); } +/* @old is leaving the tree. Walkers resting on it continue from @new, or + * climb to the parent node when there is no @new. Called with tb6_lock + * held. + */ +static void fib6_walkers_replace_leaf(struct net *net, struct fib6_info *old, + struct fib6_info *new) +{ + struct fib6_walker *w; + + read_lock(&net->ipv6.fib6_walker_lock); + FOR_WALKERS(net, w) { + if (w->state == FWS_C && w->leaf == old) { + pr_debug("walker %p adjusted by unlink of %p\n", w, old); + w->leaf = new; + w->skip_in_node = 0; + if (!new) + w->state = FWS_U; + } + } + read_unlock(&net->ipv6.fib6_walker_lock); +} + +/* @rt is removed from its node: walkers resting on it continue from the + * next route of the node. + */ +static void fib6_walkers_skip_rt(struct net *net, struct fib6_info *rt) +{ + struct fib6_info *next; + + next = rcu_dereference_protected(rt->fib6_next, + lockdep_is_held(&rt->fib6_table->tb6_lock)); + fib6_walkers_replace_leaf(net, rt, next); +} + static int fib6_new_sernum(struct net *net) { int new, old = atomic_read(&net->ipv6.fib6_sernum); @@ -1218,9 +1252,7 @@ static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt, fib6_nsiblings++; } BUG_ON(fib6_nsiblings != rt->fib6_nsiblings); - rcu_read_lock(); rt6_multipath_rebalance(temp_sibling); - rcu_read_unlock(); } /* @@ -1264,9 +1296,7 @@ static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt, sibling->fib6_nsiblings - 1); WRITE_ONCE(rt->fib6_nsiblings, 0); list_del_rcu(&rt->fib6_siblings); - rcu_read_lock(); rt6_multipath_rebalance(next_sibling); - rcu_read_unlock(); return err; } } @@ -1306,6 +1336,7 @@ static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt, rcu_assign_pointer(rt->fib6_node, fn); rt->fib6_next = iter->fib6_next; rcu_assign_pointer(*ins, rt); + fib6_walkers_replace_leaf(info->nl_net, iter, rt); if (!info->skip_notify) inet6_rt_notify(RTM_NEWROUTE, rt, info, NLM_F_REPLACE); if (!(fn->fn_flags & RTN_RTINFO)) { @@ -1327,6 +1358,7 @@ static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt, if (iter->fib6_metric > rt->fib6_metric) break; if (rt6_qualify_for_ecmp(iter)) { + fib6_walkers_skip_rt(info->nl_net, iter); *ins = iter->fib6_next; iter->fib6_node = NULL; list_add(&iter->purge_link, purge_list); @@ -1967,7 +1999,6 @@ static void fib6_del_route(struct fib6_table *table, struct fib6_node *fn, struct fib6_info __rcu **rtp, struct nl_info *info) { struct fib6_info *leaf, *replace_rt = NULL; - struct fib6_walker *w; struct fib6_info *rt = rcu_dereference_protected(*rtp, lockdep_is_held(&table->tb6_lock)); struct net *net = info->nl_net; @@ -2018,18 +2049,7 @@ static void fib6_del_route(struct fib6_table *table, struct fib6_node *fn, rt6_multipath_rebalance(next_sibling); } - /* Adjust walkers */ - read_lock(&net->ipv6.fib6_walker_lock); - FOR_WALKERS(net, w) { - if (w->state == FWS_C && w->leaf == rt) { - pr_debug("walker %p adjusted by delroute\n", w); - w->leaf = rcu_dereference_protected(rt->fib6_next, - lockdep_is_held(&table->tb6_lock)); - if (!w->leaf) - w->state = FWS_U; - } - } - read_unlock(&net->ipv6.fib6_walker_lock); + fib6_walkers_skip_rt(net, rt); /* If it was last route, call fib6_repair_tree() to: * 1. For root node, put back null_entry as how the table was created. diff --git a/net/ipv6/ip6_output.c b/net/ipv6/ip6_output.c index 7f17e700736a..9abbf9129e12 100644 --- a/net/ipv6/ip6_output.c +++ b/net/ipv6/ip6_output.c @@ -1287,7 +1287,7 @@ EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow); * @sk: socket which provides the dst cache and route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup - * @connected: whether @sk is connected or not + * @connected: whether the flow can use and update the socket dst cache * * This function performs a route lookup on the given flow with the * possibility of using the cached route in the socket if it is valid. @@ -1304,11 +1304,14 @@ struct dst_entry *ip6_sk_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst, bool connected) { - struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie); + struct dst_entry *dst; - dst = ip6_sk_dst_check(sk, dst, fl6); - if (dst) - return dst; + if (connected) { + dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie); + dst = ip6_sk_dst_check(sk, dst, fl6); + if (dst) + return dst; + } dst = ip6_dst_lookup_flow(sock_net(sk), sk, fl6, final_dst); if (connected && !IS_ERR(dst)) diff --git a/net/ipv6/ip6mr.c b/net/ipv6/ip6mr.c index f61035619cac..5a49fb4ae451 100644 --- a/net/ipv6/ip6mr.c +++ b/net/ipv6/ip6mr.c @@ -629,6 +629,13 @@ static netdev_tx_t reg_vif_xmit(struct sk_buff *skb, DEV_STATS_ADD(dev, tx_bytes, skb->len); DEV_STATS_INC(dev, tx_packets); rcu_read_lock(); + + /* skb->cb[] holds qdisc/tc state at this point, not IP6CB. + * ip6mr_cache_report() copies it to the report delivered to + * the mroute socket, where it is read as IP6CB. + */ + memset(IP6CB(skb), 0, sizeof(*IP6CB(skb))); + ip6mr_cache_report(mrt, skb, READ_ONCE(mrt->mroute_reg_vif_num), MRT6MSG_WHOLEPKT); rcu_read_unlock(); @@ -1580,12 +1587,20 @@ static void mroute_clean_tables(struct mr_table *mrt, int flags) } } -static int ip6mr_sk_init(struct mr_table *mrt, struct sock *sk) +static int ip6mr_sk_init(struct sock *sk) { - int err = 0; struct net *net = sock_net(sk); + struct mr_table *mrt; + int err = 0; rtnl_lock(); + mrt = __ip6mr_get_table(net, + raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT); + if (!mrt) { + err = -ENOENT; + goto out_unlock; + } + spin_lock(&mrt_lock); if (rtnl_dereference(mrt->mroute_sk)) { err = -EADDRINUSE; @@ -1601,6 +1616,7 @@ static int ip6mr_sk_init(struct mr_table *mrt, struct sock *sk) NETCONFA_MC_FORWARDING, NETCONFA_IFINDEX_ALL, net->ipv6.devconf_all); +out_unlock: rtnl_unlock(); return err; @@ -1699,7 +1715,7 @@ int ip6_mroute_setsockopt(struct sock *sk, int optname, sockptr_t optval, if (optlen < sizeof(int)) return -EINVAL; - return ip6mr_sk_init(mrt, sk); + return ip6mr_sk_init(sk); case MRT6_DONE: return ip6mr_sk_done(sk); @@ -1820,16 +1836,21 @@ int ip6_mroute_setsockopt(struct sock *sk, int optname, sockptr_t optval, /* "pim6reg%u" should not exceed 16 bytes (IFNAMSIZ) */ if (v != RT_TABLE_DEFAULT && v >= 100000000) return -EINVAL; - if (sk == rcu_access_pointer(mrt->mroute_sk)) - return -EBUSY; - rtnl_lock(); ret = 0; - mrt = ip6mr_new_table(net, v); - if (IS_ERR(mrt)) - ret = PTR_ERR(mrt); - else - raw6_sk(sk)->ip6mr_table = v; + mrt = __ip6mr_get_table(net, + raw6_sk(sk)->ip6mr_table ? : RT6_TABLE_DFLT); + if (!mrt) { + ret = -ENOENT; + } else if (sk == rtnl_dereference(mrt->mroute_sk)) { + ret = -EBUSY; + } else { + mrt = ip6mr_new_table(net, v); + if (IS_ERR(mrt)) + ret = PTR_ERR(mrt); + else + raw6_sk(sk)->ip6mr_table = v; + } rtnl_unlock(); return ret; } diff --git a/net/ipv6/mip6.c b/net/ipv6/mip6.c index 6a16a5bd0d91..961567972411 100644 --- a/net/ipv6/mip6.c +++ b/net/ipv6/mip6.c @@ -211,9 +211,16 @@ static int mip6_destopt_reject(struct xfrm_state *x, struct sk_buff *skb, if (likely(opt->dsthao)) { offset = ipv6_find_tlv(skb, opt->dsthao, IPV6_TLV_HAO); - if (likely(offset >= 0)) + if (likely(offset >= 0)) { hao = (struct ipv6_destopt_hao *) (skb_network_header(skb) + offset); + /* + * The header can have moved or changed after + * ipv6_dest_hao() checked the length. + */ + if (hao->length != 16) + hao = NULL; + } } stamp = skb_get_ktime(skb); diff --git a/net/ipv6/netfilter/ip6_tables.c b/net/ipv6/netfilter/ip6_tables.c index 22db263682bd..9353e9105f4a 100644 --- a/net/ipv6/netfilter/ip6_tables.c +++ b/net/ipv6/netfilter/ip6_tables.c @@ -440,11 +440,12 @@ mark_source_chains(const struct xt_table_info *newinfo, e->counters.pcnt = pos; pos += size; } else { - int newpos = t->verdict; + int newpos; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && - newpos >= 0) { + t->verdict >= 0) { + newpos = t->verdict; /* This a jump; chase it. */ if (!xt_find_jump_offset(offsets, newpos, newinfo->number)) diff --git a/net/ipv6/netfilter/nf_reject_ipv6.c b/net/ipv6/netfilter/nf_reject_ipv6.c index 5e08d8529cc8..7c9464184517 100644 --- a/net/ipv6/netfilter/nf_reject_ipv6.c +++ b/net/ipv6/netfilter/nf_reject_ipv6.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -409,7 +410,19 @@ void nf_send_reset6(struct net *net, struct sock *sk, struct sk_buff *oldskb, dev_queue_xmit(nskb); } else #endif + { + local_bh_disable(); + if (nf_dev_xmit_recursion()) { + local_bh_enable(); + kfree_skb(nskb); + return; + } + + nf_dev_xmit_recursion_inc(); ip6_local_out(net, sk, nskb); + nf_dev_xmit_recursion_dec(); + local_bh_enable(); + } } EXPORT_SYMBOL_GPL(nf_send_reset6); diff --git a/net/ipv6/raw.c b/net/ipv6/raw.c index 5ecbb9c775be..b69016d9a263 100644 --- a/net/ipv6/raw.c +++ b/net/ipv6/raw.c @@ -161,12 +161,6 @@ static bool ipv6_raw_deliver(struct sk_buff *skb, int nexthdr) inet6_iif(skb), inet6_sdif(skb))) continue; - if (atomic_read(&sk->sk_rmem_alloc) >= - READ_ONCE(sk->sk_rcvbuf)) { - sk_drops_inc(sk); - continue; - } - delivered = true; switch (nexthdr) { case IPPROTO_ICMPV6: @@ -197,8 +191,15 @@ static bool ipv6_raw_deliver(struct sk_buff *skb, int nexthdr) if (filtered < 0) break; if (filtered == 0) { - struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC); + struct sk_buff *clone; + + if (atomic_read(&sk->sk_rmem_alloc) >= + READ_ONCE(sk->sk_rcvbuf)) { + sk_drops_inc(sk); + continue; + } + clone = skb_clone(skb, GFP_ATOMIC); /* Not releasing hash table! */ if (clone) rawv6_rcv(sk, clone); diff --git a/net/ipv6/reassembly.c b/net/ipv6/reassembly.c index a5e0cec45974..74ac8e8bc19b 100644 --- a/net/ipv6/reassembly.c +++ b/net/ipv6/reassembly.c @@ -236,9 +236,10 @@ static int ip6_frag_queue(struct net *net, err = -EINVAL; goto err; } + if (err == IPFRAG_OVERLAP) + __IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), + IPSTATS_MIB_REASM_OVERLAPS); err = -EINVAL; - __IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), - IPSTATS_MIB_REASM_OVERLAPS); discard_fq: inet_frag_kill(&fq->q, refs); __IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), diff --git a/net/ipv6/route.c b/net/ipv6/route.c index af376b9568e2..9ea43498a1b3 100644 --- a/net/ipv6/route.c +++ b/net/ipv6/route.c @@ -1143,6 +1143,12 @@ static void ip6_rt_init_dst(struct rt6_info *rt, const struct fib6_result *res) return; } + /* addrconf_ifdown() removed inet6_dev. The device can't do IPv6. */ + if (!rt->rt6i_idev) { + ip6_rt_init_dst_reject(rt, RTN_UNREACHABLE); + return; + } + rt->dst.error = 0; rt->dst.output = ip6_output; @@ -1178,10 +1184,10 @@ static void ip6_rt_copy_init(struct rt6_info *rt, const struct fib6_result *res) const struct net_device *dev = nh->fib_nh_dev; struct fib6_info *f6i = res->f6i; + rt->rt6i_idev = dev ? in6_dev_get(dev) : NULL; ip6_rt_init_dst(rt, res); rt->rt6i_dst = f6i->fib6_dst; - rt->rt6i_idev = dev ? in6_dev_get(dev) : NULL; rt->rt6i_flags = res->fib6_flags; if (nh->fib_nh_gw_family) { rt->rt6i_gateway = nh->fib_nh_gw6; @@ -3461,9 +3467,9 @@ static int ip6_route_check_nh(struct net *net, netdevice_tracker *dev_tracker, struct inet6_dev **idev) { + int flags = RT6_LOOKUP_F_IFACE | RT6_LOOKUP_F_IGNORE_LINKSTATE; const struct in6_addr *gw_addr = &cfg->fc_gateway; struct net_device *dev = _dev ? *_dev : NULL; - int flags = RT6_LOOKUP_F_IFACE; struct fib6_result res = {}; int err = -EHOSTUNREACH; @@ -4892,8 +4898,10 @@ void rt6_multipath_rebalance(struct fib6_info *rt) if (WARN_ON_ONCE(!first)) return; + rcu_read_lock(); total = rt6_multipath_total_weight(first); rt6_multipath_upper_bound_set(first, total); + rcu_read_unlock(); } static int fib6_ifup(struct fib6_info *rt, void *p_arg) @@ -5430,6 +5438,7 @@ static int ip6_route_multipath_add(struct fib6_config *cfg, struct fib6_info *rt_notif = NULL, *rt_last = NULL; struct nl_info *info = &cfg->fc_nlinfo; struct rt6_nh *nh, *nh_safe; + struct fib6_table *table; struct fib6_config r_cfg; struct rtnexthop *rtnh; LIST_HEAD(rt6_nh_list); @@ -5516,10 +5525,12 @@ static int ip6_route_multipath_add(struct fib6_config *cfg, */ info->skip_notify_kernel = 1; + table = rt->fib6_table; + spin_lock_bh(&table->tb6_lock); + err_nh = NULL; list_for_each_entry(nh, &rt6_nh_list, list) { - err = __ip6_ins_rt(nh->fib6_info, info, extack); - + err = fib6_add(&table->tb6_root, nh->fib6_info, info, extack); if (err) { if (replace && nhn) NL_SET_ERR_MSG_MOD(extack, @@ -5574,11 +5585,13 @@ static int ip6_route_multipath_add(struct fib6_config *cfg, /* success ... tell user about new route */ ip6_route_mpath_notify(rt_notif, rt_last, info, nlflags); + + spin_unlock_bh(&table->tb6_lock); goto cleanup; add_errout: /* send notification for routes that were added so that - * the delete notifications sent by ip6_route_del are + * the delete notifications sent by fib6_del() are * coherent */ if (rt_notif) @@ -5588,9 +5601,10 @@ static int ip6_route_multipath_add(struct fib6_config *cfg, list_for_each_entry(nh, &rt6_nh_list, list) { if (err_nh == nh) break; - ip6_route_del(&nh->r_cfg, extack); + fib6_del(nh->fib6_info, &nh->r_cfg.fc_nlinfo); } + spin_unlock_bh(&table->tb6_lock); cleanup: list_for_each_entry_safe(nh, nh_safe, &rt6_nh_list, list) { fib6_info_release(nh->fib6_info); diff --git a/net/ipv6/seg6_iptunnel.c b/net/ipv6/seg6_iptunnel.c index d18f73ccf3d4..e4ff2410803f 100644 --- a/net/ipv6/seg6_iptunnel.c +++ b/net/ipv6/seg6_iptunnel.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -58,6 +59,21 @@ static inline struct seg6_lwt *seg6_lwt_lwtunnel(struct lwtunnel_state *lwt) return (struct seg6_lwt *)lwt->data; } +static bool seg6_skb_has_lwtstate(struct sk_buff *skb) +{ + struct dst_entry *dst; + + if (unlikely(!skb_valid_dst(skb))) + return false; + + dst = skb_dst(skb); + if (unlikely(!dst->lwtstate || + dst->lwtstate->type != LWTUNNEL_ENCAP_SEG6)) + return false; + + return true; +} + static inline struct seg6_iptunnel_encap * seg6_encap_lwtunnel(struct lwtunnel_state *lwt) { @@ -538,6 +554,17 @@ static int seg6_input_core(struct net *net, struct sock *sk, return err; } +static int seg6_input_core_nf(struct net *net, struct sock *sk, + struct sk_buff *skb) +{ + if (unlikely(!seg6_skb_has_lwtstate(skb))) { + kfree_skb(skb); + return -EINVAL; + } + + return seg6_input_core(net, sk, skb); +} + static int seg6_input_nf(struct sk_buff *skb) { struct net_device *dev = skb_dst_dev(skb); @@ -546,10 +573,10 @@ static int seg6_input_nf(struct sk_buff *skb) switch (skb->protocol) { case htons(ETH_P_IP): return NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING, net, NULL, - skb, NULL, dev, seg6_input_core); + skb, NULL, dev, seg6_input_core_nf); case htons(ETH_P_IPV6): return NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING, net, NULL, - skb, NULL, dev, seg6_input_core); + skb, NULL, dev, seg6_input_core_nf); } return -EINVAL; @@ -624,6 +651,17 @@ static int seg6_output_core(struct net *net, struct sock *sk, return err; } +static int seg6_output_core_nf(struct net *net, struct sock *sk, + struct sk_buff *skb) +{ + if (unlikely(!seg6_skb_has_lwtstate(skb))) { + kfree_skb(skb); + return -EINVAL; + } + + return seg6_output_core(net, sk, skb); +} + static int seg6_output_nf(struct net *net, struct sock *sk, struct sk_buff *skb) { struct net_device *dev = skb_dst_dev(skb); @@ -631,10 +669,10 @@ static int seg6_output_nf(struct net *net, struct sock *sk, struct sk_buff *skb) switch (skb->protocol) { case htons(ETH_P_IP): return NF_HOOK(NFPROTO_IPV4, NF_INET_POST_ROUTING, net, sk, skb, - NULL, dev, seg6_output_core); + NULL, dev, seg6_output_core_nf); case htons(ETH_P_IPV6): return NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING, net, sk, skb, - NULL, dev, seg6_output_core); + NULL, dev, seg6_output_core_nf); } return -EINVAL; diff --git a/net/ipv6/seg6_local.c b/net/ipv6/seg6_local.c index 67eeb27ee43a..82207da08dfd 100644 --- a/net/ipv6/seg6_local.c +++ b/net/ipv6/seg6_local.c @@ -24,6 +24,7 @@ #include #include #include +#include #include #ifdef CONFIG_IPV6_SEG6_HMAC #include @@ -149,9 +150,7 @@ struct seg6_end_dt_info { int vrf_ifindex; int vrf_table; - /* tunneled packet family (IPv4 or IPv6). - * Protocol and header length are inferred from family. - */ + /* tunneled packet family (IPv4 or IPv6) */ u16 family; }; @@ -213,6 +212,21 @@ static struct seg6_local_lwt *seg6_local_lwtunnel(struct lwtunnel_state *lwt) return (struct seg6_local_lwt *)lwt->data; } +static bool seg6_local_skb_has_lwtstate(struct sk_buff *skb) +{ + struct dst_entry *dst; + + if (unlikely(!skb_valid_dst(skb))) + return false; + + dst = skb_dst(skb); + if (unlikely(!dst->lwtstate || + dst->lwtstate->type != LWTUNNEL_ENCAP_SEG6_LOCAL)) + return false; + + return true; +} + static struct ipv6_sr_hdr *get_and_validate_srh(struct sk_buff *skb) { struct ipv6_sr_hdr *srh; @@ -278,13 +292,43 @@ static bool decap_and_validate(struct sk_buff *skb, int proto) return true; } -static void advance_nextseg(struct ipv6_sr_hdr *srh, struct in6_addr *daddr) +/* advance the SRH to the next segment and set the IPv6 DA accordingly. + * skb pointers may change: after this call, the caller must evaluate again + * any pointer into the packet data. + * + * This function returns: + * - the SRH on success; + * - NULL when the skb cannot be made writable. In this case, the function + * sets the drop reason to SKB_DROP_REASON_NOMEM. + */ +static struct ipv6_sr_hdr *advance_nextseg(struct sk_buff *skb, + struct ipv6_sr_hdr *srh, + enum skb_drop_reason *reason) { struct in6_addr *addr; + int srhoff; + int wlen; + + srhoff = (unsigned char *)srh - skb->data; + /* we write only the Segment Left field and the IPv6 DA. The segment + * list is only read, and seg6_get_srh() already pulled it into the + * linear area. + */ + wlen = srhoff + sizeof(*srh); + + if (unlikely(skb_ensure_writable(skb, wlen))) { + *reason = SKB_DROP_REASON_NOMEM; + return NULL; + } + + /* skb_ensure_writable() may change skb pointers; evaluate srh again */ + srh = (struct ipv6_sr_hdr *)(skb->data + srhoff); srh->segments_left--; addr = srh->segments + srh->segments_left; - *daddr = *addr; + ipv6_hdr(skb)->daddr = *addr; + + return srh; } static int @@ -382,12 +426,26 @@ static bool seg6_next_csid_is_arg_zero(const struct in6_addr *addr, return true; } -/* assume that DA.Argument length > 0 */ -static void seg6_next_csid_advance_arg(struct in6_addr *addr, - const struct seg6_flavors_info *finfo) +/* assume that DA.Argument length > 0. + * skb pointers may change: after this call, the caller must evaluate again + * any pointer into the packet data. + * + * This function returns: + * - SKB_NOT_DROPPED_YET on success; + * - SKB_DROP_REASON_NOMEM when the skb cannot be made writable. + */ +static enum skb_drop_reason +seg6_next_csid_advance_arg(struct sk_buff *skb, + const struct seg6_flavors_info *finfo) { __u8 fnc_octects = seg6_flv_lcnode_func_octects(finfo); __u8 blk_octects = seg6_flv_lcblock_octects(finfo); + struct in6_addr *addr; + + if (unlikely(skb_ensure_writable(skb, sizeof(struct ipv6hdr)))) + return SKB_DROP_REASON_NOMEM; + + addr = &ipv6_hdr(skb)->daddr; /* advance DA.Argument */ memmove(&addr->s6_addr[blk_octects], @@ -395,6 +453,8 @@ static void seg6_next_csid_advance_arg(struct in6_addr *addr, 16 - blk_octects - fnc_octects); memset(&addr->s6_addr[16 - fnc_octects], 0x00, fnc_octects); + + return SKB_NOT_DROPPED_YET; } static int input_action_end_finish(struct sk_buff *skb, @@ -408,31 +468,42 @@ static int input_action_end_finish(struct sk_buff *skb, static int input_action_end_core(struct sk_buff *skb, struct seg6_local_lwt *slwt) { + enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED; struct ipv6_sr_hdr *srh; + int err = -EINVAL; srh = get_and_validate_srh(skb); if (!srh) goto drop; - advance_nextseg(srh, &ipv6_hdr(skb)->daddr); + srh = advance_nextseg(skb, srh, &reason); + if (!srh) { + err = -ENOMEM; + goto drop; + } return input_action_end_finish(skb, slwt); drop: - kfree_skb(skb); - return -EINVAL; + kfree_skb_reason(skb, reason); + return err; } static int end_next_csid_core(struct sk_buff *skb, struct seg6_local_lwt *slwt) { const struct seg6_flavors_info *finfo = &slwt->flv_info; struct in6_addr *daddr = &ipv6_hdr(skb)->daddr; + enum skb_drop_reason reason; if (seg6_next_csid_is_arg_zero(daddr, finfo)) return input_action_end_core(skb, slwt); /* update DA */ - seg6_next_csid_advance_arg(daddr, finfo); + reason = seg6_next_csid_advance_arg(skb, finfo); + if (reason) { + kfree_skb_reason(skb, reason); + return -ENOMEM; + } return input_action_end_finish(skb, slwt); } @@ -448,19 +519,25 @@ static int input_action_end_x_finish(struct sk_buff *skb, static int input_action_end_x_core(struct sk_buff *skb, struct seg6_local_lwt *slwt) { + enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED; struct ipv6_sr_hdr *srh; + int err = -EINVAL; srh = get_and_validate_srh(skb); if (!srh) goto drop; - advance_nextseg(srh, &ipv6_hdr(skb)->daddr); + srh = advance_nextseg(skb, srh, &reason); + if (!srh) { + err = -ENOMEM; + goto drop; + } return input_action_end_x_finish(skb, slwt); drop: - kfree_skb(skb); - return -EINVAL; + kfree_skb_reason(skb, reason); + return err; } static int end_x_next_csid_core(struct sk_buff *skb, @@ -468,12 +545,17 @@ static int end_x_next_csid_core(struct sk_buff *skb, { const struct seg6_flavors_info *finfo = &slwt->flv_info; struct in6_addr *daddr = &ipv6_hdr(skb)->daddr; + enum skb_drop_reason reason; if (seg6_next_csid_is_arg_zero(daddr, finfo)) return input_action_end_x_core(skb, slwt); /* update DA */ - seg6_next_csid_advance_arg(daddr, finfo); + reason = seg6_next_csid_advance_arg(skb, finfo); + if (reason) { + kfree_skb_reason(skb, reason); + return -ENOMEM; + } return input_action_end_x_finish(skb, slwt); } @@ -760,10 +842,12 @@ static bool seg6_pop_srh(struct sk_buff *skb, int srhoff) */ static int end_flv8986_core(struct sk_buff *skb, struct seg6_local_lwt *slwt) { + enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED; const struct seg6_flavors_info *finfo = &slwt->flv_info; enum seg6_local_flv_action action; enum seg6_local_pktinfo pinfo; struct ipv6_sr_hdr *srh; + int err = -EINVAL; __u32 flvmask; int srhoff; @@ -787,10 +871,18 @@ static int end_flv8986_core(struct sk_buff *skb, struct seg6_local_lwt *slwt) switch (action) { case SEG6_LOCAL_FLV_ACT_END: /* process the packet as the "standard" End behavior */ - advance_nextseg(srh, &ipv6_hdr(skb)->daddr); + srh = advance_nextseg(skb, srh, &reason); + if (!srh) { + err = -ENOMEM; + goto drop; + } break; case SEG6_LOCAL_FLV_ACT_PSP: - advance_nextseg(srh, &ipv6_hdr(skb)->daddr); + srh = advance_nextseg(skb, srh, &reason); + if (!srh) { + err = -ENOMEM; + goto drop; + } if (unlikely(!seg6_pop_srh(skb, srhoff))) goto drop; @@ -807,8 +899,8 @@ static int end_flv8986_core(struct sk_buff *skb, struct seg6_local_lwt *slwt) return input_action_end_finish(skb, slwt); drop: - kfree_skb(skb); - return -EINVAL; + kfree_skb_reason(skb, reason); + return err; } /* regular endpoint function */ @@ -847,21 +939,27 @@ static int input_action_end_x(struct sk_buff *skb, struct seg6_local_lwt *slwt) static int input_action_end_t(struct sk_buff *skb, struct seg6_local_lwt *slwt) { + enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED; struct ipv6_sr_hdr *srh; + int err = -EINVAL; srh = get_and_validate_srh(skb); if (!srh) goto drop; - advance_nextseg(srh, &ipv6_hdr(skb)->daddr); + srh = advance_nextseg(skb, srh, &reason); + if (!srh) { + err = -ENOMEM; + goto drop; + } seg6_lookup_nexthop(skb, NULL, slwt->table); return dst_input(skb); drop: - kfree_skb(skb); - return -EINVAL; + kfree_skb_reason(skb, reason); + return err; } /* decapsulate and forward inner L2 frame on specified interface */ @@ -944,6 +1042,17 @@ static int input_action_end_dx6_finish(struct net *net, struct sock *sk, return dst_input(skb); } +static int input_action_end_dx6_finish_nf(struct net *net, struct sock *sk, + struct sk_buff *skb) +{ + if (unlikely(!seg6_local_skb_has_lwtstate(skb))) { + kfree_skb(skb); + return -EINVAL; + } + + return input_action_end_dx6_finish(net, sk, skb); +} + /* decapsulate and forward to specified nexthop */ static int input_action_end_dx6(struct sk_buff *skb, struct seg6_local_lwt *slwt) @@ -964,7 +1073,7 @@ static int input_action_end_dx6(struct sk_buff *skb, if (static_branch_unlikely(&nf_hooks_lwtunnel_enabled)) return NF_HOOK(NFPROTO_IPV6, NF_INET_PRE_ROUTING, dev_net(skb->dev), NULL, skb, skb->dev, - NULL, input_action_end_dx6_finish); + NULL, input_action_end_dx6_finish_nf); return input_action_end_dx6_finish(dev_net(skb->dev), NULL, skb); drop: @@ -972,6 +1081,40 @@ static int input_action_end_dx6(struct sk_buff *skb, return -EINVAL; } +/* Validate the length of the IPv4 header at skb->data (which must point to + * the network header) and report that length, options included. + * Only the version, the header length and the presence of the whole header + * are checked. + * The length is written only when SKB_NOT_DROPPED_YET is returned. + * + * skb pointers may change: after this call, the caller must evaluate again + * any pointer into the packet data. + */ +static enum skb_drop_reason +seg6_validate_iphdr_len(struct sk_buff *skb, int *hdrlen) +{ + enum skb_drop_reason reason; + const struct iphdr *iph; + int len; + + reason = pskb_may_pull_reason(skb, sizeof(struct iphdr)); + if (reason) + return reason; + + iph = ip_hdr(skb); + if (iph->version != 4 || iph->ihl < 5) + return SKB_DROP_REASON_IP_INHDR; + + len = ip_hdrlen(skb); + + reason = pskb_may_pull_reason(skb, len); + if (reason) + return reason; + + *hdrlen = len; + return SKB_NOT_DROPPED_YET; +} + static int input_action_end_dx4_finish(struct net *net, struct sock *sk, struct sk_buff *skb) { @@ -998,27 +1141,42 @@ static int input_action_end_dx4_finish(struct net *net, struct sock *sk, return dst_input(skb); } +static int input_action_end_dx4_finish_nf(struct net *net, struct sock *sk, + struct sk_buff *skb) +{ + if (unlikely(!seg6_local_skb_has_lwtstate(skb))) { + kfree_skb(skb); + return -EINVAL; + } + + return input_action_end_dx4_finish(net, sk, skb); +} + static int input_action_end_dx4(struct sk_buff *skb, struct seg6_local_lwt *slwt) { + SKB_DR(reason); + int hdrlen; + if (!decap_and_validate(skb, IPPROTO_IPIP)) goto drop; - if (!pskb_may_pull(skb, sizeof(struct iphdr))) + reason = seg6_validate_iphdr_len(skb, &hdrlen); + if (reason) goto drop; skb->protocol = htons(ETH_P_IP); - skb_set_transport_header(skb, sizeof(struct iphdr)); + skb_set_transport_header(skb, hdrlen); nf_reset_ct(skb); if (static_branch_unlikely(&nf_hooks_lwtunnel_enabled)) return NF_HOOK(NFPROTO_IPV4, NF_INET_PRE_ROUTING, dev_net(skb->dev), NULL, skb, skb->dev, - NULL, input_action_end_dx4_finish); + NULL, input_action_end_dx4_finish_nf); return input_action_end_dx4_finish(dev_net(skb->dev), NULL, skb); drop: - kfree_skb(skb); + kfree_skb_reason(skb, reason); return -EINVAL; } @@ -1153,16 +1311,24 @@ static struct sk_buff *end_dt_vrf_core(struct sk_buff *skb, struct seg6_end_dt_info *info = &slwt->dt_info; struct net_device *vrf; __be16 protocol; + SKB_DR(reason); int hdrlen; vrf = end_dt_get_vrf_rcu(skb, info); if (unlikely(!vrf)) goto drop; + if (unlikely(info->family != AF_UNSPEC && info->family != family)) { + pr_warn_once("seg6local: SRv6 End.DT* family mismatch"); + goto drop; + } + switch (family) { case AF_INET: protocol = htons(ETH_P_IP); - hdrlen = sizeof(struct iphdr); + reason = seg6_validate_iphdr_len(skb, &hdrlen); + if (unlikely(reason)) + goto drop; break; case AF_INET6: protocol = htons(ETH_P_IPV6); @@ -1174,11 +1340,6 @@ static struct sk_buff *end_dt_vrf_core(struct sk_buff *skb, goto drop; } - if (unlikely(info->family != AF_UNSPEC && info->family != family)) { - pr_warn_once("seg6local: SRv6 End.DT* family mismatch"); - goto drop; - } - skb->protocol = protocol; skb_dst_drop(skb); @@ -1189,7 +1350,7 @@ static struct sk_buff *end_dt_vrf_core(struct sk_buff *skb, return end_dt_vrf_rcv(skb, family, vrf); drop: - kfree_skb(skb); + kfree_skb_reason(skb, reason); return ERR_PTR(-EINVAL); } @@ -1202,9 +1363,7 @@ static int input_action_end_dt4(struct sk_buff *skb, if (!decap_and_validate(skb, IPPROTO_IPIP)) goto drop; - if (!pskb_may_pull(skb, sizeof(struct iphdr))) - goto drop; - + /* end_dt_vrf_core() validates the inner IPv4 header length */ skb = end_dt_vrf_core(skb, slwt, AF_INET); if (!skb) /* packet has been processed and consumed by the VRF */ @@ -1375,6 +1534,7 @@ static int input_action_end_b6(struct sk_buff *skb, struct seg6_local_lwt *slwt) static int input_action_end_b6_encap(struct sk_buff *skb, struct seg6_local_lwt *slwt) { + enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED; struct ipv6_sr_hdr *srh; int err = -EINVAL; @@ -1382,7 +1542,11 @@ static int input_action_end_b6_encap(struct sk_buff *skb, if (!srh) goto drop; - advance_nextseg(srh, &ipv6_hdr(skb)->daddr); + srh = advance_nextseg(skb, srh, &reason); + if (!srh) { + err = -ENOMEM; + goto drop; + } skb_reset_inner_headers(skb); skb->encapsulation = 1; @@ -1398,7 +1562,7 @@ static int input_action_end_b6_encap(struct sk_buff *skb, return dst_input(skb); drop: - kfree_skb(skb); + kfree_skb_reason(skb, reason); return err; } @@ -1434,6 +1598,7 @@ static int input_action_end_bpf(struct sk_buff *skb, struct seg6_local_lwt *slwt) { struct seg6_bpf_srh_state *srh_state; + enum skb_drop_reason reason; struct ipv6_sr_hdr *srh; int ret; @@ -1442,7 +1607,11 @@ static int input_action_end_bpf(struct sk_buff *skb, kfree_skb(skb); return -EINVAL; } - advance_nextseg(srh, &ipv6_hdr(skb)->daddr); + srh = advance_nextseg(skb, srh, &reason); + if (!srh) { + kfree_skb_reason(skb, reason); + return -ENOMEM; + } /* The access to the per-CPU buffer srh_state is protected by running * always in softirq context (with disabled BH). On PREEMPT_RT the @@ -1647,6 +1816,17 @@ static int seg6_local_input_core(struct net *net, struct sock *sk, return rc; } +static int seg6_local_input_core_nf(struct net *net, struct sock *sk, + struct sk_buff *skb) +{ + if (unlikely(!seg6_local_skb_has_lwtstate(skb))) { + kfree_skb(skb); + return -EINVAL; + } + + return seg6_local_input_core(net, sk, skb); +} + static int seg6_local_input(struct sk_buff *skb) { if (skb->protocol != htons(ETH_P_IPV6)) { @@ -1657,7 +1837,7 @@ static int seg6_local_input(struct sk_buff *skb) if (static_branch_unlikely(&nf_hooks_lwtunnel_enabled)) return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_IN, dev_net(skb->dev), NULL, skb, skb->dev, NULL, - seg6_local_input_core); + seg6_local_input_core_nf); return seg6_local_input_core(dev_net(skb->dev), NULL, skb); } diff --git a/net/ipv6/sit.c b/net/ipv6/sit.c index 590b54e9b947..d7d166cd54f8 100644 --- a/net/ipv6/sit.c +++ b/net/ipv6/sit.c @@ -394,7 +394,7 @@ ipip6_tunnel_add_prl(struct ip_tunnel *t, struct ip_tunnel_prl *a, int chg) goto out; } - p = kzalloc(sizeof(struct ip_tunnel_prl_entry), GFP_KERNEL); + p = kzalloc(sizeof(struct ip_tunnel_prl_entry), GFP_KERNEL_ACCOUNT); if (!p) { err = -ENOBUFS; goto out; diff --git a/net/ipv6/tcp_ipv6.c b/net/ipv6/tcp_ipv6.c index 027413fe37a4..490fc17a782c 100644 --- a/net/ipv6/tcp_ipv6.c +++ b/net/ipv6/tcp_ipv6.c @@ -425,7 +425,7 @@ static int tcp_v6_err(struct sk_buff *skb, struct inet6_skb_parm *opt, if (sock_owned_by_user(sk) && type != ICMPV6_PKT_TOOBIG) __NET_INC_STATS(net, LINUX_MIB_LOCKDROPPEDICMPS); - if (sk->sk_state == TCP_CLOSE) + if (sk->sk_state == TCP_CLOSE || inet_test_bit(DEFER_CONNECT, sk)) goto out; if (static_branch_unlikely(&ip6_min_hopcount)) { @@ -554,8 +554,8 @@ static int tcp_v6_send_synack(const struct sock *sk, struct dst_entry *dst, &ireq->ir_v6_rmt_addr); fl6->daddr = ireq->ir_v6_rmt_addr; - if (inet6_test_bit(REPFLOW, sk) && ireq->pktopts) - fl6->flowlabel = ip6_flowlabel(ipv6_hdr(ireq->pktopts)); + if (inet6_test_bit(REPFLOW, sk)) + fl6->flowlabel = tcp_rsk(req)->syn_flowlabel; tclass = READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reflect_tos) ? (tcp_rsk(req)->syn_tos & ~INET_ECN_MASK) | @@ -583,7 +583,7 @@ static int tcp_v6_send_synack(const struct sock *sk, struct dst_entry *dst, static void tcp_v6_reqsk_destructor(struct request_sock *req) { - kfree(inet_rsk(req)->ipv6_opt); + kfree_rcu(inet_rsk(req)->ipv6_opt, rcu); consume_skb(inet_rsk(req)->pktopts); } @@ -808,6 +808,7 @@ static void tcp_v6_init_req(struct request_sock *req, ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr; ireq->ir_rmt_addr = LOOPBACK4_IPV6; ireq->ir_loc_addr = LOOPBACK4_IPV6; + tcp_rsk(req)->syn_flowlabel = ip6_flowlabel(ipv6_hdr(skb)); /* So that link locals have meaning */ if ((!sk_listener->sk_bound_dev_if || l3_slave) && diff --git a/net/ipv6/udp.c b/net/ipv6/udp.c index 7468c1f0a4ff..1cc143ef7b9c 100644 --- a/net/ipv6/udp.c +++ b/net/ipv6/udp.c @@ -1264,8 +1264,11 @@ void udp_v6_early_demux(struct sk_buff *skb) skb->destructor = sock_pfree; dst = rcu_dereference(sk->sk_rx_dst); - if (dst) + /* A dual-stack socket can cache an IPv4 dst. */ + if (dst && dst->ops->family == AF_INET6) dst = dst_check(dst, sk->sk_rx_dst_cookie); + else + dst = NULL; if (dst) { /* set noref for now. * any place which wants to hold dst has to call diff --git a/net/iucv/af_iucv.c b/net/iucv/af_iucv.c index 3472bdde31af..a8601a878240 100644 --- a/net/iucv/af_iucv.c +++ b/net/iucv/af_iucv.c @@ -2072,11 +2072,20 @@ static int afiucv_hs_rcv(struct sk_buff *skb, struct net_device *dev, int err = NET_RX_SUCCESS; char nullstring[8]; + skb = skb_share_check(skb, GFP_ATOMIC); + if (!skb) + return NET_RX_SUCCESS; + if (!pskb_may_pull(skb, sizeof(*trans_hdr))) { kfree_skb(skb); return NET_RX_SUCCESS; } + if (skb_cow(skb, ETH_HLEN)) { + kfree_skb(skb); + return NET_RX_SUCCESS; + } + trans_hdr = iucv_trans_hdr(skb); EBCASC(trans_hdr->destAppName, sizeof(trans_hdr->destAppName)); EBCASC(trans_hdr->destUserID, sizeof(trans_hdr->destUserID)); diff --git a/net/mac80211/airtime.c b/net/mac80211/airtime.c index c61df637232a..51f636e1f9f0 100644 --- a/net/mac80211/airtime.c +++ b/net/mac80211/airtime.c @@ -550,6 +550,8 @@ static u32 ieee80211_get_rate_duration(struct ieee80211_hw *hw, group = HE_GROUP_IDX(streams, status->he_gi, bw); break; case RX_ENC_EHT: + if (status->eht.gi > NL80211_RATE_INFO_EHT_GI_3_2) + return 0; streams = status->nss; idx = status->rate_idx; group = EHT_GROUP_IDX(streams, status->eht.gi, bw); diff --git a/net/mac80211/ibss.c b/net/mac80211/ibss.c index 4dc748a667a7..8962f8d8ef9c 100644 --- a/net/mac80211/ibss.c +++ b/net/mac80211/ibss.c @@ -676,6 +676,10 @@ static void ieee80211_ibss_disconnect(struct ieee80211_sub_if_data *sdata) ifibss->state = IEEE80211_IBSS_MLME_SEARCH; netif_carrier_off(sdata->dev); + + sdata->vif.bss_conf.csa_active = false; + ieee80211_vif_unblock_queues_csa(sdata); + if (!sta_info_flush(sdata, -1)) synchronize_net(); @@ -687,6 +691,7 @@ static void ieee80211_ibss_disconnect(struct ieee80211_sub_if_data *sdata) spin_unlock_bh(&ifibss->incomplete_lock); sta_info_free(local, sta); + atomic_dec(&ifibss->incomplete_sta_count); spin_lock_bh(&ifibss->incomplete_lock); } spin_unlock_bh(&ifibss->incomplete_lock); @@ -1203,9 +1208,18 @@ void ieee80211_ibss_rx_no_sta(struct ieee80211_sub_if_data *sdata, band = chanctx_conf->def.chan->band; rcu_read_unlock(); + if (!atomic_add_unless(&ifibss->incomplete_sta_count, 1, + IEEE80211_IBSS_MAX_STA_ENTRIES)) { + net_info_ratelimited("%s: No room for a new IBSS STA entry %pM\n", + sdata->name, addr); + return; + } + sta = sta_info_alloc(sdata, addr, GFP_ATOMIC); - if (!sta) + if (!sta) { + atomic_dec(&ifibss->incomplete_sta_count); return; + } /* make sure mandatory rates are always added */ sband = local->hw.wiphy->bands[band]; @@ -1652,8 +1666,13 @@ void ieee80211_ibss_work(struct ieee80211_sub_if_data *sdata) list_del(&sta->list); spin_unlock_bh(&ifibss->incomplete_lock); - ieee80211_ibss_finish_sta(sta); - rcu_read_unlock(); + if (sdata->local->num_sta >= IEEE80211_IBSS_MAX_STA_ENTRIES) { + sta_info_free(sdata->local, sta); + } else { + ieee80211_ibss_finish_sta(sta); + rcu_read_unlock(); + } + atomic_dec(&ifibss->incomplete_sta_count); spin_lock_bh(&ifibss->incomplete_lock); } spin_unlock_bh(&ifibss->incomplete_lock); diff --git a/net/mac80211/ieee80211_i.h b/net/mac80211/ieee80211_i.h index 1f049720bfda..f2d25b08e653 100644 --- a/net/mac80211/ieee80211_i.h +++ b/net/mac80211/ieee80211_i.h @@ -668,6 +668,7 @@ struct ieee80211_if_ibss { spinlock_t incomplete_lock; struct list_head incomplete_stations; + atomic_t incomplete_sta_count; enum { IEEE80211_IBSS_MLME_SEARCH, @@ -682,6 +683,7 @@ struct ieee80211_if_ibss { * @wrkq_flags: OCB deferred task action * @incomplete_lock: delayed STA insertion lock * @incomplete_stations: list of STAs waiting for delayed insertion + * @incomplete_sta_count: pending entries and reserved allocations * @joined: indication if the interface is connected to an OCB network */ struct ieee80211_if_ocb { @@ -690,6 +692,7 @@ struct ieee80211_if_ocb { spinlock_t incomplete_lock; struct list_head incomplete_stations; + atomic_t incomplete_sta_count; bool joined; }; diff --git a/net/mac80211/link.c b/net/mac80211/link.c index 54415ca128d2..b7f3b1573669 100644 --- a/net/mac80211/link.c +++ b/net/mac80211/link.c @@ -179,6 +179,7 @@ struct link_container { static void ieee80211_tear_down_links(struct ieee80211_sub_if_data *sdata, struct link_container **links, u16 mask) { + struct ieee80211_link_data *stop[IEEE80211_MLD_MAX_NUM_LINKS] = {}; struct ieee80211_link_data *link; LIST_HEAD(keys); unsigned int link_id; @@ -193,11 +194,16 @@ static void ieee80211_tear_down_links(struct ieee80211_sub_if_data *sdata, continue; ieee80211_remove_link_keys(link, &keys); ieee80211_link_debugfs_remove(link); - ieee80211_link_stop(link); + stop[link_id] = link; } + /* drain RCU readers before cancelling work they may queue */ synchronize_rcu(); + for (link_id = 0; link_id < IEEE80211_MLD_MAX_NUM_LINKS; link_id++) + if (stop[link_id]) + ieee80211_link_stop(stop[link_id]); + ieee80211_free_key_list(sdata->local, &keys); } @@ -278,6 +284,7 @@ static int ieee80211_vif_update_links(struct ieee80211_sub_if_data *sdata, { u16 old_links = sdata->vif.valid_links; u16 old_active = sdata->vif.active_links; + u16 old_dormant = sdata->vif.dormant_links; unsigned long add = new_links & ~old_links; unsigned long rem = old_links & ~new_links; unsigned long sta_rem = rem; @@ -384,7 +391,9 @@ static int ieee80211_vif_update_links(struct ieee80211_sub_if_data *sdata, /* restore config */ memcpy(sdata->link, old_data, sizeof(old_data)); memcpy(sdata->vif.link_conf, old, sizeof(old)); - ieee80211_set_vif_links_bitmaps(sdata, old_links, dormant_links); + ieee80211_set_vif_links_bitmaps(sdata, old_links, old_dormant); + /* drain RCU readers before cancelling work they may queue */ + synchronize_rcu(); for_each_set_bit(link_id, &add, IEEE80211_MLD_MAX_NUM_LINKS) { ieee80211_link_debugfs_remove(&links[link_id]->data); ieee80211_link_stop(&links[link_id]->data); diff --git a/net/mac80211/mlme.c b/net/mac80211/mlme.c index 2ca905b9da22..84549328e292 100644 --- a/net/mac80211/mlme.c +++ b/net/mac80211/mlme.c @@ -7127,15 +7127,15 @@ static void ieee80211_tid_to_link_map_work(struct wiphy *wiphy, sdata->u.mgd.ttlm_info.switch_time = 0; } -static void ieee80211_process_adv_ttlm(struct ieee80211_sub_if_data *sdata, - struct ieee802_11_elems *elems, - u64 beacon_ts) +static bool ieee80211_process_adv_ttlm(struct ieee80211_sub_if_data *sdata, + struct ieee802_11_elems *elems, + u64 beacon_ts) { u8 i; int ret; if (!ieee80211_vif_is_mld(&sdata->vif)) - return; + return true; if (!elems->ttlm_num) { if (sdata->u.mgd.ttlm_info.switch_time) { @@ -7153,14 +7153,14 @@ static void ieee80211_process_adv_ttlm(struct ieee80211_sub_if_data *sdata, 0); if (ret) { sdata_info(sdata, "Failed setting valid/dormant links\n"); - return; + return true; } ieee80211_vif_cfg_change_notify(sdata, BSS_CHANGED_MLD_VALID_LINKS); } memset(&sdata->u.mgd.ttlm_info, 0, sizeof(sdata->u.mgd.ttlm_info)); - return; + return true; } for (i = 0; i < elems->ttlm_num; i++) { @@ -7172,7 +7172,7 @@ static void ieee80211_process_adv_ttlm(struct ieee80211_sub_if_data *sdata, if (res) { __ieee80211_disconnect(sdata); - return; + return false; } if (ttlm_info.switch_time) { @@ -7197,7 +7197,7 @@ static void ieee80211_process_adv_ttlm(struct ieee80211_sub_if_data *sdata, * switch the AP will continue to announce it anyway. */ if (delay > IEEE80211_ADV_TTLM_ST_UNDERFLOW) - return; + return true; delay_usec = ieee80211_tu_to_usec(delay); @@ -7216,9 +7216,11 @@ static void ieee80211_process_adv_ttlm(struct ieee80211_sub_if_data *sdata, wiphy_hrtimer_work_queue(sdata->local->hw.wiphy, &sdata->u.mgd.ttlm_work, us_to_ktime(delay_usec)); - return; + return true; } } + + return true; } static void @@ -7738,8 +7740,9 @@ static void ieee80211_rx_mgmt_beacon(struct ieee80211_link_data *link, elems->cisco_dtpc_elem); ieee80211_ml_reconfiguration(sdata, elems); - ieee80211_process_adv_ttlm(sdata, elems, - le64_to_cpu(mgmt->u.beacon.timestamp)); + if (!ieee80211_process_adv_ttlm(sdata, elems, + le64_to_cpu(mgmt->u.beacon.timestamp))) + goto free; apply: ieee80211_link_info_change_notify(sdata, link, changed); diff --git a/net/mac80211/ocb.c b/net/mac80211/ocb.c index ebb4f4d88c23..f383fd0fab02 100644 --- a/net/mac80211/ocb.c +++ b/net/mac80211/ocb.c @@ -70,9 +70,18 @@ void ieee80211_ocb_rx_no_sta(struct ieee80211_sub_if_data *sdata, band = chanctx_conf->def.chan->band; rcu_read_unlock(); + if (!atomic_add_unless(&ifocb->incomplete_sta_count, 1, + IEEE80211_OCB_MAX_STA_ENTRIES)) { + net_info_ratelimited("%s: No room for a new OCB STA entry %pM\n", + sdata->name, addr); + return; + } + sta = sta_info_alloc(sdata, addr, GFP_ATOMIC); - if (!sta) + if (!sta) { + atomic_dec(&ifocb->incomplete_sta_count); return; + } /* Add only mandatory rates for now */ sband = local->hw.wiphy->bands[band]; @@ -136,8 +145,13 @@ void ieee80211_ocb_work(struct ieee80211_sub_if_data *sdata) list_del(&sta->list); spin_unlock_bh(&ifocb->incomplete_lock); - ieee80211_ocb_finish_sta(sta); - rcu_read_unlock(); + if (sdata->local->num_sta >= IEEE80211_OCB_MAX_STA_ENTRIES) { + sta_info_free(sdata->local, sta); + } else { + ieee80211_ocb_finish_sta(sta); + rcu_read_unlock(); + } + atomic_dec(&ifocb->incomplete_sta_count); spin_lock_bh(&ifocb->incomplete_lock); } spin_unlock_bh(&ifocb->incomplete_lock); @@ -221,6 +235,7 @@ int ieee80211_ocb_leave(struct ieee80211_sub_if_data *sdata) spin_unlock_bh(&ifocb->incomplete_lock); sta_info_free(local, sta); + atomic_dec(&ifocb->incomplete_sta_count); spin_lock_bh(&ifocb->incomplete_lock); } spin_unlock_bh(&ifocb->incomplete_lock); diff --git a/net/mac80211/rx.c b/net/mac80211/rx.c index 1f1b1e4f0df7..04dafe115d2c 100644 --- a/net/mac80211/rx.c +++ b/net/mac80211/rx.c @@ -2818,9 +2818,6 @@ ieee80211_rx_mesh_fast_forward(struct ieee80211_sub_if_data *sdata, if (!sta) return false; - if (skb_linearize(skb)) - return false; - tid = skb->priority & IEEE80211_QOS_CTL_TAG1D_MASK; tid_tx = rcu_dereference(sta->ampdu_mlme.tid_tx[tid]); if (tid_tx) { @@ -2831,6 +2828,10 @@ ieee80211_rx_mesh_fast_forward(struct ieee80211_sub_if_data *sdata, tid_tx->last_tx = jiffies; } + /* this function must not fail after this */ + if (skb_linearize(skb)) + return false; + ieee80211_aggr_check(sdata, sta, skb); if (ieee80211_get_8023_tunnel_proto(skb->data + hdrlen, diff --git a/net/mac80211/tx.c b/net/mac80211/tx.c index 6f511ebc5109..595a5eabe47f 100644 --- a/net/mac80211/tx.c +++ b/net/mac80211/tx.c @@ -2552,6 +2552,12 @@ netdev_tx_t ieee80211_monitor_start_xmit(struct sk_buff *skb, /* remove the injection radiotap header */ skb_pull(skb, len_rthdr); + /* FCS removal may have shortened the 802.11 header. */ + hdrlen = max_t(int, hdrlen, + offsetofend(struct ieee80211_hdr, addr1)); + if (skb_headlen(skb) < hdrlen) + goto fail_rcu; + ieee80211_xmit(sdata, NULL, skb); rcu_read_unlock(); diff --git a/net/mctp/af_mctp.c b/net/mctp/af_mctp.c index b99ba14f39d2..4cc0766e411f 100644 --- a/net/mctp/af_mctp.c +++ b/net/mctp/af_mctp.c @@ -291,7 +291,7 @@ static int mctp_recvmsg(struct socket *sock, struct msghdr *msg, size_t len, u8 type; int rc; - if (flags & ~(MSG_DONTWAIT | MSG_TRUNC | MSG_PEEK)) + if (flags & ~(MSG_DONTWAIT | MSG_TRUNC | MSG_PEEK | MSG_CMSG_COMPAT)) return -EOPNOTSUPP; skb = skb_recv_datagram(sk, flags, &rc); diff --git a/net/mptcp/options.c b/net/mptcp/options.c index 69c2906bf314..ad7da6be7221 100644 --- a/net/mptcp/options.c +++ b/net/mptcp/options.c @@ -1137,9 +1137,9 @@ static void ack_update_msk(struct mptcp_sock *msk, struct sock *ssk, struct mptcp_options_received *mp_opt) { - u64 new_wnd_end, new_snd_una, snd_nxt = READ_ONCE(msk->snd_nxt); + u64 new_wnd_end, new_snd_una, old_snd_una; struct sock *sk = (struct sock *)msk; - u64 old_snd_una; + u64 snd_nxt; mptcp_data_lock(sk); @@ -1148,10 +1148,14 @@ static void ack_update_msk(struct mptcp_sock *msk, * more dangerous than missing an ack */ old_snd_una = msk->snd_una; + snd_nxt = READ_ONCE(msk->snd_nxt); new_snd_una = mptcp_expand_seq(old_snd_una, mp_opt->data_ack, mp_opt->ack64); - /* ACK for data not even sent yet? Ignore.*/ - if (unlikely(after64(new_snd_una, snd_nxt))) + /* The active-open state sync can defer the snd_nxt update. Do not + * accept an ACK against a reversed interval, or beyond snd_nxt. + */ + if (unlikely(before64(snd_nxt, old_snd_una) || + after64(new_snd_una, snd_nxt))) new_snd_una = old_snd_una; new_wnd_end = new_snd_una + tcp_sk(ssk)->snd_wnd; diff --git a/net/netfilter/ipvs/ip_vs_app.c b/net/netfilter/ipvs/ip_vs_app.c index 0c690a30a85d..3302d4a83d01 100644 --- a/net/netfilter/ipvs/ip_vs_app.c +++ b/net/netfilter/ipvs/ip_vs_app.c @@ -243,7 +243,7 @@ void unregister_ip_vs_app(struct netns_ipvs *ipvs, struct ip_vs_app *app) } list_del(&a->a_list); - kfree(a); + kfree_rcu(a, rcu_head); /* decrease the module use count */ ip_vs_use_count_dec(); diff --git a/net/netfilter/ipvs/ip_vs_core.c b/net/netfilter/ipvs/ip_vs_core.c index 401159a66075..cd6a64e13ffb 100644 --- a/net/netfilter/ipvs/ip_vs_core.c +++ b/net/netfilter/ipvs/ip_vs_core.c @@ -2319,12 +2319,12 @@ static int __net_init __ip_vs_init(struct net *net) if (ip_vs_estimator_net_init(ipvs) < 0) goto estimator_fail; - if (ip_vs_control_net_init(ipvs) < 0) - goto control_fail; - if (ip_vs_protocol_net_init(ipvs) < 0) goto protocol_fail; + if (ip_vs_control_net_init(ipvs) < 0) + goto control_fail; + if (ip_vs_app_net_init(ipvs) < 0) goto app_fail; @@ -2344,10 +2344,10 @@ static int __net_init __ip_vs_init(struct net *net) conn_fail: ip_vs_app_net_cleanup(ipvs); app_fail: - ip_vs_protocol_net_cleanup(ipvs); -protocol_fail: ip_vs_control_net_cleanup(ipvs); control_fail: + ip_vs_protocol_net_cleanup(ipvs); +protocol_fail: ip_vs_estimator_net_cleanup(ipvs); estimator_fail: net->ipvs = NULL; @@ -2364,8 +2364,8 @@ static void __net_exit __ip_vs_cleanup_batch(struct list_head *net_list) ipvs = net_ipvs(net); ip_vs_conn_net_cleanup(ipvs); ip_vs_app_net_cleanup(ipvs); - ip_vs_protocol_net_cleanup(ipvs); ip_vs_control_net_cleanup(ipvs); + ip_vs_protocol_net_cleanup(ipvs); ip_vs_estimator_net_cleanup(ipvs); IP_VS_DBG(2, "ipvs netns %d released\n", ipvs->gen); net->ipvs = NULL; diff --git a/net/netfilter/nf_conntrack_helper.c b/net/netfilter/nf_conntrack_helper.c index 2cef826e20fb..17538e3382dd 100644 --- a/net/netfilter/nf_conntrack_helper.c +++ b/net/netfilter/nf_conntrack_helper.c @@ -425,6 +425,18 @@ static bool expect_iter_me(struct nf_conntrack_expect *exp, void *data) return this == me; } +void nf_conntrack_helper_release(struct nf_conntrack_helper *me) +{ + nf_ct_expect_iterate_destroy(expect_iter_me, me); + nf_ct_iterate_destroy(unhelp, me); + + /* nf_ct_iterate_destroy() does an unconditional synchronize_rcu() as + * last step, this ensures rcu readers of exp->helper are done. + * No need for another synchronize_rcu() here. + */ +} +EXPORT_SYMBOL_GPL(nf_conntrack_helper_release); + void nf_conntrack_helper_unregister(struct nf_conntrack_helper *me) { mutex_lock(&nf_ct_helper_mutex); @@ -437,13 +449,7 @@ void nf_conntrack_helper_unregister(struct nf_conntrack_helper *me) */ synchronize_rcu(); - nf_ct_expect_iterate_destroy(expect_iter_me, me); - nf_ct_iterate_destroy(unhelp, me); - - /* nf_ct_iterate_destroy() does an unconditional synchronize_rcu() as - * last step, this ensures rcu readers of exp->helper are done. - * No need for another synchronize_rcu() here. - */ + nf_conntrack_helper_release(me); } EXPORT_SYMBOL_GPL(nf_conntrack_helper_unregister); diff --git a/net/netfilter/nf_conntrack_sip.c b/net/netfilter/nf_conntrack_sip.c index 449a6e53feae..12b8c7fcca64 100644 --- a/net/netfilter/nf_conntrack_sip.c +++ b/net/netfilter/nf_conntrack_sip.c @@ -707,9 +707,9 @@ static int ct_sip_parse_transport(struct nf_conn *ct, const char *dptr, if (ct_sip_parse_param(ct, dptr, dataoff, datalen, "transport=", &matchoff, &matchlen)) { - if (!strncasecmp(dptr + matchoff, "TCP", strlen("TCP"))) + if (matchlen >= 3 && !strncasecmp(dptr + matchoff, "TCP", 3)) *proto = IPPROTO_TCP; - else if (!strncasecmp(dptr + matchoff, "UDP", strlen("UDP"))) + else if (matchlen >= 3 && !strncasecmp(dptr + matchoff, "UDP", 3)) *proto = IPPROTO_UDP; else return 0; diff --git a/net/netfilter/nf_dup_netdev.c b/net/netfilter/nf_dup_netdev.c index 02d1880bab6b..c47508b54ba9 100644 --- a/net/netfilter/nf_dup_netdev.c +++ b/net/netfilter/nf_dup_netdev.c @@ -12,6 +12,7 @@ #include #include #include +#include static void nf_do_netdev_egress(struct sk_buff *skb, struct net_device *dev, enum nf_dev_hooks hook) diff --git a/net/netfilter/nf_flow_table_core.c b/net/netfilter/nf_flow_table_core.c index f1f119062c86..100950d80e3a 100644 --- a/net/netfilter/nf_flow_table_core.c +++ b/net/netfilter/nf_flow_table_core.c @@ -537,6 +537,7 @@ static void nf_flow_table_extend_ct_timeout(struct nf_conn *ct) switch (l4proto) { case IPPROTO_UDP: + case IPPROTO_GRE: new_timeout = NF_CT_DAY; break; case IPPROTO_TCP: diff --git a/net/netfilter/nf_flow_table_ip.c b/net/netfilter/nf_flow_table_ip.c index 041d928b0bee..aa22d8fd39fc 100644 --- a/net/netfilter/nf_flow_table_ip.c +++ b/net/netfilter/nf_flow_table_ip.c @@ -410,6 +410,7 @@ static int nf_flow_offload_forward(struct nf_flowtable_ctx *ctx, nf_flow_encap_pop(skb, tuplehash); thoff -= ctx->offset; + skb_set_transport_header(skb, thoff); iph = ip_hdr(skb); nf_flow_nat_ip(flow, skb, thoff, dir, iph); @@ -698,6 +699,7 @@ static int nf_flow_offload_ipv6_forward(struct nf_flowtable_ctx *ctx, flow_offload_refresh(flow_table, flow, false); nf_flow_encap_pop(skb, tuplehash); + skb_set_transport_header(skb, sizeof(*ip6h)); ip6h = ipv6_hdr(skb); nf_flow_nat_ipv6(flow, skb, dir, ip6h); diff --git a/net/netfilter/nf_nat_masquerade.c b/net/netfilter/nf_nat_masquerade.c index 1a506b0c6511..2506aace39bc 100644 --- a/net/netfilter/nf_nat_masquerade.c +++ b/net/netfilter/nf_nat_masquerade.c @@ -62,8 +62,7 @@ nf_nat_masquerade_ipv4(struct sk_buff *skb, unsigned int hooknum, nat->masq_index = out->ifindex; /* Transfer from original range. */ - memset(&newrange.min_addr, 0, sizeof(newrange.min_addr)); - memset(&newrange.max_addr, 0, sizeof(newrange.max_addr)); + memset(&newrange, 0, sizeof(newrange)); newrange.flags = range->flags | NF_NAT_RANGE_MAP_IPS; newrange.min_addr.ip = newsrc; newrange.max_addr.ip = newsrc; @@ -259,6 +258,7 @@ nf_nat_masquerade_ipv6(struct sk_buff *skb, const struct nf_nat_range2 *range, if (nat) nat->masq_index = out->ifindex; + memset(&newrange, 0, sizeof(newrange)); newrange.flags = range->flags | NF_NAT_RANGE_MAP_IPS; newrange.min_addr.in6 = src; newrange.max_addr.in6 = src; diff --git a/net/netfilter/nf_queue.c b/net/netfilter/nf_queue.c index c0c9ea5fc4e1..e25966a09fe3 100644 --- a/net/netfilter/nf_queue.c +++ b/net/netfilter/nf_queue.c @@ -218,6 +218,7 @@ static int __nf_queue(struct sk_buff *skb, const struct nf_hook_state *state, *entry = (struct nf_queue_entry) { .skb = skb, .skb_dev = skb->dev, + .in_nf_duplicate = current->in_nf_duplicate, .state = *state, .hook_index = index, .size = sizeof(*entry) + route_key_size, diff --git a/net/netfilter/nf_tables_api.c b/net/netfilter/nf_tables_api.c index 76876761698e..a248dc75c5a0 100644 --- a/net/netfilter/nf_tables_api.c +++ b/net/netfilter/nf_tables_api.c @@ -754,16 +754,6 @@ static int nft_delrule(struct nft_ctx *ctx, struct nft_rule *rule) if (trans == NULL) return -ENOMEM; - if (ctx->chain->flags & NFT_CHAIN_HW_OFFLOAD) { - flow = nft_flow_rule_create(ctx->net, rule); - if (IS_ERR(flow)) { - nft_trans_destroy(trans); - return PTR_ERR(flow); - } - - nft_trans_flow_rule(trans) = flow; - } - err = nf_tables_delrule_deactivate(ctx, rule); if (err < 0) { nft_trans_destroy(trans); @@ -771,6 +761,14 @@ static int nft_delrule(struct nft_ctx *ctx, struct nft_rule *rule) } nft_rule_expr_deactivate(ctx, rule, NFT_TRANS_PREPARE); + if (ctx->chain->flags & NFT_CHAIN_HW_OFFLOAD) { + flow = nft_flow_rule_create(ctx->net, rule); + if (IS_ERR(flow)) + return PTR_ERR(flow); + + nft_trans_flow_rule(trans) = flow; + } + return 0; } @@ -4527,8 +4525,7 @@ static int nf_tables_newrule(struct sk_buff *skb, const struct nfnl_info *info, err_destroy_flow_rule: nft_use_dec_restore(&chain->use); err_destroy_flow: - if (flow) - nft_flow_rule_destroy(flow); + nft_flow_rule_destroy(flow); err_release_rule: nft_rule_expr_deactivate(&ctx, rule, NFT_TRANS_PREPARE_ERROR); nf_tables_rule_destroy(&ctx, rule); diff --git a/net/netfilter/nf_tables_offload.c b/net/netfilter/nf_tables_offload.c index 933a17d0f251..853094a300c2 100644 --- a/net/netfilter/nf_tables_offload.c +++ b/net/netfilter/nf_tables_offload.c @@ -148,6 +148,9 @@ void nft_flow_rule_destroy(struct nft_flow_rule *flow) struct flow_action_entry *entry; int i; + if (!flow) + return; + flow_action_for_each(i, entry, &flow->rule->action) { switch (entry->id) { case FLOW_ACTION_REDIRECT: diff --git a/net/netfilter/nfnetlink_queue.c b/net/netfilter/nfnetlink_queue.c index c5f3307936f8..d8cfae6fb039 100644 --- a/net/netfilter/nfnetlink_queue.c +++ b/net/netfilter/nfnetlink_queue.c @@ -44,6 +44,7 @@ #include #include #include +#include #include #include @@ -351,21 +352,30 @@ static void nf_reinject(struct nf_queue_entry *entry, unsigned int verdict) const struct nf_hook_entry *hook_entry; const struct nf_hook_entries *hooks; struct sk_buff *skb = entry->skb; + bool old_in_nf_duplicate; const struct net *net; unsigned int i; int err; u8 pf; + DEBUG_NET_WARN_ONCE(current->in_nf_duplicate && + !entry->in_nf_duplicate, + "%s called with unexpected duplication guard", + __func__); + local_bh_disable(); + old_in_nf_duplicate = current->in_nf_duplicate; + net = entry->state.net; pf = entry->state.pf; + current->in_nf_duplicate = entry->in_nf_duplicate; hooks = nf_hook_entries_head(net, pf, entry->state.hook); i = entry->hook_index; if (!hooks || i >= hooks->num_hook_entries) { kfree_skb_reason(skb, SKB_DROP_REASON_NETFILTER_DROP); nf_queue_entry_free(entry); - return; + goto out; } hook_entry = &hooks->hooks[i]; @@ -388,9 +398,7 @@ static void nf_reinject(struct nf_queue_entry *entry, unsigned int verdict) switch (verdict & NF_VERDICT_MASK) { case NF_ACCEPT: case NF_STOP: - local_bh_disable(); entry->state.okfn(entry->state.net, entry->state.sk, skb); - local_bh_enable(); break; case NF_QUEUE: err = nf_queue(skb, &entry->state, i, verdict); @@ -404,6 +412,9 @@ static void nf_reinject(struct nf_queue_entry *entry, unsigned int verdict) } nf_queue_entry_free(entry); +out: + current->in_nf_duplicate = old_in_nf_duplicate; + local_bh_enable(); } /* return true if the entry has an unconfirmed conntrack attached that isn't owned by us diff --git a/net/netfilter/nft_ct.c b/net/netfilter/nft_ct.c index 11d99778216f..87de920ead03 100644 --- a/net/netfilter/nft_ct.c +++ b/net/netfilter/nft_ct.c @@ -1217,11 +1217,84 @@ struct nft_ct_expect_obj { u32 timeout; }; +static int nft_ct_expect_timeout_get(const struct nlattr *attr, u32 *val) +{ + unsigned long jiffies_val = msecs_to_jiffies(nla_get_u32(attr)); + + if (jiffies_val > UINT_MAX) + return -ERANGE; + + *val = jiffies_val; + return 0; +} + +struct nft_ct_expect_data { + struct nft_ct_expect_obj obj; + enum ip_conntrack_dir dir; +}; + +static int ct_expect_help(struct sk_buff *skb, unsigned int protoff, + struct nf_conn *ct, enum ip_conntrack_info ctinfo) +{ + enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo); + struct nft_ct_expect_data *expect_data; + struct nf_conntrack_expect *exp; + int ret = NF_ACCEPT; + u16 l3num; + + if (nf_ct_is_confirmed(ct)) + return NF_ACCEPT; + + expect_data = nfct_help_data(ct); + if (!expect_data) + return NF_ACCEPT; + + if (expect_data->dir != dir) + return NF_ACCEPT; + + exp = nf_ct_expect_alloc(ct); + if (!exp) + return NF_DROP; + + if (expect_data->obj.l3num == NFPROTO_INET) + l3num = nf_ct_l3num(ct); + else + l3num = expect_data->obj.l3num; + + nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT, l3num, + &ct->tuplehash[!dir].tuple.src.u3, + &ct->tuplehash[!dir].tuple.dst.u3, + expect_data->obj.l4proto, NULL, &expect_data->obj.dport); + exp->timeout += expect_data->obj.timeout; + + if (nf_ct_expect_related(exp, 0) != 0) + ret = NF_ACCEPT; + + nf_ct_expect_put(exp); + + return ret; +} + +static const struct nf_conntrack_expect_policy nft_ct_expect_helper_policy = { + .max_expected = NF_CT_EXPECT_MAX_CNT, +}; + +/* No need to register this helper, this is internal. */ +static struct nf_conntrack_helper nft_ct_expect_helper = { + .name = "nft_ct_expect", + .me = THIS_MODULE, + .expect_policy = &nft_ct_expect_helper_policy, + .help = ct_expect_help, +}; + static int nft_ct_expect_obj_init(const struct nft_ctx *ctx, const struct nlattr * const tb[], struct nft_object *obj) { struct nft_ct_expect_obj *priv = nft_obj_data(obj); + int err; + + NF_CT_HELPER_BUILD_BUG_ON(sizeof(struct nft_ct_expect_data)); if (!tb[NFTA_CT_EXPECT_L4PROTO] || !tb[NFTA_CT_EXPECT_DPORT] || @@ -1257,15 +1330,18 @@ static int nft_ct_expect_obj_init(const struct nft_ctx *ctx, return -EOPNOTSUPP; } + err = nft_ct_expect_timeout_get(tb[NFTA_CT_EXPECT_TIMEOUT], &priv->timeout); + if (err) + return err; + priv->dport = nla_get_be16(tb[NFTA_CT_EXPECT_DPORT]); - priv->timeout = nla_get_u32(tb[NFTA_CT_EXPECT_TIMEOUT]); priv->size = nla_get_u8(tb[NFTA_CT_EXPECT_SIZE]); return nf_ct_netns_get(ctx->net, ctx->family); } static void nft_ct_expect_obj_destroy(const struct nft_ctx *ctx, - struct nft_object *obj) + struct nft_object *obj) { nf_ct_netns_put(ctx->net, ctx->family); } @@ -1278,7 +1354,7 @@ static int nft_ct_expect_obj_dump(struct sk_buff *skb, if (nla_put_be16(skb, NFTA_CT_EXPECT_L3PROTO, htons(priv->l3num)) || nla_put_u8(skb, NFTA_CT_EXPECT_L4PROTO, priv->l4proto) || nla_put_be16(skb, NFTA_CT_EXPECT_DPORT, priv->dport) || - nla_put_u32(skb, NFTA_CT_EXPECT_TIMEOUT, priv->timeout) || + nla_put_u32(skb, NFTA_CT_EXPECT_TIMEOUT, jiffies_to_msecs(priv->timeout)) || nla_put_u8(skb, NFTA_CT_EXPECT_SIZE, priv->size)) return -1; @@ -1290,11 +1366,9 @@ static void nft_ct_expect_obj_eval(struct nft_object *obj, const struct nft_pktinfo *pkt) { const struct nft_ct_expect_obj *priv = nft_obj_data(obj); - struct nf_conntrack_expect *exp; + struct nft_ct_expect_data *expect_data; enum ip_conntrack_info ctinfo; struct nf_conn_help *help; - enum ip_conntrack_dir dir; - u16 l3num = priv->l3num; struct nf_conn *ct; ct = nf_ct_get(pkt->skb, &ctinfo); @@ -1302,38 +1376,28 @@ static void nft_ct_expect_obj_eval(struct nft_object *obj, regs->verdict.code = NFT_BREAK; return; } - dir = CTINFO2DIR(ctinfo); help = nfct_help(ct); - if (!help) - help = nf_ct_helper_ext_add(ct, GFP_ATOMIC); - if (!help) { - regs->verdict.code = NF_DROP; - return; - } - - if (help->expecting[NF_CT_EXPECT_CLASS_DEFAULT] >= priv->size) { + if (help) { regs->verdict.code = NFT_BREAK; return; } - if (l3num == NFPROTO_INET) - l3num = nf_ct_l3num(ct); - exp = nf_ct_expect_alloc(ct); - if (exp == NULL) { + help = nf_ct_helper_ext_add(ct, GFP_ATOMIC); + if (!help) { regs->verdict.code = NF_DROP; return; } - nf_ct_expect_init(exp, NF_CT_EXPECT_CLASS_DEFAULT, l3num, - &ct->tuplehash[!dir].tuple.src.u3, - &ct->tuplehash[!dir].tuple.dst.u3, - priv->l4proto, NULL, &priv->dport); - exp->timeout += priv->timeout * HZ; - if (nf_ct_expect_related(exp, 0) != 0) - regs->verdict.code = NF_DROP; + expect_data = nfct_help_data(ct); + if (!expect_data) { + regs->verdict.code = NFT_BREAK; + return; + } + expect_data->obj = *priv; + expect_data->dir = CTINFO2DIR(ctinfo); - nf_ct_expect_put(exp); + rcu_assign_pointer(help->helper, &nft_ct_expect_helper); } static const struct nla_policy nft_ct_expect_policy[NFTA_CT_EXPECT_MAX + 1] = { @@ -1413,6 +1477,7 @@ static void __exit nft_ct_module_exit(void) nft_unregister_obj(&nft_ct_helper_obj_type); nft_unregister_expr(&nft_notrack_type); nft_unregister_expr(&nft_ct_type); + nf_conntrack_helper_release(&nft_ct_expect_helper); } module_init(nft_ct_module_init); diff --git a/net/netfilter/nft_fwd_netdev.c b/net/netfilter/nft_fwd_netdev.c index eceab479bd8c..84ae30cd208b 100644 --- a/net/netfilter/nft_fwd_netdev.c +++ b/net/netfilter/nft_fwd_netdev.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include diff --git a/net/netfilter/nft_set_rbtree.c b/net/netfilter/nft_set_rbtree.c index 1270b472e333..c00ac231ccda 100644 --- a/net/netfilter/nft_set_rbtree.c +++ b/net/netfilter/nft_set_rbtree.c @@ -958,7 +958,8 @@ static void nft_rbtree_gc_queue(struct nft_set *set) } gc = nft_trans_gc_catchall_sync(gc); - nft_trans_gc_queue_sync_done(gc); + if (gc) + nft_trans_gc_queue_sync_done(gc); } static u64 nft_rbtree_privsize(const struct nlattr * const nla[], diff --git a/net/netfilter/xt_NETMAP.c b/net/netfilter/xt_NETMAP.c index cb2ee80d84fa..591a6af6c61f 100644 --- a/net/netfilter/xt_NETMAP.c +++ b/net/netfilter/xt_NETMAP.c @@ -42,6 +42,7 @@ netmap_tg6(struct sk_buff *skb, const struct xt_action_param *par) netmask.ip6[i]; } + memset(&newrange, 0, sizeof(newrange)); newrange.flags = range->flags | NF_NAT_RANGE_MAP_IPS; newrange.min_addr = new_addr; newrange.max_addr = new_addr; @@ -89,8 +90,7 @@ netmap_tg4(struct sk_buff *skb, const struct xt_action_param *par) new_ip = ip_hdr(skb)->saddr & ~netmask; new_ip |= mr->range[0].min_ip & netmask; - memset(&newrange.min_addr, 0, sizeof(newrange.min_addr)); - memset(&newrange.max_addr, 0, sizeof(newrange.max_addr)); + memset(&newrange, 0, sizeof(newrange)); newrange.flags = mr->range[0].flags | NF_NAT_RANGE_MAP_IPS; newrange.min_addr.ip = new_ip; newrange.max_addr.ip = new_ip; diff --git a/net/netfilter/xt_recent.c b/net/netfilter/xt_recent.c index 588a5e6ad899..44b11e3c1811 100644 --- a/net/netfilter/xt_recent.c +++ b/net/netfilter/xt_recent.c @@ -649,14 +649,15 @@ static void __net_exit recent_proc_net_exit(struct net *net) /* recent_net_exit() is called before recent_mt_destroy(). Make sure * that the parent xt_recent proc entry is empty before trying to - * remove it. + * remove it. Use recent_mutex instead of recent_lock since + * remove_proc_entry() may sleep. */ - spin_lock_bh(&recent_lock); + mutex_lock(&recent_mutex); list_for_each_entry(t, &recent_net->tables, list) remove_proc_entry(t->name, recent_net->xt_recent); recent_net->xt_recent = NULL; - spin_unlock_bh(&recent_lock); + mutex_unlock(&recent_mutex); remove_proc_entry("xt_recent", net->proc_net); } diff --git a/net/netlink/af_netlink.c b/net/netlink/af_netlink.c index fb7785a59af5..9e1f64f18e3f 100644 --- a/net/netlink/af_netlink.c +++ b/net/netlink/af_netlink.c @@ -1032,8 +1032,9 @@ static int netlink_bind(struct socket *sock, struct sockaddr *addr, netlink_insert(sk, nladdr->nl_pid) : netlink_autobind(sock); if (err) { + netlink_unlock_table(); netlink_undo_bind(BITS_PER_TYPE(u32), groups, sk); - goto unlock; + return err; } } diff --git a/net/netrom/nr_out.c b/net/netrom/nr_out.c index 150cb4263d31..1c6b4386c86b 100644 --- a/net/netrom/nr_out.c +++ b/net/netrom/nr_out.c @@ -135,7 +135,12 @@ void nr_send_nak_frame(struct sock *sk) nr->condition &= ~NR_COND_ACK_PENDING; nr->vl = nr->vr; - nr_stop_t1timer(sk); + /* + * The frame just sent again, and any sent after it, still wait for + * an acknowledgment: keep T1 running so that losing this copy too + * is noticed. + */ + nr_start_t1timer(sk); } void nr_kick(struct sock *sk) diff --git a/net/netrom/nr_subr.c b/net/netrom/nr_subr.c index c3bbd5880850..144d9c5ea5b1 100644 --- a/net/netrom/nr_subr.c +++ b/net/netrom/nr_subr.c @@ -61,9 +61,9 @@ void nr_frames_acked(struct sock *sk, unsigned short nr) } /* - * Requeue all the un-ack-ed frames on the output queue to be picked - * up by nr_kick called from the timer. This arrangement handles the - * possibility of an empty output queue. + * Requeue all the un-ack-ed frames on the output queue to be sent + * again by nr_kick(), which the T1 timer calls next. This arrangement + * handles the possibility of an empty output queue. */ void nr_requeue_frames(struct sock *sk) { diff --git a/net/netrom/nr_timer.c b/net/netrom/nr_timer.c index b3a62b1f3a09..0be44b88f894 100644 --- a/net/netrom/nr_timer.c +++ b/net/netrom/nr_timer.c @@ -171,6 +171,8 @@ static void nr_t4timer_expiry(struct timer_list *t) bh_lock_sock(sk); nr_sk(sk)->condition &= ~NR_COND_PEER_RX_BUSY; + /* the peer is assumed ready again: send what was held back */ + nr_kick(sk); bh_unlock_sock(sk); sock_put(sk); } @@ -238,6 +240,8 @@ static void nr_t1timer_expiry(struct timer_list *t) } else { nr->n2count++; nr_requeue_frames(sk); + /* nothing else sends them if the peer stays silent */ + nr_kick(sk); } break; } diff --git a/net/netrom/sysctl_net_netrom.c b/net/netrom/sysctl_net_netrom.c index 7dc0fa628f2e..bccc165a4a2e 100644 --- a/net/netrom/sysctl_net_netrom.c +++ b/net/netrom/sysctl_net_netrom.c @@ -15,16 +15,17 @@ static int min_quality[] = {0}, max_quality[] = {255}; static int min_obs[] = {0}, max_obs[] = {255}; static int min_ttl[] = {0}, max_ttl[] = {255}; -static int min_t1[] = {5 * HZ}; -static int max_t1[] = {600 * HZ}; +/* The timers are given in milliseconds */ +static int min_t1[] = {5 * MSEC_PER_SEC}; +static int max_t1[] = {600 * MSEC_PER_SEC}; static int min_n2[] = {2}, max_n2[] = {127}; -static int min_t2[] = {1 * HZ}; -static int max_t2[] = {60 * HZ}; -static int min_t4[] = {1 * HZ}; -static int max_t4[] = {1000 * HZ}; +static int min_t2[] = {1 * MSEC_PER_SEC}; +static int max_t2[] = {60 * MSEC_PER_SEC}; +static int min_t4[] = {1 * MSEC_PER_SEC}; +static int max_t4[] = {1000 * MSEC_PER_SEC}; static int min_window[] = {1}, max_window[] = {127}; -static int min_idle[] = {0 * HZ}; -static int max_idle[] = {65535 * HZ}; +static int min_idle[] = {0 * MSEC_PER_SEC}; +static int max_idle[] = {65535 * MSEC_PER_SEC}; static int min_route[] = {0}, max_route[] = {1}; static int min_fails[] = {1}, max_fails[] = {10}; static int min_reset[] = {0}, max_reset[] = {1}; diff --git a/net/nsh/nsh.c b/net/nsh/nsh.c index bfb7758063f3..dd4de50fc38c 100644 --- a/net/nsh/nsh.c +++ b/net/nsh/nsh.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -84,6 +85,12 @@ static struct sk_buff *nsh_gso_segment(struct sk_buff *skb, skb_reset_network_header(skb); + /* NSH can carry NSH (directly, or in an inner Ethernet frame): + * limit the recursion, as IPv4 and IPv6 do. + */ + if (unlikely(gso_recursion_inc_test(skb, IP_TUNNEL_RECURSION_LIMIT))) + goto out; + outer_proto = skb->protocol; outer_hlen = skb_mac_header_len(skb); mac_len = skb->mac_len; diff --git a/net/openvswitch/flow.c b/net/openvswitch/flow.c index 868d9fdf3afd..03a41594fcec 100644 --- a/net/openvswitch/flow.c +++ b/net/openvswitch/flow.c @@ -370,11 +370,28 @@ static void get_ipv6_ext_hdrs(struct sk_buff *skb, struct ipv6hdr *nh, return; } + if (next_type == IPPROTO_FRAGMENT) { + struct frag_hdr _fh, *fh; + + fh = skb_header_pointer(skb, start, sizeof(_fh), &_fh); + if (!fh) + break; + /* Only the first fragment has the headers that follow. */ + if (fh->frag_off & htons(IP6_OFFSET)) + break; + start += sizeof(_fh); + next_type = fh->nexthdr; + continue; + } + hp = skb_header_pointer(skb, start, sizeof(_hdr), &_hdr); if (!hp) break; + if (next_type == IPPROTO_AH) + start += ipv6_authlen(hp); + else + start += ipv6_optlen(hp); next_type = hp->nexthdr; - start += ipv6_optlen(hp); } } diff --git a/net/rds/rdma.c b/net/rds/rdma.c index 062c12d9318e..8c13a0e4d8df 100644 --- a/net/rds/rdma.c +++ b/net/rds/rdma.c @@ -960,8 +960,11 @@ int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm, } ret = rds_pin_pages(args->local_addr, 1, &page, 1); - if (ret != 1) + if (ret != 1) { + /* A failed pin can leave a stale page pointer. */ + page = NULL; goto err; + } ret = 0; sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr)); diff --git a/net/rose/rose_in.c b/net/rose/rose_in.c index befb4c55e459..b58f3b2700a6 100644 --- a/net/rose/rose_in.c +++ b/net/rose/rose_in.c @@ -194,6 +194,27 @@ static int rose_state3_machine(struct sock *sk, struct sk_buff *skb, int framety if (atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1)) rose->condition |= ROSE_COND_OWN_RX_BUSY; + } else { + /* + * A DATA packet was lost on the way: a relay dropped + * it, or a link was reset under it. ROSE never sends a + * DATA packet again, so the window of the sender would + * stay full and the call would hang. Acknowledge what + * arrived in sequence, then reset the call (X.25: + * invalid P(S)); the sender then sends its + * unacknowledged packets again. + */ + rose_enquiry_response(sk); + rose_write_internal(sk, ROSE_RESET_REQUEST); + rose->condition = 0x00; + rose->vs = 0; + rose->vr = 0; + rose->va = 0; + rose->vl = 0; + rose->state = ROSE_STATE_4; + rose_start_t2timer(sk); + rose_stop_idletimer(sk); + break; } /* * If the window is full, ack the frame, else start the diff --git a/net/sched/act_ife.c b/net/sched/act_ife.c index cd8c8418ec0d..d273ed78ad07 100644 --- a/net/sched/act_ife.c +++ b/net/sched/act_ife.c @@ -50,8 +50,7 @@ int ife_encode_meta_u16(u16 metaval, void *skbdata, struct tcf_meta_info *mi) edata = *(u16 *)mi->metaval; else if (metaval) edata = metaval; - - if (!edata) /* will not encode */ + else return 0; edata = htons(edata); @@ -94,8 +93,7 @@ int ife_encode_meta_u32(u32 metaval, void *skbdata, struct tcf_meta_info *mi) edata = *(u32 *)mi->metaval; else if (metaval) edata = metaval; - - if (!edata) /* will not encode */ + else return 0; edata = htonl(edata); @@ -873,13 +871,16 @@ static int tcf_ife_encode(struct sk_buff *skb, const struct tc_action *a, * is an Ethernet header because the skb could've been redirected with mirred * from a non-Ethernet device. */ -static bool tcf_ife_is_eth_skb(const struct sk_buff *skb) +static bool tcf_ife_is_eth_skb(struct sk_buff *skb) { if (skb->dev->type != ARPHRD_ETHER && skb->dev->type != ARPHRD_LOOPBACK) return false; - return !skb_at_tc_ingress(skb) || skb->mac_len == ETH_HLEN; + if (skb_at_tc_ingress(skb)) + return skb->mac_len == ETH_HLEN; + + return pskb_may_pull(skb, ETH_HLEN); } TC_INDIRECT_SCOPE int tcf_ife_act(struct sk_buff *skb, diff --git a/net/sched/sch_teql.c b/net/sched/sch_teql.c index d0e81d1d553c..cb26c6ce5ef1 100644 --- a/net/sched/sch_teql.c +++ b/net/sched/sch_teql.c @@ -198,6 +198,8 @@ static int teql_qdisc_init(struct Qdisc *sch, struct nlattr *opt, struct Qdisc *first; unsigned long flags; + skb_queue_head_init(&q->q); + if (dev->hard_header_len > m->dev->hard_header_len) return -EINVAL; @@ -209,9 +211,12 @@ static int teql_qdisc_init(struct Qdisc *sch, struct nlattr *opt, return -EOPNOTSUPP; } - q->m = m; + if (dev_net(dev) != dev_net(m->dev)) { + NL_SET_ERR_MSG_MOD(extack, "teql master is in a different network namespace"); + return -EOPNOTSUPP; + } - skb_queue_head_init(&q->q); + q->m = m; raw_spin_lock_irqsave(&m->slaves_lock, flags); first = rcu_dereference_protected(m->slaves, lockdep_is_held(&m->slaves_lock)); diff --git a/net/sctp/sm_make_chunk.c b/net/sctp/sm_make_chunk.c index 3518f997a7b8..db9406f4681c 100644 --- a/net/sctp/sm_make_chunk.c +++ b/net/sctp/sm_make_chunk.c @@ -2867,7 +2867,6 @@ struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc, int addr_param_len = 0; union sctp_addr *addr; int totallen = 0, i; - int del_pickup = 0; struct sctp_af *af; void *addr_buf; @@ -2882,16 +2881,21 @@ struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc, totallen += addr_param_len; addr_buf += af->sockaddr_len; - if (asoc->asconf_addr_del_pending && !del_pickup) { - /* reuse the parameter length from the same scope one */ - totallen += paramlen; - totallen += addr_param_len; - del_pickup = 1; - - pr_debug("%s: picked same-scope del_pending addr, " - "totallen for all addresses is %d\n", - __func__, totallen); - } + } + + if (asoc->asconf_addr_del_pending) { + /* The DEL_IP parameter is serialized from the pending address + * itself below; account for its own address family, which may + * differ from the added ones. + */ + addr = asoc->asconf_addr_del_pending; + af = sctp_get_af_specific(addr->v4.sin_family); + totallen += paramlen; + totallen += af->to_addr_param(addr, &addr_param); + + pr_debug("%s: picked del_pending addr, " + "totallen for all addresses is %d\n", + __func__, totallen); } /* Create an asconf chunk with the required length. */ @@ -2914,7 +2918,7 @@ struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc, addr_buf += af->sockaddr_len; } - if (flags == SCTP_PARAM_ADD_IP && del_pickup) { + if (flags == SCTP_PARAM_ADD_IP && asoc->asconf_addr_del_pending) { addr = asoc->asconf_addr_del_pending; af = sctp_get_af_specific(addr->v4.sin_family); addr_param_len = af->to_addr_param(addr, &addr_param); @@ -3157,9 +3161,12 @@ static __be16 sctp_process_asconf_param(struct sctp_association *asoc, * packet MUST be deleted. */ if (af->is_any(&addr)) { - sctp_assoc_set_primary(asoc, asconf->transport); - sctp_assoc_del_nonprimary_peers(asoc, - asconf->transport); + peer = sctp_assoc_lookup_paddr(asoc, &asconf->source); + if (!peer) + return SCTP_ERROR_REQ_REFUSED; + sctp_assoc_set_primary(asoc, peer); + sctp_assoc_del_nonprimary_peers(asoc, peer); + asconf->transport = peer; return SCTP_ERROR_NO_ERROR; } @@ -3172,13 +3179,9 @@ static __be16 sctp_process_asconf_param(struct sctp_association *asoc, if (!peer) return SCTP_ERROR_DNS_FAILED; - /* Don't free asconf->transport; a later wildcard DEL-IP - * parameter reuses it. - */ - if (peer == asconf->transport) - return SCTP_ERROR_REQ_REFUSED; - sctp_assoc_rm_peer(asoc, peer); + if (asconf->transport == peer) + asconf->transport = asoc->peer.primary_path; break; case SCTP_PARAM_SET_PRIMARY: /* ADDIP Section 4.2.4 diff --git a/net/sctp/sm_statefuns.c b/net/sctp/sm_statefuns.c index ff72f7467630..d747fda4fb60 100644 --- a/net/sctp/sm_statefuns.c +++ b/net/sctp/sm_statefuns.c @@ -1122,9 +1122,11 @@ enum sctp_disposition sctp_sf_send_reconf(struct net *net, return SCTP_DISPOSITION_DELETE_TCB; } - sctp_chunk_hold(asoc->strreset_chunk); - sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, - SCTP_CHUNK(asoc->strreset_chunk)); + if (!sctp_chunk_pending(asoc->strreset_chunk)) { + sctp_chunk_hold(asoc->strreset_chunk); + sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, + SCTP_CHUNK(asoc->strreset_chunk)); + } sctp_add_cmd_sf(commands, SCTP_CMD_STRIKE, SCTP_TRANSPORT(transport)); return SCTP_DISPOSITION_CONSUME; @@ -6194,9 +6196,11 @@ enum sctp_disposition sctp_sf_t4_timer_expire( * chunk, it MUST be the same (including its serial number) as the last * ASCONF sent. */ - sctp_chunk_hold(asoc->addip_last_asconf); - sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, - SCTP_CHUNK(asoc->addip_last_asconf)); + if (!sctp_chunk_pending(asoc->addip_last_asconf)) { + sctp_chunk_hold(asoc->addip_last_asconf); + sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, + SCTP_CHUNK(asoc->addip_last_asconf)); + } /* ADDIP 4.1 B5) Restart the T-4 RTO timer. Note that if a different * destination is selected, then the RTO used will be that of the new diff --git a/net/sctp/socket.c b/net/sctp/socket.c index 5cbc364a5357..54e78833c57f 100644 --- a/net/sctp/socket.c +++ b/net/sctp/socket.c @@ -808,7 +808,6 @@ static int sctp_send_asconf_del_ip(struct sock *sk, struct sctp_sockaddr_entry *saddr; int i; int retval = 0; - int stored = 0; chunk = NULL; sp = sctp_sk(sk); @@ -821,6 +820,7 @@ static int sctp_send_asconf_del_ip(struct sock *sk, __func__, sk, addrs, addrcnt); list_for_each_entry(asoc, &ep->asocs, asocs) { + int stored = 0; if (!asoc->peer.asconf_capable) continue; diff --git a/net/sctp/stream.c b/net/sctp/stream.c index 8826dd60e59e..8fc5dc3c352e 100644 --- a/net/sctp/stream.c +++ b/net/sctp/stream.c @@ -749,6 +749,7 @@ struct sctp_chunk *sctp_process_strreset_tsnreq( */ max_tsn_seen = sctp_tsnmap_get_max_tsn_seen(&asoc->peer.tsn_map); asoc->stream.si->report_ftsn(&asoc->ulpq, max_tsn_seen); + asoc->stream.si->abort_pd(&asoc->ulpq, GFP_ATOMIC); /* G1: Compute an appropriate value for the Receiver's Next TSN -- the * TSN that the peer should use to send the next DATA chunk. The @@ -1028,6 +1029,7 @@ struct sctp_chunk *sctp_process_strreset_resp( LIST_HEAD(temp); asoc->stream.si->report_ftsn(&asoc->ulpq, mtsn); + asoc->stream.si->abort_pd(&asoc->ulpq, GFP_ATOMIC); sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL, diff --git a/net/sctp/stream_interleave.c b/net/sctp/stream_interleave.c index 840f24045ae2..1113b3455369 100644 --- a/net/sctp/stream_interleave.c +++ b/net/sctp/stream_interleave.c @@ -1203,28 +1203,21 @@ static void sctp_report_fwdtsn(struct sctp_ulpq *ulpq, __u32 ftsn) sctp_ulpq_abort_pd(ulpq, GFP_ATOMIC); } -static void sctp_intl_reasm_flushtsn(struct sctp_ulpq *ulpq, __u32 ftsn) +static void sctp_intl_reasm_flush_mid(struct sk_buff_head *reasm, __u16 sid, + __u32 mid) { struct sk_buff *pos, *tmp; - skb_queue_walk_safe(&ulpq->reasm, pos, tmp) { + skb_queue_walk_safe(reasm, pos, tmp) { struct sctp_ulpevent *event = sctp_skb2event(pos); - __u32 tsn = event->tsn; - if (TSN_lte(tsn, ftsn)) { - __skb_unlink(pos, &ulpq->reasm); - sctp_ulpevent_free(event); - } - } - - skb_queue_walk_safe(&ulpq->reasm_uo, pos, tmp) { - struct sctp_ulpevent *event = sctp_skb2event(pos); - __u32 tsn = event->tsn; + if (event->stream < sid) + continue; + if (event->stream > sid || MID_lt(mid, event->mid)) + break; - if (TSN_lte(tsn, ftsn)) { - __skb_unlink(pos, &ulpq->reasm_uo); - sctp_ulpevent_free(event); - } + __skb_unlink(pos, reasm); + sctp_ulpevent_free(event); } } @@ -1232,11 +1225,6 @@ static void sctp_report_iftsn(struct sctp_ulpq *ulpq, __u32 ftsn) { /* Move the Cumulattive TSN Ack ahead. */ sctp_tsnmap_skip(&ulpq->asoc->peer.tsn_map, ftsn); - /* purge the fragmentation queue */ - sctp_intl_reasm_flushtsn(ulpq, ftsn); - /* abort only when it's for all data */ - if (ftsn == sctp_tsnmap_get_max_tsn_seen(&ulpq->asoc->peer.tsn_map)) - sctp_intl_abort_pd(ulpq, GFP_ATOMIC); } static void sctp_handle_fwdtsn(struct sctp_ulpq *ulpq, struct sctp_chunk *chunk) @@ -1255,11 +1243,12 @@ static void sctp_intl_skip(struct sctp_ulpq *ulpq, __u16 sid, __u32 mid, struct sctp_stream *stream = &ulpq->asoc->stream; if (flags & SCTP_FTSN_U_BIT) { - if (sin->pd_mode_uo && MID_lt(sin->mid_uo, mid)) { + if (sin->pd_mode_uo && !MID_lt(mid, sin->mid_uo)) { sin->pd_mode_uo = 0; - sctp_intl_stream_abort_pd(ulpq, sid, mid, 0x1, + sctp_intl_stream_abort_pd(ulpq, sid, sin->mid_uo, 0x1, GFP_ATOMIC); } + sctp_intl_reasm_flush_mid(&ulpq->reasm_uo, sid, mid); return; } @@ -1268,9 +1257,10 @@ static void sctp_intl_skip(struct sctp_ulpq *ulpq, __u16 sid, __u32 mid, if (sin->pd_mode) { sin->pd_mode = 0; - sctp_intl_stream_abort_pd(ulpq, sid, mid, 0x0, GFP_ATOMIC); + sctp_intl_stream_abort_pd(ulpq, sid, sin->mid, 0x0, GFP_ATOMIC); } + sctp_intl_reasm_flush_mid(&ulpq->reasm, sid, mid); sctp_mid_skip(stream, in, sid, mid); sctp_intl_reap_ordered(ulpq, sid); diff --git a/net/smc/af_smc.c b/net/smc/af_smc.c index 1db56310fda0..fb88766595de 100644 --- a/net/smc/af_smc.c +++ b/net/smc/af_smc.c @@ -976,7 +976,7 @@ static int smc_connect_fallback(struct smc_sock *smc, int reason_code) smc_copy_sock_settings_to_clc(smc); smc->connect_nonblock = 0; if (smc->sk.sk_state == SMC_INIT) - smc->sk.sk_state = SMC_ACTIVE; + smp_store_release(&smc->sk.sk_state, SMC_ACTIVE); return 0; } @@ -1009,14 +1009,15 @@ static void smc_conn_abort(struct smc_sock *smc, int local_first) { struct smc_connection *conn = &smc->conn; struct smc_link_group *lgr = conn->lgr; - bool lgr_valid = false; - - if (smc_conn_lgr_valid(conn)) - lgr_valid = true; + bool lgr_valid = local_first && smc_conn_lgr_valid(conn); + if (lgr_valid) + smc_lgr_hold(lgr); /* lgr_put below */ smc_conn_free(conn); - if (local_first && lgr_valid) + if (lgr_valid) { smc_lgr_cleanup_early(lgr); + smc_lgr_put(lgr); + } } /* check if there is a rdma device available for this connection. */ @@ -1381,7 +1382,7 @@ static int smc_connect_rdma(struct smc_sock *smc, smc_copy_sock_settings_to_clc(smc); smc->connect_nonblock = 0; if (smc->sk.sk_state == SMC_INIT) - smc->sk.sk_state = SMC_ACTIVE; + smp_store_release(&smc->sk.sk_state, SMC_ACTIVE); return 0; connect_abort: @@ -1484,7 +1485,7 @@ static int smc_connect_ism(struct smc_sock *smc, smc_copy_sock_settings_to_clc(smc); smc->connect_nonblock = 0; if (smc->sk.sk_state == SMC_INIT) - smc->sk.sk_state = SMC_ACTIVE; + smp_store_release(&smc->sk.sk_state, SMC_ACTIVE); return 0; connect_abort: @@ -1955,7 +1956,7 @@ static void smc_listen_out_connected(struct smc_sock *new_smc) struct sock *newsmcsk = &new_smc->sk; if (newsmcsk->sk_state == SMC_INIT) - newsmcsk->sk_state = SMC_ACTIVE; + smp_store_release(&newsmcsk->sk_state, SMC_ACTIVE); smc_listen_out(new_smc); } @@ -1969,7 +1970,7 @@ static void smc_listen_out_err(struct smc_sock *new_smc) this_cpu_inc(net->smc.smc_stats->srv_hshake_err_cnt); if (newsmcsk->sk_state == SMC_INIT) sock_put(&new_smc->sk); /* passive closing */ - newsmcsk->sk_state = SMC_CLOSED; + smp_store_release(&newsmcsk->sk_state, SMC_CLOSED); smc_listen_out(new_smc); } diff --git a/net/smc/smc.h b/net/smc/smc.h index 1425fd756d34..270736973aaa 100644 --- a/net/smc/smc.h +++ b/net/smc/smc.h @@ -196,6 +196,7 @@ struct smc_connection { struct rb_node alert_node; struct smc_link_group *lgr; /* link group of connection */ struct smc_link *lnk; /* assigned SMC-R link */ + bool is_smcd; /* SMC-R or SMC-D connection */ u32 alert_token_local; /* unique conn. id */ u8 peer_rmbe_idx; /* from tcp handshake */ int peer_rmbe_size; /* size of peer rx buffer */ diff --git a/net/smc/smc_close.c b/net/smc/smc_close.c index bb0313ef5f7c..cbe1cdf01aed 100644 --- a/net/smc/smc_close.c +++ b/net/smc/smc_close.c @@ -154,6 +154,7 @@ void smc_close_active_abort(struct smc_sock *smc) if (sk->sk_state != SMC_PEERABORTWAIT) break; sk->sk_state = SMC_CLOSED; + sk->sk_prot->unhash(sk); smc_conn_free(&smc->conn); release_clcsock = true; sock_put(sk); /* passive closing */ @@ -165,6 +166,7 @@ void smc_close_active_abort(struct smc_sock *smc) if (sk->sk_state != SMC_PEERABORTWAIT) break; sk->sk_state = SMC_CLOSED; + sk->sk_prot->unhash(sk); smc_conn_free(&smc->conn); release_clcsock = true; break; @@ -367,6 +369,17 @@ static void smc_close_passive_work(struct work_struct *work) lock_sock(sk); old_state = sk->sk_state; + if (conn->freed) { + /* conn->freed is set under the socket lock, which is + * held here as well, so this cannot race with the free; the + * state machine and its postponed sock_put() are not owed + * anymore + */ + release_sock(sk); + sock_put(sk); /* sock_hold done by schedulers of close_work */ + return; + } + rxflags = &conn->local_rx_ctrl.conn_state_flags; if (rxflags->peer_conn_abort) { /* peer has not received all data */ @@ -433,6 +446,7 @@ static void smc_close_passive_work(struct work_struct *work) sk->sk_state_change(sk); if ((sk->sk_state == SMC_CLOSED) && (sock_flag(sk, SOCK_DEAD) || !sk->sk_socket)) { + sk->sk_prot->unhash(sk); smc_conn_free(conn); if (smc->clcsock) release_clcsock = true; diff --git a/net/smc/smc_core.c b/net/smc/smc_core.c index fff84df00cab..c34c7340ee3f 100644 --- a/net/smc/smc_core.c +++ b/net/smc/smc_core.c @@ -80,16 +80,21 @@ static void smc_ibdev_cnt_dec(struct smc_link *lnk) static void smc_lgr_schedule_free_work(struct smc_link_group *lgr) { + spinlock_t *lgr_lock; + /* client link group creation always follows the server link group * creation. For client use a somewhat higher removal delay time, * otherwise there is a risk of out-of-sync link groups. */ + smc_lgr_list_head(lgr, &lgr_lock); + spin_lock_bh(lgr_lock); if (!lgr->freeing) { mod_delayed_work(system_percpu_wq, &lgr->free_work, (!lgr->is_smcd && lgr->role == SMC_CLNT) ? SMC_LGR_FREE_DELAY_CLNT : SMC_LGR_FREE_DELAY_SERV); } + spin_unlock_bh(lgr_lock); } /* Register connection's alert token in our lookup structure. @@ -679,19 +684,34 @@ int smcd_nl_get_lgr(struct sk_buff *skb, struct netlink_callback *cb) return skb->len; } -void smc_lgr_cleanup_early(struct smc_link_group *lgr) +/* Claim a link group for termination. Only one context can succeed: the + * lgr is removed from its list and marked freeing under lgr_lock. + * Returns false if @lgr is NULL or another context owns it. + */ +static bool smc_lgr_claim(struct smc_link_group *lgr) { spinlock_t *lgr_lock; if (!lgr) - return; - + return false; smc_lgr_list_head(lgr, &lgr_lock); spin_lock_bh(lgr_lock); + if (lgr->freeing || lgr->terminating || list_empty(&lgr->list)) { + spin_unlock_bh(lgr_lock); + return false; + } /* do not use this link group for new connections */ - if (!list_empty(&lgr->list)) - list_del_init(&lgr->list); + list_del_init(&lgr->list); + lgr->freeing = 1; spin_unlock_bh(lgr_lock); + return true; +} + +/* The caller must keep @lgr alive for the duration of the call. */ +void smc_lgr_cleanup_early(struct smc_link_group *lgr) +{ + if (!smc_lgr_claim(lgr)) + return; /* another context owns the termination */ __smc_lgr_terminate(lgr, true); } @@ -1265,10 +1285,12 @@ void smc_conn_free(struct smc_connection *conn) if (current_work() != &conn->abort_work) cancel_work_sync(&conn->abort_work); } - if (!list_empty(&lgr->list)) { + /* The handshake can retry another device or SMC version with this + * connection, so it must never stay registered in an lgr it left. + */ + if (!list_empty(&lgr->list)) smc_buf_unuse(conn, lgr); /* allow buffer reuse */ - smc_lgr_unregister_conn(conn); - } + smc_lgr_unregister_conn(conn); if (!lgr->conns_num) smc_lgr_schedule_free_work(lgr); @@ -1503,6 +1525,15 @@ static void smc_conn_kill(struct smc_connection *conn, bool soft) { struct smc_sock *smc = container_of(conn, struct smc_sock, conn); + if (conn->freed) { + /* The connection was already freed, e.g. by a close or + * a handshake that fell back to TCP. Do not abort a socket + * that is no longer part of this link group. + */ + smc_lgr_unregister_conn(conn); + return; + } + if (conn->lgr->is_smcd && conn->lgr->peer_shutdown) conn->local_tx_ctrl.conn_state_flags.peer_conn_abort = 1; else @@ -1516,8 +1547,10 @@ static void smc_conn_kill(struct smc_connection *conn, bool soft) tasklet_kill(&conn->rx_tsklet); else tasklet_unlock_wait(&conn->rx_tsklet); - if (smc_ism_support_dmb_nocopy(conn->lgr->smcd)) + if (smc_ism_support_dmb_nocopy(conn->lgr->smcd)) { + smc->sk.sk_prot->unhash(&smc->sk); smcd_buf_detach(conn); + } } else { smc_cdc_wait_pend_tx_wr(conn); } @@ -1548,12 +1581,20 @@ static void __smc_lgr_terminate(struct smc_link_group *lgr, bool soft) struct smc_connection *conn; struct smc_sock *smc; struct rb_node *node; + spinlock_t *lgr_lock; - if (lgr->terminating) + smc_lgr_list_head(lgr, &lgr_lock); + spin_lock_bh(lgr_lock); + if (lgr->terminating) { + spin_unlock_bh(lgr_lock); return; /* lgr already terminating */ - /* cancel free_work sync, will terminate when lgr->freeing is set */ - cancel_delayed_work(&lgr->free_work); + } lgr->terminating = 1; + spin_unlock_bh(lgr_lock); + /* The lgr is claimed, so no new free_work can be armed; wait for + * one that is already queued or running. + */ + cancel_delayed_work_sync(&lgr->free_work); /* kill remaining link group connections */ read_lock_bh(&lgr->conns_lock); @@ -1564,7 +1605,11 @@ static void __smc_lgr_terminate(struct smc_link_group *lgr, bool soft) sock_hold(&smc->sk); /* sock_put below */ read_unlock_bh(&lgr->conns_lock); lock_sock(&smc->sk); - smc_conn_kill(conn, soft); + /* The connection may have been re-registered in another + * link group by a retried handshake in the meantime. + */ + if (conn->lgr == lgr) + smc_conn_kill(conn, soft); release_sock(&smc->sk); sock_put(&smc->sk); /* sock_hold above */ read_lock_bh(&lgr->conns_lock); @@ -1578,17 +1623,8 @@ static void __smc_lgr_terminate(struct smc_link_group *lgr, bool soft) /* unlink link group and schedule termination */ void smc_lgr_terminate_sched(struct smc_link_group *lgr) { - spinlock_t *lgr_lock; - - smc_lgr_list_head(lgr, &lgr_lock); - spin_lock_bh(lgr_lock); - if (list_empty(&lgr->list) || lgr->terminating || lgr->freeing) { - spin_unlock_bh(lgr_lock); + if (!smc_lgr_claim(lgr)) return; /* lgr already terminating */ - } - list_del_init(&lgr->list); - lgr->freeing = 1; - spin_unlock_bh(lgr_lock); schedule_work(&lgr->terminate_work); } @@ -2037,6 +2073,10 @@ int smc_conn_create(struct smc_sock *smc, struct smc_init_info *ini) goto out; } } + /* cache the connection type: smc_diag reads it after + * smc_conn_free() dropped the link group reference + */ + conn->is_smcd = conn->lgr->is_smcd; smc_lgr_hold(conn->lgr); /* lgr_put in smc_conn_free() */ if (!conn->lgr->is_smcd) smcr_link_hold(conn->lnk); /* link_put in smc_conn_free() */ diff --git a/net/smc/smc_core.h b/net/smc/smc_core.h index a5a78cbff341..fb14a0b3d994 100644 --- a/net/smc/smc_core.h +++ b/net/smc/smc_core.h @@ -297,9 +297,9 @@ struct smc_link_group { struct delayed_work free_work; /* delayed freeing of an lgr */ struct work_struct terminate_work; /* abnormal lgr termination */ struct workqueue_struct *tx_wq; /* wq for conn. tx workers */ - u8 sync_err : 1; /* lgr no longer fits to peer */ - u8 terminating : 1;/* lgr is terminating */ - u8 freeing : 1; /* lgr is being freed */ + u8 sync_err; /* lgr no longer fits to peer */ + u8 terminating; /* lgr is terminating */ + u8 freeing; /* lgr is being freed */ refcount_t refcnt; /* lgr reference count */ bool is_smcd; /* SMC-R or SMC-D */ diff --git a/net/smc/smc_diag.c b/net/smc/smc_diag.c index bf0beaa23bdb..15485a08d9a0 100644 --- a/net/smc/smc_diag.c +++ b/net/smc/smc_diag.c @@ -87,10 +87,10 @@ static int __smc_diag_dump(struct sock *sk, struct sk_buff *skb, r = nlmsg_data(nlh); smc_diag_msg_common_fill(r, sk); - r->diag_state = sk->sk_state; + r->diag_state = smp_load_acquire(&sk->sk_state); if (smc->use_fallback) r->diag_mode = SMC_DIAG_MODE_FALLBACK_TCP; - else if (smc_conn_lgr_valid(&smc->conn) && smc->conn.lgr->is_smcd) + else if (smc->conn.is_smcd) r->diag_mode = SMC_DIAG_MODE_SMCD; else r->diag_mode = SMC_DIAG_MODE_SMCR; @@ -103,6 +103,10 @@ static int __smc_diag_dump(struct sock *sk, struct sk_buff *skb, if (nla_put(skb, SMC_DIAG_FALLBACK, sizeof(fallback), &fallback) < 0) goto errout; + if (r->diag_state == SMC_INIT || r->diag_state == SMC_CLOSED || + smc->use_fallback) + goto out; + if ((req->diag_ext & (1 << (SMC_DIAG_CONNINFO - 1))) && smc->conn.alert_token_local) { struct smc_connection *conn = &smc->conn; @@ -154,8 +158,7 @@ static int __smc_diag_dump(struct sock *sk, struct sk_buff *skb, .lnk[0].link_id = link->link_id, }; - memcpy(linfo.lnk[0].ibname, link->smcibdev->ibdev->name, - sizeof(link->smcibdev->ibdev->name)); + memcpy(linfo.lnk[0].ibname, link->ibname, sizeof(link->ibname)); smc_gid_be16_convert(linfo.lnk[0].gid, link->gid); smc_gid_be16_convert(linfo.lnk[0].peer_gid, link->peer_gid); @@ -185,6 +188,7 @@ static int __smc_diag_dump(struct sock *sk, struct sk_buff *skb, goto errout; } +out: nlmsg_end(skb, nlh); return 0; diff --git a/net/smc/smc_sysctl.c b/net/smc/smc_sysctl.c index 2fab6456f765..7da98bd5287a 100644 --- a/net/smc/smc_sysctl.c +++ b/net/smc/smc_sysctl.c @@ -93,11 +93,9 @@ static struct ctl_table smc_table[] = { { .procname = "limit_smc_hs", .data = &init_net.smc.limit_smc_hs, - .maxlen = sizeof(int), + .maxlen = sizeof(bool), .mode = 0644, - .proc_handler = proc_dointvec_minmax, - .extra1 = SYSCTL_ZERO, - .extra2 = SYSCTL_ONE, + .proc_handler = proc_dobool, }, }; diff --git a/net/socket.c b/net/socket.c index 4ce6ddd768fb..fcf86543b2d4 100644 --- a/net/socket.c +++ b/net/socket.c @@ -2613,8 +2613,6 @@ static int ____sys_sendmsg(struct socket *sock, struct msghdr *msg_sys, flags &= ~MSG_INTERNAL_SENDMSG_FLAGS; msg_sys->msg_flags = flags; - if (sock->file->f_flags & O_NONBLOCK) - msg_sys->msg_flags |= MSG_DONTWAIT; /* * If this is sendmmsg() and current destination address is same as * previously succeeded address, omit asking LSM's decision. @@ -2678,6 +2676,9 @@ static int ___sys_sendmsg(struct socket *sock, struct user_msghdr __user *msg, msg_sys->msg_name = &address; + if (sock->file->f_flags & O_NONBLOCK) + flags |= MSG_DONTWAIT; + err = sendmsg_copy_msghdr(msg_sys, msg, flags, &iov); if (err < 0) return err; @@ -2842,9 +2843,6 @@ static int ____sys_recvmsg(struct socket *sock, struct msghdr *msg_sys, /* We assume all kernel code knows the size of sockaddr_storage */ msg_sys->msg_namelen = 0; - if (sock->file->f_flags & O_NONBLOCK) - flags |= MSG_DONTWAIT; - if (unlikely(nosec)) err = sock_recvmsg_nosec(sock, msg_sys, flags); else @@ -2886,6 +2884,9 @@ static int ___sys_recvmsg(struct socket *sock, struct user_msghdr __user *msg, struct sockaddr __user *uaddr; ssize_t err; + if (sock->file->f_flags & O_NONBLOCK) + flags |= MSG_DONTWAIT; + err = recvmsg_copy_msghdr(msg_sys, msg, flags, &uaddr, &iov); if (err < 0) return err; diff --git a/net/sunrpc/clnt.c b/net/sunrpc/clnt.c index 07de0efaf37d..9c6cdc29102a 100644 --- a/net/sunrpc/clnt.c +++ b/net/sunrpc/clnt.c @@ -653,6 +653,9 @@ static struct rpc_clnt *__rpc_clone_client(struct rpc_create_args *args, } args->servername = xprt->servername; args->nodename = clnt->cl_nodename; + args->xprtsec = clnt->cl_xprtsec; + if (!args->timeout) + args->timeout = clnt->cl_timeout; new = rpc_new_client(args, xps, xprt, clnt); if (IS_ERR(new)) @@ -1194,7 +1197,7 @@ void rpc_task_set_transport(struct rpc_task *task, struct rpc_clnt *clnt) (task->tk_flags & RPC_TASK_MOVEABLE))) return; xprt_release(task); - xprt_put(task->tk_xprt); + rpc_task_release_xprt(clnt, task->tk_xprt); } if (task->tk_flags & RPC_TASK_NO_ROUND_ROBIN) task->tk_xprt = rpc_task_get_first_xprt(clnt); @@ -2125,8 +2128,10 @@ call_bind_status(struct rpc_task *task) goto retry_timeout; case -ENETDOWN: case -ENETUNREACH: - if (task->tk_flags & RPC_TASK_NETUNREACH_FATAL) + if (task->tk_flags & RPC_TASK_NETUNREACH_FATAL) { + status = task->tk_status; break; + } fallthrough; case -ECONNREFUSED: /* connection problems */ case -ECONNRESET: @@ -2257,6 +2262,7 @@ call_connect_status(struct rpc_task *task) xprt_release(task); value = atomic_long_dec_return(&xprt->queuelen); + atomic_long_dec(&xps->xps_queuelen); if (value == 0) rpc_xprt_switch_remove_xprt(xps, saved, true); diff --git a/net/sunrpc/rpc_pipe.c b/net/sunrpc/rpc_pipe.c index 0bd1df2ebb47..3a71426e8b76 100644 --- a/net/sunrpc/rpc_pipe.c +++ b/net/sunrpc/rpc_pipe.c @@ -191,6 +191,7 @@ rpc_close_pipes(struct dentry *dentry) cancel_delayed_work_sync(&pipe->queue_timeout); rpc_inode_setowner(inode, NULL); RPC_I(inode)->pipe = NULL; + wake_up(&RPC_I(inode)->waitq); inode_unlock(inode); } diff --git a/net/sunrpc/xprtsock.c b/net/sunrpc/xprtsock.c index e2318100d811..1df25df6b9a2 100644 --- a/net/sunrpc/xprtsock.c +++ b/net/sunrpc/xprtsock.c @@ -3524,7 +3524,7 @@ static struct rpc_xprt *xs_setup_tcp_tls(struct xprt_create *args) transport = container_of(xprt, struct sock_xprt, xprt); xprt->prot = IPPROTO_TCP; - xprt->xprt_class = &xs_tcp_transport; + xprt->xprt_class = &xs_tcp_tls_transport; xprt->max_payload = RPC_MAX_FRAGMENT_SIZE; xprt->bind_timeout = XS_BIND_TO; diff --git a/net/tipc/bearer.c b/net/tipc/bearer.c index 24dcb8aa3233..e057d0c6786c 100644 --- a/net/tipc/bearer.c +++ b/net/tipc/bearer.c @@ -285,17 +285,50 @@ static int tipc_enable_bearer(struct net *net, const char *name, bearer_id = MAX_BEARERS; i = MAX_BEARERS; while (i-- != 0) { + struct net_device *dev; + b = rtnl_dereference(tn->bearer_list[i]); if (!b) { bearer_id = i; continue; } if (!strcmp(name, b->name)) { +duplicate: errstr = "already enabled"; NL_SET_ERR_MSG(extack, "Already enabled"); goto rejected; } + /* udp media can be used together with any media */ + if (b->media->type_id == TIPC_MEDIA_TYPE_UDP || + m->type_id == TIPC_MEDIA_TYPE_UDP) + goto priority; + + dev = __dev_get_by_name(net, b_names.if_name); + + if (!dev) { + res = -ENODEV; + errstr = "no device for the media"; + NL_SET_ERR_MSG(extack, "No device for the media"); + goto rejected; + } + + if (rtnl_dereference(b->media_ptr) == dev) { + char *dev_name = strchr((const char *)b->name, ':') + 1; + + /* Not allow altname of occupied device */ + if (strcmp(dev_name, b_names.if_name) && + b->media->type_id == m->type_id) + goto duplicate; + + /* Not allow eth and ib to attach to the same device */ + errstr = "same dev for different media"; + NL_SET_ERR_MSG(extack, + "Same dev for different media"); + goto rejected; + } + +priority: if (b->priority == prio && (++with_this_prio > 2)) { pr_warn("Bearer <%s>: already 2 bearers with priority %u\n", diff --git a/net/tls/tls_device.c b/net/tls/tls_device.c index 2c661e17efb8..c49798486ea5 100644 --- a/net/tls/tls_device.c +++ b/net/tls/tls_device.c @@ -1030,6 +1030,20 @@ int tls_device_decrypted(struct sock *sk, struct tls_context *tls_ctx) return tls_device_reencrypt(sk, tls_ctx); } +/* Both directions share ctx->netdev. A second direction must use that + * device; after NETDEV_DOWN clears it, no new direction can be offloaded. + */ +static bool tls_device_can_attach(struct tls_context *ctx, struct sock *sk, + struct net_device *netdev) +{ + struct net_device *ctx_netdev; + + ctx_netdev = rcu_dereference_protected(ctx->netdev, + lockdep_is_held(&device_offload_lock)); + return sk->sk_destruct != tls_device_sk_destruct || + ctx_netdev == netdev; +} + static void tls_device_attach(struct tls_context *ctx, struct sock *sk, struct net_device *netdev) { @@ -1165,6 +1179,11 @@ int tls_set_device_offload(struct sock *sk) goto release_lock; } + if (!tls_device_can_attach(ctx, sk, netdev)) { + rc = -EOPNOTSUPP; + goto release_lock; + } + ctx->priv_ctx_tx = offload_ctx; rc = netdev->tlsdev_ops->tls_dev_add(netdev, sk, TLS_OFFLOAD_CTX_DIR_TX, &ctx->crypto_send.info, @@ -1235,6 +1254,11 @@ int tls_set_device_offload_rx(struct sock *sk, struct tls_context *ctx) goto release_lock; } + if (!tls_device_can_attach(ctx, sk, netdev)) { + rc = -EOPNOTSUPP; + goto release_lock; + } + context = kzalloc(sizeof(*context), GFP_KERNEL); if (!context) { rc = -ENOMEM; diff --git a/net/tls/tls_sw.c b/net/tls/tls_sw.c index ad6c0d61d547..ff4690735f70 100644 --- a/net/tls/tls_sw.c +++ b/net/tls/tls_sw.c @@ -436,7 +436,8 @@ int tls_tx_records(struct sock *sk, int flags) /* Tx all ready records */ list_for_each_entry_safe(rec, tmp, &ctx->tx_list, list) { - if (READ_ONCE(rec->tx_ready)) { + /* Pairs with smp_store_release() in tls_encrypt_done() */ + if (smp_load_acquire(&rec->tx_ready)) { if (flags == -1) tx_flags = rec->tx_flags; else @@ -504,8 +505,14 @@ static void tls_encrypt_done(void *data, int err) if (rec) { struct tls_rec *first_rec; - /* Mark the record as ready for transmission */ - smp_store_mb(rec->tx_ready, true); + /* Mark the record as ready for transmission. Pairs with + * smp_load_acquire() in tls_tx_records(): the sge + * offset/length update above must be visible before tx_ready. + */ + smp_store_release(&rec->tx_ready, true); + + /* Order the tx_ready store before the tx_list head check */ + smp_mb(); /* If received record is at head of tx_list, schedule tx */ first_rec = list_first_entry(&ctx->tx_list, @@ -2324,10 +2331,14 @@ ssize_t tls_sw_splice_read(struct socket *sock, loff_t *ppos, struct tls_msg *tlm; struct sk_buff *skb; ssize_t copied = 0; + bool nonblock; int chunk; int err; - err = tls_rx_reader_lock(sk, ctx, flags & SPLICE_F_NONBLOCK); + nonblock = flags & SPLICE_F_NONBLOCK || + sock->file->f_flags & O_NONBLOCK; + + err = tls_rx_reader_lock(sk, ctx, nonblock); if (err < 0) return err; @@ -2341,8 +2352,7 @@ ssize_t tls_sw_splice_read(struct socket *sock, loff_t *ppos, } else { struct tls_decrypt_arg darg; - err = tls_rx_rec_wait(sk, NULL, flags & SPLICE_F_NONBLOCK, - true, false); + err = tls_rx_rec_wait(sk, NULL, nonblock, true, false); if (err <= 0) goto splice_read_end; @@ -2923,7 +2933,8 @@ int tls_set_sw_offload(struct sock *sk, int tx, } } - ctx->push_pending_record = tls_sw_push_pending_record; + if (tx) + ctx->push_pending_record = tls_sw_push_pending_record; /* setkey is the last operation that could fail during a * rekey. if it succeeds, we can start modifying the diff --git a/net/unix/af_unix.c b/net/unix/af_unix.c index a1e832e531bf..9c92d13aa636 100644 --- a/net/unix/af_unix.c +++ b/net/unix/af_unix.c @@ -934,6 +934,7 @@ static bool unix_custom_sockopt(int optname) { switch (optname) { case SO_INQ: + case SO_RIGHTS_NOTRUNC: return true; default: return false; @@ -969,6 +970,14 @@ static int unix_setsockopt(struct socket *sock, int level, int optname, WRITE_ONCE(u->recvmsg_inq, val); break; + + case SO_RIGHTS_NOTRUNC: + if (val > 1 || val < 0) + return -EINVAL; + + WRITE_ONCE(u->scm_rights_notrunc, val); + break; + default: return -ENOPROTOOPT; } @@ -1762,9 +1771,11 @@ static int unix_stream_connect(struct socket *sock, struct sockaddr *uaddr, init_peercred(newsk, &peercred); newu = unix_sk(newsk); + otheru = unix_sk(other); newu->listener = other; + newu->recvmsg_inq = READ_ONCE(otheru->recvmsg_inq); + newu->scm_rights_notrunc = READ_ONCE(otheru->scm_rights_notrunc); RCU_INIT_POINTER(newsk->sk_wq, &newu->peer_wq); - otheru = unix_sk(other); /* copy address information from listening to new sock * diff --git a/net/unix/garbage.c b/net/unix/garbage.c index 11b75d37ac03..fc1828e01bdb 100644 --- a/net/unix/garbage.c +++ b/net/unix/garbage.c @@ -78,9 +78,9 @@ struct unix_vertex { struct list_head edges; struct list_head entry; struct list_head scc_entry; - unsigned long out_degree; - unsigned long index; - unsigned long scc_index; + u64 out_degree; + u64 index; + u64 scc_index; }; struct unix_edge { @@ -148,8 +148,8 @@ enum unix_vertex_index { UNIX_VERTEX_INDEX_START, }; -static unsigned long unix_vertex_unvisited_index = UNIX_VERTEX_INDEX_MARK1; -static unsigned long unix_vertex_max_scc_index = UNIX_VERTEX_INDEX_START; +static u64 unix_vertex_unvisited_index = UNIX_VERTEX_INDEX_MARK1; +static u64 unix_vertex_max_scc_index = UNIX_VERTEX_INDEX_START; static void unix_add_edge(struct scm_fp_list *fpl, struct unix_edge *edge) { @@ -330,9 +330,6 @@ void unix_peek_fpl(struct scm_fp_list *fpl) if (!fpl || !fpl->count_unix) return; - if (!READ_ONCE(gc_in_progress)) - return; - /* Invalidate the final refcnt check in unix_vertex_dead(). */ spin_lock(&unix_peek_lock); raw_write_seqcount_barrier(&unix_peek_seq); @@ -373,7 +370,7 @@ static bool unix_vertex_dead(struct unix_vertex *vertex) } static LIST_HEAD(unix_visited_vertices); -static unsigned long unix_vertex_grouped_index = UNIX_VERTEX_INDEX_MARK2; +static u64 unix_vertex_grouped_index = UNIX_VERTEX_INDEX_MARK2; static bool unix_scc_dead(struct list_head *scc) { @@ -451,14 +448,14 @@ static bool unix_scc_cyclic(struct list_head *scc) return false; } -static unsigned long __unix_walk_scc(struct unix_vertex *vertex, - unsigned long *last_index, - struct sk_buff_head *hitlist) +static u64 __unix_walk_scc(struct unix_vertex *vertex, + u64 *last_index, + struct sk_buff_head *hitlist) { - unsigned long cyclic_sccs = 0; LIST_HEAD(vertex_stack); struct unix_edge *edge; LIST_HEAD(edge_stack); + u64 cyclic_sccs = 0; next_vertex: /* Push vertex to vertex_stack and mark it as on-stack @@ -554,12 +551,12 @@ static unsigned long __unix_walk_scc(struct unix_vertex *vertex, return cyclic_sccs; } -static unsigned long unix_graph_cyclic_sccs; +static u64 unix_graph_cyclic_sccs; static void unix_walk_scc(struct sk_buff_head *hitlist) { - unsigned long last_index = UNIX_VERTEX_INDEX_START; - unsigned long cyclic_sccs = 0; + u64 last_index = UNIX_VERTEX_INDEX_START; + u64 cyclic_sccs = 0; unix_vertex_max_scc_index = UNIX_VERTEX_INDEX_START; @@ -582,7 +579,7 @@ static void unix_walk_scc(struct sk_buff_head *hitlist) static void unix_walk_scc_fast(struct sk_buff_head *hitlist) { - unsigned long cyclic_sccs = unix_graph_cyclic_sccs; + u64 cyclic_sccs = unix_graph_cyclic_sccs; while (!list_empty(&unix_unvisited_vertices)) { struct unix_vertex *vertex; diff --git a/net/vmw_vsock/af_vsock.c b/net/vmw_vsock/af_vsock.c index 999b18f2d17f..391ac6d2435b 100644 --- a/net/vmw_vsock/af_vsock.c +++ b/net/vmw_vsock/af_vsock.c @@ -1986,7 +1986,8 @@ static int vsock_connectible_setsockopt(struct socket *sock, optname == SO_VM_SOCKETS_CONNECT_TIMEOUT_OLD); if (err) break; - if (tv.tv_sec >= 0 && tv.tv_usec < USEC_PER_SEC && + if (tv.tv_sec >= 0 && tv.tv_usec >= 0 && + tv.tv_usec < USEC_PER_SEC && tv.tv_sec < (MAX_SCHEDULE_TIMEOUT / HZ - 1)) { vsk->connect_timeout = tv.tv_sec * HZ + DIV_ROUND_UP((unsigned long)tv.tv_usec, (USEC_PER_SEC / HZ)); diff --git a/net/vmw_vsock/hyperv_transport.c b/net/vmw_vsock/hyperv_transport.c index 54c7f51f9145..23eb866ebad3 100644 --- a/net/vmw_vsock/hyperv_transport.c +++ b/net/vmw_vsock/hyperv_transport.c @@ -698,6 +698,9 @@ static s64 hvs_stream_has_data(struct vsock_sock *vsk) struct hvsock *hvs = vsk->trans; s64 ret; + if (!hvs->chan) + return 0; + if (hvs->recv_data_len > 0) return hvs->recv_data_len; diff --git a/net/vmw_vsock/virtio_transport.c b/net/vmw_vsock/virtio_transport.c index 8b56ff4bdf4d..f41c9403050b 100644 --- a/net/vmw_vsock/virtio_transport.c +++ b/net/vmw_vsock/virtio_transport.c @@ -690,8 +690,10 @@ static int virtio_vsock_vqs_init(struct virtio_vsock *vsock) atomic_set(&vsock->queued_replies, 0); ret = virtio_find_vqs(vdev, VSOCK_VQ_MAX, vsock->vqs, vqs_info, NULL); - if (ret < 0) + if (ret < 0) { + memset(vsock->vqs, 0, sizeof(vsock->vqs)); return ret; + } virtio_vsock_update_guest_cid(vsock); @@ -752,11 +754,19 @@ static void virtio_vsock_vqs_del(struct virtio_vsock *vsock) vsock->event_run = false; mutex_unlock(&vsock->event_lock); + virtio_vsock_skb_queue_purge(&vsock->send_pkt_queue); + /* Flush all device writes and interrupts, device will not use any * more buffers. */ virtio_reset_device(vdev); + /* After a failed restore no virtqueues are live, and a second + * del_vqs() would free virtio-mmio's IRQ again (a WARN in free_irq()). + */ + if (!vsock->vqs[VSOCK_VQ_RX]) + return; + mutex_lock(&vsock->rx_lock); while ((skb = virtqueue_detach_unused_buf(vsock->vqs[VSOCK_VQ_RX]))) kfree_skb(skb); @@ -767,10 +777,10 @@ static void virtio_vsock_vqs_del(struct virtio_vsock *vsock) kfree_skb(skb); mutex_unlock(&vsock->tx_lock); - virtio_vsock_skb_queue_purge(&vsock->send_pkt_queue); - /* Delete virtqueues and flush outstanding callbacks if any */ vdev->config->del_vqs(vdev); + + memset(vsock->vqs, 0, sizeof(vsock->vqs)); } static int virtio_vsock_probe(struct virtio_device *vdev) diff --git a/net/wireless/core.c b/net/wireless/core.c index c7d449868254..0661c432b4e5 100644 --- a/net/wireless/core.c +++ b/net/wireless/core.c @@ -1762,7 +1762,7 @@ static int cfg80211_netdev_notifier_call(struct notifier_block *nb, return NOTIFY_DONE; } - wireless_nlevent_flush(); + wireless_nlevent_flush(dev_net(dev)); return NOTIFY_OK; } diff --git a/net/wireless/nl80211.c b/net/wireless/nl80211.c index d4b1e5dc5eb4..429dba541cb8 100644 --- a/net/wireless/nl80211.c +++ b/net/wireless/nl80211.c @@ -6152,6 +6152,9 @@ nl80211_parse_mbssid_elems(struct wiphy *wiphy, struct nlattr *attrs, num_elems++; } + if (!num_elems) + return ERR_PTR(-EINVAL); + elems = kzalloc(struct_size(elems, elem, num_elems), GFP_KERNEL); if (!elems) return ERR_PTR(-ENOMEM); @@ -6187,6 +6190,9 @@ nl80211_parse_rnr_elems(struct wiphy *wiphy, struct nlattr *attrs, num_elems++; } + if (!num_elems) + return ERR_PTR(-EINVAL); + elems = kzalloc(struct_size(elems, elem, num_elems), GFP_KERNEL); if (!elems) return ERR_PTR(-ENOMEM); @@ -6335,7 +6341,8 @@ static int nl80211_parse_beacon(struct cfg80211_registered_device *rdev, if (IS_ERR(rnr)) return PTR_ERR(rnr); - if (rnr && rnr->cnt < bcn->mbssid_ies->cnt) { + /* RNR elements are only used with MBSSID elements */ + if (rnr->cnt < bcn->mbssid_ies->cnt) { kfree(rnr); return -EINVAL; } diff --git a/net/wireless/scan.c b/net/wireless/scan.c index 3d3956e4cce2..9aaa9808004a 100644 --- a/net/wireless/scan.c +++ b/net/wireless/scan.c @@ -2437,6 +2437,7 @@ cfg80211_inform_single_bss_data(struct wiphy *wiphy, if (cfg80211_add_nontrans_list(data->source_bss, &res->pub)) { if (__cfg80211_unlink_bss(rdev, res)) { rdev->bss_generation++; + bss_ref_put(rdev, res); res = NULL; } } @@ -2579,7 +2580,7 @@ cfg80211_parse_mbssid_data(struct wiphy *wiphy, if (elem->data[0] < 1 || (int)elem->data[0] > 8) continue; for_each_element(sub, elem->data + 1, elem->datalen - 1) { - u8 profile_len; + size_t profile_len; if (sub->id != 0 || sub->datalen < 4) { /* not a valid BSS profile */ diff --git a/net/wireless/util.c b/net/wireless/util.c index 0254cd5f89f1..de0642bca2dd 100644 --- a/net/wireless/util.c +++ b/net/wireless/util.c @@ -745,12 +745,12 @@ __ieee80211_amsdu_copy(struct sk_buff *skb, unsigned int hlen, return frame; } -static u16 +static unsigned int ieee80211_amsdu_subframe_length(void *field, u8 mesh_flags, u8 hdr_type) { __le16 *field_le = field; __be16 *field_be = field; - u16 len; + unsigned int len; if (hdr_type >= 2) len = le16_to_cpu(*field_le); @@ -772,7 +772,7 @@ bool ieee80211_is_valid_amsdu(struct sk_buff *skb, u8 mesh_hdr) __be16 len; u8 mesh_flags; } hdr; - u16 len; + unsigned int len; if (sizeof(hdr) > remaining) return false; diff --git a/net/wireless/wext-core.c b/net/wireless/wext-core.c index 7b8e94214b07..7de96c3ffda8 100644 --- a/net/wireless/wext-core.c +++ b/net/wireless/wext-core.c @@ -343,32 +343,28 @@ static const int compat_event_type_size[] = { /* IW event code */ -void wireless_nlevent_flush(void) +void wireless_nlevent_flush(struct net *net) { struct sk_buff *skb; - struct net *net; - down_read(&net_rwsem); - for_each_net(net) { - while ((skb = skb_dequeue(&net->wext_nlevents))) - rtnl_notify(skb, net, 0, RTNLGRP_LINK, NULL, - GFP_KERNEL); - } - up_read(&net_rwsem); + while ((skb = skb_dequeue(&net->wext_nlevents))) + rtnl_notify(skb, net, 0, RTNLGRP_LINK, NULL, GFP_KERNEL); } EXPORT_SYMBOL_GPL(wireless_nlevent_flush); static int wext_netdev_notifier_call(struct notifier_block *nb, unsigned long state, void *ptr) { + struct net_device *dev = netdev_notifier_info_to_dev(ptr); + /* - * When a netdev changes state in any way, flush all pending messages - * to avoid them going out in a strange order, e.g. RTM_NEWLINK after - * RTM_DELLINK, or with IFF_UP after without IFF_UP during dev_close() - * or similar - all of which could otherwise happen due to delays from - * schedule_work(). + * When a netdev changes state in any way, flush all pending messages in + * its network namespace to avoid them going out in a strange order, + * e.g. RTM_NEWLINK after RTM_DELLINK, or with IFF_UP after without + * IFF_UP during dev_close() or similar - all of which could otherwise + * happen due to delays from schedule_work(). */ - wireless_nlevent_flush(); + wireless_nlevent_flush(dev_net(dev)); return NOTIFY_OK; } @@ -411,7 +407,12 @@ subsys_initcall(wireless_nlevent_init); /* Process events generated by the wireless layer or the driver. */ static void wireless_nlevent_process(struct work_struct *work) { - wireless_nlevent_flush(); + struct net *net; + + down_read(&net_rwsem); + for_each_net(net) + wireless_nlevent_flush(net); + up_read(&net_rwsem); } static DECLARE_WORK(wireless_nlevent_work, wireless_nlevent_process); diff --git a/net/xdp/xsk.c b/net/xdp/xsk.c index 5d2067777d35..120453647cf4 100644 --- a/net/xdp/xsk.c +++ b/net/xdp/xsk.c @@ -902,14 +902,6 @@ static int xsk_skb_metadata(struct sk_buff *skb, void *buffer, skb->csum_start = hr + csum_start; skb->csum_offset = csum_offset; skb->ip_summed = CHECKSUM_PARTIAL; - - if (unlikely(pool->tx_sw_csum)) { - int err; - - err = skb_checksum_help(skb); - if (err) - return err; - } } if (flags & XDP_TXMD_FLAGS_LAUNCH_TIME) @@ -921,6 +913,15 @@ static int xsk_skb_metadata(struct sk_buff *skb, void *buffer, return 0; } +static int xsk_skb_sw_csum(struct sk_buff *skb, struct xsk_buff_pool *pool) +{ + if (unlikely(pool->tx_sw_csum && + skb->ip_summed == CHECKSUM_PARTIAL)) + return skb_checksum_help(skb); + + return 0; +} + static struct sk_buff *xsk_build_skb_zerocopy(struct xdp_sock *xs, struct xdp_desc *desc) { @@ -1174,6 +1175,12 @@ static int __xsk_generic_xmit(struct sock *sk) continue; } + err = xsk_skb_sw_csum(skb, xs->pool); + if (unlikely(err)) { + xsk_drop_skb(skb); + goto out; + } + err = __dev_direct_xmit(skb, xs->queue_id); if (err == NETDEV_TX_BUSY) { /* Tell user-space to retry the send */ @@ -2038,6 +2045,11 @@ static int xsk_notifier(struct notifier_block *this, mutex_unlock(&xs->mutex); } mutex_unlock(&net->xdp.lock); + /* + * A released socket is no longer on xdp.list. Its pool can still + * hold a device reference on the frozen release workqueue. + */ + xp_clear_dev_all(dev); break; } return NOTIFY_DONE; diff --git a/net/xdp/xsk_buff_pool.c b/net/xdp/xsk_buff_pool.c index 9dc1ff31867a..f261a8879ea9 100644 --- a/net/xdp/xsk_buff_pool.c +++ b/net/xdp/xsk_buff_pool.c @@ -182,7 +182,7 @@ int xp_assign_dev(struct xsk_buff_pool *pool, u32 frame_size; int err = 0; - ASSERT_RTNL(); + netdev_ops_assert_locked(netdev); force_zc = flags & XDP_ZEROCOPY; force_copy = flags & XDP_COPY; @@ -211,6 +211,11 @@ int xp_assign_dev(struct xsk_buff_pool *pool, pool->cached_need_wakeup = XDP_WAKEUP_TX; dev_hold(netdev); + /* + * Socket removal precedes the final pool put. Keep the pool visible to + * NETDEV_UNREGISTER even while release work is waiting for process thaw. + */ + hlist_add_head(&pool->dev_node, &netdev->xsk_pools); if (force_copy) /* For copy-mode, we are done. */ @@ -251,7 +256,6 @@ int xp_assign_dev(struct xsk_buff_pool *pool, bpf.xsk.pool = pool; bpf.xsk.queue_id = queue_id; - netdev_ops_assert_locked(netdev); err = netdev->netdev_ops->ndo_bpf(netdev, &bpf); if (err) goto err_unreg_pool; @@ -273,6 +277,8 @@ int xp_assign_dev(struct xsk_buff_pool *pool, if (err) { pool->umem->flags = umem_flags; xsk_clear_pool_at_qid(netdev, queue_id); + hlist_del(&pool->dev_node); + pool->netdev = NULL; dev_put(netdev); } return err; @@ -299,19 +305,39 @@ int xp_assign_dev_shared(struct xsk_buff_pool *pool, struct xdp_sock *umem_xs, return xp_assign_dev(pool, dev, queue_id, flags); } +static void __xp_clear_dev(struct xsk_buff_pool *pool) +{ + struct net_device *netdev = pool->netdev; + + netdev_ops_assert_locked(netdev); + xp_disable_drv_zc(pool); + xsk_clear_pool_at_qid(netdev, pool->queue_id); + hlist_del(&pool->dev_node); + pool->netdev = NULL; + dev_put(netdev); +} + void xp_clear_dev(struct xsk_buff_pool *pool) { struct net_device *netdev = pool->netdev; - if (!pool->netdev) + if (!netdev) return; netdev_lock_ops(netdev); - xp_disable_drv_zc(pool); - xsk_clear_pool_at_qid(pool->netdev, pool->queue_id); - pool->netdev = NULL; + __xp_clear_dev(pool); netdev_unlock_ops(netdev); - dev_put(netdev); +} + +void xp_clear_dev_all(struct net_device *dev) +{ + struct xsk_buff_pool *pool; + struct hlist_node *next; + + netdev_lock_ops(dev); + hlist_for_each_entry_safe(pool, next, &dev->xsk_pools, dev_node) + __xp_clear_dev(pool); + netdev_unlock_ops(dev); } static void xp_release_deferred(struct work_struct *work) @@ -349,7 +375,11 @@ bool xp_put_pool(struct xsk_buff_pool *pool) if (refcount_dec_and_test(&pool->users)) { INIT_WORK(&pool->work, xp_release_deferred); - schedule_work(&pool->work); + /* + * Teardown calls ndo_bpf(), which may need powered hardware. + * RTNL alone does not exclude the device's system PM callbacks. + */ + queue_work(system_freezable_wq, &pool->work); return true; } diff --git a/net/xfrm/xfrm_iptfs.c b/net/xfrm/xfrm_iptfs.c index 4d3489acb099..9a539618cb8f 100644 --- a/net/xfrm/xfrm_iptfs.c +++ b/net/xfrm/xfrm_iptfs.c @@ -1183,6 +1183,7 @@ static bool __input_process_payload(struct xfrm_state *x, u32 data, /* this should not happen from the above code */ XFRM_INC_STATS(net, LINUX_MIB_XFRMINIPTFSERROR); +done: if (first_skb && first_iplen && !defer && !first_skb_partial) { /* first_skb is queued b/c !defer and not partial */ if (pskb_trim(first_skb, first_iplen)) { @@ -1199,7 +1200,7 @@ static bool __input_process_payload(struct xfrm_state *x, u32 data, if (xfrm_input(skb, 0, 0, -2)) kfree_skb(skb); } -done: + skb = skbseq->root_skb; skb_abort_seq_read(skbseq); diff --git a/net/xfrm/xfrm_policy.c b/net/xfrm/xfrm_policy.c index c13382bcc658..b737139b3fc6 100644 --- a/net/xfrm/xfrm_policy.c +++ b/net/xfrm/xfrm_policy.c @@ -2777,9 +2777,12 @@ static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy, xdst0->path = dst; err = -ENODEV; - dev = dst->dev; - if (!dev) + rcu_read_lock(); + dev = dst_dev_rcu(dst); + if (!dev) { + rcu_read_unlock(); goto free_dst; + } xfrm_init_path(xdst0, dst, nfheader_len); xfrm_init_pmtu(bundle, nx); @@ -2787,8 +2790,10 @@ static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy, for (xdst_prev = xdst0; xdst_prev != (struct xfrm_dst *)dst; xdst_prev = (struct xfrm_dst *) xfrm_dst_child(&xdst_prev->u.dst)) { err = xfrm_fill_dst(xdst_prev, dev, fl); - if (err) + if (err) { + rcu_read_unlock(); goto free_dst; + } xdst_prev->u.dst.header_len = header_len; xdst_prev->u.dst.trailer_len = trailer_len; @@ -2796,6 +2801,7 @@ static struct dst_entry *xfrm_bundle_create(struct xfrm_policy *policy, trailer_len -= xdst_prev->u.dst.xfrm->props.trailer_len; } + rcu_read_unlock(); return &xdst0->u.dst; put_states: @@ -3065,11 +3071,15 @@ static struct xfrm_dst *xfrm_create_dummy_bundle(struct net *net, xfrm_init_path((struct xfrm_dst *)dst1, dst, 0); err = -ENODEV; - dev = dst->dev; - if (!dev) + rcu_read_lock(); + dev = dst_dev_rcu(dst); + if (!dev) { + rcu_read_unlock(); goto free_dst; + } err = xfrm_fill_dst(xdst, dev, fl); + rcu_read_unlock(); if (err) goto free_dst; diff --git a/net/xfrm/xfrm_replay.c b/net/xfrm/xfrm_replay.c index dbdf8a39dffe..9394953247ab 100644 --- a/net/xfrm/xfrm_replay.c +++ b/net/xfrm/xfrm_replay.c @@ -40,7 +40,7 @@ static void xfrm_replay_notify_esn(struct xfrm_state *x, int event); void xfrm_replay_notify(struct xfrm_state *x, int event) { - struct km_event c; + struct km_event c = {}; /* we send notify messages in case * 1. we updated on of the sequence numbers, and the seqno difference * is at least x->replay_maxdiff, in this case we also update the @@ -304,7 +304,7 @@ static void xfrm_replay_advance_bmp(struct xfrm_state *x, __be32 net_seq) static void xfrm_replay_notify_bmp(struct xfrm_state *x, int event) { - struct km_event c; + struct km_event c = {}; struct xfrm_replay_state_esn *replay_esn = x->replay_esn; struct xfrm_replay_state_esn *preplay_esn = x->preplay_esn; @@ -356,7 +356,7 @@ static void xfrm_replay_notify_bmp(struct xfrm_state *x, int event) static void xfrm_replay_notify_esn(struct xfrm_state *x, int event) { u32 seq_diff, oseq_diff; - struct km_event c; + struct km_event c = {}; struct xfrm_replay_state_esn *replay_esn = x->replay_esn; struct xfrm_replay_state_esn *preplay_esn = x->preplay_esn; diff --git a/security/keys/key.c b/security/keys/key.c index 6e6cd146e6b8..a4d385a8b480 100644 --- a/security/keys/key.c +++ b/security/keys/key.c @@ -245,6 +245,8 @@ struct key *key_alloc(struct key_type *type, const char *desc, } desclen = strlen(desc); + if (desclen >= KEY_MAX_DESC_SIZE) + goto error; quotalen = desclen + 1 + type->def_datalen; /* get hold of the key tracking for this user */ @@ -829,6 +831,7 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref, key_ref_t key_ref; int ret; struct key_restriction *restrict_link = NULL; + size_t desclen; /* look up the key type to see if it's one of the registered kernel * types */ @@ -869,7 +872,12 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref, if (!index_key.description) goto error_free_prep; } - index_key.desc_len = strlen(index_key.description); + desclen = strlen(index_key.description); + if (desclen >= KEY_MAX_DESC_SIZE) { + key_ref = ERR_PTR(-EINVAL); + goto error_free_prep; + } + index_key.desc_len = desclen; key_set_index_key(&index_key); ret = __key_link_lock(keyring, &index_key); diff --git a/security/keys/keyctl.c b/security/keys/keyctl.c index 0fc520de9995..2899705f3221 100644 --- a/security/keys/keyctl.c +++ b/security/keys/keyctl.c @@ -24,8 +24,6 @@ #include #include "internal.h" -#define KEY_MAX_DESC_SIZE 4096 - static const unsigned char keyrings_capabilities[2] = { [0] = (KEYCTL_CAPS0_CAPABILITIES | (IS_ENABLED(CONFIG_PERSISTENT_KEYRINGS) ? KEYCTL_CAPS0_PERSISTENT_KEYRINGS : 0) | diff --git a/security/keys/keyring.c b/security/keys/keyring.c index 74ed1372d22c..9d5ca1e7d8ba 100644 --- a/security/keys/keyring.c +++ b/security/keys/keyring.c @@ -598,6 +598,12 @@ static int keyring_search_iterator(const void *object, void *iterator_data) return 0; } + /* A key the caller did not ask for must not decide the result. */ + if (!ctx->match_data.cmp(key, &ctx->match_data)) { + kleave(" = 0 [!match]"); + return 0; + } + /* skip invalidated, revoked and expired keys */ if (ctx->flags & KEYRING_SEARCH_DO_STATE_CHECK) { time64_t expiry = READ_ONCE(key->expiry); @@ -617,12 +623,6 @@ static int keyring_search_iterator(const void *object, void *iterator_data) } } - /* keys that don't match */ - if (!ctx->match_data.cmp(key, &ctx->match_data)) { - kleave(" = 0 [!match]"); - return 0; - } - /* key must have search permissions */ if (!(ctx->flags & KEYRING_SEARCH_NO_CHECK_PERM) && key_task_permission(make_key_ref(key, ctx->possessed), @@ -957,7 +957,6 @@ key_ref_t keyring_search(key_ref_t keyring, struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, - .index_key.desc_len = strlen(description), .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, @@ -965,8 +964,14 @@ key_ref_t keyring_search(key_ref_t keyring, .flags = KEYRING_SEARCH_DO_STATE_CHECK, }; key_ref_t key; + size_t desclen; int ret; + desclen = strlen(description); + if (desclen >= KEY_MAX_DESC_SIZE) + return ERR_PTR(-EINVAL); + ctx.index_key.desc_len = desclen; + if (recurse) ctx.flags |= KEYRING_SEARCH_RECURSE; if (type->match_preparse) { @@ -1501,9 +1506,15 @@ static int __key_unlink_begin(struct key *keyring, struct key *key, struct assoc_array_edit **_edit) { struct assoc_array_edit *edit; + const void *object; BUG_ON(*_edit != NULL); + object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops, + &key->index_key); + if (!object || keyring_ptr_to_key(object) != key) + return -ENOENT; + edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops, &key->index_key); if (IS_ERR(edit)) diff --git a/security/keys/request_key.c b/security/keys/request_key.c index a7673ad86d18..b153f36973ac 100644 --- a/security/keys/request_key.c +++ b/security/keys/request_key.c @@ -584,7 +584,6 @@ struct key *request_key_and_link(struct key_type *type, .index_key.type = type, .index_key.domain_tag = domain_tag, .index_key.description = description, - .index_key.desc_len = strlen(description), .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, @@ -595,8 +594,14 @@ struct key *request_key_and_link(struct key_type *type, }; struct key *key; key_ref_t key_ref; + size_t desclen; int ret; + desclen = strlen(description); + if (desclen >= KEY_MAX_DESC_SIZE) + return ERR_PTR(-EINVAL); + ctx.index_key.desc_len = desclen; + kenter("%s,%s,%p,%zu,%p,%p,%lx", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); @@ -787,7 +792,6 @@ struct key *request_key_rcu(struct key_type *type, .index_key.type = type, .index_key.domain_tag = domain_tag, .index_key.description = description, - .index_key.desc_len = strlen(description), .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, @@ -797,6 +801,12 @@ struct key *request_key_rcu(struct key_type *type, }; struct key *key; key_ref_t key_ref; + size_t desclen; + + desclen = strlen(description); + if (desclen >= KEY_MAX_DESC_SIZE) + return ERR_PTR(-EINVAL); + ctx.index_key.desc_len = desclen; kenter("%s,%s", type->name, description); diff --git a/sound/core/memalloc.c b/sound/core/memalloc.c index b3853583d2ae..e2887c9a2463 100644 --- a/sound/core/memalloc.c +++ b/sound/core/memalloc.c @@ -506,7 +506,7 @@ static void *snd_dma_wc_alloc(struct snd_dma_buffer *dmab, size_t size) return NULL; dmab->addr = dma_map_single(dmab->dev.dev, p, size, DMA_BIDIRECTIONAL); if (dma_mapping_error(dmab->dev.dev, dmab->addr)) { - do_free_pages(dmab->area, size, true); + do_free_pages(p, size, true); return NULL; } return p; diff --git a/sound/drivers/aloop.c b/sound/drivers/aloop.c index 93ac63edfb97..c11648f43109 100644 --- a/sound/drivers/aloop.c +++ b/sound/drivers/aloop.c @@ -1276,7 +1276,7 @@ static const struct loopback_ops loopback_snd_timer_ops = { .dpcm_info = loopback_snd_timer_dpcm_info, }; -static int loopback_open(struct snd_pcm_substream *substream) +static int __loopback_open(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; struct loopback *loopback = substream->private_data; @@ -1285,7 +1285,6 @@ static int loopback_open(struct snd_pcm_substream *substream) int err = 0; int dev = get_cable_index(substream); - guard(mutex)(&loopback->cable_lock); dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL); if (!dpcm) return -ENOMEM; @@ -1375,6 +1374,14 @@ static int loopback_open(struct snd_pcm_substream *substream) return err; } +static int loopback_open(struct snd_pcm_substream *substream) +{ + struct loopback *loopback = substream->private_data; + + guard(mutex)(&loopback->cable_lock); + return __loopback_open(substream); +} + static int loopback_close(struct snd_pcm_substream *substream) { struct loopback *loopback = substream->private_data; diff --git a/sound/drivers/pcmtest.c b/sound/drivers/pcmtest.c index b63df0623c73..026bc53211d7 100644 --- a/sound/drivers/pcmtest.c +++ b/sound/drivers/pcmtest.c @@ -465,20 +465,6 @@ static snd_pcm_uframes_t snd_pcmtst_pcm_pointer(struct snd_pcm_substream *substr return bytes_to_frames(substream->runtime, v_iter->buf_pos); } -static int snd_pcmtst_free(struct pcmtst *pcmtst) -{ - if (!pcmtst) - return 0; - kfree(pcmtst); - return 0; -} - -// These callbacks are required, but empty - all freeing occurs in pdev_remove -static int snd_pcmtst_dev_free(struct snd_device *device) -{ - return 0; -} - static void pcmtst_pdev_release(struct device *dev) { } @@ -582,40 +568,9 @@ static int snd_pcmtst_new_pcm(struct pcmtst *pcmtst) return err; } -static int snd_pcmtst_create(struct snd_card *card, struct platform_device *pdev, - struct pcmtst **r_pcmtst) -{ - struct pcmtst *pcmtst; - int err; - static const struct snd_device_ops ops = { - .dev_free = snd_pcmtst_dev_free, - }; - - pcmtst = kzalloc(sizeof(*pcmtst), GFP_KERNEL); - if (!pcmtst) - return -ENOMEM; - pcmtst->card = card; - pcmtst->pdev = pdev; - - err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, pcmtst, &ops); - if (err < 0) - goto _err_free_chip; - - err = snd_pcmtst_new_pcm(pcmtst); - if (err < 0) - goto _err_free_chip; - - *r_pcmtst = pcmtst; - return 0; - -_err_free_chip: - snd_pcmtst_free(pcmtst); - return err; -} - static int pcmtst_probe(struct platform_device *pdev) { - struct snd_card *card; + struct snd_card *card __free(snd_card_free) = NULL; struct pcmtst *pcmtst; int err; @@ -623,10 +578,16 @@ static int pcmtst_probe(struct platform_device *pdev) if (err) return err; - err = snd_devm_card_new(&pdev->dev, index, id, THIS_MODULE, 0, &card); + err = snd_devm_card_new(&pdev->dev, index, id, THIS_MODULE, + sizeof(*pcmtst), &card); if (err < 0) return err; - err = snd_pcmtst_create(card, pdev, &pcmtst); + + pcmtst = card->private_data; + pcmtst->card = card; + pcmtst->pdev = pdev; + + err = snd_pcmtst_new_pcm(pcmtst); if (err < 0) return err; @@ -639,17 +600,11 @@ static int pcmtst_probe(struct platform_device *pdev) return err; platform_set_drvdata(pdev, pcmtst); + card = NULL; /* probe succeeded, don't release as error */ return 0; } -static void pdev_remove(struct platform_device *pdev) -{ - struct pcmtst *pcmtst = platform_get_drvdata(pdev); - - snd_pcmtst_free(pcmtst); -} - static struct platform_device pcmtst_pdev = { .name = "pcmtest", .dev.release = pcmtst_pdev_release, @@ -657,7 +612,6 @@ static struct platform_device pcmtst_pdev = { static struct platform_driver pcmtst_pdrv = { .probe = pcmtst_probe, - .remove = pdev_remove, .driver = { .name = "pcmtest", }, diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index ba850cb119ec..dbc7b56f4d42 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -1585,6 +1585,14 @@ static void alc245_fixup_hp_mute_led_coefbit(struct hda_codec *codec, } } +/* mute LED via COEF bit and mic-mute LED via GPIO, called directly */ +static void alc245_fixup_cs35l41_mute_micmute(struct hda_codec *codec, + const struct hda_fixup *fix, int action) +{ + alc245_fixup_hp_mute_led_coefbit(codec, fix, action); + alc245_fixup_hp_gpio_led(codec, fix, action); +} + static void alc245_fixup_hp_mute_led_v1_coefbit(struct hda_codec *codec, const struct hda_fixup *fix, int action) @@ -4045,6 +4053,7 @@ enum { ALC289_FIXUP_ASUS_ZEPHYRUS_DUAL_SPK, ALC256_FIXUP_VAIO_RPL_MIC_NO_PRESENCE, ALC245_FIXUP_ACER_MICMUTE_LED, + ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED, }; /* A special fixup for Lenovo C940 and Yoga Duet 7; @@ -6668,6 +6677,12 @@ static const struct hda_fixup alc269_fixups[] = { .v.func = alc285_fixup_hp_coef_micmute_led, .chained = true, .chain_id = ALC2XX_FIXUP_HEADSET_MIC, + }, + [ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED] = { + .type = HDA_FIXUP_FUNC, + .v.func = alc245_fixup_cs35l41_mute_micmute, + .chained = true, + .chain_id = ALC287_FIXUP_CS35L41_I2C_2, } }; @@ -7103,10 +7118,10 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x103c, 0x8be1, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x103c, 0x8be2, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x103c, 0x8be3, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2), - SND_PCI_QUIRK(0x103c, 0x8be5, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2), + SND_PCI_QUIRK(0x103c, 0x8be5, "HP Envy 16", ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED), SND_PCI_QUIRK(0x103c, 0x8be6, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x103c, 0x8be7, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2), - SND_PCI_QUIRK(0x103c, 0x8be8, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2), + SND_PCI_QUIRK(0x103c, 0x8be8, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2_HP_MUTE_LEDS), SND_PCI_QUIRK(0x103c, 0x8be9, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2), SND_PCI_QUIRK(0x103c, 0x8bf0, "HP", ALC236_FIXUP_HP_GPIO_LED), SND_PCI_QUIRK(0x103c, 0x8bfd, "HP Pavilion 15-eg3xxx", ALC287_FIXUP_HP_GPIO_LED), diff --git a/sound/hda/codecs/realtek/alc882.c b/sound/hda/codecs/realtek/alc882.c index fd466b6985f0..9577b8af9e21 100644 --- a/sound/hda/codecs/realtek/alc882.c +++ b/sound/hda/codecs/realtek/alc882.c @@ -50,6 +50,7 @@ enum { ALC889_FIXUP_MP41_VREF, ALC882_FIXUP_INV_DMIC, ALC882_FIXUP_NO_PRIMARY_HP, + ALC898_FIXUP_DELL_XPS8940_MIC, ALC887_FIXUP_ASUS_BASS, ALC887_FIXUP_BASS_CHMAP, ALC1220_FIXUP_GB_DUAL_CODECS, @@ -507,6 +508,13 @@ static const struct hda_fixup alc882_fixups[] = { .type = HDA_FIXUP_FUNC, .v.func = alc882_fixup_no_primary_hp, }, + [ALC898_FIXUP_DELL_XPS8940_MIC] = { + .type = HDA_FIXUP_PINS, + .v.pins = (const struct hda_pintbl[]) { + { 0x19, 0x02a19130 }, /* headset mic, no separate jack detect */ + {} + }, + }, [ALC887_FIXUP_ASUS_BASS] = { .type = HDA_FIXUP_PINS, .v.pins = (const struct hda_pintbl[]) { @@ -610,6 +618,8 @@ static const struct hda_quirk alc882_fixup_tbl[] = { SND_PCI_QUIRK(0x1025, 0x0259, "Acer Aspire 5935", ALC889_FIXUP_DAC_ROUTE), SND_PCI_QUIRK(0x1025, 0x026b, "Acer Aspire 8940G", ALC882_FIXUP_ACER_ASPIRE_8930G), SND_PCI_QUIRK(0x1025, 0x0296, "Acer Aspire 7736z", ALC882_FIXUP_ACER_ASPIRE_7736), + SND_PCI_QUIRK(0x1028, 0x09c5, "Dell XPS 8940", + ALC898_FIXUP_DELL_XPS8940_MIC), SND_PCI_QUIRK(0x1043, 0x13c2, "Asus A7M", ALC882_FIXUP_EAPD), SND_PCI_QUIRK(0x1043, 0x1873, "ASUS W90V", ALC882_FIXUP_ASUS_W90V), SND_PCI_QUIRK(0x1043, 0x1971, "Asus W2JC", ALC882_FIXUP_ASUS_W2JC), diff --git a/sound/hda/codecs/side-codecs/cs35l56_hda.c b/sound/hda/codecs/side-codecs/cs35l56_hda.c index baf286bf7ec8..b55391fed61a 100644 --- a/sound/hda/codecs/side-codecs/cs35l56_hda.c +++ b/sound/hda/codecs/side-codecs/cs35l56_hda.c @@ -738,6 +738,8 @@ static void cs35l56_hda_unbind(struct device *dev, struct device *master, void * cs_dsp_cleanup_debugfs(&cs35l56->cs_dsp); debugfs_remove_recursive(cs35l56->debugfs_root); #endif + if (cs35l56->cs_dsp.running) + cs_dsp_stop(&cs35l56->cs_dsp); if (cs35l56->base.fw_patched) cs_dsp_power_down(&cs35l56->cs_dsp); diff --git a/sound/hda/codecs/side-codecs/tas2781_hda.c b/sound/hda/codecs/side-codecs/tas2781_hda.c index dc4e42fd8848..c44dfa2757b1 100644 --- a/sound/hda/codecs/side-codecs/tas2781_hda.c +++ b/sound/hda/codecs/side-codecs/tas2781_hda.c @@ -89,6 +89,7 @@ static void tas2781_apply_calib(struct tasdevice_priv *p) TASDEVICE_REG(0, 0x18, 0x7c), }; unsigned int crc, oft, node_num; + bool custom_addr = false; unsigned char *buf; int i, j, k, l; @@ -129,6 +130,7 @@ static void tas2781_apply_calib(struct tasdevice_priv *p) for (j = 0, k = 0; j < node_num; j++) { oft = j * 6 + 3; if (tmp_val[oft] == TASDEV_UEFI_CALI_REG_ADDR_FLG) { + custom_addr = true; for (i = 0; i < TASDEV_CALIB_N; i++) { buf = &data[(oft + i + 1) * 4]; cali_reg[i] = TASDEVICE_REG(buf[1], @@ -188,7 +190,7 @@ static void tas2781_apply_calib(struct tasdevice_priv *p) } } - if (p->dspbin_typ == TASDEV_BASIC) { + if (custom_addr || p->dspbin_typ == TASDEV_BASIC) { r->r0_reg = cali_reg[0]; r->invr0_reg = cali_reg[1]; r->r0_low_reg = cali_reg[2]; diff --git a/sound/hda/common/sysfs.c b/sound/hda/common/sysfs.c index 121a54ea3150..7d9157d2c8c1 100644 --- a/sound/hda/common/sysfs.c +++ b/sound/hda/common/sysfs.c @@ -511,11 +511,12 @@ static inline int strmatch(const char *a, const char *b) static void parse_codec_mode(char *buf, struct hda_bus *bus, struct hda_codec **codecp) { - int vendorid, subid, caddr; + long long vendorid, subid; + int caddr; struct hda_codec *codec; *codecp = NULL; - if (sscanf(buf, "%i %i %i", &vendorid, &subid, &caddr) == 3) { + if (sscanf(buf, "%lli %lli %i", &vendorid, &subid, &caddr) == 3) { list_for_each_codec(codec, bus) { if ((vendorid <= 0 || codec->core.vendor_id == vendorid) && (subid <= 0 || codec->core.subsystem_id == subid) && diff --git a/sound/hda/core/controller.c b/sound/hda/core/controller.c index a7c00ad80117..fd09b4b18fd8 100644 --- a/sound/hda/core/controller.c +++ b/sound/hda/core/controller.c @@ -426,6 +426,13 @@ int snd_hdac_bus_parse_capabilities(struct hdac_bus *bus) break; } + /* An all-zero header means no capability is present here */ + if (!cur_cap) { + dev_dbg(bus->dev, "Empty capability header at offset 0x%x\n", + offset); + break; + } + switch ((cur_cap & AZX_CAP_HDR_ID_MASK) >> AZX_CAP_HDR_ID_OFF) { case AZX_ML_CAP_ID: dev_dbg(bus->dev, "Found ML capability\n"); @@ -456,7 +463,8 @@ int snd_hdac_bus_parse_capabilities(struct hdac_bus *bus) break; default: - dev_err(bus->dev, "Unknown capability %d\n", cur_cap); + dev_err(bus->dev, "Unknown capability ID 0x%x\n", + (cur_cap & AZX_CAP_HDR_ID_MASK) >> AZX_CAP_HDR_ID_OFF); cur_cap = 0; break; } diff --git a/sound/pci/Kconfig b/sound/pci/Kconfig index e0996a9d90b0..776d778fa30e 100644 --- a/sound/pci/Kconfig +++ b/sound/pci/Kconfig @@ -141,6 +141,7 @@ config SND_AU8830 config SND_AW2 tristate "Emagic Audiowerk 2" + select SND_PCM help Say Y here to include support for Emagic Audiowerk 2 soundcards. diff --git a/sound/soc/amd/acp/acp3x-es83xx/acp3x-es83xx.c b/sound/soc/amd/acp/acp3x-es83xx/acp3x-es83xx.c index 8f65720b153f..56a733a1ba9b 100644 --- a/sound/soc/amd/acp/acp3x-es83xx/acp3x-es83xx.c +++ b/sound/soc/amd/acp/acp3x-es83xx/acp3x-es83xx.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include "../acp-mach.h" @@ -61,6 +62,8 @@ static const struct snd_pcm_hw_constraint_list constraints_channels = { #define ES83xx_12288_KHZ_MCLK_FREQ (48000 * 256) #define ES83xx_48_MHZ_MCLK_FREQ (48000 * 1000) +#define ES83XX_AMP_ON_DELAY_MS 50 + static int acp3x_es83xx_headphone_power_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event); static int acp3x_es83xx_speaker_power_event(struct snd_soc_dapm_widget *w, @@ -115,7 +118,7 @@ static struct snd_soc_jack_pin es83xx_jack_pins[] = { }; static const struct snd_soc_dapm_widget acp3x_es83xx_widgets[] = { - SND_SOC_DAPM_SPK("Speaker", NULL), + SND_SOC_DAPM_SPK("Speaker", acp3x_es83xx_speaker_power_event), SND_SOC_DAPM_HP("Headphone", NULL), SND_SOC_DAPM_MIC("Headset Mic", NULL), SND_SOC_DAPM_MIC("Internal Mic", NULL), @@ -123,9 +126,6 @@ static const struct snd_soc_dapm_widget acp3x_es83xx_widgets[] = { SND_SOC_DAPM_SUPPLY("Headphone Power", SND_SOC_NOPM, 0, 0, acp3x_es83xx_headphone_power_event, SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMU), - SND_SOC_DAPM_SUPPLY("Speaker Power", SND_SOC_NOPM, 0, 0, - acp3x_es83xx_speaker_power_event, - SND_SOC_DAPM_PRE_PMD | SND_SOC_DAPM_POST_PMU), }; static const struct snd_soc_dapm_route acp3x_es83xx_audio_map[] = { @@ -139,7 +139,6 @@ static const struct snd_soc_dapm_route acp3x_es83xx_audio_map[] = { */ {"Speaker", NULL, "HPOL"}, {"Speaker", NULL, "HPOR"}, - {"Speaker", NULL, "Speaker Power"}, }; @@ -185,10 +184,13 @@ static int acp3x_es83xx_speaker_power_event(struct snd_soc_dapm_widget *w, struct acp3x_es83xx_private *priv = get_mach_priv(w->dapm->card); dev_dbg(priv->codec_dev, "speaker power event: %d\n", event); - if (SND_SOC_DAPM_EVENT_ON(event)) + if (SND_SOC_DAPM_EVENT_ON(event)) { + /* Let the codec output settle before enabling the amplifier */ + msleep(ES83XX_AMP_ON_DELAY_MS); priv->speaker_on = true; - else + } else { priv->speaker_on = false; + } gpiod_set_value_cansleep(priv->gpio_speakers, priv->speaker_on); gpiod_set_value_cansleep(priv->gpio_headphone, priv->headphone_on); diff --git a/sound/soc/amd/ps/pci-ps.c b/sound/soc/amd/ps/pci-ps.c index c75aac4af73b..07bdfdf0d760 100644 --- a/sound/soc/amd/ps/pci-ps.c +++ b/sound/soc/amd/ps/pci-ps.c @@ -26,16 +26,20 @@ static void handle_acp70_sdw_wake_event(struct acp63_dev_data *adata) struct amd_sdw_manager *amd_manager; if (adata->acp70_sdw0_wake_event) { - amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); - if (amd_manager) - pm_request_resume(amd_manager->dev); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); + if (amd_manager) + pm_request_resume(amd_manager->dev); + } adata->acp70_sdw0_wake_event = 0; } if (adata->acp70_sdw1_wake_event) { - amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); - if (amd_manager) - pm_request_resume(amd_manager->dev); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); + if (amd_manager) + pm_request_resume(amd_manager->dev); + } adata->acp70_sdw1_wake_event = 0; } } @@ -209,18 +213,22 @@ static irqreturn_t acp63_irq_handler(int irq, void *dev_id) ext_intr_stat = readl(adata->acp63_base + ACP_EXTERNAL_INTR_STAT); if (ext_intr_stat & ACP_SDW0_STAT) { writel(ACP_SDW0_STAT, adata->acp63_base + ACP_EXTERNAL_INTR_STAT); - amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); - if (amd_manager) - schedule_work(&amd_manager->amd_sdw_irq_thread); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); + if (amd_manager) + schedule_work(&amd_manager->amd_sdw_irq_thread); + } irq_flag = 1; } ext_intr_stat1 = readl(adata->acp63_base + ACP_EXTERNAL_INTR_STAT1); if (ext_intr_stat1 & ACP_SDW1_STAT) { writel(ACP_SDW1_STAT, adata->acp63_base + ACP_EXTERNAL_INTR_STAT1); - amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); - if (amd_manager) - schedule_work(&amd_manager->amd_sdw_irq_thread); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); + if (amd_manager) + schedule_work(&amd_manager->amd_sdw_irq_thread); + } irq_flag = 1; } diff --git a/sound/soc/codecs/max98090.c b/sound/soc/codecs/max98090.c index 830caf62d0fa..f686f80b2c52 100644 --- a/sound/soc/codecs/max98090.c +++ b/sound/soc/codecs/max98090.c @@ -743,14 +743,6 @@ static int max98090_micinput_event(struct snd_soc_dapm_widget *w, else val = (val & M98090_MIC_PA2EN_MASK) >> M98090_MIC_PA2EN_SHIFT; - if (val >= 1) { - if (w->reg == M98090_REG_MIC1_INPUT_LEVEL) { - max98090->pa1en = val - 1; /* Update for volatile */ - } else { - max98090->pa2en = val - 1; /* Update for volatile */ - } - } - switch (event) { case SND_SOC_DAPM_POST_PMU: /* If turning on, set to most recently selected volume */ @@ -759,6 +751,14 @@ static int max98090_micinput_event(struct snd_soc_dapm_widget *w, else val = max98090->pa2en + 1; break; + case SND_SOC_DAPM_PRE_PMD: + if (val >= 1) { + if (w->reg == M98090_REG_MIC1_INPUT_LEVEL) + max98090->pa1en = val - 1; + else + max98090->pa2en = val - 1; + } + return 0; case SND_SOC_DAPM_POST_PMD: /* If turning off, turn off */ val = 0; @@ -1108,11 +1108,13 @@ static const struct snd_soc_dapm_widget max98090_dapm_widgets[] = { SND_SOC_DAPM_PGA_E("MIC1 Input", M98090_REG_MIC1_INPUT_LEVEL, M98090_MIC_PA1EN_SHIFT, 0, NULL, 0, max98090_micinput_event, - SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), + SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | + SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_PGA_E("MIC2 Input", M98090_REG_MIC2_INPUT_LEVEL, M98090_MIC_PA2EN_SHIFT, 0, NULL, 0, max98090_micinput_event, - SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), + SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD | + SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MIXER("LINEA Mixer", SND_SOC_NOPM, 0, 0, &max98090_linea_mixer_controls[0], diff --git a/sound/soc/codecs/wm_adsp.c b/sound/soc/codecs/wm_adsp.c index 751a3c25e4f0..7c1c2ba7a0f6 100644 --- a/sound/soc/codecs/wm_adsp.c +++ b/sound/soc/codecs/wm_adsp.c @@ -44,6 +44,9 @@ #define adsp_dbg(_dsp, fmt, ...) \ dev_dbg(_dsp->cs_dsp.dev, "%s: " fmt, _dsp->cs_dsp.name, ##__VA_ARGS__) +#define adsp_warn_once(_dsp, fmt, ...) \ + dev_warn_once(_dsp->cs_dsp.dev, "%s: " fmt, _dsp->cs_dsp.name, ##__VA_ARGS__) + #define compr_err(_obj, fmt, ...) \ adsp_err(_obj->dsp, "%s: " fmt, _obj->name ? _obj->name : "legacy", \ ##__VA_ARGS__) @@ -619,6 +622,13 @@ int wm_adsp_control_add(struct cs_dsp_coeff_ctl *cs_ctl) if (dsp->component->name_prefix) avail -= strlen(dsp->component->name_prefix) + 1; + if (avail < 1) { + adsp_warn_once(dsp, + "%.*s: ALSA prefix too long: control not created\n", + cs_ctl->subname_len, cs_ctl->subname); + return -EINVAL; + } + /* Truncate the subname from the start if it is too long */ if (cs_ctl->subname_len > avail) skip = cs_ctl->subname_len - avail; diff --git a/sound/soc/mediatek/mt8188/mt8188-audsys-clk.c b/sound/soc/mediatek/mt8188/mt8188-audsys-clk.c index 40d2ab0a7677..4d0d65e217bc 100644 --- a/sound/soc/mediatek/mt8188/mt8188-audsys-clk.c +++ b/sound/soc/mediatek/mt8188/mt8188-audsys-clk.c @@ -170,7 +170,7 @@ int mt8188_audsys_clk_register(struct mtk_base_afe *afe) struct mt8188_afe_private *afe_priv = afe->platform_priv; struct clk *clk; struct clk_lookup *cl; - int i; + int i, ret; afe_priv->lookup = devm_kcalloc(afe->dev, CLK_AUD_NR_CLK, sizeof(*afe_priv->lookup), @@ -179,6 +179,10 @@ int mt8188_audsys_clk_register(struct mtk_base_afe *afe) if (!afe_priv->lookup) return -ENOMEM; + ret = devm_add_action_or_reset(afe->dev, mt8188_audsys_clk_unregister, afe); + if (ret) + return ret; + for (i = 0; i < ARRAY_SIZE(aud_clks); i++) { const struct afe_gate *gate = &aud_clks[i]; @@ -194,8 +198,10 @@ int mt8188_audsys_clk_register(struct mtk_base_afe *afe) /* add clk_lookup for devm_clk_get(SND_SOC_DAPM_CLOCK_SUPPLY) */ cl = kzalloc(sizeof(*cl), GFP_KERNEL); - if (!cl) + if (!cl) { + clk_unregister_gate(clk); return -ENOMEM; + } cl->clk = clk; cl->con_id = gate->name; @@ -206,5 +212,5 @@ int mt8188_audsys_clk_register(struct mtk_base_afe *afe) afe_priv->lookup[i] = cl; } - return devm_add_action_or_reset(afe->dev, mt8188_audsys_clk_unregister, afe); + return 0; } diff --git a/sound/soc/meson/axg-fifo.c b/sound/soc/meson/axg-fifo.c index 75909196b769..edf43b7fb5cf 100644 --- a/sound/soc/meson/axg-fifo.c +++ b/sound/soc/meson/axg-fifo.c @@ -244,17 +244,10 @@ int axg_fifo_pcm_open(struct snd_soc_component *component, if (ret) return ret; - /* Use the threaded irq handler only with non-atomic links */ - ret = request_threaded_irq(fifo->irq, NULL, - axg_fifo_pcm_irq_block, - IRQF_ONESHOT, dev_name(dev), ss); - if (ret) - return ret; - /* Enable pclk to access registers and clock the fifo ip */ ret = clk_prepare_enable(fifo->pclk); if (ret) - goto free_irq; + return ret; /* Setup status2 so it reports the memory pointer */ regmap_update_bits(fifo->map, FIFO_CTRL1, @@ -271,17 +264,24 @@ int axg_fifo_pcm_open(struct snd_soc_component *component, /* Clear any pending interrupt */ axg_fifo_ack_irq(fifo, FIFO_INT_MASK); + /* Use the threaded irq handler only with non-atomic links */ + ret = request_threaded_irq(fifo->irq, NULL, + axg_fifo_pcm_irq_block, + IRQF_ONESHOT, dev_name(dev), ss); + if (ret) + goto free_clk; + /* Take memory arbitror out of reset */ ret = reset_control_deassert(fifo->arb); if (ret) - goto free_clk; + goto free_irq; return 0; -free_clk: - clk_disable_unprepare(fifo->pclk); free_irq: free_irq(fifo->irq, ss); +free_clk: + clk_disable_unprepare(fifo->pclk); return ret; } EXPORT_SYMBOL_GPL(axg_fifo_pcm_open); @@ -295,12 +295,12 @@ int axg_fifo_pcm_close(struct snd_soc_component *component, /* Put the memory arbitror back in reset */ ret = reset_control_assert(fifo->arb); - /* Disable fifo ip and register access */ - clk_disable_unprepare(fifo->pclk); - /* remove IRQ */ free_irq(fifo->irq, ss); + /* Disable fifo ip and register access */ + clk_disable_unprepare(fifo->pclk); + return ret; } EXPORT_SYMBOL_GPL(axg_fifo_pcm_close); diff --git a/sound/soc/qcom/common.c b/sound/soc/qcom/common.c index 7ee60a58a336..71cbdd1a44ca 100644 --- a/sound/soc/qcom/common.c +++ b/sound/soc/qcom/common.c @@ -23,6 +23,161 @@ static const struct snd_soc_dapm_widget qcom_jack_snd_widgets[] = { SND_SOC_DAPM_SPK("DP7 Jack", NULL), }; +static struct device_node *qcom_snd_get_link_node(struct snd_soc_pcm_runtime *rtd) +{ + struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); + struct snd_soc_card *card = rtd->card; + struct of_phandle_args args; + int ret; + + if (!card->dev || !card->dev->of_node) + return NULL; + + for_each_available_child_of_node_scoped(card->dev->of_node, np) { + struct device_node *cpu_np __free(device_node) = + of_get_child_by_name(np, "cpu"); + + if (!cpu_np) + continue; + + ret = of_parse_phandle_with_args(cpu_np, "sound-dai", "#sound-dai-cells", 0, + &args); + if (ret) + continue; + + if (args.np == rtd->dai_link->cpus[0].of_node && + args.args_count == 1 && args.args[0] == cpu_dai->id) { + of_node_put(args.np); + return of_node_get(np); + } + + of_node_put(args.np); + } + + return NULL; +} + +static int qcom_snd_parse_tdm_slot(struct device_node *np, + struct qcom_snd_tdm_slot_cfg *cfg) +{ + memset(cfg, 0, sizeof(*cfg)); + + return snd_soc_of_parse_tdm_slot(np, &cfg->tx_mask, &cfg->rx_mask, + &cfg->slots, &cfg->slot_width); +} + +static int qcom_snd_normalize_tdm_slots(struct qcom_snd_tdm_slot_cfg *cpu_cfg, + struct qcom_snd_tdm_slot_cfg *codec_cfg) +{ + unsigned int slots; + unsigned int slot_width; + + if (cpu_cfg->slots && codec_cfg->slots && cpu_cfg->slots != codec_cfg->slots) + return -EINVAL; + + if (cpu_cfg->slot_width && codec_cfg->slot_width && + cpu_cfg->slot_width != codec_cfg->slot_width) + return -EINVAL; + + slots = cpu_cfg->slots ?: codec_cfg->slots; + if (!slots) + return 0; + + slot_width = cpu_cfg->slot_width ?: codec_cfg->slot_width; + if (!slot_width) + return -EINVAL; + + cpu_cfg->slots = slots; + codec_cfg->slots = slots; + cpu_cfg->slot_width = slot_width; + codec_cfg->slot_width = slot_width; + + return 0; +} + +static int qcom_snd_parse_dai_tdm_slots(struct snd_soc_pcm_runtime *rtd, + struct qcom_snd_tdm_slot_cfg *cpu_cfg, + struct qcom_snd_tdm_slot_cfg *codec_cfg) +{ + struct device_node *link_np __free(device_node) = qcom_snd_get_link_node(rtd); + int ret; + + if (!link_np) + return -EINVAL; + + struct device_node *cpu_np __free(device_node) = + of_get_child_by_name(link_np, "cpu"); + struct device_node *codec_np __free(device_node) = + of_get_child_by_name(link_np, "codec"); + if (!cpu_np || !codec_np) + return -EINVAL; + + ret = qcom_snd_parse_tdm_slot(cpu_np, cpu_cfg); + if (ret) + return ret; + + return qcom_snd_parse_tdm_slot(codec_np, codec_cfg); +} + +int qcom_snd_get_dai_tdm_slots(struct snd_soc_pcm_runtime *rtd, + struct qcom_snd_tdm_slot_cfg *cpu_cfg, + struct qcom_snd_tdm_slot_cfg *codec_cfg) +{ + int ret; + + ret = qcom_snd_parse_dai_tdm_slots(rtd, cpu_cfg, codec_cfg); + if (ret) + return ret; + + return qcom_snd_normalize_tdm_slots(cpu_cfg, codec_cfg); +} +EXPORT_SYMBOL_GPL(qcom_snd_get_dai_tdm_slots); + +int qcom_snd_apply_dai_tdm_slots_cfg(struct snd_soc_pcm_runtime *rtd, + const struct qcom_snd_tdm_slot_cfg *cpu_cfg, + const struct qcom_snd_tdm_slot_cfg *codec_cfg) +{ + struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); + struct snd_soc_dai *codec_dai; + int i; + int ret; + + if (!cpu_cfg->slots) + return 0; + + ret = snd_soc_dai_set_tdm_slot(cpu_dai, cpu_cfg->tx_mask, cpu_cfg->rx_mask, + cpu_cfg->slots, cpu_cfg->slot_width); + if (ret) + return ret; + + for_each_rtd_codec_dais(rtd, i, codec_dai) { + ret = snd_soc_dai_set_tdm_slot(codec_dai, + codec_cfg->tx_mask, + codec_cfg->rx_mask, + codec_cfg->slots, + codec_cfg->slot_width); + if (ret) + return ret; + } + + return 0; +} +EXPORT_SYMBOL_GPL(qcom_snd_apply_dai_tdm_slots_cfg); + +int qcom_snd_apply_dai_tdm_slots(struct snd_soc_pcm_runtime *rtd) +{ + struct qcom_snd_tdm_slot_cfg cpu_cfg; + struct qcom_snd_tdm_slot_cfg codec_cfg; + int ret; + + ret = qcom_snd_get_dai_tdm_slots(rtd, &cpu_cfg, &codec_cfg); + if (ret) + return ret == -EINVAL ? 0 : ret; + + return qcom_snd_apply_dai_tdm_slots_cfg(rtd, &cpu_cfg, &codec_cfg); +} +EXPORT_SYMBOL_GPL(qcom_snd_apply_dai_tdm_slots); + int qcom_snd_parse_of(struct snd_soc_card *card) { struct device_node *np; @@ -120,6 +275,12 @@ int qcom_snd_parse_of(struct snd_soc_card *card) link->id = args.args[0]; + if (link->id >= LPASS_MAX_PORT) { + dev_err(dev, "%s: Invalid cpu dai id %d\n", link->name, link->id); + ret = -EINVAL; + goto err; + } + if (platform) { link->platforms->of_node = of_parse_phandle(platform, "sound-dai", @@ -195,13 +356,11 @@ static struct snd_soc_jack_pin qcom_headset_jack_pins[] = { }, }; -int qcom_snd_wcd_jack_setup(struct snd_soc_pcm_runtime *rtd, - struct snd_soc_jack *jack, bool *jack_setup) +static int qcom_snd_headset_jack_init(struct snd_soc_card *card, + struct snd_soc_jack *jack, + bool *jack_setup) { - struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); - struct snd_soc_dai *codec_dai = snd_soc_rtd_to_codec(rtd, 0); - struct snd_soc_card *card = rtd->card; - int rval, i; + int rval; if (!*jack_setup) { rval = snd_soc_card_jack_new_pins(card, "Headset Jack", @@ -225,6 +384,55 @@ int qcom_snd_wcd_jack_setup(struct snd_soc_pcm_runtime *rtd, *jack_setup = true; } + return 0; +} + +int qcom_snd_headset_jack_setup(struct snd_soc_pcm_runtime *rtd, + struct snd_soc_jack *jack, bool *jack_setup) +{ + struct snd_soc_dai *codec_dai; + struct snd_soc_card *card = rtd->card; + int rval, i; + + rval = qcom_snd_headset_jack_init(card, jack, jack_setup); + if (rval) + return rval; + + for_each_rtd_codec_dais(rtd, i, codec_dai) { + rval = snd_soc_component_set_jack(codec_dai->component, jack, NULL); + if (rval != 0 && rval != -ENOTSUPP) { + dev_warn(card->dev, "Failed to set jack: %d\n", rval); + qcom_snd_headset_jack_cleanup(rtd); + return rval; + } + } + + return 0; +} +EXPORT_SYMBOL_GPL(qcom_snd_headset_jack_setup); + +void qcom_snd_headset_jack_cleanup(struct snd_soc_pcm_runtime *rtd) +{ + struct snd_soc_dai *codec_dai; + int i; + + for_each_rtd_codec_dais(rtd, i, codec_dai) + snd_soc_component_set_jack(codec_dai->component, NULL, NULL); +} +EXPORT_SYMBOL_GPL(qcom_snd_headset_jack_cleanup); + +int qcom_snd_wcd_jack_setup(struct snd_soc_pcm_runtime *rtd, + struct snd_soc_jack *jack, bool *jack_setup) +{ + struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); + struct snd_soc_dai *codec_dai = snd_soc_rtd_to_codec(rtd, 0); + struct snd_soc_card *card = rtd->card; + int rval, i; + + rval = qcom_snd_headset_jack_init(card, jack, jack_setup); + if (rval) + return rval; + switch (cpu_dai->id) { case TX_CODEC_DMA_TX_0: case TX_CODEC_DMA_TX_1: @@ -243,8 +451,6 @@ int qcom_snd_wcd_jack_setup(struct snd_soc_pcm_runtime *rtd, default: break; } - - return 0; } EXPORT_SYMBOL_GPL(qcom_snd_wcd_jack_setup); diff --git a/sound/soc/qcom/common.h b/sound/soc/qcom/common.h index 1b8d3f90bffa..6705e135ccd7 100644 --- a/sound/soc/qcom/common.h +++ b/sound/soc/qcom/common.h @@ -4,9 +4,29 @@ #ifndef __QCOM_SND_COMMON_H__ #define __QCOM_SND_COMMON_H__ +#include #include +#define LPASS_MAX_PORT (SENARY_MI2S_TX + 1) + +struct qcom_snd_tdm_slot_cfg { + unsigned int tx_mask; + unsigned int rx_mask; + unsigned int slots; + unsigned int slot_width; +}; + int qcom_snd_parse_of(struct snd_soc_card *card); +int qcom_snd_get_dai_tdm_slots(struct snd_soc_pcm_runtime *rtd, + struct qcom_snd_tdm_slot_cfg *cpu_cfg, + struct qcom_snd_tdm_slot_cfg *codec_cfg); +int qcom_snd_apply_dai_tdm_slots_cfg(struct snd_soc_pcm_runtime *rtd, + const struct qcom_snd_tdm_slot_cfg *cpu_cfg, + const struct qcom_snd_tdm_slot_cfg *codec_cfg); +int qcom_snd_apply_dai_tdm_slots(struct snd_soc_pcm_runtime *rtd); +int qcom_snd_headset_jack_setup(struct snd_soc_pcm_runtime *rtd, + struct snd_soc_jack *jack, bool *jack_setup); +void qcom_snd_headset_jack_cleanup(struct snd_soc_pcm_runtime *rtd); int qcom_snd_wcd_jack_setup(struct snd_soc_pcm_runtime *rtd, struct snd_soc_jack *jack, bool *jack_setup); int qcom_snd_dp_jack_setup(struct snd_soc_pcm_runtime *rtd, diff --git a/sound/soc/qcom/lpass.h b/sound/soc/qcom/lpass.h index de3ec6f594c1..68b71039b981 100644 --- a/sound/soc/qcom/lpass.h +++ b/sound/soc/qcom/lpass.h @@ -14,10 +14,11 @@ #include #include #include +#include "common.h" #include "lpass-hdmi.h" #define LPASS_AHBIX_CLOCK_FREQUENCY 131072000 -#define LPASS_MAX_PORTS (DISPLAY_PORT_RX_7 + 1) +#define LPASS_MAX_PORTS (LPASS_MAX_PORT) #define LPASS_MAX_MI2S_PORTS (8) #define LPASS_MAX_DMA_CHANNELS (8) #define LPASS_MAX_HDMI_DMA_CHANNELS (4) diff --git a/sound/soc/qcom/qdsp6/q6afe.h b/sound/soc/qcom/qdsp6/q6afe.h index a29abe4ce436..0b8c3ec1315c 100644 --- a/sound/soc/qcom/qdsp6/q6afe.h +++ b/sound/soc/qcom/qdsp6/q6afe.h @@ -2,8 +2,9 @@ #ifndef __Q6AFE_H__ #define __Q6AFE_H__ +#include "../common.h" -#define AFE_PORT_MAX 137 +#define AFE_PORT_MAX (LPASS_MAX_PORT) #define MSM_AFE_PORT_TYPE_RX 0 #define MSM_AFE_PORT_TYPE_TX 1 diff --git a/sound/soc/qcom/qdsp6/q6apm.h b/sound/soc/qcom/qdsp6/q6apm.h index 7ce08b401e31..5cf538397841 100644 --- a/sound/soc/qcom/qdsp6/q6apm.h +++ b/sound/soc/qcom/qdsp6/q6apm.h @@ -14,9 +14,10 @@ #include #include #include +#include "../common.h" #include "audioreach.h" -#define APM_PORT_MAX 127 +#define APM_PORT_MAX LPASS_MAX_PORT #define APM_PORT_MAX_AUDIO_CHAN_CNT 8 #define PCM_CHANNEL_NULL 0 #define PCM_CHANNEL_FL 1 /* Front left channel. */ diff --git a/sound/soc/qcom/sc8280xp.c b/sound/soc/qcom/sc8280xp.c index ed8b04c6022e..b3f2558c9fb8 100644 --- a/sound/soc/qcom/sc8280xp.c +++ b/sound/soc/qcom/sc8280xp.c @@ -18,7 +18,6 @@ struct sc8280xp_snd_data { bool stream_prepared[AFE_PORT_MAX]; struct snd_soc_card *card; - struct sdw_stream_runtime *sruntime[AFE_PORT_MAX]; struct snd_soc_jack jack; struct snd_soc_jack dp_jack[8]; bool jack_setup; @@ -68,17 +67,6 @@ static int sc8280xp_snd_init(struct snd_soc_pcm_runtime *rtd) return qcom_snd_wcd_jack_setup(rtd, &data->jack, &data->jack_setup); } -static void sc8280xp_snd_shutdown(struct snd_pcm_substream *substream) -{ - struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); - struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); - struct sc8280xp_snd_data *pdata = snd_soc_card_get_drvdata(rtd->card); - struct sdw_stream_runtime *sruntime = qcom_snd_sdw_get_stream(substream); - - pdata->sruntime[cpu_dai->id] = NULL; - sdw_release_stream(sruntime); -} - static int sc8280xp_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, struct snd_pcm_hw_params *params) { @@ -108,25 +96,13 @@ static int sc8280xp_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, return 0; } -static int sc8280xp_snd_hw_params(struct snd_pcm_substream *substream, - struct snd_pcm_hw_params *params) -{ - struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); - struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); - struct sc8280xp_snd_data *pdata = snd_soc_card_get_drvdata(rtd->card); - - return qcom_snd_sdw_hw_params(substream, params, &pdata->sruntime[cpu_dai->id]); -} - static int sc8280xp_snd_prepare(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); struct sc8280xp_snd_data *data = snd_soc_card_get_drvdata(rtd->card); - struct sdw_stream_runtime *sruntime = data->sruntime[cpu_dai->id]; - return qcom_snd_sdw_prepare(substream, sruntime, - &data->stream_prepared[cpu_dai->id]); + return qcom_snd_sdw_prepare(substream, &data->stream_prepared[cpu_dai->id]); } static int sc8280xp_snd_hw_free(struct snd_pcm_substream *substream) @@ -134,16 +110,13 @@ static int sc8280xp_snd_hw_free(struct snd_pcm_substream *substream) struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); struct sc8280xp_snd_data *data = snd_soc_card_get_drvdata(rtd->card); struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); - struct sdw_stream_runtime *sruntime = data->sruntime[cpu_dai->id]; - return qcom_snd_sdw_hw_free(substream, sruntime, - &data->stream_prepared[cpu_dai->id]); + return qcom_snd_sdw_hw_free(substream, &data->stream_prepared[cpu_dai->id]); } static const struct snd_soc_ops sc8280xp_be_ops = { .startup = qcom_snd_sdw_startup, - .shutdown = sc8280xp_snd_shutdown, - .hw_params = sc8280xp_snd_hw_params, + .shutdown = qcom_snd_sdw_shutdown, .hw_free = sc8280xp_snd_hw_free, .prepare = sc8280xp_snd_prepare, }; diff --git a/sound/soc/qcom/sdw.c b/sound/soc/qcom/sdw.c index 5f880c74c8dc..6576b47a4c8c 100644 --- a/sound/soc/qcom/sdw.c +++ b/sound/soc/qcom/sdw.c @@ -124,19 +124,21 @@ int qcom_snd_sdw_startup(struct snd_pcm_substream *substream) EXPORT_SYMBOL_GPL(qcom_snd_sdw_startup); int qcom_snd_sdw_prepare(struct snd_pcm_substream *substream, - struct sdw_stream_runtime *sruntime, bool *stream_prepared) { struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); + struct sdw_stream_runtime *sruntime; int ret; - if (!sruntime) - return 0; if (!qcom_snd_is_sdw_dai(cpu_dai->id)) return 0; + sruntime = qcom_snd_sdw_get_stream(substream); + if (!sruntime) + return 0; + if (*stream_prepared) return 0; @@ -183,26 +185,24 @@ struct sdw_stream_runtime *qcom_snd_sdw_get_stream(struct snd_pcm_substream *sub } EXPORT_SYMBOL_GPL(qcom_snd_sdw_get_stream); -int qcom_snd_sdw_hw_params(struct snd_pcm_substream *substream, - struct snd_pcm_hw_params *params, - struct sdw_stream_runtime **psruntime) +void qcom_snd_sdw_shutdown(struct snd_pcm_substream *substream) { - *psruntime = qcom_snd_sdw_get_stream(substream); - - return 0; + struct sdw_stream_runtime *sruntime = qcom_snd_sdw_get_stream(substream); + sdw_release_stream(sruntime); } -EXPORT_SYMBOL_GPL(qcom_snd_sdw_hw_params); +EXPORT_SYMBOL_GPL(qcom_snd_sdw_shutdown); -int qcom_snd_sdw_hw_free(struct snd_pcm_substream *substream, - struct sdw_stream_runtime *sruntime, bool *stream_prepared) +int qcom_snd_sdw_hw_free(struct snd_pcm_substream *substream, bool *stream_prepared) { struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); + struct sdw_stream_runtime *sruntime; if (!qcom_snd_is_sdw_dai(cpu_dai->id)) return 0; + sruntime = qcom_snd_sdw_get_stream(substream); if (sruntime && *stream_prepared) { sdw_disable_stream(sruntime); sdw_deprepare_stream(sruntime); diff --git a/sound/soc/qcom/sdw.h b/sound/soc/qcom/sdw.h index b8bc5beb0522..061a63f1ac52 100644 --- a/sound/soc/qcom/sdw.h +++ b/sound/soc/qcom/sdw.h @@ -7,14 +7,10 @@ #include int qcom_snd_sdw_startup(struct snd_pcm_substream *substream); +void qcom_snd_sdw_shutdown(struct snd_pcm_substream *substream); int qcom_snd_sdw_prepare(struct snd_pcm_substream *substream, - struct sdw_stream_runtime *runtime, bool *stream_prepared); struct sdw_stream_runtime *qcom_snd_sdw_get_stream(struct snd_pcm_substream *stream); -int qcom_snd_sdw_hw_params(struct snd_pcm_substream *substream, - struct snd_pcm_hw_params *params, - struct sdw_stream_runtime **psruntime); int qcom_snd_sdw_hw_free(struct snd_pcm_substream *substream, - struct sdw_stream_runtime *sruntime, bool *stream_prepared); #endif diff --git a/sound/soc/qcom/sm8250.c b/sound/soc/qcom/sm8250.c index ce5b0059207f..203a8705a42f 100644 --- a/sound/soc/qcom/sm8250.c +++ b/sound/soc/qcom/sm8250.c @@ -21,7 +21,6 @@ struct sm8250_snd_data { bool stream_prepared[AFE_PORT_MAX]; struct snd_soc_card *card; - struct sdw_stream_runtime *sruntime[AFE_PORT_MAX]; struct snd_soc_jack jack; struct snd_soc_jack usb_offload_jack; bool usb_offload_jack_setup; @@ -112,36 +111,13 @@ static int sm8250_snd_startup(struct snd_pcm_substream *substream) return qcom_snd_sdw_startup(substream); } -static void sm8250_snd_shutdown(struct snd_pcm_substream *substream) -{ - struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); - struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); - struct sm8250_snd_data *data = snd_soc_card_get_drvdata(rtd->card); - struct sdw_stream_runtime *sruntime = qcom_snd_sdw_get_stream(substream); - - data->sruntime[cpu_dai->id] = NULL; - sdw_release_stream(sruntime); -} - -static int sm8250_snd_hw_params(struct snd_pcm_substream *substream, - struct snd_pcm_hw_params *params) -{ - struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); - struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); - struct sm8250_snd_data *pdata = snd_soc_card_get_drvdata(rtd->card); - - return qcom_snd_sdw_hw_params(substream, params, &pdata->sruntime[cpu_dai->id]); -} - static int sm8250_snd_prepare(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); struct sm8250_snd_data *data = snd_soc_card_get_drvdata(rtd->card); - struct sdw_stream_runtime *sruntime = data->sruntime[cpu_dai->id]; - return qcom_snd_sdw_prepare(substream, sruntime, - &data->stream_prepared[cpu_dai->id]); + return qcom_snd_sdw_prepare(substream, &data->stream_prepared[cpu_dai->id]); } static int sm8250_snd_hw_free(struct snd_pcm_substream *substream) @@ -149,16 +125,13 @@ static int sm8250_snd_hw_free(struct snd_pcm_substream *substream) struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); struct sm8250_snd_data *data = snd_soc_card_get_drvdata(rtd->card); struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); - struct sdw_stream_runtime *sruntime = data->sruntime[cpu_dai->id]; - return qcom_snd_sdw_hw_free(substream, sruntime, - &data->stream_prepared[cpu_dai->id]); + return qcom_snd_sdw_hw_free(substream, &data->stream_prepared[cpu_dai->id]); } static const struct snd_soc_ops sm8250_be_ops = { .startup = sm8250_snd_startup, - .shutdown = sm8250_snd_shutdown, - .hw_params = sm8250_snd_hw_params, + .shutdown = qcom_snd_sdw_shutdown, .hw_free = sm8250_snd_hw_free, .prepare = sm8250_snd_prepare, }; diff --git a/sound/soc/qcom/x1e80100.c b/sound/soc/qcom/x1e80100.c index 2e3599516aa2..f9a1dfe3e6ae 100644 --- a/sound/soc/qcom/x1e80100.c +++ b/sound/soc/qcom/x1e80100.c @@ -18,7 +18,6 @@ struct x1e80100_snd_data { bool stream_prepared[AFE_PORT_MAX]; struct snd_soc_card *card; - struct sdw_stream_runtime *sruntime[AFE_PORT_MAX]; struct snd_soc_jack jack; struct snd_soc_jack dp_jack[8]; bool jack_setup; @@ -50,15 +49,21 @@ static int x1e80100_snd_init(struct snd_soc_pcm_runtime *rtd) return qcom_snd_wcd_jack_setup(rtd, &data->jack, &data->jack_setup); } -static void x1e80100_snd_shutdown(struct snd_pcm_substream *substream) +static void x1e80100_snd_exit(struct snd_soc_pcm_runtime *rtd) { - struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); - struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); struct x1e80100_snd_data *data = snd_soc_card_get_drvdata(rtd->card); - struct sdw_stream_runtime *sruntime = qcom_snd_sdw_get_stream(substream); + struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); - data->sruntime[cpu_dai->id] = NULL; - sdw_release_stream(sruntime); + switch (cpu_dai->id) { + case DISPLAY_PORT_RX_0: + case DISPLAY_PORT_RX_1 ... DISPLAY_PORT_RX_7: + return; + default: + break; + } + + qcom_snd_headset_jack_cleanup(rtd); + data->jack_setup = false; } static int x1e80100_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, @@ -85,16 +90,6 @@ static int x1e80100_be_hw_params_fixup(struct snd_soc_pcm_runtime *rtd, return 0; } -static int x1e80100_snd_hw_params(struct snd_pcm_substream *substream, - struct snd_pcm_hw_params *params) -{ - struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); - struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); - struct x1e80100_snd_data *data = snd_soc_card_get_drvdata(rtd->card); - - return qcom_snd_sdw_hw_params(substream, params, &data->sruntime[cpu_dai->id]); -} - static int x1e80100_snd_hw_map_channels(unsigned int *ch_map, int num) { switch (num) { @@ -128,7 +123,6 @@ static int x1e80100_snd_prepare(struct snd_pcm_substream *substream) struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); struct x1e80100_snd_data *data = snd_soc_card_get_drvdata(rtd->card); - struct sdw_stream_runtime *sruntime = data->sruntime[cpu_dai->id]; unsigned int channels = substream->runtime->channels; unsigned int rx_slot[4]; int ret; @@ -149,8 +143,7 @@ static int x1e80100_snd_prepare(struct snd_pcm_substream *substream) break; } - return qcom_snd_sdw_prepare(substream, sruntime, - &data->stream_prepared[cpu_dai->id]); + return qcom_snd_sdw_prepare(substream, &data->stream_prepared[cpu_dai->id]); } static int x1e80100_snd_hw_free(struct snd_pcm_substream *substream) @@ -158,16 +151,13 @@ static int x1e80100_snd_hw_free(struct snd_pcm_substream *substream) struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); struct x1e80100_snd_data *data = snd_soc_card_get_drvdata(rtd->card); struct snd_soc_dai *cpu_dai = snd_soc_rtd_to_cpu(rtd, 0); - struct sdw_stream_runtime *sruntime = data->sruntime[cpu_dai->id]; - return qcom_snd_sdw_hw_free(substream, sruntime, - &data->stream_prepared[cpu_dai->id]); + return qcom_snd_sdw_hw_free(substream, &data->stream_prepared[cpu_dai->id]); } static const struct snd_soc_ops x1e80100_be_ops = { .startup = qcom_snd_sdw_startup, - .shutdown = x1e80100_snd_shutdown, - .hw_params = x1e80100_snd_hw_params, + .shutdown = qcom_snd_sdw_shutdown, .hw_free = x1e80100_snd_hw_free, .prepare = x1e80100_snd_prepare, }; @@ -180,6 +170,7 @@ static void x1e80100_add_be_ops(struct snd_soc_card *card) for_each_card_prelinks(card, i, link) { if (link->no_pcm == 1) { link->init = x1e80100_snd_init; + link->exit = x1e80100_snd_exit; link->be_hw_params_fixup = x1e80100_be_hw_params_fixup; link->ops = &x1e80100_be_ops; } diff --git a/sound/soc/rockchip/Kconfig b/sound/soc/rockchip/Kconfig index bd210fafe9fe..0e5110125c14 100644 --- a/sound/soc/rockchip/Kconfig +++ b/sound/soc/rockchip/Kconfig @@ -5,6 +5,7 @@ menu "Rockchip" config SND_SOC_ROCKCHIP_I2S tristate "Rockchip I2S Device Driver" + select REGMAP_MMIO select SND_SOC_GENERIC_DMAENGINE_PCM help Say Y or M if you want to add support for I2S driver for @@ -13,6 +14,7 @@ config SND_SOC_ROCKCHIP_I2S config SND_SOC_ROCKCHIP_I2S_TDM tristate "Rockchip I2S/TDM Device Driver" + select REGMAP_MMIO select SND_SOC_GENERIC_DMAENGINE_PCM help Say Y or M if you want to add support for the I2S/TDM driver for @@ -23,6 +25,7 @@ config SND_SOC_ROCKCHIP_I2S_TDM config SND_SOC_ROCKCHIP_PDM tristate "Rockchip PDM Controller Driver" + select REGMAP_MMIO select SND_SOC_GENERIC_DMAENGINE_PCM select RATIONAL help @@ -32,6 +35,7 @@ config SND_SOC_ROCKCHIP_PDM config SND_SOC_ROCKCHIP_SAI tristate "Rockchip SAI Controller Driver" + select REGMAP_MMIO select SND_SOC_GENERIC_DMAENGINE_PCM help Say Y or M if you want to add support for the Rockchip Serial Audio @@ -41,6 +45,8 @@ config SND_SOC_ROCKCHIP_SAI config SND_SOC_ROCKCHIP_SPDIF tristate "Rockchip SPDIF Device Driver" + select REGMAP_MMIO + select SND_PCM_IEC958 select SND_SOC_GENERIC_DMAENGINE_PCM help Say Y or M if you want to add support for SPDIF driver for diff --git a/sound/soc/rockchip/rockchip_spdif.c b/sound/soc/rockchip/rockchip_spdif.c index 7a15f680de2f..be84b226827e 100644 --- a/sound/soc/rockchip/rockchip_spdif.c +++ b/sound/soc/rockchip/rockchip_spdif.c @@ -16,6 +16,7 @@ #include #include #include +#include #include #include "rockchip_spdif.h" @@ -27,7 +28,25 @@ enum rk_spdif_type { RK_SPDIF_RK3366, }; -#define RK3288_GRF_SOC_CON2 0x24c +/* + * | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | + * CS0: | Mode | d | c | b | a | + * CS1: | Category Code | + * CS2: | Channel Number | Source Number | + * CS3: | Clock Accuracy | Sample Freq | + * CS4: | Ori Sample Freq | Word Length | + * CS5: | | CGMS-A | + * CS6~CS23: Reserved + * + * a: use of channel status block + * b: linear PCM identification: 0 for lpcm, 1 for nlpcm + * c: copyright information + * d: additional format information + */ +#define CS_BYTE 6 +#define CS_FRAME(c) ((c) << 16 | (c)) + +#define RK3288_GRF_SOC_CON2 0x24c struct rk_spdif_dev { struct device *dev; @@ -110,39 +129,63 @@ static int rk_spdif_hw_params(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct rk_spdif_dev *spdif = snd_soc_dai_get_drvdata(dai); + unsigned int mclk_rate = clk_get_rate(spdif->mclk); unsigned int val = SPDIF_CFGR_HALFWORD_ENABLE; - int srate, mclk; - int ret; + int bmc, div, ret, i; + u16 *fc; + u8 cs[CS_BYTE]; + + ret = snd_pcm_create_iec958_consumer_hw_params(params, cs, sizeof(cs)); + if (ret < 0) + return ret; - srate = params_rate(params); - mclk = srate * 128; + fc = (u16 *)cs; + for (i = 0; i < CS_BYTE / 2; i++) + regmap_write(spdif->regmap, SPDIF_CHNSRn(i), CS_FRAME(fc[i])); + + regmap_update_bits(spdif->regmap, SPDIF_CFGR, SPDIF_CFGR_CSE_MASK, + SPDIF_CFGR_CSE_EN); + + /* bmc = 128fs */ + bmc = 128 * params_rate(params); + div = DIV_ROUND_CLOSEST(mclk_rate, bmc); + val |= SPDIF_CFGR_CLK_DIV(div); switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: val |= SPDIF_CFGR_VDW_16; + val |= SPDIF_CFGR_ADJ_RIGHT_J; break; case SNDRV_PCM_FORMAT_S20_3LE: val |= SPDIF_CFGR_VDW_20; + val |= SPDIF_CFGR_ADJ_RIGHT_J; break; case SNDRV_PCM_FORMAT_S24_LE: val |= SPDIF_CFGR_VDW_24; + val |= SPDIF_CFGR_ADJ_RIGHT_J; + break; + case SNDRV_PCM_FORMAT_S32_LE: + val |= SPDIF_CFGR_VDW_24; + val |= SPDIF_CFGR_ADJ_LEFT_J; break; default: return -EINVAL; } - /* Set clock and calculate divider */ - ret = clk_set_rate(spdif->mclk, mclk); - if (ret != 0) { - dev_err(spdif->dev, "Failed to set module clock rate: %d\n", - ret); - return ret; - } + /* + * clear MCLK domain logic before setting Fmclk and Fsdo to ensure + * that switching between S16_LE and S32_LE audio does not result + * in accidential channels swap. + */ + regmap_update_bits(spdif->regmap, SPDIF_CFGR, SPDIF_CFGR_CLR_MASK, + SPDIF_CFGR_CLR_EN); + udelay(1); ret = regmap_update_bits(spdif->regmap, SPDIF_CFGR, SPDIF_CFGR_CLK_DIV_MASK | SPDIF_CFGR_HALFWORD_ENABLE | - SDPIF_CFGR_VDW_MASK, val); + SDPIF_CFGR_VDW_MASK | + SPDIF_CFGR_ADJ_MASK, val); return ret; } @@ -201,7 +244,24 @@ static int rk_spdif_dai_probe(struct snd_soc_dai *dai) return 0; } +static int rk_spdif_set_sysclk(struct snd_soc_dai *dai, + int clk_id, unsigned int freq, int dir) +{ + struct rk_spdif_dev *spdif = snd_soc_dai_get_drvdata(dai); + int ret; + + if (!freq) + return 0; + + ret = clk_set_rate(spdif->mclk, freq); + if (ret) + dev_err(spdif->dev, "Failed to set mclk: %d\n", ret); + + return ret; +} + static const struct snd_soc_dai_ops rk_spdif_dai_ops = { + .set_sysclk = rk_spdif_set_sysclk, .probe = rk_spdif_dai_probe, .hw_params = rk_spdif_hw_params, .trigger = rk_spdif_trigger, @@ -219,7 +279,8 @@ static struct snd_soc_dai_driver rk_spdif_dai = { SNDRV_PCM_RATE_192000), .formats = (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | - SNDRV_PCM_FMTBIT_S24_LE), + SNDRV_PCM_FMTBIT_S24_LE | + SNDRV_PCM_FMTBIT_S32_LE), }, .ops = &rk_spdif_dai_ops, }; @@ -237,6 +298,9 @@ static bool rk_spdif_wr_reg(struct device *dev, unsigned int reg) case SPDIF_INTCR: case SPDIF_XFER: case SPDIF_SMPDR: + case SPDIF_VLDFRn(0) ... SPDIF_VLDFRn(11): + case SPDIF_USRDRn(0) ... SPDIF_USRDRn(11): + case SPDIF_CHNSRn(0) ... SPDIF_CHNSRn(11): return true; default: return false; @@ -252,6 +316,9 @@ static bool rk_spdif_rd_reg(struct device *dev, unsigned int reg) case SPDIF_INTSR: case SPDIF_XFER: case SPDIF_SMPDR: + case SPDIF_VLDFRn(0) ... SPDIF_VLDFRn(11): + case SPDIF_USRDRn(0) ... SPDIF_USRDRn(11): + case SPDIF_CHNSRn(0) ... SPDIF_CHNSRn(11): return true; default: return false; @@ -274,7 +341,7 @@ static const struct regmap_config rk_spdif_regmap_config = { .reg_bits = 32, .reg_stride = 4, .val_bits = 32, - .max_register = SPDIF_SMPDR, + .max_register = SPDIF_VERSION, .writeable_reg = rk_spdif_wr_reg, .readable_reg = rk_spdif_rd_reg, .volatile_reg = rk_spdif_volatile_reg, diff --git a/sound/soc/rockchip/rockchip_spdif.h b/sound/soc/rockchip/rockchip_spdif.h index d8be9aae5b19..b837b1f8d57f 100644 --- a/sound/soc/rockchip/rockchip_spdif.h +++ b/sound/soc/rockchip/rockchip_spdif.h @@ -15,7 +15,19 @@ */ #define SPDIF_CFGR_CLK_DIV_SHIFT (16) #define SPDIF_CFGR_CLK_DIV_MASK (0xff << SPDIF_CFGR_CLK_DIV_SHIFT) -#define SPDIF_CFGR_CLK_DIV(x) (x << SPDIF_CFGR_CLK_DIV_SHIFT) +#define SPDIF_CFGR_CLK_DIV(x) ((x-1) << SPDIF_CFGR_CLK_DIV_SHIFT) + +#define SPDIF_CFGR_CLR_MASK BIT(7) +#define SPDIF_CFGR_CLR_EN BIT(7) +#define SPDIF_CFGR_CLR_DIS 0 + +#define SPDIF_CFGR_CSE_MASK BIT(6) +#define SPDIF_CFGR_CSE_EN BIT(6) +#define SPDIF_CFGR_CSE_DIS 0 + +#define SPDIF_CFGR_ADJ_MASK BIT(3) +#define SPDIF_CFGR_ADJ_LEFT_J BIT(3) +#define SPDIF_CFGR_ADJ_RIGHT_J 0 #define SPDIF_CFGR_HALFWORD_SHIFT 2 #define SPDIF_CFGR_HALFWORD_DISABLE (0 << SPDIF_CFGR_HALFWORD_SHIFT) @@ -56,5 +68,9 @@ #define SPDIF_INTSR (0x0010) #define SPDIF_XFER (0x0018) #define SPDIF_SMPDR (0x0020) +#define SPDIF_VLDFRn(x) (0x0060 + (x) * 4) +#define SPDIF_USRDRn(x) (0x0090 + (x) * 4) +#define SPDIF_CHNSRn(x) (0x00c0 + (x) * 4) +#define SPDIF_VERSION (0x01c0) #endif /* _ROCKCHIP_SPDIF_H */ diff --git a/sound/soc/soc-core.c b/sound/soc/soc-core.c index feecf3e4e38b..34f350b75b18 100644 --- a/sound/soc/soc-core.c +++ b/sound/soc/soc-core.c @@ -3701,6 +3701,18 @@ void snd_soc_of_put_dai_link_codecs(struct snd_soc_dai_link *dai_link) } EXPORT_SYMBOL_GPL(snd_soc_of_put_dai_link_codecs); +/* dai_name belongs to the component, which can unbind before the card. */ +static int snd_soc_of_dup_dai_name(struct device *dev, + struct snd_soc_dai_link_component *dlc) +{ + if (!dlc->dai_name) + return 0; + + dlc->dai_name = devm_kstrdup_const(dev, dlc->dai_name, GFP_KERNEL); + + return dlc->dai_name ? 0 : -ENOMEM; +} + /* * snd_soc_of_get_dai_link_codecs - Parse a list of CODECs in the devicetree * @dev: Card device @@ -3730,6 +3742,8 @@ int snd_soc_of_get_dai_link_codecs(struct device *dev, /* Parse the list */ for_each_link_codecs(dai_link, index, component) { ret = snd_soc_of_get_dlc(of_node, NULL, component, index); + if (!ret) + ret = snd_soc_of_dup_dai_name(dev, component); if (ret) goto err; } @@ -3785,6 +3799,8 @@ int snd_soc_of_get_dai_link_cpus(struct device *dev, /* Parse the list */ for_each_link_cpus(dai_link, index, component) { ret = snd_soc_of_get_dlc(of_node, NULL, component, index); + if (!ret) + ret = snd_soc_of_dup_dai_name(dev, component); if (ret) goto err; } diff --git a/sound/soc/sof/amd/acp.c b/sound/soc/sof/amd/acp.c index 475b77b8ea30..e84ab3069b38 100644 --- a/sound/soc/sof/amd/acp.c +++ b/sound/soc/sof/amd/acp.c @@ -394,16 +394,20 @@ static void amd_sof_handle_acp70_sdw_wake_event(struct acp_dev_data *adata) struct amd_sdw_manager *amd_manager; if (adata->acp70_sdw0_wake_event) { - amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); - if (amd_manager) - pm_request_resume(amd_manager->dev); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); + if (amd_manager) + pm_request_resume(amd_manager->dev); + } adata->acp70_sdw0_wake_event = 0; } if (adata->acp70_sdw1_wake_event) { - amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); - if (amd_manager) - pm_request_resume(amd_manager->dev); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); + if (amd_manager) + pm_request_resume(amd_manager->dev); + } adata->acp70_sdw1_wake_event = 0; } } @@ -495,10 +499,12 @@ static irqreturn_t acp_irq_handler(int irq, void *dev_id) val = snd_sof_dsp_read(sdev, ACP_DSP_BAR, desc->ext_intr_stat); if (val & ACP_SDW0_IRQ_MASK) { - amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); snd_sof_dsp_write(sdev, ACP_DSP_BAR, desc->ext_intr_stat, ACP_SDW0_IRQ_MASK); - if (amd_manager) - schedule_work(&amd_manager->amd_sdw_irq_thread); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[0]->dev); + if (amd_manager) + schedule_work(&amd_manager->amd_sdw_irq_thread); + } irq_flag = 1; } @@ -515,11 +521,13 @@ static irqreturn_t acp_irq_handler(int irq, void *dev_id) if (desc->ext_intr_stat1) { val = snd_sof_dsp_read(sdev, ACP_DSP_BAR, desc->ext_intr_stat1); if (val & ACP_SDW1_IRQ_MASK) { - amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); snd_sof_dsp_write(sdev, ACP_DSP_BAR, desc->ext_intr_stat1, ACP_SDW1_IRQ_MASK); - if (amd_manager) - schedule_work(&amd_manager->amd_sdw_irq_thread); + if (adata->sdw) { + amd_manager = dev_get_drvdata(&adata->sdw->pdev[1]->dev); + if (amd_manager) + schedule_work(&amd_manager->amd_sdw_irq_thread); + } irq_flag = 1; } switch (adata->pci_rev) { diff --git a/sound/soc/sof/ipc4-topology.c b/sound/soc/sof/ipc4-topology.c index 7178279ddfb7..609762c57e4f 100644 --- a/sound/soc/sof/ipc4-topology.c +++ b/sound/soc/sof/ipc4-topology.c @@ -1205,7 +1205,7 @@ static int sof_ipc4_widget_setup_comp_process(struct snd_sof_widget *swidget) ret = sof_ipc4_widget_setup_msg(swidget, &process->msg); if (ret) - goto err; + goto free_available_fmt; /* parse process init module payload config type from module info */ fw_module = swidget->module_info; diff --git a/sound/usb/caiaq/device.c b/sound/usb/caiaq/device.c index 5e89047c9d9c..aec96ad0c040 100644 --- a/sound/usb/caiaq/device.c +++ b/sound/usb/caiaq/device.c @@ -593,14 +593,19 @@ static void snd_disconnect(struct usb_interface *intf) snd_card_disconnect(card); + /* + * Kill the EP1 URB before disconnecting the input device: its + * completion reports into cdev->input_dev, which input_disconnect() + * frees without clearing the pointer. + */ + usb_kill_urb(cdev->ep1_in_urb); + usb_kill_urb(cdev->midi_out_urb); + #ifdef CONFIG_SND_USB_CAIAQ_INPUT snd_usb_caiaq_input_disconnect(cdev); #endif snd_usb_caiaq_audio_disconnect(cdev); - usb_kill_urb(cdev->ep1_in_urb); - usb_kill_urb(cdev->midi_out_urb); - snd_card_free_when_closed(card); } diff --git a/sound/usb/mixer.c b/sound/usb/mixer.c index f4e44c31111c..e578a29a675f 100644 --- a/sound/usb/mixer.c +++ b/sound/usb/mixer.c @@ -335,6 +335,17 @@ static int get_ctl_value_v1(struct usb_mixer_elem_info *cval, int request, return -EINVAL; } +/* convert the given UAC1 wValue (ICN|OCN) to UAC2 MCN */ +static unsigned char to_mcn(const struct usb_mixer_elem_info *cval, + unsigned int validx) +{ + unsigned char m = (validx >> 8) & 0xff; /* 1-based input channel */ + unsigned char v = validx & 0xff; /* 1-based output channel */ + + /* num_inputs * num_outputs is guaranteed to be < 256 */ + return (m - 1) * cval->num_outputs + (v - 1); +} + static int get_ctl_value_v2(struct usb_mixer_elem_info *cval, int request, int validx, int *value_ret) { @@ -347,6 +358,10 @@ static int get_ctl_value_v2(struct usb_mixer_elem_info *cval, int request, val_size = uac2_ctl_value_size(cval->val_type); + /* correct wValue for UAC2 mixer control with MCN */ + if (cval->v2_mixer) + validx = (UAC2_MU_MIXER << 8) | to_mcn(cval, validx); + if (request == UAC_GET_CUR) { bRequest = UAC2_CS_CUR; size = val_size; @@ -473,6 +488,10 @@ int snd_usb_mixer_set_ctl_value(struct usb_mixer_elem_info *cval, } request = UAC2_CS_CUR; + + /* correct wValue for UAC2 mixer control with MCN */ + if (cval->v2_mixer) + validx = (UAC2_MU_MIXER << 8) | to_mcn(cval, validx); } value_set = convert_bytes_value(cval, value_set); @@ -2206,6 +2225,10 @@ static void build_mixer_unit_ctl(struct mixer_build *state, snd_usb_mixer_elem_init_std(&cval->head, state->mixer, unitid); cval->control = in_ch + 1; /* based on 1 */ + if (state->mixer->protocol == UAC_VERSION_2 || + state->mixer->protocol == UAC_VERSION_3) + cval->v2_mixer = true; + cval->num_outputs = num_outs; cval->val_type = USB_MIXER_S16; for (i = 0; i < num_outs; i++) { __u8 *c = uac_mixer_unit_bmControls(desc, state->mixer->protocol); diff --git a/sound/usb/mixer.h b/sound/usb/mixer.h index 8e5e8da6d480..00ffefb751d2 100644 --- a/sound/usb/mixer.h +++ b/sound/usb/mixer.h @@ -97,6 +97,8 @@ struct usb_mixer_elem_info { int cache_val[MAX_CHANNELS]; u8 initialized; u8 min_mute; + u8 num_outputs; + bool v2_mixer; void *private_data; }; diff --git a/sound/usb/pcm.c b/sound/usb/pcm.c index c2f7b08607ac..57a26492dd61 100644 --- a/sound/usb/pcm.c +++ b/sound/usb/pcm.c @@ -1337,6 +1337,12 @@ static void retire_capture_urb(struct snd_usb_substream *subs, "frame %d active: %d\n", i, urb->iso_frame_desc[i].status); bytes = urb->iso_frame_desc[i].actual_length; + if (unlikely(bytes > urb->iso_frame_desc[i].length)) { + dev_warn_ratelimited(&subs->dev->dev, + "packet %d: actual_length %u exceeds length %u, dropping\n", + i, bytes, urb->iso_frame_desc[i].length); + continue; + } if (subs->stream_offset_adj > 0) { unsigned int adj = min(subs->stream_offset_adj, bytes); cp += adj; diff --git a/tools/bootconfig/test-bootconfig.sh b/tools/bootconfig/test-bootconfig.sh index 7594659af1e1..d6211efe6dbe 100755 --- a/tools/bootconfig/test-bootconfig.sh +++ b/tools/bootconfig/test-bootconfig.sh @@ -171,6 +171,24 @@ $BOOTCONF $INITRD > $OUTFILE xfail grep -q 'val[[:space:]]' $OUTFILE xpass grep -q 'val2[[:space:]]' $OUTFILE +echo "Remove unquoted trailing whitespace at end of file" +printf 'foo = val \t' > $TEMPCONF +$BOOTCONF -l $TEMPCONF > $OUTFILE +printf 'foo = "val"\n' > $TEMPCONF +xpass cmp $TEMPCONF $OUTFILE + +echo "Remove trailing whitespace from the last array value at end of file" +printf 'foo = first, last \t' > $TEMPCONF +$BOOTCONF -l $TEMPCONF > $OUTFILE +printf 'foo = "first", "last"\n' > $TEMPCONF +xpass cmp $TEMPCONF $OUTFILE + +echo "Keep quoted trailing whitespace at end of file" +printf 'foo = "val "' > $TEMPCONF +$BOOTCONF -l $TEMPCONF > $OUTFILE +printf 'foo = "val "\n' > $TEMPCONF +xpass cmp $TEMPCONF $OUTFILE + echo "=== expected failure cases ===" for i in samples/bad-* ; do xfail $BOOTCONF -a $i $INITRD diff --git a/tools/include/nolibc/dirent.h b/tools/include/nolibc/dirent.h index 61a122a60327..be0eaefea7a4 100644 --- a/tools/include/nolibc/dirent.h +++ b/tools/include/nolibc/dirent.h @@ -67,6 +67,7 @@ int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result) struct linux_dirent64 *ldir = (void *)buf; intptr_t i = (intptr_t)dirp; int fd, ret; + off_t off; if (i >= 0) return EBADF; @@ -86,9 +87,9 @@ int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result) * readdir() can only return one entry at a time. * Make sure the non-returned ones are not skipped. */ - ret = sys_lseek(fd, ldir->d_off, SEEK_SET); - if (ret < 0) - return -ret; + off = sys_lseek(fd, ldir->d_off, SEEK_SET); + if (off < 0) + return -off; entry->d_ino = ldir->d_ino; /* the destination should always be big enough */ diff --git a/tools/perf/builtin-lock.c b/tools/perf/builtin-lock.c index 5585aeb97684..66bfd9e4fe17 100644 --- a/tools/perf/builtin-lock.c +++ b/tools/perf/builtin-lock.c @@ -977,6 +977,7 @@ static int report_lock_contention_begin_event(struct evsel *evsel, struct machine *machine = &session->machines.host; struct map *kmap; struct symbol *sym; + u64 *callstack = NULL; ret = get_key_by_aggr_mode(&key, addr, evsel, sample); if (ret < 0) @@ -1012,33 +1013,6 @@ static int report_lock_contention_begin_event(struct evsel *evsel, } } - ls = lock_stat_find(key); - if (!ls) { - char buf[128]; - const char *name = ""; - - switch (aggr_mode) { - case LOCK_AGGR_ADDR: - sym = machine__find_kernel_symbol(machine, key, &kmap); - if (sym) - name = sym->name; - break; - case LOCK_AGGR_CALLER: - name = buf; - if (lock_contention_caller(evsel, sample, buf, sizeof(buf)) < 0) - name = "Unknown"; - break; - case LOCK_AGGR_CGROUP: - case LOCK_AGGR_TASK: - default: - break; - } - - ls = lock_stat_findnew(key, name, flags); - if (!ls) - return -ENOMEM; - } - if (filters.nr_types) { bool found = false; @@ -1068,7 +1042,7 @@ static int report_lock_contention_begin_event(struct evsel *evsel, } if (needs_callstack()) { - u64 *callstack = get_callstack(sample, max_stack_depth); + callstack = get_callstack(sample, max_stack_depth); if (callstack == NULL) return -ENOMEM; @@ -1076,7 +1050,38 @@ static int report_lock_contention_begin_event(struct evsel *evsel, free(callstack); return 0; } + } + + ls = lock_stat_find(key); + if (!ls) { + char buf[128]; + const char *name = ""; + + switch (aggr_mode) { + case LOCK_AGGR_ADDR: + sym = machine__find_kernel_symbol(machine, key, &kmap); + if (sym) + name = sym->name; + break; + case LOCK_AGGR_CALLER: + name = buf; + if (lock_contention_caller(evsel, sample, buf, sizeof(buf)) < 0) + name = "Unknown"; + break; + case LOCK_AGGR_CGROUP: + case LOCK_AGGR_TASK: + default: + break; + } + + ls = lock_stat_findnew(key, name, flags); + if (!ls) { + free(callstack); + return -ENOMEM; + } + } + if (callstack) { if (ls->callstack == NULL) ls->callstack = callstack; else diff --git a/tools/perf/tests/hists_cumulate.c b/tools/perf/tests/hists_cumulate.c index 3eb9ef8d7ec6..bdf4ce82612d 100644 --- a/tools/perf/tests/hists_cumulate.c +++ b/tools/perf/tests/hists_cumulate.c @@ -724,7 +724,7 @@ static int test__hists_cumulate(struct test_suite *test __maybe_unused, int subt goto out; err = TEST_FAIL; - machines__init(&machines); + machines__init(&machines, /*session=*/NULL); /* setup threads/dso/map/symbols also */ machine = setup_fake_machine(&machines); diff --git a/tools/perf/tests/hists_filter.c b/tools/perf/tests/hists_filter.c index 1cebd20cc91c..4a1d45ecc03f 100644 --- a/tools/perf/tests/hists_filter.c +++ b/tools/perf/tests/hists_filter.c @@ -131,7 +131,7 @@ static int test__hists_filter(struct test_suite *test __maybe_unused, int subtes goto out; err = TEST_FAIL; - machines__init(&machines); + machines__init(&machines, /*session=*/NULL); /* setup threads/dso/map/symbols also */ machine = setup_fake_machine(&machines); diff --git a/tools/perf/tests/hists_link.c b/tools/perf/tests/hists_link.c index 996f5f0b3bd1..0af2ba1ad1aa 100644 --- a/tools/perf/tests/hists_link.c +++ b/tools/perf/tests/hists_link.c @@ -303,7 +303,7 @@ static int test__hists_link(struct test_suite *test __maybe_unused, int subtest goto out; err = TEST_FAIL; - machines__init(&machines); + machines__init(&machines, /*session=*/NULL); /* setup threads/dso/map/symbols also */ machine = setup_fake_machine(&machines); diff --git a/tools/perf/tests/hists_output.c b/tools/perf/tests/hists_output.c index ee5ec8bda60e..a80263ab1d34 100644 --- a/tools/perf/tests/hists_output.c +++ b/tools/perf/tests/hists_output.c @@ -611,7 +611,7 @@ static int test__hists_output(struct test_suite *test __maybe_unused, int subtes goto out; err = TEST_FAIL; - machines__init(&machines); + machines__init(&machines, /*session=*/NULL); /* setup threads/dso/map/symbols also */ machine = setup_fake_machine(&machines); diff --git a/tools/perf/tests/thread-maps-share.c b/tools/perf/tests/thread-maps-share.c index e9ecd30a5c05..cea1f92b5302 100644 --- a/tools/perf/tests/thread-maps-share.c +++ b/tools/perf/tests/thread-maps-share.c @@ -27,7 +27,7 @@ static int test__thread_maps_share(struct test_suite *test __maybe_unused, int s * other group (pid: 4, tids: 4, 5) */ - machines__init(&machines); + machines__init(&machines, /*session=*/NULL); machine = &machines.host; /* create process with 4 threads */ diff --git a/tools/perf/util/dso.c b/tools/perf/util/dso.c index 70daf4fd200e..f381ac71e8a5 100644 --- a/tools/perf/util/dso.c +++ b/tools/perf/util/dso.c @@ -32,6 +32,7 @@ #include "string2.h" #include "vdso.h" #include "annotate-data.h" +#include "libbfd.h" static const char * const debuglink_paths[] = { "%.0s%s", @@ -1668,6 +1669,7 @@ void dso__delete(struct dso *dso) auxtrace_cache__free(RC_CHK_ACCESS(dso)->auxtrace_cache); dso_cache__free(dso); dso__free_a2l(dso); + dso__free_a2l_libbfd(dso); dso__free_symsrc_filename(dso); nsinfo__zput(RC_CHK_ACCESS(dso)->nsinfo); mutex_destroy(dso__lock(dso)); diff --git a/tools/perf/util/dso.h b/tools/perf/util/dso.h index b374dfabf49c..a580e7a58078 100644 --- a/tools/perf/util/dso.h +++ b/tools/perf/util/dso.h @@ -303,6 +303,9 @@ DECLARE_RC_STRUCT(dso) { const char *short_name; const char *long_name; void *a2l; +#ifdef HAVE_LIBBFD_SUPPORT + void *a2l_libbfd; +#endif char *symsrc_filename; #if defined(__powerpc__) void *dwfl; /* DWARF debug info */ @@ -369,6 +372,18 @@ static inline void dso__set_a2l(struct dso *dso, void *val) RC_CHK_ACCESS(dso)->a2l = val; } +#ifdef HAVE_LIBBFD_SUPPORT +static inline void *dso__a2l_libbfd(const struct dso *dso) +{ + return RC_CHK_ACCESS(dso)->a2l_libbfd; +} + +static inline void dso__set_a2l_libbfd(struct dso *dso, void *val) +{ + RC_CHK_ACCESS(dso)->a2l_libbfd = val; +} +#endif + static inline unsigned int dso__a2l_fails(const struct dso *dso) { return RC_CHK_ACCESS(dso)->a2l_fails; diff --git a/tools/perf/util/evlist.c b/tools/perf/util/evlist.c index 314393a430a3..67d1ad8a6ee1 100644 --- a/tools/perf/util/evlist.c +++ b/tools/perf/util/evlist.c @@ -648,13 +648,15 @@ static int evlist__event2id(struct evlist *evlist, union perf_event *event, u64 const __u64 *array = event->sample.array; ssize_t n; - n = (event->header.size - sizeof(event->header)) >> 3; - if (event->header.type == PERF_RECORD_SAMPLE) { + n = (event->header.size - sizeof(event->header)) >> 3; if (evlist->id_pos >= n) return -1; *id = array[evlist->id_pos]; } else { + u16 size = evsel__event_size(evlist__first(evlist), event); + + n = (size - sizeof(event->header)) >> 3; if (evlist->is_pos > n) return -1; n -= evlist->is_pos; diff --git a/tools/perf/util/evsel.c b/tools/perf/util/evsel.c index a0db385b9bec..a6d91af538dc 100644 --- a/tools/perf/util/evsel.c +++ b/tools/perf/util/evsel.c @@ -2888,7 +2888,7 @@ static int perf_evsel__parse_id_sample(const struct evsel *evsel, bool swapped = evsel->needs_swap; union u64_swap u; - array += ((event->header.size - + array += ((evsel__event_size(evsel, event) - sizeof(event->header)) / sizeof(u64)) - 1; if (type & PERF_SAMPLE_IDENTIFIER) { @@ -3512,6 +3512,63 @@ u16 evsel__id_hdr_size(const struct evsel *evsel) return size; } +/* + * Prior to kernel fix, perf_event_ksymbol_output(), perf_event_bpf_output(), + * and perf_event_text_poke_output() in kernel/events/core.c did not save and + * restore event_id.header.size across perf_iterate_sb() iterations. When + * multiple perf_events had attr.ksymbol, attr.bpf_event, or attr.text_poke + * enabled, header.size was incremented by id_header_size for each matching + * event while only a single id_sample was written immediately after the event + * payload. Clamp the effective size used to locate the trailing id_sample to + * payload + id_hdr_size so events recorded on unpatched kernels can be parsed + * without reading uninitialized ring-buffer bytes. + */ +u16 evsel__event_size(const struct evsel *evsel, const union perf_event *event) +{ + u16 size = event->header.size; + u16 id_hdr_size; + size_t payload; + + if (!evsel->core.attr.sample_id_all) + return size; + + switch (event->header.type) { + case PERF_RECORD_KSYMBOL: { + const char *name = event->ksymbol.name; + size_t fixed = offsetof(struct perf_record_ksymbol, name); + size_t max_len, len; + + if (size <= fixed) + return size; + max_len = size - fixed; + len = strnlen(name, max_len); + if (len == max_len) + return size; + payload = fixed + PERF_ALIGN(len + 1, sizeof(u64)); + break; + } + case PERF_RECORD_BPF_EVENT: + payload = sizeof(struct perf_record_bpf_event); + break; + case PERF_RECORD_TEXT_POKE: { + size_t fixed = offsetof(struct perf_record_text_poke_event, bytes); + + if (size < fixed) + return size; + payload = PERF_ALIGN(fixed + (size_t)event->text_poke.old_len + + event->text_poke.new_len, sizeof(u64)); + break; + } + default: + return size; + } + + id_hdr_size = evsel__id_hdr_size(evsel); + if (payload + id_hdr_size < size) + return payload + id_hdr_size; + return size; +} + #ifdef HAVE_LIBTRACEEVENT struct tep_format_field *evsel__field(struct evsel *evsel, const char *name) { diff --git a/tools/perf/util/evsel.h b/tools/perf/util/evsel.h index f8de0f9a719b..664bcc8712c2 100644 --- a/tools/perf/util/evsel.h +++ b/tools/perf/util/evsel.h @@ -425,6 +425,7 @@ int evsel__parse_sample_timestamp(struct evsel *evsel, union perf_event *event, u64 *timestamp); u16 evsel__id_hdr_size(const struct evsel *evsel); +u16 evsel__event_size(const struct evsel *evsel, const union perf_event *event); static inline struct evsel *evsel__next(struct evsel *evsel) { diff --git a/tools/perf/util/libbfd.c b/tools/perf/util/libbfd.c index 47d691e4af32..8771a6541f8b 100644 --- a/tools/perf/util/libbfd.c +++ b/tools/perf/util/libbfd.c @@ -227,7 +227,7 @@ static int inline_list__append_dso_a2l(struct dso *dso, struct inline_node *node, struct symbol *sym) { - struct a2l_data *a2l = dso__a2l(dso); + struct a2l_data *a2l = dso__a2l_libbfd(dso); struct symbol *inline_sym = new_inline_sym(dso, sym, a2l->funcname); char *srcline = NULL; @@ -243,11 +243,11 @@ int libbfd__addr2line(const char *dso_name, u64 addr, struct symbol *sym) { int ret = 0; - struct a2l_data *a2l = dso__a2l(dso); + struct a2l_data *a2l = dso__a2l_libbfd(dso); if (!a2l) { a2l = addr2line_init(dso_name); - dso__set_a2l(dso, a2l); + dso__set_a2l_libbfd(dso, a2l); } if (a2l == NULL) { @@ -299,14 +299,14 @@ int libbfd__addr2line(const char *dso_name, u64 addr, void dso__free_a2l_libbfd(struct dso *dso) { - struct a2l_data *a2l = dso__a2l(dso); + struct a2l_data *a2l = dso__a2l_libbfd(dso); if (!a2l) return; addr2line_cleanup(a2l); - dso__set_a2l(dso, NULL); + dso__set_a2l_libbfd(dso, NULL); } static int bfd_symbols__cmpvalue(const void *a, const void *b) diff --git a/tools/perf/util/machine.c b/tools/perf/util/machine.c index 8452d776d994..0fcbd56746f2 100644 --- a/tools/perf/util/machine.c +++ b/tools/perf/util/machine.c @@ -229,9 +229,11 @@ void machine__delete(struct machine *machine) } } -void machines__init(struct machines *machines) +void machines__init(struct machines *machines, struct perf_session *session) { machine__init(&machines->host, "", HOST_KERNEL_ID); + machines->session = session; + machines->host.machines = machines; machines->guests = RB_ROOT_CACHED; } diff --git a/tools/perf/util/machine.h b/tools/perf/util/machine.h index 22a42c5825fa..049bbbdfa20d 100644 --- a/tools/perf/util/machine.h +++ b/tools/perf/util/machine.h @@ -15,6 +15,7 @@ struct dso; struct dso_id; struct evsel; struct perf_sample; +struct perf_session; struct symbol; struct target; struct thread; @@ -148,13 +149,20 @@ int machine__process_event(struct machine *machine, union perf_event *event, typedef void (*machine__process_t)(struct machine *machine, void *data); struct machines { + /** @session: back link to owning session if there is one. */ + struct perf_session *session; struct machine host; struct rb_root_cached guests; }; -void machines__init(struct machines *machines); +void machines__init(struct machines *machines, struct perf_session *session); void machines__exit(struct machines *machines); +static inline struct perf_session *machines__session(struct machines *machines) +{ + return machines->session; +} + void machines__process_guests(struct machines *machines, machine__process_t process, void *data); diff --git a/tools/perf/util/session.c b/tools/perf/util/session.c index 0eee9d2f59d9..f737ddb37755 100644 --- a/tools/perf/util/session.c +++ b/tools/perf/util/session.c @@ -152,7 +152,7 @@ struct perf_session *__perf_session__new(struct perf_data *data, session->decomp_data.zstd_decomp = &session->zstd_data; session->active_decomp = &session->decomp_data; INIT_LIST_HEAD(&session->auxtrace_index); - machines__init(&session->machines); + machines__init(&session->machines, session); ordered_events__init(&session->ordered_events, ordered_events__deliver_event, NULL); diff --git a/tools/perf/util/srcline.c b/tools/perf/util/srcline.c index 27c0966611ab..467cdd8353aa 100644 --- a/tools/perf/util/srcline.c +++ b/tools/perf/util/srcline.c @@ -192,6 +192,7 @@ char *__get_srcline(struct dso *dso, u64 addr, struct symbol *sym, if (dso__a2l_fails(dso) > A2L_FAIL_LIMIT) { dso__set_has_srcline(dso, false); dso__free_a2l(dso); + dso__free_a2l_libbfd(dso); } out: if (!show_addr) @@ -232,6 +233,7 @@ char *get_srcline_split(struct dso *dso, u64 addr, unsigned *line) if (dso__a2l_fails(dso) > A2L_FAIL_LIMIT) { dso__set_has_srcline(dso, false); dso__free_a2l(dso); + dso__free_a2l_libbfd(dso); } return NULL; diff --git a/tools/perf/util/thread.c b/tools/perf/util/thread.c index 9409d32dce04..6e22f83ae1e1 100644 --- a/tools/perf/util/thread.c +++ b/tools/perf/util/thread.c @@ -513,12 +513,10 @@ uint16_t thread__e_machine(struct thread *thread, struct machine *machine) bool is_live = machine->machines == NULL; if (!is_live) { - /* Check if the session has a data file. */ - struct perf_session *session = container_of(machine->machines, - struct perf_session, - machines); + /* Check if the session has a data file (assume no session is a test). */ + struct perf_session *session = machines__session(machine->machines); - is_live = !!session->data; + is_live = !session || !session->data; } /* Read from /proc/pid/exe if live. */ if (is_live) diff --git a/tools/testing/cxl/test/cxl.c b/tools/testing/cxl/test/cxl.c index aadb90ec516e..9663f183aa2c 100644 --- a/tools/testing/cxl/test/cxl.c +++ b/tools/testing/cxl/test/cxl.c @@ -1369,7 +1369,7 @@ static int cxl_mem_init(void) if (!pdev) goto err_mem; pdev->dev.parent = &dport->dev; - set_dev_node(&pdev->dev, i % 2); + set_dev_node(&pdev->dev, numa_map_to_online_node(i % 2)); rc = cxl_mock_platform_device_add(pdev, &cxl_mem[i]); if (rc) @@ -1384,7 +1384,7 @@ static int cxl_mem_init(void) if (!pdev) goto err_single; pdev->dev.parent = &dport->dev; - set_dev_node(&pdev->dev, i % 2); + set_dev_node(&pdev->dev, numa_map_to_online_node(i % 2)); rc = cxl_mock_platform_device_add(pdev, &cxl_mem_single[i]); if (rc) @@ -1400,7 +1400,7 @@ static int cxl_mem_init(void) if (!pdev) goto err_rcd; pdev->dev.parent = &rch->dev; - set_dev_node(&pdev->dev, i % 2); + set_dev_node(&pdev->dev, numa_map_to_online_node(i % 2)); rc = cxl_mock_platform_device_add(pdev, &cxl_rcd[i]); if (rc) diff --git a/tools/testing/selftests/bpf/prog_tests/kfunc_dynptr_param.c b/tools/testing/selftests/bpf/prog_tests/kfunc_dynptr_param.c index 8cd298b78e44..04aaf4c9cf5e 100644 --- a/tools/testing/selftests/bpf/prog_tests/kfunc_dynptr_param.c +++ b/tools/testing/selftests/bpf/prog_tests/kfunc_dynptr_param.c @@ -14,7 +14,7 @@ static struct { const char *prog_name; int expected_runtime_err; } kfunc_dynptr_tests[] = { - {"dynptr_data_null", -EBADMSG}, + {"dynptr_data_null", -EINVAL}, }; static bool kfunc_not_supported; diff --git a/tools/testing/selftests/cgroup/test_cpuset_prs.sh b/tools/testing/selftests/cgroup/test_cpuset_prs.sh index 6f7e387f68e5..25eef20c1746 100755 --- a/tools/testing/selftests/cgroup/test_cpuset_prs.sh +++ b/tools/testing/selftests/cgroup/test_cpuset_prs.sh @@ -277,6 +277,7 @@ TEST_MATRIX=( " C0-3:S+ C1-3:S+ C2-3 C4 X2-3 X2-3 X2-3:P2 P2:C4-5 0 A3:2-3|B1:4-5 A3:P2|B1:P2 2-5" " C4:X0-3:S+ X1-3:S+ X2-3 . . P2 . . 0 A1:4|A2:1-3|A3:1-3 A2:P2 1-3" " C4:X0-3:S+ X1-3:S+ X2-3 . . . P2 . 0 A1:4|A2:4|A3:2-3 A3:P2 2-3" + " CX1-6:S+ C1-4:P1 . C4-5 . C1-3 . . 0 A1:4-6|A2:1-3|B1:4-5 A2:P1" # Nested remote/local partition tests " C0-3:S+ C1-3:S+ C2-3 C4-5 X2-3 X2-3:P1 P2 P1 0 A1:0-1|A2:|A3:2-3|B1:4-5 \ @@ -291,9 +292,11 @@ TEST_MATRIX=( A1:P0|A2:P2|A3:P1 2-4|2-3" " C0-4:S+ C1-4:S+ C2-4 . X2-4 X2-4:P2 X3-4:P1 . 0 A1:0-1|A2:2|A3:3-4 \ A1:P0|A2:P2|A3:P1 2" - " C0-4:X2-4:S+ C1-4:X2-4:S+:P2 C2-4:X4:P1 \ - . . X5 . . 0 A1:0-4|A2:1-4|A3:2-4 \ - A1:P0|A2:P-2|A3:P-1 ." + "C1-6:P2:S+ C3-6:P2:S+ C3-4:P2 . . C5-6 . . 0 A1:1-4|A2:5-6|A3:5-6 \ + A1:P2|A2:P2|A3:P-2 1-6" + " C1-4:X2-4:S+ C2-4:X3-4:S+:P1 C3-4:X4:P2 \ + . . X5 . . 0 A1:1-4|A2:2-4|A3:3-4 \ + A1:P0|A2:P-1|A3:P-2 ." " C0-4:X2-4:S+ C1-4:X2-4:S+:P2 C2-4:X4:P1 \ . . . X1 . 0 A1:0-1|A2:2-4|A3:2-4 \ A1:P0|A2:P2|A3:P-1 2-4" @@ -360,6 +363,10 @@ TEST_MATRIX=( # cpuset.cpus is allowed, but those extra CPUs are ignored. "C2-3:P1:S+ C3:P1 . . . C2-4 . . 0 A1:|A2:2-3 A1:P1|A2:P1" + # A child cannot recover until its exclusive CPUs are available again. + "CX1-4:P1:S+ CX3-4:P1 . . X1-2 . . . 0 A1:1-2|A2:1-2|XA2: A1:P1|A2:P-1" + "CX1-4:P1:S+ CX3-4:P1 . . X1-2:X1-4 . . . 0 A1:1-2|A2:3-4|XA2:3-4 A1:P1|A2:P1" + # Taking away all CPUs from parent or itself if there are tasks # will make the partition invalid. "C2-3:P1:S+ C3:P1 . . T C2-3 . . 0 A1:2-3|A2:2-3 A1:P1|A2:P-1" @@ -419,6 +426,22 @@ TEST_MATRIX=( " CX1-4:S+ CX2-4:P2 . C5-6 . . . P1:C3-6 0 A1:1|A2:2-4|B1:5-6 \ A1:P0|A2:P2:B1:P-1 2-4" + # A middle isolated parent shrunk below coverage: the released CPUs of + # an invalidated child stay isolated as a higher ancestor still covers them. + "CX0-4:P2:S+ CX2-4:P2:S+ CX3-4:P2 . . X2 . . 0 A1:0-1,3-4|A2:2|A3:2 \ + A1:P2|A2:P2|A3:P-2 0-4" + + # When an isolated partition child with root partition parent is invalidated, + # its effective xcpus will be removed from isolated_cpus. + "C1-4:P1:S+ C3-4:P2 . . T:C3-4 . . . 0 A1:3-4|A2:3-4 A1:P1|A2:P-2 ." + + # When a root partition parent with an isolated partition child is shrunk + # so that its effective xcpus is no longer a superset of its child effective + # xcpus, the invalid isolated CPUs should be removed from cpuset.cpus.isolated. + "C1-4:P1:S+ C3-4:P2 . . T:C4-6 . . . 0 A1:5-6|A2:4 A1:P1|A2:P2 4" + "C1-4:P1:S+ C1-2:P2 . . T:C4-6 . . . 0 A1:4-6|A2:4-6 A1:P1|A2:P-2 ." + + # # old-A1 old-A2 old-A3 old-B1 new-A1 new-A2 new-A3 new-B1 fail ECPUs Pstate ISOLCPUS # ------ ------ ------ ------ ------ ------ ------ ------ ---- ----- ------ -------- # Failure cases: diff --git a/tools/testing/selftests/ftrace/test.d/dynevent/fprobe_syntax_errors.tc b/tools/testing/selftests/ftrace/test.d/dynevent/fprobe_syntax_errors.tc index fee479295e2f..9cc208898cab 100644 --- a/tools/testing/selftests/ftrace/test.d/dynevent/fprobe_syntax_errors.tc +++ b/tools/testing/selftests/ftrace/test.d/dynevent/fprobe_syntax_errors.tc @@ -33,7 +33,7 @@ check_error 'f vfs_read ^$stack10000' # BAD_STACK_NUM check_error 'f vfs_read ^$arg10000' # BAD_ARG_NUM -if !grep -q 'kernel return probes support:' README; then +if ! grep -q 'kernel return probes support:' README; then check_error 'f vfs_read $retval ^$arg1' # BAD_VAR fi check_error 'f vfs_read ^$none_var' # BAD_VAR @@ -100,7 +100,7 @@ if grep -q "" README; then check_error 'f vfs_read args=^$arg*' # BAD_VAR_ARGS check_error 'f vfs_read +0(^$arg*)' # BAD_VAR_ARGS check_error 'f vfs_read $arg* ^$arg*' # DOUBLE_ARGS -if !grep -q 'kernel return probes support:' README; then +if ! grep -q 'kernel return probes support:' README; then check_error 'f vfs_read%return ^$arg*' # NOFENTRY_ARGS fi check_error 'f vfs_read ^hoge' # NO_BTFARG diff --git a/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc b/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc index 07b1177c1634..5b95c7f312f4 100644 --- a/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc +++ b/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc @@ -6,7 +6,7 @@ SYMBOL='name_show' # We skip this test on kernel where SYMBOL is unique or does not exist. -if [ "$(grep -c -E "[[:alnum:]]+ t ${SYMBOL}$" /proc/kallsyms)" -le '1' ]; then +if [ "$(grep -c -E "[[:alnum:]]+ t ${SYMBOL}\$" /proc/kallsyms)" -le '1' ]; then exit_unsupported fi diff --git a/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_syntax_errors.tc b/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_syntax_errors.tc index 8f1c58f0c239..84cd7f15003b 100644 --- a/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_syntax_errors.tc +++ b/tools/testing/selftests/ftrace/test.d/kprobe/kprobe_syntax_errors.tc @@ -108,7 +108,7 @@ if grep -q "" README; then check_error 'p vfs_read args=^$arg*' # BAD_VAR_ARGS check_error 'p vfs_read +0(^$arg*)' # BAD_VAR_ARGS check_error 'p vfs_read $arg* ^$arg*' # DOUBLE_ARGS -if !grep -q 'kernel return probes support:' README; then +if ! grep -q 'kernel return probes support:' README; then check_error 'r vfs_read ^$arg*' # NOFENTRY_ARGS fi check_error 'p vfs_read+20 ^$arg*' # NOFENTRY_ARGS diff --git a/tools/testing/selftests/mm/merge.c b/tools/testing/selftests/mm/merge.c index 10b686102b79..65c30632795e 100644 --- a/tools/testing/selftests/mm/merge.c +++ b/tools/testing/selftests/mm/merge.c @@ -22,9 +22,12 @@ FIXTURE(merge) struct procmap_fd procmap; }; +#define FAR_PAGES 30 +#define CARVEOUT_PAGES (3 * FAR_PAGES) + static char *map_carveout(unsigned int page_size) { - return mmap(NULL, 30 * page_size, PROT_NONE, + return mmap(NULL, CARVEOUT_PAGES * page_size, PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0); } @@ -60,7 +63,7 @@ FIXTURE_SETUP(merge) FIXTURE_TEARDOWN(merge) { - ASSERT_EQ(munmap(self->carveout, 30 * self->page_size), 0); + ASSERT_EQ(munmap(self->carveout, CARVEOUT_PAGES * self->page_size), 0); /* May fail for parent of forked process. */ close_procmap(&self->procmap); /* @@ -102,7 +105,7 @@ FIXTURE_SETUP(merge_with_fork) FIXTURE_TEARDOWN(merge_with_fork) { - ASSERT_EQ(munmap(self->carveout, 30 * self->page_size), 0); + ASSERT_EQ(munmap(self->carveout, CARVEOUT_PAGES * self->page_size), 0); ASSERT_EQ(close_procmap(&self->procmap), 0); /* See above. */ prctl(PR_SET_MEMORY_MERGE, 0, 0, 0, 0); @@ -647,7 +650,7 @@ TEST_F(merge, mremap_unfaulted_to_faulted) /* Offset ptr2 further away. */ ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size); ASSERT_NE(ptr2, MAP_FAILED); /* @@ -708,7 +711,7 @@ TEST_F(merge, mremap_unfaulted_behind_faulted) /* Offset ptr2 further away. */ ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size); ASSERT_NE(ptr2, MAP_FAILED); /* @@ -772,12 +775,12 @@ TEST_F(merge, mremap_unfaulted_between_faulted) /* Offset ptr3 further away. */ ptr3 = sys_mremap(ptr3, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + page_size * 2000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + 2 * FAR_PAGES * page_size); ASSERT_NE(ptr3, MAP_FAILED); /* Offset ptr2 further away. */ ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size); ASSERT_NE(ptr2, MAP_FAILED); /* @@ -857,13 +860,13 @@ TEST_F(merge, mremap_unfaulted_between_faulted_unfaulted) /* Offset ptr3 further away. */ ptr3 = sys_mremap(ptr3, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + page_size * 2000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + 2 * FAR_PAGES * page_size); ASSERT_NE(ptr3, MAP_FAILED); /* Offset ptr2 further away. */ ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size); ASSERT_NE(ptr2, MAP_FAILED); /* @@ -1022,11 +1025,11 @@ TEST_F(merge, mremap_correct_placed_faulted) */ ptr3 = &ptr[10 * page_size]; ptr3 = sys_mremap(ptr3, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + page_size * 2000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + 2 * FAR_PAGES * page_size); ASSERT_NE(ptr3, MAP_FAILED); ptr2 = &ptr[5 * page_size]; ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size); ASSERT_NE(ptr2, MAP_FAILED); /* @@ -1062,7 +1065,7 @@ TEST_F(merge, mremap_correct_placed_faulted) * ptr2 \ ptr \ ptr3 */ ptr = sys_mremap(ptr, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr + FAR_PAGES * page_size); ASSERT_NE(ptr, MAP_FAILED); /* @@ -1097,7 +1100,7 @@ TEST_F(merge, mremap_correct_placed_faulted) * ptr2 \ ptr \ ptr3 */ ptr = sys_mremap(ptr, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr + FAR_PAGES * page_size); ASSERT_NE(ptr, MAP_FAILED); /* @@ -1155,7 +1158,7 @@ TEST_F(merge, mremap_correct_placed_faulted) * ptr ptr3 \ ptr2 */ ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size); ASSERT_NE(ptr2, MAP_FAILED); /* @@ -1190,7 +1193,7 @@ TEST_F(merge, mremap_correct_placed_faulted) * ptr \ ptr3 */ ptr3 = sys_mremap(ptr3, 5 * page_size, 5 * page_size, - MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + page_size * 1000); + MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + FAR_PAGES * page_size); ASSERT_NE(ptr3, MAP_FAILED); /* diff --git a/tools/testing/selftests/net/packetdrill/tcp_bidir_fast_retransmit_nosack.pkt b/tools/testing/selftests/net/packetdrill/tcp_bidir_fast_retransmit_nosack.pkt new file mode 100644 index 000000000000..5c66b7171d22 --- /dev/null +++ b/tools/testing/selftests/net/packetdrill/tcp_bidir_fast_retransmit_nosack.pkt @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: GPL-2.0 +// +// Verify that non-SACK connections properly detect duplicate acks when mixed +// with other data segments from peer. + +`./defaults.sh` + + 0 socket(..., SOCK_STREAM, IPPROTO_TCP) = 4 + +0...0 connect(4, ..., ...) = 0 + + // Three-way handshake, SACK not supported by peer + +0 > S 0:0(0) + +0 < S. 0:0(0) ack 1 win 65535 + +0 > . 1:1(0) ack 1 + + // Send 1000 bytes, peer acks everything + +0 send(4, ..., 1000, 0) = 1000 + +0 > P. 1:1001(1000) ack 1 + +0 < . 1:1(0) ack 1001 win 65535 + + // Send 4000 more bytes + +0 send(4, ..., 4000, 0) = 4000 + +0 > P. 1001:5001(4000) ack 1 + + // Receive first dup-ack (considering segment 1001-2001 was lost) + +0 < . 1:1(0) ack 1001 win 65535 + + // Receive unrelated data segment from peer and ack it + +0 < P. 1:11(10) ack 1001 win 65535 + +0 > . 5001:5001(0) ack 11 + + // Receive second dup-ack + +0 < . 11:11(0) ack 1001 win 65535 + + // Receive another data segment from peer and ack it + +0 < P. 11:21(10) ack 1001 win 65535 + +0 > . 5001:5001(0) ack 21 + + // Receive third dup-ack, which should trigger fast retransmit (without + // waiting for RTO) + +0 < . 21:21(0) ack 1001 win 65535 + +0 > . 1001:2001(1000) ack 21 diff --git a/tools/testing/selftests/net/tls.c b/tools/testing/selftests/net/tls.c index b37ebc2beac7..462f80a46b90 100644 --- a/tools/testing/selftests/net/tls.c +++ b/tools/testing/selftests/net/tls.c @@ -2558,6 +2558,9 @@ TEST_F(zero_len, test) int rec_off; int i; + if (self->notls) + SKIP(return, "no TLS support"); + for (i = 0; i < 4 && variant->recs[i]; i++) EXPECT_EQ(send(self->fd, variant->recs[i]->cipher_data, variant->recs[i]->cipher_len, 0),