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=1795420860; b=o0tnsXmTp+7IMUsN65NmrG1YqkKoLoerOERk5mVevMmesQgNHAZkQAECnruV0w8q5kRe YzvRGNyBYjL6ExS74e68P7U1rDShjtx2sVd9cMHpfWu995nBbPHhT05/c3uKjfHPDfaIE LOv7r8WkrlDnajVTHDKrIR6m9VI+hDeBCSvdt6hHfZaFppnv6CKTSLYHZlMvYcYqy/T2b eJ+1DkTSTJSKy/2PRBuWx7IzfWLkv0jFh6m0zxoXckEMLYxsAkH8WVnfIfWmNCFPFrBbF K/krNQ2SRQB6ZzLEjZ4rb73yOUFtx466e+ctFy5exnhDAE74x9WHAs8QZITFBCqdq/A== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795420860; 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=peqVRny+aDIbK7/n3nSUYWqbUkaUSXPuJxPw5yL5g2Y=; b=LsO5j5pFumLgSx35qEhmN03w+7zUGKMFR3vR8vP/7xRZQkP56dEjRkcghqtM45BgJ3+9 60N+nDxnEnqa32mcSOkL/b4dp4HsjQ449+HUZPQWVeO+Uvyuat5sNvwr1g6EXr2sYDXuI 08QnH2Cja/NqJMbEA3sA1j+TADds9SnbFDuCnSzuD4WwXEUmOIg9nXTWSp0QHM+wh2fnH KHbq0Inl05WuW/kUbKQJcDa5thF3JxPHDWAVyz68pB173z+PEOVLkusNCT2Y7Kxqj2HIS rVyU/hNWp4N3g9X+9hZp2jwB2qVYgGcO6pSgJLuJnGWRoPxScAv+vR91egwMKIBGjdA== 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=Vn8i8+QQ; 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 D50A4606A31E; Mon, 23 Nov 2026 08:01:00 +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=Vn8i8+QQ Received: by smtp.kernel.org (Postfix) with ESMTPSA id 446CA1F000C0; Mon, 23 Nov 2026 08:00:57 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=linuxfoundation.org; s=korg; t=1795420859; bh=peqVRny+aDIbK7/n3nSUYWqbUkaUSXPuJxPw5yL5g2Y=; h=From:To:Cc:Subject:Date:In-Reply-To:References; b=Vn8i8+QQSHZ6frH2QCpi+nVJnrVS8vT49VRQsW5GvAFYyH5GjtO1C4V6UGj/70wmf fscHdYwwU647tcJ1W6F7/uEw2bQlESwo/ahRKYSlxWpwmh/1a6KwnnYaiDVsc0PAvh pb8Obg7nBNMXpE5z79/ecRqk6ItH3mDCf2xkbjDg= 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 7.3.6 Date: Mon, 23 Nov 2026 09:00:10 +0100 Message-ID: <2026112310-retold-unleveled-38a3@gregkh> X-Mailer: git-send-email 2.56.1 In-Reply-To: <2026112310-virus-ecology-b943@gregkh> References: <2026112310-virus-ecology-b943@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/.gitignore b/.gitignore index 9875120ea7bd..01e6a1f7a49e 100644 --- a/.gitignore +++ b/.gitignore @@ -75,7 +75,6 @@ modules.order /vmlinux-gdb.py /vmlinuz /System.map -/Module.markers /modules.builtin /modules.builtin.modinfo /modules.builtin.ranges diff --git a/Documentation/ABI/stable/sysfs-class-infiniband b/Documentation/ABI/stable/sysfs-class-infiniband index 7ba116103429..726a38470e58 100644 --- a/Documentation/ABI/stable/sysfs-class-infiniband +++ b/Documentation/ABI/stable/sysfs-class-infiniband @@ -422,124 +422,6 @@ Description: information) =============== ============================================= - -sysfs interface for Intel IB driver qib ---------------------------------------- - -What: /sys/class/infiniband/qibX/version -What: /sys/class/infiniband/qibX/hw_rev -What: /sys/class/infiniband/qibX/hca_type -What: /sys/class/infiniband/qibX/board_id -What: /sys/class/infiniband/qibX/boardversion -What: /sys/class/infiniband/qibX/nctxts -What: /sys/class/infiniband/qibX/localbus_info -What: /sys/class/infiniband/qibX/tempsense -What: /sys/class/infiniband/qibX/serial -What: /sys/class/infiniband/qibX/nfreectxts -What: /sys/class/infiniband/qibX/chip_reset -Date: May, 2010 -KernelVersion: v2.6.35 -Contact: linux-rdma@vger.kernel.org -Description: - =============== ====================================================== - version: (RO) Display version information of installed software - and drivers. - - hw_rev: (RO) Hardware revision number - - hca_type: (RO) Host channel adapter type - - board_id: (RO) Manufacturing board id - - boardversion: (RO) Current version of the chip architecture - - nctxts: (RO) Return the number of user ports (contexts) - available - - localbus_info: (RO) Human readable localbus info - - tempsense: (RO) Display temp sense registers in decimal - - serial: (RO) Serial number of the HCA - - nfreectxts: (RO) The number of free user ports (contexts) - available. - - chip_reset: (WO) Reset the chip if possible by writing - "reset" to this file. Only allowed if no user - contexts are open that use chip resources. - =============== ====================================================== - - -What: /sys/class/infiniband/qibX/ports//sl2vl/[0-15] -Date: May, 2010 -KernelVersion: v2.6.35 -Contact: linux-rdma@vger.kernel.org -Description: - (RO) The directory contains 16 files numbered 0-15 that specify - the Service Level (SL). Listing the SL files returns the Virtual - Lane (VL) as programmed by the SL. - -What: /sys/class/infiniband/qibX/ports//CCMgtA/cc_settings_bin -What: /sys/class/infiniband/qibX/ports//CCMgtA/cc_table_bin -Date: May, 2010 -KernelVersion: v2.6.35 -Contact: linux-rdma@vger.kernel.org -Description: - Per-port congestion control. Both are binary attributes. - - =============== ================================================ - cc_table_bin (RO) Congestion control table size followed by - table entries. - - cc_settings_bin (RO) Congestion settings: port control, control - map and an array of 16 entries for the - congestion entries - increase, timer, event log - trigger threshold and the minimum injection rate - delay. - =============== ================================================ - -What: /sys/class/infiniband/qibX/ports//linkstate/loopback -What: /sys/class/infiniband/qibX/ports//linkstate/led_override -What: /sys/class/infiniband/qibX/ports//linkstate/hrtbt_enable -What: /sys/class/infiniband/qibX/ports//linkstate/status -What: /sys/class/infiniband/qibX/ports//linkstate/status_str -Date: May, 2010 -KernelVersion: v2.6.35 -Contact: linux-rdma@vger.kernel.org -Description: - [to be documented] - - =============== =============================================== - loopback: (WO) - led_override: (WO) - hrtbt_enable: (RW) - status: (RO) - - status_str: (RO) Displays information about the link state, - possible cable/switch problems, and hardware - errors. Possible states are- "Initted", - "Present", "IB_link_up", "IB_configured" or - "Fatal_Hardware_Error". - =============== =============================================== - -What: /sys/class/infiniband/qibX/ports//diag_counters/rc_resends -What: /sys/class/infiniband/qibX/ports//diag_counters/seq_naks -What: /sys/class/infiniband/qibX/ports//diag_counters/rdma_seq -What: /sys/class/infiniband/qibX/ports//diag_counters/rnr_naks -What: /sys/class/infiniband/qibX/ports//diag_counters/other_naks -What: /sys/class/infiniband/qibX/ports//diag_counters/rc_timeouts -What: /sys/class/infiniband/qibX/ports//diag_counters/look_pkts -What: /sys/class/infiniband/qibX/ports//diag_counters/pkt_drops -What: /sys/class/infiniband/qibX/ports//diag_counters/dma_wait -What: /sys/class/infiniband/qibX/ports//diag_counters/unaligned -Date: May, 2010 -KernelVersion: v2.6.35 -Contact: linux-rdma@vger.kernel.org -Description: - [to be documented] - - sysfs interface for Mellanox Connect-IB HCA driver mlx5 ------------------------------------------------------- diff --git a/Documentation/ABI/testing/sysfs-bus-pci b/Documentation/ABI/testing/sysfs-bus-pci index 55ea1db749a1..c4ff6b538233 100644 --- a/Documentation/ABI/testing/sysfs-bus-pci +++ b/Documentation/ABI/testing/sysfs-bus-pci @@ -244,10 +244,16 @@ Contact: Narendra K , linux-bugs@dell.com Description: Reading this attribute will provide the firmware given name (SMBIOS type 41 string or ACPI _DSM string) of - the PCI device. The attribute will be created only - if the firmware has given a name to the PCI device. - ACPI _DSM string name will be given priority if the - system firmware provides SMBIOS type 41 string also. + the PCI device. The attribute will be created only if the + firmware naming mechanism is implemented for the device: + a SMBIOS type 41 record with a non-empty reference + designation, or a Device Name _DSM that returns the name + as a string or a buffer. The value read is empty when the + firmware implements the _DSM but gives the device no name, + which per PCI Firmware r3.3, sec 4.6.7 the firmware reports + as a NULL string. ACPI _DSM string name will be given + priority if the system firmware provides SMBIOS type 41 + string also. Users: Userspace applications interested in knowing the firmware assigned name of the PCI device. diff --git a/Documentation/ABI/testing/sysfs-class-led b/Documentation/ABI/testing/sysfs-class-led index d4c918cc11a1..f6d4e17e1a3b 100644 --- a/Documentation/ABI/testing/sysfs-class-led +++ b/Documentation/ABI/testing/sysfs-class-led @@ -28,7 +28,9 @@ Description: Writing 0 to this file clears active trigger. Writing non-zero to this file while trigger is active changes the - top brightness trigger is going to use. + top brightness trigger is going to use, unless the current + trigger is offloaded to hardware (in which case writing any + value will deactivate the trigger). diff --git a/Documentation/ABI/testing/sysfs-class-power-mp2629 b/Documentation/ABI/testing/sysfs-class-power-mp2629 index 914d67caac0d..a85f926ce9c2 100644 --- a/Documentation/ABI/testing/sysfs-class-power-mp2629 +++ b/Documentation/ABI/testing/sysfs-class-power-mp2629 @@ -1,4 +1,4 @@ -What: /sys/class/power_supply/mp2629_battery/batt_impedance_compen +What: /sys/class/power_supply/mp2629_battery/batt_impedance_compensation Date: April 2020 KernelVersion: 5.7 Description: diff --git a/Documentation/admin-guide/LSM/LoadPin.rst b/Documentation/admin-guide/LSM/LoadPin.rst index dd3ca68b5df1..a90fd9dac960 100644 --- a/Documentation/admin-guide/LSM/LoadPin.rst +++ b/Documentation/admin-guide/LSM/LoadPin.rst @@ -23,9 +23,9 @@ sysctl allows for easy testing on systems with a mutable filesystem.) It's also possible to exclude specific file types from LoadPin using kernel command line option "``loadpin.exclude``". By default, all files are included, but they can be excluded using kernel command line option such -as "``loadpin.exclude=kernel-module,kexec-image``". This allows to use +as "``loadpin.exclude=kernel-module,kexec-image``". This allows using different mechanisms such as ``CONFIG_MODULE_SIG`` and -``CONFIG_KEXEC_VERIFY_SIG`` to verify kernel module and kernel image while -still use LoadPin to protect the integrity of other files kernel loads. The -full list of valid file types can be found in ``kernel_read_file_str`` -defined in ``include/linux/kernel_read_file.h``. +``CONFIG_KEXEC_SIG`` to verify kernel modules and kernel images while +still using LoadPin to protect the integrity of other files the kernel +loads. The full list of valid file types can be found in +``kernel_read_file_str`` defined in ``include/linux/kernel_read_file.h``. diff --git a/Documentation/admin-guide/LSM/ipe.rst b/Documentation/admin-guide/LSM/ipe.rst index a756d8158531..bebf14fc2411 100644 --- a/Documentation/admin-guide/LSM/ipe.rst +++ b/Documentation/admin-guide/LSM/ipe.rst @@ -502,11 +502,11 @@ The following table lists the error codes that may appear in the errno field whi Event Examples:: type=1404 audit(1653425689.008:55): enforcing=0 old_enforcing=1 auid=4294967295 ses=4294967295 enabled=1 old-enabled=1 lsm=ipe res=1 - type=1300 audit(1653425689.008:55): arch=c000003e syscall=1 success=yes exit=2 a0=1 a1=55c1065e5c60 a2=2 a3=0 items=0 ppid=405 pid=441 auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=) + type=1300 audit(1653425689.008:55): arch=c000003e syscall=1 success=yes exit=2 a0=1 a1=55c1065e5c60 a2=2 a3=0 items=0 ppid=405 pid=441 auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 type=1327 audit(1653425689.008:55): proctitle="-bash" type=1404 audit(1653425689.008:55): enforcing=1 old_enforcing=0 auid=4294967295 ses=4294967295 enabled=1 old-enabled=1 lsm=ipe res=1 - type=1300 audit(1653425689.008:55): arch=c000003e syscall=1 success=yes exit=2 a0=1 a1=55c1065e5c60 a2=2 a3=0 items=0 ppid=405 pid=441 auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=) + type=1300 audit(1653425689.008:55): arch=c000003e syscall=1 success=yes exit=2 a0=1 a1=55c1065e5c60 a2=2 a3=0 items=0 ppid=405 pid=441 auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 type=1327 audit(1653425689.008:55): proctitle="-bash" This record will always be emitted in conjunction with a ``AUDITSYSCALL`` record for the ``write`` syscall. diff --git a/Documentation/admin-guide/cgroup-v2.rst b/Documentation/admin-guide/cgroup-v2.rst index 86a2a0099178..f8bc721ec408 100644 --- a/Documentation/admin-guide/cgroup-v2.rst +++ b/Documentation/admin-guide/cgroup-v2.rst @@ -2727,7 +2727,9 @@ Cpuset Interface Files be retained, but behaves more like a "member". All possible state transitions among "member", "root" and - "isolated" are allowed. + "isolated" are allowed with the exception that a local child + "root" partition is not allowed to be created under an "isolated" + parent partition. On read, the "cpuset.cpus.partition" file can show the following values. diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt index 4e64219c8da4..b92d84e33b55 100644 --- a/Documentation/admin-guide/kernel-parameters.txt +++ b/Documentation/admin-guide/kernel-parameters.txt @@ -501,13 +501,6 @@ Kernel parameters disable Disable amd-pstate preferred core. - amd_dynamic_epp= - [X86] - disable - Disable amd-pstate dynamic EPP. - enable - Enable amd-pstate dynamic EPP. - amijoy.map= [HW,JOY] Amiga joystick support Map of devices attached to JOY0DAT and JOY1DAT Format: , @@ -6622,6 +6615,9 @@ Kernel parameters reserve_mem=12M:4096:oops ramoops.mem_name=oops + Both the size and the alignment must be multiples of + the page size. + reservetop= [X86-32,EARLY] Format: nn[KMG] Reserves a hole at the top of the kernel virtual diff --git a/Documentation/admin-guide/pm/amd-pstate.rst b/Documentation/admin-guide/pm/amd-pstate.rst index 6fd72ba52df2..4c5d3d8acf64 100644 --- a/Documentation/admin-guide/pm/amd-pstate.rst +++ b/Documentation/admin-guide/pm/amd-pstate.rst @@ -481,12 +481,6 @@ For systems that support ``amd-pstate`` preferred core, the core rankings will always be advertised by the platform. But OS can choose to ignore that via the kernel parameter ``amd_prefcore=disable``. -``amd_dynamic_epp`` - -When AMD pstate is in auto mode, dynamic EPP will control whether the kernel -autonomously changes the EPP mode. The default is disabled. It can be enabled -with the kernel parameter ``amd_dynamic_epp=enable``. - User Space Interface in ``sysfs`` - General =========================================== diff --git a/Documentation/bpf/bpf_iterators.rst b/Documentation/bpf/bpf_iterators.rst index 189e3ec1c6c8..72435e32ffa1 100644 --- a/Documentation/bpf/bpf_iterators.rst +++ b/Documentation/bpf/bpf_iterators.rst @@ -86,6 +86,16 @@ Constructor/next/destructor implementation contract is as follows: resources and marks stack space used by `struct bpf_iter_` as usable for something else. Destructor is marked with KF_ITER_DESTROY flag. +The verifier treats a non-RCU, non-acquired struct result as borrowed from +the iterator's current element. It invalidates the previous result and its +tracked derived pointers on the next call, including when it returns NULL, +and on destruction of the iterator. Resources borrowing that lifetime must +be released first. A next method whose struct result has an independent +lifetime must use ``KF_ITER_RET_INDEPENDENT``. This flag requires +``KF_ITER_NEXT`` and a struct pointer return type, and cannot be combined +with ``KF_ACQUIRE``. RCU-protected and acquired results retain their own +lifetime rules. + Any open-coded BPF iterator implementation has to implement at least these three methods. It is enforced that for any given type of iterator only applicable constructor/destructor/next are callable. I.e., verifier ensures diff --git a/Documentation/devicetree/bindings/arm/mediatek/mediatek,audsys.yaml b/Documentation/devicetree/bindings/arm/mediatek/mediatek,audsys.yaml index 9aa39b002361..5ede7d277488 100644 --- a/Documentation/devicetree/bindings/arm/mediatek/mediatek,audsys.yaml +++ b/Documentation/devicetree/bindings/arm/mediatek/mediatek,audsys.yaml @@ -19,7 +19,7 @@ properties: - enum: - mediatek,mt2701-audsys - mediatek,mt6765-audsys - - mediatek,mt6779-audsys + - mediatek,mt6779-audio - mediatek,mt7622-audsys - mediatek,mt8167-audsys - mediatek,mt8173-audsys diff --git a/Documentation/devicetree/bindings/clock/mediatek,apmixedsys.yaml b/Documentation/devicetree/bindings/clock/mediatek,apmixedsys.yaml index 591a9e862c7d..438723d25320 100644 --- a/Documentation/devicetree/bindings/clock/mediatek,apmixedsys.yaml +++ b/Documentation/devicetree/bindings/clock/mediatek,apmixedsys.yaml @@ -26,7 +26,6 @@ properties: - mediatek,mt7988-apmixedsys - mediatek,mt8135-apmixedsys - mediatek,mt8173-apmixedsys - - mediatek,mt8516-apmixedsys - items: - const: mediatek,mt7623-apmixedsys - const: mediatek,mt2701-apmixedsys @@ -42,6 +41,7 @@ properties: - mediatek,mt7629-apmixedsys - mediatek,mt8167-apmixedsys - mediatek,mt8183-apmixedsys + - mediatek,mt8516-apmixedsys - const: syscon reg: diff --git a/Documentation/devicetree/bindings/clock/mediatek,topckgen.yaml b/Documentation/devicetree/bindings/clock/mediatek,topckgen.yaml index c080fb0a1618..6594d491e215 100644 --- a/Documentation/devicetree/bindings/clock/mediatek,topckgen.yaml +++ b/Documentation/devicetree/bindings/clock/mediatek,topckgen.yaml @@ -23,7 +23,6 @@ properties: - mediatek,mt7622-topckgen - mediatek,mt8135-topckgen - mediatek,mt8173-topckgen - - mediatek,mt8516-topckgen - items: - const: mediatek,mt7623-topckgen - const: mediatek,mt2701-topckgen @@ -43,6 +42,7 @@ properties: - mediatek,mt7988-topckgen - mediatek,mt8167-topckgen - mediatek,mt8183-topckgen + - mediatek,mt8516-topckgen - const: syscon reg: diff --git a/Documentation/devicetree/bindings/clock/qcom,milos-camcc.yaml b/Documentation/devicetree/bindings/clock/qcom,milos-camcc.yaml index 707b25d2c11e..c4aba40e316c 100644 --- a/Documentation/devicetree/bindings/clock/qcom,milos-camcc.yaml +++ b/Documentation/devicetree/bindings/clock/qcom,milos-camcc.yaml @@ -29,9 +29,21 @@ properties: items: - description: Interconnect path to enable the MultiMedia NoC + power-domains: + items: + - description: CX power domain + - description: MX power domain + + required-opps: + items: + - description: CX performance point + - description: MX performance point + required: - compatible - clocks + - power-domains + - required-opps allOf: - $ref: qcom,gcc.yaml# @@ -43,6 +55,7 @@ examples: #include #include #include + #include clock-controller@adb0000 { compatible = "qcom,milos-camcc"; reg = <0x0adb0000 0x40000>; @@ -51,6 +64,12 @@ examples: <&gcc GCC_CAMERA_AHB_CLK>; interconnects = <&mmss_noc MASTER_CAMNOC_HF QCOM_ICC_TAG_ALWAYS &mmss_noc SLAVE_MNOC_HF_MEM_NOC QCOM_ICC_TAG_ALWAYS>; + + power-domains = <&rpmhpd RPMHPD_CX>, + <&rpmhpd RPMHPD_MX>; + required-opps = <&rpmhpd_opp_low_svs>, + <&rpmhpd_opp_low_svs>; + #clock-cells = <1>; #reset-cells = <1>; #power-domain-cells = <1>; diff --git a/Documentation/devicetree/bindings/clock/qcom,milos-videocc.yaml b/Documentation/devicetree/bindings/clock/qcom,milos-videocc.yaml index 14c31efe1308..4d8d109cd304 100644 --- a/Documentation/devicetree/bindings/clock/qcom,milos-videocc.yaml +++ b/Documentation/devicetree/bindings/clock/qcom,milos-videocc.yaml @@ -26,9 +26,21 @@ properties: - description: Sleep clock source - description: Video AHB clock from GCC + power-domains: + items: + - description: CX power domain + - description: MX power domain + + required-opps: + items: + - description: CX performance point + - description: MX performance point + required: - compatible - clocks + - power-domains + - required-opps allOf: - $ref: qcom,gcc.yaml# @@ -38,6 +50,7 @@ unevaluatedProperties: false examples: - | #include + #include clock-controller@aaf0000 { compatible = "qcom,milos-videocc"; reg = <0x0aaf0000 0x10000>; @@ -45,6 +58,12 @@ examples: <&bi_tcxo_ao_div2>, <&sleep_clk>, <&gcc GCC_VIDEO_AHB_CLK>; + + power-domains = <&rpmhpd RPMHPD_CX>, + <&rpmhpd RPMHPD_MX>; + required-opps = <&rpmhpd_opp_low_svs>, + <&rpmhpd_opp_low_svs>; + #clock-cells = <1>; #reset-cells = <1>; #power-domain-cells = <1>; diff --git a/Documentation/devicetree/bindings/clock/qcom,sm8750-gcc.yaml b/Documentation/devicetree/bindings/clock/qcom,sm8750-gcc.yaml index 0114d347b26f..59da3eb2b073 100644 --- a/Documentation/devicetree/bindings/clock/qcom,sm8750-gcc.yaml +++ b/Documentation/devicetree/bindings/clock/qcom,sm8750-gcc.yaml @@ -34,9 +34,14 @@ properties: - description: UFS Phy Tx symbol 0 clock source - description: USB3 Phy wrapper pipe clock source + power-domains: + items: + - description: CX power domain + required: - compatible - clocks + - power-domains - '#power-domain-cells' allOf: @@ -47,6 +52,7 @@ unevaluatedProperties: false examples: - | #include + #include clock-controller@100000 { compatible = "qcom,sm8750-gcc"; reg = <0x00100000 0x001f4200>; @@ -58,6 +64,7 @@ examples: <&ufs_mem_phy 1>, <&ufs_mem_phy 2>, <&usb_1_qmpphy>; + power-domains = <&rpmhpd RPMHPD_CX>; #clock-cells = <1>; #reset-cells = <1>; #power-domain-cells = <1>; diff --git a/Documentation/devicetree/bindings/display/msm/gmu.yaml b/Documentation/devicetree/bindings/display/msm/gmu.yaml index 9e459f12ce3f..f22661447e7c 100644 --- a/Documentation/devicetree/bindings/display/msm/gmu.yaml +++ b/Documentation/devicetree/bindings/display/msm/gmu.yaml @@ -363,7 +363,7 @@ allOf: properties: compatible: contains: - const: qcom,adreno-gmu-x285.1 + const: qcom,adreno-gmu-x290.1 then: properties: reg: diff --git a/Documentation/devicetree/bindings/display/msm/hdmi.yaml b/Documentation/devicetree/bindings/display/msm/hdmi.yaml index dfec6c3480f3..02d27ccad024 100644 --- a/Documentation/devicetree/bindings/display/msm/hdmi.yaml +++ b/Documentation/devicetree/bindings/display/msm/hdmi.yaml @@ -113,7 +113,7 @@ allOf: - const: core - const: master_iface - const: slave_iface - core-vcc-supplies: false + core-vcc-supply: false - if: properties: @@ -136,7 +136,7 @@ allOf: - const: core - const: alt_iface - const: extp - hdmi-mux-supplies: false + hdmi-mux-supply: false - if: properties: diff --git a/Documentation/devicetree/bindings/display/panel/samsung,s6e8aa5x01-ams561ra01.yaml b/Documentation/devicetree/bindings/display/panel/samsung,s6e8aa5x01-ams561ra01.yaml index b271de575e15..f04702de1101 100644 --- a/Documentation/devicetree/bindings/display/panel/samsung,s6e8aa5x01-ams561ra01.yaml +++ b/Documentation/devicetree/bindings/display/panel/samsung,s6e8aa5x01-ams561ra01.yaml @@ -34,7 +34,7 @@ required: - compatible - reg -additionalProperties: false +unevaluatedProperties: false examples: - | diff --git a/Documentation/devicetree/bindings/dma/stericsson,dma40.yaml b/Documentation/devicetree/bindings/dma/stericsson,dma40.yaml index d8f92838f4c9..81b83603ea79 100644 --- a/Documentation/devicetree/bindings/dma/stericsson,dma40.yaml +++ b/Documentation/devicetree/bindings/dma/stericsson,dma40.yaml @@ -140,8 +140,22 @@ properties: - description: LCPA (Logical Channel Parameter Address) memory. - description: LCLA (Logical Channel Link base Address) memory. + disabled-channels: + $ref: /schemas/types.yaml#/definitions/uint32-array + minItems: 1 + maxItems: 31 + uniqueItems: true + items: + maximum: 31 + description: Physical channels that cannot be used by the DMA engine. + memcpy-channels: $ref: /schemas/types.yaml#/definitions/uint32-array + minItems: 1 + maxItems: 8 + uniqueItems: true + items: + maximum: 63 description: Array of u32 elements indicating which channels on the DMA engine are eligible for memcpy transfers diff --git a/Documentation/devicetree/bindings/iio/adc/renesas,r9a09g077-adc.yaml b/Documentation/devicetree/bindings/iio/adc/renesas,r9a09g077-adc.yaml index dc0206b28231..ae14fdbe44b1 100644 --- a/Documentation/devicetree/bindings/iio/adc/renesas,r9a09g077-adc.yaml +++ b/Documentation/devicetree/bindings/iio/adc/renesas,r9a09g077-adc.yaml @@ -34,8 +34,6 @@ properties: - description: A/D scan end interrupt for Group C - description: Window A compare match - description: Window B compare match - - description: Compare match - - description: Compare mismatch interrupt-names: items: @@ -44,8 +42,6 @@ properties: - const: gcadi - const: cmpai - const: cmpbi - - const: wcmpm - - const: wcmpum clocks: items: @@ -107,11 +103,9 @@ examples: , , , - , - , - ; + ; interrupt-names = "adi", "gbadi", "gcadi", - "cmpai", "cmpbi", "wcmpm", "wcmpum"; + "cmpai", "cmpbi"; clocks = <&cpg CPG_CORE R9A09G077_CLK_PCLKL>, <&cpg CPG_MOD 225>; clock-names = "adclk", "pclk"; diff --git a/Documentation/devicetree/bindings/iio/light/liteon,ltr501.yaml b/Documentation/devicetree/bindings/iio/light/liteon,ltr501.yaml index c8074f180a79..6234e2eaec2e 100644 --- a/Documentation/devicetree/bindings/iio/light/liteon,ltr501.yaml +++ b/Documentation/devicetree/bindings/iio/light/liteon,ltr501.yaml @@ -15,9 +15,10 @@ allOf: properties: compatible: enum: + - liteon,ltr301 + - liteon,ltr303 - liteon,ltr501 - liteon,ltr559 - - liteon,ltr301 reg: maxItems: 1 diff --git a/Documentation/devicetree/bindings/interrupt-controller/chrp,open-pic.yaml b/Documentation/devicetree/bindings/interrupt-controller/chrp,open-pic.yaml index 642738512f3c..294af57a7c37 100644 --- a/Documentation/devicetree/bindings/interrupt-controller/chrp,open-pic.yaml +++ b/Documentation/devicetree/bindings/interrupt-controller/chrp,open-pic.yaml @@ -12,8 +12,9 @@ maintainers: description: This binding specifies what properties must be available in the device tree representation of an Open PIC compliant interrupt controller. This binding is - based on the binding defined for Open PIC in [1] and is a superset of that - binding. + based on the binding defined for Open PIC in the Devicetree Specification + (available from https://www.devicetree.org/specifications/) and is a superset + of that binding. properties: compatible: @@ -24,7 +25,7 @@ properties: - const: chrp,open-pic device_type: - const: open-pci + const: open-pic deprecated: true reg: diff --git a/Documentation/devicetree/bindings/interrupt-controller/thead,c900-aclint-mswi.yaml b/Documentation/devicetree/bindings/interrupt-controller/thead,c900-aclint-mswi.yaml index 62fd220e126e..d17f5613612c 100644 --- a/Documentation/devicetree/bindings/interrupt-controller/thead,c900-aclint-mswi.yaml +++ b/Documentation/devicetree/bindings/interrupt-controller/thead,c900-aclint-mswi.yaml @@ -12,6 +12,7 @@ maintainers: properties: compatible: oneOf: + - const: spacemit,k3-aclint-mswi - items: - enum: - sophgo,sg2042-aclint-mswi diff --git a/Documentation/devicetree/bindings/interrupt-controller/thead,c900-aclint-sswi.yaml b/Documentation/devicetree/bindings/interrupt-controller/thead,c900-aclint-sswi.yaml index d02c6886283a..0b34ed5b4639 100644 --- a/Documentation/devicetree/bindings/interrupt-controller/thead,c900-aclint-sswi.yaml +++ b/Documentation/devicetree/bindings/interrupt-controller/thead,c900-aclint-sswi.yaml @@ -24,12 +24,13 @@ description: properties: compatible: oneOf: + - enum: + - mips,p8700-aclint-sswi + - spacemit,k3-aclint-sswi - items: - enum: - sophgo,sg2044-aclint-sswi - const: thead,c900-aclint-sswi - - items: - - const: mips,p8700-aclint-sswi - items: - enum: - anlogic,dr1v90-aclint-sswi diff --git a/Documentation/devicetree/bindings/media/allwinner,sun4i-a10-video-engine.yaml b/Documentation/devicetree/bindings/media/allwinner,sun4i-a10-video-engine.yaml index 01f2afa023f0..932043d7f0cc 100644 --- a/Documentation/devicetree/bindings/media/allwinner,sun4i-a10-video-engine.yaml +++ b/Documentation/devicetree/bindings/media/allwinner,sun4i-a10-video-engine.yaml @@ -55,7 +55,10 @@ properties: description: Phandle to the device SRAM iommus: - maxItems: 1 + minItems: 1 + items: + - description: VE port on IOMMU + - description: VE_R port on IOMMU memory-region: maxItems: 1 @@ -82,6 +85,22 @@ required: - resets - allwinner,sram +allOf: + - if: + properties: + compatible: + contains: + enum: + - allwinner,sun50i-h6-video-engine + then: + properties: + iommus: + minItems: 2 + else: + properties: + iommus: + maxItems: 1 + additionalProperties: false examples: diff --git a/Documentation/devicetree/bindings/phy/ti,tcan104x-can.yaml b/Documentation/devicetree/bindings/phy/ti,tcan104x-can.yaml index 9f5c37ca6496..0cf5fa21106b 100644 --- a/Documentation/devicetree/bindings/phy/ti,tcan104x-can.yaml +++ b/Documentation/devicetree/bindings/phy/ti,tcan104x-can.yaml @@ -71,10 +71,11 @@ allOf: - if: properties: compatible: - enum: - - nxp,tjr1443 - - ti,tcan1042 - - ti,tcan1043 + contains: + enum: + - nxp,tjr1443 + - ti,tcan1042 + - ti,tcan1043 then: properties: '#phy-cells': diff --git a/Documentation/devicetree/bindings/power/supply/bq27xxx.yaml b/Documentation/devicetree/bindings/power/supply/bq27xxx.yaml index bc05400186cf..d985ae632599 100644 --- a/Documentation/devicetree/bindings/power/supply/bq27xxx.yaml +++ b/Documentation/devicetree/bindings/power/supply/bq27xxx.yaml @@ -91,7 +91,6 @@ allOf: - ti,bq27742 - ti,bq27545 - ti,bq27411 - - ti,bq27z561 - ti,bq28z610 - ti,bq34z100 - ti,bq78z100 diff --git a/Documentation/devicetree/bindings/power/supply/stericsson,ab8500-charger.yaml b/Documentation/devicetree/bindings/power/supply/stericsson,ab8500-charger.yaml index 4f19744844e9..dcffcecaea13 100644 --- a/Documentation/devicetree/bindings/power/supply/stericsson,ab8500-charger.yaml +++ b/Documentation/devicetree/bindings/power/supply/stericsson,ab8500-charger.yaml @@ -10,12 +10,13 @@ title: AB8500 Charger maintainers: - Sebastian Reichel -allOf: - - $ref: power-supply.yaml# - properties: compatible: - const: stericsson,ab8500-charger + oneOf: + - const: stericsson,ab8500-charger + - items: + - const: stericsson,ab8505-charger + - const: stericsson,ab8500-charger monitored-battery: true @@ -28,27 +29,15 @@ properties: autopower_cfg: type: boolean - description: automatic poweron after powerloss + description: AB8500 automatic poweron after powerloss interrupts: + minItems: 9 maxItems: 14 interrupt-names: - items: - - const: MAIN_CH_UNPLUG_DET - - const: MAIN_CHARGE_PLUG_DET - - const: MAIN_EXT_CH_NOT_OK - - const: MAIN_CH_TH_PROT_R - - const: MAIN_CH_TH_PROT_F - - const: VBUS_DET_F - - const: VBUS_DET_R - - const: USB_LINK_STATUS - - const: USB_CH_TH_PROT_R - - const: USB_CH_TH_PROT_F - - const: USB_CHARGER_NOT_OKR - - const: VBUS_OVV - - const: CH_WD_EXP - - const: VBUS_CH_DROP_END + minItems: 9 + maxItems: 14 io-channels: minItems: 2 @@ -74,6 +63,53 @@ required: - io-channels - io-channel-names +allOf: + - $ref: power-supply.yaml# + - if: + properties: + compatible: + contains: + const: stericsson,ab8505-charger + then: + properties: + interrupts: + minItems: 9 + maxItems: 9 + + interrupt-names: + items: + - const: VBUS_DET_F + - const: VBUS_DET_R + - const: USB_LINK_STATUS + - const: USB_CH_TH_PROT_R + - const: USB_CH_TH_PROT_F + - const: USB_CHARGER_NOT_OKR + - const: VBUS_OVV + - const: CH_WD_EXP + - const: VBUS_CH_DROP_END + else: + properties: + interrupts: + minItems: 14 + maxItems: 14 + + interrupt-names: + items: + - const: MAIN_CH_UNPLUG_DET + - const: MAIN_CHARGE_PLUG_DET + - const: MAIN_EXT_CH_NOT_OK + - const: MAIN_CH_TH_PROT_R + - const: MAIN_CH_TH_PROT_F + - const: VBUS_DET_F + - const: VBUS_DET_R + - const: USB_LINK_STATUS + - const: USB_CH_TH_PROT_R + - const: USB_CH_TH_PROT_F + - const: USB_CHARGER_NOT_OKR + - const: VBUS_OVV + - const: CH_WD_EXP + - const: VBUS_CH_DROP_END + additionalProperties: false examples: diff --git a/Documentation/devicetree/bindings/thermal/amlogic,thermal.yaml b/Documentation/devicetree/bindings/thermal/amlogic,thermal.yaml index 8cfa44dcda58..e72cb39ac635 100644 --- a/Documentation/devicetree/bindings/thermal/amlogic,thermal.yaml +++ b/Documentation/devicetree/bindings/thermal/amlogic,thermal.yaml @@ -32,7 +32,15 @@ properties: maxItems: 1 clocks: - maxItems: 1 + minItems: 1 + items: + - description: Bus clock, gates register access to the sensor. + - description: Functional clock of the temperature sensor, shared between sensors. + + clock-names: + items: + - const: bus + - const: core power-domains: maxItems: 1 @@ -72,6 +80,22 @@ allOf: else: required: - amlogic,secure-monitor + - if: + properties: + compatible: + contains: + const: amlogic,t7-thermal + then: + properties: + clocks: + minItems: 2 + required: + - clock-names + else: + properties: + clocks: + maxItems: 1 + clock-names: false unevaluatedProperties: false @@ -94,7 +118,8 @@ examples: compatible = "amlogic,t7-thermal"; reg = <0x20000 0x50>; interrupts = ; - clocks = <&clkc_periphs CLKID_TS>; + clocks = <&clkc_periphs CLKID_SYS_TS_A73>, <&clkc_periphs CLKID_TS>; + clock-names = "bus", "core"; #thermal-sensor-cells = <0>; amlogic,secure-monitor = <&sm 1>; }; diff --git a/Documentation/devicetree/bindings/timer/sifive,clint.yaml b/Documentation/devicetree/bindings/timer/sifive,clint.yaml index 3673836e14de..d53f52e80d88 100644 --- a/Documentation/devicetree/bindings/timer/sifive,clint.yaml +++ b/Documentation/devicetree/bindings/timer/sifive,clint.yaml @@ -34,7 +34,6 @@ properties: - microchip,pic64gx-clint # Microchip PIC64GX - sifive,fu540-c000-clint # SiFive FU540 - spacemit,k1-clint # SpacemiT K1 - - spacemit,k3-clint # SpacemiT K3 - starfive,jh7100-clint # StarFive JH7100 - starfive,jh7110-clint # StarFive JH7110 - starfive,jh8100-clint # StarFive JH8100 diff --git a/Documentation/devicetree/bindings/timer/thead,c900-aclint-mtimer.yaml b/Documentation/devicetree/bindings/timer/thead,c900-aclint-mtimer.yaml index cf7c82e980f6..082378b04d72 100644 --- a/Documentation/devicetree/bindings/timer/thead,c900-aclint-mtimer.yaml +++ b/Documentation/devicetree/bindings/timer/thead,c900-aclint-mtimer.yaml @@ -12,6 +12,7 @@ maintainers: properties: compatible: oneOf: + - const: spacemit,k3-aclint-mtimer - items: - enum: - sophgo,sg2042-aclint-mtimer diff --git a/Documentation/devicetree/bindings/vendor-prefixes.yaml b/Documentation/devicetree/bindings/vendor-prefixes.yaml index ba2002969373..9bee5cec0b8a 100644 --- a/Documentation/devicetree/bindings/vendor-prefixes.yaml +++ b/Documentation/devicetree/bindings/vendor-prefixes.yaml @@ -114,6 +114,8 @@ patternProperties: description: Amarula Solutions "^amazon,.*": description: Amazon.com, Inc. + "^ambarella,.*": + description: Ambarella, Inc. "^amcc,.*": description: Applied Micro Circuits Corporation (APM, formally AMCC) "^amd,.*": @@ -327,6 +329,8 @@ patternProperties: description: ChipOne "^chipspark,.*": description: ChipSPARK + "^chipwealth,.*": + description: Chip Wealth Technology "^chongzhou,.*": description: Shenzhen Chongzhou Electronic Technology Co., Ltd "^chrontel,.*": @@ -559,6 +563,8 @@ patternProperties: description: Seiko Epson Corp. "^esp,.*": description: Espressif Systems Co. Ltd. + "^esstech,.*": + description: ESS Technology, Inc. "^est,.*": description: ESTeem Wireless Modems "^eswin,.*": @@ -626,6 +632,8 @@ patternProperties: description: Freebox SAS "^freecom,.*": description: Freecom Gmbh + "^freemobile,.*": + description: Free Mobile "^frida,.*": description: Shenzhen Frida LCD Co., Ltd. "^friendlyarm,.*": @@ -662,6 +670,8 @@ patternProperties: description: Gemei Digital Technology Co., Ltd. "^gemtek,.*": description: Gemtek Technology Co., Ltd. + "^generalmobile,.*": + description: General Mobile Fzc. "^genesys,.*": description: Genesys Logic, Inc. "^genexis,.*": @@ -949,6 +959,8 @@ patternProperties: description: Shenzen LC Technology Co., Ltd. "^leadtek,.*": description: Shenzhen Leadtek Technology Co., Ltd. + "^leeco,.*": + description: Leshi Holding Beijing. "^leez,.*": description: Leez "^lego,.*": @@ -1192,6 +1204,8 @@ patternProperties: description: New Vision Display (Shenzhen) Co., Ltd. "^nexbox,.*": description: Nexbox + "^nexperia,.*": + description: Nexperia B.V. "^nextthing,.*": description: Next Thing Co. "^ni,.*": @@ -1419,6 +1433,8 @@ patternProperties: description: Renesas Electronics Corporation "^rervision,.*": description: Shenzhen Rervision Technology Co., Ltd. + "^retroidpocket,.*": + description: Retroid Pocket "^retronix,.*": description: Retronix Technology Inc. "^revotics,.*": @@ -1495,6 +1511,8 @@ patternProperties: description: Sensirion AG "^sensortek,.*": description: Sensortek Technology Corporation + "^sensylink,.*": + description: Sensylink Microelectronics Technology Co., Ltd. "^sercomm,.*": description: Sercomm (Suzhou) Corporation "^sff,.*": @@ -1595,6 +1613,8 @@ patternProperties: description: Sony Corporation "^sophgo,.*": description: Sophgo Technology Inc. + "^sophos,.*": + description: Sophos Ltd. "^sourceparts,.*": description: Source Parts Inc. "^spacemit,.*": diff --git a/Documentation/filesystems/erofs.rst b/Documentation/filesystems/erofs.rst index d301d9ac946a..02caf3b061fe 100644 --- a/Documentation/filesystems/erofs.rst +++ b/Documentation/filesystems/erofs.rst @@ -139,6 +139,9 @@ inode_share Enable inode page sharing for this filesystem. Inodes wi page cache. source=%s (For file-backed mounts) Specify the backing image as a path or as an already-opened file descriptor. +superblock_share (For file-backed mounts) Share the superblock when the same + backing file is mounted more than once with compatible + options. Remount is not allowed on shared superblocks. =================== ========================================================= File-backed mounts @@ -156,6 +159,10 @@ Only regular files are accepted as backing files; to mount an image that resides on a block device, use the traditional block device mount path instead. +When superblock_share is specified, multiple mounts of the same backing +file at the same fsoffset with compatible mount options can share a single +superblock. Remount is not allowed on shared superblocks. + Sysfs Entries ============= diff --git a/Documentation/filesystems/f2fs.rst b/Documentation/filesystems/f2fs.rst index 771216f45207..55798421f2c4 100644 --- a/Documentation/filesystems/f2fs.rst +++ b/Documentation/filesystems/f2fs.rst @@ -421,7 +421,8 @@ resizable_tail_secno=%u Control the number of sections at the tail of the (MAIN_SECS - resizable_tail_secno) - 1. If set to 0 (default), there is no tail restriction unless running on a zoned block device where conventional zones are - used. + used. Online shrink consumes this reservation, reducing + the value by the number of removed sections, down to zero. ======================== ============================================================ Debugfs Entries diff --git a/Documentation/filesystems/resctrl.rst b/Documentation/filesystems/resctrl.rst index 6b641c3cee64..fd643cea4726 100644 --- a/Documentation/filesystems/resctrl.rst +++ b/Documentation/filesystems/resctrl.rst @@ -658,7 +658,7 @@ When monitoring is enabled all MON groups will also contain: during execution of instructions summed across all logical CPUs on a package for the current monitoring group. - "activity" also reports a floating point value (in Farads). This provides + "activity" also reports a floating point value (in nanofarads). This provides an estimate of work done independent of the frequency that the CPUs used for execution. diff --git a/Documentation/leds/leds-st1202.rst b/Documentation/leds/leds-st1202.rst index ed32eb3a27d4..28479a112389 100644 --- a/Documentation/leds/leds-st1202.rst +++ b/Documentation/leds/leds-st1202.rst @@ -20,6 +20,11 @@ brightness (PWM) and duration must be written to hw_pattern. - Min pattern duration: 22 ms - Max pattern duration: 5610 ms +If the device tree sets max-brightness, that value replaces 255 as the +upper limit, and a step equal to it drives the channel at full scale. +The hardware cannot go above 255, so with a larger max-brightness every +step from 255 upwards is full scale. + The format of the hardware pattern values should be: "brightness duration brightness duration ..." diff --git a/Documentation/mm/process_addrs.rst b/Documentation/mm/process_addrs.rst index a7296f251799..bfd4dfada663 100644 --- a/Documentation/mm/process_addrs.rst +++ b/Documentation/mm/process_addrs.rst @@ -808,9 +808,17 @@ All this is achieved by the use of per-mm and per-VMA sequence counts, which are used in order to reduce complexity, especially for operations which write-lock multiple VMAs at once. -If the mm sequence count, :c:member:`!mm->mm_lock_seq` is equal to the VMA -sequence count :c:member:`!vma->vm_lock_seq` then the VMA is write-locked. If -they differ, then it is not. +The mm sequence count :c:member:`!mm->mm_lock_seq` is incremented on both mmap +write lock and unlock, so it is odd while the mmap write lock is held. If it is +equal to the VMA sequence count :c:member:`!vma->vm_lock_seq`, and that value +is odd, then the VMA is write-locked. If they differ, then it is not. + +A VMA's sequence count is not updated on unlock, so after 2^31 write lock/unlock +cycles the mm sequence count would wrap and match stale VMA values again. To +prevent this, when the mm sequence count wraps to zero, +:c:func:`!vma_end_write_all` invokes :c:func:`!__mm_reset_vma_seqcounts` to +reset every VMA's sequence count to zero, an even value which can never +indicate a write lock. Each time the mmap write lock is released in :c:func:`!mmap_write_unlock` or :c:func:`!mmap_write_downgrade`, :c:func:`!vma_end_write_all` is invoked which diff --git a/Documentation/netlink/specs/devlink.yaml b/Documentation/netlink/specs/devlink.yaml index 38b1190f3d26..31667f43b848 100644 --- a/Documentation/netlink/specs/devlink.yaml +++ b/Documentation/netlink/specs/devlink.yaml @@ -845,13 +845,14 @@ attribute-sets: name: linecard-supported-types type: nest nested-attributes: dl-linecard-supported-types - - # TODO: fill in the attributes in between - + - + name: nested-devlink + type: nest + multi-attr: true + nested-attributes: dl-nested-devlink - name: selftests type: nest - value: 176 nested-attributes: dl-selftest-id - name: rate-tx-priority @@ -898,7 +899,7 @@ attribute-sets: - name: parent-dev type: nest - nested-attributes: dl-parent-dev + nested-attributes: dl-nested-devlink doc: | Identifies the devlink instance which owns the parent rate node. Used with rate-set and rate-new to parent a rate object to a node on @@ -1330,6 +1331,52 @@ attribute-sets: - name: dl-parent-dev subset-of: devlink + doc: | + Devlink handle accepted as the parent-dev input; the netns id the + kernel reports back is not accepted, the parent is always resolved + in the caller's netns. + attributes: + - + name: bus-name + - + name: dev-name + - + name: index + + - + name: dl-rate-set + subset-of: devlink + doc: Attributes accepted by the rate-set and rate-new requests. + attributes: + - + name: bus-name + - + name: dev-name + - + name: index + - + name: port-index + - + name: rate-node-name + - + name: rate-tx-share + - + name: rate-tx-max + - + name: rate-tx-priority + - + name: rate-tx-weight + - + name: rate-parent-node-name + - + name: rate-tc-bws + - + name: parent-dev + nested-attributes: dl-parent-dev + + - + name: dl-nested-devlink + subset-of: devlink attributes: - name: bus-name @@ -1337,6 +1384,8 @@ attribute-sets: name: dev-name - name: index + - + name: netns-id operations: enum-model: directional @@ -1363,6 +1412,7 @@ operations: - index - reload-failed - dev-stats + - nested-devlink dump: reply: *get-reply @@ -2305,7 +2355,7 @@ operations: - name: rate-set doc: Set rate instances. - attribute-set: devlink + attribute-set: dl-rate-set dont-validate: [strict] flags: [admin-perm] do: @@ -2328,7 +2378,7 @@ operations: - name: rate-new doc: Create rate instances. - attribute-set: devlink + attribute-set: dl-rate-set dont-validate: [strict] flags: [admin-perm] do: diff --git a/Documentation/networking/psp.rst b/Documentation/networking/psp.rst index 4ac09e64e95a..0f9b6b73f244 100644 --- a/Documentation/networking/psp.rst +++ b/Documentation/networking/psp.rst @@ -132,6 +132,14 @@ numbers in a way that deletes a prefix of the PSP protected part of the TCP stream. If userspace cares to mitigate this type of attack, a special "start of PSP" message should be exchanged after ``tx-assoc``. +Upgrade to PSP must be done on established TCP connections. +``rx-assoc`` and ``tx-assoc`` will return ``-ENOTCONN`` if +``sk_state`` is not ``TCP_ESTABLISHED``. + +The PSP assoc state of a socket is not reset when the connection is +torn down. ``connect()`` on a socket that has PSP assoc state will +return ``-EINVAL``. + Rotation notifications ---------------------- diff --git a/Documentation/networking/tls-offload.rst b/Documentation/networking/tls-offload.rst index e5802bcd4d22..cf0e599c06a1 100644 --- a/Documentation/networking/tls-offload.rst +++ b/Documentation/networking/tls-offload.rst @@ -71,12 +71,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/rust/testing.rst b/Documentation/rust/testing.rst index e3943aceceb9..73046523a9a2 100644 --- a/Documentation/rust/testing.rst +++ b/Documentation/rust/testing.rst @@ -97,7 +97,7 @@ operator are also supported as usual, e.g.: /// ``` /// # use kernel::{spawn_work_item, workqueue}; - /// spawn_work_item!(workqueue::system(), || pr_info!("x\n"))?; + /// spawn_work_item!(workqueue::system_dfl(), || pr_info!("x\n"))?; /// # Ok::<(), Error>(()) /// ``` diff --git a/Documentation/trace/histogram.rst b/Documentation/trace/histogram.rst index 340bcb5099e7..97b67f05f5ea 100644 --- a/Documentation/trace/histogram.rst +++ b/Documentation/trace/histogram.rst @@ -1943,6 +1943,9 @@ the ".buckets" modifier and specify a size (in this case groups of 10):: Entries: 16 Dropped: 0 +Keys are 64-bit, so the group holding the largest values is truncated where +that range ends and can be smaller than the size asked for. + To save stacktraces, create a synthetic event with a field of type "unsigned long[]" or even just "long[]". For example, to see how long a task is blocked in an uninterruptible state:: diff --git a/Documentation/translations/zh_CN/rust/testing.rst b/Documentation/translations/zh_CN/rust/testing.rst index 6747d0012991..fdd88fa2fe40 100644 --- a/Documentation/translations/zh_CN/rust/testing.rst +++ b/Documentation/translations/zh_CN/rust/testing.rst @@ -93,7 +93,7 @@ KUnit 测试即文档测试 /// ``` /// # use kernel::{spawn_work_item, workqueue}; - /// spawn_work_item!(workqueue::system(), || pr_info!("x\n"))?; + /// spawn_work_item!(workqueue::system_dfl(), || pr_info!("x\n"))?; /// # Ok::<(), Error>(()) /// ``` diff --git a/Documentation/virt/hyperv/overview.rst b/Documentation/virt/hyperv/overview.rst index 77408a89d1a4..34a53ba7a122 100644 --- a/Documentation/virt/hyperv/overview.rst +++ b/Documentation/virt/hyperv/overview.rst @@ -114,11 +114,13 @@ a shared page or remove an overlay page after the new kernel is using the page for a different purpose, corrupting the new kernel. Hyper-V does not provide a single "set everything" operation to guest VMs, so Linux code must individually revoke all sharing before -doing kexec. See hv_kexec_handler() and hv_crash_handler(). But -the crash/panic path still has holes in cleanup because some shared -pages are set using per-CPU synthetic registers and there's no -mechanism to revoke the shared pages for CPUs other than the CPU -running the panic path. +doing kexec. For a normal kexec reboot, the VMBus driver calls +hv_kexec_handler() from its syscore shutdown callback, after device +shutdown and before the architecture-specific machine shutdown. The +crash/panic path uses hv_crash_handler(), but still has holes in +cleanup because some shared pages are set using per-CPU synthetic +registers and there is no mechanism to revoke the shared pages for +CPUs other than the CPU running the panic path. CPU Management -------------- diff --git a/Makefile b/Makefile index 51e278ccea9c..28ae92d9d760 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ # SPDX-License-Identifier: GPL-2.0 VERSION = 7 PATCHLEVEL = 3 -SUBLEVEL = 5 +SUBLEVEL = 6 EXTRAVERSION = NAME = Baby Opossum Posse @@ -298,6 +298,7 @@ no-dot-config-targets := $(clean-targets) \ %asm-generic kernelversion %src-pkg dt_binding_check \ dt_style_selftest \ outputmakefile rustavailable rustfmt rustfmtcheck \ + usr_gen_init_cpio \ run-command no-sync-config-targets := $(no-dot-config-targets) %install modules_sign kernelrelease \ image_name diff --git a/arch/alpha/Kconfig b/arch/alpha/Kconfig index e53ef2d88463..c9aba0ab96e5 100644 --- a/arch/alpha/Kconfig +++ b/arch/alpha/Kconfig @@ -44,6 +44,7 @@ config ALPHA select MMU_GATHER_NO_RANGE select MMU_GATHER_RCU_TABLE_FREE select SPARSEMEM_EXTREME if SPARSEMEM + select SYSCTL_EXCEPTION_TRACE select ZONE_DMA select TRACE_IRQFLAGS_SUPPORT select ARCH_WANT_FRAME_POINTERS diff --git a/arch/alpha/include/asm/ptrace.h b/arch/alpha/include/asm/ptrace.h index 8e0a589e2d15..14e8b1a2ee02 100644 --- a/arch/alpha/include/asm/ptrace.h +++ b/arch/alpha/include/asm/ptrace.h @@ -24,11 +24,6 @@ static inline unsigned long regs_return_value(struct pt_regs *regs) return regs->r0; } -/* Helpers for working with the user stack pointer */ -static inline unsigned long user_stack_pointer(struct pt_regs *regs) -{ - /* Valid for user-mode regs */ - return regs->usp; -} +unsigned long user_stack_pointer(struct pt_regs *regs); #endif diff --git a/arch/alpha/kernel/ptrace.c b/arch/alpha/kernel/ptrace.c index fc8f6cedbb28..0ba9a2da17ba 100644 --- a/arch/alpha/kernel/ptrace.c +++ b/arch/alpha/kernel/ptrace.c @@ -405,6 +405,18 @@ ptrace_cancel_bpt(struct task_struct * child) return (nsaved != 0); } +/* + * PALcode keeps the user stack pointer in the PCB, not the trap frame. + * A user-mode pt_regs sits at the top of its task's stack, so the + * thread_info is at the base. + */ +unsigned long user_stack_pointer(struct pt_regs *regs) +{ + struct thread_info *ti = (void *)((unsigned long)regs & -THREAD_SIZE); + + return ti == current_thread_info() ? rdusp() : ti->pcb.usp; +} + void user_enable_single_step(struct task_struct *child) { /* Mark single stepping. */ diff --git a/arch/alpha/mm/fault.c b/arch/alpha/mm/fault.c index 53e170e96591..63a24afa7a15 100644 --- a/arch/alpha/mm/fault.c +++ b/arch/alpha/mm/fault.c @@ -28,8 +28,32 @@ #include #include +#include + extern void die_if_kernel(char *,struct pt_regs *,long, unsigned long *); +int show_unhandled_signals = 1; + +static void +show_signal_msg(struct pt_regs *regs, unsigned long address, int signo, + const char *desc) +{ + const char *level; + + if (!show_unhandled_signals || !unhandled_signal(current, signo)) + return; + if (!printk_ratelimit()) + return; + + /* Losing init is fatal, so shout about it. */ + level = task_pid_nr(current) > 1 ? KERN_INFO : KERN_EMERG; + + printk("%s%s[%d]: %s at %016lx pc %016lx sp %016lx\n", + level, current->comm, task_pid_nr(current), desc, + address, regs->pc, rdusp()); + print_vma_addr(KERN_CONT " in ", regs->pc); + printk(KERN_CONT "\n"); +} /* * Force a new ASN for a task. @@ -223,6 +247,8 @@ do_page_fault(unsigned long address, unsigned long mmcsr, mmap_read_unlock(mm); /* Send a sigbus, regardless of whether we were in kernel or user mode. */ + if (user_mode(regs)) + show_signal_msg(regs, address, SIGBUS, "bus error"); force_sig_fault(SIGBUS, BUS_ADRERR, (void __user *) address); if (!user_mode(regs)) goto no_context; @@ -244,6 +270,9 @@ do_page_fault(unsigned long address, unsigned long mmcsr, return; do_sigsegv: + show_signal_msg(regs, address, SIGSEGV, + si_code == SEGV_MAPERR ? "unmapped access" + : "access violation"); force_sig_fault(SIGSEGV, si_code, (void __user *) address); return; diff --git a/arch/arc/Makefile b/arch/arc/Makefile index 868805ffcfea..4ea705a331c7 100644 --- a/arch/arc/Makefile +++ b/arch/arc/Makefile @@ -86,7 +86,14 @@ core-$(CONFIG_ARC_PLAT_TB10X) += arch/arc/plat-tb10x/ core-$(CONFIG_ARC_PLAT_AXS10X) += arch/arc/plat-axs10x/ core-$(CONFIG_ARC_SOC_HSDK) += arch/arc/plat-hsdk/ -libs-y += arch/arc/lib/ $(LIBGCC) +libs-y += arch/arc/lib/ + +ifdef CONFIG_DEBUG_INFO_BTF +export LIBGCC := $(LIBGCC) +libs-y += arch/arc/lib/libgcc.a +else +libs-y += $(LIBGCC) +endif boot := arch/arc/boot 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/arc/lib/Makefile b/arch/arc/lib/Makefile index 30158ae69fd4..2807ee24f27e 100644 --- a/arch/arc/lib/Makefile +++ b/arch/arc/lib/Makefile @@ -13,3 +13,11 @@ lib-$(CONFIG_ISA_ARCV2) +=memcpy-archs-unaligned.o else lib-$(CONFIG_ISA_ARCV2) +=memcpy-archs.o endif + +# libgcc can contain complex floating-point debug types unsupported by BTF. +# Strip only the debug information from a local copy of the selected archive. +always-$(CONFIG_DEBUG_INFO_BTF) += libgcc.a +OBJCOPYFLAGS_libgcc.a := --strip-debug + +$(obj)/libgcc.a: $(LIBGCC) FORCE + $(call if_changed,objcopy) diff --git a/arch/arm/boot/dts/gemini/gemini.dtsi b/arch/arm/boot/dts/gemini/gemini.dtsi index 23e68e17ffbb..d8f64fea0a79 100644 --- a/arch/arm/boot/dts/gemini/gemini.dtsi +++ b/arch/arm/boot/dts/gemini/gemini.dtsi @@ -445,7 +445,7 @@ dma-controller@67000000 { display-controller@6a000000 { compatible = "cortina,gemini-tvc", "faraday,tve200"; reg = <0x6a000000 0x1000>; - interrupts = <13 IRQ_TYPE_EDGE_RISING>; + interrupts = <13 IRQ_TYPE_LEVEL_HIGH>; resets = <&syscon GEMINI_RESET_TVC>; clocks = <&syscon GEMINI_CLK_GATE_TVC>, <&syscon GEMINI_CLK_TVC>; diff --git a/arch/arm/boot/dts/marvell/armada-385-clearfog-gtr.dtsi b/arch/arm/boot/dts/marvell/armada-385-clearfog-gtr.dtsi index 7aa71a9aa1bb..16e9a258876c 100644 --- a/arch/arm/boot/dts/marvell/armada-385-clearfog-gtr.dtsi +++ b/arch/arm/boot/dts/marvell/armada-385-clearfog-gtr.dtsi @@ -235,7 +235,7 @@ sdhci@d8000 { pinctrl-0 = <&cf_gtr_sdhci_pins>; pinctrl-names = "default"; status = "okay"; - vmmc = <®_3p3v>; + vmmc-supply = <®_3p3v>; wp-inverted; }; diff --git a/arch/arm/boot/dts/marvell/armada-388-helios4.dts b/arch/arm/boot/dts/marvell/armada-388-helios4.dts index 003b0708e965..33e30528bc7c 100644 --- a/arch/arm/boot/dts/marvell/armada-388-helios4.dts +++ b/arch/arm/boot/dts/marvell/armada-388-helios4.dts @@ -140,7 +140,7 @@ fan2: j17-pwm { usb2_phy: usb2-phy { compatible = "usb-nop-xceiv"; - vbus-regulator = <®_5p0v_usb>; + vbus-supply = <®_5p0v_usb>; }; usb3_phy: usb3-phy { @@ -200,7 +200,7 @@ usb3-ilimit-hog { temp_sensor: temp@4c { compatible = "ti,lm75"; reg = <0x4c>; - vcc-supply = <®_3p3v>; + vs-supply = <®_3p3v>; }; eeprom@53 { @@ -254,13 +254,6 @@ sata3: sata-port@1 { }; }; - spi@10680 { - pinctrl-0 = <&spi1_pins - µsom_spi1_cs_pins>; - pinctrl-names = "default"; - status = "okay"; - }; - sdhci@d8000 { bus-width = <4>; cd-gpios = <&gpio0 20 GPIO_ACTIVE_LOW>; @@ -269,7 +262,7 @@ sdhci@d8000 { &helios_sdhci_cd_pins>; pinctrl-names = "default"; status = "okay"; - vmmc = <®_3p3v>; + vmmc-supply = <®_3p3v>; wp-inverted; }; @@ -327,11 +320,13 @@ helios_fan2_pins: helios_fan2_pins { marvell,pins = "mpp48", "mpp55"; marvell,function = "gpio"; }; - microsom_spi1_cs_pins: spi1-cs-pins { - marvell,pins = "mpp59"; - marvell,function = "spi1"; - }; }; }; }; }; + +&spi1 { + pinctrl-0 = <&spi1_pins>; + pinctrl-names = "default"; + status = "okay"; +}; diff --git a/arch/arm/boot/dts/marvell/armada-395-gp.dts b/arch/arm/boot/dts/marvell/armada-395-gp.dts index 6dd9e9077f84..9ea447cd35a8 100644 --- a/arch/arm/boot/dts/marvell/armada-395-gp.dts +++ b/arch/arm/boot/dts/marvell/armada-395-gp.dts @@ -59,7 +59,6 @@ sata@a8000 { /* CON18 */ sdhci@d8000 { - clock-frequency = <200000000>; broken-cd; wp-inverted; bus-width = <8>; diff --git a/arch/arm/boot/dts/nvidia/tegra114-dalmore.dts b/arch/arm/boot/dts/nvidia/tegra114-dalmore.dts index c06b52fe330a..8d97a47c969c 100644 --- a/arch/arm/boot/dts/nvidia/tegra114-dalmore.dts +++ b/arch/arm/boot/dts/nvidia/tegra114-dalmore.dts @@ -969,7 +969,7 @@ smps45 { regulator-boot-on; }; - smps457 { + vdd_core: smps457 { regulator-name = "vdd-core"; regulator-min-microvolt = <900000>; regulator-max-microvolt = <1400000>; @@ -1095,6 +1095,8 @@ flash@0 { }; pmc@7000e400 { + core-supply = <&vdd_core>; + nvidia,invert-interrupt; nvidia,suspend-mode = <1>; nvidia,cpu-pwr-good-time = <500>; diff --git a/arch/arm/boot/dts/nvidia/tegra114-roth.dts b/arch/arm/boot/dts/nvidia/tegra114-roth.dts index a89b16573b42..f48d5c37e848 100644 --- a/arch/arm/boot/dts/nvidia/tegra114-roth.dts +++ b/arch/arm/boot/dts/nvidia/tegra114-roth.dts @@ -837,7 +837,7 @@ vdd_1v8: smps3 { regulator-boot-on; }; - smps457 { + vdd_core: smps457 { regulator-name = "vdd-soc"; regulator-min-microvolt = <900000>; regulator-max-microvolt = <1400000>; @@ -960,6 +960,8 @@ rtc { }; pmc@7000e400 { + core-supply = <&vdd_core>; + nvidia,invert-interrupt; }; diff --git a/arch/arm/boot/dts/nvidia/tegra114-tn7.dts b/arch/arm/boot/dts/nvidia/tegra114-tn7.dts index 75fbafb4a872..4b1e47364fdb 100644 --- a/arch/arm/boot/dts/nvidia/tegra114-tn7.dts +++ b/arch/arm/boot/dts/nvidia/tegra114-tn7.dts @@ -95,7 +95,7 @@ smps123 { regulator-boot-on; }; - smps45 { + vdd_core: smps45 { regulator-name = "vd-soc"; regulator-min-microvolt = <1100000>; regulator-max-microvolt = <1100000>; @@ -241,6 +241,8 @@ rtc { }; pmc@7000e400 { + core-supply = <&vdd_core>; + nvidia,invert-interrupt; }; diff --git a/arch/arm/boot/dts/nxp/imx/imx7-tqma7.dtsi b/arch/arm/boot/dts/nxp/imx/imx7-tqma7.dtsi index e1f740edfb76..7f49c80fef4c 100644 --- a/arch/arm/boot/dts/nxp/imx/imx7-tqma7.dtsi +++ b/arch/arm/boot/dts/nxp/imx/imx7-tqma7.dtsi @@ -46,8 +46,8 @@ pfuze3000: pmic@8 { regulators { sw1a_reg: sw1a { - regulator-min-microvolt = <700000>; - regulator-max-microvolt = <3300000>; + regulator-min-microvolt = <1000000>; + regulator-max-microvolt = <1225000>; regulator-boot-on; regulator-always-on; regulator-ramp-delay = <6250>; @@ -55,34 +55,33 @@ sw1a_reg: sw1a { /* use sw1c_reg to align with pfuze100/pfuze200 */ sw1c_reg: sw1b { - regulator-min-microvolt = <700000>; - regulator-max-microvolt = <1475000>; + regulator-min-microvolt = <1000000>; + regulator-max-microvolt = <1000000>; regulator-boot-on; regulator-always-on; regulator-ramp-delay = <6250>; }; sw2_reg: sw2 { - regulator-min-microvolt = <1500000>; - regulator-max-microvolt = <1850000>; + regulator-min-microvolt = <1800000>; + regulator-max-microvolt = <1800000>; regulator-boot-on; regulator-always-on; }; sw3a_reg: sw3 { - regulator-min-microvolt = <900000>; - regulator-max-microvolt = <1650000>; + regulator-min-microvolt = <1350000>; + regulator-max-microvolt = <1350000>; regulator-boot-on; regulator-always-on; }; swbst_reg: swbst { - regulator-min-microvolt = <5000000>; - regulator-max-microvolt = <5150000>; + /* Not connected and left unconfigured */ }; snvs_reg: vsnvs { - regulator-min-microvolt = <1000000>; + regulator-min-microvolt = <3000000>; regulator-max-microvolt = <3000000>; regulator-boot-on; regulator-always-on; @@ -95,18 +94,25 @@ vref_reg: vrefddr { vgen1_reg: vldo1 { regulator-min-microvolt = <1800000>; - regulator-max-microvolt = <3300000>; + regulator-max-microvolt = <1800000>; regulator-always-on; }; vgen2_reg: vldo2 { - regulator-min-microvolt = <800000>; - regulator-max-microvolt = <1550000>; + regulator-min-microvolt = <1500000>; + regulator-max-microvolt = <1500000>; regulator-always-on; }; vgen3_reg: vccsd { - regulator-min-microvolt = <2850000>; + /* + * Specified values refer to 3.3V operation; voltage for 1.8V + * operation is derived from this. + * + * The base board should usually mux GPIO1_IO08 to SD1_VSELECT for + * automatic switching of SD card IO voltage. + */ + regulator-min-microvolt = <3300000>; regulator-max-microvolt = <3300000>; regulator-always-on; }; @@ -118,13 +124,13 @@ vgen4_reg: v33 { }; vgen5_reg: vldo3 { - regulator-min-microvolt = <1800000>; + regulator-min-microvolt = <3300000>; regulator-max-microvolt = <3300000>; regulator-always-on; }; vgen6_reg: vldo4 { - regulator-min-microvolt = <1800000>; + regulator-min-microvolt = <3300000>; regulator-max-microvolt = <3300000>; regulator-always-on; }; diff --git a/arch/arm/boot/dts/qcom/qcom-msm8974.dtsi b/arch/arm/boot/dts/qcom/qcom-msm8974.dtsi index 06c0af0aa317..f300de74c47d 100644 --- a/arch/arm/boot/dts/qcom/qcom-msm8974.dtsi +++ b/arch/arm/boot/dts/qcom/qcom-msm8974.dtsi @@ -10,6 +10,7 @@ #include #include #include +#include / { #address-cells = <1>; @@ -1935,6 +1936,8 @@ mdss: display-subsystem@fd900000 { interrupt-controller; #interrupt-cells = <1>; + resets = <&mmcc MDSS_RESET>; + status = "disabled"; #address-cells = <1>; diff --git a/arch/arm/boot/dts/st/ste-ab8500.dtsi b/arch/arm/boot/dts/st/ste-ab8500.dtsi index dd30d08ccb9b..a55f365ea020 100644 --- a/arch/arm/boot/dts/st/ste-ab8500.dtsi +++ b/arch/arm/boot/dts/st/ste-ab8500.dtsi @@ -364,12 +364,6 @@ ab8500_ldo_ana_reg: ab8500_ldo_ana { }; }; - sound { - stericsson,audio-codec = <&codec>; - clocks = <&prcmu_clk PRCMU_SYSCLK>, <&ab8500_clock AB8500_SYSCLK_ULP>, <&ab8500_clock AB8500_SYSCLK_INT>; - clock-names = "sysclk", "ulpclk", "intclk"; - }; - mcde@a0350000 { vana-supply = <&ab8500_ldo_ana_reg>; diff --git a/arch/arm/boot/dts/st/ste-ab8505.dtsi b/arch/arm/boot/dts/st/ste-ab8505.dtsi index 131c82508e82..434251f36ff6 100644 --- a/arch/arm/boot/dts/st/ste-ab8505.dtsi +++ b/arch/arm/boot/dts/st/ste-ab8505.dtsi @@ -137,13 +137,9 @@ ab8500_btemp { }; ab8500_charger { - compatible = "stericsson,ab8500-charger"; - interrupts = <10 IRQ_TYPE_LEVEL_HIGH>, - <11 IRQ_TYPE_LEVEL_HIGH>, - <0 IRQ_TYPE_LEVEL_HIGH>, - <107 IRQ_TYPE_LEVEL_HIGH>, - <106 IRQ_TYPE_LEVEL_HIGH>, - <14 IRQ_TYPE_LEVEL_HIGH>, + compatible = "stericsson,ab8505-charger", + "stericsson,ab8500-charger"; + interrupts = <14 IRQ_TYPE_LEVEL_HIGH>, <15 IRQ_TYPE_LEVEL_HIGH>, <79 IRQ_TYPE_LEVEL_HIGH>, <105 IRQ_TYPE_LEVEL_HIGH>, @@ -152,12 +148,7 @@ ab8500_charger { <22 IRQ_TYPE_LEVEL_HIGH>, <21 IRQ_TYPE_LEVEL_HIGH>, <16 IRQ_TYPE_LEVEL_HIGH>; - interrupt-names = "MAIN_CH_UNPLUG_DET", - "MAIN_CHARGE_PLUG_DET", - "MAIN_EXT_CH_NOT_OK", - "MAIN_CH_TH_PROT_R", - "MAIN_CH_TH_PROT_F", - "VBUS_DET_F", + interrupt-names = "VBUS_DET_F", "VBUS_DET_R", "USB_LINK_STATUS", "USB_CH_TH_PROT_R", @@ -301,12 +292,6 @@ ab8500_ldo_ana_reg: ab8500_ldo_ana { }; }; - sound { - stericsson,audio-codec = <&codec>; - clocks = <&prcmu_clk PRCMU_SYSCLK>, <&ab8500_clock AB8500_SYSCLK_ULP>, <&ab8500_clock AB8500_SYSCLK_INT>; - clock-names = "sysclk", "ulpclk", "intclk"; - }; - mcde@a0350000 { vana-supply = <&ab8500_ldo_ana_reg>; diff --git a/arch/arm/boot/dts/st/ste-dbx5x0.dtsi b/arch/arm/boot/dts/st/ste-dbx5x0.dtsi index 25a20fafc6b9..32ef115a243c 100644 --- a/arch/arm/boot/dts/st/ste-dbx5x0.dtsi +++ b/arch/arm/boot/dts/st/ste-dbx5x0.dtsi @@ -1071,11 +1071,6 @@ mmc@80008000 { status = "disabled"; }; - sound { - compatible = "stericsson,snd-soc-mop500"; - stericsson,cpu-dai = <&msp1 &msp3>; - }; - msp0: msp@80123000 { compatible = "stericsson,ux500-msp-i2s"; reg = <0x80123000 0x1000>; diff --git a/arch/arm/boot/dts/st/ste-href-ab8500.dtsi b/arch/arm/boot/dts/st/ste-href-ab8500.dtsi index 5eeb44c5e932..ff72f5f6d652 100644 --- a/arch/arm/boot/dts/st/ste-href-ab8500.dtsi +++ b/arch/arm/boot/dts/st/ste-href-ab8500.dtsi @@ -6,6 +6,48 @@ #include "ste-ab8500.dtsi" / { + href_sound: sound { + compatible = "audio-graph-card2"; + label = "HREF-500"; + widgets = + "Headphone", "Headset", + "Speaker", "Earpiece Speaker", + "Speaker", "Loudspeaker", + "Line", "Line Out", + "Speaker", "Vibra 1 Motor", + "Speaker", "Vibra 2 Motor", + "Microphone", "Mic 1 Jack", + "Microphone", "Mic 2 Jack", + "Line", "Line In", + "Microphone", "Digital Mic 1", + "Microphone", "Digital Mic 2", + "Microphone", "Digital Mic 3", + "Microphone", "Digital Mic 4", + "Microphone", "Digital Mic 5", + "Microphone", "Digital Mic 6"; + routing = + "Headset", "Headset Left", + "Headset", "Headset Right", + "Earpiece Speaker", "Earpiece", + "Loudspeaker", "Speaker Left", + "Loudspeaker", "Speaker Right", + "Line Out", "LineOut Left", + "Line Out", "LineOut Right", + "Vibra 1 Motor", "Vibra 1", + "Vibra 2 Motor", "Vibra 2", + "Mic 1", "Mic 1 Jack", + "Mic 2", "Mic 2 Jack", + "LineIn Left", "Line In", + "LineIn Right", "Line In", + "DMic 1", "Digital Mic 1", + "DMic 2", "Digital Mic 2", + "DMic 3", "Digital Mic 3", + "DMic 4", "Digital Mic 4", + "DMic 5", "Digital Mic 5", + "DMic 6", "Digital Mic 6"; + links = <&href_msp1_port &href_msp3_port>; + }; + soc { prcmu@80157000 { ab8500 { @@ -488,3 +530,65 @@ ab8500_chargalg { }; }; }; + +&codec { + assigned-clocks = <&ab8500_clock AB8500_SYSCLK_INT>; + assigned-clock-parents = <&ab8500_clock AB8500_SYSCLK_ULP>; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + + href_codec_playback: endpoint { + remote-endpoint = <&href_msp1_endpoint>; + bitclock-master; + frame-master; + dai-tdm-slot-num = <16>; + dai-tdm-slot-width = <16>; + dai-tdm-slot-tx-mask = <0 1 0 1>; + }; + }; + + port@1 { + reg = <1>; + + href_codec_capture: endpoint { + remote-endpoint = <&href_msp3_endpoint>; + bitclock-master; + frame-master; + dai-tdm-slot-num = <16>; + dai-tdm-slot-width = <16>; + dai-tdm-slot-rx-mask = <1>; + }; + }; + }; +}; + +&msp1 { + href_msp1_port: port { + href_msp1_endpoint: endpoint { + continuous-clock; + remote-endpoint = <&href_codec_playback>; + dai-format = "dsp_a"; + dai-tdm-slot-num = <16>; + dai-tdm-slot-width = <16>; + dai-tdm-slot-tx-mask = <0 1 0 1>; + }; + }; +}; + +&msp3 { + href_msp3_port: port { + href_msp3_endpoint: endpoint { + continuous-clock; + remote-endpoint = <&href_codec_capture>; + dai-format = "dsp_a"; + dai-tdm-slot-num = <16>; + dai-tdm-slot-width = <16>; + dai-tdm-slot-rx-mask = <1>; + }; + }; +}; diff --git a/arch/arm/boot/dts/st/ste-href-ab8505.dtsi b/arch/arm/boot/dts/st/ste-href-ab8505.dtsi index 268db68ccf87..eba6f674c691 100644 --- a/arch/arm/boot/dts/st/ste-href-ab8505.dtsi +++ b/arch/arm/boot/dts/st/ste-href-ab8505.dtsi @@ -6,6 +6,36 @@ #include "ste-ab8505.dtsi" / { + href_sound: sound { + compatible = "audio-graph-card2"; + label = "HREF-500"; + widgets = + "Headphone", "Headset", + "Speaker", "Earpiece Speaker", + "Speaker", "Loudspeaker", + "Line", "Line Out", + "Speaker", "Vibra 1 Motor", + "Speaker", "Vibra 2 Motor", + "Microphone", "Mic 1 Jack", + "Microphone", "Mic 2 Jack", + "Line", "Line In"; + routing = + "Headset", "Headset Left", + "Headset", "Headset Right", + "Earpiece Speaker", "Earpiece", + "Loudspeaker", "Speaker Left", + "Loudspeaker", "Speaker Right", + "Line Out", "LineOut Left", + "Line Out", "LineOut Right", + "Vibra 1 Motor", "Vibra 1", + "Vibra 2 Motor", "Vibra 2", + "Mic 1", "Mic 1 Jack", + "Mic 2", "Mic 2 Jack", + "LineIn Left", "Line In", + "LineIn Right", "Line In"; + links = <&href_msp1_port &href_msp3_port>; + }; + soc { prcmu@80157000 { ab8505 { @@ -48,10 +78,6 @@ ab8500_ldo_anamic2_reg: ab8500_ldo_anamic2 { regulator-name = "V-AMIC2"; }; - ab8500_ldo_dmic_reg: ab8500_ldo_dmic { - regulator-name = "V-DMIC"; - }; - ab8500_ldo_ana_reg: ab8500_ldo_ana { regulator-name = "V-CSI/DSI"; }; @@ -80,7 +106,6 @@ gpio { <&pwm_default_mode>, <&adi1_default_mode>, <&usbuicc_default_mode>, - <&dmic_default_mode>, <&extcpena_default_mode>, <&modsclsda_default_mode>; @@ -365,27 +390,6 @@ default_cfg { }; }; }; - /* This sets up the microphone pins */ - dmic { - dmic_default_mode: dmic_default { - default_mux { - function = "dmic"; - groups = "dmic12_d_1", - "dmic34_d_1", - "dmic56_d_1"; - }; - default_cfg { - pins = "GPIO27_J6", - "GPIO28_K6", - "GPIO29_G6", - "GPIO30_H6", - "GPIO31_F5", - "GPIO32_G5"; - input-enable; - bias-pull-down; - }; - }; - }; extcpena { extcpena_default_mode: extcpena_default { default_mux { @@ -488,3 +492,65 @@ ab8500_chargalg { }; }; }; + +&codec { + assigned-clocks = <&ab8500_clock AB8500_SYSCLK_INT>; + assigned-clock-parents = <&ab8500_clock AB8500_SYSCLK_ULP>; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + + href_codec_playback: endpoint { + remote-endpoint = <&href_msp1_endpoint>; + bitclock-master; + frame-master; + dai-tdm-slot-num = <16>; + dai-tdm-slot-width = <16>; + dai-tdm-slot-tx-mask = <0 1 0 1>; + }; + }; + + port@1 { + reg = <1>; + + href_codec_capture: endpoint { + remote-endpoint = <&href_msp3_endpoint>; + bitclock-master; + frame-master; + dai-tdm-slot-num = <16>; + dai-tdm-slot-width = <16>; + dai-tdm-slot-rx-mask = <1>; + }; + }; + }; +}; + +&msp1 { + href_msp1_port: port { + href_msp1_endpoint: endpoint { + continuous-clock; + remote-endpoint = <&href_codec_playback>; + dai-format = "dsp_a"; + dai-tdm-slot-num = <16>; + dai-tdm-slot-width = <16>; + dai-tdm-slot-tx-mask = <0 1 0 1>; + }; + }; +}; + +&msp3 { + href_msp3_port: port { + href_msp3_endpoint: endpoint { + continuous-clock; + remote-endpoint = <&href_codec_capture>; + dai-format = "dsp_a"; + dai-tdm-slot-num = <16>; + dai-tdm-slot-width = <16>; + dai-tdm-slot-rx-mask = <1>; + }; + }; +}; diff --git a/arch/arm/boot/dts/st/stm32mp135.dtsi b/arch/arm/boot/dts/st/stm32mp135.dtsi index 834a4d545fe4..f573335edf6b 100644 --- a/arch/arm/boot/dts/st/stm32mp135.dtsi +++ b/arch/arm/boot/dts/st/stm32mp135.dtsi @@ -6,29 +6,29 @@ #include "stm32mp133.dtsi" -/ { - soc { - dcmipp: dcmipp@5a000000 { - compatible = "st,stm32mp13-dcmipp"; - reg = <0x5a000000 0x400>; - interrupts = ; - resets = <&rcc DCMIPP_R>; - clocks = <&rcc DCMIPP_K>; - status = "disabled"; +&etzpc { + dcmipp: dcmipp@5a000000 { + compatible = "st,stm32mp13-dcmipp"; + reg = <0x5a000000 0x400>; + interrupts = ; + resets = <&rcc DCMIPP_R>; + clocks = <&rcc DCMIPP_K>; + access-controllers = <&etzpc 4>; + status = "disabled"; - port { - }; + port { }; + }; - ltdc: display-controller@5a001000 { - compatible = "st,stm32-ltdc"; - reg = <0x5a001000 0x400>; - interrupts = , - ; - clocks = <&rcc LTDC_PX>; - clock-names = "lcd"; - resets = <&scmi_reset RST_SCMI_LTDC>; - status = "disabled"; - }; + ltdc: display-controller@5a001000 { + compatible = "st,stm32-ltdc"; + reg = <0x5a001000 0x400>; + interrupts = , + ; + clocks = <&rcc LTDC_PX>; + clock-names = "lcd"; + resets = <&scmi_reset RST_SCMI_LTDC>; + access-controllers = <&etzpc 3>; + status = "disabled"; }; }; diff --git a/arch/arm/boot/dts/st/stm32mp135f-dk.dts b/arch/arm/boot/dts/st/stm32mp135f-dk.dts index 1d6435c59096..bd5d6818d7ba 100644 --- a/arch/arm/boot/dts/st/stm32mp135f-dk.dts +++ b/arch/arm/boot/dts/st/stm32mp135f-dk.dts @@ -628,6 +628,7 @@ hub@1 { compatible = "usb424,2514"; reg = <1>; vdd-supply = <&scmi_v3v3_sw>; + vdda-supply = <&scmi_v3v3_sw>; }; }; diff --git a/arch/arm/boot/dts/st/stm32mp153c-lxa-fairytux2.dtsi b/arch/arm/boot/dts/st/stm32mp153c-lxa-fairytux2.dtsi index 7d3a6a3b5d09..d30b626a18c2 100644 --- a/arch/arm/boot/dts/st/stm32mp153c-lxa-fairytux2.dtsi +++ b/arch/arm/boot/dts/st/stm32mp153c-lxa-fairytux2.dtsi @@ -28,7 +28,7 @@ aliases { }; chosen { - stdout-path = &uart4; + stdout-path = "serial0:115200n8"; }; backlight: backlight { diff --git a/arch/arm/boot/dts/st/stm32mp157c-ev1.dts b/arch/arm/boot/dts/st/stm32mp157c-ev1.dts index 0e65a1862eb5..ce014561a8ac 100644 --- a/arch/arm/boot/dts/st/stm32mp157c-ev1.dts +++ b/arch/arm/boot/dts/st/stm32mp157c-ev1.dts @@ -439,6 +439,7 @@ hub@1 { compatible = "usb424,2514"; reg = <1>; vdd-supply = <&v3v3>; + vdda-supply = <&v3v3>; }; }; diff --git a/arch/arm/boot/dts/st/stm32mp157c-lxa-mc1.dts b/arch/arm/boot/dts/st/stm32mp157c-lxa-mc1.dts index eada9cf257be..b3d8eb57aa24 100644 --- a/arch/arm/boot/dts/st/stm32mp157c-lxa-mc1.dts +++ b/arch/arm/boot/dts/st/stm32mp157c-lxa-mc1.dts @@ -33,7 +33,7 @@ backlight: backlight { }; chosen { - stdout-path = &uart4; + stdout-path = "serial0:115200n8"; }; led-controller-0 { diff --git a/arch/arm/boot/dts/st/stm32mp157f-dk2-scmi.dtsi b/arch/arm/boot/dts/st/stm32mp157f-dk2-scmi.dtsi index 89de85a2eff3..172347769e02 100644 --- a/arch/arm/boot/dts/st/stm32mp157f-dk2-scmi.dtsi +++ b/arch/arm/boot/dts/st/stm32mp157f-dk2-scmi.dtsi @@ -180,6 +180,7 @@ &sdmmc3 { &usbh_ehci { hub@1 { vdd-supply = <&scmi_v3v3>; + vdda-supply = <&scmi_v3v3>; }; }; diff --git a/arch/arm/boot/dts/st/stm32mp15xc-lxa-tac.dtsi b/arch/arm/boot/dts/st/stm32mp15xc-lxa-tac.dtsi index ab13f0c39892..ddb1657cd785 100644 --- a/arch/arm/boot/dts/st/stm32mp15xc-lxa-tac.dtsi +++ b/arch/arm/boot/dts/st/stm32mp15xc-lxa-tac.dtsi @@ -33,7 +33,7 @@ aliases { }; chosen { - stdout-path = &uart4; + stdout-path = "serial0:115200n8"; }; led-controller-0 { diff --git a/arch/arm/boot/dts/st/stm32mp15xx-dhcom-som.dtsi b/arch/arm/boot/dts/st/stm32mp15xx-dhcom-som.dtsi index 4cc633683c6b..0a4263e6209d 100644 --- a/arch/arm/boot/dts/st/stm32mp15xx-dhcom-som.dtsi +++ b/arch/arm/boot/dts/st/stm32mp15xx-dhcom-som.dtsi @@ -505,9 +505,11 @@ &sdmmc1_b4_pins_a { * - mandatory on SoMs without SD voltage translator */ pins1 { + /delete-property/ bias-disable; bias-pull-up; }; pins2 { + /delete-property/ bias-disable; bias-pull-up; }; }; diff --git a/arch/arm/boot/dts/st/stm32mp15xx-dkx.dtsi b/arch/arm/boot/dts/st/stm32mp15xx-dkx.dtsi index 599ea07bdb19..01ac3d7d6d0e 100644 --- a/arch/arm/boot/dts/st/stm32mp15xx-dkx.dtsi +++ b/arch/arm/boot/dts/st/stm32mp15xx-dkx.dtsi @@ -764,6 +764,7 @@ hub@1 { compatible = "usb424,2514"; reg = <1>; vdd-supply = <&v3v3>; + vdda-supply = <&v3v3>; }; }; diff --git a/arch/arm/include/asm/domain.h b/arch/arm/include/asm/domain.h index d48859fdf32c..f91c2a72b9dc 100644 --- a/arch/arm/include/asm/domain.h +++ b/arch/arm/include/asm/domain.h @@ -18,27 +18,10 @@ * DOMAIN_IO - domain 2 includes all IO only * DOMAIN_USER - domain 1 includes all user memory only * DOMAIN_KERNEL - domain 0 includes all kernel memory only - * - * The domain numbering depends on whether we support 36 physical - * address for I/O or not. Addresses above the 32 bit boundary can - * only be mapped using supersections and supersections can only - * be set for domain 0. We could just default to DOMAIN_IO as zero, - * but there may be systems with supersection support and no 36-bit - * addressing. In such cases, we want to map system memory with - * supersections to reduce TLB misses and footprint. - * - * 36-bit addressing and supersections are only available on - * CPUs based on ARMv6+ or the Intel XSC3 core. */ -#ifndef CONFIG_IO_36 #define DOMAIN_KERNEL 0 #define DOMAIN_USER 1 #define DOMAIN_IO 2 -#else -#define DOMAIN_KERNEL 2 -#define DOMAIN_USER 1 -#define DOMAIN_IO 0 -#endif #define DOMAIN_VECTORS 3 /* diff --git a/arch/arm/include/asm/memory.h b/arch/arm/include/asm/memory.h index 7c2fa7dcec6d..e25749bfbf90 100644 --- a/arch/arm/include/asm/memory.h +++ b/arch/arm/include/asm/memory.h @@ -89,9 +89,9 @@ #if !defined(CONFIG_SMP) && !defined(CONFIG_ARM_LPAE) /* - * Allow 16MB-aligned ioremap pages + * Allow 2MB-aligned ioremap pages */ -#define IOREMAP_MAX_ORDER 24 +#define IOREMAP_MAX_ORDER 21 #endif #define VECTORS_BASE UL(0xffff0000) diff --git a/arch/arm/include/asm/pgtable-2level-hwdef.h b/arch/arm/include/asm/pgtable-2level-hwdef.h index 556937e1790e..3fa254ac8a26 100644 --- a/arch/arm/include/asm/pgtable-2level-hwdef.h +++ b/arch/arm/include/asm/pgtable-2level-hwdef.h @@ -35,7 +35,6 @@ #define PMD_SECT_APX (_AT(pmdval_t, 1) << 15) /* v6 */ #define PMD_SECT_S (_AT(pmdval_t, 1) << 16) /* v6 */ #define PMD_SECT_nG (_AT(pmdval_t, 1) << 17) /* v6 */ -#define PMD_SECT_SUPER (_AT(pmdval_t, 1) << 18) /* v6 */ #define PMD_SECT_AF (_AT(pmdval_t, 0)) #define PMD_SECT_UNCACHED (_AT(pmdval_t, 0)) diff --git a/arch/arm/include/asm/pgtable-2level.h b/arch/arm/include/asm/pgtable-2level.h index 6b5392e20f41..7e1c08fdd029 100644 --- a/arch/arm/include/asm/pgtable-2level.h +++ b/arch/arm/include/asm/pgtable-2level.h @@ -96,13 +96,6 @@ #define SECTION_SIZE (1UL << SECTION_SHIFT) #define SECTION_MASK (~(SECTION_SIZE-1)) -/* - * ARMv6 supersection address mask and size definitions. - */ -#define SUPERSECTION_SHIFT 24 -#define SUPERSECTION_SIZE (1UL << SUPERSECTION_SHIFT) -#define SUPERSECTION_MASK (~(SUPERSECTION_SIZE-1)) - #define USER_PTRS_PER_PGD (TASK_SIZE / PGDIR_SIZE) /* diff --git a/arch/arm/include/asm/sparsemem.h b/arch/arm/include/asm/sparsemem.h index 421e3415338a..6b512be3a34a 100644 --- a/arch/arm/include/asm/sparsemem.h +++ b/arch/arm/include/asm/sparsemem.h @@ -19,7 +19,11 @@ * These can be overridden in your mach/memory.h. */ #if !defined(MAX_PHYSMEM_BITS) || !defined(SECTION_SIZE_BITS) +#ifdef CONFIG_ARM_LPAE #define MAX_PHYSMEM_BITS 36 +#else +#define MAX_PHYSMEM_BITS 32 +#endif #define SECTION_SIZE_BITS 28 #endif diff --git a/arch/arm/kernel/efi.c b/arch/arm/kernel/efi.c index 6f9ec7d28a71..c14275257a8a 100644 --- a/arch/arm/kernel/efi.c +++ b/arch/arm/kernel/efi.c @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -54,6 +55,18 @@ int __init efi_create_mapping(struct mm_struct *mm, efi_memory_desc_t *md) .length = md->num_pages * EFI_PAGE_SIZE, }; + /* + * Non-LPAE page tables cannot map EFI runtime regions extending + * beyond the 32-bit physical address space. + */ + if (!IS_ENABLED(CONFIG_ARM_LPAE) && + (md->phys_addr >= SZ_4G || + md->num_pages > (SZ_4G - md->phys_addr) / EFI_PAGE_SIZE)) { + pr_warn("EFI runtime region at 0x%llx exceeds 32-bit physical address space\n", + md->phys_addr); + return -ERANGE; + } + /* * Order is important here: memory regions may have all of the * bits below set (and usually do), so we check them in order of diff --git a/arch/arm/mach-mvebu/Kconfig b/arch/arm/mach-mvebu/Kconfig index 9f60a6fe0eaf..5203b5cfa457 100644 --- a/arch/arm/mach-mvebu/Kconfig +++ b/arch/arm/mach-mvebu/Kconfig @@ -55,7 +55,9 @@ config MACH_ARMADA_375 config MACH_ARMADA_38X bool "Marvell Armada 380/385 boards" depends on ARCH_MULTI_V7 - select ARM_ERRATA_720789 + select ARM_ERRATA_754322 + select ARM_ERRATA_764319 + select ARM_ERRATA_764369 if SMP select PL310_ERRATA_753970 select ARM_GIC select ARM_GLOBAL_TIMER diff --git a/arch/arm/mach-versatile/platsmp-vexpress.c b/arch/arm/mach-versatile/platsmp-vexpress.c index 1ee3c45e71c9..b810ad50b98c 100644 --- a/arch/arm/mach-versatile/platsmp-vexpress.c +++ b/arch/arm/mach-versatile/platsmp-vexpress.c @@ -61,8 +61,8 @@ static const struct of_device_id vexpress_smp_dt_scu_match[] __initconst = { static void __init vexpress_smp_dt_prepare_cpus(unsigned int max_cpus) { - struct device_node *scu = of_find_matching_node(NULL, - vexpress_smp_dt_scu_match); + struct device_node *scu __free(device_node) = + of_find_matching_node(NULL, vexpress_smp_dt_scu_match); if (scu) scu_enable(of_iomap(scu, 0)); diff --git a/arch/arm/mach-versatile/v2m.c b/arch/arm/mach-versatile/v2m.c index 79afdf2a90b6..c86b38386cf7 100644 --- a/arch/arm/mach-versatile/v2m.c +++ b/arch/arm/mach-versatile/v2m.c @@ -13,8 +13,8 @@ void vexpress_flags_set(u32 data) static void __iomem *base; if (!base) { - struct device_node *node = of_find_compatible_node(NULL, NULL, - "arm,vexpress-sysreg"); + struct device_node *node __free(device_node) = + of_find_compatible_node(NULL, NULL, "arm,vexpress-sysreg"); base = of_iomap(node, 0); } diff --git a/arch/arm/mm/Kconfig b/arch/arm/mm/Kconfig index 6574659dfb61..41d7b495ec45 100644 --- a/arch/arm/mm/Kconfig +++ b/arch/arm/mm/Kconfig @@ -328,7 +328,6 @@ config CPU_XSC3 select CPU_PABRT_LEGACY select CPU_THUMB_CAPABLE select CPU_TLB_V4WBI if MMU - select IO_36 # Marvell PJ1 (Mohawk) config CPU_MOHAWK @@ -676,12 +675,6 @@ config CPU_V7M_NUM_IRQ If unsure, keep default value. -# -# CPU supports 36-bit I/O -# -config IO_36 - bool - comment "Processor Features" config ARM_LPAE diff --git a/arch/arm/mm/alignment.c b/arch/arm/mm/alignment.c index 2b470a419dda..f6c1e6b61179 100644 --- a/arch/arm/mm/alignment.c +++ b/arch/arm/mm/alignment.c @@ -915,11 +915,17 @@ do_alignment(unsigned long addr, unsigned int fsr, struct pt_regs *regs) break; case SHIFT_LSR: - offset.un >>= shiftval; + if (shiftval == 0) + offset.un = 0; + else + offset.un >>= shiftval; break; case SHIFT_ASR: - offset.sn >>= shiftval; + if (shiftval == 0) + offset.sn >>= 31; + else + offset.sn >>= shiftval; break; case SHIFT_RORRRX: diff --git a/arch/arm/mm/dma-mapping.c b/arch/arm/mm/dma-mapping.c index 7761099dde9e..fb2eb0ed7bb8 100644 --- a/arch/arm/mm/dma-mapping.c +++ b/arch/arm/mm/dma-mapping.c @@ -1056,7 +1056,10 @@ static void *__iommu_alloc_simple(struct device *dev, size_t size, gfp_t gfp, return addr; err_mapping: - __free_from_pool(addr, size); + if (coherent_flag == COHERENT) + __dma_free_buffer(virt_to_page(addr), size); + else + __free_from_pool(addr, size); return NULL; } diff --git a/arch/arm/mm/ioremap.c b/arch/arm/mm/ioremap.c index 27e64f782cb3..539b6c2995af 100644 --- a/arch/arm/mm/ioremap.c +++ b/arch/arm/mm/ioremap.c @@ -30,8 +30,6 @@ #include #include -#include -#include #include #include #include @@ -236,39 +234,6 @@ remap_area_sections(unsigned long virt, unsigned long pfn, return 0; } -static int -remap_area_supersections(unsigned long virt, unsigned long pfn, - size_t size, const struct mem_type *type) -{ - unsigned long addr = virt, end = virt + size; - pmd_t *pmd = pmd_off_k(addr); - - /* - * Remove and free any PTE-based mapping, and - * sync the current kernel mapping. - */ - unmap_area_sections(virt, size); - do { - unsigned long super_pmd_val, i; - - super_pmd_val = __pfn_to_phys(pfn) | type->prot_sect | - PMD_SECT_SUPER; - super_pmd_val |= ((pfn >> (32 - PAGE_SHIFT)) & 0xf) << 20; - - for (i = 0; i < 8; i++) { - pmd[0] = __pmd(super_pmd_val); - pmd[1] = __pmd(super_pmd_val); - flush_pmd_entry(pmd); - - addr += PMD_SIZE; - pmd += 2; - } - - pfn += SUPERSECTION_SIZE >> PAGE_SHIFT; - } while (addr < end); - - return 0; -} #endif static void __iomem * __arm_ioremap_pfn_caller(unsigned long pfn, @@ -278,15 +243,17 @@ static void __iomem * __arm_ioremap_pfn_caller(unsigned long pfn, int err; unsigned long addr; struct vm_struct *area; - phys_addr_t paddr = __pfn_to_phys(pfn); + phys_addr_t paddr; #ifndef CONFIG_ARM_LPAE /* - * High mappings must be supersection aligned + * The physical range must not extend beyond the 32-bit + * phys_addr_t */ - if (pfn >= 0x100000 && (paddr & ~SUPERSECTION_MASK)) + if (((u64)pfn << PAGE_SHIFT) + offset + size > SZ_4G) return NULL; #endif + paddr = __pfn_to_phys(pfn); type = get_mem_type(mtype); if (!type) @@ -300,7 +267,7 @@ static void __iomem * __arm_ioremap_pfn_caller(unsigned long pfn, /* * Try to reuse one of the static mapping whenever possible. */ - if (size && !(sizeof(phys_addr_t) == 4 && pfn >= 0x100000)) { + if (size) { struct static_vm *svm; svm = find_static_vm_paddr(paddr, size, mtype); @@ -326,13 +293,7 @@ static void __iomem * __arm_ioremap_pfn_caller(unsigned long pfn, area->phys_addr = paddr; #if !defined(CONFIG_SMP) && !defined(CONFIG_ARM_LPAE) - if (DOMAIN_IO == 0 && - (((cpu_architecture() >= CPU_ARCH_ARMv6) && (get_cr() & CR_XP)) || - cpu_is_xsc3()) && pfn >= 0x100000 && - !((paddr | size | addr) & ~SUPERSECTION_MASK)) { - area->flags |= VM_ARM_SECTION_MAPPING; - err = remap_area_supersections(addr, pfn, size, type); - } else if (!((paddr | size | addr) & ~PMD_MASK)) { + if (!((paddr | size | addr) & ~PMD_MASK)) { area->flags |= VM_ARM_SECTION_MAPPING; err = remap_area_sections(addr, pfn, size, type); } else diff --git a/arch/arm/mm/mmu.c b/arch/arm/mm/mmu.c index 23b87b5ef7f1..5d0ae2529872 100644 --- a/arch/arm/mm/mmu.c +++ b/arch/arm/mm/mmu.c @@ -854,69 +854,6 @@ static void __init alloc_init_p4d(pgd_t *pgd, unsigned long addr, } while (p4d++, addr = next, addr != end); } -#ifndef CONFIG_ARM_LPAE -static void __init create_36bit_mapping(struct mm_struct *mm, - struct map_desc *md, - const struct mem_type *type, - bool ng) -{ - unsigned long addr, length, end; - phys_addr_t phys; - pgd_t *pgd; - - addr = md->virtual; - phys = __pfn_to_phys(md->pfn); - length = PAGE_ALIGN(md->length); - - if (!(cpu_architecture() >= CPU_ARCH_ARMv6 || cpu_is_xsc3())) { - pr_err("MM: CPU does not support supersection mapping for 0x%08llx at 0x%08lx\n", - (long long)__pfn_to_phys((u64)md->pfn), addr); - return; - } - - /* N.B. ARMv6 supersections are only defined to work with domain 0. - * Since domain assignments can in fact be arbitrary, the - * 'domain == 0' check below is required to insure that ARMv6 - * supersections are only allocated for domain 0 regardless - * of the actual domain assignments in use. - */ - if (type->domain) { - pr_err("MM: invalid domain in supersection mapping for 0x%08llx at 0x%08lx\n", - (long long)__pfn_to_phys((u64)md->pfn), addr); - return; - } - - if ((addr | length | __pfn_to_phys(md->pfn)) & ~SUPERSECTION_MASK) { - pr_err("MM: cannot create mapping for 0x%08llx at 0x%08lx invalid alignment\n", - (long long)__pfn_to_phys((u64)md->pfn), addr); - return; - } - - /* - * Shift bits [35:32] of address into bits [23:20] of PMD - * (See ARMv6 spec). - */ - phys |= (((md->pfn >> (32 - PAGE_SHIFT)) & 0xF) << 20); - - pgd = pgd_offset(mm, addr); - end = addr + length; - do { - p4d_t *p4d = p4d_offset(pgd, addr); - pud_t *pud = pud_offset(p4d, addr); - pmd_t *pmd = pmd_offset(pud, addr); - int i; - - for (i = 0; i < 16; i++) - *pmd++ = __pmd(phys | type->prot_sect | PMD_SECT_SUPER | - (ng ? PMD_SECT_nG : 0)); - - addr += SUPERSECTION_SIZE; - phys += SUPERSECTION_SIZE; - pgd += SUPERSECTION_SIZE >> PGDIR_SHIFT; - } while (addr != end); -} -#endif /* !CONFIG_ARM_LPAE */ - static void __init __create_mapping(struct mm_struct *mm, struct map_desc *md, void *(*alloc)(unsigned long sz), bool ng) @@ -928,16 +865,6 @@ static void __init __create_mapping(struct mm_struct *mm, struct map_desc *md, type = &mem_types[md->type]; -#ifndef CONFIG_ARM_LPAE - /* - * Catch 36-bit addresses - */ - if (md->pfn >= 0x100000) { - create_36bit_mapping(mm, md, type, ng); - return; - } -#endif - addr = md->virtual & PAGE_MASK; phys = __pfn_to_phys(md->pfn); length = PAGE_ALIGN(md->length + (md->virtual & ~PAGE_MASK)); @@ -964,8 +891,7 @@ static void __init __create_mapping(struct mm_struct *mm, struct map_desc *md, * Create the page directory entries and any necessary * page tables for the mapping specified by `md'. We * are able to cope here with varying sizes and address - * offsets, and we take full advantage of sections and - * supersections. + * offsets, and we take full advantage of sections. */ static void __init create_mapping(struct map_desc *md) { diff --git a/arch/arm64/boot/dts/allwinner/sun50i-h6.dtsi b/arch/arm64/boot/dts/allwinner/sun50i-h6.dtsi index 72ce1a75647b..48c771223af4 100644 --- a/arch/arm64/boot/dts/allwinner/sun50i-h6.dtsi +++ b/arch/arm64/boot/dts/allwinner/sun50i-h6.dtsi @@ -205,8 +205,8 @@ video-codec@1c0e000 { clock-names = "ahb", "mod", "ram"; resets = <&ccu RST_BUS_VE>; interrupts = ; - allwinner,sram = <&ve_sram 1>; - iommus = <&iommu 3>; + allwinner,sram = <&ve_sram 1>, <&de2_sram 1>; + iommus = <&iommu 3>, <&iommu 1>; }; gpu: gpu@1800000 { diff --git a/arch/arm64/boot/dts/amlogic/meson-g12-common.dtsi b/arch/arm64/boot/dts/amlogic/meson-g12-common.dtsi index 00609d2da674..3135566df880 100644 --- a/arch/arm64/boot/dts/amlogic/meson-g12-common.dtsi +++ b/arch/arm64/boot/dts/amlogic/meson-g12-common.dtsi @@ -615,6 +615,15 @@ mux { }; }; + nor_hold_wp_pins: nor-hold-wp { + mux { + groups = "nor_hold", + "nor_wp"; + function = "nor"; + bias-disable; + }; + }; + pdm_din0_a_pins: pdm-din0-a { mux { groups = "pdm_din0_a"; diff --git a/arch/arm64/boot/dts/amlogic/meson-sm1-odroid-hc4.dts b/arch/arm64/boot/dts/amlogic/meson-sm1-odroid-hc4.dts index 3ece30a0a1ff..5f15c2299509 100644 --- a/arch/arm64/boot/dts/amlogic/meson-sm1-odroid-hc4.dts +++ b/arch/arm64/boot/dts/amlogic/meson-sm1-odroid-hc4.dts @@ -126,7 +126,7 @@ &sd_emmc_c { &spifc { status = "okay"; - pinctrl-0 = <&nor_pins>; + pinctrl-0 = <&nor_pins>, <&nor_hold_wp_pins>; pinctrl-names = "default"; flash@0 { @@ -134,7 +134,7 @@ flash@0 { #size-cells = <1>; compatible = "jedec,spi-nor"; reg = <0>; - spi-max-frequency = <104000000>; + spi-max-frequency = <40000000>; }; }; diff --git a/arch/arm64/boot/dts/apple/t6030.dtsi b/arch/arm64/boot/dts/apple/t6030.dtsi index dda9568af11f..5ff12edfc553 100644 --- a/arch/arm64/boot/dts/apple/t6030.dtsi +++ b/arch/arm64/boot/dts/apple/t6030.dtsi @@ -208,7 +208,7 @@ l2_cache_1: l2-cache-1 { cache-unified; cache-size = <0x1000000>; }; - }; + }; timer { compatible = "arm,armv8-timer"; diff --git a/arch/arm64/boot/dts/apple/t6032.dtsi b/arch/arm64/boot/dts/apple/t6032.dtsi index bbf19ecdaaec..61d044f3a734 100644 --- a/arch/arm64/boot/dts/apple/t6032.dtsi +++ b/arch/arm64/boot/dts/apple/t6032.dtsi @@ -283,7 +283,7 @@ l2_cache_5: l2-cache-5 { cache-unified; cache-size = <0x1000000>; }; - }; + }; die0: soc@200000000 { compatible = "simple-bus"; diff --git a/arch/arm64/boot/dts/broadcom/bcm2712-d-rpi-5-b.dts b/arch/arm64/boot/dts/broadcom/bcm2712-d-rpi-5-b.dts index 127be0fc27c2..ae4b7c587dbc 100644 --- a/arch/arm64/boot/dts/broadcom/bcm2712-d-rpi-5-b.dts +++ b/arch/arm64/boot/dts/broadcom/bcm2712-d-rpi-5-b.dts @@ -3,6 +3,11 @@ #include "bcm2712-rpi-5-b.dts" +/ { + compatible = "raspberrypi,5-model-b-d0", "brcm,bcm2712-d0"; + model = "Raspberry Pi 5 d0 Stepping"; +}; + &gio_aon { brcm,gpio-bank-widths = <15 6>; diff --git a/arch/arm64/boot/dts/broadcom/bcm2712-rpi-5-b-base.dtsi b/arch/arm64/boot/dts/broadcom/bcm2712-rpi-5-b-base.dtsi index b7a6bc34ae1a..d998bfae91ac 100644 --- a/arch/arm64/boot/dts/broadcom/bcm2712-rpi-5-b-base.dtsi +++ b/arch/arm64/boot/dts/broadcom/bcm2712-rpi-5-b-base.dtsi @@ -104,6 +104,18 @@ wl_on_reg: wl-on-reg { }; }; +&ddc0 { + status = "okay"; +}; + +&ddc1 { + status = "okay"; +}; + +&disp_intr { + status = "okay"; +}; + &pinctrl { bt_shutdown_default: bt-shutdown-default-state { function = "gpio"; @@ -230,16 +242,27 @@ bluetooth: bluetooth { &hvs { clocks = <&firmware_clocks 4>, <&firmware_clocks 16>; clock-names = "core", "disp"; + status = "okay"; }; &hdmi0 { clocks = <&firmware_clocks 13>, <&firmware_clocks 14>, <&dvp 0>, <&clk_27MHz>; clock-names = "hdmi", "bvb", "audio", "cec"; + status = "okay"; }; &hdmi1 { clocks = <&firmware_clocks 13>, <&firmware_clocks 14>, <&dvp 1>, <&clk_27MHz>; clock-names = "hdmi", "bvb", "audio", "cec"; + status = "okay"; +}; + +&mop { + status = "okay"; +}; + +&moplet { + status = "okay"; }; &pcie1 { @@ -250,6 +273,18 @@ &pcie2 { status = "okay"; }; +&pixelvalve0 { + status = "okay"; +}; + +&pixelvalve1 { + status = "okay"; +}; + &v3d { clocks = <&firmware_clocks 5>; }; + +&vc4 { + status = "okay"; +}; diff --git a/arch/arm64/boot/dts/broadcom/bcm2712.dtsi b/arch/arm64/boot/dts/broadcom/bcm2712.dtsi index 45aa8ec5e2b1..a2c71a4355bf 100644 --- a/arch/arm64/boot/dts/broadcom/bcm2712.dtsi +++ b/arch/arm64/boot/dts/broadcom/bcm2712.dtsi @@ -359,12 +359,14 @@ pixelvalve0: pixelvalve@7c410000 { compatible = "brcm,bcm2712-pixelvalve0"; reg = <0x7c410000 0x100>; interrupts = ; + status = "disabled"; }; pixelvalve1: pixelvalve@7c411000 { compatible = "brcm,bcm2712-pixelvalve1"; reg = <0x7c411000 0x100>; interrupts = ; + status = "disabled"; }; mop: mop@7c500000 { @@ -372,6 +374,7 @@ mop: mop@7c500000 { reg = <0x7c500000 0x28>; interrupt-parent = <&disp_intr>; interrupts = <1>; + status = "disabled"; }; moplet: moplet@7c501000 { @@ -379,6 +382,7 @@ moplet: moplet@7c501000 { reg = <0x7c501000 0x20>; interrupt-parent = <&disp_intr>; interrupts = <0>; + status = "disabled"; }; disp_intr: interrupt-controller@7c502000 { @@ -387,6 +391,7 @@ disp_intr: interrupt-controller@7c502000 { interrupts = ; interrupt-controller; #interrupt-cells = <1>; + status = "disabled"; }; dvp: clock@7c700000 { @@ -405,6 +410,7 @@ ddc0: i2c@7d508200 { clock-frequency = <97500>; #address-cells = <1>; #size-cells = <0>; + status = "disabled"; }; ddc1: i2c@7d508280 { @@ -415,6 +421,7 @@ ddc1: i2c@7d508280 { clock-frequency = <97500>; #address-cells = <1>; #size-cells = <0>; + status = "disabled"; }; bsc_irq: interrupt-controller@7d508380 { @@ -460,6 +467,7 @@ hdmi0: hdmi@7c701400 { interrupt-names = "cec-tx", "cec-rx", "cec-low", "hpd-connected", "hpd-removed"; ddc = <&ddc0>; + status = "disabled"; }; hdmi1: hdmi@7c706400 { @@ -489,6 +497,7 @@ hdmi1: hdmi@7c706400 { interrupt-names = "cec-tx", "cec-rx", "cec-low", "hpd-connected", "hpd-removed"; ddc = <&ddc1>; + status = "disabled"; }; }; @@ -667,6 +676,7 @@ v3d: gpu@1002000000 { vc4: gpu { compatible = "brcm,bcm2712-vc6"; + status = "disabled"; }; timer { @@ -701,5 +711,6 @@ hvs: hvs@107c580000 { interrupt-parent = <&disp_intr>; interrupts = <2>, <9>, <16>; interrupt-names = "ch0-eof", "ch1-eof", "ch2-eof"; + status = "disabled"; }; }; diff --git a/arch/arm64/boot/dts/freescale/imx8dxl-evk.dts b/arch/arm64/boot/dts/freescale/imx8dxl-evk.dts index 0ede0c7ed422..71eff3efa6d3 100644 --- a/arch/arm64/boot/dts/freescale/imx8dxl-evk.dts +++ b/arch/arm64/boot/dts/freescale/imx8dxl-evk.dts @@ -29,7 +29,7 @@ imx8dxl-cm4 { clocks = <&clk_dummy>; mbox-names = "tx", "rx", "rxdb"; mboxes = <&lsio_mu5 0 1 &lsio_mu5 1 1 &lsio_mu5 3 1>; - memory-region = <&vdevbuffer>, <&vdev0vring0>, <&vdev0vring1>, + memory-region = <&vdev0buffer>, <&vdev0vring0>, <&vdev0vring1>, <&vdev1vring0>, <&vdev1vring1>, <&rsc_table>; power-domains = <&pd IMX_SC_R_M4_0_PID0>, <&pd IMX_SC_R_M4_0_MU_1A>; fsl,resource-id = ; @@ -65,32 +65,32 @@ linux,cma { linux,cma-default; }; - vdev0vring0: memory0@90000000 { + vdev0vring0: vdev0vring0@90000000 { reg = <0 0x90000000 0 0x8000>; no-map; }; - vdev0vring1: memory@90008000 { + vdev0vring1: vdev0vring1@90008000 { reg = <0 0x90008000 0 0x8000>; no-map; }; - vdev1vring0: memory@90010000 { + vdev1vring0: vdev1vring0@90010000 { reg = <0 0x90010000 0 0x8000>; no-map; }; - vdev1vring1: memory@90018000 { + vdev1vring1: vdev1vring1@90018000 { reg = <0 0x90018000 0 0x8000>; no-map; }; - rsc_table: memory-rsc-table@900ff000 { + rsc_table: rsc-table@900ff000 { reg = <0 0x900ff000 0 0x1000>; no-map; }; - vdevbuffer: memory-vdevbuffer@90400000 { + vdev0buffer: vdev0buffer@90400000 { compatible = "shared-dma-pool"; reg = <0 0x90400000 0 0x100000>; no-map; diff --git a/arch/arm64/boot/dts/freescale/imx8dxl-sr-som.dtsi b/arch/arm64/boot/dts/freescale/imx8dxl-sr-som.dtsi index 93a0eb4d7f77..83d22ae373c3 100644 --- a/arch/arm64/boot/dts/freescale/imx8dxl-sr-som.dtsi +++ b/arch/arm64/boot/dts/freescale/imx8dxl-sr-som.dtsi @@ -26,7 +26,7 @@ imx8dxl-cm4 { clocks = <&clk_dummy>; mboxes = <&lsio_mu5 0 1 &lsio_mu5 1 1 &lsio_mu5 3 1>; mbox-names = "tx", "rx", "rxdb"; - memory-region = <&vdevbuffer>, <&vdev0vring0>, <&vdev0vring1>, + memory-region = <&vdev0buffer>, <&vdev0vring0>, <&vdev0vring1>, <&vdev1vring0>, <&vdev1vring1>, <&rsc_table>; power-domains = <&pd IMX_SC_R_M4_0_PID0>, <&pd IMX_SC_R_M4_0_MU_1A>; fsl,entry-address = <0x34fe0000>; @@ -103,32 +103,32 @@ linux,cma { linux,cma-default; }; - vdev0vring0: memory0@90000000 { + vdev0vring0: vdev0vring0@90000000 { reg = <0 0x90000000 0 0x8000>; no-map; }; - vdev0vring1: memory@90008000 { + vdev0vring1: vdev0vring1@90008000 { reg = <0 0x90008000 0 0x8000>; no-map; }; - vdev1vring0: memory@90010000 { + vdev1vring0: vdev1vring0@90010000 { reg = <0 0x90010000 0 0x8000>; no-map; }; - vdev1vring1: memory@90018000 { + vdev1vring1: vdev1vring1@90018000 { reg = <0 0x90018000 0 0x8000>; no-map; }; - rsc_table: memory-rsc-table@900ff000 { + rsc_table: rsc-table@900ff000 { reg = <0 0x900ff000 0 0x1000>; no-map; }; - vdevbuffer: memory-vdevbuffer@90400000 { + vdev0buffer: vdev0buffer@90400000 { compatible = "shared-dma-pool"; reg = <0 0x90400000 0 0x100000>; no-map; diff --git a/arch/arm64/boot/dts/freescale/imx8mp-kontron-dl.dtso b/arch/arm64/boot/dts/freescale/imx8mp-kontron-dl.dtso index 41a2bb74f156..88b30ca66adf 100644 --- a/arch/arm64/boot/dts/freescale/imx8mp-kontron-dl.dtso +++ b/arch/arm64/boot/dts/freescale/imx8mp-kontron-dl.dtso @@ -6,6 +6,7 @@ /dts-v1/; /plugin/; +#include #include #include #include "imx8mp-pinfunc.h" @@ -99,6 +100,16 @@ &ldb_lvds_ch0 { &lvds_bridge { status = "okay"; + /* + * The video PLL clock frequency needs to be configured manually. + * The panel needs a LVDS clock of 50 MHz * 7 = 350 MHz. + * IMX8MP_CLK_MEDIA_LDB = IMX8MP_CLK_MEDIA_DISP2_PIX * 7 + * IMX8MP_VIDEO_PLL1 = IMX8MP_CLK_MEDIA_LDB * 2 + */ + assigned-clocks = <&clk IMX8MP_CLK_MEDIA_LDB>, + <&clk IMX8MP_VIDEO_PLL1>; + assigned-clock-parents = <&clk IMX8MP_VIDEO_PLL1_OUT>; + assigned-clock-rates = <0>, <700000000>; }; /* redefine to remove touch controller GPIOs */ diff --git a/arch/arm64/boot/dts/freescale/imx8mp-phyboard-pollux-peb-av-10.dtsi b/arch/arm64/boot/dts/freescale/imx8mp-phyboard-pollux-peb-av-10.dtsi index bb740f845855..8957b24a7ad2 100644 --- a/arch/arm64/boot/dts/freescale/imx8mp-phyboard-pollux-peb-av-10.dtsi +++ b/arch/arm64/boot/dts/freescale/imx8mp-phyboard-pollux-peb-av-10.dtsi @@ -77,13 +77,12 @@ sound { "MIC3R", "Microphone Jack", "Microphone Jack", "Mic Bias"; - simple-audio-card,cpu { + dailink_master: simple-audio-card,cpu { sound-dai = <&sai2>; }; - dailink_master: simple-audio-card,codec { + simple-audio-card,codec { sound-dai = <&codec>; - clocks = <&clk IMX8MP_CLK_SAI2>; }; }; }; diff --git a/arch/arm64/boot/dts/freescale/imx8qm-mek.dts b/arch/arm64/boot/dts/freescale/imx8qm-mek.dts index 9e49ac377162..1afa65bd955e 100644 --- a/arch/arm64/boot/dts/freescale/imx8qm-mek.dts +++ b/arch/arm64/boot/dts/freescale/imx8qm-mek.dts @@ -44,57 +44,57 @@ reserved-memory { #size-cells = <2>; ranges; - vdev0vring0: memory@90000000 { + vdev0vring0: vdev0vring0@90000000 { reg = <0 0x90000000 0 0x8000>; no-map; }; - vdev0vring1: memory@90008000 { + vdev0vring1: vdev0vring1@90008000 { reg = <0 0x90008000 0 0x8000>; no-map; }; - vdev1vring0: memory@90010000 { + vdev1vring0: vdev1vring0@90010000 { reg = <0 0x90010000 0 0x8000>; no-map; }; - vdev1vring1: memory@90018000 { + vdev1vring1: vdev1vring1@90018000 { reg = <0 0x90018000 0 0x8000>; no-map; }; - rsc_table0: memory@900ff000 { + rsc_table0: rsc-table@900ff000 { reg = <0 0x900ff000 0 0x1000>; no-map; }; - vdev2vring0: memory@90100000 { + vdev2vring0: vdev2vring0@90100000 { reg = <0 0x90100000 0 0x8000>; no-map; }; - vdev2vring1: memory@90108000 { + vdev2vring1: vdev2vring1@90108000 { reg = <0 0x90108000 0 0x8000>; no-map; }; - vdev3vring0: memory@90110000 { + vdev3vring0: vdev3vring0@90110000 { reg = <0 0x90110000 0 0x8000>; no-map; }; - vdev3vring1: memory@90118000 { + vdev3vring1: vdev3vring1@90118000 { reg = <0 0x90118000 0 0x8000>; no-map; }; - rsc_table1: memory@901ff000 { + rsc_table1: rsc-table@901ff000 { reg = <0 0x901ff000 0 0x1000>; no-map; }; - vdevbuffer: memory@90400000 { + vdev0buffer: vdev0buffer@90400000 { compatible = "shared-dma-pool"; reg = <0 0x90400000 0 0x100000>; no-map; @@ -105,17 +105,17 @@ dsp_reserved: memory@92400000 { no-map; }; - dsp_vdev0vring0: memory@942f0000 { + dsp_vdev0vring0: vdev0vring0@942f0000 { reg = <0 0x942f0000 0 0x8000>; no-map; }; - dsp_vdev0vring1: memory@942f8000 { + dsp_vdev0vring1: vdev0vring1@942f8000 { reg = <0 0x942f8000 0 0x8000>; no-map; }; - dsp_vdev0buffer: memory@94300000 { + dsp_vdev0buffer: vdev0buffer@94300000 { compatible = "shared-dma-pool"; reg = <0 0x94300000 0 0x100000>; no-map; @@ -456,7 +456,7 @@ imx8qm-cm4-0 { mboxes = <&lsio_mu5 0 1 &lsio_mu5 1 1 &lsio_mu5 3 1>; - memory-region = <&vdevbuffer>, <&vdev0vring0>, <&vdev0vring1>, + memory-region = <&vdev0buffer>, <&vdev0vring0>, <&vdev0vring1>, <&vdev1vring0>, <&vdev1vring1>, <&rsc_table0>; power-domains = <&pd IMX_SC_R_M4_0_PID0>, <&pd IMX_SC_R_M4_0_MU_1A>; @@ -471,7 +471,7 @@ imx8qm-cm4-1 { mboxes = <&lsio_mu6 0 1 &lsio_mu6 1 1 &lsio_mu6 3 1>; - memory-region = <&vdevbuffer>, <&vdev2vring0>, <&vdev2vring1>, + memory-region = <&vdev0buffer>, <&vdev2vring0>, <&vdev2vring1>, <&vdev3vring0>, <&vdev3vring1>, <&rsc_table1>; power-domains = <&pd IMX_SC_R_M4_1_PID0>, <&pd IMX_SC_R_M4_1_MU_1A>; diff --git a/arch/arm64/boot/dts/freescale/imx8qxp-mek.dts b/arch/arm64/boot/dts/freescale/imx8qxp-mek.dts index 857a6e512228..eb994f3e2872 100644 --- a/arch/arm64/boot/dts/freescale/imx8qxp-mek.dts +++ b/arch/arm64/boot/dts/freescale/imx8qxp-mek.dts @@ -27,7 +27,7 @@ imx8x_cm4: imx8x-cm4 { mboxes = <&lsio_mu5 0 1 &lsio_mu5 1 1 &lsio_mu5 3 1>; - memory-region = <&vdevbuffer>, <&vdev0vring0>, <&vdev0vring1>, + memory-region = <&vdev0buffer>, <&vdev0vring0>, <&vdev0vring1>, <&vdev1vring0>, <&vdev1vring1>, <&rsc_table>; power-domains = <&pd IMX_SC_R_M4_0_PID0>, <&pd IMX_SC_R_M4_0_MU_1A>; @@ -242,48 +242,48 @@ reserved-memory { #size-cells = <2>; ranges; - vdev0vring0: memory@90000000 { + vdev0vring0: vdev0vring0@90000000 { reg = <0 0x90000000 0 0x8000>; no-map; }; - vdev0vring1: memory@90008000 { + vdev0vring1: vdev0vring1@90008000 { reg = <0 0x90008000 0 0x8000>; no-map; }; - vdev1vring0: memory@90010000 { + vdev1vring0: vdev1vring0@90010000 { reg = <0 0x90010000 0 0x8000>; no-map; }; - vdev1vring1: memory@90018000 { + vdev1vring1: vdev1vring1@90018000 { reg = <0 0x90018000 0 0x8000>; no-map; }; - rsc_table: memory@900ff000 { + rsc_table: rsc-table@900ff000 { reg = <0 0x900ff000 0 0x1000>; no-map; }; - vdevbuffer: memory@90400000 { + vdev0buffer: vdev0buffer@90400000 { compatible = "shared-dma-pool"; reg = <0 0x90400000 0 0x100000>; no-map; }; - dsp_vdev0vring0: memory@942f0000 { + dsp_vdev0vring0: vdev0vring0@942f0000 { reg = <0 0x942f0000 0 0x8000>; no-map; }; - dsp_vdev0vring1: memory@942f8000 { + dsp_vdev0vring1: vdev0vring1@942f8000 { reg = <0 0x942f8000 0 0x8000>; no-map; }; - dsp_vdev0buffer: memory@94300000 { + dsp_vdev0buffer: vdev0buffer@94300000 { compatible = "shared-dma-pool"; reg = <0 0x94300000 0 0x100000>; no-map; diff --git a/arch/arm64/boot/dts/freescale/imx8ulp-evk.dts b/arch/arm64/boot/dts/freescale/imx8ulp-evk.dts index 4b925832bb66..4e19847f240a 100644 --- a/arch/arm64/boot/dts/freescale/imx8ulp-evk.dts +++ b/arch/arm64/boot/dts/freescale/imx8ulp-evk.dts @@ -80,7 +80,7 @@ vdev1vring1: vdev1vring1@aff18000 { no-map; }; - vdevbuffer: vdevbuffer@a8400000 { + vdev0buffer: vdev0buffer@a8400000 { compatible = "shared-dma-pool"; reg = <0 0xa8400000 0 0x100000>; no-map; @@ -139,7 +139,7 @@ &cm33 { mboxes = <&mu 0 1>, <&mu 1 1>, <&mu 3 1>; - memory-region = <&vdevbuffer>, <&vdev0vring0>, <&vdev0vring1>, + memory-region = <&vdev0buffer>, <&vdev0vring0>, <&vdev0vring1>, <&vdev1vring0>, <&vdev1vring1>, <&rsc_table>; status = "okay"; }; diff --git a/arch/arm64/boot/dts/freescale/imx93-11x11-evk-common.dtsi b/arch/arm64/boot/dts/freescale/imx93-11x11-evk-common.dtsi index f48e7947cf64..c57a2040b9c2 100644 --- a/arch/arm64/boot/dts/freescale/imx93-11x11-evk-common.dtsi +++ b/arch/arm64/boot/dts/freescale/imx93-11x11-evk-common.dtsi @@ -67,7 +67,7 @@ rsc_table: rsc-table@2021e000 { no-map; }; - vdevbuffer: vdevbuffer@a4020000 { + vdev0buffer: vdev0buffer@a4020000 { compatible = "shared-dma-pool"; reg = <0 0xa4020000 0 0x100000>; no-map; @@ -170,7 +170,7 @@ &cm33 { mboxes = <&mu1 0 1>, <&mu1 1 1>, <&mu1 3 1>; - memory-region = <&vdevbuffer>, <&vdev0vring0>, <&vdev0vring1>, + memory-region = <&vdev0buffer>, <&vdev0vring0>, <&vdev0vring1>, <&vdev1vring0>, <&vdev1vring1>, <&rsc_table>; status = "okay"; }; diff --git a/arch/arm64/boot/dts/freescale/imx93-11x11-frdm-common.dtsi b/arch/arm64/boot/dts/freescale/imx93-11x11-frdm-common.dtsi new file mode 100644 index 000000000000..32e5054cc091 --- /dev/null +++ b/arch/arm64/boot/dts/freescale/imx93-11x11-frdm-common.dtsi @@ -0,0 +1,680 @@ +// SPDX-License-Identifier: (GPL-2.0+ OR MIT) + +#include + +/ { + aliases { + can0 = &flexcan2; + ethernet0 = &fec; + ethernet1 = &eqos; + i2c0 = &lpi2c1; + i2c1 = &lpi2c2; + i2c2 = &lpi2c3; + mmc0 = &usdhc1; /* EMMC */ + mmc1 = &usdhc2; /* uSD */ + rtc0 = &pcf2131; + serial0 = &lpuart1; + serial4 = &lpuart5; + }; + + chosen { + stdout-path = &lpuart1; + }; + + flexcan2_phy: can-phy { + compatible = "nxp,tja1051"; + #phy-cells = <0>; + max-bitrate = <5000000>; + silent-gpios = <&pcal6524 23 GPIO_ACTIVE_HIGH>; + }; + + gpio-keys { + compatible = "gpio-keys"; + + button-k2 { + label = "Button K2"; + linux,code = ; + gpios = <&pcal6524 5 (GPIO_ACTIVE_LOW | GPIO_PULL_UP)>; + interrupt-parent = <&pcal6524>; + interrupts = <5 IRQ_TYPE_EDGE_FALLING>; + }; + + button-k3 { + label = "Button K3"; + linux,code = ; + gpios = <&pcal6524 6 (GPIO_ACTIVE_LOW | GPIO_PULL_UP)>; + interrupt-parent = <&pcal6524>; + interrupts = <6 IRQ_TYPE_EDGE_FALLING>; + }; + }; + + reg_usdhc2_vmmc: regulator-usdhc2 { + compatible = "regulator-fixed"; + off-on-delay-us = <12000>; + pinctrl-0 = <&pinctrl_reg_usdhc2_vmmc>; + pinctrl-names = "default"; + regulator-min-microvolt = <3300000>; + regulator-max-microvolt = <3300000>; + regulator-name = "VSD_3V3"; + vin-supply = <&buck4>; + gpio = <&gpio3 7 GPIO_ACTIVE_HIGH>; + enable-active-high; + }; + + reserved-memory { + ranges; + #address-cells = <2>; + #size-cells = <2>; + + linux,cma { + compatible = "shared-dma-pool"; + alloc-ranges = <0 0x80000000 0 0x30000000>; + reusable; + size = <0 0x10000000>; + linux,cma-default; + }; + + rsc_table: rsc-table@2021e000 { + reg = <0 0x2021e000 0 0x1000>; + no-map; + }; + + vdev0vring0: vdev0vring0@a4000000 { + reg = <0 0xa4000000 0 0x8000>; + no-map; + }; + + vdev0vring1: vdev0vring1@a4008000 { + reg = <0 0xa4008000 0 0x8000>; + no-map; + }; + + vdev1vring0: vdev1vring0@a4010000 { + reg = <0 0xa4010000 0 0x8000>; + no-map; + }; + + vdev1vring1: vdev1vring1@a4018000 { + reg = <0 0xa4018000 0 0x8000>; + no-map; + }; + + vdev0buffer: vdev0buffer@a4020000 { + compatible = "shared-dma-pool"; + reg = <0 0xa4020000 0 0x100000>; + no-map; + }; + }; +}; + +&adc1 { + vref-supply = <&buck5>; + status = "okay"; +}; + +&mu1 { + status = "okay"; +}; + +&cm33 { + mboxes = <&mu1 0 1>, + <&mu1 1 1>, + <&mu1 3 1>; + mbox-names = "tx", "rx", "rxdb"; + memory-region = <&vdev0buffer>, <&vdev0vring0>, <&vdev0vring1>, + <&vdev1vring0>, <&vdev1vring1>, <&rsc_table>; + status = "okay"; +}; + +&eqos { + pinctrl-names = "default", "sleep"; + pinctrl-0 = <&pinctrl_eqos>; + pinctrl-1 = <&pinctrl_eqos_sleep>; + phy-handle = <ðphy1>; + phy-mode = "rgmii-id"; + status = "okay"; + + mdio { + compatible = "snps,dwmac-mdio"; + #address-cells = <1>; + #size-cells = <0>; + clock-frequency = <5000000>; + + ethphy1: ethernet-phy@1 { + reg = <1>; + reset-assert-us = <10000>; + reset-deassert-us = <80000>; + reset-gpios = <&pcal6524 15 GPIO_ACTIVE_LOW>; + realtek,clkout-disable; + }; + }; +}; + +&fec { + pinctrl-names = "default", "sleep"; + pinctrl-0 = <&pinctrl_fec>; + pinctrl-1 = <&pinctrl_fec_sleep>; + phy-mode = "rgmii-id"; + phy-handle = <ðphy2>; + fsl,magic-packet; + status = "okay"; + + mdio { + #address-cells = <1>; + #size-cells = <0>; + clock-frequency = <5000000>; + + ethphy2: ethernet-phy@2 { + reg = <2>; + reset-assert-us = <10000>; + reset-deassert-us = <80000>; + reset-gpios = <&pcal6524 16 GPIO_ACTIVE_LOW>; + realtek,clkout-disable; + }; + }; +}; + +&flexcan2 { + phys = <&flexcan2_phy>; + pinctrl-0 = <&pinctrl_flexcan2>; + pinctrl-1 = <&pinctrl_flexcan2_sleep>; + pinctrl-names = "default", "sleep"; + status = "okay"; +}; + +&lpi2c1 { + clock-frequency = <400000>; + pinctrl-0 = <&pinctrl_lpi2c1>; + pinctrl-names = "default"; + status = "okay"; +}; + +&lpi2c2 { + clock-frequency = <400000>; + pinctrl-0 = <&pinctrl_lpi2c2>; + pinctrl-names = "default"; + status = "okay"; + + pcal6524: gpio@22 { + compatible = "nxp,pcal6524"; + reg = <0x22>; + #interrupt-cells = <2>; + interrupt-controller; + interrupt-parent = <&gpio3>; + interrupts = <27 IRQ_TYPE_LEVEL_LOW>; + #gpio-cells = <2>; + gpio-controller; + pinctrl-0 = <&pinctrl_pcal6524>; + pinctrl-names = "default"; + /* does not boot with supplier set, because it is the bucks interrupt parent */ + /* vcc-supply = <&buck4>; */ + }; + + pmic@25 { + compatible = "nxp,pca9451a"; + reg = <0x25>; + interrupt-parent = <&pcal6524>; + interrupts = <11 IRQ_TYPE_EDGE_FALLING>; + + regulators { + + buck1: BUCK1 { + regulator-name = "VDD_SOC_0V8"; + regulator-min-microvolt = <610000>; + regulator-max-microvolt = <950000>; + regulator-always-on; + regulator-boot-on; + regulator-ramp-delay = <3125>; + }; + + buck2: BUCK2 { + regulator-name = "LPD4_x_VDDQ_0V6"; + regulator-min-microvolt = <600000>; + regulator-max-microvolt = <670000>; + regulator-always-on; + regulator-boot-on; + regulator-ramp-delay = <3125>; + }; + + buck4: BUCK4 { + regulator-name = "VDD_3V3"; + regulator-min-microvolt = <3300000>; + regulator-max-microvolt = <3300000>; + regulator-always-on; + regulator-boot-on; + }; + + buck5: BUCK5 { + regulator-name = "VDD_1V8"; + regulator-min-microvolt = <1800000>; + regulator-max-microvolt = <1800000>; + regulator-always-on; + regulator-boot-on; + }; + + buck6: BUCK6 { + regulator-name = "LPD4_x_VDD2_1V1"; + regulator-min-microvolt = <1060000>; + regulator-max-microvolt = <1140000>; + regulator-always-on; + regulator-boot-on; + }; + + ldo1: LDO1 { + regulator-name = "NVCC_BBSM_1V8"; + regulator-min-microvolt = <1620000>; + regulator-max-microvolt = <1980000>; + regulator-always-on; + regulator-boot-on; + }; + + ldo4: LDO4 { + regulator-name = "VDD_ANA_0V8"; + regulator-min-microvolt = <800000>; + regulator-max-microvolt = <840000>; + regulator-always-on; + regulator-boot-on; + }; + + ldo5: LDO5 { + regulator-name = "NVCC_SD"; + regulator-min-microvolt = <1800000>; + regulator-max-microvolt = <3300000>; + regulator-always-on; + regulator-boot-on; + }; + }; + }; + + eeprom: eeprom@50 { + compatible = "atmel,24c256"; + reg = <0x50>; + pagesize = <64>; + vcc-supply = <&buck4>; + }; +}; + +&lpi2c3 { + clock-frequency = <400000>; + pinctrl-0 = <&pinctrl_lpi2c3>; + pinctrl-names = "default"; + status = "okay"; + + ptn5110: tcpc@50 { + compatible = "nxp,ptn5110", "tcpci"; + reg = <0x50>; + interrupt-parent = <&gpio3>; + interrupts = <27 IRQ_TYPE_LEVEL_LOW>; + + typec1_con: connector { + compatible = "usb-c-connector"; + data-role = "dual"; + label = "USB-C"; + op-sink-microwatt = <15000000>; + power-role = "dual"; + self-powered; + sink-pdos = ; + source-pdos = ; + try-power-role = "sink"; + + ports { + #address-cells = <1>; + #size-cells = <0>; + + port@0 { + reg = <0>; + + typec1_dr_sw: endpoint { + remote-endpoint = <&usb1_drd_sw>; + }; + }; + }; + }; + }; + + pcf2131: rtc@53 { + compatible = "nxp,pcf2131"; + reg = <0x53>; + interrupt-parent = <&pcal6524>; + interrupts = <1 IRQ_TYPE_EDGE_FALLING>; + }; +}; + +&lpuart1 { /* console */ + pinctrl-0 = <&pinctrl_uart1>; + pinctrl-names = "default"; + status = "okay"; +}; + +&lpuart5 { + pinctrl-0 = <&pinctrl_uart5>; + pinctrl-names = "default"; + status = "okay"; + + uart-has-rtscts; + + bluetooth: bluetooth { + compatible = "nxp,88w8987-bt"; + }; +}; + +&usbotg1 { + adp-disable; + disable-over-current; + dr_mode = "otg"; + hnp-disable; + srp-disable; + usb-role-switch; + samsung,picophy-dc-vol-level-adjust = <7>; + samsung,picophy-pre-emp-curr-control = <3>; + status = "okay"; + + port { + usb1_drd_sw: endpoint { + remote-endpoint = <&typec1_dr_sw>; + }; + }; +}; + +&usbotg2 { + disable-over-current; + dr_mode = "host"; + samsung,picophy-dc-vol-level-adjust = <7>; + samsung,picophy-pre-emp-curr-control = <3>; + status = "okay"; +}; + +&usdhc1 { + bus-width = <8>; + non-removable; + pinctrl-0 = <&pinctrl_usdhc1>; + pinctrl-1 = <&pinctrl_usdhc1_100mhz>; + pinctrl-2 = <&pinctrl_usdhc1_200mhz>; + pinctrl-names = "default", "state_100mhz", "state_200mhz"; + vmmc-supply = <&buck4>; + status = "okay"; +}; + +&usdhc2 { + bus-width = <4>; + cd-gpios = <&gpio3 00 GPIO_ACTIVE_LOW>; + no-mmc; + no-sdio; + pinctrl-0 = <&pinctrl_usdhc2>, <&pinctrl_usdhc2_gpio>; + pinctrl-1 = <&pinctrl_usdhc2_100mhz>, <&pinctrl_usdhc2_gpio>; + pinctrl-2 = <&pinctrl_usdhc2_200mhz>, <&pinctrl_usdhc2_gpio>; + pinctrl-3 = <&pinctrl_usdhc2_sleep>, <&pinctrl_usdhc2_gpio_sleep>; + pinctrl-names = "default", "state_100mhz", "state_200mhz", "sleep"; + vmmc-supply = <®_usdhc2_vmmc>; + status = "okay"; +}; + +&wdog3 { + pinctrl-names = "default"; + pinctrl-0 = <&pinctrl_wdog>; + fsl,ext-reset-output; + status = "okay"; +}; + +&iomuxc { + + pinctrl_eqos: eqosgrp { + fsl,pins = < + MX93_PAD_ENET1_MDC__ENET_QOS_MDC 0x57e + MX93_PAD_ENET1_MDIO__ENET_QOS_MDIO 0x57e + MX93_PAD_ENET1_RD0__ENET_QOS_RGMII_RD0 0x57e + MX93_PAD_ENET1_RD1__ENET_QOS_RGMII_RD1 0x57e + MX93_PAD_ENET1_RD2__ENET_QOS_RGMII_RD2 0x57e + MX93_PAD_ENET1_RD3__ENET_QOS_RGMII_RD3 0x57e + MX93_PAD_ENET1_RXC__CCM_ENET_QOS_CLOCK_GENERATE_RX_CLK 0x58e + MX93_PAD_ENET1_RX_CTL__ENET_QOS_RGMII_RX_CTL 0x57e + MX93_PAD_ENET1_TD0__ENET_QOS_RGMII_TD0 0x57e + MX93_PAD_ENET1_TD1__ENET_QOS_RGMII_TD1 0x57e + MX93_PAD_ENET1_TD2__ENET_QOS_RGMII_TD2 0x57e + MX93_PAD_ENET1_TD3__ENET_QOS_RGMII_TD3 0x57e + MX93_PAD_ENET1_TXC__CCM_ENET_QOS_CLOCK_GENERATE_TX_CLK 0x58e + MX93_PAD_ENET1_TX_CTL__ENET_QOS_RGMII_TX_CTL 0x57e + >; + }; + + pinctrl_eqos_sleep: eqossleepgrp { + fsl,pins = < + MX93_PAD_ENET1_MDC__GPIO4_IO00 0x31e + MX93_PAD_ENET1_MDIO__GPIO4_IO01 0x31e + MX93_PAD_ENET1_RD0__GPIO4_IO10 0x31e + MX93_PAD_ENET1_RD1__GPIO4_IO11 0x31e + MX93_PAD_ENET1_RD2__GPIO4_IO12 0x31e + MX93_PAD_ENET1_RD3__GPIO4_IO13 0x31e + MX93_PAD_ENET1_RXC__GPIO4_IO09 0x31e + MX93_PAD_ENET1_RX_CTL__GPIO4_IO08 0x31e + MX93_PAD_ENET1_TD0__GPIO4_IO05 0x31e + MX93_PAD_ENET1_TD1__GPIO4_IO04 0x31e + MX93_PAD_ENET1_TD2__GPIO4_IO03 0x31e + MX93_PAD_ENET1_TD3__GPIO4_IO02 0x31e + MX93_PAD_ENET1_TXC__GPIO4_IO07 0x31e + MX93_PAD_ENET1_TX_CTL__GPIO4_IO06 0x31e + >; + }; + + pinctrl_fec: fecgrp { + fsl,pins = < + MX93_PAD_ENET2_MDC__ENET1_MDC 0x57e + MX93_PAD_ENET2_MDIO__ENET1_MDIO 0x57e + MX93_PAD_ENET2_RD0__ENET1_RGMII_RD0 0x57e + MX93_PAD_ENET2_RD1__ENET1_RGMII_RD1 0x57e + MX93_PAD_ENET2_RD2__ENET1_RGMII_RD2 0x57e + MX93_PAD_ENET2_RD3__ENET1_RGMII_RD3 0x57e + MX93_PAD_ENET2_RXC__ENET1_RGMII_RXC 0x58e + MX93_PAD_ENET2_RX_CTL__ENET1_RGMII_RX_CTL 0x57e + MX93_PAD_ENET2_TD0__ENET1_RGMII_TD0 0x57e + MX93_PAD_ENET2_TD1__ENET1_RGMII_TD1 0x57e + MX93_PAD_ENET2_TD2__ENET1_RGMII_TD2 0x57e + MX93_PAD_ENET2_TD3__ENET1_RGMII_TD3 0x57e + MX93_PAD_ENET2_TXC__ENET1_RGMII_TXC 0x58e + MX93_PAD_ENET2_TX_CTL__ENET1_RGMII_TX_CTL 0x57e + >; + }; + + pinctrl_fec_sleep: fecsleepgrp { + fsl,pins = < + MX93_PAD_ENET2_MDC__GPIO4_IO14 0x51e + MX93_PAD_ENET2_MDIO__GPIO4_IO15 0x51e + MX93_PAD_ENET2_RD0__GPIO4_IO24 0x51e + MX93_PAD_ENET2_RD1__GPIO4_IO25 0x51e + MX93_PAD_ENET2_RD2__GPIO4_IO26 0x51e + MX93_PAD_ENET2_RD3__GPIO4_IO27 0x51e + MX93_PAD_ENET2_RXC__GPIO4_IO23 0x51e + MX93_PAD_ENET2_RX_CTL__GPIO4_IO22 0x51e + MX93_PAD_ENET2_TD0__GPIO4_IO19 0x51e + MX93_PAD_ENET2_TD1__GPIO4_IO18 0x51e + MX93_PAD_ENET2_TD2__GPIO4_IO17 0x51e + MX93_PAD_ENET2_TD3__GPIO4_IO16 0x51e + MX93_PAD_ENET2_TXC__GPIO4_IO21 0x51e + MX93_PAD_ENET2_TX_CTL__GPIO4_IO20 0x51e + >; + }; + + pinctrl_flexcan2: flexcan2grp { + fsl,pins = < + MX93_PAD_GPIO_IO25__CAN2_TX 0x139e + MX93_PAD_GPIO_IO27__CAN2_RX 0x139e + >; + }; + + pinctrl_flexcan2_sleep: flexcan2sleepgrp { + fsl,pins = < + MX93_PAD_GPIO_IO25__GPIO2_IO25 0x31e + MX93_PAD_GPIO_IO27__GPIO2_IO27 0x31e + >; + }; + + pinctrl_lpi2c1: lpi2c1grp { + fsl,pins = < + MX93_PAD_I2C1_SCL__LPI2C1_SCL 0x40000b9e + MX93_PAD_I2C1_SDA__LPI2C1_SDA 0x40000b9e + >; + }; + + pinctrl_lpi2c2: lpi2c2grp { + fsl,pins = < + MX93_PAD_I2C2_SCL__LPI2C2_SCL 0x40000b9e + MX93_PAD_I2C2_SDA__LPI2C2_SDA 0x40000b9e + >; + }; + + pinctrl_lpi2c3: lpi2c3grp { + fsl,pins = < + MX93_PAD_GPIO_IO28__LPI2C3_SDA 0x40000b9e + MX93_PAD_GPIO_IO29__LPI2C3_SCL 0x40000b9e + >; + }; + + pinctrl_pcal6524: pcal6524grp { + fsl,pins = < + MX93_PAD_CCM_CLKO2__GPIO3_IO27 0x31e + >; + }; + + pinctrl_reg_usdhc2_vmmc: regusdhc2vmmcgrp { + fsl,pins = < + MX93_PAD_SD2_RESET_B__GPIO3_IO07 0x31e + >; + }; + + pinctrl_uart1: uart1grp { + fsl,pins = < + MX93_PAD_UART1_RXD__LPUART1_RX 0x31e + MX93_PAD_UART1_TXD__LPUART1_TX 0x31e + >; + }; + + pinctrl_uart5: uart5grp { + fsl,pins = < + MX93_PAD_DAP_TDO_TRACESWO__LPUART5_TX 0x31e + MX93_PAD_DAP_TDI__LPUART5_RX 0x31e + MX93_PAD_DAP_TMS_SWDIO__LPUART5_RTS_B 0x31e + MX93_PAD_DAP_TCLK_SWCLK__LPUART5_CTS_B 0x31e + >; + }; + + /* need to config the SION for data and cmd pad, refer to ERR052021 */ + pinctrl_usdhc1: usdhc1grp { + fsl,pins = < + MX93_PAD_SD1_CLK__USDHC1_CLK 0x1582 + MX93_PAD_SD1_CMD__USDHC1_CMD 0x40001382 + MX93_PAD_SD1_DATA0__USDHC1_DATA0 0x40001382 + MX93_PAD_SD1_DATA1__USDHC1_DATA1 0x40001382 + MX93_PAD_SD1_DATA2__USDHC1_DATA2 0x40001382 + MX93_PAD_SD1_DATA3__USDHC1_DATA3 0x40001382 + MX93_PAD_SD1_DATA4__USDHC1_DATA4 0x40001382 + MX93_PAD_SD1_DATA5__USDHC1_DATA5 0x40001382 + MX93_PAD_SD1_DATA6__USDHC1_DATA6 0x40001382 + MX93_PAD_SD1_DATA7__USDHC1_DATA7 0x40001382 + MX93_PAD_SD1_STROBE__USDHC1_STROBE 0x1582 + >; + }; + + /* need to config the SION for data and cmd pad, refer to ERR052021 */ + pinctrl_usdhc1_100mhz: usdhc1-100mhzgrp { + fsl,pins = < + MX93_PAD_SD1_CLK__USDHC1_CLK 0x158e + MX93_PAD_SD1_CMD__USDHC1_CMD 0x4000138e + MX93_PAD_SD1_DATA0__USDHC1_DATA0 0x4000138e + MX93_PAD_SD1_DATA1__USDHC1_DATA1 0x4000138e + MX93_PAD_SD1_DATA2__USDHC1_DATA2 0x4000138e + MX93_PAD_SD1_DATA3__USDHC1_DATA3 0x4000138e + MX93_PAD_SD1_DATA4__USDHC1_DATA4 0x4000138e + MX93_PAD_SD1_DATA5__USDHC1_DATA5 0x4000138e + MX93_PAD_SD1_DATA6__USDHC1_DATA6 0x4000138e + MX93_PAD_SD1_DATA7__USDHC1_DATA7 0x4000138e + MX93_PAD_SD1_STROBE__USDHC1_STROBE 0x158e + >; + }; + + /* need to config the SION for data and cmd pad, refer to ERR052021 */ + pinctrl_usdhc1_200mhz: usdhc1-200mhzgrp { + fsl,pins = < + MX93_PAD_SD1_CLK__USDHC1_CLK 0x15fe + MX93_PAD_SD1_CMD__USDHC1_CMD 0x400013fe + MX93_PAD_SD1_DATA0__USDHC1_DATA0 0x400013fe + MX93_PAD_SD1_DATA1__USDHC1_DATA1 0x400013fe + MX93_PAD_SD1_DATA2__USDHC1_DATA2 0x400013fe + MX93_PAD_SD1_DATA3__USDHC1_DATA3 0x400013fe + MX93_PAD_SD1_DATA4__USDHC1_DATA4 0x400013fe + MX93_PAD_SD1_DATA5__USDHC1_DATA5 0x400013fe + MX93_PAD_SD1_DATA6__USDHC1_DATA6 0x400013fe + MX93_PAD_SD1_DATA7__USDHC1_DATA7 0x400013fe + MX93_PAD_SD1_STROBE__USDHC1_STROBE 0x15fe + >; + }; + + pinctrl_usdhc2_gpio: usdhc2gpiogrp { + fsl,pins = < + MX93_PAD_SD2_CD_B__GPIO3_IO00 0x31e + >; + }; + + pinctrl_usdhc2_gpio_sleep: usdhc2gpiosleepgrp { + fsl,pins = < + MX93_PAD_SD2_CD_B__GPIO3_IO00 0x51e + >; + }; + + /* need to config the SION for data and cmd pad, refer to ERR052021 */ + pinctrl_usdhc2: usdhc2grp { + fsl,pins = < + MX93_PAD_SD2_CLK__USDHC2_CLK 0x1582 + MX93_PAD_SD2_CMD__USDHC2_CMD 0x40001382 + MX93_PAD_SD2_DATA0__USDHC2_DATA0 0x40001382 + MX93_PAD_SD2_DATA1__USDHC2_DATA1 0x40001382 + MX93_PAD_SD2_DATA2__USDHC2_DATA2 0x40001382 + MX93_PAD_SD2_DATA3__USDHC2_DATA3 0x40001382 + MX93_PAD_SD2_VSELECT__USDHC2_VSELECT 0x51e + >; + }; + + /* need to config the SION for data and cmd pad, refer to ERR052021 */ + pinctrl_usdhc2_100mhz: usdhc2-100mhzgrp { + fsl,pins = < + MX93_PAD_SD2_CLK__USDHC2_CLK 0x158e + MX93_PAD_SD2_CMD__USDHC2_CMD 0x4000138e + MX93_PAD_SD2_DATA0__USDHC2_DATA0 0x4000138e + MX93_PAD_SD2_DATA1__USDHC2_DATA1 0x4000138e + MX93_PAD_SD2_DATA2__USDHC2_DATA2 0x4000138e + MX93_PAD_SD2_DATA3__USDHC2_DATA3 0x4000138e + MX93_PAD_SD2_VSELECT__USDHC2_VSELECT 0x51e + >; + }; + + /* need to config the SION for data and cmd pad, refer to ERR052021 */ + pinctrl_usdhc2_200mhz: usdhc2-200mhzgrp { + fsl,pins = < + MX93_PAD_SD2_CLK__USDHC2_CLK 0x15fe + MX93_PAD_SD2_CMD__USDHC2_CMD 0x400013fe + MX93_PAD_SD2_DATA0__USDHC2_DATA0 0x400013fe + MX93_PAD_SD2_DATA1__USDHC2_DATA1 0x400013fe + MX93_PAD_SD2_DATA2__USDHC2_DATA2 0x400013fe + MX93_PAD_SD2_DATA3__USDHC2_DATA3 0x400013fe + MX93_PAD_SD2_VSELECT__USDHC2_VSELECT 0x51e + >; + }; + + pinctrl_usdhc2_sleep: usdhc2-sleepgrp { + fsl,pins = < + MX93_PAD_SD2_CLK__GPIO3_IO01 0x51e + MX93_PAD_SD2_CMD__GPIO3_IO02 0x51e + MX93_PAD_SD2_DATA0__GPIO3_IO03 0x51e + MX93_PAD_SD2_DATA1__GPIO3_IO04 0x51e + MX93_PAD_SD2_DATA2__GPIO3_IO05 0x51e + MX93_PAD_SD2_DATA3__GPIO3_IO06 0x51e + MX93_PAD_SD2_VSELECT__GPIO3_IO19 0x51e + >; + }; + + pinctrl_wdog: wdoggrp { + fsl,pins = < + MX93_PAD_WDOG_ANY__WDOG1_WDOG_ANY 0x31e + >; + }; +}; diff --git a/arch/arm64/boot/dts/freescale/imx93-11x11-frdm.dts b/arch/arm64/boot/dts/freescale/imx93-11x11-frdm.dts index bd14ba28690c..8034992a73c7 100644 --- a/arch/arm64/boot/dts/freescale/imx93-11x11-frdm.dts +++ b/arch/arm64/boot/dts/freescale/imx93-11x11-frdm.dts @@ -1,71 +1,14 @@ // SPDX-License-Identifier: (GPL-2.0+ OR MIT) + /dts-v1/; -#include #include "imx93.dtsi" +#include "imx93-11x11-frdm-common.dtsi" / { compatible = "fsl,imx93-11x11-frdm", "fsl,imx93"; model = "NXP i.MX93 11X11 FRDM board"; - aliases { - can0 = &flexcan2; - ethernet0 = &fec; - ethernet1 = &eqos; - i2c0 = &lpi2c1; - i2c1 = &lpi2c2; - i2c2 = &lpi2c3; - mmc0 = &usdhc1; /* EMMC */ - mmc1 = &usdhc2; /* uSD */ - rtc0 = &pcf2131; - serial0 = &lpuart1; - serial4 = &lpuart5; - }; - - chosen { - stdout-path = &lpuart1; - }; - - flexcan2_phy: can-phy { - compatible = "nxp,tja1051"; - #phy-cells = <0>; - max-bitrate = <5000000>; - silent-gpios = <&pcal6524 23 GPIO_ACTIVE_HIGH>; - }; - - gpio-keys { - compatible = "gpio-keys"; - - button-k2 { - label = "Button K2"; - linux,code = ; - gpios = <&pcal6524 5 (GPIO_ACTIVE_LOW | GPIO_PULL_UP)>; - interrupt-parent = <&pcal6524>; - interrupts = <5 IRQ_TYPE_EDGE_FALLING>; - }; - - button-k3 { - label = "Button K3"; - linux,code = ; - gpios = <&pcal6524 6 (GPIO_ACTIVE_LOW | GPIO_PULL_UP)>; - interrupt-parent = <&pcal6524>; - interrupts = <6 IRQ_TYPE_EDGE_FALLING>; - }; - }; - - reg_usdhc2_vmmc: regulator-usdhc2 { - compatible = "regulator-fixed"; - off-on-delay-us = <12000>; - pinctrl-0 = <&pinctrl_reg_usdhc2_vmmc>; - pinctrl-names = "default"; - regulator-min-microvolt = <3300000>; - regulator-max-microvolt = <3300000>; - regulator-name = "VSD_3V3"; - vin-supply = <&buck4>; - gpio = <&gpio3 7 GPIO_ACTIVE_HIGH>; - enable-active-high; - }; - reg_usdhc3_vmmc: regulator-usdhc3 { compatible = "regulator-fixed"; regulator-name = "VPCIe_3V3"; @@ -76,51 +19,6 @@ reg_usdhc3_vmmc: regulator-usdhc3 { enable-active-high; }; - reserved-memory { - ranges; - #address-cells = <2>; - #size-cells = <2>; - - linux,cma { - compatible = "shared-dma-pool"; - alloc-ranges = <0 0x80000000 0 0x30000000>; - reusable; - size = <0 0x10000000>; - linux,cma-default; - }; - - rsc_table: rsc-table@2021e000 { - reg = <0 0x2021e000 0 0x1000>; - no-map; - }; - - vdev0vring0: vdev0vring0@a4000000 { - reg = <0 0xa4000000 0 0x8000>; - no-map; - }; - - vdev0vring1: vdev0vring1@a4008000 { - reg = <0 0xa4008000 0 0x8000>; - no-map; - }; - - vdev1vring0: vdev1vring0@a4010000 { - reg = <0 0xa4010000 0 0x8000>; - no-map; - }; - - vdev1vring1: vdev1vring1@a4018000 { - reg = <0 0xa4018000 0 0x8000>; - no-map; - }; - - vdevbuffer: vdevbuffer@a4020000 { - compatible = "shared-dma-pool"; - reg = <0 0xa4020000 0 0x100000>; - no-map; - }; - }; - sound-mqs { compatible = "fsl,imx-audio-mqs"; model = "mqs-audio"; @@ -134,87 +32,13 @@ usdhc3_pwrseq: mmc-pwrseq { }; }; -&adc1 { - vref-supply = <&buck5>; - status = "okay"; -}; - -&mu1 { - status = "okay"; -}; - -&cm33 { - mboxes = <&mu1 0 1>, - <&mu1 1 1>, - <&mu1 3 1>; - mbox-names = "tx", "rx", "rxdb"; - memory-region = <&vdevbuffer>, <&vdev0vring0>, <&vdev0vring1>, - <&vdev1vring0>, <&vdev1vring1>, <&rsc_table>; - status = "okay"; -}; - -&eqos { - pinctrl-names = "default", "sleep"; - pinctrl-0 = <&pinctrl_eqos>; - pinctrl-1 = <&pinctrl_eqos_sleep>; - phy-handle = <ðphy1>; - phy-mode = "rgmii-id"; - status = "okay"; - - mdio { - compatible = "snps,dwmac-mdio"; - #address-cells = <1>; - #size-cells = <0>; - clock-frequency = <5000000>; - - ethphy1: ethernet-phy@1 { - reg = <1>; - reset-assert-us = <10000>; - reset-deassert-us = <80000>; - reset-gpios = <&pcal6524 15 GPIO_ACTIVE_LOW>; - realtek,clkout-disable; - }; - }; -}; - -&fec { - pinctrl-names = "default", "sleep"; - pinctrl-0 = <&pinctrl_fec>; - pinctrl-1 = <&pinctrl_fec_sleep>; - phy-mode = "rgmii-id"; - phy-handle = <ðphy2>; - fsl,magic-packet; - status = "okay"; - - mdio { - #address-cells = <1>; - #size-cells = <0>; - clock-frequency = <5000000>; - - ethphy2: ethernet-phy@2 { - reg = <2>; - reset-assert-us = <10000>; - reset-deassert-us = <80000>; - reset-gpios = <&pcal6524 16 GPIO_ACTIVE_LOW>; - realtek,clkout-disable; - }; - }; -}; - -&flexcan2 { - phys = <&flexcan2_phy>; - pinctrl-0 = <&pinctrl_flexcan2>; - pinctrl-1 = <&pinctrl_flexcan2_sleep>; - pinctrl-names = "default", "sleep"; - status = "okay"; +&bluetooth { + device-wakeup-gpios = <&pcal6408 3 GPIO_ACTIVE_HIGH>; + reset-gpios = <&pcal6524 19 GPIO_ACTIVE_LOW>; + vcc-supply = <®_usdhc3_vmmc>; }; &lpi2c1 { - clock-frequency = <400000>; - pinctrl-0 = <&pinctrl_lpi2c1>; - pinctrl-names = "default"; - status = "okay"; - pcal6408: gpio@20 { compatible = "nxp,pcal6408"; reg = <0x20>; @@ -224,179 +48,6 @@ pcal6408: gpio@20 { }; }; -&lpi2c2 { - clock-frequency = <400000>; - pinctrl-0 = <&pinctrl_lpi2c2>; - pinctrl-names = "default"; - status = "okay"; - - pcal6524: gpio@22 { - compatible = "nxp,pcal6524"; - reg = <0x22>; - #interrupt-cells = <2>; - interrupt-controller; - interrupt-parent = <&gpio3>; - interrupts = <27 IRQ_TYPE_LEVEL_LOW>; - #gpio-cells = <2>; - gpio-controller; - pinctrl-0 = <&pinctrl_pcal6524>; - pinctrl-names = "default"; - /* does not boot with supplier set, because it is the bucks interrupt parent */ - /* vcc-supply = <&buck4>; */ - }; - - pmic@25 { - compatible = "nxp,pca9451a"; - reg = <0x25>; - interrupt-parent = <&pcal6524>; - interrupts = <11 IRQ_TYPE_EDGE_FALLING>; - - regulators { - - buck1: BUCK1 { - regulator-name = "VDD_SOC_0V8"; - regulator-min-microvolt = <610000>; - regulator-max-microvolt = <950000>; - regulator-always-on; - regulator-boot-on; - regulator-ramp-delay = <3125>; - }; - - buck2: BUCK2 { - regulator-name = "LPD4_x_VDDQ_0V6"; - regulator-min-microvolt = <600000>; - regulator-max-microvolt = <670000>; - regulator-always-on; - regulator-boot-on; - regulator-ramp-delay = <3125>; - }; - - buck4: BUCK4 { - regulator-name = "VDD_3V3"; - regulator-min-microvolt = <3300000>; - regulator-max-microvolt = <3300000>; - regulator-always-on; - regulator-boot-on; - }; - - buck5: BUCK5 { - regulator-name = "VDD_1V8"; - regulator-min-microvolt = <1800000>; - regulator-max-microvolt = <1800000>; - regulator-always-on; - regulator-boot-on; - }; - - buck6: BUCK6 { - regulator-name = "LPD4_x_VDD2_1V1"; - regulator-min-microvolt = <1060000>; - regulator-max-microvolt = <1140000>; - regulator-always-on; - regulator-boot-on; - }; - - ldo1: LDO1 { - regulator-name = "NVCC_BBSM_1V8"; - regulator-min-microvolt = <1620000>; - regulator-max-microvolt = <1980000>; - regulator-always-on; - regulator-boot-on; - }; - - ldo4: LDO4 { - regulator-name = "VDD_ANA_0V8"; - regulator-min-microvolt = <800000>; - regulator-max-microvolt = <840000>; - regulator-always-on; - regulator-boot-on; - }; - - ldo5: LDO5 { - regulator-name = "NVCC_SD"; - regulator-min-microvolt = <1800000>; - regulator-max-microvolt = <3300000>; - regulator-always-on; - regulator-boot-on; - }; - }; - }; - - eeprom: eeprom@50 { - compatible = "atmel,24c256"; - reg = <0x50>; - pagesize = <64>; - vcc-supply = <&buck4>; - }; -}; - -&lpi2c3 { - clock-frequency = <400000>; - pinctrl-0 = <&pinctrl_lpi2c3>; - pinctrl-names = "default"; - status = "okay"; - - ptn5110: tcpc@50 { - compatible = "nxp,ptn5110", "tcpci"; - reg = <0x50>; - interrupt-parent = <&gpio3>; - interrupts = <27 IRQ_TYPE_LEVEL_LOW>; - - typec1_con: connector { - compatible = "usb-c-connector"; - data-role = "dual"; - label = "USB-C"; - op-sink-microwatt = <15000000>; - power-role = "dual"; - self-powered; - sink-pdos = ; - source-pdos = ; - try-power-role = "sink"; - - ports { - #address-cells = <1>; - #size-cells = <0>; - - port@0 { - reg = <0>; - - typec1_dr_sw: endpoint { - remote-endpoint = <&usb1_drd_sw>; - }; - }; - }; - }; - }; - - pcf2131: rtc@53 { - compatible = "nxp,pcf2131"; - reg = <0x53>; - interrupt-parent = <&pcal6524>; - interrupts = <1 IRQ_TYPE_EDGE_FALLING>; - }; -}; - -&lpuart1 { /* console */ - pinctrl-0 = <&pinctrl_uart1>; - pinctrl-names = "default"; - status = "okay"; -}; - -&lpuart5 { - pinctrl-0 = <&pinctrl_uart5>; - pinctrl-names = "default"; - status = "okay"; - - uart-has-rtscts; - - bluetooth { - compatible = "nxp,88w8987-bt"; - device-wakeup-gpios = <&pcal6408 3 GPIO_ACTIVE_HIGH>; - reset-gpios = <&pcal6524 19 GPIO_ACTIVE_LOW>; - vcc-supply = <®_usdhc3_vmmc>; - }; -}; - &mqs1 { pinctrl-names = "default"; pinctrl-0 = <&pinctrl_mqs1>; @@ -418,57 +69,6 @@ &sai1 { status = "okay"; }; -&usbotg1 { - adp-disable; - disable-over-current; - dr_mode = "otg"; - hnp-disable; - srp-disable; - usb-role-switch; - samsung,picophy-dc-vol-level-adjust = <7>; - samsung,picophy-pre-emp-curr-control = <3>; - status = "okay"; - - port { - usb1_drd_sw: endpoint { - remote-endpoint = <&typec1_dr_sw>; - }; - }; -}; - -&usbotg2 { - disable-over-current; - dr_mode = "host"; - samsung,picophy-dc-vol-level-adjust = <7>; - samsung,picophy-pre-emp-curr-control = <3>; - status = "okay"; -}; - -&usdhc1 { - bus-width = <8>; - non-removable; - pinctrl-0 = <&pinctrl_usdhc1>; - pinctrl-1 = <&pinctrl_usdhc1_100mhz>; - pinctrl-2 = <&pinctrl_usdhc1_200mhz>; - pinctrl-names = "default", "state_100mhz", "state_200mhz"; - vmmc-supply = <&buck4>; - status = "okay"; -}; - -&usdhc2 { - bus-width = <4>; - cd-gpios = <&gpio3 00 GPIO_ACTIVE_LOW>; - no-mmc; - no-sdio; - pinctrl-0 = <&pinctrl_usdhc2>, <&pinctrl_usdhc2_gpio>; - pinctrl-1 = <&pinctrl_usdhc2_100mhz>, <&pinctrl_usdhc2_gpio>; - pinctrl-2 = <&pinctrl_usdhc2_200mhz>, <&pinctrl_usdhc2_gpio>; - pinctrl-3 = <&pinctrl_usdhc2_sleep>, <&pinctrl_usdhc2_gpio_sleep>; - pinctrl-names = "default", "state_100mhz", "state_200mhz", "sleep"; - vmmc-supply = <®_usdhc2_vmmc>; - status = "okay"; -}; - &usdhc3 { bus-width = <4>; keep-power-in-suspend; @@ -483,126 +83,7 @@ &usdhc3 { status = "okay"; }; -&wdog3 { - pinctrl-names = "default"; - pinctrl-0 = <&pinctrl_wdog>; - fsl,ext-reset-output; - status = "okay"; -}; - &iomuxc { - - pinctrl_eqos: eqosgrp { - fsl,pins = < - MX93_PAD_ENET1_MDC__ENET_QOS_MDC 0x57e - MX93_PAD_ENET1_MDIO__ENET_QOS_MDIO 0x57e - MX93_PAD_ENET1_RD0__ENET_QOS_RGMII_RD0 0x57e - MX93_PAD_ENET1_RD1__ENET_QOS_RGMII_RD1 0x57e - MX93_PAD_ENET1_RD2__ENET_QOS_RGMII_RD2 0x57e - MX93_PAD_ENET1_RD3__ENET_QOS_RGMII_RD3 0x57e - MX93_PAD_ENET1_RXC__CCM_ENET_QOS_CLOCK_GENERATE_RX_CLK 0x58e - MX93_PAD_ENET1_RX_CTL__ENET_QOS_RGMII_RX_CTL 0x57e - MX93_PAD_ENET1_TD0__ENET_QOS_RGMII_TD0 0x57e - MX93_PAD_ENET1_TD1__ENET_QOS_RGMII_TD1 0x57e - MX93_PAD_ENET1_TD2__ENET_QOS_RGMII_TD2 0x57e - MX93_PAD_ENET1_TD3__ENET_QOS_RGMII_TD3 0x57e - MX93_PAD_ENET1_TXC__CCM_ENET_QOS_CLOCK_GENERATE_TX_CLK 0x58e - MX93_PAD_ENET1_TX_CTL__ENET_QOS_RGMII_TX_CTL 0x57e - >; - }; - - pinctrl_eqos_sleep: eqossleepgrp { - fsl,pins = < - MX93_PAD_ENET1_MDC__GPIO4_IO00 0x31e - MX93_PAD_ENET1_MDIO__GPIO4_IO01 0x31e - MX93_PAD_ENET1_RD0__GPIO4_IO10 0x31e - MX93_PAD_ENET1_RD1__GPIO4_IO11 0x31e - MX93_PAD_ENET1_RD2__GPIO4_IO12 0x31e - MX93_PAD_ENET1_RD3__GPIO4_IO13 0x31e - MX93_PAD_ENET1_RXC__GPIO4_IO09 0x31e - MX93_PAD_ENET1_RX_CTL__GPIO4_IO08 0x31e - MX93_PAD_ENET1_TD0__GPIO4_IO05 0x31e - MX93_PAD_ENET1_TD1__GPIO4_IO04 0x31e - MX93_PAD_ENET1_TD2__GPIO4_IO03 0x31e - MX93_PAD_ENET1_TD3__GPIO4_IO02 0x31e - MX93_PAD_ENET1_TXC__GPIO4_IO07 0x31e - MX93_PAD_ENET1_TX_CTL__GPIO4_IO06 0x31e - >; - }; - - pinctrl_fec: fecgrp { - fsl,pins = < - MX93_PAD_ENET2_MDC__ENET1_MDC 0x57e - MX93_PAD_ENET2_MDIO__ENET1_MDIO 0x57e - MX93_PAD_ENET2_RD0__ENET1_RGMII_RD0 0x57e - MX93_PAD_ENET2_RD1__ENET1_RGMII_RD1 0x57e - MX93_PAD_ENET2_RD2__ENET1_RGMII_RD2 0x57e - MX93_PAD_ENET2_RD3__ENET1_RGMII_RD3 0x57e - MX93_PAD_ENET2_RXC__ENET1_RGMII_RXC 0x58e - MX93_PAD_ENET2_RX_CTL__ENET1_RGMII_RX_CTL 0x57e - MX93_PAD_ENET2_TD0__ENET1_RGMII_TD0 0x57e - MX93_PAD_ENET2_TD1__ENET1_RGMII_TD1 0x57e - MX93_PAD_ENET2_TD2__ENET1_RGMII_TD2 0x57e - MX93_PAD_ENET2_TD3__ENET1_RGMII_TD3 0x57e - MX93_PAD_ENET2_TXC__ENET1_RGMII_TXC 0x58e - MX93_PAD_ENET2_TX_CTL__ENET1_RGMII_TX_CTL 0x57e - >; - }; - - pinctrl_fec_sleep: fecsleepgrp { - fsl,pins = < - MX93_PAD_ENET2_MDC__GPIO4_IO14 0x51e - MX93_PAD_ENET2_MDIO__GPIO4_IO15 0x51e - MX93_PAD_ENET2_RD0__GPIO4_IO24 0x51e - MX93_PAD_ENET2_RD1__GPIO4_IO25 0x51e - MX93_PAD_ENET2_RD2__GPIO4_IO26 0x51e - MX93_PAD_ENET2_RD3__GPIO4_IO27 0x51e - MX93_PAD_ENET2_RXC__GPIO4_IO23 0x51e - MX93_PAD_ENET2_RX_CTL__GPIO4_IO22 0x51e - MX93_PAD_ENET2_TD0__GPIO4_IO19 0x51e - MX93_PAD_ENET2_TD1__GPIO4_IO18 0x51e - MX93_PAD_ENET2_TD2__GPIO4_IO17 0x51e - MX93_PAD_ENET2_TD3__GPIO4_IO16 0x51e - MX93_PAD_ENET2_TXC__GPIO4_IO21 0x51e - MX93_PAD_ENET2_TX_CTL__GPIO4_IO20 0x51e - >; - }; - - pinctrl_flexcan2: flexcan2grp { - fsl,pins = < - MX93_PAD_GPIO_IO25__CAN2_TX 0x139e - MX93_PAD_GPIO_IO27__CAN2_RX 0x139e - >; - }; - - pinctrl_flexcan2_sleep: flexcan2sleepgrp { - fsl,pins = < - MX93_PAD_GPIO_IO25__GPIO2_IO25 0x31e - MX93_PAD_GPIO_IO27__GPIO2_IO27 0x31e - >; - }; - - pinctrl_lpi2c1: lpi2c1grp { - fsl,pins = < - MX93_PAD_I2C1_SCL__LPI2C1_SCL 0x40000b9e - MX93_PAD_I2C1_SDA__LPI2C1_SDA 0x40000b9e - >; - }; - - pinctrl_lpi2c2: lpi2c2grp { - fsl,pins = < - MX93_PAD_I2C2_SCL__LPI2C2_SCL 0x40000b9e - MX93_PAD_I2C2_SDA__LPI2C2_SDA 0x40000b9e - >; - }; - - pinctrl_lpi2c3: lpi2c3grp { - fsl,pins = < - MX93_PAD_GPIO_IO28__LPI2C3_SDA 0x40000b9e - MX93_PAD_GPIO_IO29__LPI2C3_SCL 0x40000b9e - >; - }; - pinctrl_mqs1: mqs1grp { fsl,pins = < MX93_PAD_PDM_CLK__MQS1_LEFT 0x31e @@ -610,149 +91,7 @@ MX93_PAD_PDM_BIT_STREAM0__MQS1_RIGHT 0x31e >; }; - pinctrl_pcal6524: pcal6524grp { - fsl,pins = < - MX93_PAD_CCM_CLKO2__GPIO3_IO27 0x31e - >; - }; - - pinctrl_reg_usdhc2_vmmc: regusdhc2vmmcgrp { - fsl,pins = < - MX93_PAD_SD2_RESET_B__GPIO3_IO07 0x31e - >; - }; - - pinctrl_uart1: uart1grp { - fsl,pins = < - MX93_PAD_UART1_RXD__LPUART1_RX 0x31e - MX93_PAD_UART1_TXD__LPUART1_TX 0x31e - >; - }; - - pinctrl_uart5: uart5grp { - fsl,pins = < - MX93_PAD_DAP_TDO_TRACESWO__LPUART5_TX 0x31e - MX93_PAD_DAP_TDI__LPUART5_RX 0x31e - MX93_PAD_DAP_TMS_SWDIO__LPUART5_RTS_B 0x31e - MX93_PAD_DAP_TCLK_SWCLK__LPUART5_CTS_B 0x31e - >; - }; - /* need to config the SION for data and cmd pad, refer to ERR052021 */ - pinctrl_usdhc1: usdhc1grp { - fsl,pins = < - MX93_PAD_SD1_CLK__USDHC1_CLK 0x1582 - MX93_PAD_SD1_CMD__USDHC1_CMD 0x40001382 - MX93_PAD_SD1_DATA0__USDHC1_DATA0 0x40001382 - MX93_PAD_SD1_DATA1__USDHC1_DATA1 0x40001382 - MX93_PAD_SD1_DATA2__USDHC1_DATA2 0x40001382 - MX93_PAD_SD1_DATA3__USDHC1_DATA3 0x40001382 - MX93_PAD_SD1_DATA4__USDHC1_DATA4 0x40001382 - MX93_PAD_SD1_DATA5__USDHC1_DATA5 0x40001382 - MX93_PAD_SD1_DATA6__USDHC1_DATA6 0x40001382 - MX93_PAD_SD1_DATA7__USDHC1_DATA7 0x40001382 - MX93_PAD_SD1_STROBE__USDHC1_STROBE 0x1582 - >; - }; - - /* need to config the SION for data and cmd pad, refer to ERR052021 */ - pinctrl_usdhc1_100mhz: usdhc1-100mhzgrp { - fsl,pins = < - MX93_PAD_SD1_CLK__USDHC1_CLK 0x158e - MX93_PAD_SD1_CMD__USDHC1_CMD 0x4000138e - MX93_PAD_SD1_DATA0__USDHC1_DATA0 0x4000138e - MX93_PAD_SD1_DATA1__USDHC1_DATA1 0x4000138e - MX93_PAD_SD1_DATA2__USDHC1_DATA2 0x4000138e - MX93_PAD_SD1_DATA3__USDHC1_DATA3 0x4000138e - MX93_PAD_SD1_DATA4__USDHC1_DATA4 0x4000138e - MX93_PAD_SD1_DATA5__USDHC1_DATA5 0x4000138e - MX93_PAD_SD1_DATA6__USDHC1_DATA6 0x4000138e - MX93_PAD_SD1_DATA7__USDHC1_DATA7 0x4000138e - MX93_PAD_SD1_STROBE__USDHC1_STROBE 0x158e - >; - }; - - /* need to config the SION for data and cmd pad, refer to ERR052021 */ - pinctrl_usdhc1_200mhz: usdhc1-200mhzgrp { - fsl,pins = < - MX93_PAD_SD1_CLK__USDHC1_CLK 0x15fe - MX93_PAD_SD1_CMD__USDHC1_CMD 0x400013fe - MX93_PAD_SD1_DATA0__USDHC1_DATA0 0x400013fe - MX93_PAD_SD1_DATA1__USDHC1_DATA1 0x400013fe - MX93_PAD_SD1_DATA2__USDHC1_DATA2 0x400013fe - MX93_PAD_SD1_DATA3__USDHC1_DATA3 0x400013fe - MX93_PAD_SD1_DATA4__USDHC1_DATA4 0x400013fe - MX93_PAD_SD1_DATA5__USDHC1_DATA5 0x400013fe - MX93_PAD_SD1_DATA6__USDHC1_DATA6 0x400013fe - MX93_PAD_SD1_DATA7__USDHC1_DATA7 0x400013fe - MX93_PAD_SD1_STROBE__USDHC1_STROBE 0x15fe - >; - }; - - pinctrl_usdhc2_gpio: usdhc2gpiogrp { - fsl,pins = < - MX93_PAD_SD2_CD_B__GPIO3_IO00 0x31e - >; - }; - - pinctrl_usdhc2_gpio_sleep: usdhc2gpiosleepgrp { - fsl,pins = < - MX93_PAD_SD2_CD_B__GPIO3_IO00 0x51e - >; - }; - - /* need to config the SION for data and cmd pad, refer to ERR052021 */ - pinctrl_usdhc2: usdhc2grp { - fsl,pins = < - MX93_PAD_SD2_CLK__USDHC2_CLK 0x1582 - MX93_PAD_SD2_CMD__USDHC2_CMD 0x40001382 - MX93_PAD_SD2_DATA0__USDHC2_DATA0 0x40001382 - MX93_PAD_SD2_DATA1__USDHC2_DATA1 0x40001382 - MX93_PAD_SD2_DATA2__USDHC2_DATA2 0x40001382 - MX93_PAD_SD2_DATA3__USDHC2_DATA3 0x40001382 - MX93_PAD_SD2_VSELECT__USDHC2_VSELECT 0x51e - >; - }; - - /* need to config the SION for data and cmd pad, refer to ERR052021 */ - pinctrl_usdhc2_100mhz: usdhc2-100mhzgrp { - fsl,pins = < - MX93_PAD_SD2_CLK__USDHC2_CLK 0x158e - MX93_PAD_SD2_CMD__USDHC2_CMD 0x4000138e - MX93_PAD_SD2_DATA0__USDHC2_DATA0 0x4000138e - MX93_PAD_SD2_DATA1__USDHC2_DATA1 0x4000138e - MX93_PAD_SD2_DATA2__USDHC2_DATA2 0x4000138e - MX93_PAD_SD2_DATA3__USDHC2_DATA3 0x4000138e - MX93_PAD_SD2_VSELECT__USDHC2_VSELECT 0x51e - >; - }; - - /* need to config the SION for data and cmd pad, refer to ERR052021 */ - pinctrl_usdhc2_200mhz: usdhc2-200mhzgrp { - fsl,pins = < - MX93_PAD_SD2_CLK__USDHC2_CLK 0x15fe - MX93_PAD_SD2_CMD__USDHC2_CMD 0x400013fe - MX93_PAD_SD2_DATA0__USDHC2_DATA0 0x400013fe - MX93_PAD_SD2_DATA1__USDHC2_DATA1 0x400013fe - MX93_PAD_SD2_DATA2__USDHC2_DATA2 0x400013fe - MX93_PAD_SD2_DATA3__USDHC2_DATA3 0x400013fe - MX93_PAD_SD2_VSELECT__USDHC2_VSELECT 0x51e - >; - }; - - pinctrl_usdhc2_sleep: usdhc2-sleepgrp { - fsl,pins = < - MX93_PAD_SD2_CLK__GPIO3_IO01 0x51e - MX93_PAD_SD2_CMD__GPIO3_IO02 0x51e - MX93_PAD_SD2_DATA0__GPIO3_IO03 0x51e - MX93_PAD_SD2_DATA1__GPIO3_IO04 0x51e - MX93_PAD_SD2_DATA2__GPIO3_IO05 0x51e - MX93_PAD_SD2_DATA3__GPIO3_IO06 0x51e - MX93_PAD_SD2_VSELECT__GPIO3_IO19 0x51e - >; - }; - - /* need to config the SION for data and cmd pad, refer to ERR052021 */ pinctrl_usdhc3: usdhc3grp { fsl,pins = < MX93_PAD_SD3_CLK__USDHC3_CLK 0x1582 @@ -798,10 +137,4 @@ MX93_PAD_SD3_DATA2__GPIO3_IO24 0x31e MX93_PAD_SD3_DATA3__GPIO3_IO25 0x31e >; }; - - pinctrl_wdog: wdoggrp { - fsl,pins = < - MX93_PAD_WDOG_ANY__WDOG1_WDOG_ANY 0x31e - >; - }; }; diff --git a/arch/arm64/boot/dts/freescale/imx93-14x14-evk.dts b/arch/arm64/boot/dts/freescale/imx93-14x14-evk.dts index ec78c03f4788..3ea50d808034 100644 --- a/arch/arm64/boot/dts/freescale/imx93-14x14-evk.dts +++ b/arch/arm64/boot/dts/freescale/imx93-14x14-evk.dts @@ -75,7 +75,7 @@ rsc_table: rsc-table@2021e000 { no-map; }; - vdevbuffer: vdevbuffer@a4020000 { + vdev0buffer: vdev0buffer@a4020000 { compatible = "shared-dma-pool"; reg = <0 0xa4020000 0 0x100000>; no-map; @@ -222,7 +222,7 @@ &cm33 { mboxes = <&mu1 0 1>, <&mu1 1 1>, <&mu1 3 1>; - memory-region = <&vdevbuffer>, <&vdev0vring0>, <&vdev0vring1>, + memory-region = <&vdev0buffer>, <&vdev0vring0>, <&vdev0vring1>, <&vdev1vring0>, <&vdev1vring1>, <&rsc_table>; status = "okay"; }; diff --git a/arch/arm64/boot/dts/freescale/imx93-9x9-qsb.dts b/arch/arm64/boot/dts/freescale/imx93-9x9-qsb.dts index 01c11c517986..f07e93653e4e 100644 --- a/arch/arm64/boot/dts/freescale/imx93-9x9-qsb.dts +++ b/arch/arm64/boot/dts/freescale/imx93-9x9-qsb.dts @@ -76,7 +76,7 @@ rsc_table: rsc-table@2021e000 { no-map; }; - vdevbuffer: vdevbuffer@a4020000 { + vdev0buffer: vdev0buffer@a4020000 { compatible = "shared-dma-pool"; reg = <0 0xa4020000 0 0x100000>; no-map; @@ -212,7 +212,7 @@ &cm33 { mboxes = <&mu1 0 1>, <&mu1 1 1>, <&mu1 3 1>; - memory-region = <&vdevbuffer>, <&vdev0vring0>, <&vdev0vring1>, + memory-region = <&vdev0buffer>, <&vdev0vring0>, <&vdev0vring1>, <&vdev1vring0>, <&vdev1vring1>, <&rsc_table>; status = "okay"; }; diff --git a/arch/arm64/boot/dts/freescale/imx94.dtsi b/arch/arm64/boot/dts/freescale/imx94.dtsi index 34833e62bd79..afaaf70417d2 100644 --- a/arch/arm64/boot/dts/freescale/imx94.dtsi +++ b/arch/arm64/boot/dts/freescale/imx94.dtsi @@ -1379,7 +1379,7 @@ pcie0: pcie@4c300000 { <0 0x4c340000 0 0x4000>; reg-names = "dbi", "config", "atu", "app"; ranges = <0x43000000 0x9 0x00000000 0x9 0x00000000 0x0 0xe0000000>, - <0x82000000 0x0 0xe0000000 0x9 0xe0000000 0x0 0x10000000>, + <0x82000000 0x0 0x10000000 0x9 0xe0000000 0x0 0x10000000>, <0x81000000 0x0 0x00000000 0x9 0xf0000000 0x0 0x00100000>; #address-cells = <3>; #size-cells = <2>; diff --git a/arch/arm64/boot/dts/freescale/imx943.dtsi b/arch/arm64/boot/dts/freescale/imx943.dtsi index 01152fd0efa5..a564488d9cd7 100644 --- a/arch/arm64/boot/dts/freescale/imx943.dtsi +++ b/arch/arm64/boot/dts/freescale/imx943.dtsi @@ -219,7 +219,7 @@ pcie1: pcie@4c380000 { <0 0x4c3c0000 0 0x4000>; reg-names = "dbi", "config", "atu", "app"; ranges = <0x43000000 0xa 0x00000000 0xa 0x00000000 0x0 0xe0000000>, - <0x82000000 0x0 0xe0000000 0xa 0xe0000000 0x0 0x10000000>, + <0x82000000 0x0 0x10000000 0xa 0xe0000000 0x0 0x10000000>, <0x81000000 0x0 0x00000000 0xa 0xf0000000 0x0 0x00100000>; #address-cells = <3>; #size-cells = <2>; diff --git a/arch/arm64/boot/dts/freescale/imx95-15x15-frdm.dts b/arch/arm64/boot/dts/freescale/imx95-15x15-frdm.dts index 0f43e3be7058..7ad1a4199ae4 100644 --- a/arch/arm64/boot/dts/freescale/imx95-15x15-frdm.dts +++ b/arch/arm64/boot/dts/freescale/imx95-15x15-frdm.dts @@ -56,7 +56,7 @@ dmic: dmic { num-channels = <2>; }; - flexcan2_phy: can-phy { + flexcan2_phy: can-phy0 { compatible = "nxp,tja1051"; #phy-cells = <0>; max-bitrate = <5000000>; @@ -67,7 +67,7 @@ flexcan2_phy: can-phy { silent-gpios = <&pcal6524 7 GPIO_ACTIVE_HIGH>; }; - flexcan5_phy: can-phy { + flexcan5_phy: can-phy1 { compatible = "nxp,tja1051"; #phy-cells = <0>; max-bitrate = <5000000>; @@ -188,33 +188,33 @@ linux_cma: linux,cma { linux,cma-default; }; - vdev0vring0: memory@88000000 { + vdev0vring0: vdev0vring0@88000000 { reg = <0 0x88000000 0 0x8000>; no-map; }; - vdev0vring1: memory@88008000 { + vdev0vring1: vdev0vring1@88008000 { reg = <0 0x88008000 0 0x8000>; no-map; }; - vdev1vring0: memory@88010000 { + vdev1vring0: vdev1vring0@88010000 { reg = <0 0x88010000 0 0x8000>; no-map; }; - vdev1vring1: memory@88018000 { + vdev1vring1: vdev1vring1@88018000 { reg = <0 0x88018000 0 0x8000>; no-map; }; - vdevbuffer: memory@88020000 { + vdev0buffer: vdev0buffer@88020000 { compatible = "shared-dma-pool"; reg = <0 0x88020000 0 0x100000>; no-map; }; - rsc_table: memory@88220000 { + rsc_table: rsc-table@88220000 { reg = <0 0x88220000 0 0x1000>; no-map; }; diff --git a/arch/arm64/boot/dts/freescale/imx95.dtsi b/arch/arm64/boot/dts/freescale/imx95.dtsi index 38fc47024841..0f03b85aaec1 100644 --- a/arch/arm64/boot/dts/freescale/imx95.dtsi +++ b/arch/arm64/boot/dts/freescale/imx95.dtsi @@ -1948,7 +1948,7 @@ pcie0: pcie@4c300000 { <0 0x4c340000 0 0x4000>; reg-names = "dbi", "config", "atu", "app"; ranges = <0x43000000 0x9 0x00000000 0x9 0x00000000 0x0 0xe0000000>, - <0x82000000 0x0 0xe0000000 0x9 0xe0000000 0x0 0x10000000>, + <0x82000000 0x0 0x10000000 0x9 0xe0000000 0x0 0x10000000>, <0x81000000 0x0 0x00000000 0x9 0xf0000000 0x0 0x00100000>; #address-cells = <3>; #size-cells = <2>; @@ -2039,7 +2039,7 @@ pcie1: pcie@4c380000 { <0 0x4c3c0000 0 0x4000>; reg-names = "dbi", "config", "atu", "app"; ranges = <0x43000000 0xa 0x00000000 0xa 0x00000000 0x0 0xe0000000>, - <0x82000000 0x0 0xe0000000 0xa 0xe0000000 0x0 0x10000000>, + <0x82000000 0x0 0x10000000 0xa 0xe0000000 0x0 0x10000000>, <0x81000000 0x0 0x00000000 0xa 0xf0000000 0x0 0x00100000>; #address-cells = <3>; #size-cells = <2>; diff --git a/arch/arm64/boot/dts/mediatek/mt6878-pinfunc.h b/arch/arm64/boot/dts/mediatek/mt6878-pinfunc.h index 4e8e475a7454..5aeceb904b18 100644 --- a/arch/arm64/boot/dts/mediatek/mt6878-pinfunc.h +++ b/arch/arm64/boot/dts/mediatek/mt6878-pinfunc.h @@ -9,7 +9,7 @@ #ifndef __MT6878_PINFUNC_H #define __MT6878_PINFUNC_H -#include "mt65xx.h" +#include #define PINMUX_GPIO0__FUNC_GPIO0 (MTK_PIN_NO(0) | 0) #define PINMUX_GPIO0__FUNC_TP_GPIO0_AO (MTK_PIN_NO(0) | 1) diff --git a/arch/arm64/boot/dts/mediatek/mt6893-pinfunc.h b/arch/arm64/boot/dts/mediatek/mt6893-pinfunc.h index 982bc95c471c..7cda5c73fb68 100644 --- a/arch/arm64/boot/dts/mediatek/mt6893-pinfunc.h +++ b/arch/arm64/boot/dts/mediatek/mt6893-pinfunc.h @@ -7,7 +7,7 @@ #ifndef __MT6893_PINFUNC_H #define __MT6893_PINFUNC_H -#include "mt65xx.h" +#include #define PINMUX_GPIO0__FUNC_GPIO0 (MTK_PIN_NO(0) | 0) #define PINMUX_GPIO0__FUNC_SPI6_CLK (MTK_PIN_NO(0) | 1) diff --git a/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn13.dtso b/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn13.dtso index 973b76ba0cbf..e9c322df15fc 100644 --- a/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn13.dtso +++ b/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn13.dtso @@ -16,5 +16,6 @@ / { }; &{/soc/pinctrl@1001f000/pcie-2-hog} { + line-name = "pcie2-cn13-hog"; output-high; }; diff --git a/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn14.dtso b/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn14.dtso index 90b2a64459c3..9d8de737ca40 100644 --- a/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn14.dtso +++ b/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn14.dtso @@ -16,5 +16,6 @@ / { }; &{/soc/pinctrl@1001f000/pcie-3-hog} { + line-name = "pcie3-cn14-hog"; output-high; }; diff --git a/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn15.dtso b/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn15.dtso index 9750916042de..57ee7dacdd78 100644 --- a/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn15.dtso +++ b/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn15.dtso @@ -16,5 +16,6 @@ / { }; &{/soc/pinctrl@1001f000/pcie-2-hog} { + line-name = "pcie2-cn15-hog"; output-low; }; diff --git a/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn18.dtso b/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn18.dtso index 9830fb0fd97a..7830980ac95a 100644 --- a/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn18.dtso +++ b/arch/arm64/boot/dts/mediatek/mt7988a-bananapi-bpi-r4-pro-cn18.dtso @@ -16,5 +16,6 @@ / { }; &{/soc/pinctrl@1001f000/pcie-3-hog} { + line-name = "pcie3-cn18-hog"; output-low; }; diff --git a/arch/arm64/boot/dts/mediatek/mt8173-elm.dtsi b/arch/arm64/boot/dts/mediatek/mt8173-elm.dtsi index a0573bc359fb..777da2129e77 100644 --- a/arch/arm64/boot/dts/mediatek/mt8173-elm.dtsi +++ b/arch/arm64/boot/dts/mediatek/mt8173-elm.dtsi @@ -16,6 +16,11 @@ aliases { mmc2 = &mmc3; }; + firmware { + #address-cells = <2>; + #size-cells = <2>; + }; + memory@40000000 { device_type = "memory"; reg = <0 0x40000000 0 0x80000000>; diff --git a/arch/arm64/boot/dts/mediatek/mt8173.dtsi b/arch/arm64/boot/dts/mediatek/mt8173.dtsi index 78c2ccd5be13..556e806b7787 100644 --- a/arch/arm64/boot/dts/mediatek/mt8173.dtsi +++ b/arch/arm64/boot/dts/mediatek/mt8173.dtsi @@ -505,7 +505,7 @@ power-domain@MT8173_POWER_DOMAIN_USB { }; mfg_async: power-domain@MT8173_POWER_DOMAIN_MFG_ASYNC { reg = ; - clocks = <&clk26m>; + clocks = <&topckgen CLK_TOP_AXI_MFG_IN_SEL>; clock-names = "mfg"; #address-cells = <1>; #size-cells = <0>; diff --git a/arch/arm64/boot/dts/mediatek/mt8183-kukui.dtsi b/arch/arm64/boot/dts/mediatek/mt8183-kukui.dtsi index 69cab9f9c530..acd5f59b0d4c 100644 --- a/arch/arm64/boot/dts/mediatek/mt8183-kukui.dtsi +++ b/arch/arm64/boot/dts/mediatek/mt8183-kukui.dtsi @@ -22,6 +22,11 @@ chosen { stdout-path = "serial0:115200n8"; }; + firmware { + #address-cells = <2>; + #size-cells = <2>; + }; + backlight_lcd0: backlight_lcd0 { compatible = "pwm-backlight"; pwms = <&pwm0 0 500000>; diff --git a/arch/arm64/boot/dts/mediatek/mt8186-corsola.dtsi b/arch/arm64/boot/dts/mediatek/mt8186-corsola.dtsi index ff20376a44d7..2b327d9ef65e 100644 --- a/arch/arm64/boot/dts/mediatek/mt8186-corsola.dtsi +++ b/arch/arm64/boot/dts/mediatek/mt8186-corsola.dtsi @@ -26,6 +26,11 @@ chosen { stdout-path = "serial0:115200n8"; }; + firmware { + #address-cells = <2>; + #size-cells = <2>; + }; + memory@40000000 { device_type = "memory"; /* The size should be filled in by the bootloader. */ diff --git a/arch/arm64/boot/dts/mediatek/mt8188-geralt.dtsi b/arch/arm64/boot/dts/mediatek/mt8188-geralt.dtsi index f382f90c48f5..801eee735afe 100644 --- a/arch/arm64/boot/dts/mediatek/mt8188-geralt.dtsi +++ b/arch/arm64/boot/dts/mediatek/mt8188-geralt.dtsi @@ -41,6 +41,11 @@ dmic-codec { wakeup-delay-ms = <100>; }; + firmware { + #address-cells = <2>; + #size-cells = <2>; + }; + memory@40000000 { device_type = "memory"; /* The size will be filled in by the bootloader */ @@ -166,7 +171,7 @@ reserved_memory: reserved-memory { scp_mem_reserved: memory@50000000 { compatible = "shared-dma-pool"; - reg = <0 0x50000000 0 0x800000>; + reg = <0 0x50000000 0 0x900000>; no-map; }; diff --git a/arch/arm64/boot/dts/mediatek/mt8192-asurada.dtsi b/arch/arm64/boot/dts/mediatek/mt8192-asurada.dtsi index 40d34b16dc80..e8ebbb74987f 100644 --- a/arch/arm64/boot/dts/mediatek/mt8192-asurada.dtsi +++ b/arch/arm64/boot/dts/mediatek/mt8192-asurada.dtsi @@ -25,6 +25,11 @@ chosen { stdout-path = "serial0:115200n8"; }; + firmware { + #address-cells = <2>; + #size-cells = <2>; + }; + memory@40000000 { device_type = "memory"; reg = <0 0x40000000 0 0x80000000>; diff --git a/arch/arm64/boot/dts/mediatek/mt8195-cherry.dtsi b/arch/arm64/boot/dts/mediatek/mt8195-cherry.dtsi index ef7afc436aef..f06ca2bc165d 100644 --- a/arch/arm64/boot/dts/mediatek/mt8195-cherry.dtsi +++ b/arch/arm64/boot/dts/mediatek/mt8195-cherry.dtsi @@ -42,6 +42,11 @@ dmic-codec { wakeup-delay-ms = <50>; }; + firmware { + #address-cells = <2>; + #size-cells = <2>; + }; + memory@40000000 { device_type = "memory"; reg = <0 0x40000000 0 0x80000000>; diff --git a/arch/arm64/boot/dts/qcom/agatti.dtsi b/arch/arm64/boot/dts/qcom/agatti.dtsi index 590bd2432d85..d010ef7fdf8c 100644 --- a/arch/arm64/boot/dts/qcom/agatti.dtsi +++ b/arch/arm64/boot/dts/qcom/agatti.dtsi @@ -381,6 +381,14 @@ rmtfs_mem: memory@89b01000 { qcom,client-id = <1>; qcom,vmid = ; }; + + adsp_rpc_remote_heap_mem: adsp-rpc-remote-heap { + compatible = "shared-dma-pool"; + alloc-ranges = <0x0 0x0 0x1 0x0>; + reusable; + alignment = <0x0 0x400000>; + size = <0x0 0x800000>; + }; }; smp2p-adsp { @@ -2348,6 +2356,9 @@ fastrpc { compatible = "qcom,fastrpc"; qcom,glink-channels = "fastrpcglink-apps-dsp"; label = "adsp"; + memory-region = <&adsp_rpc_remote_heap_mem>; + qcom,vmids = ; qcom,non-secure-domain; diff --git a/arch/arm64/boot/dts/qcom/eliza.dtsi b/arch/arm64/boot/dts/qcom/eliza.dtsi index 66ea4aaafd73..45853c11a03c 100644 --- a/arch/arm64/boot/dts/qcom/eliza.dtsi +++ b/arch/arm64/boot/dts/qcom/eliza.dtsi @@ -655,7 +655,7 @@ gcc: clock-controller@100000 { <&ufs_mem_phy 0>, <&ufs_mem_phy 1>, <&ufs_mem_phy 2>, - <0>; + <&usb_dp_qmpphy QMP_USB43DP_USB3_PIPE_CLK>; power-domains = <&rpmhpd RPMHPD_CX>; diff --git a/arch/arm64/boot/dts/qcom/glymur-asus-zenbook-a16-ux3607oa.dts b/arch/arm64/boot/dts/qcom/glymur-asus-zenbook-a16-ux3607oa.dts index 939e1a927a79..95da35125d75 100644 --- a/arch/arm64/boot/dts/qcom/glymur-asus-zenbook-a16-ux3607oa.dts +++ b/arch/arm64/boot/dts/qcom/glymur-asus-zenbook-a16-ux3607oa.dts @@ -737,7 +737,7 @@ &lpass_vamacro { pinctrl-0 = <&dmic01_default>; pinctrl-names = "default"; - qcom,dmic-sample-rate = <4800000>; + qcom,dmic-sample-rate = <2400000>; }; &mdss { @@ -861,7 +861,6 @@ nvme_reg_en: nvme-reg-en-state { }; &pmk8850_rtc { - qcom,uefi-rtc-info; qcom,no-alarm; }; diff --git a/arch/arm64/boot/dts/qcom/glymur-crd.dtsi b/arch/arm64/boot/dts/qcom/glymur-crd.dtsi index e27c697e3170..4df3ccfee106 100644 --- a/arch/arm64/boot/dts/qcom/glymur-crd.dtsi +++ b/arch/arm64/boot/dts/qcom/glymur-crd.dtsi @@ -963,7 +963,8 @@ &remoteproc_soccp { &tlmm { gpio-reserved-ranges = <4 4>, /* EC TZ Secure I3C */ <10 2>, /* OOB UART */ - <44 4>; /* Security SPI (TPM) */ + <44 4>, /* Security SPI (TPM) */ + <65 1>; /* EC reset */ edp_bl_en: edp-bl-en-state { pins = "gpio18"; diff --git a/arch/arm64/boot/dts/qcom/glymur.dtsi b/arch/arm64/boot/dts/qcom/glymur.dtsi index f04058d2e089..c947dc737a53 100644 --- a/arch/arm64/boot/dts/qcom/glymur.dtsi +++ b/arch/arm64/boot/dts/qcom/glymur.dtsi @@ -4572,6 +4572,10 @@ usb_0: usb@a600000 { "noc_aggr_north", "noc_aggr_south"; + assigned-clocks = <&gcc GCC_USB30_PRIM_MOCK_UTMI_CLK>, + <&gcc GCC_USB30_PRIM_MASTER_CLK>; + assigned-clock-rates = <19200000>, <200000000>; + interrupts-extended = <&intc GIC_SPI 140 IRQ_TYPE_LEVEL_HIGH>, <&intc GIC_SPI 371 IRQ_TYPE_LEVEL_HIGH>, <&pdc 90 IRQ_TYPE_EDGE_BOTH>, @@ -4584,9 +4588,18 @@ usb_0: usb@a600000 { "ss_phy_irq"; power-domains = <&gcc GCC_USB30_PRIM_GDSC>; + required-opps = <&rpmhpd_opp_nom>; resets = <&gcc GCC_USB30_PRIM_BCR>; iommus = <&apps_smmu 0x1420 0x0>; + + interconnects = <&aggre4_noc MASTER_USB3_0 QCOM_ICC_TAG_ALWAYS + &mc_virt SLAVE_EBI1 QCOM_ICC_TAG_ALWAYS>, + <&hsc_noc MASTER_APPSS_PROC QCOM_ICC_TAG_ACTIVE_ONLY + &config_noc SLAVE_USB3_0 QCOM_ICC_TAG_ACTIVE_ONLY>; + interconnect-names = "usb-ddr", + "apps-usb"; + phys = <&usb_0_hsphy>, <&usb_0_qmpphy QMP_USB43DP_USB3_PHY>; phy-names = "usb2-phy", @@ -4605,6 +4618,8 @@ usb_0: usb@a600000 { usb-role-switch; wakeup-source; + dma-coherent; + status = "disabled"; ports { @@ -4647,6 +4662,10 @@ usb_1: usb@a800000 { "noc_aggr_north", "noc_aggr_south"; + assigned-clocks = <&gcc GCC_USB30_SEC_MOCK_UTMI_CLK>, + <&gcc GCC_USB30_SEC_MASTER_CLK>; + assigned-clock-rates = <19200000>, <200000000>; + interrupts-extended = <&intc GIC_SPI 875 IRQ_TYPE_LEVEL_HIGH>, <&intc GIC_SPI 369 IRQ_TYPE_LEVEL_HIGH>, <&pdc 88 IRQ_TYPE_EDGE_BOTH>, @@ -4660,9 +4679,17 @@ usb_1: usb@a800000 { resets = <&gcc GCC_USB30_SEC_BCR>; power-domains = <&gcc GCC_USB30_SEC_GDSC>; + required-opps = <&rpmhpd_opp_nom>; iommus = <&apps_smmu 0x1460 0x0>; + interconnects = <&aggre4_noc MASTER_USB3_1 QCOM_ICC_TAG_ALWAYS + &mc_virt SLAVE_EBI1 QCOM_ICC_TAG_ALWAYS>, + <&hsc_noc MASTER_APPSS_PROC QCOM_ICC_TAG_ACTIVE_ONLY + &config_noc SLAVE_USB3_1 QCOM_ICC_TAG_ACTIVE_ONLY>; + interconnect-names = "usb-ddr", + "apps-usb"; + phys = <&usb_1_hsphy>, <&usb_1_qmpphy QMP_USB43DP_USB3_PHY>; phy-names = "usb2-phy", @@ -4681,6 +4708,8 @@ usb_1: usb@a800000 { usb-role-switch; wakeup-source; + dma-coherent; + status = "disabled"; ports { @@ -4723,6 +4752,10 @@ usb_2: usb@a000000 { "noc_aggr_north", "noc_aggr_south"; + assigned-clocks = <&gcc GCC_USB30_TERT_MOCK_UTMI_CLK>, + <&gcc GCC_USB30_TERT_MASTER_CLK>; + assigned-clock-rates = <19200000>, <200000000>; + interrupts-extended = <&intc GIC_SPI 871 IRQ_TYPE_LEVEL_HIGH>, <&intc GIC_SPI 370 IRQ_TYPE_LEVEL_HIGH>, <&pdc 89 IRQ_TYPE_EDGE_BOTH>, @@ -4736,9 +4769,17 @@ usb_2: usb@a000000 { resets = <&gcc GCC_USB30_TERT_BCR>; power-domains = <&gcc GCC_USB30_TERT_GDSC>; + required-opps = <&rpmhpd_opp_nom>; iommus = <&apps_smmu 0x420 0x0>; + interconnects = <&aggre2_noc MASTER_USB3_2 QCOM_ICC_TAG_ALWAYS + &mc_virt SLAVE_EBI1 QCOM_ICC_TAG_ALWAYS>, + <&hsc_noc MASTER_APPSS_PROC QCOM_ICC_TAG_ACTIVE_ONLY + &config_noc SLAVE_USB3_2 QCOM_ICC_TAG_ACTIVE_ONLY>; + interconnect-names = "usb-ddr", + "apps-usb"; + phys = <&usb_2_hsphy>, <&usb_2_qmpphy QMP_USB43DP_USB3_PHY>; phy-names = "usb2-phy", @@ -4757,6 +4798,8 @@ usb_2: usb@a000000 { usb-role-switch; wakeup-source; + dma-coherent; + status = "disabled"; ports { @@ -4847,6 +4890,8 @@ &mc_virt SLAVE_EBI1 QCOM_ICC_TAG_ALWAYS>, usb-role-switch; wakeup-source; + dma-coherent; + status = "disabled"; }; @@ -4869,6 +4914,10 @@ usb_mp: usb@a400000 { "noc_aggr_north", "noc_aggr_south"; + assigned-clocks = <&gcc GCC_USB30_MP_MOCK_UTMI_CLK>, + <&gcc GCC_USB30_MP_MASTER_CLK>; + assigned-clock-rates = <19200000>, <200000000>; + interrupts-extended = <&intc GIC_SPI 132 IRQ_TYPE_LEVEL_HIGH>, <&intc GIC_SPI 345 IRQ_TYPE_LEVEL_HIGH>, <&intc GIC_SPI 346 IRQ_TYPE_LEVEL_HIGH>, @@ -4894,9 +4943,17 @@ usb_mp: usb@a400000 { resets = <&gcc GCC_USB30_MP_BCR>; power-domains = <&gcc GCC_USB30_MP_GDSC>; + required-opps = <&rpmhpd_opp_nom>; iommus = <&apps_smmu 0xda0 0x0>; + interconnects = <&aggre3_noc MASTER_USB3_MP QCOM_ICC_TAG_ALWAYS + &mc_virt SLAVE_EBI1 QCOM_ICC_TAG_ALWAYS>, + <&hsc_noc MASTER_APPSS_PROC QCOM_ICC_TAG_ACTIVE_ONLY + &config_noc SLAVE_USB3_MP QCOM_ICC_TAG_ACTIVE_ONLY>; + interconnect-names = "usb-ddr", + "apps-usb"; + phys = <&usb_mp_hsphy0>, <&usb_mp_qmpphy0>, <&usb_mp_hsphy1>, @@ -4919,6 +4976,8 @@ usb_mp: usb@a400000 { dr_mode = "host"; wakeup-source; + dma-coherent; + status = "disabled"; }; diff --git a/arch/arm64/boot/dts/qcom/hamoa-iot-evk.dts b/arch/arm64/boot/dts/qcom/hamoa-iot-evk.dts index 9fa86bb6438e..b8bb9bb70db7 100644 --- a/arch/arm64/boot/dts/qcom/hamoa-iot-evk.dts +++ b/arch/arm64/boot/dts/qcom/hamoa-iot-evk.dts @@ -35,6 +35,18 @@ mcp2518fd_osc: clock-40000000 { clock-frequency = <40000000>; #clock-cells = <0>; }; + + clk_rtmr1_xo: clock-rtmr1-xo { + compatible = "fixed-clock"; + clock-frequency = <25000000>; + #clock-cells = <0>; + }; + + clk_rtmr2_xo: clock-rtmr2-xo { + compatible = "fixed-clock"; + clock-frequency = <25000000>; + #clock-cells = <0>; + }; }; wcd938x: audio-codec { @@ -745,7 +757,7 @@ typec-mux@8 { compatible = "parade,ps8830"; reg = <0x08>; - clocks = <&rpmhcc RPMH_RF_CLK5>; + clocks = <&clk_rtmr2_xo>; vdd-supply = <&vreg_rtmr2_1p15>; vdd33-supply = <&vreg_rtmr2_3p3>; @@ -860,7 +872,7 @@ typec-mux@8 { compatible = "parade,ps8830"; reg = <0x8>; - clocks = <&rpmhcc RPMH_RF_CLK4>; + clocks = <&clk_rtmr1_xo>; vdd-supply = <&vreg_rtmr1_1p15>; vdd33-supply = <&vreg_rtmr1_3p3>; diff --git a/arch/arm64/boot/dts/qcom/kaanapali.dtsi b/arch/arm64/boot/dts/qcom/kaanapali.dtsi index 131fd2a16c54..c1528cc8b7b3 100644 --- a/arch/arm64/boot/dts/qcom/kaanapali.dtsi +++ b/arch/arm64/boot/dts/qcom/kaanapali.dtsi @@ -552,6 +552,8 @@ gcc: clock-controller@100000 { <&ufs_mem_phy 2>, <0>; + power-domains = <&rpmhpd RPMHPD_CX>; + #clock-cells = <1>; #reset-cells = <1>; #power-domain-cells = <1>; diff --git a/arch/arm64/boot/dts/qcom/lemans-evk-ifp-mezzanine.dtso b/arch/arm64/boot/dts/qcom/lemans-evk-ifp-mezzanine.dtso index 6cfa0bc1440e..e34639460a96 100644 --- a/arch/arm64/boot/dts/qcom/lemans-evk-ifp-mezzanine.dtso +++ b/arch/arm64/boot/dts/qcom/lemans-evk-ifp-mezzanine.dtso @@ -271,27 +271,20 @@ pcie@3,0 { ranges; bus-range = <0x5 0xff>; - pcie@0,0 { + dev@0,0 { reg = <0x50000 0x0 0x0 0x0 0x0>; - #address-cells = <3>; - #size-cells = <2>; - device_type = "pci"; - ranges; }; - pcie@0,1 { + dev@0,1 { reg = <0x50100 0x0 0x0 0x0 0x0>; - #address-cells = <3>; - #size-cells = <2>; - device_type = "pci"; - ranges; }; }; }; }; &serdes1 { - phy-supply = <&vreg_l5a>; + vdda-0p9-supply = <&vreg_l4a>; + vdda-1p2-supply = <&vreg_l1c>; status = "okay"; }; diff --git a/arch/arm64/boot/dts/qcom/lemans-evk.dts b/arch/arm64/boot/dts/qcom/lemans-evk.dts index a45485b54a5b..301461e49ffe 100644 --- a/arch/arm64/boot/dts/qcom/lemans-evk.dts +++ b/arch/arm64/boot/dts/qcom/lemans-evk.dts @@ -978,7 +978,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/lemans-ride-common.dtsi b/arch/arm64/boot/dts/qcom/lemans-ride-common.dtsi index 144f117ba511..72f745704722 100644 --- a/arch/arm64/boot/dts/qcom/lemans-ride-common.dtsi +++ b/arch/arm64/boot/dts/qcom/lemans-ride-common.dtsi @@ -856,12 +856,16 @@ &qup_uart17_rx { }; &serdes0 { - phy-supply = <&vreg_l5a>; + vdda-0p9-supply = <&vreg_l4a>; + vdda-1p2-supply = <&vreg_l1c>; + status = "okay"; }; &serdes1 { - phy-supply = <&vreg_l5a>; + vdda-0p9-supply = <&vreg_l4a>; + vdda-1p2-supply = <&vreg_l1c>; + status = "okay"; }; diff --git a/arch/arm64/boot/dts/qcom/milos.dtsi b/arch/arm64/boot/dts/qcom/milos.dtsi index aad8bf678916..f3af1d759e09 100644 --- a/arch/arm64/boot/dts/qcom/milos.dtsi +++ b/arch/arm64/boot/dts/qcom/milos.dtsi @@ -1949,6 +1949,11 @@ videocc: clock-controller@aaf0000 { <&sleep_clk>, <&gcc GCC_VIDEO_AHB_CLK>; + power-domains = <&rpmhpd RPMHPD_CX>, + <&rpmhpd RPMHPD_MX>; + required-opps = <&rpmhpd_opp_low_svs>, + <&rpmhpd_opp_low_svs>; + #clock-cells = <1>; #reset-cells = <1>; #power-domain-cells = <1>; @@ -2031,6 +2036,11 @@ camcc: clock-controller@adb0000 { interconnects = <&mmss_noc MASTER_CAMNOC_HF QCOM_ICC_TAG_ALWAYS &mmss_noc SLAVE_MNOC_HF_MEM_NOC QCOM_ICC_TAG_ALWAYS>; + power-domains = <&rpmhpd RPMHPD_CX>, + <&rpmhpd RPMHPD_MX>; + required-opps = <&rpmhpd_opp_low_svs>, + <&rpmhpd_opp_low_svs>; + #clock-cells = <1>; #reset-cells = <1>; #power-domain-cells = <1>; diff --git a/arch/arm64/boot/dts/qcom/monaco-evk-ifp-mezzanine.dtso b/arch/arm64/boot/dts/qcom/monaco-evk-ifp-mezzanine.dtso index ca5bf0fe5ec6..4f727ff6ecb6 100644 --- a/arch/arm64/boot/dts/qcom/monaco-evk-ifp-mezzanine.dtso +++ b/arch/arm64/boot/dts/qcom/monaco-evk-ifp-mezzanine.dtso @@ -117,20 +117,12 @@ pcie@3,0 { ranges; bus-range = <0x5 0xff>; - pcie@0,0 { + dev@0,0 { reg = <0x50000 0x0 0x0 0x0 0x0>; - #address-cells = <3>; - #size-cells = <2>; - device_type = "pci"; - ranges; }; - pcie@0,1 { + dev@0,1 { reg = <0x50100 0x0 0x0 0x0 0x0>; - #address-cells = <3>; - #size-cells = <2>; - device_type = "pci"; - ranges; }; }; }; diff --git a/arch/arm64/boot/dts/qcom/monaco-evk.dts b/arch/arm64/boot/dts/qcom/monaco-evk.dts index 9d17ef7d2caf..f787e78b35ce 100644 --- a/arch/arm64/boot/dts/qcom/monaco-evk.dts +++ b/arch/arm64/boot/dts/qcom/monaco-evk.dts @@ -706,7 +706,8 @@ &sdhc_1 { }; &serdes0 { - phy-supply = <&vreg_l4a>; + vdda-0p9-supply = <&vreg_l4a>; + vdda-1p2-supply = <&vreg_l5a>; status = "okay"; }; diff --git a/arch/arm64/boot/dts/qcom/purwa-iot-evk.dts b/arch/arm64/boot/dts/qcom/purwa-iot-evk.dts index ad503beec1d3..49ef183e2f5e 100644 --- a/arch/arm64/boot/dts/qcom/purwa-iot-evk.dts +++ b/arch/arm64/boot/dts/qcom/purwa-iot-evk.dts @@ -60,6 +60,26 @@ chosen { stdout-path = "serial0:115200n8"; }; + clocks { + clk_rtmr0_xo: clock-rtmr0-xo { + compatible = "fixed-clock"; + clock-frequency = <25000000>; + #clock-cells = <0>; + }; + + clk_rtmr1_xo: clock-rtmr1-xo { + compatible = "fixed-clock"; + clock-frequency = <25000000>; + #clock-cells = <0>; + }; + + clk_rtmr2_xo: clock-rtmr2-xo { + compatible = "fixed-clock"; + clock-frequency = <25000000>; + #clock-cells = <0>; + }; + }; + connector3 { compatible = "usb-a-connector"; label = "USB-3-Type-A"; @@ -295,7 +315,6 @@ vreg_pcie_3v3_aux: regulator-pcie-3v3-aux { pinctrl-names = "default"; }; - /* Left unused as the retimer is not used on this board. */ vreg_rtmr0_1p15: regulator-rtmr0-1p15 { compatible = "regulator-fixed"; @@ -686,7 +705,7 @@ typec-mux@8 { compatible = "parade,ps8830"; reg = <0x08>; - clocks = <&rpmhcc RPMH_RF_CLK5>; + clocks = <&clk_rtmr2_xo>; vdd-supply = <&vreg_rtmr2_1p15>; vdd33-supply = <&vreg_rtmr2_3p3>; @@ -743,7 +762,7 @@ typec-mux@8 { compatible = "parade,ps8830"; reg = <0x8>; - clocks = <&rpmhcc RPMH_RF_CLK4>; + clocks = <&clk_rtmr0_xo>; vdd-supply = <&vreg_rtmr0_1p15>; vdd33-supply = <&vreg_rtmr0_3p3>; @@ -848,7 +867,7 @@ typec-mux@8 { compatible = "parade,ps8830"; reg = <0x8>; - clocks = <&rpmhcc RPMH_RF_CLK4>; + clocks = <&clk_rtmr1_xo>; vdd-supply = <&vreg_rtmr1_1p15>; vdd33-supply = <&vreg_rtmr1_3p3>; diff --git a/arch/arm64/boot/dts/qcom/purwa.dtsi b/arch/arm64/boot/dts/qcom/purwa.dtsi index c698e6cb2543..4348dd3d1dc5 100644 --- a/arch/arm64/boot/dts/qcom/purwa.dtsi +++ b/arch/arm64/boot/dts/qcom/purwa.dtsi @@ -224,6 +224,11 @@ &pcie6a_phy { compatible = "qcom,x1p42100-qmp-gen4x4-pcie-phy"; }; +/* X1P42100 PDC is same as X1E80100, but without hardware register bug */ +&pdc { + compatible = "qcom,x1p42100-pdc", "qcom,pdc"; +}; + &qfprom { gpu_speed_bin: gpu-speed-bin@119 { reg = <0x119 0x2>; diff --git a/arch/arm64/boot/dts/qcom/qcs6490-rb3gen2-industrial-mezzanine.dtso b/arch/arm64/boot/dts/qcom/qcs6490-rb3gen2-industrial-mezzanine.dtso index 46bb52c667a4..5259f4f4f857 100644 --- a/arch/arm64/boot/dts/qcom/qcs6490-rb3gen2-industrial-mezzanine.dtso +++ b/arch/arm64/boot/dts/qcom/qcs6490-rb3gen2-industrial-mezzanine.dtso @@ -130,20 +130,12 @@ pcie@3,0 { ranges; bus-range = <0x5 0xff>; - pcie@0,0 { + dev@0,0 { reg = <0x50000 0x0 0x0 0x0 0x0>; - #address-cells = <3>; - #size-cells = <2>; - device_type = "pci"; - ranges; }; - pcie@0,1 { + dev@0,1 { reg = <0x50100 0x0 0x0 0x0 0x0>; - #address-cells = <3>; - #size-cells = <2>; - device_type = "pci"; - ranges; }; }; @@ -225,20 +217,12 @@ pcie@3,0 { ranges; bus-range = <0x5 0xff>; - pcie@0,0 { + dev@0,0 { reg = <0x50000 0x0 0x0 0x0 0x0>; - #address-cells = <3>; - #size-cells = <2>; - device_type = "pci"; - ranges; }; - pcie@0,1 { + dev@0,1 { reg = <0x50100 0x0 0x0 0x0 0x0>; - #address-cells = <3>; - #size-cells = <2>; - device_type = "pci"; - ranges; }; }; }; diff --git a/arch/arm64/boot/dts/qcom/qcs6490-rb3gen2.dts b/arch/arm64/boot/dts/qcom/qcs6490-rb3gen2.dts index a13315bf0fb0..3bb5fca8e2b1 100644 --- a/arch/arm64/boot/dts/qcom/qcs6490-rb3gen2.dts +++ b/arch/arm64/boot/dts/qcom/qcs6490-rb3gen2.dts @@ -954,20 +954,12 @@ pcie@3,0 { ranges; bus-range = <0x5 0xff>; - pcie@0,0 { + dev@0,0 { reg = <0x50000 0x0 0x0 0x0 0x0>; - #address-cells = <3>; - #size-cells = <2>; - device_type = "pci"; - ranges; }; - pcie@0,1 { + dev@0,1 { reg = <0x50100 0x0 0x0 0x0 0x0>; - #address-cells = <3>; - #size-cells = <2>; - device_type = "pci"; - ranges; }; }; }; diff --git a/arch/arm64/boot/dts/qcom/qcs6490-thundercomm-minipc-g1iot.dts b/arch/arm64/boot/dts/qcom/qcs6490-thundercomm-minipc-g1iot.dts index 31bafa2cf51d..51b59a75c1e0 100644 --- a/arch/arm64/boot/dts/qcom/qcs6490-thundercomm-minipc-g1iot.dts +++ b/arch/arm64/boot/dts/qcom/qcs6490-thundercomm-minipc-g1iot.dts @@ -790,20 +790,12 @@ pcie@3,0 { ranges; bus-range = <0x5 0xff>; - pcie@0,0 { + dev@0,0 { reg = <0x50000 0x0 0x0 0x0 0x0>; - #address-cells = <3>; - #size-cells = <2>; - device_type = "pci"; - ranges; }; - pcie@0,1 { + dev@0,1 { reg = <0x50100 0x0 0x0 0x0 0x0>; - #address-cells = <3>; - #size-cells = <2>; - device_type = "pci"; - ranges; }; }; }; diff --git a/arch/arm64/boot/dts/qcom/qcs8300-ride.dts b/arch/arm64/boot/dts/qcom/qcs8300-ride.dts index 1ff39530ea3d..76c34215dbdf 100644 --- a/arch/arm64/boot/dts/qcom/qcs8300-ride.dts +++ b/arch/arm64/boot/dts/qcom/qcs8300-ride.dts @@ -702,7 +702,9 @@ &remoteproc_gpdsp { }; &serdes0 { - phy-supply = <&vreg_l5a>; + vdda-0p9-supply = <&vreg_l4a>; + vdda-1p2-supply = <&vreg_l5a>; + status = "okay"; }; diff --git a/arch/arm64/boot/dts/qcom/qcs8550-rb5gen2.dts b/arch/arm64/boot/dts/qcom/qcs8550-rb5gen2.dts index 9df8dcd6c62b..e6340f7d30dd 100644 --- a/arch/arm64/boot/dts/qcom/qcs8550-rb5gen2.dts +++ b/arch/arm64/boot/dts/qcom/qcs8550-rb5gen2.dts @@ -1126,20 +1126,12 @@ pcie@3,0 { ranges; bus-range = <0x5 0xff>; - pci@0,0 { + dev@0,0 { reg = <0x50000 0x0 0x0 0x0 0x0>; - #address-cells = <3>; - #size-cells = <2>; - device_type = "pci"; - ranges; }; - pci@0,1 { + dev@0,1 { reg = <0x50100 0x0 0x0 0x0 0x0>; - #address-cells = <3>; - #size-cells = <2>; - device_type = "pci"; - ranges; }; }; }; diff --git a/arch/arm64/boot/dts/qcom/sdm845-lg-common.dtsi b/arch/arm64/boot/dts/qcom/sdm845-lg-common.dtsi index b030a10009c5..84f0e1f0bcd3 100644 --- a/arch/arm64/boot/dts/qcom/sdm845-lg-common.dtsi +++ b/arch/arm64/boot/dts/qcom/sdm845-lg-common.dtsi @@ -581,33 +581,26 @@ &tlmm { sdc2_clk: sdc2-clk-state { pins = "sdc2_clk"; bias-disable; - - /* - * It seems that mmc_test reports errors if drive - * strength is not 16 on clk, cmd, and data pins. - * - * TODO: copy-pasted from mtp, try other values - * on these devices. - */ drive-strength = <16>; }; sdc2_cmd: sdc2-cmd-state { pins = "sdc2_cmd"; bias-pull-up; - drive-strength = <16>; + drive-strength = <10>; }; sdc2_data: sdc2-data-state { pins = "sdc2_data"; bias-pull-up; - drive-strength = <16>; + drive-strength = <10>; }; sd_card_det_n: sd-card-det-n-state { pins = "gpio126"; function = "gpio"; bias-pull-up; + drive-strength = <2>; }; }; diff --git a/arch/arm64/boot/dts/qcom/sdm845-sony-xperia-tama.dtsi b/arch/arm64/boot/dts/qcom/sdm845-sony-xperia-tama.dtsi index 4c63286d8b04..05e5a3674e5f 100644 --- a/arch/arm64/boot/dts/qcom/sdm845-sony-xperia-tama.dtsi +++ b/arch/arm64/boot/dts/qcom/sdm845-sony-xperia-tama.dtsi @@ -754,6 +754,8 @@ int-pins { }; &uart6 { + pinctrl-0 = <&qup_uart6_4pin>; + status = "okay"; bluetooth { diff --git a/arch/arm64/boot/dts/qcom/sm7225-fairphone-fp4.dts b/arch/arm64/boot/dts/qcom/sm7225-fairphone-fp4.dts index 5d20ad93b0c5..773304b4759e 100644 --- a/arch/arm64/boot/dts/qcom/sm7225-fairphone-fp4.dts +++ b/arch/arm64/boot/dts/qcom/sm7225-fairphone-fp4.dts @@ -992,6 +992,10 @@ xo-therm@0 { }; }; +&pmk8350_pon { + status = "disabled"; +}; + &pmk8350_rtc { status = "okay"; }; diff --git a/arch/arm64/boot/dts/qcom/sm8150.dtsi b/arch/arm64/boot/dts/qcom/sm8150.dtsi index 94a3b02cb289..e83fe8daa7c2 100644 --- a/arch/arm64/boot/dts/qcom/sm8150.dtsi +++ b/arch/arm64/boot/dts/qcom/sm8150.dtsi @@ -3574,7 +3574,7 @@ sdhc_2: mmc@8804000 { iommus = <&apps_smmu 0x6a0 0x0>; qcom,dll-config = <0x0007642c>; qcom,ddr-config = <0x80040868>; - power-domains = <&rpmhpd 0>; + power-domains = <&rpmhpd SM8150_CX>; operating-points-v2 = <&sdhc2_opp_table>; status = "disabled"; diff --git a/arch/arm64/boot/dts/qcom/x1-asus-vivobook-s15.dtsi b/arch/arm64/boot/dts/qcom/x1-asus-vivobook-s15.dtsi index 0dc7c1b5a14a..27fab4db24d5 100644 --- a/arch/arm64/boot/dts/qcom/x1-asus-vivobook-s15.dtsi +++ b/arch/arm64/boot/dts/qcom/x1-asus-vivobook-s15.dtsi @@ -1039,6 +1039,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/boot/dts/qcom/x1-asus-zenbook-a14.dtsi b/arch/arm64/boot/dts/qcom/x1-asus-zenbook-a14.dtsi index 59cbbfbce490..8eb4c045b58a 100644 --- a/arch/arm64/boot/dts/qcom/x1-asus-zenbook-a14.dtsi +++ b/arch/arm64/boot/dts/qcom/x1-asus-zenbook-a14.dtsi @@ -1274,6 +1274,7 @@ wcd_tx: codec@0,3 { &tlmm { gpio-reserved-ranges = <44 4>, /* SPI11, TZ Protected */ + <65 1>, /* EC reset */ <90 1>; /* Unknown, TZ Protected */ cam_indicator_en: cam-indicator-en-state { diff --git a/arch/arm64/boot/dts/qcom/x1-crd.dtsi b/arch/arm64/boot/dts/qcom/x1-crd.dtsi index 60db83b8985f..d1bed84725e8 100644 --- a/arch/arm64/boot/dts/qcom/x1-crd.dtsi +++ b/arch/arm64/boot/dts/qcom/x1-crd.dtsi @@ -1531,6 +1531,7 @@ right_tweeter: speaker@0,1 { &tlmm { gpio-reserved-ranges = <34 2>, /* Unused */ <44 4>, /* SPI (TPM) */ + <65 1>, /* EC reset */ <238 1>; /* UFS Reset */ ec_int_n_default: ec-int-n-state { diff --git a/arch/arm64/boot/dts/qcom/x1-dell-thena.dtsi b/arch/arm64/boot/dts/qcom/x1-dell-thena.dtsi index 4cda708455d8..b367eef085ae 100644 --- a/arch/arm64/boot/dts/qcom/x1-dell-thena.dtsi +++ b/arch/arm64/boot/dts/qcom/x1-dell-thena.dtsi @@ -1303,6 +1303,7 @@ right_tweeter: speaker@0,1 { &tlmm { gpio-reserved-ranges = <44 4>, /* SPI11 (TPM) */ + <65 1>, /* EC reset */ <76 4>, /* SPI19 (TZ Protected) */ <80 2>, /* I2C20 (Battery SMBus) */ <238 1>; /* UFS Reset */ diff --git a/arch/arm64/boot/dts/qcom/x1-hp-omnibook-x14.dtsi b/arch/arm64/boot/dts/qcom/x1-hp-omnibook-x14.dtsi index dba8cee43e29..bcd85cbdcb93 100644 --- a/arch/arm64/boot/dts/qcom/x1-hp-omnibook-x14.dtsi +++ b/arch/arm64/boot/dts/qcom/x1-hp-omnibook-x14.dtsi @@ -1287,6 +1287,7 @@ wcd_tx: codec@0,3 { &tlmm { gpio-reserved-ranges = <34 2>, /* Unused */ <44 4>, /* SPI (TPM) */ + <65 1>, /* EC reset */ <72 2>, /* Secure EC I2C connection (?) */ <238 1>; /* UFS Reset */ diff --git a/arch/arm64/boot/dts/qcom/x1e001de-devkit.dts b/arch/arm64/boot/dts/qcom/x1e001de-devkit.dts index be1a8ac8c699..3ba45a7884a2 100644 --- a/arch/arm64/boot/dts/qcom/x1e001de-devkit.dts +++ b/arch/arm64/boot/dts/qcom/x1e001de-devkit.dts @@ -1194,7 +1194,8 @@ wcd_tx: codec@0,3 { }; &tlmm { - gpio-reserved-ranges = <44 4>; /* SPI (TPM) */ + gpio-reserved-ranges = <44 4>, /* SPI (TPM) */ + <65 1>; /* EC reset */ eusb3_reset_n: eusb3-reset-n-state { pins = "gpio6"; diff --git a/arch/arm64/boot/dts/qcom/x1e78100-lenovo-thinkpad-t14s.dtsi b/arch/arm64/boot/dts/qcom/x1e78100-lenovo-thinkpad-t14s.dtsi index 0bee2a3d6e7a..8f7b01617461 100644 --- a/arch/arm64/boot/dts/qcom/x1e78100-lenovo-thinkpad-t14s.dtsi +++ b/arch/arm64/boot/dts/qcom/x1e78100-lenovo-thinkpad-t14s.dtsi @@ -1385,6 +1385,7 @@ wcd_tx: codec@0,3 { &tlmm { gpio-reserved-ranges = <34 2>, /* Unused */ <44 4>, /* SPI (TPM) */ + <65 1>, /* EC reset */ <72 2>, /* Secure EC I2C connection (?) */ <238 1>; /* UFS Reset */ diff --git a/arch/arm64/boot/dts/qcom/x1e80100-dell-inspiron-14-plus-7441.dts b/arch/arm64/boot/dts/qcom/x1e80100-dell-inspiron-14-plus-7441.dts index 75e10d97c386..d10ce9f381ea 100644 --- a/arch/arm64/boot/dts/qcom/x1e80100-dell-inspiron-14-plus-7441.dts +++ b/arch/arm64/boot/dts/qcom/x1e80100-dell-inspiron-14-plus-7441.dts @@ -25,9 +25,9 @@ &gpu_zap_shader { }; &i2c8 { - touchscreen@10 { + touchscreen@9 { compatible = "hid-over-i2c"; - reg = <0x10>; + reg = <0x9>; hid-descr-addr = <0x1>; interrupts-extended = <&tlmm 51 IRQ_TYPE_LEVEL_LOW>; diff --git a/arch/arm64/boot/dts/qcom/x1e80100-dell-xps13-9345.dts b/arch/arm64/boot/dts/qcom/x1e80100-dell-xps13-9345.dts index 2be5a37c00cc..b795b65d604e 100644 --- a/arch/arm64/boot/dts/qcom/x1e80100-dell-xps13-9345.dts +++ b/arch/arm64/boot/dts/qcom/x1e80100-dell-xps13-9345.dts @@ -1072,6 +1072,7 @@ &smb2360_1_eusb2_repeater { &tlmm { gpio-reserved-ranges = <44 4>, /* SPI11 (TPM) */ <76 4>, /* SPI19 (TZ Protected) */ + <65 1>, /* EC reset */ <238 1>; /* UFS Reset */ cam_indicator_en: cam-indicator-en-state { diff --git a/arch/arm64/boot/dts/qcom/x1e80100-honor-magicbook-art-14.dts b/arch/arm64/boot/dts/qcom/x1e80100-honor-magicbook-art-14.dts index b70c1e094bbf..a14f0d0632f0 100644 --- a/arch/arm64/boot/dts/qcom/x1e80100-honor-magicbook-art-14.dts +++ b/arch/arm64/boot/dts/qcom/x1e80100-honor-magicbook-art-14.dts @@ -1068,7 +1068,8 @@ right_tweeter: speaker@0,1 { &tlmm { gpio-reserved-ranges = <34 2>, /* Unused */ - <44 4>; /* SPI (TPM) */ + <44 4>, /* SPI (TPM) */ + <65 1>; /* EC reset */ tpad_default: tpad-default-state { pins = "gpio3"; diff --git a/arch/arm64/boot/dts/qcom/x1e80100-lenovo-yoga-slim7x.dts b/arch/arm64/boot/dts/qcom/x1e80100-lenovo-yoga-slim7x.dts index 9eb2dfd99f20..3e4ab58d2f6f 100644 --- a/arch/arm64/boot/dts/qcom/x1e80100-lenovo-yoga-slim7x.dts +++ b/arch/arm64/boot/dts/qcom/x1e80100-lenovo-yoga-slim7x.dts @@ -1350,6 +1350,7 @@ right_tweeter: speaker@0,1 { &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/boot/dts/qcom/x1e80100-medion-sprchrgd-14-s1.dts b/arch/arm64/boot/dts/qcom/x1e80100-medion-sprchrgd-14-s1.dts index e4a0b86847cd..4b45f293e167 100644 --- a/arch/arm64/boot/dts/qcom/x1e80100-medion-sprchrgd-14-s1.dts +++ b/arch/arm64/boot/dts/qcom/x1e80100-medion-sprchrgd-14-s1.dts @@ -1251,6 +1251,7 @@ right_tweeter: speaker@0,1 { &tlmm { gpio-reserved-ranges = <28 4>, /* 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/boot/dts/qcom/x1e80100-qcp.dts b/arch/arm64/boot/dts/qcom/x1e80100-qcp.dts index 78380fec8839..19ea1add016c 100644 --- a/arch/arm64/boot/dts/qcom/x1e80100-qcp.dts +++ b/arch/arm64/boot/dts/qcom/x1e80100-qcp.dts @@ -1180,6 +1180,7 @@ wcd_tx: codec@0,3 { &tlmm { gpio-reserved-ranges = <33 3>, /* 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/boot/dts/qcom/x1p42100-lenovo-thinkbook-16.dts b/arch/arm64/boot/dts/qcom/x1p42100-lenovo-thinkbook-16.dts index c2f21fcb1b09..1e295741e676 100644 --- a/arch/arm64/boot/dts/qcom/x1p42100-lenovo-thinkbook-16.dts +++ b/arch/arm64/boot/dts/qcom/x1p42100-lenovo-thinkbook-16.dts @@ -1327,6 +1327,7 @@ wcd_tx: codec@0,3 { &tlmm { gpio-reserved-ranges = <34 2>, /* Unused */ + <65 1>, /* EC reset */ <72 2>; /* Secure EC I2C connection (?) */ edp_hpd_default: edp-hpd-default-state { diff --git a/arch/arm64/boot/dts/renesas/r8a78000-ironhide.dts b/arch/arm64/boot/dts/renesas/r8a78000-ironhide.dts index 0ab303863155..b2d6b06c6388 100644 --- a/arch/arm64/boot/dts/renesas/r8a78000-ironhide.dts +++ b/arch/arm64/boot/dts/renesas/r8a78000-ironhide.dts @@ -134,18 +134,18 @@ ecc@18cccc0000 { no-map; }; - ecc@1a66660000 { - reg = <0x1a 0x66660000 0x0 0x999a0000>; + ecc@1acccc0000 { + reg = <0x1a 0xcccc0000 0x0 0x33340000>; no-map; }; - ecc@1c66660000 { - reg = <0x1c 0x66660000 0x0 0x999a0000>; + ecc@1ccccc0000 { + reg = <0x1c 0xcccc0000 0x0 0x33340000>; no-map; }; - ecc@1e66660000 { - reg = <0x1e 0x66660000 0x0 0x999a0000>; + ecc@1ecccc0000 { + reg = <0x1e 0xcccc0000 0x0 0x33340000>; no-map; }; }; diff --git a/arch/arm64/boot/dts/renesas/r9a09g077.dtsi b/arch/arm64/boot/dts/renesas/r9a09g077.dtsi index bac39390ead7..67cd67cdcce9 100644 --- a/arch/arm64/boot/dts/renesas/r9a09g077.dtsi +++ b/arch/arm64/boot/dts/renesas/r9a09g077.dtsi @@ -1258,11 +1258,9 @@ adc0: adc@90014000 { , , , - , - , - ; + ; interrupt-names = "adi", "gbadi", "gcadi", - "cmpai", "cmpbi", "wcmpm", "wcmpum"; + "cmpai", "cmpbi"; clocks = <&cpg CPG_CORE R9A09G077_CLK_PCLKL>, <&cpg CPG_MOD 206>; clock-names = "adclk", "pclk"; @@ -1280,11 +1278,9 @@ adc1: adc@90014400 { , , , - , - , - ; + ; interrupt-names = "adi", "gbadi", "gcadi", - "cmpai", "cmpbi", "wcmpm", "wcmpum"; + "cmpai", "cmpbi"; clocks = <&cpg CPG_CORE R9A09G077_CLK_PCLKL>, <&cpg CPG_MOD 207>; clock-names = "adclk", "pclk"; @@ -1302,11 +1298,9 @@ adc2: adc@80008000 { , , , - , - , - ; + ; interrupt-names = "adi", "gbadi", "gcadi", - "cmpai", "cmpbi", "wcmpm", "wcmpum"; + "cmpai", "cmpbi"; clocks = <&cpg CPG_CORE R9A09G077_CLK_PCLKL>, <&cpg CPG_MOD 225>; clock-names = "adclk", "pclk"; diff --git a/arch/arm64/boot/dts/renesas/r9a09g087.dtsi b/arch/arm64/boot/dts/renesas/r9a09g087.dtsi index 03b976d93e10..b4c156774c9a 100644 --- a/arch/arm64/boot/dts/renesas/r9a09g087.dtsi +++ b/arch/arm64/boot/dts/renesas/r9a09g087.dtsi @@ -1261,11 +1261,9 @@ adc0: adc@90014000 { , , , - , - , - ; + ; interrupt-names = "adi", "gbadi", "gcadi", - "cmpai", "cmpbi", "wcmpm", "wcmpum"; + "cmpai", "cmpbi"; clocks = <&cpg CPG_CORE R9A09G087_CLK_PCLKL>, <&cpg CPG_MOD 206>; clock-names = "adclk", "pclk"; @@ -1283,11 +1281,9 @@ adc1: adc@90014400 { , , , - , - , - ; + ; interrupt-names = "adi", "gbadi", "gcadi", - "cmpai", "cmpbi", "wcmpm", "wcmpum"; + "cmpai", "cmpbi"; clocks = <&cpg CPG_CORE R9A09G087_CLK_PCLKL>, <&cpg CPG_MOD 207>; clock-names = "adclk", "pclk"; @@ -1305,11 +1301,9 @@ adc2: adc@80008000 { , , , - , - , - ; + ; interrupt-names = "adi", "gbadi", "gcadi", - "cmpai", "cmpbi", "wcmpm", "wcmpum"; + "cmpai", "cmpbi"; clocks = <&cpg CPG_CORE R9A09G087_CLK_PCLKL>, <&cpg CPG_MOD 225>; clock-names = "adclk", "pclk"; diff --git a/arch/arm64/boot/dts/rockchip/rk3328.dtsi b/arch/arm64/boot/dts/rockchip/rk3328.dtsi index 03b7c4313750..26c9f4558ed9 100644 --- a/arch/arm64/boot/dts/rockchip/rk3328.dtsi +++ b/arch/arm64/boot/dts/rockchip/rk3328.dtsi @@ -207,7 +207,7 @@ hdmi_sound: hdmi-sound { compatible = "simple-audio-card"; simple-audio-card,format = "i2s"; simple-audio-card,mclk-fs = <128>; - simple-audio-card,name = "HDMI"; + simple-audio-card,name = "RK3328 HDMI"; status = "disabled"; simple-audio-card,cpu { diff --git a/arch/arm64/boot/dts/rockchip/rk3399-firefly.dts b/arch/arm64/boot/dts/rockchip/rk3399-firefly.dts index 0568dfa140b3..e4570e75c203 100644 --- a/arch/arm64/boot/dts/rockchip/rk3399-firefly.dts +++ b/arch/arm64/boot/dts/rockchip/rk3399-firefly.dts @@ -96,6 +96,15 @@ key-power { }; }; + /* GPIO that enables the headphone output path */ + headphones_amp: headphones-amp { + compatible = "simple-audio-amplifier"; + enable-gpios = <&gpio4 RK_PC5 GPIO_ACTIVE_HIGH>; + pinctrl-names = "default"; + pinctrl-0 = <&rt5640_hpcon>; + sound-name-prefix = "Headphone Amp"; + }; + ir-receiver { compatible = "gpio-ir-receiver"; gpios = <&gpio0 RK_PA6 GPIO_ACTIVE_LOW>; @@ -132,8 +141,11 @@ rt5640-sound { simple-audio-card,routing = "Mic Jack", "MICBIAS1", "IN1P", "Mic Jack", - "Headphone Jack", "HPOL", - "Headphone Jack", "HPOR"; + "Headphone Amp INL", "HPOL", + "Headphone Amp INR", "HPOR", + "Headphone Jack", "Headphone Amp OUTL", + "Headphone Jack", "Headphone Amp OUTR"; + simple-audio-card,aux-devs = <&headphones_amp>; simple-audio-card,cpu { sound-dai = <&i2s1>; @@ -547,8 +559,6 @@ rt5640: rt5640@1c { clock-names = "mclk"; realtek,in1-differential; #sound-dai-cells = <0>; - pinctrl-names = "default"; - pinctrl-0 = <&rt5640_hpcon>; }; }; @@ -618,13 +628,9 @@ accelerometer@68 { }; }; -&i2s0 { - rockchip,playback-channels = <8>; - rockchip,capture-channels = <8>; - status = "okay"; -}; - &i2s1 { + pinctrl-names = "default"; + pinctrl-0 = <&i2s_8ch_mclk_pin>, <&i2s1_2ch_bus>; rockchip,playback-channels = <2>; rockchip,capture-channels = <2>; status = "okay"; @@ -679,6 +685,12 @@ ir_int: ir-int { }; }; + i2s1 { + i2s_8ch_mclk_pin: i2s-8ch-mclk-pin { + rockchip,pins = <4 RK_PA0 1 &pcfg_pull_none>; + }; + }; + lcd-panel { lcd_panel_reset: lcd-panel-reset { rockchip,pins = <4 RK_PD6 RK_FUNC_GPIO &pcfg_pull_up>; diff --git a/arch/arm64/boot/dts/rockchip/rk3566-base.dtsi b/arch/arm64/boot/dts/rockchip/rk3566-base.dtsi index e56e0b6ba941..3c365a1188d7 100644 --- a/arch/arm64/boot/dts/rockchip/rk3566-base.dtsi +++ b/arch/arm64/boot/dts/rockchip/rk3566-base.dtsi @@ -6,6 +6,10 @@ / { compatible = "rockchip,rk3566"; }; +&hdmi_sound { + simple-audio-card,name = "RK3566 HDMI"; +}; + &pipegrf { compatible = "rockchip,rk3566-pipe-grf", "syscon"; }; diff --git a/arch/arm64/boot/dts/rockchip/rk3568.dtsi b/arch/arm64/boot/dts/rockchip/rk3568.dtsi index 3bc653f027f1..2f42bf26fd9b 100644 --- a/arch/arm64/boot/dts/rockchip/rk3568.dtsi +++ b/arch/arm64/boot/dts/rockchip/rk3568.dtsi @@ -382,6 +382,10 @@ &gpu { operating-points-v2 = <&gpu_opp_table>; }; +&hdmi_sound { + simple-audio-card,name = "RK3568 HDMI"; +}; + &pipegrf { compatible = "rockchip,rk3568-pipe-grf", "syscon"; }; diff --git a/arch/arm64/boot/dts/rockchip/rk356x-base.dtsi b/arch/arm64/boot/dts/rockchip/rk356x-base.dtsi index a5832895bd39..1a4562df20ee 100644 --- a/arch/arm64/boot/dts/rockchip/rk356x-base.dtsi +++ b/arch/arm64/boot/dts/rockchip/rk356x-base.dtsi @@ -150,7 +150,6 @@ scmi_clk: protocol@14 { hdmi_sound: hdmi-sound { compatible = "simple-audio-card"; - simple-audio-card,name = "HDMI"; simple-audio-card,format = "i2s"; simple-audio-card,mclk-fs = <256>; status = "disabled"; diff --git a/arch/arm64/boot/dts/rockchip/rk3576-100ask-dshanpi-a1.dts b/arch/arm64/boot/dts/rockchip/rk3576-100ask-dshanpi-a1.dts index 05fb4a7f9a16..41c90414e898 100644 --- a/arch/arm64/boot/dts/rockchip/rk3576-100ask-dshanpi-a1.dts +++ b/arch/arm64/boot/dts/rockchip/rk3576-100ask-dshanpi-a1.dts @@ -278,9 +278,6 @@ &gpu { }; &hdmi { - frl-enable-gpios = <&gpio2 RK_PB0 GPIO_ACTIVE_LOW>; - pinctrl-0 = <&hdmi_txm0_pins &hdmi_tx_scl &hdmi_tx_sda &hdmi_tx_on_h>; - pinctrl-names = "default"; status = "okay"; }; @@ -741,12 +738,6 @@ hp_det: hp-det { }; }; - hdmi { - hdmi_tx_on_h: hdmi-tx-on-h { - rockchip,pins = <2 RK_PB0 RK_FUNC_GPIO &pcfg_pull_none>; - }; - }; - pcie { pcie_reset: pcie-reset { rockchip,pins = <1 RK_PB7 RK_FUNC_GPIO &pcfg_pull_none>; diff --git a/arch/arm64/boot/dts/rockchip/rk3576.dtsi b/arch/arm64/boot/dts/rockchip/rk3576.dtsi index b0c0d3c8b1b1..ca9cbf035265 100644 --- a/arch/arm64/boot/dts/rockchip/rk3576.dtsi +++ b/arch/arm64/boot/dts/rockchip/rk3576.dtsi @@ -410,7 +410,7 @@ scmi_clk: protocol@14 { hdmi_sound: hdmi-sound { compatible = "simple-audio-card"; - simple-audio-card,name = "HDMI"; + simple-audio-card,name = "RK3576 HDMI"; simple-audio-card,format = "i2s"; simple-audio-card,mclk-fs = <256>; status = "disabled"; diff --git a/arch/arm64/boot/dts/rockchip/rk3588-base.dtsi b/arch/arm64/boot/dts/rockchip/rk3588-base.dtsi index 376ad04e0786..7892e18a7835 100644 --- a/arch/arm64/boot/dts/rockchip/rk3588-base.dtsi +++ b/arch/arm64/boot/dts/rockchip/rk3588-base.dtsi @@ -376,7 +376,7 @@ hdmi0_sound: hdmi0-sound { compatible = "simple-audio-card"; simple-audio-card,format = "i2s"; simple-audio-card,mclk-fs = <128>; - simple-audio-card,name = "hdmi0"; + simple-audio-card,name = "RK3588 HDMI0"; status = "disabled"; simple-audio-card,codec { diff --git a/arch/arm64/boot/dts/rockchip/rk3588-extra.dtsi b/arch/arm64/boot/dts/rockchip/rk3588-extra.dtsi index b251bb129cdb..2bcf30d8a338 100644 --- a/arch/arm64/boot/dts/rockchip/rk3588-extra.dtsi +++ b/arch/arm64/boot/dts/rockchip/rk3588-extra.dtsi @@ -11,7 +11,7 @@ hdmi1_sound: hdmi1-sound { compatible = "simple-audio-card"; simple-audio-card,format = "i2s"; simple-audio-card,mclk-fs = <128>; - simple-audio-card,name = "hdmi1"; + simple-audio-card,name = "RK3588 HDMI1"; status = "disabled"; simple-audio-card,codec { diff --git a/arch/arm64/boot/dts/rockchip/rk3588s-gameforce-ace.dts b/arch/arm64/boot/dts/rockchip/rk3588s-gameforce-ace.dts index 230aac005e8f..d43eb48152e8 100644 --- a/arch/arm64/boot/dts/rockchip/rk3588s-gameforce-ace.dts +++ b/arch/arm64/boot/dts/rockchip/rk3588s-gameforce-ace.dts @@ -596,6 +596,7 @@ regulator-state-mem { &i2c3 { status = "okay"; + /* Touchscreen is rotated 90 degrees with 0,0 position near home button. */ touchscreen@14 { compatible = "goodix,gt911"; reg = <0x14>; @@ -605,10 +606,8 @@ touchscreen@14 { pinctrl-0 = <&touch_int>, <&touch_rst>; pinctrl-names = "default"; reset-gpios = <&gpio1 RK_PA7 GPIO_ACTIVE_HIGH>; - touchscreen-inverted-x; touchscreen-size-x = <1080>; touchscreen-size-y = <1920>; - touchscreen-swapped-x-y; }; }; @@ -641,11 +640,15 @@ channel@7 { }; }; + /* IMU oriented relative to panel, which is rotated 90 degrees. */ imu@68 { compatible = "invensense,mpu6880"; reg = <0x68>; interrupt-parent = <&gpio0>; interrupts = ; + mount-matrix = "-1", "0", "0", + "0", "-1", "0", + "0", "0", "1"; }; }; diff --git a/arch/arm64/boot/dts/rockchip/rk3588s-nanopi-r6.dtsi b/arch/arm64/boot/dts/rockchip/rk3588s-nanopi-r6.dtsi index 91b6eefd7abf..5bbd5d2fc5fa 100644 --- a/arch/arm64/boot/dts/rockchip/rk3588s-nanopi-r6.dtsi +++ b/arch/arm64/boot/dts/rockchip/rk3588s-nanopi-r6.dtsi @@ -360,12 +360,16 @@ rgmii_phy1: ethernet-phy@1 { }; &pcie2x1l1 { + pinctrl-names = "default"; + pinctrl-0 = <&pcie20x1_1_perstn_m2>; reset-gpios = <&gpio1 RK_PA7 GPIO_ACTIVE_HIGH>; vpcie3v3-supply = <&vcc_3v3_pcie20>; status = "okay"; }; &pcie2x1l2 { + pinctrl-names = "default"; + pinctrl-0 = <&pcie20x1_2_perstn_m0>; reset-gpios = <&gpio3 RK_PD1 GPIO_ACTIVE_HIGH>; vpcie3v3-supply = <&vcc_3v3_pcie20>; status = "okay"; @@ -420,7 +424,21 @@ rtc_int: rtc-int { }; }; + pcie { + pcie20x1_1_perstn_m2: pcie20x1-1-perstn-m2 { + rockchip,pins = <1 RK_PA7 RK_FUNC_GPIO &pcfg_pull_none>; + }; + + pcie20x1_2_perstn_m0: pcie20x1-2-perstn-m0 { + rockchip,pins = <3 RK_PD1 RK_FUNC_GPIO &pcfg_pull_none>; + }; + }; + sdmmc { + sdmmc_det_pin: sdmmc-det-pin { + rockchip,pins = <0 RK_PA4 RK_FUNC_GPIO &pcfg_pull_up>; + }; + sd_s0_pwr: sd-s0-pwr { rockchip,pins = <4 RK_PB4 RK_FUNC_GPIO &pcfg_pull_up>; }; @@ -496,6 +514,8 @@ &sdmmc { no-mmc; no-sdio; sd-uhs-sdr104; + pinctrl-names = "default"; + pinctrl-0 = <&sdmmc_bus4 &sdmmc_clk &sdmmc_cmd &sdmmc_det_pin>; vmmc-supply = <&vcc_3v3_sd_s0>; vqmmc-supply = <&vccio_sd_s0>; status = "okay"; diff --git a/arch/arm64/boot/dts/rockchip/rk3588s-orangepi-5-pro.dts b/arch/arm64/boot/dts/rockchip/rk3588s-orangepi-5-pro.dts index c9679bac1db7..783675337ab9 100644 --- a/arch/arm64/boot/dts/rockchip/rk3588s-orangepi-5-pro.dts +++ b/arch/arm64/boot/dts/rockchip/rk3588s-orangepi-5-pro.dts @@ -188,7 +188,7 @@ package_fan1: package-fan1 { /* NVMe */ &pcie2x1l1 { pinctrl-names = "default"; - pinctrl-0 = <&pcie30x1m1_1_perstn>, <&pcie30x1m1_1_clkreqn>, + pinctrl-0 = <&pcie2_1_rst>, <&pcie30x1m1_1_clkreqn>, <&pcie30x1m1_1_waken>; reset-gpios = <&gpio4 RK_PA2 GPIO_ACTIVE_HIGH>; supports-clkreq; @@ -199,7 +199,7 @@ &pcie2x1l1 { /* NIC */ &pcie2x1l2 { pinctrl-names = "default"; - pinctrl-0 = <&pcie20x1m0_perstn>, <&pcie20x1m0_clkreqn>, + pinctrl-0 = <&pcie2_2_rst>, <&pcie20x1m0_clkreqn>, <&pcie20x1m0_waken>; reset-gpios = <&gpio3 RK_PD1 GPIO_ACTIVE_HIGH>; vpcie3v3-supply = <&vcc3v3_eth>; @@ -223,6 +223,16 @@ ethernet_en: ethernet-en { }; }; + pcie { + pcie2_1_rst: pcie2-1-rst { + rockchip,pins = <4 RK_PA2 RK_FUNC_GPIO &pcfg_pull_none>; + }; + + pcie2_2_rst: pcie2-2-rst { + rockchip,pins = <3 RK_PD1 RK_FUNC_GPIO &pcfg_pull_none>; + }; + }; + usb { vcc5v0_otg_en: vcc5v0-otg-en { rockchip,pins = <0 RK_PC4 RK_FUNC_GPIO &pcfg_pull_down>; diff --git a/arch/arm64/boot/dts/st/stm32mp231.dtsi b/arch/arm64/boot/dts/st/stm32mp231.dtsi index 9e1d240888ff..0eca3ca6a781 100644 --- a/arch/arm64/boot/dts/st/stm32mp231.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp231.dtsi @@ -35,7 +35,7 @@ arm-pmu { arm_wdt: watchdog { compatible = "arm,smc-wdt"; - arm,smc-id = <0xb200005a>; + arm,smc-id = <0xbc000000>; status = "disabled"; }; @@ -577,7 +577,7 @@ sai3a: audio-controller@402b0004 { status = "disabled"; }; - sai3b: audio-controller@502b0024 { + sai3b: audio-controller@402b0024 { compatible = "st,stm32-sai-sub-b"; reg = <0x24 0x20>; #sound-dai-cells = <0>; diff --git a/arch/arm64/boot/dts/st/stm32mp251.dtsi b/arch/arm64/boot/dts/st/stm32mp251.dtsi index 9c63fdb5a885..f81fd06f4be5 100644 --- a/arch/arm64/boot/dts/st/stm32mp251.dtsi +++ b/arch/arm64/boot/dts/st/stm32mp251.dtsi @@ -36,7 +36,7 @@ arm-pmu { arm_wdt: watchdog { compatible = "arm,smc-wdt"; - arm,smc-id = <0xb200005a>; + arm,smc-id = <0xbc000000>; status = "disabled"; }; @@ -1291,7 +1291,7 @@ sai3a: audio-controller@402b0004 { status = "disabled"; }; - sai3b: audio-controller@502b0024 { + sai3b: audio-controller@402b0024 { compatible = "st,stm32-sai-sub-b"; reg = <0x24 0x20>; #sound-dai-cells = <0>; diff --git a/arch/arm64/boot/dts/ti/k3-am62-verdin-ivy.dtsi b/arch/arm64/boot/dts/ti/k3-am62-verdin-ivy.dtsi index 844f59f772e1..c99076109a9b 100644 --- a/arch/arm64/boot/dts/ti/k3-am62-verdin-ivy.dtsi +++ b/arch/arm64/boot/dts/ti/k3-am62-verdin-ivy.dtsi @@ -367,6 +367,11 @@ &main_gpio0 { "", "", "", + "", + "", + "", + "", + "", /* 90 */ ""; }; @@ -425,42 +430,6 @@ &main_gpio1 { "", "", "", /* 50 */ - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", /* 60 */ - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", /* 70 */ - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", /* 80 */ - "", - "", - "", - "", - "", - "", ""; }; diff --git a/arch/arm64/boot/dts/ti/k3-am62-verdin-zinnia.dtsi b/arch/arm64/boot/dts/ti/k3-am62-verdin-zinnia.dtsi index 0ce8357797ed..f399764b05cf 100644 --- a/arch/arm64/boot/dts/ti/k3-am62-verdin-zinnia.dtsi +++ b/arch/arm64/boot/dts/ti/k3-am62-verdin-zinnia.dtsi @@ -274,6 +274,11 @@ &main_gpio0 { "", "", "", + "", + "", + "", + "", + "", /* 90 */ ""; }; @@ -330,42 +335,6 @@ &main_gpio1 { "", "", "", /* 50 */ - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", /* 60 */ - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", /* 70 */ - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", /* 80 */ - "", - "", - "", - "", - "", - "", ""; }; diff --git a/arch/arm64/boot/dts/ti/k3-am62-verdin.dtsi b/arch/arm64/boot/dts/ti/k3-am62-verdin.dtsi index 895b1b7dcac7..042124828095 100644 --- a/arch/arm64/boot/dts/ti/k3-am62-verdin.dtsi +++ b/arch/arm64/boot/dts/ti/k3-am62-verdin.dtsi @@ -1012,6 +1012,11 @@ &main_gpio0 { "", "", "", + "", + "", + "", + "", + "", /* 90 */ ""; }; @@ -1068,42 +1073,6 @@ &main_gpio1 { "", "SODIMM_17", "SODIMM_155", /* 50 */ - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", /* 60 */ - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", /* 70 */ - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", /* 80 */ - "", - "", - "", - "", - "", - "", ""; }; diff --git a/arch/arm64/boot/dts/ti/k3-am62a-phycore-som.dtsi b/arch/arm64/boot/dts/ti/k3-am62a-phycore-som.dtsi index 5ad93be3d336..9b1666cee80e 100644 --- a/arch/arm64/boot/dts/ti/k3-am62a-phycore-som.dtsi +++ b/arch/arm64/boot/dts/ti/k3-am62a-phycore-som.dtsi @@ -67,7 +67,7 @@ wkup_r5fss0_core0_dma_memory_region: memory@9c800000 { wkup_r5fss0_core0_memory_region: memory@9c900000 { compatible = "shared-dma-pool"; - reg = <0x00 0x9c900000 0x00 0xf00000>; + reg = <0x00 0x9c900000 0x00 0x1e00000>; no-map; }; diff --git a/arch/arm64/boot/dts/ti/k3-am62a7-sk.dts b/arch/arm64/boot/dts/ti/k3-am62a7-sk.dts index e63c5200a237..42aa9bbc6831 100644 --- a/arch/arm64/boot/dts/ti/k3-am62a7-sk.dts +++ b/arch/arm64/boot/dts/ti/k3-am62a7-sk.dts @@ -61,7 +61,7 @@ wkup_r5fss0_core0_dma_memory_region: memory@9c800000 { wkup_r5fss0_core0_memory_region: memory@9c900000 { compatible = "shared-dma-pool"; - reg = <0x00 0x9c900000 0x00 0xf00000>; + reg = <0x00 0x9c900000 0x00 0x1e00000>; no-map; }; diff --git a/arch/arm64/boot/dts/ti/k3-am62d2-evm.dts b/arch/arm64/boot/dts/ti/k3-am62d2-evm.dts index f5ceb6a1b5de..a8c794d07343 100644 --- a/arch/arm64/boot/dts/ti/k3-am62d2-evm.dts +++ b/arch/arm64/boot/dts/ti/k3-am62d2-evm.dts @@ -67,7 +67,7 @@ wkup_r5fss0_core0_dma_memory_region: memory@9c800000 { wkup_r5fss0_core0_memory_region: memory@9c900000 { compatible = "shared-dma-pool"; - reg = <0x00 0x9c900000 0x00 0xf00000>; + reg = <0x00 0x9c900000 0x00 0x1e00000>; no-map; bootph-pre-ram; }; diff --git a/arch/arm64/boot/dts/ti/k3-am62l3-evm.dts b/arch/arm64/boot/dts/ti/k3-am62l3-evm.dts index 84a0cfaaf196..964387eb5178 100644 --- a/arch/arm64/boot/dts/ti/k3-am62l3-evm.dts +++ b/arch/arm64/boot/dts/ti/k3-am62l3-evm.dts @@ -253,9 +253,9 @@ AM62LX_IOPAD(0x01e0, PIN_INPUT_PULLUP, 0) /* (D8) I2C2_SDA */ mmc0_pins_default: mmc0-default-pins { pinctrl-single,pins = < - AM62LX_IOPAD(0x0214, PIN_INPUT_PULLUP, 0) /* (D2) MMC0_CMD */ + AM62LX_IOPAD(0x0214, PIN_INPUT, 0) /* (D2) MMC0_CMD */ AM62LX_IOPAD(0x020c, PIN_OUTPUT, 0) /* (B2) MMC0_CLK */ - AM62LX_IOPAD(0x0208, PIN_INPUT_PULLUP, 0) /* (D3) MMC0_DAT0 */ + AM62LX_IOPAD(0x0208, PIN_INPUT, 0) /* (D3) MMC0_DAT0 */ AM62LX_IOPAD(0x0204, PIN_INPUT_PULLUP, 0) /* (D4) MMC0_DAT1 */ AM62LX_IOPAD(0x0200, PIN_INPUT_PULLUP, 0) /* (C1) MMC0_DAT2 */ AM62LX_IOPAD(0x01fc, PIN_INPUT_PULLUP, 0) /* (C2) MMC0_DAT3 */ diff --git a/arch/arm64/boot/dts/ti/k3-am62p-verdin.dtsi b/arch/arm64/boot/dts/ti/k3-am62p-verdin.dtsi index 7ee894d59113..8a5ff5c45757 100644 --- a/arch/arm64/boot/dts/ti/k3-am62p-verdin.dtsi +++ b/arch/arm64/boot/dts/ti/k3-am62p-verdin.dtsi @@ -170,7 +170,7 @@ wkup_r5fss0_core0_dma_memory_region: memory@9c800000 { wkup_r5fss0_core0_memory_region: memory@9c900000 { compatible = "shared-dma-pool"; - reg = <0x00 0x9c900000 0x00 0x01e00000>; + reg = <0x00 0x9c900000 0x00 0x01d08000>; no-map; }; }; diff --git a/arch/arm64/boot/dts/ti/k3-am62p5-sk.dts b/arch/arm64/boot/dts/ti/k3-am62p5-sk.dts index b770ed82be9d..b8af9ec81b0c 100644 --- a/arch/arm64/boot/dts/ti/k3-am62p5-sk.dts +++ b/arch/arm64/boot/dts/ti/k3-am62p5-sk.dts @@ -57,7 +57,7 @@ wkup_r5fss0_core0_dma_memory_region: memory@9c800000 { wkup_r5fss0_core0_memory_region: memory@9c900000 { compatible = "shared-dma-pool"; - reg = <0x00 0x9c900000 0x00 0xf00000>; + reg = <0x00 0x9c900000 0x00 0x1d08000>; no-map; }; diff --git a/arch/arm64/boot/dts/ti/k3-am62p5-var-som.dtsi b/arch/arm64/boot/dts/ti/k3-am62p5-var-som.dtsi index 8a8dec80cb30..3d1a2c5bc464 100644 --- a/arch/arm64/boot/dts/ti/k3-am62p5-var-som.dtsi +++ b/arch/arm64/boot/dts/ti/k3-am62p5-var-som.dtsi @@ -71,7 +71,7 @@ wkup_r5fss0_core0_dma_memory_region: r5f-dma-memory@9c800000 { wkup_r5fss0_core0_memory_region: r5f-memory@9c900000 { compatible = "shared-dma-pool"; - reg = <0x00 0x9c900000 0x00 0x01e00000>; + reg = <0x00 0x9c900000 0x00 0x01d08000>; no-map; }; diff --git a/arch/arm64/boot/dts/ti/k3-am69-aquila.dtsi b/arch/arm64/boot/dts/ti/k3-am69-aquila.dtsi index 5119baf62a4c..b6854acee8fe 100644 --- a/arch/arm64/boot/dts/ti/k3-am69-aquila.dtsi +++ b/arch/arm64/boot/dts/ti/k3-am69-aquila.dtsi @@ -1573,7 +1573,7 @@ &wkup_gpio0 { "AQUILA_B70", "AQUILA_B71", "AQUILA_B72", - "AQUILC_B73", + "AQUILA_B73", "AQUILA_B66", "AQUILA_B62", "AQUILA_C21", diff --git a/arch/arm64/boot/dts/ti/k3-j722s-evm.dts b/arch/arm64/boot/dts/ti/k3-j722s-evm.dts index e66330c71593..90c3e3c9c496 100644 --- a/arch/arm64/boot/dts/ti/k3-j722s-evm.dts +++ b/arch/arm64/boot/dts/ti/k3-j722s-evm.dts @@ -162,6 +162,12 @@ vsys_io_1v2: regulator-vsys-io-1v2 { regulator-boot-on; }; + tlv320_mclk: clock-12288000 { + compatible = "fixed-clock"; + clock-frequency = <12288000>; + #clock-cells = <0>; + }; + codec_audio: sound { compatible = "simple-audio-card"; simple-audio-card,name = "J722S-EVM"; @@ -187,7 +193,7 @@ simple-audio-card,cpu { sound_master: simple-audio-card,codec { sound-dai = <&tlv320aic3106>; - clocks = <&audio_refclk1>; + clocks = <&tlv320_mclk>; }; }; @@ -228,11 +234,6 @@ csi23_mux: mux-controller-1 { }; }; -&audio_refclk1 { - assigned-clocks = <&k3_clks 157 0>; - assigned-clock-parents = <&k3_clks 157 15>; -}; - &cpsw_mac_syscon { bootph-all; }; @@ -358,12 +359,6 @@ J722S_IOPAD(0x0084, PIN_INPUT, 2) /* (N21) GPMC0_ADVn_ALE.MCASP1_AXR2 */ >; }; - audio_ext_refclk1_pins_default: audio-ext-refclk1-default-pins { - pinctrl-single,pins = < - J722S_IOPAD(0x00a0, PIN_OUTPUT, 1) /* (N24) GPMC0_WPn.AUDIO_EXT_REFCLK1 */ - >; - }; - pmic_irq_pins_default: pmic-irq-default-pins { pinctrl-single,pins = < J722S_IOPAD(0x030, PIN_INPUT, 7) /* (K23) GPIO0_12 */ @@ -562,12 +557,6 @@ ldo3: ldo3 { }; }; -&k3_clks { - /* Configure AUDIO_EXT_REFCLK1 pin as output */ - pinctrl-names = "default"; - pinctrl-0 = <&audio_ext_refclk1_pins_default>; -}; - &main_i2c0 { pinctrl-names = "default"; pinctrl-0 = <&main_i2c0_pins_default>; diff --git a/arch/arm64/boot/dts/ti/k3-j784s4-j742s2-evm-common.dtsi b/arch/arm64/boot/dts/ti/k3-j784s4-j742s2-evm-common.dtsi index ff3a85cbc524..7c085663c888 100644 --- a/arch/arm64/boot/dts/ti/k3-j784s4-j742s2-evm-common.dtsi +++ b/arch/arm64/boot/dts/ti/k3-j784s4-j742s2-evm-common.dtsi @@ -1206,6 +1206,8 @@ &pcie1_rc { status = "okay"; clocks = <&k3_clks 333 0>, <&serdes0 CDNS_TORRENT_REFCLK_DRIVER>; clock-names = "fck", "pcie_refclk"; + assigned-clocks = <&k3_clks 415 0>; + assigned-clock-parents = <&k3_clks 415 2>; num-lanes = <2>; reset-gpios = <&exp1 2 GPIO_ACTIVE_HIGH>; phys = <&serdes0_pcie1_link>; diff --git a/arch/arm64/include/asm/rsi_smc.h b/arch/arm64/include/asm/rsi_smc.h index e19253f96c94..6271e18e5a37 100644 --- a/arch/arm64/include/asm/rsi_smc.h +++ b/arch/arm64/include/asm/rsi_smc.h @@ -128,7 +128,7 @@ struct realm_config { union { struct { unsigned long ipa_bits; /* Width of IPA in bits */ - unsigned long hash_algo; /* Hash algorithm */ + u8 hash_algo; /* Hash algorithm */ }; u8 pad[0x200]; }; diff --git a/arch/arm64/kernel/pi/Makefile b/arch/arm64/kernel/pi/Makefile index be92d73c25b2..96243c291e39 100644 --- a/arch/arm64/kernel/pi/Makefile +++ b/arch/arm64/kernel/pi/Makefile @@ -34,6 +34,7 @@ $(obj)/lib-%.pi.o: OBJCOPYFLAGS += --prefix-alloc-sections=.init $(obj)/lib-%.o: $(srctree)/lib/%.c FORCE $(call if_changed_rule,cc_o_c) + $(call cmd,force_checksrc) obj-y := idreg-override.pi.o \ map_kernel.pi.o map_range.pi.o \ diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c index c1279fabce47..d393fa6bfbf4 100644 --- a/arch/arm64/net/bpf_jit_comp.c +++ b/arch/arm64/net/bpf_jit_comp.c @@ -22,7 +22,6 @@ #include #include #include -#include #include "bpf_jit.h" @@ -3237,21 +3236,22 @@ int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type old_t, */ plt_target = (u64)&dummy_tramp; - if (plt_target) { - /* non-zero plt_target indicates we're patching a bpf prog, - * which is read only. - */ - if (set_memory_rw(PAGE_MASK & ((uintptr_t)&plt->target), 1)) - return -EFAULT; - WRITE_ONCE(plt->target, plt_target); - set_memory_ro(PAGE_MASK & ((uintptr_t)&plt->target), 1); - /* since plt target points to either the new trampoline - * or dummy_tramp, even if another CPU reads the old plt - * target value before fetching the bl instruction to plt, - * it will be brought back by dummy_tramp, so no barrier is - * required here. - */ - } + /* + * non-zero plt_target indicates we're patching a bpf prog, + * which is read only. The prog may share its page in the bpf + * prog pack with other progs, so write the aligned target + * through the text patching fixmap without flipping the + * page permissions to avoid racing with concurrent pokers. + * + * since plt target points to either the new trampoline + * or dummy_tramp, even if another CPU reads the old plt + * target value before fetching the bl instruction to plt, + * it will be brought back by dummy_tramp, so no barrier is + * required here. + */ + if (plt_target && + aarch64_insn_write_literal_u64(&plt->target, plt_target)) + return -EFAULT; /* if the old target and the new target are both long jumps, no * patching is required diff --git a/arch/arm64/net/bpf_timed_may_goto.S b/arch/arm64/net/bpf_timed_may_goto.S index a9a802711a7f..1b4a4f91ffc9 100644 --- a/arch/arm64/net/bpf_timed_may_goto.S +++ b/arch/arm64/net/bpf_timed_may_goto.S @@ -5,13 +5,16 @@ SYM_FUNC_START(arch_bpf_timed_may_goto) /* Allocate stack space and emit frame record */ - stp x29, x30, [sp, #-64]! + stp x29, x30, [sp, #-96]! mov x29, sp /* Save BPF registers R0 - R5 (x8, x0-x4)*/ stp x8, x0, [sp, #16] stp x1, x2, [sp, #32] stp x3, x4, [sp, #48] + /* Save stack arguments 6 - 8 (x5-x7) */ + stp x5, x6, [sp, #64] + str x7, [sp, #80] /* * Stack depth was passed in BPF_REG_AX (x9), add it to the BPF_FP @@ -32,9 +35,12 @@ SYM_FUNC_START(arch_bpf_timed_may_goto) ldp x8, x0, [sp, #16] ldp x1, x2, [sp, #32] ldp x3, x4, [sp, #48] + /* Restore stack arguments 6 - 8 (x5-x7) */ + ldp x5, x6, [sp, #64] + ldr x7, [sp, #80] /* Restore FP and LR */ - ldp x29, x30, [sp], #64 + ldp x29, x30, [sp], #96 ret SYM_FUNC_END(arch_bpf_timed_may_goto) 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/net/bpf_jit.c b/arch/loongarch/net/bpf_jit.c index e78eb582c300..119a20a7edf1 100644 --- a/arch/loongarch/net/bpf_jit.c +++ b/arch/loongarch/net/bpf_jit.c @@ -1674,17 +1674,17 @@ int bpf_arch_text_invalidate(void *dst, size_t len) return ret; } -static void store_args(struct jit_ctx *ctx, int nr_arg_slots, int args_off) +static void store_args(struct jit_ctx *ctx, int nr_arg_slots, int args_off, bool is_struct_ops) { int i; + int stack_args_off = is_struct_ops ? 0 : 16; for (i = 0; i < nr_arg_slots; i++) { if (i < LOONGARCH_MAX_REG_ARGS) emit_insn(ctx, std, LOONGARCH_GPR_A0 + i, LOONGARCH_GPR_FP, -args_off); else { - /* Skip slots for T0 and FP of traced function */ emit_insn(ctx, ldd, LOONGARCH_GPR_T1, LOONGARCH_GPR_FP, - 16 + (i - LOONGARCH_MAX_REG_ARGS) * 8); + stack_args_off + (i - LOONGARCH_MAX_REG_ARGS) * 8); emit_insn(ctx, std, LOONGARCH_GPR_T1, LOONGARCH_GPR_FP, -args_off); } args_off -= 8; @@ -2017,7 +2017,7 @@ static int __arch_prepare_bpf_trampoline(struct jit_ctx *ctx, struct bpf_tramp_i func_meta = nr_arg_slots; emit_store_stack_imm64(ctx, LOONGARCH_GPR_T1, -func_meta_off, func_meta); - store_args(ctx, nr_arg_slots, args_off); + store_args(ctx, nr_arg_slots, args_off, is_struct_ops); if (bpf_fsession_cnt(tnodes)) { /* clear all session cookies' value */ diff --git a/arch/m68k/apollo/dn_ints.c b/arch/m68k/apollo/dn_ints.c index ba96a92f8f18..89bfb5aaad9d 100644 --- a/arch/m68k/apollo/dn_ints.c +++ b/arch/m68k/apollo/dn_ints.c @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -11,10 +12,13 @@ static unsigned int apollo_irq_startup(struct irq_data *data) { unsigned int irq = data->irq; + m68k_irq_startup(data); + if (irq < 8) *(volatile unsigned char *)(pica+1) &= ~(1 << irq); else *(volatile unsigned char *)(picb+1) &= ~(1 << (irq - 8)); + return 0; } @@ -26,6 +30,8 @@ static void apollo_irq_shutdown(struct irq_data *data) *(volatile unsigned char *)(pica+1) |= (1 << irq); else *(volatile unsigned char *)(picb+1) |= (1 << (irq - 8)); + + m68k_irq_shutdown(data); } static void apollo_irq_eoi(struct irq_data *data) diff --git a/arch/m68k/mac/config.c b/arch/m68k/mac/config.c index c0033f885ed4..b745cf20a71f 100644 --- a/arch/m68k/mac/config.c +++ b/arch/m68k/mac/config.c @@ -984,8 +984,37 @@ static int __init mac_platform_init(void) .start = swim_base, .end = swim_base + 0x1FFF, }; + bool fast_fclk = false; + + /* Models in this list are supposed to run FCLK at 32 MHz */ + switch (macintosh_config->ident) { + case MAC_MODEL_CCL: + case MAC_MODEL_CCLII: + case MAC_MODEL_LCIII: + case MAC_MODEL_Q605: + case MAC_MODEL_Q605_ACC: + case MAC_MODEL_Q610: + case MAC_MODEL_Q630: + case MAC_MODEL_Q650: + case MAC_MODEL_Q800: + case MAC_MODEL_P460: + case MAC_MODEL_P475: + case MAC_MODEL_P475F: + case MAC_MODEL_P520: + case MAC_MODEL_P550: + case MAC_MODEL_P575: + case MAC_MODEL_P588: + case MAC_MODEL_TV: + case MAC_MODEL_C610: + case MAC_MODEL_C650: + case MAC_MODEL_PB190: + case MAC_MODEL_PB520: + fast_fclk = true; + break; + } - platform_device_register_simple("swim", -1, &swim_rsrc, 1); + platform_device_register_resndata(NULL, "swim", -1, &swim_rsrc, 1, + &fast_fclk, sizeof(fast_fclk)); } /* diff --git a/arch/microblaze/Makefile b/arch/microblaze/Makefile index 02e6be9c5b0d..9087a366ce78 100644 --- a/arch/microblaze/Makefile +++ b/arch/microblaze/Makefile @@ -34,12 +34,10 @@ CPUFLAGS-$(CONFIG_XILINX_MICROBLAZE0_USE_BARREL) += -mxl-barrel-shift CPUFLAGS-$(CONFIG_XILINX_MICROBLAZE0_USE_PCMP_INSTR) += -mxl-pattern-compare ifdef CONFIG_CPU_BIG_ENDIAN -KBUILD_CFLAGS += -mbig-endian -KBUILD_AFLAGS += -mbig-endian +KBUILD_CPPFLAGS += -mbig-endian KBUILD_LDFLAGS += -EB else -KBUILD_CFLAGS += -mlittle-endian -KBUILD_AFLAGS += -mlittle-endian +KBUILD_CPPFLAGS += -mlittle-endian KBUILD_LDFLAGS += -EL endif diff --git a/arch/microblaze/include/asm/uaccess.h b/arch/microblaze/include/asm/uaccess.h index afa0dd8d013f..77203af255e5 100644 --- a/arch/microblaze/include/asm/uaccess.h +++ b/arch/microblaze/include/asm/uaccess.h @@ -95,7 +95,8 @@ extern long __user_bad(void); #define get_user(x, ptr) ({ \ const typeof(*(ptr)) __user *__gu_ptr = (ptr); \ access_ok(__gu_ptr, sizeof(*__gu_ptr)) ? \ - __get_user(x, __gu_ptr) : -EFAULT; \ + __get_user(x, __gu_ptr) : \ + ((x) = 0, -EFAULT); \ }) #define __get_user(x, ptr) \ diff --git a/arch/microblaze/kernel/cpu/cpuinfo.c b/arch/microblaze/kernel/cpu/cpuinfo.c index cd9b4450763b..32c508e85408 100644 --- a/arch/microblaze/kernel/cpu/cpuinfo.c +++ b/arch/microblaze/kernel/cpu/cpuinfo.c @@ -133,6 +133,7 @@ void __init setup_cpuinfo_clk(void) cpuinfo.cpu_clock_freq = fcpu(cpu, "timebase-frequency"); } else { cpuinfo.cpu_clock_freq = clk_get_rate(clk); + clk_put(clk); } if (!cpuinfo.cpu_clock_freq) { diff --git a/arch/microblaze/kernel/ptrace.c b/arch/microblaze/kernel/ptrace.c index 236264e932d6..ac1f0503216b 100644 --- a/arch/microblaze/kernel/ptrace.c +++ b/arch/microblaze/kernel/ptrace.c @@ -101,6 +101,9 @@ long arch_ptrace(struct task_struct *child, long request, } else { rval = -EIO; } + } else if (request == PTRACE_POKEUSR && + (addr == PT_MSR || addr == PT_MODE)) { + rval = -EIO; } else if (addr < PT_SIZE && (addr & 0x3) == 0) { microblaze_reg_t *reg_addr = reg_save_addr(addr, child); if (request == PTRACE_PEEKUSR) diff --git a/arch/mips/Makefile b/arch/mips/Makefile index cff1a9a43b89..3e9eb0650cac 100644 --- a/arch/mips/Makefile +++ b/arch/mips/Makefile @@ -290,18 +290,20 @@ drivers-$(CONFIG_PCI) += arch/mips/pci/ # We can always force a build with a 64-bits symbol format by # passing 'KBUILD_SYM32=no' option to the make's command line. # -ifdef CONFIG_64BIT - ifndef KBUILD_SYM32 - ifeq ($(shell expr $(load-y) \< 0xffffffff80000000), 0) - KBUILD_SYM32 = $(call cc-option-yn, -msym32) +ifdef need-compiler + ifdef CONFIG_64BIT + ifndef KBUILD_SYM32 + ifeq ($(shell expr $(load-y) \< 0xffffffff80000000), 0) + KBUILD_SYM32 = $(call cc-option-yn, -msym32) + endif endif - endif - ifeq ($(KBUILD_SYM32), y) - cflags-$(KBUILD_SYM32) += -msym32 -DKBUILD_64BIT_SYM32 - else - ifeq ($(CONFIG_CPU_DADDI_WORKAROUNDS), y) - $(error CONFIG_CPU_DADDI_WORKAROUNDS unsupported without -msym32) + ifeq ($(KBUILD_SYM32), y) + cflags-$(KBUILD_SYM32) += -msym32 -DKBUILD_64BIT_SYM32 + else + ifeq ($(CONFIG_CPU_DADDI_WORKAROUNDS), y) + $(error CONFIG_CPU_DADDI_WORKAROUNDS unsupported without -msym32) + endif endif endif endif diff --git a/arch/mips/cavium-octeon/dma-octeon.c b/arch/mips/cavium-octeon/dma-octeon.c index 9fbba6a8fa4c..c049632fbcc3 100644 --- a/arch/mips/cavium-octeon/dma-octeon.c +++ b/arch/mips/cavium-octeon/dma-octeon.c @@ -228,7 +228,7 @@ void __init plat_swiotlb_setup(void) swiotlbsize = 64 * (1<<20); } #endif -#ifdef CONFIG_USB_OHCI_HCD_PLATFORM +#if IS_ENABLED(CONFIG_USB_OHCI_HCD_PLATFORM) /* OCTEON II ohci is only 32-bit. */ if (OCTEON_IS_OCTEON2() && max_addr >= 0x100000000ul) swiotlbsize = 64 * (1<<20); diff --git a/arch/mips/include/asm/dec/reset.h b/arch/mips/include/asm/dec/reset.h index 6af49f3f24da..caf60ef0edd0 100644 --- a/arch/mips/include/asm/dec/reset.h +++ b/arch/mips/include/asm/dec/reset.h @@ -10,6 +10,7 @@ #define __ASM_DEC_RESET_H #include +#include void __noreturn dec_machine_restart(char *command); void __noreturn dec_machine_halt(void); diff --git a/arch/nios2/kernel/nios2_ksyms.c b/arch/nios2/kernel/nios2_ksyms.c index c40aa39e8658..e8710a269b39 100644 --- a/arch/nios2/kernel/nios2_ksyms.c +++ b/arch/nios2/kernel/nios2_ksyms.c @@ -38,6 +38,7 @@ DECLARE_EXPORT(__udivsi3); DECLARE_EXPORT(__umoddi3); DECLARE_EXPORT(__umodsi3); DECLARE_EXPORT(__muldi3); +DECLARE_EXPORT(__mulsi3); DECLARE_EXPORT(__ucmpdi2); DECLARE_EXPORT(__lshrdi3); DECLARE_EXPORT(__ashldi3); 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/powerpc/include/asm/interrupt.h b/arch/powerpc/include/asm/interrupt.h index 1b45a49e9bed..c7d0e71eac83 100644 --- a/arch/powerpc/include/asm/interrupt.h +++ b/arch/powerpc/include/asm/interrupt.h @@ -70,6 +70,7 @@ #include #include +#include #include #ifdef CONFIG_PPC_IRQ_SOFT_MASK_DEBUG @@ -290,7 +291,7 @@ interrupt_handler long func(struct pt_regs *regs) \ state = irqentry_nmi_enter(regs); \ } else if (IS_ENABLED(CONFIG_PPC_BOOK3S_64) && \ firmware_has_feature(FW_FEATURE_LPAR) && \ - !radix_enabled()) { \ + !early_radix_enabled()) { \ /* no nmi_entry for a pseries hash guest \ * taking a real mode exception */ \ } else if (IS_ENABLED(CONFIG_KASAN)) { \ @@ -301,13 +302,12 @@ interrupt_handler long func(struct pt_regs *regs) \ state = irqentry_nmi_enter(regs); \ } \ ret = ____##func (regs); \ - arch_interrupt_nmi_exit_prepare(regs, &nmi_state); \ if (mfmsr() & MSR_DR) { \ /* nmi_exit if relocations are on */ \ irqentry_nmi_exit(regs, state); \ } 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)) { \ @@ -317,6 +317,7 @@ interrupt_handler long func(struct pt_regs *regs) \ } else { \ irqentry_nmi_exit(regs, state); \ } \ + arch_interrupt_nmi_exit_prepare(regs, &nmi_state); \ \ return ret; \ } \ diff --git a/arch/powerpc/include/asm/kasan.h b/arch/powerpc/include/asm/kasan.h index a690e7da53c2..599a9e02af02 100644 --- a/arch/powerpc/include/asm/kasan.h +++ b/arch/powerpc/include/asm/kasan.h @@ -2,21 +2,6 @@ #ifndef __ASM_KASAN_H #define __ASM_KASAN_H -#if defined(CONFIG_KASAN) && !defined(CONFIG_CC_HAS_KASAN_MEMINTRINSIC_PREFIX) -#define _GLOBAL_KASAN(fn) \ - _GLOBAL(fn); \ - _GLOBAL(__##fn) -#define _GLOBAL_TOC_KASAN(fn) \ - _GLOBAL_TOC(fn); \ - _GLOBAL_TOC(__##fn) -#define EXPORT_SYMBOL_KASAN(fn) \ - EXPORT_SYMBOL(__##fn) -#else /* CONFIG_KASAN && !CONFIG_CC_HAS_KASAN_MEMINTRINSIC_PREFIX */ -#define _GLOBAL_KASAN(fn) _GLOBAL(fn) -#define _GLOBAL_TOC_KASAN(fn) _GLOBAL_TOC(fn) -#define EXPORT_SYMBOL_KASAN(fn) -#endif /* CONFIG_KASAN && !CONFIG_CC_HAS_KASAN_MEMINTRINSIC_PREFIX */ - #ifndef __ASSEMBLER__ #include diff --git a/arch/powerpc/include/asm/string.h b/arch/powerpc/include/asm/string.h index 1981bd4036b5..161b949683b3 100644 --- a/arch/powerpc/include/asm/string.h +++ b/arch/powerpc/include/asm/string.h @@ -29,29 +29,10 @@ extern void * memchr(const void *,int,__kernel_size_t); void memcpy_flushcache(void *dest, const void *src, size_t size); #ifdef CONFIG_KASAN -/* __mem variants are used by KASAN to implement instrumented meminstrinsics. */ -#ifdef CONFIG_CC_HAS_KASAN_MEMINTRINSIC_PREFIX +/* Used by mm/kasan as raw backends to bypass KASAN checking. */ #define __memset memset #define __memcpy memcpy #define __memmove memmove -#else /* CONFIG_CC_HAS_KASAN_MEMINTRINSIC_PREFIX */ -void *__memset(void *s, int c, __kernel_size_t count); -void *__memcpy(void *to, const void *from, __kernel_size_t n); -void *__memmove(void *to, const void *from, __kernel_size_t n); -#ifndef __SANITIZE_ADDRESS__ -/* - * For files that are not instrumented (e.g. mm/slub.c) we - * should use not instrumented version of mem* functions. - */ -#define memcpy(dst, src, len) __memcpy(dst, src, len) -#define memmove(dst, src, len) __memmove(dst, src, len) -#define memset(s, c, n) __memset(s, c, n) - -#ifndef __NO_FORTIFY -#define __NO_FORTIFY /* FORTIFY_SOURCE uses __builtin_memcpy, etc. */ -#endif -#endif /* !__SANITIZE_ADDRESS__ */ -#endif /* CONFIG_CC_HAS_KASAN_MEMINTRINSIC_PREFIX */ #endif /* CONFIG_KASAN */ #ifdef CONFIG_PPC64 diff --git a/arch/powerpc/kernel/cputable.c b/arch/powerpc/kernel/cputable.c index 6f6801da9dc1..4731e27bb7bc 100644 --- a/arch/powerpc/kernel/cputable.c +++ b/arch/powerpc/kernel/cputable.c @@ -35,12 +35,7 @@ void __init set_cur_cpu_spec(struct cpu_spec *s) struct cpu_spec *t = &the_cpu_spec; t = PTRRELOC(t); - /* - * use memcpy() instead of *t = *s so that GCC replaces it - * by __memcpy() when KASAN is active - */ - memcpy(t, s, sizeof(*t)); - + *t = *s; *PTRRELOC(&cur_cpu_spec) = &the_cpu_spec; } @@ -53,11 +48,8 @@ static struct cpu_spec * __init setup_cpu_spec(unsigned long offset, t = PTRRELOC(t); old = *t; - /* - * Copy everything, then do fixups. Use memcpy() instead of *t = *s - * so that GCC replaces it by __memcpy() when KASAN is active - */ - memcpy(t, s, sizeof(*t)); + /* Copy everything, then do fixups. */ + *t = *s; /* * If we are overriding a previous value derived from the real diff --git a/arch/powerpc/kernel/prom_init.c b/arch/powerpc/kernel/prom_init.c index eb9f556b0937..e8e071024da5 100644 --- a/arch/powerpc/kernel/prom_init.c +++ b/arch/powerpc/kernel/prom_init.c @@ -1362,14 +1362,8 @@ static void __init prom_check_platform_support(void) int prop_len = prom_getproplen(prom.chosen, "ibm,arch-vec-5-platform-support"); - /* - * First copy the architecture vec template - * - * use memcpy() instead of *vec = *vec_template so that GCC replaces it - * by __memcpy() when KASAN is active - */ - memcpy(&ibm_architecture_vec, &ibm_architecture_vec_template, - sizeof(ibm_architecture_vec)); + /* First copy the architecture vec template */ + ibm_architecture_vec = ibm_architecture_vec_template; prom_strscpy_pad(ibm_architecture_vec.vec7.os_id, linux_banner, 256); diff --git a/arch/powerpc/kernel/prom_init_check.sh b/arch/powerpc/kernel/prom_init_check.sh index 3090b97258ae..3155cc722e48 100644 --- a/arch/powerpc/kernel/prom_init_check.sh +++ b/arch/powerpc/kernel/prom_init_check.sh @@ -13,21 +13,8 @@ # If you really need to reference something from prom_init.o add # it to the list below: -has_renamed_memintrinsics() -{ - grep -q "^CONFIG_KASAN=y$" "${KCONFIG_CONFIG}" && \ - ! grep -q "^CONFIG_CC_HAS_KASAN_MEMINTRINSIC_PREFIX=y" "${KCONFIG_CONFIG}" -} - -if has_renamed_memintrinsics -then - MEM_FUNCS="__memcpy __memset" -else - MEM_FUNCS="memcpy memset" -fi - WHITELIST="add_reloc_offset __bss_start __bss_stop copy_and_flush -_end enter_prom $MEM_FUNCS reloc_offset __secondary_hold +_end enter_prom memcpy memset reloc_offset __secondary_hold __secondary_hold_acknowledge __secondary_hold_spinloop __start logo_linux_clut224 btext_prepare_BAT reloc_got2 kernstart_addr memstart_addr linux_banner _stext diff --git a/arch/powerpc/kernel/trace/ftrace_entry.S b/arch/powerpc/kernel/trace/ftrace_entry.S index 6599fe3c6234..5eb8eee32549 100644 --- a/arch/powerpc/kernel/trace/ftrace_entry.S +++ b/arch/powerpc/kernel/trace/ftrace_entry.S @@ -220,7 +220,13 @@ /* Restore gprs */ .if \allregs == 1 +#ifdef CONFIG_PPC64 + REST_GPRS(2, 12, r1) + /* Do not restore a stale PACA pointer if the task migrated */ + REST_GPRS(14, 31, r1) +#else REST_GPRS(2, 31, r1) +#endif .else REST_GPRS(3, 10, r1) #if defined(CONFIG_LIVEPATCH_64) || defined(CONFIG_PPC_FTRACE_OUT_OF_LINE) diff --git a/arch/powerpc/lib/copy_32.S b/arch/powerpc/lib/copy_32.S index 933b685e7ab6..97eb9ca0cc23 100644 --- a/arch/powerpc/lib/copy_32.S +++ b/arch/powerpc/lib/copy_32.S @@ -10,7 +10,6 @@ #include #include #include -#include #define COPY_16_BYTES \ lwz r7,4(r4); \ @@ -87,7 +86,7 @@ EXPORT_SYMBOL(memset16) * We therefore skip the optimised bloc that uses dcbz. This jump is * replaced by a nop once cache is active. This is done in machine_init() */ -_GLOBAL_KASAN(memset) +_GLOBAL(memset) cmplwi 0,r5,4 blt 7f @@ -147,7 +146,6 @@ _GLOBAL_KASAN(memset) bdnz 9b blr EXPORT_SYMBOL(memset) -EXPORT_SYMBOL_KASAN(memset) /* * This version uses dcbz on the complete cache lines in the @@ -160,12 +158,12 @@ EXPORT_SYMBOL_KASAN(memset) * We therefore jump to generic_memcpy which doesn't use dcbz. This jump is * replaced by a nop once cache is active. This is done in machine_init() */ -_GLOBAL_KASAN(memmove) +_GLOBAL(memmove) cmplw 0,r3,r4 bgt backwards_memcpy /* fall through */ -_GLOBAL_KASAN(memcpy) +_GLOBAL(memcpy) 1: b generic_memcpy patch_site 1b, patch__memcpy_nocache @@ -241,8 +239,6 @@ _GLOBAL_KASAN(memcpy) 65: blr EXPORT_SYMBOL(memcpy) EXPORT_SYMBOL(memmove) -EXPORT_SYMBOL_KASAN(memcpy) -EXPORT_SYMBOL_KASAN(memmove) generic_memcpy: srwi. r7,r5,3 diff --git a/arch/powerpc/lib/mem_64.S b/arch/powerpc/lib/mem_64.S index 6fd06cd20faa..40eaedd31486 100644 --- a/arch/powerpc/lib/mem_64.S +++ b/arch/powerpc/lib/mem_64.S @@ -8,7 +8,6 @@ #include #include #include -#include #ifndef CONFIG_KASAN _GLOBAL(__memset16) @@ -29,7 +28,7 @@ EXPORT_SYMBOL(__memset32) EXPORT_SYMBOL(__memset64) #endif -_GLOBAL_KASAN(memset) +_GLOBAL(memset) neg r0,r3 rlwimi r4,r4,8,16,23 andi. r0,r0,7 /* # bytes to be 8-byte aligned */ @@ -95,9 +94,8 @@ _GLOBAL_KASAN(memset) stb r4,0(r6) blr EXPORT_SYMBOL(memset) -EXPORT_SYMBOL_KASAN(memset) -_GLOBAL_TOC_KASAN(memmove) +_GLOBAL_TOC(memmove) cmplw 0,r3,r4 bgt backwards_memcpy b memcpy @@ -139,4 +137,3 @@ _GLOBAL(backwards_memcpy) mtctr r7 b 1b EXPORT_SYMBOL(memmove) -EXPORT_SYMBOL_KASAN(memmove) diff --git a/arch/powerpc/lib/memcpy_64.S b/arch/powerpc/lib/memcpy_64.S index b5a67e20143f..0cedd455231a 100644 --- a/arch/powerpc/lib/memcpy_64.S +++ b/arch/powerpc/lib/memcpy_64.S @@ -7,7 +7,6 @@ #include #include #include -#include #ifndef SELFTEST_CASE /* For big-endian, 0 == most CPUs, 1 == POWER6, 2 == Cell */ @@ -15,7 +14,7 @@ #endif .align 7 -_GLOBAL_TOC_KASAN(memcpy) +_GLOBAL_TOC(memcpy) BEGIN_FTR_SECTION #ifdef __LITTLE_ENDIAN__ cmpdi cr7,r5,0 @@ -227,4 +226,3 @@ END_FTR_SECTION_IFCLR(CPU_FTR_UNALIGNED_LD_STD) blr #endif EXPORT_SYMBOL(memcpy) -EXPORT_SYMBOL_KASAN(memcpy) diff --git a/arch/powerpc/net/bpf_jit.h b/arch/powerpc/net/bpf_jit.h index 44fa414dc5a7..4da8bde92e1e 100644 --- a/arch/powerpc/net/bpf_jit.h +++ b/arch/powerpc/net/bpf_jit.h @@ -195,6 +195,12 @@ struct codegen_context { #define bpf_to_ppc(r) (ctx->b2p[r]) +#ifdef CONFIG_PPC64 +#define PPC_RAW_CMPLLI(a, i) PPC_RAW_CMPLDI(a, i) +#else +#define PPC_RAW_CMPLLI(a, i) PPC_RAW_CMPLWI(a, i) +#endif + #ifdef CONFIG_PPC32 #define BPF_FIXUP_LEN 3 /* Three instructions => 12 bytes */ #else diff --git a/arch/powerpc/net/bpf_jit_comp.c b/arch/powerpc/net/bpf_jit_comp.c index 127240933612..cfe01c3544db 100644 --- a/arch/powerpc/net/bpf_jit_comp.c +++ b/arch/powerpc/net/bpf_jit_comp.c @@ -52,19 +52,19 @@ asm ( void bpf_jit_build_fentry_stubs(u32 *image, u32 *fimage, struct codegen_context *ctx) { int ool_stub_idx, long_branch_stub_idx; - int ool_stub_sz; + 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 offset. The - * OOL stub size is 4 instructions (with CONFIG_PPC_FTRACE_OUT_OF_LINE) - * or 3 instructions (without) before dummy_tramp_addr. - * - * Emit a NOP here if address is not SZL aligned. + * 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 @@ -72,8 +72,8 @@ void bpf_jit_build_fentry_stubs(u32 *image, u32 *fimage, struct codegen_context * jited_len signifies correct program size. */ - ool_stub_sz = IS_ENABLED(CONFIG_PPC_FTRACE_OUT_OF_LINE) ? 16 : 12; - if (!image || !IS_ALIGNED((unsigned long)fimage + ctx->idx*4 + ool_stub_sz, SZL)) + 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()); /* @@ -94,28 +94,29 @@ void bpf_jit_build_fentry_stubs(u32 *image, u32 *fimage, struct codegen_context /* * Long branch stub: - * .long // 8-byte aligned * 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; @@ -791,7 +792,7 @@ static void bpf_trampoline_setup_tail_call_info(u32 *image, struct codegen_conte * Setting the tail_call_info in trampoline's frame * depending on if previous frame had value or reference. */ - EMIT(PPC_RAW_CMPLWI(_R3, MAX_TAIL_CALL_CNT)); + EMIT(PPC_RAW_CMPLLI(_R3, MAX_TAIL_CALL_CNT)); PPC_BCC_CONST_SHORT(COND_GT, 8); EMIT(PPC_RAW_ADDI(_R3, _R4, -BPF_PPC_TAILCALL)); @@ -1310,6 +1311,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] / @@ -1317,14 +1319,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. * @@ -1426,10 +1428,12 @@ int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type old_t, * 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_comp64.c b/arch/powerpc/net/bpf_jit_comp64.c index 667e2d4d2c61..c1e86fe0bd79 100644 --- a/arch/powerpc/net/bpf_jit_comp64.c +++ b/arch/powerpc/net/bpf_jit_comp64.c @@ -276,7 +276,7 @@ void bpf_jit_build_prologue(u32 *image, struct codegen_context *ctx) */ EMIT(PPC_RAW_LD(bpf_to_ppc(TMP_REG_2), _R1, 0)); EMIT(PPC_RAW_LD(bpf_to_ppc(TMP_REG_1), bpf_to_ppc(TMP_REG_2), -(BPF_PPC_TAILCALL))); - EMIT(PPC_RAW_CMPLWI(bpf_to_ppc(TMP_REG_1), MAX_TAIL_CALL_CNT)); + EMIT(PPC_RAW_CMPLDI(bpf_to_ppc(TMP_REG_1), MAX_TAIL_CALL_CNT)); PPC_BCC_CONST_SHORT(COND_GT, 8); EMIT(PPC_RAW_ADDI(bpf_to_ppc(TMP_REG_1), bpf_to_ppc(TMP_REG_2), -(BPF_PPC_TAILCALL))); @@ -662,7 +662,7 @@ static int bpf_jit_emit_tail_call(u32 *image, struct codegen_context *ctx, u32 o PPC_BCC_SHORT(COND_GE, out); EMIT(PPC_RAW_LD(bpf_to_ppc(TMP_REG_1), _R1, bpf_jit_stack_tailcallinfo_offset(ctx))); - EMIT(PPC_RAW_CMPLWI(bpf_to_ppc(TMP_REG_1), MAX_TAIL_CALL_CNT)); + EMIT(PPC_RAW_CMPLDI(bpf_to_ppc(TMP_REG_1), MAX_TAIL_CALL_CNT)); PPC_BCC_CONST_SHORT(COND_LE, 8); /* dereference TMP_REG_1 */ @@ -672,7 +672,7 @@ static int bpf_jit_emit_tail_call(u32 *image, struct codegen_context *ctx, u32 o * if (tail_call_info == MAX_TAIL_CALL_CNT) * goto out; */ - EMIT(PPC_RAW_CMPLWI(bpf_to_ppc(TMP_REG_1), MAX_TAIL_CALL_CNT)); + EMIT(PPC_RAW_CMPLDI(bpf_to_ppc(TMP_REG_1), MAX_TAIL_CALL_CNT)); PPC_BCC_SHORT(COND_EQ, out); /* @@ -707,7 +707,7 @@ static int bpf_jit_emit_tail_call(u32 *image, struct codegen_context *ctx, u32 o * tail_call_info. */ EMIT(PPC_RAW_LD(bpf_to_ppc(TMP_REG_2), _R1, bpf_jit_stack_tailcallinfo_offset(ctx))); - EMIT(PPC_RAW_CMPLWI(bpf_to_ppc(TMP_REG_2), MAX_TAIL_CALL_CNT)); + EMIT(PPC_RAW_CMPLDI(bpf_to_ppc(TMP_REG_2), MAX_TAIL_CALL_CNT)); PPC_BCC_CONST_SHORT(COND_GT, 8); /* First get address of tail_call_info */ diff --git a/arch/riscv/boot/dts/sophgo/cv180x.dtsi b/arch/riscv/boot/dts/sophgo/cv180x.dtsi index ec3bf305274a..d2ec70fd515e 100644 --- a/arch/riscv/boot/dts/sophgo/cv180x.dtsi +++ b/arch/riscv/boot/dts/sophgo/cv180x.dtsi @@ -71,7 +71,7 @@ internal_mdio: mdio@0 { #size-cells = <0>; reg = <0>; - internal_ephy: phy@0 { + internal_ephy: ethernet-phy@1 { compatible = "ethernet-phy-ieee802.3-c22"; reg = <1>; }; diff --git a/arch/riscv/boot/dts/spacemit/k1-orangepi-rv2.dts b/arch/riscv/boot/dts/spacemit/k1-orangepi-rv2.dts index b907a1396b21..3844f0577c10 100644 --- a/arch/riscv/boot/dts/spacemit/k1-orangepi-rv2.dts +++ b/arch/riscv/boot/dts/spacemit/k1-orangepi-rv2.dts @@ -22,7 +22,7 @@ aliases { }; chosen { - stdout-path = "serial0"; + stdout-path = "serial0:115200n8"; }; pcie_vcc3v3: regulator-pcie-vcc3v3 { diff --git a/arch/riscv/boot/dts/spacemit/k3-com260.dtsi b/arch/riscv/boot/dts/spacemit/k3-com260.dtsi index 37627963a649..8102b9847afd 100644 --- a/arch/riscv/boot/dts/spacemit/k3-com260.dtsi +++ b/arch/riscv/boot/dts/spacemit/k3-com260.dtsi @@ -170,6 +170,7 @@ dldo3: dldo3 { dldo4: dldo4 { regulator-min-microvolt = <1800000>; regulator-max-microvolt = <1800000>; + regulator-always-on; regulator-boot-on; }; diff --git a/arch/riscv/boot/dts/spacemit/k3-pico-itx.dts b/arch/riscv/boot/dts/spacemit/k3-pico-itx.dts index b084a35aa00e..0a6f669d509a 100644 --- a/arch/riscv/boot/dts/spacemit/k3-pico-itx.dts +++ b/arch/riscv/boot/dts/spacemit/k3-pico-itx.dts @@ -328,5 +328,7 @@ &usb3d_u2phy { }; &usb3d { + phys = <&usb3d_u2phy>, <&combophy 4 PHY_TYPE_USB3>; + phy-names = "usb2-phy", "usb3-phy"; status = "okay"; }; diff --git a/arch/riscv/boot/dts/spacemit/k3.dtsi b/arch/riscv/boot/dts/spacemit/k3.dtsi index f9c2ffedeae8..af56ab9f543a 100644 --- a/arch/riscv/boot/dts/spacemit/k3.dtsi +++ b/arch/riscv/boot/dts/spacemit/k3.dtsi @@ -452,9 +452,6 @@ usb3d: usb@81a00000 { <&syscon_apmu RESET_APMU_USB3_D_VCC>, <&syscon_apmu RESET_APMU_USB3_D_PHY>; reset-names = "ahb", "vcc", "phy"; - phys = <&usb3d_u2phy>, - <&combophy 4 PHY_TYPE_USB3>; - phy-names = "usb2-phy", "usb3-phy"; phy_type = "utmi"; snps,dis_enblslpm_quirk; snps,dis_u2_susphy_quirk; @@ -1261,19 +1258,6 @@ saplic: interrupt-controller@e0804000 { riscv,num-sources = <512>; }; - clint: timer@e081c000 { - compatible = "spacemit,k3-clint", "sifive,clint0"; - reg = <0x0 0xe081c000 0x0 0x4000>; - interrupts-extended = <&cpu0_intc 3>, <&cpu0_intc 7>, - <&cpu1_intc 3>, <&cpu1_intc 7>, - <&cpu2_intc 3>, <&cpu2_intc 7>, - <&cpu3_intc 3>, <&cpu3_intc 7>, - <&cpu4_intc 3>, <&cpu4_intc 7>, - <&cpu5_intc 3>, <&cpu5_intc 7>, - <&cpu6_intc 3>, <&cpu6_intc 7>, - <&cpu7_intc 3>, <&cpu7_intc 7>; - }; - /* sec_i2c3: 0xf0614000, not available from Linux */ mimsic: interrupt-controller@f1000000 { @@ -1287,9 +1271,7 @@ mimsic: interrupt-controller@f1000000 { <&cpu4_intc 11>, <&cpu5_intc 11>, <&cpu6_intc 11>, <&cpu7_intc 11>; msi-controller; - riscv,guest-index-bits = <6>; riscv,hart-index-bits = <4>; - riscv,num-guest-ids = <511>; riscv,num-ids = <511>; status = "reserved"; }; @@ -1305,5 +1287,35 @@ maplic: interrupt-controller@f1800000 { riscv,num-sources = <512>; status = "reserved"; }; + + aclint_mswi: interrupt-controller@f1810000 { + compatible = "spacemit,k3-aclint-mswi"; + reg = <0x0 0xf1810000 0x0 0x4000>; + interrupts-extended = <&cpu0_intc 3>, <&cpu1_intc 3>, + <&cpu2_intc 3>, <&cpu3_intc 3>, + <&cpu4_intc 3>, <&cpu5_intc 3>, + <&cpu6_intc 3>, <&cpu7_intc 3>; + }; + + aclint_mtimer: timer@f1814000 { + compatible = "spacemit,k3-aclint-mtimer"; + reg = <0x0 0xf1814000 0x0 0x8000>; + reg-names = "mtimecmp"; + interrupts-extended = <&cpu0_intc 7>, <&cpu1_intc 7>, + <&cpu2_intc 7>, <&cpu3_intc 7>, + <&cpu4_intc 7>, <&cpu5_intc 7>, + <&cpu6_intc 7>, <&cpu7_intc 7>; + }; + + aclint_sswi: interrupt-controller@f181c000 { + compatible = "spacemit,k3-aclint-sswi"; + reg = <0x0 0xf181c000 0x0 0x4000>; + #interrupt-cells = <0>; + interrupt-controller; + interrupts-extended = <&cpu0_intc 1>, <&cpu1_intc 1>, + <&cpu2_intc 1>, <&cpu3_intc 1>, + <&cpu4_intc 1>, <&cpu5_intc 1>, + <&cpu6_intc 1>, <&cpu7_intc 1>; + }; }; }; diff --git a/arch/riscv/boot/dts/starfive/jh7100-common.dtsi b/arch/riscv/boot/dts/starfive/jh7100-common.dtsi index ae1a6aeb0aea..85106545090e 100644 --- a/arch/riscv/boot/dts/starfive/jh7100-common.dtsi +++ b/arch/riscv/boot/dts/starfive/jh7100-common.dtsi @@ -199,13 +199,23 @@ GPO_I2C2_PAD_SDA_OEN, }; }; - pwm_pins: pwm-0 { - pwm-pins { + pwm0_pins: pwm0-0 { + pwm0-pins { pinmux = , - ; + bias-disable; + drive-strength = <35>; + input-disable; + input-schmitt-disable; + slew-rate = <0>; + }; + }; + + pwm1_pins: pwm1-0 { + pwm1-pins { + pinmux = ; @@ -359,9 +369,15 @@ &osc_aud { clock-frequency = <27000000>; }; -&pwm { +&pwm0 { + pinctrl-names = "default"; + pinctrl-0 = <&pwm0_pins>; + status = "okay"; +}; + +&pwm1 { pinctrl-names = "default"; - pinctrl-0 = <&pwm_pins>; + pinctrl-0 = <&pwm1_pins>; status = "okay"; }; diff --git a/arch/riscv/boot/dts/starfive/jh7100.dtsi b/arch/riscv/boot/dts/starfive/jh7100.dtsi index 7de0732b8eab..90438df1f74d 100644 --- a/arch/riscv/boot/dts/starfive/jh7100.dtsi +++ b/arch/riscv/boot/dts/starfive/jh7100.dtsi @@ -360,9 +360,72 @@ watchdog@12480000 { <&rstgen JH7100_RSTN_WDT>; }; - pwm: pwm@12490000 { + pwm0: pwm@12490000 { compatible = "starfive,jh7100-pwm", "opencores,pwm-v1"; - reg = <0x0 0x12490000 0x0 0x10000>; + reg = <0x0 0x12490000 0x0 0x10>; + clocks = <&clkgen JH7100_CLK_PWM_APB>; + resets = <&rstgen JH7100_RSTN_PWM_APB>; + #pwm-cells = <3>; + status = "disabled"; + }; + + pwm1: pwm@12490010 { + compatible = "starfive,jh7100-pwm", "opencores,pwm-v1"; + reg = <0x0 0x12490010 0x0 0x10>; + clocks = <&clkgen JH7100_CLK_PWM_APB>; + resets = <&rstgen JH7100_RSTN_PWM_APB>; + #pwm-cells = <3>; + status = "disabled"; + }; + + pwm2: pwm@12490020 { + compatible = "starfive,jh7100-pwm", "opencores,pwm-v1"; + reg = <0x0 0x12490020 0x0 0x10>; + clocks = <&clkgen JH7100_CLK_PWM_APB>; + resets = <&rstgen JH7100_RSTN_PWM_APB>; + #pwm-cells = <3>; + status = "disabled"; + }; + + pwm3: pwm@12490030 { + compatible = "starfive,jh7100-pwm", "opencores,pwm-v1"; + reg = <0x0 0x12490030 0x0 0x10>; + clocks = <&clkgen JH7100_CLK_PWM_APB>; + resets = <&rstgen JH7100_RSTN_PWM_APB>; + #pwm-cells = <3>; + status = "disabled"; + }; + + pwm4: pwm@12498000 { + compatible = "starfive,jh7100-pwm", "opencores,pwm-v1"; + reg = <0x0 0x12498000 0x0 0x10>; + clocks = <&clkgen JH7100_CLK_PWM_APB>; + resets = <&rstgen JH7100_RSTN_PWM_APB>; + #pwm-cells = <3>; + status = "disabled"; + }; + + pwm5: pwm@12498010 { + compatible = "starfive,jh7100-pwm", "opencores,pwm-v1"; + reg = <0x0 0x12498010 0x0 0x10>; + clocks = <&clkgen JH7100_CLK_PWM_APB>; + resets = <&rstgen JH7100_RSTN_PWM_APB>; + #pwm-cells = <3>; + status = "disabled"; + }; + + pwm6: pwm@12498020 { + compatible = "starfive,jh7100-pwm", "opencores,pwm-v1"; + reg = <0x0 0x12498020 0x0 0x10>; + clocks = <&clkgen JH7100_CLK_PWM_APB>; + resets = <&rstgen JH7100_RSTN_PWM_APB>; + #pwm-cells = <3>; + status = "disabled"; + }; + + pwm7: pwm@12498030 { + compatible = "starfive,jh7100-pwm", "opencores,pwm-v1"; + reg = <0x0 0x12498030 0x0 0x10>; clocks = <&clkgen JH7100_CLK_PWM_APB>; resets = <&rstgen JH7100_RSTN_PWM_APB>; #pwm-cells = <3>; diff --git a/arch/riscv/boot/dts/starfive/jh7110-common.dtsi b/arch/riscv/boot/dts/starfive/jh7110-common.dtsi index a7a1c09a2c90..64de468f2c31 100644 --- a/arch/riscv/boot/dts/starfive/jh7110-common.dtsi +++ b/arch/riscv/boot/dts/starfive/jh7110-common.dtsi @@ -326,9 +326,14 @@ uboot@100000 { }; }; -&pwm { +&pwm0 { pinctrl-names = "default"; - pinctrl-0 = <&pwm_pins>; + pinctrl-0 = <&pwm0_pins>; +}; + +&pwm1 { + pinctrl-names = "default"; + pinctrl-0 = <&pwm1_pins>; }; &spi0 { @@ -528,12 +533,22 @@ GPOEN_ENABLE, }; }; - pwm_pins: pwm-0 { - pwm-pins { + pwm0_pins: pwm0-0 { + pwm0-pins { pinmux = , - ; + bias-disable; + drive-strength = <12>; + input-disable; + input-schmitt-disable; + slew-rate = <0>; + }; + }; + + pwm1_pins: pwm1-0 { + pwm1-pins { + pinmux = ; bias-disable; diff --git a/arch/riscv/boot/dts/starfive/jh7110-milkv-mars.dts b/arch/riscv/boot/dts/starfive/jh7110-milkv-mars.dts index 21873612d993..54013c70f4b4 100644 --- a/arch/riscv/boot/dts/starfive/jh7110-milkv-mars.dts +++ b/arch/riscv/boot/dts/starfive/jh7110-milkv-mars.dts @@ -68,7 +68,11 @@ &phy0 { motorcomm,tx-clk-adj-enabled; }; -&pwm { +&pwm0 { + status = "okay"; +}; + +&pwm1 { status = "okay"; }; diff --git a/arch/riscv/boot/dts/starfive/jh7110-milkv-marscm.dtsi b/arch/riscv/boot/dts/starfive/jh7110-milkv-marscm.dtsi index 025471061d43..31afac27b86d 100644 --- a/arch/riscv/boot/dts/starfive/jh7110-milkv-marscm.dtsi +++ b/arch/riscv/boot/dts/starfive/jh7110-milkv-marscm.dtsi @@ -87,7 +87,11 @@ &phy0 { motorcomm,tx-clk-adj-enabled; }; -&pwm { +&pwm0 { + status = "okay"; +}; + +&pwm1 { status = "okay"; }; diff --git a/arch/riscv/boot/dts/starfive/jh7110-pine64-star64.dts b/arch/riscv/boot/dts/starfive/jh7110-pine64-star64.dts index aec7ae3d1f5b..a9e82f25efde 100644 --- a/arch/riscv/boot/dts/starfive/jh7110-pine64-star64.dts +++ b/arch/riscv/boot/dts/starfive/jh7110-pine64-star64.dts @@ -95,7 +95,11 @@ &phy1 { motorcomm,tx-clk-100-inverted; }; -&pwm { +&pwm0 { + status = "okay"; +}; + +&pwm1 { status = "okay"; }; diff --git a/arch/riscv/boot/dts/starfive/jh7110-starfive-visionfive-2-lite.dtsi b/arch/riscv/boot/dts/starfive/jh7110-starfive-visionfive-2-lite.dtsi index f8797a666dbf..85b56a72dff7 100644 --- a/arch/riscv/boot/dts/starfive/jh7110-starfive-visionfive-2-lite.dtsi +++ b/arch/riscv/boot/dts/starfive/jh7110-starfive-visionfive-2-lite.dtsi @@ -74,7 +74,11 @@ &phy0 { tx-internal-delay-ps = <1500>; }; -&pwm { +&pwm0 { + status = "okay"; +}; + +&pwm1 { status = "okay"; }; diff --git a/arch/riscv/boot/dts/starfive/jh7110-starfive-visionfive-2.dtsi b/arch/riscv/boot/dts/starfive/jh7110-starfive-visionfive-2.dtsi index edc8f4588133..35208f95cd3d 100644 --- a/arch/riscv/boot/dts/starfive/jh7110-starfive-visionfive-2.dtsi +++ b/arch/riscv/boot/dts/starfive/jh7110-starfive-visionfive-2.dtsi @@ -73,7 +73,11 @@ &pcie1 { status = "okay"; }; -&pwm { +&pwm0 { + status = "okay"; +}; + +&pwm1 { status = "okay"; }; diff --git a/arch/riscv/boot/dts/starfive/jh7110.dtsi b/arch/riscv/boot/dts/starfive/jh7110.dtsi index 9c3e4598747e..82ea63f715b0 100644 --- a/arch/riscv/boot/dts/starfive/jh7110.dtsi +++ b/arch/riscv/boot/dts/starfive/jh7110.dtsi @@ -846,9 +846,72 @@ i2stx1: i2s@120c0000 { status = "disabled"; }; - pwm: pwm@120d0000 { + pwm0: pwm@120d0000 { compatible = "starfive,jh7110-pwm", "opencores,pwm-v1"; - reg = <0x0 0x120d0000 0x0 0x10000>; + reg = <0x0 0x120d0000 0x0 0x10>; + clocks = <&syscrg JH7110_SYSCLK_PWM_APB>; + resets = <&syscrg JH7110_SYSRST_PWM_APB>; + #pwm-cells = <3>; + status = "disabled"; + }; + + pwm1: pwm@120d0010 { + compatible = "starfive,jh7110-pwm", "opencores,pwm-v1"; + reg = <0x0 0x120d0010 0x0 0x10>; + clocks = <&syscrg JH7110_SYSCLK_PWM_APB>; + resets = <&syscrg JH7110_SYSRST_PWM_APB>; + #pwm-cells = <3>; + status = "disabled"; + }; + + pwm2: pwm@120d0020 { + compatible = "starfive,jh7110-pwm", "opencores,pwm-v1"; + reg = <0x0 0x120d0020 0x0 0x10>; + clocks = <&syscrg JH7110_SYSCLK_PWM_APB>; + resets = <&syscrg JH7110_SYSRST_PWM_APB>; + #pwm-cells = <3>; + status = "disabled"; + }; + + pwm3: pwm@120d0030 { + compatible = "starfive,jh7110-pwm", "opencores,pwm-v1"; + reg = <0x0 0x120d0030 0x0 0x10>; + clocks = <&syscrg JH7110_SYSCLK_PWM_APB>; + resets = <&syscrg JH7110_SYSRST_PWM_APB>; + #pwm-cells = <3>; + status = "disabled"; + }; + + pwm4: pwm@120d8000 { + compatible = "starfive,jh7110-pwm", "opencores,pwm-v1"; + reg = <0x0 0x120d8000 0x0 0x10>; + clocks = <&syscrg JH7110_SYSCLK_PWM_APB>; + resets = <&syscrg JH7110_SYSRST_PWM_APB>; + #pwm-cells = <3>; + status = "disabled"; + }; + + pwm5: pwm@120d8010 { + compatible = "starfive,jh7110-pwm", "opencores,pwm-v1"; + reg = <0x0 0x120d8010 0x0 0x10>; + clocks = <&syscrg JH7110_SYSCLK_PWM_APB>; + resets = <&syscrg JH7110_SYSRST_PWM_APB>; + #pwm-cells = <3>; + status = "disabled"; + }; + + pwm6: pwm@120d8020 { + compatible = "starfive,jh7110-pwm", "opencores,pwm-v1"; + reg = <0x0 0x120d8020 0x0 0x10>; + clocks = <&syscrg JH7110_SYSCLK_PWM_APB>; + resets = <&syscrg JH7110_SYSRST_PWM_APB>; + #pwm-cells = <3>; + status = "disabled"; + }; + + pwm7: pwm@120d8030 { + compatible = "starfive,jh7110-pwm", "opencores,pwm-v1"; + reg = <0x0 0x120d8030 0x0 0x10>; clocks = <&syscrg JH7110_SYSCLK_PWM_APB>; resets = <&syscrg JH7110_SYSRST_PWM_APB>; #pwm-cells = <3>; diff --git a/arch/riscv/include/asm/insn.h b/arch/riscv/include/asm/insn.h index c3005573e8c9..ad348d8b8857 100644 --- a/arch/riscv/include/asm/insn.h +++ b/arch/riscv/include/asm/insn.h @@ -142,7 +142,7 @@ #define RVG_OPCODE_JAL 0x6f #define RVG_OPCODE_SYSTEM 0x73 #define RVG_SYSTEM_CSR_OFF 20 -#define RVG_SYSTEM_CSR_MASK GENMASK(12, 0) +#define RVG_SYSTEM_CSR_MASK GENMASK(11, 0) /* parts of opcode for RVF, RVD and RVQ */ #define RVFDQ_FL_FS_WIDTH_OFF 12 diff --git a/arch/riscv/net/bpf_jit_comp64.c b/arch/riscv/net/bpf_jit_comp64.c index 01fe66774f02..d09dc27320b2 100644 --- a/arch/riscv/net/bpf_jit_comp64.c +++ b/arch/riscv/net/bpf_jit_comp64.c @@ -23,11 +23,11 @@ /* fentry and TCC init insns will be skipped on tailcall */ #define RV_TAILCALL_OFFSET ((RV_FENTRY_NINSNS + 1) * 4) -#define RV_REG_TCC RV_REG_A6 +#define RV_REG_TCC RV_REG_T5 #define RV_REG_ARENA RV_REG_S7 /* For storing arena_vm_start */ static const int regmap[] = { - [BPF_REG_0] = RV_REG_A5, + [BPF_REG_0] = RV_REG_T6, [BPF_REG_1] = RV_REG_A0, [BPF_REG_2] = RV_REG_A1, [BPF_REG_3] = RV_REG_A2, @@ -47,13 +47,13 @@ static const int pt_regmap[] = { [RV_REG_A2] = offsetof(struct pt_regs, a2), [RV_REG_A3] = offsetof(struct pt_regs, a3), [RV_REG_A4] = offsetof(struct pt_regs, a4), - [RV_REG_A5] = offsetof(struct pt_regs, a5), [RV_REG_S1] = offsetof(struct pt_regs, s1), [RV_REG_S2] = offsetof(struct pt_regs, s2), [RV_REG_S3] = offsetof(struct pt_regs, s3), [RV_REG_S4] = offsetof(struct pt_regs, s4), [RV_REG_S5] = offsetof(struct pt_regs, s5), [RV_REG_T0] = offsetof(struct pt_regs, t0), + [RV_REG_T6] = offsetof(struct pt_regs, t6), }; enum { @@ -239,7 +239,7 @@ static void __build_epilogue(bool is_tail_call, struct rv_jit_context *ctx) emit_addi(RV_REG_SP, RV_REG_SP, stack_adjust, ctx); /* Set return value. */ if (!is_tail_call) - emit_addiw(RV_REG_A0, RV_REG_A5, 0, ctx); + emit_addiw(RV_REG_A0, regmap[BPF_REG_0], 0, ctx); emit_jalr(RV_REG_ZERO, is_tail_call ? RV_REG_T3 : RV_REG_RA, is_tail_call ? RV_TAILCALL_OFFSET : 0, ctx); } @@ -875,7 +875,8 @@ int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type old_t, return ret; } -static void store_args(int nr_arg_slots, int args_off, struct rv_jit_context *ctx) +static void store_args(int nr_arg_slots, int args_off, int stack_args_off, + struct rv_jit_context *ctx) { int i; @@ -883,8 +884,8 @@ static void store_args(int nr_arg_slots, int args_off, struct rv_jit_context *ct if (i < RV_MAX_REG_ARGS) { emit_sd(RV_REG_FP, -args_off, RV_REG_A0 + i, ctx); } else { - /* skip slots for T0 and FP of traced function */ - emit_ld(RV_REG_T1, 16 + (i - RV_MAX_REG_ARGS) * 8, RV_REG_FP, ctx); + emit_ld(RV_REG_T1, stack_args_off + + (i - RV_MAX_REG_ARGS) * 8, RV_REG_FP, ctx); emit_sd(RV_REG_FP, -args_off, RV_REG_T1, ctx); } args_off -= 8; @@ -1100,7 +1101,7 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, save_ret = flags & (BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_RET_FENTRY_RET); if (save_ret) - stack_size += 16; /* Save both A5 (BPF R0) and A0 */ + stack_size += 16; /* Save both RV_REG_T6 (BPF R0) and RV_REG_A0 */ retval_off = stack_size; stack_size += nr_arg_slots * 8; @@ -1179,7 +1180,12 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, func_meta = nr_arg_slots; emit_store_stack_imm64(RV_REG_T1, -func_meta_off, func_meta, ctx); - store_args(nr_arg_slots, args_off, ctx); + /* + * A direct struct_ops call has its first stack argument at the incoming + * SP, which the trampoline keeps as FP. The fentry path pushes the + * parent frame first, so its incoming stack arguments start at FP + 16. + */ + store_args(nr_arg_slots, args_off, is_struct_ops ? 0 : 16, ctx); if (bpf_fsession_cnt(tnodes)) { /* clear all session cookies' value */ diff --git a/arch/riscv/net/bpf_jit_core.c b/arch/riscv/net/bpf_jit_core.c index cbfcd287ea16..059db1adeaf8 100644 --- a/arch/riscv/net/bpf_jit_core.c +++ b/arch/riscv/net/bpf_jit_core.c @@ -237,6 +237,7 @@ void bpf_jit_free(struct bpf_prog *prog) kvfree(jit_data->ctx.offset); kfree(jit_data); } + prog->bpf_func = (void *)prog->bpf_func - cfi_get_offset(); hdr = bpf_jit_binary_pack_hdr(prog); bpf_jit_binary_pack_free(hdr, NULL); WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(prog)); diff --git a/arch/riscv/net/bpf_timed_may_goto.S b/arch/riscv/net/bpf_timed_may_goto.S index 02c637d87420..6ec37f634aff 100644 --- a/arch/riscv/net/bpf_timed_may_goto.S +++ b/arch/riscv/net/bpf_timed_may_goto.S @@ -10,23 +10,28 @@ * - output: updated count in BPF_REG_AX (t0) * * Calls bpf_check_timed_may_goto(ptr) with the standard RISC-V ABI, where - * ptr = BPF_REG_FP (s5) + BPF_REG_AX (t0). BPF R0-R5 (a5, a0-a4) are saved - * across the call; BPF_REG_FP (s5) is callee-saved and needs no saving. + * ptr = BPF_REG_FP (s5) + BPF_REG_AX (t0). BPF R0-R5 (t6, a0-a4) and stack + * arguments 6-8 (a5-a7) are saved across the call; BPF_REG_FP (s5) is + * callee-saved and needs no saving. */ SYM_FUNC_START(arch_bpf_timed_may_goto) - addi sp, sp, -(8*SZREG) - REG_S ra, 7*SZREG(sp) - REG_S s0, 6*SZREG(sp) - addi s0, sp, 8*SZREG + addi sp, sp, -(12*SZREG) + REG_S ra, 11*SZREG(sp) + REG_S s0, 10*SZREG(sp) + addi s0, sp, 12*SZREG - /* Save BPF registers R0-R5 (a5, a0-a4) */ - REG_S a5, 5*SZREG(sp) + /* Save BPF registers R0-R5 (t6, a0-a4) */ + REG_S t6, 5*SZREG(sp) REG_S a0, 4*SZREG(sp) REG_S a1, 3*SZREG(sp) REG_S a2, 2*SZREG(sp) REG_S a3, 1*SZREG(sp) REG_S a4, 0*SZREG(sp) + /* Save stack arguments 6-8 (a5-a7) */ + REG_S a5, 6*SZREG(sp) + REG_S a6, 7*SZREG(sp) + REG_S a7, 8*SZREG(sp) add a0, t0, s5 call bpf_check_timed_may_goto @@ -38,10 +43,14 @@ SYM_FUNC_START(arch_bpf_timed_may_goto) REG_L a2, 2*SZREG(sp) REG_L a1, 3*SZREG(sp) REG_L a0, 4*SZREG(sp) - REG_L a5, 5*SZREG(sp) + REG_L t6, 5*SZREG(sp) + /* Restore stack arguments 6-8 */ + REG_L a5, 6*SZREG(sp) + REG_L a6, 7*SZREG(sp) + REG_L a7, 8*SZREG(sp) - REG_L s0, 6*SZREG(sp) - REG_L ra, 7*SZREG(sp) - addi sp, sp, 8*SZREG + REG_L s0, 10*SZREG(sp) + REG_L ra, 11*SZREG(sp) + addi sp, sp, 12*SZREG ret SYM_FUNC_END(arch_bpf_timed_may_goto) diff --git a/arch/s390/include/asm/entry-percpu.h b/arch/s390/include/asm/entry-percpu.h index 4ef47265cfce..f6f79ec4bee3 100644 --- a/arch/s390/include/asm/entry-percpu.h +++ b/arch/s390/include/asm/entry-percpu.h @@ -2,79 +2,42 @@ #ifndef ARCH_S390_ENTRY_PERCPU_H #define ARCH_S390_ENTRY_PERCPU_H -#include +#include #include #include #include -#include static __always_inline void percpu_entry(struct pt_regs *regs) { struct lowcore *lc = get_lowcore(); - if (user_mode(regs)) - return; regs->cpu = lc->cpu_nr; regs->percpu_register = lc->percpu_register; lc->percpu_register = 0; } -static __always_inline bool percpu_code_check(struct pt_regs *regs) -{ - unsigned int insn, disp; - struct kprobe *p; - - if (likely(user_mode(regs) || !regs->percpu_register)) - return false; - /* - * Within a percpu code section - check if the percpu base register - * needs to be updated. This is the case if the PSW does not point to - * the ADD instruction within the section. - * - AG %rx,percpu_offset_in_lowcore(%r0,%r0) - * which adds the percpu offset to the percpu base register. - */ - lockdep_assert_preemption_disabled(); -again: - insn = READ_ONCE(*(u16 *)psw_bits(regs->psw).ia); - if (unlikely(insn == BREAKPOINT_INSTRUCTION)) { - p = get_kprobe((void *)psw_bits(regs->psw).ia); - /* - * If the kprobe is concurrently removed on a different CPU - * it might not be found anymore. However text must have - * been restored - try again. - */ - if (!p) - goto again; - insn = p->opcode; - } - if ((insn & 0xff0f) != 0xe300) - return true; - disp = offsetof(struct lowcore, percpu_offset); - if (machine_has_relocated_lowcore()) - disp += LOWCORE_ALT_ADDRESS; - insn = (disp & 0xff000) >> 4 | (disp & 0x00fff) << 16 | 0x8; - if (*(u32 *)(psw_bits(regs->psw).ia + 2) != insn) - return true; - return false; -} - -static __always_inline void percpu_exit(struct pt_regs *regs, bool needs_fixup) +static __always_inline void percpu_exit(struct pt_regs *regs) { + unsigned char regval, regpcp, regoff, regptr; struct lowcore *lc = get_lowcore(); - unsigned char reg; - if (user_mode(regs)) - return; - reg = regs->percpu_register; - lc->percpu_register = reg; - if (likely(!needs_fixup)) + if (!regs->percpu_register) return; - /* Check if process has been migrated to a different CPU. */ + regval = regs->percpu_register; + lc->percpu_register = regval; + /* Migrated to a different CPU? */ if (regs->cpu == lc->cpu_nr) return; - /* Fixup percpu base register */ - regs->gprs[reg] -= __per_cpu_offset[regs->cpu]; - regs->gprs[reg] += lc->percpu_offset; + regpcp = FIELD_GET(PCPU_REG_PCP, regval); + regoff = FIELD_GET(PCPU_REG_OFF, regval); + regptr = regoff + 1; + /* + * Update register 'regoff' with the current CPU's percpu offset, + * and recalculate and update current CPU's percpu variable address + * contained in register 'regptr'. + */ + regs->gprs[regoff] = lc->percpu_offset; + regs->gprs[regptr] = regs->gprs[regpcp] + regs->gprs[regoff]; } #endif diff --git a/arch/s390/include/asm/lowcore.h b/arch/s390/include/asm/lowcore.h index 5cef215d30e7..0e2d3af01ecb 100644 --- a/arch/s390/include/asm/lowcore.h +++ b/arch/s390/include/asm/lowcore.h @@ -222,6 +222,9 @@ struct lowcore { __u8 pad_0x1900[0x2000-0x1900]; /* 0x1900 */ } __packed __aligned(8192); +#define LC_PERCPU_OFFSET offsetof(struct lowcore, percpu_offset) +#define LC_PERCPU_REGISTER offsetof(struct lowcore, percpu_register) + static __always_inline struct lowcore *get_lowcore(void) { struct lowcore *lc; diff --git a/arch/s390/include/asm/percpu.h b/arch/s390/include/asm/percpu.h index feb58acf87d6..3f983285f944 100644 --- a/arch/s390/include/asm/percpu.h +++ b/arch/s390/include/asm/percpu.h @@ -14,17 +14,16 @@ #define arch_raw_cpu_ptr(_ptr) \ ({ \ - unsigned long lc_percpu, tcp_ptr__; \ + unsigned long tcp_ptr__; \ \ tcp_ptr__ = (__force unsigned long)(_ptr); \ - lc_percpu = offsetof(struct lowcore, percpu_offset); \ asm_inline volatile( \ ALTERNATIVE("ag %[__ptr__],%[offzero](%%r0)\n", \ "ag %[__ptr__],%[offalt](%%r0)\n", \ ALT_FEATURE(MFEATURE_LOWCORE)) \ : [__ptr__] "+d" (tcp_ptr__) \ - : [offzero] "i" (lc_percpu), \ - [offalt] "i" (lc_percpu + LOWCORE_ALT_ADDRESS), \ + : [offzero] "i" (LC_PERCPU_OFFSET), \ + [offalt] "i" (LC_PERCPU_OFFSET + LOWCORE_ALT_ADDRESS), \ "m" (((struct lowcore *)0)->percpu_offset) \ : "cc"); \ (TYPEOF_UNQUAL(*(_ptr)) __force __kernel *)tcp_ptr__; \ @@ -68,60 +67,109 @@ * this. The idea is that this_cpu operations based on atomic instructions are * guarded with mviy instructions: * - * - The first mviy instruction writes the register number, which contains the - * percpu address variable to lowcore. This also indicates that a percpu - * code section is executed. + * - The first mviy instruction writes the register number of the percpu address + * variable and the even register number of a register pair (which encodes two + * registers: the even register for the percpu offset and the odd register for + * the percpu pointer) to lowcore. This also indicates that a percpu code + * section is executed. * - * - The first mviy instruction following the mviy instruction must be the ag - * instruction which adds the percpu offset to the percpu address register. + * - The mviy instruction is followed by the lg instruction which loads the + * percpu offset into the even register of the pair and the la instruction + * which adds the percpu offset and the percpu address into the odd register + * of the pair (the percpu pointer register). * * - Afterwards the atomic percpu operation follows. * * - Then a second mviy instruction writes a zero to lowcore, which indicates * the end of the percpu code section. * - * - In case of an interrupt/exception/nmi the register number which was - * written to lowcore is copied to the exception frame (pt_regs), and a zero - * is written to lowcore. + * - In case of an interrupt/exception/nmi the encoded register numbers which + * were written to lowcore are copied to the exception frame (pt_regs), and a + * zero is written to lowcore. * * - On return to the previous context it is checked if a percpu code section - * was executed (saved register number not zero), and if the process was - * migrated to a different cpu. If the percpu offset was already added to - * the percpu address register (instruction address does _not_ point to the - * ag instruction) the content of the percpu address register is adjusted so - * it points to percpu variable of the new cpu. + * was executed (saved register value not zero), and if the process was + * migrated to a different cpu. The content of the percpu offset register + * (even register of the pair) is reloaded with the current cpu's percpu + * offset and the percpu pointer register (odd register of the pair) is + * recalculated so it points to the percpu variable of the new cpu. * * Inline assemblies making use of this typically have a code sequence like: * - * MVIY_PERCPU(...) <- start of percpu code section - * AG_ALT(...) <- add percpu offset; must be the second instruction - * atomic_op <- atomic op - * MVIY_ALT(...) <- end of percpu code section + * __PCPU_BEGIN(...) <- start of percpu code section + * atomic_op <- atomic op + * __PCPU_END(...) <- end of percpu code section */ -#define MVIY_PERCPU(disp, dispalt, reg) \ - ".macro GEN_MVIY disp reg\n" \ - ".irp rs,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15\n" \ - " .ifc \\reg,%%r\\rs\n" \ - " mviy \\disp(%%r0),\\rs\n" \ +#define LC_ALT_ADDR __stringify(LOWCORE_ALT_ADDRESS) + +#define DEFINE_GR_NUM \ + ".macro _GR_NUM opd, gr\n" \ + ".set \\opd,255\n" \ + ".irp rs,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15\n" \ + " .ifc \\gr,%%r\\rs\n" \ + " \\opd = \\rs\n" \ " .endif\n" \ ".endr\n" \ - ".endm\n" \ - ALTERNATIVE("GEN_MVIY " disp ", " reg "\n", \ - "GEN_MVIY " dispalt ", " reg "\n", \ - ALT_FEATURE(MFEATURE_LOWCORE)) \ - ".purgem GEN_MVIY\n" - -#define MVIY_ALT(disp, dispalt) \ - ALTERNATIVE(" mviy " disp "(%%r0),0\n", \ - " mviy " dispalt "(%%r0),0\n", \ + ".if \\opd == 255\n" \ + " .error \"Illegal register number\"\n" \ + ".endif\n" \ + ".endm\n" + +#define UNDEF_GR_NUM \ + ".purgem _GR_NUM\n" + +#define PCPU_REG_PCP_SHIFT 0 +#define PCPU_REG_PCP GENMASK(3, 0) +#define PCPU_REG_OFF_SHIFT 4 +#define PCPU_REG_OFF GENMASK(7, 4) + +#define __PCPU_MVIY(lcreg, imm) \ + ALTERNATIVE(" mviy " lcreg "(%%r0)," imm "\n", \ + " mviy " lcreg "+" LC_ALT_ADDR "(%%r0)," imm "\n", \ ALT_FEATURE(MFEATURE_LOWCORE)) -#define AG_ALT(disp, dispalt, reg) \ - ALTERNATIVE(" ag " reg ", " disp "(%%r0)\n", \ - " ag " reg ", " dispalt "(%%r0)\n", \ +#define __PCPU_LG(regoff, lcoff) \ + ALTERNATIVE(" lg " regoff ", " lcoff "(%%r0)\n", \ + " lg " regoff ", " lcoff "+" LC_ALT_ADDR "(%%r0)\n", \ ALT_FEATURE(MFEATURE_LOWCORE)) +#define __PCPU_LA(regptr, regoff, regpcp) \ + " la " regptr ",0(" regoff "," regpcp ")\n" + +#define __PCPU_CALC_REGVAL(regpcp, regoff) \ + "(" regpcp " << " __stringify(PCPU_REG_PCP_SHIFT) ") |" \ + "(" regoff " << " __stringify(PCPU_REG_OFF_SHIFT) ")" + +#define __PCPU_CHECK_REGS(regpcp, regoff, regptr) \ + ".if " regoff " & 1\n" \ + " .error \"Percpu offset register must be even\"\n" \ + ".endif\n" \ + ".if (" regpcp " == 0) || (" regoff " == 0)\n" \ + " .error \"Percpu address and offset register must be non-zero\"\n"\ + ".endif\n" \ + ".if " regptr " != " regoff " + 1\n" \ + " .error \"Percpu pointer and offset register must be a pair\"\n" \ + ".endif\n" \ + ".if (" regpcp " == " regoff ") || (" regpcp " == " regptr ")\n" \ + " .error \"Percpu registers must be distinct\"\n" \ + ".endif\n" + +#define __PCPU_BEGIN(lcreg, lcoff, regpcp, regoff, regptr) \ + DEFINE_GR_NUM \ + "_GR_NUM .Lregpcp, " regpcp "\n" \ + "_GR_NUM .Lregoff, " regoff "\n" \ + "_GR_NUM .Lregptr, " regptr "\n" \ + UNDEF_GR_NUM \ + __PCPU_CHECK_REGS(".Lregpcp", ".Lregoff", ".Lregptr") \ + ".set .Lregval, " __PCPU_CALC_REGVAL(".Lregpcp", ".Lregoff") "\n" \ + __PCPU_MVIY(lcreg, ".Lregval") \ + __PCPU_LG(regoff, lcoff) \ + __PCPU_LA(regptr, regoff, regpcp) + +#define __PCPU_END(lcreg) \ + __PCPU_MVIY(lcreg, "0") + #ifndef MARCH_HAS_Z196_FEATURES #define this_cpu_add_4(pcp, val) arch_this_cpu_to_op_simple(pcp, val, +) @@ -137,44 +185,38 @@ #define arch_this_cpu_add(pcp, val, op1, op2, szcast) \ do { \ - unsigned long lc_pcpr, lc_pcpo; \ typedef typeof(pcp) pcp_op_T__; \ + union register_pair rp__; \ pcp_op_T__ val__ = (val); \ pcp_op_T__ old__, *ptr__; \ \ - lc_pcpr = offsetof(struct lowcore, percpu_register); \ - lc_pcpo = offsetof(struct lowcore, percpu_offset); \ ptr__ = PERCPU_PTR(&(pcp)); \ if (__builtin_constant_p(val__) && \ ((szcast)val__ > -129) && ((szcast)val__ < 128)) { \ - asm volatile( \ - MVIY_PERCPU("%[disppcpr]", "%[dispaltpcpr]", "%[ptr__]")\ - AG_ALT("%[disppcpo]", "%[dispaltpcpo]", "%[ptr__]") \ - op2 " 0(%[ptr__]),%[val__]\n" \ - MVIY_ALT("%[disppcpr]", "%[dispaltpcpr]") \ - : [ptr__] "+&a" (ptr__), "+m" (*ptr__), \ + asm_inline volatile( \ + __PCPU_BEGIN("%[lcreg]","%[lcoff]","%[ptr__]", \ + "%[pair__]","%N[pair__]") \ + op2 " 0(%N[pair__]),%[val__]\n" \ + __PCPU_END("%[lcreg]") \ + : [pair__] "=&a" (rp__.pair), "+m" (*ptr__), \ "=m" (((struct lowcore *)0)->percpu_register) \ - : [val__] "i" ((szcast)val__), \ - [disppcpr] "i" (lc_pcpr), \ - [disppcpo] "i" (lc_pcpo), \ - [dispaltpcpr] "i" (lc_pcpr + LOWCORE_ALT_ADDRESS), \ - [dispaltpcpo] "i" (lc_pcpo + LOWCORE_ALT_ADDRESS), \ + : [val__] "i" ((szcast)val__), [ptr__] "a" (ptr__), \ + [lcreg] "i" (LC_PERCPU_REGISTER), \ + [lcoff] "i" (LC_PERCPU_OFFSET), \ "m" (((struct lowcore *)0)->percpu_offset) \ : "cc"); \ } else { \ - asm volatile( \ - MVIY_PERCPU("%[disppcpr]", "%[dispaltpcpr]", "%[ptr__]")\ - AG_ALT("%[disppcpo]", "%[dispaltpcpo]", "%[ptr__]") \ - op1 " %[old__],%[val__],0(%[ptr__])\n" \ - MVIY_ALT("%[disppcpr]", "%[dispaltpcpr]") \ - : [old__] "=&d" (old__), \ - [ptr__] "+&a" (ptr__), "+m" (*ptr__), \ + asm_inline volatile( \ + __PCPU_BEGIN("%[lcreg]","%[lcoff]","%[ptr__]", \ + "%[pair__]","%N[pair__]") \ + op1 " %[old__],%[val__],0(%N[pair__])\n" \ + __PCPU_END("%[lcreg]") \ + : [old__] "=&d" (old__), [pair__] "=&a" (rp__.pair), \ + "+m" (*ptr__), \ "=m" (((struct lowcore *)0)->percpu_register) \ - : [val__] "d" (val__), \ - [disppcpr] "i" (lc_pcpr), \ - [disppcpo] "i" (lc_pcpo), \ - [dispaltpcpr] "i" (lc_pcpr + LOWCORE_ALT_ADDRESS), \ - [dispaltpcpo] "i" (lc_pcpo + LOWCORE_ALT_ADDRESS), \ + : [val__] "d" (val__), [ptr__] "a" (ptr__), \ + [lcreg] "i" (LC_PERCPU_REGISTER), \ + [lcoff] "i" (LC_PERCPU_OFFSET), \ "m" (((struct lowcore *)0)->percpu_offset) \ : "cc"); \ } \ @@ -185,27 +227,23 @@ do { \ #define arch_this_cpu_add_return(pcp, val, op) \ ({ \ - unsigned long lc_pcpr, lc_pcpo; \ typedef typeof(pcp) pcp_op_T__; \ + union register_pair rp__; \ pcp_op_T__ val__ = (val); \ pcp_op_T__ old__, *ptr__; \ \ - lc_pcpr = offsetof(struct lowcore, percpu_register); \ - lc_pcpo = offsetof(struct lowcore, percpu_offset); \ ptr__ = PERCPU_PTR(&(pcp)); \ asm_inline volatile( \ - MVIY_PERCPU("%[disppcpr]", "%[dispaltpcpr]", "%[ptr__]")\ - AG_ALT("%[disppcpo]", "%[dispaltpcpo]", "%[ptr__]") \ - op " %[old__],%[val__],0(%[ptr__])\n" \ - MVIY_ALT("%[disppcpr]", "%[dispaltpcpr]") \ - : [old__] "=&d" (old__), \ - [ptr__] "+&a" (ptr__), "+m" (*ptr__), \ + __PCPU_BEGIN("%[lcreg]","%[lcoff]","%[ptr__]", \ + "%[pair__]","%N[pair__]") \ + op " %[old__],%[val__],0(%N[pair__])\n" \ + __PCPU_END("%[lcreg]") \ + : [old__] "=&d" (old__), [pair__] "=&a" (rp__.pair), \ + "+m" (*ptr__), \ "=m" (((struct lowcore *)0)->percpu_register) \ - : [val__] "d" (val__), \ - [disppcpr] "i" (lc_pcpr), \ - [disppcpo] "i" (lc_pcpo), \ - [dispaltpcpr] "i" (lc_pcpr + LOWCORE_ALT_ADDRESS), \ - [dispaltpcpo] "i" (lc_pcpo + LOWCORE_ALT_ADDRESS), \ + : [val__] "d" (val__), [ptr__] "a" (ptr__), \ + [lcreg] "i" (LC_PERCPU_REGISTER), \ + [lcoff] "i" (LC_PERCPU_OFFSET), \ "m" (((struct lowcore *)0)->percpu_offset) \ : "cc"); \ old__ + val__; \ @@ -216,27 +254,23 @@ do { \ #define arch_this_cpu_to_op(pcp, val, op) \ do { \ - unsigned long lc_pcpr, lc_pcpo; \ typedef typeof(pcp) pcp_op_T__; \ + union register_pair rp__; \ pcp_op_T__ val__ = (val); \ pcp_op_T__ old__, *ptr__; \ \ - lc_pcpr = offsetof(struct lowcore, percpu_register); \ - lc_pcpo = offsetof(struct lowcore, percpu_offset); \ ptr__ = PERCPU_PTR(&(pcp)); \ asm_inline volatile( \ - MVIY_PERCPU("%[disppcpr]", "%[dispaltpcpr]", "%[ptr__]")\ - AG_ALT("%[disppcpo]", "%[dispaltpcpo]", "%[ptr__]") \ - op " %[old__],%[val__],0(%[ptr__])\n" \ - MVIY_ALT("%[disppcpr]", "%[dispaltpcpr]") \ - : [old__] "=&d" (old__), \ - [ptr__] "+&a" (ptr__), "+m" (*ptr__), \ + __PCPU_BEGIN("%[lcreg]","%[lcoff]","%[ptr__]", \ + "%[pair__]","%N[pair__]") \ + op " %[old__],%[val__],0(%N[pair__])\n" \ + __PCPU_END("%[lcreg]") \ + : [old__] "=&d" (old__), [pair__] "=&a" (rp__.pair), \ + "+m" (*ptr__), \ "=m" (((struct lowcore *)0)->percpu_register) \ - : [val__] "d" (val__), \ - [disppcpr] "i" (lc_pcpr), \ - [disppcpo] "i" (lc_pcpo), \ - [dispaltpcpr] "i" (lc_pcpr + LOWCORE_ALT_ADDRESS), \ - [dispaltpcpo] "i" (lc_pcpo + LOWCORE_ALT_ADDRESS), \ + : [val__] "d" (val__), [ptr__] "a" (ptr__), \ + [lcreg] "i" (LC_PERCPU_REGISTER), \ + [lcoff] "i" (LC_PERCPU_OFFSET), \ "m" (((struct lowcore *)0)->percpu_offset) \ : "cc"); \ } while (0) @@ -250,24 +284,22 @@ do { \ #define arch_this_cpu_read(pcp, op) \ ({ \ - unsigned long lc_pcpr, lc_pcpo, res__; \ typedef typeof(pcp) pcp_op_T__; \ + union register_pair rp__; \ + unsigned long res__; \ pcp_op_T__ *ptr__; \ \ - lc_pcpr = offsetof(struct lowcore, percpu_register); \ - lc_pcpo = offsetof(struct lowcore, percpu_offset); \ ptr__ = PERCPU_PTR(&(pcp)); \ asm_inline volatile( \ - MVIY_PERCPU("%[disppcpr]", "%[dispaltpcpr]", "%[ptr__]")\ - AG_ALT("%[disppcpo]", "%[dispaltpcpo]", "%[ptr__]") \ - op " %[res__],0(%[ptr__])\n" \ - MVIY_ALT("%[disppcpr]", "%[dispaltpcpr]") \ - : [res__] "=&d" (res__), [ptr__] "+&a" (ptr__), \ + __PCPU_BEGIN("%[lcreg]","%[lcoff]","%[ptr__]", \ + "%[pair__]","%N[pair__]") \ + op " %[res__],0(%N[pair__])\n" \ + __PCPU_END("%[lcreg]") \ + : [res__] "=&d" (res__), [pair__] "=&a" (rp__.pair), \ "=m" (((struct lowcore *)0)->percpu_register) \ - : [disppcpr] "i" (lc_pcpr), \ - [disppcpo] "i" (lc_pcpo), \ - [dispaltpcpr] "i" (lc_pcpr + LOWCORE_ALT_ADDRESS), \ - [dispaltpcpo] "i" (lc_pcpo + LOWCORE_ALT_ADDRESS), \ + : [ptr__] "a" (ptr__), \ + [lcreg] "i" (LC_PERCPU_REGISTER), \ + [lcoff] "i" (LC_PERCPU_OFFSET), \ "m" (*ptr__), \ "m" (((struct lowcore *)0)->percpu_offset) \ : "cc"); \ @@ -281,25 +313,21 @@ do { \ #define arch_this_cpu_write(pcp, val, op) \ do { \ - unsigned long lc_pcpr, lc_pcpo; \ typedef typeof(pcp) pcp_op_T__; \ + union register_pair rp__; \ pcp_op_T__ *ptr__, val__ = (val); \ \ - lc_pcpr = offsetof(struct lowcore, percpu_register); \ - lc_pcpo = offsetof(struct lowcore, percpu_offset); \ ptr__ = PERCPU_PTR(&(pcp)); \ asm_inline volatile( \ - MVIY_PERCPU("%[disppcpr]", "%[dispaltpcpr]", "%[ptr__]")\ - AG_ALT("%[disppcpo]", "%[dispaltpcpo]", "%[ptr__]") \ - op " %[val__],0(%[ptr__])\n" \ - MVIY_ALT("%[disppcpr]", "%[dispaltpcpr]") \ - : [ptr__] "+&a" (ptr__), "=m" (*ptr__), \ + __PCPU_BEGIN("%[lcreg]","%[lcoff]","%[ptr__]", \ + "%[pair__]","%N[pair__]") \ + op " %[val__],0(%N[pair__])\n" \ + __PCPU_END("%[lcreg]") \ + : [pair__] "=&a" (rp__.pair), "=m" (*ptr__), \ "=m" (((struct lowcore *)0)->percpu_register) \ - : [val__] "d" (val__), \ - [disppcpr] "i" (lc_pcpr), \ - [disppcpo] "i" (lc_pcpo), \ - [dispaltpcpr] "i" (lc_pcpr + LOWCORE_ALT_ADDRESS), \ - [dispaltpcpo] "i" (lc_pcpo + LOWCORE_ALT_ADDRESS), \ + : [val__] "d" (val__), [ptr__] "a" (ptr__), \ + [lcreg] "i" (LC_PERCPU_REGISTER), \ + [lcoff] "i" (LC_PERCPU_OFFSET), \ "m" (((struct lowcore *)0)->percpu_offset) \ : "cc"); \ } while (0) @@ -309,7 +337,7 @@ do { \ #define this_cpu_write_4(pcp, val) arch_this_cpu_write(pcp, val, "st") #define this_cpu_write_8(pcp, val) arch_this_cpu_write(pcp, val, "stg") -#define arch_this_cpu_cmpxchg(pcp, oval, nval) \ +#define arch_this_cpu_cmpxchg_simple(pcp, oval, nval) \ ({ \ typedef typeof(pcp) pcp_op_T__; \ pcp_op_T__ ret__; \ @@ -321,28 +349,62 @@ do { \ ret__; \ }) -#define this_cpu_cmpxchg_1(pcp, oval, nval) arch_this_cpu_cmpxchg(pcp, oval, nval) -#define this_cpu_cmpxchg_2(pcp, oval, nval) arch_this_cpu_cmpxchg(pcp, oval, nval) -#define this_cpu_cmpxchg_4(pcp, oval, nval) arch_this_cpu_cmpxchg(pcp, oval, nval) -#define this_cpu_cmpxchg_8(pcp, oval, nval) arch_this_cpu_cmpxchg(pcp, oval, nval) +#define arch_this_cpu_cmpxchg(pcp, oval, nval, op) \ +({ \ + typedef typeof(pcp) pcp_op_T__; \ + pcp_op_T__ old__ = (oval), new__ = (nval); \ + union register_pair rp__; \ + pcp_op_T__ *ptr__; \ + \ + ptr__ = PERCPU_PTR(&(pcp)); \ + asm_inline volatile( \ + __PCPU_BEGIN("%[lcreg]","%[lcoff]","%[ptr__]", \ + "%[pair__]","%N[pair__]") \ + op " %[old__],%[new__],0(%N[pair__])\n" \ + __PCPU_END("%[lcreg]") \ + : [old__] "+&d" (old__), [pair__] "=&a" (rp__.pair), \ + "+m" (*ptr__), \ + "=m" (((struct lowcore *)0)->percpu_register) \ + : [new__] "d" (new__), [ptr__] "a" (ptr__), \ + [lcreg] "i" (LC_PERCPU_REGISTER), \ + [lcoff] "i" (LC_PERCPU_OFFSET), \ + "m" (((struct lowcore *)0)->percpu_offset) \ + : "memory", "cc"); \ + old__; \ +}) + +#define this_cpu_cmpxchg_1(pcp, oval, nval) arch_this_cpu_cmpxchg_simple(pcp, oval, nval) +#define this_cpu_cmpxchg_2(pcp, oval, nval) arch_this_cpu_cmpxchg_simple(pcp, oval, nval) +#define this_cpu_cmpxchg_4(pcp, oval, nval) arch_this_cpu_cmpxchg(pcp, oval, nval, "cs") +#define this_cpu_cmpxchg_8(pcp, oval, nval) arch_this_cpu_cmpxchg(pcp, oval, nval, "csg") #define this_cpu_cmpxchg64(pcp, o, n) this_cpu_cmpxchg_8(pcp, o, n) #define this_cpu_cmpxchg128(pcp, oval, nval) \ ({ \ typedef typeof(pcp) pcp_op_T__; \ - u128 old__, new__, ret__; \ + u128 old__ = (oval), new__ = (nval); \ + union register_pair rp__; \ pcp_op_T__ *ptr__; \ - old__ = oval; \ - new__ = nval; \ - preempt_disable_notrace(); \ - ptr__ = raw_cpu_ptr(&(pcp)); \ - ret__ = cmpxchg128((void *)ptr__, old__, new__); \ - preempt_enable_notrace(); \ - ret__; \ + \ + ptr__ = PERCPU_PTR(&(pcp)); \ + asm_inline volatile( \ + __PCPU_BEGIN("%[lcreg]","%[lcoff]","%[ptr__]", \ + "%[pair__]","%N[pair__]") \ + " cdsg %[old__],%[new__],0(%N[pair__])\n" \ + __PCPU_END("%[lcreg]") \ + : [old__] "+&d" (old__), [pair__] "=&a" (rp__.pair), \ + "+m" (*ptr__), \ + "=m" (((struct lowcore *)0)->percpu_register) \ + : [new__] "d" (new__), [ptr__] "a" (ptr__), \ + [lcreg] "i" (LC_PERCPU_REGISTER), \ + [lcoff] "i" (LC_PERCPU_OFFSET), \ + "m" (((struct lowcore *)0)->percpu_offset) \ + : "memory", "cc"); \ + old__; \ }) -#define arch_this_cpu_xchg(pcp, nval) \ +#define arch_this_cpu_xchg_simple(pcp, nval) \ ({ \ typeof(pcp) *ptr__; \ typeof(pcp) ret__; \ @@ -353,10 +415,36 @@ do { \ ret__; \ }) -#define this_cpu_xchg_1(pcp, nval) arch_this_cpu_xchg(pcp, nval) -#define this_cpu_xchg_2(pcp, nval) arch_this_cpu_xchg(pcp, nval) -#define this_cpu_xchg_4(pcp, nval) arch_this_cpu_xchg(pcp, nval) -#define this_cpu_xchg_8(pcp, nval) arch_this_cpu_xchg(pcp, nval) +#define arch_this_cpu_xchg(pcp, nval, ldop, csop) \ +({ \ + typedef typeof(pcp) pcp_op_T__; \ + pcp_op_T__ old__, new__ = (nval); \ + union register_pair rp__; \ + pcp_op_T__ *ptr__; \ + \ + ptr__ = PERCPU_PTR(&(pcp)); \ + asm_inline volatile( \ + __PCPU_BEGIN("%[lcreg]","%[lcoff]","%[ptr__]", \ + "%[pair__]","%N[pair__]") \ + " " ldop " %[old__],0(%N[pair__])\n" \ + "0: " csop " %[old__],%[new__],0(%N[pair__])\n"\ + " jnz 0b\n" \ + __PCPU_END("%[lcreg]") \ + : [old__] "=&d" (old__), [pair__] "=&a" (rp__.pair), \ + "+m" (*ptr__), \ + "=m" (((struct lowcore *)0)->percpu_register) \ + : [new__] "d" (new__), [ptr__] "a" (ptr__), \ + [lcreg] "i" (LC_PERCPU_REGISTER), \ + [lcoff] "i" (LC_PERCPU_OFFSET), \ + "m" (((struct lowcore *)0)->percpu_offset) \ + : "memory", "cc"); \ + old__; \ +}) + +#define this_cpu_xchg_1(pcp, nval) arch_this_cpu_xchg_simple(pcp, nval) +#define this_cpu_xchg_2(pcp, nval) arch_this_cpu_xchg_simple(pcp, nval) +#define this_cpu_xchg_4(pcp, nval) arch_this_cpu_xchg(pcp, nval, "l", "cs") +#define this_cpu_xchg_8(pcp, nval) arch_this_cpu_xchg(pcp, nval, "lg", "csg") #include diff --git a/arch/s390/kernel/early.c b/arch/s390/kernel/early.c index b27239c03d79..1fc153d8385b 100644 --- a/arch/s390/kernel/early.c +++ b/arch/s390/kernel/early.c @@ -153,16 +153,25 @@ static __init void setup_topology(void) void __init __do_early_pgm_check(struct pt_regs *regs) { struct lowcore *lc = get_lowcore(); - unsigned long ip; regs->int_code = lc->pgm_int_code; regs->int_parm_long = lc->trans_exc_code; regs->last_break = lc->pgm_last_break; - ip = __rewind_psw(regs->psw, regs->int_code >> 16); + regs->monitor_code = lc->monitor_code; /* Monitor Event? Might be a warning */ if ((regs->int_code & PGM_INT_CODE_MASK) == 0x40) { - if (report_bug(ip, regs) == BUG_TRAP_TYPE_WARN) + enum bug_trap_type btt; + unsigned long ip; + + if (regs->monitor_code == MONCODE_BUG_ARG) { + regs->psw.addr = regs->gprs[14]; + btt = report_bug_entry((struct bug_entry *)regs->gprs[2], regs); + } else { + ip = __rewind_psw(regs->psw, regs->int_code >> 16); + btt = report_bug(ip, regs); + } + if (btt == BUG_TRAP_TYPE_WARN) return; } if (fixup_exception(regs)) diff --git a/arch/s390/kernel/irq.c b/arch/s390/kernel/irq.c index c923496aa7b4..8f21bea349a6 100644 --- a/arch/s390/kernel/irq.c +++ b/arch/s390/kernel/irq.c @@ -144,9 +144,9 @@ static int irq_pending(struct pt_regs *regs) void noinstr do_io_irq(struct pt_regs *regs) { - bool from_idle, percpu_needs_fixup; struct pt_regs *old_regs; irqentry_state_t state; + bool from_idle; percpu_entry(regs); state = irqentry_enter(regs); @@ -174,21 +174,20 @@ void noinstr do_io_irq(struct pt_regs *regs) do_irq_async(regs, IO_INTERRUPT); } while (machine_is_lpar() && irq_pending(regs)); - percpu_needs_fixup = percpu_code_check(regs); irq_exit_rcu(); set_irq_regs(old_regs); irqentry_exit(regs, state); if (from_idle) regs->psw.mask &= ~(PSW_MASK_EXT | PSW_MASK_IO | PSW_MASK_WAIT); - percpu_exit(regs, percpu_needs_fixup); + percpu_exit(regs); } void noinstr do_ext_irq(struct pt_regs *regs) { - bool from_idle, percpu_needs_fixup; struct pt_regs *old_regs; irqentry_state_t state; + bool from_idle; percpu_entry(regs); state = irqentry_enter(regs); @@ -214,14 +213,13 @@ void noinstr do_ext_irq(struct pt_regs *regs) do_irq_async(regs, EXT_INTERRUPT); - percpu_needs_fixup = percpu_code_check(regs); irq_exit_rcu(); set_irq_regs(old_regs); irqentry_exit(regs, state); if (from_idle) regs->psw.mask &= ~(PSW_MASK_EXT | PSW_MASK_IO | PSW_MASK_WAIT); - percpu_exit(regs, percpu_needs_fixup); + percpu_exit(regs); } static void show_msi_interrupt(struct seq_file *p, int irq) diff --git a/arch/s390/kernel/nmi.c b/arch/s390/kernel/nmi.c index 17297a8b63d9..56a15edc65d7 100644 --- a/arch/s390/kernel/nmi.c +++ b/arch/s390/kernel/nmi.c @@ -361,7 +361,6 @@ NOKPROBE_SYMBOL(s390_backup_mcck_info); */ void notrace s390_do_machine_check(struct pt_regs *regs) { - bool percpu_needs_fixup; static int ipd_count; static DEFINE_SPINLOCK(ipd_lock); static unsigned long long last_ipd; @@ -495,9 +494,8 @@ void notrace s390_do_machine_check(struct pt_regs *regs) if (mcck_pending) schedule_mcck_handler(); - percpu_needs_fixup = percpu_code_check(regs); irqentry_nmi_exit(regs, irq_state); - percpu_exit(regs, percpu_needs_fixup); + percpu_exit(regs); } NOKPROBE_SYMBOL(s390_do_machine_check); diff --git a/arch/s390/kernel/ptrace.c b/arch/s390/kernel/ptrace.c index 125ca4c4e30c..d8d5e843859c 100644 --- a/arch/s390/kernel/ptrace.c +++ b/arch/s390/kernel/ptrace.c @@ -34,6 +34,7 @@ #include #include #include +#include #include "entry.h" @@ -345,11 +346,9 @@ static int __poke_user(struct task_struct *child, addr_t addr, addr_t data) return -EINVAL; } - if (test_pt_regs_flag(regs, PIF_SYSCALL) && - addr == offsetof(struct user, regs.gprs[2])) { - struct pt_regs *regs = task_pt_regs(child); - - regs->int_code = 0x20000 | (data & 0xffff); + if (addr == offsetof(struct user, regs.gprs[2])) { + if (test_pt_regs_flag(regs, PIF_SYSCALL)) + syscall_set_nr(child, regs, data); } *(addr_t *)((addr_t) ®s->psw + addr) = data; } else if (addr < offsetof(struct user, regs.orig_gpr2)) { diff --git a/arch/s390/kernel/traps.c b/arch/s390/kernel/traps.c index b6ba4465f59d..dd051046170b 100644 --- a/arch/s390/kernel/traps.c +++ b/arch/s390/kernel/traps.c @@ -338,7 +338,6 @@ static void (*pgm_check_table[128])(struct pt_regs *regs); void noinstr __do_pgm_check(struct pt_regs *regs, unsigned long flags) { struct lowcore *lc = get_lowcore(); - bool percpu_needs_fixup; irqentry_state_t state; struct pgm_stat *stat; unsigned int trapnr; @@ -400,9 +399,8 @@ void noinstr __do_pgm_check(struct pt_regs *regs, unsigned long flags) pgm_check_table[trapnr](regs); out: local_irq_disable(); - percpu_needs_fixup = percpu_code_check(regs); irqentry_exit(regs, state); - percpu_exit(regs, percpu_needs_fixup); + percpu_exit(regs); } static int pgm_check_stat_show(struct seq_file *p, void *v) diff --git a/arch/s390/kernel/uprobes.c b/arch/s390/kernel/uprobes.c index c624f3361e43..b2b8a377ced6 100644 --- a/arch/s390/kernel/uprobes.c +++ b/arch/s390/kernel/uprobes.c @@ -241,7 +241,7 @@ static void sim_stor_event(struct pt_regs *regs, void *addr, int len) return; if (!(current->thread.per_user.control & PER_EVENT_STORE)) return; - if ((void *)current->thread.per_user.start > (addr + len)) + if ((void *)current->thread.per_user.start > (addr + len - 1)) return; if ((void *)current->thread.per_user.end < addr) return; diff --git a/arch/sh/Kconfig b/arch/sh/Kconfig index d60f1d5a94c0..b501153551c0 100644 --- a/arch/sh/Kconfig +++ b/arch/sh/Kconfig @@ -15,6 +15,7 @@ config SUPERH select ARCH_MIGHT_HAVE_PC_PARPORT select ARCH_WANT_IPC_PARSE_VERSION select ARCH_NEED_CMPXCHG_1_EMU + select BINFMT_FLAT_NO_DATA_START_OFFSET if !MMU select CPU_NO_EFFICIENT_FFS select DMA_DECLARE_COHERENT select GENERIC_ATOMIC64 diff --git a/arch/sh/boards/board-sh7785lcr.c b/arch/sh/boards/board-sh7785lcr.c index 25c4968f0d8b..b93423df582f 100644 --- a/arch/sh/boards/board-sh7785lcr.c +++ b/arch/sh/boards/board-sh7785lcr.c @@ -256,7 +256,7 @@ static struct i2c_pca9564_pf_platform_data i2c_platform_data = { static struct platform_device i2c_device = { .name = "i2c-pca-platform", - .id = -1, + .id = 0, .dev = { .platform_data = &i2c_platform_data, }, diff --git a/arch/sh/boot/dts/Makefile b/arch/sh/boot/dts/Makefile index d109978a5eb9..16e281b859ae 100644 --- a/arch/sh/boot/dts/Makefile +++ b/arch/sh/boot/dts/Makefile @@ -1,2 +1,2 @@ # SPDX-License-Identifier: GPL-2.0-only -obj-$(CONFIG_BUILTIN_DTB) += $(addsuffix .dtb.o, $(CONFIG_BUILTIN_DTB_NAME)) +dtb-y += $(addsuffix .dtb, $(CONFIG_BUILTIN_DTB_NAME)) diff --git a/arch/sh/configs/migor_defconfig b/arch/sh/configs/migor_defconfig index 1d9d543eef4c..bde70f3bf857 100644 --- a/arch/sh/configs/migor_defconfig +++ b/arch/sh/configs/migor_defconfig @@ -72,7 +72,7 @@ CONFIG_LOGO=y # CONFIG_LOGO_LINUX_VGA16 is not set # CONFIG_LOGO_LINUX_CLUT224 is not set CONFIG_USB_GADGET=y -CONFIG_USB_GADGET_M66592=y +CONFIG_USB_M66592=y CONFIG_USB_G_SERIAL=m CONFIG_RTC_CLASS=y CONFIG_RTC_DRV_RS5C372=y diff --git a/arch/sh/configs/sdk7786_defconfig b/arch/sh/configs/sdk7786_defconfig index d6fa3a422e24..d40be415dcb9 100644 --- a/arch/sh/configs/sdk7786_defconfig +++ b/arch/sh/configs/sdk7786_defconfig @@ -147,7 +147,7 @@ CONFIG_USB_MON=y CONFIG_USB_OHCI_HCD=y CONFIG_USB_STORAGE=y CONFIG_USB_GADGET=y -CONFIG_USB_GADGET_M66592=y +CONFIG_USB_M66592=y CONFIG_RTC_CLASS=y CONFIG_RTC_DRV_MAX6900=y CONFIG_RTC_DRV_SH=y diff --git a/arch/sh/configs/shx3_defconfig b/arch/sh/configs/shx3_defconfig index 0cb69a0b92cb..d7496ea9a9fc 100644 --- a/arch/sh/configs/shx3_defconfig +++ b/arch/sh/configs/shx3_defconfig @@ -79,7 +79,7 @@ CONFIG_USB=y CONFIG_USB_MON=y CONFIG_USB_R8A66597_HCD=m CONFIG_USB_GADGET=y -CONFIG_USB_GADGET_M66592=y +CONFIG_USB_M66592=y CONFIG_RTC_CLASS=y CONFIG_RTC_DRV_SH=y CONFIG_UIO=m diff --git a/arch/sh/include/asm/uaccess_32.h b/arch/sh/include/asm/uaccess_32.h index 5d7ddc092afd..cef40414bfb1 100644 --- a/arch/sh/include/asm/uaccess_32.h +++ b/arch/sh/include/asm/uaccess_32.h @@ -92,7 +92,7 @@ __asm__ __volatile__( \ ".long 1b + 2, 3b\n\t" \ ".previous" \ :"=&r" (err), "=&r" (x) \ - :"m" (__m(addr)), "i" (-EFAULT), "0" (err)); }) + :"o" (__m(addr)), "i" (-EFAULT), "0" (err)); }) #else #define __get_user_u64(x, addr, err) \ ({ \ @@ -116,7 +116,7 @@ __asm__ __volatile__( \ ".long 1b + 2, 3b\n\t" \ ".previous" \ :"=&r" (err), "=&r" (x) \ - :"m" (__m(addr)), "i" (-EFAULT), "0" (err)); }) + :"o" (__m(addr)), "i" (-EFAULT), "0" (err)); }) #endif #define __put_user_size(x,ptr,size,retval) \ @@ -196,7 +196,7 @@ __asm__ __volatile__( \ ".long 1b, 3b\n\t" \ ".previous" \ : "=r" (retval) \ - : "r" (val), "m" (__m(addr)), "i" (-EFAULT), "0" (retval) \ + : "r" (val), "o" (__m(addr)), "i" (-EFAULT), "0" (retval) \ : "memory"); }) #else #define __put_user_u64(val,addr,retval) \ @@ -218,7 +218,7 @@ __asm__ __volatile__( \ ".long 1b, 3b\n\t" \ ".previous" \ : "=r" (retval) \ - : "r" (val), "m" (__m(addr)), "i" (-EFAULT), "0" (retval) \ + : "r" (val), "o" (__m(addr)), "i" (-EFAULT), "0" (retval) \ : "memory"); }) #endif diff --git a/arch/um/include/shared/skas/stub-data.h b/arch/um/include/shared/skas/stub-data.h index 27db38e95df9..1230a325debc 100644 --- a/arch/um/include/shared/skas/stub-data.h +++ b/arch/um/include/shared/skas/stub-data.h @@ -9,11 +9,20 @@ #define __STUB_DATA_H #include +#include #include #include #include #include +#ifndef __NR_close_range +# if defined(__alpha__) +# define __NR_close_range 546 +# else +# define __NR_close_range 436 +# endif +#endif + #define FUTEX_IN_CHILD 0 #define FUTEX_IN_KERN 1 diff --git a/arch/um/kernel/skas/syscall.c b/arch/um/kernel/skas/syscall.c index bc117733e8ef..914b90af42ed 100644 --- a/arch/um/kernel/skas/syscall.c +++ b/arch/um/kernel/skas/syscall.c @@ -35,12 +35,13 @@ void handle_syscall(struct uml_pt_regs *r) /* * If no time passes, then sched_yield may not actually yield, causing * broken spinlock implementations in userspace (ASAN) to hang for long - * periods of time. + * periods of time. Advance the time-travel clock a bit so sched_yield() + * in a loop (like ping does for small intervals) also works correctly. */ if ((time_travel_mode == TT_MODE_INFCPU || time_travel_mode == TT_MODE_EXTERNAL) && syscall == __NR_sched_yield) - tt_extra_sched_jiffies += 1; + time_travel_ndelay(1000); if (syscall >= 0 && syscall < __NR_syscalls) { unsigned long ret; diff --git a/arch/x86/boot/string.c b/arch/x86/boot/string.c index 1632d40e1f54..be454a686422 100644 --- a/arch/x86/boot/string.c +++ b/arch/x86/boot/string.c @@ -15,6 +15,7 @@ #include #include #include +#include #include "ctype.h" #include "string.h" @@ -31,17 +32,7 @@ int memcmp(const void *s1, const void *s2, size_t len) { - bool diff; - - /* - * Make sure ZF is properly set in the len==0 case because in it, - * RCX==0 and the REPE; CMPSB won't get executed. - */ - asm volatile("test %3, %3\n\t" - "repe cmpsb" - : "=@ccnz" (diff), "+D" (s1), "+S" (s2), "+c" (len) - : : "cc", "memory"); - return diff; + return __inline_memcmp(s1, s2, len); } /* diff --git a/arch/x86/include/asm/cpuid/api.h b/arch/x86/include/asm/cpuid/api.h index 25b22b173f2a..759b12d94bbf 100644 --- a/arch/x86/include/asm/cpuid/api.h +++ b/arch/x86/include/asm/cpuid/api.h @@ -205,7 +205,7 @@ static inline u32 cpuid_base_hypervisor(const char *sig, u32 leaves) * from PVH early boot code before instrumentation is set up * and memcmp() itself may be instrumented. */ - if (!__builtin_memcmp(sig, signature, 12) && + if (!__inline_memcmp(sig, signature, 12) && (leaves == 0 || ((eax - base) >= leaves))) return base; } diff --git a/arch/x86/include/asm/shared/string.h b/arch/x86/include/asm/shared/string.h new file mode 100644 index 000000000000..6bef90d62a21 --- /dev/null +++ b/arch/x86/include/asm/shared/string.h @@ -0,0 +1,52 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _ASM_X86_SHARED_STRING_H +#define _ASM_X86_SHARED_STRING_H + +static __always_inline void *__inline_memcpy(void *to, const void *from, size_t len) +{ + void *ret = to; + + asm volatile("rep movsb" + : "+D" (to), "+S" (from), "+c" (len) + : : "memory"); + return ret; +} + +static __always_inline void *__inline_memset(void *s, int v, size_t n) +{ + void *ret = s; + + asm volatile("rep stosb" + : "+D" (s), "+c" (n) + : "a" ((uint8_t)v) + : "memory"); + return ret; +} + +/* + * Returns: 0 (equal) + * 1 (not equal) + * + * In contrast, the regular memcmp() follows glibc return value semantics. + */ +static __always_inline int __inline_memcmp(const void *s1, const void *s2, size_t len) +{ + bool diff; + + /* + * Make sure ZF is properly set in the len==0 case because in it, + * RCX==0 and the REPE; CMPSB won't get executed. + * + * The "cc" clobber has no meaning anymore, just source compatibility. + * On x86 the flag status bits are automatically added to the clobber + * set when there are no =@ccXY constraints. Keep it as documentation. + */ + asm volatile("test %3, %3\n\t" + "repe cmpsb" + : "=@ccnz" (diff), "+D" (s1), "+S" (s2), "+c" (len) + : : /* "cc", */ "memory"); + + return diff; +} + +#endif /* _ASM_X86_SHARED_STRING_H */ diff --git a/arch/x86/include/asm/string.h b/arch/x86/include/asm/string.h index 9cb5aae7fba9..dbf59f0d4cca 100644 --- a/arch/x86/include/asm/string.h +++ b/arch/x86/include/asm/string.h @@ -8,25 +8,6 @@ # include #endif -static __always_inline void *__inline_memcpy(void *to, const void *from, size_t len) -{ - void *ret = to; - - asm volatile("rep movsb" - : "+D" (to), "+S" (from), "+c" (len) - : : "memory"); - return ret; -} - -static __always_inline void *__inline_memset(void *s, int v, size_t n) -{ - void *ret = s; - - asm volatile("rep stosb" - : "+D" (s), "+c" (n) - : "a" ((uint8_t)v) - : "memory"); - return ret; -} +#include #endif /* _ASM_X86_STRING_H */ diff --git a/arch/x86/include/asm/svm.h b/arch/x86/include/asm/svm.h index aa63431ba92c..e883241b5e1e 100644 --- a/arch/x86/include/asm/svm.h +++ b/arch/x86/include/asm/svm.h @@ -637,8 +637,8 @@ static inline void __unused_size_checks(void) #define SVM_EVTINJ_TYPE_EXEPT (3 << SVM_EVTINJ_TYPE_SHIFT) #define SVM_EVTINJ_TYPE_SOFT (4 << SVM_EVTINJ_TYPE_SHIFT) -#define SVM_EVTINJ_VALID (1 << 31) -#define SVM_EVTINJ_VALID_ERR (1 << 11) +#define SVM_EVTINJ_VALID BIT(31) +#define SVM_EVTINJ_VALID_ERR BIT(11) #define SVM_EVTINJ_RESERVED_BITS ~(SVM_EVTINJ_VEC_MASK | SVM_EVTINJ_TYPE_MASK | \ SVM_EVTINJ_VALID_ERR | SVM_EVTINJ_VALID) diff --git a/arch/x86/kernel/cpu/common.c b/arch/x86/kernel/cpu/common.c index a9b3308f48a8..a81c1a367f5e 100644 --- a/arch/x86/kernel/cpu/common.c +++ b/arch/x86/kernel/cpu/common.c @@ -1783,6 +1783,32 @@ static void __init cpu_parse_early_param(void) } } +static void init_cpu_info(struct cpuinfo_x86 *c) +{ + c->x86_cache_size = 0; + c->x86_vendor = X86_VENDOR_UNKNOWN; + c->x86_model = c->x86_stepping = 0; /* So far unknown... */ + c->x86_vendor_id[0] = '\0'; /* Unset */ + c->x86_model_id[0] = '\0'; /* Unset */ +#ifdef CONFIG_X86_64 + c->x86_clflush_size = 64; + c->x86_phys_bits = 36; + c->x86_virt_bits = 48; +#else + c->cpuid_level = -1; /* CPUID not detected */ + c->x86_clflush_size = 32; + c->x86_phys_bits = 32; + c->x86_virt_bits = 32; +#endif + c->x86_cache_alignment = c->x86_clflush_size; + memset(&c->x86_capability, 0, sizeof(c->x86_capability)); + memset(&c->cpuid, 0, sizeof(c->cpuid)); +#ifdef CONFIG_X86_VMX_FEATURE_NAMES + memset(&c->vmx_capability, 0, sizeof(c->vmx_capability)); +#endif + c->extended_cpuid_level = 0; +} + /* * Do minimum CPU detection early. * Fields really needed: vendor, cpuid_level, family, model, mask, @@ -1801,7 +1827,7 @@ static void __init early_identify_cpu(struct cpuinfo_x86 *c) if (!cpuid_feature()) identify_cpu_without_cpuid(c); - /* cyrix could have cpuid enabled via c_identify()*/ + /* Cyrix could have CPUID enabled via c_identify(). */ if (cpuid_feature()) { cpuid_scan_cpu(c); cpu_detect(c); @@ -1965,16 +1991,21 @@ void check_null_seg_clears_base(struct cpuinfo_x86 *c) set_cpu_bug(c, X86_BUG_NULL_SEG); } -static void generic_identify(struct cpuinfo_x86 *c) +/* + * This does the hard work of actually picking apart the CPU stuff... + */ +static void identify_cpu(struct cpuinfo_x86 *c) { - c->extended_cpuid_level = 0; + int i; + + c->loops_per_jiffy = loops_per_jiffy; if (!cpuid_feature()) identify_cpu_without_cpuid(c); - /* cyrix could have cpuid enabled via c_identify()*/ + /* Cyrix could have CPUID enabled via c_identify(). */ if (!cpuid_feature()) - return; + goto no_cpuid; cpuid_scan_cpu(c); cpu_detect(c); @@ -2002,40 +2033,8 @@ static void generic_identify(struct cpuinfo_x86 *c) #ifdef CONFIG_X86_32 set_cpu_bug(c, X86_BUG_ESPFIX); #endif -} - -/* - * This does the hard work of actually picking apart the CPU stuff... - */ -static void identify_cpu(struct cpuinfo_x86 *c) -{ - int i; - - c->loops_per_jiffy = loops_per_jiffy; - c->x86_cache_size = 0; - c->x86_vendor = X86_VENDOR_UNKNOWN; - c->x86_model = c->x86_stepping = 0; /* So far unknown... */ - c->x86_vendor_id[0] = '\0'; /* Unset */ - c->x86_model_id[0] = '\0'; /* Unset */ -#ifdef CONFIG_X86_64 - c->x86_clflush_size = 64; - c->x86_phys_bits = 36; - c->x86_virt_bits = 48; -#else - c->cpuid_level = -1; /* CPUID not detected */ - c->x86_clflush_size = 32; - c->x86_phys_bits = 32; - c->x86_virt_bits = 32; -#endif - c->x86_cache_alignment = c->x86_clflush_size; - memset(&c->x86_capability, 0, sizeof(c->x86_capability)); - memset(&c->cpuid, 0, sizeof(c->cpuid)); -#ifdef CONFIG_X86_VMX_FEATURE_NAMES - memset(&c->vmx_capability, 0, sizeof(c->vmx_capability)); -#endif - - generic_identify(c); +no_cpuid: cpu_parse_topology(c); if (this_cpu->c_identify) @@ -2185,6 +2184,7 @@ void identify_secondary_cpu(unsigned int cpu) *c = boot_cpu_data; c->cpu_index = cpu; + init_cpu_info(c); identify_cpu(c); #ifdef CONFIG_X86_32 enable_sep_cpu(); diff --git a/arch/x86/kernel/cpu/mshyperv.c b/arch/x86/kernel/cpu/mshyperv.c index b4af7c0a70ac..fec1c37dafbf 100644 --- a/arch/x86/kernel/cpu/mshyperv.c +++ b/arch/x86/kernel/cpu/mshyperv.c @@ -148,7 +148,6 @@ EXPORT_SYMBOL_GPL(hv_set_msr); static void (*mshv_handler)(void); static void (*vmbus_handler)(void); static void (*hv_stimer0_handler)(void); -static void (*hv_kexec_handler)(void); static void (*hv_crash_handler)(struct pt_regs *regs); DEFINE_IDTENTRY_SYSVEC(sysvec_hyperv_callback) @@ -215,16 +214,6 @@ void hv_remove_stimer0_handler(void) hv_stimer0_handler = NULL; } -void hv_setup_kexec_handler(void (*handler)(void)) -{ - hv_kexec_handler = handler; -} - -void hv_remove_kexec_handler(void) -{ - hv_kexec_handler = NULL; -} - void hv_setup_crash_handler(void (*handler)(struct pt_regs *regs)) { hv_crash_handler = handler; @@ -240,17 +229,13 @@ static void hv_machine_shutdown(void) { if (kexec_in_progress) { hv_stimer_global_cleanup(); - - if (hv_kexec_handler) - hv_kexec_handler(); - } - - /* - * Call hv_cpu_die() on all the CPUs, otherwise later the hypervisor - * corrupts the old VP Assist Pages and can crash the kexec kernel. - */ - if (kexec_in_progress) + /* + * Call hv_cpu_die() on all the CPUs, otherwise later the + * hypervisor corrupts the old VP Assist Pages and can crash + * the kexec kernel. + */ cpuhp_remove_state(CPUHP_AP_HYPERV_ONLINE); + } /* The function calls stop_other_cpus(). */ native_machine_shutdown(); diff --git a/arch/x86/kernel/crash.c b/arch/x86/kernel/crash.c index e681ec9cf1dc..e6f23933a6df 100644 --- a/arch/x86/kernel/crash.c +++ b/arch/x86/kernel/crash.c @@ -369,9 +369,9 @@ int crash_load_segments(struct kimage *image) * maximum CPUs and maximum memory ranges. */ if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG)) - pnum = 2 + CONFIG_NR_CPUS_DEFAULT + CONFIG_CRASH_MAX_MEMORY_RANGES; + pnum = 2 + CONFIG_NR_CPUS + CONFIG_CRASH_MAX_MEMORY_RANGES; else - pnum += 2 + CONFIG_NR_CPUS_DEFAULT; + pnum += 2 + CONFIG_NR_CPUS; if (pnum < (unsigned long)PN_XNUM) { kbuf.memsz = pnum * sizeof(Elf64_Phdr); @@ -430,7 +430,7 @@ unsigned int arch_crash_get_elfcorehdr_size(void) unsigned int sz; /* kernel_map, VMCOREINFO and maximum CPUs */ - sz = 2 + CONFIG_NR_CPUS_DEFAULT; + sz = 2 + CONFIG_NR_CPUS; if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG)) sz += CONFIG_CRASH_MAX_MEMORY_RANGES; sz *= sizeof(Elf64_Phdr); diff --git a/arch/x86/kernel/fpu/xstate.c b/arch/x86/kernel/fpu/xstate.c index a7b6524a9dea..fe0a29f599d2 100644 --- a/arch/x86/kernel/fpu/xstate.c +++ b/arch/x86/kernel/fpu/xstate.c @@ -589,12 +589,13 @@ static bool __init check_xstate_against_struct(int nr) static unsigned int xstate_calculate_size(u64 xfeatures, bool compacted) { - unsigned int topmost = fls64(xfeatures) - 1; - unsigned int offset, i; + unsigned int topmost, offset, i; - if (topmost <= XFEATURE_SSE) + if (!(xfeatures & ~XFEATURE_MASK_FPSSE)) return sizeof(struct xregs_state); + topmost = fls64(xfeatures) - 1; + if (compacted) { offset = xfeature_get_offset(xfeatures, topmost); } else { diff --git a/arch/x86/kvm/svm/nested.c b/arch/x86/kvm/svm/nested.c index 2aa87ae6b8f3..b0406f3f86e1 100644 --- a/arch/x86/kvm/svm/nested.c +++ b/arch/x86/kvm/svm/nested.c @@ -821,7 +821,7 @@ static void nested_vmcb02_prepare_save(struct vcpu_svm *svm) * svm_set_msr's definition of reserved bits. */ svm_copy_lbrs(&vmcb02->save, save); - vmcb02->save.dbgctl &= ~DEBUGCTL_RESERVED_BITS; + vmcb02->save.dbgctl &= svm_get_supported_debugctl(vcpu); } else { svm_copy_lbrs(&vmcb02->save, &vmcb01->save); } @@ -1203,7 +1203,7 @@ int nested_svm_vmrun(struct kvm_vcpu *vcpu) } /* Copy state save area fields which are handled by VMRUN */ -void svm_copy_vmrun_state(struct vmcb_save_area *to_save, +void svm_copy_vmrun_state(struct kvm_vcpu *vcpu, struct vmcb_save_area *to_save, struct vmcb_save_area *from_save) { to_save->es = from_save->es; @@ -1230,7 +1230,7 @@ void svm_copy_vmrun_state(struct vmcb_save_area *to_save, if (kvm_cpu_cap_has(X86_FEATURE_LBRV)) { svm_copy_lbrs(to_save, from_save); - to_save->dbgctl &= ~DEBUGCTL_RESERVED_BITS; + to_save->dbgctl &= svm_get_supported_debugctl(vcpu); } } @@ -1878,6 +1878,21 @@ static void nested_copy_vmcb_cache_to_control(struct vmcb_control_area *dst, /* 'clean' and 'hv_enlightenments' are not changed by KVM */ } +bool nested_svm_check_vmcb01_save(struct kvm_vcpu *vcpu, + struct vmcb_save_area *save) +{ + struct vmcb_save_area_cached save_cached; + + if (!(save->cr0 & X86_CR0_PG) || + !(save->cr0 & X86_CR0_PE) || + (save->rflags & X86_EFLAGS_VM) || + ((save->efer & EFER_LMA) && !(save->efer & EFER_LME))) + return false; + + __nested_copy_vmcb_save_to_cache(&save_cached, save); + return nested_vmcb_check_save(vcpu, &save_cached, false); +} + static int svm_get_nested_state(struct kvm_vcpu *vcpu, struct kvm_nested_state __user *user_kvm_nested_state, u32 user_data_size) @@ -1957,7 +1972,6 @@ static int svm_set_nested_state(struct kvm_vcpu *vcpu, &user_kvm_nested_state->data.svm[0]; struct vmcb_control_area *ctl; struct vmcb_save_area *save; - struct vmcb_save_area_cached save_cached; struct vmcb_ctrl_area_cached ctl_cached; bool use_separate_l2_pat; unsigned long cr0; @@ -2029,12 +2043,7 @@ static int svm_set_nested_state(struct kvm_vcpu *vcpu, * KVM_GET_NESTED_STATE, and (b) it is not loaded at emulated * #VMEXIT. */ - __nested_copy_vmcb_save_to_cache(&save_cached, save); - if (!(save->cr0 & X86_CR0_PG) || - !(save->cr0 & X86_CR0_PE) || - (save->rflags & X86_EFLAGS_VM) || - ((save->efer & EFER_LMA) && !(save->efer & EFER_LME)) || - !nested_vmcb_check_save(vcpu, &save_cached, false)) + if (!nested_svm_check_vmcb01_save(vcpu, save)) goto out_free; /* @@ -2070,7 +2079,7 @@ static int svm_set_nested_state(struct kvm_vcpu *vcpu, svm->nested.vmcb12_gpa = kvm_state->hdr.svm.vmcb_pa; - svm_copy_vmrun_state(&svm->vmcb01.ptr->save, save); + svm_copy_vmrun_state(vcpu, &svm->vmcb01.ptr->save, save); nested_copy_vmcb_control_to_cache(svm, ctl); svm_switch_vmcb(svm, &svm->nested.vmcb02); diff --git a/arch/x86/kvm/svm/svm.c b/arch/x86/kvm/svm/svm.c index 13c44d619651..ef1796aff681 100644 --- a/arch/x86/kvm/svm/svm.c +++ b/arch/x86/kvm/svm/svm.c @@ -3169,7 +3169,7 @@ static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr) data &= ~DEBUGCTLMSR_BTF; } - if (data & DEBUGCTL_RESERVED_BITS) + if (data & ~svm_get_supported_debugctl(vcpu)) return 1; if (svm->vmcb->save.dbgctl == data) @@ -5064,7 +5064,7 @@ static int svm_enter_smm(struct kvm_vcpu *vcpu, union kvm_smram *smram) BUILD_BUG_ON(offsetof(struct vmcb, save) != 0x400); - svm_copy_vmrun_state(m_save.map.hva + 0x400, &svm->vmcb01.ptr->save); + svm_copy_vmrun_state(vcpu, m_save.map.hva + 0x400, &svm->vmcb01.ptr->save); return 0; } @@ -5104,7 +5104,9 @@ static int svm_leave_smm(struct kvm_vcpu *vcpu, const union kvm_smram *smram) * used during SMM (see svm_enter_smm()) */ - svm_copy_vmrun_state(&svm->vmcb01.ptr->save, m_save.map.hva + 0x400); + svm_copy_vmrun_state(vcpu, &svm->vmcb01.ptr->save, m_save.map.hva + 0x400); + if (!nested_svm_check_vmcb01_save(vcpu, &svm->vmcb01.ptr->save)) + return 1; /* * Enter the nested guest now diff --git a/arch/x86/kvm/svm/svm.h b/arch/x86/kvm/svm/svm.h index 29bde741874a..0d1cc83007c1 100644 --- a/arch/x86/kvm/svm/svm.h +++ b/arch/x86/kvm/svm/svm.h @@ -786,7 +786,10 @@ BUILD_SVM_MSR_BITMAP_HELPERS(bool, test, test) BUILD_SVM_MSR_BITMAP_HELPERS(void, clear, __clear) BUILD_SVM_MSR_BITMAP_HELPERS(void, set, __set) -#define DEBUGCTL_RESERVED_BITS (~DEBUGCTLMSR_LBR) +static inline u64 svm_get_supported_debugctl(struct kvm_vcpu *vcpu) +{ + return DEBUGCTLMSR_LBR; +} /* svm.c */ extern bool dump_invalid_vmcb; @@ -876,7 +879,7 @@ void svm_leave_nested(struct kvm_vcpu *vcpu); void svm_free_nested(struct vcpu_svm *svm); int svm_allocate_nested(struct vcpu_svm *svm); int nested_svm_vmrun(struct kvm_vcpu *vcpu); -void svm_copy_vmrun_state(struct vmcb_save_area *to_save, +void svm_copy_vmrun_state(struct kvm_vcpu *vcpu, struct vmcb_save_area *to_save, struct vmcb_save_area *from_save); void svm_copy_vmloadsave_state(struct vmcb *to_vmcb, struct vmcb *from_vmcb); void nested_svm_vmexit(struct vcpu_svm *svm); @@ -902,6 +905,8 @@ void nested_copy_vmcb_control_to_cache(struct vcpu_svm *svm, void nested_copy_vmcb_save_to_cache(struct vcpu_svm *svm, struct vmcb_save_area *save); void nested_sync_control_from_vmcb02(struct vcpu_svm *svm); +bool nested_svm_check_vmcb01_save(struct kvm_vcpu *vcpu, + struct vmcb_save_area *save); void svm_switch_vmcb(struct vcpu_svm *svm, struct kvm_vmcb_info *target_vmcb); diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c index 6bca87457e87..10f68ee7c9e6 100644 --- a/arch/x86/net/bpf_jit_comp.c +++ b/arch/x86/net/bpf_jit_comp.c @@ -2658,6 +2658,18 @@ st: insn_off = insn->off; return err; ip += err; } + 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; @@ -3401,9 +3413,9 @@ static int invoke_bpf_mod_ret(const struct btf_func_model *m, u8 **pprog, return 0; } -/* mov rax, qword ptr [rbp - rounded_stack_depth - 8] */ -#define LOAD_TRAMP_TAIL_CALL_CNT_PTR(stack) \ - __LOAD_TCC_PTR(-round_up(stack, 8) - 8) +/* mov rax, qword ptr [rbp - off] */ +#define LOAD_TRAMP_TAIL_CALL_CNT_PTR(off) \ + __LOAD_TCC_PTR(-(off)) /* Example: * __be16 eth_type_trans(struct sk_buff *skb, struct net_device *dev); @@ -3473,6 +3485,7 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im { int i, ret, nr_regs = m->nr_args, stack_size = 0; int regs_off, func_meta_off, ip_off, run_ctx_off, arg_stack_off, rbx_off; + int tcc_off = 0; struct bpf_tramp_nodes *fentry = &tnodes[BPF_TRAMP_FENTRY]; struct bpf_tramp_nodes *fexit = &tnodes[BPF_TRAMP_FEXIT]; struct bpf_tramp_nodes *fmod_ret = &tnodes[BPF_TRAMP_MODIFY_RETURN]; @@ -3523,11 +3536,12 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im * * RBP - run_ctx_off [ bpf_tramp_run_ctx ] * + * RBP - tcc_off [ tail_call_cnt_ptr ] BPF_TRAMP_F_TAIL_CALL_CTX + * * [ stack_argN ] BPF_TRAMP_F_CALL_ORIG * [ ... ] * [ stack_arg2 ] * RBP - arg_stack_off [ stack_arg1 ] - * RSP [ tail_call_cnt_ptr ] BPF_TRAMP_F_TAIL_CALL_CTX */ /* room for return value of orig_call or fentry prog */ @@ -3558,6 +3572,11 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im stack_size += (sizeof(struct bpf_tramp_run_ctx) + 7) & ~0x7; run_ctx_off = stack_size; + if (flags & BPF_TRAMP_F_TAIL_CALL_CTX) { + stack_size += 8; + tcc_off = stack_size; + } + if (nr_regs > 6 && (flags & BPF_TRAMP_F_CALL_ORIG)) { /* the space that used to pass arguments on-stack */ stack_size += (nr_regs - get_nr_used_regs(m)) * 8; @@ -3615,7 +3634,8 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im EMIT4(0x48, 0x83, 0xEC, stack_size); } if (flags & BPF_TRAMP_F_TAIL_CALL_CTX) - EMIT1(0x50); /* push rax */ + /* mov QWORD PTR [rbp - tcc_off], rax */ + emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_0, -tcc_off); /* mov QWORD PTR [rbp - rbx_off], rbx */ emit_stx(&prog, BPF_DW, BPF_REG_FP, BPF_REG_6, -rbx_off); @@ -3676,7 +3696,7 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im /* Before calling the original function, load the * tail_call_cnt_ptr from stack to rax. */ - LOAD_TRAMP_TAIL_CALL_CNT_PTR(stack_size); + LOAD_TRAMP_TAIL_CALL_CNT_PTR(tcc_off); } if (flags & BPF_TRAMP_F_ORIG_STACK) { @@ -3740,7 +3760,7 @@ static int __arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *rw_im /* Before running the original function, load the * tail_call_cnt_ptr from stack to rax. */ - LOAD_TRAMP_TAIL_CALL_CNT_PTR(stack_size); + LOAD_TRAMP_TAIL_CALL_CNT_PTR(tcc_off); } /* restore return value of orig_call or fentry prog back into RAX */ diff --git a/arch/x86/net/bpf_timed_may_goto.S b/arch/x86/net/bpf_timed_may_goto.S index 54c690cae190..dd2dde89836b 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 @@ -28,10 +22,12 @@ SYM_FUNC_START(arch_bpf_timed_may_goto) pushq %rdx pushq %rcx pushq %r8 + /* Save stack argument 6. */ + pushq %r9 /* - * 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 @@ -42,6 +38,7 @@ SYM_FUNC_START(arch_bpf_timed_may_goto) /* BPF_REG_AX=r10 will be stored into count, so move return value to it. */ movq %rax, %r10 + popq %r9 /* Restore r5-r0. */ popq %r8 popq %rcx diff --git a/arch/x86/platform/pvh/enlighten.c b/arch/x86/platform/pvh/enlighten.c index f2053cbe9b0c..88632c661430 100644 --- a/arch/x86/platform/pvh/enlighten.c +++ b/arch/x86/platform/pvh/enlighten.c @@ -8,6 +8,7 @@ #include #include #include +#include #include @@ -78,7 +79,9 @@ static void __init init_pvh_bootparams(bool xen_guest) struct hvm_modlist_entry *modaddr = __va(pvh_start_info.modlist_paddr); pvh_bootparams.hdr.ramdisk_image = modaddr->paddr; + pvh_bootparams.ext_ramdisk_image = modaddr->paddr >> 32; pvh_bootparams.hdr.ramdisk_size = modaddr->size; + pvh_bootparams.ext_ramdisk_size = modaddr->size >> 32; } /* @@ -129,7 +132,7 @@ void __init xen_prepare_pvh(void) * This must not compile to "call memset" because memset() may be * instrumented. */ - __builtin_memset(&pvh_bootparams, 0, sizeof(pvh_bootparams)); + __inline_memset(&pvh_bootparams, 0, sizeof(pvh_bootparams)); hypervisor_specific_init(xen_guest); diff --git a/arch/x86/power/hibernate.c b/arch/x86/power/hibernate.c index a2294c1649f6..dbb340fb24ad 100644 --- a/arch/x86/power/hibernate.c +++ b/arch/x86/power/hibernate.c @@ -63,6 +63,25 @@ struct restore_data_record { unsigned long e820_checksum; }; +static bool trim_e820_page_zero_ram(struct e820_entry *entry) +{ + u64 lowmem_size; + + /* + * Page zero is BIOS-owned and registered as nosave. Boot loaders may + * therefore omit part of its conventional RAM entry without changing + * any memory available to the image. Preserve all other E820 types. + */ + if (entry->type != E820_TYPE_RAM || entry->addr >= PAGE_SIZE) + return true; + + lowmem_size = min_t(u64, entry->size, PAGE_SIZE - entry->addr); + entry->addr += lowmem_size; + entry->size -= lowmem_size; + + return entry->size; +} + /** * compute_e820_crc32 - calculate crc32 of a given e820 table * @@ -70,18 +89,38 @@ struct restore_data_record { * * Return: the resulting checksum */ -static inline u32 compute_e820_crc32(struct e820_table *table) +static u32 compute_e820_crc32(struct e820_table *table) { - int size = offsetof(struct e820_table, entries) + - sizeof(struct e820_entry) * table->nr_entries; + struct e820_entry entry; + u32 crc = ~0; + u32 nr_entries = 0; + u32 i; + + for (i = 0; i < table->nr_entries; i++) { + entry = table->entries[i]; + if (trim_e820_page_zero_ram(&entry)) + nr_entries++; + } + + crc = crc32_le(crc, (unsigned char const *)&nr_entries, + sizeof(nr_entries)); + + for (i = 0; i < table->nr_entries; i++) { + entry = table->entries[i]; + if (!trim_e820_page_zero_ram(&entry)) + continue; + + crc = crc32_le(crc, (unsigned char const *)&entry, + sizeof(entry)); + } - return ~crc32_le(~0, (unsigned char const *)table, size); + return ~crc; } #ifdef CONFIG_X86_64 -#define RESTORE_MAGIC 0x23456789ABCDEF02UL +#define RESTORE_MAGIC 0x23456789ABCDEF03UL #else -#define RESTORE_MAGIC 0x12345679UL +#define RESTORE_MAGIC 0x1234567AUL #endif /** diff --git a/block/bdev.c b/block/bdev.c index cd8323083740..f20f91b3176e 100644 --- a/block/bdev.c +++ b/block/bdev.c @@ -292,7 +292,7 @@ EXPORT_SYMBOL(sync_blockdev_range); * The reference counter (bd_fsfreeze_count) guarantees that only the last * unfreeze process can unfreeze the frozen filesystem actually when multiple * freeze requests arrive simultaneously. It counts up in bdev_freeze() and - * count down in bdev_thaw(). When it becomes 0, thaw_bdev() will unfreeze + * count down in bdev_thaw(). When it becomes 0, bdev_thaw() will unfreeze * actually. * * Return: On success zero is returned, negative error code on failure. @@ -1283,7 +1283,7 @@ int lookup_bdev(const char *pathname, dev_t *dev) * registers major 0. Fake block device inodes (e.g. fuse with * rootmode=S_IFBLK) can expose i_rdev == 0, and letting that * propagate would confuse superblock lookup and trigger warnings - * in the device-to-superblock table (super_dev_register). + * in the device-to-superblock table (sget_fc). */ error = -ENODEV; if (!inode->i_rdev) @@ -1366,6 +1366,15 @@ void sync_bdevs(bool wait) old_inode = inode; bdev = I_BDEV(inode); + /* + * The inode does not keep the gendisk of a partition alive, the + * device does. + */ + if (!kobject_get_unless_zero(&bdev->bd_device.kobj)) { + spin_lock(&blockdev_superblock->s_inode_list_lock); + continue; + } + mutex_lock(&bdev->bd_disk->open_mutex); if (!atomic_read(&bdev->bd_openers)) { ; /* skip */ @@ -1381,6 +1390,7 @@ void sync_bdevs(bool wait) filemap_fdatawrite(inode->i_mapping); } mutex_unlock(&bdev->bd_disk->open_mutex); + put_device(&bdev->bd_device); spin_lock(&blockdev_superblock->s_inode_list_lock); } diff --git a/block/bfq-iosched.c b/block/bfq-iosched.c index 0f75301b3115..b21ddba30df1 100644 --- a/block/bfq-iosched.c +++ b/block/bfq-iosched.c @@ -7273,8 +7273,8 @@ static int bfq_init_queue(struct request_queue *q, struct elevator_queue *eq) bfqd->num_groups_with_pending_reqs = 0; #endif - INIT_LIST_HEAD(&bfqd->active_list[0]); - INIT_LIST_HEAD(&bfqd->active_list[1]); + for (i = 0; i < bfqd->num_actuators; i++) + INIT_LIST_HEAD(&bfqd->active_list[i]); INIT_LIST_HEAD(&bfqd->idle_list); INIT_HLIST_HEAD(&bfqd->burst_list); diff --git a/block/bio-integrity-fs.c b/block/bio-integrity-fs.c index 692403dfa047..dd6c85530913 100644 --- a/block/bio-integrity-fs.c +++ b/block/bio-integrity-fs.c @@ -52,14 +52,10 @@ void fs_bio_integrity_generate(struct bio *bio) } EXPORT_SYMBOL_GPL(fs_bio_integrity_generate); -int fs_bio_integrity_verify(struct bio *bio, sector_t sector, unsigned int size) +int fs_bio_integrity_verify(struct bio *bio, struct bvec_iter *data_iter) { struct blk_integrity *bi = blk_get_integrity(bio->bi_bdev->bd_disk); struct bio_integrity_payload *bip = bio_integrity(bio); - struct bvec_iter data_iter = { - .bi_sector = sector, - .bi_size = size, - }; if (!bip || !(bip->bip_flags & BIP_CHECK_FLAGS)) return 0; @@ -71,9 +67,10 @@ int fs_bio_integrity_verify(struct bio *bio, sector_t sector, unsigned int size) * bio. Requires the submitter to remember the sector and the size. */ memset(&bip->bip_iter, 0, sizeof(bip->bip_iter)); - bip->bip_iter.bi_sector = sector; - bip->bip_iter.bi_size = bio_integrity_bytes(bi, size >> SECTOR_SHIFT); - return blk_status_to_errno(bio_integrity_verify(bio, &data_iter)); + bip->bip_iter.bi_sector = data_iter->bi_sector; + bip->bip_iter.bi_size = + bio_integrity_bytes(bi, data_iter->bi_size >> SECTOR_SHIFT); + return blk_status_to_errno(bio_integrity_verify(bio, data_iter)); } static int __init fs_bio_integrity_init(void) diff --git a/block/bio.c b/block/bio.c index 90104e6abbcf..d4ed8a135e8f 100644 --- a/block/bio.c +++ b/block/bio.c @@ -1197,6 +1197,21 @@ bool bio_iov_iter_set(struct bio *bio, const struct iov_iter *iter) return true; } +static unsigned int bvec_nr_pages(const struct bio_vec *bv) +{ + return (bv->bv_offset + bv->bv_len - 1) / PAGE_SIZE - + bv->bv_offset / PAGE_SIZE + 1; +} + +static void bvec_unpin(struct bio_vec *bv, bool mark_dirty) +{ + struct folio *folio = bvec_folio(bv); + + if (mark_dirty) + folio_mark_dirty_lock(folio); + unpin_user_folio(folio, bvec_nr_pages(bv)); +} + /* * Aligns the bio size to the len_align_mask, releasing excessive bio vecs that * __bio_iov_iter_get_pages may have inserted, and reverts the trimmed length @@ -1206,6 +1221,7 @@ static int bio_iov_iter_align_down(struct bio *bio, struct iov_iter *iter, struct bio_vec *bv, unsigned len_align_mask) { size_t nbytes = bio->bi_iter.bi_size & len_align_mask; + unsigned int npages; if (!nbytes) return 0; @@ -1214,14 +1230,24 @@ static int bio_iov_iter_align_down(struct bio *bio, struct iov_iter *iter, bio->bi_iter.bi_size -= nbytes; while (nbytes >= bv->bv_len) { if (bio_flagged(bio, BIO_PAGE_PINNED)) - unpin_user_page(bv->bv_page); + bvec_unpin(bv, false); if (!--bio->bi_vcnt) return -EFAULT; nbytes -= bv->bv_len; bv--; } + + /* + * __bio_release_pages() only unpins the pages still covered by + * the trimmed bv_len. Count the pages spanned before and after + * the trim and unpin the difference. + */ + npages = bvec_nr_pages(bv); bv->bv_len -= nbytes; + npages -= bvec_nr_pages(bv); + if (npages && bio_flagged(bio, BIO_PAGE_PINNED)) + unpin_user_folio(bvec_folio(bv), npages); return 0; } @@ -1392,6 +1418,14 @@ static int bio_iov_iter_bounce_write(struct bio *bio, struct iov_iter *iter, folio = folio_alloc_greedy(GFP_KERNEL, &this_len, minsize); if (!folio) break; + + /* + * Align down the size to the minimum alignment. In practice + * this should not happen as minsize is expected to be a power + * of two, as is the allocation size, but it offers us a cheap + * extra safety belt. + */ + this_len &= ~(minsize - 1); bio_add_folio_nofail(bio, folio, this_len, 0); if (iter->nofault) @@ -1419,8 +1453,7 @@ static int bio_iov_iter_bounce_write(struct bio *bio, struct iov_iter *iter, if (!bio->bi_iter.bi_size) return -ENOMEM; - return bio_iov_iter_align_down(bio, iter, - &bio->bi_io_vec[bio->bi_vcnt - 1], minsize - 1); + return 0; } static int bio_iov_iter_bounce_read(struct bio *bio, struct iov_iter *iter, @@ -1492,17 +1525,6 @@ int bio_iov_iter_bounce(struct bio *bio, struct iov_iter *iter, size_t maxlen, return bio_iov_iter_bounce_read(bio, iter, maxlen, minsize); } -static void bvec_unpin(struct bio_vec *bv, bool mark_dirty) -{ - struct folio *folio = bvec_folio(bv); - size_t nr_pages = (bv->bv_offset + bv->bv_len - 1) / PAGE_SIZE - - bv->bv_offset / PAGE_SIZE + 1; - - if (mark_dirty) - folio_mark_dirty_lock(folio); - unpin_user_folio(folio, nr_pages); -} - static void bio_iov_iter_unbounce_read(struct bio *bio, bool is_error, bool mark_dirty) { diff --git a/block/blk-cgroup.c b/block/blk-cgroup.c index b56db1cc6778..1a363027b744 100644 --- a/block/blk-cgroup.c +++ b/block/blk-cgroup.c @@ -121,6 +121,11 @@ static void blkg_free_workfn(struct work_struct *work) struct request_queue *q = blkg->q; int i; +#ifdef CONFIG_BLK_CGROUP_PUNT_BIO + /* It may have been queued for bios which an earlier run has taken */ + cancel_work_sync(&blkg->async_bio_work); +#endif + /* * pd_free_fn() can also be called from blkcg_deactivate_policy(), * in order to make sure pd_free_fn() is called in order, the deletion @@ -218,7 +223,7 @@ static void blkg_async_bio_workfn(struct work_struct *work) struct blk_plug plug; bool need_plug = false; - /* as long as there are pending bios, @blkg can't go away */ + /* blkg_free_workfn() waits for us */ spin_lock(&blkg->async_bio_lock); bio_list_merge_init(&bios, &blkg->async_bios); spin_unlock(&blkg->async_bio_lock); @@ -245,10 +250,16 @@ void blkcg_punt_bio_submit(struct bio *bio) struct blkcg_gq *blkg = bio->bi_blkg; if (blkg->parent) { + /* + * Once it is on the list, a run which is under way can submit + * @bio, and its reference goes when it completes. + */ + blkg_get(blkg); spin_lock(&blkg->async_bio_lock); bio_list_add(&blkg->async_bios, bio); spin_unlock(&blkg->async_bio_lock); queue_work(blkcg_punt_bio_wq, &blkg->async_bio_work); + blkg_put(blkg); } else { /* never bounce for the root cgroup */ submit_bio(bio); @@ -873,7 +884,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); @@ -882,7 +897,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; @@ -1118,11 +1133,11 @@ static void blkcg_fill_root_iostats(void) cpu_dkstats->ios[STAT_DISCARD]; // convert sectors to bytes tmp.bytes[BLKG_IOSTAT_READ] += - cpu_dkstats->sectors[STAT_READ] << 9; + (u64)cpu_dkstats->sectors[STAT_READ] << 9; tmp.bytes[BLKG_IOSTAT_WRITE] += - cpu_dkstats->sectors[STAT_WRITE] << 9; + (u64)cpu_dkstats->sectors[STAT_WRITE] << 9; tmp.bytes[BLKG_IOSTAT_DISCARD] += - cpu_dkstats->sectors[STAT_DISCARD] << 9; + (u64)cpu_dkstats->sectors[STAT_DISCARD] << 9; } flags = u64_stats_update_begin_irqsave(&blkg->iostat.sync); @@ -1630,7 +1645,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); @@ -1642,7 +1658,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 @@ -2132,8 +2148,7 @@ static inline struct blkcg_gq *blkg_tryget_closest(struct bio *bio, void bio_associate_blkg_from_css(struct bio *bio, struct cgroup_subsys_state *css) { - if (bio->bi_blkg) - blkg_put(bio->bi_blkg); + struct blkcg_gq *old_blkg = bio->bi_blkg; if (css && css->parent) { bio->bi_blkg = blkg_tryget_closest(bio, css); @@ -2141,6 +2156,10 @@ void bio_associate_blkg_from_css(struct bio *bio, blkg_get(bdev_get_queue(bio->bi_bdev)->root_blkg); bio->bi_blkg = bdev_get_queue(bio->bi_bdev)->root_blkg; } + + /* @old_blkg may be the only thing which pins @css */ + if (old_blkg) + blkg_put(old_blkg); } EXPORT_SYMBOL_GPL(bio_associate_blkg_from_css); diff --git a/block/blk-cgroup.h b/block/blk-cgroup.h index e67c69839129..1fd60cb4157c 100644 --- a/block/blk-cgroup.h +++ b/block/blk-cgroup.h @@ -76,11 +76,9 @@ struct blkcg_gq { #ifdef CONFIG_BLK_CGROUP_PUNT_BIO spinlock_t async_bio_lock; struct bio_list async_bios; + struct work_struct async_bio_work; #endif - union { - struct work_struct async_bio_work; - struct work_struct free_work; - }; + struct work_struct free_work; atomic_t use_delay; atomic64_t delay_nsec; diff --git a/block/blk-flush.c b/block/blk-flush.c index 403a46c86411..38bd4ae5d9e7 100644 --- a/block/blk-flush.c +++ b/block/blk-flush.c @@ -212,7 +212,13 @@ static enum rq_end_io_ret flush_end_io(struct request *flush_rq, spin_lock_irqsave(&fq->mq_flush_lock, flags); if (!req_ref_put_and_test(flush_rq)) { - fq->rq_status = error; + /* + * Remember the status of the flush for whoever drops the last + * reference. blk_mq_put_rq_ref() gets here with BLK_STS_OK and + * must not wipe it out. + */ + if (error != BLK_STS_OK) + fq->rq_status = error; spin_unlock_irqrestore(&fq->mq_flush_lock, flags); return RQ_END_IO_NONE; } diff --git a/block/blk-iocost.c b/block/blk-iocost.c index 23445d701433..6cf314f9de40 100644 --- a/block/blk-iocost.c +++ b/block/blk-iocost.c @@ -173,6 +173,7 @@ */ #include +#include #include #include #include @@ -472,8 +473,8 @@ struct ioc_gq { * * When an idle cgroup becomes active its `active` goes from 0 to * `weight`. `inuse` is the surplus adjusted active weight. - * `active` and `inuse` are used to calculate `hweight_active` and - * `hweight_inuse`. + * `active` and `inuse` determine the hierarchical weights cached in + * `hweight_cache`. * * `last_inuse` remembers `inuse` while an iocg is idle to persist * surplus adjustments. @@ -520,7 +521,9 @@ struct ioc_gq { u64 child_active_sum; u64 child_inuse_sum; u64 child_adjusted_sum; - int hweight_gen; + /* Generation in bits 63:32; active - 1 and inuse - 1 in 31:16/15:0. */ + atomic64_t hweight_cache; + /* Donation workspace, protected by ioc->lock. */ u32 hweight_active; u32 hweight_inuse; u32 hweight_donating; @@ -727,6 +730,54 @@ static void iocg_commit_bio(struct ioc_gq *iocg, struct bio *bio, put_cpu_ptr(gcs); } +/* + * The hierarchical weights are in [1, WEIGHT_ONE] and the generation is a + * 32-bit counter. Pack generation and both weights into one 64-bit value so + * that a reader or a refresher always observes a complete snapshot: + * + * bits 63:32 generation + * bits 31:16 hweight_active - 1 + * bits 15:0 hweight_inuse - 1 + */ +#define HWEIGHT_GEN_MASK GENMASK_ULL(63, 32) +#define HWEIGHT_ACTIVE_MASK GENMASK_ULL(31, 16) +#define HWEIGHT_INUSE_MASK GENMASK_ULL(15, 0) + +static inline u64 hweight_cache_pack(u32 gen, u32 active, u32 inuse) +{ + return FIELD_PREP(HWEIGHT_GEN_MASK, gen) | + FIELD_PREP(HWEIGHT_ACTIVE_MASK, active - 1) | + FIELD_PREP(HWEIGHT_INUSE_MASK, inuse - 1); +} + +static inline void hweight_cache_unpack(u64 cache, u32 *genp, u32 *activep, + u32 *inusep) +{ + if (genp) + *genp = FIELD_GET(HWEIGHT_GEN_MASK, cache); + if (activep) + *activep = FIELD_GET(HWEIGHT_ACTIVE_MASK, cache) + 1; + if (inusep) + *inusep = FIELD_GET(HWEIGHT_INUSE_MASK, cache) + 1; +} + +/* Decode the published weights without refreshing the cache. */ +static inline void iocg_hweight_cache(struct ioc_gq *iocg, u32 *activep, + u32 *inusep) +{ + hweight_cache_unpack(atomic64_read(&iocg->hweight_cache), NULL, + activep, inusep); +} + +/* Decode the cached inuse weight; only used by tracepoints. */ +static inline u32 iocg_hweight_cache_inuse(struct ioc_gq *iocg) +{ + u32 inuse; + + iocg_hweight_cache(iocg, NULL, &inuse); + return inuse; +} + #define CREATE_TRACE_POINTS #include @@ -1154,12 +1205,15 @@ static void current_hweight(struct ioc_gq *iocg, u32 *hw_activep, u32 *hw_inusep { struct ioc *ioc = iocg->ioc; int lvl; - u32 hwa, hwi; - int ioc_gen; + u32 hwa, hwi, ioc_gen, cache_gen; + u64 cache; + + ioc_gen = (u32)atomic_read(&ioc->hweight_gen); - /* hot path - if uptodate, use cached */ - ioc_gen = atomic_read(&ioc->hweight_gen); - if (ioc_gen == iocg->hweight_gen) + /* hot path - if uptodate, use the cached snapshot */ + cache = atomic64_read(&iocg->hweight_cache); + hweight_cache_unpack(cache, &cache_gen, &hwa, &hwi); + if (cache_gen == ioc_gen) goto out; /* @@ -1194,14 +1248,20 @@ static void current_hweight(struct ioc_gq *iocg, u32 *hw_activep, u32 *hw_inusep hwi = div64_u64((u64)hwi * inuse, inuse_sum); } - iocg->hweight_active = max_t(u32, hwa, 1); - iocg->hweight_inuse = max_t(u32, hwi, 1); - iocg->hweight_gen = ioc_gen; + hwa = max_t(u32, hwa, 1); + hwi = max_t(u32, hwi, 1); + /* + * Publish the generation and both weights as one atomic snapshot. + * A concurrent refresher may overwrite this with its own snapshot, + * but the generation travels with the weights so the next reader + * detects the mismatch and refreshes again. + */ + atomic64_set(&iocg->hweight_cache, hweight_cache_pack(ioc_gen, hwa, hwi)); out: if (hw_activep) - *hw_activep = iocg->hweight_active; + *hw_activep = hwa; if (hw_inusep) - *hw_inusep = iocg->hweight_inuse; + *hw_inusep = hwi; } /* @@ -1249,7 +1309,8 @@ static bool iocg_activate(struct ioc_gq *iocg, struct ioc_now *now) { struct ioc *ioc = iocg->ioc; u64 __maybe_unused last_period, cur_period; - u64 vtime, vtarget; + u64 vtime, vtarget, cache; + u32 active, inuse; int i; /* @@ -1299,11 +1360,16 @@ static bool iocg_activate(struct ioc_gq *iocg, struct ioc_now *now) vtime = vtarget; /* - * Activate, propagate weight and start period timer if not - * running. Reset hweight_gen to avoid accidental match from - * wrapping. + * Activate, propagate weight and start period timer if not running. + * Invalidate the cached generation to avoid an accidental match from + * wrapping. Keep the last published weights so that the activation + * tracepoint can report them; the next current_hweight() recomputes. */ - iocg->hweight_gen = atomic_read(&ioc->hweight_gen) - 1; + cache = atomic64_read(&iocg->hweight_cache); + hweight_cache_unpack(cache, NULL, &active, &inuse); + atomic64_set(&iocg->hweight_cache, + hweight_cache_pack((u32)(atomic_read(&ioc->hweight_gen) - 1), + active, inuse)); list_add(&iocg->active_list, &ioc->active_iocgs); propagate_weights(iocg, iocg->weight, @@ -2049,7 +2115,7 @@ static void transfer_surpluses(struct list_head *surpluses, struct ioc_now *now) TRACE_IOCG_PATH(inuse_transfer, iocg, now, iocg->inuse, inuse, - iocg->hweight_inuse, + iocg_hweight_cache_inuse(iocg), iocg->hweight_after_donation); __propagate_weights(iocg, iocg->active, inuse, true, now); @@ -2362,7 +2428,7 @@ static void ioc_timer_fn(struct timer_list *timer) */ TRACE_IOCG_PATH(inuse_shortage, iocg, &now, iocg->inuse, iocg->active, - iocg->hweight_inuse, new_hwi); + old_hwi, new_hwi); __propagate_weights(iocg, iocg->active, iocg->active, true, &now); @@ -2545,6 +2611,7 @@ static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg, coef_randio = ioc->params.lcoefs[LCOEF_RRANDIO]; coef_page = ioc->params.lcoefs[LCOEF_RPAGE]; break; + case REQ_OP_ZONE_APPEND: case REQ_OP_WRITE: coef_seqio = ioc->params.lcoefs[LCOEF_WSEQIO]; coef_randio = ioc->params.lcoefs[LCOEF_WRANDIO]; @@ -2588,6 +2655,7 @@ static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc, case REQ_OP_READ: *costp = pages * ioc->params.lcoefs[LCOEF_RPAGE]; break; + case REQ_OP_ZONE_APPEND: case REQ_OP_WRITE: *costp = pages * ioc->params.lcoefs[LCOEF_WPAGE]; break; @@ -2859,6 +2927,7 @@ static void ioc_rqos_done(struct rq_qos *rqos, struct request *rq) pidx = QOS_RLAT; rw = READ; break; + case REQ_OP_ZONE_APPEND: case REQ_OP_WRITE: pidx = QOS_WLAT; rw = WRITE; @@ -2905,7 +2974,8 @@ static void ioc_rqos_exit(struct rq_qos *rqos) timer_shutdown_sync(&ioc->timer); free_percpu(ioc->pcpu_stat); - kfree(ioc); + /* blkcg_print_blkgs() gets here from a pd with only RCU held */ + kfree_rcu_mightsleep(ioc); } static const struct rq_qos_ops ioc_rqos_ops = { @@ -2922,11 +2992,12 @@ static int blk_iocost_init(struct gendisk *disk) struct ioc *ioc; int i, cpu, ret; - ioc = kzalloc_obj(*ioc); + /* The caller holds rq_qos_mutex, which is taken with the queue frozen */ + ioc = kzalloc_obj(*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; @@ -3037,6 +3108,9 @@ static void ioc_pd_init(struct blkg_policy_data *pd) INIT_LIST_HEAD(&iocg->active_list); INIT_LIST_HEAD(&iocg->walk_list); INIT_LIST_HEAD(&iocg->surplus_list); + atomic64_set(&iocg->hweight_cache, + hweight_cache_pack((u32)(atomic_read(&ioc->hweight_gen) - 1), + WEIGHT_ONE, WEIGHT_ONE)); iocg->hweight_active = WEIGHT_ONE; iocg->hweight_inuse = WEIGHT_ONE; diff --git a/block/blk-iolatency.c b/block/blk-iolatency.c index 2caa79a008ad..a3bd153c67be 100644 --- a/block/blk-iolatency.c +++ b/block/blk-iolatency.c @@ -637,8 +637,9 @@ static void blkcg_iolatency_exit(struct rq_qos *rqos) struct blk_iolatency *blkiolat = BLKIOLATENCY(rqos); timer_shutdown_sync(&blkiolat->timer); - flush_work(&blkiolat->enable_work); blkcg_deactivate_policy(rqos->disk, &blkcg_policy_iolatency); + /* iolatency_pd_offline() schedules it for the last group with a target */ + flush_work(&blkiolat->enable_work); kfree(blkiolat); } @@ -760,7 +761,8 @@ static int blk_iolatency_init(struct gendisk *disk) struct blk_iolatency *blkiolat; int ret; - blkiolat = kzalloc_obj(*blkiolat); + /* The caller holds rq_qos_mutex, which is taken with the queue frozen */ + blkiolat = kzalloc_obj(*blkiolat, GFP_NOIO); if (!blkiolat) return -ENOMEM; diff --git a/block/blk-map.c b/block/blk-map.c index 9cb9605d1f62..2685f6177ceb 100644 --- a/block/blk-map.c +++ b/block/blk-map.c @@ -236,6 +236,7 @@ static int bio_copy_user_iov(struct request *rq, struct rq_map_data *map_data, ret = bio_copy_from_iter(bio, &iter2); if (ret) goto cleanup; + iov_iter_advance(iter, bio->bi_iter.bi_size); } else { if (bmd->is_our_pages) zero_fill_bio(bio); diff --git a/block/blk-mq-dma.c b/block/blk-mq-dma.c index 88fd9cbc951f..e0e7a18790b5 100644 --- a/block/blk-mq-dma.c +++ b/block/blk-mq-dma.c @@ -181,6 +181,8 @@ static bool blk_dma_map_iter_start(struct request *req, struct device *dma_dev, switch (pci_p2pdma_state(&iter->p2pdma, dma_dev, phys_to_page(vec.paddr))) { case PCI_P2PDMA_MAP_BUS_ADDR: + /* 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-tag.c b/block/blk-mq-tag.c index 35deee5bbc73..04805808ccf9 100644 --- a/block/blk-mq-tag.c +++ b/block/blk-mq-tag.c @@ -18,6 +18,13 @@ #include "blk-mq.h" #include "blk-mq-sched.h" +/* + * Protects tag iteration against the deferred freeing of tags->page_list and + * flush queues. The callbacks touch neither the tag set nor driver code, so + * one global instance is enough and freeing a tag set needn't wait for them. + */ +DEFINE_SRCU(blk_mq_tags_srcu); + /* * Recalculate wakeup batch when tag is shared by hctx. */ @@ -443,7 +450,7 @@ void blk_mq_tagset_busy_iter(struct blk_mq_tag_set *tagset, unsigned int flags = tagset->flags; int i, nr_tags, srcu_idx; - srcu_idx = srcu_read_lock(&tagset->tags_srcu); + srcu_idx = srcu_read_lock(&blk_mq_tags_srcu); nr_tags = blk_mq_is_shared_tags(flags) ? 1 : tagset->nr_hw_queues; @@ -452,7 +459,7 @@ void blk_mq_tagset_busy_iter(struct blk_mq_tag_set *tagset, __blk_mq_all_tag_iter(tagset->tags[i], fn, priv, BT_TAG_ITER_STARTED); } - srcu_read_unlock(&tagset->tags_srcu, srcu_idx); + srcu_read_unlock(&blk_mq_tags_srcu, srcu_idx); } EXPORT_SYMBOL(blk_mq_tagset_busy_iter); @@ -512,7 +519,7 @@ void blk_mq_queue_tag_busy_iter(struct request_queue *q, busy_tag_iter_fn *fn, if (!percpu_ref_tryget(&q->q_usage_counter)) return; - srcu_idx = srcu_read_lock(&q->tag_set->tags_srcu); + srcu_idx = srcu_read_lock(&blk_mq_tags_srcu); if (blk_mq_is_shared_tags(q->tag_set->flags)) { struct blk_mq_tags *tags = q->tag_set->shared_tags; struct sbitmap_queue *bresv = &tags->breserved_tags; @@ -542,7 +549,7 @@ void blk_mq_queue_tag_busy_iter(struct request_queue *q, busy_tag_iter_fn *fn, bt_for_each(hctx, q, btags, fn, priv, false); } } - srcu_read_unlock(&q->tag_set->tags_srcu, srcu_idx); + srcu_read_unlock(&blk_mq_tags_srcu, srcu_idx); blk_queue_exit(q); } @@ -604,21 +611,21 @@ static void blk_mq_free_tags_callback(struct rcu_head *head) kmemleak_free(page_address(page)); __free_pages(page, page->private); } + /* An iterator may walk the bitmaps for as long as it may see the tags */ + sbitmap_queue_free(&tags->bitmap_tags); + sbitmap_queue_free(&tags->breserved_tags); kfree(tags); } void blk_mq_free_tags(struct blk_mq_tag_set *set, struct blk_mq_tags *tags) { - sbitmap_queue_free(&tags->bitmap_tags); - sbitmap_queue_free(&tags->breserved_tags); - /* if tags pages is not allocated yet, free tags directly */ if (list_empty(&tags->page_list)) { - kfree(tags); + blk_mq_free_tags_callback(&tags->rcu_head); return; } - call_srcu(&set->tags_srcu, &tags->rcu_head, blk_mq_free_tags_callback); + call_srcu(&blk_mq_tags_srcu, &tags->rcu_head, blk_mq_free_tags_callback); } void blk_mq_tag_resize_shared_tags(struct blk_mq_tag_set *set, unsigned int size) diff --git a/block/blk-mq.c b/block/blk-mq.c index e21d69767fd4..a162a64648c8 100644 --- a/block/blk-mq.c +++ b/block/blk-mq.c @@ -336,12 +336,15 @@ void blk_mq_quiesce_tagset(struct blk_mq_tag_set *set) { struct request_queue *q; + spin_lock(&set->quiesce_lock); + set->quiesce_depth++; rcu_read_lock(); list_for_each_entry_rcu(q, &set->tag_list, tag_set_list) { if (!blk_queue_skip_tagset_quiesce(q)) blk_mq_quiesce_queue_nowait(q); } rcu_read_unlock(); + spin_unlock(&set->quiesce_lock); blk_mq_wait_quiesce_done(set); } @@ -351,12 +354,16 @@ void blk_mq_unquiesce_tagset(struct blk_mq_tag_set *set) { struct request_queue *q; + spin_lock(&set->quiesce_lock); + if (set->quiesce_depth) + set->quiesce_depth--; rcu_read_lock(); list_for_each_entry_rcu(q, &set->tag_list, tag_set_list) { if (!blk_queue_skip_tagset_quiesce(q)) blk_mq_unquiesce_queue(q); } rcu_read_unlock(); + spin_unlock(&set->quiesce_lock); } EXPORT_SYMBOL_GPL(blk_mq_unquiesce_tagset); @@ -1639,7 +1646,7 @@ EXPORT_SYMBOL_GPL(blk_mq_queue_inflight); static void blk_mq_rq_timed_out(struct request *req) { - req->rq_flags |= RQF_TIMED_OUT; + blk_rq_change_timed_out(req, true); if (req->q->mq_ops->timeout) { enum blk_eh_timer_return ret; @@ -1710,8 +1717,11 @@ static bool blk_mq_handle_expired(struct request *rq, void *priv) { struct blk_expired_data *expired = priv; - if (blk_mq_req_expired(rq, expired)) + if (blk_mq_req_expired(rq, expired)) { blk_mq_rq_timed_out(rq); + /* If its timer has been started again, count the new deadline */ + blk_mq_req_expired(rq, expired); + } return true; } @@ -3696,9 +3706,9 @@ static bool blk_mq_hctx_has_requests(struct blk_mq_hw_ctx *hctx) }; int srcu_idx; - srcu_idx = srcu_read_lock(&hctx->queue->tag_set->tags_srcu); + srcu_idx = srcu_read_lock(&blk_mq_tags_srcu); blk_mq_all_tag_iter(tags, blk_mq_has_request, &data); - srcu_read_unlock(&hctx->queue->tag_set->tags_srcu, srcu_idx); + srcu_read_unlock(&blk_mq_tags_srcu, srcu_idx); return data.has_rq; } @@ -3970,7 +3980,7 @@ static void blk_mq_exit_hctx(struct request_queue *q, if (set->ops->exit_hctx) set->ops->exit_hctx(hctx, hctx_idx); - call_srcu(&set->tags_srcu, &hctx->fq->rcu_head, + call_srcu(&blk_mq_tags_srcu, &hctx->fq->rcu_head, blk_free_flush_queue_callback); hctx->fq = NULL; @@ -4329,7 +4339,8 @@ static void blk_mq_del_queue_tag_set(struct request_queue *q) { struct blk_mq_tag_set *set = q->tag_set; - mutex_lock(&set->tag_list_lock); + lockdep_assert_held(&set->tag_list_lock); + list_del_rcu(&q->tag_set_list); if (list_is_singular(&set->tag_list)) { /* just transitioned to unshared */ @@ -4337,13 +4348,14 @@ static void blk_mq_del_queue_tag_set(struct request_queue *q) /* update existing queue */ blk_mq_update_tag_set_shared(set, false); } - mutex_unlock(&set->tag_list_lock); } static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set, struct request_queue *q) { - mutex_lock(&set->tag_list_lock); + unsigned int i; + + lockdep_assert_held(&set->tag_list_lock); /* * Check to see if we're transitioning to shared (from 1 to 2 queues). @@ -4356,9 +4368,18 @@ static void blk_mq_add_queue_tag_set(struct blk_mq_tag_set *set, } if (set->flags & BLK_MQ_F_TAG_QUEUE_SHARED) queue_set_hctx_shared(q, true); - list_add_tail_rcu(&q->tag_set_list, &set->tag_list); - mutex_unlock(&set->tag_list_lock); + /* + * A queue that joins a quiesced tag set is quiesced like the others, + * and blk_mq_unquiesce_tagset() finds what it is going to undo. + */ + spin_lock(&set->quiesce_lock); + list_add_tail_rcu(&q->tag_set_list, &set->tag_list); + if (!blk_queue_skip_tagset_quiesce(q)) { + for (i = 0; i < set->quiesce_depth; i++) + blk_mq_quiesce_queue_nowait(q); + } + spin_unlock(&set->quiesce_lock); } /* All allocations will be freed in release handler of q->mq_kobj */ @@ -4635,6 +4656,8 @@ static void blk_mq_realloc_hw_ctxs(struct blk_mq_tag_set *set, int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set, struct request_queue *q) { + unsigned int memflags; + /* mark the queue as mq asap */ q->mq_ops = set->ops; @@ -4653,6 +4676,16 @@ int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set, INIT_LIST_HEAD(&q->unused_hctx_list); spin_lock_init(&q->unused_hctx_lock); + /* + * Keep blk_mq_update_nr_hw_queues() away until the queue is on + * set->tag_list: it changes the number of hardware queues, the tags and + * the maps, and blk_mq_map_swqueue() allocates and frees tags of the set. + * An update can be part of the error handling of a driver, so it must + * not have to wait for somebody who waits for I/O. + */ + memflags = memalloc_noio_save(); + mutex_lock(&set->tag_list_lock); + blk_mq_realloc_hw_ctxs(set, q); if (!q->nr_hw_queues) goto err_hctxs; @@ -4673,9 +4706,14 @@ int blk_mq_init_allocated_queue(struct blk_mq_tag_set *set, blk_mq_init_cpu_queues(q, set->nr_hw_queues); blk_mq_map_swqueue(q); blk_mq_add_queue_tag_set(set, q); + + mutex_unlock(&set->tag_list_lock); + memalloc_noio_restore(memflags); return 0; err_hctxs: + mutex_unlock(&set->tag_list_lock); + memalloc_noio_restore(memflags); blk_mq_release(q); err_exit: q->mq_ops = NULL; @@ -4688,10 +4726,16 @@ void blk_mq_exit_queue(struct request_queue *q) { struct blk_mq_tag_set *set = q->tag_set; + /* + * As long as the queue is on set->tag_list, its hctxs belong to + * blk_mq_update_nr_hw_queues() as well, which exits and replaces them. + */ + mutex_lock(&set->tag_list_lock); /* Checks hctx->flags & BLK_MQ_F_TAG_QUEUE_SHARED. */ blk_mq_exit_hw_queues(q, set, set->nr_hw_queues); /* May clear BLK_MQ_F_TAG_QUEUE_SHARED in hctx->flags. */ blk_mq_del_queue_tag_set(q); + mutex_unlock(&set->tag_list_lock); } static int __blk_mq_alloc_rq_maps(struct blk_mq_tag_set *set) @@ -4898,9 +4942,6 @@ int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set) if (ret) goto out_free_srcu; } - ret = init_srcu_struct(&set->tags_srcu); - if (ret) - goto out_cleanup_srcu; init_rwsem(&set->update_nr_hwq_lock); @@ -4909,7 +4950,7 @@ int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set) sizeof(struct blk_mq_tags *), GFP_KERNEL, set->numa_node); if (!set->tags) - goto out_cleanup_tags_srcu; + goto out_cleanup_srcu; for (i = 0; i < set->nr_maps; i++) { set->map[i].mq_map = kcalloc_node(nr_cpu_ids, @@ -4928,6 +4969,8 @@ int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set) mutex_init(&set->tag_list_lock); INIT_LIST_HEAD(&set->tag_list); + spin_lock_init(&set->quiesce_lock); + set->quiesce_depth = 0; return 0; @@ -4938,8 +4981,6 @@ int blk_mq_alloc_tag_set(struct blk_mq_tag_set *set) } kfree(set->tags); set->tags = NULL; -out_cleanup_tags_srcu: - cleanup_srcu_struct(&set->tags_srcu); out_cleanup_srcu: if (set->flags & BLK_MQ_F_BLOCKING) cleanup_srcu_struct(set->srcu); @@ -4986,8 +5027,6 @@ void blk_mq_free_tag_set(struct blk_mq_tag_set *set) kfree(set->tags); set->tags = NULL; - srcu_barrier(&set->tags_srcu); - cleanup_srcu_struct(&set->tags_srcu); if (set->flags & BLK_MQ_F_BLOCKING) { srcu_barrier(set->srcu); cleanup_srcu_struct(set->srcu); @@ -5191,6 +5230,9 @@ static void __blk_mq_update_nr_hw_queues(struct blk_mq_tag_set *set, goto fallback; } blk_mq_map_swqueue(q); + /* The new hctxs don't know yet that they share their tags */ + if (set->flags & BLK_MQ_F_TAG_QUEUE_SHARED) + queue_set_hctx_shared(q, true); } switch_back: /* The blk_mq_elv_switch_back unfreezes queue for us. */ @@ -5252,9 +5294,22 @@ static int blk_hctx_poll(struct request_queue *q, struct blk_mq_hw_ctx *hctx, int blk_mq_poll(struct request_queue *q, blk_qc_t cookie, struct io_comp_batch *iob, unsigned int flags) { + struct blk_mq_hw_ctx *hctx; + if (!blk_mq_can_poll(q)) return 0; - return blk_hctx_poll(q, q->queue_hw_ctx[cookie], iob, flags); + + /* + * The cookie is no more than a hint. iocb_bio_iopoll() may have read it + * from a bio that was reused for another queue right afterwards, and + * zone write plugging keeps the number of segments in the same field. + */ + if (cookie >= q->nr_hw_queues) + return 0; + hctx = q->queue_hw_ctx[cookie]; + if (hctx->type != HCTX_TYPE_POLL) + return 0; + return blk_hctx_poll(q, hctx, iob, flags); } int blk_rq_poll(struct request *rq, struct io_comp_batch *iob, diff --git a/block/blk-mq.h b/block/blk-mq.h index aa15d31aaae9..e6b463da5071 100644 --- a/block/blk-mq.h +++ b/block/blk-mq.h @@ -178,6 +178,8 @@ struct blk_mq_tags *blk_mq_init_tags(unsigned int nr_tags, unsigned int reserved_tags, unsigned int flags, int node); void blk_mq_free_tags(struct blk_mq_tag_set *set, struct blk_mq_tags *tags); +extern struct srcu_struct blk_mq_tags_srcu; + unsigned int blk_mq_get_tag(struct blk_mq_alloc_data *data); unsigned long blk_mq_get_tags(struct blk_mq_alloc_data *data, int nr_tags, unsigned int *offset); diff --git a/block/blk-settings.c b/block/blk-settings.c index 8274631290db..e469baa1f08b 100644 --- a/block/blk-settings.c +++ b/block/blk-settings.c @@ -206,6 +206,12 @@ static int blk_validate_integrity_limits(struct queue_limits *lim) lim->max_sectors = min(lim->max_sectors, max_integrity_io_size(lim) >> SECTOR_SHIFT); + if (lim->features & BLK_FEAT_ATOMIC_WRITES) { + lim->atomic_write_max_sectors = + min(lim->atomic_write_max_sectors, + max_integrity_io_size(lim) >> SECTOR_SHIFT); + } + return 0; } diff --git a/block/blk-throttle.c b/block/blk-throttle.c index ffc3b70065d4..c5e26551956a 100644 --- a/block/blk-throttle.c +++ b/block/blk-throttle.c @@ -1322,7 +1322,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; @@ -1386,7 +1387,8 @@ static ssize_t tg_set_conf(struct kernfs_open_file *of, if (is_u64) *(u64 *)((void *)tg + of_cft(of)->private) = v; else - *(unsigned int *)((void *)tg + of_cft(of)->private) = v; + *(unsigned int *)((void *)tg + of_cft(of)->private) = + min_t(u64, v, UINT_MAX); tg_conf_updated(tg, false); ret = 0; @@ -1669,7 +1671,26 @@ static void tg_flush_bios(struct throtl_grp *tg) static void throtl_pd_offline(struct blkg_policy_data *pd) { - tg_flush_bios(pd_to_tg(pd)); + struct throtl_grp *tg = pd_to_tg(pd); + struct throtl_grp *parent = blkg_to_tg(tg_to_blkg(tg)->parent); + + tg_flush_bios(tg); + + /* the recursive files of the ancestors go on counting what it did */ + if (parent) { + blkg_rwstat_add_aux(&parent->stat_bytes, &tg->stat_bytes); + blkg_rwstat_add_aux(&parent->stat_ios, &tg->stat_ios); + blkg_rwstat_reset(&tg->stat_bytes); + blkg_rwstat_reset(&tg->stat_ios); + } +} + +static void throtl_pd_reset_stats(struct blkg_policy_data *pd) +{ + struct throtl_grp *tg = pd_to_tg(pd); + + blkg_rwstat_reset(&tg->stat_bytes); + blkg_rwstat_reset(&tg->stat_ios); } struct blkcg_policy blkcg_policy_throtl = { @@ -1681,6 +1702,7 @@ struct blkcg_policy blkcg_policy_throtl = { .pd_online_fn = throtl_pd_online, .pd_offline_fn = throtl_pd_offline, .pd_free_fn = throtl_pd_free, + .pd_reset_stats_fn = throtl_pd_reset_stats, }; static void tg_cancel_writeback_bios(struct throtl_grp *tg, diff --git a/block/blk-timeout.c b/block/blk-timeout.c index 1b8de0417fc1..0590720e38c7 100644 --- a/block/blk-timeout.c +++ b/block/blk-timeout.c @@ -137,7 +137,8 @@ void blk_add_timer(struct request *req) if (!req->timeout) req->timeout = q->rq_timeout; - req->rq_flags &= ~RQF_TIMED_OUT; + if (req->rq_flags & RQF_TIMED_OUT) + blk_rq_change_timed_out(req, false); expiry = jiffies + req->timeout; WRITE_ONCE(req->deadline, expiry); diff --git a/block/blk.h b/block/blk.h index 50abfd932886..694d3f94ced5 100644 --- a/block/blk.h +++ b/block/blk.h @@ -332,6 +332,20 @@ static inline void bio_integrity_free(struct bio *bio) unsigned long blk_rq_timeout(unsigned long timeout); void blk_add_timer(struct request *req); +/* + * The timeout handler changes RQF_TIMED_OUT in a request which it does not + * own: whoever completes it changes rq_flags at the same time, with plain + * loads and stores. Never write back a flag that has changed under us. + */ +static inline void blk_rq_change_timed_out(struct request *rq, bool set) +{ + req_flags_t old = READ_ONCE(rq->rq_flags), new; + + do { + new = set ? old | RQF_TIMED_OUT : old & ~RQF_TIMED_OUT; + } while (!try_cmpxchg(&rq->rq_flags, &old, new)); +} + enum bio_merge_status { BIO_MERGE_OK, BIO_MERGE_NONE, diff --git a/block/fops.c b/block/fops.c index c915ec0126d7..f404ab1bd4d1 100644 --- a/block/fops.c +++ b/block/fops.c @@ -26,12 +26,26 @@ static inline struct inode *bdev_file_inode(struct file *file) return file->f_mapping->host; } -static blk_opf_t dio_bio_write_op(struct kiocb *iocb) +static bool blkdev_dio_fua(struct kiocb *iocb, struct block_device *bdev) +{ + if (!iocb_is_dsync(iocb)) + return false; + /* + * Async writes cannot fall back to generic_write_sync(), so they must + * use FUA (emulated if needed); sync writes only need it when the + * device supports FUA natively. + */ + if (!is_sync_kiocb(iocb)) + return true; + return bdev_fua(bdev); +} + +static blk_opf_t dio_bio_write_op(struct kiocb *iocb, struct block_device *bdev) { blk_opf_t opf = REQ_OP_WRITE | REQ_SYNC | REQ_IDLE; /* avoid the need for a I/O completion work item */ - if (iocb_is_dsync(iocb)) + if (blkdev_dio_fua(iocb, bdev)) opf |= REQ_FUA; return opf; } @@ -75,7 +89,8 @@ static ssize_t __blkdev_direct_IO_simple(struct kiocb *iocb, if (user_backed_iter(iter)) should_dirty = true; } else { - bio_init(&bio, bdev, vecs, nr_pages, dio_bio_write_op(iocb)); + bio_init(&bio, bdev, vecs, nr_pages, + dio_bio_write_op(iocb, bdev)); } bio.bi_iter.bi_sector = pos >> SECTOR_SHIFT; bio.bi_write_hint = file_inode(iocb->ki_filp)->i_write_hint; @@ -179,7 +194,7 @@ static ssize_t __blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter, struct blkdev_dio *dio; struct bio *bio; bool is_read = (iov_iter_rw(iter) == READ), is_sync; - blk_opf_t opf = is_read ? REQ_OP_READ : dio_bio_write_op(iocb); + blk_opf_t opf = is_read ? REQ_OP_READ : dio_bio_write_op(iocb, bdev); loff_t pos = iocb->ki_pos; int ret = 0; @@ -325,7 +340,7 @@ static ssize_t __blkdev_direct_IO_async(struct kiocb *iocb, unsigned int nr_pages) { bool is_read = iov_iter_rw(iter) == READ; - blk_opf_t opf = is_read ? REQ_OP_READ : dio_bio_write_op(iocb); + blk_opf_t opf = is_read ? REQ_OP_READ : dio_bio_write_op(iocb, bdev); struct blkdev_dio *dio; struct bio *bio; loff_t pos = iocb->ki_pos; @@ -565,7 +580,7 @@ static int blkdev_writepages(struct address_space *mapping, } const struct address_space_operations def_blk_aops = { - .dirty_folio = filemap_dirty_folio, + .dirty_folio = iomap_dirty_folio, .release_folio = iomap_release_folio, .invalidate_folio = iomap_invalidate_folio, .read_folio = blkdev_read_folio, @@ -714,8 +729,22 @@ blkdev_direct_write(struct kiocb *iocb, struct iov_iter *from) static ssize_t blkdev_buffered_write(struct kiocb *iocb, struct iov_iter *from) { - return iomap_file_buffered_write(iocb, from, &blkdev_iomap_ops, NULL, - NULL); + struct inode *inode = bdev_file_inode(iocb->ki_filp); + ssize_t ret; + + /* Buffered fallback waits for writeback, which NOWAIT cannot allow. */ + if (iocb->ki_flags & IOCB_NOWAIT) + return -EAGAIN; + + /* + * Take i_rwsem to avoid racing with set_blocksize() changing + * i_blkbits/folio order and truncating the page cache. + */ + inode_lock_shared(inode); + ret = iomap_file_buffered_write(iocb, from, &blkdev_iomap_ops, NULL, + NULL); + inode_unlock_shared(inode); + return ret; } /* @@ -733,6 +762,7 @@ static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from) bool atomic = iocb->ki_flags & IOCB_ATOMIC; loff_t size = bdev_nr_bytes(bdev); size_t shorted = 0; + bool need_sync = false; ssize_t ret; if (bdev_read_only(bdev)) @@ -770,21 +800,42 @@ static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from) if (iocb->ki_flags & IOCB_DIRECT) { ret = blkdev_direct_write(iocb, from); - if (ret >= 0 && iov_iter_count(from)) - ret = direct_write_fallback(iocb, from, ret, - blkdev_buffered_write(iocb, from)); + if (ret >= 0 && iov_iter_count(from)) { + if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_ATOMIC)) { + /* + * The buffered fallback blocks on i_rwsem and + * on writeback of the data it copied, and + * can't provide torn-write protection: return + * the short direct write instead and let the + * caller retry. The bytes already written + * still need a flush if REQ_FUA was not set. + */ + if (!ret) + ret = -EAGAIN; + else if (!blkdev_dio_fua(iocb, bdev)) + need_sync = true; + } else { + ssize_t ret2; + + ret2 = blkdev_buffered_write(iocb, from); + ret = direct_write_fallback(iocb, from, ret, + ret2); + need_sync = true; + } + } else if (ret > 0 && !blkdev_dio_fua(iocb, bdev)) { + /* + * The device does not support FUA, so REQ_FUA was not + * set and the O_DSYNC direct write still needs a flush + * to be made durable. + */ + need_sync = true; + } } else { - /* - * Take i_rwsem and invalidate_lock to avoid racing with - * set_blocksize changing i_blkbits/folio order and punching - * out the pagecache. - */ - inode_lock_shared(bd_inode); ret = blkdev_buffered_write(iocb, from); - inode_unlock_shared(bd_inode); + need_sync = true; } - if (ret > 0) + if (ret > 0 && need_sync) ret = generic_write_sync(iocb, ret); iov_iter_reexpand(from, iov_iter_count(from) + shorted); return ret; @@ -833,7 +884,15 @@ static ssize_t blkdev_read_iter(struct kiocb *iocb, struct iov_iter *to) * Take i_rwsem and invalidate_lock to avoid racing with set_blocksize * changing i_blkbits/folio order and punching out the pagecache. */ - inode_lock_shared(bd_inode); + if (iocb->ki_flags & IOCB_NOWAIT) { + if (!inode_trylock_shared(bd_inode)) { + if (!ret) + ret = -EAGAIN; + goto reexpand; + } + } else { + inode_lock_shared(bd_inode); + } ret = filemap_read(iocb, to, ret); inode_unlock_shared(bd_inode); @@ -843,6 +902,22 @@ static ssize_t blkdev_read_iter(struct kiocb *iocb, struct iov_iter *to) return ret; } +/* + * Take i_rwsem to avoid racing with set_blocksize changing i_blkbits/folio + * order and punching out the pagecache. + */ +static ssize_t blkdev_splice_read(struct file *in, loff_t *ppos, + struct pipe_inode_info *pipe, size_t len, unsigned int flags) +{ + struct inode *bd_inode = bdev_file_inode(in); + ssize_t ret; + + inode_lock_shared(bd_inode); + ret = filemap_splice_read(in, ppos, pipe, len, flags); + inode_unlock_shared(bd_inode); + return ret; +} + #define BLKDEV_FALLOC_FL_SUPPORTED \ (FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE | \ FALLOC_FL_ZERO_RANGE | FALLOC_FL_WRITE_ZEROES) @@ -944,7 +1019,7 @@ const struct file_operations def_blk_fops = { #ifdef CONFIG_COMPAT .compat_ioctl = compat_blkdev_ioctl, #endif - .splice_read = filemap_splice_read, + .splice_read = blkdev_splice_read, .splice_write = iter_file_splice_write, .fallocate = blkdev_fallocate, .uring_cmd = blkdev_uring_cmd, diff --git a/block/partitions/mac.c b/block/partitions/mac.c index df03ca428e15..f372392af95b 100644 --- a/block/partitions/mac.c +++ b/block/partitions/mac.c @@ -97,8 +97,8 @@ int mac_partition(struct parsed_partitions *state) if (be16_to_cpu(part->signature) != MAC_PARTITION_MAGIC) break; put_partition(state, slot, - be32_to_cpu(part->start_block) * (secsize/512), - be32_to_cpu(part->block_count) * (secsize/512)); + (sector_t)be32_to_cpu(part->start_block) * (secsize/512), + (sector_t)be32_to_cpu(part->block_count) * (secsize/512)); if (!strncasecmp(part->type, "Linux_RAID", 10)) state->parts[slot].flags = ADDPART_FLAG_RAID; diff --git a/crypto/algapi.c b/crypto/algapi.c index 37de377719ae..a6839e2a20f3 100644 --- a/crypto/algapi.c +++ b/crypto/algapi.c @@ -424,7 +424,6 @@ static void crypto_free_alg(struct crypto_alg *alg) unsigned int algsize = alg->cra_type->algsize; u8 *p = (u8 *)alg - algsize; - crypto_destroy_alg(alg); kfree(p); } @@ -494,9 +493,31 @@ void crypto_unregister_alg(struct crypto_alg *alg) LIST_HEAD(list); down_write(&crypto_alg_sem); + if (alg->cra_flags & CRYPTO_ALG_DUP_FIRST) { + struct crypto_alg *q, *r = NULL; + + list_for_each_entry(q, &crypto_alg_list, cra_list) { + if (crypto_is_larval(q)) + continue; + if (strcmp(q->cra_driver_name, alg->cra_driver_name)) + continue; + r = q; + break; + } + + if (!r) { + up_write(&crypto_alg_sem); + ret = -ENOENT; + goto not_found; + } + + alg = r; + } + ret = crypto_remove_alg(alg, &list); up_write(&crypto_alg_sem); +not_found: if (WARN(ret, "Algorithm %s is not registered", alg->cra_driver_name)) return; diff --git a/crypto/asymmetric_keys/pkcs7_parser.c b/crypto/asymmetric_keys/pkcs7_parser.c index 6e3ffdac83ac..7f00e45a33cf 100644 --- a/crypto/asymmetric_keys/pkcs7_parser.c +++ b/crypto/asymmetric_keys/pkcs7_parser.c @@ -111,6 +111,12 @@ static int pkcs7_check_authattrs(struct pkcs7_message *msg) if (!!sinfo->authattrs != want) goto inconsistent; +#ifdef CONFIG_PKCS7_WAIVE_AUTHATTRS_REJECTION_FOR_MLDSA + if (sinfo->authattrs && + strncmp(sinfo->sig->pkey_algo, "mldsa", 5) != 0) + msg->authattrs_rej_waivable = false; +#endif + if (!sinfo->authattrs && sinfo->sig->algo_takes_data) sinfo->sig->hash_algo = "none"; diff --git a/crypto/asymmetric_keys/verify_pefile.c b/crypto/asymmetric_keys/verify_pefile.c index cec99db14129..1efd5c0d0e9c 100644 --- a/crypto/asymmetric_keys/verify_pefile.c +++ b/crypto/asymmetric_keys/verify_pefile.c @@ -87,6 +87,11 @@ static int pefile_parse_binary(const void *pebuf, unsigned int pelen, if (ctx->n_data_dirents > (ctx->header_size - cursor) / sizeof(*dde)) return -ELIBBAD; + /* the certificate table entry must be present in the data directory */ + if (ctx->n_data_dirents <= + offsetof(struct data_directory, certs) / sizeof(*dde)) + return -ELIBBAD; + ddir = pebuf + cursor; cursor += sizeof(*dde) * ctx->n_data_dirents; diff --git a/crypto/asymmetric_keys/x509_public_key.c b/crypto/asymmetric_keys/x509_public_key.c index 25cf8ac7f257..5c9165a83f91 100644 --- a/crypto/asymmetric_keys/x509_public_key.c +++ b/crypto/asymmetric_keys/x509_public_key.c @@ -53,9 +53,11 @@ int x509_get_sig_params(struct x509_certificate *cert) if (sig->algo_takes_data) { /* The signature algorithm does whatever passes for hashing. */ - sig->m = (u8 *)cert->tbs; + sig->m = kmemdup(cert->tbs, cert->tbs_size, GFP_KERNEL); + if (!sig->m) + return -ENOMEM; sig->m_size = cert->tbs_size; - sig->m_free = false; + sig->m_free = true; goto out; } diff --git a/crypto/lskcipher.c b/crypto/lskcipher.c index a8b07594005d..6c30436a1135 100644 --- a/crypto/lskcipher.c +++ b/crypto/lskcipher.c @@ -75,6 +75,7 @@ static int crypto_lskcipher_crypt_unaligned( unsigned ivsize = crypto_lskcipher_ivsize(tfm); unsigned bs = crypto_lskcipher_blocksize(tfm); unsigned cs = crypto_lskcipher_chunksize(tfm); + u32 flags = 0; int err; u8 *tiv; u8 *p; @@ -98,13 +99,16 @@ static int crypto_lskcipher_crypt_unaligned( if (chunk > cs) chunk &= ~(cs - 1); + if (chunk == len) + flags |= CRYPTO_LSKCIPHER_FLAG_FINAL; memcpy(p, src, chunk); - err = crypt(tfm, p, p, chunk, tiv, CRYPTO_LSKCIPHER_FLAG_FINAL); + err = crypt(tfm, p, p, chunk, tiv, flags); if (err) goto out; memcpy(dst, p, chunk); + flags |= CRYPTO_LSKCIPHER_FLAG_CONT; src += chunk; dst += chunk; len -= chunk; diff --git a/crypto/rsassa-pkcs1.c b/crypto/rsassa-pkcs1.c index 94fa5e9600e7..39137476ce81 100644 --- a/crypto/rsassa-pkcs1.c +++ b/crypto/rsassa-pkcs1.c @@ -169,7 +169,7 @@ static int rsassa_pkcs1_sign(struct crypto_sig *tfm, u8 *in_buf; int err; - if (!ctx->key_size) + if (ctx->key_size < 11) return -EINVAL; if (dlen < ctx->key_size) @@ -231,7 +231,7 @@ static int rsassa_pkcs1_verify(struct crypto_sig *tfm, int err; /* RFC 8017 sec 8.2.2 step 1 - length checking */ - if (!ctx->key_size || + if (ctx->key_size < 11 || slen != ctx->key_size || rsassa_pkcs1_invalid_hash_len(dlen, hash_prefix)) return -EINVAL; diff --git a/crypto/tcrypt.c b/crypto/tcrypt.c index 61a2501bfe9b..e6834bdde9b9 100644 --- a/crypto/tcrypt.c +++ b/crypto/tcrypt.c @@ -56,6 +56,21 @@ */ #define get_driver_name(tfm_type, tfm) crypto_tfm_alg_driver_name(tfm_type ## _tfm(tfm)) +struct tcrypt_aead_request { + struct aead_request *req; + struct crypto_wait wait; +}; + +struct tcrypt_ahash_request { + struct ahash_request *req; + struct crypto_wait wait; +}; + +struct tcrypt_skcipher_request { + struct skcipher_request *req; + struct crypto_wait wait; +}; + /* * Used by test_cipher_speed() */ @@ -129,18 +144,15 @@ static void sg_init_aead(struct scatterlist *sg, char *xbuf[XBUFSIZE], sg_set_buf(&sg[k + 1], xbuf[k], rem); } -static inline int do_one_aead_op(struct aead_request *req, int ret) +static inline int do_one_aead_op(struct tcrypt_aead_request *req, int ret) { - struct crypto_wait *wait = req->base.data; - - return crypto_wait_req(ret, wait); + return crypto_wait_req(ret, &req->wait); } struct test_mb_aead_data { struct scatterlist sg[XBUFSIZE]; struct scatterlist sgout[XBUFSIZE]; - struct aead_request *req; - struct crypto_wait wait; + struct tcrypt_aead_request req; char *xbuf[XBUFSIZE]; char *xoutbuf[XBUFSIZE]; char *axbuf[XBUFSIZE]; @@ -154,14 +166,14 @@ static int do_mult_aead_op(struct test_mb_aead_data *data, int enc, /* Fire up a bunch of concurrent requests */ for (i = 0; i < num_mb; i++) { if (enc == ENCRYPT) - rc[i] = crypto_aead_encrypt(data[i].req); + rc[i] = crypto_aead_encrypt(data[i].req.req); else - rc[i] = crypto_aead_decrypt(data[i].req); + rc[i] = crypto_aead_decrypt(data[i].req.req); } /* Wait for all requests to finish */ for (i = 0; i < num_mb; i++) { - rc[i] = crypto_wait_req(rc[i], &data[i].wait); + rc[i] = crypto_wait_req(rc[i], &data[i].req.wait); if (rc[i]) { pr_info("concurrent request %d error %d\n", i, rc[i]); @@ -310,21 +322,21 @@ static void test_mb_aead_speed(const char *algo, int enc, int secs, } for (i = 0; i < num_mb; ++i) { - data[i].req = aead_request_alloc(tfm, GFP_KERNEL); - if (!data[i].req) { + data[i].req.req = aead_request_alloc(tfm, GFP_KERNEL); + if (!data[i].req.req) { pr_err("alg: aead: Failed to allocate request for %s\n", algo); while (i--) - aead_request_free(data[i].req); + aead_request_free(data[i].req.req); goto out_free_xoutbuf; } } for (i = 0; i < num_mb; ++i) { - crypto_init_wait(&data[i].wait); - aead_request_set_callback(data[i].req, + crypto_init_wait(&data[i].req.wait); + aead_request_set_callback(data[i].req.req, CRYPTO_TFM_REQ_MAY_BACKLOG, - crypto_req_done, &data[i].wait); + crypto_req_done, &data[i].req.wait); } pr_info("testing speed of multibuffer %s (%s) %s\n", algo, @@ -386,16 +398,16 @@ static void test_mb_aead_speed(const char *algo, int enc, int secs, bs + (enc ? authsize : 0), assoc, aad_size); - aead_request_set_ad(cur->req, aad_size); + aead_request_set_ad(cur->req.req, aad_size); if (!enc) { - aead_request_set_crypt(cur->req, + aead_request_set_crypt(cur->req.req, cur->sgout, cur->sg, bs, iv); - ret = crypto_aead_encrypt(cur->req); - ret = do_one_aead_op(cur->req, ret); + ret = crypto_aead_encrypt(cur->req.req); + ret = do_one_aead_op(&cur->req, ret); if (ret) { pr_err("calculating auth failed (%d)\n", @@ -404,7 +416,7 @@ static void test_mb_aead_speed(const char *algo, int enc, int secs, } } - aead_request_set_crypt(cur->req, cur->sg, + aead_request_set_crypt(cur->req.req, cur->sg, cur->sgout, bs + (enc ? 0 : authsize), iv); @@ -432,7 +444,7 @@ static void test_mb_aead_speed(const char *algo, int enc, int secs, out: for (i = 0; i < num_mb; ++i) - aead_request_free(data[i].req); + aead_request_free(data[i].req.req); out_free_xoutbuf: for (i = 0; i < num_mb; ++i) testmgr_free_buf(data[i].xoutbuf); @@ -450,9 +462,10 @@ static void test_mb_aead_speed(const char *algo, int enc, int secs, kfree(iv); } -static int test_aead_jiffies(struct aead_request *req, int enc, +static int test_aead_jiffies(struct tcrypt_aead_request *treq, int enc, int blen, int secs) { + struct aead_request *req = treq->req; unsigned long start, end; int bcount; int ret; @@ -460,9 +473,9 @@ static int test_aead_jiffies(struct aead_request *req, int enc, for (start = jiffies, end = start + secs * HZ, bcount = 0; time_before(jiffies, end); bcount++) { if (enc) - ret = do_one_aead_op(req, crypto_aead_encrypt(req)); + ret = do_one_aead_op(treq, crypto_aead_encrypt(req)); else - ret = do_one_aead_op(req, crypto_aead_decrypt(req)); + ret = do_one_aead_op(treq, crypto_aead_decrypt(req)); if (ret) return ret; @@ -473,8 +486,9 @@ static int test_aead_jiffies(struct aead_request *req, int enc, return 0; } -static int test_aead_cycles(struct aead_request *req, int enc, int blen) +static int test_aead_cycles(struct tcrypt_aead_request *treq, int enc, int blen) { + struct aead_request *req = treq->req; unsigned long cycles = 0; int ret = 0; int i; @@ -482,9 +496,9 @@ static int test_aead_cycles(struct aead_request *req, int enc, int blen) /* Warm-up run. */ for (i = 0; i < 4; i++) { if (enc) - ret = do_one_aead_op(req, crypto_aead_encrypt(req)); + ret = do_one_aead_op(treq, crypto_aead_encrypt(req)); else - ret = do_one_aead_op(req, crypto_aead_decrypt(req)); + ret = do_one_aead_op(treq, crypto_aead_decrypt(req)); if (ret) goto out; @@ -496,9 +510,9 @@ static int test_aead_cycles(struct aead_request *req, int enc, int blen) start = get_cycles(); if (enc) - ret = do_one_aead_op(req, crypto_aead_encrypt(req)); + ret = do_one_aead_op(treq, crypto_aead_encrypt(req)); else - ret = do_one_aead_op(req, crypto_aead_decrypt(req)); + ret = do_one_aead_op(treq, crypto_aead_decrypt(req)); end = get_cycles(); if (ret) @@ -520,6 +534,7 @@ static void test_aead_speed(const char *algo, int enc, unsigned int secs, unsigned int tcount, u8 authsize, unsigned int aad_size, u8 *keysize) { + struct tcrypt_aead_request treq; unsigned int i, j; struct crypto_aead *tfm; int ret = -ENOMEM; @@ -535,7 +550,6 @@ static void test_aead_speed(const char *algo, int enc, unsigned int secs, char *axbuf[XBUFSIZE]; const int *b_size; unsigned int iv_len; - struct crypto_wait wait; iv = kzalloc(MAX_IVLEN, GFP_KERNEL); if (!iv) @@ -577,7 +591,7 @@ static void test_aead_speed(const char *algo, int enc, unsigned int secs, goto out_noreq; } - crypto_init_wait(&wait); + crypto_init_wait(&treq.wait); pr_info("testing speed of %s (%s) %s\n", algo, get_driver_name(crypto_aead, tfm), e); @@ -587,9 +601,10 @@ static void test_aead_speed(const char *algo, int enc, unsigned int secs, algo); goto out_noreq; } + treq.req = req; aead_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG, - crypto_req_done, &wait); + crypto_req_done, &treq.wait); i = 0; do { @@ -650,7 +665,7 @@ static void test_aead_speed(const char *algo, int enc, unsigned int secs, */ aead_request_set_crypt(req, sgout, sg, bs, iv); - ret = do_one_aead_op(req, + ret = do_one_aead_op(&treq, crypto_aead_encrypt(req)); if (ret) { @@ -665,11 +680,11 @@ static void test_aead_speed(const char *algo, int enc, unsigned int secs, iv); if (secs) { - ret = test_aead_jiffies(req, enc, bs, + ret = test_aead_jiffies(&treq, enc, bs, secs); cond_resched(); } else { - ret = test_aead_cycles(req, enc, bs); + ret = test_aead_cycles(&treq, enc, bs); } if (ret) { @@ -709,23 +724,22 @@ static void test_hash_sg_init(struct scatterlist *sg) } } -static inline int do_one_ahash_op(struct ahash_request *req, int ret) +static inline int do_one_ahash_op(struct tcrypt_ahash_request *treq, int ret) { - struct crypto_wait *wait = req->base.data; - - return crypto_wait_req(ret, wait); + return crypto_wait_req(ret, &treq->wait); } -static int test_ahash_jiffies_digest(struct ahash_request *req, int blen, - char *out, int secs) +static int test_ahash_jiffies_digest(struct tcrypt_ahash_request *treq, + int blen, char *out, int secs) { + struct ahash_request *req = treq->req; unsigned long start, end; int bcount; int ret; for (start = jiffies, end = start + secs * HZ, bcount = 0; time_before(jiffies, end); bcount++) { - ret = do_one_ahash_op(req, crypto_ahash_digest(req)); + ret = do_one_ahash_op(treq, crypto_ahash_digest(req)); if (ret) return ret; } @@ -736,28 +750,29 @@ static int test_ahash_jiffies_digest(struct ahash_request *req, int blen, return 0; } -static int test_ahash_jiffies(struct ahash_request *req, int blen, +static int test_ahash_jiffies(struct tcrypt_ahash_request *treq, int blen, int plen, char *out, int secs) { + struct ahash_request *req = treq->req; unsigned long start, end; int bcount, pcount; int ret; if (plen == blen) - return test_ahash_jiffies_digest(req, blen, out, secs); + return test_ahash_jiffies_digest(treq, blen, out, secs); for (start = jiffies, end = start + secs * HZ, bcount = 0; time_before(jiffies, end); bcount++) { - ret = do_one_ahash_op(req, crypto_ahash_init(req)); + ret = do_one_ahash_op(treq, crypto_ahash_init(req)); if (ret) return ret; for (pcount = 0; pcount < blen; pcount += plen) { - ret = do_one_ahash_op(req, crypto_ahash_update(req)); + ret = do_one_ahash_op(treq, crypto_ahash_update(req)); if (ret) return ret; } /* we assume there is enough space in 'out' for the result */ - ret = do_one_ahash_op(req, crypto_ahash_final(req)); + ret = do_one_ahash_op(treq, crypto_ahash_final(req)); if (ret) return ret; } @@ -768,15 +783,16 @@ static int test_ahash_jiffies(struct ahash_request *req, int blen, return 0; } -static int test_ahash_cycles_digest(struct ahash_request *req, int blen, - char *out) +static int test_ahash_cycles_digest(struct tcrypt_ahash_request *treq, + int blen, char *out) { + struct ahash_request *req = treq->req; unsigned long cycles = 0; int ret, i; /* Warm-up run. */ for (i = 0; i < 4; i++) { - ret = do_one_ahash_op(req, crypto_ahash_digest(req)); + ret = do_one_ahash_op(treq, crypto_ahash_digest(req)); if (ret) goto out; } @@ -787,7 +803,7 @@ static int test_ahash_cycles_digest(struct ahash_request *req, int blen, start = get_cycles(); - ret = do_one_ahash_op(req, crypto_ahash_digest(req)); + ret = do_one_ahash_op(treq, crypto_ahash_digest(req)); if (ret) goto out; @@ -806,26 +822,27 @@ static int test_ahash_cycles_digest(struct ahash_request *req, int blen, return 0; } -static int test_ahash_cycles(struct ahash_request *req, int blen, +static int test_ahash_cycles(struct tcrypt_ahash_request *treq, int blen, int plen, char *out) { + struct ahash_request *req = treq->req; unsigned long cycles = 0; int i, pcount, ret; if (plen == blen) - return test_ahash_cycles_digest(req, blen, out); + return test_ahash_cycles_digest(treq, blen, out); /* Warm-up run. */ for (i = 0; i < 4; i++) { - ret = do_one_ahash_op(req, crypto_ahash_init(req)); + ret = do_one_ahash_op(treq, crypto_ahash_init(req)); if (ret) goto out; for (pcount = 0; pcount < blen; pcount += plen) { - ret = do_one_ahash_op(req, crypto_ahash_update(req)); + ret = do_one_ahash_op(treq, crypto_ahash_update(req)); if (ret) goto out; } - ret = do_one_ahash_op(req, crypto_ahash_final(req)); + ret = do_one_ahash_op(treq, crypto_ahash_final(req)); if (ret) goto out; } @@ -836,15 +853,15 @@ static int test_ahash_cycles(struct ahash_request *req, int blen, start = get_cycles(); - ret = do_one_ahash_op(req, crypto_ahash_init(req)); + ret = do_one_ahash_op(treq, crypto_ahash_init(req)); if (ret) goto out; for (pcount = 0; pcount < blen; pcount += plen) { - ret = do_one_ahash_op(req, crypto_ahash_update(req)); + ret = do_one_ahash_op(treq, crypto_ahash_update(req)); if (ret) goto out; } - ret = do_one_ahash_op(req, crypto_ahash_final(req)); + ret = do_one_ahash_op(treq, crypto_ahash_final(req)); if (ret) goto out; @@ -867,7 +884,7 @@ static void test_ahash_speed_common(const char *algo, unsigned int secs, struct hash_speed *speed, unsigned mask) { struct scatterlist sg[TVMEMSIZE]; - struct crypto_wait wait; + struct tcrypt_ahash_request treq; struct ahash_request *req; struct crypto_ahash *tfm; char *output; @@ -896,9 +913,10 @@ static void test_ahash_speed_common(const char *algo, unsigned int secs, goto out; } - crypto_init_wait(&wait); + treq.req = req; + crypto_init_wait(&treq.wait); ahash_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG, - crypto_req_done, &wait); + crypto_req_done, &treq.wait); output = kmalloc(MAX_DIGEST_SIZE, GFP_KERNEL); if (!output) @@ -927,11 +945,11 @@ static void test_ahash_speed_common(const char *algo, unsigned int secs, ahash_request_set_crypt(req, sg, output, speed[i].plen); if (secs) { - ret = test_ahash_jiffies(req, speed[i].blen, + ret = test_ahash_jiffies(&treq, speed[i].blen, speed[i].plen, output, secs); cond_resched(); } else { - ret = test_ahash_cycles(req, speed[i].blen, + ret = test_ahash_cycles(&treq, speed[i].blen, speed[i].plen, output); } @@ -1217,16 +1235,16 @@ static void test_mb_skcipher_speed(const char *algo, int enc, int secs, kfree(data); } -static inline int do_one_acipher_op(struct skcipher_request *req, int ret) +static inline int do_one_acipher_op(struct tcrypt_skcipher_request *req, + int ret) { - struct crypto_wait *wait = req->base.data; - - return crypto_wait_req(ret, wait); + return crypto_wait_req(ret, &req->wait); } -static int test_acipher_jiffies(struct skcipher_request *req, int enc, +static int test_acipher_jiffies(struct tcrypt_skcipher_request *treq, int enc, int blen, int secs) { + struct skcipher_request *req = treq->req; unsigned long start, end; int bcount; int ret; @@ -1234,10 +1252,10 @@ static int test_acipher_jiffies(struct skcipher_request *req, int enc, for (start = jiffies, end = start + secs * HZ, bcount = 0; time_before(jiffies, end); bcount++) { if (enc) - ret = do_one_acipher_op(req, + ret = do_one_acipher_op(treq, crypto_skcipher_encrypt(req)); else - ret = do_one_acipher_op(req, + ret = do_one_acipher_op(treq, crypto_skcipher_decrypt(req)); if (ret) @@ -1249,9 +1267,10 @@ static int test_acipher_jiffies(struct skcipher_request *req, int enc, return 0; } -static int test_acipher_cycles(struct skcipher_request *req, int enc, +static int test_acipher_cycles(struct tcrypt_skcipher_request *treq, int enc, int blen) { + struct skcipher_request *req = treq->req; unsigned long cycles = 0; int ret = 0; int i; @@ -1259,10 +1278,10 @@ static int test_acipher_cycles(struct skcipher_request *req, int enc, /* Warm-up run. */ for (i = 0; i < 4; i++) { if (enc) - ret = do_one_acipher_op(req, + ret = do_one_acipher_op(treq, crypto_skcipher_encrypt(req)); else - ret = do_one_acipher_op(req, + ret = do_one_acipher_op(treq, crypto_skcipher_decrypt(req)); if (ret) @@ -1275,10 +1294,10 @@ static int test_acipher_cycles(struct skcipher_request *req, int enc, start = get_cycles(); if (enc) - ret = do_one_acipher_op(req, + ret = do_one_acipher_op(treq, crypto_skcipher_encrypt(req)); else - ret = do_one_acipher_op(req, + ret = do_one_acipher_op(treq, crypto_skcipher_decrypt(req)); end = get_cycles(); @@ -1300,8 +1319,8 @@ static void test_skcipher_speed(const char *algo, int enc, unsigned int secs, struct cipher_speed_template *template, unsigned int tcount, u8 *keysize, bool async) { + struct tcrypt_skcipher_request treq; unsigned int ret, i, j, k, iv_len; - struct crypto_wait wait; const char *key; char iv[128]; struct skcipher_request *req; @@ -1314,7 +1333,7 @@ static void test_skcipher_speed(const char *algo, int enc, unsigned int secs, else e = "decryption"; - crypto_init_wait(&wait); + crypto_init_wait(&treq.wait); tfm = crypto_alloc_skcipher(algo, 0, async ? 0 : CRYPTO_ALG_ASYNC); @@ -1333,8 +1352,9 @@ static void test_skcipher_speed(const char *algo, int enc, unsigned int secs, goto out; } + treq.req = req; skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG, - crypto_req_done, &wait); + crypto_req_done, &treq.wait); i = 0; do { @@ -1401,11 +1421,11 @@ static void test_skcipher_speed(const char *algo, int enc, unsigned int secs, skcipher_request_set_crypt(req, sg, sg, bs, iv); if (secs) { - ret = test_acipher_jiffies(req, enc, + ret = test_acipher_jiffies(&treq, enc, bs, secs); cond_resched(); } else { - ret = test_acipher_cycles(req, enc, + ret = test_acipher_cycles(&treq, enc, bs); } diff --git a/drivers/accel/amdxdna/aie2_ctx.c b/drivers/accel/amdxdna/aie2_ctx.c index baf9a8b90a4d..d927c8c9d557 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 @@ -99,9 +100,9 @@ static void aie2_job_put(struct amdxdna_sched_job *job) 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); - drm_sched_start(&hwctx->priv->sched, 0); + drm_sched_start(hwctx->priv->sched, 0); } static int aie2_hwctx_restart(struct amdxdna_dev *xdna, struct amdxdna_hwctx *hwctx) @@ -659,10 +660,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->aie.xdna; const struct drm_sched_init_args args = { .ops = &sched_ops, .num_rqs = DRM_SCHED_PRIORITY_COUNT, @@ -673,7 +683,55 @@ 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; int i, ret; @@ -683,13 +741,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 = xa_load(&client->dev_heap_xa, 0); 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); @@ -722,30 +793,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_locked(xdna); @@ -791,19 +848,20 @@ 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]) continue; + amdxdna_gem_heap_free(client, priv->cmd_buf[i]); drm_gem_object_put(to_gobj(priv->cmd_buf[i])); } 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; @@ -811,18 +869,20 @@ int aie2_hwctx_init(struct amdxdna_hwctx *hwctx) void aie2_hwctx_fini(struct amdxdna_hwctx *hwctx) { + struct amdxdna_dev_hdl *ndev; struct amdxdna_dev *xdna; int idx; xdna = hwctx->client->xdna; + ndev = xdna->dev_handle; XDNA_DBG(xdna, "%s sequence number %lld", hwctx->name, hwctx->priv->seq); 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); - 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); @@ -833,11 +893,17 @@ 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++) + for (idx = 0; idx < ARRAY_SIZE(hwctx->priv->cmd_buf); idx++) { + /* + * The open/close will never be called for driver allocated + * dev bo. Call amdxdna_gem_heap_free explicitly. + */ + amdxdna_gem_heap_free(hwctx->client, hwctx->priv->cmd_buf[idx]); drm_gem_object_put(to_gobj(hwctx->priv->cmd_buf[idx])); + } amdxdna_gem_unpin(hwctx->priv->heap); drm_gem_object_put(to_gobj(hwctx->priv->heap)); diff --git a/drivers/accel/amdxdna/aie2_pci.c b/drivers/accel/amdxdna/aie2_pci.c index daec1f6b4907..7a4314ca843b 100644 --- a/drivers/accel/amdxdna/aie2_pci.c +++ b/drivers/accel/amdxdna/aie2_pci.c @@ -503,10 +503,16 @@ static int aie2_init(struct amdxdna_dev *xdna) ndev->priv = xdna->dev_info->dev_priv; ndev->aie.xdna = xdna; + ret = aie2_hwctx_sched_init(ndev); + if (ret) + return ret; + for (i = 0; i < ARRAY_SIZE(npu_fw); i++) { fw_full_path = kasprintf(GFP_KERNEL, "%s%s", ndev->priv->fw_path, npu_fw[i]); - if (!fw_full_path) - return -ENOMEM; + if (!fw_full_path) { + ret = -ENOMEM; + goto free_hwctx_sched; + } ret = firmware_request_nowarn(&fw, fw_full_path, &pdev->dev); kfree(fw_full_path); @@ -519,7 +525,7 @@ static int aie2_init(struct amdxdna_dev *xdna) 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); @@ -623,6 +629,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; } @@ -631,6 +639,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 ea1dac106400..2c7019bd26b5 100644 --- a/drivers/accel/amdxdna/aie2_pci.h +++ b/drivers/accel/amdxdna/aie2_pci.h @@ -107,7 +107,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 */ @@ -152,6 +152,8 @@ struct amdxdna_dev_hdl { u32 total_col; struct amdxdna_drm_query_aie_version version; struct aie2_exec_msg_ops *exec_msg_ops; + struct drm_gpu_scheduler *hwctx_sched; + struct ida hwctx_sched_ida; /* power management and clock*/ enum amdxdna_power_mode_type pw_mode; @@ -294,6 +296,8 @@ int aie2_update_prop_time_quota(struct amdxdna_dev_hdl *ndev, u32 us); /* 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); int aie2_hwctx_sync_debug_bo(struct amdxdna_hwctx *hwctx, u32 debug_bo_hdl); void aie2_hwctx_suspend(struct amdxdna_client *client); diff --git a/drivers/accel/amdxdna/amdxdna_gem.c b/drivers/accel/amdxdna/amdxdna_gem.c index 4b0d58d0329b..f14484bc31ec 100644 --- a/drivers/accel/amdxdna/amdxdna_gem.c +++ b/drivers/accel/amdxdna/amdxdna_gem.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include "amdxdna_cbuf.h" @@ -37,6 +38,7 @@ amdxdna_init_dev_bo(struct amdxdna_gem_obj *dev_bo) struct amdxdna_gem_obj *heap; u64 heap_addr, exp_heap_uva; u32 heap_id; + int ret; if (xa_empty(&client->dev_heap_xa)) { XDNA_DBG(xdna, "Empty heap xa"); @@ -58,24 +60,32 @@ amdxdna_init_dev_bo(struct amdxdna_gem_obj *dev_bo) heap = xa_load(&client->dev_heap_xa, heap_id); exp_heap_uva = amdxdna_gem_uva(heap); heap_addr = amdxdna_gem_dev_addr(heap); - dev_bo->heap_start_id = heap_id; dev_bo->mem.uva = dev_bo->mm_node.start - heap_addr + exp_heap_uva; for (; heap_id < client->dev_heap_nid; heap_id++) { heap = xa_load(&client->dev_heap_xa, heap_id); if (!heap) { XDNA_ERR(xdna, "Failed to load heap %d", heap_id); - return -EINVAL; + ret = -EINVAL; + goto cleanup_heap_xa; } heap_addr = amdxdna_gem_uva(heap); if (heap_addr == AMDXDNA_INVALID_ADDR) { XDNA_ERR(xdna, "Heap %d is not mapped", heap_id); - return -EAGAIN; + ret = -EAGAIN; + goto cleanup_heap_xa; } if (heap_addr != exp_heap_uva) { XDNA_ERR(xdna, "Heap %d uva is not contiguous", heap_id); - return -EINVAL; + ret = -EINVAL; + goto cleanup_heap_xa; + } + + ret = xa_insert(&dev_bo->heap_xa, heap_id, heap, GFP_KERNEL); + if (ret) { + ret = -ENOMEM; + goto cleanup_heap_xa; } if (heap->dev_addr + heap->mem.size >= @@ -87,12 +97,15 @@ amdxdna_init_dev_bo(struct amdxdna_gem_obj *dev_bo) if (heap_id == client->dev_heap_nid) { XDNA_DBG(xdna, "Can not find heap end"); - return -EAGAIN; + ret = -EAGAIN; + goto cleanup_heap_xa; } - dev_bo->heap_end_id = heap_id; - return 0; + +cleanup_heap_xa: + xa_destroy(&dev_bo->heap_xa); + return ret; } static int @@ -132,8 +145,7 @@ amdxdna_gem_heap_alloc(struct amdxdna_gem_obj *abo) } client->heap_usage += mem->size; - xa_for_each_range(&client->dev_heap_xa, heap_id, heap, - abo->heap_start_id, abo->heap_end_id) + xa_for_each(&abo->heap_xa, heap_id, heap) drm_gem_object_get(to_gobj(heap)); unlock_out: @@ -142,48 +154,16 @@ amdxdna_gem_heap_alloc(struct amdxdna_gem_obj *abo) return ret; } -static void -amdxdna_gem_heap_free(struct amdxdna_gem_obj *abo) +void amdxdna_gem_heap_free(struct amdxdna_client *client, struct amdxdna_gem_obj *abo) { - struct amdxdna_client *client = abo->client; - struct amdxdna_gem_obj *heap; - unsigned long heap_id; - mutex_lock(&client->mm_lock); drm_mm_remove_node(&abo->mm_node); client->heap_usage -= abo->mem.size; - xa_for_each_range(&client->dev_heap_xa, heap_id, heap, - abo->heap_start_id, abo->heap_end_id) - drm_gem_object_put(to_gobj(heap)); - mutex_unlock(&client->mm_lock); } -static struct amdxdna_gem_obj * -amdxdna_gem_create_obj(struct drm_device *dev, size_t size) -{ - struct amdxdna_gem_obj *abo; - - abo = kzalloc_obj(*abo); - if (!abo) - return ERR_PTR(-ENOMEM); - - abo->pinned = false; - abo->assigned_hwctx = AMDXDNA_INVALID_CTX_HANDLE; - mutex_init(&abo->lock); - - abo->mem.dma_addr = AMDXDNA_INVALID_ADDR; - abo->mem.uva = AMDXDNA_INVALID_ADDR; - abo->mem.size = size; - abo->open_ref = 0; - abo->internal = false; - INIT_LIST_HEAD(&abo->mem.umap_list); - - return abo; -} - static void amdxdna_gem_destroy_obj(struct amdxdna_gem_obj *abo) { @@ -253,13 +233,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; @@ -271,10 +254,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); } @@ -301,33 +282,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.uva = 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); } @@ -339,10 +329,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, @@ -387,6 +377,21 @@ static int amdxdna_hmm_register(struct amdxdna_gem_obj *abo, goto free_map; } + mapp->range.notifier = &mapp->notifier; + mapp->range.start = vma->vm_start; + mapp->range.end = vma->vm_end; + /* + * Access permissions are fixed at mmap() time. Changing them later + * with mprotect() is not supported: the range keeps requesting the + * original permissions, so the application may see a fault failure + * or an IOMMU fault. + */ + mapp->range.default_flags = HMM_PFN_REQ_FAULT; + if (vma->vm_flags & VM_WRITE) + mapp->range.default_flags |= HMM_PFN_REQ_WRITE; + mapp->abo = abo; + kref_init(&mapp->refcnt); + ret = mmu_interval_notifier_insert_locked(&mapp->notifier, current->mm, addr, @@ -397,15 +402,6 @@ static int amdxdna_hmm_register(struct amdxdna_gem_obj *abo, goto free_pfns; } - mapp->range.notifier = &mapp->notifier; - mapp->range.start = vma->vm_start; - mapp->range.end = vma->vm_end; - mapp->range.default_flags = HMM_PFN_REQ_FAULT; - mapp->abo = abo; - kref_init(&mapp->refcnt); - - INIT_WORK(&mapp->hmm_unreg_work, amdxdna_hmm_unreg_work); - down_write(&xdna->notifier_lock); if (list_empty(&abo->mem.umap_list)) abo->mem.uva = addr; @@ -421,17 +417,47 @@ static int amdxdna_hmm_register(struct amdxdna_gem_obj *abo, return ret; } +static struct amdxdna_gem_obj * +amdxdna_gem_create_obj(struct drm_device *dev, size_t size) +{ + struct amdxdna_gem_obj *abo; + + abo = kzalloc_obj(*abo); + if (!abo) + return ERR_PTR(-ENOMEM); + + abo->pinned = false; + abo->assigned_hwctx = AMDXDNA_INVALID_CTX_HANDLE; + mutex_init(&abo->lock); + + abo->mem.dma_addr = AMDXDNA_INVALID_ADDR; + abo->mem.uva = AMDXDNA_INVALID_ADDR; + abo->mem.size = size; + abo->open_ref = 0; + abo->internal = false; + INIT_LIST_HEAD(&abo->mem.umap_list); + xa_init_flags(&abo->heap_xa, XA_FLAGS_ALLOC); + INIT_WORK(&abo->hmm_unreg_work, amdxdna_hmm_unreg_work); + + return abo; +} + static void amdxdna_gem_dev_obj_free(struct drm_gem_object *gobj) { struct amdxdna_dev *xdna = to_xdna_dev(gobj->dev); struct amdxdna_gem_obj *abo = to_xdna_obj(gobj); + struct amdxdna_gem_obj *heap; + unsigned long heap_id; XDNA_DBG(xdna, "BO type %d xdna_addr 0x%llx", abo->type, amdxdna_gem_dev_addr(abo)); if (abo->pinned) amdxdna_gem_unpin(abo); amdxdna_gem_vunmap(abo); - amdxdna_gem_heap_free(abo); + xa_for_each(&abo->heap_xa, heap_id, heap) + drm_gem_object_put(to_gobj(heap)); + xa_destroy(&abo->heap_xa); + drm_gem_object_release(gobj); amdxdna_gem_destroy_obj(abo); } @@ -458,16 +484,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); @@ -476,23 +502,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; } @@ -504,6 +535,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; @@ -514,9 +549,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: @@ -524,14 +556,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 = linear_page_delta(vma, vmf->address); + + 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); @@ -541,16 +658,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; @@ -609,10 +719,8 @@ amdxdna_gem_skip_bo_usage(struct amdxdna_gem_obj *abo) } static void -amdxdna_gem_add_bo_usage(struct amdxdna_gem_obj *abo) +amdxdna_gem_add_bo_usage(struct amdxdna_client *client, struct amdxdna_gem_obj *abo) { - struct amdxdna_client *client = abo->client; - if (amdxdna_gem_skip_bo_usage(abo)) return; @@ -624,10 +732,8 @@ amdxdna_gem_add_bo_usage(struct amdxdna_gem_obj *abo) } static void -amdxdna_gem_del_bo_usage(struct amdxdna_gem_obj *abo) +amdxdna_gem_del_bo_usage(struct amdxdna_client *client, struct amdxdna_gem_obj *abo) { - struct amdxdna_client *client = abo->client; - if (amdxdna_gem_skip_bo_usage(abo)) return; @@ -643,8 +749,9 @@ static void amdxdna_gem_obj_free(struct drm_gem_object *gobj) struct amdxdna_dev *xdna = to_xdna_dev(gobj->dev); struct amdxdna_gem_obj *abo = to_xdna_obj(gobj); - 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); @@ -663,12 +770,20 @@ static int amdxdna_gem_obj_open(struct drm_gem_object *gobj, struct drm_file *fi { struct amdxdna_dev *xdna = to_xdna_dev(gobj->dev); struct amdxdna_gem_obj *abo = to_xdna_obj(gobj); + struct amdxdna_client *client; int ret; - guard(mutex)(&abo->lock); + mutex_lock(&abo->lock); + if (abo->open_ref > 0 && filp->driver_priv != abo->client) { + mutex_unlock(&abo->lock); + return -EPERM; + } + abo->open_ref++; - if (abo->open_ref > 1) + if (abo->open_ref > 1) { + mutex_unlock(&abo->lock); return 0; + } /* Attached to the client when first opened by it. */ abo->client = filp->driver_priv; @@ -679,26 +794,34 @@ static int amdxdna_gem_obj_open(struct drm_gem_object *gobj, struct drm_file *fi if (ret) { abo->open_ref--; abo->client = NULL; + mutex_unlock(&abo->lock); return ret; } } + client = abo->client; + mutex_unlock(&abo->lock); - amdxdna_gem_add_bo_usage(abo); + amdxdna_gem_add_bo_usage(client, abo); return 0; } static void amdxdna_gem_obj_close(struct drm_gem_object *gobj, struct drm_file *filp) { struct amdxdna_gem_obj *abo = to_xdna_obj(gobj); + struct amdxdna_client *client = NULL; - guard(mutex)(&abo->lock); + mutex_lock(&abo->lock); abo->open_ref--; if (abo->open_ref == 0) { - amdxdna_gem_del_bo_usage(abo); /* Detach from the client when last closed by it. */ + client = abo->client; abo->client = NULL; } + mutex_unlock(&abo->lock); + + if (client) + amdxdna_gem_del_bo_usage(client, abo); } static int amdxdna_gem_obj_vmap(struct drm_gem_object *obj, struct iosys_map *map) @@ -734,19 +857,72 @@ static void amdxdna_gem_obj_vunmap(struct drm_gem_object *obj, struct iosys_map drm_gem_shmem_object_vunmap(obj, map); } +static int amdxdna_gem_dev_obj_open(struct drm_gem_object *gobj, struct drm_file *filp) +{ + struct amdxdna_gem_obj *abo = to_xdna_obj(gobj); + + guard(mutex)(&abo->lock); + if (filp->driver_priv != abo->client) + return -EPERM; + abo->open_ref++; + + return 0; +} + +static void amdxdna_gem_dev_obj_close(struct drm_gem_object *gobj, struct drm_file *filp) +{ + struct amdxdna_gem_obj *abo = to_xdna_obj(gobj); + struct amdxdna_client *client = NULL; + + mutex_lock(&abo->lock); + abo->open_ref--; + + /* + * Freeing the heap allocation here, when the handle is closed, is + * intentional. DEV BOs are carved out of a per-client drm_mm heap; + * any subsequent allocation that lands on the same device address will + * also belong to the same client. If the user closes the handle while + * a job is still in flight the only consequence is self-inflicted + * corruption within their own context -- it cannot affect other + * processes. The GEM reference held by the in-flight job keeps the + * amdxdna_gem_obj struct alive until the job completes; it does not + * prevent the device address from being reclaimed by the allocator. + * + * Cross-process handle creation for DEV BOs is rejected in + * amdxdna_gem_dev_obj_open(), which prevents the following UAF: + * if a second process shared the handle via GEM flink and the + * original creator exited (freeing client), the importer would later + * reach open_ref == 0 here and call amdxdna_gem_heap_free() with a + * dangling abo->client pointer. Because cross-process opens are + * rejected, the process arriving here is always the owning client, + * which is still alive. abo->client is nulled out afterwards so that + * any code path running on a lingering GEM reference (e.g. an + * in-flight job) cannot silently dereference a stale pointer. + */ + if (abo->open_ref == 0) { + client = abo->client; + abo->client = NULL; + } + mutex_unlock(&abo->lock); + + if (client) + amdxdna_gem_heap_free(client, abo); +} + static int amdxdna_gem_dev_obj_vmap(struct drm_gem_object *obj, struct iosys_map *map) { struct amdxdna_gem_obj *abo = to_xdna_obj(obj); struct amdxdna_gem_obj *heap; + unsigned long index = 0; void *base; u64 offset; - /* vmap dev bo which is across more than 1 heap is not allowed */ - if (abo->heap_start_id != abo->heap_end_id) + heap = xa_find(&abo->heap_xa, &index, ULONG_MAX, XA_PRESENT); + if (!heap) return -ENOMEM; - heap = xa_load(&abo->client->dev_heap_xa, abo->heap_start_id); - if (!heap) + /* vmap dev bo which is across more than 1 heap is not allowed */ + if (xa_find_after(&abo->heap_xa, &index, ULONG_MAX, XA_PRESENT)) return -ENOMEM; base = amdxdna_gem_vmap(heap); @@ -765,6 +941,8 @@ static struct dma_buf *amdxdna_gem_dev_obj_export(struct drm_gem_object *gobj, i static const struct drm_gem_object_funcs amdxdna_gem_dev_obj_funcs = { .free = amdxdna_gem_dev_obj_free, + .open = amdxdna_gem_dev_obj_open, + .close = amdxdna_gem_dev_obj_close, .vmap = amdxdna_gem_dev_obj_vmap, .export = amdxdna_gem_dev_obj_export, }; @@ -780,7 +958,7 @@ static const struct drm_gem_object_funcs amdxdna_gem_shmem_funcs = { .vmap = amdxdna_gem_obj_vmap, .vunmap = amdxdna_gem_obj_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, }; @@ -962,6 +1140,11 @@ amdxdna_drm_create_dev_heap_bo(struct drm_device *dev, struct amdxdna_gem_obj *abo; int ret; + if (!xdna->dev_info->dev_mem_size) { + XDNA_DBG(xdna, "Device heap is not supported"); + return ERR_PTR(-EOPNOTSUPP); + } + WARN_ON(!is_power_of_2(xdna->dev_info->dev_mem_size)); XDNA_DBG(xdna, "Requested dev heap size 0x%llx", args->size); if (!args->size || !IS_ALIGNED(args->size, xdna->dev_info->dev_mem_size)) { @@ -1103,6 +1286,8 @@ int amdxdna_drm_create_bo_ioctl(struct drm_device *dev, void *data, struct drm_f args->handle, args->type, amdxdna_gem_uva(abo), amdxdna_gem_dev_addr(abo), abo->mem.size); put_obj: + if (ret && abo->type == AMDXDNA_BO_DEV) + amdxdna_gem_heap_free(client, abo); /* Dereference object reference. Handle holds it now. */ drm_gem_object_put(to_gobj(abo)); return ret; @@ -1136,7 +1321,6 @@ static void amdxdna_bo_unpin(struct amdxdna_gem_obj *abo) int amdxdna_gem_pin_nolock(struct amdxdna_gem_obj *abo) { - struct amdxdna_client *client = abo->client; struct amdxdna_gem_obj *heap; unsigned long heap_id, last = ULONG_MAX; int ret = 0; @@ -1144,17 +1328,15 @@ int amdxdna_gem_pin_nolock(struct amdxdna_gem_obj *abo) if (abo->type != AMDXDNA_BO_DEV) return amdxdna_bo_pin(abo); - xa_for_each_range(&client->dev_heap_xa, heap_id, heap, - abo->heap_start_id, abo->heap_end_id) { + xa_for_each(&abo->heap_xa, heap_id, heap) { ret = amdxdna_bo_pin(heap); if (ret) break; last = heap_id; } - if (ret && last <= abo->heap_end_id) { - xa_for_each_range(&client->dev_heap_xa, heap_id, heap, - abo->heap_start_id, last) + if (ret && last != ULONG_MAX) { + xa_for_each_range(&abo->heap_xa, heap_id, heap, 0, last) amdxdna_bo_unpin(heap); } @@ -1179,8 +1361,7 @@ void amdxdna_gem_unpin(struct amdxdna_gem_obj *abo) struct amdxdna_gem_obj *heap; unsigned long heap_id; - xa_for_each_range(&abo->client->dev_heap_xa, heap_id, heap, - abo->heap_start_id, abo->heap_end_id) + xa_for_each(&abo->heap_xa, heap_id, heap) amdxdna_bo_unpin(heap); } else { amdxdna_bo_unpin(abo); @@ -1300,8 +1481,7 @@ int amdxdna_drm_sync_bo_ioctl(struct drm_device *dev, u64 flush_start = bo_start + args->offset; u64 flush_end = flush_start + args->size; - xa_for_each_range(&client->dev_heap_xa, heap_id, heap, - abo->heap_start_id, abo->heap_end_id) { + xa_for_each(&abo->heap_xa, heap_id, heap) { u64 heap_start = amdxdna_gem_dev_addr(heap); u64 heap_end = heap_start + heap->mem.size; u64 start = max(flush_start, heap_start); @@ -1328,7 +1508,7 @@ int amdxdna_drm_sync_bo_ioctl(struct drm_device *dev, amdxdna_gem_unpin(abo); if (ret) { - drm_WARN(&xdna->ddev, 1, "Can not get flush memory"); + XDNA_DBG(xdna, "Flush BO %d failed, ret %d", args->handle, ret); goto put_obj; } } @@ -1336,7 +1516,8 @@ int amdxdna_drm_sync_bo_ioctl(struct drm_device *dev, XDNA_DBG(xdna, "Sync bo %d offset 0x%llx, size 0x%llx\n", args->handle, args->offset, args->size); - if (args->direction == SYNC_DIRECT_FROM_DEVICE) + if (abo->assigned_hwctx != AMDXDNA_INVALID_CTX_HANDLE && + args->direction == SYNC_DIRECT_FROM_DEVICE) ret = amdxdna_hwctx_sync_debug_bo(client, args->handle); put_obj: diff --git a/drivers/accel/amdxdna/amdxdna_gem.h b/drivers/accel/amdxdna/amdxdna_gem.h index 1e90e32bf3cd..9b4aa21a37c9 100644 --- a/drivers/accel/amdxdna/amdxdna_gem.h +++ b/drivers/accel/amdxdna/amdxdna_gem.h @@ -14,7 +14,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; @@ -43,11 +42,11 @@ struct amdxdna_gem_obj { struct mutex lock; /* Protects: pinned, mem.kva, open_ref */ struct amdxdna_mem mem; int open_ref; + struct work_struct hmm_unreg_work; /* Below members are initialized when needed */ struct drm_mm_node mm_node; /* For AMDXDNA_BO_DEV */ - u32 heap_start_id; - u32 heap_end_id; + struct xarray heap_xa; u64 dev_addr; /* For heap bo */ u32 assigned_hwctx; struct dma_buf *dma_buf; @@ -104,6 +103,7 @@ static inline u64 amdxdna_obj_dma_addr(struct amdxdna_gem_obj *abo) } void amdxdna_umap_put(struct amdxdna_umap *mapp); +void amdxdna_gem_heap_free(struct amdxdna_client *client, struct amdxdna_gem_obj *abo); struct drm_gem_object * amdxdna_gem_create_shmem_object_cb(struct drm_device *dev, size_t size); diff --git a/drivers/accel/ethosu/ethosu_drv.c b/drivers/accel/ethosu/ethosu_drv.c index 8108622de258..4a24bbd2bb61 100644 --- a/drivers/accel/ethosu/ethosu_drv.c +++ b/drivers/accel/ethosu/ethosu_drv.c @@ -12,10 +12,10 @@ #include #include -#include #include #include #include +#include #include #include "ethosu_drv.h" diff --git a/drivers/accel/ivpu/ivpu_gem.c b/drivers/accel/ivpu/ivpu_gem.c index 4f2005a8d496..563eeffb5736 100644 --- a/drivers/accel/ivpu/ivpu_gem.c +++ b/drivers/accel/ivpu/ivpu_gem.c @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include "ivpu_drv.h" #include "ivpu_fw.h" diff --git a/drivers/accel/qaic/qaic_data.c b/drivers/accel/qaic/qaic_data.c index ef0351b6dc9b..ee35e13091b3 100644 --- a/drivers/accel/qaic/qaic_data.c +++ b/drivers/accel/qaic/qaic_data.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -455,7 +456,12 @@ static int create_sgt(struct qaic_device *qdev, struct sg_table **sgt_out, u64 s int order; if (size) { - nr_pages = DIV_ROUND_UP(size, PAGE_SIZE); + u64 nr_pages_u64 = DIV_ROUND_UP_ULL(size, PAGE_SIZE); + + if (overflows_type(nr_pages_u64, int)) + return -E2BIG; + + nr_pages = nr_pages_u64; /* * calculate how much extra we are going to allocate, to remove * later @@ -1834,15 +1840,16 @@ int qaic_perf_stats_bo_ioctl(struct drm_device *dev, void *data, struct drm_file goto free_ent; } bo = to_qaic_bo(obj); + ret = mutex_lock_interruptible(&bo->lock); + if (ret) + goto put_obj; if (!bo->sliced) { - drm_gem_object_put(obj); ret = -EINVAL; - goto free_ent; + goto unlock_bo; } if (bo->dbc->id != args->hdr.dbc_id) { - drm_gem_object_put(obj); ret = -EINVAL; - goto free_ent; + goto unlock_bo; } /* * perf stats ioctl is called before wait ioctl is complete then @@ -1858,7 +1865,12 @@ int qaic_perf_stats_bo_ioctl(struct drm_device *dev, void *data, struct drm_file bo->perf_stats.req_received_ts), 1000); ent[i].queue_level_before = bo->perf_stats.queue_level_before; ent[i].num_queue_element = bo->total_slice_nents; +unlock_bo: + mutex_unlock(&bo->lock); +put_obj: drm_gem_object_put(obj); + if (ret) + goto free_ent; } if (copy_to_user(u64_to_user_ptr(args->data), ent, args->hdr.count * sizeof(*ent))) diff --git a/drivers/accel/qaic/qaic_debugfs.c b/drivers/accel/qaic/qaic_debugfs.c index 95c78e12dd61..909a4d774d90 100644 --- a/drivers/accel/qaic/qaic_debugfs.c +++ b/drivers/accel/qaic/qaic_debugfs.c @@ -5,6 +5,7 @@ #include #include +#include #include #include #include diff --git a/drivers/accel/qaic/qaic_drv.c b/drivers/accel/qaic/qaic_drv.c index 0acf6cdd44f8..c1bb6db78d12 100644 --- a/drivers/accel/qaic/qaic_drv.c +++ b/drivers/accel/qaic/qaic_drv.c @@ -4,6 +4,7 @@ /* Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries. */ #include +#include #include #include #include diff --git a/drivers/accel/qaic/qaic_ras.c b/drivers/accel/qaic/qaic_ras.c index e0205c2cda3d..236e520f708f 100644 --- a/drivers/accel/qaic/qaic_ras.c +++ b/drivers/accel/qaic/qaic_ras.c @@ -5,6 +5,7 @@ #include #include +#include #include #include diff --git a/drivers/accel/qaic/qaic_ssr.c b/drivers/accel/qaic/qaic_ssr.c index a98928654959..418f14936f9a 100644 --- a/drivers/accel/qaic/qaic_ssr.c +++ b/drivers/accel/qaic/qaic_ssr.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include diff --git a/drivers/accel/qaic/qaic_timesync.c b/drivers/accel/qaic/qaic_timesync.c index 45e5f0728ebe..b5162677ccc4 100644 --- a/drivers/accel/qaic/qaic_timesync.c +++ b/drivers/accel/qaic/qaic_timesync.c @@ -2,6 +2,7 @@ /* Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries. */ +#include #include #include #include diff --git a/drivers/accel/qaic/sahara.c b/drivers/accel/qaic/sahara.c index 6333c45ef7d2..e951181e424f 100644 --- a/drivers/accel/qaic/sahara.c +++ b/drivers/accel/qaic/sahara.c @@ -3,6 +3,7 @@ /* Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries. */ #include +#include #include #include #include diff --git a/drivers/accel/rocket/rocket_gem.c b/drivers/accel/rocket/rocket_gem.c index a5fffa51ff35..d981c6a93ff1 100644 --- a/drivers/accel/rocket/rocket_gem.c +++ b/drivers/accel/rocket/rocket_gem.c @@ -3,7 +3,7 @@ #include #include -#include +#include #include #include #include diff --git a/drivers/accel/rocket/rocket_job.c b/drivers/accel/rocket/rocket_job.c index 4bc4f9c8ee40..088e41e40433 100644 --- a/drivers/accel/rocket/rocket_job.c +++ b/drivers/accel/rocket/rocket_job.c @@ -494,8 +494,6 @@ int rocket_job_init(struct rocket_core *core) return 0; err_sched: - drm_sched_fini(&core->sched); - destroy_workqueue(core->reset.wq); return ret; } diff --git a/drivers/acpi/acpi_extlog.c b/drivers/acpi/acpi_extlog.c index 7ad3b36013cc..9e61354a807b 100644 --- a/drivers/acpi/acpi_extlog.c +++ b/drivers/acpi/acpi_extlog.c @@ -134,22 +134,42 @@ static int print_extlog_rcd(const char *pfx, } static void extlog_print_pcie(struct cper_sec_pcie *pcie_err, - int severity) + int severity, u32 len) { -#ifdef ACPI_APEI_PCIEAER - struct aer_capability_regs *aer; +#ifdef CONFIG_ACPI_APEI_PCIEAER + struct aer_capability_regs aer_regs = {}; struct pci_dev *pdev; unsigned int devfn; unsigned int bus; int aer_severity; int domain; + if (len < sizeof(*pcie_err)) { + pr_warn_ratelimited(FW_WARN + "PCIe error section too small (%u)\n", len); + return; + } + if (!(pcie_err->validation_bits & CPER_PCIE_VALID_DEVICE_ID && pcie_err->validation_bits & CPER_PCIE_VALID_AER_INFO)) return; aer_severity = cper_severity_to_aer(severity); - aer = (struct aer_capability_regs *)pcie_err->aer_info; + + /* + * struct pcie_tlp_log is larger than the hardware layout, so aer_info + * only maps onto the struct up to the four Header Log DWORDs. Copy that + * much, then place the TLP Prefix Log from where the hardware keeps it. + * Everything else stays zero: nothing reads root_command, root_status or + * the error source IDs, and header_len and flit are software-only. + */ + memcpy(&aer_regs, pcie_err->aer_info, + offsetof(struct aer_capability_regs, header_log) + + PCIE_STD_NUM_TLP_HEADERLOG * sizeof(u32)); + memcpy(aer_regs.header_log.prefix, + pcie_err->aer_info + PCI_ERR_PREFIX_LOG, + sizeof(aer_regs.header_log.prefix)); + domain = pcie_err->device_id.segment; bus = pcie_err->device_id.bus; devfn = PCI_DEVFN(pcie_err->device_id.device, @@ -158,28 +178,11 @@ static void extlog_print_pcie(struct cper_sec_pcie *pcie_err, if (!pdev) return; - pci_print_aer(pdev, aer_severity, aer); + pci_print_aer(pdev, aer_severity, &aer_regs); pci_dev_put(pdev); #endif } -static void -extlog_cxl_cper_handle_prot_err(struct cxl_cper_sec_prot_err *prot_err, - int severity) -{ -#ifdef ACPI_APEI_PCIEAER - struct cxl_cper_prot_err_work_data wd; - - if (cxl_cper_sec_prot_err_valid(prot_err)) - return; - - if (cxl_cper_setup_prot_err_work_data(&wd, prot_err, severity)) - return; - - cxl_cper_handle_prot_err(&wd); -#endif -} - static int extlog_print(struct notifier_block *nb, unsigned long val, void *data) { @@ -208,6 +211,15 @@ static int extlog_print(struct notifier_block *nb, unsigned long val, tmp = (struct acpi_hest_generic_status *)elog_buf; + /* + * Bound the length before cper_estatus_check() walks the sections: it + * iterates over data_length, which is not yet known to fit elog_buf. + * cper_estatus_check_header() then rejects a length that wrapped, which + * the bound cannot see. + */ + if (cper_estatus_len(tmp) > ELOG_ENTRY_LEN || cper_estatus_check(tmp)) + return NOTIFY_DONE; + if (!ras_userspace_consumers()) { print_extlog_rcd(NULL, tmp, cpu); goto out; @@ -235,12 +247,14 @@ static int extlog_print(struct notifier_block *nb, unsigned long val, struct cxl_cper_sec_prot_err *prot_err = acpi_hest_get_payload(gdata); - extlog_cxl_cper_handle_prot_err(prot_err, - gdata->error_severity); + cxl_cper_post_prot_err(prot_err, + gdata->error_severity, + gdata->error_data_length); } else if (guid_equal(sec_type, &CPER_SEC_PCIE)) { struct cper_sec_pcie *pcie_err = acpi_hest_get_payload(gdata); - extlog_print_pcie(pcie_err, gdata->error_severity); + extlog_print_pcie(pcie_err, gdata->error_severity, + gdata->error_data_length); } else { void *err = acpi_hest_get_payload(gdata); diff --git a/drivers/acpi/acpi_pcc.c b/drivers/acpi/acpi_pcc.c index 438c67189511..57d13b25c1d6 100644 --- a/drivers/acpi/acpi_pcc.c +++ b/drivers/acpi/acpi_pcc.c @@ -28,6 +28,7 @@ * to PCC commands */ #define PCC_CMD_WAIT_RETRIES_NUM 500ULL +#define PCC_SIGNATURE_SIZE sizeof(u32) struct pcc_data { struct pcc_mbox_chan *pcc_chan; @@ -54,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_obj(*data); if (!data) return AE_NO_MEMORY; @@ -74,6 +88,14 @@ acpi_pcc_address_space_setup(acpi_handle region_handle, u32 function, } pcc_chan = data->pcc_chan; + if (pcc_chan->shmem_size < PCC_SIGNATURE_SIZE || + ctx->length > pcc_chan->shmem_size - PCC_SIGNATURE_SIZE) { + pr_err("PCC channel-%d shared memory is too small.\n", + ctx->subspace_id); + ret = AE_AML_REGION_LIMIT; + goto err_free_channel; + } + if (!pcc_chan->mchan->mbox->txdone_irq) { pr_err("This channel-%d does not support interrupt.\n", ctx->subspace_id); @@ -97,14 +119,17 @@ acpi_pcc_address_space_handler(u32 function, acpi_physical_address addr, u32 bits, acpi_integer *value, void *handler_context, void *region_context) { - int ret; struct pcc_data *data = region_context; + void __iomem *pcc_opregion; u64 usecs_lat; + int ret; + + pcc_opregion = data->pcc_chan->shmem + PCC_SIGNATURE_SIZE; reinit_completion(&data->done); - /* Write to Shared Memory */ - memcpy_toio(data->pcc_chan->shmem, (void *)value, data->ctx.length); + /* Write to the PCC OperationRegion after the shared memory signature. */ + memcpy_toio(pcc_opregion, (void *)value, data->ctx.length); ret = mbox_send_message(data->pcc_chan->mchan, NULL); if (ret < 0) @@ -125,7 +150,7 @@ acpi_pcc_address_space_handler(u32 function, acpi_physical_address addr, mbox_chan_txdone(data->pcc_chan->mchan, ret); - memcpy_fromio(value, data->pcc_chan->shmem, data->ctx.length); + memcpy_fromio(value, pcc_opregion, data->ctx.length); return AE_OK; } diff --git a/drivers/acpi/acpi_video.c b/drivers/acpi/acpi_video.c index 4d6fd9f6e9ad..6cfe390411c1 100644 --- a/drivers/acpi/acpi_video.c +++ b/drivers/acpi/acpi_video.c @@ -1825,6 +1825,12 @@ static int acpi_video_bus_register_backlight(struct acpi_video_bus *video) static void acpi_video_dev_unregister_backlight(struct acpi_video_device *device) { + if (device->cooling_dev) { + sysfs_remove_link(&device->dev->dev.kobj, "thermal_cooling"); + sysfs_remove_link(&device->cooling_dev->device.kobj, "device"); + thermal_cooling_device_unregister(device->cooling_dev); + device->cooling_dev = NULL; + } if (device->backlight) { backlight_device_unregister(device->backlight); device->backlight = NULL; @@ -1834,12 +1840,6 @@ static void acpi_video_dev_unregister_backlight(struct acpi_video_device *device kfree(device->brightness); device->brightness = NULL; } - if (device->cooling_dev) { - sysfs_remove_link(&device->dev->dev.kobj, "thermal_cooling"); - sysfs_remove_link(&device->cooling_dev->device.kobj, "device"); - thermal_cooling_device_unregister(device->cooling_dev); - device->cooling_dev = NULL; - } } static int acpi_video_bus_unregister_backlight(struct acpi_video_bus *video) diff --git a/drivers/acpi/acpica/dsfield.c b/drivers/acpi/acpica/dsfield.c index d7d56cc600d3..f7e503bf57c8 100644 --- a/drivers/acpi/acpica/dsfield.c +++ b/drivers/acpi/acpica/dsfield.c @@ -522,7 +522,8 @@ acpi_ds_create_field(union acpi_parse_object *op, } if (info.region_node->object->region.space_id == - ACPI_ADR_SPACE_PLATFORM_COMM) { + ACPI_ADR_SPACE_PLATFORM_COMM && + !region_node->object->field.internal_pcc_buffer) { region_node->object->field.internal_pcc_buffer = ACPI_ALLOCATE_ZEROED(info.region_node->object->region. length); diff --git a/drivers/acpi/acpica/exfield.c b/drivers/acpi/acpica/exfield.c index 9a55524ed8f4..50317fe0cbd5 100644 --- a/drivers/acpi/acpica/exfield.c +++ b/drivers/acpi/acpica/exfield.c @@ -45,12 +45,13 @@ static const u8 acpi_protocol_lengths[] = { /* * The following macros determine a given offset is a COMD field. - * According to the specification, generic subspaces (types 0-2) contains a - * 2-byte COMD field at offset 4 and master subspaces (type 3) contains a 4-byte - * COMD field starting at offset 12. + * According to the specification, the PCC OperationRegion begins after + * the PCC signature. The raw shared memory COMD offsets of 4 for generic + * subspaces (types 0-2) and 12 for master subspaces (type 3) therefore + * appear at OperationRegion offsets 0 and 8. */ -#define GENERIC_SUBSPACE_COMMAND(a) (4 == a || a == 5) -#define MASTER_SUBSPACE_COMMAND(a) (12 <= a && a <= 15) +#define GENERIC_SUBSPACE_COMMAND(a) (0 == a || a == 1) +#define MASTER_SUBSPACE_COMMAND(a) (8 <= a && a <= 11) /******************************************************************************* * diff --git a/drivers/acpi/acpica/nsxfname.c b/drivers/acpi/acpica/nsxfname.c index b6534187cd43..fcd94947fedb 100644 --- a/drivers/acpi/acpica/nsxfname.c +++ b/drivers/acpi/acpica/nsxfname.c @@ -503,6 +503,7 @@ acpi_status acpi_install_method(u8 *buffer) /* First AML opcode in the table must be a control method */ parser_state.aml = buffer + sizeof(struct acpi_table_header); + parser_state.aml_end = buffer + table->length; opcode = acpi_ps_peek_opcode(&parser_state); if (opcode != AML_METHOD_OP) { return (AE_BAD_PARAMETER); diff --git a/drivers/acpi/apei/ghes.c b/drivers/acpi/apei/ghes.c index ec2d5ca51db0..4e7df028a0b8 100644 --- a/drivers/acpi/apei/ghes.c +++ b/drivers/acpi/apei/ghes.c @@ -642,11 +642,14 @@ static void ghes_handle_aer(struct acpi_hest_generic_data *gdata) #ifdef CONFIG_ACPI_APEI_PCIEAER struct cper_sec_pcie *pcie_err = acpi_hest_get_payload(gdata); + if (gdata->error_data_length < sizeof(*pcie_err)) + return; + if (pcie_err->validation_bits & CPER_PCIE_VALID_DEVICE_ID && pcie_err->validation_bits & CPER_PCIE_VALID_AER_INFO) { + struct aer_capability_regs *aer_info; unsigned int devfn; int aer_severity; - u8 *aer_info; devfn = PCI_DEVFN(pcie_err->device_id.device, pcie_err->device_id.function); @@ -664,13 +667,25 @@ static void ghes_handle_aer(struct acpi_hest_generic_data *gdata) sizeof(struct aer_capability_regs)); if (!aer_info) return; - memcpy(aer_info, pcie_err->aer_info, sizeof(struct aer_capability_regs)); + + /* + * Map aer_info onto the struct as extlog_print_pcie() does: + * copy up to the four Header Log DWORDs, then place the TLP + * Prefix Log from where the hardware keeps it. The rest stays + * zero, so firmware cannot drive the pcie_print_tlp_log() loop + * over dw[] out of bounds. + */ + memset(aer_info, 0, sizeof(struct aer_capability_regs)); + memcpy(aer_info, pcie_err->aer_info, + offsetof(struct aer_capability_regs, header_log) + + PCIE_STD_NUM_TLP_HEADERLOG * sizeof(u32)); + memcpy(aer_info->header_log.prefix, + pcie_err->aer_info + PCI_ERR_PREFIX_LOG, + sizeof(aer_info->header_log.prefix)); aer_recover_queue(pcie_err->device_id.segment, pcie_err->device_id.bus, - devfn, aer_severity, - (struct aer_capability_regs *) - aer_info); + devfn, aer_severity, aer_info); } #endif } @@ -752,13 +767,13 @@ static DEFINE_KFIFO(cxl_cper_prot_err_fifo, struct cxl_cper_prot_err_work_data, static DEFINE_RAW_SPINLOCK(cxl_cper_prot_err_work_lock); struct work_struct *cxl_cper_prot_err_work; -static void cxl_cper_post_prot_err(struct cxl_cper_sec_prot_err *prot_err, - int severity) +void cxl_cper_post_prot_err(struct cxl_cper_sec_prot_err *prot_err, + int severity, u32 len) { #ifdef CONFIG_ACPI_APEI_PCIEAER struct cxl_cper_prot_err_work_data wd; - if (cxl_cper_sec_prot_err_valid(prot_err)) + if (cxl_cper_sec_prot_err_valid(prot_err, len)) return; guard(raw_spinlock_irqsave)(&cxl_cper_prot_err_work_lock); @@ -777,6 +792,7 @@ static void cxl_cper_post_prot_err(struct cxl_cper_sec_prot_err *prot_err, schedule_work(cxl_cper_prot_err_work); #endif } +EXPORT_SYMBOL_FOR_MODULES(cxl_cper_post_prot_err, "acpi_extlog"); void cxl_cper_register_prot_err_work(struct work_struct *work) { @@ -823,10 +839,15 @@ static DEFINE_RAW_SPINLOCK(cxl_cper_work_lock); struct work_struct *cxl_cper_work; static void cxl_cper_post_event(enum cxl_event_type event_type, - struct cxl_cper_event_rec *rec) + struct cxl_cper_event_rec *rec, u32 len) { struct cxl_cper_work_data wd; + if (len < sizeof(*rec)) { + pr_err(FW_WARN "CXL CPER section too small (%u)\n", len); + return; + } + if (rec->hdr.length <= sizeof(rec->hdr) || rec->hdr.length > sizeof(*rec)) { pr_err(FW_WARN "CXL CPER Invalid section length (%u)\n", @@ -923,6 +944,28 @@ static void ghes_log_hwerr(int sev, guid_t *sec_type) hwerr_log_error_type(HWERR_RECOV_OTHERS); } +/* + * 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) { @@ -948,6 +991,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); @@ -959,19 +1021,23 @@ static void ghes_do_proc(struct ghes *ghes, } else if (guid_equal(sec_type, &CPER_SEC_CXL_PROT_ERR)) { struct cxl_cper_sec_prot_err *prot_err = acpi_hest_get_payload(gdata); - cxl_cper_post_prot_err(prot_err, gdata->error_severity); + cxl_cper_post_prot_err(prot_err, gdata->error_severity, + gdata->error_data_length); } else if (guid_equal(sec_type, &CPER_SEC_CXL_GEN_MEDIA_GUID)) { struct cxl_cper_event_rec *rec = acpi_hest_get_payload(gdata); - cxl_cper_post_event(CXL_CPER_EVENT_GEN_MEDIA, rec); + cxl_cper_post_event(CXL_CPER_EVENT_GEN_MEDIA, rec, + gdata->error_data_length); } else if (guid_equal(sec_type, &CPER_SEC_CXL_DRAM_GUID)) { struct cxl_cper_event_rec *rec = acpi_hest_get_payload(gdata); - cxl_cper_post_event(CXL_CPER_EVENT_DRAM, rec); + cxl_cper_post_event(CXL_CPER_EVENT_DRAM, rec, + gdata->error_data_length); } else if (guid_equal(sec_type, &CPER_SEC_CXL_MEM_MODULE_GUID)) { struct cxl_cper_event_rec *rec = acpi_hest_get_payload(gdata); - cxl_cper_post_event(CXL_CPER_EVENT_MEM_MODULE, rec); + cxl_cper_post_event(CXL_CPER_EVENT_MEM_MODULE, rec, + gdata->error_data_length); } else { void *err = acpi_hest_get_payload(gdata); diff --git a/drivers/acpi/apei/ghes_helpers.c b/drivers/acpi/apei/ghes_helpers.c index bc7111b740af..df41b993f413 100644 --- a/drivers/acpi/apei/ghes_helpers.c +++ b/drivers/acpi/apei/ghes_helpers.c @@ -5,8 +5,15 @@ #include #include -int cxl_cper_sec_prot_err_valid(struct cxl_cper_sec_prot_err *prot_err) +int cxl_cper_sec_prot_err_valid(struct cxl_cper_sec_prot_err *prot_err, u32 len) { + if (len < sizeof(*prot_err)) { + pr_err_ratelimited(FW_WARN + "CXL CPER prot err section too small (%u)\n", + len); + return -EINVAL; + } + if (!(prot_err->valid_bits & PROT_ERR_VALID_AGENT_ADDRESS)) { pr_err_ratelimited("CXL CPER invalid agent type\n"); return -EINVAL; @@ -23,6 +30,15 @@ int cxl_cper_sec_prot_err_valid(struct cxl_cper_sec_prot_err *prot_err) return -EINVAL; } + /* The RAS Capability block sits after a firmware-sized DVSEC. */ + if (sizeof(*prot_err) + prot_err->dvsec_len + + sizeof(struct cxl_ras_capability_regs) > len) { + pr_err_ratelimited(FW_WARN + "CXL CPER prot err DVSEC (%u) overruns section (%u)\n", + prot_err->dvsec_len, len); + return -EINVAL; + } + if ((prot_err->agent_type == RCD || prot_err->agent_type == DEVICE || prot_err->agent_type == LD || prot_err->agent_type == FMLD) && !(prot_err->valid_bits & PROT_ERR_VALID_SERIAL_NUMBER)) diff --git a/drivers/acpi/button.c b/drivers/acpi/button.c index cdbb1023a8ee..34c7173b5a6c 100644 --- a/drivers/acpi/button.c +++ b/drivers/acpi/button.c @@ -144,6 +144,18 @@ static const struct dmi_system_id dmi_lid_quirks[] = { }, .driver_data = (void *)(long)ACPI_BUTTON_LID_INIT_OPEN, }, + { + /* + * Razer Blade Stealth 13 early 2020, when the lid is opened + * while suspended the open notification is lost and _LID keeps + * returning closed after resume, causing spurious re-suspends. + */ + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Razer"), + DMI_MATCH(DMI_PRODUCT_NAME, "Blade Stealth 13 (Early 2020) - RZ09-0310"), + }, + .driver_data = (void *)(long)ACPI_BUTTON_LID_INIT_OPEN, + }, { /* * Samsung galaxybook2 ,initial _LID device notification returns diff --git a/drivers/acpi/cppc_acpi.c b/drivers/acpi/cppc_acpi.c index 8aa0ce556863..67dae96a3cd8 100644 --- a/drivers/acpi/cppc_acpi.c +++ b/drivers/acpi/cppc_acpi.c @@ -804,6 +804,11 @@ int acpi_cppc_processor_probe(struct acpi_processor *pr) } out_obj = (union acpi_object *) output.pointer; + if (out_obj->package.count < 2) { + pr_debug("Unexpected _CPC package count (%u) for CPU:%d\n", + out_obj->package.count, pr->id); + goto out_buf_free; + } cpc_ptr = kzalloc_obj(struct cpc_desc); if (!cpc_ptr) { @@ -814,12 +819,15 @@ int acpi_cppc_processor_probe(struct acpi_processor *pr) /* First entry is NumEntries. */ cpc_obj = &out_obj->package.elements[0]; if (cpc_obj->type == ACPI_TYPE_INTEGER) { - num_ent = cpc_obj->integer.value; - if (num_ent <= 1) { - pr_debug("Unexpected _CPC NumEntries value (%d) for CPU:%d\n", - num_ent, pr->id); + if (cpc_obj->integer.value < 2 || + cpc_obj->integer.value > out_obj->package.count) { + pr_debug("Invalid _CPC NumEntries (%llu) for package count (%u) on CPU:%d\n", + cpc_obj->integer.value, out_obj->package.count, + pr->id); goto out_free; } + + num_ent = cpc_obj->integer.value; } else { pr_debug("Unexpected _CPC NumEntries entry type (%d) for CPU:%d\n", cpc_obj->type, pr->id); @@ -829,6 +837,12 @@ int acpi_cppc_processor_probe(struct acpi_processor *pr) /* Second entry should be revision. */ cpc_obj = &out_obj->package.elements[1]; if (cpc_obj->type == ACPI_TYPE_INTEGER) { + if (cpc_obj->integer.value > U8_MAX) { + pr_debug("Invalid _CPC Revision (%llu) for CPU:%d\n", + cpc_obj->integer.value, pr->id); + ret = -EINVAL; + goto out_free; + } cpc_rev = cpc_obj->integer.value; } else { pr_debug("Unexpected _CPC Revision entry type (%d) for CPU:%d\n", diff --git a/drivers/acpi/device_pm.c b/drivers/acpi/device_pm.c index aa55ecfc2923..76104f715efa 100644 --- a/drivers/acpi/device_pm.c +++ b/drivers/acpi/device_pm.c @@ -23,6 +23,8 @@ #include "fan.h" #include "internal.h" +#define ACPI_D_STATE_INVALID ACPI_D_STATE_COUNT + /** * acpi_power_state_string - String representation of ACPI device power state. * @state: ACPI device power state to return the string representation of. @@ -75,15 +77,14 @@ static int acpi_dev_pm_explicit_get(struct acpi_device *device, int *state) int acpi_device_get_power(struct acpi_device *device, int *state) { int result = ACPI_STATE_UNKNOWN; - struct acpi_device *parent; int error; if (!device || !state) return -EINVAL; - parent = acpi_dev_parent(device); - if (!device->flags.power_manageable) { + struct acpi_device *parent = acpi_dev_parent(device); + /* TBD: Non-recursive algorithm for walking up hierarchy. */ *state = parent ? parent->power.state : ACPI_STATE_D0; goto out; @@ -119,16 +120,6 @@ int acpi_device_get_power(struct acpi_device *device, int *state) result = psc > ACPI_STATE_D2 ? ACPI_STATE_D3_HOT : psc; } - /* - * If we were unsure about the device parent's power state up to this - * point, the fact that the device is in D0 implies that the parent has - * to be in D0 too, except if ignore_parent is set. - */ - if (!device->power.flags.ignore_parent && parent && - parent->power.state == ACPI_STATE_UNKNOWN && - result == ACPI_STATE_D0) - parent->power.state = ACPI_STATE_D0; - *state = result; out: @@ -304,24 +295,28 @@ int acpi_bus_set_power(acpi_handle handle, int state) } EXPORT_SYMBOL(acpi_bus_set_power); -int acpi_bus_init_power(struct acpi_device *device) +static int acpi_device_init_power(struct acpi_device *device) { int state; int result; - if (!device) - return -EINVAL; - - device->power.state = ACPI_STATE_UNKNOWN; - if (!acpi_device_is_present(device)) { - device->flags.initialized = false; - return -ENXIO; - } - result = acpi_device_get_power(device, &state); if (result) return result; + /* + * If the current power state of the device is D0 and it has a parent + * whose power state is not ignored, and the parent's power state + * initialization has failed, the parent's power state can be updated to + * D0 for consistency. + */ + if (!device->power.flags.ignore_parent && state == ACPI_STATE_D0) { + struct acpi_device *parent = acpi_dev_parent(device); + + if (parent && parent->power.state == ACPI_D_STATE_INVALID) + parent->power.state = ACPI_STATE_D0; + } + if (state < ACPI_STATE_D3_COLD && device->power.flags.power_resources) { /* Reference count the power resources. */ result = acpi_power_on_resources(device, state); @@ -351,9 +346,36 @@ int acpi_bus_init_power(struct acpi_device *device) state = ACPI_STATE_D0; } device->power.state = state; + + acpi_handle_debug(device->handle, "Initial power state: %s\n", + acpi_power_state_string(state)); + return 0; } +int acpi_bus_init_power(struct acpi_device *device) +{ + int result; + + if (device->power.state != ACPI_STATE_UNKNOWN) + return 0; + + /* + * The ACPI device power state can be only initialized once. If this + * fails, ACPI power management will not be used for the device going + * forward. + */ + result = acpi_device_init_power(device); + if (result) { + device->flags.power_manageable = 0; + device->power.state = ACPI_D_STATE_INVALID; + acpi_handle_info(device->handle, + "Initial power state undetermined, ACPI PM disabled\n"); + } + + return result; +} + /** * acpi_device_fix_up_power - Force device with missing _PSC into D0. * @device: Device object whose power state is to be fixed up. @@ -475,8 +497,13 @@ static int acpi_power_up_if_adr_present(struct acpi_device *adev, void *not_used if (!(adev->flags.power_manageable && adev->pnp.type.bus_address)) return 0; - acpi_handle_debug(adev->handle, "Power state: %s\n", - acpi_power_state_string(adev->power.state)); + /* + * This is done during the PCI root initialization which occurs before + * acpi_bus_attach() is called for the device, so the ACPI power state + * of the device needs to be initialized here. + */ + if (acpi_bus_init_power(adev)) + return 0; if (adev->power.state == ACPI_STATE_D3_COLD) return acpi_device_set_power(adev, ACPI_STATE_D0); diff --git a/drivers/acpi/fan_core.c b/drivers/acpi/fan_core.c index 624d0736b581..a31d7beca5d0 100644 --- a/drivers/acpi/fan_core.c +++ b/drivers/acpi/fan_core.c @@ -284,7 +284,7 @@ static int acpi_fan_speed_cmp(const void *a, const void *b) return fps1->speed - fps2->speed; } -static int acpi_fan_get_fps(struct acpi_device *device) +static int acpi_fan_get_fps(struct device *dev, struct acpi_device *device) { struct acpi_fan *fan = acpi_driver_data(device); struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL }; @@ -304,11 +304,8 @@ static int acpi_fan_get_fps(struct acpi_device *device) } fan->fps_count = obj->package.count - 1; /* minus revision field */ - fan->fps = devm_kcalloc(&device->dev, - fan->fps_count, sizeof(struct acpi_fan_fps), - GFP_KERNEL); + fan->fps = devm_kcalloc(dev, fan->fps_count, sizeof(*fan->fps), GFP_KERNEL); if (!fan->fps) { - dev_err(&device->dev, "Not enough memory\n"); status = -ENOMEM; goto err; } @@ -522,7 +519,7 @@ static int acpi_fan_probe(struct platform_device *pdev) if (result) return result; - result = acpi_fan_get_fps(device); + result = acpi_fan_get_fps(&pdev->dev, device); if (result) return result; } diff --git a/drivers/acpi/glue.c b/drivers/acpi/glue.c index b1776809279d..e55daa4221da 100644 --- a/drivers/acpi/glue.c +++ b/drivers/acpi/glue.c @@ -59,19 +59,34 @@ int unregister_acpi_bus_type(struct acpi_bus_type *type) } EXPORT_SYMBOL_GPL(unregister_acpi_bus_type); -static struct acpi_bus_type *acpi_get_bus_type(struct device *dev) +static struct acpi_device *acpi_companion_lookup(struct device *dev) { - struct acpi_bus_type *tmp, *ret = NULL; + struct acpi_bus_type *type; - down_read(&bus_type_sem); - list_for_each_entry(tmp, &bus_type_list, list) { - if (tmp->match(dev)) { - ret = tmp; - break; + guard(rwsem_read)(&bus_type_sem); + + list_for_each_entry(type, &bus_type_list, list) { + struct acpi_device *adev; + + if (!type->match(dev)) + continue; + + adev = type->find_companion(dev); + if (!adev) { + dev_dbg(dev, "ACPI companion not found\n"); + return NULL; + } + if (acpi_bind_one(dev, adev)) { + dev_dbg(dev, "Binding to ACPI companion failed\n"); + return NULL; } + if (type->setup) + type->setup(dev); + + return adev; } - up_read(&bus_type_sem); - return ret; + + return NULL; } #define FIND_CHILD_MIN_SCORE 1 @@ -228,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_obj(*physical_node); - 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 @@ -263,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) { @@ -280,12 +286,19 @@ int acpi_bind_one(struct device *dev, struct acpi_device *acpi_dev) } } + physical_node = kzalloc_obj(*physical_node); + 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); @@ -301,28 +314,20 @@ 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); -int acpi_unbind_one(struct device *dev) +void acpi_unbind_one(struct device *dev) { struct acpi_device *acpi_dev = ACPI_COMPANION(dev); struct acpi_device_physical_node *entry; if (!acpi_dev) - return 0; + return; mutex_lock(&acpi_dev->physical_node_lock); @@ -337,15 +342,17 @@ int acpi_unbind_one(struct device *dev) sysfs_remove_link(&acpi_dev->dev.kobj, physnode_name); sysfs_remove_link(&dev->kobj, "firmware_node"); ACPI_COMPANION_SET(dev, NULL); + + mutex_unlock(&acpi_dev->physical_node_lock); + /* Drop references taken by acpi_bind_one(). */ put_device(dev); acpi_dev_put(acpi_dev); kfree(entry); - break; + return; } mutex_unlock(&acpi_dev->physical_node_lock); - return 0; } EXPORT_SYMBOL_GPL(acpi_unbind_one); @@ -354,48 +361,29 @@ void acpi_device_notify(struct device *dev) struct acpi_device *adev; int ret; + /* ACPI devices have no ACPI companions. */ + if (dev->bus == &acpi_bus_type) + return; + ret = acpi_bind_one(dev, NULL); if (ret) { - struct acpi_bus_type *type = acpi_get_bus_type(dev); - - if (!type) - goto err; - - adev = type->find_companion(dev); - if (!adev) { - dev_dbg(dev, "ACPI companion not found\n"); - goto err; - } - ret = acpi_bind_one(dev, adev); - if (ret) - goto err; - - if (type->setup) { - type->setup(dev); - goto done; - } + adev = acpi_companion_lookup(dev); + if (!adev) + return; } else { adev = ACPI_COMPANION(dev); if (dev_is_pci(dev)) { pci_acpi_setup(dev, adev); - goto done; } else if (dev_is_platform(dev)) { acpi_configure_pmsi_domain(dev); + + if (adev->handler && adev->handler->bind) + adev->handler->bind(dev); } } - if (adev->handler && adev->handler->bind) - adev->handler->bind(dev); - -done: - acpi_handle_debug(ACPI_HANDLE(dev), "Bound to device %s\n", - dev_name(dev)); - - return; - -err: - dev_dbg(dev, "No ACPI support\n"); + dev_dbg(dev, "Bound to ACPI device %s\n", acpi_dev_name(adev)); } void acpi_device_notify_remove(struct device *dev) diff --git a/drivers/acpi/numa/hmat.c b/drivers/acpi/numa/hmat.c index 9792dc394756..3006789ae31f 100644 --- a/drivers/acpi/numa/hmat.c +++ b/drivers/acpi/numa/hmat.c @@ -995,7 +995,7 @@ static int hmat_calculate_adistance(struct notifier_block *self, return NOTIFY_STOP; } -static struct notifier_block hmat_adist_nb __meminitdata = { +static struct notifier_block hmat_adist_nb = { .notifier_call = hmat_calculate_adistance, .priority = 100, }; diff --git a/drivers/acpi/pci_link.c b/drivers/acpi/pci_link.c index e6ed13aee48d..84bfcdf242dd 100644 --- a/drivers/acpi/pci_link.c +++ b/drivers/acpi/pci_link.c @@ -787,6 +787,7 @@ static void acpi_pci_link_remove(struct acpi_device *device) list_del(&link->list); mutex_unlock(&acpi_link_lock); + device->driver_data = NULL; kfree(link); } diff --git a/drivers/acpi/pci_root.c b/drivers/acpi/pci_root.c index 88c65f34e305..a1a9c06012f8 100644 --- a/drivers/acpi/pci_root.c +++ b/drivers/acpi/pci_root.c @@ -993,6 +993,25 @@ static void acpi_pci_root_release_info(struct pci_host_bridge *bridge) __acpi_pci_root_release_info(bridge->release_data); } +#define OSC_OWNER(ctrl, bit, flag) \ + do { \ + if (!((ctrl) & (bit))) \ + flag = 0; \ + } while (0) + +#define FLAG(x) ((x) ? '+' : '-') + +/* + * _OSC control bits for the features implemented by the PCIe port driver, + * i.e., the ones "pcie_ports=native" applies to. LTR and SHPC hotplug are + * negotiated via _OSC as well, but they are not portdrv services, so + * "pcie_ports=" has no bearing on them. + */ +#define OSC_PCIE_PORT_SERVICE_CONTROLS (OSC_PCI_EXPRESS_NATIVE_HP_CONTROL | \ + OSC_PCI_EXPRESS_PME_CONTROL | \ + OSC_PCI_EXPRESS_AER_CONTROL | \ + OSC_PCI_EXPRESS_DPC_CONTROL) + struct pci_bus *acpi_pci_root_create(struct acpi_pci_root *root, struct acpi_pci_root_ops *ops, struct acpi_pci_root_info *info, @@ -1003,6 +1022,7 @@ struct pci_bus *acpi_pci_root_create(struct acpi_pci_root *root, int node = acpi_get_node(device->handle); struct pci_bus *bus; struct pci_host_bridge *host_bridge; + u32 ctrl, ext_ctrl, override = 0; info->root = root; info->bridge = device; @@ -1028,21 +1048,49 @@ struct pci_bus *acpi_pci_root_create(struct acpi_pci_root *root, goto out_release_info; host_bridge = to_pci_host_bridge(bus->bridge); - if (!(root->osc_control_set & OSC_PCI_EXPRESS_NATIVE_HP_CONTROL)) - host_bridge->native_pcie_hotplug = 0; - if (!(root->osc_control_set & OSC_PCI_SHPC_NATIVE_HP_CONTROL)) - host_bridge->native_shpc_hotplug = 0; - if (!(root->osc_control_set & OSC_PCI_EXPRESS_AER_CONTROL)) - host_bridge->native_aer = 0; - if (!(root->osc_control_set & OSC_PCI_EXPRESS_PME_CONTROL)) - host_bridge->native_pme = 0; - if (!(root->osc_control_set & OSC_PCI_EXPRESS_LTR_CONTROL)) - host_bridge->native_ltr = 0; - if (!(root->osc_control_set & OSC_PCI_EXPRESS_DPC_CONTROL)) - host_bridge->native_dpc = 0; - - if (!(root->osc_ext_control_set & OSC_CXL_ERROR_REPORTING_CONTROL)) - host_bridge->native_cxl_error = 0; + + ctrl = root->osc_control_set; + ext_ctrl = root->osc_ext_control_set; + + /* + * If the user specified "pcie_ports=native", use the PCIe port + * services regardless of what _OSC says, i.e., proceed as though the + * platform had granted us control of them. "pcie_ports=dpc-native" + * does the same for DPC alone. This may conflict with firmware that + * expects to own those features. + */ + if (pcie_ports_native) + override = OSC_PCIE_PORT_SERVICE_CONTROLS & ~ctrl; + else if (pcie_ports_dpc_native) + override = OSC_PCI_EXPRESS_DPC_CONTROL & ~ctrl; + + if (override) { + decode_osc_control(root, pcie_ports_native ? + "OS forcing control (\"pcie_ports=native\") of" : + "OS forcing control (\"pcie_ports=dpc-native\") of", + override); + ctrl |= override; + } + + OSC_OWNER(ctrl, OSC_PCI_EXPRESS_NATIVE_HP_CONTROL, + host_bridge->native_pcie_hotplug); + OSC_OWNER(ctrl, OSC_PCI_SHPC_NATIVE_HP_CONTROL, + host_bridge->native_shpc_hotplug); + OSC_OWNER(ctrl, OSC_PCI_EXPRESS_AER_CONTROL, host_bridge->native_aer); + OSC_OWNER(ctrl, OSC_PCI_EXPRESS_PME_CONTROL, host_bridge->native_pme); + OSC_OWNER(ctrl, OSC_PCI_EXPRESS_LTR_CONTROL, host_bridge->native_ltr); + OSC_OWNER(ctrl, OSC_PCI_EXPRESS_DPC_CONTROL, host_bridge->native_dpc); + + OSC_OWNER(ext_ctrl, OSC_CXL_ERROR_REPORTING_CONTROL, + host_bridge->native_cxl_error); + + dev_info(&root->device->dev, "OS native features: SHPCHotplug%c PCIeHotplug%c PME%c AER%c DPC%c LTR%c\n", + FLAG(host_bridge->native_shpc_hotplug), + FLAG(host_bridge->native_pcie_hotplug), + FLAG(host_bridge->native_pme), + FLAG(host_bridge->native_aer), + FLAG(host_bridge->native_dpc), + FLAG(host_bridge->native_ltr)); acpi_dev_power_up_children_with_adr(device); diff --git a/drivers/acpi/platform_profile.c b/drivers/acpi/platform_profile.c index 79d2e92e5c28..b4c91d57f3d4 100644 --- a/drivers/acpi/platform_profile.c +++ b/drivers/acpi/platform_profile.c @@ -8,15 +8,25 @@ #include #include #include +#include #include #include #include #define to_pprof_handler(d) (container_of(d, struct platform_profile_handler, dev)) +/* + * Protects profile_handlers membership and serializes profile operations + * against each other and handler removal. Never held across sysfs teardown, + * which can wait for callbacks that acquire this lock. + */ static DEFINE_MUTEX(profile_lock); +/* Serialize registration and sysfs updates without blocking sysfs callbacks. */ +static DEFINE_MUTEX(profile_registration_lock); +static LIST_HEAD(profile_handlers); struct platform_profile_handler { + struct list_head node; const char *name; struct device dev; int minor; @@ -44,6 +54,23 @@ static_assert(ARRAY_SIZE(profile_names) == PLATFORM_PROFILE_LAST); static DEFINE_IDA(platform_profile_ida); +static int profile_for_each_handler(void *data, + int (*fn)(struct device *dev, void *data)) +{ + struct platform_profile_handler *handler; + int ret; + + lockdep_assert_held(&profile_lock); + + list_for_each_entry(handler, &profile_handlers, node) { + ret = fn(&handler->dev, data); + if (ret) + return ret; + } + + return 0; +} + /** * _commmon_choices_show - Show the available profile choices * @choices: The available profile choices @@ -306,20 +333,18 @@ static ssize_t platform_profile_choices_show(struct kobject *kobj, int err; scoped_cond_guard(mutex_intr, return -ERESTARTSYS, &profile_lock) { - err = class_for_each_device(&platform_profile_class, NULL, - &data, _aggregate_choices); + err = profile_for_each_handler(&data, _aggregate_choices); if (err) return err; if (data.count == 1) { - err = class_for_each_device(&platform_profile_class, NULL, - &data, _remove_hidden_choices); + err = profile_for_each_handler(&data, _remove_hidden_choices); if (err) return err; } } /* no profile handler registered any more */ - if (bitmap_empty(data.aggregate, PLATFORM_PROFILE_LAST)) + if (!data.count || bitmap_empty(data.aggregate, PLATFORM_PROFILE_LAST)) return -EINVAL; return _commmon_choices_show(data.aggregate, buf); @@ -384,8 +409,7 @@ static ssize_t platform_profile_show(struct kobject *kobj, int err; scoped_cond_guard(mutex_intr, return -ERESTARTSYS, &profile_lock) { - err = class_for_each_device(&platform_profile_class, NULL, - &profile, _aggregate_profiles); + err = profile_for_each_handler(&profile, _aggregate_profiles); if (err) return err; } @@ -423,15 +447,13 @@ static ssize_t platform_profile_store(struct kobject *kobj, return -EINVAL; scoped_cond_guard(mutex_intr, return -ERESTARTSYS, &profile_lock) { - ret = class_for_each_device(&platform_profile_class, NULL, - &data, _aggregate_choices); + ret = profile_for_each_handler(&data, _aggregate_choices); if (ret) return ret; - if (!test_bit(i, data.aggregate)) + if (!data.count || !test_bit(i, data.aggregate)) return -EOPNOTSUPP; - ret = class_for_each_device(&platform_profile_class, NULL, &i, - _store_and_notify); + ret = profile_for_each_handler(&i, _store_and_notify); if (ret) return ret; } @@ -450,22 +472,11 @@ static struct attribute *platform_profile_attrs[] = { NULL }; -static int profile_class_registered(struct device *dev, const void *data) -{ - return 1; -} - static umode_t profile_class_is_visible(struct kobject *kobj, struct attribute *attr, int idx) { - struct device *dev; - - dev = class_find_device(&platform_profile_class, NULL, NULL, profile_class_registered); - if (!dev) - return 0; - - put_device(dev); + guard(mutex)(&profile_lock); - return attr->mode; + return list_empty(&profile_handlers) ? 0 : attr->mode; } static const struct attribute_group platform_profile_group = { @@ -502,8 +513,7 @@ int platform_profile_cycle(void) int err; scoped_cond_guard(mutex_intr, return -ERESTARTSYS, &profile_lock) { - err = class_for_each_device(&platform_profile_class, NULL, - &profile, _aggregate_profiles); + err = profile_for_each_handler(&profile, _aggregate_profiles); if (err) return err; @@ -512,8 +522,7 @@ int platform_profile_cycle(void) profile == PLATFORM_PROFILE_LAST) return -EINVAL; - err = class_for_each_device(&platform_profile_class, NULL, - &data, _aggregate_choices); + err = profile_for_each_handler(&data, _aggregate_choices); if (err) return err; @@ -525,8 +534,7 @@ int platform_profile_cycle(void) PLATFORM_PROFILE_LAST, profile + 1); - err = class_for_each_device(&platform_profile_class, NULL, &next, - _store_and_notify); + err = profile_for_each_handler(&next, _store_and_notify); if (err) return err; @@ -583,7 +591,7 @@ struct device *platform_profile_register(struct device *dev, const char *name, } } - guard(mutex)(&profile_lock); + guard(mutex)(&profile_registration_lock); /* create class interface for individual handler */ minor = ida_alloc(&platform_profile_ida, GFP_KERNEL); @@ -604,6 +612,8 @@ struct device *platform_profile_register(struct device *dev, const char *name, put_device(ppdev); goto cleanup_ida; } + scoped_guard(mutex, &profile_lock) + list_add_tail(&to_pprof_handler(ppdev)->node, &profile_handlers); sysfs_notify(acpi_kobj, NULL, "platform_profile"); @@ -614,6 +624,9 @@ struct device *platform_profile_register(struct device *dev, const char *name, return ppdev; cleanup_cur: + scoped_guard(mutex, &profile_lock) + list_del(&to_pprof_handler(ppdev)->node); + device_unregister(ppdev); cleanup_ida: @@ -636,7 +649,10 @@ void platform_profile_remove(struct device *dev) pprof = to_pprof_handler(dev); - guard(mutex)(&profile_lock); + guard(mutex)(&profile_registration_lock); + + scoped_guard(mutex, &profile_lock) + list_del(&pprof->node); ida_free(&platform_profile_ida, pprof->minor); device_unregister(&pprof->dev); diff --git a/drivers/acpi/scan.c b/drivers/acpi/scan.c index 163a3cccf197..e8189849eaa6 100644 --- a/drivers/acpi/scan.c +++ b/drivers/acpi/scan.c @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -1143,8 +1144,7 @@ static void acpi_bus_get_power_flags(struct acpi_device *device) device->power.states[ACPI_STATE_D3_COLD].flags.valid = 1; } - if (acpi_bus_init_power(device)) - device->flags.power_manageable = 0; + device->power.state = ACPI_STATE_UNKNOWN; } static void acpi_bus_get_flags(struct acpi_device *device) @@ -2338,38 +2338,50 @@ static int acpi_scan_attach_handler(struct acpi_device *device) static int acpi_bus_attach(struct acpi_device *device, void *first_pass) { bool skip = !first_pass && device->flags.visited; + struct pci_dev *pci; acpi_handle ejd; int ret; if (skip) goto ok; + device->flags.initialized = true; + if (ACPI_SUCCESS(acpi_bus_get_ejd(device->handle, &ejd))) register_dock_dependent_device(device, ejd); acpi_bus_get_status(device); - /* Skip devices that are not ready for enumeration (e.g. not present) */ - if (!acpi_dev_ready_for_enumeration(device)) { - device->flags.initialized = false; + /* + * If the given ACPI device object has been already associated with a + * PCI device found on the bus, its status is effectively "present and + * enabled", and dependencies are not tracked for PCI devices, so it is + * not necessary or even useful to check the device's readiness in that + * case. + */ + pci = acpi_dev_get_pci_dev(device); + if (pci) { + acpi_handle_debug(device->handle, "PCI companion %s found\n", + pci_name(pci)); + + if (!acpi_device_is_present(device)) + pci_info(pci, FW_BUG "ACPI status differs from reality\n"); + + pci_dev_put(pci); + } else if (!acpi_dev_ready_for_enumeration(device)) { + /* The device is not ready (e.g. not present), so skip it. */ acpi_device_clear_enumerated(device); - device->flags.power_manageable = 0; return 0; } + if (device->handler) goto ok; acpi_ec_register_opregions(device); - if (!device->flags.initialized) { - device->flags.power_manageable = - device->power.states[ACPI_STATE_D0].flags.valid; - if (acpi_bus_init_power(device)) - device->flags.power_manageable = 0; + acpi_bus_init_power(device); - device->flags.initialized = true; - } else if (device->flags.visited) { + if (device->flags.visited) goto ok; - } ret = acpi_scan_attach_handler(device); if (ret < 0) diff --git a/drivers/acpi/tables.c b/drivers/acpi/tables.c index eb93c060426f..aaa1de79bccf 100644 --- a/drivers/acpi/tables.c +++ b/drivers/acpi/tables.c @@ -560,6 +560,9 @@ acpi_table_initrd_override(struct acpi_table_header *existing_table, while (table_offset + ACPI_HEADER_SIZE <= all_tables_size) { table = acpi_os_map_memory(acpi_tables_addr + table_offset, ACPI_HEADER_SIZE); + if (!table) + return AE_NO_MEMORY; + if (table_offset + table->length > all_tables_size) { acpi_os_unmap_memory(table, ACPI_HEADER_SIZE); WARN_ON(1); diff --git a/drivers/android/binder/process.rs b/drivers/android/binder/process.rs index 5372bfbd93b3..de5bca7f9fc7 100644 --- a/drivers/android/binder/process.rs +++ b/drivers/android/binder/process.rs @@ -1728,7 +1728,7 @@ pub(crate) fn release(this: Arc, _file: &File) { if should_schedule { // Ignore failures to schedule to the workqueue. Those just mean that we're already // scheduled for execution. - let _ = workqueue::system().enqueue(this); + let _ = workqueue::system_percpu().enqueue(this); } drop(binderfs_file); @@ -1745,7 +1745,7 @@ pub(crate) fn flush(this: ArcBorrow<'_, Process>) -> Result { if should_schedule { // Ignore failures to schedule to the workqueue. Those just mean that we're already // scheduled for execution. - let _ = workqueue::system().enqueue(Arc::from(this)); + let _ = workqueue::system_percpu().enqueue(Arc::from(this)); } Ok(()) } diff --git a/drivers/ata/ahci.c b/drivers/ata/ahci.c index 9b8c0935001c..fdce365969b4 100644 --- a/drivers/ata/ahci.c +++ b/drivers/ata/ahci.c @@ -1642,34 +1642,27 @@ MODULE_PARM_DESC(mask_port_ext, "where is the PCI ID of an AHCI controller in the " "form \"domain:bus:dev.func\""); -static u32 ahci_port_mask(struct device *dev, char *mask_s) +static void ahci_port_mask(struct device *dev, char *mask_s, u32 *mask) { - unsigned int mask; - - if (kstrtouint(mask_s, 0, &mask)) { + if (kstrtou32(mask_s, 0, mask)) dev_err(dev, "Invalid port map mask\n"); - return 0; - } - - return mask; } -static u32 ahci_get_port_mask(struct device *dev, char *mask_p) +static void ahci_get_port_mask(struct device *dev, char *mask_p, u32 *mask) { char *param, *end, *str, *mask_s; char *name; - u32 mask = 0; if (!mask_p || !strlen(mask_p)) - return 0; + return; str = kstrdup(mask_p, GFP_KERNEL); if (!str) - return 0; + return; /* Handle single mask case */ if (!strchr(str, '=')) { - mask = ahci_port_mask(dev, str); + ahci_port_mask(dev, str, mask); goto free; } @@ -1704,13 +1697,11 @@ static u32 ahci_get_port_mask(struct device *dev, char *mask_p) param++; } - mask = ahci_port_mask(dev, mask_s); + ahci_port_mask(dev, mask_s, mask); } free: kfree(str); - - return mask; } static void ahci_pci_save_initial_config(struct pci_dev *pdev, @@ -1736,10 +1727,10 @@ static void ahci_pci_save_initial_config(struct pci_dev *pdev, } /* Handle port map masks passed as module parameter. */ - hpriv->mask_port_map = - ahci_get_port_mask(&pdev->dev, ahci_mask_port_map); - hpriv->mask_port_ext = - ahci_get_port_mask(&pdev->dev, ahci_mask_port_ext); + ahci_get_port_mask(&pdev->dev, ahci_mask_port_map, + &hpriv->mask_port_map); + ahci_get_port_mask(&pdev->dev, ahci_mask_port_ext, + &hpriv->mask_port_ext); ahci_save_initial_config(&pdev->dev, hpriv); } diff --git a/drivers/ata/libahci.c b/drivers/ata/libahci.c index f3fd56f15334..222af8d9fc01 100644 --- a/drivers/ata/libahci.c +++ b/drivers/ata/libahci.c @@ -2233,6 +2233,21 @@ void ahci_error_handler(struct ata_port *ap) sata_pmp_error_handler(ap); + /* + * ahci_do_softreset() turns FBS off before resetting a fan-out link + * and turns it back on only if that reset succeeds. When it fails + * (e.g. a hot-plugged drive is still spinning up), EH escalates to a + * PMP hardreset, which never re-enables FBS, so the port would keep + * command-based switching until the PMP is attached again (reboot). + * Restore FBS once recovery is done and the PMP is still attached. + */ + if (sata_pmp_attached(ap) && ata_dev_enabled(ap->link.device)) { + struct ahci_port_priv *pp = ap->private_data; + + if (pp->fbs_supported && !pp->fbs_enabled) + ahci_enable_fbs(ap); + } + if (!ata_dev_enabled(ap->link.device)) hpriv->stop_engine(ap); } diff --git a/drivers/ata/libata-core.c b/drivers/ata/libata-core.c index f218773f187f..30572ca510de 100644 --- a/drivers/ata/libata-core.c +++ b/drivers/ata/libata-core.c @@ -434,6 +434,7 @@ static void ata_force_link_limits(struct ata_link *link) */ static void ata_force_xfermask(struct ata_device *dev) { + struct ata_port *ap = dev->link->ap; int devno = dev->link->pmp + dev->devno; int alt_devno = devno; int i; @@ -458,6 +459,17 @@ static void ata_force_xfermask(struct ata_device *dev) ata_unpack_xfermask(fe->param.xfer_mask, &pio_mask, &mwdma_mask, &udma_mask); + + /* Make sure that the port supports the specified xfer modes. */ + if (!(pio_mask & ap->pio_mask) && + !(mwdma_mask & ap->mwdma_mask) && + !(udma_mask & ap->udma_mask)) { + ata_dev_warn(dev, + "FORCE: ignoring unsupported xfer_mask %s\n", + fe->param.name); + continue; + } + if (udma_mask) dev->udma_mask = udma_mask; else if (mwdma_mask) { @@ -4323,7 +4335,8 @@ static const struct ata_dev_quirks_entry __ata_dev_quirks[] = { { "MAXTOR 6L080L4", "A93.0500", ATA_QUIRK_BROKEN_HPA }, /* this one allows HPA unlocking but fails IOs on the area */ - { "OCZ-VERTEX", "1.30", ATA_QUIRK_BROKEN_HPA }, + { "OCZ-VERTEX", "1.30", ATA_QUIRK_BROKEN_HPA | + ATA_QUIRK_NO_FUA }, /* Devices which report 1 sector over size HPA */ { "ST340823A", NULL, ATA_QUIRK_HPA_SIZE }, @@ -4459,6 +4472,8 @@ static const struct ata_dev_quirks_entry __ata_dev_quirks[] = { { "Crucial*", NULL, ATA_QUIRK_ZERO_AFTER_TRIM }, { "INTEL SSDSC2KG480G8", "XCV10120", ATA_QUIRK_ZERO_AFTER_TRIM | ATA_QUIRK_MAX_SEC }, + { "INTEL*SSDSC2CT*", NULL, ATA_QUIRK_ZERO_AFTER_TRIM | + ATA_QUIRK_NO_FUA }, { "INTEL*SSD*", NULL, ATA_QUIRK_ZERO_AFTER_TRIM }, { "SSD*INTEL*", NULL, ATA_QUIRK_ZERO_AFTER_TRIM }, { "Samsung*SSD*", NULL, ATA_QUIRK_ZERO_AFTER_TRIM }, @@ -4479,7 +4494,8 @@ static const struct ata_dev_quirks_entry __ata_dev_quirks[] = { { "WDC WD1200JD-*", NULL, ATA_QUIRK_WD_BROKEN_LPM }, { "WDC WD1600JD-*", NULL, ATA_QUIRK_WD_BROKEN_LPM }, { "WDC WD2000JD-*", NULL, ATA_QUIRK_WD_BROKEN_LPM }, - { "WDC WD2500JD-*", NULL, ATA_QUIRK_WD_BROKEN_LPM }, + { "WDC WD2500JD-*", NULL, ATA_QUIRK_WD_BROKEN_LPM | + ATA_QUIRK_NO_FUA }, { "WDC WD3000JD-*", NULL, ATA_QUIRK_WD_BROKEN_LPM }, { "WDC WD3200JD-*", NULL, ATA_QUIRK_WD_BROKEN_LPM }, @@ -4504,7 +4520,6 @@ static const struct ata_dev_quirks_entry __ata_dev_quirks[] = { { "Maxtor", "BANC1G10", ATA_QUIRK_NO_FUA }, { "WDC*WD2500J*", NULL, ATA_QUIRK_NO_FUA }, { "OCZ-VERTEX*", NULL, ATA_QUIRK_NO_FUA }, - { "INTEL*SSDSC2CT*", NULL, ATA_QUIRK_NO_FUA }, /* End Marker */ { } diff --git a/drivers/ata/libata-scsi.c b/drivers/ata/libata-scsi.c index 023de0e633b7..5be2e2597770 100644 --- a/drivers/ata/libata-scsi.c +++ b/drivers/ata/libata-scsi.c @@ -5422,7 +5422,7 @@ bool ata_scsi_offline_dev(struct ata_device *dev) * ata_scsi_remove_dev - remove attached SCSI device * @dev: ATA device to remove attached SCSI device for * - * This function is called from ata_eh_scsi_hotplug() and + * This function is called from ata_scsi_hotplug() and * responsible for removing the SCSI device attached to @dev. * * LOCKING: diff --git a/drivers/ata/pata_parport/pata_parport.c b/drivers/ata/pata_parport/pata_parport.c index 40baeac594a9..f0fe921a10b4 100644 --- a/drivers/ata/pata_parport/pata_parport.c +++ b/drivers/ata/pata_parport/pata_parport.c @@ -618,8 +618,9 @@ void pata_parport_unregister_driver(struct pi_protocol *pr) break; } idr_remove(&protocols, id); - mutex_unlock(&pi_mutex); driver_unregister(&pr->driver); + mutex_unlock(&pi_mutex); + } EXPORT_SYMBOL_GPL(pata_parport_unregister_driver); @@ -646,18 +647,18 @@ static ssize_t new_device_store(const struct bus_type *bus, const char *buf, siz port_wanted = -1; } + mutex_lock(&pi_mutex); drv = driver_find(protocol, &pata_parport_bus_type); if (!drv) { if (strcmp(protocol, "auto")) { pr_err("protocol %s not found\n", protocol); + mutex_unlock(&pi_mutex); return -EINVAL; } pr_wanted = NULL; } else { pr_wanted = container_of(drv, struct pi_protocol, driver); } - - mutex_lock(&pi_mutex); /* walk all parports */ idr_for_each_entry(&parport_list, parport, port_num) { if (port_num == port_wanted || port_wanted == -1) { @@ -722,7 +723,7 @@ static void pata_parport_attach(struct parport *port) int pr_num, id; mutex_lock(&pi_mutex); - id = idr_alloc(&parport_list, port, port->number, port->number, + id = idr_alloc(&parport_list, port, port->number, port->number + 1, GFP_KERNEL); if (id < 0) { mutex_unlock(&pi_mutex); diff --git a/drivers/ata/sata_dwc_460ex.c b/drivers/ata/sata_dwc_460ex.c index 8e3fc713891a..aa816a1a4c54 100644 --- a/drivers/ata/sata_dwc_460ex.c +++ b/drivers/ata/sata_dwc_460ex.c @@ -1185,11 +1185,14 @@ static int sata_dwc_probe(struct platform_device *ofdev) * error_handler() to execute a dummy Softreset EH session */ err = ata_host_activate(host, irq, sata_dwc_isr, 0, &sata_dwc_sht); - if (err) + if (err) { dev_err(dev, "failed to activate host"); + goto error_out; + } /* Enable SATA Interrupts */ sata_dwc_enable_interrupts(hsdev); + return 0; error_out: diff --git a/drivers/base/node.c b/drivers/base/node.c index 3da91929ad4e..dcdc8626627a 100644 --- a/drivers/base/node.c +++ b/drivers/base/node.c @@ -167,20 +167,19 @@ static struct node_access_nodes *node_init_node_access(struct node *node, dev->parent = &node->dev; dev->release = node_access_release; dev->groups = node_access_node_groups; - if (dev_set_name(dev, "access%u", access)) - goto free; + if (dev_set_name(dev, "access%u", access)) { + kfree(access_node); + return NULL; + } - if (device_register(dev)) - goto free_name; + if (device_register(dev)) { + put_device(dev); + return NULL; + } pm_runtime_no_callbacks(dev); list_add_tail(&access_node->list_node, &node->access_list); return access_node; -free_name: - kfree_const(dev->kobj.name); -free: - kfree(access_node); - return NULL; } #ifdef CONFIG_HMEM_REPORTING diff --git a/drivers/base/power/runtime.c b/drivers/base/power/runtime.c index fab38bc98113..f18d99c8d052 100644 --- a/drivers/base/power/runtime.c +++ b/drivers/base/power/runtime.c @@ -343,6 +343,9 @@ static void __rpm_put_suppliers(struct device *dev, bool try_to_suspend) list_for_each_entry_rcu(link, &dev->links.suppliers, c_node, device_links_read_lock_held()) { + if (!device_link_test(link, DL_FLAG_PM_RUNTIME)) + continue; + pm_runtime_release_supplier(link); if (try_to_suspend) pm_request_idle(link->supplier); @@ -361,7 +364,8 @@ static void rpm_suspend_suppliers(struct device *dev) list_for_each_entry_rcu(link, &dev->links.suppliers, c_node, device_links_read_lock_held()) - pm_request_idle(link->supplier); + if (device_link_test(link, DL_FLAG_PM_RUNTIME)) + pm_request_idle(link->supplier); device_links_read_unlock(idx); } diff --git a/drivers/block/drbd/drbd_main.c b/drivers/block/drbd/drbd_main.c index a2a841c89201..099dff1ea256 100644 --- a/drivers/block/drbd/drbd_main.c +++ b/drivers/block/drbd/drbd_main.c @@ -2163,6 +2163,7 @@ void drbd_destroy_device(struct kref *kref) struct drbd_peer_device *peer_device, *tmp_peer_device; timer_shutdown_sync(&device->request_timer); + timer_shutdown_sync(&device->start_resync_timer); /* paranoia asserts */ D_ASSERT(device, device->open_cnt == 0); diff --git a/drivers/block/drbd/drbd_receiver.c b/drivers/block/drbd/drbd_receiver.c index 2135c14354a8..a405ccdf919e 100644 --- a/drivers/block/drbd/drbd_receiver.c +++ b/drivers/block/drbd/drbd_receiver.c @@ -4096,8 +4096,10 @@ static int receive_uuids(struct drbd_connection *connection, struct packet_info BM_LOCKED_TEST_ALLOWED, NULL); _drbd_uuid_set(device, UI_CURRENT, p_uuid[UI_CURRENT]); _drbd_uuid_set(device, UI_BITMAP, 0); + spin_lock_irq(&device->resource->req_lock); _drbd_set_state(_NS2(device, disk, D_UP_TO_DATE, pdsk, D_UP_TO_DATE), CS_VERBOSE, NULL); + spin_unlock_irq(&device->resource->req_lock); drbd_md_sync(device); updated_uuids = 1; } diff --git a/drivers/block/floppy.c b/drivers/block/floppy.c index 7465e10f36d4..166451c91066 100644 --- a/drivers/block/floppy.c +++ b/drivers/block/floppy.c @@ -1784,6 +1784,9 @@ static void reset_interrupt(void) { debugt(__func__, ""); result(current_fdc); /* get the status ready for set_fdc */ + /* Stale work: unlock_fdc()/do_wakeup() may have cleared cont. */ + if (!cont) + return; if (fdc_state[current_fdc].reset) { pr_info("reset set in interrupt, calling %ps\n", cont->error); cont->error(); /* a reset just after a reset. BAD! */ @@ -4729,8 +4732,11 @@ static int __init do_floppy_init(void) err = device_add_disk(&floppy_device[drive].dev, disks[drive][0], NULL); - if (err) + if (err) { + platform_device_unregister(&floppy_device[drive]); + registered[drive] = false; goto out_remove_drives; + } } return 0; @@ -4744,6 +4750,8 @@ static int __init do_floppy_init(void) } } out_release_dma: + /* Drain the queued redo_fd_request() before releasing IRQ and DMA. */ + flush_workqueue(floppy_wq); if (atomic_read(&usage_count)) floppy_release_irq_and_dma(); out_unreg_driver: diff --git a/drivers/block/rnbd/rnbd-srv-sysfs.c b/drivers/block/rnbd/rnbd-srv-sysfs.c index 64780094442c..9d00c42f2624 100644 --- a/drivers/block/rnbd/rnbd-srv-sysfs.c +++ b/drivers/block/rnbd/rnbd-srv-sysfs.c @@ -44,12 +44,17 @@ int rnbd_srv_create_dev_sysfs(struct rnbd_srv_dev *dev, struct kobject *bdev_kobj; int ret; - ret = kobject_init_and_add(&dev->dev_kobj, &dev_ktype, - rnbd_devs_kobj, "%pg", bdev); - if (ret) { - kobject_put(&dev->dev_kobj); + /* + * The release function frees the device, which the caller goes on + * using and which others may share: never drop the reference of the + * kobject here. That is for destroy_device(). + */ + if (!dev->dev_kobj.state_initialized) + kobject_init(&dev->dev_kobj, &dev_ktype); + + ret = kobject_add(&dev->dev_kobj, rnbd_devs_kobj, "%pg", bdev); + if (ret) return ret; - } dev->dev_sessions_kobj = kobject_create_and_add("sessions", &dev->dev_kobj); @@ -69,7 +74,6 @@ int rnbd_srv_create_dev_sysfs(struct rnbd_srv_dev *dev, kobject_put(dev->dev_sessions_kobj); free_dev_kobj: kobject_del(&dev->dev_kobj); - kobject_put(&dev->dev_kobj); return ret; } @@ -189,6 +193,10 @@ static const struct kobj_type rnbd_srv_sess_dev_ktype = { .release = rnbd_srv_sess_dev_release, }; +/* + * On failure the caller has to drop the reference of the kobject. The release + * function takes the lock of the device, which the caller holds here. + */ int rnbd_srv_create_dev_session_sysfs(struct rnbd_srv_sess_dev *sess_dev) { int ret; @@ -196,17 +204,13 @@ int rnbd_srv_create_dev_session_sysfs(struct rnbd_srv_sess_dev *sess_dev) ret = kobject_init_and_add(&sess_dev->kobj, &rnbd_srv_sess_dev_ktype, sess_dev->dev->dev_sessions_kobj, "%s", sess_dev->sess->sessname); - if (ret) { - kobject_put(&sess_dev->kobj); + if (ret) return ret; - } ret = sysfs_create_group(&sess_dev->kobj, &rnbd_srv_default_dev_session_attr_group); - if (ret) { + if (ret) kobject_del(&sess_dev->kobj); - kobject_put(&sess_dev->kobj); - } return ret; } diff --git a/drivers/block/rnbd/rnbd-srv.c b/drivers/block/rnbd/rnbd-srv.c index 79c9a5fb418f..1c80e8fe0267 100644 --- a/drivers/block/rnbd/rnbd-srv.c +++ b/drivers/block/rnbd/rnbd-srv.c @@ -208,6 +208,9 @@ static void destroy_device(struct kref *kref) * Destroy kobj only if it was really created. */ rnbd_srv_destroy_dev_sysfs(dev); + else if (dev->dev_kobj.state_initialized) + /* The files could not be created. Frees the name, too. */ + kobject_put(&dev->dev_kobj); else kfree(dev); } @@ -357,14 +360,15 @@ static void process_msg_close(struct rnbd_srv_session *srv_sess, trace_process_msg_close(srv_sess, close_msg); - sess_dev = rnbd_get_sess_dev(le32_to_cpu(close_msg->device_id), - srv_sess); - if (IS_ERR(sess_dev)) - return; - - rnbd_put_sess_dev(sess_dev); + /* + * Each teardown of a sess_dev runs under srv_sess->lock and erases the + * ID, so an entry that is found under the lock is alive. + */ mutex_lock(&srv_sess->lock); - rnbd_srv_destroy_dev_session_sysfs(sess_dev); + sess_dev = xa_load(&srv_sess->index_idr, + le32_to_cpu(close_msg->device_id)); + if (sess_dev) + rnbd_srv_destroy_dev_session_sysfs(sess_dev); mutex_unlock(&srv_sess->lock); } @@ -427,7 +431,7 @@ static struct rnbd_srv_sess_dev if (!sess_dev) return ERR_PTR(-ENOMEM); - error = xa_alloc(&srv_sess->index_idr, &sess_dev->device_id, sess_dev, + error = xa_alloc(&srv_sess->index_idr, &sess_dev->device_id, NULL, xa_limit_32b, GFP_NOWAIT); if (error < 0) { pr_warn("Allocating idr failed, err: %d\n", error); @@ -587,6 +591,7 @@ rnbd_srv_create_set_sess_dev(struct rnbd_srv_session *srv_sess, return sdev; kref_init(&sdev->kref); + INIT_LIST_HEAD(&sdev->dev_list); strscpy(sdev->pathname, open_msg->dev_name, sizeof(sdev->pathname)); @@ -786,12 +791,24 @@ static int process_msg_open(struct rnbd_srv_session *srv_sess, rnbd_srv_err(srv_sess_dev, "Opening device failed, failed to create dev client sysfs files, err: %d\n", ret); - goto free_srv_sess_dev; + /* + * rnbd_destroy_sess_dev() undoes everything down to the open + * of the block device. + */ + kobject_put(&srv_sess_dev->kobj); + goto free_path; } list_add(&srv_sess_dev->dev_list, &srv_dev->sess_dev_list); mutex_unlock(&srv_dev->lock); + /* + * Nothing fails from here on, so let I/O messages find the sess_dev. + * The ID is reserved, so this store allocates nothing. + */ + xa_store(&srv_sess->index_idr, srv_sess_dev->device_id, srv_sess_dev, + GFP_KERNEL); + rnbd_srv_info(srv_sess_dev, "Opened device '%s'\n", srv_dev->name); kfree(full_path); @@ -803,7 +820,6 @@ static int process_msg_open(struct rnbd_srv_session *srv_sess, free_srv_sess_dev: xa_erase(&srv_sess->index_idr, srv_sess_dev->device_id); - synchronize_rcu(); kfree(srv_sess_dev); srv_dev_put: if (open_msg->access_mode != RNBD_ACCESS_RO) { diff --git a/drivers/block/rnull/configfs.rs b/drivers/block/rnull/configfs.rs index 32c10c3f4d0f..5f1cdd54cf48 100644 --- a/drivers/block/rnull/configfs.rs +++ b/drivers/block/rnull/configfs.rs @@ -35,7 +35,7 @@ impl AttributeOperations<0> for Config { fn show(_this: &Config, page: &mut [u8; PAGE_SIZE]) -> Result { let mut writer = kernel::str::Formatter::new(page); - writer.write_str("blocksize,size,rotational,irqmode\n")?; + writer.write_str("blocksize,size,rotational,irqmode,power\n")?; Ok(writer.bytes_written()) } } diff --git a/drivers/block/swim.c b/drivers/block/swim.c index 0ccc12a72388..fe46f9656f8a 100644 --- a/drivers/block/swim.c +++ b/drivers/block/swim.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -87,37 +88,37 @@ struct iwm { #define iwm_write(base, reg, v) out_8(&(base)->reg, (v)) #define iwm_read(base, reg) in_8(&(base)->reg) -/* bits in phase register */ +/* Bits in phase register */ -#define SEEK_POSITIVE 0x070 -#define SEEK_NEGATIVE 0x074 -#define STEP 0x071 -#define MOTOR_ON 0x072 -#define MOTOR_OFF 0x076 -#define INDEX 0x073 -#define EJECT 0x077 -#define SETMFM 0x171 -#define SETGCR 0x175 - -#define RELAX 0x033 -#define LSTRB 0x008 - -#define CA_MASK 0x077 +#define RELAX 0x03 +#define LSTRB 0x08 +#define CA_MASK 0x07 +#define PHASE_PIN_DIR 0xF0 /* Select values for swim_select and swim_readbit */ -#define READ_DATA_0 0x074 -#define ONEMEG_DRIVE 0x075 -#define SINGLE_SIDED 0x076 -#define DRIVE_PRESENT 0x077 -#define DISK_IN 0x170 -#define WRITE_PROT 0x171 -#define TRACK_ZERO 0x172 -#define TACHO 0x173 -#define READ_DATA_1 0x174 -#define GCR_MODE 0x175 -#define SEEK_COMPLETE 0x176 -#define TWOMEG_MEDIA 0x177 +#define SEEK_POSITIVE 0x000 +#define SEEK_NEGATIVE 0x004 +#define STEP 0x001 +#define MOTOR_ON 0x002 +#define MOTOR_OFF 0x006 +#define INDEX 0x003 +#define EJECT 0x007 +#define SETMFM 0x101 +#define SETGCR 0x105 + +#define READ_DATA_0 0x004 +#define ONEMEG_DRIVE 0x005 +#define SINGLE_SIDED 0x006 +#define DRIVE_PRESENT 0x007 +#define DISK_IN 0x100 +#define WRITE_PROT 0x101 +#define TRACK_ZERO 0x102 +#define TACHO 0x103 +#define READ_DATA_1 0x104 +#define GCR_MODE 0x105 +#define READY 0x106 +#define TWOMEG_MEDIA 0x107 /* Bits in handshake register */ @@ -149,13 +150,15 @@ struct iwm { #define ACTION 0x08 #define WRITE_MODE 0x10 #define HEDSEL 0x20 +#define ISM_SELECT 0x40 #define MOTON 0x80 /*----------------------------------------------------------------------------*/ enum drive_location { - INTERNAL_DRIVE = 0x02, - EXTERNAL_DRIVE = 0x04, + NO_DRIVE = 0, + INTERNAL_DRIVE = BIT(1), + EXTERNAL_DRIVE = BIT(2), }; enum media_type { @@ -209,7 +212,6 @@ enum head { struct swim_priv { struct swim __iomem *base; - spinlock_t lock; int floppy_count; struct floppy_state unit[FD_MAX_UNIT]; }; @@ -222,18 +224,21 @@ extern int swim_read_sector_data(struct swim __iomem *base, static DEFINE_MUTEX(swim_mutex); static inline void set_swim_mode(struct swim __iomem *base, int enable) { - struct iwm __iomem *iwm_base; + struct iwm __iomem *iwm_base = (struct iwm __iomem *)base; unsigned long flags; if (!enable) { - swim_write(base, mode0, 0xf8); + swim_write(base, mode0, ACTION); + swim_write(base, mode0, ENBL1 | ENBL2 | MOTON); + swim_write(base, mode0, ISM_SELECT); + iwm_read(iwm_base, q7L); return; } - iwm_base = (struct iwm __iomem *)base; local_irq_save(flags); iwm_read(iwm_base, q7L); + iwm_read(iwm_base, q6L); iwm_read(iwm_base, mtrOff); iwm_read(iwm_base, q6H); @@ -269,11 +274,11 @@ static inline int get_swim_mode(struct swim __iomem *base) static inline void swim_select(struct swim __iomem *base, int sel) { - swim_write(base, phase, RELAX); + swim_write(base, phase, RELAX | PHASE_PIN_DIR); via1_set_head(sel & 0x100); - swim_write(base, phase, sel & CA_MASK); + swim_write(base, phase, (sel & CA_MASK) | PHASE_PIN_DIR); } static inline void swim_action(struct swim __iomem *base, int action) @@ -284,15 +289,15 @@ static inline void swim_action(struct swim __iomem *base, int action) swim_select(base, action); udelay(1); - swim_write(base, phase, (LSTRB<<4) | LSTRB); - udelay(1); - swim_write(base, phase, (LSTRB<<4) | ((~LSTRB) & 0x0F)); + swim_write(base, phase, LSTRB | action | PHASE_PIN_DIR); + udelay(2); + swim_write(base, phase, action | PHASE_PIN_DIR); udelay(1); local_irq_restore(flags); } -static inline int swim_readbit(struct swim __iomem *base, int bit) +static inline bool swim_readbit(struct swim __iomem *base, int bit) { int stat; @@ -305,59 +310,57 @@ static inline int swim_readbit(struct swim __iomem *base, int bit) return (stat & SENSE) == 0; } +#define swim_readbit_timeout(base, bit, val, timeout_us) \ + poll_timeout_us(, swim_readbit(base, bit) == val, 1000, timeout_us, false) + +#define swim_READY_timeout(base) \ +({ \ + int ret = swim_readbit_timeout(base, READY, true, 1000 * 1000); \ + if (ret) \ + printk(KERN_DEBUG "%s: drive not ready\n", __func__); \ + ret; \ +}) + static inline void swim_drive(struct swim __iomem *base, enum drive_location location) { if (location == INTERNAL_DRIVE) { swim_write(base, mode0, EXTERNAL_DRIVE); /* clear drive 1 bit */ swim_write(base, mode1, INTERNAL_DRIVE); /* set drive 0 bit */ + swim_write(base, mode1, MOTON); } else if (location == EXTERNAL_DRIVE) { swim_write(base, mode0, INTERNAL_DRIVE); /* clear drive 0 bit */ swim_write(base, mode1, EXTERNAL_DRIVE); /* set drive 1 bit */ + swim_write(base, mode1, MOTON); + } else { + swim_write(base, mode0, INTERNAL_DRIVE); + swim_write(base, mode0, EXTERNAL_DRIVE); + swim_write(base, mode0, MOTON); } + udelay(1); } static inline void swim_motor(struct swim __iomem *base, enum motor_action action) { if (action == ON) { - int i; - swim_action(base, MOTOR_ON); - - for (i = 0; i < 2*HZ; i++) { - swim_select(base, RELAX); - if (swim_readbit(base, MOTOR_ON)) - break; - set_current_state(TASK_INTERRUPTIBLE); - schedule_timeout(1); - } + swim_readbit_timeout(base, MOTOR_ON, true, 2000 * 1000); } else if (action == OFF) { swim_action(base, MOTOR_OFF); - swim_select(base, RELAX); + swim_write(base, phase, RELAX | PHASE_PIN_DIR); } } static inline void swim_eject(struct swim __iomem *base) { - int i; - swim_action(base, EJECT); - - for (i = 0; i < 2*HZ; i++) { - swim_select(base, RELAX); - if (!swim_readbit(base, DISK_IN)) - break; - set_current_state(TASK_INTERRUPTIBLE); - schedule_timeout(1); - } - swim_select(base, RELAX); + swim_readbit_timeout(base, DISK_IN, false, 2000 * 1000); + msleep(1); } static inline void swim_head(struct swim __iomem *base, enum head head) { - /* wait drive is ready */ - if (head == UPPER_HEAD) swim_select(base, READ_DATA_1); else if (head == LOWER_HEAD) @@ -366,20 +369,9 @@ static inline void swim_head(struct swim __iomem *base, enum head head) static inline int swim_step(struct swim __iomem *base) { - int wait; - swim_action(base, STEP); - - for (wait = 0; wait < HZ; wait++) { - - set_current_state(TASK_INTERRUPTIBLE); - schedule_timeout(1); - - swim_select(base, RELAX); - if (!swim_readbit(base, STEP)) - return 0; - } - return -1; + udelay(150); + return swim_readbit_timeout(base, STEP, false, 20 * 1000); } static inline int swim_track00(struct swim __iomem *base) @@ -389,37 +381,41 @@ static inline int swim_track00(struct swim __iomem *base) swim_action(base, SEEK_NEGATIVE); for (try = 0; try < 100; try++) { + msleep(3); - swim_select(base, RELAX); if (swim_readbit(base, TRACK_ZERO)) - break; + return 0; if (swim_step(base)) - return -1; + break; } - if (swim_readbit(base, TRACK_ZERO)) - return 0; - + pr_err("swim: track zero recalibration failed\n"); return -1; } static inline int swim_seek(struct swim __iomem *base, int step) { - if (step == 0) - return 0; - if (step < 0) { swim_action(base, SEEK_NEGATIVE); step = -step; - } else + } else if (step > 0) swim_action(base, SEEK_POSITIVE); + udelay(1); + + swim_READY_timeout(base); + + if (step == 0) + return 0; for ( ; step > 0; step--) { if (swim_step(base)) return -1; } + msleep(30); + swim_READY_timeout(base); + return 0; } @@ -445,8 +441,10 @@ static int floppy_eject(struct floppy_state *fs) struct swim __iomem *base = fs->swd->base; swim_drive(base, fs->location); + swim_track(fs, 40); swim_motor(base, OFF); swim_eject(base); + swim_drive(base, NO_DRIVE); fs->disk_in = 0; fs->ejected = 1; @@ -465,29 +463,26 @@ static inline int swim_read_sector(struct floppy_state *fs, short i; swim_track(fs, track); - - swim_write(base, mode1, MOTON); swim_head(base, side); swim_write(base, mode0, side); local_irq_save(flags); for (i = 0; i < 36; i++) { - ret = swim_read_sector_header(base, &header); - if (!ret && (header.sector == sector)) { + if (swim_read_sector_header(base, &header) || + swim_read(base, error) || header.track != track || + header.side != side || header.size != 2) + continue; + if (header.sector == sector) { /* found */ ret = swim_read_sector_data(base, buffer); + if (swim_read(base, error)) + ret = -EIO; break; } } local_irq_restore(flags); - swim_write(base, mode0, MOTON); - - if ((header.side != side) || (header.track != track) || - (header.sector != sector)) - return 0; - return ret; } @@ -502,6 +497,8 @@ static blk_status_t floppy_read_sectors(struct floppy_state *fs, swim_drive(base, fs->location); + swim_READY_timeout(base); + for (i = req_sector; i < req_sector + sectors_nb; i++) { int x; track = i / fs->secpercyl; @@ -527,12 +524,10 @@ static blk_status_t swim_queue_rq(struct blk_mq_hw_ctx *hctx, const struct blk_mq_queue_data *bd) { struct floppy_state *fs = hctx->queue->queuedata; - struct swim_priv *swd = fs->swd; struct request *req = bd->rq; blk_status_t err; - if (!spin_trylock_irq(&swd->lock)) - return BLK_STS_DEV_RESOURCE; + mutex_lock(&swim_mutex); blk_mq_start_request(req); @@ -550,7 +545,7 @@ static blk_status_t swim_queue_rq(struct blk_mq_hw_ctx *hctx, err = BLK_STS_OK; out: - spin_unlock_irq(&swd->lock); + mutex_unlock(&swim_mutex); return err; } @@ -588,13 +583,6 @@ static void setup_medium(struct floppy_state *fs) struct floppy_struct *g; fs->disk_in = 1; fs->write_protected = swim_readbit(base, WRITE_PROT); - - if (swim_track00(base)) - printk(KERN_ERR - "SWIM: cannot move floppy head to track 0\n"); - - swim_track00(base); - fs->type = swim_readbit(base, TWOMEG_MEDIA) ? HD_MEDIA : DD_MEDIA; fs->head_number = swim_readbit(base, SINGLE_SIDED) ? 1 : 2; @@ -602,7 +590,6 @@ static void setup_medium(struct floppy_state *fs) fs->total_secs = g->size; fs->secpercyl = g->head * g->sect; fs->secpertrack = g->sect; - fs->track = 0; } else { fs->disk_in = 0; } @@ -620,11 +607,9 @@ static int floppy_open(struct gendisk *disk, blk_mode_t mode) fs->ref_count = -1; else fs->ref_count++; - swim_write(base, setup, S_IBM_DRIVE | S_FCLK_DIV2); - udelay(10); + swim_drive(base, fs->location); - swim_motor(base, ON); - swim_action(base, SETMFM); + if (fs->ejected) setup_medium(fs); if (!fs->disk_in) { @@ -632,6 +617,11 @@ static int floppy_open(struct gendisk *disk, blk_mode_t mode) goto out; } + swim_motor(base, ON); + swim_action(base, SETMFM); + msleep(30); + swim_READY_timeout(base); + set_capacity(fs->disk, fs->total_secs); if (mode & BLK_OPEN_NDELAY) @@ -640,7 +630,8 @@ static int floppy_open(struct gendisk *disk, blk_mode_t mode) if (mode & (BLK_OPEN_READ | BLK_OPEN_WRITE)) { if (disk_check_media_change(disk) && fs->disk_in) fs->ejected = 0; - if ((mode & BLK_OPEN_WRITE) && fs->write_protected) { + if (mode & BLK_OPEN_WRITE) { + /* Write support isn't implemented. */ err = -EROFS; goto out; } @@ -652,8 +643,10 @@ static int floppy_open(struct gendisk *disk, blk_mode_t mode) else if (fs->ref_count > 0) --fs->ref_count; - if (fs->ref_count == 0) + if (fs->ref_count == 0) { swim_motor(base, OFF); + swim_drive(base, NO_DRIVE); + } return err; } @@ -679,8 +672,11 @@ static void floppy_release(struct gendisk *disk) else if (fs->ref_count > 0) --fs->ref_count; - if (fs->ref_count == 0) + if (fs->ref_count == 0) { + swim_drive(base, fs->location); swim_motor(base, OFF); + swim_drive(base, NO_DRIVE); + } mutex_unlock(&swim_mutex); } @@ -695,10 +691,11 @@ static int floppy_ioctl(struct block_device *bdev, blk_mode_t mode, switch (cmd) { case FDEJECT: - if (fs->ref_count != 1) - return -EBUSY; mutex_lock(&swim_mutex); - err = floppy_eject(fs); + if (fs->ref_count == -1 || fs->ref_count == 1) + err = floppy_eject(fs); + else + err = -EBUSY; mutex_unlock(&swim_mutex); return err; @@ -745,26 +742,33 @@ static const struct block_device_operations floppy_fops = { .check_events = floppy_check_events, }; -static int swim_add_floppy(struct swim_priv *swd, enum drive_location location) +static void swim_add_floppy(struct swim_priv *swd, enum drive_location location) { struct floppy_state *fs = &swd->unit[swd->floppy_count]; struct swim __iomem *base = swd->base; - fs->location = location; - swim_drive(base, location); + if (!swim_readbit(base, DRIVE_PRESENT) || + swim_readbit(base, ONEMEG_DRIVE)) + goto out; + if (swim_readbit(base, DISK_IN)) + swim_motor(base, ON); + if (swim_track00(base)) + goto out; - swim_motor(base, OFF); + fs->location = location; fs->type = HD_MEDIA; fs->head_number = 2; fs->ref_count = 0; fs->ejected = 1; + fs->track = 0; swd->floppy_count++; - return 0; +out: + swim_motor(base, OFF); } static const struct blk_mq_ops swim_mq_ops = { @@ -785,8 +789,22 @@ static void swim_cleanup_floppy_disk(struct floppy_state *fs) blk_mq_free_tag_set(&fs->tag_set); } -static int swim_floppy_init(struct swim_priv *swd) +static void swim_set_parameters(struct swim __iomem *base) { + unsigned int i; + static const u8 mem[] = { 0x18, 0x41, 0x2e, 0x2e, 0x18, 0x18, 0x1b, 0x1b, + 0x2f, 0x2f, 0x19, 0x19, 0x97, 0x1b, 0x57, 0x3b, }; + + swim_write(base, mode0, 0); /* reset parameter memory index */ + for (i = 0; i < 16; ++i) + swim_write(base, parameter, mem[i]); +} + +static int swim_floppy_init(struct platform_device *pdev) +{ + struct swim_priv *swd = platform_get_drvdata(pdev); + bool *data = pdev->dev.platform_data; + bool fast_fclk = data && *data; struct queue_limits lim = { .features = BLK_FEAT_ROTATIONAL, }; @@ -794,16 +812,15 @@ static int swim_floppy_init(struct swim_priv *swd) int drive; struct swim __iomem *base = swd->base; + swim_write(base, setup, S_IBM_DRIVE | (fast_fclk ? S_FCLK_DIV2 : 0)); + + swim_set_parameters(base); + /* scan floppy drives */ - swim_drive(base, INTERNAL_DRIVE); - if (swim_readbit(base, DRIVE_PRESENT) && - !swim_readbit(base, ONEMEG_DRIVE)) - swim_add_floppy(swd, INTERNAL_DRIVE); - swim_drive(base, EXTERNAL_DRIVE); - if (swim_readbit(base, DRIVE_PRESENT) && - !swim_readbit(base, ONEMEG_DRIVE)) - swim_add_floppy(swd, EXTERNAL_DRIVE); + swim_add_floppy(swd, INTERNAL_DRIVE); + swim_add_floppy(swd, EXTERNAL_DRIVE); + swim_drive(base, NO_DRIVE); /* register floppy drives */ @@ -814,11 +831,9 @@ static int swim_floppy_init(struct swim_priv *swd) return -EBUSY; } - spin_lock_init(&swd->lock); - for (drive = 0; drive < swd->floppy_count; drive++) { err = blk_mq_alloc_sq_tag_set(&swd->unit[drive].tag_set, - &swim_mq_ops, 2, 0); + &swim_mq_ops, 2, BLK_MQ_F_BLOCKING); if (err) goto exit_put_disks; @@ -905,7 +920,7 @@ static int swim_probe(struct platform_device *dev) swd->base = swim_base; - ret = swim_floppy_init(swd); + ret = swim_floppy_init(dev); if (ret) goto out_kfree; diff --git a/drivers/block/swim3.c b/drivers/block/swim3.c index d4f0d43e0a72..a03de4c4d35f 100644 --- a/drivers/block/swim3.c +++ b/drivers/block/swim3.c @@ -887,7 +887,6 @@ static int floppy_locked_ioctl(struct block_device *bdev, blk_mode_t mode, unsigned int cmd, unsigned long param) { struct floppy_state *fs = bdev->bd_disk->private_data; - int err; if ((cmd & 0x80) && !capable(CAP_SYS_ADMIN)) return -EPERM; @@ -898,10 +897,9 @@ static int floppy_locked_ioctl(struct block_device *bdev, blk_mode_t mode, switch (cmd) { case FDEJECT: - if (fs->ref_count != 1) - return -EBUSY; - err = fd_eject(fs); - return err; + if (fs->ref_count == -1 || fs->ref_count == 1) + return fd_eject(fs); + return -EBUSY; case FDGETPRM: if (copy_to_user((void __user *) param, &floppy_type, sizeof(struct floppy_struct))) diff --git a/drivers/block/swim_asm.S b/drivers/block/swim_asm.S index 3d7a2d87595a..4d6404234bf0 100644 --- a/drivers/block/swim_asm.S +++ b/drivers/block/swim_asm.S @@ -41,14 +41,46 @@ .equ seek_time, 30000 .equ max_retry, 40 .equ sector_size, 512 + .equ .Lmark_sequence_len, 4 + + .equ .Lhr_crc_error, 0x02 + .equ .Lhr_fifo_2bytes, 0x40 + .equ .Lhr_fifo_1byte, 0x80 + +.Lmfm_mark_check: + /* + * This subroutine reads and validates a mark byte sequence. + * On entry, %a1 and %d4 shall hold the location and length (resp.) + * of the mark byte array. + * %a2 and %a3 shall hold the locations of the handshake and mark + * registers. + * Returns zero in %d1 for success. + */ + + moveq #-1, %d1 + subq #1, %d4 + movew #seek_time, %d2 + +5: tstb %a2@ + dbmi %d2, 5b + bpl 6f + + moveb %a3@, %d3 + cmpb %a1@+, %d3 + dbne %d4, 5b + bne 6f + + moveq #0, %d1 +6: rts .global swim_read_sector_header swim_read_sector_header: link %a6, #0 - moveml %d1-%d5/%a0-%a4,%sp@- + moveml %d1-%d5/%a0-%a5,%sp@- movel %a6@(0x0c), %a4 - bsr mfm_read_addrmark - moveml %sp@+, %d1-%d5/%a0-%a4 + moveq #-1, %d0 + bsr .Lmfm_read_header + moveml %sp@+, %d1-%d5/%a0-%a5 unlk %a6 rts @@ -57,34 +89,25 @@ sector_address_mark: sector_data_mark: .byte 0xa1, 0xa1, 0xa1, 0xfb -mfm_read_addrmark: +.Lmfm_read_header: movel %a6@(0x08), %a3 lea %a3@(read_handshake), %a2 + lea %a3@(read_data), %a5 lea %a3@(read_mark), %a3 - moveq #-1, %d0 - movew #seek_time, %d2 -wait_header_init: - tstb %a3@(read_error - read_mark) moveb #0x18, %a3@(write_mode0 - read_mark) moveb #0x01, %a3@(write_mode1 - read_mark) moveb #0x01, %a3@(write_mode0 - read_mark) tstb %a3@(read_error - read_mark) moveb #0x08, %a3@(write_mode1 - read_mark) - lea sector_address_mark, %a0 - moveq #3, %d1 - -wait_addr_mark_byte: + lea sector_address_mark, %a1 + moveq #.Lmark_sequence_len, %d4 + bsr .Lmfm_mark_check + tstl %d1 + bne signal_nonyb - tstb %a2@ - dbmi %d2, wait_addr_mark_byte - bpl header_exit - - moveb %a3@, %d3 - cmpb %a0@+, %d3 - dbne %d1, wait_addr_mark_byte - bne wait_header_init + /* read header */ moveq #max_retry, %d2 @@ -92,7 +115,7 @@ amark0: tstb %a2@ dbmi %d2, amark0 bpl signal_nonyb - moveb %a3@, %a4@(o_track) + moveb %a5@, %a4@(o_track) moveq #max_retry, %d2 @@ -100,7 +123,7 @@ amark1: tstb %a2@ dbmi %d2, amark1 bpl signal_nonyb - moveb %a3@, %a4@(o_side) + moveb %a5@, %a4@(o_side) moveq #max_retry, %d2 @@ -108,7 +131,7 @@ amark2: tstb %a2@ dbmi %d2, amark2 bpl signal_nonyb - moveb %a3@, %a4@(o_sector) + moveb %a5@, %a4@(o_sector) moveq #max_retry, %d2 @@ -116,7 +139,7 @@ amark3: tstb %a2@ dbmi %d2, amark3 bpl signal_nonyb - moveb %a3@, %a4@(o_size) + moveb %a5@, %a4@(o_size) moveq #max_retry, %d2 @@ -124,7 +147,7 @@ crc0: tstb %a2@ dbmi %d2, crc0 bpl signal_nonyb - moveb %a3@, %a4@(o_crc0) + moveb %a5@, %a4@(o_crc0) moveq #max_retry, %d2 @@ -132,16 +155,14 @@ crc1: tstb %a2@ dbmi %d2, crc1 bpl signal_nonyb - moveb %a3@, %a4@(o_crc1) + moveb %a5@, %a4@(o_crc1) - tstb %a3@(read_error - read_mark) + moveb %a2@, %d5 + andb #.Lhr_crc_error, %d5 + bne signal_nonyb -header_exit: moveq #0, %d0 - moveb #0x18, %a3@(write_mode0 - read_mark) - rts signal_nonyb: - moveq #-1, %d0 moveb #0x18, %a3@(write_mode0 - read_mark) rts @@ -150,6 +171,7 @@ swim_read_sector_data: link %a6, #0 moveml %d1-%d5/%a0-%a5,%sp@- movel %a6@(0x0c), %a4 + moveq #-1, %d0 bsr mfm_read_data moveml %sp@+, %d1-%d5/%a0-%a5 unlk %a6 @@ -160,51 +182,36 @@ mfm_read_data: lea %a3@(read_handshake), %a2 lea %a3@(read_data), %a5 lea %a3@(read_mark), %a3 - movew #seek_time, %d2 -wait_data_init: - tstb %a3@(read_error - read_mark) moveb #0x18, %a3@(write_mode0 - read_mark) moveb #0x01, %a3@(write_mode1 - read_mark) moveb #0x01, %a3@(write_mode0 - read_mark) tstb %a3@(read_error - read_mark) moveb #0x08, %a3@(write_mode1 - read_mark) - lea sector_data_mark, %a0 - moveq #3, %d1 - - /* wait data address mark */ - -wait_data_mark_byte: - - tstb %a2@ - dbmi %d2, wait_data_mark_byte - bpl data_exit - - moveb %a3@, %d3 - cmpb %a0@+, %d3 - dbne %d1, wait_data_mark_byte - bne wait_data_init + lea sector_data_mark, %a1 + moveq #.Lmark_sequence_len, %d4 + bsr .Lmfm_mark_check + tstl %d1 + bne data_exit /* read data */ - tstb %a3@(read_error - read_mark) - movel #sector_size-1, %d4 /* sector size */ -read_new_data: movew #max_retry, %d2 read_data_loop: moveb %a2@, %d5 - andb #0xc0, %d5 + andb #(.Lhr_fifo_1byte + .Lhr_fifo_2bytes), %d5 dbne %d2, read_data_loop beq data_exit + moveq #max_retry, %d2 moveb %a5@, %a4@+ - andb #0x40, %d5 - dbne %d4, read_new_data - beq exit_loop + dbra %d4, 1f + bra data_crc0 +1: andb #.Lhr_fifo_2bytes, %d5 + beq read_data_loop moveb %a5@, %a4@+ - dbra %d4, read_new_data -exit_loop: + dbra %d4, read_data_loop /* read CRC */ @@ -215,7 +222,7 @@ data_crc0: dbmi %d2, data_crc0 bpl data_exit - moveb %a3@, %d5 + moveb %a5@, %d5 moveq #max_retry, %d2 @@ -225,19 +232,18 @@ data_crc1: dbmi %d2, data_crc1 bpl data_exit - moveb %a3@, %d5 - - tstb %a3@(read_error - read_mark) + moveb %a5@, %d5 - moveb #0x18, %a3@(write_mode0 - read_mark) + moveb %a2@, %d5 + andb #.Lhr_crc_error, %d5 + bne data_exit /* return number of bytes read */ movel #sector_size, %d0 addw #1, %d4 subl %d4, %d0 - rts + data_exit: moveb #0x18, %a3@(write_mode0 - read_mark) - moveq #-1, %d0 rts diff --git a/drivers/block/ublk_drv.c b/drivers/block/ublk_drv.c index 959e6594013a..cc4e72fd5d4d 100644 --- a/drivers/block/ublk_drv.c +++ b/drivers/block/ublk_drv.c @@ -696,7 +696,7 @@ static int ublk_report_zones(struct gendisk *disk, sector_t sector, if (!zone->len) break; - ret = disk_report_zone(disk, zone, i, args); + ret = disk_report_zone(disk, zone, done_zones, args); if (ret) goto out; @@ -2910,6 +2910,7 @@ static void ublk_uring_cmd_cancel_fn(struct io_uring_cmd *cmd, { struct ublk_uring_cmd_pdu *pdu = ublk_get_uring_cmd_pdu(cmd); struct ublk_queue *ubq = pdu->ubq; + struct io_uring_cmd *cur; struct task_struct *task; struct ublk_io *io; @@ -2926,7 +2927,9 @@ static void ublk_uring_cmd_cancel_fn(struct io_uring_cmd *cmd, ublk_start_cancel(ubq->dev); - WARN_ON_ONCE(io->cmd != cmd); + /* NULL if a cancel from the control path took it meanwhile */ + cur = READ_ONCE(io->cmd); + WARN_ON_ONCE(cur && cur != cmd); ublk_cancel_cmd(ubq, pdu->tag, issue_flags); } @@ -5738,6 +5741,8 @@ static bool ublk_try_buf_match(struct ublk_device *ub, unsigned long expected_offset = 0; bool first = true; + guard(rcu)(); + rq_for_each_bvec(bv, rq, iter) { unsigned long pfn = page_to_pfn(bv.bv_page); unsigned long end_pfn = pfn + diff --git a/drivers/block/xen-blkback/blkback.c b/drivers/block/xen-blkback/blkback.c index 7871099bc0d4..88526e349ce1 100644 --- a/drivers/block/xen-blkback/blkback.c +++ b/drivers/block/xen-blkback/blkback.c @@ -1021,6 +1021,13 @@ static void xen_blk_drain_io(struct xen_blkif_ring *ring) struct xen_blkif *blkif = ring->blkif; atomic_set(&blkif->drain, 1); + /* + * Publish drain before checking inflight. Otherwise, + * xen_blkbk_unmap_and_respond_callback() can decrement inflight with + * atomic_dec_and_test() and still see drain == 0 after this path saw + * inflight > 0, missing the completion. + */ + smp_mb(); do { if (atomic_read(&ring->inflight) == 0) break; diff --git a/drivers/block/zloop.c b/drivers/block/zloop.c index 394dc2408ed7..e02a5249ae60 100644 --- a/drivers/block/zloop.c +++ b/drivers/block/zloop.c @@ -1097,8 +1097,6 @@ static int zloop_init_zone(struct zloop_device *zlo, struct zloop_options *opts, { struct zloop_zone *zone = &zlo->zones[zone_no]; int oflags = O_RDWR; - struct kstat stat; - sector_t file_sectors; int ret; mutex_init(&zone->lock); @@ -1112,38 +1110,49 @@ static int zloop_init_zone(struct zloop_device *zlo, struct zloop_options *opts, if (!opts->buffered_io) oflags |= O_DIRECT; + zone->file = zloop_filp_open_fmt(oflags, 0600, "%s/%u/%s-%06u", + zlo->base_dir, zlo->id, + zone_no < zlo->nr_conv_zones ? "cnv" : "seq", + zone_no); + if (IS_ERR(zone->file)) { + pr_err("Failed to open zone %u file %s/%u/%s-%06u (err=%ld)", + zone_no, zlo->base_dir, zlo->id, + zone_no < zlo->nr_conv_zones ? "cnv" : "seq", + zone_no, PTR_ERR(zone->file)); + return PTR_ERR(zone->file); + } + + if (!zone->file->f_op->read_iter || !zone->file->f_op->write_iter) { + ret = -EINVAL; + goto out_fput; + } + + if (!zlo->block_size) { + ret = zloop_get_block_size(zlo, zone); + if (ret) + goto out_fput; + } + if (zone_no < zlo->nr_conv_zones) { + sector_t file_sectors; + struct kstat stat; + /* Conventional zone file. */ set_bit(ZLOOP_ZONE_CONV, &zone->flags); zone->cond = BLK_ZONE_COND_NOT_WP; zone->wp = U64_MAX; - zone->file = zloop_filp_open_fmt(oflags, 0600, "%s/%u/cnv-%06u", - zlo->base_dir, zlo->id, zone_no); - if (IS_ERR(zone->file)) { - pr_err("Failed to open zone %u file %s/%u/cnv-%06u (err=%ld)", - zone_no, zlo->base_dir, zlo->id, zone_no, - PTR_ERR(zone->file)); - return PTR_ERR(zone->file); - } - - if (!zlo->block_size) { - ret = zloop_get_block_size(zlo, zone); - if (ret) - return ret; - } - ret = vfs_getattr(&zone->file->f_path, &stat, STATX_SIZE, 0); if (ret < 0) { pr_err("Failed to get zone %u file stat\n", zone_no); - return ret; + goto out_fput; } file_sectors = stat.size >> SECTOR_SHIFT; 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); - return ret; + goto out_fput; } ret = vfs_truncate(&zone->file->f_path, @@ -1151,34 +1160,21 @@ static int zloop_init_zone(struct zloop_device *zlo, struct zloop_options *opts, if (ret < 0) { pr_err("Failed to truncate zone %u file (err=%d)\n", zone_no, ret); - return ret; + goto out_fput; } - - return 0; - } - - /* Sequential zone file. */ - zone->file = zloop_filp_open_fmt(oflags, 0600, "%s/%u/seq-%06u", - zlo->base_dir, zlo->id, zone_no); - if (IS_ERR(zone->file)) { - pr_err("Failed to open zone %u file %s/%u/seq-%06u (err=%ld)", - zone_no, zlo->base_dir, zlo->id, zone_no, - PTR_ERR(zone->file)); - return PTR_ERR(zone->file); - } - - if (!zlo->block_size) { - ret = zloop_get_block_size(zlo, zone); + } else { + /* Sequential zone file. */ + mutex_lock(&zone->lock); + ret = zloop_update_seq_zone(zlo, zone_no); + mutex_unlock(&zone->lock); if (ret) - return ret; + goto out_fput; } - zloop_get_block_size(zlo, zone); - - mutex_lock(&zone->lock); - ret = zloop_update_seq_zone(zlo, zone_no); - mutex_unlock(&zone->lock); + return 0; +out_fput: + fput(zone->file); return ret; } diff --git a/drivers/block/zram/zram_drv.c b/drivers/block/zram/zram_drv.c index 4ba0f77b2abd..30f11e36d19c 100644 --- a/drivers/block/zram/zram_drv.c +++ b/drivers/block/zram/zram_drv.c @@ -1547,68 +1547,70 @@ 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; - unsigned long index; - ssize_t 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; - - guard(rwsem_read)(&zram->dev_lock); - if (!init_done(zram)) { - kvfree(kbuf); - return -EINVAL; - } + down_read(&zram->dev_lock); + 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; + return pos; +} - slot_lock(zram, index); - if (!slot_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; - copied = snprintf(kbuf + written, count, - "%12lu %12u.%06d %c%c%c%c%c%c\n", - index, zram->table[index].attr.ac_time, 0, - test_slot_flag(zram, index, ZRAM_SAME) ? 's' : '.', - test_slot_flag(zram, index, ZRAM_WB) ? 'w' : '.', - test_slot_flag(zram, index, ZRAM_HUGE) ? 'h' : '.', - test_slot_flag(zram, index, ZRAM_IDLE) ? 'i' : '.', - get_slot_comp_priority(zram, index) ? 'r' : '.', - test_slot_flag(zram, index, - ZRAM_INCOMPRESSIBLE) ? 'n' : '.'); - - if (count <= copied) { - slot_unlock(zram, index); - break; - } - written += copied; - count -= copied; -next: - 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; - if (copy_to_user(buf, kbuf, written)) - written = -EFAULT; - kvfree(kbuf); + up_read(&zram->dev_lock); +} + +static int zram_block_state_show(struct seq_file *seq, void *v) +{ + struct zram *zram = seq->private; + unsigned long index = *(loff_t *)v; + + slot_lock(zram, index); + if (slot_allocated(zram, index)) { + seq_printf(seq, "%12lu %12u.%06d %c%c%c%c%c%c\n", + index, zram->table[index].attr.ac_time, 0, + test_slot_flag(zram, index, ZRAM_SAME) ? 's' : '.', + test_slot_flag(zram, index, ZRAM_WB) ? 'w' : '.', + test_slot_flag(zram, index, ZRAM_HUGE) ? 'h' : '.', + test_slot_flag(zram, index, ZRAM_IDLE) ? 'i' : '.', + get_slot_comp_priority(zram, index) ? 'r' : '.', + test_slot_flag(zram, index, + ZRAM_INCOMPRESSIBLE) ? 'n' : '.'); + } + slot_unlock(zram, index); - return written; + 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) { @@ -1618,7 +1620,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/Makefile b/drivers/bluetooth/Makefile index e6b1c1180d1d..8b436c6de8b7 100644 --- a/drivers/bluetooth/Makefile +++ b/drivers/bluetooth/Makefile @@ -51,4 +51,6 @@ hci_uart-$(CONFIG_BT_HCIUART_MRVL) += hci_mrvl.o hci_uart-$(CONFIG_BT_HCIUART_AML) += hci_aml.o hci_uart-objs := $(hci_uart-y) +btusb-y := btusb_main.o + CONTEXT_ANALYSIS := y diff --git a/drivers/bluetooth/btintel.c b/drivers/bluetooth/btintel.c index c69a5d226e88..4871a552d3aa 100644 --- a/drivers/bluetooth/btintel.c +++ b/drivers/bluetooth/btintel.c @@ -66,6 +66,7 @@ static struct { const char *driver_name; u8 hw_variant; u32 fw_build_num; + u32 fw_sha; } coredump_info; const guid_t btintel_guid_dsm = @@ -569,6 +570,7 @@ int btintel_version_info_tlv(struct hci_dev *hdev, coredump_info.hw_variant = INTEL_HW_VARIANT(version->cnvi_bt); coredump_info.fw_build_num = version->build_num; + coredump_info.fw_sha = version->git_sha1; bt_dev_info(hdev, "%s timestamp %u.%u buildtype %u build %u", variant, 2000 + (version->timestamp >> 8), version->timestamp & 0xff, @@ -749,6 +751,7 @@ static int btintel_read_version_tlv(struct hci_dev *hdev, return -EIO; } + memset(version, 0, sizeof(*version)); err = btintel_parse_version_tlv(hdev, version, skb); kfree_skb(skb); @@ -2382,6 +2385,7 @@ static int btintel_prepare_fw_download_tlv(struct hci_dev *hdev, struct intel_version_tlv *ver, u32 *boot_param) { + struct btintel_data *intel_data = hci_get_priv(hdev); const struct firmware *fw; char fwname[128]; int err; @@ -2494,6 +2498,7 @@ static int btintel_prepare_fw_download_tlv(struct hci_dev *hdev, btintel_reset_to_bootloader(hdev); done: + intel_data->cnvi_bt = ver->cnvi_bt; release_firmware(fw); return err; } @@ -3531,6 +3536,9 @@ int btintel_bootloader_setup_tlv(struct hci_dev *hdev, btintel_version_info_tlv(hdev, &new_ver); + /* Update ver with the operational firmware version */ + *ver = new_ver; + finish: /* Set the event mask for Intel specific vendor events. This enables * a few extra events that are useful during general operation. It diff --git a/drivers/bluetooth/btintel.h b/drivers/bluetooth/btintel.h index 966ec1b02be2..ef232820c31b 100644 --- a/drivers/bluetooth/btintel.h +++ b/drivers/bluetooth/btintel.h @@ -247,6 +247,7 @@ enum { struct btintel_data { DECLARE_BITMAP(flags, __INTEL_NUM_FLAGS); int (*acpi_reset_method)(struct hci_dev *hdev); + u32 cnvi_bt; }; #define btintel_set_flag(hdev, nr) \ diff --git a/drivers/bluetooth/btintel_pcie.c b/drivers/bluetooth/btintel_pcie.c index ac7193400769..85141532de60 100644 --- a/drivers/bluetooth/btintel_pcie.c +++ b/drivers/bluetooth/btintel_pcie.c @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -73,17 +74,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 - -#define BTINTEL_PCIE_SCP_HWEXP_SIZE 4096 -#define BTINTEL_PCIE_SCP_HWEXP_DMP_ADDR 0xB030F800 - -#define BTINTEL_PCIE_SCP2_HWEXP_SIZE 4096 -#define BTINTEL_PCIE_SCP2_HWEXP_DMP_ADDR 0xB031D000 - #define BTINTEL_PCIE_MAGIC_NUM 0xA5A5A5A5 #define BTINTEL_PCIE_TRIGGER_REASON_USER_TRIGGER 0x17A2 @@ -732,7 +722,7 @@ static int btintel_pcie_read_dram_buffers(struct btintel_pcie_data *data) sizeof(*tlv) + sizeof(data->dmp_hdr.write_ptr) + sizeof(*tlv) + sizeof(data->dmp_hdr.wrap_ctr) + sizeof(*tlv) + sizeof(data->dmp_hdr.trigger_reason) + - sizeof(*tlv) + sizeof(data->dmp_hdr.fw_git_sha1) + + sizeof(*tlv) + sizeof(data->dmp_hdr.fw_sha) + sizeof(*tlv) + sizeof(data->dmp_hdr.cnvr_top) + sizeof(*tlv) + sizeof(data->dmp_hdr.cnvi_top) + sizeof(*tlv) + strlen(ts) + @@ -781,8 +771,8 @@ static int btintel_pcie_read_dram_buffers(struct btintel_pcie_data *data) sizeof(data->dmp_hdr.wrap_ctr)); p = btintel_pcie_copy_tlv(p, BTINTEL_TRIGGER_REASON, &data->dmp_hdr.trigger_reason, sizeof(data->dmp_hdr.trigger_reason)); - p = btintel_pcie_copy_tlv(p, BTINTEL_FW_SHA, &data->dmp_hdr.fw_git_sha1, - sizeof(data->dmp_hdr.fw_git_sha1)); + p = btintel_pcie_copy_tlv(p, BTINTEL_FW_SHA, &data->dmp_hdr.fw_sha, + sizeof(data->dmp_hdr.fw_sha)); p = btintel_pcie_copy_tlv(p, BTINTEL_CNVR_TOP, &data->dmp_hdr.cnvr_top, sizeof(data->dmp_hdr.cnvr_top)); p = btintel_pcie_copy_tlv(p, BTINTEL_CNVI_TOP, &data->dmp_hdr.cnvi_top, @@ -963,10 +953,325 @@ static inline bool btintel_pcie_in_error(struct btintel_pcie_data *data) return data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_ABORT_HANDLER; } +static const char *btintel_pcie_tlv_str(u8 tlv_type) +{ + switch (tlv_type) { + case BTINTEL_PCIE_TLV_TYPE_EXCEPTION_DUMP_ADDRESS: + return "EXCEPTION_DUMP_ADDRESS"; + case BTINTEL_PCIE_TLV_TYPE_DCCM_MEM_ADDRESS: + return "DCCM_MEM_ADDRESS"; + case BTINTEL_PCIE_TLV_TYPE_SDS_MEM_ADDRESS: + return "SDS_MEM_ADDRESS"; + case BTINTEL_PCIE_TLV_TYPE_ECL_MEM_ADDRESS: + return "ECL_MEM_ADDRESS"; + case BTINTEL_PCIE_TLV_TYPE_SMEM_ADDRESS: + return "SMEM_ADDRESS"; + default: + return "UNKNOWN"; + } +} + +static int btintel_parse_mbox_tlv(struct btintel_pcie_data *data) +{ + /* Custom TLV structure for mailbox parsing + * len is __le16 as per agreement with FW + */ + struct mbox_tlv { + u8 type; + __le16 len; + u8 val[]; + } __packed; + + u8 *buffer, *ptr; + u32 buffer_len, remaining; + int err; + u32 tbl_addr, tbl_size; + struct mbox_tlv *tlv; + struct btintel_data *cnvi_data = hci_get_priv(data->hdev); + u8 hw_variant = INTEL_HW_VARIANT(cnvi_data->cnvi_bt); + long t; + + /* Wait for GP0 alive interrupt to post RX buffers */ + t = wait_event_timeout(data->mbox_parse_wait_q, + test_bit(BTINTEL_PCIE_MBOX_PARSE_READY, &data->flags), + msecs_to_jiffies(BTINTEL_PCIE_MBOX_INTR_TIMEOUT_MS)); + if (!t) { + bt_dev_warn(data->hdev, + "Timeout (%u ms) waiting for alive interrupt before mbox TLV parse; skipping", + BTINTEL_PCIE_MBOX_INTR_TIMEOUT_MS); + return 0; + } + clear_bit(BTINTEL_PCIE_MBOX_PARSE_READY, &data->flags); + + bt_dev_info(data->hdev, + "mbox TLV parse started at %lld ns (%lld us after mbox interrupt)", + ktime_to_ns(ktime_get()), + ktime_to_us(ktime_sub(ktime_get(), data->mbox_intr_ts))); + + memset(&data->dump_info, 0, sizeof(data->dump_info)); + + /* Snapshot to avoid TOCTOU with the GP1 IRQ handler */ + tbl_size = READ_ONCE(data->debug_table_size); + tbl_addr = READ_ONCE(data->debug_table_addr); + + if (!tbl_size || !tbl_addr) + return -EINVAL; + + /* Ensure size is 4-byte aligned; btintel_pcie_read_device_mem() + * reads device memory in 4-byte units. + */ + tbl_size = ALIGN_DOWN(tbl_size, 4); + + if (!tbl_size) + return -EINVAL; + + if (tbl_size > SZ_1M) { + bt_dev_err(data->hdev, "Debug table size too large: %u", + tbl_size); + return -EINVAL; + } + + buffer_len = tbl_size; + + buffer = vmalloc(buffer_len); + if (!buffer) + return -ENOMEM; + + btintel_pcie_mac_init(data); + + err = btintel_pcie_read_device_mem(data, buffer, tbl_addr, + buffer_len); + if (err) + goto exit_on_error; + + print_hex_dump(KERN_INFO, "Bluetooth: mbox_tlv: ", DUMP_PREFIX_OFFSET, 16, 1, + buffer, buffer_len, false); + + ptr = buffer; + remaining = buffer_len; + + /* Parse TLV structures: type(1) + length(2) + value */ + while (remaining >= sizeof(struct mbox_tlv)) { + u16 tlv_len; + u32 tlv_total; + + tlv = (struct mbox_tlv *)ptr; + tlv_len = le16_to_cpu(tlv->len); + tlv_total = sizeof(tlv->type) + + sizeof(tlv->len) + tlv_len; + + if (tlv_total > remaining) { + bt_dev_err(data->hdev, + "TLV parse error: type=%u, len=%u", + tlv->type, tlv_len); + break; + } + + switch (tlv->type) { + case BTINTEL_PCIE_TLV_TYPE_EXCEPTION_DUMP_ADDRESS: + if (tlv_len < 8) { + bt_dev_err(data->hdev, + "TLV %s too short: %u", + btintel_pcie_tlv_str(tlv->type), + tlv_len); + break; + } + data->dump_info.exception_dump_addr = + get_unaligned_le32(&tlv->val[0]); + data->dump_info.exception_dump_len = + get_unaligned_le32(&tlv->val[4]); + break; + case BTINTEL_PCIE_TLV_TYPE_DCCM_MEM_ADDRESS: + if (tlv_len < 8) { + bt_dev_err(data->hdev, + "TLV %s too short: %u", + btintel_pcie_tlv_str(tlv->type), + tlv_len); + break; + } + data->dump_info.dccm_addr_start = + get_unaligned_le32(&tlv->val[0]); + data->dump_info.dccm_addr_end = + get_unaligned_le32(&tlv->val[4]); + break; + case BTINTEL_PCIE_TLV_TYPE_SDS_MEM_ADDRESS: + /* hw_variant comes from cnvi_bt which is set during + * setup. If mailbox fires before setup completes, + * hw_variant is 0. Skip SDS parsing in that case. + */ + if (!hw_variant) { + bt_dev_dbg(data->hdev, "SDS TLV: skipped, hw_variant not yet known"); + break; + } + if (tlv_len == 16 && + hw_variant > BTINTEL_HWID_BZRI) { + data->dump_info.sds_start_addr_start = + get_unaligned_le32(&tlv->val[0]); + data->dump_info.sds_start_addr_end = + get_unaligned_le32(&tlv->val[4]); + data->dump_info.sds_iosf_data_addr_start = + get_unaligned_le32(&tlv->val[8]); + data->dump_info.sds_iosf_data_addr_end = + get_unaligned_le32(&tlv->val[12]); + } else if (tlv_len == 24 && + (hw_variant == BTINTEL_HWID_BZRI || + hw_variant == BTINTEL_HWID_BZRIW)) { + data->dump_info.sds_fixed_rom_addr_start = + get_unaligned_le32(&tlv->val[0]); + data->dump_info.sds_fixed_rom_addr_end = + get_unaligned_le32(&tlv->val[4]); + data->dump_info.sds_start_addr_start = + get_unaligned_le32(&tlv->val[8]); + data->dump_info.sds_start_addr_end = + get_unaligned_le32(&tlv->val[12]); + data->dump_info.sds_iosf_data_addr_start = + get_unaligned_le32(&tlv->val[16]); + data->dump_info.sds_iosf_data_addr_end = + get_unaligned_le32(&tlv->val[20]); + } else { + bt_dev_err(data->hdev, + "SDS TLV: hw=0x%2.2x len=%u", + hw_variant, tlv_len); + } + break; + case BTINTEL_PCIE_TLV_TYPE_ECL_MEM_ADDRESS: + if (tlv_len < 8) { + bt_dev_err(data->hdev, + "TLV %s too short: %u", + btintel_pcie_tlv_str(tlv->type), + tlv_len); + break; + } + data->dump_info.ecl_addr_start = + get_unaligned_le32(&tlv->val[0]); + data->dump_info.ecl_addr_end = + get_unaligned_le32(&tlv->val[4]); + break; + case BTINTEL_PCIE_TLV_TYPE_SMEM_ADDRESS: + if (tlv_len < 8) { + bt_dev_err(data->hdev, + "TLV %s too short: %u", + btintel_pcie_tlv_str(tlv->type), + tlv_len); + break; + } + data->dump_info.smem_addr_start = + get_unaligned_le32(&tlv->val[0]); + data->dump_info.smem_addr_end = + get_unaligned_le32(&tlv->val[4]); + break; + default: + bt_dev_dbg(data->hdev, + "Unknown TLV type: %u length: %u", + tlv->type, tlv_len); + break; + } + + /* Move to next TLV */ + ptr += tlv_total; + remaining -= tlv_total; + } + + bt_dev_info(data->hdev, + "exception_dump: addr:0x%08x len:0x%08x", + data->dump_info.exception_dump_addr, + data->dump_info.exception_dump_len); + bt_dev_info(data->hdev, + "dccm: start:0x%08x end:0x%08x", + data->dump_info.dccm_addr_start, + data->dump_info.dccm_addr_end); + bt_dev_info(data->hdev, + "sds_fixed_rom: start:0x%08x end:0x%08x", + data->dump_info.sds_fixed_rom_addr_start, + data->dump_info.sds_fixed_rom_addr_end); + bt_dev_info(data->hdev, + "sds: start:0x%08x end:0x%08x", + data->dump_info.sds_start_addr_start, + data->dump_info.sds_start_addr_end); + bt_dev_info(data->hdev, + "sds_iosf: start:0x%08x end:0x%08x", + data->dump_info.sds_iosf_data_addr_start, + data->dump_info.sds_iosf_data_addr_end); + bt_dev_info(data->hdev, + "ecl: start:0x%08x end:0x%08x", + data->dump_info.ecl_addr_start, + data->dump_info.ecl_addr_end); + bt_dev_info(data->hdev, + "smem: start:0x%08x end:0x%08x", + data->dump_info.smem_addr_start, + data->dump_info.smem_addr_end); + + vfree(buffer); + return 0; + +exit_on_error: + vfree(buffer); + return err; +} + static void btintel_pcie_msix_gp1_handler(struct btintel_pcie_data *data) { - bt_dev_err(data->hdev, "Received gp1 mailbox interrupt"); - btintel_pcie_dump_debug_registers(data->hdev); + bool target_access = false; + u32 addr = 0, size = 0; + + /* Read the Mail box status and registers */ + data->mbox.mbox_status = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MBOX_STATUS_REG); + if (data->mbox.mbox_status & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX1) { + data->mbox.mbox1 = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MBOX_1_REG); + if (data->mbox.mbox1 == + BTINTEL_PCIE_BUILD_SPECIFIC_RESOURCES_MAPPING) { + bt_dev_info(data->hdev, + "mailbox for target access"); + target_access = true; + } + } + + if (data->mbox.mbox_status & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX2) { + data->mbox.mbox2 = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MBOX_2_REG); + if (target_access) + addr = data->mbox.mbox2; + } + + if (data->mbox.mbox_status & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX3) { + data->mbox.mbox3 = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MBOX_3_REG); + if (target_access) + size = data->mbox.mbox3; + } + + if (data->mbox.mbox_status & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX4) + data->mbox.mbox4 = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MBOX_4_REG); + + bt_dev_dbg(data->hdev, + "GP1: sts:0x%08x mb1:0x%08x mb2:0x%08x mb3:0x%08x mb4:0x%08x", + data->mbox.mbox_status, data->mbox.mbox1, + data->mbox.mbox2, data->mbox.mbox3, + data->mbox.mbox4); + + if (target_access && + !test_and_set_bit(BTINTEL_PCIE_MAIL_BOX_INTR, + &data->flags)) { + /* Arm the mbox<->alive handshake */ + clear_bit(BTINTEL_PCIE_MBOX_PARSE_READY, &data->flags); + set_bit(BTINTEL_PCIE_MBOX_PARSE_PENDING, &data->flags); + data->mbox_intr_ts = ktime_get(); + + bt_dev_info(data->hdev, + "mbox interrupt received at %lld ns; queuing mbox_work", + ktime_to_ns(data->mbox_intr_ts)); + + WRITE_ONCE(data->debug_table_addr, addr); + WRITE_ONCE(data->debug_table_size, size); + if (!queue_work(data->dump_workqueue, + &data->mbox_work)) { + clear_bit(BTINTEL_PCIE_MAIL_BOX_INTR, &data->flags); + clear_bit(BTINTEL_PCIE_MBOX_PARSE_PENDING, &data->flags); + } + } + + /* Mailbox is read, ack to FW */ + btintel_pcie_set_reg_bits(data, + BTINTEL_PCIE_CSR_IPC_DOORBELL_VEC_REG, + BTINTEL_PCIE_CSR_DOORBELL_MBOX_READ_CONFIRM); } /* This function handles the MSI-X interrupt for gp0 cause (bit 0 in @@ -1011,6 +1316,10 @@ static void btintel_pcie_msix_gp0_handler(struct btintel_pcie_data *data) submit_rx = false; signal_waitq = false; + /* Serialize the alive_intr_ctxt claim against set_dxstate()'s + * register-based fallback, which can run concurrently. + */ + spin_lock(&data->irq_lock); switch (data->alive_intr_ctxt) { case BTINTEL_PCIE_ROM: data->alive_intr_ctxt = BTINTEL_PCIE_FW_DL; @@ -1066,10 +1375,17 @@ static void btintel_pcie_msix_gp0_handler(struct btintel_pcie_data *data) data->alive_intr_ctxt); break; } + spin_unlock(&data->irq_lock); if (submit_rx) { btintel_pcie_reset_ia(data); btintel_pcie_start_rx(data); + + /* Complete the mbox<->alive handshake */ + if (test_and_clear_bit(BTINTEL_PCIE_MBOX_PARSE_PENDING, &data->flags)) { + set_bit(BTINTEL_PCIE_MBOX_PARSE_READY, &data->flags); + wake_up(&data->mbox_parse_wait_q); + } } if (signal_waitq) { @@ -1298,7 +1614,8 @@ static int btintel_pcie_recv_frame(struct btintel_pcie_data *data, static void btintel_pcie_read_hwexp(struct btintel_pcie_data *data) { - int len, err, offset, pending; + int err, offset, pending; + u32 len; struct sk_buff *skb; u8 *buf, prefix[64]; u32 addr, val; @@ -1318,23 +1635,30 @@ static void btintel_pcie_read_hwexp(struct btintel_pcie_data *data) /* only from step B0 onwards */ if (INTEL_CNVX_TOP_STEP(data->dmp_hdr.cnvi_top) != 0x01) return; - len = BTINTEL_PCIE_BLZR_HWEXP_SIZE; /* exception data length */ - addr = BTINTEL_PCIE_BLZR_HWEXP_DMP_ADDR; break; case BTINTEL_CNVI_SCP: - len = BTINTEL_PCIE_SCP_HWEXP_SIZE; - addr = BTINTEL_PCIE_SCP_HWEXP_DMP_ADDR; - break; case BTINTEL_CNVI_SCP2: case BTINTEL_CNVI_SCP2F: - len = BTINTEL_PCIE_SCP2_HWEXP_SIZE; - addr = BTINTEL_PCIE_SCP2_HWEXP_DMP_ADDR; break; default: bt_dev_err(data->hdev, "Unsupported cnvi 0x%8.8x", data->dmp_hdr.cnvi_top); return; } + len = data->dump_info.exception_dump_len; + addr = data->dump_info.exception_dump_addr; + + if (!addr || len < sizeof(__le32) || len > SZ_4K) { + bt_dev_err(data->hdev, "Invalid exception address: 0x%8.8x or length: %u", + addr, len); + return; + } + + /* Ensure size is 4-byte aligned; btintel_pcie_read_device_mem() + * reads device memory in 4-byte units. + */ + len = ALIGN_DOWN(len, 4); + buf = kzalloc(len, GFP_KERNEL); if (!buf) goto exit_on_error; @@ -1587,6 +1911,20 @@ static void btintel_pcie_fwtrigger_worker(struct work_struct *work) clear_bit(BTINTEL_PCIE_FWTRIGGER_DUMP_INPROGRESS, &data->flags); } +static void btintel_pcie_mbox_worker(struct work_struct *work) +{ + struct btintel_pcie_data *data = container_of(work, + struct btintel_pcie_data, mbox_work); + + if (!data->hdev) + goto out; + + btintel_parse_mbox_tlv(data); +out: + /* Release guard last; matches set in gp1 handler. */ + clear_bit(BTINTEL_PCIE_MAIL_BOX_INTR, &data->flags); +} + static void btintel_pcie_rx_work(struct work_struct *work) { struct btintel_pcie_data *data = container_of(work, @@ -2428,6 +2766,7 @@ static int btintel_pcie_setup_internal(struct hci_dev *hdev) goto exit_error; } + data->dmp_hdr.cnvi_bt = ver_tlv.cnvi_bt; switch (INTEL_HW_PLATFORM(ver_tlv.cnvi_bt)) { case 0x37: break; @@ -2480,10 +2819,9 @@ static int btintel_pcie_setup_internal(struct hci_dev *hdev) data->dmp_hdr.fw_timestamp = ver_tlv.timestamp; data->dmp_hdr.fw_build_type = ver_tlv.build_type; data->dmp_hdr.fw_build_num = ver_tlv.build_num; - data->dmp_hdr.cnvi_bt = ver_tlv.cnvi_bt; if (ver_tlv.img_type == 0x02 || ver_tlv.img_type == 0x03) - data->dmp_hdr.fw_git_sha1 = ver_tlv.git_sha1; + data->dmp_hdr.fw_sha = ver_tlv.git_sha1; err = btintel_pcie_get_debug_info_addr(hdev); if (err) @@ -2763,6 +3101,7 @@ static void btintel_pcie_reset_work(struct work_struct *wk) disable_work_sync(&data->coredump_work); disable_work_sync(&data->hwexp_work); disable_work_sync(&data->fwtrigger_work); + disable_work_sync(&data->mbox_work); bt_dev_dbg(data->hdev, "Release bluetooth interface"); @@ -2787,6 +3126,7 @@ static void btintel_pcie_reset_work(struct work_struct *wk) enable_work(&data->coredump_work); enable_work(&data->hwexp_work); enable_work(&data->fwtrigger_work); + enable_work(&data->mbox_work); } out: @@ -3044,6 +3384,8 @@ static int btintel_pcie_probe(struct pci_dev *pdev, init_waitqueue_head(&data->tx_wait_q); data->tx_wait_done = false; + init_waitqueue_head(&data->mbox_parse_wait_q); + data->workqueue = alloc_ordered_workqueue(KBUILD_MODNAME, WQ_HIGHPRI); if (!data->workqueue) return -ENOMEM; @@ -3060,6 +3402,7 @@ static int btintel_pcie_probe(struct pci_dev *pdev, INIT_WORK(&data->coredump_work, btintel_pcie_coredump_worker); INIT_WORK(&data->hwexp_work, btintel_pcie_hwexp_worker); INIT_WORK(&data->fwtrigger_work, btintel_pcie_fwtrigger_worker); + INIT_WORK(&data->mbox_work, btintel_pcie_mbox_worker); data->boot_stage_cache = 0x00; data->img_resp_cache = 0x00; @@ -3129,6 +3472,7 @@ static void btintel_pcie_remove(struct pci_dev *pdev) disable_work_sync(&data->coredump_work); disable_work_sync(&data->hwexp_work); disable_work_sync(&data->fwtrigger_work); + disable_work_sync(&data->mbox_work); /* Cancel pending reset work. Skip only when remove() is called from * within the reset work itself (PLDR device_reprobe path) to avoid @@ -3182,7 +3526,8 @@ static void btintel_pcie_coredump(struct device *dev) static int btintel_pcie_set_dxstate(struct btintel_pcie_data *data, u32 dxstate) { - int retry = 0, status; + int retry = 0, err; + long status; u32 dx_intr_timeout_ms = 200; do { @@ -3193,28 +3538,75 @@ static int btintel_pcie_set_dxstate(struct btintel_pcie_data *data, u32 dxstate) status = wait_event_timeout(data->gp0_wait_q, data->gp0_received, msecs_to_jiffies(dx_intr_timeout_ms)); - if (status) - return 0; - - bt_dev_warn(data->hdev, - "Timeout (%u ms) on alive interrupt for D%d entry, retry count %d", - dx_intr_timeout_ms, dxstate, retry); + if (!status) { + bt_dev_warn(data->hdev, + "Timeout (%u ms) on alive interrupt for D%d entry, retry count %d", + dx_intr_timeout_ms, dxstate, retry); - /* clear gp0 cause */ - btintel_pcie_clr_reg_bits(data, - BTINTEL_PCIE_CSR_MSIX_HW_INT_CAUSES, - BTINTEL_PCIE_MSIX_HW_INT_CAUSES_GP0); + /* MSIX_HW_INT_CAUSES is W1C. Write only GP0 so other + * pending causes are not acknowledged here. + */ + btintel_pcie_wr_reg32(data, + BTINTEL_PCIE_CSR_MSIX_HW_INT_CAUSES, + BTINTEL_PCIE_MSIX_HW_INT_CAUSES_GP0); + } - /* A hardware bug may cause the alive interrupt to be missed. - * Check if the controller reached the expected state and retry - * the operation only if it hasn't. + /* gp0_received is set at the top of the handler, before the switch on + * alive_intr_ctxt. Error and lockdown are filtered out above it, but a + * matched case can still complete without doing anything - D3 breaks + * unchanged while the controller has not reached D0 - and a hardware + * bug may drop the interrupt outright. Either way the flag says a gp0 + * was handled, not that the transition completed, and only the register + * knows. Refresh the cache here and retry only if the state check still + * fails. */ + data->boot_stage_cache = btintel_pcie_rd_reg32(data, + BTINTEL_PCIE_CSR_BOOT_STAGE_REG); if (dxstate == BTINTEL_PCIE_STATE_D0) { - if (btintel_pcie_in_d0(data)) + if (btintel_pcie_in_d0(data)) { + bool armed; + + /* Claim the transition under irq_lock so a + * concurrent gp0 handler run cannot also arm RX. + */ + spin_lock(&data->irq_lock); + armed = data->alive_intr_ctxt == BTINTEL_PCIE_D0; + if (!armed) + data->alive_intr_ctxt = BTINTEL_PCIE_D0; + spin_unlock(&data->irq_lock); + + if (armed) + return 0; + + /* Do what the handler's D3 -> D0 branch + * would have done, unless it already has. + */ + btintel_pcie_reset_ia(data); + err = btintel_pcie_start_rx(data); + if (err) + return err; + + /* Complete the mbox<->alive handshake */ + if (test_and_clear_bit(BTINTEL_PCIE_MBOX_PARSE_PENDING, + &data->flags)) { + set_bit(BTINTEL_PCIE_MBOX_PARSE_READY, &data->flags); + wake_up(&data->mbox_parse_wait_q); + } + return 0; + } } else { - if (btintel_pcie_in_d3(data)) + if (btintel_pcie_in_d3(data)) { + /* Do what the handler's D0 -> D3 branch + * would have done, unless it already has. + */ + spin_lock(&data->irq_lock); + if (data->alive_intr_ctxt != BTINTEL_PCIE_D3) + data->alive_intr_ctxt = BTINTEL_PCIE_D3; + spin_unlock(&data->irq_lock); + return 0; + } } } while (++retry < BTINTEL_PCIE_DX_TRANSITION_MAX_RETRIES); @@ -3232,18 +3624,23 @@ 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; start = ktime_get(); /* Refer: 6.4.11.7 -> Platform power management */ err = btintel_pcie_set_dxstate(data, dxstate); - if (err) + if (err) { + bt_dev_err(data->hdev, "Failed to set dxstate:%u (%d)", + dxstate, err); return err; + } bt_dev_dbg(data->hdev, "device entered into d3 state from d0 in %lld us", @@ -3266,7 +3663,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; @@ -3274,19 +3671,15 @@ static int btintel_pcie_resume(struct device *dev) int err; data = pci_get_drvdata(pdev); - data->gp0_received = false; 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_request_reset(data, BTINTEL_PCIE_IOSF_PRR_FLR); return 0; @@ -3295,7 +3688,9 @@ static int btintel_pcie_resume(struct device *dev) /* Refer: 6.4.11.7 -> Platform power management */ err = btintel_pcie_set_dxstate(data, BTINTEL_PCIE_STATE_D0); - if (err == 0) { + if (err) { + bt_dev_err(data->hdev, "Failed to set D0 state (%d)", err); + } else { bt_dev_dbg(data->hdev, "device entered into d0 state from d3 in %lld us", ktime_to_us(ktime_get() - start)); @@ -3320,13 +3715,28 @@ static int btintel_pcie_resume(struct device *dev) return err; } +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 749369b24031..a7573b377a3e 100644 --- a/drivers/bluetooth/btintel_pcie.h +++ b/drivers/bluetooth/btintel_pcie.h @@ -18,6 +18,7 @@ #define BTINTEL_PCIE_CSR_CI_ADDR_LSB_REG (BTINTEL_PCIE_CSR_BASE + 0x118) #define BTINTEL_PCIE_CSR_CI_ADDR_MSB_REG (BTINTEL_PCIE_CSR_BASE + 0x11C) #define BTINTEL_PCIE_CSR_IMG_RESPONSE_REG (BTINTEL_PCIE_CSR_BASE + 0x12C) +#define BTINTEL_PCIE_CSR_IPC_DOORBELL_VEC_REG (BTINTEL_PCIE_CSR_BASE + 0x130) #define BTINTEL_PCIE_CSR_MBOX_1_REG (BTINTEL_PCIE_CSR_BASE + 0x170) #define BTINTEL_PCIE_CSR_MBOX_2_REG (BTINTEL_PCIE_CSR_BASE + 0x174) #define BTINTEL_PCIE_CSR_MBOX_3_REG (BTINTEL_PCIE_CSR_BASE + 0x178) @@ -50,8 +51,11 @@ #define BTINTEL_PCIE_CSR_BOOT_STAGE_DEVICE_HALTED (BIT(14)) #define BTINTEL_PCIE_CSR_BOOT_STAGE_MAC_ACCESS_ON (BIT(16)) #define BTINTEL_PCIE_CSR_BOOT_STAGE_ALIVE (BIT(23)) +/* Reflects live D-state. Updated by hardware on every D-state transition. */ #define BTINTEL_PCIE_CSR_BOOT_STAGE_D3_STATE_READY (BIT(24)) +#define BTINTEL_PCIE_CSR_DOORBELL_MBOX_READ_CONFIRM (BIT(4)) + /* Registers for MSI-X */ #define BTINTEL_PCIE_CSR_MSIX_BASE (0x2000) #define BTINTEL_PCIE_CSR_MSIX_FH_INT_CAUSES (BTINTEL_PCIE_CSR_MSIX_BASE + 0x0800) @@ -121,7 +125,10 @@ enum { BTINTEL_PCIE_COREDUMP_INPROGRESS, BTINTEL_PCIE_FWTRIGGER_DUMP_INPROGRESS, BTINTEL_PCIE_RECOVERY_IN_PROGRESS, - BTINTEL_PCIE_SETUP_DONE + BTINTEL_PCIE_SETUP_DONE, + BTINTEL_PCIE_MAIL_BOX_INTR, + BTINTEL_PCIE_MBOX_PARSE_PENDING, + BTINTEL_PCIE_MBOX_PARSE_READY }; enum btintel_pcie_tlv_type { @@ -153,6 +160,14 @@ enum btintel_pcie_reset_type { BTINTEL_PCIE_IOSF_PRR_PLDR = 1, }; +enum btintel_pcie_mbox_msg { + BTINTEL_PCIE_NO_USE = 0, + BTINTEL_PCIE_TOP_SILENT_RESET, + BTINTEL_PCIE_SB_AUDIO_DEVICE_REPORT, + BTINTEL_PCIE_BUILD_SPECIFIC_RESOURCES_MAPPING, + BTINTEL_PCIE_LAST_MESSAGE = 4095 +}; + #define BTINTEL_PCIE_MSIX_NON_AUTO_CLEAR_CAUSE BIT(7) /* Minimum and Maximum number of MSI-X Vector @@ -166,6 +181,7 @@ enum btintel_pcie_reset_type { /* Default interrupt timeout in msec */ #define BTINTEL_DEFAULT_INTR_TIMEOUT_MS 3000 +#define BTINTEL_PCIE_MBOX_INTR_TIMEOUT_MS 500 #define BTINTEL_PCIE_DX_TRANSITION_MAX_RETRIES 3 @@ -198,6 +214,12 @@ enum { /* RBD buffer size mapping */ #define BTINTEL_PCIE_RBD_SIZE_4K 0x04 +#define BTINTEL_PCIE_TLV_TYPE_EXCEPTION_DUMP_ADDRESS 0x04 +#define BTINTEL_PCIE_TLV_TYPE_DCCM_MEM_ADDRESS 0x05 +#define BTINTEL_PCIE_TLV_TYPE_SDS_MEM_ADDRESS 0x06 +#define BTINTEL_PCIE_TLV_TYPE_ECL_MEM_ADDRESS 0x07 +#define BTINTEL_PCIE_TLV_TYPE_SMEM_ADDRESS 0x08 + /* * Struct for Context Information (v2) * @@ -424,6 +446,32 @@ struct btintel_pcie_dbgc { struct data_buf *bufs; }; +struct btintel_pcie_dump_mem_info { + u32 exception_dump_addr; + u32 exception_dump_len; + u32 dccm_addr_start; + u32 dccm_addr_end; + u32 sds_fixed_rom_addr_start; + u32 sds_fixed_rom_addr_end; + u32 sds_start_addr_start; + u32 sds_start_addr_end; + u32 sds_iosf_data_addr_start; + u32 sds_iosf_data_addr_end; + u32 ecl_addr_start; + u32 ecl_addr_end; + u32 smem_addr_start; + u32 smem_addr_end; +}; + +struct btintel_pcie_mbox { + u32 mbox_flags; + u32 mbox_status; + u32 mbox1; + u32 mbox2; + u32 mbox3; + u32 mbox4; +}; + struct btintel_pcie_dump_header { const char *driver_name; u32 cnvi_top; @@ -431,7 +479,7 @@ struct btintel_pcie_dump_header { u16 fw_timestamp; u8 fw_build_type; u32 fw_build_num; - u32 fw_git_sha1; + u32 fw_sha; u32 cnvi_bt; u32 write_ptr; u32 wrap_ctr; @@ -479,7 +527,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; @@ -522,6 +569,7 @@ struct btintel_pcie_data { struct work_struct coredump_work; struct work_struct hwexp_work; struct work_struct fwtrigger_work; + struct work_struct mbox_work; struct dma_pool *dma_pool; dma_addr_t dma_p_addr; @@ -536,9 +584,17 @@ struct btintel_pcie_data { enum btintel_pcie_reset_type reset_type; struct btintel_pcie_dbgc dbgc; struct btintel_pcie_dump_header dmp_hdr; - u8 pm_sx_event; u32 debug_evt_addr; u32 debug_evt_size; + dma_addr_t debug_table_addr; + u32 debug_table_size; + struct btintel_pcie_dump_mem_info dump_info; + struct btintel_pcie_mbox mbox; + + /* Wait queue for mbox_worker to wait for GP0 alive interrupt */ + wait_queue_head_t mbox_parse_wait_q; + /* Timestamp captured in GP1 handler when mbox interrupt is received */ + ktime_t mbox_intr_ts; }; 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 7ea8bcd8a7ec..56296d142187 100644 --- a/drivers/bluetooth/btmtk.c +++ b/drivers/bluetooth/btmtk.c @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -59,6 +60,67 @@ struct btmtk_section_map { }; } __packed; +/* Reject a firmware image whose header, global descriptor or section map + * array does not fit in the file, and hand back the validated section + * count, so that the section map walks stay inside the firmware buffer. + */ +static int btmtk_fw_validate_layout(struct hci_dev *hdev, + const struct firmware *fw, + u32 *section_num) +{ + const struct btmtk_global_desc *globaldesc; + size_t need; + + if (fw->size < MTK_FW_ROM_PATCH_HEADER_SIZE + MTK_FW_ROM_PATCH_GD_SIZE) { + bt_dev_err(hdev, "Firmware too small: %zu bytes, need at least %u", + fw->size, + MTK_FW_ROM_PATCH_HEADER_SIZE + MTK_FW_ROM_PATCH_GD_SIZE); + return -EINVAL; + } + + globaldesc = (const struct btmtk_global_desc *)(fw->data + + MTK_FW_ROM_PATCH_HEADER_SIZE); + *section_num = le32_to_cpu(globaldesc->section_num); + + if (!*section_num) { + bt_dev_err(hdev, "Firmware declares no sections"); + return -EINVAL; + } + + if (check_mul_overflow((size_t)MTK_FW_ROM_PATCH_SEC_MAP_SIZE, + (size_t)*section_num, &need) || + check_add_overflow(need, + (size_t)(MTK_FW_ROM_PATCH_HEADER_SIZE + + MTK_FW_ROM_PATCH_GD_SIZE), + &need)) { + bt_dev_err(hdev, "Firmware section count too large: %u", + *section_num); + return -EINVAL; + } + + if (fw->size < need) { + bt_dev_err(hdev, "Firmware truncated: %zu bytes, need %zu for %u sections", + fw->size, need, *section_num); + return -EINVAL; + } + + return 0; +} + +/* Reject a section whose payload does not lie within the firmware file. */ +static int btmtk_fw_validate_section(struct hci_dev *hdev, + const struct firmware *fw, int index, + u32 offset, u32 size) +{ + if (offset > fw->size || size > fw->size - offset) { + bt_dev_err(hdev, "Firmware section %d out of bounds: offset=%u, size=%u, fw_size=%zu", + index, offset, size, fw->size); + return -EINVAL; + } + + return 0; +} + static void btmtk_coredump(struct hci_dev *hdev) { int err; @@ -137,7 +199,6 @@ int btmtk_setup_firmware_79xx(struct hci_dev *hdev, const char *fwname, { struct btmtk_hci_wmt_params wmt_params; struct btmtk_patch_header *hdr; - struct btmtk_global_desc *globaldesc = NULL; struct btmtk_section_map *sectionmap; const struct firmware *fw; const u8 *fw_ptr; @@ -153,14 +214,18 @@ int btmtk_setup_firmware_79xx(struct hci_dev *hdev, const char *fwname, return err; } + bt_dev_info(hdev, "Loading BT firmware: %s", fwname); + + err = btmtk_fw_validate_layout(hdev, fw, §ion_num); + if (err < 0) + goto err_release_fw; + fw_ptr = fw->data; fw_bin_ptr = fw_ptr; hdr = (struct btmtk_patch_header *)fw_ptr; - globaldesc = (struct btmtk_global_desc *)(fw_ptr + MTK_FW_ROM_PATCH_HEADER_SIZE); - section_num = le32_to_cpu(globaldesc->section_num); - bt_dev_info(hdev, "HW/SW Version: 0x%04x%04x, Build Time: %s", - le16_to_cpu(hdr->hwver), le16_to_cpu(hdr->swver), hdr->datetime); + bt_dev_info(hdev, "BT HW ver: 0x%04x, SW ver: 0x%04x, Build Time: %.16s", + dev_id & 0xffff, le16_to_cpu(hdr->swver), hdr->datetime); for (i = 0; i < section_num; i++) { first_block = 1; @@ -180,6 +245,11 @@ int btmtk_setup_firmware_79xx(struct hci_dev *hdev, const char *fwname, continue; if (dl_size > 0) { + err = btmtk_fw_validate_section(hdev, fw, i, + section_offset, dl_size); + if (err < 0) + goto err_release_fw; + retry = 20; while (retry > 0) { cmd[0] = 0; /* 0 means legacy dl mode. */ @@ -1023,12 +1093,8 @@ static int btmtk_isopkt_pad(struct hci_dev *hdev, struct sk_buff *skb) if (skb->len > MTK_ISO_THRESHOLD) return -EINVAL; - if (skb_pad(skb, MTK_ISO_THRESHOLD - skb->len)) - return -ENOMEM; - - __skb_put(skb, MTK_ISO_THRESHOLD - skb->len); - - return 0; + /* On error, the skb is freed by hci_send_frame(). */ + return __skb_put_padto(skb, MTK_ISO_THRESHOLD, false); } static int __set_mtk_intr_interface(struct hci_dev *hdev) diff --git a/drivers/bluetooth/btmtksdio.c b/drivers/bluetooth/btmtksdio.c index a15ae6598c66..ba907845d825 100644 --- a/drivers/bluetooth/btmtksdio.c +++ b/drivers/bluetooth/btmtksdio.c @@ -909,14 +909,14 @@ static int mt76xx_setup(struct hci_dev *hdev, const char *fwname) return 0; } -static int mt79xx_setup(struct hci_dev *hdev, const char *fwname) +static int mt79xx_setup(struct hci_dev *hdev, const char *fwname, u32 dev_id) { struct btmtksdio_dev *bdev = hci_get_drvdata(hdev); struct btmtk_hci_wmt_params wmt_params; u8 param = 0x1; int err; - err = btmtk_setup_firmware_79xx(hdev, fwname, mtk_hci_wmt_sync, 0); + err = btmtk_setup_firmware_79xx(hdev, fwname, mtk_hci_wmt_sync, dev_id); if (err < 0) { bt_dev_err(hdev, "Failed to setup 79xx firmware (%d)", err); return err; @@ -1129,8 +1129,8 @@ static int btmtksdio_setup(struct hci_dev *hdev) ktime_t calltime, delta, rettime; unsigned long long duration; char fwname[64]; - int err, dev_id; - u32 fw_version = 0, val; + int err; + u32 dev_id, fw_version = 0, val; calltime = ktime_get(); set_bit(BTMTKSDIO_HW_TX_READY, &bdev->tx_state); @@ -1172,10 +1172,7 @@ static int btmtksdio_setup(struct hci_dev *hdev) btmtk_fw_get_filename(fwname, sizeof(fwname), dev_id, fw_version, 0); - snprintf(fwname, sizeof(fwname), - "mediatek/BT_RAM_CODE_MT%04x_1_%x_hdr.bin", - dev_id & 0xffff, (fw_version & 0xff) + 1); - err = mt79xx_setup(hdev, fwname); + err = mt79xx_setup(hdev, fwname, dev_id); if (err < 0) return err; diff --git a/drivers/bluetooth/btusb.c b/drivers/bluetooth/btusb.c deleted file mode 100644 index ece1fd426f12..000000000000 --- a/drivers/bluetooth/btusb.c +++ /dev/null @@ -1,4866 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -/* - * - * Generic Bluetooth USB driver - * - * Copyright (C) 2005-2008 Marcel Holtmann - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "btintel.h" -#include "btbcm.h" -#include "btrtl.h" -#include "btmtk.h" - -#define VERSION "0.8" - -static bool disable_scofix; -static bool force_scofix; -static bool enable_autosuspend = IS_ENABLED(CONFIG_BT_HCIBTUSB_AUTOSUSPEND); -static bool enable_poll_sync = IS_ENABLED(CONFIG_BT_HCIBTUSB_POLL_SYNC); -static bool reset = true; - -static struct usb_driver btusb_driver; - -#define BTUSB_IGNORE BIT(0) -#define BTUSB_DIGIANSWER BIT(1) -#define BTUSB_CSR BIT(2) -#define BTUSB_SNIFFER BIT(3) -#define BTUSB_BCM92035 BIT(4) -#define BTUSB_BROKEN_ISOC BIT(5) -#define BTUSB_WRONG_SCO_MTU BIT(6) -#define BTUSB_ATH3012 BIT(7) -#define BTUSB_INTEL_COMBINED BIT(8) -#define BTUSB_INTEL_BOOT BIT(9) -#define BTUSB_BCM_PATCHRAM BIT(10) -#define BTUSB_MARVELL BIT(11) -#define BTUSB_SWAVE BIT(12) -#define BTUSB_AMP BIT(13) -#define BTUSB_QCA_ROME BIT(14) -#define BTUSB_BCM_APPLE BIT(15) -#define BTUSB_REALTEK BIT(16) -#define BTUSB_BCM2045 BIT(17) -#define BTUSB_IFNUM_2 BIT(18) -#define BTUSB_CW6622 BIT(19) -#define BTUSB_MEDIATEK BIT(20) -#define BTUSB_WIDEBAND_SPEECH BIT(21) -#define BTUSB_INVALID_LE_STATES BIT(22) -#define BTUSB_QCA_WCN6855 BIT(23) -#define BTUSB_INTEL_BROKEN_SHUTDOWN_LED BIT(24) -#define BTUSB_INTEL_BROKEN_INITIAL_NCMD BIT(25) -#define BTUSB_INTEL_NO_WBS_SUPPORT BIT(26) -#define BTUSB_ACTIONS_SEMI BIT(27) -#define BTUSB_BARROT BIT(28) -#define BTUSB_BROKEN_EXT_SCAN BIT(29) - -static const struct usb_device_id btusb_table[] = { - /* - * NXP IW610 (0471:0215): the composite device reports Bluetooth - * class at the whole-device level, so the generic entry below - * would also match this WiFi vendor interface. Ignore it here - * first so mwifiex-nxp can bind it instead. - */ - { USB_DEVICE_AND_INTERFACE_INFO(0x0471, 0x0215, 0xff, 0xff, 0xff), - .driver_info = BTUSB_IGNORE }, - - /* Generic Bluetooth USB device */ - { USB_DEVICE_INFO(0xe0, 0x01, 0x01) }, - - /* Generic Bluetooth AMP device */ - { USB_DEVICE_INFO(0xe0, 0x01, 0x04), .driver_info = BTUSB_AMP }, - - /* Generic Bluetooth USB interface */ - { USB_INTERFACE_INFO(0xe0, 0x01, 0x01) }, - - /* Apple-specific (Broadcom) devices */ - { USB_VENDOR_AND_INTERFACE_INFO(0x05ac, 0xff, 0x01, 0x01), - .driver_info = BTUSB_BCM_APPLE | BTUSB_IFNUM_2 }, - - /* MediaTek MT76x0E */ - { USB_DEVICE(0x0e8d, 0x763f) }, - - /* Broadcom SoftSailing reporting vendor specific */ - { USB_DEVICE(0x0a5c, 0x21e1) }, - - /* Apple MacBookPro 7,1 */ - { USB_DEVICE(0x05ac, 0x8213) }, - - /* Apple iMac11,1 */ - { USB_DEVICE(0x05ac, 0x8215) }, - - /* Apple MacBookPro6,2 */ - { USB_DEVICE(0x05ac, 0x8218) }, - - /* Apple MacBookAir3,1, MacBookAir3,2 */ - { USB_DEVICE(0x05ac, 0x821b) }, - - /* Apple MacBookAir4,1 */ - { USB_DEVICE(0x05ac, 0x821f) }, - - /* Apple MacBookPro8,2 */ - { USB_DEVICE(0x05ac, 0x821a) }, - - /* Apple MacMini5,1 */ - { USB_DEVICE(0x05ac, 0x8281) }, - - /* AVM BlueFRITZ! USB v2.0 */ - { USB_DEVICE(0x057c, 0x3800), .driver_info = BTUSB_SWAVE }, - - /* Bluetooth Ultraport Module from IBM */ - { USB_DEVICE(0x04bf, 0x030a) }, - - /* ALPS Modules with non-standard id */ - { USB_DEVICE(0x044e, 0x3001) }, - { USB_DEVICE(0x044e, 0x3002) }, - - /* Ericsson with non-standard id */ - { USB_DEVICE(0x0bdb, 0x1002) }, - - /* Canyon CN-BTU1 with HID interfaces */ - { USB_DEVICE(0x0c10, 0x0000) }, - - /* Broadcom BCM20702B0 (Dynex/Insignia) */ - { USB_DEVICE(0x19ff, 0x0239), .driver_info = BTUSB_BCM_PATCHRAM }, - - /* Broadcom BCM43142A0 (Foxconn/Lenovo) */ - { USB_VENDOR_AND_INTERFACE_INFO(0x105b, 0xff, 0x01, 0x01), - .driver_info = BTUSB_BCM_PATCHRAM }, - - /* Broadcom BCM920703 (HTC Vive) */ - { USB_VENDOR_AND_INTERFACE_INFO(0x0bb4, 0xff, 0x01, 0x01), - .driver_info = BTUSB_BCM_PATCHRAM }, - - /* Foxconn - Hon Hai */ - { USB_VENDOR_AND_INTERFACE_INFO(0x0489, 0xff, 0x01, 0x01), - .driver_info = BTUSB_BCM_PATCHRAM }, - - /* Lite-On Technology - Broadcom based */ - { USB_VENDOR_AND_INTERFACE_INFO(0x04ca, 0xff, 0x01, 0x01), - .driver_info = BTUSB_BCM_PATCHRAM }, - - /* Broadcom devices with vendor specific id */ - { USB_VENDOR_AND_INTERFACE_INFO(0x0a5c, 0xff, 0x01, 0x01), - .driver_info = BTUSB_BCM_PATCHRAM }, - - /* ASUSTek Computer - Broadcom based */ - { USB_VENDOR_AND_INTERFACE_INFO(0x0b05, 0xff, 0x01, 0x01), - .driver_info = BTUSB_BCM_PATCHRAM }, - - /* Belkin F8065bf - Broadcom based */ - { USB_VENDOR_AND_INTERFACE_INFO(0x050d, 0xff, 0x01, 0x01), - .driver_info = BTUSB_BCM_PATCHRAM }, - - /* IMC Networks - Broadcom based */ - { USB_VENDOR_AND_INTERFACE_INFO(0x13d3, 0xff, 0x01, 0x01), - .driver_info = BTUSB_BCM_PATCHRAM }, - - /* Dell Computer - Broadcom based */ - { USB_VENDOR_AND_INTERFACE_INFO(0x413c, 0xff, 0x01, 0x01), - .driver_info = BTUSB_BCM_PATCHRAM }, - - /* Toshiba Corp - Broadcom based */ - { USB_VENDOR_AND_INTERFACE_INFO(0x0930, 0xff, 0x01, 0x01), - .driver_info = BTUSB_BCM_PATCHRAM }, - - /* Intel Bluetooth USB Bootloader (RAM module) */ - { USB_DEVICE(0x8087, 0x0a5a), - .driver_info = BTUSB_INTEL_BOOT | BTUSB_BROKEN_ISOC }, - - { } /* Terminating entry */ -}; - -MODULE_DEVICE_TABLE(usb, btusb_table); - -static const struct usb_device_id quirks_table[] = { - /* CSR BlueCore devices */ - { USB_DEVICE(0x0a12, 0x0001), .driver_info = BTUSB_CSR }, - - /* Broadcom BCM2033 without firmware */ - { USB_DEVICE(0x0a5c, 0x2033), .driver_info = BTUSB_IGNORE }, - - /* Broadcom BCM2045 devices */ - { USB_DEVICE(0x0a5c, 0x2045), .driver_info = BTUSB_BCM2045 }, - - /* Atheros 3011 with sflash firmware */ - { USB_DEVICE(0x0489, 0xe027), .driver_info = BTUSB_IGNORE }, - { USB_DEVICE(0x0489, 0xe03d), .driver_info = BTUSB_IGNORE }, - { USB_DEVICE(0x04f2, 0xaff1), .driver_info = BTUSB_IGNORE }, - { USB_DEVICE(0x0930, 0x0215), .driver_info = BTUSB_IGNORE }, - { USB_DEVICE(0x0cf3, 0x3002), .driver_info = BTUSB_IGNORE }, - { USB_DEVICE(0x0cf3, 0xe019), .driver_info = BTUSB_IGNORE }, - { USB_DEVICE(0x13d3, 0x3304), .driver_info = BTUSB_IGNORE }, - - /* Atheros AR9285 Malbec with sflash firmware */ - { USB_DEVICE(0x03f0, 0x311d), .driver_info = BTUSB_IGNORE }, - - /* Atheros 3012 with sflash firmware */ - { USB_DEVICE(0x0489, 0xe04d), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0489, 0xe04e), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0489, 0xe056), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0489, 0xe057), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0489, 0xe05f), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0489, 0xe076), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0489, 0xe078), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0489, 0xe095), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x04c5, 0x1330), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x04ca, 0x3004), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x04ca, 0x3005), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x04ca, 0x3006), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x04ca, 0x3007), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x04ca, 0x3008), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x04ca, 0x300b), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x04ca, 0x300d), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x04ca, 0x300f), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x04ca, 0x3010), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x04ca, 0x3014), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x04ca, 0x3018), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0930, 0x0219), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0930, 0x021c), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0930, 0x0220), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0930, 0x0227), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0b05, 0x17d0), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0cf3, 0x0036), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0cf3, 0x3004), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0cf3, 0x3008), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0cf3, 0x311d), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0cf3, 0x311e), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0cf3, 0x311f), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0cf3, 0x3121), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0cf3, 0x817a), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0cf3, 0x817b), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0cf3, 0xe003), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0cf3, 0xe004), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0cf3, 0xe005), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0cf3, 0xe006), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x13d3, 0x3362), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x13d3, 0x3375), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x13d3, 0x3393), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x13d3, 0x3395), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x13d3, 0x3402), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x13d3, 0x3408), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x13d3, 0x3423), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x13d3, 0x3432), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x13d3, 0x3472), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x13d3, 0x3474), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x13d3, 0x3487), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x13d3, 0x3490), .driver_info = BTUSB_ATH3012 }, - - /* Atheros AR5BBU12 with sflash firmware */ - { USB_DEVICE(0x0489, 0xe02c), .driver_info = BTUSB_IGNORE }, - - /* Atheros AR5BBU12 with sflash firmware */ - { USB_DEVICE(0x0489, 0xe036), .driver_info = BTUSB_ATH3012 }, - { USB_DEVICE(0x0489, 0xe03c), .driver_info = BTUSB_ATH3012 }, - - /* QCA ROME chipset */ - { USB_DEVICE(0x0cf3, 0x535b), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0cf3, 0xe007), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0cf3, 0xe009), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0cf3, 0xe010), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0cf3, 0xe300), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0cf3, 0xe301), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0cf3, 0xe360), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0cf3, 0xe500), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe092), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe09f), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0a2), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x3011), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x3015), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x3016), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x301a), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x3021), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3491), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3496), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3501), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3503), .driver_info = BTUSB_QCA_ROME | - BTUSB_WIDEBAND_SPEECH }, - - /* QCA WCN6855 chipset */ - { USB_DEVICE(0x0489, 0xe0c7), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0c9), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0ca), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0cb), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0cc), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0ce), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0d0), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0d6), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0de), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0df), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0e1), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0e3), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0ea), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0ec), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x3022), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x3023), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x3024), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x3a22), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x3a24), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x3a26), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x3a27), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0cf3, 0xe600), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x10ab, 0x9108), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x10ab, 0x9109), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x10ab, 0x9208), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x10ab, 0x9209), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x10ab, 0x9308), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x10ab, 0x9309), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x10ab, 0x9408), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x10ab, 0x9409), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x10ab, 0x9508), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x10ab, 0x9509), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x10ab, 0x9608), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x10ab, 0x9609), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x10ab, 0x9f09), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x28de, 0x1401), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - - /* QCA WCN785x chipset */ - { USB_DEVICE(0x0cf3, 0xe700), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0fc), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0f3), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe100), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe103), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe10a), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe10d), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe11b), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe11c), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe11f), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe141), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe14a), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe14b), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe14d), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3623), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3624), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x2c7c, 0x0130), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x2c7c, 0x0131), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x2c7c, 0x0132), .driver_info = BTUSB_QCA_WCN6855 | - BTUSB_WIDEBAND_SPEECH }, - - /* Broadcom BCM2035 */ - { USB_DEVICE(0x0a5c, 0x2009), .driver_info = BTUSB_BCM92035 }, - { USB_DEVICE(0x0a5c, 0x200a), .driver_info = BTUSB_WRONG_SCO_MTU }, - { USB_DEVICE(0x0a5c, 0x2035), .driver_info = BTUSB_WRONG_SCO_MTU }, - - /* Broadcom BCM2045 */ - { USB_DEVICE(0x0a5c, 0x2039), .driver_info = BTUSB_WRONG_SCO_MTU }, - { USB_DEVICE(0x0a5c, 0x2101), .driver_info = BTUSB_WRONG_SCO_MTU }, - - /* IBM/Lenovo ThinkPad with Broadcom chip */ - { USB_DEVICE(0x0a5c, 0x201e), .driver_info = BTUSB_WRONG_SCO_MTU }, - { USB_DEVICE(0x0a5c, 0x2110), .driver_info = BTUSB_WRONG_SCO_MTU }, - - /* HP laptop with Broadcom chip */ - { USB_DEVICE(0x03f0, 0x171d), .driver_info = BTUSB_WRONG_SCO_MTU }, - - /* Dell laptop with Broadcom chip */ - { USB_DEVICE(0x413c, 0x8126), .driver_info = BTUSB_WRONG_SCO_MTU }, - - /* Dell Wireless 370 and 410 devices */ - { USB_DEVICE(0x413c, 0x8152), .driver_info = BTUSB_WRONG_SCO_MTU }, - { USB_DEVICE(0x413c, 0x8156), .driver_info = BTUSB_WRONG_SCO_MTU }, - - /* Belkin F8T012 and F8T013 devices */ - { USB_DEVICE(0x050d, 0x0012), .driver_info = BTUSB_WRONG_SCO_MTU }, - { USB_DEVICE(0x050d, 0x0013), .driver_info = BTUSB_WRONG_SCO_MTU }, - - /* Asus WL-BTD202 device */ - { USB_DEVICE(0x0b05, 0x1715), .driver_info = BTUSB_WRONG_SCO_MTU }, - - /* Kensington Bluetooth USB adapter */ - { USB_DEVICE(0x047d, 0x105e), .driver_info = BTUSB_WRONG_SCO_MTU }, - - /* RTX Telecom based adapters with buggy SCO support */ - { USB_DEVICE(0x0400, 0x0807), .driver_info = BTUSB_BROKEN_ISOC }, - { USB_DEVICE(0x0400, 0x080a), .driver_info = BTUSB_BROKEN_ISOC }, - - /* CONWISE Technology based adapters with buggy SCO support */ - { USB_DEVICE(0x0e5e, 0x6622), - .driver_info = BTUSB_BROKEN_ISOC | BTUSB_CW6622}, - - /* Roper Class 1 Bluetooth Dongle (Silicon Wave based) */ - { USB_DEVICE(0x1310, 0x0001), .driver_info = BTUSB_SWAVE }, - - /* Digianswer devices */ - { USB_DEVICE(0x08fd, 0x0001), .driver_info = BTUSB_DIGIANSWER }, - { USB_DEVICE(0x08fd, 0x0002), .driver_info = BTUSB_IGNORE }, - - /* CSR BlueCore Bluetooth Sniffer */ - { USB_DEVICE(0x0a12, 0x0002), - .driver_info = BTUSB_SNIFFER | BTUSB_BROKEN_ISOC }, - - /* Frontline ComProbe Bluetooth Sniffer */ - { USB_DEVICE(0x16d3, 0x0002), - .driver_info = BTUSB_SNIFFER | BTUSB_BROKEN_ISOC }, - - /* Marvell Bluetooth devices */ - { USB_DEVICE(0x1286, 0x2044), .driver_info = BTUSB_MARVELL }, - { USB_DEVICE(0x1286, 0x2046), .driver_info = BTUSB_MARVELL }, - { USB_DEVICE(0x1286, 0x204e), .driver_info = BTUSB_MARVELL }, - - /* - * NXP IW610 BT interfaces (Marvell-lineage silicon, same quirk as - * the 0x1286 entries above). Scoped to the BT interface class, - * not just VID/PID -- see the btusb_table entry above. - */ - { USB_DEVICE_AND_INTERFACE_INFO(0x0471, 0x0215, 0xe0, 0x01, 0x01), - .driver_info = BTUSB_MARVELL }, - - /* Intel Bluetooth devices */ - { USB_DEVICE(0x8087, 0x0025), .driver_info = BTUSB_INTEL_COMBINED }, - { USB_DEVICE(0x8087, 0x0026), .driver_info = BTUSB_INTEL_COMBINED }, - { USB_DEVICE(0x8087, 0x0029), .driver_info = BTUSB_INTEL_COMBINED }, - { USB_DEVICE(0x8087, 0x0032), .driver_info = BTUSB_INTEL_COMBINED }, - { USB_DEVICE(0x8087, 0x0033), .driver_info = BTUSB_INTEL_COMBINED }, - { USB_DEVICE(0x8087, 0x0035), .driver_info = BTUSB_INTEL_COMBINED }, - { USB_DEVICE(0x8087, 0x0036), .driver_info = BTUSB_INTEL_COMBINED }, - { USB_DEVICE(0x8087, 0x0037), .driver_info = BTUSB_INTEL_COMBINED }, - { USB_DEVICE(0x8087, 0x0038), .driver_info = BTUSB_INTEL_COMBINED }, - { USB_DEVICE(0x8087, 0x0039), .driver_info = BTUSB_INTEL_COMBINED }, - { USB_DEVICE(0x8087, 0x0040), .driver_info = BTUSB_INTEL_COMBINED }, /* Lizard Peak 2 */ - { USB_DEVICE(0x8087, 0x07da), .driver_info = BTUSB_CSR }, - { USB_DEVICE(0x8087, 0x07dc), .driver_info = BTUSB_INTEL_COMBINED | - BTUSB_INTEL_NO_WBS_SUPPORT | - BTUSB_INTEL_BROKEN_INITIAL_NCMD | - BTUSB_INTEL_BROKEN_SHUTDOWN_LED }, - { USB_DEVICE(0x8087, 0x0a2a), .driver_info = BTUSB_INTEL_COMBINED | - BTUSB_INTEL_NO_WBS_SUPPORT | - BTUSB_INTEL_BROKEN_SHUTDOWN_LED }, - { USB_DEVICE(0x8087, 0x0a2b), .driver_info = BTUSB_INTEL_COMBINED }, - { USB_DEVICE(0x8087, 0x0aa7), .driver_info = BTUSB_INTEL_COMBINED | - BTUSB_INTEL_BROKEN_SHUTDOWN_LED }, - { USB_DEVICE(0x8087, 0x0aaa), .driver_info = BTUSB_INTEL_COMBINED }, - - /* Other Intel Bluetooth devices */ - { USB_VENDOR_AND_INTERFACE_INFO(0x8087, 0xe0, 0x01, 0x01), - .driver_info = BTUSB_IGNORE }, - - /* Realtek 8821CE Bluetooth devices */ - { USB_DEVICE(0x13d3, 0x3529), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3533), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Realtek 8822CE Bluetooth devices */ - { USB_DEVICE(0x0bda, 0xb00c), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0bda, 0xc822), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Realtek 8822CU Bluetooth devices */ - { USB_DEVICE(0x13d3, 0x3549), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Realtek 8851BE Bluetooth devices */ - { USB_DEVICE(0x0bda, 0xb850), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x13d3, 0x3600), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x13d3, 0x3601), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x0489, 0xe112), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Realtek 8851BU Bluetooth devices */ - { USB_DEVICE(0x3625, 0x010b), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x2001, 0x332a), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x7392, 0xe611), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x2c4e, 0x0128), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Realtek 8852AE Bluetooth devices */ - { USB_DEVICE(0x0bda, 0x2852), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0bda, 0xc852), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0bda, 0x385a), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0bda, 0x4852), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04c5, 0x165c), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x4006), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0cb8, 0xc549), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Realtek 8852CE Bluetooth devices */ - { USB_DEVICE(0x04ca, 0x4007), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04c5, 0x1675), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0cb8, 0xc558), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3587), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3586), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3592), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3612), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe122), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Realtek 8852BE Bluetooth devices */ - { USB_DEVICE(0x0cb8, 0xc559), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0bda, 0x4853), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0bda, 0x887b), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0bda, 0xb85b), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3570), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3571), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3572), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3591), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe123), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe125), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Realtek 8852BT/8852BE-VT Bluetooth devices */ - { USB_DEVICE(0x0bda, 0x8520), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe12f), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3618), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3619), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Realtek 8922AE Bluetooth devices */ - { USB_DEVICE(0x0bda, 0x8922), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0bda, 0xd922), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0bda, 0xd923), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3617), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3616), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe130), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Realtek 8761BU Bluetooth devices */ - { USB_DEVICE(0x0bda, 0xa728), .driver_info = BTUSB_REALTEK | - BTUSB_BROKEN_EXT_SCAN }, - - /* Realtek Bluetooth devices */ - { USB_VENDOR_AND_INTERFACE_INFO(0x0bda, 0xe0, 0x01, 0x01), - .driver_info = BTUSB_REALTEK }, - - /* MediaTek Bluetooth devices */ - { USB_VENDOR_AND_INTERFACE_INFO(0x0e8d, 0xe0, 0x01, 0x01), - .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Additional MediaTek MT7615E Bluetooth devices */ - { USB_DEVICE(0x13d3, 0x3560), .driver_info = BTUSB_MEDIATEK}, - - /* Additional MediaTek MT7663 Bluetooth devices */ - { USB_DEVICE(0x043e, 0x310c), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x3801), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Additional MediaTek MT7668 Bluetooth devices */ - { USB_DEVICE(0x043e, 0x3109), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Additional MediaTek MT7920 Bluetooth devices */ - { USB_DEVICE(0x0489, 0xe134), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe135), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3620), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3621), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3622), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe158), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Additional MediaTek MT7921 Bluetooth devices */ - { USB_DEVICE(0x0489, 0xe0c8), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0cd), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0e0), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0f2), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x3802), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0e8d, 0x0608), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3563), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3564), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3567), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3576), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3578), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3583), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3606), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - /* MediaTek MT7902 Bluetooth devices */ - { USB_DEVICE(0x0489, 0xe156), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0e8d, 0x1ede), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3579), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3580), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3594), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3596), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - /* MediaTek MT7922 Bluetooth devices */ - { USB_DEVICE(0x13d3, 0x3585), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3610), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - - /* MediaTek MT7922A Bluetooth devices */ - { USB_DEVICE(0x0489, 0xe0d8), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0d9), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0e2), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0e4), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0f1), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0f2), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0f5), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0f6), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe102), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe11d), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe152), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe153), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe170), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe174), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x3804), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x3807), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04ca, 0x38e4), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0e8d, 0x223c), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3568), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3584), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3605), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3607), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3614), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3615), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3633), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x35f5, 0x7922), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Additional MediaTek MT7925 Bluetooth devices */ - { USB_DEVICE(0x0489, 0xe111), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe113), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe118), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe11e), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe124), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe139), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe13a), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe0fa), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe10f), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe110), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe116), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3588), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe14e), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe14f), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe150), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0489, 0xe151), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0e8d, 0x8c38), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3602), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3603), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3604), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3608), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3609), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3613), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3625), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3627), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3628), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3630), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x2c7c, 0x7009), .driver_info = BTUSB_MEDIATEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Additional Realtek 8723AE Bluetooth devices */ - { USB_DEVICE(0x0930, 0x021d), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x13d3, 0x3394), .driver_info = BTUSB_REALTEK }, - - /* Additional Realtek 8723BE Bluetooth devices */ - { USB_DEVICE(0x0489, 0xe085), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x0489, 0xe08b), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x04f2, 0xb49f), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x13d3, 0x3410), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x13d3, 0x3416), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x13d3, 0x3459), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x13d3, 0x3494), .driver_info = BTUSB_REALTEK }, - - /* Additional Realtek 8723BU Bluetooth devices */ - { USB_DEVICE(0x7392, 0xa611), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x2c0a, 0x8761), .driver_info = BTUSB_REALTEK }, - - /* Additional Realtek 8723DE Bluetooth devices */ - { USB_DEVICE(0x0bda, 0xb009), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x2ff8, 0xb011), .driver_info = BTUSB_REALTEK }, - - /* Additional Realtek 8761BUV Bluetooth devices */ - { USB_DEVICE(0x2c4e, 0x0115), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x2357, 0x0604), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x2357, 0x0607), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0b05, 0x190e), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x2550, 0x8761), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0bda, 0x8771), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x6655, 0x8771), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x7392, 0xc611), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x2b89, 0x8761), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x2b89, 0x6275), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x37ad, 0x0600), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x14b0, 0x047a), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Additional Realtek 8761CU Bluetooth devices */ - { USB_DEVICE(0x0b05, 0x1bef), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0b05, 0x1d70), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Additional Realtek 8821AE Bluetooth devices */ - { USB_DEVICE(0x0b05, 0x17dc), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x13d3, 0x3414), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x13d3, 0x3458), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x13d3, 0x3461), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x13d3, 0x3462), .driver_info = BTUSB_REALTEK }, - - /* Additional Realtek 8822BE Bluetooth devices */ - { USB_DEVICE(0x13d3, 0x3526), .driver_info = BTUSB_REALTEK }, - { USB_DEVICE(0x0b05, 0x185c), .driver_info = BTUSB_REALTEK }, - - /* Additional Realtek 8822CE Bluetooth devices */ - { USB_DEVICE(0x04ca, 0x4005), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x04c5, 0x161f), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0b05, 0x18ef), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3548), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3549), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3553), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x13d3, 0x3555), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x2ff8, 0x3051), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x1358, 0xc123), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0bda, 0xc123), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x1357, 0xc123), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - { USB_DEVICE(0x0cb5, 0xc547), .driver_info = BTUSB_REALTEK | - BTUSB_WIDEBAND_SPEECH }, - - /* Barrot Technology Bluetooth devices */ - { USB_DEVICE(0x33fa, 0x0010), .driver_info = BTUSB_BARROT }, - { USB_DEVICE(0x33fa, 0x0012), .driver_info = BTUSB_BARROT }, - - /* Actions Semiconductor ATS2851 based devices */ - { USB_DEVICE(0x10d7, 0xb012), .driver_info = BTUSB_ACTIONS_SEMI }, - - /* Silicon Wave based devices */ - { USB_DEVICE(0x0c10, 0x0000), .driver_info = BTUSB_SWAVE }, - - { } /* Terminating entry */ -}; - -/* The Bluetooth USB module build into some devices needs to be reset on resume, - * this is a problem with the platform (likely shutting off all power) not with - * the module itself. So we use a DMI list to match known broken platforms. - */ -static const struct dmi_system_id btusb_needs_reset_resume_table[] = { - { - /* Dell OptiPlex 3060 (QCA ROME device 0cf3:e007) */ - .matches = { - DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), - DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex 3060"), - }, - }, - { - /* Dell XPS 9360 (QCA ROME device 0cf3:e300) */ - .matches = { - DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), - DMI_MATCH(DMI_PRODUCT_NAME, "XPS 13 9360"), - }, - }, - { - /* Dell Inspiron 5565 (QCA ROME device 0cf3:e009) */ - .matches = { - DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), - DMI_MATCH(DMI_PRODUCT_NAME, "Inspiron 5565"), - }, - }, - {} -}; - -struct qca_dump_info { - /* fields for dump collection */ - u16 id_vendor; - u16 id_product; - u32 fw_version; - u32 controller_id; - u32 ram_dump_size; - u16 ram_dump_seqno; -}; - -struct btqca_data { - struct qca_dump_info qca_dump; -}; - -#define BTUSB_MAX_ISOC_FRAMES 10 - -#define BTUSB_INTR_RUNNING 0 -#define BTUSB_BULK_RUNNING 1 -#define BTUSB_ISOC_RUNNING 2 -#define BTUSB_SUSPENDING 3 -#define BTUSB_DID_ISO_RESUME 4 -#define BTUSB_BOOTLOADER 5 -#define BTUSB_DOWNLOADING 6 -#define BTUSB_FIRMWARE_LOADED 7 -#define BTUSB_FIRMWARE_FAILED 8 -#define BTUSB_BOOTING 9 -#define BTUSB_DIAG_RUNNING 10 -#define BTUSB_OOB_WAKE_ENABLED 11 -#define BTUSB_HW_RESET_ACTIVE 12 -#define BTUSB_TX_WAIT_VND_EVT 13 -#define BTUSB_WAKEUP_AUTOSUSPEND 14 -#define BTUSB_USE_ALT3_FOR_WBS 15 -#define BTUSB_ALT6_CONTINUOUS_TX 16 -#define BTUSB_HW_SSR_ACTIVE 17 -#define BTUSB_WAKEUP_BROKEN 18 -#define BTUSB_RESET 19 - -struct btusb_data { - struct hci_dev *hdev; - struct usb_device *udev; - struct usb_interface *intf; - struct usb_interface *isoc; - struct usb_interface *diag; - unsigned isoc_ifnum; - - unsigned long flags; - - bool poll_sync; - int intr_interval; - struct work_struct work; - struct work_struct waker; - struct delayed_work rx_work; - - struct sk_buff_head acl_q; - - struct usb_anchor deferred; - struct usb_anchor tx_anchor; - int tx_in_flight; - spinlock_t txlock; - - struct usb_anchor intr_anchor; - struct usb_anchor bulk_anchor; - struct usb_anchor isoc_anchor; - struct usb_anchor diag_anchor; - struct usb_anchor ctrl_anchor; - spinlock_t rxlock; - - struct sk_buff *evt_skb; - struct sk_buff *acl_skb; - struct sk_buff *sco_skb; - - struct usb_endpoint_descriptor *intr_ep; - struct usb_endpoint_descriptor *bulk_tx_ep; - struct usb_endpoint_descriptor *bulk_rx_ep; - struct usb_endpoint_descriptor *isoc_tx_ep; - struct usb_endpoint_descriptor *isoc_rx_ep; - struct usb_endpoint_descriptor *diag_tx_ep; - struct usb_endpoint_descriptor *diag_rx_ep; - - struct gpio_desc *reset_gpio; - - __u8 cmdreq_type; - __u8 cmdreq; - - unsigned int sco_num; - unsigned int air_mode; - bool usb_alt6_packet_flow; - int isoc_altsetting; - int suspend_count; - const struct usb_device_id *match_id; - - int (*recv_event)(struct hci_dev *hdev, struct sk_buff *skb); - int (*recv_acl)(struct hci_dev *hdev, struct sk_buff *skb); - int (*recv_bulk)(struct btusb_data *data, void *buffer, int count); - - int (*setup_on_usb)(struct hci_dev *hdev); - - int (*suspend)(struct hci_dev *hdev); - int (*resume)(struct hci_dev *hdev); - int (*disconnect)(struct hci_dev *hdev); - - int oob_wake_irq; /* irq for out-of-band wake-on-bt */ -}; - -static void btusb_reset(struct hci_dev *hdev) -{ - struct btusb_data *data; - int err; - - data = hci_get_drvdata(hdev); - err = usb_autopm_get_interface(data->intf); - if (err) { - bt_dev_err(hdev, "Failed usb_autopm_get_interface: %d", err); - return; - } - - if (test_and_set_bit(BTUSB_RESET, &data->flags)) - usb_autopm_put_interface_no_suspend(data->intf); - - bt_dev_err(hdev, "Resetting usb device."); - usb_queue_reset_device(data->intf); -} - -static void btusb_intel_reset(struct hci_dev *hdev) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct gpio_desc *reset_gpio = data->reset_gpio; - struct btintel_data *intel_data = hci_get_priv(hdev); - - if (intel_data->acpi_reset_method) { - if (test_and_set_bit(INTEL_ACPI_RESET_ACTIVE, intel_data->flags)) { - bt_dev_err(hdev, "acpi: last reset failed ? Not resetting again"); - return; - } - - bt_dev_err(hdev, "Initiating acpi reset method"); - /* If ACPI reset method fails, lets try with legacy GPIO - * toggling - */ - if (!intel_data->acpi_reset_method(hdev)) { - return; - } - } - - if (!reset_gpio) { - btusb_reset(hdev); - return; - } - - /* - * Toggle the hard reset line if the platform provides one. The reset - * is going to yank the device off the USB and then replug. So doing - * once is enough. The cleanup is handled correctly on the way out - * (standard USB disconnect), and the new device is detected cleanly - * and bound to the driver again like it should be. - */ - if (test_and_set_bit(BTUSB_HW_RESET_ACTIVE, &data->flags)) { - bt_dev_err(hdev, "last reset failed? Not resetting again"); - return; - } - - bt_dev_err(hdev, "Initiating HW reset via gpio"); - gpiod_set_value_cansleep(reset_gpio, 1); - msleep(100); - gpiod_set_value_cansleep(reset_gpio, 0); -} - -#define RTK_DEVCOREDUMP_CODE_MEMDUMP 0x01 -#define RTK_DEVCOREDUMP_CODE_HW_ERR 0x02 -#define RTK_DEVCOREDUMP_CODE_CMD_TIMEOUT 0x03 - -#define RTK_SUB_EVENT_CODE_COREDUMP 0x34 - -struct rtk_dev_coredump_hdr { - u8 type; - u8 code; - u8 reserved[2]; -} __packed; - -static inline void btusb_rtl_alloc_devcoredump(struct hci_dev *hdev, - struct rtk_dev_coredump_hdr *hdr, u8 *buf, u32 len) -{ - struct sk_buff *skb; - - skb = alloc_skb(len + sizeof(*hdr), GFP_ATOMIC); - if (!skb) - return; - - skb_put_data(skb, hdr, sizeof(*hdr)); - if (len) - skb_put_data(skb, buf, len); - - if (!hci_devcd_init(hdev, skb->len)) { - hci_devcd_append(hdev, skb); - hci_devcd_complete(hdev); - } else { - bt_dev_err(hdev, "RTL: Failed to generate devcoredump"); - kfree_skb(skb); - } -} - -static void btusb_rtl_reset(struct hci_dev *hdev) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct gpio_desc *reset_gpio = data->reset_gpio; - struct rtk_dev_coredump_hdr hdr = { - .type = RTK_DEVCOREDUMP_CODE_CMD_TIMEOUT, - }; - - btusb_rtl_alloc_devcoredump(hdev, &hdr, NULL, 0); - - if (!reset_gpio) { - btusb_reset(hdev); - return; - } - - /* Toggle the hard reset line. The Realtek device is going to - * yank itself off the USB and then replug. The cleanup is handled - * correctly on the way out (standard USB disconnect), and the new - * device is detected cleanly and bound to the driver again like - * it should be. - */ - if (test_and_set_bit(BTUSB_HW_RESET_ACTIVE, &data->flags)) { - bt_dev_err(hdev, "last reset failed? Not resetting again"); - return; - } - - bt_dev_err(hdev, "Reset Realtek device via gpio"); - gpiod_set_value_cansleep(reset_gpio, 1); - msleep(200); - gpiod_set_value_cansleep(reset_gpio, 0); -} - -static void btusb_rtl_hw_error(struct hci_dev *hdev, u8 code) -{ - struct rtk_dev_coredump_hdr hdr = { - .type = RTK_DEVCOREDUMP_CODE_HW_ERR, - .code = code, - }; - - bt_dev_err(hdev, "RTL: hw err, trigger devcoredump (%d)", code); - - btusb_rtl_alloc_devcoredump(hdev, &hdr, NULL, 0); -} - -static void btusb_qca_reset(struct hci_dev *hdev) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct gpio_desc *reset_gpio = data->reset_gpio; - - if (test_bit(BTUSB_HW_SSR_ACTIVE, &data->flags)) { - bt_dev_info(hdev, "Ramdump in progress, defer reset"); - return; - } - - if (reset_gpio) { - bt_dev_err(hdev, "Reset qca device via bt_en gpio"); - - /* Toggle the hard reset line. The qca bt device is going to - * yank itself off the USB and then replug. The cleanup is handled - * correctly on the way out (standard USB disconnect), and the new - * device is detected cleanly and bound to the driver again like - * it should be. - */ - if (test_and_set_bit(BTUSB_HW_RESET_ACTIVE, &data->flags)) { - bt_dev_err(hdev, "last reset failed? Not resetting again"); - return; - } - - gpiod_set_value_cansleep(reset_gpio, 0); - msleep(200); - gpiod_set_value_cansleep(reset_gpio, 1); - - return; - } - - btusb_reset(hdev); -} - -static u8 btusb_classify_qca_pkt_type(struct hci_dev *hdev, struct sk_buff *skb) -{ - /* Some Qualcomm controllers, e.g., QCNFA765 with WCN6855 chip, send debug - * packets as ACL frames with connection handle 0x2EDC. These are not real - * ACL packets and should be reclassified as HCI_DIAG_PKT to prevent - * "ACL packet for unknown connection handle 3804" errors. - */ - if (skb->len >= 2) { - u16 handle = get_unaligned_le16(skb->data); - - if (handle == 0x2EDC) - return HCI_DIAG_PKT; - } - - /* Use default packet type for other packets */ - return hci_skb_pkt_type(skb); -} - -static inline void btusb_free_frags(struct btusb_data *data) -{ - unsigned long flags; - - spin_lock_irqsave(&data->rxlock, flags); - - dev_kfree_skb_irq(data->evt_skb); - data->evt_skb = NULL; - - dev_kfree_skb_irq(data->acl_skb); - data->acl_skb = NULL; - - dev_kfree_skb_irq(data->sco_skb); - data->sco_skb = NULL; - - spin_unlock_irqrestore(&data->rxlock, flags); -} - -static int btusb_recv_event(struct hci_dev *hdev, struct sk_buff *skb) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - - if (data->intr_interval) { - /* Trigger dequeue immediately if an event is received */ - schedule_delayed_work(&data->rx_work, 0); - } - - return data->recv_event(hdev, skb); -} - -static int btusb_recv_intr(struct btusb_data *data, void *buffer, int count) -{ - struct sk_buff *skb; - unsigned long flags; - int err = 0; - - spin_lock_irqsave(&data->rxlock, flags); - skb = data->evt_skb; - - while (count) { - int len; - - if (!skb) { - skb = bt_skb_alloc(HCI_MAX_EVENT_SIZE, GFP_ATOMIC); - if (!skb) { - err = -ENOMEM; - break; - } - - hci_skb_pkt_type(skb) = HCI_EVENT_PKT; - hci_skb_expect(skb) = HCI_EVENT_HDR_SIZE; - } - - len = min_t(uint, hci_skb_expect(skb), count); - skb_put_data(skb, buffer, len); - - count -= len; - buffer += len; - hci_skb_expect(skb) -= len; - - if (skb->len == HCI_EVENT_HDR_SIZE) { - /* Complete event header */ - hci_skb_expect(skb) = hci_event_hdr(skb)->plen; - - if (skb_tailroom(skb) < hci_skb_expect(skb)) { - kfree_skb(skb); - skb = NULL; - - err = -EILSEQ; - break; - } - } - - if (!hci_skb_expect(skb)) { - /* Each chunk should correspond to at least 1 or more - * events so if there are still bytes left that doesn't - * constitute a new event this is likely a bug in the - * controller. - */ - if (count && count < HCI_EVENT_HDR_SIZE) { - bt_dev_warn(data->hdev, - "Unexpected continuation: %d bytes", - count); - count = 0; - } - - /* Complete frame */ - btusb_recv_event(data->hdev, skb); - skb = NULL; - } - } - - data->evt_skb = skb; - spin_unlock_irqrestore(&data->rxlock, flags); - - return err; -} - -static int btusb_recv_acl(struct hci_dev *hdev, struct sk_buff *skb) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - - /* Only queue ACL packet if intr_interval is set as it means - * force_poll_sync has been enabled. - */ - if (!data->intr_interval) - return data->recv_acl(hdev, skb); - - skb_queue_tail(&data->acl_q, skb); - schedule_delayed_work(&data->rx_work, data->intr_interval); - - return 0; -} - -static int btusb_recv_bulk(struct btusb_data *data, void *buffer, int count) -{ - struct sk_buff *skb; - unsigned long flags; - int err = 0; - - spin_lock_irqsave(&data->rxlock, flags); - skb = data->acl_skb; - - while (count) { - int len; - - if (!skb) { - skb = bt_skb_alloc(HCI_MAX_FRAME_SIZE, GFP_ATOMIC); - if (!skb) { - err = -ENOMEM; - break; - } - - hci_skb_pkt_type(skb) = HCI_ACLDATA_PKT; - hci_skb_expect(skb) = HCI_ACL_HDR_SIZE; - } - - len = min_t(uint, hci_skb_expect(skb), count); - skb_put_data(skb, buffer, len); - - count -= len; - buffer += len; - hci_skb_expect(skb) -= len; - - if (skb->len == HCI_ACL_HDR_SIZE) { - /* Complete ACL header */ - hci_skb_expect(skb) = hci_acl_dlen(skb); - - if (skb_tailroom(skb) < hci_skb_expect(skb)) { - kfree_skb(skb); - skb = NULL; - - err = -EILSEQ; - break; - } - } - - if (!hci_skb_expect(skb)) { - /* Complete frame */ - btusb_recv_acl(data->hdev, skb); - skb = NULL; - } - } - - data->acl_skb = skb; - spin_unlock_irqrestore(&data->rxlock, flags); - - return err; -} - -static bool btusb_validate_sco_handle(struct hci_dev *hdev, - struct hci_sco_hdr *hdr) -{ - __u16 handle; - - if (hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) - // Can't validate, userspace controls everything. - return true; - - /* - * USB isochronous transfers are not designed to be reliable and may - * lose fragments. When this happens, the next first fragment - * encountered might actually be a continuation fragment. - * Validate the handle to detect it and drop it, or else the upper - * layer will get garbage for a while. - */ - - handle = hci_handle(__le16_to_cpu(hdr->handle)); - - switch (hci_conn_lookup_type(hdev, handle)) { - case SCO_LINK: - case ESCO_LINK: - return true; - default: - return false; - } -} - -static int btusb_recv_isoc(struct btusb_data *data, void *buffer, int count) -{ - struct sk_buff *skb; - unsigned long flags; - int err = 0; - - spin_lock_irqsave(&data->rxlock, flags); - skb = data->sco_skb; - - while (count) { - int len; - - if (!skb) { - skb = bt_skb_alloc(HCI_MAX_SCO_SIZE, GFP_ATOMIC); - if (!skb) { - err = -ENOMEM; - break; - } - - hci_skb_pkt_type(skb) = HCI_SCODATA_PKT; - hci_skb_expect(skb) = HCI_SCO_HDR_SIZE; - } - - len = min_t(uint, hci_skb_expect(skb), count); - skb_put_data(skb, buffer, len); - - count -= len; - buffer += len; - hci_skb_expect(skb) -= len; - - if (skb->len == HCI_SCO_HDR_SIZE) { - /* Complete SCO header */ - struct hci_sco_hdr *hdr = hci_sco_hdr(skb); - - hci_skb_expect(skb) = hdr->dlen; - - if (skb_tailroom(skb) < hci_skb_expect(skb) || - !btusb_validate_sco_handle(data->hdev, hdr)) { - kfree_skb(skb); - skb = NULL; - - err = -EILSEQ; - break; - } - } - - if (!hci_skb_expect(skb)) { - /* Complete frame */ - hci_recv_frame(data->hdev, skb); - skb = NULL; - } - } - - data->sco_skb = skb; - spin_unlock_irqrestore(&data->rxlock, flags); - - return err; -} - -static void btusb_intr_complete(struct urb *urb) -{ - struct hci_dev *hdev = urb->context; - struct btusb_data *data = hci_get_drvdata(hdev); - int err; - - BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, - urb->actual_length); - - if (!test_bit(HCI_RUNNING, &hdev->flags)) - return; - - if (urb->status == 0) { - hdev->stat.byte_rx += urb->actual_length; - - if (btusb_recv_intr(data, urb->transfer_buffer, - urb->actual_length) < 0) { - bt_dev_err(hdev, "corrupted event packet"); - hdev->stat.err_rx++; - } - } else if (urb->status == -ENOENT) { - /* Avoid suspend failed when usb_kill_urb */ - return; - } - - if (!test_bit(BTUSB_INTR_RUNNING, &data->flags)) - return; - - usb_mark_last_busy(data->udev); - usb_anchor_urb(urb, &data->intr_anchor); - - err = usb_submit_urb(urb, GFP_ATOMIC); - if (err < 0) { - /* -EPERM: urb is being killed; - * -ENODEV: device got disconnected - */ - if (err != -EPERM && err != -ENODEV) - bt_dev_err(hdev, "urb %p failed to resubmit (%d)", - urb, -err); - if (err != -EPERM) - hci_cmd_sync_cancel(hdev, -err); - usb_unanchor_urb(urb); - } -} - -static int btusb_submit_intr_urb(struct hci_dev *hdev, gfp_t mem_flags) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct urb *urb; - unsigned char *buf; - unsigned int pipe; - int err, size; - - BT_DBG("%s", hdev->name); - - if (!data->intr_ep) - return -ENODEV; - - urb = usb_alloc_urb(0, mem_flags); - if (!urb) - return -ENOMEM; - - if (le16_to_cpu(data->udev->descriptor.idVendor) == 0x0a12 && - le16_to_cpu(data->udev->descriptor.idProduct) == 0x0001) - /* Fake CSR devices don't seem to support sort-transter */ - size = le16_to_cpu(data->intr_ep->wMaxPacketSize); - else - /* Use maximum HCI Event size so the USB stack handles - * ZPL/short-transfer automatically. - */ - size = HCI_MAX_EVENT_SIZE; - - buf = kmalloc(size, mem_flags); - if (!buf) { - usb_free_urb(urb); - return -ENOMEM; - } - - pipe = usb_rcvintpipe(data->udev, data->intr_ep->bEndpointAddress); - - usb_fill_int_urb(urb, data->udev, pipe, buf, size, - btusb_intr_complete, hdev, data->intr_ep->bInterval); - - urb->transfer_flags |= URB_FREE_BUFFER; - - usb_anchor_urb(urb, &data->intr_anchor); - - err = usb_submit_urb(urb, mem_flags); - if (err < 0) { - if (err != -EPERM && err != -ENODEV) - bt_dev_err(hdev, "urb %p submission failed (%d)", - urb, -err); - if (err != -EPERM) - hci_cmd_sync_cancel(hdev, -err); - usb_unanchor_urb(urb); - } - - /* Only initialize intr_interval if URB poll sync is enabled */ - if (!data->poll_sync) - goto done; - - /* The units are frames (milliseconds) for full and low speed devices, - * and microframes (1/8 millisecond) for highspeed and SuperSpeed - * devices. - * - * This is done once on open/resume so it shouldn't change even if - * force_poll_sync changes. - */ - switch (urb->dev->speed) { - case USB_SPEED_SUPER_PLUS: - case USB_SPEED_SUPER: /* units are 125us */ - data->intr_interval = usecs_to_jiffies(urb->interval * 125); - break; - default: - data->intr_interval = msecs_to_jiffies(urb->interval); - break; - } - -done: - usb_free_urb(urb); - - return err; -} - -static void btusb_bulk_complete(struct urb *urb) -{ - struct hci_dev *hdev = urb->context; - struct btusb_data *data = hci_get_drvdata(hdev); - int err; - - BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, - urb->actual_length); - - if (!test_bit(HCI_RUNNING, &hdev->flags)) - return; - - if (urb->status == 0) { - hdev->stat.byte_rx += urb->actual_length; - - if (data->recv_bulk(data, urb->transfer_buffer, - urb->actual_length) < 0) { - bt_dev_err(hdev, "corrupted ACL packet"); - hdev->stat.err_rx++; - } - } else if (urb->status == -ENOENT) { - /* Avoid suspend failed when usb_kill_urb */ - return; - } - - if (!test_bit(BTUSB_BULK_RUNNING, &data->flags)) - return; - - usb_anchor_urb(urb, &data->bulk_anchor); - usb_mark_last_busy(data->udev); - - err = usb_submit_urb(urb, GFP_ATOMIC); - if (err < 0) { - /* -EPERM: urb is being killed; - * -ENODEV: device got disconnected - */ - if (err != -EPERM && err != -ENODEV) - bt_dev_err(hdev, "urb %p failed to resubmit (%d)", - urb, -err); - usb_unanchor_urb(urb); - } -} - -static int btusb_submit_bulk_urb(struct hci_dev *hdev, gfp_t mem_flags) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct urb *urb; - unsigned char *buf; - unsigned int pipe; - int err, size = HCI_MAX_FRAME_SIZE; - - BT_DBG("%s", hdev->name); - - if (!data->bulk_rx_ep) - return -ENODEV; - - urb = usb_alloc_urb(0, mem_flags); - if (!urb) - return -ENOMEM; - - buf = kmalloc(size, mem_flags); - if (!buf) { - usb_free_urb(urb); - return -ENOMEM; - } - - pipe = usb_rcvbulkpipe(data->udev, data->bulk_rx_ep->bEndpointAddress); - - usb_fill_bulk_urb(urb, data->udev, pipe, buf, size, - btusb_bulk_complete, hdev); - - urb->transfer_flags |= URB_FREE_BUFFER; - - usb_mark_last_busy(data->udev); - usb_anchor_urb(urb, &data->bulk_anchor); - - err = usb_submit_urb(urb, mem_flags); - if (err < 0) { - if (err != -EPERM && err != -ENODEV) - bt_dev_err(hdev, "urb %p submission failed (%d)", - urb, -err); - usb_unanchor_urb(urb); - } - - usb_free_urb(urb); - - return err; -} - -static void btusb_isoc_complete(struct urb *urb) -{ - struct hci_dev *hdev = urb->context; - struct btusb_data *data = hci_get_drvdata(hdev); - int i, err; - - BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, - urb->actual_length); - - if (!test_bit(HCI_RUNNING, &hdev->flags)) - return; - - if (urb->status == 0) { - for (i = 0; i < urb->number_of_packets; i++) { - unsigned int offset = urb->iso_frame_desc[i].offset; - unsigned int length = urb->iso_frame_desc[i].actual_length; - - if (urb->iso_frame_desc[i].status) - continue; - - hdev->stat.byte_rx += length; - - if (btusb_recv_isoc(data, urb->transfer_buffer + offset, - length) < 0) { - bt_dev_err(hdev, "corrupted SCO packet"); - hdev->stat.err_rx++; - } - } - } else if (urb->status == -ENOENT) { - /* Avoid suspend failed when usb_kill_urb */ - return; - } - - if (!test_bit(BTUSB_ISOC_RUNNING, &data->flags)) - return; - - usb_anchor_urb(urb, &data->isoc_anchor); - - err = usb_submit_urb(urb, GFP_ATOMIC); - if (err < 0) { - /* -EPERM: urb is being killed; - * -ENODEV: device got disconnected - */ - if (err != -EPERM && err != -ENODEV) - bt_dev_err(hdev, "urb %p failed to resubmit (%d)", - urb, -err); - usb_unanchor_urb(urb); - } -} - -static inline void __fill_isoc_descriptor_msbc(struct urb *urb, int len, - int mtu, struct btusb_data *data) -{ - int i = 0, offset = 0; - unsigned int interval; - - BT_DBG("len %d mtu %d", len, mtu); - - /* For mSBC ALT 6 settings some chips need to transmit the data - * continuously without the zero length of USB packets. - */ - if (test_bit(BTUSB_ALT6_CONTINUOUS_TX, &data->flags)) - goto ignore_usb_alt6_packet_flow; - - /* For mSBC ALT 6 setting the host will send the packet at continuous - * flow. As per core spec 5, vol 4, part B, table 2.1. For ALT setting - * 6 the HCI PACKET INTERVAL should be 7.5ms for every usb packets. - * To maintain the rate we send 63bytes of usb packets alternatively for - * 7ms and 8ms to maintain the rate as 7.5ms. - */ - if (data->usb_alt6_packet_flow) { - interval = 7; - data->usb_alt6_packet_flow = false; - } else { - interval = 6; - data->usb_alt6_packet_flow = true; - } - - for (i = 0; i < interval; i++) { - urb->iso_frame_desc[i].offset = offset; - urb->iso_frame_desc[i].length = offset; - } - -ignore_usb_alt6_packet_flow: - if (len && i < BTUSB_MAX_ISOC_FRAMES) { - urb->iso_frame_desc[i].offset = offset; - urb->iso_frame_desc[i].length = len; - i++; - } - - urb->number_of_packets = i; -} - -static inline void __fill_isoc_descriptor(struct urb *urb, int len, int mtu) -{ - int i, offset = 0; - - BT_DBG("len %d mtu %d", len, mtu); - - for (i = 0; i < BTUSB_MAX_ISOC_FRAMES && len >= mtu; - i++, offset += mtu, len -= mtu) { - urb->iso_frame_desc[i].offset = offset; - urb->iso_frame_desc[i].length = mtu; - } - - if (len && i < BTUSB_MAX_ISOC_FRAMES) { - urb->iso_frame_desc[i].offset = offset; - urb->iso_frame_desc[i].length = len; - i++; - } - - urb->number_of_packets = i; -} - -static int btusb_submit_isoc_urb(struct hci_dev *hdev, gfp_t mem_flags) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct urb *urb; - unsigned char *buf; - unsigned int pipe; - int err, size; - - BT_DBG("%s", hdev->name); - - if (!data->isoc_rx_ep) - return -ENODEV; - - urb = usb_alloc_urb(BTUSB_MAX_ISOC_FRAMES, mem_flags); - if (!urb) - return -ENOMEM; - - size = le16_to_cpu(data->isoc_rx_ep->wMaxPacketSize) * - BTUSB_MAX_ISOC_FRAMES; - - buf = kmalloc(size, mem_flags); - if (!buf) { - usb_free_urb(urb); - return -ENOMEM; - } - - pipe = usb_rcvisocpipe(data->udev, data->isoc_rx_ep->bEndpointAddress); - - usb_fill_int_urb(urb, data->udev, pipe, buf, size, btusb_isoc_complete, - hdev, data->isoc_rx_ep->bInterval); - - urb->transfer_flags = URB_FREE_BUFFER | URB_ISO_ASAP; - - __fill_isoc_descriptor(urb, size, - le16_to_cpu(data->isoc_rx_ep->wMaxPacketSize)); - - usb_anchor_urb(urb, &data->isoc_anchor); - - err = usb_submit_urb(urb, mem_flags); - if (err < 0) { - if (err != -EPERM && err != -ENODEV) - bt_dev_err(hdev, "urb %p submission failed (%d)", - urb, -err); - usb_unanchor_urb(urb); - } - - usb_free_urb(urb); - - return err; -} - -static void btusb_diag_complete(struct urb *urb) -{ - struct hci_dev *hdev = urb->context; - struct btusb_data *data = hci_get_drvdata(hdev); - int err; - - BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, - urb->actual_length); - - if (urb->status == 0) { - struct sk_buff *skb; - - skb = bt_skb_alloc(urb->actual_length, GFP_ATOMIC); - if (skb) { - skb_put_data(skb, urb->transfer_buffer, - urb->actual_length); - hci_recv_diag(hdev, skb); - } - } else if (urb->status == -ENOENT) { - /* Avoid suspend failed when usb_kill_urb */ - return; - } - - if (!test_bit(BTUSB_DIAG_RUNNING, &data->flags)) - return; - - usb_anchor_urb(urb, &data->diag_anchor); - usb_mark_last_busy(data->udev); - - err = usb_submit_urb(urb, GFP_ATOMIC); - if (err < 0) { - /* -EPERM: urb is being killed; - * -ENODEV: device got disconnected - */ - if (err != -EPERM && err != -ENODEV) - bt_dev_err(hdev, "urb %p failed to resubmit (%d)", - urb, -err); - usb_unanchor_urb(urb); - } -} - -static int btusb_submit_diag_urb(struct hci_dev *hdev, gfp_t mem_flags) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct urb *urb; - unsigned char *buf; - unsigned int pipe; - int err, size = HCI_MAX_FRAME_SIZE; - - BT_DBG("%s", hdev->name); - - if (!data->diag_rx_ep) - return -ENODEV; - - urb = usb_alloc_urb(0, mem_flags); - if (!urb) - return -ENOMEM; - - buf = kmalloc(size, mem_flags); - if (!buf) { - usb_free_urb(urb); - return -ENOMEM; - } - - pipe = usb_rcvbulkpipe(data->udev, data->diag_rx_ep->bEndpointAddress); - - usb_fill_bulk_urb(urb, data->udev, pipe, buf, size, - btusb_diag_complete, hdev); - - urb->transfer_flags |= URB_FREE_BUFFER; - - usb_mark_last_busy(data->udev); - usb_anchor_urb(urb, &data->diag_anchor); - - err = usb_submit_urb(urb, mem_flags); - if (err < 0) { - if (err != -EPERM && err != -ENODEV) - bt_dev_err(hdev, "urb %p submission failed (%d)", - urb, -err); - usb_unanchor_urb(urb); - } - - usb_free_urb(urb); - - return err; -} - -static void btusb_tx_complete(struct urb *urb) -{ - struct sk_buff *skb = urb->context; - struct hci_dev *hdev = (struct hci_dev *)skb->dev; - struct btusb_data *data = hci_get_drvdata(hdev); - unsigned long flags; - - BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, - urb->actual_length); - - if (!test_bit(HCI_RUNNING, &hdev->flags)) - goto done; - - if (!urb->status) { - hdev->stat.byte_tx += urb->transfer_buffer_length; - } else { - if (hci_skb_pkt_type(skb) == HCI_COMMAND_PKT) - hci_cmd_sync_cancel(hdev, -urb->status); - hdev->stat.err_tx++; - } - -done: - spin_lock_irqsave(&data->txlock, flags); - data->tx_in_flight--; - spin_unlock_irqrestore(&data->txlock, flags); - - kfree(urb->setup_packet); - - kfree_skb(skb); -} - -static void btusb_isoc_tx_complete(struct urb *urb) -{ - struct sk_buff *skb = urb->context; - struct hci_dev *hdev = (struct hci_dev *)skb->dev; - - BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, - urb->actual_length); - - if (!test_bit(HCI_RUNNING, &hdev->flags)) - goto done; - - if (!urb->status) - hdev->stat.byte_tx += urb->transfer_buffer_length; - else - hdev->stat.err_tx++; - -done: - kfree(urb->setup_packet); - - kfree_skb(skb); -} - -static int btusb_open(struct hci_dev *hdev) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - int err; - - BT_DBG("%s", hdev->name); - - err = usb_autopm_get_interface(data->intf); - if (err < 0) - return err; - - /* Patching USB firmware files prior to starting any URBs of HCI path - * It is more safe to use USB bulk channel for downloading USB patch - */ - if (data->setup_on_usb) { - err = data->setup_on_usb(hdev); - if (err < 0) - goto setup_fail; - } - - data->intf->needs_remote_wakeup = 1; - - if (test_and_set_bit(BTUSB_INTR_RUNNING, &data->flags)) - goto done; - - err = btusb_submit_intr_urb(hdev, GFP_KERNEL); - if (err < 0) - goto failed; - - err = btusb_submit_bulk_urb(hdev, GFP_KERNEL); - if (err < 0) { - usb_kill_anchored_urbs(&data->intr_anchor); - goto failed; - } - - set_bit(BTUSB_BULK_RUNNING, &data->flags); - btusb_submit_bulk_urb(hdev, GFP_KERNEL); - - if (data->diag) { - if (!btusb_submit_diag_urb(hdev, GFP_KERNEL)) - set_bit(BTUSB_DIAG_RUNNING, &data->flags); - } - -done: - usb_autopm_put_interface(data->intf); - return 0; - -failed: - clear_bit(BTUSB_INTR_RUNNING, &data->flags); -setup_fail: - usb_autopm_put_interface(data->intf); - return err; -} - -static void btusb_stop_traffic(struct btusb_data *data) -{ - usb_kill_anchored_urbs(&data->intr_anchor); - usb_kill_anchored_urbs(&data->bulk_anchor); - usb_kill_anchored_urbs(&data->isoc_anchor); - usb_kill_anchored_urbs(&data->diag_anchor); - usb_kill_anchored_urbs(&data->ctrl_anchor); -} - -static void btusb_prepare_reset(struct hci_dev *hdev) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - - btusb_stop_traffic(data); - usb_kill_anchored_urbs(&data->tx_anchor); -} - -static int btusb_close(struct hci_dev *hdev) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - int err; - - BT_DBG("%s", hdev->name); - - cancel_work_sync(&data->work); - cancel_work_sync(&data->waker); - - clear_bit(BTUSB_ISOC_RUNNING, &data->flags); - clear_bit(BTUSB_BULK_RUNNING, &data->flags); - clear_bit(BTUSB_INTR_RUNNING, &data->flags); - clear_bit(BTUSB_DIAG_RUNNING, &data->flags); - - btusb_stop_traffic(data); - - /* rx_work must only be canceled once the URBs that can rearm it are - * gone, and it must be canceled synchronously since btusb_disconnect() - * frees the btusb_data it dereferences right after hci_unregister_dev(). - */ - cancel_delayed_work_sync(&data->rx_work); - - skb_queue_purge(&data->acl_q); - - btusb_free_frags(data); - - err = usb_autopm_get_interface(data->intf); - if (err < 0) - goto failed; - - data->intf->needs_remote_wakeup = 0; - - /* Enable remote wake up for auto-suspend */ - if (test_bit(BTUSB_WAKEUP_AUTOSUSPEND, &data->flags)) - data->intf->needs_remote_wakeup = 1; - - usb_autopm_put_interface(data->intf); - -failed: - usb_scuttle_anchored_urbs(&data->deferred); - return 0; -} - -static int btusb_flush(struct hci_dev *hdev) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - - BT_DBG("%s", hdev->name); - - cancel_delayed_work_sync(&data->rx_work); - - skb_queue_purge(&data->acl_q); - - usb_kill_anchored_urbs(&data->tx_anchor); - btusb_free_frags(data); - - return 0; -} - -static struct urb *alloc_ctrl_urb(struct hci_dev *hdev, struct sk_buff *skb) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct usb_ctrlrequest *dr; - struct urb *urb; - unsigned int pipe; - - urb = usb_alloc_urb(0, GFP_KERNEL); - if (!urb) - return ERR_PTR(-ENOMEM); - - dr = kmalloc_obj(*dr); - if (!dr) { - usb_free_urb(urb); - return ERR_PTR(-ENOMEM); - } - - dr->bRequestType = data->cmdreq_type; - dr->bRequest = data->cmdreq; - dr->wIndex = 0; - dr->wValue = 0; - dr->wLength = __cpu_to_le16(skb->len); - - pipe = usb_sndctrlpipe(data->udev, 0x00); - - usb_fill_control_urb(urb, data->udev, pipe, (void *)dr, - skb->data, skb->len, btusb_tx_complete, skb); - - skb->dev = (void *)hdev; - - return urb; -} - -static struct urb *alloc_bulk_urb(struct hci_dev *hdev, struct sk_buff *skb) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct urb *urb; - unsigned int pipe; - - if (!data->bulk_tx_ep) - return ERR_PTR(-ENODEV); - - urb = usb_alloc_urb(0, GFP_KERNEL); - if (!urb) - return ERR_PTR(-ENOMEM); - - pipe = usb_sndbulkpipe(data->udev, data->bulk_tx_ep->bEndpointAddress); - - usb_fill_bulk_urb(urb, data->udev, pipe, - skb->data, skb->len, btusb_tx_complete, skb); - - skb->dev = (void *)hdev; - - return urb; -} - -static struct urb *alloc_isoc_urb(struct hci_dev *hdev, struct sk_buff *skb) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct urb *urb; - unsigned int pipe; - - if (!data->isoc_tx_ep) - return ERR_PTR(-ENODEV); - - urb = usb_alloc_urb(BTUSB_MAX_ISOC_FRAMES, GFP_KERNEL); - if (!urb) - return ERR_PTR(-ENOMEM); - - pipe = usb_sndisocpipe(data->udev, data->isoc_tx_ep->bEndpointAddress); - - usb_fill_int_urb(urb, data->udev, pipe, - skb->data, skb->len, btusb_isoc_tx_complete, - skb, data->isoc_tx_ep->bInterval); - - urb->transfer_flags = URB_ISO_ASAP; - - if (data->isoc_altsetting == 6) - __fill_isoc_descriptor_msbc(urb, skb->len, - le16_to_cpu(data->isoc_tx_ep->wMaxPacketSize), - data); - else - __fill_isoc_descriptor(urb, skb->len, - le16_to_cpu(data->isoc_tx_ep->wMaxPacketSize)); - skb->dev = (void *)hdev; - - return urb; -} - -static int submit_tx_urb(struct hci_dev *hdev, struct urb *urb) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - int err; - - usb_anchor_urb(urb, &data->tx_anchor); - - err = usb_submit_urb(urb, GFP_KERNEL); - if (err < 0) { - if (err != -EPERM && err != -ENODEV) - bt_dev_err(hdev, "urb %p submission failed (%d)", - urb, -err); - kfree(urb->setup_packet); - usb_unanchor_urb(urb); - } else { - usb_mark_last_busy(data->udev); - } - - usb_free_urb(urb); - return err; -} - -static int submit_or_queue_tx_urb(struct hci_dev *hdev, struct urb *urb) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - unsigned long flags; - bool suspending; - - spin_lock_irqsave(&data->txlock, flags); - suspending = test_bit(BTUSB_SUSPENDING, &data->flags); - if (!suspending) - data->tx_in_flight++; - spin_unlock_irqrestore(&data->txlock, flags); - - if (!suspending) - return submit_tx_urb(hdev, urb); - - usb_anchor_urb(urb, &data->deferred); - schedule_work(&data->waker); - - usb_free_urb(urb); - return 0; -} - -static int btusb_send_frame(struct hci_dev *hdev, struct sk_buff *skb) -{ - struct urb *urb; - - BT_DBG("%s", hdev->name); - - switch (hci_skb_pkt_type(skb)) { - case HCI_COMMAND_PKT: - urb = alloc_ctrl_urb(hdev, skb); - if (IS_ERR(urb)) - return PTR_ERR(urb); - - hdev->stat.cmd_tx++; - return submit_or_queue_tx_urb(hdev, urb); - - case HCI_ACLDATA_PKT: - urb = alloc_bulk_urb(hdev, skb); - if (IS_ERR(urb)) - return PTR_ERR(urb); - - hdev->stat.acl_tx++; - return submit_or_queue_tx_urb(hdev, urb); - - case HCI_SCODATA_PKT: - if (!hci_dev_test_flag(hdev, HCI_USER_CHANNEL) && - hci_conn_num(hdev, SCO_LINK) < 1) - return -ENODEV; - - urb = alloc_isoc_urb(hdev, skb); - if (IS_ERR(urb)) - return PTR_ERR(urb); - - hdev->stat.sco_tx++; - return submit_tx_urb(hdev, urb); - - case HCI_ISODATA_PKT: - urb = alloc_bulk_urb(hdev, skb); - if (IS_ERR(urb)) - return PTR_ERR(urb); - - return submit_or_queue_tx_urb(hdev, urb); - } - - return -EILSEQ; -} - -static void btusb_notify(struct hci_dev *hdev, unsigned int evt) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - - BT_DBG("%s evt %d", hdev->name, evt); - - if (hci_conn_num(hdev, SCO_LINK) != data->sco_num) { - data->sco_num = hci_conn_num(hdev, SCO_LINK); - data->air_mode = evt; - schedule_work(&data->work); - } -} - -static inline int __set_isoc_interface(struct hci_dev *hdev, int altsetting) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct usb_interface *intf = data->isoc; - struct usb_endpoint_descriptor *ep_desc; - int i, err; - - if (!data->isoc) - return -ENODEV; - - err = usb_set_interface(data->udev, data->isoc_ifnum, altsetting); - if (err < 0) { - bt_dev_err(hdev, "setting interface failed (%d)", -err); - return err; - } - - data->isoc_altsetting = altsetting; - - data->isoc_tx_ep = NULL; - data->isoc_rx_ep = NULL; - - for (i = 0; i < intf->cur_altsetting->desc.bNumEndpoints; i++) { - ep_desc = &intf->cur_altsetting->endpoint[i].desc; - - if (!data->isoc_tx_ep && usb_endpoint_is_isoc_out(ep_desc)) { - data->isoc_tx_ep = ep_desc; - continue; - } - - if (!data->isoc_rx_ep && usb_endpoint_is_isoc_in(ep_desc)) { - data->isoc_rx_ep = ep_desc; - continue; - } - } - - if (!data->isoc_tx_ep || !data->isoc_rx_ep) { - bt_dev_err(hdev, "invalid SCO descriptors"); - return -ENODEV; - } - - return 0; -} - -static int btusb_switch_alt_setting(struct hci_dev *hdev, int new_alts) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - int err; - - if (data->isoc_altsetting != new_alts) { - unsigned long flags; - - clear_bit(BTUSB_ISOC_RUNNING, &data->flags); - usb_kill_anchored_urbs(&data->isoc_anchor); - - /* When isochronous alternate setting needs to be - * changed, because SCO connection has been added - * or removed, a packet fragment may be left in the - * reassembling state. This could lead to wrongly - * assembled fragments. - * - * Clear outstanding fragment when selecting a new - * alternate setting. - */ - spin_lock_irqsave(&data->rxlock, flags); - dev_kfree_skb_irq(data->sco_skb); - data->sco_skb = NULL; - spin_unlock_irqrestore(&data->rxlock, flags); - - err = __set_isoc_interface(hdev, new_alts); - if (err < 0) - return err; - } - - if (!test_and_set_bit(BTUSB_ISOC_RUNNING, &data->flags)) { - if (btusb_submit_isoc_urb(hdev, GFP_KERNEL) < 0) - clear_bit(BTUSB_ISOC_RUNNING, &data->flags); - else - btusb_submit_isoc_urb(hdev, GFP_KERNEL); - } - - return 0; -} - -static struct usb_host_interface *btusb_find_altsetting(struct btusb_data *data, - int alt) -{ - struct usb_interface *intf = data->isoc; - int i; - - BT_DBG("Looking for Alt no :%d", alt); - - if (!intf) - return NULL; - - for (i = 0; i < intf->num_altsetting; i++) { - if (intf->altsetting[i].desc.bAlternateSetting == alt) - return &intf->altsetting[i]; - } - - return NULL; -} - -static void btusb_work(struct work_struct *work) -{ - struct btusb_data *data = container_of(work, struct btusb_data, work); - struct hci_dev *hdev = data->hdev; - int new_alts = 0; - int err; - - if (data->sco_num > 0) { - if (!test_bit(BTUSB_DID_ISO_RESUME, &data->flags)) { - err = usb_autopm_get_interface(data->isoc ? data->isoc : data->intf); - if (err < 0) { - clear_bit(BTUSB_ISOC_RUNNING, &data->flags); - usb_kill_anchored_urbs(&data->isoc_anchor); - return; - } - - set_bit(BTUSB_DID_ISO_RESUME, &data->flags); - } - - if (data->air_mode == HCI_NOTIFY_ENABLE_SCO_CVSD) { - if (hdev->voice_setting & 0x0020) { - static const int alts[3] = { 2, 4, 5 }; - unsigned int sco_idx; - - sco_idx = min_t(unsigned int, data->sco_num - 1, - ARRAY_SIZE(alts) - 1); - new_alts = alts[sco_idx]; - } else { - new_alts = data->sco_num; - } - } else if (data->air_mode == HCI_NOTIFY_ENABLE_SCO_TRANSP) { - /* Bluetooth USB spec recommends alt 6 (63 bytes), but - * many adapters do not support it. Alt 1 appears to - * work for all adapters that do not have alt 6, and - * which work with WBS at all. Some devices prefer - * alt 3 (HCI payload >= 60 Bytes let air packet - * data satisfy 60 bytes), requiring - * MTU >= 3 (packets) * 25 (size) - 3 (headers) = 72 - * see also Core spec 5, vol 4, B 2.1.1 & Table 2.1. - */ - if (btusb_find_altsetting(data, 6)) - new_alts = 6; - else if (btusb_find_altsetting(data, 3) && - hdev->sco_mtu >= 72 && - test_bit(BTUSB_USE_ALT3_FOR_WBS, &data->flags)) - new_alts = 3; - else - new_alts = 1; - } - - if (btusb_switch_alt_setting(hdev, new_alts) < 0) - bt_dev_err(hdev, "set USB alt:(%d) failed!", new_alts); - } else { - usb_kill_anchored_urbs(&data->isoc_anchor); - - if (test_and_clear_bit(BTUSB_ISOC_RUNNING, &data->flags)) - __set_isoc_interface(hdev, 0); - - if (test_and_clear_bit(BTUSB_DID_ISO_RESUME, &data->flags)) - usb_autopm_put_interface(data->isoc ? data->isoc : data->intf); - } -} - -static void btusb_waker(struct work_struct *work) -{ - struct btusb_data *data = container_of(work, struct btusb_data, waker); - int err; - - err = usb_autopm_get_interface(data->intf); - if (err < 0) - return; - - usb_autopm_put_interface(data->intf); -} - -static void btusb_rx_work(struct work_struct *work) -{ - struct btusb_data *data = container_of(work, struct btusb_data, - rx_work.work); - struct sk_buff *skb; - - /* Dequeue ACL data received during the interval */ - while ((skb = skb_dequeue(&data->acl_q))) - data->recv_acl(data->hdev, skb); -} - -static int btusb_setup_bcm92035(struct hci_dev *hdev) -{ - struct sk_buff *skb; - u8 val = 0x00; - - BT_DBG("%s", hdev->name); - - skb = __hci_cmd_sync(hdev, 0xfc3b, 1, &val, HCI_INIT_TIMEOUT); - if (IS_ERR(skb)) - bt_dev_err(hdev, "BCM92035 command failed (%ld)", PTR_ERR(skb)); - else - kfree_skb(skb); - - return 0; -} - -static int btusb_setup_csr(struct hci_dev *hdev) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - u16 bcdDevice = le16_to_cpu(data->udev->descriptor.bcdDevice); - struct hci_rp_read_local_version *rp; - struct sk_buff *skb; - bool is_fake = false; - int ret; - - BT_DBG("%s", hdev->name); - - skb = __hci_cmd_sync(hdev, HCI_OP_READ_LOCAL_VERSION, 0, NULL, - HCI_INIT_TIMEOUT); - if (IS_ERR(skb)) { - int err = PTR_ERR(skb); - - bt_dev_err(hdev, "CSR: Local version failed (%d)", err); - return err; - } - - rp = skb_pull_data(skb, sizeof(*rp)); - if (!rp) { - bt_dev_err(hdev, "CSR: Local version length mismatch"); - kfree_skb(skb); - return -EIO; - } - - bt_dev_info(hdev, "CSR: Setting up dongle with HCI ver=%u rev=%04x", - rp->hci_ver, le16_to_cpu(rp->hci_rev)); - - bt_dev_info(hdev, "LMP ver=%u subver=%04x; manufacturer=%u", - rp->lmp_ver, le16_to_cpu(rp->lmp_subver), - le16_to_cpu(rp->manufacturer)); - - /* Detect a wide host of Chinese controllers that aren't CSR. - * - * Known fake bcdDevices: 0x0100, 0x0134, 0x1915, 0x2520, 0x7558, 0x8891 - * - * The main thing they have in common is that these are really popular low-cost - * options that support newer Bluetooth versions but rely on heavy VID/PID - * squatting of this poor old Bluetooth 1.1 device. Even sold as such. - * - * We detect actual CSR devices by checking that the HCI manufacturer code - * is Cambridge Silicon Radio (10) and ensuring that LMP sub-version and - * HCI rev values always match. As they both store the firmware number. - */ - if (le16_to_cpu(rp->manufacturer) != 10 || - le16_to_cpu(rp->hci_rev) != le16_to_cpu(rp->lmp_subver)) - is_fake = true; - - /* Known legit CSR firmware build numbers and their supported BT versions: - * - 1.1 (0x1) -> 0x0073, 0x020d, 0x033c, 0x034e - * - 1.2 (0x2) -> 0x04d9, 0x0529 - * - 2.0 (0x3) -> 0x07a6, 0x07ad, 0x0c5c - * - 2.1 (0x4) -> 0x149c, 0x1735, 0x1899 (0x1899 is a BlueCore4-External) - * - 4.0 (0x6) -> 0x1d86, 0x2031, 0x22bb - * - * e.g. Real CSR dongles with LMP subversion 0x73 are old enough that - * support BT 1.1 only; so it's a dead giveaway when some - * third-party BT 4.0 dongle reuses it. - */ - else if (le16_to_cpu(rp->lmp_subver) <= 0x034e && - rp->hci_ver > BLUETOOTH_VER_1_1) - is_fake = true; - - else if (le16_to_cpu(rp->lmp_subver) <= 0x0529 && - rp->hci_ver > BLUETOOTH_VER_1_2) - is_fake = true; - - else if (le16_to_cpu(rp->lmp_subver) <= 0x0c5c && - rp->hci_ver > BLUETOOTH_VER_2_0) - is_fake = true; - - else if (le16_to_cpu(rp->lmp_subver) <= 0x1899 && - rp->hci_ver > BLUETOOTH_VER_2_1) - is_fake = true; - - else if (le16_to_cpu(rp->lmp_subver) <= 0x22bb && - rp->hci_ver > BLUETOOTH_VER_4_0) - is_fake = true; - - /* Other clones which beat all the above checks */ - else if (bcdDevice == 0x0134 && - le16_to_cpu(rp->lmp_subver) == 0x0c5c && - rp->hci_ver == BLUETOOTH_VER_2_0) - is_fake = true; - - if (is_fake) { - bt_dev_warn(hdev, "CSR: Unbranded CSR clone detected; adding workarounds and force-suspending once..."); - - /* Generally these clones have big discrepancies between - * advertised features and what's actually supported. - * Probably will need to be expanded in the future; - * without these the controller will lock up. - */ - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_STORED_LINK_KEY); - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_ERR_DATA_REPORTING); - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_FILTER_CLEAR_ALL); - hci_set_quirk(hdev, HCI_QUIRK_NO_SUSPEND_NOTIFIER); - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_READ_VOICE_SETTING); - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_READ_PAGE_SCAN_TYPE); - - /* Clear the reset quirk since this is not an actual - * early Bluetooth 1.1 device from CSR. - */ - hci_clear_quirk(hdev, HCI_QUIRK_RESET_ON_CLOSE); - hci_clear_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY); - - /* - * Special workaround for these BT 4.0 chip clones, and potentially more: - * - * - 0x0134: a Barrot 8041a02 (HCI rev: 0x0810 sub: 0x1012) - * - 0x7558: IC markings FR3191AHAL 749H15143 (HCI rev/sub-version: 0x0709) - * - * These controllers are really messed-up. - * - * 1. Their bulk RX endpoint will never report any data unless - * the device was suspended at least once (yes, really). - * 2. They will not wakeup when autosuspended and receiving data - * on their bulk RX endpoint from e.g. a keyboard or mouse - * (IOW remote-wakeup support is broken for the bulk endpoint). - * - * To fix 1. enable runtime-suspend, force-suspend the - * HCI and then wake-it up by disabling runtime-suspend. - * - * To fix 2. clear the HCI's can_wake flag, this way the HCI - * will still be autosuspended when it is not open. - * - * -- - * - * Because these are widespread problems we prefer generic solutions; so - * apply this initialization quirk to every controller that gets here, - * it should be harmless. The alternative is to not work at all. - */ - pm_runtime_allow(&data->udev->dev); - - ret = pm_runtime_suspend(&data->udev->dev); - if (ret >= 0) - msleep(200); - else - bt_dev_warn(hdev, "CSR: Couldn't suspend the device for our Barrot 8041a02 receive-issue workaround"); - - pm_runtime_forbid(&data->udev->dev); - - device_set_wakeup_capable(&data->udev->dev, false); - - /* Re-enable autosuspend if this was requested */ - if (enable_autosuspend) - usb_enable_autosuspend(data->udev); - } - - kfree_skb(skb); - - return 0; -} - -static int inject_cmd_complete(struct hci_dev *hdev, __u16 opcode) -{ - struct sk_buff *skb; - struct hci_event_hdr *hdr; - struct hci_ev_cmd_complete *evt; - - skb = bt_skb_alloc(sizeof(*hdr) + sizeof(*evt) + 1, GFP_KERNEL); - if (!skb) - return -ENOMEM; - - hdr = skb_put(skb, sizeof(*hdr)); - hdr->evt = HCI_EV_CMD_COMPLETE; - hdr->plen = sizeof(*evt) + 1; - - evt = skb_put(skb, sizeof(*evt)); - evt->ncmd = 0x01; - evt->opcode = cpu_to_le16(opcode); - - skb_put_u8(skb, 0x00); - - hci_skb_pkt_type(skb) = HCI_EVENT_PKT; - - return hci_recv_frame(hdev, skb); -} - -static int btusb_recv_bulk_intel(struct btusb_data *data, void *buffer, - int count) -{ - struct hci_dev *hdev = data->hdev; - - /* When the device is in bootloader mode, then it can send - * events via the bulk endpoint. These events are treated the - * same way as the ones received from the interrupt endpoint. - */ - if (btintel_test_flag(hdev, INTEL_BOOTLOADER)) - return btusb_recv_intr(data, buffer, count); - - return btusb_recv_bulk(data, buffer, count); -} - -static int btusb_send_frame_intel(struct hci_dev *hdev, struct sk_buff *skb) -{ - struct urb *urb; - - BT_DBG("%s", hdev->name); - - switch (hci_skb_pkt_type(skb)) { - case HCI_COMMAND_PKT: - if (btintel_test_flag(hdev, INTEL_BOOTLOADER)) { - struct hci_command_hdr *cmd = (void *)skb->data; - __u16 opcode = le16_to_cpu(cmd->opcode); - - /* When in bootloader mode and the command 0xfc09 - * is received, it needs to be send down the - * bulk endpoint. So allocate a bulk URB instead. - */ - if (opcode == 0xfc09) - urb = alloc_bulk_urb(hdev, skb); - else - urb = alloc_ctrl_urb(hdev, skb); - - /* When the BTINTEL_HCI_OP_RESET command is issued to - * boot into the operational firmware, it will actually - * not send a command complete event. To keep the flow - * control working inject that event here. - */ - if (opcode == BTINTEL_HCI_OP_RESET) - inject_cmd_complete(hdev, opcode); - } else { - urb = alloc_ctrl_urb(hdev, skb); - } - if (IS_ERR(urb)) - return PTR_ERR(urb); - - hdev->stat.cmd_tx++; - return submit_or_queue_tx_urb(hdev, urb); - - case HCI_ACLDATA_PKT: - urb = alloc_bulk_urb(hdev, skb); - if (IS_ERR(urb)) - return PTR_ERR(urb); - - hdev->stat.acl_tx++; - return submit_or_queue_tx_urb(hdev, urb); - - case HCI_SCODATA_PKT: - if (!hci_dev_test_flag(hdev, HCI_USER_CHANNEL) && - hci_conn_num(hdev, SCO_LINK) < 1) - return -ENODEV; - - urb = alloc_isoc_urb(hdev, skb); - if (IS_ERR(urb)) - return PTR_ERR(urb); - - hdev->stat.sco_tx++; - return submit_tx_urb(hdev, urb); - - case HCI_ISODATA_PKT: - urb = alloc_bulk_urb(hdev, skb); - if (IS_ERR(urb)) - return PTR_ERR(urb); - - return submit_or_queue_tx_urb(hdev, urb); - } - - return -EILSEQ; -} - -static int btusb_setup_realtek(struct hci_dev *hdev) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - int ret; - - ret = btrtl_setup_realtek(hdev); - - if (btrealtek_test_flag(data->hdev, REALTEK_ALT6_CONTINUOUS_TX_CHIP)) - set_bit(BTUSB_ALT6_CONTINUOUS_TX, &data->flags); - - return ret; -} - -static int btusb_recv_event_realtek(struct hci_dev *hdev, struct sk_buff *skb) -{ - if (skb->len >= HCI_EVENT_HDR_SIZE + 1 && - skb->data[0] == HCI_EV_VENDOR && - skb->data[2] == RTK_SUB_EVENT_CODE_COREDUMP) { - struct rtk_dev_coredump_hdr hdr = { - .code = RTK_DEVCOREDUMP_CODE_MEMDUMP, - }; - - bt_dev_dbg(hdev, "RTL: received coredump vendor evt, len %u", - skb->len); - - btusb_rtl_alloc_devcoredump(hdev, &hdr, skb->data, skb->len); - kfree_skb(skb); - - return 0; - } - - return hci_recv_frame(hdev, skb); -} - -static void btusb_mtk_claim_iso_intf(struct btusb_data *data) -{ - struct btmtk_data *btmtk_data; - int err; - - if (!data->hdev) - return; - - btmtk_data = hci_get_priv(data->hdev); - if (!btmtk_data) - return; - - if (!btmtk_data->isopkt_intf) { - bt_dev_err(data->hdev, "Can't claim NULL iso interface"); - return; - } - - /* - * The function usb_driver_claim_interface() is documented to need - * locks held if it's not called from a probe routine. The code here - * is called from the hci_power_on workqueue, so grab the lock. - */ - device_lock(&btmtk_data->isopkt_intf->dev); - err = usb_driver_claim_interface(&btusb_driver, - btmtk_data->isopkt_intf, data); - device_unlock(&btmtk_data->isopkt_intf->dev); - if (err < 0) { - btmtk_data->isopkt_intf = NULL; - bt_dev_err(data->hdev, "Failed to claim iso interface: %d", err); - return; - } - - set_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags); - init_usb_anchor(&btmtk_data->isopkt_anchor); -} - -static void btusb_mtk_release_iso_intf(struct hci_dev *hdev) -{ - struct btmtk_data *btmtk_data; - - if (!hdev) - return; - - btmtk_data = hci_get_priv(hdev); - if (!btmtk_data) - return; - - if (test_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags)) { - usb_kill_anchored_urbs(&btmtk_data->isopkt_anchor); - clear_bit(BTMTK_ISOPKT_RUNNING, &btmtk_data->flags); - - if (btmtk_data->isopkt_skb) { - dev_kfree_skb_irq(btmtk_data->isopkt_skb); - btmtk_data->isopkt_skb = NULL; - } - - if (btmtk_data->isopkt_intf) { - usb_set_intfdata(btmtk_data->isopkt_intf, NULL); - usb_driver_release_interface(&btusb_driver, - btmtk_data->isopkt_intf); - btmtk_data->isopkt_intf = NULL; - } - } - - clear_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags); -} - -static int btusb_mtk_disconnect(struct hci_dev *hdev) -{ - /* This function describes the specific additional steps taken by MediaTek - * when Bluetooth usb driver's resume function is called. - */ - btusb_mtk_release_iso_intf(hdev); - - return 0; -} - -static int btusb_mtk_reset(struct hci_dev *hdev, void *rst_data) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct btmtk_data *btmtk_data = hci_get_priv(hdev); - int err; - - /* It's MediaTek specific bluetooth reset mechanism via USB */ - if (test_and_set_bit(BTMTK_HW_RESET_ACTIVE, &btmtk_data->flags)) { - bt_dev_err(hdev, "last reset failed? Not resetting again"); - return -EBUSY; - } - - err = usb_autopm_get_interface(data->intf); - if (err < 0) { - bt_dev_err(hdev, "Failed usb_autopm_get_interface: %d", err); - clear_bit(BTMTK_HW_RESET_ACTIVE, &btmtk_data->flags); - return err; - } - - /* Release MediaTek ISO data interface */ - btusb_mtk_release_iso_intf(hdev); - - btusb_prepare_reset(hdev); - - /* Toggle the hard reset line. The MediaTek device is going to - * yank itself off the USB and then replug. The cleanup is handled - * correctly on the way out (standard USB disconnect), and the new - * device is detected cleanly and bound to the driver again like - * it should be. - */ - if (data->reset_gpio) { - gpiod_set_value_cansleep(data->reset_gpio, 1); - msleep(200); - gpiod_set_value_cansleep(data->reset_gpio, 0); - return 0; - } - - err = btmtk_usb_subsys_reset(hdev, btmtk_data->dev_id); - - if (test_and_set_bit(BTUSB_RESET, &data->flags)) { - bt_dev_err(hdev, "last usb reset failed? Resetting again"); - usb_autopm_put_interface_no_suspend(data->intf); - } - - usb_queue_reset_device(data->intf); - clear_bit(BTMTK_HW_RESET_ACTIVE, &btmtk_data->flags); - - return err; -} - -static int btusb_send_frame_mtk(struct hci_dev *hdev, struct sk_buff *skb) -{ - struct urb *urb; - - BT_DBG("%s", hdev->name); - - if (hci_skb_pkt_type(skb) == HCI_ISODATA_PKT) { - urb = alloc_mtk_intr_urb(hdev, skb, btusb_tx_complete); - if (IS_ERR(urb)) - return PTR_ERR(urb); - - return submit_or_queue_tx_urb(hdev, urb); - } else { - return btusb_send_frame(hdev, skb); - } -} - -static inline bool platform_is_ryzen(void) -{ -#ifdef CONFIG_X86 - return boot_cpu_has(X86_FEATURE_ZEN); -#else - return false; -#endif -} - -static inline bool is_direct_child_of_root_hub(struct usb_device *udev) -{ - return udev->parent == udev->bus->root_hub; -} - -static int btusb_mtk_setup(struct hci_dev *hdev) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct btmtk_data *btmtk_data = hci_get_priv(hdev); - int err; - - /* MediaTek WMT vendor cmd requiring below USB resources to - * complete the handshake. - */ - btmtk_data->drv_name = btusb_driver.name; - btmtk_data->intf = data->intf; - btmtk_data->udev = data->udev; - btmtk_data->ctrl_anchor = &data->ctrl_anchor; - btmtk_data->reset_sync = btusb_mtk_reset; - - /* Claim ISO data interface and endpoint */ - if (!test_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags)) { - btmtk_data->isopkt_intf = usb_ifnum_to_if(data->udev, MTK_ISO_IFNUM); - btusb_mtk_claim_iso_intf(data); - } - - err = btmtk_usb_setup(hdev); - if (err) - return err; - - switch (btmtk_data->dev_id) { - case 0x7922: - case 0x7925: - /* - * All reports seen to be relevant to Ryzen-based laptops. These - * NICs are usually used as OEM components thanks to some sort - * of reference designs. - * - * Their popularity on other platforms is unclear. While there - * is still a chance that the quirk may exist on other - * platforms, be cautious and only apply the quirk to direct - * children of Ryzen platforms's root hubs for the time being. - * - * In most cases the root hub is on the SoC or PCH, which needs - * the quirk. Unfortunately, this can't distinguish root hubs on - * PCIe add-in cards. Such roughness should be acceptable, as - * PCIe USB controller add-in cards are less commonly used - * nowadays. On the other hand, applying the quirk doesn't hurt - * any functionalities either, as the device can still be used - * as a wakeup source if desired. - * - * Theoretically, we could retrieve the root hub's PCI vendor ID - * with some hierarchy magic, but that's too intrusive... - */ - if (platform_is_ryzen() && is_direct_child_of_root_hub(data->udev)) - set_bit(BTUSB_WAKEUP_BROKEN, &data->flags); - break; - } - - return 0; -} - -static int btusb_mtk_shutdown(struct hci_dev *hdev) -{ - int ret; - - ret = btmtk_usb_shutdown(hdev); - - /* Release MediaTek iso interface after shutdown */ - btusb_mtk_release_iso_intf(hdev); - - return ret; -} - -#ifdef CONFIG_PM -/* Configure an out-of-band gpio as wake-up pin, if specified in device tree */ -static int marvell_config_oob_wake(struct hci_dev *hdev) -{ - struct sk_buff *skb; - struct btusb_data *data = hci_get_drvdata(hdev); - struct device *dev = &data->udev->dev; - u16 pin, gap, opcode; - int ret; - u8 cmd[5]; - - /* Move on if no wakeup pin specified */ - if (of_property_read_u16(dev->of_node, "marvell,wakeup-pin", &pin) || - of_property_read_u16(dev->of_node, "marvell,wakeup-gap-ms", &gap)) - return 0; - - /* Vendor specific command to configure a GPIO as wake-up pin */ - opcode = hci_opcode_pack(0x3F, 0x59); - cmd[0] = opcode & 0xFF; - cmd[1] = opcode >> 8; - cmd[2] = 2; /* length of parameters that follow */ - cmd[3] = pin; - cmd[4] = gap; /* time in ms, for which wakeup pin should be asserted */ - - skb = bt_skb_alloc(sizeof(cmd), GFP_KERNEL); - if (!skb) { - bt_dev_err(hdev, "%s: No memory", __func__); - return -ENOMEM; - } - - skb_put_data(skb, cmd, sizeof(cmd)); - hci_skb_pkt_type(skb) = HCI_COMMAND_PKT; - - ret = btusb_send_frame(hdev, skb); - if (ret) { - bt_dev_err(hdev, "%s: configuration failed", __func__); - kfree_skb(skb); - return ret; - } - - return 0; -} -#else -static inline int marvell_config_oob_wake(struct hci_dev *hdev) -{ - return 0; -} -#endif - -static int btusb_set_bdaddr_marvell(struct hci_dev *hdev, - const bdaddr_t *bdaddr) -{ - struct sk_buff *skb; - u8 buf[8]; - long ret; - - buf[0] = 0xfe; - buf[1] = sizeof(bdaddr_t); - memcpy(buf + 2, bdaddr, sizeof(bdaddr_t)); - - skb = __hci_cmd_sync(hdev, 0xfc22, sizeof(buf), buf, HCI_INIT_TIMEOUT); - if (IS_ERR(skb)) { - ret = PTR_ERR(skb); - bt_dev_err(hdev, "changing Marvell device address failed (%ld)", - ret); - return ret; - } - kfree_skb(skb); - - return 0; -} - -static int btusb_set_bdaddr_ath3012(struct hci_dev *hdev, - const bdaddr_t *bdaddr) -{ - struct sk_buff *skb; - u8 buf[10]; - long ret; - - buf[0] = 0x01; - buf[1] = 0x01; - buf[2] = 0x00; - buf[3] = sizeof(bdaddr_t); - memcpy(buf + 4, bdaddr, sizeof(bdaddr_t)); - - skb = __hci_cmd_sync(hdev, 0xfc0b, sizeof(buf), buf, HCI_INIT_TIMEOUT); - if (IS_ERR(skb)) { - ret = PTR_ERR(skb); - bt_dev_err(hdev, "Change address command failed (%ld)", ret); - return ret; - } - kfree_skb(skb); - - return 0; -} - -static int btusb_set_bdaddr_wcn6855(struct hci_dev *hdev, - const bdaddr_t *bdaddr) -{ - bdaddr_t bdaddr_swapped; - struct sk_buff *skb; - long ret; - - baswap(&bdaddr_swapped, bdaddr); - - skb = __hci_cmd_sync_ev(hdev, 0xfc14, sizeof(bdaddr_swapped), - &bdaddr_swapped, HCI_EV_CMD_COMPLETE, - HCI_INIT_TIMEOUT); - if (IS_ERR(skb)) { - ret = PTR_ERR(skb); - bt_dev_err(hdev, "Change address command failed (%ld)", ret); - return ret; - } - kfree_skb(skb); - - return 0; -} - -#define QCA_MEMDUMP_ACL_HANDLE 0x2EDD -#define QCA_MEMDUMP_SIZE_MAX 0x100000 -#define QCA_MEMDUMP_VSE_CLASS 0x01 -#define QCA_MEMDUMP_MSG_TYPE 0x08 -#define QCA_MEMDUMP_PKT_SIZE 248 -#define QCA_LAST_SEQUENCE_NUM 0xffff - -struct qca_dump_hdr { - u8 vse_class; - u8 msg_type; - __le16 seqno; - u8 reserved; - union { - u8 data[0]; - struct { - __le32 ram_dump_size; - u8 data0[0]; - } __packed; - }; -} __packed; - - -static void btusb_dump_hdr_qca(struct hci_dev *hdev, struct sk_buff *skb) -{ - char buf[128]; - struct btqca_data *btqca_data = hci_get_priv(hdev); - struct qca_dump_info *qca_dump_ptr = &btqca_data->qca_dump; - - snprintf(buf, sizeof(buf), "Controller Name: 0x%x\n", - qca_dump_ptr->controller_id); - skb_put_data(skb, buf, strlen(buf)); - - snprintf(buf, sizeof(buf), "Firmware Version: 0x%x\n", - qca_dump_ptr->fw_version); - skb_put_data(skb, buf, strlen(buf)); - - snprintf(buf, sizeof(buf), "Driver: %s\nVendor: qca\n", - btusb_driver.name); - skb_put_data(skb, buf, strlen(buf)); - - snprintf(buf, sizeof(buf), "VID: 0x%x\nPID:0x%x\n", - qca_dump_ptr->id_vendor, qca_dump_ptr->id_product); - skb_put_data(skb, buf, strlen(buf)); - - snprintf(buf, sizeof(buf), "Lmp Subversion: 0x%x\n", - hdev->lmp_subver); - skb_put_data(skb, buf, strlen(buf)); -} - -static void btusb_coredump_qca(struct hci_dev *hdev) -{ - int err; - static const u8 param[] = { 0x26 }; - - err = __hci_cmd_send(hdev, 0xfc0c, 1, param); - if (err < 0) - bt_dev_err(hdev, "%s: triggle crash failed (%d)", __func__, err); -} - -/* Return: 0 on success, negative errno on failure. */ -static int handle_dump_pkt_qca(struct hci_dev *hdev, struct sk_buff *skb) -{ - int ret = 0; - unsigned int skip = 0; - u8 pkt_type; - u16 seqno; - u32 dump_size; - - struct qca_dump_hdr *dump_hdr; - struct btusb_data *btdata = hci_get_drvdata(hdev); - struct btqca_data *btqca_data = hci_get_priv(hdev); - struct qca_dump_info *qca_dump_ptr = &btqca_data->qca_dump; - struct usb_device *udev = btdata->udev; - - pkt_type = hci_skb_pkt_type(skb); - skip = sizeof(struct hci_event_hdr); - if (pkt_type == HCI_ACLDATA_PKT) - skip += sizeof(struct hci_acl_hdr); - - skb_pull(skb, skip); - dump_hdr = (struct qca_dump_hdr *)skb->data; - - seqno = le16_to_cpu(dump_hdr->seqno); - if (seqno == 0) { - set_bit(BTUSB_HW_SSR_ACTIVE, &btdata->flags); - dump_size = le32_to_cpu(dump_hdr->ram_dump_size); - if (!dump_size || (dump_size > QCA_MEMDUMP_SIZE_MAX)) { - ret = -EILSEQ; - bt_dev_err(hdev, "Invalid memdump size(%u)", - dump_size); - goto out; - } - - ret = hci_devcd_init(hdev, dump_size); - if (ret < 0) { - bt_dev_err(hdev, "memdump init error(%d)", ret); - goto out; - } - - qca_dump_ptr->ram_dump_size = dump_size; - qca_dump_ptr->ram_dump_seqno = 0; - - skb_pull(skb, offsetof(struct qca_dump_hdr, data0)); - - usb_disable_autosuspend(udev); - bt_dev_info(hdev, "%s memdump size(%u)\n", - (pkt_type == HCI_ACLDATA_PKT) ? "ACL" : "event", - dump_size); - } else { - skb_pull(skb, offsetof(struct qca_dump_hdr, data)); - } - - if (!qca_dump_ptr->ram_dump_size) { - ret = -EINVAL; - bt_dev_err(hdev, "memdump is not active"); - goto out; - } - - if ((seqno > qca_dump_ptr->ram_dump_seqno + 1) && seqno != QCA_LAST_SEQUENCE_NUM) { - dump_size = QCA_MEMDUMP_PKT_SIZE * (seqno - qca_dump_ptr->ram_dump_seqno - 1); - hci_devcd_append_pattern(hdev, 0x0, dump_size); - bt_dev_err(hdev, - "expected memdump seqno(%u) is not received(%u)\n", - qca_dump_ptr->ram_dump_seqno, seqno); - qca_dump_ptr->ram_dump_seqno = seqno; - kfree_skb(skb); - return ret; - } - - hci_devcd_append(hdev, skb); - qca_dump_ptr->ram_dump_seqno++; - if (seqno == QCA_LAST_SEQUENCE_NUM) { - bt_dev_info(hdev, - "memdump done: pkts(%u), total(%u)\n", - qca_dump_ptr->ram_dump_seqno, qca_dump_ptr->ram_dump_size); - - hci_devcd_complete(hdev); - goto out; - } - return ret; - -out: - if (qca_dump_ptr->ram_dump_size) - usb_enable_autosuspend(udev); - qca_dump_ptr->ram_dump_size = 0; - qca_dump_ptr->ram_dump_seqno = 0; - clear_bit(BTUSB_HW_SSR_ACTIVE, &btdata->flags); - - if (ret < 0) - kfree_skb(skb); - return ret; -} - -/* Return: true if the ACL packet is a dump packet, false otherwise. */ -static bool acl_pkt_is_dump_qca(struct hci_dev *hdev, struct sk_buff *skb) -{ - struct hci_event_hdr *event_hdr; - struct hci_acl_hdr *acl_hdr; - struct qca_dump_hdr *dump_hdr; - struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC); - bool is_dump = false; - - if (!clone) - return false; - - acl_hdr = skb_pull_data(clone, sizeof(*acl_hdr)); - if (!acl_hdr || (le16_to_cpu(acl_hdr->handle) != QCA_MEMDUMP_ACL_HANDLE)) - goto out; - - event_hdr = skb_pull_data(clone, sizeof(*event_hdr)); - if (!event_hdr || event_hdr->evt != HCI_EV_VENDOR) - goto out; - - dump_hdr = skb_pull_data(clone, sizeof(*dump_hdr)); - if (!dump_hdr || (dump_hdr->vse_class != QCA_MEMDUMP_VSE_CLASS) || - (dump_hdr->msg_type != QCA_MEMDUMP_MSG_TYPE)) - goto out; - - is_dump = true; -out: - consume_skb(clone); - return is_dump; -} - -/* Return: true if the event packet is a dump packet, false otherwise. */ -static bool evt_pkt_is_dump_qca(struct hci_dev *hdev, struct sk_buff *skb) -{ - struct hci_event_hdr *event_hdr; - struct qca_dump_hdr *dump_hdr; - struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC); - bool is_dump = false; - - if (!clone) - return false; - - event_hdr = skb_pull_data(clone, sizeof(*event_hdr)); - if (!event_hdr || event_hdr->evt != HCI_EV_VENDOR) - goto out; - - dump_hdr = skb_pull_data(clone, sizeof(*dump_hdr)); - if (!dump_hdr || (dump_hdr->vse_class != QCA_MEMDUMP_VSE_CLASS) || - (dump_hdr->msg_type != QCA_MEMDUMP_MSG_TYPE)) - goto out; - - is_dump = true; -out: - consume_skb(clone); - return is_dump; -} - -static int btusb_recv_acl_qca(struct hci_dev *hdev, struct sk_buff *skb) -{ - if (acl_pkt_is_dump_qca(hdev, skb)) - return handle_dump_pkt_qca(hdev, skb); - return hci_recv_frame(hdev, skb); -} - -static int btusb_recv_evt_qca(struct hci_dev *hdev, struct sk_buff *skb) -{ - if (evt_pkt_is_dump_qca(hdev, skb)) - return handle_dump_pkt_qca(hdev, skb); - return hci_recv_frame(hdev, skb); -} - - -#define QCA_DFU_PACKET_LEN 4096 - -#define QCA_GET_TARGET_VERSION 0x09 -#define QCA_CHECK_STATUS 0x05 -#define QCA_DFU_DOWNLOAD 0x01 - -#define QCA_SYSCFG_UPDATED 0x40 -#define QCA_PATCH_UPDATED 0x80 -#define QCA_DFU_TIMEOUT 3000 -#define QCA_FLAG_MULTI_NVM 0x80 -#define QCA_BT_RESET_WAIT_MS 100 - -#define WCN6855_2_0_RAM_VERSION_GF 0x400c1200 -#define WCN6855_2_1_RAM_VERSION_GF 0x400c1211 - -struct qca_version { - __le32 rom_version; - __le32 patch_version; - __le32 ram_version; - __u8 chip_id; - __u8 platform_id; - __le16 flag; - __u8 reserved[4]; -} __packed; - -struct qca_rampatch_version { - __le16 rom_version_high; - __le16 rom_version_low; - __le16 patch_version; -} __packed; - -struct qca_device_info { - u32 rom_version; - u8 rampatch_hdr; /* length of header in rampatch */ - u8 nvm_hdr; /* length of header in NVM */ - u8 ver_offset; /* offset of version structure in rampatch */ -}; - -struct qca_custom_firmware { - u32 rom_version; - u16 board_id; - const char *subdirectory; -}; - -static const struct qca_device_info qca_devices_table[] = { - { 0x00000100, 20, 4, 8 }, /* Rome 1.0 */ - { 0x00000101, 20, 4, 8 }, /* Rome 1.1 */ - { 0x00000200, 28, 4, 16 }, /* Rome 2.0 */ - { 0x00000201, 28, 4, 16 }, /* Rome 2.1 */ - { 0x00000300, 28, 4, 16 }, /* Rome 3.0 */ - { 0x00000302, 28, 4, 16 }, /* Rome 3.2 */ - { 0x00130100, 40, 4, 16 }, /* WCN6855 1.0 */ - { 0x00130200, 40, 4, 16 }, /* WCN6855 2.0 */ - { 0x00130201, 40, 4, 16 }, /* WCN6855 2.1 */ - { 0x00190200, 40, 4, 16 }, /* WCN785x 2.0 */ -}; - -static const struct qca_custom_firmware qca_custom_btfws[] = { - { 0x00130201, 0x030A, "QCA2066" }, - { 0x00130201, 0x030B, "QCA2066" }, - { }, -}; - -static u16 qca_extract_board_id(const struct qca_version *ver) -{ - u16 flag = le16_to_cpu(ver->flag); - u16 board_id = 0; - - if (((flag >> 8) & 0xff) == QCA_FLAG_MULTI_NVM) { - /* The board_id should be split into two bytes - * The 1st byte is chip ID, and the 2nd byte is platform ID - * For example, board ID 0x010A, 0x01 is platform ID. 0x0A is chip ID - * we have several platforms, and platform IDs are continuously added - * Platform ID: - * 0x00 is for Mobile - * 0x01 is for X86 - * 0x02 is for Automotive - * 0x03 is for Consumer electronic - */ - board_id = (ver->chip_id << 8) + ver->platform_id; - } - - /* Take 0xffff as invalid board ID */ - if (board_id == 0xffff) - board_id = 0; - - return board_id; -} - -static const char *qca_get_fw_subdirectory(const struct qca_version *ver) -{ - const struct qca_custom_firmware *ptr; - u32 rom_ver; - u16 board_id; - - rom_ver = le32_to_cpu(ver->rom_version); - board_id = qca_extract_board_id(ver); - if (!board_id) - return NULL; - - for (ptr = qca_custom_btfws; ptr->rom_version; ptr++) { - if (ptr->rom_version == rom_ver && - ptr->board_id == board_id) - return ptr->subdirectory; - } - - return NULL; -} - -static int btusb_qca_send_vendor_req(struct usb_device *udev, u8 request, - void *data, u16 size) -{ - int err; - - /* Found some of USB hosts have IOT issues with ours so that we should - * not wait until HCI layer is ready. - */ - err = usb_control_msg_recv(udev, 0, request, USB_TYPE_VENDOR | USB_DIR_IN, - 0, 0, data, size, USB_CTRL_GET_TIMEOUT, - GFP_KERNEL); - if (err) - dev_err(&udev->dev, "Failed to access otp area (%d)", err); - - return err; -} - -static int btusb_setup_qca_download_fw(struct hci_dev *hdev, - const struct firmware *firmware, - size_t hdr_size) -{ - struct btusb_data *btdata = hci_get_drvdata(hdev); - struct usb_device *udev = btdata->udev; - size_t count, size, sent = 0; - int pipe, len, err; - u8 *buf; - - buf = kmalloc(QCA_DFU_PACKET_LEN, GFP_KERNEL); - if (!buf) - return -ENOMEM; - - count = firmware->size; - - size = min_t(size_t, count, hdr_size); - memcpy(buf, firmware->data, size); - - /* USB patches should go down to controller through USB path - * because binary format fits to go down through USB channel. - * USB control path is for patching headers and USB bulk is for - * patch body. - */ - pipe = usb_sndctrlpipe(udev, 0); - err = usb_control_msg(udev, pipe, QCA_DFU_DOWNLOAD, USB_TYPE_VENDOR, - 0, 0, buf, size, USB_CTRL_SET_TIMEOUT); - if (err < 0) { - bt_dev_err(hdev, "Failed to send headers (%d)", err); - goto done; - } - - sent += size; - count -= size; - - /* ep2 need time to switch from function acl to function dfu, - * so we add 20ms delay here. - */ - msleep(20); - - while (count) { - size = min_t(size_t, count, QCA_DFU_PACKET_LEN); - - memcpy(buf, firmware->data + sent, size); - - pipe = usb_sndbulkpipe(udev, 0x02); - err = usb_bulk_msg(udev, pipe, buf, size, &len, - QCA_DFU_TIMEOUT); - if (err < 0) { - bt_dev_err(hdev, "Failed to send body at %zd of %zd (%d)", - sent, firmware->size, err); - break; - } - - if (size != len) { - bt_dev_err(hdev, "Failed to get bulk buffer"); - err = -EILSEQ; - break; - } - - sent += size; - count -= size; - } - -done: - kfree(buf); - return err; -} - -static int btusb_setup_qca_load_rampatch(struct hci_dev *hdev, - struct qca_version *ver, - const struct qca_device_info *info) -{ - struct qca_rampatch_version *rver; - const struct firmware *fw; - const char *fw_subdir; - u32 ver_rom, ver_patch, rver_rom; - u16 rver_rom_low, rver_rom_high, rver_patch; - char fwname[80]; - int err; - - ver_rom = le32_to_cpu(ver->rom_version); - ver_patch = le32_to_cpu(ver->patch_version); - - fw_subdir = qca_get_fw_subdirectory(ver); - if (fw_subdir) - snprintf(fwname, sizeof(fwname), "qca/%s/rampatch_usb_%08x.bin", - fw_subdir, ver_rom); - else - snprintf(fwname, sizeof(fwname), "qca/rampatch_usb_%08x.bin", - ver_rom); - - err = request_firmware(&fw, fwname, &hdev->dev); - if (err) { - bt_dev_err(hdev, "failed to request rampatch file: %s (%d)", - fwname, err); - return err; - } - - bt_dev_info(hdev, "using rampatch file: %s", fwname); - - rver = (struct qca_rampatch_version *)(fw->data + info->ver_offset); - rver_rom_low = le16_to_cpu(rver->rom_version_low); - rver_patch = le16_to_cpu(rver->patch_version); - - if (ver_rom & ~0xffffU) { - rver_rom_high = le16_to_cpu(rver->rom_version_high); - rver_rom = rver_rom_high << 16 | rver_rom_low; - } else { - rver_rom = rver_rom_low; - } - - bt_dev_info(hdev, "QCA: patch rome 0x%x build 0x%x, " - "firmware rome 0x%x build 0x%x", - rver_rom, rver_patch, ver_rom, ver_patch); - - /* Allow rampatch when the patch version equals the firmware version. - * A firmware download may be aborted by a transient USB error (e.g. - * disconnect) after the controller updates version info but before - * completion. - * Allowing equal versions enables re-flashing during recovery. - */ - if (rver_rom != ver_rom || rver_patch < ver_patch) { - bt_dev_err(hdev, "rampatch file version did not match with firmware"); - err = -EINVAL; - goto done; - } - - err = btusb_setup_qca_download_fw(hdev, fw, info->rampatch_hdr); - -done: - release_firmware(fw); - - return err; -} - -static void btusb_generate_qca_nvm_name(char *fwname, size_t max_size, - const struct qca_version *ver) -{ - u32 rom_version = le32_to_cpu(ver->rom_version); - const char *variant, *fw_subdir; - int len; - u16 board_id; - - fw_subdir = qca_get_fw_subdirectory(ver); - board_id = qca_extract_board_id(ver); - - switch (le32_to_cpu(ver->ram_version)) { - case WCN6855_2_0_RAM_VERSION_GF: - case WCN6855_2_1_RAM_VERSION_GF: - variant = "_gf"; - break; - default: - variant = NULL; - break; - } - - if (fw_subdir) - len = snprintf(fwname, max_size, "qca/%s/nvm_usb_%08x", - fw_subdir, rom_version); - else - len = snprintf(fwname, max_size, "qca/nvm_usb_%08x", - rom_version); - if (variant) - len += snprintf(fwname + len, max_size - len, "%s", variant); - if (board_id) - len += snprintf(fwname + len, max_size - len, "_%04x", board_id); - len += snprintf(fwname + len, max_size - len, ".bin"); -} - -static int btusb_setup_qca_load_nvm(struct hci_dev *hdev, - struct qca_version *ver, - const struct qca_device_info *info) -{ - const struct firmware *fw; - char fwname[80]; - int err; - - btusb_generate_qca_nvm_name(fwname, sizeof(fwname), ver); - - err = request_firmware(&fw, fwname, &hdev->dev); - if (err) { - bt_dev_err(hdev, "failed to request NVM file: %s (%d)", - fwname, err); - return err; - } - - bt_dev_info(hdev, "using NVM file: %s", fwname); - - err = btusb_setup_qca_download_fw(hdev, fw, info->nvm_hdr); - - release_firmware(fw); - - return err; -} - -/* identify the ROM version and check whether patches are needed */ -static bool btusb_qca_need_patch(struct usb_device *udev) -{ - struct qca_version ver; - - if (btusb_qca_send_vendor_req(udev, QCA_GET_TARGET_VERSION, &ver, - sizeof(ver))) - return false; - /* only low ROM versions need patches */ - return !(le32_to_cpu(ver.rom_version) & ~0xffffU); -} - -static int btusb_setup_qca(struct hci_dev *hdev) -{ - struct btusb_data *btdata = hci_get_drvdata(hdev); - struct usb_device *udev = btdata->udev; - const struct qca_device_info *info = NULL; - struct qca_version ver; - u32 ver_rom; - u8 status; - int i, err; - - err = btusb_qca_send_vendor_req(udev, QCA_GET_TARGET_VERSION, &ver, - sizeof(ver)); - if (err) - return err; - - ver_rom = le32_to_cpu(ver.rom_version); - - for (i = 0; i < ARRAY_SIZE(qca_devices_table); i++) { - if (ver_rom == qca_devices_table[i].rom_version) - info = &qca_devices_table[i]; - } - if (!info) { - /* If the rom_version is not matched in the qca_devices_table - * and the high ROM version is not zero, we assume this chip no - * need to load the rampatch and nvm. - */ - if (ver_rom & ~0xffffU) - return 0; - - bt_dev_err(hdev, "don't support firmware rome 0x%x", ver_rom); - return -ENODEV; - } - - err = btusb_qca_send_vendor_req(udev, QCA_CHECK_STATUS, &status, - sizeof(status)); - if (err) - return err; - - if (!(status & QCA_PATCH_UPDATED)) { - err = btusb_setup_qca_load_rampatch(hdev, &ver, info); - if (err < 0) - return err; - } - - err = btusb_qca_send_vendor_req(udev, QCA_GET_TARGET_VERSION, &ver, - sizeof(ver)); - if (err) - return err; - - if (btdata->match_id->driver_info & BTUSB_QCA_WCN6855) { - struct btqca_data *btqca_data = hci_get_priv(hdev); - - btqca_data->qca_dump.fw_version = le32_to_cpu(ver.patch_version); - btqca_data->qca_dump.controller_id = le32_to_cpu(ver.rom_version); - } - - if (!(status & QCA_SYSCFG_UPDATED)) { - err = btusb_setup_qca_load_nvm(hdev, &ver, info); - if (err < 0) - return err; - - /* WCN6855 2.1 and later will reset to apply firmware downloaded here, so - * wait ~100ms for reset Done then go ahead, otherwise, it maybe - * cause potential enable failure. - */ - if (info->rom_version >= 0x00130201) - msleep(QCA_BT_RESET_WAIT_MS); - } - - /* Mark HCI_OP_ENHANCED_SETUP_SYNC_CONN as broken as it doesn't seem to - * work with the likes of HSP/HFP mSBC. - */ - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_ENHANCED_SETUP_SYNC_CONN); - - return 0; -} - -static inline int __set_diag_interface(struct hci_dev *hdev) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct usb_interface *intf = data->diag; - int ret; - - if (!data->diag) - return -ENODEV; - - ret = usb_find_common_endpoints(intf->cur_altsetting, &data->diag_rx_ep, - &data->diag_tx_ep, NULL, NULL); - if (ret) { - bt_dev_err(hdev, "invalid diagnostic descriptors"); - return -ENODEV; - } - - return 0; -} - -static struct urb *alloc_diag_urb(struct hci_dev *hdev, bool enable) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct sk_buff *skb; - struct urb *urb; - unsigned int pipe; - - if (!data->diag_tx_ep) - return ERR_PTR(-ENODEV); - - urb = usb_alloc_urb(0, GFP_KERNEL); - if (!urb) - return ERR_PTR(-ENOMEM); - - skb = bt_skb_alloc(2, GFP_KERNEL); - if (!skb) { - usb_free_urb(urb); - return ERR_PTR(-ENOMEM); - } - - skb_put_u8(skb, 0xf0); - skb_put_u8(skb, enable); - - pipe = usb_sndbulkpipe(data->udev, data->diag_tx_ep->bEndpointAddress); - - usb_fill_bulk_urb(urb, data->udev, pipe, - skb->data, skb->len, btusb_tx_complete, skb); - - skb->dev = (void *)hdev; - - return urb; -} - -static int btusb_bcm_set_diag(struct hci_dev *hdev, bool enable) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct urb *urb; - - if (!data->diag) - return -ENODEV; - - if (!test_bit(HCI_RUNNING, &hdev->flags)) - return -ENETDOWN; - - urb = alloc_diag_urb(hdev, enable); - if (IS_ERR(urb)) - return PTR_ERR(urb); - - return submit_or_queue_tx_urb(hdev, urb); -} - -#ifdef CONFIG_PM -static irqreturn_t btusb_oob_wake_handler(int irq, void *priv) -{ - struct btusb_data *data = priv; - - pm_wakeup_event(&data->udev->dev, 0); - pm_system_wakeup(); - - /* Disable only if not already disabled (keep it balanced) */ - if (test_and_clear_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags)) { - disable_irq_nosync(irq); - disable_irq_wake(irq); - } - return IRQ_HANDLED; -} - -static const struct of_device_id btusb_match_table[] = { - { .compatible = "usb1286,204e" }, - { .compatible = "usbcf3,e300" }, /* QCA6174A */ - { .compatible = "usb4ca,301a" }, /* QCA6174A (Lite-On) */ - { } -}; -MODULE_DEVICE_TABLE(of, btusb_match_table); - -/* Use an oob wakeup pin? */ -static int btusb_config_oob_wake(struct hci_dev *hdev) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - struct device *dev = &data->udev->dev; - int irq, ret; - - clear_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags); - - if (!of_match_device(btusb_match_table, dev)) - return 0; - - /* Move on if no IRQ specified */ - irq = of_irq_get_byname(dev->of_node, "wakeup"); - if (irq <= 0) { - bt_dev_dbg(hdev, "%s: no OOB Wakeup IRQ in DT", __func__); - return 0; - } - - irq_set_status_flags(irq, IRQ_NOAUTOEN); - ret = request_irq(irq, btusb_oob_wake_handler, 0, "OOB Wake-on-BT", data); - if (ret) { - bt_dev_err(hdev, "%s: IRQ request failed", __func__); - return ret; - } - - ret = device_init_wakeup(dev, true); - if (ret) { - bt_dev_err(hdev, "%s: failed to init_wakeup", __func__); - goto err_free_irq; - } - - data->oob_wake_irq = irq; - bt_dev_info(hdev, "OOB Wake-on-BT configured at IRQ %u", irq); - - return 0; - -err_free_irq: - free_irq(irq, data); - - return ret; -} -#else -static inline int btusb_config_oob_wake(struct hci_dev *hdev) -{ - return 0; -} -#endif - -static void btusb_check_needs_reset_resume(struct usb_interface *intf) -{ - if (dmi_check_system(btusb_needs_reset_resume_table)) - interface_to_usbdev(intf)->quirks |= USB_QUIRK_RESET_RESUME; -} - -static bool btusb_wakeup(struct hci_dev *hdev) -{ - struct btusb_data *data = hci_get_drvdata(hdev); - - return device_may_wakeup(&data->udev->dev); -} - -static int btusb_shutdown_qca(struct hci_dev *hdev) -{ - int err; - - err = __hci_reset_sync(hdev); - if (err) - bt_dev_err(hdev, "HCI reset during shutdown failed"); - - return err; -} - -static ssize_t force_poll_sync_read(struct file *file, char __user *user_buf, - size_t count, loff_t *ppos) -{ - struct btusb_data *data = file->private_data; - char buf[3]; - - buf[0] = data->poll_sync ? 'Y' : 'N'; - buf[1] = '\n'; - buf[2] = '\0'; - return simple_read_from_buffer(user_buf, count, ppos, buf, 2); -} - -static ssize_t force_poll_sync_write(struct file *file, - const char __user *user_buf, - size_t count, loff_t *ppos) -{ - struct btusb_data *data = file->private_data; - bool enable; - int err; - - err = kstrtobool_from_user(user_buf, count, &enable); - if (err) - return err; - - /* Only allow changes while the adapter is down */ - if (test_bit(HCI_UP, &data->hdev->flags)) - return -EPERM; - - if (data->poll_sync == enable) - return -EALREADY; - - data->poll_sync = enable; - - return count; -} - -static const struct file_operations force_poll_sync_fops = { - .owner = THIS_MODULE, - .open = simple_open, - .read = force_poll_sync_read, - .write = force_poll_sync_write, - .llseek = default_llseek, -}; - -#define BTUSB_HCI_DRV_OP_SUPPORTED_ALTSETTINGS \ - hci_opcode_pack(HCI_DRV_OGF_DRIVER_SPECIFIC, 0x0000) -#define BTUSB_HCI_DRV_SUPPORTED_ALTSETTINGS_SIZE 0 -struct btusb_hci_drv_rp_supported_altsettings { - __u8 num; - __u8 altsettings[]; -} __packed; - -#define BTUSB_HCI_DRV_OP_SWITCH_ALTSETTING \ - hci_opcode_pack(HCI_DRV_OGF_DRIVER_SPECIFIC, 0x0001) -#define BTUSB_HCI_DRV_SWITCH_ALTSETTING_SIZE 1 -struct btusb_hci_drv_cmd_switch_altsetting { - __u8 altsetting; -} __packed; - -static const struct { - u16 opcode; - const char *desc; -} btusb_hci_drv_supported_commands[] = { - /* Common commands */ - { HCI_DRV_OP_READ_INFO, "Read Info" }, - - /* Driver specific commands */ - { BTUSB_HCI_DRV_OP_SUPPORTED_ALTSETTINGS, "Supported Altsettings" }, - { BTUSB_HCI_DRV_OP_SWITCH_ALTSETTING, "Switch Altsetting" }, -}; -static int btusb_hci_drv_read_info(struct hci_dev *hdev, void *data, - u16 data_len) -{ - struct hci_drv_rp_read_info *rp; - size_t rp_size; - int err, i; - u16 opcode, num_supported_commands = - ARRAY_SIZE(btusb_hci_drv_supported_commands); - - rp_size = sizeof(*rp) + num_supported_commands * 2; - - rp = kmalloc(rp_size, GFP_KERNEL); - if (!rp) - return -ENOMEM; - - strscpy_pad(rp->driver_name, btusb_driver.name); - - rp->num_supported_commands = cpu_to_le16(num_supported_commands); - for (i = 0; i < num_supported_commands; i++) { - opcode = btusb_hci_drv_supported_commands[i].opcode; - bt_dev_info(hdev, - "Supported HCI Drv command (0x%02x|0x%04x): %s", - hci_opcode_ogf(opcode), - hci_opcode_ocf(opcode), - btusb_hci_drv_supported_commands[i].desc); - rp->supported_commands[i] = cpu_to_le16(opcode); - } - - err = hci_drv_cmd_complete(hdev, HCI_DRV_OP_READ_INFO, - HCI_DRV_STATUS_SUCCESS, rp, rp_size); - - kfree(rp); - return err; -} - -static int btusb_hci_drv_supported_altsettings(struct hci_dev *hdev, void *data, - u16 data_len) -{ - struct btusb_data *drvdata = hci_get_drvdata(hdev); - struct btusb_hci_drv_rp_supported_altsettings *rp; - size_t rp_size; - int err; - u8 i; - - /* There are at most 7 alt (0 - 6) */ - rp = kmalloc(sizeof(*rp) + 7, GFP_KERNEL); - if (!rp) - return -ENOMEM; - - rp->num = 0; - if (!drvdata->isoc) - goto done; - - for (i = 0; i <= 6; i++) { - if (btusb_find_altsetting(drvdata, i)) - rp->altsettings[rp->num++] = i; - } - -done: - rp_size = sizeof(*rp) + rp->num; - - err = hci_drv_cmd_complete(hdev, BTUSB_HCI_DRV_OP_SUPPORTED_ALTSETTINGS, - HCI_DRV_STATUS_SUCCESS, rp, rp_size); - kfree(rp); - return err; -} - -static int btusb_hci_drv_switch_altsetting(struct hci_dev *hdev, void *data, - u16 data_len) -{ - struct btusb_hci_drv_cmd_switch_altsetting *cmd = data; - u8 status; - - if (cmd->altsetting > 6) { - status = HCI_DRV_STATUS_INVALID_PARAMETERS; - } else { - if (btusb_switch_alt_setting(hdev, cmd->altsetting)) - status = HCI_DRV_STATUS_UNSPECIFIED_ERROR; - else - status = HCI_DRV_STATUS_SUCCESS; - } - - return hci_drv_cmd_status(hdev, BTUSB_HCI_DRV_OP_SWITCH_ALTSETTING, - status); -} - -static const struct hci_drv_handler btusb_hci_drv_common_handlers[] = { - { btusb_hci_drv_read_info, HCI_DRV_READ_INFO_SIZE }, -}; - -static const struct hci_drv_handler btusb_hci_drv_specific_handlers[] = { - { btusb_hci_drv_supported_altsettings, - BTUSB_HCI_DRV_SUPPORTED_ALTSETTINGS_SIZE }, - { btusb_hci_drv_switch_altsetting, - BTUSB_HCI_DRV_SWITCH_ALTSETTING_SIZE }, -}; - -static struct hci_drv btusb_hci_drv = { - .common_handler_count = ARRAY_SIZE(btusb_hci_drv_common_handlers), - .common_handlers = btusb_hci_drv_common_handlers, - .specific_handler_count = ARRAY_SIZE(btusb_hci_drv_specific_handlers), - .specific_handlers = btusb_hci_drv_specific_handlers, -}; - -static int btusb_probe(struct usb_interface *intf, - const struct usb_device_id *id) -{ - struct gpio_desc *reset_gpio; - struct btusb_data *data; - struct hci_dev *hdev; - unsigned ifnum_base; - int err, priv_size = 0; - - BT_DBG("intf %p id %p", intf, id); - - if ((id->driver_info & BTUSB_IFNUM_2) && - (intf->cur_altsetting->desc.bInterfaceNumber != 0) && - (intf->cur_altsetting->desc.bInterfaceNumber != 2)) - return -ENODEV; - - ifnum_base = intf->cur_altsetting->desc.bInterfaceNumber; - - if (!id->driver_info) { - const struct usb_device_id *match; - - match = usb_match_id(intf, quirks_table); - if (match) - id = match; - } - - if (id->driver_info & BTUSB_IGNORE) - return -ENODEV; - - if (id->driver_info & BTUSB_ATH3012) { - struct usb_device *udev = interface_to_usbdev(intf); - - /* Old firmware would otherwise let ath3k driver load - * patch and sysconfig files - */ - if (le16_to_cpu(udev->descriptor.bcdDevice) <= 0x0001 && - !btusb_qca_need_patch(udev)) - return -ENODEV; - } - - data = kzalloc_obj(*data); - if (!data) - return -ENOMEM; - - data->match_id = id; - err = usb_find_common_endpoints(intf->cur_altsetting, &data->bulk_rx_ep, - &data->bulk_tx_ep, &data->intr_ep, NULL); - if (err) - goto err_free_data; - - if (id->driver_info & BTUSB_AMP) { - data->cmdreq_type = USB_TYPE_CLASS | 0x01; - data->cmdreq = 0x2b; - } else { - data->cmdreq_type = USB_TYPE_CLASS; - data->cmdreq = 0x00; - } - - data->udev = interface_to_usbdev(intf); - data->intf = intf; - - INIT_WORK(&data->work, btusb_work); - INIT_WORK(&data->waker, btusb_waker); - INIT_DELAYED_WORK(&data->rx_work, btusb_rx_work); - - skb_queue_head_init(&data->acl_q); - - init_usb_anchor(&data->deferred); - init_usb_anchor(&data->tx_anchor); - spin_lock_init(&data->txlock); - - init_usb_anchor(&data->intr_anchor); - init_usb_anchor(&data->bulk_anchor); - init_usb_anchor(&data->isoc_anchor); - init_usb_anchor(&data->diag_anchor); - init_usb_anchor(&data->ctrl_anchor); - spin_lock_init(&data->rxlock); - - data->recv_event = hci_recv_frame; - data->recv_bulk = btusb_recv_bulk; - - if (id->driver_info & BTUSB_INTEL_COMBINED) { - /* Allocate extra space for Intel device */ - priv_size += sizeof(struct btintel_data); - - /* Override the rx handlers */ - data->recv_event = btintel_recv_event; - data->recv_bulk = btusb_recv_bulk_intel; - } else if (id->driver_info & BTUSB_REALTEK) { - /* Allocate extra space for Realtek device */ - priv_size += sizeof(struct btrealtek_data); - - data->recv_event = btusb_recv_event_realtek; - } else if (id->driver_info & BTUSB_MEDIATEK) { - /* Allocate extra space for Mediatek device */ - priv_size += sizeof(struct btmtk_data); - } else if (id->driver_info & BTUSB_QCA_WCN6855) { - /* Allocate extra space for QCA WCN6855 device */ - priv_size += sizeof(struct btqca_data); - } - - data->recv_acl = hci_recv_frame; - - hdev = hci_alloc_dev_priv(priv_size); - if (!hdev) { - err = -ENOMEM; - goto err_free_data; - } - - hdev->bus = HCI_USB; - hci_set_drvdata(hdev, data); - - data->hdev = hdev; - - SET_HCIDEV_DEV(hdev, &intf->dev); - - reset_gpio = gpiod_get_optional(&data->udev->dev, "reset", - GPIOD_OUT_LOW); - if (IS_ERR(reset_gpio)) { - err = PTR_ERR(reset_gpio); - goto err_free_hdev; - } else if (reset_gpio) { - data->reset_gpio = reset_gpio; - } - - hdev->open = btusb_open; - hdev->close = btusb_close; - hdev->flush = btusb_flush; - hdev->send = btusb_send_frame; - hdev->notify = btusb_notify; - hdev->wakeup = btusb_wakeup; - hdev->hci_drv = &btusb_hci_drv; - - err = btusb_config_oob_wake(hdev); - if (err) - goto err_put_reset; - - /* Marvell devices may need a specific chip configuration */ - if (id->driver_info & BTUSB_MARVELL && data->oob_wake_irq) { - err = marvell_config_oob_wake(hdev); - if (err) - goto err_disable_wakeup; - } - - if (id->driver_info & BTUSB_CW6622) - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_STORED_LINK_KEY); - - if (id->driver_info & BTUSB_BCM2045) - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_STORED_LINK_KEY); - - if (id->driver_info & BTUSB_BCM92035) - hdev->setup = btusb_setup_bcm92035; - - if (IS_ENABLED(CONFIG_BT_HCIBTUSB_BCM) && - (id->driver_info & BTUSB_BCM_PATCHRAM)) { - hdev->manufacturer = 15; - hdev->setup = btbcm_setup_patchram; - hdev->set_diag = btusb_bcm_set_diag; - hdev->set_bdaddr = btbcm_set_bdaddr; - - /* Broadcom LM_DIAG Interface numbers are hardcoded */ - data->diag = usb_ifnum_to_if(data->udev, ifnum_base + 2); - } - - if (IS_ENABLED(CONFIG_BT_HCIBTUSB_BCM) && - (id->driver_info & BTUSB_BCM_APPLE)) { - hdev->manufacturer = 15; - hdev->setup = btbcm_setup_apple; - hdev->set_diag = btusb_bcm_set_diag; - - /* Broadcom LM_DIAG Interface numbers are hardcoded */ - data->diag = usb_ifnum_to_if(data->udev, ifnum_base + 2); - } - - /* Combined Intel Device setup to support multiple setup routine */ - if (id->driver_info & BTUSB_INTEL_COMBINED) { - err = btintel_configure_setup(hdev, btusb_driver.name); - if (err) - goto err_kill_tx_urbs; - - /* Transport specific configuration */ - hdev->send = btusb_send_frame_intel; - hdev->reset = btusb_intel_reset; - - if (id->driver_info & BTUSB_INTEL_NO_WBS_SUPPORT) - btintel_set_flag(hdev, INTEL_ROM_LEGACY_NO_WBS_SUPPORT); - - if (id->driver_info & BTUSB_INTEL_BROKEN_INITIAL_NCMD) - btintel_set_flag(hdev, INTEL_BROKEN_INITIAL_NCMD); - - if (id->driver_info & BTUSB_INTEL_BROKEN_SHUTDOWN_LED) - btintel_set_flag(hdev, INTEL_BROKEN_SHUTDOWN_LED); - } - - if (id->driver_info & BTUSB_MARVELL) - hdev->set_bdaddr = btusb_set_bdaddr_marvell; - - if (IS_ENABLED(CONFIG_BT_HCIBTUSB_MTK) && - (id->driver_info & BTUSB_MEDIATEK)) { - hdev->setup = btusb_mtk_setup; - hdev->shutdown = btusb_mtk_shutdown; - hdev->manufacturer = 70; - hdev->reset = btmtk_reset_sync; - hdev->set_bdaddr = btmtk_set_bdaddr; - hdev->send = btusb_send_frame_mtk; - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_ENHANCED_SETUP_SYNC_CONN); - hci_set_quirk(hdev, HCI_QUIRK_NON_PERSISTENT_SETUP); - data->recv_acl = btmtk_usb_recv_acl; - data->recv_event = btmtk_recv_event; - data->suspend = btmtk_usb_suspend; - data->resume = btmtk_usb_resume; - data->disconnect = btusb_mtk_disconnect; - } - - if (id->driver_info & BTUSB_SWAVE) { - hci_set_quirk(hdev, HCI_QUIRK_FIXUP_INQUIRY_MODE); - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_LOCAL_COMMANDS); - } - - if (id->driver_info & BTUSB_INTEL_BOOT) { - hdev->manufacturer = 2; - hci_set_quirk(hdev, HCI_QUIRK_RAW_DEVICE); - } - - if (id->driver_info & BTUSB_ATH3012) { - data->setup_on_usb = btusb_setup_qca; - hdev->set_bdaddr = btusb_set_bdaddr_ath3012; - hci_set_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY); - hci_set_quirk(hdev, HCI_QUIRK_STRICT_DUPLICATE_FILTER); - } - - if (id->driver_info & BTUSB_QCA_ROME) { - data->setup_on_usb = btusb_setup_qca; - hdev->shutdown = btusb_shutdown_qca; - hdev->set_bdaddr = btusb_set_bdaddr_ath3012; - hdev->reset = btusb_qca_reset; - hci_set_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY); - btusb_check_needs_reset_resume(intf); - } - - if (id->driver_info & BTUSB_QCA_WCN6855) { - struct btqca_data *btqca_data = hci_get_priv(hdev); - - btqca_data->qca_dump.id_vendor = id->idVendor; - btqca_data->qca_dump.id_product = id->idProduct; - data->recv_event = btusb_recv_evt_qca; - data->recv_acl = btusb_recv_acl_qca; - hci_devcd_register(hdev, btusb_coredump_qca, btusb_dump_hdr_qca, NULL); - data->setup_on_usb = btusb_setup_qca; - hdev->classify_pkt_type = btusb_classify_qca_pkt_type; - hdev->shutdown = btusb_shutdown_qca; - hdev->set_bdaddr = btusb_set_bdaddr_wcn6855; - hdev->reset = btusb_qca_reset; - hci_set_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY); - hci_set_msft_opcode(hdev, 0xFD70); - } - - if (id->driver_info & BTUSB_AMP) { - /* AMP controllers do not support SCO packets */ - data->isoc = NULL; - } else { - /* Interface orders are hardcoded in the specification */ - data->isoc = usb_ifnum_to_if(data->udev, ifnum_base + 1); - data->isoc_ifnum = ifnum_base + 1; - } - - if (IS_ENABLED(CONFIG_BT_HCIBTUSB_RTL) && - (id->driver_info & BTUSB_REALTEK)) { - btrtl_set_driver_name(hdev, btusb_driver.name); - hdev->setup = btusb_setup_realtek; - hdev->shutdown = btrtl_shutdown_realtek; - hdev->reset = btusb_rtl_reset; - hdev->hw_error = btusb_rtl_hw_error; - - /* Realtek devices need to set remote wakeup on auto-suspend */ - set_bit(BTUSB_WAKEUP_AUTOSUSPEND, &data->flags); - set_bit(BTUSB_USE_ALT3_FOR_WBS, &data->flags); - } - - if (id->driver_info & BTUSB_ACTIONS_SEMI) { - /* Support is advertised, but not implemented */ - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_ERR_DATA_REPORTING); - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_READ_TRANSMIT_POWER); - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_SET_RPA_TIMEOUT); - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_EXT_SCAN); - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_READ_ENC_KEY_SIZE); - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_EXT_CREATE_CONN); - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_WRITE_AUTH_PAYLOAD_TIMEOUT); - } - - if (!reset) - hci_set_quirk(hdev, HCI_QUIRK_RESET_ON_CLOSE); - - if (force_scofix || id->driver_info & BTUSB_WRONG_SCO_MTU) { - if (!disable_scofix) - hci_set_quirk(hdev, HCI_QUIRK_FIXUP_BUFFER_SIZE); - } - - if (id->driver_info & BTUSB_BROKEN_ISOC) - data->isoc = NULL; - - if (id->driver_info & BTUSB_WIDEBAND_SPEECH) - hci_set_quirk(hdev, HCI_QUIRK_WIDEBAND_SPEECH_SUPPORTED); - - if (id->driver_info & BTUSB_INVALID_LE_STATES) - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_LE_STATES); - - if (id->driver_info & BTUSB_BROKEN_EXT_SCAN) - hci_set_quirk(hdev, HCI_QUIRK_BROKEN_EXT_SCAN); - - if (id->driver_info & BTUSB_DIGIANSWER) { - data->cmdreq_type = USB_TYPE_VENDOR; - hci_set_quirk(hdev, HCI_QUIRK_RESET_ON_CLOSE); - } - - if (id->driver_info & BTUSB_CSR) { - struct usb_device *udev = data->udev; - u16 bcdDevice = le16_to_cpu(udev->descriptor.bcdDevice); - - /* Old firmware would otherwise execute USB reset */ - if (bcdDevice < 0x117) - hci_set_quirk(hdev, HCI_QUIRK_RESET_ON_CLOSE); - - /* This must be set first in case we disable it for fakes */ - hci_set_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY); - - /* Fake CSR devices with broken commands */ - if (le16_to_cpu(udev->descriptor.idVendor) == 0x0a12 && - le16_to_cpu(udev->descriptor.idProduct) == 0x0001) - hdev->setup = btusb_setup_csr; - } - - if (id->driver_info & BTUSB_SNIFFER) { - struct usb_device *udev = data->udev; - - /* New sniffer firmware has crippled HCI interface */ - if (le16_to_cpu(udev->descriptor.bcdDevice) > 0x997) - hci_set_quirk(hdev, HCI_QUIRK_RAW_DEVICE); - } - - if (id->driver_info & BTUSB_INTEL_BOOT) { - /* A bug in the bootloader causes that interrupt interface is - * only enabled after receiving SetInterface(0, AltSetting=0). - */ - err = usb_set_interface(data->udev, 0, 0); - if (err < 0) { - BT_ERR("failed to set interface 0, alt 0 %d", err); - goto err_kill_tx_urbs; - } - } - - if (data->isoc) { - err = usb_driver_claim_interface(&btusb_driver, - data->isoc, data); - if (err < 0) - goto err_kill_tx_urbs; - } - - if (IS_ENABLED(CONFIG_BT_HCIBTUSB_BCM) && data->diag) { - if (!usb_driver_claim_interface(&btusb_driver, - data->diag, data)) - __set_diag_interface(hdev); - else - data->diag = NULL; - } - - if (enable_autosuspend) - usb_enable_autosuspend(data->udev); - - data->poll_sync = enable_poll_sync; - - err = hci_register_dev(hdev); - if (err < 0) - goto err_release_siblings; - - usb_set_intfdata(intf, data); - - debugfs_create_file("force_poll_sync", 0644, hdev->debugfs, data, - &force_poll_sync_fops); - - return 0; - -err_release_siblings: - if (data->diag) { - usb_set_intfdata(data->diag, NULL); - usb_driver_release_interface(&btusb_driver, data->diag); - } - if (data->isoc) { - usb_set_intfdata(data->isoc, NULL); - usb_driver_release_interface(&btusb_driver, data->isoc); - } -err_kill_tx_urbs: - usb_kill_anchored_urbs(&data->tx_anchor); -err_disable_wakeup: - if (data->oob_wake_irq) { - device_init_wakeup(&data->udev->dev, false); - free_irq(data->oob_wake_irq, data); - } -err_put_reset: - if (data->reset_gpio) - gpiod_put(data->reset_gpio); -err_free_hdev: - hci_free_dev(hdev); -err_free_data: - kfree(data); - - return err; -} - -static void btusb_disconnect(struct usb_interface *intf) -{ - struct btusb_data *data = usb_get_intfdata(intf); - struct hci_dev *hdev; - - BT_DBG("intf %p", intf); - - if (!data) - return; - - hdev = data->hdev; - usb_set_intfdata(data->intf, NULL); - - if (data->isoc) - usb_set_intfdata(data->isoc, NULL); - - if (data->diag) - usb_set_intfdata(data->diag, NULL); - - if (data->disconnect) - data->disconnect(hdev); - - hci_unregister_dev(hdev); - - if (data->oob_wake_irq) { - device_init_wakeup(&data->udev->dev, false); - free_irq(data->oob_wake_irq, data); - } - - if (data->reset_gpio) - gpiod_put(data->reset_gpio); - - if (test_and_clear_bit(BTUSB_RESET, &data->flags)) - usb_autopm_put_interface_no_suspend(data->intf); - - if (intf == data->intf) { - if (data->isoc) - usb_driver_release_interface(&btusb_driver, data->isoc); - if (data->diag) - usb_driver_release_interface(&btusb_driver, data->diag); - } else if (intf == data->isoc) { - if (data->diag) - usb_driver_release_interface(&btusb_driver, data->diag); - usb_driver_release_interface(&btusb_driver, data->intf); - } else if (intf == data->diag) { - if (data->isoc) - usb_driver_release_interface(&btusb_driver, data->isoc); - usb_driver_release_interface(&btusb_driver, data->intf); - } - - hci_free_dev(hdev); - kfree(data); -} - -static int btusb_suspend(struct usb_interface *intf, pm_message_t message) -{ - struct btusb_data *data = usb_get_intfdata(intf); - - BT_DBG("intf %p", intf); - - /* - * It is reported that remote wakeup events could sometimes cause some - * adapters completely unresponsive. Resetting the xHCI root hub doesn't - * help at all, and recovering from such a state needs a power cycle. - * Since disabling remote wakeup simply causes the USB core to gate - * runtime autosuspend as well due to needs_remote_wakeup == 1, let's do - * this ourselves to make our life easier. The interface can be safely - * autosuspended as long as remote wakeup is disabled, i.e., after - * closing the HCI device. - * - * Don't auto-suspend if there are connections or discovery in progress. - * - * External suspend calls shall never fail. Specifically, a device with - * broken remote wakeup may still take the advantage of remote wakeup in - * order to wake up the system from sleep if userspace has enabled it as - * a wakeup source. - */ - if (PMSG_IS_AUTO(message) && - ((test_bit(BTUSB_WAKEUP_BROKEN, &data->flags) && data->intf->needs_remote_wakeup) || - hci_conn_count(data->hdev) || hci_discovery_active(data->hdev))) - return -EBUSY; - - if (data->suspend_count++) - return 0; - - spin_lock_irq(&data->txlock); - if (!(PMSG_IS_AUTO(message) && data->tx_in_flight)) { - set_bit(BTUSB_SUSPENDING, &data->flags); - spin_unlock_irq(&data->txlock); - } else { - spin_unlock_irq(&data->txlock); - data->suspend_count--; - return -EBUSY; - } - - cancel_work_sync(&data->work); - - if (data->suspend) - data->suspend(data->hdev); - - btusb_stop_traffic(data); - usb_kill_anchored_urbs(&data->tx_anchor); - - if (data->oob_wake_irq && device_may_wakeup(&data->udev->dev)) { - set_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags); - enable_irq_wake(data->oob_wake_irq); - enable_irq(data->oob_wake_irq); - } - - /* For global suspend, Realtek devices lose the loaded fw - * in them. But for autosuspend, firmware should remain. - * Actually, it depends on whether the usb host sends - * set feature (enable wakeup) or not. - */ - if (test_bit(BTUSB_WAKEUP_AUTOSUSPEND, &data->flags)) { - if (PMSG_IS_AUTO(message) && - device_can_wakeup(&data->udev->dev)) - data->udev->do_remote_wakeup = 1; - else if (!PMSG_IS_AUTO(message) && - !device_may_wakeup(&data->udev->dev)) { - data->udev->do_remote_wakeup = 0; - data->udev->reset_resume = 1; - } - } - - return 0; -} - -static void play_deferred(struct btusb_data *data) -{ - struct urb *urb; - int err; - - while ((urb = usb_get_from_anchor(&data->deferred))) { - usb_anchor_urb(urb, &data->tx_anchor); - - err = usb_submit_urb(urb, GFP_ATOMIC); - if (err < 0) { - if (err != -EPERM && err != -ENODEV) - BT_ERR("%s urb %p submission failed (%d)", - data->hdev->name, urb, -err); - kfree(urb->setup_packet); - usb_unanchor_urb(urb); - usb_free_urb(urb); - break; - } - - data->tx_in_flight++; - usb_free_urb(urb); - } - - /* Cleanup the rest deferred urbs. */ - while ((urb = usb_get_from_anchor(&data->deferred))) { - kfree(urb->setup_packet); - usb_free_urb(urb); - } -} - -static int btusb_resume(struct usb_interface *intf) -{ - struct btusb_data *data = usb_get_intfdata(intf); - struct hci_dev *hdev = data->hdev; - int err = 0; - - BT_DBG("intf %p", intf); - - if (--data->suspend_count) - return 0; - - /* Disable only if not already disabled (keep it balanced) */ - if (test_and_clear_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags)) { - disable_irq(data->oob_wake_irq); - disable_irq_wake(data->oob_wake_irq); - } - - if (!test_bit(HCI_RUNNING, &hdev->flags)) - goto done; - - if (test_bit(BTUSB_INTR_RUNNING, &data->flags)) { - err = btusb_submit_intr_urb(hdev, GFP_NOIO); - if (err < 0) { - clear_bit(BTUSB_INTR_RUNNING, &data->flags); - goto failed; - } - } - - if (test_bit(BTUSB_BULK_RUNNING, &data->flags)) { - err = btusb_submit_bulk_urb(hdev, GFP_NOIO); - if (err < 0) { - clear_bit(BTUSB_BULK_RUNNING, &data->flags); - goto failed; - } - - btusb_submit_bulk_urb(hdev, GFP_NOIO); - } - - if (test_bit(BTUSB_ISOC_RUNNING, &data->flags)) { - if (btusb_submit_isoc_urb(hdev, GFP_NOIO) < 0) - clear_bit(BTUSB_ISOC_RUNNING, &data->flags); - else - btusb_submit_isoc_urb(hdev, GFP_NOIO); - } - - if (data->resume) - data->resume(hdev); - - spin_lock_irq(&data->txlock); - play_deferred(data); - clear_bit(BTUSB_SUSPENDING, &data->flags); - spin_unlock_irq(&data->txlock); - schedule_work(&data->work); - - return 0; - -failed: - usb_scuttle_anchored_urbs(&data->deferred); -done: - spin_lock_irq(&data->txlock); - clear_bit(BTUSB_SUSPENDING, &data->flags); - spin_unlock_irq(&data->txlock); - - return err; -} - -#ifdef CONFIG_DEV_COREDUMP -static void btusb_coredump(struct device *dev) -{ - struct btusb_data *data = dev_get_drvdata(dev); - struct hci_dev *hdev = data->hdev; - - if (hdev->dump.coredump) - hdev->dump.coredump(hdev); -} -#endif - -static struct usb_driver btusb_driver = { - .name = "btusb", - .probe = btusb_probe, - .disconnect = btusb_disconnect, - .suspend = pm_ptr(btusb_suspend), - .resume = pm_ptr(btusb_resume), - .id_table = btusb_table, - .supports_autosuspend = 1, - .disable_hub_initiated_lpm = 1, - -#ifdef CONFIG_DEV_COREDUMP - .driver = { - .coredump = btusb_coredump, - }, -#endif -}; - -module_usb_driver(btusb_driver); - -module_param(disable_scofix, bool, 0644); -MODULE_PARM_DESC(disable_scofix, "Disable fixup of wrong SCO buffer size"); - -module_param(force_scofix, bool, 0644); -MODULE_PARM_DESC(force_scofix, "Force fixup of wrong SCO buffers size"); - -module_param(enable_autosuspend, bool, 0644); -MODULE_PARM_DESC(enable_autosuspend, "Enable USB autosuspend by default"); - -module_param(reset, bool, 0644); -MODULE_PARM_DESC(reset, "Send HCI reset command on initialization"); - -MODULE_AUTHOR("Marcel Holtmann "); -MODULE_DESCRIPTION("Generic Bluetooth USB driver ver " VERSION); -MODULE_VERSION(VERSION); -MODULE_LICENSE("GPL"); diff --git a/drivers/bluetooth/btusb_main.c b/drivers/bluetooth/btusb_main.c new file mode 100644 index 000000000000..67b7271c9eb9 --- /dev/null +++ b/drivers/bluetooth/btusb_main.c @@ -0,0 +1,4861 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * + * Generic Bluetooth USB driver + * + * Copyright (C) 2005-2008 Marcel Holtmann + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "btintel.h" +#include "btbcm.h" +#include "btrtl.h" +#include "btmtk.h" + +#define VERSION "0.8" + +static bool disable_scofix; +static bool force_scofix; +static bool enable_autosuspend = IS_ENABLED(CONFIG_BT_HCIBTUSB_AUTOSUSPEND); +static bool enable_poll_sync = IS_ENABLED(CONFIG_BT_HCIBTUSB_POLL_SYNC); +static bool reset = true; + +static struct usb_driver btusb_driver; + +#define BTUSB_IGNORE BIT(0) +#define BTUSB_DIGIANSWER BIT(1) +#define BTUSB_CSR BIT(2) +#define BTUSB_SNIFFER BIT(3) +#define BTUSB_BCM92035 BIT(4) +#define BTUSB_BROKEN_ISOC BIT(5) +#define BTUSB_WRONG_SCO_MTU BIT(6) +#define BTUSB_ATH3012 BIT(7) +#define BTUSB_INTEL_COMBINED BIT(8) +#define BTUSB_INTEL_BOOT BIT(9) +#define BTUSB_BCM_PATCHRAM BIT(10) +#define BTUSB_MARVELL BIT(11) +#define BTUSB_SWAVE BIT(12) +#define BTUSB_AMP BIT(13) +#define BTUSB_QCA_ROME BIT(14) +#define BTUSB_BCM_APPLE BIT(15) +#define BTUSB_REALTEK BIT(16) +#define BTUSB_BCM2045 BIT(17) +#define BTUSB_IFNUM_2 BIT(18) +#define BTUSB_CW6622 BIT(19) +#define BTUSB_MEDIATEK BIT(20) +#define BTUSB_WIDEBAND_SPEECH BIT(21) +#define BTUSB_INVALID_LE_STATES BIT(22) +#define BTUSB_QCA_WCN6855 BIT(23) +#define BTUSB_INTEL_BROKEN_SHUTDOWN_LED BIT(24) +#define BTUSB_INTEL_BROKEN_INITIAL_NCMD BIT(25) +#define BTUSB_INTEL_NO_WBS_SUPPORT BIT(26) +#define BTUSB_ACTIONS_SEMI BIT(27) +#define BTUSB_BARROT BIT(28) + +static const struct usb_device_id btusb_table[] = { + /* + * NXP IW610 (0471:0215): the composite device reports Bluetooth + * class at the whole-device level, so the generic entry below + * would also match this WiFi vendor interface. Ignore it here + * first so mwifiex-nxp can bind it instead. + */ + { USB_DEVICE_AND_INTERFACE_INFO(0x0471, 0x0215, 0xff, 0xff, 0xff), + .driver_info = BTUSB_IGNORE }, + + /* Generic Bluetooth USB device */ + { USB_DEVICE_INFO(0xe0, 0x01, 0x01) }, + + /* Generic Bluetooth AMP device */ + { USB_DEVICE_INFO(0xe0, 0x01, 0x04), .driver_info = BTUSB_AMP }, + + /* Generic Bluetooth USB interface */ + { USB_INTERFACE_INFO(0xe0, 0x01, 0x01) }, + + /* Apple-specific (Broadcom) devices */ + { USB_VENDOR_AND_INTERFACE_INFO(0x05ac, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_APPLE | BTUSB_IFNUM_2 }, + + /* MediaTek MT76x0E */ + { USB_DEVICE(0x0e8d, 0x763f) }, + + /* Broadcom SoftSailing reporting vendor specific */ + { USB_DEVICE(0x0a5c, 0x21e1) }, + + /* Apple MacBookPro 7,1 */ + { USB_DEVICE(0x05ac, 0x8213) }, + + /* Apple iMac11,1 */ + { USB_DEVICE(0x05ac, 0x8215) }, + + /* Apple MacBookPro6,2 */ + { USB_DEVICE(0x05ac, 0x8218) }, + + /* Apple MacBookAir3,1, MacBookAir3,2 */ + { USB_DEVICE(0x05ac, 0x821b) }, + + /* Apple MacBookAir4,1 */ + { USB_DEVICE(0x05ac, 0x821f) }, + + /* Apple MacBookPro8,2 */ + { USB_DEVICE(0x05ac, 0x821a) }, + + /* Apple MacMini5,1 */ + { USB_DEVICE(0x05ac, 0x8281) }, + + /* AVM BlueFRITZ! USB v2.0 */ + { USB_DEVICE(0x057c, 0x3800), .driver_info = BTUSB_SWAVE }, + + /* Bluetooth Ultraport Module from IBM */ + { USB_DEVICE(0x04bf, 0x030a) }, + + /* ALPS Modules with non-standard id */ + { USB_DEVICE(0x044e, 0x3001) }, + { USB_DEVICE(0x044e, 0x3002) }, + + /* Ericsson with non-standard id */ + { USB_DEVICE(0x0bdb, 0x1002) }, + + /* Canyon CN-BTU1 with HID interfaces */ + { USB_DEVICE(0x0c10, 0x0000) }, + + /* Broadcom BCM20702B0 (Dynex/Insignia) */ + { USB_DEVICE(0x19ff, 0x0239), .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Broadcom BCM43142A0 (Foxconn/Lenovo) */ + { USB_VENDOR_AND_INTERFACE_INFO(0x105b, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Broadcom BCM920703 (HTC Vive) */ + { USB_VENDOR_AND_INTERFACE_INFO(0x0bb4, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Foxconn - Hon Hai */ + { USB_VENDOR_AND_INTERFACE_INFO(0x0489, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Lite-On Technology - Broadcom based */ + { USB_VENDOR_AND_INTERFACE_INFO(0x04ca, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Broadcom devices with vendor specific id */ + { USB_VENDOR_AND_INTERFACE_INFO(0x0a5c, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* ASUSTek Computer - Broadcom based */ + { USB_VENDOR_AND_INTERFACE_INFO(0x0b05, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Belkin F8065bf - Broadcom based */ + { USB_VENDOR_AND_INTERFACE_INFO(0x050d, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* IMC Networks - Broadcom based */ + { USB_VENDOR_AND_INTERFACE_INFO(0x13d3, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Dell Computer - Broadcom based */ + { USB_VENDOR_AND_INTERFACE_INFO(0x413c, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Toshiba Corp - Broadcom based */ + { USB_VENDOR_AND_INTERFACE_INFO(0x0930, 0xff, 0x01, 0x01), + .driver_info = BTUSB_BCM_PATCHRAM }, + + /* Intel Bluetooth USB Bootloader (RAM module) */ + { USB_DEVICE(0x8087, 0x0a5a), + .driver_info = BTUSB_INTEL_BOOT | BTUSB_BROKEN_ISOC }, + + { } /* Terminating entry */ +}; + +MODULE_DEVICE_TABLE(usb, btusb_table); + +static const struct usb_device_id quirks_table[] = { + /* CSR BlueCore devices */ + { USB_DEVICE(0x0a12, 0x0001), .driver_info = BTUSB_CSR }, + + /* Broadcom BCM2033 without firmware */ + { USB_DEVICE(0x0a5c, 0x2033), .driver_info = BTUSB_IGNORE }, + + /* Broadcom BCM2045 devices */ + { USB_DEVICE(0x0a5c, 0x2045), .driver_info = BTUSB_BCM2045 }, + + /* Atheros 3011 with sflash firmware */ + { USB_DEVICE(0x0489, 0xe027), .driver_info = BTUSB_IGNORE }, + { USB_DEVICE(0x0489, 0xe03d), .driver_info = BTUSB_IGNORE }, + { USB_DEVICE(0x04f2, 0xaff1), .driver_info = BTUSB_IGNORE }, + { USB_DEVICE(0x0930, 0x0215), .driver_info = BTUSB_IGNORE }, + { USB_DEVICE(0x0cf3, 0x3002), .driver_info = BTUSB_IGNORE }, + { USB_DEVICE(0x0cf3, 0xe019), .driver_info = BTUSB_IGNORE }, + { USB_DEVICE(0x13d3, 0x3304), .driver_info = BTUSB_IGNORE }, + + /* Atheros AR9285 Malbec with sflash firmware */ + { USB_DEVICE(0x03f0, 0x311d), .driver_info = BTUSB_IGNORE }, + + /* Atheros 3012 with sflash firmware */ + { USB_DEVICE(0x0489, 0xe04d), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe04e), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe056), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe057), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe05f), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe076), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe078), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe095), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04c5, 0x1330), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3004), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3005), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3006), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3007), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3008), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x300b), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x300d), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x300f), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3010), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3014), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x04ca, 0x3018), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0930, 0x0219), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0930, 0x021c), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0930, 0x0220), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0930, 0x0227), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0b05, 0x17d0), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x0036), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x3004), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x3008), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x311d), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x311e), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x311f), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x3121), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x817a), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0x817b), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0xe003), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0xe004), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0xe005), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0cf3, 0xe006), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3362), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3375), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3393), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3395), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3402), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3408), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3423), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3432), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3472), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3474), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3487), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x13d3, 0x3490), .driver_info = BTUSB_ATH3012 }, + + /* Atheros AR5BBU12 with sflash firmware */ + { USB_DEVICE(0x0489, 0xe02c), .driver_info = BTUSB_IGNORE }, + + /* Atheros AR5BBU12 with sflash firmware */ + { USB_DEVICE(0x0489, 0xe036), .driver_info = BTUSB_ATH3012 }, + { USB_DEVICE(0x0489, 0xe03c), .driver_info = BTUSB_ATH3012 }, + + /* QCA ROME chipset */ + { USB_DEVICE(0x0cf3, 0x535b), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe007), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe009), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe010), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe300), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe301), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe360), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe500), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe092), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe09f), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0a2), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3011), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3015), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3016), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x301a), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3021), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3491), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3496), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3501), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3503), .driver_info = BTUSB_QCA_ROME | + BTUSB_WIDEBAND_SPEECH }, + + /* QCA WCN6855 chipset */ + { USB_DEVICE(0x0489, 0xe0c7), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0c9), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0ca), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0cb), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0cc), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0ce), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0d0), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0d6), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0de), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0df), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0e1), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0e3), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0ea), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0ec), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3022), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3023), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3024), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3a22), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3a24), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3a26), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3a27), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cf3, 0xe600), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9108), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9109), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9208), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9209), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9308), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9309), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9408), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9409), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9508), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9509), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9608), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9609), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x10ab, 0x9f09), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x28de, 0x1401), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + + /* QCA WCN785x chipset */ + { USB_DEVICE(0x0cf3, 0xe700), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0fc), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0f3), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe100), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe103), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe10a), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe10d), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe11b), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe11c), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe11f), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe141), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe14a), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe14b), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe14d), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3623), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3624), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2c7c, 0x0130), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2c7c, 0x0131), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2c7c, 0x0132), .driver_info = BTUSB_QCA_WCN6855 | + BTUSB_WIDEBAND_SPEECH }, + + /* Broadcom BCM2035 */ + { USB_DEVICE(0x0a5c, 0x2009), .driver_info = BTUSB_BCM92035 }, + { USB_DEVICE(0x0a5c, 0x200a), .driver_info = BTUSB_WRONG_SCO_MTU }, + { USB_DEVICE(0x0a5c, 0x2035), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* Broadcom BCM2045 */ + { USB_DEVICE(0x0a5c, 0x2039), .driver_info = BTUSB_WRONG_SCO_MTU }, + { USB_DEVICE(0x0a5c, 0x2101), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* IBM/Lenovo ThinkPad with Broadcom chip */ + { USB_DEVICE(0x0a5c, 0x201e), .driver_info = BTUSB_WRONG_SCO_MTU }, + { USB_DEVICE(0x0a5c, 0x2110), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* HP laptop with Broadcom chip */ + { USB_DEVICE(0x03f0, 0x171d), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* Dell laptop with Broadcom chip */ + { USB_DEVICE(0x413c, 0x8126), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* Dell Wireless 370 and 410 devices */ + { USB_DEVICE(0x413c, 0x8152), .driver_info = BTUSB_WRONG_SCO_MTU }, + { USB_DEVICE(0x413c, 0x8156), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* Belkin F8T012 and F8T013 devices */ + { USB_DEVICE(0x050d, 0x0012), .driver_info = BTUSB_WRONG_SCO_MTU }, + { USB_DEVICE(0x050d, 0x0013), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* Asus WL-BTD202 device */ + { USB_DEVICE(0x0b05, 0x1715), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* Kensington Bluetooth USB adapter */ + { USB_DEVICE(0x047d, 0x105e), .driver_info = BTUSB_WRONG_SCO_MTU }, + + /* RTX Telecom based adapters with buggy SCO support */ + { USB_DEVICE(0x0400, 0x0807), .driver_info = BTUSB_BROKEN_ISOC }, + { USB_DEVICE(0x0400, 0x080a), .driver_info = BTUSB_BROKEN_ISOC }, + + /* CONWISE Technology based adapters with buggy SCO support */ + { USB_DEVICE(0x0e5e, 0x6622), + .driver_info = BTUSB_BROKEN_ISOC | BTUSB_CW6622}, + + /* Roper Class 1 Bluetooth Dongle (Silicon Wave based) */ + { USB_DEVICE(0x1310, 0x0001), .driver_info = BTUSB_SWAVE }, + + /* Digianswer devices */ + { USB_DEVICE(0x08fd, 0x0001), .driver_info = BTUSB_DIGIANSWER }, + { USB_DEVICE(0x08fd, 0x0002), .driver_info = BTUSB_IGNORE }, + + /* CSR BlueCore Bluetooth Sniffer */ + { USB_DEVICE(0x0a12, 0x0002), + .driver_info = BTUSB_SNIFFER | BTUSB_BROKEN_ISOC }, + + /* Frontline ComProbe Bluetooth Sniffer */ + { USB_DEVICE(0x16d3, 0x0002), + .driver_info = BTUSB_SNIFFER | BTUSB_BROKEN_ISOC }, + + /* Marvell Bluetooth devices */ + { USB_DEVICE(0x1286, 0x2044), .driver_info = BTUSB_MARVELL }, + { USB_DEVICE(0x1286, 0x2046), .driver_info = BTUSB_MARVELL }, + { USB_DEVICE(0x1286, 0x204e), .driver_info = BTUSB_MARVELL }, + + /* + * NXP IW610 BT interfaces (Marvell-lineage silicon, same quirk as + * the 0x1286 entries above). Scoped to the BT interface class, + * not just VID/PID -- see the btusb_table entry above. + */ + { USB_DEVICE_AND_INTERFACE_INFO(0x0471, 0x0215, 0xe0, 0x01, 0x01), + .driver_info = BTUSB_MARVELL }, + + /* Intel Bluetooth devices */ + { USB_DEVICE(0x8087, 0x0025), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0026), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0029), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0032), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0033), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0035), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0036), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0037), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0038), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0039), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0040), .driver_info = BTUSB_INTEL_COMBINED }, /* Lizard Peak 2 */ + { USB_DEVICE(0x8087, 0x07da), .driver_info = BTUSB_CSR }, + { USB_DEVICE(0x8087, 0x07dc), .driver_info = BTUSB_INTEL_COMBINED | + BTUSB_INTEL_NO_WBS_SUPPORT | + BTUSB_INTEL_BROKEN_INITIAL_NCMD | + BTUSB_INTEL_BROKEN_SHUTDOWN_LED }, + { USB_DEVICE(0x8087, 0x0a2a), .driver_info = BTUSB_INTEL_COMBINED | + BTUSB_INTEL_NO_WBS_SUPPORT | + BTUSB_INTEL_BROKEN_SHUTDOWN_LED }, + { USB_DEVICE(0x8087, 0x0a2b), .driver_info = BTUSB_INTEL_COMBINED }, + { USB_DEVICE(0x8087, 0x0aa7), .driver_info = BTUSB_INTEL_COMBINED | + BTUSB_INTEL_BROKEN_SHUTDOWN_LED }, + { USB_DEVICE(0x8087, 0x0aaa), .driver_info = BTUSB_INTEL_COMBINED }, + + /* Other Intel Bluetooth devices */ + { USB_VENDOR_AND_INTERFACE_INFO(0x8087, 0xe0, 0x01, 0x01), + .driver_info = BTUSB_IGNORE }, + + /* Realtek 8821CE Bluetooth devices */ + { USB_DEVICE(0x13d3, 0x3529), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3533), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8822CE Bluetooth devices */ + { USB_DEVICE(0x0bda, 0xb00c), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0xc822), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8822CU Bluetooth devices */ + { USB_DEVICE(0x13d3, 0x3549), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8851BE Bluetooth devices */ + { USB_DEVICE(0x0bda, 0xb850), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3600), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3601), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x0489, 0xe112), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8851BU Bluetooth devices */ + { USB_DEVICE(0x3625, 0x010b), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2001, 0x332a), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x7392, 0xe611), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2c4e, 0x0128), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8852AE Bluetooth devices */ + { USB_DEVICE(0x0bda, 0x2852), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0xc852), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0x385a), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0x4852), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04c5, 0x165c), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x4006), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cb8, 0xc549), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8852CE Bluetooth devices */ + { USB_DEVICE(0x04ca, 0x4007), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04c5, 0x1675), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cb8, 0xc558), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3587), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3586), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3592), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3612), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe122), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8852BE Bluetooth devices */ + { USB_DEVICE(0x0cb8, 0xc559), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0x4853), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0x887b), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0xb85b), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3570), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3571), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3572), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3591), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe123), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe125), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8852BT/8852BE-VT Bluetooth devices */ + { USB_DEVICE(0x0bda, 0x8520), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe12f), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3618), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3619), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek 8922AE Bluetooth devices */ + { USB_DEVICE(0x0bda, 0x8922), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0xd922), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0xd923), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3617), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3616), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe130), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Realtek Bluetooth devices */ + { USB_VENDOR_AND_INTERFACE_INFO(0x0bda, 0xe0, 0x01, 0x01), + .driver_info = BTUSB_REALTEK }, + + /* MediaTek Bluetooth devices */ + { USB_VENDOR_AND_INTERFACE_INFO(0x0e8d, 0xe0, 0x01, 0x01), + .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Additional MediaTek MT7615E Bluetooth devices */ + { USB_DEVICE(0x13d3, 0x3560), .driver_info = BTUSB_MEDIATEK}, + + /* Additional MediaTek MT7663 Bluetooth devices */ + { USB_DEVICE(0x043e, 0x310c), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3801), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Additional MediaTek MT7668 Bluetooth devices */ + { USB_DEVICE(0x043e, 0x3109), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Additional MediaTek MT7920 Bluetooth devices */ + { USB_DEVICE(0x0489, 0xe134), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe135), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3620), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3621), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3622), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe158), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Additional MediaTek MT7921 Bluetooth devices */ + { USB_DEVICE(0x0489, 0xe0c8), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0cd), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0e0), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0f2), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3802), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0e8d, 0x0608), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3563), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3564), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3567), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3576), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3578), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3583), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3606), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + /* MediaTek MT7902 Bluetooth devices */ + { USB_DEVICE(0x0489, 0xe156), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0e8d, 0x1ede), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3579), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3580), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3594), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3596), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + /* MediaTek MT7922 Bluetooth devices */ + { USB_DEVICE(0x13d3, 0x3585), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3610), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + + /* MediaTek MT7922A Bluetooth devices */ + { USB_DEVICE(0x0489, 0xe0d8), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0d9), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0e2), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0e4), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0f1), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0f2), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0f5), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0f6), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe102), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe11d), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe152), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe153), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe170), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe174), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3804), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x3807), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04ca, 0x38e4), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0e8d, 0x223c), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3568), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3584), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3605), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3607), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3614), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3615), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3633), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x35f5, 0x7922), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Additional MediaTek MT7925 Bluetooth devices */ + { USB_DEVICE(0x0489, 0xe111), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe113), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe118), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe11e), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe124), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe139), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe13a), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe0fa), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe10f), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe110), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe116), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3588), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe14e), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe14f), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe150), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0489, 0xe151), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0e8d, 0x8c38), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3602), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3603), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3604), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3608), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3609), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3613), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3625), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3627), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3628), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3630), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2c7c, 0x7009), .driver_info = BTUSB_MEDIATEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Additional Realtek 8723AE Bluetooth devices */ + { USB_DEVICE(0x0930, 0x021d), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3394), .driver_info = BTUSB_REALTEK }, + + /* Additional Realtek 8723BE Bluetooth devices */ + { USB_DEVICE(0x0489, 0xe085), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x0489, 0xe08b), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x04f2, 0xb49f), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3410), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3416), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3459), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3494), .driver_info = BTUSB_REALTEK }, + + /* Additional Realtek 8723BU Bluetooth devices */ + { USB_DEVICE(0x7392, 0xa611), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x2c0a, 0x8761), .driver_info = BTUSB_REALTEK }, + + /* Additional Realtek 8723DE Bluetooth devices */ + { USB_DEVICE(0x0bda, 0xb009), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x2ff8, 0xb011), .driver_info = BTUSB_REALTEK }, + + /* Additional Realtek 8761BUV Bluetooth devices */ + { USB_DEVICE(0x2c4e, 0x0115), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2357, 0x0604), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2357, 0x0607), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0b05, 0x190e), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2550, 0x8761), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0x8771), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x6655, 0x8771), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x7392, 0xc611), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2b89, 0x8761), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2b89, 0x6275), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x37ad, 0x0600), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x14b0, 0x047a), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Additional Realtek 8761CU Bluetooth devices */ + { USB_DEVICE(0x0b05, 0x1bef), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0b05, 0x1d70), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Additional Realtek 8821AE Bluetooth devices */ + { USB_DEVICE(0x0b05, 0x17dc), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3414), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3458), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3461), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x13d3, 0x3462), .driver_info = BTUSB_REALTEK }, + + /* Additional Realtek 8822BE Bluetooth devices */ + { USB_DEVICE(0x13d3, 0x3526), .driver_info = BTUSB_REALTEK }, + { USB_DEVICE(0x0b05, 0x185c), .driver_info = BTUSB_REALTEK }, + + /* Additional Realtek 8822CE Bluetooth devices */ + { USB_DEVICE(0x04ca, 0x4005), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x04c5, 0x161f), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0b05, 0x18ef), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3548), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3549), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3553), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x13d3, 0x3555), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x2ff8, 0x3051), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x1358, 0xc123), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0bda, 0xc123), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x1357, 0xc123), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + { USB_DEVICE(0x0cb5, 0xc547), .driver_info = BTUSB_REALTEK | + BTUSB_WIDEBAND_SPEECH }, + + /* Barrot Technology Bluetooth devices */ + { USB_DEVICE(0x33fa, 0x0010), .driver_info = BTUSB_BARROT }, + { USB_DEVICE(0x33fa, 0x0012), .driver_info = BTUSB_BARROT }, + + /* Actions Semiconductor ATS2851 based devices */ + { USB_DEVICE(0x10d7, 0xb012), .driver_info = BTUSB_ACTIONS_SEMI }, + + /* Silicon Wave based devices */ + { USB_DEVICE(0x0c10, 0x0000), .driver_info = BTUSB_SWAVE }, + + { } /* Terminating entry */ +}; + +/* The Bluetooth USB module build into some devices needs to be reset on resume, + * this is a problem with the platform (likely shutting off all power) not with + * the module itself. So we use a DMI list to match known broken platforms. + */ +static const struct dmi_system_id btusb_needs_reset_resume_table[] = { + { + /* Dell OptiPlex 3060 (QCA ROME device 0cf3:e007) */ + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), + DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex 3060"), + }, + }, + { + /* Dell XPS 9360 (QCA ROME device 0cf3:e300) */ + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), + DMI_MATCH(DMI_PRODUCT_NAME, "XPS 13 9360"), + }, + }, + { + /* Dell Inspiron 5565 (QCA ROME device 0cf3:e009) */ + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."), + DMI_MATCH(DMI_PRODUCT_NAME, "Inspiron 5565"), + }, + }, + {} +}; + +struct qca_dump_info { + /* fields for dump collection */ + u16 id_vendor; + u16 id_product; + u32 fw_version; + u32 controller_id; + u32 ram_dump_size; + u16 ram_dump_seqno; +}; + +struct btqca_data { + struct qca_dump_info qca_dump; +}; + +#define BTUSB_MAX_ISOC_FRAMES 10 + +#define BTUSB_INTR_RUNNING 0 +#define BTUSB_BULK_RUNNING 1 +#define BTUSB_ISOC_RUNNING 2 +#define BTUSB_SUSPENDING 3 +#define BTUSB_DID_ISO_RESUME 4 +#define BTUSB_BOOTLOADER 5 +#define BTUSB_DOWNLOADING 6 +#define BTUSB_FIRMWARE_LOADED 7 +#define BTUSB_FIRMWARE_FAILED 8 +#define BTUSB_BOOTING 9 +#define BTUSB_DIAG_RUNNING 10 +#define BTUSB_OOB_WAKE_ENABLED 11 +#define BTUSB_HW_RESET_ACTIVE 12 +#define BTUSB_TX_WAIT_VND_EVT 13 +#define BTUSB_WAKEUP_AUTOSUSPEND 14 +#define BTUSB_USE_ALT3_FOR_WBS 15 +#define BTUSB_ALT6_CONTINUOUS_TX 16 +#define BTUSB_HW_SSR_ACTIVE 17 +#define BTUSB_WAKEUP_BROKEN 18 +#define BTUSB_RESET 19 + +struct btusb_data { + struct hci_dev *hdev; + struct usb_device *udev; + struct usb_interface *intf; + struct usb_interface *isoc; + struct usb_interface *diag; + unsigned isoc_ifnum; + + unsigned long flags; + + bool poll_sync; + int intr_interval; + struct work_struct work; + struct work_struct waker; + struct delayed_work rx_work; + + struct sk_buff_head acl_q; + + struct usb_anchor deferred; + struct usb_anchor tx_anchor; + int tx_in_flight; + spinlock_t txlock; + + struct usb_anchor intr_anchor; + struct usb_anchor bulk_anchor; + struct usb_anchor isoc_anchor; + struct usb_anchor diag_anchor; + struct usb_anchor ctrl_anchor; + spinlock_t rxlock; + + struct sk_buff *evt_skb; + struct sk_buff *acl_skb; + struct sk_buff *sco_skb; + + struct usb_endpoint_descriptor *intr_ep; + struct usb_endpoint_descriptor *bulk_tx_ep; + struct usb_endpoint_descriptor *bulk_rx_ep; + struct usb_endpoint_descriptor *isoc_tx_ep; + struct usb_endpoint_descriptor *isoc_rx_ep; + struct usb_endpoint_descriptor *diag_tx_ep; + struct usb_endpoint_descriptor *diag_rx_ep; + + struct gpio_desc *reset_gpio; + + __u8 cmdreq_type; + __u8 cmdreq; + + unsigned int sco_num; + unsigned int air_mode; + bool usb_alt6_packet_flow; + int isoc_altsetting; + int suspend_count; + const struct usb_device_id *match_id; + + int (*recv_event)(struct hci_dev *hdev, struct sk_buff *skb); + int (*recv_acl)(struct hci_dev *hdev, struct sk_buff *skb); + int (*recv_bulk)(struct btusb_data *data, void *buffer, int count); + + int (*setup_on_usb)(struct hci_dev *hdev); + + int (*suspend)(struct hci_dev *hdev); + int (*resume)(struct hci_dev *hdev); + int (*disconnect)(struct hci_dev *hdev); + + int oob_wake_irq; /* irq for out-of-band wake-on-bt */ +}; + +static void btusb_reset(struct hci_dev *hdev) +{ + struct btusb_data *data; + int err; + + data = hci_get_drvdata(hdev); + err = usb_autopm_get_interface(data->intf); + if (err) { + bt_dev_err(hdev, "Failed usb_autopm_get_interface: %d", err); + return; + } + + if (test_and_set_bit(BTUSB_RESET, &data->flags)) + usb_autopm_put_interface_no_suspend(data->intf); + + bt_dev_err(hdev, "Resetting usb device."); + usb_queue_reset_device(data->intf); +} + +static void btusb_intel_reset(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct gpio_desc *reset_gpio = data->reset_gpio; + struct btintel_data *intel_data = hci_get_priv(hdev); + + if (intel_data->acpi_reset_method) { + if (test_and_set_bit(INTEL_ACPI_RESET_ACTIVE, intel_data->flags)) { + bt_dev_err(hdev, "acpi: last reset failed ? Not resetting again"); + return; + } + + bt_dev_err(hdev, "Initiating acpi reset method"); + /* If ACPI reset method fails, lets try with legacy GPIO + * toggling + */ + if (!intel_data->acpi_reset_method(hdev)) { + return; + } + } + + if (!reset_gpio) { + btusb_reset(hdev); + return; + } + + /* + * Toggle the hard reset line if the platform provides one. The reset + * is going to yank the device off the USB and then replug. So doing + * once is enough. The cleanup is handled correctly on the way out + * (standard USB disconnect), and the new device is detected cleanly + * and bound to the driver again like it should be. + */ + if (test_and_set_bit(BTUSB_HW_RESET_ACTIVE, &data->flags)) { + bt_dev_err(hdev, "last reset failed? Not resetting again"); + return; + } + + bt_dev_err(hdev, "Initiating HW reset via gpio"); + gpiod_set_value_cansleep(reset_gpio, 1); + msleep(100); + gpiod_set_value_cansleep(reset_gpio, 0); +} + +#define RTK_DEVCOREDUMP_CODE_MEMDUMP 0x01 +#define RTK_DEVCOREDUMP_CODE_HW_ERR 0x02 +#define RTK_DEVCOREDUMP_CODE_CMD_TIMEOUT 0x03 + +#define RTK_SUB_EVENT_CODE_COREDUMP 0x34 + +struct rtk_dev_coredump_hdr { + u8 type; + u8 code; + u8 reserved[2]; +} __packed; + +static inline void btusb_rtl_alloc_devcoredump(struct hci_dev *hdev, + struct rtk_dev_coredump_hdr *hdr, u8 *buf, u32 len) +{ + struct sk_buff *skb; + + skb = alloc_skb(len + sizeof(*hdr), GFP_ATOMIC); + if (!skb) + return; + + skb_put_data(skb, hdr, sizeof(*hdr)); + if (len) + skb_put_data(skb, buf, len); + + if (!hci_devcd_init(hdev, skb->len)) { + hci_devcd_append(hdev, skb); + hci_devcd_complete(hdev); + } else { + bt_dev_err(hdev, "RTL: Failed to generate devcoredump"); + kfree_skb(skb); + } +} + +static void btusb_rtl_reset(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct gpio_desc *reset_gpio = data->reset_gpio; + struct rtk_dev_coredump_hdr hdr = { + .type = RTK_DEVCOREDUMP_CODE_CMD_TIMEOUT, + }; + + btusb_rtl_alloc_devcoredump(hdev, &hdr, NULL, 0); + + if (!reset_gpio) { + btusb_reset(hdev); + return; + } + + /* Toggle the hard reset line. The Realtek device is going to + * yank itself off the USB and then replug. The cleanup is handled + * correctly on the way out (standard USB disconnect), and the new + * device is detected cleanly and bound to the driver again like + * it should be. + */ + if (test_and_set_bit(BTUSB_HW_RESET_ACTIVE, &data->flags)) { + bt_dev_err(hdev, "last reset failed? Not resetting again"); + return; + } + + bt_dev_err(hdev, "Reset Realtek device via gpio"); + gpiod_set_value_cansleep(reset_gpio, 1); + msleep(200); + gpiod_set_value_cansleep(reset_gpio, 0); +} + +static void btusb_rtl_hw_error(struct hci_dev *hdev, u8 code) +{ + struct rtk_dev_coredump_hdr hdr = { + .type = RTK_DEVCOREDUMP_CODE_HW_ERR, + .code = code, + }; + + bt_dev_err(hdev, "RTL: hw err, trigger devcoredump (%d)", code); + + btusb_rtl_alloc_devcoredump(hdev, &hdr, NULL, 0); +} + +static void btusb_qca_reset(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct gpio_desc *reset_gpio = data->reset_gpio; + + if (test_bit(BTUSB_HW_SSR_ACTIVE, &data->flags)) { + bt_dev_info(hdev, "Ramdump in progress, defer reset"); + return; + } + + if (reset_gpio) { + bt_dev_err(hdev, "Reset qca device via bt_en gpio"); + + /* Toggle the hard reset line. The qca bt device is going to + * yank itself off the USB and then replug. The cleanup is handled + * correctly on the way out (standard USB disconnect), and the new + * device is detected cleanly and bound to the driver again like + * it should be. + */ + if (test_and_set_bit(BTUSB_HW_RESET_ACTIVE, &data->flags)) { + bt_dev_err(hdev, "last reset failed? Not resetting again"); + return; + } + + gpiod_set_value_cansleep(reset_gpio, 0); + msleep(200); + gpiod_set_value_cansleep(reset_gpio, 1); + + return; + } + + btusb_reset(hdev); +} + +static u8 btusb_classify_qca_pkt_type(struct hci_dev *hdev, struct sk_buff *skb) +{ + /* Some Qualcomm controllers, e.g., QCNFA765 with WCN6855 chip, send debug + * packets as ACL frames with connection handle 0x2EDC. These are not real + * ACL packets and should be reclassified as HCI_DIAG_PKT to prevent + * "ACL packet for unknown connection handle 3804" errors. + */ + if (skb->len >= 2) { + u16 handle = get_unaligned_le16(skb->data); + + if (handle == 0x2EDC) + return HCI_DIAG_PKT; + } + + /* Use default packet type for other packets */ + return hci_skb_pkt_type(skb); +} + +static inline void btusb_free_frags(struct btusb_data *data) +{ + unsigned long flags; + + spin_lock_irqsave(&data->rxlock, flags); + + dev_kfree_skb_irq(data->evt_skb); + data->evt_skb = NULL; + + dev_kfree_skb_irq(data->acl_skb); + data->acl_skb = NULL; + + dev_kfree_skb_irq(data->sco_skb); + data->sco_skb = NULL; + + spin_unlock_irqrestore(&data->rxlock, flags); +} + +static int btusb_recv_event(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + int err; + + err = data->recv_event(hdev, skb); + + if (data->intr_interval) { + /* Trigger dequeue immediately if an event is received */ + schedule_delayed_work(&data->rx_work, 0); + } + + return err; +} + +static int btusb_recv_intr(struct btusb_data *data, void *buffer, int count) +{ + struct sk_buff *skb; + unsigned long flags; + int err = 0; + + spin_lock_irqsave(&data->rxlock, flags); + skb = data->evt_skb; + + while (count) { + int len; + + if (!skb) { + skb = bt_skb_alloc(HCI_MAX_EVENT_SIZE, GFP_ATOMIC); + if (!skb) { + err = -ENOMEM; + break; + } + + hci_skb_pkt_type(skb) = HCI_EVENT_PKT; + hci_skb_expect(skb) = HCI_EVENT_HDR_SIZE; + } + + len = min_t(uint, hci_skb_expect(skb), count); + skb_put_data(skb, buffer, len); + + count -= len; + buffer += len; + hci_skb_expect(skb) -= len; + + if (skb->len == HCI_EVENT_HDR_SIZE) { + /* Complete event header */ + hci_skb_expect(skb) = hci_event_hdr(skb)->plen; + + if (skb_tailroom(skb) < hci_skb_expect(skb)) { + kfree_skb(skb); + skb = NULL; + + err = -EILSEQ; + break; + } + } + + if (!hci_skb_expect(skb)) { + /* Each chunk should correspond to at least 1 or more + * events so if there are still bytes left that doesn't + * constitute a new event this is likely a bug in the + * controller. + */ + if (count && count < HCI_EVENT_HDR_SIZE) { + bt_dev_warn(data->hdev, + "Unexpected continuation: %d bytes", + count); + count = 0; + } + + /* Complete frame */ + btusb_recv_event(data->hdev, skb); + skb = NULL; + } + } + + data->evt_skb = skb; + spin_unlock_irqrestore(&data->rxlock, flags); + + return err; +} + +static int btusb_recv_acl(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + + /* Only queue ACL packet if intr_interval is set as it means + * force_poll_sync has been enabled. + */ + if (!data->intr_interval) + return data->recv_acl(hdev, skb); + + skb_queue_tail(&data->acl_q, skb); + schedule_delayed_work(&data->rx_work, data->intr_interval); + + return 0; +} + +static int btusb_recv_bulk(struct btusb_data *data, void *buffer, int count) +{ + struct sk_buff *skb; + unsigned long flags; + int err = 0; + + spin_lock_irqsave(&data->rxlock, flags); + skb = data->acl_skb; + + while (count) { + int len; + + if (!skb) { + skb = bt_skb_alloc(HCI_MAX_FRAME_SIZE, GFP_ATOMIC); + if (!skb) { + err = -ENOMEM; + break; + } + + hci_skb_pkt_type(skb) = HCI_ACLDATA_PKT; + hci_skb_expect(skb) = HCI_ACL_HDR_SIZE; + } + + len = min_t(uint, hci_skb_expect(skb), count); + skb_put_data(skb, buffer, len); + + count -= len; + buffer += len; + hci_skb_expect(skb) -= len; + + if (skb->len == HCI_ACL_HDR_SIZE) { + /* Complete ACL header */ + hci_skb_expect(skb) = hci_acl_dlen(skb); + + if (skb_tailroom(skb) < hci_skb_expect(skb)) { + kfree_skb(skb); + skb = NULL; + + err = -EILSEQ; + break; + } + } + + if (!hci_skb_expect(skb)) { + /* Complete frame */ + btusb_recv_acl(data->hdev, skb); + skb = NULL; + } + } + + data->acl_skb = skb; + spin_unlock_irqrestore(&data->rxlock, flags); + + return err; +} + +static bool btusb_validate_sco_handle(struct hci_dev *hdev, + struct hci_sco_hdr *hdr) +{ + __u16 handle; + + if (hci_dev_test_flag(hdev, HCI_USER_CHANNEL)) + // Can't validate, userspace controls everything. + return true; + + /* + * USB isochronous transfers are not designed to be reliable and may + * lose fragments. When this happens, the next first fragment + * encountered might actually be a continuation fragment. + * Validate the handle to detect it and drop it, or else the upper + * layer will get garbage for a while. + */ + + handle = hci_handle(__le16_to_cpu(hdr->handle)); + + switch (hci_conn_lookup_type(hdev, handle)) { + case SCO_LINK: + case ESCO_LINK: + return true; + default: + return false; + } +} + +static int btusb_recv_isoc(struct btusb_data *data, void *buffer, int count) +{ + struct sk_buff *skb; + unsigned long flags; + int err = 0; + + spin_lock_irqsave(&data->rxlock, flags); + skb = data->sco_skb; + + while (count) { + int len; + + if (!skb) { + skb = bt_skb_alloc(HCI_MAX_SCO_SIZE, GFP_ATOMIC); + if (!skb) { + err = -ENOMEM; + break; + } + + hci_skb_pkt_type(skb) = HCI_SCODATA_PKT; + hci_skb_expect(skb) = HCI_SCO_HDR_SIZE; + } + + len = min_t(uint, hci_skb_expect(skb), count); + skb_put_data(skb, buffer, len); + + count -= len; + buffer += len; + hci_skb_expect(skb) -= len; + + if (skb->len == HCI_SCO_HDR_SIZE) { + /* Complete SCO header */ + struct hci_sco_hdr *hdr = hci_sco_hdr(skb); + + hci_skb_expect(skb) = hdr->dlen; + + if (skb_tailroom(skb) < hci_skb_expect(skb) || + !btusb_validate_sco_handle(data->hdev, hdr)) { + kfree_skb(skb); + skb = NULL; + + err = -EILSEQ; + break; + } + } + + if (!hci_skb_expect(skb)) { + /* Complete frame */ + hci_recv_frame(data->hdev, skb); + skb = NULL; + } + } + + data->sco_skb = skb; + spin_unlock_irqrestore(&data->rxlock, flags); + + return err; +} + +static void btusb_intr_complete(struct urb *urb) +{ + struct hci_dev *hdev = urb->context; + struct btusb_data *data = hci_get_drvdata(hdev); + int err; + + BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, + urb->actual_length); + + if (!test_bit(HCI_RUNNING, &hdev->flags)) + return; + + if (urb->status == 0) { + hdev->stat.byte_rx += urb->actual_length; + + if (btusb_recv_intr(data, urb->transfer_buffer, + urb->actual_length) < 0) { + bt_dev_err(hdev, "corrupted event packet"); + hdev->stat.err_rx++; + } + } else if (urb->status == -ENOENT) { + /* Avoid suspend failed when usb_kill_urb */ + return; + } + + if (!test_bit(BTUSB_INTR_RUNNING, &data->flags)) + return; + + usb_mark_last_busy(data->udev); + usb_anchor_urb(urb, &data->intr_anchor); + + err = usb_submit_urb(urb, GFP_ATOMIC); + if (err < 0) { + /* -EPERM: urb is being killed; + * -ENODEV: device got disconnected + */ + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p failed to resubmit (%d)", + urb, -err); + if (err != -EPERM) + hci_cmd_sync_cancel(hdev, -err); + usb_unanchor_urb(urb); + } +} + +static int btusb_submit_intr_urb(struct hci_dev *hdev, gfp_t mem_flags) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct urb *urb; + unsigned char *buf; + unsigned int pipe; + int err, size; + + BT_DBG("%s", hdev->name); + + if (!data->intr_ep) + return -ENODEV; + + urb = usb_alloc_urb(0, mem_flags); + if (!urb) + return -ENOMEM; + + if (le16_to_cpu(data->udev->descriptor.idVendor) == 0x0a12 && + le16_to_cpu(data->udev->descriptor.idProduct) == 0x0001) + /* Fake CSR devices don't seem to support sort-transter */ + size = le16_to_cpu(data->intr_ep->wMaxPacketSize); + else + /* Use maximum HCI Event size so the USB stack handles + * ZPL/short-transfer automatically. + */ + size = HCI_MAX_EVENT_SIZE; + + buf = kmalloc(size, mem_flags); + if (!buf) { + usb_free_urb(urb); + return -ENOMEM; + } + + pipe = usb_rcvintpipe(data->udev, data->intr_ep->bEndpointAddress); + + usb_fill_int_urb(urb, data->udev, pipe, buf, size, + btusb_intr_complete, hdev, data->intr_ep->bInterval); + + urb->transfer_flags |= URB_FREE_BUFFER; + + usb_anchor_urb(urb, &data->intr_anchor); + + err = usb_submit_urb(urb, mem_flags); + if (err < 0) { + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p submission failed (%d)", + urb, -err); + if (err != -EPERM) + hci_cmd_sync_cancel(hdev, -err); + usb_unanchor_urb(urb); + } + + /* Only initialize intr_interval if URB poll sync is enabled */ + if (!data->poll_sync) + goto done; + + /* The units are frames (milliseconds) for full and low speed devices, + * and microframes (1/8 millisecond) for highspeed and SuperSpeed + * devices. + * + * This is done once on open/resume so it shouldn't change even if + * force_poll_sync changes. + */ + switch (urb->dev->speed) { + case USB_SPEED_SUPER_PLUS: + case USB_SPEED_SUPER: /* units are 125us */ + data->intr_interval = usecs_to_jiffies(urb->interval * 125); + break; + default: + data->intr_interval = msecs_to_jiffies(urb->interval); + break; + } + +done: + usb_free_urb(urb); + + return err; +} + +static void btusb_bulk_complete(struct urb *urb) +{ + struct hci_dev *hdev = urb->context; + struct btusb_data *data = hci_get_drvdata(hdev); + int err; + + BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, + urb->actual_length); + + if (!test_bit(HCI_RUNNING, &hdev->flags)) + return; + + if (urb->status == 0) { + hdev->stat.byte_rx += urb->actual_length; + + if (data->recv_bulk(data, urb->transfer_buffer, + urb->actual_length) < 0) { + bt_dev_err(hdev, "corrupted ACL packet"); + hdev->stat.err_rx++; + } + } else if (urb->status == -ENOENT) { + /* Avoid suspend failed when usb_kill_urb */ + return; + } + + if (!test_bit(BTUSB_BULK_RUNNING, &data->flags)) + return; + + usb_anchor_urb(urb, &data->bulk_anchor); + usb_mark_last_busy(data->udev); + + err = usb_submit_urb(urb, GFP_ATOMIC); + if (err < 0) { + /* -EPERM: urb is being killed; + * -ENODEV: device got disconnected + */ + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p failed to resubmit (%d)", + urb, -err); + usb_unanchor_urb(urb); + } +} + +static int btusb_submit_bulk_urb(struct hci_dev *hdev, gfp_t mem_flags) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct urb *urb; + unsigned char *buf; + unsigned int pipe; + int err, size = HCI_MAX_FRAME_SIZE; + + BT_DBG("%s", hdev->name); + + if (!data->bulk_rx_ep) + return -ENODEV; + + urb = usb_alloc_urb(0, mem_flags); + if (!urb) + return -ENOMEM; + + buf = kmalloc(size, mem_flags); + if (!buf) { + usb_free_urb(urb); + return -ENOMEM; + } + + pipe = usb_rcvbulkpipe(data->udev, data->bulk_rx_ep->bEndpointAddress); + + usb_fill_bulk_urb(urb, data->udev, pipe, buf, size, + btusb_bulk_complete, hdev); + + urb->transfer_flags |= URB_FREE_BUFFER; + + usb_mark_last_busy(data->udev); + usb_anchor_urb(urb, &data->bulk_anchor); + + err = usb_submit_urb(urb, mem_flags); + if (err < 0) { + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p submission failed (%d)", + urb, -err); + usb_unanchor_urb(urb); + } + + usb_free_urb(urb); + + return err; +} + +static void btusb_isoc_complete(struct urb *urb) +{ + struct hci_dev *hdev = urb->context; + struct btusb_data *data = hci_get_drvdata(hdev); + int i, err; + + BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, + urb->actual_length); + + if (!test_bit(HCI_RUNNING, &hdev->flags)) + return; + + if (urb->status == 0) { + for (i = 0; i < urb->number_of_packets; i++) { + unsigned int offset = urb->iso_frame_desc[i].offset; + unsigned int length = urb->iso_frame_desc[i].actual_length; + + if (urb->iso_frame_desc[i].status) + continue; + + hdev->stat.byte_rx += length; + + if (btusb_recv_isoc(data, urb->transfer_buffer + offset, + length) < 0) { + bt_dev_err(hdev, "corrupted SCO packet"); + hdev->stat.err_rx++; + } + } + } else if (urb->status == -ENOENT) { + /* Avoid suspend failed when usb_kill_urb */ + return; + } + + if (!test_bit(BTUSB_ISOC_RUNNING, &data->flags)) + return; + + usb_anchor_urb(urb, &data->isoc_anchor); + + err = usb_submit_urb(urb, GFP_ATOMIC); + if (err < 0) { + /* -EPERM: urb is being killed; + * -ENODEV: device got disconnected + */ + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p failed to resubmit (%d)", + urb, -err); + usb_unanchor_urb(urb); + } +} + +static inline void __fill_isoc_descriptor_msbc(struct urb *urb, int len, + int mtu, struct btusb_data *data) +{ + int i = 0, offset = 0; + unsigned int interval; + + BT_DBG("len %d mtu %d", len, mtu); + + /* For mSBC ALT 6 settings some chips need to transmit the data + * continuously without the zero length of USB packets. + */ + if (test_bit(BTUSB_ALT6_CONTINUOUS_TX, &data->flags)) + goto ignore_usb_alt6_packet_flow; + + /* For mSBC ALT 6 setting the host will send the packet at continuous + * flow. As per core spec 5, vol 4, part B, table 2.1. For ALT setting + * 6 the HCI PACKET INTERVAL should be 7.5ms for every usb packets. + * To maintain the rate we send 63bytes of usb packets alternatively for + * 7ms and 8ms to maintain the rate as 7.5ms. + */ + if (data->usb_alt6_packet_flow) { + interval = 7; + data->usb_alt6_packet_flow = false; + } else { + interval = 6; + data->usb_alt6_packet_flow = true; + } + + for (i = 0; i < interval; i++) { + urb->iso_frame_desc[i].offset = offset; + urb->iso_frame_desc[i].length = offset; + } + +ignore_usb_alt6_packet_flow: + if (len && i < BTUSB_MAX_ISOC_FRAMES) { + urb->iso_frame_desc[i].offset = offset; + urb->iso_frame_desc[i].length = len; + i++; + } + + urb->number_of_packets = i; +} + +static inline void __fill_isoc_descriptor(struct urb *urb, int len, int mtu) +{ + int i, offset = 0; + + BT_DBG("len %d mtu %d", len, mtu); + + for (i = 0; i < BTUSB_MAX_ISOC_FRAMES && len >= mtu; + i++, offset += mtu, len -= mtu) { + urb->iso_frame_desc[i].offset = offset; + urb->iso_frame_desc[i].length = mtu; + } + + if (len && i < BTUSB_MAX_ISOC_FRAMES) { + urb->iso_frame_desc[i].offset = offset; + urb->iso_frame_desc[i].length = len; + i++; + } + + urb->number_of_packets = i; +} + +static int btusb_submit_isoc_urb(struct hci_dev *hdev, gfp_t mem_flags) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct urb *urb; + unsigned char *buf; + unsigned int pipe; + int err, size; + + BT_DBG("%s", hdev->name); + + if (!data->isoc_rx_ep) + return -ENODEV; + + urb = usb_alloc_urb(BTUSB_MAX_ISOC_FRAMES, mem_flags); + if (!urb) + return -ENOMEM; + + size = le16_to_cpu(data->isoc_rx_ep->wMaxPacketSize) * + BTUSB_MAX_ISOC_FRAMES; + + buf = kmalloc(size, mem_flags); + if (!buf) { + usb_free_urb(urb); + return -ENOMEM; + } + + pipe = usb_rcvisocpipe(data->udev, data->isoc_rx_ep->bEndpointAddress); + + usb_fill_int_urb(urb, data->udev, pipe, buf, size, btusb_isoc_complete, + hdev, data->isoc_rx_ep->bInterval); + + urb->transfer_flags = URB_FREE_BUFFER | URB_ISO_ASAP; + + __fill_isoc_descriptor(urb, size, + le16_to_cpu(data->isoc_rx_ep->wMaxPacketSize)); + + usb_anchor_urb(urb, &data->isoc_anchor); + + err = usb_submit_urb(urb, mem_flags); + if (err < 0) { + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p submission failed (%d)", + urb, -err); + usb_unanchor_urb(urb); + } + + usb_free_urb(urb); + + return err; +} + +static void btusb_diag_complete(struct urb *urb) +{ + struct hci_dev *hdev = urb->context; + struct btusb_data *data = hci_get_drvdata(hdev); + int err; + + BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, + urb->actual_length); + + if (urb->status == 0) { + struct sk_buff *skb; + + skb = bt_skb_alloc(urb->actual_length, GFP_ATOMIC); + if (skb) { + skb_put_data(skb, urb->transfer_buffer, + urb->actual_length); + hci_recv_diag(hdev, skb); + } + } else if (urb->status == -ENOENT) { + /* Avoid suspend failed when usb_kill_urb */ + return; + } + + if (!test_bit(BTUSB_DIAG_RUNNING, &data->flags)) + return; + + usb_anchor_urb(urb, &data->diag_anchor); + usb_mark_last_busy(data->udev); + + err = usb_submit_urb(urb, GFP_ATOMIC); + if (err < 0) { + /* -EPERM: urb is being killed; + * -ENODEV: device got disconnected + */ + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p failed to resubmit (%d)", + urb, -err); + usb_unanchor_urb(urb); + } +} + +static int btusb_submit_diag_urb(struct hci_dev *hdev, gfp_t mem_flags) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct urb *urb; + unsigned char *buf; + unsigned int pipe; + int err, size = HCI_MAX_FRAME_SIZE; + + BT_DBG("%s", hdev->name); + + if (!data->diag_rx_ep) + return -ENODEV; + + urb = usb_alloc_urb(0, mem_flags); + if (!urb) + return -ENOMEM; + + buf = kmalloc(size, mem_flags); + if (!buf) { + usb_free_urb(urb); + return -ENOMEM; + } + + pipe = usb_rcvbulkpipe(data->udev, data->diag_rx_ep->bEndpointAddress); + + usb_fill_bulk_urb(urb, data->udev, pipe, buf, size, + btusb_diag_complete, hdev); + + urb->transfer_flags |= URB_FREE_BUFFER; + + usb_mark_last_busy(data->udev); + usb_anchor_urb(urb, &data->diag_anchor); + + err = usb_submit_urb(urb, mem_flags); + if (err < 0) { + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p submission failed (%d)", + urb, -err); + usb_unanchor_urb(urb); + } + + usb_free_urb(urb); + + return err; +} + +static void btusb_tx_complete(struct urb *urb) +{ + struct sk_buff *skb = urb->context; + struct hci_dev *hdev = (struct hci_dev *)skb->dev; + struct btusb_data *data = hci_get_drvdata(hdev); + unsigned long flags; + + BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, + urb->actual_length); + + if (!test_bit(HCI_RUNNING, &hdev->flags)) + goto done; + + if (!urb->status) { + hdev->stat.byte_tx += urb->transfer_buffer_length; + } else { + if (hci_skb_pkt_type(skb) == HCI_COMMAND_PKT) + hci_cmd_sync_cancel(hdev, -urb->status); + hdev->stat.err_tx++; + } + +done: + spin_lock_irqsave(&data->txlock, flags); + data->tx_in_flight--; + spin_unlock_irqrestore(&data->txlock, flags); + + kfree(urb->setup_packet); + + kfree_skb(skb); +} + +static void btusb_isoc_tx_complete(struct urb *urb) +{ + struct sk_buff *skb = urb->context; + struct hci_dev *hdev = (struct hci_dev *)skb->dev; + + BT_DBG("%s urb %p status %d count %d", hdev->name, urb, urb->status, + urb->actual_length); + + if (!test_bit(HCI_RUNNING, &hdev->flags)) + goto done; + + if (!urb->status) + hdev->stat.byte_tx += urb->transfer_buffer_length; + else + hdev->stat.err_tx++; + +done: + kfree(urb->setup_packet); + + kfree_skb(skb); +} + +static int btusb_open(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + int err; + + BT_DBG("%s", hdev->name); + + err = usb_autopm_get_interface(data->intf); + if (err < 0) + return err; + + /* Patching USB firmware files prior to starting any URBs of HCI path + * It is more safe to use USB bulk channel for downloading USB patch + */ + if (data->setup_on_usb) { + err = data->setup_on_usb(hdev); + if (err < 0) + goto setup_fail; + } + + data->intf->needs_remote_wakeup = 1; + + if (test_and_set_bit(BTUSB_INTR_RUNNING, &data->flags)) + goto done; + + err = btusb_submit_intr_urb(hdev, GFP_KERNEL); + if (err < 0) + goto failed; + + err = btusb_submit_bulk_urb(hdev, GFP_KERNEL); + if (err < 0) { + usb_kill_anchored_urbs(&data->intr_anchor); + goto failed; + } + + set_bit(BTUSB_BULK_RUNNING, &data->flags); + btusb_submit_bulk_urb(hdev, GFP_KERNEL); + + if (data->diag) { + if (!btusb_submit_diag_urb(hdev, GFP_KERNEL)) + set_bit(BTUSB_DIAG_RUNNING, &data->flags); + } + +done: + usb_autopm_put_interface(data->intf); + return 0; + +failed: + clear_bit(BTUSB_INTR_RUNNING, &data->flags); +setup_fail: + usb_autopm_put_interface(data->intf); + return err; +} + +static void btusb_stop_traffic(struct btusb_data *data) +{ + usb_kill_anchored_urbs(&data->intr_anchor); + usb_kill_anchored_urbs(&data->bulk_anchor); + usb_kill_anchored_urbs(&data->isoc_anchor); + usb_kill_anchored_urbs(&data->diag_anchor); + usb_kill_anchored_urbs(&data->ctrl_anchor); +} + +static void btusb_prepare_reset(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + + btusb_stop_traffic(data); + usb_kill_anchored_urbs(&data->tx_anchor); +} + +static int btusb_close(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + int err; + + BT_DBG("%s", hdev->name); + + cancel_work_sync(&data->work); + cancel_work_sync(&data->waker); + + clear_bit(BTUSB_ISOC_RUNNING, &data->flags); + clear_bit(BTUSB_BULK_RUNNING, &data->flags); + clear_bit(BTUSB_INTR_RUNNING, &data->flags); + clear_bit(BTUSB_DIAG_RUNNING, &data->flags); + + btusb_stop_traffic(data); + + /* rx_work must only be canceled once the URBs that can rearm it are + * gone, and it must be canceled synchronously since btusb_disconnect() + * frees the btusb_data it dereferences right after hci_unregister_dev(). + */ + cancel_delayed_work_sync(&data->rx_work); + + skb_queue_purge(&data->acl_q); + + btusb_free_frags(data); + + err = usb_autopm_get_interface(data->intf); + if (err < 0) + goto failed; + + data->intf->needs_remote_wakeup = 0; + + /* Enable remote wake up for auto-suspend */ + if (test_bit(BTUSB_WAKEUP_AUTOSUSPEND, &data->flags)) + data->intf->needs_remote_wakeup = 1; + + usb_autopm_put_interface(data->intf); + +failed: + usb_scuttle_anchored_urbs(&data->deferred); + return 0; +} + +static int btusb_flush(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + + BT_DBG("%s", hdev->name); + + cancel_delayed_work_sync(&data->rx_work); + + skb_queue_purge(&data->acl_q); + + usb_kill_anchored_urbs(&data->tx_anchor); + btusb_free_frags(data); + + return 0; +} + +static struct urb *alloc_ctrl_urb(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct usb_ctrlrequest *dr; + struct urb *urb; + unsigned int pipe; + + urb = usb_alloc_urb(0, GFP_KERNEL); + if (!urb) + return ERR_PTR(-ENOMEM); + + dr = kmalloc_obj(*dr); + if (!dr) { + usb_free_urb(urb); + return ERR_PTR(-ENOMEM); + } + + dr->bRequestType = data->cmdreq_type; + dr->bRequest = data->cmdreq; + dr->wIndex = 0; + dr->wValue = 0; + dr->wLength = __cpu_to_le16(skb->len); + + pipe = usb_sndctrlpipe(data->udev, 0x00); + + usb_fill_control_urb(urb, data->udev, pipe, (void *)dr, + skb->data, skb->len, btusb_tx_complete, skb); + + skb->dev = (void *)hdev; + + return urb; +} + +static struct urb *alloc_bulk_urb(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct urb *urb; + unsigned int pipe; + + if (!data->bulk_tx_ep) + return ERR_PTR(-ENODEV); + + urb = usb_alloc_urb(0, GFP_KERNEL); + if (!urb) + return ERR_PTR(-ENOMEM); + + pipe = usb_sndbulkpipe(data->udev, data->bulk_tx_ep->bEndpointAddress); + + usb_fill_bulk_urb(urb, data->udev, pipe, + skb->data, skb->len, btusb_tx_complete, skb); + + skb->dev = (void *)hdev; + + return urb; +} + +static struct urb *alloc_isoc_urb(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct urb *urb; + unsigned int pipe; + + if (!data->isoc_tx_ep) + return ERR_PTR(-ENODEV); + + urb = usb_alloc_urb(BTUSB_MAX_ISOC_FRAMES, GFP_KERNEL); + if (!urb) + return ERR_PTR(-ENOMEM); + + pipe = usb_sndisocpipe(data->udev, data->isoc_tx_ep->bEndpointAddress); + + usb_fill_int_urb(urb, data->udev, pipe, + skb->data, skb->len, btusb_isoc_tx_complete, + skb, data->isoc_tx_ep->bInterval); + + urb->transfer_flags = URB_ISO_ASAP; + + if (data->isoc_altsetting == 6) + __fill_isoc_descriptor_msbc(urb, skb->len, + le16_to_cpu(data->isoc_tx_ep->wMaxPacketSize), + data); + else + __fill_isoc_descriptor(urb, skb->len, + le16_to_cpu(data->isoc_tx_ep->wMaxPacketSize)); + skb->dev = (void *)hdev; + + return urb; +} + +static int submit_tx_urb(struct hci_dev *hdev, struct urb *urb) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + int err; + + usb_anchor_urb(urb, &data->tx_anchor); + + err = usb_submit_urb(urb, GFP_KERNEL); + if (err < 0) { + if (err != -EPERM && err != -ENODEV) + bt_dev_err(hdev, "urb %p submission failed (%d)", + urb, -err); + kfree(urb->setup_packet); + usb_unanchor_urb(urb); + } else { + usb_mark_last_busy(data->udev); + } + + usb_free_urb(urb); + return err; +} + +static int submit_or_queue_tx_urb(struct hci_dev *hdev, struct urb *urb) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + unsigned long flags; + bool suspending; + + spin_lock_irqsave(&data->txlock, flags); + suspending = test_bit(BTUSB_SUSPENDING, &data->flags); + if (!suspending) + data->tx_in_flight++; + spin_unlock_irqrestore(&data->txlock, flags); + + if (!suspending) + return submit_tx_urb(hdev, urb); + + usb_anchor_urb(urb, &data->deferred); + schedule_work(&data->waker); + + usb_free_urb(urb); + return 0; +} + +static int btusb_send_frame(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct urb *urb; + + BT_DBG("%s", hdev->name); + + switch (hci_skb_pkt_type(skb)) { + case HCI_COMMAND_PKT: + urb = alloc_ctrl_urb(hdev, skb); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + hdev->stat.cmd_tx++; + return submit_or_queue_tx_urb(hdev, urb); + + case HCI_ACLDATA_PKT: + urb = alloc_bulk_urb(hdev, skb); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + hdev->stat.acl_tx++; + return submit_or_queue_tx_urb(hdev, urb); + + case HCI_SCODATA_PKT: + if (!hci_dev_test_flag(hdev, HCI_USER_CHANNEL) && + hci_conn_num(hdev, SCO_LINK) < 1) + return -ENODEV; + + urb = alloc_isoc_urb(hdev, skb); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + hdev->stat.sco_tx++; + return submit_tx_urb(hdev, urb); + + case HCI_ISODATA_PKT: + urb = alloc_bulk_urb(hdev, skb); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + return submit_or_queue_tx_urb(hdev, urb); + } + + return -EILSEQ; +} + +static void btusb_notify(struct hci_dev *hdev, unsigned int evt) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + + BT_DBG("%s evt %d", hdev->name, evt); + + if (hci_conn_num(hdev, SCO_LINK) != data->sco_num) { + data->sco_num = hci_conn_num(hdev, SCO_LINK); + data->air_mode = evt; + schedule_work(&data->work); + } +} + +static inline int __set_isoc_interface(struct hci_dev *hdev, int altsetting) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct usb_interface *intf = data->isoc; + struct usb_endpoint_descriptor *ep_desc; + int i, err; + + if (!data->isoc) + return -ENODEV; + + err = usb_set_interface(data->udev, data->isoc_ifnum, altsetting); + if (err < 0) { + bt_dev_err(hdev, "setting interface failed (%d)", -err); + return err; + } + + data->isoc_altsetting = altsetting; + + data->isoc_tx_ep = NULL; + data->isoc_rx_ep = NULL; + + for (i = 0; i < intf->cur_altsetting->desc.bNumEndpoints; i++) { + ep_desc = &intf->cur_altsetting->endpoint[i].desc; + + if (!data->isoc_tx_ep && usb_endpoint_is_isoc_out(ep_desc)) { + data->isoc_tx_ep = ep_desc; + continue; + } + + if (!data->isoc_rx_ep && usb_endpoint_is_isoc_in(ep_desc)) { + data->isoc_rx_ep = ep_desc; + continue; + } + } + + if (!data->isoc_tx_ep || !data->isoc_rx_ep) { + bt_dev_err(hdev, "invalid SCO descriptors"); + return -ENODEV; + } + + return 0; +} + +static int btusb_switch_alt_setting(struct hci_dev *hdev, int new_alts) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + int err; + + if (data->isoc_altsetting != new_alts) { + unsigned long flags; + + clear_bit(BTUSB_ISOC_RUNNING, &data->flags); + usb_kill_anchored_urbs(&data->isoc_anchor); + + /* When isochronous alternate setting needs to be + * changed, because SCO connection has been added + * or removed, a packet fragment may be left in the + * reassembling state. This could lead to wrongly + * assembled fragments. + * + * Clear outstanding fragment when selecting a new + * alternate setting. + */ + spin_lock_irqsave(&data->rxlock, flags); + dev_kfree_skb_irq(data->sco_skb); + data->sco_skb = NULL; + spin_unlock_irqrestore(&data->rxlock, flags); + + err = __set_isoc_interface(hdev, new_alts); + if (err < 0) + return err; + } + + if (!test_and_set_bit(BTUSB_ISOC_RUNNING, &data->flags)) { + if (btusb_submit_isoc_urb(hdev, GFP_KERNEL) < 0) + clear_bit(BTUSB_ISOC_RUNNING, &data->flags); + else + btusb_submit_isoc_urb(hdev, GFP_KERNEL); + } + + return 0; +} + +static struct usb_host_interface *btusb_find_altsetting(struct btusb_data *data, + int alt) +{ + struct usb_interface *intf = data->isoc; + int i; + + BT_DBG("Looking for Alt no :%d", alt); + + if (!intf) + return NULL; + + for (i = 0; i < intf->num_altsetting; i++) { + if (intf->altsetting[i].desc.bAlternateSetting == alt) + return &intf->altsetting[i]; + } + + return NULL; +} + +static void btusb_work(struct work_struct *work) +{ + struct btusb_data *data = container_of(work, struct btusb_data, work); + struct hci_dev *hdev = data->hdev; + int new_alts = 0; + int err; + + if (data->sco_num > 0) { + if (!test_bit(BTUSB_DID_ISO_RESUME, &data->flags)) { + err = usb_autopm_get_interface(data->isoc ? data->isoc : data->intf); + if (err < 0) { + clear_bit(BTUSB_ISOC_RUNNING, &data->flags); + usb_kill_anchored_urbs(&data->isoc_anchor); + return; + } + + set_bit(BTUSB_DID_ISO_RESUME, &data->flags); + } + + if (data->air_mode == HCI_NOTIFY_ENABLE_SCO_CVSD) { + if (hdev->voice_setting & 0x0020) { + static const int alts[3] = { 2, 4, 5 }; + unsigned int sco_idx; + + sco_idx = min_t(unsigned int, data->sco_num - 1, + ARRAY_SIZE(alts) - 1); + new_alts = alts[sco_idx]; + } else { + new_alts = data->sco_num; + } + } else if (data->air_mode == HCI_NOTIFY_ENABLE_SCO_TRANSP) { + /* Bluetooth USB spec recommends alt 6 (63 bytes), but + * many adapters do not support it. Alt 1 appears to + * work for all adapters that do not have alt 6, and + * which work with WBS at all. Some devices prefer + * alt 3 (HCI payload >= 60 Bytes let air packet + * data satisfy 60 bytes), requiring + * MTU >= 3 (packets) * 25 (size) - 3 (headers) = 72 + * see also Core spec 5, vol 4, B 2.1.1 & Table 2.1. + */ + if (btusb_find_altsetting(data, 6)) + new_alts = 6; + else if (btusb_find_altsetting(data, 3) && + hdev->sco_mtu >= 72 && + test_bit(BTUSB_USE_ALT3_FOR_WBS, &data->flags)) + new_alts = 3; + else + new_alts = 1; + } + + if (btusb_switch_alt_setting(hdev, new_alts) < 0) + bt_dev_err(hdev, "set USB alt:(%d) failed!", new_alts); + } else { + usb_kill_anchored_urbs(&data->isoc_anchor); + + if (test_and_clear_bit(BTUSB_ISOC_RUNNING, &data->flags)) + __set_isoc_interface(hdev, 0); + + if (test_and_clear_bit(BTUSB_DID_ISO_RESUME, &data->flags)) + usb_autopm_put_interface(data->isoc ? data->isoc : data->intf); + } +} + +static void btusb_waker(struct work_struct *work) +{ + struct btusb_data *data = container_of(work, struct btusb_data, waker); + int err; + + err = usb_autopm_get_interface(data->intf); + if (err < 0) + return; + + usb_autopm_put_interface(data->intf); +} + +static void btusb_rx_work(struct work_struct *work) +{ + struct btusb_data *data = container_of(work, struct btusb_data, + rx_work.work); + struct sk_buff *skb; + + /* Dequeue ACL data received during the interval */ + while ((skb = skb_dequeue(&data->acl_q))) + data->recv_acl(data->hdev, skb); +} + +static int btusb_setup_bcm92035(struct hci_dev *hdev) +{ + struct sk_buff *skb; + u8 val = 0x00; + + BT_DBG("%s", hdev->name); + + skb = __hci_cmd_sync(hdev, 0xfc3b, 1, &val, HCI_INIT_TIMEOUT); + if (IS_ERR(skb)) + bt_dev_err(hdev, "BCM92035 command failed (%ld)", PTR_ERR(skb)); + else + kfree_skb(skb); + + return 0; +} + +static int btusb_setup_csr(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + u16 bcdDevice = le16_to_cpu(data->udev->descriptor.bcdDevice); + struct hci_rp_read_local_version *rp; + struct sk_buff *skb; + bool is_fake = false; + int ret; + + BT_DBG("%s", hdev->name); + + skb = __hci_cmd_sync(hdev, HCI_OP_READ_LOCAL_VERSION, 0, NULL, + HCI_INIT_TIMEOUT); + if (IS_ERR(skb)) { + int err = PTR_ERR(skb); + + bt_dev_err(hdev, "CSR: Local version failed (%d)", err); + return err; + } + + rp = skb_pull_data(skb, sizeof(*rp)); + if (!rp) { + bt_dev_err(hdev, "CSR: Local version length mismatch"); + kfree_skb(skb); + return -EIO; + } + + bt_dev_info(hdev, "CSR: Setting up dongle with HCI ver=%u rev=%04x", + rp->hci_ver, le16_to_cpu(rp->hci_rev)); + + bt_dev_info(hdev, "LMP ver=%u subver=%04x; manufacturer=%u", + rp->lmp_ver, le16_to_cpu(rp->lmp_subver), + le16_to_cpu(rp->manufacturer)); + + /* Detect a wide host of Chinese controllers that aren't CSR. + * + * Known fake bcdDevices: 0x0100, 0x0134, 0x1915, 0x2520, 0x7558, 0x8891 + * + * The main thing they have in common is that these are really popular low-cost + * options that support newer Bluetooth versions but rely on heavy VID/PID + * squatting of this poor old Bluetooth 1.1 device. Even sold as such. + * + * We detect actual CSR devices by checking that the HCI manufacturer code + * is Cambridge Silicon Radio (10) and ensuring that LMP sub-version and + * HCI rev values always match. As they both store the firmware number. + */ + if (le16_to_cpu(rp->manufacturer) != 10 || + le16_to_cpu(rp->hci_rev) != le16_to_cpu(rp->lmp_subver)) + is_fake = true; + + /* Known legit CSR firmware build numbers and their supported BT versions: + * - 1.1 (0x1) -> 0x0073, 0x020d, 0x033c, 0x034e + * - 1.2 (0x2) -> 0x04d9, 0x0529 + * - 2.0 (0x3) -> 0x07a6, 0x07ad, 0x0c5c + * - 2.1 (0x4) -> 0x149c, 0x1735, 0x1899 (0x1899 is a BlueCore4-External) + * - 4.0 (0x6) -> 0x1d86, 0x2031, 0x22bb + * + * e.g. Real CSR dongles with LMP subversion 0x73 are old enough that + * support BT 1.1 only; so it's a dead giveaway when some + * third-party BT 4.0 dongle reuses it. + */ + else if (le16_to_cpu(rp->lmp_subver) <= 0x034e && + rp->hci_ver > BLUETOOTH_VER_1_1) + is_fake = true; + + else if (le16_to_cpu(rp->lmp_subver) <= 0x0529 && + rp->hci_ver > BLUETOOTH_VER_1_2) + is_fake = true; + + else if (le16_to_cpu(rp->lmp_subver) <= 0x0c5c && + rp->hci_ver > BLUETOOTH_VER_2_0) + is_fake = true; + + else if (le16_to_cpu(rp->lmp_subver) <= 0x1899 && + rp->hci_ver > BLUETOOTH_VER_2_1) + is_fake = true; + + else if (le16_to_cpu(rp->lmp_subver) <= 0x22bb && + rp->hci_ver > BLUETOOTH_VER_4_0) + is_fake = true; + + /* Other clones which beat all the above checks */ + else if (bcdDevice == 0x0134 && + le16_to_cpu(rp->lmp_subver) == 0x0c5c && + rp->hci_ver == BLUETOOTH_VER_2_0) + is_fake = true; + + if (is_fake) { + bt_dev_warn(hdev, "CSR: Unbranded CSR clone detected; adding workarounds and force-suspending once..."); + + /* Generally these clones have big discrepancies between + * advertised features and what's actually supported. + * Probably will need to be expanded in the future; + * without these the controller will lock up. + */ + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_STORED_LINK_KEY); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_ERR_DATA_REPORTING); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_FILTER_CLEAR_ALL); + hci_set_quirk(hdev, HCI_QUIRK_NO_SUSPEND_NOTIFIER); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_READ_VOICE_SETTING); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_READ_PAGE_SCAN_TYPE); + + /* Clear the reset quirk since this is not an actual + * early Bluetooth 1.1 device from CSR. + */ + hci_clear_quirk(hdev, HCI_QUIRK_RESET_ON_CLOSE); + hci_clear_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY); + + /* + * Special workaround for these BT 4.0 chip clones, and potentially more: + * + * - 0x0134: a Barrot 8041a02 (HCI rev: 0x0810 sub: 0x1012) + * - 0x7558: IC markings FR3191AHAL 749H15143 (HCI rev/sub-version: 0x0709) + * + * These controllers are really messed-up. + * + * 1. Their bulk RX endpoint will never report any data unless + * the device was suspended at least once (yes, really). + * 2. They will not wakeup when autosuspended and receiving data + * on their bulk RX endpoint from e.g. a keyboard or mouse + * (IOW remote-wakeup support is broken for the bulk endpoint). + * + * To fix 1. enable runtime-suspend, force-suspend the + * HCI and then wake-it up by disabling runtime-suspend. + * + * To fix 2. clear the HCI's can_wake flag, this way the HCI + * will still be autosuspended when it is not open. + * + * -- + * + * Because these are widespread problems we prefer generic solutions; so + * apply this initialization quirk to every controller that gets here, + * it should be harmless. The alternative is to not work at all. + */ + pm_runtime_allow(&data->udev->dev); + + ret = pm_runtime_suspend(&data->udev->dev); + if (ret >= 0) + msleep(200); + else + bt_dev_warn(hdev, "CSR: Couldn't suspend the device for our Barrot 8041a02 receive-issue workaround"); + + pm_runtime_forbid(&data->udev->dev); + + device_set_wakeup_capable(&data->udev->dev, false); + + /* Re-enable autosuspend if this was requested */ + if (enable_autosuspend) + usb_enable_autosuspend(data->udev); + } + + kfree_skb(skb); + + return 0; +} + +static int inject_cmd_complete(struct hci_dev *hdev, __u16 opcode) +{ + struct sk_buff *skb; + struct hci_event_hdr *hdr; + struct hci_ev_cmd_complete *evt; + + skb = bt_skb_alloc(sizeof(*hdr) + sizeof(*evt) + 1, GFP_KERNEL); + if (!skb) + return -ENOMEM; + + hdr = skb_put(skb, sizeof(*hdr)); + hdr->evt = HCI_EV_CMD_COMPLETE; + hdr->plen = sizeof(*evt) + 1; + + evt = skb_put(skb, sizeof(*evt)); + evt->ncmd = 0x01; + evt->opcode = cpu_to_le16(opcode); + + skb_put_u8(skb, 0x00); + + hci_skb_pkt_type(skb) = HCI_EVENT_PKT; + + return hci_recv_frame(hdev, skb); +} + +static int btusb_recv_bulk_intel(struct btusb_data *data, void *buffer, + int count) +{ + struct hci_dev *hdev = data->hdev; + + /* When the device is in bootloader mode, then it can send + * events via the bulk endpoint. These events are treated the + * same way as the ones received from the interrupt endpoint. + */ + if (btintel_test_flag(hdev, INTEL_BOOTLOADER)) + return btusb_recv_intr(data, buffer, count); + + return btusb_recv_bulk(data, buffer, count); +} + +static int btusb_send_frame_intel(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct urb *urb; + + BT_DBG("%s", hdev->name); + + switch (hci_skb_pkt_type(skb)) { + case HCI_COMMAND_PKT: + if (btintel_test_flag(hdev, INTEL_BOOTLOADER)) { + struct hci_command_hdr *cmd = (void *)skb->data; + __u16 opcode = le16_to_cpu(cmd->opcode); + + /* When in bootloader mode and the command 0xfc09 + * is received, it needs to be send down the + * bulk endpoint. So allocate a bulk URB instead. + */ + if (opcode == 0xfc09) + urb = alloc_bulk_urb(hdev, skb); + else + urb = alloc_ctrl_urb(hdev, skb); + + /* When the BTINTEL_HCI_OP_RESET command is issued to + * boot into the operational firmware, it will actually + * not send a command complete event. To keep the flow + * control working inject that event here. + */ + if (opcode == BTINTEL_HCI_OP_RESET) + inject_cmd_complete(hdev, opcode); + } else { + urb = alloc_ctrl_urb(hdev, skb); + } + if (IS_ERR(urb)) + return PTR_ERR(urb); + + hdev->stat.cmd_tx++; + return submit_or_queue_tx_urb(hdev, urb); + + case HCI_ACLDATA_PKT: + urb = alloc_bulk_urb(hdev, skb); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + hdev->stat.acl_tx++; + return submit_or_queue_tx_urb(hdev, urb); + + case HCI_SCODATA_PKT: + if (!hci_dev_test_flag(hdev, HCI_USER_CHANNEL) && + hci_conn_num(hdev, SCO_LINK) < 1) + return -ENODEV; + + urb = alloc_isoc_urb(hdev, skb); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + hdev->stat.sco_tx++; + return submit_tx_urb(hdev, urb); + + case HCI_ISODATA_PKT: + urb = alloc_bulk_urb(hdev, skb); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + return submit_or_queue_tx_urb(hdev, urb); + } + + return -EILSEQ; +} + +static int btusb_setup_realtek(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + int ret; + + ret = btrtl_setup_realtek(hdev); + + if (btrealtek_test_flag(data->hdev, REALTEK_ALT6_CONTINUOUS_TX_CHIP)) + set_bit(BTUSB_ALT6_CONTINUOUS_TX, &data->flags); + + return ret; +} + +static int btusb_recv_event_realtek(struct hci_dev *hdev, struct sk_buff *skb) +{ + if (skb->len >= HCI_EVENT_HDR_SIZE + 1 && + skb->data[0] == HCI_EV_VENDOR && + skb->data[2] == RTK_SUB_EVENT_CODE_COREDUMP) { + struct rtk_dev_coredump_hdr hdr = { + .code = RTK_DEVCOREDUMP_CODE_MEMDUMP, + }; + + bt_dev_dbg(hdev, "RTL: received coredump vendor evt, len %u", + skb->len); + + btusb_rtl_alloc_devcoredump(hdev, &hdr, skb->data, skb->len); + kfree_skb(skb); + + return 0; + } + + return hci_recv_frame(hdev, skb); +} + +static void btusb_mtk_claim_iso_intf(struct btusb_data *data) +{ + struct btmtk_data *btmtk_data; + int err; + + if (!data->hdev) + return; + + btmtk_data = hci_get_priv(data->hdev); + if (!btmtk_data) + return; + + if (!btmtk_data->isopkt_intf) { + bt_dev_err(data->hdev, "Can't claim NULL iso interface"); + return; + } + + /* + * The function usb_driver_claim_interface() is documented to need + * locks held if it's not called from a probe routine. The code here + * is called from the hci_power_on workqueue, so grab the lock. + */ + device_lock(&btmtk_data->isopkt_intf->dev); + err = usb_driver_claim_interface(&btusb_driver, + btmtk_data->isopkt_intf, data); + device_unlock(&btmtk_data->isopkt_intf->dev); + if (err < 0) { + btmtk_data->isopkt_intf = NULL; + bt_dev_err(data->hdev, "Failed to claim iso interface: %d", err); + return; + } + + set_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags); + init_usb_anchor(&btmtk_data->isopkt_anchor); +} + +static void btusb_mtk_release_iso_intf(struct hci_dev *hdev) +{ + struct btmtk_data *btmtk_data; + + if (!hdev) + return; + + btmtk_data = hci_get_priv(hdev); + if (!btmtk_data) + return; + + if (test_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags)) { + usb_kill_anchored_urbs(&btmtk_data->isopkt_anchor); + clear_bit(BTMTK_ISOPKT_RUNNING, &btmtk_data->flags); + + if (btmtk_data->isopkt_skb) { + dev_kfree_skb_irq(btmtk_data->isopkt_skb); + btmtk_data->isopkt_skb = NULL; + } + + if (btmtk_data->isopkt_intf) { + usb_set_intfdata(btmtk_data->isopkt_intf, NULL); + usb_driver_release_interface(&btusb_driver, + btmtk_data->isopkt_intf); + btmtk_data->isopkt_intf = NULL; + } + } + + clear_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags); +} + +static int btusb_mtk_disconnect(struct hci_dev *hdev) +{ + /* This function describes the specific additional steps taken by MediaTek + * when Bluetooth usb driver's resume function is called. + */ + btusb_mtk_release_iso_intf(hdev); + + return 0; +} + +static int btusb_mtk_reset(struct hci_dev *hdev, void *rst_data) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct btmtk_data *btmtk_data = hci_get_priv(hdev); + int err; + + /* It's MediaTek specific bluetooth reset mechanism via USB */ + if (test_and_set_bit(BTMTK_HW_RESET_ACTIVE, &btmtk_data->flags)) { + bt_dev_err(hdev, "last reset failed? Not resetting again"); + return -EBUSY; + } + + err = usb_autopm_get_interface(data->intf); + if (err < 0) { + bt_dev_err(hdev, "Failed usb_autopm_get_interface: %d", err); + clear_bit(BTMTK_HW_RESET_ACTIVE, &btmtk_data->flags); + return err; + } + + /* Release MediaTek ISO data interface */ + btusb_mtk_release_iso_intf(hdev); + + btusb_prepare_reset(hdev); + + /* Toggle the hard reset line. The MediaTek device is going to + * yank itself off the USB and then replug. The cleanup is handled + * correctly on the way out (standard USB disconnect), and the new + * device is detected cleanly and bound to the driver again like + * it should be. + */ + if (data->reset_gpio) { + gpiod_set_value_cansleep(data->reset_gpio, 1); + msleep(200); + gpiod_set_value_cansleep(data->reset_gpio, 0); + return 0; + } + + err = btmtk_usb_subsys_reset(hdev, btmtk_data->dev_id); + + if (test_and_set_bit(BTUSB_RESET, &data->flags)) { + bt_dev_err(hdev, "last usb reset failed? Resetting again"); + usb_autopm_put_interface_no_suspend(data->intf); + } + + usb_queue_reset_device(data->intf); + clear_bit(BTMTK_HW_RESET_ACTIVE, &btmtk_data->flags); + + return err; +} + +static int btusb_send_frame_mtk(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct urb *urb; + + BT_DBG("%s", hdev->name); + + if (hci_skb_pkt_type(skb) == HCI_ISODATA_PKT) { + urb = alloc_mtk_intr_urb(hdev, skb, btusb_tx_complete); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + return submit_or_queue_tx_urb(hdev, urb); + } else { + return btusb_send_frame(hdev, skb); + } +} + +static inline bool platform_is_ryzen(void) +{ +#ifdef CONFIG_X86 + return boot_cpu_has(X86_FEATURE_ZEN); +#else + return false; +#endif +} + +static inline bool is_direct_child_of_root_hub(struct usb_device *udev) +{ + return udev->parent == udev->bus->root_hub; +} + +static int btusb_mtk_setup(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct btmtk_data *btmtk_data = hci_get_priv(hdev); + int err; + + /* MediaTek WMT vendor cmd requiring below USB resources to + * complete the handshake. + */ + btmtk_data->drv_name = btusb_driver.name; + btmtk_data->intf = data->intf; + btmtk_data->udev = data->udev; + btmtk_data->ctrl_anchor = &data->ctrl_anchor; + btmtk_data->reset_sync = btusb_mtk_reset; + + /* Claim ISO data interface and endpoint */ + if (!test_bit(BTMTK_ISOPKT_OVER_INTR, &btmtk_data->flags)) { + btmtk_data->isopkt_intf = usb_ifnum_to_if(data->udev, MTK_ISO_IFNUM); + btusb_mtk_claim_iso_intf(data); + } + + err = btmtk_usb_setup(hdev); + if (err) + return err; + + switch (btmtk_data->dev_id) { + case 0x7922: + case 0x7925: + /* + * All reports seen to be relevant to Ryzen-based laptops. These + * NICs are usually used as OEM components thanks to some sort + * of reference designs. + * + * Their popularity on other platforms is unclear. While there + * is still a chance that the quirk may exist on other + * platforms, be cautious and only apply the quirk to direct + * children of Ryzen platforms's root hubs for the time being. + * + * In most cases the root hub is on the SoC or PCH, which needs + * the quirk. Unfortunately, this can't distinguish root hubs on + * PCIe add-in cards. Such roughness should be acceptable, as + * PCIe USB controller add-in cards are less commonly used + * nowadays. On the other hand, applying the quirk doesn't hurt + * any functionalities either, as the device can still be used + * as a wakeup source if desired. + * + * Theoretically, we could retrieve the root hub's PCI vendor ID + * with some hierarchy magic, but that's too intrusive... + */ + if (platform_is_ryzen() && is_direct_child_of_root_hub(data->udev)) + set_bit(BTUSB_WAKEUP_BROKEN, &data->flags); + break; + } + + return 0; +} + +static int btusb_mtk_shutdown(struct hci_dev *hdev) +{ + int ret; + + ret = btmtk_usb_shutdown(hdev); + + /* Release MediaTek iso interface after shutdown */ + btusb_mtk_release_iso_intf(hdev); + + return ret; +} + +#ifdef CONFIG_PM +/* Configure an out-of-band gpio as wake-up pin, if specified in device tree */ +static int marvell_config_oob_wake(struct hci_dev *hdev) +{ + struct sk_buff *skb; + struct btusb_data *data = hci_get_drvdata(hdev); + struct device *dev = &data->udev->dev; + u16 pin, gap, opcode; + int ret; + u8 cmd[5]; + + /* Move on if no wakeup pin specified */ + if (of_property_read_u16(dev->of_node, "marvell,wakeup-pin", &pin) || + of_property_read_u16(dev->of_node, "marvell,wakeup-gap-ms", &gap)) + return 0; + + /* Vendor specific command to configure a GPIO as wake-up pin */ + opcode = hci_opcode_pack(0x3F, 0x59); + cmd[0] = opcode & 0xFF; + cmd[1] = opcode >> 8; + cmd[2] = 2; /* length of parameters that follow */ + cmd[3] = pin; + cmd[4] = gap; /* time in ms, for which wakeup pin should be asserted */ + + skb = bt_skb_alloc(sizeof(cmd), GFP_KERNEL); + if (!skb) { + bt_dev_err(hdev, "%s: No memory", __func__); + return -ENOMEM; + } + + skb_put_data(skb, cmd, sizeof(cmd)); + hci_skb_pkt_type(skb) = HCI_COMMAND_PKT; + + ret = btusb_send_frame(hdev, skb); + if (ret) { + bt_dev_err(hdev, "%s: configuration failed", __func__); + kfree_skb(skb); + return ret; + } + + return 0; +} +#else +static inline int marvell_config_oob_wake(struct hci_dev *hdev) +{ + return 0; +} +#endif + +static int btusb_set_bdaddr_marvell(struct hci_dev *hdev, + const bdaddr_t *bdaddr) +{ + struct sk_buff *skb; + u8 buf[8]; + long ret; + + buf[0] = 0xfe; + buf[1] = sizeof(bdaddr_t); + memcpy(buf + 2, bdaddr, sizeof(bdaddr_t)); + + skb = __hci_cmd_sync(hdev, 0xfc22, sizeof(buf), buf, HCI_INIT_TIMEOUT); + if (IS_ERR(skb)) { + ret = PTR_ERR(skb); + bt_dev_err(hdev, "changing Marvell device address failed (%ld)", + ret); + return ret; + } + kfree_skb(skb); + + return 0; +} + +static int btusb_set_bdaddr_ath3012(struct hci_dev *hdev, + const bdaddr_t *bdaddr) +{ + struct sk_buff *skb; + u8 buf[10]; + long ret; + + buf[0] = 0x01; + buf[1] = 0x01; + buf[2] = 0x00; + buf[3] = sizeof(bdaddr_t); + memcpy(buf + 4, bdaddr, sizeof(bdaddr_t)); + + skb = __hci_cmd_sync(hdev, 0xfc0b, sizeof(buf), buf, HCI_INIT_TIMEOUT); + if (IS_ERR(skb)) { + ret = PTR_ERR(skb); + bt_dev_err(hdev, "Change address command failed (%ld)", ret); + return ret; + } + kfree_skb(skb); + + return 0; +} + +static int btusb_set_bdaddr_wcn6855(struct hci_dev *hdev, + const bdaddr_t *bdaddr) +{ + bdaddr_t bdaddr_swapped; + struct sk_buff *skb; + long ret; + + baswap(&bdaddr_swapped, bdaddr); + + skb = __hci_cmd_sync_ev(hdev, 0xfc14, sizeof(bdaddr_swapped), + &bdaddr_swapped, HCI_EV_CMD_COMPLETE, + HCI_INIT_TIMEOUT); + if (IS_ERR(skb)) { + ret = PTR_ERR(skb); + bt_dev_err(hdev, "Change address command failed (%ld)", ret); + return ret; + } + kfree_skb(skb); + + return 0; +} + +#define QCA_MEMDUMP_ACL_HANDLE 0x2EDD +#define QCA_MEMDUMP_SIZE_MAX 0x100000 +#define QCA_MEMDUMP_VSE_CLASS 0x01 +#define QCA_MEMDUMP_MSG_TYPE 0x08 +#define QCA_MEMDUMP_PKT_SIZE 248 +#define QCA_LAST_SEQUENCE_NUM 0xffff + +struct qca_dump_hdr { + u8 vse_class; + u8 msg_type; + __le16 seqno; + u8 reserved; + union { + u8 data[0]; + struct { + __le32 ram_dump_size; + u8 data0[0]; + } __packed; + }; +} __packed; + + +static void btusb_dump_hdr_qca(struct hci_dev *hdev, struct sk_buff *skb) +{ + char buf[128]; + struct btqca_data *btqca_data = hci_get_priv(hdev); + struct qca_dump_info *qca_dump_ptr = &btqca_data->qca_dump; + + snprintf(buf, sizeof(buf), "Controller Name: 0x%x\n", + qca_dump_ptr->controller_id); + skb_put_data(skb, buf, strlen(buf)); + + snprintf(buf, sizeof(buf), "Firmware Version: 0x%x\n", + qca_dump_ptr->fw_version); + skb_put_data(skb, buf, strlen(buf)); + + snprintf(buf, sizeof(buf), "Driver: %s\nVendor: qca\n", + btusb_driver.name); + skb_put_data(skb, buf, strlen(buf)); + + snprintf(buf, sizeof(buf), "VID: 0x%x\nPID:0x%x\n", + qca_dump_ptr->id_vendor, qca_dump_ptr->id_product); + skb_put_data(skb, buf, strlen(buf)); + + snprintf(buf, sizeof(buf), "Lmp Subversion: 0x%x\n", + hdev->lmp_subver); + skb_put_data(skb, buf, strlen(buf)); +} + +static void btusb_coredump_qca(struct hci_dev *hdev) +{ + int err; + static const u8 param[] = { 0x26 }; + + err = __hci_cmd_send(hdev, 0xfc0c, 1, param); + if (err < 0) + bt_dev_err(hdev, "%s: triggle crash failed (%d)", __func__, err); +} + +/* Return: 0 on success, negative errno on failure. */ +static int handle_dump_pkt_qca(struct hci_dev *hdev, struct sk_buff *skb) +{ + int ret = 0; + unsigned int skip = 0; + u8 pkt_type; + u16 seqno; + u32 dump_size; + + struct qca_dump_hdr *dump_hdr; + struct btusb_data *btdata = hci_get_drvdata(hdev); + struct btqca_data *btqca_data = hci_get_priv(hdev); + struct qca_dump_info *qca_dump_ptr = &btqca_data->qca_dump; + struct usb_device *udev = btdata->udev; + + pkt_type = hci_skb_pkt_type(skb); + skip = sizeof(struct hci_event_hdr); + if (pkt_type == HCI_ACLDATA_PKT) + skip += sizeof(struct hci_acl_hdr); + + skb_pull(skb, skip); + dump_hdr = (struct qca_dump_hdr *)skb->data; + + seqno = le16_to_cpu(dump_hdr->seqno); + if (seqno == 0) { + set_bit(BTUSB_HW_SSR_ACTIVE, &btdata->flags); + dump_size = le32_to_cpu(dump_hdr->ram_dump_size); + if (!dump_size || (dump_size > QCA_MEMDUMP_SIZE_MAX)) { + ret = -EILSEQ; + bt_dev_err(hdev, "Invalid memdump size(%u)", + dump_size); + goto out; + } + + ret = hci_devcd_init(hdev, dump_size); + if (ret < 0) { + bt_dev_err(hdev, "memdump init error(%d)", ret); + goto out; + } + + qca_dump_ptr->ram_dump_size = dump_size; + qca_dump_ptr->ram_dump_seqno = 0; + + skb_pull(skb, offsetof(struct qca_dump_hdr, data0)); + + usb_disable_autosuspend(udev); + bt_dev_info(hdev, "%s memdump size(%u)\n", + (pkt_type == HCI_ACLDATA_PKT) ? "ACL" : "event", + dump_size); + } else { + skb_pull(skb, offsetof(struct qca_dump_hdr, data)); + } + + if (!qca_dump_ptr->ram_dump_size) { + ret = -EINVAL; + bt_dev_err(hdev, "memdump is not active"); + goto out; + } + + if ((seqno > qca_dump_ptr->ram_dump_seqno + 1) && seqno != QCA_LAST_SEQUENCE_NUM) { + dump_size = QCA_MEMDUMP_PKT_SIZE * (seqno - qca_dump_ptr->ram_dump_seqno - 1); + hci_devcd_append_pattern(hdev, 0x0, dump_size); + bt_dev_err(hdev, + "expected memdump seqno(%u) is not received(%u)\n", + qca_dump_ptr->ram_dump_seqno, seqno); + qca_dump_ptr->ram_dump_seqno = seqno; + kfree_skb(skb); + return ret; + } + + hci_devcd_append(hdev, skb); + qca_dump_ptr->ram_dump_seqno++; + if (seqno == QCA_LAST_SEQUENCE_NUM) { + bt_dev_info(hdev, + "memdump done: pkts(%u), total(%u)\n", + qca_dump_ptr->ram_dump_seqno, qca_dump_ptr->ram_dump_size); + + hci_devcd_complete(hdev); + goto out; + } + return ret; + +out: + if (qca_dump_ptr->ram_dump_size) + usb_enable_autosuspend(udev); + qca_dump_ptr->ram_dump_size = 0; + qca_dump_ptr->ram_dump_seqno = 0; + clear_bit(BTUSB_HW_SSR_ACTIVE, &btdata->flags); + + if (ret < 0) + kfree_skb(skb); + return ret; +} + +/* Return: true if the ACL packet is a dump packet, false otherwise. */ +static bool acl_pkt_is_dump_qca(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct hci_event_hdr *event_hdr; + struct hci_acl_hdr *acl_hdr; + struct qca_dump_hdr *dump_hdr; + struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC); + bool is_dump = false; + + if (!clone) + return false; + + acl_hdr = skb_pull_data(clone, sizeof(*acl_hdr)); + if (!acl_hdr || (le16_to_cpu(acl_hdr->handle) != QCA_MEMDUMP_ACL_HANDLE)) + goto out; + + event_hdr = skb_pull_data(clone, sizeof(*event_hdr)); + if (!event_hdr || event_hdr->evt != HCI_EV_VENDOR) + goto out; + + dump_hdr = skb_pull_data(clone, sizeof(*dump_hdr)); + if (!dump_hdr || (dump_hdr->vse_class != QCA_MEMDUMP_VSE_CLASS) || + (dump_hdr->msg_type != QCA_MEMDUMP_MSG_TYPE)) + goto out; + + is_dump = true; +out: + consume_skb(clone); + return is_dump; +} + +/* Return: true if the event packet is a dump packet, false otherwise. */ +static bool evt_pkt_is_dump_qca(struct hci_dev *hdev, struct sk_buff *skb) +{ + struct hci_event_hdr *event_hdr; + struct qca_dump_hdr *dump_hdr; + struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC); + bool is_dump = false; + + if (!clone) + return false; + + event_hdr = skb_pull_data(clone, sizeof(*event_hdr)); + if (!event_hdr || event_hdr->evt != HCI_EV_VENDOR) + goto out; + + dump_hdr = skb_pull_data(clone, sizeof(*dump_hdr)); + if (!dump_hdr || (dump_hdr->vse_class != QCA_MEMDUMP_VSE_CLASS) || + (dump_hdr->msg_type != QCA_MEMDUMP_MSG_TYPE)) + goto out; + + is_dump = true; +out: + consume_skb(clone); + return is_dump; +} + +static int btusb_recv_acl_qca(struct hci_dev *hdev, struct sk_buff *skb) +{ + if (acl_pkt_is_dump_qca(hdev, skb)) + return handle_dump_pkt_qca(hdev, skb); + return hci_recv_frame(hdev, skb); +} + +static int btusb_recv_evt_qca(struct hci_dev *hdev, struct sk_buff *skb) +{ + if (evt_pkt_is_dump_qca(hdev, skb)) + return handle_dump_pkt_qca(hdev, skb); + return hci_recv_frame(hdev, skb); +} + + +#define QCA_DFU_PACKET_LEN 4096 + +#define QCA_GET_TARGET_VERSION 0x09 +#define QCA_CHECK_STATUS 0x05 +#define QCA_DFU_DOWNLOAD 0x01 + +#define QCA_SYSCFG_UPDATED 0x40 +#define QCA_PATCH_UPDATED 0x80 +#define QCA_DFU_TIMEOUT 3000 +#define QCA_FLAG_MULTI_NVM 0x80 +#define QCA_BT_RESET_WAIT_MS 100 + +#define WCN6855_2_0_RAM_VERSION_GF 0x400c1200 +#define WCN6855_2_1_RAM_VERSION_GF 0x400c1211 + +struct qca_version { + __le32 rom_version; + __le32 patch_version; + __le32 ram_version; + __u8 chip_id; + __u8 platform_id; + __le16 flag; + __u8 reserved[4]; +} __packed; + +struct qca_rampatch_version { + __le16 rom_version_high; + __le16 rom_version_low; + __le16 patch_version; +} __packed; + +struct qca_device_info { + u32 rom_version; + u8 rampatch_hdr; /* length of header in rampatch */ + u8 nvm_hdr; /* length of header in NVM */ + u8 ver_offset; /* offset of version structure in rampatch */ +}; + +struct qca_custom_firmware { + u32 rom_version; + u16 board_id; + const char *subdirectory; +}; + +static const struct qca_device_info qca_devices_table[] = { + { 0x00000100, 20, 4, 8 }, /* Rome 1.0 */ + { 0x00000101, 20, 4, 8 }, /* Rome 1.1 */ + { 0x00000200, 28, 4, 16 }, /* Rome 2.0 */ + { 0x00000201, 28, 4, 16 }, /* Rome 2.1 */ + { 0x00000300, 28, 4, 16 }, /* Rome 3.0 */ + { 0x00000302, 28, 4, 16 }, /* Rome 3.2 */ + { 0x00130100, 40, 4, 16 }, /* WCN6855 1.0 */ + { 0x00130200, 40, 4, 16 }, /* WCN6855 2.0 */ + { 0x00130201, 40, 4, 16 }, /* WCN6855 2.1 */ + { 0x00190200, 40, 4, 16 }, /* WCN785x 2.0 */ +}; + +static const struct qca_custom_firmware qca_custom_btfws[] = { + { 0x00130201, 0x030A, "QCA2066" }, + { 0x00130201, 0x030B, "QCA2066" }, + { }, +}; + +static u16 qca_extract_board_id(const struct qca_version *ver) +{ + u16 flag = le16_to_cpu(ver->flag); + u16 board_id = 0; + + if (((flag >> 8) & 0xff) == QCA_FLAG_MULTI_NVM) { + /* The board_id should be split into two bytes + * The 1st byte is chip ID, and the 2nd byte is platform ID + * For example, board ID 0x010A, 0x01 is platform ID. 0x0A is chip ID + * we have several platforms, and platform IDs are continuously added + * Platform ID: + * 0x00 is for Mobile + * 0x01 is for X86 + * 0x02 is for Automotive + * 0x03 is for Consumer electronic + */ + board_id = (ver->chip_id << 8) + ver->platform_id; + } + + /* Take 0xffff as invalid board ID */ + if (board_id == 0xffff) + board_id = 0; + + return board_id; +} + +static const char *qca_get_fw_subdirectory(const struct qca_version *ver) +{ + const struct qca_custom_firmware *ptr; + u32 rom_ver; + u16 board_id; + + rom_ver = le32_to_cpu(ver->rom_version); + board_id = qca_extract_board_id(ver); + if (!board_id) + return NULL; + + for (ptr = qca_custom_btfws; ptr->rom_version; ptr++) { + if (ptr->rom_version == rom_ver && + ptr->board_id == board_id) + return ptr->subdirectory; + } + + return NULL; +} + +static int btusb_qca_send_vendor_req(struct usb_device *udev, u8 request, + void *data, u16 size) +{ + int err; + + /* Found some of USB hosts have IOT issues with ours so that we should + * not wait until HCI layer is ready. + */ + err = usb_control_msg_recv(udev, 0, request, USB_TYPE_VENDOR | USB_DIR_IN, + 0, 0, data, size, USB_CTRL_GET_TIMEOUT, + GFP_KERNEL); + if (err) + dev_err(&udev->dev, "Failed to access otp area (%d)", err); + + return err; +} + +static int btusb_setup_qca_download_fw(struct hci_dev *hdev, + const struct firmware *firmware, + size_t hdr_size) +{ + struct btusb_data *btdata = hci_get_drvdata(hdev); + struct usb_device *udev = btdata->udev; + size_t count, size, sent = 0; + int pipe, len, err; + u8 *buf; + + buf = kmalloc(QCA_DFU_PACKET_LEN, GFP_KERNEL); + if (!buf) + return -ENOMEM; + + count = firmware->size; + + size = min_t(size_t, count, hdr_size); + memcpy(buf, firmware->data, size); + + /* USB patches should go down to controller through USB path + * because binary format fits to go down through USB channel. + * USB control path is for patching headers and USB bulk is for + * patch body. + */ + pipe = usb_sndctrlpipe(udev, 0); + err = usb_control_msg(udev, pipe, QCA_DFU_DOWNLOAD, USB_TYPE_VENDOR, + 0, 0, buf, size, USB_CTRL_SET_TIMEOUT); + if (err < 0) { + bt_dev_err(hdev, "Failed to send headers (%d)", err); + goto done; + } + + sent += size; + count -= size; + + /* ep2 need time to switch from function acl to function dfu, + * so we add 20ms delay here. + */ + msleep(20); + + while (count) { + size = min_t(size_t, count, QCA_DFU_PACKET_LEN); + + memcpy(buf, firmware->data + sent, size); + + pipe = usb_sndbulkpipe(udev, 0x02); + err = usb_bulk_msg(udev, pipe, buf, size, &len, + QCA_DFU_TIMEOUT); + if (err < 0) { + bt_dev_err(hdev, "Failed to send body at %zd of %zd (%d)", + sent, firmware->size, err); + break; + } + + if (size != len) { + bt_dev_err(hdev, "Failed to get bulk buffer"); + err = -EILSEQ; + break; + } + + sent += size; + count -= size; + } + +done: + kfree(buf); + return err; +} + +static int btusb_setup_qca_load_rampatch(struct hci_dev *hdev, + struct qca_version *ver, + const struct qca_device_info *info) +{ + struct qca_rampatch_version *rver; + const struct firmware *fw; + const char *fw_subdir; + u32 ver_rom, ver_patch, rver_rom; + u16 rver_rom_low, rver_rom_high, rver_patch; + char fwname[80]; + int err; + + ver_rom = le32_to_cpu(ver->rom_version); + ver_patch = le32_to_cpu(ver->patch_version); + + fw_subdir = qca_get_fw_subdirectory(ver); + if (fw_subdir) + snprintf(fwname, sizeof(fwname), "qca/%s/rampatch_usb_%08x.bin", + fw_subdir, ver_rom); + else + snprintf(fwname, sizeof(fwname), "qca/rampatch_usb_%08x.bin", + ver_rom); + + err = request_firmware(&fw, fwname, &hdev->dev); + if (err) { + bt_dev_err(hdev, "failed to request rampatch file: %s (%d)", + fwname, err); + return err; + } + + bt_dev_info(hdev, "using rampatch file: %s", fwname); + + rver = (struct qca_rampatch_version *)(fw->data + info->ver_offset); + rver_rom_low = le16_to_cpu(rver->rom_version_low); + rver_patch = le16_to_cpu(rver->patch_version); + + if (ver_rom & ~0xffffU) { + rver_rom_high = le16_to_cpu(rver->rom_version_high); + rver_rom = rver_rom_high << 16 | rver_rom_low; + } else { + rver_rom = rver_rom_low; + } + + bt_dev_info(hdev, "QCA: patch rome 0x%x build 0x%x, " + "firmware rome 0x%x build 0x%x", + rver_rom, rver_patch, ver_rom, ver_patch); + + /* Allow rampatch when the patch version equals the firmware version. + * A firmware download may be aborted by a transient USB error (e.g. + * disconnect) after the controller updates version info but before + * completion. + * Allowing equal versions enables re-flashing during recovery. + */ + if (rver_rom != ver_rom || rver_patch < ver_patch) { + bt_dev_err(hdev, "rampatch file version did not match with firmware"); + err = -EINVAL; + goto done; + } + + err = btusb_setup_qca_download_fw(hdev, fw, info->rampatch_hdr); + +done: + release_firmware(fw); + + return err; +} + +static void btusb_generate_qca_nvm_name(char *fwname, size_t max_size, + const struct qca_version *ver) +{ + u32 rom_version = le32_to_cpu(ver->rom_version); + const char *variant, *fw_subdir; + int len; + u16 board_id; + + fw_subdir = qca_get_fw_subdirectory(ver); + board_id = qca_extract_board_id(ver); + + switch (le32_to_cpu(ver->ram_version)) { + case WCN6855_2_0_RAM_VERSION_GF: + case WCN6855_2_1_RAM_VERSION_GF: + variant = "_gf"; + break; + default: + variant = NULL; + break; + } + + if (fw_subdir) + len = snprintf(fwname, max_size, "qca/%s/nvm_usb_%08x", + fw_subdir, rom_version); + else + len = snprintf(fwname, max_size, "qca/nvm_usb_%08x", + rom_version); + if (variant) + len += snprintf(fwname + len, max_size - len, "%s", variant); + if (board_id) + len += snprintf(fwname + len, max_size - len, "_%04x", board_id); + len += snprintf(fwname + len, max_size - len, ".bin"); +} + +static int btusb_setup_qca_load_nvm(struct hci_dev *hdev, + struct qca_version *ver, + const struct qca_device_info *info) +{ + const struct firmware *fw; + char fwname[80]; + int err; + + btusb_generate_qca_nvm_name(fwname, sizeof(fwname), ver); + + err = request_firmware(&fw, fwname, &hdev->dev); + if (err) { + bt_dev_err(hdev, "failed to request NVM file: %s (%d)", + fwname, err); + return err; + } + + bt_dev_info(hdev, "using NVM file: %s", fwname); + + err = btusb_setup_qca_download_fw(hdev, fw, info->nvm_hdr); + + release_firmware(fw); + + return err; +} + +/* identify the ROM version and check whether patches are needed */ +static bool btusb_qca_need_patch(struct usb_device *udev) +{ + struct qca_version ver; + + if (btusb_qca_send_vendor_req(udev, QCA_GET_TARGET_VERSION, &ver, + sizeof(ver))) + return false; + /* only low ROM versions need patches */ + return !(le32_to_cpu(ver.rom_version) & ~0xffffU); +} + +static int btusb_setup_qca(struct hci_dev *hdev) +{ + struct btusb_data *btdata = hci_get_drvdata(hdev); + struct usb_device *udev = btdata->udev; + const struct qca_device_info *info = NULL; + struct qca_version ver; + u32 ver_rom; + u8 status; + int i, err; + + err = btusb_qca_send_vendor_req(udev, QCA_GET_TARGET_VERSION, &ver, + sizeof(ver)); + if (err) + return err; + + ver_rom = le32_to_cpu(ver.rom_version); + + for (i = 0; i < ARRAY_SIZE(qca_devices_table); i++) { + if (ver_rom == qca_devices_table[i].rom_version) + info = &qca_devices_table[i]; + } + if (!info) { + /* If the rom_version is not matched in the qca_devices_table + * and the high ROM version is not zero, we assume this chip no + * need to load the rampatch and nvm. + */ + if (ver_rom & ~0xffffU) + return 0; + + bt_dev_err(hdev, "don't support firmware rome 0x%x", ver_rom); + return -ENODEV; + } + + err = btusb_qca_send_vendor_req(udev, QCA_CHECK_STATUS, &status, + sizeof(status)); + if (err) + return err; + + if (!(status & QCA_PATCH_UPDATED)) { + err = btusb_setup_qca_load_rampatch(hdev, &ver, info); + if (err < 0) + return err; + } + + err = btusb_qca_send_vendor_req(udev, QCA_GET_TARGET_VERSION, &ver, + sizeof(ver)); + if (err) + return err; + + if (btdata->match_id->driver_info & BTUSB_QCA_WCN6855) { + struct btqca_data *btqca_data = hci_get_priv(hdev); + + btqca_data->qca_dump.fw_version = le32_to_cpu(ver.patch_version); + btqca_data->qca_dump.controller_id = le32_to_cpu(ver.rom_version); + } + + if (!(status & QCA_SYSCFG_UPDATED)) { + err = btusb_setup_qca_load_nvm(hdev, &ver, info); + if (err < 0) + return err; + + /* WCN6855 2.1 and later will reset to apply firmware downloaded here, so + * wait ~100ms for reset Done then go ahead, otherwise, it maybe + * cause potential enable failure. + */ + if (info->rom_version >= 0x00130201) + msleep(QCA_BT_RESET_WAIT_MS); + } + + /* Mark HCI_OP_ENHANCED_SETUP_SYNC_CONN as broken as it doesn't seem to + * work with the likes of HSP/HFP mSBC. + */ + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_ENHANCED_SETUP_SYNC_CONN); + + return 0; +} + +static inline int __set_diag_interface(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct usb_interface *intf = data->diag; + int ret; + + if (!data->diag) + return -ENODEV; + + ret = usb_find_common_endpoints(intf->cur_altsetting, &data->diag_rx_ep, + &data->diag_tx_ep, NULL, NULL); + if (ret) { + bt_dev_err(hdev, "invalid diagnostic descriptors"); + return -ENODEV; + } + + return 0; +} + +static struct urb *alloc_diag_urb(struct hci_dev *hdev, bool enable) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct sk_buff *skb; + struct urb *urb; + unsigned int pipe; + + if (!data->diag_tx_ep) + return ERR_PTR(-ENODEV); + + urb = usb_alloc_urb(0, GFP_KERNEL); + if (!urb) + return ERR_PTR(-ENOMEM); + + skb = bt_skb_alloc(2, GFP_KERNEL); + if (!skb) { + usb_free_urb(urb); + return ERR_PTR(-ENOMEM); + } + + skb_put_u8(skb, 0xf0); + skb_put_u8(skb, enable); + + pipe = usb_sndbulkpipe(data->udev, data->diag_tx_ep->bEndpointAddress); + + usb_fill_bulk_urb(urb, data->udev, pipe, + skb->data, skb->len, btusb_tx_complete, skb); + + skb->dev = (void *)hdev; + + return urb; +} + +static int btusb_bcm_set_diag(struct hci_dev *hdev, bool enable) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct urb *urb; + + if (!data->diag) + return -ENODEV; + + if (!test_bit(HCI_RUNNING, &hdev->flags)) + return -ENETDOWN; + + urb = alloc_diag_urb(hdev, enable); + if (IS_ERR(urb)) + return PTR_ERR(urb); + + return submit_or_queue_tx_urb(hdev, urb); +} + +#ifdef CONFIG_PM +static irqreturn_t btusb_oob_wake_handler(int irq, void *priv) +{ + struct btusb_data *data = priv; + + pm_wakeup_event(&data->udev->dev, 0); + pm_system_wakeup(); + + /* Disable only if not already disabled (keep it balanced) */ + if (test_and_clear_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags)) { + disable_irq_nosync(irq); + disable_irq_wake(irq); + } + return IRQ_HANDLED; +} + +static const struct of_device_id btusb_match_table[] = { + { .compatible = "usb1286,204e" }, + { .compatible = "usbcf3,e300" }, /* QCA6174A */ + { .compatible = "usb4ca,301a" }, /* QCA6174A (Lite-On) */ + { } +}; +MODULE_DEVICE_TABLE(of, btusb_match_table); + +/* Use an oob wakeup pin? */ +static int btusb_config_oob_wake(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + struct device *dev = &data->udev->dev; + int irq, ret; + + clear_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags); + + if (!of_match_device(btusb_match_table, dev)) + return 0; + + /* Move on if no IRQ specified */ + irq = of_irq_get_byname(dev->of_node, "wakeup"); + if (irq <= 0) { + bt_dev_dbg(hdev, "%s: no OOB Wakeup IRQ in DT", __func__); + return 0; + } + + irq_set_status_flags(irq, IRQ_NOAUTOEN); + ret = request_irq(irq, btusb_oob_wake_handler, 0, "OOB Wake-on-BT", data); + if (ret) { + bt_dev_err(hdev, "%s: IRQ request failed", __func__); + return ret; + } + + ret = device_init_wakeup(dev, true); + if (ret) { + bt_dev_err(hdev, "%s: failed to init_wakeup", __func__); + goto err_free_irq; + } + + data->oob_wake_irq = irq; + bt_dev_info(hdev, "OOB Wake-on-BT configured at IRQ %u", irq); + + return 0; + +err_free_irq: + free_irq(irq, data); + + return ret; +} +#else +static inline int btusb_config_oob_wake(struct hci_dev *hdev) +{ + return 0; +} +#endif + +static void btusb_check_needs_reset_resume(struct usb_interface *intf) +{ + if (dmi_check_system(btusb_needs_reset_resume_table)) + interface_to_usbdev(intf)->quirks |= USB_QUIRK_RESET_RESUME; +} + +static bool btusb_wakeup(struct hci_dev *hdev) +{ + struct btusb_data *data = hci_get_drvdata(hdev); + + return device_may_wakeup(&data->udev->dev); +} + +static int btusb_shutdown_qca(struct hci_dev *hdev) +{ + int err; + + err = __hci_reset_sync(hdev); + if (err) + bt_dev_err(hdev, "HCI reset during shutdown failed"); + + return err; +} + +static ssize_t force_poll_sync_read(struct file *file, char __user *user_buf, + size_t count, loff_t *ppos) +{ + struct btusb_data *data = file->private_data; + char buf[3]; + + buf[0] = data->poll_sync ? 'Y' : 'N'; + buf[1] = '\n'; + buf[2] = '\0'; + return simple_read_from_buffer(user_buf, count, ppos, buf, 2); +} + +static ssize_t force_poll_sync_write(struct file *file, + const char __user *user_buf, + size_t count, loff_t *ppos) +{ + struct btusb_data *data = file->private_data; + bool enable; + int err; + + err = kstrtobool_from_user(user_buf, count, &enable); + if (err) + return err; + + /* Only allow changes while the adapter is down */ + if (test_bit(HCI_UP, &data->hdev->flags)) + return -EPERM; + + if (data->poll_sync == enable) + return -EALREADY; + + data->poll_sync = enable; + + return count; +} + +static const struct file_operations force_poll_sync_fops = { + .owner = THIS_MODULE, + .open = simple_open, + .read = force_poll_sync_read, + .write = force_poll_sync_write, + .llseek = default_llseek, +}; + +#define BTUSB_HCI_DRV_OP_SUPPORTED_ALTSETTINGS \ + hci_opcode_pack(HCI_DRV_OGF_DRIVER_SPECIFIC, 0x0000) +#define BTUSB_HCI_DRV_SUPPORTED_ALTSETTINGS_SIZE 0 +struct btusb_hci_drv_rp_supported_altsettings { + __u8 num; + __u8 altsettings[]; +} __packed; + +#define BTUSB_HCI_DRV_OP_SWITCH_ALTSETTING \ + hci_opcode_pack(HCI_DRV_OGF_DRIVER_SPECIFIC, 0x0001) +#define BTUSB_HCI_DRV_SWITCH_ALTSETTING_SIZE 1 +struct btusb_hci_drv_cmd_switch_altsetting { + __u8 altsetting; +} __packed; + +static const struct { + u16 opcode; + const char *desc; +} btusb_hci_drv_supported_commands[] = { + /* Common commands */ + { HCI_DRV_OP_READ_INFO, "Read Info" }, + + /* Driver specific commands */ + { BTUSB_HCI_DRV_OP_SUPPORTED_ALTSETTINGS, "Supported Altsettings" }, + { BTUSB_HCI_DRV_OP_SWITCH_ALTSETTING, "Switch Altsetting" }, +}; +static int btusb_hci_drv_read_info(struct hci_dev *hdev, void *data, + u16 data_len) +{ + struct hci_drv_rp_read_info *rp; + size_t rp_size; + int err, i; + u16 opcode, num_supported_commands = + ARRAY_SIZE(btusb_hci_drv_supported_commands); + + rp_size = sizeof(*rp) + num_supported_commands * 2; + + rp = kmalloc(rp_size, GFP_KERNEL); + if (!rp) + return -ENOMEM; + + strscpy_pad(rp->driver_name, btusb_driver.name); + + rp->num_supported_commands = cpu_to_le16(num_supported_commands); + for (i = 0; i < num_supported_commands; i++) { + opcode = btusb_hci_drv_supported_commands[i].opcode; + bt_dev_info(hdev, + "Supported HCI Drv command (0x%02x|0x%04x): %s", + hci_opcode_ogf(opcode), + hci_opcode_ocf(opcode), + btusb_hci_drv_supported_commands[i].desc); + rp->supported_commands[i] = cpu_to_le16(opcode); + } + + err = hci_drv_cmd_complete(hdev, HCI_DRV_OP_READ_INFO, + HCI_DRV_STATUS_SUCCESS, rp, rp_size); + + kfree(rp); + return err; +} + +static int btusb_hci_drv_supported_altsettings(struct hci_dev *hdev, void *data, + u16 data_len) +{ + struct btusb_data *drvdata = hci_get_drvdata(hdev); + struct btusb_hci_drv_rp_supported_altsettings *rp; + size_t rp_size; + int err; + u8 i; + + /* There are at most 7 alt (0 - 6) */ + rp = kmalloc(sizeof(*rp) + 7, GFP_KERNEL); + if (!rp) + return -ENOMEM; + + rp->num = 0; + if (!drvdata->isoc) + goto done; + + for (i = 0; i <= 6; i++) { + if (btusb_find_altsetting(drvdata, i)) + rp->altsettings[rp->num++] = i; + } + +done: + rp_size = sizeof(*rp) + rp->num; + + err = hci_drv_cmd_complete(hdev, BTUSB_HCI_DRV_OP_SUPPORTED_ALTSETTINGS, + HCI_DRV_STATUS_SUCCESS, rp, rp_size); + kfree(rp); + return err; +} + +static int btusb_hci_drv_switch_altsetting(struct hci_dev *hdev, void *data, + u16 data_len) +{ + struct btusb_hci_drv_cmd_switch_altsetting *cmd = data; + u8 status; + + if (cmd->altsetting > 6) { + status = HCI_DRV_STATUS_INVALID_PARAMETERS; + } else { + if (btusb_switch_alt_setting(hdev, cmd->altsetting)) + status = HCI_DRV_STATUS_UNSPECIFIED_ERROR; + else + status = HCI_DRV_STATUS_SUCCESS; + } + + return hci_drv_cmd_status(hdev, BTUSB_HCI_DRV_OP_SWITCH_ALTSETTING, + status); +} + +static const struct hci_drv_handler btusb_hci_drv_common_handlers[] = { + { btusb_hci_drv_read_info, HCI_DRV_READ_INFO_SIZE }, +}; + +static const struct hci_drv_handler btusb_hci_drv_specific_handlers[] = { + { btusb_hci_drv_supported_altsettings, + BTUSB_HCI_DRV_SUPPORTED_ALTSETTINGS_SIZE }, + { btusb_hci_drv_switch_altsetting, + BTUSB_HCI_DRV_SWITCH_ALTSETTING_SIZE }, +}; + +static struct hci_drv btusb_hci_drv = { + .common_handler_count = ARRAY_SIZE(btusb_hci_drv_common_handlers), + .common_handlers = btusb_hci_drv_common_handlers, + .specific_handler_count = ARRAY_SIZE(btusb_hci_drv_specific_handlers), + .specific_handlers = btusb_hci_drv_specific_handlers, +}; + +static int btusb_probe(struct usb_interface *intf, + const struct usb_device_id *id) +{ + struct gpio_desc *reset_gpio; + struct btusb_data *data; + struct hci_dev *hdev; + unsigned ifnum_base; + int err, priv_size = 0; + + BT_DBG("intf %p id %p", intf, id); + + if ((id->driver_info & BTUSB_IFNUM_2) && + (intf->cur_altsetting->desc.bInterfaceNumber != 0) && + (intf->cur_altsetting->desc.bInterfaceNumber != 2)) + return -ENODEV; + + ifnum_base = intf->cur_altsetting->desc.bInterfaceNumber; + + if (!id->driver_info) { + const struct usb_device_id *match; + + match = usb_match_id(intf, quirks_table); + if (match) + id = match; + } + + if (id->driver_info & BTUSB_IGNORE) + return -ENODEV; + + if (id->driver_info & BTUSB_ATH3012) { + struct usb_device *udev = interface_to_usbdev(intf); + + /* Old firmware would otherwise let ath3k driver load + * patch and sysconfig files + */ + if (le16_to_cpu(udev->descriptor.bcdDevice) <= 0x0001 && + !btusb_qca_need_patch(udev)) + return -ENODEV; + } + + data = kzalloc_obj(*data); + if (!data) + return -ENOMEM; + + data->match_id = id; + err = usb_find_common_endpoints(intf->cur_altsetting, &data->bulk_rx_ep, + &data->bulk_tx_ep, &data->intr_ep, NULL); + if (err) + goto err_free_data; + + if (id->driver_info & BTUSB_AMP) { + data->cmdreq_type = USB_TYPE_CLASS | 0x01; + data->cmdreq = 0x2b; + } else { + data->cmdreq_type = USB_TYPE_CLASS; + data->cmdreq = 0x00; + } + + data->udev = interface_to_usbdev(intf); + data->intf = intf; + + INIT_WORK(&data->work, btusb_work); + INIT_WORK(&data->waker, btusb_waker); + INIT_DELAYED_WORK(&data->rx_work, btusb_rx_work); + + skb_queue_head_init(&data->acl_q); + + init_usb_anchor(&data->deferred); + init_usb_anchor(&data->tx_anchor); + spin_lock_init(&data->txlock); + + init_usb_anchor(&data->intr_anchor); + init_usb_anchor(&data->bulk_anchor); + init_usb_anchor(&data->isoc_anchor); + init_usb_anchor(&data->diag_anchor); + init_usb_anchor(&data->ctrl_anchor); + spin_lock_init(&data->rxlock); + + data->recv_event = hci_recv_frame; + data->recv_bulk = btusb_recv_bulk; + + if (id->driver_info & BTUSB_INTEL_COMBINED) { + /* Allocate extra space for Intel device */ + priv_size += sizeof(struct btintel_data); + + /* Override the rx handlers */ + data->recv_event = btintel_recv_event; + data->recv_bulk = btusb_recv_bulk_intel; + } else if (id->driver_info & BTUSB_REALTEK) { + /* Allocate extra space for Realtek device */ + priv_size += sizeof(struct btrealtek_data); + + data->recv_event = btusb_recv_event_realtek; + } else if (id->driver_info & BTUSB_MEDIATEK) { + /* Allocate extra space for Mediatek device */ + priv_size += sizeof(struct btmtk_data); + } else if (id->driver_info & BTUSB_QCA_WCN6855) { + /* Allocate extra space for QCA WCN6855 device */ + priv_size += sizeof(struct btqca_data); + } + + data->recv_acl = hci_recv_frame; + + hdev = hci_alloc_dev_priv(priv_size); + if (!hdev) { + err = -ENOMEM; + goto err_free_data; + } + + hdev->bus = HCI_USB; + hci_set_drvdata(hdev, data); + + data->hdev = hdev; + + SET_HCIDEV_DEV(hdev, &intf->dev); + + reset_gpio = gpiod_get_optional(&data->udev->dev, "reset", + GPIOD_OUT_LOW); + if (IS_ERR(reset_gpio)) { + err = PTR_ERR(reset_gpio); + goto err_free_hdev; + } else if (reset_gpio) { + data->reset_gpio = reset_gpio; + } + + hdev->open = btusb_open; + hdev->close = btusb_close; + hdev->flush = btusb_flush; + hdev->send = btusb_send_frame; + hdev->notify = btusb_notify; + hdev->wakeup = btusb_wakeup; + hdev->hci_drv = &btusb_hci_drv; + + err = btusb_config_oob_wake(hdev); + if (err) + goto err_put_reset; + + /* Marvell devices may need a specific chip configuration */ + if (id->driver_info & BTUSB_MARVELL && data->oob_wake_irq) { + err = marvell_config_oob_wake(hdev); + if (err) + goto err_disable_wakeup; + } + + if (id->driver_info & BTUSB_CW6622) + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_STORED_LINK_KEY); + + if (id->driver_info & BTUSB_BCM2045) + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_STORED_LINK_KEY); + + if (id->driver_info & BTUSB_BCM92035) + hdev->setup = btusb_setup_bcm92035; + + if (IS_ENABLED(CONFIG_BT_HCIBTUSB_BCM) && + (id->driver_info & BTUSB_BCM_PATCHRAM)) { + hdev->manufacturer = 15; + hdev->setup = btbcm_setup_patchram; + hdev->set_diag = btusb_bcm_set_diag; + hdev->set_bdaddr = btbcm_set_bdaddr; + + /* Broadcom LM_DIAG Interface numbers are hardcoded */ + data->diag = usb_ifnum_to_if(data->udev, ifnum_base + 2); + } + + if (IS_ENABLED(CONFIG_BT_HCIBTUSB_BCM) && + (id->driver_info & BTUSB_BCM_APPLE)) { + hdev->manufacturer = 15; + hdev->setup = btbcm_setup_apple; + hdev->set_diag = btusb_bcm_set_diag; + + /* Broadcom LM_DIAG Interface numbers are hardcoded */ + data->diag = usb_ifnum_to_if(data->udev, ifnum_base + 2); + } + + /* Combined Intel Device setup to support multiple setup routine */ + if (id->driver_info & BTUSB_INTEL_COMBINED) { + err = btintel_configure_setup(hdev, btusb_driver.name); + if (err) + goto err_kill_tx_urbs; + + /* Transport specific configuration */ + hdev->send = btusb_send_frame_intel; + hdev->reset = btusb_intel_reset; + + if (id->driver_info & BTUSB_INTEL_NO_WBS_SUPPORT) + btintel_set_flag(hdev, INTEL_ROM_LEGACY_NO_WBS_SUPPORT); + + if (id->driver_info & BTUSB_INTEL_BROKEN_INITIAL_NCMD) + btintel_set_flag(hdev, INTEL_BROKEN_INITIAL_NCMD); + + if (id->driver_info & BTUSB_INTEL_BROKEN_SHUTDOWN_LED) + btintel_set_flag(hdev, INTEL_BROKEN_SHUTDOWN_LED); + } + + if (id->driver_info & BTUSB_MARVELL) + hdev->set_bdaddr = btusb_set_bdaddr_marvell; + + if (IS_ENABLED(CONFIG_BT_HCIBTUSB_MTK) && + (id->driver_info & BTUSB_MEDIATEK)) { + hdev->setup = btusb_mtk_setup; + hdev->shutdown = btusb_mtk_shutdown; + hdev->manufacturer = 70; + hdev->reset = btmtk_reset_sync; + hdev->set_bdaddr = btmtk_set_bdaddr; + hdev->send = btusb_send_frame_mtk; + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_ENHANCED_SETUP_SYNC_CONN); + hci_set_quirk(hdev, HCI_QUIRK_NON_PERSISTENT_SETUP); + data->recv_acl = btmtk_usb_recv_acl; + data->recv_event = btmtk_recv_event; + data->suspend = btmtk_usb_suspend; + data->resume = btmtk_usb_resume; + data->disconnect = btusb_mtk_disconnect; + } + + if (id->driver_info & BTUSB_SWAVE) { + hci_set_quirk(hdev, HCI_QUIRK_FIXUP_INQUIRY_MODE); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_LOCAL_COMMANDS); + } + + if (id->driver_info & BTUSB_INTEL_BOOT) { + hdev->manufacturer = 2; + hci_set_quirk(hdev, HCI_QUIRK_RAW_DEVICE); + } + + if (id->driver_info & BTUSB_ATH3012) { + data->setup_on_usb = btusb_setup_qca; + hdev->set_bdaddr = btusb_set_bdaddr_ath3012; + hci_set_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY); + hci_set_quirk(hdev, HCI_QUIRK_STRICT_DUPLICATE_FILTER); + } + + if (id->driver_info & BTUSB_QCA_ROME) { + data->setup_on_usb = btusb_setup_qca; + hdev->shutdown = btusb_shutdown_qca; + hdev->set_bdaddr = btusb_set_bdaddr_ath3012; + hdev->reset = btusb_qca_reset; + hci_set_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY); + btusb_check_needs_reset_resume(intf); + } + + if (id->driver_info & BTUSB_QCA_WCN6855) { + struct btqca_data *btqca_data = hci_get_priv(hdev); + + btqca_data->qca_dump.id_vendor = id->idVendor; + btqca_data->qca_dump.id_product = id->idProduct; + data->recv_event = btusb_recv_evt_qca; + data->recv_acl = btusb_recv_acl_qca; + hci_devcd_register(hdev, btusb_coredump_qca, btusb_dump_hdr_qca, NULL); + data->setup_on_usb = btusb_setup_qca; + hdev->classify_pkt_type = btusb_classify_qca_pkt_type; + hdev->shutdown = btusb_shutdown_qca; + hdev->set_bdaddr = btusb_set_bdaddr_wcn6855; + hdev->reset = btusb_qca_reset; + hci_set_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY); + hci_set_msft_opcode(hdev, 0xFD70); + } + + if (id->driver_info & BTUSB_AMP) { + /* AMP controllers do not support SCO packets */ + data->isoc = NULL; + } else { + /* Interface orders are hardcoded in the specification */ + data->isoc = usb_ifnum_to_if(data->udev, ifnum_base + 1); + data->isoc_ifnum = ifnum_base + 1; + } + + if (IS_ENABLED(CONFIG_BT_HCIBTUSB_RTL) && + (id->driver_info & BTUSB_REALTEK)) { + btrtl_set_driver_name(hdev, btusb_driver.name); + hdev->setup = btusb_setup_realtek; + hdev->shutdown = btrtl_shutdown_realtek; + hdev->reset = btusb_rtl_reset; + hdev->hw_error = btusb_rtl_hw_error; + + /* Realtek devices need to set remote wakeup on auto-suspend */ + set_bit(BTUSB_WAKEUP_AUTOSUSPEND, &data->flags); + set_bit(BTUSB_USE_ALT3_FOR_WBS, &data->flags); + } + + if (id->driver_info & BTUSB_ACTIONS_SEMI) { + /* Support is advertised, but not implemented */ + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_ERR_DATA_REPORTING); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_READ_TRANSMIT_POWER); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_SET_RPA_TIMEOUT); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_EXT_SCAN); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_READ_ENC_KEY_SIZE); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_EXT_CREATE_CONN); + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_WRITE_AUTH_PAYLOAD_TIMEOUT); + } + + if (!reset) + hci_set_quirk(hdev, HCI_QUIRK_RESET_ON_CLOSE); + + if (force_scofix || id->driver_info & BTUSB_WRONG_SCO_MTU) { + if (!disable_scofix) + hci_set_quirk(hdev, HCI_QUIRK_FIXUP_BUFFER_SIZE); + } + + if (id->driver_info & BTUSB_BROKEN_ISOC) + data->isoc = NULL; + + if (id->driver_info & BTUSB_WIDEBAND_SPEECH) + hci_set_quirk(hdev, HCI_QUIRK_WIDEBAND_SPEECH_SUPPORTED); + + if (id->driver_info & BTUSB_INVALID_LE_STATES) + hci_set_quirk(hdev, HCI_QUIRK_BROKEN_LE_STATES); + + if (id->driver_info & BTUSB_DIGIANSWER) { + data->cmdreq_type = USB_TYPE_VENDOR; + hci_set_quirk(hdev, HCI_QUIRK_RESET_ON_CLOSE); + } + + if (id->driver_info & BTUSB_CSR) { + struct usb_device *udev = data->udev; + u16 bcdDevice = le16_to_cpu(udev->descriptor.bcdDevice); + + /* Old firmware would otherwise execute USB reset */ + if (bcdDevice < 0x117) + hci_set_quirk(hdev, HCI_QUIRK_RESET_ON_CLOSE); + + /* This must be set first in case we disable it for fakes */ + hci_set_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY); + + /* Fake CSR devices with broken commands */ + if (le16_to_cpu(udev->descriptor.idVendor) == 0x0a12 && + le16_to_cpu(udev->descriptor.idProduct) == 0x0001) + hdev->setup = btusb_setup_csr; + } + + if (id->driver_info & BTUSB_SNIFFER) { + struct usb_device *udev = data->udev; + + /* New sniffer firmware has crippled HCI interface */ + if (le16_to_cpu(udev->descriptor.bcdDevice) > 0x997) + hci_set_quirk(hdev, HCI_QUIRK_RAW_DEVICE); + } + + if (id->driver_info & BTUSB_INTEL_BOOT) { + /* A bug in the bootloader causes that interrupt interface is + * only enabled after receiving SetInterface(0, AltSetting=0). + */ + err = usb_set_interface(data->udev, 0, 0); + if (err < 0) { + BT_ERR("failed to set interface 0, alt 0 %d", err); + goto err_kill_tx_urbs; + } + } + + if (data->isoc) { + err = usb_driver_claim_interface(&btusb_driver, + data->isoc, data); + if (err < 0) + goto err_kill_tx_urbs; + } + + if (IS_ENABLED(CONFIG_BT_HCIBTUSB_BCM) && data->diag) { + if (!usb_driver_claim_interface(&btusb_driver, + data->diag, data)) + __set_diag_interface(hdev); + else + data->diag = NULL; + } + + if (enable_autosuspend) + usb_enable_autosuspend(data->udev); + + data->poll_sync = enable_poll_sync; + + err = hci_register_dev(hdev); + if (err < 0) + goto err_release_siblings; + + usb_set_intfdata(intf, data); + + debugfs_create_file("force_poll_sync", 0644, hdev->debugfs, data, + &force_poll_sync_fops); + + return 0; + +err_release_siblings: + if (data->diag) { + usb_set_intfdata(data->diag, NULL); + usb_driver_release_interface(&btusb_driver, data->diag); + } + if (data->isoc) { + usb_set_intfdata(data->isoc, NULL); + usb_driver_release_interface(&btusb_driver, data->isoc); + } +err_kill_tx_urbs: + usb_kill_anchored_urbs(&data->tx_anchor); +err_disable_wakeup: + if (data->oob_wake_irq) { + device_init_wakeup(&data->udev->dev, false); + free_irq(data->oob_wake_irq, data); + } +err_put_reset: + if (data->reset_gpio) + gpiod_put(data->reset_gpio); +err_free_hdev: + hci_free_dev(hdev); +err_free_data: + kfree(data); + + return err; +} + +static void btusb_disconnect(struct usb_interface *intf) +{ + struct btusb_data *data = usb_get_intfdata(intf); + struct hci_dev *hdev; + + BT_DBG("intf %p", intf); + + if (!data) + return; + + hdev = data->hdev; + usb_set_intfdata(data->intf, NULL); + + if (data->isoc) + usb_set_intfdata(data->isoc, NULL); + + if (data->diag) + usb_set_intfdata(data->diag, NULL); + + if (data->disconnect) + data->disconnect(hdev); + + hci_unregister_dev(hdev); + + if (data->oob_wake_irq) { + device_init_wakeup(&data->udev->dev, false); + free_irq(data->oob_wake_irq, data); + } + + if (data->reset_gpio) + gpiod_put(data->reset_gpio); + + if (test_and_clear_bit(BTUSB_RESET, &data->flags)) + usb_autopm_put_interface_no_suspend(data->intf); + + if (intf == data->intf) { + if (data->isoc) + usb_driver_release_interface(&btusb_driver, data->isoc); + if (data->diag) + usb_driver_release_interface(&btusb_driver, data->diag); + } else if (intf == data->isoc) { + if (data->diag) + usb_driver_release_interface(&btusb_driver, data->diag); + usb_driver_release_interface(&btusb_driver, data->intf); + } else if (intf == data->diag) { + if (data->isoc) + usb_driver_release_interface(&btusb_driver, data->isoc); + usb_driver_release_interface(&btusb_driver, data->intf); + } + + hci_free_dev(hdev); + kfree(data); +} + +static int btusb_suspend(struct usb_interface *intf, pm_message_t message) +{ + struct btusb_data *data = usb_get_intfdata(intf); + + BT_DBG("intf %p", intf); + + /* + * It is reported that remote wakeup events could sometimes cause some + * adapters completely unresponsive. Resetting the xHCI root hub doesn't + * help at all, and recovering from such a state needs a power cycle. + * Since disabling remote wakeup simply causes the USB core to gate + * runtime autosuspend as well due to needs_remote_wakeup == 1, let's do + * this ourselves to make our life easier. The interface can be safely + * autosuspended as long as remote wakeup is disabled, i.e., after + * closing the HCI device. + * + * Don't auto-suspend if there are connections or discovery in progress. + * + * External suspend calls shall never fail. Specifically, a device with + * broken remote wakeup may still take the advantage of remote wakeup in + * order to wake up the system from sleep if userspace has enabled it as + * a wakeup source. + */ + if (PMSG_IS_AUTO(message) && + ((test_bit(BTUSB_WAKEUP_BROKEN, &data->flags) && data->intf->needs_remote_wakeup) || + hci_conn_count(data->hdev) || hci_discovery_active(data->hdev))) + return -EBUSY; + + if (data->suspend_count++) + return 0; + + spin_lock_irq(&data->txlock); + if (!(PMSG_IS_AUTO(message) && data->tx_in_flight)) { + set_bit(BTUSB_SUSPENDING, &data->flags); + spin_unlock_irq(&data->txlock); + } else { + spin_unlock_irq(&data->txlock); + data->suspend_count--; + return -EBUSY; + } + + cancel_work_sync(&data->work); + + if (data->suspend) + data->suspend(data->hdev); + + btusb_stop_traffic(data); + usb_kill_anchored_urbs(&data->tx_anchor); + + if (data->oob_wake_irq && device_may_wakeup(&data->udev->dev)) { + set_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags); + enable_irq_wake(data->oob_wake_irq); + enable_irq(data->oob_wake_irq); + } + + /* For global suspend, Realtek devices lose the loaded fw + * in them. But for autosuspend, firmware should remain. + * Actually, it depends on whether the usb host sends + * set feature (enable wakeup) or not. + */ + if (test_bit(BTUSB_WAKEUP_AUTOSUSPEND, &data->flags)) { + if (PMSG_IS_AUTO(message) && + device_can_wakeup(&data->udev->dev)) + data->udev->do_remote_wakeup = 1; + else if (!PMSG_IS_AUTO(message) && + !device_may_wakeup(&data->udev->dev)) { + data->udev->do_remote_wakeup = 0; + data->udev->reset_resume = 1; + } + } + + return 0; +} + +static void play_deferred(struct btusb_data *data) +{ + struct urb *urb; + int err; + + while ((urb = usb_get_from_anchor(&data->deferred))) { + usb_anchor_urb(urb, &data->tx_anchor); + + err = usb_submit_urb(urb, GFP_ATOMIC); + if (err < 0) { + if (err != -EPERM && err != -ENODEV) + BT_ERR("%s urb %p submission failed (%d)", + data->hdev->name, urb, -err); + kfree(urb->setup_packet); + usb_unanchor_urb(urb); + usb_free_urb(urb); + break; + } + + data->tx_in_flight++; + usb_free_urb(urb); + } + + /* Cleanup the rest deferred urbs. */ + while ((urb = usb_get_from_anchor(&data->deferred))) { + kfree(urb->setup_packet); + usb_free_urb(urb); + } +} + +static int btusb_resume(struct usb_interface *intf) +{ + struct btusb_data *data = usb_get_intfdata(intf); + struct hci_dev *hdev = data->hdev; + int err = 0; + + BT_DBG("intf %p", intf); + + if (--data->suspend_count) + return 0; + + /* Disable only if not already disabled (keep it balanced) */ + if (test_and_clear_bit(BTUSB_OOB_WAKE_ENABLED, &data->flags)) { + disable_irq(data->oob_wake_irq); + disable_irq_wake(data->oob_wake_irq); + } + + if (!test_bit(HCI_RUNNING, &hdev->flags)) + goto done; + + if (test_bit(BTUSB_INTR_RUNNING, &data->flags)) { + err = btusb_submit_intr_urb(hdev, GFP_NOIO); + if (err < 0) { + clear_bit(BTUSB_INTR_RUNNING, &data->flags); + goto failed; + } + } + + if (test_bit(BTUSB_BULK_RUNNING, &data->flags)) { + err = btusb_submit_bulk_urb(hdev, GFP_NOIO); + if (err < 0) { + clear_bit(BTUSB_BULK_RUNNING, &data->flags); + goto failed; + } + + btusb_submit_bulk_urb(hdev, GFP_NOIO); + } + + if (test_bit(BTUSB_ISOC_RUNNING, &data->flags)) { + if (btusb_submit_isoc_urb(hdev, GFP_NOIO) < 0) + clear_bit(BTUSB_ISOC_RUNNING, &data->flags); + else + btusb_submit_isoc_urb(hdev, GFP_NOIO); + } + + if (data->resume) + data->resume(hdev); + + spin_lock_irq(&data->txlock); + play_deferred(data); + clear_bit(BTUSB_SUSPENDING, &data->flags); + spin_unlock_irq(&data->txlock); + schedule_work(&data->work); + + return 0; + +failed: + usb_scuttle_anchored_urbs(&data->deferred); +done: + spin_lock_irq(&data->txlock); + clear_bit(BTUSB_SUSPENDING, &data->flags); + spin_unlock_irq(&data->txlock); + + return err; +} + +#ifdef CONFIG_DEV_COREDUMP +static void btusb_coredump(struct device *dev) +{ + struct btusb_data *data = dev_get_drvdata(dev); + struct hci_dev *hdev = data->hdev; + + if (hdev->dump.coredump) + hdev->dump.coredump(hdev); +} +#endif + +static struct usb_driver btusb_driver = { + .name = "btusb", + .probe = btusb_probe, + .disconnect = btusb_disconnect, + .suspend = pm_ptr(btusb_suspend), + .resume = pm_ptr(btusb_resume), + .id_table = btusb_table, + .supports_autosuspend = 1, + .disable_hub_initiated_lpm = 1, + +#ifdef CONFIG_DEV_COREDUMP + .driver = { + .coredump = btusb_coredump, + }, +#endif +}; + +module_usb_driver(btusb_driver); + +module_param(disable_scofix, bool, 0644); +MODULE_PARM_DESC(disable_scofix, "Disable fixup of wrong SCO buffer size"); + +module_param(force_scofix, bool, 0644); +MODULE_PARM_DESC(force_scofix, "Force fixup of wrong SCO buffers size"); + +module_param(enable_autosuspend, bool, 0644); +MODULE_PARM_DESC(enable_autosuspend, "Enable USB autosuspend by default"); + +module_param(reset, bool, 0644); +MODULE_PARM_DESC(reset, "Send HCI reset command on initialization"); + +MODULE_AUTHOR("Marcel Holtmann "); +MODULE_DESCRIPTION("Generic Bluetooth USB driver ver " VERSION); +MODULE_VERSION(VERSION); +MODULE_LICENSE("GPL"); diff --git a/drivers/bluetooth/hci_h4.c b/drivers/bluetooth/hci_h4.c index 767372707498..cbdf51458ec3 100644 --- a/drivers/bluetooth/hci_h4.c +++ b/drivers/bluetooth/hci_h4.c @@ -29,6 +29,7 @@ #include #include +#include #include "hci_uart.h" @@ -112,8 +113,9 @@ static int h4_recv(struct hci_uart *hu, const void *data, int count) if (!h4) return -ENODEV; - h4->rx_skb = h4_recv_buf(hu, h4->rx_skb, data, count, - h4_recv_pkts, ARRAY_SIZE(h4_recv_pkts)); + h4->rx_skb = h4_recv_skb(hu->hdev, &hu->alignment, &hu->padding, + h4->rx_skb, data, count, h4_recv_pkts, + ARRAY_SIZE(h4_recv_pkts)); if (IS_ERR(h4->rx_skb)) { int err = PTR_ERR(h4->rx_skb); bt_dev_err(hu->hdev, "Frame reassembly failed (%d)", err); @@ -155,120 +157,7 @@ struct sk_buff *h4_recv_buf(struct hci_uart *hu, struct sk_buff *skb, const unsigned char *buffer, int count, const struct h4_recv_pkt *pkts, int pkts_count) { - u8 alignment = hu->alignment ? hu->alignment : 1; - struct hci_dev *hdev = hu->hdev; - - /* Check for error from previous call */ - if (IS_ERR(skb)) - skb = NULL; - - while (count) { - int i, len; - - /* remove padding bytes from buffer */ - for (; hu->padding && count > 0; hu->padding--) { - count--; - buffer++; - } - if (!count) - break; - - if (!skb) { - for (i = 0; i < pkts_count; i++) { - if (buffer[0] != (&pkts[i])->type) - continue; - - skb = bt_skb_alloc((&pkts[i])->maxlen, - GFP_ATOMIC); - if (!skb) - return ERR_PTR(-ENOMEM); - - hci_skb_pkt_type(skb) = (&pkts[i])->type; - hci_skb_expect(skb) = (&pkts[i])->hlen; - break; - } - - /* Check for invalid packet type */ - if (!skb) - return ERR_PTR(-EILSEQ); - - count -= 1; - buffer += 1; - } - - len = min_t(uint, hci_skb_expect(skb) - skb->len, count); - skb_put_data(skb, buffer, len); - - count -= len; - buffer += len; - - /* Check for partial packet */ - if (skb->len < hci_skb_expect(skb)) - continue; - - for (i = 0; i < pkts_count; i++) { - if (hci_skb_pkt_type(skb) == (&pkts[i])->type) - break; - } - - if (i >= pkts_count) { - kfree_skb(skb); - return ERR_PTR(-EILSEQ); - } - - if (skb->len == (&pkts[i])->hlen) { - u16 dlen; - - switch ((&pkts[i])->lsize) { - case 0: - /* No variable data length */ - dlen = 0; - break; - case 1: - /* Single octet variable length */ - dlen = skb->data[(&pkts[i])->loff]; - hci_skb_expect(skb) += dlen; - - if (skb_tailroom(skb) < dlen) { - kfree_skb(skb); - return ERR_PTR(-EMSGSIZE); - } - break; - case 2: - /* Double octet variable length */ - dlen = get_unaligned_le16(skb->data + - (&pkts[i])->loff); - hci_skb_expect(skb) += dlen; - - if (skb_tailroom(skb) < dlen) { - kfree_skb(skb); - return ERR_PTR(-EMSGSIZE); - } - break; - default: - /* Unsupported variable length */ - kfree_skb(skb); - return ERR_PTR(-EILSEQ); - } - - if (!dlen) { - hu->padding = (skb->len + 1) % alignment; - hu->padding = (alignment - hu->padding) % alignment; - - /* No more data, complete frame */ - (&pkts[i])->recv(hdev, skb); - skb = NULL; - } - } else { - hu->padding = (skb->len + 1) % alignment; - hu->padding = (alignment - hu->padding) % alignment; - - /* Complete frame */ - (&pkts[i])->recv(hdev, skb); - skb = NULL; - } - } - - return skb; + return h4_recv_skb(hu->hdev, &hu->alignment, &hu->padding, skb, buffer, + count, pkts, pkts_count); } EXPORT_SYMBOL_GPL(h4_recv_buf); diff --git a/drivers/bluetooth/hci_uart.h b/drivers/bluetooth/hci_uart.h index 48ac7ca9334e..7fbe8dffab98 100644 --- a/drivers/bluetooth/hci_uart.h +++ b/drivers/bluetooth/hci_uart.h @@ -8,6 +8,8 @@ * Copyright (C) 2004-2005 Marcel Holtmann */ +#include + #ifndef N_HCI #define N_HCI 15 #endif @@ -121,43 +123,6 @@ void hci_uart_set_flow_control(struct hci_uart *hu, bool enable); void hci_uart_set_speeds(struct hci_uart *hu, unsigned int init_speed, unsigned int oper_speed); -struct h4_recv_pkt { - u8 type; /* Packet type */ - u8 hlen; /* Header length */ - u8 loff; /* Data length offset in header */ - u8 lsize; /* Data length field size */ - u16 maxlen; /* Max overall packet length */ - int (*recv)(struct hci_dev *hdev, struct sk_buff *skb); -}; - -#define H4_RECV_ACL \ - .type = HCI_ACLDATA_PKT, \ - .hlen = HCI_ACL_HDR_SIZE, \ - .loff = 2, \ - .lsize = 2, \ - .maxlen = HCI_MAX_FRAME_SIZE \ - -#define H4_RECV_SCO \ - .type = HCI_SCODATA_PKT, \ - .hlen = HCI_SCO_HDR_SIZE, \ - .loff = 2, \ - .lsize = 1, \ - .maxlen = HCI_MAX_SCO_SIZE - -#define H4_RECV_EVENT \ - .type = HCI_EVENT_PKT, \ - .hlen = HCI_EVENT_HDR_SIZE, \ - .loff = 1, \ - .lsize = 1, \ - .maxlen = HCI_MAX_EVENT_SIZE - -#define H4_RECV_ISO \ - .type = HCI_ISODATA_PKT, \ - .hlen = HCI_ISO_HDR_SIZE, \ - .loff = 2, \ - .lsize = 2, \ - .maxlen = HCI_MAX_FRAME_SIZE \ - #ifdef CONFIG_BT_HCIUART_H4 int h4_init(void); int h4_deinit(void); diff --git a/drivers/bluetooth/virtio_bt.c b/drivers/bluetooth/virtio_bt.c index c20d54088c8c..c67f329b6752 100644 --- a/drivers/bluetooth/virtio_bt.c +++ b/drivers/bluetooth/virtio_bt.c @@ -228,7 +228,7 @@ static void virtbt_rx_handle(struct virtio_bluetooth *vbt, struct sk_buff *skb) if (skb->len < min_hdr) { bt_dev_err_ratelimited(vbt->hdev, - "rx pkt_type 0x%02x payload %u < hdr %zu\n", + "rx pkt_type 0x%02x payload %u < hdr %zu", pkt_type, skb->len, min_hdr); kfree_skb(skb); return; @@ -251,7 +251,7 @@ static void virtbt_rx_work(struct work_struct *work) if (!len || len > VIRTBT_RX_BUF_SIZE) { bt_dev_err_ratelimited(vbt->hdev, - "rx reply len %u outside [1, %u]\n", + "rx reply len %u outside [1, %u]", len, VIRTBT_RX_BUF_SIZE); kfree_skb(skb); } else { diff --git a/drivers/bus/arm-cci.c b/drivers/bus/arm-cci.c index 7f2baf057128..435952602d06 100644 --- a/drivers/bus/arm-cci.c +++ b/drivers/bus/arm-cci.c @@ -167,9 +167,12 @@ static int __cci_ace_get_port(struct device_node *dn, int type) cci_portn = of_parse_phandle(dn, "cci-control-port", 0); for (i = 0; i < nb_cci_ports; i++) { ace_match = ports[i].type == type; - if (ace_match && cci_portn == ports[i].dn) + if (ace_match && cci_portn == ports[i].dn) { + of_node_put(cci_portn); return i; + } } + of_node_put(cci_portn); return -ENODEV; } @@ -199,6 +202,7 @@ static void cci_ace_init_ports(void) continue; port = __cci_ace_get_port(cpun, ACE_PORT); + of_node_put(cpun); if (port < 0) continue; diff --git a/drivers/bus/mhi/host/pci_generic.c b/drivers/bus/mhi/host/pci_generic.c index b636e2c23b4d..eda00a2e242c 100644 --- a/drivers/bus/mhi/host/pci_generic.c +++ b/drivers/bus/mhi/host/pci_generic.c @@ -1097,6 +1097,7 @@ struct mhi_pci_device { struct work_struct recovery_work; struct timer_list health_check_timer; unsigned long status; + bool no_m3; bool reset_on_remove; }; @@ -1409,6 +1410,8 @@ static int mhi_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id) mhi_cntrl->mru = info->mru_default; mhi_cntrl->name = info->name; + mhi_pdev->no_m3 = info->no_m3; + if (!pdev->is_virtfn) mhi_pdev->reset_on_remove = info->reset_on_remove; @@ -1497,7 +1500,7 @@ static void mhi_pci_remove(struct pci_dev *pdev) } /* balancing probe put_noidle */ - if (pci_pme_capable(pdev, PCI_D3hot)) + if (pci_pme_capable(pdev, PCI_D3hot) && !mhi_pdev->no_m3) pm_runtime_get_noresume(&pdev->dev); if (mhi_pdev->reset_on_remove) diff --git a/drivers/char/hw_random/cctrng.c b/drivers/char/hw_random/cctrng.c index a6925211c3b5..51290ea345c3 100644 --- a/drivers/char/hw_random/cctrng.c +++ b/drivers/char/hw_random/cctrng.c @@ -86,12 +86,7 @@ static inline u32 cc_ioread(struct cctrng_drvdata *drvdata, u32 reg) static int cc_trng_pm_get(struct device *dev) { - int rc = 0; - - rc = pm_runtime_get_sync(dev); - - /* pm_runtime_get_sync() can return 1 as a valid return code */ - return (rc == 1 ? 0 : rc); + return pm_runtime_resume_and_get(dev); } static void cc_trng_pm_put_suspend(struct device *dev) diff --git a/drivers/char/hw_random/intel-rng.c b/drivers/char/hw_random/intel-rng.c index d24e747203c1..f7f734881c68 100644 --- a/drivers/char/hw_random/intel-rng.c +++ b/drivers/char/hw_random/intel-rng.c @@ -318,8 +318,8 @@ PFX "RNG, try using the 'no_fwh_detect' option.\n"; } intel_rng_hw->mem = ioremap(INTEL_FWH_ADDR, INTEL_FWH_ADDR_LEN); - if (intel_rng_hw->mem == NULL) - return -EBUSY; + if (!intel_rng_hw->mem) + return -ENOMEM; return 0; } @@ -349,6 +349,7 @@ static int __init intel_rng_mod_init(void) intel_rng_hw = kmalloc_obj(*intel_rng_hw); if (!intel_rng_hw) { pci_dev_put(dev); + err = -ENOMEM; goto out; } diff --git a/drivers/char/hw_random/jh7110-trng.c b/drivers/char/hw_random/jh7110-trng.c index aee12caab578..61eb4db7ac01 100644 --- a/drivers/char/hw_random/jh7110-trng.c +++ b/drivers/char/hw_random/jh7110-trng.c @@ -320,9 +320,17 @@ static int starfive_trng_probe(struct platform_device *pdev) return dev_err_probe(&pdev->dev, PTR_ERR(trng->rst), "Error getting hardware reset line\n"); - clk_prepare_enable(trng->hclk); - clk_prepare_enable(trng->ahb); - reset_control_deassert(trng->rst); + ret = clk_prepare_enable(trng->hclk); + if (ret) + return ret; + + ret = clk_prepare_enable(trng->ahb); + if (ret) + goto disable_hclk; + + ret = reset_control_deassert(trng->rst); + if (ret) + goto disable_ahb; trng->rng.name = dev_driver_string(&pdev->dev); trng->rng.init = starfive_trng_init; @@ -342,13 +350,18 @@ static int starfive_trng_probe(struct platform_device *pdev) pm_runtime_disable(&pdev->dev); reset_control_assert(trng->rst); - clk_disable_unprepare(trng->ahb); - clk_disable_unprepare(trng->hclk); - - return dev_err_probe(&pdev->dev, ret, "Failed to register hwrng\n"); + ret = dev_err_probe(&pdev->dev, ret, "Failed to register hwrng\n"); + goto disable_ahb; } return 0; + +disable_ahb: + clk_disable_unprepare(trng->ahb); +disable_hclk: + clk_disable_unprepare(trng->hclk); + + return ret; } static int __maybe_unused starfive_trng_suspend(struct device *dev) @@ -364,11 +377,17 @@ static int __maybe_unused starfive_trng_suspend(struct device *dev) static int __maybe_unused starfive_trng_resume(struct device *dev) { struct starfive_trng *trng = dev_get_drvdata(dev); + int ret; + + ret = clk_prepare_enable(trng->hclk); + if (ret) + return ret; - clk_prepare_enable(trng->hclk); - clk_prepare_enable(trng->ahb); + ret = clk_prepare_enable(trng->ahb); + if (ret) + clk_disable_unprepare(trng->hclk); - return 0; + return ret; } static const struct dev_pm_ops starfive_trng_pm_ops = { diff --git a/drivers/char/scx200_gpio.c b/drivers/char/scx200_gpio.c index 700e6affea6f..3ec17832e9c9 100644 --- a/drivers/char/scx200_gpio.c +++ b/drivers/char/scx200_gpio.c @@ -107,10 +107,16 @@ static int __init scx200_gpio_init(void) } cdev_init(&scx200_gpio_cdev, &scx200_gpio_fileops); - cdev_add(&scx200_gpio_cdev, devid, MAX_PINS); + rc = cdev_add(&scx200_gpio_cdev, devid, MAX_PINS); + if (rc) { + dev_err(&pdev->dev, "cdev_add err: %d\n", rc); + goto undo_chrdev_region; + } return 0; /* succeed */ +undo_chrdev_region: + unregister_chrdev_region(devid, MAX_PINS); undo_platform_device_add: platform_device_del(pdev); undo_malloc: diff --git a/drivers/clk/aspeed/Kconfig b/drivers/clk/aspeed/Kconfig index ef50481c31ff..2f505eb3ca95 100644 --- a/drivers/clk/aspeed/Kconfig +++ b/drivers/clk/aspeed/Kconfig @@ -15,6 +15,7 @@ config COMMON_CLK_ASPEED config COMMON_CLK_AST2700 bool "Clock driver for AST2700 SoC" depends on ARCH_ASPEED || COMPILE_TEST + select AUXILIARY_BUS help This driver provides support for clock on AST2700 SoC. The driver is responsible for managing the various clocks required diff --git a/drivers/clk/bcm/clk-raspberrypi.c b/drivers/clk/bcm/clk-raspberrypi.c index f1a99de6de4f..9882f243d681 100644 --- a/drivers/clk/bcm/clk-raspberrypi.c +++ b/drivers/clk/bcm/clk-raspberrypi.c @@ -553,6 +553,8 @@ static int raspberrypi_clk_probe(struct platform_device *pdev) rpi->cpufreq = platform_device_register_data(dev, "raspberrypi-cpufreq", -1, NULL, 0); + if (IS_ERR(rpi->cpufreq)) + return PTR_ERR(rpi->cpufreq); return 0; } diff --git a/drivers/clk/clk-cdce925.c b/drivers/clk/clk-cdce925.c index 30d0493c7718..231e7726fdb0 100644 --- a/drivers/clk/clk-cdce925.c +++ b/drivers/clk/clk-cdce925.c @@ -625,7 +625,12 @@ static int cdce925_probe(struct i2c_client *client) int i; int err; struct device_node *np_output; - char child_name[6]; + /* + * The PLL number isn't a compile time constant so GCC can't infer + * the number. Make the stack buffer large enough to hold any int + * so Wformat-truncation does not complain. + */ + char child_name[15]; struct regmap_config config = { .name = "configuration0", .reg_bits = 8, @@ -697,7 +702,7 @@ static int cdce925_probe(struct i2c_client *client) dev_err(&client->dev, "Failed register PLL %d\n", i); goto error; } - sprintf(child_name, "PLL%d", i+1); + snprintf(child_name, sizeof(child_name), "PLL%d", i + 1); np_output = of_get_child_by_name(node, child_name); if (!np_output) continue; diff --git a/drivers/clk/clk-lmk04832.c b/drivers/clk/clk-lmk04832.c index f9a0684d2628..81801ccb2675 100644 --- a/drivers/clk/clk-lmk04832.c +++ b/drivers/clk/clk-lmk04832.c @@ -1410,6 +1410,9 @@ static int lmk04832_probe(struct spi_device *spi) lmk->reset_gpio = devm_gpiod_get_optional(&spi->dev, "reset", GPIOD_OUT_LOW); + if (IS_ERR(lmk->reset_gpio)) + return dev_err_probe(lmk->dev, PTR_ERR(lmk->reset_gpio), + "failed to get reset GPIO\n"); lmk->dclk = devm_kcalloc(lmk->dev, info->num_channels >> 1, sizeof(struct lmk_dclk), GFP_KERNEL); diff --git a/drivers/clk/clk-milbeaut.c b/drivers/clk/clk-milbeaut.c index 4265bc442dfd..b3bf569ef747 100644 --- a/drivers/clk/clk-milbeaut.c +++ b/drivers/clk/clk-milbeaut.c @@ -410,8 +410,8 @@ static int m10v_clk_divider_set_rate(struct clk_hw *hw, unsigned long rate, unsigned long parent_rate) { struct m10v_clk_divider *divider = to_m10v_div(hw); - int value; unsigned long flags = 0; + int value, ret = 0; u32 val; u32 write_en = BIT(divider->width - 1); @@ -433,8 +433,10 @@ static int m10v_clk_divider_set_rate(struct clk_hw *hw, unsigned long rate, if (divider->write_valid_reg) { writel(M10V_DCHREQ, divider->write_valid_reg); - if (readl_poll_timeout(divider->write_valid_reg, val, - !val, M10V_UPOLL_RATE, M10V_UTIMEOUT)) + ret = readl_poll_timeout_atomic(divider->write_valid_reg, val, + !val, M10V_UPOLL_RATE, + M10V_UTIMEOUT); + if (ret) pr_err("%s:%s couldn't stabilize\n", __func__, clk_hw_get_name(hw)); } @@ -444,7 +446,7 @@ static int m10v_clk_divider_set_rate(struct clk_hw *hw, unsigned long rate, else __release(divider->lock); - return 0; + return ret; } static const struct clk_ops m10v_clk_divider_ops = { diff --git a/drivers/clk/clk-renesas-pcie.c b/drivers/clk/clk-renesas-pcie.c index 564550c80389..f3376c29007a 100644 --- a/drivers/clk/clk-renesas-pcie.c +++ b/drivers/clk/clk-renesas-pcie.c @@ -276,6 +276,11 @@ rs9_of_clk_get(struct of_phandle_args *clkspec, void *data) struct rs9_driver_data *rs9 = data; unsigned int idx = clkspec->args[0]; + if (idx >= rs9->chip_info->num_clks) { + pr_err("%s: Invalid clock index %u\n", __func__, idx); + return ERR_PTR(-EINVAL); + } + return rs9->clk_dif[idx]; } diff --git a/drivers/clk/clk-s2mps11.c b/drivers/clk/clk-s2mps11.c index fa5ac8f673f6..94969d97d6e9 100644 --- a/drivers/clk/clk-s2mps11.c +++ b/drivers/clk/clk-s2mps11.c @@ -192,8 +192,10 @@ static int s2mps11_clk_probe(struct platform_device *pdev) clk_data->hws[i] = &s2mps11_clks[i].hw; } - of_clk_add_hw_provider(s2mps11_clks->clk_np, of_clk_hw_onecell_get, - clk_data); + ret = of_clk_add_hw_provider(s2mps11_clks->clk_np, + of_clk_hw_onecell_get, clk_data); + if (ret) + goto err_reg; platform_set_drvdata(pdev, s2mps11_clks); @@ -201,8 +203,10 @@ static int s2mps11_clk_probe(struct platform_device *pdev) err_reg: of_node_put(s2mps11_clks[0].clk_np); - while (--i >= 0) - clkdev_drop(s2mps11_clks[i].lookup); + while (--i >= 0) { + if (s2mps11_clks[i].lookup) + clkdev_drop(s2mps11_clks[i].lookup); + } return ret; } diff --git a/drivers/clk/clk-si521xx.c b/drivers/clk/clk-si521xx.c index e3fb8df712ef..406cd154fba1 100644 --- a/drivers/clk/clk-si521xx.c +++ b/drivers/clk/clk-si521xx.c @@ -374,7 +374,7 @@ MODULE_DEVICE_TABLE(i2c, si521xx_id); static const struct of_device_id clk_si521xx_of_match[] = { { .compatible = "skyworks,si52144", .data = (void *)SI521XX_OE_MAP(0x5, 0xc0) }, { .compatible = "skyworks,si52146", .data = (void *)SI521XX_OE_MAP(0x15, 0xe0) }, - { .compatible = "skyworks,si52147", .data = (void *)SI521XX_OE_MAP(0x15, 0xf8) }, + { .compatible = "skyworks,si52147", .data = (void *)SI521XX_OE_MAP(0x17, 0xf8) }, { } }; MODULE_DEVICE_TABLE(of, clk_si521xx_of_match); diff --git a/drivers/clk/clk-si5351.c b/drivers/clk/clk-si5351.c index 20b0c3c48b86..70daba62305c 100644 --- a/drivers/clk/clk-si5351.c +++ b/drivers/clk/clk-si5351.c @@ -907,7 +907,7 @@ static int _si5351_clkout_set_disable_state( return 0; } -static void _si5351_clkout_reset_pll(struct si5351_driver_data *drvdata, int num) +static int _si5351_clkout_reset_pll(struct si5351_driver_data *drvdata, int num) { u8 val = si5351_reg_read(drvdata, SI5351_CLK0_CTRL + num); u8 mask = val & SI5351_CLK_PLL_SELECT ? SI5351_PLL_RESET_B : @@ -918,7 +918,7 @@ static void _si5351_clkout_reset_pll(struct si5351_driver_data *drvdata, int num switch (val & SI5351_CLK_INPUT_MASK) { case SI5351_CLK_INPUT_XTAL: case SI5351_CLK_INPUT_CLKIN: - return; /* pll not used, no need to reset */ + return 0; /* pll not used, no need to reset */ } si5351_reg_write(drvdata, SI5351_PLL_RESET, mask); @@ -931,6 +931,8 @@ static void _si5351_clkout_reset_pll(struct si5351_driver_data *drvdata, int num dev_dbg(&drvdata->client->dev, "%s - %s: pll = %d\n", __func__, clk_hw_get_name(&drvdata->clkout[num].hw), (val & SI5351_CLK_PLL_SELECT) ? 1 : 0); + + return err; } static int si5351_clkout_prepare(struct clk_hw *hw) @@ -947,8 +949,18 @@ static int si5351_clkout_prepare(struct clk_hw *hw) * Do a pll soft reset on the parent pll -- needed to get a * deterministic phase relationship between the output clocks. */ - if (pdata->clkout[hwdata->num].pll_reset) - _si5351_clkout_reset_pll(hwdata->drvdata, hwdata->num); + if (pdata->clkout[hwdata->num].pll_reset) { + int ret; + + ret = _si5351_clkout_reset_pll(hwdata->drvdata, hwdata->num); + if (ret) { + si5351_set_bits(hwdata->drvdata, + SI5351_CLK0_CTRL + hwdata->num, + SI5351_CLK_POWERDOWN, + SI5351_CLK_POWERDOWN); + return ret; + } + } si5351_set_bits(hwdata->drvdata, SI5351_OUTPUT_ENABLE_CTRL, (1 << hwdata->num), 0); diff --git a/drivers/clk/clk.c b/drivers/clk/clk.c index fef87167a60b..d045e8d3222b 100644 --- a/drivers/clk/clk.c +++ b/drivers/clk/clk.c @@ -166,6 +166,7 @@ struct clk { unsigned long max_rate; unsigned int exclusive_count; struct hlist_node clks_node; + bool pinning; }; /*** runtime pm ***/ @@ -2851,6 +2852,20 @@ int clk_hw_set_spread_spectrum(struct clk_hw *hw, const struct clk_spread_spectr if (!hw) return 0; + switch (ss_conf->method) { + case CLK_SPREAD_NO: + break; + case CLK_SPREAD_CENTER: + case CLK_SPREAD_UP: + case CLK_SPREAD_DOWN: + if (!ss_conf->modfreq_hz || !ss_conf->spread_bp || + ss_conf->spread_bp > 10000) + return -EINVAL; + break; + default: + return -EINVAL; + } + core = hw->core; clk_prepare_lock(); @@ -4237,13 +4252,15 @@ static void free_clk(struct clk *clk) * @hw: clk_hw associated with the clk being consumed * @dev_id: string describing device name * @con_id: connection ID string on device + * @owner: reference to the module creating the clock * * This is the main function used to create a clk pointer for use by clk * consumers. It connects a consumer to the clk_core and clk_hw structures * used by the framework and clk provider respectively. */ struct clk *clk_hw_create_clk(struct device *dev, struct clk_hw *hw, - const char *dev_id, const char *con_id) + const char *dev_id, const char *con_id, + struct module *owner) { struct clk *clk; struct clk_core *core; @@ -4258,7 +4275,13 @@ struct clk *clk_hw_create_clk(struct device *dev, struct clk_hw *hw, return clk; clk->dev = dev; - if (!try_module_get(core->owner)) { + /* + * Pin the provider module only when the consumer lives in a different + * module. A provider getting a clk from its own clk_hw would otherwise + * pin itself and could never be unloaded. + */ + clk->pinning = owner != core->owner; + if (clk->pinning && !try_module_get(core->owner)) { free_clk(clk); return ERR_PTR(-ENOENT); } @@ -4269,24 +4292,19 @@ struct clk *clk_hw_create_clk(struct device *dev, struct clk_hw *hw, return clk; } -/** - * clk_hw_get_clk - get clk consumer given an clk_hw - * @hw: clk_hw associated with the clk being consumed - * @con_id: connection ID string on device - * - * Returns: new clk consumer - * This is the function to be used by providers which need - * to get a consumer clk and act on the clock element - * Calls to this function must be balanced with calls clk_put() +/* + * Internal helper backing the clk_hw_get_clk() macro, which passes the caller's + * module via THIS_MODULE. */ -struct clk *clk_hw_get_clk(struct clk_hw *hw, const char *con_id) +struct clk *__clk_hw_get_clk(struct clk_hw *hw, const char *con_id, + struct module *owner) { struct device *dev = hw->core->dev; const char *name = dev ? dev_name(dev) : NULL; - return clk_hw_create_clk(dev, hw, name, con_id); + return clk_hw_create_clk(dev, hw, name, con_id, owner); } -EXPORT_SYMBOL(clk_hw_get_clk); +EXPORT_SYMBOL(__clk_hw_get_clk); static int clk_cpy_name(const char **dst_p, const char *src, bool must_exist) { @@ -4450,8 +4468,9 @@ __clk_register(struct device *dev, struct device_node *np, struct clk_hw *hw) INIT_HLIST_HEAD(&core->clks); /* - * Don't call clk_hw_create_clk() here because that would pin the - * provider module to itself and prevent it from ever being removed. + * Don't call clk_hw_create_clk() here because it would systematically + * add a consumer to the hw clock and all clocks would appear to have + * consumer in the clock summary. */ hw->clk = alloc_clk(core, NULL, NULL); if (IS_ERR(hw->clk)) { @@ -4808,7 +4827,7 @@ struct clk *devm_clk_hw_get_clk(struct device *dev, struct clk_hw *hw, if (!clkp) return ERR_PTR(-ENOMEM); - clk = clk_hw_get_clk(hw, con_id); + clk = __clk_hw_get_clk(hw, con_id, dev->driver->owner); if (!IS_ERR(clk)) { *clkp = clk; devres_add(dev, clkp); @@ -4855,7 +4874,8 @@ void __clk_put(struct clk *clk) owner = clk->core->owner; kref_put(&clk->core->ref, __clk_release); - module_put(owner); + if (clk->pinning) + module_put(owner); free_clk(clk); } @@ -5314,6 +5334,8 @@ static int of_parse_clkspec(const struct device_node *np, int index, * has a "clock-ranges" property, then we can try one of its * clocks. */ + if (of_property_present(np, "clocks")) + break; np = np->parent; if (np && !of_property_present(np, "clock-ranges")) break; @@ -5376,7 +5398,7 @@ struct clk *of_clk_get_from_provider(struct of_phandle_args *clkspec) { struct clk_hw *hw = of_clk_get_hw_from_clkspec(clkspec); - return clk_hw_create_clk(NULL, hw, NULL, __func__); + return clk_hw_create_clk(NULL, hw, NULL, __func__, NULL); } EXPORT_SYMBOL_GPL(of_clk_get_from_provider); @@ -5403,7 +5425,7 @@ static struct clk *__of_clk_get(struct device_node *np, { struct clk_hw *hw = of_clk_get_hw(np, index, con_id); - return clk_hw_create_clk(NULL, hw, dev_id, con_id); + return clk_hw_create_clk(NULL, hw, dev_id, con_id, NULL); } struct clk *of_clk_get(struct device_node *np, int index) @@ -5458,8 +5480,7 @@ const char *of_clk_get_parent_name(const struct device_node *np, int index) int count; struct clk *clk; - rc = of_parse_phandle_with_args(np, "clocks", "#clock-cells", index, - &clkspec); + rc = of_parse_clkspec(np, index, NULL, &clkspec); if (rc) return NULL; diff --git a/drivers/clk/clk.h b/drivers/clk/clk.h index 2d801900cad5..5009380863a9 100644 --- a/drivers/clk/clk.h +++ b/drivers/clk/clk.h @@ -23,13 +23,14 @@ struct clk_hw *clk_find_hw(const char *dev_id, const char *con_id); #ifdef CONFIG_COMMON_CLK struct clk *clk_hw_create_clk(struct device *dev, struct clk_hw *hw, - const char *dev_id, const char *con_id); + const char *dev_id, const char *con_id, + struct module *owner); void __clk_put(struct clk *clk); #else /* All these casts to avoid ifdefs in clkdev... */ static inline struct clk * clk_hw_create_clk(struct device *dev, struct clk_hw *hw, const char *dev_id, - const char *con_id) + const char *con_id, struct module *owner) { return (struct clk *)hw; } diff --git a/drivers/clk/clk_test.c b/drivers/clk/clk_test.c index 1c5c8b7c1f3c..21e62d68f87f 100644 --- a/drivers/clk/clk_test.c +++ b/drivers/clk/clk_test.c @@ -3526,7 +3526,7 @@ static const struct clk_assigned_rates_test_param clk_assigned_sscs_skips_test_p */ .desc = "provider missing assigned-clocks", TEST_PARAM_OVERLAY(kunit_clk_assigned_sscs_without), - .sscs = {50000, 60000, 3}, + .sscs = {50000, 600, 3}, }, { /* @@ -3535,7 +3535,7 @@ static const struct clk_assigned_rates_test_param clk_assigned_sscs_skips_test_p */ .desc = "consumer missing assigned-clocks", TEST_PARAM_OVERLAY(kunit_clk_assigned_sscs_without_consumer), - .sscs = {50000, 60000, 3}, + .sscs = {50000, 600, 3}, .consumer_test = true, }, { @@ -3545,7 +3545,7 @@ static const struct clk_assigned_rates_test_param clk_assigned_sscs_skips_test_p */ .desc = "provider assigned-clock-sscs of zero", TEST_PARAM_OVERLAY(kunit_clk_assigned_sscs_zero), - .sscs = {50000, 60000, 3}, + .sscs = {50000, 600, 3}, }, { /* @@ -3554,7 +3554,7 @@ static const struct clk_assigned_rates_test_param clk_assigned_sscs_skips_test_p */ .desc = "consumer assigned-clock-sscs of zero", TEST_PARAM_OVERLAY(kunit_clk_assigned_sscs_zero_consumer), - .sscs = {50000, 60000, 3}, + .sscs = {50000, 600, 3}, .consumer_test = true, }, { @@ -3564,7 +3564,7 @@ static const struct clk_assigned_rates_test_param clk_assigned_sscs_skips_test_p */ .desc = "provider assigned-clocks null phandle", TEST_PARAM_OVERLAY(kunit_clk_assigned_sscs_null), - .sscs = {50000, 60000, 3}, + .sscs = {50000, 600, 3}, }, { /* @@ -3573,7 +3573,7 @@ static const struct clk_assigned_rates_test_param clk_assigned_sscs_skips_test_p */ .desc = "consumer assigned-clocks null phandle", TEST_PARAM_OVERLAY(kunit_clk_assigned_sscs_null_consumer), - .sscs = {50000, 60000, 3}, + .sscs = {50000, 600, 3}, .consumer_test = true, }, }; diff --git a/drivers/clk/clkdev.c b/drivers/clk/clkdev.c index abaa0f9e0083..919fc680ae4d 100644 --- a/drivers/clk/clkdev.c +++ b/drivers/clk/clkdev.c @@ -88,7 +88,7 @@ static struct clk *__clk_get_sys(struct device *dev, const char *dev_id, { struct clk_hw *hw = clk_find_hw(dev_id, con_id); - return clk_hw_create_clk(dev, hw, dev_id, con_id); + return clk_hw_create_clk(dev, hw, dev_id, con_id, NULL); } struct clk *clk_get_sys(const char *dev_id, const char *con_id) @@ -105,7 +105,7 @@ struct clk *clk_get(struct device *dev, const char *con_id) if (dev && dev->of_node) { hw = of_clk_get_hw(dev->of_node, 0, con_id); if (!IS_ERR(hw) || PTR_ERR(hw) == -EPROBE_DEFER) - return clk_hw_create_clk(dev, hw, dev_id, con_id); + return clk_hw_create_clk(dev, hw, dev_id, con_id, NULL); } return __clk_get_sys(dev, dev_id, con_id); diff --git a/drivers/clk/imx/clk-composite-93.c b/drivers/clk/imx/clk-composite-93.c index ef20ceb2d255..953f67d13978 100644 --- a/drivers/clk/imx/clk-composite-93.c +++ b/drivers/clk/imx/clk-composite-93.c @@ -43,11 +43,12 @@ static int imx93_clk_composite_wait_ready(struct clk_hw *hw, void __iomem *reg) return ret; } -static void imx93_clk_composite_gate_endisable(struct clk_hw *hw, int enable) +static int imx93_clk_composite_gate_endisable(struct clk_hw *hw, int enable) { struct clk_gate *gate = to_clk_gate(hw); unsigned long flags; u32 reg; + int ret; if (gate->lock) spin_lock_irqsave(gate->lock, flags); @@ -61,17 +62,17 @@ static void imx93_clk_composite_gate_endisable(struct clk_hw *hw, int enable) writel(reg, gate->reg); - imx93_clk_composite_wait_ready(hw, gate->reg); + ret = imx93_clk_composite_wait_ready(hw, gate->reg); if (gate->lock) spin_unlock_irqrestore(gate->lock, flags); + + return ret; } static int imx93_clk_composite_gate_enable(struct clk_hw *hw) { - imx93_clk_composite_gate_endisable(hw, 1); - - return 0; + return imx93_clk_composite_gate_endisable(hw, 1); } static void imx93_clk_composite_gate_disable(struct clk_hw *hw) diff --git a/drivers/clk/kunit_clk_assigned_rates.h b/drivers/clk/kunit_clk_assigned_rates.h index d7ae5ec2d25b..c5d9f004ee81 100644 --- a/drivers/clk/kunit_clk_assigned_rates.h +++ b/drivers/clk/kunit_clk_assigned_rates.h @@ -9,10 +9,10 @@ #define ASSIGNED_RATES_1_RATE 9700000 #define ASSIGNED_SSCS_0_MODFREQ 10000 -#define ASSIGNED_SSCS_0_SPREAD 30000 +#define ASSIGNED_SSCS_0_SPREAD 300 #define ASSIGNED_SSCS_0_METHOD CLK_SSC_CENTER_SPREAD #define ASSIGNED_SSCS_1_MODFREQ 20000 -#define ASSIGNED_SSCS_1_SPREAD 40000 +#define ASSIGNED_SSCS_1_SPREAD 400 #define ASSIGNED_SSCS_1_METHOD CLK_SSC_UP_SPREAD #endif diff --git a/drivers/clk/mediatek/reset.h b/drivers/clk/mediatek/reset.h index 562ffd290a22..b09cdcab0c4b 100644 --- a/drivers/clk/mediatek/reset.h +++ b/drivers/clk/mediatek/reset.h @@ -60,11 +60,11 @@ struct mtk_clk_rst_data { }; /** - * mtk_register_reset_controller - Register mediatek clock reset controller with device - * @np: Pointer to device. + * mtk_register_reset_controller_with_dev - Register a MediaTek reset controller + * @dev: Device used to manage the reset controller resources. * @desc: Constant pointer to description of clock reset. * - * Return: 0 on success and errorno otherwise. + * Return: 0 on success, negative errno otherwise. */ int mtk_register_reset_controller_with_dev(struct device *dev, const struct mtk_clk_rst_desc *desc); diff --git a/drivers/clk/meson/t7-peripherals.c b/drivers/clk/meson/t7-peripherals.c index 214db7850d86..55d09e78593b 100644 --- a/drivers/clk/meson/t7-peripherals.c +++ b/drivers/clk/meson/t7-peripherals.c @@ -945,11 +945,16 @@ static T7_SYS_PCLK(sys_aucpu, SYS_CLK_EN0_REG0, 14, 0); static T7_SYS_PCLK(sys_cec, SYS_CLK_EN0_REG0, 16, 0); static T7_SYS_PCLK(sys_gdc, SYS_CLK_EN0_REG0, 17, 0); static T7_SYS_PCLK(sys_deswarp, SYS_CLK_EN0_REG0, 18, 0); -static T7_SYS_PCLK(sys_ampipe_nand, SYS_CLK_EN0_REG0, 19, 0); +/* + * NOTE: sys_ampipe_nand and sys_am2axi0..2 provide the clock to the AXI bus + * used for DMA between the peripherals and the DRAM. After the clocks are + * disabled, a device that starts a transfer cannot complete it. + */ +static T7_SYS_PCLK(sys_ampipe_nand, SYS_CLK_EN0_REG0, 19, CLK_IS_CRITICAL); static T7_SYS_PCLK(sys_ampipe_eth, SYS_CLK_EN0_REG0, 20, 0); -static T7_SYS_PCLK(sys_am2axi0, SYS_CLK_EN0_REG0, 21, 0); -static T7_SYS_PCLK(sys_am2axi1, SYS_CLK_EN0_REG0, 22, 0); -static T7_SYS_PCLK(sys_am2axi2, SYS_CLK_EN0_REG0, 23, 0); +static T7_SYS_PCLK(sys_am2axi0, SYS_CLK_EN0_REG0, 21, CLK_IS_CRITICAL); +static T7_SYS_PCLK(sys_am2axi1, SYS_CLK_EN0_REG0, 22, CLK_IS_CRITICAL); +static T7_SYS_PCLK(sys_am2axi2, SYS_CLK_EN0_REG0, 23, CLK_IS_CRITICAL); static T7_SYS_PCLK(sys_sd_emmc_a, SYS_CLK_EN0_REG0, 24, 0); static T7_SYS_PCLK(sys_sd_emmc_b, SYS_CLK_EN0_REG0, 25, 0); static T7_SYS_PCLK(sys_sd_emmc_c, SYS_CLK_EN0_REG0, 26, 0); diff --git a/drivers/clk/qcom/Kconfig b/drivers/clk/qcom/Kconfig index d1fc9bf87126..283cca5aca0e 100644 --- a/drivers/clk/qcom/Kconfig +++ b/drivers/clk/qcom/Kconfig @@ -73,7 +73,6 @@ config CLK_GLYMUR_DISPCC config CLK_GLYMUR_EVACC tristate "Glymur EVA Clock Controller" depends on ARM64 || COMPILE_TEST - default m if ARCH_QCOM select CLK_GLYMUR_GCC default m if ARCH_QCOM help @@ -96,6 +95,7 @@ config CLK_GLYMUR_GPUCC tristate "Glymur Graphics Clock Controller" depends on ARM64 || COMPILE_TEST select CLK_GLYMUR_GCC + default m if ARCH_QCOM help Support for the graphics clock controller on Glymur devices. Say Y if you want to support graphics controller devices and diff --git a/drivers/clk/qcom/cambistmclkcc-kaanapali.c b/drivers/clk/qcom/cambistmclkcc-kaanapali.c index c96e9196d908..b5bafc1e7d42 100644 --- a/drivers/clk/qcom/cambistmclkcc-kaanapali.c +++ b/drivers/clk/qcom/cambistmclkcc-kaanapali.c @@ -394,11 +394,18 @@ static const struct regmap_config cam_bist_mclk_cc_kaanapali_regmap_config = { .fast_io = true, }; +static void cam_bist_mclk_cc_kaanapali_regs_configure(struct device *dev, struct regmap *regmap) +{ + regmap_write(regmap, 0x18, 0); /* CAM_BIST_MCLK_CC_PLL0_USER_CTL_U */ + regmap_write(regmap, 0x28, 0); /* CAM_BIST_MCLK_CC_PLL0_CONFIG_CTL_U2 */ +} + static const struct qcom_cc_driver_data cam_bist_mclk_cc_kaanapali_driver_data = { .alpha_plls = cam_bist_mclk_cc_kaanapali_plls, .num_alpha_plls = ARRAY_SIZE(cam_bist_mclk_cc_kaanapali_plls), .clk_cbcrs = cam_bist_mclk_cc_kaanapali_critical_cbcrs, .num_clk_cbcrs = ARRAY_SIZE(cam_bist_mclk_cc_kaanapali_critical_cbcrs), + .clk_regs_configure = cam_bist_mclk_cc_kaanapali_regs_configure, }; static const struct qcom_cc_desc cam_bist_mclk_cc_kaanapali_desc = { diff --git a/drivers/clk/qcom/cambistmclkcc-sm8750.c b/drivers/clk/qcom/cambistmclkcc-sm8750.c index 69abb756c04f..45788ddb9dcc 100644 --- a/drivers/clk/qcom/cambistmclkcc-sm8750.c +++ b/drivers/clk/qcom/cambistmclkcc-sm8750.c @@ -413,11 +413,18 @@ static const struct regmap_config cam_bist_mclk_cc_sm8750_regmap_config = { .fast_io = true, }; +static void cam_bist_mclk_cc_sm8750_regs_configure(struct device *dev, struct regmap *regmap) +{ + regmap_write(regmap, 0x18, 0); /* CAM_BIST_MCLK_CC_PLL0_USER_CTL_U */ + regmap_write(regmap, 0x28, 0); /* CAM_BIST_MCLK_CC_PLL0_CONFIG_CTL_U2 */ +} + static const struct qcom_cc_driver_data cam_bist_mclk_cc_sm8750_driver_data = { .alpha_plls = cam_bist_mclk_cc_sm8750_plls, .num_alpha_plls = ARRAY_SIZE(cam_bist_mclk_cc_sm8750_plls), .clk_cbcrs = cam_bist_mclk_cc_sm8750_critical_cbcrs, .num_clk_cbcrs = ARRAY_SIZE(cam_bist_mclk_cc_sm8750_critical_cbcrs), + .clk_regs_configure = cam_bist_mclk_cc_sm8750_regs_configure, }; static const struct qcom_cc_desc cam_bist_mclk_cc_sm8750_desc = { diff --git a/drivers/clk/qcom/camcc-glymur.c b/drivers/clk/qcom/camcc-glymur.c index 81c1e102b110..6d022bbd2ce2 100644 --- a/drivers/clk/qcom/camcc-glymur.c +++ b/drivers/clk/qcom/camcc-glymur.c @@ -2235,11 +2235,18 @@ static const struct regmap_config cam_cc_glymur_regmap_config = { .fast_io = true, }; +static void cam_cc_glymur_regs_configure(struct device *dev, struct regmap *regmap) +{ + regmap_write(regmap, 0x2018, 0); /* CAM_CC_PLL2_PLL_USER_CTL_U */ + regmap_write(regmap, 0x2028, 0); /* CAM_CC_PLL2_PLL_CONFIG_CTL_U2 */ +} + static const struct qcom_cc_driver_data cam_cc_glymur_driver_data = { .alpha_plls = cam_cc_glymur_plls, .num_alpha_plls = ARRAY_SIZE(cam_cc_glymur_plls), .clk_cbcrs = cam_cc_glymur_critical_cbcrs, .num_clk_cbcrs = ARRAY_SIZE(cam_cc_glymur_critical_cbcrs), + .clk_regs_configure = cam_cc_glymur_regs_configure, }; static const struct qcom_cc_desc cam_cc_glymur_desc = { diff --git a/drivers/clk/qcom/clk-alpha-pll.c b/drivers/clk/qcom/clk-alpha-pll.c index f8313f9d0e30..60173b076cc5 100644 --- a/drivers/clk/qcom/clk-alpha-pll.c +++ b/drivers/clk/qcom/clk-alpha-pll.c @@ -2373,6 +2373,15 @@ void clk_lucid_ole_pll_configure(struct clk_alpha_pll *pll, struct regmap *regma { u32 lval = config->l; + /* + * If the bootloader left the PLL enabled it's likely that there are + * RCGs that will lock up if we disable the PLL below. + */ + if (trion_pll_is_enabled(pll, regmap)) { + pr_debug("Lucid Ole PLL is already enabled, skipping configuration\n"); + return; + } + lval |= TRION_PLL_CAL_VAL << LUCID_EVO_PLL_CAL_L_VAL_SHIFT; lval |= TRION_PLL_CAL_VAL << LUCID_OLE_PLL_RINGOSC_CAL_L_VAL_SHIFT; clk_alpha_pll_write_config(regmap, PLL_L_VAL(pll), lval); diff --git a/drivers/clk/qcom/clk-rcg2.c b/drivers/clk/qcom/clk-rcg2.c index d7914e59129f..c44c51d860e1 100644 --- a/drivers/clk/qcom/clk-rcg2.c +++ b/drivers/clk/qcom/clk-rcg2.c @@ -1332,7 +1332,10 @@ static int clk_rcg2_set_force_enable(struct clk_hw *hw) /* wait for RCG to turn ON */ for (count = 500; count > 0; count--) { - if (clk_rcg2_is_enabled(hw)) + ret = clk_rcg2_is_enabled(hw); + if (ret < 0) + return ret; + if (ret) return 0; udelay(1); @@ -1361,8 +1364,10 @@ clk_rcg2_shared_force_enable_clear(struct clk_hw *hw, const struct freq_tbl *f) return ret; ret = clk_rcg2_configure(rcg, f); - if (ret) + if (ret) { + clk_rcg2_clear_force_enable(hw); return ret; + } return clk_rcg2_clear_force_enable(hw); } @@ -1555,7 +1560,20 @@ const struct clk_ops clk_rcg2_shared_ops = { }; EXPORT_SYMBOL_GPL(clk_rcg2_shared_ops); +static int clk_rcg2_shared_no_init_park(struct clk_hw *hw) +{ + struct clk_rcg2 *rcg = to_clk_rcg2(hw); + + /* + * Read the config register so that the parent is properly mapped at + * registration time. + */ + return regmap_read(rcg->clkr.regmap, rcg->cmd_rcgr + CFG_REG, + &rcg->parked_cfg); +} + const struct clk_ops clk_rcg2_shared_floor_ops = { + .init = clk_rcg2_shared_no_init_park, .enable = clk_rcg2_shared_enable, .disable = clk_rcg2_shared_disable, .get_parent = clk_rcg2_shared_get_parent, @@ -1567,19 +1585,6 @@ const struct clk_ops clk_rcg2_shared_floor_ops = { }; EXPORT_SYMBOL_GPL(clk_rcg2_shared_floor_ops); -static int clk_rcg2_shared_no_init_park(struct clk_hw *hw) -{ - struct clk_rcg2 *rcg = to_clk_rcg2(hw); - - /* - * Read the config register so that the parent is properly mapped at - * registration time. - */ - regmap_read(rcg->clkr.regmap, rcg->cmd_rcgr + CFG_REG, &rcg->parked_cfg); - - return 0; -} - /* * Like clk_rcg2_shared_ops but skip the init so that the clk frequency is left * unchanged at registration time. diff --git a/drivers/clk/qcom/clk-rpmh.c b/drivers/clk/qcom/clk-rpmh.c index a224a94ae273..88e872e58f64 100644 --- a/drivers/clk/qcom/clk-rpmh.c +++ b/drivers/clk/qcom/clk-rpmh.c @@ -393,6 +393,7 @@ DEFINE_CLK_RPMH_VRM(clk2, _a1_e0, "C2A_E0", 1); DEFINE_CLK_RPMH_VRM(clk3, _a1_e0, "C3A_E0", 1); DEFINE_CLK_RPMH_VRM(clk4, _a1_e0, "C4A_E0", 1); DEFINE_CLK_RPMH_VRM(clk5, _a1_e0, "C5A_E0", 1); +DEFINE_CLK_RPMH_VRM(clk7, _a1_e0, "C7A_E0", 1); DEFINE_CLK_RPMH_VRM(clk8, _a1_e0, "C8A_E0", 1); DEFINE_CLK_RPMH_VRM(clk3, _a2_e0, "C3A_E0", 2); @@ -902,6 +903,10 @@ static struct clk_hw *glymur_rpmh_clocks[] = { [RPMH_RF_CLK4_A] = &clk_rpmh_clk4_a1_e0_ao.hw, [RPMH_RF_CLK5] = &clk_rpmh_clk5_a1_e0.hw, [RPMH_RF_CLK5_A] = &clk_rpmh_clk5_a1_e0_ao.hw, + [RPMH_LN_BB_CLK2] = &clk_rpmh_clk7_a1_e0.hw, + [RPMH_LN_BB_CLK2_A] = &clk_rpmh_clk7_a1_e0_ao.hw, + [RPMH_LN_BB_CLK3] = &clk_rpmh_clk8_a1_e0.hw, + [RPMH_LN_BB_CLK3_A] = &clk_rpmh_clk8_a1_e0_ao.hw, }; static const struct clk_rpmh_desc clk_rpmh_glymur = { diff --git a/drivers/clk/qcom/dispcc-sm8450.c b/drivers/clk/qcom/dispcc-sm8450.c index 3af120e54cdd..c7e04bd315d5 100644 --- a/drivers/clk/qcom/dispcc-sm8450.c +++ b/drivers/clk/qcom/dispcc-sm8450.c @@ -613,7 +613,7 @@ static struct clk_rcg2 disp_cc_mdss_mdp_clk_src = { .parent_data = disp_cc_parent_data_5, .num_parents = ARRAY_SIZE(disp_cc_parent_data_5), .flags = CLK_SET_RATE_PARENT, - .ops = &clk_rcg2_shared_ops, + .ops = &clk_rcg2_shared_no_init_park_ops, }, }; diff --git a/drivers/clk/qcom/gcc-eliza.c b/drivers/clk/qcom/gcc-eliza.c index fe18942a59ac..e26e6e6e52f1 100644 --- a/drivers/clk/qcom/gcc-eliza.c +++ b/drivers/clk/qcom/gcc-eliza.c @@ -3068,6 +3068,7 @@ static const struct qcom_cc_desc gcc_eliza_desc = { .num_resets = ARRAY_SIZE(gcc_eliza_resets), .gdscs = gcc_eliza_gdscs, .num_gdscs = ARRAY_SIZE(gcc_eliza_gdscs), + .use_rpm = true, .driver_data = &gcc_eliza_driver_data, }; diff --git a/drivers/clk/qcom/gcc-glymur.c b/drivers/clk/qcom/gcc-glymur.c index 2ee4820b6fdf..a47a2c6b961b 100644 --- a/drivers/clk/qcom/gcc-glymur.c +++ b/drivers/clk/qcom/gcc-glymur.c @@ -481,36 +481,6 @@ static const struct clk_parent_data gcc_parent_data_17[] = { { .hw = &gcc_gpll0_out_even.clkr.hw }, }; -static const struct parent_map gcc_parent_map_18[] = { - { P_UFS_PHY_RX_SYMBOL_0_CLK, 0 }, - { P_BI_TCXO, 2 }, -}; - -static const struct clk_parent_data gcc_parent_data_18[] = { - { .index = DT_UFS_PHY_RX_SYMBOL_0_CLK }, - { .index = DT_BI_TCXO }, -}; - -static const struct parent_map gcc_parent_map_19[] = { - { P_UFS_PHY_RX_SYMBOL_1_CLK, 0 }, - { P_BI_TCXO, 2 }, -}; - -static const struct clk_parent_data gcc_parent_data_19[] = { - { .index = DT_UFS_PHY_RX_SYMBOL_1_CLK }, - { .index = DT_BI_TCXO }, -}; - -static const struct parent_map gcc_parent_map_20[] = { - { P_UFS_PHY_TX_SYMBOL_0_CLK, 0 }, - { P_BI_TCXO, 2 }, -}; - -static const struct clk_parent_data gcc_parent_data_20[] = { - { .index = DT_UFS_PHY_TX_SYMBOL_0_CLK }, - { .index = DT_BI_TCXO }, -}; - static const struct parent_map gcc_parent_map_21[] = { { P_GCC_USB3_PRIM_PHY_PIPE_CLK_SRC, 0 }, { P_USB4_0_PHY_GCC_USB4RTR_MAX_PIPE_CLK, 1 }, @@ -907,47 +877,44 @@ static struct clk_regmap_phy_mux gcc_pcie_6_pipe_clk_src = { }, }; -static struct clk_regmap_mux gcc_ufs_phy_rx_symbol_0_clk_src = { +static struct clk_regmap_phy_mux gcc_ufs_phy_rx_symbol_0_clk_src = { .reg = 0x7706c, - .shift = 0, - .width = 2, - .parent_map = gcc_parent_map_18, .clkr = { .hw.init = &(const struct clk_init_data) { .name = "gcc_ufs_phy_rx_symbol_0_clk_src", - .parent_data = gcc_parent_data_18, - .num_parents = ARRAY_SIZE(gcc_parent_data_18), - .ops = &clk_regmap_mux_closest_ops, + .parent_data = &(const struct clk_parent_data){ + .index = DT_UFS_PHY_RX_SYMBOL_0_CLK, + }, + .num_parents = 1, + .ops = &clk_regmap_phy_mux_ops, }, }, }; -static struct clk_regmap_mux gcc_ufs_phy_rx_symbol_1_clk_src = { +static struct clk_regmap_phy_mux gcc_ufs_phy_rx_symbol_1_clk_src = { .reg = 0x770f0, - .shift = 0, - .width = 2, - .parent_map = gcc_parent_map_19, .clkr = { .hw.init = &(const struct clk_init_data) { .name = "gcc_ufs_phy_rx_symbol_1_clk_src", - .parent_data = gcc_parent_data_19, - .num_parents = ARRAY_SIZE(gcc_parent_data_19), - .ops = &clk_regmap_mux_closest_ops, + .parent_data = &(const struct clk_parent_data){ + .index = DT_UFS_PHY_RX_SYMBOL_1_CLK, + }, + .num_parents = 1, + .ops = &clk_regmap_phy_mux_ops, }, }, }; -static struct clk_regmap_mux gcc_ufs_phy_tx_symbol_0_clk_src = { +static struct clk_regmap_phy_mux gcc_ufs_phy_tx_symbol_0_clk_src = { .reg = 0x7705c, - .shift = 0, - .width = 2, - .parent_map = gcc_parent_map_20, .clkr = { .hw.init = &(const struct clk_init_data) { .name = "gcc_ufs_phy_tx_symbol_0_clk_src", - .parent_data = gcc_parent_data_20, - .num_parents = ARRAY_SIZE(gcc_parent_data_20), - .ops = &clk_regmap_mux_closest_ops, + .parent_data = &(const struct clk_parent_data){ + .index = DT_UFS_PHY_TX_SYMBOL_0_CLK, + }, + .num_parents = 1, + .ops = &clk_regmap_phy_mux_ops, }, }, }; diff --git a/drivers/clk/qcom/gcc-ipq5424.c b/drivers/clk/qcom/gcc-ipq5424.c index 3ddd4b3aedea..32243e110b27 100644 --- a/drivers/clk/qcom/gcc-ipq5424.c +++ b/drivers/clk/qcom/gcc-ipq5424.c @@ -2949,7 +2949,7 @@ static const struct qcom_reset_map gcc_ipq5424_resets[] = { [GCC_QUPV3_SPI0_BCR] = { 0x04000, 0 }, [GCC_QUPV3_SPI1_BCR] = { 0x05000, 0 }, [GCC_IMEM_BCR] = { 0x0e000, 0 }, - [GCC_TME_BCR] = { 0x100000, 0 }, + [GCC_TME_BCR] = { 0x10000, 0 }, [GCC_DDRSS_BCR] = { 0x11000, 0 }, [GCC_PRNG_BCR] = { 0x13020, 0 }, [GCC_BOOT_ROM_BCR] = { 0x13028, 0 }, @@ -2960,7 +2960,7 @@ static const struct qcom_reset_map gcc_ipq5424_resets[] = { [GCC_UNIPHY2_BCR] = { 0x17064, 0 }, [GCC_WCSS_BCR] = { 0x18004, 0 }, [GCC_SEC_CTRL_BCR] = { 0x1a000, 0 }, - [GCC_TME_SEC_BUS_BCR] = { 0xa1030, 0 }, + [GCC_TME_SEC_BUS_BCR] = { 0x1a030, 0 }, [GCC_ADSS_BCR] = { 0x1c000, 0 }, [GCC_LPASS_BCR] = { 0x27000, 0 }, [GCC_PCIE0_BCR] = { 0x28000, 0 }, diff --git a/drivers/clk/qcom/gcc-kaanapali.c b/drivers/clk/qcom/gcc-kaanapali.c index 5bcbcd178657..c40d2da1086a 100644 --- a/drivers/clk/qcom/gcc-kaanapali.c +++ b/drivers/clk/qcom/gcc-kaanapali.c @@ -3502,6 +3502,7 @@ static const struct qcom_cc_desc gcc_kaanapali_desc = { .num_resets = ARRAY_SIZE(gcc_kaanapali_resets), .gdscs = gcc_kaanapali_gdscs, .num_gdscs = ARRAY_SIZE(gcc_kaanapali_gdscs), + .use_rpm = true, .driver_data = &gcc_kaanapali_driver_data, }; diff --git a/drivers/clk/qcom/gcc-qcs615.c b/drivers/clk/qcom/gcc-qcs615.c index 57f8c80c6f32..1a6a1e74e805 100644 --- a/drivers/clk/qcom/gcc-qcs615.c +++ b/drivers/clk/qcom/gcc-qcs615.c @@ -2999,7 +2999,7 @@ static int gcc_qcs615_probe(struct platform_device *pdev) qcom_branch_set_clk_en(regmap, 0x71004); /* GCC_GPU_CFG_AHB_CLK */ qcom_branch_set_clk_en(regmap, 0xb004); /* GCC_VIDEO_AHB_CLK */ qcom_branch_set_clk_en(regmap, 0xb040); /* GCC_VIDEO_XO_CLK */ - qcom_branch_set_clk_en(regmap, 0x480040); /* GCC_CPUSS_GNOC_CLK */ + qcom_branch_set_clk_en(regmap, 0x48004); /* GCC_CPUSS_GNOC_CLK */ ret = qcom_cc_register_rcg_dfs(regmap, gcc_dfs_clocks, ARRAY_SIZE(gcc_dfs_clocks)); diff --git a/drivers/clk/qcom/gcc-x1e80100.c b/drivers/clk/qcom/gcc-x1e80100.c index 8c146d62c077..754d1e03c2fa 100644 --- a/drivers/clk/qcom/gcc-x1e80100.c +++ b/drivers/clk/qcom/gcc-x1e80100.c @@ -6049,7 +6049,7 @@ static struct clk_branch gcc_usb4_0_sb_if_clk = { static struct clk_branch gcc_usb4_0_sys_clk = { .halt_reg = 0x9f054, - .halt_check = BRANCH_HALT, + .halt_check = BRANCH_HALT_SKIP, .clkr = { .enable_reg = 0x9f054, .enable_mask = BIT(0), @@ -6266,7 +6266,7 @@ static struct clk_branch gcc_usb4_1_sb_if_clk = { static struct clk_branch gcc_usb4_1_sys_clk = { .halt_reg = 0x2b054, - .halt_check = BRANCH_HALT, + .halt_check = BRANCH_HALT_SKIP, .clkr = { .enable_reg = 0x2b054, .enable_mask = BIT(0), @@ -6483,7 +6483,7 @@ static struct clk_branch gcc_usb4_2_sb_if_clk = { static struct clk_branch gcc_usb4_2_sys_clk = { .halt_reg = 0x11054, - .halt_check = BRANCH_HALT, + .halt_check = BRANCH_HALT_SKIP, .clkr = { .enable_reg = 0x11054, .enable_mask = BIT(0), diff --git a/drivers/clk/qcom/lpasscc-sm6115.c b/drivers/clk/qcom/lpasscc-sm6115.c index 226dc02fc42d..fcc1512d4a99 100644 --- a/drivers/clk/qcom/lpasscc-sm6115.c +++ b/drivers/clk/qcom/lpasscc-sm6115.c @@ -34,7 +34,7 @@ static const struct qcom_cc_desc lpass_audiocc_sm6115_reset_desc = { }; static const struct qcom_reset_map lpasscc_sm6115_resets[] = { - [LPASS_SWR_TX_CONFIG_CGCR] = { .reg = 0x100, .bit = 1, .udelay = 500 }, + [LPASS_SWR_TX_CONFIG_CGCR] = { .reg = 0xc100, .bit = 1, .udelay = 500 }, }; static struct regmap_config lpasscc_sm6115_regmap_config = { @@ -42,7 +42,7 @@ static struct regmap_config lpasscc_sm6115_regmap_config = { .reg_stride = 4, .val_bits = 32, .name = "lpass-tcsr", - .max_register = 0x1000, + .max_register = 0x12000, }; static const struct qcom_cc_desc lpasscc_sm6115_reset_desc = { diff --git a/drivers/clk/qcom/mmcc-msm8960.c b/drivers/clk/qcom/mmcc-msm8960.c index a23440e13b71..a67df833592a 100644 --- a/drivers/clk/qcom/mmcc-msm8960.c +++ b/drivers/clk/qcom/mmcc-msm8960.c @@ -3170,7 +3170,8 @@ static int mmcc_msm8960_probe(struct platform_device *pdev) if (IS_ERR(regmap)) return PTR_ERR(regmap); - clk_pll_configure_sr(&pll15, regmap, &pll15_config, false); + if (desc == &mmcc_apq8064_desc) + clk_pll_configure_sr(&pll15, regmap, &pll15_config, false); return qcom_cc_really_probe(&pdev->dev, desc, regmap); } diff --git a/drivers/clk/qcom/mmcc-msm8996.c b/drivers/clk/qcom/mmcc-msm8996.c index 3426e3dde924..ef7bde361fc3 100644 --- a/drivers/clk/qcom/mmcc-msm8996.c +++ b/drivers/clk/qcom/mmcc-msm8996.c @@ -3133,9 +3133,9 @@ static struct clk_branch fd_core_uar_clk = { }; static struct clk_branch fd_ahb_clk = { - .halt_reg = 0x3ba74, + .halt_reg = 0x3b74, .clkr = { - .enable_reg = 0x3ba74, + .enable_reg = 0x3b74, .enable_mask = BIT(0), .hw.init = &(struct clk_init_data){ .name = "fd_ahb_clk", diff --git a/drivers/clk/qcom/mmcc-sdm660.c b/drivers/clk/qcom/mmcc-sdm660.c index 200f986de965..9f8b8e29fa0f 100644 --- a/drivers/clk/qcom/mmcc-sdm660.c +++ b/drivers/clk/qcom/mmcc-sdm660.c @@ -2017,7 +2017,7 @@ static struct clk_branch csiphy_ahb2crif_clk = { static struct clk_branch mdss_ahb_clk = { .halt_reg = 0x2308, .halt_check = BRANCH_HALT, - .hwcg_reg = 0x8a004, + .hwcg_reg = 0x2308, .hwcg_bit = 1, .clkr = { .enable_reg = 0x2308, diff --git a/drivers/clk/qcom/negcc-nord.c b/drivers/clk/qcom/negcc-nord.c index 0db284edc4e4..ef9ff450bcd4 100644 --- a/drivers/clk/qcom/negcc-nord.c +++ b/drivers/clk/qcom/negcc-nord.c @@ -46,7 +46,7 @@ static struct clk_alpha_pll ne_gcc_gpll0 = { .offset = 0x0, .regs = clk_alpha_pll_regs[CLK_ALPHA_PLL_TYPE_LUCID_OLE], .clkr = { - .enable_reg = 0x0, + .enable_reg = 0x57010, .enable_mask = BIT(0), .hw.init = &(const struct clk_init_data) { .name = "ne_gcc_gpll0", @@ -85,7 +85,7 @@ static struct clk_alpha_pll ne_gcc_gpll2 = { .offset = 0x2000, .regs = clk_alpha_pll_regs[CLK_ALPHA_PLL_TYPE_LUCID_OLE], .clkr = { - .enable_reg = 0x0, + .enable_reg = 0x57010, .enable_mask = BIT(2), .hw.init = &(const struct clk_init_data) { .name = "ne_gcc_gpll2", diff --git a/drivers/clk/qcom/nwgcc-nord.c b/drivers/clk/qcom/nwgcc-nord.c index e061c0623e9a..1eb8e5313912 100644 --- a/drivers/clk/qcom/nwgcc-nord.c +++ b/drivers/clk/qcom/nwgcc-nord.c @@ -36,7 +36,7 @@ static struct clk_alpha_pll nw_gcc_gpll0 = { .offset = 0x0, .regs = clk_alpha_pll_regs[CLK_ALPHA_PLL_TYPE_LUCID_OLE], .clkr = { - .enable_reg = 0x0, + .enable_reg = 0x76008, .enable_mask = BIT(0), .hw.init = &(const struct clk_init_data) { .name = "nw_gcc_gpll0", @@ -623,6 +623,9 @@ static const struct qcom_reset_map nw_gcc_nord_resets[] = { [NW_GCC_GPU_2_BCR] = { 0x24000 }, [NW_GCC_GPU_BCR] = { 0x23000 }, [NW_GCC_VIDEO_BCR] = { 0x1a000 }, + [NW_GCC_VIDEO_AXI0_CLK_ARES] = { 0x1a008, 2 }, + [NW_GCC_VIDEO_AXI0C_CLK_ARES] = { 0x1a01c, 2 }, + [NW_GCC_VIDEO_AXI1_CLK_ARES] = { 0x1a030, 2 }, }; static const u32 nw_gcc_nord_critical_cbcrs[] = { diff --git a/drivers/clk/qcom/segcc-nord.c b/drivers/clk/qcom/segcc-nord.c index 51d7f83e21b6..98b53311d333 100644 --- a/drivers/clk/qcom/segcc-nord.c +++ b/drivers/clk/qcom/segcc-nord.c @@ -39,7 +39,7 @@ static struct clk_alpha_pll se_gcc_gpll0 = { .offset = 0x0, .regs = clk_alpha_pll_regs[CLK_ALPHA_PLL_TYPE_LUCID_OLE], .clkr = { - .enable_reg = 0x0, + .enable_reg = 0x57010, .enable_mask = BIT(0), .hw.init = &(const struct clk_init_data) { .name = "se_gcc_gpll0", @@ -78,7 +78,7 @@ static struct clk_alpha_pll se_gcc_gpll2 = { .offset = 0x2000, .regs = clk_alpha_pll_regs[CLK_ALPHA_PLL_TYPE_LUCID_OLE], .clkr = { - .enable_reg = 0x0, + .enable_reg = 0x57010, .enable_mask = BIT(2), .hw.init = &(const struct clk_init_data) { .name = "se_gcc_gpll2", @@ -95,7 +95,7 @@ static struct clk_alpha_pll se_gcc_gpll4 = { .offset = 0x4000, .regs = clk_alpha_pll_regs[CLK_ALPHA_PLL_TYPE_LUCID_OLE], .clkr = { - .enable_reg = 0x0, + .enable_reg = 0x57010, .enable_mask = BIT(4), .hw.init = &(const struct clk_init_data) { .name = "se_gcc_gpll4", @@ -112,7 +112,7 @@ static struct clk_alpha_pll se_gcc_gpll5 = { .offset = 0x5000, .regs = clk_alpha_pll_regs[CLK_ALPHA_PLL_TYPE_LUCID_OLE], .clkr = { - .enable_reg = 0x0, + .enable_reg = 0x57010, .enable_mask = BIT(5), .hw.init = &(const struct clk_init_data) { .name = "se_gcc_gpll5", diff --git a/drivers/clk/starfive/clk-starfive-jh7110-sys.c b/drivers/clk/starfive/clk-starfive-jh7110-sys.c index 03c17cd2032f..847c0a39e5ab 100644 --- a/drivers/clk/starfive/clk-starfive-jh7110-sys.c +++ b/drivers/clk/starfive/clk-starfive-jh7110-sys.c @@ -390,6 +390,9 @@ static int jh7110_pll0_clk_notifier_cb(struct notifier_block *nb, if (action == PRE_RATE_CHANGE) { struct clk *osc = clk_get(priv->dev, "osc"); + if (IS_ERR(osc)) + return notifier_from_errno(PTR_ERR(osc)); + priv->original_clk = clk_get_parent(cpu_root); ret = clk_set_parent(cpu_root, osc); clk_put(osc); diff --git a/drivers/clk/stm32/clk-stm32mp21.c b/drivers/clk/stm32/clk-stm32mp21.c index bdb17419908c..961a228d8c64 100644 --- a/drivers/clk/stm32/clk-stm32mp21.c +++ b/drivers/clk/stm32/clk-stm32mp21.c @@ -17,8 +17,8 @@ #include #include -/* Max clock binding value */ -#define STM32MP21_LAST_CLK CK_SCMI_KER_ETR +/* Number of RCC clock bindings (highest RCC clock ID + 1) */ +#define STM32MP21_LAST_CLK (CK_KER_STM + 1) /* Clock security definition */ #define SECF_NONE -1 diff --git a/drivers/clk/sunxi-ng/ccu-sun55i-a523-r.c b/drivers/clk/sunxi-ng/ccu-sun55i-a523-r.c index db0e36d8838e..349230e28c1c 100644 --- a/drivers/clk/sunxi-ng/ccu-sun55i-a523-r.c +++ b/drivers/clk/sunxi-ng/ccu-sun55i-a523-r.c @@ -43,27 +43,24 @@ static SUNXI_CCU_M_DATA_WITH_MUX(r_apb1_clk, "r-apb1", 24, 3, /* mux */ 0); -static SUNXI_CCU_MP_DATA_WITH_MUX_GATE(r_cpu_timer0, "r-timer0", - r_ahb_apb_parents, 0x100, - 0, 0, /* no M */ - 1, 3, /* P */ - 4, 3, /* mux */ - BIT(0), +static SUNXI_CCU_P_DATA_WITH_MUX_GATE(r_cpu_timer0, "r-timer0", + r_ahb_apb_parents, 0x100, + 1, 3, /* P */ + 4, 3, /* mux */ + BIT(0), + 0); +static SUNXI_CCU_P_DATA_WITH_MUX_GATE(r_cpu_timer1, "r-timer1", + r_ahb_apb_parents, 0x104, + 1, 3, /* P */ + 4, 3, /* mux */ + BIT(0), + 0); +static SUNXI_CCU_P_DATA_WITH_MUX_GATE(r_cpu_timer2, "r-timer2", + r_ahb_apb_parents, 0x108, + 1, 3, /* P */ + 4, 3, /* mux */ + BIT(0), 0); -static SUNXI_CCU_MP_DATA_WITH_MUX_GATE(r_cpu_timer1, "r-timer1", - r_ahb_apb_parents, 0x104, - 0, 0, /* no M */ - 1, 3, /* P */ - 4, 3, /* mux */ - BIT(0), - 0); -static SUNXI_CCU_MP_DATA_WITH_MUX_GATE(r_cpu_timer2, "r-timer2", - r_ahb_apb_parents, 0x108, - 0, 0, /* no M */ - 1, 3, /* P */ - 4, 3, /* mux */ - BIT(0), - 0); static SUNXI_CCU_GATE_HW(bus_r_timer_clk, "bus-r-timer", &r_ahb_clk.common.hw, 0x11c, BIT(0), 0); diff --git a/drivers/clk/sunxi-ng/ccu-sun55i-a523.c b/drivers/clk/sunxi-ng/ccu-sun55i-a523.c index 20dad06b37ca..0714090cc3b0 100644 --- a/drivers/clk/sunxi-ng/ccu-sun55i-a523.c +++ b/drivers/clk/sunxi-ng/ccu-sun55i-a523.c @@ -380,14 +380,13 @@ static const struct clk_parent_data mbus_parents[] = { { .hw = &pll_periph1_150M_clk.hw }, { .fw_name = "hosc" }, }; -static SUNXI_CCU_MP_DATA_WITH_MUX_GATE_FEAT(mbus_clk, "mbus", mbus_parents, - 0x540, - 0, 5, /* M */ - 0, 0, /* no P */ - 24, 3, /* mux */ - BIT(31), /* gate */ - CLK_IS_CRITICAL, - CCU_FEATURE_UPDATE_BIT); +static SUNXI_CCU_M_DATA_WITH_MUX_GATE_FEAT(mbus_clk, "mbus", mbus_parents, + 0x540, + 0, 5, /* M */ + 24, 3, /* mux */ + BIT(31), /* gate */ + CLK_IS_CRITICAL, + CCU_FEATURE_UPDATE_BIT); static const struct clk_hw *mbus_hws[] = { &mbus_clk.common.hw }; @@ -513,58 +512,47 @@ static const struct clk_parent_data hstimer_parents[] = { { .fw_name = "losc" }, { .hw = &pll_periph0_200M_clk.hw }, }; -static SUNXI_CCU_MP_DATA_WITH_MUX_GATE(hstimer0_clk, "hstimer0", - hstimer_parents, 0x730, - 0, 0, /* M */ - 0, 3, /* P */ - 24, 3, /* mux */ - BIT(31), /* gate */ - 0); +static SUNXI_CCU_P_DATA_WITH_MUX_GATE(hstimer0_clk, "hstimer0", + hstimer_parents, 0x730, + 0, 3, /* P */ + 24, 3, /* mux */ + BIT(31), /* gate */ + 0); -static SUNXI_CCU_MP_DATA_WITH_MUX_GATE(hstimer1_clk, "hstimer1", - hstimer_parents, - 0x734, - 0, 0, /* M */ - 0, 3, /* P */ - 24, 3, /* mux */ - BIT(31), /* gate */ - 0); +static SUNXI_CCU_P_DATA_WITH_MUX_GATE(hstimer1_clk, "hstimer1", + hstimer_parents, 0x734, + 0, 3, /* P */ + 24, 3, /* mux */ + BIT(31), /* gate */ + 0); -static SUNXI_CCU_MP_DATA_WITH_MUX_GATE(hstimer2_clk, "hstimer2", - hstimer_parents, - 0x738, - 0, 0, /* M */ - 0, 3, /* P */ - 24, 3, /* mux */ - BIT(31), /* gate */ - 0); +static SUNXI_CCU_P_DATA_WITH_MUX_GATE(hstimer2_clk, "hstimer2", + hstimer_parents, 0x738, + 0, 3, /* P */ + 24, 3, /* mux */ + BIT(31), /* gate */ + 0); -static SUNXI_CCU_MP_DATA_WITH_MUX_GATE(hstimer3_clk, "hstimer3", - hstimer_parents, - 0x73c, - 0, 0, /* M */ - 0, 3, /* P */ - 24, 3, /* mux */ - BIT(31), /* gate */ - 0); +static SUNXI_CCU_P_DATA_WITH_MUX_GATE(hstimer3_clk, "hstimer3", + hstimer_parents, 0x73c, + 0, 3, /* P */ + 24, 3, /* mux */ + BIT(31), /* gate */ + 0); -static SUNXI_CCU_MP_DATA_WITH_MUX_GATE(hstimer4_clk, "hstimer4", - hstimer_parents, - 0x740, - 0, 0, /* M */ - 0, 3, /* P */ - 24, 3, /* mux */ - BIT(31), /* gate */ - 0); +static SUNXI_CCU_P_DATA_WITH_MUX_GATE(hstimer4_clk, "hstimer4", + hstimer_parents, 0x740, + 0, 3, /* P */ + 24, 3, /* mux */ + BIT(31), /* gate */ + 0); -static SUNXI_CCU_MP_DATA_WITH_MUX_GATE(hstimer5_clk, "hstimer5", - hstimer_parents, - 0x744, - 0, 0, /* M */ - 0, 3, /* P */ - 24, 3, /* mux */ - BIT(31), /* gate */ - 0); +static SUNXI_CCU_P_DATA_WITH_MUX_GATE(hstimer5_clk, "hstimer5", + hstimer_parents, 0x744, + 0, 3, /* P */ + 24, 3, /* mux */ + BIT(31), /* gate */ + 0); static SUNXI_CCU_GATE_HWS(bus_hstimer_clk, "bus-hstimer", ahb_hws, 0x74c, BIT(0), 0); @@ -584,14 +572,13 @@ static const struct clk_parent_data iommu_parents[] = { { .fw_name = "hosc" }, }; -static SUNXI_CCU_MP_DATA_WITH_MUX_GATE_FEAT(iommu_clk, "iommu", iommu_parents, - 0x7b0, - 0, 5, /* M */ - 0, 0, /* no P */ - 24, 3, /* mux */ - BIT(31), /* gate */ - CLK_SET_RATE_PARENT, - CCU_FEATURE_UPDATE_BIT); +static SUNXI_CCU_M_DATA_WITH_MUX_GATE_FEAT(iommu_clk, "iommu", iommu_parents, + 0x7b0, + 0, 5, /* M */ + 24, 3, /* mux */ + BIT(31), /* gate */ + CLK_SET_RATE_PARENT, + CCU_FEATURE_UPDATE_BIT); static SUNXI_CCU_GATE_HWS(bus_iommu_clk, "bus-iommu", apb0_hws, 0x7bc, BIT(0), 0); @@ -603,14 +590,13 @@ static const struct clk_parent_data dram_parents[] = { { .hw = &pll_periph0_400M_clk.hw }, { .hw = &pll_periph0_150M_clk.hw }, }; -static SUNXI_CCU_MP_DATA_WITH_MUX_GATE_FEAT(dram_clk, "dram", dram_parents, - 0x800, - 0, 5, /* M */ - 0, 0, /* no P */ - 24, 3, /* mux */ - BIT(31), /* gate */ - CLK_IS_CRITICAL, - CCU_FEATURE_UPDATE_BIT); +static SUNXI_CCU_M_DATA_WITH_MUX_GATE_FEAT(dram_clk, "dram", dram_parents, + 0x800, + 0, 5, /* M */ + 24, 3, /* mux */ + BIT(31), /* gate */ + CLK_IS_CRITICAL, + CCU_FEATURE_UPDATE_BIT); static SUNXI_CCU_GATE_HWS(mbus_dma_clk, "mbus-dma", mbus_hws, 0x804, BIT(0), 0); diff --git a/drivers/clk/sunxi-ng/ccu_div.h b/drivers/clk/sunxi-ng/ccu_div.h index a30a92780a05..6d3541a3b519 100644 --- a/drivers/clk/sunxi-ng/ccu_div.h +++ b/drivers/clk/sunxi-ng/ccu_div.h @@ -212,16 +212,17 @@ struct ccu_div { SUNXI_CCU_M_WITH_GATE(_struct, _name, _parent, _reg, \ _mshift, _mwidth, 0, _flags) -#define SUNXI_CCU_M_DATA_WITH_MUX_GATE(_struct, _name, _parents, _reg, \ - _mshift, _mwidth, \ - _muxshift, _muxwidth, \ - _gate, _flags) \ +#define SUNXI_CCU_M_DATA_WITH_MUX_GATE_FEAT(_struct, _name, _parents, _reg, \ + _mshift, _mwidth, \ + _muxshift, _muxwidth, \ + _gate, _flags, _features) \ struct ccu_div _struct = { \ .enable = _gate, \ .div = _SUNXI_CCU_DIV(_mshift, _mwidth), \ .mux = _SUNXI_CCU_MUX(_muxshift, _muxwidth), \ .common = { \ .reg = _reg, \ + .features = _features, \ .hw.init = CLK_HW_INIT_PARENTS_DATA(_name, \ _parents, \ &ccu_div_ops, \ @@ -229,6 +230,15 @@ struct ccu_div { }, \ } +#define SUNXI_CCU_M_DATA_WITH_MUX_GATE(_struct, _name, _parents, _reg, \ + _mshift, _mwidth, \ + _muxshift, _muxwidth, \ + _gate, _flags) \ + SUNXI_CCU_M_DATA_WITH_MUX_GATE_FEAT(_struct, _name, _parents, _reg, \ + _mshift, _mwidth, \ + _muxshift, _muxwidth, \ + _gate, _flags, 0) + #define SUNXI_CCU_M_DATA_WITH_MUX(_struct, _name, _parents, _reg, \ _mshift, _mwidth, \ _muxshift, _muxwidth, \ diff --git a/drivers/clk/ti/adpll.c b/drivers/clk/ti/adpll.c index 8885d28face5..0d729c9980a5 100644 --- a/drivers/clk/ti/adpll.c +++ b/drivers/clk/ti/adpll.c @@ -925,6 +925,7 @@ static void ti_adpll_remove(struct platform_device *pdev) { struct ti_adpll_data *d = dev_get_drvdata(&pdev->dev); + of_clk_del_provider(d->np); ti_adpll_free_resources(d); } diff --git a/drivers/clk/versatile/clk-icst.c b/drivers/clk/versatile/clk-icst.c index 6bd3db54dd22..8c84377f3ec1 100644 --- a/drivers/clk/versatile/clk-icst.c +++ b/drivers/clk/versatile/clk-icst.c @@ -516,16 +516,19 @@ static void __init of_syscon_icst_setup(struct device_node *np) map = syscon_node_to_regmap(parent); if (IS_ERR(map)) { pr_err("no regmap for syscon ICST clock parent\n"); + of_node_put(parent); return; } if (of_property_read_u32(np, "reg", &icst_desc.vco_offset) && of_property_read_u32(np, "vco-offset", &icst_desc.vco_offset)) { pr_err("no VCO register offset for ICST clock\n"); + of_node_put(parent); return; } if (of_property_read_u32(np, "lock-offset", &icst_desc.lock_offset)) { pr_err("no lock register offset for ICST clock\n"); + of_node_put(parent); return; } @@ -552,6 +555,7 @@ static void __init of_syscon_icst_setup(struct device_node *np) ctype = ICST_INTEGRATOR_CP_CM_MEM; } else { pr_err("unknown ICST clock %pOF\n", np); + of_node_put(parent); return; } diff --git a/drivers/clocksource/clksrc-dbx500-prcmu.c b/drivers/clocksource/clksrc-dbx500-prcmu.c index 2fc93e46cea3..1af223b0e896 100644 --- a/drivers/clocksource/clksrc-dbx500-prcmu.c +++ b/drivers/clocksource/clksrc-dbx500-prcmu.c @@ -52,6 +52,8 @@ static struct clocksource clocksource_dbx500_prcmu = { static int __init clksrc_dbx500_prcmu_init(struct device_node *node) { clksrc_dbx500_timer_base = of_iomap(node, 0); + if (!clksrc_dbx500_timer_base) + return -ENOMEM; /* * The A9 sub system expects the timer to be configured as diff --git a/drivers/clocksource/timer-econet-en751221.c b/drivers/clocksource/timer-econet-en751221.c index 4008076b1a21..1859335345b5 100644 --- a/drivers/clocksource/timer-econet-en751221.c +++ b/drivers/clocksource/timer-econet-en751221.c @@ -181,6 +181,7 @@ static int __init timer_init(struct device_node *np) } econet_timer.freq_hz = clk_get_rate(clk); + clk_put(clk); for (int i = 0; i < num_blocks; i++) { econet_timer.membase[i] = of_iomap(np, i); diff --git a/drivers/clocksource/timer-mediatek.c b/drivers/clocksource/timer-mediatek.c index 7bcb4a3f26fb..e20075b09fab 100644 --- a/drivers/clocksource/timer-mediatek.c +++ b/drivers/clocksource/timer-mediatek.c @@ -277,7 +277,7 @@ static struct timer_of to = { }, .of_irq = { - .flags = IRQF_TIMER | IRQF_IRQPOLL, + .flags = IRQF_TIMER | IRQF_IRQPOLL | IRQF_NO_AUTOEN, }, }; @@ -298,6 +298,7 @@ static int __init mtk_syst_init(struct device_node *node) clockevents_config_and_register(&to.clkevt, timer_of_rate(&to), TIMER_SYNC_TICKS, 0xffffffff); + enable_irq(timer_of_irq(&to)); return 0; } @@ -334,6 +335,7 @@ static int __init mtk_gpt_init(struct device_node *node) TIMER_SYNC_TICKS, 0xffffffff); mtk_gpt_enable_irq(&to, TIMER_CLK_EVT); + enable_irq(timer_of_irq(&to)); return 0; } diff --git a/drivers/clocksource/timer-ti-dm.c b/drivers/clocksource/timer-ti-dm.c index 6787acac9a43..8012d3f3e1a3 100644 --- a/drivers/clocksource/timer-ti-dm.c +++ b/drivers/clocksource/timer-ti-dm.c @@ -1095,6 +1095,7 @@ static int omap_dm_timer_write_counter(struct omap_dm_timer *cookie, unsigned in { struct dmtimer *timer; struct device *dev; + int ret; timer = to_dmtimer(cookie); if (unlikely(!timer)) { @@ -1104,7 +1105,10 @@ static int omap_dm_timer_write_counter(struct omap_dm_timer *cookie, unsigned in dev = &timer->pdev->dev; - pm_runtime_resume_and_get(dev); + ret = pm_runtime_resume_and_get(dev); + if (ret < 0) + return ret; + dmtimer_write(timer, OMAP_TIMER_COUNTER_REG, value); pm_runtime_put_sync(dev); @@ -1475,7 +1479,8 @@ static int omap_dm_timer_probe(struct platform_device *pdev) timer->pdev = pdev; - if (timer->capability & OMAP_TIMER_ALWON && !IS_ERR_OR_NULL(timer->fclk)) { + if (pdata->system_timer_capable && + timer->capability & OMAP_TIMER_ALWON && !IS_ERR_OR_NULL(timer->fclk)) { if (!omap_dm_timer_sched_clock_counter) { ret = omap_dm_timer_setup_clocksource(timer); if (ret) @@ -1585,6 +1590,7 @@ static const struct dmtimer_platform_data omap3plus_pdata = { static const struct dmtimer_platform_data am6_pdata = { .timer_ops = &dmtimer_ops, + .system_timer_capable = true, }; static const struct of_device_id omap_timer_match[] = { diff --git a/drivers/comedi/drivers/addi_apci_3xxx.c b/drivers/comedi/drivers/addi_apci_3xxx.c index 695cce103177..1dcda82d9503 100644 --- a/drivers/comedi/drivers/addi_apci_3xxx.c +++ b/drivers/comedi/drivers/addi_apci_3xxx.c @@ -787,7 +787,7 @@ static int apci3xxx_auto_attach(struct comedi_device *dev, dev->irq = pcidev->irq; } - n_subdevices = (board->ai_n_chan ? 0 : 1) + board->has_ao + + n_subdevices = (board->ai_n_chan ? 1 : 0) + board->has_ao + board->has_dig_in + board->has_dig_out + board->has_ttl_io; ret = comedi_alloc_subdevices(dev, n_subdevices); diff --git a/drivers/comedi/drivers/comedi_parport.c b/drivers/comedi/drivers/comedi_parport.c index 57ee3f9dfba2..94284ff157ac 100644 --- a/drivers/comedi/drivers/comedi_parport.c +++ b/drivers/comedi/drivers/comedi_parport.c @@ -243,7 +243,8 @@ static int parport_attach(struct comedi_device *dev, outb(0, dev->iobase + PARPORT_DATA_REG); outb(0, dev->iobase + PARPORT_CTRL_REG); - if (it->options[1]) { + /* only ISA interrupts are valid on a parallel port */ + if (it->options[1] >= 1 && it->options[1] <= 15) { ret = request_irq(it->options[1], parport_interrupt, 0, dev->board_name, dev); if (ret == 0) diff --git a/drivers/comedi/drivers/dmm32at.c b/drivers/comedi/drivers/dmm32at.c index d1d9f75e168f..c6a6ba2899e6 100644 --- a/drivers/comedi/drivers/dmm32at.c +++ b/drivers/comedi/drivers/dmm32at.c @@ -600,7 +600,8 @@ static int dmm32at_attach(struct comedi_device *dev, return ret; } - if (it->options[1]) { + /* only ISA interrupts are valid on this board */ + if (it->options[1] >= 1 && it->options[1] <= 15) { ret = request_irq(it->options[1], dmm32at_isr, 0, dev->board_name, dev); if (ret == 0) diff --git a/drivers/comedi/drivers/dt2811.c b/drivers/comedi/drivers/dt2811.c index 0438b8c90e44..53cb17993ae7 100644 --- a/drivers/comedi/drivers/dt2811.c +++ b/drivers/comedi/drivers/dt2811.c @@ -567,7 +567,7 @@ static int dt2811_attach(struct comedi_device *dev, struct comedi_devconfig *it) dt2811_reset(dev); /* IRQ's 2,3,5,7 are valid for async command support */ - if (it->options[1] <= 7 && (BIT(it->options[1]) & 0xac)) { + if (it->options[1] >= 0 && it->options[1] <= 7 && (BIT(it->options[1]) & 0xac)) { ret = request_irq(it->options[1], dt2811_interrupt, 0, dev->board_name, dev); if (ret == 0) diff --git a/drivers/comedi/drivers/dt2814.c b/drivers/comedi/drivers/dt2814.c index caec16482afb..63b7f17691ff 100644 --- a/drivers/comedi/drivers/dt2814.c +++ b/drivers/comedi/drivers/dt2814.c @@ -316,7 +316,8 @@ static int dt2814_attach(struct comedi_device *dev, struct comedi_devconfig *it) return -EIO; } - if (it->options[1]) { + /* only ISA interrupts are valid on this board */ + if (it->options[1] >= 1 && it->options[1] <= 15) { ret = request_irq(it->options[1], dt2814_interrupt, 0, dev->board_name, dev); if (ret == 0) diff --git a/drivers/comedi/drivers/ni_atmio16d.c b/drivers/comedi/drivers/ni_atmio16d.c index 6765cdc276ca..87fed16b112c 100644 --- a/drivers/comedi/drivers/ni_atmio16d.c +++ b/drivers/comedi/drivers/ni_atmio16d.c @@ -593,7 +593,9 @@ static int atmio16d_attach(struct comedi_device *dev, /* reset the atmio16d hardware */ reset_atmio16d(dev); - if (it->options[1]) { + /* only irqs 3, 4, 5, 6, 7, 9, 10, 11, 12, 14, and 15 are valid */ + if (it->options[1] >= 3 && it->options[1] <= 15 && + (1 << it->options[1]) & 0xdef8) { ret = request_irq(it->options[1], atmio16d_interrupt, 0, dev->board_name, dev); if (ret == 0) diff --git a/drivers/comedi/drivers/pcmmio.c b/drivers/comedi/drivers/pcmmio.c index f42b7343b4e4..afe2bda91659 100644 --- a/drivers/comedi/drivers/pcmmio.c +++ b/drivers/comedi/drivers/pcmmio.c @@ -684,7 +684,8 @@ static int pcmmio_attach(struct comedi_device *dev, struct comedi_devconfig *it) pcmmio_reset(dev); - if (it->options[1]) { + /* the irq is configured in software, so any ISA irq is OK */ + if (it->options[1] >= 1 && it->options[1] <= 15) { ret = request_irq(it->options[1], interrupt_pcmmio, 0, dev->board_name, dev); if (ret == 0) { diff --git a/drivers/comedi/drivers/pcmuio.c b/drivers/comedi/drivers/pcmuio.c index d9995cbeecb6..da80bca0bb55 100644 --- a/drivers/comedi/drivers/pcmuio.c +++ b/drivers/comedi/drivers/pcmuio.c @@ -546,7 +546,8 @@ static int pcmuio_attach(struct comedi_device *dev, struct comedi_devconfig *it) pcmuio_reset(dev); - if (it->options[1]) { + /* only ISA interrupts are valid on this board */ + if (it->options[1] >= 1 && it->options[1] <= 15) { /* request the irq for the 1st asic */ ret = request_irq(it->options[1], pcmuio_interrupt, 0, dev->board_name, dev); @@ -558,7 +559,7 @@ static int pcmuio_attach(struct comedi_device *dev, struct comedi_devconfig *it) if (it->options[2] == dev->irq) { /* the same irq (or none) is used by both asics */ devpriv->irq2 = it->options[2]; - } else if (it->options[2]) { + } else if (it->options[2] >= 1 && it->options[2] <= 15) { /* request the irq for the 2nd asic */ ret = request_irq(it->options[2], pcmuio_interrupt, 0, dev->board_name, dev); diff --git a/drivers/cpufreq/amd-pstate-ut.c b/drivers/cpufreq/amd-pstate-ut.c index e23773680e05..c2c1a166b3a9 100644 --- a/drivers/cpufreq/amd-pstate-ut.c +++ b/drivers/cpufreq/amd-pstate-ut.c @@ -226,11 +226,14 @@ static int amd_pstate_ut_check_freq(u32 index) for_each_online_cpu(cpu) { struct cpufreq_policy *policy __free(put_cpufreq_policy) = NULL; struct amd_cpudata *cpudata; + union perf_cached perf; policy = cpufreq_cpu_get(cpu); if (!policy) continue; + cpudata = policy->driver_data; + perf = READ_ONCE(cpudata->perf); if (!((policy->cpuinfo.max_freq >= cpudata->nominal_freq) && (cpudata->nominal_freq > cpudata->lowest_nonlinear_freq) && @@ -242,7 +245,25 @@ static int amd_pstate_ut_check_freq(u32 index) return -EINVAL; } - if (cpudata->lowest_nonlinear_freq != policy->min) { + if (perf.bios_min_perf) { + u32 bios_min_freq = perf_to_freq(perf, cpudata->nominal_freq, + perf.bios_min_perf); + + /* + * User set bios_min_freq cannot be trusted to + * be within the driver limits. Clamp it similar + * to cpufreq_verify_within_cpu_limits(). + */ + bios_min_freq = clamp_t(u32, bios_min_freq, + policy->cpuinfo.min_freq, + policy->cpuinfo.max_freq); + + if (bios_min_freq != policy->min) { + pr_err("%s cpu%d bios_min_freq=%d policy_min=%d, they should be equal!\n", + __func__, cpu, bios_min_freq, policy->min); + return -EINVAL; + } + } else if (cpudata->lowest_nonlinear_freq != policy->min) { pr_err("%s cpu%d cpudata_lowest_nonlinear_freq=%d policy_min=%d, they should be equal!\n", __func__, cpu, cpudata->lowest_nonlinear_freq, policy->min); return -EINVAL; diff --git a/drivers/cpufreq/amd-pstate.c b/drivers/cpufreq/amd-pstate.c index 28b9d4d062b9..8cfc8eb5c05c 100644 --- a/drivers/cpufreq/amd-pstate.c +++ b/drivers/cpufreq/amd-pstate.c @@ -145,19 +145,6 @@ static struct quirk_entry quirk_amd_7k62 = { .lowest_freq = 550, }; -static inline u8 freq_to_perf(union perf_cached perf, u32 nominal_freq, unsigned int freq_val) -{ - u32 perf_val = DIV_ROUND_UP_ULL((u64)freq_val * perf.nominal_perf, nominal_freq); - - return (u8)clamp(perf_val, perf.lowest_perf, perf.highest_perf); -} - -static inline u32 perf_to_freq(union perf_cached perf, u32 nominal_freq, u8 perf_val) -{ - return DIV_ROUND_UP_ULL((u64)nominal_freq * perf_val, - perf.nominal_perf); -} - static int __init dmi_matched_7k62_bios_bug(const struct dmi_system_id *dmi) { /** @@ -1294,8 +1281,10 @@ static int amd_pstate_set_dynamic_epp(struct cpufreq_policy *policy) return ret; cpudata->profile_name = kasprintf(GFP_KERNEL, "amd-pstate-epp-cpu%d", cpudata->cpu); - if (!cpudata->profile_name) - return -ENOMEM; + if (!cpudata->profile_name) { + ret = -ENOMEM; + goto cleanup; + } cpudata->ppdev = platform_profile_register(get_cpu_device(policy->cpu), cpudata->profile_name, @@ -1723,6 +1712,7 @@ static int amd_pstate_unregister_driver(int dummy) static int amd_pstate_change_mode_without_dvr_change(int mode) { int cpu = 0; + int ret; cppc_state = mode; @@ -1730,7 +1720,9 @@ static int amd_pstate_change_mode_without_dvr_change(int mode) return 0; for_each_online_cpu(cpu) { - cppc_set_auto_sel(cpu, (cppc_state == AMD_PSTATE_PASSIVE) ? 0 : 1); + ret = cppc_set_auto_sel(cpu, (cppc_state == AMD_PSTATE_PASSIVE) ? 0 : 1); + if (ret) + return ret; } return 0; @@ -1738,6 +1730,7 @@ static int amd_pstate_change_mode_without_dvr_change(int mode) static int amd_pstate_change_driver_mode(int mode) { + int old_mode = cppc_state; int ret; lockdep_assert_held(&amd_pstate_driver_lock); @@ -1747,10 +1740,16 @@ static int amd_pstate_change_driver_mode(int mode) return ret; ret = amd_pstate_register_driver(mode); - if (ret) - return ret; + if (ret) { + pr_err("Failed to register %s mode, restoring %s mode\n", + amd_pstate_get_mode_string(mode), + amd_pstate_get_mode_string(old_mode)); + if (amd_pstate_register_driver(old_mode)) + pr_err("Failed to restore %s mode\n", + amd_pstate_get_mode_string(old_mode)); + } - return 0; + return ret; } static cppc_mode_transition_fn mode_state_machine[AMD_PSTATE_MAX][AMD_PSTATE_MAX] = { diff --git a/drivers/cpufreq/amd-pstate.h b/drivers/cpufreq/amd-pstate.h index 9f5a81976eae..578465187b7a 100644 --- a/drivers/cpufreq/amd-pstate.h +++ b/drivers/cpufreq/amd-pstate.h @@ -159,6 +159,20 @@ enum amd_pstate_mode { AMD_PSTATE_GUIDED, AMD_PSTATE_MAX, }; + +static inline u8 freq_to_perf(union perf_cached perf, u32 nominal_freq, unsigned int freq_val) +{ + u32 perf_val = DIV_ROUND_UP_ULL((u64)freq_val * perf.nominal_perf, nominal_freq); + + return (u8)clamp(perf_val, perf.lowest_perf, perf.highest_perf); +} + +static inline u32 perf_to_freq(union perf_cached perf, u32 nominal_freq, u8 perf_val) +{ + return DIV_ROUND_UP_ULL((u64)nominal_freq * perf_val, + perf.nominal_perf); +} + const char *amd_pstate_get_mode_string(enum amd_pstate_mode mode); int amd_pstate_get_status(void); int amd_pstate_update_status(const char *buf, size_t size); diff --git a/drivers/cpufreq/qcom-cpufreq-hw.c b/drivers/cpufreq/qcom-cpufreq-hw.c index 874ff3fb9d97..060a460716f7 100644 --- a/drivers/cpufreq/qcom-cpufreq-hw.c +++ b/drivers/cpufreq/qcom-cpufreq-hw.c @@ -322,6 +322,8 @@ static void qcom_get_related_cpus(int index, struct cpumask *m) if (index == args.args[0]) cpumask_set_cpu(cpu, m); + + of_node_put(args.np); } } @@ -554,6 +556,7 @@ static int qcom_cpufreq_hw_cpu_init(struct cpufreq_policy *policy) return ret; index = args.args[0]; + of_node_put(args.np); data = &qcom_cpufreq.data[index]; /* HW should be in enabled state to proceed */ diff --git a/drivers/cpufreq/sparc-us2e-cpufreq.c b/drivers/cpufreq/sparc-us2e-cpufreq.c index a68706406b88..5cda391ad03b 100644 --- a/drivers/cpufreq/sparc-us2e-cpufreq.c +++ b/drivers/cpufreq/sparc-us2e-cpufreq.c @@ -282,12 +282,11 @@ static int us2e_freq_cpu_init(struct cpufreq_policy *policy) table[1].frequency = clock_tick / 2; table[2].driver_data = 2; table[2].frequency = clock_tick / 4; - table[2].driver_data = 3; - table[2].frequency = clock_tick / 6; - table[2].driver_data = 4; - table[2].frequency = clock_tick / 8; - table[2].driver_data = 5; - table[3].frequency = CPUFREQ_TABLE_END; + table[3].driver_data = 3; + table[3].frequency = clock_tick / 6; + table[4].driver_data = 4; + table[4].frequency = clock_tick / 8; + table[5].frequency = CPUFREQ_TABLE_END; policy->cpuinfo.transition_latency = 0; policy->cur = clock_tick; diff --git a/drivers/cpufreq/sti-cpufreq.c b/drivers/cpufreq/sti-cpufreq.c index b15b3142b5fe..144ac0f1d85d 100644 --- a/drivers/cpufreq/sti-cpufreq.c +++ b/drivers/cpufreq/sti-cpufreq.c @@ -263,7 +263,7 @@ static int __init sti_cpufreq_init(void) ddata.cpu = get_cpu_device(0); if (!ddata.cpu) { - dev_err(ddata.cpu, "Failed to get device for CPU0\n"); + pr_err("Failed to get device for CPU0\n"); goto skip_voltage_scaling; } @@ -281,7 +281,7 @@ static int __init sti_cpufreq_init(void) goto register_cpufreq_dt; skip_voltage_scaling: - dev_err(ddata.cpu, "Not doing voltage scaling\n"); + pr_err("Not doing voltage scaling\n"); register_cpufreq_dt: platform_device_register_simple("cpufreq-dt", -1, NULL, 0); diff --git a/drivers/cpufreq/tegra194-cpufreq.c b/drivers/cpufreq/tegra194-cpufreq.c index c6375e14d445..1eb96e9f3310 100644 --- a/drivers/cpufreq/tegra194-cpufreq.c +++ b/drivers/cpufreq/tegra194-cpufreq.c @@ -367,7 +367,7 @@ static void tegra194_get_cpu_ndiv_sysreg(void *ndiv) static int tegra194_get_cpu_ndiv(u32 cpu, u32 cpuid, u32 clusterid, u64 *ndiv) { - return smp_call_function_single(cpu, tegra194_get_cpu_ndiv_sysreg, &ndiv, true); + return smp_call_function_single(cpu, tegra194_get_cpu_ndiv_sysreg, ndiv, true); } static void tegra194_set_cpu_ndiv_sysreg(void *data) diff --git a/drivers/cpuidle/governors/menu.c b/drivers/cpuidle/governors/menu.c index 544a5d593007..eb529d73d4b7 100644 --- a/drivers/cpuidle/governors/menu.c +++ b/drivers/cpuidle/governors/menu.c @@ -284,10 +284,10 @@ static int menu_select(struct cpuidle_driver *drv, struct cpuidle_device *dev, data->bucket = BUCKETS - 1; } - if (latency_req == 0 || - ((data->next_timer_ns < drv->states[1].target_residency_ns || - latency_req < drv->states[1].exit_latency_ns) && - !dev->states_usage[0].disable)) { + if (!dev->states_usage[0].disable && + (latency_req == 0 || + data->next_timer_ns < drv->states[1].target_residency_ns || + latency_req < drv->states[1].exit_latency_ns)) { /* * In this case state[0] will be used no matter what, so return * it right away and keep the tick running if state[0] is a diff --git a/drivers/cpuidle/governors/teo.c b/drivers/cpuidle/governors/teo.c index ac43b9b013b3..906f4f89e365 100644 --- a/drivers/cpuidle/governors/teo.c +++ b/drivers/cpuidle/governors/teo.c @@ -426,6 +426,17 @@ static int teo_select(struct cpuidle_driver *drv, struct cpuidle_device *dev, } } + /* + * If the latency constraint does not allow any of the enabled idle + * states to be used, the candidate state index will be capped to 0 + * by the check below, but state 0 may be disabled. To prevent the + * selection of a disabled state in that case, ensure that + * constraint_idx is at least equal to the index of the first + * enabled idle state. + */ + if (constraint_idx < idx0) + constraint_idx = idx0; + /* * If there is a latency constraint, it may be necessary to select an * idle state shallower than the current candidate one. diff --git a/drivers/crypto/amlogic/amlogic-gxl-cipher.c b/drivers/crypto/amlogic/amlogic-gxl-cipher.c index 29048da6f50a..d78815b0547d 100644 --- a/drivers/crypto/amlogic/amlogic-gxl-cipher.c +++ b/drivers/crypto/amlogic/amlogic-gxl-cipher.c @@ -177,10 +177,13 @@ static int meson_cipher(struct skcipher_request *areq) if (areq->src == areq->dst) { nr_sgs = dma_map_sg(mc->dev, areq->src, sg_nents(areq->src), DMA_BIDIRECTIONAL); - if (!nr_sgs) { - dev_err(mc->dev, "Invalid SG count %d\n", nr_sgs); + if (!nr_sgs || nr_sgs > MAXDESC - 3) { + dev_err(mc->dev, "Invalid BIDIR SG count %d\n", nr_sgs); err = -EINVAL; - goto theend; + + if (nr_sgs) + dma_unmap_sg(mc->dev, areq->src, sg_nents(areq->src), DMA_BIDIRECTIONAL); + goto error_keyiv; } nr_sgd = nr_sgs; } else { @@ -189,14 +192,20 @@ static int meson_cipher(struct skcipher_request *areq) if (!nr_sgs || nr_sgs > MAXDESC - 3) { dev_err(mc->dev, "Invalid SG count %d\n", nr_sgs); err = -EINVAL; - goto theend; + + if (nr_sgs) + dma_unmap_sg(mc->dev, areq->src, sg_nents(areq->src), DMA_TO_DEVICE); + goto error_keyiv; } nr_sgd = dma_map_sg(mc->dev, areq->dst, sg_nents(areq->dst), DMA_FROM_DEVICE); if (!nr_sgd || nr_sgd > MAXDESC - 3) { dev_err(mc->dev, "Invalid SG count %d\n", nr_sgd); err = -EINVAL; - goto theend; + + if (nr_sgd) + dma_unmap_sg(mc->dev, areq->dst, sg_nents(areq->dst), DMA_FROM_DEVICE); + goto error_src; } } @@ -251,6 +260,12 @@ static int meson_cipher(struct skcipher_request *areq) ivsize, 0); } } + goto theend; + +error_src: + dma_unmap_sg(mc->dev, areq->src, sg_nents(areq->src), DMA_TO_DEVICE); +error_keyiv: + dma_unmap_single(mc->dev, phykeyiv, keyivlen, DMA_TO_DEVICE); theend: kfree_sensitive(bkeyiv); kfree_sensitive(backup_iv); diff --git a/drivers/crypto/atmel-aes.c b/drivers/crypto/atmel-aes.c index 8e4de859cadc..84392411b98d 100644 --- a/drivers/crypto/atmel-aes.c +++ b/drivers/crypto/atmel-aes.c @@ -1826,6 +1826,8 @@ static int atmel_aes_authenc_transfer(struct atmel_aes_dev *dd, int err, dd->is_async = true; if (err) return atmel_aes_complete(dd, err); + if (!rctx->textlen) + return atmel_aes_authenc_digest(dd); /* Prepare src and dst scatter-lists to transfer cipher/plain texts. */ src = scatterwalk_ffwd(rctx->src, req->src, req->assoclen); diff --git a/drivers/crypto/atmel-sha.c b/drivers/crypto/atmel-sha.c index 48f54b615504..0e16609321f1 100644 --- a/drivers/crypto/atmel-sha.c +++ b/drivers/crypto/atmel-sha.c @@ -422,6 +422,9 @@ static int atmel_sha_init(struct ahash_request *req) struct atmel_sha_reqctx *ctx = ahash_request_ctx(req); struct atmel_sha_dev *dd = atmel_sha_find_dev(tctx); + if (!dd) + return -ENODEV; + ctx->dd = dd; ctx->flags = 0; @@ -2383,11 +2386,25 @@ static int atmel_sha_authenc_final_done(struct atmel_sha_dev *dd) { struct ahash_request *req = dd->req; struct atmel_sha_authenc_reqctx *authctx = ahash_request_ctx(req); + atmel_aes_authenc_fn_t cb; + struct atmel_aes_dev *aes_dev; size_t i, num_words = authctx->digestlen / sizeof(u32); for (i = 0; i < num_words; ++i) authctx->digest[i] = atmel_sha_read(dd, SHA_REG_DIGEST(i)); + if (!dd->is_async) { + /* + * Return the AES finalizer's status directly for synchronous requests. + * The ahash callback cannot propagate it. + */ + cb = authctx->cb; + aes_dev = authctx->aes_dev; + dd->force_complete = false; + (void)atmel_sha_complete(dd, 0); + return cb(aes_dev, 0, false); + } + return atmel_sha_complete(dd, 0); } diff --git a/drivers/crypto/caam/caamalg_qi.c b/drivers/crypto/caam/caamalg_qi.c index aa779caacfe5..2f2682c8bcd8 100644 --- a/drivers/crypto/caam/caamalg_qi.c +++ b/drivers/crypto/caam/caamalg_qi.c @@ -637,6 +637,8 @@ static int skcipher_setkey(struct crypto_skcipher *skcipher, const u8 *key, ctx->cdata.keylen = keylen; ctx->cdata.key_virt = key; ctx->cdata.key_inline = true; + ctx->cdata.plain_keylen = keylen; + ctx->cdata.key_cmd_opt = 0; /* skcipher encrypt, decrypt shared descriptors */ cnstr_shdsc_skcipher_encap(ctx->sh_desc_enc, &ctx->cdata, ivsize, diff --git a/drivers/crypto/caam/caamalg_qi2.c b/drivers/crypto/caam/caamalg_qi2.c index 6b47bcc16a50..d52706931285 100644 --- a/drivers/crypto/caam/caamalg_qi2.c +++ b/drivers/crypto/caam/caamalg_qi2.c @@ -961,6 +961,8 @@ static int skcipher_setkey(struct crypto_skcipher *skcipher, const u8 *key, ctx->cdata.keylen = keylen; ctx->cdata.key_virt = key; ctx->cdata.key_inline = true; + ctx->cdata.plain_keylen = keylen; + ctx->cdata.key_cmd_opt = 0; /* skcipher_encrypt shared descriptor */ flc = &ctx->flc[ENCRYPT]; diff --git a/drivers/crypto/ccp/ccp-dev-v3.c b/drivers/crypto/ccp/ccp-dev-v3.c index 60a133e23e5f..d92de4ad31ac 100644 --- a/drivers/crypto/ccp/ccp-dev-v3.c +++ b/drivers/crypto/ccp/ccp-dev-v3.c @@ -506,6 +506,8 @@ static int ccp_init(struct ccp_device *ccp) kthread_stop(ccp->cmd_q[i].kthread); sp_free_ccp_irq(ccp->sp, ccp); + if (ccp->use_tasklet) + tasklet_kill(&ccp->irq_tasklet); e_pool: for (i = 0; i < ccp->cmd_q_count; i++) @@ -545,6 +547,8 @@ static void ccp_destroy(struct ccp_device *ccp) kthread_stop(ccp->cmd_q[i].kthread); sp_free_ccp_irq(ccp->sp, ccp); + if (ccp->use_tasklet) + tasklet_kill(&ccp->irq_tasklet); for (i = 0; i < ccp->cmd_q_count; i++) dma_pool_destroy(ccp->cmd_q[i].dma_pool); diff --git a/drivers/crypto/ccp/ccp-dev-v5.c b/drivers/crypto/ccp/ccp-dev-v5.c index dcd6aab51e47..dacde9614e8a 100644 --- a/drivers/crypto/ccp/ccp-dev-v5.c +++ b/drivers/crypto/ccp/ccp-dev-v5.c @@ -995,6 +995,8 @@ static int ccp5_init(struct ccp_device *ccp) e_irq: sp_free_ccp_irq(ccp->sp, ccp); + if (ccp->use_tasklet) + tasklet_kill(&ccp->irq_tasklet); e_pool: for (i = 0; i < ccp->cmd_q_count; i++) @@ -1046,6 +1048,8 @@ static void ccp5_destroy(struct ccp_device *ccp) kthread_stop(ccp->cmd_q[i].kthread); sp_free_ccp_irq(ccp->sp, ccp); + if (ccp->use_tasklet) + tasklet_kill(&ccp->irq_tasklet); /* Flush the cmd and backlog queue */ while (!list_empty(&ccp->cmd)) { diff --git a/drivers/crypto/ccp/sfs.c b/drivers/crypto/ccp/sfs.c index a4777839790b..530141f8bc74 100644 --- a/drivers/crypto/ccp/sfs.c +++ b/drivers/crypto/ccp/sfs.c @@ -111,13 +111,13 @@ static long sfs_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) struct sfs_device *sfs_dev; int ret = 0; + guard(mutex)(&sfs_ioctl_mutex); + if (!psp_master || !psp_master->sfs_data) return -ENODEV; sfs_dev = psp_master->sfs_data; - guard(mutex)(&sfs_ioctl_mutex); - switch (cmd) { case SFSIOCFWVERS: dev_dbg(sfs_dev->dev, "in SFSIOCFWVERS\n"); @@ -191,8 +191,11 @@ static void sfs_exit(struct kref *ref) void sfs_dev_destroy(struct psp_device *psp) { - struct sfs_device *sfs_dev = psp->sfs_data; + struct sfs_device *sfs_dev; + + guard(mutex)(&sfs_ioctl_mutex); + sfs_dev = psp->sfs_data; if (!sfs_dev) return; diff --git a/drivers/crypto/hisilicon/hpre/hpre_crypto.c b/drivers/crypto/hisilicon/hpre/hpre_crypto.c index 0861f06da8ee..6ca34f3bf9ff 100644 --- a/drivers/crypto/hisilicon/hpre/hpre_crypto.c +++ b/drivers/crypto/hisilicon/hpre/hpre_crypto.c @@ -1411,8 +1411,6 @@ static void hpre_ecdh_hw_data_clr_all(struct hpre_ctx *ctx, if (unlikely(dma_mapping_error(dev, dma))) return; - if (req->dst) - dma_free_coherent(dev, ctx->key_sz << 1, req->dst, dma); if (dst) dma_unmap_single(dev, dma, ctx->key_sz << 1, DMA_FROM_DEVICE); } diff --git a/drivers/crypto/inside-secure/eip93/eip93-regs.h b/drivers/crypto/inside-secure/eip93/eip93-regs.h index 96d28c6651bd..1d726bcdd77f 100644 --- a/drivers/crypto/inside-secure/eip93/eip93-regs.h +++ b/drivers/crypto/inside-secure/eip93/eip93-regs.h @@ -281,7 +281,7 @@ #define EIP93_SA_CMD_HASH_CRYPT_OFFSET GENMASK(23, 16) #define EIP93_SA_CMD_BYTE_OFFSET BIT(13) /* 0: CRYPT_OFFSET in 32bit word 1: CRYPT_OFFSET in 8bit bytes */ #define EIP93_SA_CMD_HMAC BIT(12) -#define EIP93_SA_CMD_SSL_MAC BIT(12) +#define EIP93_SA_CMD_SSL_MAC BIT(11) /* This mask can be either used for ARC4 or AES */ #define EIP93_SA_CMD_CHIPER_MODE GENMASK(9, 8) /* AES or DES operations */ diff --git a/drivers/crypto/inside-secure/safexcel_hash.c b/drivers/crypto/inside-secure/safexcel_hash.c index 3402e570d045..7c68118fbb05 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_prepareenckey(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 b88febf53a19..e13db9ede0fa 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_obj(*key_val); 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_obj(*sec); - 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/crypto/intel/qat/qat_common/adf_init.c b/drivers/crypto/intel/qat/qat_common/adf_init.c index 3e39c53814de..81cb5e6c9f4a 100644 --- a/drivers/crypto/intel/qat/qat_common/adf_init.c +++ b/drivers/crypto/intel/qat/qat_common/adf_init.c @@ -260,13 +260,23 @@ static int adf_dev_start(struct adf_accel_dev *accel_dev) clear_bit(ADF_STATUS_STARTING, &accel_dev->status); set_bit(ADF_STATUS_STARTED, &accel_dev->status); - if (!list_empty(&accel_dev->crypto_list) && - (qat_algs_register() || qat_asym_algs_register())) { - dev_err(&GET_DEV(accel_dev), - "Failed to register crypto algs\n"); - set_bit(ADF_STATUS_STARTING, &accel_dev->status); - clear_bit(ADF_STATUS_STARTED, &accel_dev->status); - return -EFAULT; + if (!list_empty(&accel_dev->crypto_list)) { + ret = qat_algs_register(); + if (ret) { + dev_err(&GET_DEV(accel_dev), "Failed to register crypto algs\n"); + set_bit(ADF_STATUS_STARTING, &accel_dev->status); + clear_bit(ADF_STATUS_STARTED, &accel_dev->status); + return ret; + } + + ret = qat_asym_algs_register(); + if (ret) { + dev_err(&GET_DEV(accel_dev), "Failed to register crypto asym algs\n"); + qat_algs_unregister(); + set_bit(ADF_STATUS_STARTING, &accel_dev->status); + clear_bit(ADF_STATUS_STARTED, &accel_dev->status); + return ret; + } } set_bit(ADF_STATUS_CRYPTO_ALGS_REGISTERED, &accel_dev->status); diff --git a/drivers/crypto/intel/qat/qat_common/adf_isr.c b/drivers/crypto/intel/qat/qat_common/adf_isr.c index 159e91a50106..0df4b398508e 100644 --- a/drivers/crypto/intel/qat/qat_common/adf_isr.c +++ b/drivers/crypto/intel/qat/qat_common/adf_isr.c @@ -70,6 +70,7 @@ void adf_enable_vf2pf_interrupts(struct adf_accel_dev *accel_dev, u32 vf_mask) void adf_enable_all_vf2pf_interrupts(struct adf_accel_dev *accel_dev, u32 num_vfs) { void __iomem *pmisc_addr = adf_get_pmisc_base(accel_dev); + struct adf_pfvf_ops *pfvf_ops = GET_PFVF_OPS(accel_dev); unsigned long flags; u32 vf_mask; @@ -79,7 +80,19 @@ void adf_enable_all_vf2pf_interrupts(struct adf_accel_dev *accel_dev, u32 num_vf spin_lock_irqsave(&accel_dev->pf.vf2pf_ints_lock, flags); WRITE_ONCE(accel_dev->pf.vf2pf_disabled, false); - GET_PFVF_OPS(accel_dev)->enable_vf2pf_interrupts(pmisc_addr, vf_mask); + /* + * A VF2PF interrupt is only generated when a source transitions from + * masked to unmasked. A VF may write to its VF2PF CSR while the source + * is masked or while the MSI-X vectors are torn down, for example + * during a device reset, leaving the source latched with no interrupt + * pending. The FLR performed as part of a device reset returns the mask + * register to its default value, which leaves all the sources unmasked, + * so simply unmasking is not guaranteed to be a transition. Mask all the + * sources first, so that unmasking always generates an interrupt for + * the sources latched in the meantime. + */ + pfvf_ops->disable_all_vf2pf_interrupts(pmisc_addr); + pfvf_ops->enable_vf2pf_interrupts(pmisc_addr, vf_mask); spin_unlock_irqrestore(&accel_dev->pf.vf2pf_ints_lock, flags); } diff --git a/drivers/crypto/intel/qat/qat_common/adf_sysfs_kpt.c b/drivers/crypto/intel/qat/qat_common/adf_sysfs_kpt.c index 1f733ae80bdf..a0db98f33f1f 100644 --- a/drivers/crypto/intel/qat/qat_common/adf_sysfs_kpt.c +++ b/drivers/crypto/intel/qat/qat_common/adf_sysfs_kpt.c @@ -31,6 +31,7 @@ static ssize_t enable_store(struct device *dev, struct device_attribute *attr, struct adf_hw_device_data *hw_data; struct adf_accel_dev *accel_dev; bool enable; + int svc; int ret; accel_dev = adf_devmgr_pci_to_accel_dev(to_pci_dev(dev)); @@ -38,14 +39,25 @@ static ssize_t enable_store(struct device *dev, struct device_attribute *attr, return -EINVAL; if (adf_dev_started(accel_dev)) { - dev_info(dev, "Device qat_dev%d must be down before enabling KPT\n", + dev_info(dev, "Device qat_dev%d must be down before changing KPT state\n", accel_dev->accel_id); return -EINVAL; } - if (adf_get_service_enabled(accel_dev) != SVC_ASYM) { - dev_info(dev, "KPT can only be enabled when the asymmetric service is enabled\n"); - return -EINVAL; + ret = kstrtobool(buf, &enable); + if (ret) + return ret; + + if (enable) { + svc = adf_get_service_enabled(accel_dev); + if (svc < 0) + return svc; + + if (svc != SVC_ASYM) { + dev_info(dev, + "KPT can only be enabled when the asymmetric crypto service is enabled\n"); + return -EINVAL; + } } hw_data = GET_HW_DATA(accel_dev); @@ -59,10 +71,6 @@ static ssize_t enable_store(struct device *dev, struct device_attribute *attr, if (!hw_data->accel_capabilities_mask) return -EINVAL; - ret = kstrtobool(buf, &enable); - if (ret) - return ret; - user_data = GET_KPT_USER_DATA(accel_dev); user_data->enable = enable; diff --git a/drivers/crypto/intel/qat/qat_common/qat_algs.c b/drivers/crypto/intel/qat/qat_common/qat_algs.c index 91663805d9e6..f954e7c0e4d0 100644 --- a/drivers/crypto/intel/qat/qat_common/qat_algs.c +++ b/drivers/crypto/intel/qat/qat_common/qat_algs.c @@ -1320,19 +1320,22 @@ int qat_algs_register(void) ret = crypto_register_skciphers(qat_skciphers, ARRAY_SIZE(qat_skciphers)); if (ret) - goto unlock; + goto err_dec; ret = crypto_register_aeads(qat_aeads, ARRAY_SIZE(qat_aeads)); if (ret) - goto unreg_algs; + goto err_unreg_skciphers; -unlock: mutex_unlock(&algs_lock); - return ret; + return 0; -unreg_algs: +err_unreg_skciphers: crypto_unregister_skciphers(qat_skciphers, ARRAY_SIZE(qat_skciphers)); - goto unlock; +err_dec: + active_devs--; +unlock: + mutex_unlock(&algs_lock); + return ret; } void qat_algs_unregister(void) diff --git a/drivers/crypto/intel/qat/qat_common/qat_asym_algs.c b/drivers/crypto/intel/qat/qat_common/qat_asym_algs.c index 75c15c8e41db..77d59e977472 100644 --- a/drivers/crypto/intel/qat/qat_common/qat_asym_algs.c +++ b/drivers/crypto/intel/qat/qat_common/qat_asym_algs.c @@ -535,8 +535,10 @@ static int qat_dh_init_tfm(struct crypto_kpp *tfm) return -EINVAL; ctx->ftfm = crypto_alloc_kpp(alg, 0, CRYPTO_ALG_NEED_FALLBACK); - if (IS_ERR(ctx->ftfm)) + if (IS_ERR(ctx->ftfm)) { + qat_crypto_put_instance(inst); return PTR_ERR(ctx->ftfm); + } crypto_kpp_set_flags(ctx->ftfm, crypto_kpp_get_flags(tfm)); @@ -987,7 +989,7 @@ static int qat_rsa_set_n(struct qat_rsa_ctx *ctx, const char *value, const char *ptr = value; int ret; - while (!*ptr && vlen) { + while (vlen && !*ptr) { ptr++; vlen--; } @@ -1018,7 +1020,7 @@ static int qat_rsa_set_e(struct qat_rsa_ctx *ctx, const char *value, struct device *dev = &GET_DEV(inst->accel_dev); const char *ptr = value; - while (!*ptr && vlen) { + while (vlen && !*ptr) { ptr++; vlen--; } @@ -1044,7 +1046,7 @@ static int qat_rsa_set_d(struct qat_rsa_ctx *ctx, const char *value, const char *ptr = value; int ret; - while (!*ptr && vlen) { + while (vlen && !*ptr) { ptr++; vlen--; } @@ -1067,7 +1069,7 @@ static int qat_rsa_set_d(struct qat_rsa_ctx *ctx, const char *value, static void qat_rsa_drop_leading_zeros(const char **ptr, unsigned int *len) { - while (!**ptr && *len) { + while (*len && !**ptr) { (*ptr)++; (*len)--; } @@ -1338,13 +1340,25 @@ int qat_asym_algs_register(void) int ret = 0; mutex_lock(&algs_lock); - if (++active_devs == 1) { - rsa.base.cra_flags = 0; - ret = crypto_register_akcipher(&rsa); - if (ret) - goto unlock; - ret = crypto_register_kpp(&dh); - } + if (++active_devs != 1) + goto unlock; + + rsa.base.cra_flags = 0; + ret = crypto_register_akcipher(&rsa); + if (ret) + goto err_dec; + + ret = crypto_register_kpp(&dh); + if (ret) + goto err_unreg_akcipher; + + mutex_unlock(&algs_lock); + return 0; + +err_unreg_akcipher: + crypto_unregister_akcipher(&rsa); +err_dec: + active_devs--; unlock: mutex_unlock(&algs_lock); return ret; diff --git a/drivers/crypto/mxs-dcp.c b/drivers/crypto/mxs-dcp.c index c75a06999787..d104d958cb61 100644 --- a/drivers/crypto/mxs-dcp.c +++ b/drivers/crypto/mxs-dcp.c @@ -473,6 +473,9 @@ static int mxs_dcp_aes_enqueue(struct skcipher_request *req, int enc, int ecb) struct dcp_aes_req_ctx *rctx = skcipher_request_ctx(req); int ret; + if (!req->cryptlen) + return 0; + if (unlikely(actx->key_len != AES_KEYSIZE_128 && !actx->key_referenced)) return mxs_dcp_block_fallback(req, enc); diff --git a/drivers/crypto/starfive/jh7110-cryp.c b/drivers/crypto/starfive/jh7110-cryp.c index 842f76b0f114..856290347b95 100644 --- a/drivers/crypto/starfive/jh7110-cryp.c +++ b/drivers/crypto/starfive/jh7110-cryp.c @@ -120,9 +120,17 @@ static int starfive_cryp_probe(struct platform_device *pdev) return dev_err_probe(&pdev->dev, PTR_ERR(cryp->rst), "Error getting hardware reset line\n"); - clk_prepare_enable(cryp->hclk); - clk_prepare_enable(cryp->ahb); - reset_control_deassert(cryp->rst); + ret = clk_prepare_enable(cryp->hclk); + if (ret) + return ret; + + ret = clk_prepare_enable(cryp->ahb); + if (ret) + goto disable_hclk; + + ret = reset_control_deassert(cryp->rst); + if (ret) + goto disable_ahb; spin_lock(&dev_list.lock); list_add(&cryp->list, &dev_list.dev_list); @@ -170,9 +178,11 @@ static int starfive_cryp_probe(struct platform_device *pdev) list_del(&cryp->list); spin_unlock(&dev_list.lock); - clk_disable_unprepare(cryp->hclk); - clk_disable_unprepare(cryp->ahb); reset_control_assert(cryp->rst); +disable_ahb: + clk_disable_unprepare(cryp->ahb); +disable_hclk: + clk_disable_unprepare(cryp->hclk); return ret; } diff --git a/drivers/crypto/talitos.c b/drivers/crypto/talitos.c index fa96b6bf17e3..f9eb06aa487e 100644 --- a/drivers/crypto/talitos.c +++ b/drivers/crypto/talitos.c @@ -3355,21 +3355,13 @@ static int talitos_probe_irq(struct platform_device *ofdev) int err; bool is_sec1 = has_ftr_sec1(priv); - priv->irq[0] = platform_get_irq(ofdev, 0); - if (priv->irq[0] < 0) - return priv->irq[0]; - if (is_sec1) { err = request_irq(priv->irq[0], talitos1_interrupt_4ch, 0, dev_driver_string(dev), dev); goto primary_out; } - priv->irq[1] = platform_get_irq_optional(ofdev, 1); - if (priv->irq[1] == -EPROBE_DEFER) - return priv->irq[1]; - - /* get the primary irq line */ + /* single (or primary) irq line */ if (priv->irq[1] < 0) { err = request_irq(priv->irq[0], talitos2_interrupt_4ch, 0, dev_driver_string(dev), dev); @@ -3381,7 +3373,7 @@ static int talitos_probe_irq(struct platform_device *ofdev) if (err) goto primary_out; - /* get the secondary irq line */ + /* secondary irq line */ err = request_irq(priv->irq[1], talitos2_interrupt_ch1_3, 0, dev_driver_string(dev), dev); if (err) { @@ -3394,7 +3386,9 @@ static int talitos_probe_irq(struct platform_device *ofdev) primary_out: if (err) { dev_err(dev, "failed to request primary irq\n"); + /* neither line is requested, keep remove() from freeing them */ priv->irq[0] = 0; + priv->irq[1] = 0; } return err; @@ -3406,12 +3400,27 @@ static int talitos_probe(struct platform_device *ofdev) struct device_node *np = ofdev->dev.of_node; struct talitos_private *priv; unsigned int num_channels; + void __iomem *reg; int i, err; int stride; + int irq0; + int irq1; if (of_property_read_u32(np, "fsl,num-channels", &num_channels)) return -EINVAL; + irq0 = platform_get_irq(ofdev, 0); + if (irq0 < 0) + return irq0; + + irq1 = platform_get_irq_optional(ofdev, 1); + if (irq1 == -EPROBE_DEFER) + return irq1; + + reg = devm_platform_ioremap_resource(ofdev, 0); + if (IS_ERR(reg)) + return PTR_ERR(reg); + priv = devm_kzalloc(dev, struct_size(priv, chan, num_channels), GFP_KERNEL); if (!priv) return -ENOMEM; @@ -3426,12 +3435,7 @@ static int talitos_probe(struct platform_device *ofdev) spin_lock_init(&priv->reg_lock); - priv->reg = devm_platform_ioremap_resource(ofdev, 0); - if (IS_ERR(priv->reg)) { - dev_err(dev, "failed to of_iomap\n"); - err = PTR_ERR(priv->reg); - goto err_out; - } + priv->reg = reg; /* get SEC version capabilities from device tree */ of_property_read_u32(np, "fsl,channel-fifo-len", &priv->chfifo_len); @@ -3482,9 +3486,7 @@ static int talitos_probe(struct platform_device *ofdev) stride = TALITOS2_CH_STRIDE; } - err = talitos_probe_irq(ofdev); - if (err) - goto err_out; + priv->irq[0] = irq0; if (has_ftr_sec1(priv)) { if (priv->num_channels == 1) @@ -3494,6 +3496,7 @@ static int talitos_probe(struct platform_device *ofdev) tasklet_init(&priv->done_task[0], talitos1_done_4ch, (unsigned long)dev); } else { + priv->irq[1] = irq1; if (priv->irq[1] > 0) { tasklet_init(&priv->done_task[0], talitos2_done_ch0_2, (unsigned long)dev); @@ -3525,7 +3528,7 @@ static int talitos_probe(struct platform_device *ofdev) if (!priv->chan[i].fifo) { dev_err(dev, "failed to allocate request fifo %d\n", i); err = -ENOMEM; - goto err_out; + goto err_noirq; } atomic_set(&priv->chan[i].submit_count, @@ -3538,9 +3541,14 @@ static int talitos_probe(struct platform_device *ofdev) err = init_device(dev); if (err) { dev_err(dev, "failed to initialize device\n"); - goto err_out; + goto err_noirq; } + /* enable interrupts once the channel fifos and tasklets are set up */ + err = talitos_probe_irq(ofdev); + if (err) + goto err_out; + /* register the RNG, if available */ if (hw_supports(dev, DESC_HDR_SEL0_RNG)) { err = talitos_register_rng(dev); @@ -3598,6 +3606,10 @@ static int talitos_probe(struct platform_device *ofdev) return 0; +err_noirq: + /* the irq numbers are known, but the lines are not requested yet */ + priv->irq[0] = 0; + priv->irq[1] = 0; err_out: talitos_remove(ofdev); diff --git a/drivers/cxl/core/cdat.c b/drivers/cxl/core/cdat.c index 5c9f07262513..df9261ba84e5 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_obj(*res_xa); - 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/core.h b/drivers/cxl/core/core.h index 35eaf636adc9..79918fde1575 100644 --- a/drivers/cxl/core/core.h +++ b/drivers/cxl/core/core.h @@ -178,11 +178,7 @@ static inline struct device *port_to_host(struct cxl_port *port) static inline struct device *dport_to_host(struct cxl_dport *dport) { - struct cxl_port *port = dport->port; - - if (is_cxl_root(port)) - return port->uport_dev; - return &port->dev; + return cxl_port_dport_host(dport->port); } #ifdef CONFIG_CXL_RAS void cxl_ras_init(void); @@ -217,10 +213,10 @@ int cxl_port_get_possible_dports(struct cxl_port *port); #ifdef CONFIG_CXL_FEATURES struct cxl_feat_entry * cxl_feature_info(struct cxl_features_state *cxlfs, const uuid_t *uuid); -size_t cxl_get_feature(struct cxl_mailbox *cxl_mbox, const uuid_t *feat_uuid, - enum cxl_get_feat_selection selection, - void *feat_out, size_t feat_out_size, u16 offset, - u16 *return_code); +ssize_t cxl_get_feature(struct cxl_mailbox *cxl_mbox, const uuid_t *feat_uuid, + enum cxl_get_feat_selection selection, + void *feat_out, size_t feat_out_size, u16 offset, + u16 *return_code); int cxl_set_feature(struct cxl_mailbox *cxl_mbox, const uuid_t *feat_uuid, u8 feat_version, const void *feat_data, size_t feat_data_size, u32 feat_flag, u16 offset, diff --git a/drivers/cxl/core/edac.c b/drivers/cxl/core/edac.c index b321971fef58..34b81e8dfbbb 100644 --- a/drivers/cxl/core/edac.c +++ b/drivers/cxl/core/edac.c @@ -78,7 +78,7 @@ static int cxl_mem_scrub_get_attrbs(struct cxl_mailbox *cxl_mbox, u8 *cap, u16 *cycle, u8 *flags, u8 *min_cycle) { size_t rd_data_size = sizeof(struct cxl_scrub_rd_attrbs); - size_t data_size; + ssize_t data_size; struct cxl_scrub_rd_attrbs *rd_attrbs __free(kfree) = kzalloc(rd_data_size, GFP_KERNEL); if (!rd_attrbs) @@ -87,7 +87,9 @@ static int cxl_mem_scrub_get_attrbs(struct cxl_mailbox *cxl_mbox, u8 *cap, data_size = cxl_get_feature(cxl_mbox, &CXL_FEAT_PATROL_SCRUB_UUID, CXL_GET_FEAT_SEL_CURRENT_VALUE, rd_attrbs, rd_data_size, 0, NULL); - if (!data_size) + if (data_size < 0) + return data_size; + if ((size_t)data_size != rd_data_size) return -EIO; *cap = rd_attrbs->scrub_cycle_cap; @@ -551,7 +553,7 @@ static int cxl_mem_ecs_get_attrbs(struct device *dev, struct cxl_mailbox *cxl_mbox = &cxlmd->cxlds->cxl_mbox; struct cxl_ecs_fru_rd_attrbs *fru_rd_attrbs; size_t rd_data_size; - size_t data_size; + ssize_t data_size; rd_data_size = cxl_ecs_ctx->get_feat_size; @@ -563,7 +565,9 @@ static int cxl_mem_ecs_get_attrbs(struct device *dev, data_size = cxl_get_feature(cxl_mbox, &CXL_FEAT_ECS_UUID, CXL_GET_FEAT_SEL_CURRENT_VALUE, rd_attrbs, rd_data_size, 0, NULL); - if (!data_size) + if (data_size < 0) + return data_size; + if ((size_t)data_size != rd_data_size) return -EIO; fru_rd_attrbs = rd_attrbs->fru_attrbs; @@ -583,7 +587,7 @@ static int cxl_mem_ecs_set_attrbs(struct device *dev, struct cxl_ecs_fru_wr_attrbs *fru_wr_attrbs; size_t rd_data_size, wr_data_size; u16 num_media_frus, count; - size_t data_size; + ssize_t data_size; num_media_frus = cxl_ecs_ctx->num_media_frus; rd_data_size = cxl_ecs_ctx->get_feat_size; @@ -596,7 +600,9 @@ static int cxl_mem_ecs_set_attrbs(struct device *dev, data_size = cxl_get_feature(cxl_mbox, &CXL_FEAT_ECS_UUID, CXL_GET_FEAT_SEL_CURRENT_VALUE, rd_attrbs, rd_data_size, 0, NULL); - if (!data_size) + if (data_size < 0) + return data_size; + if ((size_t)data_size != rd_data_size) return -EIO; struct cxl_ecs_wr_attrbs *wr_attrbs __free(kvfree) = @@ -1264,7 +1270,7 @@ cxl_mem_sparing_get_attrbs(struct cxl_mem_sparing_context *cxl_sparing_ctx) struct cxl_memdev *cxlmd = cxl_sparing_ctx->cxlmd; struct cxl_mailbox *cxl_mbox = &cxlmd->cxlds->cxl_mbox; u16 restriction_flags; - size_t data_size; + ssize_t data_size; u16 return_code; struct cxl_memdev_sparing_rd_attrbs *rd_attrbs __free(kfree) = kzalloc(rd_data_size, GFP_KERNEL); @@ -1274,7 +1280,9 @@ cxl_mem_sparing_get_attrbs(struct cxl_mem_sparing_context *cxl_sparing_ctx) data_size = cxl_get_feature(cxl_mbox, &cxl_sparing_ctx->repair_uuid, CXL_GET_FEAT_SEL_CURRENT_VALUE, rd_attrbs, rd_data_size, 0, &return_code); - if (!data_size) + if (data_size < 0) + return data_size; + if ((size_t)data_size != rd_data_size) return -EIO; cxl_sparing_ctx->op_class = rd_attrbs->hdr.op_class; @@ -1750,7 +1758,7 @@ static int cxl_mem_ppr_get_attrbs(struct cxl_ppr_context *cxl_ppr_ctx) struct cxl_memdev *cxlmd = cxl_ppr_ctx->cxlmd; struct cxl_mailbox *cxl_mbox = &cxlmd->cxlds->cxl_mbox; u16 restriction_flags; - size_t data_size; + ssize_t data_size; u16 return_code; struct cxl_memdev_ppr_rd_attrbs *rd_attrbs __free(kfree) = @@ -1761,7 +1769,9 @@ static int cxl_mem_ppr_get_attrbs(struct cxl_ppr_context *cxl_ppr_ctx) data_size = cxl_get_feature(cxl_mbox, &cxl_ppr_ctx->repair_uuid, CXL_GET_FEAT_SEL_CURRENT_VALUE, rd_attrbs, rd_data_size, 0, &return_code); - if (!data_size) + if (data_size < 0) + return data_size; + if ((size_t)data_size != rd_data_size) return -EIO; cxl_ppr_ctx->op_class = rd_attrbs->hdr.op_class; diff --git a/drivers/cxl/core/features.c b/drivers/cxl/core/features.c index 754fe5eb4b76..8024c2dcae1d 100644 --- a/drivers/cxl/core/features.c +++ b/drivers/cxl/core/features.c @@ -220,10 +220,10 @@ int devm_cxl_setup_features(struct cxl_dev_state *cxlds) } EXPORT_SYMBOL_NS_GPL(devm_cxl_setup_features, "CXL"); -size_t cxl_get_feature(struct cxl_mailbox *cxl_mbox, const uuid_t *feat_uuid, - enum cxl_get_feat_selection selection, - void *feat_out, size_t feat_out_size, u16 offset, - u16 *return_code) +ssize_t cxl_get_feature(struct cxl_mailbox *cxl_mbox, const uuid_t *feat_uuid, + enum cxl_get_feat_selection selection, + void *feat_out, size_t feat_out_size, u16 offset, + u16 *return_code) { size_t data_to_rd_size; struct cxl_mbox_get_feat_in pi; @@ -232,10 +232,13 @@ size_t cxl_get_feature(struct cxl_mailbox *cxl_mbox, const uuid_t *feat_uuid, int rc; if (return_code) - *return_code = CXL_MBOX_CMD_RC_INPUT; + *return_code = CXL_MBOX_CMD_RC_SUCCESS; if (!feat_out || !feat_out_size) - return 0; + return -EINVAL; + + if (feat_out_size > U16_MAX - offset) + return -EINVAL; uuid_copy(&pi.uuid, feat_uuid); pi.selection = selection; @@ -256,17 +259,25 @@ size_t cxl_get_feature(struct cxl_mailbox *cxl_mbox, const uuid_t *feat_uuid, .min_out = data_to_rd_size, }; rc = cxl_internal_send_cmd(cxl_mbox, &mbox_cmd); + /* + * Per CXL r4.0 8.2.10.6.2, when Offset + Count runs past the + * end of the Feature the device returns only the bytes up to + * the Feature size. cxl_internal_send_cmd() reports that as + * -EIO with a short payload, so stop and return what arrived. + */ + if (rc == -EIO && mbox_cmd.size_out && + mbox_cmd.size_out < data_to_rd_size) { + data_rcvd_size += mbox_cmd.size_out; + break; + } if (rc < 0 || !mbox_cmd.size_out) { if (return_code) *return_code = mbox_cmd.return_code; - return 0; + return rc < 0 ? rc : -EIO; } data_rcvd_size += mbox_cmd.size_out; } while (data_rcvd_size < feat_out_size); - if (return_code) - *return_code = CXL_MBOX_CMD_RC_SUCCESS; - return data_rcvd_size; } @@ -286,7 +297,10 @@ int cxl_set_feature(struct cxl_mailbox *cxl_mbox, size_t hdr_size; if (return_code) - *return_code = CXL_MBOX_CMD_RC_INPUT; + *return_code = CXL_MBOX_CMD_RC_SUCCESS; + + if (feat_data_size > U16_MAX - offset) + return -EINVAL; struct cxl_mbox_set_feat_in *pi __free(kfree) = kzalloc(cxl_mbox->payload_size, GFP_KERNEL); @@ -334,11 +348,8 @@ int cxl_set_feature(struct cxl_mailbox *cxl_mbox, } data_sent_size += data_in_size; - if (data_sent_size >= feat_data_size) { - if (return_code) - *return_code = CXL_MBOX_CMD_RC_SUCCESS; + if (data_sent_size >= feat_data_size) return 0; - } if ((feat_data_size - data_sent_size) <= (cxl_mbox->payload_size - hdr_size)) { data_in_size = feat_data_size - data_sent_size; @@ -462,6 +473,7 @@ static void *cxlctl_get_feature(struct cxl_features_state *cxlfs, const struct cxl_mbox_get_feat_in *feat_in; u16 offset, count, return_code; size_t out_size = *out_len; + ssize_t data_size; if (rpc_in->op_size != sizeof(*feat_in)) return ERR_PTR(-EINVAL); @@ -482,16 +494,20 @@ static void *cxlctl_get_feature(struct cxl_features_state *cxlfs, if (!rpc_out) return ERR_PTR(-ENOMEM); - out_size = cxl_get_feature(cxl_mbox, &feat_in->uuid, - feat_in->selection, rpc_out->payload, - count, offset, &return_code); + data_size = cxl_get_feature(cxl_mbox, &feat_in->uuid, + feat_in->selection, rpc_out->payload, + count, offset, &return_code); + if (data_size <= 0 && + return_code == CXL_MBOX_CMD_RC_SUCCESS) + return ERR_PTR(data_size ?: -EIO); *out_len = sizeof(struct fwctl_rpc_cxl_out); - if (!out_size) { + if (data_size <= 0) { rpc_out->size = 0; rpc_out->retval = return_code; return no_free_ptr(rpc_out); } + out_size = data_size; rpc_out->size = out_size; rpc_out->retval = CXL_MBOX_CMD_RC_SUCCESS; *out_len += out_size; @@ -536,6 +552,8 @@ static void *cxlctl_set_feature(struct cxl_features_state *cxlfs, rc = cxl_set_feature(cxl_mbox, &feat_in->uuid, feat_in->version, feat_in->feat_data, data_size, flags, offset, &return_code); + if (rc && return_code == CXL_MBOX_CMD_RC_SUCCESS) + return ERR_PTR(rc); *out_len = sizeof(*rpc_out); if (rc) { rpc_out->retval = return_code; diff --git a/drivers/cxl/core/hdm.c b/drivers/cxl/core/hdm.c index 0c80b76a5f9b..cb24901dd289 100644 --- a/drivers/cxl/core/hdm.c +++ b/drivers/cxl/core/hdm.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only /* Copyright(c) 2022 Intel Corporation. All rights reserved. */ #include +#include #include #include @@ -76,6 +77,8 @@ static void parse_hdm_decoder_caps(struct cxl_hdm *cxlhdm) hdm_cap = readl(cxlhdm->regs.hdm_decoder + CXL_HDM_DECODER_CAP_OFFSET); cxlhdm->decoder_count = cxl_hdm_decoder_count(hdm_cap); + + /* target_count is a direct count (1h..8h), not 0-based like decoder_count */ cxlhdm->target_count = FIELD_GET(CXL_HDM_DECODER_TARGET_COUNT_MASK, hdm_cap); if (FIELD_GET(CXL_HDM_DECODER_INTERLEAVE_11_8, hdm_cap)) @@ -953,7 +956,8 @@ static int cxl_setup_hdm_decoder_from_dvsec( * change the range registers at run time. */ cxld->flags |= CXL_DECODER_F_ENABLE | CXL_DECODER_F_LOCK; - port->commit_end = cxld->id; + scoped_guard(rwsem_write, &cxl_rwsem.region) + port->commit_end = cxld->id; rc = devm_cxl_dpa_reserve(cxled, *dpa_base, len, 0); if (rc) { @@ -973,15 +977,12 @@ static int init_hdm_decoder(struct cxl_port *port, struct cxl_decoder *cxld, u64 *dpa_base, struct cxl_endpoint_dvsec_info *info) { struct cxl_endpoint_decoder *cxled = NULL; + u8 target_id[CXL_HDM_DECODER0_TL_TARGETS]; u64 size, base, skip, dpa_size, lo, hi; bool committed; u32 remainder; int i, rc; u32 ctrl; - union { - u64 value; - unsigned char target_id[8]; - } target_list; if (should_emulate_decoders(info)) return cxl_setup_hdm_decoder_from_dvsec(port, cxld, dpa_base, @@ -1084,11 +1085,22 @@ static int init_hdm_decoder(struct cxl_port *port, struct cxl_decoder *cxld, cxld->interleave_ways, cxld->interleave_granularity); if (!cxled) { - lo = readl(hdm + CXL_HDM_DECODER0_TL_LOW(which)); - hi = readl(hdm + CXL_HDM_DECODER0_TL_HIGH(which)); - target_list.value = (hi << 32) + lo; + struct cxl_switch_decoder *cxlsd = to_cxl_switch_decoder(&cxld->dev); + + if (cxld->interleave_ways > cxlsd->nr_targets) { + dev_err(&port->dev, + "decoder%d.%d: interleave ways: %d exceeds targets: %d\n", + port->id, cxld->id, cxld->interleave_ways, + cxlsd->nr_targets); + return -ENXIO; + } + + put_unaligned_le32(readl(hdm + CXL_HDM_DECODER0_TL_LOW(which)), + &target_id[0]); + put_unaligned_le32(readl(hdm + CXL_HDM_DECODER0_TL_HIGH(which)), + &target_id[4]); for (i = 0; i < cxld->interleave_ways; i++) - cxld->target_map[i] = target_list.target_id[i]; + cxld->target_map[i] = target_id[i]; return 0; } @@ -1148,6 +1160,14 @@ static void cxl_settle_decoders(struct cxl_hdm *cxlhdm) msleep(20); } +static void cxl_reset_commit_end(void *data) +{ + struct cxl_port *port = data; + + guard(rwsem_write)(&cxl_rwsem.region); + port->commit_end = -1; +} + /** * devm_cxl_enumerate_decoders - add decoder objects per HDM register set * @cxlhdm: Structure to populate with HDM capabilities @@ -1158,13 +1178,33 @@ static int devm_cxl_enumerate_decoders(struct cxl_hdm *cxlhdm, { void __iomem *hdm = cxlhdm->regs.hdm_decoder; struct cxl_port *port = cxlhdm->port; - int i; u64 dpa_base = 0; + int i, rc; + + /* + * Per CXL 4.0 8.2.4.20.1 Target Count is the number of target ports + * per decoder, max 8. Endpoint decoders have no targets. + */ + if (!is_cxl_endpoint(port) && + (cxlhdm->target_count < 1 || + cxlhdm->target_count > CXL_HDM_DECODER0_TL_TARGETS)) { + dev_err(&port->dev, "Invalid decoder target count: %u\n", + cxlhdm->target_count); + return -ENXIO; + } cxl_settle_decoders(cxlhdm); + /* + * Reset commit_end after all decoders have been torn down so a + * subsequent probe rebuilds it from scratch. + */ + rc = devm_add_action(&port->dev, cxl_reset_commit_end, port); + if (rc) + return rc; + for (i = 0; i < cxlhdm->decoder_count; i++) { - int rc, target_count = cxlhdm->target_count; + int target_count = cxlhdm->target_count; struct cxl_decoder *cxld; if (is_cxl_endpoint(port)) { diff --git a/drivers/cxl/core/mce.c b/drivers/cxl/core/mce.c index 65fed913b221..3ac6802e750d 100644 --- a/drivers/cxl/core/mce.c +++ b/drivers/cxl/core/mce.c @@ -18,7 +18,13 @@ static int cxl_handle_mce(struct notifier_block *nb, unsigned long val, u64 spa, spa_alias; unsigned long pfn; - if (!mce || !mce_usable_address(mce)) + if (!mce) + return NOTIFY_DONE; + + if (mce_is_correctable(mce)) + return NOTIFY_DONE; + + if (!mce_usable_address(mce)) return NOTIFY_DONE; spa = mce->addr & MCI_ADDR_PHYSADDR; diff --git a/drivers/cxl/core/pci.c b/drivers/cxl/core/pci.c index bb6ad0753a42..125abb36df7f 100644 --- a/drivers/cxl/core/pci.c +++ b/drivers/cxl/core/pci.c @@ -683,6 +683,15 @@ static int __cxl_endpoint_decoder_reset_detected(struct device *dev, void *data) if ((cxld->flags & CXL_DECODER_F_ENABLE) == 0) return 0; + /* + * Decoders emulated from the DVSEC range registers have no commit + * callback and no HDM decoder registers to consult. + */ + if (!cxld->commit) { + dev_warn(dev, "DVSEC emulated decode may have been cleared by reset\n"); + return 0; + } + cxlhdm = dev_get_drvdata(&port->dev); hdm = cxlhdm->regs.hdm_decoder; ctrl = readl(hdm + CXL_HDM_DECODER0_CTRL_OFFSET(cxld->id)); @@ -734,10 +743,16 @@ int cxl_pci_setup_regs(struct pci_dev *pdev, enum cxl_regloc_type type, if (rc && type == CXL_REGLOC_RBI_COMPONENT && is_cxl_restricted(pdev)) { struct cxl_dport *dport; struct cxl_port *port __free(put_cxl_port) = - cxl_pci_find_port(pdev, &dport); + cxl_pci_find_port(pdev); if (!port) return -EPROBE_DEFER; + guard(device)(cxl_port_dport_host(port)); + + dport = cxl_pci_find_dport(pdev, port); + if (!dport) + return -EPROBE_DEFER; + rc = cxl_rcrb_get_comp_regs(pdev, map, dport); if (rc) return rc; @@ -840,8 +855,8 @@ static int update_gpf_port_dvsec(struct pci_dev *pdev, int dvsec, int phase) FIELD_GET(scale, ctrl) == GPF_TIMEOUT_SCALE_MAX) return 0; - ctrl = FIELD_PREP(base, GPF_TIMEOUT_BASE_MAX); - ctrl |= FIELD_PREP(scale, GPF_TIMEOUT_SCALE_MAX); + FIELD_MODIFY(base, &ctrl, GPF_TIMEOUT_BASE_MAX); + FIELD_MODIFY(scale, &ctrl, GPF_TIMEOUT_SCALE_MAX); rc = pci_write_config_word(pdev, dvsec + offset, ctrl); if (rc) { diff --git a/drivers/cxl/core/port.c b/drivers/cxl/core/port.c index cd9e58d8144f..f3705ea44db7 100644 --- a/drivers/cxl/core/port.c +++ b/drivers/cxl/core/port.c @@ -148,20 +148,29 @@ static ssize_t target_type_show(struct device *dev, } static DEVICE_ATTR_RO(target_type); +/* + * Interleave ways selects how many targets a decoder uses, but the target + * array is only nr_targets long. Bound array access by both. + */ +static int cxlsd_nr_used_targets(struct cxl_switch_decoder *cxlsd) +{ + return min(cxlsd->cxld.interleave_ways, cxlsd->nr_targets); +} + static ssize_t emit_target_list(struct cxl_switch_decoder *cxlsd, char *buf) { - struct cxl_decoder *cxld = &cxlsd->cxld; + int nr_used = cxlsd_nr_used_targets(cxlsd); ssize_t offset = 0; int i, rc = 0; - for (i = 0; i < cxld->interleave_ways; i++) { + for (i = 0; i < nr_used; i++) { struct cxl_dport *dport = cxlsd->target[i]; struct cxl_dport *next = NULL; if (!dport) break; - if (i + 1 < cxld->interleave_ways) + if (i + 1 < nr_used) next = cxlsd->target[i + 1]; rc = sysfs_emit_at(buf, offset, "%d%s", dport->port_id, next ? "," : ""); @@ -814,6 +823,11 @@ static int cxl_einj_inject(void *data, u64 type) DEFINE_DEBUGFS_ATTRIBUTE(cxl_einj_inject_fops, NULL, cxl_einj_inject, "0x%llx\n"); +static void remove_debugfs(void *dentry) +{ + debugfs_remove_recursive(dentry); +} + static void cxl_debugfs_create_dport_dir(struct cxl_dport *dport) { struct cxl_port *parent = parent_port_of(dport->port); @@ -832,6 +846,9 @@ static void cxl_debugfs_create_dport_dir(struct cxl_dport *dport) dir = cxl_debugfs_create_dir(dev_name(dport->dport_dev)); + if (devm_add_action_or_reset(dport_to_host(dport), remove_debugfs, dir)) + return; + debugfs_create_file("einj_inject", 0200, dir, dport, &cxl_einj_inject_fops); } @@ -1349,7 +1366,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; @@ -1365,6 +1382,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) { @@ -1387,13 +1409,11 @@ static int cxl_add_ep(struct cxl_dport *dport, struct device *ep_dev) struct cxl_find_port_ctx { const struct device *dport_dev; const struct cxl_port *parent_port; - struct cxl_dport **dport; }; static int match_port_by_dport(struct device *dev, const void *data) { const struct cxl_find_port_ctx *ctx = data; - struct cxl_dport *dport; struct cxl_port *port; if (!is_cxl_port(dev)) @@ -1402,10 +1422,7 @@ static int match_port_by_dport(struct device *dev, const void *data) return 0; port = to_cxl_port(dev); - dport = cxl_find_dport_by_dev(port, ctx->dport_dev); - if (ctx->dport) - *ctx->dport = dport; - return dport != NULL; + return !!cxl_find_dport_by_dev(port, ctx->dport_dev); } static struct cxl_port *__find_cxl_port_by_dport(struct cxl_find_port_ctx *ctx) @@ -1424,22 +1441,21 @@ static struct cxl_port *__find_cxl_port_by_dport(struct cxl_find_port_ctx *ctx) /** * find_cxl_port_by_dport - find a cxl_port by one of its targets * @dport_dev: device representing the dport target - * @dport: optional output of the 'struct cxl_dport' companion of the @dport_dev * * Return a 'struct cxl_port' with an elevated reference if found. Use * __free(put_cxl_port) to release. + * + * The port reference does not pin the dport, which is a devm allocation of + * cxl_port_dport_host(). Use cxl_pci_find_dport() or cxl_mem_find_dport() + * under that device's lock to get it. */ -static struct cxl_port *find_cxl_port_by_dport(struct device *dport_dev, - struct cxl_dport **dport) +static struct cxl_port *find_cxl_port_by_dport(struct device *dport_dev) { struct cxl_find_port_ctx ctx = { .dport_dev = dport_dev, - .dport = dport, }; - struct cxl_port *port; - port = __find_cxl_port_by_dport(&ctx); - return port; + return __find_cxl_port_by_dport(&ctx); } /* @@ -1640,7 +1656,7 @@ static int update_decoder_targets(struct device *dev, void *data) struct cxl_dport *dport = data; struct cxl_switch_decoder *cxlsd; struct cxl_decoder *cxld; - int i; + int i, nr_used; if (!is_switch_decoder(dev)) return 0; @@ -1648,8 +1664,9 @@ static int update_decoder_targets(struct device *dev, void *data) cxlsd = to_cxl_switch_decoder(dev); cxld = &cxlsd->cxld; guard(rwsem_write)(&cxl_rwsem.region); + nr_used = cxlsd_nr_used_targets(cxlsd); - for (i = 0; i < cxld->interleave_ways; i++) { + for (i = 0; i < nr_used; i++) { if (cxld->target_map[i] == dport->port_id) { cxlsd->target[i] = dport; dev_dbg(dev, "dport%d found in target list, index %d\n", @@ -1701,13 +1718,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) { @@ -1724,7 +1743,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 @@ -1732,7 +1751,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)); @@ -1741,11 +1760,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, @@ -1753,7 +1786,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)) { @@ -1782,33 +1815,23 @@ 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; /* * The port is already visible in CXL hierarchy, but it may still @@ -1824,13 +1847,28 @@ static struct cxl_dport *find_or_add_dport(struct cxl_port *port, 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) @@ -1859,7 +1897,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; @@ -1886,27 +1923,13 @@ int devm_cxl_enumerate_ports(struct cxl_memdev *cxlmd) * RP port enumerated by cxl_acpi without dport will * have the dport added here. */ - 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; @@ -1929,25 +1952,55 @@ int devm_cxl_enumerate_ports(struct cxl_memdev *cxlmd) } EXPORT_SYMBOL_NS_GPL(devm_cxl_enumerate_ports, "CXL"); -struct cxl_port *cxl_pci_find_port(struct pci_dev *pdev, - struct cxl_dport **dport) +struct cxl_port *cxl_pci_find_port(struct pci_dev *pdev) { - return find_cxl_port_by_dport(pdev->dev.parent, dport); + return find_cxl_port_by_dport(pdev->dev.parent); } EXPORT_SYMBOL_NS_GPL(cxl_pci_find_port, "CXL"); -struct cxl_port *cxl_mem_find_port(struct cxl_memdev *cxlmd, - struct cxl_dport **dport) +struct cxl_port *cxl_mem_find_port(struct cxl_memdev *cxlmd) { - return find_cxl_port_by_dport(grandparent(&cxlmd->dev), dport); + return find_cxl_port_by_dport(grandparent(&cxlmd->dev)); } EXPORT_SYMBOL_NS_GPL(cxl_mem_find_port, "CXL"); +/** + * cxl_pci_find_dport - find the dport of @port that @pdev is below + * @pdev: PCI device below the dport + * @port: port to search, typically from cxl_pci_find_port() + * + * Context: Caller must hold the cxl_port_dport_host() lock of @port, and + * must not use the result after dropping it. + */ +struct cxl_dport *cxl_pci_find_dport(struct pci_dev *pdev, + struct cxl_port *port) +{ + device_lock_assert(cxl_port_dport_host(port)); + return cxl_find_dport_by_dev(port, pdev->dev.parent); +} +EXPORT_SYMBOL_NS_GPL(cxl_pci_find_dport, "CXL"); + +/** + * cxl_mem_find_dport - find the dport of @port that @cxlmd is below + * @cxlmd: memdev below the dport + * @port: port to search, typically from cxl_mem_find_port() + * + * Context: Caller must hold the cxl_port_dport_host() lock of @port, and + * must not use the result after dropping it. + */ +struct cxl_dport *cxl_mem_find_dport(struct cxl_memdev *cxlmd, + struct cxl_port *port) +{ + device_lock_assert(cxl_port_dport_host(port)); + return cxl_find_dport_by_dev(port, grandparent(&cxlmd->dev)); +} +EXPORT_SYMBOL_NS_GPL(cxl_mem_find_dport, "CXL"); + static int decoder_populate_targets(struct cxl_switch_decoder *cxlsd, struct cxl_port *port) { struct cxl_decoder *cxld = &cxlsd->cxld; - int i; + int i, nr_used; device_lock_assert(&port->dev); @@ -1955,7 +2008,8 @@ static int decoder_populate_targets(struct cxl_switch_decoder *cxlsd, return 0; guard(rwsem_write)(&cxl_rwsem.region); - for (i = 0; i < cxlsd->cxld.interleave_ways; i++) { + nr_used = cxlsd_nr_used_targets(cxlsd); + for (i = 0; i < nr_used; i++) { struct cxl_dport *dport = find_dport(port, cxld->target_map[i]); if (!dport) { @@ -2016,7 +2070,7 @@ static int cxl_switch_decoder_init(struct cxl_port *port, struct cxl_switch_decoder *cxlsd, int nr_targets) { - if (nr_targets > CXL_DECODER_MAX_INTERLEAVE) + if (nr_targets < 1 || nr_targets > CXL_DECODER_MAX_INTERLEAVE) return -EINVAL; cxlsd->nr_targets = nr_targets; @@ -2426,8 +2480,10 @@ int cxl_endpoint_get_perf_coordinates(struct cxl_port *port, * Skip calculation for RCD. Expectation is HMAT already covers RCD case * since RCH does not support hotplug. */ - if (cxlmd->cxlds->rcd) + if (cxlmd->cxlds->rcd) { + memset(coord, 0, sizeof(*coord) * ACCESS_COORDINATE_MAX); return 0; + } /* * Exit the loop when the parent port of the current iter port is cxl diff --git a/drivers/cxl/core/ras.c b/drivers/cxl/core/ras.c index e307361bb39e..0759fc9b07de 100644 --- a/drivers/cxl/core/ras.c +++ b/drivers/cxl/core/ras.c @@ -70,9 +70,9 @@ cxl_cper_trace_uncorr_prot_err(struct cxl_memdev *cxlmd, trace_cxl_aer_uncorrectable_error(cxlmd, status, fe, hl); } -static int match_memdev_by_parent(struct device *dev, const void *uport) +static int match_memdev_by_parent(struct device *dev, const void *parent) { - if (is_cxl_memdev(dev) && dev->parent == uport) + if (is_cxl_memdev(dev) && dev->parent == parent) return 1; return 0; } @@ -108,7 +108,7 @@ void cxl_cper_handle_prot_err(struct cxl_cper_prot_err_work_data *data) return; struct device *mem_dev __free(put_device) = bus_find_device( - &cxl_bus_type, NULL, pdev, match_memdev_by_parent); + &cxl_bus_type, NULL, &pdev->dev, match_memdev_by_parent); if (!mem_dev) return; diff --git a/drivers/cxl/core/ras_rch.c b/drivers/cxl/core/ras_rch.c index e0e01aa5eba6..3c6aae26deed 100644 --- a/drivers/cxl/core/ras_rch.c +++ b/drivers/cxl/core/ras_rch.c @@ -118,10 +118,20 @@ void cxl_handle_rdport_errors(struct cxl_dev_state *cxlds) int severity; struct cxl_port *port __free(put_cxl_port) = - cxl_pci_find_port(pdev, &dport); + cxl_pci_find_port(pdev); if (!port) return; + /* + * The dport may have been freed since the lookup above, so take the + * lock that pins it and find it again. + */ + guard(device)(cxl_port_dport_host(port)); + + dport = cxl_pci_find_dport(pdev, port); + if (!dport) + return; + if (!cxl_rch_get_aer_info(dport->regs.dport_aer, &aer_regs)) return; diff --git a/drivers/cxl/core/region.c b/drivers/cxl/core/region.c index 27e63e6dab7c..9a5fd3da539d 100644 --- a/drivers/cxl/core/region.c +++ b/drivers/cxl/core/region.c @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only /* Copyright(c) 2022 Intel Corporation. All rights reserved. */ +#include #include #include #include @@ -2630,7 +2631,19 @@ static bool cxl_region_update_coordinates(struct cxl_region *cxlr, int nid) for (int i = 0; i < ACCESS_COORDINATE_MAX; i++) { if (cxlr->coord[i].read_bandwidth) { - node_update_perf_attrs(nid, &cxlr->coord[i], i); + /* + * A CFMWS-only node (not backed by a real SRAT pxm) + * has no HMAT memory_target, so hmat_callback() + * never created the access attributes for it: + * create them here instead of only updating them. + * This is called at most once per node (see + * nodemask_region_seen), so the attributes are not + * created twice. + */ + if (!acpi_node_backed_by_real_pxm(nid)) + node_set_perf_attrs(nid, &cxlr->coord[i], i); + else + node_update_perf_attrs(nid, &cxlr->coord[i], i); cset++; } } diff --git a/drivers/cxl/core/region_pmem.c b/drivers/cxl/core/region_pmem.c index 23d97e3d78b6..7ab1373a95e0 100644 --- a/drivers/cxl/core/region_pmem.c +++ b/drivers/cxl/core/region_pmem.c @@ -168,12 +168,14 @@ 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/cxl/cxl.h b/drivers/cxl/cxl.h index cab8ce39f465..ee408f5730c3 100644 --- a/drivers/cxl/cxl.h +++ b/drivers/cxl/cxl.h @@ -67,6 +67,8 @@ extern const struct nvdimm_security_ops *cxl_security_ops; #define CXL_HDM_DECODER0_CTRL_HOSTONLY BIT(12) #define CXL_HDM_DECODER0_TL_LOW(i) (0x20 * (i) + 0x24) #define CXL_HDM_DECODER0_TL_HIGH(i) (0x20 * (i) + 0x28) +/* Target list capacity, i.e. max interleave ways for a non-endpoint decoder */ +#define CXL_HDM_DECODER0_TL_TARGETS 8 #define CXL_HDM_DECODER0_SKIP_LOW(i) CXL_HDM_DECODER0_TL_LOW(i) #define CXL_HDM_DECODER0_SKIP_HIGH(i) CXL_HDM_DECODER0_TL_HIGH(i) @@ -701,6 +703,18 @@ static inline bool is_cxl_root(struct cxl_port *port) return port->uport_dev == port->dev.parent; } +/* + * Return the owner device of the devm allocations of @port's dports. They + * are freed when that device unbinds, so hold device_lock() on the returned + * device across any lookup and use of a 'struct cxl_dport'. + */ +static inline struct device *cxl_port_dport_host(struct cxl_port *port) +{ + if (is_cxl_root(port)) + return port->uport_dev; + return &port->dev; +} + /* Address translation functions exported to cxl_translate test module only */ int cxl_validate_translation_params(u8 eiw, u16 eig, int pos); u64 cxl_calculate_hpa_offset(u64 dpa_offset, int pos, u8 eiw, u16 eig); @@ -747,10 +761,12 @@ DEFINE_FREE(put_cxl_dax_region, struct cxl_dax_region *, if (!IS_ERR_OR_NULL(_T) int devm_cxl_enumerate_ports(struct cxl_memdev *cxlmd); void cxl_bus_rescan(void); void cxl_bus_drain(void); -struct cxl_port *cxl_pci_find_port(struct pci_dev *pdev, - struct cxl_dport **dport); -struct cxl_port *cxl_mem_find_port(struct cxl_memdev *cxlmd, - struct cxl_dport **dport); +struct cxl_dport *cxl_pci_find_dport(struct pci_dev *pdev, + struct cxl_port *port); +struct cxl_dport *cxl_mem_find_dport(struct cxl_memdev *cxlmd, + struct cxl_port *port); +struct cxl_port *cxl_pci_find_port(struct pci_dev *pdev); +struct cxl_port *cxl_mem_find_port(struct cxl_memdev *cxlmd); bool schedule_cxl_memdev_detach(struct cxl_memdev *cxlmd); struct cxl_dport *devm_cxl_add_dport(struct cxl_port *port, diff --git a/drivers/cxl/mem.c b/drivers/cxl/mem.c index 798e5c369cfc..493c4071245d 100644 --- a/drivers/cxl/mem.c +++ b/drivers/cxl/mem.c @@ -50,8 +50,13 @@ static int cxl_debugfs_poison_inject(void *data, u64 dpa) struct cxl_memdev *cxlmd = data; int rc; - ACQUIRE(device_intr, devlock)(&cxlmd->dev); - if ((rc = ACQUIRE_ERR(device_intr, &devlock))) + /* + * Never wait for this lock: the debugfs proxy holds a file reference + * across the callback and unbind removes the file under the same + * device lock, so waiting here deadlocks against unbind. + */ + ACQUIRE(device_try, devlock)(&cxlmd->dev); + if ((rc = ACQUIRE_ERR(device_try, &devlock))) return rc; return cxl_inject_poison(cxlmd, dpa); @@ -65,8 +70,9 @@ static int cxl_debugfs_poison_clear(void *data, u64 dpa) struct cxl_memdev *cxlmd = data; int rc; - ACQUIRE(device_intr, devlock)(&cxlmd->dev); - if ((rc = ACQUIRE_ERR(device_intr, &devlock))) + /* Never wait, per the inject path above. */ + ACQUIRE(device_try, devlock)(&cxlmd->dev); + if ((rc = ACQUIRE_ERR(device_try, &devlock))) return rc; return cxl_clear_poison(cxlmd, dpa); @@ -133,7 +139,7 @@ static int cxl_mem_probe(struct device *dev) return rc; struct cxl_port *parent_port __free(put_cxl_port) = - cxl_mem_find_port(cxlmd, &dport); + cxl_mem_find_port(cxlmd); if (!parent_port) { dev_err(dev, "CXL port topology not found\n"); return -ENXIO; @@ -148,10 +154,7 @@ static int cxl_mem_probe(struct device *dev) } } - if (dport->rch) - endpoint_parent = parent_port->uport_dev; - else - endpoint_parent = &parent_port->dev; + endpoint_parent = cxl_port_dport_host(parent_port); scoped_guard(device, endpoint_parent) { if (!endpoint_parent->driver) { @@ -160,6 +163,13 @@ static int cxl_mem_probe(struct device *dev) return -ENXIO; } + /* @dport is only valid while @endpoint_parent stays bound */ + dport = cxl_mem_find_dport(cxlmd, parent_port); + if (!dport) { + dev_err(dev, "CXL topology dport not found\n"); + return -ENXIO; + } + rc = devm_cxl_add_endpoint(endpoint_parent, cxlmd, dport); if (rc) return rc; diff --git a/drivers/cxl/pci.c b/drivers/cxl/pci.c index c7c91e8dc51d..d51f00d4a7a7 100644 --- a/drivers/cxl/pci.c +++ b/drivers/cxl/pci.c @@ -706,22 +706,23 @@ static ssize_t rcd_pcie_cap_emit(struct device *dev, u16 offset, char *buf, size struct device *root_dev; struct cxl_dport *dport; struct cxl_port *root __free(put_cxl_port) = - cxl_mem_find_port(cxlmd, &dport); + cxl_mem_find_port(cxlmd); if (!root) return -ENXIO; - root_dev = root->uport_dev; + root_dev = cxl_port_dport_host(root); if (!root_dev) return -ENXIO; - if (!dport->regs.rcd_pcie_cap) - return -ENXIO; - guard(device)(root_dev); if (!root_dev->driver) return -ENXIO; + dport = cxl_mem_find_dport(cxlmd, root); + if (!dport || !dport->regs.rcd_pcie_cap) + return -ENXIO; + switch (width) { case 2: return sysfs_emit(buf, "%#x\n", @@ -892,6 +893,10 @@ static int cxl_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id) if (rc) dev_dbg(&pdev->dev, "No CXL FWCTL setup\n"); + rc = cxl_event_config(host_bridge, mds, irq_avail); + if (rc) + return rc; + pmu_count = cxl_count_regblock(pdev, CXL_REGLOC_RBI_PMU); if (pmu_count < 0) return pmu_count; @@ -918,13 +923,10 @@ static int cxl_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id) } } - rc = cxl_event_config(host_bridge, mds, irq_avail); - if (rc) - return rc; - pci_save_state(pdev); - return rc; + /* A missing PMU is not fatal, the memdev is still usable */ + return 0; } static const struct pci_device_id cxl_mem_pci_tbl[] = { diff --git a/drivers/dax/bus.c b/drivers/dax/bus.c index b809e1a264af..e40c25401cf0 100644 --- a/drivers/dax/bus.c +++ b/drivers/dax/bus.c @@ -1192,7 +1192,7 @@ static ssize_t mapping_store(struct device *dev, struct device_attribute *attr, return rc; if (!dax_region->dev->driver) { up_write(&dax_region_rwsem); - return rc; + return -ENXIO; } rc = down_write_killable(&dax_dev_rwsem); if (rc) { @@ -1201,8 +1201,12 @@ static ssize_t mapping_store(struct device *dev, struct device_attribute *attr, } to_alloc = range_len(&r); - if (alloc_is_aligned(dev_dax, to_alloc)) + if (!alloc_is_aligned(dev_dax, to_alloc)) { + dev_dbg(dev, "%s: size: %zu misaligned\n", __func__, to_alloc); + rc = -EINVAL; + } else { rc = alloc_dev_dax_range(dev_dax, r.start, to_alloc); + } up_write(&dax_dev_rwsem); up_write(&dax_region_rwsem); diff --git a/drivers/dax/fsdev.c b/drivers/dax/fsdev.c index 598604bf5ac5..910665c1f492 100644 --- a/drivers/dax/fsdev.c +++ b/drivers/dax/fsdev.c @@ -234,6 +234,29 @@ static const struct file_operations fsdev_fops = { .release = fsdev_release, }; +/** + * fsdev_dax_from_file - get dax_device from an open file + * @file: open device file + * + * Returns a dax_device pointer if @file refers to a fsdev_dax device. + * Otherwise return NULL. + * + * Caller must put_dax() the returned device when done. + */ +struct dax_device *fsdev_dax_from_file(struct file *file) +{ + struct dax_device *dax_dev; + + if (file->f_op != &fsdev_fops) + return NULL; + + dax_dev = inode_dax(file_inode(file)); + ihold(dax_inode(dax_dev)); + + return dax_dev; +} +EXPORT_SYMBOL_GPL(fsdev_dax_from_file); + /* * Acquire the dev_pagemap for probe: the static (pre-populated) one if * present, or a devm-allocated one for the dynamic case. Note that diff --git a/drivers/dax/super.c b/drivers/dax/super.c index 210f4af479f0..22ff364a5e34 100644 --- a/drivers/dax/super.c +++ b/drivers/dax/super.c @@ -565,7 +565,7 @@ static int dax_set(struct inode *inode, void *data) return 0; } -struct dax_device *dax_dev_get(dev_t devt) +static struct dax_device *dax_dev_get(dev_t devt) { struct dax_device *dax_dev; struct inode *inode; @@ -588,7 +588,6 @@ struct dax_device *dax_dev_get(dev_t devt) return dax_dev; } -EXPORT_SYMBOL_GPL(dax_dev_get); struct dax_device *alloc_dax(void *private, const struct dax_operations *ops) { diff --git a/drivers/dma/at_hdmac.c b/drivers/dma/at_hdmac.c index e5b30a57c477..7fa6af973fd8 100644 --- a/drivers/dma/at_hdmac.c +++ b/drivers/dma/at_hdmac.c @@ -244,7 +244,7 @@ struct at_desc { /* Memset temporary buffer */ bool memset_buffer; dma_addr_t memset_paddr; - int *memset_vaddr; + u32 *memset_vaddr; struct atdma_sg sg[] __counted_by(sglen); }; @@ -1097,7 +1097,7 @@ atc_prep_dma_memset(struct dma_chan *chan, dma_addr_t dest, int value, struct at_dma_chan *atchan = to_at_dma_chan(chan); struct at_dma *atdma = to_at_dma(chan->device); struct at_desc *desc; - void __iomem *vaddr; + u32 *vaddr; dma_addr_t paddr; char fill_pattern; int ret; @@ -1126,10 +1126,10 @@ atc_prep_dma_memset(struct dma_chan *chan, dma_addr_t dest, int value, /* Only the first byte of value is to be used according to dmaengine */ fill_pattern = (char)value; - *(u32*)vaddr = (fill_pattern << 24) | - (fill_pattern << 16) | - (fill_pattern << 8) | - fill_pattern; + *vaddr = (fill_pattern << 24) | + (fill_pattern << 16) | + (fill_pattern << 8) | + fill_pattern; desc = kzalloc_flex(*desc, sg, 1, GFP_ATOMIC); if (!desc) @@ -1168,7 +1168,7 @@ atc_prep_dma_memset_sg(struct dma_chan *chan, struct at_dma *atdma = to_at_dma(chan->device); struct at_desc *desc; struct scatterlist *sg; - void __iomem *vaddr; + u32 *vaddr; dma_addr_t paddr; size_t total_len = 0; int i; @@ -1189,7 +1189,7 @@ atc_prep_dma_memset_sg(struct dma_chan *chan, __func__); return NULL; } - *(u32*)vaddr = value; + *vaddr = value; desc = kzalloc_flex(*desc, sg, sg_len, GFP_ATOMIC); if (!desc) @@ -1940,6 +1940,20 @@ static void at_dma_off(struct at_dma *atdma) cpu_relax(); } +static void at_dma_cleanup_channels(struct at_dma *atdma) +{ + struct dma_chan *chan, *_chan; + int i = 0; + + list_for_each_entry_safe(chan, _chan, &atdma->dma_device.channels, + device_node) { + /* Disable interrupts */ + atc_disable_chan_irq(atdma, i++); + tasklet_kill(&to_at_dma_chan(chan)->vc.task); + list_del(&chan->device_node); + } +} + static int __init at_dma_probe(struct platform_device *pdev) { struct at_dma *atdma; @@ -2105,6 +2119,8 @@ static int __init at_dma_probe(struct platform_device *pdev) err_of_dma_controller_register: dma_async_device_unregister(&atdma->dma_device); err_dma_async_device_register: + disable_irq(platform_get_irq(pdev, 0)); + at_dma_cleanup_channels(atdma); dma_pool_destroy(atdma->memset_pool); err_memset_pool_create: dma_pool_destroy(atdma->lli_pool); @@ -2118,23 +2134,17 @@ static int __init at_dma_probe(struct platform_device *pdev) static void at_dma_remove(struct platform_device *pdev) { struct at_dma *atdma = platform_get_drvdata(pdev); - struct dma_chan *chan, *_chan; at_dma_off(atdma); if (pdev->dev.of_node) of_dma_controller_free(pdev->dev.of_node); dma_async_device_unregister(&atdma->dma_device); - dma_pool_destroy(atdma->memset_pool); - dma_pool_destroy(atdma->lli_pool); free_irq(platform_get_irq(pdev, 0), atdma); - list_for_each_entry_safe(chan, _chan, &atdma->dma_device.channels, - device_node) { - /* Disable interrupts */ - atc_disable_chan_irq(atdma, chan->chan_id); - list_del(&chan->device_node); - } + at_dma_cleanup_channels(atdma); + dma_pool_destroy(atdma->memset_pool); + dma_pool_destroy(atdma->lli_pool); clk_disable_unprepare(atdma->clk); } diff --git a/drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c b/drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c index eebed2474210..2d7d49017002 100644 --- a/drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c +++ b/drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c @@ -706,7 +706,7 @@ static int dw_axi_dma_set_hw_desc(struct axi_dma_chan *chan, ctlhi = CH_CTL_H_LLI_VALID; if (chan->chip->dw->hdata->restrict_axi_burst_len) { - burst_len = chan->chip->dw->hdata->axi_rw_burst_len; + burst_len = chan->chip->dw->hdata->axi_rw_burst_len - 1; ctlhi |= CH_CTL_H_ARLEN_EN | CH_CTL_H_AWLEN_EN | burst_len << CH_CTL_H_ARLEN_POS | burst_len << CH_CTL_H_AWLEN_POS; @@ -975,7 +975,7 @@ dma_chan_prep_dma_memcpy(struct dma_chan *dchan, dma_addr_t dst_adr, reg = CH_CTL_H_LLI_VALID; if (chan->chip->dw->hdata->restrict_axi_burst_len) { - u32 burst_len = chan->chip->dw->hdata->axi_rw_burst_len; + u32 burst_len = chan->chip->dw->hdata->axi_rw_burst_len - 1; reg |= (CH_CTL_H_ARLEN_EN | burst_len << CH_CTL_H_ARLEN_POS | @@ -1052,10 +1052,7 @@ static void axi_chan_dump_lli(struct axi_dma_chan *chan, static void axi_chan_list_dump_lli(struct axi_dma_chan *chan, struct axi_dma_desc *desc_head) { - int count = atomic_read(&chan->descs_allocated); - int i; - - for (i = 0; i < count; i++) + for (unsigned int i = 0; i < desc_head->nr_hw_descs; i++) axi_chan_dump_lli(chan, &desc_head->hw_desc[i]); } @@ -1320,8 +1317,7 @@ static int axi_dma_suspend(struct axi_dma_chip *chip) axi_dma_irq_disable(chip); axi_dma_disable(chip); - clk_disable_unprepare(chip->core_clk); - clk_disable_unprepare(chip->cfgr_clk); + clk_bulk_disable_unprepare(ARRAY_SIZE(chip->clks), chip->clks); return 0; } @@ -1330,11 +1326,7 @@ static int axi_dma_resume(struct axi_dma_chip *chip) { int ret; - ret = clk_prepare_enable(chip->cfgr_clk); - if (ret < 0) - return ret; - - ret = clk_prepare_enable(chip->core_clk); + ret = clk_bulk_prepare_enable(ARRAY_SIZE(chip->clks), chip->clks); if (ret < 0) return ret; @@ -1524,13 +1516,11 @@ static int dw_probe(struct platform_device *pdev) chip->dw->hdata->use_cfg2 = !!(flags & AXI_DMA_FLAG_USE_CFG2); - chip->core_clk = devm_clk_get(chip->dev, "core-clk"); - if (IS_ERR(chip->core_clk)) - return PTR_ERR(chip->core_clk); - - chip->cfgr_clk = devm_clk_get(chip->dev, "cfgr-clk"); - if (IS_ERR(chip->cfgr_clk)) - return PTR_ERR(chip->cfgr_clk); + chip->clks[0].id = "core-clk"; + chip->clks[1].id = "cfgr-clk"; + ret = devm_clk_bulk_get(chip->dev, ARRAY_SIZE(chip->clks), chip->clks); + if (ret) + return dev_err_probe(chip->dev, ret, "failed to get clocks\n"); ret = parse_device_properties(chip); if (ret) @@ -1640,10 +1630,13 @@ static void dw_remove(struct platform_device *pdev) struct dw_axi_dma *dw = chip->dw; struct axi_dma_chan *chan, *_chan; u32 i; + int ret; /* Enable clk before accessing to registers */ - clk_prepare_enable(chip->cfgr_clk); - clk_prepare_enable(chip->core_clk); + ret = clk_bulk_prepare_enable(ARRAY_SIZE(chip->clks), chip->clks); + if (ret) + dev_warn(chip->dev, "failed to enable clocks before remove: %d\n", + ret); axi_dma_irq_disable(chip); for (i = 0; i < dw->hdata->nr_channels; i++) { axi_chan_disable(&chip->dw->chan[i]); diff --git a/drivers/dma/dw-axi-dmac/dw-axi-dmac.h b/drivers/dma/dw-axi-dmac/dw-axi-dmac.h index 67cc199e24d1..da706bff3f12 100644 --- a/drivers/dma/dw-axi-dmac/dw-axi-dmac.h +++ b/drivers/dma/dw-axi-dmac/dw-axi-dmac.h @@ -69,8 +69,7 @@ struct axi_dma_chip { int irq[DMAC_MAX_CHANNELS]; void __iomem *regs; void __iomem *apb_regs; - struct clk *core_clk; - struct clk *cfgr_clk; + struct clk_bulk_data clks[2]; struct dw_axi_dma *dw; }; @@ -327,7 +326,7 @@ enum { #define CH_CFG2_H_TT_FC_POS 0 #define CH_CFG2_H_HS_SEL_SRC_POS 3 #define CH_CFG2_H_HS_SEL_DST_POS 4 -#define CH_CFG2_H_PRIORITY_POS 20 +#define CH_CFG2_H_PRIORITY_POS 15 /** * DW AXI DMA channel interrupts diff --git a/drivers/dma/fsl_raid.c b/drivers/dma/fsl_raid.c index 2d86f61105e5..befb4bb69d54 100644 --- a/drivers/dma/fsl_raid.c +++ b/drivers/dma/fsl_raid.c @@ -162,6 +162,7 @@ static void fsl_re_dequeue(struct tasklet_struct *t) struct fsl_re_hw_desc *hwdesc; unsigned long flags; unsigned int count, oub_count; + LIST_HEAD(completed); int found; fsl_re_cleanup_descs(re_chan); @@ -182,8 +183,7 @@ static void fsl_re_dequeue(struct tasklet_struct *t) } if (found) { - fsl_re_desc_done(desc); - list_move_tail(&desc->node, &re_chan->ack_q); + list_move_tail(&desc->node, &completed); } else { dev_err(re_chan->dev, "found hwdesc not in sw queue, discard it\n"); @@ -196,6 +196,17 @@ static void fsl_re_dequeue(struct tasklet_struct *t) FSL_RE_RMVD_JOB(1)); } spin_unlock_irqrestore(&re_chan->desc_lock, flags); + + /* Invoke the client callbacks outside the channel lock. The callback + * may submit new work which re-acquires desc_lock, so holding it here + * would deadlock. + */ + list_for_each_entry_safe(desc, _desc, &completed, node) { + fsl_re_desc_done(desc); + spin_lock_irqsave(&re_chan->desc_lock, flags); + list_move_tail(&desc->node, &re_chan->ack_q); + spin_unlock_irqrestore(&re_chan->desc_lock, flags); + } } /* Per Job Ring interrupt handler */ @@ -295,8 +306,8 @@ static struct fsl_re_desc *fsl_re_chan_alloc_desc(struct fsl_re_chan *re_chan, if (!desc) return NULL; - cf = dma_pool_alloc(re_chan->re_dev->cf_desc_pool, GFP_NOWAIT, - &paddr); + cf = dma_pool_zalloc(re_chan->re_dev->cf_desc_pool, GFP_NOWAIT, + &paddr); if (!cf) { kfree(desc); return NULL; @@ -584,8 +595,8 @@ static int fsl_re_alloc_chan_resources(struct dma_chan *chan) if (!desc) break; - cf = dma_pool_alloc(re_chan->re_dev->cf_desc_pool, GFP_KERNEL, - &paddr); + cf = dma_pool_zalloc(re_chan->re_dev->cf_desc_pool, GFP_KERNEL, + &paddr); if (!cf) { kfree(desc); break; @@ -603,18 +614,15 @@ static int fsl_re_alloc_chan_resources(struct dma_chan *chan) static void fsl_re_free_chan_resources(struct dma_chan *chan) { struct fsl_re_chan *re_chan; - struct fsl_re_desc *desc; + struct fsl_re_desc *desc, *_desc; re_chan = container_of(chan, struct fsl_re_chan, chan); - while (re_chan->alloc_count--) { - desc = list_first_entry(&re_chan->free_q, - struct fsl_re_desc, - node); - + list_for_each_entry_safe(desc, _desc, &re_chan->free_q, node) { list_del(&desc->node); dma_pool_free(re_chan->re_dev->cf_desc_pool, desc->cf_addr, desc->cf_paddr); kfree(desc); + re_chan->alloc_count--; } if (!list_empty(&re_chan->free_q)) diff --git a/drivers/dma/img-mdc-dma.c b/drivers/dma/img-mdc-dma.c index b3765ba15803..a3192d49b6c8 100644 --- a/drivers/dma/img-mdc-dma.c +++ b/drivers/dma/img-mdc-dma.c @@ -738,7 +738,7 @@ static int mdc_alloc_chan_resources(struct dma_chan *chan) struct mdc_chan *mchan = to_mdc_chan(chan); struct device *dev = mdma2dev(mchan->mdma); - return pm_runtime_get_sync(dev); + return pm_runtime_resume_and_get(dev); } static void mdc_free_chan_resources(struct dma_chan *chan) diff --git a/drivers/dma/ioat/init.c b/drivers/dma/ioat/init.c index 737496391109..a57024c4b066 100644 --- a/drivers/dma/ioat/init.c +++ b/drivers/dma/ioat/init.c @@ -1170,15 +1170,6 @@ static int ioat3_dma_probe(struct ioatdma_device *ioat_dma, int dca) ioat_chan->reg_base + IOAT_DCACTRL_OFFSET); } - err = dma_async_device_register(&ioat_dma->dma_dev); - if (err) - goto err_disable_interrupts; - - ioat_kobject_add(ioat_dma, &ioat_ktype); - - if (dca) - ioat_dma->dca = ioat_dca_init(pdev, ioat_dma->reg_base); - /* disable relaxed ordering */ err = pcie_capability_read_word(pdev, PCI_EXP_DEVCTL, &val16); if (err) { @@ -1194,6 +1185,15 @@ static int ioat3_dma_probe(struct ioatdma_device *ioat_dma, int dca) goto err_disable_interrupts; } + err = dma_async_device_register(&ioat_dma->dma_dev); + if (err) + goto err_disable_interrupts; + + ioat_kobject_add(ioat_dma, &ioat_ktype); + + if (dca) + ioat_dma->dca = ioat_dca_init(pdev, ioat_dma->reg_base); + if (ioat_dma->cap & IOAT_CAP_DPS) writeb(ioat_pending_level + 1, ioat_dma->reg_base + IOAT_PREFETCH_LIMIT_OFFSET); diff --git a/drivers/dma/loongson/loongson2-apb-cmc-dma.c b/drivers/dma/loongson/loongson2-apb-cmc-dma.c index 60eb4d961610..c6ee34aa656e 100644 --- a/drivers/dma/loongson/loongson2-apb-cmc-dma.c +++ b/drivers/dma/loongson/loongson2-apb-cmc-dma.c @@ -90,7 +90,7 @@ struct loongson2_cmc_dma_chan { struct dma_slave_config dma_sconfig; struct loongson2_cmc_dma_desc *desc; u32 id; - u32 irq; + int irq; u32 next_sg; struct loongson2_cmc_dma_chan_reg chan_reg; }; diff --git a/drivers/dma/mediatek/mtk-hsdma.c b/drivers/dma/mediatek/mtk-hsdma.c index a43412ff5edd..27cb370106c7 100644 --- a/drivers/dma/mediatek/mtk-hsdma.c +++ b/drivers/dma/mediatek/mtk-hsdma.c @@ -848,17 +848,27 @@ static int mtk_hsdma_hw_init(struct mtk_hsdma_device *hsdma) { int err; - pm_runtime_enable(hsdma2dev(hsdma)); - pm_runtime_get_sync(hsdma2dev(hsdma)); + err = devm_pm_runtime_enable(hsdma2dev(hsdma)); + if (err) + return err; + + err = pm_runtime_resume_and_get(hsdma2dev(hsdma)); + if (err < 0) + return err; err = clk_prepare_enable(hsdma->clk); if (err) - return err; + goto err_put_pm; mtk_dma_write(hsdma, MTK_HSDMA_INT_ENABLE, 0); mtk_dma_write(hsdma, MTK_HSDMA_GLO, MTK_HSDMA_GLO_DEFAULT); return 0; + +err_put_pm: + pm_runtime_put_sync(hsdma2dev(hsdma)); + + return err; } static int mtk_hsdma_hw_deinit(struct mtk_hsdma_device *hsdma) @@ -868,7 +878,6 @@ static int mtk_hsdma_hw_deinit(struct mtk_hsdma_device *hsdma) clk_disable_unprepare(hsdma->clk); pm_runtime_put_sync(hsdma2dev(hsdma)); - pm_runtime_disable(hsdma2dev(hsdma)); return 0; } @@ -983,7 +992,9 @@ static int mtk_hsdma_probe(struct platform_device *pdev) goto err_unregister; } - mtk_hsdma_hw_init(hsdma); + err = mtk_hsdma_hw_init(hsdma); + if (err) + goto err_free; err = devm_request_irq(&pdev->dev, hsdma->irq, mtk_hsdma_irq, 0, @@ -991,7 +1002,7 @@ static int mtk_hsdma_probe(struct platform_device *pdev) if (err) { dev_err(&pdev->dev, "request_irq failed with err %d\n", err); - goto err_free; + goto err_deinit; } platform_set_drvdata(pdev, hsdma); @@ -1000,8 +1011,9 @@ static int mtk_hsdma_probe(struct platform_device *pdev) return 0; -err_free: +err_deinit: mtk_hsdma_hw_deinit(hsdma); +err_free: of_dma_controller_free(pdev->dev.of_node); err_unregister: dma_async_device_unregister(dd); diff --git a/drivers/dma/mv_xor.c b/drivers/dma/mv_xor.c index 25ed61f1b089..24f22db5dfa1 100644 --- a/drivers/dma/mv_xor.c +++ b/drivers/dma/mv_xor.c @@ -1162,6 +1162,7 @@ mv_xor_channel_add(struct mv_xor_device *xordev, err_free_irq: free_irq(mv_chan->irq, mv_chan); + tasklet_kill(&mv_chan->irq_tasklet); err_free_dma: dma_free_wc(&pdev->dev, MV_XOR_POOL_SIZE, mv_chan->dma_desc_pool_virt, mv_chan->dma_desc_pool); diff --git a/drivers/dma/plx_dma.c b/drivers/dma/plx_dma.c index 84941a918b01..409898e92c32 100644 --- a/drivers/dma/plx_dma.c +++ b/drivers/dma/plx_dma.c @@ -504,17 +504,17 @@ static int plx_dma_create(struct pci_dev *pdev) if (!plxdev) return -ENOMEM; - rc = request_irq(pci_irq_vector(pdev, 0), plx_dma_isr, 0, - KBUILD_MODNAME, plxdev); - if (rc) - goto free_plx; - spin_lock_init(&plxdev->ring_lock); tasklet_setup(&plxdev->desc_task, plx_dma_desc_task); RCU_INIT_POINTER(plxdev->pdev, pdev); plxdev->bar = pcim_iomap_table(pdev)[0]; + rc = request_irq(pci_irq_vector(pdev, 0), plx_dma_isr, 0, + KBUILD_MODNAME, plxdev); + if (rc) + goto free_plx; + dma = &plxdev->dma_dev; INIT_LIST_HEAD(&dma->channels); dma_cap_set(DMA_MEMCPY, dma->cap_mask); diff --git a/drivers/dma/sprd-dma.c b/drivers/dma/sprd-dma.c index 19b32a23c882..60b3067a0099 100644 --- a/drivers/dma/sprd-dma.c +++ b/drivers/dma/sprd-dma.c @@ -208,8 +208,7 @@ struct sprd_dma_chn { struct sprd_dma_dev { struct dma_device dma_dev; void __iomem *glb_base; - struct clk *clk; - struct clk *ashb_clk; + struct clk_bulk_data clks[2]; int irq; u32 total_chns; struct sprd_dma_chn channels[] __counted_by(total_chns); @@ -260,31 +259,12 @@ static void sprd_dma_chn_update(struct sprd_dma_chn *schan, u32 reg, static int sprd_dma_enable(struct sprd_dma_dev *sdev) { - int ret; - - ret = clk_prepare_enable(sdev->clk); - if (ret) - return ret; - - /* - * The ashb_clk is optional and only for AGCP DMA controller, so we - * need add one condition to check if the ashb_clk need enable. - */ - if (!IS_ERR(sdev->ashb_clk)) - ret = clk_prepare_enable(sdev->ashb_clk); - - return ret; + return clk_bulk_prepare_enable(ARRAY_SIZE(sdev->clks), sdev->clks); } static void sprd_dma_disable(struct sprd_dma_dev *sdev) { - clk_disable_unprepare(sdev->clk); - - /* - * Need to check if we need disable the optional ashb_clk for AGCP DMA. - */ - if (!IS_ERR(sdev->ashb_clk)) - clk_disable_unprepare(sdev->ashb_clk); + clk_bulk_disable_unprepare(ARRAY_SIZE(sdev->clks), sdev->clks); } static void sprd_dma_set_uid(struct sprd_dma_chn *schan) @@ -1140,16 +1120,17 @@ static int sprd_dma_probe(struct platform_device *pdev) if (!sdev) return -ENOMEM; - sdev->clk = devm_clk_get(&pdev->dev, "enable"); - if (IS_ERR(sdev->clk)) { - dev_err(&pdev->dev, "get enable clock failed\n"); - return PTR_ERR(sdev->clk); - } + /* The ashb_eb clock is optional and only present for AGCP DMA */ + sdev->clks[0].id = "enable"; + sdev->clks[1].id = "ashb_eb"; + ret = devm_clk_bulk_get_optional(&pdev->dev, ARRAY_SIZE(sdev->clks), + sdev->clks); + if (ret) + return dev_err_probe(&pdev->dev, ret, "get clocks failed\n"); - /* ashb clock is optional for AGCP DMA */ - sdev->ashb_clk = devm_clk_get(&pdev->dev, "ashb_eb"); - if (IS_ERR(sdev->ashb_clk)) - dev_warn(&pdev->dev, "no optional ashb eb clock\n"); + if (!sdev->clks[0].clk) + return dev_err_probe(&pdev->dev, -ENOENT, + "get enable clock failed\n"); /* * We have three DMA controllers: AP DMA, AON DMA and AGCP DMA. For AGCP diff --git a/drivers/dma/ste_dma40.c b/drivers/dma/ste_dma40.c index 0d9ffa3e2663..4f1af65b4671 100644 --- a/drivers/dma/ste_dma40.c +++ b/drivers/dma/ste_dma40.c @@ -28,6 +28,8 @@ #include "ste_dma40.h" #include "ste_dma40_ll.h" +#define D40_MEMCPY_MAX_CHANS 8 + /** * struct stedma40_platform_data - Configuration struct for the dma device. * @@ -41,6 +43,7 @@ * to use SoftLLI. * @use_esram_lcla: flag for mapping the lcla into esram region * @num_of_memcpy_chans: The number of channels reserved for memcpy. + * @memcpy_channels: The event lines used for memcpy. * @num_of_phy_chans: The number of physical channels implemented in HW. * 0 means reading the number of channels from DMA HW but this is only valid * for 'multiple of 4' channels, like 8. @@ -51,6 +54,7 @@ struct stedma40_platform_data { int num_of_soft_lli_chans; bool use_esram_lcla; int num_of_memcpy_chans; + u32 memcpy_channels[D40_MEMCPY_MAX_CHANS]; int num_of_phy_chans; }; @@ -65,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 @@ -75,6 +82,11 @@ struct stedma40_platform_data { #define D40_LCLA_LINK_PER_EVENT_GRP 128 #define D40_LCLA_END D40_LCLA_LINK_PER_EVENT_GRP +/* Number of event groups per hardware register layout */ +#define D40_EVENT_GROUPS_V4A 4 +#define D40_EVENT_GROUPS_V4B 5 +#define D40_PHYS_PER_EVENT_GROUP 2 + /* Max number of logical channels per physical channel */ #define D40_MAX_LOG_CHAN_PER_PHY 32 @@ -86,25 +98,6 @@ struct stedma40_platform_data { #define D40_ALLOC_PHY BIT(30) #define D40_ALLOC_LOG_FREE 0 -#define D40_MEMCPY_MAX_CHANS 8 - -/* Reserved event lines for memcpy only. */ -#define DB8500_DMA_MEMCPY_EV_0 51 -#define DB8500_DMA_MEMCPY_EV_1 56 -#define DB8500_DMA_MEMCPY_EV_2 57 -#define DB8500_DMA_MEMCPY_EV_3 58 -#define DB8500_DMA_MEMCPY_EV_4 59 -#define DB8500_DMA_MEMCPY_EV_5 60 - -static int dma40_memcpy_channels[] = { - DB8500_DMA_MEMCPY_EV_0, - DB8500_DMA_MEMCPY_EV_1, - DB8500_DMA_MEMCPY_EV_2, - DB8500_DMA_MEMCPY_EV_3, - DB8500_DMA_MEMCPY_EV_4, - DB8500_DMA_MEMCPY_EV_5, -}; - /* Default configuration for physical memcpy */ static const struct stedma40_chan_cfg dma40_memcpy_conf_phy = { .mode = STEDMA40_MODE_PHYSICAL, @@ -378,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. */ @@ -396,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; }; /** @@ -411,8 +416,8 @@ struct d40_desc { * @dma_addr: DMA address, if mapped * @base_unaligned: The original kmalloc pointer, if kmalloc is used. * This pointer is only there for clean-up on error. - * @pages: The number of pages needed for all physical channels. - * Only used later for clean-up on error + * @alloc_order: Order used for the LCLA page allocation. + * Only used later for clean-up on error. * @lock: Lock to protect the content in this struct. * @alloc_map: big map over which LCLA entry is own by which job. */ @@ -420,7 +425,7 @@ struct d40_lcla_pool { void *base; dma_addr_t dma_addr; void *base_unaligned; - int pages; + unsigned int alloc_order; spinlock_t lock; struct d40_desc **alloc_map; }; @@ -504,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; @@ -522,6 +527,7 @@ struct d40_chan { * @high_prio_clear: the high priority clear register * @interrupt_en: the interrupt enable register * @interrupt_clear: the interrupt clear register + * @num_event_groups: number of supported event groups * @il: the pointer to struct d40_interrupt_lookup * @il_size: the size of d40_interrupt_lookup array * @init_reg: the pointer to the struct d40_reg_val @@ -536,6 +542,7 @@ struct d40_gen_dmac { u32 high_prio_clear; u32 interrupt_en; u32 interrupt_clear; + u32 num_event_groups; struct d40_interrupt_lookup *il; u32 il_size; struct d40_reg_val *init_reg; @@ -610,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; @@ -1420,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; @@ -1448,11 +1568,14 @@ static int d40_pause(struct dma_chan *chan) return 0; spin_lock_irqsave(&d40c->lock, flags); - pm_runtime_get_sync(d40c->base->dev); + res = pm_runtime_resume_and_get(d40c->base->dev); + if (res < 0) + goto unlock; res = d40_channel_execute_command(d40c, D40_DMA_SUSPEND_REQ); pm_runtime_put_autosuspend(d40c->base->dev); + unlock: spin_unlock_irqrestore(&d40c->lock, flags); return res; } @@ -1472,13 +1595,16 @@ static int d40_resume(struct dma_chan *chan) return 0; spin_lock_irqsave(&d40c->lock, flags); - pm_runtime_get_sync(d40c->base->dev); + res = pm_runtime_resume_and_get(d40c->base->dev); + if (res < 0) + goto unlock; /* If bytes left to transfer or linked tx resume job */ if (d40_residue(d40c) || d40_tx_is_linked(d40c)) res = d40_channel_execute_command(d40c, D40_DMA_RUN); pm_runtime_put_autosuspend(d40c->base->dev); + unlock: spin_unlock_irqrestore(&d40c->lock, flags); return res; } @@ -1515,8 +1641,20 @@ static struct d40_desc *d40_queue_start(struct d40_chan *d40c) if (d40d != NULL) { if (!d40c->busy) { + err = pm_runtime_resume_and_get(d40c->base->dev); + if (err < 0) { + chan_err(d40c, "Failed to resume DMA: %d\n", + err); + do { + d40_desc_remove(d40d); + d40_desc_done(d40c, d40d); + d40c->pending_tx++; + d40d = d40_first_queued(d40c); + } while (d40d); + tasklet_schedule(&d40c->tasklet); + return ERR_PTR(err); + } d40c->busy = true; - pm_runtime_get_sync(d40c->base->dev); } /* Remove from queue */ @@ -1531,8 +1669,15 @@ static struct d40_desc *d40_queue_start(struct d40_chan *d40c) /* Start dma job */ err = d40_start(d40c); - if (err) - return NULL; + if (err) { + d40_desc_remove(d40d); + d40_desc_done(d40c, d40d); + d40c->pending_tx++; + d40c->busy = false; + pm_runtime_put_autosuspend(d40c->base->dev); + tasklet_schedule(&d40c->tasklet); + return ERR_PTR(err); + } } return d40d; @@ -1542,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); @@ -1566,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); @@ -1576,17 +1724,17 @@ static void dma_tc_handle(struct d40_chan *d40c) return; } + d40_desc_remove(d40d); + d40_desc_done(d40c, d40d); + if (d40_queue_start(d40c) == NULL) { d40c->busy = false; pm_runtime_put_autosuspend(d40c->base->dev); } - - d40_desc_remove(d40d); - d40_desc_done(d40c, d40d); } - d40c->pending_tx++; + d40c->pending_tx += callbacks; tasklet_schedule(&d40c->tasklet); } @@ -1597,20 +1745,22 @@ static void dma_tasklet(struct tasklet_struct *t) struct d40_desc *d40d; unsigned long flags; bool callback_active; + bool from_done; struct dmaengine_desc_callback cb; spin_lock_irqsave(&d40c->lock, flags); /* Get first entry from the done list */ d40d = d40_first_done(d40c); - if (d40d == NULL) { + from_done = !!d40d; + if (!from_done) { /* Check if we have reached here for cyclic job */ d40d = d40_first_active_get(d40c); if (d40d == NULL || !d40d->cyclic) goto check_pending_tx; } - if (!d40d->cyclic) + if (from_done) dma_cookie_complete(&d40d->txd); /* @@ -1626,7 +1776,7 @@ static void dma_tasklet(struct tasklet_struct *t) callback_active = !!(d40d->txd.flags & DMA_PREP_INTERRUPT); dmaengine_desc_get_callback(&d40d->txd, &cb); - if (!d40d->cyclic) { + if (from_done) { if (async_tx_test_ack(&d40d->txd)) { d40_desc_remove(d40d); d40_desc_free(d40c, d40d); @@ -1658,6 +1808,7 @@ static void dma_tasklet(struct tasklet_struct *t) static irqreturn_t d40_handle_interrupt(int irq, void *data) { + irqreturn_t handled = IRQ_NONE; int i; u32 idx; u32 row; @@ -1667,6 +1818,11 @@ static irqreturn_t d40_handle_interrupt(int irq, void *data) u32 *regs = base->regs_interrupt; struct d40_interrupt_lookup *il = base->gen_dmac.il; u32 il_size = base->gen_dmac.il_size; + int ret; + + ret = pm_runtime_get_if_active(base->dev); + if (IS_ENABLED(CONFIG_PM) && ret <= 0) + return IRQ_NONE; spin_lock(&base->interrupt_lock); @@ -1686,6 +1842,12 @@ static irqreturn_t d40_handle_interrupt(int irq, void *data) row = chan / BITS_PER_LONG; idx = chan & (BITS_PER_LONG - 1); + /* + * Status for a channel owned by another core still explains + * the interrupt, but only ACK Linux-owned channels below. + */ + handled = IRQ_HANDLED; + if (il[row].offset == D40_PHY_CHAN) d40c = base->lookup_phy_chans[idx]; else @@ -1715,7 +1877,10 @@ static irqreturn_t d40_handle_interrupt(int irq, void *data) spin_unlock(&base->interrupt_lock); - return IRQ_HANDLED; + if (ret > 0) + pm_runtime_put_autosuspend(base->dev); + + return handled; } static int d40_validate_conf(struct d40_chan *d40c, @@ -1723,19 +1888,43 @@ static int d40_validate_conf(struct d40_chan *d40c, { int res = 0; bool is_log = conf->mode == STEDMA40_MODE_LOGICAL; + bool invalid_dev_type = conf->dev_type < 0; + + if (!invalid_dev_type && + D40_TYPE_TO_GROUP(conf->dev_type) >= + d40c->base->gen_dmac.num_event_groups) + invalid_dev_type = true; - if (!conf->dir) { + if (conf->dir != DMA_MEM_TO_MEM && + !is_slave_direction(conf->dir)) { chan_err(d40c, "Invalid direction.\n"); res = -EINVAL; } - if ((is_log && conf->dev_type > d40c->base->num_log_chans) || - (!is_log && conf->dev_type > d40c->base->num_phy_chans) || - (conf->dev_type < 0)) { + if (!invalid_dev_type && is_log) { + int max_dev_type; + + if (conf->dir == DMA_DEV_TO_MEM) + max_dev_type = DIV_ROUND_UP(d40c->base->num_log_chans, 2); + else + max_dev_type = d40c->base->num_log_chans / 2; + + invalid_dev_type = conf->dev_type >= max_dev_type; + } + + if (invalid_dev_type) { chan_err(d40c, "Invalid device type (%d)\n", conf->dev_type); res = -EINVAL; } + if (conf->use_fixed_channel && + (conf->phy_channel < 0 || + conf->phy_channel >= d40c->base->num_phy_chans)) { + chan_err(d40c, "Invalid physical channel (%d)\n", + conf->phy_channel); + res = -EINVAL; + } + if (conf->dir == DMA_DEV_TO_DEV) { /* * DMAC HW supports it. Will be added to this driver, @@ -1848,6 +2037,12 @@ static bool d40_alloc_mask_free(struct d40_phy_res *phy, bool is_src, return is_free; } +static int d40_phy_to_group(struct d40_base *base, int phy) +{ + return (phy / D40_PHYS_PER_EVENT_GROUP) % + base->gen_dmac.num_event_groups; +} + static int d40_allocate_channel(struct d40_chan *d40c, bool *first_phy_user) { int dev_type = d40c->dma_cfg.dev_type; @@ -1858,11 +2053,14 @@ static int d40_allocate_channel(struct d40_chan *d40c, bool *first_phy_user) int j; int log_num; int num_phy_chans; + int phy_group_stride; bool is_src; bool is_log = d40c->dma_cfg.mode == STEDMA40_MODE_LOGICAL; phys = d40c->base->phy_res; num_phy_chans = d40c->base->num_phy_chans; + phy_group_stride = D40_PHYS_PER_EVENT_GROUP * + d40c->base->gen_dmac.num_event_groups; if (d40c->dma_cfg.dir == DMA_DEV_TO_MEM) { log_num = 2 * dev_type; @@ -1896,9 +2094,18 @@ static int d40_allocate_channel(struct d40_chan *d40c, bool *first_phy_user) } } } else - for (j = 0; j < d40c->base->num_phy_chans; j += 8) { - int phy_num = j + event_group * 2; - for (i = phy_num; i < phy_num + 2; i++) { + for (j = 0; j < num_phy_chans; + j += phy_group_stride) { + int phy_num = j + event_group * + D40_PHYS_PER_EVENT_GROUP; + + if (phy_num + D40_PHYS_PER_EVENT_GROUP > + num_phy_chans) + break; + + for (i = phy_num; + i < phy_num + D40_PHYS_PER_EVENT_GROUP; + i++) { if (d40_alloc_mask_set(&phys[i], is_src, 0, @@ -1917,8 +2124,11 @@ static int d40_allocate_channel(struct d40_chan *d40c, bool *first_phy_user) return -EINVAL; /* Find logical channel */ - for (j = 0; j < d40c->base->num_phy_chans; j += 8) { - int phy_num = j + event_group * 2; + for (j = 0; j < num_phy_chans; j += phy_group_stride) { + int phy_num = j + event_group * D40_PHYS_PER_EVENT_GROUP; + + if (phy_num + D40_PHYS_PER_EVENT_GROUP > num_phy_chans) + break; if (d40c->dma_cfg.use_fixed_channel) { i = d40c->dma_cfg.phy_channel; @@ -1944,14 +2154,17 @@ static int d40_allocate_channel(struct d40_chan *d40c, bool *first_phy_user) * channels. */ if (is_src) { - for (i = phy_num; i < phy_num + 2; i++) { + for (i = phy_num; + i < phy_num + D40_PHYS_PER_EVENT_GROUP; + i++) { if (d40_alloc_mask_set(&phys[i], is_src, event_line, is_log, first_phy_user)) goto found_log; } } else { - for (i = phy_num + 1; i >= phy_num; i--) { + for (i = phy_num + D40_PHYS_PER_EVENT_GROUP - 1; + i >= phy_num; i--) { if (d40_alloc_mask_set(&phys[i], is_src, event_line, is_log, first_phy_user)) @@ -1978,10 +2191,16 @@ static int d40_allocate_channel(struct d40_chan *d40c, bool *first_phy_user) static int d40_config_memcpy(struct d40_chan *d40c) { dma_cap_mask_t cap = d40c->chan.device->cap_mask; + int ret; if (dma_has_cap(DMA_MEMCPY, cap) && !dma_has_cap(DMA_SLAVE, cap)) { d40c->dma_cfg = dma40_memcpy_conf_log; - d40c->dma_cfg.dev_type = dma40_memcpy_channels[d40c->chan.chan_id]; + d40c->dma_cfg.dev_type = + d40c->base->plat_data->memcpy_channels[d40c->chan.chan_id]; + + ret = d40_validate_conf(d40c, &d40c->dma_cfg); + if (ret) + return ret; d40_log_cfg(&d40c->dma_cfg, &d40c->log_def.lcsp1, &d40c->log_def.lcsp3); @@ -1990,6 +2209,10 @@ static int d40_config_memcpy(struct d40_chan *d40c) dma_has_cap(DMA_SLAVE, cap)) { d40c->dma_cfg = dma40_memcpy_conf_phy; + ret = d40_validate_conf(d40c, &d40c->dma_cfg); + if (ret) + return ret; + /* Generate interrupt at end of transfer or relink. */ d40c->dst_def_cfg |= BIT(D40_SREG_CFG_TIM_POS); @@ -2013,9 +2236,6 @@ static int d40_free_dma(struct d40_chan *d40c) struct d40_phy_res *phy = d40c->phy_chan; bool is_src; - /* Terminate all queued and active transfers */ - d40_term_all(d40c); - if (phy == NULL) { chan_err(d40c, "phy == null\n"); return -EINVAL; @@ -2037,11 +2257,18 @@ static int d40_free_dma(struct d40_chan *d40c) return -EINVAL; } - pm_runtime_get_sync(d40c->base->dev); - res = d40_channel_execute_command(d40c, D40_DMA_STOP); - if (res) { - chan_err(d40c, "stop failed\n"); - goto mark_last_busy; + /* Release descriptor state; this does not access DMA40 registers. */ + d40_term_all(d40c); + + res = pm_runtime_resume_and_get(d40c->base->dev); + if (res >= 0) { + res = d40_channel_execute_command(d40c, D40_DMA_STOP); + if (res) + chan_err(d40c, "stop failed\n"); + + pm_runtime_put_autosuspend(d40c->base->dev); + if (res) + return res; } d40_alloc_mask_free(phy, is_src, chan_is_logical(d40c) ? event : 0); @@ -2057,8 +2284,6 @@ static int d40_free_dma(struct d40_chan *d40c) d40c->busy = false; d40c->phy_chan = NULL; d40c->configured = false; - mark_last_busy: - pm_runtime_put_autosuspend(d40c->base->dev); return res; } @@ -2108,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; @@ -2238,7 +2474,13 @@ d40_prep_sg(struct dma_chan *dchan, struct scatterlist *sg_src, return NULL; } - d40_set_runtime_config_write(dchan, &chan->slave_config, direction); + if (direction != DMA_MEM_TO_MEM) { + ret = d40_set_runtime_config_write(dchan, + &chan->slave_config, + direction); + if (ret) + return NULL; + } spin_lock_irqsave(&chan->lock, flags); @@ -2246,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; @@ -2365,6 +2612,9 @@ static struct dma_chan *d40_xlate(struct of_phandle_args *dma_spec, dma_cap_mask_t cap; u32 flags; + if (dma_spec->args_count != 3) + return NULL; + memset(&cfg, 0, sizeof(struct stedma40_chan_cfg)); dma_cap_zero(cap); @@ -2417,10 +2667,14 @@ static int d40_alloc_chan_resources(struct dma_chan *chan) err = d40_config_memcpy(d40c); if (err) { chan_err(d40c, "Failed to configure memcpy channel\n"); - goto mark_last_busy; + goto unlock; } } + err = pm_runtime_resume_and_get(d40c->base->dev); + if (err < 0) + goto unlock; + err = d40_allocate_channel(d40c, &is_free_phy); if (err) { chan_err(d40c, "Failed to allocate channel\n"); @@ -2428,8 +2682,6 @@ static int d40_alloc_chan_resources(struct dma_chan *chan) goto mark_last_busy; } - pm_runtime_get_sync(d40c->base->dev); - d40_set_prio_realtime(d40c); if (chan_is_logical(d40c)) { @@ -2461,6 +2713,7 @@ static int d40_alloc_chan_resources(struct dma_chan *chan) d40_config_write(d40c); mark_last_busy: pm_runtime_put_autosuspend(d40c->base->dev); + unlock: spin_unlock_irqrestore(&d40c->lock, flags); return err; } @@ -2524,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 = kzalloc_objs(struct scatterlist, periods + 1, GFP_NOWAIT); if (!sg) return NULL; @@ -2543,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); @@ -2563,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; @@ -2605,19 +2874,26 @@ static int d40_terminate_all(struct dma_chan *chan) spin_lock_irqsave(&d40c->lock, flags); - pm_runtime_get_sync(d40c->base->dev); - ret = d40_channel_execute_command(d40c, D40_DMA_STOP); - if (ret) - chan_err(d40c, "Failed to stop channel\n"); + ret = pm_runtime_resume_and_get(d40c->base->dev); + if (ret >= 0) { + ret = d40_channel_execute_command(d40c, D40_DMA_STOP); + if (ret) + chan_err(d40c, "Failed to stop channel\n"); + + pm_runtime_put_autosuspend(d40c->base->dev); + } + /* + * Always release software state, even when the controller cannot + * resume. d40_term_all() does not access DMA40 registers. + */ d40_term_all(d40c); - pm_runtime_put_autosuspend(d40c->base->dev); if (d40c->busy) pm_runtime_put_autosuspend(d40c->base->dev); d40c->busy = false; spin_unlock_irqrestore(&d40c->lock, flags); - return 0; + return ret; } static int @@ -2680,6 +2956,13 @@ static int d40_set_runtime_config_write(struct dma_chan *chan, return -EINVAL; } + if (direction != cfg->dir) { + chan_err(d40c, + "transfer direction %d differs from allocated direction %d\n", + direction, cfg->dir); + return -EINVAL; + } + src_addr_width = config->src_addr_width; src_maxburst = config->src_maxburst; dst_addr_width = config->dst_addr_width; @@ -2688,13 +2971,6 @@ static int d40_set_runtime_config_write(struct dma_chan *chan, if (direction == DMA_DEV_TO_MEM) { config_addr = config->src_addr; - if (cfg->dir != DMA_DEV_TO_MEM) - dev_dbg(d40c->base->dev, - "channel was not configured for peripheral " - "to memory transfer (%d) overriding\n", - cfg->dir); - cfg->dir = DMA_DEV_TO_MEM; - /* Configure the memory side */ if (dst_addr_width == DMA_SLAVE_BUSWIDTH_UNDEFINED) dst_addr_width = src_addr_width; @@ -2704,13 +2980,6 @@ static int d40_set_runtime_config_write(struct dma_chan *chan, } else if (direction == DMA_MEM_TO_DEV) { config_addr = config->dst_addr; - if (cfg->dir != DMA_MEM_TO_DEV) - dev_dbg(d40c->base->dev, - "channel was not configured for memory " - "to peripheral transfer (%d) overriding\n", - cfg->dir); - cfg->dir = DMA_MEM_TO_DEV; - /* Configure the memory side */ if (src_addr_width == DMA_SLAVE_BUSWIDTH_UNDEFINED) src_addr_width = dst_addr_width; @@ -2822,6 +3091,18 @@ static void __init d40_chan_init(struct d40_base *base, struct dma_device *dma, } } +static void d40_kill_tasklets(void *data) +{ + struct dma_device *dma = data; + struct d40_chan *d40c; + struct dma_chan *chan; + + list_for_each_entry(chan, &dma->channels, device_node) { + d40c = container_of(chan, struct d40_chan, chan); + tasklet_kill(&d40c->tasklet); + } +} + static void d40_ops_init(struct d40_base *base, struct dma_device *dev) { if (dma_has_cap(DMA_SLAVE, dev->cap_mask)) { @@ -2868,6 +3149,11 @@ static int __init d40_dmaengine_init(struct d40_base *base, d40_ops_init(base, &base->dma_slave); + err = devm_add_action(base->dev, d40_kill_tasklets, + &base->dma_slave); + if (err) + goto exit; + err = dmaenginem_async_device_register(&base->dma_slave); if (err) { @@ -2883,6 +3169,11 @@ static int __init d40_dmaengine_init(struct d40_base *base, d40_ops_init(base, &base->dma_memcpy); + err = devm_add_action(base->dev, d40_kill_tasklets, + &base->dma_memcpy); + if (err) + goto exit; + err = dmaenginem_async_device_register(&base->dma_memcpy); if (err) { @@ -2897,9 +3188,15 @@ static int __init d40_dmaengine_init(struct d40_base *base, dma_cap_zero(base->dma_both.cap_mask); dma_cap_set(DMA_SLAVE, base->dma_both.cap_mask); dma_cap_set(DMA_MEMCPY, base->dma_both.cap_mask); - dma_cap_set(DMA_CYCLIC, base->dma_slave.cap_mask); + dma_cap_set(DMA_CYCLIC, base->dma_both.cap_mask); d40_ops_init(base, &base->dma_both); + + err = devm_add_action(base->dev, d40_kill_tasklets, + &base->dma_both); + if (err) + goto exit; + err = dmaenginem_async_device_register(&base->dma_both); if (err) { @@ -3047,9 +3344,9 @@ static int __init d40_phy_res_init(struct d40_base *base) base->phy_res[i].allocated_src = D40_ALLOC_PHY; base->phy_res[i].allocated_dst = D40_ALLOC_PHY; base->phy_res[i].reserved = true; - gcc |= D40_DREG_GCC_EVTGRP_ENA(D40_PHYS_TO_GROUP(i), + gcc |= D40_DREG_GCC_EVTGRP_ENA(d40_phy_to_group(base, i), D40_DREG_GCC_SRC); - gcc |= D40_DREG_GCC_EVTGRP_ENA(D40_PHYS_TO_GROUP(i), + gcc |= D40_DREG_GCC_EVTGRP_ENA(d40_phy_to_group(base, i), D40_DREG_GCC_DST); @@ -3069,9 +3366,9 @@ static int __init d40_phy_res_init(struct d40_base *base) base->phy_res[chan].allocated_src = D40_ALLOC_PHY; base->phy_res[chan].allocated_dst = D40_ALLOC_PHY; base->phy_res[chan].reserved = true; - gcc |= D40_DREG_GCC_EVTGRP_ENA(D40_PHYS_TO_GROUP(chan), + gcc |= D40_DREG_GCC_EVTGRP_ENA(d40_phy_to_group(base, chan), D40_DREG_GCC_SRC); - gcc |= D40_DREG_GCC_EVTGRP_ENA(D40_PHYS_TO_GROUP(chan), + gcc |= D40_DREG_GCC_EVTGRP_ENA(d40_phy_to_group(base, chan), D40_DREG_GCC_DST); num_phy_chans_avail--; } @@ -3188,13 +3485,17 @@ static int __init d40_hw_detect_init(struct platform_device *pdev, num_phy_chans = min(num_phy_chans, STEDMA40_MAX_PHYS); - /* The number of channels used for memcpy */ - if (plat_data->num_of_memcpy_chans) - num_memcpy_chans = plat_data->num_of_memcpy_chans; - else - num_memcpy_chans = ARRAY_SIZE(dma40_memcpy_channels); + for (i = 0; plat_data->disabled_channels[i] != -1; i++) { + int chan = plat_data->disabled_channels[i]; + + if (chan < 0 || chan >= num_phy_chans) { + dev_err(dev, "Invalid disabled channel %d\n", chan); + return -EINVAL; + } + } - num_memcpy_chans = min(num_memcpy_chans, D40_MEMCPY_MAX_CHANS); + /* The number of channels used for memcpy */ + num_memcpy_chans = plat_data->num_of_memcpy_chans; num_log_chans = num_phy_chans * D40_MAX_LOG_CHAN_PER_PHY; dev_info(dev, @@ -3219,6 +3520,7 @@ static int __init d40_hw_detect_init(struct platform_device *pdev, base->log_chans = &base->phy_chans[num_phy_chans]; if (base->plat_data->num_of_phy_chans == 14) { + base->gen_dmac.num_event_groups = D40_EVENT_GROUPS_V4B; base->gen_dmac.backup = d40_backup_regs_v4b; base->gen_dmac.backup_size = BACKUP_REGS_SZ_V4B; base->gen_dmac.interrupt_en = D40_DREG_CPCMIS; @@ -3232,6 +3534,7 @@ static int __init d40_hw_detect_init(struct platform_device *pdev, base->gen_dmac.init_reg = dma_init_reg_v4b; base->gen_dmac.init_reg_size = ARRAY_SIZE(dma_init_reg_v4b); } else { + base->gen_dmac.num_event_groups = D40_EVENT_GROUPS_V4A; if (base->rev >= 3) { base->gen_dmac.backup = d40_backup_regs_v4a; base->gen_dmac.backup_size = BACKUP_REGS_SZ_V4A; @@ -3358,6 +3661,7 @@ static void __init d40_hw_init(struct d40_base *base) static int __init d40_lcla_allocate(struct d40_base *base) { struct d40_lcla_pool *pool = &base->lcla_pool; + size_t lcla_size = SZ_1K * base->num_phy_chans; unsigned long *page_list; int i, j; int ret; @@ -3373,20 +3677,20 @@ static int __init d40_lcla_allocate(struct d40_base *base) if (!page_list) return -ENOMEM; - /* Calculating how many pages that are required */ - base->lcla_pool.pages = SZ_1K * base->num_phy_chans / PAGE_SIZE; + base->lcla_pool.alloc_order = get_order(lcla_size); for (i = 0; i < MAX_LCLA_ALLOC_ATTEMPTS; i++) { page_list[i] = __get_free_pages(GFP_KERNEL, - base->lcla_pool.pages); + base->lcla_pool.alloc_order); if (!page_list[i]) { - d40_err(base->dev, "Failed to allocate %d pages.\n", - base->lcla_pool.pages); + d40_err(base->dev, "Failed to allocate %zu bytes.\n", + lcla_size); ret = -ENOMEM; for (j = 0; j < i; j++) - free_pages(page_list[j], base->lcla_pool.pages); + free_pages(page_list[j], + base->lcla_pool.alloc_order); goto free_page_list; } @@ -3396,7 +3700,7 @@ static int __init d40_lcla_allocate(struct d40_base *base) } for (j = 0; j < i; j++) - free_pages(page_list[j], base->lcla_pool.pages); + free_pages(page_list[j], base->lcla_pool.alloc_order); if (i < MAX_LCLA_ALLOC_ATTEMPTS) { base->lcla_pool.base = (void *)page_list[i]; @@ -3406,10 +3710,9 @@ static int __init d40_lcla_allocate(struct d40_base *base) * alignment, try with allocating a big buffer. */ dev_warn(base->dev, - "[%s] Failed to get %d pages @ 18 bit align.\n", - __func__, base->lcla_pool.pages); - base->lcla_pool.base_unaligned = kmalloc(SZ_1K * - base->num_phy_chans + + "[%s] Failed to get %zu bytes @ 18 bit align.\n", + __func__, lcla_size); + base->lcla_pool.base_unaligned = kmalloc(lcla_size + LCLA_ALIGNMENT, GFP_KERNEL); if (!base->lcla_pool.base_unaligned) { @@ -3421,8 +3724,7 @@ static int __init d40_lcla_allocate(struct d40_base *base) LCLA_ALIGNMENT); } - pool->dma_addr = dma_map_single(base->dev, pool->base, - SZ_1K * base->num_phy_chans, + pool->dma_addr = dma_map_single(base->dev, pool->base, lcla_size, DMA_TO_DEVICE); if (dma_mapping_error(base->dev, pool->dma_addr)) { pool->dma_addr = 0; @@ -3444,6 +3746,7 @@ static int __init d40_of_probe(struct device *dev, struct stedma40_platform_data *pdata; int num_phy = 0, num_memcpy = 0, num_disabled = 0; const __be32 *list; + int ret; pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) @@ -3457,18 +3760,19 @@ static int __init d40_of_probe(struct device *dev, list = of_get_property(np, "memcpy-channels", &num_memcpy); num_memcpy /= sizeof(*list); - if (num_memcpy > D40_MEMCPY_MAX_CHANS || num_memcpy <= 0) { + if (num_memcpy > ARRAY_SIZE(pdata->memcpy_channels) || + num_memcpy <= 0) { d40_err(dev, "Invalid number of memcpy channels specified (%d)\n", num_memcpy); return -EINVAL; } + ret = of_property_read_u32_array(np, "memcpy-channels", + pdata->memcpy_channels, num_memcpy); + if (ret) + return ret; pdata->num_of_memcpy_chans = num_memcpy; - of_property_read_u32_array(np, "memcpy-channels", - dma40_memcpy_channels, - num_memcpy); - list = of_get_property(np, "disabled-channels", &num_disabled); num_disabled /= sizeof(*list); @@ -3497,6 +3801,7 @@ static int __init d40_probe(struct platform_device *pdev) struct d40_base *base; struct resource *res; struct resource res_lcpa; + void *dmaenginem_reg_group; int num_reserved_chans; u32 val; int ret; @@ -3526,6 +3831,7 @@ static int __init d40_probe(struct platform_device *pdev) } /* This is no device so read the address directly from the node */ ret = of_address_to_resource(np_lcpa, 0, &res_lcpa); + of_node_put(np_lcpa); if (ret) { dev_err(dev, "no LCPA SRAM resource\n"); goto report_failure; @@ -3585,12 +3891,6 @@ static int __init d40_probe(struct platform_device *pdev) goto destroy_cache; } - ret = request_irq(base->irq, d40_handle_interrupt, 0, D40_NAME, base); - if (ret) { - d40_err(dev, "No IRQ defined\n"); - goto destroy_cache; - } - if (base->plat_data->use_esram_lcla) { base->lcpa_regulator = regulator_get(base->dev, "lcla_esram"); @@ -3615,38 +3915,62 @@ static int __init d40_probe(struct platform_device *pdev) pm_runtime_irq_safe(base->dev); pm_runtime_set_autosuspend_delay(base->dev, DMA40_AUTOSUSPEND_DELAY); - pm_runtime_use_autosuspend(base->dev); pm_runtime_mark_last_busy(base->dev); - pm_runtime_set_active(base->dev); - pm_runtime_enable(base->dev); - ret = d40_dmaengine_init(base, num_reserved_chans); - if (ret) + ret = devm_pm_runtime_set_active_enabled(base->dev); + if (ret) { + d40_err(dev, "Failed to enable runtime PM: %d\n", ret); goto destroy_cache; + } + pm_runtime_use_autosuspend(base->dev); dma_set_max_seg_size(base->dev, STEDMA40_MAX_SEG_SIZE); d40_hw_init(base); + ret = request_irq(base->irq, d40_handle_interrupt, 0, D40_NAME, base); + if (ret) { + d40_err(dev, "No IRQ defined\n"); + goto destroy_cache; + } + + dmaenginem_reg_group = devres_open_group(dev, NULL, GFP_KERNEL); + if (!dmaenginem_reg_group) { + ret = -ENOMEM; + goto release_irq; + } + + ret = d40_dmaengine_init(base, num_reserved_chans); + if (ret) + goto release_dmaenginem; + ret = of_dma_controller_register(np, d40_xlate, NULL); if (ret) { dev_err(dev, "could not register of_dma_controller\n"); - goto destroy_cache; + goto release_dmaenginem; } + devres_remove_group(dev, dmaenginem_reg_group); dev_info(base->dev, "initialized\n"); return 0; + release_dmaenginem: + free_irq(base->irq, base); + devres_release_group(dev, dmaenginem_reg_group); + goto destroy_cache; + release_irq: + free_irq(base->irq, base); destroy_cache: if (base->lcla_pool.dma_addr) dma_unmap_single(base->dev, base->lcla_pool.dma_addr, SZ_1K * base->num_phy_chans, DMA_TO_DEVICE); - if (!base->lcla_pool.base_unaligned && base->lcla_pool.base) + if (!base->plat_data->use_esram_lcla && + !base->lcla_pool.base_unaligned && base->lcla_pool.base) free_pages((unsigned long)base->lcla_pool.base, - base->lcla_pool.pages); + base->lcla_pool.alloc_order); kfree(base->lcla_pool.base_unaligned); @@ -3654,7 +3978,6 @@ static int __init d40_probe(struct platform_device *pdev) regulator_disable(base->lcpa_regulator); regulator_put(base->lcpa_regulator); } - pm_runtime_disable(base->dev); report_failure: d40_err(dev, "probe failed\n"); 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 2e30e9a94a1e..ca9d07649361 100644 --- a/drivers/dma/ste_dma40_ll.h +++ b/drivers/dma/ste_dma40_ll.h @@ -16,8 +16,6 @@ #define D40_TYPE_TO_GROUP(type) (type / 16) #define D40_TYPE_TO_EVENT(type) (type % 16) -#define D40_GROUP_SIZE 8 -#define D40_PHYS_TO_GROUP(phys) ((phys & (D40_GROUP_SIZE - 1)) / 2) /* Most bits of the CFG register are the same in log as in phy mode */ #define D40_SREG_CFG_MST_POS 15 @@ -457,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/sun6i-dma.c b/drivers/dma/sun6i-dma.c index 7704b016aed8..738f2547a1b9 100644 --- a/drivers/dma/sun6i-dma.c +++ b/drivers/dma/sun6i-dma.c @@ -408,16 +408,12 @@ static inline void sun6i_dma_dump_lli(struct sun6i_vchan *vchan, v_lli->len, v_lli->para, v_lli->p_lli_next); } -static void sun6i_dma_free_desc(struct virt_dma_desc *vd) +static void sun6i_dma_free_desc(struct sun6i_dma_dev *sdev, + struct sun6i_desc *txd) { - struct sun6i_desc *txd = to_sun6i_desc(&vd->tx); - struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(vd->tx.chan->device); struct sun6i_dma_lli *v_lli, *v_next; dma_addr_t p_lli, p_next; - if (unlikely(!txd)) - return; - p_lli = txd->p_lli; v_lli = txd->v_lli; @@ -434,6 +430,17 @@ static void sun6i_dma_free_desc(struct virt_dma_desc *vd) kfree(txd); } +static void sun6i_dma_free_desc_virt(struct virt_dma_desc *vd) +{ + struct sun6i_desc *txd = to_sun6i_desc(&vd->tx); + struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(vd->tx.chan->device); + + if (unlikely(!txd)) + return; + + sun6i_dma_free_desc(sdev, txd); +} + static int sun6i_dma_start_desc(struct sun6i_vchan *vchan) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(vchan->vc.chan.device); @@ -790,10 +797,7 @@ static struct dma_async_tx_descriptor *sun6i_dma_prep_slave_sg( return vchan_tx_prep(&vchan->vc, &txd->vd, flags); err_lli_free: - for (p_lli = txd->p_lli, v_lli = txd->v_lli; v_lli; - p_lli = v_lli->p_lli_next, v_lli = v_lli->v_lli_next) - dma_pool_free(sdev->pool, v_lli, p_lli); - kfree(txd); + sun6i_dma_free_desc(sdev, txd); return NULL; } @@ -871,10 +875,7 @@ static struct dma_async_tx_descriptor *sun6i_dma_prep_dma_cyclic( return vchan_tx_prep(&vchan->vc, &txd->vd, flags); err_lli_free: - for (p_lli = txd->p_lli, v_lli = txd->v_lli; v_lli; - p_lli = v_lli->p_lli_next, v_lli = v_lli->v_lli_next) - dma_pool_free(sdev->pool, v_lli, p_lli); - kfree(txd); + sun6i_dma_free_desc(sdev, txd); return NULL; } @@ -1429,7 +1430,7 @@ static int sun6i_dma_probe(struct platform_device *pdev) struct sun6i_vchan *vchan = &sdc->vchans[i]; INIT_LIST_HEAD(&vchan->node); - vchan->vc.desc_free = sun6i_dma_free_desc; + vchan->vc.desc_free = sun6i_dma_free_desc_virt; vchan_init(&vchan->vc, &sdc->slave); } diff --git a/drivers/dma/switchtec_dma.c b/drivers/dma/switchtec_dma.c index c8e2169877e9..1708e7ff840d 100644 --- a/drivers/dma/switchtec_dma.c +++ b/drivers/dma/switchtec_dma.c @@ -886,14 +886,18 @@ static void switchtec_dma_free_desc(struct switchtec_dma_chan *swdma_chan) if (swdma_chan->hw_sq) dma_free_coherent(swdma_dev->dma_dev.dev, size, swdma_chan->hw_sq, swdma_chan->dma_addr_sq); + swdma_chan->hw_sq = NULL; size = SWITCHTEC_DMA_CQ_SIZE * sizeof(*swdma_chan->hw_cq); if (swdma_chan->hw_cq) dma_free_coherent(swdma_dev->dma_dev.dev, size, swdma_chan->hw_cq, swdma_chan->dma_addr_cq); + swdma_chan->hw_cq = NULL; - for (i = 0; i < SWITCHTEC_DMA_RING_SIZE; i++) + for (i = 0; i < SWITCHTEC_DMA_RING_SIZE; i++) { kfree(swdma_chan->desc_ring[i]); + swdma_chan->desc_ring[i] = NULL; + } } static int switchtec_dma_alloc_desc(struct switchtec_dma_chan *swdma_chan) @@ -984,15 +988,15 @@ static int switchtec_dma_alloc_chan_resources(struct dma_chan *chan) rc = enable_channel(swdma_chan); if (rc) - return rc; + goto err_free_desc; rc = reset_channel(swdma_chan); if (rc) - return rc; + goto err_disable_channel; rc = unhalt_channel(swdma_chan); if (rc) - return rc; + goto err_disable_channel; swdma_chan->ring_active = true; swdma_chan->comp_ring_active = true; @@ -1003,7 +1007,8 @@ static int switchtec_dma_alloc_chan_resources(struct dma_chan *chan) rcu_read_lock(); if (!rcu_dereference(swdma_dev->pdev)) { rcu_read_unlock(); - return -ENODEV; + rc = -ENODEV; + goto err_ring_inactive; } perf_cfg = readl(&swdma_chan->mmio_chan_fw->perf_cfg); @@ -1025,6 +1030,20 @@ static int switchtec_dma_alloc_chan_resources(struct dma_chan *chan) FIELD_GET(PERF_MRRS_MASK, perf_cfg)); return SWITCHTEC_DMA_SQ_SIZE; + +err_ring_inactive: + spin_lock_bh(&swdma_chan->submit_lock); + swdma_chan->ring_active = false; + spin_unlock_bh(&swdma_chan->submit_lock); + + spin_lock_bh(&swdma_chan->complete_lock); + swdma_chan->comp_ring_active = false; + spin_unlock_bh(&swdma_chan->complete_lock); +err_disable_channel: + disable_channel(swdma_chan); +err_free_desc: + switchtec_dma_free_desc(swdma_chan); + return rc; } static void switchtec_dma_free_chan_resources(struct dma_chan *chan) @@ -1156,6 +1175,18 @@ static int switchtec_dma_chans_release(struct pci_dev *pdev, return 0; } +static void switchtec_dma_chans_free(struct switchtec_dma_dev *swdma_dev) +{ + int i; + + for (i = 0; i < swdma_dev->chan_cnt; i++) { + list_del(&swdma_dev->swdma_chans[i]->dma_chan.device_node); + kfree(swdma_dev->swdma_chans[i]); + } + + kfree(swdma_dev->swdma_chans); +} + static int switchtec_dma_chans_enumerate(struct switchtec_dma_dev *swdma_dev, struct pci_dev *pdev, int chan_cnt) { @@ -1180,7 +1211,7 @@ static int switchtec_dma_chans_enumerate(struct switchtec_dma_dev *swdma_dev, if (rc) { dev_err(&pdev->dev, "Channel %d: init channel failed\n", i); - chan_cnt = i; + swdma_dev->chan_cnt = i; goto err_exit; } } @@ -1188,10 +1219,8 @@ static int switchtec_dma_chans_enumerate(struct switchtec_dma_dev *swdma_dev, return chan_cnt; err_exit: - for (i = 0; i < chan_cnt; i++) - switchtec_dma_chan_free(pdev, swdma_dev->swdma_chans[i]); - - kfree(swdma_dev->swdma_chans); + switchtec_dma_chans_release(pdev, swdma_dev); + switchtec_dma_chans_free(swdma_dev); return rc; } @@ -1200,12 +1229,8 @@ static void switchtec_dma_release(struct dma_device *dma_dev) { struct switchtec_dma_dev *swdma_dev = container_of(dma_dev, struct switchtec_dma_dev, dma_dev); - int i; - for (i = 0; i < swdma_dev->chan_cnt; i++) - kfree(swdma_dev->swdma_chans[i]); - - kfree(swdma_dev->swdma_chans); + switchtec_dma_chans_free(swdma_dev); put_device(dma_dev->dev); kfree(swdma_dev); @@ -1296,6 +1321,7 @@ static int switchtec_dma_create(struct pci_dev *pdev) err_chans_release_exit: switchtec_dma_chans_release(pdev, swdma_dev); + switchtec_dma_chans_free(swdma_dev); err_exit: if (swdma_dev->chan_status_irq) diff --git a/drivers/dma/xilinx/xilinx_dma.c b/drivers/dma/xilinx/xilinx_dma.c index cffe7c6fa640..1792e8cefad2 100644 --- a/drivers/dma/xilinx/xilinx_dma.c +++ b/drivers/dma/xilinx/xilinx_dma.c @@ -223,6 +223,7 @@ #define XILINX_MCDMA_IRQ_ERR_MASK BIT(7) #define XILINX_MCDMA_BD_EOP BIT(30) #define XILINX_MCDMA_BD_SOP BIT(31) +#define XILINX_MCDMA_BD_HW_SIZE 64 /** * struct xilinx_vdma_desc_hw - Hardware Descriptor @@ -277,8 +278,10 @@ struct xilinx_axidma_desc_hw { * @buf_addr_msb: MSB of Buffer address @0x0C * @rsvd: Reserved field @0x10 * @control: Control Information field @0x14 - * @status: Status field @0x18 - * @sideband_status: Status of sideband signals @0x1C + * @mm2s_ctrl_sideband: Sideband control info for mm2s @0x18 + * @s2mm_status: Status field for s2mm @0x18 + * @mm2s_status: Status field for mm2s @0x1C + * @s2mm_sideband_status: Sideband status for s2mm @0x1C * @app: APP Fields @0x20 - 0x30 */ struct xilinx_aximcdma_desc_hw { @@ -288,10 +291,17 @@ struct xilinx_aximcdma_desc_hw { u32 buf_addr_msb; u32 rsvd; u32 control; - u32 status; - u32 sideband_status; + union { + u32 mm2s_ctrl_sideband; + u32 s2mm_status; + }; + union { + u32 mm2s_status; + u32 s2mm_sideband_status; + }; u32 app[XILINX_DMA_NUM_APP_WORDS]; } __aligned(64); +static_assert(sizeof(struct xilinx_aximcdma_desc_hw) == XILINX_MCDMA_BD_HW_SIZE); /** * struct xilinx_cdma_desc_hw - Hardware Descriptor @@ -1025,9 +1035,11 @@ static u32 xilinx_dma_get_residue(struct xilinx_dma_chan *chan, struct xilinx_aximcdma_tx_segment, node); aximcdma_hw = &aximcdma_seg->hw; - residue += - (aximcdma_hw->control & chan->xdev->max_buffer_len) - - (aximcdma_hw->status & chan->xdev->max_buffer_len); + residue += aximcdma_hw->control & chan->xdev->max_buffer_len; + if (chan->direction == DMA_DEV_TO_MEM) + residue -= aximcdma_hw->s2mm_status & chan->xdev->max_buffer_len; + else + residue -= aximcdma_hw->mm2s_status & chan->xdev->max_buffer_len; } } @@ -1782,6 +1794,17 @@ static void xilinx_dma_complete_descriptor(struct xilinx_dma_chan *chan) struct xilinx_axidma_tx_segment, node); if (!(seg->hw.status & XILINX_DMA_BD_COMP_MASK) && chan->has_sg) break; + } else if (chan->xdev->dma_config->dmatype == XDMA_TYPE_AXIMCDMA) { + struct xilinx_aximcdma_tx_segment *seg; + u32 status; + + seg = list_last_entry(&desc->segments, + struct xilinx_aximcdma_tx_segment, + node); + status = (chan->direction == DMA_DEV_TO_MEM) ? + seg->hw.s2mm_status : seg->hw.mm2s_status; + if (!(status & XILINX_DMA_BD_COMP_MASK)) + break; } if (chan->has_sg && chan->xdev->dma_config->dmatype != XDMA_TYPE_VDMA) diff --git a/drivers/dma/xilinx/zynqmp_dma.c b/drivers/dma/xilinx/zynqmp_dma.c index 2b03584102ac..56464b6dc283 100644 --- a/drivers/dma/xilinx/zynqmp_dma.c +++ b/drivers/dma/xilinx/zynqmp_dma.c @@ -205,7 +205,7 @@ struct zynqmp_dma_desc_sw { * @desc_pool_p: Physical allocated descriptor base * @desc_free_cnt: Descriptor available count * @dev: The dma device - * @irq: Channel IRQ + * @irq: Linux IRQ number, or -1 when not registered * @is_dmacoherent: Tells whether dma operations are coherent or not * @tasklet: Cleanup work after irq * @idle : Channel status; @@ -483,8 +483,10 @@ static int zynqmp_dma_alloc_chan_resources(struct dma_chan *dchan) return ret; chan->sw_desc_pool = kzalloc_objs(*desc, ZYNQMP_DMA_NUM_DESCS); - 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; @@ -502,8 +504,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; @@ -516,6 +520,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; } /** @@ -885,10 +896,11 @@ static void zynqmp_dma_chan_remove(struct zynqmp_dma_chan *chan) if (!chan) return; - if (chan->irq) + if (chan->irq >= 0) devm_free_irq(chan->zdev->dev, chan->irq, chan); tasklet_kill(&chan->tasklet); - list_del(&chan->common.device_node); + if (!list_empty(&chan->common.device_node)) + list_del(&chan->common.device_node); } /** @@ -904,13 +916,14 @@ static int zynqmp_dma_chan_probe(struct zynqmp_dma_device *zdev, struct zynqmp_dma_chan *chan; struct device_node *node = pdev->dev.of_node; const struct zynqmp_dma_config *match_data; - int err; + int err, ret; chan = devm_kzalloc(zdev->dev, sizeof(*chan), GFP_KERNEL); if (!chan) return -ENOMEM; chan->dev = zdev->dev; chan->zdev = zdev; + chan->irq = -1; chan->regs = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(chan->regs)) @@ -943,22 +956,26 @@ static int zynqmp_dma_chan_probe(struct zynqmp_dma_device *zdev, INIT_LIST_HEAD(&chan->pending_list); INIT_LIST_HEAD(&chan->done_list); INIT_LIST_HEAD(&chan->free_list); + INIT_LIST_HEAD(&chan->common.device_node); dma_cookie_init(&chan->common); chan->common.device = &zdev->common; - list_add_tail(&chan->common.device_node, &zdev->common.channels); - zynqmp_dma_init(chan); - chan->irq = platform_get_irq(pdev, 0); - if (chan->irq < 0) - return -ENXIO; - err = devm_request_irq(&pdev->dev, chan->irq, zynqmp_dma_irq_handler, 0, + ret = platform_get_irq(pdev, 0); + if (ret < 0) + return ret; + + err = devm_request_irq(&pdev->dev, ret, zynqmp_dma_irq_handler, 0, "zynqmp-dma", chan); if (err) return err; + chan->irq = ret; + chan->desc_size = sizeof(struct zynqmp_dma_desc_ll); chan->idle = true; + list_add_tail(&chan->common.device_node, &zdev->common.channels); + return 0; } @@ -1123,7 +1140,7 @@ static int zynqmp_dma_probe(struct platform_device *pdev) ret = zynqmp_dma_chan_probe(zdev, pdev); if (ret) { dev_err_probe(&pdev->dev, ret, "Probing channel failed\n"); - goto err_disable_pm; + goto free_chan_resources; } p->dst_addr_widths = BIT(zdev->chan->bus_width / 8); @@ -1149,7 +1166,6 @@ static int zynqmp_dma_probe(struct platform_device *pdev) free_chan_resources: zynqmp_dma_chan_remove(zdev->chan); -err_disable_pm: if (!pm_runtime_enabled(zdev->dev)) zynqmp_dma_runtime_suspend(zdev->dev); pm_runtime_disable(zdev->dev); diff --git a/drivers/dpll/zl3073x/dpll.c b/drivers/dpll/zl3073x/dpll.c index f2e137475b40..1cdadb8e46fb 100644 --- a/drivers/dpll/zl3073x/dpll.c +++ b/drivers/dpll/zl3073x/dpll.c @@ -123,6 +123,8 @@ zl3073x_dpll_pin_get_by_ref(struct zl3073x_dpll *zldpll, u8 ref_id) { struct zl3073x_dpll_pin *pin; + lockdep_assert_held(&zldpll->lock); + list_for_each_entry(pin, &zldpll->pins, list) { if (zl3073x_dpll_is_input_pin(pin) && zl3073x_input_pin_ref_get(pin->id) == ref_id) @@ -132,11 +134,42 @@ zl3073x_dpll_pin_get_by_ref(struct zl3073x_dpll *zldpll, u8 ref_id) return NULL; } +/** + * zl3073x_dpll_output_pin_sibling_get - get the other pin of an output pair + * @pin: output pin whose sibling is sought + * + * Output pin ids are allocated in P/N pairs (P even, N odd) that share a + * single HW output. Looks up the other pin of the pair in the pin list + * of this DPLL. A pin is on the list from just before its registration + * until just after its unregistration, so a registered sibling is always + * found, but the returned pin may also be one that is not (yet or any + * longer) registered. + * + * Return: pointer to sibling pin, or NULL if it is not on the pin list + */ +static struct zl3073x_dpll_pin * +zl3073x_dpll_output_pin_sibling_get(struct zl3073x_dpll_pin *pin) +{ + struct zl3073x_dpll_pin *sibling; + + lockdep_assert_held(&pin->dpll->lock); + + list_for_each_entry(sibling, &pin->dpll->pins, list) { + if (!zl3073x_dpll_is_input_pin(sibling) && + sibling->id == (pin->id ^ 1)) + return sibling; + } + + return NULL; +} + static struct zl3073x_dpll_pin * zl3073x_dpll_nco_pin_get(struct zl3073x_dpll *zldpll) { struct zl3073x_dpll_pin *pin; + lockdep_assert_held(&zldpll->lock); + list_for_each_entry(pin, &zldpll->pins, list) { if (zl3073x_dpll_is_nco_pin(pin)) return pin; @@ -878,7 +911,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); - if (zl3073x_out_clock_type_get(out) != 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; @@ -894,7 +927,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; } @@ -909,12 +942,14 @@ zl3073x_dpll_output_pin_esync_set(const struct dpll_pin *dpll_pin, struct zl3073x_dpll *zldpll = dpll_priv; struct zl3073x_dev *zldev = zldpll->dev; struct zl3073x_dpll_pin *pin = pin_priv; + struct zl3073x_dpll_pin *sibling = NULL; const struct zl3073x_synth *synth; struct zl3073x_out out; u32 synth_freq; u8 out_id; + int rc; - guard(mutex)(&zldpll->lock); + mutex_lock(&zldpll->lock); out_id = zl3073x_output_pin_out_get(pin->id); out = *zl3073x_out_state_get(zldev, out_id); @@ -923,38 +958,40 @@ zl3073x_dpll_output_pin_esync_set(const struct dpll_pin *dpll_pin, * for N-division is also used for the esync divider so both cannot * be used. */ - if (zl3073x_out_is_ndiv(&out)) - return -EOPNOTSUPP; - - /* Update clock type in output mode */ - if (freq) - zl3073x_out_clock_type_set(&out, - ZL_OUTPUT_MODE_CLOCK_TYPE_ESYNC); - else - zl3073x_out_clock_type_set(&out, - ZL_OUTPUT_MODE_CLOCK_TYPE_NORMAL); + if (zl3073x_out_is_ndiv(&out)) { + rc = -EOPNOTSUPP; + goto unlock; + } - /* If esync is being disabled just write mailbox and finish */ - if (!freq) - return zl3073x_out_state_set(zldev, out_id, &out); + if (!freq) { + zl3073x_out_esync_disable(&out); + goto commit; + } /* 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; + /* Enable 1PPS eSync for this pin frequency */ + zl3073x_out_esync_enable(&out, synth_freq / out.div); +commit: + /* Commit output configuration */ + rc = zl3073x_out_state_set(zldev, out_id, &out); + if (rc) + goto unlock; - /* 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. + /* The clock type, esync period and esync width are all shared by + * both pins of the output pair, so the sibling pin's esync + * configuration changes too and userspace has to be notified. */ - out.esync_n_width = out.div / 2; + sibling = zl3073x_dpll_output_pin_sibling_get(pin); +unlock: + mutex_unlock(&zldpll->lock); - /* Commit output configuration */ - return zl3073x_out_state_set(zldev, out_id, &out); + if (!rc && sibling) + __dpll_pin_change_ntf(sibling->dpll_pin); + + return rc; } static int @@ -984,12 +1021,15 @@ zl3073x_dpll_output_pin_frequency_set(const struct dpll_pin *dpll_pin, struct zl3073x_dpll *zldpll = dpll_priv; struct zl3073x_dev *zldev = zldpll->dev; struct zl3073x_dpll_pin *pin = pin_priv; + struct zl3073x_dpll_pin *sibling = NULL; const struct zl3073x_synth *synth; u32 new_div, synth_freq; struct zl3073x_out out; + u64 n_period, rem; u8 out_id; + int rc; - guard(mutex)(&zldpll->lock); + mutex_lock(&zldpll->lock); out_id = zl3073x_output_pin_out_get(pin->id); out = *zl3073x_out_state_get(zldev, out_id); @@ -1002,28 +1042,50 @@ zl3073x_dpll_output_pin_frequency_set(const struct dpll_pin *dpll_pin, /* Check signal format */ if (!zl3073x_out_is_ndiv(&out)) { /* For non N-divided signal formats the frequency is computed - * as division of synth frequency and output divisor. + * as division of synth frequency and output divisor, which + * is shared by both pins of the output pair. */ out.div = new_div; /* 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); + rc = zl3073x_out_state_set(zldev, out_id, &out); + if (rc) + goto unlock; + + /* The other pin's frequency changed too - it has to be + * notified about the change. + */ + sibling = zl3073x_dpll_output_pin_sibling_get(pin); + + goto unlock; } if (zl3073x_dpll_is_p_pin(pin)) { - /* We are going to change output frequency for P-pin but - * if the requested frequency is less than current N-pin - * frequency then indicate a failure as we are not able - * to compute N-pin divisor to keep its frequency unchanged. - * - * Update divisor for N-pin to keep N-pin frequency. + /* Keep the N-pin frequency: the new P-pin frequency has to be + * a multiple of it, at least twice as high. */ - out.esync_n_period = (out.esync_n_period * out.div) / new_div; - if (!out.esync_n_period) - return -EINVAL; + n_period = mul_u32_u32(out.esync_n_period, out.div); + n_period = div64_u64_rem(n_period, new_div, &rem); /* Update the output divisor */ out.div = new_div; @@ -1031,23 +1093,47 @@ 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 = out.div; } else { - /* We are going to change frequency of N-pin but if - * the requested freq is greater or equal than freq of P-pin - * in the output pair we cannot compute divisor for the N-pin. - * In this case indicate a failure. - * - * Update divisor for N-pin + /* The N-pin frequency has to divide the P-pin frequency and + * be at most half of it. */ - out.esync_n_period = div64_u64(synth_freq, frequency * out.div); - if (!out.esync_n_period) - return -EINVAL; + n_period = frequency * out.div; + n_period = div64_u64_rem(synth_freq, n_period, &rem); + } + if (n_period < 2) { + NL_SET_ERR_MSG_FMT(extack, + "OUT%uN freq must be at most half of OUT%uP freq", + out_id, out_id); + rc = -EINVAL; + goto unlock; + } + if (n_period > U32_MAX) { + NL_SET_ERR_MSG_FMT(extack, + "OUT%uN freq is too low for OUT%uP freq", + out_id, out_id); + rc = -EINVAL; + goto unlock; } + if (rem != 0) { + NL_SET_ERR_MSG_FMT(extack, + "OUT%uN freq must divide OUT%uP freq", + out_id, out_id); + rc = -EINVAL; + goto unlock; + } + out.esync_n_period = n_period; /* For 50/50 duty cycle the divisor is equal to width */ out.esync_n_width = out.esync_n_period; /* Commit output configuration */ - return zl3073x_out_state_set(zldev, out_id, &out); + rc = zl3073x_out_state_set(zldev, out_id, &out); +unlock: + mutex_unlock(&zldpll->lock); + + if (!rc && sibling) + __dpll_pin_change_ntf(sibling->dpll_pin); + + return rc; } static int @@ -1086,10 +1172,12 @@ zl3073x_dpll_output_pin_phase_adjust_set(const struct dpll_pin *dpll_pin, struct zl3073x_dpll *zldpll = dpll_priv; struct zl3073x_dev *zldev = zldpll->dev; struct zl3073x_dpll_pin *pin = pin_priv; + struct zl3073x_dpll_pin *sibling = NULL; struct zl3073x_out out; u8 out_id; + int rc; - guard(mutex)(&zldpll->lock); + mutex_lock(&zldpll->lock); out_id = zl3073x_output_pin_out_get(pin->id); out = *zl3073x_out_state_get(zldev, out_id); @@ -1098,7 +1186,21 @@ zl3073x_dpll_output_pin_phase_adjust_set(const struct dpll_pin *dpll_pin, out.phase_comp = phase_adjust / pin->phase_gran; /* Update output configuration from mailbox */ - return zl3073x_out_state_set(zldev, out_id, &out); + rc = zl3073x_out_state_set(zldev, out_id, &out); + if (rc) + goto unlock; + + /* The phase compensation register is shared by both pins of the + * output pair, so the sibling pin's phase adjustment changes too. + */ + sibling = zl3073x_dpll_output_pin_sibling_get(pin); +unlock: + mutex_unlock(&zldpll->lock); + + if (!rc && sibling) + __dpll_pin_change_ntf(sibling->dpll_pin); + + return rc; } static int @@ -1722,6 +1824,13 @@ zl3073x_dpll_pin_register(struct zl3073x_dpll_pin *pin, u32 index) else ops = &zl3073x_dpll_output_pin_ops; + /* Add the pin to the list before registering it with the DPLL core so + * that it is findable as a sibling as soon as the core publishes it. + */ + mutex_lock(&zldpll->lock); + list_add(&pin->list, &zldpll->pins); + mutex_unlock(&zldpll->lock); + /* Register the pin */ rc = dpll_pin_register(zldpll->dpll_dev, pin->dpll_pin, ops, pin); if (rc) @@ -1733,6 +1842,9 @@ zl3073x_dpll_pin_register(struct zl3073x_dpll_pin *pin, u32 index) return 0; err_register: + mutex_lock(&zldpll->lock); + list_del(&pin->list); + mutex_unlock(&zldpll->lock); dpll_pin_put(pin->dpll_pin, &pin->tracker); err_pin_get: pin->dpll_pin = NULL; @@ -1767,6 +1879,13 @@ zl3073x_dpll_pin_unregister(struct zl3073x_dpll_pin *pin) /* Unregister the pin */ dpll_pin_unregister(zldpll->dpll_dev, pin->dpll_pin, ops, pin); + /* Remove the pin from the list only after it has been unregistered so + * that a still-registered pin is always findable as a sibling. + */ + mutex_lock(&zldpll->lock); + list_del(&pin->list); + mutex_unlock(&zldpll->lock); + dpll_pin_put(pin->dpll_pin, &pin->tracker); pin->dpll_pin = NULL; @@ -1786,9 +1905,11 @@ zl3073x_dpll_pins_unregister(struct zl3073x_dpll *zldpll) { struct zl3073x_dpll_pin *pin, *next; + /* Unregister each pin before removing it from the list so that a + * still-registered pin is always findable as a sibling. + */ list_for_each_entry_safe(pin, next, &zldpll->pins, list) { zl3073x_dpll_pin_unregister(pin); - list_del(&pin->list); zl3073x_dpll_pin_free(pin); } } @@ -1901,16 +2022,24 @@ zl3073x_dpll_nco_pin_register(struct zl3073x_dpll *zldpll) goto err_pin_get; } + /* Add the pin to the list before registering it with the DPLL core so + * that a registered pin is always on the list. + */ + mutex_lock(&zldpll->lock); + list_add(&pin->list, &zldpll->pins); + mutex_unlock(&zldpll->lock); + rc = dpll_pin_register(zldpll->dpll_dev, pin->dpll_pin, &zl3073x_dpll_nco_pin_ops, pin); if (rc) goto err_register; - list_add(&pin->list, &zldpll->pins); - return 0; err_register: + mutex_lock(&zldpll->lock); + list_del(&pin->list); + mutex_unlock(&zldpll->lock); dpll_pin_put(pin->dpll_pin, &pin->tracker); err_pin_get: pin->dpll_pin = NULL; @@ -1962,8 +2091,6 @@ zl3073x_dpll_pins_register(struct zl3073x_dpll *zldpll) zl3073x_dpll_pin_free(pin); goto error; } - - list_add(&pin->list, &zldpll->pins); } /* Register NCO virtual input pin */ diff --git a/drivers/dpll/zl3073x/out.h b/drivers/dpll/zl3073x/out.h index 660889c57bff..d2b8b4eb5a76 100644 --- a/drivers/dpll/zl3073x/out.h +++ b/drivers/dpll/zl3073x/out.h @@ -134,4 +134,40 @@ 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 = zl3073x_out_clock_type_get(out); + + 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 */ + zl3073x_out_clock_type_set(out, 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. + */ + zl3073x_out_clock_type_set(out, ZL_OUTPUT_MODE_CLOCK_TYPE_NORMAL); +} + #endif /* _ZL3073X_OUT_H */ diff --git a/drivers/dpll/zl3073x/prop.c b/drivers/dpll/zl3073x/prop.c index ac9d41d0f978..4e006ed5950a 100644 --- a/drivers/dpll/zl3073x/prop.c +++ b/drivers/dpll/zl3073x/prop.c @@ -22,7 +22,8 @@ * The function checks the given frequency is valid for the device. For input * pins it checks that the frequency can be factorized using supported base * frequencies. For output pins it checks that the frequency divides connected - * synth frequency without remainder. + * synth frequency without remainder and that the resulting divisor is not + * below the minimum the driver supports. * * Return: true if the frequency is valid, false if not. */ @@ -30,7 +31,7 @@ static bool zl3073x_pin_check_freq(struct zl3073x_dev *zldev, enum dpll_pin_direction dir, u8 id, u64 freq) { - if (freq > U32_MAX) + if (!freq || freq > U32_MAX) goto err_inv_freq; if (dir == DPLL_PIN_DIRECTION_INPUT) { @@ -41,18 +42,38 @@ zl3073x_pin_check_freq(struct zl3073x_dev *zldev, enum dpll_pin_direction dir, if (rc) goto err_inv_freq; } else { - u32 synth_freq; - u8 out, synth; + u32 synth_freq, div, min_div, rem; + const struct zl3073x_out *out; + u8 out_id, synth; /* Get output pin synthesizer */ - out = zl3073x_output_pin_out_get(id); - synth = zl3073x_dev_out_synth_get(zldev, out); + out_id = zl3073x_output_pin_out_get(id); + synth = zl3073x_dev_out_synth_get(zldev, out_id); /* Get synth frequency */ synth_freq = zl3073x_dev_synth_freq_get(zldev, synth); /* Check the frequency divides synth frequency */ - if (synth_freq % (u32)freq) + div = div_u64_rem(synth_freq, freq, &rem); + if (rem) + goto err_inv_freq; + + /* The driver requires an output divisor of at least 2 - + * below that the hardware bypasses the divider and ignores + * the pulse width and eSync registers the driver programs. + * For the N-pin of an N-divided output the effective divisor + * also includes the N divider (>= 2), so the minimum is 4. + * For N-divided outputs this is only a necessary condition - + * whether the frequency can be set also depends on the output + * divisor shared by both pins, which is checked when the + * frequency is set. + */ + out = zl3073x_out_state_get(zldev, out_id); + if (zl3073x_out_is_ndiv(out) && zl3073x_is_n_pin(id)) + min_div = 4; + else + min_div = 2; + if (div < min_div) goto err_inv_freq; } @@ -295,13 +316,20 @@ struct zl3073x_pin_props *zl3073x_pin_props_get(struct zl3073x_dev *zldev, goto err_alloc_ranges; } - /* Start with current frequency at index 0 */ - ranges[0] = (struct dpll_pin_frequency)DPLL_PIN_FREQUENCY(curr_freq); + /* Start with current frequency at index 0. A sub-Hz frequency is + * read back as 0 Hz and cannot be set, so it is not offered. + */ + j = 0; + if (curr_freq) { + struct dpll_pin_frequency freq = DPLL_PIN_FREQUENCY(curr_freq); + + ranges[j++] = freq; + } /* Add frequencies from firmware node, skipping current frequency * and filtering out frequencies not representable by device */ - for (i = 0, j = 1; i < num_freqs; i++) { + for (i = 0; i < num_freqs; i++) { struct dpll_pin_frequency freq = DPLL_PIN_FREQUENCY(freqs[i]); if (freqs[i] == curr_freq) @@ -312,6 +340,14 @@ struct zl3073x_pin_props *zl3073x_pin_props_get(struct zl3073x_dev *zldev, } } + /* The DPLL core rejects a non-NULL list without entries, so do + * not publish the array at all when nothing is settable. + */ + if (!j) { + kfree(ranges); + ranges = NULL; + } + /* Save number of freq ranges and pointer to them into pin properties */ props->dpll_props.freq_supported = ranges; props->dpll_props.freq_supported_num = j; diff --git a/drivers/edac/i10nm_base.c b/drivers/edac/i10nm_base.c index 12e1949fcf44..87e541c3bf4b 100644 --- a/drivers/edac/i10nm_base.c +++ b/drivers/edac/i10nm_base.c @@ -479,6 +479,7 @@ static struct pci_dev *get_gnr_mdev(struct skx_dev *d, int logical_idx, int *phy if (mdev) { if (logical == logical_idx) { *physical_idx = i; + skx_set_mc_mapping(d, i, logical_idx); return mdev; } diff --git a/drivers/firmware/arm_scmi/common.h b/drivers/firmware/arm_scmi/common.h index fe8c22cfb9f7..a5492dd90b41 100644 --- a/drivers/firmware/arm_scmi/common.h +++ b/drivers/firmware/arm_scmi/common.h @@ -284,6 +284,28 @@ static inline bool is_polling_enabled(struct scmi_chan_info *cinfo, is_transport_polling_capable(desc); } +/** + * scmi_xfer_async_response_arm - Arm the delayed response completion + * + * @xfer: A reference to the xfer to arm + * @async_done: The completion to signal upon reception of a delayed response, + * or NULL to disarm @xfer. + */ +static inline void scmi_xfer_async_response_arm(struct scmi_xfer *xfer, + struct completion *async_done) +{ + unsigned long flags; + + spin_lock_irqsave(&xfer->lock, flags); + xfer->async_done = async_done; + spin_unlock_irqrestore(&xfer->lock, flags); +} + +static inline void scmi_xfer_async_response_disarm(struct scmi_xfer *xfer) +{ + scmi_xfer_async_response_arm(xfer, NULL); +} + void scmi_xfer_raw_put(const struct scmi_handle *handle, struct scmi_xfer *xfer); struct scmi_xfer *scmi_xfer_raw_get(const struct scmi_handle *handle); diff --git a/drivers/firmware/arm_scmi/driver.c b/drivers/firmware/arm_scmi/driver.c index a666ad39acdf..1291dc68b495 100644 --- a/drivers/firmware/arm_scmi/driver.c +++ b/drivers/firmware/arm_scmi/driver.c @@ -718,6 +718,7 @@ static struct scmi_xfer *scmi_xfer_get(const struct scmi_handle *handle, refcount_set(&xfer->users, 1); atomic_set(&xfer->busy, SCMI_XFER_FREE); + xfer->async_done = NULL; spin_unlock_irqrestore(&minfo->xfer_lock, flags); return xfer; @@ -1064,6 +1065,29 @@ static inline void scmi_xfer_command_release(struct scmi_info *info, __scmi_xfer_put(&info->tx_minfo, xfer); } +/** + * scmi_xfer_async_response_complete - Signal a received delayed response + * + * @xfer: A reference to the xfer whose delayed response was received + * + * Return: True if a completion was still armed on @xfer and has been + * signalled, false if a waiter has already disarmed it due to + * timeout or other error. + */ +static bool scmi_xfer_async_response_complete(struct scmi_xfer *xfer) +{ + unsigned long flags; + struct completion *async_done; + + spin_lock_irqsave(&xfer->lock, flags); + async_done = xfer->async_done; + if (async_done) + complete(async_done); + spin_unlock_irqrestore(&xfer->lock, flags); + + return !!async_done; +} + static inline void scmi_clear_channel(struct scmi_info *info, struct scmi_chan_info *cinfo) { @@ -1167,8 +1191,12 @@ static void scmi_handle_response(struct scmi_chan_info *cinfo, if (xfer->hdr.type == MSG_TYPE_DELAYED_RESP) { scmi_clear_channel(info, cinfo); - complete(xfer->async_done); - scmi_inc_count(info->dbg, DELAYED_RESPONSE_OK); + if (scmi_xfer_async_response_complete(xfer)) + scmi_inc_count(info->dbg, DELAYED_RESPONSE_OK); + else + dev_err(cinfo->dev, + "Delayed Response for %d (protocol 0x%X msg 0x%X) received after waiter was disarmed, dropping\n", + xfer->hdr.seq, xfer->hdr.protocol_id, xfer->hdr.id); } else { complete(&xfer->done); scmi_inc_count(info->dbg, RESPONSE_OK); @@ -1510,7 +1538,7 @@ static int do_xfer_with_response(const struct scmi_protocol_handle *ph, int ret, timeout = msecs_to_jiffies(SCMI_MAX_RESPONSE_TIMEOUT); DECLARE_COMPLETION_ONSTACK(async_response); - xfer->async_done = &async_response; + scmi_xfer_async_response_arm(xfer, &async_response); /* * Delayed responses should not be polled, so an async command should @@ -1522,7 +1550,7 @@ static int do_xfer_with_response(const struct scmi_protocol_handle *ph, ret = do_xfer(ph, xfer); if (!ret) { - if (!wait_for_completion_timeout(xfer->async_done, timeout)) { + if (!wait_for_completion_timeout(&async_response, timeout)) { dev_err(ph->dev, "timed out in delayed resp(caller: %pS)\n", (void *)_RET_IP_); @@ -1532,7 +1560,7 @@ static int do_xfer_with_response(const struct scmi_protocol_handle *ph, } } - xfer->async_done = NULL; + scmi_xfer_async_response_disarm(xfer); return ret; } diff --git a/drivers/firmware/arm_scmi/protocols.h b/drivers/firmware/arm_scmi/protocols.h index 15ad5162e37a..8583159059e6 100644 --- a/drivers/firmware/arm_scmi/protocols.h +++ b/drivers/firmware/arm_scmi/protocols.h @@ -100,7 +100,10 @@ struct scmi_msg_hdr { * message. If request-ACK protocol is used, we can reuse the same * buffer for the rx path as we use for the tx path. * @done: command message transmit completion event - * @async_done: pointer to delayed response message received event completion + * @async_done: pointer to delayed response message received event completion, + * or NULL when no delayed response is expected. Protected by + * @lock, since the completion is owned by the waiter and can + * vanish once the wait times out. * @pending: True for xfers added to @pending_xfers hashtable * @node: An hlist_node reference used to store this xfer, alternatively, on * the free list @free_xfers or in the @pending_xfers hashtable @@ -121,7 +124,7 @@ struct scmi_msg_hdr { * - SCMI_XFER_SENT_OK -> SCMI_XFER_DRESP_OK * (Missing synchronous response is assumed OK and ignored) * @flags: Optional flags associated to this xfer. - * @lock: A spinlock to protect state and busy fields. + * @lock: A spinlock to protect state, busy and async_done fields. * @priv: A pointer for transport private usage. */ struct scmi_xfer { @@ -147,7 +150,7 @@ struct scmi_xfer { #define SCMI_XFER_IS_CHAN_SET(x) \ ((x)->flags & SCMI_XFER_FLAG_CHAN_SET) int flags; - /* A lock to protect state and busy fields */ + /* A lock to protect state, busy and async_done fields */ spinlock_t lock; void *priv; }; diff --git a/drivers/firmware/arm_scmi/raw_mode.c b/drivers/firmware/arm_scmi/raw_mode.c index 1f6e51670208..f01bf2f6ce1d 100644 --- a/drivers/firmware/arm_scmi/raw_mode.c +++ b/drivers/firmware/arm_scmi/raw_mode.c @@ -198,6 +198,8 @@ struct scmi_raw_mode_info { * @async_response: A completion to be, optionally, used for async waits: it * will be setup by @scmi_do_xfer_raw_start, if needed, to be * pointed at by xfer->async_done. + * @async: True if @async_response was armed on @xfer, i.e. if a delayed + * response has to be waited for. * @node: A list node. */ struct scmi_xfer_raw_waiter { @@ -205,6 +207,7 @@ struct scmi_xfer_raw_waiter { struct scmi_chan_info *cinfo; struct scmi_xfer *xfer; struct completion async_response; + bool async; struct list_head node; }; @@ -346,9 +349,10 @@ scmi_xfer_raw_waiter_get(struct scmi_raw_mode_info *raw, struct scmi_xfer *xfer, if (async) { reinit_completion(&rw->async_response); - xfer->async_done = &rw->async_response; + scmi_xfer_async_response_arm(xfer, &rw->async_response); } + rw->async = async; rw->cinfo = cinfo; rw->xfer = xfer; } @@ -361,8 +365,16 @@ static void scmi_xfer_raw_waiter_put(struct scmi_raw_mode_info *raw, struct scmi_xfer_raw_waiter *rw) { if (rw->xfer) { - rw->xfer->async_done = NULL; + /* + * Disarm the delayed response before this waiter, and its + * embedded completion, can be picked up again for a new + * transaction: a delayed response received late, after the + * related wait timed out, must not signal a completion which + * has been in the meantime re-armed on a different xfer. + */ + scmi_xfer_async_response_disarm(rw->xfer); rw->xfer = NULL; + rw->async = false; } mutex_lock(&raw->free_mtx); @@ -479,18 +491,23 @@ static void scmi_xfer_raw_worker(struct work_struct *work) ret, scmi_inflight_count(raw->handle)); /* Wait also for an async delayed response if needed */ - if (!ret && xfer->async_done) { + if (!ret && rw->async) { unsigned long tmo = msecs_to_jiffies(SCMI_MAX_RESPONSE_TIMEOUT); - if (!wait_for_completion_timeout(xfer->async_done, tmo)) + if (!wait_for_completion_timeout(&rw->async_response, tmo)) dev_err(dev, "timed out in RAW delayed resp - HDR:%08X\n", pack_scmi_header(&xfer->hdr)); } - /* Release waiter and xfer */ - scmi_xfer_raw_put(raw->handle, xfer); + /* + * Release the waiter first: this disarms the delayed response + * while we still hold a reference on the xfer, so that the xfer + * cannot be recycled by a new transaction while it still points + * at this waiter's completion. + */ scmi_xfer_raw_waiter_put(raw, rw); + scmi_xfer_raw_put(raw->handle, xfer); } while (1); } @@ -694,6 +711,7 @@ static int scmi_raw_message_send(struct scmi_raw_mode_info *raw, } else { dev_err(raw->handle->dev, "Failed to send RAW message - Polling NOT supported\n"); + scmi_xfer_raw_put(raw->handle, xfer); return -EINVAL; } } diff --git a/drivers/firmware/cirrus/cs_dsp.c b/drivers/firmware/cirrus/cs_dsp.c index bb93b24c659d..838fece8dc01 100644 --- a/drivers/firmware/cirrus/cs_dsp.c +++ b/drivers/firmware/cirrus/cs_dsp.c @@ -2960,6 +2960,8 @@ int cs_dsp_run(struct cs_dsp *dsp) return 0; err: + dsp->running = false; + if (dsp->ops->stop_core) dsp->ops->stop_core(dsp); if (dsp->ops->disable_core) diff --git a/drivers/firmware/efi/cper.c b/drivers/firmware/efi/cper.c index 06b4fdb59917..13b3e72c3b62 100644 --- a/drivers/firmware/efi/cper.c +++ b/drivers/firmware/efi/cper.c @@ -389,10 +389,28 @@ void cper_mem_err_pack(const struct cper_sec_mem_err *mem, cmem->requestor_id = mem->requestor_id; cmem->responder_id = mem->responder_id; cmem->target_id = mem->target_id; - cmem->extended = mem->extended; - cmem->rank = mem->rank; - cmem->mem_array_handle = mem->mem_array_handle; - cmem->mem_dev_handle = mem->mem_dev_handle; + + /* + * These four sit past the end of the UEFI 2.1/2.2 layout, which older + * firmware still emits, so reading them unconditionally runs off a + * short record. Every consumer of the compact record gates them on the + * same validation bits, so leave them zero when firmware does not + * claim them. + */ + cmem->extended = 0; + cmem->rank = 0; + cmem->mem_array_handle = 0; + cmem->mem_dev_handle = 0; + + if (mem->validation_bits & + (CPER_MEM_VALID_ROW_EXT | CPER_MEM_VALID_CHIP_ID)) + cmem->extended = mem->extended; + if (mem->validation_bits & CPER_MEM_VALID_RANK_NUMBER) + cmem->rank = mem->rank; + if (mem->validation_bits & CPER_MEM_VALID_CARD_HANDLE) + cmem->mem_array_handle = mem->mem_array_handle; + if (mem->validation_bits & CPER_MEM_VALID_MODULE_HANDLE) + cmem->mem_dev_handle = mem->mem_dev_handle; } EXPORT_SYMBOL_GPL(cper_mem_err_pack); @@ -745,6 +763,17 @@ int cper_estatus_check_header(const struct acpi_hest_generic_status *estatus) estatus->raw_data_offset < sizeof(*estatus) + estatus->data_length) return -EINVAL; + /* + * cper_estatus_len() sums these into a u32, and a wrapped sum reads + * back smaller than the record. Reject a length that cannot be + * expressed so no caller is handed the short value. + */ + if ((u64)sizeof(*estatus) + estatus->data_length > U32_MAX) + return -EINVAL; + if (estatus->raw_data_length && + (u64)estatus->raw_data_offset + estatus->raw_data_length > U32_MAX) + return -EINVAL; + return 0; } EXPORT_SYMBOL_GPL(cper_estatus_check_header); @@ -752,7 +781,7 @@ EXPORT_SYMBOL_GPL(cper_estatus_check_header); int cper_estatus_check(const struct acpi_hest_generic_status *estatus) { struct acpi_hest_generic_data *gdata; - unsigned int data_len, record_size; + unsigned int data_len; int rc; rc = cper_estatus_check_header(estatus); @@ -762,10 +791,18 @@ int cper_estatus_check(const struct acpi_hest_generic_status *estatus) data_len = estatus->data_length; apei_estatus_for_each_section(estatus, gdata) { - if (acpi_hest_get_size(gdata) > data_len) + int record_size; + + /* + * The helpers sum these as a signed int, so a + * huge error_data_length wraps small rather than large and the + * walk then advances by that wrapped value. Reject a size an + * int cannot carry. + */ + if (check_add_overflow(acpi_hest_get_size(gdata), + gdata->error_data_length, &record_size)) return -EINVAL; - record_size = acpi_hest_get_record_size(gdata); if (record_size > data_len) return -EINVAL; diff --git a/drivers/firmware/efi/libstub/efi-stub-entry.c b/drivers/firmware/efi/libstub/efi-stub-entry.c index aa85e910fe59..efa3ab8ad1c6 100644 --- a/drivers/firmware/efi/libstub/efi-stub-entry.c +++ b/drivers/firmware/efi/libstub/efi-stub-entry.c @@ -35,13 +35,12 @@ struct sysfb_display_info *alloc_primary_display(void) efi_status_t __efiapi efi_pe_entry(efi_handle_t handle, efi_system_table_t *systab) { + static efi_guid_t loaded_image_proto = LOADED_IMAGE_PROTOCOL_GUID; efi_loaded_image_t *image; efi_status_t status; unsigned long image_addr; unsigned long image_size = 0; /* addr/point and size pairs for memory management*/ - char *cmdline_ptr = NULL; - efi_guid_t loaded_image_proto = LOADED_IMAGE_PROTOCOL_GUID; unsigned long reserve_addr = 0; unsigned long reserve_size = 0; @@ -63,6 +62,7 @@ efi_status_t __efiapi efi_pe_entry(efi_handle_t handle, return status; } + char *cmdline_ptr __free(efi_pool) = NULL; status = efi_handle_cmdline(image, &cmdline_ptr); if (status != EFI_SUCCESS) return status; diff --git a/drivers/firmware/efi/libstub/efi-stub-helper.c b/drivers/firmware/efi/libstub/efi-stub-helper.c index f27f2e1f0019..48f93f7758e9 100644 --- a/drivers/firmware/efi/libstub/efi-stub-helper.c +++ b/drivers/firmware/efi/libstub/efi-stub-helper.c @@ -248,6 +248,7 @@ static efi_status_t efi_measure_tagged_event(unsigned long load_addr, unsigned long load_size, enum efistub_event_type event) { + static efi_guid_t tcg2_guid = EFI_TCG2_PROTOCOL_GUID; union { efi_status_t (__efiapi *hash_log_extend_event)(void *, u64, efi_physical_addr_t, @@ -257,7 +258,6 @@ static efi_status_t efi_measure_tagged_event(unsigned long load_addr, struct efistub_measured_event *evt __free(efi_pool) = NULL; int size = struct_size(evt, tagged_event.tagged_event_data, events[event].event_data_len); - efi_guid_t tcg2_guid = EFI_TCG2_PROTOCOL_GUID; efi_tcg2_protocol_t *tcg2 = NULL; union efistub_event ev; efi_status_t status; @@ -276,7 +276,7 @@ static efi_status_t efi_measure_tagged_event(unsigned long load_addr, method.hash_log_extend_event = (void *)efi_table_attr(tcg2, hash_log_extend_event); } else { - efi_guid_t cc_guid = EFI_CC_MEASUREMENT_PROTOCOL_GUID; + static efi_guid_t cc_guid = EFI_CC_MEASUREMENT_PROTOCOL_GUID; efi_cc_protocol_t *cc = NULL; efi_bs_call(locate_protocol, &cc_guid, NULL, (void **)&cc); @@ -552,7 +552,7 @@ static efi_status_t efi_load_initrd_dev_path(struct linux_efi_initrd *initrd, unsigned long max) { - efi_guid_t lf2_proto_guid = EFI_LOAD_FILE2_PROTOCOL_GUID; + static efi_guid_t lf2_proto_guid = EFI_LOAD_FILE2_PROTOCOL_GUID; efi_device_path_protocol_t *dp; efi_load_file2_protocol_t *lf2; efi_handle_t handle; @@ -614,7 +614,7 @@ efi_status_t efi_load_initrd(efi_loaded_image_t *image, unsigned long hard_limit, const struct linux_efi_initrd **out) { - efi_guid_t tbl_guid = LINUX_EFI_INITRD_MEDIA_GUID; + static efi_guid_t tbl_guid = LINUX_EFI_INITRD_MEDIA_GUID; efi_status_t status = EFI_SUCCESS; struct linux_efi_initrd initrd, *tbl; @@ -725,7 +725,7 @@ efi_status_t efi_wait_for_key(unsigned long usec, efi_input_key_t *key) void efi_remap_image(unsigned long image_base, unsigned alloc_size, unsigned long code_size) { - efi_guid_t guid = EFI_MEMORY_ATTRIBUTE_PROTOCOL_GUID; + static efi_guid_t guid = EFI_MEMORY_ATTRIBUTE_PROTOCOL_GUID; efi_memory_attribute_protocol_t *memattr; efi_status_t status; u64 attr; diff --git a/drivers/firmware/efi/libstub/efi-stub.c b/drivers/firmware/efi/libstub/efi-stub.c index a4cb39656b03..f3f6f37921ef 100644 --- a/drivers/firmware/efi/libstub/efi-stub.c +++ b/drivers/firmware/efi/libstub/efi-stub.c @@ -79,8 +79,8 @@ static struct sysfb_display_info *setup_primary_display(void) static void install_memreserve_table(void) { + static efi_guid_t memreserve_table_guid = LINUX_EFI_MEMRESERVE_TABLE_GUID; struct linux_efi_memreserve *rsv; - efi_guid_t memreserve_table_guid = LINUX_EFI_MEMRESERVE_TABLE_GUID; efi_status_t status; /* diff --git a/drivers/firmware/efi/libstub/efistub.h b/drivers/firmware/efi/libstub/efistub.h index fd91fc15ec81..049263a541ae 100644 --- a/drivers/firmware/efi/libstub/efistub.h +++ b/drivers/firmware/efi/libstub/efistub.h @@ -224,8 +224,8 @@ typedef void (__efiapi *efi_event_notify_t)(efi_event_t, void *); * efi_set_event_at() - add event to events array * * @events: array of UEFI events - * @ids: index where to put the event in the array - * @event: event to add to the aray + * @idx: index where to put the event in the array + * @event: event to add to the array * * boottime->wait_for_event() takes an array of events as input. * Provide a helper to set it up correctly for mixed mode. diff --git a/drivers/firmware/efi/libstub/fdt.c b/drivers/firmware/efi/libstub/fdt.c index 23b3543d3041..f01450b49975 100644 --- a/drivers/firmware/efi/libstub/fdt.c +++ b/drivers/firmware/efi/libstub/fdt.c @@ -229,6 +229,7 @@ efi_status_t allocate_new_fdt_and_exit_boot(void *handle, u32 desc_ver; efi_status_t status; struct exit_boot_struct priv; + unsigned long fdt_size_allocated = 0; unsigned long fdt_addr = 0; unsigned long fdt_size = 0; @@ -251,12 +252,13 @@ efi_status_t allocate_new_fdt_and_exit_boot(void *handle, if (strstr(cmdline_ptr, "dtb=")) efi_err("Ignoring DTB from command line.\n"); } else { - status = efi_load_dtb(image, &fdt_addr, &fdt_size); + status = efi_load_dtb(image, &fdt_addr, &fdt_size_allocated); if (status != EFI_SUCCESS && status != EFI_NOT_READY) { efi_err("Failed to load device tree!\n"); goto fail; } + fdt_size = fdt_size_allocated; } if (fdt_addr) { @@ -334,7 +336,7 @@ efi_status_t allocate_new_fdt_and_exit_boot(void *handle, efi_free(MAX_FDT_SIZE, *new_fdt_addr); fail: - efi_free(fdt_size, fdt_addr); + efi_free(fdt_size_allocated, fdt_addr); if (!efi_novamap) efi_bs_call(free_pool, priv.runtime_map); diff --git a/drivers/firmware/efi/libstub/file.c b/drivers/firmware/efi/libstub/file.c index bd626d55dcbc..0dff9e08d49e 100644 --- a/drivers/firmware/efi/libstub/file.c +++ b/drivers/firmware/efi/libstub/file.c @@ -39,7 +39,7 @@ static efi_status_t efi_open_file(efi_file_protocol_t *volume, efi_file_protocol_t **handle, unsigned long *file_size) { - efi_guid_t info_guid = EFI_FILE_INFO_ID; + static efi_guid_t info_guid = EFI_FILE_INFO_ID; efi_file_protocol_t *fh; unsigned long info_sz; efi_status_t status; @@ -74,7 +74,7 @@ static efi_status_t efi_open_file(efi_file_protocol_t *volume, static efi_status_t efi_open_volume(efi_loaded_image_t *image, efi_file_protocol_t **fh) { - efi_guid_t fs_proto = EFI_FILE_SYSTEM_GUID; + static efi_guid_t fs_proto = EFI_FILE_SYSTEM_GUID; efi_simple_file_system_protocol_t *io; efi_status_t status; @@ -128,9 +128,9 @@ static int find_file_option(const efi_char16_t *cmdline, int cmdline_len, static efi_status_t efi_open_device_path(efi_file_protocol_t **volume, struct finfo *fi) { - efi_guid_t text_to_dp_guid = EFI_DEVICE_PATH_FROM_TEXT_PROTOCOL_GUID; + static efi_guid_t text_to_dp_guid = EFI_DEVICE_PATH_FROM_TEXT_PROTOCOL_GUID; + static efi_guid_t fs_proto = EFI_FILE_SYSTEM_GUID; static efi_device_path_from_text_protocol_t *text_to_dp = NULL; - efi_guid_t fs_proto = EFI_FILE_SYSTEM_GUID; efi_device_path_protocol_t *initrd_dp; efi_simple_file_system_protocol_t *io; struct efi_file_path_dev_path *fpath; diff --git a/drivers/firmware/efi/libstub/kaslr.c b/drivers/firmware/efi/libstub/kaslr.c index 4bc963e999eb..f5074656457a 100644 --- a/drivers/firmware/efi/libstub/kaslr.c +++ b/drivers/firmware/efi/libstub/kaslr.c @@ -18,7 +18,7 @@ */ u32 efi_kaslr_get_phys_seed(efi_handle_t image_handle) { - efi_guid_t li_fixed_proto = LINUX_EFI_LOADED_IMAGE_FIXED_GUID; + static efi_guid_t li_fixed_proto = LINUX_EFI_LOADED_IMAGE_FIXED_GUID; void *p; if (!IS_ENABLED(CONFIG_RANDOMIZE_BASE)) diff --git a/drivers/firmware/efi/libstub/mem.c b/drivers/firmware/efi/libstub/mem.c index 59f3f83de50c..fec561e3a792 100644 --- a/drivers/firmware/efi/libstub/mem.c +++ b/drivers/firmware/efi/libstub/mem.c @@ -20,10 +20,10 @@ efi_status_t efi_get_memory_map(struct efi_boot_memmap **map, bool install_cfg_tbl) { + static efi_guid_t tbl_guid = LINUX_EFI_BOOT_MEMMAP_GUID; struct efi_boot_memmap tmp, *m __free(efi_pool) = NULL; int memtype = install_cfg_tbl ? EFI_ACPI_RECLAIM_MEMORY : EFI_LOADER_DATA; - efi_guid_t tbl_guid = LINUX_EFI_BOOT_MEMMAP_GUID; efi_status_t status; unsigned long size; diff --git a/drivers/firmware/efi/libstub/pci.c b/drivers/firmware/efi/libstub/pci.c index 1dccf77958d3..5daa7a0a0e87 100644 --- a/drivers/firmware/efi/libstub/pci.c +++ b/drivers/firmware/efi/libstub/pci.c @@ -15,7 +15,7 @@ void efi_pci_disable_bridge_busmaster(void) { - efi_guid_t pci_proto = EFI_PCI_IO_PROTOCOL_GUID; + static efi_guid_t pci_proto = EFI_PCI_IO_PROTOCOL_GUID; efi_handle_t *pci_handle __free(efi_pool) = NULL; unsigned long pci_handle_num; efi_handle_t handle; diff --git a/drivers/firmware/efi/libstub/random.c b/drivers/firmware/efi/libstub/random.c index 7109b8a2dcba..3ca230fa7aa3 100644 --- a/drivers/firmware/efi/libstub/random.c +++ b/drivers/firmware/efi/libstub/random.c @@ -38,7 +38,7 @@ union efi_rng_protocol { */ efi_status_t efi_get_random_bytes(unsigned long size, u8 *out) { - efi_guid_t rng_proto = EFI_RNG_PROTOCOL_GUID; + static efi_guid_t rng_proto = EFI_RNG_PROTOCOL_GUID; efi_status_t status; efi_rng_protocol_t *rng = NULL; @@ -64,9 +64,9 @@ efi_status_t efi_get_random_bytes(unsigned long size, u8 *out) */ efi_status_t efi_random_get_seed(void) { - efi_guid_t rng_proto = EFI_RNG_PROTOCOL_GUID; - efi_guid_t rng_algo_raw = EFI_RNG_ALGORITHM_RAW; - efi_guid_t rng_table_guid = LINUX_EFI_RANDOM_SEED_TABLE_GUID; + static efi_guid_t rng_proto = EFI_RNG_PROTOCOL_GUID; + static efi_guid_t rng_algo_raw = EFI_RNG_ALGORITHM_RAW; + static efi_guid_t rng_table_guid = LINUX_EFI_RANDOM_SEED_TABLE_GUID; struct linux_efi_random_seed *prev_seed, *seed = NULL; int prev_seed_size = 0, seed_size = EFI_RANDOM_SEED_SIZE; unsigned long nv_seed_size = 0, offset = 0; diff --git a/drivers/firmware/efi/libstub/riscv-stub.c b/drivers/firmware/efi/libstub/riscv-stub.c index e7d9204baee3..725b634c5179 100644 --- a/drivers/firmware/efi/libstub/riscv-stub.c +++ b/drivers/firmware/efi/libstub/riscv-stub.c @@ -37,17 +37,14 @@ efi_status_t handle_kernel_image(unsigned long *image_addr, kernel_codesize = __init_text_end - _start; kernel_memsize = kernel_size + (_end - _edata); *image_addr = (unsigned long)_start; - *image_size = kernel_memsize; - *reserve_size = *image_size; + *reserve_size = kernel_memsize; status = efi_kaslr_relocate_kernel(image_addr, reserve_addr, reserve_size, kernel_size, kernel_codesize, kernel_memsize, efi_kaslr_get_phys_seed(image_handle)); - if (status != EFI_SUCCESS) { + if (status != EFI_SUCCESS) efi_err("Failed to relocate kernel\n"); - *image_size = 0; - } return status; } diff --git a/drivers/firmware/efi/libstub/riscv.c b/drivers/firmware/efi/libstub/riscv.c index f66f33ceb99e..49db47c05bfe 100644 --- a/drivers/firmware/efi/libstub/riscv.c +++ b/drivers/firmware/efi/libstub/riscv.c @@ -45,7 +45,7 @@ static int get_boot_hartid_from_fdt(void) static efi_status_t get_boot_hartid_from_efi(void) { - efi_guid_t boot_protocol_guid = RISCV_EFI_BOOT_PROTOCOL_GUID; + static efi_guid_t boot_protocol_guid = RISCV_EFI_BOOT_PROTOCOL_GUID; struct riscv_efi_boot_protocol *boot_protocol; efi_status_t status; diff --git a/drivers/firmware/efi/libstub/tpm.c b/drivers/firmware/efi/libstub/tpm.c index a5c6c4f163fc..73f001114732 100644 --- a/drivers/firmware/efi/libstub/tpm.c +++ b/drivers/firmware/efi/libstub/tpm.c @@ -28,8 +28,8 @@ static const efi_char16_t efi_MemoryOverWriteRequest_name[] = */ void efi_enable_reset_attack_mitigation(void) { + static efi_guid_t var_guid = MEMORY_ONLY_RESET_CONTROL_GUID; u8 val = 1; - efi_guid_t var_guid = MEMORY_ONLY_RESET_CONTROL_GUID; efi_status_t status; unsigned long datasize = 0; @@ -52,7 +52,7 @@ static void efi_retrieve_tcg2_eventlog(int version, efi_physical_addr_t log_loca efi_bool_t truncated, struct efi_tcg2_final_events_table *final_events_table) { - efi_guid_t linux_eventlog_guid = LINUX_EFI_TPM_EVENT_LOG_GUID; + static efi_guid_t linux_eventlog_guid = LINUX_EFI_TPM_EVENT_LOG_GUID; efi_status_t status; struct linux_efi_tpm_eventlog *log_tbl = NULL; unsigned long first_entry_addr, last_entry_addr; @@ -150,9 +150,9 @@ static void efi_retrieve_tcg2_eventlog(int version, efi_physical_addr_t log_loca void efi_retrieve_eventlog(void) { + static efi_guid_t tpm2_guid = EFI_TCG2_PROTOCOL_GUID; struct efi_tcg2_final_events_table *final_events_table = NULL; efi_physical_addr_t log_location = 0, log_last_entry = 0; - efi_guid_t tpm2_guid = EFI_TCG2_PROTOCOL_GUID; int version = EFI_TCG2_EVENT_LOG_FORMAT_TCG_2; efi_tcg2_protocol_t *tpm2 = NULL; efi_bool_t truncated; @@ -173,7 +173,7 @@ void efi_retrieve_eventlog(void) get_efi_config_table(EFI_TCG2_FINAL_EVENTS_TABLE_GUID); } } else { - efi_guid_t cc_guid = EFI_CC_MEASUREMENT_PROTOCOL_GUID; + static efi_guid_t cc_guid = EFI_CC_MEASUREMENT_PROTOCOL_GUID; efi_cc_protocol_t *cc = NULL; status = efi_bs_call(locate_protocol, &cc_guid, NULL, (void **)&cc); diff --git a/drivers/firmware/efi/libstub/unaccepted_memory.c b/drivers/firmware/efi/libstub/unaccepted_memory.c index 757dbe734a47..2a7eac7fef86 100644 --- a/drivers/firmware/efi/libstub/unaccepted_memory.c +++ b/drivers/firmware/efi/libstub/unaccepted_memory.c @@ -9,7 +9,7 @@ struct efi_unaccepted_memory *unaccepted_table; efi_status_t allocate_unaccepted_bitmap(__u32 nr_desc, struct efi_boot_memmap *map) { - efi_guid_t unaccepted_table_guid = LINUX_EFI_UNACCEPTED_MEM_TABLE_GUID; + static efi_guid_t unaccepted_table_guid = LINUX_EFI_UNACCEPTED_MEM_TABLE_GUID; u64 unaccepted_start = ULLONG_MAX, unaccepted_end = 0, bitmap_size; efi_status_t status; int i; diff --git a/drivers/firmware/efi/libstub/x86-stub.c b/drivers/firmware/efi/libstub/x86-stub.c index cef32e2c82d8..7e0f5997072a 100644 --- a/drivers/firmware/efi/libstub/x86-stub.c +++ b/drivers/firmware/efi/libstub/x86-stub.c @@ -114,9 +114,9 @@ preserve_pci_rom_image(efi_pci_io_protocol_t *pci, struct pci_setup_rom **__rom) */ static void setup_efi_pci(struct boot_params *params) { + static efi_guid_t pci_proto = EFI_PCI_IO_PROTOCOL_GUID; efi_status_t status; efi_handle_t *pci_handle __free(efi_pool) = NULL; - efi_guid_t pci_proto = EFI_PCI_IO_PROTOCOL_GUID; struct setup_data *data; unsigned long num; efi_handle_t h; @@ -155,7 +155,7 @@ static void setup_efi_pci(struct boot_params *params) static void retrieve_apple_device_properties(struct boot_params *boot_params) { - efi_guid_t guid = APPLE_PROPERTIES_PROTOCOL_GUID; + static efi_guid_t guid = APPLE_PROPERTIES_PROTOCOL_GUID; struct setup_data *data, *new; efi_status_t status; u32 size = 0; @@ -444,7 +444,7 @@ efi_status_t efi_adjust_memory_range_protection(unsigned long start, static void setup_unaccepted_memory(void) { - efi_guid_t mem_acceptance_proto = OVMF_SEV_MEMORY_ACCEPTANCE_PROTOCOL_GUID; + static efi_guid_t mem_acceptance_proto = OVMF_SEV_MEMORY_ACCEPTANCE_PROTOCOL_GUID; sev_memory_acceptance_protocol_t *proto; efi_status_t status; @@ -507,7 +507,7 @@ static void __noreturn efi_exit(efi_handle_t handle, efi_status_t status) static efi_status_t efi_allocate_bootparams(efi_handle_t handle, struct boot_params **bp) { - efi_guid_t proto = LOADED_IMAGE_PROTOCOL_GUID; + static efi_guid_t proto = LOADED_IMAGE_PROTOCOL_GUID; struct boot_params *boot_params; struct setup_header *hdr; efi_status_t status; @@ -914,7 +914,7 @@ void __noreturn efi_stub_entry(efi_handle_t handle, struct boot_params *boot_params) { - efi_guid_t guid = EFI_MEMORY_ATTRIBUTE_PROTOCOL_GUID; + static efi_guid_t guid = EFI_MEMORY_ATTRIBUTE_PROTOCOL_GUID; const struct linux_efi_initrd *initrd = NULL; unsigned long kernel_entry; struct setup_header *hdr; diff --git a/drivers/firmware/efi/runtime-wrappers.c b/drivers/firmware/efi/runtime-wrappers.c index 2344b9d1e81f..8f4de91727d0 100644 --- a/drivers/firmware/efi/runtime-wrappers.c +++ b/drivers/firmware/efi/runtime-wrappers.c @@ -126,6 +126,12 @@ struct efi_runtime_work efi_rts_work; */ #define EFI_RTS_TIMEOUT (120 * HZ) +/* + * Set when __efi_queue_work() gives up waiting for a call that is wedged in + * firmware. EFI runtime services are disabled for good at that point. + */ +static bool efi_rts_abandoned; + /* * efi_queue_work: Queue EFI runtime service call and wait for completion * @_rts: EFI runtime service function identifier @@ -336,7 +342,12 @@ static void __nocfi efi_call_rts(struct work_struct *work) efi_call_virt_check_flags(flags, efi_rts_work.caller); arch_efi_call_virt_teardown(); - if (!efi_enabled(EFI_RUNTIME_SERVICES)) + /* + * EFI runtime services may also have been disabled because the + * firmware faulted, but the caller is still waiting for us in that + * case. Only park the worker if the caller has given up on it. + */ + if (READ_ONCE(efi_rts_abandoned)) efi_rts_park_worker(); efi_rts_work.status = status; @@ -373,6 +384,7 @@ static efi_status_t __efi_queue_work(enum efi_rts_ids id, EFI_RTS_TIMEOUT)) { pr_err("EFI runtime service %d wedged in firmware; disabling EFI runtime services\n", id); + WRITE_ONCE(efi_rts_abandoned, true); clear_bit(EFI_RUNTIME_SERVICES, &efi.flags); return EFI_ABORTED; } diff --git a/drivers/firmware/imx/imx-dsp.c b/drivers/firmware/imx/imx-dsp.c index ed79e823157a..7e3f45ddf0c1 100644 --- a/drivers/firmware/imx/imx-dsp.c +++ b/drivers/firmware/imx/imx-dsp.c @@ -99,8 +99,10 @@ static int imx_dsp_setup_channels(struct imx_dsp_ipc *dsp_ipc) else chan_name = kasprintf(GFP_KERNEL, "rxdb%d", i - 2); - if (!chan_name) - return -ENOMEM; + if (!chan_name) { + ret = -ENOMEM; + goto out; + } dsp_chan = &dsp_ipc->chans[i]; dsp_chan->name = chan_name; diff --git a/drivers/firmware/qcom/qcom_scm.c b/drivers/firmware/qcom/qcom_scm.c index 3eaa4c9ccf3c..db23e88155e8 100644 --- a/drivers/firmware/qcom/qcom_scm.c +++ b/drivers/firmware/qcom/qcom_scm.c @@ -854,17 +854,27 @@ static void *__qcom_scm_pas_get_rsc_table2(struct device *dev, output_rt_tzm = __qcom_scm_pas_get_rsc_table(dev, ctx->pas_id, input_rt_tzm, input_rt_size, &size); - if (PTR_ERR(output_rt_tzm) == -EOVERFLOW) - /* Try again with the size requested by the TZ */ + if (PTR_ERR(output_rt_tzm) == -EOVERFLOW) { + /* Try again with a page-aligned size requested by the TZ. */ + size = PAGE_ALIGN(size); output_rt_tzm = __qcom_scm_pas_get_rsc_table(dev, ctx->pas_id, input_rt_tzm, input_rt_size, &size); + } if (IS_ERR(output_rt_tzm)) { ret = PTR_ERR(output_rt_tzm); goto free_input_rt; } + *output_rt_size = size; + + /* A zero-sized table means that TrustZone has no resource table. */ + if (!size) { + tbl_ptr = NULL; + goto free_output_rt; + } + tbl_ptr = kmemdup(output_rt_tzm, size, GFP_KERNEL); if (!tbl_ptr) { qcom_tzmem_free(output_rt_tzm); @@ -872,7 +882,7 @@ static void *__qcom_scm_pas_get_rsc_table2(struct device *dev, goto free_input_rt; } - *output_rt_size = size; +free_output_rt: qcom_tzmem_free(output_rt_tzm); free_input_rt: diff --git a/drivers/firmware/qcom/qcom_tzmem.c b/drivers/firmware/qcom/qcom_tzmem.c index f926c1f64822..9fca7d302943 100644 --- a/drivers/firmware/qcom/qcom_tzmem.c +++ b/drivers/firmware/qcom/qcom_tzmem.c @@ -516,7 +516,7 @@ int qcom_tzmem_enable(struct device *dev) static int result; qcom_tzmem_dev = dev; - DO_ONCE(qcom_tzmem_do_init, &result); + DO_ONCE_SLEEPABLE(qcom_tzmem_do_init, &result); return result; } EXPORT_SYMBOL_GPL(qcom_tzmem_enable); diff --git a/drivers/gpio/gpio-crystalcove.c b/drivers/gpio/gpio-crystalcove.c index 0fb5c06d0886..ab7fab5b9754 100644 --- a/drivers/gpio/gpio-crystalcove.c +++ b/drivers/gpio/gpio-crystalcove.c @@ -396,3 +396,4 @@ module_platform_driver(crystalcove_gpio_driver); MODULE_AUTHOR("Yang, Bin "); MODULE_DESCRIPTION("Intel Crystal Cove GPIO Driver"); MODULE_LICENSE("GPL v2"); +MODULE_ALIAS("platform:crystal_cove_gpio"); diff --git a/drivers/gpio/gpio-pcf857x.c b/drivers/gpio/gpio-pcf857x.c index c1f5e10a3c20..1ba6a09542f3 100644 --- a/drivers/gpio/gpio-pcf857x.c +++ b/drivers/gpio/gpio-pcf857x.c @@ -71,8 +71,9 @@ MODULE_DEVICE_TABLE(of, pcf857x_of_table); struct pcf857x { struct gpio_chip chip; struct i2c_client *client; - struct mutex lock; /* protect 'out' */ + struct mutex lock; /* protect 'out' and 'dir' */ unsigned int out; /* software latch */ + unsigned int dir; /* direction latch (1 = input) */ unsigned int status; /* current status */ unsigned int irq_enabled; /* enabled irqs */ @@ -126,12 +127,21 @@ static int pcf857x_input(struct gpio_chip *chip, unsigned int offset) mutex_lock(&gpio->lock); gpio->out |= (1 << offset); + gpio->dir |= (1 << offset); status = gpio->write(gpio->client, gpio->out); mutex_unlock(&gpio->lock); return status; } +static int pcf857x_get_direction(struct gpio_chip *chip, unsigned int offset) +{ + struct pcf857x *gpio = gpiochip_get_data(chip); + + return (gpio->dir & (1 << offset)) ? GPIO_LINE_DIRECTION_IN + : GPIO_LINE_DIRECTION_OUT; +} + static int pcf857x_get(struct gpio_chip *chip, unsigned int offset) { struct pcf857x *gpio = gpiochip_get_data(chip); @@ -167,6 +177,7 @@ static int pcf857x_output(struct gpio_chip *chip, unsigned int offset, int value gpio->out |= bit; else gpio->out &= ~bit; + gpio->dir &= ~bit; status = gpio->write(gpio->client, gpio->out); mutex_unlock(&gpio->lock); @@ -187,6 +198,7 @@ static int pcf857x_set_multiple(struct gpio_chip *chip, unsigned long *mask, mutex_lock(&gpio->lock); gpio->out &= ~*mask; gpio->out |= *bits & *mask; + gpio->dir &= ~*mask; status = gpio->write(gpio->client, gpio->out); mutex_unlock(&gpio->lock); @@ -301,6 +313,7 @@ static int pcf857x_probe(struct i2c_client *client) gpio->chip.set_multiple = pcf857x_set_multiple; gpio->chip.direction_input = pcf857x_input; gpio->chip.direction_output = pcf857x_output; + gpio->chip.get_direction = pcf857x_get_direction; gpio->chip.ngpio = (uintptr_t)i2c_get_match_data(client); reset_gpio = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH); @@ -396,6 +409,7 @@ static int pcf857x_probe(struct i2c_client *client) * reset state. Otherwise it flags pins to be driven low. */ gpio->out = ~n_latch; + gpio->dir = ~n_latch; gpio->status = gpio->read(gpio->client); /* Enable irqchip if we have an interrupt */ diff --git a/drivers/gpio/gpiolib.c b/drivers/gpio/gpiolib.c index 226ed5b8d444..90731a547ed6 100644 --- a/drivers/gpio/gpiolib.c +++ b/drivers/gpio/gpiolib.c @@ -2682,6 +2682,8 @@ void gpiod_free_commit(struct gpio_desc *desc) clear_bit(GPIOD_FLAG_BIAS_DISABLE, &flags); clear_bit(GPIOD_FLAG_EDGE_RISING, &flags); clear_bit(GPIOD_FLAG_EDGE_FALLING, &flags); + clear_bit(GPIOD_FLAG_EVENT_CLOCK_REALTIME, &flags); + clear_bit(GPIOD_FLAG_EVENT_CLOCK_HTE, &flags); clear_bit(GPIOD_FLAG_IS_HOGGED, &flags); #ifdef CONFIG_OF_DYNAMIC WRITE_ONCE(desc->hog, NULL); @@ -3850,7 +3852,7 @@ int gpiod_set_array_value_complex(bool raw, bool can_sleep, unsigned long *value_bitmap) { struct gpio_chip *gc; - int i = 0, ret; + int i = 0, ret = 0; /* * Validate array_info against desc_array and its size. @@ -3928,8 +3930,10 @@ int gpiod_set_array_value_complex(bool raw, bool can_sleep, int hwgpio = gpiod_hwgpio(desc); int value = test_bit(i, value_bitmap); - if (unlikely(!test_bit(GPIOD_FLAG_IS_OUT, &desc->flags))) - return -EPERM; + if (unlikely(!test_bit(GPIOD_FLAG_IS_OUT, &desc->flags))) { + ret = -EPERM; + goto cleanup_bitmap; + } /* * Pins applicable for fast input but not for @@ -3946,9 +3950,13 @@ int gpiod_set_array_value_complex(bool raw, bool can_sleep, * open drain and open source outputs are set individually */ if (test_bit(GPIOD_FLAG_OPEN_DRAIN, &desc->flags) && !raw) { - gpio_set_open_drain_value_commit(desc, value); + ret = gpio_set_open_drain_value_commit(desc, value); + if (ret) + goto cleanup_bitmap; } else if (test_bit(GPIOD_FLAG_OPEN_SOURCE, &desc->flags) && !raw) { - gpio_set_open_source_value_commit(desc, value); + ret = gpio_set_open_source_value_commit(desc, value); + if (ret) + goto cleanup_bitmap; } else { __set_bit(hwgpio, mask); __assign_bit(hwgpio, bits, value); @@ -3962,10 +3970,10 @@ int gpiod_set_array_value_complex(bool raw, bool can_sleep, } while ((i < array_size) && gpio_device_chip_cmp(desc_array[i]->gdev, guard.gc)); /* push collected bits to outputs */ - ret = 0; if (count != 0) ret = gpiochip_set_multiple(guard.gc, mask, bits); +cleanup_bitmap: if (mask != fastpath_mask) bitmap_free(mask); if (bits != fastpath_bits) diff --git a/drivers/gpu/buddy.c b/drivers/gpu/buddy.c index 26e7a48b55f3..d728ddfc4f0b 100644 --- a/drivers/gpu/buddy.c +++ b/drivers/gpu/buddy.c @@ -1586,7 +1586,6 @@ EXPORT_SYMBOL(gpu_buddy_block_print); * gpu_buddy_print - print allocator state * * @mm: GPU buddy manager - * @p: GPU printer to use */ void gpu_buddy_print(struct gpu_buddy *mm) { diff --git a/drivers/gpu/drm/Makefile b/drivers/gpu/drm/Makefile index e635fcffd379..7283cf87880f 100644 --- a/drivers/gpu/drm/Makefile +++ b/drivers/gpu/drm/Makefile @@ -68,6 +68,7 @@ drm-y := \ drm_rect.o \ drm_syncobj.o \ drm_sysfs.o \ + drm_timeout.o \ drm_trace_points.o \ drm_vblank.o \ drm_vblank_work.o \ diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.c index ca5860e493a6..6e5709e641c2 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.c @@ -751,9 +751,8 @@ int amdgpu_amdkfd_submit_ib(struct amdgpu_device *adev, void amdgpu_amdkfd_set_compute_idle(struct amdgpu_device *adev, bool idle) { enum amd_powergating_state state = idle ? AMD_PG_STATE_GATE : AMD_PG_STATE_UNGATE; - if ((IP_VERSION_MAJ(amdgpu_ip_version(adev, GC_HWIP, 0)) == 11 && - ((adev->mes.kiq_version & AMDGPU_MES_VERSION_MASK) <= 64)) || - (IP_VERSION_MAJ(amdgpu_ip_version(adev, GC_HWIP, 0)) == 12)) { + if (IP_VERSION_MAJ(amdgpu_ip_version(adev, GC_HWIP, 0)) == 11 && + ((adev->mes.kiq_version & AMDGPU_MES_VERSION_MASK) <= 64)) { pr_debug("GFXOFF is %s\n", idle ? "enabled" : "disabled"); amdgpu_gfx_off_ctrl(adev, idle); } else if ((IP_VERSION_MAJ(amdgpu_ip_version(adev, GC_HWIP, 0)) == 9) && diff --git a/drivers/gpu/drm/amd/amdgpu/amdgpu_userq_fence.c b/drivers/gpu/drm/amd/amdgpu/amdgpu_userq_fence.c index 743b41db5b7c..d29581f84535 100644 --- a/drivers/gpu/drm/amd/amdgpu/amdgpu_userq_fence.c +++ b/drivers/gpu/drm/amd/amdgpu/amdgpu_userq_fence.c @@ -370,7 +370,7 @@ static int amdgpu_userq_fence_read_wptr(struct amdgpu_device *adev, struct amdgpu_bo_va_mapping *mapping; struct amdgpu_bo *bo; struct drm_exec exec; - u64 addr, *ptr; + u64 addr, offset, *ptr; int ret; addr = queue->userq_prop->wptr_gpu_addr; @@ -402,7 +402,10 @@ static int amdgpu_userq_fence_read_wptr(struct amdgpu_device *adev, goto lock_error; } - *wptr = le64_to_cpu(*ptr); + /* The WPTR can be anywhere within the BO's VA mapping. */ + offset = addr - (mapping->start << AMDGPU_GPU_PAGE_SHIFT); + offset += mapping->offset; + *wptr = le64_to_cpu(ptr[offset / sizeof(*ptr)]); amdgpu_bo_kunmap(bo); drm_exec_fini(&exec); diff --git a/drivers/gpu/drm/amd/amdgpu/atom.c b/drivers/gpu/drm/amd/amdgpu/atom.c index e0e585f280e2..1a599d5cf6a5 100644 --- a/drivers/gpu/drm/amd/amdgpu/atom.c +++ b/drivers/gpu/drm/amd/amdgpu/atom.c @@ -1420,6 +1420,11 @@ static void atom_get_vbios_date(struct atom_context *ctx) p_rom = ctx->bios; + if (ctx->bios_size < OFFSET_TO_VBIOS_DATE + 14) { + ctx->date[0] = '\0'; + return; + } + date_in_rom = p_rom + OFFSET_TO_VBIOS_DATE; ctx->date[0] = '2'; @@ -1483,10 +1488,15 @@ static void atom_get_vbios_pn(struct atom_context *ctx) vbios_str = p_rom + OFFSET_TO_VBIOS_PART_NUMBER; } - if (*vbios_str == 0) { + if (vbios_str >= p_rom + ctx->bios_size) + vbios_str = NULL; + + if (vbios_str == NULL || *vbios_str == 0) { vbios_str = atom_find_str_in_rom(ctx, BIOS_ATOM_PREFIX, 3, 1024, 64); if (vbios_str == NULL) vbios_str += sizeof(BIOS_ATOM_PREFIX) - 1; + if (vbios_str >= p_rom + ctx->bios_size) + vbios_str = NULL; } OPTIMIZER_HIDE_VAR(vbios_str); if (vbios_str != NULL && *vbios_str == 0) @@ -1494,7 +1504,9 @@ static void atom_get_vbios_pn(struct atom_context *ctx) if (vbios_str != NULL) { count = 0; - while ((count < BIOS_STRING_LENGTH) && vbios_str[count] >= ' ' && + while ((count < BIOS_STRING_LENGTH) && + vbios_str + count < p_rom + ctx->bios_size && + vbios_str[count] >= ' ' && vbios_str[count] <= 'z') { ctx->vbios_pn[count] = vbios_str[count]; count++; @@ -1527,9 +1539,10 @@ static void atom_get_vbios_version(struct atom_context *ctx) /* find anchor ATOMBIOSBK-AMD */ vbios_ver = atom_find_str_in_rom(ctx, BIOS_VERSION_PREFIX, start, end, 64); - if (vbios_ver != NULL) { - /* skip ATOMBIOSBK-AMD VER */ - vbios_ver += 18; + if (vbios_ver != NULL) + vbios_ver += 18; /* skip ATOMBIOSBK-AMD VER */ + + if (vbios_ver != NULL && vbios_ver + STRLEN_NORMAL <= p_rom + ctx->bios_size) { memcpy(ctx->vbios_ver_str, vbios_ver, STRLEN_NORMAL); } else { ctx->vbios_ver_str[0] = '\0'; @@ -1545,7 +1558,13 @@ static void atom_get_vbios_build(struct atom_context *ctx) base = CU16(ATOM_ROM_TABLE_PTR); atom_rom_hdr = CSTR(base); + if ((uint32_t)base + ATOM_ROM_CFG_PTR + sizeof(uint16_t) > ctx->bios_size) + return; + str = CSTR(CU16(base + ATOM_ROM_CFG_PTR)); + if (str >= atom_rom_hdr) + return; + /* Skip config string */ while (str < atom_rom_hdr && *str++) ; diff --git a/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c b/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c index e49d8a79045c..0213df54b33a 100644 --- a/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c +++ b/drivers/gpu/drm/amd/amdgpu/gfx_v12_1.c @@ -214,6 +214,10 @@ static void gfx_v12_1_update_perf_clk(struct amdgpu_device *adev, static void gfx_v12_1_xcc_update_perf_clk(struct amdgpu_device *adev, bool enable, int xcc_id); static int gfx_v12_1_init_cp_compute_microcode_bo(struct amdgpu_device *adev); +static void gfx_v12_1_xcc_update_medium_grain_clock_gating( + struct amdgpu_device *adev, bool enable, int xcc_id, bool force); +static void gfx_v12_1_update_spm_vmid(struct amdgpu_device *adev, int xcc_id, + struct amdgpu_ring *ring, unsigned vmid); static void gfx_v12_1_kiq_set_resources(struct amdgpu_ring *kiq_ring, uint64_t queue_mask) @@ -680,7 +684,7 @@ static void gfx_v12_1_init_rlcg_reg_access_ctrl(struct amdgpu_device *adev) static int gfx_v12_1_rlc_init(struct amdgpu_device *adev) { const struct cs_section_def *cs_data; - int r, i, num_xcc; + int r; adev->gfx.rlc.cs_data = gfx12_cs_data; @@ -693,13 +697,6 @@ static int gfx_v12_1_rlc_init(struct amdgpu_device *adev) return r; } - /* init spm vmid with 0xf */ - num_xcc = NUM_XCC(adev->gfx.xcc_mask); - for (i = 0; i < num_xcc; i++) { - if (adev->gfx.rlc.funcs->update_spm_vmid) - adev->gfx.rlc.funcs->update_spm_vmid(adev, i, NULL, 0xf); - } - return 0; } @@ -2052,6 +2049,9 @@ static int gfx_v12_1_xcc_rlc_resume(struct amdgpu_device *adev, { int r; + /* init spm vmid with 0xf */ + gfx_v12_1_update_spm_vmid(adev, xcc_id, NULL, 0xf); + if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) { gfx_v12_1_xcc_init_csb(adev, xcc_id); @@ -2817,9 +2817,10 @@ static int gfx_v12_1_xcc_cp_resume(struct amdgpu_device *adev, uint16_t xcc_mask return r; } - /* GFX CGCG and LS is set by default */ - if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) - gfx_v12_1_xcc_enable_gui_idle_interrupt(adev, true, xcc_id); + gfx_v12_1_xcc_update_medium_grain_clock_gating(adev, false, + xcc_id, true); + /* GFX CGCG and LS is disabled by rlc fw */ + gfx_v12_1_xcc_enable_gui_idle_interrupt(adev, false, xcc_id); gfx_v12_1_xcc_cp_set_doorbell_range(adev, xcc_id); @@ -2851,6 +2852,8 @@ static int gfx_v12_1_xcc_cp_resume(struct amdgpu_device *adev, uint16_t xcc_mask if (r) return r; } + gfx_v12_1_xcc_update_medium_grain_clock_gating(adev, true, + xcc_id, true); } return 0; @@ -3490,37 +3493,41 @@ static void gfx_v12_1_xcc_update_coarse_grain_clock_gating(struct amdgpu_device } } -static void gfx_v12_1_xcc_update_medium_grain_clock_gating(struct amdgpu_device *adev, - bool enable, int xcc_id) +static void gfx_v12_1_xcc_update_medium_grain_clock_gating( + struct amdgpu_device *adev, bool enable, int xcc_id, bool force) { uint32_t data, def; - if (!(adev->cg_flags & (AMD_CG_SUPPORT_GFX_MGCG | AMD_CG_SUPPORT_GFX_MGLS))) + bool support_mgcg; + + support_mgcg = force || (adev->cg_flags & AMD_CG_SUPPORT_GFX_MGCG); + + if (!support_mgcg) return; /* It is disabled by HW by default */ if (enable) { - if (adev->cg_flags & AMD_CG_SUPPORT_GFX_MGCG) { - /* 1 - RLC_CGTT_MGCG_OVERRIDE */ - def = data = RREG32_SOC15(GC, GET_INST(GC, xcc_id), regRLC_CGTT_MGCG_OVERRIDE); + /* 1 - RLC_CGTT_MGCG_OVERRIDE */ + def = data = RREG32_SOC15(GC, GET_INST(GC, xcc_id), + regRLC_CGTT_MGCG_OVERRIDE); - data &= ~(RLC_CGTT_MGCG_OVERRIDE__GRBM_CGTT_SCLK_OVERRIDE_MASK | - RLC_CGTT_MGCG_OVERRIDE__RLC_CGTT_SCLK_OVERRIDE_MASK | - RLC_CGTT_MGCG_OVERRIDE__GFXIP_MGCG_OVERRIDE_MASK); + data &= ~(RLC_CGTT_MGCG_OVERRIDE__GRBM_CGTT_SCLK_OVERRIDE_MASK | + RLC_CGTT_MGCG_OVERRIDE__RLC_CGTT_SCLK_OVERRIDE_MASK | + RLC_CGTT_MGCG_OVERRIDE__GFXIP_MGCG_OVERRIDE_MASK); - if (def != data) - WREG32_SOC15(GC, GET_INST(GC, xcc_id), regRLC_CGTT_MGCG_OVERRIDE, data); - } + if (def != data) + WREG32_SOC15(GC, GET_INST(GC, xcc_id), + regRLC_CGTT_MGCG_OVERRIDE, data); } else { - if (adev->cg_flags & AMD_CG_SUPPORT_GFX_MGCG) { - def = data = RREG32_SOC15(GC, GET_INST(GC, xcc_id), regRLC_CGTT_MGCG_OVERRIDE); + def = data = RREG32_SOC15(GC, GET_INST(GC, xcc_id), + regRLC_CGTT_MGCG_OVERRIDE); - data |= (RLC_CGTT_MGCG_OVERRIDE__RLC_CGTT_SCLK_OVERRIDE_MASK | - RLC_CGTT_MGCG_OVERRIDE__GRBM_CGTT_SCLK_OVERRIDE_MASK | - RLC_CGTT_MGCG_OVERRIDE__GFXIP_MGCG_OVERRIDE_MASK); + data |= (RLC_CGTT_MGCG_OVERRIDE__RLC_CGTT_SCLK_OVERRIDE_MASK | + RLC_CGTT_MGCG_OVERRIDE__GRBM_CGTT_SCLK_OVERRIDE_MASK | + RLC_CGTT_MGCG_OVERRIDE__GFXIP_MGCG_OVERRIDE_MASK); - if (def != data) - WREG32_SOC15(GC, GET_INST(GC, xcc_id), regRLC_CGTT_MGCG_OVERRIDE, data); - } + if (def != data) + WREG32_SOC15(GC, GET_INST(GC, xcc_id), + regRLC_CGTT_MGCG_OVERRIDE, data); } } @@ -3590,7 +3597,8 @@ static int gfx_v12_1_xcc_update_gfx_clock_gating(struct amdgpu_device *adev, gfx_v12_1_xcc_update_coarse_grain_clock_gating(adev, enable, xcc_id); - gfx_v12_1_xcc_update_medium_grain_clock_gating(adev, enable, xcc_id); + gfx_v12_1_xcc_update_medium_grain_clock_gating(adev, enable, xcc_id, + false); gfx_v12_1_xcc_update_repeater_fgcg(adev, enable, xcc_id); diff --git a/drivers/gpu/drm/amd/amdgpu/jpeg_v2_0.c b/drivers/gpu/drm/amd/amdgpu/jpeg_v2_0.c index a9c00adcfe41..2f4167f74ca2 100644 --- a/drivers/gpu/drm/amd/amdgpu/jpeg_v2_0.c +++ b/drivers/gpu/drm/amd/amdgpu/jpeg_v2_0.c @@ -159,11 +159,15 @@ static int jpeg_v2_0_hw_init(struct amdgpu_ip_block *ip_block) { struct amdgpu_device *adev = ip_block->adev; struct amdgpu_ring *ring = adev->jpeg.inst->ring_dec; + int r; adev->nbio.funcs->vcn_doorbell_range(adev, ring->use_doorbell, (adev->doorbell_index.vcn.vcn_ring0_1 << 1), 0); - return amdgpu_ring_test_helper(ring); + r = amdgpu_ring_test_helper(ring); + if (r) + cancel_delayed_work_sync(&adev->jpeg.idle_work); + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/jpeg_v2_5.c b/drivers/gpu/drm/amd/amdgpu/jpeg_v2_5.c index 5208312e7017..cd3ea918a392 100644 --- a/drivers/gpu/drm/amd/amdgpu/jpeg_v2_5.c +++ b/drivers/gpu/drm/amd/amdgpu/jpeg_v2_5.c @@ -221,10 +221,14 @@ static int jpeg_v2_5_hw_init(struct amdgpu_ip_block *ip_block) r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; } return 0; + +error: + cancel_delayed_work_sync(&adev->jpeg.idle_work); + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/jpeg_v3_0.c b/drivers/gpu/drm/amd/amdgpu/jpeg_v3_0.c index e9ccadeb7696..e63ee43831c7 100644 --- a/drivers/gpu/drm/amd/amdgpu/jpeg_v3_0.c +++ b/drivers/gpu/drm/amd/amdgpu/jpeg_v3_0.c @@ -174,11 +174,15 @@ static int jpeg_v3_0_hw_init(struct amdgpu_ip_block *ip_block) { struct amdgpu_device *adev = ip_block->adev; struct amdgpu_ring *ring = adev->jpeg.inst->ring_dec; + int r; adev->nbio.funcs->vcn_doorbell_range(adev, ring->use_doorbell, (adev->doorbell_index.vcn.vcn_ring0_1 << 1), 0); - return amdgpu_ring_test_helper(ring); + r = amdgpu_ring_test_helper(ring); + if (r) + cancel_delayed_work_sync(&adev->jpeg.idle_work); + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/jpeg_v4_0.c b/drivers/gpu/drm/amd/amdgpu/jpeg_v4_0.c index 6fd4238a8471..88646b579259 100644 --- a/drivers/gpu/drm/amd/amdgpu/jpeg_v4_0.c +++ b/drivers/gpu/drm/amd/amdgpu/jpeg_v4_0.c @@ -204,10 +204,14 @@ static int jpeg_v4_0_hw_init(struct amdgpu_ip_block *ip_block) r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; } return 0; + +error: + cancel_delayed_work_sync(&adev->jpeg.idle_work); + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/jpeg_v4_0_3.c b/drivers/gpu/drm/amd/amdgpu/jpeg_v4_0_3.c index 0fdc32b3ae91..d6dbf855c136 100644 --- a/drivers/gpu/drm/amd/amdgpu/jpeg_v4_0_3.c +++ b/drivers/gpu/drm/amd/amdgpu/jpeg_v4_0_3.c @@ -434,12 +434,16 @@ static int jpeg_v4_0_3_hw_init(struct amdgpu_ip_block *ip_block) VCN_JPEG_DB_CTRL__EN_MASK); r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; } } } return 0; + +error: + cancel_delayed_work_sync(&adev->jpeg.idle_work); + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/jpeg_v4_0_5.c b/drivers/gpu/drm/amd/amdgpu/jpeg_v4_0_5.c index 3f61d5367d94..2e15214525ff 100644 --- a/drivers/gpu/drm/amd/amdgpu/jpeg_v4_0_5.c +++ b/drivers/gpu/drm/amd/amdgpu/jpeg_v4_0_5.c @@ -231,10 +231,14 @@ static int jpeg_v4_0_5_hw_init(struct amdgpu_ip_block *ip_block) ring = adev->jpeg.inst[i].ring_dec; r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; } return 0; + +error: + cancel_delayed_work_sync(&adev->jpeg.idle_work); + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/jpeg_v5_0_0.c b/drivers/gpu/drm/amd/amdgpu/jpeg_v5_0_0.c index e6e99f7e0a8a..daead8213bab 100644 --- a/drivers/gpu/drm/amd/amdgpu/jpeg_v5_0_0.c +++ b/drivers/gpu/drm/amd/amdgpu/jpeg_v5_0_0.c @@ -172,9 +172,13 @@ static int jpeg_v5_0_0_hw_init(struct amdgpu_ip_block *ip_block) r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; return 0; + +error: + cancel_delayed_work_sync(&adev->jpeg.idle_work); + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/jpeg_v5_0_1.c b/drivers/gpu/drm/amd/amdgpu/jpeg_v5_0_1.c index db3fbe4eabb9..044deab6febd 100644 --- a/drivers/gpu/drm/amd/amdgpu/jpeg_v5_0_1.c +++ b/drivers/gpu/drm/amd/amdgpu/jpeg_v5_0_1.c @@ -306,11 +306,15 @@ static int jpeg_v5_0_1_hw_init(struct amdgpu_ip_block *ip_block) VCN_JPEG_DB_CTRL__EN_MASK); r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; } } return 0; + +error: + cancel_delayed_work_sync(&adev->jpeg.idle_work); + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/jpeg_v5_0_2.c b/drivers/gpu/drm/amd/amdgpu/jpeg_v5_0_2.c index ea54a2b6eddb..ad554733a699 100644 --- a/drivers/gpu/drm/amd/amdgpu/jpeg_v5_0_2.c +++ b/drivers/gpu/drm/amd/amdgpu/jpeg_v5_0_2.c @@ -252,11 +252,15 @@ static int jpeg_v5_0_2_hw_init(struct amdgpu_ip_block *ip_block) VCN_JPEG_DB_CTRL__EN_MASK); r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; } } return 0; + +error: + cancel_delayed_work_sync(&adev->jpeg.idle_work); + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/jpeg_v5_3_0.c b/drivers/gpu/drm/amd/amdgpu/jpeg_v5_3_0.c index c929d6f83bac..9f8f3a3cbc04 100644 --- a/drivers/gpu/drm/amd/amdgpu/jpeg_v5_3_0.c +++ b/drivers/gpu/drm/amd/amdgpu/jpeg_v5_3_0.c @@ -156,9 +156,13 @@ static int jpeg_v5_3_0_hw_init(struct amdgpu_ip_block *ip_block) r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; return 0; + +error: + cancel_delayed_work_sync(&adev->jpeg.idle_work); + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/mes_userqueue.c b/drivers/gpu/drm/amd/amdgpu/mes_userqueue.c index 8d5dcaf4fea6..d19ece2eb7d4 100644 --- a/drivers/gpu/drm/amd/amdgpu/mes_userqueue.c +++ b/drivers/gpu/drm/amd/amdgpu/mes_userqueue.c @@ -60,7 +60,8 @@ mes_userq_create_wptr_mapping(struct amdgpu_device *adev, } obj = wptr_mapping->bo_va->base.bo; - ret = drm_exec_lock_obj(&exec, &obj->tbo.base); + ret = drm_exec_prepare_obj(&exec, &obj->tbo.base, + TTM_NUM_MOVE_FENCES + 1); drm_exec_retry_on_contention(&exec); if (unlikely(ret)) goto fail_lock; diff --git a/drivers/gpu/drm/amd/amdgpu/soc_v1_0.c b/drivers/gpu/drm/amd/amdgpu/soc_v1_0.c index 43e92e2a85e8..1918313d1496 100644 --- a/drivers/gpu/drm/amd/amdgpu/soc_v1_0.c +++ b/drivers/gpu/drm/amd/amdgpu/soc_v1_0.c @@ -293,8 +293,7 @@ static int soc_v1_0_common_early_init(struct amdgpu_ip_block *ip_block) switch (amdgpu_ip_version(adev, GC_HWIP, 0)) { case IP_VERSION(12, 1, 0): - adev->cg_flags = AMD_CG_SUPPORT_GFX_CGCG | - AMD_CG_SUPPORT_GFX_CGLS; + adev->cg_flags = 0; adev->pg_flags = AMD_PG_SUPPORT_VCN_DPG; adev->external_rev_id = adev->rev_id + 0x50; break; @@ -849,6 +848,11 @@ int soc_v1_0_init_soc_config(struct amdgpu_device *adev) adev->sdma.sdma_mask = sdma_mask; adev->sdma.num_instances = NUM_XCC(adev->sdma.sdma_mask); + adev->vcn.harvest_config = 0; + adev->vcn.num_inst_per_aid = 1; + adev->vcn.inst_mask = 1; + adev->vcn.num_vcn_inst = hweight32(adev->vcn.inst_mask); + ret = soc_v1_0_xcp_mgr_init(adev); if (ret) return ret; diff --git a/drivers/gpu/drm/amd/amdgpu/uvd_v3_1.c b/drivers/gpu/drm/amd/amdgpu/uvd_v3_1.c index b7d451f439a7..603ee842fda7 100644 --- a/drivers/gpu/drm/amd/amdgpu/uvd_v3_1.c +++ b/drivers/gpu/drm/amd/amdgpu/uvd_v3_1.c @@ -710,7 +710,9 @@ static int uvd_v3_1_hw_init(struct amdgpu_ip_block *ip_block) amdgpu_ring_commit(ring); done: - if (!r) + if (r) + cancel_delayed_work_sync(&adev->uvd.idle_work); + else drm_info(adev_to_drm(adev), "UVD initialized successfully.\n"); return r; diff --git a/drivers/gpu/drm/amd/amdgpu/uvd_v4_2.c b/drivers/gpu/drm/amd/amdgpu/uvd_v4_2.c index 8a9ba2276275..174868aebd41 100644 --- a/drivers/gpu/drm/amd/amdgpu/uvd_v4_2.c +++ b/drivers/gpu/drm/amd/amdgpu/uvd_v4_2.c @@ -198,7 +198,9 @@ static int uvd_v4_2_hw_init(struct amdgpu_ip_block *ip_block) amdgpu_ring_commit(ring); done: - if (!r) + if (r) + cancel_delayed_work_sync(&adev->uvd.idle_work); + else drm_info(adev_to_drm(adev), "UVD initialized successfully.\n"); return r; diff --git a/drivers/gpu/drm/amd/amdgpu/uvd_v5_0.c b/drivers/gpu/drm/amd/amdgpu/uvd_v5_0.c index 454f109cbb2e..90e8fbfb5a32 100644 --- a/drivers/gpu/drm/amd/amdgpu/uvd_v5_0.c +++ b/drivers/gpu/drm/amd/amdgpu/uvd_v5_0.c @@ -190,7 +190,9 @@ static int uvd_v5_0_hw_init(struct amdgpu_ip_block *ip_block) amdgpu_ring_commit(ring); done: - if (!r) + if (r) + cancel_delayed_work_sync(&adev->uvd.idle_work); + else drm_info(adev_to_drm(adev), "UVD initialized successfully.\n"); return r; diff --git a/drivers/gpu/drm/amd/amdgpu/uvd_v6_0.c b/drivers/gpu/drm/amd/amdgpu/uvd_v6_0.c index bbd0e05d39e5..b084c92609bc 100644 --- a/drivers/gpu/drm/amd/amdgpu/uvd_v6_0.c +++ b/drivers/gpu/drm/amd/amdgpu/uvd_v6_0.c @@ -515,7 +515,9 @@ static int uvd_v6_0_hw_init(struct amdgpu_ip_block *ip_block) } done: - if (!r) { + if (r) { + cancel_delayed_work_sync(&adev->uvd.idle_work); + } else { if (uvd_v6_0_enc_support(adev)) drm_info(adev_to_drm(adev), "UVD and UVD ENC initialized successfully.\n"); else diff --git a/drivers/gpu/drm/amd/amdgpu/uvd_v7_0.c b/drivers/gpu/drm/amd/amdgpu/uvd_v7_0.c index 46222fc30be6..48eac56f758e 100644 --- a/drivers/gpu/drm/amd/amdgpu/uvd_v7_0.c +++ b/drivers/gpu/drm/amd/amdgpu/uvd_v7_0.c @@ -583,7 +583,9 @@ static int uvd_v7_0_hw_init(struct amdgpu_ip_block *ip_block) } } done: - if (!r) + if (r) + cancel_delayed_work_sync(&adev->uvd.idle_work); + else drm_info(adev_to_drm(adev), "UVD and UVD ENC initialized successfully.\n"); return r; diff --git a/drivers/gpu/drm/amd/amdgpu/vce_v1_0.c b/drivers/gpu/drm/amd/amdgpu/vce_v1_0.c index 93253db5e2de..cc9dec9c3621 100644 --- a/drivers/gpu/drm/amd/amdgpu/vce_v1_0.c +++ b/drivers/gpu/drm/amd/amdgpu/vce_v1_0.c @@ -651,12 +651,16 @@ static int vce_v1_0_hw_init(struct amdgpu_ip_block *ip_block) for (i = 0; i < adev->vce.num_rings; i++) { r = amdgpu_ring_test_helper(&adev->vce.ring[i]); if (r) - return r; + goto error; } dev_info(adev->dev, "VCE initialized successfully.\n"); return 0; + +error: + cancel_delayed_work_sync(&adev->vce.idle_work); + return r; } static int vce_v1_0_hw_fini(struct amdgpu_ip_block *ip_block) diff --git a/drivers/gpu/drm/amd/amdgpu/vce_v2_0.c b/drivers/gpu/drm/amd/amdgpu/vce_v2_0.c index 3a6fc8604108..f8c65fb4ee56 100644 --- a/drivers/gpu/drm/amd/amdgpu/vce_v2_0.c +++ b/drivers/gpu/drm/amd/amdgpu/vce_v2_0.c @@ -483,12 +483,16 @@ static int vce_v2_0_hw_init(struct amdgpu_ip_block *ip_block) for (i = 0; i < adev->vce.num_rings; i++) { r = amdgpu_ring_test_helper(&adev->vce.ring[i]); if (r) - return r; + goto error; } drm_info(adev_to_drm(adev), "VCE initialized successfully.\n"); return 0; + +error: + cancel_delayed_work_sync(&adev->vce.idle_work); + return r; } static int vce_v2_0_hw_fini(struct amdgpu_ip_block *ip_block) diff --git a/drivers/gpu/drm/amd/amdgpu/vce_v3_0.c b/drivers/gpu/drm/amd/amdgpu/vce_v3_0.c index 4dbbeaf97ad1..e5b7f64b94ba 100644 --- a/drivers/gpu/drm/amd/amdgpu/vce_v3_0.c +++ b/drivers/gpu/drm/amd/amdgpu/vce_v3_0.c @@ -482,12 +482,16 @@ static int vce_v3_0_hw_init(struct amdgpu_ip_block *ip_block) for (i = 0; i < adev->vce.num_rings; i++) { r = amdgpu_ring_test_helper(&adev->vce.ring[i]); if (r) - return r; + goto error; } drm_info(adev_to_drm(adev), "VCE initialized successfully.\n"); return 0; + +error: + cancel_delayed_work_sync(&adev->vce.idle_work); + return r; } static int vce_v3_0_hw_fini(struct amdgpu_ip_block *ip_block) diff --git a/drivers/gpu/drm/amd/amdgpu/vce_v4_0.c b/drivers/gpu/drm/amd/amdgpu/vce_v4_0.c index ee445d8abe47..4e1fbc7b50f5 100644 --- a/drivers/gpu/drm/amd/amdgpu/vce_v4_0.c +++ b/drivers/gpu/drm/amd/amdgpu/vce_v4_0.c @@ -533,12 +533,16 @@ static int vce_v4_0_hw_init(struct amdgpu_ip_block *ip_block) for (i = 0; i < adev->vce.num_rings; i++) { r = amdgpu_ring_test_helper(&adev->vce.ring[i]); if (r) - return r; + goto error; } drm_info(adev_to_drm(adev), "VCE initialized successfully.\n"); return 0; + +error: + cancel_delayed_work_sync(&adev->vce.idle_work); + return r; } static int vce_v4_0_hw_fini(struct amdgpu_ip_block *ip_block) diff --git a/drivers/gpu/drm/amd/amdgpu/vcn_v1_0.c b/drivers/gpu/drm/amd/amdgpu/vcn_v1_0.c index e9d790914761..70ad27daeb51 100644 --- a/drivers/gpu/drm/amd/amdgpu/vcn_v1_0.c +++ b/drivers/gpu/drm/amd/amdgpu/vcn_v1_0.c @@ -252,18 +252,25 @@ static int vcn_v1_0_hw_init(struct amdgpu_ip_block *ip_block) r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error_vcn; for (i = 0; i < adev->vcn.inst[0].num_enc_rings; ++i) { ring = &adev->vcn.inst->ring_enc[i]; r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error_vcn; } ring = adev->jpeg.inst->ring_dec; r = amdgpu_ring_test_helper(ring); + if (r) + goto error_both; + return 0; +error_both: + cancel_delayed_work_sync(&adev->jpeg.idle_work); +error_vcn: + cancel_delayed_work_sync(&adev->vcn.inst[0].idle_work); return r; } diff --git a/drivers/gpu/drm/amd/amdgpu/vcn_v2_0.c b/drivers/gpu/drm/amd/amdgpu/vcn_v2_0.c index 0442bfcfd384..a8bead3124cc 100644 --- a/drivers/gpu/drm/amd/amdgpu/vcn_v2_0.c +++ b/drivers/gpu/drm/amd/amdgpu/vcn_v2_0.c @@ -293,7 +293,7 @@ static int vcn_v2_0_hw_init(struct amdgpu_ip_block *ip_block) r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; //Disable vcn decode for sriov if (amdgpu_sriov_vf(adev)) @@ -303,10 +303,14 @@ static int vcn_v2_0_hw_init(struct amdgpu_ip_block *ip_block) ring = &adev->vcn.inst->ring_enc[i]; r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; } return 0; + +error: + cancel_delayed_work_sync(&adev->vcn.inst->idle_work); + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/vcn_v2_5.c b/drivers/gpu/drm/amd/amdgpu/vcn_v2_5.c index 0d8a3cea63ee..2592927d2fd4 100644 --- a/drivers/gpu/drm/amd/amdgpu/vcn_v2_5.c +++ b/drivers/gpu/drm/amd/amdgpu/vcn_v2_5.c @@ -480,18 +480,26 @@ static int vcn_v2_5_hw_init(struct amdgpu_ip_block *ip_block) r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; for (i = 0; i < adev->vcn.inst[j].num_enc_rings; ++i) { ring = &adev->vcn.inst[j].ring_enc[i]; r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; } } } return r; + +error: + for (i = 0; i <= j; i++) { + if (adev->vcn.harvest_config & (1 << i)) + continue; + cancel_delayed_work_sync(&adev->vcn.inst[i].idle_work); + } + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/vcn_v3_0.c b/drivers/gpu/drm/amd/amdgpu/vcn_v3_0.c index 00d8f35846f2..d4a3d5da3f76 100644 --- a/drivers/gpu/drm/amd/amdgpu/vcn_v3_0.c +++ b/drivers/gpu/drm/amd/amdgpu/vcn_v3_0.c @@ -416,18 +416,26 @@ static int vcn_v3_0_hw_init(struct amdgpu_ip_block *ip_block) r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; for (j = 0; j < adev->vcn.inst[i].num_enc_rings; ++j) { ring = &adev->vcn.inst[i].ring_enc[j]; r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; } } } return 0; + +error: + while (i >= 0) { + if (!(adev->vcn.harvest_config & (1 << i))) + cancel_delayed_work_sync(&adev->vcn.inst[i].idle_work); + i--; + } + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/vcn_v4_0.c b/drivers/gpu/drm/amd/amdgpu/vcn_v4_0.c index c2ddf3cb368f..f2e89ba9fe41 100644 --- a/drivers/gpu/drm/amd/amdgpu/vcn_v4_0.c +++ b/drivers/gpu/drm/amd/amdgpu/vcn_v4_0.c @@ -348,11 +348,19 @@ static int vcn_v4_0_hw_init(struct amdgpu_ip_block *ip_block) r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; } } return 0; + +error: + while (i >= 0) { + if (!(adev->vcn.harvest_config & (1 << i))) + cancel_delayed_work_sync(&adev->vcn.inst[i].idle_work); + i--; + } + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/vcn_v4_0_3.c b/drivers/gpu/drm/amd/amdgpu/vcn_v4_0_3.c index 62e2e04314dc..44a5d57c07a3 100644 --- a/drivers/gpu/drm/amd/amdgpu/vcn_v4_0_3.c +++ b/drivers/gpu/drm/amd/amdgpu/vcn_v4_0_3.c @@ -394,11 +394,19 @@ static int vcn_v4_0_3_hw_init(struct amdgpu_ip_block *ip_block) r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; } } return r; + +error: + while (i >= 0) { + if (!(adev->vcn.harvest_config & (1 << i))) + cancel_delayed_work_sync(&adev->vcn.inst[i].idle_work); + i--; + } + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/vcn_v4_0_5.c b/drivers/gpu/drm/amd/amdgpu/vcn_v4_0_5.c index c8879a6e5297..f3a57cb8b6ae 100644 --- a/drivers/gpu/drm/amd/amdgpu/vcn_v4_0_5.c +++ b/drivers/gpu/drm/amd/amdgpu/vcn_v4_0_5.c @@ -302,10 +302,18 @@ static int vcn_v4_0_5_hw_init(struct amdgpu_ip_block *ip_block) r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; } return 0; + +error: + while (i >= 0) { + if (!(adev->vcn.harvest_config & (1 << i))) + cancel_delayed_work_sync(&adev->vcn.inst[i].idle_work); + i--; + } + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/vcn_v5_0_0.c b/drivers/gpu/drm/amd/amdgpu/vcn_v5_0_0.c index 886e2c2074a9..b2936da0786c 100644 --- a/drivers/gpu/drm/amd/amdgpu/vcn_v5_0_0.c +++ b/drivers/gpu/drm/amd/amdgpu/vcn_v5_0_0.c @@ -266,10 +266,18 @@ static int vcn_v5_0_0_hw_init(struct amdgpu_ip_block *ip_block) r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; } return 0; + +error: + while (i >= 0) { + if (!(adev->vcn.harvest_config & (1 << i))) + cancel_delayed_work_sync(&adev->vcn.inst[i].idle_work); + i--; + } + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/vcn_v5_0_1.c b/drivers/gpu/drm/amd/amdgpu/vcn_v5_0_1.c index 011afc0fdc87..5abd0da3dd92 100644 --- a/drivers/gpu/drm/amd/amdgpu/vcn_v5_0_1.c +++ b/drivers/gpu/drm/amd/amdgpu/vcn_v5_0_1.c @@ -341,11 +341,19 @@ static int vcn_v5_0_1_hw_init(struct amdgpu_ip_block *ip_block) r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; } } return 0; + +error: + while (i >= 0) { + if (!(adev->vcn.harvest_config & (1 << i))) + cancel_delayed_work_sync(&adev->vcn.inst[i].idle_work); + i--; + } + return r; } /** diff --git a/drivers/gpu/drm/amd/amdgpu/vcn_v5_0_2.c b/drivers/gpu/drm/amd/amdgpu/vcn_v5_0_2.c index b9f6ae75ea72..70706703b02c 100644 --- a/drivers/gpu/drm/amd/amdgpu/vcn_v5_0_2.c +++ b/drivers/gpu/drm/amd/amdgpu/vcn_v5_0_2.c @@ -129,7 +129,7 @@ static int vcn_v5_0_2_sw_init(struct amdgpu_ip_block *ip_block) ring->use_doorbell = true; ring->doorbell_index = - (adev->doorbell_index.vcn.vcn_ring0_1 << 1) + 32 * vcn_inst; + (adev->doorbell_index.vcn.vcn_ring0_1 << 1) + 11 * vcn_inst; ring->vm_hub = AMDGPU_MMHUB0(adev->vcn.inst[i].aid_id); sprintf(ring->name, "vcn_unified_%d", adev->vcn.inst[i].aid_id); @@ -203,8 +203,6 @@ static int vcn_v5_0_2_hw_init(struct amdgpu_ip_block *ip_block) int i, r, vcn_inst; uint32_t tmp; - if (RREG32_SOC15(VCN, GET_INST(VCN, 0), regVCN_RRMT_CNTL) & 0x200) - adev->vcn.caps |= AMDGPU_VCN_CAPS(RRMT_ENABLED); for (i = 0; i < adev->vcn.num_vcn_inst; ++i) { vcn_inst = GET_INST(VCN, i); ring = &adev->vcn.inst[i].ring_enc[0]; @@ -225,10 +223,18 @@ static int vcn_v5_0_2_hw_init(struct amdgpu_ip_block *ip_block) r = amdgpu_ring_test_helper(ring); if (r) - return r; + goto error; } return 0; + +error: + while (i >= 0) { + if (!(adev->vcn.harvest_config & (1 << i))) + cancel_delayed_work_sync(&adev->vcn.inst[i].idle_work); + i--; + } + return r; } /** diff --git a/drivers/gpu/drm/amd/amdkfd/kfd_priv.h b/drivers/gpu/drm/amd/amdkfd/kfd_priv.h index f405f476ed18..288731acc928 100644 --- a/drivers/gpu/drm/amd/amdkfd/kfd_priv.h +++ b/drivers/gpu/drm/amd/amdkfd/kfd_priv.h @@ -437,8 +437,6 @@ enum kfd_unmap_queues_filter { * * @KFD_QUEUE_TYPE_HIQ: HIQ queue type. * - * @KFD_QUEUE_TYPE_DIQ: DIQ queue type. - * * @KFD_QUEUE_TYPE_SDMA_XGMI: Special SDMA queue for XGMI interface. * * @KFD_QUEUE_TYPE_SDMA_BY_ENG_ID: SDMA user mode queue with target SDMA engine ID. diff --git a/drivers/gpu/drm/amd/display/Kconfig b/drivers/gpu/drm/amd/display/Kconfig index 1727d25646cc..617bc1932524 100644 --- a/drivers/gpu/drm/amd/display/Kconfig +++ b/drivers/gpu/drm/amd/display/Kconfig @@ -34,11 +34,20 @@ config DRM_AMD_DC_SI bool "AMD DC support for Southern Islands ASICs" depends on DRM_AMDGPU_SI depends on DRM_AMD_DC + depends on DRM_AMD_DC_DCE help Choose this option to enable new AMD DC support for SI asics by default. This includes Tahiti, Pitcairn, Cape Verde, Oland. Hainan is not supported by AMD DC and it has no physical DCE6. +config DRM_AMD_DC_DCE + bool "AMD DC support for legacy DCE ASICs" + default y + depends on DRM_AMD_DC + help + Enable support for the legacy DCE (DCE 8/10/11/12) display engines. + Enabled by default so DC keeps support for these older ASICs. + config DEBUG_KERNEL_DC bool "Enable kgdb break in DC" depends on DRM_AMD_DC diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c index f3551bd0b0a4..0c92f9c5d582 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c @@ -1979,6 +1979,10 @@ static int dm_resume(struct amdgpu_ip_block *ip_block) /* On resume we need to rewrite the MSTM control bits to enable MST*/ s3_handle_mst(ddev, false); + /* Exit IPS before the detection loop's first AUX/DDC access. */ + scoped_guard(mutex, &dm->dc_lock) + dc_exit_ips_for_hw_access(dm->dc); + /* Do detection*/ drm_connector_list_iter_begin(ddev, &iter); drm_for_each_connector_iter(connector, &iter) { diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.c index 45a69bf43971..bfcc8ad75295 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.c @@ -3963,6 +3963,24 @@ void amdgpu_dm_update_freesync_caps(struct drm_connector *connector, } } + /* + * Apply per-monitor FreeSync range quirks. Some panels report a + * VRR minimum that does not operate reliably; force it when the + * monitor is quirked (see apply_edid_quirks()). + */ + if (sink->edid_caps.panel_patch.force_freesync_min_hz && freesync_capable) { + amdgpu_dm_connector->min_vfreq = + sink->edid_caps.panel_patch.force_freesync_min_hz; + connector->display_info.monitor_range.min_vfreq = + amdgpu_dm_connector->min_vfreq; + } + + /* HDMI/PCON without an EDID FreeSync VCP code is not FreeSync-capable. */ + if ((sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A || + as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) && + !sink->edid_caps.freesync_vcp_code) + freesync_capable = false; + /* Handle MCCS */ if (do_mccs) { dm_helpers_read_mccs_caps(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink); diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.c index 9ff25bc8ee5a..870534b7cf46 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_dmub.c @@ -511,7 +511,6 @@ int dm_dmub_sw_init(struct amdgpu_device *adev) DMUB_WINDOW_MEMORY_TYPE_FB, /* DMUB_WINDOW_CURSOR_OFFLOAD */ }; int r; - int mem_domain = AMDGPU_GEM_DOMAIN_GTT; switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) { case IP_VERSION(2, 1, 0): @@ -648,19 +647,13 @@ int dm_dmub_sw_init(struct amdgpu_device *adev) return -EINVAL; } - /* Limit to allocate dmub to GTT on DCN32/1 - * TODO: Other asics with GDDR7 may have worse latency - */ - if (dmub_asic != DMUB_ASIC_DCN32 && - dmub_asic != DMUB_ASIC_DCN321) - mem_domain |= AMDGPU_GEM_DOMAIN_VRAM; - /* * Allocate a framebuffer based on the total size of all the regions. * TODO: Move this into GART. */ r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE, - mem_domain, + AMDGPU_GEM_DOMAIN_VRAM | + AMDGPU_GEM_DOMAIN_GTT, &adev->dm.dmub_bo, &adev->dm.dmub_bo_gpu_addr, &adev->dm.dmub_bo_cpu_addr); diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_helpers.c b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_helpers.c index 673b3cede7dd..e1cc617eeda5 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_helpers.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_helpers.c @@ -147,6 +147,24 @@ STATIC_IFN_KUNIT void apply_edid_quirks(struct dc_link *link, struct edid *edid, drm_dbg_driver(dev, "Hiding secondary tile on panel id %X\n", panel_id); edid_caps->panel_patch.disable_second_tile = true; break; + /* + * Workaround for the Acer Predator X34GS which reports a FreeSync + * minimum refresh rate that does not operate reliably. Force the + * FreeSync range minimum to 55 Hz. + */ + case drm_edid_encode_panel_id('A', 'C', 'R', 0x08AF): + drm_dbg_driver(dev, "Force FreeSync min to 55 Hz on panel id %X\n", panel_id); + edid_caps->panel_patch.force_freesync_min_hz = 55; + break; + /* + * Workaround for the Lenovo G34w-30 which reports a FreeSync + * minimum refresh rate (48 Hz) that fails to light up over DP. + * Force the FreeSync range minimum to 60 Hz. + */ + case drm_edid_encode_panel_id('L', 'E', 'N', 0x66F1): + drm_dbg_driver(dev, "Force FreeSync min to 60 Hz on panel id %X\n", panel_id); + edid_caps->panel_patch.force_freesync_min_hz = 60; + break; default: return; } 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 f33a2c1e0da5..7d46631854c6 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 @@ -76,10 +76,10 @@ TRACE_EVENT(amdgpu_dc_performance, const char *func, unsigned int line), TP_ARGS(read_count, write_count, last_read, last_write, func, line), TP_STRUCT__entry( - __field(uint32_t, reads) - __field(uint32_t, writes) - __field(uint32_t, read_delta) - __field(uint32_t, write_delta) + __field(unsigned long, reads) + __field(unsigned long, writes) + __field(unsigned long, read_delta) + __field(unsigned long, write_delta) __string(func, func) __field(uint32_t, line) ), @@ -93,12 +93,9 @@ TRACE_EVENT(amdgpu_dc_performance, *last_read = read_count; *last_write = write_count; ), - TP_printk("%s:%d reads=%08ld (%08ld total), writes=%08ld (%08ld total)", - __get_str(func), __entry->line, - (unsigned long)__entry->read_delta, - (unsigned long)__entry->reads, - (unsigned long)__entry->write_delta, - (unsigned long)__entry->writes) + TP_printk("%s:%u reads=%08lu (%08lu total), writes=%08lu (%08lu total)", + __get_str(func), __entry->line, __entry->read_delta, + __entry->reads, __entry->write_delta, __entry->writes) ); TRACE_EVENT(amdgpu_dm_connector_atomic_check, @@ -314,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_commit *state), - TP_ARGS(state), - - TP_STRUCT__entry( - __field(const struct drm_atomic_commit *, 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_commit *state), + TP_ARGS(state), + TP_STRUCT__entry(__field(const struct drm_atomic_commit *, 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, @@ -513,6 +506,7 @@ TRACE_EVENT(amdgpu_dm_dc_clocks_state, TP_fast_assign( __entry->dispclk_khz = clk->dispclk_khz; __entry->dppclk_khz = clk->dppclk_khz; + __entry->disp_dpp_voltage_level_khz = clk->disp_dpp_voltage_level_khz; __entry->dcfclk_khz = clk->dcfclk_khz; __entry->socclk_khz = clk->socclk_khz; __entry->dcfclk_deep_sleep_khz = clk->dcfclk_deep_sleep_khz; @@ -522,7 +516,6 @@ TRACE_EVENT(amdgpu_dm_dc_clocks_state, __entry->p_state_change_support = clk->p_state_change_support; __entry->prev_p_state_change_support = clk->prev_p_state_change_support; __entry->pwr_state = clk->pwr_state; - __entry->prev_p_state_change_support = clk->prev_p_state_change_support; __entry->dtm_level = clk->dtm_level; __entry->max_supported_dppclk_khz = clk->max_supported_dppclk_khz; __entry->max_supported_dispclk_khz = clk->max_supported_dispclk_khz; @@ -532,8 +525,8 @@ TRACE_EVENT(amdgpu_dm_dc_clocks_state, TP_printk("dispclk_khz=%d dppclk_khz=%d disp_dpp_voltage_level_khz=%d dcfclk_khz=%d socclk_khz=%d " "dcfclk_deep_sleep_khz=%d fclk_khz=%d phyclk_khz=%d " "dramclk_khz=%d p_state_change_support=%d " - "prev_p_state_change_support=%d pwr_state=%d prev_p_state_change_support=%d " - "dtm_level=%d max_supported_dppclk_khz=%d max_supported_dispclk_khz=%d " + "prev_p_state_change_support=%d pwr_state=%d dtm_level=%d " + "max_supported_dppclk_khz=%d max_supported_dispclk_khz=%d " "bw_dppclk_khz=%d bw_dispclk_khz=%d ", __entry->dispclk_khz, __entry->dppclk_khz, @@ -547,7 +540,6 @@ TRACE_EVENT(amdgpu_dm_dc_clocks_state, __entry->p_state_change_support, __entry->prev_p_state_change_support, __entry->pwr_state, - __entry->prev_p_state_change_support, __entry->dtm_level, __entry->max_supported_dppclk_khz, __entry->max_supported_dispclk_khz, @@ -646,20 +638,20 @@ TRACE_EVENT(dcn_fpu, TP_STRUCT__entry( __field(bool, begin) - __field(const char *, function) + __string(function, function) __field(int, line) __field(int, recursion_depth) ), TP_fast_assign( __entry->begin = begin; - __entry->function = function; + __assign_str(function); __entry->line = line; __entry->recursion_depth = recursion_depth; ), TP_printk("%s: recursion_depth: %d: %s()+%d:", __entry->begin ? "begin" : "end", __entry->recursion_depth, - __entry->function, + __get_str(function), __entry->line ) ); @@ -669,7 +661,7 @@ TRACE_EVENT(dcn_optc_lock_unlock_state, TP_ARGS(optc_state, instance, lock, function, line), TP_STRUCT__entry( - __field(const char *, function) + __string(function, function) __field(int, instance) __field(bool, lock) __field(int, line) @@ -687,7 +679,7 @@ TRACE_EVENT(dcn_optc_lock_unlock_state, __field(int, vready_offset) ), TP_fast_assign( - __entry->function = function; + __assign_str(function); __entry->instance = instance; __entry->lock = lock; __entry->line = line; @@ -702,14 +694,14 @@ TRACE_EVENT(dcn_optc_lock_unlock_state, __entry->vstartup_start = optc_state->vstartup_start; __entry->vupdate_offset = optc_state->vupdate_offset; __entry->vupdate_width = optc_state->vupdate_width; - __entry->vready_offset = optc_state->vupdate_offset; + __entry->vready_offset = optc_state->vready_offset; ), TP_printk("%s: %s()+%d: optc_instance=%d opp_count=%d max_h_total=%d max_v_total=%d " "min_h_blank=%d min_h_sync_width=%d min_v_sync_width=%d min_v_blank=%d " "min_v_blank_interlace=%d vstartup_start=%d vupdate_offset=%d vupdate_width=%d " "vready_offset=%d", __entry->lock ? "Lock" : "Unlock", - __entry->function, + __get_str(function), __entry->line, __entry->instance, __entry->opp_count, diff --git a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_helpers_test.c b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_helpers_test.c index 639512bea275..d03a5a61b0cd 100644 --- a/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_helpers_test.c +++ b/drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_helpers_test.c @@ -186,6 +186,22 @@ static void dm_test_apply_edid_quirks_skip_phy_ssc(struct kunit *test) KUNIT_EXPECT_TRUE(test, link->wa_flags.skip_phy_ssc_reduction); } +/** + * dm_test_apply_edid_quirks_force_freesync_min - Test ACR 0x08AF FreeSync min quirk + * @test: The KUnit test context + */ +static void dm_test_apply_edid_quirks_force_freesync_min(struct kunit *test) +{ + struct dc_edid_caps edid_caps = {0}; + struct dc_link *link = dm_test_quirk_link(test); + struct edid *edid = dm_test_edid_with_panel_id(test, + drm_edid_encode_panel_id('A', 'C', 'R', 0x08AF)); + + apply_edid_quirks(link, edid, &edid_caps); + + KUNIT_EXPECT_EQ(test, edid_caps.panel_patch.force_freesync_min_hz, 55U); +} + /** * dm_test_apply_edid_quirks_unknown_noop - Test unknown panel id is a no-op * @test: The KUnit test context @@ -3730,6 +3746,7 @@ static struct kunit_case amdgpu_dm_helpers_test_cases[] = { KUNIT_CASE(dm_test_apply_edid_quirks_remove_sink_ext_caps), KUNIT_CASE(dm_test_apply_edid_quirks_disable_colorimetry), KUNIT_CASE(dm_test_apply_edid_quirks_skip_phy_ssc), + KUNIT_CASE(dm_test_apply_edid_quirks_force_freesync_min), KUNIT_CASE(dm_test_apply_edid_quirks_unknown_noop), /* dm_helpers_parse_edid_caps */ KUNIT_CASE(dm_test_parse_edid_caps_null_edid), diff --git a/drivers/gpu/drm/amd/display/dc/bios/command_table_helper.c b/drivers/gpu/drm/amd/display/dc/bios/command_table_helper.c index 91bc8a06e2cf..ab67771ddab4 100644 --- a/drivers/gpu/drm/amd/display/dc/bios/command_table_helper.c +++ b/drivers/gpu/drm/amd/display/dc/bios/command_table_helper.c @@ -35,7 +35,10 @@ bool dal_bios_parser_init_cmd_tbl_helper( const struct command_table_helper **h, enum dce_version dce) { - switch (dce) { + if (!h) + return false; + + switch (dce) { #if defined(CONFIG_DRM_AMD_DC_SI) case DCE_VERSION_6_0: case DCE_VERSION_6_1: @@ -44,6 +47,7 @@ bool dal_bios_parser_init_cmd_tbl_helper( return true; #endif +#if defined(CONFIG_DRM_AMD_DC_DCE) case DCE_VERSION_8_0: case DCE_VERSION_8_1: case DCE_VERSION_8_3: @@ -62,6 +66,7 @@ bool dal_bios_parser_init_cmd_tbl_helper( case DCE_VERSION_11_22: *h = dal_cmd_tbl_helper_dce112_get_table(); return true; +#endif default: /* Unsupported DCE */ diff --git a/drivers/gpu/drm/amd/display/dc/bios/command_table_helper2.c b/drivers/gpu/drm/amd/display/dc/bios/command_table_helper2.c index 9ae5cf42754a..ea0a270e9de3 100644 --- a/drivers/gpu/drm/amd/display/dc/bios/command_table_helper2.c +++ b/drivers/gpu/drm/amd/display/dc/bios/command_table_helper2.c @@ -45,6 +45,7 @@ bool dal_bios_parser_init_cmd_tbl_helper2( return true; #endif +#if defined(CONFIG_DRM_AMD_DC_DCE) case DCE_VERSION_8_0: case DCE_VERSION_8_1: case DCE_VERSION_8_3: @@ -58,6 +59,7 @@ bool dal_bios_parser_init_cmd_tbl_helper2( case DCE_VERSION_11_0: *h = dal_cmd_tbl_helper_dce110_get_table(); return true; +#endif case DCE_VERSION_11_2: case DCE_VERSION_11_22: diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/Makefile b/drivers/gpu/drm/amd/display/dc/clk_mgr/Makefile index 8cfd7bf57fbe..c803a2bdf749 100644 --- a/drivers/gpu/drm/amd/display/dc/clk_mgr/Makefile +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/Makefile @@ -29,6 +29,7 @@ AMD_DAL_CLK_MGR = $(addprefix $(AMDDALPATH)/dc/clk_mgr/,$(CLK_MGR)) AMD_DISPLAY_FILES += $(AMD_DAL_CLK_MGR) +ifdef CONFIG_DRM_AMD_DC_DCE ############################################################################### # DCE 100 and DCE8x ############################################################################### @@ -62,6 +63,13 @@ CLK_MGR_DCE120 = dce120_clk_mgr.o AMD_DAL_CLK_MGR_DCE120 = $(addprefix $(AMDDALPATH)/dc/clk_mgr/dce120/,$(CLK_MGR_DCE120)) AMD_DISPLAY_FILES += $(AMD_DAL_CLK_MGR_DCE120) +endif # CONFIG_DRM_AMD_DC_DCE + +# Shared clock helpers used by both the DCE and DCN clock managers. Built +# unconditionally (not gated on CONFIG_DRM_AMD_DC_FP) so non-FP configs that +# still build the DCE clock managers can resolve them. +AMD_DISPLAY_FILES += $(AMDDALPATH)/dc/clk_mgr/dcn10/dcn10_clk_mgr.o + ifdef CONFIG_DRM_AMD_DC_FP ############################################################################### # DCN10 diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/clk_mgr.c b/drivers/gpu/drm/amd/display/dc/clk_mgr/clk_mgr.c index bf80eaf23e9a..7f24433a42c1 100644 --- a/drivers/gpu/drm/amd/display/dc/clk_mgr/clk_mgr.c +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/clk_mgr.c @@ -30,10 +30,12 @@ #include "dc_state_priv.h" #include "link_service.h" +#if defined(CONFIG_DRM_AMD_DC_DCE) #include "dce100/dce_clk_mgr.h" #include "dce110/dce110_clk_mgr.h" #include "dce112/dce112_clk_mgr.h" #include "dce120/dce120_clk_mgr.h" +#endif #include "dcn10/rv1_clk_mgr.h" #include "dcn10/rv2_clk_mgr.h" #include "dcn20/dcn20_clk_mgr.h" @@ -152,6 +154,7 @@ struct clk_mgr *dc_clk_mgr_create(struct dc_context *ctx, struct pp_smu_funcs *p struct hw_asic_id asic_id = ctx->asic_id; switch (asic_id.chip_family) { +#if defined(CONFIG_DRM_AMD_DC_DCE) case FAMILY_SI: case FAMILY_CI: case FAMILY_KV: { @@ -211,6 +214,7 @@ struct clk_mgr *dc_clk_mgr_create(struct dc_context *ctx, struct pp_smu_funcs *p dce120_clk_mgr_construct(ctx, clk_mgr); return &clk_mgr->base; } +#endif #if defined(CONFIG_DRM_AMD_DC_FP) case FAMILY_RV: { struct clk_mgr_internal *clk_mgr = kzalloc_obj(*clk_mgr); diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/dce100/dce_clk_mgr.c b/drivers/gpu/drm/amd/display/dc/clk_mgr/dce100/dce_clk_mgr.c index d891b3bfe2a1..42e6d6538825 100644 --- a/drivers/gpu/drm/amd/display/dc/clk_mgr/dce100/dce_clk_mgr.c +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/dce100/dce_clk_mgr.c @@ -62,56 +62,6 @@ static const struct clk_mgr_mask disp_clk_mask = { CLK_COMMON_MASK_SH_LIST_DCE_COMMON_BASE(_MASK) }; -unsigned int dentist_get_divider_from_did(unsigned int did) -{ - if (did < DENTIST_BASE_DID_1) - did = DENTIST_BASE_DID_1; - if (did > DENTIST_MAX_DID) - did = DENTIST_MAX_DID; - - if (did < DENTIST_BASE_DID_2) { - return DENTIST_DIVIDER_RANGE_1_START + DENTIST_DIVIDER_RANGE_1_STEP - * (did - DENTIST_BASE_DID_1); - } else if (did < DENTIST_BASE_DID_3) { - return DENTIST_DIVIDER_RANGE_2_START + DENTIST_DIVIDER_RANGE_2_STEP - * (did - DENTIST_BASE_DID_2); - } else if (did < DENTIST_BASE_DID_4) { - return DENTIST_DIVIDER_RANGE_3_START + DENTIST_DIVIDER_RANGE_3_STEP - * (did - DENTIST_BASE_DID_3); - } else { - return DENTIST_DIVIDER_RANGE_4_START + DENTIST_DIVIDER_RANGE_4_STEP - * (did - DENTIST_BASE_DID_4); - } -} - -/* SW will adjust DP REF Clock average value for all purposes - * (DP DTO / DP Audio DTO and DP GTC) - if clock is spread for all cases: - -if SS enabled on DP Ref clock and HW de-spreading enabled with SW - calculations for DS_INCR/DS_MODULO (this is planned to be default case) - -if SS enabled on DP Ref clock and HW de-spreading enabled with HW - calculations (not planned to be used, but average clock should still - be valid) - -if SS enabled on DP Ref clock and HW de-spreading disabled - (should not be case with CIK) then SW should program all rates - generated according to average value (case as with previous ASICs) - */ - -int dce_adjust_dp_ref_freq_for_ss(struct clk_mgr_internal *clk_mgr_dce, int dp_ref_clk_khz) -{ - if (clk_mgr_dce->ss_on_dprefclk && clk_mgr_dce->dprefclk_ss_divider != 0) { - struct fixed31_32 ss_percentage = dc_fixpt_div_int( - dc_fixpt_from_fraction(clk_mgr_dce->dprefclk_ss_percentage, - clk_mgr_dce->dprefclk_ss_divider), 200); - struct fixed31_32 adj_dp_ref_clk_khz; - - ss_percentage = dc_fixpt_sub(dc_fixpt_one, ss_percentage); - adj_dp_ref_clk_khz = dc_fixpt_mul_int(ss_percentage, dp_ref_clk_khz); - dp_ref_clk_khz = dc_fixpt_floor(adj_dp_ref_clk_khz); - } - return dp_ref_clk_khz; -} - static int dce60_get_dp_ref_freq_khz(struct clk_mgr *clk_mgr_base) { struct clk_mgr_internal *clk_mgr = TO_CLK_MGR_INTERNAL(clk_mgr_base); @@ -155,13 +105,6 @@ int dce_get_dp_ref_freq_khz(struct clk_mgr *clk_mgr_base) return dce_adjust_dp_ref_freq_for_ss(clk_mgr, dp_ref_clk_khz); } -int dce12_get_dp_ref_freq_khz(struct clk_mgr *clk_mgr_base) -{ - struct clk_mgr_internal *clk_mgr_dce = TO_CLK_MGR_INTERNAL(clk_mgr_base); - - return dce_adjust_dp_ref_freq_for_ss(clk_mgr_dce, clk_mgr_base->dprefclk_khz); -} - /* unit: in_khz before mode set, get pixel clock from context. ASIC register * may not be programmed yet */ @@ -256,64 +199,6 @@ static void dce_clock_read_integrated_info(struct clk_mgr_internal *clk_mgr_dce) clk_mgr_dce->dfs_bypass_enabled = true; } -void dce_clock_read_ss_info(struct clk_mgr_internal *clk_mgr_dce) -{ - struct dc_bios *bp = clk_mgr_dce->base.ctx->dc_bios; - int ss_info_num = bp->funcs->get_ss_entry_number( - bp, AS_SIGNAL_TYPE_GPU_PLL); - - if (ss_info_num) { - struct spread_spectrum_info info = { { 0 } }; - enum bp_result result = bp->funcs->get_spread_spectrum_info( - bp, AS_SIGNAL_TYPE_GPU_PLL, 0, &info); - - /* Based on VBIOS, VBIOS will keep entry for GPU PLL SS - * even if SS not enabled and in that case - * SSInfo.spreadSpectrumPercentage !=0 would be sign - * that SS is enabled - */ - if (result == BP_RESULT_OK && - info.spread_spectrum_percentage != 0) { - clk_mgr_dce->ss_on_dprefclk = true; - clk_mgr_dce->dprefclk_ss_divider = info.spread_percentage_divider; - - if (info.type.CENTER_MODE == 0) { - /* TODO: Currently for DP Reference clock we - * need only SS percentage for - * downspread */ - clk_mgr_dce->dprefclk_ss_percentage = - info.spread_spectrum_percentage; - } - - return; - } - - result = bp->funcs->get_spread_spectrum_info( - bp, AS_SIGNAL_TYPE_DISPLAY_PORT, 0, &info); - - /* Based on VBIOS, VBIOS will keep entry for DPREFCLK SS - * even if SS not enabled and in that case - * SSInfo.spreadSpectrumPercentage !=0 would be sign - * that SS is enabled - */ - if (result == BP_RESULT_OK && - info.spread_spectrum_percentage != 0) { - clk_mgr_dce->ss_on_dprefclk = true; - clk_mgr_dce->dprefclk_ss_divider = info.spread_percentage_divider; - - if (info.type.CENTER_MODE == 0) { - /* Currently for DP Reference clock we - * need only SS percentage for - * downspread */ - clk_mgr_dce->dprefclk_ss_percentage = - info.spread_spectrum_percentage; - } - if (clk_mgr_dce->base.ctx->dc->config.ignore_dpref_ss) - clk_mgr_dce->dprefclk_ss_percentage = 0; - } - } -} - static void dce_pplib_apply_display_requirements( struct dc *dc, struct dc_state *context) diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/dce100/dce_clk_mgr.h b/drivers/gpu/drm/amd/display/dc/clk_mgr/dce100/dce_clk_mgr.h index e1c6a92d7957..2f4165f1a7bc 100644 --- a/drivers/gpu/drm/amd/display/dc/clk_mgr/dce100/dce_clk_mgr.h +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/dce100/dce_clk_mgr.h @@ -28,9 +28,9 @@ #define _DCE_CLK_MGR_H_ #include "dc.h" +#include "dcn10/dcn10_clk_mgr.h" /* functions shared by other dce clk mgrs */ -int dce_adjust_dp_ref_freq_for_ss(struct clk_mgr_internal *clk_mgr_dce, int dp_ref_clk_khz); int dce_get_dp_ref_freq_khz(struct clk_mgr *clk_mgr_base); uint32_t dce_get_max_pixel_clock_for_all_paths(struct dc_state *context); @@ -40,10 +40,6 @@ void dce_clk_mgr_construct( struct dc_context *ctx, struct clk_mgr_internal *clk_mgr_dce); -void dce_clock_read_ss_info(struct clk_mgr_internal *dccg_dce); - -int dce12_get_dp_ref_freq_khz(struct clk_mgr *dccg); - int dce_set_clock( struct clk_mgr *clk_mgr_base, int requested_clk_khz); @@ -51,6 +47,4 @@ int dce_set_clock( void dce_clk_mgr_destroy(struct clk_mgr **clk_mgr); -unsigned int dentist_get_divider_from_did(unsigned int did); - #endif /* _DCE_CLK_MGR_H_ */ diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/dce112/dce112_clk_mgr.c b/drivers/gpu/drm/amd/display/dc/clk_mgr/dce112/dce112_clk_mgr.c index 08ed6f88025f..2157761c3b4b 100644 --- a/drivers/gpu/drm/amd/display/dc/clk_mgr/dce112/dce112_clk_mgr.c +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/dce112/dce112_clk_mgr.c @@ -101,65 +101,6 @@ int dce112_set_clock(struct clk_mgr *clk_mgr_base, int requested_clk_khz) return actual_clock; } -int dce112_set_dispclk(struct clk_mgr_internal *clk_mgr, int requested_clk_khz) -{ - struct bp_set_dce_clock_parameters dce_clk_params; - struct dc_bios *bp = clk_mgr->base.ctx->dc_bios; - struct dc *dc = clk_mgr->base.ctx->dc; - struct dmcu *dmcu = dc->res_pool->dmcu; - int actual_clock = requested_clk_khz; - /* Prepare to program display clock*/ - memset(&dce_clk_params, 0, sizeof(dce_clk_params)); - - /* Make sure requested clock isn't lower than minimum threshold*/ - if (requested_clk_khz > 0) - requested_clk_khz = max(requested_clk_khz, - clk_mgr->base.dentist_vco_freq_khz / 62); - - dce_clk_params.target_clock_frequency = requested_clk_khz; - dce_clk_params.pll_id = CLOCK_SOURCE_ID_DFS; - dce_clk_params.clock_type = DCECLOCK_TYPE_DISPLAY_CLOCK; - - bp->funcs->set_dce_clock(bp, &dce_clk_params); - actual_clock = dce_clk_params.target_clock_frequency; - - if (dmcu && dmcu->funcs->is_dmcu_initialized(dmcu)) { - if (clk_mgr->dfs_bypass_disp_clk != actual_clock) - dmcu->funcs->set_psr_wait_loop(dmcu, - actual_clock / 1000 / 7); - } - - clk_mgr->dfs_bypass_disp_clk = actual_clock; - return actual_clock; - -} - -int dce112_set_dprefclk(struct clk_mgr_internal *clk_mgr) -{ - struct bp_set_dce_clock_parameters dce_clk_params; - struct dc_bios *bp = clk_mgr->base.ctx->dc_bios; - - memset(&dce_clk_params, 0, sizeof(dce_clk_params)); - - /*Program DP ref Clock*/ - /*VBIOS will determine DPREFCLK frequency, so we don't set it*/ - dce_clk_params.target_clock_frequency = 0; - dce_clk_params.pll_id = CLOCK_SOURCE_ID_DFS; - dce_clk_params.clock_type = DCECLOCK_TYPE_DPREFCLK; - if (!((clk_mgr->base.ctx->asic_id.chip_family == FAMILY_AI) && - ASICREV_IS_VEGA20_P(clk_mgr->base.ctx->asic_id.hw_internal_rev))) - dce_clk_params.flags.USE_GENLOCK_AS_SOURCE_FOR_DPREFCLK = - (dce_clk_params.pll_id == - CLOCK_SOURCE_COMBO_DISPLAY_PLL0); - else - dce_clk_params.flags.USE_GENLOCK_AS_SOURCE_FOR_DPREFCLK = false; - - bp->funcs->set_dce_clock(bp, &dce_clk_params); - - /* Returns the dp_refclk that was set */ - return dce_clk_params.target_clock_frequency; -} - static void dce112_update_clocks(struct clk_mgr *clk_mgr_base, struct dc_state *context, bool safe_to_lower) diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/dce112/dce112_clk_mgr.h b/drivers/gpu/drm/amd/display/dc/clk_mgr/dce112/dce112_clk_mgr.h index dfb06db118e1..766b73c19365 100644 --- a/drivers/gpu/drm/amd/display/dc/clk_mgr/dce112/dce112_clk_mgr.h +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/dce112/dce112_clk_mgr.h @@ -26,6 +26,8 @@ #ifndef DAL_DC_DCE_DCE112_CLK_MGR_H_ #define DAL_DC_DCE_DCE112_CLK_MGR_H_ +/* dce112_set_dispclk and dce112_set_dprefclk are declared here. */ +#include "dcn10/dcn10_clk_mgr.h" void dce112_clk_mgr_construct( struct dc_context *ctx, @@ -33,7 +35,5 @@ void dce112_clk_mgr_construct( /* functions shared with other clk mgr */ int dce112_set_clock(struct clk_mgr *clk_mgr_base, int requested_clk_khz); -int dce112_set_dispclk(struct clk_mgr_internal *clk_mgr, int requested_clk_khz); -int dce112_set_dprefclk(struct clk_mgr_internal *clk_mgr); #endif /* DAL_DC_DCE_DCE112_CLK_MGR_H_ */ diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn10/dcn10_clk_mgr.c b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn10/dcn10_clk_mgr.c new file mode 100644 index 000000000000..75d5c90e7707 --- /dev/null +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn10/dcn10_clk_mgr.c @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: MIT +// +// Copyright 2026 Advanced Micro Devices, Inc. + +#include "clk_mgr_internal.h" +#include "core_types.h" +#include "dal_asic_id.h" +#include "dcn10_clk_mgr.h" + +unsigned int dentist_get_divider_from_did(unsigned int did) +{ + if (did < DENTIST_BASE_DID_1) + did = DENTIST_BASE_DID_1; + if (did > DENTIST_MAX_DID) + did = DENTIST_MAX_DID; + + if (did < DENTIST_BASE_DID_2) { + return DENTIST_DIVIDER_RANGE_1_START + DENTIST_DIVIDER_RANGE_1_STEP + * (did - DENTIST_BASE_DID_1); + } else if (did < DENTIST_BASE_DID_3) { + return DENTIST_DIVIDER_RANGE_2_START + DENTIST_DIVIDER_RANGE_2_STEP + * (did - DENTIST_BASE_DID_2); + } else if (did < DENTIST_BASE_DID_4) { + return DENTIST_DIVIDER_RANGE_3_START + DENTIST_DIVIDER_RANGE_3_STEP + * (did - DENTIST_BASE_DID_3); + } else { + return DENTIST_DIVIDER_RANGE_4_START + DENTIST_DIVIDER_RANGE_4_STEP + * (did - DENTIST_BASE_DID_4); + } +} + +/* SW will adjust DP REF Clock average value for all purposes + * (DP DTO / DP Audio DTO and DP GTC) + if clock is spread for all cases: + -if SS enabled on DP Ref clock and HW de-spreading enabled with SW + calculations for DS_INCR/DS_MODULO (this is planned to be default case) + -if SS enabled on DP Ref clock and HW de-spreading enabled with HW + calculations (not planned to be used, but average clock should still + be valid) + -if SS enabled on DP Ref clock and HW de-spreading disabled + (should not be case with CIK) then SW should program all rates + generated according to average value (case as with previous ASICs) + */ +int dce_adjust_dp_ref_freq_for_ss(struct clk_mgr_internal *clk_mgr_dce, int dp_ref_clk_khz) +{ + if (clk_mgr_dce->ss_on_dprefclk && clk_mgr_dce->dprefclk_ss_divider != 0) { + struct fixed31_32 ss_percentage = dc_fixpt_div_int( + dc_fixpt_from_fraction(clk_mgr_dce->dprefclk_ss_percentage, + clk_mgr_dce->dprefclk_ss_divider), 200); + struct fixed31_32 adj_dp_ref_clk_khz; + + ss_percentage = dc_fixpt_sub(dc_fixpt_one, ss_percentage); + adj_dp_ref_clk_khz = dc_fixpt_mul_int(ss_percentage, dp_ref_clk_khz); + dp_ref_clk_khz = dc_fixpt_floor(adj_dp_ref_clk_khz); + } + return dp_ref_clk_khz; +} + +int dce12_get_dp_ref_freq_khz(struct clk_mgr *clk_mgr_base) +{ + struct clk_mgr_internal *clk_mgr_dce = TO_CLK_MGR_INTERNAL(clk_mgr_base); + + return dce_adjust_dp_ref_freq_for_ss(clk_mgr_dce, clk_mgr_base->dprefclk_khz); +} + +void dce_clock_read_ss_info(struct clk_mgr_internal *clk_mgr_dce) +{ + struct dc_bios *bp = clk_mgr_dce->base.ctx->dc_bios; + int ss_info_num = bp->funcs->get_ss_entry_number( + bp, AS_SIGNAL_TYPE_GPU_PLL); + + if (ss_info_num) { + struct spread_spectrum_info info = { { 0 } }; + enum bp_result result = bp->funcs->get_spread_spectrum_info( + bp, AS_SIGNAL_TYPE_GPU_PLL, 0, &info); + + /* Based on VBIOS, VBIOS will keep entry for GPU PLL SS + * even if SS not enabled and in that case + * SSInfo.spreadSpectrumPercentage !=0 would be sign + * that SS is enabled + */ + if (result == BP_RESULT_OK && + info.spread_spectrum_percentage != 0) { + clk_mgr_dce->ss_on_dprefclk = true; + clk_mgr_dce->dprefclk_ss_divider = info.spread_percentage_divider; + + if (info.type.CENTER_MODE == 0) { + /* TODO: Currently for DP Reference clock we + * need only SS percentage for + * downspread */ + clk_mgr_dce->dprefclk_ss_percentage = + info.spread_spectrum_percentage; + } + + return; + } + + result = bp->funcs->get_spread_spectrum_info( + bp, AS_SIGNAL_TYPE_DISPLAY_PORT, 0, &info); + + /* Based on VBIOS, VBIOS will keep entry for DPREFCLK SS + * even if SS not enabled and in that case + * SSInfo.spreadSpectrumPercentage !=0 would be sign + * that SS is enabled + */ + if (result == BP_RESULT_OK && + info.spread_spectrum_percentage != 0) { + clk_mgr_dce->ss_on_dprefclk = true; + clk_mgr_dce->dprefclk_ss_divider = info.spread_percentage_divider; + + if (info.type.CENTER_MODE == 0) { + /* Currently for DP Reference clock we + * need only SS percentage for + * downspread */ + clk_mgr_dce->dprefclk_ss_percentage = + info.spread_spectrum_percentage; + } + if (clk_mgr_dce->base.ctx->dc->config.ignore_dpref_ss) + clk_mgr_dce->dprefclk_ss_percentage = 0; + } + } +} + +int dce112_set_dispclk(struct clk_mgr_internal *clk_mgr, int requested_clk_khz) +{ + struct bp_set_dce_clock_parameters dce_clk_params; + struct dc_bios *bp = clk_mgr->base.ctx->dc_bios; + struct dc *dc = clk_mgr->base.ctx->dc; + struct dmcu *dmcu = dc->res_pool->dmcu; + int actual_clock; + /* Prepare to program display clock*/ + memset(&dce_clk_params, 0, sizeof(dce_clk_params)); + + /* Make sure requested clock isn't lower than minimum threshold*/ + if (requested_clk_khz > 0) + requested_clk_khz = max(requested_clk_khz, + clk_mgr->base.dentist_vco_freq_khz / 62); + + dce_clk_params.target_clock_frequency = requested_clk_khz; + dce_clk_params.pll_id = CLOCK_SOURCE_ID_DFS; + dce_clk_params.clock_type = DCECLOCK_TYPE_DISPLAY_CLOCK; + + bp->funcs->set_dce_clock(bp, &dce_clk_params); + actual_clock = dce_clk_params.target_clock_frequency; + + if (dmcu && dmcu->funcs->is_dmcu_initialized(dmcu)) { + if (clk_mgr->dfs_bypass_disp_clk != actual_clock) + dmcu->funcs->set_psr_wait_loop(dmcu, + actual_clock / 1000 / 7); + } + + clk_mgr->dfs_bypass_disp_clk = actual_clock; + return actual_clock; + +} + +int dce112_set_dprefclk(struct clk_mgr_internal *clk_mgr) +{ + struct bp_set_dce_clock_parameters dce_clk_params; + struct dc_bios *bp = clk_mgr->base.ctx->dc_bios; + + memset(&dce_clk_params, 0, sizeof(dce_clk_params)); + + /*Program DP ref Clock*/ + /*VBIOS will determine DPREFCLK frequency, so we don't set it*/ + dce_clk_params.target_clock_frequency = 0; + dce_clk_params.pll_id = CLOCK_SOURCE_ID_DFS; + dce_clk_params.clock_type = DCECLOCK_TYPE_DPREFCLK; + if (!((clk_mgr->base.ctx->asic_id.chip_family == FAMILY_AI) && + ASICREV_IS_VEGA20_P(clk_mgr->base.ctx->asic_id.hw_internal_rev))) + dce_clk_params.flags.USE_GENLOCK_AS_SOURCE_FOR_DPREFCLK = + (dce_clk_params.pll_id == + CLOCK_SOURCE_COMBO_DISPLAY_PLL0); + else + dce_clk_params.flags.USE_GENLOCK_AS_SOURCE_FOR_DPREFCLK = false; + + bp->funcs->set_dce_clock(bp, &dce_clk_params); + + /* Returns the dp_refclk that was set */ + return dce_clk_params.target_clock_frequency; +} diff --git a/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn10/dcn10_clk_mgr.h b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn10/dcn10_clk_mgr.h new file mode 100644 index 000000000000..e27486db4b62 --- /dev/null +++ b/drivers/gpu/drm/amd/display/dc/clk_mgr/dcn10/dcn10_clk_mgr.h @@ -0,0 +1,29 @@ +/* + * SPDX-License-Identifier: MIT + * + * Copyright 2026 Advanced Micro Devices, Inc. + */ + +#ifndef __DCN10_CLK_MGR_H__ +#define __DCN10_CLK_MGR_H__ + +#include "dc.h" + +struct clk_mgr_internal; + +/* + * Shared clock helpers referenced by both the DCE and DCN clock managers. + */ +int dce_adjust_dp_ref_freq_for_ss(struct clk_mgr_internal *clk_mgr_dce, int dp_ref_clk_khz); + +void dce_clock_read_ss_info(struct clk_mgr_internal *clk_mgr_dce); + +int dce12_get_dp_ref_freq_khz(struct clk_mgr *clk_mgr_base); + +unsigned int dentist_get_divider_from_did(unsigned int did); + +int dce112_set_dispclk(struct clk_mgr_internal *clk_mgr, int requested_clk_khz); + +int dce112_set_dprefclk(struct clk_mgr_internal *clk_mgr); + +#endif /* __DCN10_CLK_MGR_H__ */ diff --git a/drivers/gpu/drm/amd/display/dc/core/dc.c b/drivers/gpu/drm/amd/display/dc/core/dc.c index 60b903edff2f..2b6ed83021f1 100644 --- a/drivers/gpu/drm/amd/display/dc/core/dc.c +++ b/drivers/gpu/drm/amd/display/dc/core/dc.c @@ -4973,9 +4973,7 @@ static void commit_planes_for_stream(struct dc *dc, top_pipe_to_program->stream_res.tg); } - if (dc->hwss.wait_for_dcc_meta_propagation) { - dc->hwss.wait_for_dcc_meta_propagation(dc, top_pipe_to_program); - } + hwss_hubp_wait_for_dcc_meta_prop(dc, top_pipe_to_program); if (dc->hwseq->funcs.wait_for_pipe_update_if_needed) dc->hwseq->funcs.wait_for_pipe_update_if_needed(dc, top_pipe_to_program, update_type < UPDATE_TYPE_FULL); diff --git a/drivers/gpu/drm/amd/display/dc/core/dc_hw_sequencer.c b/drivers/gpu/drm/amd/display/dc/core/dc_hw_sequencer.c index d4dbdf7d0506..c98055364b8e 100644 --- a/drivers/gpu/drm/amd/display/dc/core/dc_hw_sequencer.c +++ b/drivers/gpu/drm/amd/display/dc/core/dc_hw_sequencer.c @@ -1119,6 +1119,22 @@ void hwss_build_post_unlock_full_sequence(struct dc *dc, } } +static uint32_t get_dcc_meta_propagation_delay(struct dc *dc, struct pipe_ctx *pipe_ctx) +{ + /* check if any surfaces are updating address while using flip immediate and dcc */ + while (pipe_ctx != NULL) { + if (pipe_ctx->plane_state && + pipe_ctx->plane_state->dcc.enable && + pipe_ctx->plane_state->flip_immediate && + pipe_ctx->plane_state->update_bits.addr_update) { + return dc->debug.dcc_meta_propagation_delay_us; + } + /* check next pipe */ + pipe_ctx = pipe_ctx->bottom_pipe; + } + return 0; +} + void hwss_build_fast_sequence(struct dc *dc, struct dc_dmub_cmd *dc_dmub_cmd, unsigned int dmub_cmd_count, @@ -1142,8 +1158,7 @@ void hwss_build_fast_sequence(struct dc *dc, return; if (dc->hwss.wait_for_dcc_meta_propagation) { - block_sequence[*num_steps].params.wait_for_dcc_meta_propagation_params.dc = dc; - block_sequence[*num_steps].params.wait_for_dcc_meta_propagation_params.top_pipe_to_program = pipe_ctx; + block_sequence[*num_steps].params.wait_for_dcc_meta_propagation_params.delay = get_dcc_meta_propagation_delay(dc, pipe_ctx); block_sequence[*num_steps].func = HUBP_WAIT_FOR_DCC_META_PROP; (*num_steps)++; } @@ -1459,9 +1474,22 @@ void hwss_build_fast_sequence(struct dc *dc, (*num_steps)++; } if (hws->funcs.set_input_transfer_func && current_mpc_pipe->plane_state->update_bits.gamma_change) { - block_sequence[*num_steps].params.set_input_transfer_func_params.dc = dc; - block_sequence[*num_steps].params.set_input_transfer_func_params.pipe_ctx = current_mpc_pipe; - block_sequence[*num_steps].params.set_input_transfer_func_params.plane_state = current_mpc_pipe->plane_state; + struct pipe_ctx *primary_dpp_pipe = + resource_get_primary_dpp_pipe(current_mpc_pipe); + + block_sequence[*num_steps].params.set_input_transfer_func_params = + (struct set_input_transfer_func_params) { + .dc = dc, + .dpp = current_mpc_pipe->plane_res.dpp, + .hubp = current_mpc_pipe->plane_res.hubp, + .primary_hubp = primary_dpp_pipe ? + primary_dpp_pipe->plane_res.hubp : current_mpc_pipe->plane_res.hubp, + .ipp = current_mpc_pipe->plane_res.ipp, + .mpc = dc->res_pool->mpc, + .mpcc_id = current_mpc_pipe->plane_res.mpcc_inst, + .stream = current_mpc_pipe->stream, + .plane_state = current_mpc_pipe->plane_state, + }; block_sequence[*num_steps].func = DPP_SET_INPUT_TRANSFER_FUNC; (*num_steps)++; } @@ -1662,9 +1690,7 @@ void hwss_execute_sequence(struct dc *dc, params->update_plane_addr_params.pipe_ctx); break; case DPP_SET_INPUT_TRANSFER_FUNC: - hws->funcs.set_input_transfer_func(params->set_input_transfer_func_params.dc, - params->set_input_transfer_func_params.pipe_ctx, - params->set_input_transfer_func_params.plane_state); + hws->funcs.set_input_transfer_func(¶ms->set_input_transfer_func_params); break; case DPP_PROGRAM_GAMUT_REMAP: if (dc->hwss.program_gamut_remap) @@ -1721,9 +1747,7 @@ void hwss_execute_sequence(struct dc *dc, hwss_subvp_save_surf_addr(params); break; case HUBP_WAIT_FOR_DCC_META_PROP: - dc->hwss.wait_for_dcc_meta_propagation( - params->wait_for_dcc_meta_propagation_params.dc, - params->wait_for_dcc_meta_propagation_params.top_pipe_to_program); + dc->hwss.wait_for_dcc_meta_propagation(params->wait_for_dcc_meta_propagation_params.delay); break; case DMUB_HW_CONTROL_LOCK_FAST: dc->hwss.dmub_hw_control_lock_fast(params); @@ -2233,15 +2257,25 @@ void hwss_add_hubp_update_plane_addr(struct block_sequence_state *seq_state, /* * Helper function to add DPP set input transfer function to block sequence */ -void hwss_add_dpp_set_input_transfer_func(struct block_sequence_state *seq_state, - struct dc *dc, - struct pipe_ctx *pipe_ctx, - struct dc_plane_state *plane_state) +void hwss_add_dpp_set_input_transfer_func(struct block_sequence_state *seq_state, struct dc *dc, + struct pipe_ctx *pipe_ctx) { if (*seq_state->num_steps < MAX_HWSS_BLOCK_SEQUENCE_SIZE) { - seq_state->steps[*seq_state->num_steps].params.set_input_transfer_func_params.dc = dc; - seq_state->steps[*seq_state->num_steps].params.set_input_transfer_func_params.pipe_ctx = pipe_ctx; - seq_state->steps[*seq_state->num_steps].params.set_input_transfer_func_params.plane_state = plane_state; + struct pipe_ctx *primary_dpp_pipe = resource_get_primary_dpp_pipe(pipe_ctx); + + seq_state->steps[*seq_state->num_steps].params.set_input_transfer_func_params = + (struct set_input_transfer_func_params) { + .dc = dc, + .dpp = pipe_ctx->plane_res.dpp, + .hubp = pipe_ctx->plane_res.hubp, + .primary_hubp = primary_dpp_pipe ? + primary_dpp_pipe->plane_res.hubp : pipe_ctx->plane_res.hubp, + .ipp = pipe_ctx->plane_res.ipp, + .mpc = dc->res_pool->mpc, + .mpcc_id = pipe_ctx->plane_res.mpcc_inst, + .plane_state = pipe_ctx->plane_state, + .stream = pipe_ctx->stream, + }; seq_state->steps[*seq_state->num_steps].func = DPP_SET_INPUT_TRANSFER_FUNC; (*seq_state->num_steps)++; } @@ -2436,21 +2470,6 @@ void hwss_add_dmub_subvp_save_surf_addr(struct block_sequence_state *seq_state, } } -/* - * Helper function to add HUBP wait for DCC meta propagation to block sequence - */ -void hwss_add_hubp_wait_for_dcc_meta_prop(struct block_sequence_state *seq_state, - struct dc *dc, - struct pipe_ctx *top_pipe_to_program) -{ - if (*seq_state->num_steps < MAX_HWSS_BLOCK_SEQUENCE_SIZE) { - seq_state->steps[*seq_state->num_steps].params.wait_for_dcc_meta_propagation_params.dc = dc; - seq_state->steps[*seq_state->num_steps].params.wait_for_dcc_meta_propagation_params.top_pipe_to_program = top_pipe_to_program; - seq_state->steps[*seq_state->num_steps].func = HUBP_WAIT_FOR_DCC_META_PROP; - (*seq_state->num_steps)++; - } -} - /* * Helper function to add HUBP wait pipe read start to block sequence */ @@ -4528,6 +4547,26 @@ void hwss_disable_audio_stream(struct dc *dc, union block_sequence_params *param params->disable_audio_stream_params.pipe_ctx); } +void hwss_set_input_transfer_func(struct dc *dc, struct pipe_ctx *pipe_ctx) +{ + if (dc->hwseq->funcs.set_input_transfer_func) { + struct pipe_ctx *primary_dpp_pipe = resource_get_primary_dpp_pipe(pipe_ctx); + + dc->hwseq->funcs.set_input_transfer_func(&(struct set_input_transfer_func_params) { + .dc = dc, + .dpp = pipe_ctx->plane_res.dpp, + .hubp = pipe_ctx->plane_res.hubp, + .primary_hubp = primary_dpp_pipe ? + primary_dpp_pipe->plane_res.hubp : pipe_ctx->plane_res.hubp, + .ipp = pipe_ctx->plane_res.ipp, + .mpc = dc->res_pool->mpc, + .mpcc_id = pipe_ctx->plane_res.mpcc_inst, + .plane_state = pipe_ctx->plane_state, + .stream = pipe_ctx->stream, + }); + } +} + void hwss_prepare_bandwidth(struct dc *dc, union block_sequence_params *params) { if (dc && dc->hwss.prepare_bandwidth) @@ -6171,3 +6210,11 @@ void get_refresh_rate_confirm_color(struct pipe_ctx *pipe_ctx, struct tg_color * pipe_ctx->visual_confirm_color.color_b_cb = (uint16_t)color_value; } } + +void hwss_hubp_wait_for_dcc_meta_prop(struct dc *dc, struct pipe_ctx *top_pipe_to_program) +{ + if (dc->hwss.wait_for_dcc_meta_propagation) { + uint32_t delay = get_dcc_meta_propagation_delay(dc, top_pipe_to_program); + dc->hwss.wait_for_dcc_meta_propagation(delay); + } +} diff --git a/drivers/gpu/drm/amd/display/dc/core/dc_resource.c b/drivers/gpu/drm/amd/display/dc/core/dc_resource.c index fc9080f0c093..7fc0facc7cf1 100644 --- a/drivers/gpu/drm/amd/display/dc/core/dc_resource.c +++ b/drivers/gpu/drm/amd/display/dc/core/dc_resource.c @@ -55,11 +55,13 @@ #if defined(CONFIG_DRM_AMD_DC_SI) #include "dce60/dce60_resource.h" #endif +#if defined(CONFIG_DRM_AMD_DC_DCE) #include "dce80/dce80_resource.h" #include "dce100/dce100_resource.h" #include "dce110/dce110_resource.h" #include "dce112/dce112_resource.h" #include "dce120/dce120_resource.h" +#endif #include "dcn10/dcn10_resource.h" #include "dcn20/dcn20_resource.h" #include "dcn21/dcn21_resource.h" @@ -293,6 +295,7 @@ struct resource_pool *dc_create_resource_pool(struct dc *dc, init_data->num_virtual_links, dc); break; #endif +#if defined(CONFIG_DRM_AMD_DC_DCE) case DCE_VERSION_8_0: res_pool = dce80_create_resource_pool( (uint8_t)init_data->num_virtual_links, dc); @@ -324,6 +327,7 @@ struct resource_pool *dc_create_resource_pool(struct dc *dc, res_pool = dce120_create_resource_pool( (uint8_t)init_data->num_virtual_links, dc); break; +#endif #if defined(CONFIG_DRM_AMD_DC_FP) case DCN_VERSION_1_0: @@ -5306,6 +5310,81 @@ void resource_build_info_frame(struct pipe_ctx *pipe_ctx) patch_gamut_packet_checksum(&info->gamut); } +/* + * Physical-clock resource mapping used by the DCE and DCN resource pools. + * Unit tests provide their own stub (see dc_resource_ut_helpers.c). + */ +enum { + CLK_SRC_PLL0 = 0, + CLK_SRC_PLL1, + CLK_SRC_PLL2, + CLK_SRC_PLL3, + CLK_SRC_PLL4, + CLK_SRC_PLL5, +}; + +static struct clock_source *find_matching_pll( + struct resource_context *res_ctx, + const struct resource_pool *pool, + const struct dc_stream_state *const stream) +{ + (void)res_ctx; + switch (stream->link->link_enc->transmitter) { + case TRANSMITTER_UNIPHY_A: + return pool->clock_sources[CLK_SRC_PLL0]; + case TRANSMITTER_UNIPHY_B: + return pool->clock_sources[CLK_SRC_PLL1]; + case TRANSMITTER_UNIPHY_C: + return pool->clock_sources[CLK_SRC_PLL2]; + case TRANSMITTER_UNIPHY_D: + return pool->clock_sources[CLK_SRC_PLL3]; + case TRANSMITTER_UNIPHY_E: + return pool->clock_sources[CLK_SRC_PLL4]; + case TRANSMITTER_UNIPHY_F: + return pool->clock_sources[CLK_SRC_PLL5]; + default: + return NULL; + } +} + +enum dc_status resource_map_phy_clock_resources( + const struct dc *dc, + struct dc_state *context, + struct dc_stream_state *stream) +{ + + /* acquire new resources */ + struct pipe_ctx *pipe_ctx = resource_get_otg_master_for_stream( + &context->res_ctx, stream); + + if (!pipe_ctx) + return DC_ERROR_UNEXPECTED; + + if (dc_is_dp_signal(pipe_ctx->stream->signal) + || dc_is_virtual_signal(pipe_ctx->stream->signal)) + pipe_ctx->clock_source = + dc->res_pool->dp_clock_source; + else if (pipe_ctx->stream->signal == SIGNAL_TYPE_HDMI_FRL) + pipe_ctx->clock_source = + dc->res_pool->dp_clock_source; + else { + if (stream && stream->link && stream->link->link_enc) + pipe_ctx->clock_source = find_matching_pll( + &context->res_ctx, dc->res_pool, + stream); + } + + if (pipe_ctx->clock_source == NULL) + return DC_NO_CLOCK_SOURCE_RESOURCE; + + resource_reference_clock_source( + &context->res_ctx, + dc->res_pool, + pipe_ctx->clock_source); + + return DC_OK; +} + enum dc_status resource_map_clock_resources( const struct dc *dc, struct dc_state *context, diff --git a/drivers/gpu/drm/amd/display/dc/dc_types.h b/drivers/gpu/drm/amd/display/dc/dc_types.h index 7da673111ed9..64b4adee36c4 100644 --- a/drivers/gpu/drm/amd/display/dc/dc_types.h +++ b/drivers/gpu/drm/amd/display/dc/dc_types.h @@ -194,6 +194,7 @@ struct dc_panel_patch { bool oled_optimize_display_on; unsigned int force_mst_blocked_discovery; unsigned int wait_after_dpcd_poweroff_ms; + unsigned int force_freesync_min_hz; }; /** diff --git a/drivers/gpu/drm/amd/display/dc/dce/dce_clock_source.c b/drivers/gpu/drm/amd/display/dc/dce/dce_clock_source.c index 20ccecf23677..f88404a37dea 100644 --- a/drivers/gpu/drm/amd/display/dc/dce/dce_clock_source.c +++ b/drivers/gpu/drm/amd/display/dc/dce/dce_clock_source.c @@ -1232,9 +1232,9 @@ static bool get_dp_dto_frequency_100hz( */ modulo_hz = REG_READ(MODULO[inst]); if (modulo_hz) { - temp = clock_hz * dp_dto_ref_khz * 10; + temp = (unsigned long long)clock_hz * dp_dto_ref_khz * 10; ASSERT(temp <= UINT_MAX * modulo_hz * 100ULL); - *pixel_clk_100hz = div_u64(temp, modulo_hz * 100); + *pixel_clk_100hz = (unsigned int)div_u64(temp, modulo_hz * 100); } else *pixel_clk_100hz = 0; } else { @@ -1293,7 +1293,7 @@ static bool dcn401_get_dp_dto_frequency_100hz(const struct clock_source *clock_s BREAK_TO_DEBUGGER(); *pixel_clk_100hz = 0; } else { - *pixel_clk_100hz = div_u64(temp, 100); + *pixel_clk_100hz = (unsigned int)div_u64(temp, 100); } return true; diff --git a/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/src/dml2_core/dml2_core_dcn6_calcs_dchub.c b/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/src/dml2_core/dml2_core_dcn6_calcs_dchub.c index a4e2f8604650..60e873edf13c 100644 --- a/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/src/dml2_core/dml2_core_dcn6_calcs_dchub.c +++ b/drivers/gpu/drm/amd/display/dc/dml2_0/dml21/src/dml2_core/dml2_core_dcn6_calcs_dchub.c @@ -1252,7 +1252,7 @@ void dcn6_calculate_watermarks_and_dram_speed_change_support( DML_LOG_VERBOSE("DML::%s: k=%u, VActiveLatencyHidingUs = %f\n", __func__, k, p->VActiveLatencyHidingUs[k]); } - for (unsigned int j = 0; j < p->display_cfg->stream_descriptors[p->display_cfg->plane_descriptors[j].stream_index].writeback.active_writebacks_per_stream; ++j) { + for (unsigned int j = 0; j < p->display_cfg->stream_descriptors[p->display_cfg->plane_descriptors[k].stream_index].writeback.active_writebacks_per_stream; ++j) { double byte_per_pixel_luma_in_buffer = 1.0; double buffer_for_luma = (double)p->WritebackInterfaceBufferSize * 1024.0 / 2.0; if (p->display_cfg->stream_descriptors[p->display_cfg->plane_descriptors[k].stream_index].writeback.writeback_stream[j].pixel_format == dml2_444_64) { diff --git a/drivers/gpu/drm/amd/display/dc/gpio/hw_factory.c b/drivers/gpu/drm/amd/display/dc/gpio/hw_factory.c index 3300dbc67f32..368ebcbf3fed 100644 --- a/drivers/gpu/drm/amd/display/dc/gpio/hw_factory.c +++ b/drivers/gpu/drm/amd/display/dc/gpio/hw_factory.c @@ -43,9 +43,11 @@ #if defined(CONFIG_DRM_AMD_DC_SI) #include "dce60/hw_factory_dce60.h" #endif +#if defined(CONFIG_DRM_AMD_DC_DCE) #include "dce80/hw_factory_dce80.h" #include "dce110/hw_factory_dce110.h" #include "dce120/hw_factory_dce120.h" +#endif #include "dcn10/hw_factory_dcn10.h" #include "dcn20/hw_factory_dcn20.h" #include "dcn21/hw_factory_dcn21.h" @@ -71,6 +73,7 @@ bool dal_hw_factory_init( dal_hw_factory_dce60_init(factory); return true; #endif +#if defined(CONFIG_DRM_AMD_DC_DCE) case DCE_VERSION_8_0: case DCE_VERSION_8_1: case DCE_VERSION_8_3: @@ -89,6 +92,7 @@ bool dal_hw_factory_init( case DCE_VERSION_12_1: dal_hw_factory_dce120_init(factory); return true; +#endif case DCN_VERSION_1_0: case DCN_VERSION_1_01: dal_hw_factory_dcn10_init(factory); diff --git a/drivers/gpu/drm/amd/display/dc/gpio/hw_translate.c b/drivers/gpu/drm/amd/display/dc/gpio/hw_translate.c index 5a231f97aee3..46cdc8b1069a 100644 --- a/drivers/gpu/drm/amd/display/dc/gpio/hw_translate.c +++ b/drivers/gpu/drm/amd/display/dc/gpio/hw_translate.c @@ -43,9 +43,11 @@ #if defined(CONFIG_DRM_AMD_DC_SI) #include "dce60/hw_translate_dce60.h" #endif +#if defined(CONFIG_DRM_AMD_DC_DCE) #include "dce80/hw_translate_dce80.h" #include "dce110/hw_translate_dce110.h" #include "dce120/hw_translate_dce120.h" +#endif #include "dcn10/hw_translate_dcn10.h" #include "dcn20/hw_translate_dcn20.h" #include "dcn21/hw_translate_dcn21.h" @@ -75,6 +77,7 @@ bool dal_hw_translate_init( dal_hw_translate_dce60_init(translate); return true; #endif +#if defined(CONFIG_DRM_AMD_DC_DCE) case DCE_VERSION_8_0: case DCE_VERSION_8_1: case DCE_VERSION_8_3: @@ -90,6 +93,7 @@ bool dal_hw_translate_init( case DCE_VERSION_12_1: dal_hw_translate_dce120_init(translate); return true; +#endif case DCN_VERSION_1_0: case DCN_VERSION_1_01: dal_hw_translate_dcn10_init(translate); diff --git a/drivers/gpu/drm/amd/display/dc/hubbub/dcn42/dcn42_hubbub.h b/drivers/gpu/drm/amd/display/dc/hubbub/dcn42/dcn42_hubbub.h index 926ddc156a2b..f74d5690c89d 100644 --- a/drivers/gpu/drm/amd/display/dc/hubbub/dcn42/dcn42_hubbub.h +++ b/drivers/gpu/drm/amd/display/dc/hubbub/dcn42/dcn42_hubbub.h @@ -114,7 +114,12 @@ SR(DCHUBBUB_ARB_ALLOW_SR_EXIT_WATERMARK_Z8_C),\ SR(DCHUBBUB_ARB_ALLOW_SR_ENTER_WATERMARK_Z8_D),\ SR(DCHUBBUB_ARB_ALLOW_SR_EXIT_WATERMARK_Z8_D),\ - SR(DCHUBBUB_ARB_QOS_FORCE) + SR(DCHUBBUB_ARB_QOS_FORCE),\ + SR(DCHUBBUB_TEST_DEBUG_INDEX),\ + SR(DCHUBBUB_TEST_DEBUG_DATA),\ + SR(DCHUBBUB_CTRL_STATUS),\ + SR(DCHUBBUB_TIMEOUT_DETECTION_CTRL1),\ + SR(DCHUBBUB_TIMEOUT_DETECTION_CTRL2)\ #define HUBBUB_MASK_SH_LIST_DCN4_2(mask_sh)\ HUBBUB_MASK_SH_LIST_DCN32(mask_sh), \ diff --git a/drivers/gpu/drm/amd/display/dc/hwss/Makefile b/drivers/gpu/drm/amd/display/dc/hwss/Makefile index 9769ec9a32df..7c2afb773685 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/Makefile +++ b/drivers/gpu/drm/amd/display/dc/hwss/Makefile @@ -36,11 +36,13 @@ endif ############################################################################### +ifdef CONFIG_DRM_AMD_DC_DCE HWSS_DCE80 = dce80_hwseq.o AMD_DAL_HWSS_DCE80 = $(addprefix $(AMDDALPATH)/dc/hwss/dce80/,$(HWSS_DCE80)) AMD_DISPLAY_FILES += $(AMD_DAL_HWSS_DCE80) +endif ############################################################################### @@ -52,11 +54,13 @@ AMD_DISPLAY_FILES += $(AMD_DAL_HWSS_DCE) ############################################################################### +ifdef CONFIG_DRM_AMD_DC_DCE HWSS_DCE100 = dce100_hwseq.o AMD_DAL_HWSS_DCE100 = $(addprefix $(AMDDALPATH)/dc/hwss/dce100/,$(HWSS_DCE100)) AMD_DISPLAY_FILES += $(AMD_DAL_HWSS_DCE100) +endif ############################################################################### @@ -68,6 +72,7 @@ AMD_DISPLAY_FILES += $(AMD_DAL_HWSS_DCE110) ############################################################################### +ifdef CONFIG_DRM_AMD_DC_DCE HWSS_DCE112 = dce112_hwseq.o AMD_DAL_HWSS_DCE112 = $(addprefix $(AMDDALPATH)/dc/hwss/dce112/,$(HWSS_DCE112)) @@ -81,6 +86,7 @@ HWSS_DCE120 = dce120_hwseq.o AMD_DAL_HWSS_DCE120 = $(addprefix $(AMDDALPATH)/dc/hwss/dce120/,$(HWSS_DCE120)) AMD_DISPLAY_FILES += $(AMD_DAL_HWSS_DCE120) +endif ifdef CONFIG_DRM_AMD_DC_FP ############################################################################### diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dce110/dce110_hwseq.c b/drivers/gpu/drm/amd/display/dc/hwss/dce110/dce110_hwseq.c index 328321961fba..f593aae34745 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dce110/dce110_hwseq.c +++ b/drivers/gpu/drm/amd/display/dc/hwss/dce110/dce110_hwseq.c @@ -283,11 +283,10 @@ static void dce110_prescale_params(struct ipp_prescale_params *prescale_params, } static bool -dce110_set_input_transfer_func(struct dc *dc, struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state) +dce110_set_input_transfer_func(struct set_input_transfer_func_params *params) { - (void)dc; - struct input_pixel_processor *ipp = pipe_ctx->plane_res.ipp; + struct input_pixel_processor *ipp = params->ipp; + struct dc_plane_state *plane_state = params->plane_state; const struct dc_transfer_func *tf = NULL; struct ipp_prescale_params prescale_params = { 0 }; bool result = true; @@ -3140,7 +3139,6 @@ static void dce110_program_front_end_for_pipe( struct xfm_grph_csc_adjustment adjust; struct out_csc_color_matrix tbl_entry; unsigned int i; - struct dce_hwseq *hws = dc->hwseq; memset(&tbl_entry, 0, sizeof(tbl_entry)); @@ -3199,7 +3197,7 @@ static void dce110_program_front_end_for_pipe( if (pipe_ctx->plane_state->update_bits.full_update || pipe_ctx->plane_state->update_bits.in_transfer_func_change || pipe_ctx->plane_state->update_bits.gamma_change) - hws->funcs.set_input_transfer_func(dc, pipe_ctx, pipe_ctx->plane_state); + hwss_set_input_transfer_func(dc, pipe_ctx); if (pipe_ctx->plane_state->update_bits.full_update) hwss_set_output_transfer_func(dc, pipe_ctx); @@ -3489,6 +3487,10 @@ void dce110_enable_tmds_link_output(struct dc_link *link, uint32_t pixel_clock) { (void)link_res; + + if (!link->link_enc) + return; + link->link_enc->funcs->enable_tmds_output( link->link_enc, clock_source, @@ -3499,12 +3501,12 @@ void dce110_enable_tmds_link_output(struct dc_link *link, // For dongle Type 2 with no I2C support on board, setup sw mode of Ri/Pj check with proper aux instance if (link->force_to_use_aux) { - if (link->link_enc && link->link_enc->funcs->setup_ri_pj_check_in_sw_or_hw_mode) + if (link->link_enc->funcs->setup_ri_pj_check_in_sw_or_hw_mode) link->link_enc->funcs->setup_ri_pj_check_in_sw_or_hw_mode(link->link_enc, link->aux_hw_inst, true); } else // For HDMI setup hw mode of Ri/Pj check with proper ddc pin instance - if (link->link_enc && link->link_enc->funcs->setup_ri_pj_check_in_sw_or_hw_mode) + if (link->link_enc->funcs->setup_ri_pj_check_in_sw_or_hw_mode) link->link_enc->funcs->setup_ri_pj_check_in_sw_or_hw_mode(link->link_enc, link->ddc_hw_inst, false); } @@ -3682,7 +3684,8 @@ static const struct hwseq_private_funcs dce110_private_funcs = { void dce110_hw_sequencer_construct(struct dc *dc) { - dc->hwss = dce110_funcs; - dc->hwseq->funcs = dce110_private_funcs; + if (IS_ENABLED(CONFIG_DRM_AMD_DC_DCE)) { + dc->hwss = dce110_funcs; + dc->hwseq->funcs = dce110_private_funcs; + } } - diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dce60/dce60_hwseq.c b/drivers/gpu/drm/amd/display/dc/hwss/dce60/dce60_hwseq.c index 221996b348ab..1652e47716a0 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dce60/dce60_hwseq.c +++ b/drivers/gpu/drm/amd/display/dc/hwss/dce60/dce60_hwseq.c @@ -275,7 +275,6 @@ dce60_program_front_end_for_pipe( struct xfm_grph_csc_adjustment adjust; struct out_csc_color_matrix tbl_entry; unsigned int i; - struct dce_hwseq *hws = dc->hwseq; DC_LOGGER_INIT(); memset(&tbl_entry, 0, sizeof(tbl_entry)); @@ -335,7 +334,7 @@ dce60_program_front_end_for_pipe( if (pipe_ctx->plane_state->update_bits.full_update || pipe_ctx->plane_state->update_bits.in_transfer_func_change || pipe_ctx->plane_state->update_bits.gamma_change) - hws->funcs.set_input_transfer_func(dc, pipe_ctx, pipe_ctx->plane_state); + hwss_set_input_transfer_func(dc, pipe_ctx); if (pipe_ctx->plane_state->update_bits.full_update) hwss_set_output_transfer_func(dc, pipe_ctx); diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dcn10/dcn10_hwseq.c b/drivers/gpu/drm/amd/display/dc/hwss/dcn10/dcn10_hwseq.c index 097e4ac2df05..a2322e88494e 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dcn10/dcn10_hwseq.c +++ b/drivers/gpu/drm/amd/display/dc/hwss/dcn10/dcn10_hwseq.c @@ -2076,39 +2076,38 @@ void dcn10_update_plane_addr(const struct dc *dc, struct pipe_ctx *pipe_ctx) pipe_ctx->plane_state->address.grph_stereo.left_addr = addr; } -bool dcn10_set_input_transfer_func(struct dc *dc, struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state) +bool dcn10_set_input_transfer_func(struct set_input_transfer_func_params *params) { - (void)dc; - struct dpp *dpp_base = pipe_ctx->plane_res.dpp; + struct dpp *dpp = params->dpp; + struct dc_plane_state *plane_state = params->plane_state; const struct dc_transfer_func *tf = NULL; bool result = true; - if (dpp_base == NULL) + if (dpp == NULL) return false; tf = &plane_state->in_transfer_func; - if (!dpp_base->ctx->dc->debug.always_use_regamma + if (!dpp->ctx->dc->debug.always_use_regamma && !plane_state->gamma_correction.is_identity && dce_use_lut(plane_state->format)) - dpp_base->funcs->dpp_program_input_lut(dpp_base, &plane_state->gamma_correction); + dpp->funcs->dpp_program_input_lut(dpp, &plane_state->gamma_correction); if (tf->type == TF_TYPE_PREDEFINED) { switch (tf->tf) { case TRANSFER_FUNCTION_SRGB: - dpp_base->funcs->dpp_set_degamma(dpp_base, IPP_DEGAMMA_MODE_HW_sRGB); + dpp->funcs->dpp_set_degamma(dpp, IPP_DEGAMMA_MODE_HW_sRGB); break; case TRANSFER_FUNCTION_BT709: - dpp_base->funcs->dpp_set_degamma(dpp_base, IPP_DEGAMMA_MODE_HW_xvYCC); + dpp->funcs->dpp_set_degamma(dpp, IPP_DEGAMMA_MODE_HW_xvYCC); break; case TRANSFER_FUNCTION_LINEAR: - dpp_base->funcs->dpp_set_degamma(dpp_base, IPP_DEGAMMA_MODE_BYPASS); + dpp->funcs->dpp_set_degamma(dpp, IPP_DEGAMMA_MODE_BYPASS); break; case TRANSFER_FUNCTION_PQ: - dpp_base->funcs->dpp_set_degamma(dpp_base, IPP_DEGAMMA_MODE_USER_PWL); - cm_helper_translate_curve_to_degamma_hw_format(tf, &dpp_base->degamma_params); - dpp_base->funcs->dpp_program_degamma_pwl(dpp_base, &dpp_base->degamma_params); + dpp->funcs->dpp_set_degamma(dpp, IPP_DEGAMMA_MODE_USER_PWL); + cm_helper_translate_curve_to_degamma_hw_format(tf, &dpp->degamma_params); + dpp->funcs->dpp_program_degamma_pwl(dpp, &dpp->degamma_params); result = true; break; default: @@ -2116,12 +2115,12 @@ bool dcn10_set_input_transfer_func(struct dc *dc, struct pipe_ctx *pipe_ctx, break; } } else if (tf->type == TF_TYPE_BYPASS) { - dpp_base->funcs->dpp_set_degamma(dpp_base, IPP_DEGAMMA_MODE_BYPASS); + dpp->funcs->dpp_set_degamma(dpp, IPP_DEGAMMA_MODE_BYPASS); } else { cm_helper_translate_curve_to_degamma_hw_format(tf, - &dpp_base->degamma_params); - dpp_base->funcs->dpp_program_degamma_pwl(dpp_base, - &dpp_base->degamma_params); + &dpp->degamma_params); + dpp->funcs->dpp_program_degamma_pwl(dpp, + &dpp->degamma_params); result = true; } @@ -3296,7 +3295,7 @@ void dcn10_program_pipe( if (pipe_ctx->plane_state->update_bits.full_update || pipe_ctx->plane_state->update_bits.in_transfer_func_change || pipe_ctx->plane_state->update_bits.gamma_change) - hws->funcs.set_input_transfer_func(dc, pipe_ctx, pipe_ctx->plane_state); + hwss_set_input_transfer_func(dc, pipe_ctx); /* dcn10_translate_regamma_to_hw_format takes 750us to finish * only do gamma programming for full update. diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dcn10/dcn10_hwseq.h b/drivers/gpu/drm/amd/display/dc/hwss/dcn10/dcn10_hwseq.h index 2cb674ba54e1..1ff17394d0a7 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dcn10/dcn10_hwseq.h +++ b/drivers/gpu/drm/amd/display/dc/hwss/dcn10/dcn10_hwseq.h @@ -74,8 +74,7 @@ void dcn10_program_output_csc(struct dc *dc, uint16_t *matrix, int opp_id); bool dcn10_set_output_transfer_func(struct set_output_transfer_func_params *params); -bool dcn10_set_input_transfer_func(struct dc *dc, struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state); +bool dcn10_set_input_transfer_func(struct set_input_transfer_func_params *params); void dcn10_update_plane_addr(const struct dc *dc, struct pipe_ctx *pipe_ctx); void dcn10_update_mpcc(struct dc *dc, struct pipe_ctx *pipe_ctx); void dcn10_reset_hw_ctx_wrap( diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dcn20/dcn20_hwseq.c b/drivers/gpu/drm/amd/display/dc/hwss/dcn20/dcn20_hwseq.c index 16bb6f678567..c56279cb9f29 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dcn20/dcn20_hwseq.c +++ b/drivers/gpu/drm/amd/display/dc/hwss/dcn20/dcn20_hwseq.c @@ -1065,9 +1065,8 @@ bool dcn20_set_output_transfer_func(struct set_output_transfer_func_params *otf_ } bool dcn20_set_blend_lut( - struct pipe_ctx *pipe_ctx, const struct dc_plane_state *plane_state) + struct dpp *dpp, struct dc_plane_state *plane_state) { - struct dpp *dpp_base = pipe_ctx->plane_res.dpp; bool result = true; const struct pwl_params *blend_lut = NULL; @@ -1076,18 +1075,17 @@ bool dcn20_set_blend_lut( else if (plane_state->cm.blend_func.type == TF_TYPE_DISTRIBUTED_POINTS) { cm_helper_translate_curve_to_hw_format(plane_state->ctx, &plane_state->cm.blend_func, - &dpp_base->regamma_params, false); - blend_lut = &dpp_base->regamma_params; + &dpp->regamma_params, false); + blend_lut = &dpp->regamma_params; } - result = dpp_base->funcs->dpp_program_blnd_lut(dpp_base, blend_lut); + result = dpp->funcs->dpp_program_blnd_lut(dpp, blend_lut); return result; } bool dcn20_set_shaper_3dlut( - struct pipe_ctx *pipe_ctx, const struct dc_plane_state *plane_state) + struct dpp *dpp, struct dc_plane_state *plane_state) { - struct dpp *dpp_base = pipe_ctx->plane_res.dpp; bool result = true; const struct pwl_params *shaper_lut = NULL; @@ -1096,35 +1094,34 @@ bool dcn20_set_shaper_3dlut( else if (plane_state->cm.shaper_func.type == TF_TYPE_DISTRIBUTED_POINTS) { cm_helper_translate_curve_to_hw_format(plane_state->ctx, &plane_state->cm.shaper_func, - &dpp_base->shaper_params, true); - shaper_lut = &dpp_base->shaper_params; + &dpp->shaper_params, true); + shaper_lut = &dpp->shaper_params; } - result = dpp_base->funcs->dpp_program_shaper_lut(dpp_base, shaper_lut); + dpp->funcs->dpp_program_shaper_lut(dpp, shaper_lut); if (plane_state->cm.lut3d_func.state.bits.initialized == 1) - result = dpp_base->funcs->dpp_program_3dlut(dpp_base, + result = dpp->funcs->dpp_program_3dlut(dpp, &plane_state->cm.lut3d_func.lut_3d); else - result = dpp_base->funcs->dpp_program_3dlut(dpp_base, NULL); + result = dpp->funcs->dpp_program_3dlut(dpp, NULL); return result; } -bool dcn20_set_input_transfer_func(struct dc *dc, - struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state) +bool dcn20_set_input_transfer_func(struct set_input_transfer_func_params *params) { - struct dce_hwseq *hws = dc->hwseq; - struct dpp *dpp_base = pipe_ctx->plane_res.dpp; + struct dpp *dpp = params->dpp; + struct dc_plane_state *plane_state = params->plane_state; + struct dce_hwseq *hws = params->dc->hwseq; const struct dc_transfer_func *tf = NULL; bool result = true; bool use_degamma_ram = false; - if (dpp_base == NULL || plane_state == NULL) + if (dpp == NULL || plane_state == NULL) return false; - hws->funcs.set_shaper_3dlut(pipe_ctx, plane_state); - hws->funcs.set_blend_lut(pipe_ctx, plane_state); + hws->funcs.set_shaper_3dlut(dpp, plane_state); + hws->funcs.set_blend_lut(dpp, plane_state); tf = &plane_state->in_transfer_func; @@ -1133,13 +1130,13 @@ bool dcn20_set_input_transfer_func(struct dc *dc, if (use_degamma_ram == true) { if (tf->type == TF_TYPE_HWPWL) - dpp_base->funcs->dpp_program_degamma_pwl(dpp_base, + dpp->funcs->dpp_program_degamma_pwl(dpp, &tf->pwl); else if (tf->type == TF_TYPE_DISTRIBUTED_POINTS) { cm_helper_translate_curve_to_degamma_hw_format(tf, - &dpp_base->degamma_params); - dpp_base->funcs->dpp_program_degamma_pwl(dpp_base, - &dpp_base->degamma_params); + &dpp->degamma_params); + dpp->funcs->dpp_program_degamma_pwl(dpp, + &dpp->degamma_params); } return true; } @@ -1149,21 +1146,21 @@ bool dcn20_set_input_transfer_func(struct dc *dc, if (tf->type == TF_TYPE_PREDEFINED) { switch (tf->tf) { case TRANSFER_FUNCTION_SRGB: - dpp_base->funcs->dpp_set_degamma(dpp_base, + dpp->funcs->dpp_set_degamma(dpp, IPP_DEGAMMA_MODE_HW_sRGB); break; case TRANSFER_FUNCTION_BT709: - dpp_base->funcs->dpp_set_degamma(dpp_base, + dpp->funcs->dpp_set_degamma(dpp, IPP_DEGAMMA_MODE_HW_xvYCC); break; case TRANSFER_FUNCTION_LINEAR: - dpp_base->funcs->dpp_set_degamma(dpp_base, + dpp->funcs->dpp_set_degamma(dpp, IPP_DEGAMMA_MODE_BYPASS); break; case TRANSFER_FUNCTION_PQ: - dpp_base->funcs->dpp_set_degamma(dpp_base, IPP_DEGAMMA_MODE_USER_PWL); - cm_helper_translate_curve_to_degamma_hw_format(tf, &dpp_base->degamma_params); - dpp_base->funcs->dpp_program_degamma_pwl(dpp_base, &dpp_base->degamma_params); + dpp->funcs->dpp_set_degamma(dpp, IPP_DEGAMMA_MODE_USER_PWL); + cm_helper_translate_curve_to_degamma_hw_format(tf, &dpp->degamma_params); + dpp->funcs->dpp_program_degamma_pwl(dpp, &dpp->degamma_params); result = true; break; default: @@ -1171,7 +1168,7 @@ bool dcn20_set_input_transfer_func(struct dc *dc, break; } } else if (tf->type == TF_TYPE_BYPASS) - dpp_base->funcs->dpp_set_degamma(dpp_base, + dpp->funcs->dpp_set_degamma(dpp, IPP_DEGAMMA_MODE_BYPASS); else { /* @@ -1179,7 +1176,7 @@ bool dcn20_set_input_transfer_func(struct dc *dc, * fix is required for this use case */ BREAK_TO_DEBUGGER(); - dpp_base->funcs->dpp_set_degamma(dpp_base, + dpp->funcs->dpp_set_degamma(dpp, IPP_DEGAMMA_MODE_BYPASS); } @@ -1987,7 +1984,7 @@ static void dcn20_program_pipe( pipe_ctx->plane_state->update_bits.gamma_change || pipe_ctx->plane_state->update_bits.lut_3d || pipe_ctx->update_flags.bits.enable)) - hws->funcs.set_input_transfer_func(dc, pipe_ctx, pipe_ctx->plane_state); + hwss_set_input_transfer_func(dc, pipe_ctx); /* dcn10_translate_regamma_to_hw_format takes 750us to finish * only do gamma programming for powering on, internal memcmp to avoid diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dcn20/dcn20_hwseq.h b/drivers/gpu/drm/amd/display/dc/hwss/dcn20/dcn20_hwseq.h index 749348d3c793..9312c88e31ad 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dcn20/dcn20_hwseq.h +++ b/drivers/gpu/drm/amd/display/dc/hwss/dcn20/dcn20_hwseq.h @@ -31,9 +31,9 @@ void dcn20_log_color_state(struct dc *dc, struct dc_log_buffer_ctx *log_ctx); bool dcn20_set_blend_lut( - struct pipe_ctx *pipe_ctx, const struct dc_plane_state *plane_state); + struct dpp *dpp, struct dc_plane_state *plane_state); bool dcn20_set_shaper_3dlut( - struct pipe_ctx *pipe_ctx, const struct dc_plane_state *plane_state); + struct dpp *dpp, struct dc_plane_state *plane_state); void dcn20_program_front_end_for_ctx( struct dc *dc, struct dc_state *context); @@ -42,8 +42,7 @@ void dcn20_post_unlock_program_front_end( struct dc_state *context); void dcn20_update_plane_addr(const struct dc *dc, struct pipe_ctx *pipe_ctx); void dcn20_update_mpcc(struct dc *dc, struct pipe_ctx *pipe_ctx); -bool dcn20_set_input_transfer_func(struct dc *dc, struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state); +bool dcn20_set_input_transfer_func(struct set_input_transfer_func_params *params); bool dcn20_set_output_transfer_func(struct set_output_transfer_func_params *params); void dcn20_program_output_csc(struct dc *dc, struct pipe_ctx *pipe_ctx, diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dcn30/dcn30_hwseq.c b/drivers/gpu/drm/amd/display/dc/hwss/dcn30/dcn30_hwseq.c index d669b47af120..a6144da65254 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dcn30/dcn30_hwseq.c +++ b/drivers/gpu/drm/amd/display/dc/hwss/dcn30/dcn30_hwseq.c @@ -234,25 +234,23 @@ void dcn30_log_color_state(struct dc *dc, } bool dcn30_set_blend_lut( - struct pipe_ctx *pipe_ctx, const struct dc_plane_state *plane_state) + struct dpp *dpp, struct dc_plane_state *plane_state) { - struct dpp *dpp_base = pipe_ctx->plane_res.dpp; bool result = true; const struct pwl_params *blend_lut = NULL; if (plane_state->cm.blend_func.type == TF_TYPE_HWPWL) blend_lut = &plane_state->cm.blend_func.pwl; else if (plane_state->cm.blend_func.type == TF_TYPE_DISTRIBUTED_POINTS) { - result = cm3_helper_translate_curve_to_hw_format(plane_state->ctx, + result = cm3_helper_translate_curve_to_degamma_hw_format( &plane_state->cm.blend_func, - &dpp_base->regamma_params, - false); + &dpp->regamma_params); if (!result) return result; - blend_lut = &dpp_base->regamma_params; + blend_lut = &dpp->regamma_params; } - result = dpp_base->funcs->dpp_program_blnd_lut(dpp_base, blend_lut); + result = dpp->funcs->dpp_program_blnd_lut(dpp, blend_lut); return result; } @@ -314,17 +312,16 @@ static bool dcn30_set_mpc_shaper_3dlut(struct dpp *dpp, struct mpc *mpc, return result; } -bool dcn30_set_input_transfer_func(struct dc *dc, - struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state) +bool dcn30_set_input_transfer_func(struct set_input_transfer_func_params *params) { - struct dce_hwseq *hws = dc->hwseq; - struct dpp *dpp_base = pipe_ctx->plane_res.dpp; + struct dpp *dpp = params->dpp; + struct dce_hwseq *hws = params->dc->hwseq; + struct dc_plane_state *plane_state = params->plane_state; enum dc_transfer_func_predefined tf; bool result = true; - const struct pwl_params *params = NULL; + const struct pwl_params *pwl_params = NULL; - if (dpp_base == NULL || plane_state == NULL) + if (dpp == NULL || plane_state == NULL) return false; tf = TRANSFER_FUNCTION_UNITY; @@ -332,25 +329,23 @@ bool dcn30_set_input_transfer_func(struct dc *dc, if (plane_state->in_transfer_func.type == TF_TYPE_PREDEFINED) tf = plane_state->in_transfer_func.tf; - dpp_base->funcs->dpp_set_pre_degam(dpp_base, tf); + dpp->funcs->dpp_set_pre_degam(dpp, tf); if (plane_state->in_transfer_func.type == TF_TYPE_HWPWL) - params = &plane_state->in_transfer_func.pwl; + pwl_params = &plane_state->in_transfer_func.pwl; else if (plane_state->in_transfer_func.type == TF_TYPE_DISTRIBUTED_POINTS && - cm3_helper_translate_curve_to_hw_format(plane_state->ctx, - &plane_state->in_transfer_func, - &dpp_base->degamma_params, false)) - params = &dpp_base->degamma_params; - - result = dpp_base->funcs->dpp_program_gamcor_lut(dpp_base, params); - - if (pipe_ctx->stream_res.opp && pipe_ctx->stream_res.opp->ctx) { - if (dpp_base->funcs->dpp_program_blnd_lut) - hws->funcs.set_blend_lut(pipe_ctx, plane_state); - if (dpp_base->funcs->dpp_program_shaper_lut && - dpp_base->funcs->dpp_program_3dlut) - hws->funcs.set_shaper_3dlut(pipe_ctx, plane_state); - } + cm3_helper_translate_curve_to_degamma_hw_format(&plane_state->in_transfer_func, + &dpp->degamma_params)) + pwl_params = &dpp->degamma_params; + + result = dpp->funcs->dpp_program_gamcor_lut(dpp, pwl_params); + + if (dpp->funcs->dpp_program_blnd_lut) + hws->funcs.set_blend_lut(dpp, plane_state); + if (dpp->funcs->dpp_program_shaper_lut && + dpp->funcs->dpp_program_3dlut) + hws->funcs.set_shaper_3dlut(dpp, plane_state); + return result; } diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dcn30/dcn30_hwseq.h b/drivers/gpu/drm/amd/display/dc/hwss/dcn30/dcn30_hwseq.h index 0399642076eb..65014d42195c 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dcn30/dcn30_hwseq.h +++ b/drivers/gpu/drm/amd/display/dc/hwss/dcn30/dcn30_hwseq.h @@ -56,12 +56,10 @@ bool dcn30_mmhubbub_warmup( void dcn30_log_color_state(struct dc *dc, struct dc_log_buffer_ctx *log_ctx); -bool dcn30_set_blend_lut(struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state); +bool dcn30_set_blend_lut(struct dpp *dpp, + struct dc_plane_state *plane_state); -bool dcn30_set_input_transfer_func(struct dc *dc, - struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state); +bool dcn30_set_input_transfer_func(struct set_input_transfer_func_params *params); void dcn30_program_gamut_remap(struct program_gamut_remap_params *params); diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dcn32/dcn32_hwseq.c b/drivers/gpu/drm/amd/display/dc/hwss/dcn32/dcn32_hwseq.c index 51fd2b3fe106..e0b3ba747422 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dcn32/dcn32_hwseq.c +++ b/drivers/gpu/drm/amd/display/dc/hwss/dcn32/dcn32_hwseq.c @@ -477,26 +477,30 @@ bool dcn32_set_mpc_shaper_3dlut(struct dpp *dpp, struct mpc *mpc, return result; } -bool dcn32_set_mcm_luts( - struct pipe_ctx *pipe_ctx, const struct dc_plane_state *plane_state) +bool dcn32_set_mcm_luts(struct dc *dc, struct dpp *dpp, struct hubp *hubp, + struct hubp *primary_hubp, struct mpc *mpc, int mpcc_id, + struct dc_stream_state *stream, + struct dc_plane_state *plane_state) { - struct dpp *dpp_base = pipe_ctx->plane_res.dpp; - int mpcc_id = pipe_ctx->plane_res.hubp->inst; - struct mpc *mpc = pipe_ctx->stream_res.opp->ctx->dc->res_pool->mpc; bool rval, result; const struct pwl_params *lut_params = NULL; + (void)dc; + (void)hubp; + (void)primary_hubp; + (void)stream; + // 1D LUT if (plane_state->cm.blend_func.type == TF_TYPE_HWPWL) lut_params = &plane_state->cm.blend_func.pwl; else if (plane_state->cm.blend_func.type == TF_TYPE_DISTRIBUTED_POINTS) { result = cm3_helper_translate_curve_to_degamma_hw_format( &plane_state->cm.blend_func, - &dpp_base->regamma_params); + &dpp->regamma_params); if (!result) return result; - lut_params = &dpp_base->regamma_params; + lut_params = &dpp->regamma_params; } mpc->funcs->program_1dlut(mpc, lut_params, mpcc_id); lut_params = NULL; @@ -505,12 +509,12 @@ bool dcn32_set_mcm_luts( if (plane_state->cm.shaper_func.type == TF_TYPE_HWPWL) lut_params = &plane_state->cm.shaper_func.pwl; else if (plane_state->cm.shaper_func.type == TF_TYPE_DISTRIBUTED_POINTS) { - // TODO: dpp_base replace + // TODO: dpp replace rval = cm3_helper_translate_curve_to_hw_format(plane_state->ctx, &plane_state->cm.shaper_func, - &dpp_base->shaper_params, + &dpp->shaper_params, true); - lut_params = rval ? &dpp_base->shaper_params : NULL; + lut_params = rval ? &dpp->shaper_params : NULL; } mpc->funcs->program_shaper(mpc, lut_params, mpcc_id); @@ -524,19 +528,17 @@ bool dcn32_set_mcm_luts( return result; } -bool dcn32_set_input_transfer_func(struct dc *dc, - struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state) +bool dcn32_set_input_transfer_func(struct set_input_transfer_func_params *params) { - struct dce_hwseq *hws = dc->hwseq; - struct mpc *mpc = dc->res_pool->mpc; - struct dpp *dpp_base = pipe_ctx->plane_res.dpp; + struct dce_hwseq *hws = params->dc->hwseq; + struct dpp *dpp = params->dpp; + struct dc_plane_state *plane_state = params->plane_state; enum dc_transfer_func_predefined tf; bool result = true; - const struct pwl_params *params = NULL; + const struct pwl_params *pwl_params = NULL; - if (mpc == NULL || plane_state == NULL) + if (params->mpc == NULL || plane_state == NULL) return false; tf = TRANSFER_FUNCTION_UNITY; @@ -544,24 +546,24 @@ bool dcn32_set_input_transfer_func(struct dc *dc, if (plane_state->in_transfer_func.type == TF_TYPE_PREDEFINED) tf = plane_state->in_transfer_func.tf; - if (dpp_base->funcs->dpp_set_pregam_state) - dpp_base->funcs->dpp_set_pregam_state(dpp_base, tf, plane_state->scaling_linearity); + if (dpp->funcs->dpp_set_pregam_state) + dpp->funcs->dpp_set_pregam_state(dpp, tf, plane_state->scaling_linearity); else - dpp_base->funcs->dpp_set_pre_degam(dpp_base, tf); + dpp->funcs->dpp_set_pre_degam(dpp, tf); if (plane_state->in_transfer_func.type == TF_TYPE_HWPWL) - params = &plane_state->in_transfer_func.pwl; + pwl_params = &plane_state->in_transfer_func.pwl; else if (plane_state->in_transfer_func.type == TF_TYPE_DISTRIBUTED_POINTS && cm3_helper_translate_curve_to_degamma_hw_format(&plane_state->in_transfer_func, - &dpp_base->degamma_params)) - params = &dpp_base->degamma_params; + &dpp->degamma_params)) + pwl_params = &dpp->degamma_params; - dpp_base->funcs->dpp_program_gamcor_lut(dpp_base, params); + dpp->funcs->dpp_program_gamcor_lut(dpp, pwl_params); - if (pipe_ctx->stream_res.opp && - pipe_ctx->stream_res.opp->ctx && - hws->funcs.set_mcm_luts) - result = hws->funcs.set_mcm_luts(pipe_ctx, plane_state); + if (hws->funcs.set_mcm_luts) + result = hws->funcs.set_mcm_luts(params->dc, dpp, params->hubp, + params->primary_hubp, params->mpc, params->mpcc_id, + params->stream, plane_state); return result; } diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dcn32/dcn32_hwseq.h b/drivers/gpu/drm/amd/display/dc/hwss/dcn32/dcn32_hwseq.h index 090d94d38343..c85ff14596af 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dcn32/dcn32_hwseq.h +++ b/drivers/gpu/drm/amd/display/dc/hwss/dcn32/dcn32_hwseq.h @@ -47,12 +47,12 @@ void dcn32_cab_for_ss_control(struct dc *dc, bool enable); void dcn32_commit_subvp_config(struct dc *dc, struct dc_state *context); -bool dcn32_set_mcm_luts(struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state); +bool dcn32_set_mcm_luts(struct dc *dc, struct dpp *dpp, struct hubp *hubp, + struct hubp *primary_hubp, struct mpc *mpc, int mpcc_id, + struct dc_stream_state *stream, + struct dc_plane_state *plane_state); -bool dcn32_set_input_transfer_func(struct dc *dc, - struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state); +bool dcn32_set_input_transfer_func(struct set_input_transfer_func_params *params); bool dcn32_set_mpc_shaper_3dlut(struct dpp *dpp_base, struct mpc *mpc, int mpcc_id, const struct dc_stream_state *stream); diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dcn401/dcn401_hwseq.c b/drivers/gpu/drm/amd/display/dc/hwss/dcn401/dcn401_hwseq.c index 51596f445a09..6d839f45b085 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dcn401/dcn401_hwseq.c +++ b/drivers/gpu/drm/amd/display/dc/hwss/dcn401/dcn401_hwseq.c @@ -420,18 +420,12 @@ void dcn401_trigger_3dlut_dma_load(struct pipe_ctx *pipe_ctx) } } -bool dcn401_set_mcm_luts(struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state) +bool dcn401_set_mcm_luts(struct dc *dc, struct dpp *dpp, struct hubp *hubp, + struct hubp *primary_hubp, struct mpc *mpc, int mpcc_id, + struct dc_stream_state *stream, + struct dc_plane_state *plane_state) { - struct dc *dc = pipe_ctx->plane_res.hubp->ctx->dc; - const struct pipe_ctx *primary_dpp_pipe_ctx = resource_get_primary_dpp_pipe(pipe_ctx); - struct dpp *dpp_base = pipe_ctx->plane_res.dpp; - struct hubp *hubp = pipe_ctx->plane_res.hubp; - struct hubp *primary_hubp = primary_dpp_pipe_ctx ? - primary_dpp_pipe_ctx->plane_res.hubp : hubp; /* fall back to current pipe */ const struct dc_plane_cm *cm = &plane_state->cm; - int mpcc_id = hubp->inst; - struct mpc *mpc = dc->res_pool->mpc; union mcm_lut_params m_lut_params; struct dc_3dlut_dma lut3d_dma; bool lut_enable; @@ -439,6 +433,9 @@ bool dcn401_set_mcm_luts(struct pipe_ctx *pipe_ctx, bool rval; bool result = true; + (void)dc; + (void)stream; + /* decide LUT bank based on current in use */ mpc->funcs->get_lut_mode(mpc, MCM_LUT_1DLUT, mpcc_id, &lut_enable, &lut_bank_a); if (!lut_enable) { @@ -465,9 +462,9 @@ bool dcn401_set_mcm_luts(struct pipe_ctx *pipe_ctx, else if (cm->blend_func.type == TF_TYPE_DISTRIBUTED_POINTS) { rval = cm3_helper_translate_curve_to_hw_format(plane_state->ctx, &cm->blend_func, - &dpp_base->regamma_params, + &dpp->regamma_params, false); - m_lut_params.pwl = rval ? &dpp_base->regamma_params : NULL; + m_lut_params.pwl = rval ? &dpp->regamma_params : NULL; } if (!m_lut_params.pwl) { @@ -492,9 +489,9 @@ bool dcn401_set_mcm_luts(struct pipe_ctx *pipe_ctx, ASSERT(false); rval = cm3_helper_translate_curve_to_hw_format(plane_state->ctx, &cm->shaper_func, - &dpp_base->shaper_params, + &dpp->shaper_params, true); - m_lut_params.pwl = rval ? &dpp_base->shaper_params : NULL; + m_lut_params.pwl = rval ? &dpp->shaper_params : NULL; } if (!m_lut_params.pwl) { lut_enable = false; @@ -1332,28 +1329,10 @@ bool dcn401_apply_idle_power_optimizations(struct dc *dc, bool enable) return true; } -void dcn401_wait_for_dcc_meta_propagation(const struct dc *dc, - const struct pipe_ctx *top_pipe) +void dcn401_wait_for_dcc_meta_propagation(uint32_t delay) { - bool is_wait_needed = false; - const struct pipe_ctx *pipe_ctx = top_pipe; - - /* check if any surfaces are updating address while using flip immediate and dcc */ - while (pipe_ctx != NULL) { - if (pipe_ctx->plane_state && - pipe_ctx->plane_state->dcc.enable && - pipe_ctx->plane_state->flip_immediate && - pipe_ctx->plane_state->update_bits.addr_update) { - is_wait_needed = true; - break; - } - - /* check next pipe */ - pipe_ctx = pipe_ctx->bottom_pipe; - } - - if (is_wait_needed && dc->debug.dcc_meta_propagation_delay_us > 0) { - udelay(dc->debug.dcc_meta_propagation_delay_us); + if (delay > 0) { + udelay(delay); } } @@ -2305,7 +2284,7 @@ void dcn401_program_pipe( pipe_ctx->plane_state->update_bits.gamma_change || pipe_ctx->plane_state->update_bits.lut_3d || pipe_ctx->update_flags.bits.enable)) - hws->funcs.set_input_transfer_func(dc, pipe_ctx, pipe_ctx->plane_state); + hwss_set_input_transfer_func(dc, pipe_ctx); /* dcn10_translate_regamma_to_hw_format takes 750us to finish * only do gamma programming for powering on, internal memcmp to avoid @@ -2462,7 +2441,7 @@ void dcn401_program_pipe_sequence( pipe_ctx->plane_state->update_bits.lut_3d || pipe_ctx->update_flags.bits.enable)) { - hwss_add_dpp_set_input_transfer_func(seq_state, dc, pipe_ctx, pipe_ctx->plane_state); + hwss_add_dpp_set_input_transfer_func(seq_state, dc, pipe_ctx); } /* dcn10_translate_regamma_to_hw_format takes 750us to finish diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dcn401/dcn401_hwseq.h b/drivers/gpu/drm/amd/display/dc/hwss/dcn401/dcn401_hwseq.h index 69c7dc73a29a..c08fd359b38b 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dcn401/dcn401_hwseq.h +++ b/drivers/gpu/drm/amd/display/dc/hwss/dcn401/dcn401_hwseq.h @@ -36,8 +36,10 @@ void dcn401_program_gamut_remap(struct program_gamut_remap_params *params); void dcn401_init_hw(struct dc *dc); -bool dcn401_set_mcm_luts(struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state); +bool dcn401_set_mcm_luts(struct dc *dc, struct dpp *dpp, struct hubp *hubp, + struct hubp *primary_hubp, struct mpc *mpc, int mpcc_id, + struct dc_stream_state *stream, + struct dc_plane_state *plane_state); bool dcn401_set_output_transfer_func(struct set_output_transfer_func_params *params); void dcn401_trigger_3dlut_dma_load(struct pipe_ctx *pipe_ctx); void dcn401_calculate_dccg_tmds_div_value(struct pipe_ctx *pipe_ctx, @@ -57,8 +59,7 @@ void dcn401_set_cursor_position(struct pipe_ctx *pipe_ctx); bool dcn401_apply_idle_power_optimizations(struct dc *dc, bool enable); -void dcn401_wait_for_dcc_meta_propagation(const struct dc *dc, - const struct pipe_ctx *top_pipe_to_program); +void dcn401_wait_for_dcc_meta_propagation(uint32_t delay); void dcn401_prepare_bandwidth(struct dc *dc, struct dc_state *context); diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dcn42/dcn42_hwseq.c b/drivers/gpu/drm/amd/display/dc/hwss/dcn42/dcn42_hwseq.c index 13580d9f9303..bde918acba5b 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dcn42/dcn42_hwseq.c +++ b/drivers/gpu/drm/amd/display/dc/hwss/dcn42/dcn42_hwseq.c @@ -413,19 +413,18 @@ static bool dc_is_rmcm_3dlut_supported(struct hubp *hubp, struct mpc *mpc) } bool dcn42_program_rmcm_luts( + struct dc *dc, + struct dpp *dpp, struct hubp *hubp, - struct pipe_ctx *pipe_ctx, const struct dc_plane_cm *cm, struct mpc *mpc, - int mpcc_id) + int mpcc_id, + struct dc_stream_state *stream) { - struct dpp *dpp_base = pipe_ctx->plane_res.dpp; union mcm_lut_params m_lut_params = {0}; - struct dc *dc = hubp->ctx->dc; struct mpc_fl_3dlut_config mpc_fl_config; - struct dc_stream_state *stream = pipe_ctx->stream; bool bypass_rmcm_shaper = false; // true->false when it can be allocated at DI time struct dc_rmcm_3dlut *rmcm_3dlut = dc_stream_get_3dlut_for_stream(dc, stream, false); @@ -457,8 +456,8 @@ bool dcn42_program_rmcm_luts( cm_helper_translate_curve_to_hw_format( dc->ctx, &cm->shaper_func, - &dpp_base->shaper_params, true); - m_lut_params.pwl = &dpp_base->shaper_params; + &dpp->shaper_params, true); + m_lut_params.pwl = &dpp->shaper_params; } if (m_lut_params.pwl) { if (mpc->funcs->rmcm.populate_lut) @@ -511,31 +510,29 @@ bool dcn42_program_rmcm_luts( return true; } -bool dcn42_set_mcm_luts(struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state) +bool dcn42_set_mcm_luts(struct dc *dc, struct dpp *dpp, struct hubp *hubp, + struct hubp *primary_hubp, struct mpc *mpc, int mpcc_id, + struct dc_stream_state *stream, + struct dc_plane_state *plane_state) { bool result; + const struct dc_plane_cm *cm = &plane_state->cm; /* MCM */ - result = dcn401_set_mcm_luts(pipe_ctx, plane_state); + result = dcn401_set_mcm_luts(dc, dpp, hubp, primary_hubp, mpc, mpcc_id, + stream, plane_state); /* RMCM */ - { - struct dc *dc = pipe_ctx->plane_res.hubp->ctx->dc; - struct hubp *hubp = pipe_ctx->plane_res.hubp; - const struct dc_plane_cm *cm = &plane_state->cm; - struct mpc *mpc = dc->res_pool->mpc; - int mpcc_id = hubp->inst; - - if (cm->flags.bits.rmcm_enable && cm->flags.bits.lut3d_dma_enable) { - /* TODO - move RMCM to its own block */ - dcn42_program_rmcm_luts( - hubp, - pipe_ctx, - cm, - mpc, - mpcc_id); - } + if (cm->flags.bits.rmcm_enable && cm->flags.bits.lut3d_dma_enable) { + /* TODO - move RMCM to its own block */ + dcn42_program_rmcm_luts( + dc, + dpp, + hubp, + cm, + mpc, + mpcc_id, + stream); } return result; @@ -686,7 +683,7 @@ void dcn42_prepare_bandwidth( /* valid C-state watermarks have now been committed to HW, so it * is safe to vote "allow" to PMFW. */ - if (dc->clk_mgr && dc->clk_mgr->funcs && dc->clk_mgr->funcs->notify_cstate_disable) + if (dc->clk_mgr->funcs->notify_cstate_disable) dc->clk_mgr->funcs->notify_cstate_disable(dc->clk_mgr, false); } diff --git a/drivers/gpu/drm/amd/display/dc/hwss/dcn42/dcn42_hwseq.h b/drivers/gpu/drm/amd/display/dc/hwss/dcn42/dcn42_hwseq.h index c4cfeed45b19..61d1217a30df 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/dcn42/dcn42_hwseq.h +++ b/drivers/gpu/drm/amd/display/dc/hwss/dcn42/dcn42_hwseq.h @@ -15,15 +15,19 @@ void dcn42_program_cm_hist( struct pipe_ctx *pipe_ctx, const struct dc_plane_state *plane_state); -bool dcn42_set_mcm_luts(struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state); +bool dcn42_set_mcm_luts(struct dc *dc, struct dpp *dpp, struct hubp *hubp, + struct hubp *primary_hubp, struct mpc *mpc, int mpcc_id, + struct dc_stream_state *stream, + struct dc_plane_state *plane_state); bool dcn42_program_rmcm_luts( + struct dc *dc, + struct dpp *dpp, struct hubp *hubp, - struct pipe_ctx *pipe_ctx, const struct dc_plane_cm *cm, struct mpc *mpc, - int mpcc_id); + int mpcc_id, + struct dc_stream_state *stream); void dcn42_hardware_release(struct dc *dc); void dcn42_prepare_bandwidth( diff --git a/drivers/gpu/drm/amd/display/dc/hwss/hw_sequencer.h b/drivers/gpu/drm/amd/display/dc/hwss/hw_sequencer.h index 0d64a0c1913d..cdaa3cd51a0f 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/hw_sequencer.h +++ b/drivers/gpu/drm/amd/display/dc/hwss/hw_sequencer.h @@ -90,7 +90,13 @@ struct update_plane_addr_params { struct set_input_transfer_func_params { struct dc *dc; - struct pipe_ctx *pipe_ctx; + struct dpp *dpp; + struct hubp *hubp; + struct hubp *primary_hubp; + struct mpc *mpc; + int mpcc_id; + struct dc_stream_state *stream; + struct input_pixel_processor *ipp; struct dc_plane_state *plane_state; }; @@ -182,8 +188,7 @@ struct subvp_save_surf_addr { }; struct wait_for_dcc_meta_propagation_params { - const struct dc *dc; - const struct pipe_ctx *top_pipe_to_program; + uint32_t delay; }; struct dmub_hw_control_lock_fast_params { @@ -1652,8 +1657,7 @@ struct hw_sequencer_funcs { bool (*is_pipe_topology_transition_seamless)(struct dc *dc, const struct dc_state *cur_ctx, const struct dc_state *new_ctx); - void (*wait_for_dcc_meta_propagation)(const struct dc *dc, - const struct pipe_ctx *top_pipe_to_program); + void (*wait_for_dcc_meta_propagation)(uint32_t delay); void (*dmub_hw_control_lock)(struct dc *dc, struct dc_state *context, bool lock); @@ -2120,6 +2124,10 @@ void hwss_setup_periodic_interrupt(struct dc *dc, union block_sequence_params *p void hwss_disable_audio_stream(struct dc *dc, union block_sequence_params *params); +void hwss_hubp_wait_for_dcc_meta_prop(struct dc *dc, struct pipe_ctx *top_pipe_to_program); + +void hwss_set_input_transfer_func(struct dc *dc, struct pipe_ctx *pipe_ctx); + void hwss_add_optc_pipe_control_lock(struct block_sequence_state *seq_state, struct dc *dc, struct pipe_ctx *pipe_ctx, bool lock); @@ -2133,7 +2141,7 @@ void hwss_add_hubp_update_plane_addr(struct block_sequence_state *seq_state, struct dc *dc, struct pipe_ctx *pipe_ctx); void hwss_add_dpp_set_input_transfer_func(struct block_sequence_state *seq_state, - struct dc *dc, struct pipe_ctx *pipe_ctx, struct dc_plane_state *plane_state); + struct dc *dc, struct pipe_ctx *pipe_ctx); void hwss_add_dpp_program_gamut_remap(struct block_sequence_state *seq_state, struct pipe_ctx *pipe_ctx); @@ -2167,9 +2175,6 @@ void hwss_add_dmub_send_dmcub_cmd(struct block_sequence_state *seq_state, void hwss_add_dmub_subvp_save_surf_addr(struct block_sequence_state *seq_state, struct dc_dmub_srv *dc_dmub_srv, struct dc_plane_address *addr, uint8_t subvp_index); -void hwss_add_hubp_wait_for_dcc_meta_prop(struct block_sequence_state *seq_state, - struct dc *dc, struct pipe_ctx *top_pipe_to_program); - void hwss_add_hubp_wait_pipe_read_start(struct block_sequence_state *seq_state, struct hubp *hubp); diff --git a/drivers/gpu/drm/amd/display/dc/hwss/hw_sequencer_private.h b/drivers/gpu/drm/amd/display/dc/hwss/hw_sequencer_private.h index 0f7881a21462..956513125be0 100644 --- a/drivers/gpu/drm/amd/display/dc/hwss/hw_sequencer_private.h +++ b/drivers/gpu/drm/amd/display/dc/hwss/hw_sequencer_private.h @@ -90,9 +90,7 @@ struct hwseq_private_funcs { void (*update_mpcc)(struct dc *dc, struct pipe_ctx *pipe_ctx); void (*update_mpcc_sequence)(struct dc *dc, struct pipe_ctx *pipe_ctx, struct block_sequence_state *seq_state); - bool (*set_input_transfer_func)(struct dc *dc, - struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state); + bool (*set_input_transfer_func)(struct set_input_transfer_func_params *params); bool (*set_output_transfer_func)(struct set_output_transfer_func_params *params); void (*power_down)(struct dc *dc); void (*enable_display_pipe_clock_gating)(struct dc_context *ctx, @@ -187,12 +185,14 @@ struct hwseq_private_funcs { struct block_sequence_state *seq_state); bool (*wait_for_blank_complete)(struct output_pixel_processor *opp); void (*dccg_init)(struct dce_hwseq *hws); - bool (*set_blend_lut)(struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state); - bool (*set_shaper_3dlut)(struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state); - bool (*set_mcm_luts)(struct pipe_ctx *pipe_ctx, - const struct dc_plane_state *plane_state); + bool (*set_blend_lut)(struct dpp *dpp, + struct dc_plane_state *plane_state); + bool (*set_shaper_3dlut)(struct dpp *dpp, + struct dc_plane_state *plane_state); + bool (*set_mcm_luts)(struct dc *dc, struct dpp *dpp, struct hubp *hubp, + struct hubp *primary_hubp, struct mpc *mpc, int mpcc_id, + struct dc_stream_state *stream, + struct dc_plane_state *plane_state); void (*PLAT_58856_wa)(struct dc_state *context, struct pipe_ctx *pipe_ctx); void (*setup_hpo_hw_control)(const struct dce_hwseq *hws, bool enable); diff --git a/drivers/gpu/drm/amd/display/dc/irq/Makefile b/drivers/gpu/drm/amd/display/dc/irq/Makefile index bbec53719c5d..497794a1f1d1 100644 --- a/drivers/gpu/drm/amd/display/dc/irq/Makefile +++ b/drivers/gpu/drm/amd/display/dc/irq/Makefile @@ -41,6 +41,7 @@ AMD_DAL_IRQ_DCE60 = $(addprefix $(AMDDALPATH)/dc/irq/dce60/,$(IRQ_DCE60)) AMD_DISPLAY_FILES += $(AMD_DAL_IRQ_DCE60) endif +ifdef CONFIG_DRM_AMD_DC_DCE ############################################################################### # DCE 8x ############################################################################### @@ -67,6 +68,7 @@ IRQ_DCE12 = irq_service_dce120.o AMD_DAL_IRQ_DCE12 = $(addprefix $(AMDDALPATH)/dc/irq/dce120/,$(IRQ_DCE12)) AMD_DISPLAY_FILES += $(AMD_DAL_IRQ_DCE12) +endif # CONFIG_DRM_AMD_DC_DCE ############################################################################### # DCN 1x diff --git a/drivers/gpu/drm/amd/display/dc/irq/dce110/irq_service_dce110.c b/drivers/gpu/drm/amd/display/dc/irq/dce110/irq_service_dce110.c index 8958d286dde1..7f3084c6dd49 100644 --- a/drivers/gpu/drm/amd/display/dc/irq/dce110/irq_service_dce110.c +++ b/drivers/gpu/drm/amd/display/dc/irq/dce110/irq_service_dce110.c @@ -179,27 +179,6 @@ static struct irq_source_info_funcs vupdate_irq_info_funcs = { #define dc_underflow_int_entry(reg_num) \ [DC_IRQ_SOURCE_DC ## reg_num ## UNDERFLOW] = dummy_irq_entry() -bool dal_irq_service_dummy_set(struct irq_service *irq_service, - const struct irq_source_info *info, - bool enable) -{ - (void)enable; - DC_LOG_ERROR("%s: called for non-implemented irq source, src_id=%u, ext_id=%u\n", - __func__, info->src_id, info->ext_id); - - return false; -} - -bool dal_irq_service_dummy_ack(struct irq_service *irq_service, - const struct irq_source_info *info) -{ - DC_LOG_ERROR("%s: called for non-implemented irq source, src_id=%u, ext_id=%u\n", - __func__, info->src_id, info->ext_id); - - return false; -} - - bool dce110_vblank_set(struct irq_service *irq_service, const struct irq_source_info *info, bool enable) diff --git a/drivers/gpu/drm/amd/display/dc/irq/dce110/irq_service_dce110.h b/drivers/gpu/drm/amd/display/dc/irq/dce110/irq_service_dce110.h index 9237646c0959..b641e6a9b135 100644 --- a/drivers/gpu/drm/amd/display/dc/irq/dce110/irq_service_dce110.h +++ b/drivers/gpu/drm/amd/display/dc/irq/dce110/irq_service_dce110.h @@ -36,15 +36,6 @@ enum dc_irq_source to_dal_irq_source_dce110( uint32_t src_id, uint32_t ext_id); -bool dal_irq_service_dummy_set( - struct irq_service *irq_service, - const struct irq_source_info *info, - bool enable); - -bool dal_irq_service_dummy_ack( - struct irq_service *irq_service, - const struct irq_source_info *info); - bool dce110_vblank_set( struct irq_service *irq_service, const struct irq_source_info *info, diff --git a/drivers/gpu/drm/amd/display/dc/irq/irq_service.c b/drivers/gpu/drm/amd/display/dc/irq/irq_service.c index b595a11c5eaf..f8c8ca266ec1 100644 --- a/drivers/gpu/drm/amd/display/dc/irq/irq_service.c +++ b/drivers/gpu/drm/amd/display/dc/irq/irq_service.c @@ -28,14 +28,18 @@ #include "include/irq_service_interface.h" #include "include/logger_interface.h" +#if defined(CONFIG_DRM_AMD_DC_DCE) #include "dce110/irq_service_dce110.h" +#endif #if defined(CONFIG_DRM_AMD_DC_SI) #include "dce60/irq_service_dce60.h" #endif +#if defined(CONFIG_DRM_AMD_DC_DCE) #include "dce80/irq_service_dce80.h" #include "dce120/irq_service_dce120.h" +#endif #include "dcn10/irq_service_dcn10.h" #include "reg_helper.h" @@ -105,6 +109,30 @@ void dal_irq_service_set_generic( dm_write_reg(irq_service->ctx, addr, value); } +/* + * Base "non-implemented source" irq handlers referenced by irq_service.c and + * every DCN irq vtable. + */ +bool dal_irq_service_dummy_set(struct irq_service *irq_service, + const struct irq_source_info *info, + bool enable) +{ + (void)enable; + DC_LOG_ERROR("%s: called for non-implemented irq source, src_id=%u, ext_id=%u\n", + __func__, info->src_id, info->ext_id); + + return false; +} + +bool dal_irq_service_dummy_ack(struct irq_service *irq_service, + const struct irq_source_info *info) +{ + DC_LOG_ERROR("%s: called for non-implemented irq source, src_id=%u, ext_id=%u\n", + __func__, info->src_id, info->ext_id); + + return false; +} + bool dal_irq_service_set( struct irq_service *irq_service, enum dc_irq_source source, diff --git a/drivers/gpu/drm/amd/display/dc/irq/irq_service.h b/drivers/gpu/drm/amd/display/dc/irq/irq_service.h index bbcef3d2fe33..c13986754a4a 100644 --- a/drivers/gpu/drm/amd/display/dc/irq/irq_service.h +++ b/drivers/gpu/drm/amd/display/dc/irq/irq_service.h @@ -90,4 +90,13 @@ bool hpd1_ack( struct irq_service *irq_service, const struct irq_source_info *info); +bool dal_irq_service_dummy_set( + struct irq_service *irq_service, + const struct irq_source_info *info, + bool enable); + +bool dal_irq_service_dummy_ack( + struct irq_service *irq_service, + const struct irq_source_info *info); + #endif diff --git a/drivers/gpu/drm/amd/display/dc/resource/Makefile b/drivers/gpu/drm/amd/display/dc/resource/Makefile index b29986266888..bf127b9882f7 100644 --- a/drivers/gpu/drm/amd/display/dc/resource/Makefile +++ b/drivers/gpu/drm/amd/display/dc/resource/Makefile @@ -37,6 +37,8 @@ endif ############################################################################### +ifdef CONFIG_DRM_AMD_DC_DCE + RESOURCE_DCE80 = dce80_resource.o AMD_DAL_RESOURCE_DCE80 = $(addprefix $(AMDDALPATH)/dc/resource/dce80/,$(RESOURCE_DCE80)) @@ -75,6 +77,8 @@ AMD_DAL_RESOURCE_DCE120 = $(addprefix $(AMDDALPATH)/dc/resource/dce120/,$(RESOUR AMD_DISPLAY_FILES += $(AMD_DAL_RESOURCE_DCE120) +endif # CONFIG_DRM_AMD_DC_DCE + ifdef CONFIG_DRM_AMD_DC_FP ############################################################################### # DCN diff --git a/drivers/gpu/drm/amd/display/dc/resource/dce112/dce112_resource.c b/drivers/gpu/drm/amd/display/dc/resource/dce112/dce112_resource.c index 8c4494a8ec8f..2da5d44e5203 100644 --- a/drivers/gpu/drm/amd/display/dc/resource/dce112/dce112_resource.c +++ b/drivers/gpu/drm/amd/display/dc/resource/dce112/dce112_resource.c @@ -848,30 +848,6 @@ static void dce112_resource_destruct(struct dce110_resource_pool *pool) } } -static struct clock_source *find_matching_pll( - struct resource_context *res_ctx, - const struct resource_pool *pool, - const struct dc_stream_state *const stream) -{ - (void)res_ctx; - switch (stream->link->link_enc->transmitter) { - case TRANSMITTER_UNIPHY_A: - return pool->clock_sources[DCE112_CLK_SRC_PLL0]; - case TRANSMITTER_UNIPHY_B: - return pool->clock_sources[DCE112_CLK_SRC_PLL1]; - case TRANSMITTER_UNIPHY_C: - return pool->clock_sources[DCE112_CLK_SRC_PLL2]; - case TRANSMITTER_UNIPHY_D: - return pool->clock_sources[DCE112_CLK_SRC_PLL3]; - case TRANSMITTER_UNIPHY_E: - return pool->clock_sources[DCE112_CLK_SRC_PLL4]; - case TRANSMITTER_UNIPHY_F: - return pool->clock_sources[DCE112_CLK_SRC_PLL5]; - default: - return NULL; - } -} - static enum dc_status build_mapped_resource( const struct dc *dc, struct dc_state *context, @@ -963,44 +939,6 @@ enum dc_status dce112_validate_bandwidth( return result ? DC_OK : DC_FAIL_BANDWIDTH_VALIDATE; } -enum dc_status resource_map_phy_clock_resources( - const struct dc *dc, - struct dc_state *context, - struct dc_stream_state *stream) -{ - - /* acquire new resources */ - struct pipe_ctx *pipe_ctx = resource_get_otg_master_for_stream( - &context->res_ctx, stream); - - if (!pipe_ctx) - return DC_ERROR_UNEXPECTED; - - if (dc_is_dp_signal(pipe_ctx->stream->signal) - || dc_is_virtual_signal(pipe_ctx->stream->signal)) - pipe_ctx->clock_source = - dc->res_pool->dp_clock_source; - else if (pipe_ctx->stream->signal == SIGNAL_TYPE_HDMI_FRL) - pipe_ctx->clock_source = - dc->res_pool->dp_clock_source; - else { - if (stream && stream->link && stream->link->link_enc) - pipe_ctx->clock_source = find_matching_pll( - &context->res_ctx, dc->res_pool, - stream); - } - - if (pipe_ctx->clock_source == NULL) - return DC_NO_CLOCK_SOURCE_RESOURCE; - - resource_reference_clock_source( - &context->res_ctx, - dc->res_pool, - pipe_ctx->clock_source); - - return DC_OK; -} - static bool dce112_validate_surface_sets( struct dc_state *context) { diff --git a/drivers/gpu/drm/amd/display/dc/resource/dcn42b/dcn42b_resource.c b/drivers/gpu/drm/amd/display/dc/resource/dcn42b/dcn42b_resource.c index f36d0f828166..8e5bc0276abb 100644 --- a/drivers/gpu/drm/amd/display/dc/resource/dcn42b/dcn42b_resource.c +++ b/drivers/gpu/drm/amd/display/dc/resource/dcn42b/dcn42b_resource.c @@ -2422,6 +2422,8 @@ static bool dcn42b_resource_construct( /* SPL */ dc->caps.scl_caps.sharpener_support = true; + dc->dml2_options.pmo.force_mandatory_uclk_pstate_support = true; + return true; create_fail: diff --git a/drivers/gpu/drm/amd/pm/powerplay/hwmgr/ppatomctrl.c b/drivers/gpu/drm/amd/pm/powerplay/hwmgr/ppatomctrl.c index 4b796d60b03d..3217ad3c1d17 100644 --- a/drivers/gpu/drm/amd/pm/powerplay/hwmgr/ppatomctrl.c +++ b/drivers/gpu/drm/amd/pm/powerplay/hwmgr/ppatomctrl.c @@ -1025,6 +1025,9 @@ int atomctrl_get_smc_sclk_range_table(struct pp_hwmgr *hwmgr, struct pp_atom_ctr if (!psmu_info) return -EINVAL; + if (psmu_info->ucSclkEntryNum > MAX_SCLK_RANGE) + return -EINVAL; + for (i = 0; i < psmu_info->ucSclkEntryNum; i++) { table->entry[i].ucVco_setting = psmu_info->asSclkFcwRangeEntry[i].ucVco_setting; table->entry[i].ucPostdiv = psmu_info->asSclkFcwRangeEntry[i].ucPostdiv; diff --git a/drivers/gpu/drm/amd/pm/swsmu/inc/smu_v15_0.h b/drivers/gpu/drm/amd/pm/swsmu/inc/smu_v15_0.h index ec96dc775485..0c97bee2c4bb 100644 --- a/drivers/gpu/drm/amd/pm/swsmu/inc/smu_v15_0.h +++ b/drivers/gpu/drm/amd/pm/swsmu/inc/smu_v15_0.h @@ -113,8 +113,6 @@ int smu_v15_0_init_microcode(struct smu_context *smu); void smu_v15_0_fini_microcode(struct smu_context *smu); -int smu_v15_0_load_microcode(struct smu_context *smu); - int smu_v15_0_init_smc_tables(struct smu_context *smu); int smu_v15_0_fini_smc_tables(struct smu_context *smu); @@ -183,10 +181,6 @@ int smu_v15_0_set_performance_level(struct smu_context *smu, int smu_v15_0_set_power_source(struct smu_context *smu, enum smu_power_src_type power_src); -int smu_v15_0_set_single_dpm_table(struct smu_context *smu, - enum smu_clk_type clk_type, - struct smu_dpm_table *single_dpm_table); - int smu_v15_0_gfx_ulv_control(struct smu_context *smu, bool enablement); diff --git a/drivers/gpu/drm/amd/pm/swsmu/smu15/smu_v15_0.c b/drivers/gpu/drm/amd/pm/swsmu/smu15/smu_v15_0.c index 4c0236196de4..2269703869f9 100644 --- a/drivers/gpu/drm/amd/pm/swsmu/smu15/smu_v15_0.c +++ b/drivers/gpu/drm/amd/pm/swsmu/smu15/smu_v15_0.c @@ -106,44 +106,6 @@ void smu_v15_0_fini_microcode(struct smu_context *smu) adev->pm.fw_version = 0; } -int smu_v15_0_load_microcode(struct smu_context *smu) -{ - struct amdgpu_device *adev = smu->adev; - const uint32_t *src; - const struct smc_firmware_header_v1_0 *hdr; - uint32_t addr_start = MP1_SRAM; - uint32_t i; - uint32_t smc_fw_size; - uint32_t mp1_fw_flags; - - hdr = (const struct smc_firmware_header_v1_0 *) adev->pm.fw->data; - src = (const uint32_t *)(adev->pm.fw->data + - le32_to_cpu(hdr->header.ucode_array_offset_bytes)); - smc_fw_size = hdr->header.ucode_size_bytes; - - for (i = 1; i < smc_fw_size/4 - 1; i++) { - WREG32_PCIE(addr_start, src[i]); - addr_start += 4; - } - - - for (i = 0; i < adev->usec_timeout; i++) { - if (smu->is_apu) - mp1_fw_flags = RREG32_PCIE(MP1_Public | - (smnMP1_FIRMWARE_FLAGS & 0xffffffff)); - - if ((mp1_fw_flags & MP1_CRU1_MP1_FIRMWARE_FLAGS__INTERRUPTS_ENABLED_MASK) >> - MP1_CRU1_MP1_FIRMWARE_FLAGS__INTERRUPTS_ENABLED__SHIFT) - break; - udelay(1); - } - - if (i == adev->usec_timeout) - return -ETIME; - - return 0; -} - int smu_v15_0_init_pptable_microcode(struct smu_context *smu) { struct amdgpu_device *adev = smu->adev; @@ -1161,134 +1123,6 @@ int smu_v15_0_set_power_source(struct smu_context *smu, NULL); } -static int smu_v15_0_get_dpm_freq_by_index(struct smu_context *smu, - enum smu_clk_type clk_type, - uint16_t level, - uint32_t *value) -{ - int ret = 0, clk_id = 0; - uint32_t param; - - if (!value) - return -EINVAL; - - if (!smu_cmn_clk_dpm_is_enabled(smu, clk_type)) - return 0; - - clk_id = smu_cmn_to_asic_specific_index(smu, - CMN2ASIC_MAPPING_CLK, - clk_type); - if (clk_id < 0) - return clk_id; - - param = (uint32_t)(((clk_id & 0xffff) << 16) | (level & 0xffff)); - - ret = smu_cmn_send_smc_msg_with_param(smu, - SMU_MSG_GetDpmFreqByIndex, - param, - value); - if (ret) - return ret; - - *value = *value & 0x7fffffff; - - return ret; -} - -static int smu_v15_0_get_dpm_level_count(struct smu_context *smu, - enum smu_clk_type clk_type, - uint32_t *value) -{ - int ret; - - ret = smu_v15_0_get_dpm_freq_by_index(smu, clk_type, 0xff, value); - - return ret; -} - -static int smu_v15_0_get_fine_grained_status(struct smu_context *smu, - enum smu_clk_type clk_type, - bool *is_fine_grained_dpm) -{ - int ret = 0, clk_id = 0; - uint32_t param; - uint32_t value; - - if (!is_fine_grained_dpm) - return -EINVAL; - - if (!smu_cmn_clk_dpm_is_enabled(smu, clk_type)) - return 0; - - clk_id = smu_cmn_to_asic_specific_index(smu, - CMN2ASIC_MAPPING_CLK, - clk_type); - if (clk_id < 0) - return clk_id; - - param = (uint32_t)(((clk_id & 0xffff) << 16) | 0xff); - - ret = smu_cmn_send_smc_msg_with_param(smu, - SMU_MSG_GetDpmFreqByIndex, - param, - &value); - if (ret) - return ret; - - /* - * BIT31: 1 - Fine grained DPM, 0 - Dicrete DPM - * now, we un-support it - */ - *is_fine_grained_dpm = value & 0x80000000; - - return 0; -} - -int smu_v15_0_set_single_dpm_table(struct smu_context *smu, - enum smu_clk_type clk_type, - struct smu_dpm_table *single_dpm_table) -{ - int ret = 0; - uint32_t clk; - bool is_fine_grained; - int i; - - ret = smu_v15_0_get_dpm_level_count(smu, - clk_type, - &single_dpm_table->count); - if (ret) { - dev_err(smu->adev->dev, "[%s] failed to get dpm levels!\n", __func__); - return ret; - } - - ret = smu_v15_0_get_fine_grained_status(smu, - clk_type, - &is_fine_grained); - if (ret) { - dev_err(smu->adev->dev, "[%s] failed to get fine grained status!\n", __func__); - return ret; - } - - if (is_fine_grained) - single_dpm_table->flags |= SMU_DPM_TABLE_FINE_GRAINED; - - for (i = 0; i < single_dpm_table->count; i++) { - ret = smu_v15_0_get_dpm_freq_by_index(smu, - clk_type, - i, - &clk); - if (ret) { - dev_err(smu->adev->dev, "[%s] failed to get dpm freq by index!\n", __func__); - return ret; - } - - single_dpm_table->dpm_levels[i].value = clk; - single_dpm_table->dpm_levels[i].enabled = true; - } - - return 0; -} - int smu_v15_0_set_vcn_enable(struct smu_context *smu, bool enable, int inst) diff --git a/drivers/gpu/drm/amd/ras/core/eeprom.c b/drivers/gpu/drm/amd/ras/core/eeprom.c index 7afaac81f37a..08409881a7ed 100644 --- a/drivers/gpu/drm/amd/ras/core/eeprom.c +++ b/drivers/gpu/drm/amd/ras/core/eeprom.c @@ -269,7 +269,7 @@ static void __encode_table_header_to_buf(struct ras_eeprom_table_header *hdr, unsigned char *buf) { - u32 *pp = (uint32_t *)buf; + __le32 *pp = (__le32 *)buf; pp[0] = cpu_to_le32(hdr->header); pp[1] = cpu_to_le32(hdr->version); @@ -282,7 +282,7 @@ static void __decode_table_header_from_buf(struct ras_eeprom_table_header *hdr, unsigned char *buf) { - u32 *pp = (uint32_t *)buf; + __le32 *pp = (__le32 *)buf; hdr->header = le32_to_cpu(pp[0]); hdr->version = le32_to_cpu(pp[1]); @@ -324,7 +324,7 @@ static void __encode_table_ras_info_to_buf(struct ras_eeprom_table_ras_info *rai, unsigned char *buf) { - u32 *pp = (uint32_t *)buf; + __le32 *pp = (__le32 *)buf; u32 tmp; tmp = ((uint32_t)(rai->rma_status) & 0xFF) | diff --git a/drivers/gpu/drm/arm/display/include/malidp_product.h b/drivers/gpu/drm/arm/display/include/malidp_product.h index 6f954bcdf40e..f9a3ee7ba4b7 100644 --- a/drivers/gpu/drm/arm/display/include/malidp_product.h +++ b/drivers/gpu/drm/arm/display/include/malidp_product.h @@ -8,14 +8,18 @@ #define _MALIDP_PRODUCT_H_ /* Product identification */ +/* GLB_CORE_ID fields as per HW specification: + * MINOR is 8 bits ([11:4]) and STATUS is 4 bits ([3:0]). + * Update masks/shifts accordingly. + */ #define MALIDP_CORE_ID(__product, __major, __minor, __status) \ ((((__product) & 0xFFFF) << 16) | (((__major) & 0xF) << 12) | \ - (((__minor) & 0xF) << 8) | ((__status) & 0xFF)) + (((__minor) & 0xFF) << 4) | ((__status) & 0xF)) #define MALIDP_CORE_ID_PRODUCT_ID(__core_id) ((__u32)(__core_id) >> 16) #define MALIDP_CORE_ID_MAJOR(__core_id) (((__u32)(__core_id) >> 12) & 0xF) -#define MALIDP_CORE_ID_MINOR(__core_id) (((__u32)(__core_id) >> 8) & 0xF) -#define MALIDP_CORE_ID_STATUS(__core_id) (((__u32)(__core_id)) & 0xFF) +#define MALIDP_CORE_ID_MINOR(__core_id) (((__u32)(__core_id) >> 4) & 0xFF) +#define MALIDP_CORE_ID_STATUS(__core_id) ((__u32)(__core_id) & 0xF) /* Mali-display product IDs */ #define MALIDP_D71_PRODUCT_ID 0x0071 diff --git a/drivers/gpu/drm/atmel-hlcdc/atmel_hlcdc_plane.c b/drivers/gpu/drm/atmel-hlcdc/atmel_hlcdc_plane.c index f17a832351e9..70a1cef24388 100644 --- a/drivers/gpu/drm/atmel-hlcdc/atmel_hlcdc_plane.c +++ b/drivers/gpu/drm/atmel-hlcdc/atmel_hlcdc_plane.c @@ -1186,8 +1186,6 @@ static void atmel_hlcdc_plane_atomic_destroy_state(struct drm_plane *p, static void atmel_hlcdc_plane_reset(struct drm_plane *p) { struct atmel_hlcdc_plane_state *state; - struct atmel_hlcdc_dc *dc = p->dev->dev_private; - struct atmel_hlcdc_plane *plane = drm_plane_to_atmel_hlcdc_plane(p); if (p->state) { atmel_hlcdc_plane_atomic_destroy_state(p, p->state); @@ -1204,9 +1202,6 @@ static void atmel_hlcdc_plane_reset(struct drm_plane *p) } __drm_atomic_helper_plane_reset(p, &state->base); } - - if (plane->layer.desc->layout.csc) - dc->desc->ops->lcdc_csc_init(plane, plane->layer.desc); } static const struct drm_plane_funcs layer_plane_funcs = { diff --git a/drivers/gpu/drm/bridge/synopsys/dw-hdmi.c b/drivers/gpu/drm/bridge/synopsys/dw-hdmi.c index 34c5f583e910..937d61c42b58 100644 --- a/drivers/gpu/drm/bridge/synopsys/dw-hdmi.c +++ b/drivers/gpu/drm/bridge/synopsys/dw-hdmi.c @@ -3353,7 +3353,7 @@ struct dw_hdmi *dw_hdmi_probe(struct platform_device *pdev, hdmi->channels = 2; hdmi->disabled = true; hdmi->rxsense = true; - hdmi->phy_mask = (u8)~(HDMI_PHY_HPD | HDMI_PHY_RX_SENSE); + hdmi->phy_mask = ~(HDMI_PHY_HPD | HDMI_PHY_RX_SENSE) & 0xff; hdmi->mc_clkdis = 0x7f; hdmi->last_connector_result = connector_status_disconnected; diff --git a/drivers/gpu/drm/drm_connector.c b/drivers/gpu/drm/drm_connector.c index 8b4baed060f3..0e39431e85b2 100644 --- a/drivers/gpu/drm/drm_connector.c +++ b/drivers/gpu/drm/drm_connector.c @@ -628,6 +628,8 @@ int drmm_connector_hdmi_init(struct drm_device *dev, connector->state = state; } else if (connector->funcs->reset) { connector->funcs->reset(connector); + if (!connector->state) + return -ENOMEM; } drm_connector_attach_max_bpc_property(connector, 8, max_bpc); diff --git a/drivers/gpu/drm/drm_of.c b/drivers/gpu/drm/drm_of.c index e495117735e1..cf02dbca5458 100644 --- a/drivers/gpu/drm/drm_of.c +++ b/drivers/gpu/drm/drm_of.c @@ -550,8 +550,8 @@ EXPORT_SYMBOL_GPL(drm_of_lvds_get_data_mapping); * * Return: * * min..max - positive integer count of "data-lanes" elements - * * -ve - the "data-lanes" property is missing or invalid - * * -EINVAL - the "data-lanes" property is unsupported + * * -ENODATA - the property does not have a value. + * * -EINVAL - the "data-lanes" property is missing or invalid */ int drm_of_get_data_lanes_count(const struct device_node *endpoint, const unsigned int min, const unsigned int max) @@ -582,8 +582,8 @@ EXPORT_SYMBOL_GPL(drm_of_get_data_lanes_count); * * Return: * * min..max - positive integer count of "data-lanes" elements - * * -EINVAL - the "data-mapping" property is unsupported - * * -ENODEV - the "data-mapping" property is missing + * * -ENODATA - the property does not have a value. + * * -EINVAL - the "data-lanes" property is missing or invalid */ int drm_of_get_data_lanes_count_ep(const struct device_node *port, int port_reg, int reg, diff --git a/drivers/gpu/drm/drm_pagemap.c b/drivers/gpu/drm/drm_pagemap.c index a0546955d0b9..743988036a5f 100644 --- a/drivers/gpu/drm/drm_pagemap.c +++ b/drivers/gpu/drm/drm_pagemap.c @@ -1079,7 +1079,7 @@ static void drm_pagemap_release(struct kref *ref) dpagemap->dev_hold = NULL; drm_pagemap_shrinker_add(dpagemap); llist_add(&dev_hold->link, &drm_pagemap_unhold_list); - schedule_work(&drm_pagemap_work); + queue_work(system_dfl_wq, &drm_pagemap_work); /* * Here, either the provider device is still alive, since if called from * page_free(), the caller is holding a reference on the dev_pagemap, @@ -1106,6 +1106,7 @@ static void drm_pagemap_dev_unhold_work(struct work_struct *work) drm_dev_put(drm); module_put(module); kfree(dev_hold); + cond_resched(); } } diff --git a/drivers/gpu/drm/drm_ras.c b/drivers/gpu/drm/drm_ras.c index d6eab29a1394..467a169026fc 100644 --- a/drivers/gpu/drm/drm_ras.c +++ b/drivers/gpu/drm/drm_ras.c @@ -201,25 +201,28 @@ static int doit_reply_value(struct genl_info *info, u32 node_id, hdr = genlmsg_iput(msg, info); if (!hdr) { - nlmsg_free(msg); - return -EMSGSIZE; + ret = -EMSGSIZE; + goto free_msg; } ret = get_node_error_counter(node_id, error_id, &error_name, &value); if (ret) - return ret; + goto cancel_msg; ret = msg_reply_value(msg, error_id, error_name, value); - if (ret) { - genlmsg_cancel(msg, hdr); - nlmsg_free(msg); - return ret; - } + if (ret) + goto cancel_msg; genlmsg_end(msg, hdr); return genlmsg_reply(msg, info); + +cancel_msg: + genlmsg_cancel(msg, hdr); +free_msg: + nlmsg_free(msg); + return ret; } /** diff --git a/drivers/gpu/drm/drm_syncobj.c b/drivers/gpu/drm/drm_syncobj.c index c23a5de27eff..f1d4da168545 100644 --- a/drivers/gpu/drm/drm_syncobj.c +++ b/drivers/gpu/drm/drm_syncobj.c @@ -208,7 +208,7 @@ #include #include #include -#include +#include #include "drm_internal.h" @@ -1193,39 +1193,6 @@ static signed long drm_syncobj_array_wait_timeout(struct drm_syncobj **syncobjs, return timeout; } -/** - * drm_timeout_abs_to_jiffies - calculate jiffies timeout from absolute value - * - * @timeout_nsec: timeout nsec component in ns, 0 for poll - * - * Calculate the timeout in jiffies from an absolute time in sec/nsec. - */ -signed long drm_timeout_abs_to_jiffies(int64_t timeout_nsec) -{ - ktime_t abs_timeout, now; - u64 timeout_ns, timeout_jiffies64; - - /* make 0 timeout means poll - absolute 0 doesn't seem valid */ - if (timeout_nsec == 0) - return 0; - - abs_timeout = ns_to_ktime(timeout_nsec); - now = ktime_get(); - - if (!ktime_after(abs_timeout, now)) - return 0; - - timeout_ns = ktime_to_ns(ktime_sub(abs_timeout, now)); - - timeout_jiffies64 = nsecs_to_jiffies64(timeout_ns); - /* clamp timeout to avoid infinite timeout */ - if (timeout_jiffies64 >= MAX_SCHEDULE_TIMEOUT - 1) - return MAX_SCHEDULE_TIMEOUT - 1; - - return timeout_jiffies64 + 1; -} -EXPORT_SYMBOL(drm_timeout_abs_to_jiffies); - static int drm_syncobj_array_wait(struct drm_device *dev, struct drm_file *file_private, struct drm_syncobj_wait *wait, diff --git a/drivers/gpu/drm/drm_timeout.c b/drivers/gpu/drm/drm_timeout.c new file mode 100644 index 000000000000..1a823607c633 --- /dev/null +++ b/drivers/gpu/drm/drm_timeout.c @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: MIT +/* + * Timeout conversion helpers for wait ioctls. + * + * Copyright 2017 Red Hat + * Copyright 2016 Advanced Micro Devices, Inc. + */ + +#include +#include +#include +#include +#include + +#include + +/** + * drm_timeout_abs_to_jiffies - calculate jiffies timeout from absolute value + * @timeout_nsec: timeout nsec component in ns, 0 for poll + * + * Calculate the timeout in jiffies from an absolute time in ns. The result is + * clamped to MAX_SCHEDULE_TIMEOUT - 1 to avoid infinite timeouts. + * + * Returns: + * The number of jiffies until the given timeout, or the upper limit. + */ +signed long drm_timeout_abs_to_jiffies(s64 timeout_nsec) +{ + ktime_t abs_timeout, now; + u64 timeout_ns, timeout_jiffies64; + + /* make 0 timeout means poll - absolute 0 doesn't seem valid */ + if (timeout_nsec == 0) + return 0; + + abs_timeout = ns_to_ktime(timeout_nsec); + now = ktime_get(); + + if (!ktime_after(abs_timeout, now)) + return 0; + + timeout_ns = ktime_to_ns(ktime_sub(abs_timeout, now)); + + timeout_jiffies64 = nsecs_to_jiffies64(timeout_ns); + /* clamp timeout to avoid infinite timeout */ + if (timeout_jiffies64 >= MAX_SCHEDULE_TIMEOUT - 1) + return MAX_SCHEDULE_TIMEOUT - 1; + + return timeout_jiffies64 + 1; +} +EXPORT_SYMBOL(drm_timeout_abs_to_jiffies); + +/** + * drm_timeout_rel_to_jiffies - calculate jiffies timeout from relative value + * @timeout_nsec: relative timeout in ns, 0 for poll + * + * Calculate the timeout in jiffies from a relative timeout in ns, for drivers + * whose UAPI expresses a wait as a duration rather than as a deadline. + * + * The result is clamped to MAX_JIFFY_OFFSET. That keeps it positive once it is + * converted to the signed long taken by dma_fence_wait_timeout() and friends, + * which matters on 32-bit, and keeps it distinct from MAX_SCHEDULE_TIMEOUT so + * that a finite wait is never understood as an infinite one. + * + * It's strongly discouraged to use relative timeouts in uAPIs, as they do not + * survive a restarted ioctl. A signal-interrupted ioctl is re-entered with the + * same arguments, so the duration starts counting from zero again. New uAPIs + * should take an absolute deadline and use drm_timeout_abs_to_jiffies(). + * + * Returns: + * 0 if @timeout_nsec is 0. Otherwise the equivalent number of jiffies and + * clamped to MAX_JIFFY_OFFSET. + */ +unsigned long drm_timeout_rel_to_jiffies(u64 timeout_nsec) +{ + u64 secs; + u32 rem; + + /* Make 0 timeout means poll, as for the absolute variant. */ + if (timeout_nsec == 0) + return 0; + + /* + * As nsecs_to_jiffies64() does not guard against overflow, split + * the timeout into whole seconds and nanoseconds. This way + * nsecs_to_jiffies64() is always handed a value below a second. + */ + secs = div_u64_rem(timeout_nsec, NSEC_PER_SEC, &rem); + if (secs >= MAX_JIFFY_OFFSET / HZ) + return MAX_JIFFY_OFFSET; + + return min_t(u64, MAX_JIFFY_OFFSET, + secs_to_jiffies(secs) + nsecs_to_jiffies64(rem) + 1); +} +EXPORT_SYMBOL(drm_timeout_rel_to_jiffies); diff --git a/drivers/gpu/drm/exynos/exynos_drm_fimd.c b/drivers/gpu/drm/exynos/exynos_drm_fimd.c index b6abdc4f2b0a..695d3515d421 100644 --- a/drivers/gpu/drm/exynos/exynos_drm_fimd.c +++ b/drivers/gpu/drm/exynos/exynos_drm_fimd.c @@ -989,7 +989,7 @@ static void fimd_trigger(struct device *dev) { struct fimd_context *ctx = dev_get_drvdata(dev); const struct fimd_driver_data *driver_data = ctx->driver_data; - void *timing_base = ctx->regs + driver_data->timing_base; + void __iomem *timing_base = ctx->regs + driver_data->timing_base; u32 reg; /* diff --git a/drivers/gpu/drm/i915/display/intel_psr.c b/drivers/gpu/drm/i915/display/intel_psr.c index 7aaf5b4d3503..01c36ea315fa 100644 --- a/drivers/gpu/drm/i915/display/intel_psr.c +++ b/drivers/gpu/drm/i915/display/intel_psr.c @@ -2899,6 +2899,19 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state, bool full_update = false, su_area_changed; int i; + /* + * Selective fetch is not always usable, for instance it is dropped + * while pipe CRC is active. The planes keep their selective fetch + * enable bit set in hardware over that, and a plane disabled while + * selective fetch is off never gets the bit cleared. Once selective + * fetch comes back the hardware would resume fetching for a plane that + * is no longer enabled and keep its DDB range reserved, so have the + * plane update drop the bit for every plane of the pipe as selective + * fetch is turned off. + */ + crtc_state->clear_psr2_sel_fetch = old_crtc_state->enable_psr2_sel_fetch && + !crtc_state->enable_psr2_sel_fetch; + /* * Selective fetch is not always usable, for instance it is dropped * while pipe CRC is active. The planes keep their selective fetch diff --git a/drivers/gpu/drm/imx/lcdc/imx-lcdc.c b/drivers/gpu/drm/imx/lcdc/imx-lcdc.c index c67fe80b8115..e00e52c1c46e 100644 --- a/drivers/gpu/drm/imx/lcdc/imx-lcdc.c +++ b/drivers/gpu/drm/imx/lcdc/imx-lcdc.c @@ -310,7 +310,8 @@ static void imx_lcdc_pipe_update(struct drm_simple_display_pipe *pipe, else if (old_crtc != crtc) mode_changed = true; - imx_lcdc_update_hw_registers(pipe, old_state, mode_changed); + if (!drm_atomic_crtc_needs_modeset(crtc->state)) + imx_lcdc_update_hw_registers(pipe, old_state, mode_changed); if (event) { crtc->state->event = NULL; diff --git a/drivers/gpu/drm/lima/lima_gem.c b/drivers/gpu/drm/lima/lima_gem.c index 0c73860bb501..97e1dc541c2e 100644 --- a/drivers/gpu/drm/lima/lima_gem.c +++ b/drivers/gpu/drm/lima/lima_gem.c @@ -10,7 +10,7 @@ #include #include -#include +#include #include diff --git a/drivers/gpu/drm/msm/adreno/a3xx_gpu.c b/drivers/gpu/drm/msm/adreno/a3xx_gpu.c index 0259e60b8011..f672abd5e15e 100644 --- a/drivers/gpu/drm/msm/adreno/a3xx_gpu.c +++ b/drivers/gpu/drm/msm/adreno/a3xx_gpu.c @@ -500,14 +500,18 @@ static u64 a3xx_gpu_busy(struct msm_gpu *gpu, unsigned long *out_sample_rate) static int a3xx_vbif_halt(struct msm_gpu *gpu) { + struct adreno_gpu *adreno_gpu = to_adreno_gpu(gpu); + u32 mask = A3XX_VBIF_XIN_HALT_CTRL0_MASK; u32 ack; int ret; - gpu_write(gpu, REG_A3XX_VBIF_XIN_HALT_CTRL0, - A3XX_VBIF_XIN_HALT_CTRL0_MASK); + /* A306(A) only have three VBIF XIN ports. */ + if (adreno_is_a306(adreno_gpu) || adreno_is_a306a(adreno_gpu)) + mask = GENMASK(2, 0); + + gpu_write(gpu, REG_A3XX_VBIF_XIN_HALT_CTRL0, mask); ret = spin_until(((ack = gpu_read(gpu, REG_A3XX_VBIF_XIN_HALT_CTRL1)) & - A3XX_VBIF_XIN_HALT_CTRL0_MASK) == - A3XX_VBIF_XIN_HALT_CTRL0_MASK); + mask) == mask); gpu_write(gpu, REG_A3XX_VBIF_XIN_HALT_CTRL0, 0); if (ret) diff --git a/drivers/gpu/drm/msm/adreno/a5xx_gpu.c b/drivers/gpu/drm/msm/adreno/a5xx_gpu.c index 5d96b8f63156..3974aaf6fd33 100644 --- a/drivers/gpu/drm/msm/adreno/a5xx_gpu.c +++ b/drivers/gpu/drm/msm/adreno/a5xx_gpu.c @@ -1337,9 +1337,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) @@ -1448,6 +1453,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, @@ -1565,8 +1571,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_obj(*a5xx_state); bool stalled = !!(gpu_read(gpu, REG_A5XX_RBBM_STATUS3) & BIT(24)); @@ -1581,6 +1609,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 @@ -1602,6 +1633,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); @@ -1630,6 +1662,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/msm/adreno/a6xx_gmu.c b/drivers/gpu/drm/msm/adreno/a6xx_gmu.c index 6d49c51df1a2..161b360bf3eb 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_gmu.c +++ b/drivers/gpu/drm/msm/adreno/a6xx_gmu.c @@ -1656,8 +1656,12 @@ static int a6xx_gmu_rpmh_bw_votes_init(struct adreno_gpu *adreno_gpu, if (bcm->fixed) { u32 perfmode = 0; - /* GMU on A6xx votes perfmode on all valid bandwidth */ - if (!adreno_is_a7xx(adreno_gpu) || + /* + * GMU on A6xx votes perfmode on all valid + * bandwidth. A7xx and A8xx only vote perfmode + * above the perfmode_bw threshold. + */ + if (adreno_is_a6xx(adreno_gpu) || (bcm->perfmode_bw && bw >= bcm->perfmode_bw)) perfmode = bcm->perfmode; @@ -1761,10 +1765,14 @@ static int a6xx_gmu_rpmh_arc_votes_init(struct device *dev, u32 *votes, /* * Look for a level in in the secondary list that matches. If * nothing fits, use the maximum non zero vote + * + * The secondary rail depends on the primary rail, so match it + * against the quantized primary voltage (which is >= the + * requested level), not the requested level itself. */ for (j = 0; j < sec_count; j++) { - if (sec[j] >= level) { + if (sec[j] >= pri[pindex]) { sindex = j; break; } else if (sec[j]) { @@ -1860,13 +1868,13 @@ static int a6xx_gmu_rpmh_votes_init(struct a6xx_gmu *gmu) ret = a6xx_gmu_rpmh_arc_votes_init(&gpu->pdev->dev, gmu->gx_arc_votes, gmu->gpu_freqs, gmu->nr_gpu_freqs, "gfx.lvl", sec_id); + ret |= a6xx_gmu_rpmh_dep_votes_init(&gpu->pdev->dev, gmu->dep_arc_votes, + gmu->gpu_freqs, gmu->nr_gpu_freqs); + /* Build the CX votes */ ret |= a6xx_gmu_rpmh_arc_votes_init(gmu->dev, gmu->cx_arc_votes, gmu->gmu_freqs, gmu->nr_gmu_freqs, "cx.lvl", "mx.lvl"); - ret |= a6xx_gmu_rpmh_dep_votes_init(gmu->dev, gmu->dep_arc_votes, - gmu->gpu_freqs, gmu->nr_gpu_freqs); - /* Build the interconnect votes */ if (info->bcms && gmu->nr_gpu_bws > 1) ret |= a6xx_gmu_rpmh_bw_votes_init(adreno_gpu, info, gmu); diff --git a/drivers/gpu/drm/msm/adreno/a6xx_gpu.c b/drivers/gpu/drm/msm/adreno/a6xx_gpu.c index 081e79ea4652..1f04503f718c 100644 --- a/drivers/gpu/drm/msm/adreno/a6xx_gpu.c +++ b/drivers/gpu/drm/msm/adreno/a6xx_gpu.c @@ -2181,44 +2181,48 @@ static int a6xx_pm_resume(struct msm_gpu *gpu) opp = dev_pm_opp_find_freq_ceil(&gpu->pdev->dev, &freq); if (IS_ERR(opp)) { ret = PTR_ERR(opp); - goto err_set_opp; + goto err_unlock; } - dev_pm_opp_put(opp); /* Set the core clock and bus bw, having VDD scaling in mind */ dev_pm_opp_set_opp(&gpu->pdev->dev, opp); + dev_pm_opp_put(opp); - pm_runtime_resume_and_get(gmu->dev); - pm_runtime_resume_and_get(gmu->gxpd); + ret = pm_runtime_resume_and_get(gmu->dev); + if (ret < 0) + goto err_opp_clear; + ret = pm_runtime_resume_and_get(gmu->gxpd); + if (ret < 0) + goto err_put_dev; ret = clk_bulk_prepare_enable(gpu->nr_clocks, gpu->grp_clks); if (ret) - goto err_bulk_clk; + goto err_put_gxpd; ret = clk_bulk_prepare_enable(gmu->nr_clocks, gmu->clocks); if (ret) { clk_bulk_disable_unprepare(gpu->nr_clocks, gpu->grp_clks); - goto err_bulk_clk; + goto err_put_gxpd; } if (adreno_is_a619_holi(adreno_gpu)) a6xx_sptprac_enable(gmu); - /* If anything goes south, tear the GPU down piece by piece.. */ - if (ret) { -err_bulk_clk: - pm_runtime_put(gmu->gxpd); - pm_runtime_put(gmu->dev); - dev_pm_opp_set_opp(&gpu->pdev->dev, NULL); - } -err_set_opp: mutex_unlock(&a6xx_gpu->gmu.lock); + msm_devfreq_resume(gpu); + a6xx_llc_activate(a6xx_gpu); - if (!ret) { - msm_devfreq_resume(gpu); - a6xx_llc_activate(a6xx_gpu); - } + return 0; + /* If anything goes south, tear the GPU down piece by piece.. */ +err_put_gxpd: + pm_runtime_put(gmu->gxpd); +err_put_dev: + pm_runtime_put(gmu->dev); +err_opp_clear: + dev_pm_opp_set_opp(&gpu->pdev->dev, NULL); +err_unlock: + mutex_unlock(&a6xx_gpu->gmu.lock); return ret; } diff --git a/drivers/gpu/drm/msm/adreno/a8xx_gpu.c b/drivers/gpu/drm/msm/adreno/a8xx_gpu.c index add93c1fa039..2f6f36fb8ba9 100644 --- a/drivers/gpu/drm/msm/adreno/a8xx_gpu.c +++ b/drivers/gpu/drm/msm/adreno/a8xx_gpu.c @@ -112,6 +112,9 @@ void a8xx_gpu_get_slice_info(struct msm_gpu *gpu) /* Chip ID depends on the number of slices available. So update it */ adreno_gpu->chip_id |= FIELD_PREP(GENMASK(7, 4), hweight32(slice_mask)); + /* GMEM is split evenly between slices: report the active share */ + adreno_gpu->gmem = (adreno_gpu->info->gmem / info->max_slices) * hweight32(slice_mask); + /* Update the gpu-name to reflect the slice config: */ const char *name = devm_kasprintf(dev, GFP_KERNEL, "%"ADRENO_CHIPID_FMT, diff --git a/drivers/gpu/drm/msm/adreno/adreno_gpu.c b/drivers/gpu/drm/msm/adreno/adreno_gpu.c index 5832dc25d6bf..dadfe4c69438 100644 --- a/drivers/gpu/drm/msm/adreno/adreno_gpu.c +++ b/drivers/gpu/drm/msm/adreno/adreno_gpu.c @@ -379,7 +379,7 @@ int adreno_get_param(struct msm_gpu *gpu, struct msm_context *ctx, *value = adreno_gpu->info->revn; return 0; case MSM_PARAM_GMEM_SIZE: - *value = adreno_gpu->info->gmem; + *value = adreno_gpu->gmem; return 0; case MSM_PARAM_GMEM_BASE: if (adreno_gpu->info->family >= ADRENO_6XX_GEN3) @@ -1205,6 +1205,7 @@ int adreno_gpu_init(struct drm_device *drm, struct platform_device *pdev, adreno_gpu->funcs = funcs; adreno_gpu->info = config->info; adreno_gpu->chip_id = config->chip_id; + adreno_gpu->gmem = config->info->gmem; gpu->allow_relocs = config->info->family < ADRENO_6XX_GEN1; gpu->pdev = pdev; diff --git a/drivers/gpu/drm/msm/adreno/adreno_gpu.h b/drivers/gpu/drm/msm/adreno/adreno_gpu.h index 114a40f79ef3..e0d0043cd8ba 100644 --- a/drivers/gpu/drm/msm/adreno/adreno_gpu.h +++ b/drivers/gpu/drm/msm/adreno/adreno_gpu.h @@ -204,6 +204,8 @@ struct adreno_gpu { struct msm_gpu base; const struct adreno_info *info; uint32_t chip_id; + /* GMEM size available to userspace, see a8xx_gpu_get_slice_info(): */ + uint32_t gmem; uint16_t speedbin; const struct adreno_gpu_funcs *funcs; @@ -580,6 +582,11 @@ static inline int adreno_is_a750_family(struct adreno_gpu *gpu) return gpu->info->family == ADRENO_7XX_GEN3; } +static inline int adreno_is_a6xx(struct adreno_gpu *gpu) +{ + return (gpu->info->family >= ADRENO_6XX_GEN1) && (gpu->info->family < ADRENO_7XX_GEN1); +} + static inline int adreno_is_a7xx(struct adreno_gpu *gpu) { /* Update with non-fake (i.e. non-A702) Gen 7 GPUs */ diff --git a/drivers/gpu/drm/msm/disp/dpu1/dpu_core_perf.c b/drivers/gpu/drm/msm/disp/dpu1/dpu_core_perf.c index fea173e37464..9fa55904dba1 100644 --- a/drivers/gpu/drm/msm/disp/dpu1/dpu_core_perf.c +++ b/drivers/gpu/drm/msm/disp/dpu1/dpu_core_perf.c @@ -54,24 +54,19 @@ u64 dpu_core_perf_adjusted_mode_clk(u64 mode_clk_rate, /** * _dpu_core_perf_calc_bw() - to calculate BW per crtc * @perf_cfg: performance configuration - * @crtc: pointer to a crtc + * @state: the CRTC state * Return: returns aggregated BW for all planes in crtc. */ static u64 _dpu_core_perf_calc_bw(const struct dpu_perf_cfg *perf_cfg, - struct drm_crtc *crtc) + struct drm_crtc_state *state) { struct drm_plane *plane; - struct dpu_plane_state *pstate; + const struct drm_plane_state *plane_state; u64 crtc_plane_bw = 0; u32 bw_factor; - drm_atomic_crtc_for_each_plane(plane, crtc) { - pstate = to_dpu_plane_state(plane->state); - if (!pstate) - continue; - - crtc_plane_bw += pstate->plane_fetch_bw; - } + drm_atomic_crtc_state_for_each_plane_state(plane, plane_state, state) + crtc_plane_bw += to_dpu_plane_state(plane_state)->plane_fetch_bw; bw_factor = perf_cfg->bw_inefficiency_factor; if (bw_factor) { @@ -131,7 +126,7 @@ static void _dpu_core_perf_calc_crtc(const struct dpu_core_perf *core_perf, return; } - perf->bw_ctl = _dpu_core_perf_calc_bw(perf_cfg, crtc); + perf->bw_ctl = _dpu_core_perf_calc_bw(perf_cfg, state); perf->max_per_pipe_ib = perf_cfg->min_dram_ib; perf->core_clk_rate = _dpu_core_perf_calc_clk(perf_cfg, crtc, state); DRM_DEBUG_ATOMIC( diff --git a/drivers/gpu/drm/msm/disp/dpu1/dpu_encoder.c b/drivers/gpu/drm/msm/disp/dpu1/dpu_encoder.c index 1f20695f81e3..0a6be69a3e83 100644 --- a/drivers/gpu/drm/msm/disp/dpu1/dpu_encoder.c +++ b/drivers/gpu/drm/msm/disp/dpu1/dpu_encoder.c @@ -1386,7 +1386,6 @@ static void dpu_encoder_virt_atomic_disable(struct drm_encoder *drm_enc, struct dpu_encoder_virt *dpu_enc = NULL; struct drm_crtc *crtc; struct drm_crtc_state *old_state = NULL; - int i = 0; dpu_enc = to_dpu_encoder_virt(drm_enc); DPU_DEBUG_ENC(dpu_enc, "\n"); @@ -1412,12 +1411,11 @@ static void dpu_encoder_virt_atomic_disable(struct drm_encoder *drm_enc, dpu_encoder_resource_control(drm_enc, DPU_ENC_RC_EVENT_PRE_STOP); - for (i = 0; i < dpu_enc->num_phys_encs; i++) { - struct dpu_encoder_phys *phys = dpu_enc->phys_encs[i]; + if (dpu_enc->cur_slave && dpu_enc->cur_slave->ops.disable) + dpu_enc->cur_slave->ops.disable(dpu_enc->cur_slave); - if (phys->ops.disable) - phys->ops.disable(phys); - } + if (dpu_enc->cur_master && dpu_enc->cur_master->ops.disable) + dpu_enc->cur_master->ops.disable(dpu_enc->cur_master); /* after phys waits for frame-done, should be no more frames pending */ diff --git a/drivers/gpu/drm/msm/disp/dpu1/dpu_encoder_phys_vid.c b/drivers/gpu/drm/msm/disp/dpu1/dpu_encoder_phys_vid.c index ba810f26ea30..2ac517db50fc 100644 --- a/drivers/gpu/drm/msm/disp/dpu1/dpu_encoder_phys_vid.c +++ b/drivers/gpu/drm/msm/disp/dpu1/dpu_encoder_phys_vid.c @@ -134,8 +134,8 @@ static void drm_mode_to_intf_timing_params( * TODO: replace drm_dsc_get_bpp_int with logic to handle * fractional part if there is fraction */ - timing->width = timing->width * drm_dsc_get_bpp_int(dsc) / - (dsc->bits_per_component * 3); + timing->width = DIV_ROUND_UP(timing->width * drm_dsc_get_bpp_int(dsc), + dsc->bits_per_component * 3); timing->xres = timing->width; timing->dce_bytes_per_line = msm_dsc_get_bytes_per_line(dsc); } diff --git a/drivers/gpu/drm/msm/disp/mdp5/mdp5_cfg.c b/drivers/gpu/drm/msm/disp/mdp5/mdp5_cfg.c index 7c91fc1915f3..389d74ff7516 100644 --- a/drivers/gpu/drm/msm/disp/mdp5/mdp5_cfg.c +++ b/drivers/gpu/drm/msm/disp/mdp5/mdp5_cfg.c @@ -698,15 +698,6 @@ static const struct mdp5_cfg_hw msm8x76_config = { MDP_PIPE_CAP_SW_PIX_EXT | 0, }, - .pipe_cursor = { - .count = 1, - .base = { 0x440DC }, - .caps = MDP_PIPE_CAP_HFLIP | - MDP_PIPE_CAP_VFLIP | - MDP_PIPE_CAP_SW_PIX_EXT | - MDP_PIPE_CAP_CURSOR | - 0, - }, .lm = { .count = 2, .base = { 0x44000, 0x45000 }, diff --git a/drivers/gpu/drm/msm/dp/dp_ctrl.c b/drivers/gpu/drm/msm/dp/dp_ctrl.c index 59070f399e2d..fd4f75384829 100644 --- a/drivers/gpu/drm/msm/dp/dp_ctrl.c +++ b/drivers/gpu/drm/msm/dp/dp_ctrl.c @@ -2434,6 +2434,9 @@ int msm_dp_ctrl_on_link(struct msm_dp_ctrl *msm_dp_ctrl, if (ctrl->link->sink_request & DP_TEST_LINK_PHY_TEST_PATTERN) return rc; + if (!link_train_max_retries) + rc = -ETIMEDOUT; + if (rc == 0) { /* link train successfully */ /* * do not stop train pattern here diff --git a/drivers/gpu/drm/msm/dp/dp_debug.c b/drivers/gpu/drm/msm/dp/dp_debug.c index cf3838fcd154..00fb1a7ba40e 100644 --- a/drivers/gpu/drm/msm/dp/dp_debug.c +++ b/drivers/gpu/drm/msm/dp/dp_debug.c @@ -216,6 +216,7 @@ int msm_dp_debug_init(struct device *dev, struct msm_dp_panel *panel, debug->link = link; debug->panel = panel; + debug->connector = connector; debugfs_create_file("dp_debug", 0444, root, debug, &msm_dp_debug_fops); diff --git a/drivers/gpu/drm/msm/msm_io_utils.c b/drivers/gpu/drm/msm/msm_io_utils.c index a6efe1eac271..99221b0d7e3f 100644 --- a/drivers/gpu/drm/msm/msm_io_utils.c +++ b/drivers/gpu/drm/msm/msm_io_utils.c @@ -77,7 +77,8 @@ static void __iomem *_msm_ioremap(struct platform_device *pdev, const char *name if (!res) { if (!quiet) - DRM_DEV_ERROR(&pdev->dev, "failed to get memory resource: %s\n", name); + DRM_DEV_ERROR(&pdev->dev, "failed to get memory resource: %s\n", + (name ?: "#0")); return ERR_PTR(-EINVAL); } @@ -86,7 +87,8 @@ static void __iomem *_msm_ioremap(struct platform_device *pdev, const char *name ptr = devm_ioremap(&pdev->dev, res->start, size); if (!ptr) { if (!quiet) - DRM_DEV_ERROR(&pdev->dev, "failed to ioremap: %s\n", name); + DRM_DEV_ERROR(&pdev->dev, "failed to ioremap: %s\n", + (name ?: "#0")); return ERR_PTR(-ENOMEM); } diff --git a/drivers/gpu/drm/omapdrm/dss/dsi.c b/drivers/gpu/drm/omapdrm/dss/dsi.c index 6da720e8732d..a57f5df5c830 100644 --- a/drivers/gpu/drm/omapdrm/dss/dsi.c +++ b/drivers/gpu/drm/omapdrm/dss/dsi.c @@ -59,9 +59,6 @@ static void dsi_uninit_dispc(struct dsi_data *dsi); static int dsi_vc_send_null(struct dsi_data *dsi, int vc, int channel); -static ssize_t _omap_dsi_host_transfer(struct dsi_data *dsi, int vc, - const struct mipi_dsi_msg *msg); - #ifdef DSI_PERF_MEASURE static bool dsi_perf; module_param(dsi_perf, bool, 0644); @@ -2190,28 +2187,45 @@ static int dsi_vc_send_null(struct dsi_data *dsi, int vc, int channel) static int dsi_vc_write_common(struct omap_dss_device *dssdev, int vc, const struct mipi_dsi_msg *msg) { + DECLARE_COMPLETION_ONSTACK(completion); struct dsi_data *dsi = to_dsi_data(dssdev); + u32 err; int r; + /* wait for IRQ for packet transmission confirmation */ + r = dsi_register_isr_vc(dsi, vc, dsi_completion_handler, + &completion, DSI_VC_IRQ_PACKET_SENT); + if (r) + return r; + if (mipi_dsi_packet_format_is_short(msg->type)) r = dsi_vc_send_short(dsi, vc, msg); else r = dsi_vc_send_long(dsi, vc, msg); - if (r < 0) + if ((!r) && wait_for_completion_timeout(&completion, + msecs_to_jiffies(500)) == 0) + r = -EIO; + + dsi_unregister_isr_vc(dsi, vc, dsi_completion_handler, + &completion, DSI_VC_IRQ_PACKET_SENT); + if (r) return r; - /* - * TODO: we do not always have to do the BTA sync, for example - * we can improve performance by setting the update window - * information without sending BTA sync between the commands. - * In that case we can return early. - */ + /* TODO: find out if more needs to be done for MIPI_DSI_MSG_REQ_ACK */ - r = dsi_vc_send_bta_sync(dssdev, vc); - if (r) { - DSSERR("bta sync failed\n"); - return r; + if (msg->flags & MIPI_DSI_MSG_REQ_ACK) { + r = dsi_vc_send_bta_sync(dssdev, vc); + if (r) { + DSSERR("bta sync failed\n"); + return r; + } + } else { + err = dsi_get_errors(dsi); + if (err) { + DSSERR("Error while sending: %x\n", err); + return -EIO; + } } /* RX_FIFO_NOT_EMPTY */ @@ -3229,21 +3243,6 @@ static int _dsi_update(struct dsi_data *dsi) return 0; } -static int _dsi_send_nop(struct dsi_data *dsi, int vc, int channel) -{ - const u8 payload[] = { MIPI_DCS_NOP }; - const struct mipi_dsi_msg msg = { - .channel = channel, - .type = MIPI_DSI_DCS_SHORT_WRITE, - .tx_len = 1, - .tx_buf = payload, - }; - - WARN_ON(!dsi_bus_is_locked(dsi)); - - return _omap_dsi_host_transfer(dsi, vc, &msg); -} - static int dsi_update_channel(struct omap_dss_device *dssdev, int vc) { struct dsi_data *dsi = to_dsi_data(dssdev); @@ -3264,13 +3263,13 @@ static int dsi_update_channel(struct omap_dss_device *dssdev, int vc) DSSDBG("dsi_update_channel: %d", vc); /* - * Send NOP between the frames. If we don't send something here, the + * Transition to LP here. If we don't send something here, the * updates stop working. This is probably related to DSI spec stating * that the DSI host should transition to LP at least once per frame. */ - r = _dsi_send_nop(dsi, VC_CMD, dsi->dsidev->channel); + r = dsi_vc_send_bta_sync(dssdev, VC_CMD); if (r < 0) { - DSSWARN("failed to send nop between frames: %d\n", r); + DSSWARN("failed to send bta sync between frames: %d\n", r); goto err; } diff --git a/drivers/gpu/drm/panel/Kconfig b/drivers/gpu/drm/panel/Kconfig index cbdf7b8f7f7a..67fc67134100 100644 --- a/drivers/gpu/drm/panel/Kconfig +++ b/drivers/gpu/drm/panel/Kconfig @@ -669,6 +669,8 @@ config DRM_PANEL_NOVATEK_NT36536 depends on OF depends on DRM_MIPI_DSI depends on BACKLIGHT_CLASS_DEVICE + select DRM_DISPLAY_DSC_HELPER + select DRM_DISPLAY_HELPER select DRM_KMS_HELPER help Say Y here if you want to enable support for Novatek NT36536-based diff --git a/drivers/gpu/drm/panfrost/panfrost_devfreq.c b/drivers/gpu/drm/panfrost/panfrost_devfreq.c index b51c30778811..0fe81d259274 100644 --- a/drivers/gpu/drm/panfrost/panfrost_devfreq.c +++ b/drivers/gpu/drm/panfrost/panfrost_devfreq.c @@ -78,7 +78,7 @@ static int panfrost_devfreq_get_dev_status(struct device *dev, dev_dbg(pfdev->base.dev, "busy %lu total %lu %lu %% freq %lu MHz\n", status->busy_time, status->total_time, - status->busy_time / (status->total_time / 100), + status->busy_time * 100 / MAX(status->total_time, 1), status->current_frequency / 1000 / 1000); return 0; diff --git a/drivers/gpu/drm/panfrost/panfrost_device.c b/drivers/gpu/drm/panfrost/panfrost_device.c index d0a23c51be39..6318d5f3a892 100644 --- a/drivers/gpu/drm/panfrost/panfrost_device.c +++ b/drivers/gpu/drm/panfrost/panfrost_device.c @@ -217,13 +217,6 @@ int panfrost_device_init(struct panfrost_device *pfdev) { int err; - mutex_init(&pfdev->sched_lock); - INIT_LIST_HEAD(&pfdev->as_lru_list); - - spin_lock_init(&pfdev->as_lock); - - spin_lock_init(&pfdev->cycle_counter.lock); - #ifdef CONFIG_DEBUG_FS mutex_init(&pfdev->debugfs.gems_lock); INIT_LIST_HEAD(&pfdev->debugfs.gems_list); @@ -281,9 +274,14 @@ int panfrost_device_init(struct panfrost_device *pfdev) if (err) goto out_job; - panfrost_gem_init(pfdev); + err = panfrost_gem_init(pfdev); + if (err) + goto out_perfcnt; return 0; + +out_perfcnt: + panfrost_perfcnt_fini(pfdev); out_job: panfrost_jm_fini(pfdev); out_mmu: @@ -305,6 +303,7 @@ int panfrost_device_init(struct panfrost_device *pfdev) void panfrost_device_fini(struct panfrost_device *pfdev) { + panfrost_gem_fini(pfdev); panfrost_perfcnt_fini(pfdev); panfrost_jm_fini(pfdev); panfrost_mmu_fini(pfdev); @@ -418,6 +417,8 @@ bool panfrost_exception_needs_reset(const struct panfrost_device *pfdev, void panfrost_device_reset(struct panfrost_device *pfdev, bool enable_job_int) { + guard(rwsem_write)(&pfdev->reset.lock); + panfrost_gpu_soft_reset(pfdev); panfrost_gpu_power_on(pfdev); @@ -426,6 +427,8 @@ void panfrost_device_reset(struct panfrost_device *pfdev, bool enable_job_int) panfrost_jm_reset_interrupts(pfdev); if (enable_job_int) panfrost_jm_enable_interrupts(pfdev); + + panfrost_perfcnt_reset(pfdev); } static int panfrost_device_runtime_resume(struct device *dev) diff --git a/drivers/gpu/drm/panfrost/panfrost_device.h b/drivers/gpu/drm/panfrost/panfrost_device.h index 1fe1554f2652..dec4a7a8bf45 100644 --- a/drivers/gpu/drm/panfrost/panfrost_device.h +++ b/drivers/gpu/drm/panfrost/panfrost_device.h @@ -165,6 +165,7 @@ struct panfrost_device { struct { struct workqueue_struct *wq; struct work_struct work; + struct rw_semaphore lock; atomic_t pending; } reset; diff --git a/drivers/gpu/drm/panfrost/panfrost_drv.c b/drivers/gpu/drm/panfrost/panfrost_drv.c index 36cc2e67a308..3eb5ca75dcb1 100644 --- a/drivers/gpu/drm/panfrost/panfrost_drv.c +++ b/drivers/gpu/drm/panfrost/panfrost_drv.c @@ -18,10 +18,9 @@ #include #include #include -#include +#include #include "panfrost_device.h" -#include "panfrost_drv.h" #include "panfrost_gem.h" #include "panfrost_mmu.h" #include "panfrost_job.h" @@ -42,9 +41,12 @@ static int panfrost_ioctl_query_timestamp(struct panfrost_device *pfdev, if (ret) return ret; - panfrost_cycle_counter_get(pfdev); - *arg = panfrost_timestamp_read(pfdev); - panfrost_cycle_counter_put(pfdev); + /* We should not read timestamp register while the GPU is being reset */ + scoped_guard(rwsem_read, &pfdev->reset.lock) { + panfrost_cycle_counter_get(pfdev); + *arg = panfrost_timestamp_read(pfdev); + panfrost_cycle_counter_put(pfdev); + } pm_runtime_put(pfdev->base.dev); return 0; @@ -662,7 +664,7 @@ static int panfrost_ioctl_query_bo_info(struct drm_device *dev, void *data, if (bo->is_heap) args->create_flags |= PANFROST_BO_HEAP; - if (!bo->base.map_wc) + if (bo->wb_mmap) args->create_flags |= PANFROST_BO_WB_MMAP; } @@ -933,6 +935,7 @@ static void panfrost_debugfs_init(struct drm_minor *minor) * - 1.6 - adds PANFROST_BO_MAP_WB, PANFROST_IOCTL_SYNC_BO, * PANFROST_IOCTL_QUERY_BO_INFO and * DRM_PANFROST_PARAM_SELECTED_COHERENCY + * - 1.7 - adds PERFCNT_DUMP state field */ static const struct drm_driver panfrost_drm_driver = { .driver_features = DRIVER_RENDER | DRIVER_GEM | DRIVER_SYNCOBJ, @@ -945,7 +948,7 @@ static const struct drm_driver panfrost_drm_driver = { .name = "panfrost", .desc = "panfrost DRM", .major = 1, - .minor = 6, + .minor = 7, .gem_create_object = panfrost_gem_create_object, .gem_prime_import = panfrost_gem_prime_import, @@ -955,12 +958,6 @@ static const struct drm_driver panfrost_drm_driver = { #endif }; -#ifdef CONFIG_TRANSPARENT_HUGEPAGE -bool panfrost_transparent_hugepage = true; -module_param_named(transparent_hugepage, panfrost_transparent_hugepage, bool, 0400); -MODULE_PARM_DESC(transparent_hugepage, "Use a dedicated tmpfs mount point with Transparent Hugepage enabled (true = default)"); -#endif - static int panfrost_probe(struct platform_device *pdev) { struct panfrost_device *pfdev; @@ -979,9 +976,6 @@ static int panfrost_probe(struct platform_device *pdev) pfdev->coherent = device_get_dma_attr(&pdev->dev) == DEV_DMA_COHERENT; - mutex_init(&pfdev->shrinker_lock); - INIT_LIST_HEAD(&pfdev->shrinker_list); - err = panfrost_device_init(pfdev); if (err) { if (err != -EPROBE_DEFER) @@ -989,6 +983,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->base.dev); pm_runtime_set_active(pfdev->base.dev); pm_runtime_mark_last_busy(pfdev->base.dev); pm_runtime_enable(pfdev->base.dev); @@ -1003,18 +1002,16 @@ static int panfrost_probe(struct platform_device *pdev) if (err < 0) goto err_out1; - err = panfrost_gem_shrinker_init(&pfdev->base); - if (err) - goto err_out2; + pm_runtime_put_autosuspend(pfdev->base.dev); return 0; -err_out2: - drm_dev_unregister(&pfdev->base); err_out1: + pm_runtime_dont_use_autosuspend(pfdev->base.dev); pm_runtime_disable(pfdev->base.dev); panfrost_device_fini(pfdev); pm_runtime_set_suspended(pfdev->base.dev); + pm_runtime_put_noidle(pfdev->base.dev); err_out0: return err; } @@ -1024,12 +1021,14 @@ static void panfrost_remove(struct platform_device *pdev) struct panfrost_device *pfdev = platform_get_drvdata(pdev); drm_dev_unregister(&pfdev->base); - panfrost_gem_shrinker_cleanup(&pfdev->base); pm_runtime_get_sync(pfdev->base.dev); + pm_runtime_dont_use_autosuspend(pfdev->base.dev); pm_runtime_disable(pfdev->base.dev); panfrost_device_fini(pfdev); pm_runtime_set_suspended(pfdev->base.dev); + pm_runtime_put_noidle(pfdev->base.dev); + } static ssize_t profiling_show(struct device *dev, diff --git a/drivers/gpu/drm/panfrost/panfrost_drv.h b/drivers/gpu/drm/panfrost/panfrost_drv.h deleted file mode 100644 index a2277ec61aab..000000000000 --- a/drivers/gpu/drm/panfrost/panfrost_drv.h +++ /dev/null @@ -1,9 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0 or MIT */ -/* Copyright 2025 Amazon.com, Inc. or its affiliates */ - -#ifndef __PANFROST_DRV_H__ -#define __PANFROST_DRV_H__ - -extern bool panfrost_transparent_hugepage; - -#endif diff --git a/drivers/gpu/drm/panfrost/panfrost_gem.c b/drivers/gpu/drm/panfrost/panfrost_gem.c index 3a7fce428898..383ac8cd5645 100644 --- a/drivers/gpu/drm/panfrost/panfrost_gem.c +++ b/drivers/gpu/drm/panfrost/panfrost_gem.c @@ -11,24 +11,35 @@ #include #include #include "panfrost_device.h" -#include "panfrost_drv.h" #include "panfrost_gem.h" #include "panfrost_mmu.h" -void panfrost_gem_init(struct panfrost_device *pfdev) +#ifdef CONFIG_TRANSPARENT_HUGEPAGE +static bool panfrost_transparent_hugepage = true; +module_param_named(transparent_hugepage, panfrost_transparent_hugepage, bool, 0400); +MODULE_PARM_DESC(transparent_hugepage, "Use a dedicated tmpfs mount point with Transparent Hugepage enabled (true = default)"); +#else +#define panfrost_transparent_hugepage false +#endif + +int panfrost_gem_init(struct panfrost_device *pfdev) { - int err; + if (panfrost_transparent_hugepage) { + int err = drm_gem_huge_mnt_create(&pfdev->base, "within_size"); + + if (err) + drm_warn(&pfdev->base, + "Can't use Transparent Hugepage (%d)\n", err); + else + drm_info(&pfdev->base, "Using Transparent Hugepage\n"); + } - if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && - !panfrost_transparent_hugepage) - return; + return panfrost_gem_shrinker_init(pfdev); +} - err = drm_gem_huge_mnt_create(&pfdev->base, "within_size"); - if (drm_gem_get_huge_mnt(&pfdev->base)) - drm_info(&pfdev->base, "Using Transparent Hugepage\n"); - else if (err) - drm_warn(&pfdev->base, "Can't use Transparent Hugepage (%d)\n", - err); +void panfrost_gem_fini(struct panfrost_device *pfdev) +{ + panfrost_gem_shrinker_fini(pfdev); } #ifdef CONFIG_DEBUG_FS diff --git a/drivers/gpu/drm/panfrost/panfrost_gem.h b/drivers/gpu/drm/panfrost/panfrost_gem.h index 79d4377019e9..5c823cdbd980 100644 --- a/drivers/gpu/drm/panfrost/panfrost_gem.h +++ b/drivers/gpu/drm/panfrost/panfrost_gem.h @@ -129,7 +129,8 @@ drm_mm_node_to_panfrost_mapping(struct drm_mm_node *node) return container_of(node, struct panfrost_gem_mapping, mmnode); } -void panfrost_gem_init(struct panfrost_device *pfdev); +int panfrost_gem_init(struct panfrost_device *pfdev); +void panfrost_gem_fini(struct panfrost_device *pfdev); struct drm_gem_object *panfrost_gem_create_object(struct drm_device *dev, size_t size); @@ -154,8 +155,8 @@ panfrost_gem_mapping_get(struct panfrost_gem_object *bo, void panfrost_gem_mapping_put(struct panfrost_gem_mapping *mapping); void panfrost_gem_teardown_mappings_locked(struct panfrost_gem_object *bo); -int panfrost_gem_shrinker_init(struct drm_device *dev); -void panfrost_gem_shrinker_cleanup(struct drm_device *dev); +int panfrost_gem_shrinker_init(struct panfrost_device *pfdev); +void panfrost_gem_shrinker_fini(struct panfrost_device *pfdev); void panfrost_gem_set_label(struct drm_gem_object *obj, const char *label); int panfrost_gem_sync(struct drm_gem_object *obj, u32 type, diff --git a/drivers/gpu/drm/panfrost/panfrost_gem_shrinker.c b/drivers/gpu/drm/panfrost/panfrost_gem_shrinker.c index 2fe967a90bcb..72cd7a165e6d 100644 --- a/drivers/gpu/drm/panfrost/panfrost_gem_shrinker.c +++ b/drivers/gpu/drm/panfrost/panfrost_gem_shrinker.c @@ -95,9 +95,10 @@ panfrost_gem_shrinker_scan(struct shrinker *shrinker, struct shrink_control *sc) * * This function registers and sets up the panfrost shrinker. */ -int panfrost_gem_shrinker_init(struct drm_device *dev) +int panfrost_gem_shrinker_init(struct panfrost_device *pfdev) { - struct panfrost_device *pfdev = to_panfrost_device(dev); + mutex_init(&pfdev->shrinker_lock); + INIT_LIST_HEAD(&pfdev->shrinker_list); pfdev->shrinker = shrinker_alloc(0, "drm-panfrost"); if (!pfdev->shrinker) @@ -118,10 +119,8 @@ int panfrost_gem_shrinker_init(struct drm_device *dev) * * This function unregisters the panfrost shrinker. */ -void panfrost_gem_shrinker_cleanup(struct drm_device *dev) +void panfrost_gem_shrinker_fini(struct panfrost_device *pfdev) { - struct panfrost_device *pfdev = to_panfrost_device(dev); - if (pfdev->shrinker) shrinker_free(pfdev->shrinker); } diff --git a/drivers/gpu/drm/panfrost/panfrost_gpu.c b/drivers/gpu/drm/panfrost/panfrost_gpu.c index 7d555e63e21a..8a15ccce08e9 100644 --- a/drivers/gpu/drm/panfrost/panfrost_gpu.c +++ b/drivers/gpu/drm/panfrost/panfrost_gpu.c @@ -516,6 +516,8 @@ int panfrost_gpu_init(struct panfrost_device *pfdev) { int err; + spin_lock_init(&pfdev->cycle_counter.lock); + err = panfrost_gpu_soft_reset(pfdev); if (err) return err; diff --git a/drivers/gpu/drm/panfrost/panfrost_job.c b/drivers/gpu/drm/panfrost/panfrost_job.c index d59b4863b8ad..ab83f8f7c8f5 100644 --- a/drivers/gpu/drm/panfrost/panfrost_job.c +++ b/drivers/gpu/drm/panfrost/panfrost_job.c @@ -874,6 +874,8 @@ int panfrost_jm_init(struct panfrost_device *pfdev) INIT_WORK(&pfdev->reset.work, panfrost_reset_work); spin_lock_init(&js->job_lock); + mutex_init(&pfdev->sched_lock); + init_rwsem(&pfdev->reset.lock); js->irq = platform_get_irq_byname(to_platform_device(pfdev->base.dev), "job"); if (js->irq < 0) diff --git a/drivers/gpu/drm/panfrost/panfrost_mmu.c b/drivers/gpu/drm/panfrost/panfrost_mmu.c index 4a3162c3b659..faa62643caf1 100644 --- a/drivers/gpu/drm/panfrost/panfrost_mmu.c +++ b/drivers/gpu/drm/panfrost/panfrost_mmu.c @@ -336,6 +336,12 @@ void panfrost_mmu_as_put(struct panfrost_device *pfdev, struct panfrost_mmu *mmu WARN_ON(atomic_read(&mmu->as_count) < 0); } +static void panfrost_mmu_enable_interrupts(struct panfrost_device *pfdev) +{ + mmu_write(pfdev, MMU_INT_CLEAR, ~0); + mmu_write(pfdev, MMU_INT_MASK, ~0); +} + void panfrost_mmu_reset(struct panfrost_device *pfdev) { struct panfrost_mmu *mmu, *mmu_tmp; @@ -355,8 +361,7 @@ void panfrost_mmu_reset(struct panfrost_device *pfdev) spin_unlock(&pfdev->as_lock); - mmu_write(pfdev, MMU_INT_CLEAR, ~0); - mmu_write(pfdev, MMU_INT_MASK, ~0); + panfrost_mmu_enable_interrupts(pfdev); } static size_t get_pgsize(u64 addr, size_t size, size_t *count) @@ -955,6 +960,9 @@ int panfrost_mmu_init(struct panfrost_device *pfdev) { int err; + INIT_LIST_HEAD(&pfdev->as_lru_list); + spin_lock_init(&pfdev->as_lock); + pfdev->mmu_irq = platform_get_irq_byname(to_platform_device(pfdev->base.dev), "mmu"); if (pfdev->mmu_irq < 0) return pfdev->mmu_irq; @@ -970,6 +978,8 @@ int panfrost_mmu_init(struct panfrost_device *pfdev) return err; } + panfrost_mmu_enable_interrupts(pfdev); + return 0; } diff --git a/drivers/gpu/drm/panfrost/panfrost_perfcnt.c b/drivers/gpu/drm/panfrost/panfrost_perfcnt.c index 7020c0192e18..03a6dcd8da2f 100644 --- a/drivers/gpu/drm/panfrost/panfrost_perfcnt.c +++ b/drivers/gpu/drm/panfrost/panfrost_perfcnt.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0 /* Copyright 2019 Collabora Ltd */ +#include "asm-generic/errno-base.h" #include #include #include @@ -11,6 +12,7 @@ #include #include #include +#include #include "panfrost_device.h" #include "panfrost_features.h" @@ -28,13 +30,33 @@ struct panfrost_perfcnt { struct panfrost_gem_mapping *mapping; + unsigned int counterset; size_t bosize; void *buf; struct panfrost_file_priv *user; struct mutex lock; struct completion dump_comp; + u32 state; + bool owns_as_ref; }; +static void panfrost_perfcnt_hw_disable(struct panfrost_device *pfdev) +{ + struct panfrost_perfcnt *perfcnt = pfdev->perfcnt; + + gpu_write(pfdev, GPU_PERFCNT_CFG, + GPU_PERFCNT_CFG_MODE(GPU_PERFCNT_CFG_MODE_OFF)); + gpu_write(pfdev, GPU_PRFCNT_JM_EN, 0x0); + gpu_write(pfdev, GPU_PRFCNT_SHADER_EN, 0x0); + gpu_write(pfdev, GPU_PRFCNT_MMU_L2_EN, 0x0); + gpu_write(pfdev, GPU_PRFCNT_TILER_EN, 0); + + if (perfcnt->owns_as_ref) { + panfrost_mmu_as_put(pfdev, perfcnt->mapping->mmu); + perfcnt->owns_as_ref = false; + } +} + void panfrost_perfcnt_clean_cache_done(struct panfrost_device *pfdev) { complete(&pfdev->perfcnt->dump_comp); @@ -45,27 +67,129 @@ void panfrost_perfcnt_sample_done(struct panfrost_device *pfdev) gpu_write(pfdev, GPU_CMD, GPU_CMD_CLEAN_CACHES); } -static int panfrost_perfcnt_dump_locked(struct panfrost_device *pfdev) +static int panfrost_perfcnt_hw_enable(struct panfrost_device *pfdev) +{ + struct panfrost_perfcnt *perfcnt = pfdev->perfcnt; + u32 cfg, as; + int ret; + + lockdep_assert_held(&pfdev->reset.lock); + drm_WARN_ON(&pfdev->base, perfcnt->owns_as_ref); + + ret = panfrost_mmu_as_get(pfdev, perfcnt->mapping->mmu); + if (ret < 0) + return ret; + + perfcnt->owns_as_ref = true; + + as = ret; + cfg = GPU_PERFCNT_CFG_AS(as) | + GPU_PERFCNT_CFG_MODE(GPU_PERFCNT_CFG_MODE_MANUAL); + + /* + * Bifrost GPUs have 2 set of counters, but we're only interested by + * the first one for now. + */ + if (panfrost_model_is_bifrost(pfdev)) + cfg |= GPU_PERFCNT_CFG_SETSEL(perfcnt->counterset); + + gpu_write(pfdev, GPU_PRFCNT_JM_EN, 0xffffffff); + gpu_write(pfdev, GPU_PRFCNT_SHADER_EN, 0xffffffff); + gpu_write(pfdev, GPU_PRFCNT_MMU_L2_EN, 0xffffffff); + + /* + * Due to PRLAM-8186 we need to disable the Tiler before we enable HW + * counters. + */ + if (panfrost_has_hw_issue(pfdev, HW_ISSUE_8186)) + gpu_write(pfdev, GPU_PRFCNT_TILER_EN, 0); + else + gpu_write(pfdev, GPU_PRFCNT_TILER_EN, 0xffffffff); + + gpu_write(pfdev, GPU_PERFCNT_CFG, cfg); + + if (panfrost_has_hw_issue(pfdev, HW_ISSUE_8186)) + gpu_write(pfdev, GPU_PRFCNT_TILER_EN, 0xffffffff); + + return 0; +} + +static int panfrost_perfcnt_dump_locked(struct panfrost_device *pfdev, u32 *state) { - u64 gpuva; + struct panfrost_perfcnt *perfcnt = pfdev->perfcnt; + u64 gpuva = perfcnt->mapping->mmnode.start << PAGE_SHIFT; int ret; - reinit_completion(&pfdev->perfcnt->dump_comp); - gpuva = pfdev->perfcnt->mapping->mmnode.start << PAGE_SHIFT; - gpu_write(pfdev, GPU_PERFCNT_BASE_LO, lower_32_bits(gpuva)); - gpu_write(pfdev, GPU_PERFCNT_BASE_HI, upper_32_bits(gpuva)); - gpu_write(pfdev, GPU_INT_CLEAR, - GPU_IRQ_CLEAN_CACHES_COMPLETED | - GPU_IRQ_PERFCNT_SAMPLE_COMPLETED); - gpu_write(pfdev, GPU_CMD, GPU_CMD_PERFCNT_SAMPLE); + scoped_guard(rwsem_read, &pfdev->reset.lock) { + *state = perfcnt->state; + if (perfcnt->state & PANFROST_PERFCNT_SESSION_DEAD) + return -EIO; + + perfcnt->state = 0; + + reinit_completion(&pfdev->perfcnt->dump_comp); + + gpu_write(pfdev, GPU_PERFCNT_BASE_LO, lower_32_bits(gpuva)); + gpu_write(pfdev, GPU_PERFCNT_BASE_HI, upper_32_bits(gpuva)); + gpu_write(pfdev, GPU_INT_CLEAR, GPU_IRQ_CLEAN_CACHES_COMPLETED | + GPU_IRQ_PERFCNT_SAMPLE_COMPLETED); + gpu_write(pfdev, GPU_CMD, GPU_CMD_PERFCNT_SAMPLE); + } + + /* + * Here we release the reset semaphore because perfcnt should not get in the way + * of a HW reset. Besides, a legitimate reset might be issued during the wait. + */ ret = wait_for_completion_interruptible_timeout(&pfdev->perfcnt->dump_comp, msecs_to_jiffies(1000)); if (!ret) ret = -ETIMEDOUT; - else if (ret > 0) - ret = 0; - return ret; + scoped_guard(rwsem_read, &pfdev->reset.lock) { + /* Restore perfcnt state so the next successful dump can relay it to UM */ + if (ret < 0) { + perfcnt->state |= *state; + *state = 0; + return ret; + } + + *state |= perfcnt->state; + + /* UM must re-enable their session before requesting new dumps. */ + if (perfcnt->state & PANFROST_PERFCNT_SESSION_DEAD) + return -EIO; + + /* If we faced a reset during our SAMPLE, the user needs to try again. */ + if (perfcnt->state & PANFROST_PERFCNT_SESSION_INTERRUPTED_BY_RESET) + return -EAGAIN; + } + + return 0; +} + +static int panfrost_perfcnt_disable_locked(struct panfrost_device *pfdev, + struct drm_file *file_priv) +{ + struct panfrost_file_priv *user = file_priv->driver_priv; + struct panfrost_perfcnt *perfcnt = pfdev->perfcnt; + struct iosys_map map = IOSYS_MAP_INIT_VADDR(perfcnt->buf); + + if (user != perfcnt->user) + return -EINVAL; + + scoped_guard(rwsem_read, &pfdev->reset.lock) { + panfrost_perfcnt_hw_disable(pfdev); + perfcnt->user = NULL; + } + + drm_gem_vunmap(&perfcnt->mapping->obj->base.base, &map); + perfcnt->buf = NULL; + panfrost_gem_close(&perfcnt->mapping->obj->base.base, file_priv); + panfrost_gem_mapping_put(perfcnt->mapping); + perfcnt->mapping = NULL; + pm_runtime_put_autosuspend(pfdev->base.dev); + + return 0; } static int panfrost_perfcnt_enable_locked(struct panfrost_device *pfdev, @@ -74,14 +198,29 @@ static int panfrost_perfcnt_enable_locked(struct panfrost_device *pfdev, { struct panfrost_file_priv *user = file_priv->driver_priv; struct panfrost_perfcnt *perfcnt = pfdev->perfcnt; - struct iosys_map map; struct drm_gem_shmem_object *bo; - u32 cfg, as; + struct iosys_map map; int ret; - if (user == perfcnt->user) + if (perfcnt->user == user) { + scoped_guard(rwsem_read, &pfdev->reset.lock) { + if (perfcnt->state & PANFROST_PERFCNT_SESSION_DEAD) { + /* A successful reset might've come through in the time gap + * between the last failed one and this re-enable attempt. + */ + ret = (perfcnt->owns_as_ref) ? 0 : + panfrost_perfcnt_hw_enable(pfdev); + if (!ret) + perfcnt->state = 0; + + return ret; + } + } + return 0; - else if (perfcnt->user) + } + + if (perfcnt->user) return -EBUSY; ret = pm_runtime_get_sync(pfdev->base.dev); @@ -109,65 +248,30 @@ static int panfrost_perfcnt_enable_locked(struct panfrost_device *pfdev, ret = drm_gem_vmap(&bo->base, &map); if (ret) goto err_put_mapping; + perfcnt->buf = map.vaddr; + perfcnt->counterset = counterset; panfrost_gem_internal_set_label(&bo->base, "Perfcnt sample buffer"); - /* - * Invalidate the cache and clear the counters to start from a fresh - * state. - */ - reinit_completion(&pfdev->perfcnt->dump_comp); - gpu_write(pfdev, GPU_INT_CLEAR, - GPU_IRQ_CLEAN_CACHES_COMPLETED | - GPU_IRQ_PERFCNT_SAMPLE_COMPLETED); - gpu_write(pfdev, GPU_CMD, GPU_CMD_PERFCNT_CLEAR); - gpu_write(pfdev, GPU_CMD, GPU_CMD_CLEAN_INV_CACHES); - ret = wait_for_completion_timeout(&pfdev->perfcnt->dump_comp, - msecs_to_jiffies(1000)); - if (!ret) { - ret = -ETIMEDOUT; - goto err_vunmap; - } - - ret = panfrost_mmu_as_get(pfdev, perfcnt->mapping->mmu); - if (ret < 0) - goto err_vunmap; - - as = ret; - cfg = GPU_PERFCNT_CFG_AS(as) | - GPU_PERFCNT_CFG_MODE(GPU_PERFCNT_CFG_MODE_MANUAL); - - /* - * Bifrost GPUs have 2 set of counters, but we're only interested by - * the first one for now. - */ - if (panfrost_model_is_bifrost(pfdev)) - cfg |= GPU_PERFCNT_CFG_SETSEL(counterset); - - gpu_write(pfdev, GPU_PRFCNT_JM_EN, 0xffffffff); - gpu_write(pfdev, GPU_PRFCNT_SHADER_EN, 0xffffffff); - gpu_write(pfdev, GPU_PRFCNT_MMU_L2_EN, 0xffffffff); - - /* - * Due to PRLAM-8186 we need to disable the Tiler before we enable HW - * counters. - */ - if (panfrost_has_hw_issue(pfdev, HW_ISSUE_8186)) - gpu_write(pfdev, GPU_PRFCNT_TILER_EN, 0); - else - gpu_write(pfdev, GPU_PRFCNT_TILER_EN, 0xffffffff); + scoped_guard(rwsem_read, &pfdev->reset.lock) { + /* + * Clear the counters to start from a fresh state. + */ + gpu_write(pfdev, GPU_INT_CLEAR, GPU_IRQ_PERFCNT_SAMPLE_COMPLETED); + gpu_write(pfdev, GPU_CMD, GPU_CMD_PERFCNT_CLEAR); - gpu_write(pfdev, GPU_PERFCNT_CFG, cfg); + ret = panfrost_perfcnt_hw_enable(pfdev); + if (ret) + goto err_vunmap; - if (panfrost_has_hw_issue(pfdev, HW_ISSUE_8186)) - gpu_write(pfdev, GPU_PRFCNT_TILER_EN, 0xffffffff); + perfcnt->user = user; + perfcnt->state = 0; + } /* The BO ref is retained by the mapping. */ drm_gem_object_put(&bo->base); - perfcnt->user = user; - return 0; err_vunmap: @@ -183,35 +287,6 @@ static int panfrost_perfcnt_enable_locked(struct panfrost_device *pfdev, return ret; } -static int panfrost_perfcnt_disable_locked(struct panfrost_device *pfdev, - struct drm_file *file_priv) -{ - struct panfrost_file_priv *user = file_priv->driver_priv; - struct panfrost_perfcnt *perfcnt = pfdev->perfcnt; - struct iosys_map map = IOSYS_MAP_INIT_VADDR(perfcnt->buf); - - if (user != perfcnt->user) - return -EINVAL; - - gpu_write(pfdev, GPU_PRFCNT_JM_EN, 0x0); - gpu_write(pfdev, GPU_PRFCNT_SHADER_EN, 0x0); - gpu_write(pfdev, GPU_PRFCNT_MMU_L2_EN, 0x0); - gpu_write(pfdev, GPU_PRFCNT_TILER_EN, 0); - gpu_write(pfdev, GPU_PERFCNT_CFG, - GPU_PERFCNT_CFG_MODE(GPU_PERFCNT_CFG_MODE_OFF)); - - perfcnt->user = NULL; - drm_gem_vunmap(&perfcnt->mapping->obj->base.base, &map); - perfcnt->buf = NULL; - panfrost_gem_close(&perfcnt->mapping->obj->base.base, file_priv); - panfrost_mmu_as_put(pfdev, perfcnt->mapping->mmu); - panfrost_gem_mapping_put(perfcnt->mapping); - perfcnt->mapping = NULL; - pm_runtime_put_autosuspend(pfdev->base.dev); - - return 0; -} - int panfrost_ioctl_perfcnt_enable(struct drm_device *dev, void *data, struct drm_file *file_priv) { @@ -252,13 +327,16 @@ int panfrost_ioctl_perfcnt_dump(struct drm_device *dev, void *data, if (ret) return ret; + if (req->pad) + return -EINVAL; + mutex_lock(&perfcnt->lock); if (perfcnt->user != file_priv->driver_priv) { ret = -EINVAL; goto out; } - ret = panfrost_perfcnt_dump_locked(pfdev); + ret = panfrost_perfcnt_dump_locked(pfdev, &req->state); if (ret) goto out; @@ -325,18 +403,12 @@ int panfrost_perfcnt_init(struct panfrost_device *pfdev) return -ENOMEM; perfcnt->bosize = size; + pfdev->perfcnt = perfcnt; + mutex_init(&perfcnt->lock); + init_completion(&perfcnt->dump_comp); /* Start with everything disabled. */ - gpu_write(pfdev, GPU_PERFCNT_CFG, - GPU_PERFCNT_CFG_MODE(GPU_PERFCNT_CFG_MODE_OFF)); - gpu_write(pfdev, GPU_PRFCNT_JM_EN, 0); - gpu_write(pfdev, GPU_PRFCNT_SHADER_EN, 0); - gpu_write(pfdev, GPU_PRFCNT_MMU_L2_EN, 0); - gpu_write(pfdev, GPU_PRFCNT_TILER_EN, 0); - - init_completion(&perfcnt->dump_comp); - mutex_init(&perfcnt->lock); - pfdev->perfcnt = perfcnt; + panfrost_perfcnt_hw_disable(pfdev); return 0; } @@ -344,10 +416,27 @@ int panfrost_perfcnt_init(struct panfrost_device *pfdev) void panfrost_perfcnt_fini(struct panfrost_device *pfdev) { /* Disable everything before leaving. */ - gpu_write(pfdev, GPU_PERFCNT_CFG, - GPU_PERFCNT_CFG_MODE(GPU_PERFCNT_CFG_MODE_OFF)); - gpu_write(pfdev, GPU_PRFCNT_JM_EN, 0); - gpu_write(pfdev, GPU_PRFCNT_SHADER_EN, 0); - gpu_write(pfdev, GPU_PRFCNT_MMU_L2_EN, 0); - gpu_write(pfdev, GPU_PRFCNT_TILER_EN, 0); + panfrost_perfcnt_hw_disable(pfdev); +} + +void panfrost_perfcnt_reset(struct panfrost_device *pfdev) +{ + struct panfrost_perfcnt *perfcnt = pfdev->perfcnt; + + if (drm_WARN_ON(&pfdev->base, !perfcnt)) + return; + + lockdep_assert_held(&pfdev->reset.lock); + + if (!perfcnt->user) + return; + + /* All active AS are released during the MMU post_reset. */ + perfcnt->owns_as_ref = false; + perfcnt->state |= PANFROST_PERFCNT_SESSION_INTERRUPTED_BY_RESET; + if (panfrost_perfcnt_hw_enable(pfdev)) + perfcnt->state |= PANFROST_PERFCNT_SESSION_DEAD; + + /* Unblock pending sample requests. */ + complete(&perfcnt->dump_comp); } diff --git a/drivers/gpu/drm/panfrost/panfrost_perfcnt.h b/drivers/gpu/drm/panfrost/panfrost_perfcnt.h index 8bbcf5f5fb33..8b9bc704b634 100644 --- a/drivers/gpu/drm/panfrost/panfrost_perfcnt.h +++ b/drivers/gpu/drm/panfrost/panfrost_perfcnt.h @@ -14,5 +14,6 @@ int panfrost_ioctl_perfcnt_enable(struct drm_device *dev, void *data, struct drm_file *file_priv); int panfrost_ioctl_perfcnt_dump(struct drm_device *dev, void *data, struct drm_file *file_priv); +void panfrost_perfcnt_reset(struct panfrost_device *pfdev); #endif diff --git a/drivers/gpu/drm/panthor/panthor_gem.c b/drivers/gpu/drm/panthor/panthor_gem.c index 72908be5e144..75d462f20b6c 100644 --- a/drivers/gpu/drm/panthor/panthor_gem.c +++ b/drivers/gpu/drm/panthor/panthor_gem.c @@ -744,6 +744,9 @@ static int panthor_gem_mmap(struct drm_gem_object *obj, struct vm_area_struct *v struct panthor_gem_object *bo = to_panthor_bo(obj); int ret; + if (bo->flags & DRM_PANTHOR_BO_NO_MMAP) + return -EINVAL; + if (drm_gem_is_imported(obj)) { /* Reset both vm_ops and vm_private_data, so we don't end up with * vm_ops pointing to our implementation if the dma-buf backend diff --git a/drivers/gpu/drm/panthor/panthor_gpu.c b/drivers/gpu/drm/panthor/panthor_gpu.c index c013d6bf9a59..aa903fda20a5 100644 --- a/drivers/gpu/drm/panthor/panthor_gpu.c +++ b/drivers/gpu/drm/panthor/panthor_gpu.c @@ -317,6 +317,21 @@ int panthor_gpu_l2_power_on(struct panthor_device *ptdev) return panthor_gpu_power_on(ptdev, L2, 1, 20000); } +static inline void panthor_gpu_emit_flush_caches_tp(struct panthor_device *ptdev, + u64 start, u32 l2, u32 lsc, + u32 other, int ret) +{ + u32 duration; + + if (!tracepoint_enabled(gpu_cache_flush) || !start) + return; + + if (check_sub_overflow(ktime_get_ns(), start, &duration)) + duration = U32_MAX; + + trace_gpu_cache_flush(ptdev->base.dev, l2, lsc, other, duration, ret); +} + /** * panthor_gpu_flush_caches() - Flush caches * @ptdev: Device. @@ -330,36 +345,40 @@ int panthor_gpu_flush_caches(struct panthor_device *ptdev, u32 l2, u32 lsc, u32 other) { struct panthor_gpu *gpu = ptdev->gpu; - unsigned long flags; + u64 start = 0; 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(gpu->iomem, GPU_CMD, GPU_FLUSH_CACHES(l2, lsc, other)); - } else { - ret = -EIO; + scoped_guard(spinlock, &ptdev->gpu->reqs_lock) { + if (tracepoint_enabled(gpu_cache_flush)) + start = ktime_get_ns(); + + if (!(ptdev->gpu->pending_reqs & GPU_IRQ_CLEAN_CACHES_COMPLETED)) { + ptdev->gpu->pending_reqs |= GPU_IRQ_CLEAN_CACHES_COMPLETED; + gpu_write(gpu->iomem, GPU_CMD, GPU_FLUSH_CACHES(l2, lsc, other)); + } else { + panthor_gpu_emit_flush_caches_tp(ptdev, start, l2, lsc, + other, -EIO); + 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(gpu->irq.iomem, 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(gpu->irq.iomem, INT_RAWSTAT) & GPU_IRQ_CLEAN_CACHES_COMPLETED)) + ret = -ETIMEDOUT; + else + ptdev->gpu->pending_reqs &= ~GPU_IRQ_CLEAN_CACHES_COMPLETED; + } } + panthor_gpu_emit_flush_caches_tp(ptdev, start, l2, lsc, other, ret); + if (ret) { panthor_device_schedule_reset(ptdev); drm_err(&ptdev->base, "Flush caches timeout"); @@ -378,27 +397,26 @@ int panthor_gpu_soft_reset(struct panthor_device *ptdev) { struct panthor_gpu *gpu = ptdev->gpu; 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(gpu->irq.iomem, INT_CLEAR, GPU_IRQ_RESET_COMPLETED); - gpu_write(gpu->iomem, 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(gpu->irq.iomem, INT_CLEAR, GPU_IRQ_RESET_COMPLETED); + gpu_write(gpu->iomem, 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(gpu->irq.iomem, 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(gpu->irq.iomem, INT_RAWSTAT) & GPU_IRQ_RESET_COMPLETED)) + timedout = true; + else + ptdev->gpu->pending_reqs &= ~GPU_IRQ_RESET_COMPLETED; + } } if (timedout) { @@ -406,7 +424,10 @@ int panthor_gpu_soft_reset(struct panthor_device *ptdev) return -ETIMEDOUT; } - ptdev->gpu->pending_reqs = 0; + scoped_guard(spinlock, &ptdev->gpu->reqs_lock) { + ptdev->gpu->pending_reqs = 0; + } + return 0; } diff --git a/drivers/gpu/drm/panthor/panthor_mmu.c b/drivers/gpu/drm/panthor/panthor_mmu.c index 9f63a048df61..7ed89d484d0f 100644 --- a/drivers/gpu/drm/panthor/panthor_mmu.c +++ b/drivers/gpu/drm/panthor/panthor_mmu.c @@ -620,8 +620,7 @@ static int panthor_mmu_as_enable(struct panthor_device *ptdev, u32 as_nr, return as_send_cmd_and_wait(ptdev, as_nr, AS_COMMAND_UPDATE); } -static int panthor_mmu_as_disable(struct panthor_device *ptdev, u32 as_nr, - bool recycle_slot) +static int panthor_mmu_as_disable(struct panthor_device *ptdev, u32 as_nr) { struct panthor_mmu *mmu = ptdev->mmu; struct panthor_vm *vm = ptdev->mmu->as.slots[as_nr].vm; @@ -634,7 +633,7 @@ static int panthor_mmu_as_disable(struct panthor_device *ptdev, u32 as_nr, /* Flush+invalidate RW caches, invalidate RO ones. */ ret = panthor_gpu_flush_caches(ptdev, CACHE_CLEAN | CACHE_INV, - CACHE_CLEAN | CACHE_INV, CACHE_INV); + CACHE_CLEAN | CACHE_INV, 0); if (ret) return ret; @@ -645,12 +644,6 @@ static int panthor_mmu_as_disable(struct panthor_device *ptdev, u32 as_nr, return ret; } - /* If the slot is going to be used immediately, don't bother changing - * the config. - */ - if (recycle_slot) - return 0; - gpu_write64(mmu->iomem, AS_TRANSTAB(as_nr), 0); gpu_write64(mmu->iomem, AS_MEMATTR(as_nr), 0); gpu_write64(mmu->iomem, AS_TRANSCFG(as_nr), AS_TRANSCFG_ADRMODE_UNMAPPED); @@ -777,7 +770,7 @@ int panthor_vm_active(struct panthor_vm *vm) drm_WARN_ON(&ptdev->base, refcount_read(&lru_vm->as.active_cnt)); as = lru_vm->as.id; - ret = panthor_mmu_as_disable(ptdev, as, true); + ret = panthor_mmu_as_disable(ptdev, as); if (ret) goto out_unlock; @@ -919,7 +912,7 @@ static void panthor_vm_declare_unusable(struct panthor_vm *vm) vm->unusable = true; mutex_lock(&ptdev->mmu->as.slots_lock); if (vm->as.id >= 0 && drm_dev_enter(&ptdev->base, &cookie)) { - panthor_mmu_as_disable(ptdev, vm->as.id, false); + panthor_mmu_as_disable(ptdev, vm->as.id); drm_dev_exit(cookie); } mutex_unlock(&ptdev->mmu->as.slots_lock); @@ -1836,13 +1829,12 @@ static void panthor_vm_unlock_region(struct panthor_vm *vm) if (vm->as.id >= 0) { int ret; - /* flush+invalidate RW caches and invalidate RO ones. + /* flush+invalidate RW caches. * TODO: See if we can use FLUSH_PA_RANGE when the physical * range is narrow enough and the HW supports it. */ ret = panthor_gpu_flush_caches(ptdev, CACHE_CLEAN | CACHE_INV, - CACHE_CLEAN | CACHE_INV, - CACHE_INV); + CACHE_CLEAN | CACHE_INV, 0); /* Unlock the region if the flush is effective. */ if (!ret) @@ -1912,7 +1904,7 @@ static void panthor_mmu_irq_handler(struct panthor_device *ptdev, u32 status) ptdev->mmu->as.slots[as].vm->unhandled_fault = true; /* Disable the MMU to kill jobs on this AS. */ - panthor_mmu_as_disable(ptdev, as, false); + panthor_mmu_as_disable(ptdev, as); mutex_unlock(&ptdev->mmu->as.slots_lock); status &= ~mask; @@ -1941,7 +1933,7 @@ void panthor_mmu_suspend(struct panthor_device *ptdev) if (vm) { drm_WARN_ON(&ptdev->base, - panthor_mmu_as_disable(ptdev, i, false)); + panthor_mmu_as_disable(ptdev, i)); panthor_vm_release_as_locked(vm); } } @@ -2066,7 +2058,7 @@ static void panthor_vm_free(struct drm_gpuvm *gpuvm) int cookie; if (drm_dev_enter(&ptdev->base, &cookie)) { - panthor_mmu_as_disable(ptdev, vm->as.id, false); + panthor_mmu_as_disable(ptdev, vm->as.id); drm_dev_exit(cookie); } @@ -3361,7 +3353,7 @@ void panthor_mmu_unplug(struct panthor_device *ptdev) if (vm) { drm_WARN_ON(&ptdev->base, - panthor_mmu_as_disable(ptdev, i, false)); + panthor_mmu_as_disable(ptdev, i)); panthor_vm_release_as_locked(vm); } } diff --git a/drivers/gpu/drm/panthor/panthor_trace.h b/drivers/gpu/drm/panthor/panthor_trace.h index 6ffeb4fe6599..bd8652549ab4 100644 --- a/drivers/gpu/drm/panthor/panthor_trace.h +++ b/drivers/gpu/drm/panthor/panthor_trace.h @@ -76,6 +76,44 @@ TRACE_EVENT(gpu_job_irq, __entry->events, __entry->duration_ns) ); +/** + * gpu_cache_flush - emitted after cache flush completes + * @dev: pointer to the &struct device, for printing the device name + * @l2: "l2" flush flags + * @lsc: "lsc" flush flags + * @other: "other" flush flags + * @duration_ns: how long the cache flush operation took, in nanoseconds + * @ret: return status, 0 == success, negative errno on error + * + * Begins measuring after any initial lock contention around the locks needed + * for flushing caches, but before the actual cache flush is requested. Stops + * measuring and is emitted after flush operation is over. + */ +TRACE_EVENT(gpu_cache_flush, + TP_PROTO(const struct device *dev, u32 l2, u32 lsc, u32 other, + u32 duration_ns, int ret), + TP_ARGS(dev, l2, lsc, other, duration_ns, ret), + TP_STRUCT__entry( + __string(dev_name, dev_name(dev)) + __field(u32, l2) + __field(u32, lsc) + __field(u32, other) + __field(u32, duration_ns) + __field(int, ret) + ), + TP_fast_assign( + __assign_str(dev_name); + __entry->l2 = l2; + __entry->lsc = lsc; + __entry->other = other; + __entry->duration_ns = duration_ns; + __entry->ret = ret; + ), + TP_printk("%s: l2=0x%x lsc=0x%x other=0x%x duration_ns=%u ret=%d", + __get_str(dev_name), __entry->l2, __entry->lsc, + __entry->other, __entry->duration_ns, __entry->ret) +); + #endif /* __PANTHOR_TRACE_H__ */ #undef TRACE_INCLUDE_PATH diff --git a/drivers/gpu/drm/pl111/pl111_display.c b/drivers/gpu/drm/pl111/pl111_display.c index 5d10bc5fdf1f..e1b513d36c27 100644 --- a/drivers/gpu/drm/pl111/pl111_display.c +++ b/drivers/gpu/drm/pl111/pl111_display.c @@ -267,14 +267,12 @@ static void pl111_display_enable(struct drm_simple_display_pipe *pipe, if (priv->variant->st_bitmux_control) cntl |= CNTL_ST_LCDBPP24_PACKED; break; - case DRM_FORMAT_ABGR8888: case DRM_FORMAT_XBGR8888: if (priv->variant->st_bitmux_control) cntl |= CNTL_LCDBPP24 | CNTL_BGR; else cntl |= CNTL_LCDBPP24; break; - case DRM_FORMAT_ARGB8888: case DRM_FORMAT_XRGB8888: if (priv->variant->st_bitmux_control) cntl |= CNTL_LCDBPP24; @@ -297,13 +295,11 @@ static void pl111_display_enable(struct drm_simple_display_pipe *pipe, else cntl |= CNTL_LCDBPP16_565 | CNTL_BGR; break; - case DRM_FORMAT_ABGR1555: case DRM_FORMAT_XBGR1555: cntl |= CNTL_LCDBPP16; if (priv->variant->st_bitmux_control) cntl |= CNTL_ST_1XBPP_5551 | CNTL_BGR; break; - case DRM_FORMAT_ARGB1555: case DRM_FORMAT_XRGB1555: cntl |= CNTL_LCDBPP16; if (priv->variant->st_bitmux_control) @@ -311,13 +307,11 @@ static void pl111_display_enable(struct drm_simple_display_pipe *pipe, else cntl |= CNTL_BGR; break; - case DRM_FORMAT_ABGR4444: case DRM_FORMAT_XBGR4444: cntl |= CNTL_LCDBPP16_444; if (priv->variant->st_bitmux_control) cntl |= CNTL_ST_1XBPP_444 | CNTL_BGR; break; - case DRM_FORMAT_ARGB4444: case DRM_FORMAT_XRGB4444: cntl |= CNTL_LCDBPP16_444; if (priv->variant->st_bitmux_control) diff --git a/drivers/gpu/drm/pl111/pl111_drv.c b/drivers/gpu/drm/pl111/pl111_drv.c index 8ec659b3c08e..0e97261e988d 100644 --- a/drivers/gpu/drm/pl111/pl111_drv.c +++ b/drivers/gpu/drm/pl111/pl111_drv.c @@ -342,13 +342,9 @@ static void pl111_amba_shutdown(struct amba_device *amba_dev) * This early variant lacks the 565 and 444 pixel formats. */ static const u32 pl110_pixel_formats[] = { - DRM_FORMAT_ABGR8888, DRM_FORMAT_XBGR8888, - DRM_FORMAT_ARGB8888, DRM_FORMAT_XRGB8888, - DRM_FORMAT_ABGR1555, DRM_FORMAT_XBGR1555, - DRM_FORMAT_ARGB1555, DRM_FORMAT_XRGB1555, }; @@ -362,19 +358,13 @@ static const struct pl111_variant_data pl110_variant = { /* RealView, Versatile Express etc use this modern variant */ static const u32 pl111_pixel_formats[] = { - DRM_FORMAT_ABGR8888, DRM_FORMAT_XBGR8888, - DRM_FORMAT_ARGB8888, DRM_FORMAT_XRGB8888, DRM_FORMAT_BGR565, DRM_FORMAT_RGB565, - DRM_FORMAT_ABGR1555, DRM_FORMAT_XBGR1555, - DRM_FORMAT_ARGB1555, DRM_FORMAT_XRGB1555, - DRM_FORMAT_ABGR4444, DRM_FORMAT_XBGR4444, - DRM_FORMAT_ARGB4444, DRM_FORMAT_XRGB4444, }; @@ -388,19 +378,13 @@ static const struct pl111_variant_data pl111_variant = { static const u32 pl110_nomadik_pixel_formats[] = { DRM_FORMAT_RGB888, DRM_FORMAT_BGR888, - DRM_FORMAT_ABGR8888, DRM_FORMAT_XBGR8888, - DRM_FORMAT_ARGB8888, DRM_FORMAT_XRGB8888, DRM_FORMAT_BGR565, DRM_FORMAT_RGB565, - DRM_FORMAT_ABGR1555, DRM_FORMAT_XBGR1555, - DRM_FORMAT_ARGB1555, DRM_FORMAT_XRGB1555, - DRM_FORMAT_ABGR4444, DRM_FORMAT_XBGR4444, - DRM_FORMAT_ARGB4444, DRM_FORMAT_XRGB4444, }; diff --git a/drivers/gpu/drm/pl111/pl111_versatile.c b/drivers/gpu/drm/pl111/pl111_versatile.c index 0d8331a3909f..9a60f10231b1 100644 --- a/drivers/gpu/drm/pl111/pl111_versatile.c +++ b/drivers/gpu/drm/pl111/pl111_versatile.c @@ -209,9 +209,7 @@ static void pl111_versatile_enable(struct drm_device *drm, u32 format) drm_info(drm, "enable Versatile CLCD connectors\n"); switch (format) { - case DRM_FORMAT_ABGR8888: case DRM_FORMAT_XBGR8888: - case DRM_FORMAT_ARGB8888: case DRM_FORMAT_XRGB8888: val |= SYS_CLCD_MODE_888; break; @@ -221,9 +219,7 @@ static void pl111_versatile_enable(struct drm_device *drm, u32 format) case DRM_FORMAT_RGB565: val |= SYS_CLCD_MODE_565_B_LSB; break; - case DRM_FORMAT_ABGR1555: case DRM_FORMAT_XBGR1555: - case DRM_FORMAT_ARGB1555: case DRM_FORMAT_XRGB1555: val |= SYS_CLCD_MODE_5551; break; @@ -266,44 +262,30 @@ static void pl111_realview_clcd_enable(struct drm_device *drm, u32 format) /* PL110 pixel formats for Integrator, vanilla PL110 */ static const u32 pl110_integrator_pixel_formats[] = { - DRM_FORMAT_ABGR8888, DRM_FORMAT_XBGR8888, - DRM_FORMAT_ARGB8888, DRM_FORMAT_XRGB8888, - DRM_FORMAT_ABGR1555, DRM_FORMAT_XBGR1555, - DRM_FORMAT_ARGB1555, DRM_FORMAT_XRGB1555, }; /* Extended PL110 pixel formats for Integrator and Versatile */ static const u32 pl110_versatile_pixel_formats[] = { - DRM_FORMAT_ABGR8888, DRM_FORMAT_XBGR8888, - DRM_FORMAT_ARGB8888, DRM_FORMAT_XRGB8888, DRM_FORMAT_BGR565, /* Uses external PLD */ DRM_FORMAT_RGB565, /* Uses external PLD */ - DRM_FORMAT_ABGR1555, DRM_FORMAT_XBGR1555, - DRM_FORMAT_ARGB1555, DRM_FORMAT_XRGB1555, }; static const u32 pl111_realview_pixel_formats[] = { - DRM_FORMAT_ABGR8888, DRM_FORMAT_XBGR8888, - DRM_FORMAT_ARGB8888, DRM_FORMAT_XRGB8888, DRM_FORMAT_BGR565, DRM_FORMAT_RGB565, - DRM_FORMAT_ABGR1555, DRM_FORMAT_XBGR1555, - DRM_FORMAT_ARGB1555, DRM_FORMAT_XRGB1555, - DRM_FORMAT_ABGR4444, DRM_FORMAT_XBGR4444, - DRM_FORMAT_ARGB4444, DRM_FORMAT_XRGB4444, }; diff --git a/drivers/gpu/drm/rockchip/dw_hdmi_qp-rockchip.c b/drivers/gpu/drm/rockchip/dw_hdmi_qp-rockchip.c index 9c4cf68d79d5..df0e2bb1eedc 100644 --- a/drivers/gpu/drm/rockchip/dw_hdmi_qp-rockchip.c +++ b/drivers/gpu/drm/rockchip/dw_hdmi_qp-rockchip.c @@ -681,20 +681,20 @@ static int dw_hdmi_qp_rockchip_bind(struct device *dev, struct device *master, drm_encoder_helper_add(encoder, &dw_hdmi_qp_rockchip_encoder_helper_funcs); ret = drmm_encoder_init(drm, encoder, NULL, DRM_MODE_ENCODER_TMDS, NULL); if (ret) - return dev_err_probe(hdmi->dev, ret, "Failed to init encoder"); - - platform_set_drvdata(pdev, hdmi); + return dev_err_probe(hdmi->dev, ret, "Failed to init encoder\n"); hdmi->hdmi = dw_hdmi_qp_bind(pdev, encoder, &plat_data); if (IS_ERR(hdmi->hdmi)) return dev_err_probe(hdmi->dev, PTR_ERR(hdmi->hdmi), - "Failed to bind dw-hdmi-qp"); + "Failed to bind dw-hdmi-qp\n"); connector = drm_bridge_connector_init(drm, encoder); if (IS_ERR(connector)) return dev_err_probe(hdmi->dev, PTR_ERR(connector), "Failed to init bridge connector\n"); + platform_set_drvdata(pdev, hdmi); + return 0; } @@ -704,6 +704,8 @@ static void dw_hdmi_qp_rockchip_unbind(struct device *dev, { struct rockchip_hdmi_qp *hdmi = dev_get_drvdata(dev); + dev_set_drvdata(dev, NULL); + cancel_delayed_work_sync(&hdmi->hpd_work); } @@ -726,6 +728,11 @@ static int __maybe_unused dw_hdmi_qp_rockchip_suspend(struct device *dev) { struct rockchip_hdmi_qp *hdmi = dev_get_drvdata(dev); + if (!hdmi) + return 0; + + cancel_delayed_work_sync(&hdmi->hpd_work); + dw_hdmi_qp_suspend(dev, hdmi->hdmi); return 0; @@ -735,6 +742,9 @@ static int __maybe_unused dw_hdmi_qp_rockchip_resume(struct device *dev) { struct rockchip_hdmi_qp *hdmi = dev_get_drvdata(dev); + if (!hdmi) + return 0; + hdmi->ctrl_ops->io_init(hdmi); dw_hdmi_qp_resume(dev, hdmi->hdmi); diff --git a/drivers/gpu/drm/tegra/submit.c b/drivers/gpu/drm/tegra/submit.c index e5841857c937..658396f2e954 100644 --- a/drivers/gpu/drm/tegra/submit.c +++ b/drivers/gpu/drm/tegra/submit.c @@ -530,6 +530,7 @@ int tegra_drm_ioctl_channel_submit(struct drm_device *drm, void *data, if (args->syncobj_in) { struct dma_fence *fence; + long wait_err; err = drm_syncobj_find_fence(file, args->syncobj_in, 0, 0, &fence); if (err) { @@ -537,10 +538,15 @@ int tegra_drm_ioctl_channel_submit(struct drm_device *drm, void *data, goto unlock; } - err = dma_fence_wait_timeout(fence, true, msecs_to_jiffies(10000)); + wait_err = dma_fence_wait_timeout(fence, true, msecs_to_jiffies(10000)); dma_fence_put(fence); - if (err) { + if (wait_err == 0) { SUBMIT_ERR(context, "wait for syncobj_in timed out"); + err = -ETIMEDOUT; + goto unlock; + } else if (wait_err < 0) { + /* In practice, -ERESTARTSYS */ + err = wait_err; goto unlock; } } @@ -649,9 +655,11 @@ int tegra_drm_ioctl_channel_submit(struct drm_device *drm, void *data, if (IS_ERR(fence)) { err = PTR_ERR(fence); SUBMIT_ERR(context, "failed to create postfence: %d", err); + goto put_job; } drm_syncobj_replace_fence(syncobj, fence); + dma_fence_put(fence); } goto put_job; diff --git a/drivers/gpu/drm/tegra/uapi.c b/drivers/gpu/drm/tegra/uapi.c index c0ac6b45f2d7..bee310b07eb0 100644 --- a/drivers/gpu/drm/tegra/uapi.c +++ b/drivers/gpu/drm/tegra/uapi.c @@ -7,7 +7,7 @@ #include #include -#include +#include #include "drm.h" #include "uapi.h" diff --git a/drivers/gpu/drm/tests/drm_hdmi_state_helper_test.c b/drivers/gpu/drm/tests/drm_hdmi_state_helper_test.c index 353a261d42da..f8ae1a0bd5c0 100644 --- a/drivers/gpu/drm/tests/drm_hdmi_state_helper_test.c +++ b/drivers/gpu/drm/tests/drm_hdmi_state_helper_test.c @@ -2929,15 +2929,6 @@ static void drm_test_check_infoframes(struct kunit *test) old_hdmi_update_failures = priv->hdmi_update_failures; - ret = drm_atomic_check_only(state); - if (ret == -EDEADLK) { - drm_atomic_commit_clear(state); - ret = drm_modeset_backoff(&ctx); - if (!ret) - goto retry_crtc_state; - } - KUNIT_ASSERT_EQ(test, ret, 0); - ret = drm_atomic_commit(state); if (ret == -EDEADLK) { drm_atomic_commit_clear(state); @@ -3034,15 +3025,6 @@ static void drm_test_check_reject_avi_infoframe(struct kunit *test) old_hdmi_update_failures = priv->hdmi_update_failures; - ret = drm_atomic_check_only(state); - if (ret == -EDEADLK) { - drm_atomic_commit_clear(state); - ret = drm_modeset_backoff(&ctx); - if (!ret) - goto retry_crtc_state; - } - KUNIT_ASSERT_EQ(test, ret, 0); - ret = drm_atomic_commit(state); if (ret == -EDEADLK) { drm_atomic_commit_clear(state); @@ -3153,15 +3135,6 @@ static void drm_test_check_reject_hdr_infoframe_bpc_8(struct kunit *test) old_hdmi_update_failures = priv->hdmi_update_failures; - ret = drm_atomic_check_only(state); - if (ret == -EDEADLK) { - drm_atomic_commit_clear(state); - ret = drm_modeset_backoff(&ctx); - if (!ret) - goto retry_conn_state; - } - KUNIT_ASSERT_EQ(test, ret, 0); - ret = drm_atomic_commit(state); if (ret == -EDEADLK) { drm_atomic_commit_clear(state); @@ -3276,15 +3249,6 @@ static void drm_test_check_reject_hdr_infoframe_bpc_10(struct kunit *test) old_hdmi_update_failures = priv->hdmi_update_failures; - ret = drm_atomic_check_only(state); - if (ret == -EDEADLK) { - drm_atomic_commit_clear(state); - ret = drm_modeset_backoff(&ctx); - if (!ret) - goto retry_conn_state; - } - KUNIT_ASSERT_EQ(test, ret, 0); - ret = drm_atomic_commit(state); if (ret == -EDEADLK) { drm_atomic_commit_clear(state); @@ -3387,15 +3351,6 @@ static void drm_test_check_reject_audio_infoframe(struct kunit *test) old_hdmi_update_failures = priv->hdmi_update_failures; - ret = drm_atomic_check_only(state); - if (ret == -EDEADLK) { - drm_atomic_commit_clear(state); - ret = drm_modeset_backoff(&ctx); - if (!ret) - goto retry_crtc_state; - } - KUNIT_ASSERT_EQ(test, ret, 0); - ret = drm_atomic_commit(state); if (ret == -EDEADLK) { drm_atomic_commit_clear(state); @@ -3438,15 +3393,6 @@ static void drm_test_check_reject_audio_infoframe(struct kunit *test) old_hdmi_update_failures = priv->hdmi_update_failures; - ret = drm_atomic_check_only(state); - if (ret == -EDEADLK) { - drm_atomic_commit_clear(state); - ret = drm_modeset_backoff(&ctx); - if (!ret) - goto retry_crtc_state_2; - } - KUNIT_ASSERT_EQ(test, ret, 0); - ret = drm_atomic_commit(state); if (ret == -EDEADLK) { drm_atomic_commit_clear(state); diff --git a/drivers/gpu/drm/tiny/appletbdrm.c b/drivers/gpu/drm/tiny/appletbdrm.c index ef71b9957961..f4e0340f98ff 100644 --- a/drivers/gpu/drm/tiny/appletbdrm.c +++ b/drivers/gpu/drm/tiny/appletbdrm.c @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -724,7 +725,7 @@ static int appletbdrm_setup_mode_config(struct appletbdrm_device *adev) ret = drm_connector_attach_encoder(connector, encoder); if (ret) { - drm_err(drm, "Failed to initialize simple display pipe\n"); + drm_err(drm, "Failed to attach connector to encoder\n"); return ret; } @@ -821,6 +822,48 @@ static void appletbdrm_shutdown(struct usb_interface *intf) drm_atomic_helper_shutdown(&adev->drm); } +static int appletbdrm_suspend(struct usb_interface *intf, pm_message_t message) +{ + struct appletbdrm_device *adev = usb_get_intfdata(intf); + + return drm_mode_config_helper_suspend(&adev->drm); +} + +static int appletbdrm_resume(struct usb_interface *intf) +{ + struct appletbdrm_device *adev = usb_get_intfdata(intf); + + return drm_mode_config_helper_resume(&adev->drm); +} + +static int appletbdrm_reset_resume(struct usb_interface *intf) +{ + struct appletbdrm_device *adev = usb_get_intfdata(intf); + struct drm_device *drm = &adev->drm; + int ret, resume_ret; + + /* + * A reset puts the device back into its initial state, where it + * expects the same handshake as during probe. Resume the DRM side + * even if the handshake fails, so that the state saved on suspend + * is released. + */ + ret = appletbdrm_get_information(adev); + if (ret) { + drm_err(drm, "Failed to get display information\n"); + goto resume; + } + + ret = appletbdrm_signal_readiness(adev); + if (ret) + drm_err(drm, "Failed to signal readiness\n"); + +resume: + resume_ret = drm_mode_config_helper_resume(drm); + + return ret ? ret : resume_ret; +} + static const struct usb_device_id appletbdrm_usb_id_table[] = { { USB_DEVICE_INTERFACE_CLASS(0x05ac, 0x8302, USB_CLASS_AUDIO_VIDEO) }, {} @@ -832,6 +875,9 @@ static struct usb_driver appletbdrm_usb_driver = { .probe = appletbdrm_probe, .disconnect = appletbdrm_disconnect, .shutdown = appletbdrm_shutdown, + .suspend = appletbdrm_suspend, + .resume = appletbdrm_resume, + .reset_resume = appletbdrm_reset_resume, .id_table = appletbdrm_usb_id_table, }; module_usb_driver(appletbdrm_usb_driver); diff --git a/drivers/gpu/drm/vc4/vc4_bo.c b/drivers/gpu/drm/vc4/vc4_bo.c index 7b8b3364000f..da4b11b7ce9f 100644 --- a/drivers/gpu/drm/vc4/vc4_bo.c +++ b/drivers/gpu/drm/vc4/vc4_bo.c @@ -303,7 +303,8 @@ static void vc4_bo_purge(struct drm_gem_object *obj) drm_vma_node_unmap(&obj->vma_node, dev->anon_inode->i_mapping); - dma_free_wc(dev->dev, obj->size, bo->base.vaddr, bo->base.dma_addr); + dma_free_wc(drm_dev_dma_dev(dev), obj->size, bo->base.vaddr, + bo->base.dma_addr); bo->base.vaddr = NULL; bo->madv = __VC4_MADV_PURGED; } diff --git a/drivers/gpu/drm/vc4/vc4_drv.c b/drivers/gpu/drm/vc4/vc4_drv.c index 7b64e1ed02d4..6072b4e1ffed 100644 --- a/drivers/gpu/drm/vc4/vc4_drv.c +++ b/drivers/gpu/drm/vc4/vc4_drv.c @@ -24,10 +24,8 @@ #include #include #include -#include #include #include -#include #include #include @@ -273,16 +271,6 @@ static void vc4_component_unbind_all(void *ptr) component_unbind_all(vc4->dev, &vc4->base); } -static const struct of_device_id vc4_dma_range_matches[] = { - { .compatible = "brcm,bcm2711-hvs" }, - { .compatible = "brcm,bcm2712-hvs" }, - { .compatible = "brcm,bcm2835-hvs" }, - { .compatible = "brcm,bcm2835-v3d" }, - { .compatible = "brcm,cygnus-v3d" }, - { .compatible = "brcm,vc4-v3d" }, - {} -}; - static int vc4_drm_bind(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); @@ -295,8 +283,6 @@ static int vc4_drm_bind(struct device *dev) enum vc4_gen gen; int ret = 0; - dev->coherent_dma_mask = DMA_BIT_MASK(32); - gen = (enum vc4_gen)of_device_get_match_data(dev); if (gen > VC4_GEN_4) @@ -304,21 +290,6 @@ static int vc4_drm_bind(struct device *dev) else driver = &vc4_drm_driver; - if (gen >= VC4_GEN_6_C) - dma_set_mask_and_coherent(dev, DMA_BIT_MASK(36)); - else - dma_set_mask_and_coherent(dev, DMA_BIT_MASK(32)); - - node = of_find_matching_node_and_match(NULL, vc4_dma_range_matches, - NULL); - if (node) { - ret = of_dma_configure(dev, node, true); - of_node_put(node); - - if (ret) - return ret; - } - vc4 = devm_drm_dev_alloc(dev, driver, struct vc4_dev, base); if (IS_ERR(vc4)) return PTR_ERR(vc4); diff --git a/drivers/gpu/drm/vc4/vc4_gem.c b/drivers/gpu/drm/vc4/vc4_gem.c index 0fef9b48d3c6..e76f686bb374 100644 --- a/drivers/gpu/drm/vc4/vc4_gem.c +++ b/drivers/gpu/drm/vc4/vc4_gem.c @@ -32,6 +32,7 @@ #include #include #include +#include #include "vc4_drv.h" #include "vc4_regs.h" @@ -984,7 +985,7 @@ vc4_wait_bo_ioctl(struct drm_device *dev, void *data, int ret; struct drm_vc4_wait_bo *args = data; unsigned long timeout_jiffies = - usecs_to_jiffies(div_u64(args->timeout_ns, 1000)); + drm_timeout_rel_to_jiffies(args->timeout_ns); ktime_t start = ktime_get(); u64 delta_ns; diff --git a/drivers/gpu/drm/vc4/vc4_hvs.c b/drivers/gpu/drm/vc4/vc4_hvs.c index e715147d091c..b1fb096858cc 100644 --- a/drivers/gpu/drm/vc4/vc4_hvs.c +++ b/drivers/gpu/drm/vc4/vc4_hvs.c @@ -22,6 +22,7 @@ #include #include #include +#include #include #include @@ -1662,6 +1663,15 @@ static int vc4_hvs_bind(struct device *dev, struct device *master, void *data) hvs->regset.nregs = ARRAY_SIZE(vc4_hvs_regs); } + if (vc4->gen >= VC4_GEN_6_C) { + ret = dma_set_mask_and_coherent(dev, DMA_BIT_MASK(36)); + if (ret) + return ret; + } + + if (drm_dev_dma_dev(drm) == drm->dev) + drm_dev_set_dma_dev(drm, dev); + if (vc4->gen >= VC4_GEN_5) { struct rpi_firmware *firmware; struct device_node *node; diff --git a/drivers/gpu/drm/vc4/vc4_v3d.c b/drivers/gpu/drm/vc4/vc4_v3d.c index 6844e8f3948c..29737ae6a745 100644 --- a/drivers/gpu/drm/vc4/vc4_v3d.c +++ b/drivers/gpu/drm/vc4/vc4_v3d.c @@ -441,6 +441,13 @@ static int vc4_v3d_bind(struct device *dev, struct device *master, void *data) vc4->v3d = v3d; v3d->vc4 = vc4; + /* + * In headless setups where HVS is absent, use V3D as the fallback + * DMA controller for buffer allocations. + */ + if (drm_dev_dma_dev(drm) == drm->dev) + drm_dev_set_dma_dev(drm, dev); + v3d->clk = devm_clk_get_optional(dev, NULL); if (IS_ERR(v3d->clk)) return dev_err_probe(dev, PTR_ERR(v3d->clk), "Failed to get V3D clock\n"); @@ -536,7 +543,6 @@ static void vc4_v3d_dev_remove(struct platform_device *pdev) const struct of_device_id vc4_v3d_dt_match[] = { { .compatible = "brcm,bcm2835-v3d" }, { .compatible = "brcm,cygnus-v3d" }, - { .compatible = "brcm,vc4-v3d" }, {} }; diff --git a/drivers/gpu/drm/verisilicon/vs_cursor_plane.c b/drivers/gpu/drm/verisilicon/vs_cursor_plane.c index da456dced88a..b1e71da48350 100644 --- a/drivers/gpu/drm/verisilicon/vs_cursor_plane.c +++ b/drivers/gpu/drm/verisilicon/vs_cursor_plane.c @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -177,7 +178,8 @@ static void vs_cursor_plane_atomic_update(struct drm_plane *plane, break; } - dma_addr = vs_fb_get_dma_addr(fb, &state->src); + /* hardware handles clipping as seen below */ + dma_addr = drm_fb_dma_get_gem_addr(fb, state, 0); regmap_write(dc->regs, VSDC_CURSOR_ADDRESS(output), lower_32_bits(dma_addr)); @@ -200,7 +202,7 @@ static void vs_cursor_plane_atomic_update(struct drm_plane *plane, } else { regmap_update_bits(dc->regs, VSDC_CURSOR_CONFIG(output), VSDC_CURSOR_CONFIG_X_OFF_MASK, - -state->crtc_x); + VSDC_CURSOR_CONFIG_X_OFF(-state->crtc_x)); regmap_update_bits(dc->regs, VSDC_CURSOR_LOCATION(output), VSDC_CURSOR_LOCATION_X_MASK, 0); } @@ -214,7 +216,7 @@ static void vs_cursor_plane_atomic_update(struct drm_plane *plane, } else { regmap_update_bits(dc->regs, VSDC_CURSOR_CONFIG(output), VSDC_CURSOR_CONFIG_Y_OFF_MASK, - -state->crtc_y); + VSDC_CURSOR_CONFIG_Y_OFF(-state->crtc_y)); regmap_update_bits(dc->regs, VSDC_CURSOR_LOCATION(output), VSDC_CURSOR_LOCATION_Y_MASK, 0); } diff --git a/drivers/gpu/drm/verisilicon/vs_plane.c b/drivers/gpu/drm/verisilicon/vs_plane.c index 7ddb9d2dcb83..f189c0bba5b7 100644 --- a/drivers/gpu/drm/verisilicon/vs_plane.c +++ b/drivers/gpu/drm/verisilicon/vs_plane.c @@ -107,26 +107,6 @@ int drm_format_to_vs_format(u32 drm_format, struct vs_format *vs_format) return 0; } -dma_addr_t vs_fb_get_dma_addr(struct drm_framebuffer *fb, - const struct drm_rect *src_rect) -{ - struct drm_gem_dma_object *gem; - dma_addr_t dma_addr; - - /* Get the physical address of the buffer in memory */ - gem = drm_fb_dma_get_gem_obj(fb, 0); - - /* Compute the start of the displayed memory */ - dma_addr = gem->dma_addr + fb->offsets[0]; - - /* Fixup framebuffer address for src coordinates */ - dma_addr += drm_format_info_min_pitch(fb->format, 0, - src_rect->x1 >> 16); - dma_addr += (src_rect->y1 >> 16) * fb->pitches[0]; - - return dma_addr; -} - struct drm_plane_state *vs_plane_duplicate_state(struct drm_plane *plane) { struct vs_plane_state *vs_state, *vs_state_old; diff --git a/drivers/gpu/drm/verisilicon/vs_plane.h b/drivers/gpu/drm/verisilicon/vs_plane.h index 32ed1d70f3b8..e4f82f1fc6e9 100644 --- a/drivers/gpu/drm/verisilicon/vs_plane.h +++ b/drivers/gpu/drm/verisilicon/vs_plane.h @@ -75,8 +75,6 @@ static inline struct vs_plane_state *to_vs_plane_state(struct drm_plane_state *s } int drm_format_to_vs_format(u32 drm_format, struct vs_format *vs_format); -dma_addr_t vs_fb_get_dma_addr(struct drm_framebuffer *fb, - const struct drm_rect *src_rect); struct drm_plane_state *vs_plane_duplicate_state(struct drm_plane *plane); void vs_plane_destroy_state(struct drm_plane *plane, diff --git a/drivers/gpu/drm/verisilicon/vs_primary_plane.c b/drivers/gpu/drm/verisilicon/vs_primary_plane.c index 8e9449169301..d5a8d61e9a48 100644 --- a/drivers/gpu/drm/verisilicon/vs_primary_plane.c +++ b/drivers/gpu/drm/verisilicon/vs_primary_plane.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -126,7 +127,11 @@ static void vs_primary_plane_atomic_update(struct drm_plane *plane, VSDC_FB_CONFIG_UV_SWIZZLE_EN, vs_state->format.uv_swizzle); - dma_addr = vs_fb_get_dma_addr(fb, &state->src); + /* + * Primary plane cannot be moved, no clipping is involved, + * so the non-clipped framebuffer address can be used. + */ + dma_addr = drm_fb_dma_get_gem_addr(fb, state, 0); regmap_write(dc->regs, VSDC_FB_ADDRESS(output), lower_32_bits(dma_addr)); diff --git a/drivers/gpu/drm/vkms/tests/gen_yuv_conversion.py b/drivers/gpu/drm/vkms/tests/gen_yuv_conversion.py new file mode 100755 index 000000000000..f4d226137cc2 --- /dev/null +++ b/drivers/gpu/drm/vkms/tests/gen_yuv_conversion.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0+ +""" +Derive the VKMS YCbCr -> RGB conversion constants and the vkms-format KUnit +reference values. + +It produces: + 1. The S31.32 fixed-point conversion matrices used in + drivers/gpu/drm/vkms/vkms_formats.c and asserted by + vkms_format_test_conversion_matrix. + 2. The 16-bit reference YCbCr inputs for the limited-range + yuv_u16_to_argb_u16 round-trip cases (the values changed by the fix). + +Requires numpy. +""" + +import numpy as np + +FP = 1 << 32 # S31.32 scale: fixed = round(coeff * 2^32) + +# ITU-R luma weights (Kr, Kb); Kg = 1 - Kr - Kb. +ENCODINGS = { + "BT601": (0.299, 0.114), + "BT709": (0.2126, 0.0722), + "BT2020": (0.2627, 0.0593), # non-constant luminance +} + +# 8-bit studio-range levels: luma 16..235 (range 219), chroma 16..240 +# (range 224, neutral 128); full-range maximum is 2^n - 1 = 255. +FULL_MAX = 255 +Y_RANGE = 235 - 16 # 219 +C_RANGE = 240 - 16 # 224 + +# 16-bit RGB test colors. +COLORS = { + "white": (0xffff, 0xffff, 0xffff), + "gray": (0x8080, 0x8080, 0x8080), + "black": (0x0000, 0x0000, 0x0000), + "red": (0xffff, 0x0000, 0x0000), + "green": (0x0000, 0xffff, 0x0000), + "blue": (0x0000, 0x0000, 0xffff), +} + + +def rgb_matrix(kr, kb, limited): + """Normalized YCbCr -> RGB (Y in [0,1], Cb/Cr in [-0.5, 0.5]).""" + kg = 1.0 - kr - kb + # Standard full-range relations. + m = [[1.0, 0.0, 2 * (1 - kr)], + [1.0, -2 * (1 - kb) * kb / kg, -2 * (1 - kr) * kr / kg], + [1.0, 2 * (1 - kb), 0.0]] + if limited: + # Expand studio input range to full range: luma by 255/219, + # chroma by 255/224 (relative to full-range maximum 2^n - 1). + ys, cs = FULL_MAX / Y_RANGE, FULL_MAX / C_RANGE + m = [[r[0] * ys, r[1] * cs, r[2] * cs] for r in m] + return m + + +def ref_yuv(m, y_offset): + """16-bit YCbCr that VKMS decodes back to each RGB color. + + VKMS decode: [R,G,B] = M . [Y - y_offset*257, Cb - 128*257, Cr - 128*257] + (8-bit offsets lifted to 16-bit by *257 = 65535/255), so invert and + re-add the offsets. + """ + inv = np.linalg.inv(np.array(m, float)) + off = np.array([y_offset * 257, 128 * 257, 128 * 257]) + return {name: tuple(int(min(max(round(v), 0), 0xffff)) + for v in inv @ np.array(rgb, float) + off) + for name, rgb in COLORS.items()} + +print(f"== RGB REFERENCE VALUES ==") +for name, rgb in COLORS.items(): + print(f" {name:6} {{ {rgb[0]:#06x}, {rgb[1]:#06x}, {rgb[2]:#06x} }}") +print() + +for enc, (kr, kb) in ENCODINGS.items(): + for limited in (False, True): + m = rgb_matrix(kr, kb, limited) + y_offset = 16 if limited else 0 + print(f"== {enc} {'LIMITED' if limited else 'FULL'} (y_offset={y_offset}) ==") + for row in m: + print(" { " + ", ".join(str(round(v * FP)) for v in row) + " },") + for name, yuv in ref_yuv(m, y_offset).items(): + print(f" {name:6} {{ {yuv[0]:#06x}, {yuv[1]:#06x}, {yuv[2]:#06x} }}") + print() diff --git a/drivers/gpu/drm/vkms/tests/vkms_format_test.c b/drivers/gpu/drm/vkms/tests/vkms_format_test.c index a7788fbc45dc..d2ae6321383b 100644 --- a/drivers/gpu/drm/vkms/tests/vkms_format_test.c +++ b/drivers/gpu/drm/vkms/tests/vkms_format_test.c @@ -54,6 +54,8 @@ struct yuv_u16_to_argb_u16_case { * The YUV color representation were acquired via the colour python framework. * Below are the function calls used for generating each case. * + * The limited-range cases are generated by gen_yuv_conversion.py. + * * For more information got to the docs: * https://colour.readthedocs.io/en/master/generated/colour.RGB_to_YCbCr.html */ @@ -101,12 +103,12 @@ static struct yuv_u16_to_argb_u16_case yuv_u16_to_argb_u16_cases[] = { .range = DRM_COLOR_YCBCR_LIMITED_RANGE, .n_colors = 6, .colors = { - { "white", { 0xeb00, 0x8000, 0x8000 }, { 0xffff, 0xffff, 0xffff, 0xffff }}, - { "gray", { 0x7dee, 0x8000, 0x8000 }, { 0xffff, 0x8080, 0x8080, 0x8080 }}, - { "black", { 0x1000, 0x8000, 0x8000 }, { 0xffff, 0x0000, 0x0000, 0x0000 }}, - { "red", { 0x517b, 0x5a34, 0xf000 }, { 0xffff, 0xffff, 0x0000, 0x0000 }}, - { "green", { 0x908e, 0x35cc, 0x2237 }, { 0xffff, 0x0000, 0xffff, 0x0000 }}, - { "blue", { 0x28f7, 0xf000, 0x6dc9 }, { 0xffff, 0x0000, 0x0000, 0xffff }}, + { "white", { 0xebeb, 0x8080, 0x8080 }, { 0xffff, 0xffff, 0xffff, 0xffff }}, + { "gray", { 0x7e6c, 0x8080, 0x8080 }, { 0xffff, 0x8080, 0x8080, 0x8080 }}, + { "black", { 0x1010, 0x8080, 0x8080 }, { 0xffff, 0x0000, 0x0000, 0x0000 }}, + { "red", { 0x51cd, 0x5a8e, 0xf0f0 }, { 0xffff, 0xffff, 0x0000, 0x0000 }}, + { "green", { 0x911e, 0x3602, 0x2259 }, { 0xffff, 0x0000, 0xffff, 0x0000 }}, + { "blue", { 0x2920, 0xf0f0, 0x6e37 }, { 0xffff, 0x0000, 0x0000, 0xffff }}, } }, /* @@ -151,12 +153,12 @@ static struct yuv_u16_to_argb_u16_case yuv_u16_to_argb_u16_cases[] = { .range = DRM_COLOR_YCBCR_LIMITED_RANGE, .n_colors = 6, .colors = { - { "white", { 0xeb00, 0x8000, 0x8000 }, { 0xffff, 0xffff, 0xffff, 0xffff }}, - { "gray", { 0x7dee, 0x8000, 0x8000 }, { 0xffff, 0x8080, 0x8080, 0x8080 }}, - { "black", { 0x1000, 0x8000, 0x8000 }, { 0xffff, 0x0000, 0x0000, 0x0000 }}, - { "red", { 0x3e8f, 0x6656, 0xf000 }, { 0xffff, 0xffff, 0x0000, 0x0000 }}, - { "green", { 0xaca1, 0x29aa, 0x1a45 }, { 0xffff, 0x0000, 0xffff, 0x0000 }}, - { "blue", { 0x1fd0, 0xf000, 0x75bb }, { 0xffff, 0x0000, 0x0000, 0xffff }}, + { "white", { 0xebeb, 0x8080, 0x8080 }, { 0xffff, 0xffff, 0xffff, 0xffff }}, + { "gray", { 0x7e6c, 0x8080, 0x8080 }, { 0xffff, 0x8080, 0x8080, 0x8080 }}, + { "black", { 0x1010, 0x8080, 0x8080 }, { 0xffff, 0x0000, 0x0000, 0x0000 }}, + { "red", { 0x3ece, 0x66bc, 0xf0f0 }, { 0xffff, 0xffff, 0x0000, 0x0000 }}, + { "green", { 0xad4e, 0x29d4, 0x1a5f }, { 0xffff, 0x0000, 0xffff, 0x0000 }}, + { "blue", { 0x1ff0, 0xf0f0, 0x7631 }, { 0xffff, 0x0000, 0x0000, 0xffff }}, } }, /* @@ -201,12 +203,12 @@ static struct yuv_u16_to_argb_u16_case yuv_u16_to_argb_u16_cases[] = { .range = DRM_COLOR_YCBCR_LIMITED_RANGE, .n_colors = 6, .colors = { - { "white", { 0xeb00, 0x8000, 0x8000 }, { 0xffff, 0xffff, 0xffff, 0xffff }}, - { "gray", { 0x7dee, 0x8000, 0x8000 }, { 0xffff, 0x8080, 0x8080, 0x8080 }}, - { "black", { 0x1000, 0x8000, 0x8000 }, { 0xffff, 0x0000, 0x0000, 0x0000 }}, - { "red", { 0x4988, 0x60b9, 0xf000 }, { 0xffff, 0xffff, 0x0000, 0x0000 }}, - { "green", { 0xa47b, 0x2f47, 0x1902 }, { 0xffff, 0x0000, 0xffff, 0x0000 }}, - { "blue", { 0x1cfd, 0xf000, 0x76fe }, { 0xffff, 0x0000, 0x0000, 0xffff }}, + { "white", { 0xebeb, 0x8080, 0x8080 }, { 0xffff, 0xffff, 0xffff, 0xffff }}, + { "gray", { 0x7e6c, 0x8080, 0x8080 }, { 0xffff, 0x8080, 0x8080, 0x8080 }}, + { "black", { 0x1010, 0x8080, 0x8080 }, { 0xffff, 0x0000, 0x0000, 0x0000 }}, + { "red", { 0x49d2, 0x611a, 0xf0f0 }, { 0xffff, 0xffff, 0x0000, 0x0000 }}, + { "green", { 0xa520, 0x2f76, 0x191b }, { 0xffff, 0x0000, 0xffff, 0x0000 }}, + { "blue", { 0x1d1a, 0xf0f0, 0x7775 }, { 0xffff, 0x0000, 0x0000, 0xffff }}, } }, }; diff --git a/drivers/gpu/drm/vkms/vkms_formats.c b/drivers/gpu/drm/vkms/vkms_formats.c index dfb8e13cba87..4d5fcaeb82c5 100644 --- a/drivers/gpu/drm/vkms/vkms_formats.c +++ b/drivers/gpu/drm/vkms/vkms_formats.c @@ -788,15 +788,36 @@ static const struct conversion_matrix yuv_bt601_full = { }; /* - * numpy.around(colour.matrix_YCbCr(K=colour.WEIGHTS_YCBCR["ITU-R BT.601"], - * is_legal = True, - * bits = 8) * 2**32).astype(int) + * BT.601 limited-/studio-range YCbCr to full-range RGB. + * + * The coefficients are derived as follows: + * + * 1. Take the standard ITU-R YCbCr -> RGB relations for luma weights + * Kr, Kb (Kg = 1 - Kr - Kb), with Y in [0, 1] and Cb, Cr in + * [-0.5, 0.5]. For BT.601 Kr = 0.299 and Kb = 0.114: + * + * R = Y + 2 * (1 - Kr) * Cr + * G = Y - 2 * (1 - Kb) * Kb / Kg * Cb - 2 * (1 - Kr) * Kr / Kg * Cr + * B = Y + 2 * (1 - Kb) * Cb + * + * These are exactly the yuv_bt601_full coefficients above. + * + * 2. Expand the studio input range to full range, relative to a + * full-range maximum of 2^n - 1 (255 for 8-bit): the luma + * coefficient is scaled by 255/(235 - 16) and the chroma + * coefficients by 255/(240 - 16). This matches the DRM UAPI + * definition and IGT's igt_ycbcr_to_rgb_matrix(). Note this differs + * from colour.matrix_YCbCr(is_legal=True), which normalises by 2^n + * and is thus off by a factor of 256/255. + * + * 3. Convert each coefficient to S31.32 fixed point, i.e. + * round(coeff * 2^32). */ static const struct conversion_matrix yuv_bt601_limited = { .matrix = { - { 5020601039, 0, 6881764740 }, - { 5020601039, -1689204679, -3505362278 }, - { 5020601039, 8697922339, 0 }, + { 5000989317, 0, 6854882848 }, + { 5000989317, -1682606224, -3491669458 }, + { 5000989317, 8663946082, 0 }, }, .y_offset = 16, }; @@ -816,15 +837,14 @@ static const struct conversion_matrix yuv_bt709_full = { }; /* - * numpy.around(colour.matrix_YCbCr(K=colour.WEIGHTS_YCBCR["ITU-R BT.709"], - * is_legal = True, - * bits = 8) * 2**32).astype(int) + * BT.709 limited-range YCbCr to full-range RGB (Kr = 0.2126, Kb = 0.0722). + * Derived as described for yuv_bt601_limited. */ static const struct conversion_matrix yuv_bt709_limited = { .matrix = { - { 5020601039, 0, 7729959424 }, - { 5020601039, -919487572, -2297803934 }, - { 5020601039, 9108275786, 0 }, + { 5000989317, 0, 7699764272 }, + { 5000989317, -915895824, -2288828138 }, + { 5000989317, 9072696586, 0 }, }, .y_offset = 16, }; @@ -844,15 +864,14 @@ static const struct conversion_matrix yuv_bt2020_full = { }; /* - * numpy.around(colour.matrix_YCbCr(K=colour.WEIGHTS_YCBCR["ITU-R BT.2020"], - * is_legal = True, - * bits = 8) * 2**32).astype(int) + * BT.2020 non-constant-luminance limited-range YCbCr to full-range RGB + * (Kr = 0.2627, Kb = 0.0593). Derived as described for yuv_bt601_limited. */ static const struct conversion_matrix yuv_bt2020_limited = { .matrix = { - { 5020601039, 0, 7238124312 }, - { 5020601039, -807714626, -2804506279 }, - { 5020601039, 9234915964, 0 }, + { 5000989317, 0, 7209850391 }, + { 5000989317, -804559491, -2793551177 }, + { 5000989317, 9198842076, 0 }, }, .y_offset = 16, }; diff --git a/drivers/gpu/drm/xe/xe_pagefault.c b/drivers/gpu/drm/xe/xe_pagefault.c index a4986df8328d..7a0ea4d414ca 100644 --- a/drivers/gpu/drm/xe/xe_pagefault.c +++ b/drivers/gpu/drm/xe/xe_pagefault.c @@ -304,6 +304,13 @@ static void xe_pagefault_queue_work(struct work_struct *w) */ guard(xe_pm_runtime)(xe); + /* + * A live VM holds a PM reference, but a torn-down VM does not. + * Guard the entire worker loop to safely drain stale faults and + * prevent autosuspends from desyncing batched CT flushes. + */ + guard(xe_pm_runtime)(xe); + #define USM_QUEUE_MAX_RUNTIME_MS 20 threshold = jiffies + msecs_to_jiffies(USM_QUEUE_MAX_RUNTIME_MS); diff --git a/drivers/gpu/drm/xe/xe_wait_user_fence.c b/drivers/gpu/drm/xe/xe_wait_user_fence.c index 51eb940ceb4e..e241f3ec3547 100644 --- a/drivers/gpu/drm/xe/xe_wait_user_fence.c +++ b/drivers/gpu/drm/xe/xe_wait_user_fence.c @@ -7,7 +7,7 @@ #include #include -#include +#include #include #include "xe_device.h" diff --git a/drivers/gpu/nova-core/gsp/boot.rs b/drivers/gpu/nova-core/gsp/boot.rs index e03700ee7bea..874f6e9499f0 100644 --- a/drivers/gpu/nova-core/gsp/boot.rs +++ b/drivers/gpu/nova-core/gsp/boot.rs @@ -44,6 +44,11 @@ pub(crate) fn boot( let gsp_fw = KBox::pin_init(GspFirmware::new(dev, chipset), GFP_KERNEL)?; + self.cmdq + .send_command_no_wait(bar, commands::SetSystemInfo::new(pdev, chipset))?; + self.cmdq + .send_command_no_wait(bar, commands::SetRegistry::new(ctx.vgpu.state())?)?; + // Perform the chipset-specific boot sequence, and retrieve the unload bundle. let unload_bundle = hal.boot(&self, &mut ctx, &gsp_fw)?.or_else(|| { dev_warn!(dev, "The GSP won't be able to unload properly on unbind.\n"); @@ -73,11 +78,6 @@ pub(crate) fn boot( dev_dbg!(pdev, "RISC-V active? {}\n", gsp_falcon.is_riscv_active(),); - self.cmdq - .send_command_no_wait(bar, commands::SetSystemInfo::new(pdev, chipset))?; - self.cmdq - .send_command_no_wait(bar, commands::SetRegistry::new(ctx.vgpu.state())?)?; - hal.post_boot(&self, ctx, &gsp_fw)?; // Wait until GSP is fully initialized. diff --git a/drivers/hid/hid-asus.c b/drivers/hid/hid-asus.c index 7dc6417fe262..baa8589d45ae 100644 --- a/drivers/hid/hid-asus.c +++ b/drivers/hid/hid-asus.c @@ -765,9 +765,14 @@ static void asus_work(struct work_struct *work) struct asus_work_action *action = NULL; unsigned long flags; - /* Save the action to be performed and clear the flag */ + /* + * Dequeue the next action, if any. Once teardown has begun .removed + * is set and asus_worker_stop() drains the queue: leave the queued + * actions alone, they are dropped instead of being executed against + * a device that is being removed. + */ spin_lock_irqsave(&worker->lock, flags); - if (!list_empty(&worker->actions)) { + if (!worker->removed && !list_empty(&worker->actions)) { action = list_first_entry(&worker->actions, struct asus_work_action, node); list_del(&action->node); @@ -817,6 +822,25 @@ static int asus_worker_create(struct hid_device *hdev, struct asus_drvdata *drvd return 0; } +/** + * asus_worker_stop - quiesce the worker + * @worker: the worker to quiesce + * + * Once this function returns no more actions can be queued and no instance + * of asus_work() is running or pending. + * + * Callers must do this before hid_hw_stop(): actions are executed while the + * device is fully operational, since they send raw requests to it and, in + * the fan-key fallback path, re-inject raw reports into the HID core. After + * hid_hw_stop() the transport is gone (usbhid_stop() frees the URBs and the + * I/O buffers) and the input devices have been unregistered. + * + * The quiescing is race free because every site that queues an action holds + * worker->lock across the .removed check, the list insertion and + * schedule_work(): anything scheduled before .removed is set here is caught + * by the cancel_work_sync() below, anything after it is discarded by + * asus_worker_schedule(). + */ static void asus_worker_stop(struct asus_worker *worker) { struct asus_work_action *action, *tmp; diff --git a/drivers/hid/hid-ids.h b/drivers/hid/hid-ids.h index 3b19b742d4dd..042421c8399b 100644 --- a/drivers/hid/hid-ids.h +++ b/drivers/hid/hid-ids.h @@ -1170,6 +1170,7 @@ #define USB_DEVICE_ID_PDP_PS4_JAGUAR 0x0173 #define USB_DEVICE_ID_PDP_PS4_RIFFMASTER 0x024a #define USB_DEVICE_ID_PDP_PS5_RIFFMASTER 0x0249 +#define USB_DEVICE_ID_PDP_SWITCH_AFTERGLOW 0x018c #define USB_VENDOR_ID_PLANTRONICS 0x047f #define USB_DEVICE_ID_PLANTRONICS_BLACKWIRE_3210_SERIES 0xc055 diff --git a/drivers/hid/hid-logitech-hidpp.c b/drivers/hid/hid-logitech-hidpp.c index 9646380febac..27d83b8bbaaf 100644 --- a/drivers/hid/hid-logitech-hidpp.c +++ b/drivers/hid/hid-logitech-hidpp.c @@ -4791,6 +4791,7 @@ static int hidpp_probe(struct hid_device *hdev, const struct hid_device_id *id) hid_hw_start_fail: sysfs_remove_group(&hdev->dev.kobj, &ps_attribute_group); cancel_work_sync(&hidpp->work); + cancel_work_sync(&hidpp->reset_hi_res_work); mutex_destroy(&hidpp->send_mutex); return ret; } diff --git a/drivers/hid/hid-magicmouse.c b/drivers/hid/hid-magicmouse.c index d637c0477379..e6d4d4930526 100644 --- a/drivers/hid/hid-magicmouse.c +++ b/drivers/hid/hid-magicmouse.c @@ -553,6 +553,10 @@ static int magicmouse_event(struct hid_device *hdev, struct hid_field *field, struct hid_usage *usage, __s32 value) { struct magicmouse_sc *msc = hid_get_drvdata(hdev); + + if (!msc || !msc->input) + return 0; + if ((msc->input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE2 || msc->input->id.product == USB_DEVICE_ID_APPLE_MAGICMOUSE2_USBC) && field->report->id == MOUSE2_REPORT_ID) { diff --git a/drivers/hid/hid-nintendo.c b/drivers/hid/hid-nintendo.c index 43e0f2aaea3b..b1fcf3e5767b 100644 --- a/drivers/hid/hid-nintendo.c +++ b/drivers/hid/hid-nintendo.c @@ -434,8 +434,8 @@ static const struct joycon_ctlr_button_mapping procon_button_mappings[] = { { /* sentinel */ }, }; -/* Licensed Pro Controllers (e.g. HORI) swap X/Y bits in the report */ -static const struct joycon_ctlr_button_mapping lic_procon_button_mappings[] = { +/* HORI Licensed Pro Controllers swap X/Y bits in the report */ +static const struct joycon_ctlr_button_mapping lic_hori_procon_button_mappings[] = { { BTN_EAST, JC_BTN_A, }, { BTN_SOUTH, JC_BTN_B, }, { BTN_NORTH, JC_BTN_Y, }, @@ -1767,8 +1767,8 @@ static void joycon_parse_report(struct joycon_ctlr *ctlr, joycon_report_left_stick(ctlr, rep); joycon_report_right_stick(ctlr, rep); joycon_report_dpad(ctlr, rep); - if (ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO) - joycon_report_buttons(ctlr, rep, lic_procon_button_mappings); + if (ctlr->hdev->vendor == USB_VENDOR_ID_HORI) + joycon_report_buttons(ctlr, rep, lic_hori_procon_button_mappings); else joycon_report_buttons(ctlr, rep, procon_button_mappings); } else if (joycon_type_is_any_nescon(ctlr)) { @@ -2212,8 +2212,8 @@ static int joycon_input_create(struct joycon_ctlr *ctlr) joycon_config_left_stick(ctlr->input); joycon_config_right_stick(ctlr->input); joycon_config_dpad(ctlr->input); - if (ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO) - joycon_config_buttons(ctlr->input, lic_procon_button_mappings); + if (ctlr->hdev->vendor == USB_VENDOR_ID_HORI) + joycon_config_buttons(ctlr->input, lic_hori_procon_button_mappings); else joycon_config_buttons(ctlr->input, procon_button_mappings); } else if (joycon_type_is_any_nescon(ctlr)) { @@ -2905,6 +2905,8 @@ static const struct hid_device_id nintendo_hid_devices[] = { USB_DEVICE_ID_NINTENDO_N64CON) }, { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_HORI, USB_DEVICE_ID_HORI_WIRELESS_SWITCH_PAD) }, + { HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_PDP, + USB_DEVICE_ID_PDP_SWITCH_AFTERGLOW) }, { } }; MODULE_DEVICE_TABLE(hid, nintendo_hid_devices); diff --git a/drivers/hid/i2c-hid/i2c-hid-core.c b/drivers/hid/i2c-hid/i2c-hid-core.c index a61fd1de5203..a8a9854854f5 100644 --- a/drivers/hid/i2c-hid/i2c-hid-core.c +++ b/drivers/hid/i2c-hid/i2c-hid-core.c @@ -1357,7 +1357,16 @@ void i2c_hid_core_shutdown(struct i2c_client *client) { struct i2c_hid *ihid = i2c_get_clientdata(client); - i2c_hid_set_power(ihid, I2C_HID_PWR_SLEEP); + /* + * Like in i2c_hid_core_remove(): if we're a follower, the act of + * unfollowing will cause us to be powered down. Otherwise we need to + * manually do it. + */ + if (ihid->is_panel_follower) + drm_panel_remove_follower(&ihid->panel_follower); + else + i2c_hid_set_power(ihid, I2C_HID_PWR_SLEEP); + free_irq(client->irq, ihid); i2c_hid_core_shutdown_tail(ihid); diff --git a/drivers/hid/intel-thc-hid/intel-quicki2c/pci-quicki2c.c b/drivers/hid/intel-thc-hid/intel-quicki2c/pci-quicki2c.c index 2537288b5026..7a913f717efa 100644 --- a/drivers/hid/intel-thc-hid/intel-quicki2c/pci-quicki2c.c +++ b/drivers/hid/intel-thc-hid/intel-quicki2c/pci-quicki2c.c @@ -315,7 +315,7 @@ static int handle_input_report(struct quicki2c_device *qcdev) if (qcdev->state != QUICKI2C_ENABLED) continue; - quicki2c_hid_send_report(qcdev, pkt->data, + quicki2c_hid_send_report(qcdev, pkt->data, qcdev->input_len, HIDI2C_DATA_LEN(le16_to_cpu(pkt->len))); } @@ -611,6 +611,8 @@ static int quicki2c_alloc_report_buf(struct quicki2c_device *qcdev) if (!qcdev->input_buf) return -ENOMEM; + qcdev->input_len = max_report_len; + if (!le16_to_cpu(qcdev->dev_desc.max_output_len)) qcdev->dev_desc.max_output_len = cpu_to_le16(SZ_4K); diff --git a/drivers/hid/intel-thc-hid/intel-quicki2c/quicki2c-dev.h b/drivers/hid/intel-thc-hid/intel-quicki2c/quicki2c-dev.h index 6d25a846153e..e9ff0440fb54 100644 --- a/drivers/hid/intel-thc-hid/intel-quicki2c/quicki2c-dev.h +++ b/drivers/hid/intel-thc-hid/intel-quicki2c/quicki2c-dev.h @@ -181,6 +181,7 @@ struct acpi_device; * @low_power_ltr_val: THC low power LTR value * @report_descriptor: Store a copy of device report descriptor * @input_buf: Store a copy of latest input report data + * @input_len: The data size of the input report buffer * @report_buf: Store a copy of latest input/output report packet from set/get feature * @report_len: The length of input/output report packet * @reset_ack_wq: Workqueue for waiting reset response from device @@ -212,6 +213,7 @@ struct quicki2c_device { u8 *report_descriptor; u8 *input_buf; + size_t input_len; u8 *report_buf; size_t report_len; diff --git a/drivers/hid/intel-thc-hid/intel-quicki2c/quicki2c-hid.c b/drivers/hid/intel-thc-hid/intel-quicki2c/quicki2c-hid.c index 8075992e8732..1a220a50d934 100644 --- a/drivers/hid/intel-thc-hid/intel-quicki2c/quicki2c-hid.c +++ b/drivers/hid/intel-thc-hid/intel-quicki2c/quicki2c-hid.c @@ -157,16 +157,18 @@ void quicki2c_hid_remove(struct quicki2c_device *qcdev) * * @qcdev: point to quicki2c device * @data: point to input report data buffer + * @buf_size: the allocated size of the input report data buffer * @data_len: the length of input report data * * Return: 0 on success, non zero on error. */ int quicki2c_hid_send_report(struct quicki2c_device *qcdev, - void *data, size_t data_len) + void *data, size_t buf_size, size_t data_len) { int ret; - ret = hid_input_report(qcdev->hid_dev, HID_INPUT_REPORT, data, data_len, 1); + ret = hid_safe_input_report(qcdev->hid_dev, HID_INPUT_REPORT, data, + buf_size, data_len, 1); if (ret) dev_err(qcdev->dev, "Failed to send HID input report, ret = %d.\n", ret); diff --git a/drivers/hid/intel-thc-hid/intel-quicki2c/quicki2c-hid.h b/drivers/hid/intel-thc-hid/intel-quicki2c/quicki2c-hid.h index e80df5f339fe..4c6757eca18e 100644 --- a/drivers/hid/intel-thc-hid/intel-quicki2c/quicki2c-hid.h +++ b/drivers/hid/intel-thc-hid/intel-quicki2c/quicki2c-hid.h @@ -7,7 +7,7 @@ struct quicki2c_device; int quicki2c_hid_send_report(struct quicki2c_device *qcdev, - void *data, size_t data_size); + void *data, size_t buf_size, size_t data_size); int quicki2c_hid_probe(struct quicki2c_device *qcdev); void quicki2c_hid_remove(struct quicki2c_device *qcdev); diff --git a/drivers/hid/intel-thc-hid/intel-quickspi/pci-quickspi.c b/drivers/hid/intel-thc-hid/intel-quickspi/pci-quickspi.c index ad676fde211b..53023e30cf8d 100644 --- a/drivers/hid/intel-thc-hid/intel-quickspi/pci-quickspi.c +++ b/drivers/hid/intel-thc-hid/intel-quickspi/pci-quickspi.c @@ -557,6 +557,8 @@ static int quickspi_alloc_report_buf(struct quickspi_device *qsdev) if (!qsdev->input_buf) return -ENOMEM; + qsdev->input_len = max_input_len; + max_report_len = max(le16_to_cpu(qsdev->dev_desc.max_output_len), le16_to_cpu(qsdev->dev_desc.max_input_len)); diff --git a/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-dev.h b/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-dev.h index dc67a39ad546..fe51ff51d8c0 100644 --- a/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-dev.h +++ b/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-dev.h @@ -113,6 +113,7 @@ struct acpi_device; * @low_power_ltr_val: THC low power LTR value * @report_descriptor: store a copy of device report descriptor * @input_buf: store a copy of latest input report data + * @input_len: the data size of the input report buffer * @report_buf: store a copy of latest input/output report packet from set/get feature * @report_len: the length of input/output report packet * @reset_ack_wq: workqueue for waiting reset response from device @@ -159,6 +160,7 @@ struct quickspi_device { u8 *report_descriptor; u8 *input_buf; + u32 input_len; u8 *report_buf; u32 report_buf_size; u32 report_len; diff --git a/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-hid.c b/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-hid.c index a60a0a7f16aa..ed1c40b8c4fa 100644 --- a/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-hid.c +++ b/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-hid.c @@ -148,16 +148,18 @@ void quickspi_hid_remove(struct quickspi_device *qsdev) * * @qsdev: point to quickspi device * @data: point to input report data buffer + * @buf_size: the allocated size of the input report data buffer * @data_len: the length of input report data * * Return: 0 on success, non zero on error. */ int quickspi_hid_send_report(struct quickspi_device *qsdev, - void *data, size_t data_len) + void *data, size_t buf_size, size_t data_len) { int ret; - ret = hid_input_report(qsdev->hid_dev, HID_INPUT_REPORT, data, data_len, 1); + ret = hid_safe_input_report(qsdev->hid_dev, HID_INPUT_REPORT, data, + buf_size, data_len, 1); if (ret) dev_err(qsdev->dev, "Failed to send HID input report, ret = %d.\n", ret); diff --git a/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-hid.h b/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-hid.h index f640fa876a40..61b7c6be6c51 100644 --- a/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-hid.h +++ b/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-hid.h @@ -7,7 +7,7 @@ struct quickspi_device; int quickspi_hid_send_report(struct quickspi_device *qsdev, - void *data, size_t data_size); + void *data, size_t buf_size, size_t data_size); int quickspi_hid_probe(struct quickspi_device *qsdev); void quickspi_hid_remove(struct quickspi_device *qsdev); diff --git a/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-protocol.c b/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-protocol.c index 847c5ec55569..0df33c44fbff 100644 --- a/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-protocol.c +++ b/drivers/hid/intel-thc-hid/intel-quickspi/quickspi-protocol.c @@ -240,7 +240,7 @@ void quickspi_handle_input_data(struct quickspi_device *qsdev, u32 buf_len) input_len = sizeof(body_hdr->content_id) + input_len; input_report = input_body->content - sizeof(body_hdr->content_id); - ret = quickspi_hid_send_report(qsdev, input_report, input_len); + ret = quickspi_hid_send_report(qsdev, input_report, qsdev->input_len, input_len); if (ret) dev_err_once(qsdev->dev, "Failed to send HID input report: %d\n", ret); diff --git a/drivers/hid/wacom_wac.c b/drivers/hid/wacom_wac.c index cf459c16b39a..361738bb8725 100644 --- a/drivers/hid/wacom_wac.c +++ b/drivers/hid/wacom_wac.c @@ -1027,10 +1027,10 @@ static int wacom_intuos_general(struct wacom_wac *wacom) return 2; } -static int wacom_intuos_irq(struct wacom_wac *wacom) +static int wacom_intuos_irq(struct wacom_wac *wacom_wac) { - unsigned char *data = wacom->data; - struct input_dev *input = wacom->pen_input; + unsigned char *data = wacom_wac->data; + struct wacom *wacom = container_of(wacom_wac, struct wacom, wacom_wac); int result; if (data[0] != WACOM_REPORT_PENABLED && @@ -1041,23 +1041,23 @@ static int wacom_intuos_irq(struct wacom_wac *wacom) data[0] != WACOM_REPORT_CINTIQ && data[0] != WACOM_REPORT_CINTIQPAD && data[0] != WACOM_REPORT_INTUOS5PAD) { - dev_dbg(input->dev.parent, + hid_dbg(wacom->hdev, "%s: received unknown report #%d\n", __func__, data[0]); return 0; } /* process pad events */ - result = wacom_intuos_pad(wacom); + result = wacom_intuos_pad(wacom_wac); if (result) return result; /* process in/out prox events */ - result = wacom_intuos_inout(wacom); + result = wacom_intuos_inout(wacom_wac); if (result) return result - 1; /* process general packets */ - result = wacom_intuos_general(wacom); + result = wacom_intuos_general(wacom_wac); if (result) return result - 1; diff --git a/drivers/hv/hv_common.c b/drivers/hv/hv_common.c index 31256cb22b39..bb290a5eaf1d 100644 --- a/drivers/hv/hv_common.c +++ b/drivers/hv/hv_common.c @@ -681,16 +681,6 @@ void __weak hv_setup_mshv_handler(void (*handler)(void)) } EXPORT_SYMBOL_GPL(hv_setup_mshv_handler); -void __weak hv_setup_kexec_handler(void (*handler)(void)) -{ -} -EXPORT_SYMBOL_GPL(hv_setup_kexec_handler); - -void __weak hv_remove_kexec_handler(void) -{ -} -EXPORT_SYMBOL_GPL(hv_remove_kexec_handler); - void __weak hv_setup_crash_handler(void (*handler)(struct pt_regs *regs)) { } diff --git a/drivers/hv/mshv_vtl_main.c b/drivers/hv/mshv_vtl_main.c index 9133646b5b66..2d4fe24cecbf 100644 --- a/drivers/hv/mshv_vtl_main.c +++ b/drivers/hv/mshv_vtl_main.c @@ -97,7 +97,7 @@ union hv_synic_overlay_page_msr { } __packed; }; -static struct mutex mshv_vtl_poll_file_lock; +static DEFINE_MUTEX(mshv_vtl_poll_file_lock); static union hv_register_vsm_page_offsets mshv_vsm_page_offsets; static union hv_register_vsm_capabilities mshv_vsm_capabilities; @@ -1411,8 +1411,6 @@ static int __init mshv_vtl_init(void) goto free_low; } - mutex_init(&mshv_vtl_poll_file_lock); - device_initialize(mem_dev); dev_set_name(mem_dev, "mshv vtl mem dev"); ret = device_add(mem_dev); diff --git a/drivers/hv/vmbus_drv.c b/drivers/hv/vmbus_drv.c index 4692687cdbf3..c8330fffb138 100644 --- a/drivers/hv/vmbus_drv.c +++ b/drivers/hv/vmbus_drv.c @@ -33,6 +33,7 @@ #include #include #include +#include #include #include #include @@ -2571,10 +2572,14 @@ EXPORT_SYMBOL_GPL(vmbus_free_mmio); #ifdef CONFIG_ACPI static int vmbus_acpi_add(struct platform_device *pdev) { + struct acpi_device *ancestor; + struct acpi_device *device; acpi_status result; int ret_val = -ENODEV; - struct acpi_device *ancestor; - struct acpi_device *device = ACPI_COMPANION(&pdev->dev); + + device = ACPI_COMPANION(&pdev->dev); + if (!device) + return -ENODEV; vmbus_root_device = &device->dev; @@ -2904,6 +2909,12 @@ static void hv_kexec_handler(void) cpuhp_remove_state(hyperv_cpuhp_online); }; +static void hv_vmbus_syscore_shutdown(void *data) +{ + if (kexec_is_in_progress()) + hv_kexec_handler(); +} + static void hv_crash_handler(struct pt_regs *regs) { int cpu; @@ -2954,14 +2965,15 @@ static void hv_synic_resume(void *data) */ } -/* The callbacks run only on CPU0, with irqs_disabled. */ -static const struct syscore_ops hv_synic_syscore_ops = { +/* The suspend and resume callbacks run only on CPU0, with irqs_disabled. */ +static const struct syscore_ops hv_vmbus_syscore_ops = { .suspend = hv_synic_suspend, .resume = hv_synic_resume, + .shutdown = hv_vmbus_syscore_shutdown, }; -static struct syscore hv_synic_syscore = { - .ops = &hv_synic_syscore_ops, +static struct syscore hv_vmbus_syscore = { + .ops = &hv_vmbus_syscore_ops, }; static int __init hv_acpi_init(void) @@ -3010,10 +3022,9 @@ static int __init hv_acpi_init(void) if (ret) goto cleanup; - hv_setup_kexec_handler(hv_kexec_handler); hv_setup_crash_handler(hv_crash_handler); - register_syscore(&hv_synic_syscore); + register_syscore(&hv_vmbus_syscore); return 0; @@ -3035,9 +3046,8 @@ static void __exit vmbus_exit(void) */ return; - unregister_syscore(&hv_synic_syscore); + unregister_syscore(&hv_vmbus_syscore); - hv_remove_kexec_handler(); hv_remove_crash_handler(); hv_stimer_global_cleanup(); vmbus_disconnect(); diff --git a/drivers/hwmon/coretemp.c b/drivers/hwmon/coretemp.c index 2d7487b2f80a..96d57fe12de6 100644 --- a/drivers/hwmon/coretemp.c +++ b/drivers/hwmon/coretemp.c @@ -76,7 +76,7 @@ struct temp_data { int temp; bool temp_valid; int tjmax; - unsigned long last_updated; + u64 last_updated; unsigned int cpu; int index; u32 cpu_core_id; @@ -406,9 +406,9 @@ static ssize_t show_temp(struct device *dev, mutex_lock(&tdata->update_lock); - tjmax = get_tjmax(tdata, dev); /* Check whether the time interval has elapsed */ - if (time_after(jiffies, tdata->last_updated + HZ)) { + if (time_after64(get_jiffies_64(), tdata->last_updated + HZ)) { + tjmax = get_tjmax(tdata, dev); rdmsrq_on_cpu(tdata->cpu, tdata->status_reg, &val.q); /* * Bit 31 indicates whether the reading is valid. Some CPUs @@ -417,7 +417,7 @@ static ssize_t show_temp(struct device *dev, */ tdata->temp_valid = (val.l >> 31) & 1; tdata->temp = tjmax - ((val.l >> 16) & 0xff) * 1000; - tdata->last_updated = jiffies; + tdata->last_updated = get_jiffies_64(); } valid = tdata->temp_valid; @@ -521,11 +521,8 @@ init_temp_data(struct platform_data *pdata, unsigned int cpu, int pkg_flag) tdata->cpu = cpu; tdata->cpu_core_id = topology_core_id(cpu); tdata->attr_size = MAX_CORE_ATTRS; - /* - * A zero timestamp does not look stale on 32-bit, where jiffies - * starts just short of wrapping. Backdate it instead. - */ - tdata->last_updated = jiffies - HZ - 1; + /* Backdate to force a refresh on the first read */ + tdata->last_updated = get_jiffies_64() - HZ - 1; mutex_init(&tdata->update_lock); return tdata; } diff --git a/drivers/hwtracing/coresight/coresight-config.c b/drivers/hwtracing/coresight/coresight-config.c index 4f72ae71b696..0e296289f286 100644 --- a/drivers/hwtracing/coresight/coresight-config.c +++ b/drivers/hwtracing/coresight/coresight-config.c @@ -73,13 +73,12 @@ static void cscfg_init_reg_param(struct cscfg_feature_csdev *feat_csdev, /* set values into the driver locations referenced in cscfg_reg_csdev */ static int cscfg_set_on_enable(struct cscfg_feature_csdev *feat_csdev) { - unsigned long flags; int i; - raw_spin_lock_irqsave(feat_csdev->drv_spinlock, flags); - for (i = 0; i < feat_csdev->nr_regs; i++) - cscfg_set_reg(&feat_csdev->regs_csdev[i]); - raw_spin_unlock_irqrestore(feat_csdev->drv_spinlock, flags); + scoped_guard(feat_csdev_lock, feat_csdev) { + for (i = 0; i < feat_csdev->nr_regs; i++) + cscfg_set_reg(&feat_csdev->regs_csdev[i]); + } dev_dbg(&feat_csdev->csdev->dev, "Feature %s: %s", feat_csdev->feat_desc->name, "set on enable"); return 0; @@ -88,13 +87,12 @@ static int cscfg_set_on_enable(struct cscfg_feature_csdev *feat_csdev) /* copy back values from the driver locations referenced in cscfg_reg_csdev */ static void cscfg_save_on_disable(struct cscfg_feature_csdev *feat_csdev) { - unsigned long flags; int i; - raw_spin_lock_irqsave(feat_csdev->drv_spinlock, flags); - for (i = 0; i < feat_csdev->nr_regs; i++) - cscfg_save_reg(&feat_csdev->regs_csdev[i]); - raw_spin_unlock_irqrestore(feat_csdev->drv_spinlock, flags); + scoped_guard(feat_csdev_lock, feat_csdev) { + for (i = 0; i < feat_csdev->nr_regs; i++) + cscfg_save_reg(&feat_csdev->regs_csdev[i]); + } dev_dbg(&feat_csdev->csdev->dev, "Feature %s: %s", feat_csdev->feat_desc->name, "save on disable"); } diff --git a/drivers/hwtracing/coresight/coresight-config.h b/drivers/hwtracing/coresight/coresight-config.h index 90fd937d3bd8..ae6295e30813 100644 --- a/drivers/hwtracing/coresight/coresight-config.h +++ b/drivers/hwtracing/coresight/coresight-config.h @@ -7,6 +7,7 @@ #ifndef _CORESIGHT_CORESIGHT_CONFIG_H #define _CORESIGHT_CORESIGHT_CONFIG_H +#include #include #include @@ -259,4 +260,25 @@ void cscfg_csdev_disable_config(struct cscfg_config_csdev *config_csdev); /* reset a feature to default values */ void cscfg_reset_feat(struct cscfg_feature_csdev *feat_csdev); +#define feat_csdev_lock(feat_csdev, flags) \ + do { \ + raw_spinlock_t *__lock = feat_csdev->drv_spinlock; \ + typecheck(unsigned long, flags); \ + if (__lock) \ + raw_spin_lock_irqsave(__lock, flags); \ + } while (0) + +#define feat_csdev_unlock(feat_csdev, flags) \ + do { \ + raw_spinlock_t *__lock = feat_csdev->drv_spinlock; \ + typecheck(unsigned long, flags); \ + if (__lock) \ + raw_spin_unlock_irqrestore(__lock, flags); \ + } while (0) + +DEFINE_LOCK_GUARD_1(feat_csdev_lock, struct cscfg_feature_csdev, + feat_csdev_lock(_T->lock, _T->flags), + feat_csdev_unlock(_T->lock, _T->flags), + unsigned long flags) + #endif /* _CORESIGHT_CORESIGHT_CONFIG_H */ diff --git a/drivers/hwtracing/coresight/coresight-etm.h b/drivers/hwtracing/coresight/coresight-etm.h index 1d753cca2943..52f23a3c7364 100644 --- a/drivers/hwtracing/coresight/coresight-etm.h +++ b/drivers/hwtracing/coresight/coresight-etm.h @@ -226,7 +226,8 @@ struct etm_config { * @etmccr: value of register ETMCCR. * @etmccer: value of register ETMCCER. * @traceid: value of the current ID for this component. - * @config: structure holding configuration parameters. + * @curr_config: structure holding current running configuration. + * @config: structure holding sysfs mode configuration. */ struct etm_drvdata { struct csdev_access csa; @@ -248,6 +249,7 @@ struct etm_drvdata { u32 etmccr; u32 etmccer; u32 traceid; + struct etm_config curr_config; struct etm_config config; }; diff --git a/drivers/hwtracing/coresight/coresight-etm3x-core.c b/drivers/hwtracing/coresight/coresight-etm3x-core.c index 862ad0786699..dcadcc383012 100644 --- a/drivers/hwtracing/coresight/coresight-etm3x-core.c +++ b/drivers/hwtracing/coresight/coresight-etm3x-core.c @@ -308,7 +308,7 @@ void etm_config_trace_mode(struct etm_config *config) static int etm_parse_event_config(struct etm_drvdata *drvdata, struct perf_event *event) { - struct etm_config *config = &drvdata->config; + struct etm_config *config = &drvdata->curr_config; struct perf_event_attr *attr = &event->attr; u8 ts_level; @@ -367,7 +367,7 @@ static int etm_enable_hw(struct etm_drvdata *drvdata) { int i, rc; u32 etmcr; - struct etm_config *config = &drvdata->config; + struct etm_config *config = &drvdata->curr_config; struct coresight_device *csdev = drvdata->csdev; CS_UNLOCK(drvdata->csa.base); @@ -448,26 +448,22 @@ struct etm_enable_arg { static void etm_enable_sysfs_smp_call(void *info) { struct etm_enable_arg *arg = info; + struct etm_drvdata *drvdata; struct coresight_device *csdev; if (WARN_ON(!arg)) return; - csdev = arg->drvdata->csdev; - if (!coresight_take_mode(csdev, CS_MODE_SYSFS)) { - /* Someone is already using the tracer */ - arg->rc = -EBUSY; - return; - } + drvdata = arg->drvdata; + csdev = drvdata->csdev; - arg->rc = etm_enable_hw(arg->drvdata); + drvdata->traceid = arg->path->trace_id; - /* The tracer didn't start */ - if (arg->rc) { - coresight_set_mode(csdev, CS_MODE_DISABLED); + arg->rc = etm_enable_hw(arg->drvdata); + if (arg->rc) return; - } + drvdata->sticky_enable = true; csdev->path = arg->path; } @@ -512,9 +508,10 @@ static int etm_enable_sysfs(struct coresight_device *csdev, struct coresight_pat struct etm_enable_arg arg = { }; int ret; - spin_lock(&drvdata->spinlock); - - drvdata->traceid = path->trace_id; + if (!coresight_take_mode(csdev, CS_MODE_SYSFS)) { + /* Someone is already using the tracer */ + return -EBUSY; + } /* * Configure the ETM only if the CPU is online. If it isn't online @@ -523,23 +520,27 @@ static int etm_enable_sysfs(struct coresight_device *csdev, struct coresight_pat if (cpu_online(drvdata->cpu)) { arg.drvdata = drvdata; arg.path = path; + + scoped_guard(spinlock, &drvdata->spinlock) { + drvdata->curr_config = drvdata->config; + } + ret = smp_call_function_single(drvdata->cpu, etm_enable_sysfs_smp_call, &arg, 1); if (!ret) ret = arg.rc; - if (!ret) - drvdata->sticky_enable = true; } else { ret = -ENODEV; } - if (ret) + if (!ret) { + dev_dbg(&csdev->dev, "ETM tracing enabled\n"); + } else { etm_release_trace_id(drvdata); + /* The tracer didn't start */ + coresight_set_mode(csdev, CS_MODE_DISABLED); + } - spin_unlock(&drvdata->spinlock); - - if (!ret) - dev_dbg(&csdev->dev, "ETM tracing enabled\n"); return ret; } @@ -565,7 +566,7 @@ static int etm_enable(struct coresight_device *csdev, struct perf_event *event, static void etm_disable_hw(struct etm_drvdata *drvdata) { int i; - struct etm_config *config = &drvdata->config; + struct etm_config *config = &drvdata->curr_config; struct coresight_device *csdev = drvdata->csdev; CS_UNLOCK(drvdata->csa.base); @@ -593,7 +594,6 @@ static void etm_disable_sysfs_smp_call(void *info) etm_disable_hw(drvdata); drvdata->csdev->path = NULL; - coresight_set_mode(drvdata->csdev, CS_MODE_DISABLED); } static void etm_disable_perf(struct coresight_device *csdev) @@ -630,8 +630,9 @@ static void etm_disable_perf(struct coresight_device *csdev) static void etm_disable_sysfs(struct coresight_device *csdev) { struct etm_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent); - - spin_lock(&drvdata->spinlock); + struct etm_config *config = &drvdata->config; + const struct etm_config *curr_config = &drvdata->curr_config; + int i; /* * Executing etm_disable_hw on the cpu whose ETM is being disabled @@ -640,7 +641,14 @@ static void etm_disable_sysfs(struct coresight_device *csdev) smp_call_function_single(drvdata->cpu, etm_disable_sysfs_smp_call, drvdata, 1); - spin_unlock(&drvdata->spinlock); + /* + * Userspace may read seq_curr_state and cntr_val through sysfs + * after the sysfs-session has been disabled. + */ + for (i = 0; i < drvdata->nr_cntr; i++) + config->cntr_val[i] = curr_config->cntr_val[i]; + + config->seq_curr_state = curr_config->seq_curr_state; /* * we only release trace IDs when resetting sysfs. @@ -649,6 +657,8 @@ static void etm_disable_sysfs(struct coresight_device *csdev) * prior trace id allocation method */ + coresight_set_mode(drvdata->csdev, CS_MODE_DISABLED); + dev_dbg(&csdev->dev, "ETM tracing disabled\n"); } diff --git a/drivers/hwtracing/coresight/coresight-etm3x-sysfs.c b/drivers/hwtracing/coresight/coresight-etm3x-sysfs.c index b3c67e96a82a..284998f18017 100644 --- a/drivers/hwtracing/coresight/coresight-etm3x-sysfs.c +++ b/drivers/hwtracing/coresight/coresight-etm3x-sysfs.c @@ -6,10 +6,48 @@ #include #include +#include #include #include "coresight-etm.h" #include "coresight-priv.h" +struct etm_readl_cslocked_arg { + struct etm_drvdata *drvdata; + u32 off; + unsigned long *val; +}; + +static void etm_readl_cslocked_smp_call(void *info) +{ + struct etm_readl_cslocked_arg *arg = info; + + CS_UNLOCK(arg->drvdata->csa.base); + *arg->val = etm_readl(arg->drvdata, arg->off); + CS_LOCK(arg->drvdata->csa.base); +} + +static int etm_readl_cslocked(struct etm_drvdata *drvdata, u32 off, + unsigned long *val) +{ + int ret; + struct etm_readl_cslocked_arg arg; + + ret = pm_runtime_get_sync(drvdata->csdev->dev.parent); + if (ret < 0) + goto out; + + arg.drvdata = drvdata; + arg.off = off; + arg.val = val; + + ret = smp_call_function_single(drvdata->cpu, + etm_readl_cslocked_smp_call, + (void *)&arg, 1); +out: + pm_runtime_put(drvdata->csdev->dev.parent); + return ret; +} + static ssize_t nr_addr_cmp_show(struct device *dev, struct device_attribute *attr, char *buf) { @@ -45,18 +83,13 @@ static DEVICE_ATTR_RO(nr_ctxid_cmp); static ssize_t etmsr_show(struct device *dev, struct device_attribute *attr, char *buf) { - unsigned long flags, val; + int ret; + unsigned long val; struct etm_drvdata *drvdata = dev_get_drvdata(dev->parent); - pm_runtime_get_sync(dev->parent); - spin_lock_irqsave(&drvdata->spinlock, flags); - CS_UNLOCK(drvdata->csa.base); - - val = etm_readl(drvdata, ETMSR); - - CS_LOCK(drvdata->csa.base); - spin_unlock_irqrestore(&drvdata->spinlock, flags); - pm_runtime_put(dev->parent); + ret = etm_readl_cslocked(drvdata, ETMSR, &val); + if (ret) + return ret; return sprintf(buf, "%#lx\n", val); } @@ -75,6 +108,10 @@ static ssize_t reset_store(struct device *dev, if (ret) return ret; + if (IS_ERR_OR_NULL(drvdata->csdev) || + coresight_get_mode(drvdata->csdev) == CS_MODE_SYSFS) + return -EBUSY; + if (val) { spin_lock(&drvdata->spinlock); memset(config, 0, sizeof(struct etm_config)); @@ -717,7 +754,9 @@ static DEVICE_ATTR_RW(cntr_rld_event); static ssize_t cntr_val_show(struct device *dev, struct device_attribute *attr, char *buf) { + int ret; u32 val; + unsigned long val2; struct etm_drvdata *drvdata = dev_get_drvdata(dev->parent); struct etm_config *config = &drvdata->config; @@ -726,7 +765,10 @@ static ssize_t cntr_val_show(struct device *dev, val = config->cntr_val[config->cntr_idx]; spin_unlock(&drvdata->spinlock); } else { - val = etm_readl(drvdata, ETMCNTVRn(config->cntr_idx)); + ret = etm_readl_cslocked(drvdata, ETMCNTVRn(config->cntr_idx), &val2); + if (ret) + return ret; + val = val2; } return sysfs_emit(buf, "%#x\n", val); @@ -744,6 +786,9 @@ static ssize_t cntr_val_store(struct device *dev, ret = kstrtoul(buf, 16, &val); if (ret) return ret; + if (IS_ERR_OR_NULL(drvdata->csdev) || + coresight_get_mode(drvdata->csdev) == CS_MODE_SYSFS) + return -EBUSY; spin_lock(&drvdata->spinlock); config->cntr_val[config->cntr_idx] = val; @@ -930,7 +975,8 @@ static DEVICE_ATTR_RW(seq_13_event); static ssize_t seq_curr_state_show(struct device *dev, struct device_attribute *attr, char *buf) { - unsigned long val, flags; + int ret; + unsigned long val; struct etm_drvdata *drvdata = dev_get_drvdata(dev->parent); struct etm_config *config = &drvdata->config; @@ -939,15 +985,10 @@ static ssize_t seq_curr_state_show(struct device *dev, goto out; } - pm_runtime_get_sync(dev->parent); - spin_lock_irqsave(&drvdata->spinlock, flags); - - CS_UNLOCK(drvdata->csa.base); - val = (etm_readl(drvdata, ETMSQR) & ETM_SQR_MASK); - CS_LOCK(drvdata->csa.base); - - spin_unlock_irqrestore(&drvdata->spinlock, flags); - pm_runtime_put(dev->parent); + ret = etm_readl_cslocked(drvdata, ETMSQR, &val); + if (ret) + return ret; + val &= ETM_SQR_MASK; out: return sprintf(buf, "%#lx\n", val); } diff --git a/drivers/hwtracing/coresight/coresight-etm4x-cfg.c b/drivers/hwtracing/coresight/coresight-etm4x-cfg.c index e1a59b434505..a9f6ed47a2f5 100644 --- a/drivers/hwtracing/coresight/coresight-etm4x-cfg.c +++ b/drivers/hwtracing/coresight/coresight-etm4x-cfg.c @@ -47,7 +47,7 @@ static int etm4_cfg_map_reg_offset(struct etmv4_drvdata *drvdata, struct cscfg_regval_csdev *reg_csdev, u32 offset) { int err = -EINVAL, idx; - struct etmv4_config *drvcfg = &drvdata->config; + struct etmv4_config *drvcfg = &drvdata->curr_config; u32 off_mask; if (((offset >= TRCEVENTCTL0R) && (offset <= TRCVIPCSSCTLR)) || @@ -154,11 +154,14 @@ static int etm4_cfg_load_feature(struct coresight_device *csdev, int i = 0, err = 0; /* - * essential we set the device spinlock - this is used in the generic - * programming routines when copying values into the drvdata structures - * via the pointers setup in etm4_cfg_map_reg_offset(). + * drvdata structure of etm4 for configfs is curr_config and + * this curr_config is protected with csdev->mode by restricting + * access to curr_config after mode changed to PERF or SYSFS. + * + * Therefore, it doesn't need to protected with etmv4_drvdata->spinlock + * to feature applying and set the NULL. */ - feat_csdev->drv_spinlock = &drvdata->spinlock; + feat_csdev->drv_spinlock = NULL; /* process the register descriptions */ for (i = 0; i < feat_csdev->nr_regs && !err; i++) { diff --git a/drivers/hwtracing/coresight/coresight-etm4x-core.c b/drivers/hwtracing/coresight/coresight-etm4x-core.c index 2247ad55d444..61e9971bdc6b 100644 --- a/drivers/hwtracing/coresight/coresight-etm4x-core.c +++ b/drivers/hwtracing/coresight/coresight-etm4x-core.c @@ -264,10 +264,11 @@ static void etm4x_prohibit_trace(struct etmv4_drvdata *drvdata) static u64 etm4x_get_kern_user_filter(struct etmv4_drvdata *drvdata) { u64 trfcr = drvdata->trfcr; + struct etmv4_config *config = &drvdata->curr_config; - if (drvdata->config.mode & ETM_MODE_EXCL_KERN) + if (config->mode & ETM_MODE_EXCL_KERN) trfcr &= ~TRFCR_EL1_ExTRE; - if (drvdata->config.mode & ETM_MODE_EXCL_USER) + if (config->mode & ETM_MODE_EXCL_USER) trfcr &= ~TRFCR_EL1_E0TRE; return trfcr; @@ -275,7 +276,7 @@ static u64 etm4x_get_kern_user_filter(struct etmv4_drvdata *drvdata) /* * etm4x_allow_trace - Allow CPU tracing in the respective ELs, - * as configured by the drvdata->config.mode for the current + * as configured by the drvdata->curr_config.mode for the current * session. Even though we have TRCVICTLR bits to filter the * trace in the ELs, it doesn't prevent the ETM from generating * a packet (e.g, TraceInfo) that might contain the addresses from @@ -286,12 +287,13 @@ static u64 etm4x_get_kern_user_filter(struct etmv4_drvdata *drvdata) static void etm4x_allow_trace(struct etmv4_drvdata *drvdata) { u64 trfcr, guest_trfcr; + struct etmv4_config *config = &drvdata->curr_config; /* If the CPU doesn't support FEAT_TRF, nothing to do */ if (!drvdata->trfcr) return; - if (drvdata->config.mode & ETM_MODE_EXCL_HOST) + if (config->mode & ETM_MODE_EXCL_HOST) trfcr = drvdata->trfcr & ~(TRFCR_EL1_ExTRE | TRFCR_EL1_E0TRE); else trfcr = etm4x_get_kern_user_filter(drvdata); @@ -299,7 +301,7 @@ static void etm4x_allow_trace(struct etmv4_drvdata *drvdata) write_trfcr(trfcr); /* Set filters for guests and pass to KVM */ - if (drvdata->config.mode & ETM_MODE_EXCL_GUEST) + if (config->mode & ETM_MODE_EXCL_GUEST) guest_trfcr = drvdata->trfcr & ~(TRFCR_EL1_ExTRE | TRFCR_EL1_E0TRE); else guest_trfcr = etm4x_get_kern_user_filter(drvdata); @@ -492,7 +494,7 @@ static int etm4_enable_trace_unit(struct etmv4_drvdata *drvdata) static int etm4_enable_hw(struct etmv4_drvdata *drvdata) { int i, rc; - struct etmv4_config *config = &drvdata->config; + struct etmv4_config *config = &drvdata->curr_config; struct coresight_device *csdev = drvdata->csdev; struct device *etm_dev = &csdev->dev; struct csdev_access *csa = &csdev->access; @@ -612,27 +614,42 @@ static int etm4_enable_hw(struct etmv4_drvdata *drvdata) static void etm4_enable_sysfs_smp_call(void *info) { struct etm4_enable_arg *arg = info; + struct etmv4_drvdata *drvdata; struct coresight_device *csdev; + unsigned long cfg_hash; + int preset; if (WARN_ON(!arg)) return; - csdev = arg->drvdata->csdev; - if (!coresight_take_mode(csdev, CS_MODE_SYSFS)) { - /* Someone is already using the tracer */ - arg->rc = -EBUSY; - return; + drvdata = arg->drvdata; + csdev = drvdata->csdev; + + /* enable any config activated by configfs */ + cscfg_config_sysfs_get_active_cfg(&cfg_hash, &preset); + if (cfg_hash) { + arg->rc = cscfg_csdev_enable_active_config(csdev, + cfg_hash, + preset); + if (arg->rc) + return; } - arg->rc = etm4_enable_hw(arg->drvdata); + drvdata->trcid = arg->path->trace_id; + + /* Tracer will never be paused in sysfs mode */ + drvdata->paused = false; - /* The tracer didn't start */ + arg->rc = etm4_enable_hw(drvdata); if (arg->rc) { - coresight_set_mode(csdev, CS_MODE_DISABLED); + cscfg_csdev_disable_active_config(csdev); return; } + drvdata->sticky_enable = true; csdev->path = arg->path; + + return; } /* @@ -669,7 +686,7 @@ static int etm4_config_timestamp_event(struct etmv4_drvdata *drvdata, { int ctridx; int rselector; - struct etmv4_config *config = &drvdata->config; + struct etmv4_config *config = &drvdata->curr_config; /* No point in trying if we don't have at least one counter */ if (!drvdata->nr_cntr) @@ -752,7 +769,7 @@ static int etm4_parse_event_config(struct coresight_device *csdev, { int ret = 0; struct etmv4_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent); - struct etmv4_config *config = &drvdata->config; + struct etmv4_config *config = &drvdata->curr_config; struct perf_event_attr max_timestamp = { .ATTR_CFG_FLD_timestamp_CFG = U64_MAX, }; @@ -919,46 +936,36 @@ static int etm4_enable_sysfs(struct coresight_device *csdev, struct coresight_pa { struct etmv4_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent); struct etm4_enable_arg arg = { }; - unsigned long cfg_hash; - int ret, preset; + int ret; - /* enable any config activated by configfs */ - cscfg_config_sysfs_get_active_cfg(&cfg_hash, &preset); - if (cfg_hash) { - ret = cscfg_csdev_enable_active_config(csdev, cfg_hash, preset); - if (ret) { - etm4_release_trace_id(drvdata); - return ret; - } + if (!coresight_take_mode(csdev, CS_MODE_SYSFS)) { + /* Someone is already using the tracer */ + return -EBUSY; } - raw_spin_lock(&drvdata->spinlock); - - drvdata->trcid = path->trace_id; - - /* Tracer will never be paused in sysfs mode */ - drvdata->paused = false; - /* * Executing etm4_enable_hw on the cpu whose ETM is being enabled * ensures that register writes occur when cpu is powered. */ arg.drvdata = drvdata; arg.path = path; + + scoped_guard(raw_spinlock, &drvdata->spinlock) { + drvdata->curr_config = drvdata->config; + } + ret = smp_call_function_single(drvdata->cpu, etm4_enable_sysfs_smp_call, &arg, 1); if (!ret) ret = arg.rc; - if (!ret) - drvdata->sticky_enable = true; - - if (ret) + if (!ret) { + dev_dbg(&csdev->dev, "ETM tracing enabled\n"); + } else { etm4_release_trace_id(drvdata); + /* The tracer didn't start */ + coresight_set_mode(csdev, CS_MODE_DISABLED); + } - raw_spin_unlock(&drvdata->spinlock); - - if (!ret) - dev_dbg(&csdev->dev, "ETM tracing enabled\n"); return ret; } @@ -1044,7 +1051,7 @@ static void etm4_disable_trace_unit(struct etmv4_drvdata *drvdata) static void etm4_disable_hw(struct etmv4_drvdata *drvdata) { u32 control; - struct etmv4_config *config = &drvdata->config; + struct etmv4_config *config = &drvdata->curr_config; struct coresight_device *csdev = drvdata->csdev; struct csdev_access *csa = &csdev->access; int i; @@ -1073,6 +1080,10 @@ static void etm4_disable_hw(struct etmv4_drvdata *drvdata) etm4x_relaxed_read32(csa, TRCCNTVRn(i)); } + /* read back the sequence state */ + if (drvdata->nrseqstate) + config->seq_state = etm4x_relaxed_read32(csa, TRCSEQSTR); + coresight_disclaim_device_unlocked(csdev); etm4_cs_lock(drvdata, csa); @@ -1086,8 +1097,9 @@ static void etm4_disable_sysfs_smp_call(void *info) etm4_disable_hw(drvdata); + cscfg_csdev_disable_active_config(drvdata->csdev); + drvdata->csdev->path = NULL; - coresight_set_mode(drvdata->csdev, CS_MODE_DISABLED); } static int etm4_disable_perf(struct coresight_device *csdev, @@ -1130,8 +1142,9 @@ static int etm4_disable_perf(struct coresight_device *csdev, static void etm4_disable_sysfs(struct coresight_device *csdev) { struct etmv4_drvdata *drvdata = dev_get_drvdata(csdev->dev.parent); - - raw_spin_lock(&drvdata->spinlock); + struct etmv4_config *config = &drvdata->config; + const struct etmv4_config *curr_config = &drvdata->curr_config; + int i; /* * Executing etm4_disable_hw on the cpu whose ETM is being disabled @@ -1140,9 +1153,19 @@ static void etm4_disable_sysfs(struct coresight_device *csdev) smp_call_function_single(drvdata->cpu, etm4_disable_sysfs_smp_call, drvdata, 1); - raw_spin_unlock(&drvdata->spinlock); + /* + * Userspace may read ss_status and cntr_val through sysfs after + * the sysfs-session has been disabled. + */ + for (i = 0; i < drvdata->nr_ss_cmp; i++) + config->ss_status[i] = curr_config->ss_status[i]; + + for (i = 0; i < drvdata->nr_cntr; i++) + config->cntr_val[i] = curr_config->cntr_val[i]; - cscfg_csdev_disable_active_config(csdev); + config->seq_state = curr_config->seq_state; + + coresight_set_mode(drvdata->csdev, CS_MODE_DISABLED); /* * we only release trace IDs when resetting sysfs. @@ -1690,7 +1713,7 @@ static void etm4_set_default(struct etmv4_config *config) static int etm4_get_next_comparator(struct etmv4_drvdata *drvdata, u32 type) { int nr_comparator, index = 0; - struct etmv4_config *config = &drvdata->config; + struct etmv4_config *config = &drvdata->curr_config; /* * nr_addr_cmp holds the number of comparator _pair_, so time 2 @@ -1731,7 +1754,7 @@ static int etm4_set_event_filters(struct etmv4_drvdata *drvdata, { int i, comparator, ret = 0; u64 address; - struct etmv4_config *config = &drvdata->config; + struct etmv4_config *config = &drvdata->curr_config; struct etm_filters *filters = event->hw.addr_filters; if (!filters) diff --git a/drivers/hwtracing/coresight/coresight-etm4x-sysfs.c b/drivers/hwtracing/coresight/coresight-etm4x-sysfs.c index cc6cdd3ae29d..f4d7286b053a 100644 --- a/drivers/hwtracing/coresight/coresight-etm4x-sysfs.c +++ b/drivers/hwtracing/coresight/coresight-etm4x-sysfs.c @@ -1435,6 +1435,9 @@ static ssize_t seq_state_store(struct device *dev, if (kstrtoul(buf, 16, &val)) return -EINVAL; + if (IS_ERR_OR_NULL(drvdata->csdev) || + coresight_get_mode(drvdata->csdev) == CS_MODE_SYSFS) + return -EBUSY; if (val >= drvdata->nrseqstate) return -EINVAL; @@ -1613,6 +1616,9 @@ static ssize_t cntr_val_store(struct device *dev, return -EINVAL; if (val > ETM_CNTR_MAX_VAL) return -EINVAL; + if (IS_ERR_OR_NULL(drvdata->csdev) || + coresight_get_mode(drvdata->csdev) == CS_MODE_SYSFS) + return -EBUSY; raw_spin_lock(&drvdata->spinlock); idx = config->cntr_idx; diff --git a/drivers/hwtracing/coresight/coresight-etm4x.h b/drivers/hwtracing/coresight/coresight-etm4x.h index df9e0748d71e..52f66e26ceaa 100644 --- a/drivers/hwtracing/coresight/coresight-etm4x.h +++ b/drivers/hwtracing/coresight/coresight-etm4x.h @@ -1019,7 +1019,8 @@ struct etmv4_save_state { * allows tracing at all ELs. We don't want to compute this * at runtime, due to the additional setting of TRFCR_CX when * in EL2. Otherwise, 0. - * @config: structure holding configuration parameters. + * @curr_config: structure holding current applied configuration. + * @config: structure holding sysfs mode configuration. * @save_state: State to be preserved across power loss * @skip_power_up: Indicates if an implementation can skip powering up * the trace unit. @@ -1077,6 +1078,7 @@ struct etmv4_drvdata { bool skip_power_up : 1; bool paused : 1; u64 trfcr; + struct etmv4_config curr_config; struct etmv4_config config; struct etmv4_save_state *save_state; DECLARE_BITMAP(arch_features, ETM4_IMPDEF_FEATURE_MAX); diff --git a/drivers/i3c/device.c b/drivers/i3c/device.c index f1ba363b22a1..4df4682af150 100644 --- a/drivers/i3c/device.c +++ b/drivers/i3c/device.c @@ -301,16 +301,23 @@ i3c_device_match_id(struct i3c_device *i3cdev, EXPORT_SYMBOL_GPL(i3c_device_match_id); /** - * i3c_device_get_supported_xfer_mode - Returns the supported transfer mode by - * connected master controller. + * i3c_device_get_supported_xfer_mode - Returns the transfer modes supported by + * the connected master controller and @dev, + * and allowed by the bus configuration. * @dev: I3C device * * Return: a bit mask, which supported transfer mode, bit position is defined at - * enum i3c_hdr_mode + * enum i3c_xfer_mode */ u32 i3c_device_get_supported_xfer_mode(struct i3c_device *dev) { - return i3c_bus_to_i3c_master(dev->bus)->this->info.hdr_cap | BIT(I3C_SDR); + u32 modes; + + i3c_bus_normaluse_lock(dev->bus); + modes = i3c_dev_supported_xfer_modes_locked(dev->desc); + i3c_bus_normaluse_unlock(dev->bus); + + return modes; } EXPORT_SYMBOL_GPL(i3c_device_get_supported_xfer_mode); diff --git a/drivers/i3c/internals.h b/drivers/i3c/internals.h index 86a36b951e0d..9a6936e2c660 100644 --- a/drivers/i3c/internals.h +++ b/drivers/i3c/internals.h @@ -18,6 +18,8 @@ bool i3c_bus_rpm_ibi_allowed(struct i3c_bus *bus); void i3c_bus_normaluse_lock(struct i3c_bus *bus); void i3c_bus_normaluse_unlock(struct i3c_bus *bus); +u32 i3c_dev_supported_xfer_modes_locked(struct i3c_dev_desc *dev); + int i3c_dev_setdasa_locked(struct i3c_dev_desc *dev); int i3c_dev_do_xfers_locked(struct i3c_dev_desc *dev, struct i3c_xfer *xfers, diff --git a/drivers/i3c/master.c b/drivers/i3c/master.c index f9a6c8560fab..b6a95a1708ee 100644 --- a/drivers/i3c/master.c +++ b/drivers/i3c/master.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -937,6 +938,61 @@ static int i3c_bus_set_mode(struct i3c_bus *i3cbus, enum i3c_bus_mode mode, return 0; } +/* + * I3C v1.1.1 Section 5.1.2.4 Table 9 lists the HDR Modes each Bus + * Configuration allows. A Mixed Slow / Limited Bus has Legacy I2C Devices + * without a 50 ns spike filter, so there is no way to hide any HDR Mode from + * them. Of the two Ternary Modes, only HDR-TSL is defined for a Bus that + * also has Legacy I2C Devices; HDR-TSP is defined for a Pure Bus. + */ +static u32 i3c_bus_hdr_modes(struct i3c_bus *bus) +{ + switch (bus->mode) { + case I3C_BUS_MODE_PURE: + return BIT(I3C_HDR_DDR) | BIT(I3C_HDR_TSP) | BIT(I3C_HDR_TSL); + case I3C_BUS_MODE_MIXED_FAST: + return BIT(I3C_HDR_DDR) | BIT(I3C_HDR_TSL); + case I3C_BUS_MODE_MIXED_LIMITED: + case I3C_BUS_MODE_MIXED_SLOW: + break; + } + + return 0; +} + +static u32 i3c_dev_hdr_modes(struct i3c_dev_desc *dev) +{ + if (!(dev->info.bcr & I3C_BCR_HDR_CAP)) + return 0; + + return dev->info.hdr_cap; +} + +/** + * i3c_dev_supported_xfer_modes_locked() - Get the transfer modes usable with a + * device + * @dev: I3C device descriptor + * + * The HDR Modes the controller and @dev both support, restricted to those the + * bus configuration allows. SDR is always supported. + * + * The bus lock must be held in normal use mode. + * + * Return: a bit mask of &enum i3c_xfer_mode values. + */ +u32 i3c_dev_supported_xfer_modes_locked(struct i3c_dev_desc *dev) +{ + struct i3c_master_controller *master = i3c_dev_get_master(dev); + + /* + * master->this->info.bcr is ignored because it describes the master's + * target capability, not its controller capability. + */ + return (master->this->info.hdr_cap & + i3c_bus_hdr_modes(&master->bus) & + i3c_dev_hdr_modes(dev)) | BIT(I3C_SDR); +} + static struct i3c_master_controller * i2c_adapter_to_i3c_master(struct i2c_adapter *adap) { @@ -3076,6 +3132,13 @@ static int i3c_master_add_of_dev(struct i3c_master_controller *master, return ret; } +#define I3C_ACPI_ADR_PID GENMASK_U64(47, 0) +/* + * Zero-based instance number of the Bus Controller to which the Target is + * connected. + */ +#define I3C_ACPI_ADR_INSTANCE GENMASK_U64(51, 48) + #ifdef CONFIG_ACPI static int i3c_master_add_acpi_dev(struct i3c_master_controller *master, struct fwnode_handle *fwnode) @@ -3083,6 +3146,7 @@ static int i3c_master_add_acpi_dev(struct i3c_master_controller *master, struct acpi_device *adev = to_acpi_device_node(fwnode); acpi_bus_address adr; u32 reg[3] = { 0 }; + u64 pid; int ret; /* @@ -3100,9 +3164,15 @@ static int i3c_master_add_acpi_dev(struct i3c_master_controller *master, adr = acpi_device_adr(adev); + /* Match the multi-bus instance number */ + if (FIELD_GET(I3C_ACPI_ADR_INSTANCE, adr) != master->instance) + return 0; + /* For I3C devices, _ADR will have the 48 bit PID of the device */ - reg[1] = upper_32_bits(adr); - reg[2] = lower_32_bits(adr); + pid = FIELD_GET(I3C_ACPI_ADR_PID, adr); + + reg[1] = upper_32_bits(pid); + reg[2] = lower_32_bits(pid); fwnode_property_read_u32(fwnode, "mipi-i3c-static-address", ®[0]); @@ -3846,7 +3916,7 @@ int i3c_dev_do_xfers_locked(struct i3c_dev_desc *dev, struct i3c_xfer *xfers, if (!master || !xfers) return -EINVAL; - if (mode != I3C_SDR && !(master->this->info.hdr_cap & BIT(mode))) + if (mode != I3C_SDR && !(i3c_dev_supported_xfer_modes_locked(dev) & BIT(mode))) return -EOPNOTSUPP; return master->ops->i3c_xfers(dev, xfers, nxfers, mode); diff --git a/drivers/i3c/master/mipi-i3c-hci/core.c b/drivers/i3c/master/mipi-i3c-hci/core.c index dadf049bd4b5..1ede0d2428cf 100644 --- a/drivers/i3c/master/mipi-i3c-hci/core.c +++ b/drivers/i3c/master/mipi-i3c-hci/core.c @@ -675,11 +675,13 @@ static void __i3c_hci_disable_ibi(struct i3c_hci *hci, struct i3c_dev_desc *dev) static void i3c_hci_free_ibi(struct i3c_dev_desc *dev) { + struct i3c_hci_dev_data *dev_data = i3c_dev_get_master_data(dev); struct i3c_master_controller *m = i3c_dev_get_master(dev); struct i3c_hci *hci = to_i3c_hci(m); - /* Must ensure the IBI has been disabled */ - __i3c_hci_disable_ibi(hci, dev); + /* Must ensure IBIs for this device will no longer be processed */ + scoped_guard(spinlock_irqsave, &hci->lock) + hci->ibi_devs[dev_data->dat_idx] = NULL; hci->io->free_ibi(hci, dev); } @@ -703,11 +705,15 @@ static int i3c_hci_enable_ibi(struct i3c_dev_desc *dev) struct i3c_master_controller *m = i3c_dev_get_master(dev); struct i3c_hci *hci = to_i3c_hci(m); struct i3c_hci_dev_data *dev_data = i3c_dev_get_master_data(dev); + int ret; mipi_i3c_hci_dat_v1.clear_flags(hci, dev_data->dat_idx, DAT_0_SIR_REJECT, 0); scoped_guard(spinlock_irqsave, &hci->lock) hci->ibi_devs[dev_data->dat_idx] = dev; - return i3c_master_enec_locked(m, dev->info.dyn_addr, I3C_CCC_EVENT_SIR); + ret = i3c_master_enec_locked(m, dev->info.dyn_addr, I3C_CCC_EVENT_SIR); + if (ret) + __i3c_hci_disable_ibi(hci, dev); + return ret; } static int i3c_hci_disable_ibi(struct i3c_dev_desc *dev) @@ -1142,8 +1148,10 @@ static int i3c_hci_probe(struct platform_device *pdev) * necessarily in separate contiguous sub-ranges. To avoid overlapping * mappings, provide base_regs from the parent mapping. */ - if (pdata) + if (pdata) { hci->base_regs = pdata->base_regs; + hci->master.instance = pdata->instance; + } if (!hci->base_regs) { hci->base_regs = devm_platform_ioremap_resource(pdev, 0); diff --git a/drivers/i3c/master/mipi-i3c-hci/dma.c b/drivers/i3c/master/mipi-i3c-hci/dma.c index 5b195978f376..b8fcea0870ab 100644 --- a/drivers/i3c/master/mipi-i3c-hci/dma.c +++ b/drivers/i3c/master/mipi-i3c-hci/dma.c @@ -15,6 +15,7 @@ #include #include #include +#include #include "hci.h" #include "cmd.h" @@ -273,29 +274,6 @@ static void hci_dma_init_rings(struct i3c_hci *hci) hci_dma_init_rh(hci, &rings->headers[i], i); } -static void hci_dma_suspend(struct i3c_hci *hci) -{ - struct hci_rings_data *rings = hci->io_data; - int n = rings ? rings->total : 0; - - for (int i = 0; i < n; i++) { - struct hci_rh_data *rh = &rings->headers[i]; - - rh_reg_write(INTR_SIGNAL_ENABLE, 0); - rh_reg_write(RING_CONTROL, 0); - } - - i3c_hci_sync_irq_inactive(hci); -} - -static void hci_dma_resume(struct i3c_hci *hci) -{ - struct hci_rings_data *rings = hci->io_data; - - if (rings) - hci_dma_init_rings(hci); -} - static int hci_dma_init(struct i3c_hci *hci) { struct hci_rings_data *rings; @@ -868,25 +846,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; @@ -936,7 +913,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; @@ -1015,10 +992,9 @@ static void hci_dma_process_ibi(struct i3c_hci *hci, struct hci_rh_data *rh) i3c_master_queue_ibi(dev, slot); done: - 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 &= ~RING_OP1_IBI_DEQ_PTR; + *op1_val |= FIELD_PREP(RING_OP1_IBI_DEQ_PTR, deq_ptr); + rh_reg_write(RING_OPERATION1, *op1_val); /* update the chunk pointer */ rh->ibi_chunk_ptr += ibi_chunks; @@ -1026,6 +1002,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) @@ -1047,7 +1036,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) @@ -1064,6 +1053,77 @@ static bool hci_dma_irq_handler(struct i3c_hci *hci) return handled; } +/* + * With the bus disabled, a ring should stop within a few microseconds. The + * timeout is therefore only expected to expire if the hardware is stuck. + * Allow sufficient margin for slow systems, but keep the delay acceptable + * during suspend. + */ +#define RING_STOP_TIMEOUT_US (100 * USEC_PER_MSEC) +/* + * The ring is usually already stopped, so polling typically completes on the + * first iteration. Use a modest sleep interval to avoid busy-waiting without + * adding excessive latency. + */ +#define RING_STOP_SLEEP_US 100 + +static void hci_dma_suspend(struct i3c_hci *hci) +{ + struct hci_rings_data *rings = hci->io_data; + int n = rings ? rings->total : 0; + struct hci_rh_data *rh; + u32 regval; + + /* Gracefully stop the rings */ + scoped_guard(spinlock_irqsave, &hci->lock) { + for (int i = 0; i < n; i++) { + rh = &rings->headers[i]; + regval = rh_reg_read(RING_CONTROL); + if (regval & RING_CTRL_RUN_STOP) + rh_reg_write(RING_CONTROL, regval & ~RING_CTRL_RUN_STOP); + } + } + + /* Wait for actual stop */ + for (int i = 0; i < n; i++) { + rh = &rings->headers[i]; + if (readx_poll_timeout(readl, rh->regs + RH_RING_STATUS, regval, + !(regval & RING_STATUS_RUNNING), + RING_STOP_SLEEP_US, RING_STOP_TIMEOUT_US)) + dev_err(&hci->master.dev, "%s: Ring did not stop, status %#x\n", + __func__, regval); + } + + /* + * With the rings stopped, no more IBIs can be received. Flush and make + * the interrupt handler inactive. + */ + i3c_hci_sync_irq_inactive(hci); + + /* Disable interrupt signals and disable the rings */ + scoped_guard(spinlock_irqsave, &hci->lock) + for (int i = 0; i < n; i++) { + rh = &rings->headers[i]; + rh_reg_write(INTR_SIGNAL_ENABLE, 0); + /* + * Be absolutely certain there is no unprocessed IBI. + * hci_dma_drain_ibi_ring() will do nothing if there is + * none. + */ + if (i < IBI_RINGS) + hci_dma_drain_ibi_ring(hci, rh); + rh_reg_write(RING_CONTROL, 0); + } +} + +static void hci_dma_resume(struct i3c_hci *hci) +{ + struct hci_rings_data *rings = hci->io_data; + + if (rings) + hci_dma_init_rings(hci); +} + const struct hci_io_ops mipi_i3c_hci_dma = { .init = hci_dma_init, .cleanup = hci_dma_cleanup, diff --git a/drivers/i3c/master/mipi-i3c-hci/mipi-i3c-hci-pci.c b/drivers/i3c/master/mipi-i3c-hci/mipi-i3c-hci-pci.c index af9595009b03..5b8e10d05cee 100644 --- a/drivers/i3c/master/mipi-i3c-hci/mipi-i3c-hci-pci.c +++ b/drivers/i3c/master/mipi-i3c-hci/mipi-i3c-hci-pci.c @@ -390,6 +390,7 @@ static void mipi_i3c_hci_pci_setup_cell(struct mipi_i3c_hci_pci *hci, int idx, struct mfd_cell *cell) { data->pdata.base_regs = hci->base + hci->info->instance_offset[idx]; + data->pdata.instance = idx; data->res = DEFINE_RES_IRQ(0); diff --git a/drivers/iio/accel/bma220_spi.c b/drivers/iio/accel/bma220_spi.c index d6c1087cc3c0..d7a95289df48 100644 --- a/drivers/iio/accel/bma220_spi.c +++ b/drivers/iio/accel/bma220_spi.c @@ -28,12 +28,13 @@ static const struct spi_device_id bma220_spi_id[] = { { .name = "bma220" }, { } }; +MODULE_DEVICE_TABLE(spi, bma220_spi_id); static const struct acpi_device_id bma220_acpi_id[] = { { "BMA0220", 0 }, { } }; -MODULE_DEVICE_TABLE(spi, bma220_spi_id); +MODULE_DEVICE_TABLE(acpi, bma220_acpi_id); static const struct of_device_id bma220_of_spi_match[] = { { .compatible = "bosch,bma220" }, diff --git a/drivers/iio/accel/kionix-kx022a.h b/drivers/iio/accel/kionix-kx022a.h index 0ed54f584223..a2d122c1e234 100644 --- a/drivers/iio/accel/kionix-kx022a.h +++ b/drivers/iio/accel/kionix-kx022a.h @@ -65,7 +65,7 @@ #define KX022A_MASK_IEN BIT(5) #define KX022A_MASK_IPOL BIT(4) #define KX022A_IPOL_LOW 0 -#define KX022A_IPOL_HIGH KX022A_MASK_IPOL1 +#define KX022A_IPOL_HIGH KX022A_MASK_IPOL #define KX022A_MASK_ITYP BIT(3) #define KX022A_ITYP_PULSE KX022A_MASK_ITYP #define KX022A_ITYP_LEVEL 0 diff --git a/drivers/iio/dac/ad5758.c b/drivers/iio/dac/ad5758.c index 44efa373cd80..1e21ad2a050d 100644 --- a/drivers/iio/dac/ad5758.c +++ b/drivers/iio/dac/ad5758.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -117,7 +118,7 @@ struct ad5758_state { unsigned int dc_dc_ilim; unsigned int slew_time; bool pwr_down; - __be32 d32[3]; + __be32 d32[3] __aligned(IIO_DMA_MINALIGN); }; /* @@ -540,7 +541,7 @@ static int ad5758_read_raw(struct iio_dev *indio_dev, case IIO_CHAN_INFO_OFFSET: min = st->out_range.min; max = st->out_range.max; - *val = ((min * (1 << 16)) / (max - min)) / 1000; + *val = div_s64((s64)min * (1 << 16), max - min); return IIO_VAL_INT; default: return -EINVAL; @@ -556,6 +557,9 @@ static int ad5758_write_raw(struct iio_dev *indio_dev, switch (info) { case IIO_CHAN_INFO_RAW: + if (val < 0 || val > U16_MAX) + return -EINVAL; + mutex_lock(&st->lock); ret = ad5758_spi_reg_write(st, AD5758_DAC_INPUT, val); mutex_unlock(&st->lock); diff --git a/drivers/iio/dac/mcp47feb02.c b/drivers/iio/dac/mcp47feb02.c index baeb1be455c6..5353013ff98c 100644 --- a/drivers/iio/dac/mcp47feb02.c +++ b/drivers/iio/dac/mcp47feb02.c @@ -442,8 +442,6 @@ static int mcp47feb02_write_to_eeprom(struct mcp47feb02_data *data, unsigned int * Wait until the currently occurring EEPROM Write Cycle is completed. * Only serial commands to the volatile memory are allowed. */ - guard(mutex)(&data->lock); - ret = regmap_read_poll_timeout(data->regmap, MCP47FEB02_GAIN_CTRL_STATUS_REG_ADDR, eewa_val, !(eewa_val & MCP47FEB02_GAIN_BIT_STATUS_EEWA_MASK), @@ -469,6 +467,8 @@ static ssize_t store_eeprom_store(struct device *dev, struct device_attribute *a if (!state) return len; + guard(mutex)(&data->lock); + /* * Verify DAC Wiper and DAC Configuration are unlocked. If both are disabled, * writing to EEPROM is available. diff --git a/drivers/iio/humidity/hts221_core.c b/drivers/iio/humidity/hts221_core.c index bfeb0a60d3af..76a391f421f5 100644 --- a/drivers/iio/humidity/hts221_core.c +++ b/drivers/iio/humidity/hts221_core.c @@ -10,7 +10,6 @@ #include #include #include -#include #include #include #include @@ -49,7 +48,7 @@ struct hts221_odr { struct hts221_avg { u8 addr; u8 mask; - u16 avg_avl[HTS221_AVG_DEPTH]; + int avg_avl[HTS221_AVG_DEPTH]; }; static const struct hts221_odr hts221_odr_table[] = { @@ -58,6 +57,8 @@ static const struct hts221_odr hts221_odr_table[] = { { 13, 0x03 }, /* 12.5Hz */ }; +static const int hts221_odr_avail[] = { 1, 7, 13 }; + static const struct hts221_avg hts221_avg_list[] = { { .addr = 0x10, @@ -97,7 +98,11 @@ static const struct iio_chan_spec hts221_channels[] = { BIT(IIO_CHAN_INFO_OFFSET) | BIT(IIO_CHAN_INFO_SCALE) | BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), + .info_mask_separate_available = + BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ), + .info_mask_shared_by_all_available = + BIT(IIO_CHAN_INFO_SAMP_FREQ), .scan_index = 0, .scan_type = { .sign = 's', @@ -113,7 +118,11 @@ static const struct iio_chan_spec hts221_channels[] = { BIT(IIO_CHAN_INFO_OFFSET) | BIT(IIO_CHAN_INFO_SCALE) | BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), + .info_mask_separate_available = + BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ), + .info_mask_shared_by_all_available = + BIT(IIO_CHAN_INFO_SAMP_FREQ), .scan_index = 1, .scan_type = { .sign = 's', @@ -192,53 +201,35 @@ static int hts221_update_avg(struct hts221_hw *hw, return 0; } -static ssize_t hts221_sysfs_sampling_freq(struct device *dev, - struct device_attribute *attr, - char *buf) -{ - int i; - ssize_t len = 0; - - for (i = 0; i < ARRAY_SIZE(hts221_odr_table); i++) - len += scnprintf(buf + len, PAGE_SIZE - len, "%d ", - hts221_odr_table[i].hz); - buf[len - 1] = '\n'; - - return len; -} - -static ssize_t -hts221_sysfs_rh_oversampling_avail(struct device *dev, - struct device_attribute *attr, - char *buf) -{ - const struct hts221_avg *avg = &hts221_avg_list[HTS221_SENSOR_H]; - ssize_t len = 0; - int i; - - for (i = 0; i < ARRAY_SIZE(avg->avg_avl); i++) - len += scnprintf(buf + len, PAGE_SIZE - len, "%d ", - avg->avg_avl[i]); - buf[len - 1] = '\n'; - - return len; -} - -static ssize_t -hts221_sysfs_temp_oversampling_avail(struct device *dev, - struct device_attribute *attr, - char *buf) +static int hts221_read_avail(struct iio_dev *indio_dev, + struct iio_chan_spec const *chan, + const int **vals, int *type, int *length, + long mask) { - const struct hts221_avg *avg = &hts221_avg_list[HTS221_SENSOR_T]; - ssize_t len = 0; - int i; - - for (i = 0; i < ARRAY_SIZE(avg->avg_avl); i++) - len += scnprintf(buf + len, PAGE_SIZE - len, "%d ", - avg->avg_avl[i]); - buf[len - 1] = '\n'; - - return len; + switch (mask) { + case IIO_CHAN_INFO_OVERSAMPLING_RATIO: + switch (chan->type) { + case IIO_HUMIDITYRELATIVE: + *vals = hts221_avg_list[HTS221_SENSOR_H].avg_avl; + *length = ARRAY_SIZE(hts221_avg_list[HTS221_SENSOR_H].avg_avl); + break; + case IIO_TEMP: + *vals = hts221_avg_list[HTS221_SENSOR_T].avg_avl; + *length = ARRAY_SIZE(hts221_avg_list[HTS221_SENSOR_T].avg_avl); + break; + default: + return -EINVAL; + } + *type = IIO_VAL_INT; + return IIO_AVAIL_LIST; + case IIO_CHAN_INFO_SAMP_FREQ: + *vals = hts221_odr_avail; + *type = IIO_VAL_INT; + *length = ARRAY_SIZE(hts221_odr_avail); + return IIO_AVAIL_LIST; + default: + return -EINVAL; + } } int hts221_set_enable(struct hts221_hw *hw, bool enable) @@ -521,27 +512,10 @@ static int hts221_validate_trigger(struct iio_dev *iio_dev, return hw->trig == trig ? 0 : -EINVAL; } -static IIO_DEVICE_ATTR(in_humidity_oversampling_ratio_available, S_IRUGO, - hts221_sysfs_rh_oversampling_avail, NULL, 0); -static IIO_DEVICE_ATTR(in_temp_oversampling_ratio_available, S_IRUGO, - hts221_sysfs_temp_oversampling_avail, NULL, 0); -static IIO_DEV_ATTR_SAMP_FREQ_AVAIL(hts221_sysfs_sampling_freq); - -static struct attribute *hts221_attributes[] = { - &iio_dev_attr_sampling_frequency_available.dev_attr.attr, - &iio_dev_attr_in_humidity_oversampling_ratio_available.dev_attr.attr, - &iio_dev_attr_in_temp_oversampling_ratio_available.dev_attr.attr, - NULL, -}; - -static const struct attribute_group hts221_attribute_group = { - .attrs = hts221_attributes, -}; - static const struct iio_info hts221_info = { - .attrs = &hts221_attribute_group, .read_raw = hts221_read_raw, .write_raw = hts221_write_raw, + .read_avail = hts221_read_avail, .validate_trigger = hts221_validate_trigger, }; diff --git a/drivers/iio/imu/adis16400.c b/drivers/iio/imu/adis16400.c index 512a8da63cdc..79f2974d3777 100644 --- a/drivers/iio/imu/adis16400.c +++ b/drivers/iio/imu/adis16400.c @@ -420,7 +420,10 @@ static int adis16400_initial_setup(struct iio_dev *indio_dev) else st->adis.spi->max_speed_hz = ADIS16400_SPI_FAST; st->adis.spi->mode = SPI_MODE_3; - spi_setup(st->adis.spi); + + ret = spi_setup(st->adis.spi); + if (ret) + return ret; ret = __adis_initial_startup(&st->adis); if (ret) diff --git a/drivers/iio/pressure/rohm-bm1390.c b/drivers/iio/pressure/rohm-bm1390.c index f9deb48e6a41..d1268c289831 100644 --- a/drivers/iio/pressure/rohm-bm1390.c +++ b/drivers/iio/pressure/rohm-bm1390.c @@ -479,6 +479,7 @@ static const struct iio_info bm1390_info = { static int bm1390_chip_init(struct bm1390_data *data) { + u8 regval; int ret; ret = regmap_write_bits(data->regmap, BM1390_REG_POWER, @@ -512,8 +513,9 @@ static int bm1390_chip_init(struct bm1390_data *data) * Default to use IIR filter in "middle" mode. Also the AVE_NUM must * be fixed when IIR is in use. */ + regval = FIELD_PREP(BM1390_MASK_AVE_NUM, BM1390_IIR_AVE_NUM); ret = regmap_update_bits(data->regmap, BM1390_REG_MODE_CTRL, - BM1390_MASK_AVE_NUM, BM1390_IIR_AVE_NUM); + BM1390_MASK_AVE_NUM, regval); if (ret) return ret; diff --git a/drivers/iio/temperature/tmp117.c b/drivers/iio/temperature/tmp117.c index 74cb8d62bef3..3d8c97aa0d99 100644 --- a/drivers/iio/temperature/tmp117.c +++ b/drivers/iio/temperature/tmp117.c @@ -97,15 +97,20 @@ static int tmp117_write_raw(struct iio_dev *indio_dev, struct iio_chan_spec { struct tmp117_data *data = iio_priv(indio_dev); s16 off; + int ret; switch (mask) { case IIO_CHAN_INFO_CALIBBIAS: off = clamp_t(int, val, S16_MIN, S16_MAX); if (off == data->calibbias) return 0; + + ret = i2c_smbus_write_word_swapped(data->client, TMP117_REG_TEMP_OFFSET, off); + if (ret) + return ret; + data->calibbias = off; - return i2c_smbus_write_word_swapped(data->client, - TMP117_REG_TEMP_OFFSET, off); + return 0; default: return -EINVAL; diff --git a/drivers/infiniband/core/device.c b/drivers/infiniband/core/device.c index 7a3ed5ecac00..05dd890b2ebd 100644 --- a/drivers/infiniband/core/device.c +++ b/drivers/infiniband/core/device.c @@ -3067,7 +3067,7 @@ int ib_add_sub_device(struct ib_device *parent, sub->parent = parent; mutex_lock(&parent->subdev_lock); - list_add_tail(&parent->subdev_list_head, &sub->subdev_list); + list_add_tail(&sub->subdev_list, &parent->subdev_list_head); mutex_unlock(&parent->subdev_lock); return ret; diff --git a/drivers/infiniband/core/ib_core_uverbs.c b/drivers/infiniband/core/ib_core_uverbs.c index 2bdb6972fe1a..74d9c006bad5 100644 --- a/drivers/infiniband/core/ib_core_uverbs.c +++ b/drivers/infiniband/core/ib_core_uverbs.c @@ -527,18 +527,6 @@ int uverbs_destroy_def_handler(struct uverbs_attr_bundle *attrs) } EXPORT_SYMBOL(uverbs_destroy_def_handler); -/* - * When calling a destroy function during an error unwind we need to pass in - * the udata that is sanitized of all user arguments. Ie from the driver - * perspective it looks like no udata was passed. - */ -struct ib_udata *uverbs_get_cleared_udata(struct uverbs_attr_bundle *attrs) -{ - attrs->driver_udata = (struct ib_udata){}; - return &attrs->driver_udata; -} -EXPORT_SYMBOL_NS_GPL(uverbs_get_cleared_udata, "rdma_core"); - /** * _uverbs_alloc() - Quickly allocate memory for use with a bundle * @bundle: The bundle diff --git a/drivers/infiniband/core/lag.c b/drivers/infiniband/core/lag.c index 00fe241737ff..651c868aa04e 100644 --- a/drivers/infiniband/core/lag.c +++ b/drivers/infiniband/core/lag.c @@ -19,6 +19,11 @@ static struct sk_buff *rdma_build_skb(struct net_device *netdev, u8 smac[ETH_ALEN]; bool is_ipv4; int hdr_len; + int ret; + + ret = rdma_read_gid_l2_fields(ah_attr->grh.sgid_attr, NULL, smac); + if (ret) + return ERR_PTR(ret); is_ipv4 = ipv6_addr_v4mapped((struct in6_addr *)ah_attr->grh.dgid.raw); hdr_len = ETH_HLEN + sizeof(struct udphdr) + LL_RESERVED_SPACE(netdev); @@ -26,7 +31,7 @@ static struct sk_buff *rdma_build_skb(struct net_device *netdev, skb = alloc_skb(hdr_len, flags); if (!skb) - return NULL; + return ERR_PTR(-ENOMEM); skb->dev = netdev; skb_reserve(skb, hdr_len); @@ -59,7 +64,7 @@ static struct sk_buff *rdma_build_skb(struct net_device *netdev, ip6h->version = 6; ip6h->nexthdr = IPPROTO_UDP; memcpy(&ip6h->flow_lbl, &ah_attr->grh.flow_label, - sizeof(*ip6h->flow_lbl)); + sizeof(ip6h->flow_lbl)); memcpy(&ip6h->saddr, ah_attr->grh.sgid_attr->gid.raw, sizeof(struct in6_addr)); memcpy(&ip6h->daddr, ah_attr->grh.dgid.raw, @@ -70,7 +75,6 @@ static struct sk_buff *rdma_build_skb(struct net_device *netdev, skb_reset_mac_header(skb); eth = eth_hdr(skb); skb->protocol = eth->h_proto = htons(is_ipv4 ? ETH_P_IP : ETH_P_IPV6); - rdma_read_gid_l2_fields(ah_attr->grh.sgid_attr, NULL, smac); memcpy(eth->h_source, smac, ETH_ALEN); memcpy(eth->h_dest, ah_attr->roce.dmac, ETH_ALEN); @@ -86,8 +90,8 @@ static struct net_device *rdma_get_xmit_slave_udp(struct ib_device *device, struct sk_buff *skb; skb = rdma_build_skb(master, ah_attr, flags); - if (!skb) - return ERR_PTR(-ENOMEM); + if (IS_ERR(skb)) + return ERR_CAST(skb); rcu_read_lock(); slave = netdev_get_xmit_slave(master, skb, diff --git a/drivers/infiniband/core/mad.c b/drivers/infiniband/core/mad.c index 3c91f00d09c6..8124e0b5a87d 100644 --- a/drivers/infiniband/core/mad.c +++ b/drivers/infiniband/core/mad.c @@ -2342,6 +2342,8 @@ static void ib_mad_recv_done(struct ib_cq *cq, struct ib_wc *wc) recv->header.mapping, mad_priv_dma_size(recv), DMA_FROM_DEVICE); + if (unlikely(wc->byte_len < sizeof(struct ib_grh))) + goto out; /* Setup MAD receive work completion from "normal" work completion */ recv->header.wc = *wc; diff --git a/drivers/infiniband/core/mad_rmpp.c b/drivers/infiniband/core/mad_rmpp.c index 17c4c52a19e4..f05e9ce93c33 100644 --- a/drivers/infiniband/core/mad_rmpp.c +++ b/drivers/infiniband/core/mad_rmpp.c @@ -245,12 +245,15 @@ static void recv_timeout_handler(struct work_struct *work) struct ib_mad_recv_wc *rmpp_wc; unsigned long flags; - spin_lock_irqsave(&rmpp_recv->agent->lock, flags); + spin_lock_irqsave(&rmpp_recv->lock, flags); if (rmpp_recv->state != RMPP_STATE_ACTIVE) { - spin_unlock_irqrestore(&rmpp_recv->agent->lock, flags); + spin_unlock_irqrestore(&rmpp_recv->lock, flags); return; } rmpp_recv->state = RMPP_STATE_TIMEOUT; + spin_unlock_irqrestore(&rmpp_recv->lock, flags); + + spin_lock_irqsave(&rmpp_recv->agent->lock, flags); list_del(&rmpp_recv->list); spin_unlock_irqrestore(&rmpp_recv->agent->lock, flags); diff --git a/drivers/infiniband/core/nldev.c b/drivers/infiniband/core/nldev.c index 4e8fbee34745..849a5db54e1c 100644 --- a/drivers/infiniband/core/nldev.c +++ b/drivers/infiniband/core/nldev.c @@ -700,7 +700,8 @@ static int fill_res_cq_entry(struct sk_buff *msg, bool has_cap_net_admin, if (nla_put_u32(msg, RDMA_NLDEV_ATTR_RES_CQN, res->id)) return -EMSGSIZE; - if (!rdma_is_kernel_res(res) && + + if (cq->uobject && cq->uobject->uevent.uobject.context && nla_put_u32(msg, RDMA_NLDEV_ATTR_RES_CTXN, cq->uobject->uevent.uobject.context->res.id)) return -EMSGSIZE; @@ -790,7 +791,7 @@ static int fill_res_pd_entry(struct sk_buff *msg, bool has_cap_net_admin, if (nla_put_u32(msg, RDMA_NLDEV_ATTR_RES_PDN, res->id)) goto err; - if (!rdma_is_kernel_res(res) && + if (pd->uobject && pd->uobject->context && nla_put_u32(msg, RDMA_NLDEV_ATTR_RES_CTXN, pd->uobject->context->res.id)) goto err; @@ -1895,8 +1896,10 @@ static int nldev_dellink(struct sk_buff *skb, struct nlmsghdr *nlh, mutex_lock(&nldev_dellink_mutex); err = device->link_ops->dellink(device); mutex_unlock(&nldev_dellink_mutex); - if (err) + if (err) { + ib_device_put(device); return err; + } } ib_unregister_device_and_put(device); diff --git a/drivers/infiniband/core/rdma_core.c b/drivers/infiniband/core/rdma_core.c index a7cbe643e33c..b32e5445601b 100644 --- a/drivers/infiniband/core/rdma_core.c +++ b/drivers/infiniband/core/rdma_core.c @@ -734,6 +734,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); } EXPORT_SYMBOL_NS_GPL(rdma_assign_uobject, "rdma_core"); @@ -750,6 +751,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/core/rdma_core.h b/drivers/infiniband/core/rdma_core.h index 2b91e8527287..9de14e625dd3 100644 --- a/drivers/infiniband/core/rdma_core.h +++ b/drivers/infiniband/core/rdma_core.h @@ -71,14 +71,19 @@ int uverbs_output_written(const struct uverbs_attr_bundle *bundle, size_t idx); void setup_ufile_idr_uobject(struct ib_uverbs_file *ufile); -#if IS_ENABLED(CONFIG_INFINIBAND_USER_ACCESS) -struct ib_udata *uverbs_get_cleared_udata(struct uverbs_attr_bundle *attrs); -#else -static inline struct ib_udata *uverbs_get_cleared_udata(struct uverbs_attr_bundle *attrs) +/* + * When calling a destroy function during an error unwind we need to pass in + * the udata that is sanitized of all user arguments. Ie from the driver + * perspective it looks like no udata was passed. + */ +static inline struct ib_udata * +uverbs_get_cleared_udata(struct uverbs_attr_bundle *attrs) { - return NULL; + if (!attrs) + return NULL; + attrs->driver_udata = (struct ib_udata){}; + return &attrs->driver_udata; } -#endif /* * This is the runtime description of the uverbs API, used by the syscall diff --git a/drivers/infiniband/core/restrack.c b/drivers/infiniband/core/restrack.c index f89a81dad72f..a8b838fdc7b5 100644 --- a/drivers/infiniband/core/restrack.c +++ b/drivers/infiniband/core/restrack.c @@ -250,8 +250,7 @@ void rdma_restrack_add(struct rdma_restrack_entry *res) ret = xa_insert(&rt->xa, res->id, res, GFP_KERNEL); if (ret) res->id = 0; - - if (qp->qp_type >= IB_QPT_DRIVER) + else if (qp->qp_type >= IB_QPT_DRIVER) xa_set_mark(&rt->xa, res->id, RESTRACK_DD); } else if (res->type == RDMA_RESTRACK_COUNTER) { /* Special case to ensure that cntn points to right counter */ diff --git a/drivers/infiniband/core/sysfs.c b/drivers/infiniband/core/sysfs.c index 69df8b703cbd..4cd861b5d953 100644 --- a/drivers/infiniband/core/sysfs.c +++ b/drivers/infiniband/core/sysfs.c @@ -996,8 +996,8 @@ static int setup_hw_port_stats(struct ib_port *port, data->stats->num_counters); if (ret != data->stats->num_counters) { if (WARN_ON(ret >= 0)) - return -EINVAL; - return ret; + ret = -EINVAL; + goto err_free_data; } data->stats->timestamp = jiffies; @@ -1031,6 +1031,11 @@ static int setup_hw_port_stats(struct ib_port *port, port->hw_stats_data = data; return 0; + +err_free_data: + rdma_free_hw_stats_struct(data->stats); + kfree(data); + return ret; } struct rdma_hw_stats *ib_get_hw_stats_port(struct ib_device *ibdev, diff --git a/drivers/infiniband/core/uverbs_std_types_device.c b/drivers/infiniband/core/uverbs_std_types_device.c index ce0a7de00405..db65032e80b4 100644 --- a/drivers/infiniband/core/uverbs_std_types_device.c +++ b/drivers/infiniband/core/uverbs_std_types_device.c @@ -272,6 +272,7 @@ static int UVERBS_HANDLER(UVERBS_METHOD_GET_CONTEXT)( return ret; ret = ib_init_ucontext(attrs); if (ret) { + rdma_restrack_put(&attrs->context->res); kfree(attrs->context); attrs->context = NULL; return ret; diff --git a/drivers/infiniband/core/uverbs_std_types_wq.c b/drivers/infiniband/core/uverbs_std_types_wq.c index 7ded8339346f..c23f455231bf 100644 --- a/drivers/infiniband/core/uverbs_std_types_wq.c +++ b/drivers/infiniband/core/uverbs_std_types_wq.c @@ -140,7 +140,7 @@ DECLARE_UVERBS_NAMED_METHOD( UVERBS_ATTR_IDR(UVERBS_ATTR_CREATE_WQ_CQ_HANDLE, UVERBS_OBJECT_CQ, UVERBS_ACCESS_READ, - UA_OPTIONAL), + UA_MANDATORY), UVERBS_ATTR_FD(UVERBS_ATTR_CREATE_WQ_EVENT_FD, UVERBS_OBJECT_ASYNC_EVENT, UVERBS_ACCESS_READ, diff --git a/drivers/infiniband/core/verbs.c b/drivers/infiniband/core/verbs.c index c43e25d37266..5dea57778b1a 100644 --- a/drivers/infiniband/core/verbs.c +++ b/drivers/infiniband/core/verbs.c @@ -1011,7 +1011,8 @@ int rdma_modify_ah(struct ib_ah *ah, struct rdma_ah_attr *ah_attr) ah->device->ops.modify_ah(ah, ah_attr) : -EOPNOTSUPP; - ah->sgid_attr = rdma_update_sgid_attr(ah_attr, ah->sgid_attr); + if (!ret) + ah->sgid_attr = rdma_update_sgid_attr(ah_attr, ah->sgid_attr); rdma_unfill_sgid_attr(ah_attr, old_sgid_attr); return ret; } @@ -1331,8 +1332,7 @@ static struct ib_qp *create_qp(struct ib_device *dev, struct ib_pd *pd, return qp; err_security: - qp->device->ops.destroy_qp( - qp, uattrs ? uverbs_get_cleared_udata(uattrs) : NULL); + qp->device->ops.destroy_qp(qp, uverbs_get_cleared_udata(uattrs)); err_create: rdma_restrack_put(&qp->res); xa_destroy(&qp->comp_cntrs); diff --git a/drivers/infiniband/hw/bnxt_re/bnxt_re.h b/drivers/infiniband/hw/bnxt_re/bnxt_re.h index a43e678151d3..da471c63a3ba 100644 --- a/drivers/infiniband/hw/bnxt_re/bnxt_re.h +++ b/drivers/infiniband/hw/bnxt_re/bnxt_re.h @@ -216,6 +216,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; struct dentry *cq_coal_cfg; diff --git a/drivers/infiniband/hw/bnxt_re/hw_counters.c b/drivers/infiniband/hw/bnxt_re/hw_counters.c index 651cf9d0e0c7..575b97030587 100644 --- a/drivers/infiniband/hw/bnxt_re/hw_counters.c +++ b/drivers/infiniband/hw/bnxt_re/hw_counters.c @@ -413,7 +413,8 @@ int bnxt_re_ib_get_hw_stats(struct ib_device *ibdev, } done: - return bnxt_qplib_is_chip_gen_p5_p7(rdev->chip_ctx) ? + return bnxt_ext_stats_supported(rdev->chip_ctx, rdev->dev_attr->dev_cap_flags, + rdev->is_virtfn) ? BNXT_RE_NUM_EXT_COUNTERS : BNXT_RE_NUM_STD_COUNTERS; } @@ -423,7 +424,8 @@ struct rdma_hw_stats *bnxt_re_ib_alloc_hw_port_stats(struct ib_device *ibdev, struct bnxt_re_dev *rdev = to_bnxt_re_dev(ibdev, ibdev); int num_counters = 0; - if (bnxt_qplib_is_chip_gen_p5_p7(rdev->chip_ctx)) + if (bnxt_ext_stats_supported(rdev->chip_ctx, rdev->dev_attr->dev_cap_flags, + rdev->is_virtfn)) num_counters = BNXT_RE_NUM_EXT_COUNTERS; else num_counters = BNXT_RE_NUM_STD_COUNTERS; diff --git a/drivers/infiniband/hw/bnxt_re/ib_verbs.c b/drivers/infiniband/hw/bnxt_re/ib_verbs.c index ccd2702db78b..22583d2d361d 100644 --- a/drivers/infiniband/hw/bnxt_re/ib_verbs.c +++ b/drivers/infiniband/hw/bnxt_re/ib_verbs.c @@ -165,10 +165,11 @@ static void bnxt_re_check_and_set_relaxed_ordering(struct bnxt_re_dev *rdev, qplib_mr->flags |= CMDQ_REGISTER_MR_FLAGS_ENABLE_RO; } -static int bnxt_re_build_sgl(struct ib_sge *ib_sg_list, +static u32 bnxt_re_build_sgl(struct ib_sge *ib_sg_list, struct bnxt_qplib_sge *sg_list, int num) { - int i, total = 0; + u32 total = 0; + int i; for (i = 0; i < num; i++) { sg_list[i].addr = ib_sg_list[i].addr; @@ -2235,6 +2236,14 @@ int bnxt_re_create_srq(struct ib_srq *ib_srq, goto exit; } + if (srq_init_attr->attr.max_sge > dev_attr->max_srq_sges) { + ibdev_err(&rdev->ibdev, + "Create SRQ failed - max_sge %d exceeds supported %d", + srq_init_attr->attr.max_sge, dev_attr->max_srq_sges); + rc = -EINVAL; + goto exit; + } + if (srq_init_attr->srq_type != IB_SRQT_BASIC) { rc = -EOPNOTSUPP; goto exit; @@ -2388,6 +2397,7 @@ int bnxt_re_post_srq_recv(struct ib_srq *ib_srq, const struct ib_recv_wr *wr, spin_lock_irqsave(&srq->lock, flags); while (wr) { /* Transcribe each ib_recv_wr to qplib_swqe */ + wqe.flags = 0; wqe.num_sge = wr->num_sge; bnxt_re_build_sgl(wr->sg_list, wqe.sg_list, wr->num_sge); wqe.wr_id = wr->wr_id; @@ -3168,8 +3178,9 @@ static int bnxt_re_copy_inline_data(struct bnxt_re_dev *rdev, wr->sg_list[i].addr; sge_len = wr->sg_list[i].length; - if ((sge_len + wqe->inline_len) > - BNXT_QPLIB_SWQE_MAX_INLINE_LENGTH) { + if (sge_len > BNXT_QPLIB_SWQE_MAX_INLINE_LENGTH || + ((sge_len + wqe->inline_len) > + BNXT_QPLIB_SWQE_MAX_INLINE_LENGTH)) { ibdev_err(&rdev->ibdev, "Inline data size requested > supported value"); return -EINVAL; @@ -3185,17 +3196,22 @@ static int bnxt_re_copy_inline_data(struct bnxt_re_dev *rdev, static int bnxt_re_copy_wr_payload(struct bnxt_re_dev *rdev, const struct ib_send_wr *wr, - struct bnxt_qplib_swqe *wqe) + struct bnxt_qplib_swqe *wqe, + u32 *payload_sz) { - int payload_sz = 0; + int rc; - if (wr->send_flags & IB_SEND_INLINE) - payload_sz = bnxt_re_copy_inline_data(rdev, wr, wqe); - else - payload_sz = bnxt_re_build_sgl(wr->sg_list, wqe->sg_list, - wqe->num_sge); + if (wr->send_flags & IB_SEND_INLINE) { + rc = bnxt_re_copy_inline_data(rdev, wr, wqe); + if (rc < 0) + return rc; + *payload_sz = rc; + } else { + *payload_sz = bnxt_re_build_sgl(wr->sg_list, wqe->sg_list, + wqe->num_sge); + } - return payload_sz; + return 0; } static void bnxt_ud_qp_hw_stall_workaround(struct bnxt_re_qp *qp) @@ -3218,7 +3234,8 @@ static int bnxt_re_post_send_shadow_qp(struct bnxt_re_dev *rdev, struct bnxt_re_qp *qp, const struct ib_send_wr *wr) { - int rc = 0, payload_sz = 0; + int rc = 0; + u32 payload_sz = 0; unsigned long flags; spin_lock_irqsave(&qp->sq_lock, flags); @@ -3234,11 +3251,9 @@ static int bnxt_re_post_send_shadow_qp(struct bnxt_re_dev *rdev, goto bad; } - payload_sz = bnxt_re_copy_wr_payload(qp->rdev, wr, &wqe); - if (payload_sz < 0) { - rc = -EINVAL; + rc = bnxt_re_copy_wr_payload(qp->rdev, wr, &wqe, &payload_sz); + if (rc) goto bad; - } wqe.wr_id = wr->wr_id; wqe.type = BNXT_QPLIB_SWQE_TYPE_SEND; @@ -3279,7 +3294,8 @@ int bnxt_re_post_send(struct ib_qp *ib_qp, const struct ib_send_wr *wr, { struct bnxt_re_qp *qp = container_of(ib_qp, struct bnxt_re_qp, ib_qp); struct bnxt_qplib_swqe wqe; - int rc = 0, payload_sz = 0; + int rc = 0; + u32 payload_sz = 0; unsigned long flags; spin_lock_irqsave(&qp->sq_lock, flags); @@ -3296,11 +3312,9 @@ int bnxt_re_post_send(struct ib_qp *ib_qp, const struct ib_send_wr *wr, goto bad; } - payload_sz = bnxt_re_copy_wr_payload(qp->rdev, wr, &wqe); - if (payload_sz < 0) { - rc = -EINVAL; + rc = bnxt_re_copy_wr_payload(qp->rdev, wr, &wqe, &payload_sz); + if (rc) goto bad; - } wqe.wr_id = wr->wr_id; switch (wr->opcode) { diff --git a/drivers/infiniband/hw/bnxt_re/main.c b/drivers/infiniband/hw/bnxt_re/main.c index 17654a9e23fe..fa0e1323a326 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_obj(*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; @@ -1448,6 +1463,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 9ee0d500436c..34d8aa12265d 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 756f8b5f042a..cde56ff2313b 100644 --- a/drivers/infiniband/hw/bnxt_re/qplib_res.c +++ b/drivers/infiniband/hw/bnxt_re/qplib_res.c @@ -45,6 +45,7 @@ #include #include #include +#include #include #include @@ -668,9 +669,9 @@ static int bnxt_qplib_alloc_pd_tbl(struct bnxt_qplib_res *res, { u32 bytes; - bytes = max >> 3; + bytes = BITS_TO_LONGS(max) * sizeof(unsigned long); if (!bytes) - bytes = 1; + bytes = sizeof(unsigned long); pdt->tbl = kmalloc(bytes, GFP_KERNEL); if (!pdt->tbl) return -ENOMEM; @@ -848,9 +849,9 @@ static int bnxt_qplib_alloc_dpi_tbl(struct bnxt_qplib_res *res, if (!dpit->app_tbl) return -ENOMEM; - bytes = dpit->max >> 3; + bytes = BITS_TO_LONGS(dpit->max) * sizeof(unsigned long); if (!bytes) - bytes = 1; + bytes = sizeof(unsigned long); dpit->tbl = kmalloc(bytes, GFP_KERNEL); if (!dpit->tbl) { @@ -909,7 +910,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); @@ -926,8 +935,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 = kzalloc_objs(struct bnxt_qplib_qp_node, - rcfw->qp_tbl_size); + rcfw->qp_tbl = kvzalloc_objs(struct bnxt_qplib_qp_node, + rcfw->qp_tbl_size); if (!rcfw->qp_tbl) return -ENOMEM; diff --git a/drivers/infiniband/hw/bnxt_re/qplib_sp.c b/drivers/infiniband/hw/bnxt_re/qplib_sp.c index ec9eb52a8ebf..9aaa2b5204b8 100644 --- a/drivers/infiniband/hw/bnxt_re/qplib_sp.c +++ b/drivers/infiniband/hw/bnxt_re/qplib_sp.c @@ -160,7 +160,7 @@ int bnxt_qplib_get_dev_attr(struct bnxt_qplib_rcfw *rcfw) attr->max_srq = le16_to_cpu(sb->max_srq); attr->max_srq_wqes = le32_to_cpu(sb->max_srq_wr) - 1; - attr->max_srq_sges = sb->max_srq_sge; + attr->max_srq_sges = min_t(u32, sb->max_srq_sge, BNXT_STATIC_MAX_SGE); attr->max_pkey = 1; attr->max_inline_data = attr->max_qp_sges * sizeof(struct sq_sge); if (!bnxt_qplib_is_chip_gen_p7(rcfw->res->cctx)) diff --git a/drivers/infiniband/hw/cxgb4/cm.c b/drivers/infiniband/hw/cxgb4/cm.c index b3b45c49077d..a6f520f49d59 100644 --- a/drivers/infiniband/hw/cxgb4/cm.c +++ b/drivers/infiniband/hw/cxgb4/cm.c @@ -4006,8 +4006,10 @@ static void send_fw_pass_open_req(struct c4iw_dev *dev, struct sk_buff *skb, int ret; req_skb = alloc_skb(sizeof(struct fw_ofld_connection_wr), GFP_KERNEL); - if (!req_skb) + if (!req_skb) { + kfree_skb(skb); return; + } req = __skb_put_zero(req_skb, sizeof(*req)); req->op_compl = htonl(WR_OP_V(FW_OFLD_CONNECTION_WR) | FW_WR_COMPL_F); req->len16_pkd = htonl(FW_WR_LEN16_V(DIV_ROUND_UP(sizeof(*req), 16))); @@ -4156,6 +4158,7 @@ static int rx_pkt(struct c4iw_dev *dev, struct sk_buff *skb) pdev = ip_dev_find(&init_net, iph->daddr); if (!pdev) { pr_err("%s - failed to find device!\n", __func__); + neigh_release(neigh); goto free_dst; } e = cxgb4_l2t_get(dev->rdev.lldi.l2t, neigh, diff --git a/drivers/infiniband/hw/cxgb4/provider.c b/drivers/infiniband/hw/cxgb4/provider.c index ebe3170a641c..904a5323a693 100644 --- a/drivers/infiniband/hw/cxgb4/provider.c +++ b/drivers/infiniband/hw/cxgb4/provider.c @@ -171,6 +171,11 @@ static int c4iw_mmap(struct ib_ucontext *context, struct vm_area_struct *vma) len, t4_pgprot_wc(vma->vm_page_prot)); break; case CXGB4_MMAP_CONTIG: + if (vma->vm_flags & (VM_WRITE | VM_EXEC)) { + ret = -EPERM; + break; + } + vm_flags_clear(vma, VM_MAYWRITE); ret = io_remap_pfn_range(vma, vma->vm_start, addr >> PAGE_SHIFT, len, vma->vm_page_prot); diff --git a/drivers/infiniband/hw/efa/efa_com.c b/drivers/infiniband/hw/efa/efa_com.c index 04c6d63c449e..9c59d127e1e0 100644 --- a/drivers/infiniband/hw/efa/efa_com.c +++ b/drivers/infiniband/hw/efa/efa_com.c @@ -41,6 +41,7 @@ enum efa_cmd_status { EFA_CMD_ALLOCATED, EFA_CMD_SUBMITTED, EFA_CMD_COMPLETED, + EFA_CMD_TIMED_OUT, }; struct efa_comp_ctx { @@ -591,6 +592,7 @@ static int efa_com_comp_status_to_errno(u8 comp_status) static int efa_com_wait_and_process_admin_cq_polling(struct efa_comp_ctx *comp_ctx, struct efa_com_admin_queue *aq) { + bool comp_timeout = false; unsigned long timeout; unsigned long flags; @@ -599,12 +601,19 @@ static int efa_com_wait_and_process_admin_cq_polling(struct efa_comp_ctx *comp_c while (1) { spin_lock_irqsave(&aq->cq.lock, flags); efa_com_handle_admin_completion(aq); - spin_unlock_irqrestore(&aq->cq.lock, flags); - - if (comp_ctx->status != EFA_CMD_SUBMITTED) + if (comp_ctx->status != EFA_CMD_SUBMITTED) { + spin_unlock_irqrestore(&aq->cq.lock, flags); break; + } if (time_is_before_jiffies(timeout)) { + comp_ctx->status = EFA_CMD_TIMED_OUT; + comp_timeout = true; + } + + spin_unlock_irqrestore(&aq->cq.lock, flags); + + if (comp_timeout) { ibdev_err_ratelimited( aq->efa_dev, "Wait for completion (polling) timeout\n"); @@ -625,10 +634,11 @@ static int efa_com_wait_and_process_admin_cq_polling(struct efa_comp_ctx *comp_c static int efa_com_wait_and_process_admin_cq_interrupts(struct efa_comp_ctx *comp_ctx, struct efa_com_admin_queue *aq) { - unsigned long flags; + unsigned long flags, remaining_jiffies; + bool completed; - wait_for_completion_timeout(&comp_ctx->wait_event, - usecs_to_jiffies(aq->completion_timeout)); + remaining_jiffies = wait_for_completion_timeout( + &comp_ctx->wait_event, usecs_to_jiffies(aq->completion_timeout)); /* * In case the command wasn't completed find out the root cause. @@ -636,14 +646,16 @@ static int efa_com_wait_and_process_admin_cq_interrupts(struct efa_comp_ctx *com * 1) No completion (timeout reached) * 2) There is completion but the device didn't get any msi-x interrupt. */ - if (comp_ctx->status == EFA_CMD_SUBMITTED) { + if (remaining_jiffies == 0) { spin_lock_irqsave(&aq->cq.lock, flags); efa_com_handle_admin_completion(aq); + completed = (comp_ctx->status == EFA_CMD_COMPLETED); + comp_ctx->status = EFA_CMD_TIMED_OUT; spin_unlock_irqrestore(&aq->cq.lock, flags); atomic64_inc(&aq->stats.no_completion); - if (comp_ctx->status == EFA_CMD_COMPLETED) + if (completed) ibdev_err_ratelimited( aq->efa_dev, "The device sent a completion but the driver didn't receive any MSI-X interrupt for admin cmd %s(%d) status %d (id: %d, sq producer: %d, sq consumer: %d, cq consumer: %d)\n", diff --git a/drivers/infiniband/hw/hfi1/sdma.c b/drivers/infiniband/hw/hfi1/sdma.c index f253c8ee182d..a71fc8f2d37e 100644 --- a/drivers/infiniband/hw/hfi1/sdma.c +++ b/drivers/infiniband/hw/hfi1/sdma.c @@ -1569,6 +1569,9 @@ void sdma_exit(struct hfi1_devdata *dd) * it is not running. */ sdma_finalput(&sde->state); + cancel_work_sync(&sde->err_halt_worker); + tasklet_kill(&sde->sdma_hw_clean_up_task); + cancel_work_sync(&sde->flush_worker); } } diff --git a/drivers/infiniband/hw/hfi1/verbs.c b/drivers/infiniband/hw/hfi1/verbs.c index e569b647d611..0ef3b1a89a53 100644 --- a/drivers/infiniband/hw/hfi1/verbs.c +++ b/drivers/infiniband/hw/hfi1/verbs.c @@ -1888,6 +1888,10 @@ int hfi1_register_ib_device(struct hfi1_devdata *dd) void hfi1_unregister_ib_device(struct hfi1_devdata *dd) { struct hfi1_ibdev *dev = &dd->verbs_dev; + int i; + + for (i = 0; i < dd->num_pports; i++) + timer_shutdown_sync(&dd->pport[i].ibport_data.rvp.trap_timer); hfi1_verbs_unregister_sysfs(dd); diff --git a/drivers/infiniband/hw/hns/hns_roce_bond.c b/drivers/infiniband/hw/hns/hns_roce_bond.c index f2b12ae13a58..8d8272705fb7 100644 --- a/drivers/infiniband/hw/hns/hns_roce_bond.c +++ b/drivers/infiniband/hw/hns/hns_roce_bond.c @@ -81,7 +81,7 @@ static int hns_roce_set_bond_netdev(struct hns_roce_bond_group *bond_grp, { struct net_device *active_dev; struct net_device *old_dev; - int i, ret = 0; + int i = 0, ret = 0; if (bond_grp->tx_type == NETDEV_LAG_TX_TYPE_ACTIVEBACKUP) { rcu_read_lock(); @@ -89,7 +89,7 @@ static int hns_roce_set_bond_netdev(struct hns_roce_bond_group *bond_grp, bond_option_active_slave_get_rcu(netdev_priv(bond_grp->upper_dev)); rcu_read_unlock(); } else { - for (i = 0; i < ROCE_BOND_FUNC_MAX; i++) { + for (; i < ROCE_BOND_FUNC_MAX; i++) { active_dev = bond_grp->bond_func_info[i].net_dev; if (active_dev && ib_get_curr_port_state(active_dev) == IB_PORT_ACTIVE) diff --git a/drivers/infiniband/hw/hns/hns_roce_cq.c b/drivers/infiniband/hw/hns/hns_roce_cq.c index 1dd0efb5620d..ae314f136732 100644 --- a/drivers/infiniband/hw/hns/hns_roce_cq.c +++ b/drivers/infiniband/hw/hns/hns_roce_cq.c @@ -261,6 +261,7 @@ static int alloc_cq_buf(struct hns_roce_dev *hr_dev, struct hns_roce_cq *hr_cq, buf_attr.region[0].size = hr_cq->cq_depth * hr_cq->cqe_size; buf_attr.region[0].hopnum = hr_dev->caps.cqe_hop_num; buf_attr.region_count = 1; + buf_attr.user_access = IB_ACCESS_LOCAL_WRITE; ret = hns_roce_mtr_create(hr_dev, &hr_cq->mtr, &buf_attr, hr_dev->caps.cqe_ba_pg_sz + PAGE_SHIFT, diff --git a/drivers/infiniband/hw/hns/hns_roce_device.h b/drivers/infiniband/hw/hns/hns_roce_device.h index eb7b1865e4c7..95529251e2e2 100644 --- a/drivers/infiniband/hw/hns/hns_roce_device.h +++ b/drivers/infiniband/hw/hns/hns_roce_device.h @@ -654,6 +654,7 @@ struct hns_roce_qp { u8 priority; spinlock_t flush_lock; struct hns_roce_dip *dip; + bool ud_sl_set; }; struct hns_roce_ib_iboe { diff --git a/drivers/infiniband/hw/hns/hns_roce_hw_v2.c b/drivers/infiniband/hw/hns/hns_roce_hw_v2.c index 27cc7df55ee7..7dd24f022a06 100644 --- a/drivers/infiniband/hw/hns/hns_roce_hw_v2.c +++ b/drivers/infiniband/hw/hns/hns_roce_hw_v2.c @@ -431,7 +431,8 @@ static int set_ud_opcode(struct hns_roce_v2_ud_send_wqe *ud_sq_wqe, return 0; } -static int fill_ud_av(struct hns_roce_v2_ud_send_wqe *ud_sq_wqe, +static int fill_ud_av(struct hns_roce_qp *qp, + struct hns_roce_v2_ud_send_wqe *ud_sq_wqe, struct hns_roce_ah *ah) { struct ib_device *ib_dev = ah->ibah.device; @@ -441,7 +442,12 @@ static int fill_ud_av(struct hns_roce_v2_ud_send_wqe *ud_sq_wqe, hr_reg_write(ud_sq_wqe, UD_SEND_WQE_HOPLIMIT, ah->av.hop_limit); hr_reg_write(ud_sq_wqe, UD_SEND_WQE_TCLASS, ah->av.tclass); hr_reg_write(ud_sq_wqe, UD_SEND_WQE_FLOW_LABEL, ah->av.flowlabel); - hr_reg_write(ud_sq_wqe, UD_SEND_WQE_SL, ah->av.sl); + if (!qp->ud_sl_set) { + qp->sl = ah->av.sl; + qp->ud_sl_set = true; + } + + hr_reg_write(ud_sq_wqe, UD_SEND_WQE_SL, qp->sl); ud_sq_wqe->sgid_index = ah->av.gid_index; @@ -491,12 +497,10 @@ static inline int set_ud_wqe(struct hns_roce_qp *qp, qp->qkey : ud_wr(wr)->remote_qkey); hr_reg_write(ud_sq_wqe, UD_SEND_WQE_DQPN, ud_wr(wr)->remote_qpn); - ret = fill_ud_av(ud_sq_wqe, ah); + ret = fill_ud_av(qp, ud_sq_wqe, ah); if (ret) return ret; - qp->sl = to_hr_ah(ud_wr(wr)->ah)->av.sl; - set_extend_sge(qp, wr->sg_list, &curr_idx, valid_num_sge); /* @@ -2416,8 +2420,7 @@ static void apply_func_caps(struct hns_roce_dev *hr_dev) caps->gmv_bt_num * (HNS_HW_PAGE_SIZE / caps->gmv_entry_sz)); - caps->gmv_entry_num = caps->gmv_bt_num * (HNS_HW_PAGE_SIZE / - caps->gmv_entry_sz); + caps->gmv_entry_num = caps->gid_table_len[0]; } else { u32 func_num = max_t(u32, 1, hr_dev->func_num); @@ -4353,18 +4356,39 @@ static int get_op_for_set_hem(struct hns_roce_dev *hr_dev, u32 type, static int config_gmv_ba_to_hw(struct hns_roce_dev *hr_dev, unsigned long obj, dma_addr_t base_addr) { + u32 obj_num_per_bt = HNS_HW_PAGE_SIZE / hr_dev->caps.gmv_entry_sz; + u32 chunk_size = 1 << (hr_dev->caps.gmv_buf_pg_sz + PAGE_SHIFT); + u32 bt_num_per_chunk = chunk_size / HNS_HW_PAGE_SIZE; + u32 first = obj / obj_num_per_bt; + u32 last = min(first + bt_num_per_chunk, hr_dev->caps.gmv_bt_num); struct hns_roce_cmq_desc desc; - struct hns_roce_cmq_req *req = (struct hns_roce_cmq_req *)desc.data; - u32 idx = obj / (HNS_HW_PAGE_SIZE / hr_dev->caps.gmv_entry_sz); - u64 addr = to_hr_hw_page_addr(base_addr); + struct hns_roce_cmq_req *req; + u64 addr; + int ret; + u32 i; - hns_roce_cmq_setup_basic_desc(&desc, HNS_ROCE_OPC_CFG_GMV_BT, false); + /* The GMV BT entry of hardware covers a fixed 4K region, so a buffer + * chunk larger than 4K must be registered to hardware with one BT + * entry per 4K block, otherwise the GMV entries beyond the first + * 4K of the chunk are unreachable. + */ + for (i = first; i < last; i++) { + hns_roce_cmq_setup_basic_desc(&desc, HNS_ROCE_OPC_CFG_GMV_BT, + false); + req = (struct hns_roce_cmq_req *)desc.data; - hr_reg_write(req, CFG_GMV_BT_BA_L, lower_32_bits(addr)); - hr_reg_write(req, CFG_GMV_BT_BA_H, upper_32_bits(addr)); - hr_reg_write(req, CFG_GMV_BT_IDX, idx); + addr = to_hr_hw_page_addr(base_addr + + (u64)(i - first) * HNS_HW_PAGE_SIZE); + hr_reg_write(req, CFG_GMV_BT_BA_L, lower_32_bits(addr)); + hr_reg_write(req, CFG_GMV_BT_BA_H, upper_32_bits(addr)); + hr_reg_write(req, CFG_GMV_BT_IDX, i); - return hns_roce_cmq_send(hr_dev, &desc, 1); + ret = hns_roce_cmq_send(hr_dev, &desc, 1); + if (ret) + return ret; + } + + return 0; } static int set_hem_to_hw(struct hns_roce_dev *hr_dev, int obj, @@ -5603,6 +5627,7 @@ static void v2_set_flushed_fields(struct ib_qp *ibqp, hr_reg_write(context, QPC_SQ_PRODUCER_IDX, hr_qp->sq.head); hr_reg_clear(qpc_mask, QPC_SQ_PRODUCER_IDX); hr_qp->state = IB_QPS_ERR; + hr_qp->ud_sl_set = false; spin_unlock_irqrestore(&hr_qp->sq.lock, sq_flag); if (ibqp->srq || ibqp->qp_type == IB_QPT_XRC_INI) /* no RQ */ diff --git a/drivers/infiniband/hw/ionic/ionic_controlpath.c b/drivers/infiniband/hw/ionic/ionic_controlpath.c index a70ef59a8064..c82e61fdadc2 100644 --- a/drivers/infiniband/hw/ionic/ionic_controlpath.c +++ b/drivers/infiniband/hw/ionic/ionic_controlpath.c @@ -2336,7 +2336,7 @@ int ionic_create_qp(struct ib_qp *ibqp, struct ib_qp_init_attr *attr, &resp.sq_cmb_offset); if (!qp->mmap_sq_cmb) { rc = -ENOMEM; - goto err_mmap_sq; + goto err_qp_cmd; } resp.sq_cmb = qp->sq_cmb; @@ -2373,7 +2373,7 @@ int ionic_create_qp(struct ib_qp *ibqp, struct ib_qp_init_attr *attr, &resp.rq_cmb_offset); if (!qp->mmap_rq_cmb) { rc = -ENOMEM; - goto err_mmap_rq; + goto err_qp_cmd; } resp.rq_cmb = qp->rq_cmb; @@ -2381,7 +2381,7 @@ int ionic_create_qp(struct ib_qp *ibqp, struct ib_qp_init_attr *attr, rc = ib_respond_udata(udata, resp); if (rc) - goto err_resp; + goto err_qp_cmd; } ionic_pgtbl_unbuf(dev, &rq_buf); @@ -2399,7 +2399,7 @@ int ionic_create_qp(struct ib_qp *ibqp, struct ib_qp_init_attr *attr, else rc = xa_err(entry); - goto err_resp; + goto err_qp_cmd; } if (qp->has_sq) { @@ -2430,13 +2430,7 @@ int ionic_create_qp(struct ib_qp *ibqp, struct ib_qp_init_attr *attr, return 0; -err_resp: - if (udata && (qp->rq_cmb & IONIC_CMB_ENABLE)) - rdma_user_mmap_entry_remove(qp->mmap_rq_cmb); -err_mmap_rq: - if (udata && (qp->sq_cmb & IONIC_CMB_ENABLE)) - rdma_user_mmap_entry_remove(qp->mmap_sq_cmb); -err_mmap_sq: +err_qp_cmd: ionic_destroy_qp_cmd(dev, qp->qpid); err_cmd: ionic_pgtbl_unbuf(dev, &rq_buf); diff --git a/drivers/infiniband/hw/ionic/ionic_ibdev.c b/drivers/infiniband/hw/ionic/ionic_ibdev.c index cba7809ec3d9..fa79732c2f7d 100644 --- a/drivers/infiniband/hw/ionic/ionic_ibdev.c +++ b/drivers/infiniband/hw/ionic/ionic_ibdev.c @@ -320,8 +320,8 @@ static struct ionic_ibdev *ionic_create_ibdev(struct ionic_aux_dev *ionic_adev) ionic_fill_lif_cfg(ionic_adev->lif, &dev->lif_cfg); - xa_init_flags(&dev->qp_tbl, GFP_ATOMIC); - xa_init_flags(&dev->cq_tbl, GFP_ATOMIC); + xa_init_flags(&dev->qp_tbl, XA_FLAGS_LOCK_IRQ); + xa_init_flags(&dev->cq_tbl, XA_FLAGS_LOCK_IRQ); ionic_init_resids(dev); diff --git a/drivers/infiniband/hw/irdma/ctrl.c b/drivers/infiniband/hw/irdma/ctrl.c index 335ae3c82e17..ade451a4eb23 100644 --- a/drivers/infiniband/hw/irdma/ctrl.c +++ b/drivers/infiniband/hw/irdma/ctrl.c @@ -1723,15 +1723,13 @@ int irdma_sc_mr_fast_register(struct irdma_sc_qp *qp, info->wr_id, wqe_idx, &qp->qp_uk.sq_wrtrk_array[wqe_idx].wrid); - temp = (info->addr_type == IRDMA_ADDR_TYPE_VA_BASED) ? - (uintptr_t)info->va : info->fbo; - set_64bit_val(wqe, 0, temp); + set_64bit_val(wqe, 0, info->va); temp = FIELD_GET(IRDMAQPSQ_FIRSTPMPBLIDXHI, info->first_pm_pbl_index >> 16); set_64bit_val(wqe, 8, FIELD_PREP(IRDMAQPSQ_FIRSTPMPBLIDXHI, temp) | - FIELD_PREP(IRDMAQPSQ_PBLADDR >> IRDMA_HW_PAGE_SHIFT, info->reg_addr_pa)); + FIELD_PREP(IRDMAQPSQ_PBLADDR, info->reg_addr_pa >> IRDMA_HW_PAGE_SHIFT)); set_64bit_val(wqe, 16, info->total_len | FIELD_PREP(IRDMAQPSQ_FIRSTPMPBLIDXLO, info->first_pm_pbl_index)); @@ -1742,7 +1740,7 @@ int irdma_sc_mr_fast_register(struct irdma_sc_qp *qp, FIELD_PREP(IRDMAQPSQ_LPBLSIZE, info->chunk_size) | FIELD_PREP(IRDMAQPSQ_HPAGESIZE, page_size) | FIELD_PREP(IRDMAQPSQ_STAGRIGHTS, info->access_rights) | - FIELD_PREP(IRDMAQPSQ_VABASEDTO, info->addr_type) | + IRDMAQPSQ_VABASEDTO | FIELD_PREP(IRDMAQPSQ_READFENCE, info->read_fence) | FIELD_PREP(IRDMAQPSQ_LOCALFENCE, info->local_fence) | FIELD_PREP(IRDMAQPSQ_SIGCOMPL, info->signaled) | @@ -5331,7 +5329,11 @@ int irdma_sc_static_hmc_pages_allocated(struct irdma_sc_cqp *cqp, u64 scratch, */ static bool irdma_cqp_ring_full(struct irdma_sc_cqp *cqp) { - return IRDMA_RING_FULL_ERR(cqp->sq_ring); + u64 in_flight = cqp->requested_ops - + atomic64_read(&cqp->completed_ops); + + return IRDMA_RING_FULL_ERR(cqp->sq_ring) || + in_flight >= (cqp->sq_size - 1); } /** diff --git a/drivers/infiniband/hw/irdma/hw.c b/drivers/infiniband/hw/irdma/hw.c index c345cc654256..554f5d8962b9 100644 --- a/drivers/infiniband/hw/irdma/hw.c +++ b/drivers/infiniband/hw/irdma/hw.c @@ -265,6 +265,7 @@ static void irdma_process_ae_def_cmpl(struct irdma_pci_f *rf, irdma_sc_cqp_def_cmpl_ae_handler(&rf->sc_dev, info, false, &scratch, &sw_def_info); } + irdma_process_bh(&rf->sc_dev); } /** @@ -1252,12 +1253,21 @@ static int irdma_cfg_ceq_vector(struct irdma_pci_f *rf, struct irdma_ceq *iwceq, } msix_vec->ceq_id = ceq_id; - if (rf->sc_dev.privileged) + if (rf->sc_dev.privileged) { rf->sc_dev.irq_ops->irdma_cfg_ceq(&rf->sc_dev, ceq_id, msix_vec->idx, true); - else + } else { status = irdma_vchnl_req_ceq_vec_map(&rf->sc_dev, ceq_id, msix_vec->idx); + if (!status) + return 0; + + if (rf->msix_shared && !ceq_id) + irdma_destroy_irq(rf, msix_vec, rf); + else + irdma_destroy_irq(rf, msix_vec, iwceq); + } + return status; } diff --git a/drivers/infiniband/hw/irdma/main.c b/drivers/infiniband/hw/irdma/main.c index 95957d52883d..106915b51e7c 100644 --- a/drivers/infiniband/hw/irdma/main.c +++ b/drivers/infiniband/hw/irdma/main.c @@ -80,6 +80,8 @@ static int ig3rdma_vport_probe(struct auxiliary_device *aux_dev, return -ENOMEM; } iwdev = ib_alloc_device(irdma_device, ibdev); + if (!iwdev) + return -ENOMEM; /* Fill iwdev info */ iwdev->is_vport = true; iwdev->rf = rf; diff --git a/drivers/infiniband/hw/irdma/pble.c b/drivers/infiniband/hw/irdma/pble.c index 28dfad7f940c..0c2c5e96a05a 100644 --- a/drivers/infiniband/hw/irdma/pble.c +++ b/drivers/infiniband/hw/irdma/pble.c @@ -330,7 +330,7 @@ static void free_lvl2(struct irdma_hmc_pble_rsrc *pble_rsrc, if (root->addr) irdma_prm_return_pbles(&pble_rsrc->pinfo, &root->chunkinfo); - kfree(lvl2->leafmem.va); + kvfree(lvl2->leafmem.va); lvl2->leaf = NULL; } @@ -358,7 +358,7 @@ static int get_lvl2_pble(struct irdma_hmc_pble_rsrc *pble_rsrc, lvl2->leaf_cnt = total; lvl2->leafmem.size = (sizeof(*leaf) * total); - lvl2->leafmem.va = kzalloc(lvl2->leafmem.size, GFP_KERNEL); + lvl2->leafmem.va = kvzalloc(lvl2->leafmem.size, GFP_KERNEL); if (!lvl2->leafmem.va) return -ENOMEM; @@ -367,7 +367,7 @@ static int get_lvl2_pble(struct irdma_hmc_pble_rsrc *pble_rsrc, ret_code = irdma_prm_get_pbles(&pble_rsrc->pinfo, &root->chunkinfo, total << 3, &root->addr, &fpm_addr); if (ret_code) { - kfree(lvl2->leafmem.va); + kvfree(lvl2->leafmem.va); lvl2->leaf = NULL; return -ENOMEM; } @@ -482,7 +482,7 @@ int irdma_get_pble(struct irdma_hmc_pble_rsrc *pble_rsrc, status = get_lvl1_lvl2_pble(pble_rsrc, palloc, lvl); /* if level1_only, only go through it once */ - if (!status || lvl) + if (!status || lvl == PBLE_LEVEL_1) break; } diff --git a/drivers/infiniband/hw/irdma/type.h b/drivers/infiniband/hw/irdma/type.h index 5557d9338796..81c5c5da1988 100644 --- a/drivers/infiniband/hw/irdma/type.h +++ b/drivers/infiniband/hw/irdma/type.h @@ -1173,13 +1173,11 @@ struct irdma_reg_ns_stag_info { struct irdma_fast_reg_stag_info { u64 wr_id; u64 reg_addr_pa; - u64 fbo; - void *va; + u64 va; u64 total_len; u32 page_size; u32 chunk_size; u32 first_pm_pbl_index; - enum irdma_addressing_type addr_type; irdma_stag_index stag_idx; u16 access_rights; u32 pd_id; diff --git a/drivers/infiniband/hw/irdma/verbs.c b/drivers/infiniband/hw/irdma/verbs.c index 5d71300da0ff..2820d94a5e8d 100644 --- a/drivers/infiniband/hw/irdma/verbs.c +++ b/drivers/infiniband/hw/irdma/verbs.c @@ -1576,9 +1576,17 @@ int irdma_modify_qp_roce(struct ib_qp *ibqp, struct ib_qp_attr *attr, issue_modify_qp = 1; iwqp->suspend_pending = true; break; + case IB_QPS_RESET: + /* + * A QP that was never moved to INIT has nothing to + * flush, so skip the hardware modify. Moving it to + * ERROR would make the following INIT fail. + */ + if (iwqp->iwarp_state == IRDMA_QP_STATE_INVALID) + break; + fallthrough; case IB_QPS_SQE: case IB_QPS_ERR: - case IB_QPS_RESET: if (iwqp->iwarp_state == IRDMA_QP_STATE_ERROR) { iwqp->ibqp_state = attr->qp_state; spin_unlock_irqrestore(&iwqp->lock, flags); @@ -4276,8 +4284,7 @@ static int irdma_post_send(struct ib_qp *ibqp, stag_info.stag_idx = reg_wr(ib_wr)->key >> 8; stag_info.page_size = reg_wr(ib_wr)->mr->page_size; stag_info.wr_id = ib_wr->wr_id; - stag_info.addr_type = IRDMA_ADDR_TYPE_VA_BASED; - stag_info.va = (void *)(uintptr_t)iwmr->ibmr.iova; + stag_info.va = iwmr->ibmr.iova; stag_info.total_len = iwmr->ibmr.length; stag_info.reg_addr_pa = *palloc->level1.addr; stag_info.first_pm_pbl_index = palloc->level1.idx; diff --git a/drivers/infiniband/hw/mlx4/cm.c b/drivers/infiniband/hw/mlx4/cm.c index 1e5e525fea73..810f95e55fda 100644 --- a/drivers/infiniband/hw/mlx4/cm.c +++ b/drivers/infiniband/hw/mlx4/cm.c @@ -301,10 +301,20 @@ static void schedule_delayed(struct ib_device *ibdev, struct id_map_entry *id, spin_lock_irqsave(&sriov->going_down_lock, flags); /*make sure that there is no schedule inside the scheduled work.*/ if (!sriov->is_going_down || id->scheduled_delete) { + /* + * Do not requeue timeout work that is already executing. The + * timeout handler may be waiting for id_map_lock and will free + * this entry after the caller releases it. + */ + if (id->scheduled_delete && + !cancel_delayed_work(&id->timeout)) + goto out; + id->scheduled_delete = 1; id->rtu_timeout = rtu_timeout; mod_delayed_work(cm_wq, &id->timeout, timeout); } +out: spin_unlock_irqrestore(&sriov->going_down_lock, flags); } diff --git a/drivers/infiniband/hw/mlx4/main.c b/drivers/infiniband/hw/mlx4/main.c index 7266a6141944..1594e6407b6c 100644 --- a/drivers/infiniband/hw/mlx4/main.c +++ b/drivers/infiniband/hw/mlx4/main.c @@ -1169,6 +1169,10 @@ static int mlx4_ib_mmap(struct ib_ucontext *context, struct vm_area_struct *vma) struct mlx4_clock_params params; int ret; + if (vma->vm_flags & (VM_WRITE | VM_EXEC)) + return -EPERM; + vm_flags_clear(vma, VM_MAYWRITE); + ret = mlx4_get_internal_clock_params(dev->dev, ¶ms); if (ret) return ret; diff --git a/drivers/infiniband/hw/mlx5/cq.c b/drivers/infiniband/hw/mlx5/cq.c index 49b4bf148a4a..6d4857d1c064 100644 --- a/drivers/infiniband/hw/mlx5/cq.c +++ b/drivers/infiniband/hw/mlx5/cq.c @@ -1117,6 +1117,9 @@ int mlx5_ib_pre_destroy_cq(struct ib_cq *cq) struct mlx5_ib_dev *dev = to_mdev(cq->device); struct mlx5_ib_cq *mcq = to_mcq(cq); + if (!cq->uobject) + cancel_work_sync(&mcq->notify_work); + return mlx5_core_destroy_cq(dev->mdev, &mcq->mcq); } @@ -1312,7 +1315,7 @@ static int copy_resize_cqes(struct mlx5_ib_cq *cq) while (get_cqe_opcode(scqe64) != MLX5_CQE_RESIZE_CQ) { dcqe = mlx5_frag_buf_get_wqe(&cq->resize_buf->fbc, - (i + 1) & cq->resize_buf->nent); + (i + 1) & (cq->resize_buf->nent - 1)); dcqe64 = dsize == 64 ? dcqe : dcqe + 64; sw_own = sw_ownership_bit(i + 1, cq->resize_buf->nent); memcpy(dcqe, scqe, dsize); diff --git a/drivers/infiniband/hw/mlx5/fs.c b/drivers/infiniband/hw/mlx5/fs.c index b155baee0017..bc2c15c7172b 100644 --- a/drivers/infiniband/hw/mlx5/fs.c +++ b/drivers/infiniband/hw/mlx5/fs.c @@ -17,6 +17,7 @@ #include #include #include +#include #include #include "mlx5_ib.h" #include "counters.h" @@ -1647,36 +1648,32 @@ static struct mlx5_ib_flow_handler *create_leftovers_rule(struct mlx5_ib_dev *de struct ib_flow_attr *flow_attr, struct mlx5_flow_destination *dst) { + DEFINE_RAW_FLEX(struct ib_flow_attr, flow_attr_wc, flows, 1); + DEFINE_RAW_FLEX(struct ib_flow_attr, flow_attr_uc, flows, 1); + struct mlx5_ib_flow_handler *handler_ucast = NULL; struct mlx5_ib_flow_handler *handler = NULL; - static struct { - struct ib_flow_spec_eth eth_flow; - struct ib_flow_attr flow_attr; - } leftovers_wc = { .flow_attr = { .num_of_specs = 1, - .size = sizeof(leftovers_wc) }, - .eth_flow = { - .type = IB_FLOW_SPEC_ETH, - .size = sizeof(struct ib_flow_spec_eth), - .mask = { .dst_mac = { 0x1 } }, - .val = { .dst_mac = { 0x1 } } } }; - - static struct { - struct ib_flow_spec_eth eth_flow; - struct ib_flow_attr flow_attr; - } leftovers_uc = { .flow_attr = { .num_of_specs = 1, - .size = sizeof(leftovers_uc) }, - .eth_flow = { - .type = IB_FLOW_SPEC_ETH, - .size = sizeof(struct ib_flow_spec_eth), - .mask = { .dst_mac = { 0x1 } }, - .val = { .dst_mac = {} } } }; - - handler = create_flow_rule(dev, ft_prio, &leftovers_wc.flow_attr, dst); + flow_attr_wc->num_of_specs = 1; + flow_attr_wc->size = sizeof(struct ib_flow_attr) + + sizeof(struct ib_flow_spec_eth); + flow_attr_wc->flows[0].eth.type = IB_FLOW_SPEC_ETH; + flow_attr_wc->flows[0].eth.size = sizeof(struct ib_flow_spec_eth); + flow_attr_wc->flows[0].eth.mask.dst_mac[0] = 0x1; + flow_attr_wc->flows[0].eth.val.dst_mac[0] = 0x1; + + flow_attr_uc->num_of_specs = 1; + flow_attr_uc->size = sizeof(struct ib_flow_attr) + + sizeof(struct ib_flow_spec_eth); + flow_attr_uc->flows[0].eth.type = IB_FLOW_SPEC_ETH; + flow_attr_uc->flows[0].eth.size = sizeof(struct ib_flow_spec_eth); + flow_attr_uc->flows[0].eth.mask.dst_mac[0] = 0x1; + + handler = create_flow_rule(dev, ft_prio, flow_attr_wc, dst); if (!IS_ERR(handler) && flow_attr->type == IB_FLOW_ATTR_ALL_DEFAULT) { handler_ucast = create_flow_rule(dev, ft_prio, - &leftovers_uc.flow_attr, dst); + flow_attr_uc, dst); if (IS_ERR(handler_ucast)) { mlx5_del_flow_rules(handler->rule); ft_prio->refcount--; @@ -3017,6 +3014,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_obj(*obj); if (!obj) return -ENOMEM; @@ -3056,8 +3056,8 @@ static int UVERBS_HANDLER(MLX5_IB_METHOD_STEERING_ANCHOR_CREATE)( return 0; destroy_res: - --ft_prio->anchor.rule_goto_table_ref; - mlx5_steering_anchor_destroy_res(ft_prio); + if (!--ft_prio->anchor.rule_goto_table_ref) + mlx5_steering_anchor_destroy_res(ft_prio); put_flow_table: put_flow_table(dev, ft_prio, true); free_obj: diff --git a/drivers/infiniband/hw/mlx5/main.c b/drivers/infiniband/hw/mlx5/main.c index a457647edacd..4a0b4dcf2830 100644 --- a/drivers/infiniband/hw/mlx5/main.c +++ b/drivers/infiniband/hw/mlx5/main.c @@ -3370,7 +3370,7 @@ int mlx5_ib_dev_res_srq_init(struct mlx5_ib_dev *dev) { struct mlx5_ib_resources *devr = &dev->devr; struct ib_srq_init_attr attr; - struct ib_srq *s0, *s1; + struct ib_srq *s0 = NULL, *s1; int ret = 0; /* @@ -3388,19 +3388,27 @@ int mlx5_ib_dev_res_srq_init(struct mlx5_ib_dev *dev) if (ret) goto unlock; - memset(&attr, 0, sizeof(attr)); - attr.attr.max_sge = 1; - attr.attr.max_wr = 1; - attr.srq_type = IB_SRQT_XRC; - attr.ext.cq = devr->c0; - - s0 = ib_create_srq(devr->p0, &attr); - if (IS_ERR(s0)) { - ret = PTR_ERR(s0); - mlx5_ib_err(dev, - "Couldn't create SRQ 0 for res init, err=%pe\n", - s0); - goto unlock; + /* + * s0 is an XRC-type placeholder SRQ used as the default XRQN for + * XRC QPs. Skip it when XRC is absent; all devr->s0 accesses in + * qp.c are inside XRC QP paths that the verbs layer blocks before + * reaching this driver when xrc=0, so NULL is safe. + */ + if (MLX5_CAP_GEN(dev->mdev, xrc)) { + memset(&attr, 0, sizeof(attr)); + attr.attr.max_sge = 1; + attr.attr.max_wr = 1; + attr.srq_type = IB_SRQT_XRC; + attr.ext.cq = devr->c0; + + s0 = ib_create_srq(devr->p0, &attr); + if (IS_ERR(s0)) { + ret = PTR_ERR(s0); + mlx5_ib_err(dev, + "Couldn't create SRQ 0 for res init, err=%pe\n", + s0); + goto unlock; + } } memset(&attr, 0, sizeof(attr)); @@ -3414,7 +3422,8 @@ int mlx5_ib_dev_res_srq_init(struct mlx5_ib_dev *dev) mlx5_ib_err(dev, "Couldn't create SRQ 1 for res init, err=%pe\n", s1); - ib_destroy_srq(s0); + if (s0) + ib_destroy_srq(s0); goto unlock; } @@ -3431,8 +3440,11 @@ static int mlx5_ib_dev_res_init(struct mlx5_ib_dev *dev) struct mlx5_ib_resources *devr = &dev->devr; int ret; + mutex_init(&devr->cq_lock); + mutex_init(&devr->srq_lock); + if (!MLX5_CAP_GEN(dev->mdev, xrc)) - return -EOPNOTSUPP; + return 0; ret = mlx5_cmd_xrcd_alloc(dev->mdev, &devr->xrcdn0, 0); if (ret) @@ -3444,9 +3456,6 @@ static int mlx5_ib_dev_res_init(struct mlx5_ib_dev *dev) return ret; } - mutex_init(&devr->cq_lock); - mutex_init(&devr->srq_lock); - return 0; } @@ -3457,10 +3466,13 @@ static void mlx5_ib_dev_res_cleanup(struct mlx5_ib_dev *dev) /* After s0/s1 init, they are not unset during the device lifetime. */ if (devr->s1) { ib_destroy_srq(devr->s1); - ib_destroy_srq(devr->s0); + if (devr->s0) + ib_destroy_srq(devr->s0); + } + if (MLX5_CAP_GEN(dev->mdev, xrc)) { + mlx5_cmd_xrcd_dealloc(dev->mdev, devr->xrcdn1, 0); + mlx5_cmd_xrcd_dealloc(dev->mdev, devr->xrcdn0, 0); } - mlx5_cmd_xrcd_dealloc(dev->mdev, devr->xrcdn1, 0); - mlx5_cmd_xrcd_dealloc(dev->mdev, devr->xrcdn0, 0); /* After p0/c0 init, they are not unset during the device lifetime. */ if (devr->c0) { ib_destroy_cq(devr->c0); diff --git a/drivers/infiniband/hw/mlx5/odp.c b/drivers/infiniband/hw/mlx5/odp.c index b8618610737a..1f28c30095dc 100644 --- a/drivers/infiniband/hw/mlx5/odp.c +++ b/drivers/infiniband/hw/mlx5/odp.c @@ -1885,8 +1885,8 @@ mlx5_ib_odp_destroy_eq(struct mlx5_ib_dev *dev, struct mlx5_ib_pf_eq *eq) if (!eq->core) return 0; mlx5_eq_disable(dev->mdev, eq->core, &eq->irq_nb); - err = mlx5_eq_destroy_generic(dev->mdev, eq->core); cancel_work_sync(&eq->work); + err = mlx5_eq_destroy_generic(dev->mdev, eq->core); destroy_workqueue(eq->wq); mempool_destroy(eq->pool); diff --git a/drivers/infiniband/hw/mlx5/qp.c b/drivers/infiniband/hw/mlx5/qp.c index 0d4f8b109ad2..60dda72c2d0b 100644 --- a/drivers/infiniband/hw/mlx5/qp.c +++ b/drivers/infiniband/hw/mlx5/qp.c @@ -1624,6 +1624,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, attrs, sq, in, pd, to_mcq(init_attr->send_cq)); if (err) @@ -1635,9 +1637,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) { @@ -1647,6 +1646,7 @@ static int create_raw_packet_qp(struct mlx5_ib_dev *dev, struct mlx5_ib_qp *qp, } rq->base.container_mibqp = qp; + rq->base.mqp.event = mlx5_ib_qp_event; if (qp->flags & IB_QP_CREATE_CVLAN_STRIPPING) rq->flags |= MLX5_IB_RQ_CVLAN_STRIPPING; @@ -2092,13 +2092,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); @@ -2236,14 +2236,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); @@ -2432,6 +2432,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; @@ -2446,8 +2448,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); @@ -2577,14 +2577,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); @@ -5344,11 +5343,14 @@ static void mlx5_ib_wq_event(struct mlx5_core_qp *core_qp, int type) break; default: mlx5_ib_warn(dev, "Unexpected event type %d on WQ %06x\n", type, core_qp->qpn); - return; + goto out; } rwq->ibwq.event_handler(&event, rwq->ibwq.wq_context); } + +out: + mlx5_core_res_put(&core_qp->common); } static int set_delay_drop(struct mlx5_ib_dev *dev) @@ -5616,6 +5618,7 @@ struct ib_wq *mlx5_ib_create_wq(struct ib_pd *pd, rwq = kzalloc_obj(*rwq); if (!rwq) return ERR_PTR(-ENOMEM); + rwq->core_qp.event = mlx5_ib_wq_event; err = prepare_user_rq(pd, init_attr, udata, rwq); if (err) goto err; @@ -5639,7 +5642,6 @@ struct ib_wq *mlx5_ib_create_wq(struct ib_pd *pd, goto err_copy; } - rwq->core_qp.event = mlx5_ib_wq_event; rwq->ibwq.event_handler = init_attr->event_handler; return &rwq->ibwq; diff --git a/drivers/infiniband/hw/mlx5/qpc.c b/drivers/infiniband/hw/mlx5/qpc.c index a7a4f9420271..8b5bd33a7f0f 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; @@ -165,6 +167,10 @@ static int create_resource_common(struct mlx5_ib_dev *dev, int err; qp->common.res = rsc_type; + refcount_set(&qp->common.refcount, 1); + init_completion(&qp->common.free); + qp->pid = current->pid; + spin_lock_irq(&table->lock); err = radix_tree_insert(&table->tree, qp->qpn | (rsc_type << MLX5_USER_INDEX_LEN), @@ -173,10 +179,6 @@ static int create_resource_common(struct mlx5_ib_dev *dev, if (err) return err; - refcount_set(&qp->common.refcount, 1); - init_completion(&qp->common.free); - qp->pid = current->pid; - return 0; } @@ -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/mlx5/srq.c b/drivers/infiniband/hw/mlx5/srq.c index a973c1b7515f..6a4a937d97ce 100644 --- a/drivers/infiniband/hw/mlx5/srq.c +++ b/drivers/infiniband/hw/mlx5/srq.c @@ -284,6 +284,7 @@ int mlx5_ib_create_srq(struct ib_srq *ib_srq, in.pd = to_mpd(ib_srq->pd)->pdn; in.db_record = srq->db.dma; + srq->msrq.event = mlx5_ib_srq_event; err = mlx5_cmd_create_srq(dev, &srq->msrq, &in); kvfree(in.pas); if (err) { @@ -292,8 +293,6 @@ int mlx5_ib_create_srq(struct ib_srq *ib_srq, } mlx5_ib_dbg(dev, "create SRQ with srqn 0x%x\n", srq->msrq.srqn); - - srq->msrq.event = mlx5_ib_srq_event; srq->ibsrq.ext.xrc.srq_num = srq->msrq.srqn; if (udata) { diff --git a/drivers/infiniband/hw/mlx5/wr.c b/drivers/infiniband/hw/mlx5/wr.c index fca9e1d9d5e9..bb2c60380fe2 100644 --- a/drivers/infiniband/hw/mlx5/wr.c +++ b/drivers/infiniband/hw/mlx5/wr.c @@ -927,6 +927,7 @@ static noinline_for_stack int handle_reg_mr_integrity(struct mlx5_ib_dev *dev, qp->next_fence = MLX5_FENCE_MODE_INITIATOR_SMALL; out: + mr->pi_mr = pi_mr; return err; } diff --git a/drivers/infiniband/hw/usnic/usnic_debugfs.c b/drivers/infiniband/hw/usnic/usnic_debugfs.c index 10a8cd5ba076..ece7c6e71499 100644 --- a/drivers/infiniband/hw/usnic/usnic_debugfs.c +++ b/drivers/infiniband/hw/usnic/usnic_debugfs.c @@ -76,7 +76,7 @@ static ssize_t flowinfo_read(struct file *f, char __user *data, qp_flow = f->private_data; ptr = buf; - left = count; + left = sizeof(buf); if (*ppos > 0) return 0; diff --git a/drivers/infiniband/hw/vmw_pvrdma/pvrdma_qp.c b/drivers/infiniband/hw/vmw_pvrdma/pvrdma_qp.c index e939cd5ce40b..53cc49f2b8c9 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_va(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_va(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 345ec486a223..3252c2eb405a 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, if (ret) goto err_srq; - srq->umem = ib_umem_get_va(ibsrq->device, ucmd.buf_addr, ucmd.buf_size, 0); + srq->umem = ib_umem_get_va(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/sw/rdmavt/qp.c b/drivers/infiniband/sw/rdmavt/qp.c index c40cce69e945..ec64a595ce03 100644 --- a/drivers/infiniband/sw/rdmavt/qp.c +++ b/drivers/infiniband/sw/rdmavt/qp.c @@ -1173,7 +1173,7 @@ int rvt_create_qp(struct ib_qp *ibqp, struct ib_qp_init_attr *init_attr, if (rdi->driver_f.qp_priv_init) { ret = rdi->driver_f.qp_priv_init(rdi, qp, init_attr); if (ret) - goto bail_rq_wq; + goto bail_qpn; } break; diff --git a/drivers/infiniband/sw/rxe/rxe_loc.h b/drivers/infiniband/sw/rxe/rxe_loc.h index 64d636bf80fd..9a8e96dfb792 100644 --- a/drivers/infiniband/sw/rxe/rxe_loc.h +++ b/drivers/infiniband/sw/rxe/rxe_loc.h @@ -64,7 +64,7 @@ int rxe_flush_pmem_iova(struct rxe_mr *mr, u64 iova, unsigned int length); int rxe_mr_copy(struct rxe_mr *mr, u64 iova, void *addr, unsigned int length, enum rxe_mr_copy_dir dir); int copy_data(struct rxe_pd *pd, int access, struct rxe_dma_info *dma, - void *addr, int length, enum rxe_mr_copy_dir dir); + void *addr, u32 length, enum rxe_mr_copy_dir dir); int rxe_map_mr_sg(struct ib_mr *ibmr, struct scatterlist *sg, int sg_nents, unsigned int *sg_offset); enum resp_states rxe_mr_do_atomic_op(struct rxe_mr *mr, u64 iova, int opcode, @@ -91,7 +91,8 @@ void rxe_mw_cleanup(struct rxe_pool_elem *elem); /* rxe_net.c */ struct sk_buff *rxe_init_packet(struct rxe_dev *rxe, struct rxe_av *av, - int paylen, struct rxe_pkt_info *pkt); + u32 paylen, struct rxe_pkt_info *pkt); +void rxe_put_skb(struct sk_buff *skb); int rxe_prepare(struct rxe_av *av, struct rxe_pkt_info *pkt, struct sk_buff *skb); int rxe_xmit_packet(struct rxe_qp *qp, struct rxe_pkt_info *pkt, @@ -184,6 +185,9 @@ void rxe_comp_queue_pkt(struct rxe_qp *qp, struct sk_buff *skb); static inline unsigned int wr_opcode_mask(int opcode, struct rxe_qp *qp) { + if (unlikely(opcode < 0 || opcode > IB_WR_REG_MR)) + return 0; + return rxe_wr_opcode_info[opcode].mask[qp->ibqp.qp_type]; } diff --git a/drivers/infiniband/sw/rxe/rxe_mr.c b/drivers/infiniband/sw/rxe/rxe_mr.c index 71d9ea477289..bc7e3cb5a11b 100644 --- a/drivers/infiniband/sw/rxe/rxe_mr.c +++ b/drivers/infiniband/sw/rxe/rxe_mr.c @@ -418,13 +418,13 @@ int copy_data( int access, struct rxe_dma_info *dma, void *addr, - int length, + u32 length, enum rxe_mr_copy_dir dir) { - int bytes; + u32 bytes; struct rxe_sge *sge = &dma->sge[dma->cur_sge]; - int offset = dma->sge_offset; - int resid = dma->resid; + u32 offset = dma->sge_offset; + u32 resid = dma->resid; struct rxe_mr *mr = NULL; u64 iova; int err; @@ -777,6 +777,10 @@ int rxe_reg_fast_mr(struct rxe_qp *qp, struct rxe_send_wqe *wqe) u32 key = wqe->wr.wr.reg.key; u32 access = wqe->wr.wr.reg.access; + /* IB_WR_REG_MR is a kernel-only op; a user QP must not reach here. */ + if (qp->is_user) + return -EOPNOTSUPP; + /* user can only register MR in free state */ if (unlikely(mr->state != RXE_MR_STATE_FREE)) { rxe_dbg_mr(mr, "mr->lkey = 0x%x not free\n", mr->lkey); diff --git a/drivers/infiniband/sw/rxe/rxe_mw.c b/drivers/infiniband/sw/rxe/rxe_mw.c index bddb7a257831..a2e3a6ce0946 100644 --- a/drivers/infiniband/sw/rxe/rxe_mw.c +++ b/drivers/infiniband/sw/rxe/rxe_mw.c @@ -161,6 +161,7 @@ static void rxe_do_bind_mw(struct rxe_qp *qp, struct rxe_send_wqe *wqe, if (mw->ibmw.type == IB_MW_TYPE_2) { rxe_get(qp); + atomic_inc(&qp->mw_bind_num); mw->qp = qp; } } @@ -245,6 +246,7 @@ static void rxe_do_invalidate_mw(struct rxe_mw *mw) /* valid type 2 MW will always have a QP pointer */ qp = mw->qp; mw->qp = NULL; + atomic_dec(&qp->mw_bind_num); rxe_put(qp); /* valid type 2 MW will always have an MR pointer */ @@ -332,6 +334,7 @@ void rxe_mw_cleanup(struct rxe_pool_elem *elem) struct rxe_qp *qp = mw->qp; mw->qp = NULL; + atomic_dec(&qp->mw_bind_num); rxe_put(qp); } diff --git a/drivers/infiniband/sw/rxe/rxe_net.c b/drivers/infiniband/sw/rxe/rxe_net.c index 53daaf4c1eb2..c572cda8fe18 100644 --- a/drivers/infiniband/sw/rxe/rxe_net.c +++ b/drivers/infiniband/sw/rxe/rxe_net.c @@ -429,6 +429,29 @@ int rxe_prepare(struct rxe_av *av, struct rxe_pkt_info *pkt, return err; } +/* + * skb->dev may be rewritten on the TX path (VLAN/bond/tunnel, etc.). + * The netdev we held in rxe_init_packet() is kept in destructor_arg so + * that put always matches hold. skb->cb cannot be used: it is already + * occupied by struct rxe_pkt_info and rewritten by IP control blocks. + */ +static void rxe_skb_set_held_ndev(struct sk_buff *skb, struct net_device *ndev) +{ + dev_hold(ndev); + skb->dev = ndev; + skb_shinfo(skb)->destructor_arg = ndev; +} + +static void rxe_skb_put_held_ndev(struct sk_buff *skb) +{ + struct net_device *ndev = skb_shinfo(skb)->destructor_arg; + + if (ndev) { + skb_shinfo(skb)->destructor_arg = NULL; + dev_put(ndev); + } +} + static void rxe_skb_tx_dtor(struct sk_buff *skb) { struct rxe_qp *qp = skb->sk->sk_user_data; @@ -441,6 +464,18 @@ static void rxe_skb_tx_dtor(struct sk_buff *skb) rxe_put(qp); sock_put(skb->sk); + rxe_skb_put_held_ndev(skb); +} + +/* + * Free an skb that still holds a netdev reference from rxe_init_packet() + * and does not yet have rxe_skb_tx_dtor() installed. Once the TX + * destructor is set, callers must use kfree_skb() instead. + */ +void rxe_put_skb(struct sk_buff *skb) +{ + rxe_skb_put_held_ndev(skb); + kfree_skb(skb); } static int rxe_send(struct sk_buff *skb, struct rxe_pkt_info *pkt) @@ -529,14 +564,14 @@ int rxe_xmit_packet(struct rxe_qp *qp, struct rxe_pkt_info *pkt, goto done; drop: - kfree_skb(skb); + rxe_put_skb(skb); err = 0; done: return err; } struct sk_buff *rxe_init_packet(struct rxe_dev *rxe, struct rxe_av *av, - int paylen, struct rxe_pkt_info *pkt) + u32 paylen, struct rxe_pkt_info *pkt) { unsigned int hdr_len; struct sk_buff *skb = NULL; @@ -574,8 +609,7 @@ struct sk_buff *rxe_init_packet(struct rxe_dev *rxe, struct rxe_av *av, skb_reserve(skb, hdr_len + LL_RESERVED_SPACE(ndev)); - /* FIXME: hold reference to this netdev until life of this skb. */ - skb->dev = ndev; + rxe_skb_set_held_ndev(skb, ndev); rcu_read_unlock(); if (av->network_type == RXE_NETWORK_TYPE_IPV4) @@ -638,9 +672,8 @@ static void rxe_sock_put(struct sock *sk, if (refcount_read(&sk->sk_refcnt) > SK_REF_FOR_TUNNEL) { __sock_put(sk); } else { + set_sk(net, NULL); rxe_release_udp_tunnel(sk); - sk = NULL; - set_sk(net, sk); } } @@ -710,6 +743,28 @@ void rxe_set_port_state(struct rxe_dev *rxe) dev_put(ndev); } +/* + * Move all QPs to the error state so pending send/recv work is drained and + * in-flight TX skbs (which hold a netdev reference) can be released. Called + * from the netdev notifier so unregister cannot stall on held skbs. + */ +static void rxe_flush_qps(struct rxe_dev *rxe) +{ + struct rxe_pool_elem *elem; + struct rxe_qp *qp; + unsigned long index; + + rcu_read_lock(); + xa_for_each(&rxe->qp_pool.xa, index, elem) { + if (!elem || !kref_get_unless_zero(&elem->ref_cnt)) + continue; + qp = elem->obj; + rxe_qp_error(qp); + rxe_put(qp); + } + rcu_read_unlock(); +} + static int rxe_notify(struct notifier_block *not_blk, unsigned long event, void *arg) @@ -721,7 +776,12 @@ static int rxe_notify(struct notifier_block *not_blk, return NOTIFY_OK; switch (event) { + case NETDEV_GOING_DOWN: + /* Start draining TX queues before the netdev disappears. */ + rxe_flush_qps(rxe); + break; case NETDEV_UNREGISTER: + rxe_flush_qps(rxe); ib_unregister_device_queued(&rxe->ib_dev); rxe_net_del(&rxe->ib_dev); break; @@ -735,7 +795,6 @@ static int rxe_notify(struct notifier_block *not_blk, rxe_counter_inc(rxe, RXE_CNT_LINK_DOWNED); break; case NETDEV_REBOOT: - case NETDEV_GOING_DOWN: case NETDEV_CHANGEADDR: case NETDEV_CHANGENAME: case NETDEV_FEAT_CHANGE: diff --git a/drivers/infiniband/sw/rxe/rxe_odp.c b/drivers/infiniband/sw/rxe/rxe_odp.c index ab21b620e94c..9d27244f89bc 100644 --- a/drivers/infiniband/sw/rxe/rxe_odp.c +++ b/drivers/infiniband/sw/rxe/rxe_odp.c @@ -136,6 +136,11 @@ static inline bool rxe_check_pagefault(struct ib_umem_odp *umem_odp, u64 iova, while (addr < iova + length) { idx = (addr - ib_umem_start(umem_odp)) >> umem_odp->page_shift; + if (idx >= ib_umem_odp_num_pages(umem_odp)) { + need_fault = true; + break; + } + if ((umem_odp->map.pfn_list[idx] & access) != access) { need_fault = true; break; @@ -469,7 +474,7 @@ static int rxe_ib_prefetch_sg_list(struct ib_pd *ibpd, struct rxe_mr *mr; struct ib_umem_odp *umem_odp; - mr = lookup_mr(pd, IB_ACCESS_LOCAL_WRITE, + mr = lookup_mr(pd, IB_ACCESS_LOCAL_WRITE | IB_ACCESS_ON_DEMAND, sg_list[i].lkey, RXE_LOOKUP_LOCAL); if (!mr) { @@ -535,7 +540,7 @@ static int rxe_ib_advise_mr_prefetch(struct ib_pd *ibpd, for (i = 0; i < num_sge; ++i) { /* Takes a reference, which will be released in the queued work */ - mr = lookup_mr(pd, IB_ACCESS_LOCAL_WRITE, + mr = lookup_mr(pd, IB_ACCESS_LOCAL_WRITE | IB_ACCESS_ON_DEMAND, sg_list[i].lkey, RXE_LOOKUP_LOCAL); if (!mr) { mr = ERR_PTR(-EINVAL); diff --git a/drivers/infiniband/sw/rxe/rxe_qp.c b/drivers/infiniband/sw/rxe/rxe_qp.c index 311f285d78a6..fea55bc3b0cb 100644 --- a/drivers/infiniband/sw/rxe/rxe_qp.c +++ b/drivers/infiniband/sw/rxe/rxe_qp.c @@ -858,6 +858,16 @@ int rxe_qp_chk_destroy(struct rxe_qp *qp) return -EBUSY; } + /* An attempt to destroy a QP while it still holds references for + * bound type 2 memory windows will fail immediately. Otherwise the + * QP is freed with those references outstanding and the windows are + * left pointing at freed memory (use-after-free). + */ + if (atomic_read(&qp->mw_bind_num)) { + rxe_dbg_qp(qp, "Attempt to destroy while type 2 MWs are bound\n"); + return -EBUSY; + } + return 0; } diff --git a/drivers/infiniband/sw/rxe/rxe_recv.c b/drivers/infiniband/sw/rxe/rxe_recv.c index 2c90387aa126..e1d90633f085 100644 --- a/drivers/infiniband/sw/rxe/rxe_recv.c +++ b/drivers/infiniband/sw/rxe/rxe_recv.c @@ -320,6 +320,14 @@ void rxe_rcv(struct sk_buff *skb) struct rxe_dev *rxe = pkt->rxe; unsigned int skblen = skb->len - skb_network_offset(skb); + /* + * pkt lives in skb->cb, which the network stack has already used + * for its own state: for IPv6 the qword holding pkt->qp holds + * inet6_skb_parm.nhoff. The drop label puts pkt->qp, so clear + * it before the first early exit. + */ + pkt->qp = NULL; + if (unlikely(skb->len < RXE_BTH_BYTES)) goto drop; @@ -328,7 +336,6 @@ void rxe_rcv(struct sk_buff *skb) pkt->opcode = bth_opcode(pkt); pkt->psn = bth_psn(pkt); - pkt->qp = NULL; pkt->mask |= rxe_opcode[pkt->opcode].mask; /* diff --git a/drivers/infiniband/sw/rxe/rxe_req.c b/drivers/infiniband/sw/rxe/rxe_req.c index 24f5c044363f..4f353abd76f5 100644 --- a/drivers/infiniband/sw/rxe/rxe_req.c +++ b/drivers/infiniband/sw/rxe/rxe_req.c @@ -510,7 +510,14 @@ static int finish_packet(struct rxe_qp *qp, struct rxe_av *av, if (pkt->mask & RXE_WRITE_OR_SEND_MASK) { if (wqe->wr.send_flags & IB_SEND_INLINE) { - u8 *tmp = &wqe->dma.inline_data[wqe->dma.sge_offset]; + u32 sge_offset = READ_ONCE(wqe->dma.sge_offset); + u8 *tmp; + + if (unlikely(sge_offset > (u32)qp->sq.max_inline || + payload > (u32)qp->sq.max_inline - sge_offset)) + return -EINVAL; + + tmp = &wqe->dma.inline_data[sge_offset]; memcpy(payload_addr(pkt), tmp, payload); @@ -811,7 +818,7 @@ int rxe_requester(struct rxe_qp *qp) wqe->status = IB_WC_LOC_PROT_ERR; else wqe->status = IB_WC_LOC_QP_OP_ERR; - kfree_skb(skb); + rxe_put_skb(skb); if (ah) rxe_put(ah); goto err; diff --git a/drivers/infiniband/sw/rxe/rxe_resp.c b/drivers/infiniband/sw/rxe/rxe_resp.c index 02b16e2b49b8..1b7f31737225 100644 --- a/drivers/infiniband/sw/rxe/rxe_resp.c +++ b/drivers/infiniband/sw/rxe/rxe_resp.c @@ -288,6 +288,7 @@ static enum resp_states get_srq_wqe(struct rxe_qp *qp) } size = sizeof(*wqe) + num_sge * sizeof(struct rxe_sge); memcpy(&qp->resp.srq_wqe, wqe, size); + qp->resp.srq_wqe.wqe.dma.num_sge = num_sge; qp->resp.wqe = &qp->resp.srq_wqe.wqe; queue_advance_consumer(q, QUEUE_TYPE_FROM_CLIENT); @@ -328,6 +329,7 @@ static enum resp_states rxe_get_recv_wqe(struct rxe_qp *qp) } size = sizeof(*wqe) + num_sge * sizeof(struct rxe_sge); memcpy(&qp->resp.srq_wqe, wqe, size); + qp->resp.srq_wqe.wqe.dma.num_sge = num_sge; qp->resp.wqe = &qp->resp.srq_wqe.wqe; return RESPST_CHK_LENGTH; @@ -612,7 +614,7 @@ static enum resp_states check_rkey(struct rxe_qp *qp, } static enum resp_states send_data_in(struct rxe_qp *qp, void *data_addr, - int data_len) + u32 data_len) { int err; @@ -827,20 +829,21 @@ static enum resp_states atomic_write_reply(struct rxe_qp *qp, static struct sk_buff *prepare_ack_packet(struct rxe_qp *qp, struct rxe_pkt_info *ack, int opcode, - int payload, + u32 payload, u32 psn, u8 syndrome) { struct rxe_dev *rxe = to_rdev(qp->ibqp.device); struct sk_buff *skb; - int paylen; - int pad; + u32 paylen; + u32 pad = 0; int err; /* * allocate packet */ - pad = (-payload) & 0x3; + if (payload % 4) + pad = 4 - payload % 4; paylen = rxe_opcode[opcode].length + payload + pad + RXE_ICRC_SIZE; skb = rxe_init_packet(rxe, &qp->pri_av, paylen, ack); @@ -866,7 +869,7 @@ static struct sk_buff *prepare_ack_packet(struct rxe_qp *qp, err = rxe_prepare(&qp->pri_av, ack, skb); if (err) { - kfree_skb(skb); + rxe_put_skb(skb); return NULL; } @@ -934,9 +937,9 @@ static enum resp_states read_reply(struct rxe_qp *qp, { struct rxe_pkt_info ack_pkt; struct sk_buff *skb; - int mtu = qp->mtu; + u32 mtu = qp->mtu; enum resp_states state; - int payload; + u32 payload; int opcode; int err; struct resp_res *res = qp->resp.res; @@ -982,7 +985,7 @@ static enum resp_states read_reply(struct rxe_qp *qp, res->state = rdatm_res_state_next; - payload = min_t(int, res->read.resid, mtu); + payload = min(res->read.resid, mtu); skb = prepare_ack_packet(qp, &ack_pkt, opcode, payload, res->cur_psn, AETH_ACK_UNLIMITED); @@ -994,7 +997,7 @@ static enum resp_states read_reply(struct rxe_qp *qp, err = rxe_mr_copy(mr, res->read.va, payload_addr(&ack_pkt), payload, RXE_FROM_MR_OBJ); if (err) { - kfree_skb(skb); + rxe_put_skb(skb); state = RESPST_ERR_RKEY_VIOLATION; goto err_out; } diff --git a/drivers/infiniband/sw/rxe/rxe_verbs.h b/drivers/infiniband/sw/rxe/rxe_verbs.h index 0f5ffd94643f..80df376e61ee 100644 --- a/drivers/infiniband/sw/rxe/rxe_verbs.h +++ b/drivers/infiniband/sw/rxe/rxe_verbs.h @@ -261,6 +261,7 @@ struct rxe_qp { struct rxe_av alt_av; atomic_t mcg_num; + atomic_t mw_bind_num; struct sk_buff_head req_pkts; struct sk_buff_head resp_pkts; diff --git a/drivers/infiniband/sw/siw/siw_main.c b/drivers/infiniband/sw/siw/siw_main.c index 9735b75ac933..c08796e4262a 100644 --- a/drivers/infiniband/sw/siw/siw_main.c +++ b/drivers/infiniband/sw/siw/siw_main.c @@ -217,8 +217,11 @@ static struct ib_qp *siw_get_base_qp(struct ib_device *base_dev, int id) /* * siw_qp_id2obj() increments object reference count */ + struct ib_qp *base_qp = &qp->base_qp; + siw_qp_put(qp); - return &qp->base_qp; + + return base_qp; } return NULL; } diff --git a/drivers/infiniband/sw/siw/siw_qp_tx.c b/drivers/infiniband/sw/siw/siw_qp_tx.c index f7dd32c6e5ba..c133c20b835d 100644 --- a/drivers/infiniband/sw/siw/siw_qp_tx.c +++ b/drivers/infiniband/sw/siw/siw_qp_tx.c @@ -85,7 +85,7 @@ static int siw_try_1seg(struct siw_iwarp_tx *c_tx, void *paddr) if (likely(PAGE_SIZE - off >= bytes)) { memcpy(paddr, buffer + off, bytes); } else { - unsigned long part = bytes - (PAGE_SIZE - off); + unsigned long part = PAGE_SIZE - off; memcpy(paddr, buffer + off, part); kunmap_local(buffer); @@ -805,17 +805,21 @@ static int siw_qp_sq_proc_tx(struct siw_qp *qp, struct siw_wqe *wqe) if (wqe->wr_status == SIW_WR_QUEUED) { if (!(wqe->sqe.flags & SIW_WQE_INLINE)) { - if (tx_type(wqe) == SIW_OP_READ_RESPONSE) - wqe->sqe.num_sge = 1; - if (tx_type(wqe) != SIW_OP_READ && tx_type(wqe) != SIW_OP_READ_LOCAL_INV) { + enum ib_access_flags perms = 0; + /* - * Reference memory to be tx'd w/o checking - * access for LOCAL_READ permission, since - * not defined in RDMA core. + * Local READ permission doesn't exist in RDMA core. + * A READ RESPONSE source is read by the remote peer, + * so it must be checked for REMOTE_READ permission. */ - rv = siw_check_sgl_tx(qp->pd, wqe, 0); + if (tx_type(wqe) == SIW_OP_READ_RESPONSE) { + perms = IB_ACCESS_REMOTE_READ; + wqe->sqe.num_sge = 1; + } + + rv = siw_check_sgl_tx(qp->pd, wqe, perms); if (rv < 0) { if (tx_type(wqe) == SIW_OP_READ_RESPONSE) diff --git a/drivers/infiniband/ulp/ipoib/ipoib_main.c b/drivers/infiniband/ulp/ipoib/ipoib_main.c index 6c14246befb1..f0b72d65fdeb 100644 --- a/drivers/infiniband/ulp/ipoib/ipoib_main.c +++ b/drivers/infiniband/ulp/ipoib/ipoib_main.c @@ -230,6 +230,13 @@ static int ipoib_stop(struct net_device *dev) clear_bit(IPOIB_FLAG_ADMIN_UP, &priv->flags); + /* Normal flush runs without RTNL and may bring the device back + * up. Cancel it before the device down transition. + * Heavy flush is already serialized by RTNL and must not be + * waited on here while RTNL is held. + */ + cancel_work_sync(&priv->flush_normal); + netif_stop_queue(dev); ipoib_ib_dev_down(dev); diff --git a/drivers/infiniband/ulp/isert/ib_isert.c b/drivers/infiniband/ulp/isert/ib_isert.c index e69db43370ff..efa8d7b7844c 100644 --- a/drivers/infiniband/ulp/isert/ib_isert.c +++ b/drivers/infiniband/ulp/isert/ib_isert.c @@ -2583,7 +2583,7 @@ static void isert_put_unsol_pending_cmds(struct iscsit_conn *conn) { struct iscsit_cmd *cmd, *tmp; - static LIST_HEAD(drop_cmd_list); + LIST_HEAD(drop_cmd_list); spin_lock_bh(&conn->cmd_lock); list_for_each_entry_safe(cmd, tmp, &conn->conn_cmd_list, i_conn_node) { diff --git a/drivers/infiniband/ulp/rtrs/rtrs-clt.c b/drivers/infiniband/ulp/rtrs/rtrs-clt.c index eac38b57b00d..a908745af1a9 100644 --- a/drivers/infiniband/ulp/rtrs/rtrs-clt.c +++ b/drivers/infiniband/ulp/rtrs/rtrs-clt.c @@ -489,18 +489,22 @@ static int rtrs_post_send_rdma(struct rtrs_clt_con *con, imm, flags, wr, NULL); } -static void process_io_rsp(struct rtrs_clt_path *clt_path, u32 msg_id, +static bool process_io_rsp(struct rtrs_clt_path *clt_path, u32 msg_id, s16 errno, bool w_inval) { struct rtrs_clt_io_req *req; - if (WARN_ON(msg_id >= clt_path->queue_depth)) - return; + if (!clt_path->reqs || msg_id >= clt_path->queue_depth) + return false; req = &clt_path->reqs[msg_id]; + if (!req->mr) + return false; + /* Drop need_inv if server responded with send with invalidation */ req->mr->need_inval &= !w_inval; complete_rdma_req(req, errno, true, false); + return true; } static void rtrs_clt_recv_done(struct rtrs_clt_con *con, struct ib_wc *wc) @@ -562,7 +566,8 @@ static void rtrs_clt_rkey_rsp_done(struct rtrs_clt_con *con, struct ib_wc *wc) if (WARN_ON(buf_id != msg_id)) goto out; clt_path->rbufs[buf_id].rkey = le32_to_cpu(msg->rkey); - process_io_rsp(clt_path, msg_id, err, w_inval); + if (!process_io_rsp(clt_path, msg_id, err, w_inval)) + goto out; } ib_dma_sync_single_for_device(clt_path->s.dev->ib_dev, iu->dma_addr, iu->size, DMA_FROM_DEVICE); @@ -577,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) @@ -634,7 +635,13 @@ static void rtrs_clt_rdma_done(struct ib_cq *cq, struct ib_wc *wc) w_inval = (imm_type == RTRS_IO_RSP_W_INV_IMM); rtrs_from_io_rsp_imm(imm_payload, &msg_id, &err); - process_io_rsp(clt_path, msg_id, err, w_inval); + if (!process_io_rsp(clt_path, msg_id, err, w_inval)) { + rtrs_err(clt_path->clt, + "Invalid IO rsp: msg_id %u queue_depth %zu\n", + msg_id, clt_path->queue_depth); + rtrs_rdma_error_recovery(con); + return; + } } else if (imm_type == RTRS_HB_MSG_IMM) { WARN_ON(con->c.cid); rtrs_send_hb_ack(&clt_path->s); @@ -650,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(): %pe\n", - ERR_PTR(err)); - rtrs_rdma_error_recovery(con); - } + rtrs_clt_repost_recv(con); break; case IB_WC_RECV: /* @@ -678,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: /* @@ -1693,7 +1689,7 @@ static int create_con_cq_qp(struct rtrs_clt_con *con) clt_path->s.dev_ref++; /* QD * (REQ + RSP + FR REGS or INVS) + drain */ max_send_wr = min(wr_limit, clt_path->queue_depth * 4 + 1); - max_recv_wr = min(wr_limit, clt_path->queue_depth * 3 + 1); + max_recv_wr = min(wr_limit, clt_path->queue_depth * 2 + 1); max_send_sge = 2; } atomic_set(&con->c.sq_wr_avail, max_send_wr); @@ -1853,6 +1849,10 @@ static int rtrs_rdma_conn_established(struct rtrs_clt_con *con, } if (con->c.cid == 0) { queue_depth = le16_to_cpu(msg->queue_depth); + if (!queue_depth) { + rtrs_err(clt, "Invalid queue depth %u\n", queue_depth); + return -ECONNRESET; + } if (clt_path->queue_depth > 0 && queue_depth != clt_path->queue_depth) { rtrs_err(clt, "Error: queue depth changed\n"); @@ -2514,7 +2514,12 @@ static void rtrs_clt_info_rsp_done(struct ib_cq *cq, struct ib_wc *wc) ib_wc_status_msg(wc->status)); goto out; } - WARN_ON(wc->opcode != IB_WC_RECV); + if (wc->opcode != IB_WC_RECV) { + rtrs_err(clt_path->clt, + "Path info response has unexpected opcode %d\n", + wc->opcode); + goto out; + } if (wc->byte_len < sizeof(*msg)) { rtrs_err(clt_path->clt, "Path info response is malformed: size %d\n", diff --git a/drivers/infiniband/ulp/srp/ib_srp.c b/drivers/infiniband/ulp/srp/ib_srp.c index 955f36efeebd..5811f02df980 100644 --- a/drivers/infiniband/ulp/srp/ib_srp.c +++ b/drivers/infiniband/ulp/srp/ib_srp.c @@ -3499,7 +3499,7 @@ static int srp_parse_options(struct net *net, const char *buf, } ret = srp_parse_in(net, &target->rdma_cm.dst.ss, p, &has_port); - if (!has_port) + if (ret == 0 && !has_port) ret = -EINVAL; if (ret < 0) { pr_warn("bad dest parameter '%s'\n", p); diff --git a/drivers/interconnect/qcom/bcm-voter.c b/drivers/interconnect/qcom/bcm-voter.c index a2d437a05a11..b05350af0320 100644 --- a/drivers/interconnect/qcom/bcm-voter.c +++ b/drivers/interconnect/qcom/bcm-voter.c @@ -3,7 +3,6 @@ * Copyright (c) 2020-2021, The Linux Foundation. All rights reserved. */ -#include #include #include #include @@ -14,6 +13,7 @@ #include #include "bcm-voter.h" +#include "icc-common.h" #include "icc-rpmh.h" static LIST_HEAD(bcm_voters); @@ -47,17 +47,6 @@ static int cmp_vcd(void *priv, const struct list_head *a, const struct list_head return bcm_a->aux_data.vcd - bcm_b->aux_data.vcd; } -static u64 bcm_div(u64 num, u32 base) -{ - /* Ensure that small votes aren't lost. */ - if (num && num < base) - return 1; - - do_div(num, base); - - return num; -} - /* BCMs with enable_mask use one-hot-encoding for on/off signaling */ static void bcm_aggregate_mask(struct qcom_icc_bcm *bcm) { @@ -99,20 +88,20 @@ static void bcm_aggregate(struct qcom_icc_bcm *bcm) for (bucket = 0; bucket < QCOM_ICC_NUM_BUCKETS; bucket++) { for (i = 0; i < bcm->num_nodes; i++) { node = bcm->nodes[i]; - temp = bcm_div(node->sum_avg[bucket] * bcm->aux_data.width, - node->buswidth * node->channels); + temp = qcom_bw_div(node->sum_avg[bucket] * bcm->aux_data.width, + node->buswidth * node->channels); agg_avg[bucket] = max(agg_avg[bucket], temp); - temp = bcm_div(node->max_peak[bucket] * bcm->aux_data.width, - node->buswidth); + temp = qcom_bw_div(node->max_peak[bucket] * bcm->aux_data.width, + node->buswidth); agg_peak[bucket] = max(agg_peak[bucket], temp); } temp = agg_avg[bucket] * bcm->vote_scale; - bcm->vote_x[bucket] = bcm_div(temp, bcm->aux_data.unit); + bcm->vote_x[bucket] = qcom_bw_div(temp, bcm->aux_data.unit); temp = agg_peak[bucket] * bcm->vote_scale; - bcm->vote_y[bucket] = bcm_div(temp, bcm->aux_data.unit); + bcm->vote_y[bucket] = qcom_bw_div(temp, bcm->aux_data.unit); } if (bcm->keepalive && bcm->vote_x[QCOM_ICC_BUCKET_AMC] == 0 && diff --git a/drivers/interconnect/qcom/icc-common.h b/drivers/interconnect/qcom/icc-common.h index 21c39b163948..af4b5a6f30b7 100644 --- a/drivers/interconnect/qcom/icc-common.h +++ b/drivers/interconnect/qcom/icc-common.h @@ -7,6 +7,15 @@ #define __DRIVERS_INTERCONNECT_QCOM_ICC_COMMON_H__ #include +#include + +static inline u64 qcom_bw_div(u64 num, u32 base) +{ + if (num && num < base) + return 1; + + return div_u64(num, base); +} struct icc_node_data *qcom_icc_xlate_extended(const struct of_phandle_args *spec, void *data); diff --git a/drivers/interconnect/qcom/icc-rpm.c b/drivers/interconnect/qcom/icc-rpm.c index ca4c8a944755..407233f2d121 100644 --- a/drivers/interconnect/qcom/icc-rpm.c +++ b/drivers/interconnect/qcom/icc-rpm.c @@ -58,15 +58,32 @@ static int qcom_icc_set_qnoc_qos(struct icc_node *src) struct qcom_icc_qos *qos = &qn->qos; int rc; + rc = regmap_update_bits(qp->regmap, + qp->qos_offset + QNOC_QOS_MCTL_LOWn_ADDR(qos->qos_port), + QNOC_QOS_MCTL_DFLT_PRIO_MASK, + qos->areq_prio << QNOC_QOS_MCTL_DFLT_PRIO_SHIFT); + if (rc) + return rc; + rc = regmap_update_bits(qp->regmap, qp->qos_offset + QNOC_QOS_MCTL_LOWn_ADDR(qos->qos_port), - QNOC_QOS_MCTL_DFLT_PRIO_MASK, - qos->areq_prio << QNOC_QOS_MCTL_DFLT_PRIO_SHIFT); + QNOC_QOS_MCTL_URGFWD_EN_MASK, + !!qos->urg_fwd_en << QNOC_QOS_MCTL_URGFWD_EN_SHIFT); + if (rc) + return rc; + + if (!qos->aux_qos_port) + return 0; + + rc = regmap_update_bits(qp->regmap, + qp->qos_offset + QNOC_QOS_MCTL_LOWn_ADDR(qos->aux_qos_port), + QNOC_QOS_MCTL_DFLT_PRIO_MASK, + qos->areq_prio << QNOC_QOS_MCTL_DFLT_PRIO_SHIFT); if (rc) return rc; return regmap_update_bits(qp->regmap, - qp->qos_offset + QNOC_QOS_MCTL_LOWn_ADDR(qos->qos_port), + qp->qos_offset + QNOC_QOS_MCTL_LOWn_ADDR(qos->aux_qos_port), QNOC_QOS_MCTL_URGFWD_EN_MASK, !!qos->urg_fwd_en << QNOC_QOS_MCTL_URGFWD_EN_SHIFT); } @@ -75,8 +92,9 @@ static int qcom_icc_bimc_set_qos_health(struct qcom_icc_provider *qp, struct qcom_icc_qos *qos, int regnum) { - u32 val; u32 mask; + u32 val; + int ret; val = qos->prio_level; mask = M_BKE_HEALTH_CFG_PRIOLVL_MASK; @@ -90,8 +108,17 @@ static int qcom_icc_bimc_set_qos_health(struct qcom_icc_provider *qp, mask |= M_BKE_HEALTH_CFG_LIMITCMDS_MASK; } + ret = regmap_update_bits(qp->regmap, + qp->qos_offset + M_BKE_HEALTH_CFG_ADDR(regnum, qos->qos_port), + mask, val); + if (ret) + return ret; + + if (!qos->aux_qos_port) + return 0; + return regmap_update_bits(qp->regmap, - qp->qos_offset + M_BKE_HEALTH_CFG_ADDR(regnum, qos->qos_port), + qp->qos_offset + M_BKE_HEALTH_CFG_ADDR(regnum, qos->aux_qos_port), mask, val); } @@ -102,7 +129,7 @@ static int qcom_icc_set_bimc_qos(struct icc_node *src) struct icc_provider *provider; u32 mode = NOC_QOS_MODE_BYPASS; u32 val = 0; - int i, rc = 0; + int i, rc; qn = src->data; provider = src->provider; @@ -116,8 +143,7 @@ static int qcom_icc_set_bimc_qos(struct icc_node *src) */ if (mode != NOC_QOS_MODE_BYPASS) { for (i = 3; i >= 0; i--) { - rc = qcom_icc_bimc_set_qos_health(qp, - &qn->qos, i); + rc = qcom_icc_bimc_set_qos_health(qp, &qn->qos, i); if (rc) return rc; } @@ -126,8 +152,17 @@ static int qcom_icc_set_bimc_qos(struct icc_node *src) val = 1; } + rc = regmap_update_bits(qp->regmap, + qp->qos_offset + M_BKE_EN_ADDR(qn->qos.qos_port), + M_BKE_EN_EN_BMASK, val); + if (rc) + return rc; + + if (!qn->qos.aux_qos_port) + return 0; + return regmap_update_bits(qp->regmap, - qp->qos_offset + M_BKE_EN_ADDR(qn->qos.qos_port), + qp->qos_offset + M_BKE_EN_ADDR(qn->qos.aux_qos_port), M_BKE_EN_EN_BMASK, val); } @@ -145,8 +180,24 @@ static int qcom_icc_noc_set_qos_priority(struct qcom_icc_provider *qp, if (rc) return rc; + rc = regmap_update_bits(qp->regmap, + qp->qos_offset + NOC_QOS_PRIORITYn_ADDR(qos->qos_port), + NOC_QOS_PRIORITY_P0_MASK, qos->prio_level); + if (rc) + return rc; + + if (!qos->aux_qos_port) + return 0; + + val = qos->areq_prio << NOC_QOS_PRIORITY_P1_SHIFT; + rc = regmap_update_bits(qp->regmap, + qp->qos_offset + NOC_QOS_PRIORITYn_ADDR(qos->aux_qos_port), + NOC_QOS_PRIORITY_P1_MASK, val); + if (rc) + return rc; + return regmap_update_bits(qp->regmap, - qp->qos_offset + NOC_QOS_PRIORITYn_ADDR(qos->qos_port), + qp->qos_offset + NOC_QOS_PRIORITYn_ADDR(qos->aux_qos_port), NOC_QOS_PRIORITY_P0_MASK, qos->prio_level); } @@ -182,8 +233,17 @@ static int qcom_icc_set_noc_qos(struct icc_node *src) /* How did we get here? */ } + rc = regmap_update_bits(qp->regmap, + qp->qos_offset + NOC_QOS_MODEn_ADDR(qn->qos.qos_port), + NOC_QOS_MODEn_MASK, mode); + if (rc) + return rc; + + if (!qn->qos.aux_qos_port) + return 0; + return regmap_update_bits(qp->regmap, - qp->qos_offset + NOC_QOS_MODEn_ADDR(qn->qos.qos_port), + qp->qos_offset + NOC_QOS_MODEn_ADDR(qn->qos.aux_qos_port), NOC_QOS_MODEn_MASK, mode); } @@ -298,25 +358,25 @@ static u64 qcom_icc_calc_rate(struct qcom_icc_provider *qp, struct qcom_icc_node u64 agg_avg_rate, agg_peak_rate, agg_rate; if (qn->channels) - agg_avg_rate = div_u64(qn->sum_avg[ctx], qn->channels); + agg_avg_rate = qcom_bw_div(qn->sum_avg[ctx], qn->channels); else agg_avg_rate = qn->sum_avg[ctx]; if (qn->ab_coeff) { agg_avg_rate = agg_avg_rate * qn->ab_coeff; - agg_avg_rate = div_u64(agg_avg_rate, 100); + agg_avg_rate = qcom_bw_div(agg_avg_rate, 100); } if (qn->ib_coeff) { agg_peak_rate = qn->max_peak[ctx] * 100; - agg_peak_rate = div_u64(agg_peak_rate, qn->ib_coeff); + agg_peak_rate = qcom_bw_div(agg_peak_rate, qn->ib_coeff); } else { agg_peak_rate = qn->max_peak[ctx]; } agg_rate = max_t(u64, agg_avg_rate, agg_peak_rate); - return div_u64(agg_rate, qn->buswidth); + return qcom_bw_div(agg_rate, qn->buswidth); } /** @@ -583,8 +643,15 @@ int qnoc_probe(struct platform_device *pdev) node->data = qnodes[i]; icc_node_add(node, provider); - for (j = 0; j < qnodes[i]->num_links; j++) - icc_link_create(node, qnodes[i]->links[j]); + for (j = 0; j < qnodes[i]->num_links; j++) { + ret = icc_link_create(node, qnodes[i]->links[j]); + if (ret) { + icc_nodes_remove(provider); + clk_bulk_disable_unprepare(qp->num_intf_clks, + qp->intf_clks); + goto err_disable_unprepare_clk; + } + } /* Set QoS registers (we only need to do it once, generally) */ if (qnodes[i]->qos.ap_owned && diff --git a/drivers/interconnect/qcom/icc-rpm.h b/drivers/interconnect/qcom/icc-rpm.h index cdd5f444b152..d2c5f45eeedf 100644 --- a/drivers/interconnect/qcom/icc-rpm.h +++ b/drivers/interconnect/qcom/icc-rpm.h @@ -30,7 +30,7 @@ enum qcom_icc_type { * @resource_type: RPM resource type of the clock resource * @clock_id: index of the clock resource of a specific resource type * @branch: whether the resource represents a branch clock -*/ + */ struct rpm_clk_resource { u32 resource_type; u32 clock_id; @@ -77,6 +77,7 @@ struct qcom_icc_provider { * @ap_owned: indicates if the node is owned by the AP or by the RPM * @qos_mode: default qos mode for this node * @qos_port: qos port number for finding qos registers of this node + * @aux_qos_port: optional QoS port in addition to @qos_port. Zero means "none". * @urg_fwd_en: enable urgent forwarding */ struct qcom_icc_qos { @@ -86,6 +87,7 @@ struct qcom_icc_qos { bool ap_owned; int qos_mode; int qos_port; + u16 aux_qos_port; bool urg_fwd_en; }; @@ -167,7 +169,7 @@ int qnoc_probe(struct platform_device *pdev); void qnoc_remove(struct platform_device *pdev); bool qcom_icc_rpm_smd_available(void); -int qcom_icc_rpm_smd_send(int ctx, int rsc_type, int id, u32 val); +int qcom_icc_rpm_smd_send(int ctx, int rsc_type, int id, u64 val); int qcom_icc_rpm_set_bus_rate(const struct rpm_clk_resource *clk, int ctx, u32 rate); #endif diff --git a/drivers/interconnect/qcom/msm8976.c b/drivers/interconnect/qcom/msm8976.c index c219dcfd43b6..11100264ef69 100644 --- a/drivers/interconnect/qcom/msm8976.c +++ b/drivers/interconnect/qcom/msm8976.c @@ -454,7 +454,8 @@ static struct qcom_icc_node mas_oxili = { .qos.qos_mode = NOC_QOS_MODE_BYPASS, .qos.areq_prio = 0, .qos.prio_level = 0, - .qos.qos_port = 16, /* [16, 17] */ + .qos.qos_port = 16, + .qos.aux_qos_port = 17, .num_links = ARRAY_SIZE(mas_oxili_links), .links = mas_oxili_links, }; diff --git a/drivers/interconnect/qcom/msm8996.c b/drivers/interconnect/qcom/msm8996.c index 882f9d2b6d4e..7fc808cc5975 100644 --- a/drivers/interconnect/qcom/msm8996.c +++ b/drivers/interconnect/qcom/msm8996.c @@ -501,6 +501,7 @@ static struct qcom_icc_node mas_venus = { .qos.areq_prio = 0, .qos.prio_level = 0, .qos.qos_port = 3, + .qos.aux_qos_port = 4, .num_links = ARRAY_SIZE(mas_mnoc_bimc_common_links), .links = mas_mnoc_bimc_common_links }; diff --git a/drivers/interconnect/qcom/smd-rpm.c b/drivers/interconnect/qcom/smd-rpm.c index dbc7ae50b02b..6ac9aef942ad 100644 --- a/drivers/interconnect/qcom/smd-rpm.c +++ b/drivers/interconnect/qcom/smd-rpm.c @@ -20,7 +20,7 @@ static struct qcom_smd_rpm *icc_smd_rpm; struct icc_rpm_smd_req { __le32 key; __le32 nbytes; - __le32 value; + __le64 value; }; bool qcom_icc_rpm_smd_available(void) @@ -29,12 +29,12 @@ bool qcom_icc_rpm_smd_available(void) } EXPORT_SYMBOL_GPL(qcom_icc_rpm_smd_available); -int qcom_icc_rpm_smd_send(int ctx, int rsc_type, int id, u32 val) +int qcom_icc_rpm_smd_send(int ctx, int rsc_type, int id, u64 val) { struct icc_rpm_smd_req req = { .key = cpu_to_le32(RPM_KEY_BW), - .nbytes = cpu_to_le32(sizeof(u32)), - .value = cpu_to_le32(val), + .nbytes = cpu_to_le32(sizeof(u64)), + .value = cpu_to_le64(val), }; return qcom_rpm_smd_write(icc_smd_rpm, ctx, rsc_type, id, &req, diff --git a/drivers/interconnect/samsung/exynos.c b/drivers/interconnect/samsung/exynos.c index 8e8f56186a36..9a4789fadac2 100644 --- a/drivers/interconnect/samsung/exynos.c +++ b/drivers/interconnect/samsung/exynos.c @@ -98,6 +98,7 @@ static void exynos_generic_icc_remove(struct platform_device *pdev) struct exynos_icc_priv *priv = platform_get_drvdata(pdev); icc_provider_deregister(&priv->provider); + dev_pm_qos_remove_request(&priv->qos_req); icc_nodes_remove(&priv->provider); } diff --git a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c index add671363c82..e52a7d95c919 100644 --- a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c +++ b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3-test.c @@ -125,8 +125,8 @@ arm_smmu_v3_test_debug_print_used_bits(struct arm_smmu_entry_writer *writer, { __le64 used_bits[NUM_ENTRY_QWORDS] = {}; - arm_smmu_get_ste_used(ste, used_bits); - pr_debug("STE used bits: "); + writer->ops->get_used(ste, used_bits); + pr_debug("Entry used bits: "); print_hex_dump_debug(" ", DUMP_PREFIX_NONE, 16, 8, used_bits, sizeof(used_bits), false); } @@ -643,7 +643,7 @@ static void arm_smmu_v3_invs_test_verify(struct kunit *test, const int *ids, const int *users, const int *ssids) { - KUNIT_EXPECT_EQ(test, invs->num_invs, num_invs); + KUNIT_ASSERT_EQ(test, invs->num_invs, num_invs); KUNIT_EXPECT_EQ(test, invs->num_trashes, num_trashes); while (num_invs--) { KUNIT_EXPECT_EQ(test, invs->inv[num_invs].id, ids[num_invs]); @@ -654,6 +654,7 @@ static void arm_smmu_v3_invs_test_verify(struct kunit *test, } static struct arm_smmu_invs invs1 = { + .max_invs = 3, .num_invs = 3, .inv = { { .type = INV_TYPE_S2_VMID, .id = 1, }, { .type = INV_TYPE_S2_VMID_S1_CLEAR, .id = 1, }, @@ -661,6 +662,7 @@ static struct arm_smmu_invs invs1 = { }; static struct arm_smmu_invs invs2 = { + .max_invs = 3, .num_invs = 3, .inv = { { .type = INV_TYPE_S2_VMID, .id = 1, }, /* duplicated */ { .type = INV_TYPE_ATS, .id = 4, }, @@ -668,6 +670,7 @@ static struct arm_smmu_invs invs2 = { }; static struct arm_smmu_invs invs3 = { + .max_invs = 3, .num_invs = 3, .inv = { { .type = INV_TYPE_S2_VMID, .id = 1, }, /* duplicated */ { .type = INV_TYPE_ATS, .id = 5, }, /* recover a trash */ @@ -675,6 +678,7 @@ static struct arm_smmu_invs invs3 = { }; static struct arm_smmu_invs invs4 = { + .max_invs = 3, .num_invs = 3, .inv = { { .type = INV_TYPE_ATS, .id = 10, .ssid = 1 }, { .type = INV_TYPE_ATS, .id = 10, .ssid = 3 }, @@ -682,6 +686,7 @@ static struct arm_smmu_invs invs4 = { }; static struct arm_smmu_invs invs5 = { + .max_invs = 3, .num_invs = 3, .inv = { { .type = INV_TYPE_ATS, .id = 10, .ssid = 2 }, { .type = INV_TYPE_ATS, .id = 10, .ssid = 3 }, /* duplicate */ @@ -704,17 +709,20 @@ static void arm_smmu_v3_invs_test(struct kunit *test) /* New array */ test_a = arm_smmu_invs_alloc(0); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, test_a); KUNIT_EXPECT_EQ(test, test_a->num_invs, 0); /* Test1: merge invs1 (new array) */ test_b = arm_smmu_invs_merge(test_a, &invs1); kfree(test_a); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, test_b); arm_smmu_v3_invs_test_verify(test, test_b, ARRAY_SIZE(results1[0]), 0, results1[0], results1[1], results1[2]); /* Test2: merge invs2 (new array) */ test_a = arm_smmu_invs_merge(test_b, &invs2); kfree(test_b); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, test_a); arm_smmu_v3_invs_test_verify(test, test_a, ARRAY_SIZE(results2[0]), 0, results2[0], results2[1], results2[2]); @@ -726,6 +734,7 @@ static void arm_smmu_v3_invs_test(struct kunit *test) /* Test4: merge invs3 (new array) */ test_b = arm_smmu_invs_merge(test_a, &invs3); kfree(test_a); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, test_b); arm_smmu_v3_invs_test_verify(test, test_b, ARRAY_SIZE(results4[0]), 0, results4[0], results4[1], results4[2]); @@ -737,6 +746,7 @@ static void arm_smmu_v3_invs_test(struct kunit *test) /* Test6: purge test_b (new array) */ test_a = arm_smmu_invs_purge(test_b); kfree(test_b); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, test_a); arm_smmu_v3_invs_test_verify(test, test_a, ARRAY_SIZE(results6[0]), 0, results6[0], results6[1], results6[2]); @@ -748,12 +758,14 @@ static void arm_smmu_v3_invs_test(struct kunit *test) /* Test8: merge invs4 (new array) */ test_b = arm_smmu_invs_merge(test_a, &invs4); kfree(test_a); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, test_b); arm_smmu_v3_invs_test_verify(test, test_b, ARRAY_SIZE(results7[0]), 0, results7[0], results7[1], results7[2]); /* Test9: merge invs5 (new array) */ test_a = arm_smmu_invs_merge(test_b, &invs5); kfree(test_b); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, test_a); arm_smmu_v3_invs_test_verify(test, test_a, ARRAY_SIZE(results8[0]), 0, results8[0], results8[1], results8[2]); @@ -765,6 +777,7 @@ static void arm_smmu_v3_invs_test(struct kunit *test) /* Test11: purge test_a (new array) */ test_b = arm_smmu_invs_purge(test_a); kfree(test_a); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, test_b); arm_smmu_v3_invs_test_verify(test, test_b, ARRAY_SIZE(results10[0]), 0, results10[0], results10[1], results10[2]); 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 b510dd47f231..68f1f6e8ba7e 100644 --- a/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +++ b/drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c @@ -1515,6 +1515,9 @@ static void arm_smmu_write_cd_l1_desc(struct arm_smmu_cdtab_l1 *dst, { u64 val = (l2ptr_dma & CTXDESC_L1_DESC_L2PTR_MASK) | CTXDESC_L1_DESC_V; + /* Ensure the zero-cleared L2 table is fully visible. */ + dma_wmb(); + /* The HW has 64 bit atomicity with stores to the L2 CD table */ WRITE_ONCE(dst->l2ptr, cpu_to_le64(val)); } @@ -1804,6 +1807,9 @@ static void arm_smmu_write_strtab_l1_desc(struct arm_smmu_strtab_l1 *dst, val |= FIELD_PREP(STRTAB_L1_DESC_SPAN, STRTAB_SPLIT + 1); val |= l2ptr_dma & STRTAB_L1_DESC_L2PTR_MASK; + /* Ensure the new L2 table is fully visible. */ + dma_wmb(); + /* The HW has 64 bit atomicity with stores to the L2 STE table */ WRITE_ONCE(dst->l2ptr, cpu_to_le64(val)); } @@ -4170,6 +4176,13 @@ static int arm_smmu_insert_master(struct arm_smmu_device *smmu, sizeof(master->streams[0]), arm_smmu_stream_id_cmp, NULL); + /* + * Clear after sorting: RB_CLEAR_NODE() records the node's own address, + * which sort_nonatomic() invalidates by relocating the entries. + */ + 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]; @@ -4202,7 +4215,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); kfree(master->build_invs); } @@ -4222,7 +4237,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/iommu/intel/dmar.c b/drivers/iommu/intel/dmar.c index ba675b08cd20..6377ba97a9ea 100644 --- a/drivers/iommu/intel/dmar.c +++ b/drivers/iommu/intel/dmar.c @@ -1344,6 +1344,49 @@ static void qi_dump_fault(struct intel_iommu *iommu, u32 fault) (unsigned long long)desc->qw1); } +static int qi_drain_remaining_descs(struct intel_iommu *iommu, int head, + int wait_index) +{ + struct q_inval *qi = iommu->qi; + int shift = qi_shift(iommu); + struct qi_desc wait_desc = {}; + struct qi_desc nop_desc = {}; + cycles_t start; + + nop_desc.qw0 = QI_IWD_FENCE | QI_IWD_TYPE; + + wait_desc.qw0 = QI_IWD_STATUS_DATA(QI_DONE) | QI_IWD_PRQ_DRAIN | + QI_IWD_STATUS_WRITE | QI_IWD_FENCE | QI_IWD_TYPE; + wait_desc.qw1 = virt_to_phys(&qi->desc_status[wait_index]); + + while (head != wait_index) { + memcpy(qi->desc + (head << shift), &nop_desc, 1 << shift); + head = (head + 1) % QI_LENGTH; + } + + WRITE_ONCE(qi->desc_status[wait_index], QI_IN_USE); + memcpy(qi->desc + (wait_index << shift), &wait_desc, 1 << shift); + + /* + * Order the descriptor rewrites before the writel() that restarts + * the fetch engine. + */ + wmb(); + + writel(DMA_FSTS_IQE, iommu->reg + DMAR_FSTS_REG); + + start = get_cycles(); + while (READ_ONCE(qi->desc_status[wait_index]) != QI_DONE) { + if (DMAR_OPERATION_TIMEOUT < (get_cycles() - start)) { + pr_err("Timeout draining invalidation queue after IQE\n"); + return -ETIMEDOUT; + } + cpu_relax(); + } + + return 0; +} + static int qi_check_fault(struct intel_iommu *iommu, int index, int wait_index) { u32 fault; @@ -1366,18 +1409,25 @@ static int qi_check_fault(struct intel_iommu *iommu, int index, int wait_index) * is cleared. */ if (fault & DMA_FSTS_IQE) { + int head_idx, ret; + head = readl(iommu->reg + DMAR_IQH_REG); - if ((head >> shift) == index) { - struct qi_desc *desc = qi->desc + head; - - /* - * desc->qw2 and desc->qw3 are either reserved or - * used by software as private data. We won't print - * out these two qw's for security consideration. - */ - memcpy(desc, qi->desc + (wait_index << shift), - 1 << shift); - writel(DMA_FSTS_IQE, iommu->reg + DMAR_FSTS_REG); + head_idx = (head >> shift) % QI_LENGTH; + + /* + * The faulting descriptor can be anywhere within the current + * submission's range [index, wait_index]. Since the queue is + * circular, this submission may wrap around QI_LENGTH + * (index > wait_index in that case), so check both the + * non-wrapped and wrapped cases of the range. + */ + if (index <= wait_index ? + (head_idx >= index && head_idx <= wait_index) : + (head_idx >= index || head_idx <= wait_index)) { + ret = qi_drain_remaining_descs(iommu, head_idx, wait_index); + if (ret) + return ret; + pr_info("Invalidation Queue Error (IQE) cleared\n"); return -EINVAL; } diff --git a/drivers/iommu/intel/iommu.c b/drivers/iommu/intel/iommu.c index 2e3b3ab216f8..fddb624af7c1 100644 --- a/drivers/iommu/intel/iommu.c +++ b/drivers/iommu/intel/iommu.c @@ -1452,12 +1452,103 @@ static void intel_iommu_init_qi(struct intel_iommu *iommu) } } +/* + * Reserve a domain ID inherited from the previous kernel so that it is not + * handed out again while the copied translation structures are still live. + * + * Returns 0 when the ID is reserved, was already reserved, or cannot be + * re-assigned, and a negative errno for a genuine allocation failure. + */ +static int reserve_domain_id(struct intel_iommu *iommu, int did) +{ + int ret; + + if (did < 0 || did >= iommu->max_domain_id) + return 0; + + ret = ida_alloc_range(&iommu->domain_ida, did, did, GFP_KERNEL); + /* + * Devices sharing a domain share its ID, so the same ID is seen in + * more than one context entry; -ENOSPC merely reports that it is + * already reserved. On success the allocated ID is returned, which + * is not an error either. + */ + if (ret == -ENOSPC || ret >= 0) + return 0; + + return ret; +} + +/* + * Reserve the domain IDs used by a scalable mode context entry copied from + * the previous kernel. + */ +static int copy_pasid_table_dids(struct intel_iommu *iommu, struct context_entry *ce) +{ + struct pasid_dir_entry *dir; + unsigned long dir_size; + phys_addr_t dir_phys; + int ret = 0; + int i, j; + + dir_phys = ce->lo & VTD_PAGE_MASK; + if (!dir_phys) + return 0; + + dir_size = get_pasid_dir_size(ce); + dir = memremap(dir_phys, dir_size * sizeof(*dir), MEMREMAP_WB); + if (!dir) + return -ENOMEM; + + for (i = 0; i < dir_size; i++) { + struct pasid_entry *table; + phys_addr_t table_phys; + + if (!pasid_pde_is_present(&dir[i])) + continue; + + /* + * Do not use get_pasid_table_from_pde(); that returns a + * phys_to_virt() pointer, which is not valid for memory + * owned by the previous kernel. + */ + table_phys = READ_ONCE(dir[i].val) & PDE_PFN_MASK; + if (!table_phys) + continue; + + /* A PASID table is one page: PASID_TBL_ENTRIES * 64 bytes. */ + table = memremap(table_phys, PAGE_SIZE, MEMREMAP_WB); + if (!table) { + ret = -ENOMEM; + goto out; + } + + for (j = 0; j < PASID_TBL_ENTRIES; j++) { + if (!pasid_pte_is_present(&table[j])) + continue; + + ret = reserve_domain_id(iommu, pasid_get_domain_id(&table[j])); + if (ret) { + memunmap(table); + goto out; + } + } + + memunmap(table); + } + +out: + memunmap(dir); + + return ret; +} + static int copy_context_table(struct intel_iommu *iommu, struct root_entry *old_re, struct context_entry **tbl, int bus, bool ext) { - int tbl_idx, tbl_slot = 0, idx, devfn, ret = 0, did; + int tbl_idx, tbl_slot = 0, idx, devfn, ret = 0; struct context_entry *new_ce = NULL, ce; struct context_entry *old_ce = NULL; struct root_entry re; @@ -1519,10 +1610,20 @@ static int copy_context_table(struct intel_iommu *iommu, if (!context_present(&ce)) continue; - - did = context_domain_id(&ce); - if (did >= 0 && did < iommu->max_domain_id) - ida_alloc_range(&iommu->domain_ida, did, did, GFP_KERNEL); + /* + * The context entry only holds a domain ID in legacy mode. + * In scalable mode the IDs are in the PASID table entries. + */ + if (ext) + ret = copy_pasid_table_dids(iommu, &ce); + else + ret = reserve_domain_id(iommu, context_domain_id(&ce)); + if (ret) { + /* Not yet published through @tbl, so free it here. */ + iommu_free_pages(new_ce); + new_ce = NULL; + goto out_unmap; + } set_context_copied(iommu, bus, devfn); new_ce[idx] = ce; @@ -1591,7 +1692,7 @@ static int copy_translation_tables(struct intel_iommu *iommu) if (ret) { pr_err("%s: Failed to copy context table for bus %d\n", iommu->name, bus); - continue; + goto err_free_ctxt_tbls; } } @@ -1623,11 +1724,27 @@ static int copy_translation_tables(struct intel_iommu *iommu) memunmap(old_rt); return 0; +err_free_ctxt_tbls: + /* + * None of these tables have been linked into iommu->root_entry yet, + * so they are unreachable and must be freed here. + */ + for (bus = 0; bus < ctxt_table_entries; bus++) + iommu_free_pages(ctxt_tbls[bus]); + kfree(ctxt_tbls); out_unmap: memunmap(old_rt); err_free_bitmap: bitmap_free(iommu->copied_tables); iommu->copied_tables = NULL; + + /* + * Only reservations taken from the old context entries can be in the + * ida at this point; no domain has been allocated on this IOMMU yet. + * ida_destroy() empties it and leaves it ready for reuse. + */ + ida_destroy(&iommu->domain_ida); + return ret; } @@ -2911,10 +3028,10 @@ static unsigned int compute_vasz_lg2_ss(struct intel_iommu *iommu, *top_level = 4; return min(57, mgaw); } else if (mgaw > 39 && sagaw >= BIT(2)) { - *top_level = 3 + ffs(sagaw >> 3); + *top_level = 2 + ffs(sagaw >> 2); return min(48, mgaw); } else if (mgaw > 30 && sagaw >= BIT(1)) { - *top_level = 2 + ffs(sagaw >> 2); + *top_level = 1 + ffs(sagaw >> 1); return min(39, mgaw); } return 0; @@ -3870,6 +3987,14 @@ static int identity_domain_attach_dev(struct iommu_domain *domain, if (dev_is_real_dma_subdevice(dev)) return 0; + if (sm_supported(iommu)) + ret = intel_pasid_setup_pass_through(iommu, dev, IOMMU_NO_PASID); + else + ret = device_setup_pass_through(dev); + + if (ret) + return ret; + /* * The identity domain has no iopf_handler, so no IOPF reference is * taken for it. The reference held by the old domain must still be @@ -3877,16 +4002,9 @@ static int identity_domain_attach_dev(struct iommu_domain *domain, * not affect the IOPF reference count. */ iopf_for_domain_remove(old, dev); + info->domain_attached = true; - if (sm_supported(iommu)) - ret = intel_pasid_setup_pass_through(iommu, dev, IOMMU_NO_PASID); - else - ret = device_setup_pass_through(dev); - - if (!ret) - info->domain_attached = true; - - return ret; + return 0; } static int identity_domain_set_dev_pasid(struct iommu_domain *domain, diff --git a/drivers/iommu/intel/nested.c b/drivers/iommu/intel/nested.c index 2b979bec56ce..f84fc8b41fde 100644 --- a/drivers/iommu/intel/nested.c +++ b/drivers/iommu/intel/nested.c @@ -59,6 +59,8 @@ static int intel_nested_attach_dev(struct iommu_domain *domain, if (ret) goto disable_iopf; + iopf_for_domain_remove(old, dev); + info->domain = dmar_domain; info->domain_attached = true; spin_lock_irqsave(&dmar_domain->lock, flags); diff --git a/drivers/iommu/iommufd/device.c b/drivers/iommu/iommufd/device.c index a664c70a6fe7..1b0bdf57ac8a 100644 --- a/drivers/iommu/iommufd/device.c +++ b/drivers/iommu/iommufd/device.c @@ -849,7 +849,8 @@ iommufd_group_do_replace_reserved_iova(struct iommufd_group *igroup, return 0; err_unresv: - iommufd_group_remove_reserved_iova(igroup, hwpt_paging); + if (!old_hwpt_paging || hwpt_paging->ioas != old_hwpt_paging->ioas) + iommufd_group_remove_reserved_iova(igroup, hwpt_paging); return rc; } @@ -889,6 +890,7 @@ iommufd_device_do_replace(struct iommufd_device *idev, ioasid_t pasid, return NULL; } + old_hwpt_paging = find_hwpt_paging(old_hwpt); if (attach_resv) { rc = iommufd_group_do_replace_reserved_iova(igroup, hwpt_paging); if (rc) @@ -899,7 +901,6 @@ iommufd_device_do_replace(struct iommufd_device *idev, ioasid_t pasid, if (rc) goto err_unresv; - old_hwpt_paging = find_hwpt_paging(old_hwpt); if (old_hwpt_paging && pasid == IOMMU_NO_PASID && (!hwpt_paging || hwpt_paging->ioas != old_hwpt_paging->ioas)) iommufd_group_remove_reserved_iova(igroup, old_hwpt_paging); @@ -920,7 +921,8 @@ iommufd_device_do_replace(struct iommufd_device *idev, ioasid_t pasid, /* Caller must destroy old_hwpt */ return old_hwpt; err_unresv: - if (attach_resv) + if (attach_resv && + (!old_hwpt_paging || hwpt_paging->ioas != old_hwpt_paging->ioas)) iommufd_group_remove_reserved_iova(igroup, hwpt_paging); err_unlock: mutex_unlock(&igroup->lock); diff --git a/drivers/iommu/iommufd/selftest.c b/drivers/iommu/iommufd/selftest.c index ee706f18f7e9..f6da927461b5 100644 --- a/drivers/iommu/iommufd/selftest.c +++ b/drivers/iommu/iommufd/selftest.c @@ -2056,11 +2056,9 @@ static int iommufd_test_dmabuf_get(struct iommufd_ucmd *ucmd, } rc = dma_buf_fd(dmabuf, open_flags); - if (rc < 0) { + if (rc < 0) dma_buf_put(dmabuf); - return rc; - } - return 0; + return rc; err_free: kfree(priv->memory); diff --git a/drivers/irqchip/Kconfig b/drivers/irqchip/Kconfig index 20b77fbc51ee..01f8415f62fc 100644 --- a/drivers/irqchip/Kconfig +++ b/drivers/irqchip/Kconfig @@ -522,7 +522,7 @@ config GOLDFISH_PIC config QCOM_PDC tristate "Qualcomm PDC" - depends on ARCH_QCOM + depends on QCOM_SCM select IRQ_DOMAIN_HIERARCHY help Power Domain Controller driver to manage and configure wakeup @@ -530,7 +530,7 @@ config QCOM_PDC config QCOM_MPM tristate "Qualcomm MPM" - depends on ARCH_QCOM + depends on ARCH_QCOM || COMPILE_TEST depends on MAILBOX select IRQ_DOMAIN_HIERARCHY help diff --git a/drivers/irqchip/irq-aclint-sswi.c b/drivers/irqchip/irq-aclint-sswi.c index ca06efd86fa1..d3ef2cd3b5c5 100644 --- a/drivers/irqchip/irq-aclint-sswi.c +++ b/drivers/irqchip/irq-aclint-sswi.c @@ -179,6 +179,7 @@ static int __init generic_aclint_sswi_early_probe(struct device_node *node, } IRQCHIP_DECLARE(mips_p8700_sswi, "mips,p8700-aclint-sswi", generic_aclint_sswi_early_probe); IRQCHIP_DECLARE(nuclei_ux900_sswi, "nuclei,ux900-aclint-sswi", generic_aclint_sswi_early_probe); +IRQCHIP_DECLARE(spacemit_k3_sswi, "spacemit,k3-aclint-sswi", generic_aclint_sswi_early_probe); /* THEAD variant */ #define THEAD_C9XX_CSR_SXSTATUS 0x5c0 diff --git a/drivers/irqchip/irq-gic-common.c b/drivers/irqchip/irq-gic-common.c index c776f9142610..8bd1eaa54295 100644 --- a/drivers/irqchip/irq-gic-common.c +++ b/drivers/irqchip/irq-gic-common.c @@ -48,7 +48,7 @@ void gic_enable_quirks(u32 iidr, const struct gic_quirk *quirks, int gic_configure_irq(unsigned int irq, unsigned int type, void __iomem *base) { - u32 confmask = 0x2 << ((irq % 16) * 2); + u32 confmask = BIT(((irq % 16) * 2) + 1); u32 confoff = (irq / 16) * 4; u32 val, oldval; int ret = 0; diff --git a/drivers/irqchip/irq-gic-v3-its.c b/drivers/irqchip/irq-gic-v3-its.c index 81a96149f915..011415f59b34 100644 --- a/drivers/irqchip/irq-gic-v3-its.c +++ b/drivers/irqchip/irq-gic-v3-its.c @@ -87,6 +87,8 @@ struct its_baser { u64 val; u32 order; u32 psz; + /* Inherited from a sibling ITS, not freed here */ + bool shared; }; struct its_device; @@ -2248,7 +2250,8 @@ static unsigned long *its_lpi_alloc(int nr_irqs, u32 *base, int *nr_ids) static void its_lpi_free(unsigned long *bitmap, u32 base, u32 nr_ids) { - WARN_ON(free_lpi_range(base, nr_ids)); + if (free_lpi_range(base, nr_ids)) + pr_err_ratelimited("ITS: failed to free LPI range %u:%u\n", base, nr_ids); bitmap_free(bitmap); } @@ -2604,7 +2607,8 @@ static void its_free_tables(struct its_node *its) for (i = 0; i < GITS_BASER_NR_REGS; i++) { if (its->tables[i].base) { - its_free_pages(its->tables[i].base, its->tables[i].order); + if (!its->tables[i].shared) + its_free_pages(its->tables[i].base, its->tables[i].order); its->tables[i].base = NULL; } } @@ -2703,6 +2707,7 @@ static int its_alloc_tables(struct its_node *its) WARN_ON(i != 2); if ((sibling = find_sibling_its(its))) { *baser = sibling->tables[2]; + baser->shared = true; its_write_baser(its, baser, baser->val); continue; } @@ -4599,6 +4604,7 @@ static void its_vpe_teardown(struct its_vpe *vpe) its_vpe_db_proxy_unmap(vpe); its_vpe_id_free(vpe->vpe_id); its_free_pending_table(vpe->vpt_page); + vpe->vpt_page = NULL; } static void its_vpe_irq_domain_free(struct irq_domain *domain, @@ -5328,16 +5334,18 @@ static int __init its_probe_one(struct its_node *its) } gits_write_cwriter(0, its->base + GITS_CWRITER); + + err = its_init_domain(its); + if (err) + goto out_free_collection; + + /* Enable last: the unwind frees memory an enabled ITS may access */ ctlr = readl_relaxed(its->base + GITS_CTLR); ctlr |= GITS_CTLR_ENABLE; if (is_v4(its)) ctlr |= GITS_CTLR_ImDe; writel_relaxed(ctlr, its->base + GITS_CTLR); - err = its_init_domain(its); - if (err) - goto out_free_collection; - raw_spin_lock(&its_lock); list_add(&its->entry, &its_nodes); raw_spin_unlock(&its_lock); diff --git a/drivers/irqchip/irq-gic-v3.c b/drivers/irqchip/irq-gic-v3.c index 6e1fa5b247fc..187bd149f68c 100644 --- a/drivers/irqchip/irq-gic-v3.c +++ b/drivers/irqchip/irq-gic-v3.c @@ -457,7 +457,7 @@ static int gic_peek_irq(struct irq_data *d, u32 offset) u32 index, mask; offset = convert_offset_index(d, offset, &index); - mask = 1 << (index % 32); + mask = BIT(index % 32); if (gic_irq_in_rdist(d)) base = gic_data_rdist_sgi_base(); @@ -473,7 +473,7 @@ static void gic_poke_irq(struct irq_data *d, u32 offset) u32 index, mask; offset = convert_offset_index(d, offset, &index); - mask = 1 << (index % 32); + mask = BIT(index % 32); if (gic_irq_in_rdist(d)) base = gic_data_rdist_sgi_base(); @@ -1728,8 +1728,6 @@ static int gic_irq_get_fwspec_info(struct irq_fwspec *fwspec, struct irq_fwspec_ /* If the specifier provides an affinity, use it */ if (fwspec->param_count == 4 && fwspec->param[3]) { - struct fwnode_handle *fw; - switch (fwspec->param[0]) { case 1: /* PPI */ case 3: /* EPPI */ @@ -1738,7 +1736,10 @@ static int gic_irq_get_fwspec_info(struct irq_fwspec *fwspec, struct irq_fwspec_ return 0; } - fw = of_fwnode_handle(of_find_node_by_phandle(fwspec->param[3])); + struct device_node *np __free(device_node) = + of_find_node_by_phandle(fwspec->param[3]); + struct fwnode_handle *fw = of_fwnode_handle(np); + if (!fw) return -ENOENT; @@ -2344,6 +2345,17 @@ gic_acpi_parse_madt_gicc(union acpi_subtable_headers *header, return 0; } + /* Not counted by gic_acpi_match_gicc(), so there is no slot for it */ + if (!gicc->gicr_base_address) { + int cpu = get_cpu_for_acpi_id(gicc->uid); + + pr_warn(FW_BUG "GICC entry with ACPI UID %u has no GICR base address, CPU kept offline\n", + gicc->uid); + if (cpu >= 0) + cpumask_set_cpu(cpu, &broken_rdists); + return 0; + } + redist_base = ioremap(gicc->gicr_base_address, size); if (!redist_base) return -ENOMEM; diff --git a/drivers/irqchip/irq-gic.c b/drivers/irqchip/irq-gic.c index f6bc29f515fb..fb7a55f5b394 100644 --- a/drivers/irqchip/irq-gic.c +++ b/drivers/irqchip/irq-gic.c @@ -178,14 +178,14 @@ static inline bool cascading_gic_irq(struct irq_data *d) */ static void gic_poke_irq(struct irq_data *d, u32 offset) { - u32 mask = 1 << (irqd_to_hwirq(d) % 32); + u32 mask = BIT(irqd_to_hwirq(d) % 32); writel_relaxed(mask, gic_dist_base(d) + offset + (irqd_to_hwirq(d) / 32) * 4); } static int gic_peek_irq(struct irq_data *d, u32 offset) { - u32 mask = 1 << (irqd_to_hwirq(d) % 32); + u32 mask = BIT(irqd_to_hwirq(d) % 32); return !!(readl_relaxed(gic_dist_base(d) + offset + (irqd_to_hwirq(d) / 32) * 4) & mask); } diff --git a/drivers/irqchip/irq-mips-gic.c b/drivers/irqchip/irq-mips-gic.c index 19a57c5e2b2e..be38989d8e73 100644 --- a/drivers/irqchip/irq-mips-gic.c +++ b/drivers/irqchip/irq-mips-gic.c @@ -70,6 +70,10 @@ static int __gic_with_next_online_cpu(int prev) { unsigned int cpu; + /* Release the redirect/other region lock to the previous CPU, if any. */ + if (prev >= 0) + mips_cm_unlock_other(); + /* Discover the next online CPU */ cpu = cpumask_next(prev, cpu_online_mask); @@ -77,23 +81,12 @@ static int __gic_with_next_online_cpu(int prev) if (cpu >= nr_cpu_ids) return cpu; - /* - * Move the access lock to the next CPU's GIC local register block. - * - * Set GIC_VL_OTHER. Since the caller holds gic_lock nothing can - * clobber the written value. - */ - write_gic_vl_other(mips_cm_vp_id(cpu)); + /* Lock access to redirect/other region to the next CPU */ + mips_cm_lock_other_cpu(cpu, CM_GCR_Cx_OTHER_BLOCK_LOCAL); return cpu; } -static inline void gic_unlock_cluster(void) -{ - if (mips_cps_multicluster_cpus()) - mips_cm_unlock_other(); -} - /** * for_each_online_cpu_gic() - Iterate over online CPUs, access local registers * @cpu: An integer variable to hold the current CPU number @@ -108,7 +101,6 @@ static inline void gic_unlock_cluster(void) guard(raw_spinlock_irqsave)(gic_lock); \ for ((cpu) = __gic_with_next_online_cpu(-1); \ (cpu) < nr_cpu_ids; \ - gic_unlock_cluster(), \ (cpu) = __gic_with_next_online_cpu(cpu)) /** @@ -305,14 +297,14 @@ static void gic_ack_irq(struct irq_data *d) } } -static int gic_set_type(struct irq_data *d, unsigned int type) +static int gic_set_type_locked(struct irq_data *d, unsigned int type) { unsigned int irq, pol, trig, dual; - unsigned long flags; + + lockdep_assert_held(&gic_lock); irq = GIC_HWIRQ_TO_SHARED(d->hwirq); - raw_spin_lock_irqsave(&gic_lock, flags); switch (type & IRQ_TYPE_SENSE_MASK) { case IRQ_TYPE_EDGE_FALLING: pol = GIC_POL_FALLING_EDGE; @@ -359,11 +351,16 @@ static int gic_set_type(struct irq_data *d, unsigned int type) else irq_set_chip_handler_name_locked(d, &gic_level_irq_controller, handle_level_irq, NULL); - raw_spin_unlock_irqrestore(&gic_lock, flags); return 0; } +static int gic_set_type(struct irq_data *d, unsigned int type) +{ + guard(raw_spinlock_irqsave)(&gic_lock); + return gic_set_type_locked(d, type); +} + #ifdef CONFIG_SMP static int gic_set_affinity(struct irq_data *d, const struct cpumask *cpumask, bool force) @@ -371,6 +368,7 @@ static int gic_set_affinity(struct irq_data *d, const struct cpumask *cpumask, unsigned int irq = GIC_HWIRQ_TO_SHARED(d->hwirq); unsigned int cpu, cl, old_cpu, old_cl; unsigned long flags; + bool enabled; /* * The GIC specifies that we can only route an interrupt to one VP(E), @@ -392,15 +390,20 @@ static int gic_set_affinity(struct irq_data *d, const struct cpumask *cpumask, raw_spin_lock_irqsave(&gic_lock, flags); /* - * If we're moving affinity between clusters, stop routing the - * interrupt to any VP(E) in the old cluster. + * If we're moving affinity between clusters, save the interrupt's + * mask state, stop routing it to any VP(E) in the old cluster and + * disable it there so it is no longer delivered. */ if (cl != old_cl) { if (gic_irq_lock_cluster(d)) { + enabled = read_gic_redir_mask(irq); write_gic_redir_map_vp(irq, 0); + write_gic_redir_rmask(irq); mips_cm_unlock_other(); } else { + enabled = read_gic_mask(irq); write_gic_map_vp(irq, 0); + write_gic_rmask(irq); } } @@ -412,10 +415,20 @@ static int gic_set_affinity(struct irq_data *d, const struct cpumask *cpumask, /* * If we're moving affinity between clusters, configure the interrupt - * trigger type in the new cluster. + * trigger type and, if it was enabled in the old cluster, enable it + * in the new one. */ - if (cl != old_cl) - gic_set_type(d, irqd_get_trigger_type(d)); + if (cl != old_cl) { + gic_set_type_locked(d, irqd_get_trigger_type(d)); + if (enabled) { + if (gic_irq_lock_cluster(d)) { + write_gic_redir_smask(irq); + mips_cm_unlock_other(); + } else { + write_gic_smask(irq); + } + } + } /* Route the interrupt to its new VP(E) */ if (gic_irq_lock_cluster(d)) { diff --git a/drivers/irqchip/irq-mst-intc.c b/drivers/irqchip/irq-mst-intc.c index b5335f6fd6d6..1070de5de8cc 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_obj(*cd); if (!cd) return -ENOMEM; diff --git a/drivers/irqchip/irq-riscv-imsic-state.c b/drivers/irqchip/irq-riscv-imsic-state.c index b8d1bbbf42f7..960c71d6295b 100644 --- a/drivers/irqchip/irq-riscv-imsic-state.c +++ b/drivers/irqchip/irq-riscv-imsic-state.c @@ -7,6 +7,7 @@ #define pr_fmt(fmt) "riscv-imsic: " fmt #include #include +#include #include #include #include @@ -739,6 +740,14 @@ static int __init imsic_parse_fwnode(struct fwnode_handle *fwnode, return -EINVAL; } + /* Group index bits must not overlap guest and HART index bits. */ + i = IMSIC_MMIO_PAGE_SHIFT + global->guest_index_bits + + global->hart_index_bits; + if (global->group_index_bits && global->group_index_shift < i) { + pr_err("%pfwP: group index shift too small\n", fwnode); + return -EINVAL; + } + /* Sanity check group index shift */ i = global->group_index_bits + global->group_index_shift - 1; if (i >= BITS_PER_LONG) { @@ -769,9 +778,9 @@ static int __init imsic_parse_fwnode(struct fwnode_handle *fwnode, return -EINVAL; } global->base_addr = res.start; - global->base_addr &= ~(BIT(global->guest_index_bits + - global->hart_index_bits + - IMSIC_MMIO_PAGE_SHIFT) - 1); + global->base_addr &= ~GENMASK(global->guest_index_bits + + global->hart_index_bits + + IMSIC_MMIO_PAGE_SHIFT - 1, 0); global->base_addr &= ~((BIT(global->group_index_bits) - 1) << global->group_index_shift); @@ -850,9 +859,9 @@ int __init imsic_setup_state(struct fwnode_handle *fwnode, void *opaque) } base_addr = mmios[i].start; - base_addr &= ~(BIT(global->guest_index_bits + - global->hart_index_bits + - IMSIC_MMIO_PAGE_SHIFT) - 1); + base_addr &= ~GENMASK(global->guest_index_bits + + global->hart_index_bits + + IMSIC_MMIO_PAGE_SHIFT - 1, 0); base_addr &= ~((BIT(global->group_index_bits) - 1) << global->group_index_shift); if (base_addr != global->base_addr) { diff --git a/drivers/irqchip/irq-sifive-plic.c b/drivers/irqchip/irq-sifive-plic.c index 5b0dac104814..d3d4187b96ab 100644 --- a/drivers/irqchip/irq-sifive-plic.c +++ b/drivers/irqchip/irq-sifive-plic.c @@ -108,7 +108,7 @@ static int plic_irq_set_type(struct irq_data *d, unsigned int type); static void __plic_toggle(struct plic_handler *handler, int hwirq, int enable) { u32 __iomem *base = handler->enable_base; - u32 hwirq_mask = 1 << (hwirq % 32); + u32 hwirq_mask = BIT(hwirq % 32); int group = hwirq / 32; u32 value; diff --git a/drivers/leds/led-class-flash.c b/drivers/leds/led-class-flash.c index 165035a8826c..3bb90823de1a 100644 --- a/drivers/leds/led-class-flash.c +++ b/drivers/leds/led-class-flash.c @@ -187,7 +187,7 @@ static ssize_t flash_fault_show(struct device *dev, { struct led_classdev *led_cdev = dev_get_drvdata(dev); struct led_classdev_flash *fled_cdev = lcdev_to_flcdev(led_cdev); - u32 fault, mask = 0x1; + u32 fault = 0, mask = 0x1; char *pbuf = buf; int i, ret, buf_len; diff --git a/drivers/leds/led-class.c b/drivers/leds/led-class.c index a51b0ed53886..39cc2f3ea63f 100644 --- a/drivers/leds/led-class.c +++ b/drivers/leds/led-class.c @@ -27,29 +27,19 @@ static LIST_HEAD(leds_lookup_list); static struct workqueue_struct *leds_wq; -static bool led_trigger_is_hw_controlled(struct led_classdev *led_cdev) -{ -#ifdef CONFIG_LEDS_TRIGGERS - guard(rwsem_read)(&led_cdev->trigger_lock); - return led_cdev->trigger && led_cdev->trigger->trigger_type; -#else - return false; -#endif -} - static ssize_t brightness_show(struct device *dev, struct device_attribute *attr, char *buf) { struct led_classdev *led_cdev = dev_get_drvdata(dev); unsigned int brightness; - if (led_trigger_is_hw_controlled(led_cdev)) - return -ENODATA; + scoped_guard(mutex, &led_cdev->led_access) { + if (led_trigger_is_hw_controlled(led_cdev)) + return -ENODATA; - mutex_lock(&led_cdev->led_access); - led_update_brightness(led_cdev); - brightness = led_cdev->brightness; - mutex_unlock(&led_cdev->led_access); + led_update_brightness(led_cdev); + brightness = led_cdev->brightness; + } return sysfs_emit(buf, "%u\n", brightness); } @@ -74,6 +64,9 @@ static ssize_t brightness_store(struct device *dev, if (state == LED_OFF) led_trigger_remove(led_cdev); + else + led_trigger_remove_hw_control(led_cdev); + led_set_brightness(led_cdev, state); ret = size; diff --git a/drivers/leds/led-triggers.c b/drivers/leds/led-triggers.c index b1223218bda1..804a04b326c4 100644 --- a/drivers/leds/led-triggers.c +++ b/drivers/leds/led-triggers.c @@ -7,9 +7,11 @@ * Author: Richard Purdie */ +#include #include #include #include +#include #include #include #include @@ -33,6 +35,23 @@ trigger_relevant(struct led_classdev *led_cdev, struct led_trigger *trig) return !trig->trigger_type || trig->trigger_type == led_cdev->trigger_type; } +static bool __led_trigger_is_hw_controlled(struct led_classdev *led_cdev) +{ + lockdep_assert_held(&led_cdev->trigger_lock); + + if (!led_cdev->trigger) + return false; + + return led_cdev->trigger->trigger_type; +} + +bool led_trigger_is_hw_controlled(struct led_classdev *led_cdev) +{ + guard(rwsem_read)(&led_cdev->trigger_lock); + return __led_trigger_is_hw_controlled(led_cdev); +} +EXPORT_SYMBOL_GPL(led_trigger_is_hw_controlled); + ssize_t led_trigger_write(struct file *filp, struct kobject *kobj, const struct bin_attribute *bin_attr, char *buf, loff_t pos, size_t count) @@ -268,6 +287,15 @@ void led_trigger_remove(struct led_classdev *led_cdev) } EXPORT_SYMBOL_GPL(led_trigger_remove); +void led_trigger_remove_hw_control(struct led_classdev *led_cdev) +{ + guard(rwsem_write)(&led_cdev->trigger_lock); + + if (__led_trigger_is_hw_controlled(led_cdev)) + led_trigger_set(led_cdev, NULL); +} +EXPORT_SYMBOL_GPL(led_trigger_remove_hw_control); + static bool led_match_default_trigger(struct led_classdev *led_cdev, struct led_trigger *trig) { diff --git a/drivers/leds/leds-lm3692x.c b/drivers/leds/leds-lm3692x.c index 8d2678dc9e4f..9c58d54c5783 100644 --- a/drivers/leds/leds-lm3692x.c +++ b/drivers/leds/leds-lm3692x.c @@ -276,9 +276,11 @@ static int lm3692x_leds_enable(struct lm3692x_led *led) ret = regmap_update_bits(led->regmap, LM3692X_EN, LM3692X_ENABLE_MASK, enable_state | LM3692X_DEVICE_EN); + if (ret) + goto out; led->enabled = true; - return ret; + return 0; out: dev_err(&led->client->dev, "Fail writing initialization values\n"); diff --git a/drivers/leds/leds-lp8860.c b/drivers/leds/leds-lp8860.c index 69f064781f69..f6e4227de903 100644 --- a/drivers/leds/leds-lp8860.c +++ b/drivers/leds/leds-lp8860.c @@ -7,6 +7,7 @@ * Author: Dan Murphy */ +#include #include #include #include @@ -274,7 +275,6 @@ static int lp8860_probe(struct i2c_client *client) int ret; struct lp8860_led *led; struct device_node *np = dev_of_node(&client->dev); - struct device_node *child_node; struct led_init_data init_data = {}; struct gpio_desc *enable_gpio; @@ -282,7 +282,8 @@ static int lp8860_probe(struct i2c_client *client) if (!led) return -ENOMEM; - child_node = of_get_next_available_child(np, NULL); + struct device_node *child_node __free(device_node) = + of_get_next_available_child(np, NULL); if (!child_node) return -EINVAL; diff --git a/drivers/leds/leds-max77705.c b/drivers/leds/leds-max77705.c index 1e2054c1bf80..4fd803c95989 100644 --- a/drivers/leds/leds-max77705.c +++ b/drivers/leds/leds-max77705.c @@ -160,7 +160,6 @@ static int max77705_add_led(struct device *dev, struct regmap *regmap, struct fw struct max77705_led *led; struct led_classdev *cdev; struct mc_subled *info; - struct fwnode_handle *child; struct led_init_data init_data = {}; led = devm_kzalloc(dev, sizeof(*led), GFP_KERNEL); @@ -191,7 +190,7 @@ static int max77705_add_led(struct device *dev, struct regmap *regmap, struct fw cdev->brightness_set_blocking = max77705_led_brightness_set_multi; cdev->blink_set = max77705_rgb_blink; - fwnode_for_each_child_node(np, child) { + fwnode_for_each_child_node_scoped(np, child) { ret = max77705_parse_subled(dev, child, &info[i]); if (ret < 0) return ret; diff --git a/drivers/leds/leds-pca9532.c b/drivers/leds/leds-pca9532.c index b2e081c8f139..1133fa348e24 100644 --- a/drivers/leds/leds-pca9532.c +++ b/drivers/leds/leds-pca9532.c @@ -298,12 +298,15 @@ static enum pca9532_state pca9532_getled(struct pca9532_led *led) struct i2c_client *client = led->client; struct pca9532_data *data = i2c_get_clientdata(client); u8 maxleds = data->chip_info->num_leds; - char reg; - enum pca9532_state ret; + int reg; + enum pca9532_state ret = PCA9532_OFF; mutex_lock(&data->update_lock); reg = i2c_smbus_read_byte_data(client, LED_REG(maxleds, led->id)); - ret = (reg & LED_MASK(led->id)) >> LED_SHIFT(led->id); + if (reg >= 0) + ret = (reg & LED_MASK(led->id)) >> LED_SHIFT(led->id); + else + dev_warn(&client->dev, "failed to read LED register: %d\n", reg); mutex_unlock(&data->update_lock); return ret; } diff --git a/drivers/leds/leds-st1202.c b/drivers/leds/leds-st1202.c index 168df5ecf27b..2d34f9d06f60 100644 --- a/drivers/leds/leds-st1202.c +++ b/drivers/leds/leds-st1202.c @@ -12,9 +12,11 @@ #include #include #include +#include #include #include +#define ST1202_BLINK_DEFAULT_DELAY 500 #define ST1202_CHAN_DISABLE_ALL 0x00 #define ST1202_CHAN_ENABLE_HIGH 0x03 #define ST1202_CHAN_ENABLE_LOW 0x02 @@ -23,7 +25,8 @@ #define ST1202_CONFIG_REG_PATS BIT(7) /* PATSR: Pattern sequence runs (self-clear when sequence is finished) */ #define ST1202_CONFIG_REG_PATSR BIT(6) -#define ST1202_CONFIG_REG_SHFT BIT(3) +/* SHFT: Phase-shift delay enable */ +#define ST1202_CONFIG_REG_PHASE_SHIFT BIT(3) #define ST1202_DEV_ENABLE 0x01 #define ST1202_DEV_ENABLE_ON BIT(0) #define ST1202_DEV_ENABLE_RESET BIT(7) @@ -89,6 +92,16 @@ static uint8_t st1202_prescalar_to_miliseconds(unsigned int value) return value / ST1202_MILLIS_PATTERN_DUR_MIN; } +static u16 st1202_brightness_to_pwm(int brightness, unsigned int max_brightness) +{ + if (!max_brightness) + return 0; + + brightness = clamp_t(int, brightness, LED_OFF, max_brightness); + + return brightness * ST1202_PATTERN_PWM_FULL / max_brightness; +} + static int st1202_pwm_pattern_write(struct st1202_chip *chip, int led_num, int pattern, unsigned int value) { @@ -160,27 +173,6 @@ static int __st1202_channel_set(struct st1202_chip *chip, int led_num, bool acti return 0; } -static int st1202_channel_set(struct st1202_chip *chip, int led_num, bool active) -{ - guard(mutex)(&chip->lock); - - return __st1202_channel_set(chip, led_num, active); -} - -static void st1202_brightness_set(struct led_classdev *led_cdev, - enum led_brightness value) -{ - struct st1202_led *led = cdev_to_st1202_led(led_cdev); - struct st1202_chip *chip = led->chip; - - guard(mutex)(&chip->lock); - - for (int patt = 0; patt < ST1202_MAX_PATTERNS; patt++) - st1202_pwm_pattern_write(chip, led->led_num, patt, ST1202_PATTERN_PWM_FULL); - st1202_write_reg(chip, ST1202_ILED_REG0 + led->led_num, value); - __st1202_channel_set(chip, led->led_num, !!value); -} - static enum led_brightness st1202_brightness_get(struct led_classdev *led_cdev) { struct st1202_led *led = cdev_to_st1202_led(led_cdev); @@ -197,8 +189,30 @@ static enum led_brightness st1202_brightness_get(struct led_classdev *led_cdev) static int st1202_led_set(struct led_classdev *ldev, enum led_brightness value) { struct st1202_led *led = cdev_to_st1202_led(ldev); + struct st1202_chip *chip = led->chip; + int ret; + + guard(mutex)(&chip->lock); + + /* + * The output of a channel is ILED x Pattern_PWM / 4095. Setting every + * PWM slot to full scale makes it equal ILED whatever the state of the + * sequencer, so the brightness takes effect without stopping the + * sequencer, which is global and would disturb the other channels. + */ + for (int pattern = 0; pattern < ST1202_MAX_PATTERNS; pattern++) { + ret = st1202_pwm_pattern_write(chip, led->led_num, pattern, + ST1202_PATTERN_PWM_FULL); + if (ret) + return ret; + } - return st1202_channel_set(led->chip, led->led_num, !!value); + ret = st1202_write_reg(chip, ST1202_ILED_REG0 + led->led_num, + min_t(unsigned int, value, U8_MAX)); + if (ret) + return ret; + + return __st1202_channel_set(chip, led->led_num, !!value); } static int st1202_led_pattern_clear(struct led_classdev *ldev) @@ -209,16 +223,25 @@ static int st1202_led_pattern_clear(struct led_classdev *ldev) guard(mutex)(&chip->lock); - ret = st1202_write_reg(chip, ST1202_CONFIG_REG, ST1202_CONFIG_REG_SHFT); + ret = st1202_write_reg(chip, ST1202_ILED_REG0 + led->led_num, LED_OFF); + if (ret != 0) + return ret; + + ret = __st1202_channel_set(chip, led->led_num, false); + if (ret != 0) + return ret; + + ret = st1202_write_reg(chip, ST1202_CONFIG_REG, ST1202_CONFIG_REG_PHASE_SHIFT); if (ret != 0) return ret; - for (int patt = 0; patt < ST1202_MAX_PATTERNS; patt++) { - ret = st1202_pwm_pattern_write(chip, led->led_num, patt, ST1202_PATTERN_PWM_FULL); + for (int pattern = 0; pattern < ST1202_MAX_PATTERNS; pattern++) { + ret = st1202_pwm_pattern_write(chip, led->led_num, pattern, + ST1202_PATTERN_PWM_FULL); if (ret != 0) return ret; - ret = st1202_write_reg(chip, ST1202_PATTERN_DUR + patt, 0); + ret = st1202_write_reg(chip, ST1202_PATTERN_DUR + pattern, 0); if (ret != 0) return ret; } @@ -227,34 +250,45 @@ static int st1202_led_pattern_clear(struct led_classdev *ldev) } static int st1202_led_pattern_set(struct led_classdev *ldev, - struct led_pattern *pattern, + struct led_pattern *patterns, u32 len, int repeat) { struct st1202_led *led = cdev_to_st1202_led(ldev); struct st1202_chip *chip = led->chip; + unsigned int max_brightness; int ret; + max_brightness = min_t(unsigned int, ldev->max_brightness, U8_MAX); + if (len > ST1202_MAX_PATTERNS) return -EINVAL; - for (int patt = 0; patt < len; patt++) { - if (pattern[patt].delta_t < ST1202_MILLIS_PATTERN_DUR_MIN || - pattern[patt].delta_t > ST1202_MILLIS_PATTERN_DUR_MAX) + for (int pattern = 0; pattern < len; pattern++) { + if (patterns[pattern].delta_t < ST1202_MILLIS_PATTERN_DUR_MIN || + patterns[pattern].delta_t > ST1202_MILLIS_PATTERN_DUR_MAX) return -EINVAL; } guard(mutex)(&chip->lock); - ret = st1202_write_reg(chip, ST1202_CONFIG_REG, ST1202_CONFIG_REG_SHFT); + ret = st1202_write_reg(chip, ST1202_CONFIG_REG, ST1202_CONFIG_REG_PHASE_SHIFT); if (ret != 0) return ret; - for (int patt = 0; patt < len; patt++) { - ret = st1202_pwm_pattern_write(chip, led->led_num, patt, pattern[patt].brightness); + for (int pattern = 0; pattern < len; pattern++) { + ret = st1202_pwm_pattern_write(chip, led->led_num, pattern, + st1202_brightness_to_pwm(patterns[pattern].brightness, + max_brightness)); if (ret != 0) return ret; - ret = st1202_duration_pattern_write(chip, patt, pattern[patt].delta_t); + ret = st1202_duration_pattern_write(chip, pattern, patterns[pattern].delta_t); + if (ret != 0) + return ret; + } + + for (int pattern = len; pattern < ST1202_MAX_PATTERNS; pattern++) { + ret = st1202_pwm_pattern_write(chip, led->led_num, pattern, LED_OFF); if (ret != 0) return ret; } @@ -263,18 +297,118 @@ static int st1202_led_pattern_set(struct led_classdev *ldev, if (ret != 0) return ret; + ret = st1202_write_reg(chip, ST1202_ILED_REG0 + led->led_num, max_brightness); + if (ret != 0) + return ret; + ret = __st1202_channel_set(chip, led->led_num, true); if (ret != 0) return ret; - ret = st1202_write_reg(chip, ST1202_CONFIG_REG, (ST1202_CONFIG_REG_PATSR | - ST1202_CONFIG_REG_PATS | ST1202_CONFIG_REG_SHFT)); + ret = st1202_write_reg(chip, ST1202_CONFIG_REG, + ST1202_CONFIG_REG_PATSR | ST1202_CONFIG_REG_PATS | + ST1202_CONFIG_REG_PHASE_SHIFT); if (ret != 0) return ret; return 0; } +static int st1202_blink_set(struct led_classdev *led_cdev, + unsigned long *delay_on, unsigned long *delay_off) +{ + struct st1202_led *led = cdev_to_st1202_led(led_cdev); + struct st1202_chip *chip = led->chip; + unsigned long on, off; + int ret; + + if (!*delay_on) + *delay_on = ST1202_BLINK_DEFAULT_DELAY; + if (!*delay_off) + *delay_off = ST1202_BLINK_DEFAULT_DELAY; + + on = *delay_on; + off = *delay_off; + + on = clamp_val(on, ST1202_MILLIS_PATTERN_DUR_MIN, ST1202_MILLIS_PATTERN_DUR_MAX); + off = clamp_val(off, ST1202_MILLIS_PATTERN_DUR_MIN, ST1202_MILLIS_PATTERN_DUR_MAX); + on = roundup(on, ST1202_MILLIS_PATTERN_DUR_MIN); + off = roundup(off, ST1202_MILLIS_PATTERN_DUR_MIN); + + guard(mutex)(&chip->lock); + + ret = st1202_write_reg(chip, ST1202_CONFIG_REG, ST1202_CONFIG_REG_PHASE_SHIFT); + if (ret) + return ret; + + /* Zero out PWM for all other active channels to prevent them from blinking */ + for (int chan = 0; chan < ST1202_MAX_LEDS; chan++) { + if (!chip->leds[chan].is_active || chan == led->led_num) + continue; + + ret = st1202_pwm_pattern_write(chip, chan, 0, LED_OFF); + if (ret) + return ret; + + ret = st1202_pwm_pattern_write(chip, chan, 1, LED_OFF); + if (ret) + return ret; + } + + ret = st1202_pwm_pattern_write(chip, led->led_num, 0, ST1202_PATTERN_PWM_FULL); + if (ret) + return ret; + + for (int pattern = 1; pattern < ST1202_MAX_PATTERNS; pattern++) { + ret = st1202_pwm_pattern_write(chip, led->led_num, pattern, LED_OFF); + if (ret) + return ret; + } + + ret = st1202_duration_pattern_write(chip, 0, on); + if (ret) + return ret; + + ret = st1202_duration_pattern_write(chip, 1, off); + if (ret) + return ret; + + for (int pattern = 2; pattern < ST1202_MAX_PATTERNS; pattern++) { + ret = st1202_write_reg(chip, ST1202_PATTERN_DUR + pattern, 0); + if (ret) + return ret; + } + + ret = st1202_write_reg(chip, ST1202_PATTERN_REP, U8_MAX); + if (ret) + return ret; + + ret = st1202_write_reg(chip, ST1202_ILED_REG0 + led->led_num, + min_t(unsigned int, led_cdev->max_brightness, U8_MAX)); + if (ret) + return ret; + + ret = __st1202_channel_set(chip, led->led_num, true); + if (ret) + return ret; + + ret = st1202_write_reg(chip, ST1202_CONFIG_REG, + ST1202_CONFIG_REG_PATSR | ST1202_CONFIG_REG_PATS | + ST1202_CONFIG_REG_PHASE_SHIFT); + if (ret) + return ret; + + *delay_on = on; + *delay_off = off; + + return 0; +} + +static void st1202_fwnode_put(void *data) +{ + fwnode_handle_put(data); +} + static int st1202_dt_init(struct st1202_chip *chip) { struct device *dev = &chip->client->dev; @@ -294,14 +428,18 @@ static int st1202_dt_init(struct st1202_chip *chip) led = &chip->leds[reg]; led->is_active = true; - led->fwnode = of_fwnode_handle(child); + led->fwnode = fwnode_handle_get(of_fwnode_handle(child)); + + err = devm_add_action_or_reset(dev, st1202_fwnode_put, led->fwnode); + if (err) + return err; led->led_cdev.max_brightness = U8_MAX; led->led_cdev.brightness_set_blocking = st1202_led_set; led->led_cdev.pattern_set = st1202_led_pattern_set; led->led_cdev.pattern_clear = st1202_led_pattern_clear; led->led_cdev.default_trigger = "pattern"; - led->led_cdev.brightness_set = st1202_brightness_set; + led->led_cdev.blink_set = st1202_blink_set; led->led_cdev.brightness_get = st1202_brightness_get; } @@ -330,7 +468,7 @@ static int st1202_setup(struct st1202_chip *chip) return ret; /* Enable phase-shift delay feature */ - ret = st1202_write_reg(chip, ST1202_CONFIG_REG, ST1202_CONFIG_REG_SHFT); + ret = st1202_write_reg(chip, ST1202_CONFIG_REG, ST1202_CONFIG_REG_PHASE_SHIFT); if (ret < 0) return ret; @@ -342,7 +480,7 @@ static int st1202_setup(struct st1202_chip *chip) /* Duration of initialization */ usleep_range(6500, 10000); - /* Deactivate all LEDS (channels) and activate only the ones found in Device Tree */ + /* Deactivate all LEDs (channels); each is enabled when it is lit */ ret = st1202_write_reg(chip, ST1202_CHAN_ENABLE_LOW, ST1202_CHAN_DISABLE_ALL); if (ret < 0) return ret; @@ -389,11 +527,6 @@ static int st1202_probe(struct i2c_client *client) if (!led->is_active) continue; - ret = st1202_channel_set(led->chip, led->led_num, true); - if (ret < 0) - return dev_err_probe(&client->dev, ret, - "Failed to activate LED channel\n"); - ret = st1202_led_pattern_clear(&led->led_cdev); if (ret < 0) return dev_err_probe(&client->dev, ret, diff --git a/drivers/mailbox/arm_mhu_db.c b/drivers/mailbox/arm_mhu_db.c index a39239e38a47..9f1c7bcfdcb4 100644 --- a/drivers/mailbox/arm_mhu_db.c +++ b/drivers/mailbox/arm_mhu_db.c @@ -317,10 +317,8 @@ static int mhu_db_probe(struct amba_device *adev, const struct amba_id *id) err = devm_request_threaded_irq(dev, irq, NULL, mhu_db_mbox_rx_handler, IRQF_ONESHOT, "mhu_db_link", mhu); - if (err) { - mbox_controller_unregister(&mhu->mbox); + if (err) return err; - } } dev_info(dev, "ARM MHU Doorbell mailbox registered\n"); diff --git a/drivers/mailbox/arm_mhuv2.c b/drivers/mailbox/arm_mhuv2.c index d4077cd49360..0520d4996634 100644 --- a/drivers/mailbox/arm_mhuv2.c +++ b/drivers/mailbox/arm_mhuv2.c @@ -27,6 +27,7 @@ #include #include +#include #include #include #include @@ -967,6 +968,7 @@ static int mhuv2_tx_init(struct amba_device *adev, struct mhuv2 *mhu, { struct device *dev = mhu->mbox.dev; int ret, i; + u32 val; mhu->frame = SENDER_FRAME; mhu->mbox.ops = &mhuv2_sender_ops; @@ -1007,8 +1009,11 @@ static int mhuv2_tx_init(struct amba_device *adev, struct mhuv2 *mhu, out: /* Wait for receiver to be ready */ writel_relaxed(0x1, &mhu->send->access_request); - while (!readl_relaxed(&mhu->send->access_ready)) - continue; + if (readl_relaxed_poll_timeout(&mhu->send->access_ready, val, val, + 100, 1000000)) { + dev_err(dev, "receiver not ready\n"); + return -ETIMEDOUT; + } return 0; } diff --git a/drivers/mailbox/axiado-mailbox.c b/drivers/mailbox/axiado-mailbox.c index 3a3cf7421863..a87693c639dc 100644 --- a/drivers/mailbox/axiado-mailbox.c +++ b/drivers/mailbox/axiado-mailbox.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -36,6 +37,12 @@ #define AXIADO_MBOX_CSR_ERRORS (AXIADO_MBOX_CSR_OVERFLOW | \ AXIADO_MBOX_CSR_UNDERFLOW) +enum axiado_mbox_frame_result { + AXIADO_MBOX_FRAME_EMPTY, + AXIADO_MBOX_FRAME_OK, + AXIADO_MBOX_FRAME_BAD, /* malformed/incomplete; FIFO flushed */ +}; + struct axiado_mbox_data { u8 num_chans; u16 msg_size; @@ -116,6 +123,13 @@ static int axiado_mbox_send_data(struct mbox_chan *chan, void *data) return -EBUSY; } + /* + * Per-word get_unaligned_le32()/writel(), not writesl(): @data is + * supplied by whatever client calls mbox_send_message(), and + * mbox_chan_ops.send_data(void *data) makes no alignment guarantee + * for that buffer. writesl() dereferences it as a native u32 *, + * which is unsafe unless alignment is known. + */ for (offset = 0; offset + sizeof(u32) <= msg_len; offset += sizeof(u32)) writel(get_unaligned_le32(buf + offset), priv->mbox_reg); @@ -131,31 +145,42 @@ static int axiado_mbox_send_data(struct mbox_chan *chan, void *data) return 0; } -static irqreturn_t axiado_rx_thread(int irq, void *dev_id) +/* + * Read and, if valid, deliver exactly one length-prefixed frame currently + * at the head of the RX FIFO. Does not loop -- the caller decides whether + * to call this again. May clear a pending FIFO error at several points + * below, wherever a new one could plausibly have appeared since the last + * check; each check is a cheap readl() when nothing is pending. + */ +static enum axiado_mbox_frame_result axiado_mbox_receive_one_frame(struct axiado_channel_data *priv, + bool *serviced) { - struct axiado_channel_data *priv = dev_id; struct mbox_chan *chan = priv->chan; struct axiado_mbox *mb = dev_get_drvdata(chan->mbox->dev); u8 *buf = priv->rx_buffer; unsigned int num_words; unsigned int remaining; - unsigned int i; u32 msg_len; u32 word; u32 csr; int ret; /* - * Clear and log/count any pending errors, but don't discard data - * on their account alone: a rejected overflow write doesn't - * corrupt what was already safely queued ahead of it, so let the - * length-based read below decide whether what's here is usable. + * Don't discard data on a cleared error's account alone: a rejected + * overflow write doesn't corrupt what was already safely queued + * ahead of it, so let the length-based read below decide whether + * what's here is usable. Count clearing a real error as @serviced + * so the handler reports IRQ_HANDLED whenever it actually handled + * a hardware condition. */ - axiado_mbox_clear_fifo_errors(priv); + if (axiado_mbox_clear_fifo_errors(priv)) + *serviced = true; csr = readl(priv->csr_reg); if (csr & AXIADO_MBOX_CSR_EMPTY) - return IRQ_NONE; + return AXIADO_MBOX_FRAME_EMPTY; + + *serviced = true; /* * The first word contains the total message length in bytes, @@ -165,8 +190,12 @@ static irqreturn_t axiado_rx_thread(int irq, void *dev_id) msg_len = word; put_unaligned_le32(word, buf); - if (msg_len < sizeof(u32) || msg_len > mb->drv_data->msg_size) - goto invalid_message; + if (msg_len < sizeof(u32) || msg_len > mb->drv_data->msg_size) { + dev_warn_ratelimited(chan->mbox->dev, + "Channel %u invalid frame length %u (max %u)\n", + priv->channel_num, msg_len, mb->drv_data->msg_size); + goto bad_frame; + } num_words = DIV_ROUND_UP(msg_len, sizeof(u32)); remaining = num_words - 1; @@ -182,33 +211,68 @@ static irqreturn_t axiado_rx_thread(int irq, void *dev_id) remaining, AXIADO_MBOX_RX_POLL_US, AXIADO_MBOX_RX_TIMEOUT_US); - if (ret) - goto incomplete_message; + /* + * The wait condition above is satisfied by EITHER the + * expected word count landing OR a FIFO error appearing. + * ret == 0 only means "didn't time out" - it does not mean + * the words are actually there. Check @csr for the error + * bit explicitly; otherwise an underflow can present as + * "success" and the read loop below pulls words that were + * never pushed, handing the client garbage. + */ + if (ret || (csr & AXIADO_MBOX_CSR_ERRORS)) { + dev_warn_ratelimited(chan->mbox->dev, + "Channel %u incomplete frame: got %lu/%u words (%s)\n", + priv->channel_num, + FIELD_GET(AXIADO_MBOX_CSR_LEVEL, csr), + num_words, + (csr & AXIADO_MBOX_CSR_ERRORS) ? + "FIFO error" : "timed out"); + goto bad_frame; + } axiado_mbox_clear_fifo_errors(priv); } - for (i = 1; i < num_words; i++) { - word = readl(priv->mbox_reg); - put_unaligned_le32(word, buf + i * sizeof(u32)); - } + /* + * readsl() streams the payload words directly into rx_buffer, which + * is allocated by this driver via devm_kzalloc() and therefore has + * suitable alignment for a stream accessor. + */ + readsl(priv->mbox_reg, buf + sizeof(u32), remaining); axiado_mbox_clear_fifo_errors(priv); if (READ_ONCE(priv->active)) mbox_chan_received_data(chan, priv->rx_buffer); - return IRQ_HANDLED; + return AXIADO_MBOX_FRAME_OK; -incomplete_message: - dev_warn_ratelimited(chan->mbox->dev, - "Channel %u received an incomplete message\n", - priv->channel_num); - -invalid_message: +bad_frame: + axiado_mbox_clear_fifo_errors(priv); writel(AXIADO_MBOX_CSR_FLUSH, priv->csr_reg); - return IRQ_HANDLED; + return AXIADO_MBOX_FRAME_BAD; +} + +static irqreturn_t axiado_rx_thread(int irq, void *dev_id) +{ + struct axiado_channel_data *priv = dev_id; + enum axiado_mbox_frame_result result; + bool handled = false; + + /* + * Drain all frames currently queued in the FIFO before returning. + * Multiple frames may accumulate while the threaded handler is + * running. cond_resched() prevents a continuously-fed channel from + * monopolizing the CPU. + */ + do { + result = axiado_mbox_receive_one_frame(priv, &handled); + cond_resched(); + } while (result == AXIADO_MBOX_FRAME_OK); + + return handled ? IRQ_HANDLED : IRQ_NONE; } static int axiado_mbox_startup(struct mbox_chan *chan) @@ -315,7 +379,7 @@ static int axiado_mbox_probe(struct platform_device *pdev) return ret; for (i = 0; i < drv_data->num_chans; i++) { - char name[16]; + char name[32]; ch_data[i].channel_num = i; ch_data[i].chan = &mb->mbox.chans[i]; diff --git a/drivers/mailbox/pcc.c b/drivers/mailbox/pcc.c index 9888dab64639..db30812c5051 100644 --- a/drivers/mailbox/pcc.c +++ b/drivers/mailbox/pcc.c @@ -438,12 +438,13 @@ void pcc_mbox_free_channel(struct pcc_mbox_chan *pchan) return; pchan_info = chan->con_priv; pcc_mbox_chan = &pchan_info->chan; + + mbox_free_channel(chan); + if (pcc_mbox_chan->shmem) { iounmap(pcc_mbox_chan->shmem); pcc_mbox_chan->shmem = NULL; } - - mbox_free_channel(chan); } EXPORT_SYMBOL_GPL(pcc_mbox_free_channel); diff --git a/drivers/mailbox/qcom-cpucp-mbox.c b/drivers/mailbox/qcom-cpucp-mbox.c index 515d2d12c01b..b88ea2527265 100644 --- a/drivers/mailbox/qcom-cpucp-mbox.c +++ b/drivers/mailbox/qcom-cpucp-mbox.c @@ -61,7 +61,7 @@ static irqreturn_t qcom_cpucp_mbox_irq_fn(int irq, void *data) status = readq(cpucp->rx_base + APSS_CPUCP_RX_MBOX_STAT); for_each_set_bit(i, (unsigned long *)&status, cpucp->mbox.num_chans) { - u32 val = readl(cpucp->rx_base + APSS_CPUCP_RX_MBOX_CMD(i) + APSS_CPUCP_MBOX_CMD_OFF); + u64 val = readq(cpucp->rx_base + APSS_CPUCP_RX_MBOX_CMD(i)); struct mbox_chan *chan = &cpucp->chans[i]; struct mbox_client *cl; unsigned long flags; diff --git a/drivers/mailbox/qcom-ipcc.c b/drivers/mailbox/qcom-ipcc.c index 387aa72aeedf..c1dec33290a7 100644 --- a/drivers/mailbox/qcom-ipcc.c +++ b/drivers/mailbox/qcom-ipcc.c @@ -335,15 +335,12 @@ static int qcom_ipcc_probe(struct platform_device *pdev) IRQF_TRIGGER_HIGH | IRQF_NO_SUSPEND | IRQF_NO_THREAD, name, ipcc); if (ret < 0) - goto err_req_irq; + goto err_mbox; platform_set_drvdata(pdev, ipcc); return 0; -err_req_irq: - if (ipcc->num_chans) - mbox_controller_unregister(&ipcc->mbox); err_mbox: irq_domain_remove(ipcc->irq_domain); @@ -354,7 +351,6 @@ static void qcom_ipcc_remove(struct platform_device *pdev) { struct qcom_ipcc *ipcc = platform_get_drvdata(pdev); - disable_irq_wake(ipcc->irq); irq_domain_remove(ipcc->irq_domain); } diff --git a/drivers/mailbox/ti-msgmgr.c b/drivers/mailbox/ti-msgmgr.c index 8eb8df8d95a4..fb3f7e41ac36 100644 --- a/drivers/mailbox/ti-msgmgr.c +++ b/drivers/mailbox/ti-msgmgr.c @@ -20,6 +20,7 @@ #include #include #include +#include #define Q_DATA_OFFSET(proxy, queue, reg) \ ((0x10000 * (proxy)) + (0x80 * (queue)) + ((reg) * 4)) @@ -425,10 +426,15 @@ static int ti_msgmgr_send_data(struct mbox_chan *chan, void *data) trail_bytes = message->len % sizeof(u32); if (trail_bytes) { - u32 data_trail = *word_data; - - /* Ensure all unused data is 0 */ - data_trail &= 0xFFFFFFFF >> (8 * (sizeof(u32) - trail_bytes)); + /* + * Copy only the trailing bytes instead of reading a full u32, + * as the message buffer may end right after them and a u32 + * read would go past the end of it. This also leaves all + * unused data as 0. + */ + u32 data_trail = 0; + + memcpy(&data_trail, word_data, trail_bytes); writel(data_trail, data_reg); data_reg += sizeof(u32); } diff --git a/drivers/md/dm-snap.c b/drivers/md/dm-snap.c index 7c3725e4ac54..797c432594d8 100644 --- a/drivers/md/dm-snap.c +++ b/drivers/md/dm-snap.c @@ -766,7 +766,7 @@ static void dm_insert_exception(struct dm_exception_table *eh, struct dm_exception *new_e) { struct hlist_head *l; - struct dm_exception *e = NULL; + struct dm_exception *e = NULL, *prev = NULL; l = &eh->table[exception_hash(eh, new_e->old_chunk)].head; @@ -798,21 +798,23 @@ static void dm_insert_exception(struct dm_exception_table *eh, if (new_e->old_chunk < e->old_chunk) break; + + prev = e; } out: - if (!e) { + if (e && new_e->old_chunk < e->old_chunk) { + /* Add before an existing exception */ + hlist_add_before(&new_e->hash_list, &e->hash_list); + } else if (prev) { + /* Add to l's tail: prev is the last exception in this slot */ + hlist_add_behind(&new_e->hash_list, &prev->hash_list); + } else { /* * Either the table doesn't support consecutive chunks or slot * l is empty. */ hlist_add_head(&new_e->hash_list, l); - } else if (new_e->old_chunk < e->old_chunk) { - /* Add before an existing exception */ - hlist_add_before(&new_e->hash_list, &e->hash_list); - } else { - /* Add to l's tail: e is the last exception in this slot */ - hlist_add_behind(&new_e->hash_list, &e->hash_list); } } diff --git a/drivers/md/md.c b/drivers/md/md.c index d8ecf76d4a5f..782123383605 100644 --- a/drivers/md/md.c +++ b/drivers/md/md.c @@ -414,6 +414,20 @@ bool md_handle_request(struct mddev *mddev, struct bio *bio) if (!percpu_ref_tryget_live(&mddev->active_io)) goto check_suspended; } + if (!mddev->pers) { + /* + * The __md_stop() sets 'mddev->private' to NULL during + * the IO submitting, check 'mddev->pers' before the IO + * being processed by specific driver to avoid the + * null-ptr-deref of 'mddev->'. The check is + * safe because the IO has got the 'mddev->active_io' + * reference, and all __md_stop() callers will wait for + * the reference to be zero. + */ + bio_io_error(bio); + percpu_ref_put(&mddev->active_io); + return true; + } if (!mddev->pers->make_request(mddev, bio)) { percpu_ref_put(&mddev->active_io); if (mddev_is_dm(mddev) && mddev->pers->prepare_suspend) @@ -1393,7 +1407,7 @@ static int super_90_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor goto abort; } - if (sb->raid_disks <= 0) + if (sb->raid_disks <= 0 || sb->raid_disks > MD_SB_DISKS) goto abort; if (md_csum_fold(calc_sb_csum(sb)) != md_csum_fold(sb->sb_csum)) { @@ -4673,7 +4687,8 @@ array_state_store(struct mddev *mddev, const char *buf, size_t len) case readonly: case inactive: case read_auto: - if (!mddev->pers || !md_is_rdwr(mddev)) + if (!mddev->pers || + (st != clear && st != inactive && !md_is_rdwr(mddev))) break; /* write sysfs will not open mddev and opener should be 0 */ err = mddev_set_closing_and_sync_blockdev(mddev, 0); @@ -5887,7 +5902,15 @@ consistency_policy_store(struct mddev *mddev, const char *buf, size_t len) else err = -EBUSY; } else if (mddev->external && strncmp(buf, "ppl", 3) == 0) { - set_bit(MD_HAS_PPL, &mddev->flags); + /* md_run() holds the lock until ->pers is set */ + err = mddev_lock(mddev); + if (err) + return err; + if (mddev->pers) + err = -EBUSY; + else + set_bit(MD_HAS_PPL, &mddev->flags); + mddev_unlock(mddev); } else { err = -EINVAL; } @@ -6051,11 +6074,10 @@ lbs_store(struct mddev *mddev, const char *buf, size_t len) err = mddev_lock(mddev); if (err) - goto unlock; + return err; err = mddev_set_logical_block_size(mddev, lbs); -unlock: mddev_unlock(mddev); return err ?: len; } @@ -8312,6 +8334,7 @@ static bool md_ioctl_need_suspend(unsigned int cmd) case HOT_REMOVE_DISK: case SET_BITMAP_FILE: case SET_ARRAY_INFO: + case STOP_ARRAY: return true; default: return false; diff --git a/drivers/md/raid0.c b/drivers/md/raid0.c index 35e103f0c2c3..453e8abda22b 100644 --- a/drivers/md/raid0.c +++ b/drivers/md/raid0.c @@ -79,7 +79,10 @@ static int create_strip_zones(struct mddev *mddev, struct r0conf **private_conf) *private_conf = ERR_PTR(-ENOMEM); if (!conf) return -ENOMEM; + + cnt = 0; rdev_for_each(rdev1, mddev) { + cnt++; pr_debug("md/raid0:%s: looking at %pg\n", mdname(mddev), rdev1->bdev); @@ -144,6 +147,14 @@ static int create_strip_zones(struct mddev *mddev, struct r0conf **private_conf) } err = -ENOMEM; + + if (cnt != mddev->raid_disks) { + pr_warn("md/raid0:%s: too few disks (%d of %d) - aborting!\n", + mdname(mddev), cnt, mddev->raid_disks); + err = -EINVAL; + goto abort; + } + conf->strip_zone = kvzalloc_objs(struct strip_zone, conf->nr_strip_zones); if (!conf->strip_zone) goto abort; @@ -200,11 +211,6 @@ static int create_strip_zones(struct mddev *mddev, struct r0conf **private_conf) smallest = rdev1; cnt++; } - if (cnt != mddev->raid_disks) { - pr_warn("md/raid0:%s: too few disks (%d of %d) - aborting!\n", - mdname(mddev), cnt, mddev->raid_disks); - goto abort; - } zone->nb_dev = cnt; zone->zone_end = smallest->sectors * cnt; diff --git a/drivers/md/raid10.c b/drivers/md/raid10.c index 1093c798d9dd..186e17e0a635 100644 --- a/drivers/md/raid10.c +++ b/drivers/md/raid10.c @@ -1010,7 +1010,8 @@ static bool wait_barrier_nolock(struct r10conf *conf) if (!read_seqretry(&conf->resync_lock, seq)) return true; - if (atomic_dec_and_test(&conf->nr_pending)) + if (atomic_dec_and_test(&conf->nr_pending) || + READ_ONCE(conf->array_freeze_pending)) wake_up_barrier(conf); return false; diff --git a/drivers/md/raid5-cache.c b/drivers/md/raid5-cache.c index 62460e231f02..7d5427f063f2 100644 --- a/drivers/md/raid5-cache.c +++ b/drivers/md/raid5-cache.c @@ -2970,7 +2970,9 @@ bool r5c_big_stripe_cached(struct r5conf *conf, sector_t sect) return false; tree_index = r5c_tree_index(conf, sect); + rcu_read_lock(); slot = radix_tree_lookup(&log->big_stripe_tree, tree_index); + rcu_read_unlock(); return slot != NULL; } @@ -3084,6 +3086,7 @@ int r5l_init_log(struct r5conf *conf, struct md_rdev *rdev) { struct r5l_log *log; struct md_thread *thread; + char cache_name[48]; int ret; pr_debug("md/raid:%s: using device %pg as journal\n", @@ -3123,7 +3126,16 @@ int r5l_init_log(struct r5conf *conf, struct md_rdev *rdev) INIT_LIST_HEAD(&log->flushing_ios); INIT_LIST_HEAD(&log->finished_ios); - log->io_kc = KMEM_CACHE(r5l_io_unit, 0); + if (mddev_is_dm(conf->mddev)) + snprintf(cache_name, sizeof(cache_name), "r5l_io_unit-%p", + conf->mddev); + else + snprintf(cache_name, sizeof(cache_name), "r5l_io_unit-%s", + mdname(conf->mddev)); + + log->io_kc = kmem_cache_create(cache_name, sizeof(struct r5l_io_unit), + __alignof__(struct r5l_io_unit), + 0, NULL); if (!log->io_kc) goto io_kc; diff --git a/drivers/md/raid5-ppl.c b/drivers/md/raid5-ppl.c index 7f8a9d3fd578..0530632f9d2a 100644 --- a/drivers/md/raid5-ppl.c +++ b/drivers/md/raid5-ppl.c @@ -1318,6 +1318,7 @@ int ppl_init_log(struct r5conf *conf) { struct ppl_conf *ppl_conf; struct mddev *mddev = conf->mddev; + char cache_name[48]; int ret = 0; int max_disks; int i; @@ -1360,7 +1361,16 @@ int ppl_init_log(struct r5conf *conf) ppl_conf->mddev = mddev; - ppl_conf->io_kc = KMEM_CACHE(ppl_io_unit, 0); + if (mddev_is_dm(mddev)) + snprintf(cache_name, sizeof(cache_name), "ppl_io_unit-%p", mddev); + else + snprintf(cache_name, sizeof(cache_name), "ppl_io_unit-%s", + mdname(mddev)); + + ppl_conf->io_kc = kmem_cache_create(cache_name, + sizeof(struct ppl_io_unit), + __alignof__(struct ppl_io_unit), + 0, NULL); if (!ppl_conf->io_kc) { ret = -ENOMEM; goto err; diff --git a/drivers/md/raid5.c b/drivers/md/raid5.c index bc5f4b048eed..05f1b17491ad 100644 --- a/drivers/md/raid5.c +++ b/drivers/md/raid5.c @@ -2713,6 +2713,37 @@ static int drop_one_stripe(struct r5conf *conf) static void shrink_stripes(struct r5conf *conf) { + struct list_head temp[NR_STRIPE_HASH_LOCKS]; + int i; + + /* + * grow_one_stripe() parks new stripes on released_stripes when + * mddev->thread is already set. Takeover leaves the previous + * personality's thread there, so raid5d never moves them to + * inactive_list. Drain them before the cache is destroyed. + * slab_cache is assigned only after device_lock and the hash + * lists exist; earlier abort paths have nothing to drain. + */ + if (conf->slab_cache) { + for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++) + INIT_LIST_HEAD(&temp[i]); + + spin_lock_irq(&conf->device_lock); + release_stripe_list(conf, temp); + spin_unlock_irq(&conf->device_lock); + + for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++) { + if (list_empty(&temp[i])) + continue; + spin_lock_irq(conf->hash_locks + i); + if (list_empty(conf->inactive_list + i)) + atomic_dec(&conf->empty_inactive_list_nr); + list_splice_tail_init(&temp[i], + conf->inactive_list + i); + spin_unlock_irq(conf->hash_locks + i); + } + } + while (conf->max_nr_stripes && drop_one_stripe(conf)) ; @@ -7659,9 +7690,11 @@ static struct r5conf *setup_conf(struct mddev *mddev) mdname(mddev), mddev->new_layout); return ERR_PTR(-EIO); } - if (mddev->new_level == 6 && mddev->raid_disks < 4) { - pr_warn("md/raid:%s: not enough configured devices (%d, minimum 4)\n", - mdname(mddev), mddev->raid_disks); + if ((mddev->new_level != 6 && mddev->raid_disks < 2) || + (mddev->new_level == 6 && mddev->raid_disks < 4)) { + pr_warn("md/raid:%s: not enough configured devices (%d, minimum %d)\n", + mdname(mddev), mddev->raid_disks, + mddev->new_level == 6 ? 4 : 2); return ERR_PTR(-EINVAL); } @@ -7677,6 +7710,7 @@ static struct r5conf *setup_conf(struct mddev *mddev) if (conf == NULL) goto abort; + conf->mddev = mddev; #if PAGE_SIZE != DEFAULT_STRIPE_SIZE conf->stripe_size = DEFAULT_STRIPE_SIZE; conf->stripe_shift = ilog2(DEFAULT_STRIPE_SIZE) - 9; @@ -7745,7 +7779,6 @@ static struct r5conf *setup_conf(struct mddev *mddev) ret = bioset_init(&conf->bio_split, BIO_POOL_SIZE, 0, 0); if (ret) goto abort; - conf->mddev = mddev; ret = -ENOMEM; conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL); @@ -8112,11 +8145,17 @@ static int raid5_run(struct mddev *mddev) } pr_debug("md/raid:%s: reshape will continue\n", mdname(mddev)); /* OK, we should be able to continue; */ - } else { - BUG_ON(mddev->level != mddev->new_level); - BUG_ON(mddev->layout != mddev->new_layout); - BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors); - BUG_ON(mddev->delta_disks != 0); + } else if (mddev->level != mddev->new_level || + mddev->layout != mddev->new_layout || + mddev->chunk_sectors != mddev->new_chunk_sectors || + mddev->delta_disks != 0) { + /* No reshape is in progress, but the array describes one. + * The superblock validators do not cross-check these against + * reshape_position, so this is reachable from disk. + */ + pr_warn("md/raid:%s: inconsistent reshape state - aborting.\n", + mdname(mddev)); + return -EINVAL; } if (test_bit(MD_HAS_JOURNAL, &mddev->flags) && @@ -8205,6 +8244,12 @@ static int raid5_run(struct mddev *mddev) /* device size must be a multiple of chunk size */ mddev->dev_sectors &= ~((sector_t)mddev->chunk_sectors - 1); + if (!mddev->dev_sectors) { + pr_warn("md/raid:%s: device size is smaller than one chunk\n", + mdname(mddev)); + ret = -EINVAL; + goto abort; + } mddev->resync_max_sectors = mddev->dev_sectors; if (mddev->degraded > dirty_parity_disks && @@ -8538,6 +8583,8 @@ static int raid5_resize(struct mddev *mddev, sector_t sectors) if (raid5_has_log(conf) || raid5_has_ppl(conf)) return -EINVAL; sectors &= ~((sector_t)conf->chunk_sectors - 1); + if (!sectors) + return -EINVAL; newsize = raid5_size(mddev, sectors, mddev->raid_disks); if (mddev->external_size && mddev->array_sectors > newsize) diff --git a/drivers/media/i2c/ar0521.c b/drivers/media/i2c/ar0521.c index ed324c2d87aa..be68789eb8f5 100644 --- a/drivers/media/i2c/ar0521.c +++ b/drivers/media/i2c/ar0521.c @@ -1142,7 +1142,6 @@ static int ar0521_probe(struct i2c_client *client) disable: v4l2_async_unregister_subdev(&sensor->sd); - media_entity_cleanup(&sensor->sd.entity); free_ctrls: v4l2_ctrl_handler_free(&sensor->ctrls.handler); entity_cleanup: diff --git a/drivers/media/i2c/imx471.c b/drivers/media/i2c/imx471.c index 4053aed84340..b442b083286d 100644 --- a/drivers/media/i2c/imx471.c +++ b/drivers/media/i2c/imx471.c @@ -46,7 +46,7 @@ #define IMX471_ANA_GAIN_DEFAULT 0 /* Digital gain control */ -#define IMX471_REG_DPGA_USE_GLOBAL_GAIN CCI_REG16(0x3ff9) +#define IMX471_REG_DPGA_USE_GLOBAL_GAIN CCI_REG8(0x3ff9) #define IMX471_REG_DIG_GAIN_GLOBAL CCI_REG16(0x020e) #define IMX471_DGTL_GAIN_MIN 256 #define IMX471_DGTL_GAIN_MAX 4095 diff --git a/drivers/media/i2c/ov5648.c b/drivers/media/i2c/ov5648.c index f0b839cd65f1..006aeb93482b 100644 --- a/drivers/media/i2c/ov5648.c +++ b/drivers/media/i2c/ov5648.c @@ -2145,13 +2145,13 @@ static int ov5648_s_stream(struct v4l2_subdev *subdev, int enable) mutex_lock(&sensor->mutex); ret = ov5648_sw_standby(sensor, !enable); + if (!ret) + state->streaming = !!enable; mutex_unlock(&sensor->mutex); if (ret) return ret; - state->streaming = !!enable; - if (!enable) pm_runtime_put(sensor->dev); diff --git a/drivers/media/i2c/t4ka3.c b/drivers/media/i2c/t4ka3.c index a5a68e3fbec2..bf48a56f5a91 100644 --- a/drivers/media/i2c/t4ka3.c +++ b/drivers/media/i2c/t4ka3.c @@ -1034,7 +1034,6 @@ static int t4ka3_probe(struct i2c_client *client) err_pm_disable: pm_runtime_disable(&client->dev); - pm_runtime_put_noidle(&client->dev); t4ka3_pm_suspend(&client->dev); return ret; diff --git a/drivers/media/pci/intel/ivsc/mei_ace.c b/drivers/media/pci/intel/ivsc/mei_ace.c index b306a320b70f..bb57656fc85a 100644 --- a/drivers/media/pci/intel/ivsc/mei_ace.c +++ b/drivers/media/pci/intel/ivsc/mei_ace.c @@ -414,13 +414,13 @@ static int mei_ace_setup_dev_link(struct mei_ace *ace) /* setup link between mei_ace and mei_csi */ ace->csi_link = device_link_add(csi_dev, dev, DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE | DL_FLAG_STATELESS); - put_device(csi_dev); if (!ace->csi_link) { ret = -EINVAL; dev_err(dev, "failed to link to %s\n", dev_name(csi_dev)); - goto err; + goto err_put; } + put_device(csi_dev); ace->csi_dev = csi_dev; return 0; diff --git a/drivers/media/platform/qcom/iris/iris_ctrls.c b/drivers/media/platform/qcom/iris/iris_ctrls.c index bf17d310eac0..232be0cb7fa0 100644 --- a/drivers/media/platform/qcom/iris/iris_ctrls.c +++ b/drivers/media/platform/qcom/iris/iris_ctrls.c @@ -525,6 +525,8 @@ int iris_set_stage(struct iris_inst *inst, enum platform_inst_fw_cap_type cap_id work_mode = STAGE_1; } + inst->fw_caps[cap_id].value = work_mode; + return hfi_ops->session_set_property(inst, hfi_id, HFI_HOST_FLAGS_NONE, iris_get_port_info(inst, cap_id), diff --git a/drivers/media/platform/qcom/iris/iris_firmware.c b/drivers/media/platform/qcom/iris/iris_firmware.c index 21cdf1c39835..ea9654dd679e 100644 --- a/drivers/media/platform/qcom/iris/iris_firmware.c +++ b/drivers/media/platform/qcom/iris/iris_firmware.c @@ -17,109 +17,20 @@ #define MAX_FIRMWARE_NAME_SIZE 128 -/* Detect Gen2 firmware by scanning the blob for: - * QC_IMAGE_VERSION_STRING= - * and then checking: - * - version starts with "vfw", OR - * - version matches "video-firmware.N.M" with N >= 2 - */ - -static bool iris_detect_gen2_from_fwdata(const u8 *data, size_t size) -{ - static const char *marker = "QC_IMAGE_VERSION_STRING="; - const size_t mlen = strlen(marker); - static const char *vfw = "vfw"; - const size_t vfwlen = strlen(vfw); - static const char *vf = "video-firmware."; - const size_t vflen = strlen(vf); - - for (size_t i = 0; i + mlen < size; i++) { - const char *found; - - if (memcmp(data + i, marker, mlen)) - continue; - - found = data + i + mlen; - size -= i + mlen; - - /* vfw => Gen2 */ - if (size > vfwlen && !memcmp(found, vfw, vfwlen)) - return true; - - if (size < vflen || - memcmp(found, vf, vflen)) - return false; - - found += vflen; - size -= vflen; - - /* - * video-firmware.1.x is Gen1. - * video-firmware.2.x and video-firmware.10.x are Gen2. - */ - return size >= 2 && - (*found >= '2' || (*found == '1' && found[1] != '.')); - } - - return false; -} - -static const struct firmware *iris_detect_firmware(struct iris_core *core, - const char **fw_name) -{ - const struct firmware *firmware; - bool has_both_gens; - int ret; - - *fw_name = NULL; - if (core->iris_platform_data->firmware_desc_gen2) - core->iris_firmware_desc = core->iris_platform_data->firmware_desc_gen2; - else if (core->iris_platform_data->firmware_desc_gen1) - core->iris_firmware_desc = core->iris_platform_data->firmware_desc_gen1; - else - return ERR_PTR(-EINVAL); - - has_both_gens = core->iris_platform_data->firmware_desc_gen2 && - core->iris_platform_data->firmware_desc_gen1; - - ret = of_property_read_string_index(dev_of_node(core->dev), "firmware-name", 0, fw_name); - if (ret) { - *fw_name = core->iris_firmware_desc->fwname; - ret = request_firmware(&firmware, *fw_name, core->dev); - if (ret && has_both_gens) { - core->iris_firmware_desc = core->iris_platform_data->firmware_desc_gen1; - *fw_name = core->iris_firmware_desc->fwname; - ret = request_firmware(&firmware, *fw_name, core->dev); - } - - return ret ? ERR_PTR(ret) : firmware; - } - - ret = request_firmware(&firmware, *fw_name, core->dev); - if (ret) - return ERR_PTR(ret); - - if (has_both_gens && - !iris_detect_gen2_from_fwdata((const u8 *)firmware->data, firmware->size)) { - dev_info(core->dev, "Gen1 FW detected in %s\n", *fw_name); - core->iris_firmware_desc = core->iris_platform_data->firmware_desc_gen1; - } - - return firmware; -} - -static int iris_load_fw_to_memory(struct iris_core *core) +static int iris_load_fw_to_memory(struct iris_core *core, const char *fw_name) { const struct firmware *firmware = NULL; struct device *dev = core->dev; struct resource res; phys_addr_t mem_phys; - const char *fw_name; size_t res_size; ssize_t fw_size; void *mem_virt; int ret; + if (strlen(fw_name) >= MAX_FIRMWARE_NAME_SIZE - 4) + return -EINVAL; + ret = of_reserved_mem_region_to_resource(dev->of_node, 0, &res); if (ret) return ret; @@ -127,11 +38,9 @@ static int iris_load_fw_to_memory(struct iris_core *core) mem_phys = res.start; res_size = resource_size(&res); - firmware = iris_detect_firmware(core, &fw_name); - if (IS_ERR(firmware)) - return PTR_ERR(firmware); - - core->iris_firmware_data = core->iris_firmware_desc->firmware_data; + ret = request_firmware(&firmware, fw_name, dev); + if (ret) + return ret; fw_size = qcom_mdt_get_size(firmware); if (fw_size < 0 || res_size < (size_t)fw_size) { @@ -158,12 +67,18 @@ static int iris_load_fw_to_memory(struct iris_core *core) int iris_fw_load(struct iris_core *core) { const struct tz_cp_config *cp_config; + const char *fwpath = NULL; int i, ret; - ret = iris_load_fw_to_memory(core); + ret = of_property_read_string_index(core->dev->of_node, "firmware-name", 0, + &fwpath); + if (ret) + fwpath = core->iris_firmware_desc->fwname; + + ret = iris_load_fw_to_memory(core, fwpath); if (ret) { - dev_err(core->dev, "firmware download failed %d\n", ret); - return ret; + dev_err(core->dev, "firmware download failed\n"); + return -ENOMEM; } ret = qcom_pas_auth_and_reset(IRIS_PAS_ID); @@ -185,7 +100,7 @@ int iris_fw_load(struct iris_core *core) } } - return 0; + return ret; } int iris_fw_unload(struct iris_core *core) diff --git a/drivers/media/platform/qcom/iris/iris_hfi_common.c b/drivers/media/platform/qcom/iris/iris_hfi_common.c index 8769ec61f117..42fc854d4c05 100644 --- a/drivers/media/platform/qcom/iris/iris_hfi_common.c +++ b/drivers/media/platform/qcom/iris/iris_hfi_common.c @@ -109,7 +109,8 @@ irqreturn_t iris_hfi_isr_handler(int irq, void *data) iris_vpu_clear_interrupt(core); mutex_unlock(&core->lock); - core->hfi_sys_ops->sys_hfi_response_handler(core); + if (core->hfi_sys_ops) + core->hfi_sys_ops->sys_hfi_response_handler(core); if (!iris_vpu_watchdog(core, core->intr_status)) enable_irq(irq); diff --git a/drivers/media/platform/qcom/iris/iris_hfi_gen1_response.c b/drivers/media/platform/qcom/iris/iris_hfi_gen1_response.c index bfd7495bf44f..e2b95c22f4d1 100644 --- a/drivers/media/platform/qcom/iris/iris_hfi_gen1_response.c +++ b/drivers/media/platform/qcom/iris/iris_hfi_gen1_response.c @@ -632,6 +632,7 @@ static void iris_hfi_gen1_handle_response(struct iris_core *core, void *response mutex_lock(&inst->lock); iris_hfi_gen1_session_event_notify(inst, hdr); mutex_unlock(&inst->lock); + iris_inst_put(inst); } else { iris_hfi_gen1_sys_event_notify(core, hdr); } @@ -667,6 +668,7 @@ static void iris_hfi_gen1_handle_response(struct iris_core *core, void *response } } mutex_unlock(&inst->lock); + iris_inst_put(inst); break; } diff --git a/drivers/media/platform/qcom/iris/iris_hfi_gen2_response.c b/drivers/media/platform/qcom/iris/iris_hfi_gen2_response.c index 8c2644c7f6e8..f0782c4b1e6e 100644 --- a/drivers/media/platform/qcom/iris/iris_hfi_gen2_response.c +++ b/drivers/media/platform/qcom/iris/iris_hfi_gen2_response.c @@ -969,6 +969,7 @@ static int iris_hfi_gen2_handle_session_response(struct iris_core *core, iris_hfi_gen2_handle_dequeue_buffers(inst); mutex_unlock(&inst->lock); + iris_inst_put(inst); return ret; } diff --git a/drivers/media/platform/qcom/iris/iris_instance.h b/drivers/media/platform/qcom/iris/iris_instance.h index a770331d1675..dde5d0b8a83b 100644 --- a/drivers/media/platform/qcom/iris/iris_instance.h +++ b/drivers/media/platform/qcom/iris/iris_instance.h @@ -6,6 +6,8 @@ #ifndef __IRIS_INSTANCE_H__ #define __IRIS_INSTANCE_H__ +#include + #include #include "iris_buffer.h" @@ -35,6 +37,7 @@ enum iris_fmt_type_cap { * struct iris_inst - holds per video instance parameters * * @list: used for attach an instance to the core + * @kref: reference count, keeps the instance alive while the IRQ thread uses it * @core: pointer to core structure * @session_id: id of current video session * @hfi_session_ops: iris HFI session ops @@ -82,6 +85,7 @@ enum iris_fmt_type_cap { struct iris_inst { struct list_head list; + struct kref kref; struct iris_core *core; u32 session_id; const struct iris_hfi_session_ops *hfi_session_ops; diff --git a/drivers/media/platform/qcom/iris/iris_platform_common.h b/drivers/media/platform/qcom/iris/iris_platform_common.h index 974809509146..a9453d539fc2 100644 --- a/drivers/media/platform/qcom/iris/iris_platform_common.h +++ b/drivers/media/platform/qcom/iris/iris_platform_common.h @@ -292,7 +292,11 @@ struct iris_firmware_desc { }; struct iris_platform_data { - const struct iris_firmware_desc *firmware_desc_gen1, *firmware_desc_gen2; + /* + * XXX: replace with gen1 / gen2 pointers once we have platforms + * supporting both firmware kinds. + */ + const struct iris_firmware_desc *firmware_desc; const struct vpu_ops *vpu_ops; const struct icc_info *icc_tbl; diff --git a/drivers/media/platform/qcom/iris/iris_platform_vpu2.c b/drivers/media/platform/qcom/iris/iris_platform_vpu2.c index bbdbf21961d7..cfff647cf440 100644 --- a/drivers/media/platform/qcom/iris/iris_platform_vpu2.c +++ b/drivers/media/platform/qcom/iris/iris_platform_vpu2.c @@ -29,12 +29,6 @@ static const struct iris_firmware_desc iris_vpu20_p1_gen1_desc = { .fwname = "qcom/vpu/vpu20_p1.mbn", }; -static const struct iris_firmware_desc iris_vpu20_p1_gen2_s6_desc = { - .firmware_data = &iris_hfi_gen2_data, - .get_vpu_buffer_size = iris_vpu33_buf_size, - .fwname = "qcom/vpu/vpu20_p1_gen2_s6.mbn", -}; - static const struct iris_firmware_desc iris_vpu20_p4_gen1_desc = { .firmware_data = &iris_hfi_gen1_data, .get_vpu_buffer_size = iris_vpu_buf_size, @@ -78,7 +72,7 @@ static const struct tz_cp_config tz_cp_config_vpu2[] = { }; const struct iris_platform_data milos_data = { - .firmware_desc_gen1 = &iris_milos_desc, + .firmware_desc = &iris_milos_desc, .vpu_ops = &iris_vpu2_ops, .icc_tbl = iris_icc_info_milos, .icc_tbl_size = ARRAY_SIZE(iris_icc_info_milos), @@ -106,8 +100,7 @@ const struct iris_platform_data milos_data = { }; const struct iris_platform_data sc7280_data = { - .firmware_desc_gen1 = &iris_vpu20_p1_gen1_desc, - .firmware_desc_gen2 = &iris_vpu20_p1_gen2_s6_desc, + .firmware_desc = &iris_vpu20_p1_gen1_desc, .vpu_ops = &iris_vpu2_ops, .icc_tbl = iris_icc_info_vpu2, .icc_tbl_size = ARRAY_SIZE(iris_icc_info_vpu2), @@ -136,7 +129,7 @@ const struct iris_platform_data sc7280_data = { }; const struct iris_platform_data sm8250_data = { - .firmware_desc_gen1 = &iris_vpu20_p4_gen1_desc, + .firmware_desc = &iris_vpu20_p4_gen1_desc, .vpu_ops = &iris_vpu2_ops, .icc_tbl = iris_icc_info_vpu2, .icc_tbl_size = ARRAY_SIZE(iris_icc_info_vpu2), diff --git a/drivers/media/platform/qcom/iris/iris_platform_vpu3x.c b/drivers/media/platform/qcom/iris/iris_platform_vpu3x.c index 74626b35d9cb..2c63adbc5579 100644 --- a/drivers/media/platform/qcom/iris/iris_platform_vpu3x.c +++ b/drivers/media/platform/qcom/iris/iris_platform_vpu3x.c @@ -90,7 +90,7 @@ static const struct tz_cp_config tz_cp_config_vpu3[] = { * - inst_caps to platform_inst_cap_qcs8300 */ const struct iris_platform_data qcs8300_data = { - .firmware_desc_gen2 = &iris_vpu30_p4_s6_gen2_desc, + .firmware_desc = &iris_vpu30_p4_s6_gen2_desc, .vpu_ops = &iris_vpu3_ops, .icc_tbl = iris_icc_info_vpu3x, .icc_tbl_size = ARRAY_SIZE(iris_icc_info_vpu3x), @@ -119,7 +119,7 @@ const struct iris_platform_data qcs8300_data = { }; const struct iris_platform_data sm8550_data = { - .firmware_desc_gen2 = &iris_vpu30_p4_gen2_desc, + .firmware_desc = &iris_vpu30_p4_gen2_desc, .vpu_ops = &iris_vpu3_ops, .icc_tbl = iris_icc_info_vpu3x, .icc_tbl_size = ARRAY_SIZE(iris_icc_info_vpu3x), @@ -154,7 +154,7 @@ const struct iris_platform_data sm8550_data = { * - controller_rst_tbl to sm8650_controller_reset_table */ const struct iris_platform_data sm8650_data = { - .firmware_desc_gen2 = &iris_vpu33_p4_gen2_desc, + .firmware_desc = &iris_vpu33_p4_gen2_desc, .vpu_ops = &iris_vpu33_ops, .icc_tbl = iris_icc_info_vpu3x, .icc_tbl_size = ARRAY_SIZE(iris_icc_info_vpu3x), @@ -185,7 +185,7 @@ const struct iris_platform_data sm8650_data = { }; const struct iris_platform_data sm8750_data = { - .firmware_desc_gen2 = &iris_vpu35_p4_gen2_desc, + .firmware_desc = &iris_vpu35_p4_gen2_desc, .vpu_ops = &iris_vpu35_ops, .icc_tbl = iris_icc_info_vpu3x, .icc_tbl_size = ARRAY_SIZE(iris_icc_info_vpu3x), @@ -220,7 +220,7 @@ const struct iris_platform_data sm8750_data = { * - different num_vpp_pipe */ const struct iris_platform_data x1p42100_data = { - .firmware_desc_gen2 = &iris_vpu30_p1_gen2_desc, + .firmware_desc = &iris_vpu30_p1_gen2_desc, .vpu_ops = &iris_vpu3_ops, .icc_tbl = iris_icc_info_vpu3x, .icc_tbl_size = ARRAY_SIZE(iris_icc_info_vpu3x), diff --git a/drivers/media/platform/qcom/iris/iris_probe.c b/drivers/media/platform/qcom/iris/iris_probe.c index 6581a969fe3f..5e5d77736d5f 100644 --- a/drivers/media/platform/qcom/iris/iris_probe.c +++ b/drivers/media/platform/qcom/iris/iris_probe.c @@ -251,6 +251,8 @@ static void iris_remove(struct platform_device *pdev) if (!core) return; + cancel_delayed_work_sync(&core->sys_error_handler); + iris_core_deinit(core); video_unregister_device(core->vdev_dec); @@ -304,6 +306,8 @@ static int iris_probe(struct platform_device *pdev) return core->irq; core->iris_platform_data = of_device_get_match_data(core->dev); + core->iris_firmware_desc = core->iris_platform_data->firmware_desc; + core->iris_firmware_data = core->iris_firmware_desc->firmware_data; core->ubwc_cfg = qcom_ubwc_config_get_data(); if (IS_ERR(core->ubwc_cfg)) @@ -327,6 +331,8 @@ static int iris_probe(struct platform_device *pdev) if (ret) return ret; + iris_session_init_caps(core); + ret = v4l2_device_register(dev, &core->v4l2_dev); if (ret) goto err_unresv_iova_region; diff --git a/drivers/media/platform/qcom/iris/iris_utils.c b/drivers/media/platform/qcom/iris/iris_utils.c index ba5c8dc1280c..1096cc4b01c3 100644 --- a/drivers/media/platform/qcom/iris/iris_utils.c +++ b/drivers/media/platform/qcom/iris/iris_utils.c @@ -92,6 +92,12 @@ struct iris_inst *iris_get_instance(struct iris_core *core, u32 session_id) mutex_lock(&core->lock); list_for_each_entry(inst, &core->instances, list) { if (inst->session_id == session_id) { + /* + * Take a reference under core->lock, paired with + * iris_inst_put() once the caller is done, so the + * instance cannot be freed by a concurrent close(). + */ + kref_get(&inst->kref); mutex_unlock(&core->lock); return inst; } diff --git a/drivers/media/platform/qcom/iris/iris_utils.h b/drivers/media/platform/qcom/iris/iris_utils.h index 228a5f963812..be23acc0e848 100644 --- a/drivers/media/platform/qcom/iris/iris_utils.h +++ b/drivers/media/platform/qcom/iris/iris_utils.h @@ -48,6 +48,7 @@ bool iris_split_mode_enabled(struct iris_inst *inst); bool iris_fmt_is_8bit(u32 pixelformat); bool iris_fmt_is_10bit(u32 pixelformat); struct iris_inst *iris_get_instance(struct iris_core *core, u32 session_id); +void iris_inst_put(struct iris_inst *inst); void iris_helper_buffers_done(struct iris_inst *inst, unsigned int type, enum vb2_buffer_state state); int iris_wait_for_session_response(struct iris_inst *inst, bool is_flush); diff --git a/drivers/media/platform/qcom/iris/iris_vb2.c b/drivers/media/platform/qcom/iris/iris_vb2.c index a2ea2d67f60d..8faf709c26c1 100644 --- a/drivers/media/platform/qcom/iris/iris_vb2.c +++ b/drivers/media/platform/qcom/iris/iris_vb2.c @@ -56,10 +56,14 @@ static int iris_check_session_supported(struct iris_inst *inst) bool found = false; int ret; + mutex_lock(&core->lock); list_for_each_entry(instance, &core->instances, list) { - if (instance == inst) + if (instance == inst) { found = true; + break; + } } + mutex_unlock(&core->lock); if (!found) { ret = -EINVAL; diff --git a/drivers/media/platform/qcom/iris/iris_vidc.c b/drivers/media/platform/qcom/iris/iris_vidc.c index f1d7f186002d..63c1611af6f6 100644 --- a/drivers/media/platform/qcom/iris/iris_vidc.c +++ b/drivers/media/platform/qcom/iris/iris_vidc.c @@ -9,7 +9,6 @@ #include #include -#include "iris_ctrls.h" #include "iris_vidc.h" #include "iris_instance.h" #include "iris_vdec.h" @@ -40,21 +39,39 @@ static void iris_v4l2_fh_deinit(struct iris_inst *inst, struct file *filp) v4l2_fh_exit(&inst->fh); } -static void iris_add_session(struct iris_inst *inst) +static void iris_inst_release(struct kref *kref) +{ + struct iris_inst *inst = container_of(kref, struct iris_inst, kref); + + mutex_destroy(&inst->ctx_q_lock); + mutex_destroy(&inst->lock); + kfree(inst->fmt_src); + kfree(inst->fmt_dst); + kfree(inst); +} + +void iris_inst_put(struct iris_inst *inst) +{ + kref_put(&inst->kref, iris_inst_release); +} + +static int iris_add_session(struct iris_inst *inst) { struct iris_core *core = inst->core; struct iris_inst *iter; u32 count = 0; - mutex_lock(&core->lock); + guard(mutex)(&core->lock); list_for_each_entry(iter, &core->instances, list) count++; - if (count < core->iris_platform_data->max_session_count) - list_add_tail(&inst->list, &core->instances); + if (count >= core->iris_platform_data->max_session_count) + return -EBUSY; - mutex_unlock(&core->lock); + list_add_tail(&inst->list, &core->instances); + + return 0; } static void iris_remove_session(struct iris_inst *inst) @@ -165,6 +182,7 @@ int iris_open(struct file *filp) inst->domain = session_type; inst->session_id = hash32_ptr(inst); inst->state = IRIS_INST_DEINIT; + kref_init(&inst->kref); mutex_init(&inst->lock); mutex_init(&inst->ctx_q_lock); @@ -197,8 +215,6 @@ int iris_open(struct file *filp) goto fail_m2m_release; } - iris_session_init_caps(core); - if (inst->domain == DECODER) ret = iris_vdec_inst_init(inst); else if (inst->domain == ENCODER) @@ -206,12 +222,17 @@ int iris_open(struct file *filp) if (ret) goto fail_m2m_ctx_release; - iris_add_session(inst); + ret = iris_add_session(inst); + if (ret) + goto fail_inst_deinit; inst->fh.m2m_ctx = inst->m2m_ctx; return 0; +fail_inst_deinit: + kfree(inst->fmt_src); + kfree(inst->fmt_dst); fail_m2m_ctx_release: v4l2_m2m_ctx_release(inst->m2m_ctx); fail_m2m_release: @@ -301,11 +322,7 @@ int iris_close(struct file *filp) iris_check_num_queued_internal_buffers(inst, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE); iris_remove_session(inst); mutex_unlock(&inst->lock); - mutex_destroy(&inst->ctx_q_lock); - mutex_destroy(&inst->lock); - kfree(inst->fmt_src); - kfree(inst->fmt_dst); - kfree(inst); + iris_inst_put(inst); return 0; } diff --git a/drivers/media/platform/qcom/iris/iris_vpu_common.c b/drivers/media/platform/qcom/iris/iris_vpu_common.c index c9f5dc851d9f..7e4fcf79a01d 100644 --- a/drivers/media/platform/qcom/iris/iris_vpu_common.c +++ b/drivers/media/platform/qcom/iris/iris_vpu_common.c @@ -84,7 +84,7 @@ int iris_vpu_boot_firmware(struct iris_core *core) ctrl_status = readl(core->reg_base + CTRL_STATUS); if ((ctrl_status & CTRL_ERROR_STATUS__M) == 0x4) { dev_err(core->dev, "invalid setting for uc_region\n"); - break; + return -EINVAL; } usleep_range(50, 100); diff --git a/drivers/media/platform/qcom/venus/hfi_msgs.c b/drivers/media/platform/qcom/venus/hfi_msgs.c index 5c2025c5acc7..ed6b4e5e5e92 100644 --- a/drivers/media/platform/qcom/venus/hfi_msgs.c +++ b/drivers/media/platform/qcom/venus/hfi_msgs.c @@ -230,6 +230,9 @@ static void hfi_event_notify(struct venus_core *core, struct venus_inst *inst, if (!packet) return; + if (!inst && pkt->event_id != HFI_EVENT_SYS_ERROR) + return; + switch (pkt->event_id) { case HFI_EVENT_SYS_ERROR: event_sys_error(core, EVT_SYS_ERROR, pkt); diff --git a/drivers/media/platform/renesas/rcar-isp/core-io.c b/drivers/media/platform/renesas/rcar-isp/core-io.c index 820af506f896..b60b91f43d42 100644 --- a/drivers/media/platform/renesas/rcar-isp/core-io.c +++ b/drivers/media/platform/renesas/rcar-isp/core-io.c @@ -15,6 +15,12 @@ #include "risp-core.h" +#define RISP_MIN_WIDTH 128 +#define RISP_MAX_WIDTH 5120 +#define RISP_MIN_HEIGHT 128 +#define RISP_MAX_HEIGHT 4096 +#define RISP_SIZE_ALIGNMENT 2 /* 2^2 = 4 */ + #define risp_io_err(d, fmt, arg...) dev_err((d)->core->dev, fmt, ##arg) static struct risp_buffer *risp_io_vb2buf(struct vb2_v4l2_buffer *vb) @@ -330,8 +336,9 @@ static void risp_io_input_try_format(struct rcar_isp_core_io *io, { unsigned int bpp = 0; - v4l_bound_align_image(&pix->width, 128, 5120, 2, - &pix->height, 128, 4096, 2, 0); + v4l_bound_align_image(&pix->width, RISP_MIN_WIDTH, RISP_MAX_WIDTH, RISP_SIZE_ALIGNMENT, + &pix->height, RISP_MIN_HEIGHT, RISP_MAX_HEIGHT, RISP_SIZE_ALIGNMENT, + 0); for (unsigned int i = 0; i < ARRAY_SIZE(risp_io_input_formats); i++) { if (risp_io_input_formats[i].fourcc == pix->pixelformat) { @@ -423,13 +430,13 @@ static int risp_io_input_enum_framesizes(struct file *file, void *fh, fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE; - fsize->stepwise.min_width = 128; - fsize->stepwise.max_width = 5120; - fsize->stepwise.step_width = 2; + fsize->stepwise.min_width = RISP_MIN_WIDTH; + fsize->stepwise.max_width = RISP_MAX_WIDTH; + fsize->stepwise.step_width = 1u << RISP_SIZE_ALIGNMENT; - fsize->stepwise.min_height = 128; - fsize->stepwise.max_height = 4096; - fsize->stepwise.step_height = 2; + fsize->stepwise.min_height = RISP_MIN_HEIGHT; + fsize->stepwise.max_height = RISP_MAX_HEIGHT; + fsize->stepwise.step_height = 1u << RISP_SIZE_ALIGNMENT; return 0; } @@ -720,8 +727,9 @@ static const struct v4l2_pix_format_mplane risp_io_capture_default_format = { static void risp_io_capture_try_format(struct rcar_isp_core_io *io, struct v4l2_pix_format_mplane *pix) { - v4l_bound_align_image(&pix->width, 128, 5120, 2, - &pix->height, 128, 4096, 2, 0); + v4l_bound_align_image(&pix->width, RISP_MIN_WIDTH, RISP_MAX_WIDTH, RISP_SIZE_ALIGNMENT, + &pix->height, RISP_MIN_HEIGHT, RISP_MAX_HEIGHT, RISP_SIZE_ALIGNMENT, + 0); pix->field = V4L2_FIELD_NONE; pix->colorspace = V4L2_COLORSPACE_SRGB; @@ -824,13 +832,13 @@ static int risp_io_capture_enum_framesizes(struct file *file, void *fh, fsize->type = V4L2_FRMSIZE_TYPE_STEPWISE; - fsize->stepwise.min_width = 128; - fsize->stepwise.max_width = 5120; - fsize->stepwise.step_width = 2; + fsize->stepwise.min_width = RISP_MIN_WIDTH; + fsize->stepwise.max_width = RISP_MAX_WIDTH; + fsize->stepwise.step_width = 1u << RISP_SIZE_ALIGNMENT; - fsize->stepwise.min_height = 128; - fsize->stepwise.max_height = 4096; - fsize->stepwise.step_height = 2; + fsize->stepwise.min_height = RISP_MIN_HEIGHT; + fsize->stepwise.max_height = RISP_MAX_HEIGHT; + fsize->stepwise.step_height = 1u << RISP_SIZE_ALIGNMENT; return 0; } diff --git a/drivers/media/usb/em28xx/em28xx-video.c b/drivers/media/usb/em28xx/em28xx-video.c index e441f221dbb7..e708d483137e 100644 --- a/drivers/media/usb/em28xx/em28xx-video.c +++ b/drivers/media/usb/em28xx/em28xx-video.c @@ -2474,6 +2474,7 @@ static int em28xx_v4l2_resume(struct em28xx *dev) */ static int em28xx_v4l2_close(struct file *filp) { + struct video_device *vdev = video_devdata(filp); struct em28xx *dev = video_drvdata(filp); struct em28xx_v4l2 *v4l2 = dev->v4l2; struct usb_device *udev = interface_to_usbdev(dev->intf); @@ -2482,7 +2483,7 @@ static int em28xx_v4l2_close(struct file *filp) mutex_lock(&dev->lock); last_user = v4l2_fh_is_singular_file(filp); - _vb2_fop_release(filp, NULL); + _vb2_fop_release(filp, vdev->queue->lock); if (last_user) { /* No sense to try to write to the device */ diff --git a/drivers/memory/brcmstb_dpfe.c b/drivers/memory/brcmstb_dpfe.c index 7b02c36c7fca..04ae3cfb449e 100644 --- a/drivers/memory/brcmstb_dpfe.c +++ b/drivers/memory/brcmstb_dpfe.c @@ -533,9 +533,15 @@ static int __verify_firmware(struct init_data *init, const struct firmware *fw) { const struct dpfe_firmware_header *header = (void *)fw->data; - unsigned int dmem_size, imem_size, total_size; + unsigned int dmem_size, imem_size; bool is_big_endian = false; const u32 *chksum_ptr; + size_t payload_size; + + if (fw->size < sizeof(*header) + sizeof(*chksum_ptr)) + return ERR_INVALID_SIZE; + + payload_size = fw->size - sizeof(*header) - sizeof(*chksum_ptr); if (header->magic == DPFE_BE_MAGIC) is_big_endian = true; @@ -554,13 +560,8 @@ static int __verify_firmware(struct init_data *init, if ((dmem_size % sizeof(u32)) != 0 || (imem_size % sizeof(u32)) != 0) return ERR_INVALID_SIZE; - /* - * The header + the data section + the instruction section + the - * checksum must be equal to the total firmware size. - */ - total_size = dmem_size + imem_size + sizeof(*header) + - sizeof(*chksum_ptr); - if (total_size != fw->size) + /* The data and instruction sections must fill the payload exactly. */ + if (dmem_size > payload_size || imem_size != payload_size - dmem_size) return ERR_INVALID_SIZE; /* The checksum comes at the very end. */ diff --git a/drivers/memory/emif.c b/drivers/memory/emif.c index 2fadad0666b1..44ccc2561835 100644 --- a/drivers/memory/emif.c +++ b/drivers/memory/emif.c @@ -922,6 +922,7 @@ static struct emif_data *of_get_memory_device_details( if (!emif || !pd || !dev_info) { dev_err(dev, "%s: Out of memory!!\n", __func__); + of_node_put(np_ddr); goto error; } @@ -946,6 +947,7 @@ static struct emif_data *of_get_memory_device_details( pd->device_info->io_width, pd->phy_type, pd->ip_rev, emif->dev)) { dev_err(dev, "%s: invalid device data!!\n", __func__); + of_node_put(np_ddr); goto error; } /* @@ -1140,6 +1142,7 @@ static void emif_remove(struct platform_device *pdev) struct emif_data *emif = platform_get_drvdata(pdev); emif_debugfs_exit(emif); + of_node_put(emif->np_ddr); } static void emif_shutdown(struct platform_device *pdev) diff --git a/drivers/memory/samsung/exynos5422-dmc.c b/drivers/memory/samsung/exynos5422-dmc.c index 788d49c688b1..98c319552583 100644 --- a/drivers/memory/samsung/exynos5422-dmc.c +++ b/drivers/memory/samsung/exynos5422-dmc.c @@ -1297,8 +1297,15 @@ static int exynos5_dmc_init_clks(struct exynos5_dmc *dmc) if (ret) return ret; - clk_prepare_enable(dmc->fout_bpll); - clk_prepare_enable(dmc->mout_bpll); + ret = clk_prepare_enable(dmc->fout_bpll); + if (ret) + return ret; + + ret = clk_prepare_enable(dmc->mout_bpll); + if (ret) { + clk_disable_unprepare(dmc->fout_bpll); + return ret; + } /* * Some bootloaders do not set clock routes correctly. diff --git a/drivers/mfd/cs42l43-i2c.c b/drivers/mfd/cs42l43-i2c.c index cbe05c3ea910..36c5b03bae69 100644 --- a/drivers/mfd/cs42l43-i2c.c +++ b/drivers/mfd/cs42l43-i2c.c @@ -54,6 +54,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", .data = (void *)CS42L43_DEVID_VAL }, @@ -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 0a6999453f32..afed34d23af8 100644 --- a/drivers/mfd/cs42l43-sdw.c +++ b/drivers/mfd/cs42l43-sdw.c @@ -180,6 +180,13 @@ static int cs42l43_sdw_probe(struct sdw_slave *sdw, const struct sdw_device_id * return cs42l43_dev_probe(cs42l43); } +static void cs42l43_sdw_remove(struct sdw_slave *sdw) +{ + struct cs42l43 *cs42l43 = dev_get_drvdata(&sdw->dev); + + cs42l43_dev_remove(cs42l43); +} + static const struct sdw_device_id cs42l43_sdw_id[] = { SDW_SLAVE_ENTRY(0x01FA, 0x4243, (void *)CS42L43_DEVID_VAL), SDW_SLAVE_ENTRY(0x01FA, 0x2A3B, (void *)CS42L43B_DEVID_VAL), @@ -194,6 +201,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 4212ebcca60b..3d26c33fee1d 100644 --- a/drivers/mfd/cs42l43.c +++ b/drivers/mfd/cs42l43.c @@ -1099,15 +1099,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; @@ -1153,7 +1157,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 a0068f6572e2..862bc6fb68cb 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/mfd/da9150-core.c b/drivers/mfd/da9150-core.c index 5c59cc869fb3..19325d72a27e 100644 --- a/drivers/mfd/da9150-core.c +++ b/drivers/mfd/da9150-core.c @@ -450,7 +450,7 @@ static int da9150_probe(struct i2c_client *client) da9150->irq_base = regmap_irq_chip_get_base(da9150->regmap_irq_data); - enable_irq_wake(da9150->irq); + da9150->irq_wake_enabled = !enable_irq_wake(da9150->irq); ret = mfd_add_devices(da9150->dev, -1, da9150_devs, ARRAY_SIZE(da9150_devs), NULL, @@ -463,6 +463,8 @@ static int da9150_probe(struct i2c_client *client) return 0; mfd_fail: + if (da9150->irq_wake_enabled) + disable_irq_wake(da9150->irq); regmap_del_irq_chip(da9150->irq, da9150->regmap_irq_data); regmap_irq_fail: i2c_unregister_device(da9150->core_qif); @@ -474,8 +476,10 @@ static void da9150_remove(struct i2c_client *client) { struct da9150 *da9150 = i2c_get_clientdata(client); - regmap_del_irq_chip(da9150->irq, da9150->regmap_irq_data); mfd_remove_devices(da9150->dev); + if (da9150->irq_wake_enabled) + disable_irq_wake(da9150->irq); + regmap_del_irq_chip(da9150->irq, da9150->regmap_irq_data); i2c_unregister_device(da9150->core_qif); } diff --git a/drivers/mfd/intel_quark_i2c_gpio.c b/drivers/mfd/intel_quark_i2c_gpio.c index 9b9c76bd067b..443a1a0cf777 100644 --- a/drivers/mfd/intel_quark_i2c_gpio.c +++ b/drivers/mfd/intel_quark_i2c_gpio.c @@ -35,11 +35,6 @@ /* The Quark I2C controller source clock */ #define INTEL_QUARK_I2C_CLK_HZ 33000000 -struct intel_quark_mfd { - struct clk *i2c_clk; - struct clk_lookup *i2c_clk_lookup; -}; - static const struct property_entry intel_quark_i2c_controller_standard_properties[] = { PROPERTY_ENTRY_U32("clock-frequency", I2C_MAX_STANDARD_MODE_FREQ), { } @@ -160,37 +155,12 @@ MODULE_DEVICE_TABLE(pci, intel_quark_mfd_ids); static int intel_quark_register_i2c_clk(struct device *dev) { - struct intel_quark_mfd *quark_mfd = dev_get_drvdata(dev); - struct clk *i2c_clk; - - i2c_clk = clk_register_fixed_rate(dev, - INTEL_QUARK_I2C_CONTROLLER_CLK, NULL, - 0, INTEL_QUARK_I2C_CLK_HZ); - if (IS_ERR(i2c_clk)) - return PTR_ERR(i2c_clk); - - quark_mfd->i2c_clk = i2c_clk; - quark_mfd->i2c_clk_lookup = clkdev_create(i2c_clk, NULL, - INTEL_QUARK_I2C_CONTROLLER_CLK); - - if (!quark_mfd->i2c_clk_lookup) { - clk_unregister(quark_mfd->i2c_clk); - dev_err(dev, "Fixed clk register failed\n"); - return -ENOMEM; - } - - return 0; -} - -static void intel_quark_unregister_i2c_clk(struct device *dev) -{ - struct intel_quark_mfd *quark_mfd = dev_get_drvdata(dev); - - if (!quark_mfd->i2c_clk_lookup) - return; + struct clk_hw *hw; - clkdev_drop(quark_mfd->i2c_clk_lookup); - clk_unregister(quark_mfd->i2c_clk); + hw = devm_clk_hw_register_fixed_rate(dev, INTEL_QUARK_I2C_CONTROLLER_CLK, + NULL, 0, INTEL_QUARK_I2C_CLK_HZ); + return devm_clk_hw_register_clkdev(dev, hw, NULL, + INTEL_QUARK_I2C_CONTROLLER_CLK); } static int intel_quark_i2c_setup(struct pci_dev *pdev) @@ -238,19 +208,12 @@ static int intel_quark_gpio_setup(struct pci_dev *pdev) static int intel_quark_mfd_probe(struct pci_dev *pdev, const struct pci_device_id *id) { - struct intel_quark_mfd *quark_mfd; int ret; ret = pcim_enable_device(pdev); if (ret) return ret; - quark_mfd = devm_kzalloc(&pdev->dev, sizeof(*quark_mfd), GFP_KERNEL); - if (!quark_mfd) - return -ENOMEM; - - dev_set_drvdata(&pdev->dev, quark_mfd); - ret = intel_quark_register_i2c_clk(&pdev->dev); if (ret) return ret; @@ -260,7 +223,7 @@ static int intel_quark_mfd_probe(struct pci_dev *pdev, /* This driver only requires 1 IRQ vector */ ret = pci_alloc_irq_vectors(pdev, 1, 1, PCI_IRQ_ALL_TYPES); if (ret < 0) - goto err_unregister_i2c_clk; + return ret; ret = intel_quark_i2c_setup(pdev); if (ret) @@ -282,8 +245,6 @@ static int intel_quark_mfd_probe(struct pci_dev *pdev, software_node_unregister_node_group(intel_quark_gpio_node_group); err_free_irq_vectors: pci_free_irq_vectors(pdev); -err_unregister_i2c_clk: - intel_quark_unregister_i2c_clk(&pdev->dev); return ret; } @@ -292,7 +253,6 @@ static void intel_quark_mfd_remove(struct pci_dev *pdev) mfd_remove_devices(&pdev->dev); software_node_unregister_node_group(intel_quark_gpio_node_group); pci_free_irq_vectors(pdev); - intel_quark_unregister_i2c_clk(&pdev->dev); } static struct pci_driver intel_quark_mfd_driver = { diff --git a/drivers/mfd/rk8xx-core.c b/drivers/mfd/rk8xx-core.c index 3dcf6abfda74..21182df45d1b 100644 --- a/drivers/mfd/rk8xx-core.c +++ b/drivers/mfd/rk8xx-core.c @@ -875,7 +875,7 @@ int rk8xx_probe(struct device *dev, int variant, unsigned int irq, struct regmap if (device_property_read_bool(dev, "system-power-controller") || device_property_read_bool(dev, "rockchip,system-power-controller")) { ret = devm_register_sys_off_handler(dev, - SYS_OFF_MODE_POWER_OFF_PREPARE, SYS_OFF_PRIO_HIGH, + SYS_OFF_MODE_POWER_OFF, SYS_OFF_PRIO_HIGH, &rk808_power_off, rk808); if (ret) return dev_err_probe(dev, ret, diff --git a/drivers/misc/enclosure.c b/drivers/misc/enclosure.c index de457378c501..bdbff5178ec7 100644 --- a/drivers/misc/enclosure.c +++ b/drivers/misc/enclosure.c @@ -148,8 +148,7 @@ enclosure_register(struct device *dev, const char *name, int components, return edev; err: - put_device(edev->edev.parent); - kfree(edev); + put_device(&edev->edev); return ERR_PTR(err); } EXPORT_SYMBOL_GPL(enclosure_register); diff --git a/drivers/misc/mei/vsc-tp.c b/drivers/misc/mei/vsc-tp.c index ce877cb95757..5410ec1c9328 100644 --- a/drivers/misc/mei/vsc-tp.c +++ b/drivers/misc/mei/vsc-tp.c @@ -496,30 +496,30 @@ static int vsc_tp_probe(struct spi_device *spi) init_waitqueue_head(&tp->xfer_wait); tp->spi = spi; + mutex_init(&tp->mutex); + mutex_init(&tp->event_notify_mutex); + INIT_WORK(&tp->event_work, vsc_tp_event_work); + irq_set_status_flags(spi->irq, IRQ_DISABLE_UNLAZY); ret = request_threaded_irq(spi->irq, NULL, vsc_tp_isr, IRQF_TRIGGER_FALLING | IRQF_ONESHOT, dev_name(dev), tp); if (ret) - return ret; - - mutex_init(&tp->mutex); - mutex_init(&tp->event_notify_mutex); - INIT_WORK(&tp->event_work, vsc_tp_event_work); + goto err_destroy_lock; /* only one child acpi device */ ret = acpi_dev_for_each_child(ACPI_COMPANION(dev), vsc_tp_match_any, &adev); if (!ret) { ret = -ENODEV; - goto err_destroy_lock; + goto err_free_irq; } pinfo.fwnode = acpi_fwnode_handle(adev); pdev = platform_device_register_full(&pinfo); if (IS_ERR(pdev)) { ret = PTR_ERR(pdev); - goto err_destroy_lock; + goto err_free_irq; } tp->pdev = pdev; @@ -527,9 +527,10 @@ static int vsc_tp_probe(struct spi_device *spi) return 0; -err_destroy_lock: +err_free_irq: free_irq(spi->irq, tp); +err_destroy_lock: cancel_work_sync(&tp->event_work); mutex_destroy(&tp->event_notify_mutex); mutex_destroy(&tp->mutex); diff --git a/drivers/misc/nsm.c b/drivers/misc/nsm.c index a3a9f9bfc6b7..b6d3fa79a5e8 100644 --- a/drivers/misc/nsm.c +++ b/drivers/misc/nsm.c @@ -117,7 +117,7 @@ static int cbor_object_get_array(u8 *cbor_object, size_t cbor_object_size, u8 ** array_len_p = &cbor_object[1]; switch (cbor_short_size) { - case CBOR_SHORT_SIZE_MAX_VALUE: /* short encoding */ + case 0 ... CBOR_SHORT_SIZE_MAX_VALUE: /* short encoding */ array_len = cbor_short_size; break; case CBOR_LONG_SIZE_U8: @@ -132,6 +132,8 @@ static int cbor_object_get_array(u8 *cbor_object, size_t cbor_object_size, u8 ** case CBOR_LONG_SIZE_U64: array_len = be64_to_cpup((__be64 *)array_len_p); break; + default: + return -EFAULT; } if (cbor_object_size < array_offset) @@ -439,6 +441,8 @@ static int nsm_device_probe(struct virtio_device *vdev) mutex_init(&nsm->lock); + virtio_device_ready(vdev); + /* Register as hwrng provider */ nsm->hwrng = (struct hwrng) { .read = nsm_rng_read, @@ -471,6 +475,7 @@ static int nsm_device_probe(struct virtio_device *vdev) err_misc: hwrng_unregister(&nsm->hwrng); err_hwrng: + virtio_reset_device(vdev); vdev->config->del_vqs(vdev); err_init_vq: return rc; diff --git a/drivers/mtd/mtd_blkdevs.c b/drivers/mtd/mtd_blkdevs.c index 4d2e7b7774e9..42f250344f0c 100644 --- a/drivers/mtd/mtd_blkdevs.c +++ b/drivers/mtd/mtd_blkdevs.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include "mtdcore.h" @@ -167,6 +168,7 @@ static blk_status_t mtd_queue_rq(struct blk_mq_hw_ctx *hctx, const struct blk_mq_queue_data *bd) { struct mtd_blktrans_dev *dev; + unsigned int noio_flags; dev = hctx->queue->queuedata; if (!dev) { @@ -174,10 +176,13 @@ static blk_status_t mtd_queue_rq(struct blk_mq_hw_ctx *hctx, return BLK_STS_IOERR; } + /* Reclaim must not recurse into I/O while processing requests. */ + noio_flags = memalloc_noio_save(); spin_lock_irq(&dev->queue_lock); list_add_tail(&bd->rq->queuelist, &dev->rq_list); mtd_blktrans_work(dev); spin_unlock_irq(&dev->queue_lock); + memalloc_noio_restore(noio_flags); return BLK_STS_OK; } diff --git a/drivers/mtd/nand/raw/pl35x-nand-controller.c b/drivers/mtd/nand/raw/pl35x-nand-controller.c index bd89aaadd1b2..26b61d856143 100644 --- a/drivers/mtd/nand/raw/pl35x-nand-controller.c +++ b/drivers/mtd/nand/raw/pl35x-nand-controller.c @@ -807,6 +807,7 @@ static int pl35x_nfc_setup_interface(struct nand_chip *chip, int cs, * macro to convert from one to the other. */ period_ns = NSEC_PER_SEC / clk_get_rate(mclk); + clk_put(mclk); /* * PL35X SMC needs one extra read cycle in SDR Mode 5. This is not diff --git a/drivers/mtd/nand/raw/sunxi_nand.c b/drivers/mtd/nand/raw/sunxi_nand.c index 89fe3c0379f7..f41feebe4257 100644 --- a/drivers/mtd/nand/raw/sunxi_nand.c +++ b/drivers/mtd/nand/raw/sunxi_nand.c @@ -222,6 +222,7 @@ * USER_DATA_LEN registers. */ #define USER_DATA_SZ 4 +#define SUNXI_NFC_MAX_USER_DATA_SZ 32 /** * struct sunxi_nand_chip_sel - stores information related to NAND Chip Select @@ -1003,11 +1004,10 @@ static void sunxi_nfc_hw_ecc_set_prot_oob_bytes(struct nand_chip *nand, struct sunxi_nfc *nfc = to_sunxi_nfc(nand->controller); struct sunxi_nand_chip *sunxi_nand = to_sunxi_nand(nand); unsigned int user_data_sz = sunxi_nfc_user_data_sz(sunxi_nand, step); - u8 *user_data = NULL; + u8 user_data[SUNXI_NFC_MAX_USER_DATA_SZ] = {}; /* Randomize the Bad Block Marker. */ if (bbm && (nand->options & NAND_NEED_SCRAMBLING)) { - user_data = kmalloc(user_data_sz, GFP_KERNEL); memcpy(user_data, oob, user_data_sz); sunxi_nfc_randomize_bbm(nand, page, user_data); oob = user_data; @@ -1040,7 +1040,6 @@ static void sunxi_nfc_hw_ecc_set_prot_oob_bytes(struct nand_chip *nand, } } - kfree(user_data); } static void sunxi_nfc_hw_ecc_update_stats(struct nand_chip *nand, @@ -1991,7 +1990,7 @@ static int sunxi_nand_ooblayout_free(struct mtd_info *mtd, int section, struct nand_chip *nand = mtd_to_nand(mtd); struct nand_ecc_ctrl *ecc = &nand->ecc; struct sunxi_nand_chip *sunxi_nand = to_sunxi_nand(nand); - unsigned int user_data_sz = sunxi_nfc_user_data_sz(sunxi_nand, section); + unsigned int user_data_sz; /* * The controller does not provide access to OOB bytes @@ -2000,6 +1999,8 @@ static int sunxi_nand_ooblayout_free(struct mtd_info *mtd, int section, if (section >= ecc->steps) return -ERANGE; + user_data_sz = sunxi_nfc_user_data_sz(sunxi_nand, section); + /* * The first 2 bytes are used for BB markers, hence we * only have user_data_sz - 2 bytes available in the first user data @@ -2007,7 +2008,7 @@ static int sunxi_nand_ooblayout_free(struct mtd_info *mtd, int section, */ if (section == 0) { oobregion->offset = 2; - oobregion->length = user_data_sz - 2; + oobregion->length = user_data_sz > 2 ? user_data_sz - 2 : 0; return 0; } @@ -2041,6 +2042,9 @@ static int sunxi_nfc_maximize_user_data(struct nand_chip *nand, uint32_t oobsize int remaining_bytes = oobsize - (ecc_bytes * nsectors); int i, step; + if (nsectors <= 0) + return -EINVAL; + sunxi_nand->user_data_bytes = devm_kzalloc(nfc->dev, nsectors, GFP_KERNEL); if (!sunxi_nand->user_data_bytes) @@ -2056,6 +2060,8 @@ static int sunxi_nfc_maximize_user_data(struct nand_chip *nand, uint32_t oobsize if (sunxi_nand->user_data_bytes[step] == 0) break; } + if (sunxi_nand->user_data_bytes[0] < USER_DATA_SZ) + return -EINVAL; return 0; } @@ -2072,6 +2078,7 @@ static int sunxi_nand_hw_ecc_ctrl_init(struct nand_chip *nand, int total_user_data_sz = 0; int nsectors; int ecc_mode; + int ret; int i; if (nanddev->ecc.user_conf.flags & NAND_ECC_MAXIMIZE_STRENGTH) { @@ -2105,10 +2112,10 @@ static int sunxi_nand_hw_ecc_ctrl_init(struct nand_chip *nand, bytes -= total_user_data_sz; } else { /* - * remove at least the BBM size before computing the - * max ECC + * User-data lengths are encoded in four-byte units. Reserve + * the first word because it contains the two BBM bytes. */ - bytes -= 2; + bytes -= USER_DATA_SZ; } /* @@ -2172,9 +2179,12 @@ static int sunxi_nand_hw_ecc_ctrl_init(struct nand_chip *nand, * The rationale for variable data length is to prioritize maximum ECC * strength, and then use the remaining space for user data. */ - if (nfc->caps->reg_user_data_len) - sunxi_nfc_maximize_user_data(nand, mtd->oobsize, ecc->bytes, - nsectors); + if (nfc->caps->reg_user_data_len) { + ret = sunxi_nfc_maximize_user_data(nand, mtd->oobsize, + ecc->bytes, nsectors); + if (ret) + return ret; + } if (total_user_data_sz == 0) for (i = 0; i < nsectors; i++) diff --git a/drivers/mtd/spi-nor/spansion.c b/drivers/mtd/spi-nor/spansion.c index 65227d989de1..db9b5416fcf1 100644 --- a/drivers/mtd/spi-nor/spansion.c +++ b/drivers/mtd/spi-nor/spansion.c @@ -870,13 +870,6 @@ static const struct flash_info spansion_nor_parts[] = { .sector_size = SZ_256K, .no_sfdp_flags = SPI_NOR_SKIP_SFDP | SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ, .mfr_flags = USE_CLSR, - }, { - .id = SNOR_ID(0x01, 0x02, 0x19, 0x4d, 0x00, 0x81), - .name = "s25fs256s0", - .size = SZ_32M, - .sector_size = SZ_256K, - .no_sfdp_flags = SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ, - .mfr_flags = USE_CLSR, }, { .id = SNOR_ID(0x01, 0x02, 0x19, 0x4d, 0x01, 0x80), .name = "s25fl256s1", diff --git a/drivers/net/amt.c b/drivers/net/amt.c index b53f8ec55661..faa21015b34d 100644 --- a/drivers/net/amt.c +++ b/drivers/net/amt.c @@ -1292,8 +1292,12 @@ static int amt_parse_type(struct sk_buff *skb) { struct amt_header *amth; - if (!pskb_may_pull(skb, sizeof(struct udphdr) + - sizeof(struct amt_header))) + /* skb->data is the UDP header on receive, but the quoted IP header + * when amt_err_lookup() parses an ICMP error, so pull up to the + * transport header rather than from skb->data. + */ + if (!pskb_may_pull(skb, skb_transport_offset(skb) + + sizeof(struct udphdr) + sizeof(struct amt_header))) return -1; amth = (struct amt_header *)(udp_hdr(skb) + 1); diff --git a/drivers/net/dsa/mt7530.c b/drivers/net/dsa/mt7530.c index 96832852c65a..5dbcea38209f 100644 --- a/drivers/net/dsa/mt7530.c +++ b/drivers/net/dsa/mt7530.c @@ -3335,10 +3335,13 @@ mt753x_conduit_state_change(struct dsa_switch *ds, /* Set the CPU port to trap frames to for MT7530. Trapped frames will be * forwarded to the numerically smallest CPU port whose conduit - * interface is up. + * interface is up. On EN7581, trapped BPDUs do not reach the CPU port + * without this, even with the CPU port bitmap set. AN7583 is set up + * the same way as EN7581. */ if (priv->id != ID_MT7530 && priv->id != ID_MT7621 && - priv->id != ID_EN7528) + priv->id != ID_EN7528 && + priv->id != ID_EN7581 && priv->id != ID_AN7583) return; mask = BIT(cpu_dp->index); diff --git a/drivers/net/dsa/mv88e6xxx/chip.c b/drivers/net/dsa/mv88e6xxx/chip.c index a4a8c7e11bf4..e647e36dea39 100644 --- a/drivers/net/dsa/mv88e6xxx/chip.c +++ b/drivers/net/dsa/mv88e6xxx/chip.c @@ -4610,7 +4610,7 @@ static const struct mv88e6xxx_ops mv88e6171_ops = { .port_disable_pri_override = mv88e6xxx_port_disable_pri_override, .port_get_cmode = mv88e6352_port_get_cmode, .port_setup_message_port = mv88e6xxx_setup_message_port, - .stats_snapshot = mv88e6320_g1_stats_snapshot, + .stats_snapshot = mv88e6xxx_g1_stats_snapshot, .stats_set_histogram = mv88e6095_g1_stats_set_histogram, .stats_get_sset_count = mv88e6095_stats_get_sset_count, .stats_get_strings = mv88e6095_stats_get_strings, @@ -4714,7 +4714,7 @@ static const struct mv88e6xxx_ops mv88e6175_ops = { .port_disable_pri_override = mv88e6xxx_port_disable_pri_override, .port_get_cmode = mv88e6352_port_get_cmode, .port_setup_message_port = mv88e6xxx_setup_message_port, - .stats_snapshot = mv88e6320_g1_stats_snapshot, + .stats_snapshot = mv88e6xxx_g1_stats_snapshot, .stats_set_histogram = mv88e6095_g1_stats_set_histogram, .stats_get_sset_count = mv88e6095_stats_get_sset_count, .stats_get_strings = mv88e6095_stats_get_strings, @@ -5380,7 +5380,7 @@ static const struct mv88e6xxx_ops mv88e6350_ops = { .port_disable_pri_override = mv88e6xxx_port_disable_pri_override, .port_get_cmode = mv88e6352_port_get_cmode, .port_setup_message_port = mv88e6xxx_setup_message_port, - .stats_snapshot = mv88e6320_g1_stats_snapshot, + .stats_snapshot = mv88e6xxx_g1_stats_snapshot, .stats_set_histogram = mv88e6095_g1_stats_set_histogram, .stats_get_sset_count = mv88e6095_stats_get_sset_count, .stats_get_strings = mv88e6095_stats_get_strings, @@ -5426,7 +5426,7 @@ static const struct mv88e6xxx_ops mv88e6351_ops = { .port_disable_pri_override = mv88e6xxx_port_disable_pri_override, .port_get_cmode = mv88e6352_port_get_cmode, .port_setup_message_port = mv88e6xxx_setup_message_port, - .stats_snapshot = mv88e6320_g1_stats_snapshot, + .stats_snapshot = mv88e6xxx_g1_stats_snapshot, .stats_set_histogram = mv88e6095_g1_stats_set_histogram, .stats_get_sset_count = mv88e6095_stats_get_sset_count, .stats_get_strings = mv88e6095_stats_get_strings, @@ -6022,7 +6022,7 @@ static const struct mv88e6xxx_info mv88e6xxx_table[] = { .age_time_coeff = 15000, .g1_irqs = 9, .g2_irqs = 10, - .stats_type = STATS_TYPE_BANK0 | STATS_TYPE_BANK1, + .stats_type = STATS_TYPE_BANK0 | STATS_TYPE_PORT, .atu_move_port_mask = 0xf, .pvt = true, .multi_chip = true, diff --git a/drivers/net/dsa/yt921x.c b/drivers/net/dsa/yt921x.c index 159b16606f6c..44fcdd47ffb5 100644 --- a/drivers/net/dsa/yt921x.c +++ b/drivers/net/dsa/yt921x.c @@ -198,14 +198,14 @@ static u32 ethaddr_lo2_to_u32(const unsigned char *addr) static int yt921x_reg_read(struct yt921x_priv *priv, u32 reg, u32 *valp) { - WARN_ON(!mutex_is_locked(&priv->reg_lock)); + lockdep_assert_held_once(&priv->reg_lock); return priv->reg_ops->read(priv->reg_ctx, reg, valp); } static int yt921x_reg_write(struct yt921x_priv *priv, u32 reg, u32 val) { - WARN_ON(!mutex_is_locked(&priv->reg_lock)); + lockdep_assert_held_once(&priv->reg_lock); return priv->reg_ops->write(priv->reg_ctx, reg, val); } diff --git a/drivers/net/ethernet/alacritech/slicoss.c b/drivers/net/ethernet/alacritech/slicoss.c index c1949ca060ca..311a9d1d9071 100644 --- a/drivers/net/ethernet/alacritech/slicoss.c +++ b/drivers/net/ethernet/alacritech/slicoss.c @@ -813,7 +813,7 @@ static int slic_init_stat_queue(struct slic_device *sdev) free_descs: while (i--) { - dma_free_coherent(&sdev->pdev->dev, stq->mem_size, + dma_free_coherent(&sdev->pdev->dev, size, stq->descs[i] - stq->addr_offset[i], stq->paddr[i] - stq->addr_offset[i]); } diff --git a/drivers/net/ethernet/aquantia/atlantic/aq_pci_func.c b/drivers/net/ethernet/aquantia/atlantic/aq_pci_func.c index 005d6ef4fc36..881727c3aa0a 100644 --- a/drivers/net/ethernet/aquantia/atlantic/aq_pci_func.c +++ b/drivers/net/ethernet/aquantia/atlantic/aq_pci_func.c @@ -344,9 +344,9 @@ static void aq_pci_remove(struct pci_dev *pdev) struct aq_nic_s *self = pci_get_drvdata(pdev); if (self->ndev) { - aq_clear_rxnfc_all_rules(self); if (self->ndev->reg_state == NETREG_REGISTERED) unregister_netdev(self->ndev); + aq_clear_rxnfc_all_rules(self); #if IS_ENABLED(CONFIG_MACSEC) aq_macsec_free(self); diff --git a/drivers/net/ethernet/broadcom/asp2/bcmasp.c b/drivers/net/ethernet/broadcom/asp2/bcmasp.c index 972474893a6b..f41a79529f10 100644 --- a/drivers/net/ethernet/broadcom/asp2/bcmasp.c +++ b/drivers/net/ethernet/broadcom/asp2/bcmasp.c @@ -511,6 +511,13 @@ static int bcmasp_netfilt_wr_to_hw(struct bcmasp_priv *priv, return 0; } +static bool bcmasp_netfilt_is_companion(struct bcmasp_priv *priv, int i) +{ + return i > 0 && (i % 2) && + priv->net_filters[i].wake_filter && + priv->net_filters[i - 1].wake_filter; +} + void bcmasp_netfilt_suspend(struct bcmasp_intf *intf) { struct bcmasp_priv *priv = intf->parent; @@ -524,9 +531,7 @@ void bcmasp_netfilt_suspend(struct bcmasp_intf *intf) priv->net_filters[i].port != intf->port) continue; - if (i > 0 && (i % 2) && - priv->net_filters[i].wake_filter && - priv->net_filters[i - 1].wake_filter) + if (bcmasp_netfilt_is_companion(priv, i)) continue; ret = bcmasp_netfilt_wr_to_hw(priv, &priv->net_filters[i]); @@ -556,9 +561,7 @@ int bcmasp_netfilt_get_all_active(struct bcmasp_intf *intf, u32 *rule_locs, priv->net_filters[i].port != intf->port) continue; - if (i > 0 && (i % 2) && - priv->net_filters[i].wake_filter && - priv->net_filters[i - 1].wake_filter) + if (bcmasp_netfilt_is_companion(priv, i)) continue; if (j == *rule_cnt) @@ -583,9 +586,7 @@ int bcmasp_netfilt_get_active(struct bcmasp_intf *intf) continue; /* Skip over a wake filter pair */ - if (i > 0 && (i % 2) && - priv->net_filters[i].wake_filter && - priv->net_filters[i - 1].wake_filter) + if (bcmasp_netfilt_is_companion(priv, i)) continue; cnt++; @@ -607,6 +608,9 @@ bool bcmasp_netfilt_check_dup(struct bcmasp_intf *intf, priv->net_filters[i].port != intf->port) continue; + if (bcmasp_netfilt_is_companion(priv, i)) + continue; + cur = &priv->net_filters[i].fs; if (cur->flow_type != fs->flow_type || @@ -659,7 +663,7 @@ bool bcmasp_netfilt_check_dup(struct bcmasp_intf *intf, } /* If no network filter found, return open filter. - * If no more open filters return NULL + * If no more open filters return error. */ struct bcmasp_net_filter *bcmasp_netfilt_get_init(struct bcmasp_intf *intf, u32 loc, bool wake_filter, @@ -669,45 +673,55 @@ struct bcmasp_net_filter *bcmasp_netfilt_get_init(struct bcmasp_intf *intf, struct bcmasp_priv *priv = intf->parent; int i, open_index = -1; - /* Check whether we exceed the filter table capacity */ + if (!init) { + if (loc == RX_CLS_LOC_ANY || loc >= priv->num_net_filters) + return ERR_PTR(-EINVAL); + + if (priv->net_filters[loc].claimed && + priv->net_filters[loc].port == intf->port && + !bcmasp_netfilt_is_companion(priv, loc)) + return &priv->net_filters[loc]; + + return ERR_PTR(-ENOENT); + } + if (loc != RX_CLS_LOC_ANY && loc >= priv->num_net_filters) return ERR_PTR(-EINVAL); /* If the filter location is busy (already claimed) and we are initializing * the filter (insertion), return a busy error code. */ - if (loc != RX_CLS_LOC_ANY && init && priv->net_filters[loc].claimed) - return ERR_PTR(-EBUSY); - - /* We need two filters for wake-up, so we cannot use an odd filter */ - if (wake_filter && loc != RX_CLS_LOC_ANY && (loc % 2)) - return ERR_PTR(-EINVAL); - - /* Initialize the loop index based on the desired location or from 0 */ - i = loc == RX_CLS_LOC_ANY ? 0 : loc; - - for ( ; i < priv->num_net_filters; i++) { - /* Found matching network filter */ - if (!init && - priv->net_filters[i].claimed && - priv->net_filters[i].hw_index == i && - priv->net_filters[i].port == intf->port) - return &priv->net_filters[i]; - - /* If we don't need a new filter or new filter already found */ - if (!init || open_index >= 0) - continue; - - /* Wake filter conslidates two filters to cover more bytes - * Wake filter is open if... - * 1. It is an even filter - * 2. The current and next filter is not claimed - */ - if (wake_filter && !(i % 2) && !priv->net_filters[i].claimed && - !priv->net_filters[i + 1].claimed) - open_index = i; - else if (!priv->net_filters[i].claimed) - open_index = i; + if (loc != RX_CLS_LOC_ANY) { + if (priv->net_filters[loc].claimed) + return ERR_PTR(-EBUSY); + + /* We need two filters for wake-up, so we cannot use an odd filter */ + if (wake_filter) { + if ((loc % 2) || loc + 1 >= priv->num_net_filters) + return ERR_PTR(-EINVAL); + if (priv->net_filters[loc + 1].claimed) + return ERR_PTR(-EBUSY); + } + open_index = loc; + } else { + for (i = 0; i < priv->num_net_filters; i++) { + /* Wake filter consolidates two filters to cover more bytes. + * Wake filter is open if: + * 1. It is an even filter + * 2. The current and next filter is not claimed + */ + if (wake_filter) { + if (!(i % 2) && (i + 1 < priv->num_net_filters) && + !priv->net_filters[i].claimed && + !priv->net_filters[i + 1].claimed) { + open_index = i; + break; + } + } else if (!priv->net_filters[i].claimed) { + open_index = i; + break; + } + } } if (open_index >= 0) { @@ -716,16 +730,20 @@ struct bcmasp_net_filter *bcmasp_netfilt_get_init(struct bcmasp_intf *intf, nfilter->port = intf->port; nfilter->ch = intf->channel + priv->tx_chan_offset; nfilter->hw_index = open_index; - } - if (wake_filter && open_index >= 0) { - /* Claim next filter */ - priv->net_filters[open_index + 1].claimed = true; - priv->net_filters[open_index + 1].wake_filter = true; - nfilter->wake_filter = true; + if (wake_filter) { + /* Claim next filter */ + priv->net_filters[open_index + 1].claimed = true; + priv->net_filters[open_index + 1].wake_filter = true; + priv->net_filters[open_index + 1].hw_index = open_index + 1; + priv->net_filters[open_index + 1].port = intf->port; + priv->net_filters[open_index + 1].ch = intf->channel + + priv->tx_chan_offset; + nfilter->wake_filter = true; + } } - return nfilter ? nfilter : ERR_PTR(-EINVAL); + return nfilter ? nfilter : ERR_PTR(-ENOSPC); } void bcmasp_netfilt_release(struct bcmasp_intf *intf, @@ -733,7 +751,8 @@ void bcmasp_netfilt_release(struct bcmasp_intf *intf, { struct bcmasp_priv *priv = intf->parent; - if (nfilt->wake_filter) { + if (nfilt->wake_filter && !(nfilt->hw_index % 2) && + nfilt->hw_index + 1 < priv->num_net_filters) { memset(&priv->net_filters[nfilt->hw_index + 1], 0, sizeof(struct bcmasp_net_filter)); } diff --git a/drivers/net/ethernet/broadcom/asp2/bcmasp.h b/drivers/net/ethernet/broadcom/asp2/bcmasp.h index 8c8ffaeadc79..9c9721da1662 100644 --- a/drivers/net/ethernet/broadcom/asp2/bcmasp.h +++ b/drivers/net/ethernet/broadcom/asp2/bcmasp.h @@ -250,10 +250,6 @@ struct bcmasp_intf_stats64 { }; struct bcmasp_mib_counters { - u32 edpkt_ts; - u32 edpkt_rx_pkt_cnt; - u32 edpkt_hdr_ext_cnt; - u32 edpkt_hdr_out_cnt; u32 umac_frm_cnt; u32 fb_frm_cnt; u32 fb_rx_fifo_depth; diff --git a/drivers/net/ethernet/broadcom/asp2/bcmasp_intf.c b/drivers/net/ethernet/broadcom/asp2/bcmasp_intf.c index f2176ef3a127..a855e637b6f0 100644 --- a/drivers/net/ethernet/broadcom/asp2/bcmasp_intf.c +++ b/drivers/net/ethernet/broadcom/asp2/bcmasp_intf.c @@ -236,7 +236,7 @@ static struct sk_buff *bcmasp_csum_offload(struct net_device *dev, static netdev_tx_t bcmasp_xmit(struct sk_buff *skb, struct net_device *dev) { struct bcmasp_intf *intf = netdev_priv(dev); - unsigned int total_bytes, size; + unsigned int total_bytes, size, min_size; int spb_index, nr_frags, i, j; struct bcmasp_tx_cb *txcb; dma_addr_t mapping, valid; @@ -262,16 +262,21 @@ static netdev_tx_t bcmasp_xmit(struct sk_buff *skb, struct net_device *dev) if (!skb) return NETDEV_TX_OK; + min_size = ETH_ZLEN + ETH_FCS_LEN; + if (csum_hw) + min_size += sizeof(struct bcmasp_pkt_offload); + + if (skb->len < min_size) { + if (skb_put_padto(skb, min_size)) + return NETDEV_TX_OK; + nr_frags = skb_shinfo(skb)->nr_frags; + } + spb_index = intf->tx_spb_index; valid = intf->tx_spb_dma_valid; for (i = 0; i <= nr_frags; i++) { if (!i) { size = skb_headlen(skb); - if (!nr_frags && size < (ETH_ZLEN + ETH_FCS_LEN)) { - if (skb_put_padto(skb, ETH_ZLEN + ETH_FCS_LEN)) - return NETDEV_TX_OK; - size = skb->len; - } mapping = dma_map_single(kdev, skb->data, size, DMA_TO_DEVICE); } else { @@ -285,6 +290,11 @@ static netdev_tx_t bcmasp_xmit(struct sk_buff *skb, struct net_device *dev) intf->mib.tx_dma_failed++; spb_index = intf->tx_spb_index; for (j = 0; j < i; j++) { + txcb = &intf->tx_cbs[spb_index]; + dma_unmap_single(kdev, + dma_unmap_addr(txcb, dma_addr), + dma_unmap_len(txcb, dma_len), + DMA_TO_DEVICE); bcmasp_clean_txcb(intf, spb_index); spb_index = incr_ring(spb_index, DESC_RING_COUNT); @@ -518,6 +528,12 @@ static int bcmasp_rx_poll(struct napi_struct *napi, int budget) DMA_FROM_DEVICE); len = desc->size; + if (unlikely(len < 2 + ETH_HLEN + (intf->crc_fwd ? ETH_FCS_LEN : 0))) { + u64_stats_update_begin(&stats->syncp); + u64_stats_inc(&stats->rx_dropped); + u64_stats_update_end(&stats->syncp); + goto next; + } /* Allocate a page pool page as the SKB data area so the * kernel can recycle it efficiently after the packet is @@ -1287,7 +1303,7 @@ struct bcmasp_intf *bcmasp_interface_create(struct bcmasp_priv *priv, ndev_dn->name); goto err_free_netdev; } - intf->phy_dn = ndev_dn; + intf->phy_dn = of_node_get(ndev_dn); } /* Map resource */ @@ -1327,6 +1343,7 @@ struct bcmasp_intf *bcmasp_interface_create(struct bcmasp_priv *priv, err_deregister_fixed_link: if (of_phy_is_fixed_link(ndev_dn)) of_phy_deregister_fixed_link(ndev_dn); + of_node_put(intf->phy_dn); err_free_netdev: free_netdev(ndev); err: @@ -1339,6 +1356,7 @@ void bcmasp_interface_destroy(struct bcmasp_intf *intf) unregister_netdev(intf->ndev); if (of_phy_is_fixed_link(intf->ndev_dn)) of_phy_deregister_fixed_link(intf->ndev_dn); + of_node_put(intf->phy_dn); free_netdev(intf->ndev); } diff --git a/drivers/net/ethernet/broadcom/bgmac.c b/drivers/net/ethernet/broadcom/bgmac.c index 1835266fdd09..b3f0ecc583fd 100644 --- a/drivers/net/ethernet/broadcom/bgmac.c +++ b/drivers/net/ethernet/broadcom/bgmac.c @@ -208,19 +208,24 @@ static netdev_tx_t bgmac_dma_tx_add(struct bgmac *bgmac, return NETDEV_TX_OK; err_dma: - dma_unmap_single(dma_dev, slot->dma_addr, skb_headlen(skb), - DMA_TO_DEVICE); + slot->dma_addr = 0; while (i-- > 0) { - int index = (ring->end + i) % BGMAC_TX_RING_SLOTS; - struct bgmac_slot_info *slot = &ring->slots[index]; - u32 ctl1 = le32_to_cpu(ring->cpu_base[index].ctl1); - int len = ctl1 & BGMAC_DESC_CTL1_LEN; - - dma_unmap_page(dma_dev, slot->dma_addr, len, DMA_TO_DEVICE); + index = (ring->end + 1 + i) % BGMAC_TX_RING_SLOTS; + slot = &ring->slots[index]; + dma_unmap_page(dma_dev, slot->dma_addr, + skb_frag_size(&skb_shinfo(skb)->frags[i]), + DMA_TO_DEVICE); + slot->dma_addr = 0; } + slot = &ring->slots[ring->end % BGMAC_TX_RING_SLOTS]; + dma_unmap_single(dma_dev, slot->dma_addr, skb_headlen(skb), + DMA_TO_DEVICE); + err_dma_head: + slot->dma_addr = 0; + netdev_err(bgmac->net_dev, "Mapping error of skb on ring 0x%X\n", ring->mmio_base); @@ -535,17 +540,25 @@ static void bgmac_dma_tx_ring_free(struct bgmac *bgmac, unsigned int len = ctl1 & BGMAC_DESC_CTL1_LEN; slot = &ring->slots[i]; - dev_kfree_skb(slot->skb); - if (!slot->dma_addr) - continue; + if (slot->dma_addr) { + if (le32_to_cpu(dma_desc[i].ctl0) & BGMAC_DESC_CTL0_SOF) + dma_unmap_single(dma_dev, slot->dma_addr, + len, DMA_TO_DEVICE); + else + dma_unmap_page(dma_dev, slot->dma_addr, + len, DMA_TO_DEVICE); + slot->dma_addr = 0; + } + } - if (slot->skb) - dma_unmap_single(dma_dev, slot->dma_addr, - len, DMA_TO_DEVICE); - else - dma_unmap_page(dma_dev, slot->dma_addr, - len, DMA_TO_DEVICE); + /* A packet can wrap around the end of the ring with its skb on the + * last slot, so free the skbs only once every slot is unmapped. + */ + for (i = 0; i < BGMAC_TX_RING_SLOTS; i++) { + slot = &ring->slots[i]; + dev_kfree_skb(slot->skb); + slot->skb = NULL; } } diff --git a/drivers/net/ethernet/broadcom/bnge/bnge_netdev.c b/drivers/net/ethernet/broadcom/bnge/bnge_netdev.c index a4288f0258f8..92aea6f6f09f 100644 --- a/drivers/net/ethernet/broadcom/bnge/bnge_netdev.c +++ b/drivers/net/ethernet/broadcom/bnge/bnge_netdev.c @@ -2182,19 +2182,21 @@ static bool bnge_uc_list_updated(struct bnge_net *bn, const struct netdev_hw_addr_list *uc) { 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_hw_addr_list_count(uc) != (vnic->uc_filter_count - 1)) - return true; + int off = 0, count = 0; netdev_hw_addr_list_for_each(ha, uc) { + 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) @@ -2207,9 +2209,9 @@ static int bnge_cfg_rx_mode(struct bnge_net *bn, struct netdev_hw_addr_list *uc, { 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; if (!uc_update) goto skip_uc; @@ -2225,10 +2227,20 @@ static int bnge_cfg_rx_mode(struct bnge_net *bn, struct netdev_hw_addr_list *uc, if (!snapshot) netif_addr_lock_bh(dev); - if (netdev_hw_addr_list_count(uc) > (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_hw_addr_list_for_each(ha, uc) + 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_hw_addr_list_for_each(ha, uc) { + 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/bnge/bnge_resc.c b/drivers/net/ethernet/broadcom/bnge/bnge_resc.c index 4711dd4945ff..b540eed12fc6 100644 --- a/drivers/net/ethernet/broadcom/bnge/bnge_resc.c +++ b/drivers/net/ethernet/broadcom/bnge/bnge_resc.c @@ -182,8 +182,9 @@ int bnge_cal_nr_rss_ctxs(u16 rx_rings) if (!rx_rings) return 0; - return bnge_adjust_pow_two(rx_rings - 1, - BNGE_RSS_TABLE_ENTRIES); + return min_t(int, bnge_adjust_pow_two(rx_rings - 1, + BNGE_RSS_TABLE_ENTRIES), + BNGE_RSS_TABLE_MAX_TBL); } static u16 bnge_rss_ctxs_in_use(struct bnge_dev *bd, @@ -459,6 +460,7 @@ static void _bnge_get_max_rings(struct bnge_dev *bd, u16 *max_rx, } *max_rx = min_t(int, *max_rx, max_ring_grps); + *max_rx = min_t(int, *max_rx, BNGE_MAX_RSS_TABLE_ENTRIES); } static int bnge_get_max_rings(struct bnge_dev *bd, u16 *max_rx, diff --git a/drivers/net/ethernet/broadcom/bnge/bnge_resc.h b/drivers/net/ethernet/broadcom/bnge/bnge_resc.h index b62a634669f6..c0b6992d7f82 100644 --- a/drivers/net/ethernet/broadcom/bnge/bnge_resc.h +++ b/drivers/net/ethernet/broadcom/bnge/bnge_resc.h @@ -81,13 +81,10 @@ bnge_adjust_pow_two(u32 total_ent, u16 ent_per_blk) { u32 blks = total_ent / ent_per_blk; - if (blks == 0 || blks == 1) - return ++blks; + if (!blks) + return 1; - if (!is_power_of_2(blks)) - blks = roundup_pow_of_two(blks); - - return blks; + return roundup_pow_of_two(blks + 1); } #define BNGE_MAX_ROCE_MSIX 64 diff --git a/drivers/net/ethernet/broadcom/bnge/bnge_txrx.c b/drivers/net/ethernet/broadcom/bnge/bnge_txrx.c index 7d45e057f2e8..472b02cc43b3 100644 --- a/drivers/net/ethernet/broadcom/bnge/bnge_txrx.c +++ b/drivers/net/ethernet/broadcom/bnge/bnge_txrx.c @@ -1490,6 +1490,9 @@ netdev_tx_t bnge_start_xmit(struct sk_buff *skb, struct net_device *dev) return NETDEV_TX_BUSY; } + if (eth_skb_pad(skb)) + goto tx_kick_pending; + last_frag = skb_shinfo(skb)->nr_frags; txbd = &txr->tx_desc_ring[TX_RING(bn, prod)][TX_IDX(prod)]; @@ -1513,9 +1516,6 @@ netdev_tx_t bnge_start_xmit(struct sk_buff *skb, struct net_device *dev) if (unlikely(skb->no_fcs)) lflags |= cpu_to_le32(TX_BD_FLAGS_NO_CRC); - if (eth_skb_pad(skb)) - goto tx_kick_pending; - len = skb_headlen(skb); mapping = dma_map_single(bd->dev, skb->data, len, DMA_TO_DEVICE); diff --git a/drivers/net/ethernet/broadcom/bnx2x/bnx2x_cmn.c b/drivers/net/ethernet/broadcom/bnx2x/bnx2x_cmn.c index 5a9742fd3ddf..6fb0619731ae 100644 --- a/drivers/net/ethernet/broadcom/bnx2x/bnx2x_cmn.c +++ b/drivers/net/ethernet/broadcom/bnx2x/bnx2x_cmn.c @@ -3666,7 +3666,8 @@ static void bnx2x_update_pbds_gso_enc(struct sk_buff *skb, u8 outerip_off, outerip_len = 0; /* from outer IP to transport */ - hlen_w = skb_inner_transport_offset(skb) >> 1; + hlen_w = (skb_inner_transport_offset(skb) - + skb_network_offset(skb)) >> 1; /* transport len */ hlen_w += inner_tcp_hdrlen(skb) >> 1; diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt.c b/drivers/net/ethernet/broadcom/bnxt/bnxt.c index 15a8349ccf7b..1fd6a676085b 100644 --- a/drivers/net/ethernet/broadcom/bnxt/bnxt.c +++ b/drivers/net/ethernet/broadcom/bnxt/bnxt.c @@ -1215,7 +1215,15 @@ static struct sk_buff *bnxt_rx_multi_page_skb(struct bnxt *bp, bp->rx_dir); skb = napi_build_skb(frag_start, rxr->rx_page_size); if (!skb) { - page_pool_recycle_direct(rxr->page_pool, page); + struct page *new_page; + + new_page = rxr->rx_buf_ring[RING_RX(bp, prod)].data; + /* The caller may still need the XDP frags from shinfo at the + * end of the head page. Release the new buffer instead and + * put the head back on the ring. + */ + page_pool_recycle_direct(rxr->page_pool, new_page); + bnxt_reuse_rx_data(rxr, cons, data); return NULL; } skb_mark_for_recycle(skb); @@ -1419,16 +1427,19 @@ static u32 bnxt_rx_agg_netmems_xdp(struct bnxt *bp, struct skb_shared_info *shinfo = xdp_get_shared_info_from_buff(xdp); u32 total_frag_len = 0; - if (!xdp_buff_has_frags(xdp)) + if (!xdp_buff_has_frags(xdp)) { + xdp_buff_set_frags_flag(xdp); shinfo->nr_frags = 0; + } total_frag_len = __bnxt_rx_agg_netmems(bp, cpr, idx, agg_bufs, tpa, NULL, xdp); - if (total_frag_len) { - xdp_buff_set_frags_flag(xdp); - shinfo->nr_frags = agg_bufs; - shinfo->xdp_frags_size = total_frag_len; + if (!total_frag_len) { + bnxt_xdp_buff_frags_free(cpr->bnapi->rx_ring, xdp); + return 0; } + shinfo->nr_frags = agg_bufs; + shinfo->xdp_frags_size = total_frag_len; return total_frag_len; } @@ -1500,6 +1511,14 @@ static struct sk_buff *bnxt_copy_xdp(struct bnxt_napi *bnapi, __skb_pull(skb, metasize); } + if (unlikely(xdp_buff_has_frags(xdp))) { + struct skb_shared_info *sinfo; + + sinfo = xdp_get_shared_info_from_buff(xdp); + memcpy(skb_shinfo(skb)->frags, sinfo->frags, + sinfo->nr_frags * sizeof(skb_frag_t)); + } + return skb; } @@ -2285,8 +2304,10 @@ static int bnxt_rx_pkt(struct bnxt *bp, struct bnxt_cp_ring_info *cpr, cp_cons, agg_bufs, false); - if (!frag_len) + if (!frag_len) { + bnxt_reuse_rx_data(rxr, cons, data); goto oom_next_rx; + } } xdp_active = true; @@ -2313,17 +2334,8 @@ static int bnxt_rx_pkt(struct bnxt *bp, struct bnxt_cp_ring_info *cpr, skb = bnxt_copy_xdp(bnapi, &bnxt_xdp.xdp, len, dma_addr); bnxt_reuse_rx_data(rxr, cons, data); - if (!skb) { - if (agg_bufs) { - if (!xdp_active) - bnxt_reuse_rx_agg_bufs(cpr, cp_cons, 0, - agg_bufs, false); - else - bnxt_xdp_buff_frags_free(rxr, - &bnxt_xdp.xdp); - } - goto oom_next_rx; - } + if (!skb) + goto oom_next_rx_agg; } else { u32 payload; @@ -2334,7 +2346,7 @@ static int bnxt_rx_pkt(struct bnxt *bp, struct bnxt_cp_ring_info *cpr, skb = bp->rx_skb_func(bp, rxr, cons, data, data_ptr, dma_addr, payload | len); if (!skb) - goto oom_next_rx; + goto oom_next_rx_agg; } if (agg_bufs) { @@ -2424,6 +2436,14 @@ static int bnxt_rx_pkt(struct bnxt *bp, struct bnxt_cp_ring_info *cpr, return rc; +oom_next_rx_agg: + if (agg_bufs) { + if (!xdp_active) + bnxt_reuse_rx_agg_bufs(cpr, cp_cons, 0, agg_bufs, + false); + else + bnxt_xdp_buff_frags_free(rxr, &bnxt_xdp.xdp); + } oom_next_rx: cpr->sw_stats->rx.rx_oom_discards += 1; rc = -ENOMEM; diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt_ethtool.c b/drivers/net/ethernet/broadcom/bnxt/bnxt_ethtool.c index 622e89587e5d..ef4bea4a0f8c 100644 --- a/drivers/net/ethernet/broadcom/bnxt/bnxt_ethtool.c +++ b/drivers/net/ethernet/broadcom/bnxt/bnxt_ethtool.c @@ -4601,6 +4601,7 @@ static int bnxt_set_tunable(struct net_device *dev, if (netif_running(dev)) return -EBUSY; bp->rx_copybreak = rx_copybreak; + bnxt_set_ring_params(bp); } return 0; case ETHTOOL_PFC_PREVENTION_TOUT: diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt_xdp.c b/drivers/net/ethernet/broadcom/bnxt/bnxt_xdp.c index 96845c8646e0..161e0dd62be6 100644 --- a/drivers/net/ethernet/broadcom/bnxt/bnxt_xdp.c +++ b/drivers/net/ethernet/broadcom/bnxt/bnxt_xdp.c @@ -307,6 +307,7 @@ bool bnxt_rx_xdp(struct bnxt *bp, struct bnxt_rx_ring_info *rxr, u16 cons, if (xdp_do_redirect(bp->dev, xdp, xdp_prog)) { trace_xdp_exception(bp->dev, xdp_prog, act); + bnxt_xdp_buff_frags_free(rxr, xdp); page_pool_recycle_direct(rxr->page_pool, page); return true; } diff --git a/drivers/net/ethernet/broadcom/genet/bcmgenet.c b/drivers/net/ethernet/broadcom/genet/bcmgenet.c index f4cfbff49a1b..f258997f20a9 100644 --- a/drivers/net/ethernet/broadcom/genet/bcmgenet.c +++ b/drivers/net/ethernet/broadcom/genet/bcmgenet.c @@ -931,10 +931,13 @@ static int bcmgenet_set_coalesce(struct net_device *dev, /* Program all TX queues with the same values, as there is no * ethtool knob to do coalescing on a per-queue basis */ - for (i = 0; i <= priv->hw_params->tx_queues; i++) + for (i = 0; i <= priv->hw_params->tx_queues; i++) { + priv->tx_rings[i].tx_max_coalesced_frames = + ec->tx_max_coalesced_frames; bcmgenet_tdma_ring_writel(priv, i, ec->tx_max_coalesced_frames, DMA_MBUF_DONE_THRESH); + } for (i = 0; i <= priv->hw_params->rx_queues; i++) bcmgenet_set_ring_rx_coalesce(&priv->rx_rings[i], ec); @@ -2758,7 +2761,8 @@ static void bcmgenet_init_tx_ring(struct bcmgenet_priv *priv, bcmgenet_tdma_ring_writel(priv, index, 0, TDMA_PROD_INDEX); bcmgenet_tdma_ring_writel(priv, index, 0, TDMA_CONS_INDEX); - bcmgenet_tdma_ring_writel(priv, index, 1, DMA_MBUF_DONE_THRESH); + bcmgenet_tdma_ring_writel(priv, index, ring->tx_max_coalesced_frames, + DMA_MBUF_DONE_THRESH); /* Disable rate control for now */ bcmgenet_tdma_ring_writel(priv, index, flow_period_val, TDMA_FLOW_PERIOD); @@ -3117,7 +3121,9 @@ static void bcmgenet_fini_dma(struct bcmgenet_priv *priv) bcmgenet_free_rx_buffers(priv); bcmgenet_destroy_rx_page_pools(priv); kfree(priv->rx_cbs); + priv->rx_cbs = NULL; kfree(priv->tx_cbs); + priv->tx_cbs = NULL; } /* init_edma: Initialize DMA control register */ @@ -3175,6 +3181,7 @@ static int bcmgenet_init_dma(struct bcmgenet_priv *priv, bool flush_rx) priv->tx_cbs = kzalloc_objs(struct enet_cb, priv->num_tx_bds); if (!priv->tx_cbs) { kfree(priv->rx_cbs); + priv->rx_cbs = NULL; return -ENOMEM; } @@ -3194,7 +3201,9 @@ static int bcmgenet_init_dma(struct bcmgenet_priv *priv, bool flush_rx) bcmgenet_free_rx_buffers(priv); bcmgenet_destroy_rx_page_pools(priv); kfree(priv->rx_cbs); + priv->rx_cbs = NULL; kfree(priv->tx_cbs); + priv->tx_cbs = NULL; return ret; } @@ -3503,7 +3512,9 @@ static int bcmgenet_close(struct net_device *dev) netif_dbg(priv, ifdown, dev, "bcmgenet_close\n"); - bcmgenet_netif_stop(dev, false); + /* A failed resume has torn the datapath down already */ + if (priv->tx_cbs) + bcmgenet_netif_stop(dev, false); /* Really kill the PHY state machine and disconnect from it */ phy_disconnect(dev->phydev); @@ -3511,6 +3522,9 @@ static int bcmgenet_close(struct net_device *dev) free_irq(priv->irq0, priv); free_irq(priv->irq1, priv); + /* A failed resume left the device detached, __dev_open() refuses that */ + netif_device_attach(dev); + if (priv->internal_phy) ret = bcmgenet_power_down(priv, GENET_POWER_PASSIVE); @@ -4166,6 +4180,8 @@ static int bcmgenet_probe(struct platform_device *pdev) priv->rx_rings[i].index = i; priv->rx_rings[i].rx_max_coalesced_frames = 1; } + for (i = 0; i <= priv->hw_params->tx_queues; i++) + priv->tx_rings[i].tx_max_coalesced_frames = 1; /* Initialize u64 stats seq counter for 32bit machines */ for (i = 0; i <= GENET_MAX_MQ_CNT; i++) { @@ -4268,7 +4284,11 @@ static int bcmgenet_resume(struct device *d) if (device_may_wakeup(d) && priv->wolopts) { reg = bcmgenet_umac_readl(priv, UMAC_CMD); - if (reg & CMD_RX_EN) { + + /* The WoL power down sets CMD_RX_EN itself, so the bit + * alone does not mean the rings survived + */ + if (priv->tx_cbs && (reg & CMD_RX_EN)) { /* Successfully exited WoL, just resume data flows */ list_for_each_entry(rule, &priv->rxnfc_list, list) if (rule->state == BCMGENET_RXNFC_STATE_ENABLED) @@ -4298,6 +4318,9 @@ static int bcmgenet_resume(struct device *d) bcmgenet_rdma_disable(priv); bcmgenet_intr_disable(priv); bcmgenet_fini_dma(priv); + if (phy_is_started(dev->phydev) || + dev->phydev->state == PHY_ERROR) + phy_stop(dev->phydev); enable_irq(priv->irq1); } @@ -4320,8 +4343,9 @@ static int bcmgenet_resume(struct device *d) /* Reinitialize TDMA and RDMA and SW housekeeping */ ret = bcmgenet_init_dma(priv, false); if (ret) { + /* Leave the block clocked, close and suspend tear it down */ netdev_err(dev, "failed to initialize DMA\n"); - goto out_clk_disable; + return ret; } if (!device_may_wakeup(d)) @@ -4332,24 +4356,57 @@ static int bcmgenet_resume(struct device *d) netif_device_attach(dev); return 0; +} -out_clk_disable: - if (priv->internal_phy) - bcmgenet_power_down(priv, GENET_POWER_PASSIVE); - clk_disable_unprepare(priv->clk); - return ret; +/* Arm the configured wake filters and drop the rest, then clear old + * matches so that only a new one wakes the system + */ +static void bcmgenet_wol_arm_filters(struct bcmgenet_priv *priv) +{ + struct bcmgenet_rxnfc_rule *rule; + u32 reg, hfb_enable = 0; + + if (priv->wolopts & WAKE_FILTER) + list_for_each_entry(rule, &priv->rxnfc_list, list) + if (rule->fs.ring_cookie == RX_CLS_FLOW_WAKE && + rule->state == BCMGENET_RXNFC_STATE_ENABLED) + hfb_enable |= 1 << rule->fs.location; + + reg = bcmgenet_hfb_reg_readl(priv, HFB_CTRL); + if (GENET_IS_V1(priv) || GENET_IS_V2(priv)) { + reg &= ~RBUF_HFB_FILTER_EN_MASK; + reg |= hfb_enable << (RBUF_HFB_FILTER_EN_SHIFT + 1); + } else { + bcmgenet_hfb_reg_writel(priv, hfb_enable << 1, + HFB_FLT_ENABLE_V3PLUS + 4); + } + if (!hfb_enable) + reg &= ~RBUF_HFB_EN; + bcmgenet_hfb_reg_writel(priv, reg, HFB_CTRL); + + bcmgenet_intrl2_0_writel(priv, 0xFFFFFFFF, INTRL2_CPU_MASK_SET); + bcmgenet_intrl2_0_writel(priv, 0xFFFFFFFF, INTRL2_CPU_CLEAR); } static int bcmgenet_suspend(struct device *d) { struct net_device *dev = dev_get_drvdata(d); struct bcmgenet_priv *priv = netdev_priv(dev); - struct bcmgenet_rxnfc_rule *rule; - u32 reg, hfb_enable = 0; if (!netif_running(dev)) return 0; + /* A failed resume has torn the datapath down already. Resume still + * enables irq1 on the WoL path, so it has to be disabled here. + */ + if (!priv->tx_cbs) { + if (device_may_wakeup(d) && priv->wolopts) { + bcmgenet_wol_arm_filters(priv); + disable_irq(priv->irq1); + } + return 0; + } + netif_device_detach(dev); if (device_may_wakeup(d) && priv->wolopts) { @@ -4358,26 +4415,7 @@ static int bcmgenet_suspend(struct device *d) netif_tx_disable(dev); /* Suspend non-wake Rx data flows */ - if (priv->wolopts & WAKE_FILTER) - list_for_each_entry(rule, &priv->rxnfc_list, list) - if (rule->fs.ring_cookie == RX_CLS_FLOW_WAKE && - rule->state == BCMGENET_RXNFC_STATE_ENABLED) - hfb_enable |= 1 << rule->fs.location; - reg = bcmgenet_hfb_reg_readl(priv, HFB_CTRL); - if (GENET_IS_V1(priv) || GENET_IS_V2(priv)) { - reg &= ~RBUF_HFB_FILTER_EN_MASK; - reg |= hfb_enable << (RBUF_HFB_FILTER_EN_SHIFT + 1); - } else { - bcmgenet_hfb_reg_writel(priv, hfb_enable << 1, - HFB_FLT_ENABLE_V3PLUS + 4); - } - if (!hfb_enable) - reg &= ~RBUF_HFB_EN; - bcmgenet_hfb_reg_writel(priv, reg, HFB_CTRL); - - /* Clear any old filter matches so only new matches wake */ - bcmgenet_intrl2_0_writel(priv, 0xFFFFFFFF, INTRL2_CPU_MASK_SET); - bcmgenet_intrl2_0_writel(priv, 0xFFFFFFFF, INTRL2_CPU_CLEAR); + bcmgenet_wol_arm_filters(priv); if (-ETIMEDOUT == bcmgenet_tdma_disable(priv)) netdev_warn(priv->dev, diff --git a/drivers/net/ethernet/broadcom/genet/bcmgenet.h b/drivers/net/ethernet/broadcom/genet/bcmgenet.h index 86f2aed20dbe..e48ce39d3e7c 100644 --- a/drivers/net/ethernet/broadcom/genet/bcmgenet.h +++ b/drivers/net/ethernet/broadcom/genet/bcmgenet.h @@ -553,6 +553,7 @@ struct bcmgenet_tx_ring { unsigned int prod_index; /* Tx ring producer index SW copy */ unsigned int cb_ptr; /* Tx ring initial CB ptr */ unsigned int end_ptr; /* Tx ring end CB ptr */ + unsigned int tx_max_coalesced_frames; struct bcmgenet_priv *priv; }; diff --git a/drivers/net/ethernet/cadence/macb.h b/drivers/net/ethernet/cadence/macb.h index d6931c41f39d..c23fd4082987 100644 --- a/drivers/net/ethernet/cadence/macb.h +++ b/drivers/net/ethernet/cadence/macb.h @@ -1493,7 +1493,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. @@ -1502,7 +1501,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 261a7e87520a..ab9f6f25cd6a 100644 --- a/drivers/net/ethernet/cadence/macb_main.c +++ b/drivers/net/ethernet/cadence/macb_main.c @@ -4336,7 +4336,7 @@ static int macb_taprio_setup_replace(struct net_device *netdev, struct macb_queue *queue; u32 queue_mask; u8 queue_id; - size_t i; + size_t i, q; int err; if (conf->num_entries > bp->num_queues) { @@ -4364,7 +4364,7 @@ static int macb_taprio_setup_replace(struct net_device *netdev, return -EINVAL; } - enst_queue = kzalloc_objs(*enst_queue, conf->num_entries); + enst_queue = kzalloc_objs(*enst_queue, bp->num_queues); if (unlikely(!enst_queue)) return -ENOMEM; @@ -4423,13 +4423,12 @@ static int macb_taprio_setup_replace(struct net_device *netdev, goto cleanup; } - enst_queue[i].queue_id = queue_id; - enst_queue[i].start_time_mask = + 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; @@ -4455,15 +4454,14 @@ static int macb_taprio_setup_replace(struct net_device *netdev, gem_writel(bp, ENST_CONTROL, 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/freescale/dpaa2/dpaa2-ptp.c b/drivers/net/ethernet/freescale/dpaa2/dpaa2-ptp.c index 4497e3c0456d..ac2b873dcf8e 100644 --- a/drivers/net/ethernet/freescale/dpaa2/dpaa2-ptp.c +++ b/drivers/net/ethernet/freescale/dpaa2/dpaa2-ptp.c @@ -78,6 +78,7 @@ static const struct ptp_clock_info dpaa2_ptp_caps = { .n_per_out = 3, .n_pins = 0, .pps = 1, + .supported_extts_flags = PTP_RISING_EDGE | PTP_STRICT_FLAGS, .adjfine = ptp_qoriq_adjfine, .adjtime = ptp_qoriq_adjtime, .gettime64 = ptp_qoriq_gettime, diff --git a/drivers/net/ethernet/freescale/enetc/enetc_ptp.c b/drivers/net/ethernet/freescale/enetc/enetc_ptp.c index 162cbc801730..5ffee882d624 100644 --- a/drivers/net/ethernet/freescale/enetc/enetc_ptp.c +++ b/drivers/net/ethernet/freescale/enetc/enetc_ptp.c @@ -16,6 +16,7 @@ static struct ptp_clock_info enetc_ptp_caps = { .n_per_out = 0, .n_pins = 0, .pps = 1, + .supported_extts_flags = PTP_RISING_EDGE | PTP_STRICT_FLAGS, .adjfine = ptp_qoriq_adjfine, .adjtime = ptp_qoriq_adjtime, .gettime64 = ptp_qoriq_gettime, diff --git a/drivers/net/ethernet/hisilicon/hibmcge/hbg_main.c b/drivers/net/ethernet/hisilicon/hibmcge/hbg_main.c index 66792e2b0fad..a518dc66d9ef 100644 --- a/drivers/net/ethernet/hisilicon/hibmcge/hbg_main.c +++ b/drivers/net/ethernet/hisilicon/hibmcge/hbg_main.c @@ -448,6 +448,7 @@ static int hbg_probe(struct pci_dev *pdev, const struct pci_device_id *ent) if (ret) return ret; + netdev->netdev_ops = &hbg_netdev_ops; ret = hbg_init(priv); if (ret) return ret; @@ -460,7 +461,6 @@ static int hbg_probe(struct pci_dev *pdev, const struct pci_device_id *ent) netdev->pcpu_stat_type = NETDEV_PCPU_STAT_TSTATS; netdev->max_mtu = priv->dev_specs.max_mtu; netdev->min_mtu = priv->dev_specs.min_mtu; - netdev->netdev_ops = &hbg_netdev_ops; netdev->watchdog_timeo = 5 * HZ; hbg_hw_set_mtu(priv, ETH_DATA_LEN); diff --git a/drivers/net/ethernet/hisilicon/hix5hd2_gmac.c b/drivers/net/ethernet/hisilicon/hix5hd2_gmac.c index 02282dc86faf..12a5657653f8 100644 --- a/drivers/net/ethernet/hisilicon/hix5hd2_gmac.c +++ b/drivers/net/ethernet/hisilicon/hix5hd2_gmac.c @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -890,8 +891,13 @@ static void hix5hd2_tx_timeout_task(struct work_struct *work) struct hix5hd2_priv *priv; priv = container_of(work, struct hix5hd2_priv, tx_timeout_task); - hix5hd2_net_close(priv->netdev); - hix5hd2_net_open(priv->netdev); + + rtnl_lock(); + if (netif_running(priv->netdev)) { + dev_close(priv->netdev); + dev_open(priv->netdev, NULL); + } + rtnl_unlock(); } static void hix5hd2_net_timeout(struct net_device *dev, unsigned int txqueue) @@ -1283,6 +1289,7 @@ static void hix5hd2_dev_remove(struct platform_device *pdev) struct hix5hd2_priv *priv = netdev_priv(ndev); unregister_netdev(ndev); + cancel_work_sync(&priv->tx_timeout_task); mdiobus_unregister(priv->bus); mdiobus_free(priv->bus); @@ -1290,7 +1297,6 @@ static void hix5hd2_dev_remove(struct platform_device *pdev) hix5hd2_destroy_sg_desc_queue(priv); hix5hd2_destroy_hw_desc_queue(priv); of_node_put(priv->phy_node); - cancel_work_sync(&priv->tx_timeout_task); free_netdev(ndev); } diff --git a/drivers/net/ethernet/ibm/ibmveth.c b/drivers/net/ethernet/ibm/ibmveth.c index abebdb1fc262..e9874dfedf37 100644 --- a/drivers/net/ethernet/ibm/ibmveth.c +++ b/drivers/net/ethernet/ibm/ibmveth.c @@ -135,6 +135,13 @@ static inline int ibmveth_rxq_frame_length(struct ibmveth_adapter *adapter) return be32_to_cpu(adapter->rx_queue.queue_addr[adapter->rx_queue.index].length); } +static u64 ibmveth_rxq_correlator(struct ibmveth_adapter *adapter) +{ + unsigned int idx = adapter->rx_queue.index; + + return READ_ONCE(adapter->rx_queue.queue_addr[idx].correlator); +} + static inline int ibmveth_rxq_csum_good(struct ibmveth_adapter *adapter) { return ibmveth_rxq_flags(adapter) & IBMVETH_RXQ_CSUM_GOOD; @@ -443,6 +450,37 @@ static void ibmveth_free_buffer_pool(struct ibmveth_adapter *adapter, } } +/* The correlator comes back from PHYP; a bad one schedules a reset. */ +static bool ibmveth_rxq_correlator_valid(struct ibmveth_adapter *adapter, + u64 correlator) +{ + unsigned int index = correlator & 0xffffffffUL; + unsigned int pool = correlator >> 32; + + /* An inactive pool keeps its size but has no skbuff array. */ + if (pool < IBMVETH_NUM_BUFF_POOLS && + index < adapter->rx_buff_pool[pool].size && + adapter->rx_buff_pool[pool].skbuff) + return true; + + if (net_ratelimit()) + netdev_err(adapter->netdev, + "invalid RX correlator %llx, resetting\n", + correlator); + schedule_work(&adapter->work); + return false; +} + +static void ibmveth_rxq_no_skb(struct ibmveth_adapter *adapter, + u64 correlator) +{ + if (net_ratelimit()) + netdev_err(adapter->netdev, + "no buffer for RX correlator %llx, resetting\n", + correlator); + schedule_work(&adapter->work); +} + /** * ibmveth_remove_buffer_from_pool - remove a buffer from a pool * @adapter: adapter instance @@ -451,7 +489,8 @@ static void ibmveth_free_buffer_pool(struct ibmveth_adapter *adapter, * * Return: * * %0 - success - * * %-EINVAL - correlator maps to pool or index out of range + * * %-EINVAL - correlator maps to pool or index out of range, or to an + * inactive pool * * %-EFAULT - pool and index map to null skb */ static int ibmveth_remove_buffer_from_pool(struct ibmveth_adapter *adapter, @@ -462,15 +501,12 @@ static int ibmveth_remove_buffer_from_pool(struct ibmveth_adapter *adapter, unsigned int free_index; struct sk_buff *skb; - if (WARN_ON(pool >= IBMVETH_NUM_BUFF_POOLS) || - WARN_ON(index >= adapter->rx_buff_pool[pool].size)) { - schedule_work(&adapter->work); + if (!ibmveth_rxq_correlator_valid(adapter, correlator)) return -EINVAL; - } skb = adapter->rx_buff_pool[pool].skbuff[index]; - if (WARN_ON(!skb)) { - schedule_work(&adapter->work); + if (!skb) { + ibmveth_rxq_no_skb(adapter, correlator); return -EFAULT; } @@ -504,51 +540,56 @@ static int ibmveth_remove_buffer_from_pool(struct ibmveth_adapter *adapter, return 0; } -/* get the current buffer on the rx queue */ -static inline struct sk_buff *ibmveth_rxq_get_buffer(struct ibmveth_adapter *adapter) +/* get the buffer for @correlator, read once from the current rx queue entry */ +static struct sk_buff *ibmveth_rxq_get_buffer(struct ibmveth_adapter *adapter, + u64 correlator) { - u64 correlator = adapter->rx_queue.queue_addr[adapter->rx_queue.index].correlator; unsigned int pool = correlator >> 32; unsigned int index = correlator & 0xffffffffUL; + struct sk_buff *skb; - if (WARN_ON(pool >= IBMVETH_NUM_BUFF_POOLS) || - WARN_ON(index >= adapter->rx_buff_pool[pool].size)) { - schedule_work(&adapter->work); + if (!ibmveth_rxq_correlator_valid(adapter, correlator)) return NULL; - } - return adapter->rx_buff_pool[pool].skbuff[index]; + skb = adapter->rx_buff_pool[pool].skbuff[index]; + if (!skb) + ibmveth_rxq_no_skb(adapter, correlator); + return skb; +} + +static void ibmveth_rxq_advance(struct ibmveth_adapter *adapter) +{ + if (++adapter->rx_queue.index == adapter->rx_queue.num_slots) { + adapter->rx_queue.index = 0; + adapter->rx_queue.toggle = !adapter->rx_queue.toggle; + } } /** * ibmveth_rxq_harvest_buffer - Harvest buffer from pool * - * @adapter: pointer to adapter - * @reuse: whether to reuse buffer + * @adapter: pointer to adapter + * @correlator: correlator of the current rx queue entry, as read by poll + * @reuse: whether to reuse buffer * * Context: called from ibmveth_poll * + * The ring advances even on error, so poll does not return to a bad + * slot before the scheduled reset can run. + * * Return: * * %0 - success * * other - non-zero return from ibmveth_remove_buffer_from_pool */ static int ibmveth_rxq_harvest_buffer(struct ibmveth_adapter *adapter, - bool reuse) + u64 correlator, bool reuse) { - u64 cor; int rc; - cor = adapter->rx_queue.queue_addr[adapter->rx_queue.index].correlator; - rc = ibmveth_remove_buffer_from_pool(adapter, cor, reuse); - if (unlikely(rc)) - return rc; + rc = ibmveth_remove_buffer_from_pool(adapter, correlator, reuse); + ibmveth_rxq_advance(adapter); - if (++adapter->rx_queue.index == adapter->rx_queue.num_slots) { - adapter->rx_queue.index = 0; - adapter->rx_queue.toggle = !adapter->rx_queue.toggle; - } - - return 0; + return rc; } static void ibmveth_free_tx_ltb(struct ibmveth_adapter *adapter, int idx) @@ -628,8 +669,6 @@ static int ibmveth_open(struct net_device *netdev) netdev_dbg(netdev, "open starting\n"); - napi_enable(&adapter->napi); - for(i = 0; i < IBMVETH_NUM_BUFF_POOLS; i++) rxq_entries += adapter->rx_buff_pool[i].size; @@ -717,10 +756,19 @@ static int ibmveth_open(struct net_device *netdev) } } + /* NAPI can run as soon as it is enabled, from netpoll during the + * direct close()/open() pairs or from a direct ibmveth_interrupt() + * call, so enable it only once everything ibmveth_poll() touches + * exists. + */ + napi_enable(&adapter->napi); + netdev_dbg(netdev, "registering irq 0x%x\n", netdev->irq); rc = request_irq(netdev->irq, ibmveth_interrupt, 0, netdev->name, netdev); if (rc != 0) { + napi_disable(&adapter->napi); + synchronize_net(); netdev_err(netdev, "unable to request irq 0x%x, rc %d\n", netdev->irq, rc); goto out_free_buffer_pools; @@ -733,6 +781,7 @@ static int ibmveth_open(struct net_device *netdev) netif_tx_start_all_queues(netdev); + adapter->opened = true; netdev_dbg(netdev, "open complete\n"); return 0; @@ -765,7 +814,6 @@ static int ibmveth_open(struct net_device *netdev) out_free_buffer_list: free_page((unsigned long)adapter->buffer_list_addr); out: - napi_disable(&adapter->napi); return rc; } @@ -776,11 +824,24 @@ static int ibmveth_close(struct net_device *netdev) long lpar_rc; int i; + /* change_mtu, pool sysfs, set_csum and set_tso call close() and + * open() directly. If that open() fails, IFF_UP stays set and + * NAPI is disabled; a second close() would hang in napi_disable(). + */ + if (!adapter->opened) + return 0; + adapter->opened = false; + netdev_dbg(netdev, "close starting\n"); napi_disable(&adapter->napi); + /* napi_disable() returns once ibmveth_poll() has called + * napi_complete_done(), but the poll still re-enables the + * interrupt and reads the RX queue after that. + */ + synchronize_net(); - netif_tx_stop_all_queues(netdev); + netif_tx_disable(netdev); h_vio_signal(adapter->vdev->unit_address, VIO_IRQ_DISABLE); @@ -827,10 +888,10 @@ static int ibmveth_close(struct net_device *netdev) * * @w: pointer to work_struct embedded in adapter structure * - * Context: This routine acquires rtnl_mutex and disables its NAPI through - * ibmveth_close. It can't be called directly in a context that has - * already acquired rtnl_mutex or disabled its NAPI, or directly from - * a poll routine. + * Context: This routine acquires rtnl_mutex and, if the device is open, + * disables its NAPI through ibmveth_close. It can't be called + * directly in a context that has already acquired rtnl_mutex or + * disabled its NAPI, or directly from a poll routine. * * Return: void */ @@ -1122,12 +1183,13 @@ static int ibmveth_set_channels(struct net_device *netdev, struct ibmveth_adapter *adapter = netdev_priv(netdev); unsigned int old = netdev->real_num_tx_queues, goal = channels->tx_count; - int rc, i; + int rc, i, alloc_rc = 0; - /* If ndo_open has not been called yet then don't allocate, just set - * desired netdev_queue's and return + /* If the device is not open (including a failed close/open with + * IFF_UP still set) then don't allocate, just set desired + * netdev_queue's and return */ - if (!(netdev->flags & IFF_UP)) + if (!adapter->opened) return netif_set_real_num_tx_queues(netdev, goal); /* We have IBMVETH_MAX_QUEUES netdev_queue's allocated @@ -1147,6 +1209,7 @@ static int ibmveth_set_channels(struct net_device *netdev, /* if something goes wrong, free everything we just allocated */ netdev_err(netdev, "Failed to allocate more tx queues, returning to %d queues\n", old); + alloc_rc = rc; goal = old; old = i; break; @@ -1157,6 +1220,8 @@ static int ibmveth_set_channels(struct net_device *netdev, old); goal = old; old = i; + } else if (alloc_rc) { + rc = alloc_rc; } /* Free any that are no longer needed */ for (i = old; i > goal; i--) { @@ -1331,8 +1396,12 @@ static netdev_tx_t ibmveth_start_xmit(struct sk_buff *skb, } -static void ibmveth_rx_mss_helper(struct sk_buff *skb, u16 mss, int lrg_pkt) +/* Returns false when the IP or TCP headers fail the checks; the frame is + * then left unchanged and not marked GSO. + */ +static bool ibmveth_rx_mss_helper(struct sk_buff *skb, u16 mss, int lrg_pkt) { + unsigned int gso_type, ip_len; struct tcphdr *tcph; int offset = 0; int hdr_len; @@ -1341,28 +1410,41 @@ static void ibmveth_rx_mss_helper(struct sk_buff *skb, u16 mss, int lrg_pkt) if (skb->protocol == htons(ETH_P_IP)) { struct iphdr *iph = (struct iphdr *)skb->data; + if (skb_headlen(skb) < sizeof(*iph) || iph->ihl < 5) + return false; if (iph->protocol == IPPROTO_TCP) { + /* only a whole datagram has a TCP header to segment */ + if (ip_is_fragment(iph)) + return false; offset = iph->ihl * 4; - skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4; + ip_len = ntohs(iph->tot_len); + gso_type = SKB_GSO_TCPV4; } else { - return; + return true; } } else if (skb->protocol == htons(ETH_P_IPV6)) { struct ipv6hdr *iph6 = (struct ipv6hdr *)skb->data; + if (skb_headlen(skb) < sizeof(*iph6)) + return false; if (iph6->nexthdr == IPPROTO_TCP) { offset = sizeof(struct ipv6hdr); - skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6; + ip_len = offset + ntohs(iph6->payload_len); + gso_type = SKB_GSO_TCPV6; } else { - return; + return true; } } else { - return; + return true; } /* if mss is not set through Large Packet bit/mss in rx buffer, * expect that the mss will be written to the tcp header checksum. */ tcph = (struct tcphdr *)(skb->data + offset); + if (skb_headlen(skb) < offset + sizeof(*tcph) || tcph->doff < 5 || + ip_len != skb_headlen(skb) || ip_len <= offset + tcph->doff * 4) + return false; + skb_shinfo(skb)->gso_type = gso_type; if (lrg_pkt) { skb_shinfo(skb)->gso_size = mss; } else if (offset) { @@ -1371,11 +1453,18 @@ static void ibmveth_rx_mss_helper(struct sk_buff *skb, u16 mss, int lrg_pkt) } if (skb_shinfo(skb)->gso_size) { + /* chosen by the sending partition: at least the floor + * virtio_net_hdr_to_skb() uses, and never GSO_BY_FRAGS + */ + skb_shinfo(skb)->gso_size = + clamp_t(u16, skb_shinfo(skb)->gso_size, + TCP_MIN_GSO_SIZE, GSO_BY_FRAGS - 1); hdr_len = offset + tcph->doff * 4; skb_shinfo(skb)->gso_segs = - DIV_ROUND_UP(skb->len - hdr_len, + DIV_ROUND_UP(ip_len - hdr_len, skb_shinfo(skb)->gso_size); } + return true; } static void ibmveth_rx_csum_helper(struct sk_buff *skb, @@ -1392,6 +1481,10 @@ static void ibmveth_rx_csum_helper(struct sk_buff *skb, if (skb_proto == ETH_P_IP) { iph = (struct iphdr *)skb->data; + if (skb_headlen(skb) < sizeof(*iph) || iph->ihl < 5 || + skb_headlen(skb) < iph->ihl * 4 || + (iph->protocol == IPPROTO_TCP && ip_is_fragment(iph))) + goto bad_hdr; /* If the IP checksum is not offloaded and if the packet * is large send, the checksum must be rebuilt. @@ -1406,6 +1499,8 @@ static void ibmveth_rx_csum_helper(struct sk_buff *skb, iph_proto = iph->protocol; } else if (skb_proto == ETH_P_IPV6) { iph6 = (struct ipv6hdr *)skb->data; + if (skb_headlen(skb) < sizeof(*iph6)) + goto bad_hdr; iphlen = sizeof(struct ipv6hdr); iph_proto = iph6->nexthdr; } @@ -1428,6 +1523,8 @@ static void ibmveth_rx_csum_helper(struct sk_buff *skb, if (iph_proto == IPPROTO_TCP) { struct tcphdr *tcph = (struct tcphdr *)(skb->data + iphlen); + if (skb_headlen(skb) < iphlen + sizeof(*tcph)) + goto bad_hdr; if (tcph->check == 0x0000) { /* Recompute TCP pseudo header checksum */ tcphdrlen = skb->len - iphlen; @@ -1445,6 +1542,13 @@ static void ibmveth_rx_csum_helper(struct sk_buff *skb, skb_reset_network_header(skb); } } + return; + +bad_hdr: + /* headers do not fit the frame, or a fragment has no whole TCP + * segment; let the stack check it + */ + skb->ip_summed = CHECKSUM_NONE; } static int ibmveth_poll(struct napi_struct *napi, int budget) @@ -1454,31 +1558,60 @@ static int ibmveth_poll(struct napi_struct *napi, int budget) struct net_device *netdev = adapter->netdev; int frames_processed = 0; unsigned long lpar_rc; + u64 correlator; u16 mss = 0; + int rc; -restart_poll: while (frames_processed < budget) { if (!ibmveth_rxq_pending_buffer(adapter)) break; smp_rmb(); + correlator = ibmveth_rxq_correlator(adapter); if (!ibmveth_rxq_buffer_valid(adapter)) { wmb(); /* suggested by larson1 */ adapter->rx_invalid_buffer++; netdev_dbg(netdev, "recycling invalid buffer\n"); - if (unlikely(ibmveth_rxq_harvest_buffer(adapter, true))) - break; + rc = ibmveth_rxq_harvest_buffer(adapter, correlator, true); + if (unlikely(rc)) { + netdev->stats.rx_dropped++; + frames_processed++; + continue; + } } else { struct sk_buff *skb, *new_skb; int length = ibmveth_rxq_frame_length(adapter); int offset = ibmveth_rxq_frame_offset(adapter); int csum_good = ibmveth_rxq_csum_good(adapter); int lrg_pkt = ibmveth_rxq_large_packet(adapter); + unsigned int pool, room, off, len; __sum16 iph_check = 0; - skb = ibmveth_rxq_get_buffer(adapter); - if (unlikely(!skb)) - break; + skb = ibmveth_rxq_get_buffer(adapter, correlator); + if (unlikely(!skb)) { + ibmveth_rxq_advance(adapter); + netdev->stats.rx_dropped++; + frames_processed++; + continue; + } + + pool = correlator >> 32; + room = min_t(unsigned int, skb_tailroom(skb), + adapter->rx_buff_pool[pool].buff_size); + off = offset; + len = length; + if (unlikely(len < ETH_HLEN || off >= room || + len > room - off)) { + if (net_ratelimit()) + netdev_err(netdev, + "bad RX frame offset %u length %u (buffer %u), dropping\n", + off, len, room); + ibmveth_rxq_harvest_buffer(adapter, correlator, + true); + netdev->stats.rx_dropped++; + frames_processed++; + continue; + } /* if the large packet bit is set in the rx queue * descriptor, the mss will be written by PHYP eight @@ -1502,12 +1635,25 @@ static int ibmveth_poll(struct napi_struct *napi, int budget) if (rx_flush) ibmveth_flush_buffer(skb->data, length + offset); - if (unlikely(ibmveth_rxq_harvest_buffer(adapter, true))) - break; + rc = ibmveth_rxq_harvest_buffer(adapter, + correlator, + true); + if (unlikely(rc)) { + dev_kfree_skb_any(new_skb); + netdev->stats.rx_dropped++; + frames_processed++; + continue; + } skb = new_skb; } else { - if (unlikely(ibmveth_rxq_harvest_buffer(adapter, false))) - break; + rc = ibmveth_rxq_harvest_buffer(adapter, + correlator, + false); + if (unlikely(rc)) { + netdev->stats.rx_dropped++; + frames_processed++; + continue; + } skb_reserve(skb, offset); } @@ -1517,7 +1663,8 @@ static int ibmveth_poll(struct napi_struct *napi, int budget) /* PHYP without PLSO support places a -1 in the ip * checksum for large send frames. */ - if (skb->protocol == cpu_to_be16(ETH_P_IP)) { + if (skb->protocol == cpu_to_be16(ETH_P_IP) && + skb_headlen(skb) >= sizeof(struct iphdr)) { struct iphdr *iph = (struct iphdr *)skb->data; iph_check = iph->check; @@ -1525,7 +1672,8 @@ static int ibmveth_poll(struct napi_struct *napi, int budget) if ((length > netdev->mtu + ETH_HLEN) || lrg_pkt || iph_check == 0xffff) { - ibmveth_rx_mss_helper(skb, mss, lrg_pkt); + if (!ibmveth_rx_mss_helper(skb, mss, lrg_pkt)) + csum_good = 0; adapter->rx_large_packets++; } @@ -1542,7 +1690,11 @@ static int ibmveth_poll(struct napi_struct *napi, int budget) } } - ibmveth_replenish_task(adapter); + /* netpoll polls with budget 0 for TX only, and is not serialized + * with a NAPI poll that was already running when it was set up + */ + if (budget) + ibmveth_replenish_task(adapter); if (frames_processed == budget) goto out; @@ -1559,10 +1711,13 @@ static int ibmveth_poll(struct napi_struct *napi, int budget) goto out; } - if (ibmveth_rxq_pending_buffer(adapter) && napi_schedule(napi)) { + /* Mask before queueing, as ibmveth_interrupt() does: a threaded + * NAPI can start polling, and unmask, as soon as it is queued. + */ + if (ibmveth_rxq_pending_buffer(adapter) && napi_schedule_prep(napi)) { lpar_rc = h_vio_signal(adapter->vdev->unit_address, VIO_IRQ_DISABLE); - goto restart_poll; + __napi_schedule(napi); } out: @@ -1682,14 +1837,6 @@ static int ibmveth_change_mtu(struct net_device *dev, int new_mtu) return -EINVAL; } -#ifdef CONFIG_NET_POLL_CONTROLLER -static void ibmveth_poll_controller(struct net_device *dev) -{ - ibmveth_replenish_task(netdev_priv(dev)); - ibmveth_interrupt(dev->irq, dev); -} -#endif - /** * ibmveth_get_desired_dma - Calculate IO memory desired by the driver * @@ -1791,11 +1938,42 @@ static const struct net_device_ops ibmveth_netdev_ops = { .ndo_validate_addr = eth_validate_addr, .ndo_set_mac_address = ibmveth_set_mac_addr, .ndo_features_check = ibmveth_features_check, -#ifdef CONFIG_NET_POLL_CONTROLLER - .ndo_poll_controller = ibmveth_poll_controller, -#endif }; +/** + * ibmveth_pool_kobj_release - Mark a pool kobject finished + * @kobj: kobject embedded in the pool + * + * The pool kobjects live in netdev_priv(), so the last put must wait + * for this before free_netdev(). + */ +static void ibmveth_pool_kobj_release(struct kobject *kobj) +{ + struct ibmveth_buff_pool *pool = container_of(kobj, + struct ibmveth_buff_pool, + kobj); + + complete(&pool->released); +} + +/** + * ibmveth_put_pool_kobjs - Drop the pool kobjects and wait for release + * @adapter: ibmveth adapter + * + * With CONFIG_DEBUG_KOBJECT_RELEASE the cleanup, including removing the + * sysfs files, runs later from a work item in the kobject; wait for it + * so free_netdev() cannot free the pools first. + */ +static void ibmveth_put_pool_kobjs(struct ibmveth_adapter *adapter) +{ + int i; + + for (i = 0; i < IBMVETH_NUM_BUFF_POOLS; i++) + kobject_put(&adapter->rx_buff_pool[i].kobj); + for (i = 0; i < IBMVETH_NUM_BUFF_POOLS; i++) + wait_for_completion(&adapter->rx_buff_pool[i].released); +} + static int ibmveth_probe(struct vio_dev *dev, const struct vio_device_id *id) { int rc, i, mac_len; @@ -1906,6 +2084,7 @@ static int ibmveth_probe(struct vio_dev *dev, const struct vio_device_id *id) ibmveth_init_buffer_pool(&adapter->rx_buff_pool[i], i, pool_count[i], pool_size[i], pool_active[i]); + init_completion(&adapter->rx_buff_pool[i].released); error = kobject_init_and_add(kobj, &ktype_veth_pool, &dev->dev.kobj, "pool%d", i); if (!error) @@ -1917,8 +2096,7 @@ static int ibmveth_probe(struct vio_dev *dev, const struct vio_device_id *id) if (rc) { netdev_dbg(netdev, "failed to set number of tx queues rc=%d\n", rc); - free_netdev(netdev); - return rc; + goto err_put_pools; } adapter->tx_ltb_size = PAGE_ALIGN(IBMVETH_MAX_TX_BUF_SIZE); for (i = 0; i < IBMVETH_MAX_QUEUES; i++) @@ -1933,25 +2111,27 @@ static int ibmveth_probe(struct vio_dev *dev, const struct vio_device_id *id) if (rc) { netdev_dbg(netdev, "failed to register netdev rc=%d\n", rc); - free_netdev(netdev); - return rc; + goto err_put_pools; } netdev_dbg(netdev, "registered\n"); return 0; + +err_put_pools: + ibmveth_put_pool_kobjs(adapter); + free_netdev(netdev); + return rc; } static void ibmveth_remove(struct vio_dev *dev) { struct net_device *netdev = dev_get_drvdata(&dev->dev); struct ibmveth_adapter *adapter = netdev_priv(netdev); - int i; - cancel_work_sync(&adapter->work); + disable_work_sync(&adapter->work); - for (i = 0; i < IBMVETH_NUM_BUFF_POOLS; i++) - kobject_put(&adapter->rx_buff_pool[i].kobj); + ibmveth_put_pool_kobjs(adapter); unregister_netdev(netdev); @@ -2127,7 +2307,7 @@ static const struct sysfs_ops veth_pool_ops = { }; static struct kobj_type ktype_veth_pool = { - .release = NULL, + .release = ibmveth_pool_kobj_release, .sysfs_ops = &veth_pool_ops, .default_groups = veth_pool_groups, }; @@ -2198,8 +2378,7 @@ static void ibmveth_reset_kunit(struct work_struct *w) * @test: pointer to kunit structure * * Tests the error returns from ibmveth_remove_buffer_from_pool. - * ibmveth_remove_buffer_from_pool also calls WARN_ON, so dmesg should be - * checked to see that these warnings happened. + * Each error also logs a ratelimited netdev_err. * * Return: void */ @@ -2208,6 +2387,7 @@ static void ibmveth_remove_buffer_from_pool_test(struct kunit *test) struct ibmveth_adapter *adapter = kunit_kzalloc(test, sizeof(*adapter), GFP_KERNEL); struct ibmveth_buff_pool *pool; u64 correlator; + int ret; KUNIT_ASSERT_NOT_ERR_OR_NULL(test, adapter); @@ -2231,6 +2411,13 @@ static void ibmveth_remove_buffer_from_pool_test(struct kunit *test) KUNIT_EXPECT_EQ(test, -EINVAL, ibmveth_remove_buffer_from_pool(adapter, correlator, false)); KUNIT_EXPECT_EQ(test, -EINVAL, ibmveth_remove_buffer_from_pool(adapter, correlator, true)); + /* Pool 2 is in range but has no skbuff array, like an inactive pool. */ + correlator = ((u64)2 << 32) | 0; + ret = ibmveth_remove_buffer_from_pool(adapter, correlator, false); + KUNIT_EXPECT_EQ(test, -EINVAL, ret); + ret = ibmveth_remove_buffer_from_pool(adapter, correlator, true); + KUNIT_EXPECT_EQ(test, -EINVAL, ret); + correlator = (u64)0 | 0; pool->skbuff[0] = NULL; KUNIT_EXPECT_EQ(test, -EFAULT, ibmveth_remove_buffer_from_pool(adapter, correlator, false)); @@ -2243,9 +2430,8 @@ static void ibmveth_remove_buffer_from_pool_test(struct kunit *test) * ibmveth_rxq_get_buffer_test - unit test for ibmveth_rxq_get_buffer * @test: pointer to kunit structure * - * Tests ibmveth_rxq_get_buffer. ibmveth_rxq_get_buffer also calls WARN_ON for - * the NULL returns, so dmesg should be checked to see that these warnings - * happened. + * Tests ibmveth_rxq_get_buffer. Each NULL return also logs a ratelimited + * netdev_err. * * Return: void */ @@ -2254,6 +2440,7 @@ static void ibmveth_rxq_get_buffer_test(struct kunit *test) struct ibmveth_adapter *adapter = kunit_kzalloc(test, sizeof(*adapter), GFP_KERNEL); struct sk_buff *skb = kunit_kzalloc(test, sizeof(*skb), GFP_KERNEL); struct ibmveth_buff_pool *pool; + u64 cor; KUNIT_ASSERT_NOT_ERR_OR_NULL(test, adapter); KUNIT_ASSERT_NOT_ERR_OR_NULL(test, skb); @@ -2277,21 +2464,322 @@ static void ibmveth_rxq_get_buffer_test(struct kunit *test) KUNIT_ASSERT_NOT_ERR_OR_NULL(test, pool->skbuff); adapter->rx_queue.queue_addr[0].correlator = (u64)IBMVETH_NUM_BUFF_POOLS << 32 | 0; - KUNIT_EXPECT_PTR_EQ(test, NULL, ibmveth_rxq_get_buffer(adapter)); + cor = ibmveth_rxq_correlator(adapter); + KUNIT_EXPECT_PTR_EQ(test, NULL, + ibmveth_rxq_get_buffer(adapter, cor)); adapter->rx_queue.queue_addr[0].correlator = (u64)0 << 32 | adapter->rx_buff_pool[0].size; - KUNIT_EXPECT_PTR_EQ(test, NULL, ibmveth_rxq_get_buffer(adapter)); + cor = ibmveth_rxq_correlator(adapter); + KUNIT_EXPECT_PTR_EQ(test, NULL, + ibmveth_rxq_get_buffer(adapter, cor)); + + /* Pool 2 is in range but has no skbuff array, like an inactive pool. */ + adapter->rx_queue.queue_addr[0].correlator = (u64)2 << 32 | 0; + cor = ibmveth_rxq_correlator(adapter); + KUNIT_EXPECT_PTR_EQ(test, NULL, + ibmveth_rxq_get_buffer(adapter, cor)); pool->skbuff[0] = skb; adapter->rx_queue.queue_addr[0].correlator = (u64)0 << 32 | 0; - KUNIT_EXPECT_PTR_EQ(test, skb, ibmveth_rxq_get_buffer(adapter)); + cor = ibmveth_rxq_correlator(adapter); + KUNIT_EXPECT_PTR_EQ(test, skb, + ibmveth_rxq_get_buffer(adapter, cor)); + + flush_work(&adapter->work); +} + +/** + * ibmveth_rxq_harvest_buffer_test - unit test for ibmveth_rxq_harvest_buffer + * @test: pointer to kunit structure + * + * A bad correlator must still advance the RX ring, wrapping and flipping + * the toggle at the end. This covers the harvest path; the advance after + * ibmveth_rxq_get_buffer() fails in ibmveth_poll() is not tested here. + * + * Return: void + */ +static void ibmveth_rxq_harvest_buffer_test(struct kunit *test) +{ + struct ibmveth_adapter *adapter; + struct ibmveth_buff_pool *pool; + u64 cor; + int ret; + + adapter = kunit_kzalloc(test, sizeof(*adapter), GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, adapter); + + INIT_WORK(&adapter->work, ibmveth_reset_kunit); + + adapter->rx_queue.num_slots = 2; + adapter->rx_queue.index = 0; + adapter->rx_queue.toggle = 1; + adapter->rx_queue.queue_addr = + kunit_kcalloc(test, 2, sizeof(struct ibmveth_rx_q_entry), + GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, adapter->rx_queue.queue_addr); + + /* Set sane values for buffer pools */ + for (int i = 0; i < IBMVETH_NUM_BUFF_POOLS; i++) + ibmveth_init_buffer_pool(&adapter->rx_buff_pool[i], i, + pool_count[i], pool_size[i], + pool_active[i]); + + pool = &adapter->rx_buff_pool[0]; + pool->skbuff = kunit_kcalloc(test, pool->size, sizeof(void *), + GFP_KERNEL); + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, pool->skbuff); + + /* Slot 0: pool out of range. Slot 1: valid, but no skb. */ + adapter->rx_queue.queue_addr[0].correlator = + (u64)IBMVETH_NUM_BUFF_POOLS << 32 | 0; + adapter->rx_queue.queue_addr[1].correlator = (u64)0 << 32 | 0; + + cor = ibmveth_rxq_correlator(adapter); + ret = ibmveth_rxq_harvest_buffer(adapter, cor, true); + KUNIT_EXPECT_EQ(test, -EINVAL, ret); + KUNIT_EXPECT_EQ(test, 1ULL, adapter->rx_queue.index); + KUNIT_EXPECT_EQ(test, 1ULL, adapter->rx_queue.toggle); + + cor = ibmveth_rxq_correlator(adapter); + ret = ibmveth_rxq_harvest_buffer(adapter, cor, true); + KUNIT_EXPECT_EQ(test, -EFAULT, ret); + KUNIT_EXPECT_EQ(test, 0ULL, adapter->rx_queue.index); + KUNIT_EXPECT_EQ(test, 0ULL, adapter->rx_queue.toggle); flush_work(&adapter->work); } +KUNIT_DEFINE_ACTION_WRAPPER(ibmveth_kfree_skb, kfree_skb, struct sk_buff *); + +/* A TCP frame after eth_type_trans(): IP header, 20 byte TCP header and + * payload bytes of data, with the IP length matching the frame. + */ +static struct sk_buff *ibmveth_test_tcp_skb(struct kunit *test, bool ipv6, + unsigned int payload) +{ + unsigned int iplen = ipv6 ? sizeof(struct ipv6hdr) : + sizeof(struct iphdr); + unsigned int len = iplen + sizeof(struct tcphdr) + payload; + struct sk_buff *skb = alloc_skb(len, GFP_KERNEL); + struct tcphdr *tcph; + + KUNIT_ASSERT_NOT_ERR_OR_NULL(test, skb); + KUNIT_ASSERT_EQ(test, 0, kunit_add_action_or_reset(test, + ibmveth_kfree_skb, + skb)); + skb_put_zero(skb, len); + if (ipv6) { + struct ipv6hdr *iph6 = (struct ipv6hdr *)skb->data; + + skb->protocol = htons(ETH_P_IPV6); + iph6->version = 6; + iph6->nexthdr = IPPROTO_TCP; + iph6->payload_len = htons(len - iplen); + } else { + struct iphdr *iph = (struct iphdr *)skb->data; + + skb->protocol = htons(ETH_P_IP); + iph->version = 4; + iph->ihl = 5; + iph->protocol = IPPROTO_TCP; + iph->tot_len = htons(len); + } + tcph = (struct tcphdr *)(skb->data + iplen); + tcph->doff = 5; + return skb; +} + +/** + * ibmveth_rx_mss_helper_test - unit test for ibmveth_rx_mss_helper + * @test: pointer to kunit structure + * + * Large send frames get gso_size from the descriptor or the TCP checksum + * field, clamped, and gso_segs from the IP length. Frames whose headers + * do not fit, whose IP length is not the frame length, with no TCP + * payload within the IP length, or that are IPv4 fragments, are refused + * and left without GSO. + * + * Return: void + */ +static void ibmveth_rx_mss_helper_test(struct kunit *test) +{ + struct sk_buff *skb; + struct tcphdr *tcph; + struct iphdr *iph; + + skb = ibmveth_test_tcp_skb(test, false, 2896); + tcph = (struct tcphdr *)(skb->data + sizeof(*iph)); + tcph->check = (__force __sum16)htons(1448); + KUNIT_EXPECT_TRUE(test, ibmveth_rx_mss_helper(skb, 0, 0)); + KUNIT_EXPECT_EQ(test, SKB_GSO_TCPV4, skb_shinfo(skb)->gso_type); + KUNIT_EXPECT_EQ(test, 1448, skb_shinfo(skb)->gso_size); + KUNIT_EXPECT_EQ(test, 2, skb_shinfo(skb)->gso_segs); + KUNIT_EXPECT_EQ(test, 0, (__force u16)tcph->check); + + skb = ibmveth_test_tcp_skb(test, false, 2896); + KUNIT_EXPECT_TRUE(test, ibmveth_rx_mss_helper(skb, 1000, 1)); + KUNIT_EXPECT_EQ(test, 1000, skb_shinfo(skb)->gso_size); + KUNIT_EXPECT_EQ(test, 3, skb_shinfo(skb)->gso_segs); + + skb = ibmveth_test_tcp_skb(test, true, 2896); + tcph = (struct tcphdr *)(skb->data + sizeof(struct ipv6hdr)); + tcph->check = (__force __sum16)htons(1448); + KUNIT_EXPECT_TRUE(test, ibmveth_rx_mss_helper(skb, 0, 0)); + KUNIT_EXPECT_EQ(test, SKB_GSO_TCPV6, skb_shinfo(skb)->gso_type); + KUNIT_EXPECT_EQ(test, 1448, skb_shinfo(skb)->gso_size); + KUNIT_EXPECT_EQ(test, 2, skb_shinfo(skb)->gso_segs); + + skb = ibmveth_test_tcp_skb(test, false, 2896); + KUNIT_EXPECT_TRUE(test, ibmveth_rx_mss_helper(skb, 1, 1)); + KUNIT_EXPECT_EQ(test, TCP_MIN_GSO_SIZE, skb_shinfo(skb)->gso_size); + + skb = ibmveth_test_tcp_skb(test, false, 2896); + KUNIT_EXPECT_TRUE(test, ibmveth_rx_mss_helper(skb, GSO_BY_FRAGS, 1)); + KUNIT_EXPECT_EQ(test, GSO_BY_FRAGS - 1, skb_shinfo(skb)->gso_size); + + /* refused: ihl 0, doff 4, IP length past the frame. With ihl 0 the + * TCP header would overlap the IP header; saddr makes its doff 5. + */ + skb = ibmveth_test_tcp_skb(test, false, 2896); + ((struct iphdr *)skb->data)->ihl = 0; + ((struct iphdr *)skb->data)->saddr = htonl(0x50000000); + KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 1448, 1)); + KUNIT_EXPECT_EQ(test, 0, skb_shinfo(skb)->gso_size); + + skb = ibmveth_test_tcp_skb(test, false, 2896); + ((struct tcphdr *)(skb->data + sizeof(*iph)))->doff = 4; + KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 1448, 1)); + + skb = ibmveth_test_tcp_skb(test, false, 2896); + ((struct iphdr *)skb->data)->tot_len = htons(skb->len + 1); + KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 1448, 1)); + + /* refused: bytes past the IP length, its large send fields left + * alone; gso_segs from the IP length would undercount them + */ + skb = ibmveth_test_tcp_skb(test, false, 2896); + ((struct iphdr *)skb->data)->tot_len = htons(skb->len - 100); + tcph = (struct tcphdr *)(skb->data + sizeof(*iph)); + tcph->check = (__force __sum16)htons(1448); + KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 0, 0)); + KUNIT_EXPECT_EQ(test, 0, skb_shinfo(skb)->gso_size); + KUNIT_EXPECT_EQ(test, 1448, ntohs((__force __be16)tcph->check)); + + /* refused: a fragment past the first, its payload left alone */ + skb = ibmveth_test_tcp_skb(test, false, 2896); + ((struct iphdr *)skb->data)->frag_off = htons(185); + tcph = (struct tcphdr *)(skb->data + sizeof(*iph)); + tcph->check = (__force __sum16)htons(1448); + KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 0, 0)); + KUNIT_EXPECT_EQ(test, 0, skb_shinfo(skb)->gso_size); + KUNIT_EXPECT_EQ(test, 1448, ntohs((__force __be16)tcph->check)); + + /* refused: only Ethernet padding past the TCP header */ + skb = ibmveth_test_tcp_skb(test, false, 6); + ((struct iphdr *)skb->data)->tot_len = htons(40); + KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 1448, 1)); + KUNIT_EXPECT_EQ(test, 0, skb_shinfo(skb)->gso_size); + + skb = ibmveth_test_tcp_skb(test, true, 2896); + ((struct ipv6hdr *)skb->data)->payload_len = 0; + KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 1448, 1)); + + /* refused: no TCP payload, with the IP length matching the frame */ + skb = ibmveth_test_tcp_skb(test, false, 0); + KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 1448, 1)); + KUNIT_EXPECT_EQ(test, 0, skb_shinfo(skb)->gso_size); + + skb = ibmveth_test_tcp_skb(test, true, 0); + KUNIT_EXPECT_FALSE(test, ibmveth_rx_mss_helper(skb, 1448, 1)); + KUNIT_EXPECT_EQ(test, 0, skb_shinfo(skb)->gso_size); + + /* not TCP: accepted and left alone */ + skb = ibmveth_test_tcp_skb(test, false, 2896); + ((struct iphdr *)skb->data)->protocol = IPPROTO_UDP; + KUNIT_EXPECT_TRUE(test, ibmveth_rx_mss_helper(skb, 1448, 1)); + KUNIT_EXPECT_EQ(test, 0, skb_shinfo(skb)->gso_size); +} + +/** + * ibmveth_rx_csum_helper_test - unit test for ibmveth_rx_csum_helper + * @test: pointer to kunit structure + * + * A large send IPv4 header checksum of 0xffff is rebuilt. Headers that + * do not fit the frame, an IPv4 ihl below 5, or a TCP fragment, clear + * CHECKSUM_UNNECESSARY instead of being read. + * + * Return: void + */ +static void ibmveth_rx_csum_helper_test(struct kunit *test) +{ + struct sk_buff *skb; + struct tcphdr *tcph; + struct iphdr *iph; + + skb = ibmveth_test_tcp_skb(test, false, 100); + iph = (struct iphdr *)skb->data; + iph->check = (__force __sum16)0xffff; + tcph = (struct tcphdr *)(skb->data + sizeof(*iph)); + tcph->check = (__force __sum16)htons(1); + skb->ip_summed = CHECKSUM_UNNECESSARY; + ibmveth_rx_csum_helper(skb, NULL); + KUNIT_EXPECT_EQ(test, 0, (__force u16)ip_fast_csum(iph, iph->ihl)); + KUNIT_EXPECT_EQ(test, CHECKSUM_UNNECESSARY, (int)skb->ip_summed); + + skb = ibmveth_test_tcp_skb(test, false, 100); + iph = (struct iphdr *)skb->data; + iph->ihl = 0; + iph->check = (__force __sum16)0xffff; + skb->ip_summed = CHECKSUM_UNNECESSARY; + ibmveth_rx_csum_helper(skb, NULL); + KUNIT_EXPECT_EQ(test, CHECKSUM_NONE, (int)skb->ip_summed); + KUNIT_EXPECT_EQ(test, 0xffff, (__force u16)iph->check); + + /* IPv4 options past the frame; UDP, so no TCP check follows */ + skb = ibmveth_test_tcp_skb(test, false, 0); + iph = (struct iphdr *)skb->data; + iph->protocol = IPPROTO_UDP; + iph->ihl = 15; + iph->check = (__force __sum16)0xffff; + skb->ip_summed = CHECKSUM_UNNECESSARY; + ibmveth_rx_csum_helper(skb, NULL); + KUNIT_EXPECT_EQ(test, CHECKSUM_NONE, (int)skb->ip_summed); + + /* a TCP fragment past the first: header and payload left alone */ + skb = ibmveth_test_tcp_skb(test, false, 100); + iph = (struct iphdr *)skb->data; + iph->frag_off = htons(185); + iph->check = (__force __sum16)0xffff; + skb->ip_summed = CHECKSUM_UNNECESSARY; + ibmveth_rx_csum_helper(skb, NULL); + KUNIT_EXPECT_EQ(test, CHECKSUM_NONE, (int)skb->ip_summed); + KUNIT_EXPECT_EQ(test, 0xffff, (__force u16)iph->check); + KUNIT_EXPECT_EQ(test, 0, + (__force u16)((struct tcphdr *)(skb->data + + sizeof(*iph)))->check); + + /* TCP header past the frame */ + skb = ibmveth_test_tcp_skb(test, false, 0); + skb_trim(skb, sizeof(struct iphdr)); + skb->ip_summed = CHECKSUM_UNNECESSARY; + ibmveth_rx_csum_helper(skb, NULL); + KUNIT_EXPECT_EQ(test, CHECKSUM_NONE, (int)skb->ip_summed); + + /* IPv6 header past the frame; UDP, so no TCP check follows */ + skb = ibmveth_test_tcp_skb(test, true, 0); + ((struct ipv6hdr *)skb->data)->nexthdr = IPPROTO_UDP; + skb_trim(skb, sizeof(struct ipv6hdr) - 1); + skb->ip_summed = CHECKSUM_UNNECESSARY; + ibmveth_rx_csum_helper(skb, NULL); + KUNIT_EXPECT_EQ(test, CHECKSUM_NONE, (int)skb->ip_summed); +} + static struct kunit_case ibmveth_test_cases[] = { KUNIT_CASE(ibmveth_remove_buffer_from_pool_test), KUNIT_CASE(ibmveth_rxq_get_buffer_test), + KUNIT_CASE(ibmveth_rxq_harvest_buffer_test), + KUNIT_CASE(ibmveth_rx_mss_helper_test), + KUNIT_CASE(ibmveth_rx_csum_helper_test), {} }; diff --git a/drivers/net/ethernet/ibm/ibmveth.h b/drivers/net/ethernet/ibm/ibmveth.h index d87713668ed3..be0939caa328 100644 --- a/drivers/net/ethernet/ibm/ibmveth.h +++ b/drivers/net/ethernet/ibm/ibmveth.h @@ -14,6 +14,8 @@ #ifndef _IBMVETH_H #define _IBMVETH_H +#include + /* constants for H_MULTICAST_CTRL */ #define IbmVethMcastReceptionModifyBit 0x80000UL #define IbmVethMcastReceptionEnableBit 0x20000UL @@ -143,6 +145,7 @@ struct ibmveth_buff_pool { struct sk_buff **skbuff; int active; struct kobject kobj; + struct completion released; }; struct ibmveth_rx_q { @@ -172,6 +175,8 @@ struct ibmveth_adapter { int rx_csum; int large_send; bool is_active_trunk; + /* Set by a successful ibmveth_open(), cleared by ibmveth_close(). */ + bool opened; unsigned int rx_buffers_per_hcall; u64 fw_ipv6_csum_support; diff --git a/drivers/net/ethernet/intel/ice/ice.h b/drivers/net/ethernet/intel/ice/ice.h index db3c7015c56c..f1ba86d066be 100644 --- a/drivers/net/ethernet/intel/ice/ice.h +++ b/drivers/net/ethernet/intel/ice/ice.h @@ -328,6 +328,8 @@ enum ice_vsi_state { struct ice_vsi_stats { struct ice_ring_stats **tx_ring_stats; /* Tx ring stats array */ struct ice_ring_stats **rx_ring_stats; /* Rx ring stats array */ + u16 tx_ring_stats_len; /* Length of the Tx ring stats array */ + u16 rx_ring_stats_len; /* Length of the Rx ring stats array */ }; /* struct that defines a VSI, associated with a dev */ @@ -401,9 +403,11 @@ struct ice_vsi { u8 rx_mapping_mode; /* ICE_MAP_MODE_[CONTIG|SCATTER] */ u16 *txq_map; /* index in pf->avail_txqs */ u16 *rxq_map; /* index in pf->avail_rxqs */ - u16 alloc_txq; /* Allocated Tx queues */ + struct_group_tagged(ice_vsi_alloc_queues_params, alloc_txq_rxq, + u16 alloc_txq; /* Allocated Tx queues */ + u16 alloc_rxq; /* Allocated Rx queues */ + ); u16 num_txq; /* Used Tx queues */ - u16 alloc_rxq; /* Allocated Rx queues */ u16 num_rxq; /* Used Rx queues */ u16 req_txq; /* User requested Tx queues */ u16 req_rxq; /* User requested Rx queues */ diff --git a/drivers/net/ethernet/intel/ice/ice_adapter.c b/drivers/net/ethernet/intel/ice/ice_adapter.c index 2dc3629d6d0f..536923b6ae97 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,11 +55,18 @@ 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_obj(*adapter); 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); @@ -66,18 +74,19 @@ static struct ice_adapter *ice_adapter_new(struct pci_dev *pdev) mutex_init(&adapter->cpi_phy_lock[i]); 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)); + WARN_ON(!list_empty(&adapter->ports.list)); for (int i = 0; i < ARRAY_SIZE(adapter->cpi_phy_lock); i++) mutex_destroy(&adapter->cpi_phy_lock[i]); - mutex_destroy(&adapter->ports.lock); + + 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 4f695f32da3d..c61bd645e460 100644 --- a/drivers/net/ethernet/intel/ice/ice_adapter.h +++ b/drivers/net/ethernet/intel/ice/ice_adapter.h @@ -6,6 +6,7 @@ #include #include +#include #include #include @@ -17,15 +18,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_lib.c b/drivers/net/ethernet/intel/ice/ice_lib.c index 9e08db376d3d..c393d913d037 100644 --- a/drivers/net/ethernet/intel/ice/ice_lib.c +++ b/drivers/net/ethernet/intel/ice/ice_lib.c @@ -153,23 +153,61 @@ static void ice_vsi_set_num_desc(struct ice_vsi *vsi) } } -static u16 ice_get_rxq_count(struct ice_pf *pf) +static u16 ice_get_rxq_count(struct ice_pf *pf, u16 held) { - return min(ice_get_avail_rxq_count(pf), - netif_get_num_default_rss_queues()); + return min_t(u16, ice_get_avail_rxq_count(pf) + held, + netif_get_num_default_rss_queues()); } -static u16 ice_get_txq_count(struct ice_pf *pf) +static u16 ice_get_txq_count(struct ice_pf *pf, u16 held) { - return min(ice_get_avail_txq_count(pf), - netif_get_num_default_rss_queues()); + return min_t(u16, ice_get_avail_txq_count(pf) + held, + netif_get_num_default_rss_queues()); +} + +/* @held_txq, @held_rxq: queues the VSI still owns but is about to return to the + * PF pool, so that the result matches what it will be once they are back there. + */ +static struct ice_vsi_alloc_queues_params +ice_vsi_get_num_qs(struct ice_vsi *vsi, u16 held_txq, u16 held_rxq) +{ + struct ice_vsi_alloc_queues_params qs = {}; + struct ice_pf *pf = vsi->back; + + switch (vsi->type) { + case ICE_VSI_PF: + qs.alloc_txq = vsi->req_txq ?: ice_get_txq_count(pf, held_txq); + + /* only 1 Rx queue unless RSS is enabled */ + if (!test_bit(ICE_FLAG_RSS_ENA, pf->flags)) + qs.alloc_rxq = 1; + else + qs.alloc_rxq = vsi->req_rxq ?: + ice_get_rxq_count(pf, held_rxq); + break; + case ICE_VSI_SF: + case ICE_VSI_CTRL: + case ICE_VSI_LB: + qs.alloc_txq = 1; + qs.alloc_rxq = 1; + break; + case ICE_VSI_VF: + qs.alloc_txq = vsi->vf->num_req_qs ?: vsi->vf->num_vf_qs; + qs.alloc_rxq = qs.alloc_txq; + break; + case ICE_VSI_CHNL: + break; + default: + dev_warn(ice_pf_to_dev(pf), "Unknown VSI type %d\n", vsi->type); + return vsi->alloc_txq_rxq; + } + + return qs; } /** * ice_vsi_set_num_qs - Set number of queues, descriptors and vectors for a VSI * @vsi: the VSI being configured - * - * Return 0 on success and a negative value on error */ static void ice_vsi_set_num_qs(struct ice_vsi *vsi) { @@ -180,44 +218,27 @@ static void ice_vsi_set_num_qs(struct ice_vsi *vsi) if (WARN_ON(vsi_type == ICE_VSI_VF && !vf)) return; + vsi->alloc_txq_rxq = ice_vsi_get_num_qs(vsi, 0, 0); + switch (vsi_type) { case ICE_VSI_PF: - if (vsi->req_txq) { - vsi->alloc_txq = vsi->req_txq; + if (vsi->req_txq) vsi->num_txq = vsi->req_txq; - } else { - vsi->alloc_txq = ice_get_txq_count(pf); - } + if (vsi->req_rxq && test_bit(ICE_FLAG_RSS_ENA, pf->flags)) + vsi->num_rxq = vsi->req_rxq; pf->num_lan_tx = vsi->alloc_txq; - - /* only 1 Rx queue unless RSS is enabled */ - if (!test_bit(ICE_FLAG_RSS_ENA, pf->flags)) { - vsi->alloc_rxq = 1; - } else { - if (vsi->req_rxq) { - vsi->alloc_rxq = vsi->req_rxq; - vsi->num_rxq = vsi->req_rxq; - } else { - vsi->alloc_rxq = ice_get_rxq_count(pf); - } - } - pf->num_lan_rx = vsi->alloc_rxq; vsi->num_q_vectors = max(vsi->alloc_rxq, vsi->alloc_txq); break; case ICE_VSI_SF: - vsi->alloc_txq = 1; - vsi->alloc_rxq = 1; vsi->num_q_vectors = 1; vsi->irq_dyn_alloc = true; break; case ICE_VSI_VF: if (vf->num_req_qs) vf->num_vf_qs = vf->num_req_qs; - vsi->alloc_txq = vf->num_vf_qs; - vsi->alloc_rxq = vf->num_vf_qs; /* pf->vfs.num_msix_per includes (VF miscellaneous vector + * data queue interrupts). Since vsi->num_q_vectors is number * of queues vectors, subtract 1 (ICE_NONQ_VECS_VF) from the @@ -226,22 +247,15 @@ static void ice_vsi_set_num_qs(struct ice_vsi *vsi) vsi->num_q_vectors = vf->num_msix - ICE_NONQ_VECS_VF; break; case ICE_VSI_CTRL: - vsi->alloc_txq = 1; - vsi->alloc_rxq = 1; vsi->num_q_vectors = 1; break; case ICE_VSI_CHNL: - vsi->alloc_txq = 0; - vsi->alloc_rxq = 0; break; case ICE_VSI_LB: - vsi->alloc_txq = 1; - vsi->alloc_rxq = 1; /* A dummy q_vector, no actual IRQ. */ vsi->num_q_vectors = 1; break; default: - dev_warn(ice_pf_to_dev(pf), "Unknown VSI type %d\n", vsi_type); break; } @@ -330,6 +344,32 @@ static void ice_vsi_free_arrays(struct ice_vsi *vsi) vsi->rxq_map = NULL; } +/* free single stats memory */ +static void __ice_vsi_free_stats(struct ice_vsi_stats *vsi_stat, bool free_entries) +{ + if (!vsi_stat) + return; + + if (free_entries) { + for (int i = 0; i < vsi_stat->tx_ring_stats_len; i++) { + if (vsi_stat->tx_ring_stats[i]) { + kfree_rcu(vsi_stat->tx_ring_stats[i], rcu); + WRITE_ONCE(vsi_stat->tx_ring_stats[i], NULL); + } + } + for (int i = 0; i < vsi_stat->rx_ring_stats_len; i++) { + if (vsi_stat->rx_ring_stats[i]) { + kfree_rcu(vsi_stat->rx_ring_stats[i], rcu); + WRITE_ONCE(vsi_stat->rx_ring_stats[i], NULL); + } + } + } + + kfree(vsi_stat->tx_ring_stats); + kfree(vsi_stat->rx_ring_stats); + kfree(vsi_stat); +} + /** * ice_vsi_free_stats - Free the ring statistics structures * @vsi: VSI pointer @@ -338,7 +378,6 @@ static void ice_vsi_free_stats(struct ice_vsi *vsi) { struct ice_vsi_stats *vsi_stat; struct ice_pf *pf = vsi->back; - int i; if (vsi->type == ICE_VSI_CHNL) return; @@ -346,26 +385,7 @@ static void ice_vsi_free_stats(struct ice_vsi *vsi) return; vsi_stat = pf->vsi_stats[vsi->idx]; - if (!vsi_stat) - return; - - ice_for_each_alloc_txq(vsi, i) { - if (vsi_stat->tx_ring_stats[i]) { - kfree_rcu(vsi_stat->tx_ring_stats[i], rcu); - WRITE_ONCE(vsi_stat->tx_ring_stats[i], NULL); - } - } - - ice_for_each_alloc_rxq(vsi, i) { - if (vsi_stat->rx_ring_stats[i]) { - kfree_rcu(vsi_stat->rx_ring_stats[i], rcu); - WRITE_ONCE(vsi_stat->rx_ring_stats[i], NULL); - } - } - - kfree(vsi_stat->tx_ring_stats); - kfree(vsi_stat->rx_ring_stats); - kfree(vsi_stat); + __ice_vsi_free_stats(vsi_stat, true); pf->vsi_stats[vsi->idx] = NULL; } @@ -513,13 +533,116 @@ static irqreturn_t ice_msix_clean_rings(int __always_unused irq, void *data) return IRQ_HANDLED; } +static struct ice_vsi_stats *ice_vsi_new_stat_arrays(int txq, int rxq) +{ + struct ice_ring_stats **tx_ring_stats; + struct ice_ring_stats **rx_ring_stats; + struct ice_vsi_stats *vsi_stat; + + vsi_stat = kzalloc_obj(*vsi_stat); + tx_ring_stats = kzalloc_objs(*tx_ring_stats, txq); + rx_ring_stats = kzalloc_objs(*rx_ring_stats, rxq); + if (!vsi_stat || !tx_ring_stats || !rx_ring_stats) { + kfree(vsi_stat); + kfree(tx_ring_stats); + kfree(rx_ring_stats); + return NULL; + } + + vsi_stat->tx_ring_stats = tx_ring_stats; + vsi_stat->rx_ring_stats = rx_ring_stats; + vsi_stat->tx_ring_stats_len = txq; + vsi_stat->rx_ring_stats_len = rxq; + + return vsi_stat; +} + +static void ice_vsi_free_unused_stat_arrays(struct ice_vsi_stats *vsi_stat, + struct ice_vsi_stats *new_vsi_stat) +{ + int new_txq = new_vsi_stat->tx_ring_stats_len; + int new_rxq = new_vsi_stat->rx_ring_stats_len; + int prev_txq = vsi_stat->tx_ring_stats_len; + int prev_rxq = vsi_stat->rx_ring_stats_len; + + for (int i = new_txq; i < prev_txq; i++) { + if (vsi_stat->tx_ring_stats[i]) { + kfree_rcu(vsi_stat->tx_ring_stats[i], rcu); + WRITE_ONCE(vsi_stat->tx_ring_stats[i], NULL); + } + } + for (int i = new_rxq; i < prev_rxq; i++) { + if (vsi_stat->rx_ring_stats[i]) { + kfree_rcu(vsi_stat->rx_ring_stats[i], rcu); + WRITE_ONCE(vsi_stat->rx_ring_stats[i], NULL); + } + } +} + +static void ice_vsi_set_stat_arrays(struct ice_vsi *vsi, + struct ice_vsi_stats *new_vsi_stat) +{ + u16 new_txq, new_rxq, prev_txq, prev_rxq; + struct ice_vsi_stats *vsi_stat; + struct ice_pf *pf = vsi->back; + + new_txq = new_vsi_stat->tx_ring_stats_len; + new_rxq = new_vsi_stat->rx_ring_stats_len; + vsi_stat = pf->vsi_stats[vsi->idx]; + pf->vsi_stats[vsi->idx] = new_vsi_stat; + if (!vsi_stat) + return; /* don't copy if there is no source */ + + prev_txq = vsi_stat->tx_ring_stats_len; + prev_rxq = vsi_stat->rx_ring_stats_len; + + memcpy(new_vsi_stat->tx_ring_stats, vsi_stat->tx_ring_stats, + sizeof(*vsi_stat->tx_ring_stats) * min(prev_txq, new_txq)); + memcpy(new_vsi_stat->rx_ring_stats, vsi_stat->rx_ring_stats, + sizeof(*vsi_stat->rx_ring_stats) * min(prev_rxq, new_rxq)); +} + +/** + * ice_vsi_install_stat_arrays - swap in freshly sized ring stats arrays + * @vsi: VSI to install the ring stats arrays of + * @txq: number of Tx ring stats entries to make room for + * @rxq: number of Rx ring stats entries to make room for + * + * Surviving entries are carried over, the rest is freed together with the old + * container. + * + * Return: 0 on success and negative value on failure. + */ +static int ice_vsi_install_stat_arrays(struct ice_vsi *vsi, u16 txq, u16 rxq) +{ + struct ice_vsi_stats *old_stat, *new_stat; + + new_stat = ice_vsi_new_stat_arrays(txq, rxq); + if (!new_stat) + return -ENOMEM; + + old_stat = vsi->back->vsi_stats[vsi->idx]; + ice_vsi_set_stat_arrays(vsi, new_stat); + if (old_stat) { + ice_vsi_free_unused_stat_arrays(old_stat, new_stat); + __ice_vsi_free_stats(old_stat, false); + } + + return 0; +} + /** * ice_vsi_alloc_stat_arrays - Allocate statistics arrays * @vsi: VSI pointer + * + * Runs after ice_vsi_set_num_qs(), so this is the first point where the queue + * count is final. Grow the arrays if an earlier sizing guessed too low. + * + * Return: 0 on success, negative error code otherwise. */ static int ice_vsi_alloc_stat_arrays(struct ice_vsi *vsi) { - struct ice_vsi_stats *vsi_stat; + struct ice_vsi_stats *old_stat; struct ice_pf *pf = vsi->back; if (vsi->type == ICE_VSI_CHNL) @@ -527,35 +650,13 @@ static int ice_vsi_alloc_stat_arrays(struct ice_vsi *vsi) if (!pf->vsi_stats) return -ENOENT; - if (pf->vsi_stats[vsi->idx]) - /* realloc will happen in rebuild path */ + old_stat = pf->vsi_stats[vsi->idx]; + if (old_stat && old_stat->tx_ring_stats_len >= vsi->alloc_txq && + old_stat->rx_ring_stats_len >= vsi->alloc_rxq) return 0; - vsi_stat = kzalloc_obj(*vsi_stat); - if (!vsi_stat) - return -ENOMEM; - - vsi_stat->tx_ring_stats = - kzalloc_objs(*vsi_stat->tx_ring_stats, vsi->alloc_txq); - if (!vsi_stat->tx_ring_stats) - goto err_alloc_tx; - - vsi_stat->rx_ring_stats = - kzalloc_objs(*vsi_stat->rx_ring_stats, vsi->alloc_rxq); - if (!vsi_stat->rx_ring_stats) - goto err_alloc_rx; - - pf->vsi_stats[vsi->idx] = vsi_stat; - - return 0; - -err_alloc_rx: - kfree(vsi_stat->rx_ring_stats); -err_alloc_tx: - kfree(vsi_stat->tx_ring_stats); - kfree(vsi_stat); - pf->vsi_stats[vsi->idx] = NULL; - return -ENOMEM; + return ice_vsi_install_stat_arrays(vsi, vsi->alloc_txq, + vsi->alloc_rxq); } /** @@ -3015,63 +3116,27 @@ ice_vsi_rebuild_set_coalesce(struct ice_vsi *vsi, } /** - * ice_vsi_realloc_stat_arrays - Frees unused stat structures or alloc new ones - * @vsi: VSI pointer + * ice_vsi_resize_stat_arrays - resize ring stats arrays for new queue count + * @vsi: VSI to swap the ring stats arrays of + * + * Call while @vsi still owns its queues and before ice_vsi_decfg() returns them + * to the PF pool, so that the new size is what ice_vsi_set_num_qs() will compute + * afterwards. Surviving entries are carried over, the rest is freed. + * + * Return: 0 on success and negative value on failure. */ -static int -ice_vsi_realloc_stat_arrays(struct ice_vsi *vsi) +static int ice_vsi_resize_stat_arrays(struct ice_vsi *vsi) { - u16 req_txq = vsi->req_txq ? vsi->req_txq : vsi->alloc_txq; - u16 req_rxq = vsi->req_rxq ? vsi->req_rxq : vsi->alloc_rxq; - struct ice_ring_stats **tx_ring_stats; - struct ice_ring_stats **rx_ring_stats; - struct ice_vsi_stats *vsi_stat; - struct ice_pf *pf = vsi->back; - u16 prev_txq = vsi->alloc_txq; - u16 prev_rxq = vsi->alloc_rxq; - int i; - - vsi_stat = pf->vsi_stats[vsi->idx]; + struct ice_vsi_alloc_queues_params qs; - if (req_txq < prev_txq) { - for (i = req_txq; i < prev_txq; i++) { - if (vsi_stat->tx_ring_stats[i]) { - kfree_rcu(vsi_stat->tx_ring_stats[i], rcu); - WRITE_ONCE(vsi_stat->tx_ring_stats[i], NULL); - } - } - } - - tx_ring_stats = vsi_stat->tx_ring_stats; - vsi_stat->tx_ring_stats = - krealloc_array(vsi_stat->tx_ring_stats, req_txq, - sizeof(*vsi_stat->tx_ring_stats), - GFP_KERNEL | __GFP_ZERO); - if (!vsi_stat->tx_ring_stats) { - vsi_stat->tx_ring_stats = tx_ring_stats; - return -ENOMEM; - } - - if (req_rxq < prev_rxq) { - for (i = req_rxq; i < prev_rxq; i++) { - if (vsi_stat->rx_ring_stats[i]) { - kfree_rcu(vsi_stat->rx_ring_stats[i], rcu); - WRITE_ONCE(vsi_stat->rx_ring_stats[i], NULL); - } - } - } + /* channel VSIs have no entry in pf->vsi_stats[] */ + if (vsi->type == ICE_VSI_CHNL) + return 0; - rx_ring_stats = vsi_stat->rx_ring_stats; - vsi_stat->rx_ring_stats = - krealloc_array(vsi_stat->rx_ring_stats, req_rxq, - sizeof(*vsi_stat->rx_ring_stats), - GFP_KERNEL | __GFP_ZERO); - if (!vsi_stat->rx_ring_stats) { - vsi_stat->rx_ring_stats = rx_ring_stats; - return -ENOMEM; - } + qs = ice_vsi_get_num_qs(vsi, vsi->alloc_txq + vsi->num_xdp_txq, + vsi->alloc_rxq); - return 0; + return ice_vsi_install_stat_arrays(vsi, qs.alloc_txq, qs.alloc_rxq); } /** @@ -3101,7 +3166,7 @@ int ice_vsi_rebuild(struct ice_vsi *vsi, u32 vsi_flags) mutex_lock(&vsi->xdp_state_lock); - ret = ice_vsi_realloc_stat_arrays(vsi); + ret = ice_vsi_resize_stat_arrays(vsi); if (ret) goto unlock; diff --git a/drivers/net/ethernet/intel/ice/ice_ptp.c b/drivers/net/ethernet/intel/ice/ice_ptp.c index eaec36ab6ae3..2f8563eb6fb1 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" @@ -364,7 +367,7 @@ ice_ptp_is_tx_tracker_up(struct ice_ptp_tx *tx) { lockdep_assert_held(&tx->lock); - return tx->init && !tx->calibrating; + return tx->init && !tx->disabled; } /** @@ -589,6 +592,12 @@ static void ice_ptp_process_tx_tstamp(struct ice_ptp_tx *tx) bool drop_ts = !link_up; struct sk_buff *skb; + /* Paired with smp_mb__before_atomic() in ice_ptp_request_ts() + * to ensure ordering the in_use bitmap and the indexed fields + * in the tstamps array. + */ + smp_rmb(); + /* Drop packets which have waited for more than 2 seconds */ if (time_is_before_jiffies(tx->tstamps[idx].start + 2 * HZ)) { drop_ts = true; @@ -673,20 +682,37 @@ static void ice_ptp_process_tx_tstamp(struct ice_ptp_tx *tx) pf->ptp.tx_hwtstamp_good += tstamp_good; } +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); } /** @@ -806,10 +832,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); } /** @@ -1133,6 +1168,7 @@ static int ice_ptp_check_tx_fifo(struct ice_ptp_port *port) static void ice_ptp_wait_for_offsets(struct kthread_work *work) { struct ice_ptp_port *port; + unsigned long flags; struct ice_pf *pf; struct ice_hw *hw; int tx_err; @@ -1153,9 +1189,26 @@ static void ice_ptp_wait_for_offsets(struct kthread_work *work) tx_err = ice_ptp_check_tx_fifo(port); if (!tx_err) tx_err = ice_phy_cfg_tx_offset_e82x(hw, port->port_num); + if (!tx_err) { + /* Tx offset has been configured, re-enable Tx timestamps */ + spin_lock_irqsave(&port->tx.lock, flags); + if (port->tx.disabled) { + port->tx.disabled = false; + dev_dbg(ice_pf_to_dev(pf), "PTP Tx offset valid for port %u, Tx timestamps enabled\n", + port->port_num); + } + spin_unlock_irqrestore(&port->tx.lock, flags); + } + rx_err = ice_phy_cfg_rx_offset_e82x(hw, port->port_num); if (tx_err || rx_err) { - /* Tx and/or Rx offset not yet configured, try again later */ + /* Tx and/or Rx offset not yet configured, try again later. + * This is expected during normal link-up: the vernier offset + * calibration cannot complete until at least one packet has + * been transmitted, so the first retries routinely land here. + */ + dev_dbg(ice_pf_to_dev(pf), "PTP offset not yet valid for port %u (tx_err=%d rx_err=%d)\n", + port->port_num, tx_err, rx_err); kthread_queue_delayed_work(pf->ptp.kworker, &port->ov_work, msecs_to_jiffies(100)); @@ -1233,11 +1286,9 @@ ice_ptp_port_phy_restart(struct ice_ptp_port *ptp_port) /* Start the PHY timer in Vernier mode */ kthread_cancel_delayed_work_sync(&ptp_port->ov_work); - /* temporarily disable Tx timestamps while calibrating - * PHY offset - */ + /* Disable Tx timestamps until PHY calibration completes */ spin_lock_irqsave(&ptp_port->tx.lock, flags); - ptp_port->tx.calibrating = true; + ptp_port->tx.disabled = true; spin_unlock_irqrestore(&ptp_port->tx.lock, flags); ptp_port->tx_fifo_busy_cnt = 0; @@ -1246,11 +1297,10 @@ ice_ptp_port_phy_restart(struct ice_ptp_port *ptp_port) if (err) break; - /* Enable Tx timestamps right away */ - spin_lock_irqsave(&ptp_port->tx.lock, flags); - ptp_port->tx.calibrating = false; - spin_unlock_irqrestore(&ptp_port->tx.lock, flags); - + /* Do not clear disabled flag here. Tx timestamp requests + * remain disabled until ice_ptp_wait_for_offsets() has + * verified that the Tx offset calibration has completed. + */ kthread_queue_delayed_work(pf->ptp.kworker, &ptp_port->ov_work, 0); break; @@ -1424,16 +1474,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); } /** @@ -2638,11 +2694,13 @@ s8 ice_ptp_request_ts(struct ice_ptp_tx *tx, struct sk_buff *skb) * a reference to the skb and the start time to allow discarding old * requests. */ - set_bit(idx, tx->in_use); - clear_bit(idx, tx->stale); tx->tstamps[idx].start = jiffies; tx->tstamps[idx].skb = skb_get(skb); skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS; + clear_bit(idx, tx->stale); + /* Ensure index is setup before marking it as used */ + smp_mb__before_atomic(); + set_bit(idx, tx->in_use); ice_trace(tx_tstamp_request, skb, idx); } @@ -2694,19 +2752,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) @@ -2890,14 +2957,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: @@ -2909,7 +2980,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); } /** @@ -3086,11 +3160,11 @@ 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); /* Seed the per-PHY Tx reference clock usage map for this port. * Only meaningful on E825 (other MAC types don't expose tx-clk @@ -3112,13 +3186,23 @@ static int ice_ptp_setup_pf(struct ice_pf *pf) 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 c4b0da7ce20e..8d46e57368ca 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" @@ -104,8 +106,8 @@ enum ice_tx_tstamp_work { * @offset: offset into timestamp block to get the real index * @len: length of the tstamps and in_use fields. * @init: if true, the tracker is initialized; - * @calibrating: if true, the PHY is calibrating the Tx offset. During this - * window, timestamps are temporarily disabled. + * @disabled: set to true when new Tx timestamp requests are disabled, such as + * while the PHY Tx offset configuration has not yet completed. * @has_ready_bitmap: if true, the hardware has a valid Tx timestamp ready * bitmap register. If false, fall back to verifying new * timestamp values against previously cached copy. @@ -120,7 +122,7 @@ struct ice_ptp_tx { u8 offset; u8 len; u8 init : 1; - u8 calibrating : 1; + u8 disabled : 1; u8 has_ready_bitmap : 1; s8 last_ll_ts_idx_read; }; @@ -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 @@ -149,6 +152,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/marvell/octeontx2/af/rvu_nix.c b/drivers/net/ethernet/marvell/octeontx2/af/rvu_nix.c index 153eb57bad06..95f782d47927 100644 --- a/drivers/net/ethernet/marvell/octeontx2/af/rvu_nix.c +++ b/drivers/net/ethernet/marvell/octeontx2/af/rvu_nix.c @@ -1239,7 +1239,7 @@ static int rvu_nix_blk_aq_enq_inst(struct rvu *rvu, struct nix_hw *nix_hw, __clear_bit(req->qidx, pfvf->rq_bmap); } if (req->ctype == NIX_AQ_CTYPE_SQ) { - ena = (req->rq.ena & req->sq_mask.ena) | + ena = (req->sq.ena & req->sq_mask.ena) | (test_bit(req->qidx, pfvf->sq_bmap) & ~req->sq_mask.ena); if (ena) @@ -1248,7 +1248,7 @@ static int rvu_nix_blk_aq_enq_inst(struct rvu *rvu, struct nix_hw *nix_hw, __clear_bit(req->qidx, pfvf->sq_bmap); } if (req->ctype == NIX_AQ_CTYPE_CQ) { - ena = (req->rq.ena & req->cq_mask.ena) | + ena = (req->cq.ena & req->cq_mask.ena) | (test_bit(req->qidx, pfvf->cq_bmap) & ~req->cq_mask.ena); if (ena) diff --git a/drivers/net/ethernet/marvell/octeontx2/nic/cn10k_ipsec.c b/drivers/net/ethernet/marvell/octeontx2/nic/cn10k_ipsec.c index 77543d472345..443435608781 100644 --- a/drivers/net/ethernet/marvell/octeontx2/nic/cn10k_ipsec.c +++ b/drivers/net/ethernet/marvell/octeontx2/nic/cn10k_ipsec.c @@ -1037,6 +1037,9 @@ bool cn10k_ipsec_transmit(struct otx2_nic *pf, struct netdev_queue *txq, cn10k_cpt_inst_flush(pf, &inst, sizeof(struct cpt_inst_s)); return true; drop: + otx2_dma_unmap_skb_frags(pf, &sq->sg[sq->head], skb); + sq->sg[sq->head].skb = (u64)NULL; + atomic_long_inc(&pf->hw.dev_stats.tx_discards); dev_kfree_skb_any(skb); - return false; + return true; } diff --git a/drivers/net/ethernet/marvell/octeontx2/nic/otx2_common.c b/drivers/net/ethernet/marvell/octeontx2/nic/otx2_common.c index b11389a841d1..07c43a4fcb4e 100644 --- a/drivers/net/ethernet/marvell/octeontx2/nic/otx2_common.c +++ b/drivers/net/ethernet/marvell/octeontx2/nic/otx2_common.c @@ -2140,13 +2140,12 @@ dma_addr_t otx2_dma_map_skb_frag(struct otx2_nic *pfvf, return otx2_dma_map_page(pfvf, page, offset, *len, dir); } -void otx2_dma_unmap_skb_frags(struct otx2_nic *pfvf, struct sg_list *sg) +void otx2_dma_unmap_skb_frags(struct otx2_nic *pfvf, struct sg_list *sg, + struct sk_buff *skb) { enum dma_data_direction dir = DMA_TO_DEVICE; - struct sk_buff *skb = NULL; int seg; - skb = (struct sk_buff *)sg->skb; if (unlikely(xfrm_offload(skb))) dir = DMA_BIDIRECTIONAL; diff --git a/drivers/net/ethernet/marvell/octeontx2/nic/otx2_common.h b/drivers/net/ethernet/marvell/octeontx2/nic/otx2_common.h index 44cd56a0c2c4..9a80450857f8 100644 --- a/drivers/net/ethernet/marvell/octeontx2/nic/otx2_common.h +++ b/drivers/net/ethernet/marvell/octeontx2/nic/otx2_common.h @@ -1253,7 +1253,8 @@ static inline int mcam_entry_cmp(const void *a, const void *b) dma_addr_t otx2_dma_map_skb_frag(struct otx2_nic *pfvf, struct sk_buff *skb, int seg, int *len); -void otx2_dma_unmap_skb_frags(struct otx2_nic *pfvf, struct sg_list *sg); +void otx2_dma_unmap_skb_frags(struct otx2_nic *pfvf, struct sg_list *sg, + struct sk_buff *skb); int otx2_read_free_sqe(struct otx2_nic *pfvf, u16 qidx); void otx2_queue_vf_work(struct mbox *mw, struct workqueue_struct *mbox_wq, int first, int mdevs, u64 intr); diff --git a/drivers/net/ethernet/marvell/octeontx2/nic/otx2_txrx.c b/drivers/net/ethernet/marvell/octeontx2/nic/otx2_txrx.c index 8d2d607bc92f..66dc8cc15486 100644 --- a/drivers/net/ethernet/marvell/octeontx2/nic/otx2_txrx.c +++ b/drivers/net/ethernet/marvell/octeontx2/nic/otx2_txrx.c @@ -160,7 +160,7 @@ static void otx2_snd_pkt_handler(struct otx2_nic *pfvf, *tx_bytes += skb->len; (*tx_pkts)++; - otx2_dma_unmap_skb_frags(pfvf, sg); + otx2_dma_unmap_skb_frags(pfvf, sg, skb); napi_consume_skb(skb, budget); sg->skb = (u64)NULL; } @@ -872,7 +872,7 @@ static int otx2_dma_map_tso_skb(struct otx2_nic *pfvf, } return 0; unmap: - otx2_dma_unmap_skb_frags(pfvf, sg); + otx2_dma_unmap_skb_frags(pfvf, sg, skb); return -EINVAL; } @@ -1252,7 +1252,7 @@ bool otx2_sq_append_skb(void *dev, struct netdev_queue *txq, ret = otx2_sqe_add_sg(pfvf, sq, skb, num_segs, &offset); if (!ret) { - otx2_dma_unmap_skb_frags(pfvf, &sq->sg[sq->head]); + otx2_dma_unmap_skb_frags(pfvf, &sq->sg[sq->head], skb); return false; } @@ -1344,7 +1344,7 @@ void otx2_cleanup_tx_cqes(struct otx2_nic *pfvf, struct otx2_cq_queue *cq) if (skb) { tx_bytes += skb->len; tx_pkts++; - otx2_dma_unmap_skb_frags(pfvf, sg); + otx2_dma_unmap_skb_frags(pfvf, sg, skb); dev_kfree_skb_any(skb); sg->skb = (u64)NULL; } @@ -1399,7 +1399,7 @@ void otx2_free_pending_sqe(struct otx2_nic *pfvf) if (skb) { tx_bytes += skb->len; tx_pkts++; - otx2_dma_unmap_skb_frags(pfvf, sg); + otx2_dma_unmap_skb_frags(pfvf, sg, skb); dev_kfree_skb_any(skb); sg->skb = (u64)NULL; } diff --git a/drivers/net/ethernet/marvell/octeontx2/nic/qos.c b/drivers/net/ethernet/marvell/octeontx2/nic/qos.c index f160b1618efa..2ede0b84e5f5 100644 --- a/drivers/net/ethernet/marvell/octeontx2/nic/qos.c +++ b/drivers/net/ethernet/marvell/octeontx2/nic/qos.c @@ -331,6 +331,8 @@ static void otx2_qos_sw_node_delete(struct otx2_nic *pfvf, otx2_qos_update_tx_netdev_queues(pfvf); } + synchronize_net(); + list_del(&node->list); kfree(node); } diff --git a/drivers/net/ethernet/mellanox/mlx4/intf.c b/drivers/net/ethernet/mellanox/mlx4/intf.c index 82e467c45d23..31860b4abe43 100644 --- a/drivers/net/ethernet/mellanox/mlx4/intf.c +++ b/drivers/net/ethernet/mellanox/mlx4/intf.c @@ -43,23 +43,12 @@ static DEFINE_IDA(mlx4_adev_ida); static bool is_eth_supported(struct mlx4_dev *dev) { - for (int port = 1; port <= dev->caps.num_ports; port++) - if (dev->caps.port_type[port] == MLX4_PORT_TYPE_ETH) - return true; - - return false; + return true; } static bool is_ib_supported(struct mlx4_dev *dev) { - for (int port = 1; port <= dev->caps.num_ports; port++) - if (dev->caps.port_type[port] == MLX4_PORT_TYPE_IB) - return true; - - if (dev->caps.flags & MLX4_DEV_CAP_FLAG_IBOE) - return true; - - return false; + return true; } static const struct mlx4_adev_device { diff --git a/drivers/net/ethernet/mellanox/mlx5/core/devlink.c b/drivers/net/ethernet/mellanox/mlx5/core/devlink.c index b9026cc64383..30a97e48dda7 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/devlink.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/devlink.c @@ -542,6 +542,12 @@ static int mlx5_devlink_num_doorbells_validate(struct devlink *devlink, u32 id, u32 val32 = val->vu32; u32 max_num_channels; + if (mlx5_dev_is_lightweight(mdev)) { + NL_SET_ERR_MSG_MOD(extack, + "Setting num_doorbells requires full device initialization; reload the device first"); + return -EOPNOTSUPP; + } + max_num_channels = mlx5e_get_max_num_channels(mdev); if (val32 > max_num_channels) { NL_SET_ERR_MSG_FMT_MOD(extack, diff --git a/drivers/net/ethernet/mellanox/mlx5/core/dpll.c b/drivers/net/ethernet/mellanox/mlx5/core/dpll.c index 7c69d9029bfa..54ba7c330d66 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/dpll.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/dpll.c @@ -138,7 +138,7 @@ mlx5_dpll_pin_ffo_get(struct mlx5_dpll_synce_status *synce_status, { if (!synce_status->oper_freq_measure) return -ENODATA; - *ffo = 1000000LL * synce_status->frequency_diff; + *ffo = synce_status->frequency_diff; return 0; } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en/ptp.c b/drivers/net/ethernet/mellanox/mlx5/core/en/ptp.c index 723f66a6bd63..2e1c3bb5a959 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en/ptp.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en/ptp.c @@ -98,7 +98,7 @@ static void mlx5e_skb_cb_hwtstamp_tx(struct sk_buff *skb, ptpsq->cq_stats->abort_abs_diff_ns += diff; if (diff > (NSEC_PER_SEC >> 1) && !test_and_set_bit(MLX5E_SQ_STATE_RECOVERING, &sq->state)) { - netdev_warn(sq->channel->netdev, + netdev_warn(sq->netdev, "PTP TX timestamp difference between CQE and port exceeds threshold: %lld ns, recovering SQ %u\n", (s64)diff, sq->sqn); queue_work(sq->priv->wq, &ptpsq->report_unhealthy_work); diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/en_accel.h b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/en_accel.h index 3f212e46fc2f..5a340f1435e6 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/en_accel.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/en_accel.h @@ -218,6 +218,12 @@ static inline void mlx5e_accel_tx_finish(struct mlx5e_txqsq *sq, #endif } +static inline bool +mlx5e_accel_shampo_can_merge(struct mlx5e_rq *rq, struct mlx5_cqe64 *cqe) +{ + return mlx5e_psp_shampo_can_merge(rq->hw_gro_data->skb, cqe); +} + static inline int mlx5e_accel_init_rx(struct mlx5e_priv *priv) { return mlx5e_ktls_init_rx(priv); 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 db260e3d1412..e6dd911475e3 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/ipsec.c @@ -958,6 +958,9 @@ static int mlx5e_ipsec_netevent_event(struct notifier_block *nb, xa_for_each_marked(&ipsec->sadb, idx, sa_entry, MLX5E_IPSEC_TUNNEL_SA) { attrs = &sa_entry->attrs; + if (attrs->addrs.family != n->tbl->family) + continue; + if (attrs->addrs.family == AF_INET) { if (!neigh_key_eq32(n, &attrs->addrs.saddr.a4) && !neigh_key_eq32(n, &attrs->addrs.daddr.a4)) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/psp_rxtx.h b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/psp_rxtx.h index 2b080c39cc37..9fd1ee789de0 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_accel/psp_rxtx.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_accel/psp_rxtx.h @@ -85,6 +85,13 @@ static inline bool mlx5e_psp_is_rx_flow(struct mlx5_cqe64 *cqe) return MLX5_PSP_METADATA_MARKER(be32_to_cpu(cqe->ft_metadata)); } +static inline bool +mlx5e_psp_shampo_can_merge(struct sk_buff *skb, struct mlx5_cqe64 *cqe) +{ + /* PSP packets cannot be merged. */ + return !skb_ext_exist(skb, SKB_EXT_PSP) && !mlx5e_psp_is_rx_flow(cqe); +} + bool mlx5e_psp_offload_handle_rx_skb(struct net_device *netdev, struct sk_buff *skb, struct mlx5_cqe64 *cqe); #else @@ -110,6 +117,12 @@ static inline bool mlx5e_psp_is_rx_flow(struct mlx5_cqe64 *cqe) return false; } +static inline bool +mlx5e_psp_shampo_can_merge(struct sk_buff *skb, struct mlx5_cqe64 *cqe) +{ + return true; +} + static inline bool mlx5e_psp_offload_handle_rx_skb(struct net_device *netdev, struct sk_buff *skb, struct mlx5_cqe64 *cqe) diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_ethtool.c b/drivers/net/ethernet/mellanox/mlx5/core/en_ethtool.c index 3ed59ced0407..f38e033ab8fa 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_ethtool.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_ethtool.c @@ -403,11 +403,6 @@ static bool mlx5e_ethtool_set_tcp_data_split(struct mlx5e_priv *priv, return false; } - /* Might need to disable HW-GRO if it was kept on due to hds. */ - if (tcp_data_split == ETHTOOL_TCP_DATA_SPLIT_DISABLED && - dev->cfg->hds_config == ETHTOOL_TCP_DATA_SPLIT_ENABLED) - netdev_update_features(priv->netdev); - return true; } @@ -468,13 +463,23 @@ static int mlx5e_set_ringparam(struct net_device *dev, struct netlink_ext_ack *extack) { struct mlx5e_priv *priv = netdev_priv(dev); + int err; if (!mlx5e_ethtool_set_tcp_data_split(priv, kernel_param->tcp_data_split, extack)) return -EINVAL; - return mlx5e_ethtool_set_ringparam(priv, param, extack); + err = mlx5e_ethtool_set_ringparam(priv, param, extack); + if (err) + return err; + + /* Might need to disable HW-GRO if it was kept on due to hds. */ + if (kernel_param->tcp_data_split == ETHTOOL_TCP_DATA_SPLIT_DISABLED && + dev->cfg->hds_config == ETHTOOL_TCP_DATA_SPLIT_ENABLED) + netdev_update_features(priv->netdev); + + return 0; } void mlx5e_ethtool_get_channels(struct mlx5e_priv *priv, diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c index 4c6060d54fbe..38ce7d0a9001 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_main.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_main.c @@ -3075,7 +3075,6 @@ void mlx5e_close_channels(struct mlx5e_channels *chs) { int i; - ASSERT_RTNL(); if (chs->ptp) { mlx5e_ptp_close(chs->ptp); chs->ptp = NULL; diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c b/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c index 903af3b3e779..d49f26323b1e 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_rx.c @@ -49,6 +49,7 @@ #include "en_rep.h" #include "en/rep/tc.h" #include "ipoib/ipoib.h" +#include "en_accel/en_accel.h" #include "en_accel/ipsec.h" #include "en_accel/macsec.h" #include "en_accel/psp_rxtx.h" @@ -2268,8 +2269,9 @@ static void mlx5e_handle_rx_cqe_mpwrq_shampo(struct mlx5e_rq *rq, struct mlx5_cq } if (*skb && - !(match && mlx5e_hw_gro_skb_has_enough_space(*skb, data_bcnt, - page_size))) { + !(match && + mlx5e_hw_gro_skb_has_enough_space(*skb, data_bcnt, page_size) && + mlx5e_accel_shampo_can_merge(rq, cqe))) { match = false; mlx5e_shampo_flush_skb(rq, cqe, match); } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/en_selftest.c b/drivers/net/ethernet/mellanox/mlx5/core/en_selftest.c index 1dcdb86690bb..8eb9a9469549 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/en_selftest.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/en_selftest.c @@ -166,6 +166,10 @@ mlx5e_test_loopback_validate(struct sk_buff *skb, struct udphdr *udph; struct iphdr *iph; + skb = skb_share_check(skb, GFP_ATOMIC); + if (!skb) + goto out; + if (skb_linearize(skb)) goto out; 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 54761754e657..d6958ba5dcc2 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 @@ -63,6 +63,7 @@ static int mlx5_fs_init_hws_actions_pool(struct mlx5_core_dev *dev, xa_init(&hws_pool->el2tol3tnl_pools); xa_init(&hws_pool->el2tol2tnl_pools); xa_init(&hws_pool->mh_pools); + mutex_init(&hws_pool->mh_pools_lock); xa_init(&hws_pool->table_dests); xa_init(&hws_pool->vport_dests); xa_init(&hws_pool->vport_vhca_dests); @@ -111,6 +112,7 @@ static void mlx5_fs_cleanup_hws_actions_pool(struct mlx5_fs_hws_context *fs_ctx) xa_for_each(&hws_pool->mh_pools, i, pool) mlx5_fs_destroy_mh_pool(pool, &hws_pool->mh_pools, i); xa_destroy(&hws_pool->mh_pools); + mutex_destroy(&hws_pool->mh_pools_lock); xa_for_each(&hws_pool->el2tol2tnl_pools, i, pool) mlx5_fs_destroy_pr_pool(pool, &hws_pool->el2tol2tnl_pools, i); xa_destroy(&hws_pool->el2tol2tnl_pools); @@ -1229,7 +1231,7 @@ static struct mlx5_fs_pool * mlx5_fs_get_pr_encap_pool(struct mlx5_core_dev *dev, struct xarray *pr_pools, enum mlx5hws_action_type reformat_type, size_t size) { - struct mlx5_fs_pool *pr_pool; + struct mlx5_fs_pool *pr_pool, *old; unsigned long index = size; int err; @@ -1243,13 +1245,14 @@ mlx5_fs_get_pr_encap_pool(struct mlx5_core_dev *dev, struct xarray *pr_pools, err = mlx5_fs_hws_pr_pool_init(pr_pool, dev, size, reformat_type); if (err) goto free_pr_pool; - err = xa_insert(pr_pools, index, pr_pool, GFP_KERNEL); - if (err) - goto cleanup_pr_pool; - return pr_pool; + old = xa_cmpxchg(pr_pools, index, NULL, pr_pool, GFP_KERNEL); + if (!old) + return pr_pool; -cleanup_pr_pool: mlx5_fs_hws_pr_pool_cleanup(pr_pool); + kfree(pr_pool); + return xa_is_err(old) ? ERR_PTR(xa_err(old)) : old; + free_pr_pool: kfree(pr_pool); return ERR_PTR(err); @@ -1457,6 +1460,23 @@ mlx5_fs_destroy_mh_pool(struct mlx5_fs_pool *pool, struct xarray *mh_pools, kfree(pool); } +static struct mlx5_fs_pool * +mlx5_fs_find_mh_pool(struct xarray *mh_pools, + struct mlx5hws_action_mh_pattern *pattern, + unsigned long *cnt) +{ + struct mlx5_fs_pool *pool; + unsigned long i; + + *cnt = 0; + xa_for_each(mh_pools, i, pool) { + if (mlx5_fs_hws_mh_pool_match(pool, pattern)) + return pool; + (*cnt)++; + } + return NULL; +} + static int mlx5_cmd_hws_modify_header_alloc(struct mlx5_flow_root_namespace *ns, u8 namespace, u8 num_actions, void *modify_actions, @@ -1467,33 +1487,28 @@ static int mlx5_cmd_hws_modify_header_alloc(struct mlx5_flow_root_namespace *ns, struct mlx5_fs_hws_mh *mh_data = NULL; struct mlx5hws_action *hws_action; struct mlx5_fs_pool *pool; - unsigned long i, cnt = 0; - bool known_pattern; + unsigned long cnt; int err; pattern.sz = MLX5_UN_SZ_BYTES(set_add_copy_action_in_auto) * num_actions; pattern.data = modify_actions; - known_pattern = false; - xa_for_each(&hws_pool->mh_pools, i, pool) { - if (mlx5_fs_hws_mh_pool_match(pool, &pattern)) { - known_pattern = true; - break; - } - cnt++; - } - - if (!known_pattern) { - pool = mlx5_fs_create_mh_pool(ns->dev, &pattern, - &hws_pool->mh_pools, cnt); + pool = mlx5_fs_find_mh_pool(&hws_pool->mh_pools, &pattern, &cnt); + if (!pool) { + mutex_lock(&hws_pool->mh_pools_lock); + pool = mlx5_fs_find_mh_pool(&hws_pool->mh_pools, &pattern, + &cnt); + if (!pool) + pool = mlx5_fs_create_mh_pool(ns->dev, &pattern, + &hws_pool->mh_pools, cnt); + mutex_unlock(&hws_pool->mh_pools_lock); if (IS_ERR(pool)) return PTR_ERR(pool); } + mh_data = mlx5_fs_hws_mh_pool_acquire_mh(pool); - if (IS_ERR(mh_data)) { - err = PTR_ERR(mh_data); - goto destroy_pool; - } + if (IS_ERR(mh_data)) + return PTR_ERR(mh_data); hws_action = mh_data->bulk->hws_action; mh_data->data = kmemdup(pattern.data, pattern.sz, GFP_KERNEL); if (!mh_data->data) { @@ -1509,9 +1524,6 @@ static int mlx5_cmd_hws_modify_header_alloc(struct mlx5_flow_root_namespace *ns, release_mh: mlx5_fs_hws_mh_pool_release_mh(pool, mh_data); -destroy_pool: - if (!known_pattern) - mlx5_fs_destroy_mh_pool(pool, &hws_pool->mh_pools, cnt); return err; } 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 20cdacd8f12e..cf068fb5bdbf 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 @@ -19,6 +19,7 @@ struct mlx5_fs_hws_actions_pool { struct xarray el2tol3tnl_pools; struct xarray el2tol2tnl_pools; struct xarray mh_pools; + struct mutex mh_pools_lock; /* serializes pool creation */ struct xarray table_dests; struct xarray vport_vhca_dests; struct xarray vport_dests; diff --git a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws_pools.c b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws_pools.c index 86828e329187..05aa143fa088 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws_pools.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws_pools.c @@ -3,6 +3,7 @@ #include #include "fs_hws_pools.h" +#include "internal.h" #define MLX5_FS_HWS_DEFAULT_BULK_LEN 65536 #define MLX5_FS_HWS_POOL_MAX_THRESHOLD BIT(18) @@ -389,7 +390,7 @@ bool mlx5_fs_hws_mh_pool_match(struct mlx5_fs_pool *mh_pool, struct mlx5hws_action_mh_pattern *pattern) { struct mlx5hws_action_mh_pattern *pool_pattern; - int num_actions, i; + int num_actions; pool_pattern = mh_pool->pool_ctx; if (WARN_ON_ONCE(!pool_pattern)) @@ -398,12 +399,8 @@ bool mlx5_fs_hws_mh_pool_match(struct mlx5_fs_pool *mh_pool, if (pattern->sz != pool_pattern->sz) return false; num_actions = pattern->sz / MLX5_UN_SZ_BYTES(set_add_copy_action_in_auto); - for (i = 0; i < num_actions; i++) { - if ((__force __be32)pattern->data[i] != - (__force __be32)pool_pattern->data[i]) - return false; - } - return true; + return mlx5hws_pat_compare_pattern(num_actions, pool_pattern->data, + num_actions, pattern->data); } struct mlx5hws_action *mlx5_fc_get_hws_action(struct mlx5hws_context *ctx, diff --git a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/pat_arg.c b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/pat_arg.c index 9af449c2b4d5..a49115f04025 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/pat_arg.c +++ b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/pat_arg.c @@ -96,10 +96,10 @@ void mlx5hws_pat_uninit_pattern_cache(struct mlx5hws_pattern_cache *cache) kfree(cache); } -static bool mlx5hws_pat_compare_pattern(int cur_num_of_actions, - __be64 cur_actions[], - int num_of_actions, - __be64 actions[]) +bool mlx5hws_pat_compare_pattern(int cur_num_of_actions, + __be64 cur_actions[], + int num_of_actions, + __be64 actions[]) { int i; @@ -116,8 +116,8 @@ static bool mlx5hws_pat_compare_pattern(int cur_num_of_actions, return false; } else { /* Compare just the control, not the values */ - if ((__force __be32)actions[i] != - (__force __be32)cur_actions[i]) + if (*(__be32 *)&actions[i] != + *(__be32 *)&cur_actions[i]) return false; } } diff --git a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/pat_arg.h b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/pat_arg.h index 7fbd8dc7aa18..2be7787104e1 100644 --- a/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/pat_arg.h +++ b/drivers/net/ethernet/mellanox/mlx5/core/steering/hws/pat_arg.h @@ -49,6 +49,11 @@ int mlx5hws_pat_init_pattern_cache(struct mlx5hws_pattern_cache **cache); void mlx5hws_pat_uninit_pattern_cache(struct mlx5hws_pattern_cache *cache); +bool mlx5hws_pat_compare_pattern(int cur_num_of_actions, + __be64 cur_actions[], + int num_of_actions, + __be64 actions[]); + bool mlx5hws_pat_verify_actions(struct mlx5hws_context *ctx, __be64 pattern[], size_t sz); int mlx5hws_arg_create(struct mlx5hws_context *ctx, diff --git a/drivers/net/ethernet/meta/fbnic/fbnic.h b/drivers/net/ethernet/meta/fbnic/fbnic.h index d0715695c43e..0d381a6273a5 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic.h +++ b/drivers/net/ethernet/meta/fbnic/fbnic.h @@ -160,7 +160,12 @@ void fbnic_fw_wr32(struct fbnic_dev *fbd, u32 reg, u32 val); static inline bool fbnic_bmc_present(struct fbnic_dev *fbd) { - return fbd->fw_cap.bmc_present; + return test_bit(FBNIC_FW_CAP_F_BMC_PRESENT, &fbd->fw_cap.state); +} + +static inline bool fbnic_bmc_all_multi(struct fbnic_dev *fbd) +{ + return test_bit(FBNIC_FW_CAP_F_BMC_ALL_MULTI, &fbd->fw_cap.state); } static inline bool fbnic_init_failure(struct fbnic_dev *fbd) diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_fw.c b/drivers/net/ethernet/meta/fbnic/fbnic_fw.c index 6d7eb8479edf..ce2a66aeb8d2 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_fw.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_fw.c @@ -620,11 +620,55 @@ static int fbnic_fw_parse_bmc_addrs(u8 bmc_mac_addr[][ETH_ALEN], return 0; } +static int fbnic_fw_parse_bmc_cap(struct fbnic_dev *fbd, + struct fbnic_tlv_msg **results) +{ + struct fbnic_tlv_msg *attr; + bool bmc_present = false; + u32 all_multi = 0; + int err; + + /* FW reports the BMC present once its NC-SI channel is enabled, before + * it has a MAC. No MAC array means nothing to program, so treat it as + * absent rather than rejecting the message. + */ + attr = results[FBNIC_FW_CAP_RESP_BMC_PRESENT] ? + results[FBNIC_FW_CAP_RESP_BMC_MAC_ARRAY] : NULL; + if (attr) { + err = fbnic_fw_parse_bmc_addrs(fbd->fw_cap.bmc_mac_addr, + attr, 4); + if (err) + return err; + + all_multi = fta_get_uint(results, + FBNIC_FW_CAP_RESP_BMC_ALL_MULTI); + bmc_present = true; + } else { + memset(fbd->fw_cap.bmc_mac_addr, 0, + sizeof(fbd->fw_cap.bmc_mac_addr)); + } + + /* all_multi is only read out of the message when a BMC is present, so + * it is never set on its own and callers can test it without pairing + * it with the presence check. + */ + assign_bit(FBNIC_FW_CAP_F_BMC_PRESENT, &fbd->fw_cap.state, bmc_present); + assign_bit(FBNIC_FW_CAP_F_BMC_ALL_MULTI, &fbd->fw_cap.state, all_multi); + + /* Always assume we need a BMC reinit. The barrier orders the BMC state + * published above ahead of the flag, pairing with the ordering implied + * by the test_and_clear_bit() in fbnic_bmc_rpc_check(). + */ + smp_mb__before_atomic(); + set_bit(FBNIC_FW_CAP_F_BMC_TCAM_REINIT, &fbd->fw_cap.state); + + return 0; +} + static int fbnic_fw_parse_cap_resp(void *opaque, struct fbnic_tlv_msg **results) { - u32 all_multi = 0, version = 0; struct fbnic_dev *fbd = opaque; - bool bmc_present; + u32 version = 0; int err; version = fta_get_uint(results, FBNIC_FW_CAP_RESP_VERSION); @@ -684,37 +728,13 @@ static int fbnic_fw_parse_cap_resp(void *opaque, struct fbnic_tlv_msg **results) fbd->fw_cap.link_fec = fta_get_uint(results, FBNIC_FW_CAP_RESP_FW_LINK_FEC); - bmc_present = !!results[FBNIC_FW_CAP_RESP_BMC_PRESENT]; - if (bmc_present) { - struct fbnic_tlv_msg *attr; - - attr = results[FBNIC_FW_CAP_RESP_BMC_MAC_ARRAY]; - if (!attr) - return -EINVAL; - - err = fbnic_fw_parse_bmc_addrs(fbd->fw_cap.bmc_mac_addr, - attr, 4); - if (err) - return err; - - all_multi = - fta_get_uint(results, FBNIC_FW_CAP_RESP_BMC_ALL_MULTI); - } else { - memset(fbd->fw_cap.bmc_mac_addr, 0, - sizeof(fbd->fw_cap.bmc_mac_addr)); - } - - fbd->fw_cap.bmc_present = bmc_present; - - if (results[FBNIC_FW_CAP_RESP_BMC_ALL_MULTI] || !bmc_present) - fbd->fw_cap.all_multi = all_multi; + err = fbnic_fw_parse_bmc_cap(fbd, results); + if (err) + return err; fbd->fw_cap.anti_rollback_version = fta_get_uint(results, FBNIC_FW_CAP_RESP_ANTI_ROLLBACK_VERSION); - /* Always assume we need a BMC reinit */ - fbd->fw_cap.need_bmc_tcam_reinit = true; - return 0; } diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_fw.h b/drivers/net/ethernet/meta/fbnic/fbnic_fw.h index 5f9969247e30..e542b17bdac7 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_fw.h +++ b/drivers/net/ethernet/meta/fbnic/fbnic_fw.h @@ -45,7 +45,18 @@ struct fbnic_fw_ver { char commit[FBNIC_FW_CAP_RESP_COMMIT_MAX_SIZE]; }; +/* Bits in fbnic_fw_cap.state. The firmware mailbox publishes the BMC state + * and the service task consumes it, so they are updated with atomic bitops. + */ +enum { + FBNIC_FW_CAP_F_BMC_PRESENT, + FBNIC_FW_CAP_F_BMC_ALL_MULTI, + FBNIC_FW_CAP_F_BMC_TCAM_REINIT, + FBNIC_FW_CAP_F_BMC_MACDA_SYNC, +}; + struct fbnic_fw_cap { + unsigned long state; struct { struct fbnic_fw_ver mgmt, bootloader; } running; @@ -54,10 +65,6 @@ struct fbnic_fw_cap { } stored; u8 active_slot; u8 bmc_mac_addr[4][ETH_ALEN]; - u8 bmc_present : 1; - u8 need_bmc_tcam_reinit : 1; - u8 need_bmc_macda_sync : 1; - u8 all_multi : 1; u8 link_speed; u8 link_fec; u32 anti_rollback_version; diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_rpc.c b/drivers/net/ethernet/meta/fbnic/fbnic_rpc.c index bc0f38b6a2b2..f94ce73ddc10 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_rpc.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_rpc.c @@ -117,7 +117,7 @@ void fbnic_bmc_rpc_all_multi_config(struct fbnic_dev *fbd, * BMC. */ mac_addr = &fbd->mac_addr[fbd->mac_addr_boundary - 1]; - if (fbnic_bmc_present(fbd) && fbd->fw_cap.all_multi) { + if (fbnic_bmc_all_multi(fbd)) { if (mac_addr->state != FBNIC_TCAM_S_VALID) { eth_zero_addr(mac_addr->value.addr8); eth_broadcast_addr(mac_addr->mask.addr8); @@ -148,7 +148,7 @@ void fbnic_bmc_rpc_all_multi_config(struct fbnic_dev *fbd, /* If we are not enabling the rule just delete it. We will fall * back to the RSS rules that support the multicast addresses. */ - if (!fbnic_bmc_present(fbd) || !fbd->fw_cap.all_multi || enable_host) { + if (!fbnic_bmc_all_multi(fbd) || enable_host) { if (act_tcam->state == FBNIC_TCAM_S_VALID) act_tcam->state = FBNIC_TCAM_S_DELETE; return; @@ -242,20 +242,25 @@ void fbnic_bmc_rpc_check(struct fbnic_dev *fbd) { int err; - if (fbd->fw_cap.need_bmc_tcam_reinit) { + /* Consume the flag before the state it advertises. The ordering + * implied by test_and_clear_bit() pairs with the barrier in + * fbnic_fw_parse_bmc_cap(), and claiming it atomically means a set + * racing with us is kept and retried rather than overwritten. + */ + if (test_and_clear_bit(FBNIC_FW_CAP_F_BMC_TCAM_REINIT, + &fbd->fw_cap.state)) { fbnic_bmc_rpc_init(fbd); netif_addr_lock_bh(fbd->netdev); __fbnic_set_rx_mode(fbd, &fbd->netdev->uc, &fbd->netdev->mc); netif_addr_unlock_bh(fbd->netdev); - fbd->fw_cap.need_bmc_tcam_reinit = false; } - if (fbd->fw_cap.need_bmc_macda_sync) { + if (test_and_clear_bit(FBNIC_FW_CAP_F_BMC_MACDA_SYNC, + &fbd->fw_cap.state)) { err = fbnic_fw_xmit_rpc_macda_sync(fbd); if (err) dev_warn(fbd->dev, "Writing MACDA table to FW failed, err: %d\n", err); - fbd->fw_cap.need_bmc_macda_sync = false; } } @@ -488,8 +493,7 @@ void fbnic_promisc_sync(struct fbnic_dev *fbd, mac_addr->act_tcam); mac_addr->state = FBNIC_TCAM_S_ADD; } - } else if (mc_promisc && - (!fbnic_bmc_present(fbd) || !fbd->fw_cap.all_multi)) { + } else if (mc_promisc && !fbnic_bmc_all_multi(fbd)) { /* We have to add a special handler for multicast as the * BMC may have an all-multi rule already in place. As such * adding a rule ourselves won't do any good so we will have @@ -660,12 +664,12 @@ void fbnic_write_macda(struct fbnic_dev *fbd) } /* If reinitializing the BMC TCAM we are doing an initial update */ - if (fbd->fw_cap.need_bmc_tcam_reinit) + if (test_bit(FBNIC_FW_CAP_F_BMC_TCAM_REINIT, &fbd->fw_cap.state)) updates++; /* If needed notify firmware of changes to MACDA TCAM */ if (updates != 0 && fbnic_bmc_present(fbd)) - fbd->fw_cap.need_bmc_macda_sync = true; + set_bit(FBNIC_FW_CAP_F_BMC_MACDA_SYNC, &fbd->fw_cap.state); } static void fbnic_clear_act_tcam(struct fbnic_dev *fbd, unsigned int idx) diff --git a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c index 10caacffee0f..69cd96a4508f 100644 --- a/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c +++ b/drivers/net/ethernet/meta/fbnic/fbnic_txrx.c @@ -1011,7 +1011,7 @@ static void fbnic_pkt_prepare(struct fbnic_napi_vector *nv, u64 rcd, /* Build frame around buffer */ hdr_start = page_address(page) + hdr_pg_start; - net_prefetch(pkt->buff.data); + net_prefetch(hdr_start + headroom); xdp_prepare_buff(&pkt->buff, hdr_start, headroom, len - FBNIC_RX_PAD, true); diff --git a/drivers/net/ethernet/microchip/fdma/fdma_api.c b/drivers/net/ethernet/microchip/fdma/fdma_api.c index e78c3590da9e..a85dcb492829 100644 --- a/drivers/net/ethernet/microchip/fdma/fdma_api.c +++ b/drivers/net/ethernet/microchip/fdma/fdma_api.c @@ -12,10 +12,18 @@ static int __fdma_db_add(struct fdma *fdma, int dcb_idx, int db_idx, u64 status, int db_idx, u64 *dataptr)) { struct fdma_db *db = fdma_db_get(fdma, dcb_idx, db_idx); + u64 dataptr; + int err; - db->status = status; + db->status = cpu_to_le64(status); - return cb(fdma, dcb_idx, db_idx, &db->dataptr); + err = cb(fdma, dcb_idx, db_idx, &dataptr); + if (unlikely(err)) + return err; + + db->dataptr = cpu_to_le64(dataptr); + + return 0; } /* Add a DB to a DCB, using the callback set in the fdma_ops struct. */ @@ -35,22 +43,47 @@ int __fdma_dcb_add(struct fdma *fdma, int dcb_idx, u64 info, u64 status, u64 *dataptr)) { struct fdma_dcb *dcb = fdma_dcb_get(fdma, dcb_idx); + struct fdma_dcb *prev = fdma->last_dcb; + u64 nextptr; int i, err; + /* Per the FDMA datasheet, adding a DCB to an active channel takes + * three steps: + * 1) Write NEXT_PTR of the current last DCB with the LSB forced to + * FDMA_DCB_INVALID_DATA, and flush that write. + * 2) Clear the LSB to complete the link. + * 3) Reload the channel (FDMA_CH_RELOAD); this is done by the caller + * once the chain has been extended. + */ + for (i = 0; i < fdma->n_dbs; i++) { err = __fdma_db_add(fdma, dcb_idx, i, status, db_cb); if (unlikely(err)) return err; } - err = dcb_cb(fdma, dcb_idx, &fdma->last_dcb->nextptr); + err = dcb_cb(fdma, dcb_idx, &nextptr); if (unlikely(err)) return err; - fdma->last_dcb = dcb; + dcb->nextptr = cpu_to_le64(FDMA_DCB_INVALID_DATA); + dcb->info = cpu_to_le64(info); + + /* On the first DCB of fdma_dcbs_init() prev is the DCB itself; + * don't link it to itself. + */ + if (prev != dcb) { + /* Write NEXT_PTR of the current last DCB with the LSB forced + * to FDMA_DCB_INVALID_DATA, and flush that write. + */ + prev->nextptr = cpu_to_le64(nextptr | FDMA_DCB_INVALID_DATA); + dma_wmb(); + + /* Clear the LSB to complete the link. */ + prev->nextptr = cpu_to_le64(nextptr); + } - dcb->nextptr = FDMA_DCB_INVALID_DATA; - dcb->info = info; + fdma->last_dcb = dcb; return 0; } diff --git a/drivers/net/ethernet/microchip/fdma/fdma_api.h b/drivers/net/ethernet/microchip/fdma/fdma_api.h index d91affe8bd98..a1bd7b8a75c1 100644 --- a/drivers/net/ethernet/microchip/fdma/fdma_api.h +++ b/drivers/net/ethernet/microchip/fdma/fdma_api.h @@ -64,13 +64,13 @@ struct fdma; struct fdma_db { - u64 dataptr; - u64 status; + __le64 dataptr; + __le64 status; }; struct fdma_dcb { - u64 nextptr; - u64 info; + __le64 nextptr; + __le64 info; struct fdma_db db[FDMA_DB_MAX]; }; @@ -140,19 +140,25 @@ static inline bool fdma_dcb_is_reusable(struct fdma *fdma) /* Check if the FDMA has marked this DB as done. */ static inline bool fdma_db_is_done(struct fdma_db *db) { - return db->status & FDMA_DCB_STATUS_DONE; + return le64_to_cpu(db->status) & FDMA_DCB_STATUS_DONE; } /* Get the length of a DB. */ static inline int fdma_db_len_get(struct fdma_db *db) { - return FDMA_DCB_STATUS_BLOCKL(db->status); + return FDMA_DCB_STATUS_BLOCKL(le64_to_cpu(db->status)); +} + +/* Get the dataptr of a DB. */ +static inline u64 fdma_db_dataptr_get(struct fdma_db *db) +{ + return le64_to_cpu(db->dataptr); } /* Set the length of a DB. */ static inline void fdma_dcb_len_set(struct fdma_dcb *dcb, u32 len) { - dcb->info = FDMA_DCB_INFO_DATAL(len); + dcb->info = cpu_to_le64(FDMA_DCB_INFO_DATAL(len)); } /* Get a DB by index. */ diff --git a/drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c b/drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c index 41d4ec7f2f57..5cc9b2321dad 100644 --- a/drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c +++ b/drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c @@ -337,14 +337,13 @@ static void lan966x_fdma_tx_clear_buf(struct lan966x *lan966x, int weight) struct lan966x_tx_dcb_buf *dcb_buf; struct fdma *fdma = &tx->fdma; struct xdp_frame_bulk bq; - unsigned long flags; bool clear = false; struct fdma_db *db; int i; xdp_frame_bulk_init(&bq); - spin_lock_irqsave(&lan966x->tx_lock, flags); + spin_lock(&lan966x->tx_lock); for (i = 0; i < fdma->n_dcbs; ++i) { dcb_buf = &tx->dcbs_buf[i]; @@ -389,7 +388,7 @@ static void lan966x_fdma_tx_clear_buf(struct lan966x *lan966x, int weight) if (clear) lan966x_fdma_wakeup_netdev(lan966x); - spin_unlock_irqrestore(&lan966x->tx_lock, flags); + spin_unlock(&lan966x->tx_lock); } static int lan966x_fdma_rx_check_frame(struct lan966x_rx *rx, u64 *src_port) @@ -406,8 +405,9 @@ static int lan966x_fdma_rx_check_frame(struct lan966x_rx *rx, u64 *src_port) return FDMA_ERROR; dma_sync_single_for_cpu(lan966x->dev, - (dma_addr_t)db->dataptr + XDP_PACKET_HEADROOM, - FDMA_DCB_STATUS_BLOCKL(db->status), + (dma_addr_t)fdma_db_dataptr_get(db) + + XDP_PACKET_HEADROOM, + fdma_db_len_get(db), DMA_FROM_DEVICE); lan966x_ifh_get_src_port(page_address(page) + XDP_PACKET_HEADROOM, @@ -419,7 +419,7 @@ static int lan966x_fdma_rx_check_frame(struct lan966x_rx *rx, u64 *src_port) if (!lan966x_xdp_port_present(port)) return FDMA_PASS; - return lan966x_xdp_run(port, page, FDMA_DCB_STATUS_BLOCKL(db->status)); + return lan966x_xdp_run(port, page, fdma_db_len_get(db)); } static struct sk_buff *lan966x_fdma_rx_get_frame(struct lan966x_rx *rx, @@ -443,7 +443,7 @@ static struct sk_buff *lan966x_fdma_rx_get_frame(struct lan966x_rx *rx, skb_mark_for_recycle(skb); skb_reserve(skb, XDP_PACKET_HEADROOM); - skb_put(skb, FDMA_DCB_STATUS_BLOCKL(db->status)); + skb_put(skb, fdma_db_len_get(db)); lan966x_ifh_get_timestamp(skb->data, ×tamp); @@ -686,7 +686,8 @@ int lan966x_fdma_xmit_xdpf(struct lan966x_port *port, void *ptr, u32 len) FDMA_DCB_STATUS_BLOCKO(0) | FDMA_DCB_STATUS_BLOCKL(next_dcb_buf->len), &fdma_nextptr_cb, - &lan966x_fdma_xdp_tx_dataptr_cb); + len ? &lan966x_fdma_xdp_tx_dataptr_cb : + &lan966x_fdma_tx_dataptr_cb); /* Start the transmission */ lan966x_fdma_tx_start(tx); diff --git a/drivers/net/ethernet/microchip/lan966x/lan966x_mac.c b/drivers/net/ethernet/microchip/lan966x/lan966x_mac.c index 7a2294a0d099..986c60ac2343 100644 --- a/drivers/net/ethernet/microchip/lan966x/lan966x_mac.c +++ b/drivers/net/ethernet/microchip/lan966x/lan966x_mac.c @@ -447,7 +447,7 @@ static void lan966x_mac_irq_process(struct lan966x *lan966x, u32 row, lan966x_mac_process_raw_entry(&raw_entries[column], mac, &vid, &dest_idx); - if (WARN_ON(dest_idx >= lan966x->num_phys_ports)) + if (dest_idx >= lan966x->num_phys_ports) continue; /* If the entry in SW is found, then there is nothing @@ -501,7 +501,7 @@ static void lan966x_mac_irq_process(struct lan966x *lan966x, u32 row, lan966x_mac_process_raw_entry(&raw_entries[column], mac, &vid, &dest_idx); - if (WARN_ON(dest_idx >= lan966x->num_phys_ports)) + if (dest_idx >= lan966x->num_phys_ports) continue; spin_lock(&lan966x->mac_lock); diff --git a/drivers/net/ethernet/microchip/lan966x/lan966x_main.c b/drivers/net/ethernet/microchip/lan966x/lan966x_main.c index 1179a6e127c5..e576bc7c6dee 100644 --- a/drivers/net/ethernet/microchip/lan966x/lan966x_main.c +++ b/drivers/net/ethernet/microchip/lan966x/lan966x_main.c @@ -253,9 +253,8 @@ static int lan966x_port_ifh_xmit(struct sk_buff *skb, lan_wr((__force u32)ifh[i], lan966x, QS_INJ_WR(grp)); } - /* Write frame */ - count = DIV_ROUND_UP(skb->len, 4); - last = skb->len % 4; + /* Write the whole words of the frame */ + count = skb->len / 4; for (i = 0; i < count; ++i) { /* Wait until the fifo is ready */ err = lan966x_port_inj_ready(lan966x, grp); @@ -265,6 +264,20 @@ static int lan966x_port_ifh_xmit(struct sk_buff *skb, lan_wr(((u32 *)skb->data)[i], lan966x, QS_INJ_WR(grp)); } + /* Write the last 1 to 3 bytes, zero padded to a whole word */ + last = skb->len % 4; + if (last) { + /* Wait until the fifo is ready */ + err = lan966x_port_inj_ready(lan966x, grp); + if (err) + goto err; + + val = 0; + memcpy(&val, skb->data + count * 4, last); + lan_wr(val, lan966x, QS_INJ_WR(grp)); + ++i; + } + /* Add padding */ while (i < (LAN966X_BUFFER_MIN_SZ / 4)) { /* Wait until the fifo is ready */ diff --git a/drivers/net/ethernet/microchip/lan966x/lan966x_ptp.c b/drivers/net/ethernet/microchip/lan966x/lan966x_ptp.c index 8c40db90ee8f..9be2cfe6feeb 100644 --- a/drivers/net/ethernet/microchip/lan966x/lan966x_ptp.c +++ b/drivers/net/ethernet/microchip/lan966x/lan966x_ptp.c @@ -376,9 +376,10 @@ static void lan966x_ptp_classify(struct lan966x_port *port, struct sk_buff *skb, *rew_op = IFH_REW_OP_TWO_STEP_PTP; } -static void lan966x_ptp_txtstamp_old_release(struct lan966x_port *port) +static unsigned int lan966x_ptp_txtstamp_old_release(struct lan966x_port *port) { struct sk_buff *skb, *skb_tmp; + unsigned int purged = 0; unsigned long flags; spin_lock_irqsave(&port->tx_skbs.lock, flags); @@ -389,14 +390,18 @@ static void lan966x_ptp_txtstamp_old_release(struct lan966x_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 lan966x_ptp_txtstamp_request(struct lan966x_port *port, struct sk_buff *skb) { struct lan966x *lan966x = port->lan966x; + unsigned int purged; unsigned long flags; u8 pdu_type; u8 rew_op; @@ -408,9 +413,10 @@ int lan966x_ptp_txtstamp_request(struct lan966x_port *port, if (rew_op != IFH_REW_OP_TWO_STEP_PTP) return 0; - lan966x_ptp_txtstamp_old_release(port); + purged = lan966x_ptp_txtstamp_old_release(port); spin_lock_irqsave(&lan966x->ptp_ts_id_lock, flags); + lan966x->ptp_skbs -= purged; if (lan966x->ptp_skbs == LAN966X_MAX_PTP_ID) { spin_unlock_irqrestore(&lan966x->ptp_ts_id_lock, flags); return -EBUSY; diff --git a/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_calendar.c b/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_calendar.c index e857640df185..4442c0c1a957 100644 --- a/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_calendar.c +++ b/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_calendar.c @@ -82,6 +82,9 @@ int lan969x_dsm_calendar_calc(struct sparx5 *sparx5, u32 taxi, struct lan969x_dsm_cal_dev_speed *speed; int err; + for (u32 i = 0; i < SPX5_DSM_CAL_LEN; i++) + data->schedule[i] = SPX5_DSM_CAL_EMPTY; + /* Maximum bandwidth for this taxi */ taxi_bw = (128 * 1000000) / sparx5_clk_period(sparx5->coreclock); @@ -125,7 +128,7 @@ int lan969x_dsm_calendar_calc(struct sparx5 *sparx5, u32 taxi, } if (n_devs == 0) { - data->schedule[0] = SPX5_DSM_CAL_EMPTY; + data->schedule[0] = SPX5_DSM_CAL_MAX_DEVS_PER_TAXI; return 0; } @@ -167,9 +170,6 @@ int lan969x_dsm_calendar_calc(struct sparx5 *sparx5, u32 taxi, return -EINVAL; } - for (u32 i = 0; i < SPX5_DSM_CAL_LEN; i++) - data->schedule[i] = SPX5_DSM_CAL_EMPTY; - /* Place the remaining devices */ for (u32 i = 0; i < DSM_CAL_DEV_MAX; i++) { speed = &dev_speeds[i]; diff --git a/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_fdma.c b/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_fdma.c index c7e0e58ff0f7..053d125eda65 100644 --- a/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_fdma.c +++ b/drivers/net/ethernet/microchip/sparx5/lan969x/lan969x_fdma.c @@ -54,10 +54,9 @@ static void lan969x_fdma_tx_clear_buf(struct sparx5 *sparx5, int weight) { struct fdma *fdma = &sparx5->tx.fdma; struct sparx5_tx_buf *db; - unsigned long flags; int i; - spin_lock_irqsave(&sparx5->tx_lock, flags); + spin_lock(&sparx5->tx_lock); for (i = 0; i < fdma->n_dcbs; ++i) { db = &sparx5->tx.dbs[i]; @@ -83,7 +82,7 @@ static void lan969x_fdma_tx_clear_buf(struct sparx5 *sparx5, int weight) db->used = false; } - spin_unlock_irqrestore(&sparx5->tx_lock, flags); + spin_unlock(&sparx5->tx_lock); } static void lan969x_fdma_free_pages(struct sparx5_rx *rx) diff --git a/drivers/net/ethernet/microchip/sparx5/sparx5_fdma.c b/drivers/net/ethernet/microchip/sparx5/sparx5_fdma.c index dbe86f937b21..15ec9b053824 100644 --- a/drivers/net/ethernet/microchip/sparx5/sparx5_fdma.c +++ b/drivers/net/ethernet/microchip/sparx5/sparx5_fdma.c @@ -217,7 +217,6 @@ int sparx5_fdma_xmit(struct sparx5 *sparx5, u32 *ifh, struct sk_buff *skb, struct fdma *fdma = &tx->fdma; void *virt_addr; - fdma_dcb_advance(fdma); if (!fdma_db_is_done(fdma_db_get(fdma, fdma->dcb_index, 0))) return -EINVAL; @@ -235,6 +234,8 @@ int sparx5_fdma_xmit(struct sparx5 *sparx5, u32 *ifh, struct sk_buff *skb, FDMA_DCB_STATUS_BLOCKO(0) | FDMA_DCB_STATUS_BLOCKL(skb->len + IFH_LEN * 4 + 4)); + fdma_dcb_advance(fdma); + sparx5_fdma_reload(sparx5, fdma); return NETDEV_TX_OK; diff --git a/drivers/net/ethernet/microchip/sparx5/sparx5_packet.c b/drivers/net/ethernet/microchip/sparx5/sparx5_packet.c index f713656f1fae..14c9ae673e35 100644 --- a/drivers/net/ethernet/microchip/sparx5/sparx5_packet.c +++ b/drivers/net/ethernet/microchip/sparx5/sparx5_packet.c @@ -169,8 +169,8 @@ static int sparx5_inject(struct sparx5 *sparx5, struct sk_buff *skb, struct net_device *ndev) { + u32 val, w, count, last; int grp = INJ_QUEUE; - u32 val, w, count; u8 *buf; val = spx5_rd(sparx5, QS_INJ_STATUS); @@ -189,14 +189,23 @@ static int sparx5_inject(struct sparx5 *sparx5, for (w = 0; w < IFH_LEN; w++) spx5_wr(ifh[w], sparx5, QS_INJ_WR(grp)); - /* Write words, round up */ - count = DIV_ROUND_UP(skb->len, 4); + /* Write the whole words of the frame */ + count = skb->len / 4; buf = skb->data; for (w = 0; w < count; w++, buf += 4) { val = get_unaligned((const u32 *)buf); spx5_wr(val, sparx5, QS_INJ_WR(grp)); } + /* Write the last 1 to 3 bytes, zero padded to a whole word */ + last = skb->len % 4; + if (last) { + val = 0; + memcpy(&val, buf, last); + spx5_wr(val, sparx5, QS_INJ_WR(grp)); + w++; + } + /* Add padding */ while (w < (60 / 4)) { spx5_wr(0, sparx5, QS_INJ_WR(grp)); diff --git a/drivers/net/ethernet/microchip/sparx5/sparx5_psfp.c b/drivers/net/ethernet/microchip/sparx5/sparx5_psfp.c index 83b37f95ee46..fa19a48f941d 100644 --- a/drivers/net/ethernet/microchip/sparx5/sparx5_psfp.c +++ b/drivers/net/ethernet/microchip/sparx5/sparx5_psfp.c @@ -322,6 +322,7 @@ void sparx5_psfp_init(struct sparx5 *sparx5) { const struct sparx5_ops *ops = sparx5->data->ops; const struct sparx5_sdlb_group *group; + u32 sg_ct_clks; int i; for (i = 0; i < sparx5->data->consts->n_lb_groups; i++) { @@ -330,7 +331,14 @@ void sparx5_psfp_init(struct sparx5 *sparx5) group->min_burst, group->frame_size, i); } - spx5_wr(ANA_AC_SG_CYCLETIME_UPDATE_PERIOD_SG_CT_UPDATE_ENA_SET(1), + /* Poll the stream gate cycle start times every 10 us. The core clock + * period is in picoseconds. + */ + sg_ct_clks = 10 * NSEC_PER_USEC * PSEC_PER_NSEC / + sparx5_clk_period(sparx5->coreclock); + + spx5_wr(ANA_AC_SG_CYCLETIME_UPDATE_PERIOD_SG_CT_CLKS_SET(sg_ct_clks) | + ANA_AC_SG_CYCLETIME_UPDATE_PERIOD_SG_CT_UPDATE_ENA_SET(1), sparx5, ANA_AC_SG_CYCLETIME_UPDATE_PERIOD); spx5_rmw(ANA_L2_FWD_CFG_ISDX_LOOKUP_ENA_SET(1), diff --git a/drivers/net/ethernet/microsoft/mana/gdma_main.c b/drivers/net/ethernet/microsoft/mana/gdma_main.c index 8e9bfc1d6a2a..5df4deee5784 100644 --- a/drivers/net/ethernet/microsoft/mana/gdma_main.c +++ b/drivers/net/ethernet/microsoft/mana/gdma_main.c @@ -2,49 +2,42 @@ /* Copyright (c) 2021, Microsoft Corporation. */ #include +#include #include +#include +#include #include -#include #include #include #include #include #include #include +#include +#include +#include #include +#include #include #include struct dentry *mana_debugfs_root; -struct mana_dev_recovery { - struct list_head list; - struct pci_dev *pdev; - enum gdma_eqe_type type; -}; - -static struct mana_dev_recovery_work { - struct list_head dev_list; - struct delayed_work work; - - /* Lock for dev_list above */ - spinlock_t lock; -} mana_dev_recovery_work; - -static u32 mana_gd_r32(struct gdma_context *g, u64 offset) +/* + * True if the underlying bus can allocate MSI-X vectors after probe time. + * Buses that size their vector pool at probe install no callback. + */ +static bool mana_gd_msix_can_alloc_dyn(struct gdma_context *gc) { - return readl(g->bar0_va + offset); -} + if (!gc->bus_ops || !gc->bus_ops->msix_can_alloc_dyn) + return false; -static u64 mana_gd_r64(struct gdma_context *g, u64 offset) -{ - return readq(g->bar0_va + offset); + return gc->bus_ops->msix_can_alloc_dyn(gc); } -static int mana_gd_init_pf_regs(struct pci_dev *pdev) +static int mana_gd_init_pf_regs(struct gdma_context *gc) { - struct gdma_context *gc = pci_get_drvdata(pdev); u64 remaining_barsize; u64 sriov_base_off; u64 sriov_shm_off; @@ -102,9 +95,8 @@ static int mana_gd_init_pf_regs(struct pci_dev *pdev) return 0; } -static int mana_gd_init_vf_regs(struct pci_dev *pdev) +static int mana_gd_init_vf_regs(struct gdma_context *gc) { - struct gdma_context *gc = pci_get_drvdata(pdev); u64 shm_off; gc->db_page_size = mana_gd_r32(gc, GDMA_REG_DB_PAGE_SIZE) & 0xFFFF; @@ -148,14 +140,12 @@ static int mana_gd_init_vf_regs(struct pci_dev *pdev) return 0; } -static int mana_gd_init_registers(struct pci_dev *pdev) +int mana_gd_init_registers(struct gdma_context *gc) { - struct gdma_context *gc = pci_get_drvdata(pdev); - if (gc->is_pf && !gc->is_pf2) - return mana_gd_init_pf_regs(pdev); + return mana_gd_init_pf_regs(gc); else - return mana_gd_init_vf_regs(pdev); + return mana_gd_init_vf_regs(gc); } /* Suppress logging when we set timeout to zero */ @@ -176,9 +166,8 @@ bool mana_need_log(struct gdma_context *gc, int err) return true; } -static int mana_gd_query_max_resources(struct pci_dev *pdev) +int mana_gd_query_max_resources(struct gdma_context *gc) { - struct gdma_context *gc = pci_get_drvdata(pdev); struct gdma_query_max_resources_resp resp = {}; struct gdma_general_req req = {}; unsigned int max_num_queues; @@ -194,7 +183,7 @@ static int mana_gd_query_max_resources(struct pci_dev *pdev) * MSI-X allocation; on non-dyn platforms msi_sharing is * unconditionally true (set in mana_gd_setup_hwc_irqs). */ - if (pci_msix_can_alloc_dyn(to_pci_dev(gc->dev))) + if (mana_gd_msix_can_alloc_dyn(gc)) gc->msi_sharing = false; mana_gd_init_req_hdr(&req.hdr, GDMA_QUERY_MAX_RESOURCES, @@ -207,7 +196,11 @@ static int mana_gd_query_max_resources(struct pci_dev *pdev) return err ? err : -EPROTO; } - if (!pci_msix_can_alloc_dyn(pdev)) { + if (!mana_gd_msix_can_alloc_dyn(gc)) { + /* Buses that size their vector pool at probe time cannot grow + * it afterwards, so never raise num_msix_usable above what has + * already been allocated. + */ if (gc->num_msix_usable > resp.max_msix) gc->num_msix_usable = resp.max_msix; } else { @@ -221,20 +214,24 @@ static int mana_gd_query_max_resources(struct pci_dev *pdev) /* MSI-X vectors are allocated by index into the device MSI-X table, so * never ask for more than the table holds. It can be smaller than both - * resp.max_msix and the CPU count. + * resp.max_msix and the CPU count. A bus that cannot report a table + * size installs no callback and skips the clamp. */ - err = pci_msix_vec_count(pdev); - if (err <= 0) { - dev_err(gc->dev, "Failed to query MSI-X table size: %d\n", err); - return err < 0 ? err : -ENOSPC; - } - msix_vec_count = err; + if (gc->bus_ops && gc->bus_ops->msix_vec_count) { + err = gc->bus_ops->msix_vec_count(gc); + if (err <= 0) { + dev_err(gc->dev, + "Failed to query MSI-X table size: %d\n", err); + return err < 0 ? err : -ENOSPC; + } + msix_vec_count = err; - if (gc->num_msix_usable > msix_vec_count) { - dev_info(gc->dev, - "Limiting MSI-X vectors from %u to table size %u\n", - gc->num_msix_usable, msix_vec_count); - gc->num_msix_usable = msix_vec_count; + if (gc->num_msix_usable > msix_vec_count) { + dev_info(gc->dev, + "Limiting MSI-X vectors from %u to table size %u\n", + gc->num_msix_usable, msix_vec_count); + gc->num_msix_usable = msix_vec_count; + } } if (gc->num_msix_usable <= 1) @@ -286,6 +283,8 @@ static int mana_gd_query_max_resources(struct pci_dev *pdev) if (num_ports > MAX_PORTS_IN_MANA_DEV) num_ports = MAX_PORTS_IN_MANA_DEV; + gc->num_ports = num_ports; + /* * Adjust the per-vPort max queue count to allow dedicated * MSIx for each vPort. Prefer at least MANA_DEF_NUM_QUEUES, @@ -317,9 +316,8 @@ static int mana_gd_query_max_resources(struct pci_dev *pdev) return 0; } -static int mana_gd_query_hwc_timeout(struct pci_dev *pdev, u32 *timeout_val) +static int mana_gd_query_hwc_timeout(struct gdma_context *gc, u32 *timeout_val) { - struct gdma_context *gc = pci_get_drvdata(pdev); struct gdma_query_hwc_timeout_resp resp = {}; struct gdma_query_hwc_timeout_req req = {}; int err; @@ -336,9 +334,8 @@ static int mana_gd_query_hwc_timeout(struct pci_dev *pdev, u32 *timeout_val) return 0; } -static int mana_gd_detect_devices(struct pci_dev *pdev) +int mana_gd_detect_devices(struct gdma_context *gc) { - struct gdma_context *gc = pci_get_drvdata(pdev); struct gdma_list_devices_resp resp = {}; struct gdma_general_req req = {}; struct gdma_dev_id dev; @@ -657,187 +654,31 @@ void mana_gd_ring_dim(struct gdma_queue *cq, u32 mod_usec, bool mod_usec_vld, } EXPORT_SYMBOL_NS(mana_gd_ring_dim, "NET_MANA"); -#define MANA_SERVICE_PERIOD 10 - -static void mana_serv_rescan(struct pci_dev *pdev) -{ - struct pci_bus *parent; - - pci_lock_rescan_remove(); - - parent = pdev->bus; - if (!parent) { - dev_err(&pdev->dev, "MANA service: no parent bus\n"); - goto out; - } - - pci_stop_and_remove_bus_device(pdev); - pci_rescan_bus(parent); - -out: - pci_unlock_rescan_remove(); -} - -static void mana_serv_fpga(struct pci_dev *pdev) -{ - struct pci_bus *bus, *parent; - - pci_lock_rescan_remove(); - - bus = pdev->bus; - if (!bus) { - dev_err(&pdev->dev, "MANA service: no bus\n"); - goto out; - } - - parent = bus->parent; - if (!parent) { - dev_err(&pdev->dev, "MANA service: no parent bus\n"); - goto out; - } - - pci_stop_and_remove_bus_device(bus->self); - - msleep(MANA_SERVICE_PERIOD * 1000); - - pci_rescan_bus(parent); - -out: - pci_unlock_rescan_remove(); -} - -static void mana_serv_reset(struct pci_dev *pdev) -{ - struct gdma_context *gc = pci_get_drvdata(pdev); - struct hw_channel_context *hwc; - int ret; - - if (!gc) { - /* Perform PCI rescan on device if GC is not set up */ - dev_err(&pdev->dev, "MANA service: GC not setup, rescanning\n"); - mana_serv_rescan(pdev); - return; - } - - hwc = gc->hwc.driver_data; - if (!hwc) { - dev_err(&pdev->dev, "MANA service: no HWC\n"); - goto out; - } - - /* HWC is not responding in this case, so don't wait */ - hwc->hwc_timeout = 0; - - dev_info(&pdev->dev, "MANA reset cycle start\n"); - - mana_gd_suspend(pdev, PMSG_SUSPEND); - - msleep(MANA_SERVICE_PERIOD * 1000); - - ret = mana_gd_resume(pdev); - if (ret == -ETIMEDOUT || ret == -EPROTO) { - /* Perform PCI rescan on device if we failed on HWC */ - dev_err(&pdev->dev, "MANA service: resume failed, rescanning\n"); - mana_serv_rescan(pdev); - return; - } - - if (ret) - dev_info(&pdev->dev, "MANA reset cycle failed err %d\n", ret); - else - dev_info(&pdev->dev, "MANA reset cycle completed\n"); - -out: - clear_bit(GC_IN_SERVICE, &gc->flags); -} - -static void mana_do_service(enum gdma_eqe_type type, struct pci_dev *pdev) -{ - switch (type) { - case GDMA_EQE_HWC_FPGA_RECONFIG: - mana_serv_fpga(pdev); - break; - - case GDMA_EQE_HWC_RESET_REQUEST: - mana_serv_reset(pdev); - break; - - default: - dev_err(&pdev->dev, "MANA service: unknown type %d\n", type); - break; - } -} - -static void mana_recovery_delayed_func(struct work_struct *w) -{ - struct mana_dev_recovery_work *work; - struct mana_dev_recovery *dev; - unsigned long flags; - - work = container_of(w, struct mana_dev_recovery_work, work.work); - - spin_lock_irqsave(&work->lock, flags); - - while (!list_empty(&work->dev_list)) { - dev = list_first_entry(&work->dev_list, - struct mana_dev_recovery, list); - list_del(&dev->list); - spin_unlock_irqrestore(&work->lock, flags); - - mana_do_service(dev->type, dev->pdev); - pci_dev_put(dev->pdev); - kfree(dev); - - spin_lock_irqsave(&work->lock, flags); - } - - spin_unlock_irqrestore(&work->lock, flags); -} - -static void mana_serv_func(struct work_struct *w) +/* + * Queue device servicing or recovery on buses that support it. + * + * Servicing tears the device down and brings it back up, so it depends on + * bus-level facilities the GDMA core does not have. Buses that provide no + * servicing path install no callback and the request is rejected. + */ +int mana_schedule_serv_work(struct gdma_context *gc, enum gdma_eqe_type type) { - struct mana_serv_work *mns_wk; - struct pci_dev *pdev; - - mns_wk = container_of(w, struct mana_serv_work, serv_work); - pdev = mns_wk->pdev; - - if (pdev) - mana_do_service(mns_wk->type, pdev); + if (!gc->bus_ops || !gc->bus_ops->schedule_serv_work) + return -EOPNOTSUPP; - pci_dev_put(pdev); - kfree(mns_wk); - module_put(THIS_MODULE); + return gc->bus_ops->schedule_serv_work(gc, type); } -int mana_schedule_serv_work(struct gdma_context *gc, enum gdma_eqe_type type) +/* The servicing workqueue is owned by the GDMA core because the queueing + * sites live here and in mana_en.c, which every transport shares. Each bus + * driver creates it during setup and destroys it during cleanup. + */ +int mana_gd_alloc_service_wq(struct gdma_context *gc) { - struct mana_serv_work *mns_wk; - - if (test_and_set_bit(GC_IN_SERVICE, &gc->flags)) { - dev_info(gc->dev, "Already in service\n"); - return -EBUSY; - } - - if (!try_module_get(THIS_MODULE)) { - dev_info(gc->dev, "Module is unloading\n"); - clear_bit(GC_IN_SERVICE, &gc->flags); - return -ENODEV; - } - - mns_wk = kzalloc_obj(*mns_wk, GFP_ATOMIC); - if (!mns_wk) { - module_put(THIS_MODULE); - clear_bit(GC_IN_SERVICE, &gc->flags); + gc->service_wq = alloc_ordered_workqueue("gdma_service_wq", 0); + if (!gc->service_wq) return -ENOMEM; - } - dev_info(gc->dev, "Start MANA service type:%d\n", type); - mns_wk->pdev = to_pci_dev(gc->dev); - mns_wk->type = type; - pci_dev_get(mns_wk->pdev); - INIT_WORK(&mns_wk->serv_work, mana_serv_func); - schedule_work(&mns_wk->serv_work); return 0; } @@ -904,6 +745,36 @@ ssize_t mana_gd_read_ring(struct gdma_queue *q, char __user *buf, return copied; } +void mana_gd_free_service_wq(struct gdma_context *gc) +{ + if (!gc->service_wq) + return; + + destroy_workqueue(gc->service_wq); + gc->service_wq = NULL; +} + +static void mana_gd_schedule_eq_cqs(struct gdma_queue *eq) +{ + struct gdma_context *gc = eq->gdma_dev->gdma_context; + struct gdma_queue *cq; + u8 i; + + for (i = 0; i < GDMA_EQ_MAX_CHILD_CQ; i++) { + cq = rcu_dereference(eq->eq.child_cq[i]); + + if (!cq) + continue; + + if (cq->id >= READ_ONCE(gc->max_num_cqs) || + !gc->cq_table || gc->cq_table[cq->id] != cq) + continue; + + if (cq->cq.callback) + cq->cq.callback(cq->cq.context, cq); + } +} + static void mana_gd_process_eqe(struct gdma_queue *eq) { u32 head = eq->head % (eq->queue_size / GDMA_EQE_SIZE); @@ -934,6 +805,14 @@ static void mana_gd_process_eqe(struct gdma_queue *eq) break; + case GDMA_EQE_THROTTLE: + u64_stats_update_begin(&eq->eq.stats.syncp); + u64_stats_inc(&eq->eq.stats.throttle_count); + u64_stats_update_end(&eq->eq.stats.syncp); + + mana_gd_schedule_eq_cqs(eq); + break; + case GDMA_EQE_TEST_EVENT: gc->test_event_eq_id = eq->id; complete(&gc->eq_test_event); @@ -975,7 +854,7 @@ static void mana_gd_process_eqe(struct gdma_queue *eq) } } -static void mana_gd_process_eq_events(void *arg) +void mana_gd_process_eq_events(void *arg) { u32 owner_bits, new_bits, old_bits; union gdma_eqe_info eqe_info; @@ -1179,6 +1058,8 @@ static int mana_gd_create_eq(struct gdma_dev *gd, queue->eq.msix_index = INVALID_PCI_MSIX_INDEX; queue->id = INVALID_QUEUE_ID; + u64_stats_init(&queue->eq.stats.syncp); + log2_num_entries = ilog2(queue->queue_size / GDMA_EQE_SIZE); if (spec->eq.log2_throttle_limit > log2_num_entries) { @@ -1220,28 +1101,69 @@ static void mana_gd_create_cq(const struct gdma_queue_spec *spec, struct gdma_queue *queue) { u32 log2_num_entries = ilog2(spec->queue_size / GDMA_CQE_SIZE); + struct gdma_queue *parent; + u8 i; queue->head |= INITIALIZED_OWNER_BIT(log2_num_entries); - queue->cq.parent = spec->cq.parent_eq; + parent = spec->cq.parent_eq; + queue->cq.parent = parent; queue->cq.context = spec->cq.context; queue->cq.callback = spec->cq.callback; + + if (!parent) + return; + + /* For throttled EQE store the child CQ */ + for (i = 0; i < GDMA_EQ_MAX_CHILD_CQ; i++) { + if (!rcu_access_pointer(parent->eq.child_cq[i])) { + rcu_assign_pointer(parent->eq.child_cq[i], queue); + return; + } + } + + WARN_ONCE(1, "mana: EQ %u has no free child CQ slot\n", parent->id); } -static void mana_gd_destroy_cq(struct gdma_context *gc, - struct gdma_queue *queue) +/* Unlink queue from its parent EQ's child_cq[] and from gc->cq_table[]. + * + * Return: true if queue was in the parent EQ's child_cq[]. In that case the + * caller must wait for an RCU grace period before freeing queue, because + * mana_gd_intr() may still be handling a throttle EQE for it. + */ +bool mana_gd_detach_cq(struct gdma_context *gc, struct gdma_queue *queue) { + struct gdma_queue *eq = queue->cq.parent; + bool attached = false; u32 id = queue->id; + u8 i; - if (id >= gc->max_num_cqs) - return; + if (eq) { + for (i = 0; i < GDMA_EQ_MAX_CHILD_CQ; i++) { + if (rcu_access_pointer(eq->eq.child_cq[i]) == queue) { + RCU_INIT_POINTER(eq->eq.child_cq[i], NULL); + attached = true; + } + } + } - if (!gc->cq_table[id]) - return; + /* Check if CQ might have been detached already, only clear if + * it still points to same queue . + */ + if (id < gc->max_num_cqs && READ_ONCE(gc->cq_table[id]) == queue) + WRITE_ONCE(gc->cq_table[id], NULL); - gc->cq_table[id] = NULL; + return attached; } -int mana_gd_create_hwc_queue(struct gdma_dev *gd, +static void mana_gd_destroy_cq(struct gdma_context *gc, + struct gdma_queue *queue) +{ + /* Wait for irq reader holding the cq */ + if (mana_gd_detach_cq(gc, queue)) + synchronize_net(); +} + +int mana_gd_create_hwc_queue(struct gdma_dev *gd, const struct gdma_queue_spec *spec, struct gdma_queue **queue_ptr) { @@ -1530,9 +1452,8 @@ void mana_gd_destroy_queue(struct gdma_context *gc, struct gdma_queue *queue) } EXPORT_SYMBOL_NS(mana_gd_destroy_queue, "NET_MANA"); -int mana_gd_verify_vf_version(struct pci_dev *pdev) +int mana_gd_verify_vf_version(struct gdma_context *gc) { - struct gdma_context *gc = pci_get_drvdata(pdev); struct gdma_verify_ver_resp resp = {}; struct gdma_verify_ver_req req = {}; struct hw_channel_context *hwc; @@ -1546,6 +1467,8 @@ int mana_gd_verify_vf_version(struct pci_dev *pdev) req.protocol_ver_max = GDMA_PROTOCOL_LAST; req.gd_drv_cap_flags1 = GDMA_DRV_CAP_FLAGS1; + if (gc->bus_ops) + req.gd_drv_cap_flags1 |= gc->bus_ops->drv_cap_flags1; req.gd_drv_cap_flags2 = GDMA_DRV_CAP_FLAGS2; req.gd_drv_cap_flags3 = GDMA_DRV_CAP_FLAGS3; req.gd_drv_cap_flags4 = GDMA_DRV_CAP_FLAGS4; @@ -1574,7 +1497,7 @@ int mana_gd_verify_vf_version(struct pci_dev *pdev) &gc->pf_cap_flags1); if (resp.pf_cap_flags1 & GDMA_DRV_CAP_FLAG_1_HWC_TIMEOUT_RECONFIG) { - err = mana_gd_query_hwc_timeout(pdev, &hwc->hwc_timeout); + err = mana_gd_query_hwc_timeout(gc, &hwc->hwc_timeout); if (err) { dev_err(gc->dev, "Failed to set the hwc timeout %d\n", err); return err; @@ -1873,7 +1796,7 @@ int mana_gd_poll_cq(struct gdma_queue *cq, struct gdma_comp *comp, int num_cqe) } EXPORT_SYMBOL_NS(mana_gd_poll_cq, "NET_MANA"); -static irqreturn_t mana_gd_intr(int irq, void *arg) +irqreturn_t mana_gd_intr(int irq, void *arg) { struct gdma_irq_context *gic = arg; struct list_head *eq_list = &gic->eq_list; @@ -1888,11 +1811,25 @@ static irqreturn_t mana_gd_intr(int irq, void *arg) return IRQ_HANDLED; } +/* + * Reset the device using whatever mechanism the bus provides. + */ +int mana_gd_dev_reset(struct gdma_context *gc) +{ + if (!gc->bus_ops || !gc->bus_ops->dev_reset) + return -EOPNOTSUPP; + + return gc->bus_ops->dev_reset(gc); +} + +/* + * Release a reference on the IRQ context backing an MSI vector, freeing + * the vector once the last user is gone. + */ void mana_gd_put_gic(struct gdma_context *gc, bool use_msi_bitmap, int msi) { - struct pci_dev *dev = to_pci_dev(gc->dev); + const struct gdma_bus_ops *ops = gc->bus_ops; struct gdma_irq_context *gic; - struct msi_map irq_map; int irq; mutex_lock(&gc->gic_mutex); @@ -1917,11 +1854,8 @@ void mana_gd_put_gic(struct gdma_context *gc, bool use_msi_bitmap, int msi) irq_update_affinity_hint(irq, NULL); free_irq(irq, gic); - if (gic->dyn_msix) { - irq_map.virq = irq; - irq_map.index = msi; - pci_msix_free_irq(dev, irq_map); - } + if (gic->dyn_msix) + ops->msix_free(gc, msi, irq); xa_erase(&gc->irq_contexts, msi); kfree(gic); @@ -1944,12 +1878,10 @@ struct gdma_irq_context *mana_gd_get_gic(struct gdma_context *gc, bool use_msi_bitmap, int *msi_requested) { - struct pci_dev *dev = to_pci_dev(gc->dev); + const struct gdma_bus_ops *ops = gc->bus_ops; struct gdma_irq_context *gic; - struct msi_map irq_map = { }; - int irq; - int msi; - int err; + bool dyn_msix = false; + int msi, irq, err; mutex_lock(&gc->gic_mutex); @@ -1975,27 +1907,34 @@ struct gdma_irq_context *mana_gd_get_gic(struct gdma_context *gc, goto out; } - irq = pci_irq_vector(dev, msi); + irq = ops->msix_virq(gc, msi); if (irq == -EINVAL) { - irq_map = pci_msix_alloc_irq_at(dev, msi, NULL); - if (!irq_map.virq) { - err = irq_map.index; - dev_err(gc->dev, - "Failed to alloc irq_map msi %d err %d\n", - msi, err); - gic = ERR_PTR(err); + /* A bus that sizes its vector pool up front has nothing left + * to hand out once every vector has been claimed. + */ + if (!ops->msix_alloc_at) { + dev_err(gc->dev, "No IRQ for MSI %d\n", msi); + gic = ERR_PTR(-ENOENT); + goto out; + } + + irq = ops->msix_alloc_at(gc, &msi); + if (irq < 0) { + dev_err(gc->dev, "Failed to alloc irq msi %d err %d\n", + *msi_requested, irq); + gic = ERR_PTR(irq); goto out; } - irq = irq_map.virq; - msi = irq_map.index; + + dyn_msix = true; *msi_requested = msi; } gic = kzalloc_obj(*gic); if (!gic) { gic = ERR_PTR(-ENOMEM); - if (irq_map.virq) - pci_msix_free_irq(dev, irq_map); + if (dyn_msix) + ops->msix_free(gc, msi, irq); goto out; } @@ -2006,11 +1945,11 @@ struct gdma_irq_context *mana_gd_get_gic(struct gdma_context *gc, spin_lock_init(&gic->lock); if (!gic->msi) - snprintf(gic->name, MANA_IRQ_NAME_SZ, "mana_hwc@pci:%s", - pci_name(dev)); + snprintf(gic->name, MANA_IRQ_NAME_SZ, "mana_hwc@%s:%s", + ops->bus_name, dev_name(gc->dev)); else - snprintf(gic->name, MANA_IRQ_NAME_SZ, "mana_msi%d@pci:%s", - gic->msi, pci_name(dev)); + snprintf(gic->name, MANA_IRQ_NAME_SZ, "mana_msi%d@%s:%s", + gic->msi, ops->bus_name, dev_name(gc->dev)); err = request_irq(irq, mana_gd_intr, 0, gic->name, gic); if (err) { @@ -2018,12 +1957,12 @@ struct gdma_irq_context *mana_gd_get_gic(struct gdma_context *gc, irq, gic->name); kfree(gic); gic = ERR_PTR(err); - if (irq_map.virq) - pci_msix_free_irq(dev, irq_map); + if (dyn_msix) + ops->msix_free(gc, msi, irq); goto out; } - gic->dyn_msix = !!irq_map.virq; + gic->dyn_msix = dyn_msix; refcount_set(&gic->refcount, 1); gic->bitmap_refs = use_msi_bitmap ? 1 : 0; @@ -2034,8 +1973,8 @@ struct gdma_irq_context *mana_gd_get_gic(struct gdma_context *gc, free_irq(irq, gic); kfree(gic); gic = ERR_PTR(err); - if (irq_map.virq) - pci_msix_free_irq(dev, irq_map); + if (dyn_msix) + ops->msix_free(gc, msi, irq); goto out; } @@ -2067,6 +2006,326 @@ void mana_gd_free_res_map(struct gdma_resource *r) r->size = 0; } +/* Bring up the GDMA context on a probed device: create the debugfs directory, + * map the shared-memory registers, start the hardware channel and size the + * interrupt pool. Every step here is common to all buses; the ones that are + * not are reached through gdma_bus_ops. + */ +int mana_gd_setup(struct gdma_context *gc) +{ + int err; + + gc->mana_pci_debugfs = debugfs_create_dir(dev_name(gc->dev), + mana_debugfs_root); + + err = mana_gd_init_registers(gc); + if (err) + goto remove_debugfs; + + mana_smc_init(&gc->shm_channel, gc->dev, gc->shm_base); + + err = mana_gd_alloc_service_wq(gc); + if (err) + goto remove_debugfs; + + err = gc->bus_ops->setup_hwc_irqs(gc); + if (err) { + dev_err(gc->dev, "Failed to setup IRQs for HWC creation: %d\n", + err); + goto free_workqueue; + } + + err = mana_hwc_create_channel(gc); + if (err) + goto remove_irq; + + err = mana_gd_verify_vf_version(gc); + if (err) + goto destroy_hwc; + + err = mana_gd_detect_devices(gc); + if (err) + goto destroy_hwc; + + err = mana_gd_query_max_resources(gc); + if (err) + goto destroy_hwc; + + err = gc->bus_ops->setup_remaining_irqs(gc); + if (err) + goto destroy_hwc; + + dev_dbg(gc->dev, "mana gdma setup successful\n"); + return 0; + +destroy_hwc: + mana_hwc_destroy_channel(gc); +remove_irq: + gc->bus_ops->remove_irqs(gc); +free_workqueue: + mana_gd_free_service_wq(gc); +remove_debugfs: + debugfs_remove_recursive(gc->mana_pci_debugfs); + gc->mana_pci_debugfs = NULL; + dev_err(gc->dev, "%s failed (error %d)\n", __func__, err); + return err; +} + +void mana_gd_cleanup(struct gdma_context *gc) +{ + mana_hwc_destroy_channel(gc); + + gc->bus_ops->remove_irqs(gc); + + mana_gd_free_service_wq(gc); + + debugfs_remove_recursive(gc->mana_pci_debugfs); + gc->mana_pci_debugfs = NULL; + + dev_dbg(gc->dev, "mana gdma cleanup successful\n"); +} + +struct mana_dev_recovery { + struct list_head list; + struct pci_dev *pdev; + enum gdma_eqe_type type; +}; + +static struct mana_dev_recovery_work { + struct list_head dev_list; + struct delayed_work work; + + /* Lock for dev_list above */ + spinlock_t lock; +} mana_dev_recovery_work; + +static int mana_gd_suspend(struct pci_dev *pdev, pm_message_t state); +static int mana_gd_resume(struct pci_dev *pdev); + +#define MANA_SERVICE_PERIOD 10 + +static void mana_serv_rescan(struct pci_dev *pdev) +{ + struct pci_bus *parent; + + pci_lock_rescan_remove(); + + parent = pdev->bus; + if (!parent) { + dev_err(&pdev->dev, "MANA service: no parent bus\n"); + goto out; + } + + pci_stop_and_remove_bus_device(pdev); + pci_rescan_bus(parent); + +out: + pci_unlock_rescan_remove(); +} + +static void mana_serv_fpga(struct pci_dev *pdev) +{ + struct pci_bus *bus, *parent; + + pci_lock_rescan_remove(); + + bus = pdev->bus; + if (!bus) { + dev_err(&pdev->dev, "MANA service: no bus\n"); + goto out; + } + + parent = bus->parent; + if (!parent) { + dev_err(&pdev->dev, "MANA service: no parent bus\n"); + goto out; + } + + pci_stop_and_remove_bus_device(bus->self); + + msleep(MANA_SERVICE_PERIOD * 1000); + + pci_rescan_bus(parent); + +out: + pci_unlock_rescan_remove(); +} + +static void mana_serv_reset(struct pci_dev *pdev) +{ + struct gdma_context *gc = pci_get_drvdata(pdev); + struct hw_channel_context *hwc; + int ret; + + if (!gc) { + /* Perform PCI rescan on device if GC is not set up */ + dev_err(&pdev->dev, "MANA service: GC not setup, rescanning\n"); + mana_serv_rescan(pdev); + return; + } + + hwc = gc->hwc.driver_data; + if (!hwc) { + dev_err(&pdev->dev, "MANA service: no HWC\n"); + goto out; + } + + /* HWC is not responding in this case, so don't wait */ + hwc->hwc_timeout = 0; + + dev_info(&pdev->dev, "MANA reset cycle start\n"); + + mana_gd_suspend(pdev, PMSG_SUSPEND); + + msleep(MANA_SERVICE_PERIOD * 1000); + + ret = mana_gd_resume(pdev); + if (ret == -ETIMEDOUT || ret == -EPROTO) { + /* Perform PCI rescan on device if we failed on HWC */ + dev_err(&pdev->dev, "MANA service: resume failed, rescanning\n"); + mana_serv_rescan(pdev); + return; + } + + if (ret) + dev_info(&pdev->dev, "MANA reset cycle failed err %d\n", ret); + else + dev_info(&pdev->dev, "MANA reset cycle completed\n"); + +out: + clear_bit(GC_IN_SERVICE, &gc->flags); +} + +static void mana_do_service(enum gdma_eqe_type type, struct pci_dev *pdev) +{ + switch (type) { + case GDMA_EQE_HWC_FPGA_RECONFIG: + mana_serv_fpga(pdev); + break; + + case GDMA_EQE_HWC_RESET_REQUEST: + mana_serv_reset(pdev); + break; + + default: + dev_err(&pdev->dev, "MANA service: unknown type %d\n", type); + break; + } +} + +static void mana_recovery_delayed_func(struct work_struct *w) +{ + struct mana_dev_recovery_work *work; + struct mana_dev_recovery *dev; + unsigned long flags; + + work = container_of(w, struct mana_dev_recovery_work, work.work); + + spin_lock_irqsave(&work->lock, flags); + + while (!list_empty(&work->dev_list)) { + dev = list_first_entry(&work->dev_list, + struct mana_dev_recovery, list); + list_del(&dev->list); + spin_unlock_irqrestore(&work->lock, flags); + + mana_do_service(dev->type, dev->pdev); + pci_dev_put(dev->pdev); + kfree(dev); + + spin_lock_irqsave(&work->lock, flags); + } + + spin_unlock_irqrestore(&work->lock, flags); +} + +static void mana_serv_func(struct work_struct *w) +{ + struct mana_serv_work *mns_wk; + struct pci_dev *pdev; + + mns_wk = container_of(w, struct mana_serv_work, serv_work); + pdev = mns_wk->pdev; + + if (pdev) + mana_do_service(mns_wk->type, pdev); + + pci_dev_put(pdev); + kfree(mns_wk); + module_put(THIS_MODULE); +} + +static int mana_pci_schedule_serv_work(struct gdma_context *gc, + enum gdma_eqe_type type) +{ + struct mana_serv_work *mns_wk; + + if (test_and_set_bit(GC_IN_SERVICE, &gc->flags)) { + dev_info(gc->dev, "Already in service\n"); + return -EBUSY; + } + + if (!try_module_get(THIS_MODULE)) { + dev_info(gc->dev, "Module is unloading\n"); + clear_bit(GC_IN_SERVICE, &gc->flags); + return -ENODEV; + } + + mns_wk = kzalloc(sizeof(*mns_wk), GFP_ATOMIC); + if (!mns_wk) { + module_put(THIS_MODULE); + clear_bit(GC_IN_SERVICE, &gc->flags); + return -ENOMEM; + } + + dev_info(gc->dev, "Start MANA service type:%d\n", type); + mns_wk->pdev = to_pci_dev(gc->dev); + mns_wk->type = type; + pci_dev_get(mns_wk->pdev); + INIT_WORK(&mns_wk->serv_work, mana_serv_func); + schedule_work(&mns_wk->serv_work); + return 0; +} + +static bool mana_pci_msix_can_alloc_dyn(struct gdma_context *gc) +{ + return pci_msix_can_alloc_dyn(to_pci_dev(gc->dev)); +} + +static int mana_pci_msix_virq(struct gdma_context *gc, int msi) +{ + return pci_irq_vector(to_pci_dev(gc->dev), msi); +} + +static int mana_pci_msix_alloc_at(struct gdma_context *gc, int *msi) +{ + struct msi_map irq_map; + + irq_map = pci_msix_alloc_irq_at(to_pci_dev(gc->dev), *msi, NULL); + if (!irq_map.virq) + return irq_map.index; + + *msi = irq_map.index; + return irq_map.virq; +} + +static void mana_pci_msix_free(struct gdma_context *gc, int msi, int irq) +{ + struct msi_map irq_map = { .virq = irq, .index = msi }; + + pci_msix_free_irq(to_pci_dev(gc->dev), irq_map); +} + +static int mana_pci_msix_vec_count(struct gdma_context *gc) +{ + return pci_msix_vec_count(to_pci_dev(gc->dev)); +} + +static int mana_pci_dev_reset(struct gdma_context *gc) +{ + return pcie_flr(to_pci_dev(gc->dev)); +} + /* * Spread on CPUs with the following heuristics: * @@ -2396,101 +2655,52 @@ static void mana_gd_remove_irqs(struct pci_dev *pdev) gc->num_msix_usable = 0; } -static int mana_gd_setup(struct pci_dev *pdev) +static int mana_pci_setup_hwc_irqs(struct gdma_context *gc) { - struct gdma_context *gc = pci_get_drvdata(pdev); - int err; - - gc->mana_pci_debugfs = debugfs_create_dir(pci_name(pdev), - mana_debugfs_root); - - err = mana_gd_init_registers(pdev); - if (err) - goto remove_debugfs; - - mana_smc_init(&gc->shm_channel, gc->dev, gc->shm_base); - - gc->service_wq = alloc_ordered_workqueue("gdma_service_wq", 0); - if (!gc->service_wq) { - err = -ENOMEM; - goto remove_debugfs; - } - - err = mana_gd_setup_hwc_irqs(pdev); - if (err) { - dev_err(gc->dev, "Failed to setup IRQs for HWC creation: %d\n", - err); - goto free_workqueue; - } - - err = mana_hwc_create_channel(gc); - if (err) - goto remove_irq; - - err = mana_gd_verify_vf_version(pdev); - if (err) - goto destroy_hwc; - - err = mana_gd_detect_devices(pdev); - if (err) - goto destroy_hwc; + return mana_gd_setup_hwc_irqs(to_pci_dev(gc->dev)); +} - err = mana_gd_query_max_resources(pdev); - if (err) - goto destroy_hwc; +static int mana_pci_setup_remaining_irqs(struct gdma_context *gc) +{ + int err; - err = mana_gd_setup_remaining_irqs(pdev); + err = mana_gd_setup_remaining_irqs(to_pci_dev(gc->dev)); if (err) { dev_err(gc->dev, "Failed to setup remaining IRQs: %d", err); - goto destroy_hwc; + return err; } if (!gc->msi_sharing) { gc->msi_bitmap = bitmap_zalloc(gc->num_msix_usable, GFP_KERNEL); - if (!gc->msi_bitmap) { - err = -ENOMEM; - goto destroy_hwc; - } + if (!gc->msi_bitmap) + return -ENOMEM; /* Set bit for HWC */ set_bit(0, gc->msi_bitmap); } - dev_dbg(&pdev->dev, "mana gdma setup successful\n"); return 0; - -destroy_hwc: - mana_hwc_destroy_channel(gc); -remove_irq: - mana_gd_remove_irqs(pdev); -free_workqueue: - destroy_workqueue(gc->service_wq); - gc->service_wq = NULL; -remove_debugfs: - debugfs_remove_recursive(gc->mana_pci_debugfs); - gc->mana_pci_debugfs = NULL; - dev_err(&pdev->dev, "%s failed (error %d)\n", __func__, err); - return err; } -static void mana_gd_cleanup_device(struct pci_dev *pdev) +static void mana_pci_remove_irqs(struct gdma_context *gc) { - struct gdma_context *gc = pci_get_drvdata(pdev); - - mana_hwc_destroy_channel(gc); - - mana_gd_remove_irqs(pdev); - - if (gc->service_wq) { - destroy_workqueue(gc->service_wq); - gc->service_wq = NULL; - } - - debugfs_remove_recursive(gc->mana_pci_debugfs); - gc->mana_pci_debugfs = NULL; - - dev_dbg(&pdev->dev, "mana gdma cleanup successful\n"); + mana_gd_remove_irqs(to_pci_dev(gc->dev)); } +static const struct gdma_bus_ops mana_pci_bus_ops = { + .bus_name = "pci", + .msix_can_alloc_dyn = mana_pci_msix_can_alloc_dyn, + .msix_virq = mana_pci_msix_virq, + .msix_alloc_at = mana_pci_msix_alloc_at, + .msix_free = mana_pci_msix_free, + .msix_vec_count = mana_pci_msix_vec_count, + .setup_hwc_irqs = mana_pci_setup_hwc_irqs, + .setup_remaining_irqs = mana_pci_setup_remaining_irqs, + .remove_irqs = mana_pci_remove_irqs, + .dev_reset = mana_pci_dev_reset, + .schedule_serv_work = mana_pci_schedule_serv_work, + .drv_cap_flags1 = GDMA_DRV_CAP_FLAGS1_PCI, +}; + static bool mana_is_pf(unsigned short dev_id) { return dev_id == MANA_PF_DEVICE_ID || dev_id == MANA_PF2_DEVICE_ID; @@ -2546,9 +2756,10 @@ static int mana_gd_probe(struct pci_dev *pdev, const struct pci_device_id *ent) gc->bar0_va = bar0_va; gc->dev = &pdev->dev; + gc->bus_ops = &mana_pci_bus_ops; xa_init(&gc->irq_contexts); - err = mana_gd_setup(pdev); + err = mana_gd_setup(gc); if (err) goto unmap_bar; @@ -2576,7 +2787,7 @@ static int mana_gd_probe(struct pci_dev *pdev, const struct pci_device_id *ent) cleanup_mana: mana_remove(&gc->mana, false); cleanup_gd: - mana_gd_cleanup_device(pdev); + mana_gd_cleanup(gc); unmap_bar: xa_destroy(&gc->irq_contexts); pci_iounmap(pdev, bar0_va); @@ -2629,7 +2840,7 @@ static void mana_gd_remove(struct pci_dev *pdev) mana_rdma_remove(&gc->mana_ib); mana_remove(&gc->mana, false); - mana_gd_cleanup_device(pdev); + mana_gd_cleanup(gc); xa_destroy(&gc->irq_contexts); @@ -2644,24 +2855,24 @@ static void mana_gd_remove(struct pci_dev *pdev) } /* The 'state' parameter is not used. */ -int mana_gd_suspend(struct pci_dev *pdev, pm_message_t state) +static int mana_gd_suspend(struct pci_dev *pdev, pm_message_t state) { struct gdma_context *gc = pci_get_drvdata(pdev); mana_rdma_remove(&gc->mana_ib); mana_remove(&gc->mana, true); - mana_gd_cleanup_device(pdev); + mana_gd_cleanup(gc); return 0; } -int mana_gd_resume(struct pci_dev *pdev) +static int mana_gd_resume(struct pci_dev *pdev) { struct gdma_context *gc = pci_get_drvdata(pdev); int err; - err = mana_gd_setup(pdev); + err = mana_gd_setup(gc); if (err) return err; @@ -2676,7 +2887,7 @@ int mana_gd_resume(struct pci_dev *pdev) return err; cleanup_gd: - mana_gd_cleanup_device(pdev); + mana_gd_cleanup(gc); return err; } @@ -2690,7 +2901,7 @@ static void mana_gd_shutdown(struct pci_dev *pdev) mana_rdma_remove(&gc->mana_ib); mana_remove(&gc->mana, true); - mana_gd_cleanup_device(pdev); + mana_gd_cleanup(gc); pci_disable_device(pdev); } @@ -2734,26 +2945,19 @@ static struct pci_driver mana_driver = { .sriov_configure = mana_sriov_configure, }; -static int __init mana_driver_init(void) -{ - int err; +MODULE_DEVICE_TABLE(pci, mana_id_table); +static int mana_pci_driver_register(void) +{ INIT_LIST_HEAD(&mana_dev_recovery_work.dev_list); spin_lock_init(&mana_dev_recovery_work.lock); - INIT_DELAYED_WORK(&mana_dev_recovery_work.work, mana_recovery_delayed_func); - - mana_debugfs_root = debugfs_create_dir("mana", NULL); + INIT_DELAYED_WORK(&mana_dev_recovery_work.work, + mana_recovery_delayed_func); - err = pci_register_driver(&mana_driver); - if (err) { - debugfs_remove(mana_debugfs_root); - mana_debugfs_root = NULL; - } - - return err; + return pci_register_driver(&mana_driver); } -static void __exit mana_driver_exit(void) +static void mana_pci_driver_unregister(void) { struct mana_dev_recovery *dev; unsigned long flags; @@ -2771,6 +2975,29 @@ static void __exit mana_driver_exit(void) spin_unlock_irqrestore(&mana_dev_recovery_work.lock, flags); pci_unregister_driver(&mana_driver); +} + +static int __init mana_driver_init(void) +{ + int err; + + mana_debugfs_root = debugfs_create_dir("mana", NULL); + + err = mana_pci_driver_register(); + if (err) + goto err_debugfs; + + return 0; + +err_debugfs: + debugfs_remove(mana_debugfs_root); + mana_debugfs_root = NULL; + return err; +} + +static void __exit mana_driver_exit(void) +{ + mana_pci_driver_unregister(); debugfs_remove(mana_debugfs_root); @@ -2780,7 +3007,5 @@ static void __exit mana_driver_exit(void) module_init(mana_driver_init); module_exit(mana_driver_exit); -MODULE_DEVICE_TABLE(pci, mana_id_table); - MODULE_LICENSE("Dual BSD/GPL"); MODULE_DESCRIPTION("Microsoft Azure Network Adapter driver"); diff --git a/drivers/net/ethernet/microsoft/mana/hw_channel.c b/drivers/net/ethernet/microsoft/mana/hw_channel.c index 263e7c4e2934..2f7f32f55785 100644 --- a/drivers/net/ethernet/microsoft/mana/hw_channel.c +++ b/drivers/net/ethernet/microsoft/mana/hw_channel.c @@ -364,7 +364,7 @@ static void mana_hwc_comp_event(void *ctx, struct gdma_queue *q_self) completions = hwc_cq->comp_buf; comp_read = mana_gd_poll_cq(q_self, completions, hwc_cq->queue_depth); - WARN_ON_ONCE(comp_read <= 0 || comp_read > hwc_cq->queue_depth); + WARN_ON_ONCE(comp_read < 0 || comp_read > hwc_cq->queue_depth); for (i = 0; i < comp_read; ++i) { comp_data = *(struct hwc_rx_oob *)completions[i].cqe_data; @@ -820,9 +820,14 @@ void mana_hwc_destroy_channel(struct gdma_context *gc) */ if (gc->max_num_cqs > 0) { mana_smc_teardown_hwc(&gc->shm_channel, false); - gc->max_num_cqs = 0; + WRITE_ONCE(gc->max_num_cqs, 0); } + if (hwc->cq) + mana_gd_detach_cq(gc, hwc->cq->gdma_cq); + + synchronize_rcu(); + if (hwc->txq) mana_hwc_destroy_wq(hwc, hwc->txq); diff --git a/drivers/net/ethernet/microsoft/mana/mana_en.c b/drivers/net/ethernet/microsoft/mana/mana_en.c index a1fb06b23947..89af8bf6758b 100644 --- a/drivers/net/ethernet/microsoft/mana/mana_en.c +++ b/drivers/net/ethernet/microsoft/mana/mana_en.c @@ -9,7 +9,6 @@ #include #include #include -#include #include #include @@ -20,6 +19,7 @@ #include #include + #include #include @@ -2672,6 +2672,7 @@ static void mana_deinit_txq(struct mana_port_context *apc, struct mana_txq *txq) static void mana_destroy_txq(struct mana_port_context *apc) { + struct gdma_context *gc = apc->ac->gdma_dev->gdma_context; struct napi_struct *napi; int i; @@ -2690,13 +2691,23 @@ static void mana_destroy_txq(struct mana_port_context *apc) napi_synchronize(napi); napi_disable_locked(napi); cancel_work_sync(&apc->tx_qp[i]->tx_cq.dim.work); - netif_napi_del_locked(napi); - apc->tx_qp[i]->txq.napi_initialized = false; } if (apc->tx_qp[i]->tx_object != INVALID_MANA_HANDLE) mana_destroy_wq_obj(apc, GDMA_SQ, apc->tx_qp[i]->tx_object); + if (apc->tx_qp[i]->txq.napi_initialized) { + /* Detach the CQ only after the WQ object is destroyed, + * so a completion EQE that arrives before then still + * finds the CQ in cq_table[] rather than hitting the + * WARN in mana_gd_process_eqe(). One grace period then + * covers both mana_gd_intr() and NAPI users. + */ + mana_gd_detach_cq(gc, apc->tx_qp[i]->tx_cq.gdma_cq); + netif_napi_del_locked(napi); + apc->tx_qp[i]->txq.napi_initialized = false; + } + mana_deinit_cq(apc, &apc->tx_qp[i]->tx_cq); mana_deinit_txq(apc, &apc->tx_qp[i]->txq); @@ -2903,7 +2914,6 @@ static void mana_destroy_rxq(struct mana_port_context *apc, napi_disable_locked(napi); cancel_work_sync(&rxq->rx_cq.dim.work); - netif_napi_del_locked(napi); } if (xdp_rxq_info_is_reg(&rxq->xdp_rxq)) @@ -2912,6 +2922,12 @@ static void mana_destroy_rxq(struct mana_port_context *apc, if (rxq->rxobj != INVALID_MANA_HANDLE) mana_destroy_wq_obj(apc, GDMA_RQ, rxq->rxobj); + if (napi_initialized) { + /* See the comment in mana_destroy_txq() */ + mana_gd_detach_cq(gc, rxq->rx_cq.gdma_cq); + netif_napi_del_locked(napi); + } + mana_deinit_cq(apc, &rxq->rx_cq); if (rxq->xdp_save_va) @@ -3754,10 +3770,9 @@ static int mana_dealloc_queues(struct net_device *ndev) tsleep <<= 1; } if (atomic_read(&txq->pending_sends)) { - err = - pcie_flr(to_pci_dev(gd->gdma_context->dev)); + err = mana_gd_dev_reset(gd->gdma_context); if (err) { - netdev_err(ndev, "flr failed %d with %d pkts pending in txq %u\n", + netdev_err(ndev, "device reset failed %d with %d pkts pending in txq %u\n", err, atomic_read(&txq->pending_sends), txq->gdma_txq_id); @@ -4060,6 +4075,9 @@ int mana_rdma_service_event(struct gdma_context *gc, enum gdma_service_type even return 0; } + if (!gc->service_wq) + return -EOPNOTSUPP; + serv_work = kzalloc_obj(*serv_work, GFP_ATOMIC); if (!serv_work) return -ENOMEM; diff --git a/drivers/net/ethernet/microsoft/mana/mana_ethtool.c b/drivers/net/ethernet/microsoft/mana/mana_ethtool.c index 33db79569d3b..a91eb12badca 100644 --- a/drivers/net/ethernet/microsoft/mana/mana_ethtool.c +++ b/drivers/net/ethernet/microsoft/mana/mana_ethtool.c @@ -147,7 +147,8 @@ static int mana_get_sset_count(struct net_device *ndev, int stringset) return ARRAY_SIZE(mana_eth_stats) + ARRAY_SIZE(mana_phy_stats) + ARRAY_SIZE(mana_hc_stats) + - num_queues * (MANA_STATS_RX_COUNT + MANA_STATS_TX_COUNT); + num_queues * (MANA_STATS_RX_COUNT + MANA_STATS_TX_COUNT + + MANA_STATS_EQ_COUNT); case ETH_SS_PRIV_FLAGS: return MANA_PRIV_FLAG_MAX; @@ -198,6 +199,9 @@ static void mana_get_strings_stats(struct mana_port_context *apc, u8 **data) ethtool_sprintf(data, "tx_%d_csum_partial", i); ethtool_sprintf(data, "tx_%d_mana_map_err", i); } + + for (i = 0; i < num_queues; i++) + ethtool_sprintf(data, "eq_%d_throttle_events", i); } static void mana_get_strings_priv_flags(u8 **data) @@ -234,6 +238,7 @@ static void mana_get_ethtool_stats(struct net_device *ndev, void *phy_stats = &apc->phy_stats; struct mana_stats_rx *rx_stats; struct mana_stats_tx *tx_stats; + struct gdma_eq_stats *eq_stats; unsigned int start; u64 packets, bytes; u64 xdp_redirect; @@ -251,6 +256,7 @@ static void mana_get_ethtool_stats(struct net_device *ndev, u64 csum_partial; u64 mana_map_err; int q, i = 0, j; + u64 throttled; if (!apc->port_is_up) return; @@ -325,6 +331,17 @@ static void mana_get_ethtool_stats(struct net_device *ndev, data[i++] = csum_partial; data[i++] = mana_map_err; } + + for (q = 0; q < num_queues; q++) { + eq_stats = &apc->eqs[q].eq->eq.stats; + + do { + start = u64_stats_fetch_begin(&eq_stats->syncp); + throttled = u64_stats_read(&eq_stats->throttle_count); + } while (u64_stats_fetch_retry(&eq_stats->syncp, start)); + + data[i++] = throttled; + } } static u32 mana_get_rx_ring_count(struct net_device *ndev) diff --git a/drivers/net/ethernet/netronome/nfp/bpf/verifier.c b/drivers/net/ethernet/netronome/nfp/bpf/verifier.c index 1caa87da72b5..9ddbfe9d6019 100644 --- a/drivers/net/ethernet/netronome/nfp/bpf/verifier.c +++ b/drivers/net/ethernet/netronome/nfp/bpf/verifier.c @@ -105,7 +105,7 @@ static bool nfp_bpf_map_update_value_ok(struct bpf_verifier_env *env) unsigned int soff; soff = -(off + i) - 1; - stack_entry = &state->stack[soff / BPF_REG_SIZE]; + stack_entry = bpf_stack_slot(state, soff / BPF_REG_SIZE); if (stack_entry->slot_type[soff % BPF_REG_SIZE] == STACK_ZERO) continue; diff --git a/drivers/net/ethernet/netronome/nfp/flower/main.h b/drivers/net/ethernet/netronome/nfp/flower/main.h index 2b7c947ff4f2..bd4399758ed4 100644 --- a/drivers/net/ethernet/netronome/nfp/flower/main.h +++ b/drivers/net/ethernet/netronome/nfp/flower/main.h @@ -94,6 +94,7 @@ struct nfp_fl_stats_id { * @ipv6_off_lock: Lock for the IPv6 address list * @mac_off_ids: IDA to manage id assignment for offloaded MACs * @neigh_nb: Notifier to monitor neighbour state + * @neigh_wq: Workqueue for neighbour updates */ struct nfp_fl_tunnel_offloads { struct rhashtable offloaded_macs; @@ -103,6 +104,7 @@ struct nfp_fl_tunnel_offloads { struct mutex ipv6_off_lock; struct ida mac_off_ids; struct notifier_block neigh_nb; + struct workqueue_struct *neigh_wq; }; /** diff --git a/drivers/net/ethernet/netronome/nfp/flower/tunnel_conf.c b/drivers/net/ethernet/netronome/nfp/flower/tunnel_conf.c index ca30702f8878..8f5b0d3eb377 100644 --- a/drivers/net/ethernet/netronome/nfp/flower/tunnel_conf.c +++ b/drivers/net/ethernet/netronome/nfp/flower/tunnel_conf.c @@ -742,7 +742,7 @@ nfp_tun_neigh_event_handler(struct notifier_block *nb, unsigned long event, if (!update_work) return NOTIFY_DONE; - queue_work(system_highpri_wq, &update_work->work); + queue_work(app_priv->tun.neigh_wq, &update_work->work); return NOTIFY_DONE; } @@ -1515,6 +1515,13 @@ int nfp_tunnel_config_start(struct nfp_app *app) if (err) return err; + priv->tun.neigh_wq = alloc_workqueue("nfp-flower-neigh", + WQ_HIGHPRI | WQ_PERCPU, 0); + if (!priv->tun.neigh_wq) { + err = -ENOMEM; + goto err_free_macs; + } + ida_init(&priv->tun.mac_off_ids); /* Initialise priv data for IPv4/v6 offloading. */ @@ -1527,13 +1534,17 @@ int nfp_tunnel_config_start(struct nfp_app *app) priv->tun.neigh_nb.notifier_call = nfp_tun_neigh_event_handler; err = register_netevent_notifier(&priv->tun.neigh_nb); - if (err) { - rhashtable_free_and_destroy(&priv->tun.offloaded_macs, - nfp_check_rhashtable_empty, NULL); - return err; - } + if (err) + goto err_destroy_neigh_wq; return 0; + +err_destroy_neigh_wq: + destroy_workqueue(priv->tun.neigh_wq); +err_free_macs: + rhashtable_free_and_destroy(&priv->tun.offloaded_macs, + nfp_check_rhashtable_empty, NULL); + return err; } void nfp_tunnel_config_stop(struct nfp_app *app) @@ -1543,6 +1554,7 @@ void nfp_tunnel_config_stop(struct nfp_app *app) struct list_head *ptr, *storage; unregister_netevent_notifier(&priv->tun.neigh_nb); + destroy_workqueue(priv->tun.neigh_wq); ida_destroy(&priv->tun.mac_off_ids); diff --git a/drivers/net/ethernet/pensando/ionic/ionic_bus_pci.c b/drivers/net/ethernet/pensando/ionic/ionic_bus_pci.c index 05f19489ec5c..68b3bceedd99 100644 --- a/drivers/net/ethernet/pensando/ionic/ionic_bus_pci.c +++ b/drivers/net/ethernet/pensando/ionic/ionic_bus_pci.c @@ -397,6 +397,7 @@ static int ionic_probe(struct pci_dev *pdev, const struct pci_device_id *ent) err_out_free_irqs: ionic_bus_free_irq_vectors(ionic); err_out_pci: + ionic_port_reset(ionic); ionic_dev_teardown(ionic); ionic_clear_pci(ionic); ionic_debugfs_del_dev(ionic); diff --git a/drivers/net/ethernet/pensando/ionic/ionic_main.c b/drivers/net/ethernet/pensando/ionic/ionic_main.c index 10501be9ef95..38b47b959a11 100644 --- a/drivers/net/ethernet/pensando/ionic/ionic_main.c +++ b/drivers/net/ethernet/pensando/ionic/ionic_main.c @@ -722,6 +722,7 @@ int ionic_port_init(struct ionic *ionic) { struct ionic_identity *ident = &ionic->ident; struct ionic_dev *idev = &ionic->idev; + bool allocated = false; size_t sz; int err; @@ -733,6 +734,8 @@ int ionic_port_init(struct ionic *ionic) GFP_KERNEL); if (!idev->port_info) return -ENOMEM; + + allocated = true; } /* If the driver knows about more "extra stats" than the firmware, @@ -757,10 +760,12 @@ int ionic_port_init(struct ionic *ionic) mutex_unlock(&ionic->dev_cmd_lock); if (err) { dev_err(ionic->dev, "Failed to init port\n"); - dma_free_coherent(ionic->dev, idev->port_info_sz, - idev->port_info, idev->port_info_pa); - idev->port_info = NULL; - idev->port_info_pa = 0; + if (allocated) { + dma_free_coherent(ionic->dev, idev->port_info_sz, + idev->port_info, idev->port_info_pa); + idev->port_info = NULL; + idev->port_info_pa = 0; + } } return err; diff --git a/drivers/net/ethernet/qlogic/qede/qede_filter.c b/drivers/net/ethernet/qlogic/qede/qede_filter.c index ab8b818588e2..5bf32f1034e0 100644 --- a/drivers/net/ethernet/qlogic/qede/qede_filter.c +++ b/drivers/net/ethernet/qlogic/qede/qede_filter.c @@ -1991,8 +1991,8 @@ static int qede_flow_spec_to_rule(struct qede_dev *edev, struct ethtool_rx_flow_spec *fs) { struct ethtool_rx_flow_spec_input input = {}; + struct netlink_ext_ack extack = {}; struct ethtool_rx_flow_rule *flow; - struct netlink_ext_ack extack; __be16 proto; int err; diff --git a/drivers/net/ethernet/sfc/Kconfig b/drivers/net/ethernet/sfc/Kconfig index 979f2801e2a8..e2898ec2e6e9 100644 --- a/drivers/net/ethernet/sfc/Kconfig +++ b/drivers/net/ethernet/sfc/Kconfig @@ -68,7 +68,7 @@ config SFC_MCDI_LOGGING a sysfs file 'mcdi_logging' under the PCI device. config SFC_CXL bool "Solarflare SFC9100-family CXL support" - depends on SFC && CXL_BUS >= SFC + depends on SFC && CXL_MEM >= SFC default SFC help This enables SFC CXL support if the kernel is configuring CXL for diff --git a/drivers/net/ethernet/stmicro/stmmac/descs.h b/drivers/net/ethernet/stmicro/stmmac/descs.h index 846007cc245f..0af819a98fda 100644 --- a/drivers/net/ethernet/stmicro/stmmac/descs.h +++ b/drivers/net/ethernet/stmicro/stmmac/descs.h @@ -116,7 +116,7 @@ #define ETDES1_BUFFER2_SIZE_MASK GENMASK(28, 16) /* Extended Receive descriptor definitions */ -#define ERDES4_IP_PAYLOAD_TYPE_MASK GENMASK(6, 2) +#define ERDES4_IP_PAYLOAD_TYPE_MASK GENMASK(2, 0) #define ERDES4_IP_HDR_ERR BIT(3) #define ERDES4_IP_PAYLOAD_ERR BIT(4) #define ERDES4_IP_CSUM_BYPASSED BIT(5) @@ -147,6 +147,10 @@ #define RDES_PTP_SIGNALING 0xa #define RDES_PTP_PKT_RESERVED_TYPE 0xf +#define RDES_EXT_PAYLOAD_UDP 0x1 +#define RDES_EXT_PAYLOAD_TCP 0x2 +#define RDES_EXT_PAYLOAD_ICMP 0x3 + /* Basic descriptor structure for normal and alternate descriptors */ struct dma_desc { __le32 des0; diff --git a/drivers/net/ethernet/stmicro/stmmac/dwxgmac2_dma.c b/drivers/net/ethernet/stmicro/stmmac/dwxgmac2_dma.c index ff83858ebc1f..0a6e82a155c0 100644 --- a/drivers/net/ethernet/stmicro/stmmac/dwxgmac2_dma.c +++ b/drivers/net/ethernet/stmicro/stmmac/dwxgmac2_dma.c @@ -346,7 +346,7 @@ static int dwxgmac2_dma_interrupt(struct stmmac_priv *priv, u64_stats_update_end(&stats->syncp); ret |= handle_rx; } - if (likely(intr_status & (XGMAC_TI | XGMAC_TBU))) { + if (likely(intr_status & XGMAC_TI)) { u64_stats_update_begin(&stats->syncp); u64_stats_inc(&stats->tx_normal_irq_n[chan]); u64_stats_update_end(&stats->syncp); diff --git a/drivers/net/ethernet/stmicro/stmmac/enh_desc.c b/drivers/net/ethernet/stmicro/stmmac/enh_desc.c index 051253601225..023b54b72478 100644 --- a/drivers/net/ethernet/stmicro/stmmac/enh_desc.c +++ b/drivers/net/ethernet/stmicro/stmmac/enh_desc.c @@ -109,8 +109,25 @@ static int enh_desc_coe_rdes0(int ipc_err, int type, int payload_err) return ret; } -static void enh_desc_get_ext_status(struct stmmac_extra_stats *x, - struct dma_extended_desc *p) +static int enh_desc_ext_rx_csum(u32 rdes0, u32 rdes4, int status) +{ + u32 type = FIELD_GET(ERDES4_IP_PAYLOAD_TYPE_MASK, rdes4); + + if (status != csum_none || !(rdes0 & RDES0_FRAME_TYPE)) + return status; + if (!(rdes4 & (ERDES4_IPV4_PKT_RCVD | ERDES4_IPV6_PKT_RCVD)) || + (rdes4 & (ERDES4_IP_HDR_ERR | ERDES4_IP_PAYLOAD_ERR | + ERDES4_IP_CSUM_BYPASSED))) + return status; + if (type != RDES_EXT_PAYLOAD_UDP && type != RDES_EXT_PAYLOAD_TCP && + type != RDES_EXT_PAYLOAD_ICMP) + return status; + + return good_frame; +} + +static int enh_desc_get_ext_status(struct stmmac_extra_stats *x, + struct dma_extended_desc *p, int status) { u32 rdes0 = le32_to_cpu(p->basic.des0); u32 rdes4 = le32_to_cpu(p->des4); @@ -170,7 +187,11 @@ static void enh_desc_get_ext_status(struct stmmac_extra_stats *x, x->l4_filter_match++; if (rdes4 & ERDES4_L3_L4_FILT_NO_MATCH_MASK) x->l3_l4_filter_no_match++; + + status = enh_desc_ext_rx_csum(rdes0, rdes4, status); } + + return status; } static int enh_desc_get_rx_status(struct stmmac_extra_stats *x, diff --git a/drivers/net/ethernet/stmicro/stmmac/hwif.h b/drivers/net/ethernet/stmicro/stmmac/hwif.h index 5e2654c91b41..9925b789bcc9 100644 --- a/drivers/net/ethernet/stmicro/stmmac/hwif.h +++ b/drivers/net/ethernet/stmicro/stmmac/hwif.h @@ -70,8 +70,8 @@ struct stmmac_desc_ops { /* Return the reception status looking at the RDES1 */ int (*rx_status)(struct stmmac_extra_stats *x, struct dma_desc *p); - void (*rx_extended_status)(struct stmmac_extra_stats *x, - struct dma_extended_desc *p); + int (*rx_extended_status)(struct stmmac_extra_stats *x, + struct dma_extended_desc *p, int status); /* Set tx timestamp enable bit */ void (*enable_tx_timestamp) (struct dma_desc *p); /* get tx timestamp status */ @@ -128,7 +128,7 @@ struct stmmac_desc_ops { #define stmmac_rx_status(__priv, __args...) \ stmmac_do_callback(__priv, desc, rx_status, __args) #define stmmac_rx_extended_status(__priv, __args...) \ - stmmac_do_void_callback(__priv, desc, rx_extended_status, __args) + stmmac_do_callback(__priv, desc, rx_extended_status, __args) #define stmmac_enable_tx_timestamp(__priv, __args...) \ stmmac_do_void_callback(__priv, desc, enable_tx_timestamp, __args) #define stmmac_get_tx_timestamp_status(__priv, __args...) \ diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac.h b/drivers/net/ethernet/stmicro/stmmac/stmmac.h index d2d387f45c10..9cdad8430856 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac.h +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac.h @@ -270,6 +270,7 @@ struct stmmac_priv { bool sph_capable; u32 sarc_type; u32 rx_riwt[MTL_MAX_RX_QUEUES]; + u32 tx_threshold[MTL_MAX_TX_QUEUES]; int hwts_rx_en; bool tsfupdt_coarse; @@ -299,6 +300,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 1be5310ca766..e2c5b6950510 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_ethtool.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_ethtool.c @@ -798,7 +798,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; @@ -887,14 +888,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 b837e8e27a35..8a8e9f71e6f9 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_main.c @@ -1742,8 +1742,10 @@ static void stmmac_free_tx_buffer(struct stmmac_priv *priv, tx_q->xdpf[i] = NULL; } - if (tx_q->tx_skbuff_dma[i].buf_type == STMMAC_TXBUF_T_XSK_TX) + if (tx_q->tx_skbuff_dma[i].buf_type == STMMAC_TXBUF_T_XSK_TX) { tx_q->xsk_frames_done++; + tx_q->tx_skbuff_dma[i].buf_type = STMMAC_TXBUF_T_SKB; + } if (tx_q->tx_skbuff[i] && tx_q->tx_skbuff_dma[i].buf_type == STMMAC_TXBUF_T_SKB) { @@ -2591,7 +2593,6 @@ static void stmmac_dma_operation_mode(struct stmmac_priv *priv) } if (priv->plat->force_thresh_dma_mode) { - txmode = tc; rxmode = tc; } else if (priv->plat->force_sf_dma_mode || priv->plat->tx_coe) { /* @@ -2605,7 +2606,6 @@ static void stmmac_dma_operation_mode(struct stmmac_priv *priv) rxmode = SF_DMA_MODE; priv->xstats.threshold = SF_DMA_MODE; } else { - txmode = tc; rxmode = SF_DMA_MODE; } @@ -2624,8 +2624,11 @@ static void stmmac_dma_operation_mode(struct stmmac_priv *priv) for (chan = 0; chan < tx_channels_count; chan++) { qmode = priv->plat->tx_queues_cfg[chan].mode_to_use; - stmmac_dma_tx_mode(priv, priv->ioaddr, txmode, chan, - txfifosz, qmode); + if (txmode == SF_DMA_MODE) + priv->tx_threshold[chan] = SF_DMA_MODE; + + stmmac_dma_tx_mode(priv, priv->ioaddr, priv->tx_threshold[chan], + chan, txfifosz, qmode); } } @@ -2702,7 +2705,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. @@ -2743,12 +2747,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; @@ -2794,17 +2795,20 @@ static bool stmmac_xdp_xmit_zc(struct stmmac_priv *priv, u32 queue, u32 budget) static void stmmac_bump_dma_threshold(struct stmmac_priv *priv, u32 chan) { - if (unlikely(priv->xstats.threshold != SF_DMA_MODE) && tc <= 256) { - tc += 64; + u32 thresh = priv->tx_threshold[chan]; - if (priv->plat->force_thresh_dma_mode) - stmmac_set_dma_operation_mode(priv, tc, tc, chan); - else - stmmac_set_dma_operation_mode(priv, tc, SF_DMA_MODE, - chan); + if (unlikely(thresh == SF_DMA_MODE) || thresh > 256) + return; - priv->xstats.threshold = tc; - } + thresh += 64; + + if (priv->plat->force_thresh_dma_mode) + stmmac_set_dma_operation_mode(priv, thresh, tc, chan); + else + stmmac_set_dma_operation_mode(priv, thresh, SF_DMA_MODE, chan); + + priv->tx_threshold[chan] = thresh; + priv->xstats.threshold = thresh; } /** @@ -2926,8 +2930,11 @@ static int stmmac_tx_clean(struct stmmac_priv *priv, int budget, u32 queue, tx_q->xdpf[entry] = NULL; } - if (tx_q->tx_skbuff_dma[entry].buf_type == STMMAC_TXBUF_T_XSK_TX) + if (tx_q->tx_skbuff_dma[entry].buf_type == STMMAC_TXBUF_T_XSK_TX) { tx_q->xsk_frames_done++; + /* Teardown must not count this slot again. */ + tx_q->tx_skbuff_dma[entry].buf_type = STMMAC_TXBUF_T_SKB; + } if (tx_q->tx_skbuff_dma[entry].buf_type == STMMAC_TXBUF_T_SKB) { if (likely(skb)) { @@ -3390,7 +3397,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); @@ -3749,7 +3756,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); @@ -4521,10 +4528,10 @@ static netdev_tx_t stmmac_tso_xmit(struct sk_buff *skb, struct net_device *dev) struct dma_desc *desc, *first, *mss_desc = NULL; struct stmmac_priv *priv = netdev_priv(dev); 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; bool set_ic, is_last_segment; - u32 pay_len, mss, queue; dma_addr_t des; u8 hdr; @@ -4643,16 +4650,16 @@ static netdev_tx_t stmmac_tso_xmit(struct sk_buff *skb, struct net_device *dev) priv->dma_conf.dma_tx_size); 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; @@ -4797,9 +4804,9 @@ static netdev_tx_t stmmac_xmit(struct sk_buff *skb, struct net_device *dev) struct dma_desc *desc, *first_desc; struct stmmac_tx_queue *tx_q; int i, csum_insertion = 0; + u32 tx_coal, sdu_len; int entry, first_tx; dma_addr_t dma_addr; - u32 sdu_len; if (priv->tx_path_in_lpi_mode && priv->eee_sw_timer_en) stmmac_stop_sw_lpi(priv); @@ -4940,16 +4947,16 @@ static netdev_tx_t stmmac_xmit(struct sk_buff *skb, struct net_device *dev) tx_packets = CIRC_CNT(entry + 1, first_tx, priv->dma_conf.dma_tx_size); 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; @@ -5214,7 +5221,7 @@ static int stmmac_xdp_xmit_xdpf(struct stmmac_priv *priv, int queue, enum stmmac_txbuf_type buf_type; 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; @@ -5259,12 +5266,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); @@ -5604,9 +5607,13 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue) if (!buf->xdp) break; - if (priv->extend_desc) - stmmac_rx_extended_status(priv, &priv->xstats, - rx_q->dma_erx + entry); + if (priv->extend_desc) { + /* Read the extended status after the own bit */ + dma_rmb(); + status = stmmac_rx_extended_status(priv, &priv->xstats, + &rx_q->dma_erx[entry], + status); + } if (unlikely(status == discard_frame)) { xsk_buff_free(buf->xdp); buf->xdp = NULL; @@ -5787,8 +5794,13 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue) prefetch(np); - if (priv->extend_desc) - stmmac_rx_extended_status(priv, &priv->xstats, rx_q->dma_erx + entry); + if (priv->extend_desc) { + /* Read the extended status after the own bit */ + dma_rmb(); + status = stmmac_rx_extended_status(priv, &priv->xstats, + &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; @@ -7633,6 +7645,10 @@ int stmmac_reinit_queues(struct net_device *dev, u8 rx_cnt, u8 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); @@ -7640,6 +7656,9 @@ int stmmac_reinit_queues(struct net_device *dev, u8 rx_cnt, u8 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, @@ -7952,6 +7971,9 @@ static 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; @@ -8025,6 +8047,9 @@ static int __stmmac_dvr_probe(struct device *device, priv->xstats.threshold = tc; + for (i = 0; i < MTL_MAX_TX_QUEUES; i++) + priv->tx_threshold[i] = tc; + /* Initialize RSS */ rxq = priv->plat->rx_queues_to_use; netdev_rss_key_fill(priv->rss.key, sizeof(priv->rss.key)); diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_selftests.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_selftests.c index c485217ba880..6c01fdb6667e 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_selftests.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_selftests.c @@ -262,7 +262,7 @@ static int stmmac_test_loopback_validate(struct sk_buff *skb, struct tcphdr *thdr; struct iphdr *ihdr; - skb = skb_unshare(skb, GFP_ATOMIC); + skb = skb_share_check(skb, GFP_ATOMIC); if (!skb) goto out; diff --git a/drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c b/drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c index 42a00446e9b4..a7721b2eee96 100644 --- a/drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c +++ b/drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c @@ -1266,6 +1266,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); @@ -1299,11 +1302,19 @@ static int tc_setup_dwmac510_mqprio(struct stmmac_priv *priv, ndev_prio_tc_map[i] = READ_ONCE(ndev->prio_tc_map[i]); for (i = 0; i < qopt->num_tc; i++) { + if (qopt->offset[i] + qopt->count[i] > + priv->plat->tx_queues_to_use) { + NL_SET_ERR_MSG_MOD(extack, + "Queues exceed hw TX queues"); + return -EINVAL; + } + tc_to_txq[i] = (struct netdev_tc_txq) { .count = qopt->count[i], .offset = qopt->offset[i], }; - num_tx_queues += qopt->count[i]; + num_tx_queues = max(num_tx_queues, + qopt->offset[i] + qopt->count[i]); } err = stmmac_set_ndev_tcs(ndev, qopt->num_tc, tc_to_txq); @@ -1320,6 +1331,9 @@ static int tc_setup_dwmac510_mqprio(struct stmmac_priv *priv, if (err) goto error_reset_num_tx_queues; + priv->xmit_qdisc.num_tx_queues = num_tx_queues; + priv->xmit_qdisc.enabled = true; + return 0; error_reset_num_tx_queues: diff --git a/drivers/net/ethernet/ti/am65-cpts.c b/drivers/net/ethernet/ti/am65-cpts.c index efbf2ef976a3..df5659ead72f 100644 --- a/drivers/net/ethernet/ti/am65-cpts.c +++ b/drivers/net/ethernet/ti/am65-cpts.c @@ -779,6 +779,7 @@ static long am65_cpts_ts_work(struct ptp_clock_info *ptp); static struct ptp_clock_info am65_ptp_info = { .owner = THIS_MODULE, .name = "CTPS timer", + .supported_extts_flags = PTP_RISING_EDGE | PTP_STRICT_FLAGS, .adjfine = am65_cpts_ptp_adjfine, .adjtime = am65_cpts_ptp_adjtime, .gettimex64 = am65_cpts_ptp_gettimex, diff --git a/drivers/net/ethernet/xilinx/xilinx_axienet_main.c b/drivers/net/ethernet/xilinx/xilinx_axienet_main.c index 09443623a3e2..567ac8aed474 100644 --- a/drivers/net/ethernet/xilinx/xilinx_axienet_main.c +++ b/drivers/net/ethernet/xilinx/xilinx_axienet_main.c @@ -173,6 +173,46 @@ static dma_addr_t desc_get_phys_addr(struct axienet_local *lp, return ret; } +/** + * axienet_free_tx_bufs - Release the buffers still held by the TX ring + * @lp: Pointer to the axienet_local structure + * + * Unmap every descriptor whose mapping is still live, free any skb still + * attached, and clear the descriptor for reuse. axienet_free_tx_chain() + * clears cntrl when it reclaims a descriptor, so a non-zero value means + * the mapping is live. The DMA engine must be stopped. + */ +static void axienet_free_tx_bufs(struct axienet_local *lp) +{ + struct axidma_bd *cur_p; + u32 i; + + for (i = 0; i < lp->tx_bd_num; i++) { + cur_p = &lp->tx_bd_v[i]; + if (cur_p->cntrl) { + dma_addr_t addr = desc_get_phys_addr(lp, cur_p); + + dma_unmap_single(lp->dev, addr, + (cur_p->cntrl & + XAXIDMA_BD_CTRL_LENGTH_MASK), + DMA_TO_DEVICE); + } + /* not reclaimed by axienet_free_tx_chain(), so a drop */ + if (cur_p->skb) + dev_kfree_skb_any(cur_p->skb); + cur_p->phys = 0; + cur_p->phys_msb = 0; + cur_p->cntrl = 0; + cur_p->status = 0; + cur_p->app0 = 0; + cur_p->app1 = 0; + cur_p->app2 = 0; + cur_p->app3 = 0; + cur_p->app4 = 0; + cur_p->skb = NULL; + } +} + /** * axienet_dma_bd_release - Release buffer descriptor rings * @ndev: Pointer to the net_device structure @@ -186,11 +226,18 @@ static void axienet_dma_bd_release(struct net_device *ndev) int i; struct axienet_local *lp = netdev_priv(ndev); - /* If we end up here, tx_bd_v must have been DMA allocated. */ + /* tx_bd_v is NULL if axienet_dma_bd_init() did not get as far as + * allocating it, and is cleared below once the ring is freed; + * dma_free_coherent() accepts NULL. + */ + if (lp->tx_bd_v) + axienet_free_tx_bufs(lp); + dma_free_coherent(lp->dev, sizeof(*lp->tx_bd_v) * lp->tx_bd_num, lp->tx_bd_v, lp->tx_bd_p); + lp->tx_bd_v = NULL; if (!lp->rx_bd_v) return; @@ -198,13 +245,13 @@ static void axienet_dma_bd_release(struct net_device *ndev) for (i = 0; i < lp->rx_bd_num; i++) { dma_addr_t phys; - /* A NULL skb means this descriptor has not been initialised - * at all. + /* A NULL skb means the descriptor holds no buffer: it was + * never filled, or axienet_rx_poll() took its skb and could + * not refill it, having already unmapped the old buffer. + * Such slots can sit anywhere in a ring that has been running. */ if (!lp->rx_bd_v[i].skb) - break; - - dev_kfree_skb(lp->rx_bd_v[i].skb); + continue; /* For each descriptor, we programmed cntrl with the (non-zero) * descriptor size, after it had been successfully allocated. @@ -215,12 +262,15 @@ static void axienet_dma_bd_release(struct net_device *ndev) dma_unmap_single(lp->dev, phys, lp->max_frm_size, DMA_FROM_DEVICE); } + + dev_kfree_skb(lp->rx_bd_v[i].skb); } dma_free_coherent(lp->dev, sizeof(*lp->rx_bd_v) * lp->rx_bd_num, lp->rx_bd_v, lp->rx_bd_p); + lp->rx_bd_v = NULL; } static u64 axienet_dma_rate(struct axienet_local *lp) @@ -2749,29 +2799,7 @@ static void axienet_dma_err_handler(struct work_struct *work) axienet_dma_stop(lp); netdev_reset_queue(ndev); - for (i = 0; i < lp->tx_bd_num; i++) { - cur_p = &lp->tx_bd_v[i]; - if (cur_p->cntrl) { - dma_addr_t addr = desc_get_phys_addr(lp, cur_p); - - dma_unmap_single(lp->dev, addr, - (cur_p->cntrl & - XAXIDMA_BD_CTRL_LENGTH_MASK), - DMA_TO_DEVICE); - } - if (cur_p->skb) - dev_kfree_skb_irq(cur_p->skb); - cur_p->phys = 0; - cur_p->phys_msb = 0; - cur_p->cntrl = 0; - cur_p->status = 0; - cur_p->app0 = 0; - cur_p->app1 = 0; - cur_p->app2 = 0; - cur_p->app3 = 0; - cur_p->app4 = 0; - cur_p->skb = NULL; - } + axienet_free_tx_bufs(lp); for (i = 0; i < lp->rx_bd_num; i++) { cur_p = &lp->rx_bd_v[i]; diff --git a/drivers/net/gtp.c b/drivers/net/gtp.c index 69fe5717846b..efb045001c43 100644 --- a/drivers/net/gtp.c +++ b/drivers/net/gtp.c @@ -2050,7 +2050,10 @@ static int gtp_genl_new_pdp(struct sk_buff *skb, struct genl_info *info) rtnl_lock(); + /* the rtnl lock keeps the device alive once found */ + rcu_read_lock(); gtp = gtp_find_dev(sock_net(skb->sk), info->attrs); + rcu_read_unlock(); if (!gtp) { err = -ENODEV; goto out_unlock; @@ -2279,7 +2282,7 @@ static int gtp_genl_get_pdp(struct sk_buff *skb, struct genl_info *info) } err = gtp_genl_fill_info(skb2, NETLINK_CB(skb).portid, info->snd_seq, - 0, info->nlhdr->nlmsg_type, pctx); + 0, GTP_CMD_GETPDP, pctx); if (err < 0) goto err_unlock_free; @@ -2326,7 +2329,7 @@ static int gtp_genl_dump_pdp(struct sk_buff *skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, NLM_F_MULTI, - cb->nlh->nlmsg_type, pctx)) { + GTP_CMD_GETPDP, pctx)) { cb->args[0] = i; cb->args[1] = j; cb->args[2] = (unsigned long)gtp; @@ -2352,9 +2355,9 @@ static int gtp_genl_send_echo_req(struct sk_buff *skb, struct genl_info *info) struct gtp_dev *gtp; struct flowi4 fl4; struct rtable *rt; + int len, ret = 0; struct sock *sk; __be16 port; - int len; if (!info->attrs[GTPA_VERSION] || !info->attrs[GTPA_LINK] || @@ -2366,14 +2369,21 @@ static int gtp_genl_send_echo_req(struct sk_buff *skb, struct genl_info *info) dst_ip = nla_get_be32(info->attrs[GTPA_PEER_ADDRESS]); src_ip = nla_get_be32(info->attrs[GTPA_MS_ADDRESS]); + rcu_read_lock(); gtp = gtp_find_dev(sock_net(skb->sk), info->attrs); - if (!gtp) - return -ENODEV; + if (!gtp) { + ret = -ENODEV; + goto unlock; + } - if (!gtp->sk_created) - return -EOPNOTSUPP; - if (!(gtp->dev->flags & IFF_UP)) - return -ENETDOWN; + if (!gtp->sk_created) { + ret = -EOPNOTSUPP; + goto unlock; + } + if (!(gtp->dev->flags & IFF_UP)) { + ret = -ENETDOWN; + goto unlock; + } if (version == GTP_V0) { struct gtp0_header *gtp0_h; @@ -2382,8 +2392,10 @@ static int gtp_genl_send_echo_req(struct sk_buff *skb, struct genl_info *info) sizeof(struct iphdr) + sizeof(struct udphdr); skb_to_send = netdev_alloc_skb_ip_align(gtp->dev, len); - if (!skb_to_send) - return -ENOMEM; + if (!skb_to_send) { + ret = -ENOMEM; + goto unlock; + } sk = gtp->sk0; port = htons(GTP0_PORT); @@ -2399,8 +2411,10 @@ static int gtp_genl_send_echo_req(struct sk_buff *skb, struct genl_info *info) sizeof(struct iphdr) + sizeof(struct udphdr); skb_to_send = netdev_alloc_skb_ip_align(gtp->dev, len); - if (!skb_to_send) - return -ENOMEM; + if (!skb_to_send) { + ret = -ENOMEM; + goto unlock; + } sk = gtp->sk1u; port = htons(GTP1U_PORT); @@ -2410,7 +2424,8 @@ static int gtp_genl_send_echo_req(struct sk_buff *skb, struct genl_info *info) memset(gtp1u_h, 0, sizeof(struct gtp1_header_long)); gtp1u_build_echo_msg(gtp1u_h, GTP_ECHO_REQ); } else { - return -ENODEV; + ret = -ENODEV; + goto unlock; } rt = ip4_route_output_gtp(&fl4, sk, dst_ip, src_ip); @@ -2418,7 +2433,8 @@ static int gtp_genl_send_echo_req(struct sk_buff *skb, struct genl_info *info) netdev_dbg(gtp->dev, "no route for echo request to %pI4\n", &dst_ip); kfree_skb(skb_to_send); - return -ENODEV; + ret = -ENODEV; + goto unlock; } local_bh_disable(); @@ -2432,7 +2448,10 @@ static int gtp_genl_send_echo_req(struct sk_buff *skb, struct genl_info *info) dev_net(gtp->dev)), false, 0); local_bh_enable(); - return 0; + +unlock: + rcu_read_unlock(); + return ret; } static const struct nla_policy gtp_genl_policy[GTPA_MAX + 1] = { diff --git a/drivers/net/loopback.c b/drivers/net/loopback.c index 1fb6ce6843ad..6d16d6040401 100644 --- a/drivers/net/loopback.c +++ b/drivers/net/loopback.c @@ -70,6 +70,7 @@ EXPORT_SYMBOL(blackhole_netdev); static netdev_tx_t loopback_xmit(struct sk_buff *skb, struct net_device *dev) { + enum skb_drop_reason reason; int len; skb_tx_timestamp(skb); @@ -84,7 +85,12 @@ static netdev_tx_t loopback_xmit(struct sk_buff *skb, */ skb_dst_force(skb); - skb->protocol = eth_type_trans(skb, dev); + reason = eth_type_trans_careful(skb, dev); + if (unlikely(reason)) { + dev_core_stats_tx_dropped_inc(dev); + kfree_skb_reason(skb, reason); + return NETDEV_TX_OK; + } len = skb->len; if (likely(__netif_rx(skb) == NET_RX_SUCCESS)) diff --git a/drivers/net/macsec.c b/drivers/net/macsec.c index 78a19b134632..233391acebb0 100644 --- a/drivers/net/macsec.c +++ b/drivers/net/macsec.c @@ -486,6 +486,9 @@ static pn_t tx_sa_update_pn(struct macsec_tx_sa *tx_sa, spin_lock_bh(&tx_sa->lock); pn = tx_sa->next_pn_halves; + if (unlikely(pn.full64 == 0)) + goto out; + if (secy->xpn) tx_sa->next_pn++; else @@ -493,6 +496,8 @@ static pn_t tx_sa_update_pn(struct macsec_tx_sa *tx_sa, if (tx_sa->next_pn == 0) __macsec_pn_wrapped(secy, tx_sa); + +out: spin_unlock_bh(&tx_sa->lock); return pn; diff --git a/drivers/net/phy/marvell.c b/drivers/net/phy/marvell.c index f71cffa88406..94e8dbe9a859 100644 --- a/drivers/net/phy/marvell.c +++ b/drivers/net/phy/marvell.c @@ -55,6 +55,8 @@ #define MII_M1011_IMASK 0x12 #define MII_M1011_IMASK_INIT 0x6400 #define MII_M1011_IMASK_CLEAR 0x0000 +/* WOL Event Interrupt Enable, 88E1318S and 88E1510 only */ +#define MII_M1011_IMASK_WOL BIT(7) #define MII_M1011_PHY_SCR 0x10 #define MII_M1011_PHY_SCR_DOWNSHIFT_EN BIT(11) @@ -139,11 +141,6 @@ #define MII_88E1318S_PHY_MSCR1_REG 16 #define MII_88E1318S_PHY_MSCR1_PAD_ODD BIT(6) -/* Copper Specific Interrupt Enable Register */ -#define MII_88E1318S_PHY_CSIER 0x12 -/* WOL Event Interrupt Enable */ -#define MII_88E1318S_PHY_CSIER_WOL_EIE BIT(7) - #define MII_88E1318S_PHY_LED_FUNC 0x10 #define MII_88E1318S_PHY_LED_FUNC_OFF (0x8) #define MII_88E1318S_PHY_LED_FUNC_ON (0x9) @@ -354,6 +351,7 @@ struct marvell_priv { u32 step; s8 pair; u8 vct_phase; + bool wol_enabled; }; static int marvell_read_page(struct phy_device *phydev) @@ -407,7 +405,8 @@ static int marvell_config_intr(struct phy_device *phydev) return err; } -static irqreturn_t marvell_handle_interrupt(struct phy_device *phydev) +static irqreturn_t __marvell_handle_interrupt(struct phy_device *phydev, + u16 mask) { int irq_status; @@ -417,7 +416,7 @@ static irqreturn_t marvell_handle_interrupt(struct phy_device *phydev) return IRQ_NONE; } - if (!(irq_status & MII_M1011_IMASK_INIT)) + if (!(irq_status & mask)) return IRQ_NONE; phy_trigger_machine(phydev); @@ -425,6 +424,57 @@ static irqreturn_t marvell_handle_interrupt(struct phy_device *phydev) return IRQ_HANDLED; } +static irqreturn_t marvell_handle_interrupt(struct phy_device *phydev) +{ + return __marvell_handle_interrupt(phydev, MII_M1011_IMASK_INIT); +} + +/* WOL_EIE also routes WoL events to INTn. Keep it set while WoL is enabled, + * unless INTn is the PHY interrupt and that interrupt is being disabled: + * nothing would read IEVENT after free_irq() to release the line. + */ +static u16 m88e1318_wol_imask(struct phy_device *phydev) +{ + struct marvell_priv *priv = phydev->priv; + + if (priv->wol_enabled && + (phydev->interrupts == PHY_INTERRUPT_ENABLED || + !phy_interrupt_is_valid(phydev))) + return MII_M1011_IMASK_WOL; + + return 0; +} + +static int m88e1318_config_intr(struct phy_device *phydev) +{ + bool enable = phydev->interrupts == PHY_INTERRUPT_ENABLED; + u16 imask; + int err; + + if (enable) { + err = marvell_ack_interrupt(phydev); + if (err) + return err; + } + + /* Serialise against m88e1318_set_wol() updating wol_enabled */ + phy_lock_mdio_bus(phydev); + imask = enable ? MII_M1011_IMASK_INIT : MII_M1011_IMASK_CLEAR; + imask |= m88e1318_wol_imask(phydev); + err = __phy_write(phydev, MII_M1011_IMASK, imask); + phy_unlock_mdio_bus(phydev); + if (err || enable) + return err; + + return marvell_ack_interrupt(phydev); +} + +static irqreturn_t m88e1318_handle_interrupt(struct phy_device *phydev) +{ + return __marvell_handle_interrupt(phydev, MII_M1011_IMASK_INIT | + MII_M1011_IMASK_WOL); +} + static int marvell_set_polarity(struct phy_device *phydev, int polarity) { u16 val; @@ -1969,18 +2019,27 @@ static void m88e1318_get_wol(struct phy_device *phydev, static int m88e1318_set_wol(struct phy_device *phydev, struct ethtool_wolinfo *wol) { + struct marvell_priv *priv = phydev->priv; int err = 0, oldpage; oldpage = phy_save_page(phydev); if (oldpage < 0) goto error; - if (wol->wolopts & (WAKE_MAGIC | WAKE_PHY)) { - /* Explicitly switch to page 0x00, just to be sure */ - err = marvell_write_page(phydev, MII_MARVELL_COPPER_PAGE); - if (err < 0) - goto error; + priv->wol_enabled = !!(wol->wolopts & (WAKE_MAGIC | WAKE_PHY)); + /* Explicitly switch to page 0x00, just to be sure */ + err = marvell_write_page(phydev, MII_MARVELL_COPPER_PAGE); + if (err < 0) + goto error; + + /* Update the WOL interrupt enable */ + err = __phy_modify(phydev, MII_M1011_IMASK, MII_M1011_IMASK_WOL, + m88e1318_wol_imask(phydev)); + if (err < 0) + goto error; + + if (priv->wol_enabled) { /* If WOL event happened once, the LED[2] interrupt pin * will not be cleared unless we reading the interrupt status * register. If interrupts are in use, the normal interrupt @@ -1990,12 +2049,6 @@ static int m88e1318_set_wol(struct phy_device *phydev, if (!phy_interrupt_is_valid(phydev)) __phy_read(phydev, MII_M1011_IEVENT); - /* Enable the WOL interrupt */ - err = __phy_set_bits(phydev, MII_88E1318S_PHY_CSIER, - MII_88E1318S_PHY_CSIER_WOL_EIE); - if (err < 0) - goto error; - err = marvell_write_page(phydev, MII_MARVELL_LED_PAGE); if (err < 0) goto error; @@ -3817,8 +3870,8 @@ static struct phy_driver marvell_drivers[] = { .config_init = m88e1318_config_init, .config_aneg = m88e1318_config_aneg, .read_status = marvell_read_status, - .config_intr = marvell_config_intr, - .handle_interrupt = marvell_handle_interrupt, + .config_intr = m88e1318_config_intr, + .handle_interrupt = m88e1318_handle_interrupt, .get_wol = m88e1318_get_wol, .set_wol = m88e1318_set_wol, .resume = genphy_resume, @@ -3925,8 +3978,8 @@ static struct phy_driver marvell_drivers[] = { .config_init = m88e1510_config_init, .config_aneg = m88e1510_config_aneg, .read_status = marvell_read_status, - .config_intr = marvell_config_intr, - .handle_interrupt = marvell_handle_interrupt, + .config_intr = m88e1318_config_intr, + .handle_interrupt = m88e1318_handle_interrupt, .get_wol = m88e1318_get_wol, .set_wol = m88e1318_set_wol, .resume = m88e1510_resume, diff --git a/drivers/net/phy/qcom/at803x.c b/drivers/net/phy/qcom/at803x.c index cacbadf1f484..09105f1e3737 100644 --- a/drivers/net/phy/qcom/at803x.c +++ b/drivers/net/phy/qcom/at803x.c @@ -1019,10 +1019,10 @@ static int ipq5018_cable_test_start(struct phy_device *phydev) return 0; } -static int ipq5018_config_init(struct phy_device *phydev) +static int ipq5018_analog_init(struct phy_device *phydev) { struct ipq5018_priv *priv = phydev->priv; - u16 val; + int val, ret; /* * set LDO efuse: first temporarily store ANA_DAC_FILTER value from @@ -1030,39 +1030,66 @@ static int ipq5018_config_init(struct phy_device *phydev) * is written to */ val = at803x_debug_reg_read(phydev, IPQ5018_PHY_DEBUG_ANA_DAC_FILTER); - at803x_debug_reg_mask(phydev, IPQ5018_PHY_DEBUG_ANA_LDO_EFUSE, - IPQ5018_PHY_DEBUG_ANA_LDO_EFUSE_MASK, - IPQ5018_PHY_DEBUG_ANA_LDO_EFUSE_DEFAULT); - at803x_debug_reg_write(phydev, IPQ5018_PHY_DEBUG_ANA_DAC_FILTER, val); + if (val < 0) + return val; + + ret = at803x_debug_reg_mask(phydev, IPQ5018_PHY_DEBUG_ANA_LDO_EFUSE, + IPQ5018_PHY_DEBUG_ANA_LDO_EFUSE_MASK, + IPQ5018_PHY_DEBUG_ANA_LDO_EFUSE_DEFAULT); + if (ret) + return ret; + + ret = at803x_debug_reg_write(phydev, IPQ5018_PHY_DEBUG_ANA_DAC_FILTER, + val); + if (ret) + return ret; /* set 8023AZ EEE TX and RX timer values */ - phy_write_mmd(phydev, MDIO_MMD_PCS, IPQ5018_PHY_PCS_EEE_TX_TIMER, - IPQ5018_PHY_PCS_EEE_TX_TIMER_VAL); - phy_write_mmd(phydev, MDIO_MMD_PCS, IPQ5018_PHY_PCS_EEE_RX_TIMER, - IPQ5018_PHY_PCS_EEE_RX_TIMER_VAL); + ret = phy_write_mmd(phydev, MDIO_MMD_PCS, IPQ5018_PHY_PCS_EEE_TX_TIMER, + IPQ5018_PHY_PCS_EEE_TX_TIMER_VAL); + if (ret) + return ret; + + ret = phy_write_mmd(phydev, MDIO_MMD_PCS, IPQ5018_PHY_PCS_EEE_RX_TIMER, + IPQ5018_PHY_PCS_EEE_RX_TIMER_VAL); + if (ret) + return ret; /* set MSE threshold values */ - phy_write_mmd(phydev, MDIO_MMD_PMAPMD, IPQ5018_PHY_MMD1_MSE_THRESH1, - IPQ5018_PHY_MMD1_MSE_THRESH1_VAL); - phy_write_mmd(phydev, MDIO_MMD_PMAPMD, IPQ5018_PHY_MMD1_MSE_THRESH2, - IPQ5018_PHY_MMD1_MSE_THRESH2_VAL); + ret = phy_write_mmd(phydev, MDIO_MMD_PMAPMD, + IPQ5018_PHY_MMD1_MSE_THRESH1, + IPQ5018_PHY_MMD1_MSE_THRESH1_VAL); + if (ret) + return ret; + + ret = phy_write_mmd(phydev, MDIO_MMD_PMAPMD, + IPQ5018_PHY_MMD1_MSE_THRESH2, + IPQ5018_PHY_MMD1_MSE_THRESH2_VAL); + if (ret) + return ret; /* PHY DAC values are optional and only set in a PHY to PHY link architecture */ - if (priv->set_short_cable_dac) { - /* setting MDAC (Multi-level Digital-to-Analog Converter) in MMD1 */ - phy_modify_mmd(phydev, MDIO_MMD_PMAPMD, IPQ5018_PHY_MMD1_MDAC, - IPQ5018_PHY_DAC_MASK, - FIELD_PREP(IPQ5018_PHY_DAC_MASK, - IPQ5018_PHY_MMD1_MDAC_VAL)); - - /* setting EDAC (Error-detection and Correction) in debug register */ - at803x_debug_reg_mask(phydev, IPQ5018_PHY_DEBUG_EDAC, - IPQ5018_PHY_DAC_MASK, - FIELD_PREP(IPQ5018_PHY_DAC_MASK, - IPQ5018_PHY_DEBUG_EDAC_VAL)); - } + if (!priv->set_short_cable_dac) + return 0; - return 0; + /* setting MDAC (Multi-level Digital-to-Analog Converter) in MMD1 */ + ret = phy_modify_mmd(phydev, MDIO_MMD_PMAPMD, IPQ5018_PHY_MMD1_MDAC, + IPQ5018_PHY_DAC_MASK, + FIELD_PREP(IPQ5018_PHY_DAC_MASK, + IPQ5018_PHY_MMD1_MDAC_VAL)); + if (ret) + return ret; + + /* setting EDAC (Error-detection and Correction) in debug register */ + return at803x_debug_reg_mask(phydev, IPQ5018_PHY_DEBUG_EDAC, + IPQ5018_PHY_DAC_MASK, + FIELD_PREP(IPQ5018_PHY_DAC_MASK, + IPQ5018_PHY_DEBUG_EDAC_VAL)); +} + +static int ipq5018_config_init(struct phy_device *phydev) +{ + return ipq5018_analog_init(phydev); } static void ipq5018_link_change_notify(struct phy_device *phydev) @@ -1111,6 +1138,21 @@ static int ipq5018_probe(struct phy_device *phydev) phydev->priv = priv; + /* + * The PHY starts autonegotiation as soon as it leaves reset. Apply the + * analog settings now instead of waiting for config_init() at attach + * time, and restart autonegotiation so that it uses them. + */ + ret = ipq5018_analog_init(phydev); + if (ret) + return dev_err_probe(dev, ret, + "failed to apply analog settings\n"); + + ret = genphy_restart_aneg(phydev); + if (ret) + return dev_err_probe(dev, ret, + "failed to restart autonegotiation\n"); + return 0; } diff --git a/drivers/net/phy/qcom/qca83xx.c b/drivers/net/phy/qcom/qca83xx.c index bc70ed8efd86..2c4d085bacdb 100644 --- a/drivers/net/phy/qcom/qca83xx.c +++ b/drivers/net/phy/qcom/qca83xx.c @@ -92,6 +92,63 @@ static int qca83xx_probe(struct phy_device *phydev) return 0; } +static int qca8337_read_status(struct phy_device *phydev) +{ + struct at803x_ss_mask ss_mask = { + .speed_mask = AT803X_SS_SPEED_MASK, + .speed_shift = __bf_shf(AT803X_SS_SPEED_MASK), + }; + int ret, old_link = phydev->link; + + ret = genphy_read_status(phydev); + if (ret) + return ret; + + /* Keep the state resolved at link-up while the link stays up */ + if (phydev->autoneg == AUTONEG_ENABLE && old_link && phydev->link) + goto out; + + phydev->mdix = ETH_TP_MDI_INVALID; + + /* genphy_read_status() derives speed and duplex from the + * advertisements, which is wrong after a SmartSpeed downshift. + * Use what the PHY resolved instead. + */ + if (phydev->autoneg == AUTONEG_ENABLE && phydev->autoneg_complete && + phydev->link) { + phydev->speed = SPEED_UNKNOWN; + phydev->duplex = DUPLEX_UNKNOWN; + phydev->pause = false; + phydev->asym_pause = false; + + ret = at803x_read_specific_status(phydev, ss_mask); + if (ret) + return ret; + + /* Report the link down until speed and duplex are resolved, + * so that the next poll reads them again. Also clear what + * genphy_read_status() read for an up link, as the + * PHY_HALTED path of the state machine does. + */ + if (phydev->speed == SPEED_UNKNOWN || + phydev->duplex == DUPLEX_UNKNOWN) { + phydev->link = 0; + phydev->duplex = DUPLEX_UNKNOWN; + phydev->mdix = ETH_TP_MDI_INVALID; + phydev->master_slave_state = MASTER_SLAVE_STATE_UNKNOWN; + linkmode_zero(phydev->lp_advertising); + } else { + phy_resolve_aneg_pause(phydev); + } + } + +out: + /* MDI-X configuration is not implemented */ + phydev->mdix_ctrl = ETH_TP_MDI_INVALID; + + return 0; +} + static int qca83xx_config_init(struct phy_device *phydev) { u8 switch_revision; @@ -220,6 +277,7 @@ static struct phy_driver qca83xx_driver[] = { .flags = PHY_IS_INTERNAL, .config_init = qca83xx_config_init, .soft_reset = genphy_soft_reset, + .read_status = qca8337_read_status, .get_sset_count = qca83xx_get_sset_count, .get_strings = qca83xx_get_strings, .get_stats = qca83xx_get_stats, diff --git a/drivers/net/phy/realtek/realtek_main.c b/drivers/net/phy/realtek/realtek_main.c index 177b62a7b2d1..c867e5213216 100644 --- a/drivers/net/phy/realtek/realtek_main.c +++ b/drivers/net/phy/realtek/realtek_main.c @@ -1375,7 +1375,7 @@ static int rtl821x_resume(struct phy_device *phydev) msleep(20); - return 0; + return rtl8211f_config_rgmii_delay(phydev); } static int rtl8211f_resume(struct phy_device *phydev) diff --git a/drivers/net/ppp/ppp_generic.c b/drivers/net/ppp/ppp_generic.c index 3998ce4332f4..29847dc4bb45 100644 --- a/drivers/net/ppp/ppp_generic.c +++ b/drivers/net/ppp/ppp_generic.c @@ -45,6 +45,7 @@ #include #include #include +#include #include #include #include @@ -2278,6 +2279,73 @@ static bool ppp_decompress_proto(struct sk_buff *skb) return pskb_may_pull(skb, 2); } +#define PPP_BRIDGE_GSO_TYPES (SKB_GSO_TCPV4 | SKB_GSO_TCPV6 | \ + SKB_GSO_TCP_ECN | SKB_GSO_TCP_ACCECN | \ + SKB_GSO_TCP_FIXEDID | SKB_GSO_UDP_L4 | \ + SKB_GSO_FRAGLIST | SKB_GSO_DODGY) + +/* Segment a GSO packet (built by PPPoE GRO, or injected with a + * virtio_net_hdr) before sending it to a bridged channel that does + * not accept GSO packets. + * skb->data points to the PPP protocol field, which is replicated + * in front of each segment. + * Returns a list of segments, or NULL if the packet was dropped. + */ +static struct sk_buff *ppp_bridge_gso_segment(struct sk_buff *skb, + netdev_features_t features) +{ + struct sk_buff *segs; + + /* skb->dev is NULL here (cleared by __sk_receive_skb() for PPPoE), + * and some GSO handlers (tunnels, IPv6 UFO) dereference it. + */ + if (skb->encapsulation || + (skb_shinfo(skb)->gso_type & ~PPP_BRIDGE_GSO_TYPES)) + goto drop; + + if (!pskb_may_pull(skb, PPP_PROTO_LEN)) + goto drop; + + switch (get_unaligned((__be16 *)skb->data)) { + case htons(PPP_IP): + skb->protocol = htons(ETH_P_IP); + break; + case htons(PPP_IPV6): + skb->protocol = htons(ETH_P_IPV6); + break; + default: + goto drop; + } + skb_set_network_header(skb, PPP_PROTO_LEN); + + /* No checksum offload: skb_segment() computes the checksums. */ + segs = skb_gso_segment(skb, features); + if (IS_ERR_OR_NULL(segs)) + goto drop; + + consume_skb(skb); + return segs; + +drop: + kfree_skb(skb); + return NULL; +} + +static void ppp_bridge_xmit(struct ppp_channel *chan, struct sk_buff *skb) +{ + if (!chan->direct_xmit && skb_linearize(skb)) + goto drop; + + if (!chan->xmit_offload && skb->ip_summed == CHECKSUM_PARTIAL && + skb_csum_hwoffload_help(skb, 0)) + goto drop; + + if (chan->ops->start_xmit(chan, skb)) + return; +drop: + kfree_skb(skb); +} + /* Attempt to handle a frame via. a bridged channel, if one exists. * If the channel is bridged, the frame is consumed by the bridge. * If not, the caller must handle the frame by normal recv mechanisms. @@ -2285,6 +2353,8 @@ static bool ppp_decompress_proto(struct sk_buff *skb) */ static bool ppp_channel_bridge_input(struct channel *pch, struct sk_buff *skb) { + struct sk_buff *segs, *next; + struct ppp_channel *chan; struct channel *pchb; rcu_read_lock(); @@ -2300,8 +2370,29 @@ static bool ppp_channel_bridge_input(struct channel *pch, struct sk_buff *skb) } skb_scrub_packet(skb, !net_eq(pch->chan_net, pchb->chan_net)); - if (!pchb->chan->ops->start_xmit(pchb->chan, skb)) - kfree_skb(skb); + + /* Receive paths such as L2TP pull headers without updating + * the checksum state: drop a stale CHECKSUM_PARTIAL state + * pointing before skb->data, as skb_postpull_rcsum() does. + */ + if (skb->ip_summed == CHECKSUM_PARTIAL && + skb_checksum_start_offset(skb) < 0) + skb->ip_summed = CHECKSUM_NONE; + + chan = pchb->chan; + if (!chan->xmit_offload && skb_is_gso(skb)) { + /* Channels needing linear packets get linear segments, + * others keep references to the original pages. + */ + segs = ppp_bridge_gso_segment(skb, chan->direct_xmit ? + NETIF_F_SG : 0); + skb_list_walk_safe(segs, skb, next) { + skb_mark_not_on_list(skb); + ppp_bridge_xmit(chan, skb); + } + } else { + ppp_bridge_xmit(chan, skb); + } outl: spin_unlock_bh(&pchb->downl); diff --git a/drivers/net/ppp/pppoe.c b/drivers/net/ppp/pppoe.c index ee0e318d6a2a..67c28ac763ef 100644 --- a/drivers/net/ppp/pppoe.c +++ b/drivers/net/ppp/pppoe.c @@ -460,6 +460,9 @@ static int pppoe_disc_rcv(struct sk_buff *skb, struct net_device *dev, if (skb->pkt_type != PACKET_HOST) goto abort; + if (skb_mac_header_len(skb) < ETH_HLEN) + goto abort; + if (!pskb_may_pull(skb, sizeof(struct pppoe_hdr))) goto abort; @@ -618,6 +621,10 @@ static int pppoe_connect(struct socket *sock, struct sockaddr_unsized *uservaddr pppox_unbind_sock(sk); pn = pppoe_pernet(sock_net(sk)); delete_item(pn, po); + + /* wait for concurrent readers before clearing the fields */ + synchronize_net(); + if (po->pppoe_dev) { dev_put(po->pppoe_dev); po->pppoe_dev = NULL; @@ -664,6 +671,7 @@ static int pppoe_connect(struct socket *sock, struct sockaddr_unsized *uservaddr po->chan.private = sk; po->chan.ops = &pppoe_chan_ops; po->chan.direct_xmit = true; + po->chan.xmit_offload = true; error = ppp_register_net_channel(dev_net(dev), &po->chan); if (error) { diff --git a/drivers/net/pse-pd/si3474.c b/drivers/net/pse-pd/si3474.c index 1845b9c51cf7..97a3b998729d 100644 --- a/drivers/net/pse-pd/si3474.c +++ b/drivers/net/pse-pd/si3474.c @@ -250,9 +250,9 @@ static int si3474_get_of_channels(struct si3474_priv *priv) "Failed to read channel reg property\n"); return ret; } - if (chan_id > SI3474_MAX_CHANS) { + if (chan_id >= SI3474_MAX_CHANS) { dev_err(&priv->client[0]->dev, - "Incorrect channel number: %d\n", chan_id); + "Incorrect channel number: %u\n", chan_id); return -EINVAL; } @@ -267,6 +267,16 @@ static int si3474_get_of_channels(struct si3474_priv *priv) pi->np); return -EINVAL; } + + /* The 2P/4P mode bit pairs channels 0+1 and 2+3 of a quad */ + if (pairset_found && + (priv->pi[pi_no].chan[0] ^ 1) != priv->pi[pi_no].chan[1]) { + dev_err(&priv->client[0]->dev, + "PI %pOF: channels %u and %u are not a channel pair\n", + pi->np, priv->pi[pi_no].chan[0], + priv->pi[pi_no].chan[1]); + return -EINVAL; + } } return 0; @@ -312,8 +322,13 @@ static int si3474_pi_enable(struct pse_controller_dev *pcdev, int id) /* DETECT_CLASS_ENABLE must be set when using AUTO mode, * otherwise PI does not power up - datasheet section 2.10.2 */ - val = CHAN_BIT(chan0) | CHAN_UPPER_BIT(chan0) | - CHAN_BIT(chan1) | CHAN_UPPER_BIT(chan1); + ret = i2c_smbus_read_byte_data(client, DETECT_CLASS_ENABLE_REG); + if (ret < 0) + return ret; + + val = (u8)ret; + val |= CHAN_BIT(chan0) | CHAN_UPPER_BIT(chan0) | + CHAN_BIT(chan1) | CHAN_UPPER_BIT(chan1); ret = i2c_smbus_write_byte_data(client, DETECT_CLASS_ENABLE_REG, val); if (ret) @@ -516,10 +531,8 @@ static int si3474_i2c_probe(struct i2c_client *client) return PTR_ERR(priv->client[1]); ret = devm_add_action_or_reset(dev, si3474_ancillary_i2c_remove, priv->client[1]); - if (ret < 0) { - dev_err(&priv->client[1]->dev, "Cannot register remove callback\n"); + if (ret) return ret; - } ret = i2c_smbus_read_byte_data(priv->client[1], VENDOR_IC_ID_REG); if (ret < 0) { diff --git a/drivers/net/team/team_core.c b/drivers/net/team/team_core.c index ca75f08e3c59..957cc7885d2f 100644 --- a/drivers/net/team/team_core.c +++ b/drivers/net/team/team_core.c @@ -1225,6 +1225,17 @@ static int team_port_add(struct team *team, struct net_device *port_dev, return -EINVAL; } + if (port_dev->type == ARPHRD_CAN || + port_dev->type == ARPHRD_IEEE802154 || + port_dev->type == ARPHRD_IEEE802154_MONITOR || + port_dev->type == ARPHRD_6LOWPAN) { + NL_SET_ERR_MSG(extack, + "CAN, IEEE 802.15.4 and 6LoWPAN devices can't be added as a team port"); + netdev_err(dev, "Device %s is CAN, IEEE 802.15.4 or 6LoWPAN. These device types can't be added as a team port\n", + portname); + return -EINVAL; + } + if (netif_is_team_port(port_dev)) { NL_SET_ERR_MSG(extack, "Device is already a port of a team device"); netdev_err(dev, "Device %s is already a port " diff --git a/drivers/net/tun.c b/drivers/net/tun.c index 7cca1a6f72ff..2ed348b95315 100644 --- a/drivers/net/tun.c +++ b/drivers/net/tun.c @@ -688,14 +688,18 @@ static void tun_detach_all(struct net_device *dev) synchronize_net(); for (i = 0; i < n; i++) { tfile = rtnl_dereference(tun->tfiles[i]); + mutex_lock(&tfile->napi_mutex); tun_napi_del(tfile); + mutex_unlock(&tfile->napi_mutex); /* Drop read queue */ tun_queue_purge(tfile); xdp_rxq_info_unreg(&tfile->xdp_rxq); sock_put(&tfile->sk); } list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) { + mutex_lock(&tfile->napi_mutex); tun_napi_del(tfile); + mutex_unlock(&tfile->napi_mutex); tun_enable_queue(tfile); tun_queue_purge(tfile); xdp_rxq_info_unreg(&tfile->xdp_rxq); @@ -2549,6 +2553,12 @@ static int tun_xdp_one(struct tun_struct *tun, return -EINVAL; } + if (unlikely(!(READ_ONCE(tun->dev->flags) & IFF_UP))) { + put_page(virt_to_head_page(xdp->data)); + dev_core_stats_rx_dropped_inc(tun->dev); + return -EIO; + } + xdp_prog = rcu_dereference(tun->xdp_prog); if (xdp_prog) { if (gso->gso_type) { diff --git a/drivers/net/usb/cdc_mbim.c b/drivers/net/usb/cdc_mbim.c index a7010a0664c7..8f5734ac35b8 100644 --- a/drivers/net/usb/cdc_mbim.c +++ b/drivers/net/usb/cdc_mbim.c @@ -289,9 +289,10 @@ static struct sk_buff *cdc_mbim_tx_fixup(struct usbnet *dev, struct sk_buff *skb } } - spin_lock_bh(&ctx->mtx); + /* BHs or IRQs are always off here, see cdc_ncm_tx_fixup() */ + spin_lock(&ctx->mtx); skb_out = cdc_ncm_fill_tx_frame(dev, skb, sign); - spin_unlock_bh(&ctx->mtx); + spin_unlock(&ctx->mtx); return skb_out; error: diff --git a/drivers/net/usb/cdc_ncm.c b/drivers/net/usb/cdc_ncm.c index 35db38cb3e4a..3bd7cb66f3fc 100644 --- a/drivers/net/usb/cdc_ncm.c +++ b/drivers/net/usb/cdc_ncm.c @@ -1535,14 +1535,17 @@ cdc_ncm_tx_fixup(struct usbnet *dev, struct sk_buff *skb, gfp_t flags) if (ctx == NULL) goto error; - spin_lock_bh(&ctx->mtx); + /* BHs or IRQs are always off here. netpoll only disables IRQs, and + * spin_unlock_bh() would then run softirqs with the txq lock held. + */ + spin_lock(&ctx->mtx); if (ctx->is_ndp16) skb_out = cdc_ncm_fill_tx_frame(dev, skb, cpu_to_le32(USB_CDC_NCM_NDP16_NOCRC_SIGN)); else skb_out = cdc_ncm_fill_tx_frame(dev, skb, cpu_to_le32(USB_CDC_NCM_NDP32_NOCRC_SIGN)); - spin_unlock_bh(&ctx->mtx); + spin_unlock(&ctx->mtx); return skb_out; error: diff --git a/drivers/net/usb/lan78xx.c b/drivers/net/usb/lan78xx.c index 5655941f1478..af845623bf60 100644 --- a/drivers/net/usb/lan78xx.c +++ b/drivers/net/usb/lan78xx.c @@ -1712,13 +1712,16 @@ static int lan78xx_ethtool_set_eeprom(struct net_device *netdev, /* Invalid EEPROM_INDICATOR at offset zero will result in a failure * to load data from EEPROM */ - if (ee->magic == LAN78XX_EEPROM_MAGIC) + if (ee->magic == LAN78XX_EEPROM_MAGIC) { ret = lan78xx_write_raw_eeprom(dev, ee->offset, ee->len, data); - else if ((ee->magic == LAN78XX_OTP_MAGIC) && + } else if ((ee->magic == LAN78XX_OTP_MAGIC) && (ee->offset == 0) && (ee->len == 512) && - (data[0] == OTP_INDICATOR_1)) + (data[0] == OTP_INDICATOR_1)) { ret = lan78xx_write_raw_otp(dev, ee->offset, ee->len, data); + } else { + ret = -EINVAL; + } usb_autopm_put_interface(dev->intf); @@ -1764,6 +1767,12 @@ static void lan78xx_get_wol(struct net_device *netdev, u32 buf; struct lan78xx_priv *pdata = (struct lan78xx_priv *)(dev->data[0]); + if (!netdev->phydev) { + wol->supported = 0; + wol->wolopts = 0; + return; + } + if (usb_autopm_get_interface(dev->intf) < 0) return; @@ -1795,6 +1804,9 @@ static int lan78xx_set_wol(struct net_device *netdev, if (wol->wolopts & ~WAKE_ALL) return -EINVAL; + if (!netdev->phydev) + return -EOPNOTSUPP; + ret = usb_autopm_get_interface(dev->intf); if (ret < 0) return ret; diff --git a/drivers/net/usb/usbnet.c b/drivers/net/usb/usbnet.c index a19ecf718f36..97a30dd22c54 100644 --- a/drivers/net/usb/usbnet.c +++ b/drivers/net/usb/usbnet.c @@ -325,23 +325,30 @@ static void __usbnet_status_stop_force(struct usbnet *dev) */ void usbnet_skb_return(struct usbnet *dev, struct sk_buff *skb) { - struct pcpu_sw_netstats *stats64 = this_cpu_ptr(dev->net->tstats); + struct pcpu_sw_netstats *stats64; unsigned long flags; int status; - if (test_bit(EVENT_RX_PAUSED, &dev->flags)) { - skb_queue_tail(&dev->rxq_pause, skb); - return; + if (unlikely(test_bit(EVENT_RX_PAUSED, &dev->flags))) { + spin_lock_irqsave(&dev->rxq_pause.lock, flags); + if (test_bit(EVENT_RX_PAUSED, &dev->flags)) { + __skb_queue_tail(&dev->rxq_pause, skb); + spin_unlock_irqrestore(&dev->rxq_pause.lock, flags); + return; + } + spin_unlock_irqrestore(&dev->rxq_pause.lock, flags); } /* only update if unset to allow minidriver rx_fixup override */ if (skb->protocol == 0) skb->protocol = eth_type_trans(skb, dev->net); + stats64 = get_cpu_ptr(dev->net->tstats); flags = u64_stats_update_begin_irqsave(&stats64->syncp); u64_stats_inc(&stats64->rx_packets); u64_stats_add(&stats64->rx_bytes, skb->len); u64_stats_update_end_irqrestore(&stats64->syncp, flags); + put_cpu_ptr(dev->net->tstats); netif_dbg(dev, rx_status, dev->net, "< rx, len %zu, type 0x%x\n", skb->len + sizeof(struct ethhdr), skb->protocol); @@ -696,13 +703,20 @@ EXPORT_SYMBOL_GPL(usbnet_pause_rx); void usbnet_resume_rx(struct usbnet *dev) { + struct sk_buff_head q; struct sk_buff *skb; + unsigned long flags; int num = 0; + __skb_queue_head_init(&q); + local_bh_disable(); + spin_lock_irqsave(&dev->rxq_pause.lock, flags); clear_bit(EVENT_RX_PAUSED, &dev->flags); + skb_queue_splice_init(&dev->rxq_pause, &q); + spin_unlock_irqrestore(&dev->rxq_pause.lock, flags); - while ((skb = skb_dequeue(&dev->rxq_pause)) != NULL) { + while ((skb = __skb_dequeue(&q))) { usbnet_skb_return(dev, skb); num++; } @@ -1298,13 +1312,15 @@ static void tx_complete(struct urb *urb) struct usbnet *dev = entry->dev; if (urb->status == 0) { - struct pcpu_sw_netstats *stats64 = this_cpu_ptr(dev->net->tstats); + struct pcpu_sw_netstats *stats64; unsigned long flags; + stats64 = get_cpu_ptr(dev->net->tstats); flags = u64_stats_update_begin_irqsave(&stats64->syncp); u64_stats_add(&stats64->tx_packets, entry->packets); u64_stats_add(&stats64->tx_bytes, entry->length); u64_stats_update_end_irqrestore(&stats64->syncp, flags); + put_cpu_ptr(dev->net->tstats); } else { dev->net->stats.tx_errors++; diff --git a/drivers/net/veth.c b/drivers/net/veth.c index c1859ffcdaf1..e5ea979005d2 100644 --- a/drivers/net/veth.c +++ b/drivers/net/veth.c @@ -377,6 +377,9 @@ static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev) skb_tx_timestamp(skb); + /* tx queue index of this device, meaningless as rx queue of the peer */ + skb_set_queue_mapping(skb, 0); + ret = veth_forward_skb(rcv, skb, rq, use_napi); switch (ret) { case NET_RX_SUCCESS: /* same as NETDEV_TX_OK */ @@ -397,6 +400,8 @@ static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev) } /* Restore Eth hdr pulled by dev_forward_skb/eth_type_trans */ __skb_push(skb, ETH_HLEN); + /* qdisc requeues the skb on the txq it points to */ + skb_set_queue_mapping(skb, rxq); netif_tx_stop_queue(txq); /* Makes sure NAPI peer consumer runs. Consumer is responsible * for starting txq again, until then ndo_start_xmit (this @@ -612,7 +617,7 @@ static void veth_xdp_flush(struct veth_rq *rq, struct veth_xdp_tx_bq *bq) rcv_priv = netdev_priv(rcv); rcv_rq = &rcv_priv->rq[veth_select_rxq(rcv)]; /* xdp_ring is initialized on receive side? */ - if (unlikely(!rcu_access_pointer(rcv_rq->xdp_prog))) + if (unlikely(!rcu_access_pointer(rcv_rq->napi))) goto out; __veth_xdp_flush(rcv_rq); diff --git a/drivers/net/virtio_net.c b/drivers/net/virtio_net.c index 4e8a792cec0e..584bc05c577c 100644 --- a/drivers/net/virtio_net.c +++ b/drivers/net/virtio_net.c @@ -900,6 +900,15 @@ static struct sk_buff *page_to_skb(struct virtnet_info *vi, } BUG_ON(offset >= PAGE_SIZE); + + /* The first frag starts at offset, each next frag is a full page. */ + if (unlikely(DIV_ROUND_UP(offset + len, PAGE_SIZE) > MAX_SKB_FRAGS)) { + pr_debug("%s: rx error: len %u needs more than %d frags\n", + vi->dev->name, len, MAX_SKB_FRAGS); + kfree_skb(skb); + return NULL; + } + while (len) { unsigned int frag_size = min((unsigned)PAGE_SIZE - offset, len); skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page, offset, @@ -6709,7 +6718,8 @@ static void virtnet_set_big_packets(struct virtnet_info *vi, const int mtu) */ if (mtu > ETH_DATA_LEN || guest_gso) { vi->big_packets = true; - vi->big_packets_num_skbfrags = guest_gso ? MAX_SKB_FRAGS : DIV_ROUND_UP(mtu, PAGE_SIZE); + vi->big_packets_num_skbfrags = guest_gso ? MAX_SKB_FRAGS - 1 : + DIV_ROUND_UP(mtu, PAGE_SIZE); } } diff --git a/drivers/net/vxlan/vxlan_core.c b/drivers/net/vxlan/vxlan_core.c index 7ecd73a5a374..66fdca6cad1c 100644 --- a/drivers/net/vxlan/vxlan_core.c +++ b/drivers/net/vxlan/vxlan_core.c @@ -4358,7 +4358,7 @@ static int vxlan_nl2conf(struct nlattr *tb[], struct nlattr *data[], } conf->reserved_bits = reserved_bits; - } else { + } else if (!changelink) { /* For backwards compatibility, only allow reserved fields to be * used by VXLAN extensions if explicitly requested. */ diff --git a/drivers/net/wireless/ath/ath10k/htt_tx.c b/drivers/net/wireless/ath/ath10k/htt_tx.c index e46f579d745d..efaea150025b 100644 --- a/drivers/net/wireless/ath/ath10k/htt_tx.c +++ b/drivers/net/wireless/ath/ath10k/htt_tx.c @@ -505,9 +505,8 @@ int ath10k_htt_tx_start(struct ath10k_htt *htt) return ret; } -static int ath10k_htt_tx_clean_up_pending(int msdu_id, void *skb, void *ctx) +static void ath10k_htt_tx_clean_up_pending(int msdu_id, struct ath10k *ar) { - struct ath10k *ar = ctx; struct ath10k_htt *htt = &ar->htt; struct htt_tx_done tx_done = {}; @@ -517,8 +516,6 @@ static int ath10k_htt_tx_clean_up_pending(int msdu_id, void *skb, void *ctx) tx_done.status = HTT_TX_COMPL_STATE_DISCARD; ath10k_txrx_tx_unref(htt, &tx_done); - - return 0; } void ath10k_htt_tx_destroy(struct ath10k_htt *htt) @@ -535,8 +532,13 @@ void ath10k_htt_tx_destroy(struct ath10k_htt *htt) static void ath10k_htt_flush_tx_queue(struct ath10k_htt *htt) { + struct sk_buff *msdu; + int msdu_id; + ath10k_htc_stop_hl(htt->ar); - idr_for_each(&htt->pending_tx, ath10k_htt_tx_clean_up_pending, htt->ar); + + idr_for_each_entry(&htt->pending_tx, msdu, msdu_id) + ath10k_htt_tx_clean_up_pending(msdu_id, htt->ar); } void ath10k_htt_tx_stop(struct ath10k_htt *htt) diff --git a/drivers/net/wireless/ath/ath11k/Kconfig b/drivers/net/wireless/ath/ath11k/Kconfig index 122726f84492..44b520d2e66e 100644 --- a/drivers/net/wireless/ath/ath11k/Kconfig +++ b/drivers/net/wireless/ath/ath11k/Kconfig @@ -14,6 +14,9 @@ config ATH11K_AHB tristate "Atheros ath11k AHB support" depends on ATH11K depends on REMOTEPROC + select RPMSG + select QRTR + select QRTR_SMD help This module adds support for AHB bus diff --git a/drivers/net/wireless/ath/ath11k/ahb.c b/drivers/net/wireless/ath/ath11k/ahb.c index ec5bf5c9fd79..ee3f493d2e44 100644 --- a/drivers/net/wireless/ath/ath11k/ahb.c +++ b/drivers/net/wireless/ath/ath11k/ahb.c @@ -1296,14 +1296,16 @@ static void ath11k_ahb_remove(struct platform_device *pdev) { struct ath11k_base *ab = platform_get_drvdata(pdev); - if (test_bit(ATH11K_FLAG_QMI_FAIL, &ab->dev_flags)) { + ath11k_ahb_remove_prepare(ab); + + if (!test_bit(ATH11K_FLAG_REGISTERED, &ab->dev_flags)) { ath11k_ahb_power_down(ab, false); ath11k_debugfs_soc_destroy(ab); ath11k_qmi_deinit_service(ab); + ath11k_core_pm_notifier_unregister(ab); goto qmi_fail; } - ath11k_ahb_remove_prepare(ab); ath11k_core_deinit(ab); qmi_fail: @@ -1343,5 +1345,6 @@ static struct platform_driver ath11k_ahb_driver = { module_platform_driver(ath11k_ahb_driver); +MODULE_SOFTDEP("pre: qrtr_smd"); MODULE_DESCRIPTION("Driver support for Qualcomm Technologies 802.11ax WLAN AHB devices"); MODULE_LICENSE("Dual BSD/GPL"); diff --git a/drivers/net/wireless/ath/ath11k/ce.c b/drivers/net/wireless/ath/ath11k/ce.c index c56dd8a86760..1e08b0970b14 100644 --- a/drivers/net/wireless/ath/ath11k/ce.c +++ b/drivers/net/wireless/ath/ath11k/ce.c @@ -325,7 +325,7 @@ static int ath11k_ce_rx_post_pipe(struct ath11k_ce_pipe *pipe) dma_addr_t paddr; int ret = 0; - if (!(pipe->dest_ring || pipe->status_ring)) + if (!pipe->dest_ring || !pipe->status_ring) return 0; spin_lock_bh(&ab->ce.ce_lock); diff --git a/drivers/net/wireless/ath/ath11k/core.c b/drivers/net/wireless/ath/ath11k/core.c index 8039124e7832..766ae27306f4 100644 --- a/drivers/net/wireless/ath/ath11k/core.c +++ b/drivers/net/wireless/ath/ath11k/core.c @@ -1275,9 +1275,6 @@ int ath11k_core_suspend_late(struct ath11k_base *ab) if (ab->actual_pm_policy == ATH11K_PM_WOW) return 0; - ath11k_hif_irq_disable(ab); - ath11k_hif_ce_irq_disable(ab); - ath11k_hif_power_down(ab, true); return 0; @@ -2333,6 +2330,8 @@ static int ath11k_core_reconfigure_on_crash(struct ath11k_base *ab) int ret; mutex_lock(&ab->core_lock); + ath11k_hif_irq_disable(ab); + ath11k_hif_ce_irq_disable(ab); ath11k_thermal_unregister(ab); ath11k_dp_pdev_free(ab); ath11k_cfr_deinit(ab); @@ -2449,8 +2448,7 @@ void ath11k_core_pre_reconfigure_recovery(struct ath11k_base *ab) complete(&ar->thermal.wmi_sync); wake_up(&ar->dp.tx_empty_waitq); - idr_for_each(&ar->txmgmt_idr, - ath11k_mac_tx_mgmt_pending_free, ar); + ath11k_mac_tx_mgmt_pending_free(ar); idr_destroy(&ar->txmgmt_idr); wake_up(&ar->txmgmt_empty_waitq); @@ -2595,9 +2593,6 @@ static void ath11k_core_reset(struct work_struct *work) time_left = wait_for_completion_timeout(&ab->recovery_start, ATH11K_RECOVER_START_TIMEOUT_HZ); - ath11k_hif_irq_disable(ab); - ath11k_hif_ce_irq_disable(ab); - ath11k_hif_power_down(ab, false); ath11k_hif_power_up(ab); diff --git a/drivers/net/wireless/ath/ath11k/dp_rx.c b/drivers/net/wireless/ath/ath11k/dp_rx.c index 33425707c084..5b717b731197 100644 --- a/drivers/net/wireless/ath/ath11k/dp_rx.c +++ b/drivers/net/wireless/ath/ath11k/dp_rx.c @@ -762,6 +762,9 @@ static void ath11k_dp_rx_tid_del_func(struct ath11k_dp *dp, void *ctx, struct ath11k_base *ab = dp->ab; struct dp_rx_tid *rx_tid = ctx; struct dp_reo_cache_flush_elem *elem, *tmp; + struct list_head flush_list; + + INIT_LIST_HEAD(&flush_list); if (status == HAL_REO_CMD_DRAIN) { goto free_desc; @@ -783,23 +786,25 @@ static void ath11k_dp_rx_tid_del_func(struct ath11k_dp *dp, void *ctx, list_add_tail(&elem->list, &dp->reo_cmd_cache_flush_list); dp->reo_cmd_cache_flush_count++; - /* Flush and invalidate aged REO desc from HW cache */ + /* identify aged REO desc that needs removal */ list_for_each_entry_safe(elem, tmp, &dp->reo_cmd_cache_flush_list, list) { if (dp->reo_cmd_cache_flush_count > DP_REO_DESC_FREE_THRESHOLD || time_after(jiffies, elem->ts + msecs_to_jiffies(DP_REO_DESC_FREE_TIMEOUT_MS))) { - list_del(&elem->list); + list_move_tail(&elem->list, &flush_list); dp->reo_cmd_cache_flush_count--; - spin_unlock_bh(&dp->reo_cmd_lock); - - ath11k_dp_reo_cache_flush(ab, &elem->data); - kfree(elem); - spin_lock_bh(&dp->reo_cmd_lock); } } spin_unlock_bh(&dp->reo_cmd_lock); + /* remove aged REO desc from HW */ + list_for_each_entry_safe(elem, tmp, &flush_list, list) { + ath11k_dp_reo_cache_flush(ab, &elem->data); + list_del(&elem->list); + kfree(elem); + } + return; free_desc: dma_free_noncoherent(ab->dev, rx_tid->unaligned_size, diff --git a/drivers/net/wireless/ath/ath11k/mac.c b/drivers/net/wireless/ath/ath11k/mac.c index c1fa42edd363..1a237adaa37d 100644 --- a/drivers/net/wireless/ath/ath11k/mac.c +++ b/drivers/net/wireless/ath/ath11k/mac.c @@ -6167,25 +6167,27 @@ static void ath11k_mac_tx_mgmt_free(struct ath11k *ar, int buf_id) ath11k_mgmt_over_wmi_tx_drop(ar, msdu); } -int ath11k_mac_tx_mgmt_pending_free(int buf_id, void *skb, void *ctx) +void ath11k_mac_tx_mgmt_pending_free(struct ath11k *ar) { - struct ath11k *ar = ctx; - - ath11k_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) + ath11k_mac_tx_mgmt_free(ar, buf_id); } -static int ath11k_mac_vif_txmgmt_idr_remove(int buf_id, void *skb, void *ctx) +static void ath11k_mac_vif_txmgmt_cleanup(struct ath11k *ar, + struct ieee80211_vif *vif) { - struct ieee80211_vif *vif = ctx; - struct ath11k_skb_cb *skb_cb = ATH11K_SKB_CB((struct sk_buff *)skb); - struct ath11k *ar = skb_cb->ar; - - if (skb_cb->vif == vif) - ath11k_mac_tx_mgmt_free(ar, buf_id); + struct ath11k_skb_cb *skb_cb; + struct sk_buff *skb; + int buf_id; - return 0; + idr_for_each_entry(&ar->txmgmt_idr, skb, buf_id) { + skb_cb = ATH11K_SKB_CB(skb); + if (skb_cb->vif == vif) + ath11k_mac_tx_mgmt_free(ar, buf_id); + } } static int ath11k_mac_mgmt_tx_wmi(struct ath11k *ar, struct ath11k_vif *arvif, @@ -7417,8 +7419,7 @@ static void ath11k_mac_op_remove_interface(struct ieee80211_hw *hw, ath11k_peer_cleanup(ar, arvif->vdev_id); - idr_for_each(&ar->txmgmt_idr, - ath11k_mac_vif_txmgmt_idr_remove, vif); + ath11k_mac_vif_txmgmt_cleanup(ar, vif); for (i = 0; i < ab->hw_params.hal_params->num_tx_rings; i++) { spin_lock_bh(&ab->dp.tx_ring[i].tx_idr_lock); @@ -10418,7 +10419,7 @@ static void __ath11k_mac_unregister(struct ath11k *ar) ieee80211_unregister_hw(ar->hw); - idr_for_each(&ar->txmgmt_idr, ath11k_mac_tx_mgmt_pending_free, ar); + ath11k_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/ath11k/mac.h b/drivers/net/wireless/ath/ath11k/mac.h index 59f83c7175fd..127cb476b44b 100644 --- a/drivers/net/wireless/ath/ath11k/mac.h +++ b/drivers/net/wireless/ath/ath11k/mac.h @@ -162,7 +162,7 @@ struct ath11k *ath11k_mac_get_ar_by_pdev_id(struct ath11k_base *ab, u32 pdev_id) void ath11k_mac_drain_tx(struct ath11k *ar); void ath11k_mac_peer_cleanup_all(struct ath11k *ar); -int ath11k_mac_tx_mgmt_pending_free(int buf_id, void *skb, void *ctx); +void ath11k_mac_tx_mgmt_pending_free(struct ath11k *ar); u8 ath11k_mac_bw_to_mac80211_bw(u8 bw); enum nl80211_he_gi ath11k_mac_he_gi_to_nl80211_he_gi(u8 sgi); enum nl80211_he_ru_alloc ath11k_mac_phy_he_ru_to_nl80211_he_ru_alloc(u16 ru_phy); diff --git a/drivers/net/wireless/ath/ath11k/wmi.c b/drivers/net/wireless/ath/ath11k/wmi.c index bbca275a8289..08fd6795ed9e 100644 --- a/drivers/net/wireless/ath/ath11k/wmi.c +++ b/drivers/net/wireless/ath/ath11k/wmi.c @@ -5136,6 +5136,15 @@ static int ath11k_service_ready_ext_event(struct ath11k_base *ab, err: kfree(svc_rdy_ext.mac_phy_caps); + + /* + * During TLV iteration the WMI_TAG_SOC_HAL_REG_CAPABILITIES + * handler may have allocated ab->reg_info_store, so free it + * on error to avoid a memory leak + */ + kfree(ab->reg_info_store); + ab->reg_info_store = NULL; + ath11k_wmi_free_dbring_caps(ab); return ret; } diff --git a/drivers/net/wireless/ath/ath12k/ahb.c b/drivers/net/wireless/ath/ath12k/ahb.c index d89a49c6ebb7..df79f15c1cca 100644 --- a/drivers/net/wireless/ath/ath12k/ahb.c +++ b/drivers/net/wireless/ath/ath12k/ahb.c @@ -191,6 +191,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; @@ -594,8 +614,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); @@ -647,12 +669,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) @@ -1229,7 +1258,7 @@ static int ath12k_ahb_probe(struct platform_device *pdev) ret = ab_ahb->device_family_ops->arch_init(ab); if (ret) { ath12k_err(ab, "AHB arch_init failed %d\n", ret); - goto err_rproc_deconfigure; + goto err_free_ext_napi; } ret = ath12k_core_init(ab); @@ -1243,6 +1272,9 @@ static int ath12k_ahb_probe(struct platform_device *pdev) err_deinit_arch: ab_ahb->device_family_ops->arch_deinit(ab); +err_free_ext_napi: + ath12k_ahb_free_ext_napi(ab); + err_rproc_deconfigure: mutex_lock(&ath12k_rproc_info_lock); ath12k_ahb_deconfigure_rproc(ab); @@ -1285,6 +1317,7 @@ static void ath12k_ahb_free_resources(struct ath12k_base *ab) struct platform_device *pdev = ab->pdev; struct ath12k_ahb *ab_ahb = ath12k_ab_to_ahb(ab); + 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 b25202effb00..c6af10e54c3f 100644 --- a/drivers/net/wireless/ath/ath12k/core.c +++ b/drivers/net/wireless/ath/ath12k/core.c @@ -1516,8 +1516,7 @@ static void ath12k_core_pre_reconfigure_recovery(struct ath12k_base *ab) complete_all(&ar->thermal.wmi_sync); 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); diff --git a/drivers/net/wireless/ath/ath12k/debugfs_htt_stats.c b/drivers/net/wireless/ath/ath12k/debugfs_htt_stats.c index b772181a496e..f84f1828275a 100644 --- a/drivers/net/wireless/ath/ath12k/debugfs_htt_stats.c +++ b/drivers/net/wireless/ath/ath12k/debugfs_htt_stats.c @@ -6190,7 +6190,7 @@ static ssize_t ath12k_write_htt_stats_type(struct file *file, const int size = 32; int num_args; - if (count > size) + if (count >= size) return -EINVAL; char *buf __free(kfree) = kzalloc(size, GFP_KERNEL); diff --git a/drivers/net/wireless/ath/ath12k/dp.c b/drivers/net/wireless/ath/ath12k/dp.c index 779529d189f8..eee9ab792115 100644 --- a/drivers/net/wireless/ath/ath12k/dp.c +++ b/drivers/net/wireless/ath/ath12k/dp.c @@ -1002,10 +1002,11 @@ static void ath12k_dp_cc_cleanup(struct ath12k_base *ab) if (!skb) continue; - dma_unmap_single(ab->dev, - ATH12K_SKB_RXCB(skb)->paddr, - skb->len + skb_tailroom(skb), - DMA_FROM_DEVICE); + if (!ATH12K_SKB_RXCB(skb)->unmapped) + dma_unmap_single(ab->dev, + ATH12K_SKB_RXCB(skb)->paddr, + skb->len + skb_tailroom(skb), + DMA_FROM_DEVICE); dev_kfree_skb_any(skb); } diff --git a/drivers/net/wireless/ath/ath12k/dp_mon.c b/drivers/net/wireless/ath/ath12k/dp_mon.c index 7d5be77b081f..db20d27b6333 100644 --- a/drivers/net/wireless/ath/ath12k/dp_mon.c +++ b/drivers/net/wireless/ath/ath12k/dp_mon.c @@ -81,24 +81,23 @@ struct sk_buff } EXPORT_SYMBOL(ath12k_dp_rx_alloc_mon_status_buf); -u32 ath12k_dp_mon_comp_ppduid(u32 msdu_ppdu_id, u32 *ppdu_id) +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; } EXPORT_SYMBOL(ath12k_dp_mon_comp_ppduid); diff --git a/drivers/net/wireless/ath/ath12k/dp_mon.h b/drivers/net/wireless/ath/ath12k/dp_mon.h index 162cdcaa57a7..f352655eae9d 100644 --- a/drivers/net/wireless/ath/ath12k/dp_mon.h +++ b/drivers/net/wireless/ath/ath12k/dp_mon.h @@ -100,7 +100,7 @@ struct sk_buff *ath12k_dp_rx_alloc_mon_status_buf(struct ath12k_base *ab, struct dp_rxdma_mon_ring *rx_ring, int *buf_id); -u32 ath12k_dp_mon_comp_ppduid(u32 msdu_ppdu_id, u32 *ppdu_id); +bool ath12k_dp_mon_comp_ppduid(u32 msdu_ppdu_id, u32 *ppdu_id); int ath12k_dp_mon_parse_status_buf(struct ath12k_pdev_dp *dp_pdev, struct ath12k_mon_data *pmon, diff --git a/drivers/net/wireless/ath/ath12k/mac.c b/drivers/net/wireless/ath/ath12k/mac.c index a997e888feb5..56578321e88c 100644 --- a/drivers/net/wireless/ath/ath12k/mac.c +++ b/drivers/net/wireless/ath/ath12k/mac.c @@ -1506,6 +1506,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++; @@ -9187,25 +9194,27 @@ 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 int ath12k_mac_vif_txmgmt_idr_remove(int buf_id, void *skb, void *ctx) +static void ath12k_mac_vif_txmgmt_cleanup(struct ath12k *ar, + struct ieee80211_vif *vif) { - struct ieee80211_vif *vif = ctx; - struct ath12k_skb_cb *skb_cb = ATH12K_SKB_CB(skb); - struct ath12k *ar = skb_cb->ar; - - if (skb_cb->vif == vif) - ath12k_mac_tx_mgmt_free(ar, buf_id); + struct ath12k_skb_cb *skb_cb; + struct sk_buff *skb; + int buf_id; - return 0; + idr_for_each_entry(&ar->txmgmt_idr, skb, buf_id) { + skb_cb = ATH12K_SKB_CB(skb); + if (skb_cb->vif == vif) + ath12k_mac_tx_mgmt_free(ar, buf_id); + } } static int ath12k_mac_mgmt_tx_wmi(struct ath12k *ar, struct ath12k_link_vif *arvif, @@ -10970,8 +10979,7 @@ static int ath12k_mac_vdev_delete(struct ath12k *ar, struct ath12k_link_vif *arv ath12k_peer_cleanup(ar, arvif->vdev_id); ath12k_ahvif_put_link_cache(ahvif, arvif->link_id); - idr_for_each(&ar->txmgmt_idr, - ath12k_mac_vif_txmgmt_idr_remove, vif); + ath12k_mac_vif_txmgmt_cleanup(ar, vif); ath12k_mac_vif_unref(ath12k_ab_to_dp(ab), vif); @@ -14728,7 +14736,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 aba98afd4365..ae44ebfd9bd9 100644 --- a/drivers/net/wireless/ath/ath12k/mac.h +++ b/drivers/net/wireless/ath/ath12k/mac.h @@ -173,7 +173,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); void ath12k_mac_dp_peer_cleanup(struct ath12k_hw *ah); -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/pci.c b/drivers/net/wireless/ath/ath12k/pci.c index 8978edb44cec..12bbb75570f1 100644 --- a/drivers/net/wireless/ath/ath12k/pci.c +++ b/drivers/net/wireless/ath/ath12k/pci.c @@ -313,11 +313,24 @@ static void ath12k_pci_sw_reset(struct ath12k_base *ab, bool power_on) ath12k_mhi_set_mhictrl_reset(ab); } -static void ath12k_pci_free_ext_irq(struct ath12k_base *ab) +static void ath12k_pci_free_ce_irq(struct ath12k_base *ab, int num_ce) +{ + int i, irq_idx; + + for (i = 0; i < num_ce; i++) { + if (ath12k_ce_get_attr_flags(ab, i) & CE_ATTR_DIS_INTR) + continue; + + irq_idx = ATH12K_PCI_IRQ_CE0_OFFSET + i; + free_irq(ab->irq_num[irq_idx], &ab->ce.ce_pipe[i]); + } +} + +static void ath12k_pci_free_ext_irq(struct ath12k_base *ab, int num_ext_irq_grp) { int i, j; - for (i = 0; i < ATH12K_EXT_IRQ_GRP_NUM_MAX; i++) { + for (i = 0; i < num_ext_irq_grp; i++) { struct ath12k_ext_irq_grp *irq_grp = &ab->ext_irq_grp[i]; for (j = 0; j < irq_grp->num_irq; j++) @@ -330,16 +343,8 @@ static void ath12k_pci_free_ext_irq(struct ath12k_base *ab) static void ath12k_pci_free_irq(struct ath12k_base *ab) { - int i, irq_idx; - - for (i = 0; i < ab->hw_params->ce_count; i++) { - if (ath12k_ce_get_attr_flags(ab, i) & CE_ATTR_DIS_INTR) - continue; - irq_idx = ATH12K_PCI_IRQ_CE0_OFFSET + i; - free_irq(ab->irq_num[irq_idx], &ab->ce.ce_pipe[i]); - } - - ath12k_pci_free_ext_irq(ab); + ath12k_pci_free_ce_irq(ab, ab->hw_params->ce_count); + ath12k_pci_free_ext_irq(ab, ATH12K_EXT_IRQ_GRP_NUM_MAX); } static void ath12k_pci_ce_irq_enable(struct ath12k_base *ab, u16 ce_id) @@ -595,8 +600,6 @@ static int ath12k_pci_ext_irq_config(struct ath12k_base *ab) irq = ath12k_pci_get_msi_irq(ab->dev, vector); - ab->irq_num[irq_idx] = irq; - ath12k_dbg(ab, ATH12K_DBG_PCI, "irq:%d group:%d\n", irq, i); @@ -607,22 +610,24 @@ static int ath12k_pci_ext_irq_config(struct ath12k_base *ab) if (ret) { ath12k_err(ab, "failed request irq %d: %d\n", vector, ret); - goto fail_request; + + for (n = 0; n < j; n++) + free_irq(ab->irq_num[irq_grp->irqs[n]], irq_grp); + + netif_napi_del(&ab->ext_irq_grp[i].napi); + free_netdev(ab->ext_irq_grp[i].napi_ndev); + goto fail_allocate; } + + ab->irq_num[irq_idx] = irq; } ath12k_pci_ext_grp_disable(irq_grp); } return 0; -fail_request: - /* i ->napi_ndev was properly allocated. Free it also */ - i += 1; fail_allocate: - for (n = 0; n < i; n++) { - irq_grp = &ab->ext_irq_grp[n]; - free_netdev(irq_grp->napi_ndev); - } + ath12k_pci_free_ext_irq(ab, i); return ret; } @@ -671,6 +676,8 @@ static int ath12k_pci_config_irq(struct ath12k_base *ab) if (ret) { ath12k_err(ab, "failed to request irq %d: %d\n", irq_idx, ret); + + ath12k_pci_free_ce_irq(ab, i); return ret; } @@ -681,8 +688,10 @@ static int ath12k_pci_config_irq(struct ath12k_base *ab) } ret = ath12k_pci_ext_irq_config(ab); - if (ret) + if (ret) { + ath12k_pci_free_ce_irq(ab, ab->hw_params->ce_count); return ret; + } return 0; } diff --git a/drivers/net/wireless/ath/ath12k/wifi7/dp_mon.c b/drivers/net/wireless/ath/ath12k/wifi7/dp_mon.c index 016b0c38e51e..1e29c13ad66d 100644 --- a/drivers/net/wireless/ath/ath12k/wifi7/dp_mon.c +++ b/drivers/net/wireless/ath/ath12k/wifi7/dp_mon.c @@ -2675,6 +2675,8 @@ ath12k_wifi7_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; } @@ -2718,7 +2720,6 @@ ath12k_wifi7_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, @@ -2801,7 +2802,7 @@ ath12k_wifi7_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; @@ -2826,7 +2827,6 @@ ath12k_wifi7_dp_rx_mon_dest_process(struct ath12k *ar, int mac_id, struct ath12k_base *ab = ar->ab; struct ath12k_dp *dp = ath12k_ab_to_dp(ab); void *ring_entry, *mon_dst_srng; - struct dp_mon_mpdu *tmp_mpdu; LIST_HEAD(rx_desc_used_list); struct hal_srng *srng; @@ -2892,18 +2892,16 @@ ath12k_wifi7_dp_rx_mon_dest_process(struct ath12k *ar, int mac_id, } if (head_msdu && tail_msdu) { - tmp_mpdu = kzalloc_obj(*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_wifi7_dp_mon_rx_deliver(&ar->dp, 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_wifi7_dp_mon_rx_deliver(&ar->dp, &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, @@ -3211,18 +3209,23 @@ __ath12k_wifi7_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_wifi7_dp_mon_rx_memset_ppdu_info(ppdu_info); hal_status = ath12k_wifi7_dp_mon_parse_rx_dest(&ar->dp, 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_wifi7_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_wifi7_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/wifi7/dp_tx.c b/drivers/net/wireless/ath/ath12k/wifi7/dp_tx.c index e14f1d190ba8..4ce0948d429f 100644 --- a/drivers/net/wireless/ath/ath12k/wifi7/dp_tx.c +++ b/drivers/net/wireless/ath/ath12k/wifi7/dp_tx.c @@ -63,7 +63,7 @@ ath12k_wifi7_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); @@ -313,10 +313,15 @@ int ath12k_wifi7_dp_tx(struct ath12k_pdev_dp *dp_pdev, struct ath12k_link_vif *a goto map; } - /* hdr is pointing to a wrong place after alignment, - * so refresh it for later use. + /* + * The payload may have been shifted or even the entire buffer may have + * been reallocated for alignment. In that case, hdr, eth and skb_cb + * are stale pointers. Refresh them now for later dereference. */ hdr = (void *)skb->data; + if (eth) + eth = (struct ethhdr *)skb->data; + skb_cb = ATH12K_SKB_CB(skb); } map: ti.paddr = dma_map_single(dp->dev, skb->data, skb->len, DMA_TO_DEVICE); @@ -449,15 +454,17 @@ int ath12k_wifi7_dp_tx(struct ath12k_pdev_dp *dp_pdev, struct ath12k_link_vif *a return 0; fail_unmap_dma_ext: - if (skb_cb->paddr_ext_desc) + if (skb_cb->paddr_ext_desc) { dma_unmap_single(dp->dev, skb_cb->paddr_ext_desc, skb_ext_desc->len, DMA_TO_DEVICE); + skb_cb->paddr_ext_desc = 0; + } fail_free_ext_skb: kfree_skb(skb_ext_desc); fail_unmap_dma: - dma_unmap_single(dp->dev, ti.paddr, ti.data_len, DMA_TO_DEVICE); + dma_unmap_single(dp->dev, skb_cb->paddr, skb->len, DMA_TO_DEVICE); fail_remove_tx_buf: ath12k_dp_tx_release_txbuf(dp, tx_desc, pool_id); @@ -582,7 +589,8 @@ ath12k_dp_tx_process_htt_tx_complete(struct ath12k_dp *dp, void *desc, wbm_status = le32_get_bits(status_desc->info0, HTT_TX_WBM_COMP_INFO0_STATUS); - dp->device_stats.fw_tx_status[wbm_status]++; + if (likely(wbm_status < MAX_FW_TX_STATUS)) + dp->device_stats.fw_tx_status[wbm_status]++; switch (wbm_status) { case HAL_WBM_REL_HTT_TX_COMP_STATUS_OK: @@ -986,11 +994,17 @@ void ath12k_wifi7_dp_tx_completion_handler(struct ath12k_dp *dp, 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); - dp->device_stats.tx_wbm_rel_source[buf_rel_source]++; + if (likely(buf_rel_source < HAL_WBM_REL_SRC_MODULE_MAX)) + dp->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); - dp->device_stats.tqm_rel_reason[rel_status]++; + if (likely(rel_status < MAX_TQM_RELEASE_REASON)) + dp->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/wmi.c b/drivers/net/wireless/ath/ath12k/wmi.c index 3e812c79a649..b0610ce7d01c 100644 --- a/drivers/net/wireless/ath/ath12k/wmi.c +++ b/drivers/net/wireless/ath/ath12k/wmi.c @@ -6992,6 +6992,14 @@ static int ath12k_reg_chan_list_event(struct ath12k_base *ab, struct sk_buff *sk goto mem_free; } + /* + * Set the valid pdev_idx before validating so that, even when the + * event is dropped or falls back, the completion the caller in + * ath12k_mac_hw_register() may be waiting on is still signalled at + * the end and it does not time out. + */ + pdev_idx = reg_info->phy_id; + ret = ath12k_reg_validate_reg_info(ab, reg_info); if (ret == ATH12K_REG_STATUS_FALLBACK) { ath12k_warn(ab, "failed to validate reg info %d\n", ret); @@ -7008,7 +7016,6 @@ static int ath12k_reg_chan_list_event(struct ath12k_base *ab, struct sk_buff *sk } /* free old reg_info if it exist */ - pdev_idx = reg_info->phy_id; if (ab->reg_info[pdev_idx]) { ath12k_reg_reset_reg_info(ab->reg_info[pdev_idx]); kfree(ab->reg_info[pdev_idx]); @@ -7047,7 +7054,7 @@ static int ath12k_reg_chan_list_event(struct ath12k_base *ab, struct sk_buff *sk out: /* In some error cases, even a valid pdev_idx might not be available */ - if (pdev_idx != 255) + if (pdev_idx < ab->num_radios) ar = ab->pdevs[pdev_idx].ar; /* During the boot-time update, 'ar' might not be allocated, diff --git a/drivers/net/wireless/ath/ath6kl/cfg80211.c b/drivers/net/wireless/ath/ath6kl/cfg80211.c index 8bbe554a9b36..626b3908d6b3 100644 --- a/drivers/net/wireless/ath/ath6kl/cfg80211.c +++ b/drivers/net/wireless/ath/ath6kl/cfg80211.c @@ -1556,9 +1556,7 @@ static int ath6kl_cfg80211_del_iface(struct wiphy *wiphy, ath6kl_cfg80211_vif_stop(vif, test_bit(WMI_READY, &ar->flag)); - rtnl_lock(); ath6kl_cfg80211_vif_cleanup(vif); - rtnl_unlock(); return 0; } diff --git a/drivers/net/wireless/ath/ath9k/xmit.c b/drivers/net/wireless/ath/ath9k/xmit.c index 89d8b3178784..3413bb4906d4 100644 --- a/drivers/net/wireless/ath/ath9k/xmit.c +++ b/drivers/net/wireless/ath/ath9k/xmit.c @@ -168,7 +168,7 @@ static bool ath_merge_ratetbl(struct ieee80211_sta *sta, struct ath_buf *bf, if (!sta) return false; - ratetbl = rcu_dereference(sta->rates); + ratetbl = rcu_dereference_bh(sta->rates); if (!ratetbl) return false; diff --git a/drivers/net/wireless/ath/carl9170/debug.c b/drivers/net/wireless/ath/carl9170/debug.c index 0498df2a2160..bc6c8e0b1d16 100644 --- a/drivers/net/wireless/ath/carl9170/debug.c +++ b/drivers/net/wireless/ath/carl9170/debug.c @@ -119,7 +119,7 @@ static ssize_t carl9170_debugfs_write(struct file *file, if (!count) return 0; - if (count > PAGE_SIZE) + if (count >= PAGE_SIZE) return -E2BIG; ar = file->private_data; @@ -131,7 +131,7 @@ static ssize_t carl9170_debugfs_write(struct file *file, if (!dfops->write) return -ENOSYS; - buf = vmalloc(count); + buf = vmalloc(count + 1); if (!buf) return -ENOMEM; @@ -139,6 +139,7 @@ static ssize_t carl9170_debugfs_write(struct file *file, err = -EFAULT; goto out_free; } + buf[count] = '\0'; if (mutex_trylock(&ar->mutex) == 0) { err = -EAGAIN; diff --git a/drivers/net/wireless/broadcom/b43/debugfs.c b/drivers/net/wireless/broadcom/b43/debugfs.c index 31a1ff00c1a4..173ef5db90fc 100644 --- a/drivers/net/wireless/broadcom/b43/debugfs.c +++ b/drivers/net/wireless/broadcom/b43/debugfs.c @@ -557,7 +557,7 @@ static ssize_t b43_debugfs_write(struct file *file, if (!count) return 0; - if (count > PAGE_SIZE) + if (count >= PAGE_SIZE) return -E2BIG; dev = file->private_data; if (!dev) diff --git a/drivers/net/wireless/broadcom/b43legacy/debugfs.c b/drivers/net/wireless/broadcom/b43legacy/debugfs.c index a04d90d7307c..7ce8bcf12f0a 100644 --- a/drivers/net/wireless/broadcom/b43legacy/debugfs.c +++ b/drivers/net/wireless/broadcom/b43legacy/debugfs.c @@ -259,7 +259,7 @@ static ssize_t b43legacy_debugfs_write(struct file *file, if (!count) return 0; - if (count > PAGE_SIZE) + if (count >= PAGE_SIZE) return -E2BIG; dev = file->private_data; if (!dev) diff --git a/drivers/net/wireless/intel/iwlwifi/mld/low_latency.c b/drivers/net/wireless/intel/iwlwifi/mld/low_latency.c index a4ddc32e2860..e7482623111c 100644 --- a/drivers/net/wireless/intel/iwlwifi/mld/low_latency.c +++ b/drivers/net/wireless/intel/iwlwifi/mld/low_latency.c @@ -257,7 +257,8 @@ static bool iwl_mld_is_vo_vi_pkt(struct ieee80211_hdr *hdr) if (tid >= IWL_MAX_TID_COUNT) return false; - return tid_to_mac80211_ac[tid] < IEEE80211_AC_VI; + return tid_to_mac80211_ac[tid] == IEEE80211_AC_VI || + tid_to_mac80211_ac[tid] == IEEE80211_AC_VO; } void iwl_mld_low_latency_update_counters(struct iwl_mld *mld, diff --git a/drivers/net/wireless/intel/iwlwifi/mvm/utils.c b/drivers/net/wireless/intel/iwlwifi/mvm/utils.c index 2fd4a9961145..42432682fdc1 100644 --- a/drivers/net/wireless/intel/iwlwifi/mvm/utils.c +++ b/drivers/net/wireless/intel/iwlwifi/mvm/utils.c @@ -1356,8 +1356,8 @@ __le32 iwl_mvm_v3_rate_to_fw(u32 rate, u8 rate_ver) case RATE_MCS_MOD_TYPE_VHT: result = RATE_MCS_VHT_MSK_V1; result |= u32_encode_bits(u32_get_bits(rate, - RATE_VHT_MCS_NSS_MSK), - RATE_MCS_CODE_MSK); + RATE_MCS_CODE_MSK), + RATE_VHT_MCS_RATE_CODE_MSK); result |= u32_encode_bits(u32_get_bits(rate, RATE_MCS_NSS_MSK), RATE_VHT_MCS_NSS_MSK); break; diff --git a/drivers/net/wireless/marvell/mwifiex/cmdevt.c b/drivers/net/wireless/marvell/mwifiex/cmdevt.c index 29e0f274575e..268a795db486 100644 --- a/drivers/net/wireless/marvell/mwifiex/cmdevt.c +++ b/drivers/net/wireless/marvell/mwifiex/cmdevt.c @@ -1594,11 +1594,17 @@ int mwifiex_ret_get_hw_spec(struct mwifiex_private *priv, api_rev->major_ver, api_rev->minor_ver); break; - case FW_HOTFIX_VER_ID: + case FW_HOTFIX_VER_ID: { + struct hw_spec_fw_hotfix_ver *hf; + + hf = (void *)tlv; + adapter->fw_hotfix_ver = + le16_to_cpu(hf->hotfix_ver); mwifiex_dbg(adapter, INFO, "Firmware hotfix version %d\n", - api_rev->major_ver); + adapter->fw_hotfix_ver); break; + } default: mwifiex_dbg(adapter, FATAL, "Unknown api_id: %d\n", diff --git a/drivers/net/wireless/marvell/mwifiex/fw.h b/drivers/net/wireless/marvell/mwifiex/fw.h index 93561116959a..f254d6d6e3eb 100644 --- a/drivers/net/wireless/marvell/mwifiex/fw.h +++ b/drivers/net/wireless/marvell/mwifiex/fw.h @@ -1104,6 +1104,12 @@ struct hw_spec_api_rev { u8 minor_ver; } __packed; +struct hw_spec_fw_hotfix_ver { + struct mwifiex_ie_types_header header; + __le16 api_id; + __le16 hotfix_ver; +} __packed; + struct host_cmd_ds_get_hw_spec { __le16 hw_if_version; __le16 version; diff --git a/drivers/net/wireless/marvell/mwifiex/init.c b/drivers/net/wireless/marvell/mwifiex/init.c index 0c8925013724..e8a5f9b758d6 100644 --- a/drivers/net/wireless/marvell/mwifiex/init.c +++ b/drivers/net/wireless/marvell/mwifiex/init.c @@ -296,6 +296,7 @@ static void mwifiex_init_adapter(struct mwifiex_adapter *adapter) adapter->config_bands = 0; adapter->adhoc_start_band = 0; adapter->fw_release_number = 0; + adapter->fw_hotfix_ver = 0; adapter->fw_cap_info = 0; memset(&adapter->upld_buf, 0, sizeof(adapter->upld_buf)); adapter->event_cause = 0; diff --git a/drivers/net/wireless/marvell/mwifiex/main.h b/drivers/net/wireless/marvell/mwifiex/main.h index 27559e2ddc31..eb47ade44e1f 100644 --- a/drivers/net/wireless/marvell/mwifiex/main.h +++ b/drivers/net/wireless/marvell/mwifiex/main.h @@ -1003,6 +1003,7 @@ struct mwifiex_adapter { bool host_mlme_enabled; struct ieee80211_txrx_stypes mwifiex_mgmt_stypes[NUM_NL80211_IFTYPES]; u8 fw_api_ver; + u16 fw_hotfix_ver; u8 key_api_major_ver, key_api_minor_ver; u8 max_p2p_conn, max_sta_conn; struct memory_type_mapping *mem_type_mapping_tbl; diff --git a/drivers/net/wireless/marvell/mwifiex/sta_ioctl.c b/drivers/net/wireless/marvell/mwifiex/sta_ioctl.c index 19196848778c..1d3874734851 100644 --- a/drivers/net/wireless/marvell/mwifiex/sta_ioctl.c +++ b/drivers/net/wireless/marvell/mwifiex/sta_ioctl.c @@ -1144,7 +1144,8 @@ mwifiex_drv_get_driver_version(struct mwifiex_adapter *adapter, char *version, char fw_ver[32]; ver.l = cpu_to_le32(adapter->fw_release_number); - sprintf(fw_ver, "%u.%u.%u.p%u", ver.c[2], ver.c[1], ver.c[0], ver.c[3]); + sprintf(fw_ver, "%u.%u.%u.p%u.%u", ver.c[2], ver.c[1], + ver.c[0], ver.c[3], adapter->fw_hotfix_ver); snprintf(version, max_len, driver_version, fw_ver); diff --git a/drivers/net/wireless/mediatek/mt76/Kconfig b/drivers/net/wireless/mediatek/mt76/Kconfig index 2ca96e0527c0..a4ece38f938d 100644 --- a/drivers/net/wireless/mediatek/mt76/Kconfig +++ b/drivers/net/wireless/mediatek/mt76/Kconfig @@ -40,6 +40,7 @@ config MT792x_USB config MT76_NPU tristate depends on NET_AIROHA_NPU=y || MT76_CORE=NET_AIROHA_NPU + depends on NET_AIROHA=y || NET_AIROHA=n || MT76_CORE=NET_AIROHA source "drivers/net/wireless/mediatek/mt76/mt76x0/Kconfig" source "drivers/net/wireless/mediatek/mt76/mt76x2/Kconfig" diff --git a/drivers/net/wireless/mediatek/mt76/channel.c b/drivers/net/wireless/mediatek/mt76/channel.c index 28ad7bcaffd4..cf964aa5c644 100644 --- a/drivers/net/wireless/mediatek/mt76/channel.c +++ b/drivers/net/wireless/mediatek/mt76/channel.c @@ -41,7 +41,7 @@ int mt76_add_chanctx(struct ieee80211_hw *hw, if (WARN_ON_ONCE(!phy)) return ret; - if (dev->scan.phy == phy) + if (mt76_phy_scanning(phy)) mt76_abort_scan(dev); mutex_lock(&dev->mutex); @@ -66,7 +66,7 @@ void mt76_remove_chanctx(struct ieee80211_hw *hw, if (WARN_ON_ONCE(!phy)) return; - if (dev->scan.phy == phy) + if (mt76_phy_scanning(phy)) mt76_abort_scan(dev); mutex_lock(&dev->mutex); @@ -114,7 +114,7 @@ int mt76_assign_vif_chanctx(struct ieee80211_hw *hw, bool mlink_alloc = false; int ret = 0; - if (dev->scan.vif == vif) + if (dev->scan.vif == vif && mt76_phy_scanning(phy)) mt76_abort_scan(dev); mutex_lock(&dev->mutex); @@ -161,7 +161,7 @@ void mt76_unassign_vif_chanctx(struct ieee80211_hw *hw, struct mt76_phy *phy = ctx->phy; struct mt76_dev *dev = phy->dev; - if (dev->scan.vif == vif) + if (dev->scan.vif == vif && mt76_phy_scanning(phy)) mt76_abort_scan(dev); mutex_lock(&dev->mutex); @@ -209,7 +209,7 @@ int mt76_switch_vif_chanctx(struct ieee80211_hw *hw, continue; if (phy->chanctx != new_ctx) { - if (dev->scan.phy == phy) + if (mt76_phy_scanning(phy)) mt76_abort_scan(dev); cancel_delayed_work_sync(&phy->mac_work); @@ -330,11 +330,13 @@ void mt76_roc_complete(struct mt76_phy *phy) !test_bit(MT76_MCU_RESET, &dev->phy.state)) { __mt76_set_channel(phy, &phy->main_chandef, false); mt76_offchannel_notify(phy, false); + } else { + phy->offchannel = false; } mt76_put_vif_phy_link(phy, phy->roc_vif, phy->roc_link); phy->roc_vif = NULL; phy->roc_link = NULL; - if (!test_bit(MT76_MCU_RESET, &dev->phy.state)) + if (!test_bit(MT76_RESTART, &dev->phy.state)) ieee80211_remain_on_channel_expired(phy->hw); } @@ -379,8 +381,9 @@ int mt76_remain_on_channel(struct ieee80211_hw *hw, struct ieee80211_vif *vif, mutex_lock(&dev->mutex); - if (phy->roc_vif || dev->scan.phy == phy || - test_bit(MT76_MCU_RESET, &dev->phy.state)) { + if (phy->roc_vif || mt76_phy_scanning(phy) || + test_bit(MT76_MCU_RESET, &dev->phy.state) || + test_bit(MT76_RESTART, &dev->phy.state)) { ret = -EBUSY; goto out; } @@ -423,7 +426,7 @@ int mt76_cancel_remain_on_channel(struct ieee80211_hw *hw, struct mt76_vif_data *mvif = mlink->mvif; struct mt76_phy *phy = mvif->roc_phy; - if (!phy) + if (!phy || phy->roc_vif != vif) return 0; mt76_abort_roc(phy); diff --git a/drivers/net/wireless/mediatek/mt76/mac80211.c b/drivers/net/wireless/mediatek/mt76/mac80211.c index 3467eb6cea0b..d36466b2173e 100644 --- a/drivers/net/wireless/mediatek/mt76/mac80211.c +++ b/drivers/net/wireless/mediatek/mt76/mac80211.c @@ -432,6 +432,7 @@ mt76_phy_init(struct mt76_phy *phy, struct ieee80211_hw *hw) INIT_LIST_HEAD(&phy->tx_list); spin_lock_init(&phy->tx_lock); INIT_DELAYED_WORK(&phy->roc_work, mt76_roc_complete_work); + INIT_DELAYED_WORK(&phy->scan_work, mt76_scan_work); if ((void *)phy != hw->priv) return 0; @@ -729,7 +730,6 @@ mt76_alloc_device(struct device *pdev, unsigned int size, INIT_LIST_HEAD(&dev->txwi_cache); INIT_LIST_HEAD(&dev->rxwi_cache); dev->token_size = dev->drv->token_size; - INIT_DELAYED_WORK(&dev->scan_work, mt76_scan_work); spin_lock_init(&dev->scan_lock); for (i = 0; i < ARRAY_SIZE(dev->q_rx); i++) @@ -856,8 +856,8 @@ void mt76_reset_device(struct mt76_dev *dev) continue; wcid->sta = 0; - mt76_wcid_cleanup(dev, wcid); rcu_assign_pointer(dev->wcid[i], NULL); + mt76_wcid_cleanup(dev, wcid); } rcu_read_unlock(); @@ -1482,6 +1482,7 @@ mt76_check_sta(struct mt76_dev *dev, struct sk_buff *skb) struct ieee80211_hw *hw; struct mt76_wcid *wcid = status->wcid; u8 tidno = status->qos_ctl & IEEE80211_QOS_CTL_TID_MASK; + int signal; bool ps; hw = mt76_phy_hw(dev, status->phy_idx); @@ -1499,8 +1500,9 @@ mt76_check_sta(struct mt76_dev *dev, struct sk_buff *skb) sta = container_of((void *)wcid, struct ieee80211_sta, drv_priv); - if (status->signal <= 0) - ewma_signal_add(&wcid->rssi, -status->signal); + signal = mt76_rx_signal(status->chains, status->chain_signal); + if (signal <= 0 && signal > -128) + ewma_signal_add(&wcid->rssi, -signal); wcid->inactive_count = 0; @@ -1758,9 +1760,8 @@ void mt76_wcid_cleanup(struct mt76_dev *dev, struct mt76_wcid *wcid) mt76_tx_status_lock(dev, &list); mt76_tx_status_skb_get(dev, wcid, -1, &list); - mt76_tx_status_unlock(dev, &list); - idr_destroy(&wcid->pktid); + mt76_tx_status_unlock(dev, &list); /* Remove from sta_poll_list to prevent list corruption after reset. * Without this, mt76_reset_device() reinitializes sta_poll_list but @@ -2121,7 +2122,7 @@ void mt76_vif_cleanup(struct mt76_dev *dev, struct ieee80211_vif *vif) rcu_assign_pointer(mvif->link[0], NULL); mt76_abort_scan(dev); - if (mvif->roc_phy) + if (mvif->roc_phy && mvif->roc_phy->roc_vif == vif) mt76_abort_roc(mvif->roc_phy); } EXPORT_SYMBOL_GPL(mt76_vif_cleanup); @@ -2335,7 +2336,7 @@ void mt76_rx_beacon(struct mt76_phy *phy, struct sk_buff *skb) .bssid = hdr->addr3, }; - mt76_scan_rx_beacon(phy->dev, phy->chandef.chan); + mt76_scan_rx_beacon(phy, phy->chandef.chan); if (!phy->num_sta) return; diff --git a/drivers/net/wireless/mediatek/mt76/mt76.h b/drivers/net/wireless/mediatek/mt76/mt76.h index e9bbec1269fa..c5776e2b07a2 100644 --- a/drivers/net/wireless/mediatek/mt76/mt76.h +++ b/drivers/net/wireless/mediatek/mt76/mt76.h @@ -879,6 +879,15 @@ struct mt76_phy { struct ieee80211_vif *roc_vif; struct mt76_vif_link *roc_link; + struct delayed_work scan_work; + struct { + struct ieee80211_channel *chan; + struct mt76_vif_link *mlink; + int chan_idx; + bool beacon_wait; + bool beacon_received; + } scan; + struct mt76_chanctx *chanctx; struct mt76_channel_state *chan_state; @@ -1015,17 +1024,12 @@ struct mt76_dev { u32 rxfilter; - struct delayed_work scan_work; spinlock_t scan_lock; struct { - struct cfg80211_scan_request *req; - struct ieee80211_channel *chan; + struct ieee80211_scan_request *req; struct ieee80211_vif *vif; - struct mt76_vif_link *mlink; - struct mt76_phy *phy; - int chan_idx; - bool beacon_wait; - bool beacon_received; + unsigned long phy_mask; + bool aborted; } scan; #ifdef CONFIG_NL80211_TESTMODE @@ -1398,6 +1402,11 @@ mt76_phy_hw(struct mt76_dev *dev, u8 phy_idx) return mt76_dev_phy(dev, phy_idx)->hw; } +static inline bool mt76_phy_scanning(struct mt76_phy *phy) +{ + return test_bit(phy->band_idx, &phy->dev->scan.phy_mask); +} + static inline u8 * mt76_get_txwi_ptr(struct mt76_dev *dev, struct mt76_txwi_cache *t) { @@ -1625,7 +1634,7 @@ int mt76_get_rate(struct mt76_dev *dev, int mt76_hw_scan(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_scan_request *hw_req); void mt76_cancel_hw_scan(struct ieee80211_hw *hw, struct ieee80211_vif *vif); -void mt76_scan_rx_beacon(struct mt76_dev *dev, struct ieee80211_channel *chan); +void mt76_scan_rx_beacon(struct mt76_phy *phy, struct ieee80211_channel *chan); void mt76_rx_beacon(struct mt76_phy *phy, struct sk_buff *skb); void mt76_beacon_mon_check(struct mt76_phy *phy); void mt76_sw_scan(struct ieee80211_hw *hw, struct ieee80211_vif *vif, diff --git a/drivers/net/wireless/mediatek/mt76/mt7603/dma.c b/drivers/net/wireless/mediatek/mt76/mt7603/dma.c index 477a9b7a8cf7..491c8c937031 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7603/dma.c +++ b/drivers/net/wireless/mediatek/mt76/mt7603/dma.c @@ -34,7 +34,7 @@ mt7603_rx_loopback_skb(struct mt7603_dev *dev, struct sk_buff *skb) int idx; u32 val; - if (skb->len < MT_TXD_SIZE + sizeof(struct ieee80211_hdr)) + if (skb->len < MT_TXD_SIZE + 2) goto free; val = le32_to_cpu(txd[1]); @@ -52,6 +52,9 @@ mt7603_rx_loopback_skb(struct mt7603_dev *dev, struct sk_buff *skb) sta = container_of(priv, struct ieee80211_sta, drv_priv); hdr = (struct ieee80211_hdr *)&skb->data[MT_TXD_SIZE]; + if (skb->len < MT_TXD_SIZE + ieee80211_hdrlen(hdr->frame_control)) + goto free; + hwq = wmm_queue_map[IEEE80211_AC_BE]; if (ieee80211_is_data_qos(hdr->frame_control)) { tid = *ieee80211_get_qos_ctl(hdr) & @@ -62,6 +65,19 @@ mt7603_rx_loopback_skb(struct mt7603_dev *dev, struct sk_buff *skb) } else if (ieee80211_is_data(hdr->frame_control)) { skb_set_queue_mapping(skb, IEEE80211_AC_BE); hwq = wmm_queue_map[IEEE80211_AC_BE]; + } else if (ieee80211_is_back_req(hdr->frame_control)) { + struct ieee80211_bar *bar = (struct ieee80211_bar *)hdr; + + if (skb->len < MT_TXD_SIZE + sizeof(*bar)) + goto free; + + tid = (le16_to_cpu(bar->control) & + IEEE80211_BAR_CTRL_TID_INFO_MASK) >> + IEEE80211_BAR_CTRL_TID_INFO_SHIFT; + tid &= IEEE80211_QOS_CTL_TAG1D_MASK; + qid = tid_to_ac[tid]; + hwq = wmm_queue_map[qid]; + skb_set_queue_mapping(skb, qid); } else { skb_pull(skb, MT_TXD_SIZE); if (!ieee80211_is_bufferable_mmpdu(skb)) diff --git a/drivers/net/wireless/mediatek/mt76/mt7615/mcu.c b/drivers/net/wireless/mediatek/mt76/mt7615/mcu.c index ff57ede87f71..aab4303fef65 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7615/mcu.c +++ b/drivers/net/wireless/mediatek/mt76/mt7615/mcu.c @@ -145,6 +145,9 @@ int mt7615_mcu_parse_response(struct mt76_dev *mdev, int cmd, } rxd = (struct mt7615_mcu_rxd *)skb->data; + if (skb->len < sizeof(*rxd)) + return -EMSGSIZE; + if (seq != rxd->seq) return -EAGAIN; @@ -152,9 +155,15 @@ int mt7615_mcu_parse_response(struct mt76_dev *mdev, int cmd, skb_pull(skb, sizeof(*rxd) - 4); ret = *skb->data; } else if (cmd == MCU_EXT_CMD(THERMAL_CTRL)) { + if (skb->len < sizeof(*rxd) + (is_mt7663(mdev) ? 8 : 4)) + return -EMSGSIZE; skb_pull(skb, sizeof(*rxd)); + if (is_mt7663(mdev)) + skb_pull(skb, 4); ret = le32_to_cpu(*(__le32 *)skb->data); } else if (cmd == MCU_EXT_QUERY(RF_REG_ACCESS)) { + if (skb->len < sizeof(*rxd) + 8 + sizeof(__le32)) + return -EMSGSIZE; skb_pull(skb, sizeof(*rxd)); ret = le32_to_cpu(*(__le32 *)&skb->data[8]); } else if (cmd == MCU_UNI_CMD(DEV_INFO_UPDATE) || @@ -165,12 +174,16 @@ int mt7615_mcu_parse_response(struct mt76_dev *mdev, int cmd, cmd == MCU_UNI_CMD(SUSPEND)) { struct mt76_connac_mcu_uni_event *event; + if (skb->len < sizeof(*rxd) + sizeof(*event)) + return -EMSGSIZE; skb_pull(skb, sizeof(*rxd)); event = (struct mt76_connac_mcu_uni_event *)skb->data; ret = le32_to_cpu(event->status); } else if (cmd == MCU_CE_QUERY(REG_READ)) { struct mt76_connac_mcu_reg_event *event; + if (skb->len < sizeof(*rxd) + sizeof(*event)) + return -EMSGSIZE; skb_pull(skb, sizeof(*rxd)); event = (struct mt76_connac_mcu_reg_event *)skb->data; ret = (int)le32_to_cpu(event->val); diff --git a/drivers/net/wireless/mediatek/mt76/mt7615/usb.c b/drivers/net/wireless/mediatek/mt76/mt7615/usb.c index bab7b91f14be..3629e3d9bf47 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7615/usb.c +++ b/drivers/net/wireless/mediatek/mt76/mt7615/usb.c @@ -58,15 +58,22 @@ static void mt7663u_copy(struct mt76_dev *dev, u32 offset, const void *data, int len) { struct mt76_usb *usb = &dev->usb; - int ret, i = 0, batch_len; const u8 *val = data; + int len_aligned; + int batch_len; + int copy_len; + int ret; + int i = 0; - len = round_up(len, 4); + len_aligned = round_up(len, 4); mutex_lock(&usb->usb_ctrl_mtx); - while (i < len) { - batch_len = min_t(int, usb->data_len, len - i); - memcpy(usb->data, val + i, batch_len); + while (i < len_aligned) { + batch_len = min_t(int, usb->data_len, len_aligned - i); + copy_len = min_t(int, batch_len, len - i); + memcpy(usb->data, val + i, copy_len); + if (copy_len < batch_len) + memset(usb->data + copy_len, 0, batch_len - copy_len); ret = __mt76u_vendor_request(dev, MT_VEND_WRITE_EXT, USB_DIR_OUT | USB_TYPE_VENDOR, (offset + i) >> 16, offset + i, diff --git a/drivers/net/wireless/mediatek/mt76/mt76_connac_mac.c b/drivers/net/wireless/mediatek/mt76/mt76_connac_mac.c index 8a8d608dd56e..8481eac8d783 100644 --- a/drivers/net/wireless/mediatek/mt76/mt76_connac_mac.c +++ b/drivers/net/wireless/mediatek/mt76/mt76_connac_mac.c @@ -600,6 +600,7 @@ void mt76_connac2_mac_write_txwi(struct mt76_dev *dev, __le32 *txwi, vif ? &vif->bss_conf : NULL, beacon, multicast); u32 val = MT_TXD6_FIXED_BW; + u8 spe_idx = mt76_connac_spe_idx(mphy->antenna_mask); /* hardware won't add HTC for mgmt/ctrl frame */ txwi[2] |= cpu_to_le32(MT_TXD2_HTC_VLD); @@ -608,13 +609,18 @@ void mt76_connac2_mac_write_txwi(struct mt76_dev *dev, __le32 *txwi, txwi[6] |= cpu_to_le32(val); txwi[3] |= cpu_to_le32(MT_TXD3_BA_DISABLE); - if (!is_connac2(dev)) { - u8 spe_idx = mt76_connac_spe_idx(mphy->antenna_mask); - - if (!spe_idx) - spe_idx = 24 + phy_idx; - txwi[7] |= cpu_to_le32(FIELD_PREP(MT_TXD7_SPE_IDX, spe_idx)); - } + /* Fixed-rate frames (all mgmt, so auth/assoc req too) otherwise + * carry spe_idx 0 and TX 1SS 1T on WF0. Fill spe_idx like the + * other connac generations do, but do NOT touch + * MT_TXD6_SPE_ID_IDX: on connac2 setting it points HW at the + * WTBL and the index below is ignored. + * + * spe_idx 0 is also a valid single-path index (WF0), so only + * take the duplicate fallback when a second path exists. + */ + if (!spe_idx && hweight8(mphy->antenna_mask) > 1) + spe_idx = 24 + phy_idx; + txwi[7] |= cpu_to_le32(FIELD_PREP(MT_TXD7_SPE_IDX, spe_idx)); txwi[7] &= ~cpu_to_le32(MT_TXD7_HW_AMSDU); } diff --git a/drivers/net/wireless/mediatek/mt76/mt76x02_mac.c b/drivers/net/wireless/mediatek/mt76/mt76x02_mac.c index 231685bb62d2..158aa356b710 100644 --- a/drivers/net/wireless/mediatek/mt76/mt76x02_mac.c +++ b/drivers/net/wireless/mediatek/mt76/mt76x02_mac.c @@ -816,9 +816,13 @@ int mt76x02_mac_process_rx(struct mt76x02_dev *dev, struct sk_buff *skb, len = FIELD_GET(MT_RXWI_CTL_MPDU_LEN, ctl); pn_len = FIELD_GET(MT_RXINFO_PN_LEN, rxinfo); if (pn_len) { - int offset = ieee80211_get_hdrlen_from_skb(skb) + pad_len; - u8 *data = skb->data + offset; + unsigned int offset = ieee80211_get_hdrlen_from_skb(skb) + pad_len; + u8 *data; + if (offset + 8 > skb->len) + return -EINVAL; + + data = skb->data + offset; status->iv[0] = data[7]; status->iv[1] = data[6]; status->iv[2] = data[5]; @@ -838,6 +842,9 @@ int mt76x02_mac_process_rx(struct mt76x02_dev *dev, struct sk_buff *skb, } } + if (pad_len + ieee80211_get_hdrlen_from_skb(skb) > skb->len) + return -EINVAL; + mt76x02_remove_hdr_pad(skb, pad_len); if ((rxinfo & MT_RXINFO_BA) && !(rxinfo & MT_RXINFO_NULL)) diff --git a/drivers/net/wireless/mediatek/mt76/mt7915/coredump.c b/drivers/net/wireless/mediatek/mt76/mt7915/coredump.c index 6c7273e5b0bc..db079b274a93 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7915/coredump.c +++ b/drivers/net/wireless/mediatek/mt76/mt7915/coredump.c @@ -345,11 +345,12 @@ static struct mt7915_coredump *mt7915_coredump_build(struct mt7915_dev *dev) mt7915_coredump_fw_stack(dev, dump, exception); /* gather memory content */ - dump_mem = (struct mt7915_coredump_mem *)(buf + sofar); - dump_mem->len = crash_data->memdump_buf_len; - if (coredump_memdump && crash_data->memdump_buf_len) + if (coredump_memdump && crash_data->memdump_buf_len) { + dump_mem = (struct mt7915_coredump_mem *)(buf + sofar); + dump_mem->len = crash_data->memdump_buf_len; memcpy(dump_mem->data, crash_data->memdump_buf, crash_data->memdump_buf_len); + } mutex_unlock(&dev->dump_mutex); diff --git a/drivers/net/wireless/mediatek/mt76/mt7915/eeprom.c b/drivers/net/wireless/mediatek/mt76/mt7915/eeprom.c index fe7b29ebc0bf..145d14a1012d 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7915/eeprom.c +++ b/drivers/net/wireless/mediatek/mt76/mt7915/eeprom.c @@ -111,6 +111,12 @@ mt7915_eeprom_load_default(struct mt7915_dev *dev) goto out; } + if (fw->size < mt7915_eeprom_size(dev)) { + dev_err(dev->mt76.dev, "Invalid default bin size\n"); + ret = -EINVAL; + goto out; + } + memcpy(eeprom, fw->data, mt7915_eeprom_size(dev)); dev->flash_mode = true; diff --git a/drivers/net/wireless/mediatek/mt76/mt7915/init.c b/drivers/net/wireless/mediatek/mt76/mt7915/init.c index c8e389db63a7..358c45acf79b 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7915/init.c +++ b/drivers/net/wireless/mediatek/mt76/mt7915/init.c @@ -200,11 +200,17 @@ static void mt7915_unregister_thermal(struct mt7915_phy *phy) { struct wiphy *wiphy = phy->mt76->hw->wiphy; + if (phy->tzone) { + devm_thermal_of_zone_unregister(phy->dev->mt76.dev, phy->tzone); + phy->tzone = NULL; + } + if (!phy->cdev) return; sysfs_remove_link(&wiphy->dev.kobj, "cooling_device"); thermal_cooling_device_unregister(phy->cdev); + phy->cdev = NULL; } static int mt7915_thermal_init(struct mt7915_phy *phy) @@ -238,8 +244,8 @@ static int mt7915_thermal_init(struct mt7915_phy *phy) if (IS_ERR(phy->tzone)) { if (PTR_ERR(phy->tzone) != -ENODEV) dev_warn(phy->dev->mt76.dev, - "failed to register thermal zone: %ld\n", - PTR_ERR(phy->tzone)); + "failed to register thermal zone %d: %ld\n", + phy->mt76->band_idx, PTR_ERR(phy->tzone)); phy->tzone = NULL; } @@ -248,7 +254,12 @@ static int mt7915_thermal_init(struct mt7915_phy *phy) hwmon = devm_hwmon_device_register_with_groups(&wiphy->dev, name, phy, mt7915_hwmon_groups); - return PTR_ERR_OR_ZERO(hwmon); + if (IS_ERR(hwmon)) { + mt7915_unregister_thermal(phy); + return PTR_ERR(hwmon); + } + + return 0; } static void mt7915_led_set_config(struct led_classdev *led_cdev, diff --git a/drivers/net/wireless/mediatek/mt76/mt7915/main.c b/drivers/net/wireless/mediatek/mt76/mt7915/main.c index a03d89aabe80..556f8948abac 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7915/main.c +++ b/drivers/net/wireless/mediatek/mt76/mt7915/main.c @@ -273,9 +273,9 @@ static int mt7915_add_interface(struct ieee80211_hw *hw, mt7915_init_bitrate_mask(vif); memset(&mvif->cap, -1, sizeof(mvif->cap)); + rcu_assign_pointer(dev->mt76.wcid[idx], &mvif->sta.wcid); mt7915_mcu_add_bss_info(phy, vif, true); mt7915_mcu_add_sta(dev, vif, NULL, CONN_STATE_PORT_SECURE, true); - rcu_assign_pointer(dev->mt76.wcid[idx], &mvif->sta.wcid); mutex_unlock(&dev->mt76.mutex); diff --git a/drivers/net/wireless/mediatek/mt76/mt7921/main.c b/drivers/net/wireless/mediatek/mt76/mt7921/main.c index 3577c4cebb2e..09574d4417cd 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7921/main.c +++ b/drivers/net/wireless/mediatek/mt76/mt7921/main.c @@ -652,9 +652,9 @@ static int mt7921_config(struct ieee80211_hw *hw, int radio_idx, u32 changed) } if (changed & IEEE80211_CONF_CHANGE_MONITOR) { - ieee80211_iterate_active_interfaces(hw, - IEEE80211_IFACE_ITER_RESUME_ALL, - mt7921_sniffer_interface_iter, dev); + ieee80211_iterate_active_interfaces_mtx(hw, + IEEE80211_IFACE_ITER_RESUME_ALL, + mt7921_sniffer_interface_iter, dev); } out: @@ -668,12 +668,8 @@ static void mt7921_configure_filter(struct ieee80211_hw *hw, unsigned int *total_flags, u64 multicast) { -#define MT7921_FILTER_FCSFAIL BIT(2) -#define MT7921_FILTER_CONTROL BIT(5) -#define MT7921_FILTER_OTHER_BSS BIT(6) -#define MT7921_FILTER_ENABLE BIT(31) - struct mt792x_dev *dev = mt792x_hw_dev(hw); + struct mt792x_phy *phy = mt792x_hw_phy(hw); u32 flags = MT7921_FILTER_ENABLE; #define MT7921_FILTER(_fif, _type) do { \ @@ -685,6 +681,8 @@ static void mt7921_configure_filter(struct ieee80211_hw *hw, MT7921_FILTER(FIF_CONTROL, CONTROL); MT7921_FILTER(FIF_OTHER_BSS, OTHER_BSS); + phy->rxfilter = flags; + mt792x_mutex_acquire(dev); mt7921_mcu_set_rxfilter(dev, flags, 0, 0); mt792x_mutex_release(dev); @@ -865,6 +863,12 @@ int mt7921_mac_sta_event(struct mt76_dev *mdev, struct ieee80211_vif *vif, if (sta->aid > MT7921_MAX_AID) return -ENOENT; + if (mvif->roc_join_held && !sta->tdls && + (ev == MT76_STA_EVENT_AUTHORIZE || ev == MT76_STA_EVENT_DISASSOC)) { + mvif->roc_join_held = false; + mt7921_abort_roc(mvif->phy, mvif); + } + if (ev != MT76_STA_EVENT_ASSOC) return 0; @@ -906,6 +910,7 @@ void mt7921_mac_sta_remove(struct mt76_dev *mdev, struct ieee80211_vif *vif, struct mt792x_vif *mvif = (struct mt792x_vif *)vif->drv_priv; mvif->wep_sta = NULL; + mvif->roc_join_held = false; ewma_rssi_init(&mvif->bss_conf.rssi); if (!sta->tdls) mt76_connac_mcu_uni_add_bss(&dev->mphy, vif, @@ -1156,10 +1161,10 @@ static int mt7921_suspend(struct ieee80211_hw *hw, mt792x_mutex_acquire(dev); clear_bit(MT76_STATE_RUNNING, &phy->mt76->state); - ieee80211_iterate_active_interfaces(hw, - IEEE80211_IFACE_ITER_RESUME_ALL, - mt7921_mcu_set_suspend_iter, - &dev->mphy); + ieee80211_iterate_active_interfaces_mtx(hw, + IEEE80211_IFACE_ITER_RESUME_ALL, + mt7921_mcu_set_suspend_iter, + &dev->mphy); mt792x_mutex_release(dev); @@ -1174,10 +1179,10 @@ static int mt7921_resume(struct ieee80211_hw *hw) mt792x_mutex_acquire(dev); set_bit(MT76_STATE_RUNNING, &phy->mt76->state); - ieee80211_iterate_active_interfaces(hw, - IEEE80211_IFACE_ITER_RESUME_ALL, - mt76_connac_mcu_set_suspend_iter, - &dev->mphy); + ieee80211_iterate_active_interfaces_mtx(hw, + IEEE80211_IFACE_ITER_RESUME_ALL, + mt76_connac_mcu_set_suspend_iter, + &dev->mphy); ieee80211_queue_delayed_work(hw, &phy->mt76->mac_work, MT792x_WATCHDOG_TIME); @@ -1448,6 +1453,16 @@ static void mt7921_mgd_complete_tx(struct ieee80211_hw *hw, { struct mt792x_vif *mvif = (struct mt792x_vif *)vif->drv_priv; + /* Keep the join ROC until the station is authorized, so that it + * covers the 4-way handshake. mt7921_mac_sta_event() releases it. + */ + if (vif->type == NL80211_IFTYPE_STATION && info->success && + (info->subtype == IEEE80211_STYPE_ASSOC_REQ || + info->subtype == IEEE80211_STYPE_REASSOC_REQ)) { + mvif->roc_join_held = true; + return; + } + mt7921_abort_roc(mvif->phy, mvif); } diff --git a/drivers/net/wireless/mediatek/mt76/mt7921/mcu.c b/drivers/net/wireless/mediatek/mt76/mt7921/mcu.c index 40546005c743..fec5205b33ca 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 "regd.h" #include "mcu.h" @@ -1231,7 +1232,7 @@ int mt7921_mcu_config_sniffer(struct mt792x_vif *vif, .len = cpu_to_le16(sizeof(req.tlv)), .control_ch = chandef->chan->hw_value, .center_ch = ieee80211_frequency_to_channel(freq1), - .drop_err = 1, + .drop_err = !(vif->phy->rxfilter & MT7921_FILTER_FCSFAIL), }, }; if (chandef->chan->band < ARRAY_SIZE(ch_band)) @@ -1359,6 +1360,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; @@ -1368,8 +1370,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/mt7921/mt7921.h b/drivers/net/wireless/mediatek/mt76/mt7921/mt7921.h index fb8654b7c5e7..f7ed11353d28 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7921/mt7921.h +++ b/drivers/net/wireless/mediatek/mt76/mt7921/mt7921.h @@ -7,6 +7,11 @@ #include "../mt792x.h" #include "regs.h" +#define MT7921_FILTER_FCSFAIL BIT(2) +#define MT7921_FILTER_CONTROL BIT(5) +#define MT7921_FILTER_OTHER_BSS BIT(6) +#define MT7921_FILTER_ENABLE BIT(31) + #define MT7921_MAX_AID 20 #define MT7921_TX_RING_SIZE 2048 diff --git a/drivers/net/wireless/mediatek/mt76/mt7921/pci.c b/drivers/net/wireless/mediatek/mt76/mt7921/pci.c index 56a914aaa81e..f87c44f2a8b6 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7921/pci.c +++ b/drivers/net/wireless/mediatek/mt76/mt7921/pci.c @@ -375,6 +375,7 @@ static int mt7921_pci_probe(struct pci_dev *pdev, } map->rx.wm2_complete_mask = 0; + map->rx.all_complete_mask &= ~MT_INT_RX_DONE_WM2; dev->irq_map = map; } diff --git a/drivers/net/wireless/mediatek/mt76/mt7921/pci_mac.c b/drivers/net/wireless/mediatek/mt76/mt7921/pci_mac.c index 98b3469ac597..d5c33a0d409c 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7921/pci_mac.c +++ b/drivers/net/wireless/mediatek/mt76/mt7921/pci_mac.c @@ -57,7 +57,9 @@ int mt7921e_mac_reset(struct mt792x_dev *dev) { int i, err; - mt792xe_mcu_drv_pmctrl(dev); + err = mt792xe_mcu_drv_pmctrl(dev); + if (err) + return err; mt76_connac_free_pending_tx_skbs(&dev->pm, NULL); diff --git a/drivers/net/wireless/mediatek/mt76/mt7921/regd.c b/drivers/net/wireless/mediatek/mt76/mt7921/regd.c index fcdeb65cd8ef..699617d9e48f 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7921/regd.c +++ b/drivers/net/wireless/mediatek/mt76/mt7921/regd.c @@ -28,6 +28,21 @@ bool mt7921_regd_clc_supported(struct mt792x_dev *dev) return true; } +static bool +mt7921_regd_dt_has_channel(struct device_node *band_np, + struct ieee80211_channel *ch) +{ + struct device_node *chan_np; + + if (!band_np) + return false; + + chan_np = mt76_find_channel_node(band_np, ch); + of_node_put(chan_np); + + return !!chan_np; +} + static void mt7921_regd_channel_update(struct wiphy *wiphy, struct mt792x_dev *dev) { @@ -43,14 +58,14 @@ mt7921_regd_channel_update(struct wiphy *wiphy, struct mt792x_dev *dev) sband = wiphy->bands[NL80211_BAND_5GHZ]; if (!sband) - return; + goto out; band_np = np ? of_get_child_by_name(np, "txpower-5g") : 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))) { + if (np && !mt7921_regd_dt_has_channel(band_np, ch)) { ch->flags |= IEEE80211_CHAN_DISABLED; continue; } @@ -59,17 +74,18 @@ mt7921_regd_channel_update(struct wiphy *wiphy, struct mt792x_dev *dev) 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))) { + if (np && !mt7921_regd_dt_has_channel(band_np, ch)) { ch->flags |= IEEE80211_CHAN_DISABLED; continue; } @@ -81,6 +97,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); } int __mt7921_mcu_regd_update(struct mt792x_dev *dev, u8 *alpha2, diff --git a/drivers/net/wireless/mediatek/mt76/mt7925/init.c b/drivers/net/wireless/mediatek/mt76/mt7925/init.c index cd22fcc021b1..8c3049b66a85 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7925/init.c +++ b/drivers/net/wireless/mediatek/mt76/mt7925/init.c @@ -270,6 +270,8 @@ int mt7925_register_device(struct mt792x_dev *dev) INIT_WORK(&dev->reset_work, mt7925_mac_reset_work); INIT_WORK(&dev->init_work, mt7925_init_work); + INIT_WORK(&dev->nan_deferred_work, mt7925_nan_deferred_work); + spin_lock_init(&dev->nan_deferred_lock); INIT_WORK(&dev->phy.roc_work, mt7925_roc_work); timer_setup(&dev->phy.roc_timer, mt792x_roc_timer, 0); diff --git a/drivers/net/wireless/mediatek/mt76/mt7925/mac.c b/drivers/net/wireless/mediatek/mt76/mt7925/mac.c index 2e34e950e111..7af996abe294 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7925/mac.c +++ b/drivers/net/wireless/mediatek/mt76/mt7925/mac.c @@ -1503,7 +1503,7 @@ mt7925_vif_connect_iter(void *priv, u8 *mac, true, NULL); mt7925_mcu_sta_update(dev, NULL, vif, &mvif->sta.deflink, true, - MT76_STA_INFO_STATE_NONE); + MT76_STA_INFO_STATE_NONE, NULL); mt7925_mcu_uni_add_beacon_offload(dev, hw, vif, true); } } diff --git a/drivers/net/wireless/mediatek/mt76/mt7925/main.c b/drivers/net/wireless/mediatek/mt76/mt7925/main.c index e3e9e0be558e..15d95ad32636 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7925/main.c +++ b/drivers/net/wireless/mediatek/mt76/mt7925/main.c @@ -840,9 +840,9 @@ static int mt7925_config(struct ieee80211_hw *hw, int radio_idx, u32 changed) } if (changed & IEEE80211_CONF_CHANGE_MONITOR) { - ieee80211_iterate_active_interfaces(hw, - IEEE80211_IFACE_ITER_RESUME_ALL, - mt7925_sniffer_interface_iter, dev); + ieee80211_iterate_active_interfaces_mtx(hw, + IEEE80211_IFACE_ITER_RESUME_ALL, + mt7925_sniffer_interface_iter, dev); } out: @@ -856,11 +856,8 @@ static void mt7925_configure_filter(struct ieee80211_hw *hw, unsigned int *total_flags, u64 multicast) { -#define MT7925_FILTER_FCSFAIL BIT(2) -#define MT7925_FILTER_CONTROL BIT(5) -#define MT7925_FILTER_OTHER_BSS BIT(6) -#define MT7925_FILTER_ENABLE BIT(31) struct mt792x_dev *dev = mt792x_hw_dev(hw); + struct mt792x_phy *phy = mt792x_hw_phy(hw); u32 flags = MT7925_FILTER_ENABLE; #define MT7925_FILTER(_fif, _type) do { \ @@ -872,6 +869,8 @@ static void mt7925_configure_filter(struct ieee80211_hw *hw, MT7925_FILTER(FIF_CONTROL, CONTROL); MT7925_FILTER(FIF_OTHER_BSS, OTHER_BSS); + phy->rxfilter = flags; + mt792x_mutex_acquire(dev); mt7925_mcu_set_rxfilter(dev, flags, 0, 0); mt792x_mutex_release(dev); @@ -964,6 +963,21 @@ static int mt7925_mac_link_sta_add(struct mt76_dev *mdev, link_conf = mt792x_vif_to_bss_conf(vif, link_id); + /* NAN_DATA (NDI) peers skip association - fill link_sta caps + * from sband and push BSS_INFO with correct phymode + RLM. + */ + if (vif->type == NL80211_IFTYPE_NAN_DATA) { + struct ieee80211_chanctx_conf *nan_ctx; + + nan_ctx = mt7925_nan_seed_link_sta(dev, link_sta); + mconf->mt76.ctx = nan_ctx; + + ret = mt7925_mcu_add_bss_info(&dev->phy, nan_ctx, + link_conf, link_sta, true); + if (ret) + goto out_pm; + } + /* should update bss info before STA add */ if (vif->type == NL80211_IFTYPE_STATION && !link_sta->sta->tdls) { struct mt792x_link_sta *mlink_bc; @@ -991,7 +1005,7 @@ static int mt7925_mac_link_sta_add(struct mt76_dev *mdev, link_sta == mlink->pri_link) { ret = mt7925_mcu_sta_update(dev, link_sta, vif, mlink, true, - MT76_STA_INFO_STATE_NONE); + MT76_STA_INFO_STATE_NONE, NULL); if (ret) goto out_pm; } else if (ieee80211_vif_is_mld(vif) && @@ -1013,19 +1027,19 @@ static int mt7925_mac_link_sta_add(struct mt76_dev *mdev, ret = mt7925_mcu_sta_update(dev, mlink->pri_link, vif, pri_mlink, true, - MT76_STA_INFO_STATE_ASSOC); + MT76_STA_INFO_STATE_ASSOC, mlink); if (ret) goto out_pm; ret = mt7925_mcu_sta_update(dev, link_sta, vif, mlink, true, - MT76_STA_INFO_STATE_ASSOC); + MT76_STA_INFO_STATE_ASSOC, mlink); if (ret) goto out_pm; } else { ret = mt7925_mcu_sta_update(dev, link_sta, vif, mlink, true, - MT76_STA_INFO_STATE_NONE); + MT76_STA_INFO_STATE_NONE, NULL); if (ret) goto out_pm; } @@ -1233,7 +1247,7 @@ static void mt7925_mac_link_sta_assoc(struct mt76_dev *mdev, memset(mlink->airtime_ac, 0, sizeof(mlink->airtime_ac)); mt7925_mcu_sta_update(dev, link_sta, vif, mlink, true, - MT76_STA_INFO_STATE_ASSOC); + MT76_STA_INFO_STATE_ASSOC, NULL); mt792x_mutex_release(dev); } @@ -1243,6 +1257,13 @@ int mt7925_mac_sta_event(struct mt76_dev *mdev, struct ieee80211_vif *vif, { struct mt792x_dev *dev = container_of(mdev, struct mt792x_dev, mt76); struct ieee80211_link_sta *link_sta = &sta->deflink; + struct mt792x_vif *mvif = (struct mt792x_vif *)vif->drv_priv; + + if (mvif->roc_join_held && !sta->tdls && + (ev == MT76_STA_EVENT_AUTHORIZE || ev == MT76_STA_EVENT_DISASSOC)) { + mvif->roc_join_held = false; + mt7925_abort_roc(mvif->phy, &mvif->bss_conf); + } switch (ev) { case MT76_STA_EVENT_ASSOC: @@ -1293,7 +1314,7 @@ static void mt7925_mac_link_sta_remove(struct mt76_dev *mdev, mt76_connac_pm_wake(&dev->mphy, &dev->pm); mt7925_mcu_sta_update(dev, link_sta, vif, mlink, false, - MT76_STA_INFO_STATE_NONE); + MT76_STA_INFO_STATE_NONE, NULL); mt7925_mac_wtbl_update(dev, mlink->wcid.idx, MT_WTBL_UPDATE_ADM_COUNT_CLEAR); @@ -1438,6 +1459,7 @@ void mt7925_mac_sta_remove(struct mt76_dev *mdev, struct ieee80211_vif *vif, if (vif->type == NL80211_IFTYPE_STATION) { mvif->wep_sta = NULL; + mvif->roc_join_held = false; ewma_rssi_init(&mvif->bss_conf.rssi); } @@ -1717,10 +1739,10 @@ static int mt7925_suspend(struct ieee80211_hw *hw, mt792x_mutex_acquire(dev); clear_bit(MT76_STATE_RUNNING, &phy->mt76->state); - ieee80211_iterate_active_interfaces(hw, - IEEE80211_IFACE_ITER_RESUME_ALL, - mt7925_mcu_set_suspend_iter, - &dev->mphy); + ieee80211_iterate_active_interfaces_mtx(hw, + IEEE80211_IFACE_ITER_RESUME_ALL, + mt7925_mcu_set_suspend_iter, + &dev->mphy); mt792x_mutex_release(dev); @@ -1735,10 +1757,10 @@ static int mt7925_resume(struct ieee80211_hw *hw) mt792x_mutex_acquire(dev); set_bit(MT76_STATE_RUNNING, &phy->mt76->state); - ieee80211_iterate_active_interfaces(hw, - IEEE80211_IFACE_ITER_RESUME_ALL, - mt7925_mcu_set_suspend_iter, - &dev->mphy); + ieee80211_iterate_active_interfaces_mtx(hw, + IEEE80211_IFACE_ITER_RESUME_ALL, + mt7925_mcu_set_suspend_iter, + &dev->mphy); ieee80211_queue_delayed_work(hw, &phy->mt76->mac_work, MT792x_WATCHDOG_TIME); @@ -1964,7 +1986,7 @@ mt7925_start_ap(struct ieee80211_hw *hw, struct ieee80211_vif *vif, err = mt7925_mcu_sta_update(dev, NULL, vif, &mvif->sta.deflink, true, - MT76_STA_INFO_STATE_NONE); + MT76_STA_INFO_STATE_NONE, NULL); out: mt792x_mutex_release(dev); @@ -2090,6 +2112,19 @@ static void mt7925_mgd_complete_tx(struct ieee80211_hw *hw, { struct mt792x_vif *mvif = (struct mt792x_vif *)vif->drv_priv; + /* Keep the join ROC until the station is authorized, so that it + * covers the 4-way handshake. mt7925_mac_sta_event() releases it. + * On MLD, the active ROC is the MLO ROC, which must be released + * before the link activation work sets its own. + */ + if (vif->type == NL80211_IFTYPE_STATION && !ieee80211_vif_is_mld(vif) && + info->success && + (info->subtype == IEEE80211_STYPE_ASSOC_REQ || + info->subtype == IEEE80211_STYPE_REASSOC_REQ)) { + mvif->roc_join_held = true; + return; + } + mt7925_abort_roc(mvif->phy, &mvif->bss_conf); } @@ -2109,7 +2144,7 @@ static void mt7925_vif_cfg_changed(struct ieee80211_hw *hw, if (changed & BSS_CHANGED_ASSOC) { mt7925_mcu_sta_update(dev, NULL, vif, &mvif->sta.deflink, true, - MT76_STA_INFO_STATE_ASSOC); + MT76_STA_INFO_STATE_ASSOC, NULL); mt7925_mcu_set_beacon_filter(dev, vif, vif->cfg.assoc); if (ieee80211_vif_is_mld(vif)) @@ -2601,26 +2636,18 @@ static int mt7925_start_nan(struct ieee80211_hw *hw, cfg80211_chandef_create(&link_conf->chanreq.oper, chan, NL80211_CHAN_NO_HT); - err = mt7925_mcu_add_bss_info(&dev->phy, NULL, link_conf, - NULL, true); + err = mt7925_mcu_add_bss_info(&dev->phy, NULL, + link_conf, NULL, true); if (err < 0) goto out; - dev->nan_vif = vif; - - err = mt7925_nan_set_nmi_addr(dev, vif->addr); - if (err) - goto rollback_bss; - err = mt7925_nan_enable(vif, dev, conf); - if (err) - goto rollback_bss; - - goto out; + if (err) { + mt7925_mcu_add_bss_info(&dev->phy, NULL, link_conf, NULL, false); + goto out; + } -rollback_bss: - dev->nan_vif = NULL; - mt7925_mcu_add_bss_info(&dev->phy, NULL, link_conf, NULL, false); + err = mt7925_nan_update_phy_setting(dev); out: mt792x_mutex_release(dev); @@ -2635,6 +2662,13 @@ static int mt7925_stop_nan(struct ieee80211_hw *hw, struct mt792x_dev *dev = mt792x_hw_dev(hw); int err, ret; + /* Drop a deferred event queued just before stop so a stale cluster_id + * cannot leak into a restart; the work re-checks liveness anyway. + */ + spin_lock_bh(&dev->nan_deferred_lock); + dev->nan_deferred_pending = 0; + spin_unlock_bh(&dev->nan_deferred_lock); + mt792x_mutex_acquire(dev); err = mt7925_nan_disable(vif, dev); @@ -2644,9 +2678,6 @@ static int mt7925_stop_nan(struct ieee80211_hw *hw, if (!err) err = ret; - if (dev->nan_vif == vif) - dev->nan_vif = NULL; - mt792x_mutex_release(dev); return err; diff --git a/drivers/net/wireless/mediatek/mt76/mt7925/mcu.c b/drivers/net/wireless/mediatek/mt76/mt7925/mcu.c index fa29c486a455..ebf454bf1eda 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7925/mcu.c +++ b/drivers/net/wireless/mediatek/mt76/mt7925/mcu.c @@ -1914,11 +1914,9 @@ mt7925_mcu_sta_phy_tlv(struct sk_buff *skb, phy = (struct sta_rec_phy *)tlv; if (mt7925_vif_is_nan(vif)) { - enum nl80211_band band = chandef->chan ? chandef->chan->band - : NL80211_BAND_2GHZ; phy->phy_type = PHY_TYPE_BIT_OFDM | PHY_TYPE_BIT_ERP; phy->phy_type |= mt76_connac_get_phy_mode_v2(mvif->phy->mt76, vif, - band, + NL80211_BAND_5GHZ, link_sta); } else { phy->phy_type = mt76_connac_get_phy_mode_v2(mvif->phy->mt76, vif, @@ -2003,7 +2001,11 @@ mt7925_mcu_sta_rate_ctrl_tlv(struct sk_buff *skb, ra_info = (struct sta_rec_ra_info *)tlv; if (mt7925_vif_is_nan(vif)) - band = chandef->chan ? chandef->chan->band : NL80211_BAND_2GHZ; + /* NAN is OFDM-only per spec; borrow the 5 GHz band lookup to + * avoid PHY_TYPE_BIT_HR_DSSS/CCK bits being added to phy_type. + * NAN interfaces have no chanctx, so chandef->chan is always NULL. + */ + band = NL80211_BAND_5GHZ; else band = chandef->chan->band; @@ -2063,14 +2065,18 @@ mt7925_mcu_sta_mld_tlv(struct sk_buff *skb, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct mt792x_bss_conf *mconf, - struct mt792x_link_sta *mlink) + struct mt792x_link_sta *mlink, + struct mt792x_link_sta *pending) { struct mt792x_vif *mvif = (struct mt792x_vif *)vif->drv_priv; struct mt792x_sta *msta = (struct mt792x_sta *)sta->drv_priv; struct mt792x_dev *dev = mvif->phy->dev; + unsigned long valid = msta->valid_links; struct mt792x_bss_conf *mconf_pri; struct sta_rec_mld *mld; + unsigned int link_id; struct tlv *tlv; + u8 max_links; u8 cnt = 0; /* Primary link always uses driver's deflink WCID. */ @@ -2099,11 +2105,38 @@ mt7925_mcu_sta_mld_tlv(struct sk_buff *skb, mld->link[cnt].wlan_id = cpu_to_le16(msta->deflink.wcid.idx); mld->link[cnt++].bss_idx = mconf_pri->mt76.idx; - /* Optionally encode the currently-updated secondary link. */ - if (mlink && mlink != &msta->deflink && mconf) { - mld->secondary_id = cpu_to_le16(mlink->wcid.idx); - mld->link[cnt].wlan_id = cpu_to_le16(mlink->wcid.idx); - mld->link[cnt++].bss_idx = mconf->mt76.idx; + max_links = ARRAY_SIZE(mld->link); + + /* A link being added is not set in msta->valid_links yet */ + if (pending && pending != &msta->deflink) + valid |= BIT(pending->wcid.link_id); + + for_each_set_bit(link_id, &valid, IEEE80211_MLD_MAX_NUM_LINKS) { + struct mt792x_link_sta *mlink_sec; + struct mt792x_bss_conf *mconf_sec; + + if (cnt == max_links) + break; + + if (link_id == msta->deflink_id) + continue; + + mlink_sec = mt792x_sta_to_link(msta, link_id); + if (!mlink_sec && pending && link_id == pending->wcid.link_id) + mlink_sec = pending; + if (!mlink_sec || mlink_sec == &msta->deflink) + continue; + + mconf_sec = rcu_dereference_protected(mvif->link_conf[link_id], + lockdep_is_held(&dev->mt76.mutex)); + if (!mconf_sec) + continue; + + if (cnt == 1) + mld->secondary_id = cpu_to_le16(mlink_sec->wcid.idx); + + mld->link[cnt].wlan_id = cpu_to_le16(mlink_sec->wcid.idx); + mld->link[cnt++].bss_idx = mconf_sec->mt76.idx; } mld->link_num = cnt; @@ -2122,7 +2155,8 @@ mt7925_mcu_sta_remove_tlv(struct sk_buff *skb) static int mt7925_mcu_sta_cmd(struct mt76_phy *phy, - struct mt76_sta_cmd_info *info) + struct mt76_sta_cmd_info *info, + struct mt792x_link_sta *pending) { struct mt792x_vif *mvif = (struct mt792x_vif *)info->vif->drv_priv; struct mt76_dev *dev = phy->dev; @@ -2163,7 +2197,7 @@ mt7925_mcu_sta_cmd(struct mt76_phy *phy, if (info->state != MT76_STA_INFO_STATE_NONE) { mt7925_mcu_sta_mld_tlv(skb, info->vif, info->link_sta->sta, - mconf, mlink); + mconf, mlink, pending); mt7925_mcu_sta_eht_mld_tlv(skb, info->vif, info->link_sta->sta); } @@ -2188,7 +2222,8 @@ int mt7925_mcu_sta_update(struct mt792x_dev *dev, struct ieee80211_vif *vif, struct mt792x_link_sta *mlink, bool enable, - enum mt76_sta_info_state state) + enum mt76_sta_info_state state, + struct mt792x_link_sta *pending) { struct mt792x_vif *mvif = (struct mt792x_vif *)vif->drv_priv; int rssi = -ewma_rssi_read(&mvif->bss_conf.rssi); @@ -2206,7 +2241,7 @@ int mt7925_mcu_sta_update(struct mt792x_dev *dev, info.wcid = &mlink->wcid; info.newly = state != MT76_STA_INFO_STATE_ASSOC; - return mt7925_mcu_sta_cmd(&dev->mphy, &info); + return mt7925_mcu_sta_cmd(&dev->mphy, &info, pending); } int mt7925_mcu_set_beacon_filter(struct mt792x_dev *dev, @@ -2354,7 +2389,7 @@ int mt7925_mcu_config_sniffer(struct mt792x_vif *vif, .len = cpu_to_le16(sizeof(req.tlv)), .control_ch = chandef->chan->hw_value, .center_ch = ieee80211_frequency_to_channel(freq1), - .drop_err = 1, + .drop_err = !(vif->phy->rxfilter & MT7925_FILTER_FCSFAIL), }, }; @@ -2847,7 +2882,7 @@ mt7925_mcu_bss_bmc_tlv(struct sk_buff *skb, struct mt792x_phy *phy, bmc = (struct bss_rate_tlv *)tlv; if (mt7925_vif_is_nan(vif)) - band = chandef->chan ? chandef->chan->band : NL80211_BAND_2GHZ; + band = NL80211_BAND_5GHZ; else band = chandef->chan->band; diff --git a/drivers/net/wireless/mediatek/mt76/mt7925/mt7925.h b/drivers/net/wireless/mediatek/mt76/mt7925/mt7925.h index 321e732347f2..ef72b50e1a7c 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7925/mt7925.h +++ b/drivers/net/wireless/mediatek/mt76/mt7925/mt7925.h @@ -7,6 +7,11 @@ #include "../mt792x.h" #include "regs.h" +#define MT7925_FILTER_FCSFAIL BIT(2) +#define MT7925_FILTER_CONTROL BIT(5) +#define MT7925_FILTER_OTHER_BSS BIT(6) +#define MT7925_FILTER_ENABLE BIT(31) + #define MT7925_BEACON_RATES_TBL 25 #define MT7925_TX_RING_SIZE 2048 @@ -286,7 +291,8 @@ int mt7925_mcu_sta_update(struct mt792x_dev *dev, struct ieee80211_vif *vif, struct mt792x_link_sta *mlink, bool enable, - enum mt76_sta_info_state state); + enum mt76_sta_info_state state, + struct mt792x_link_sta *pending); int mt7925_mcu_set_chan_info(struct mt792x_phy *phy, u16 tag); int mt7925_mcu_set_tx(struct mt792x_dev *dev, struct ieee80211_bss_conf *bss_conf); int mt7925_mcu_set_eeprom(struct mt792x_dev *dev); @@ -361,6 +367,7 @@ void mt7925_mcu_set_suspend_iter(void *priv, u8 *mac, void mt7925_connac_mcu_set_suspend_iter(void *priv, u8 *mac, struct ieee80211_vif *vif); void mt7925_set_ipv6_ns_work(struct work_struct *work); +void mt7925_nan_deferred_work(struct work_struct *work); int mt7925_mcu_set_sniffer(struct mt792x_dev *dev, struct ieee80211_vif *vif, bool enable); diff --git a/drivers/net/wireless/mediatek/mt76/mt7925/nan.c b/drivers/net/wireless/mediatek/mt76/mt7925/nan.c index d260e803d056..ce2571832c08 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7925/nan.c +++ b/drivers/net/wireless/mediatek/mt76/mt7925/nan.c @@ -32,8 +32,6 @@ static void mt7925_nan_set_5g_channel(struct mt792x_dev *dev, if (!mt7925_regd_is_valid_channel(dev, NL80211_BAND_5GHZ, chan)) return; - req->config_support_5g = 1; - req->support_5g_val = 1; req->config_5g_channel = 1; if (chan->hw_value == NAN_5G_LOW_DISC_CHANNEL) @@ -44,73 +42,6 @@ static void mt7925_nan_set_5g_channel(struct mt792x_dev *dev, req->channel_5g_val = cpu_to_le32(ch5g); } -static void mt7925_nan_set_2g_support(struct mt7925_nan_enable_req_tlv *req, - struct cfg80211_nan_conf *conf) -{ - if (!conf->band_cfgs[NL80211_BAND_2GHZ].chan) - return; - - req->config_2dot4g_support = 1; - req->support_2dot4g_val = 1; -} - -static void mt7925_nan_set_cluster_id(struct mt7925_nan_enable_req_tlv *req, - const u8 *cluster_id) -{ - if (!cluster_id) - return; - - req->cluster_high = cpu_to_le16(cluster_id[4] | cluster_id[5] << 8); - req->cluster_low = cpu_to_le16((u16)cluster_id[3]); -} - -static void mt7925_nan_set_dw_interval(struct mt7925_nan_enable_req_tlv *req, - struct cfg80211_nan_conf *conf) -{ - if (conf->band_cfgs[NL80211_BAND_2GHZ].awake_dw_interval > 0) { - req->config_dw.config_2dot4g_dw_band = 1; - req->config_dw.dw_2dot4g_interval_val = - cpu_to_le32(conf->band_cfgs[NL80211_BAND_2GHZ].awake_dw_interval); - } - - if (conf->band_cfgs[NL80211_BAND_5GHZ].awake_dw_interval > 0) { - req->config_dw.config_5g_dw_band = 1; - req->config_dw.dw_5g_interval_val = - cpu_to_le32(conf->band_cfgs[NL80211_BAND_5GHZ].awake_dw_interval); - } -} - -static void mt7925_nan_set_disc_beacon(struct mt7925_nan_enable_req_tlv *req, - struct cfg80211_nan_conf *conf) -{ - if (conf->discovery_beacon_interval > 0) { - req->config_2dot4g_beacons = true; - req->beacon_2dot4g_val = conf->discovery_beacon_interval; - } -} - -static void mt7925_nan_set_rssi_thresholds(struct mt7925_nan_enable_req_tlv *req, - struct cfg80211_nan_conf *conf) -{ - if (conf->band_cfgs[NL80211_BAND_2GHZ].chan) { - req->config_2dot4g_rssi_close = 1; - req->rssi_close_2dot4g_val = - abs(conf->band_cfgs[NL80211_BAND_2GHZ].rssi_close); - req->config_2dot4g_rssi_middle = 1; - req->rssi_middle_2dot4g_val = - abs(conf->band_cfgs[NL80211_BAND_2GHZ].rssi_middle); - } - - if (conf->band_cfgs[NL80211_BAND_5GHZ].chan) { - req->config_5g_rssi_close = 1; - req->rssi_close_5g_val = - abs(conf->band_cfgs[NL80211_BAND_5GHZ].rssi_close); - req->config_5g_rssi_middle = 1; - req->rssi_middle_5g_val = - abs(conf->band_cfgs[NL80211_BAND_5GHZ].rssi_middle); - } -} - static void mt7925_nan_set_scan_params(struct mt7925_nan_enable_req_tlv *req, struct cfg80211_nan_conf *conf) { @@ -144,101 +75,6 @@ mt7925_nan_update_conf(struct mt792x_vif *mvif, memcpy(mvif->nan.conf.cluster_id, conf->cluster_id, ETH_ALEN); } -int mt7925_nan_set_nmi_addr(struct mt792x_dev *dev, const u8 *addr) -{ - struct mt76_dev *mdev; - struct { - u8 rsv[4]; - struct mt7925_nan_nmi_addr_tlv nmi_addr_tlv; - } nmi_cmd = { - .rsv = { 0 }, - .nmi_addr_tlv = { - .tag = cpu_to_le16(NAN_UNI_CMD_CHANGE_NMI_ADDRESS), - .len = cpu_to_le16(sizeof(struct mt7925_nan_nmi_addr_tlv)), - }, - }; - int ret; - - if (!dev || !addr) - return -EINVAL; - - if (is_zero_ether_addr(addr) || is_multicast_ether_addr(addr)) { - dev_err(dev->mt76.dev, "NAN: invalid NMI address %pM\n", addr); - return -EINVAL; - } - - mdev = &dev->mt76; - memcpy(nmi_cmd.nmi_addr_tlv.nmi_addr, addr, ETH_ALEN); - - ret = mt76_mcu_send_msg(mdev, MCU_UNI_CMD(NAN), &nmi_cmd, - sizeof(nmi_cmd), true); - - return ret; -} - -int mt7925_nan_enable(struct ieee80211_vif *vif, - struct mt792x_dev *dev, - struct cfg80211_nan_conf *conf) -{ - struct mt792x_vif *mvif = (struct mt792x_vif *)vif->drv_priv; - struct mt76_dev *mdev = &dev->mt76; - struct { - u8 rsv[4]; - struct mt7925_nan_enable_req_tlv nan_req_tlv; - } nan_cmd = { - .rsv = { 0 }, - .nan_req_tlv = { - .tag = cpu_to_le16(NAN_UNI_CMD_ENABLE_REQUEST), - .len = cpu_to_le16(sizeof(struct mt7925_nan_enable_req_tlv)), - .config_random_factor_force = 0, - .random_factor_force_val = 0, - .config_hop_count_force = 0, - .hop_count_force_val = 0, - }, - }; - struct mt7925_nan_enable_req_tlv *p_nan_req_tlv = &nan_cmd.nan_req_tlv; - int ret; - - if (!vif || !dev || !conf) - return -EINVAL; - - p_nan_req_tlv->master_pref = conf->master_pref; - - mt7925_nan_set_2g_support(p_nan_req_tlv, conf); - mt7925_nan_set_5g_channel(dev, p_nan_req_tlv, conf); - mt7925_nan_set_cluster_id(p_nan_req_tlv, conf->cluster_id); - mt7925_nan_set_dw_interval(p_nan_req_tlv, conf); - mt7925_nan_set_disc_beacon(p_nan_req_tlv, conf); - mt7925_nan_set_rssi_thresholds(p_nan_req_tlv, conf); - mt7925_nan_set_scan_params(p_nan_req_tlv, conf); - - mt7925_nan_update_conf(mvif, conf); - - ret = mt76_mcu_send_msg(mdev, MCU_UNI_CMD(NAN), &nan_cmd, sizeof(nan_cmd), true); - - return ret; -} - -int mt7925_nan_disable(struct ieee80211_vif *vif, struct mt792x_dev *dev) -{ - struct mt76_dev *mdev = &dev->mt76; - struct { - u8 rsv[4]; - struct tlv nan_dis_tlv; - } nan_cmd = { - .rsv = { 0 }, - .nan_dis_tlv = { - .tag = cpu_to_le16(NAN_UNI_CMD_DISABLE_REQUEST), - .len = cpu_to_le16(sizeof(struct tlv)), - }, - }; - - if (!dev) - return -EINVAL; - - return mt76_mcu_send_msg(mdev, MCU_UNI_CMD(NAN), &nan_cmd, sizeof(nan_cmd), true); -} - static int mt7925_nan_mp_tlv(struct sk_buff *skb, u8 master_pref) { @@ -255,9 +91,6 @@ mt7925_nan_mp_tlv(struct sk_buff *skb, u8 master_pref) mp_tlv = (struct mt7925_nan_master_preference_tlv *)tlv; - if (master_pref > NAN_MAX_MASTER_PREFERENCE) - return 0; - mp_tlv->master_preference = master_pref; return 0; @@ -357,6 +190,213 @@ mt7925_nan_sync_rssi_tlv(struct sk_buff *skb, struct cfg80211_nan_conf *conf) return 0; } +/* FW rate set bit definitions (matches FW wlan_def_cmm.h) */ +#define NAN_RATE_SET_BIT_1M BIT(0) +#define NAN_RATE_SET_BIT_2M BIT(1) +#define NAN_RATE_SET_BIT_5_5M BIT(2) +#define NAN_RATE_SET_BIT_11M BIT(3) +#define NAN_RATE_SET_BIT_6M BIT(6) +#define NAN_RATE_SET_BIT_9M BIT(7) +#define NAN_RATE_SET_BIT_12M BIT(8) +#define NAN_RATE_SET_BIT_18M BIT(9) +#define NAN_RATE_SET_BIT_24M BIT(10) +#define NAN_RATE_SET_BIT_36M BIT(11) +#define NAN_RATE_SET_BIT_48M BIT(12) +#define NAN_RATE_SET_BIT_54M BIT(13) + +#define NAN_RATE_SET_ALL_A (NAN_RATE_SET_BIT_6M | NAN_RATE_SET_BIT_9M | \ + NAN_RATE_SET_BIT_12M | NAN_RATE_SET_BIT_18M | \ + NAN_RATE_SET_BIT_24M | NAN_RATE_SET_BIT_36M | \ + NAN_RATE_SET_BIT_48M | NAN_RATE_SET_BIT_54M) + +/* 5G basic: 6M+12M+24M (OFDM) */ +#define NAN_BASIC_RATE_SET_5G (NAN_RATE_SET_BIT_6M | NAN_RATE_SET_BIT_12M | \ + NAN_RATE_SET_BIT_24M) + +/* GF_MODE_DISALLOWED = 2, RIFS_MODE_DISALLOWED = 1 */ +#define NAN_GF_MODE_DISALLOWED 2 +#define NAN_RIFS_MODE_DISALLOWED 1 + +int mt7925_nan_update_phy_setting(struct mt792x_dev *dev) +{ + struct mt76_phy *mphy = &dev->mphy; + struct ieee80211_supported_band *sband_5g; + struct mt7925_nan_phy_setting *phy; + struct { + u8 rsv[4]; + struct mt7925_nan_update_phy_setting_tlv tlv; + } req = {}; + + sband_5g = mphy->hw->wiphy->bands[NL80211_BAND_5GHZ]; + + req.tlv.tag = cpu_to_le16(NAN_UNI_CMD_UPDATE_PHY_SETTING); + req.tlv.len = cpu_to_le16(sizeof(req.tlv)); + + /* 2G: ERP + HT (no CCK/HR_DSSS - NAN uses OFDM only) */ + phy = &req.tlv.phy_2g; + phy->phy_type_set = PHY_TYPE_BIT_ERP | PHY_TYPE_BIT_HT; + phy->non_ht_basic_phy_type = PHY_TYPE_ERP_INDEX; + phy->use_short_preamble = 1; + phy->use_short_slot_time = 1; + phy->operational_rate_set = cpu_to_le16(NAN_RATE_SET_ALL_A); + phy->bss_basic_rate_set = cpu_to_le16(NAN_BASIC_RATE_SET_5G); + phy->gf_operation_mode = cpu_to_le32(NAN_GF_MODE_DISALLOWED); + phy->rifs_operation_mode = cpu_to_le32(NAN_RIFS_MODE_DISALLOWED); + + /* 5G: OFDM + HT + VHT (NAN_MODE_11A) */ + phy = &req.tlv.phy_5g; + phy->phy_type_set = PHY_TYPE_BIT_OFDM | PHY_TYPE_BIT_HT | + PHY_TYPE_BIT_VHT; + phy->non_ht_basic_phy_type = PHY_TYPE_OFDM_INDEX; + phy->use_short_preamble = 1; + phy->use_short_slot_time = 1; + phy->operational_rate_set = cpu_to_le16(NAN_RATE_SET_ALL_A); + phy->bss_basic_rate_set = cpu_to_le16(NAN_BASIC_RATE_SET_5G); + phy->gf_operation_mode = cpu_to_le32(NAN_GF_MODE_DISALLOWED); + phy->rifs_operation_mode = cpu_to_le32(NAN_RIFS_MODE_DISALLOWED); + + /* VHT basic MCS set from sband capability */ + if (sband_5g && sband_5g->vht_cap.vht_supported) + phy->vht_basic_mcs_set = + sband_5g->vht_cap.vht_mcs.rx_mcs_map; + + return mt76_mcu_send_msg(&dev->mt76, MCU_UNI_CMD(NAN), + &req, sizeof(req), true); +} + +struct ieee80211_chanctx_conf * +mt7925_nan_seed_link_sta(struct mt792x_dev *dev, + struct ieee80211_link_sta *link_sta) +{ + struct ieee80211_supported_band *sband_2g, *sband_5g; + struct ieee80211_chanctx_conf *nan_ctx = NULL; + struct ieee80211_vif *nan_vif = dev->nan_vif; + + /* Fill HT cap from 2G sband */ + sband_2g = dev->mphy.hw->wiphy->bands[NL80211_BAND_2GHZ]; + sband_5g = dev->mphy.hw->wiphy->bands[NL80211_BAND_5GHZ]; + if (sband_2g) + link_sta->ht_cap = sband_2g->ht_cap; + + link_sta->sta->wme = true; + link_sta->rx_nss = hweight8(dev->mphy.antenna_mask); + + /* Get chanctx from NAN schedule. + * Prefer 5G committed slot for wider BW (VHT), fallback + * to first valid slot if no 5G data slot is scheduled. + */ + if (nan_vif) { + struct ieee80211_nan_channel **slots = + nan_vif->cfg.nan_sched.schedule; + int i; + + for (i = 0; i < CFG80211_NAN_SCHED_NUM_TIME_SLOTS; i++) { + struct ieee80211_chanctx_conf *ctx; + + if (!slots[i] || IS_ERR(slots[i]) || + !slots[i]->chanctx_conf) + continue; + + ctx = slots[i]->chanctx_conf; + if (!nan_ctx) + nan_ctx = ctx; + if (ctx->def.chan->band == NL80211_BAND_5GHZ) { + nan_ctx = ctx; + break; + } + } + } + + /* Capability describes what the device can do and must not be + * filtered by the current schedule - firmware gates the VHT rate + * mode per the data schedule and re-derives it on schedule + * change, which only works if the caps are present up front. + */ + if (sband_5g) + link_sta->vht_cap = sband_5g->vht_cap; + + /* Bandwidth here is the capability ceiling, not the operating + * width - the per-slot operating bandwidth follows the current + * slot channel via the firmware RLM sync, so deriving it from + * the schedule at STA-add time would cap a later 5 GHz schedule + * at the bring-up width. + */ + link_sta->bandwidth = IEEE80211_STA_RX_BW_80; + + return nan_ctx; +} + +int mt7925_nan_enable(struct ieee80211_vif *vif, + struct mt792x_dev *dev, + struct cfg80211_nan_conf *conf) +{ + struct mt792x_vif *mvif = (struct mt792x_vif *)vif->drv_priv; + struct mt76_dev *mdev = &dev->mt76; + struct mt7925_nan_common_hdr *hdr; + struct mt7925_nan_enable_req_tlv *req; + struct sk_buff *skb; + + if (!vif || !dev || !conf) + return -EINVAL; + + skb = mt76_mcu_msg_alloc(mdev, NULL, MT7925_NAN_ENABLE_MAX_SIZE); + if (!skb) + return -ENOMEM; + + hdr = (struct mt7925_nan_common_hdr *)skb_put(skb, sizeof(*hdr)); + memset(hdr, 0, sizeof(*hdr)); + + /* Set cluster id before joining cluster */ + if (mt7925_nan_cluster_id_tlv(skb, conf->cluster_id)) { + dev_kfree_skb(skb); + return -ENOMEM; + } + + /* NAN enable request tlv */ + req = (struct mt7925_nan_enable_req_tlv *) + mt76_connac_mcu_add_tlv(skb, NAN_UNI_CMD_ENABLE_REQUEST, + sizeof(*req)); + if (!req) { + dev_kfree_skb(skb); + return -ENOMEM; + } + + req->master_pref = conf->master_pref; + + mt7925_nan_set_5g_channel(dev, req, conf); + mt7925_nan_set_scan_params(req, conf); + + if (mt7925_nan_dw_tlv(skb, conf) || + mt7925_nan_sync_rssi_tlv(skb, conf)) { + dev_kfree_skb(skb); + return -ENOMEM; + } + + mt7925_nan_update_conf(mvif, conf); + + return mt76_mcu_skb_send_msg(mdev, skb, MCU_UNI_CMD(NAN), true); +} + +int mt7925_nan_disable(struct ieee80211_vif *vif, struct mt792x_dev *dev) +{ + struct mt76_dev *mdev = &dev->mt76; + struct { + u8 rsv[4]; + struct tlv nan_dis_tlv; + } nan_cmd = { + .rsv = { 0 }, + .nan_dis_tlv = { + .tag = cpu_to_le16(NAN_UNI_CMD_DISABLE_REQUEST), + .len = cpu_to_le16(sizeof(struct tlv)), + }, + }; + + if (!dev) + return -EINVAL; + + return mt76_mcu_send_msg(mdev, MCU_UNI_CMD(NAN), &nan_cmd, sizeof(nan_cmd), true); +} + int mt7925_nan_change_configure(struct ieee80211_vif *vif, struct mt792x_dev *dev, struct cfg80211_nan_conf *conf) @@ -473,8 +513,26 @@ mt7925_nan_mcu_handle_de_event(struct mt792x_dev *dev, struct tlv *tlv) dev_dbg(dev->mt76.dev, "nan: evt=%u cluster=%pM\n", de_evt->event_type, de_evt->cluster_id); - if (de_evt->event_type != NAN_EVENT_ID_JOINED_CLUSTER) + if (de_evt->event_type != NAN_EVENT_ID_JOINED_CLUSTER && + de_evt->event_type != NAN_EVENT_ID_STARTED_CLUSTER) + return; + + /* STARTED_CLUSTER fires during NAN_START, before nan.started is set and + * before the supplicant subscribes - defer past NAN_START via the work + * so ieee80211_nan_cluster_joined() actually reaches userspace. + */ + if (de_evt->event_type == NAN_EVENT_ID_STARTED_CLUSTER) { + dev_dbg(dev->mt76.dev, + "nan: deferring STARTED_CLUSTER cluster=%pM\n", + cluster_id); + spin_lock_bh(&dev->nan_deferred_lock); + memcpy(dev->nan_started_cluster_id, cluster_id, ETH_ALEN); + set_bit(MT7925_NAN_DEFERRED_STARTED_CLUSTER, + &dev->nan_deferred_pending); + spin_unlock_bh(&dev->nan_deferred_lock); + ieee80211_queue_work(dev->mt76.hw, &dev->nan_deferred_work); return; + } if (!dev->nan_vif || !ieee80211_vif_nan_started(dev->nan_vif)) { dev_warn(dev->mt76.dev, "nan: joined-cluster event but NAN not started\n"); @@ -487,7 +545,110 @@ mt7925_nan_mcu_handle_de_event(struct mt792x_dev *dev, struct tlv *tlv) dev_dbg(dev->mt76.dev, "nan: own_nmi=%pM master_nmi=%pM\n", de_evt->own_nmi, de_evt->master_nmi); - ieee80211_nan_cluster_joined(dev->nan_vif, cluster_id, true, GFP_KERNEL); + /* joined an existing cluster, not a self-anchored new one */ + ieee80211_nan_cluster_joined(dev->nan_vif, cluster_id, false, GFP_KERNEL); +} + +/* Runs the deferred NAN MCU events in process context; takes wiphy_lock + * before nan_vif, which the NAN stop path frees under that mutex. + */ +void +mt7925_nan_deferred_work(struct work_struct *work) +{ + struct mt792x_dev *dev = container_of(work, struct mt792x_dev, + nan_deferred_work); + struct ieee80211_vif *vif; + unsigned long pending; + u8 cluster_id[ETH_ALEN]; + + spin_lock_bh(&dev->nan_deferred_lock); + pending = dev->nan_deferred_pending; + dev->nan_deferred_pending = 0; + memcpy(cluster_id, dev->nan_started_cluster_id, ETH_ALEN); + spin_unlock_bh(&dev->nan_deferred_lock); + + if (!pending) + return; + + wiphy_lock(dev->mt76.hw->wiphy); + vif = dev->nan_vif; + if (!vif || !ieee80211_vif_nan_started(vif)) + goto out; + + if (test_bit(MT7925_NAN_DEFERRED_STARTED_CLUSTER, &pending)) + ieee80211_nan_cluster_joined(vif, cluster_id, true, GFP_KERNEL); + + if (test_bit(MT7925_NAN_DEFERRED_SCHED_UPDATE_DONE, &pending)) + ieee80211_nan_sched_update_done(vif); +out: + wiphy_unlock(dev->mt76.hw->wiphy); +} + +static void +mt7925_nan_handle_ulw_update(struct mt792x_dev *dev, struct tlv *tlv) +{ + struct mt7925_nan_ulw_event *evt; + struct mt7925_nan_ulw_attr attr; + struct wireless_dev *wdev; + u16 len; + + if (!dev || !tlv) + return; + + if (!dev->nan_vif || !ieee80211_vif_nan_started(dev->nan_vif)) + return; + + len = le16_to_cpu(tlv->len); + if (len < sizeof(*tlv) + sizeof(*evt)) { + dev_warn(dev->mt76.dev, + "nan: short ulw event tlv len=%u\n", len); + return; + } + + evt = (struct mt7925_nan_ulw_event *)tlv->data; + wdev = ieee80211_vif_to_wdev(dev->nan_vif); + if (!wdev) + return; + + dev_dbg(dev->mt76.dev, + "nan: ulw_update wdev=%p owner_nlportid=%u sched_id=%u seq=%u dur=%u\n", + wdev, wdev->owner_nlportid, + evt->sched_id, evt->seq_id, le32_to_cpu(evt->duration)); + + /* Reorder the FW fields into NAN spec Table 109 attribute layout */ + attr.attr_id = NAN_ULW_ATTR_ID; + attr.length = cpu_to_le16(NAN_ULW_FIXED_PAYLOAD); + attr.sched_id = evt->sched_id; + attr.seq_id = evt->seq_id; + attr.start_time = evt->start_time; + attr.duration = evt->duration; + attr.period = evt->period; + attr.count_down = evt->count_down; + attr.ulw_overwrite = evt->ulw_overwrite; + + cfg80211_nan_ulw_update(wdev, (const u8 *)&attr, sizeof(attr), + GFP_KERNEL); +} + +static void +mt7925_nan_handle_sched_update_done(struct mt792x_dev *dev, struct tlv *tlv) +{ + struct ieee80211_vif *vif; + + if (!dev || !tlv) + return; + + vif = dev->nan_vif; + if (!vif || !ieee80211_vif_nan_started(vif)) + return; + + /* Runs in the BH-disabled MCU-event RX path; the mac80211 helper needs + * the wiphy mutex and may sleep, so hand it to the work instead. + */ + spin_lock_bh(&dev->nan_deferred_lock); + set_bit(MT7925_NAN_DEFERRED_SCHED_UPDATE_DONE, &dev->nan_deferred_pending); + spin_unlock_bh(&dev->nan_deferred_lock); + ieee80211_queue_work(dev->mt76.hw, &dev->nan_deferred_work); } void mt7925_nan_mcu_event(struct mt792x_dev *dev, struct sk_buff *skb) @@ -515,9 +676,15 @@ void mt7925_nan_mcu_event(struct mt792x_dev *dev, struct sk_buff *skb) case NAN_UNI_EVENT_ID_DE_EVENT_IND: mt7925_nan_mcu_handle_de_event(dev, tlv); break; - case NAN_UNI_EVENT_REPORT_DW_END: + case NAN_UNI_EVENT_REPORT_DW_START: mt7925_nan_handle_dw_ind(dev, tlv); break; + case NAN_UNI_EVENT_ID_ULW_UPDATE: + mt7925_nan_handle_ulw_update(dev, tlv); + break; + case NAN_UNI_EVENT_ID_SCHED_UPDATE_DONE: + mt7925_nan_handle_sched_update_done(dev, tlv); + break; default: break; } @@ -555,6 +722,7 @@ static int mt7925_nan_avail_ctrl_tlv(struct sk_buff *skb, avail_ctrl_tlv->avail_ctrl = cpu_to_le16(ctrl & NAN_AVAIL_CTRL_CHECK_FOR_CHANGED); avail_ctrl_tlv->seq_id = seq_id; + avail_ctrl_tlv->is_deferred = sched->deferred ? 1 : 0; return 0; } @@ -584,9 +752,14 @@ static u32 mt7925_nan_slot_to_bitmap(struct ieee80211_vif *vif, if (FIELD_GET(NAN_CH_CTRL_PRIMARY_CH, raw) == slot_chan->chan->hw_value) { - u32 map = le32_to_cpu(ch_list[j].avail_map[0]); + u32 dw; + + for (dw = 0; dw < NAN_TOTAL_DW; dw++) { + u32 map = le32_to_cpu(ch_list[j].avail_map[dw]); - ch_list[j].avail_map[0] = cpu_to_le32(map | BIT(i)); + ch_list[j].avail_map[dw] = + cpu_to_le32(map | BIT(i)); + } le32_add_cpu(&ch_list[j].num, 1); is_found = true; break; @@ -594,12 +767,18 @@ static u32 mt7925_nan_slot_to_bitmap(struct ieee80211_vif *vif, } if (!is_found && num_channels < NAN_TIMELINE_MGMT_CHNL_LIST_NUM) { + u32 dw; + ch_list[num_channels].ch_info = - cpu_to_le32(FIELD_PREP(NAN_CH_CTRL_OP_CLASS, + cpu_to_le32(FIELD_PREP(NAN_CH_CTRL_CH_TYPE, + NAN_BAND_CHANNEL_ENTRY_LIST_TYPE_CHANNEL) | + FIELD_PREP(NAN_CH_CTRL_OP_CLASS, slot->channel_entry[0]) | FIELD_PREP(NAN_CH_CTRL_PRIMARY_CH, slot_chan->chan->hw_value)); - ch_list[num_channels].avail_map[0] = cpu_to_le32(BIT(i)); + for (dw = 0; dw < NAN_TOTAL_DW; dw++) + ch_list[num_channels].avail_map[dw] = + cpu_to_le32(BIT(i)); le32_add_cpu(&ch_list[num_channels].num, 1); ch_list[num_channels].is_valid++; num_channels++; @@ -647,15 +826,12 @@ void mt7925_nan_local_sched_changed(struct mt792x_dev *dev, { struct mt7925_nan_common_hdr *hdr; struct mt76_dev *mdev; - bool deferred; struct sk_buff *skb; - int ret = -ENOMEM; if (!dev || !vif) return; mdev = &dev->mt76; - deferred = vif->cfg.nan_sched.deferred; mt792x_mutex_acquire(dev); @@ -672,19 +848,9 @@ void mt7925_nan_local_sched_changed(struct mt792x_dev *dev, goto out; } - ret = mt76_mcu_skb_send_msg(mdev, skb, - MCU_UNI_CMD(NAN), true); + mt76_mcu_skb_send_msg(mdev, skb, MCU_UNI_CMD(NAN), false); out: mt792x_mutex_release(dev); - - if (deferred) { - if (ret) - dev_err(mdev->dev, - "NAN: local schedule update failed: %d\n", - ret); - - ieee80211_nan_sched_update_done(vif); - } } static int mt7925_nan_peer_rec_tlv(struct sk_buff *skb, @@ -712,23 +878,6 @@ static int mt7925_nan_peer_rec_tlv(struct sk_buff *skb, return 0; } -static u8 mt7925_nan_get_supported_bands(struct mt792x_vif *mvif) -{ - struct wiphy *wiphy; - u8 bands = 0; - - if (!mvif || !mvif->phy) - return BIT(NAN_SUPPORTED_BAND_ID_2P4G); - - wiphy = mvif->phy->mt76->hw->wiphy; - if (wiphy->nan_supported_bands & BIT(NL80211_BAND_2GHZ)) - bands |= BIT(NAN_SUPPORTED_BAND_ID_2P4G); - if (wiphy->nan_supported_bands & BIT(NL80211_BAND_5GHZ)) - bands |= BIT(NAN_SUPPORTED_BAND_ID_5G); - - return bands ?: BIT(NAN_SUPPORTED_BAND_ID_2P4G); -} - static int mt7925_nan_peer_cap_tlv(struct sk_buff *skb, struct ieee80211_sta *sta, struct mt792x_sta *msta) @@ -755,8 +904,7 @@ static int mt7925_nan_peer_cap_tlv(struct sk_buff *skb, peer_cap_tlv = (struct mt7925_nan_sched_update_peer_cap_tlv *)tlv; peer_cap_tlv->sch_idx = cpu_to_le32(msta->nan_sched.sch_idx); - peer_cap_tlv->supported_bands = - mt7925_nan_get_supported_bands(msta->vif); + peer_cap_tlv->supported_bands = BIT(NAN_SUPPORTED_BAND_ID_2P4G); peer_cap_tlv->max_chnl_switch_time = cpu_to_le16(sched->max_chan_switch); for (i = 0; i < sched->n_channels; i++) { @@ -785,52 +933,40 @@ static int mt7925_nan_peer_cap_tlv(struct sk_buff *skb, static void mt7925_nan_fill_crb_committed(struct mt7925_nan_sched_update_crb_tlv *crb_tlv, - struct ieee80211_vif *vif, struct ieee80211_nan_peer_sched *sched) { - struct ieee80211_nan_sched_cfg *local_sched; - u8 local_map_id; u32 m, slot; - if (!vif || !sched) + if (!sched) return; - local_sched = &vif->cfg.nan_sched; - local_map_id = mt7925_nan_avail_attr_ctrl(local_sched) & - NAN_AVAIL_CTRL_MAPID; - for (m = 0; m < CFG80211_NAN_MAX_PEER_MAPS && m < NAN_TIMELINE_MGMT_SIZE; m++) { + struct ieee80211_nan_peer_map *map = &sched->maps[m]; struct mt7925_nan_sched_timeline *tl = &crb_tlv->comm_faw_timeline[m]; - struct ieee80211_nan_peer_map *map = &sched->maps[m]; - u32 avail_map = 0; if (map->map_id == CFG80211_NAN_INVALID_MAP_ID) continue; tl->map_id = map->map_id; - tl->local_map_id = local_map_id; + /* + * Convert peer schedule slots to FW avail_map bitmap. + * Each bit represents one time slot where the peer has + * committed availability. Fill all DW intervals the same. + */ for (slot = 0; slot < CFG80211_NAN_SCHED_NUM_TIME_SLOTS; slot++) { - struct ieee80211_nan_channel *local_ch; - struct ieee80211_nan_channel *peer_ch; + struct ieee80211_nan_channel *ch = map->slots[slot]; + u32 dw; - local_ch = local_sched->schedule[slot]; - peer_ch = map->slots[slot]; - - if (!local_ch || !local_ch->chanctx_conf || - !peer_ch || !peer_ch->chanctx_conf) + if (!ch || !ch->chanctx_conf) continue; - if (local_ch->chanctx_conf != peer_ch->chanctx_conf) - continue; - - avail_map |= BIT(slot); + for (dw = 0; dw < NAN_TOTAL_DW; dw++) + tl->avail_map[dw] |= cpu_to_le32(BIT(slot)); } - - tl->avail_map[0] = cpu_to_le32(avail_map); } } @@ -856,8 +992,38 @@ static int mt7925_nan_update_crb_tlv(struct sk_buff *skb, crb_tlv->is_use_ranging = false; crb_tlv->comm_ndc_ctrl.is_valid = false; - mt7925_nan_fill_crb_committed(crb_tlv, msta->vif->phy->dev->nan_vif, - sta->nan_sched); + mt7925_nan_fill_crb_committed(crb_tlv, sta->nan_sched); + + return 0; +} + +static int +mt7925_nan_peer_ulw_tlv(struct sk_buff *skb, + struct ieee80211_sta *sta, + struct mt792x_sta *msta) +{ + struct mt7925_nan_update_ulw_tlv *ulw_tlv = NULL; + struct ieee80211_nan_peer_sched *sched = NULL; + struct tlv *tlv = NULL; + + if (!skb || !sta || !msta) + return -EINVAL; + + sched = sta->nan_sched; + if (!sched || !sched->init_ulw || !sched->ulw_size) + return 0; /* No ULW to send, not an error */ + + if (sched->ulw_size > NAN_ULW_MAX_SIZE) + return -EINVAL; + + tlv = mt76_connac_mcu_add_tlv(skb, NAN_UNI_CMD_UPDATE_ULW, + sizeof(struct mt7925_nan_update_ulw_tlv)); + if (!tlv) + return -ENOMEM; + + ulw_tlv = (struct mt7925_nan_update_ulw_tlv *)tlv; + ether_addr_copy(ulw_tlv->nmi_addr, sta->addr); + memcpy(ulw_tlv->ulw_attr, sched->init_ulw, sched->ulw_size); return 0; } @@ -914,6 +1080,10 @@ int mt792x_nan_set_peer_schedule(struct mt792x_dev *dev, goto free_skb; } + ret = mt7925_nan_peer_ulw_tlv(skb, sta, msta); + if (ret) + goto free_skb; + ret = mt76_mcu_skb_send_msg(mdev, skb, MCU_UNI_CMD(NAN), true); if (ret && idx_allocated) goto clear_idx; @@ -935,18 +1105,18 @@ int mt792x_nan_set_peer_schedule(struct mt792x_dev *dev, int mt792x_nan_set_peer_rec(struct mt76_dev *mdev, struct ieee80211_sta *sta) { + struct mt7925_nan_sched_update_crb_tlv *crb_tlv; struct mt7925_nan_common_hdr *hdr; struct mt792x_sta *msta; struct mt792x_nan *nan; struct sk_buff *skb; + struct tlv *tlv; int ret; if (!mdev || !sta) return -EINVAL; - skb = mt76_mcu_msg_alloc(mdev, NULL, - sizeof(struct mt7925_nan_common_hdr) + - sizeof(struct mt7925_nan_sched_manage_peer_rec_tlv)); + skb = mt76_mcu_msg_alloc(mdev, NULL, MT7925_NAN_PEER_MAX_SIZE); if (!skb) return -ENOMEM; @@ -961,6 +1131,25 @@ int mt792x_nan_set_peer_rec(struct mt76_dev *mdev, return 0; } + /* Send a zero-avail_map CRB TLV before deactivating the peer record so + * firmware clears the committed schedule slots for this peer. Without + * this, stale CRB entries linger and cause scheduling conflicts for + * subsequent NDP connections that reuse the same sch_idx. + */ + tlv = mt76_connac_mcu_add_tlv(skb, NAN_UNI_CMD_UPDATE_CRB, + sizeof(struct mt7925_nan_sched_update_crb_tlv)); + if (!tlv) { + dev_kfree_skb(skb); + return -ENOMEM; + } + crb_tlv = (struct mt7925_nan_sched_update_crb_tlv *)tlv; + crb_tlv->sch_idx = cpu_to_le32(msta->nan_sched.sch_idx); + crb_tlv->flags = NAN_CRB_USE_DATA_PATH; + crb_tlv->is_use_ranging = false; + crb_tlv->comm_ndc_ctrl.is_valid = false; + /* avail_map is zero-initialised by mt76_connac_mcu_add_tlv */ + + /* Deactivate peer record and release connection index */ if (mt7925_nan_peer_rec_tlv(skb, sta, msta, false)) { dev_kfree_skb(skb); return -ENOMEM; @@ -984,21 +1173,17 @@ int mt792x_nan_map_sta_rec(struct mt76_dev *mdev, struct mt7925_nan_common_hdr *hdr; struct ieee80211_sta *nmi_sta; struct mt792x_sta *nmi_msta; - struct mt792x_vif *mvif; struct mt792x_sta *msta; u8 nmi_addr[ETH_ALEN]; struct sk_buff *skb; int ndp_ctx_id = 0; int ret = -ENOMEM; - struct mt792x_dev *dev; struct tlv *tlv; if (!mdev || !vif || !sta) return -EINVAL; - dev = container_of(mdev, struct mt792x_dev, mt76); msta = (struct mt792x_sta *)sta->drv_priv; - mvif = (struct mt792x_vif *)vif->drv_priv; rcu_read_lock(); nmi_sta = rcu_dereference(sta->nmi); @@ -1012,33 +1197,6 @@ int mt792x_nan_map_sta_rec(struct mt76_dev *mdev, memcpy(nmi_addr, nmi_sta->addr, ETH_ALEN); nmi_msta = (struct mt792x_sta *)nmi_sta->drv_priv; - if (!nmi_msta->nan_sched.idx_assigned) { - if (!nmi_sta->nan_sched) { - rcu_read_unlock(); - dev_err(mdev->dev, - "NAN: peer schedule missing for NDI sta %pM\n", - sta->addr); - return -EAGAIN; - } - - rcu_read_unlock(); - ret = mt792x_nan_set_peer_schedule(dev, nmi_sta); - if (ret) - return ret; - - rcu_read_lock(); - nmi_sta = rcu_dereference(sta->nmi); - if (!nmi_sta) { - rcu_read_unlock(); - dev_err(mdev->dev, - "NAN: NMI sta not found for NDI sta %pM\n", - sta->addr); - return -EINVAL; - } - - nmi_msta = (struct mt792x_sta *)nmi_sta->drv_priv; - } - ndp_ctx_id = find_first_zero_bit(&nmi_msta->nan_sched.ndp_ctx_bitmap, NAN_MAX_NDP_CXT); if (ndp_ctx_id >= NAN_MAX_NDP_CXT) { @@ -1073,7 +1231,7 @@ int mt792x_nan_map_sta_rec(struct mt76_dev *mdev, memcpy(map_tlv->nmi_addr, nmi_addr, ETH_ALEN); map_tlv->sta_rec_idx = msta->deflink.wcid.idx; map_tlv->ndp_ctx_id = ndp_ctx_id; - map_tlv->role_idx = cpu_to_le32(mvif->bss_conf.mt76.idx); + map_tlv->role_idx = cpu_to_le32(NAN_BSS_INDEX_BAND0); memcpy(map_tlv->ndi_addr, vif->addr, ETH_ALEN); ret = mt76_mcu_skb_send_msg(mdev, skb, diff --git a/drivers/net/wireless/mediatek/mt76/mt7925/nan.h b/drivers/net/wireless/mediatek/mt76/mt7925/nan.h index f55730e25f46..9a0cd1d06d45 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7925/nan.h +++ b/drivers/net/wireless/mediatek/mt76/mt7925/nan.h @@ -28,6 +28,13 @@ #define NAN_MAX_CONN_CFG 8 #define NAN_MAX_NDP_CXT 4 +#define MT7925_NAN_ENABLE_MAX_SIZE \ + (sizeof(struct mt7925_nan_common_hdr) + \ + sizeof(struct mt7925_nan_enable_req_tlv) + \ + sizeof(struct mt7925_nan_dw_interval_tlv) + \ + sizeof(struct mt7925_nan_cluster_id_tlv) + \ + sizeof(struct mt7925_nan_sync_rssi_tlv)) + #define MT7925_NAN_CONF_MAX_SIZE \ (sizeof(struct mt7925_nan_common_hdr) + \ sizeof(struct mt7925_nan_master_preference_tlv) + \ @@ -44,7 +51,8 @@ (sizeof(struct mt7925_nan_common_hdr) + \ sizeof(struct mt7925_nan_sched_manage_peer_rec_tlv) + \ sizeof(struct mt7925_nan_sched_update_peer_cap_tlv) + \ - sizeof(struct mt7925_nan_sched_update_crb_tlv)) + sizeof(struct mt7925_nan_sched_update_crb_tlv) + \ + sizeof(struct mt7925_nan_update_ulw_tlv)) /* NAN Availability Attribute */ #define NAN_AVAIL_ATTR_ID_OFFSET 0 @@ -65,6 +73,8 @@ #define UNII3_LOWER_BOUND 149 #define UNII3_UPPER_BOUND 165 +#define NAN_BSS_INDEX_BAND0 0 + enum nan_uni_cmd_tag { NAN_UNI_CMD_SET_MASTER_PREFERENCE = 0, NAN_UNI_CMD_ENABLE_REQUEST = 7, @@ -73,6 +83,8 @@ enum nan_uni_cmd_tag { NAN_UNI_CMD_UPDATE_CRB = 10, NAN_UNI_CMD_MANAGE_PEER_SCH_RECORD = 12, NAN_UNI_CMD_MAP_STA_RECORD = 13, + NAN_UNI_CMD_UPDATE_ULW = 16, + NAN_UNI_CMD_UPDATE_PHY_SETTING = 18, NAN_UNI_CMD_UPDATE_AVAILABILITY_CTRL = 20, NAN_UNI_CMD_UPDATE_PEER_CAPABILITY = 21, NAN_UNI_CMD_CHANGE_NMI_ADDRESS = 24, @@ -84,14 +96,26 @@ enum nan_uni_cmd_tag { enum nan_uni_event_tag { NAN_UNI_EVENT_ID_DE_EVENT_IND = 19, + NAN_UNI_EVENT_ID_ULW_UPDATE = 39, + NAN_UNI_EVENT_ID_SCHED_UPDATE_DONE = 43, + NAN_UNI_EVENT_REPORT_DW_START = 59, NAN_UNI_EVENT_REPORT_DW_END = 60, }; enum nan_disc_event_type { NAN_EVENT_ID_DISC_MAC_ADDR = 0, + NAN_EVENT_ID_STARTED_CLUSTER = 1, NAN_EVENT_ID_JOINED_CLUSTER = 2, }; +/* bit indices into mt792x_dev->nan_deferred_pending, set from the atomic + * MCU-event RX path and consumed by mt7925_nan_deferred_work() + */ +enum mt7925_nan_deferred_event { + MT7925_NAN_DEFERRED_STARTED_CLUSTER, + MT7925_NAN_DEFERRED_SCHED_UPDATE_DONE, +}; + /* NAN 4.0 Table 79. Device Capability attribute format, Supported Bands */ enum nan_supported_bands { NAN_SUPPORTED_BAND_ID_2P4G = 2, @@ -108,12 +132,15 @@ enum nan_peer_supported_bands { NAN_SUPPORTED_BN_NUM }; +#define NAN_CH_CTRL_CH_TYPE BIT(0) #define NAN_CH_CTRL_OP_CLASS GENMASK(15, 8) #define NAN_CH_CTRL_PRIMARY_CH GENMASK(23, 16) #define NAN_CRB_USE_DATA_PATH BIT(0) #define NAN_CRB_AVAIL_6G_FORMAT GENMASK(2, 1) +#define NAN_BAND_CHANNEL_ENTRY_LIST_TYPE_CHANNEL 1 + struct mt7925_nan_social_ch_scan_params { u8 dwell_time[NAN_MAX_SOCIAL_CHANNELS]; __le16 scan_period[NAN_MAX_SOCIAL_CHANNELS]; @@ -153,6 +180,32 @@ struct nan_rpt_dw_evt { __le16 dw_num; }; +#define NAN_ULW_ATTR_ID 0x17 +#define NAN_ULW_FIXED_PAYLOAD 16 /* Table 109 fixed fields */ + +struct mt7925_nan_ulw_event { + u8 sched_id; + u8 seq_id; + u8 count_down; + u8 ulw_overwrite; + __le32 start_time; + __le32 duration; + __le32 period; +} __packed; + +/* ULW attribute laid out in NAN spec Table 109 field order */ +struct mt7925_nan_ulw_attr { + u8 attr_id; + __le16 length; + u8 sched_id; + u8 seq_id; + __le32 start_time; + __le32 duration; + __le32 period; + u8 count_down; + u8 ulw_overwrite; +} __packed; + struct mt7925_nan_conf_dw { u8 config_2dot4g_dw_band; __le32 dw_2dot4g_interval_val; @@ -302,7 +355,7 @@ struct mt7925_nan_avail_ctrl_tlv { __le16 len; __le16 avail_ctrl; u8 seq_id; - u8 reserved[1]; + u8 is_deferred; } __packed __aligned(4); struct mt7925_nan_ch_timeline { @@ -346,8 +399,7 @@ struct mt7925_nan_sched_update_peer_cap_tlv { struct mt7925_nan_sched_timeline { u8 map_id; - u8 local_map_id; - u8 reserved[2]; + u8 reserved[3]; union { __le32 avail_map[NAN_TOTAL_DW]; u8 avail_block[NAN_TOTAL_DW * 4]; @@ -378,6 +430,15 @@ struct mt7925_nan_sched_update_crb_tlv { struct mt7925_nan_sched_faw_ndc_timeline faw_ndc_timeline[NAN_TIMELINE_MGMT_SIZE]; } __packed __aligned(4); +#define NAN_ULW_MAX_SIZE 256 + +struct mt7925_nan_update_ulw_tlv { + __le16 tag; + __le16 len; + u8 nmi_addr[ETH_ALEN]; + u8 ulw_attr[NAN_ULW_MAX_SIZE]; +} __packed __aligned(4); + struct mt7925_nan_sched_map_sta_rec_tlv { __le16 tag; __le16 len; @@ -390,6 +451,38 @@ struct mt7925_nan_sched_map_sta_rec_tlv { u8 reserved[2]; } __packed __aligned(4); +/* Matches FW NAN_PHY_SETTING_T (enum fields are 4 bytes on ARM) */ +struct mt7925_nan_phy_setting { + u8 phy_type_set; + u8 non_ht_basic_phy_type; + u8 use_short_preamble; + u8 use_short_slot_time; + __le16 operational_rate_set; + __le16 bss_basic_rate_set; + __le16 vht_basic_mcs_set; + u8 erp_protect_mode; + u8 ht_op_info1; + __le16 ht_op_info2; + __le16 ht_op_info3; + __le32 ht_protect_mode; + __le32 gf_operation_mode; + __le32 rifs_operation_mode; +} __packed; + +/* Matches FW NAN_SCHED_CMD_UPDATE_PHY_PARAM_T */ +struct mt7925_nan_update_phy_setting_tlv { + __le16 tag; + __le16 len; + struct mt7925_nan_phy_setting phy_2g; + struct mt7925_nan_phy_setting phy_5g; +} __packed __aligned(4); + +int mt7925_nan_update_phy_setting(struct mt792x_dev *dev); + +struct ieee80211_chanctx_conf * +mt7925_nan_seed_link_sta(struct mt792x_dev *dev, + struct ieee80211_link_sta *link_sta); + int mt7925_nan_enable(struct ieee80211_vif *vif, struct mt792x_dev *dev, struct cfg80211_nan_conf *conf); @@ -403,8 +496,6 @@ int mt7925_nan_change_configure(struct ieee80211_vif *vif, void mt7925_nan_mcu_event(struct mt792x_dev *dev, struct sk_buff *skb); -int mt7925_nan_set_nmi_addr(struct mt792x_dev *dev, const u8 *addr); - void mt7925_nan_local_sched_changed(struct mt792x_dev *dev, struct ieee80211_vif *vif); diff --git a/drivers/net/wireless/mediatek/mt76/mt7925/pci.c b/drivers/net/wireless/mediatek/mt76/mt7925/pci.c index d2c0a78ae9f2..12c1f7868d91 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7925/pci.c +++ b/drivers/net/wireless/mediatek/mt76/mt7925/pci.c @@ -47,14 +47,16 @@ static void mt7925e_unregister_device(struct mt792x_dev *dev) if (dev->phy.chip_cap & MT792x_CHIP_CAP_WF_RF_PIN_CTRL_EVT_EN) wiphy_rfkill_stop_polling(hw->wiphy); - cancel_work_sync(&dev->reset_work); cancel_work_sync(&dev->init_work); mt76_unregister_device(&dev->mt76); + set_bit(MT76_REMOVED, &dev->mphy.state); + cancel_work_sync(&dev->reset_work); mt76_for_each_q_rx(&dev->mt76, i) napi_disable(&dev->mt76.napi[i]); cancel_delayed_work_sync(&pm->ps_work); cancel_delayed_work_sync(&dev->mlo_pm_work); cancel_work_sync(&pm->wake_work); + cancel_work_sync(&dev->nan_deferred_work); mt7925_tx_token_put(dev); __mt792x_mcu_drv_pmctrl(dev); @@ -724,7 +726,6 @@ static void mt7925_pci_remove(struct pci_dev *pdev) struct mt76_dev *mdev = pci_get_drvdata(pdev); struct mt792x_dev *dev = container_of(mdev, struct mt792x_dev, mt76); - set_bit(MT76_REMOVED, &mdev->phy.state); mt7925e_unregister_device(dev); devm_free_irq(&pdev->dev, pdev->irq, dev); mt76_free_device(&dev->mt76); diff --git a/drivers/net/wireless/mediatek/mt76/mt7925/pci_mac.c b/drivers/net/wireless/mediatek/mt76/mt7925/pci_mac.c index 8477d21abc66..67eb86746779 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7925/pci_mac.c +++ b/drivers/net/wireless/mediatek/mt76/mt7925/pci_mac.c @@ -73,7 +73,9 @@ int mt7925e_mac_reset(struct mt792x_dev *dev) const struct mt792x_irq_map *irq_map = dev->irq_map; int i, err; - mt792xe_mcu_drv_pmctrl(dev); + err = mt792xe_mcu_drv_pmctrl(dev); + if (err) + return err; mt76_connac_free_pending_tx_skbs(&dev->pm, NULL); @@ -125,7 +127,7 @@ int mt7925e_mac_reset(struct mt792x_dev *dev) err = mt792xe_mcu_fw_pmctrl(dev); if (err) - return err; + goto out; err = __mt792xe_mcu_drv_pmctrl(dev); if (err) diff --git a/drivers/net/wireless/mediatek/mt76/mt7925/usb.c b/drivers/net/wireless/mediatek/mt76/mt7925/usb.c index db6fd014447b..f97f787b2198 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7925/usb.c +++ b/drivers/net/wireless/mediatek/mt76/mt7925/usb.c @@ -357,6 +357,19 @@ static int mt7925u_resume(struct usb_interface *intf) } #endif /* CONFIG_PM */ +static void mt7925u_disconnect(struct usb_interface *usb_intf) +{ + struct mt792x_dev *dev = usb_get_intfdata(usb_intf); + + /* mt792xu_disconnect() ends in mt76_free_device(), so the work has to + * go before it rather than after mt76_unregister_device() as on PCI. + */ + if (dev) + cancel_work_sync(&dev->nan_deferred_work); + + mt792xu_disconnect(usb_intf); +} + MODULE_DEVICE_TABLE(usb, mt7925u_device_table); MODULE_FIRMWARE(MT7925_FIRMWARE_WM); MODULE_FIRMWARE(MT7925_ROM_PATCH); @@ -365,7 +378,7 @@ static struct usb_driver mt7925u_driver = { .name = KBUILD_MODNAME, .id_table = mt7925u_device_table, .probe = mt7925u_probe, - .disconnect = mt792xu_disconnect, + .disconnect = mt7925u_disconnect, #ifdef CONFIG_PM .suspend = mt7925u_suspend, .resume = mt7925u_resume, diff --git a/drivers/net/wireless/mediatek/mt76/mt792x.h b/drivers/net/wireless/mediatek/mt76/mt792x.h index 9efc251cb745..7b838a8655be 100644 --- a/drivers/net/wireless/mediatek/mt76/mt792x.h +++ b/drivers/net/wireless/mediatek/mt76/mt792x.h @@ -191,6 +191,7 @@ struct mt792x_vif { struct mt792x_sta *wep_sta; struct mt792x_phy *phy; + bool roc_join_held; /* join ROC kept until the STA is authorized */ u16 valid_links; u8 deflink_id; enum mt792x_mlo_pm_state mlo_pm_state; @@ -214,6 +215,7 @@ struct mt792x_phy { s16 coverage_class; u8 slottime; + u32 rxfilter; u32 rx_ampdu_ts; u32 ampdu_ref; @@ -342,6 +344,14 @@ struct mt792x_dev { struct ieee80211_vif *nan_vif; const struct ieee80211_iface_combination *iface_combinations; int n_iface_combinations; + /* deferred NAN MCU events run out of the atomic RX path on one shared + * work; see mt7925_nan_deferred_work() and enum mt7925_nan_deferred_event + */ + struct work_struct nan_deferred_work; + /* protects @nan_deferred_pending */ + spinlock_t nan_deferred_lock; + unsigned long nan_deferred_pending; + u8 nan_started_cluster_id[ETH_ALEN]; }; static inline struct mt792x_bss_conf * diff --git a/drivers/net/wireless/mediatek/mt76/mt792x_mac.c b/drivers/net/wireless/mediatek/mt76/mt792x_mac.c index 888e5a505673..ebf4c32924c4 100644 --- a/drivers/net/wireless/mediatek/mt76/mt792x_mac.c +++ b/drivers/net/wireless/mediatek/mt76/mt792x_mac.c @@ -165,14 +165,16 @@ mt792x_mac_rssi_iter(void *priv, u8 *mac, struct ieee80211_vif *vif) struct mt76_rx_status *status = (struct mt76_rx_status *)skb->cb; struct mt792x_vif *mvif = (struct mt792x_vif *)vif->drv_priv; struct ieee80211_hdr *hdr = mt76_skb_get_hdr(skb); + int signal; - if (status->signal > 0) + signal = mt76_rx_signal(status->chains, status->chain_signal); + if (signal > 0 || signal <= -128) return; if (!ether_addr_equal(vif->addr, hdr->addr1)) return; - ewma_rssi_add(&mvif->bss_conf.rssi, -status->signal); + ewma_rssi_add(&mvif->bss_conf.rssi, -signal); } void mt792x_mac_assoc_rssi(struct mt792x_dev *dev, struct sk_buff *skb) @@ -278,6 +280,9 @@ void mt792x_reset(struct mt76_dev *mdev) if (pm->suspended) return; + if (test_bit(MT76_REMOVED, &mdev->phy.state)) + return; + queue_work(dev->mt76.wq, &dev->reset_work); } EXPORT_SYMBOL_GPL(mt792x_reset); diff --git a/drivers/net/wireless/mediatek/mt76/mt792x_usb.c b/drivers/net/wireless/mediatek/mt76/mt792x_usb.c index 850f6b2cfc4a..5e19e64a9a00 100644 --- a/drivers/net/wireless/mediatek/mt76/mt792x_usb.c +++ b/drivers/net/wireless/mediatek/mt76/mt792x_usb.c @@ -502,21 +502,26 @@ void mt792xu_disconnect(struct usb_interface *usb_intf) return; set_bit(MT76_RESET, &dev->mphy.state); - set_bit(MT76_MCU_RESET, &dev->mphy.state); clear_bit(MT76_STATE_RUNNING, &dev->mphy.state); - wake_up(&dev->mt76.mcu.wait); - skb_queue_purge(&dev->mt76.mcu.res_q); - cancel_work_sync(&dev->reset_work); cancel_work_sync(&dev->init_work); mt76_worker_disable(&dev->mt76.tx_worker); mt792xu_reset_work_cleanup(dev); if (!test_bit(MT76_STATE_INITIALIZED, &dev->mphy.state)) { + set_bit(MT76_MCU_RESET, &dev->mphy.state); + wake_up(&dev->mt76.mcu.wait); + skb_queue_purge(&dev->mt76.mcu.res_q); + cancel_work_sync(&dev->reset_work); set_bit(MT76_REMOVED, &dev->mphy.state); return; } mt76_unregister_device(&dev->mt76); + + set_bit(MT76_MCU_RESET, &dev->mphy.state); + wake_up(&dev->mt76.mcu.wait); + skb_queue_purge(&dev->mt76.mcu.res_q); + cancel_work_sync(&dev->reset_work); mt792xu_cleanup(dev); set_bit(MT76_REMOVED, &dev->mphy.state); diff --git a/drivers/net/wireless/mediatek/mt76/mt7996/Kconfig b/drivers/net/wireless/mediatek/mt76/mt7996/Kconfig index 5742bce12fbb..3c51b402f44e 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7996/Kconfig +++ b/drivers/net/wireless/mediatek/mt76/mt7996/Kconfig @@ -17,5 +17,6 @@ config MT7996_NPU bool "MT7996 (PCIe) NPU support" depends on MT7996E depends on NET_AIROHA_NPU=y || MT76_CORE=NET_AIROHA_NPU + depends on NET_AIROHA=y || NET_AIROHA=n || MT76_CORE=NET_AIROHA select MT76_NPU default n diff --git a/drivers/net/wireless/mediatek/mt76/mt7996/coredump.c b/drivers/net/wireless/mediatek/mt76/mt7996/coredump.c index 5c293ae965cd..be4c882b3184 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7996/coredump.c +++ b/drivers/net/wireless/mediatek/mt76/mt7996/coredump.c @@ -202,11 +202,12 @@ static struct mt7996_coredump *mt7996_coredump_build(struct mt7996_dev *dev) mt7996_coredump_fw_stack(dev, dump, exception); /* gather memory content */ - dump_mem = (struct mt7996_coredump_mem *)(buf + sofar); - dump_mem->len = crash_data->memdump_buf_len; - if (coredump_memdump && crash_data->memdump_buf_len) + if (coredump_memdump && crash_data->memdump_buf_len) { + dump_mem = (struct mt7996_coredump_mem *)(buf + sofar); + dump_mem->len = crash_data->memdump_buf_len; memcpy(dump_mem->data, crash_data->memdump_buf, crash_data->memdump_buf_len); + } mutex_unlock(&dev->dump_mutex); diff --git a/drivers/net/wireless/mediatek/mt76/mt7996/debugfs.c b/drivers/net/wireless/mediatek/mt76/mt7996/debugfs.c index b85c3e549f8b..644abd0a0216 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7996/debugfs.c +++ b/drivers/net/wireless/mediatek/mt76/mt7996/debugfs.c @@ -13,13 +13,6 @@ /** global debugfs **/ -struct hw_queue_map { - const char *name; - u8 index; - u8 pid; - u8 qid; -}; - static int mt7996_implicit_txbf_set(void *data, u64 val) { @@ -604,35 +597,176 @@ mt7996_tx_stats_show(struct seq_file *file, void *data) DEFINE_SHOW_ATTRIBUTE(mt7996_tx_stats); +enum { + MT_QUEUE_PORT_HIF, + MT_QUEUE_PORT_CPU, + MT_QUEUE_PORT_LMAC, + MT_QUEUE_PORT_PLE_CTRL, +}; + +struct mt7996_hw_queue { + const char *name; + u8 pid; + u8 qid; + u8 tgid; +}; + +#define MT7996_HW_QUEUE(_name, _pid, _qid, _tgid) \ + { .name = _name, .pid = MT_QUEUE_PORT_##_pid, .qid = _qid, .tgid = _tgid } + +static const struct mt7996_hw_queue mt7996_ple_queues[32] = { + [0] = MT7996_HW_QUEUE("CPU Q0", CPU, 0, 0), + [1] = MT7996_HW_QUEUE("CPU Q1", CPU, 1, 0), + [2] = MT7996_HW_QUEUE("CPU Q2", CPU, 2, 0), + [3] = MT7996_HW_QUEUE("CPU Q3", CPU, 3, 0), + [4] = MT7996_HW_QUEUE("ALTX Q0", LMAC, 0x10, 0), + [5] = MT7996_HW_QUEUE("BMC Q0", LMAC, 0x11, 0), + [6] = MT7996_HW_QUEUE("BCN Q0", LMAC, 0x12, 0), + [7] = MT7996_HW_QUEUE("PSMP Q0", LMAC, 0x13, 0), + [8] = MT7996_HW_QUEUE("ALTX Q1", LMAC, 0x10, 1), + [9] = MT7996_HW_QUEUE("BMC Q1", LMAC, 0x11, 1), + [10] = MT7996_HW_QUEUE("BCN Q1", LMAC, 0x12, 1), + [11] = MT7996_HW_QUEUE("PSMP Q1", LMAC, 0x13, 1), + [12] = MT7996_HW_QUEUE("ALTX Q2", LMAC, 0x1c, 2), + [13] = MT7996_HW_QUEUE("BMC Q2", LMAC, 0x1d, 2), + [14] = MT7996_HW_QUEUE("BCN Q2", LMAC, 0x1e, 2), + [15] = MT7996_HW_QUEUE("PSMP Q2", LMAC, 0x1f, 2), + [16] = MT7996_HW_QUEUE("NAF Q", LMAC, 0x18, 0), + [17] = MT7996_HW_QUEUE("NBCN Q", LMAC, 0x19, 0), + [20] = MT7996_HW_QUEUE("FIXFID Q", LMAC, 0x1a, 0), + [28] = MT7996_HW_QUEUE("RLS4 Q", PLE_CTRL, 0x7c, 0), + [29] = MT7996_HW_QUEUE("RLS3 Q", PLE_CTRL, 0x7d, 0), + [30] = MT7996_HW_QUEUE("RLS2 Q", PLE_CTRL, 0x7e, 0), + [31] = MT7996_HW_QUEUE("RLS Q", PLE_CTRL, 0x7f, 0), +}; + +static const struct mt7996_hw_queue mt7996_pse_queues[32] = { + [0] = MT7996_HW_QUEUE("CPU Q0", CPU, 0, 0), + [1] = MT7996_HW_QUEUE("CPU Q1", CPU, 1, 0), + [2] = MT7996_HW_QUEUE("CPU Q2", CPU, 2, 0), + [3] = MT7996_HW_QUEUE("CPU Q3", CPU, 3, 0), + [16] = MT7996_HW_QUEUE("LMAC Q", LMAC, 0, 0), + [17] = MT7996_HW_QUEUE("MDP TX Q0", LMAC, 1, 0), + [18] = MT7996_HW_QUEUE("MDP RX Q", LMAC, 2, 0), + [19] = MT7996_HW_QUEUE("SEC TX Q0", LMAC, 3, 0), + [20] = MT7996_HW_QUEUE("SEC RX Q", LMAC, 4, 0), + [21] = MT7996_HW_QUEUE("SFD PARK Q", LMAC, 5, 0), + [22] = MT7996_HW_QUEUE("MDP TXIOC Q0", LMAC, 6, 0), + [23] = MT7996_HW_QUEUE("MDP RXIOC Q0", LMAC, 7, 0), + [24] = MT7996_HW_QUEUE("MDP TX Q1", LMAC, 0x11, 0), + [25] = MT7996_HW_QUEUE("SEC TX Q1", LMAC, 0x13, 0), + [26] = MT7996_HW_QUEUE("MDP TXIOC Q1", LMAC, 0x16, 0), + [27] = MT7996_HW_QUEUE("MDP RXIOC Q1", LMAC, 0x17, 0), + [28] = MT7996_HW_QUEUE("CPU Q4", CPU, 4, 0), + [31] = MT7996_HW_QUEUE("RLS Q", PLE_CTRL, 0x1f, 0), +}; + +static const struct mt7996_hw_queue mt7996_pse_queues_1[32] = { + [0] = MT7996_HW_QUEUE("MDP TDPIOC Q0", LMAC, 0x08, 0), + [1] = MT7996_HW_QUEUE("MDP RDPIOC Q0", LMAC, 0x09, 0), + [2] = MT7996_HW_QUEUE("MDP TDPIOC Q1", LMAC, 0x18, 0), + [3] = MT7996_HW_QUEUE("MDP RDPIOC Q1", LMAC, 0x19, 0), + [4] = MT7996_HW_QUEUE("MDP TDPIOC Q2", LMAC, 0x28, 0), + [5] = MT7996_HW_QUEUE("MDP RDPIOC Q2", LMAC, 0x29, 0), + [7] = MT7996_HW_QUEUE("MDP RDPIOC Q3", LMAC, 0x39, 0), + [8] = MT7996_HW_QUEUE("MDP TX Q2", LMAC, 0x21, 0), + [9] = MT7996_HW_QUEUE("SEC TX Q2", LMAC, 0x23, 0), + [10] = MT7996_HW_QUEUE("MDP TXIOC Q2", LMAC, 0x26, 0), + [11] = MT7996_HW_QUEUE("MDP RXIOC Q2", LMAC, 0x27, 0), + [15] = MT7996_HW_QUEUE("MDP RXIOC Q3", LMAC, 0x37, 0), + [16] = MT7996_HW_QUEUE("HIF Q0", HIF, 0, 0), + [17] = MT7996_HW_QUEUE("HIF Q1", HIF, 1, 0), + [18] = MT7996_HW_QUEUE("HIF Q2", HIF, 2, 0), + [19] = MT7996_HW_QUEUE("HIF Q3", HIF, 3, 0), + [20] = MT7996_HW_QUEUE("HIF Q4", HIF, 4, 0), + [21] = MT7996_HW_QUEUE("HIF Q5", HIF, 5, 0), + [22] = MT7996_HW_QUEUE("HIF Q6", HIF, 6, 0), + [23] = MT7996_HW_QUEUE("HIF Q7", HIF, 7, 0), + [24] = MT7996_HW_QUEUE("HIF Q8", HIF, 8, 0), + [25] = MT7996_HW_QUEUE("HIF Q9", HIF, 9, 0), + [26] = MT7996_HW_QUEUE("HIF Q10", HIF, 10, 0), + [27] = MT7996_HW_QUEUE("HIF Q11", HIF, 11, 0), + [28] = MT7996_HW_QUEUE("HIF Q12", HIF, 12, 0), + [29] = MT7996_HW_QUEUE("HIF Q13", HIF, 13, 0), +}; + static void -mt7996_hw_queue_read(struct seq_file *s, u32 size, - const struct hw_queue_map *map) +mt7996_fl_queue_show(struct seq_file *s, struct mt7996_dev *dev, bool pse, + const struct mt7996_hw_queue *q, u16 wlan_idx) { - struct mt7996_phy *phy = s->private; - struct mt7996_dev *dev = phy->dev; - u32 i, val; + static DEFINE_SPINLOCK(lock); + u32 val, fid, num; + + val = MT_FL_Q0_CTRL_EXECUTE | + u32_encode_bits(q->qid, MT_FL_Q0_CTRL_QID) | + u32_encode_bits(q->tgid, MT_FL_Q0_CTRL_TGID) | + u32_encode_bits(q->pid, MT_FL_Q0_CTRL_PID) | + u32_encode_bits(wlan_idx, MT_FL_Q0_CTRL_WLAN_IDX); + + spin_lock(&lock); + mt76_wr(dev, pse ? MT_PSE_FL_Q0_CTRL : MT_FL_Q0_CTRL, val); + fid = mt76_rr(dev, pse ? MT_PSE_FL_Q2_CTRL : MT_FL_Q2_CTRL); + num = mt76_rr(dev, pse ? MT_PSE_FL_Q3_CTRL : MT_FL_Q3_CTRL); + spin_unlock(&lock); + + seq_printf(s, "tail/head fid 0x%04x/0x%04x, packets %u", + u32_get_bits(fid, MT_FL_Q2_CTRL_TAIL_FID), + u32_get_bits(fid, MT_FL_Q2_CTRL_HEAD_FID), + u32_get_bits(num, MT_FL_Q3_CTRL_PKT_NUM)); +} - val = mt76_rr(dev, MT_FL_Q_EMPTY); - for (i = 0; i < size; i++) { - u32 ctrl, head, tail, queued; +static void +mt7996_fl_queues_show(struct seq_file *s, struct mt7996_dev *dev, bool pse, + const struct mt7996_hw_queue *queues, unsigned long empty) +{ + unsigned int i; - if (val & BIT(map[i].index)) + for_each_clear_bit(i, &empty, 32) { + if (!queues[i].name) continue; - ctrl = BIT(31) | (map[i].pid << 10) | ((u32)map[i].qid << 24); - mt76_wr(dev, MT_FL_Q0_CTRL, ctrl); + seq_printf(s, "\t%s: ", queues[i].name); + mt7996_fl_queue_show(s, dev, pse, &queues[i], 0); + seq_puts(s, "\n"); + } +} + +static void +mt7996_freepg_show(struct seq_file *s, u32 cnt, u32 head_tail) +{ + seq_printf(s, "\tfree pages 0x%04x, free for all 0x%04x, head/tail 0x%04x/0x%04x\n", + u32_get_bits(cnt, MT_FREEPG_CNT_FREE), + u32_get_bits(cnt, MT_FREEPG_CNT_FFA), + u32_get_bits(head_tail, MT_FREEPG_HEAD_TAIL_HEAD), + u32_get_bits(head_tail, MT_FREEPG_HEAD_TAIL_TAIL)); +} + +static void +mt7996_pg_group_show(struct seq_file *s, const char *name, u32 group, u32 info) +{ + seq_printf(s, "\t%s group: max/min quota 0x%04x/0x%04x, used/reserved 0x%04x/0x%04x\n", + name, u32_get_bits(group, MT_PG_GROUP_MAX_QUOTA), + u32_get_bits(group, MT_PG_GROUP_MIN_QUOTA), + u32_get_bits(info, MT_PG_INFO_SRC_CNT), + u32_get_bits(info, MT_PG_INFO_RSV_CNT)); +} + +static unsigned int +mt7996_ple_sta_cr_num(struct mt7996_dev *dev) +{ + return is_mt7996(&dev->mt76) ? 34 : 17; +} - head = mt76_get_field(dev, MT_FL_Q2_CTRL, - GENMASK(11, 0)); - tail = mt76_get_field(dev, MT_FL_Q2_CTRL, - GENMASK(27, 16)); - queued = mt76_get_field(dev, MT_FL_Q3_CTRL, - GENMASK(11, 0)); +static unsigned int +mt7996_ple_sta_cr(struct mt7996_dev *dev, unsigned int n) +{ + /* MT7992 and MT7990 keep the last station group in the + * extension register that follows the first 32 groups + */ + if (!is_mt7996(&dev->mt76) && n == mt7996_ple_sta_cr_num(dev) - 1) + return 32; - seq_printf(s, "\t%s: ", map[i].name); - seq_printf(s, "queued:0x%03x head:0x%03x tail:0x%03x\n", - queued, head, tail); - } + return n; } static void @@ -640,51 +774,53 @@ mt7996_sta_hw_queue_read(void *data, struct ieee80211_sta *sta) { struct mt7996_sta *msta = (struct mt7996_sta *)sta->drv_priv; struct mt7996_vif *mvif = msta->vif; - struct mt7996_phy *phy = mt7996_vif_link_phy(&mvif->deflink); struct ieee80211_link_sta *link_sta; struct seq_file *s = data; struct ieee80211_vif *vif; - struct mt7996_dev *dev; unsigned int link_id; - if (!phy) - return; - vif = container_of((void *)mvif, struct ieee80211_vif, drv_priv); - dev = phy->dev; rcu_read_lock(); for_each_sta_active_link(vif, sta, link_sta, link_id) { struct mt7996_sta_link *msta_link; struct mt76_vif_link *mlink; + struct mt7996_phy *phy; + unsigned int cr; + u16 wlan_idx; u8 ac; mlink = rcu_dereference(mvif->mt76.link[link_id]); if (!mlink) continue; + phy = mt7996_vif_link_phy(container_of(mlink, + struct mt7996_vif_link, + mt76)); + if (!phy) + continue; + msta_link = mt7996_sta_link(msta, link_id); if (!msta_link) continue; - for (ac = 0; ac < 4; ac++) { - u32 idx = msta_link->wcid.idx >> 5, qlen, ctrl, val; - u8 offs = msta_link->wcid.idx & GENMASK(4, 0); - - ctrl = BIT(31) | BIT(11) | (ac << 24); - val = mt76_rr(dev, MT_PLE_AC_QEMPTY(ac, idx)); + wlan_idx = msta_link->wcid.idx; + cr = mt7996_ple_sta_cr(phy->dev, wlan_idx / 32); + for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) { + struct mt7996_hw_queue q = { + .pid = MT_QUEUE_PORT_LMAC, + .qid = ac, + }; - if (val & BIT(offs)) + if (mt76_rr(phy->dev, MT_PLE_AC_QEMPTY(ac, cr)) & + BIT(wlan_idx % 32)) continue; - mt76_wr(dev, - MT_FL_Q0_CTRL, ctrl | msta_link->wcid.idx); - qlen = mt76_get_field(dev, MT_FL_Q3_CTRL, - GENMASK(11, 0)); - seq_printf(s, "\tSTA %pM wcid %d: AC%d%d queued:%d\n", - sta->addr, msta_link->wcid.idx, - mlink->wmm_idx, ac, qlen); + seq_printf(s, "\tSTA %pM wcid %u AC%u%u: ", sta->addr, + wlan_idx, mlink->wmm_idx, ac); + mt7996_fl_queue_show(s, phy->dev, false, &q, wlan_idx); + seq_puts(s, "\n"); } } @@ -692,78 +828,27 @@ mt7996_sta_hw_queue_read(void *data, struct ieee80211_sta *sta) } static int -mt7996_hw_queues_show(struct seq_file *file, void *data) +mt7996_hw_queues_show(struct seq_file *s, void *data) { - struct mt7996_dev *dev = file->private; - struct mt7996_phy *phy = &dev->phy; - static const struct hw_queue_map ple_queue_map[] = { - { "CPU_Q0", 0, 1, MT_CTX0 }, - { "CPU_Q1", 1, 1, MT_CTX0 + 1 }, - { "CPU_Q2", 2, 1, MT_CTX0 + 2 }, - { "CPU_Q3", 3, 1, MT_CTX0 + 3 }, - { "ALTX_Q0", 8, 2, MT_LMAC_ALTX0 }, - { "BMC_Q0", 9, 2, MT_LMAC_BMC0 }, - { "BCN_Q0", 10, 2, MT_LMAC_BCN0 }, - { "PSMP_Q0", 11, 2, MT_LMAC_PSMP0 }, - { "ALTX_Q1", 12, 2, MT_LMAC_ALTX0 + 4 }, - { "BMC_Q1", 13, 2, MT_LMAC_BMC0 + 4 }, - { "BCN_Q1", 14, 2, MT_LMAC_BCN0 + 4 }, - { "PSMP_Q1", 15, 2, MT_LMAC_PSMP0 + 4 }, - }; - static const struct hw_queue_map pse_queue_map[] = { - { "CPU Q0", 0, 1, MT_CTX0 }, - { "CPU Q1", 1, 1, MT_CTX0 + 1 }, - { "CPU Q2", 2, 1, MT_CTX0 + 2 }, - { "CPU Q3", 3, 1, MT_CTX0 + 3 }, - { "HIF_Q0", 8, 0, MT_HIF0 }, - { "HIF_Q1", 9, 0, MT_HIF0 + 1 }, - { "HIF_Q2", 10, 0, MT_HIF0 + 2 }, - { "HIF_Q3", 11, 0, MT_HIF0 + 3 }, - { "HIF_Q4", 12, 0, MT_HIF0 + 4 }, - { "HIF_Q5", 13, 0, MT_HIF0 + 5 }, - { "LMAC_Q", 16, 2, 0 }, - { "MDP_TXQ", 17, 2, 1 }, - { "MDP_RXQ", 18, 2, 2 }, - { "SEC_TXQ", 19, 2, 3 }, - { "SEC_RXQ", 20, 2, 4 }, - }; - u32 val, head, tail; - - /* ple queue */ - val = mt76_rr(dev, MT_PLE_FREEPG_CNT); - head = mt76_get_field(dev, MT_PLE_FREEPG_HEAD_TAIL, GENMASK(11, 0)); - tail = mt76_get_field(dev, MT_PLE_FREEPG_HEAD_TAIL, GENMASK(27, 16)); - seq_puts(file, "PLE page info:\n"); - seq_printf(file, - "\tTotal free page: 0x%08x head: 0x%03x tail: 0x%03x\n", - val, head, tail); - - val = mt76_rr(dev, MT_PLE_PG_HIF_GROUP); - head = mt76_get_field(dev, MT_PLE_HIF_PG_INFO, GENMASK(11, 0)); - tail = mt76_get_field(dev, MT_PLE_HIF_PG_INFO, GENMASK(27, 16)); - seq_printf(file, "\tHIF free page: 0x%03x res: 0x%03x used: 0x%03x\n", - val, head, tail); - - seq_puts(file, "PLE non-empty queue info:\n"); - mt7996_hw_queue_read(file, ARRAY_SIZE(ple_queue_map), - &ple_queue_map[0]); - - /* iterate per-sta ple queue */ - ieee80211_iterate_stations_atomic(phy->mt76->hw, - mt7996_sta_hw_queue_read, file); - phy = mt7996_phy2(dev); - if (phy) - ieee80211_iterate_stations_atomic(phy->mt76->hw, - mt7996_sta_hw_queue_read, file); - phy = mt7996_phy3(dev); - if (phy) - ieee80211_iterate_stations_atomic(phy->mt76->hw, - mt7996_sta_hw_queue_read, file); - - /* pse queue */ - seq_puts(file, "PSE non-empty queue info:\n"); - mt7996_hw_queue_read(file, ARRAY_SIZE(pse_queue_map), - &pse_queue_map[0]); + struct mt7996_dev *dev = s->private; + + seq_puts(s, "PLE page info:\n"); + mt7996_freepg_show(s, mt76_rr(dev, MT_PLE_FREEPG_CNT), + mt76_rr(dev, MT_PLE_FREEPG_HEAD_TAIL)); + mt7996_pg_group_show(s, "HIF", mt76_rr(dev, MT_PLE_PG_HIF_GROUP), + mt76_rr(dev, MT_PLE_HIF_PG_INFO)); + + seq_puts(s, "PLE non-empty queue info:\n"); + mt7996_fl_queues_show(s, dev, false, mt7996_ple_queues, + mt76_rr(dev, MT_FL_Q_EMPTY)); + ieee80211_iterate_stations_atomic(dev->mphy.hw, + mt7996_sta_hw_queue_read, s); + + seq_puts(s, "PSE non-empty queue info:\n"); + mt7996_fl_queues_show(s, dev, true, mt7996_pse_queues, + mt76_rr(dev, MT_PSE_QUEUE_EMPTY)); + mt7996_fl_queues_show(s, dev, true, mt7996_pse_queues_1, + mt76_rr(dev, MT_PSE_QUEUE_EMPTY_1)); return 0; } diff --git a/drivers/net/wireless/mediatek/mt76/mt7996/init.c b/drivers/net/wireless/mediatek/mt76/mt7996/init.c index c1d860029801..36944c096e40 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7996/init.c +++ b/drivers/net/wireless/mediatek/mt76/mt7996/init.c @@ -1810,6 +1810,8 @@ int mt7996_register_device(struct mt7996_dev *dev) void mt7996_unregister_device(struct mt7996_dev *dev) { + int i; + cancel_work_sync(&dev->dump_work); cancel_work_sync(&dev->wed_rro.work); cancel_work_sync(&dev->reset_work); @@ -1820,6 +1822,10 @@ void mt7996_unregister_device(struct mt7996_dev *dev) mt7996_coredump_unregister(dev); mt76_unregister_device(&dev->mt76); mt7996_wed_rro_free(dev); + for (i = 0; i < ARRAY_SIZE(dev->mt76.napi); i++) { + if (dev->mt76.napi[i].dev) + napi_disable(&dev->mt76.napi[i]); + } mt7996_mcu_exit(dev); mt7996_tx_token_put(dev); mt7996_dma_cleanup(dev); diff --git a/drivers/net/wireless/mediatek/mt76/mt7996/mac.c b/drivers/net/wireless/mediatek/mt76/mt7996/mac.c index a9558381ad91..ce1e4773bddd 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7996/mac.c +++ b/drivers/net/wireless/mediatek/mt76/mt7996/mac.c @@ -1057,7 +1057,7 @@ int mt7996_tx_prepare_skb(struct mt76_dev *mdev, void *txwi_ptr, if (!wcid) wcid = &dev->mt76.global_wcid; - if ((is_8023 || ieee80211_is_data_qos(hdr->frame_control)) && sta->mlo && + if (sta && (is_8023 || ieee80211_is_data_qos(hdr->frame_control)) && sta->mlo && likely(tx_info->skb->protocol != cpu_to_be16(ETH_P_PAE))) { u8 tid = tx_info->skb->priority & IEEE80211_QOS_CTL_TID_MASK; @@ -1097,7 +1097,7 @@ int mt7996_tx_prepare_skb(struct mt76_dev *mdev, void *txwi_ptr, * compatible with 802.11 EAPOL frame, we do the translation by * software */ - if (tx_info->skb->protocol == cpu_to_be16(ETH_P_PAE) && sta->mlo) { + if (sta && tx_info->skb->protocol == cpu_to_be16(ETH_P_PAE) && sta->mlo) { struct ieee80211_hdr *hdr = (void *)tx_info->skb->data; struct ieee80211_bss_conf *link_conf; struct ieee80211_link_sta *link_sta; @@ -1503,7 +1503,8 @@ mt7996_mac_add_txs_skb(struct mt7996_dev *dev, struct mt76_wcid *wcid, } } - if (mtk_wed_device_active(&dev->mt76.mmio.wed) && wcid->sta) { + if ((mtk_wed_device_active(&dev->mt76.mmio.wed) || + mt76_npu_device_active(&dev->mt76)) && wcid->sta) { struct ieee80211_sta *sta; u8 tid; @@ -1936,6 +1937,9 @@ void mt7996_rro_rx_process(struct mt76_dev *mdev, void *data) struct mt7996_msdu_page *p = NULL; int i, seq_num = 0; + if (seq_id > MT7996_RRO_MAX_SESSION) + return; + for (i = 0; i < ind_count; i++) { struct mt7996_wed_rro_addr *e; struct mt76_rx_status *status; @@ -2463,6 +2467,7 @@ mt7996_mac_full_reset(struct mt7996_dev *dev) dev->recovery.hw_full_reset = true; + set_bit(MT76_RESTART, &dev->mphy.state); set_bit(MT76_MCU_RESET, &dev->mphy.state); wake_up(&dev->mt76.mcu.wait); ieee80211_stop_queues(hw); @@ -2944,6 +2949,10 @@ void mt7996_mac_sta_rc_work(struct work_struct *work) changed = msta_link->changed; msta_link->changed = 0; + + if (!msta_link->connected) + continue; + mvif = msta_link->sta->vif; vif = container_of((void *)mvif, struct ieee80211_vif, drv_priv); diff --git a/drivers/net/wireless/mediatek/mt76/mt7996/main.c b/drivers/net/wireless/mediatek/mt76/mt7996/main.c index dd7a01c02a7c..335612c967dd 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7996/main.c +++ b/drivers/net/wireless/mediatek/mt76/mt7996/main.c @@ -34,6 +34,11 @@ int mt7996_run(struct mt7996_phy *phy) if (ret) return ret; + ret = mt7996_mcu_set_tx_power_ctrl(phy, UNI_TXPOWER_SKU_POWER_LIMIT_CTRL, + true); + if (ret) + return ret; + set_bit(MT76_STATE_RUNNING, &phy->mt76->state); ieee80211_queue_delayed_work(dev->mphy.hw, &phy->mt76->mac_work, @@ -54,6 +59,8 @@ static int mt7996_start(struct ieee80211_hw *hw) flush_work(&dev->init_work); + clear_bit(MT76_RESTART, &dev->mphy.state); + mutex_lock(&dev->mt76.mutex); ret = mt7996_mcu_set_hdr_trans(dev, true); if (!ret && !is_mt7996(&dev->mt76)) { @@ -286,6 +293,9 @@ mt7996_key_iter(struct ieee80211_hw *hw, struct ieee80211_vif *vif, if (sta) return; + if (key->link_id >= 0 && key->link_id != it->link_id) + return; + WARN_ON(mt7996_set_hw_key(hw, it->cmd, vif, NULL, it->link_id, key)); } @@ -307,15 +317,15 @@ int mt7996_vif_link_add(struct mt76_phy *mphy, struct ieee80211_vif *vif, if ((mvif->mt76.valid_links & BIT(link_conf->link_id)) && !mlink->offchannel) { - if (vif->type == NL80211_IFTYPE_AP) - return mt7996_mcu_mld_link_oper(dev, link_conf, link, - true); - /* update the link address */ ret = mt7996_mcu_add_dev_info(phy, vif, link_conf, mlink, true); if (ret) return ret; + if (vif->type == NL80211_IFTYPE_AP) + return mt7996_mcu_mld_link_oper(dev, link_conf, link, + true); + return mt7996_mcu_add_bss_info(phy, vif, link_conf, mlink, msta_link, true); } @@ -333,6 +343,7 @@ int mt7996_vif_link_add(struct mt76_phy *mphy, struct ieee80211_vif *vif, return -ENOSPC; link->mld_idx = mld_idx; + eth_zero_addr(link->bmc_bssid); mlink->omac_idx = idx; mlink->band_idx = band_idx; mlink->wmm_idx = vif->type == NL80211_IFTYPE_AP ? 0 : 3; @@ -565,13 +576,14 @@ static int mt7996_add_interface(struct ieee80211_hw *hw, for (i = 0; i < MT7996_MAX_RADIOS; i++) { struct mt7996_phy *phy = dev->radio_phy[i]; - if (!phy || !(wdev->radio_mask & BIT(i)) || - test_bit(MT76_STATE_RUNNING, &phy->mt76->state)) + if (!phy || !(wdev->radio_mask & BIT(i))) continue; - err = mt7996_run(phy); - if (err) - goto out; + if (!test_bit(MT76_STATE_RUNNING, &phy->mt76->state)) { + err = mt7996_run(phy); + if (err) + goto out; + } if (vif->type == NL80211_IFTYPE_MONITOR) mt7996_set_monitor(phy, true); @@ -896,6 +908,23 @@ mt7996_update_mu_group(struct ieee80211_hw *hw, struct mt7996_vif_link *link, mt76_wr(dev, MT_WF_PHYRX_BAND_GID_TAB_POS3(band), mu[3]); } +static void +mt7996_vif_link_bss_add(struct mt7996_phy *phy, struct ieee80211_vif *vif, + struct ieee80211_bss_conf *link_conf, + struct mt7996_vif_link *link, bool newly) +{ + if (vif->type == NL80211_IFTYPE_STATION) { + newly = !ether_addr_equal_unaligned(link->bmc_bssid, + link_conf->bssid); + memcpy(link->bmc_bssid, link_conf->bssid, ETH_ALEN); + } + + mt7996_mcu_add_bss_info(phy, vif, link_conf, &link->mt76, + &link->msta_link, true); + mt7996_mcu_add_sta(phy->dev, link_conf, NULL, link, NULL, + CONN_STATE_PORT_SECURE, newly); +} + static void mt7996_vif_cfg_changed(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u64 changed) @@ -927,12 +956,8 @@ mt7996_vif_cfg_changed(struct ieee80211_hw *hw, struct ieee80211_vif *vif, if (!phy) continue; - mt7996_mcu_add_bss_info(phy, vif, link_conf, - &link->mt76, &link->msta_link, - true); - mt7996_mcu_add_sta(dev, link_conf, NULL, link, NULL, - CONN_STATE_PORT_SECURE, - !!(changed & BSS_CHANGED_BSSID)); + mt7996_vif_link_bss_add(phy, vif, link_conf, link, + !!(changed & BSS_CHANGED_BSSID)); } } @@ -978,13 +1003,11 @@ mt7996_link_info_changed(struct ieee80211_hw *hw, struct ieee80211_vif *vif, * and then peer references bss_info_rfch to set bandwidth cap. */ if ((changed & BSS_CHANGED_BSSID && !is_zero_ether_addr(info->bssid)) || - (changed & BSS_CHANGED_BEACON_ENABLED && info->enable_beacon)) { - mt7996_mcu_add_bss_info(phy, vif, info, &link->mt76, - &link->msta_link, true); - mt7996_mcu_add_sta(dev, info, NULL, link, NULL, - CONN_STATE_PORT_SECURE, - !!(changed & BSS_CHANGED_BSSID)); - } + (changed & BSS_CHANGED_BEACON_ENABLED && info->enable_beacon)) + mt7996_vif_link_bss_add(phy, vif, info, link, + !!(changed & BSS_CHANGED_BSSID)); + else if (changed & BSS_CHANGED_BSSID) + eth_zero_addr(link->bmc_bssid); if (changed & BSS_CHANGED_HT || changed & BSS_CHANGED_ERP_CTS_PROT) mt7996_mcu_set_protection(phy, link, info->ht_operation_mode, @@ -1131,9 +1154,90 @@ mt7996_sta_init_txq_wcid(struct ieee80211_sta *sta, int idx) } } +static void +mt7996_sta_deflink_set(struct ieee80211_sta *sta, unsigned int link_id, + int idx) +{ + struct mt7996_sta *msta = (struct mt7996_sta *)sta->drv_priv; + + msta->deflink_id = link_id; + mt7996_sta_init_txq_wcid(sta, idx); +} + +static void +mt7996_sta_link_hdr_trans_set(struct mt7996_sta *msta, + struct mt7996_sta_link *msta_link) +{ + assign_bit(MT_WCID_FLAG_4ADDR, &msta_link->wcid.flags, + test_bit(MT_WCID_FLAG_4ADDR, &msta->wcid_flags)); + assign_bit(MT_WCID_FLAG_HDR_TRANS, &msta_link->wcid.flags, + test_bit(MT_WCID_FLAG_HDR_TRANS, &msta->wcid_flags)); +} + +static bool +mt7996_sta_deflink_busy(struct mt7996_dev *dev, struct mt7996_sta *msta) +{ + unsigned int link_id; + + for (link_id = 0; link_id < ARRAY_SIZE(msta->link); link_id++) { + if (mt7996_sta_link_protected(dev, msta, link_id) == + &msta->deflink) + return true; + } + + return false; +} + +static void +mt7996_sta_deflink_release(struct mt7996_dev *dev, struct ieee80211_sta *sta, + unsigned int link_id) +{ + struct mt7996_sta *msta = (struct mt7996_sta *)sta->drv_priv; + struct mt7996_sta_link *msta_seclink; + + if (msta->deflink_id != link_id) + return; + + msta->deflink_id = IEEE80211_LINK_UNSPECIFIED; + if (msta->seclink_id == link_id) + return; + + /* switch to the secondary link */ + msta_seclink = mt76_dereference(msta->link[msta->seclink_id], + &dev->mt76); + if (msta_seclink) + mt7996_sta_deflink_set(sta, msta->seclink_id, + msta_seclink->wcid.idx); +} + +static u8 +mt7996_sta_seclink_get(struct mt7996_dev *dev, struct mt7996_sta *msta) +{ + struct mt7996_sta_link *msta_link; + unsigned int link_id; + + if (msta->deflink_id == IEEE80211_LINK_UNSPECIFIED) + return IEEE80211_LINK_UNSPECIFIED; + + msta_link = mt7996_sta_link_protected(dev, msta, msta->seclink_id); + if (msta->seclink_id != msta->deflink_id && msta_link && + msta_link->wcid.link_valid) + return msta->seclink_id; + + for (link_id = 0; link_id < ARRAY_SIZE(msta->link); link_id++) { + if (link_id == msta->deflink_id) + continue; + + msta_link = mt7996_sta_link_protected(dev, msta, link_id); + if (msta_link && msta_link->wcid.link_valid) + return link_id; + } + + return msta->deflink_id; +} + static int mt7996_mac_sta_init_link(struct mt7996_dev *dev, - struct ieee80211_bss_conf *link_conf, struct ieee80211_link_sta *link_sta, struct mt7996_vif_link *link, unsigned int link_id) { @@ -1150,25 +1254,23 @@ mt7996_mac_sta_init_link(struct mt7996_dev *dev, if (idx < 0) return -ENOSPC; - if (msta->deflink_id == IEEE80211_LINK_UNSPECIFIED) { - msta_link = &msta->deflink; - msta->deflink_id = link_id; - msta->seclink_id = msta->deflink_id; - mt7996_sta_init_txq_wcid(sta, idx); - } else { + if (mt7996_sta_deflink_busy(dev, msta)) { msta_link = kzalloc_obj(*msta_link); - 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))) - msta->seclink_id = __ffs(sta->valid_links & - ~BIT(msta->deflink_id)); + } + } else { + msta_link = &msta->deflink; } + if (msta->deflink_id == IEEE80211_LINK_UNSPECIFIED) + mt7996_sta_deflink_set(sta, link_id, idx); + INIT_LIST_HEAD(&msta_link->rc_list); INIT_LIST_HEAD(&msta_link->wcid.poll_list); msta_link->sta = msta; + msta_link->connected = false; msta_link->wcid.sta = 1; msta_link->wcid.idx = idx; msta_link->wcid.link_id = link_id; @@ -1178,14 +1280,15 @@ mt7996_mac_sta_init_link(struct mt7996_dev *dev, if (link_sta->sta->tdls) set_bit(MT_WCID_FLAG_TDLS_PEER, &msta_link->wcid.flags); + mt7996_sta_link_hdr_trans_set(msta, msta_link); + ewma_avg_signal_init(&msta_link->avg_ack_signal); ewma_signal_init(&msta_link->wcid.rssi); rcu_assign_pointer(msta->link[link_id], msta_link); + msta->seclink_id = mt7996_sta_seclink_get(dev, msta); mt7996_mac_wtbl_update(dev, idx, MT_WTBL_UPDATE_ADM_COUNT_CLEAR); - mt7996_mcu_add_sta(dev, link_conf, link_sta, link, msta_link, - CONN_STATE_DISCONNECT, true); rcu_assign_pointer(dev->mt76.wcid[idx], &msta_link->wcid); mt76_wcid_init(&msta_link->wcid, phy->mt76->band_idx); @@ -1217,28 +1320,9 @@ void mt7996_mac_sta_remove_link(struct mt7996_dev *dev, mt7996_mac_wtbl_update(dev, msta_link->wcid.idx, MT_WTBL_UPDATE_ADM_COUNT_CLEAR); - if (msta->deflink_id == link_id) { - msta->deflink_id = IEEE80211_LINK_UNSPECIFIED; - if (msta->seclink_id == link_id) { - /* no secondary link available */ - msta->seclink_id = msta->deflink_id; - } else { - struct mt7996_sta_link *msta_seclink; - - /* switch to the secondary link */ - msta_seclink = mt76_dereference( - msta->link[msta->seclink_id], - &dev->mt76); - if (msta_seclink) { - msta->deflink_id = msta->seclink_id; - mt7996_sta_init_txq_wcid(sta, - msta_seclink->wcid.idx); - } - } - } else if (msta->seclink_id == link_id) { - msta->seclink_id = msta->deflink_id; - } + mt7996_sta_deflink_release(dev, sta, link_id); msta_link->wcid.link_valid = false; + msta->seclink_id = mt7996_sta_seclink_get(dev, msta); } if (flush) { @@ -1256,6 +1340,36 @@ void mt7996_mac_sta_remove_link(struct mt7996_dev *dev, } } +u16 mt7996_mac_sta_links(struct mt7996_dev *dev, struct ieee80211_vif *vif, + struct ieee80211_sta *sta) +{ + struct mt7996_sta *msta = (struct mt7996_sta *)sta->drv_priv; + struct ieee80211_link_sta *link_sta; + unsigned int link_id; + u16 links = 0; + + for_each_sta_active_link(vif, sta, link_sta, link_id) { + struct mt7996_sta_link *msta_link; + + msta_link = mt7996_sta_link_protected(dev, msta, link_id); + if (!msta_link) + continue; + + if (sta->valid_links && !msta_link->wcid.link_valid) + continue; + + if (!link_conf_dereference_protected(vif, link_id)) + continue; + + if (!mt7996_vif_link(dev, vif, link_id)) + continue; + + links |= BIT(link_id); + } + + return links; +} + static void mt7996_mac_sta_remove_links(struct mt7996_dev *dev, struct ieee80211_vif *vif, struct ieee80211_sta *sta, unsigned long links, @@ -1272,11 +1386,11 @@ mt7996_mac_sta_add_links(struct mt7996_dev *dev, struct ieee80211_vif *vif, struct ieee80211_sta *sta, unsigned long new_links) { struct mt7996_sta *msta = (struct mt7996_sta *)sta->drv_priv; + unsigned long created = 0, returned = 0; unsigned int link_id; int err = 0; for_each_set_bit(link_id, &new_links, IEEE80211_MLD_MAX_NUM_LINKS) { - struct ieee80211_bss_conf *link_conf; struct ieee80211_link_sta *link_sta; struct mt7996_sta_link *msta_link; struct mt7996_vif_link *link; @@ -1285,11 +1399,16 @@ mt7996_mac_sta_add_links(struct mt7996_dev *dev, struct ieee80211_vif *vif, msta_link = mt76_dereference(msta->link[link_id], &dev->mt76); if (msta_link) { msta_link->wcid.link_valid = true; + mt7996_sta_link_hdr_trans_set(msta, msta_link); + if (msta->deflink_id == IEEE80211_LINK_UNSPECIFIED) + mt7996_sta_deflink_set(sta, link_id, + msta_link->wcid.idx); + msta->seclink_id = mt7996_sta_seclink_get(dev, msta); + returned |= BIT(link_id); continue; } - link_conf = link_conf_dereference_protected(vif, link_id); - if (!link_conf) { + if (!link_conf_dereference_protected(vif, link_id)) { err = -EINVAL; goto error_unlink; } @@ -1312,18 +1431,19 @@ mt7996_mac_sta_add_links(struct mt7996_dev *dev, struct ieee80211_vif *vif, goto error_unlink; } - err = mt7996_mac_sta_init_link(dev, link_conf, link_sta, link, - link_id); + err = mt7996_mac_sta_init_link(dev, link_sta, link, link_id); if (err) goto error_unlink; mphy->num_sta++; + created |= BIT(link_id); } return 0; error_unlink: - mt7996_mac_sta_remove_links(dev, vif, sta, new_links, true); + mt7996_mac_sta_remove_links(dev, vif, sta, created, true); + mt7996_mac_sta_remove_links(dev, vif, sta, returned, false); return err; } @@ -1370,34 +1490,26 @@ mt7996_mac_sta_add(struct mt7996_dev *dev, struct ieee80211_vif *vif, } static int -mt7996_mac_sta_event(struct mt7996_dev *dev, struct ieee80211_vif *vif, - struct ieee80211_sta *sta, enum mt76_sta_event ev) +mt7996_mac_sta_links_event(struct mt7996_dev *dev, struct ieee80211_vif *vif, + struct ieee80211_sta *sta, unsigned long links, + enum mt76_sta_event ev) { struct mt7996_sta *msta = (struct mt7996_sta *)sta->drv_priv; - unsigned long links = sta->valid_links; - struct ieee80211_link_sta *link_sta; + unsigned long iter_links = links; unsigned int link_id; - int err = 0; - - mutex_lock(&dev->mt76.mutex); + int err; - for_each_sta_active_link(vif, sta, link_sta, link_id) { + for_each_set_bit(link_id, &iter_links, IEEE80211_MLD_MAX_NUM_LINKS) { struct ieee80211_bss_conf *link_conf; + struct ieee80211_link_sta *link_sta; struct mt7996_sta_link *msta_link; struct mt7996_vif_link *link; int i; link_conf = link_conf_dereference_protected(vif, link_id); - if (!link_conf) - continue; - - link = mt7996_vif_link(dev, vif, link_id); - if (!link) - continue; - + link_sta = link_sta_dereference_protected(sta, link_id); msta_link = mt7996_sta_link_protected(dev, msta, link_id); - if (!msta_link) - continue; + link = mt7996_vif_link(dev, vif, link_id); switch (ev) { case MT76_STA_EVENT_ASSOC: @@ -1405,12 +1517,13 @@ mt7996_mac_sta_event(struct mt7996_dev *dev, struct ieee80211_vif *vif, link, msta_link, CONN_STATE_CONNECT, true); if (err) - goto unlock; + return err; + msta_link->connected = true; err = mt7996_mcu_add_rate_ctrl(dev, msta_link->sta, vif, link_id, false); if (err) - goto unlock; + return err; msta_link->wcid.tx_info |= MT_WCID_TX_INFO_SET; break; @@ -1419,7 +1532,7 @@ mt7996_mac_sta_event(struct mt7996_dev *dev, struct ieee80211_vif *vif, link, msta_link, CONN_STATE_PORT_SECURE, false); if (err) - goto unlock; + return err; break; case MT76_STA_EVENT_DISASSOC: for (i = 0; i < ARRAY_SIZE(msta_link->twt.flow); i++) @@ -1440,7 +1553,37 @@ mt7996_mac_sta_event(struct mt7996_dev *dev, struct ieee80211_vif *vif, break; } } -unlock: + + return 0; +} + +static void +mt7996_mac_sta_clear_connected(struct mt7996_dev *dev, struct mt7996_sta *msta) +{ + unsigned int link_id; + + for (link_id = 0; link_id < ARRAY_SIZE(msta->link); link_id++) { + struct mt7996_sta_link *msta_link; + + msta_link = mt7996_sta_link_protected(dev, msta, link_id); + if (msta_link) + msta_link->connected = false; + } +} + +static int +mt7996_mac_sta_event(struct mt7996_dev *dev, struct ieee80211_vif *vif, + struct ieee80211_sta *sta, enum mt76_sta_event ev) +{ + struct mt7996_sta *msta = (struct mt7996_sta *)sta->drv_priv; + int err; + + mutex_lock(&dev->mt76.mutex); + err = mt7996_mac_sta_links_event(dev, vif, sta, + mt7996_mac_sta_links(dev, vif, sta), + ev); + if (!err && ev == MT76_STA_EVENT_DISASSOC) + mt7996_mac_sta_clear_connected(dev, msta); mutex_unlock(&dev->mt76.mutex); return err; @@ -1477,6 +1620,30 @@ mt7996_set_active_links(struct ieee80211_vif *vif) ieee80211_set_active_links_async(vif, active_links); } +static void +mt7996_sta_pre_rcu_remove(struct ieee80211_hw *hw, struct ieee80211_vif *vif, + struct ieee80211_sta *sta) +{ + struct mt7996_sta *msta = (struct mt7996_sta *)sta->drv_priv; + struct mt7996_dev *dev = mt7996_hw_dev(hw); + unsigned int link_id; + + mutex_lock(&dev->mt76.mutex); + spin_lock_bh(&dev->mt76.status_lock); + + for (link_id = 0; link_id < ARRAY_SIZE(msta->link); link_id++) { + struct mt7996_sta_link *msta_link; + + msta_link = mt7996_sta_link_protected(dev, msta, link_id); + if (msta_link) + rcu_assign_pointer(dev->mt76.wcid[msta_link->wcid.idx], + NULL); + } + + spin_unlock_bh(&dev->mt76.status_lock); + mutex_unlock(&dev->mt76.mutex); +} + static int mt7996_sta_state(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, enum ieee80211_sta_state old_state, @@ -1884,9 +2051,16 @@ static void mt7996_sta_statistics(struct ieee80211_hw *hw, { struct mt7996_dev *dev = mt7996_hw_dev(hw); struct mt7996_sta *msta = (struct mt7996_sta *)sta->drv_priv; - struct mt7996_sta_link *msta_link = &msta->deflink; - struct rate_info *txrate = &msta_link->wcid.rate; + struct mt7996_sta_link *msta_link; + struct rate_info *txrate; + + rcu_read_lock(); + msta_link = mt7996_sta_link(msta, msta->deflink_id); + if (!msta_link) + goto out; + + txrate = &msta_link->wcid.rate; if (txrate->legacy || txrate->flags) { if (txrate->legacy) { sinfo->txrate.legacy = txrate->legacy; @@ -1929,6 +2103,9 @@ static void mt7996_sta_statistics(struct ieee80211_hw *hw, sinfo->rx_packets = msta_link->wcid.stats.rx_packets; sinfo->filled |= BIT_ULL(NL80211_STA_INFO_RX_PACKETS); } + +out: + rcu_read_unlock(); } static void mt7996_link_rate_ctrl_update(void *data, @@ -2025,6 +2202,7 @@ static void mt7996_sta_set_4addr(struct ieee80211_hw *hw, mutex_lock(&dev->mt76.mutex); + assign_bit(MT_WCID_FLAG_4ADDR, &msta->wcid_flags, enabled); for_each_sta_active_link(vif, sta, link_sta, link_id) { struct mt7996_sta_link *msta_link; struct mt7996_vif_link *link; @@ -2037,12 +2215,8 @@ static void mt7996_sta_set_4addr(struct ieee80211_hw *hw, if (!msta_link) continue; - if (enabled) - set_bit(MT_WCID_FLAG_4ADDR, &msta_link->wcid.flags); - else - clear_bit(MT_WCID_FLAG_4ADDR, &msta_link->wcid.flags); - - if (!msta_link->wcid.sta) + mt7996_sta_link_hdr_trans_set(msta, msta_link); + if (!msta_link->connected) continue; mt7996_mcu_wtbl_update_hdr_trans(dev, vif, link, msta_link); @@ -2071,6 +2245,7 @@ static void mt7996_sta_set_decap_offload(struct ieee80211_hw *hw, mutex_lock(&dev->mt76.mutex); + assign_bit(MT_WCID_FLAG_HDR_TRANS, &msta->wcid_flags, enabled); for_each_sta_active_link(vif, sta, link_sta, link_id) { struct mt7996_sta_link *msta_link; struct mt7996_vif_link *link; @@ -2083,14 +2258,8 @@ static void mt7996_sta_set_decap_offload(struct ieee80211_hw *hw, if (!msta_link) continue; - if (enabled) - set_bit(MT_WCID_FLAG_HDR_TRANS, - &msta_link->wcid.flags); - else - clear_bit(MT_WCID_FLAG_HDR_TRANS, - &msta_link->wcid.flags); - - if (!msta_link->wcid.sta) + mt7996_sta_link_hdr_trans_set(msta, msta_link); + if (!msta_link->connected) continue; mt7996_mcu_wtbl_update_hdr_trans(dev, vif, link, msta_link); @@ -2228,11 +2397,15 @@ static void mt7996_ethtool_worker(void *wi_data, struct ieee80211_sta *sta) { struct mt76_ethtool_worker_info *wi = wi_data; struct mt7996_sta *msta = (struct mt7996_sta *)sta->drv_priv; - struct mt7996_sta_link *msta_link = &msta->deflink; + struct mt7996_sta_link *msta_link; if (msta->vif->deflink.mt76.idx != wi->idx) return; + msta_link = mt7996_sta_link(msta, msta->deflink_id); + if (!msta_link) + return; + mt76_ethtool_worker(wi, &msta_link->wcid.stats, true); } @@ -2568,7 +2741,7 @@ const struct ieee80211_ops mt7996_ops = { .vif_cfg_changed = mt7996_vif_cfg_changed, .link_info_changed = mt7996_link_info_changed, .sta_state = mt7996_sta_state, - .sta_pre_rcu_remove = mt76_sta_pre_rcu_remove, + .sta_pre_rcu_remove = mt7996_sta_pre_rcu_remove, .link_sta_rc_update = mt7996_link_sta_rc_update, .set_key = mt7996_set_key, .ampdu_action = mt7996_ampdu_action, diff --git a/drivers/net/wireless/mediatek/mt76/mt7996/mcu.c b/drivers/net/wireless/mediatek/mt76/mt7996/mcu.c index cd7587ce5b8a..02f9bcfdf5d9 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7996/mcu.c +++ b/drivers/net/wireless/mediatek/mt76/mt7996/mcu.c @@ -488,6 +488,9 @@ mt7996_mcu_ie_countdown(struct mt7996_dev *dev, struct sk_buff *skb) struct mt7996_mcu_countdown_notify *event; struct mt7996_mcu_countdown_data cdata; + if (skb->len < sizeof(*rxd) + sizeof(*hdr)) + return; + if (hdr->band >= ARRAY_SIZE(dev->mt76.phys)) return; @@ -497,9 +500,14 @@ mt7996_mcu_ie_countdown(struct mt7996_dev *dev, struct sk_buff *skb) tail = skb->data + skb->len; data += sizeof(*hdr); - while (data + sizeof(*tlv) < tail && le16_to_cpu(tlv->len)) { - event = (struct mt7996_mcu_countdown_notify *)tlv->data; + while (data + sizeof(*tlv) <= tail) { + u16 tag_len = le16_to_cpu(tlv->len); + + if (tag_len < sizeof(*tlv) + sizeof(*event) || + data + tag_len > tail) + break; + event = (struct mt7996_mcu_countdown_notify *)tlv->data; cdata.omac_idx = event->omac_idx; switch (le16_to_cpu(tlv->tag)) { @@ -517,7 +525,7 @@ mt7996_mcu_ie_countdown(struct mt7996_dev *dev, struct sk_buff *skb) break; } - data += le16_to_cpu(tlv->len); + data += tag_len; tlv = (struct tlv *)data; } } @@ -572,21 +580,32 @@ mt7996_mcu_rx_log_message(struct mt7996_dev *dev, struct sk_buff *skb) { #define UNI_EVENT_FW_LOG_FORMAT 0 struct mt7996_mcu_rxd *rxd = (struct mt7996_mcu_rxd *)skb->data; - const char *data = (char *)&rxd[1] + 4, *type; - struct tlv *tlv = (struct tlv *)data; + const char *data, *type; + struct tlv *tlv; int len; + if (skb->len < sizeof(*rxd)) + return; + if (!(rxd->option & MCU_UNI_CMD_EVENT)) { - len = skb->len - sizeof(*rxd); data = (char *)&rxd[1]; + len = skb->len - sizeof(*rxd); goto out; } + if (skb->len < sizeof(*rxd) + 4 + sizeof(*tlv)) + return; + + tlv = (struct tlv *)((char *)&rxd[1] + 4); if (le16_to_cpu(tlv->tag) != UNI_EVENT_FW_LOG_FORMAT) return; - data += sizeof(*tlv) + 4; + if (le16_to_cpu(tlv->len) < sizeof(*tlv) + 4) + return; + + data = (char *)tlv + sizeof(*tlv) + 4; len = le16_to_cpu(tlv->len) - sizeof(*tlv) - 4; + len = min_t(int, len, skb->len - (int)(data - (char *)skb->data)); out: switch (rxd->s2d_index) { @@ -648,13 +667,38 @@ static void mt7996_mcu_rx_all_sta_info_event(struct mt7996_dev *dev, struct sk_buff *skb) { struct mt7996_mcu_all_sta_info_event *res; + u32 elem_size; + u16 sta_num; u16 i; + if (skb->len < sizeof(struct mt7996_mcu_rxd)) + return; + skb_pull(skb, sizeof(struct mt7996_mcu_rxd)); res = (struct mt7996_mcu_all_sta_info_event *)skb->data; + if (skb->len < sizeof(*res)) + return; + + sta_num = le16_to_cpu(res->sta_num); + switch (le16_to_cpu(res->tag)) { + case UNI_ALL_STA_TXRX_RATE: + elem_size = sizeof(res->rate[0]); + break; + case UNI_ALL_STA_TXRX_ADM_STAT: + elem_size = sizeof(res->adm_stat[0]); + break; + case UNI_ALL_STA_TXRX_MSDU_COUNT: + elem_size = sizeof(res->msdu_cnt[0]); + break; + default: + return; + } + + if (sta_num > (skb->len - sizeof(*res)) / elem_size) + sta_num = (skb->len - sizeof(*res)) / elem_size; - for (i = 0; i < le16_to_cpu(res->sta_num); i++) { + for (i = 0; i < sta_num; i++) { u8 ac; u16 wlan_idx; struct mt76_wcid *wcid; @@ -2715,18 +2759,20 @@ mt7996_mcu_sta_mld_setup_tlv(struct mt7996_dev *dev, struct sk_buff *skb, struct ieee80211_sta *sta) { struct mt7996_sta *msta = (struct mt7996_sta *)sta->drv_priv; - unsigned int nlinks = hweight16(sta->valid_links); + unsigned long links = mt7996_mac_sta_links(dev, vif, sta); + unsigned int nlinks = hweight16(links); struct mld_setup_link *mld_setup_link; - struct ieee80211_link_sta *link_sta; struct sta_rec_mld_setup *mld_setup; struct mt7996_sta_link *msta_link; + u8 seclink_id = msta->deflink_id; unsigned int link_id; struct tlv *tlv; - msta_link = mt7996_sta_link_protected(dev, msta, msta->deflink_id); - if (!msta_link) + if (!(links & BIT(msta->deflink_id))) return; + msta_link = mt7996_sta_link_protected(dev, msta, msta->deflink_id); + tlv = mt76_connac_mcu_add_tlv(skb, STA_REC_MLD, sizeof(struct sta_rec_mld_setup) + sizeof(struct mld_setup_link) * nlinks); @@ -2736,26 +2782,18 @@ mt7996_mcu_sta_mld_setup_tlv(struct mt7996_dev *dev, struct sk_buff *skb, mld_setup->setup_wcid = cpu_to_le16(msta_link->wcid.idx); mld_setup->primary_id = cpu_to_le16(msta_link->wcid.idx); - if (nlinks > 1) { - msta_link = mt7996_sta_link_protected(dev, msta, - msta->seclink_id); - if (!msta_link) - return; - } + if (links & BIT(msta->seclink_id)) + seclink_id = msta->seclink_id; + msta_link = mt7996_sta_link_protected(dev, msta, seclink_id); mld_setup->seconed_id = cpu_to_le16(msta_link->wcid.idx); mld_setup->link_num = nlinks; mld_setup_link = (struct mld_setup_link *)mld_setup->link_info; - for_each_sta_active_link(vif, sta, link_sta, link_id) { + for_each_set_bit(link_id, &links, IEEE80211_MLD_MAX_NUM_LINKS) { struct mt7996_vif_link *link; msta_link = mt7996_sta_link_protected(dev, msta, link_id); - if (!msta_link) - continue; - link = mt7996_vif_link(dev, vif, link_id); - if (!link) - continue; mld_setup_link->wcid = cpu_to_le16(msta_link->wcid.idx); mld_setup_link->bss_idx = link->mt76.idx; @@ -5444,6 +5482,40 @@ int mt7996_mcu_set_sniffer_mode(struct mt7996_phy *phy, bool enabled) sizeof(req), true); } +int mt7996_mcu_set_tx_power_ctrl(struct mt7996_phy *phy, u8 power_ctrl_id, u8 data) +{ + struct mt7996_dev *dev = phy->dev; + struct tx_power_ctrl req = { + .tag = cpu_to_le16(power_ctrl_id), + .len = cpu_to_le16(sizeof(req) - 4), + .power_ctrl_id = power_ctrl_id, + .band_idx = phy->mt76->band_idx, + }; + + switch (power_ctrl_id) { + case UNI_TXPOWER_SKU_POWER_LIMIT_CTRL: + req.sku_enable = !!data; + break; + case UNI_TXPOWER_PERCENTAGE_CTRL: + req.percentage_ctrl_enable = !!data; + break; + case UNI_TXPOWER_PERCENTAGE_DROP_CTRL: + req.power_drop_level = data; + break; + case UNI_TXPOWER_BACKOFF_POWER_LIMIT_CTRL: + req.bf_backoff_enable = !!data; + break; + case UNI_TXPOWER_ATE_MODE_CTRL: + req.ate_mode_enable = !!data; + break; + default: + return -EINVAL; + } + + return mt76_mcu_send_msg(&dev->mt76, MCU_WM_UNI_CMD(TXPOWER), + &req, sizeof(req), false); +} + int mt7996_mcu_set_txpower_sku(struct mt7996_phy *phy) { #define TX_POWER_LIMIT_TABLE_RATE 0 diff --git a/drivers/net/wireless/mediatek/mt76/mt7996/mcu.h b/drivers/net/wireless/mediatek/mt76/mt7996/mcu.h index 1b272e904100..6078f8811b1e 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7996/mcu.h +++ b/drivers/net/wireless/mediatek/mt76/mt7996/mcu.h @@ -1039,8 +1039,31 @@ enum { UNI_CMD_THERMAL_PROTECT_DUTY_CONFIG, }; +struct tx_power_ctrl { + u8 _rsv[4]; + + __le16 tag; + __le16 len; + + u8 power_ctrl_id; + union { + bool sku_enable; + bool ate_mode_enable; + bool percentage_ctrl_enable; + bool bf_backoff_enable; + u8 power_drop_level; + }; + u8 band_idx; + u8 rsv[1]; +} __packed; + enum { + UNI_TXPOWER_SKU_POWER_LIMIT_CTRL = 0, + UNI_TXPOWER_PERCENTAGE_CTRL = 1, + UNI_TXPOWER_PERCENTAGE_DROP_CTRL = 2, + UNI_TXPOWER_BACKOFF_POWER_LIMIT_CTRL = 3, UNI_TXPOWER_POWER_LIMIT_TABLE_CTRL = 4, + UNI_TXPOWER_ATE_MODE_CTRL = 6, }; enum { diff --git a/drivers/net/wireless/mediatek/mt76/mt7996/mt7996.h b/drivers/net/wireless/mediatek/mt76/mt7996/mt7996.h index 2a0cdb56f822..ec453f5ff3a5 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7996/mt7996.h +++ b/drivers/net/wireless/mediatek/mt76/mt7996/mt7996.h @@ -244,6 +244,7 @@ struct mt7996_sta_link { struct mt76_wcid wcid; /* must be first */ struct mt7996_sta *sta; + bool connected; struct list_head rc_list; u32 airtime_ac[8]; @@ -269,6 +270,8 @@ struct mt7996_sta { u8 deflink_id; u8 seclink_id; + unsigned long wcid_flags; + struct mt7996_vif *vif; }; @@ -279,6 +282,7 @@ struct mt7996_vif_link { struct cfg80211_bitrate_mask bitrate_mask; u8 mld_idx; + u8 bmc_bssid[ETH_ALEN]; }; struct mt7996_vif_link_info { @@ -778,6 +782,7 @@ int mt7996_mcu_get_temperature(struct mt7996_phy *phy); int mt7996_mcu_set_thermal_throttling(struct mt7996_phy *phy, u8 state); int mt7996_mcu_set_thermal_protect(struct mt7996_phy *phy, bool enable); int mt7996_mcu_set_txpower_sku(struct mt7996_phy *phy); +int mt7996_mcu_set_tx_power_ctrl(struct mt7996_phy *phy, u8 power_ctrl_id, u8 data); int mt7996_mcu_rdd_resume_tx(struct mt7996_phy *phy); int mt7996_mcu_rdd_cmd(struct mt7996_dev *dev, int cmd, u8 rdd_idx, u8 val); int mt7996_mcu_rdd_background_enable(struct mt7996_phy *phy, @@ -893,6 +898,8 @@ void mt7996_mac_twt_teardown_flow(struct mt7996_dev *dev, void mt7996_mac_sta_remove_link(struct mt7996_dev *dev, struct ieee80211_sta *sta, unsigned int link_id, bool flush); +u16 mt7996_mac_sta_links(struct mt7996_dev *dev, struct ieee80211_vif *vif, + struct ieee80211_sta *sta); void mt7996_mac_add_twt_setup(struct ieee80211_hw *hw, struct ieee80211_sta *sta, struct ieee80211_twt_setup *twt); diff --git a/drivers/net/wireless/mediatek/mt76/mt7996/regs.h b/drivers/net/wireless/mediatek/mt76/mt7996/regs.h index 8ff78cf6eb04..6df6e4c3d45d 100644 --- a/drivers/net/wireless/mediatek/mt76/mt7996/regs.h +++ b/drivers/net/wireless/mediatek/mt76/mt7996/regs.h @@ -155,14 +155,42 @@ enum offs_rev { #define MT_FL_Q2_CTRL MT_PLE(0x3e8) #define MT_FL_Q3_CTRL MT_PLE(0x3ec) -#define MT_PLE_FREEPG_CNT MT_PLE(0x380) -#define MT_PLE_FREEPG_HEAD_TAIL MT_PLE(0x384) +#define MT_FL_Q0_CTRL_EXECUTE BIT(31) +#define MT_FL_Q0_CTRL_QID GENMASK(30, 24) +#define MT_FL_Q0_CTRL_TGID GENMASK(21, 20) +#define MT_FL_Q0_CTRL_PID GENMASK(17, 16) +#define MT_FL_Q0_CTRL_WLAN_IDX GENMASK(11, 0) +#define MT_FL_Q2_CTRL_TAIL_FID GENMASK(28, 16) +#define MT_FL_Q2_CTRL_HEAD_FID GENMASK(12, 0) +#define MT_FL_Q3_CTRL_PKT_NUM GENMASK(12, 0) + +#define MT_PLE_FREEPG_CNT MT_PLE(0x3a0) +#define MT_PLE_FREEPG_HEAD_TAIL MT_PLE(0x3a4) #define MT_PLE_PG_HIF_GROUP MT_PLE(0x00c) -#define MT_PLE_HIF_PG_INFO MT_PLE(0x388) +#define MT_PLE_HIF_PG_INFO MT_PLE(0x3a8) -#define MT_PLE_AC_QEMPTY(ac, n) MT_PLE(0x600 + 0x80 * (ac) + ((n) << 2)) +#define MT_PLE_AC_QEMPTY(ac, n) MT_PLE(0x600 + 0x100 * (ac) + ((n) << 2)) #define MT_PLE_AMSDU_PACK_MSDU_CNT(n) MT_PLE(0x10e0 + ((n) << 2)) +#define MT_FREEPG_CNT_FFA GENMASK(28, 16) +#define MT_FREEPG_CNT_FREE GENMASK(12, 0) +#define MT_FREEPG_HEAD_TAIL_TAIL GENMASK(28, 16) +#define MT_FREEPG_HEAD_TAIL_HEAD GENMASK(12, 0) +#define MT_PG_GROUP_MAX_QUOTA GENMASK(28, 16) +#define MT_PG_GROUP_MIN_QUOTA GENMASK(12, 0) +#define MT_PG_INFO_SRC_CNT GENMASK(28, 16) +#define MT_PG_INFO_RSV_CNT GENMASK(12, 0) + +/* PSE */ +#define MT_PSE_BASE 0x820c8000 +#define MT_PSE(ofs) (MT_PSE_BASE + (ofs)) + +#define MT_PSE_QUEUE_EMPTY MT_PSE(0x0b0) +#define MT_PSE_QUEUE_EMPTY_1 MT_PSE(0x0bc) +#define MT_PSE_FL_Q0_CTRL MT_PSE(0x1b0) +#define MT_PSE_FL_Q2_CTRL MT_PSE(0x1b8) +#define MT_PSE_FL_Q3_CTRL MT_PSE(0x1bc) + /* WF MDP TOP */ #define MT_MDP_BASE 0x820cc000 #define MT_MDP(ofs) (MT_MDP_BASE + (ofs)) diff --git a/drivers/net/wireless/mediatek/mt76/scan.c b/drivers/net/wireless/mediatek/mt76/scan.c index 3594b599662d..3271a2fa100d 100644 --- a/drivers/net/wireless/mediatek/mt76/scan.c +++ b/drivers/net/wireless/mediatek/mt76/scan.c @@ -4,16 +4,26 @@ */ #include "mt76.h" -static void mt76_scan_complete(struct mt76_dev *dev, bool abort) +static struct mt76_phy * +mt76_scan_chan_phy(struct ieee80211_hw *hw, struct ieee80211_channel *chan) { - struct mt76_phy *phy = dev->scan.phy; - struct cfg80211_scan_info info = { - .aborted = abort, - }; + struct mt76_phy *phy = hw->priv; + + if (hw->wiphy->n_radio > 1) + return phy->dev->band_phys[chan->band]; + + return phy; +} + +static void mt76_scan_phy_complete(struct mt76_phy *phy, bool abort) +{ + struct mt76_dev *dev = phy->dev; + struct cfg80211_scan_info info = {}; + struct ieee80211_hw *hw = phy->hw; lockdep_assert_held(&dev->mutex); - if (!phy) + if (!mt76_phy_scanning(phy)) return; clear_bit(MT76_SCANNING, &phy->state); @@ -29,41 +39,75 @@ static void mt76_scan_complete(struct mt76_dev *dev, bool abort) __mt76_set_channel(phy, &phy->main_chandef, false); if (offchannel) mt76_offchannel_notify(phy, false); + } else { + /* A phy that has no operating channel has nothing to restore, + * but the flag also gates the TX queues of every station whose + * wcid points at this band, so leaving it set stalls them until + * something else happens to set a channel. + */ + phy->offchannel = false; } - mt76_put_vif_phy_link(phy, dev->scan.vif, dev->scan.mlink); + mt76_put_vif_phy_link(phy, dev->scan.vif, phy->scan.mlink); + memset(&phy->scan, 0, sizeof(phy->scan)); + + clear_bit(phy->band_idx, &dev->scan.phy_mask); + if (abort) + dev->scan.aborted = true; + + if (dev->scan.phy_mask) + return; + + info.aborted = dev->scan.aborted; memset(&dev->scan, 0, sizeof(dev->scan)); - if (!test_bit(MT76_MCU_RESET, &dev->phy.state)) - ieee80211_scan_completed(phy->hw, &info); + ieee80211_scan_completed(hw, &info); } void mt76_abort_scan(struct mt76_dev *dev) { - spin_lock_bh(&dev->scan_lock); - dev->scan.beacon_wait = false; - spin_unlock_bh(&dev->scan_lock); + struct mt76_phy *phy; + int i; + + for (i = 0; i < ARRAY_SIZE(dev->phys); i++) { + phy = dev->phys[i]; + if (!phy) + continue; + + spin_lock_bh(&dev->scan_lock); + phy->scan.beacon_wait = false; + spin_unlock_bh(&dev->scan_lock); - cancel_delayed_work_sync(&dev->scan_work); + disable_delayed_work_sync(&phy->scan_work); + } mutex_lock(&dev->mutex); - mt76_scan_complete(dev, true); + for (i = 0; i < ARRAY_SIZE(dev->phys); i++) { + phy = dev->phys[i]; + if (!phy) + continue; + + mt76_scan_phy_complete(phy, true); + enable_delayed_work(&phy->scan_work); + } mutex_unlock(&dev->mutex); } EXPORT_SYMBOL_GPL(mt76_abort_scan); static void -mt76_scan_send_probe(struct mt76_dev *dev, struct cfg80211_ssid *ssid) +mt76_scan_send_probe(struct mt76_phy *phy, struct cfg80211_ssid *ssid) { - struct cfg80211_scan_request *req = dev->scan.req; + struct mt76_dev *dev = phy->dev; + struct cfg80211_scan_request *req = &dev->scan.req->req; + struct ieee80211_scan_ies *ies = &dev->scan.req->ies; struct ieee80211_vif *vif = dev->scan.vif; - struct mt76_vif_link *mvif = dev->scan.mlink; - enum nl80211_band band = dev->scan.chan->band; - struct mt76_phy *phy = dev->scan.phy; + struct mt76_vif_link *mvif = phy->scan.mlink; + enum nl80211_band band = phy->scan.chan->band; struct ieee80211_tx_info *info; struct sk_buff *skb; u8 link_id; skb = ieee80211_probereq_get(phy->hw, vif->addr, ssid->ssid, - ssid->ssid_len, req->ie_len); + ssid->ssid_len, + ies->len[band] + ies->common_ie_len); if (!skb) return; @@ -74,8 +118,10 @@ mt76_scan_send_probe(struct mt76_dev *dev, struct cfg80211_ssid *ssid) ether_addr_copy(hdr->addr3, req->bssid); } - if (req->ie_len) - skb_put_data(skb, req->ie, req->ie_len); + if (ies->len[band]) + skb_put_data(skb, ies->ies[band], ies->len[band]); + if (ies->common_ie_len) + skb_put_data(skb, ies->common_ies, ies->common_ie_len); skb->priority = 7; skb_set_queue_mapping(skb, IEEE80211_AC_VO); @@ -100,65 +146,77 @@ mt76_scan_send_probe(struct mt76_dev *dev, struct cfg80211_ssid *ssid) rcu_read_unlock(); } -void mt76_scan_rx_beacon(struct mt76_dev *dev, struct ieee80211_channel *chan) +void mt76_scan_rx_beacon(struct mt76_phy *phy, struct ieee80211_channel *chan) { - struct mt76_phy *phy; + struct mt76_dev *dev = phy->dev; spin_lock(&dev->scan_lock); - if (!dev->scan.beacon_wait || dev->scan.beacon_received || - dev->scan.chan != chan) - goto out; - - phy = dev->scan.phy; - if (!phy) + if (!phy->scan.beacon_wait || phy->scan.beacon_received || + phy->scan.chan != chan) goto out; - dev->scan.beacon_received = true; - ieee80211_queue_delayed_work(phy->hw, &dev->scan_work, 0); + phy->scan.beacon_received = true; + ieee80211_queue_delayed_work(phy->hw, &phy->scan_work, 0); out: spin_unlock(&dev->scan_lock); } +static int mt76_scan_next_chan_idx(struct mt76_phy *phy) +{ + struct cfg80211_scan_request *req = &phy->dev->scan.req->req; + int i; + + for (i = phy->scan.chan_idx; i < req->n_channels; i++) + if (mt76_scan_chan_phy(phy->hw, req->channels[i]) == phy) + return i; + + return -1; +} + void mt76_scan_work(struct work_struct *work) { - struct mt76_dev *dev = container_of(work, struct mt76_dev, + struct mt76_phy *phy = container_of(work, struct mt76_phy, scan_work.work); - struct cfg80211_scan_request *req = dev->scan.req; + struct mt76_dev *dev = phy->dev; + struct cfg80211_scan_request *req; struct cfg80211_chan_def chandef = {}; - struct mt76_phy *phy = dev->scan.phy; int duration = HZ / 9; /* ~110 ms */ bool beacon_rx, offchannel = true; - int i; + int i, idx; - if (!phy || !req) + if (!dev->scan.req || !mt76_phy_scanning(phy)) return; + req = &dev->scan.req->req; + spin_lock_bh(&dev->scan_lock); - beacon_rx = dev->scan.beacon_wait && dev->scan.beacon_received; - dev->scan.beacon_wait = false; + beacon_rx = phy->scan.beacon_wait && phy->scan.beacon_received; + phy->scan.beacon_wait = false; spin_unlock_bh(&dev->scan_lock); if (beacon_rx) goto probe; - if (dev->scan.chan_idx >= req->n_channels) { + idx = mt76_scan_next_chan_idx(phy); + if (idx < 0) { mutex_lock(&dev->mutex); - mt76_scan_complete(dev, false); + mt76_scan_phy_complete(phy, false); mutex_unlock(&dev->mutex); return; } - if (dev->scan.chan && phy->num_sta && phy->offchannel) { - dev->scan.chan = NULL; + if (phy->scan.chan && phy->num_sta && phy->offchannel) { + phy->scan.chan = NULL; mt76_set_channel(phy, &phy->main_chandef, false); mt76_offchannel_notify(phy, false); goto out; } - dev->scan.chan = req->channels[dev->scan.chan_idx++]; - offchannel = mt76_offchannel_chandef(phy, dev->scan.chan, &chandef); + phy->scan.chan = req->channels[idx]; + phy->scan.chan_idx = idx + 1; + offchannel = mt76_offchannel_chandef(phy, phy->scan.chan, &chandef); if (offchannel) mt76_offchannel_notify(phy, true); @@ -169,8 +227,8 @@ void mt76_scan_work(struct work_struct *work) if (chandef.chan->flags & (IEEE80211_CHAN_NO_IR | IEEE80211_CHAN_RADAR)) { spin_lock_bh(&dev->scan_lock); - dev->scan.beacon_received = false; - dev->scan.beacon_wait = true; + phy->scan.beacon_received = false; + phy->scan.beacon_wait = true; spin_unlock_bh(&dev->scan_lock); goto out; } @@ -180,16 +238,16 @@ void mt76_scan_work(struct work_struct *work) duration = HZ / 16; /* ~60 ms */ local_bh_disable(); for (i = 0; i < req->n_ssids; i++) - mt76_scan_send_probe(dev, &req->ssids[i]); + mt76_scan_send_probe(phy, &req->ssids[i]); local_bh_enable(); out: - if (dev->scan.chan && phy->offchannel) + if (phy->scan.chan && phy->offchannel) duration = max_t(int, duration, msecs_to_jiffies(req->duration + (req->duration >> 5))); - ieee80211_queue_delayed_work(dev->phy.hw, &dev->scan_work, duration); + ieee80211_queue_delayed_work(phy->hw, &phy->scan_work, duration); } int mt76_hw_scan(struct ieee80211_hw *hw, struct ieee80211_vif *vif, @@ -197,36 +255,67 @@ int mt76_hw_scan(struct ieee80211_hw *hw, struct ieee80211_vif *vif, { struct mt76_phy *phy = hw->priv; struct mt76_dev *dev = phy->dev; + unsigned long phy_mask = 0; struct mt76_vif_link *mlink; - int ret = 0; + int i, ret = 0; - if (hw->wiphy->n_radio > 1) { - phy = dev->band_phys[req->req.channels[0]->band]; + for (i = 0; i < req->req.n_channels; i++) { + phy = mt76_scan_chan_phy(hw, req->req.channels[i]); if (!phy) return -EINVAL; + + phy_mask |= BIT(phy->band_idx); } mutex_lock(&dev->mutex); - if (dev->scan.req || phy->roc_vif || - test_bit(MT76_MCU_RESET, &dev->phy.state)) { + if (dev->scan.req || test_bit(MT76_MCU_RESET, &dev->phy.state) || + test_bit(MT76_RESTART, &dev->phy.state)) { ret = -EBUSY; goto out; } - mlink = mt76_get_vif_phy_link(phy, vif); - if (IS_ERR(mlink)) { - ret = PTR_ERR(mlink); - goto out; + for_each_set_bit(i, &phy_mask, ARRAY_SIZE(dev->phys)) { + if (dev->phys[i]->roc_vif) { + ret = -EBUSY; + goto out; + } } - memset(&dev->scan, 0, sizeof(dev->scan)); - dev->scan.req = &req->req; + for_each_set_bit(i, &phy_mask, ARRAY_SIZE(dev->phys)) { + phy = dev->phys[i]; + mlink = mt76_get_vif_phy_link(phy, vif); + if (IS_ERR(mlink)) { + ret = PTR_ERR(mlink); + goto put_links; + } + + memset(&phy->scan, 0, sizeof(phy->scan)); + phy->scan.mlink = mlink; + } + + dev->scan.req = req; dev->scan.vif = vif; - dev->scan.phy = phy; - dev->scan.mlink = mlink; - set_bit(MT76_SCANNING, &phy->state); - ieee80211_queue_delayed_work(dev->phy.hw, &dev->scan_work, 0); + dev->scan.phy_mask = phy_mask; + dev->scan.aborted = false; + + for_each_set_bit(i, &phy_mask, ARRAY_SIZE(dev->phys)) { + phy = dev->phys[i]; + set_bit(MT76_SCANNING, &phy->state); + ieee80211_queue_delayed_work(phy->hw, &phy->scan_work, 0); + } + + goto out; + +put_links: + for_each_set_bit(i, &phy_mask, ARRAY_SIZE(dev->phys)) { + phy = dev->phys[i]; + if (!phy->scan.mlink) + break; + + mt76_put_vif_phy_link(phy, vif, phy->scan.mlink); + phy->scan.mlink = NULL; + } out: mutex_unlock(&dev->mutex); diff --git a/drivers/net/wireless/mediatek/mt76/tx.c b/drivers/net/wireless/mediatek/mt76/tx.c index 156d283243d3..b022d3843473 100644 --- a/drivers/net/wireless/mediatek/mt76/tx.c +++ b/drivers/net/wireless/mediatek/mt76/tx.c @@ -129,7 +129,7 @@ mt76_tx_status_skb_add(struct mt76_dev *dev, struct mt76_wcid *wcid, memset(cb, 0, sizeof(*cb)); - if (!wcid || !rcu_access_pointer(dev->wcid[wcid->idx])) + if (!wcid) return MT_PACKET_ID_NO_ACK; if (info->flags & IEEE80211_TX_CTL_NO_ACK) @@ -147,6 +147,11 @@ mt76_tx_status_skb_add(struct mt76_dev *dev, struct mt76_wcid *wcid, spin_lock_bh(&dev->status_lock); + if (rcu_access_pointer(dev->wcid[wcid->idx]) != wcid) { + pid = MT_PACKET_ID_NO_ACK; + goto out; + } + pid = idr_alloc(&wcid->pktid, skb, MT_PACKET_ID_FIRST, MT_PACKET_ID_MASK, GFP_ATOMIC); if (pid < 0) { diff --git a/drivers/net/wireless/mediatek/mt76/usb.c b/drivers/net/wireless/mediatek/mt76/usb.c index dfc12f6944a7..be48a88a3ad0 100644 --- a/drivers/net/wireless/mediatek/mt76/usb.c +++ b/drivers/net/wireless/mediatek/mt76/usb.c @@ -171,8 +171,10 @@ static void mt76u_copy(struct mt76_dev *dev, u32 offset, { struct mt76_usb *usb = &dev->usb; const u8 *val = data; - int ret; int current_batch_size; + int len_aligned; + int copy_len; + int ret; int i = 0; /* Assure that always a multiple of 4 bytes are copied, @@ -180,12 +182,16 @@ static void mt76u_copy(struct mt76_dev *dev, u32 offset, * See: "mt76: round up length on mt76_wr_copy" * Commit 850e8f6fbd5d0003b0 */ - len = round_up(len, 4); + len_aligned = round_up(len, 4); mutex_lock(&usb->usb_ctrl_mtx); - while (i < len) { - current_batch_size = min_t(int, usb->data_len, len - i); - memcpy(usb->data, val + i, current_batch_size); + while (i < len_aligned) { + current_batch_size = min_t(int, usb->data_len, len_aligned - i); + copy_len = min_t(int, current_batch_size, len - i); + memcpy(usb->data, val + i, copy_len); + if (copy_len < current_batch_size) + memset(usb->data + copy_len, 0, + current_batch_size - copy_len); ret = __mt76u_vendor_request(dev, MT_VEND_MULTI_WRITE, USB_DIR_OUT | USB_TYPE_VENDOR, 0, offset + i, usb->data, diff --git a/drivers/net/wireless/morsemicro/mm81x/fw.c b/drivers/net/wireless/morsemicro/mm81x/fw.c index d6d2ad086c32..a2cb97cefc4e 100644 --- a/drivers/net/wireless/morsemicro/mm81x/fw.c +++ b/drivers/net/wireless/morsemicro/mm81x/fw.c @@ -117,13 +117,15 @@ static int mm81x_fw_load_fw(struct mm81x *mors, const struct firmware *fw) if (mm81x_fw_get_header(fw->data, &ehdr)) { dev_err(mors->dev, "Wrong file format"); - return -EINVAL; + ret = -EINVAL; + goto out_free; } if (mm81x_fw_get_section_header(fw->data, &ehdr, &sh_strtab, ehdr.e_shstrndx)) { dev_err(mors->dev, "Invalid firmware. Missing string table"); - return -ENOENT; + ret = -ENOENT; + goto out_free; } sh_strs = (const char *)fw->data + sh_strtab.sh_offset; @@ -160,7 +162,7 @@ static int mm81x_fw_load_fw(struct mm81x *mors, const struct firmware *fw) mm81x_release_bus(mors); if (status) { ret = -EIO; - break; + goto out_free; } } } @@ -179,6 +181,7 @@ static int mm81x_fw_load_fw(struct mm81x *mors, const struct firmware *fw) if (ehdr.e_entry) ret = mm81x_fw_set_boot_addr(mors, ehdr.e_entry); +out_free: devm_kfree(mors->dev, fw_buf); return ret; } diff --git a/drivers/net/wireless/morsemicro/mm81x/mac.c b/drivers/net/wireless/morsemicro/mm81x/mac.c index 0fa80b1488aa..5cd55db33ca2 100644 --- a/drivers/net/wireless/morsemicro/mm81x/mac.c +++ b/drivers/net/wireless/morsemicro/mm81x/mac.c @@ -279,6 +279,11 @@ static void mm81x_mac_check_fw_disabled_chans(struct ieee80211_hw *hw) if (ret) goto out; + if (le32_to_cpu(resp->n_channels) > ARRAY_SIZE(mors_s1ghz_channels)) { + ret = -EINVAL; + goto out; + } + for (i = 0; i < ARRAY_SIZE(mors_s1ghz_channels); i++) { struct ieee80211_channel *ch = &mors_s1ghz_channels[i]; @@ -445,39 +450,6 @@ static void mm81x_beacon_h_fill_tx_info(struct mm81x *mors, cpu_to_le32(MM81X_TX_CONF_FLAGS_IMMEDIATE_REPORT); } -static void mm81x_mac_beacon_work(struct work_struct *work) -{ - struct mm81x_vif *mors_vif = - from_work(mors_vif, work, u.ap.beacon_work); - struct mm81x *mors = mm81x_vif_to_mors(mors_vif); - struct mm81x_skbq *mq; - struct sk_buff *beacon; - struct ieee80211_vif *vif = mm81x_vif_to_ieee80211_vif(mors_vif); - struct mm81x_skb_tx_info tx_info = { 0 }; - int num_bcn_vifs = atomic_read(&mors->num_bcn_vifs); - - mq = mm81x_hif_get_tx_beacon_queue(mors); - if (!mq) { - dev_err(mors->dev, "no matching beacon Q found"); - return; - } - - if (mm81x_skbq_count(mq) >= num_bcn_vifs) { - dev_err(mors->dev, - "previous beacon not consumed, dropping req [id:%d]", - mors_vif->id); - return; - } - - beacon = ieee80211_beacon_get(mors->hw, vif, false); - if (!beacon) - return; - - mm81x_beacon_h_fill_tx_info(mors, &tx_info, mors_vif, - cfg80211_chandef_s1g_pri_width(&mors->chandef)); - mm81x_skbq_skb_tx(mq, &beacon, &tx_info, MM81X_SKB_CHAN_BEACON); -} - void mm81x_mac_beacon_irq_handle(struct mm81x *mors, u32 status) { int vif_id; @@ -497,15 +469,6 @@ void mm81x_mac_beacon_irq_handle(struct mm81x *mors, u32 status) } } -static void mm81x_mac_beacon_init(struct mm81x_vif *mors_vif) -{ - struct mm81x *mors = mm81x_vif_to_mors(mors_vif); - - INIT_WORK(&mors_vif->u.ap.beacon_work, mm81x_mac_beacon_work); - mm81x_mac_beacon_irq_enable(mors_vif, true); - atomic_inc(&mors->num_bcn_vifs); -} - static struct hw_scan_tlv_hdr mm81x_hw_scan_h_pack_tlv_hdr(u16 tag, u16 len) { struct hw_scan_tlv_hdr hdr = { .tag = cpu_to_le16(tag), @@ -1328,6 +1291,47 @@ static void mm81x_mac_ops_tx(struct ieee80211_hw *hw, MM81X_SKB_CHAN_DATA); } +static void mm81x_mac_beacon_work(struct work_struct *work) +{ + struct mm81x_vif *mors_vif = + from_work(mors_vif, work, u.ap.beacon_work); + struct mm81x *mors = mm81x_vif_to_mors(mors_vif); + struct mm81x_skbq *mq; + struct sk_buff *beacon; + struct ieee80211_vif *vif = mm81x_vif_to_ieee80211_vif(mors_vif); + struct mm81x_skb_tx_info tx_info = { 0 }; + int num_bcn_vifs = atomic_read(&mors->num_bcn_vifs); + + mq = mm81x_hif_get_tx_beacon_queue(mors); + if (!mq) { + dev_err(mors->dev, "no matching beacon Q found"); + return; + } + + if (mm81x_skbq_count(mq) >= num_bcn_vifs) { + dev_err(mors->dev, + "previous beacon not consumed, dropping req [id:%d]", + mors_vif->id); + return; + } + + beacon = ieee80211_beacon_get(mors->hw, vif, false); + if (!beacon) + return; + + mm81x_beacon_h_fill_tx_info(mors, &tx_info, mors_vif, + cfg80211_chandef_s1g_pri_width(&mors->chandef)); + mm81x_skbq_skb_tx(mq, &beacon, &tx_info, MM81X_SKB_CHAN_BEACON); +} + +static void mm81x_mac_beacon_start(struct mm81x_vif *mors_vif) +{ + struct mm81x *mors = mm81x_vif_to_mors(mors_vif); + + mm81x_mac_beacon_irq_enable(mors_vif, true); + atomic_inc(&mors->num_bcn_vifs); +} + static void mm81x_mac_ops_stop(struct ieee80211_hw *hw, bool suspend) { struct mm81x *mors = hw->priv; @@ -1546,7 +1550,9 @@ static void mm81x_mac_ops_bss_info_changed(struct ieee80211_hw *hw, mm81x_cmd_config_beacon_timer(mors, mors_vif, info->enable_beacon); - if (!info->enable_beacon) + if (info->enable_beacon) + mm81x_mac_beacon_start(mors_vif); + else mm81x_mac_beacon_finish(mors_vif); } @@ -2214,7 +2220,7 @@ static int mm81x_mac_ops_add_interface(struct ieee80211_hw *hw, rcu_assign_pointer(mors->vifs[mors_vif->id], vif); if (vif->type == NL80211_IFTYPE_AP) - mm81x_mac_beacon_init(mors_vif); + INIT_WORK(&mors_vif->u.ap.beacon_work, mm81x_mac_beacon_work); ret = mm81x_cmd_get_capabilities(mors, mors_vif->id, &mors->fw_caps); if (ret) { diff --git a/drivers/net/wireless/morsemicro/mm81x/sdio.c b/drivers/net/wireless/morsemicro/mm81x/sdio.c index 96fce187dd35..65277399bf18 100644 --- a/drivers/net/wireless/morsemicro/mm81x/sdio.c +++ b/drivers/net/wireless/morsemicro/mm81x/sdio.c @@ -381,7 +381,7 @@ static int mm81x_sdio_dm_read(struct mm81x *mors, u32 address, u8 *data, static int mm81x_sdio_reg32_write(struct mm81x *mors, u32 address, u32 val) { - ssize_t ret = 0; + int ret = 0; u32 original_address = address; struct mm81x_sdio *sdio = (struct mm81x_sdio *)mors->drv_priv; struct sdio_func *func1 = sdio->func->card->sdio_func[0]; @@ -391,7 +391,7 @@ static int mm81x_sdio_reg32_write(struct mm81x *mors, u32 address, u32 val) address &= 0x0000FFFF; sdio_writel(func1, (__force u32)cpu_to_le32(val), - (__force u32)cpu_to_le32(address), (int *)&ret); + (__force u32)cpu_to_le32(address), &ret); if (ret) goto error; @@ -411,7 +411,7 @@ static int mm81x_sdio_reg32_write(struct mm81x *mors, u32 address, u32 val) static int mm81x_sdio_reg32_read(struct mm81x *mors, u32 address, u32 *val) { u32 value; - ssize_t ret = 0; + int ret = 0; struct mm81x_sdio *sdio = (struct mm81x_sdio *)mors->drv_priv; struct sdio_func *func1 = sdio->func->card->sdio_func[0]; @@ -419,8 +419,7 @@ static int mm81x_sdio_reg32_read(struct mm81x *mors, u32 address, u32 *val) MM81X_CONFIG_ACCESS_4BYTE); address &= 0x0000FFFF; - value = sdio_readl(func1, (__force u32)cpu_to_le32(address), - (int *)&ret); + value = sdio_readl(func1, (__force u32)cpu_to_le32(address), &ret); if (ret) return ret; diff --git a/drivers/net/wireless/morsemicro/mm81x/yaps_hw.c b/drivers/net/wireless/morsemicro/mm81x/yaps_hw.c index 3d641d23c35b..1d90137470c2 100644 --- a/drivers/net/wireless/morsemicro/mm81x/yaps_hw.c +++ b/drivers/net/wireless/morsemicro/mm81x/yaps_hw.c @@ -401,16 +401,17 @@ static int mm81x_yaps_hw_write_pkts(struct mm81x_yaps *yaps, static bool mm81x_read_pkts_h_is_valid_delim(u32 delim) { u8 calc_crc = mm81x_yaps_hw_crc(delim); - int pkt_size = YAPS_DELIM_GET_PHANDLE_SIZE(delim); + int pkt_size = YAPS_DELIM_GET_PKT_SIZE(delim); int padding = YAPS_DELIM_GET_PADDING(delim); if (calc_crc != YAPS_DELIM_GET_CRC(delim)) return false; - if (pkt_size == 0) + if (pkt_size <= 0) return false; - if ((pkt_size + padding) > YAPS_MAX_PKT_SIZE_BYTES) + if ((pkt_size + YAPS_RESERVED_PAGE_SIZE + padding) > + YAPS_MAX_PKT_SIZE_BYTES) return false; /* Pkt length + padding should not require more padding */ @@ -455,6 +456,10 @@ static int mm81x_yaps_hw_read_pkts(struct mm81x_yaps *yaps, return 0; if (bytes_remaining < 0) return bytes_remaining; + if (!IS_ALIGNED(bytes_remaining, sizeof(u32))) { + dev_warn(yaps->mors->dev, "yaps truncated delimiter"); + return -EIO; + } if (bytes_remaining > YAPS_HW_WINDOW_SIZE_BYTES) { bytes_remaining = YAPS_HW_WINDOW_SIZE_BYTES; @@ -486,6 +491,9 @@ static int mm81x_yaps_hw_read_pkts(struct mm81x_yaps *yaps, int total_len; int pkt_size; + if (bytes_remaining < (int)sizeof(delim)) + break; + delim = le32_to_cpu(*((__le32 *)read_ptr)); read_ptr += sizeof(delim); bytes_remaining -= sizeof(delim); diff --git a/drivers/net/wireless/nxp/nxpwifi/11ax.c b/drivers/net/wireless/nxp/nxpwifi/11ax.c index 96540914f3cf..dc1e747383ec 100644 --- a/drivers/net/wireless/nxp/nxpwifi/11ax.c +++ b/drivers/net/wireless/nxp/nxpwifi/11ax.c @@ -402,6 +402,8 @@ static u8 nxpwifi_is_ap_11ax_twt_supported(struct nxpwifi_bssdescriptor *bss_des return false; ext_cap = (struct element *)bss_desc->bcn_ext_cap; + if (ext_cap->datalen < 10) + return false; if (!(ext_cap->data[9] & WLAN_EXT_CAPA10_TWT_RESPONDER_SUPPORT)) return false; return true; diff --git a/drivers/net/wireless/nxp/nxpwifi/cfg80211.c b/drivers/net/wireless/nxp/nxpwifi/cfg80211.c index 473e81304ca8..dcdb7b2bd9ae 100644 --- a/drivers/net/wireless/nxp/nxpwifi/cfg80211.c +++ b/drivers/net/wireless/nxp/nxpwifi/cfg80211.c @@ -844,8 +844,7 @@ nxpwifi_change_vif_to_sta(struct net_device *dev, update_vif_type_counter(adapter, type, 1); dev->ieee80211_ptr->iftype = type; - if (nxpwifi_set_bss_mode(priv)) - return -1; + ret = nxpwifi_set_bss_mode(priv); if (ret) goto done; @@ -888,8 +887,7 @@ nxpwifi_change_vif_to_ap(struct net_device *dev, update_vif_type_counter(adapter, type, 1); dev->ieee80211_ptr->iftype = type; - if (nxpwifi_set_bss_mode(priv)) - return -1; + ret = nxpwifi_set_bss_mode(priv); if (ret) goto done; diff --git a/drivers/net/wireless/nxp/nxpwifi/main.c b/drivers/net/wireless/nxp/nxpwifi/main.c index 9e13348105c3..8eefd57e92c9 100644 --- a/drivers/net/wireless/nxp/nxpwifi/main.c +++ b/drivers/net/wireless/nxp/nxpwifi/main.c @@ -603,14 +603,18 @@ static int _nxpwifi_fw_dpc(const struct firmware *firmware, void *context) maybe_quirk_fw_disable_ds(adapter); if (!adapter->wiphy) { - if (nxpwifi_register_cfg80211(adapter)) { + ret = nxpwifi_register_cfg80211(adapter); + + if (ret) { nxpwifi_dbg(adapter, ERROR, "cannot register with cfg80211\n"); goto err_init_fw; } } - if (nxpwifi_init_channel_scan_gap(adapter)) { + ret = nxpwifi_init_channel_scan_gap(adapter); + + if (ret) { nxpwifi_dbg(adapter, ERROR, "could not init channel stats table\n"); goto err_init_chan_scan; @@ -623,6 +627,7 @@ static int _nxpwifi_fw_dpc(const struct firmware *firmware, void *context) if (IS_ERR(wdev)) { nxpwifi_dbg(adapter, ERROR, "cannot create default STA interface\n"); + ret = PTR_ERR(wdev); rtnl_unlock(); goto err_add_intf; } @@ -632,6 +637,7 @@ static int _nxpwifi_fw_dpc(const struct firmware *firmware, void *context) if (IS_ERR(wdev)) { nxpwifi_dbg(adapter, ERROR, "cannot create AP interface\n"); + ret = PTR_ERR(wdev); rtnl_unlock(); goto err_add_intf; } diff --git a/drivers/net/wireless/nxp/nxpwifi/scan.c b/drivers/net/wireless/nxp/nxpwifi/scan.c index 67d7ff2f10c5..f3becafb9c23 100644 --- a/drivers/net/wireless/nxp/nxpwifi/scan.c +++ b/drivers/net/wireless/nxp/nxpwifi/scan.c @@ -1209,6 +1209,8 @@ int nxpwifi_update_bss_desc_with_ie(struct nxpwifi_adapter *adapter, (u16)(current_ptr - bss_entry->beacon_buf); break; case WLAN_EID_HT_CAPABILITY: + if (element_len < sizeof(*bss_entry->bcn_ht_cap)) + return -EINVAL; bss_entry->bcn_ht_cap = (struct ieee80211_ht_cap *)(current_ptr + elem_size); @@ -1217,6 +1219,8 @@ int nxpwifi_update_bss_desc_with_ie(struct nxpwifi_adapter *adapter, bss_entry->beacon_buf); break; case WLAN_EID_HT_OPERATION: + if (element_len < sizeof(*bss_entry->bcn_ht_oper)) + return -EINVAL; bss_entry->bcn_ht_oper = (struct ieee80211_ht_operation *)(current_ptr + elem_size); @@ -1225,6 +1229,8 @@ int nxpwifi_update_bss_desc_with_ie(struct nxpwifi_adapter *adapter, bss_entry->beacon_buf); break; case WLAN_EID_VHT_CAPABILITY: + if (element_len < sizeof(*bss_entry->bcn_vht_cap)) + return -EINVAL; bss_entry->disable_11ac = false; bss_entry->bcn_vht_cap = (void *)(current_ptr + elem_size); @@ -1233,6 +1239,8 @@ int nxpwifi_update_bss_desc_with_ie(struct nxpwifi_adapter *adapter, bss_entry->beacon_buf); break; case WLAN_EID_VHT_OPERATION: + if (element_len < sizeof(*bss_entry->bcn_vht_oper)) + return -EINVAL; bss_entry->bcn_vht_oper = (void *)(current_ptr + elem_size); bss_entry->vht_info_offset = @@ -1240,6 +1248,8 @@ int nxpwifi_update_bss_desc_with_ie(struct nxpwifi_adapter *adapter, bss_entry->beacon_buf); break; case WLAN_EID_BSS_COEX_2040: + if (!element_len) + return -EINVAL; bss_entry->bcn_bss_co_2040 = current_ptr; bss_entry->bss_co_2040_offset = (u16)(current_ptr - bss_entry->beacon_buf); @@ -1250,6 +1260,8 @@ int nxpwifi_update_bss_desc_with_ie(struct nxpwifi_adapter *adapter, (u16)(current_ptr - bss_entry->beacon_buf); break; case WLAN_EID_OPMODE_NOTIF: + if (total_ie_len < sizeof(*bss_entry->oper_mode)) + return -EINVAL; bss_entry->oper_mode = (void *)current_ptr; bss_entry->oper_mode_offset = (u16)(current_ptr - bss_entry->beacon_buf); @@ -1262,6 +1274,9 @@ int nxpwifi_update_bss_desc_with_ie(struct nxpwifi_adapter *adapter, switch (elem->data[0]) { case WLAN_EID_EXT_HE_CAPABILITY: + if (element_len < + 1 + sizeof(*bss_entry->bcn_he_cap)) + return -EINVAL; bss_entry->disable_11ax = false; bss_entry->bcn_he_cap = (void *)(current_ptr + elem_size + 1); @@ -1270,6 +1285,9 @@ int nxpwifi_update_bss_desc_with_ie(struct nxpwifi_adapter *adapter, bss_entry->beacon_buf); break; case WLAN_EID_EXT_HE_OPERATION: + if (element_len < + 1 + sizeof(*bss_entry->bcn_he_oper)) + return -EINVAL; bss_entry->bcn_he_oper = (void *)(current_ptr + elem_size + 1); bss_entry->he_info_offset = diff --git a/drivers/net/wireless/nxp/nxpwifi/sdio.c b/drivers/net/wireless/nxp/nxpwifi/sdio.c index 8ef0f6eb49e2..a0d7196c13a2 100644 --- a/drivers/net/wireless/nxp/nxpwifi/sdio.c +++ b/drivers/net/wireless/nxp/nxpwifi/sdio.c @@ -665,7 +665,7 @@ nxpwifi_sdio_poll_card_status(struct nxpwifi_adapter *adapter, u8 bits) nxpwifi_dbg(adapter, ERROR, "poll card status failed, tries = %d\n", tries); - return ret; + return ret ?: -ETIMEDOUT; } /* Disable SDIO host interrupt and release IRQ. */ diff --git a/drivers/net/wireless/realtek/rtl8xxxu/core.c b/drivers/net/wireless/realtek/rtl8xxxu/core.c index bddbd0990de7..3d0c22db30a8 100644 --- a/drivers/net/wireless/realtek/rtl8xxxu/core.c +++ b/drivers/net/wireless/realtek/rtl8xxxu/core.c @@ -54,10 +54,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); @@ -5832,10 +5834,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_obj(struct rtl8xxxu_rx_urb); + 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); @@ -5843,64 +5866,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; - struct sk_buff *skb; 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); - skb = (struct sk_buff *)rx_urb->urb.context; - dev_kfree_skb(skb); - 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); } /* @@ -6558,10 +6583,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; @@ -6596,8 +6635,11 @@ static int rtl8xxxu_submit_rx_urb(struct rtl8xxxu_priv *priv, skb_size, rtl8xxxu_rx_complete, skb); usb_anchor_urb(&rx_urb->urb, &priv->rx_anchor); ret = usb_submit_urb(&rx_urb->urb, GFP_ATOMIC); - if (ret) + if (ret) { usb_unanchor_urb(&rx_urb->urb); + dev_kfree_skb(skb); + rx_urb->urb.context = NULL; + } return ret; } @@ -7408,9 +7450,7 @@ 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; - struct sk_buff *skb; unsigned long flags; int ret, i; @@ -7424,14 +7464,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_obj(struct rtl8xxxu_tx_urb); if (!tx_urb) { - if (!i) - ret = -ENOMEM; + ret = -ENOMEM; goto error_out; } @@ -7442,36 +7481,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_obj(struct rtl8xxxu_rx_urb); - 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) { - if (ret != -ENOMEM) { - skb = (struct sk_buff *)rx_urb->urb.context; - dev_kfree_skb(skb); - } - 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 */ @@ -7484,13 +7508,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; } @@ -7513,7 +7531,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); @@ -7826,7 +7844,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 eeb18eb0e4c0..c6953051d9c4 100644 --- a/drivers/net/wireless/realtek/rtl8xxxu/rtl8xxxu.h +++ b/drivers/net/wireless/realtek/rtl8xxxu/rtl8xxxu.h @@ -1809,7 +1809,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/rtw88/debug.c b/drivers/net/wireless/realtek/rtw88/debug.c index b67d69b01f87..84e45af26f52 100644 --- a/drivers/net/wireless/realtek/rtw88/debug.c +++ b/drivers/net/wireless/realtek/rtw88/debug.c @@ -315,6 +315,11 @@ static int rtw_debugfs_get_rsvd_page(struct seq_file *m, void *v) int i; int ret; + if (!buf_size) { + seq_puts(m, "usage: echo > rsvd_page\n"); + return 0; + } + buf = vzalloc(buf_size); if (!buf) return -ENOMEM; diff --git a/drivers/net/wireless/realtek/rtw88/sdio.c b/drivers/net/wireless/realtek/rtw88/sdio.c index 5b40d74b16ee..8466abad972a 100644 --- a/drivers/net/wireless/realtek/rtw88/sdio.c +++ b/drivers/net/wireless/realtek/rtw88/sdio.c @@ -636,6 +636,7 @@ static int rtw_sdio_write_port(struct rtw_dev *rtwdev, struct sk_buff *skb, enum rtw_tx_queue_type queue) { struct rtw_sdio *rtwsdio = (struct rtw_sdio *)rtwdev->priv; + size_t pad_size; bool bus_claim; size_t txsize; u32 txaddr; @@ -646,6 +647,17 @@ static int rtw_sdio_write_port(struct rtw_dev *rtwdev, struct sk_buff *skb, return -EINVAL; txsize = sdio_align_size(rtwsdio->sdio_func, skb->len); + pad_size = txsize - skb->len; + + if (pad_size > 0) { + /* + * __skb_pad() must not free the skb on failure: both callers + * still own it, one requeues it and the other frees it. + */ + ret = __skb_pad(skb, pad_size, false); + if (ret) + return ret; + } ret = rtw_sdio_check_free_txpg(rtwdev, queue, txsize); if (ret) diff --git a/drivers/net/wireless/realtek/rtw89/Kconfig b/drivers/net/wireless/realtek/rtw89/Kconfig index 7c678dd1f6b3..9c6c16af7f35 100644 --- a/drivers/net/wireless/realtek/rtw89/Kconfig +++ b/drivers/net/wireless/realtek/rtw89/Kconfig @@ -215,7 +215,7 @@ config RTW89_LEDS config RTW89_LEDS_MC bool depends on RTW89_LEDS - depends on LEDS_CLASS_MULTICOLOR + depends on LEDS_CLASS_MULTICOLOR=y || LEDS_CLASS_MULTICOLOR=RTW89_CORE imply LEDS_TRIGGER_TIMER default y diff --git a/drivers/net/wireless/realtek/rtw89/coex.c b/drivers/net/wireless/realtek/rtw89/coex.c index 5a9dc4d8a00b..12bd5539e8c6 100644 --- a/drivers/net/wireless/realtek/rtw89/coex.c +++ b/drivers/net/wireless/realtek/rtw89/coex.c @@ -3365,7 +3365,7 @@ static void _fw_set_gpio(struct rtw89_dev *rtwdev, u8 type, u32 val) gpio->mux.data.dlen = CXDGPIO_SET_L2; gpio->mux.data.sig = _get_gpiosig_for_ver(rtwdev, FIELD_GET(GENMASK(7, 0), val)); - if (gpio->mux.data.sig == 0xff) + if (gpio->mux.data.sig >= BTC_DBG_NUM) return; gpio->mux.data.gpio = FIELD_GET(GENMASK(15, 8), val); l2_h2c = gpio->mux.fmt; diff --git a/drivers/net/wireless/silabs/wfx/bh.c b/drivers/net/wireless/silabs/wfx/bh.c index 21dfdcf9cc27..0071659bc9c9 100644 --- a/drivers/net/wireless/silabs/wfx/bh.c +++ b/drivers/net/wireless/silabs/wfx/bh.c @@ -284,10 +284,10 @@ void wfx_bh_request_tx(struct wfx_dev *wdev) } /* If IRQ is not available, this function allow to manually poll the control register and simulate - * an IRQ ahen an event happened. + * an IRQ when an event happened. * - * Note that the device has a bug: If an IRQ raise while host read control register, the IRQ is - * lost. So, use this function carefully (only duing device initialisation). + * Note that the device has a bug: If an IRQ raise while host read control register, the device is + * lost. Unfortunately, this is the only way to initialize the SDIO with out-of-band IRQ. */ void wfx_bh_poll_irq(struct wfx_dev *wdev) { diff --git a/drivers/net/wireless/silabs/wfx/bus_sdio.c b/drivers/net/wireless/silabs/wfx/bus_sdio.c index ab0793b9908f..1ca2cc262feb 100644 --- a/drivers/net/wireless/silabs/wfx/bus_sdio.c +++ b/drivers/net/wireless/silabs/wfx/bus_sdio.c @@ -279,6 +279,7 @@ static int wfx_sdio_probe(struct sdio_func *func, const struct sdio_device_id *i goto sdio_release; } + bus->core->poll_irq = !!bus->of_irq; ret = wfx_probe(bus->core); if (ret) goto sdio_release; diff --git a/drivers/net/wireless/silabs/wfx/main.c b/drivers/net/wireless/silabs/wfx/main.c index dda36e41eed1..b6fd9d4c1f5f 100644 --- a/drivers/net/wireless/silabs/wfx/main.c +++ b/drivers/net/wireless/silabs/wfx/main.c @@ -362,7 +362,6 @@ int wfx_probe(struct wfx_dev *wdev) */ gpio_saved = wdev->pdata.gpio_wakeup; wdev->pdata.gpio_wakeup = NULL; - wdev->poll_irq = true; wdev->bh_wq = alloc_workqueue("wfx_bh_wq", WQ_HIGHPRI | WQ_PERCPU, 0); if (!wdev->bh_wq) @@ -370,16 +369,24 @@ int wfx_probe(struct wfx_dev *wdev) wfx_bh_register(wdev); + if (!wdev->poll_irq) { + err = wdev->hwbus_ops->irq_subscribe(wdev->hwbus_priv); + if (err) + goto bh_unregister; + } + err = wfx_init_device(wdev); if (err) - goto bh_unregister; + goto irq_unsubscribe; + + if (wdev->poll_irq) + wfx_bh_poll_irq(wdev); - wfx_bh_poll_irq(wdev); err = wait_for_completion_timeout(&wdev->firmware_ready, 1 * HZ); if (err == 0) { dev_err(wdev->dev, "timeout while waiting for startup indication\n"); err = -ETIMEDOUT; - goto bh_unregister; + goto irq_unsubscribe; } /* FIXME: fill wiphy::hw_version */ @@ -399,12 +406,12 @@ int wfx_probe(struct wfx_dev *wdev) dev_err(wdev->dev, "unsupported firmware API version (expect 1 while firmware returns %d)\n", wdev->hw_caps.api_version_major); err = -EOPNOTSUPP; - goto bh_unregister; + goto irq_unsubscribe; } if (wdev->hw_caps.link_mode == SEC_LINK_ENFORCED) { dev_err(wdev->dev, "chip require secure_link, but can't negotiate it\n"); - goto bh_unregister; + goto irq_unsubscribe; } if (wdev->hw_caps.region_sel_mode) { @@ -420,12 +427,14 @@ int wfx_probe(struct wfx_dev *wdev) dev_dbg(wdev->dev, "sending configuration file %s\n", wdev->pdata.file_pds); err = wfx_send_pdata_pds(wdev); if (err < 0 && err != -ENOENT) - goto bh_unregister; + goto irq_unsubscribe; - wdev->poll_irq = false; - err = wdev->hwbus_ops->irq_subscribe(wdev->hwbus_priv); - if (err) - goto bh_unregister; + if (wdev->poll_irq) { + err = wdev->hwbus_ops->irq_subscribe(wdev->hwbus_priv); + if (err) + goto bh_unregister; + wdev->poll_irq = false; + } err = wfx_hif_use_multi_tx_conf(wdev, true); if (err) @@ -474,9 +483,11 @@ int wfx_probe(struct wfx_dev *wdev) ieee80211_unregister: ieee80211_unregister_hw(wdev->hw); irq_unsubscribe: - wdev->hwbus_ops->irq_unsubscribe(wdev->hwbus_priv); + if (!wdev->poll_irq) + wdev->hwbus_ops->irq_unsubscribe(wdev->hwbus_priv); bh_unregister: wfx_bh_unregister(wdev); + cancel_delayed_work_sync(&wdev->cooling_timeout_work); destroy_workqueue(wdev->bh_wq); return err; } @@ -487,6 +498,7 @@ void wfx_release(struct wfx_dev *wdev) wfx_hif_shutdown(wdev); wdev->hwbus_ops->irq_unsubscribe(wdev->hwbus_priv); wfx_bh_unregister(wdev); + cancel_delayed_work_sync(&wdev->cooling_timeout_work); destroy_workqueue(wdev->bh_wq); } diff --git a/drivers/nvdimm/pmem.c b/drivers/nvdimm/pmem.c index 30a51c365ce8..648fc7d66063 100644 --- a/drivers/nvdimm/pmem.c +++ b/drivers/nvdimm/pmem.c @@ -563,8 +563,10 @@ static int pmem_attach_disk(struct device *dev, nvdimm_namespace_disk_name(ndns, disk->disk_name); set_capacity(disk, (pmem->size - pmem->pfn_pad - pmem->data_offset) / 512); - if (devm_init_badblocks(dev, &pmem->bb)) - return -ENOMEM; + if (devm_init_badblocks(dev, &pmem->bb)) { + rc = -ENOMEM; + goto out; + } nvdimm_badblocks_populate(nd_region, &pmem->bb, &bb_range); disk->bb = &pmem->bb; diff --git a/drivers/nvme/host/fabrics.c b/drivers/nvme/host/fabrics.c index 59f823dfbbcc..3d7ad86c1955 100644 --- a/drivers/nvme/host/fabrics.c +++ b/drivers/nvme/host/fabrics.c @@ -1125,16 +1125,27 @@ static int nvmf_parse_options(struct nvmf_ctrl_options *opts, void nvmf_set_io_queues(struct nvmf_ctrl_options *opts, u32 nr_io_queues, u32 io_queues[HCTX_MAX_TYPES]) { - if (opts->nr_write_queues && opts->nr_io_queues < nr_io_queues) { + /* + * Each queue type is mapped to the CPUs separately, so a type with + * more queues than online CPUs has hardware contexts without an online + * CPU. Use the same limits as nvmf_nr_io_queues. + */ + u32 nr_io = min(opts->nr_io_queues, num_online_cpus()); + u32 nr_write = min(opts->nr_write_queues, num_online_cpus()); + u32 nr_poll = min(opts->nr_poll_queues, num_online_cpus()); + + memset(io_queues, 0, sizeof(*io_queues) * HCTX_MAX_TYPES); + + if (nr_write && nr_io < nr_io_queues) { /* * separate read/write queues * hand out dedicated default queues only after we have * sufficient read queues. */ - io_queues[HCTX_TYPE_READ] = opts->nr_io_queues; + io_queues[HCTX_TYPE_READ] = nr_io; nr_io_queues -= io_queues[HCTX_TYPE_READ]; io_queues[HCTX_TYPE_DEFAULT] = - min(opts->nr_write_queues, nr_io_queues); + min(nr_write, nr_io_queues); nr_io_queues -= io_queues[HCTX_TYPE_DEFAULT]; } else { /* @@ -1143,14 +1154,14 @@ void nvmf_set_io_queues(struct nvmf_ctrl_options *opts, u32 nr_io_queues, * sufficient queue count to have dedicated default queues. */ io_queues[HCTX_TYPE_DEFAULT] = - min(opts->nr_io_queues, nr_io_queues); + min(nr_io, nr_io_queues); nr_io_queues -= io_queues[HCTX_TYPE_DEFAULT]; } - if (opts->nr_poll_queues && nr_io_queues) { + if (nr_poll && nr_io_queues) { /* map dedicated poll queues only if we have queues left */ io_queues[HCTX_TYPE_POLL] = - min(opts->nr_poll_queues, nr_io_queues); + min(nr_poll, nr_io_queues); } } EXPORT_SYMBOL_GPL(nvmf_set_io_queues); @@ -1188,6 +1199,13 @@ void nvmf_map_queues(struct blk_mq_tag_set *set, struct nvme_ctrl *ctrl, io_queues[HCTX_TYPE_DEFAULT] + io_queues[HCTX_TYPE_READ]; blk_mq_map_queues(&set->map[HCTX_TYPE_POLL]); + } else { + /* + * blk_mq_alloc_tag_set sets nr_queues of all maps to + * nr_hw_queues. Clear the poll map, otherwise the queue claims + * poll support and polled I/O ends up on hctx 0. + */ + set->map[HCTX_TYPE_POLL].nr_queues = 0; } dev_info(ctrl->device, diff --git a/drivers/nvme/host/ioctl.c b/drivers/nvme/host/ioctl.c index 6539d4750098..f2904c7fe0ab 100644 --- a/drivers/nvme/host/ioctl.c +++ b/drivers/nvme/host/ioctl.c @@ -343,7 +343,7 @@ static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns, c.common.cdw14 = cpu_to_le32(cmd.cdw14); c.common.cdw15 = cpu_to_le32(cmd.cdw15); - if (!nvme_cmd_allowed(ctrl, ns, &c, 0, open_for_write)) + if (!nvme_cmd_allowed(ctrl, ns, &c, flags, open_for_write)) return -EACCES; if (cmd.timeout_ms) diff --git a/drivers/nvme/host/pci.c b/drivers/nvme/host/pci.c index b7c5a18b899b..eb74bd8838f2 100644 --- a/drivers/nvme/host/pci.c +++ b/drivers/nvme/host/pci.c @@ -243,7 +243,7 @@ static struct kparam_string quirks_param_string = { .string = quirks_param, }; -module_param_cb(quirks, &quirks_param_ops, &quirks_param_string, 0444); +device_param_cb(quirks, &quirks_param_ops, &quirks_param_string, 0444); MODULE_PARM_DESC(quirks, "Enable/disable NVMe quirks by specifying " "quirks=VID:DID:quirk_names"); diff --git a/drivers/nvme/host/rdma.c b/drivers/nvme/host/rdma.c index ff7b9e379614..32189fdfc0f5 100644 --- a/drivers/nvme/host/rdma.c +++ b/drivers/nvme/host/rdma.c @@ -313,7 +313,7 @@ static int nvme_rdma_init_request(struct blk_mq_tag_set *set, return -ENOMEM; /* metadata nvme_rdma_sgl struct is located after command's data SGL */ - if (queue->pi_support) + if (queue_idx && ctrl->ctrl.max_integrity_segments) req->metadata_sgl = (void *)nvme_req(rq) + sizeof(struct nvme_rdma_request) + NVME_RDMA_DATA_SGL_SIZE; diff --git a/drivers/nvme/host/tcp.c b/drivers/nvme/host/tcp.c index 50297ce8bdde..6204943ea404 100644 --- a/drivers/nvme/host/tcp.c +++ b/drivers/nvme/host/tcp.c @@ -191,6 +191,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; }; static struct workqueue_struct *nvme_tcp_wq; @@ -2334,10 +2335,8 @@ static int nvme_tcp_alloc_admin_queue(struct nvme_ctrl *ctrl) return ret; } -static int __nvme_tcp_alloc_io_queues(struct nvme_ctrl *ctrl) +static int nvme_tcp_tls_check_psk(struct nvme_ctrl *ctrl) { - int i, ret; - if (nvme_tcp_tls_configured(ctrl)) { if (ctrl->opts->concat) { /* @@ -2359,6 +2358,13 @@ static int __nvme_tcp_alloc_io_queues(struct nvme_ctrl *ctrl) } } + return 0; +} + +static int __nvme_tcp_alloc_io_queues(struct nvme_ctrl *ctrl) +{ + int i, ret; + for (i = 1; i < ctrl->queue_count; i++) { ret = nvme_tcp_alloc_queue(ctrl, i, ctrl->tls_pskid); @@ -2375,7 +2381,7 @@ static int __nvme_tcp_alloc_io_queues(struct nvme_ctrl *ctrl) return ret; } -static int nvme_tcp_alloc_io_queues(struct nvme_ctrl *ctrl) +static int nvme_tcp_set_io_queue_count(struct nvme_ctrl *ctrl) { unsigned int nr_io_queues; int ret; @@ -2397,14 +2403,22 @@ static int nvme_tcp_alloc_io_queues(struct nvme_ctrl *ctrl) nvmf_set_io_queues(ctrl->opts, nr_io_queues, to_tcp_ctrl(ctrl)->io_queues); - return __nvme_tcp_alloc_io_queues(ctrl); + return 0; } static int nvme_tcp_configure_io_queues(struct nvme_ctrl *ctrl, bool new) { int ret, nr_queues; - ret = nvme_tcp_alloc_io_queues(ctrl); + ret = nvme_tcp_set_io_queue_count(ctrl); + if (ret) + return ret; + + ret = nvme_tcp_tls_check_psk(ctrl); + if (ret) + return ret; + + ret = __nvme_tcp_alloc_io_queues(ctrl); if (ret) return ret; @@ -2791,8 +2805,6 @@ 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); - /* the same count used to size and initialize the queue array */ - unsigned int nr_queues = NVME_TCP_OPT_NR_QUEUES(nctrl->opts); unsigned int i; if (list_empty_careful(&ctrl->list)) @@ -2804,7 +2816,7 @@ static void nvme_tcp_free_ctrl(struct nvme_ctrl *nctrl) nvmf_free_options(nctrl->opts); free_ctrl: - for (i = 0; i < nr_queues; i++) + for (i = 0; i < ctrl->nr_allocated_queues; i++) mutex_destroy(&ctrl->queues[i].queue_lock); kfree(ctrl->queues); kfree(ctrl); @@ -3198,7 +3210,8 @@ static struct nvme_tcp_ctrl *nvme_tcp_alloc_ctrl(struct device *dev, goto out_free_ctrl; } - ctrl->queues = kzalloc_objs(*ctrl->queues, ctrl->ctrl.queue_count); + ctrl->nr_allocated_queues = ctrl->ctrl.queue_count; + ctrl->queues = kzalloc_objs(*ctrl->queues, ctrl->nr_allocated_queues); if (!ctrl->queues) { ret = -ENOMEM; goto out_free_ctrl; @@ -3209,7 +3222,7 @@ static struct nvme_tcp_ctrl *nvme_tcp_alloc_ctrl(struct device *dev, * they outlive the per-queue connect/disconnect cycles so that * sysfs readers can never race their destruction. */ - for (i = 0; i < ctrl->ctrl.queue_count; i++) + for (i = 0; i < ctrl->nr_allocated_queues; i++) mutex_init(&ctrl->queues[i].queue_lock); ret = nvme_init_ctrl(&ctrl->ctrl, dev, &nvme_tcp_ctrl_ops, 0); diff --git a/drivers/nvme/target/configfs.c b/drivers/nvme/target/configfs.c index 61107bcfc895..81d7ada2fa05 100644 --- a/drivers/nvme/target/configfs.c +++ b/drivers/nvme/target/configfs.c @@ -387,10 +387,15 @@ static ssize_t nvmet_addr_trtype_store(struct config_item *item, const char *page, size_t count) { struct nvmet_port *port = to_nvmet_port(item); + ssize_t ret = count; int i; - if (nvmet_is_port_enabled(port, __func__)) - return -EACCES; + down_write(&nvmet_config_sem); + + if (nvmet_is_port_enabled(port, __func__)) { + ret = -EACCES; + goto out; + } for (i = 0; i < ARRAY_SIZE(nvmet_transport); i++) { if (sysfs_streq(page, nvmet_transport[i].name)) @@ -398,7 +403,8 @@ static ssize_t nvmet_addr_trtype_store(struct config_item *item, } pr_err("Invalid value '%s' for trtype\n", page); - return -EINVAL; + ret = -EINVAL; + goto out; found: memset(&port->disc_addr.tsas, 0, NVMF_TSAS_SIZE); @@ -407,7 +413,9 @@ static ssize_t nvmet_addr_trtype_store(struct config_item *item, nvmet_port_init_tsas_rdma(port); else if (port->disc_addr.trtype == NVMF_TRTYPE_TCP) nvmet_port_init_tsas_tcp(port, NVMF_TCP_SECTYPE_NONE); - return count; +out: + up_write(&nvmet_config_sem); + return ret; } CONFIGFS_ATTR(nvmet_, addr_trtype); @@ -2011,7 +2019,9 @@ static void nvmet_port_release(struct config_item *item) /* Let inflight controllers teardown complete */ flush_workqueue(nvmet_wq); + down_write(&nvmet_config_sem); list_del(&port->global_entry); + up_write(&nvmet_config_sem); key_put(port->keyring); kfree(port); @@ -2072,8 +2082,6 @@ static struct config_group *nvmet_ports_make(struct config_group *group, port->ana_state[i] = NVME_ANA_INACCESSIBLE; } - list_add(&port->global_entry, &nvmet_ports_list); - INIT_LIST_HEAD(&port->entry); INIT_LIST_HEAD(&port->subsystems); INIT_LIST_HEAD(&port->referrals); @@ -2107,6 +2115,10 @@ static struct config_group *nvmet_ports_make(struct config_group *group, configfs_add_default_group(&port->ana_default_group.group, &port->ana_groups_group); + down_write(&nvmet_config_sem); + list_add(&port->global_entry, &nvmet_ports_list); + up_write(&nvmet_config_sem); + return &port->group; } diff --git a/drivers/nvme/target/core.c b/drivers/nvme/target/core.c index 0f5e94bf12bd..9bda7089b91b 100644 --- a/drivers/nvme/target/core.c +++ b/drivers/nvme/target/core.c @@ -393,11 +393,13 @@ void nvmet_disable_port(struct nvmet_port *port) lockdep_assert_held(&nvmet_config_sem); - port->enabled = false; - port->tr_ops = NULL; + if (!port->enabled) + return; - ops = nvmet_transports[port->disc_addr.trtype]; + ops = port->tr_ops; + port->enabled = false; ops->remove_port(port); + port->tr_ops = NULL; module_put(ops->owner); } @@ -1099,6 +1101,9 @@ static u32 nvmet_io_cmd_transfer_len(struct nvmet_req *req) case nvme_cmd_dsm: return nvmet_dsm_len(req); case nvme_cmd_zone_mgmt_recv: + /* The handler rejects a NUMD whose byte count would wrap. */ + if (le32_to_cpu(req->cmd->zmr.numd) >= U32_MAX / 4) + return 0; return (le32_to_cpu(req->cmd->zmr.numd) + 1) << 2; default: return 0; @@ -1359,7 +1364,7 @@ int nvmet_req_alloc_sgls(struct nvmet_req *req) return 0; out_free: - sgl_free(req->sg); + nvmet_req_free_sgls(req); out: return -ENOMEM; } @@ -1817,6 +1822,9 @@ ssize_t nvmet_ctrl_host_traddr(struct nvmet_ctrl *ctrl, { if (!ctrl->ops->host_traddr) return -EOPNOTSUPP; + /* They all take the address from the admin queue */ + if (!ctrl->sqs[0]) + return -ENOTCONN; return ctrl->ops->host_traddr(ctrl, traddr, traddr_len); } diff --git a/drivers/nvme/target/fabrics-cmd-auth.c b/drivers/nvme/target/fabrics-cmd-auth.c index d9dab0cda3b0..a15f21fc41e4 100644 --- a/drivers/nvme/target/fabrics-cmd-auth.c +++ b/drivers/nvme/target/fabrics-cmd-auth.c @@ -301,6 +301,12 @@ void nvmet_execute_auth_send(struct nvmet_req *req) nvmet_check_transfer_len(req, tl); return; } + if (tl < sizeof(struct nvmf_auth_dhchap_failure_data)) { + status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR; + req->error_loc = + offsetof(struct nvmf_auth_send_command, tl); + goto done; + } d = kmalloc(tl, GFP_KERNEL); if (!d) { @@ -339,8 +345,9 @@ void nvmet_execute_auth_send(struct nvmet_req *req) } req->sq->dhchap_step = NVME_AUTH_DHCHAP_MESSAGE_NEGOTIATE; - } else if (data->auth_id != req->sq->dhchap_step) + } else { goto done_failure1; + } /* Validate negotiation parameters */ dhchap_status = nvmet_auth_negotiate(req, d, tl); if (dhchap_status == 0) diff --git a/drivers/nvme/target/fabrics-cmd.c b/drivers/nvme/target/fabrics-cmd.c index b451029ab8f4..fc626c2fd2c9 100644 --- a/drivers/nvme/target/fabrics-cmd.c +++ b/drivers/nvme/target/fabrics-cmd.c @@ -186,8 +186,7 @@ static u16 nvmet_install_queue(struct nvmet_ctrl *ctrl, struct nvmet_req *req) pr_warn("queue size zero!\n"); req->error_loc = offsetof(struct nvmf_connect_command, sqsize); req->cqe->result.u32 = IPO_IATTR_CONNECT_SQE(sqsize); - ret = NVME_SC_CONNECT_INVALID_PARAM | NVME_STATUS_DNR; - goto err; + return NVME_SC_CONNECT_INVALID_PARAM | NVME_STATUS_DNR; } if (ctrl->sqs[qid] != NULL) { diff --git a/drivers/nvme/target/fc.c b/drivers/nvme/target/fc.c index 9b46e16641ed..2b7dc3f03912 100644 --- a/drivers/nvme/target/fc.c +++ b/drivers/nvme/target/fc.c @@ -1567,8 +1567,14 @@ nvmet_fc_delete_ctrl(struct nvmet_ctrl *ctrl) list_for_each_entry_rcu(assoc, &tgtport->assoc_list, a_list) { queue = assoc->queues[0]; if (queue && queue->nvme_sq.ctrl == ctrl) { - if (nvmet_fc_tgt_a_get(assoc)) - found_ctrl = true; + /* + * No assoc reference here: we're called with + * subsys->lock held, and if del_work beat us, + * our put would free the ctrl under that lock. + * RCU keeps the assoc alive until unlock. + */ + nvmet_fc_schedule_delete_assoc(assoc); + found_ctrl = true; break; } } @@ -1576,11 +1582,8 @@ nvmet_fc_delete_ctrl(struct nvmet_ctrl *ctrl) nvmet_fc_tgtport_put(tgtport); - if (found_ctrl) { - nvmet_fc_schedule_delete_assoc(assoc); - nvmet_fc_tgt_a_put(assoc); + if (found_ctrl) return; - } spin_lock_irqsave(&nvmet_fc_tgtlock, flags); } diff --git a/drivers/nvme/target/io-cmd-bdev.c b/drivers/nvme/target/io-cmd-bdev.c index 4b7483bc9cc3..72618dced191 100644 --- a/drivers/nvme/target/io-cmd-bdev.c +++ b/drivers/nvme/target/io-cmd-bdev.c @@ -390,7 +390,8 @@ static void nvmet_bdev_execute_discard(struct nvmet_req *req) if (status) break; - nr_sects = le32_to_cpu(range.nlb) << (ns->blksize_shift - 9); + nr_sects = (sector_t)le32_to_cpu(range.nlb) << + (ns->blksize_shift - 9); __blkdev_issue_discard(ns->bdev, nvmet_lba_to_sect(ns, range.slba), nr_sects, GFP_KERNEL, &bio); diff --git a/drivers/nvme/target/loop.c b/drivers/nvme/target/loop.c index fcb1f8186fdd..e579a307798b 100644 --- a/drivers/nvme/target/loop.c +++ b/drivers/nvme/target/loop.c @@ -221,8 +221,6 @@ static int nvme_loop_init_hctx(struct blk_mq_hw_ctx *hctx, void *data, struct nvme_loop_ctrl *ctrl = to_loop_ctrl(data); struct nvme_loop_queue *queue = &ctrl->queues[hctx_idx + 1]; - BUG_ON(hctx_idx >= ctrl->ctrl.queue_count); - /* * flush_end_io() can be called recursively for us, so use our own * lock class key for avoiding lockdep possible recursive locking, diff --git a/drivers/nvme/target/nvmet.h b/drivers/nvme/target/nvmet.h index 215315ebe42d..aab65ef2f24b 100644 --- a/drivers/nvme/target/nvmet.h +++ b/drivers/nvme/target/nvmet.h @@ -911,7 +911,8 @@ static inline void nvmet_req_bio_put(struct nvmet_req *req, struct bio *bio) #ifdef CONFIG_NVME_TARGET_TCP_TLS static inline key_serial_t nvmet_queue_tls_keyid(struct nvmet_sq *sq) { - return sq->tls_key ? key_serial(sq->tls_key) : 0; + /* A PCI endpoint controller is created without a queue */ + return sq && sq->tls_key ? key_serial(sq->tls_key) : 0; } static inline void nvmet_sq_put_tls_key(struct nvmet_sq *sq) { diff --git a/drivers/nvme/target/rdma.c b/drivers/nvme/target/rdma.c index ebf4a7bde524..b9e39d1657d2 100644 --- a/drivers/nvme/target/rdma.c +++ b/drivers/nvme/target/rdma.c @@ -513,7 +513,9 @@ static int nvmet_rdma_post_recv(struct nvmet_rdma_device *ndev, static void nvmet_rdma_process_wr_wait_list(struct nvmet_rdma_queue *queue) { - spin_lock(&queue->rsp_wr_wait_lock); + unsigned long flags; + + spin_lock_irqsave(&queue->rsp_wr_wait_lock, flags); while (!list_empty(&queue->rsp_wr_wait_list)) { struct nvmet_rdma_rsp *rsp; bool ret; @@ -522,16 +524,16 @@ static void nvmet_rdma_process_wr_wait_list(struct nvmet_rdma_queue *queue) struct nvmet_rdma_rsp, wait_list); list_del(&rsp->wait_list); - spin_unlock(&queue->rsp_wr_wait_lock); + spin_unlock_irqrestore(&queue->rsp_wr_wait_lock, flags); ret = nvmet_rdma_execute_command(rsp); - spin_lock(&queue->rsp_wr_wait_lock); + spin_lock_irqsave(&queue->rsp_wr_wait_lock, flags); if (!ret) { list_add(&rsp->wait_list, &queue->rsp_wr_wait_list); break; } } - spin_unlock(&queue->rsp_wr_wait_lock); + spin_unlock_irqrestore(&queue->rsp_wr_wait_lock, flags); } static u16 nvmet_rdma_check_pi_status(struct ib_mr *sig_mr) @@ -801,7 +803,10 @@ static void nvmet_rdma_write_data_done(struct ib_cq *cq, struct ib_wc *wc) if (unlikely(wc->status != IB_WC_SUCCESS)) { nvmet_rdma_rw_ctx_destroy(rsp); - nvmet_req_uninit(&rsp->req); + /* + * Unlike in nvmet_rdma_read_data_done(), the request has been + * completed and its references are put: no nvmet_req_uninit(). + */ nvmet_rdma_release_rsp(rsp); if (wc->status != IB_WC_WR_FLUSH_ERR) { pr_info("RDMA WRITE for CQE failed with status %s (%d).\n", @@ -977,6 +982,7 @@ static bool nvmet_rdma_execute_command(struct nvmet_rdma_rsp *rsp) static void nvmet_rdma_handle_command(struct nvmet_rdma_queue *queue, struct nvmet_rdma_rsp *cmd) { + unsigned long flags; u16 status; ib_dma_sync_single_for_cpu(queue->dev->device, @@ -994,9 +1000,9 @@ static void nvmet_rdma_handle_command(struct nvmet_rdma_queue *queue, goto out_err; if (unlikely(!nvmet_rdma_execute_command(cmd))) { - spin_lock(&queue->rsp_wr_wait_lock); + spin_lock_irqsave(&queue->rsp_wr_wait_lock, flags); list_add_tail(&cmd->wait_list, &queue->rsp_wr_wait_list); - spin_unlock(&queue->rsp_wr_wait_lock); + spin_unlock_irqrestore(&queue->rsp_wr_wait_lock, flags); } return; @@ -2151,6 +2157,12 @@ static void __exit nvmet_rdma_exit(void) { nvmet_unregister_transport(&nvmet_rdma_ops); ib_unregister_client(&nvmet_rdma_ib_client); + /* + * nvmet_rdma_remove_one() does not flush for a device that has left + * device_list, and the release work that took it off still has to + * return from nvmet_rdma_free_dev(). + */ + flush_workqueue(nvmet_wq); WARN_ON_ONCE(!list_empty(&nvmet_rdma_queue_list)); ida_destroy(&nvmet_rdma_queue_ida); } diff --git a/drivers/nvme/target/tcp.c b/drivers/nvme/target/tcp.c index 7937377436d3..85a10679d0a9 100644 --- a/drivers/nvme/target/tcp.c +++ b/drivers/nvme/target/tcp.c @@ -166,6 +166,7 @@ enum nvmet_tcp_queue_state { struct nvmet_tcp_queue { struct socket *sock; struct nvmet_tcp_port *port; + struct nvmet_port *nport; struct work_struct io_work; struct nvmet_cq nvme_cq; struct nvmet_sq nvme_sq; @@ -1512,7 +1513,7 @@ static int nvmet_tcp_alloc_cmd(struct nvmet_tcp_queue *queue, u8 hdgst = nvmet_tcp_hdgst_len(queue); c->queue = queue; - c->req.port = queue->port->nport; + c->req.port = queue->nport; c->cmd_pdu = page_frag_alloc(&queue->pf_cache, sizeof(*c->cmd_pdu) + hdgst, GFP_KERNEL | __GFP_ZERO); @@ -1969,6 +1970,8 @@ static void nvmet_tcp_alloc_queue(struct nvmet_tcp_port *port, kref_init(&queue->kref); queue->sock = newsock; queue->port = port; + /* The port may be gone when the commands are allocated */ + queue->nport = port->nport; queue->nr_cmds = 0; spin_lock_init(&queue->state_lock); if (queue->port->nport->disc_addr.tsas.tcp.sectype == @@ -2191,6 +2194,8 @@ static void nvmet_tcp_remove_port(struct nvmet_port *nport) port->sock->sk->sk_data_ready = port->data_ready; port->sock->sk->sk_user_data = NULL; write_unlock_bh(&port->sock->sk->sk_callback_lock); + /* The accept work goes on for as long as there is something to accept */ + kernel_sock_shutdown(port->sock, SHUT_RDWR); cancel_work_sync(&port->accept_work); /* * Destroy the remaining queues, which are not belong to any diff --git a/drivers/nvme/target/zns.c b/drivers/nvme/target/zns.c index 78d82b6ff121..92f5c1435582 100644 --- a/drivers/nvme/target/zns.c +++ b/drivers/nvme/target/zns.c @@ -322,9 +322,17 @@ static void nvmet_bdev_zone_zmgmt_recv_work(struct work_struct *w) void nvmet_bdev_execute_zone_mgmt_recv(struct nvmet_req *req) { - u32 out_bufsize = (le32_to_cpu(req->cmd->zmr.numd) + 1) << 2; + u32 numd = le32_to_cpu(req->cmd->zmr.numd); + + /* From U32_MAX / 4 up, (numd + 1) << 2 wraps here and in the work. */ + if (numd >= U32_MAX / 4) { + req->error_loc = offsetof(struct nvme_zone_mgmt_recv_cmd, numd); + nvmet_req_complete(req, + NVME_SC_INVALID_FIELD | NVME_STATUS_DNR); + return; + } - if (!nvmet_check_transfer_len(req, out_bufsize)) + if (!nvmet_check_transfer_len(req, (numd + 1) << 2)) return; INIT_WORK(&req->z.zmgmt_work, nvmet_bdev_zone_zmgmt_recv_work); diff --git a/drivers/nvmem/layouts/onie-tlv.c b/drivers/nvmem/layouts/onie-tlv.c index 8b0f3c1b8a0e..4da3a704388e 100644 --- a/drivers/nvmem/layouts/onie-tlv.c +++ b/drivers/nvmem/layouts/onie-tlv.c @@ -128,6 +128,7 @@ static int onie_tlv_add_cells(struct device *dev, struct nvmem_device *nvmem, ret = nvmem_add_one_cell(nvmem, &cell); if (ret) { + of_node_put(cell.np); of_node_put(layout); return ret; } diff --git a/drivers/nvmem/layouts/sl28vpd.c b/drivers/nvmem/layouts/sl28vpd.c index e93b020b0836..79de1e6947d0 100644 --- a/drivers/nvmem/layouts/sl28vpd.c +++ b/drivers/nvmem/layouts/sl28vpd.c @@ -126,6 +126,7 @@ static int sl28vpd_add_cells(struct nvmem_layout *layout) ret = nvmem_add_one_cell(nvmem, &info); if (ret) { + of_node_put(info.np); of_node_put(layout_np); return ret; } diff --git a/drivers/of/irq.c b/drivers/of/irq.c index ef1ed9743907..d10ec6e8bea0 100644 --- a/drivers/of/irq.c +++ b/drivers/of/irq.c @@ -787,7 +787,7 @@ static int of_check_msi_parent(struct device_node *dev_node, struct device_node if ((*msi_node && *msi_node != msi_spec.np) || msi_spec.args_count != 0) ret = -EINVAL; - if (!ret) { + if (!ret && !*msi_node) { /* Return with a node reference held */ *msi_node = msi_spec.np; return 0; diff --git a/drivers/opp/of.c b/drivers/opp/of.c index 2f3bbde9a9e1..ea9380079578 100644 --- a/drivers/opp/of.c +++ b/drivers/opp/of.c @@ -1409,7 +1409,7 @@ bool dev_pm_opp_of_has_required_opp(struct device *dev) * dev_pm_opp_get_of_node() - Gets the DT node corresponding to an opp * @opp: opp for which DT node has to be returned for * - * Return: DT node corresponding to the opp, else 0 on success. + * Return: DT node corresponding to the opp, else NULL. * * The caller needs to put the node with of_node_put() after using it. */ diff --git a/drivers/pci/controller/cadence/pcie-cadence-debugfs.c b/drivers/pci/controller/cadence/pcie-cadence-debugfs.c index 0a308f95e9f6..7b8354052aea 100644 --- a/drivers/pci/controller/cadence/pcie-cadence-debugfs.c +++ b/drivers/pci/controller/cadence/pcie-cadence-debugfs.c @@ -210,24 +210,21 @@ static const char *cdns_pcie_hpa_ltssm_status_string(enum cdns_pcie_hpa_ltssm lt static int ltssm_status_show(struct seq_file *s, void *v) { struct cdns_pcie *pci = s->private; - enum cdns_pcie_lga_ltssm lga_ltssm; - enum cdns_pcie_hpa_ltssm hpa_ltssm; const char *str_ltssm; - u32 val; + u32 val, ltssm_val; if (pci->is_hpa) { val = cdns_pcie_hpa_readl(pci, REG_BANK_IP_REG, CDNS_PCIE_HPA_PHY_DBG_STS_REG0); - hpa_ltssm = FIELD_GET(CDNS_PCIE_HPA_LTSSM_STATUS_MASK, val); - str_ltssm = cdns_pcie_hpa_ltssm_status_string(hpa_ltssm); + ltssm_val = FIELD_GET(CDNS_PCIE_HPA_LTSSM_STATUS_MASK, val); + str_ltssm = cdns_pcie_hpa_ltssm_status_string(ltssm_val); } else { val = cdns_pcie_readl(pci, CDNS_PCIE_LM_BASE); - lga_ltssm = FIELD_GET(CDNS_PCIE_LGA_LTSSM_STATUS_MASK, val); - str_ltssm = cdns_pcie_lga_ltssm_status_string(lga_ltssm); + ltssm_val = FIELD_GET(CDNS_PCIE_LGA_LTSSM_STATUS_MASK, val); + str_ltssm = cdns_pcie_lga_ltssm_status_string(ltssm_val); } - seq_printf(s, "%s (0x%02x)\n", str_ltssm, - pci->is_hpa ? hpa_ltssm : lga_ltssm); + seq_printf(s, "%s (0x%02x)\n", str_ltssm, ltssm_val); return 0; } diff --git a/drivers/pci/controller/dwc/pci-dra7xx.c b/drivers/pci/controller/dwc/pci-dra7xx.c index 6ae5b27e27b3..3460a83b4395 100644 --- a/drivers/pci/controller/dwc/pci-dra7xx.c +++ b/drivers/pci/controller/dwc/pci-dra7xx.c @@ -9,7 +9,6 @@ #include #include -#include #include #include #include @@ -680,7 +679,6 @@ static int dra7xx_pcie_probe(struct platform_device *pdev) int i; int phy_count; struct phy **phy; - struct device_link **link; void __iomem *base; struct dw_pcie *pci; struct dra7xx_pcie *dra7xx; @@ -728,30 +726,16 @@ static int dra7xx_pcie_probe(struct platform_device *pdev) if (!phy) return -ENOMEM; - link = devm_kcalloc(dev, phy_count, sizeof(*link), GFP_KERNEL); - if (!link) - return -ENOMEM; - - dra7xx->clk = devm_clk_get_optional(dev, NULL); + dra7xx->clk = devm_clk_get_optional_enabled(dev, NULL); if (IS_ERR(dra7xx->clk)) return dev_err_probe(dev, PTR_ERR(dra7xx->clk), "clock request failed"); - ret = clk_prepare_enable(dra7xx->clk); - if (ret) - return ret; - for (i = 0; i < phy_count; i++) { snprintf(name, sizeof(name), "pcie-phy%d", i); phy[i] = devm_phy_get(dev, name); if (IS_ERR(phy[i])) return PTR_ERR(phy[i]); - - link[i] = device_link_add(dev, &phy[i]->dev, DL_FLAG_STATELESS); - if (!link[i]) { - ret = -EINVAL; - goto err_link; - } } dra7xx->base = base; @@ -853,10 +837,6 @@ static int dra7xx_pcie_probe(struct platform_device *pdev) pm_runtime_disable(dev); dra7xx_pcie_disable_phy(dra7xx); -err_link: - while (--i >= 0) - device_link_del(link[i]); - return ret; } diff --git a/drivers/pci/controller/dwc/pci-imx6.c b/drivers/pci/controller/dwc/pci-imx6.c index 785f575e0134..59b23eb8e956 100644 --- a/drivers/pci/controller/dwc/pci-imx6.c +++ b/drivers/pci/controller/dwc/pci-imx6.c @@ -180,8 +180,12 @@ struct imx_pcie { struct imx_lut_data luts[IMX95_MAX_LUT]; /* power domain for pcie */ struct device *pd_pcie; + /* device link for pcie power domain */ + struct device_link *pd_link; /* power domain for pcie phy */ struct device *pd_pcie_phy; + /* device link for pcie phy power domain */ + struct device_link *pd_phy_link; struct phy *phy; const struct imx_pcie_drvdata *drvdata; @@ -639,10 +643,34 @@ static int imx6q_pcie_abort_handler(unsigned long addr, } #endif +static void imx_pcie_detach_pd_action(void *data) +{ + struct imx_pcie *imx_pcie = data; + + if (!IS_ERR_OR_NULL(imx_pcie->pd_phy_link)) { + device_link_del(imx_pcie->pd_phy_link); + imx_pcie->pd_phy_link = NULL; + } + + if (!IS_ERR_OR_NULL(imx_pcie->pd_link)) { + device_link_del(imx_pcie->pd_link); + imx_pcie->pd_link = NULL; + } + + if (!IS_ERR_OR_NULL(imx_pcie->pd_pcie_phy)) { + dev_pm_domain_detach(imx_pcie->pd_pcie_phy, true); + imx_pcie->pd_pcie_phy = NULL; + } + + if (!IS_ERR_OR_NULL(imx_pcie->pd_pcie)) { + dev_pm_domain_detach(imx_pcie->pd_pcie, true); + imx_pcie->pd_pcie = NULL; + } +} + static int imx_pcie_attach_pd(struct device *dev) { struct imx_pcie *imx_pcie = dev_get_drvdata(dev); - struct device_link *link; /* Do nothing when in a single power domain */ if (dev->pm_domain) @@ -654,11 +682,11 @@ static int imx_pcie_attach_pd(struct device *dev) /* Do nothing when power domain missing */ if (!imx_pcie->pd_pcie) return 0; - link = device_link_add(dev, imx_pcie->pd_pcie, - DL_FLAG_STATELESS | - DL_FLAG_PM_RUNTIME | - DL_FLAG_RPM_ACTIVE); - if (!link) { + imx_pcie->pd_link = device_link_add(dev, imx_pcie->pd_pcie, + DL_FLAG_STATELESS | + DL_FLAG_PM_RUNTIME | + DL_FLAG_RPM_ACTIVE); + if (!imx_pcie->pd_link) { dev_err(dev, "Failed to add device_link to pcie pd\n"); return -EINVAL; } @@ -667,11 +695,11 @@ static int imx_pcie_attach_pd(struct device *dev) if (IS_ERR(imx_pcie->pd_pcie_phy)) return PTR_ERR(imx_pcie->pd_pcie_phy); - link = device_link_add(dev, imx_pcie->pd_pcie_phy, - DL_FLAG_STATELESS | - DL_FLAG_PM_RUNTIME | - DL_FLAG_RPM_ACTIVE); - if (!link) { + imx_pcie->pd_phy_link = device_link_add(dev, imx_pcie->pd_pcie_phy, + DL_FLAG_STATELESS | + DL_FLAG_PM_RUNTIME | + DL_FLAG_RPM_ACTIVE); + if (!imx_pcie->pd_phy_link) { dev_err(dev, "Failed to add device_link to pcie_phy pd\n"); return -EINVAL; } @@ -1952,6 +1980,10 @@ static int imx_pcie_probe(struct platform_device *pdev) platform_set_drvdata(pdev, imx_pcie); + ret = devm_add_action_or_reset(dev, imx_pcie_detach_pd_action, imx_pcie); + if (ret) + return ret; + ret = imx_pcie_attach_pd(dev); if (ret) return ret; diff --git a/drivers/pci/controller/dwc/pcie-eswin.c b/drivers/pci/controller/dwc/pcie-eswin.c index ce8d64f8a395..1bb44696057e 100644 --- a/drivers/pci/controller/dwc/pcie-eswin.c +++ b/drivers/pci/controller/dwc/pcie-eswin.c @@ -388,6 +388,7 @@ static const struct of_device_id eswin_pcie_of_match[] = { { .compatible = "eswin,eic7700-pcie", .data = &eswin_eic7700_data }, {} }; +MODULE_DEVICE_TABLE(of, eswin_pcie_of_match); static struct platform_driver eswin_pcie_driver = { .probe = eswin_pcie_probe, diff --git a/drivers/pci/controller/dwc/pcie-qcom.c b/drivers/pci/controller/dwc/pcie-qcom.c index 89a476c37098..13c172bf4933 100644 --- a/drivers/pci/controller/dwc/pcie-qcom.c +++ b/drivers/pci/controller/dwc/pcie-qcom.c @@ -1143,50 +1143,90 @@ static void qcom_pcie_deinit_2_7_0(struct qcom_pcie *pcie) static int qcom_pcie_config_sid_1_9_0(struct qcom_pcie *pcie) { - /* iommu map structure */ - struct { - u32 bdf; - u32 phandle; - u32 smmu_sid; - u32 smmu_sid_len; - } *map; void __iomem *bdf_to_sid_base = pcie->parf + PARF_BDF_TO_SID_TABLE_N; struct device *dev = pcie->pci->dev; + struct device_node *iommu_np; u8 qcom_pcie_crc8_table[CRC8_TABLE_SIZE]; - int i, nr_map, size = 0; - u32 smmu_sid_base; + const __be32 *map; + u32 iommu_cells, entry_cells, phandle, smmu_sid_base; + int i, nr_cells, nr_map, size = 0; u32 val; - of_get_property(dev->of_node, "iommu-map", &size); - if (!size) + map = of_get_property(dev->of_node, "iommu-map", &size); + if (!map || !size) return 0; + if (size % sizeof(*map)) { + dev_err(dev, "Malformed iommu-map property\n"); + return -EINVAL; + } + nr_cells = size / sizeof(*map); + + /* + * Each iommu-map entry is: rid-base (1 cell), phandle (1 cell), + * IOMMU specifier (#iommu-cells cells), length (1 cell). Read + * #iommu-cells from the IOMMU provider referenced by the first + * entry to compute the per-entry stride. + */ + phandle = be32_to_cpu(map[1]); + iommu_np = of_find_node_by_phandle(phandle); + if (!iommu_np) { + dev_err(dev, "Failed to find IOMMU node in iommu-map\n"); + return -ENODEV; + } + + if (of_property_read_u32(iommu_np, "#iommu-cells", &iommu_cells)) + iommu_cells = 1; + of_node_put(iommu_np); + + entry_cells = 3 + iommu_cells; + + /* + * Retain backward compatibility with DTs that describe iommu-map + * with 4-cell entries against an IOMMU declaring #iommu-cells = 2, + * matching the fallback in drivers/of/base.c::of_check_bad_map(). + */ + if (iommu_cells == 2 && !(nr_cells % 4)) { + bool legacy = true; + + for (i = 0; i < nr_cells; i += 4) { + if (be32_to_cpu(map[i + 1]) != phandle || + be32_to_cpu(map[i + 3]) != 1) { + legacy = false; + break; + } + } + + if (legacy) { + dev_warn_once(dev, "iommu-map has 1-cell entries with #iommu-cells=2, using 1-cell\n"); + entry_cells = 4; + } + } + + if (nr_cells % entry_cells) { + dev_err(dev, "Malformed iommu-map property\n"); + return -EINVAL; + } + nr_map = nr_cells / entry_cells; + /* Enable BDF to SID translation by disabling bypass mode (default) */ val = readl(pcie->parf + PARF_BDF_TO_SID_CFG); val &= ~BDF_TO_SID_BYPASS; writel(val, pcie->parf + PARF_BDF_TO_SID_CFG); - map = kzalloc(size, GFP_KERNEL); - if (!map) - return -ENOMEM; - - of_property_read_u32_array(dev->of_node, "iommu-map", (u32 *)map, - size / sizeof(u32)); - - nr_map = size / (sizeof(*map)); - crc8_populate_msb(qcom_pcie_crc8_table, QCOM_PCIE_CRC8_POLYNOMIAL); /* Registers need to be zero out first */ memset_io(bdf_to_sid_base, 0, CRC8_TABLE_SIZE * sizeof(u32)); /* Extract the SMMU SID base from the first entry of iommu-map */ - smmu_sid_base = map[0].smmu_sid; + smmu_sid_base = be32_to_cpu(map[2]); /* Look for an available entry to hold the mapping */ for (i = 0; i < nr_map; i++) { - __be16 bdf_be = cpu_to_be16(map[i].bdf); - u32 val; + u32 bdf = be32_to_cpu(map[i * entry_cells]); + u32 sid = be32_to_cpu(map[i * entry_cells + 2]); + __be16 bdf_be = cpu_to_be16(bdf); u8 hash; hash = crc8(qcom_pcie_crc8_table, (u8 *)&bdf_be, sizeof(bdf_be), 0); @@ -1208,12 +1248,10 @@ static int qcom_pcie_config_sid_1_9_0(struct qcom_pcie *pcie) } /* BDF [31:16] | SID [15:8] | NEXT [7:0] */ - val = map[i].bdf << 16 | (map[i].smmu_sid - smmu_sid_base) << 8 | 0; + val = bdf << 16 | (sid - smmu_sid_base) << 8 | 0; writel(val, bdf_to_sid_base + hash * sizeof(u32)); } - kfree(map); - return 0; } @@ -1821,6 +1859,9 @@ static int qcom_pcie_reset_root_port(struct pci_host_bridge *bridge, qcom_pcie_start_link(pci); ret = dw_pcie_wait_for_link(pci); + /* This linkdown might have been a hot-unplug */ + if (ret == -ENODEV) + ret = 0; if (ret) return ret; diff --git a/drivers/pci/controller/dwc/pcie-rcar-gen4.c b/drivers/pci/controller/dwc/pcie-rcar-gen4.c index 241adcd72789..964b45f8f9b7 100644 --- a/drivers/pci/controller/dwc/pcie-rcar-gen4.c +++ b/drivers/pci/controller/dwc/pcie-rcar-gen4.c @@ -524,6 +524,8 @@ static int rcar_gen4_add_dw_pcie_rp(struct rcar_gen4_pcie *rcar) return -ENODEV; pp->num_vectors = MAX_MSI_IRQS; + /* Reserve an iATU window for the generic PME_Turn_Off implementation. */ + pp->use_atu_msg = true; pp->ops = &rcar_gen4_pcie_host_ops; return dw_pcie_host_init(pp); @@ -903,6 +905,26 @@ static int rcar_gen4_pcie_ltssm_control(struct rcar_gen4_pcie *rcar, bool enable return 0; } +static int rcar_gen4_pcie_suspend_noirq(struct device *dev) +{ + struct rcar_gen4_pcie *rcar = dev_get_drvdata(dev); + + if (rcar->drvdata->mode != DW_PCIE_RC_TYPE) + return 0; + + return dw_pcie_suspend_noirq(&rcar->dw); +} + +static int rcar_gen4_pcie_resume_noirq(struct device *dev) +{ + struct rcar_gen4_pcie *rcar = dev_get_drvdata(dev); + + if (rcar->drvdata->mode != DW_PCIE_RC_TYPE) + return 0; + + return dw_pcie_resume_noirq(&rcar->dw); +} + static struct rcar_gen4_pcie_drvdata drvdata_r8a779f0_pcie = { .ltssm_control = r8a779f0_pcie_ltssm_control, .mode = DW_PCIE_RC_TYPE, @@ -946,10 +968,15 @@ static const struct of_device_id rcar_gen4_pcie_of_match[] = { }; MODULE_DEVICE_TABLE(of, rcar_gen4_pcie_of_match); +static DEFINE_NOIRQ_DEV_PM_OPS(rcar_gen4_pcie_pm_ops, + rcar_gen4_pcie_suspend_noirq, + rcar_gen4_pcie_resume_noirq); + static struct platform_driver rcar_gen4_pcie_driver = { .driver = { .name = "pcie-rcar-gen4", .of_match_table = rcar_gen4_pcie_of_match, + .pm = pm_sleep_ptr(&rcar_gen4_pcie_pm_ops), .probe_type = PROBE_PREFER_ASYNCHRONOUS, }, .probe = rcar_gen4_pcie_probe, diff --git a/drivers/pci/controller/pci-aardvark.c b/drivers/pci/controller/pci-aardvark.c index ecb81ac73019..2bbdb73cfb45 100644 --- a/drivers/pci/controller/pci-aardvark.c +++ b/drivers/pci/controller/pci-aardvark.c @@ -1864,28 +1864,25 @@ static int advk_pcie_probe(struct platform_device *pdev) ret = advk_sw_pci_bridge_init(pcie); if (ret) { dev_err(dev, "Failed to register emulated root PCI bridge\n"); - return ret; + goto err_disable_phy; } ret = advk_pcie_init_irq_domain(pcie); if (ret) { dev_err(dev, "Failed to initialize irq\n"); - return ret; + goto err_cleanup_bridge; } ret = advk_pcie_init_msi_irq_domain(pcie); if (ret) { dev_err(dev, "Failed to initialize irq\n"); - advk_pcie_remove_irq_domain(pcie); - return ret; + goto err_remove_irq_domain; } ret = advk_pcie_init_rp_irq_domain(pcie); if (ret) { dev_err(dev, "Failed to initialize irq\n"); - advk_pcie_remove_msi_irq_domain(pcie); - advk_pcie_remove_irq_domain(pcie); - return ret; + goto err_remove_msi_irq_domain; } bridge->sysdata = pcie; @@ -1893,14 +1890,22 @@ static int advk_pcie_probe(struct platform_device *pdev) bridge->map_irq = advk_pcie_map_irq; ret = pci_host_probe(bridge); - if (ret < 0) { - advk_pcie_remove_rp_irq_domain(pcie); - advk_pcie_remove_msi_irq_domain(pcie); - advk_pcie_remove_irq_domain(pcie); - return ret; - } + if (ret < 0) + goto err_remove_rp_irq_domain; return 0; + +err_remove_rp_irq_domain: + advk_pcie_remove_rp_irq_domain(pcie); +err_remove_msi_irq_domain: + advk_pcie_remove_msi_irq_domain(pcie); +err_remove_irq_domain: + advk_pcie_remove_irq_domain(pcie); +err_cleanup_bridge: + pci_bridge_emul_cleanup(&pcie->bridge); +err_disable_phy: + advk_pcie_disable_phy(pcie); + return ret; } static void advk_pcie_remove(struct platform_device *pdev) diff --git a/drivers/pci/controller/pci-xgene.c b/drivers/pci/controller/pci-xgene.c index 83c9a2930eec..a5b8bbc04a22 100644 --- a/drivers/pci/controller/pci-xgene.c +++ b/drivers/pci/controller/pci-xgene.c @@ -320,18 +320,11 @@ static void xgene_pcie_linkup(struct xgene_pcie *port, static int xgene_pcie_init_port(struct xgene_pcie *port) { struct device *dev = port->dev; - int rc; - port->clk = clk_get(dev, NULL); + port->clk = devm_clk_get_enabled(dev, NULL); if (IS_ERR(port->clk)) { dev_err(dev, "clock not available\n"); - return -ENODEV; - } - - rc = clk_prepare_enable(port->clk); - if (rc) { - dev_err(dev, "clock enable failed\n"); - return rc; + return PTR_ERR(port->clk); } return 0; diff --git a/drivers/pci/controller/pcie-iproc-bcma.c b/drivers/pci/controller/pcie-iproc-bcma.c index 593418c2bc3a..1e258cd8fed4 100644 --- a/drivers/pci/controller/pcie-iproc-bcma.c +++ b/drivers/pci/controller/pcie-iproc-bcma.c @@ -11,7 +11,9 @@ #include #include #include +#include +#include "../pci.h" #include "pcie-iproc.h" @@ -31,6 +33,29 @@ static int iproc_bcma_pcie_map_irq(const struct pci_dev *dev, u8 slot, u8 pin) return bcma_core_irq(bdev, 5); } +static void iproc_bcma_pcie_check_dt_window(struct iproc_pcie *pcie) +{ + struct device_node *np = pcie->dev->of_node; + struct of_pci_range_parser parser; + struct of_pci_range range; + struct resource res; + + if (!np || of_pci_range_parser_init(&parser, np)) + return; + + for_each_of_pci_range(&parser, &range) { + if ((range.flags & IORESOURCE_TYPE_BITS) != IORESOURCE_MEM) + continue; + + if (of_pci_range_to_resource(&range, np, &res)) + continue; + + if (res.start != pcie->mem.start || res.end != pcie->mem.end) + dev_warn(pcie->dev, "DT window %pR does not match EROM window %pR, using EROM\n", + &res, &pcie->mem); + } +} + static int iproc_bcma_pcie_probe(struct bcma_device *bdev) { struct device *dev = &bdev->dev; @@ -38,10 +63,20 @@ static int iproc_bcma_pcie_probe(struct bcma_device *bdev) struct pci_host_bridge *bridge; int ret; - bridge = devm_pci_alloc_host_bridge(dev, sizeof(*pcie)); + bridge = pci_alloc_host_bridge(sizeof(*pcie)); if (!bridge) return -ENOMEM; + bridge->dev.parent = dev; + + ret = devm_add_action_or_reset(dev, devm_pci_alloc_host_bridge_release, + bridge); + if (ret) + return -ENOMEM; + + bridge->swizzle_irq = pci_common_swizzle; + bridge->map_irq = iproc_bcma_pcie_map_irq; + pcie = pci_host_bridge_priv(bridge); pcie->dev = dev; @@ -59,13 +94,12 @@ static int iproc_bcma_pcie_probe(struct bcma_device *bdev) pcie->mem.end = bdev->addr_s[0] + SZ_128M - 1; pcie->mem.name = "PCIe MEM space"; pcie->mem.flags = IORESOURCE_MEM; + iproc_bcma_pcie_check_dt_window(pcie); pci_add_resource(&bridge->windows, &pcie->mem); ret = devm_request_pci_bus_resources(dev, &bridge->windows); if (ret) return ret; - bridge->map_irq = iproc_bcma_pcie_map_irq; - bcma_set_drvdata(bdev, pcie); return iproc_pcie_setup(pcie, &bridge->windows); diff --git a/drivers/pci/controller/pcie-tegra264.c b/drivers/pci/controller/pcie-tegra264.c index 653136db401e..c97576ab4a31 100644 --- a/drivers/pci/controller/pcie-tegra264.c +++ b/drivers/pci/controller/pcie-tegra264.c @@ -49,8 +49,7 @@ #define XAL_RC_BAR_CNTL_STANDARD_64B_BAR_EN BIT(2) /* XTL registers */ -#define XTL_RC_PCIE_CFG_LINK_CAPS 0x56 -#define XTL_RC_PCIE_CFG_LINK_STATUS 0x5a +#define XTL_RC_PCIE_CAP 0x48 /* PCIe Capability */ #define XTL_RC_MGMT_PERST_CONTROL 0x218 #define XTL_RC_MGMT_PERST_CONTROL_PERST_O_N BIT(0) @@ -118,11 +117,11 @@ static void tegra264_pcie_icc_set(struct tegra264_pcie *pcie) * possible, so this is as good as it gets for now. */ if (pcie->link_up) { - value = readw(pcie->ecam + XTL_RC_PCIE_CFG_LINK_STATUS); + value = readw(pcie->ecam + XTL_RC_PCIE_CAP + PCI_EXP_LNKSTA); speed = FIELD_GET(PCI_EXP_LNKSTA_CLS, value); width = FIELD_GET(PCI_EXP_LNKSTA_NLW, value); } else { - value = readw(pcie->ecam + XTL_RC_PCIE_CFG_LINK_CAPS); + value = readl(pcie->ecam + XTL_RC_PCIE_CAP + PCI_EXP_LNKCAP); speed = FIELD_GET(PCI_EXP_LNKCAP_SLS, value); width = FIELD_GET(PCI_EXP_LNKCAP_MLW, value); } @@ -263,7 +262,7 @@ static bool tegra264_pcie_supports_hotplug(struct tegra264_pcie *pcie) static bool tegra264_pcie_link_up(struct tegra264_pcie *pcie, enum pci_bus_speed *speed) { - u16 value = readw(pcie->ecam + XTL_RC_PCIE_CFG_LINK_STATUS); + u16 value = readw(pcie->ecam + XTL_RC_PCIE_CAP + PCI_EXP_LNKSTA); if (value & PCI_EXP_LNKSTA_DLLLA) { if (speed) diff --git a/drivers/pci/endpoint/functions/pci-epf-vntb.c b/drivers/pci/endpoint/functions/pci-epf-vntb.c index 8ae50779452a..f77e28f2fe96 100644 --- a/drivers/pci/endpoint/functions/pci-epf-vntb.c +++ b/drivers/pci/endpoint/functions/pci-epf-vntb.c @@ -41,6 +41,7 @@ #include #include #include +#include #include #include @@ -147,7 +148,11 @@ struct epf_ntb { u16 vntb_pid; u16 vntb_vid; - bool linkup; + /* Serialize HOST and VHOST link state changes. */ + struct mutex link_lock; + bool host_link_enabled; + bool vhost_link_enabled; + bool peer_msix; /* * True when doorbells are interrupt-driven (MSI or embedded), false @@ -155,6 +160,7 @@ struct epf_ntb { */ bool msi_doorbell; u32 spad_size; + u32 msix_table_offset; enum pci_barno epf_ntb_bar[VNTB_BAR_NUM]; @@ -183,24 +189,58 @@ static struct pci_epf_header epf_ntb_header = { .interrupt_pin = PCI_INTERRUPT_INTA, }; +static void epf_ntb_update_link(struct epf_ntb *ntb) +{ + u16 link_status = READ_ONCE(ntb->reg->link_status); + + /* The link is usable only after both sides have enabled it. */ + if (ntb->host_link_enabled && ntb->vhost_link_enabled) + link_status |= LINK_STATUS_UP; + else + link_status &= ~LINK_STATUS_UP; + + WRITE_ONCE(ntb->reg->link_status, link_status); +} + +static int epf_ntb_notify_link(struct ntb_dev *ndev) +{ + struct epf_ntb *ntb = ntb_ndev(ndev); + struct pci_epf *epf = ntb->epf; + unsigned int irq_type; + int ret; + + ntb_link_event(ndev); + + irq_type = ntb->peer_msix ? PCI_IRQ_MSIX : PCI_IRQ_MSI; + ret = pci_epc_raise_irq(epf->epc, epf->func_no, epf->vfunc_no, + irq_type, EPF_IRQ_LINK + 1); + if (ret) + dev_err(&epf->dev, "Failed to raise link event IRQ: %d\n", ret); + + return ret; +} + /** - * epf_ntb_link_up() - Raise link_up interrupt to Virtual Host (VHOST) + * epf_ntb_set_link_enabled() - Set HOST link enablement * @ntb: NTB device that facilitates communication between HOST and VHOST - * @link_up: true or false indicating Link is UP or Down - * - * Once NTB function in HOST invoke ntb_link_enable(), - * this NTB function driver will trigger a link event to VHOST. + * @enabled: true when the HOST has enabled the link * * Returns: Zero for success, or an error code in case of failure */ -static int epf_ntb_link_up(struct epf_ntb *ntb, bool link_up) +static int epf_ntb_set_link_enabled(struct epf_ntb *ntb, bool enabled) { - if (link_up) - ntb->reg->link_status |= LINK_STATUS_UP; - else - ntb->reg->link_status &= ~LINK_STATUS_UP; + bool notify; + + scoped_guard(mutex, &ntb->link_lock) { + notify = ntb->host_link_enabled != enabled && + ntb->vhost_link_enabled; + ntb->host_link_enabled = enabled; + epf_ntb_update_link(ntb); + } + + if (notify) + return epf_ntb_notify_link(ntb->ntb); - ntb_link_event(ntb->ntb); return 0; } @@ -276,6 +316,7 @@ static void epf_ntb_teardown_mw(struct epf_ntb *ntb, u32 mw) */ static void epf_ntb_cmd_handler(struct work_struct *work) { + const struct pci_epc_features *epc_features; struct epf_ntb_ctrl *ctrl; u32 command, argument; struct epf_ntb *ntb; @@ -308,6 +349,15 @@ static void epf_ntb_cmd_handler(struct work_struct *work) switch (command) { case COMMAND_CONFIGURE_DOORBELL: + epc_features = pci_epc_get_features(ntb->epf->epc, + ntb->epf->func_no, + ntb->epf->vfunc_no); + if (((argument & MSIX_ENABLE) && !epc_features->msix_capable) || + (!(argument & MSIX_ENABLE) && !epc_features->msi_capable)) { + ctrl->command_status = COMMAND_STATUS_ERROR; + break; + } + ntb->peer_msix = argument & MSIX_ENABLE; ctrl->command_status = COMMAND_STATUS_OK; break; case COMMAND_TEARDOWN_DOORBELL: @@ -325,16 +375,14 @@ static void epf_ntb_cmd_handler(struct work_struct *work) ctrl->command_status = COMMAND_STATUS_OK; break; case COMMAND_LINK_UP: - ntb->linkup = true; - ret = epf_ntb_link_up(ntb, true); + ret = epf_ntb_set_link_enabled(ntb, true); if (ret < 0) ctrl->command_status = COMMAND_STATUS_ERROR; else ctrl->command_status = COMMAND_STATUS_OK; goto reset_handler; case COMMAND_LINK_DOWN: - ntb->linkup = false; - ret = epf_ntb_link_up(ntb, false); + ret = epf_ntb_set_link_enabled(ntb, false); if (ret < 0) ctrl->command_status = COMMAND_STATUS_ERROR; else @@ -451,8 +499,9 @@ static void epf_ntb_config_spad_bar_free(struct epf_ntb *ntb) * @ntb: NTB device that facilitates communication between HOST and VHOST * * Allocate the Local Memory mentioned in the above diagram. The size of - * CONFIG REGION is sizeof(struct epf_ntb_ctrl) and size of SCRATCHPAD REGION - * is obtained from "spad-count" configfs entry. + * CONFIG REGION is sizeof(struct epf_ntb_ctrl), plus space for the MSI-X + * Table and PBA if supported. The size of SCRATCHPAD REGION is obtained + * from "spad-count" configfs entry. * * Returns: Zero for success, or an error code in case of failure */ @@ -473,6 +522,12 @@ static int epf_ntb_config_spad_bar_alloc(struct epf_ntb *ntb) spad_count = ntb->spad_count; ctrl_size = ALIGN(sizeof(struct epf_ntb_ctrl), sizeof(u32)); + if (epc_features->msix_capable) { + ntb->msix_table_offset = ALIGN(ctrl_size, 8); + ctrl_size = ntb->msix_table_offset + + ntb->db_count * PCI_MSIX_ENTRY_SIZE + + BITS_TO_U64(ntb->db_count) * sizeof(u64); + } spad_size = 2 * spad_count * sizeof(u32); base = pci_epf_alloc_space(epf, ctrl_size + spad_size, @@ -513,12 +568,14 @@ static int epf_ntb_config_spad_bar_alloc(struct epf_ntb *ntb) static int epf_ntb_configure_interrupt(struct epf_ntb *ntb) { const struct pci_epc_features *epc_features; + struct pci_epf *epf = ntb->epf; struct device *dev; int ret; - dev = &ntb->epf->dev; + dev = &epf->dev; - epc_features = pci_epc_get_features(ntb->epf->epc, ntb->epf->func_no, ntb->epf->vfunc_no); + epc_features = pci_epc_get_features(epf->epc, epf->func_no, + epf->vfunc_no); if (!(epc_features->msix_capable || epc_features->msi_capable)) { dev_err(dev, "MSI or MSI-X is required for doorbell\n"); @@ -532,16 +589,24 @@ static int epf_ntb_configure_interrupt(struct epf_ntb *ntb) } if (epc_features->msi_capable) { - ret = pci_epc_set_msi(ntb->epf->epc, - ntb->epf->func_no, - ntb->epf->vfunc_no, - 16); + ret = pci_epc_set_msi(epf->epc, epf->func_no, epf->vfunc_no, 16); if (ret) { dev_err(dev, "MSI configuration failed\n"); return ret; } } + if (epc_features->msix_capable) { + ret = pci_epc_set_msix(epf->epc, epf->func_no, epf->vfunc_no, + ntb->db_count, + ntb->epf_ntb_bar[BAR_CONFIG], + ntb->msix_table_offset); + if (ret) { + dev_err(dev, "MSI-X configuration failed\n"); + return ret; + } + } + return 0; } @@ -1342,15 +1407,20 @@ static int vpci_scan_bus(void *sysdata) struct pci_bus *vpci_bus; struct epf_ntb *ndev = sysdata; + pci_lock_rescan_remove(); + vpci_bus = pci_scan_bus(ndev->vbus_number, &vpci_ops, sysdata); if (!vpci_bus) { pr_err("create pci bus failed\n"); + pci_unlock_rescan_remove(); return -EINVAL; } ndev->vpci_bus = vpci_bus; pci_bus_add_devices(vpci_bus); + pci_unlock_rescan_remove(); + return 0; } @@ -1438,7 +1508,8 @@ static int vntb_epf_mw_set_trans(struct ntb_dev *ndev, int pidx, int idx, epf_bar->barno = barno; epf_bar->size = size; - ret = pci_epc_set_bar(ntb->epf->epc, 0, 0, epf_bar); + ret = pci_epc_set_bar(ntb->epf->epc, ntb->epf->func_no, + ntb->epf->vfunc_no, epf_bar); if (ret) { dev_err(dev, "failure set mw trans\n"); return ret; @@ -1466,11 +1537,29 @@ static int vntb_epf_peer_mw_get_addr(struct ntb_dev *ndev, int idx, return 0; } +static int vntb_epf_set_link_enabled(struct ntb_dev *ndev, bool enabled) +{ + struct epf_ntb *ntb = ntb_ndev(ndev); + bool notify; + + scoped_guard(mutex, &ntb->link_lock) { + notify = ntb->vhost_link_enabled != enabled && + ntb->host_link_enabled; + ntb->vhost_link_enabled = enabled; + epf_ntb_update_link(ntb); + } + + if (notify) + return epf_ntb_notify_link(ndev); + + return 0; +} + static int vntb_epf_link_enable(struct ntb_dev *ntb, enum ntb_speed max_speed, enum ntb_width max_width) { - return 0; + return vntb_epf_set_link_enabled(ntb, true); } static u32 vntb_epf_spad_read(struct ntb_dev *ndev, int idx) @@ -1523,6 +1612,7 @@ static void vntb_epf_peer_db_work(struct work_struct *work) struct epf_ntb *ntb = container_of(work, struct epf_ntb, peer_db_work); struct pci_epf *epf = ntb->epf; unsigned int budget = VNTB_PEER_DB_WORK_BUDGET; + unsigned int irq_type; u8 func_no, vfunc_no; unsigned int db_bit; u32 interrupt_num; @@ -1534,6 +1624,7 @@ static void vntb_epf_peer_db_work(struct work_struct *work) func_no = epf->func_no; vfunc_no = epf->vfunc_no; + irq_type = ntb->peer_msix ? PCI_IRQ_MSIX : PCI_IRQ_MSI; /* * Drain doorbells from peer_db_pending in snapshots (atomic64_xchg()). @@ -1547,7 +1638,7 @@ static void vntb_epf_peer_db_work(struct work_struct *work) while (db_bits) { /* - * pci_epc_raise_irq() for MSI expects a 1-based + * pci_epc_raise_irq() for MSI/MSI-X expects a 1-based * interrupt number. The first usable doorbell starts * at EPF_IRQ_DB_START in the legacy slot layout. * @@ -1567,7 +1658,7 @@ static void vntb_epf_peer_db_work(struct work_struct *work) db_bits &= ~BIT_ULL(db_bit); ret = pci_epc_raise_irq(epf->epc, func_no, vfunc_no, - PCI_IRQ_MSI, interrupt_num); + irq_type, interrupt_num); if (ret) dev_err(&epf->dev, "Failed to raise IRQ for interrupt_num %u: %d\n", @@ -1630,7 +1721,7 @@ static u64 vntb_epf_link_is_up(struct ntb_dev *ndev, { struct epf_ntb *ntb = ntb_ndev(ndev); - return ntb->reg->link_status; + return READ_ONCE(ntb->reg->link_status); } static int vntb_epf_db_clear_mask(struct ntb_dev *ndev, u64 db_bits) @@ -1648,7 +1739,7 @@ static int vntb_epf_db_clear(struct ntb_dev *ndev, u64 db_bits) static int vntb_epf_link_disable(struct ntb_dev *ntb) { - return 0; + return vntb_epf_set_link_enabled(ntb, false); } static struct device *vntb_epf_get_dma_dev(struct ntb_dev *ndev) @@ -1791,6 +1882,10 @@ static int epf_ntb_bind(struct pci_epf *epf) goto err_bar_alloc; } + ntb->host_link_enabled = false; + ntb->vhost_link_enabled = false; + ntb->reg->link_status = 0; + ret = epf_ntb_epc_init(ntb); if (ret) { dev_err(dev, "Failed to initialize EPC\n"); @@ -1876,7 +1971,7 @@ static int epf_ntb_probe(struct pci_epf *epf, { struct epf_ntb *ntb; struct device *dev; - int i; + int ret, i; dev = &epf->dev; @@ -1887,6 +1982,9 @@ static int epf_ntb_probe(struct pci_epf *epf, epf->header = &epf_ntb_header; ntb->epf = epf; ntb->vbus_number = 0xff; + ret = devm_mutex_init(dev, &ntb->link_lock); + if (ret) + return ret; INIT_WORK(&ntb->peer_db_work, vntb_epf_peer_db_work); disable_work(&ntb->peer_db_work); diff --git a/drivers/pci/hotplug/pciehp_core.c b/drivers/pci/hotplug/pciehp_core.c index 5ce32dc7e178..a25fbd995424 100644 --- a/drivers/pci/hotplug/pciehp_core.c +++ b/drivers/pci/hotplug/pciehp_core.c @@ -258,7 +258,7 @@ static bool pme_is_native(struct pcie_device *dev) const struct pci_host_bridge *host; host = pci_find_host_bridge(dev->port->bus); - return pcie_ports_native || host->native_pme; + return host->native_pme; } static void pciehp_disable_interrupt(struct pcie_device *dev) diff --git a/drivers/pci/iov.c b/drivers/pci/iov.c index 9d408fb8ac25..9185934a900f 100644 --- a/drivers/pci/iov.c +++ b/drivers/pci/iov.c @@ -179,29 +179,6 @@ bool pci_iov_is_memory_decoding_enabled(struct pci_dev *dev) return cmd & PCI_SRIOV_CTRL_MSE; } -static void pci_read_vf_config_common(struct pci_dev *virtfn) -{ - struct pci_dev *physfn = virtfn->physfn; - - /* - * Some config registers are the same across all associated VFs. - * Read them once from VF0 so we can skip reading them from the - * other VFs. - * - * PCIe r4.0, sec 9.3.4.1, technically doesn't require all VFs to - * have the same Revision ID and Subsystem ID, but we assume they - * do. - */ - pci_read_config_dword(virtfn, PCI_CLASS_REVISION, - &physfn->sriov->class); - pci_read_config_byte(virtfn, PCI_HEADER_TYPE, - &physfn->sriov->hdr_type); - pci_read_config_word(virtfn, PCI_SUBSYSTEM_VENDOR_ID, - &physfn->sriov->subsystem_vendor); - pci_read_config_word(virtfn, PCI_SUBSYSTEM_ID, - &physfn->sriov->subsystem_device); -} - int pci_iov_sysfs_link(struct pci_dev *dev, struct pci_dev *virtfn, int id) { @@ -329,8 +306,6 @@ static struct pci_dev *pci_iov_scan_device(struct pci_dev *dev, int id, virtfn->physfn = pci_dev_get(dev); virtfn->no_command_memory = 1; - if (id == 0) - pci_read_vf_config_common(virtfn); rc = pci_setup_device(virtfn); if (rc) { diff --git a/drivers/pci/p2pdma.c b/drivers/pci/p2pdma.c index 9334eb314663..82d37704536b 100644 --- a/drivers/pci/p2pdma.c +++ b/drivers/pci/p2pdma.c @@ -236,9 +236,8 @@ static void pci_p2pdma_release(void *data) return; /* Flush and disable pci_alloc_p2p_mem() */ - pdev->p2pdma = NULL; - if (p2pdma->pool) - synchronize_rcu(); + RCU_INIT_POINTER(pdev->p2pdma, NULL); + synchronize_rcu(); xa_destroy(&p2pdma->map_types); if (!p2pdma->pool) @@ -440,8 +439,8 @@ int pci_p2pdma_add_resource(struct pci_dev *pdev, int bar, size_t size, goto pgmap_free; } - error = devm_add_action_or_reset(&pdev->dev, pci_p2pdma_unmap_mappings, - p2p_pgmap); + error = devm_add_action(&pdev->dev, pci_p2pdma_unmap_mappings, + p2p_pgmap); if (error) goto pages_free; @@ -451,13 +450,15 @@ int pci_p2pdma_add_resource(struct pci_dev *pdev, int bar, size_t size, range_len(&pgmap->range), dev_to_node(&pdev->dev), &pgmap->ref); if (error) - goto pages_free; + goto mappings_remove; pci_info(pdev, "added peer-to-peer DMA memory %#llx-%#llx\n", pgmap->range.start, pgmap->range.end); return 0; +mappings_remove: + devm_remove_action(&pdev->dev, pci_p2pdma_unmap_mappings, p2p_pgmap); pages_free: devm_memunmap_pages(&pdev->dev, pgmap); pgmap_free: @@ -708,7 +709,6 @@ calc_map_type_and_dist(struct pci_dev *provider, struct pci_dev *client, { enum pci_p2pdma_map_type map_type = PCI_P2PDMA_MAP_THRU_HOST_BRIDGE; struct pci_dev *a = provider, *b = client, *bb; - bool acs_redirects = false; struct pci_p2pdma *p2pdma; struct seq_buf acs_list; int acs_cnt = 0; @@ -771,17 +771,18 @@ calc_map_type_and_dist(struct pci_dev *provider, struct pci_dev *client, } if (verbose) { - acs_list.buffer[acs_list.len-1] = 0; /* drop final semicolon */ + /* Drop the final semicolon; the list is not empty here */ + if (!seq_buf_has_overflowed(&acs_list)) + acs_list.buffer[acs_list.len - 1] = '\0'; pci_warn(client, "ACS redirect is set between the client and provider (%s)\n", pci_name(provider)); pci_warn(client, "to disable ACS redirect for this path, add the kernel parameter: pci=disable_acs_redir=%s\n", - acs_list.buffer); + seq_buf_str(&acs_list)); } - acs_redirects = true; map_through_host_bridge: if (!cpu_supports_p2pdma() && - !host_bridge_whitelist(provider, client, acs_redirects)) { + !host_bridge_whitelist(provider, client, verbose)) { if (verbose) pci_warn(client, "cannot be used for peer-to-peer DMA as the client and provider (%s) do not share an upstream bridge or whitelisted host bridge\n", pci_name(provider)); diff --git a/drivers/pci/pci-acpi.c b/drivers/pci/pci-acpi.c index 42d545edd7fa..1150f2fbabf4 100644 --- a/drivers/pci/pci-acpi.c +++ b/drivers/pci/pci-acpi.c @@ -812,9 +812,6 @@ bool pciehp_is_native(struct pci_dev *bridge) if (!IS_ENABLED(CONFIG_HOTPLUG_PCI_PCIE)) return false; - if (pcie_ports_native) - return true; - host = pci_find_host_bridge(bridge->bus); return host->native_pcie_hotplug; } diff --git a/drivers/pci/pci-label.c b/drivers/pci/pci-label.c index c224619b9a26..08c461f1142d 100644 --- a/drivers/pci/pci-label.c +++ b/drivers/pci/pci-label.c @@ -157,40 +157,53 @@ static int dsm_get_label(struct device *dev, char *buf, { acpi_handle handle = ACPI_HANDLE(dev); union acpi_object *obj, *tmp; - int len = 0; + int len; if (!handle) - return -1; + return -ENODEV; obj = acpi_evaluate_dsm(handle, &pci_acpi_dsm_guid, 0x2, DSM_PCI_DEVICE_NAME, NULL); if (!obj) - return -1; + return -EIO; + + if (obj->type != ACPI_TYPE_PACKAGE || obj->package.count != 2) { + len = -EIO; + goto out; + } tmp = obj->package.elements; - if (obj->type == ACPI_TYPE_PACKAGE && obj->package.count == 2 && - tmp[0].type == ACPI_TYPE_INTEGER && - (tmp[1].type == ACPI_TYPE_STRING || - tmp[1].type == ACPI_TYPE_BUFFER)) { - /* - * The second string element is optional even when - * this _DSM is implemented; when not implemented, - * this entry must return a null string. - */ - if (attr == ACPI_ATTR_INDEX_SHOW) { - len = sysfs_emit(buf, "%llu\n", tmp->integer.value); - } else if (attr == ACPI_ATTR_LABEL_SHOW) { - if (tmp[1].type == ACPI_TYPE_STRING) - len = sysfs_emit(buf, "%s\n", - tmp[1].string.pointer); - else if (tmp[1].type == ACPI_TYPE_BUFFER) - len = dsm_label_utf16s_to_utf8s(tmp + 1, buf); - } + if (tmp[0].type != ACPI_TYPE_INTEGER) { + len = -EIO; + goto out; + } + + if (attr == ACPI_ATTR_INDEX_SHOW) { + len = sysfs_emit(buf, "%llu\n", tmp[0].integer.value); + goto out; } + /* + * Per PCI Firmware r3.3, sec 4.6.7, the device name is optional + * even when this _DSM is implemented. When not implemented, this + * entry must return a NULL string. + */ + switch (tmp[1].type) { + case ACPI_TYPE_STRING: + len = sysfs_emit(buf, "%s\n", tmp[1].string.pointer); + break; + case ACPI_TYPE_BUFFER: + len = dsm_label_utf16s_to_utf8s(&tmp[1], buf); + break; + default: + len = -EIO; + break; + } + +out: ACPI_FREE(obj); - return len > 0 ? len : -1; + return len; } static ssize_t label_show(struct device *dev, struct device_attribute *attr, @@ -217,11 +230,42 @@ static umode_t acpi_attr_is_visible(struct kobject *kobj, struct attribute *a, int n) { struct device *dev = kobj_to_dev(kobj); + union acpi_object *obj, *tmp; + umode_t mode = 0; if (!device_has_acpi_name(dev)) return 0; - return a->mode; + /* + * The bitmap from _DSM function 0 only advertises function 7, + * and whether the returned object can be parsed is a separate + * question. Evaluate it and expose each attribute only if the + * element it exports has one of the types the read path + * accepts, mirroring the checks in dsm_get_label(). + */ + obj = acpi_evaluate_dsm(ACPI_HANDLE(dev), &pci_acpi_dsm_guid, 0x2, + DSM_PCI_DEVICE_NAME, NULL); + if (!obj) + return 0; + + if (obj->type != ACPI_TYPE_PACKAGE || obj->package.count != 2) + goto out; + + tmp = obj->package.elements; + if (tmp[0].type != ACPI_TYPE_INTEGER) + goto out; + + if (a == &dev_attr_acpi_index.attr) + mode = a->mode; + else if (a == &dev_attr_label.attr && + (tmp[1].type == ACPI_TYPE_STRING || + tmp[1].type == ACPI_TYPE_BUFFER)) + mode = a->mode; + +out: + ACPI_FREE(obj); + + return mode; } const struct attribute_group pci_dev_acpi_attr_group = { diff --git a/drivers/pci/pci.c b/drivers/pci/pci.c index f85256413cf3..7c6f2aba8144 100644 --- a/drivers/pci/pci.c +++ b/drivers/pci/pci.c @@ -1743,6 +1743,24 @@ static void pci_restore_pcie_state(struct pci_dev *dev) pcie_capability_write_word(dev, PCI_EXP_SLTCTL2, cap[i++]); } +/* + * Update the saved copy of the Device Control register after changing it, so + * that pci_restore_state() doesn't put back a stale value. Device Control is + * the first register saved by pci_save_pcie_state(). + */ +static void pcie_update_saved_devctl(struct pci_dev *dev, u16 clear, u16 set) +{ + struct pci_cap_saved_state *save_state; + u16 *devctl; + + save_state = pci_find_saved_cap(dev, PCI_CAP_ID_EXP); + if (!save_state) + return; + + devctl = (u16 *)&save_state->cap.data[0]; + *devctl = (*devctl & ~clear) | set; +} + static int pci_save_pcix_state(struct pci_dev *dev) { int pos; @@ -5998,8 +6016,12 @@ int pcie_set_mps(struct pci_dev *dev, int mps) ret = pcie_capability_clear_and_set_word(dev, PCI_EXP_DEVCTL, PCI_EXP_DEVCTL_PAYLOAD, v); + if (ret) + return pcibios_err_to_errno(ret); - return pcibios_err_to_errno(ret); + pcie_update_saved_devctl(dev, PCI_EXP_DEVCTL_PAYLOAD, v); + + return 0; } EXPORT_SYMBOL(pcie_set_mps); diff --git a/drivers/pci/pci.h b/drivers/pci/pci.h index ba3c3fddddc2..0ede46012339 100644 --- a/drivers/pci/pci.h +++ b/drivers/pci/pci.h @@ -502,6 +502,7 @@ enum pci_bar_type { pci_bar_mem64, /* A 64-bit memory BAR */ }; +void devm_pci_alloc_host_bridge_release(void *data); struct device *pci_get_host_bridge_device(struct pci_dev *dev); void pci_put_host_bridge_device(struct device *dev); @@ -711,10 +712,6 @@ struct pci_sriov { u16 driver_max_VFs; /* Max num VFs driver supports */ struct pci_dev *dev; /* Lowest numbered PF */ struct pci_dev *self; /* This PF */ - u32 class; /* VF device */ - u8 hdr_type; /* VF header type */ - u16 subsystem_vendor; /* VF subsystem vendor */ - u16 subsystem_device; /* VF subsystem device */ resource_size_t barsz[PCI_SRIOV_NUM_BARS]; /* VF BAR size */ u16 vf_rebar_cap; /* VF Resizable BAR capability offset */ bool drivers_autoprobe; /* Auto probing of VFs by driver */ diff --git a/drivers/pci/pcie/aer.c b/drivers/pci/pcie/aer.c index be332d3f106c..7f97e96de2a9 100644 --- a/drivers/pci/pcie/aer.c +++ b/drivers/pci/pcie/aer.c @@ -260,7 +260,7 @@ int pcie_aer_is_native(struct pci_dev *dev) if (!dev->aer_cap) return 0; - return pcie_ports_native || host->native_aer; + return host->native_aer; } EXPORT_SYMBOL_NS_GPL(pcie_aer_is_native, "CXL"); @@ -1341,7 +1341,6 @@ static void handle_error_source(struct pci_dev *dev, struct aer_err_info *info) { cxl_rch_handle_error(dev, info); pci_aer_handle_error(dev, info); - pci_dev_put(dev); } #ifdef CONFIG_ACPI_APEI_PCIEAER @@ -1369,14 +1368,13 @@ static void aer_recover_work_func(struct work_struct *work) while (kfifo_get(&aer_recover_ring, &entry)) { pdev = pci_get_domain_bus_and_slot(entry.domain, entry.bus, entry.devfn); - if (!pdev) { + if (!pdev) pr_err_ratelimited("%04x:%02x:%02x.%x: no pci_dev found\n", entry.domain, entry.bus, PCI_SLOT(entry.devfn), PCI_FUNC(entry.devfn)); - continue; - } - pci_print_aer(pdev, entry.severity, entry.regs); + else + pci_print_aer(pdev, entry.severity, entry.regs); regs = entry.regs; if (entry.severity == AER_CORRECTABLE) @@ -1394,7 +1392,7 @@ static void aer_recover_work_func(struct work_struct *work) ghes_estatus_pool_region_free((unsigned long)entry.regs, sizeof(struct aer_capability_regs)); - if (err) { + if (pdev && err) { if (entry.severity == AER_NONFATAL) pcie_do_recovery(pdev, pci_channel_io_normal, aer_root_reset); @@ -1532,6 +1530,7 @@ static inline void aer_process_err_devices(struct aer_err_info *e_info) for (i = 0; i < e_info->error_dev_num && e_info->dev[i]; i++) { if (aer_get_device_error_info(e_info, i)) handle_error_source(e_info->dev[i], e_info); + pci_dev_put(e_info->dev[i]); } } @@ -1861,7 +1860,7 @@ static pci_ers_result_t aer_root_reset(struct pci_dev *dev) */ aer = root ? root->aer_cap : 0; - if ((host->native_aer || pcie_ports_native) && aer) + if (host->native_aer && aer) aer_disable_irq(root); if (type == PCI_EXP_TYPE_RC_EC || type == PCI_EXP_TYPE_RC_END) { @@ -1876,7 +1875,7 @@ static pci_ers_result_t aer_root_reset(struct pci_dev *dev) pci_is_root_bus(dev->bus) ? "Root" : "Downstream", rc); } - if ((host->native_aer || pcie_ports_native) && aer) { + if (host->native_aer && aer) { /* Clear Root Error Status */ pci_read_config_dword(root, aer + PCI_ERR_ROOT_STATUS, ®32); pci_write_config_dword(root, aer + PCI_ERR_ROOT_STATUS, reg32); diff --git a/drivers/pci/pcie/aer_cxl_rch.c b/drivers/pci/pcie/aer_cxl_rch.c index e471eefec9c4..b480dad8bbf4 100644 --- a/drivers/pci/pcie/aer_cxl_rch.c +++ b/drivers/pci/pcie/aer_cxl_rch.c @@ -31,7 +31,7 @@ static bool cxl_error_is_native(struct pci_dev *dev) { struct pci_host_bridge *host = pci_find_host_bridge(dev->bus); - return (pcie_ports_native || host->native_aer); + return host->native_aer; } static int cxl_rch_handle_error_iter(struct pci_dev *dev, void *data) diff --git a/drivers/pci/pcie/err.c b/drivers/pci/pcie/err.c index d77403d8855b..1a7fc71c79d8 100644 --- a/drivers/pci/pcie/err.c +++ b/drivers/pci/pcie/err.c @@ -273,7 +273,7 @@ pci_ers_result_t pcie_do_recovery(struct pci_dev *dev, * it is responsible for clearing this status. In that case, the * signaling device may not even be visible to the OS. */ - if (host->native_aer || pcie_ports_native) { + if (host->native_aer) { pcie_clear_device_status(dev); pci_aer_clear_nonfatal_status(dev); } diff --git a/drivers/pci/pcie/portdrv.c b/drivers/pci/pcie/portdrv.c index a9cbfc1d2bc7..32fc623dd410 100644 --- a/drivers/pci/pcie/portdrv.c +++ b/drivers/pci/pcie/portdrv.c @@ -223,7 +223,7 @@ static int get_port_device_capability(struct pci_dev *dev) if (dev->is_pciehp && (pci_pcie_type(dev) == PCI_EXP_TYPE_ROOT_PORT || pci_pcie_type(dev) == PCI_EXP_TYPE_DOWNSTREAM) && - (pcie_ports_native || host->native_pcie_hotplug)) { + host->native_pcie_hotplug) { services |= PCIE_PORT_SERVICE_HP; /* @@ -240,14 +240,14 @@ static int get_port_device_capability(struct pci_dev *dev) if ((pci_pcie_type(dev) == PCI_EXP_TYPE_ROOT_PORT || pci_pcie_type(dev) == PCI_EXP_TYPE_RC_EC) && dev->aer_cap && pci_aer_available() && - (pcie_ports_native || host->native_aer)) + host->native_aer) services |= PCIE_PORT_SERVICE_AER; #endif /* Root Ports and Root Complex Event Collectors may generate PMEs */ if ((pci_pcie_type(dev) == PCI_EXP_TYPE_ROOT_PORT || pci_pcie_type(dev) == PCI_EXP_TYPE_RC_EC) && - (pcie_ports_native || host->native_pme)) { + host->native_pme) { services |= PCIE_PORT_SERVICE_PME; /* diff --git a/drivers/pci/pcie/portdrv.h b/drivers/pci/pcie/portdrv.h index cc58bf2f2c84..e1b6a8af6f71 100644 --- a/drivers/pci/pcie/portdrv.h +++ b/drivers/pci/pcie/portdrv.h @@ -25,8 +25,6 @@ #define PCIE_PORT_DEVICE_MAXSERVICES 5 -extern bool pcie_ports_dpc_native; - #ifdef CONFIG_PCIEAER int pcie_aer_init(void); #else diff --git a/drivers/pci/probe.c b/drivers/pci/probe.c index 52a79b033b06..46121c22b26b 100644 --- a/drivers/pci/probe.c +++ b/drivers/pci/probe.c @@ -696,10 +696,11 @@ struct pci_host_bridge *pci_alloc_host_bridge(size_t priv) } EXPORT_SYMBOL(pci_alloc_host_bridge); -static void devm_pci_alloc_host_bridge_release(void *data) +void devm_pci_alloc_host_bridge_release(void *data) { pci_free_host_bridge(data); } +EXPORT_SYMBOL(devm_pci_alloc_host_bridge_release); struct pci_host_bridge *devm_pci_alloc_host_bridge(struct device *dev, size_t priv) @@ -1892,8 +1893,13 @@ static u32 pci_class(struct pci_dev *dev) u32 class; #ifdef CONFIG_PCI_IOV - if (dev->is_virtfn) - return dev->physfn->sriov->class; + if (dev->is_virtfn) { + u8 rev; + + if (pci_read_config_byte(dev, PCI_REVISION_ID, &rev)) + rev = 0; + return (dev->physfn->class << 8) | rev; + } #endif pci_read_config_dword(dev, PCI_CLASS_REVISION, &class); return class; @@ -1903,8 +1909,8 @@ static void pci_subsystem_ids(struct pci_dev *dev, u16 *vendor, u16 *device) { #ifdef CONFIG_PCI_IOV if (dev->is_virtfn) { - *vendor = dev->physfn->sriov->subsystem_vendor; - *device = dev->physfn->sriov->subsystem_device; + *vendor = dev->physfn->subsystem_vendor; + pci_read_config_word(dev, PCI_SUBSYSTEM_ID, device); return; } #endif @@ -1918,7 +1924,7 @@ static u8 pci_hdr_type(struct pci_dev *dev) #ifdef CONFIG_PCI_IOV if (dev->is_virtfn) - return dev->physfn->sriov->hdr_type; + return 0; #endif pci_read_config_byte(dev, PCI_HEADER_TYPE, &hdr_type); return hdr_type; diff --git a/drivers/pci/pwrctrl/core.c b/drivers/pci/pwrctrl/core.c index c14df117ece3..0e2387cf4657 100644 --- a/drivers/pci/pwrctrl/core.c +++ b/drivers/pci/pwrctrl/core.c @@ -252,14 +252,16 @@ static int __pci_pwrctrl_power_on_device(struct device *dev) static int pci_pwrctrl_power_on_device(struct device_node *np) { struct platform_device *pdev; + struct device_node *child; int ret = 0; - for_each_available_child_of_node_scoped(np, child) { + for_each_available_child_of_node(np, child) { ret = pci_pwrctrl_power_on_device(child); if (ret) - return ret; + goto err_power_off; } + child = NULL; if (!pci_pwrctrl_is_required(np)) return 0; @@ -279,6 +281,19 @@ static int pci_pwrctrl_power_on_device(struct device_node *np) platform_device_put(pdev); + if (ret) + goto err_power_off; + + return 0; + +err_power_off: + for_each_available_child_of_node_scoped(np, tmp) { + if (tmp == child) + break; + pci_pwrctrl_power_off_device(tmp); + } + of_node_put(child); + return ret; } diff --git a/drivers/pci/pwrctrl/pci-pwrctrl-tc9563.c b/drivers/pci/pwrctrl/pci-pwrctrl-tc9563.c index fd53a7db9875..1b7718d07d15 100644 --- a/drivers/pci/pwrctrl/pci-pwrctrl-tc9563.c +++ b/drivers/pci/pwrctrl/pci-pwrctrl-tc9563.c @@ -481,7 +481,7 @@ static int tc9563_pwrctrl_power_off(struct pci_pwrctrl *pwrctrl) struct tc9563_pwrctrl *tc9563 = container_of(pwrctrl, struct tc9563_pwrctrl, pwrctrl); - gpiod_set_value(tc9563->reset_gpio, 1); + gpiod_set_value_cansleep(tc9563->reset_gpio, 1); regulator_bulk_disable(ARRAY_SIZE(tc9563->supplies), tc9563->supplies); @@ -501,7 +501,7 @@ static int tc9563_pwrctrl_power_on(struct pci_pwrctrl *pwrctrl) if (ret < 0) return dev_err_probe(dev, ret, "cannot enable regulators\n"); - gpiod_set_value(tc9563->reset_gpio, 0); + gpiod_set_value_cansleep(tc9563->reset_gpio, 0); fsleep(TC9563_OSC_STAB_DELAY_US); diff --git a/drivers/pci/quirks.c b/drivers/pci/quirks.c index d4fcc336bc2a..50fcb6675357 100644 --- a/drivers/pci/quirks.c +++ b/drivers/pci/quirks.c @@ -4128,7 +4128,7 @@ static int nvme_disable_and_flr(struct pci_dev *dev, bool probe) if (probe) return 0; - bar = pci_iomap(dev, 0, NVME_REG_CC + sizeof(cfg)); + bar = pci_iomap(dev, 0, NVME_REG_CSTS + sizeof(u32)); if (!bar) return -ENOTTY; diff --git a/drivers/pci/tph.c b/drivers/pci/tph.c index 655ffd60e62f..4d064b86befc 100644 --- a/drivers/pci/tph.c +++ b/drivers/pci/tph.c @@ -119,12 +119,14 @@ static acpi_status tph_invoke_dsm(acpi_handle handle, u32 cpu_uid, if (!out_obj) return AE_ERROR; - if (out_obj->type != ACPI_TYPE_BUFFER) { + if (out_obj->type != ACPI_TYPE_BUFFER || + out_obj->buffer.length < sizeof(st_out->value) || + !out_obj->buffer.pointer) { ACPI_FREE(out_obj); return AE_ERROR; } - st_out->value = *((u64 *)(out_obj->buffer.pointer)); + memcpy(&st_out->value, out_obj->buffer.pointer, sizeof(st_out->value)); ACPI_FREE(out_obj); diff --git a/drivers/pci/xen-pcifront.c b/drivers/pci/xen-pcifront.c index 5c6f7796d204..b8f2921cc253 100644 --- a/drivers/pci/xen-pcifront.c +++ b/drivers/pci/xen-pcifront.c @@ -579,16 +579,15 @@ static pci_ers_result_t pcifront_common_process(int cmd, int bus = pdev->sh_info->aer_op.bus; int devfn = pdev->sh_info->aer_op.devfn; int domain = pdev->sh_info->aer_op.domain; - struct pci_dev *pcidev; + struct pci_dev *pcidev __free(pci_dev_put) = + pci_get_domain_bus_and_slot(domain, bus, devfn); dev_dbg(&pdev->xdev->dev, "pcifront AER process: cmd %x (bus:%x, devfn%x)", cmd, bus, devfn); - pcidev = pci_get_domain_bus_and_slot(domain, bus, devfn); if (!pcidev || !pcidev->dev.driver) { dev_err(&pdev->xdev->dev, "device or AER driver is NULL\n"); - pci_dev_put(pcidev); return PCI_ERS_RESULT_NONE; } pdrv = to_pci_driver(pcidev->dev.driver); diff --git a/drivers/perf/cxl_pmu.c b/drivers/perf/cxl_pmu.c index 2c8a03cc11e4..b22ef68b4a75 100644 --- a/drivers/perf/cxl_pmu.c +++ b/drivers/perf/cxl_pmu.c @@ -112,6 +112,8 @@ struct cxl_pmu_info { bool filter_hdm; bool filter_crb; int irq; + /* Set between pmu_enable() and pmu_disable(), read by the IRQ handler */ + bool enabled; }; #define pmu_to_cxl_pmu_info(_pmu) container_of(_pmu, struct cxl_pmu_info, pmu) @@ -144,6 +146,15 @@ static int cxl_pmu_parse_caps(struct device *dev, struct cxl_pmu_info *info) info->num_counters = FIELD_GET(CXL_PMU_CAP_NUM_COUNTERS_MSK, val) + 1; info->counter_width = FIELD_GET(CXL_PMU_CAP_COUNTER_WIDTH_MSK, val); + /* + * The Counter Data register is 64 bits wide, so a Counter Width of 0 or + * >64 is invalid. Reject it rather than let GENMASK_ULL(width - 1, 0) in + * the read path shift out of range. + */ + if (info->counter_width == 0 || info->counter_width > 64) { + dev_err(dev, "Invalid counter width %d\n", info->counter_width); + return -ENODEV; + } info->num_event_capabilities = FIELD_GET(CXL_PMU_CAP_NUM_EVN_CAP_REG_SUP_MSK, val) + 1; info->filter_hdm = FIELD_GET(CXL_PMU_CAP_FILTERS_SUP_MSK, val) & CXL_PMU_FILTER_HDM; @@ -588,7 +599,10 @@ static const struct attribute_group *cxl_pmu_attr_groups[] = { NULL }; -/* If counter_idx == NULL, don't try to allocate a counter. */ +/* + * If counter_idx == NULL, don't try to allocate a counter. Callers that + * allocate pass both counter_idx and event_idx. + */ static int cxl_pmu_get_event_idx(struct perf_event *event, int *counter_idx, int *event_idx) { @@ -616,7 +630,7 @@ static int cxl_pmu_get_event_idx(struct perf_event *event, int *counter_idx, pmu_ev = cxl_pmu_find_config_counter_ev_cap(info, vid, gid, mask); if (!IS_ERR(pmu_ev)) { - if (!counter_idx) + if (!counter_idx || !event_idx) return 0; bitmap_andnot(configurable_and_free, info->conf_counter_bm, @@ -627,6 +641,7 @@ static int cxl_pmu_get_event_idx(struct perf_event *event, int *counter_idx, return -EINVAL; *counter_idx = i; + *event_idx = pmu_ev->event_idx; return 0; } @@ -696,6 +711,7 @@ static void cxl_pmu_enable(struct pmu *pmu) void __iomem *base = info->base; /* Can assume frozen at this stage */ + WRITE_ONCE(info->enabled, true); writeq(0, base + CXL_PMU_FREEZE_REG); } @@ -704,6 +720,7 @@ static void cxl_pmu_disable(struct pmu *pmu) struct cxl_pmu_info *info = pmu_to_cxl_pmu_info(pmu); void __iomem *base = info->base; + WRITE_ONCE(info->enabled, false); /* * Whilst bits above number of counters are RsvdZ * they are unlikely to be repurposed given @@ -755,17 +772,17 @@ static void cxl_pmu_event_start(struct perf_event *event, int flags) cfg |= FIELD_PREP(CXL_PMU_COUNTER_CFG_INT_ON_OVRFLW, 1); cfg |= FIELD_PREP(CXL_PMU_COUNTER_CFG_FREEZE_ON_OVRFLW, 1); cfg |= FIELD_PREP(CXL_PMU_COUNTER_CFG_ENABLE, 1); - cfg |= FIELD_PREP(CXL_PMU_COUNTER_CFG_EDGE, - cxl_pmu_config1_get_edge(event) ? 1 : 0); - cfg |= FIELD_PREP(CXL_PMU_COUNTER_CFG_INVERT, - cxl_pmu_config1_get_invert(event) ? 1 : 0); + FIELD_MODIFY(CXL_PMU_COUNTER_CFG_EDGE, &cfg, + cxl_pmu_config1_get_edge(event) ? 1 : 0); + FIELD_MODIFY(CXL_PMU_COUNTER_CFG_INVERT, &cfg, + cxl_pmu_config1_get_invert(event) ? 1 : 0); /* Fixed purpose counters have next two fields RO */ if (test_bit(hwc->idx, info->conf_counter_bm)) { - cfg |= FIELD_PREP(CXL_PMU_COUNTER_CFG_EVENT_GRP_ID_IDX_MSK, - hwc->event_base); - cfg |= FIELD_PREP(CXL_PMU_COUNTER_CFG_EVENTS_MSK, - cxl_pmu_config_get_mask(event)); + FIELD_MODIFY(CXL_PMU_COUNTER_CFG_EVENT_GRP_ID_IDX_MSK, &cfg, + hwc->event_base); + FIELD_MODIFY(CXL_PMU_COUNTER_CFG_EVENTS_MSK, &cfg, + cxl_pmu_config_get_mask(event)); } cfg &= ~CXL_PMU_COUNTER_CFG_THRESHOLD_MSK; /* @@ -778,6 +795,15 @@ static void cxl_pmu_event_start(struct perf_event *event, int flags) */ cfg |= FIELD_PREP(CXL_PMU_COUNTER_CFG_THRESHOLD_MSK, cxl_pmu_config1_get_threshold(event)); + + /* + * Drop any overflow the previous owner of this counter left pending; + * cxl_pmu_event_stop() does not. Otherwise an interrupt latched over + * the handover gets charged to this event. Do it before arming Interrupt + * on Overflow below, and note RW1C leaves the other counters alone. + */ + writeq(BIT_ULL(hwc->idx), base + CXL_PMU_OVERFLOW_REG); + writeq(cfg, base + CXL_PMU_COUNTER_CFG_REG(hwc->idx)); local64_set(&hwc->prev_count, 0); @@ -798,7 +824,7 @@ static void __cxl_pmu_read(struct perf_event *event, bool overflow) { struct cxl_pmu_info *info = pmu_to_cxl_pmu_info(event->pmu); struct hw_perf_event *hwc = &event->hw; - u64 new_cnt, prev_cnt, delta; + u64 new_cnt, prev_cnt, delta, mask; do { prev_cnt = local64_read(&hwc->prev_count); @@ -806,12 +832,16 @@ static void __cxl_pmu_read(struct perf_event *event, bool overflow) } while (local64_cmpxchg(&hwc->prev_count, prev_cnt, new_cnt) != prev_cnt); /* - * If we know an overflow occur then take that into account. - * Note counter is not reset as that would lose events + * The mask discards the bit that says the counter wrapped, so a delta of + * one whole period reads back as 0 - the same as no events at all. Only + * the overflow status separates them, and new_cnt >= prev_cnt is that + * case, so add the period back. mask + 1 is 2^counter_width, which comes + * out as 0 for a 64-bit counter and avoids an undefined 1 << 64. */ - delta = (new_cnt - prev_cnt) & GENMASK_ULL(info->counter_width - 1, 0); - if (overflow && delta < GENMASK_ULL(info->counter_width - 1, 0)) - delta += (1UL << info->counter_width); + mask = GENMASK_ULL(info->counter_width - 1, 0); + delta = (new_cnt - prev_cnt) & mask; + if (overflow && new_cnt >= prev_cnt) + delta += mask + 1; local64_add(delta, &event->count); } @@ -887,7 +917,7 @@ static irqreturn_t cxl_pmu_irq(int irq, void *data) overflowed = readq(base + CXL_PMU_OVERFLOW_REG); - /* Interrupt may be shared, so maybe it isn't ours */ + /* Nothing overflowed, so the device did not raise this */ if (!overflowed) return IRQ_NONE; @@ -896,7 +926,7 @@ static irqreturn_t cxl_pmu_irq(int irq, void *data) struct perf_event *event = info->hw_events[i]; if (!event) { - dev_dbg(info->pmu.dev, + dev_dbg(info->pmu.parent, "overflow but on non enabled counter %d\n", i); continue; } @@ -906,6 +936,21 @@ static irqreturn_t cxl_pmu_irq(int irq, void *data) writeq(overflowed, base + CXL_PMU_OVERFLOW_REG); + /* + * An overflow freezes every counter in the CPMU, so unfreeze once the + * overflowed ones have been read and their status cleared. Otherwise + * they stay frozen until the next pmu_enable() and events are lost. + * + * Not while the PMU is disabled, so as not to undo an intentional freeze. + * The check is advisory, not exclusive: pmu_disable() normally runs on + * info->on_cpu with interrupts off, where the pinned handler cannot + * preempt it. In the one window where it does not - the migration in + * cxl_pmu_offline_cpu() - the counters are legitimately running again, + * so unfreezing is correct there anyway. + */ + if (READ_ONCE(info->enabled)) + writeq(0, base + CXL_PMU_FREEZE_REG); + return IRQ_HANDLED; } @@ -978,7 +1023,7 @@ static int cxl_pmu_probe(struct device *dev) .capabilities = PERF_PMU_CAP_NO_EXCLUDE, }; - if (info->irq <= 0) + if (info->irq < 0) return -EINVAL; rc = pci_irq_vector(pdev, info->irq); @@ -990,7 +1035,22 @@ static int cxl_pmu_probe(struct device *dev) if (!irq_name) return -ENOMEM; - rc = devm_request_irq(dev, irq, cxl_pmu_irq, IRQF_SHARED | IRQF_NO_THREAD, + /* + * Same for counters no event owns yet: clear whatever firmware or a + * previous kernel left set before the handler goes live. Bits above the + * implemented counters are reserved, so only write those. + */ + writeq(GENMASK_ULL(info->num_counters - 1, 0), + info->base + CXL_PMU_OVERFLOW_REG); + + /* + * The handler must run on info->on_cpu, so the interrupt cannot be + * shared - IRQF_NOBALANCING is only honoured for the first action on a + * line, and a co-owner would keep taking the interrupt wherever its own + * affinity points. + */ + rc = devm_request_irq(dev, irq, cxl_pmu_irq, + IRQF_NO_THREAD | IRQF_NOBALANCING, irq_name, info); if (rc) return rc; diff --git a/drivers/perf/dwc_pcie_pmu.c b/drivers/perf/dwc_pcie_pmu.c index 6b9ed59de26e..eb86e7468c49 100644 --- a/drivers/perf/dwc_pcie_pmu.c +++ b/drivers/perf/dwc_pcie_pmu.c @@ -747,16 +747,16 @@ static struct notifier_block dwc_pcie_pmu_nb = { static int dwc_pcie_pmu_probe(struct platform_device *plat_dev) { - struct pci_dev *pdev; + u32 sbdf = plat_dev->id; + struct pci_dev *pdev __free(pci_dev_put) = + pci_get_domain_bus_and_slot(sbdf >> 16, + PCI_BUS_NUM(sbdf & 0xffff), + sbdf & 0xff); struct dwc_pcie_pmu *pcie_pmu; char *name; - u32 sbdf; u16 vsec; int ret; - sbdf = plat_dev->id; - pdev = pci_get_domain_bus_and_slot(sbdf >> 16, PCI_BUS_NUM(sbdf & 0xffff), - sbdf & 0xff); if (!pdev) { pr_err("No pdev found for the sbdf 0x%x\n", sbdf); return -ENODEV; @@ -766,7 +766,6 @@ static int dwc_pcie_pmu_probe(struct platform_device *plat_dev) if (!vsec) return -ENODEV; - pci_dev_put(pdev); name = devm_kasprintf(&plat_dev->dev, GFP_KERNEL, "dwc_rootport_%x", sbdf); if (!name) return -ENOMEM; diff --git a/drivers/perf/marvell_cn10k_ddr_pmu.c b/drivers/perf/marvell_cn10k_ddr_pmu.c index 0a8cb6166408..9b68d6c1c31c 100644 --- a/drivers/perf/marvell_cn10k_ddr_pmu.c +++ b/drivers/perf/marvell_cn10k_ddr_pmu.c @@ -1165,6 +1165,47 @@ static const struct ddr_pmu_platform_data odyssey_ddr_pmu_pdata = { }; #endif +static const struct pmu cn10k_pmu = { + .module = THIS_MODULE, + .capabilities = PERF_PMU_CAP_NO_EXCLUDE, + .task_ctx_nr = perf_invalid_context, + .attr_groups = cn10k_attr_groups, + .event_init = cn10k_ddr_perf_event_init, + .add = cn10k_ddr_perf_event_add, + .del = cn10k_ddr_perf_event_del, + .start = cn10k_ddr_perf_event_start, + .stop = cn10k_ddr_perf_event_stop, + .read = cn10k_ddr_perf_event_update, + .pmu_enable = cn10k_ddr_perf_pmu_enable, + .pmu_disable = cn10k_ddr_perf_pmu_disable, +}; + +static const struct pmu ody_pmu = { + .module = THIS_MODULE, + .capabilities = PERF_PMU_CAP_NO_EXCLUDE, + .task_ctx_nr = perf_invalid_context, + .attr_groups = odyssey_attr_groups, + .event_init = cn10k_ddr_perf_event_init, + .add = cn10k_ddr_perf_event_add, + .del = cn10k_ddr_perf_event_del, + .start = cn10k_ddr_perf_event_start, + .stop = cn10k_ddr_perf_event_stop, + .read = cn10k_ddr_perf_event_update, +}; + +static const struct pmu cn20k_pmu = { + .module = THIS_MODULE, + .capabilities = PERF_PMU_CAP_NO_EXCLUDE, + .task_ctx_nr = perf_invalid_context, + .attr_groups = cn20k_attr_groups, + .event_init = cn10k_ddr_perf_event_init, + .add = cn10k_ddr_perf_event_add, + .del = cn10k_ddr_perf_event_del, + .start = cn10k_ddr_perf_event_start, + .stop = cn10k_ddr_perf_event_stop, + .read = cn10k_ddr_perf_event_update, +}; + static int cn10k_ddr_perf_probe(struct platform_device *pdev) { const struct ddr_pmu_platform_data *dev_data; @@ -1202,56 +1243,20 @@ static int cn10k_ddr_perf_probe(struct platform_device *pdev) /* Setup the PMU counter to work in manual mode */ writeq_relaxed(OP_MODE_CTRL_VAL_MANUAL, ddr_pmu->base + ddr_pmu->p_data->cnt_op_mode_ctrl); + ddr_pmu->pmu = cn10k_pmu; - ddr_pmu->pmu = (struct pmu) { - .module = THIS_MODULE, - .capabilities = PERF_PMU_CAP_NO_EXCLUDE, - .task_ctx_nr = perf_invalid_context, - .attr_groups = cn10k_attr_groups, - .event_init = cn10k_ddr_perf_event_init, - .add = cn10k_ddr_perf_event_add, - .del = cn10k_ddr_perf_event_del, - .start = cn10k_ddr_perf_event_start, - .stop = cn10k_ddr_perf_event_stop, - .read = cn10k_ddr_perf_event_update, - .pmu_enable = cn10k_ddr_perf_pmu_enable, - .pmu_disable = cn10k_ddr_perf_pmu_disable, - }; } if (silicon_flags & IS_ODY) { ddr_pmu->ops = &ddr_pmu_ody_ops; - - ddr_pmu->pmu = (struct pmu) { - .module = THIS_MODULE, - .capabilities = PERF_PMU_CAP_NO_EXCLUDE, - .task_ctx_nr = perf_invalid_context, - .attr_groups = odyssey_attr_groups, - .event_init = cn10k_ddr_perf_event_init, - .add = cn10k_ddr_perf_event_add, - .del = cn10k_ddr_perf_event_del, - .start = cn10k_ddr_perf_event_start, - .stop = cn10k_ddr_perf_event_stop, - .read = cn10k_ddr_perf_event_update, - }; + ddr_pmu->pmu = ody_pmu; } if (silicon_flags & IS_CN20K) { ddr_pmu->ops = &ddr_pmu_ody_ops; - - ddr_pmu->pmu = (struct pmu) { - .module = THIS_MODULE, - .capabilities = PERF_PMU_CAP_NO_EXCLUDE, - .task_ctx_nr = perf_invalid_context, - .attr_groups = cn20k_attr_groups, - .event_init = cn10k_ddr_perf_event_init, - .add = cn10k_ddr_perf_event_add, - .del = cn10k_ddr_perf_event_del, - .start = cn10k_ddr_perf_event_start, - .stop = cn10k_ddr_perf_event_stop, - .read = cn10k_ddr_perf_event_update, - }; + ddr_pmu->pmu = cn20k_pmu; } + /* Choose this cpu to collect perf data */ ddr_pmu->cpu = raw_smp_processor_id(); diff --git a/drivers/perf/marvell_cn10k_tad_pmu.c b/drivers/perf/marvell_cn10k_tad_pmu.c index 54909d0031b7..301be4d92b1b 100644 --- a/drivers/perf/marvell_cn10k_tad_pmu.c +++ b/drivers/perf/marvell_cn10k_tad_pmu.c @@ -424,6 +424,7 @@ static const struct of_device_id tad_pmu_of_match[] = { { .compatible = "marvell,cn10k-tad-pmu", .data = &tad_pmu_data }, {}, }; +MODULE_DEVICE_TABLE(of, tad_pmu_of_match); #endif #ifdef CONFIG_ACPI diff --git a/drivers/phy/cadence/phy-cadence-sierra.c b/drivers/phy/cadence/phy-cadence-sierra.c index 92ab1a31646a..dbeda7f01cbb 100644 --- a/drivers/phy/cadence/phy-cadence-sierra.c +++ b/drivers/phy/cadence/phy-cadence-sierra.c @@ -698,23 +698,16 @@ static const struct phy_ops noop_ops = { static u8 cdns_sierra_pll_mux_get_parent(struct clk_hw *hw) { struct cdns_sierra_pll_mux *mux = to_cdns_sierra_pll_mux(hw); - struct regmap_field *plllc1en_field = mux->plllc1en_field; - struct regmap_field *termen_field = mux->termen_field; struct regmap_field *field = mux->pfdclk_sel_preg; unsigned int val; int index; regmap_field_read(field, &val); - if (strstr(clk_hw_get_name(hw), clk_names[CDNS_SIERRA_PLL_CMNLC1])) { + if (strstr(clk_hw_get_name(hw), clk_names[CDNS_SIERRA_PLL_CMNLC1])) index = clk_mux_val_to_index(hw, cdns_sierra_pll_mux_table[CMN_PLLLC1], 0, val); - if (index == 1) { - regmap_field_write(plllc1en_field, 1); - regmap_field_write(termen_field, 1); - } - } else { + else index = clk_mux_val_to_index(hw, cdns_sierra_pll_mux_table[CMN_PLLLC], 0, val); - } return index; } diff --git a/drivers/phy/hisilicon/phy-hi3670-pcie.c b/drivers/phy/hisilicon/phy-hi3670-pcie.c index 7396c601d874..148763ed2c62 100644 --- a/drivers/phy/hisilicon/phy-hi3670-pcie.c +++ b/drivers/phy/hisilicon/phy-hi3670-pcie.c @@ -480,7 +480,7 @@ static int hi3670_pcie_allclk_ctrl(struct hi3670_pcie_phy *phy, bool clk_on) ret = hi3670_pcie_pll_ctrl(phy, true); if (ret) { dev_err(dev, "Failed to enable pll\n"); - return -EINVAL; + goto close_clocks; } hi3670_pcie_hp_debounce_gt(phy, true); hi3670_pcie_phyref_gt(phy, true); @@ -569,6 +569,7 @@ static int hi3670_pcie_get_resources_from_pcie(struct hi3670_pcie_phy *phy) } pcie_dev = bus_find_device_by_of_node(&platform_bus_type, pcie_port); + of_node_put(pcie_port); if (!pcie_dev) { dev_err(dev, "Didn't find pcie device\n"); return -ENODEV; @@ -583,6 +584,7 @@ static int hi3670_pcie_get_resources_from_pcie(struct hi3670_pcie_phy *phy) * right regmap. So, let's use the named version. */ phy->apb = dev_get_regmap(pcie_dev, "kirin_pcie_apb"); + put_device(pcie_dev); if (!phy->apb) { dev_err(dev, "Failed to get APB regmap\n"); return -ENODEV; diff --git a/drivers/phy/qualcomm/Kconfig b/drivers/phy/qualcomm/Kconfig index d910a5d1a1ac..9113e1099245 100644 --- a/drivers/phy/qualcomm/Kconfig +++ b/drivers/phy/qualcomm/Kconfig @@ -81,6 +81,7 @@ config PHY_QCOM_QMP_PCIE_MULTIPHY tristate "Qualcomm QMP PCIe Multi PHY Driver" depends on PCI || COMPILE_TEST select GENERIC_PHY + select MFD_SYSCON help Enable this to support the QMP PCIe PHY transceiver that is used with PCIe controllers on Qualcomm chips. This PHY is a single diff --git a/drivers/phy/qualcomm/phy-qcom-qmp-pcie-multiphy.c b/drivers/phy/qualcomm/phy-qcom-qmp-pcie-multiphy.c index e93cba4369fb..b4bcb199e128 100644 --- a/drivers/phy/qualcomm/phy-qcom-qmp-pcie-multiphy.c +++ b/drivers/phy/qualcomm/phy-qcom-qmp-pcie-multiphy.c @@ -113,31 +113,19 @@ static const char * const glymur_vreg_l[] = { "vdda-phy", "vdda-pll", "vdda-refgen0p9", "vdda-refgen1p2", }; -static const char * const glymur_pciephy_a_reg_l[] = { +static const char * const pciephy_port_a_reg_l[] = { "port_a", }; -static const char * const glymur_pciephy_b_reg_l[] = { +static const char * const pciephy_port_b_reg_l[] = { "port_b", }; -static const char * const glymur_pciephy_reg_l[] = { +static const char * const pciephy_port_ab_reg_l[] = { "port_a", "port_b", }; -static const char * const glymur_pciephy_a_pd_l[] = { - "port_a", -}; - -static const char * const glymur_pciephy_b_pd_l[] = { - "port_b", -}; - -static const char * const glymur_pciephy_pd_l[] = { - "port_a", "port_b", -}; - -static const char * const glymur_pciephy_a_nocsr_reset_l[] = { +static const char * const pciephy_port_a_nocsr_reset_l[] = { "port_a_nocsr", }; @@ -145,7 +133,7 @@ static const char * const glymur_pciephy_nocsr_reset_l[] = { "port_a_nocsr", "port_b_nocsr", }; -static const char * const glymur_pciephy_b_nocsr_reset_l[] = { +static const char * const pciephy_port_b_nocsr_reset_l[] = { "port_b_nocsr", }; @@ -155,12 +143,12 @@ static const struct qmp_pcie_offsets glymur_pcie_offsets_v8_50 = { static const struct qmp_phy_cfg glymur_qmp_gen5x4_pciephy_a_cfg = { .offsets = &glymur_pcie_offsets_v8_50, - .reg_names = glymur_pciephy_a_reg_l, - .num_regs = ARRAY_SIZE(glymur_pciephy_a_reg_l), - .pd_names = glymur_pciephy_a_pd_l, - .num_pds = ARRAY_SIZE(glymur_pciephy_a_pd_l), - .nocsr_reset_list = glymur_pciephy_a_nocsr_reset_l, - .num_nocsr_resets = ARRAY_SIZE(glymur_pciephy_a_nocsr_reset_l), + .reg_names = pciephy_port_a_reg_l, + .num_regs = ARRAY_SIZE(pciephy_port_a_reg_l), + .pd_names = pciephy_port_a_reg_l, + .num_pds = ARRAY_SIZE(pciephy_port_a_reg_l), + .nocsr_reset_list = pciephy_port_a_nocsr_reset_l, + .num_nocsr_resets = ARRAY_SIZE(pciephy_port_a_nocsr_reset_l), .vreg_list = glymur_vreg_l, .num_vregs = ARRAY_SIZE(glymur_vreg_l), .regs = pciephy_v8_50_regs_layout, @@ -173,12 +161,12 @@ static const struct qmp_phy_cfg glymur_qmp_gen5x4_pciephy_a_cfg = { static const struct qmp_phy_cfg glymur_qmp_gen5x4_pciephy_b_cfg = { .offsets = &glymur_pcie_offsets_v8_50, - .reg_names = glymur_pciephy_b_reg_l, - .num_regs = ARRAY_SIZE(glymur_pciephy_b_reg_l), - .pd_names = glymur_pciephy_b_pd_l, - .num_pds = ARRAY_SIZE(glymur_pciephy_b_pd_l), - .nocsr_reset_list = glymur_pciephy_b_nocsr_reset_l, - .num_nocsr_resets = ARRAY_SIZE(glymur_pciephy_b_nocsr_reset_l), + .reg_names = pciephy_port_b_reg_l, + .num_regs = ARRAY_SIZE(pciephy_port_b_reg_l), + .pd_names = pciephy_port_b_reg_l, + .num_pds = ARRAY_SIZE(pciephy_port_b_reg_l), + .nocsr_reset_list = pciephy_port_b_nocsr_reset_l, + .num_nocsr_resets = ARRAY_SIZE(pciephy_port_b_nocsr_reset_l), .vreg_list = glymur_vreg_l, .num_vregs = ARRAY_SIZE(glymur_vreg_l), .regs = pciephy_v8_50_regs_layout, @@ -191,10 +179,10 @@ static const struct qmp_phy_cfg glymur_qmp_gen5x4_pciephy_b_cfg = { static const struct qmp_phy_cfg glymur_qmp_gen5x8_pciephy_cfg = { .offsets = &glymur_pcie_offsets_v8_50, - .reg_names = glymur_pciephy_reg_l, - .num_regs = ARRAY_SIZE(glymur_pciephy_reg_l), - .pd_names = glymur_pciephy_pd_l, - .num_pds = ARRAY_SIZE(glymur_pciephy_pd_l), + .reg_names = pciephy_port_ab_reg_l, + .num_regs = ARRAY_SIZE(pciephy_port_ab_reg_l), + .pd_names = pciephy_port_ab_reg_l, + .num_pds = ARRAY_SIZE(pciephy_port_ab_reg_l), .nocsr_reset_list = glymur_pciephy_nocsr_reset_l, .num_nocsr_resets = ARRAY_SIZE(glymur_pciephy_nocsr_reset_l), .vreg_list = glymur_vreg_l, @@ -398,45 +386,39 @@ static const struct phy_ops qmp_pcie_phy_ops = { static void qmp_pcie_pd_detach(void *data) { struct qmp_pcie *qmp = data; - const struct qmp_phy_cfg *cfg = qmp->cfg; int i; - for (i = 0; i < cfg->num_pds; i++) { + for (i = 0; i < qmp->cfg->num_pds; i++) { if (!IS_ERR_OR_NULL(qmp->pd_devs[i])) dev_pm_domain_detach(qmp->pd_devs[i], true); } } -static int qmp_pcie_pd_init(struct qmp_pcie *qmp) +static int qmp_pcie_pd_init(struct qmp_pcie *qmp, struct phy *phy) { const struct qmp_phy_cfg *cfg = qmp->cfg; - struct device *dev = qmp->dev; + struct device *pd_dev = &phy->dev; int i, ret; if (!cfg->num_pds) return 0; - qmp->pd_devs = devm_kcalloc(dev, cfg->num_pds, sizeof(*qmp->pd_devs), + qmp->pd_devs = devm_kcalloc(pd_dev, cfg->num_pds, sizeof(*qmp->pd_devs), GFP_KERNEL); if (!qmp->pd_devs) return -ENOMEM; + ret = devm_add_action_or_reset(pd_dev, qmp_pcie_pd_detach, qmp); + if (ret) + return ret; + for (i = 0; i < cfg->num_pds; i++) { - qmp->pd_devs[i] = dev_pm_domain_attach_by_name(dev, - cfg->pd_names[i]); - if (IS_ERR_OR_NULL(qmp->pd_devs[i])) { - ret = PTR_ERR(qmp->pd_devs[i]) ? : -ENODATA; - goto err_detach; - } + qmp->pd_devs[i] = dev_pm_domain_attach_by_name(pd_dev, cfg->pd_names[i]); + if (IS_ERR_OR_NULL(qmp->pd_devs[i])) + return PTR_ERR_OR_ZERO(qmp->pd_devs[i]) ? : -ENODATA; } - return devm_add_action_or_reset(dev, qmp_pcie_pd_detach, qmp); - -err_detach: - while (--i >= 0) - dev_pm_domain_detach(qmp->pd_devs[i], false); - - return ret; + return 0; } static int qmp_pcie_vreg_init(struct qmp_pcie *qmp) @@ -555,6 +537,9 @@ static int qmp_pcie_multiphy_register_clocks(struct device *dev, int i, ret; num_pipe_outputs = of_property_count_strings(np, "clock-output-names"); + if (num_pipe_outputs < 0) + return dev_err_probe(dev, num_pipe_outputs, + "failed to read clock-output-names\n"); qmp_data->num_pipe_outputs = num_pipe_outputs; qmp_data->pipe_out_clks = devm_kcalloc(dev, num_pipe_outputs, @@ -630,6 +615,7 @@ static struct phy *qmp_pcie_multiphy_xlate(struct device *dev, static int qmp_pcie_probe_phy(struct qmp_pcie *qmp, struct device_node *np, struct phy **out_phy) { + struct phy *phy; int ret; ret = qmp_pcie_get_mmio(qmp); @@ -648,15 +634,16 @@ static int qmp_pcie_probe_phy(struct qmp_pcie *qmp, struct device_node *np, if (ret) return ret; - ret = qmp_pcie_pd_init(qmp); + phy = devm_phy_create(qmp->dev, np, &qmp_pcie_phy_ops); + if (IS_ERR(phy)) + return PTR_ERR(phy); + + ret = qmp_pcie_pd_init(qmp, phy); if (ret) return ret; - *out_phy = devm_phy_create(qmp->dev, np, &qmp_pcie_phy_ops); - if (IS_ERR(*out_phy)) - return PTR_ERR(*out_phy); - - phy_set_drvdata(*out_phy, qmp); + phy_set_drvdata(phy, qmp); + *out_phy = phy; return 0; } @@ -739,5 +726,5 @@ static struct platform_driver qmp_pcie_multiphy_driver = { module_platform_driver(qmp_pcie_multiphy_driver); MODULE_AUTHOR("Qiang Yu "); -MODULE_DESCRIPTION("Qualcomm QMP PCIe Multi-PHY driver for Glymur"); +MODULE_DESCRIPTION("Qualcomm QMP PCIe Multi-PHY driver"); MODULE_LICENSE("GPL"); diff --git a/drivers/phy/rockchip/phy-rockchip-naneng-combphy.c b/drivers/phy/rockchip/phy-rockchip-naneng-combphy.c index 7843356a4dd4..3102a99128f6 100644 --- a/drivers/phy/rockchip/phy-rockchip-naneng-combphy.c +++ b/drivers/phy/rockchip/phy-rockchip-naneng-combphy.c @@ -106,6 +106,9 @@ #define RK3568_PHYREG18 0x44 #define RK3568_PHYREG18_PLL_LOOP 0x32 +#define RK3568_PHYREG26 0x64 +#define RK3568_PHYREG26_FORCE_RTERM_DET_RDY BIT(5) + #define RK3568_PHYREG30 0x74 #define RK3568_PHYREG30_GATE_TX_PCK_SEL BIT(7) #define RK3568_PHYREG30_GATE_TX_PCK_DLY_PLL_OFF BIT(7) @@ -194,6 +197,7 @@ struct rockchip_combphy_cfg { unsigned int num_phys; unsigned int phy_ids[3]; const struct rockchip_combphy_grfcfg *grfcfg; + bool force_rxterm_det_rdy; int (*combphy_cfg)(struct rockchip_combphy_priv *priv); }; @@ -265,6 +269,17 @@ static int rockchip_combphy_init(struct phy *phy) switch (priv->type) { case PHY_TYPE_PCIE: + /* + * Hardware Errata: TX fails to detect peer RX termination. + * Some PHY revisions may fail to detect remote RX's RTERM + * (receiver termination resistor) under certain critical + * temperature conditions. Set force rterm detect ready to + * fix it. + */ + if (priv->cfg->force_rxterm_det_rdy) + rockchip_combphy_updatel(priv, RK3568_PHYREG26_FORCE_RTERM_DET_RDY, + RK3568_PHYREG26_FORCE_RTERM_DET_RDY, RK3568_PHYREG26); + fallthrough; case PHY_TYPE_USB3: case PHY_TYPE_SATA: case PHY_TYPE_SGMII: @@ -801,6 +816,7 @@ static const struct rockchip_combphy_cfg rk3562_combphy_cfgs = { }, .grfcfg = &rk3562_combphy_grfcfgs, .combphy_cfg = rk3562_combphy_cfg, + .force_rxterm_det_rdy = true, }; static int rk3568_combphy_cfg(struct rockchip_combphy_priv *priv) @@ -998,6 +1014,7 @@ static const struct rockchip_combphy_cfg rk3568_combphy_cfgs = { }, .grfcfg = &rk3568_combphy_grfcfgs, .combphy_cfg = rk3568_combphy_cfg, + .force_rxterm_det_rdy = true, }; static int rk3576_combphy_cfg(struct rockchip_combphy_priv *priv) @@ -1219,6 +1236,7 @@ static const struct rockchip_combphy_cfg rk3576_combphy_cfgs = { }, .grfcfg = &rk3576_combphy_grfcfgs, .combphy_cfg = rk3576_combphy_cfg, + .force_rxterm_det_rdy = true, }; static int rk3588_combphy_cfg(struct rockchip_combphy_priv *priv) @@ -1391,6 +1409,7 @@ static const struct rockchip_combphy_cfg rk3588_combphy_cfgs = { }, .grfcfg = &rk3588_combphy_grfcfgs, .combphy_cfg = rk3588_combphy_cfg, + .force_rxterm_det_rdy = true, }; static const struct of_device_id rockchip_combphy_of_match[] = { diff --git a/drivers/phy/rockchip/phy-rockchip-samsung-dcphy.c b/drivers/phy/rockchip/phy-rockchip-samsung-dcphy.c index 18f5f582d1d7..7382043e1f31 100644 --- a/drivers/phy/rockchip/phy-rockchip-samsung-dcphy.c +++ b/drivers/phy/rockchip/phy-rockchip-samsung-dcphy.c @@ -1610,16 +1610,16 @@ static int samsung_mipi_dcphy_probe(struct platform_device *pdev) return dev_err_probe(dev, PTR_ERR(samsung->grf_apb_rst), "Failed to get system grf_apb_rst control\n"); + ret = devm_pm_runtime_enable(dev); + if (ret) + return dev_err_probe(dev, ret, "Failed to enable runtime PM\n"); + samsung->phy = devm_phy_create(dev, NULL, &samsung_mipi_dcphy_ops); if (IS_ERR(samsung->phy)) return dev_err_probe(dev, PTR_ERR(samsung->phy), "Failed to create MIPI DC-PHY\n"); phy_set_drvdata(samsung->phy, samsung); - ret = devm_pm_runtime_enable(dev); - if (ret) - return dev_err_probe(dev, ret, "Failed to enable runtime PM\n"); - phy_provider = devm_of_phy_provider_register(dev, samsung_mipi_dcphy_xlate); if (IS_ERR(phy_provider)) return dev_err_probe(dev, PTR_ERR(phy_provider), diff --git a/drivers/phy/rockchip/phy-rockchip-samsung-hdptx.c b/drivers/phy/rockchip/phy-rockchip-samsung-hdptx.c index 24ed0d7eb6f8..b03042ec9a84 100644 --- a/drivers/phy/rockchip/phy-rockchip-samsung-hdptx.c +++ b/drivers/phy/rockchip/phy-rockchip-samsung-hdptx.c @@ -2346,14 +2346,16 @@ static int rk_hdptx_phy_clk_determine_rate(struct clk_hw *hw, * to ensure rk_hdptx_phy_clk_set_rate() will be always invoked. * Otherwise, restrict the rate according to the PHY link setup. */ - if (hdptx->pll_config_dirty) - req->rate = 0; - else if (hdptx->hdmi_cfg.mode == PHY_HDMI_MODE_FRL) + + if (hdptx->hdmi_cfg.mode == PHY_HDMI_MODE_FRL) req->rate = hdptx->hdmi_cfg.rate; else req->rate = DIV_ROUND_CLOSEST_ULL(hdptx->hdmi_cfg.rate * 8, hdptx->hdmi_cfg.bpc); + if (hdptx->pll_config_dirty && req->rate == clk_hw_get_rate(hw)) + req->rate = 0; + return 0; } diff --git a/drivers/phy/rockchip/phy-rockchip-usbdp.c b/drivers/phy/rockchip/phy-rockchip-usbdp.c index 07a839e41db7..1d6ea291dbfe 100644 --- a/drivers/phy/rockchip/phy-rockchip-usbdp.c +++ b/drivers/phy/rockchip/phy-rockchip-usbdp.c @@ -126,7 +126,6 @@ struct rk_udphy_grf_cfg { struct rk_udphy_vogrf_cfg { /* vo-grf */ - struct rk_udphy_grf_reg hpd_trigger; u32 dp_lane_reg; }; @@ -170,7 +169,7 @@ struct rk_udphy { /* PHY status management */ bool flip; - bool mode_change; + bool phy_needs_reinit; u8 mode; u8 status; @@ -184,14 +183,12 @@ struct rk_udphy { u32 dp_lane_sel[4]; u32 dp_aux_dout_sel; u32 dp_aux_din_sel; - bool dp_sink_hpd_sel; - bool dp_sink_hpd_cfg; unsigned int link_rate; unsigned int lanes; u8 bw; int id; - bool dp_in_use; + int dp_lanes; /* PHY const config */ const struct rk_udphy_cfg *cfgs; @@ -426,11 +423,14 @@ static int rk_udphy_clk_init(struct rk_udphy *udphy, struct device *dev) int i; udphy->num_clks = devm_clk_bulk_get_all(dev, &udphy->clks); - if (udphy->num_clks < 1) - return -ENODEV; + if (udphy->num_clks < 0) + return udphy->num_clks; /* used for configure phy reference clock frequency */ for (i = 0; i < udphy->num_clks; i++) { + if (!udphy->clks[i].id) + continue; + if (!strncmp(udphy->clks[i].id, "refclk", 6)) { udphy->refclk = udphy->clks[i].clk; break; @@ -448,11 +448,6 @@ static int rk_udphy_reset_assert_all(struct rk_udphy *udphy) return reset_control_bulk_assert(udphy->num_rsts, udphy->rsts); } -static int rk_udphy_reset_deassert_all(struct rk_udphy *udphy) -{ - return reset_control_bulk_deassert(udphy->num_rsts, udphy->rsts); -} - static int rk_udphy_reset_deassert(struct rk_udphy *udphy, char *name) { struct reset_control_bulk_data *list = udphy->rsts; @@ -535,6 +530,13 @@ static void rk_udphy_usb_bvalid_enable(struct rk_udphy *udphy, u8 enable) * <0 1> dpln0 dpln1 usbrx usbtx * <2 3> usbrx usbtx dpln0 dpln1 * --------------------------------------------------------------------------- + * if 1 lane for dp function, 2 lane for usb function, define rockchip,dp-lane-mux = ; + * sample as follow: + * --------------------------------------------------------------------------- + * B11-B10 A2-A3 A11-A10 B2-B3 + * rockchip,dp-lane-mux ln0(tx/rx) ln1(tx) ln2(tx/rx) ln3(tx) + * <0> dpln0 \ usbrx usbtx + * --------------------------------------------------------------------------- */ static void rk_udphy_dplane_select(struct rk_udphy *udphy) @@ -542,18 +544,18 @@ static void rk_udphy_dplane_select(struct rk_udphy *udphy) const struct rk_udphy_cfg *cfg = udphy->cfgs; u32 value = 0; - switch (udphy->mode) { - case UDPHY_MODE_DP: - value |= 2 << udphy->dp_lane_sel[2] * 2; + switch (udphy->dp_lanes) { + case 4: value |= 3 << udphy->dp_lane_sel[3] * 2; + value |= 2 << udphy->dp_lane_sel[2] * 2; fallthrough; - case UDPHY_MODE_DP_USB: - value |= 0 << udphy->dp_lane_sel[0] * 2; + case 2: value |= 1 << udphy->dp_lane_sel[1] * 2; - break; + fallthrough; - case UDPHY_MODE_USB: + case 1: + value |= 0 << udphy->dp_lane_sel[0] * 2; break; default: @@ -566,28 +568,6 @@ static void rk_udphy_dplane_select(struct rk_udphy *udphy) FIELD_PREP(DP_AUX_DOUT_SEL, udphy->dp_aux_dout_sel) | value); } -static int rk_udphy_dplane_get(struct rk_udphy *udphy) -{ - int dp_lanes; - - switch (udphy->mode) { - case UDPHY_MODE_DP: - dp_lanes = 4; - break; - - case UDPHY_MODE_DP_USB: - dp_lanes = 2; - break; - - case UDPHY_MODE_USB: - default: - dp_lanes = 0; - break; - } - - return dp_lanes; -} - static void rk_udphy_dplane_enable(struct rk_udphy *udphy, int dp_lanes) { u32 val = 0; @@ -604,17 +584,13 @@ static void rk_udphy_dplane_enable(struct rk_udphy *udphy, int dp_lanes) CMN_DP_CMN_RSTN, FIELD_PREP(CMN_DP_CMN_RSTN, 0x0)); } -static void rk_udphy_dp_hpd_event_trigger(struct rk_udphy *udphy, bool hpd) +static void rk_udphy_mode_set(struct rk_udphy *udphy, u8 mode) { - const struct rk_udphy_cfg *cfg = udphy->cfgs; - - udphy->dp_sink_hpd_sel = true; - udphy->dp_sink_hpd_cfg = hpd; - - if (!udphy->dp_in_use) + if (udphy->mode == mode) return; - rk_udphy_grfreg_write(udphy->vogrf, &cfg->vogrfcfg[udphy->id].hpd_trigger, hpd); + udphy->phy_needs_reinit = true; + udphy->mode = mode; } static void rk_udphy_set_typec_default_mapping(struct rk_udphy *udphy) @@ -647,7 +623,8 @@ static void rk_udphy_set_typec_default_mapping(struct rk_udphy *udphy) gpiod_set_value_cansleep(udphy->sbu2_dc_gpio, 1); } - udphy->mode = UDPHY_MODE_DP_USB; + rk_udphy_mode_set(udphy, UDPHY_MODE_DP_USB); + udphy->dp_lanes = 2; } static int rk_udphy_orien_sw_set(struct typec_switch_dev *sw, @@ -793,8 +770,12 @@ static int rk_udphy_init(struct rk_udphy *udphy) /* Step 1: power on pma and deassert apb rstn */ rk_udphy_grfreg_write(udphy->udphygrf, &cfg->grfcfg.low_pwrn, true); - rk_udphy_reset_deassert(udphy, "pma_apb"); - rk_udphy_reset_deassert(udphy, "pcs_apb"); + ret = rk_udphy_reset_deassert(udphy, "pma_apb"); + if (ret) + goto assert_resets; + ret = rk_udphy_reset_deassert(udphy, "pcs_apb"); + if (ret) + goto assert_resets; /* Step 2: set init sequence and phy refclk */ ret = regmap_multi_reg_write(udphy->pma_regmap, rk_udphy_init_sequence, @@ -820,8 +801,11 @@ static int rk_udphy_init(struct rk_udphy *udphy) FIELD_PREP(CMN_DP_LANE_EN_ALL, 0)); /* Step 4: deassert init rstn and wait for 200ns from datasheet */ - if (udphy->mode & UDPHY_MODE_USB) - rk_udphy_reset_deassert(udphy, "init"); + if (udphy->mode & UDPHY_MODE_USB) { + ret = rk_udphy_reset_deassert(udphy, "init"); + if (ret) + goto assert_resets; + } if (udphy->mode & UDPHY_MODE_DP) { regmap_update_bits(udphy->pma_regmap, CMN_DP_RSTN_OFFSET, @@ -833,8 +817,14 @@ static int rk_udphy_init(struct rk_udphy *udphy) /* Step 5: deassert cmn/lane rstn */ if (udphy->mode & UDPHY_MODE_USB) { - rk_udphy_reset_deassert(udphy, "cmn"); - rk_udphy_reset_deassert(udphy, "lane"); + ret = rk_udphy_reset_deassert(udphy, "cmn"); + if (ret) + goto assert_resets; + + ret = rk_udphy_reset_deassert(udphy, "lane"); + if (ret) + goto assert_resets; + } /* Step 6: wait for lock done of pll */ @@ -886,7 +876,7 @@ static int rk_udphy_parse_lane_mux_data(struct rk_udphy *udphy) return 0; } - if (num_lanes != 2 && num_lanes != 4) + if (num_lanes != 1 && num_lanes != 2 && num_lanes != 4) return dev_err_probe(udphy->dev, -EINVAL, "invalid number of lane mux\n"); @@ -912,33 +902,13 @@ static int rk_udphy_parse_lane_mux_data(struct rk_udphy *udphy) } udphy->mode = UDPHY_MODE_DP; - if (num_lanes == 2) { + udphy->dp_lanes = num_lanes; + if (num_lanes == 1 || num_lanes == 2) { udphy->mode |= UDPHY_MODE_USB; - udphy->flip = (udphy->lane_mux_sel[0] == PHY_LANE_MUX_DP); - } - - return 0; -} - -static int rk_udphy_get_initial_status(struct rk_udphy *udphy) -{ - int ret; - u32 value; - - ret = clk_bulk_prepare_enable(udphy->num_clks, udphy->clks); - if (ret) { - dev_err(udphy->dev, "failed to enable clk\n"); - return ret; + udphy->flip = (udphy->lane_mux_sel[0] == PHY_LANE_MUX_DP) || + (udphy->lane_mux_sel[1] == PHY_LANE_MUX_DP); } - rk_udphy_reset_deassert_all(udphy); - - regmap_read(udphy->pma_regmap, CMN_LANE_MUX_AND_EN_OFFSET, &value); - if (FIELD_GET(CMN_DP_LANE_MUX_ALL, value) && FIELD_GET(CMN_DP_LANE_EN_ALL, value)) - udphy->status = UDPHY_MODE_DP; - else - rk_udphy_disable(udphy); - return 0; } @@ -999,23 +969,25 @@ static int rk_udphy_power_on(struct rk_udphy *udphy, u8 mode) } if (udphy->status == UDPHY_MODE_NONE) { - udphy->mode_change = false; ret = rk_udphy_setup(udphy); if (ret) return ret; - if (udphy->mode & UDPHY_MODE_USB) + if (!udphy->hs && udphy->mode & UDPHY_MODE_USB) rk_udphy_u3_port_disable(udphy, false); - } else if (udphy->mode_change) { - udphy->mode_change = false; - udphy->status = UDPHY_MODE_NONE; - if (udphy->mode == UDPHY_MODE_DP) - rk_udphy_u3_port_disable(udphy, true); + udphy->phy_needs_reinit = false; + } else if (udphy->phy_needs_reinit) { + rk_udphy_u3_port_disable(udphy, true); + udelay(10); rk_udphy_disable(udphy); ret = rk_udphy_setup(udphy); if (ret) return ret; + + if (!udphy->hs && udphy->mode & UDPHY_MODE_USB) + rk_udphy_u3_port_disable(udphy, false); + udphy->phy_needs_reinit = false; } udphy->status |= mode; @@ -1039,44 +1011,20 @@ static void rk_udphy_power_off(struct rk_udphy *udphy, u8 mode) rk_udphy_disable(udphy); } -static int rk_udphy_dp_phy_init(struct phy *phy) -{ - struct rk_udphy *udphy = phy_get_drvdata(phy); - - mutex_lock(&udphy->mutex); - - udphy->dp_in_use = true; - - mutex_unlock(&udphy->mutex); - - return 0; -} - -static int rk_udphy_dp_phy_exit(struct phy *phy) -{ - struct rk_udphy *udphy = phy_get_drvdata(phy); - - mutex_lock(&udphy->mutex); - udphy->dp_in_use = false; - mutex_unlock(&udphy->mutex); - return 0; -} - static int rk_udphy_dp_phy_power_on(struct phy *phy) { struct rk_udphy *udphy = phy_get_drvdata(phy); - int ret, dp_lanes; + int ret; mutex_lock(&udphy->mutex); - dp_lanes = rk_udphy_dplane_get(udphy); - phy_set_bus_width(phy, dp_lanes); + phy_set_bus_width(phy, udphy->dp_lanes); ret = rk_udphy_power_on(udphy, UDPHY_MODE_DP); if (ret) goto unlock; - rk_udphy_dplane_enable(udphy, dp_lanes); + rk_udphy_dplane_enable(udphy, udphy->dp_lanes); rk_udphy_dplane_select(udphy); @@ -1126,6 +1074,9 @@ static int rk_udphy_dp_phy_verify_link_rate(struct rk_udphy *udphy, static int rk_udphy_dp_phy_verify_lanes(struct rk_udphy *udphy, struct phy_configure_opts_dp *dp) { + if (dp->lanes > udphy->dp_lanes) + return -EINVAL; + switch (dp->lanes) { case 1: case 2: @@ -1200,6 +1151,8 @@ static int rk_udphy_dp_phy_configure(struct phy *phy, u32 i, val, lane; int ret; + guard(mutex)(&udphy->mutex); + if (dp->set_rate) { ret = rk_udphy_dp_phy_verify_link_rate(udphy, dp); if (ret) @@ -1291,8 +1244,6 @@ static int rk_udphy_dp_phy_configure(struct phy *phy, } static const struct phy_ops rk_udphy_dp_phy_ops = { - .init = rk_udphy_dp_phy_init, - .exit = rk_udphy_dp_phy_exit, .power_on = rk_udphy_dp_phy_power_on, .power_off = rk_udphy_dp_phy_power_off, .configure = rk_udphy_dp_phy_configure, @@ -1340,12 +1291,29 @@ static const struct phy_ops rk_udphy_usb3_phy_ops = { .owner = THIS_MODULE, }; +static bool rk_udphy_is_supported_mode(struct typec_mux_state *state) +{ + /* Handle Safe State and USB State */ + if (state->mode < TYPEC_STATE_MODAL) + return true; + + /* Handle DP AltMode */ + if (state->alt && state->alt->svid == USB_TYPEC_DP_SID) + return true; + + return false; +} + static int rk_udphy_typec_mux_set(struct typec_mux_dev *mux, struct typec_mux_state *state) { struct rk_udphy *udphy = typec_mux_get_drvdata(mux); u8 mode; + /* Ignore mux events not involving USB or DP */ + if (!rk_udphy_is_supported_mode(state)) + return 0; + mutex_lock(&udphy->mutex); switch (state->mode) { @@ -1356,6 +1324,7 @@ static int rk_udphy_typec_mux_set(struct typec_mux_dev *mux, udphy->lane_mux_sel[2] = PHY_LANE_MUX_DP; udphy->lane_mux_sel[3] = PHY_LANE_MUX_DP; mode = UDPHY_MODE_DP; + udphy->dp_lanes = 4; break; case TYPEC_DP_STATE_D: @@ -1372,28 +1341,11 @@ static int rk_udphy_typec_mux_set(struct typec_mux_dev *mux, udphy->lane_mux_sel[3] = PHY_LANE_MUX_DP; } mode = UDPHY_MODE_DP_USB; + udphy->dp_lanes = 2; break; } - if (state->alt && state->alt->svid == USB_TYPEC_DP_SID) { - struct typec_displayport_data *data = state->data; - - if (!data) { - rk_udphy_dp_hpd_event_trigger(udphy, false); - } else if (data->status & DP_STATUS_IRQ_HPD) { - rk_udphy_dp_hpd_event_trigger(udphy, false); - usleep_range(750, 800); - rk_udphy_dp_hpd_event_trigger(udphy, true); - } else if (data->status & DP_STATUS_HPD_STATE) { - if (udphy->mode != mode) { - udphy->mode = mode; - udphy->mode_change = true; - } - rk_udphy_dp_hpd_event_trigger(udphy, true); - } else { - rk_udphy_dp_hpd_event_trigger(udphy, false); - } - } + rk_udphy_mode_set(udphy, mode); mutex_unlock(&udphy->mutex); return 0; @@ -1492,10 +1444,6 @@ static int rk_udphy_probe(struct platform_device *pdev) if (ret) return ret; - ret = rk_udphy_get_initial_status(udphy); - if (ret) - return ret; - mutex_init(&udphy->mutex); platform_set_drvdata(pdev, udphy); @@ -1523,7 +1471,7 @@ static int rk_udphy_probe(struct platform_device *pdev) ret = PTR_ERR(udphy->phy_dp); return dev_err_probe(dev, ret, "failed to create DP phy\n"); } - phy_set_bus_width(udphy->phy_dp, rk_udphy_dplane_get(udphy)); + phy_set_bus_width(udphy->phy_dp, udphy->dp_lanes); udphy->phy_dp->attrs.max_link_rate = 8100; phy_set_drvdata(udphy->phy_dp, udphy); @@ -1536,20 +1484,6 @@ static int rk_udphy_probe(struct platform_device *pdev) return 0; } -static int __maybe_unused rk_udphy_resume(struct device *dev) -{ - struct rk_udphy *udphy = dev_get_drvdata(dev); - - if (udphy->dp_sink_hpd_sel) - rk_udphy_dp_hpd_event_trigger(udphy, udphy->dp_sink_hpd_cfg); - - return 0; -} - -static const struct dev_pm_ops rk_udphy_pm_ops = { - SET_LATE_SYSTEM_SLEEP_PM_OPS(NULL, rk_udphy_resume) -}; - static const char * const rk_udphy_rst_list[] = { "init", "cmn", "lane", "pcs_apb", "pma_apb" }; @@ -1573,7 +1507,6 @@ static const struct rk_udphy_cfg rk3576_udphy_cfgs = { }, .vogrfcfg = { { - .hpd_trigger = RK_UDPHY_GEN_GRF_REG(0x0000, 11, 10, 1, 3), .dp_lane_reg = 0x0000, }, }, @@ -1614,11 +1547,9 @@ static const struct rk_udphy_cfg rk3588_udphy_cfgs = { }, .vogrfcfg = { { - .hpd_trigger = RK_UDPHY_GEN_GRF_REG(0x0000, 11, 10, 1, 3), .dp_lane_reg = 0x0000, }, { - .hpd_trigger = RK_UDPHY_GEN_GRF_REG(0x0008, 11, 10, 1, 3), .dp_lane_reg = 0x0008, }, }, @@ -1654,7 +1585,6 @@ static struct platform_driver rk_udphy_driver = { .driver = { .name = "rockchip-usbdp-phy", .of_match_table = rk_udphy_dt_match, - .pm = &rk_udphy_pm_ops, }, }; module_platform_driver(rk_udphy_driver); diff --git a/drivers/phy/samsung/phy-exynos5-usbdrd.c b/drivers/phy/samsung/phy-exynos5-usbdrd.c index 8711a3b62c8e..087d552eb511 100644 --- a/drivers/phy/samsung/phy-exynos5-usbdrd.c +++ b/drivers/phy/samsung/phy-exynos5-usbdrd.c @@ -471,7 +471,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); }; @@ -708,7 +708,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; @@ -721,6 +721,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 @@ -831,7 +833,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; @@ -857,9 +859,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; @@ -881,6 +885,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) @@ -917,7 +923,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); @@ -940,9 +948,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) @@ -1203,7 +1212,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; @@ -1291,6 +1300,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) @@ -1304,11 +1315,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) @@ -1355,10 +1366,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) @@ -1458,11 +1471,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) @@ -1516,7 +1529,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; @@ -1622,6 +1635,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) @@ -1635,12 +1650,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) @@ -1689,11 +1705,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); @@ -1715,8 +1732,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) @@ -1741,7 +1761,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) @@ -2277,7 +2305,7 @@ exynosautov920_usb31drd_lane0_reset(struct exynos5_usbdrd_phy *phy_drd, int val) writel(reg, reg_phy + EXYNOSAUTOV920_USB31DRD_PHY_RST_CTRL); } -static void +static int exynosautov920_usb31drd_pipe3_init(struct exynos5_usbdrd_phy *phy_drd) { void __iomem *reg_phy = phy_drd->reg_phy; @@ -2335,6 +2363,8 @@ exynosautov920_usb31drd_pipe3_init(struct exynos5_usbdrd_phy *phy_drd) /* override values for level settings */ exynosautov920_usb31drd_cr_write(phy_drd, 0x22, 0x00F5); + + return 0; } static void @@ -2353,7 +2383,7 @@ exynosautov920_usb31drd_ssphy_disable(struct exynos5_usbdrd_phy *phy_drd) writel(reg, reg_phy + EXYNOSAUTOV920_USB31DRD_PHY_CONFIG7); } -static void +static int exynosautov920_usbdrd_utmi_init(struct exynos5_usbdrd_phy *phy_drd) { void __iomem *reg_phy = phy_drd->reg_phy; @@ -2457,6 +2487,8 @@ exynosautov920_usbdrd_utmi_init(struct exynos5_usbdrd_phy *phy_drd) reg = readl(reg_phy + EXYNOS2200_DRD_CLKRST); reg |= EXYNOS2200_CLKRST_LINK_PCLK_SEL; writel(reg, reg_phy + EXYNOS2200_DRD_CLKRST); + + return 0; } static void @@ -2504,11 +2536,11 @@ static int exynosautov920_usbdrd_phy_init(struct phy *phy) inst->phy_cfg->phy_isol(inst, false); /* 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 exynosautov920_usbdrd_phy_exit(struct phy *phy) diff --git a/drivers/phy/spacemit/Kconfig b/drivers/phy/spacemit/Kconfig index 5fdf18fce499..cd7ae48d8ea2 100644 --- a/drivers/phy/spacemit/Kconfig +++ b/drivers/phy/spacemit/Kconfig @@ -18,8 +18,10 @@ config PHY_SPACEMIT_K1_USB2 tristate "SpacemiT K1 USB 2.0 PHY support" depends on (ARCH_SPACEMIT || COMPILE_TEST) && OF depends on COMMON_CLK + depends on HAS_IOMEM depends on USB_COMMON select GENERIC_PHY + select REGMAP_MMIO help Enable this to support K1 USB 2.0 PHY driver. This driver takes care of enabling and clock setup and will be used by K1 udc/ehci/otg/xhci driver. diff --git a/drivers/pinctrl/mediatek/pinctrl-mt7629.c b/drivers/pinctrl/mediatek/pinctrl-mt7629.c index 385d66b8e3fb..29a4c171e8b6 100644 --- a/drivers/pinctrl/mediatek/pinctrl-mt7629.c +++ b/drivers/pinctrl/mediatek/pinctrl-mt7629.c @@ -294,7 +294,7 @@ static int mt7629_pwm_1_funcs[] = { 2, }; /* WF 2G */ static int mt7629_wf0_2g_pins[] = { 70, 71, 72, 73, 74, 75, 76, 77, 78, }; -static int mt7629_wf0_2g_funcs[] = { 1, 1, 1, 1, 1, 1, 1, 1, }; +static int mt7629_wf0_2g_funcs[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, }; /* WF 5G */ static int mt7629_wf0_5g_pins[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, }; diff --git a/drivers/pinctrl/microchip/pinctrl-mpfs-mssio.c b/drivers/pinctrl/microchip/pinctrl-mpfs-mssio.c index 92d38e5336de..8da0c5312ce3 100644 --- a/drivers/pinctrl/microchip/pinctrl-mpfs-mssio.c +++ b/drivers/pinctrl/microchip/pinctrl-mpfs-mssio.c @@ -612,7 +612,7 @@ static void mpfs_pinctrl_pinconf_dbg_show(struct pinctrl_dev *pctrl_dev, struct reg = mpfs_pinctrl_pin_to_iocfg_reg(pin); offset = mpfs_pinctrl_pin_to_iocfg_offset(pin); - seq_printf(seq, "pin: %u ", pin); + seq_printf(seq, " pin: %u ", pin); seq_printf(seq, "reg: %x offset: %u ", reg, offset); if (reg < 0 || offset < 0) diff --git a/drivers/pinctrl/nuvoton/pinctrl-ma35.c b/drivers/pinctrl/nuvoton/pinctrl-ma35.c index dafa85c105a1..a79ebf4be2c3 100644 --- a/drivers/pinctrl/nuvoton/pinctrl-ma35.c +++ b/drivers/pinctrl/nuvoton/pinctrl-ma35.c @@ -557,6 +557,8 @@ static int ma35_gpiolib_register(struct platform_device *pdev, struct ma35_pinct static int ma35_get_bank_data(struct ma35_pin_bank *bank) { + int ret; + bank->reg_base = fwnode_iomap(bank->fwnode, 0); if (!bank->reg_base) return -ENOMEM; @@ -569,7 +571,11 @@ static int ma35_get_bank_data(struct ma35_pin_bank *bank) if (IS_ERR(bank->clk)) return PTR_ERR(bank->clk); - return clk_prepare_enable(bank->clk); + ret = clk_prepare_enable(bank->clk); + if (ret) + clk_put(bank->clk); + + return ret; } static int ma35_pinctrl_get_soc_data(struct ma35_pinctrl *pctl, struct platform_device *pdev) diff --git a/drivers/pinctrl/pinctrl-generic-mux.c b/drivers/pinctrl/pinctrl-generic-mux.c index 202b72351efb..de85b4e75eb8 100644 --- a/drivers/pinctrl/pinctrl-generic-mux.c +++ b/drivers/pinctrl/pinctrl-generic-mux.c @@ -10,13 +10,11 @@ #include #include #include -#include #include #include #include #include "core.h" -#include "pinconf.h" #include "pinmux.h" #include "pinctrl-utils.h" @@ -38,39 +36,73 @@ mux_pinmux_dt_node_to_map(struct pinctrl_dev *pctldev, struct pinctrl_map **maps, unsigned int *num_maps) { unsigned int num_reserved_maps = 0; - struct mux_pin_function *function; - const char **group_names; int ret; - function = devm_kzalloc(pctldev->dev, sizeof(*function), GFP_KERNEL); - if (!function) - return -ENOMEM; - - group_names = devm_kcalloc(pctldev->dev, 1, sizeof(*group_names), GFP_KERNEL); - if (!group_names) - return -ENOMEM; - - function->mux_state = devm_mux_state_get_from_np(pctldev->dev, NULL, np_config); - if (IS_ERR(function->mux_state)) - return PTR_ERR(function->mux_state); + *maps = NULL; + *num_maps = 0; - ret = pinctrl_generic_to_map(pctldev, np_config, np_config, maps, - num_maps, &num_reserved_maps, group_names, - 0, &np_config->name, NULL, 0); + if (pinctrl_get_group_selector(pctldev, np_config->name) < 0) + return -ENODEV; + ret = pinctrl_utils_reserve_map(pctldev, maps, &num_reserved_maps, + num_maps, 1); if (ret) return ret; - ret = pinmux_generic_add_function(pctldev, np_config->name, group_names, - 1, function); + ret = pinctrl_utils_add_map_mux(pctldev, maps, &num_reserved_maps, + num_maps, np_config->name, + np_config->name); if (ret < 0) { pinctrl_utils_free_map(pctldev, *maps, *num_maps); + *maps = NULL; + *num_maps = 0; return ret; } return 0; } +static int mux_pinctrl_probe_dt(struct pinctrl_dev *pctldev, + struct device_node *np) +{ + struct device *dev = pctldev->dev; + + for_each_available_child_of_node_scoped(np, grp) { + struct mux_pin_function *function; + const char **group_names; + int ret; + + function = devm_kzalloc(dev, sizeof(*function), GFP_KERNEL); + if (!function) + return -ENOMEM; + + group_names = devm_kcalloc(dev, 1, sizeof(*group_names), GFP_KERNEL); + if (!group_names) + return -ENOMEM; + + group_names[0] = grp->name; + + function->mux_state = devm_mux_state_get_from_np(dev, NULL, grp); + if (IS_ERR(function->mux_state)) + return dev_err_probe(dev, PTR_ERR(function->mux_state), + "failed to get mux-state for %pOFn\n", + grp); + + ret = pinctrl_generic_add_group(pctldev, grp->name, NULL, 0, NULL); + if (ret < 0) + return dev_err_probe(dev, ret, + "failed to add group %pOFn\n", grp); + + ret = pinmux_generic_add_function(pctldev, grp->name, group_names, + 1, function); + if (ret < 0) + return dev_err_probe(dev, ret, + "failed to add function %pOFn\n", grp); + } + + return 0; +} + static const struct pinctrl_ops mux_pinctrl_ops = { .get_groups_count = pinctrl_generic_get_group_count, .get_group_name = pinctrl_generic_get_group_name, @@ -157,6 +189,10 @@ static int mux_pinctrl_probe(struct platform_device *pdev) if (ret) return dev_err_probe(dev, ret, "Failed to register pinctrl.\n"); + ret = mux_pinctrl_probe_dt(mpctl->pctl, dev->of_node); + if (ret) + return ret; + ret = pinctrl_enable(mpctl->pctl); if (ret) return dev_err_probe(dev, ret, "Failed to enable pinctrl.\n"); diff --git a/drivers/pinctrl/sprd/pinctrl-sprd.c b/drivers/pinctrl/sprd/pinctrl-sprd.c index 16cf9d15f247..a565d4fd4233 100644 --- a/drivers/pinctrl/sprd/pinctrl-sprd.c +++ b/drivers/pinctrl/sprd/pinctrl-sprd.c @@ -326,6 +326,9 @@ static int sprd_dt_node_to_map(struct pinctrl_dev *pctldev, out: kfree(configs); + if (ret < 0) + pinctrl_utils_free_map(pctldev, *map, *num_maps); + return ret; } diff --git a/drivers/pinctrl/stm32/Kconfig b/drivers/pinctrl/stm32/Kconfig index d6a171523012..cc425bbfc996 100644 --- a/drivers/pinctrl/stm32/Kconfig +++ b/drivers/pinctrl/stm32/Kconfig @@ -55,7 +55,7 @@ config PINCTRL_STM32MP157 config PINCTRL_STM32MP257 tristate "STMicroelectronics STM32MP257 pin control" depends on OF && HAS_IOMEM - default MACH_STM32MP25 || (ARCH_STM32 && ARM64) + default ARCH_STM32 && ARM64 select PINCTRL_STM32 config PINCTRL_STM32_HDP diff --git a/drivers/pinctrl/stm32/pinctrl-stm32.c b/drivers/pinctrl/stm32/pinctrl-stm32.c index 93127da05d56..241684cd383b 100644 --- a/drivers/pinctrl/stm32/pinctrl-stm32.c +++ b/drivers/pinctrl/stm32/pinctrl-stm32.c @@ -87,7 +87,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", @@ -609,7 +609,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; @@ -946,7 +946,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; @@ -1089,7 +1089,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; @@ -1135,7 +1135,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; @@ -1181,7 +1181,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; @@ -1242,7 +1242,7 @@ static int stm32_pconf_set_advcfgr(struct stm32_gpio_bank *bank, int offset, u32 spin_lock_irqsave(&bank->lock, flags); if (pctl->hwlock) { - err = hwspin_lock_timeout_in_atomic(pctl->hwlock, HWSPNLCK_TIMEOUT); + err = hwspin_lock_timeout_in_atomic(pctl->hwlock, HWSPNLCK_TIMEOUT_MS); if (err) { dev_err(pctl->dev, "Can't get hwspinlock\n"); goto unlock; @@ -1320,7 +1320,7 @@ stm32_pconf_set_skew_delay(struct stm32_gpio_bank *bank, int offset, u32 delay, spin_lock_irqsave(&bank->lock, flags); if (pctl->hwlock) { - err = hwspin_lock_timeout_in_atomic(pctl->hwlock, HWSPNLCK_TIMEOUT); + err = hwspin_lock_timeout_in_atomic(pctl->hwlock, HWSPNLCK_TIMEOUT_MS); if (err) { dev_err(pctl->dev, "Can't get hwspinlock\n"); goto unlock; @@ -1980,6 +1980,7 @@ int stm32_pctl_probe(struct platform_device *pdev) pctl->clks[i].clk = of_clk_get_by_name(np, NULL); if (IS_ERR(pctl->clks[i].clk)) { fwnode_handle_put(child); + clk_bulk_put(i, pctl->clks); return dev_err_probe(dev, PTR_ERR(pctl->clks[i].clk), "failed to get clk\n"); } @@ -1990,6 +1991,7 @@ int stm32_pctl_probe(struct platform_device *pdev) ret = clk_bulk_prepare_enable(banks, pctl->clks); if (ret) { dev_err(dev, "failed to prepare_enable clk (%d)\n", ret); + clk_bulk_put(banks, pctl->clks); return ret; } @@ -2014,6 +2016,7 @@ int stm32_pctl_probe(struct platform_device *pdev) } clk_bulk_disable_unprepare(banks, pctl->clks); + clk_bulk_put(banks, pctl->clks); return ret; } EXPORT_SYMBOL(stm32_pctl_probe); diff --git a/drivers/pinctrl/sunplus/Kconfig b/drivers/pinctrl/sunplus/Kconfig index 69f82590f6d2..aa9435d023d8 100644 --- a/drivers/pinctrl/sunplus/Kconfig +++ b/drivers/pinctrl/sunplus/Kconfig @@ -4,8 +4,8 @@ # config PINCTRL_SPPCTL - tristate "Sunplus SP7021 PinMux and GPIO driver" - depends on SOC_SP7021 + bool "Sunplus SP7021 PinMux and GPIO driver" + depends on SOC_SP7021 || COMPILE_TEST depends on OF && HAS_IOMEM select GENERIC_PINCTRL_GROUPS select GENERIC_PINMUX_FUNCTIONS @@ -16,6 +16,4 @@ config PINCTRL_SPPCTL help Say Y here to support Sunplus SP7021 pinmux controller. This driver requires the pinctrl framework. - GPIO is provided by the same driver. - To compile this driver as a module, choose M here. - The module will be called sppinctrl. + This driver also provides GPIO. diff --git a/drivers/platform/arm64/qcom-hamoa-ec.c b/drivers/platform/arm64/qcom-hamoa-ec.c index 4d2ad042a7f8..d34afd901324 100644 --- a/drivers/platform/arm64/qcom-hamoa-ec.c +++ b/drivers/platform/arm64/qcom-hamoa-ec.c @@ -331,17 +331,28 @@ static const struct thermal_cooling_device_ops qcom_ec_thermal_ops = { static int qcom_ec_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); + int ret; + + ret = i2c_smbus_write_byte_data(client, EC_MODERN_STANDBY_CMD, + EC_MODERN_STANDBY_EXIT); + enable_irq(client->irq); - return i2c_smbus_write_byte_data(client, EC_MODERN_STANDBY_CMD, - EC_MODERN_STANDBY_EXIT); + return ret; } static int qcom_ec_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); + int ret; + + /* Keep SCI reads from racing the I2C controller's system sleep. */ + disable_irq(client->irq); + ret = i2c_smbus_write_byte_data(client, EC_MODERN_STANDBY_CMD, + EC_MODERN_STANDBY_ENTER); + if (ret) + enable_irq(client->irq); - return i2c_smbus_write_byte_data(client, EC_MODERN_STANDBY_CMD, - EC_MODERN_STANDBY_ENTER); + return ret; } static int qcom_ec_probe(struct i2c_client *client) diff --git a/drivers/platform/chrome/cros_ec_proto.c b/drivers/platform/chrome/cros_ec_proto.c index 724d1313f6b2..b13312c1b093 100644 --- a/drivers/platform/chrome/cros_ec_proto.c +++ b/drivers/platform/chrome/cros_ec_proto.c @@ -138,7 +138,8 @@ static int cros_ec_xfer_command(struct cros_ec_device *ec_dev, struct cros_ec_co return ret; } -static int cros_ec_wait_until_complete(struct cros_ec_device *ec_dev, uint32_t *result) +static int cros_ec_wait_until_complete(struct cros_ec_device *ec_dev, + struct cros_ec_command *orig_msg) { DEFINE_RAW_FLEX(struct cros_ec_command, msg, data, sizeof(struct ec_response_get_comms_status)); @@ -161,7 +162,7 @@ static int cros_ec_wait_until_complete(struct cros_ec_device *ec_dev, uint32_t * if (ret < 0) return ret; - *result = msg->result; + orig_msg->result = msg->result; if (msg->result != EC_RES_SUCCESS) return ret; @@ -170,8 +171,31 @@ static int cros_ec_wait_until_complete(struct cros_ec_device *ec_dev, uint32_t * break; } - if (!(status->flags & EC_COMMS_STATUS_PROCESSING)) + if (!(status->flags & EC_COMMS_STATUS_PROCESSING)) { + u32 orig_cmd, orig_outsize, orig_version; + + /* If no response payload is expected, return 0. */ + if (orig_msg->insize == 0) + return 0; + + /* + * Request the response using EC_CMD_RESEND_RESPONSE. + * Restore the original message fields so it appears + * to be a direct response to the original command. + */ + orig_cmd = orig_msg->command; + orig_outsize = orig_msg->outsize; + orig_version = orig_msg->version; + + orig_msg->command = EC_CMD_RESEND_RESPONSE; + orig_msg->outsize = 0; + orig_msg->version = 0; + ret = cros_ec_xfer_command(ec_dev, orig_msg); + orig_msg->command = orig_cmd; + orig_msg->outsize = orig_outsize; + orig_msg->version = orig_version; return ret; + } } if (i >= EC_COMMAND_RETRIES) @@ -185,7 +209,7 @@ static int cros_ec_send_command(struct cros_ec_device *ec_dev, struct cros_ec_co int ret = cros_ec_xfer_command(ec_dev, msg); if (msg->result == EC_RES_IN_PROGRESS) - ret = cros_ec_wait_until_complete(ec_dev, &msg->result); + ret = cros_ec_wait_until_complete(ec_dev, msg); return ret; } diff --git a/drivers/platform/chrome/cros_ec_proto_test.c b/drivers/platform/chrome/cros_ec_proto_test.c index 3f281996a686..cbaaf98d6877 100644 --- a/drivers/platform/chrome/cros_ec_proto_test.c +++ b/drivers/platform/chrome/cros_ec_proto_test.c @@ -1744,7 +1744,7 @@ static void cros_ec_proto_test_cmd_xfer_protocol_v2_no_op(struct kunit *test) KUNIT_EXPECT_EQ(test, ret, -EIO); } -static void cros_ec_proto_test_cmd_xfer_in_progress_normal(struct kunit *test) +static void cros_ec_proto_test_cmd_xfer_in_progress_payload_0byte(struct kunit *test) { struct cros_ec_proto_test_priv *priv = test->priv; struct cros_ec_device *ec_dev = &priv->ec_dev; @@ -1774,7 +1774,7 @@ static void cros_ec_proto_test_cmd_xfer_in_progress_normal(struct kunit *test) } ret = cros_ec_cmd_xfer(ec_dev, &msg); - KUNIT_EXPECT_EQ(test, ret, sizeof(struct ec_response_get_comms_status)); + KUNIT_EXPECT_EQ(test, ret, 0); KUNIT_EXPECT_EQ(test, msg.result, EC_RES_SUCCESS); @@ -1799,6 +1799,156 @@ static void cros_ec_proto_test_cmd_xfer_in_progress_normal(struct kunit *test) KUNIT_EXPECT_EQ(test, cros_kunit_ec_pkt_xfer_mock_called, 2); } +static void cros_ec_proto_test_cmd_xfer_in_progress_payload_4bytes(struct kunit *test) +{ + struct cros_ec_proto_test_priv *priv = test->priv; + struct cros_ec_device *ec_dev = &priv->ec_dev; + struct ec_xfer_mock *mock; + u8 resp_data[4] = {0x11, 0x22, 0x33, 0x44}; + struct { + struct cros_ec_command msg; + u8 data[4]; + } buf; + struct cros_ec_command *msg = &buf.msg; + int ret; + + memset(&buf, 0, sizeof(buf)); + msg->version = 1; + msg->command = 0x1234; + msg->insize = sizeof(buf.data); + + ec_dev->max_response = sizeof(buf.data); + ec_dev->pkt_xfer = cros_kunit_ec_pkt_xfer_mock; + + /* For initial command returning EC_RES_IN_PROGRESS. */ + { + mock = cros_kunit_ec_xfer_mock_addx(test, 0, EC_RES_IN_PROGRESS, 0); + KUNIT_ASSERT_PTR_NE(test, mock, NULL); + } + + /* For EC_CMD_GET_COMMS_STATUS status polling. */ + { + struct ec_response_get_comms_status *data; + + mock = cros_kunit_ec_xfer_mock_add(test, sizeof(*data)); + KUNIT_ASSERT_PTR_NE(test, mock, NULL); + + data = (struct ec_response_get_comms_status *)mock->o_data; + data->flags = 0; + } + + /* For EC_CMD_RESEND_RESPONSE returning 4 bytes payload. */ + { + mock = cros_kunit_ec_xfer_mock_add(test, sizeof(resp_data)); + KUNIT_ASSERT_PTR_NE(test, mock, NULL); + memcpy(mock->o_data, resp_data, sizeof(resp_data)); + } + + ret = cros_ec_cmd_xfer(ec_dev, msg); + KUNIT_EXPECT_EQ(test, ret, 4); + KUNIT_EXPECT_EQ(test, msg->result, EC_RES_SUCCESS); + KUNIT_EXPECT_EQ(test, msg->command, 0x1234); + KUNIT_EXPECT_EQ(test, msg->insize, sizeof(buf.data)); + KUNIT_EXPECT_EQ(test, msg->version, 1); + KUNIT_EXPECT_EQ(test, memcmp(msg->data, resp_data, sizeof(resp_data)), 0); + + /* Verify mock sequence */ + { + mock = cros_kunit_ec_xfer_mock_next(); + KUNIT_EXPECT_PTR_NE(test, mock, NULL); + + mock = cros_kunit_ec_xfer_mock_next(); + KUNIT_EXPECT_PTR_NE(test, mock, NULL); + KUNIT_EXPECT_EQ(test, mock->msg.command, EC_CMD_GET_COMMS_STATUS); + + mock = cros_kunit_ec_xfer_mock_next(); + KUNIT_EXPECT_PTR_NE(test, mock, NULL); + KUNIT_EXPECT_EQ(test, mock->msg.command, EC_CMD_RESEND_RESPONSE); + KUNIT_EXPECT_EQ(test, mock->msg.outsize, 0); + KUNIT_EXPECT_EQ(test, mock->msg.version, 0); + KUNIT_EXPECT_EQ(test, mock->msg.insize, 4); + } + + KUNIT_EXPECT_EQ(test, cros_kunit_ec_pkt_xfer_mock_called, 3); +} + +static void cros_ec_proto_test_cmd_xfer_in_progress_payload_gt4bytes(struct kunit *test) +{ + struct cros_ec_proto_test_priv *priv = test->priv; + struct cros_ec_device *ec_dev = &priv->ec_dev; + struct ec_xfer_mock *mock; + u8 resp_data[16]; + struct { + struct cros_ec_command msg; + u8 data[16]; + } buf; + struct cros_ec_command *msg = &buf.msg; + int ret, i; + + for (i = 0; i < sizeof(resp_data); ++i) + resp_data[i] = (u8)(i + 1); + + memset(&buf, 0, sizeof(buf)); + msg->version = 0; + msg->command = 0x5678; + msg->insize = sizeof(buf.data); + + ec_dev->max_response = sizeof(buf.data); + ec_dev->pkt_xfer = cros_kunit_ec_pkt_xfer_mock; + + /* For initial command returning EC_RES_IN_PROGRESS. */ + { + mock = cros_kunit_ec_xfer_mock_addx(test, 0, EC_RES_IN_PROGRESS, 0); + KUNIT_ASSERT_PTR_NE(test, mock, NULL); + } + + /* For EC_CMD_GET_COMMS_STATUS status polling. */ + { + struct ec_response_get_comms_status *data; + + mock = cros_kunit_ec_xfer_mock_add(test, sizeof(*data)); + KUNIT_ASSERT_PTR_NE(test, mock, NULL); + + data = (struct ec_response_get_comms_status *)mock->o_data; + data->flags = 0; + } + + /* For EC_CMD_RESEND_RESPONSE returning 16 bytes payload. */ + { + mock = cros_kunit_ec_xfer_mock_add(test, sizeof(resp_data)); + KUNIT_ASSERT_PTR_NE(test, mock, NULL); + memcpy(mock->o_data, resp_data, sizeof(resp_data)); + } + + ret = cros_ec_cmd_xfer(ec_dev, msg); + KUNIT_EXPECT_EQ(test, ret, 16); + KUNIT_EXPECT_EQ(test, msg->result, EC_RES_SUCCESS); + KUNIT_EXPECT_EQ(test, msg->command, 0x5678); + KUNIT_EXPECT_EQ(test, msg->outsize, 0); + KUNIT_EXPECT_EQ(test, msg->insize, sizeof(buf.data)); + KUNIT_EXPECT_EQ(test, msg->version, 0); + KUNIT_EXPECT_EQ(test, memcmp(msg->data, resp_data, sizeof(resp_data)), 0); + + /* Verify mock sequence */ + { + mock = cros_kunit_ec_xfer_mock_next(); + KUNIT_EXPECT_PTR_NE(test, mock, NULL); + + mock = cros_kunit_ec_xfer_mock_next(); + KUNIT_EXPECT_PTR_NE(test, mock, NULL); + KUNIT_EXPECT_EQ(test, mock->msg.command, EC_CMD_GET_COMMS_STATUS); + + mock = cros_kunit_ec_xfer_mock_next(); + KUNIT_EXPECT_PTR_NE(test, mock, NULL); + KUNIT_EXPECT_EQ(test, mock->msg.command, EC_CMD_RESEND_RESPONSE); + KUNIT_EXPECT_EQ(test, mock->msg.outsize, 0); + KUNIT_EXPECT_EQ(test, mock->msg.version, 0); + KUNIT_EXPECT_EQ(test, mock->msg.insize, 16); + } + + KUNIT_EXPECT_EQ(test, cros_kunit_ec_pkt_xfer_mock_called, 3); +} + static void cros_ec_proto_test_cmd_xfer_in_progress_retries_eagain(struct kunit *test) { struct cros_ec_proto_test_priv *priv = test->priv; @@ -2703,7 +2853,9 @@ static struct kunit_case cros_ec_proto_test_cases[] = { KUNIT_CASE(cros_ec_proto_test_cmd_xfer_protocol_v3_no_op), KUNIT_CASE(cros_ec_proto_test_cmd_xfer_protocol_v2_normal), KUNIT_CASE(cros_ec_proto_test_cmd_xfer_protocol_v2_no_op), - KUNIT_CASE(cros_ec_proto_test_cmd_xfer_in_progress_normal), + KUNIT_CASE(cros_ec_proto_test_cmd_xfer_in_progress_payload_0byte), + KUNIT_CASE(cros_ec_proto_test_cmd_xfer_in_progress_payload_4bytes), + KUNIT_CASE(cros_ec_proto_test_cmd_xfer_in_progress_payload_gt4bytes), KUNIT_CASE(cros_ec_proto_test_cmd_xfer_in_progress_retries_eagain), KUNIT_CASE(cros_ec_proto_test_cmd_xfer_in_progress_retries_status_processing), KUNIT_CASE(cros_ec_proto_test_cmd_xfer_in_progress_xfer_error), diff --git a/drivers/platform/chrome/cros_ec_typec.c b/drivers/platform/chrome/cros_ec_typec.c index 50a68819ceb7..5871fe031f14 100644 --- a/drivers/platform/chrome/cros_ec_typec.c +++ b/drivers/platform/chrome/cros_ec_typec.c @@ -7,8 +7,12 @@ */ #include +#include +#include +#include #include #include +#include #include #include #include @@ -22,6 +26,14 @@ #define DRV_NAME "cros-ec-typec" +/* + * Mirrors PD_ROLE_SWAP_TIMEOUT used by the TCPM port manager: a PR_Swap may + * legitimately take seconds when the partner answers with Wait and the + * initiator retries. + */ +#define ROLE_SWAP_TIMEOUT_MS 10000 +#define ROLE_SWAP_DELAY_MS 20 + #define DP_PORT_VDO (DP_CAP_DFP_D | DP_CAP_RECEPTACLE | \ DP_CONF_SET_PIN_ASSIGN(BIT(DP_PIN_ASSIGN_C) | \ BIT(DP_PIN_ASSIGN_D) | \ @@ -58,12 +70,33 @@ static int cros_typec_enter_usb_mode(struct typec_port *tc_port, enum usb_mode m &req, sizeof(req), NULL, 0); } +/* + * Decode the role relevant to @swap_type out of an EC_CMD_USB_PD_CONTROL + * response. + * + * Returns a value comparable against the typec class target role + * (TYPEC_DEVICE/TYPEC_HOST or TYPEC_SINK/TYPEC_SOURCE), or -EOPNOTSUPP if + * @swap_type is not a role swap this driver knows how to track. + */ +static int cros_typec_resp_to_role(struct ec_response_usb_pd_control_v2 *resp, u8 swap_type) +{ + switch (swap_type) { + case USB_PD_CTRL_SWAP_DATA: + return (resp->role & PD_CTRL_RESP_ROLE_DATA) ? TYPEC_HOST : TYPEC_DEVICE; + case USB_PD_CTRL_SWAP_POWER: + return (resp->role & PD_CTRL_RESP_ROLE_POWER) ? TYPEC_SOURCE : TYPEC_SINK; + default: + return -EOPNOTSUPP; + } +} + static int cros_typec_perform_role_swap(struct typec_port *tc_port, int target_role, u8 swap_type) { struct cros_typec_port *port = typec_get_drvdata(tc_port); struct cros_typec_data *data = port->typec_data; struct ec_response_usb_pd_control_v2 resp; struct ec_params_usb_pd_control req; + unsigned long end; int role, ret; /* Must be at least v1 to support role swap. */ @@ -81,18 +114,10 @@ static int cros_typec_perform_role_swap(struct typec_port *tc_port, int target_r if (ret < 0) return ret; - switch (swap_type) { - case USB_PD_CTRL_SWAP_DATA: - role = (resp.role & PD_CTRL_RESP_ROLE_DATA) ? TYPEC_HOST : - TYPEC_DEVICE; - break; - case USB_PD_CTRL_SWAP_POWER: - role = (resp.role & PD_CTRL_RESP_ROLE_POWER) ? TYPEC_SOURCE : - TYPEC_SINK; - break; - default: + role = cros_typec_resp_to_role(&resp, swap_type); + if (role < 0) { dev_warn(data->dev, "Unsupported role swap type %d\n", swap_type); - return -EOPNOTSUPP; + return role; } if (role == target_role) @@ -104,28 +129,41 @@ static int cros_typec_perform_role_swap(struct typec_port *tc_port, int target_r if (ret < 0) return ret; - switch (swap_type) { - case USB_PD_CTRL_SWAP_DATA: - role = resp.role & PD_CTRL_RESP_ROLE_DATA ? TYPEC_HOST : TYPEC_DEVICE; - if (role != target_role) { - dev_err(data->dev, "Data role swap failed despite EC returning success\n"); - return -EIO; + /* + * Depending on the EC USB-C stack (TCPMv2 vs PDC), EC_CMD_USB_PD_CONTROL + * may either block until the swap completes or queue the request + * asynchronously and return the pre-swap role. Poll until the target + * role is reached while connected, or until the timeout expires. + */ + req.swap = USB_PD_CTRL_SWAP_NONE; + end = jiffies + msecs_to_jiffies(ROLE_SWAP_TIMEOUT_MS); + for (;;) { + if (!(resp.enabled & PD_CTRL_RESP_ENABLED_CONNECTED)) { + dev_warn(data->dev, "Port disconnected during role swap\n"); + return -ENOTCONN; } - typec_set_data_role(tc_port, target_role); - break; - case USB_PD_CTRL_SWAP_POWER: - role = resp.role & PD_CTRL_RESP_ROLE_POWER ? TYPEC_SOURCE : TYPEC_SINK; - if (role != target_role) { - dev_err(data->dev, "Power role swap failed despite EC returning success\n"); - return -EIO; + + if (cros_typec_resp_to_role(&resp, swap_type) == target_role) + break; + + if (time_after_eq(jiffies, end)) { + dev_err(data->dev, "Timed out waiting for role swap to complete\n"); + return -ETIMEDOUT; } - typec_set_pwr_role(tc_port, target_role); - break; - default: - /* Should never execute */ - break; + + msleep(ROLE_SWAP_DELAY_MS); + ret = cros_ec_cmd(data->ec, data->pd_ctrl_ver, + EC_CMD_USB_PD_CONTROL, &req, sizeof(req), + &resp, sizeof(resp)); + if (ret < 0) + return ret; } + if (swap_type == USB_PD_CTRL_SWAP_DATA) + typec_set_data_role(tc_port, target_role); + else + typec_set_pwr_role(tc_port, target_role); + return 0; } @@ -894,7 +932,15 @@ static int cros_typec_register_altmodes(struct cros_typec_data *typec, int port_ int ret = 0; int i, j; + if (struct_size(sop_disc, svids, sop_disc->svid_count) > EC_PROTO2_MAX_RESPONSE_SIZE) + return -EINVAL; + for (i = 0; i < sop_disc->svid_count; i++) { + if (sop_disc->svids[i].mode_count > ARRAY_SIZE(sop_disc->svids[i].mode_vdo)) { + ret = -EINVAL; + goto err_cleanup; + } + for (j = 0; j < sop_disc->svids[i].mode_count; j++) { memset(&desc, 0, sizeof(desc)); desc.svid = sop_disc->svids[i].svid; diff --git a/drivers/platform/cznic/turris-omnia-mcu-gpio.c b/drivers/platform/cznic/turris-omnia-mcu-gpio.c index 4e430d6c3fc4..8f43bfa92373 100644 --- a/drivers/platform/cznic/turris-omnia-mcu-gpio.c +++ b/drivers/platform/cznic/turris-omnia-mcu-gpio.c @@ -11,7 +11,6 @@ #include #include #include -#include #include #include #include @@ -841,6 +840,18 @@ static void button_release_emul_fn(struct work_struct *work) generic_handle_irq_safe(mcu->client->irq); } +static void omnia_disable_button_release_work(void *data) +{ + struct delayed_work *work = data; + + /* + * The IRQ thread may requeue this work while the IRQ remains active. + * Disable and drain it before releasing the IRQ action and the MCU + * state used by the worker. + */ + disable_delayed_work_sync(work); +} + static void fill_int_from_sts(unsigned long *rising, unsigned long *falling, unsigned long rising_sts, unsigned long falling_sts, @@ -1082,21 +1093,9 @@ int omnia_mcu_register_gpiochip(struct omnia_mcu *mcu) return dev_err_probe(dev, err, "Cannot request IRQ\n"); if (!new_api) { - /* - * The button_release_emul_work has to be initialized before the - * thread is requested, and on driver remove it needs to be - * canceled before the thread is freed. Therefore we can't use - * devm_delayed_work_autocancel() directly, because the order - * devm_delayed_work_autocancel(); - * devm_request_threaded_irq(); - * would cause improper release order: - * free_irq(); - * cancel_delayed_work_sync(); - * Instead we first initialize the work above, and only now - * after IRQ is requested we add the work devm action. - */ - err = devm_add_action(dev, devm_delayed_work_drop, - &mcu->button_release_emul_work); + err = devm_add_action_or_reset(dev, + omnia_disable_button_release_work, + &mcu->button_release_emul_work); if (err) return err; } diff --git a/drivers/platform/olpc/olpc-ec.c b/drivers/platform/olpc/olpc-ec.c index 4a2d36f7331e..063f7e55c421 100644 --- a/drivers/platform/olpc/olpc-ec.c +++ b/drivers/platform/olpc/olpc-ec.c @@ -269,7 +269,7 @@ static ssize_t ec_dbgfs_cmd_write(struct file *file, const char __user *buf, mutex_lock(&ec_dbgfs_lock); - size = simple_write_to_buffer(cmdbuf, sizeof(cmdbuf), ppos, buf, size); + size = simple_write_to_buffer(cmdbuf, sizeof(cmdbuf) - 1, ppos, buf, size); m = sscanf(cmdbuf, "%x:%u %x %x %x %x %x", &ec_cmd_int[0], &ec_dbgfs_resp_bytes, &ec_cmd_int[1], &ec_cmd_int[2], diff --git a/drivers/platform/surface/surface_aggregator_registry.c b/drivers/platform/surface/surface_aggregator_registry.c index d37a7e4c6b02..2cb8278d98ea 100644 --- a/drivers/platform/surface/surface_aggregator_registry.c +++ b/drivers/platform/surface/surface_aggregator_registry.c @@ -415,8 +415,7 @@ static const struct software_node *ssam_node_group_sp11[] = { &ssam_node_hid_kip_penstash, &ssam_node_hid_kip_touchpad, &ssam_node_hid_kip_fwupd, - &ssam_node_hid_sam_sensors, - &ssam_node_kip_tablet_switch, + &ssam_node_pos_tablet_switch, NULL, }; diff --git a/drivers/platform/x86/amd/pmc/pmc.c b/drivers/platform/x86/amd/pmc/pmc.c index f93c35efeaa0..c2ca56ef3d4e 100644 --- a/drivers/platform/x86/amd/pmc/pmc.c +++ b/drivers/platform/x86/amd/pmc/pmc.c @@ -183,7 +183,6 @@ static const struct amd_pmc_cpu_info amd_1ah_m80_cpu_info = { .smu_arg = AMD_PMC_REGISTER_ARG_1AH_80H, .smu_rsp = AMD_PMC_REGISTER_RSP_1AH_80H, .num_ips = ARRAY_SIZE(soc15_ip_blk_v3), - .scratch_reg = AMD_PMC_SCRATCH_REG_1AH, .ips_ptr = soc15_ip_blk_v3, .os_hint = MSG_OS_HINT_RN, }; @@ -958,6 +957,10 @@ static void amd_pmc_remove(struct platform_device *pdev) pci_dev_put(dev->rdev); if (IS_ENABLED(CONFIG_AMD_MP2_STB)) amd_mp2_stb_deinit(dev); + dev->regbase = NULL; + dev->smu_virt_addr = NULL; + dev->stb_virt_addr = NULL; + dev->fch_virt_addr = NULL; } static const struct acpi_device_id amd_pmc_acpi_ids[] = { diff --git a/drivers/platform/x86/amd/pmf/util.c b/drivers/platform/x86/amd/pmf/util.c index 4d1a61e4f1b9..2befc1b14842 100644 --- a/drivers/platform/x86/amd/pmf/util.c +++ b/drivers/platform/x86/amd/pmf/util.c @@ -123,6 +123,7 @@ static const struct file_operations pmf_if_ops = { .owner = THIS_MODULE, .open = amd_pmf_open, .unlocked_ioctl = amd_pmf_set_ioctl, + .compat_ioctl = compat_ptr_ioctl, }; static struct miscdevice amd_pmf_util_if = { diff --git a/drivers/platform/x86/asus-armoury.c b/drivers/platform/x86/asus-armoury.c index 93d9665717af..cb7b526bbe71 100644 --- a/drivers/platform/x86/asus-armoury.c +++ b/drivers/platform/x86/asus-armoury.c @@ -515,13 +515,25 @@ static ssize_t dgpu_disable_current_value_store(struct kobject *kobj, if (err) return err; - if (asus_armoury.gpu_mux_dev_id) { - err = armoury_get_devstate(NULL, &result, asus_armoury.gpu_mux_dev_id); - if (err) - return err; - if (!result && disable) { - pr_warn("Cannot disable dGPU when the MUX is in dGPU mode\n"); - return -EBUSY; + if (disable) { + if (asus_armoury.gpu_mux_dev_id) { + err = armoury_get_devstate(NULL, &result, asus_armoury.gpu_mux_dev_id); + if (err) + return err; + if (!result) { + pr_warn("Cannot disable dGPU when the MUX is in dGPU mode\n"); + return -EBUSY; + } + } + + if (armoury_has_devstate(ASUS_WMI_DEVID_DGPU_POWER_STATE)) { + err = armoury_get_devstate(NULL, &result, ASUS_WMI_DEVID_DGPU_POWER_STATE); + if (err) + return err; + if (result) { + pr_warn("Cannot disable dGPU when it is in use\n"); + return -EBUSY; + } } } diff --git a/drivers/platform/x86/asus-wmi.c b/drivers/platform/x86/asus-wmi.c index e4f8636f6462..53d694bffc61 100644 --- a/drivers/platform/x86/asus-wmi.c +++ b/drivers/platform/x86/asus-wmi.c @@ -3739,6 +3739,33 @@ static int fan_curve_write(struct asus_wmi *asus, arg1, arg2, arg3, arg4, &ret); } +/* + * A fan curve is a set of points the firmware interpolates between, so it + * only makes sense if neither temperature nor PWM ever decreases along it. + */ +static int fan_curve_validate(struct device *dev, struct fan_curve_data *data) +{ + u8 *percents = data->percents; + u8 *temps = data->temps; + int i; + + for (i = 1; i < FAN_CURVE_POINTS; i++) { + if (temps[i] < temps[i - 1]) { + dev_warn(dev, "fan curve: temperature decreases at point %d (%u < %u)\n", + i, temps[i], temps[i - 1]); + return -EINVAL; + } + + if (percents[i] < percents[i - 1]) { + dev_warn(dev, "fan curve: pwm decreases at point %d (%u < %u)\n", + i, percents[i], percents[i - 1]); + return -EINVAL; + } + } + + return 0; +} + static ssize_t fan_curve_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) @@ -3823,6 +3850,11 @@ static ssize_t fan_curve_enable_store(struct device *dev, } if (data->enabled) { + err = fan_curve_validate(dev, data); + if (err) { + data->enabled = false; + return err; + } err = fan_curve_write(asus, data); if (err) return err; diff --git a/drivers/platform/x86/gpd-pocket-fan.c b/drivers/platform/x86/gpd-pocket-fan.c index c9236738f896..ced93795c5d4 100644 --- a/drivers/platform/x86/gpd-pocket-fan.c +++ b/drivers/platform/x86/gpd-pocket-fan.c @@ -153,10 +153,6 @@ static int gpd_pocket_fan_probe(struct platform_device *pdev) return -ENOMEM; fan->dev = &pdev->dev; - ret = devm_delayed_work_autocancel(&pdev->dev, &fan->work, - gpd_pocket_fan_worker); - if (ret) - return ret; /* Note this returns a "weak" reference which we don't need to free */ fan->dts0 = thermal_zone_get_zone_by_name("soc_dts0"); @@ -175,6 +171,11 @@ static int gpd_pocket_fan_probe(struct platform_device *pdev) if (IS_ERR(fan->gpio1)) return PTR_ERR(fan->gpio1); + ret = devm_delayed_work_autocancel(&pdev->dev, &fan->work, + gpd_pocket_fan_worker); + if (ret) + return ret; + gpd_pocket_fan_force_update(fan); platform_set_drvdata(pdev, fan); diff --git a/drivers/platform/x86/hp/hp-bioscfg/int-attributes.c b/drivers/platform/x86/hp/hp-bioscfg/int-attributes.c index a27907066448..14317b7fd479 100644 --- a/drivers/platform/x86/hp/hp-bioscfg/int-attributes.c +++ b/drivers/platform/x86/hp/hp-bioscfg/int-attributes.c @@ -331,7 +331,12 @@ static int hp_populate_integer_elements_from_buffer(u8 *buffer_ptr, u32 *buffer_ // VALUE: integer_data->current_value = 0; - hp_get_string_from_buffer(&buffer_ptr, buffer_size, dst, dst_size); + ret = hp_get_string_from_buffer(&buffer_ptr, buffer_size, dst, dst_size); + if (ret < 0) { + kfree(dst); + return ret; + } + ret = kstrtoint(dst, 10, &integer_data->current_value); if (ret) pr_warn("Unable to convert string to integer: %s\n", dst); diff --git a/drivers/platform/x86/hp/hp-bioscfg/passwdobj-attributes.c b/drivers/platform/x86/hp/hp-bioscfg/passwdobj-attributes.c index f0551b455379..a2f50ecbecab 100644 --- a/drivers/platform/x86/hp/hp-bioscfg/passwdobj-attributes.c +++ b/drivers/platform/x86/hp/hp-bioscfg/passwdobj-attributes.c @@ -74,7 +74,7 @@ static int validate_password_input(int instance_id, const char *buf, if (is_current && !length) return 0; - if (length > MAX_PASSWD_SIZE) + if (length >= MAX_PASSWD_SIZE) return -E2BIG; if (password_data->min_password_length > length || diff --git a/drivers/platform/x86/hp/hp-bioscfg/spmobj-attributes.c b/drivers/platform/x86/hp/hp-bioscfg/spmobj-attributes.c index 040964ed50ce..343b2356943e 100644 --- a/drivers/platform/x86/hp/hp-bioscfg/spmobj-attributes.c +++ b/drivers/platform/x86/hp/hp-bioscfg/spmobj-attributes.c @@ -6,6 +6,7 @@ * Copyright (c) 2022 HP Development Company, L.P. */ +#include #include "bioscfg.h" static const char * const spm_state_types[] = { @@ -115,6 +116,9 @@ static ssize_t update_spm_state(void) if (ret < 0) return ret; + if (data.state >= ARRAY_SIZE(spm_mechanism_types)) + return -EIO; + bioscfg_drv.spm_data.mechanism = data.state; if (bioscfg_drv.spm_data.mechanism) bioscfg_drv.spm_data.is_enabled = 1; @@ -150,6 +154,9 @@ static ssize_t status_show(struct kobject *kobj, struct kobj_attribute if (ret < 0) return ret; + if (data.state >= ARRAY_SIZE(spm_state_types)) + return -EIO; + /* * 'status' is a read-only file that returns ASCII text in * JSON format reporting the status information. diff --git a/drivers/platform/x86/hp/hp-wmi.c b/drivers/platform/x86/hp/hp-wmi.c index 8a0fe50ef0c2..5582feea3c36 100644 --- a/drivers/platform/x86/hp/hp-wmi.c +++ b/drivers/platform/x86/hp/hp-wmi.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -207,7 +208,7 @@ static const char * const omen_thermal_profile_boards[] = { "886B", "886C", "88C8", "88CB", "88D1", "88D2", "88F4", "88F5", "88F6", "88F7", "88FD", "88FE", "88FF", "8900", "8901", "8902", "8912", "8917", "8918", "8949", "894A", "89EB", - "8A15", "8A42", "8A43", + "8A15", "8A17", "8A42", "8A43", "8BAD", "8C58", "8E41", @@ -227,7 +228,7 @@ static const char * const omen_thermal_profile_force_v0_boards[] = { * "balanced" when reaching zero. */ static const char * const omen_timed_thermal_profile_boards[] = { - "8A15", "8A42", + "8A15", "8A17", "8A42", "8BAD", }; @@ -2549,7 +2550,6 @@ static int __init hp_wmi_bios_setup(struct platform_device *device) static void __exit hp_wmi_bios_remove(struct platform_device *device) { int i; - struct hp_wmi_hwmon_priv *priv; for (i = 0; i < rfkill2_count; i++) { rfkill_unregister(rfkill2[i].rfkill); @@ -2568,10 +2568,6 @@ static void __exit hp_wmi_bios_remove(struct platform_device *device) rfkill_unregister(wwan_rfkill); rfkill_destroy(wwan_rfkill); } - - priv = platform_get_drvdata(device); - if (priv) - cancel_delayed_work_sync(&priv->keep_alive_dwork); } static int hp_wmi_resume_handler(struct device *device) @@ -2919,6 +2915,17 @@ static int hp_wmi_hwmon_init(void) ret = hp_wmi_setup_fan_settings(priv); if (ret) return ret; + + /* + * Set up the work before registering hwmon so that, on teardown, + * it is cancelled only after the sysfs writers that schedule it + * are gone. + */ + ret = devm_delayed_work_autocancel(dev, &priv->keep_alive_dwork, + hp_wmi_hwmon_keep_alive_handler); + if (ret) + return ret; + hwmon = devm_hwmon_device_register_with_info(dev, "hp", priv, &chip_info, NULL); @@ -2927,8 +2934,6 @@ static int hp_wmi_hwmon_init(void) return PTR_ERR(hwmon); } - INIT_DELAYED_WORK(&priv->keep_alive_dwork, hp_wmi_hwmon_keep_alive_handler); - platform_set_drvdata(hp_wmi_platform_dev, priv); ret = hp_wmi_apply_fan_settings(priv); if (ret) dev_warn(dev, "Failed to apply initial fan settings: %d\n", ret); diff --git a/drivers/platform/x86/ibm_rtl.c b/drivers/platform/x86/ibm_rtl.c index 139956168cf9..82fda8d9178b 100644 --- a/drivers/platform/x86/ibm_rtl.c +++ b/drivers/platform/x86/ibm_rtl.c @@ -234,9 +234,9 @@ static const struct dmi_system_id ibm_rtl_dmi_table[] __initconst = { }; static int __init ibm_rtl_init(void) { - unsigned long ebda_addr, ebda_size; + unsigned long ebda_addr, ebda_size, offset; unsigned int ebda_kb; - int ret = -ENODEV, i; + int ret = -ENODEV; if (force) pr_warn("module loaded by force\n"); @@ -271,9 +271,9 @@ static int __init ibm_rtl_init(void) { return -ENOMEM; /* search for the _RTL_ signature at the start of the table */ - for (i = 0 ; i < ebda_size/sizeof(unsigned int); i++) { + for (offset = 0; offset + sizeof(*rtl_table) <= ebda_size; offset += 4) { struct ibm_rtl_table __iomem * tmp; - tmp = (struct ibm_rtl_table __iomem *) (ebda_map + i*sizeof(unsigned int)); + tmp = (struct ibm_rtl_table __iomem *) (ebda_map + offset); if ((readq(&tmp->signature) & RTL_MASK) == RTL_SIGNATURE) { phys_addr_t addr; unsigned int plen; diff --git a/drivers/platform/x86/intel/pmc/core.h b/drivers/platform/x86/intel/pmc/core.h index b4c7399f8369..e55164e5807f 100644 --- a/drivers/platform/x86/intel/pmc/core.h +++ b/drivers/platform/x86/intel/pmc/core.h @@ -323,7 +323,7 @@ enum ppfear_regs { #define NVL_LPM_LIVE_STATUS_OFFSET 0x1760 #define NVL_LPM_NUM_MAPS 15 #define NVL_PCDH_NUM_S0IX_BLOCKER 107 -#define NVL_PCDS_NUM_S0IX_BLOCKER 71 +#define NVL_PCDS_NUM_S0IX_BLOCKER 70 #define NVL_PCHS_NUM_S0IX_BLOCKER 54 #define NVL_PCDS_PMC_LTR_RESERVED 0x1bac #define NVL_PCDH_BLK_REQ_OFFSET 53 diff --git a/drivers/platform/x86/intel/pmc/nvl.c b/drivers/platform/x86/intel/pmc/nvl.c index 8dabf2511dd9..1ed02332dbfc 100644 --- a/drivers/platform/x86/intel/pmc/nvl.c +++ b/drivers/platform/x86/intel/pmc/nvl.c @@ -14,7 +14,7 @@ /* PMC SSRAM PMT Telemetry GUIDS */ #define PCDH_LPM_REQ_GUID 0x01093101 #define PCHS_LPM_REQ_GUID 0x01092101 -#define PCDS_LPM_REQ_GUID 0x01091102 +#define PCDS_LPM_REQ_GUID 0x01091103 /* * Die Mapping to Product. diff --git a/drivers/platform/x86/intel/pmt/class.c b/drivers/platform/x86/intel/pmt/class.c index c25892a51180..c4f73e4e126a 100644 --- a/drivers/platform/x86/intel/pmt/class.c +++ b/drivers/platform/x86/intel/pmt/class.c @@ -100,7 +100,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; @@ -286,8 +286,6 @@ static int pmt_resolve_access_pci(struct intel_pmt_entry *entry, return -EINVAL; } - entry->pcidev = pci_dev; - return 0; } @@ -365,6 +363,7 @@ static int intel_pmt_populate_entry(struct intel_pmt_entry *entry, 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 a0ece4fc3837..258cb460e61c 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 { @@ -42,7 +41,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; u32 disc_header[PMT_DISC_DWORDS]; struct bin_attribute pmt_bin_attr; 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/platform/x86/intel/telemetry/core.c b/drivers/platform/x86/intel/telemetry/core.c index f312864b8d07..62299524a07b 100644 --- a/drivers/platform/x86/intel/telemetry/core.c +++ b/drivers/platform/x86/intel/telemetry/core.c @@ -24,6 +24,10 @@ static struct telemetry_core_config telm_core_conf; static int telemetry_def_get_trace_verbosity(enum telemetry_unit telem_unit, u32 *verbosity) { + if (!verbosity) + return -EINVAL; + + *verbosity = 0; return 0; } diff --git a/drivers/platform/x86/intel/tpmi_power_domains.c b/drivers/platform/x86/intel/tpmi_power_domains.c index 833052dc34d2..ea51fc56297d 100644 --- a/drivers/platform/x86/intel/tpmi_power_domains.c +++ b/drivers/platform/x86/intel/tpmi_power_domains.c @@ -156,6 +156,13 @@ EXPORT_SYMBOL_NS_GPL(tpmi_get_power_domain_mask, "INTEL_TPMI_POWER_DOMAIN"); int tpmi_get_linux_die_id(int pkg_id, int domain_id) { + /* + * When built in, this stays callable after tpmi_init() failed + * before allocating the map. + */ + if (!domain_die_map) + return -ENODEV; + if (pkg_id >= topology_max_packages() || domain_id >= MAX_POWER_DOMAINS) return -EINVAL; @@ -245,6 +252,7 @@ static int __init tpmi_init(void) free_domain_map: kfree(domain_die_map); + domain_die_map = NULL; free_domain_mask: kfree(tpmi_power_domain_mask); @@ -258,6 +266,7 @@ static void __exit tpmi_exit(void) cpuhp_remove_state(tpmi_hp_state); kfree(tpmi_power_domain_mask); kfree(domain_die_map); + domain_die_map = NULL; } module_exit(tpmi_exit) diff --git a/drivers/platform/x86/intel/vsec.c b/drivers/platform/x86/intel/vsec.c index 7d51f27f09bc..eea63c170ac4 100644 --- a/drivers/platform/x86/intel/vsec.c +++ b/drivers/platform/x86/intel/vsec.c @@ -51,6 +51,13 @@ struct vsec_priv { unsigned long found_caps; }; +static void intel_vsec_reset_state(struct vsec_priv *priv) +{ + memset(priv->suppliers, 0, sizeof(priv->suppliers)); + memset(priv->state, 0, sizeof(priv->state)); + priv->found_caps = 0; +} + static const char *intel_vsec_name(enum intel_vsec_id id) { switch (id) { @@ -857,6 +864,7 @@ static pci_ers_result_t intel_vsec_pci_slot_reset(struct pci_dev *pdev) { struct intel_vsec_device *intel_vsec_dev; pci_ers_result_t status = PCI_ERS_RESULT_DISCONNECT; + struct vsec_priv *priv = pci_get_drvdata(pdev); unsigned long index; dev_info(&pdev->dev, "Resetting PCI slot\n"); @@ -877,6 +885,13 @@ static pci_ers_result_t intel_vsec_pci_slot_reset(struct pci_dev *pdev) devm_release_action(&pdev->dev, intel_vsec_remove_aux, &intel_vsec_dev->auxdev); } + + /* + * intel_vsec_pci_init() reuses priv. Reset the registration state + * after tearing down old aux devices or the rewalk will skip them as + * already registered. + */ + intel_vsec_reset_state(priv); pci_restore_state(pdev); intel_vsec_pci_init(pdev); diff --git a/drivers/platform/x86/lenovo/ideapad-laptop.c b/drivers/platform/x86/lenovo/ideapad-laptop.c index 8213524504ee..1335f4e48870 100644 --- a/drivers/platform/x86/lenovo/ideapad-laptop.c +++ b/drivers/platform/x86/lenovo/ideapad-laptop.c @@ -297,12 +297,16 @@ static void ideapad_shared_exit(struct ideapad_private *priv) #define IDEAPAD_EC_POLL_MIN_US 150 #define IDEAPAD_EC_POLL_MAX_US 300 +/* + * On some models GBMD and the battery _BIX take the EC mutex and a + * serialized method in opposite order, so evaluate all methods exclusively. + */ static int eval_int(acpi_handle handle, const char *name, unsigned long *res) { unsigned long long result; acpi_status status; - status = acpi_evaluate_integer(handle, (char *)name, NULL, &result); + status = acpi_evaluate_integer_exclusive(handle, (char *)name, NULL, &result); if (ACPI_FAILURE(status)) return -EIO; @@ -324,7 +328,7 @@ static int eval_int_with_arg(acpi_handle handle, const char *name, unsigned long in_obj.type = ACPI_TYPE_INTEGER; in_obj.integer.value = arg; - status = acpi_evaluate_integer(handle, (char *)name, ¶ms, &result); + status = acpi_evaluate_integer_exclusive(handle, (char *)name, ¶ms, &result); if (ACPI_FAILURE(status)) return -EIO; @@ -336,7 +340,7 @@ static int eval_int_with_arg(acpi_handle handle, const char *name, unsigned long static int exec_simple_method(acpi_handle handle, const char *name, unsigned long arg) { - acpi_status status = acpi_execute_simple_method(handle, (char *)name, arg); + acpi_status status = acpi_execute_simple_method_exclusive(handle, (char *)name, arg); return ACPI_FAILURE(status) ? -EIO : 0; } @@ -394,7 +398,7 @@ static int eval_vpcw(acpi_handle handle, unsigned long cmd, unsigned long data) in_obj[1].type = ACPI_TYPE_INTEGER; in_obj[1].integer.value = data; - status = acpi_evaluate_object(handle, "VPCW", ¶ms, NULL); + status = acpi_evaluate_object_exclusive(handle, "VPCW", ¶ms, NULL); if (ACPI_FAILURE(status)) return -EIO; diff --git a/drivers/platform/x86/msi-ec.c b/drivers/platform/x86/msi-ec.c index 566dfc73cb67..1762551e072a 100644 --- a/drivers/platform/x86/msi-ec.c +++ b/drivers/platform/x86/msi-ec.c @@ -1279,6 +1279,15 @@ static ssize_t charge_control_threshold_show(u8 offset, if (result < 0) return result; + /* + * The EC may hold an out-of-range value (e.g. 0x80) when no charge + * limit has been set. Report the maximum threshold instead of a + * meaningless (possibly negative) percentage. + */ + if (rdata < conf.charge_control.range_min || + rdata > conf.charge_control.range_max) + rdata = conf.charge_control.range_max; + return sysfs_emit(buf, "%i\n", rdata - offset); } diff --git a/drivers/platform/x86/msi-wmi.c b/drivers/platform/x86/msi-wmi.c index c9db750fe5ae..05c35133a1b3 100644 --- a/drivers/platform/x86/msi-wmi.c +++ b/drivers/platform/x86/msi-wmi.c @@ -236,9 +236,9 @@ static void msi_wmi_notify(union acpi_object *obj, void *context) } /* Brightness is served via acpi video driver */ - if (key->type == KE_KEY && - (backlight || (key->code == MSI_KEY_BRIGHTNESSUP || - key->code == MSI_KEY_BRIGHTNESSDOWN))) + if (key->type == KE_KEY && !backlight && + (key->code == MSI_KEY_BRIGHTNESSUP || + key->code == MSI_KEY_BRIGHTNESSDOWN)) return; pr_debug("Send key: 0x%X - Input layer keycode: %d\n", key->code, key->keycode); diff --git a/drivers/platform/x86/topstar-laptop.c b/drivers/platform/x86/topstar-laptop.c index 0e842c55dcc5..730a599abf0f 100644 --- a/drivers/platform/x86/topstar-laptop.c +++ b/drivers/platform/x86/topstar-laptop.c @@ -287,10 +287,14 @@ static const struct dmi_system_id topstar_dmi_ids[] = { static int topstar_acpi_probe(struct platform_device *pdev) { - struct acpi_device *device = ACPI_COMPANION(&pdev->dev); + struct acpi_device *device; struct topstar_laptop *topstar; int err; + device = ACPI_COMPANION(&pdev->dev); + if (!device) + return -ENODEV; + dmi_check_system(topstar_dmi_ids); topstar = kzalloc_obj(struct topstar_laptop); diff --git a/drivers/pmdomain/imx/scu-pd.c b/drivers/pmdomain/imx/scu-pd.c index e3f9e741daf7..05d4364f34be 100644 --- a/drivers/pmdomain/imx/scu-pd.c +++ b/drivers/pmdomain/imx/scu-pd.c @@ -474,7 +474,7 @@ static int imx_scu_init_pm_domains(struct device *dev, struct genpd_onecell_data *pd_data; struct imx_sc_pm_domain *sc_pd; u32 count = 0; - int i, j; + int i, j, ret; for (i = 0; i < pd_soc->num_ranges; i++) count += pd_ranges[i].num; @@ -503,7 +503,13 @@ static int imx_scu_init_pm_domains(struct device *dev, pd_data->num_domains = count; pd_data->xlate = imx_scu_pd_xlate; - of_genpd_add_provider_onecell(dev->of_node, pd_data); + ret = of_genpd_add_provider_onecell(dev->of_node, pd_data); + if (ret) { + while (count) + pm_genpd_remove(domains[--count]); + + return ret; + } return 0; } diff --git a/drivers/pmdomain/renesas/r8a78000-mdlc.c b/drivers/pmdomain/renesas/r8a78000-mdlc.c index 2668fc2ac9cb..1fd71bb3da77 100644 --- a/drivers/pmdomain/renesas/r8a78000-mdlc.c +++ b/drivers/pmdomain/renesas/r8a78000-mdlc.c @@ -45,8 +45,9 @@ struct r8a78000_mdlc_priv { }; static struct generic_pm_domain *r8a78000_genpd_always_on; + static HLIST_HEAD(r8a78000_mdlc_list); -static DEFINE_MUTEX(r8a78000_mdlc_lock); /* protects the two above */ +static DEFINE_MUTEX(r8a78000_mdlc_lock); /* protects the list above */ static struct generic_pm_domain *r8a78000_genpd_xlate( const struct of_phandle_args *spec, void *data) @@ -191,10 +192,11 @@ static void r8a78000_genpd_del_provider(void *data) static int r8a78000_genpd_always_on_singleton(struct device *dev) { + static DEFINE_MUTEX(singleton_lock); struct generic_pm_domain *genpd; int ret; - guard(mutex)(&r8a78000_mdlc_lock); + guard(mutex)(&singleton_lock); if (r8a78000_genpd_always_on) return 0; diff --git a/drivers/power/sequencing/pwrseq-pcie-m2.c b/drivers/power/sequencing/pwrseq-pcie-m2.c index e42e85f47629..a745dc81003f 100644 --- a/drivers/power/sequencing/pwrseq-pcie-m2.c +++ b/drivers/power/sequencing/pwrseq-pcie-m2.c @@ -199,6 +199,8 @@ static const struct pci_device_id pwrseq_m2_pci_ids[] = { .driver_data = (kernel_ulong_t)"qcom,wcn7850-bt" }, { PCI_DEVICE_SUB(PCI_VENDOR_ID_QCOM, 0x1107, PCI_VENDOR_ID_LENOVO, 0xe0e9), .driver_data = (kernel_ulong_t)"qcom,wcn7850-bt" }, + { PCI_DEVICE_SUB(PCI_VENDOR_ID_QCOM, 0x1107, PCI_VENDOR_ID_FOXCONN, 0xe0ee), + .driver_data = (kernel_ulong_t)"qcom,wcn7850-bt" }, { } /* Sentinel */ }; diff --git a/drivers/power/supply/ab8500_bmdata.c b/drivers/power/supply/ab8500_bmdata.c index 19ed52852804..9e95bd6e4ae6 100644 --- a/drivers/power/supply/ab8500_bmdata.c +++ b/drivers/power/supply/ab8500_bmdata.c @@ -174,7 +174,7 @@ int ab8500_bm_of_probe(struct power_supply *psy, if (bi->constant_charge_voltage_max_uv < 0) bi->constant_charge_voltage_max_uv = 4100000; - if (bi->charge_term_current_ua) + if (bi->charge_term_current_ua < 0) /* Charging stops when we drop below this current */ bi->charge_term_current_ua = 200000; diff --git a/drivers/power/supply/ab8500_btemp.c b/drivers/power/supply/ab8500_btemp.c index 90a61d9db72c..8ed0246b4422 100644 --- a/drivers/power/supply/ab8500_btemp.c +++ b/drivers/power/supply/ab8500_btemp.c @@ -468,39 +468,29 @@ static void ab8500_btemp_periodic(struct ab8500_btemp *di, */ static int ab8500_btemp_get_temp(struct ab8500_btemp *di) { - int temp = 0; + int temp = di->bat_temp; /* * The BTEMP events are not reliabe on AB8500 cut3.3 * and prior versions */ - if (is_ab8500_3p3_or_earlier(di->parent)) { - temp = di->bat_temp * 10; - } else { + if (!is_ab8500_3p3_or_earlier(di->parent)) { if (di->events.btemp_low) { if (temp > di->btemp_ranges.btemp_low_limit) - temp = di->btemp_ranges.btemp_low_limit * 10; - else - temp = di->bat_temp * 10; + temp = di->btemp_ranges.btemp_low_limit; } else if (di->events.btemp_high) { if (temp < di->btemp_ranges.btemp_high_limit) - temp = di->btemp_ranges.btemp_high_limit * 10; - else - temp = di->bat_temp * 10; + temp = di->btemp_ranges.btemp_high_limit; } else if (di->events.btemp_lowmed) { if (temp > di->btemp_ranges.btemp_med_limit) - temp = di->btemp_ranges.btemp_med_limit * 10; - else - temp = di->bat_temp * 10; + temp = di->btemp_ranges.btemp_med_limit; } else if (di->events.btemp_medhigh) { if (temp < di->btemp_ranges.btemp_med_limit) - temp = di->btemp_ranges.btemp_med_limit * 10; - else - temp = di->bat_temp * 10; - } else - temp = di->bat_temp * 10; + temp = di->btemp_ranges.btemp_med_limit; + } } - return temp; + + return temp * 10; } /** diff --git a/drivers/power/supply/ab8500_chargalg.c b/drivers/power/supply/ab8500_chargalg.c index d2b9880b0770..71d82c6c193e 100644 --- a/drivers/power/supply/ab8500_chargalg.c +++ b/drivers/power/supply/ab8500_chargalg.c @@ -1241,12 +1241,9 @@ static void ab8500_chargalg_algorithm(struct ab8500_chargalg *di) charger_status = ab8500_chargalg_check_charger_connection(di); - if (is_ab8500(di->parent)) { - ret = ab8500_chargalg_check_charger_enable(di); - if (ret < 0) - dev_err(di->dev, "Checking charger is enabled error" - ": Returned Value %d\n", ret); - } + ret = ab8500_chargalg_check_charger_enable(di); + if (ret < 0) + dev_err(di->dev, "Checking charger enable failed: %d\n", ret); /* * First check if we have a charger connected. diff --git a/drivers/power/supply/ab8500_charger.c b/drivers/power/supply/ab8500_charger.c index ff38254d06ef..1a41b8d339d4 100644 --- a/drivers/power/supply/ab8500_charger.c +++ b/drivers/power/supply/ab8500_charger.c @@ -52,7 +52,8 @@ #define MAIN_CH_DET 0x01 #define MAIN_CH_CV_ON 0x04 #define USB_CH_CV_ON 0x08 -#define VBUS_DET_DBNC100 0x02 +#define USB_CH_ON 0x04 +#define VBUS_DET_DBNC_LONG 0x02 #define VBUS_DET_DBNC1 0x01 #define OTP_ENABLE_WD 0x01 #define DROP_COUNT_RESET 0x01 @@ -99,6 +100,8 @@ #define CHARGER_STATUS_POLL 10 /* in ms */ +#define AB8505_USB_CHARGER_NOT_OK_RETRIES 3 + #define CHG_WD_INTERVAL (60 * HZ) #define AB8500_SW_CONTROL_FALLBACK 0x03 @@ -136,6 +139,33 @@ enum ab8500_charger_link_status { USB_STAT_ACA_DOCK_CHARGER, }; +/* UsbLink1Status register values used by AB8505 */ +enum ab8505_charger_link_status { + AB8505_USB_STAT_OFF, + AB8505_USB_STAT_SDP_NOT_CHARGING, + AB8505_USB_STAT_SDP_CHARGING, + AB8505_USB_STAT_SDP_SUSPENDED, + AB8505_USB_STAT_CDP, + AB8505_USB_STAT_RESERVED_5, + AB8505_USB_STAT_RESERVED_6, + AB8505_USB_STAT_DCP, + AB8505_USB_STAT_ACA_RID_A, + AB8505_USB_STAT_ACA_RID_B, + AB8505_USB_STAT_ACA_RID_C, + AB8505_USB_STAT_RESERVED_11, + AB8505_USB_STAT_RESERVED_12, + AB8505_USB_STAT_UPSTREAM_IDGND, + AB8505_USB_STAT_CHARGER_NOT_OK, + AB8505_USB_STAT_CHARGER_DM_HIGH, + AB8505_USB_STAT_PHY_ENABLED, + AB8505_USB_STAT_UPSTREAM_NO_IDGND, + AB8505_USB_STAT_UPSTREAM_IDGND_VBUS, + AB8505_USB_STAT_CHARGER_SE1, + AB8505_USB_STAT_CARKIT_1, + AB8505_USB_STAT_CARKIT_2, + AB8505_USB_STAT_ACA_DOCK_CHARGER, +}; + enum ab8500_usb_state { AB8500_BM_USB_STATE_RESET_HS, /* HighSpeed Reset */ AB8500_BM_USB_STATE_RESET_FS, /* FullSpeed/LowSpeed Reset */ @@ -234,6 +264,8 @@ struct ab8500_charger_max_usb_in_curr { * @is_aca_rid: Incicate if accessory is ACA type * @current_stepping_sessions: * Counter for current stepping sessions + * @usb_charger_not_ok_retries: + * Number of AB8505 USB charger recovery attempts * @parent: Pointer to the struct ab8500 * @adc_main_charger_v ADC channel for main charger voltage * @adc_main_charger_c ADC channel for main charger current @@ -287,6 +319,7 @@ struct ab8500_charger { int invalid_charger_detect_state; int is_aca_rid; atomic_t current_stepping_sessions; + unsigned int usb_charger_not_ok_retries; struct ab8500 *parent; struct iio_channel *adc_main_charger_v; struct iio_channel *adc_main_charger_c; @@ -356,6 +389,10 @@ static void ab8500_enable_disable_sw_fallback(struct ab8500_charger *di, u8 bit; int ret; + /* SwControlFallback is reserved and must remain clear on AB8505. */ + if (is_ab8505(di->parent)) + return; + dev_dbg(di->dev, "SW Fallback: %d\n", fallback); if (is_ab8500(di->parent)) { @@ -442,6 +479,9 @@ static void ab8500_power_supply_changed(struct ab8500_charger *di, static void ab8500_charger_set_usb_connected(struct ab8500_charger *di, bool connected) { + if (!connected && !di->vbus_detected) + di->usb_charger_not_ok_retries = 0; + if (connected != di->usb.charger_connected) { dev_dbg(di->dev, "USB connected:%i\n", connected); di->usb.charger_connected = connected; @@ -661,27 +701,34 @@ static int ab8500_charger_detect_chargers(struct ab8500_charger *di, bool probe) int ret; u8 val; - /* Check for AC charger */ - ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, - AB8500_CH_STATUS1_REG, &val); - if (ret < 0) { - dev_err(di->dev, "%s ab8500 read failed\n", __func__); - return ret; - } + /* AB8505 has no integrated main charger. */ + if (!is_ab8505(di->parent)) { + ret = abx500_get_register_interruptible(di->dev, + AB8500_CHARGER, + AB8500_CH_STATUS1_REG, &val); + if (ret < 0) { + dev_err(di->dev, "%s ab8500 read failed\n", __func__); + return ret; + } - if (val & MAIN_CH_DET) - result = AC_PW_CONN; + if (val & MAIN_CH_DET) + result = AC_PW_CONN; + } /* Check for USB charger */ if (!probe) { /* - * AB8500 says VBUS_DET_DBNC1 & VBUS_DET_DBNC100 + * AB8500 says VBUS_DET_DBNC1 & VBUS_DET_DBNC_LONG * when disconnecting ACA even though no * charger was connected. Try waiting a little - * longer than the 100 ms of VBUS_DET_DBNC100... + * longer than its 100 ms debounce. AB8505 uses + * a 300 ms falling debounce for the same bit. */ - msleep(110); + if (is_ab8505(di->parent)) + msleep(310); + else + msleep(110); } ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, AB8500_CH_USBCH_STAT1_REG, &val); @@ -692,27 +739,118 @@ static int ab8500_charger_detect_chargers(struct ab8500_charger *di, bool probe) dev_dbg(di->dev, "%s AB8500_CH_USBCH_STAT1_REG %x\n", __func__, val); - if ((val & VBUS_DET_DBNC1) && (val & VBUS_DET_DBNC100)) + if ((val & VBUS_DET_DBNC1) && (val & VBUS_DET_DBNC_LONG)) result |= USB_PW_CONN; return result; } /** - * ab8500_charger_max_usb_curr() - get the max curr for the USB type + * ab8505_charger_max_usb_curr() - get the max current for the USB type * @di: pointer to the ab8500_charger structure * @link_status: the identified USB type * - * Get the maximum current that is allowed to be drawn from the host - * based on the USB type. + * Decode AB8505-specific UsbLink1Status values and get the maximum current + * that is allowed to be drawn based on the USB type. * Returns error code in case of failure else 0 on success */ +static int ab8505_charger_max_usb_curr(struct ab8500_charger *di, + u8 link_status) +{ + int ret = 0; + + di->is_aca_rid = 0; + + switch (link_status) { + case AB8505_USB_STAT_SDP_NOT_CHARGING: + case AB8505_USB_STAT_SDP_CHARGING: + case AB8505_USB_STAT_SDP_SUSPENDED: + case AB8505_USB_STAT_CDP: + case AB8505_USB_STAT_CHARGER_DM_HIGH: + case AB8505_USB_STAT_UPSTREAM_NO_IDGND: + case AB8505_USB_STAT_UPSTREAM_IDGND_VBUS: + case AB8505_USB_STAT_CHARGER_SE1: + case AB8505_USB_STAT_CARKIT_1: + case AB8505_USB_STAT_CARKIT_2: + case AB8505_USB_STAT_ACA_DOCK_CHARGER: + di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P5; + break; + case AB8505_USB_STAT_DCP: + di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_1P5; + break; + case AB8505_USB_STAT_ACA_RID_A: + di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P5; + di->is_aca_rid = 1; + break; + case AB8505_USB_STAT_ACA_RID_B: + di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_1P3; + di->is_aca_rid = 1; + break; + case AB8505_USB_STAT_ACA_RID_C: + di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_1P5; + di->is_aca_rid = 1; + break; + case AB8505_USB_STAT_OFF: + if (di->vbus_detected) { + di->usb_device_is_unrecognised = true; + di->max_usb_in_curr.usb_type_max_ua = + USB_CH_IP_CUR_LVL_1P5; + break; + } + fallthrough; + case AB8505_USB_STAT_UPSTREAM_IDGND: + case AB8505_USB_STAT_PHY_ENABLED: + dev_err(di->dev, "USB Type - Charging not allowed\n"); + di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P05; + ret = -ENXIO; + break; + case AB8505_USB_STAT_CHARGER_NOT_OK: + di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P05; + if (di->usb_charger_not_ok_retries < + AB8505_USB_CHARGER_NOT_OK_RETRIES) { + dev_warn(di->dev, + "USB Type - VBUS has collapsed, retrying\n"); + queue_delayed_work(di->charger_wq, + &di->check_usbchgnotok_work, 0); + ret = -EAGAIN; + } else { + dev_err(di->dev, + "USB Type - VBUS recovery failed\n"); + ret = -ENXIO; + } + break; + case AB8505_USB_STAT_RESERVED_5: + case AB8505_USB_STAT_RESERVED_6: + case AB8505_USB_STAT_RESERVED_11: + case AB8505_USB_STAT_RESERVED_12: + default: + dev_err(di->dev, "USB Type - Unknown\n"); + di->max_usb_in_curr.usb_type_max_ua = USB_CH_IP_CUR_LVL_0P05; + ret = -ENXIO; + break; + } + + return ret; +} + +/** + * ab8500_charger_max_usb_curr() - get the max current for the USB type + * @di: pointer to the ab8500_charger structure + * @link_status: the identified USB type + * + * Get the maximum current that is allowed to be drawn based on the USB type. + * Returns error code in case of failure else 0 on success. + */ static int ab8500_charger_max_usb_curr(struct ab8500_charger *di, - enum ab8500_charger_link_status link_status) + u8 link_status) { int ret = 0; di->usb_device_is_unrecognised = false; + if (is_ab8505(di->parent)) { + ret = ab8505_charger_max_usb_curr(di, link_status); + goto out; + } /* * Platform only supports USB 2.0. @@ -721,7 +859,7 @@ static int ab8500_charger_max_usb_curr(struct ab8500_charger *di, * should set USB_CH_IP_CUR_LVL_0P5. */ - switch (link_status) { + switch ((enum ab8500_charger_link_status)link_status) { case USB_STAT_STD_HOST_NC: case USB_STAT_STD_HOST_C_NS: case USB_STAT_STD_HOST_C_S: @@ -825,6 +963,7 @@ static int ab8500_charger_max_usb_curr(struct ab8500_charger *di, break; } +out: di->max_usb_in_curr.set_max_ua = di->max_usb_in_curr.usb_type_max_ua; dev_dbg(di->dev, "USB Type - 0x%02x MaxCurr: %d", link_status, di->max_usb_in_curr.set_max_ua); @@ -866,8 +1005,7 @@ static int ab8500_charger_read_usb_type(struct ab8500_charger *di) val = (val & AB8500_USB_LINK_STATUS) >> USB_LINK_STATUS_SHIFT; else val = (val & AB8505_USB_LINK_STATUS) >> USB_LINK_STATUS_SHIFT; - ret = ab8500_charger_max_usb_curr(di, - (enum ab8500_charger_link_status) val); + ret = ab8500_charger_max_usb_curr(di, val); return ret; } @@ -929,8 +1067,7 @@ static int ab8500_charger_detect_usb_type(struct ab8500_charger *di) if (val) break; } - ret = ab8500_charger_max_usb_curr(di, - (enum ab8500_charger_link_status) val); + ret = ab8500_charger_max_usb_curr(di, val); return ret; } @@ -1741,6 +1878,9 @@ static int ab8500_charger_usb_check_enable(struct ux500_charger *charger, int vset_uv, int iset_ua) { u8 usbch_ctrl1 = 0; + u8 usbch_status1; + u8 usbch_status2; + bool reenable; int ret = 0; struct ab8500_charger *di = to_ab8500_charger_usb_device_info(charger); @@ -1756,7 +1896,52 @@ static int ab8500_charger_usb_check_enable(struct ux500_charger *charger, } dev_dbg(di->dev, "USB charger ctrl: 0x%02x\n", usbch_ctrl1); - if (!(usbch_ctrl1 & USB_CH_ENA)) { + reenable = !(usbch_ctrl1 & USB_CH_ENA); + if (is_ab8505(di->parent)) { + ret = abx500_get_register_interruptible(di->dev, + AB8500_CHARGER, + AB8500_CH_USBCH_STAT1_REG, + &usbch_status1); + if (ret < 0) { + dev_err(di->dev, "USB charger status read failed\n"); + return ret; + } + + if (!reenable && (usbch_status1 & USB_CH_ON)) + return 0; + + if (!(usbch_status1 & VBUS_DET_DBNC_LONG)) + return 0; + + ret = abx500_get_register_interruptible(di->dev, + AB8500_CHARGER, + AB8500_CH_USBCH_STAT2_REG, + &usbch_status2); + if (ret < 0) { + dev_err(di->dev, "USB charger fault status read failed\n"); + return ret; + } + + if ((usbch_status2 & + (VBUS_CH_NOK | USB_CH_TH_PROT | VBUS_OVV_TH)) || + di->flags.usbchargernotok || di->flags.usb_thermal_prot || + di->flags.vbus_ovv || di->usb.wd_expired) + return 0; + + if (!reenable) { + dev_info(di->dev, + "USB charger enabled but inactive, cycling it\n"); + ret = abx500_mask_and_set_register_interruptible(di->dev, + AB8500_CHARGER, + AB8500_USBCH_CTRL1_REG, + USB_CH_ENA, 0); + if (ret < 0) + return ret; + reenable = true; + } + } + + if (reenable) { dev_info(di->dev, "Charging has been disabled abnormally and will be re-enabled\n"); ret = abx500_mask_and_set_register_interruptible(di->dev, @@ -1778,7 +1963,7 @@ static int ab8500_charger_usb_check_enable(struct ux500_charger *charger, } /** - * ab8500_charger_ac_check_enable() - enable usb charging + * ab8500_charger_ac_check_enable() - enable AC charging * @charger: pointer to the ux500_charger structure * @vset_uv: charging voltage in microvolt * @iset_ua: charger output current in micrompere @@ -1817,7 +2002,7 @@ static int ab8500_charger_ac_check_enable(struct ux500_charger *charger, return ret; } - ret = ab8500_charger_ac_en(&di->usb_chg, true, vset_uv, iset_ua); + ret = ab8500_charger_ac_en(&di->ac_chg, true, vset_uv, iset_ua); if (ret < 0) { dev_err(di->dev, "failed to enable AC charger %d\n", __LINE__); @@ -2277,6 +2462,7 @@ static void ab8500_charger_usb_link_status_work(struct work_struct *work) int ret; u8 val; u8 link_status; + u8 link_status_mask; struct ab8500_charger *di = container_of(work, struct ab8500_charger, usb_link_status_work); @@ -2303,20 +2489,22 @@ static void ab8500_charger_usb_link_status_work(struct work_struct *work) ret = abx500_get_register_interruptible(di->dev, AB8500_USB, AB8500_USB_LINK1_STAT_REG, &val); - if (ret >= 0) - dev_dbg(di->dev, "UsbLineStatus register = 0x%02x\n", val); - else - dev_dbg(di->dev, "Error reading USB link status\n"); + if (ret < 0) { + dev_err(di->dev, "Error reading USB link status\n"); + return; + } + dev_dbg(di->dev, "UsbLineStatus register = 0x%02x\n", val); if (is_ab8500(di->parent)) - link_status = AB8500_USB_LINK_STATUS; + link_status_mask = AB8500_USB_LINK_STATUS; else - link_status = AB8505_USB_LINK_STATUS; + link_status_mask = AB8505_USB_LINK_STATUS; + link_status = (val & link_status_mask) >> USB_LINK_STATUS_SHIFT; if (detected_chargers & USB_PW_CONN) { - if (((val & link_status) >> USB_LINK_STATUS_SHIFT) == - USB_STAT_NOT_VALID_LINK && - di->invalid_charger_detect_state == 0) { + if (is_ab8500(di->parent) && + link_status == USB_STAT_NOT_VALID_LINK && + di->invalid_charger_detect_state == 0) { dev_dbg(di->dev, "Invalid charger detected, state= 0\n"); /*Enable charger*/ @@ -2339,18 +2527,21 @@ static void ab8500_charger_usb_link_status_work(struct work_struct *work) abx500_mask_and_set_register_interruptible(di->dev, AB8500_USB, AB8500_USB_LINE_CTRL2_REG, USB_CH_DET, 0x00); - /*Check link status*/ - if (is_ab8500(di->parent)) - ret = abx500_get_register_interruptible(di->dev, - AB8500_USB, AB8500_USB_LINE_STAT_REG, - &val); - else - ret = abx500_get_register_interruptible(di->dev, - AB8500_USB, AB8500_USB_LINK1_STAT_REG, - &val); + /* Check link status */ + ret = abx500_get_register_interruptible(di->dev, + AB8500_USB, + AB8500_USB_LINE_STAT_REG, + &val); + if (ret < 0) { + dev_err(di->dev, + "Error reading USB link status\n"); + return; + } + link_status = (val & link_status_mask) >> + USB_LINK_STATUS_SHIFT; dev_dbg(di->dev, "USB link status= 0x%02x\n", - (val & link_status) >> USB_LINK_STATUS_SHIFT); + link_status); di->invalid_charger_detect_state = 2; } } else { @@ -2462,6 +2653,48 @@ static void ab8500_charger_usb_state_changed_work(struct work_struct *work) } } +static int ab8505_charger_retry_usb_detection(struct ab8500_charger *di) +{ + u8 usbch_ctrl1; + bool usb_enabled; + int restore_ret; + int ret; + + ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER, + AB8500_USBCH_CTRL1_REG, + &usbch_ctrl1); + if (ret < 0) + return ret; + + usb_enabled = usbch_ctrl1 & USB_CH_ENA; + if (usb_enabled) { + ret = abx500_mask_and_set_register_interruptible(di->dev, + AB8500_CHARGER, + AB8500_USBCH_CTRL1_REG, + USB_CH_ENA, 0); + if (ret < 0) + return ret; + } + + ret = abx500_mask_and_set_register_interruptible(di->dev, + AB8500_CHARGER, + AB8500_CHARGER_CTRL, + DROP_COUNT_RESET, + DROP_COUNT_RESET); + + if (usb_enabled) { + restore_ret = abx500_mask_and_set_register_interruptible(di->dev, + AB8500_CHARGER, + AB8500_USBCH_CTRL1_REG, + USB_CH_ENA, + USB_CH_ENA); + if (restore_ret < 0) + return restore_ret; + } + + return ret; +} + /** * ab8500_charger_check_usbchargernotok_work() - check USB chg not ok status * @work: pointer to the work_struct structure @@ -2471,7 +2704,10 @@ static void ab8500_charger_usb_state_changed_work(struct work_struct *work) static void ab8500_charger_check_usbchargernotok_work(struct work_struct *work) { int ret; + u8 link_status = 0; u8 reg_value; + bool charger_not_ok; + bool prev_collapse; bool prev_status; struct ab8500_charger *di = container_of(work, @@ -2484,19 +2720,61 @@ static void ab8500_charger_check_usbchargernotok_work(struct work_struct *work) dev_err(di->dev, "%s ab8500 read failed\n", __func__); return; } + charger_not_ok = reg_value & VBUS_CH_NOK; + if (is_ab8505(di->parent)) { + ret = abx500_get_register_interruptible(di->dev, AB8500_USB, + AB8500_USB_LINK1_STAT_REG, + &link_status); + if (ret < 0) { + dev_err(di->dev, "%s USB link status read failed\n", + __func__); + return; + } + + link_status = (link_status & AB8505_USB_LINK_STATUS) >> + USB_LINK_STATUS_SHIFT; + charger_not_ok |= + link_status == AB8505_USB_STAT_CHARGER_NOT_OK; + } + prev_status = di->flags.usbchargernotok; + prev_collapse = di->flags.vbus_collapse; + + if (is_ab8505(di->parent) && + link_status == AB8505_USB_STAT_CHARGER_NOT_OK && + di->usb_charger_not_ok_retries < + AB8505_USB_CHARGER_NOT_OK_RETRIES) { + di->usb_charger_not_ok_retries++; + di->flags.usbchargernotok = false; + di->flags.vbus_collapse = true; + dev_warn(di->dev, "Retrying USB charger detection (%u/%u)\n", + di->usb_charger_not_ok_retries, + AB8505_USB_CHARGER_NOT_OK_RETRIES); + + ret = ab8505_charger_retry_usb_detection(di); + if (ret < 0) + dev_err(di->dev, "USB charger retry failed: %d\n", ret); - if (reg_value & VBUS_CH_NOK) { + queue_delayed_work(di->charger_wq, + &di->check_usbchgnotok_work, HZ); + } else if (charger_not_ok) { di->flags.usbchargernotok = true; + if (is_ab8505(di->parent) && + link_status == AB8505_USB_STAT_CHARGER_NOT_OK) { + di->flags.vbus_collapse = false; + ab8500_charger_set_usb_connected(di, false); + } /* Check again in 1sec */ queue_delayed_work(di->charger_wq, &di->check_usbchgnotok_work, HZ); } else { di->flags.usbchargernotok = false; di->flags.vbus_collapse = false; + di->usb_charger_not_ok_retries = 0; } - if (prev_status != di->flags.usbchargernotok) + if (prev_status != di->flags.usbchargernotok || + prev_collapse != di->flags.vbus_collapse) ab8500_power_supply_changed(di, di->usb_chg.psy); } @@ -3071,7 +3349,7 @@ static int ab8500_charger_init_hw_registers(struct ab8500_charger *di) } } - if (is_ab8505_2p0(di->parent)) + if (is_ab8505(di->parent)) ret = abx500_mask_and_set_register_interruptible(di->dev, AB8500_CHARGER, AB8500_USBCH_CTRL2_REG, @@ -3340,6 +3618,10 @@ static int ab8500_charger_bind(struct device *dev) } ch_stat = ab8500_charger_detect_chargers(di, false); + if (ch_stat < 0) { + destroy_workqueue(di->charger_wq); + return ch_stat; + } if (ch_stat & AC_PW_CONN) { if (is_ab8500(di->parent)) @@ -3374,7 +3656,8 @@ static void ab8500_charger_unbind(struct device *dev) int ret; /* Disable AC charging */ - ab8500_charger_ac_en(&di->ac_chg, false, 0, 0); + if (di->ac_chg.enabled) + ab8500_charger_ac_en(&di->ac_chg, false, 0, 0); /* Disable USB charging */ ab8500_charger_usb_en(&di->usb_chg, false, 0, 0); @@ -3420,11 +3703,14 @@ static int ab8500_charger_probe(struct platform_device *pdev) di->bm = &ab8500_bm_data; - di->autopower_cfg = of_property_read_bool(np, "autopower_cfg"); - /* get parent data */ di->dev = dev; di->parent = dev_get_drvdata(pdev->dev.parent); + di->autopower_cfg = of_property_read_bool(np, "autopower_cfg"); + if (di->autopower_cfg && is_ab8505(di->parent)) { + dev_warn(dev, "autopower is not supported on AB8505\n"); + di->autopower_cfg = false; + } /* Get ADC channels */ if (!is_ab8505(di->parent)) { @@ -3595,7 +3881,13 @@ static int ab8500_charger_probe(struct platform_device *pdev) } /* Request interrupts */ - for (i = 0; i < ARRAY_SIZE(ab8500_charger_irq); i++) { + /* The first five interrupts belong to the AB8500 main charger. */ + if (is_ab8505(di->parent)) + i = 5; + else + i = 0; + + for (; i < ARRAY_SIZE(ab8500_charger_irq); i++) { irq = platform_get_irq_byname(pdev, ab8500_charger_irq[i].name); if (irq < 0) return irq; @@ -3622,6 +3914,10 @@ static int ab8500_charger_probe(struct platform_device *pdev) /* Identify the connected charger types during startup */ charger_status = ab8500_charger_detect_chargers(di, true); + if (charger_status < 0) { + ret = charger_status; + goto remove_ab8500_bm; + } if (charger_status & AC_PW_CONN) { di->ac.charger_connected = 1; di->ac_conn = true; diff --git a/drivers/power/supply/ab8500_fg.c b/drivers/power/supply/ab8500_fg.c index c5eaa32c4a2d..7e8416adb2ce 100644 --- a/drivers/power/supply/ab8500_fg.c +++ b/drivers/power/supply/ab8500_fg.c @@ -451,6 +451,16 @@ static void ab8500_fg_fill_cap_sample(struct ab8500_fg *di, int sample) avg->avg = sample; } +static u8 ab8500_fg_cc_config(struct ab8500_fg *di) +{ + u8 config = CC_PWR_UP_ENA; + + if (!is_ab8505(di->parent)) + config |= CC_DEEP_SLEEP_ENA; + + return config; +} + /** * ab8500_fg_coulomb_counter() - enable coulomb counter * @di: pointer to the ab8500_fg structure @@ -481,7 +491,7 @@ static int ab8500_fg_coulomb_counter(struct ab8500_fg *di, bool enable) /* Start the CC */ ret = abx500_set_register_interruptible(di->dev, AB8500_RTC, AB8500_RTC_CC_CONF_REG, - (CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA)); + ab8500_fg_cc_config(di)); if (ret) goto cc_err; @@ -555,7 +565,7 @@ int ab8500_fg_inst_curr_start(struct ab8500_fg *di) /* Start the CC */ ret = abx500_set_register_interruptible(di->dev, AB8500_RTC, AB8500_RTC_CC_CONF_REG, - (CC_DEEP_SLEEP_ENA | CC_PWR_UP_ENA)); + ab8500_fg_cc_config(di)); if (ret) goto fail; } else { @@ -934,9 +944,15 @@ static int ab8500_load_comp_fg_bat_voltage(struct ab8500_fg *di, bool always) int i = 0; int vbat_uv = 0; int rcomp; + int ret; /* Average the instant current to get a stable current measurement */ - ab8500_fg_inst_curr_start(di); + ret = ab8500_fg_inst_curr_start(di); + if (ret) { + dev_err(di->dev, "failed to start instantaneous current measurement\n"); + di->vbat_uv = ab8500_fg_bat_voltage(di); + return di->vbat_uv; + } do { vbat_uv += ab8500_fg_bat_voltage(di); @@ -945,15 +961,14 @@ static int ab8500_load_comp_fg_bat_voltage(struct ab8500_fg *di, bool always) } while (!ab8500_fg_inst_curr_done(di) && i <= WAIT_FOR_INST_CURRENT_MAX); - if (i > WAIT_FOR_INST_CURRENT_MAX) { + ret = ab8500_fg_inst_curr_finalize(di, &di->inst_curr_ua); + if (ret) { dev_err(di->dev, "TIMEOUT: return uncompensated measurement of VBAT\n"); di->vbat_uv = vbat_uv / i; return di->vbat_uv; } - ab8500_fg_inst_curr_finalize(di, &di->inst_curr_ua); - /* * If there is too high current dissipation, the compensation cannot be * trusted so return an error unless we must return something here, as diff --git a/drivers/power/supply/bq24190_charger.c b/drivers/power/supply/bq24190_charger.c index 4bea6fd83c36..a24e433fce1a 100644 --- a/drivers/power/supply/bq24190_charger.c +++ b/drivers/power/supply/bq24190_charger.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -2168,7 +2169,13 @@ static int bq24190_probe(struct i2c_client *client) if (ret < 0) goto out_charger; - enable_irq_wake(client->irq); + ret = devm_device_init_wakeup(dev); + if (ret < 0) + goto out_charger; + + ret = devm_pm_set_wake_irq(dev, client->irq); + if (ret < 0) + goto out_charger; pm_runtime_put_autosuspend(dev); @@ -2242,25 +2249,6 @@ static __maybe_unused int bq24190_runtime_resume(struct device *dev) return 0; } -static __maybe_unused int bq24190_pm_suspend(struct device *dev) -{ - struct i2c_client *client = to_i2c_client(dev); - struct bq24190_dev_info *bdi = i2c_get_clientdata(client); - int error; - - error = pm_runtime_resume_and_get(bdi->dev); - if (error < 0) - dev_warn(bdi->dev, "pm_runtime_get failed: %i\n", error); - - bq24190_register_reset(bdi); - - if (error >= 0) { - pm_runtime_put_autosuspend(bdi->dev); - } - - return 0; -} - static __maybe_unused int bq24190_pm_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); @@ -2274,7 +2262,14 @@ static __maybe_unused int bq24190_pm_resume(struct device *dev) if (error < 0) dev_warn(bdi->dev, "pm_runtime_get failed: %i\n", error); - bq24190_register_reset(bdi); + /* + * The chip kept its configuration through the sleep: it is in host + * mode with the i2c watchdog off, so nothing expired and nothing was + * reset. Do not reset it here either -- a userspace setting such as + * EN_HIZ or IINLIM would otherwise be silently lost on every resume. + * Re-applying the probe-time configuration is idempotent and cheap, + * and covers a part that did somehow fall back to default mode. + */ bq24190_set_config(bdi); bq24190_read(bdi, BQ24190_REG_SS, &bdi->ss_reg); @@ -2293,7 +2288,7 @@ static __maybe_unused int bq24190_pm_resume(struct device *dev) static const struct dev_pm_ops bq24190_pm_ops = { SET_RUNTIME_PM_OPS(bq24190_runtime_suspend, bq24190_runtime_resume, NULL) - SET_SYSTEM_SLEEP_PM_OPS(bq24190_pm_suspend, bq24190_pm_resume) + SET_SYSTEM_SLEEP_PM_OPS(NULL, bq24190_pm_resume) }; static const struct i2c_device_id bq24190_i2c_ids[] = { diff --git a/drivers/power/supply/bq2515x_charger.c b/drivers/power/supply/bq2515x_charger.c index 0208358ebbe4..c2b17562cf8b 100644 --- a/drivers/power/supply/bq2515x_charger.c +++ b/drivers/power/supply/bq2515x_charger.c @@ -420,7 +420,7 @@ static int bq2515x_get_battery_current_now(struct bq2515x_device *bq2515x) BQ2515X_ICHG_DIVISOR); } -static bool bq2515x_get_charge_disable(struct bq2515x_device *bq2515x) +static int bq2515x_get_charge_disable(struct bq2515x_device *bq2515x) { int ret; int ce_pin; @@ -428,6 +428,8 @@ static bool bq2515x_get_charge_disable(struct bq2515x_device *bq2515x) int charger_disable; ce_pin = gpiod_get_value_cansleep(bq2515x->ce_gpio); + if (ce_pin < 0) + return ce_pin; ret = regmap_read(bq2515x->regmap, BQ2515X_ICCTRL2, &icctrl2); if (ret) @@ -435,10 +437,7 @@ static bool bq2515x_get_charge_disable(struct bq2515x_device *bq2515x) charger_disable = icctrl2 & BQ2515X_CHARGER_DISABLE; - if (charger_disable || ce_pin) - return true; - - return false; + return charger_disable || ce_pin; } static int bq2515x_set_charge_disable(struct bq2515x_device *bq2515x, int val) @@ -615,7 +614,11 @@ static int bq2515x_charging_status(struct bq2515x_device *bq2515x, else status1_no_fault = false; - ce_status = (!bq2515x_get_charge_disable(bq2515x)); + ret = bq2515x_get_charge_disable(bq2515x); + if (ret < 0) + return ret; + + ce_status = !ret; /* * If there are no faults and charging is enabled, then status is diff --git a/drivers/power/supply/bq257xx_charger.c b/drivers/power/supply/bq257xx_charger.c index b735bb02a8e0..ab3519454193 100644 --- a/drivers/power/supply/bq257xx_charger.c +++ b/drivers/power/supply/bq257xx_charger.c @@ -1055,7 +1055,7 @@ static void bq257xx_external_power_changed(struct power_supply *psy) pdata->chip->bq257xx_get_state(pdata); - pdata->supplied = power_supply_am_i_supplied(pdata->charger); + pdata->supplied = power_supply_am_i_supplied(psy); if (pdata->supplied < 0) return; diff --git a/drivers/power/supply/generic-adc-battery.c b/drivers/power/supply/generic-adc-battery.c index 937b84e04ba2..7a1f8188bd27 100644 --- a/drivers/power/supply/generic-adc-battery.c +++ b/drivers/power/supply/generic-adc-battery.c @@ -243,6 +243,9 @@ static int gab_probe(struct platform_device *pdev) return dev_err_probe(&pdev->dev, ret, "Failed to register delayed work\n"); adc_bat->charge_finished = devm_gpiod_get_optional(&pdev->dev, "charged", GPIOD_IN); + if (IS_ERR(adc_bat->charge_finished)) + return dev_err_probe(&pdev->dev, PTR_ERR(adc_bat->charge_finished), + "failed to get charged GPIO\n"); if (adc_bat->charge_finished) { int irq; diff --git a/drivers/power/supply/gpio-charger.c b/drivers/power/supply/gpio-charger.c index 2504190eba82..1dad49acc424 100644 --- a/drivers/power/supply/gpio-charger.c +++ b/drivers/power/supply/gpio-charger.c @@ -101,7 +101,10 @@ static int gpio_charger_get_property(struct power_supply *psy, val->intval = gpiod_get_value_cansleep(gpio_charger->gpiod); break; case POWER_SUPPLY_PROP_STATUS: - if (gpiod_get_value_cansleep(gpio_charger->charge_status)) + /* Without input power the battery discharges, whatever the status pin says */ + if (gpio_charger->gpiod && !gpiod_get_value_cansleep(gpio_charger->gpiod)) + val->intval = POWER_SUPPLY_STATUS_DISCHARGING; + else if (gpiod_get_value_cansleep(gpio_charger->charge_status)) val->intval = POWER_SUPPLY_STATUS_CHARGING; else val->intval = POWER_SUPPLY_STATUS_NOT_CHARGING; diff --git a/drivers/power/supply/mm8013.c b/drivers/power/supply/mm8013.c index 819667a27cad..c38f48338d42 100644 --- a/drivers/power/supply/mm8013.c +++ b/drivers/power/supply/mm8013.c @@ -293,6 +293,7 @@ static const struct of_device_id mm8013_match_table[] = { { .compatible = "mitsumi,mm8013" }, {} }; +MODULE_DEVICE_TABLE(of, mm8013_match_table); static struct i2c_driver mm8013_i2c_driver = { .probe = mm8013_probe, diff --git a/drivers/power/supply/qcom_battmgr.c b/drivers/power/supply/qcom_battmgr.c index 97c8501c2996..636d6f6acecc 100644 --- a/drivers/power/supply/qcom_battmgr.c +++ b/drivers/power/supply/qcom_battmgr.c @@ -830,6 +830,7 @@ static const enum power_supply_property x1e80100_bat_props[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_TECHNOLOGY, + POWER_SUPPLY_PROP_CAPACITY, POWER_SUPPLY_PROP_CYCLE_COUNT, POWER_SUPPLY_PROP_VOLTAGE_MAX_DESIGN, POWER_SUPPLY_PROP_VOLTAGE_NOW, @@ -975,7 +976,7 @@ static const u8 sm8350_usb_prop_map[] = { [POWER_SUPPLY_PROP_CURRENT_NOW] = USB_CURR_NOW, [POWER_SUPPLY_PROP_CURRENT_MAX] = USB_CURR_MAX, [POWER_SUPPLY_PROP_INPUT_CURRENT_LIMIT] = USB_INPUT_CURR_LIMIT, - [POWER_SUPPLY_PROP_USB_TYPE] = USB_TYPE, + [POWER_SUPPLY_PROP_USB_TYPE] = USB_ADAP_TYPE, }; static int qcom_battmgr_usb_sm8350_update(struct qcom_battmgr *battmgr, @@ -1276,6 +1277,7 @@ static void qcom_battmgr_sc8280xp_callback(struct qcom_battmgr *battmgr, size_t len) { unsigned int opcode = le32_to_cpu(resp->hdr.opcode); + unsigned int power_state; unsigned int source; unsigned int state; size_t payload_len = len - sizeof(struct pmic_glink_hdr); @@ -1326,19 +1328,24 @@ static void qcom_battmgr_sc8280xp_callback(struct qcom_battmgr *battmgr, return; } + battmgr->status.capacity = le32_to_cpu(resp->status.capacity) * 1000; + battmgr->status.power_now = le32_to_cpu(resp->status.rate) * 1000; + battmgr->status.voltage_now = le32_to_cpu(resp->status.battery_voltage) * 1000; + battmgr->status.temperature = qcom_battmgr_sc8280xp_convert_temp(le32_to_cpu(resp->status.temperature)); + state = le32_to_cpu(resp->status.battery_state); + power_state = le32_to_cpu(resp->status.power_state); if (state & BIT(0)) battmgr->status.status = POWER_SUPPLY_STATUS_DISCHARGING; else if (state & BIT(1)) battmgr->status.status = POWER_SUPPLY_STATUS_CHARGING; + else if ((power_state & BIT(0)) && + battmgr->info.last_full_capacity && + battmgr->status.capacity >= battmgr->info.last_full_capacity) + battmgr->status.status = POWER_SUPPLY_STATUS_FULL; else battmgr->status.status = POWER_SUPPLY_STATUS_NOT_CHARGING; - battmgr->status.capacity = le32_to_cpu(resp->status.capacity) * 1000; - battmgr->status.power_now = le32_to_cpu(resp->status.rate) * 1000; - battmgr->status.voltage_now = le32_to_cpu(resp->status.battery_voltage) * 1000; - battmgr->status.temperature = qcom_battmgr_sc8280xp_convert_temp(le32_to_cpu(resp->status.temperature)); - source = le32_to_cpu(resp->status.charging_source); qcom_battmgr_sc8280xp_set_online(battmgr->ac_psy, &battmgr->ac.online, source == BATTMGR_CHARGING_SOURCE_AC); @@ -1533,7 +1540,7 @@ static void qcom_battmgr_sm8350_callback(struct qcom_battmgr *battmgr, case USB_INPUT_CURR_LIMIT: battmgr->usb.current_limit = le32_to_cpu(resp->intval.value); break; - case USB_TYPE: + case USB_ADAP_TYPE: battmgr->usb.usb_type = le32_to_cpu(resp->intval.value); break; default: diff --git a/drivers/power/supply/s2mu005-battery.c b/drivers/power/supply/s2mu005-battery.c index 53de6605b492..a76154e5a091 100644 --- a/drivers/power/supply/s2mu005-battery.c +++ b/drivers/power/supply/s2mu005-battery.c @@ -262,7 +262,7 @@ static int s2mu005_fg_i2c_probe(struct i2c_client *client) ret = devm_mutex_init(dev, &priv->monout_mutex); if (ret) - dev_err_probe(dev, ret, "failed to initialize MONOUT mutex\n"); + return dev_err_probe(dev, ret, "failed to initialize MONOUT mutex\n"); psy_desc = device_get_match_data(dev); @@ -277,7 +277,7 @@ static int s2mu005_fg_i2c_probe(struct i2c_client *client) s2mu005_handle_irq, IRQF_ONESHOT, psy_desc->name, priv); if (ret) - dev_err_probe(dev, ret, "failed to request IRQ\n"); + return dev_err_probe(dev, ret, "failed to request IRQ\n"); return 0; } diff --git a/drivers/pps/generators/pps_gen.c b/drivers/pps/generators/pps_gen.c index 452cc12a96f2..474e17c36458 100644 --- a/drivers/pps/generators/pps_gen.c +++ b/drivers/pps/generators/pps_gen.c @@ -103,11 +103,14 @@ static long pps_gen_cdev_ioctl(struct file *file, dev_dbg(&pps_gen->dev, "PPS_GEN_FETCHEVENT\n"); ret = wait_event_interruptible(pps_gen->queue, - ev != pps_gen->last_ev); + ev != pps_gen->last_ev || + !READ_ONCE(pps_gen->info)); if (ret == -ERESTARTSYS) { dev_dbg(&pps_gen->dev, "pending signal caught\n"); return -EINTR; } + if (!READ_ONCE(pps_gen->info)) + return -ENODEV; spin_lock_irq(&pps_gen->lock); info.sequence = pps_gen->sequence; @@ -238,9 +241,12 @@ static void pps_gen_unregister_cdev(struct pps_gen_device *pps_gen) pps_gen->info->enable(pps_gen, false); pps_gen->enabled = false; } - pps_gen->info = NULL; + WRITE_ONCE(pps_gen->info, NULL); } + /* Wake up the readers in PPS_GEN_FETCHEVENT, they fail now as well */ + wake_up_interruptible_all(&pps_gen->queue); + put_device(&pps_gen->dev); } diff --git a/drivers/ptp/ptp_qoriq.c b/drivers/ptp/ptp_qoriq.c index 76272e5ac5b8..bcd29104effe 100644 --- a/drivers/ptp/ptp_qoriq.c +++ b/drivers/ptp/ptp_qoriq.c @@ -355,6 +355,7 @@ static const struct ptp_clock_info ptp_qoriq_caps = { .n_per_out = 0, .n_pins = 0, .pps = 1, + .supported_extts_flags = PTP_RISING_EDGE | PTP_STRICT_FLAGS, .adjfine = ptp_qoriq_adjfine, .adjtime = ptp_qoriq_adjtime, .gettime64 = ptp_qoriq_gettime, diff --git a/drivers/pwm/core.c b/drivers/pwm/core.c index 2a050ff4608b..4c6d716e5fde 100644 --- a/drivers/pwm/core.c +++ b/drivers/pwm/core.c @@ -2389,6 +2389,7 @@ static const struct file_operations pwm_cdev_fileops = { .release = pwm_cdev_release, .owner = THIS_MODULE, .unlocked_ioctl = pwm_cdev_ioctl, + .compat_ioctl = compat_ptr_ioctl, }; static dev_t pwm_devt; diff --git a/drivers/pwm/pwm-ipq.c b/drivers/pwm/pwm-ipq.c index 6b7aec566f7e..3e1231b212b1 100644 --- a/drivers/pwm/pwm-ipq.c +++ b/drivers/pwm/pwm-ipq.c @@ -186,7 +186,7 @@ static int ipq_pwm_get_state(struct pwm_chip *chip, struct pwm_device *pwm, state->period = DIV64_U64_ROUND_UP(effective_div * NSEC_PER_SEC, ipq_chip->clk_rate); - hi_div = hi_dur * (pre_div + 1); + hi_div = (u64)hi_dur * (pre_div + 1); state->duty_cycle = DIV64_U64_ROUND_UP(hi_div * NSEC_PER_SEC, ipq_chip->clk_rate); diff --git a/drivers/pwm/pwm-loongson.c b/drivers/pwm/pwm-loongson.c index f2fb35b7af2b..98c809bde2b3 100644 --- a/drivers/pwm/pwm-loongson.c +++ b/drivers/pwm/pwm-loongson.c @@ -99,6 +99,7 @@ static void pwm_loongson_disable(struct pwm_chip *chip, struct pwm_device *pwm) struct pwm_loongson_ddata *ddata = to_pwm_loongson_ddata(chip); val = pwm_loongson_readl(ddata, LOONGSON_PWM_REG_CTRL); + val |= LOONGSON_PWM_CTRL_REG_RST; val &= ~LOONGSON_PWM_CTRL_REG_EN; pwm_loongson_writel(ddata, val, LOONGSON_PWM_REG_CTRL); } @@ -109,6 +110,7 @@ static int pwm_loongson_enable(struct pwm_chip *chip, struct pwm_device *pwm) struct pwm_loongson_ddata *ddata = to_pwm_loongson_ddata(chip); val = pwm_loongson_readl(ddata, LOONGSON_PWM_REG_CTRL); + val &= ~LOONGSON_PWM_CTRL_REG_RST; val |= LOONGSON_PWM_CTRL_REG_EN; pwm_loongson_writel(ddata, val, LOONGSON_PWM_REG_CTRL); diff --git a/drivers/pwm/pwm-lp3943.c b/drivers/pwm/pwm-lp3943.c index 10537e74be28..e42af9007546 100644 --- a/drivers/pwm/pwm-lp3943.c +++ b/drivers/pwm/pwm-lp3943.c @@ -38,6 +38,9 @@ lp3943_pwm_request_map(struct lp3943_pwm *lp3943_pwm, int hwpwm) struct lp3943_pwm_map *pwm_map = &lp3943_pwm->pwm_map[hwpwm]; int i, offset; + if (!pdata->pwms[hwpwm]) + return ERR_PTR(-ENODEV); + pwm_map->output = pdata->pwms[hwpwm]->output; pwm_map->num_outputs = pdata->pwms[hwpwm]->num_outputs; diff --git a/drivers/pwm/pwm-mtk-disp.c b/drivers/pwm/pwm-mtk-disp.c index b5409e15dac8..56d10cde5b46 100644 --- a/drivers/pwm/pwm-mtk-disp.c +++ b/drivers/pwm/pwm-mtk-disp.c @@ -210,9 +210,9 @@ static int mtk_disp_pwm_get_state(struct pwm_chip *chip, period = FIELD_GET(PWM_PERIOD_MASK, con1); /* * period has 12 bits, clk_div 11 and NSEC_PER_SEC has 30, - * so period * (clk_div + 1) * NSEC_PER_SEC doesn't overflow. + * so (period + 1) * (clk_div + 1) * NSEC_PER_SEC doesn't overflow. */ - state->period = DIV64_U64_ROUND_UP(period * (clk_div + 1) * NSEC_PER_SEC, rate); + state->period = DIV64_U64_ROUND_UP((period + 1) * (clk_div + 1) * NSEC_PER_SEC, rate); high_width = FIELD_GET(PWM_HIGH_WIDTH_MASK, con1); state->duty_cycle = DIV64_U64_ROUND_UP(high_width * (clk_div + 1) * NSEC_PER_SEC, rate); diff --git a/drivers/pwm/pwm-renesas-tpu.c b/drivers/pwm/pwm-renesas-tpu.c index 140fd0bcb93f..e35f2e14777d 100644 --- a/drivers/pwm/pwm-renesas-tpu.c +++ b/drivers/pwm/pwm-renesas-tpu.c @@ -149,10 +149,14 @@ static int tpu_pwm_timer_start(struct tpu_pwm_device *tpd) if (!tpd->timer_on) { /* Wake up device and enable clock. */ - pm_runtime_get_sync(&tpd->tpu->pdev->dev); + ret = pm_runtime_resume_and_get(&tpd->tpu->pdev->dev); + if (ret < 0) + return ret; + ret = clk_prepare_enable(tpd->tpu->clk); if (ret) { dev_err(&tpd->tpu->pdev->dev, "cannot enable clock\n"); + pm_runtime_put(&tpd->tpu->pdev->dev); return ret; } tpd->timer_on = true; @@ -382,15 +386,21 @@ static int tpu_pwm_enable(struct pwm_chip *chip, struct pwm_device *pwm) return 0; } -static void tpu_pwm_disable(struct pwm_chip *chip, struct pwm_device *pwm) +static int tpu_pwm_disable(struct pwm_chip *chip, struct pwm_device *pwm) { struct tpu_device *tpu = to_tpu_device(chip); struct tpu_pwm_device *tpd = &tpu->tpd[pwm->hwpwm]; + int ret; /* The timer must be running to modify the pin output configuration. */ - tpu_pwm_timer_start(tpd); + ret = tpu_pwm_timer_start(tpd); + if (ret < 0) + return ret; + tpu_pwm_set_pin(tpd, TPU_PIN_INACTIVE); tpu_pwm_timer_stop(tpd); + + return 0; } static int tpu_pwm_apply(struct pwm_chip *chip, struct pwm_device *pwm, @@ -401,7 +411,10 @@ static int tpu_pwm_apply(struct pwm_chip *chip, struct pwm_device *pwm, if (state->polarity != pwm->state.polarity) { if (enabled) { - tpu_pwm_disable(chip, pwm); + err = tpu_pwm_disable(chip, pwm); + if (err) + return err; + enabled = false; } @@ -412,7 +425,7 @@ static int tpu_pwm_apply(struct pwm_chip *chip, struct pwm_device *pwm, if (!state->enabled) { if (enabled) - tpu_pwm_disable(chip, pwm); + return tpu_pwm_disable(chip, pwm); return 0; } diff --git a/drivers/regulator/ab8500.c b/drivers/regulator/ab8500.c index 3705c98b0713..e4c3502c8dbc 100644 --- a/drivers/regulator/ab8500.c +++ b/drivers/regulator/ab8500.c @@ -162,6 +162,7 @@ struct ab8500_shared_mode { * @update_bank: bank to control on/off * @update_reg: register to control on/off * @update_mask: mask to enable/disable and set mode of regulator + * @enable_mask: optional mask for an enable bit separate from the mode bit * @update_val: bits holding the regulator current mode * @update_val_idle: bits to enable the regulator in idle (low power) mode * @update_val_normal: bits to enable the regulator in normal (high power) mode @@ -173,6 +174,7 @@ struct ab8500_shared_mode { * @voltage_bank: bank to control regulator voltage * @voltage_reg: register to control regulator voltage * @voltage_mask: mask to control regulator voltage + * @expand_register: additional register used to select an extra voltage */ struct ab8500_regulator_info { struct device *dev; @@ -182,6 +184,7 @@ struct ab8500_regulator_info { u8 update_bank; u8 update_reg; u8 update_mask; + u8 enable_mask; u8 update_val; u8 update_val_idle; u8 update_val_normal; @@ -193,6 +196,12 @@ struct ab8500_regulator_info { u8 voltage_bank; u8 voltage_reg; u8 voltage_mask; + struct { + u8 voltage_limit; + u8 voltage_bank; + u8 voltage_reg; + u8 voltage_mask; + } expand_register; }; /* voltage tables for the vauxn/vintcore supplies */ @@ -226,6 +235,18 @@ static const unsigned int ldo_vaux3_voltages[] = { 2910000, }; +static const unsigned int ldo_vaux3_ab8505_voltages[] = { + 1200000, + 1500000, + 1800000, + 2100000, + 2500000, + 2750000, + 2790000, + 2910000, + 3050000, +}; + static const unsigned int ldo_vaux56_voltages[] = { 1800000, 1050000, @@ -247,6 +268,17 @@ static const unsigned int ldo_vintcore_voltages[] = { 1350000, }; +static const unsigned int ldo_vintcore_ab8505_voltages[] = { + 1200000, + 1225000, + 1250000, + 1275000, + 1300000, + 1325000, + 1350000, + 1350000, +}; + static const unsigned int fixed_1200000_voltage[] = { 1200000, }; @@ -264,13 +296,13 @@ static const unsigned int fixed_2050000_voltage[] = { }; static const unsigned int ldo_vana_voltages[] = { + 1200000, 1050000, 1075000, 1100000, 1125000, 1150000, 1175000, - 1200000, 1225000, }; @@ -347,6 +379,7 @@ static int ab8500_regulator_is_enabled(struct regulator_dev *rdev) { int ret; struct ab8500_regulator_info *info = rdev_get_drvdata(rdev); + u8 enable_mask; u8 regval; if (info == NULL) { @@ -362,13 +395,15 @@ static int ab8500_regulator_is_enabled(struct regulator_dev *rdev) return ret; } + enable_mask = info->enable_mask ? info->enable_mask : info->update_mask; + dev_vdbg(rdev_get_dev(rdev), "%s-is_enabled (bank, reg, mask, value): 0x%x, 0x%x, 0x%x," " 0x%x\n", info->desc.name, info->update_bank, info->update_reg, - info->update_mask, regval); + enable_mask, regval); - if (regval & info->update_mask) + if (regval & enable_mask) return 1; else return 0; @@ -398,7 +433,7 @@ static unsigned int ab8500_regulator_get_optimum_mode( static int ab8500_regulator_set_mode(struct regulator_dev *rdev, unsigned int mode) { - int ret = 0; + int enabled, ret = 0; u8 bank, reg, mask, val; bool lp_mode_req = false; struct ab8500_regulator_info *info = rdev_get_drvdata(rdev); @@ -455,7 +490,17 @@ static int ab8500_regulator_set_mode(struct regulator_dev *rdev, goto out_unlock; } - if (info->mode_mask || ab8500_regulator_is_enabled(rdev)) { + if (info->mode_mask) { + enabled = 1; + } else { + enabled = ab8500_regulator_is_enabled(rdev); + if (enabled < 0) { + ret = enabled; + goto out_unlock; + } + } + + if (enabled) { ret = abx500_mask_and_set_register_interruptible(info->dev, bank, reg, mask, val); if (ret < 0) { @@ -593,6 +638,64 @@ static int ab8500_regulator_set_voltage_sel(struct regulator_dev *rdev, return ret; } +static int ab8500_regulator_get_voltage_sel_expand(struct regulator_dev *rdev) +{ + struct ab8500_regulator_info *info = rdev_get_drvdata(rdev); + u8 regval; + int ret; + + if (!info) + return -EINVAL; + + ret = abx500_get_register_interruptible(info->dev, + info->expand_register.voltage_bank, + info->expand_register.voltage_reg, ®val); + if (ret < 0) { + dev_err(rdev_get_dev(rdev), + "couldn't read voltage expand reg for regulator\n"); + return ret; + } + + if (regval & info->expand_register.voltage_mask) + return info->expand_register.voltage_limit; + + return ab8500_regulator_get_voltage_sel(rdev); +} + +static int ab8500_regulator_set_voltage_sel_expand(struct regulator_dev *rdev, + unsigned int selector) +{ + struct ab8500_regulator_info *info = rdev_get_drvdata(rdev); + u8 regval; + int ret; + + if (!info) + return -EINVAL; + + if (selector > info->expand_register.voltage_limit) + return -EINVAL; + + if (selector < info->expand_register.voltage_limit) { + ret = ab8500_regulator_set_voltage_sel(rdev, selector); + if (ret < 0) + return ret; + + regval = 0; + } else { + regval = info->expand_register.voltage_mask; + } + + ret = abx500_mask_and_set_register_interruptible(info->dev, + info->expand_register.voltage_bank, + info->expand_register.voltage_reg, + info->expand_register.voltage_mask, regval); + if (ret < 0) + dev_err(rdev_get_dev(rdev), + "couldn't set voltage expand reg for regulator\n"); + + return ret; +} + static const struct regulator_ops ab8500_regulator_volt_mode_ops = { .enable = ab8500_regulator_enable, .disable = ab8500_regulator_disable, @@ -605,6 +708,18 @@ static const struct regulator_ops ab8500_regulator_volt_mode_ops = { .list_voltage = regulator_list_voltage_table, }; +static const struct regulator_ops ab8500_regulator_volt_mode_expand_ops = { + .enable = ab8500_regulator_enable, + .disable = ab8500_regulator_disable, + .is_enabled = ab8500_regulator_is_enabled, + .get_optimum_mode = ab8500_regulator_get_optimum_mode, + .set_mode = ab8500_regulator_set_mode, + .get_mode = ab8500_regulator_get_mode, + .get_voltage_sel = ab8500_regulator_get_voltage_sel_expand, + .set_voltage_sel = ab8500_regulator_set_voltage_sel_expand, + .list_voltage = regulator_list_voltage_table, +}; + static const struct regulator_ops ab8500_regulator_volt_ops = { .enable = ab8500_regulator_enable, .disable = ab8500_regulator_disable, @@ -733,6 +848,7 @@ static struct ab8500_regulator_info .update_bank = 0x03, .update_reg = 0x80, .update_mask = 0x44, + .enable_mask = 0x04, .update_val = 0x44, .update_val_idle = 0x44, .update_val_normal = 0x04, @@ -761,6 +877,7 @@ static struct ab8500_regulator_info .update_bank = 0x03, .update_reg = 0x80, .update_mask = 0x82, + .enable_mask = 0x02, .update_val = 0x02, .update_val_idle = 0x82, .update_val_normal = 0x02, @@ -908,12 +1025,12 @@ static struct ab8500_regulator_info [AB8505_LDO_AUX3] = { .desc = { .name = "LDO-AUX3", - .ops = &ab8500_regulator_volt_mode_ops, + .ops = &ab8500_regulator_volt_mode_expand_ops, .type = REGULATOR_VOLTAGE, .id = AB8505_LDO_AUX3, .owner = THIS_MODULE, - .n_voltages = ARRAY_SIZE(ldo_vaux3_voltages), - .volt_table = ldo_vaux3_voltages, + .n_voltages = ARRAY_SIZE(ldo_vaux3_ab8505_voltages), + .volt_table = ldo_vaux3_ab8505_voltages, }, .load_lp_uA = 5000, .update_bank = 0x04, @@ -925,6 +1042,12 @@ static struct ab8500_regulator_info .voltage_bank = 0x04, .voltage_reg = 0x21, .voltage_mask = 0x07, + .expand_register = { + .voltage_limit = 8, + .voltage_bank = 0x04, + .voltage_reg = 0x01, + .voltage_mask = 0x10, + }, }, [AB8505_LDO_AUX4] = { .desc = { @@ -964,6 +1087,7 @@ static struct ab8500_regulator_info .update_bank = 0x01, .update_reg = 0x55, .update_mask = 0x18, + .enable_mask = 0x10, .update_val = 0x10, .update_val_idle = 0x18, .update_val_normal = 0x10, @@ -986,6 +1110,7 @@ static struct ab8500_regulator_info .update_bank = 0x01, .update_reg = 0x56, .update_mask = 0x18, + .enable_mask = 0x10, .update_val = 0x10, .update_val_idle = 0x18, .update_val_normal = 0x10, @@ -1000,13 +1125,14 @@ static struct ab8500_regulator_info .type = REGULATOR_VOLTAGE, .id = AB8505_LDO_INTCORE, .owner = THIS_MODULE, - .n_voltages = ARRAY_SIZE(ldo_vintcore_voltages), - .volt_table = ldo_vintcore_voltages, + .n_voltages = ARRAY_SIZE(ldo_vintcore_ab8505_voltages), + .volt_table = ldo_vintcore_ab8505_voltages, }, .load_lp_uA = 5000, .update_bank = 0x03, .update_reg = 0x80, .update_mask = 0x44, + .enable_mask = 0x04, .update_val = 0x04, .update_val_idle = 0x44, .update_val_normal = 0x04, @@ -1035,6 +1161,7 @@ static struct ab8500_regulator_info .update_bank = 0x03, .update_reg = 0x80, .update_mask = 0x82, + .enable_mask = 0x02, .update_val = 0x02, .update_val_idle = 0x82, .update_val_normal = 0x02, @@ -1677,9 +1804,14 @@ static int ab8500_regulator_register(struct platform_device *pdev, config.driver_data = info; config.of_node = np; - /* fix for hardware before ab8500v2.0 */ - if (is_ab8500_1p1_or_earlier(ab8500)) { - if (info->desc.id == AB8500_LDO_AUX3) { + /* Handle the different VAUX3 implementations in early AB8500 cuts. */ + if (info->desc.id == AB8500_LDO_AUX3) { + if (is_ab8500_1p0_or_earlier(ab8500)) { + info->desc.ops = &ab8500_regulator_mode_ops; + info->desc.n_voltages = 1; + info->desc.volt_table = fixed_1200000_voltage; + info->voltage_mask = 0; + } else if (is_ab8500_1p1_or_earlier(ab8500)) { info->desc.n_voltages = ARRAY_SIZE(ldo_vauxn_voltages); info->desc.volt_table = ldo_vauxn_voltages; diff --git a/drivers/regulator/fixed.c b/drivers/regulator/fixed.c index 417d282dd4ed..faa82f30eb1f 100644 --- a/drivers/regulator/fixed.c +++ b/drivers/regulator/fixed.c @@ -28,6 +28,7 @@ #include #include #include +#include struct fixed_voltage_data { struct regulator_desc desc; @@ -225,6 +226,9 @@ static int reg_fixed_voltage_probe(struct platform_device *pdev) enum gpiod_flags gflags; int ret; + if (!pdev->dev.of_node && strcmp(pdev->name, "reg-fixed-voltage")) + return -ENODEV; + drvdata = devm_kzalloc(&pdev->dev, sizeof(struct fixed_voltage_data), GFP_KERNEL); if (!drvdata) diff --git a/drivers/regulator/irq_helpers.c b/drivers/regulator/irq_helpers.c index 5b3cfac28667..cdbd170d2b15 100644 --- a/drivers/regulator/irq_helpers.c +++ b/drivers/regulator/irq_helpers.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include "internal.h" @@ -27,6 +28,7 @@ struct regulator_irq { int irq; int retry_cnt; struct delayed_work isr_work; + struct workqueue_struct *wq; }; /* @@ -145,12 +147,7 @@ static void regulator_notifier_isr_work(struct work_struct *work) return; reschedule: - if (!d->high_prio) - mod_delayed_work(system_dfl_wq, &h->isr_work, - msecs_to_jiffies(tmo)); - else - mod_delayed_work(system_highpri_wq, &h->isr_work, - msecs_to_jiffies(tmo)); + mod_delayed_work(h->wq, &h->isr_work, msecs_to_jiffies(tmo)); } static irqreturn_t regulator_notifier_isr(int irq, void *data) @@ -248,13 +245,8 @@ static irqreturn_t regulator_notifier_isr(int irq, void *data) } if (d->irq_off_ms) { - if (!d->high_prio) - schedule_delayed_work(&h->isr_work, - msecs_to_jiffies(d->irq_off_ms)); - else - mod_delayed_work(system_highpri_wq, - &h->isr_work, - msecs_to_jiffies(d->irq_off_ms)); + mod_delayed_work(h->wq, &h->isr_work, + msecs_to_jiffies(d->irq_off_ms)); } return IRQ_HANDLED; @@ -363,13 +355,25 @@ void *regulator_irq_helper(struct device *dev, init_rdev_errors(h); - if (h->desc.irq_off_ms) + if (h->desc.irq_off_ms) { + if (h->desc.high_prio) { + h->wq = alloc_workqueue("regulator_irq_highpri", + WQ_FREEZABLE | WQ_HIGHPRI, 0); + if (!h->wq) + return ERR_PTR(-ENOMEM); + } else { + h->wq = system_freezable_wq; + } + INIT_DELAYED_WORK(&h->isr_work, regulator_notifier_isr_work); + } ret = request_threaded_irq(h->irq, NULL, regulator_notifier_isr, IRQF_ONESHOT | irq_flags, h->desc.name, h); if (ret) { dev_err(dev, "Failed to request IRQ %d\n", irq); + if (h->desc.irq_off_ms && h->desc.high_prio) + destroy_workqueue(h->wq); return ERR_PTR(ret); } @@ -393,8 +397,11 @@ void regulator_irq_helper_cancel(void **handle) struct regulator_irq *h = *handle; free_irq(h->irq, h); - if (h->desc.irq_off_ms) + if (h->desc.irq_off_ms) { cancel_delayed_work_sync(&h->isr_work); + if (h->desc.high_prio) + destroy_workqueue(h->wq); + } h = NULL; } @@ -441,4 +448,3 @@ int regulator_irq_map_event_simple(int irq, struct regulator_irq_data *rid, return 0; } EXPORT_SYMBOL_GPL(regulator_irq_map_event_simple); - diff --git a/drivers/regulator/mp886x.c b/drivers/regulator/mp886x.c index e0b62bc02a1e..537c1a1158ec 100644 --- a/drivers/regulator/mp886x.c +++ b/drivers/regulator/mp886x.c @@ -256,6 +256,7 @@ static int mp886x_regulator_register(struct mp886x_device_info *di, { struct regulator_desc *rdesc = &di->desc; struct regulator_dev *rdev; + int sel; rdesc->name = "mp886x-reg"; rdesc->supply_name = "vin"; @@ -267,7 +268,7 @@ static int mp886x_regulator_register(struct mp886x_device_info *di, rdesc->min_uV = 600000; rdesc->uV_step = 10000; rdesc->vsel_reg = MP886X_VSEL; - rdesc->vsel_mask = 0x3f; + rdesc->vsel_mask = 0x7f; rdesc->ramp_reg = MP886X_SYSCNTLREG1; rdesc->ramp_mask = MP886X_SLEW_MASK; rdesc->ramp_delay_table = di->ci->slew_rates; @@ -277,7 +278,12 @@ static int mp886x_regulator_register(struct mp886x_device_info *di, rdev = devm_regulator_register(di->dev, &di->desc, config); if (IS_ERR(rdev)) return PTR_ERR(rdev); - di->sel = rdesc->ops->get_voltage_sel(rdev); + + sel = rdesc->ops->get_voltage_sel(rdev); + if (sel < 0) + return sel; + di->sel = sel; + return 0; } @@ -311,6 +317,9 @@ static int mp886x_i2c_probe(struct i2c_client *client) if (ret) return ret; + if (di->r[1] == 0) + return -EINVAL; + di->en_gpio = devm_gpiod_get(dev, "enable", GPIOD_OUT_HIGH); if (IS_ERR(di->en_gpio)) return PTR_ERR(di->en_gpio); diff --git a/drivers/regulator/pf1550-regulator.c b/drivers/regulator/pf1550-regulator.c index ceee553a84b2..84f8b187a91b 100644 --- a/drivers/regulator/pf1550-regulator.c +++ b/drivers/regulator/pf1550-regulator.c @@ -49,17 +49,26 @@ static const int pf1550_ldo13_volts[] = { static int pf1550_set_ramp_delay(struct regulator_dev *rdev, int ramp_delay) { int id = rdev_get_id(rdev); - unsigned int ramp_bits = 0; + unsigned int ramp_bits; int ret; if (id > PF1550_VREFDDR) return -EACCES; - if (ramp_delay < 0 || ramp_delay > 6250) + switch (ramp_delay) { + case 0: + /* Ramp control is disabled, so use the fastest rate. */ + ramp_bits = 0; + break; + case 1 ... 3125: + ramp_bits = 1; + break; + case 3126 ... 6250: + ramp_bits = 0; + break; + default: return -EINVAL; - - ramp_delay = 6250 / ramp_delay; - ramp_bits = ramp_delay >> 1; + } ret = regmap_update_bits(rdev->regmap, rdev->desc->vsel_reg + 4, 0x10, ramp_bits << 4); diff --git a/drivers/regulator/qcom-rpmh-regulator.c b/drivers/regulator/qcom-rpmh-regulator.c index 25c14de3cd8b..7db5730240e2 100644 --- a/drivers/regulator/qcom-rpmh-regulator.c +++ b/drivers/regulator/qcom-rpmh-regulator.c @@ -400,7 +400,7 @@ static unsigned int rpmh_regulator_vrm_get_mode(struct regulator_dev *rdev) * This function is used in the regulator_ops for VRM type RPMh regulator * devices. * - * Return: 0 on success, or a negative error number on failure + * Return: the regulator mode to use for the load */ static unsigned int rpmh_regulator_vrm_get_optimum_mode( struct regulator_dev *rdev, int input_uV, int output_uV, int load_uA) diff --git a/drivers/remoteproc/imx_dsp_rproc.c b/drivers/remoteproc/imx_dsp_rproc.c index fd60c67ba8a9..96d619daf3f5 100644 --- a/drivers/remoteproc/imx_dsp_rproc.c +++ b/drivers/remoteproc/imx_dsp_rproc.c @@ -726,14 +726,17 @@ static int imx_dsp_rproc_prepare(struct rproc *rproc) struct device *dev = rproc->dev.parent; int ret; + ret = pm_runtime_resume_and_get(dev); + if (ret < 0) + return ret; + ret = imx_dsp_rproc_add_carveout(priv); if (ret) { dev_err(dev, "failed on imx_dsp_rproc_add_carveout\n"); + pm_runtime_put_sync(dev); return ret; } - pm_runtime_get_sync(dev); - return 0; } diff --git a/drivers/remoteproc/imx_rproc.c b/drivers/remoteproc/imx_rproc.c index 745ce52cd822..ea852ca143bb 100644 --- a/drivers/remoteproc/imx_rproc.c +++ b/drivers/remoteproc/imx_rproc.c @@ -540,6 +540,7 @@ static int imx_rproc_da_to_sys(struct imx_rproc *priv, u64 da, /* parse address translation table */ for (i = 0; i < dcfg->att_size; i++) { const struct imx_rproc_att *att = &dcfg->att[i]; + u64 offset; /* * Ignore entries not belong to current core: @@ -552,9 +553,11 @@ static int imx_rproc_da_to_sys(struct imx_rproc *priv, u64 da, continue; } - if (da >= att->da && da + len < att->da + att->size) { - unsigned int offset = da - att->da; + if (da < att->da) + continue; + offset = da - att->da; + if (offset <= att->size && len <= att->size - offset) { *sys = att->sa + offset; if (is_iomem) *is_iomem = att->flags & ATT_IOMEM; @@ -585,9 +588,14 @@ static void *imx_rproc_da_to_va(struct rproc *rproc, u64 da, size_t len, bool *i return NULL; for (i = 0; i < IMX_RPROC_MEM_MAX; i++) { - if (sys >= priv->mem[i].sys_addr && sys + len < - priv->mem[i].sys_addr + priv->mem[i].size) { - unsigned int offset = sys - priv->mem[i].sys_addr; + u64 offset; + + if (sys < priv->mem[i].sys_addr) + continue; + + offset = sys - priv->mem[i].sys_addr; + if (offset <= priv->mem[i].size && + len <= priv->mem[i].size - offset) { /* __force to make sparse happy with type conversion */ va = (__force void *)(priv->mem[i].cpu_addr + offset); break; diff --git a/drivers/remoteproc/qcom_q6v5_adsp.c b/drivers/remoteproc/qcom_q6v5_adsp.c index 2e5fb5954fa9..46d9169a37f6 100644 --- a/drivers/remoteproc/qcom_q6v5_adsp.c +++ b/drivers/remoteproc/qcom_q6v5_adsp.c @@ -430,7 +430,7 @@ static int adsp_start(struct rproc *rproc) goto disable_adsp_clks; } - ret = qcom_q6v5_wait_for_start(&adsp->q6v5, msecs_to_jiffies(5 * HZ)); + ret = qcom_q6v5_wait_for_start(&adsp->q6v5, msecs_to_jiffies(5000)); if (ret == -ETIMEDOUT) { dev_err(adsp->dev, "start timed out\n"); goto disable_adsp_clks; diff --git a/drivers/remoteproc/remoteproc_core.c b/drivers/remoteproc/remoteproc_core.c index 1ed406714849..263e12f022ea 100644 --- a/drivers/remoteproc/remoteproc_core.c +++ b/drivers/remoteproc/remoteproc_core.c @@ -574,6 +574,9 @@ static int rproc_handle_trace(struct rproc *rproc, void *ptr, /* create the debugfs entry */ trace->tfile = rproc_create_trace_file(name, rproc, trace); + /* keep the name for the diagnostic in rproc_trace_read() */ + strscpy(trace->trace_mem.name, name, sizeof(trace->trace_mem.name)); + list_add_tail(&trace->node, &rproc->traces); rproc->num_traces++; diff --git a/drivers/remoteproc/xlnx_r5_remoteproc.c b/drivers/remoteproc/xlnx_r5_remoteproc.c index c685bb5fa62c..d47fbf143acd 100644 --- a/drivers/remoteproc/xlnx_r5_remoteproc.c +++ b/drivers/remoteproc/xlnx_r5_remoteproc.c @@ -318,6 +318,8 @@ static struct mbox_info *zynqmp_r5_setup_mbox(struct device *cdev) if (!ipi) return NULL; + INIT_WORK(&ipi->mbox_work, handle_event_notified); + mbox_cl = &ipi->mbox_cl; mbox_cl->rx_callback = zynqmp_r5_mb_rx_cb; mbox_cl->tx_block = false; @@ -329,6 +331,7 @@ static struct mbox_info *zynqmp_r5_setup_mbox(struct device *cdev) ipi->tx_chan = mbox_request_channel_byname(mbox_cl, "tx"); if (IS_ERR(ipi->tx_chan)) { ipi->tx_chan = NULL; + cancel_work_sync(&ipi->mbox_work); kfree(ipi); dev_warn(cdev, "mbox tx channel request failed\n"); return NULL; @@ -339,13 +342,12 @@ static struct mbox_info *zynqmp_r5_setup_mbox(struct device *cdev) mbox_free_channel(ipi->tx_chan); ipi->rx_chan = NULL; ipi->tx_chan = NULL; + cancel_work_sync(&ipi->mbox_work); kfree(ipi); dev_warn(cdev, "mbox rx channel request failed\n"); return NULL; } - INIT_WORK(&ipi->mbox_work, handle_event_notified); - return ipi; } @@ -364,6 +366,8 @@ static void zynqmp_r5_free_mbox(struct mbox_info *ipi) ipi->rx_chan = NULL; } + cancel_work_sync(&ipi->mbox_work); + kfree(ipi); } diff --git a/drivers/resctrl/mpam_devices.c b/drivers/resctrl/mpam_devices.c index dd422c56fbb1..aabbe2ad8f1a 100644 --- a/drivers/resctrl/mpam_devices.c +++ b/drivers/resctrl/mpam_devices.c @@ -157,7 +157,7 @@ static void mpam_free_garbage(void) if (iter->pdev) devm_kfree(&iter->pdev->dev, iter->to_free); else - kfree(iter->to_free); + kvfree(iter->to_free); } } @@ -930,9 +930,9 @@ static void mpam_ris_hw_probe(struct mpam_msc_ris *ris) mpam_set_feature(mpam_feat_msmon_mbwu_63counter, props); else mpam_set_feature(mpam_feat_msmon_mbwu_44counter, props); - } else { - mpam_set_feature(mpam_feat_msmon_mbwu_31counter, props); } + + mpam_set_feature(mpam_feat_msmon_mbwu_31counter, props); } } } @@ -1029,12 +1029,6 @@ struct mon_read { bool waited_timeout; }; -static bool mpam_ris_has_mbwu_long_counter(struct mpam_msc_ris *ris) -{ - return (mpam_has_feature(mpam_feat_msmon_mbwu_63counter, &ris->props) || - mpam_has_feature(mpam_feat_msmon_mbwu_44counter, &ris->props)); -} - static u64 mpam_msc_read_mbwu_l(struct mpam_msc *msc) { int retry = 3; @@ -1202,13 +1196,12 @@ static u64 mpam_msmon_overflow_val(enum mpam_device_features type, return overflow_val; } -static void __ris_msmon_read(void *arg) +static void __ris_msmon_read_locked(struct mon_read *m) { u64 now; bool nrdy = false; bool config_mismatch; bool overflow = false; - struct mon_read *m = arg; struct mon_cfg *ctx = m->ctx; bool reset_on_next_read = false; struct mpam_msc_ris *ris = m->ris; @@ -1216,10 +1209,8 @@ static void __ris_msmon_read(void *arg) struct mpam_msc *msc = m->ris->vmsc->msc; u32 mon_sel, ctl_val, flt_val, cur_ctl, cur_flt; - if (!mpam_mon_sel_lock(msc)) { - m->err = -EIO; - return; - } + mpam_mon_sel_lock_held(msc); + mon_sel = FIELD_PREP(MSMON_CFG_MON_SEL_MON_SEL, ctx->mon) | FIELD_PREP(MSMON_CFG_MON_SEL_RIS, ris->ris_idx); mpam_write_monsel_reg(msc, CFG_MON_SEL, mon_sel); @@ -1312,7 +1303,6 @@ static void __ris_msmon_read(void *arg) default: m->err = -EINVAL; } - mpam_mon_sel_unlock(msc); if (nrdy) m->err = -EBUSY; @@ -1323,6 +1313,21 @@ static void __ris_msmon_read(void *arg) *m->val += now; } +static void __ris_msmon_read(void *arg) +{ + struct mon_read *m = arg; + struct mpam_msc *msc = m->ris->vmsc->msc; + + if (!mpam_mon_sel_lock(msc)) { + m->err = -EIO; + return; + } + + __ris_msmon_read_locked(m); + + mpam_mon_sel_unlock(msc); +} + static int _msmon_read(struct mpam_component *comp, struct mon_read *arg) { int err, any_err = 0; @@ -1650,19 +1655,36 @@ static int mpam_restore_mbwu_state(void *_ris) { int i; u64 val; - struct mon_read mwbu_arg; + struct mon_read mbwu_arg; struct mpam_msc_ris *ris = _ris; + struct msmon_mbwu_state *mbwu_state; + struct mpam_msc *msc = ris->vmsc->msc; struct mpam_class *class = ris->vmsc->comp->class; for (i = 0; i < ris->props.num_mbwu_mon; i++) { - if (ris->mbwu_state[i].enabled) { - mwbu_arg.ris = ris; - mwbu_arg.ctx = &ris->mbwu_state[i].cfg; - mwbu_arg.type = mpam_msmon_choose_counter(class); - mwbu_arg.val = &val; + if (WARN_ON_ONCE(!mpam_mon_sel_lock(msc))) + return -EIO; - __ris_msmon_read(&mwbu_arg); + mbwu_state = &ris->mbwu_state[i]; + + if (!mbwu_state->enabled) { + mpam_mon_sel_unlock(msc); + continue; } + + val = 0; + mbwu_arg = (struct mon_read) { + .ris = ris, + .ctx = &mbwu_state->cfg, + .type = mpam_msmon_choose_counter(class), + .val = &val, + }; + + mbwu_state->reset_on_next_read = true; + + __ris_msmon_read_locked(&mbwu_arg); + + mpam_mon_sel_unlock(msc); } return 0; @@ -1674,40 +1696,59 @@ static int mpam_save_mbwu_state(void *arg) int i; u64 val; struct mon_cfg *cfg; + struct mon_read mbwu_arg; u32 cur_flt, cur_ctl, mon_sel; struct mpam_msc_ris *ris = arg; struct msmon_mbwu_state *mbwu_state; struct mpam_msc *msc = ris->vmsc->msc; + struct mpam_class *class = ris->vmsc->comp->class; for (i = 0; i < ris->props.num_mbwu_mon; i++) { - mbwu_state = &ris->mbwu_state[i]; - cfg = &mbwu_state->cfg; - if (WARN_ON_ONCE(!mpam_mon_sel_lock(msc))) return -EIO; + mbwu_state = &ris->mbwu_state[i]; + cfg = &mbwu_state->cfg; + mon_sel = FIELD_PREP(MSMON_CFG_MON_SEL_MON_SEL, i) | FIELD_PREP(MSMON_CFG_MON_SEL_RIS, ris->ris_idx); mpam_write_monsel_reg(msc, CFG_MON_SEL, mon_sel); cur_flt = mpam_read_monsel_reg(msc, CFG_MBWU_FLT); cur_ctl = mpam_read_monsel_reg(msc, CFG_MBWU_CTL); - mpam_write_monsel_reg(msc, CFG_MBWU_CTL, 0); - - if (mpam_ris_has_mbwu_long_counter(ris)) { - val = mpam_msc_read_mbwu_l(msc); - mpam_msc_zero_mbwu_l(msc); - } else { - val = mpam_read_monsel_reg(msc, MBWU); - mpam_write_monsel_reg(msc, MBWU, 0); - } cfg->mon = i; cfg->pmg = FIELD_GET(MSMON_CFG_x_FLT_PMG, cur_flt); cfg->match_pmg = FIELD_GET(MSMON_CFG_x_CTL_MATCH_PMG, cur_ctl); cfg->partid = FIELD_GET(MSMON_CFG_x_FLT_PARTID, cur_flt); - mbwu_state->correction += val; mbwu_state->enabled = FIELD_GET(MSMON_CFG_x_CTL_EN, cur_ctl); + + if (!mbwu_state->enabled) { + mpam_mon_sel_unlock(msc); + continue; + } + + val = 0; + mbwu_arg = (struct mon_read) { + .ris = ris, + .ctx = cfg, + .type = mpam_msmon_choose_counter(class), + .val = &val, + }; + + __ris_msmon_read_locked(&mbwu_arg); + + mbwu_state->reset_on_next_read = true; + if (!mbwu_arg.err) { + /* + * __ris_msmon_read_locked() already included the + * previous correction value. + */ + mbwu_state->correction = val; + } + + mpam_write_monsel_reg(msc, CFG_MBWU_CTL, 0); + mpam_mon_sel_unlock(msc); } @@ -1720,7 +1761,7 @@ static int mpam_save_mbwu_state(void *arg) */ static int mpam_reset_ris(void *arg) { - u16 partid, partid_max; + u16 partid_max; struct mpam_config reset_cfg = {}; struct mpam_msc_ris *ris = arg; @@ -1730,7 +1771,7 @@ static int mpam_reset_ris(void *arg) spin_lock(&partid_max_lock); partid_max = mpam_partid_max; spin_unlock(&partid_max_lock); - for (partid = 0; partid <= partid_max; partid++) + for (u32 partid = 0; partid <= partid_max; partid++) mpam_reprogram_ris_partid(ris, partid, &reset_cfg); return 0; @@ -1777,7 +1818,6 @@ static int __write_config(void *arg) static void mpam_reprogram_msc(struct mpam_msc *msc) { - u16 partid; bool reset; struct mpam_config *cfg; struct mpam_msc_ris *ris; @@ -1801,7 +1841,7 @@ static void mpam_reprogram_msc(struct mpam_msc *msc) arg.comp = ris->vmsc->comp; arg.ris = ris; reset = true; - for (partid = 0; partid <= mpam_partid_max; partid++) { + for (u32 partid = 0; partid <= mpam_partid_max; partid++) { cfg = &ris->vmsc->comp->cfg[partid]; if (!bitmap_empty(cfg->features, MPAM_FEATURE_LAST)) reset = false; @@ -2653,7 +2693,7 @@ static int __allocate_component_cfg(struct mpam_component *comp) if (comp->cfg) return 0; - comp->cfg = kzalloc_objs(*comp->cfg, mpam_partid_max + 1); + comp->cfg = kvzalloc_objs(*comp->cfg, mpam_partid_max + 1); if (!comp->cfg) return -ENOMEM; diff --git a/drivers/resctrl/mpam_resctrl.c b/drivers/resctrl/mpam_resctrl.c index 9d223057953a..9cec5843e8fa 100644 --- a/drivers/resctrl/mpam_resctrl.c +++ b/drivers/resctrl/mpam_resctrl.c @@ -497,7 +497,7 @@ static int read_mon_cdp_safe(struct mpam_resctrl_mon *mon, struct mpam_component if (err) return err; - *val += code_val + data_val; + *val = code_val + data_val; return 0; } @@ -1076,7 +1076,7 @@ static void counter_update_class(enum resctrl_event_id evt_id, struct mpam_class *existing_class = mpam_resctrl_counters[evt_id].class; if (existing_class) { - if (class->level == 3) { + if (existing_class->level == 3) { pr_debug("Existing class is L3 - L3 wins\n"); return; } @@ -1943,10 +1943,6 @@ static void mpam_resctrl_teardown_mon(struct mpam_resctrl_mon *mon, struct mpam_ mon->mbwu_idx_to_mon = NULL; } -/* - * The driver is detaching an MSC from this class, if resctrl was using it, - * pull on resctrl_exit(). - */ void mpam_resctrl_teardown_class(struct mpam_class *class) { struct mpam_resctrl_res *res; @@ -1957,17 +1953,14 @@ void mpam_resctrl_teardown_class(struct mpam_class *class) might_sleep(); for_each_mpam_resctrl_control(res, rid) { - if (res->class == class) { + if (res->class == class) res->class = NULL; - break; - } } for_each_mpam_resctrl_mon(mon, eventid) { if (mon->class == class) { mon->class = NULL; mpam_resctrl_teardown_mon(mon, class); - break; } } } diff --git a/drivers/rpmsg/mtk_rpmsg.c b/drivers/rpmsg/mtk_rpmsg.c index 1b670ed54cfa..430a9b2aa7bb 100644 --- a/drivers/rpmsg/mtk_rpmsg.c +++ b/drivers/rpmsg/mtk_rpmsg.c @@ -168,6 +168,7 @@ static void mtk_rpmsg_release_device(struct device *dev) struct rpmsg_device *rpdev = to_rpmsg_device(dev); struct mtk_rpmsg_device *mdev = to_mtk_rpmsg_device(rpdev); + of_node_put(dev->of_node); kfree(mdev); } diff --git a/drivers/rpmsg/virtio_rpmsg_bus.c b/drivers/rpmsg/virtio_rpmsg_bus.c index 1b8bb05924af..a32772d6ccbc 100644 --- a/drivers/rpmsg/virtio_rpmsg_bus.c +++ b/drivers/rpmsg/virtio_rpmsg_bus.c @@ -536,10 +536,13 @@ static int rpmsg_send_offchannel_raw(struct rpmsg_device *rpdev, (msg = get_a_tx_buf(vrp)), msecs_to_jiffies(15000)); + if (err < 0) + return err; + /* timeout ? */ if (!err) { dev_err(dev, "timeout waiting for a tx buffer\n"); - return -ERESTARTSYS; + return -ETIMEDOUT; } } diff --git a/drivers/rtc/Kconfig b/drivers/rtc/Kconfig index 05b9233b9418..dcf9bdaeacb0 100644 --- a/drivers/rtc/Kconfig +++ b/drivers/rtc/Kconfig @@ -30,6 +30,27 @@ config RTC_HCTOSYS the value read from a specified RTC device. This is useful to avoid unnecessary fsck runs at boot time, and to network better. +config RTC_HCTOSYS_TIME32_LIMIT + bool "Reject RTC dates after the 2038 cutoff" + depends on RTC_HCTOSYS && COMPAT_32BIT_TIME && !64BIT + default y + help + Reject RTC dates after 03:14:07 UTC on 19 January 2038 when + initializing the system clock in order to work around broken + RTC implementations that produce nondeterministic timestamps + without a working backup battery. + + A rejected date leaves system time unchanged, normally near + the Unix epoch, and the RTC's hctosys sysfs attribute reads + 0. Userspace must supply the time if no other source has + initialized it. + + Say Y here if the kernel may have to run old time32 userspace on + hardware that can produce unpredictable RTC timestamps. If the + kernel is intended to only run time64 compatible userspace and + continue working past 2038, you must pick N here in order to + have a working RTC_HCTOSYS functionality. + config RTC_HCTOSYS_DEVICE string "RTC used to set the system time" depends on RTC_HCTOSYS diff --git a/drivers/rtc/class.c b/drivers/rtc/class.c index 01ba04028f1f..18ea141ab8c2 100644 --- a/drivers/rtc/class.c +++ b/drivers/rtc/class.c @@ -72,12 +72,14 @@ static void rtc_hctosys(struct rtc_device *rtc) tv64.tv_sec = rtc_tm_to_time64(&tm); -#if BITS_PER_LONG == 32 - if (tv64.tv_sec > INT_MAX) { + if (IS_ENABLED(CONFIG_RTC_HCTOSYS_TIME32_LIMIT) && + tv64.tv_sec > INT_MAX) { + dev_warn(rtc->dev.parent, + "hctosys: rejecting %ptR UTC due to CONFIG_RTC_HCTOSYS_TIME32_LIMIT=y\n", + &tm); err = -ERANGE; goto err_read; } -#endif err = do_settimeofday64(&tv64); diff --git a/drivers/rtc/rtc-abx80x.c b/drivers/rtc/rtc-abx80x.c index 5486d9d0b1e5..2fd0079b7c51 100644 --- a/drivers/rtc/rtc-abx80x.c +++ b/drivers/rtc/rtc-abx80x.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -50,12 +51,18 @@ #define ABX8XX_CTRL2_RSVD BIT(5) #define ABX8XX_REG_IRQ 0x12 +#define ABX8XX_IRQ_EX1E BIT(0) +#define ABX8XX_IRQ_EX2E BIT(1) #define ABX8XX_IRQ_AIE BIT(2) +#define ABX8XX_IRQ_TIE BIT(3) +#define ABX8XX_IRQ_BLIE BIT(4) #define ABX8XX_IRQ_IM_1_4 (0x3 << 5) #define ABX8XX_REG_CD_TIMER_CTL 0x18 #define ABX8XX_REG_OSC 0x1c +#define ABX8XX_OSC_ACIE BIT(0) +#define ABX8XX_OSC_OFIE BIT(1) #define ABX8XX_OSC_FOS BIT(3) #define ABX8XX_OSC_BOS BIT(4) #define ABX8XX_OSC_ACAL_512 BIT(5) @@ -127,6 +134,7 @@ struct abx80x_priv { struct rtc_device *rtc; struct i2c_client *client; struct watchdog_device wdog; + struct mutex lock; }; static int abx80x_write_config_key(struct i2c_client *client, u8 key) @@ -219,6 +227,7 @@ static int abx80x_rtc_read_time(struct device *dev, struct rtc_time *tm) static int abx80x_rtc_set_time(struct device *dev, struct rtc_time *tm) { struct i2c_client *client = to_i2c_client(dev); + struct abx80x_priv *priv = i2c_get_clientdata(client); unsigned char buf[8]; int err, flags; @@ -234,6 +243,8 @@ static int abx80x_rtc_set_time(struct device *dev, struct rtc_time *tm) buf[ABX8XX_REG_YR] = bin2bcd(tm->tm_year - 100); buf[ABX8XX_REG_WD] = tm->tm_wday; + guard(mutex)(&priv->lock); + err = i2c_smbus_write_i2c_block_data(client, ABX8XX_REG_HTH, sizeof(buf), buf); if (err < 0) { @@ -261,8 +272,11 @@ static irqreturn_t abx80x_handle_irq(int irq, void *dev_id) struct i2c_client *client = dev_id; struct abx80x_priv *priv = i2c_get_clientdata(client); struct rtc_device *rtc = priv->rtc; + unsigned int status_flags_clear; int status; + guard(mutex)(&priv->lock); + status = i2c_smbus_read_byte_data(client, ABX8XX_REG_STATUS); if (status < 0) return IRQ_NONE; @@ -277,9 +291,15 @@ static irqreturn_t abx80x_handle_irq(int irq, void *dev_id) if (status & ABX8XX_STATUS_WDT) dev_alert(&client->dev, "watchdog timeout interrupt.\n"); - i2c_smbus_write_byte_data(client, ABX8XX_REG_STATUS, 0); + status_flags_clear = status & (ABX8XX_STATUS_AF | ABX8XX_STATUS_WDT); - return IRQ_HANDLED; + if (status_flags_clear) { + i2c_smbus_write_byte_data(client, ABX8XX_REG_STATUS, + status & ~status_flags_clear); + return IRQ_HANDLED; + } + + return IRQ_NONE; } static int abx80x_read_alarm(struct device *dev, struct rtc_wkalrm *t) @@ -294,8 +314,10 @@ static int abx80x_read_alarm(struct device *dev, struct rtc_wkalrm *t) err = i2c_smbus_read_i2c_block_data(client, ABX8XX_REG_ASC, sizeof(buf), buf); - if (err) + if (err < 0) return err; + if (err < ARRAY_SIZE(buf)) + return -EIO; irq_mask = i2c_smbus_read_byte_data(client, ABX8XX_REG_IRQ); if (irq_mask < 0) @@ -311,12 +333,13 @@ static int abx80x_read_alarm(struct device *dev, struct rtc_wkalrm *t) t->enabled = !!(irq_mask & ABX8XX_IRQ_AIE); t->pending = (buf[6] & ABX8XX_STATUS_AF) && t->enabled; - return err; + return 0; } static int abx80x_set_alarm(struct device *dev, struct rtc_wkalrm *t) { struct i2c_client *client = to_i2c_client(dev); + struct abx80x_priv *priv = i2c_get_clientdata(client); u8 alarm[6]; int err; @@ -330,6 +353,8 @@ static int abx80x_set_alarm(struct device *dev, struct rtc_wkalrm *t) alarm[4] = bin2bcd(t->time.tm_mday); alarm[5] = bin2bcd(t->time.tm_mon + 1); + guard(mutex)(&priv->lock); + err = i2c_smbus_write_i2c_block_data(client, ABX8XX_REG_AHTH, sizeof(alarm), alarm); if (err < 0) { @@ -352,6 +377,7 @@ static int abx80x_rtc_set_autocalibration(struct device *dev, int autocalibration) { struct i2c_client *client = to_i2c_client(dev); + struct abx80x_priv *priv = i2c_get_clientdata(client); int retval, flags = 0; if ((autocalibration != 0) && (autocalibration != 1024) && @@ -360,6 +386,8 @@ static int abx80x_rtc_set_autocalibration(struct device *dev, return -EINVAL; } + guard(mutex)(&priv->lock); + flags = i2c_smbus_read_byte_data(client, ABX8XX_REG_OSC); if (flags < 0) return flags; @@ -443,6 +471,7 @@ static ssize_t oscillator_store(struct device *dev, const char *buf, size_t count) { struct i2c_client *client = to_i2c_client(dev->parent); + struct abx80x_priv *priv = i2c_get_clientdata(client); int retval, flags, rc_mode = 0; if (strncmp(buf, "rc", 2) == 0) { @@ -454,6 +483,8 @@ static ssize_t oscillator_store(struct device *dev, return -EINVAL; } + guard(mutex)(&priv->lock); + flags = i2c_smbus_read_byte_data(client, ABX8XX_REG_OSC); if (flags < 0) return flags; @@ -511,8 +542,11 @@ static const struct attribute_group rtc_calib_attr_group = { static int abx80x_alarm_irq_enable(struct device *dev, unsigned int enabled) { struct i2c_client *client = to_i2c_client(dev); + struct abx80x_priv *priv = i2c_get_clientdata(client); int err; + guard(mutex)(&priv->lock); + if (enabled) err = i2c_smbus_write_byte_data(client, ABX8XX_REG_IRQ, (ABX8XX_IRQ_IM_1_4 | @@ -526,6 +560,7 @@ static int abx80x_alarm_irq_enable(struct device *dev, unsigned int enabled) static int abx80x_ioctl(struct device *dev, unsigned int cmd, unsigned long arg) { struct i2c_client *client = to_i2c_client(dev); + struct abx80x_priv *priv = i2c_get_clientdata(client); int status, tmp; switch (cmd) { @@ -539,16 +574,18 @@ static int abx80x_ioctl(struct device *dev, unsigned int cmd, unsigned long arg) return put_user(tmp, (unsigned int __user *)arg); case RTC_VL_CLR: - status = i2c_smbus_read_byte_data(client, ABX8XX_REG_STATUS); - if (status < 0) - return status; + scoped_guard(mutex, &priv->lock) { + status = i2c_smbus_read_byte_data(client, ABX8XX_REG_STATUS); + if (status < 0) + return status; - status &= ~ABX8XX_STATUS_BLF; + status &= ~ABX8XX_STATUS_BLF; - tmp = i2c_smbus_write_byte_data(client, ABX8XX_REG_STATUS, - status); - if (tmp < 0) - return tmp; + tmp = i2c_smbus_write_byte_data(client, ABX8XX_REG_STATUS, + status); + if (tmp < 0) + return tmp; + } return 0; @@ -617,6 +654,8 @@ static int __abx80x_wdog_set_timeout(struct watchdog_device *wdog, struct abx80x_priv *priv = watchdog_get_drvdata(wdog); u8 val = ABX8XX_WDT_WDS | timeout_bits(timeout); + guard(mutex)(&priv->lock); + /* * Writing any timeout to the WDT register resets the watchdog timer. * Writing 0 disables it. @@ -701,6 +740,8 @@ static int abx80x_nvmem_xfer(struct abx80x_priv *priv, unsigned int offset, len = min(lower + bytes, (size_t)ABX8XX_SRAM_WIN_SIZE) - lower; len = min_t(u8, len, I2C_SMBUS_BLOCK_MAX); + guard(mutex)(&priv->lock); + ret = i2c_smbus_write_byte_data(priv->client, ABX8XX_REG_EXTRAM, extram); if (ret) @@ -908,9 +949,47 @@ static int abx80x_probe(struct i2c_client *client) priv->rtc->ops = &abx80x_rtc_ops; priv->client = client; + err = devm_mutex_init(&client->dev, &priv->lock); + if (err) + return err; i2c_set_clientdata(client, priv); + /* Disable unused interrupts */ + data = i2c_smbus_read_byte_data(client, ABX8XX_REG_IRQ); + if (data < 0) { + dev_err(&client->dev, "Unable to read irq register\n"); + return -EIO; + } + + err = i2c_smbus_write_byte_data(client, ABX8XX_REG_IRQ, + data & ~(ABX8XX_IRQ_EX1E | + ABX8XX_IRQ_EX2E | + ABX8XX_IRQ_TIE | + ABX8XX_IRQ_BLIE)); + if (err < 0) { + dev_err(&client->dev, "Unable to write irq register\n"); + return -EIO; + } + + data = i2c_smbus_read_byte_data(client, ABX8XX_REG_OSC); + if (data < 0) { + dev_err(&client->dev, "Unable to read Oscillator Control register\n"); + return -EIO; + } + + /* Unlock write access to Oscillator Control Register */ + if (abx80x_write_config_key(client, ABX8XX_CFG_KEY_OSC) < 0) + return -EIO; + + err = i2c_smbus_write_byte_data(client, ABX8XX_REG_OSC, + data & ~(ABX8XX_OSC_ACIE | + ABX8XX_OSC_OFIE)); + if (err < 0) { + dev_err(&client->dev, "Unable to write Oscillator Control register\n"); + return -EIO; + } + if (abx80x_caps[part].has_wdog) { err = abx80x_setup_watchdog(priv); if (err) diff --git a/drivers/rtc/rtc-bd70528.c b/drivers/rtc/rtc-bd70528.c index 482810b61495..a58cf85bc1be 100644 --- a/drivers/rtc/rtc-bd70528.c +++ b/drivers/rtc/rtc-bd70528.c @@ -11,6 +11,7 @@ #include #include #include +#include #include #include @@ -321,6 +322,10 @@ static int bd70528_probe(struct platform_device *pdev) device_set_wakeup_capable(&pdev->dev, true); device_wakeup_enable(&pdev->dev); + ret = devm_pm_set_wake_irq(&pdev->dev, irq); + if (ret) + return ret; + rtc = devm_rtc_allocate_device(&pdev->dev); if (IS_ERR(rtc)) { dev_err(&pdev->dev, "RTC device creation failed\n"); diff --git a/drivers/rtc/rtc-ds1685.c b/drivers/rtc/rtc-ds1685.c index 5fc8e36b1abf..123ab9fc9c8d 100644 --- a/drivers/rtc/rtc-ds1685.c +++ b/drivers/rtc/rtc-ds1685.c @@ -1367,7 +1367,7 @@ module_platform_driver(ds1685_rtc_driver); void __noreturn ds1685_rtc_poweroff(struct platform_device *pdev) { - u8 ctrla, ctrl4a, ctrl4b; + u8 ctrla, ctrlb, ctrl4a, ctrl4b; struct ds1685_priv *rtc; /* Check for valid RTC data, else, spin forever. */ @@ -1394,6 +1394,8 @@ ds1685_rtc_poweroff(struct platform_device *pdev) ctrla &= ~(RTC_CTRL_A_DV2); rtc->write(rtc, RTC_CTRL_A, ctrla); + ctrlb = rtc->read(rtc, RTC_CTRL_B); + /* * Read Control 4A and check the status of the auxillary * battery. This must be present and working (VRT2 = 1) @@ -1408,19 +1410,23 @@ ds1685_rtc_poweroff(struct platform_device *pdev) /* * The auxillary battery is present and working. - * Enable extended functions (ABE=1), enable - * wake-up (WIE=1), and enable kickstart (KSE=1) - * in Control 4B. + * Enable extended functions (ABE=1) and kickstart + * (KSE=1) in Control 4B. Enable wake-up (WIE=1) only + * if an alarm is set, else stale alarm registers + * can power the system back on. */ ctrl4b = rtc->read(rtc, RTC_EXT_CTRL_4B); - ctrl4b |= (RTC_CTRL_4B_ABE | RTC_CTRL_4B_WIE | - RTC_CTRL_4B_KSE); + ctrl4b |= (RTC_CTRL_4B_ABE | RTC_CTRL_4B_KSE); + if (ctrlb & RTC_CTRL_B_AIE) + ctrl4b |= RTC_CTRL_4B_WIE; + else + ctrl4b &= ~(RTC_CTRL_4B_WIE); rtc->write(rtc, RTC_EXT_CTRL_4B, ctrl4b); } /* Set PAB to 1 in Control 4A to power the system down. */ dev_warn(&pdev->dev, "Powerdown.\n"); - msleep(20); + mdelay(20); rtc->write(rtc, RTC_EXT_CTRL_4A, (ctrl4a | RTC_CTRL_4A_PAB)); diff --git a/drivers/rtc/rtc-ftrtc010.c b/drivers/rtc/rtc-ftrtc010.c index 98fa0f518303..b29c96be40f4 100644 --- a/drivers/rtc/rtc-ftrtc010.c +++ b/drivers/rtc/rtc-ftrtc010.c @@ -72,7 +72,7 @@ static int ftrtc010_rtc_read_time(struct device *dev, struct rtc_time *tm) days = readl(rtc->rtc_base + FTRTC010_RTC_DAYS); offset = readl(rtc->rtc_base + FTRTC010_RTC_RECORD); - time = offset + days * 86400 + hour * 3600 + min * 60 + sec; + time = (timeu64_t)(offset + days * 86400 + hour * 3600 + min * 60 + sec); rtc_time64_to_tm(time, tm); @@ -92,7 +92,8 @@ static int ftrtc010_rtc_set_time(struct device *dev, struct rtc_time *tm) hour = readl(rtc->rtc_base + FTRTC010_RTC_HOUR); day = readl(rtc->rtc_base + FTRTC010_RTC_DAYS); - offset = time - (day * 86400 + hour * 3600 + min * 60 + sec); + offset = time - ((timeu64_t)day * 86400 + (timeu64_t)hour * 3600 + + (timeu64_t)min * 60 + (timeu64_t)sec); writel(offset, rtc->rtc_base + FTRTC010_RTC_RECORD); writel(0x01, rtc->rtc_base + FTRTC010_RTC_CR); @@ -119,51 +120,33 @@ static int ftrtc010_rtc_probe(struct platform_device *pdev) return -ENOMEM; platform_set_drvdata(pdev, rtc); - rtc->pclk = devm_clk_get(dev, "PCLK"); - if (IS_ERR(rtc->pclk)) { + rtc->pclk = devm_clk_get_enabled(dev, "PCLK"); + if (IS_ERR_OR_NULL(rtc->pclk)) { dev_err(dev, "could not get PCLK\n"); - } else { - ret = clk_prepare_enable(rtc->pclk); - if (ret) { - dev_err(dev, "failed to enable PCLK\n"); - return ret; - } + return PTR_ERR_OR_ZERO(rtc->pclk); } - rtc->extclk = devm_clk_get(dev, "EXTCLK"); - if (IS_ERR(rtc->extclk)) { + rtc->extclk = devm_clk_get_enabled(dev, "EXTCLK"); + if (IS_ERR_OR_NULL(rtc->extclk)) { dev_err(dev, "could not get EXTCLK\n"); - } else { - ret = clk_prepare_enable(rtc->extclk); - if (ret) { - dev_err(dev, "failed to enable EXTCLK\n"); - goto err_disable_pclk; - } + return PTR_ERR_OR_ZERO(rtc->extclk); } rtc->rtc_irq = platform_get_irq(pdev, 0); - if (rtc->rtc_irq < 0) { - ret = rtc->rtc_irq; - goto err_disable_extclk; - } + if (rtc->rtc_irq < 0) + return rtc->rtc_irq; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); - if (!res) { - ret = -ENODEV; - goto err_disable_extclk; - } + if (!res) + return -ENODEV; rtc->rtc_base = devm_ioremap(dev, res->start, resource_size(res)); - if (!rtc->rtc_base) { - ret = -ENOMEM; - goto err_disable_extclk; - } + if (!rtc->rtc_base) + return -ENOMEM; rtc_dev = devm_rtc_allocate_device(dev); - if (IS_ERR(rtc_dev)) { - ret = PTR_ERR(rtc_dev); - goto err_disable_extclk; - } + if (IS_ERR(rtc_dev)) + return PTR_ERR(rtc_dev); rtc_dev->ops = &ftrtc010_rtc_ops; @@ -178,25 +161,13 @@ static int ftrtc010_rtc_probe(struct platform_device *pdev) ret = devm_request_irq(dev, rtc->rtc_irq, ftrtc010_rtc_interrupt, IRQF_SHARED, pdev->name, dev); if (unlikely(ret)) - goto err_disable_extclk; + return ret; - return devm_rtc_register_device(rtc_dev); + ret = devm_rtc_register_device(rtc_dev); + if (ret) + return ret; -err_disable_extclk: - clk_disable_unprepare(rtc->extclk); -err_disable_pclk: - clk_disable_unprepare(rtc->pclk); - return ret; -} - -static void ftrtc010_rtc_remove(struct platform_device *pdev) -{ - struct ftrtc010_rtc *rtc = platform_get_drvdata(pdev); - - if (!IS_ERR(rtc->extclk)) - clk_disable_unprepare(rtc->extclk); - if (!IS_ERR(rtc->pclk)) - clk_disable_unprepare(rtc->pclk); + return 0; } static const struct of_device_id ftrtc010_rtc_dt_match[] = { @@ -212,7 +183,6 @@ static struct platform_driver ftrtc010_rtc_driver = { .of_match_table = ftrtc010_rtc_dt_match, }, .probe = ftrtc010_rtc_probe, - .remove = ftrtc010_rtc_remove, }; module_platform_driver_probe(ftrtc010_rtc_driver, ftrtc010_rtc_probe); diff --git a/drivers/rtc/rtc-mpfs.c b/drivers/rtc/rtc-mpfs.c index 60596b0ea9d8..6616ca1f02c7 100644 --- a/drivers/rtc/rtc-mpfs.c +++ b/drivers/rtc/rtc-mpfs.c @@ -131,8 +131,8 @@ static int mpfs_rtc_readalarm(struct device *dev, struct rtc_wkalrm *alrm) alrm->enabled = mode & MODE_WAKE_EN; - time = (u64)readl(rtcdev->base + ALARM_LOWER_REG) << 32; - time |= (readl(rtcdev->base + ALARM_UPPER_REG) & ALARM_UPPER_MASK); + time = readl(rtcdev->base + ALARM_LOWER_REG); + time |= ((u64)readl(rtcdev->base + ALARM_UPPER_REG) & ALARM_UPPER_MASK) << 32; rtc_time64_to_tm(time, &alrm->time); return 0; diff --git a/drivers/rtc/rtc-s35390a.c b/drivers/rtc/rtc-s35390a.c index b72eef4fb099..12ed504db94d 100644 --- a/drivers/rtc/rtc-s35390a.c +++ b/drivers/rtc/rtc-s35390a.c @@ -64,7 +64,6 @@ MODULE_DEVICE_TABLE(of, s35390a_of_match); struct s35390a { struct i2c_client *client[8]; - int twentyfourhour; }; static int s35390a_set_reg(struct s35390a *s35390a, int reg, u8 *buf, int len) @@ -102,9 +101,8 @@ static int s35390a_get_reg(struct s35390a *s35390a, int reg, u8 *buf, int len) return 0; } -static int s35390a_init(struct s35390a *s35390a) +static int s35390a_init(struct s35390a *s35390a, u8 *sts) { - u8 buf; int ret; unsigned initcount = 0; @@ -117,17 +115,17 @@ static int s35390a_init(struct s35390a *s35390a) * The 24H bit is kept over reset, so set it already here. */ initialize: - buf = S35390A_FLAG_RESET | S35390A_FLAG_24H; - ret = s35390a_set_reg(s35390a, S35390A_CMD_STATUS1, &buf, 1); + *sts = S35390A_FLAG_RESET | S35390A_FLAG_24H; + ret = s35390a_set_reg(s35390a, S35390A_CMD_STATUS1, sts, 1); if (ret < 0) return ret; - ret = s35390a_get_reg(s35390a, S35390A_CMD_STATUS1, &buf, 1); + ret = s35390a_get_reg(s35390a, S35390A_CMD_STATUS1, sts, 1); if (ret < 0) return ret; - if (buf & (S35390A_FLAG_POC | S35390A_FLAG_BLD)) { + if (*sts & (S35390A_FLAG_POC | S35390A_FLAG_BLD)) { /* Try up to five times to reset the chip */ if (initcount < 5) { ++initcount; @@ -181,9 +179,9 @@ static int s35390a_disable_test_mode(struct s35390a *s35390a) return s35390a_set_reg(s35390a, S35390A_CMD_STATUS2, buf, sizeof(buf)); } -static char s35390a_hr2reg(struct s35390a *s35390a, int hour) +static char s35390a_hr2reg(int hour, bool twentyfourhour) { - if (s35390a->twentyfourhour) + if (twentyfourhour) return bin2bcd(hour); if (hour < 12) @@ -192,11 +190,11 @@ static char s35390a_hr2reg(struct s35390a *s35390a, int hour) return 0x40 | bin2bcd(hour - 12); } -static int s35390a_reg2hr(struct s35390a *s35390a, char reg) +static int s35390a_reg2hr(char reg, bool twentyfourhour) { unsigned hour; - if (s35390a->twentyfourhour) + if (twentyfourhour) return bcd2bin(reg & 0x3f); hour = bcd2bin(reg & 0x3f); @@ -210,7 +208,7 @@ static int s35390a_rtc_set_time(struct device *dev, struct rtc_time *tm) { struct i2c_client *client = to_i2c_client(dev); struct s35390a *s35390a = i2c_get_clientdata(client); - int i; + int i, err; u8 buf[7], status; dev_dbg(&client->dev, "%s: tm is secs=%d, mins=%d, hours=%d mday=%d, " @@ -218,14 +216,18 @@ static int s35390a_rtc_set_time(struct device *dev, struct rtc_time *tm) tm->tm_min, tm->tm_hour, tm->tm_mday, tm->tm_mon, tm->tm_year, tm->tm_wday); - if (s35390a_read_status(s35390a, &status) == 1) - s35390a_init(s35390a); + err = s35390a_read_status(s35390a, &status); + if (err == 1) + err = s35390a_init(s35390a, &status); + + if (err < 0) + return err; buf[S35390A_BYTE_YEAR] = bin2bcd(tm->tm_year - 100); buf[S35390A_BYTE_MONTH] = bin2bcd(tm->tm_mon + 1); buf[S35390A_BYTE_DAY] = bin2bcd(tm->tm_mday); buf[S35390A_BYTE_WDAY] = bin2bcd(tm->tm_wday); - buf[S35390A_BYTE_HOURS] = s35390a_hr2reg(s35390a, tm->tm_hour); + buf[S35390A_BYTE_HOURS] = s35390a_hr2reg(tm->tm_hour, status & S35390A_FLAG_24H); buf[S35390A_BYTE_MINS] = bin2bcd(tm->tm_min); buf[S35390A_BYTE_SECS] = bin2bcd(tm->tm_sec); @@ -243,8 +245,11 @@ static int s35390a_rtc_read_time(struct device *dev, struct rtc_time *tm) u8 buf[7], status; int i, err; - if (s35390a_read_status(s35390a, &status) == 1) + err = s35390a_read_status(s35390a, &status); + if (err == 1) return -EINVAL; + if (err < 0) + return err; err = s35390a_get_reg(s35390a, S35390A_CMD_TIME1, buf, sizeof(buf)); if (err < 0) @@ -256,7 +261,7 @@ static int s35390a_rtc_read_time(struct device *dev, struct rtc_time *tm) tm->tm_sec = bcd2bin(buf[S35390A_BYTE_SECS]); tm->tm_min = bcd2bin(buf[S35390A_BYTE_MINS]); - tm->tm_hour = s35390a_reg2hr(s35390a, buf[S35390A_BYTE_HOURS]); + tm->tm_hour = s35390a_reg2hr(buf[S35390A_BYTE_HOURS], status & S35390A_FLAG_24H); tm->tm_wday = bcd2bin(buf[S35390A_BYTE_WDAY]); tm->tm_mday = bcd2bin(buf[S35390A_BYTE_DAY]); tm->tm_mon = bcd2bin(buf[S35390A_BYTE_MONTH]) - 1; @@ -270,11 +275,29 @@ static int s35390a_rtc_read_time(struct device *dev, struct rtc_time *tm) return 0; } +static int s35390a_rtc_alarm_irq_enable(struct device *dev, unsigned int enabled) +{ + struct s35390a *s35390a = dev_get_drvdata(dev); + u8 sts; + int err; + + if (enabled) + sts = S35390A_INT2_MODE_ALARM; + else + sts = S35390A_INT2_MODE_NOINTR; + + err = s35390a_set_reg(s35390a, S35390A_CMD_STATUS2, &sts, sizeof(sts)); + if (err < 0) + return err; + + return 0; +} + static int s35390a_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alm) { struct i2c_client *client = to_i2c_client(dev); struct s35390a *s35390a = i2c_get_clientdata(client); - u8 buf[3], sts = 0; + u8 buf[3], status1, status2 = 0; int err, i; dev_dbg(&client->dev, "%s: alm is secs=%d, mins=%d, hours=%d mday=%d, "\ @@ -283,22 +306,22 @@ static int s35390a_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alm) alm->time.tm_mon, alm->time.tm_year, alm->time.tm_wday); /* disable interrupt (which deasserts the irq line) */ - err = s35390a_set_reg(s35390a, S35390A_CMD_STATUS2, &sts, sizeof(sts)); + err = s35390a_set_reg(s35390a, S35390A_CMD_STATUS2, &status2, sizeof(status2)); if (err < 0) return err; /* clear pending interrupt (in STATUS1 only), if any */ - err = s35390a_get_reg(s35390a, S35390A_CMD_STATUS1, &sts, sizeof(sts)); + err = s35390a_get_reg(s35390a, S35390A_CMD_STATUS1, &status1, sizeof(status1)); if (err < 0) return err; if (alm->enabled) - sts = S35390A_INT2_MODE_ALARM; + status2 = S35390A_INT2_MODE_ALARM; else - sts = S35390A_INT2_MODE_NOINTR; + status2 = S35390A_INT2_MODE_NOINTR; /* set interrupt mode*/ - err = s35390a_set_reg(s35390a, S35390A_CMD_STATUS2, &sts, sizeof(sts)); + err = s35390a_set_reg(s35390a, S35390A_CMD_STATUS2, &status2, sizeof(status2)); if (err < 0) return err; @@ -307,8 +330,8 @@ static int s35390a_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alm) else buf[S35390A_ALRM_BYTE_WDAY] = 0; - buf[S35390A_ALRM_BYTE_HOURS] = s35390a_hr2reg(s35390a, - alm->time.tm_hour) | 0x80; + buf[S35390A_ALRM_BYTE_HOURS] = s35390a_hr2reg(alm->time.tm_hour, + status1 & S35390A_FLAG_24H) | 0x80; buf[S35390A_ALRM_BYTE_MINS] = bin2bcd(alm->time.tm_min) | 0x80; if (alm->time.tm_hour >= 12) @@ -327,14 +350,20 @@ static int s35390a_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alm) { struct i2c_client *client = to_i2c_client(dev); struct s35390a *s35390a = i2c_get_clientdata(client); - u8 buf[3], sts; + u8 buf[3], status1, status2; int i, err; - err = s35390a_get_reg(s35390a, S35390A_CMD_STATUS2, &sts, sizeof(sts)); + err = s35390a_read_status(s35390a, &status1); + if (err == 1) + return -EINVAL; if (err < 0) return err; - if ((sts & S35390A_INT2_MODE_MASK) != S35390A_INT2_MODE_ALARM) { + err = s35390a_get_reg(s35390a, S35390A_CMD_STATUS2, &status2, sizeof(status2)); + if (err < 0) + return err; + + if ((status2 & S35390A_INT2_MODE_MASK) != S35390A_INT2_MODE_ALARM) { /* * When the alarm isn't enabled, the register to configure * the alarm time isn't accessible. @@ -363,8 +392,8 @@ static int s35390a_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alm) if (buf[S35390A_ALRM_BYTE_HOURS] & 0x80) alm->time.tm_hour = - s35390a_reg2hr(s35390a, - buf[S35390A_ALRM_BYTE_HOURS] & ~0x80); + s35390a_reg2hr(buf[S35390A_ALRM_BYTE_HOURS] & ~0x80, + status1 & S35390A_FLAG_24H); if (buf[S35390A_ALRM_BYTE_MINS] & 0x80) alm->time.tm_min = bcd2bin(buf[S35390A_ALRM_BYTE_MINS] & ~0x80); @@ -398,7 +427,7 @@ static int s35390a_rtc_ioctl(struct device *dev, unsigned int cmd, break; case RTC_VL_CLR: /* update flag and clear register */ - err = s35390a_init(s35390a); + err = s35390a_init(s35390a, &sts); if (err < 0) return err; break; @@ -410,11 +439,12 @@ static int s35390a_rtc_ioctl(struct device *dev, unsigned int cmd, } static const struct rtc_class_ops s35390a_rtc_ops = { - .read_time = s35390a_rtc_read_time, - .set_time = s35390a_rtc_set_time, - .set_alarm = s35390a_rtc_set_alarm, - .read_alarm = s35390a_rtc_read_alarm, - .ioctl = s35390a_rtc_ioctl, + .read_time = s35390a_rtc_read_time, + .set_time = s35390a_rtc_set_time, + .set_alarm = s35390a_rtc_set_alarm, + .read_alarm = s35390a_rtc_read_alarm, + .alarm_irq_enable = s35390a_rtc_alarm_irq_enable, + .ioctl = s35390a_rtc_ioctl, }; static int s35390a_nvmem_read(void *priv, unsigned int offset, void *val, @@ -484,17 +514,12 @@ static int s35390a_probe(struct i2c_client *client) return err_read; } - if (status1 & S35390A_FLAG_24H) - s35390a->twentyfourhour = 1; - else - s35390a->twentyfourhour = 0; - if (status1 & S35390A_FLAG_INT2) { /* disable alarm (and maybe test mode) */ buf = 0; err = s35390a_set_reg(s35390a, S35390A_CMD_STATUS2, &buf, 1); if (err < 0) { - dev_err(dev, "error disabling alarm"); + dev_err(dev, "error disabling alarm\n"); return err; } } else { diff --git a/drivers/s390/net/ism_drv.c b/drivers/s390/net/ism_drv.c index 035b233abb4e..405abd99c820 100644 --- a/drivers/s390/net/ism_drv.c +++ b/drivers/s390/net/ism_drv.c @@ -256,7 +256,8 @@ static int ism_alloc_dmb(struct ism_dev *ism, struct dibs_dmb *dmb) return -EINVAL; folio = folio_alloc(GFP_KERNEL | __GFP_NOWARN | __GFP_NOMEMALLOC | - __GFP_NORETRY, get_order(dmb->dmb_len)); + __GFP_NORETRY | __GFP_ZERO, + get_order(dmb->dmb_len)); if (!folio) { rc = -ENOMEM; diff --git a/drivers/s390/virtio/virtio_ccw.c b/drivers/s390/virtio/virtio_ccw.c index bab6cad3fd5c..552d77998012 100644 --- a/drivers/s390/virtio/virtio_ccw.c +++ b/drivers/s390/virtio/virtio_ccw.c @@ -1062,7 +1062,7 @@ static void virtio_ccw_synchronize_cbs(struct virtio_device *vdev) struct virtio_ccw_device *vcdev = to_vc_device(vdev); struct airq_info *info = vcdev->airq_info; - if (info) { + if (vcdev->is_thinint && info) { /* * This device uses adapter interrupts: synchronize with * vring_interrupt() called by virtio_airq_handler() @@ -1204,13 +1204,11 @@ static void virtio_ccw_int_handler(struct ccw_device *cdev, vcdev->err = -EIO; } virtio_ccw_check_activity(vcdev, activity); -#ifdef CONFIG_VIRTIO_HARDEN_NOTIFICATION /* * Paired with virtio_ccw_synchronize_cbs() and interrupts are * disabled here. */ read_lock(&vcdev->irq_lock); -#endif for_each_set_bit(i, indicators(vcdev), sizeof(*indicators(vcdev)) * BITS_PER_BYTE) { /* The bit clear must happen before the vring kick. */ @@ -1219,9 +1217,7 @@ static void virtio_ccw_int_handler(struct ccw_device *cdev, vq = virtio_ccw_vq_by_ind(vcdev, i); vring_interrupt(0, vq); } -#ifdef CONFIG_VIRTIO_HARDEN_NOTIFICATION read_unlock(&vcdev->irq_lock); -#endif if (test_bit(0, indicators2(vcdev))) { virtio_config_changed(&vcdev->vdev); clear_bit(0, indicators2(vcdev)); diff --git a/drivers/scsi/ch.c b/drivers/scsi/ch.c index c36539c83ed1..cc4532c7782f 100644 --- a/drivers/scsi/ch.c +++ b/drivers/scsi/ch.c @@ -190,7 +190,7 @@ ch_do_scsi(scsi_changer *ch, unsigned char *cmd, int cmd_len, struct scsi_sense_hdr sshdr; struct scsi_failure failure_defs[] = { { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = SCMD_FAILURE_ASC_ANY, .ascq = SCMD_FAILURE_ASCQ_ANY, .allowed = 3, diff --git a/drivers/scsi/device_handler/scsi_dh_hp_sw.c b/drivers/scsi/device_handler/scsi_dh_hp_sw.c index 6e8849d7f0a3..3431e1ce95fd 100644 --- a/drivers/scsi/device_handler/scsi_dh_hp_sw.c +++ b/drivers/scsi/device_handler/scsi_dh_hp_sw.c @@ -84,7 +84,7 @@ static int hp_sw_tur(struct scsi_device *sdev, struct hp_sw_dh_data *h) REQ_FAILFAST_TRANSPORT | REQ_FAILFAST_DRIVER; struct scsi_failure failure_defs[] = { { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = SCMD_FAILURE_ASC_ANY, .ascq = SCMD_FAILURE_ASCQ_ANY, .allowed = SCMD_FAILURE_NO_LIMIT, @@ -138,7 +138,7 @@ static int hp_sw_start_stop(struct hp_sw_dh_data *h) * * Switch-over in progress, retry. */ - .sense = NOT_READY, + .sense_key = NOT_READY, .asc = 0x04, .ascq = 0x03, .allowed = HP_SW_RETRIES, diff --git a/drivers/scsi/device_handler/scsi_dh_rdac.c b/drivers/scsi/device_handler/scsi_dh_rdac.c index 88c8e36b221e..75c9cc291e38 100644 --- a/drivers/scsi/device_handler/scsi_dh_rdac.c +++ b/drivers/scsi/device_handler/scsi_dh_rdac.c @@ -514,33 +514,33 @@ static void send_mode_select(struct work_struct *work) REQ_FAILFAST_TRANSPORT | REQ_FAILFAST_DRIVER; struct scsi_failure failure_defs[] = { { - .sense = NO_SENSE, + .sense_key = NO_SENSE, .asc = SCMD_FAILURE_ASC_ANY, .ascq = SCMD_FAILURE_ASCQ_ANY, .result = SAM_STAT_CHECK_CONDITION, }, { - .sense = ABORTED_COMMAND, + .sense_key = ABORTED_COMMAND, .asc = SCMD_FAILURE_ASC_ANY, .ascq = SCMD_FAILURE_ASCQ_ANY, .result = SAM_STAT_CHECK_CONDITION, }, { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = SCMD_FAILURE_ASC_ANY, .ascq = SCMD_FAILURE_ASCQ_ANY, .result = SAM_STAT_CHECK_CONDITION, }, /* LUN Not Ready and is in the Process of Becoming Ready */ { - .sense = NOT_READY, + .sense_key = NOT_READY, .asc = 0x04, .ascq = 0x01, .result = SAM_STAT_CHECK_CONDITION, }, /* Command Lock contention */ { - .sense = ILLEGAL_REQUEST, + .sense_key = ILLEGAL_REQUEST, .asc = 0x91, .ascq = 0x36, .allowed = SCMD_FAILURE_NO_LIMIT, diff --git a/drivers/scsi/elx/libefc/efclib.c b/drivers/scsi/elx/libefc/efclib.c index dd3e3d0a4761..ceec0e2a0266 100644 --- a/drivers/scsi/elx/libefc/efclib.c +++ b/drivers/scsi/elx/libefc/efclib.c @@ -50,6 +50,8 @@ int efcport_init(struct efc *efc) sizeof(struct efc_els_io_req)); if (!efc->els_io_pool) { efc_log_err(efc, "Can't allocate els io pool\n"); + dma_pool_destroy(efc->node_dma_pool); + mempool_destroy(efc->node_pool); return -ENOMEM; } diff --git a/drivers/scsi/hisi_sas/hisi_sas.h b/drivers/scsi/hisi_sas/hisi_sas.h index 1323ed8aa717..d48ba3747b81 100644 --- a/drivers/scsi/hisi_sas/hisi_sas.h +++ b/drivers/scsi/hisi_sas/hisi_sas.h @@ -163,6 +163,7 @@ enum hisi_sas_phy_event { HISI_PHYE_PHY_UP = 0U, HISI_PHYE_LINK_RESET, HISI_PHYE_PHY_UP_PM, + HISI_PHYE_SPINUP_NOTIFY, HISI_PHYES_NUM, }; @@ -689,4 +690,6 @@ extern void hisi_sas_sync_cqs(struct hisi_hba *hisi_hba); extern void hisi_sas_sync_poll_cqs(struct hisi_hba *hisi_hba); extern void hisi_sas_controller_reset_prepare(struct hisi_hba *hisi_hba); extern void hisi_sas_controller_reset_done(struct hisi_hba *hisi_hba); +extern void hisi_sas_spinup_notify(struct hisi_hba *hisi_hba, + struct sas_task *task); #endif diff --git a/drivers/scsi/hisi_sas/hisi_sas_main.c b/drivers/scsi/hisi_sas/hisi_sas_main.c index 944ce19ae2fc..cf7aa0a699cd 100644 --- a/drivers/scsi/hisi_sas/hisi_sas_main.c +++ b/drivers/scsi/hisi_sas/hisi_sas_main.c @@ -996,10 +996,25 @@ static void hisi_sas_phyup_pm_work(struct work_struct *work) pm_runtime_put_sync(dev); } +static void hisi_sas_spinup_notify_work(struct work_struct *work) +{ + struct hisi_sas_phy *phy = + container_of(work, typeof(*phy), works[HISI_PHYE_SPINUP_NOTIFY]); + struct hisi_hba *hisi_hba = phy->hisi_hba; + struct device *dev = hisi_hba->dev; + int phy_no = phy->sas_phy.id; + + hisi_hba->hw->sl_notify_ssp(hisi_hba, phy_no); + dev_info(dev, "spinup notify primitive on phy%d\n", phy_no); + + pm_runtime_put_sync(dev); +} + static const work_func_t hisi_sas_phye_fns[HISI_PHYES_NUM] = { [HISI_PHYE_PHY_UP] = hisi_sas_phyup_work, [HISI_PHYE_LINK_RESET] = hisi_sas_linkreset_work, [HISI_PHYE_PHY_UP_PM] = hisi_sas_phyup_pm_work, + [HISI_PHYE_SPINUP_NOTIFY] = hisi_sas_spinup_notify_work, }; bool hisi_sas_notify_phy_event(struct hisi_sas_phy *phy, @@ -1639,6 +1654,34 @@ void hisi_sas_controller_reset_done(struct hisi_hba *hisi_hba) } EXPORT_SYMBOL_GPL(hisi_sas_controller_reset_done); +void hisi_sas_spinup_notify(struct hisi_hba *hisi_hba, + struct sas_task *task) +{ + struct task_status_struct *ts = &task->task_status; + struct domain_device *dev = task->dev; + struct scsi_sense_hdr sshdr; + struct sas_phy *local_phy; + struct hisi_sas_phy *phy; + + if (!scsi_normalize_sense(ts->buf, ts->buf_valid_size, &sshdr)) + return; + + if (sshdr.sense_key != NOT_READY || + sshdr.sense_code != LU_NOT_READY_NOTIFY_REQUIRED) + return; + + if (!pm_runtime_get_if_active(hisi_hba->dev)) + return; + + local_phy = sas_get_local_phy(dev); + phy = &hisi_hba->phy[local_phy->number]; + if (!hisi_sas_notify_phy_event(phy, HISI_PHYE_SPINUP_NOTIFY)) + pm_runtime_put(hisi_hba->dev); + + sas_put_local_phy(local_phy); +} +EXPORT_SYMBOL_GPL(hisi_sas_spinup_notify); + static int hisi_sas_controller_prereset(struct hisi_hba *hisi_hba) { if (!hisi_hba->hw->soft_reset) diff --git a/drivers/scsi/hisi_sas/hisi_sas_v1_hw.c b/drivers/scsi/hisi_sas/hisi_sas_v1_hw.c index fa94d7110714..5fcb8d5002f5 100644 --- a/drivers/scsi/hisi_sas/hisi_sas_v1_hw.c +++ b/drivers/scsi/hisi_sas/hisi_sas_v1_hw.c @@ -1272,6 +1272,10 @@ static void slot_complete_v1_hw(struct hisi_hba *hisi_hba, &status_buffer->iu[0]; sas_ssp_task_response(dev, task, iu); + if (unlikely(ts->stat == SAS_SAM_STAT_CHECK_CONDITION && + !dev_parent_is_expander(device))) + hisi_sas_spinup_notify(hisi_hba, task); + break; } case SAS_PROTOCOL_SMP: diff --git a/drivers/scsi/hisi_sas/hisi_sas_v2_hw.c b/drivers/scsi/hisi_sas/hisi_sas_v2_hw.c index f3516a0611dd..f16896e962fd 100644 --- a/drivers/scsi/hisi_sas/hisi_sas_v2_hw.c +++ b/drivers/scsi/hisi_sas/hisi_sas_v2_hw.c @@ -2427,6 +2427,10 @@ static void slot_complete_v2_hw(struct hisi_hba *hisi_hba, &status_buffer->iu[0]; sas_ssp_task_response(dev, task, iu); + if (unlikely(ts->stat == SAS_SAM_STAT_CHECK_CONDITION && + !dev_parent_is_expander(device))) + hisi_sas_spinup_notify(hisi_hba, task); + break; } case SAS_PROTOCOL_SMP: diff --git a/drivers/scsi/hisi_sas/hisi_sas_v3_hw.c b/drivers/scsi/hisi_sas/hisi_sas_v3_hw.c index 8a2500993e19..e74ab20fdbda 100644 --- a/drivers/scsi/hisi_sas/hisi_sas_v3_hw.c +++ b/drivers/scsi/hisi_sas/hisi_sas_v3_hw.c @@ -547,6 +547,9 @@ struct hisi_sas_err_record_v3 { #define IRQ_AXI_INDEX 11 #define DELAY_FOR_RESET_HW 100 +#define STOP_PHY_DELAY_US 50 +#define DISABLE_PHY_DELAY_MS 50 +#define DISABLE_HOST_PHY_DELAY_MS 10 #define HDR_SG_MOD 0x2 #define LUN_SIZE 8 #define ATTR_PRIO_REGION 9 @@ -983,7 +986,7 @@ static int reset_hw_v3_hw(struct hisi_hba *hisi_hba) /* Disable all of the PHYs */ hisi_sas_stop_phys(hisi_hba); - udelay(HISI_SAS_DELAY_FOR_PHY_DISABLE); + udelay(STOP_PHY_DELAY_US); /* Ensure axi bus idle */ ret = hisi_sas_read32_poll_timeout(AXI_CFG, val, !val, @@ -1072,7 +1075,7 @@ static void disable_phy_v3_hw(struct hisi_hba *hisi_hba, int phy_no) cfg &= ~PHY_CFG_ENA_MSK; hisi_sas_phy_write32(hisi_hba, phy_no, PHY_CFG, cfg); - mdelay(HISI_SAS_DELAY_FOR_PHY_DISABLE); + mdelay(DISABLE_PHY_DELAY_MS); state = hisi_sas_read32(hisi_hba, PHY_STATE); if (state & BIT(phy_no)) { @@ -2432,6 +2435,10 @@ static void slot_complete_v3_hw(struct hisi_hba *hisi_hba, sizeof(struct hisi_sas_err_record); sas_ssp_task_response(dev, task, iu); + if (unlikely(ts->stat == SAS_SAM_STAT_CHECK_CONDITION && + !dev_parent_is_expander(device))) + hisi_sas_spinup_notify(hisi_hba, task); + break; } case SAS_PROTOCOL_SMP: { @@ -2755,7 +2762,7 @@ static int disable_host_v3_hw(struct hisi_hba *hisi_hba) hisi_sas_stop_phys(hisi_hba); - mdelay(HISI_SAS_DELAY_FOR_PHY_DISABLE); + mdelay(DISABLE_HOST_PHY_DELAY_MS); reg_val = hisi_sas_read32(hisi_hba, AXI_MASTER_CFG_BASE + AM_CTRL_GLOBAL); diff --git a/drivers/scsi/libsas/sas_task.c b/drivers/scsi/libsas/sas_task.c index e9d291007817..2080e5836179 100644 --- a/drivers/scsi/libsas/sas_task.c +++ b/drivers/scsi/libsas/sas_task.c @@ -25,7 +25,7 @@ void sas_ssp_task_response(struct device *dev, struct sas_task *task, case SAS_DATAPRES_SENSE_DATA: tstat->stat = SAS_SAM_STAT_CHECK_CONDITION; tstat->buf_valid_size = - min_t(int, SAS_STATUS_BUF_SIZE, + min_t(u32, SAS_STATUS_BUF_SIZE, be32_to_cpu(iu->sense_data_len)); memcpy(tstat->buf, iu->sense_data, tstat->buf_valid_size); diff --git a/drivers/scsi/mpi3mr/mpi3mr_app.c b/drivers/scsi/mpi3mr/mpi3mr_app.c index 094490713d69..3751b30efea3 100644 --- a/drivers/scsi/mpi3mr/mpi3mr_app.c +++ b/drivers/scsi/mpi3mr/mpi3mr_app.c @@ -1244,7 +1244,7 @@ static long mpi3mr_bsg_query_hdb(struct mpi3mr_ioc *mrioc, length = (sizeof(*hbd_status) + ((MPI3MR_MAX_NUM_HDB - 1) * sizeof(*hbd_status_entry))); - hbd_status = kmalloc(length, GFP_KERNEL); + hbd_status = kzalloc(length, GFP_KERNEL); if (!hbd_status) return -ENOMEM; hbd_status_entry = &hbd_status->entry[0]; @@ -1466,7 +1466,8 @@ static long mpi3mr_bsg_pel_enable(struct mpi3mr_ioc *mrioc, static long mpi3mr_get_all_tgt_info(struct mpi3mr_ioc *mrioc, struct bsg_job *job) { - u16 num_devices = 0, i = 0, size; + u16 num_devices = 0, i = 0; + size_t size; unsigned long flags; struct mpi3mr_tgt_dev *tgtdev; struct mpi3mr_device_map_info *devmap_info = NULL; @@ -1492,8 +1493,8 @@ static long mpi3mr_get_all_tgt_info(struct mpi3mr_ioc *mrioc, return 0; } - kern_entrylen = num_devices * sizeof(*devmap_info); - size = sizeof(u64) + kern_entrylen; + kern_entrylen = (uint32_t)num_devices * sizeof(*devmap_info); + size = sizeof(u64) + (size_t)kern_entrylen; alltgt_info = kzalloc(size, GFP_KERNEL); if (!alltgt_info) return -ENOMEM; @@ -2384,7 +2385,7 @@ static long mpi3mr_bsg_process_mpt_cmds(struct bsg_job *job) long rval = -EINVAL; struct mpi3mr_ioc *mrioc = NULL; u8 *mpi_req = NULL, *sense_buff_k = NULL; - u8 mpi_msg_size = 0; + u32 mpi_msg_size = 0; struct mpi3mr_bsg_packet *bsg_req = NULL; struct mpi3mr_bsg_mptcmd *karg; struct mpi3mr_buf_entry *buf_entries = NULL; @@ -2538,7 +2539,15 @@ static long mpi3mr_bsg_process_mpt_cmds(struct bsg_job *job) rval = -EINVAL; goto out; } - memcpy(mpi_req, sgl_iter, buf_entries->buf_len); + if (sgl_iter + mpi_msg_size > + dout_buf + job->request_payload.payload_len) { + dprint_bsg_err(mrioc, "%s: MPI request buf exceeds dout_buf\n", + __func__); + mutex_unlock(&mrioc->bsg_cmds.mutex); + rval = -EINVAL; + goto out; + } + memcpy(mpi_req, sgl_iter, mpi_msg_size); break; default: invalid_be = 1; @@ -2737,10 +2746,12 @@ static long mpi3mr_bsg_process_mpt_cmds(struct bsg_job *job) } if (block_io) { tgtdev = mpi3mr_get_tgtdev_by_handle(mrioc, dev_handle); - if (tgtdev && tgtdev->starget && tgtdev->starget->hostdata) { - stgt_priv = (struct mpi3mr_stgt_priv_data *) - tgtdev->starget->hostdata; - atomic_inc(&stgt_priv->block_io); + if (tgtdev) { + if (tgtdev->starget && tgtdev->starget->hostdata) { + stgt_priv = (struct mpi3mr_stgt_priv_data *) + tgtdev->starget->hostdata; + atomic_inc(&stgt_priv->block_io); + } mpi3mr_tgtdev_put(tgtdev); } } @@ -2774,6 +2785,8 @@ static long mpi3mr_bsg_process_mpt_cmds(struct bsg_job *job) dprint_bsg_err(mrioc, "%s: posting bsg request is failed\n", __func__); rval = -EAGAIN; + if (block_io && stgt_priv) + atomic_dec(&stgt_priv->block_io); goto out_unlock; } wait_for_completion_timeout(&mrioc->bsg_cmds.done, @@ -2935,7 +2948,8 @@ static long mpi3mr_bsg_process_mpt_cmds(struct bsg_job *job) void mpi3mr_app_save_logdata_th(struct mpi3mr_ioc *mrioc, char *event_data, u16 event_data_size) { - u32 index = mrioc->logdata_buf_idx, sz; + u32 index = mrioc->logdata_buf_idx; + size_t entry_payload_len, sz; struct mpi3mr_logdata_entry *entry; if (!(mrioc->logdata_buf)) @@ -2944,7 +2958,12 @@ void mpi3mr_app_save_logdata_th(struct mpi3mr_ioc *mrioc, char *event_data, entry = (struct mpi3mr_logdata_entry *) (mrioc->logdata_buf + (index * mrioc->logdata_entry_sz)); entry->valid_entry = 1; - sz = min(mrioc->logdata_entry_sz, event_data_size); + if (mrioc->logdata_entry_sz > MPI3MR_BSG_LOGDATA_ENTRY_HEADER_SZ) + entry_payload_len = (size_t)mrioc->logdata_entry_sz - + MPI3MR_BSG_LOGDATA_ENTRY_HEADER_SZ; + else + entry_payload_len = 0; + sz = min_t(size_t, entry_payload_len, event_data_size); memcpy(entry->data, event_data, sz); mrioc->logdata_buf_idx = ((++index) % MPI3MR_BSG_LOGDATA_MAX_ENTRIES); diff --git a/drivers/scsi/mpi3mr/mpi3mr_fw.c b/drivers/scsi/mpi3mr/mpi3mr_fw.c index 681868716ebd..5c2547bb67a5 100644 --- a/drivers/scsi/mpi3mr/mpi3mr_fw.c +++ b/drivers/scsi/mpi3mr/mpi3mr_fw.c @@ -124,11 +124,16 @@ void mpi3mr_build_zero_len_sge(void *paddr) void *mpi3mr_get_reply_virt_addr(struct mpi3mr_ioc *mrioc, dma_addr_t phys_addr) { + u64 offset; + if (!phys_addr) return NULL; + offset = phys_addr - mrioc->reply_buf_dma; + if ((phys_addr < mrioc->reply_buf_dma) || - (phys_addr > mrioc->reply_buf_dma_max_address)) + (phys_addr > mrioc->reply_buf_dma_max_address - mrioc->reply_sz) || + do_div(offset, mrioc->reply_sz)) return NULL; return mrioc->reply_buf + (phys_addr - mrioc->reply_buf_dma); @@ -137,9 +142,19 @@ void *mpi3mr_get_reply_virt_addr(struct mpi3mr_ioc *mrioc, void *mpi3mr_get_sensebuf_virt_addr(struct mpi3mr_ioc *mrioc, dma_addr_t phys_addr) { + u64 offset; + if (!phys_addr) return NULL; + offset = phys_addr - mrioc->sense_buf_dma; + + if (phys_addr < mrioc->sense_buf_dma || + (phys_addr > mrioc->sense_buf_dma + + (mrioc->num_sense_bufs * MPI3MR_SENSE_BUF_SZ) - MPI3MR_SENSE_BUF_SZ) || + do_div(offset, MPI3MR_SENSE_BUF_SZ)) + return NULL; + return mrioc->sense_buf + (phys_addr - mrioc->sense_buf_dma); } diff --git a/drivers/scsi/mpi3mr/mpi3mr_os.c b/drivers/scsi/mpi3mr/mpi3mr_os.c index 0f7380448718..991e29a8d382 100644 --- a/drivers/scsi/mpi3mr/mpi3mr_os.c +++ b/drivers/scsi/mpi3mr/mpi3mr_os.c @@ -233,10 +233,11 @@ static void mpi3mr_fwevt_add_to_list(struct mpi3mr_ioc *mrioc, { unsigned long flags; - if (!mrioc->fwevt_worker_thread) - return; - spin_lock_irqsave(&mrioc->fwevt_lock, flags); + if (!mrioc->fwevt_worker_thread) { + spin_unlock_irqrestore(&mrioc->fwevt_lock, flags); + return; + } /* get fwevt reference count while adding it to fwevt_list */ mpi3mr_fwevt_get(fwevt); INIT_LIST_HEAD(&fwevt->list); @@ -2154,9 +2155,11 @@ static void mpi3mr_fwevt_bh(struct mpi3mr_ioc *mrioc, mpi3mr_fwevt_del_from_list(mrioc, fwevt); mrioc->current_event = fwevt; - if (mrioc->stop_drv_processing) { - dprint_event_bh(mrioc, "ignoring event(0x%02x) in the bottom half handler\n" - "due to stop_drv_processing\n", fwevt->event_id); + if (mrioc->stop_drv_processing || mrioc->pci_err_recovery) { + dprint_event_bh(mrioc, + "ignoring event(0x%02x) in the bottom half handler\n" + "due to stop_drv_processing or pci_err_recovery\n", + fwevt->event_id); goto out; } @@ -2426,7 +2429,8 @@ static void mpi3mr_dev_rmhs_complete_iou(struct mpi3mr_ioc *mrioc, ioc_info(mrioc, "%s :dev removal handshake completed successfully: handle(0x%04x)\n", __func__, drv_cmd->dev_handle); - clear_bit(drv_cmd->dev_handle, mrioc->removepend_bitmap); + if (drv_cmd->dev_handle < mrioc->facts.max_devhandle) + clear_bit(drv_cmd->dev_handle, mrioc->removepend_bitmap); } if (!list_empty(&mrioc->delayed_rmhs_list)) { @@ -2540,12 +2544,29 @@ static void mpi3mr_dev_rmhs_send_tm(struct mpi3mr_ioc *mrioc, u16 handle, struct mpi3mr_tgt_dev *tgtdev = NULL; unsigned long flags; + if (handle >= mrioc->facts.max_devhandle) { + ioc_err(mrioc, "dev_remove_hs: handle(0x%04x) >= max_devhandle(0x%04x)\n", + handle, mrioc->facts.max_devhandle); + if (drv_cmd) { + cmd_idx = drv_cmd->host_tag - MPI3MR_HOSTTAG_DEVRMCMD_MIN; + drv_cmd->state = MPI3MR_CMD_NOTUSED; + drv_cmd->callback = NULL; + drv_cmd->dev_handle = MPI3MR_INVALID_DEV_HANDLE; + drv_cmd->retry_count = 0; + clear_bit(cmd_idx, mrioc->devrem_bitmap); + } + return; + } + spin_lock_irqsave(&mrioc->tgtdev_lock, flags); tgtdev = __mpi3mr_get_tgtdev_by_handle(mrioc, handle); if (tgtdev && (iou_rc == MPI3_CTRL_OP_REMOVE_DEVICE)) tgtdev->state = MPI3MR_DEV_REMOVE_HS_STARTED; spin_unlock_irqrestore(&mrioc->tgtdev_lock, flags); + if (tgtdev) + mpi3mr_tgtdev_put(tgtdev); + if (drv_cmd) goto issue_cmd; do { @@ -2768,12 +2789,28 @@ static void mpi3mr_pcietopochg_evt_th(struct mpi3mr_ioc *mrioc, struct mpi3_event_data_pcie_topology_change_list *topo_evt = (struct mpi3_event_data_pcie_topology_change_list *)event_reply->event_data; int i; - u16 handle; - u8 reason_code; + u16 handle, avail_len; + u8 reason_code, max_entries, num_entries; struct mpi3mr_tgt_dev *tgtdev = NULL; struct mpi3mr_stgt_priv_data *scsi_tgt_priv_data = NULL; - for (i = 0; i < topo_evt->num_entries; i++) { + avail_len = event_reply->event_data_length * 4; + if (avail_len < offsetof(struct mpi3_event_data_pcie_topology_change_list, port_entry)) { + ioc_err(mrioc, "PCIe topology event: event data too small (%u bytes)\n", + avail_len); + return; + } + max_entries = (avail_len - + offsetof(struct mpi3_event_data_pcie_topology_change_list, port_entry)) / + sizeof(struct mpi3_event_pcie_topo_port_entry); + num_entries = topo_evt->num_entries; + if (num_entries > max_entries) { + ioc_err(mrioc, "PCIe topology event: num_entries(%d) exceeds max(%d)\n", + num_entries, max_entries); + return; + } + + for (i = 0; i < num_entries; i++) { handle = le16_to_cpu(topo_evt->port_entry[i].attached_dev_handle); if (!handle) continue; @@ -2834,12 +2871,28 @@ static void mpi3mr_sastopochg_evt_th(struct mpi3mr_ioc *mrioc, struct mpi3_event_data_sas_topology_change_list *topo_evt = (struct mpi3_event_data_sas_topology_change_list *)event_reply->event_data; int i; - u16 handle; - u8 reason_code; + u16 handle, avail_len; + u8 reason_code, max_entries, num_entries; struct mpi3mr_tgt_dev *tgtdev = NULL; struct mpi3mr_stgt_priv_data *scsi_tgt_priv_data = NULL; - for (i = 0; i < topo_evt->num_entries; i++) { + avail_len = event_reply->event_data_length * 4; + if (avail_len < offsetof(struct mpi3_event_data_sas_topology_change_list, phy_entry)) { + ioc_err(mrioc, "SAS topology event: event data too small (%u bytes)\n", + avail_len); + return; + } + max_entries = (avail_len - + offsetof(struct mpi3_event_data_sas_topology_change_list, phy_entry)) / + sizeof(struct mpi3_event_sas_topo_phy_entry); + num_entries = topo_evt->num_entries; + if (num_entries > max_entries) { + ioc_err(mrioc, "SAS topology event: num_entries(%d) exceeds max(%d)\n", + num_entries, max_entries); + return; + } + + for (i = 0; i < num_entries; i++) { handle = le16_to_cpu(topo_evt->phy_entry[i].attached_dev_handle); if (!handle) continue; @@ -3109,7 +3162,7 @@ void mpi3mr_add_event_wait_for_device_refresh(struct mpi3mr_ioc *mrioc) void mpi3mr_os_handle_events(struct mpi3mr_ioc *mrioc, struct mpi3_event_notification_reply *event_reply) { - u16 evt_type, sz; + u16 evt_type, sz, avail_reply_room; struct mpi3mr_fwevt *fwevt = NULL; bool ack_req = 0, process_evt_bh = 0; @@ -3170,7 +3223,12 @@ void mpi3mr_os_handle_events(struct mpi3mr_ioc *mrioc, case MPI3_EVENT_DEVICE_INFO_CHANGED: case MPI3_EVENT_LOG_DATA: - sz = event_reply->event_data_length * 4; + if (mrioc->reply_sz > offsetof(struct mpi3_event_notification_reply, event_data)) + avail_reply_room = mrioc->reply_sz - + offsetof(struct mpi3_event_notification_reply, event_data); + else + avail_reply_room = 0; + sz = min_t(u16, event_reply->event_data_length * 4, avail_reply_room); mpi3mr_app_save_logdata_th(mrioc, (char *)event_reply->event_data, sz); break; @@ -3204,7 +3262,12 @@ void mpi3mr_os_handle_events(struct mpi3mr_ioc *mrioc, dprint_event_th(mrioc, "scheduling bottom half handler for event(0x%02x) - (0x%08x), ack_required=%d\n", evt_type, le32_to_cpu(event_reply->event_context), ack_req); - sz = event_reply->event_data_length * 4; + if (mrioc->reply_sz > offsetof(struct mpi3_event_notification_reply, event_data)) + avail_reply_room = mrioc->reply_sz - + offsetof(struct mpi3_event_notification_reply, event_data); + else + avail_reply_room = 0; + sz = min_t(u16, event_reply->event_data_length * 4, avail_reply_room); fwevt = mpi3mr_alloc_fwevt(sz); if (!fwevt) { dprint_event_th(mrioc, diff --git a/drivers/scsi/mpi3mr/mpi3mr_transport.c b/drivers/scsi/mpi3mr/mpi3mr_transport.c index 232af978d737..29013d0fea54 100644 --- a/drivers/scsi/mpi3mr/mpi3mr_transport.c +++ b/drivers/scsi/mpi3mr/mpi3mr_transport.c @@ -1090,6 +1090,13 @@ void mpi3mr_update_links(struct mpi3mr_ioc *mrioc, return; } + if (phy_number >= mr_sas_node->num_phys) { + spin_unlock_irqrestore(&mrioc->sas_node_lock, flags); + ioc_err(mrioc, "%s: phy_number(%d) >= num_phys(%d)\n", + __func__, phy_number, mr_sas_node->num_phys); + return; + } + mr_sas_phy = &mr_sas_node->phy[phy_number]; mr_sas_phy->attached_handle = handle; spin_unlock_irqrestore(&mrioc->sas_node_lock, flags); diff --git a/drivers/scsi/pm8001/pm8001_defs.h b/drivers/scsi/pm8001/pm8001_defs.h index 4e19d61dffbb..a9605ca317f3 100644 --- a/drivers/scsi/pm8001/pm8001_defs.h +++ b/drivers/scsi/pm8001/pm8001_defs.h @@ -41,6 +41,104 @@ #ifndef _PM8001_DEFS_H_ #define _PM8001_DEFS_H_ +#include + +#ifdef __LITTLE_ENDIAN_BITFIELD +struct sas_identify_frame_local { + /* Byte 0 */ + u8 frame_type:4; + u8 dev_type:3; + u8 _un0:1; + + /* Byte 1 */ + u8 _un1; + + /* Byte 2 */ + union { + struct { + u8 _un20:1; + u8 smp_iport:1; + u8 stp_iport:1; + u8 ssp_iport:1; + u8 _un247:4; + }; + u8 initiator_bits; + }; + + /* Byte 3 */ + union { + struct { + u8 _un30:1; + u8 smp_tport:1; + u8 stp_tport:1; + u8 ssp_tport:1; + u8 _un347:4; + }; + u8 target_bits; + }; + + /* Byte 4 - 11 */ + u8 _un4_11[8]; + + /* Byte 12 - 19 */ + u8 sas_addr[SAS_ADDR_SIZE]; + + /* Byte 20 */ + u8 phy_id; + + u8 _un21_27[7]; + +} __packed; + +#elif defined(__BIG_ENDIAN_BITFIELD) +struct sas_identify_frame_local { + /* Byte 0 */ + u8 _un0:1; + u8 dev_type:3; + u8 frame_type:4; + + /* Byte 1 */ + u8 _un1; + + /* Byte 2 */ + union { + struct { + u8 _un247:4; + u8 ssp_iport:1; + u8 stp_iport:1; + u8 smp_iport:1; + u8 _un20:1; + }; + u8 initiator_bits; + }; + + /* Byte 3 */ + union { + struct { + u8 _un347:4; + u8 ssp_tport:1; + u8 stp_tport:1; + u8 smp_tport:1; + u8 _un30:1; + }; + u8 target_bits; + }; + + /* Byte 4 - 11 */ + u8 _un4_11[8]; + + /* Byte 12 - 19 */ + u8 sas_addr[SAS_ADDR_SIZE]; + + /* Byte 20 */ + u8 phy_id; + + u8 _un21_27[7]; +} __packed; +#else +#error "Bitfield order not defined!" +#endif + enum chip_flavors { chip_8001, chip_8008, diff --git a/drivers/scsi/pm8001/pm8001_hwi.c b/drivers/scsi/pm8001/pm8001_hwi.c index fff8d877abb9..55a01e533fd1 100644 --- a/drivers/scsi/pm8001/pm8001_hwi.c +++ b/drivers/scsi/pm8001/pm8001_hwi.c @@ -3208,7 +3208,7 @@ hw_event_sata_phy_up(struct pm8001_hba_info *pm8001_ha, void *piomb) phy->sas_phy.oob_mode = SATA_OOB_MODE; sas_notify_phy_event(&phy->sas_phy, PHYE_OOB_DONE, GFP_ATOMIC); spin_lock_irqsave(&phy->sas_phy.frame_rcvd_lock, flags); - memcpy(phy->frame_rcvd, ((u8 *)&pPayload->sata_fis - 4), + memcpy(phy->frame_rcvd, &pPayload->sata_fis, sizeof(struct dev_to_host_fis)); phy->frame_rcvd_size = sizeof(struct dev_to_host_fis); phy->identify.target_port_protocols = SAS_PROTOCOL_SATA; diff --git a/drivers/scsi/pm8001/pm8001_hwi.h b/drivers/scsi/pm8001/pm8001_hwi.h index f1ce8df082b0..a21b1b37a8ea 100644 --- a/drivers/scsi/pm8001/pm8001_hwi.h +++ b/drivers/scsi/pm8001/pm8001_hwi.h @@ -42,6 +42,7 @@ #include #include +#include "pm8001_defs.h" /* for Request Opcode of IOMB */ @@ -229,8 +230,9 @@ struct hw_event_resp { __le32 lr_evt_status_phyid_portid; __le32 evt_param; __le32 npip_portstate; - struct sas_identify_frame sas_identify; + struct sas_identify_frame_local sas_identify; struct dev_to_host_fis sata_fis; + u32 _r_a; } __attribute__((packed, aligned(4))); diff --git a/drivers/scsi/pm8001/pm80xx_hwi.c b/drivers/scsi/pm8001/pm80xx_hwi.c index 2c0fa7ab33d2..659dbd603a03 100644 --- a/drivers/scsi/pm8001/pm80xx_hwi.c +++ b/drivers/scsi/pm8001/pm80xx_hwi.c @@ -3296,7 +3296,7 @@ hw_event_sata_phy_up(struct pm8001_hba_info *pm8001_ha, void *piomb) phy->sas_phy.oob_mode = SATA_OOB_MODE; sas_notify_phy_event(&phy->sas_phy, PHYE_OOB_DONE, GFP_ATOMIC); spin_lock_irqsave(&phy->sas_phy.frame_rcvd_lock, flags); - memcpy(phy->frame_rcvd, ((u8 *)&pPayload->sata_fis - 4), + memcpy(phy->frame_rcvd, &pPayload->sata_fis, sizeof(struct dev_to_host_fis)); phy->frame_rcvd_size = sizeof(struct dev_to_host_fis); phy->identify.target_port_protocols = SAS_PROTOCOL_SATA; diff --git a/drivers/scsi/pm8001/pm80xx_hwi.h b/drivers/scsi/pm8001/pm80xx_hwi.h index d8a63b7fed6a..d6796ba40df9 100644 --- a/drivers/scsi/pm8001/pm80xx_hwi.h +++ b/drivers/scsi/pm8001/pm80xx_hwi.h @@ -43,6 +43,7 @@ #include #include +#include "pm8001_defs.h" /* for Request Opcode of IOMB */ #define OPC_INB_ECHO 1 /* 0x000 */ @@ -236,102 +237,6 @@ /* Port recovery timeout, 10000 ms for PM8006 controller */ #define CHIP_8006_PORT_RECOVERY_TIMEOUT 0x640000 -#ifdef __LITTLE_ENDIAN_BITFIELD -struct sas_identify_frame_local { - /* Byte 0 */ - u8 frame_type:4; - u8 dev_type:3; - u8 _un0:1; - - /* Byte 1 */ - u8 _un1; - - /* Byte 2 */ - union { - struct { - u8 _un20:1; - u8 smp_iport:1; - u8 stp_iport:1; - u8 ssp_iport:1; - u8 _un247:4; - }; - u8 initiator_bits; - }; - - /* Byte 3 */ - union { - struct { - u8 _un30:1; - u8 smp_tport:1; - u8 stp_tport:1; - u8 ssp_tport:1; - u8 _un347:4; - }; - u8 target_bits; - }; - - /* Byte 4 - 11 */ - u8 _un4_11[8]; - - /* Byte 12 - 19 */ - u8 sas_addr[SAS_ADDR_SIZE]; - - /* Byte 20 */ - u8 phy_id; - - u8 _un21_27[7]; - -} __packed; - -#elif defined(__BIG_ENDIAN_BITFIELD) -struct sas_identify_frame_local { - /* Byte 0 */ - u8 _un0:1; - u8 dev_type:3; - u8 frame_type:4; - - /* Byte 1 */ - u8 _un1; - - /* Byte 2 */ - union { - struct { - u8 _un247:4; - u8 ssp_iport:1; - u8 stp_iport:1; - u8 smp_iport:1; - u8 _un20:1; - }; - u8 initiator_bits; - }; - - /* Byte 3 */ - union { - struct { - u8 _un347:4; - u8 ssp_tport:1; - u8 stp_tport:1; - u8 smp_tport:1; - u8 _un30:1; - }; - u8 target_bits; - }; - - /* Byte 4 - 11 */ - u8 _un4_11[8]; - - /* Byte 12 - 19 */ - u8 sas_addr[SAS_ADDR_SIZE]; - - /* Byte 20 */ - u8 phy_id; - - u8 _un21_27[7]; -} __packed; -#else -#error "Bitfield order not defined!" -#endif - struct mpi_msg_hdr { __le32 header; /* Bits [11:0] - Message operation code */ /* Bits [15:12] - Message Category */ @@ -427,8 +332,9 @@ struct hw_event_resp { __le32 lr_status_evt_portid; __le32 evt_param; __le32 phyid_npip_portstate; - struct sas_identify_frame sas_identify; + struct sas_identify_frame_local sas_identify; struct dev_to_host_fis sata_fis; + u32 _r_a; } __attribute__((packed, aligned(4))); /* diff --git a/drivers/scsi/scsi_debug.c b/drivers/scsi/scsi_debug.c index 3346562275f8..8290feadc212 100644 --- a/drivers/scsi/scsi_debug.c +++ b/drivers/scsi/scsi_debug.c @@ -67,9 +67,6 @@ static const char *sdebug_version_date = "20210520"; #define MY_NAME "scsi_debug" -/* Additional Sense Code Qualifier (ASCQ) */ -#define ACK_NAK_TO 0x3 - /* Default values for driver parameters */ #define DEF_NUM_HOST 1 #define DEF_NUM_TGTS 1 @@ -1320,9 +1317,13 @@ static void mk_sense_invalid_fld(struct scsi_cmnd *scp, sdev_printk(KERN_ERR, scp->device, "sense_buffer is NULL\n"); return; } - asc = c_d ? INVALID_FIELD_IN_CDB : INVALID_FIELD_IN_PARAM_LIST; + if (c_d) + asc = ASC_INVALID_FIELD_IN_CDB; + else + asc = ASC_INVALID_FIELD_IN_PARAMETER_LIST; memset(sbuff, 0, SCSI_SENSE_BUFFERSIZE); - scsi_build_sense(scp, sdebug_dsense, ILLEGAL_REQUEST, asc, 0); + scsi_set_sense(scp, sdebug_dsense, ILLEGAL_REQUEST, + scsi_sense_code(asc, 0)); memset(sks, 0, sizeof(sks)); sks[0] = 0x80; if (c_d) @@ -1346,7 +1347,7 @@ static void mk_sense_invalid_fld(struct scsi_cmnd *scp, my_name, asc, c_d ? 'C' : 'D', in_byte, in_bit); } -static void mk_sense_buffer(struct scsi_cmnd *scp, int key, int asc, int asq) +static void mk_sense_buffer(struct scsi_cmnd *scp, u8 key, u16 code) { if (!scp->sense_buffer) { sdev_printk(KERN_ERR, scp->device, "sense_buffer is NULL\n"); @@ -1354,16 +1355,16 @@ static void mk_sense_buffer(struct scsi_cmnd *scp, int key, int asc, int asq) } memset(scp->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE); - scsi_build_sense(scp, sdebug_dsense, key, asc, asq); + scsi_set_sense(scp, sdebug_dsense, key, code); if (sdebug_verbose) sdev_printk(KERN_INFO, scp->device, - "%s: [sense_key,asc,ascq]: [0x%x,0x%x,0x%x]\n", - my_name, key, asc, asq); + "%s: [sense_key,sense_code]: [0x%02x,0x%04x]\n", + my_name, key, code); } /* Sense data that has information fields for tapes */ -static void mk_sense_info_tape(struct scsi_cmnd *scp, int key, int asc, int asq, +static void mk_sense_info_tape(struct scsi_cmnd *scp, u8 key, u16 code, unsigned int information, unsigned char tape_flags) { if (!scp->sense_buffer) { @@ -1372,7 +1373,7 @@ static void mk_sense_info_tape(struct scsi_cmnd *scp, int key, int asc, int asq, } memset(scp->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE); - scsi_build_sense(scp, /* sdebug_dsense */ 0, key, asc, asq); + scsi_set_sense(scp, /* sdebug_dsense */ 0, key, code); /* only fixed format so far */ scp->sense_buffer[0] |= 0x80; /* valid */ @@ -1381,13 +1382,13 @@ static void mk_sense_info_tape(struct scsi_cmnd *scp, int key, int asc, int asq, if (sdebug_verbose) sdev_printk(KERN_INFO, scp->device, - "%s: [sense_key,asc,ascq]: [0x%x,0x%x,0x%x]\n", - my_name, key, asc, asq); + "%s: [sense_key,sense_code]: [0x%02x,0x%04x]\n", + my_name, key, code); } static void mk_sense_invalid_opcode(struct scsi_cmnd *scp) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_OPCODE, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_COMMAND_OP_CODE); } static int scsi_debug_ioctl(struct scsi_device *dev, unsigned int cmd, @@ -1484,46 +1485,43 @@ static int make_ua(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) switch (k) { case SDEBUG_UA_POR: - mk_sense_buffer(scp, UNIT_ATTENTION, UA_RESET_ASC, - POWER_ON_RESET_ASCQ); + mk_sense_buffer(scp, UNIT_ATTENTION, + POWER_ON_RESET_OR_BUS_DEVICE_RESET_OCCURRED); if (sdebug_verbose) cp = "power on reset"; break; case SDEBUG_UA_POOCCUR: - mk_sense_buffer(scp, UNIT_ATTENTION, UA_RESET_ASC, - POWER_ON_OCCURRED_ASCQ); + mk_sense_buffer(scp, UNIT_ATTENTION, POWER_ON_OCCURRED); if (sdebug_verbose) cp = "power on occurred"; break; case SDEBUG_UA_BUS_RESET: - mk_sense_buffer(scp, UNIT_ATTENTION, UA_RESET_ASC, - BUS_RESET_ASCQ); + mk_sense_buffer(scp, UNIT_ATTENTION, + SCSI_BUS_RESET_OCCURRED); if (sdebug_verbose) cp = "bus reset"; break; case SDEBUG_UA_MODE_CHANGED: - mk_sense_buffer(scp, UNIT_ATTENTION, UA_CHANGED_ASC, - MODE_CHANGED_ASCQ); + mk_sense_buffer(scp, UNIT_ATTENTION, + MODE_PARAMETERS_CHANGED); if (sdebug_verbose) cp = "mode parameters changed"; break; case SDEBUG_UA_CAPACITY_CHANGED: - mk_sense_buffer(scp, UNIT_ATTENTION, UA_CHANGED_ASC, - CAPACITY_CHANGED_ASCQ); + mk_sense_buffer(scp, UNIT_ATTENTION, + CAPACITY_DATA_HAS_CHANGED); if (sdebug_verbose) cp = "capacity data changed"; break; case SDEBUG_UA_MICROCODE_CHANGED: mk_sense_buffer(scp, UNIT_ATTENTION, - TARGET_CHANGED_ASC, - MICROCODE_CHANGED_ASCQ); + MICROCODE_HAS_BEEN_CHANGED); if (sdebug_verbose) cp = "microcode has been changed"; break; case SDEBUG_UA_MICROCODE_CHANGED_WO_RESET: mk_sense_buffer(scp, UNIT_ATTENTION, - TARGET_CHANGED_ASC, - MICROCODE_CHANGED_WO_RESET_ASCQ); + MICROCODE_HAS_BEEN_CHANGED_WITHOUT_RESET); if (sdebug_verbose) cp = "microcode has been changed without reset"; break; @@ -1539,14 +1537,13 @@ static int make_ua(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) if (sdebug_scsi_level >= 6) /* SPC-4 and above */ clear_luns_changed_on_target(devip); mk_sense_buffer(scp, UNIT_ATTENTION, - TARGET_CHANGED_ASC, - LUNS_CHANGED_ASCQ); + REPORTED_LUNS_DATA_HAS_CHANGED); if (sdebug_verbose) cp = "reported luns data has changed"; break; case SDEBUG_UA_NOT_READY_TO_READY: - mk_sense_buffer(scp, UNIT_ATTENTION, UA_READY_ASC, - 0); + mk_sense_buffer(scp, UNIT_ATTENTION, + NOT_READY_TO_READY_CHANGE_MEDIUM_MAY_HAVE_CHANGED); if (sdebug_verbose) cp = "not ready to ready transition/media change"; break; @@ -2184,14 +2181,14 @@ static int resp_requests(struct scsi_cmnd *scp, if (dsense) { arr[0] = 0x72; arr[1] = NOT_READY; - arr[2] = LOGICAL_UNIT_NOT_READY; + arr[2] = ASC_LU_NOT_READY; arr[3] = (stopped_state == 2) ? 0x1 : 0x2; len = 8; } else { arr[0] = 0x70; arr[2] = NOT_READY; /* NO_SENSE in sense_key */ arr[7] = 0xa; /* 18 byte sense buffer */ - arr[12] = LOGICAL_UNIT_NOT_READY; + arr[12] = ASC_LU_NOT_READY; arr[13] = (stopped_state == 2) ? 0x1 : 0x2; } } else if ((iec_m_pg[2] & 0x4) && (6 == (iec_m_pg[3] & 0xf))) { @@ -2199,14 +2196,14 @@ static int resp_requests(struct scsi_cmnd *scp, if (dsense) { arr[0] = 0x72; arr[1] = 0x0; /* NO_SENSE in sense_key */ - arr[2] = THRESHOLD_EXCEEDED; + arr[2] = ASC_FAILURE_PREDICTION_THRESHOLD_EXCEEDED; arr[3] = 0xff; /* Failure prediction(false) */ len = 8; } else { arr[0] = 0x70; arr[2] = 0x0; /* NO_SENSE in sense_key */ arr[7] = 0xa; /* 18 byte sense buffer */ - arr[12] = THRESHOLD_EXCEEDED; + arr[12] = ASC_FAILURE_PREDICTION_THRESHOLD_EXCEEDED; arr[13] = 0xff; /* Failure prediction(false) */ } } else { /* nothing to report */ @@ -2457,8 +2454,7 @@ static int resp_rsup_opcodes(struct scsi_cmnd *scp, a_len = alloc_len; arr = kzalloc((a_len < 256) ? 320 : a_len + 64, GFP_ATOMIC); if (NULL == arr) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, INSUFF_RES_ASC, - INSUFF_RES_ASCQ); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INSUFFICIENT_RESOURCES); return check_condition_result; } switch (reporting_opts) { @@ -2924,8 +2920,9 @@ static int resp_mode_sense(struct scsi_cmnd *scp, else bd_len = 0; alloc_len = msense_6 ? cmd[4] : get_unaligned_be16(cmd + 7); - if (0x3 == pcontrol) { /* Saving values not supported */ - mk_sense_buffer(scp, ILLEGAL_REQUEST, SAVING_PARAMS_UNSUP, 0); + if (0x3 == pcontrol) { + mk_sense_buffer(scp, ILLEGAL_REQUEST, + SAVING_PARAMETERS_NOT_SUPPORTED); return check_condition_result; } target_dev_id = ((devip->sdbg_host->shost->host_no + 1) * 2000) + @@ -3174,7 +3171,7 @@ static int resp_mode_select(struct scsi_cmnd *scp, (arr[off + 1] + 2); if ((pg_len + off) > param_len) { mk_sense_buffer(scp, ILLEGAL_REQUEST, - PARAMETER_LIST_LENGTH_ERR, 0); + PARAMETER_LIST_LENGTH_ERROR); return check_condition_result; } switch (mpage) { @@ -3256,7 +3253,7 @@ static int resp_ie_l_pg(unsigned char *arr) memcpy(arr, ie_l_pg, sizeof(ie_l_pg)); if (iec_m_pg[2] & 0x4) { /* TEST bit set */ - arr[4] = THRESHOLD_EXCEEDED; + arr[4] = ASC_FAILURE_PREDICTION_THRESHOLD_EXCEEDED; arr[5] = 0xff; } return sizeof(ie_l_pg); @@ -3413,7 +3410,8 @@ static int resp_locate(struct scsi_cmnd *scp, break; if (i < pos) { devip->tape_location[partition] = i; - mk_sense_buffer(scp, BLANK_CHECK, 0x05, 0); + mk_sense_buffer(scp, BLANK_CHECK, + LU_DOES_NOT_RESPOND_TO_SELECTION); return check_condition_result; } devip->tape_location[partition] = pos; @@ -3438,8 +3436,9 @@ static int resp_write_filemarks(struct scsi_cmnd *scp, for (i = 0, pos = devip->tape_location[partition]; i < count; i++, pos++) { if (pos >= devip->tape_eop[partition] - 1) { /* don't overwrite EOD */ devip->tape_location[partition] = devip->tape_eop[partition] - 1; - mk_sense_info_tape(scp, VOLUME_OVERFLOW, NO_ADDITIONAL_SENSE, - EOP_EOM_DETECTED_ASCQ, count, SENSE_FLAG_EOM); + mk_sense_info_tape(scp, VOLUME_OVERFLOW, + END_OF_PARTITION_MEDIUM_DETECTED, + count, SENSE_FLAG_EOM); return check_condition_result; } (devip->tape_blocks[partition] + pos)->fl_size = data; @@ -3540,31 +3539,28 @@ static int resp_space(struct scsi_cmnd *scp, is_fm: devip->tape_location[partition] = pos; - mk_sense_info_tape(scp, NO_SENSE, NO_ADDITIONAL_SENSE, - FILEMARK_DETECTED_ASCQ, count - i, - SENSE_FLAG_FILEMARK); + mk_sense_info_tape(scp, NO_SENSE, FILEMARK_DETECTED, + count - i, SENSE_FLAG_FILEMARK); return check_condition_result; is_eod: devip->tape_location[partition] = pos; - mk_sense_info_tape(scp, BLANK_CHECK, NO_ADDITIONAL_SENSE, - EOD_DETECTED_ASCQ, count - i, - 0); + mk_sense_info_tape(scp, BLANK_CHECK, END_OF_DATA_DETECTED, + count - i, 0); return check_condition_result; is_bop: devip->tape_location[partition] = 0; - mk_sense_info_tape(scp, NO_SENSE, NO_ADDITIONAL_SENSE, - BEGINNING_OF_P_M_DETECTED_ASCQ, count - i, - SENSE_FLAG_EOM); + mk_sense_info_tape(scp, NO_SENSE, + BEGINNING_OF_PARTITION_MEDIUM_DETECTED, + count - i, SENSE_FLAG_EOM); devip->tape_location[partition] = 0; return check_condition_result; is_eop: devip->tape_location[partition] = devip->tape_eop[partition] - 1; - mk_sense_info_tape(scp, MEDIUM_ERROR, NO_ADDITIONAL_SENSE, - EOP_EOM_DETECTED_ASCQ, (unsigned int)i, - SENSE_FLAG_EOM); + mk_sense_info_tape(scp, MEDIUM_ERROR, END_OF_PARTITION_MEDIUM_DETECTED, + (unsigned int)i, SENSE_FLAG_EOM); return check_condition_result; } @@ -3852,8 +3848,7 @@ static int check_zbc_access_params(struct scsi_cmnd *scp, /* For host-managed, reads cannot cross zone types boundaries */ if (zsp->z_type != zsp_end->z_type) { mk_sense_buffer(scp, ILLEGAL_REQUEST, - LBA_OUT_OF_RANGE, - READ_INVDATA_ASCQ); + ATTEMPT_TO_READ_INVALID_DATA); return check_condition_result; } return 0; @@ -3861,8 +3856,8 @@ static int check_zbc_access_params(struct scsi_cmnd *scp, /* Writing into a gap zone is not allowed */ if (zbc_zone_is_gap(zsp)) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, - ATTEMPT_ACCESS_GAP); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + ATTEMPT_TO_ACCESS_GAP_ZONE); return check_condition_result; } @@ -3870,8 +3865,7 @@ static int check_zbc_access_params(struct scsi_cmnd *scp, if (zbc_zone_is_conv(zsp)) { if (!zbc_zone_is_conv(zsp_end)) { mk_sense_buffer(scp, ILLEGAL_REQUEST, - LBA_OUT_OF_RANGE, - WRITE_BOUNDARY_ASCQ); + WRITE_BOUNDARY_VIOLATION); return check_condition_result; } return 0; @@ -3881,21 +3875,29 @@ static int check_zbc_access_params(struct scsi_cmnd *scp, /* Writes cannot cross sequential zone boundaries */ if (zsp_end != zsp) { mk_sense_buffer(scp, ILLEGAL_REQUEST, - LBA_OUT_OF_RANGE, - WRITE_BOUNDARY_ASCQ); + WRITE_BOUNDARY_VIOLATION); return check_condition_result; } /* Cannot write full zones */ if (zsp->z_cond == ZC5_FULL) { mk_sense_buffer(scp, ILLEGAL_REQUEST, - INVALID_FIELD_IN_CDB, 0); + INVALID_FIELD_IN_CDB); return check_condition_result; } /* Writes must be aligned to the zone WP */ if (lba != zsp->z_wp) { mk_sense_buffer(scp, ILLEGAL_REQUEST, - LBA_OUT_OF_RANGE, - UNALIGNED_WRITE_ASCQ); + UNALIGNED_WRITE_COMMAND); + 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, + UNALIGNED_WRITE_COMMAND); return check_condition_result; } } @@ -3905,8 +3907,7 @@ static int check_zbc_access_params(struct scsi_cmnd *scp, if (devip->max_open && devip->nr_exp_open >= devip->max_open) { mk_sense_buffer(scp, DATA_PROTECT, - INSUFF_RES_ASC, - INSUFF_ZONE_ASCQ); + INSUFFICIENT_ZONE_RESOURCES); return check_condition_result; } zbc_open_zone(devip, zsp, false); @@ -3923,17 +3924,18 @@ static inline int check_device_access_params struct sdebug_dev_info *devip = (struct sdebug_dev_info *)sdp->hostdata; if (lba + num > sdebug_capacity) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE); return check_condition_result; } /* transfer length excessive (tie in to block limits VPD page) */ if (num > sdebug_store_sectors) { /* needs work to find which cdb byte 'num' comes from */ - mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB); return check_condition_result; } if (write && unlikely(sdebug_wp)) { - mk_sense_buffer(scp, DATA_PROTECT, WRITE_PROTECTED, 0x2); + mk_sense_buffer(scp, DATA_PROTECT, LU_SOFTWARE_WRITE_PROTECTED); return check_condition_result; } if (sdebug_dev_is_zoned(devip)) @@ -4442,17 +4444,17 @@ static int resp_read_tape(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) i++, pos++, blp++) { devip->tape_location[partition] = pos + 1; if (IS_TAPE_BLOCK_FM(blp->fl_size)) { - mk_sense_info_tape(scp, NO_SENSE, NO_ADDITIONAL_SENSE, - FILEMARK_DETECTED_ASCQ, fixed ? num - i : size, - SENSE_FLAG_FILEMARK); + mk_sense_info_tape(scp, NO_SENSE, FILEMARK_DETECTED, + fixed ? num - i : size, + SENSE_FLAG_FILEMARK); scsi_set_resid(scp, (num - i) * size); return check_condition_result; } /* Assume no REW */ if (IS_TAPE_BLOCK_EOD(blp->fl_size)) { - mk_sense_info_tape(scp, BLANK_CHECK, NO_ADDITIONAL_SENSE, - EOD_DETECTED_ASCQ, fixed ? num - i : size, - 0); + mk_sense_info_tape(scp, BLANK_CHECK, + END_OF_DATA_DETECTED, + fixed ? num - i : size, 0); devip->tape_location[partition] = pos; scsi_set_resid(scp, (num - i) * size); return check_condition_result; @@ -4464,9 +4466,9 @@ static int resp_read_tape(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) if (fixed) { if (blp->fl_size != devip->tape_blksize) { scsi_set_resid(scp, (num - i) * size); - mk_sense_info_tape(scp, NO_SENSE, NO_ADDITIONAL_SENSE, - 0, num - i, - SENSE_FLAG_ILI); + mk_sense_info_tape(scp, NO_SENSE, + NO_ADDITIONAL_SENSE_INFORMATION, + num - i, SENSE_FLAG_ILI); return check_condition_result; } } else { @@ -4474,18 +4476,19 @@ static int resp_read_tape(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) if (blp->fl_size < size) scsi_set_resid(scp, size - blp->fl_size); if (!sili) { - mk_sense_info_tape(scp, NO_SENSE, NO_ADDITIONAL_SENSE, - 0, size - blp->fl_size, - SENSE_FLAG_ILI); + mk_sense_info_tape(scp, NO_SENSE, + NO_ADDITIONAL_SENSE_INFORMATION, + size - blp->fl_size, + SENSE_FLAG_ILI); return check_condition_result; } } } } if (pos >= devip->tape_eop[partition]) { - mk_sense_info_tape(scp, NO_SENSE, NO_ADDITIONAL_SENSE, - EOP_EOM_DETECTED_ASCQ, fixed ? num - i : size, - SENSE_FLAG_EOM); + mk_sense_info_tape(scp, NO_SENSE, + END_OF_PARTITION_MEDIUM_DETECTED, + fixed ? num - i : size, SENSE_FLAG_EOM); devip->tape_location[partition] = pos - 1; return check_condition_result; } @@ -4572,8 +4575,7 @@ static int resp_read_dt0(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) if (unlikely((SDEBUG_OPT_MEDIUM_ERR & sdebug_opts) && (lba <= (sdebug_medium_error_start + sdebug_medium_error_count - 1)) && ((lba + num) > sdebug_medium_error_start))) { - /* claim unrecoverable read error */ - mk_sense_buffer(scp, MEDIUM_ERROR, UNRECOVERED_READ_ERR, 0); + mk_sense_buffer(scp, MEDIUM_ERROR, UNRECOVERED_READ_ERROR); /* set info field and valid bit for fixed descriptor */ if (0x70 == (scp->sense_buffer[0] & 0x7f)) { scp->sense_buffer[0] |= 0x80; /* Valid bit */ @@ -4597,22 +4599,26 @@ static int resp_read_dt0(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) case 1: /* Guard tag error */ if (cmd[1] >> 5 != 3) { /* RDPROTECT != 3 */ sdeb_meta_read_unlock(sip); - mk_sense_buffer(scp, ABORTED_COMMAND, 0x10, 1); + mk_sense_buffer(scp, ABORTED_COMMAND, + LOGICAL_BLOCK_GUARD_CHECK_FAILED); return check_condition_result; } else if (scp->prot_flags & SCSI_PROT_GUARD_CHECK) { sdeb_meta_read_unlock(sip); - mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10, 1); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LOGICAL_BLOCK_GUARD_CHECK_FAILED); return illegal_condition_result; } break; case 3: /* Reference tag error */ if (cmd[1] >> 5 != 3) { /* RDPROTECT != 3 */ sdeb_meta_read_unlock(sip); - mk_sense_buffer(scp, ABORTED_COMMAND, 0x10, 3); + mk_sense_buffer(scp, ABORTED_COMMAND, + LOGICAL_BLOCK_REFERENCE_TAG_CHECK_FAILED); return check_condition_result; } else if (scp->prot_flags & SCSI_PROT_REF_CHECK) { sdeb_meta_read_unlock(sip); - mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10, 3); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LOGICAL_BLOCK_REFERENCE_TAG_CHECK_FAILED); return illegal_condition_result; } break; @@ -4630,16 +4636,18 @@ static int resp_read_dt0(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) if (unlikely((sdebug_opts & SDEBUG_OPT_RECOV_DIF_DIX) && atomic_read(&sdeb_inject_pending))) { if (sdebug_opts & SDEBUG_OPT_RECOVERED_ERR) { - mk_sense_buffer(scp, RECOVERED_ERROR, THRESHOLD_EXCEEDED, 0); + mk_sense_buffer(scp, RECOVERED_ERROR, + FAILURE_PREDICTION_THRESHOLD_EXCEEDED); atomic_set(&sdeb_inject_pending, 0); return check_condition_result; } else if (sdebug_opts & SDEBUG_OPT_DIF_ERR) { - /* Logical block guard check failed */ - mk_sense_buffer(scp, ABORTED_COMMAND, 0x10, 1); + mk_sense_buffer(scp, ABORTED_COMMAND, + LOGICAL_BLOCK_GUARD_CHECK_FAILED); atomic_set(&sdeb_inject_pending, 0); return illegal_condition_result; } else if (SDEBUG_OPT_DIX_ERR & sdebug_opts) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10, 1); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LOGICAL_BLOCK_GUARD_CHECK_FAILED); atomic_set(&sdeb_inject_pending, 0); return illegal_condition_result; } @@ -4757,6 +4765,11 @@ static unsigned int map_state(struct sdeb_store_info *sip, sector_t lba, return mapped; } +/* + * Callers may map the whole range of a write without checking how much of + * it was written. SBC-6 4.7.4.6.2 allows a deallocated LBA to become mapped + * at any time, and only requires an LBA that was written to be mapped. + */ static void map_region(struct sdeb_store_info *sip, sector_t lba, unsigned int len) { @@ -4846,16 +4859,14 @@ static int resp_write_tape(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) blp->fl_size = TAPE_BLOCK_EOD_FLAG; if (pos >= devip->tape_eop[partition] - 1) { mk_sense_info_tape(scp, VOLUME_OVERFLOW, - NO_ADDITIONAL_SENSE, EOP_EOM_DETECTED_ASCQ, - fixed ? num - i : transfer, - SENSE_FLAG_EOM); + END_OF_PARTITION_MEDIUM_DETECTED, + fixed ? num - i : transfer, SENSE_FLAG_EOM); return check_condition_result; } if (ew) { /* early warning */ mk_sense_info_tape(scp, NO_SENSE, - NO_ADDITIONAL_SENSE, EOP_EOM_DETECTED_ASCQ, - fixed ? num - i : transfer, - SENSE_FLAG_EOM); + END_OF_PARTITION_MEDIUM_DETECTED, + fixed ? num - i : transfer, SENSE_FLAG_EOM); return check_condition_result; } @@ -4877,8 +4888,7 @@ static int resp_write_dt0(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) if (unlikely(sdebug_opts & SDEBUG_OPT_UNALIGNED_WRITE && atomic_read(&sdeb_inject_pending))) { atomic_set(&sdeb_inject_pending, 0); - mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, - UNALIGNED_WRITE_ASCQ); + mk_sense_buffer(scp, ILLEGAL_REQUEST, UNALIGNED_WRITE_COMMAND); return check_condition_result; } @@ -4959,22 +4969,26 @@ static int resp_write_dt0(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) case 1: /* Guard tag error */ if (scp->prot_flags & SCSI_PROT_GUARD_CHECK) { sdeb_meta_write_unlock(sip); - mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10, 1); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LOGICAL_BLOCK_GUARD_CHECK_FAILED); return illegal_condition_result; } else if (scp->cmnd[1] >> 5 != 3) { /* WRPROTECT != 3 */ sdeb_meta_write_unlock(sip); - mk_sense_buffer(scp, ABORTED_COMMAND, 0x10, 1); + mk_sense_buffer(scp, ABORTED_COMMAND, + LOGICAL_BLOCK_GUARD_CHECK_FAILED); return check_condition_result; } break; case 3: /* Reference tag error */ if (scp->prot_flags & SCSI_PROT_REF_CHECK) { sdeb_meta_write_unlock(sip); - mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10, 3); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LOGICAL_BLOCK_REFERENCE_TAG_CHECK_FAILED); return illegal_condition_result; } else if (scp->cmnd[1] >> 5 != 3) { /* WRPROTECT != 3 */ sdeb_meta_write_unlock(sip); - mk_sense_buffer(scp, ABORTED_COMMAND, 0x10, 3); + mk_sense_buffer(scp, ABORTED_COMMAND, + LOGICAL_BLOCK_REFERENCE_TAG_CHECK_FAILED); return check_condition_result; } break; @@ -4985,9 +4999,9 @@ static int resp_write_dt0(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) if (unlikely(scsi_debug_lbp())) map_region(sip, lba, num); - /* If ZBC zone then bump its write pointer */ - if (sdebug_dev_is_zoned(devip)) - zbc_inc_wp(devip, lba, num); + /* If ZBC zone then bump its write pointer over the data written */ + if (sdebug_dev_is_zoned(devip) && ret > 0) + zbc_inc_wp(devip, lba, ret >> ilog2(sdebug_sector_size)); if (meta_data_locked) sdeb_meta_write_unlock(sip); @@ -5002,16 +5016,18 @@ static int resp_write_dt0(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) if (unlikely((sdebug_opts & SDEBUG_OPT_RECOV_DIF_DIX) && atomic_read(&sdeb_inject_pending))) { if (sdebug_opts & SDEBUG_OPT_RECOVERED_ERR) { - mk_sense_buffer(scp, RECOVERED_ERROR, THRESHOLD_EXCEEDED, 0); + mk_sense_buffer(scp, RECOVERED_ERROR, + FAILURE_PREDICTION_THRESHOLD_EXCEEDED); atomic_set(&sdeb_inject_pending, 0); return check_condition_result; } else if (sdebug_opts & SDEBUG_OPT_DIF_ERR) { - /* Logical block guard check failed */ - mk_sense_buffer(scp, ABORTED_COMMAND, 0x10, 1); + mk_sense_buffer(scp, ABORTED_COMMAND, + LOGICAL_BLOCK_GUARD_CHECK_FAILED); atomic_set(&sdeb_inject_pending, 0); return illegal_condition_result; } else if (sdebug_opts & SDEBUG_OPT_DIX_ERR) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10, 1); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LOGICAL_BLOCK_GUARD_CHECK_FAILED); atomic_set(&sdeb_inject_pending, 0); return illegal_condition_result; } @@ -5032,7 +5048,8 @@ static int resp_write_scat(struct scsi_cmnd *scp, struct sdeb_store_info *sip = devip2sip(devip, true); u8 wrprotect; u16 lbdof, num_lrd, k; - u32 num, num_by, bt_len, lbdof_blen, sg_off, cum_lb; + u32 num, bt_len, lbdof_blen, cum_lb; + u64 num_by, sg_off; u32 lb_size = sdebug_sector_size; u32 ei_lba; u64 lba; @@ -5074,7 +5091,7 @@ static int resp_write_scat(struct scsi_cmnd *scp, if (sdebug_verbose) sdev_printk(KERN_INFO, scp->device, "%s: LB Data Offset field bad\n", my_name); - mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB); return illegal_condition_result; } lbdof_blen = lbdof * lb_size; @@ -5082,7 +5099,7 @@ static int resp_write_scat(struct scsi_cmnd *scp, if (sdebug_verbose) sdev_printk(KERN_INFO, scp->device, "%s: LBA range descriptors don't fit\n", my_name); - mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB); return illegal_condition_result; } lrdp = kzalloc(lbdof_blen, GFP_ATOMIC | __GFP_NOWARN); @@ -5108,14 +5125,14 @@ static int resp_write_scat(struct scsi_cmnd *scp, num = get_unaligned_be32(up + 8); if (sdebug_verbose) sdev_printk(KERN_INFO, scp->device, - "%s: k=%d LBA=0x%llx num=%u sg_off=%u\n", + "%s: k=%d LBA=0x%llx num=%u sg_off=%llu\n", my_name, k, lba, num, sg_off); if (num == 0) continue; ret = check_device_access_params(scp, lba, num, true); if (ret) goto err_out_unlock; - num_by = num * lb_size; + num_by = (u64)num * lb_size; ei_lba = is_16 ? 0 : get_unaligned_be32(up + 12); if ((cum_lb + num) > bt_len) { @@ -5123,8 +5140,7 @@ static int resp_write_scat(struct scsi_cmnd *scp, sdev_printk(KERN_INFO, scp->device, "%s: sum of blocks > data provided\n", my_name); - mk_sense_buffer(scp, ILLEGAL_REQUEST, WRITE_ERROR_ASC, - 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, SSC_WRITE_ERROR); ret = illegal_condition_result; goto err_out_unlock; } @@ -5135,8 +5151,9 @@ static int resp_write_scat(struct scsi_cmnd *scp, ei_lba); if (prot_ret) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10, - prot_ret); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + scsi_sense_code(ASC_ID_CRC_OR_ECC_ERROR, + prot_ret)); ret = illegal_condition_result; goto err_out_unlock; } @@ -5146,10 +5163,13 @@ static int resp_write_scat(struct scsi_cmnd *scp, * Write ranges atomically to keep as close to pre-atomic * writes behaviour as possible. */ - ret = do_device_access(sip, scp, sg_off, lba, num, group, true, true); - /* If ZBC zone then bump its write pointer */ - if (sdebug_dev_is_zoned(devip)) - zbc_inc_wp(devip, lba, num); + ret = do_device_access(sip, scp, + min_t(u64, sg_off, scsi_bufflen(scp)), + lba, num, group, true, true); + /* If ZBC zone then bump its write pointer over the data written */ + if (sdebug_dev_is_zoned(devip) && ret > 0) + zbc_inc_wp(devip, lba, + ret >> ilog2(sdebug_sector_size)); if (unlikely(scsi_debug_lbp())) map_region(sip, lba, num); if (unlikely(-1 == ret)) { @@ -5157,24 +5177,26 @@ static int resp_write_scat(struct scsi_cmnd *scp, goto err_out_unlock; } else if (unlikely(sdebug_verbose && (ret < num_by))) sdev_printk(KERN_INFO, scp->device, - "%s: write: cdb indicated=%u, IO sent=%d bytes\n", + "%s: write: cdb indicated=%llu, IO sent=%d bytes\n", my_name, num_by, ret); if (unlikely((sdebug_opts & SDEBUG_OPT_RECOV_DIF_DIX) && atomic_read(&sdeb_inject_pending))) { if (sdebug_opts & SDEBUG_OPT_RECOVERED_ERR) { - mk_sense_buffer(scp, RECOVERED_ERROR, THRESHOLD_EXCEEDED, 0); + mk_sense_buffer(scp, RECOVERED_ERROR, + FAILURE_PREDICTION_THRESHOLD_EXCEEDED); atomic_set(&sdeb_inject_pending, 0); ret = check_condition_result; goto err_out_unlock; } else if (sdebug_opts & SDEBUG_OPT_DIF_ERR) { - /* Logical block guard check failed */ - mk_sense_buffer(scp, ABORTED_COMMAND, 0x10, 1); + mk_sense_buffer(scp, ABORTED_COMMAND, + LOGICAL_BLOCK_GUARD_CHECK_FAILED); atomic_set(&sdeb_inject_pending, 0); ret = illegal_condition_result; goto err_out_unlock; } else if (sdebug_opts & SDEBUG_OPT_DIX_ERR) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10, 1); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LOGICAL_BLOCK_GUARD_CHECK_FAILED); atomic_set(&sdeb_inject_pending, 0); ret = illegal_condition_result; goto err_out_unlock; @@ -5233,7 +5255,7 @@ static int resp_write_same(struct scsi_cmnd *scp, u64 lba, u32 num, if (-1 == ret) { ret = DID_ERROR << 16; - goto out; + goto unlock; } else if (sdebug_verbose && !ndob && (ret < lb_size)) sdev_printk(KERN_INFO, scp->device, "%s: %s: lb size=%u, IO sent=%d bytes\n", @@ -5250,8 +5272,9 @@ static int resp_write_same(struct scsi_cmnd *scp, u64 lba, u32 num, /* If ZBC zone then bump its write pointer */ if (sdebug_dev_is_zoned(devip)) zbc_inc_wp(devip, lba, num); - sdeb_data_write_unlock(sip); ret = 0; +unlock: + sdeb_data_write_unlock(sip); out: if (meta_data_locked) sdeb_meta_write_unlock(sip); @@ -5393,8 +5416,7 @@ static int resp_comp_write(struct scsi_cmnd *scp, dnum = 2 * num; arr = kcalloc(lb_size, dnum, GFP_ATOMIC); if (NULL == arr) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, INSUFF_RES_ASC, - INSUFF_RES_ASCQ); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INSUFFICIENT_RESOURCES); return check_condition_result; } @@ -5407,20 +5429,21 @@ static int resp_comp_write(struct scsi_cmnd *scp, "indicated=%u, IO sent=%d bytes\n", my_name, dnum * lb_size, ret); - sdeb_data_write_lock(sip); sdeb_meta_write_lock(sip); + sdeb_data_write_lock(sip); if (!comp_write_worker(sip, lba, num, arr, false)) { - mk_sense_buffer(scp, MISCOMPARE, MISCOMPARE_VERIFY_ASC, 0); + mk_sense_buffer(scp, MISCOMPARE, + MISCOMPARE_DURING_VERIFY_OPERATION); retval = check_condition_result; goto cleanup_unlock; } - /* Cover sip->map_storep (which map_region()) sets with data lock */ + /* Cover sip->map_storep (which map_region() sets) with the meta lock */ if (scsi_debug_lbp()) map_region(sip, lba, num); cleanup_unlock: - sdeb_meta_write_unlock(sip); sdeb_data_write_unlock(sip); + sdeb_meta_write_unlock(sip); cleanup_free: kfree(arr); return retval; @@ -5453,8 +5476,7 @@ static int resp_unmap(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) buf = kzalloc(scsi_bufflen(scp), GFP_ATOMIC); if (!buf) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, INSUFF_RES_ASC, - INSUFF_RES_ASCQ); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INSUFFICIENT_RESOURCES); return check_condition_result; } @@ -5592,7 +5614,8 @@ static int resp_sync_cache(struct scsi_cmnd *scp, num_blocks = get_unaligned_be32(cmd + 10); } if (lba + num_blocks > sdebug_capacity) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE); return check_condition_result; } if (!write_since_sync || (cmd[1] & 0x2)) @@ -5630,7 +5653,8 @@ static int resp_pre_fetch(struct scsi_cmnd *scp, nblks = get_unaligned_be32(cmd + 10); } if (lba + nblks > sdebug_capacity) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE); return check_condition_result; } if (!fsp) @@ -5801,8 +5825,7 @@ static int resp_verify(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) arr = kcalloc(lb_size, vnum, GFP_ATOMIC | __GFP_NOWARN); if (!arr) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, INSUFF_RES_ASC, - INSUFF_RES_ASCQ); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INSUFFICIENT_RESOURCES); return check_condition_result; } /* Not changing store, so only need read access */ @@ -5823,7 +5846,8 @@ static int resp_verify(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) } ret = 0; if (!comp_write_worker(sip, lba, vnum, arr, true)) { - mk_sense_buffer(scp, MISCOMPARE, MISCOMPARE_VERIFY_ASC, 0); + mk_sense_buffer(scp, MISCOMPARE, + MISCOMPARE_DURING_VERIFY_OPERATION); ret = check_condition_result; goto cleanup; } @@ -5862,7 +5886,8 @@ static int resp_report_zones(struct scsi_cmnd *scp, partial = cmd[14] & 0x80; if (zs_lba >= sdebug_capacity) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE); return check_condition_result; } @@ -5873,8 +5898,8 @@ static int resp_report_zones(struct scsi_cmnd *scp, arr = kzalloc(arr_len, GFP_ATOMIC | __GFP_NOWARN); if (!arr) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, INSUFF_RES_ASC, - INSUFF_RES_ASCQ); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + INSUFFICIENT_RESOURCES); return check_condition_result; } @@ -5939,8 +5964,7 @@ static int resp_report_zones(struct scsi_cmnd *scp, continue; break; default: - mk_sense_buffer(scp, ILLEGAL_REQUEST, - INVALID_FIELD_IN_CDB, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB); ret = check_condition_result; goto fini; } @@ -5988,6 +6012,7 @@ static int resp_atomic_write(struct scsi_cmnd *scp, u8 *cmd = scp->cmnd; u16 boundary, len; u64 lba, lba_tmp; + bool lbp = scsi_debug_lbp(); int ret; if (!scsi_debug_atomic_write()) { @@ -6005,13 +6030,13 @@ static int resp_atomic_write(struct scsi_cmnd *scp, if (sdebug_atomic_wr_align && do_div(lba_tmp, sdebug_atomic_wr_align)) { /* Does not meet alignment requirement */ - mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB); return check_condition_result; } if (sdebug_atomic_wr_gran && len % sdebug_atomic_wr_gran) { /* Does not meet alignment requirement */ - mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB); return check_condition_result; } @@ -6032,7 +6057,27 @@ static int resp_atomic_write(struct scsi_cmnd *scp, } } + ret = check_device_access_params(scp, lba, len, true); + if (ret) + return ret; + + /* + * Short atomic writes are not allowed: SBC-6 4.28.2 requires an + * atomic write that cannot complete to leave its LBAs unaltered, and + * do_device_access() would already have written part of it. + */ + if (scsi_bufflen(scp) < len * sdebug_sector_size) + return DID_ERROR << 16; + + if (lbp) + sdeb_meta_write_lock(sip); + ret = do_device_access(sip, scp, 0, lba, len, 0, true, true); + if (lbp) { + map_region(sip, lba, len); + sdeb_meta_write_unlock(sip); + } + if (unlikely(ret == -1)) return DID_ERROR << 16; if (unlikely(ret != len * sdebug_sector_size)) @@ -6072,8 +6117,8 @@ static int resp_open_zone(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) /* Check if all closed zones can be open */ if (devip->max_open && devip->nr_exp_open + devip->nr_closed > devip->max_open) { - mk_sense_buffer(scp, DATA_PROTECT, INSUFF_RES_ASC, - INSUFF_ZONE_ASCQ); + mk_sense_buffer(scp, DATA_PROTECT, + INSUFFICIENT_ZONE_RESOURCES); res = check_condition_result; goto fini; } @@ -6085,19 +6130,20 @@ static int resp_open_zone(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) /* Open the specified zone */ z_id = get_unaligned_be64(cmd + 2); if (z_id >= sdebug_capacity) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE); res = check_condition_result; goto fini; } zsp = zbc_zone(devip, z_id); if (z_id != zsp->z_start) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB); res = check_condition_result; goto fini; } if (zbc_zone_is_conv(zsp)) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB); res = check_condition_result; goto fini; } @@ -6107,8 +6153,7 @@ static int resp_open_zone(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) goto fini; if (devip->max_open && devip->nr_exp_open >= devip->max_open) { - mk_sense_buffer(scp, DATA_PROTECT, INSUFF_RES_ASC, - INSUFF_ZONE_ASCQ); + mk_sense_buffer(scp, DATA_PROTECT, INSUFFICIENT_ZONE_RESOURCES); res = check_condition_result; goto fini; } @@ -6152,19 +6197,20 @@ static int resp_close_zone(struct scsi_cmnd *scp, /* Close specified zone */ z_id = get_unaligned_be64(cmd + 2); if (z_id >= sdebug_capacity) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE); res = check_condition_result; goto fini; } zsp = zbc_zone(devip, z_id); if (z_id != zsp->z_start) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB); res = check_condition_result; goto fini; } if (zbc_zone_is_conv(zsp)) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB); res = check_condition_result; goto fini; } @@ -6224,19 +6270,20 @@ static int resp_finish_zone(struct scsi_cmnd *scp, /* Finish the specified zone */ z_id = get_unaligned_be64(cmd + 2); if (z_id >= sdebug_capacity) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE); res = check_condition_result; goto fini; } zsp = zbc_zone(devip, z_id); if (z_id != zsp->z_start) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB); res = check_condition_result; goto fini; } if (zbc_zone_is_conv(zsp)) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB); res = check_condition_result; goto fini; } @@ -6303,19 +6350,20 @@ static int resp_rwp_zone(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) z_id = get_unaligned_be64(cmd + 2); if (z_id >= sdebug_capacity) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, + LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE); res = check_condition_result; goto fini; } zsp = zbc_zone(devip, z_id); if (z_id != zsp->z_start) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB); res = check_condition_result; goto fini; } if (zbc_zone_is_conv(zsp)) { - mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0); + mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB); res = check_condition_result; goto fini; } @@ -7186,7 +7234,7 @@ static int schedule_resp(struct scsi_cmnd *cmnd, struct sdebug_dev_info *devip, cmnd->result = scsi_result; if (cmnd->result == 0 && unlikely(sdebug_opts & SDEBUG_OPT_TRANSPORT_ERR)) { if (atomic_read(&sdeb_inject_pending)) { - mk_sense_buffer(cmnd, ABORTED_COMMAND, TRANSPORT_PROBLEM, ACK_NAK_TO); + mk_sense_buffer(cmnd, ABORTED_COMMAND, ACK_NAK_TIMEOUT); atomic_set(&sdeb_inject_pending, 0); cmnd->result = check_condition_result; } @@ -8481,8 +8529,8 @@ static int __init scsi_debug_init(void) return -EINVAL; } - if (sdebug_physblk_exp > 15) { - pr_err("invalid physblk_exp %u\n", sdebug_physblk_exp); + if (sdebug_physblk_exp < 0 || sdebug_physblk_exp > 15) { + pr_err("invalid physblk_exp %d\n", sdebug_physblk_exp); return -EINVAL; } @@ -8979,7 +9027,8 @@ static int resp_not_ready(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) return 0; } } - mk_sense_buffer(scp, NOT_READY, LOGICAL_UNIT_NOT_READY, 0x1); + mk_sense_buffer(scp, NOT_READY, + LU_IS_IN_PROCESS_OF_BECOMING_READY); if (sdebug_verbose) sdev_printk(KERN_INFO, sdp, "%s: Not ready: in process of becoming ready\n", my_name); @@ -8997,7 +9046,8 @@ static int resp_not_ready(struct scsi_cmnd *scp, struct sdebug_dev_info *devip) return check_condition_result; } } - mk_sense_buffer(scp, NOT_READY, LOGICAL_UNIT_NOT_READY, 0x2); + mk_sense_buffer(scp, NOT_READY, + LU_NOT_READY_INITIALIZING_COMMAND_REQUIRED); if (sdebug_verbose) sdev_printk(KERN_INFO, sdp, "%s: Not ready: initializing command required\n", my_name); @@ -9194,7 +9244,8 @@ static int sdebug_fail_cmd(struct scsi_cmnd *cmnd, int *retval, out_handle: if (err->cnt < 0) err->cnt++; - mk_sense_buffer(cmnd, err->sense_key, err->asc, err->asq); + mk_sense_buffer(cmnd, err->sense_key, + scsi_sense_code(err->asc, err->asq)); result = err->status_byte | err->host_byte << 16 | err->driver_byte << 24; *info = *err; *retval = schedule_resp(cmnd, devip, result, NULL, 0, 0); diff --git a/drivers/scsi/scsi_lib.c b/drivers/scsi/scsi_lib.c index af27fd3df8d4..4901b2dff653 100644 --- a/drivers/scsi/scsi_lib.c +++ b/drivers/scsi/scsi_lib.c @@ -243,13 +243,13 @@ static int scsi_check_passthrough(struct scsi_cmnd *scmd, continue; if (status_byte(failure->result) != SAM_STAT_CHECK_CONDITION || - failure->sense == SCMD_FAILURE_SENSE_ANY) + failure->sense_key == SCMD_FAILURE_SENSE_KEY_ANY) goto maybe_retry; if (!scsi_command_normalize_sense(scmd, &sshdr)) return 0; - if (failure->sense != sshdr.sense_key) + if (failure->sense_key != sshdr.sense_key) continue; if (failure->asc == SCMD_FAILURE_ASC_ANY) @@ -2372,7 +2372,7 @@ scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage, int subpage, struct scsi_sense_hdr my_sshdr; struct scsi_failure failure_defs[] = { { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = SCMD_FAILURE_ASC_ANY, .ascq = SCMD_FAILURE_ASCQ_ANY, .allowed = retries, diff --git a/drivers/scsi/scsi_lib_test.c b/drivers/scsi/scsi_lib_test.c index ae8af0e0047a..4558dc853e26 100644 --- a/drivers/scsi/scsi_lib_test.c +++ b/drivers/scsi/scsi_lib_test.c @@ -17,40 +17,40 @@ static void scsi_lib_test_multiple_sense(struct kunit *test) { struct scsi_failure multiple_sense_failure_defs[] = { { - .sense = DATA_PROTECT, + .sense_key = DATA_PROTECT, .asc = 0x1, .ascq = 0x1, .result = SAM_STAT_CHECK_CONDITION, }, { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = 0x11, .ascq = 0x0, .allowed = SCSI_LIB_TEST_MAX_ALLOWED, .result = SAM_STAT_CHECK_CONDITION, }, { - .sense = NOT_READY, + .sense_key = NOT_READY, .asc = 0x11, .ascq = 0x22, .allowed = SCSI_LIB_TEST_MAX_ALLOWED, .result = SAM_STAT_CHECK_CONDITION, }, { - .sense = ABORTED_COMMAND, + .sense_key = ABORTED_COMMAND, .asc = 0x11, .ascq = SCMD_FAILURE_ASCQ_ANY, .allowed = SCSI_LIB_TEST_MAX_ALLOWED, .result = SAM_STAT_CHECK_CONDITION, }, { - .sense = HARDWARE_ERROR, + .sense_key = HARDWARE_ERROR, .asc = SCMD_FAILURE_ASC_ANY, .allowed = SCSI_LIB_TEST_MAX_ALLOWED, .result = SAM_STAT_CHECK_CONDITION, }, { - .sense = ILLEGAL_REQUEST, + .sense_key = ILLEGAL_REQUEST, .asc = 0x91, .ascq = 0x36, .allowed = SCSI_LIB_TEST_MAX_ALLOWED, @@ -116,8 +116,9 @@ static void scsi_lib_test_any_sense(struct kunit *test) { struct scsi_failure any_sense_failure_defs[] = { { - .result = SCMD_FAILURE_SENSE_ANY, + .sense_key = SCMD_FAILURE_SENSE_KEY_ANY, .allowed = SCSI_LIB_TEST_MAX_ALLOWED, + .result = SCMD_FAILURE_RESULT_ANY, }, {} }; @@ -129,7 +130,7 @@ static void scsi_lib_test_any_sense(struct kunit *test) .sense_buffer = sense, }; - /* Match using SCMD_FAILURE_SENSE_ANY */ + /* Match using SCMD_FAILURE_SENSE_KEY_ANY */ failures.failure_definitions = any_sense_failure_defs; scsi_build_sense(&sc, 0, MEDIUM_ERROR, 0x11, 0x22); KUNIT_EXPECT_EQ(test, -EAGAIN, scsi_check_passthrough(&sc, &failures)); @@ -215,14 +216,14 @@ static void scsi_lib_test_total_allowed(struct kunit *test) { struct scsi_failure total_allowed_defs[] = { { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = SCMD_FAILURE_ASC_ANY, .ascq = SCMD_FAILURE_ASCQ_ANY, .result = SAM_STAT_CHECK_CONDITION, }, /* Fail all CCs except the UA above */ { - .sense = SCMD_FAILURE_SENSE_ANY, + .sense_key = SCMD_FAILURE_SENSE_KEY_ANY, .result = SAM_STAT_CHECK_CONDITION, }, /* Retry any other errors not listed above */ @@ -259,12 +260,12 @@ static void scsi_lib_test_mixed_total(struct kunit *test) { struct scsi_failure mixed_total_defs[] = { { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = 0x28, .result = SAM_STAT_CHECK_CONDITION, }, { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = 0x29, .result = SAM_STAT_CHECK_CONDITION, }, diff --git a/drivers/scsi/scsi_scan.c b/drivers/scsi/scsi_scan.c index 0f0f243c2561..6cd77b0592e4 100644 --- a/drivers/scsi/scsi_scan.c +++ b/drivers/scsi/scsi_scan.c @@ -658,12 +658,12 @@ static int scsi_probe_lun(struct scsi_device *sdev, unsigned char *inq_result, * so anyway. */ { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = 0x28, .result = SAM_STAT_CHECK_CONDITION, }, { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = 0x29, .result = SAM_STAT_CHECK_CONDITION, }, @@ -1457,14 +1457,14 @@ static int scsi_report_lun_scan(struct Scsi_Host *shost, struct scsi_device *sdev; struct scsi_failure failure_defs[] = { { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = SCMD_FAILURE_ASC_ANY, .ascq = SCMD_FAILURE_ASCQ_ANY, .result = SAM_STAT_CHECK_CONDITION, }, /* Fail all CCs except the UA above */ { - .sense = SCMD_FAILURE_SENSE_ANY, + .sense_key = SCMD_FAILURE_SENSE_KEY_ANY, .result = SAM_STAT_CHECK_CONDITION, }, /* Retry any other errors not listed above */ diff --git a/drivers/scsi/scsi_transport_spi.c b/drivers/scsi/scsi_transport_spi.c index 3e3da8c2ff26..ec3884a6657f 100644 --- a/drivers/scsi/scsi_transport_spi.c +++ b/drivers/scsi/scsi_transport_spi.c @@ -112,7 +112,7 @@ static int spi_execute(struct scsi_device *sdev, const void *cmd, REQ_FAILFAST_DRIVER; struct scsi_failure failure_defs[] = { { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = SCMD_FAILURE_ASC_ANY, .ascq = SCMD_FAILURE_ASCQ_ANY, .allowed = DV_RETRIES, diff --git a/drivers/scsi/sd.c b/drivers/scsi/sd.c index 208b915f25a2..66664d08c15a 100644 --- a/drivers/scsi/sd.c +++ b/drivers/scsi/sd.c @@ -2033,7 +2033,7 @@ static int sd_pr_in_command(struct block_device *bdev, u8 sa, u8 cmd[10] = { PERSISTENT_RESERVE_IN, sa }; struct scsi_failure failure_defs[] = { { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = SCMD_FAILURE_ASC_ANY, .ascq = SCMD_FAILURE_ASCQ_ANY, .allowed = 5, @@ -2145,7 +2145,7 @@ static int sd_pr_out_command(struct block_device *bdev, u8 sa, u64 key, struct scsi_sense_hdr sshdr; struct scsi_failure failure_defs[] = { { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = SCMD_FAILURE_ASC_ANY, .ascq = SCMD_FAILURE_ASCQ_ANY, .allowed = 5, @@ -2494,13 +2494,13 @@ sd_spinup_disk(struct scsi_disk *sdkp) struct scsi_failure failure_defs[] = { /* Do not retry Medium Not Present */ { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = 0x3A, .ascq = SCMD_FAILURE_ASCQ_ANY, .result = SAM_STAT_CHECK_CONDITION, }, { - .sense = NOT_READY, + .sense_key = NOT_READY, .asc = 0x3A, .ascq = SCMD_FAILURE_ASCQ_ANY, .result = SAM_STAT_CHECK_CONDITION, @@ -2817,18 +2817,18 @@ static int read_capacity_10(struct scsi_disk *sdkp, struct scsi_device *sdp, struct scsi_failure failure_defs[] = { /* Do not retry Medium Not Present */ { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = 0x3A, .result = SAM_STAT_CHECK_CONDITION, }, { - .sense = NOT_READY, + .sense_key = NOT_READY, .asc = 0x3A, .result = SAM_STAT_CHECK_CONDITION, }, /* Device reset might occur several times so retry a lot */ { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = 0x29, .allowed = READ_CAPACITY_RETRIES_ON_RESET, .result = SAM_STAT_CHECK_CONDITION, @@ -4159,21 +4159,21 @@ static int sd_start_stop_device(struct scsi_disk *sdkp, int start) struct scsi_failure failure_defs[] = { { /* Power on, reset, or bus device reset occurred */ - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = 0x29, .ascq = 0, .result = SAM_STAT_CHECK_CONDITION, }, { /* Power on occurred */ - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = 0x29, .ascq = 1, .result = SAM_STAT_CHECK_CONDITION, }, { /* SCSI bus reset */ - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = 0x29, .ascq = 2, .result = SAM_STAT_CHECK_CONDITION, diff --git a/drivers/scsi/ses.c b/drivers/scsi/ses.c index 4c348645b04e..454886c24570 100644 --- a/drivers/scsi/ses.c +++ b/drivers/scsi/ses.c @@ -88,14 +88,14 @@ static int ses_recv_diag(struct scsi_device *sdev, int page_code, unsigned char recv_page_code; struct scsi_failure failure_defs[] = { { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = 0x29, .ascq = SCMD_FAILURE_ASCQ_ANY, .allowed = SES_RETRIES, .result = SAM_STAT_CHECK_CONDITION, }, { - .sense = NOT_READY, + .sense_key = NOT_READY, .asc = SCMD_FAILURE_ASC_ANY, .ascq = SCMD_FAILURE_ASCQ_ANY, .allowed = SES_RETRIES, @@ -145,14 +145,14 @@ static int ses_send_diag(struct scsi_device *sdev, int page_code, }; struct scsi_failure failure_defs[] = { { - .sense = UNIT_ATTENTION, + .sense_key = UNIT_ATTENTION, .asc = 0x29, .ascq = SCMD_FAILURE_ASCQ_ANY, .allowed = SES_RETRIES, .result = SAM_STAT_CHECK_CONDITION, }, { - .sense = NOT_READY, + .sense_key = NOT_READY, .asc = SCMD_FAILURE_ASC_ANY, .ascq = SCMD_FAILURE_ASCQ_ANY, .allowed = SES_RETRIES, diff --git a/drivers/scsi/st.c b/drivers/scsi/st.c index a757646c8dc6..f7d9c67aaf87 100644 --- a/drivers/scsi/st.c +++ b/drivers/scsi/st.c @@ -2686,6 +2686,30 @@ static int do_load_unload(struct scsi_tape *STp, struct file *filp, int load_cod else { STp->rew_at_close = STp->autorew_dev; retval = check_tape(STp, filp); + /* + * LOAD leaves the medium at the beginning of partition + * 0. check_tape() records that only for a new session; + * without a new-medium unit attention (the medium was + * already loaded) the partition and the partition state + * would be left as before the load. Reset them as a + * new session does, for all partitions: a stale + * ST_WRITING state would make st_flush() write a + * filemark at the beginning of partition 0. + */ + if (retval == CHKRES_READY) { + int i; + + STp->partition = STp->new_partition = 0; + for (i = 0; i < ST_NBR_PARTITIONS; i++) { + STps = &(STp->ps[i]); + STps->rw = ST_IDLE; + STps->eof = ST_NOEOF; + STps->at_sm = 0; + STps->last_block_valid = 0; + STps->drv_block = 0; + STps->drv_file = 0; + } + } if (retval > 0) retval = 0; } @@ -3592,6 +3616,23 @@ static long st_common_ioctl(struct scsi_tape *STp, struct st_modedef *STm, return retval; } +/* + * Re-apply a density and block size that were changed by the user before a + * device reset (a negative value means "not changed"). A unit attention + * still pending after the operation (e.g. new medium after a load) fails the + * first MODE SELECT, so retry each once. As in the other post-reset restore + * path, errors are ignored and one setting failing does not prevent + * restoring the other. + */ +static void st_restore_changed_settings(struct scsi_tape *STp, int density, + int blksize) +{ + if (density >= 0 && st_int_ioctl(STp, MTSETDENSITY, density)) + st_int_ioctl(STp, MTSETDENSITY, density); + if (blksize >= 0 && st_int_ioctl(STp, MTSETBLK, blksize)) + st_int_ioctl(STp, MTSETBLK, blksize); +} + /* The ioctl command */ static long st_ioctl(struct file *file, unsigned int cmd_in, unsigned long arg) { @@ -3600,6 +3641,7 @@ static long st_ioctl(struct file *file, unsigned int cmd_in, unsigned long arg) int retval = 0; unsigned int blk; bool cmd_mtiocget; + int restore_density = -1, restore_blksize = -1; struct scsi_tape *STp = file->private_data; struct st_modedef *STm; struct st_partstat *STps; @@ -3746,6 +3788,17 @@ static long st_ioctl(struct file *file, unsigned int cmd_in, unsigned long arg) st_int_ioctl(STp, MTSETDENSITY, STp->changed_density); if (STp->blksize_changed) st_int_ioctl(STp, MTSETBLK, STp->changed_blksize); + } else if (mtc.mt_op == MTLOAD || mtc.mt_op == MTRETEN) { + /* + * The same medium ends up at BOT, so the settings + * apply as with MTREW. The operation may start a + * new session, which clears the "changed" flags: + * save the values and restore them afterwards. + */ + if (STp->density_changed) + restore_density = STp->changed_density; + if (STp->blksize_changed) + restore_blksize = STp->changed_blksize; } } @@ -3825,6 +3878,14 @@ static long st_ioctl(struct file *file, unsigned int cmd_in, unsigned long arg) if (mtc.mt_op == MTLOAD) { retval = do_load_unload(STp, file, max(1, mtc.mt_count)); + /* + * Restore only if the drive is ready: after an + * immediate-mode load with O_NONBLOCK, check_tape() + * does not wait and the drive may still be loading. + */ + if (!retval && STp->ready == ST_READY) + st_restore_changed_settings(STp, restore_density, + restore_blksize); goto out; } @@ -3843,6 +3904,20 @@ static long st_ioctl(struct file *file, unsigned int cmd_in, unsigned long arg) retval = st_compression(STp, (mtc.mt_count & 1)); else retval = st_int_ioctl(STp, mtc.mt_op, mtc.mt_count); + if (!retval && mtc.mt_op == MTRETEN && !STp->immediate && + (restore_density >= 0 || restore_blksize >= 0)) { + /* + * Retension reloads the medium and the drive may + * report a new medium. Let check_tape() start the new + * session (applying the mode defaults) now, as for + * MTLOAD; otherwise it happens at the next open and + * overrides the restored settings. + */ + if (check_tape(STp, file) >= 0 && + STp->ready == ST_READY) + st_restore_changed_settings(STp, restore_density, + restore_blksize); + } goto out; } if (!STm->defined) { diff --git a/drivers/soc/microchip/mpfs-sys-controller.c b/drivers/soc/microchip/mpfs-sys-controller.c index 0400a01b2338..ef27e1083f0f 100644 --- a/drivers/soc/microchip/mpfs-sys-controller.c +++ b/drivers/soc/microchip/mpfs-sys-controller.c @@ -159,7 +159,7 @@ static int mpfs_sys_controller_probe(struct platform_device *pdev) of_data = (struct mpfs_syscon_config *) device_get_match_data(dev); if (!of_data) { ret = dev_err_probe(dev, -EINVAL, "Error getting match data\n"); - goto out_free_channel; + goto out_put; } for (i = 0; i < of_data->nb_subdevs; i++) { @@ -173,8 +173,9 @@ static int mpfs_sys_controller_probe(struct platform_device *pdev) return 0; -out_free_channel: - mbox_free_channel(sys_controller->chan); +out_put: + mpfs_sys_controller_put(sys_controller); + return ret; out_free: kfree(sys_controller); return ret; diff --git a/drivers/soc/qcom/apr.c b/drivers/soc/qcom/apr.c index ea7f83916d8d..d72628ac09f1 100644 --- a/drivers/soc/qcom/apr.c +++ b/drivers/soc/qcom/apr.c @@ -434,31 +434,35 @@ static int apr_add_device(struct device *dev, struct device_node *np, if (np) snprintf(adev->name, APR_NAME_SIZE, "%pOFn", np); + adev->dev.bus = &aprbus; + adev->dev.parent = dev; + adev->dev.of_node = np; + adev->dev.release = apr_dev_release; + adev->dev.driver = NULL; + device_initialize(&adev->dev); + switch (apr->type) { case PR_TYPE_APR: - dev_set_name(&adev->dev, "aprsvc:%s:%x:%x", adev->name, - domain_id, svc_id); + ret = dev_set_name(&adev->dev, "aprsvc:%s:%x:%x", adev->name, + domain_id, svc_id); break; case PR_TYPE_GPR: - dev_set_name(&adev->dev, "gprsvc:%s:%x:%x", adev->name, - domain_id, svc_id); + ret = dev_set_name(&adev->dev, "gprsvc:%s:%x:%x", adev->name, + domain_id, svc_id); break; default: + ret = -EINVAL; break; } - - adev->dev.bus = &aprbus; - adev->dev.parent = dev; - adev->dev.of_node = np; - adev->dev.release = apr_dev_release; - adev->dev.driver = NULL; + if (ret) + goto out_put_device; spin_lock(&apr->svcs_lock); ret = idr_alloc(&apr->svcs_idr, svc, svc_id, svc_id + 1, GFP_ATOMIC); spin_unlock(&apr->svcs_lock); if (ret < 0) { dev_err(dev, "idr_alloc failed: %d\n", ret); - goto out; + goto out_put_device; } /* Protection domain is optional, it does not exist on older platforms */ @@ -466,18 +470,26 @@ static int apr_add_device(struct device *dev, struct device_node *np, 1, &adev->service_path); if (ret < 0 && ret != -EINVAL) { dev_err(dev, "Failed to read second value of qcom,protection-domain\n"); - goto out; + goto out_remove_idr; } dev_info(dev, "Adding APR/GPR dev: %s\n", dev_name(&adev->dev)); - ret = device_register(&adev->dev); + ret = device_add(&adev->dev); if (ret) { - dev_err(dev, "device_register failed: %d\n", ret); - put_device(&adev->dev); + dev_err(dev, "device_add failed: %d\n", ret); + goto out_remove_idr; } -out: + return 0; + +out_remove_idr: + spin_lock(&apr->svcs_lock); + idr_remove(&apr->svcs_idr, svc_id); + spin_unlock(&apr->svcs_lock); + flush_workqueue(apr->rxwq); +out_put_device: + put_device(&adev->dev); return ret; } diff --git a/drivers/soc/qcom/pmic_glink.c b/drivers/soc/qcom/pmic_glink.c index 3042261578aa..84fd0c82c0c4 100644 --- a/drivers/soc/qcom/pmic_glink.c +++ b/drivers/soc/qcom/pmic_glink.c @@ -250,7 +250,8 @@ static int pmic_glink_rpmsg_probe(struct rpmsg_device *rpdev) guard(mutex)(&__pmic_glink_lock); pg = __pmic_glink; if (!pg) - return dev_err_probe(&rpdev->dev, -ENODEV, "no pmic_glink device to attach to\n"); + return dev_err_probe(&rpdev->dev, -EPROBE_DEFER, + "no pmic_glink device to attach to\n"); dev_set_drvdata(&rpdev->dev, pg); pg->pdr_available = rpdev->id.driver_data; diff --git a/drivers/soc/qcom/pmic_pdcharger_ulog.c b/drivers/soc/qcom/pmic_pdcharger_ulog.c index 39f412bbf2c1..06cd9c4411c2 100644 --- a/drivers/soc/qcom/pmic_pdcharger_ulog.c +++ b/drivers/soc/qcom/pmic_pdcharger_ulog.c @@ -143,7 +143,7 @@ static void pmic_pdcharger_ulog_rpmsg_remove(struct rpmsg_device *rpdev) { struct pmic_pdcharger_ulog *pg = dev_get_drvdata(&rpdev->dev); - cancel_delayed_work_sync(&pg->ulog_work); + disable_delayed_work_sync(&pg->ulog_work); } static const struct rpmsg_device_id pmic_pdcharger_ulog_rpmsg_id_match[] = { diff --git a/drivers/soc/qcom/qcom-geni-se.c b/drivers/soc/qcom/qcom-geni-se.c index 6ac2bdc16984..08e05ba70f73 100644 --- a/drivers/soc/qcom/qcom-geni-se.c +++ b/drivers/soc/qcom/qcom-geni-se.c @@ -101,22 +101,26 @@ EXPORT_TRACEPOINT_SYMBOL_GPL(geni_se_regs); * @base: Base address of this instance of QUP wrapper core * @clks: Handle to the primary & optional secondary AHB clocks * @num_clks: Count of clocks + * @prog_ram_depth: Available CFG RAM depth for instance without SE_HW_PARAM_2 */ struct geni_wrapper { struct device *dev; void __iomem *base; struct clk_bulk_data clks[MAX_CLKS]; unsigned int num_clks; + unsigned int prog_ram_depth; }; /** * struct geni_se_desc - Data structure to represent the QUP Wrapper resources * @clks: Name of the primary & optional secondary AHB clocks * @num_clks: Count of clock names + * @prog_ram_depth: Available CFG RAM depth for instance without SE_HW_PARAM_2 */ struct geni_se_desc { unsigned int num_clks; const char * const *clks; + unsigned int prog_ram_depth; }; static const char * const icc_path_names[] = {"qup-core", "qup-config", @@ -1244,6 +1248,7 @@ static const struct se_fw_hdr *geni_find_protocol_fw(struct geni_se *se, const s enum geni_se_protocol_type protocol, u32 *fw_size_out) { + struct geni_wrapper *wrapper = se->wrapper; struct device *dev = se->dev; const struct elf32_hdr *ehdr; const struct elf32_phdr *phdrs; @@ -1308,8 +1313,11 @@ static const struct se_fw_hdr *geni_find_protocol_fw(struct geni_se *se, const s cfg_val_end = le16_to_cpu(sefw->cfg_val_offset) + le16_to_cpu(sefw->cfg_size_in_items) * sizeof(u32); - prog_ram_depth = FIELD_GET(PROG_RAM_DEPTH_MSK, - readl_relaxed(se->base + SE_HW_PARAM_2)); + if (wrapper->prog_ram_depth) + prog_ram_depth = wrapper->prog_ram_depth; + else + prog_ram_depth = FIELD_GET(PROG_RAM_DEPTH_MSK, + readl_relaxed(se->base + SE_HW_PARAM_2)); if (fw_size >= prog_ram_depth) { dev_err(dev, "Firmware size (%u) exceeds RAM size (%u)\n", fw_size, prog_ram_depth); @@ -1620,6 +1628,7 @@ static int geni_se_probe(struct platform_device *pdev) return PTR_ERR(wrapper->base); desc = device_get_match_data(&pdev->dev); + wrapper->prog_ram_depth = desc->prog_ram_depth; if (!has_acpi_companion(&pdev->dev) && desc->num_clks) { int i; @@ -1672,6 +1681,7 @@ static const char * const i2c_master_hub_clks[] = { static const struct geni_se_desc i2c_master_hub_desc = { .clks = i2c_master_hub_clks, .num_clks = ARRAY_SIZE(i2c_master_hub_clks), + .prog_ram_depth = 1020, }; static const struct of_device_id geni_se_dt_match[] = { diff --git a/drivers/soc/qcom/smem_dramc.c b/drivers/soc/qcom/smem_dramc.c index 63ebe7f6db59..19a831ab5907 100644 --- a/drivers/soc/qcom/smem_dramc.c +++ b/drivers/soc/qcom/smem_dramc.c @@ -219,7 +219,7 @@ static void smem_dram_parse_v3_data(struct smem_dram *dram, void *data) if (freq_entry->freq_khz && freq_entry->enabled) { u32 freq_khz = le32_to_cpu(freq_entry->freq_khz); - dram->frequencies[dram->num_frequencies++] = 1000 * freq_khz; + dram->frequencies[dram->num_frequencies++] = 1000UL * freq_khz; } } } @@ -231,8 +231,11 @@ static void smem_dram_parse_v3_14freqs_data(struct smem_dram *dram, void *data) for (int i = 0; i < MAX_DDR_FREQ_NUM_V3 + 1; i++) { struct ddr_freq_table *freq_entry = &details->ddr_freq_tbl.ddr_freq[i]; - if (freq_entry->freq_khz && freq_entry->enabled) - dram->frequencies[dram->num_frequencies++] = 1000 * freq_entry->freq_khz; + if (freq_entry->freq_khz && freq_entry->enabled) { + u32 freq_khz = le32_to_cpu(freq_entry->freq_khz); + + dram->frequencies[dram->num_frequencies++] = 1000UL * freq_khz; + } } } @@ -248,7 +251,7 @@ static void smem_dram_parse_v4_data(struct smem_dram *dram, void *data) if (freq_entry->freq_khz && freq_entry->enabled) { u32 freq_khz = le32_to_cpu(freq_entry->freq_khz); - dram->frequencies[dram->num_frequencies++] = 1000 * freq_khz; + dram->frequencies[dram->num_frequencies++] = 1000UL * freq_khz; } } } @@ -265,7 +268,7 @@ static void smem_dram_parse_v5_data(struct smem_dram *dram, void *data) if (freq_entry->freq_khz && freq_entry->enabled) { u32 freq_khz = le32_to_cpu(freq_entry->freq_khz); - dram->frequencies[dram->num_frequencies++] = 1000 * freq_khz; + dram->frequencies[dram->num_frequencies++] = 1000UL * freq_khz; } } } @@ -282,7 +285,7 @@ static void smem_dram_parse_v7_data(struct smem_dram *dram, void *data) if (freq_entry->freq_khz && freq_entry->enabled) { u32 freq_khz = le32_to_cpu(freq_entry->freq_khz); - dram->frequencies[dram->num_frequencies++] = 1000 * freq_khz; + dram->frequencies[dram->num_frequencies++] = 1000UL * freq_khz; } } } @@ -382,7 +385,7 @@ struct dentry *smem_dram_parse(struct qcom_smem *smem, struct device *dev) return ERR_PTR(-ENODATA); ver = smem_dram_infer_struct_version(actual_size); - if (ver < 0) { + if ((int)ver < 0) { /* Some SoCs don't provide data that's useful for us */ return ERR_PTR(-ENODATA); } else if (ver == INFO_UNKNOWN) { diff --git a/drivers/soc/tegra/flowctrl.c b/drivers/soc/tegra/flowctrl.c index 221202db3313..d5c3af586d31 100644 --- a/drivers/soc/tegra/flowctrl.c +++ b/drivers/soc/tegra/flowctrl.c @@ -195,11 +195,14 @@ static int __init tegra_flowctrl_init(void) np = of_find_matching_node(NULL, tegra_flowctrl_match); if (np) { - if (of_address_to_resource(np, 0, &res) < 0) { + int err = of_address_to_resource(np, 0, &res); + + of_node_put(np); + + if (err < 0) { pr_err("failed to get flowctrl register\n"); return -ENXIO; } - of_node_put(np); } else if (IS_ENABLED(CONFIG_ARM)) { /* * Hardcoded fallback for 32-bit Tegra diff --git a/drivers/soundwire/debugfs.c b/drivers/soundwire/debugfs.c index 099eb84a548e..a8a6db164fe7 100644 --- a/drivers/soundwire/debugfs.c +++ b/drivers/soundwire/debugfs.c @@ -145,6 +145,38 @@ static u32 start_addr; static size_t num_bytes; static u8 read_buffer[MAX_CMD_BYTES]; static char *firmware_file; +static DEFINE_MUTEX(firmware_file_lock); + +static ssize_t firmware_file_write(struct file *file, + const char __user *user_buf, + size_t count, loff_t *ppos) +{ + char *old, *new; + + if (*ppos) + return -EINVAL; + if (count + 1 > PAGE_SIZE) + return -E2BIG; + + new = memdup_user_nul(user_buf, count); + if (IS_ERR(new)) + return PTR_ERR(new); + strim(new); + + scoped_guard(mutex, &firmware_file_lock) { + old = firmware_file; + firmware_file = new; + } + + kfree(old); + return count; +} + +static const struct file_operations firmware_file_fops = { + .open = simple_open, + .write = firmware_file_write, + .llseek = default_llseek, +}; static int set_command(void *data, u64 value) { @@ -246,6 +278,7 @@ static int cmd_go(void *data, u64 value) { const struct firmware *fw = NULL; struct sdw_slave *slave = data; + char *fw_name = NULL; ktime_t start_t; ktime_t finish_t; int ret; @@ -265,15 +298,24 @@ static int cmd_go(void *data, u64 value) } if (cmd == 0) { - ret = request_firmware(&fw, firmware_file, &slave->dev); + scoped_guard(mutex, &firmware_file_lock) { + if (firmware_file) + fw_name = kstrdup(firmware_file, GFP_KERNEL); + } + if (!fw_name) { + ret = -ENOMEM; + goto out; + } + + ret = request_firmware(&fw, fw_name, &slave->dev); if (ret < 0) { - dev_err(&slave->dev, "firmware %s not found\n", firmware_file); + dev_err(&slave->dev, "firmware %s not found\n", fw_name); goto out; } if (fw->size < num_bytes) { dev_err(&slave->dev, "firmware %s: firmware size %zd, desired %zd\n", - firmware_file, fw->size, num_bytes); + fw_name, fw->size, num_bytes); goto out; } } @@ -306,6 +348,7 @@ static int cmd_go(void *data, u64 value) out: if (fw) release_firmware(fw); + kfree(fw_name); pm_runtime_mark_last_busy(&slave->dev); pm_runtime_put(&slave->dev); @@ -358,7 +401,8 @@ void sdw_slave_debugfs_init(struct sdw_slave *slave) debugfs_create_file("read_buffer", 0400, d, slave, &read_buffer_fops); if (firmware_file) - debugfs_create_str("firmware_file", 0200, d, &firmware_file); + debugfs_create_file("firmware_file", 0200, d, NULL, + &firmware_file_fops); slave->debugfs = d; } @@ -370,8 +414,10 @@ void sdw_slave_debugfs_exit(struct sdw_slave *slave) void sdw_debugfs_init(void) { - if (!firmware_file) - firmware_file = kstrdup("", GFP_KERNEL); + scoped_guard(mutex, &firmware_file_lock) { + if (!firmware_file) + firmware_file = kstrdup("", GFP_KERNEL); + } sdw_debugfs_root = debugfs_create_dir("soundwire", NULL); } @@ -379,6 +425,7 @@ void sdw_debugfs_init(void) void sdw_debugfs_exit(void) { debugfs_remove_recursive(sdw_debugfs_root); - kfree(firmware_file); - firmware_file = NULL; + scoped_guard(mutex, &firmware_file_lock) { + kfree(firmware_file); + } } diff --git a/drivers/soundwire/intel_auxdevice.c b/drivers/soundwire/intel_auxdevice.c index a8407560bf4f..9b1465af2645 100644 --- a/drivers/soundwire/intel_auxdevice.c +++ b/drivers/soundwire/intel_auxdevice.c @@ -159,7 +159,7 @@ static int sdw_master_read_intel_prop(struct sdw_bus *bus) struct sdw_intel_prop *intel_prop; struct fwnode_handle *link; char name[32]; - u32 quirk_mask; + u32 quirk_mask = 0; /* Find master handle */ snprintf(name, sizeof(name), diff --git a/drivers/spi/spi-amlogic-spisg.c b/drivers/spi/spi-amlogic-spisg.c index 9049a87e9d0f..6243b47b6e68 100644 --- a/drivers/spi/spi-amlogic-spisg.c +++ b/drivers/spi/spi-amlogic-spisg.c @@ -95,7 +95,7 @@ #define SPISG_MAX_REG 0x40 -#define SPISG_BLOCK_MAX 0x100000 +#define SPISG_BLOCK_MAX 0xFFFFF #define SPISG_OP_MODE_WRITE_CMD 0 #define SPISG_OP_MODE_READ_STS 1 @@ -175,7 +175,7 @@ static int spi_delay_to_sclk(u32 slck_speed_hz, struct spi_delay *delay) if (ns < 0) return 0; - return DIV_ROUND_UP_ULL(slck_speed_hz * ns, NSEC_PER_SEC); + return DIV_ROUND_UP_ULL((u64)slck_speed_hz * ns, NSEC_PER_SEC); } static inline u32 aml_spisg_sem_down_read(struct spisg_device *spisg) @@ -489,6 +489,7 @@ static int aml_spisg_transfer_one_message(struct spi_controller *ctlr, struct spisg_descriptor_extra *exdescs, *exdesc; dma_addr_t descs_paddr; int desc_num = 1, descs_len; + bool last_xfer_keep_ss = false; u32 cs_hold_in_sclk = 0; int ret = -EIO; @@ -529,9 +530,11 @@ static int aml_spisg_transfer_one_message(struct spi_controller *ctlr, spi_delay_to_sclk(xfer->effective_speed_hz, &msg->spi->cs_setup)); /* calculate cs-hold delay with the last xfer speed */ - if (list_is_last(&xfer->transfer_list, &msg->transfers)) + if (list_is_last(&xfer->transfer_list, &msg->transfers)) { cs_hold_in_sclk = spi_delay_to_sclk(xfer->effective_speed_hz, &msg->spi->cs_hold); + last_xfer_keep_ss = xfer->cs_change; + } desc++; exdesc++; @@ -539,13 +542,17 @@ static int aml_spisg_transfer_one_message(struct spi_controller *ctlr, xfer->effective_speed_hz); } - if (cs_hold_in_sclk) + if (cs_hold_in_sclk) { /* additional null-descriptor to achieve the cs-hold delay */ aml_spisg_setup_null_desc(spisg, desc, cs_hold_in_sclk); - else desc--; + desc->cfg_bus |= FIELD_PREP(CFG_KEEP_SS, 1); + desc++; + } else { + desc--; + } - desc->cfg_bus |= FIELD_PREP(CFG_KEEP_SS, 0); + FIELD_MODIFY(CFG_KEEP_SS, &desc->cfg_bus, last_xfer_keep_ss); desc->cfg_start |= FIELD_PREP(CFG_EOC, 1); /* some tolerances */ @@ -565,10 +572,13 @@ static int aml_spisg_transfer_one_message(struct spi_controller *ctlr, aml_spisg_pending(spisg, descs_paddr, false, true); if (wait_for_completion_timeout(&spisg->completion, spi_controller_is_target(spisg->controller) ? - MAX_SCHEDULE_TIMEOUT : msecs_to_jiffies(ms))) + MAX_SCHEDULE_TIMEOUT : msecs_to_jiffies(ms))) { ret = spisg->status ? -EIO : 0; - else + } else { + /* stop transfer */ + regmap_write(spisg->map, SPISG_REG_DESC_LIST_H, 0); ret = -ETIMEDOUT; + } dma_unmap_single(dev, descs_paddr, descs_len, DMA_TO_DEVICE); end: @@ -704,7 +714,9 @@ static int aml_spisg_clk_init(struct spisg_device *spisg, void __iomem *base) return PTR_ERR(spisg->sclk); } - clk_prepare_enable(spisg->sclk); + ret = clk_prepare_enable(spisg->sclk); + if (ret) + return ret; return 0; } @@ -841,9 +853,18 @@ static int spisg_suspend_runtime(struct device *dev) static int spisg_resume_runtime(struct device *dev) { struct spisg_device *spisg = dev_get_drvdata(dev); + int ret; + + ret = clk_prepare_enable(spisg->core); + if (ret) + return ret; + + ret = clk_prepare_enable(spisg->sclk); + if (ret) { + clk_disable_unprepare(spisg->core); + return ret; + } - clk_prepare_enable(spisg->core); - clk_prepare_enable(spisg->sclk); pinctrl_pm_select_default_state(&spisg->pdev->dev); return 0; diff --git a/drivers/spi/spi-axi-spi-engine.c b/drivers/spi/spi-axi-spi-engine.c index 02bbc5d0cfc5..ead5b295e680 100644 --- a/drivers/spi/spi-axi-spi-engine.c +++ b/drivers/spi/spi-axi-spi-engine.c @@ -887,6 +887,7 @@ static int spi_engine_setup(struct spi_device *device) struct spi_controller *host = device->controller; struct spi_engine *spi_engine = spi_controller_get_devdata(host); unsigned int reg; + int ret; if (device->mode & SPI_CS_HIGH) spi_engine->cs_inv |= BIT(spi_get_chipselect(device, 0)); @@ -922,8 +923,15 @@ static int spi_engine_setup(struct spi_device *device) writel_relaxed(SPI_ENGINE_CMD_SYNC(1), spi_engine->base + SPI_ENGINE_REG_CMD_FIFO); - return readl_relaxed_poll_timeout(spi_engine->base + SPI_ENGINE_REG_SYNC_ID, - reg, reg == 1, 1, 1000); + ret = readl_relaxed_poll_timeout(spi_engine->base + SPI_ENGINE_REG_SYNC_ID, + reg, reg == 1, 1, 1 * USEC_PER_MSEC); + + /* Clear the stale SYNC pending bit so it doesn't fire when the IRQ is later enabled. */ + writel_relaxed(SPI_ENGINE_INT_SYNC, spi_engine->base + SPI_ENGINE_REG_INT_PENDING); + /* Read back to flush posted write. */ + readl_relaxed(spi_engine->base + SPI_ENGINE_REG_INT_PENDING); + + return ret; } static int spi_engine_transfer_one_message(struct spi_controller *host, @@ -1028,7 +1036,13 @@ static int spi_engine_trigger_enable(struct spi_offload *offload) spi_engine->base + SPI_ENGINE_REG_CMD_FIFO); ret = readl_relaxed_poll_timeout(spi_engine->base + SPI_ENGINE_REG_SYNC_ID, - reg, reg == 1, 1, 1000); + reg, reg == 1, 1, 1 * USEC_PER_MSEC); + + /* Clear the stale SYNC pending bit so it doesn't fire when the IRQ is later enabled */ + writel_relaxed(SPI_ENGINE_INT_SYNC, spi_engine->base + SPI_ENGINE_REG_INT_PENDING); + /* Read back to flush posted write. */ + readl_relaxed(spi_engine->base + SPI_ENGINE_REG_INT_PENDING); + if (ret) return ret; diff --git a/drivers/spi/spi-bcm63xx-hsspi.c b/drivers/spi/spi-bcm63xx-hsspi.c index 25f169a2a81d..80bf02bc324a 100644 --- a/drivers/spi/spi-bcm63xx-hsspi.c +++ b/drivers/spi/spi-bcm63xx-hsspi.c @@ -882,6 +882,7 @@ static void bcm63xx_hsspi_remove(struct platform_device *pdev) /* reset the hardware and block queue progress */ __raw_writel(0, bs->regs + HSSPI_INT_MASK_REG); sysfs_remove_group(&pdev->dev.kobj, &bcm63xx_hsspi_group); + pm_runtime_disable(&pdev->dev); } static int bcm63xx_hsspi_suspend(struct device *dev) diff --git a/drivers/spi/spi-cs42l43.c b/drivers/spi/spi-cs42l43.c index 6772abb483dd..46eeb44130dd 100644 --- a/drivers/spi/spi-cs42l43.c +++ b/drivers/spi/spi-cs42l43.c @@ -301,6 +301,14 @@ static const struct dmi_system_id cs42l43_spk_id_quirks[] = { }, .driver_data = cs42l43_get_2bit_speaker_id_from_one_gpioio, }, + { + .ident = "Dell XPS 13 DX13260", + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc"), + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "0E54"), + }, + .driver_data = cs42l43_get_2bit_speaker_id_from_one_gpioio, + }, { } }; diff --git a/drivers/spi/spi-fsl-spi.c b/drivers/spi/spi-fsl-spi.c index e45816ef7b65..665902703973 100644 --- a/drivers/spi/spi-fsl-spi.c +++ b/drivers/spi/spi-fsl-spi.c @@ -702,10 +702,18 @@ static void of_fsl_spi_remove(struct platform_device *ofdev) { struct spi_controller *host = platform_get_drvdata(ofdev); struct mpc8xxx_spi *mpc8xxx_spi = spi_controller_get_devdata(host); +#if IS_ENABLED(CONFIG_FSL_SOC) + struct fsl_spi_platform_data *pdata = dev_get_platdata(&ofdev->dev); + struct mpc8xxx_spi_probe_info *pinfo = to_of_pinfo(pdata); +#endif spi_unregister_controller(host); fsl_spi_cpm_free(mpc8xxx_spi); +#if IS_ENABLED(CONFIG_FSL_SOC) + if (pinfo->immr_spi_cs) + iounmap(pinfo->immr_spi_cs); +#endif } static struct platform_driver of_fsl_spi_driver = { diff --git a/drivers/spi/spi-ma35d1-qspi.c b/drivers/spi/spi-ma35d1-qspi.c index 7f938d0c6f1f..30e3239f777d 100644 --- a/drivers/spi/spi-ma35d1-qspi.c +++ b/drivers/spi/spi-ma35d1-qspi.c @@ -633,18 +633,23 @@ static int nuvoton_qspi_probe(struct platform_device *pdev) return dev_err_probe(dev, ret, "failed to deassert reset\n"); ret = device_property_read_u32(dev, "num-cs", &num_cs); - if (ret && ret != -EINVAL) - return dev_err_probe(dev, ret, "failed to read num-cs\n"); + if (ret && ret != -EINVAL) { + ret = dev_err_probe(dev, ret, "failed to read num-cs\n"); + goto err_assert; + } - if (!num_cs || num_cs > NUVOTON_QSPI_MAX_NUM_CS) - return dev_err_probe(dev, -EINVAL, "invalid num-cs %u\n", + if (!num_cs || num_cs > NUVOTON_QSPI_MAX_NUM_CS) { + ret = dev_err_probe(dev, -EINVAL, "invalid num-cs %u\n", num_cs); + goto err_assert; + } ctlr->num_chipselect = num_cs; ctlr->max_transfer_size = nuvoton_qspi_max_transfer_size; ctlr->max_message_size = nuvoton_qspi_max_message_size; ctlr->mem_ops = &nuvoton_qspi_mem_ops; ctlr->mem_caps = &nuvoton_qspi_mem_caps; + ctlr->dtr_caps = true; ctlr->set_cs = nuvoton_qspi_set_cs; ctlr->transfer_one = nuvoton_qspi_transfer_one; ctlr->bits_per_word_mask = SPI_BPW_MASK(8); @@ -655,14 +660,20 @@ static int nuvoton_qspi_probe(struct platform_device *pdev) ret = nuvoton_qspi_hw_init(qspi); if (ret) - return ret; + goto err_assert; ret = devm_spi_register_controller(dev, ctlr); - if (ret) - return dev_err_probe(dev, ret, - "failed to register spi controller\n"); + if (ret) { + ret = dev_err_probe(dev, ret, + "failed to register spi controller\n"); + goto err_assert; + } return 0; + +err_assert: + reset_control_assert(rst); + return ret; } static const struct of_device_id nuvoton_qspi_of_match[] = { diff --git a/drivers/spi/spi-meson-spicc.c b/drivers/spi/spi-meson-spicc.c index fa2d2db2d6e7..b1f8c823d5d0 100644 --- a/drivers/spi/spi-meson-spicc.c +++ b/drivers/spi/spi-meson-spicc.c @@ -235,6 +235,13 @@ static int meson_spicc_dma_map(struct meson_spicc_device *spicc, { struct device *dev = spicc->host->dev.parent; + /* + * Mark the DMA addresses as invalid so that meson_spicc_dma_unmap() + * will not try to unmap a buffer which was not (successfully) mapped. + */ + t->tx_dma = DMA_MAPPING_ERROR; + t->rx_dma = DMA_MAPPING_ERROR; + if (!(t->tx_buf && t->rx_buf)) return -EINVAL; @@ -257,9 +264,9 @@ static void meson_spicc_dma_unmap(struct meson_spicc_device *spicc, { struct device *dev = spicc->host->dev.parent; - if (t->tx_dma) + if (!dma_mapping_error(dev, t->tx_dma)) dma_unmap_single(dev, t->tx_dma, t->len, DMA_TO_DEVICE); - if (t->rx_dma) + if (!dma_mapping_error(dev, t->rx_dma)) dma_unmap_single(dev, t->rx_dma, t->len, DMA_FROM_DEVICE); } diff --git a/drivers/spi/spi-mtk-nor.c b/drivers/spi/spi-mtk-nor.c index 63f5139176c8..6b6e55d68048 100644 --- a/drivers/spi/spi-mtk-nor.c +++ b/drivers/spi/spi-mtk-nor.c @@ -929,6 +929,7 @@ static int mtk_nor_probe(struct platform_device *pdev) return 0; err_probe: + pm_runtime_put_noidle(&pdev->dev); pm_runtime_disable(&pdev->dev); pm_runtime_set_suspended(&pdev->dev); pm_runtime_dont_use_autosuspend(&pdev->dev); diff --git a/drivers/spi/spi-mxic.c b/drivers/spi/spi-mxic.c index e3c85e5191e3..481edd4b35cb 100644 --- a/drivers/spi/spi-mxic.c +++ b/drivers/spi/spi-mxic.c @@ -744,7 +744,13 @@ static int mxic_spi_runtime_resume(struct device *dev) return ret; } - return mxic_spi_clk_enable(mxic); + ret = mxic_spi_clk_enable(mxic); + if (ret) { + clk_disable_unprepare(mxic->ps_clk); + return ret; + } + + return 0; } static const struct dev_pm_ops mxic_spi_dev_pm_ops = { diff --git a/drivers/spi/spi-omap2-mcspi.c b/drivers/spi/spi-omap2-mcspi.c index a3355147f5de..7d54739206dd 100644 --- a/drivers/spi/spi-omap2-mcspi.c +++ b/drivers/spi/spi-omap2-mcspi.c @@ -413,10 +413,11 @@ static void omap2_mcspi_tx_callback(void *data) complete(&mcspi_dma->dma_tx_completion); } -static void omap2_mcspi_tx_dma(struct spi_device *spi, - struct spi_transfer *xfer, - struct dma_slave_config cfg) +static int omap2_mcspi_tx_dma(struct spi_device *spi, + struct spi_transfer *xfer, + struct dma_slave_config cfg) { + int ret; struct omap2_mcspi *mcspi; struct omap2_mcspi_dma *mcspi_dma; struct dma_async_tx_descriptor *tx; @@ -424,31 +425,31 @@ static void omap2_mcspi_tx_dma(struct spi_device *spi, mcspi = spi_controller_get_devdata(spi->controller); mcspi_dma = &mcspi->dma_channels[spi_get_chipselect(spi, 0)]; - dmaengine_slave_config(mcspi_dma->dma_tx, &cfg); + ret = dmaengine_slave_config(mcspi_dma->dma_tx, &cfg); + if (ret) + return ret; tx = dmaengine_prep_slave_sg(mcspi_dma->dma_tx, xfer->tx_sg.sgl, xfer->tx_sg.nents, DMA_MEM_TO_DEV, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); - if (tx) { - tx->callback = omap2_mcspi_tx_callback; - tx->callback_param = spi; - dmaengine_submit(tx); - } else { - /* FIXME: fall back to PIO? */ - } - dma_async_issue_pending(mcspi_dma->dma_tx); - omap2_mcspi_set_dma_req(spi, 0, 1); + if (!tx) + return -EIO; + + tx->callback = omap2_mcspi_tx_callback; + tx->callback_param = spi; + + return dma_submit_error(dmaengine_submit(tx)); } -static unsigned +static int omap2_mcspi_rx_dma(struct spi_device *spi, struct spi_transfer *xfer, - struct dma_slave_config cfg, - unsigned es) + struct dma_slave_config cfg, unsigned int es, + unsigned int *count, bool *rx_submitted, bool *dma_started) { struct omap2_mcspi *mcspi; struct omap2_mcspi_dma *mcspi_dma; - unsigned int count, transfer_reduction = 0; + unsigned int transfer_reduction = 0; struct scatterlist *sg_out[2]; int nb_sizes = 0, out_mapped_nents[2], ret, x; size_t sizes[2]; @@ -461,7 +462,8 @@ omap2_mcspi_rx_dma(struct spi_device *spi, struct spi_transfer *xfer, mcspi = spi_controller_get_devdata(spi->controller); mcspi_dma = &mcspi->dma_channels[spi_get_chipselect(spi, 0)]; - count = xfer->len; + *count = xfer->len; + *rx_submitted = false; /* * In the "End-of-Transfer Procedure" section for DMA RX in OMAP35x TRM @@ -475,14 +477,16 @@ omap2_mcspi_rx_dma(struct spi_device *spi, struct spi_transfer *xfer, l = mcspi_cached_chconf0(spi); if (word_len <= 8) - element_count = count; + element_count = *count; else if (word_len <= 16) - element_count = count >> 1; + element_count = *count >> 1; else /* word_len <= 32 */ - element_count = count >> 2; + element_count = *count >> 2; - dmaengine_slave_config(mcspi_dma->dma_rx, &cfg); + ret = dmaengine_slave_config(mcspi_dma->dma_rx, &cfg); + if (ret) + return ret; /* * Reduce DMA transfer length by one more if McSPI is @@ -493,7 +497,7 @@ omap2_mcspi_rx_dma(struct spi_device *spi, struct spi_transfer *xfer, if (transfer_reduction) { /* Split sgl into two. The second sgl won't be used. */ - sizes[0] = count - transfer_reduction; + sizes[0] = *count - transfer_reduction; sizes[1] = transfer_reduction; nb_sizes = 2; } else { @@ -501,44 +505,56 @@ omap2_mcspi_rx_dma(struct spi_device *spi, struct spi_transfer *xfer, * Don't bother splitting the sgl. This essentially * clones the original sgl. */ - sizes[0] = count; + sizes[0] = *count; nb_sizes = 1; } ret = sg_split(xfer->rx_sg.sgl, xfer->rx_sg.nents, 0, nb_sizes, sizes, sg_out, out_mapped_nents, GFP_KERNEL); - if (ret < 0) { + if (ret) { dev_err(&spi->dev, "sg_split failed\n"); - return 0; + return ret; } tx = dmaengine_prep_slave_sg(mcspi_dma->dma_rx, sg_out[0], out_mapped_nents[0], DMA_DEV_TO_MEM, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); - if (tx) { - tx->callback = omap2_mcspi_rx_callback; - tx->callback_param = spi; - dmaengine_submit(tx); - } else { - /* FIXME: fall back to PIO? */ + if (!tx) { + ret = -EIO; + goto out_free_sg; } + tx->callback = omap2_mcspi_rx_callback; + tx->callback_param = spi; + ret = dma_submit_error(dmaengine_submit(tx)); + if (ret) + goto out_free_sg; + + *rx_submitted = true; + if (mcspi->target_aborted) { + ret = -EINTR; + goto out_free_sg; + } + *dma_started = true; + if (xfer->tx_buf) { + if (spi_controller_is_target(mcspi->ctlr)) + mcspi_write_reg(mcspi->ctlr, OMAP2_MCSPI_IRQENABLE, + OMAP2_MCSPI_IRQSTATUS_EOW); + dma_async_issue_pending(mcspi_dma->dma_tx); + omap2_mcspi_set_dma_req(spi, 0, 1); + } dma_async_issue_pending(mcspi_dma->dma_rx); omap2_mcspi_set_dma_req(spi, 1, 1); - ret = mcspi_wait_for_completion(mcspi, &mcspi_dma->dma_rx_completion); - if (ret || mcspi->target_aborted) { - dmaengine_terminate_sync(mcspi_dma->dma_rx); - omap2_mcspi_set_dma_req(spi, 1, 0); - return 0; - } + if (ret || mcspi->target_aborted) + goto out_free_sg; for (x = 0; x < nb_sizes; x++) kfree(sg_out[x]); if (mcspi->fifo_depth > 0) - return count; + return 0; /* * Due to the DMA transfer length reduction the missing bytes must @@ -565,9 +581,9 @@ omap2_mcspi_rx_dma(struct spi_device *spi, struct spi_transfer *xfer, } else { int bytes_per_word = mcspi_bytes_per_word(word_len); dev_err(&spi->dev, "DMA RX penultimate word empty\n"); - count -= (bytes_per_word << 1); + *count -= (bytes_per_word << 1); omap2_mcspi_set_enable(spi, 1); - return count; + return 0; } } if (!mcspi_wait_for_reg_bit(chstat_reg, OMAP2_MCSPI_CHSTAT_RXS)) { @@ -582,19 +598,27 @@ omap2_mcspi_rx_dma(struct spi_device *spi, struct spi_transfer *xfer, ((u32 *)xfer->rx_buf)[elements] = w; } else { dev_err(&spi->dev, "DMA RX last word empty\n"); - count -= mcspi_bytes_per_word(word_len); + *count -= mcspi_bytes_per_word(word_len); } omap2_mcspi_set_enable(spi, 1); - return count; + return 0; + +out_free_sg: + if (!ret) + ret = -EINTR; + for (x = 0; x < nb_sizes; x++) + kfree(sg_out[x]); + return ret; } -static unsigned -omap2_mcspi_txrx_dma(struct spi_device *spi, struct spi_transfer *xfer) +static int omap2_mcspi_txrx_dma(struct spi_device *spi, + struct spi_transfer *xfer, + unsigned int *count, + bool *pio_fallback) { struct omap2_mcspi *mcspi; struct omap2_mcspi_cs *cs = spi->controller_state; struct omap2_mcspi_dma *mcspi_dma; - unsigned int count; u8 *rx; const u8 *tx; struct dma_slave_config cfg; @@ -602,10 +626,13 @@ omap2_mcspi_txrx_dma(struct spi_device *spi, struct spi_transfer *xfer) unsigned es; void __iomem *chstat_reg; void __iomem *irqstat_reg; - int wait_res; + bool tx_submitted = false, rx_submitted = false; + bool dma_started = false, terminate_failed = false; + int ret, wait_res; mcspi = spi_controller_get_devdata(spi->controller); mcspi_dma = &mcspi->dma_channels[spi_get_chipselect(spi, 0)]; + *pio_fallback = false; if (cs->word_len <= 8) { width = DMA_SLAVE_BUSWIDTH_1_BYTE; @@ -618,7 +645,7 @@ omap2_mcspi_txrx_dma(struct spi_device *spi, struct spi_transfer *xfer) es = 4; } - count = xfer->len; + *count = xfer->len; memset(&cfg, 0, sizeof(cfg)); cfg.src_addr = cs->phys + OMAP2_MCSPI_RX0; @@ -636,31 +663,39 @@ omap2_mcspi_txrx_dma(struct spi_device *spi, struct spi_transfer *xfer) reinit_completion(&mcspi_dma->dma_rx_completion); reinit_completion(&mcspi->txdone); if (tx) { - /* Enable EOW IRQ to know end of tx in target mode */ + ret = omap2_mcspi_tx_dma(spi, xfer, cfg); + if (ret) + goto out; + tx_submitted = true; + } + + if (rx) { + ret = omap2_mcspi_rx_dma(spi, xfer, cfg, es, count, + &rx_submitted, &dma_started); + if (ret) + goto out; + } else if (tx) { + if (mcspi->target_aborted) { + ret = -EINTR; + goto out; + } if (spi_controller_is_target(spi->controller)) - mcspi_write_reg(spi->controller, - OMAP2_MCSPI_IRQENABLE, + mcspi_write_reg(spi->controller, OMAP2_MCSPI_IRQENABLE, OMAP2_MCSPI_IRQSTATUS_EOW); - omap2_mcspi_tx_dma(spi, xfer, cfg); + dma_started = true; + dma_async_issue_pending(mcspi_dma->dma_tx); + omap2_mcspi_set_dma_req(spi, 0, 1); } - if (rx != NULL) - count = omap2_mcspi_rx_dma(spi, xfer, cfg, es); - - if (tx != NULL) { - int ret; - + if (tx) { ret = mcspi_wait_for_completion(mcspi, &mcspi_dma->dma_tx_completion); - if (ret || mcspi->target_aborted) { - dmaengine_terminate_sync(mcspi_dma->dma_tx); - omap2_mcspi_set_dma_req(spi, 0, 0); - return 0; - } + if (ret || mcspi->target_aborted) + goto out; if (spi_controller_is_target(mcspi->ctlr)) { ret = mcspi_wait_for_completion(mcspi, &mcspi->txdone); if (ret || mcspi->target_aborted) - return 0; + goto out; } if (mcspi->fifo_depth > 0) { @@ -694,7 +729,43 @@ omap2_mcspi_txrx_dma(struct spi_device *spi, struct spi_transfer *xfer) dev_err(&spi->dev, "EOT timed out\n"); } } - return count; + return 0; + +out: + if (!ret) + ret = -EINTR; + if (rx_submitted) { + wait_res = dmaengine_terminate_sync(mcspi_dma->dma_rx); + if (wait_res) { + dev_err(&spi->dev, "failed to terminate RX DMA: %d\n", + wait_res); + terminate_failed = true; + ret = wait_res; + } + omap2_mcspi_set_dma_req(spi, 1, 0); + } + if (tx_submitted) { + wait_res = dmaengine_terminate_sync(mcspi_dma->dma_tx); + if (wait_res) { + dev_err(&spi->dev, "failed to terminate TX DMA: %d\n", + wait_res); + terminate_failed = true; + ret = wait_res; + } + omap2_mcspi_set_dma_req(spi, 0, 0); + } + if (spi_controller_is_target(mcspi->ctlr)) + mcspi_write_reg(mcspi->ctlr, OMAP2_MCSPI_IRQENABLE, 0); + + *pio_fallback = !dma_started && !terminate_failed; + return ret; +} + +static bool omap2_mcspi_can_pio_fallback(bool cleanup_ok, + const struct spi_transfer *xfer, + bool is_target) +{ + return cleanup_ok && xfer->tx_buf && !is_target; } static unsigned @@ -1214,6 +1285,8 @@ static int omap2_mcspi_transfer_one(struct spi_controller *ctlr, if (t->len) { unsigned count; + bool pio_fallback; + int ret; if ((mcspi_dma->dma_rx && mcspi_dma->dma_tx) && spi_xfer_is_dma_mapped(ctlr, spi, t)) @@ -1227,10 +1300,31 @@ static int omap2_mcspi_transfer_one(struct spi_controller *ctlr, + OMAP2_MCSPI_TX0); if ((mcspi_dma->dma_rx && mcspi_dma->dma_tx) && - spi_xfer_is_dma_mapped(ctlr, spi, t)) - count = omap2_mcspi_txrx_dma(spi, t); - else + spi_xfer_is_dma_mapped(ctlr, spi, t)) { + ret = omap2_mcspi_txrx_dma(spi, t, &count, + &pio_fallback); + if (ret) { + bool is_target = spi_controller_is_target(ctlr); + bool fallback; + + fallback = omap2_mcspi_can_pio_fallback(pio_fallback, t, + is_target); + if (!fallback) { + status = ret; + goto out; + } + + dev_warn(&spi->dev, + "DMA setup failed, falling back to PIO\n"); + /* PIO does not use the FIFO enabled for DMA */ + omap2_mcspi_set_enable(spi, 0); + omap2_mcspi_set_fifo(spi, t, 0); + omap2_mcspi_set_enable(spi, 1); + count = omap2_mcspi_txrx_pio(spi, t); + } + } else { count = omap2_mcspi_txrx_pio(spi, t); + } if (count != t->len) { status = -EIO; @@ -1246,8 +1340,12 @@ static int omap2_mcspi_transfer_one(struct spi_controller *ctlr, out: /* Restore defaults if they were overriden */ if (par_override) { + int restore_status; + par_override = 0; - status = omap2_mcspi_setup_transfer(spi, NULL); + restore_status = omap2_mcspi_setup_transfer(spi, NULL); + if (!status) + status = restore_status; } omap2_mcspi_set_enable(spi, 0); @@ -1595,7 +1693,6 @@ static int omap2_mcspi_probe(struct platform_device *pdev) err_disable_rpm: pm_runtime_dont_use_autosuspend(&pdev->dev); - pm_runtime_put_sync(&pdev->dev); pm_runtime_disable(&pdev->dev); err_release_dma: omap2_mcspi_release_dma(ctlr); @@ -1613,7 +1710,6 @@ static void omap2_mcspi_remove(struct platform_device *pdev) omap2_mcspi_release_dma(ctlr); pm_runtime_dont_use_autosuspend(mcspi->dev); - pm_runtime_put_sync(mcspi->dev); pm_runtime_disable(&pdev->dev); } diff --git a/drivers/spi/spi-qpic-snand.c b/drivers/spi/spi-qpic-snand.c index ae4a3f2a35e1..efea3657a6d7 100644 --- a/drivers/spi/spi-qpic-snand.c +++ b/drivers/spi/spi-qpic-snand.c @@ -117,6 +117,7 @@ struct qpic_spi_nand { __le32 addr2; __le32 cmd; u32 num_cw; + bool bbm_read; bool oob_rw; bool page_rw; bool raw_rw; @@ -453,6 +454,16 @@ static int qcom_spi_ecc_prepare_io_req_pipelined(struct nand_device *nand, if (req->mode == MTD_OPS_RAW) snandc->qspi->raw_rw = true; + /* + * Try to detect when the SPI NAND framework reads the first + * two bytes of the OOB area searching for bad block marker + * bytes. + */ + snandc->qspi->bbm_read = req->mode == MTD_OPS_RAW && + req->type == NAND_PAGE_READ && + req->dataoffs == 0 && req->datalen == 0 && + req->ooboffs == 0 && req->ooblen == 2; + return 0; } @@ -506,15 +517,14 @@ static void qcom_spi_set_read_loc(struct qcom_nand_controller *snandc, int cw, i static void qcom_spi_config_cw_read(struct qcom_nand_controller *snandc, bool use_ecc, int cw) { - __le32 *reg = &snandc->regs->read_location0; - int num_cw = snandc->qspi->num_cw; - - qcom_write_reg_dma(snandc, reg, NAND_READ_LOCATION_0, 4, NAND_BAM_NEXT_SGL); - if (cw == (num_cw - 1)) { - reg = &snandc->regs->read_location_last0; - qcom_write_reg_dma(snandc, reg, NAND_READ_LOCATION_LAST_CW_0, 4, + if (cw == (snandc->qspi->num_cw - 1)) + qcom_write_reg_dma(snandc, &snandc->regs->read_location_last0, + NAND_READ_LOCATION_LAST_CW_0, 4, + NAND_BAM_NEXT_SGL); + else + qcom_write_reg_dma(snandc, &snandc->regs->read_location0, + NAND_READ_LOCATION_0, 4, NAND_BAM_NEXT_SGL); - } qcom_write_reg_dma(snandc, &snandc->regs->cmd, NAND_FLASH_CMD, 1, NAND_BAM_NEXT_SGL); qcom_write_reg_dma(snandc, &snandc->regs->exec, NAND_EXEC_CMD, 1, NAND_BAM_NEXT_SGL); @@ -658,7 +668,8 @@ static int qcom_spi_read_last_cw(struct qcom_nand_controller *snandc, * This can be removed once single-byte bad block marker support * gets implemented in the SPINAND code. */ - snandc->data_buffer[bbpos + 1] = snandc->data_buffer[bbpos]; + if (snandc->qspi->bbm_read) + snandc->data_buffer[bbpos + 1] = snandc->data_buffer[bbpos]; memcpy(op->data.buf.in, snandc->data_buffer + bbpos, op->data.nbytes); @@ -1702,6 +1713,7 @@ static void qcom_spi_remove(struct platform_device *pdev) static const struct qcom_nandc_props ipq9574_snandc_props = { .dev_cmd_reg_start = 0x7000, .bam_offset = 0x30000, + .qpic_version2 = true, .supports_bam = true, }; diff --git a/drivers/spi/spi-rockchip-sfc.c b/drivers/spi/spi-rockchip-sfc.c index 662a994da60b..a85a260ba95f 100644 --- a/drivers/spi/spi-rockchip-sfc.c +++ b/drivers/spi/spi-rockchip-sfc.c @@ -719,10 +719,12 @@ static int rockchip_sfc_probe(struct platform_device *pdev) return 0; err_register: - dma_unmap_single(dev, sfc->dma_buffer, sfc->max_iosize, - DMA_BIDIRECTIONAL); + if (sfc->use_dma) + dma_unmap_single(dev, sfc->dma_buffer, sfc->max_iosize, + DMA_BIDIRECTIONAL); err_dma_map: - free_pages((unsigned long)sfc->buffer, get_order(sfc->max_iosize)); + if (sfc->use_dma) + free_pages((unsigned long)sfc->buffer, get_order(sfc->max_iosize)); err_dma: pm_runtime_get_sync(dev); pm_runtime_put_noidle(dev); @@ -743,9 +745,16 @@ static void rockchip_sfc_remove(struct platform_device *pdev) struct spi_controller *host = sfc->host; spi_unregister_controller(host); - dma_unmap_single(&pdev->dev, sfc->dma_buffer, sfc->max_iosize, - DMA_BIDIRECTIONAL); - free_pages((unsigned long)sfc->buffer, get_order(sfc->max_iosize)); + pm_runtime_get_sync(&pdev->dev); + pm_runtime_put_noidle(&pdev->dev); + pm_runtime_disable(&pdev->dev); + pm_runtime_set_suspended(&pdev->dev); + pm_runtime_dont_use_autosuspend(&pdev->dev); + if (sfc->use_dma) { + dma_unmap_single(&pdev->dev, sfc->dma_buffer, sfc->max_iosize, + DMA_BIDIRECTIONAL); + free_pages((unsigned long)sfc->buffer, get_order(sfc->max_iosize)); + } clk_disable_unprepare(sfc->clk); clk_disable_unprepare(sfc->hclk); diff --git a/drivers/spi/spi-rspi.c b/drivers/spi/spi-rspi.c index 38df676774ee..c61edd1c1353 100644 --- a/drivers/spi/spi-rspi.c +++ b/drivers/spi/spi-rspi.c @@ -22,7 +22,6 @@ #include #include #include -#include #include #include @@ -1091,24 +1090,15 @@ static irqreturn_t rspi_irq_tx(int irq, void *_sr) static struct dma_chan *rspi_request_dma_chan(struct device *dev, enum dma_transfer_direction dir, - unsigned int id, dma_addr_t port_addr) { - dma_cap_mask_t mask; struct dma_chan *chan; struct dma_slave_config cfg; int ret; - dma_cap_zero(mask); - dma_cap_set(DMA_SLAVE, mask); - - chan = dma_request_slave_channel_compat(mask, shdma_chan_filter, - (void *)(unsigned long)id, dev, - dir == DMA_MEM_TO_DEV ? "tx" : "rx"); - if (!chan) { - dev_warn(dev, "dma_request_slave_channel_compat failed\n"); - return NULL; - } + chan = dma_request_chan(dev, dir == DMA_MEM_TO_DEV ? "tx" : "rx"); + if (IS_ERR(chan)) + return chan; memset(&cfg, 0, sizeof(cfg)); cfg.dst_addr = port_addr + RSPI_SPDR; @@ -1121,7 +1111,7 @@ static struct dma_chan *rspi_request_dma_chan(struct device *dev, if (ret) { dev_warn(dev, "dmaengine_slave_config failed %d\n", ret); dma_release_channel(chan); - return NULL; + return ERR_PTR(ret); } return chan; @@ -1130,29 +1120,23 @@ static struct dma_chan *rspi_request_dma_chan(struct device *dev, static int rspi_request_dma(struct device *dev, struct spi_controller *ctlr, const struct resource *res) { - unsigned int dma_tx_id, dma_rx_id; + struct dma_chan *chan; - if (dev->of_node) { - /* In the OF case we will get the slave IDs from the DT */ - dma_tx_id = 0; - dma_rx_id = 0; - } else { - /* The driver assumes no error. */ + if (!dev->of_node) return 0; - } - ctlr->dma_tx = rspi_request_dma_chan(dev, DMA_MEM_TO_DEV, dma_tx_id, - res->start); - if (!ctlr->dma_tx) - return -ENODEV; + chan = rspi_request_dma_chan(dev, DMA_MEM_TO_DEV, res->start); + if (IS_ERR(chan)) + return PTR_ERR(chan); + ctlr->dma_tx = chan; - ctlr->dma_rx = rspi_request_dma_chan(dev, DMA_DEV_TO_MEM, dma_rx_id, - res->start); - if (!ctlr->dma_rx) { + chan = rspi_request_dma_chan(dev, DMA_DEV_TO_MEM, res->start); + if (IS_ERR(chan)) { dma_release_channel(ctlr->dma_tx); ctlr->dma_tx = NULL; - return -ENODEV; + return PTR_ERR(chan); } + ctlr->dma_rx = chan; ctlr->can_dma = rspi_can_dma; dev_info(dev, "DMA available"); @@ -1355,6 +1339,11 @@ static int rspi_probe(struct platform_device *pdev) } ret = rspi_request_dma(&pdev->dev, ctlr, res); + if (ret == -EPROBE_DEFER) { + dev_err_probe(&pdev->dev, ret, + "failed to request DMA channels\n"); + goto error2; + } if (ret < 0) dev_warn(&pdev->dev, "DMA not available, using PIO\n"); diff --git a/drivers/spi/spi-sh-msiof.c b/drivers/spi/spi-sh-msiof.c index 1aeab7ec0bc8..4c425ec62776 100644 --- a/drivers/spi/spi-sh-msiof.c +++ b/drivers/spi/spi-sh-msiof.c @@ -453,6 +453,7 @@ static int sh_msiof_spi_setup(struct spi_device *spi) struct sh_msiof_spi_priv *p = spi_controller_get_devdata(spi->controller); u32 clr, set, tmp; + int ret; if (spi_get_csgpiod(spi, 0) || spi_controller_is_target(p->ctlr)) return 0; @@ -468,7 +469,9 @@ static int sh_msiof_spi_setup(struct spi_device *spi) clr |= SIMDR1_SYNCAC; else set |= SIMDR1_SYNCAC; - pm_runtime_get_sync(&p->pdev->dev); + ret = pm_runtime_resume_and_get(&p->pdev->dev); + if (ret < 0) + return ret; tmp = sh_msiof_read(p, SITMDR1) & ~clr; sh_msiof_write(p, SITMDR1, tmp | set | SIMDR1_TRMD | SITMDR1_PCON); tmp = sh_msiof_read(p, SIRMDR1) & ~clr; diff --git a/drivers/spi/spi-sun4i.c b/drivers/spi/spi-sun4i.c index d5c16392cd4d..ea8be0170fbf 100644 --- a/drivers/spi/spi-sun4i.c +++ b/drivers/spi/spi-sun4i.c @@ -82,6 +82,8 @@ struct sun4i_spi { struct completion done; + int irq; + const u8 *tx_buf; u8 *rx_buf; int len; @@ -142,15 +144,21 @@ static inline void sun4i_spi_drain_fifo(struct sun4i_spi *sspi, int len) } } -static inline void sun4i_spi_fill_fifo(struct sun4i_spi *sspi, int len) +static inline void sun4i_spi_fill_fifo(struct sun4i_spi *sspi) { u32 cnt; + int len; u8 byte; - /* See how much data we can fit */ - cnt = SUN4I_FIFO_DEPTH - sun4i_spi_get_tx_fifo_count(sspi); + /* + * See how much data we can fit + * + * Filling the FIFO fully causes timeout for some reason + * at least on spi2 on A10s + */ + cnt = SUN4I_FIFO_DEPTH - 1 - sun4i_spi_get_tx_fifo_count(sspi); - len = min3(len, (int)cnt, sspi->len); + len = min_t(int, cnt, sspi->len); while (len--) { byte = sspi->tx_buf ? *sspi->tx_buf++ : 0; @@ -206,7 +214,7 @@ static int sun4i_spi_transfer_one(struct spi_controller *host, struct spi_transfer *tfr) { struct sun4i_spi *sspi = spi_controller_get_devdata(host); - unsigned int mclk_rate, div; + unsigned int mclk_rate, div, div_cdr1, div_cdr2; unsigned long time_left; unsigned int start, end, tx_time; unsigned int tx_len = 0; @@ -290,15 +298,13 @@ static int sun4i_spi_transfer_one(struct spi_controller *host, * First try CDR2, and if we can't reach the expected * frequency, fall back to CDR1. */ - div = mclk_rate / (2 * tfr->speed_hz); - if (div <= (SUN4I_CLK_CTL_CDR2_MASK + 1)) { - if (div > 0) - div--; - - reg = SUN4I_CLK_CTL_CDR2(div) | SUN4I_CLK_CTL_DRS; + div_cdr1 = DIV_ROUND_UP(mclk_rate, tfr->speed_hz); + div_cdr2 = DIV_ROUND_UP(div_cdr1, 2); + if (div_cdr2 <= (SUN4I_CLK_CTL_CDR2_MASK + 1)) { + reg = SUN4I_CLK_CTL_CDR2(div_cdr2 - 1) | SUN4I_CLK_CTL_DRS; } else { - div = ilog2(mclk_rate) - ilog2(tfr->speed_hz); - reg = SUN4I_CLK_CTL_CDR1(div); + div = min(SUN4I_CLK_CTL_CDR1_MASK + 1, order_base_2(div_cdr1)); + reg = SUN4I_CLK_CTL_CDR1(div - 1); } sun4i_spi_write(sspi, SUN4I_CLK_CTL_REG, reg); @@ -311,18 +317,14 @@ static int sun4i_spi_transfer_one(struct spi_controller *host, sun4i_spi_write(sspi, SUN4I_BURST_CNT_REG, SUN4I_BURST_CNT(tfr->len)); sun4i_spi_write(sspi, SUN4I_XMIT_CNT_REG, SUN4I_XMIT_CNT(tx_len)); - /* - * Fill the TX FIFO - * Filling the FIFO fully causes timeout for some reason - * at least on spi2 on A10s - */ - sun4i_spi_fill_fifo(sspi, SUN4I_FIFO_DEPTH - 1); + /* Fill the TX FIFO */ + sun4i_spi_fill_fifo(sspi); /* Enable the interrupts */ sun4i_spi_enable_interrupt(sspi, SUN4I_INT_CTL_TC | SUN4I_INT_CTL_RF_F34); /* Only enable Tx FIFO interrupt if we really need it */ - if (tx_len > SUN4I_FIFO_DEPTH) + if (tx_len > SUN4I_FIFO_DEPTH - 1) sun4i_spi_enable_interrupt(sspi, SUN4I_INT_CTL_TF_E34); /* Start the transfer */ @@ -333,6 +335,7 @@ static int sun4i_spi_transfer_one(struct spi_controller *host, start = jiffies; time_left = wait_for_completion_timeout(&sspi->done, msecs_to_jiffies(tx_time)); + end = jiffies; if (!time_left) { dev_warn(&host->dev, @@ -340,12 +343,11 @@ static int sun4i_spi_transfer_one(struct spi_controller *host, dev_name(&spi->dev), tfr->len, tfr->speed_hz, jiffies_to_msecs(end - start), tx_time); ret = -ETIMEDOUT; - goto out; + sun4i_spi_write(sspi, SUN4I_INT_CTL_REG, 0); + synchronize_irq(sspi->irq); } - -out: - sun4i_spi_write(sspi, SUN4I_INT_CTL_REG, 0); + sun4i_spi_drain_fifo(sspi, SUN4I_FIFO_DEPTH); return ret; } @@ -357,8 +359,7 @@ static irqreturn_t sun4i_spi_handler(int irq, void *dev_id) /* Transfer complete */ if (status & SUN4I_INT_CTL_TC) { - sun4i_spi_write(sspi, SUN4I_INT_STA_REG, SUN4I_INT_CTL_TC); - sun4i_spi_drain_fifo(sspi, SUN4I_FIFO_DEPTH); + sun4i_spi_write(sspi, SUN4I_INT_CTL_REG, 0); complete(&sspi->done); return IRQ_HANDLED; } @@ -373,7 +374,7 @@ static irqreturn_t sun4i_spi_handler(int irq, void *dev_id) /* Transmit FIFO 3/4 empty */ if (status & SUN4I_INT_CTL_TF_E34) { - sun4i_spi_fill_fifo(sspi, SUN4I_FIFO_DEPTH); + sun4i_spi_fill_fifo(sspi); if (!sspi->len) /* nothing left to transmit */ @@ -456,6 +457,7 @@ static int sun4i_spi_probe(struct platform_device *pdev) return ret; } + sspi->irq = irq; sspi->host = host; host->max_speed_hz = 100 * 1000 * 1000; host->min_speed_hz = 3 * 1000; diff --git a/drivers/spi/spi-tegra114.c b/drivers/spi/spi-tegra114.c index 5f8d8da7a3fc..f43f2df478b4 100644 --- a/drivers/spi/spi-tegra114.c +++ b/drivers/spi/spi-tegra114.c @@ -1308,6 +1308,9 @@ static int tegra_spi_probe(struct platform_device *pdev) struct resource *r; int ret, spi_irq; int bus_num; + u32 conflicting_cs; + u32 enabled_child_cs_polarity = 0, disabled_child_cs_low = 0, disabled_child_cs_high = 0; + u32 enabled_cs_mask = 0; host = devm_spi_alloc_host(&pdev->dev, sizeof(*tspi)); if (!host) { @@ -1402,6 +1405,52 @@ static int tegra_spi_probe(struct platform_device *pdev) udelay(2); reset_control_deassert(tspi->rst); tspi->def_command1_reg = SPI_M_S; + + /* + * SPI_COMMAND1 is written before any child is registered, so a chip + * select with CS_POL_INACTIVE clear stays asserted until + * tegra_spi_setup() runs for that device. Program the level the + * device tree asks for up front instead. + * + * Disabled children are included deliberately. The core never + * registers them, so this is the only chance to park their chip + * select at the level their hardware needs. An enabled child on the + * same CS takes priority. + */ + for_each_child_of_node_scoped(pdev->dev.of_node, np) { + u32 cs; + u32 polarity_bitmask; + u32 cs_polarity = 0; + + if (of_property_read_u32(np, "reg", &cs)) + continue; + + if (cs >= MAX_CHIP_SELECT) + continue; + + polarity_bitmask = SPI_CS_POL_INACTIVE(cs); + if (!of_property_read_bool(np, "spi-cs-high")) + cs_polarity = polarity_bitmask; + + if (of_device_is_available(np)) { + enabled_cs_mask |= polarity_bitmask; + enabled_child_cs_polarity |= cs_polarity; + } else { + if (cs_polarity) + disabled_child_cs_low |= polarity_bitmask; + else + disabled_child_cs_high |= polarity_bitmask; + } + } + conflicting_cs = disabled_child_cs_low & disabled_child_cs_high & ~enabled_cs_mask; + for (u32 cs = 0; cs < MAX_CHIP_SELECT; cs++) { + if (SPI_CS_POL_INACTIVE(cs) & conflicting_cs) + dev_warn(&pdev->dev, + "Conflicting CS polarity on disabled nodes at cs %u\n", cs); + } + + tspi->def_command1_reg |= enabled_child_cs_polarity | + (disabled_child_cs_low & ~enabled_cs_mask); tegra_spi_writel(tspi, tspi->def_command1_reg, SPI_COMMAND1); tspi->spi_cs_timing1 = tegra_spi_readl(tspi, SPI_CS_TIMING1); tspi->spi_cs_timing2 = tegra_spi_readl(tspi, SPI_CS_TIMING2); diff --git a/drivers/spi/spi-virtio.c b/drivers/spi/spi-virtio.c index 3e181bd8bc94..96cdaf1b3697 100644 --- a/drivers/spi/spi-virtio.c +++ b/drivers/spi/spi-virtio.c @@ -33,8 +33,6 @@ struct virtio_spi_priv { struct virtqueue *vq; /* Copy of config space mode_func_supported */ u32 mode_func_supported; - /* Copy of config space max_freq_hz */ - u32 max_freq_hz; }; static void virtio_spi_msg_done(struct virtqueue *vq) @@ -304,7 +302,7 @@ static void virtio_spi_read_config(struct virtio_device *vdev) virtio_cread32(vdev, offsetof(struct virtio_spi_config, bits_per_word_mask)); - priv->max_freq_hz = + ctrl->max_speed_hz = virtio_cread32(vdev, offsetof(struct virtio_spi_config, max_freq_hz)); } diff --git a/drivers/spi/spi.c b/drivers/spi/spi.c index 5b5b3bc5f0d8..172141650b64 100644 --- a/drivers/spi/spi.c +++ b/drivers/spi/spi.c @@ -2893,7 +2893,7 @@ static void of_register_spi_devices(struct spi_controller *ctlr) { } * * This may only be called from main SPI device's probe routine. * - * Return: 0 on success; negative errno on failure + * Return: the new device on success; an ERR_PTR() on failure */ struct spi_device *spi_new_ancillary_device(struct spi_device *spi, u8 chip_select) diff --git a/drivers/spmi/spmi-mtk-pmif.c b/drivers/spmi/spmi-mtk-pmif.c index 1048420b5afb..833c2b30d09f 100644 --- a/drivers/spmi/spmi-mtk-pmif.c +++ b/drivers/spmi/spmi-mtk-pmif.c @@ -21,6 +21,7 @@ #define SWINF_WFVLDCLR 0x06 #define GET_SWINF(x) (((x) >> 1) & 0x7) +#define GET_SWINFERR(x) (((x) >> 18) & 0x1) #define PMIF_CMD_REG_0 0 #define PMIF_CMD_REG 1 @@ -349,6 +350,7 @@ static int pmif_spmi_read_cmd(struct spmi_controller *ctrl, u8 opc, u8 sid, struct pmif *arb = to_mtk_pmif(ctrl); struct ch_reg *inf_reg; int ret; + u8 retry = 0; u32 data, cmd; unsigned long flags; @@ -385,17 +387,35 @@ static int pmif_spmi_read_cmd(struct spmi_controller *ctrl, u8 opc, u8 sid, return ret; } - /* Send the command. */ cmd = (opc << 30) | (sid << 24) | ((len - 1) << 16) | addr; - pmif_writel(arb, pbus, cmd, inf_reg->ch_send); + do { + /* Send the command. */ + pmif_writel(arb, pbus, cmd, inf_reg->ch_send); + + /* + * Wait for Software Interface FSM state to be WFVLDCLR or to + * return an error. + * + * If this is WFVLDCLR, read the data and clear the valid flag; + * If error or timeout, retry for a maximum of 3 times as a + * workaround for an hardware issue. + */ + ret = readl_poll_timeout_atomic(pbus->base + arb->data->regs[inf_reg->ch_sta], + data, + GET_SWINF(data) == SWINF_WFVLDCLR || + GET_SWINFERR(data), + PMIF_DELAY_US, PMIF_TIMEOUT_US / 2); + if (ret < 0) + continue; + + if (GET_SWINFERR(data)) { + ret = -EIO; + continue; + } + + break; + } while (++retry < 3); - /* - * Wait for Software Interface FSM state to be WFVLDCLR, - * read the data and clear the valid flag. - */ - ret = readl_poll_timeout_atomic(pbus->base + arb->data->regs[inf_reg->ch_sta], - data, GET_SWINF(data) == SWINF_WFVLDCLR, - PMIF_DELAY_US, PMIF_TIMEOUT_US); if (ret < 0) { raw_spin_unlock_irqrestore(&pbus->lock, flags); dev_err(&ctrl->dev, "failed to wait for SWINF_WFVLDCLR\n"); @@ -726,9 +746,11 @@ static int mtk_spmi_bus_probe(struct platform_device *pdev, for (i = 0; i < pbus->nclks; i++) { pbus->clks[i].id = pmif_clock_names[i]; pbus->clks[i].clk = of_clk_get_by_name(node, pbus->clks[i].id); - if (IS_ERR(pbus->clks[i].clk)) + if (IS_ERR(pbus->clks[i].clk)) { + clk_bulk_put(i, pbus->clks); return dev_err_probe(&pdev->dev, PTR_ERR(pbus->clks[i].clk), "Failed to get clocks\n"); + } } err = clk_bulk_prepare_enable(pbus->nclks, pbus->clks); diff --git a/drivers/spmi/spmi-pmic-arb.c b/drivers/spmi/spmi-pmic-arb.c index 2e2cb4774103..402ffeaff8e2 100644 --- a/drivers/spmi/spmi-pmic-arb.c +++ b/drivers/spmi/spmi-pmic-arb.c @@ -2060,7 +2060,7 @@ static int spmi_pmic_arb_register_buses(struct spmi_pmic_arb *pmic_arb, } } - return ret; + return 0; } static void spmi_pmic_arb_deregister_buses(struct spmi_pmic_arb *pmic_arb) diff --git a/drivers/staging/iio/adc/ad7816.c b/drivers/staging/iio/adc/ad7816.c index 30644d2d7c54..2a15d7598abb 100644 --- a/drivers/staging/iio/adc/ad7816.c +++ b/drivers/staging/iio/adc/ad7816.c @@ -5,19 +5,21 @@ * Copyright 2010 Analog Devices Inc. */ -#include -#include +#include #include +#include +#include #include -#include -#include #include -#include #include +#include +#include +#include +#include +#include #include #include -#include /* * AD7816 config masks @@ -47,6 +49,7 @@ struct ad7816_chip_info { struct gpio_desc *rdwr_pin; struct gpio_desc *convert_pin; struct gpio_desc *busy_pin; + struct mutex lock; /* protect device state during SPI transfers */ u8 oti_data[AD7816_CS_MAX + 1]; u8 channel_id; /* 0 always be temperature */ u8 mode; @@ -67,9 +70,11 @@ static int ad7816_spi_read(struct ad7816_chip_info *chip, u16 *data) int ret; __be16 buf; + guard(mutex)(&chip->lock); + gpiod_set_value(chip->rdwr_pin, 1); gpiod_set_value(chip->rdwr_pin, 0); - ret = spi_write(spi_dev, &chip->channel_id, sizeof(chip->channel_id)); + ret = spi_write_then_read(spi_dev, &chip->channel_id, sizeof(chip->channel_id), NULL, 0); if (ret < 0) { dev_err(&spi_dev->dev, "SPI channel setting error\n"); return ret; @@ -91,7 +96,7 @@ static int ad7816_spi_read(struct ad7816_chip_info *chip, u16 *data) gpiod_set_value(chip->rdwr_pin, 0); gpiod_set_value(chip->rdwr_pin, 1); - ret = spi_read(spi_dev, &buf, sizeof(*data)); + ret = spi_write_then_read(spi_dev, NULL, 0, &buf, sizeof(buf)); if (ret < 0) { dev_err(&spi_dev->dev, "SPI data read error\n"); return ret; @@ -107,9 +112,11 @@ static int ad7816_spi_write(struct ad7816_chip_info *chip, u8 data) struct spi_device *spi_dev = chip->spi_dev; int ret; + guard(mutex)(&chip->lock); + gpiod_set_value(chip->rdwr_pin, 1); gpiod_set_value(chip->rdwr_pin, 0); - ret = spi_write(spi_dev, &data, sizeof(data)); + ret = spi_write_then_read(spi_dev, &data, sizeof(data), NULL, 0); if (ret < 0) dev_err(&spi_dev->dev, "SPI oti data write error\n"); @@ -136,6 +143,8 @@ static ssize_t ad7816_store_mode(struct device *dev, struct iio_dev *indio_dev = dev_to_iio_dev(dev); struct ad7816_chip_info *chip = iio_priv(indio_dev); + guard(mutex)(&chip->lock); + if (strcmp(buf, "full") == 0) { gpiod_set_value(chip->rdwr_pin, 1); chip->mode = AD7816_FULL; @@ -200,6 +209,8 @@ static ssize_t ad7816_store_channel(struct device *dev, return -EINVAL; } + guard(mutex)(&chip->lock); + chip->channel_id = data; return len; @@ -360,6 +371,10 @@ static int ad7816_probe(struct spi_device *spi_dev) return -ENOMEM; chip = iio_priv(indio_dev); + ret = devm_mutex_init(&spi_dev->dev, &chip->lock); + if (ret) + return ret; + chip->spi_dev = spi_dev; for (i = 0; i <= AD7816_CS_MAX; i++) chip->oti_data[i] = 203; diff --git a/drivers/staging/media/ipu7/ipu7-isys.c b/drivers/staging/media/ipu7/ipu7-isys.c index 601e5a79ef8e..a54393fbb9db 100644 --- a/drivers/staging/media/ipu7/ipu7-isys.c +++ b/drivers/staging/media/ipu7/ipu7-isys.c @@ -590,6 +590,7 @@ static void isys_remove(struct auxiliary_device *auxdev) isys_notifier_cleanup(isys); isys_unregister_devices(isys); + ipu7_fw_isys_release(isys); cpu_latency_qos_remove_request(&isys->pm_qos); diff --git a/drivers/staging/media/tegra-video/tegra20.c b/drivers/staging/media/tegra-video/tegra20.c index eb1fc5b7e2cd..cdadff98eae7 100644 --- a/drivers/staging/media/tegra-video/tegra20.c +++ b/drivers/staging/media/tegra-video/tegra20.c @@ -429,12 +429,13 @@ static int tegra20_channel_host1x_syncpt_init(struct tegra_vi_channel *chan) if (!out_sp) return dev_err_probe(vi->dev, -EBUSY, "failed to request mw ack syncpoint\n"); - chan->mw_ack_sp[0] = out_sp; - fs_sp = host1x_syncpt_request(&vi->client, HOST1X_SYNCPT_CLIENT_MANAGED); - if (!fs_sp) + if (!fs_sp) { + host1x_syncpt_put(out_sp); return dev_err_probe(vi->dev, -EBUSY, "failed to request frame start syncpoint\n"); + } + chan->mw_ack_sp[0] = out_sp; chan->frame_start_sp[0] = fs_sp; return 0; diff --git a/drivers/staging/octeon/ethernet-tx.c b/drivers/staging/octeon/ethernet-tx.c index cc20c1e6791f..5e536827f87a 100644 --- a/drivers/staging/octeon/ethernet-tx.c +++ b/drivers/staging/octeon/ethernet-tx.c @@ -481,7 +481,7 @@ netdev_tx_t cvm_oct_xmit(struct sk_buff *skb, struct net_device *dev) cvmx_fau_fetch_and_add32(FAU_TOTAL_TX_TO_CLEAN, 1); } - if (total_to_clean & 0x3ff) { + if ((total_to_clean & 0x3ff) == 0) { /* * Schedule the cleanup tasklet every 1024 packets for * the pathological case of high traffic on one port diff --git a/drivers/staging/rtl8723bs/os_dep/sdio_intf.c b/drivers/staging/rtl8723bs/os_dep/sdio_intf.c index c61d3d12df7f..6ef3a7198533 100644 --- a/drivers/staging/rtl8723bs/os_dep/sdio_intf.c +++ b/drivers/staging/rtl8723bs/os_dep/sdio_intf.c @@ -122,8 +122,10 @@ static u32 sdio_init(struct dvobj_priv *dvobj) goto release; err = sdio_set_block_size(func, 512); - if (err) + if (err) { + sdio_disable_func(func); goto release; + } psdio_data->block_transfer_len = 512; psdio_data->tx_block_mode = 1; diff --git a/drivers/staging/sm750fb/sm750.c b/drivers/staging/sm750fb/sm750.c index 8b93bfeb217b..68b6d4fe79ca 100644 --- a/drivers/staging/sm750fb/sm750.c +++ b/drivers/staging/sm750fb/sm750.c @@ -825,6 +825,11 @@ static int lynxfb_set_fbinfo(struct fb_info *info, int index) return ret; } +static void lynxfb_unset_fbinfo(struct fb_info *info) +{ + fb_dealloc_cmap(&info->cmap); +} + /* chip specific g_option configuration routine */ static void sm750fb_setup(struct sm750_dev *sm750_dev, char *src) { @@ -910,6 +915,7 @@ static void sm750fb_framebuffer_release(struct sm750_dev *sm750_dev) while (sm750_dev->fb_count) { fb_info = sm750_dev->fbinfo[sm750_dev->fb_count - 1]; unregister_framebuffer(fb_info); + lynxfb_unset_fbinfo(fb_info); framebuffer_release(fb_info); sm750_dev->fb_count--; } @@ -936,12 +942,14 @@ static int sm750fb_framebuffer_alloc(struct sm750_dev *sm750_dev, int fbidx) err = register_framebuffer(fb_info); if (err < 0) - goto release_fb; + goto unset_fb; sm750_dev->fb_count++; return 0; +unset_fb: + lynxfb_unset_fbinfo(fb_info); release_fb: framebuffer_release(fb_info); return err; diff --git a/drivers/thermal/airoha_thermal.c b/drivers/thermal/airoha_thermal.c index 77b3a1af271f..1b187c41baea 100644 --- a/drivers/thermal/airoha_thermal.c +++ b/drivers/thermal/airoha_thermal.c @@ -18,10 +18,10 @@ #define EN7581_DOUT_TADC 0x2f8 #define EN7581_DOUT_TADC_MASK GENMASK(15, 0) -#define AN7583_MUX_SENSOR 0x2a0 +#define AN7583_MUX_TADC 0x2a0 #define AN7583_LOAD_ADJ GENMASK(3, 2) -#define AN7583_MUX_TADC 0x2e4 -#define AN7583_MUX_TADC_MASK GENMASK(3, 1) +#define AN7583_MUX_SENSOR 0x2e4 +#define AN7583_MUX_SENSOR_MASK GENMASK(3, 1) #define AN7583_DOUT_TADC 0x2f0 /* PTP_THERMAL regs */ @@ -528,7 +528,7 @@ static int en7581_thermal_probe(struct platform_device *pdev, struct device_node *chip_scu_np; struct device *dev = &pdev->dev; void __iomem *base; - int i, irq, ret; + int i; base = devm_platform_ioremap_resource(pdev, 0); if (IS_ERR(base)) @@ -567,16 +567,6 @@ static int en7581_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, - en7581_thermal_irq, IRQF_ONESHOT, - pdev->name, priv); - if (ret) - return ret; - en7581_thermal_setup_monitor(priv); en7581_thermal_setup_adc_val(dev, priv); @@ -586,6 +576,18 @@ static int en7581_thermal_probe(struct platform_device *pdev, static int en7581_thermal_post_probe(struct platform_device *pdev) { struct airoha_thermal_priv *priv = platform_get_drvdata(pdev); + int irq, ret; + + /* 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, + en7581_thermal_irq, IRQF_ONESHOT, + pdev->name, priv); + if (ret) + return ret; /* Enable LOW and HIGH interrupt (if supported) */ regmap_write(priv->map, EN7581_TEMPMONINT, @@ -634,8 +636,8 @@ static const struct thermal_zone_device_ops an7583_tz_ops = { static const struct reg_field an7583_chip_scu_fields[AIROHA_THERMAL_FIELD_MAX] = { [AIROHA_THERMAL_DOUT_TADC] = REG_FIELD(AN7583_DOUT_TADC, 0, 31), - [AIROHA_THERMAL_MUX_TADC] = REG_FIELD(AN7583_MUX_TADC, 1, 3), - [AIROHA_THERMAL_MUX_SENSOR] = REG_FIELD(AN7583_MUX_SENSOR, 2, 3), + [AIROHA_THERMAL_MUX_TADC] = REG_FIELD(AN7583_MUX_TADC, 2, 3), + [AIROHA_THERMAL_MUX_SENSOR] = REG_FIELD(AN7583_MUX_SENSOR, 1, 3), }; static int an7583_thermal_probe(struct platform_device *pdev, diff --git a/drivers/thermal/amlogic_thermal.c b/drivers/thermal/amlogic_thermal.c index a0b530624b60..60728de6968a 100644 --- a/drivers/thermal/amlogic_thermal.c +++ b/drivers/thermal/amlogic_thermal.c @@ -100,7 +100,8 @@ struct amlogic_thermal { const struct amlogic_thermal_data *data; struct regmap *regmap; struct regmap *sec_ao_map; - struct clk *clk; + struct clk_bulk_data *clks; + int num_clks; struct thermal_zone_device *tzd; u32 trim_info; struct meson_sm_firmware *sm_fw; @@ -142,7 +143,7 @@ static int amlogic_thermal_enable(struct amlogic_thermal *data) { int ret; - ret = clk_prepare_enable(data->clk); + ret = clk_bulk_prepare_enable(data->num_clks, data->clks); if (ret) return ret; @@ -156,7 +157,7 @@ static void amlogic_thermal_disable(struct amlogic_thermal *data) { regmap_update_bits(data->regmap, TSENSOR_CFG_REG1, TSENSOR_CFG_REG1_ENABLE, 0); - clk_disable_unprepare(data->clk); + clk_bulk_disable_unprepare(data->num_clks, data->clks); } static int amlogic_thermal_get_temp(struct thermal_zone_device *tz, int *temp) @@ -323,9 +324,10 @@ static int amlogic_thermal_probe(struct platform_device *pdev) if (IS_ERR(pdata->regmap)) return PTR_ERR(pdata->regmap); - pdata->clk = devm_clk_get(dev, NULL); - if (IS_ERR(pdata->clk)) - return dev_err_probe(dev, PTR_ERR(pdata->clk), "failed to get clock\n"); + ret = devm_clk_bulk_get_all(dev, &pdata->clks); + if (ret <= 0) + return dev_err_probe(dev, ret ?: -ENOENT, "failed to get clocks\n"); + pdata->num_clks = ret; if (pdata->data->use_sm) ret = amlogic_thermal_probe_sm(pdev, pdata); diff --git a/drivers/thermal/gov_power_allocator.c b/drivers/thermal/gov_power_allocator.c index 37f2e22a999e..b5c254187628 100644 --- a/drivers/thermal/gov_power_allocator.c +++ b/drivers/thermal/gov_power_allocator.c @@ -660,10 +660,15 @@ static void power_allocator_update_tz(struct thermal_zone_device *tz, enum thermal_notify_event reason) { struct power_allocator_params *params = tz->governor_data; - const struct thermal_trip_desc *td = trip_to_trip_desc(params->trip_max); + const struct thermal_trip_desc *td; struct thermal_instance *instance; int num_actors = 0; + if (!params->trip_max) + return; + + td = trip_to_trip_desc(params->trip_max); + switch (reason) { case THERMAL_TZ_BIND_CDEV: case THERMAL_TZ_UNBIND_CDEV: diff --git a/drivers/thermal/qcom/qcom-spmi-temp-alarm.c b/drivers/thermal/qcom/qcom-spmi-temp-alarm.c index fb003ca96454..911ebfd0cdeb 100644 --- a/drivers/thermal/qcom/qcom-spmi-temp-alarm.c +++ b/drivers/thermal/qcom/qcom-spmi-temp-alarm.c @@ -345,8 +345,8 @@ static int qpnp_tm_update_critical_trip_temp(struct qpnp_tm_chip *chip, } skip: - memcpy(chip->temp_thresh_map, chip->data->temp_map[threshold], - sizeof(chip->temp_thresh_map)); + memcpy(chip->temp_thresh_map, (*chip->data->temp_map)[threshold], + sizeof(chip->temp_thresh_map)); reg |= threshold; if (disable_stage2_shutdown && !chip->require_stage2_shutdown) reg |= SHUTDOWN_CTRL1_OVERRIDE_STAGE2; @@ -535,8 +535,8 @@ static int qpnp_tm_sync_thresholds(struct qpnp_tm_chip *chip) return ret; threshold = reg & SHUTDOWN_CTRL1_THRESHOLD_MASK; - memcpy(chip->temp_thresh_map, chip->data->temp_map[threshold], - sizeof(chip->temp_thresh_map)); + memcpy(chip->temp_thresh_map, (*chip->data->temp_map)[threshold], + sizeof(chip->temp_thresh_map)); return ret; } diff --git a/drivers/thermal/renesas/rzg3e_thermal.c b/drivers/thermal/renesas/rzg3e_thermal.c index c44f5b8858d0..8b89cdaa7603 100644 --- a/drivers/thermal/renesas/rzg3e_thermal.c +++ b/drivers/thermal/renesas/rzg3e_thermal.c @@ -93,6 +93,7 @@ struct rzg3e_thermal_info { * @info: chip type specific information * @trmval0: calibration value 0 (b) * @trmval1: calibration value 1 (c) + * @sier: cached interrupt enable register * @lock: protects hardware access during conversions */ struct rzg3e_thermal_priv { @@ -103,6 +104,7 @@ struct rzg3e_thermal_priv { const struct rzg3e_thermal_info *info; u16 trmval0; u16 trmval1; + u32 sier; struct mutex lock; }; @@ -148,12 +150,16 @@ static int rzg3e_thermal_power_on(struct rzg3e_thermal_priv *priv) return ret; } + /* Restore interrupt enable state */ + writel(priv->sier, priv->base + TSU_SIER); + return 0; } static void rzg3e_thermal_power_off(struct rzg3e_thermal_priv *priv) { - /* Disable all interrupts */ + /* Save and disable all interrupts */ + priv->sier = readl(priv->base + TSU_SIER); writel(0, priv->base + TSU_SIER); /* Clear pending interrupts */ @@ -194,7 +200,12 @@ static u16 rzg3e_thermal_temp_to_code(struct rzg3e_thermal_priv *priv, int temp_ s64 numerator, denominator; s64 code; - numerator = (temp_mc - info->temp_d_mc) * (priv->trmval1 - priv->trmval0); + /* + * Perform the arithmetic in 64 bits so that it cannot overflow for + * -INT_MAX/INT_MAX values passed from the thermal core or when + * userspace writes arbitrary trip point temperatures. + */ + numerator = ((s64)temp_mc - info->temp_d_mc) * (priv->trmval1 - priv->trmval0); denominator = info->temp_e_mc - info->temp_d_mc; code = div64_s64(numerator, denominator) + priv->trmval0; @@ -214,6 +225,16 @@ static int rzg3e_thermal_get_temp(struct thermal_zone_device *tz, int *temp) guard(mutex)(&priv->lock); + /* Make sure a previous conversion is not in progress */ + ret = readl_poll_timeout(priv->base + TSU_SSR, status, + !(status & TSU_SSR_CONV), + TSU_POLL_DELAY_US, + USEC_PER_MSEC); + if (ret) { + dev_err(priv->dev, "Timeout waiting for conversion\n"); + goto out; + } + /* Clear any previous conversion status */ writel(TSU_SICR_ADCLR, priv->base + TSU_SICR); @@ -293,9 +314,8 @@ static int rzg3e_thermal_set_trips(struct thermal_zone_device *tz, /* Enable comparison with "out of range" mode (CMPCOND=0) */ writel(TSU_CMSR_CMPEN, priv->base + TSU_CMSR); - /* Unmask compare IRQ and start a conversion to evaluate window */ + /* Unmask compare IRQ */ writel(TSU_SIER_CMPIE, priv->base + TSU_SIER); - writel(TSU_STRGR_ADST, priv->base + TSU_STRGR); pm_runtime_mark_last_busy(priv->dev); pm_runtime_put_autosuspend(priv->dev); @@ -499,15 +519,19 @@ static int rzg3e_thermal_runtime_resume(struct device *dev) static int rzg3e_thermal_suspend(struct device *dev) { struct rzg3e_thermal_priv *priv = dev_get_drvdata(dev); + bool active = pm_runtime_active(dev); + int ret; /* If device is active, power it off */ - if (pm_runtime_active(dev)) + if (active) rzg3e_thermal_power_off(priv); /* Assert reset to ensure clean state after resume */ - reset_control_assert(priv->rstc); + ret = reset_control_assert(priv->rstc); + if (ret && active) + rzg3e_thermal_power_on(priv); - return 0; + return ret; } static int rzg3e_thermal_resume(struct device *dev) diff --git a/drivers/thermal/sprd_thermal.c b/drivers/thermal/sprd_thermal.c index d683fcb0f8ab..b57277e2eac0 100644 --- a/drivers/thermal/sprd_thermal.c +++ b/drivers/thermal/sprd_thermal.c @@ -396,6 +396,12 @@ static int sprd_thm_probe(struct platform_device *pdev) goto of_put; } + if (sen->id < 0 || sen->id >= SPRD_THM_MAX_SENSOR) { + dev_err(&pdev->dev, "invalid sensor id %d\n", sen->id); + ret = -EINVAL; + goto of_put; + } + ret = sprd_thm_sensor_calibration(sen_child, thm, sen); if (ret) { dev_err(&pdev->dev, "efuse cal analysis failed"); diff --git a/drivers/thermal/thermal_trace.h b/drivers/thermal/thermal_trace.h index df8f4edd6068..2f953fd8289d 100644 --- a/drivers/thermal/thermal_trace.h +++ b/drivers/thermal/thermal_trace.h @@ -119,7 +119,7 @@ TRACE_EVENT(thermal_power_cpu_limit, TP_ARGS(cpus, freq, cdev_state, power), TP_STRUCT__entry( - __bitmask(cpumask, num_possible_cpus()) + __bitmask(cpumask, nr_cpumask_bits) __field(unsigned int, freq ) __field(unsigned long, cdev_state) __field(u32, power ) @@ -127,7 +127,7 @@ TRACE_EVENT(thermal_power_cpu_limit, TP_fast_assign( __assign_bitmask(cpumask, cpumask_bits(cpus), - num_possible_cpus()); + nr_cpumask_bits); __entry->freq = freq; __entry->cdev_state = cdev_state; __entry->power = power; diff --git a/drivers/thermal/ti-soc-thermal/ti-bandgap.c b/drivers/thermal/ti-soc-thermal/ti-bandgap.c index ba43399d0b38..815ca0786c54 100644 --- a/drivers/thermal/ti-soc-thermal/ti-bandgap.c +++ b/drivers/thermal/ti-soc-thermal/ti-bandgap.c @@ -576,7 +576,8 @@ int ti_bandgap_set_sensor_data(struct ti_bandgap *bgp, int id, void *data) * @bgp: pointer to bandgap instance * @id: sensor id * - * Return: data stored by set function with sensor id on success or NULL + * Return: the stored sensor data, which may be %NULL, or an ERR_PTR() + * if @bgp or @id is invalid. */ void *ti_bandgap_get_sensor_data(struct ti_bandgap *bgp, int id) { @@ -1077,6 +1078,10 @@ void ti_bandgap_remove(struct platform_device *pdev) if (!soc_device_match(soc_no_cpu_notifier)) cpu_pm_unregister_notifier(&bgp->nb); + /* Stop the alerts first: they queue work on the sensors' data */ + if (TI_BANDGAP_HAS(bgp, TALERT)) + free_irq(bgp->irq, bgp); + /* Remove sensor interfaces */ for (i = 0; i < bgp->conf->sensor_count; i++) { if (bgp->conf->sensors[i].unregister_cooling) @@ -1093,9 +1098,6 @@ void ti_bandgap_remove(struct platform_device *pdev) clk_put(bgp->fclock); clk_put(bgp->div_clk); - if (TI_BANDGAP_HAS(bgp, TALERT)) - free_irq(bgp->irq, bgp); - if (TI_BANDGAP_HAS(bgp, TSHUT)) free_irq(gpiod_to_irq(bgp->tshut_gpiod), NULL); } diff --git a/drivers/thermal/ti-soc-thermal/ti-thermal-common.c b/drivers/thermal/ti-soc-thermal/ti-thermal-common.c index 0cf0826b805a..4bf3b2e0fc68 100644 --- a/drivers/thermal/ti-soc-thermal/ti-thermal-common.c +++ b/drivers/thermal/ti-soc-thermal/ti-thermal-common.c @@ -195,6 +195,10 @@ int ti_thermal_remove_sensor(struct ti_bandgap *bgp, int id) data = ti_bandgap_get_sensor_data(bgp, id); + /* Work queued by the talert IRQ must not outlive the data */ + if (!IS_ERR_OR_NULL(data)) + cancel_work_sync(&data->thermal_wq); + if (!IS_ERR_OR_NULL(data) && data->ti_thermal) { if (data->our_zone) thermal_zone_device_unregister(data->ti_thermal); diff --git a/drivers/tty/serial/8250/8250.h b/drivers/tty/serial/8250/8250.h index 9337fec9394e..cc7e1d76c2b8 100644 --- a/drivers/tty/serial/8250/8250.h +++ b/drivers/tty/serial/8250/8250.h @@ -180,6 +180,7 @@ void serial8250_clear_and_reinit_fifos(struct uart_8250_port *p); void serial8250_fifo_wait_for_lsr_thre(struct uart_8250_port *up, struct nbcon_write_context *wctxt, 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); @@ -316,6 +317,14 @@ static inline int serial8250_pnp_init(void) { return 0; } static inline void serial8250_pnp_exit(void) { } #endif +#ifdef CONFIG_SERIAL_8250_HUB6 +int serial8250_hub6_init(void); +void serial8250_hub6_exit(void); +#else +static inline int serial8250_hub6_init(void) { return 0; } +static inline void serial8250_hub6_exit(void) { } +#endif + #ifdef CONFIG_SERIAL_8250_RSA void univ8250_rsa_support(struct uart_ops *ops, const struct uart_ops *core_ops); void rsa_enable(struct uart_8250_port *up); @@ -336,7 +345,7 @@ int fintek_8250_probe(struct uart_8250_port *uart); static inline int fintek_8250_probe(struct uart_8250_port *uart) { return 0; } #endif -#if IS_REACHABLE(CONFIG_SERIAL_8250_HUB6) +#if IS_ENABLED(CONFIG_SERIAL_8250_HUB6) bool hub6_match_port(const struct uart_port *port1, const struct uart_port *port2); #else static inline bool hub6_match_port(const struct uart_port *port1, const struct uart_port *port2) diff --git a/drivers/tty/serial/8250/8250_hub6.c b/drivers/tty/serial/8250/8250_hub6.c index b6767633c966..848d9723ac56 100644 --- a/drivers/tty/serial/8250/8250_hub6.c +++ b/drivers/tty/serial/8250/8250_hub6.c @@ -49,13 +49,12 @@ bool hub6_match_port(const struct uart_port *port1, const struct uart_port *port } EXPORT_SYMBOL_GPL(hub6_match_port); -static int __init hub6_init(void) +int __init serial8250_hub6_init(void) { return platform_device_register(&hub6_device); } -module_init(hub6_init); - -MODULE_AUTHOR("Russell King"); -MODULE_DESCRIPTION("8250 serial probe module for Hub6 cards"); -MODULE_LICENSE("GPL"); +void serial8250_hub6_exit(void) +{ + platform_device_unregister(&hub6_device); +} 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_mxpcie.c b/drivers/tty/serial/8250/8250_mxpcie.c index ce873fbd62e9..19f1f51eec47 100644 --- a/drivers/tty/serial/8250/8250_mxpcie.c +++ b/drivers/tty/serial/8250/8250_mxpcie.c @@ -109,6 +109,7 @@ struct mxpcie8250_port { struct mxpcie8250 { unsigned int supp_rs; unsigned int num_ports; + unsigned int nr; /* ports actually registered */ void __iomem *bar1_base; /* UART registers (MMIO) */ void __iomem *bar2_base; /* UIR / GPIO / CPLD (IO) */ struct mxpcie8250_port port[] __counted_by(num_ports); @@ -217,8 +218,6 @@ static void mxpcie8250_set_termios(struct uart_port *port, const struct ktermios *old) { struct uart_8250_port *up = up_to_u8250p(port); - struct tty_struct *tty = port->state->port.tty; - unsigned int cflag = tty->termios.c_cflag; u8 efr, val; serial8250_do_set_termios(port, new, old); @@ -228,23 +227,25 @@ static void mxpcie8250_set_termios(struct uart_port *port, efr = serial_in(up, MOXA_PUART_EFR); efr &= ~(MOXA_PUART_EFR_AUTO_RTS | MOXA_PUART_EFR_AUTO_CTS); - if (cflag & CRTSCTS) { + if (new->c_cflag & CRTSCTS) { efr |= (MOXA_PUART_EFR_AUTO_RTS | MOXA_PUART_EFR_AUTO_CTS); up->port.status |= (UPSTAT_AUTORTS | UPSTAT_AUTOCTS); } /* Set on-chip software flow control character */ - serial_out(up, MOXA_PUART_XON1, START_CHAR(tty)); - serial_out(up, MOXA_PUART_XON2, START_CHAR(tty)); - serial_out(up, MOXA_PUART_XOFF1, STOP_CHAR(tty)); - serial_out(up, MOXA_PUART_XOFF2, STOP_CHAR(tty)); + serial_out(up, MOXA_PUART_XON1, new->c_cc[VSTART]); + serial_out(up, MOXA_PUART_XON2, new->c_cc[VSTART]); + serial_out(up, MOXA_PUART_XOFF1, new->c_cc[VSTOP]); + serial_out(up, MOXA_PUART_XOFF2, new->c_cc[VSTOP]); - val = I_IXON(tty) ? MOXA_PUART_EFR_RX_FLOW_XON1_XOFF1 : MOXA_PUART_EFR_RX_FLOW_DISABLED; + val = (new->c_iflag & IXON) ? MOXA_PUART_EFR_RX_FLOW_XON1_XOFF1 : + MOXA_PUART_EFR_RX_FLOW_DISABLED; FIELD_MODIFY(MOXA_PUART_EFR_RX_FLOW_MASK, &efr, val); - val = I_IXOFF(tty) ? MOXA_PUART_EFR_TX_FLOW_XON1_XOFF1 : MOXA_PUART_EFR_TX_FLOW_DISABLED; + val = (new->c_iflag & IXOFF) ? MOXA_PUART_EFR_TX_FLOW_XON1_XOFF1 : + MOXA_PUART_EFR_TX_FLOW_DISABLED; FIELD_MODIFY(MOXA_PUART_EFR_TX_FLOW_MASK, &efr, val); - if (I_IXOFF(tty)) + if (new->c_iflag & IXOFF) up->port.status |= UPSTAT_AUTOXOFF; serial_out(up, MOXA_PUART_EFR, efr); @@ -517,6 +518,7 @@ static int mxpcie8250_probe(struct pci_dev *pdev, const struct pci_device_id *id struct mxpcie8250 *priv; unsigned short device = pdev->device; unsigned int num_ports; + unsigned int i; int ret; ret = pcim_enable_device(pdev); @@ -542,6 +544,8 @@ static int mxpcie8250_probe(struct pci_dev *pdev, const struct pci_device_id *id mxpcie8250_init_board(pdev, priv); + pci_set_drvdata(pdev, priv); + up.port.dev = dev; up.port.irq = pdev->irq; up.port.uartclk = MOXA_PUART_BASE_BAUD * 16; @@ -562,7 +566,7 @@ static int mxpcie8250_probe(struct pci_dev *pdev, const struct pci_device_id *id up.port.handle_irq = mxpcie8250_handle_irq; up.port.break_ctl = mxpcie8250_break_ctl; - for (unsigned int i = 0; i < num_ports; i++) { + for (i = 0; i < num_ports; i++) { mxpcie8250_setup_port(pdev, priv, &up, i); dev_dbg(dev, "Setup PCI port: port %lx, irq %d, type %d\n", @@ -578,7 +582,7 @@ static int mxpcie8250_probe(struct pci_dev *pdev, const struct pci_device_id *id } priv->port[i].rx_trig_level = MOXA_PUART_RX_TRIG_DEFAULT; } - pci_set_drvdata(pdev, priv); + priv->nr = i; return 0; } @@ -587,7 +591,7 @@ static void mxpcie8250_remove(struct pci_dev *pdev) { struct mxpcie8250 *priv = pci_get_drvdata(pdev); - for (unsigned int i = 0; i < priv->num_ports; i++) + for (unsigned int i = 0; i < priv->nr; i++) serial8250_unregister_port(priv->port[i].line); } diff --git a/drivers/tty/serial/8250/8250_platform.c b/drivers/tty/serial/8250/8250_platform.c index af946d12e764..0570366a71d0 100644 --- a/drivers/tty/serial/8250/8250_platform.c +++ b/drivers/tty/serial/8250/8250_platform.c @@ -319,10 +319,14 @@ static int __init serial8250_init(void) if (ret) goto unreg_uart_drv; + ret = serial8250_hub6_init(); + if (ret) + goto unreg_pnp; + serial8250_isa_devs = platform_device_alloc("serial8250", PLAT8250_DEV_LEGACY); if (!serial8250_isa_devs) { ret = -ENOMEM; - goto unreg_pnp; + goto unreg_hub6; } ret = platform_device_add(serial8250_isa_devs); @@ -338,6 +342,8 @@ static int __init serial8250_init(void) platform_device_del(serial8250_isa_devs); put_dev: platform_device_put(serial8250_isa_devs); +unreg_hub6: + serial8250_hub6_exit(); unreg_pnp: serial8250_pnp_exit(); unreg_uart_drv: @@ -365,6 +371,7 @@ static void __exit serial8250_exit(void) platform_driver_unregister(&serial8250_isa_driver); platform_device_unregister(isa_dev); + serial8250_hub6_exit(); serial8250_pnp_exit(); #ifdef CONFIG_SPARC diff --git a/drivers/tty/serial/8250/8250_port.c b/drivers/tty/serial/8250/8250_port.c index c961b969021e..434ba234eb9f 100644 --- a/drivers/tty/serial/8250/8250_port.c +++ b/drivers/tty/serial/8250/8250_port.c @@ -2024,7 +2024,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; bool tx_ready; @@ -2052,6 +2052,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 /* @@ -2098,7 +2099,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. */ @@ -2108,7 +2109,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); } @@ -2223,7 +2224,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; @@ -3293,7 +3294,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); } @@ -3507,7 +3508,7 @@ void serial8250_console_write(struct uart_8250_port *up, * 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/8250/8250_uniphier.c b/drivers/tty/serial/8250/8250_uniphier.c index e3db60bf50c9..6fffac12277a 100644 --- a/drivers/tty/serial/8250/8250_uniphier.c +++ b/drivers/tty/serial/8250/8250_uniphier.c @@ -180,16 +180,12 @@ static int uniphier_uart_probe(struct platform_device *pdev) memset(&up, 0, sizeof(up)); - priv->clk = devm_clk_get(dev, NULL); + priv->clk = devm_clk_get_enabled(dev, NULL); if (IS_ERR(priv->clk)) { - dev_err(dev, "failed to get clock\n"); + dev_err(dev, "failed to get and enable clock\n"); return PTR_ERR(priv->clk); } - ret = clk_prepare_enable(priv->clk); - if (ret) - return ret; - up.port.uartclk = clk_get_rate(priv->clk); spin_lock_init(&priv->atomic_write_lock); @@ -222,7 +218,6 @@ static int uniphier_uart_probe(struct platform_device *pdev) ret = serial8250_register_8250_port(&up); if (ret < 0) { dev_err(dev, "failed to register 8250 port\n"); - clk_disable_unprepare(priv->clk); return ret; } priv->line = ret; @@ -237,7 +232,6 @@ static void uniphier_uart_remove(struct platform_device *pdev) struct uniphier8250_priv *priv = platform_get_drvdata(pdev); serial8250_unregister_port(priv->line); - clk_disable_unprepare(priv->clk); } static int __maybe_unused uniphier_uart_suspend(struct device *dev) diff --git a/drivers/tty/serial/8250/Kconfig b/drivers/tty/serial/8250/Kconfig index fa6f33303cb0..1d3f7e57e959 100644 --- a/drivers/tty/serial/8250/Kconfig +++ b/drivers/tty/serial/8250/Kconfig @@ -304,8 +304,8 @@ config SERIAL_8250_EXAR_ST16C554 will be called 8250_exar_st16c554. config SERIAL_8250_HUB6 - tristate "Support Hub6 cards" - depends on SERIAL_8250 != n && ISA && SERIAL_8250_MANY_PORTS + bool "Support Hub6 cards" + depends on SERIAL_8250_MANY_PORTS && ISA help Say Y here if you have a HUB6 serial board. diff --git a/drivers/tty/serial/8250/Makefile b/drivers/tty/serial/8250/Makefile index 46adadcfe072..330dd6cf7c83 100644 --- a/drivers/tty/serial/8250/Makefile +++ b/drivers/tty/serial/8250/Makefile @@ -7,6 +7,7 @@ obj-$(CONFIG_SERIAL_8250) += 8250.o 8250-y := 8250_core.o 8250-y += 8250_platform.o 8250-$(CONFIG_SERIAL_8250_PNP) += 8250_pnp.o +8250-$(CONFIG_SERIAL_8250_HUB6) += 8250_hub6.o obj-$(CONFIG_SERIAL_8250) += 8250_base.o 8250_base-y := 8250_port.o @@ -35,7 +36,6 @@ obj-$(CONFIG_SERIAL_8250_EXAR_ST16C554) += 8250_exar_st16c554.o obj-$(CONFIG_SERIAL_8250_FOURPORT) += 8250_fourport.o obj-$(CONFIG_SERIAL_8250_FSL) += 8250_fsl.o obj-$(CONFIG_SERIAL_8250_HP300) += 8250_hp300.o -obj-$(CONFIG_SERIAL_8250_HUB6) += 8250_hub6.o obj-$(CONFIG_SERIAL_8250_INGENIC) += 8250_ingenic.o obj-$(CONFIG_SERIAL_8250_IOC3) += 8250_ioc3.o obj-$(CONFIG_SERIAL_8250_KEBA) += 8250_keba.o diff --git a/drivers/tty/serial/Kconfig b/drivers/tty/serial/Kconfig index cf7dba473b20..bf680d22199b 100644 --- a/drivers/tty/serial/Kconfig +++ b/drivers/tty/serial/Kconfig @@ -904,6 +904,7 @@ config SERIAL_JSM config SERIAL_MSM tristate "MSM on-chip serial port support" depends on ARCH_QCOM || COMPILE_TEST + select PM_OPP select SERIAL_CORE config SERIAL_MSM_CONSOLE diff --git a/drivers/tty/serial/ma35d1_serial.c b/drivers/tty/serial/ma35d1_serial.c index 0809655f4395..3be30fb05513 100644 --- a/drivers/tty/serial/ma35d1_serial.c +++ b/drivers/tty/serial/ma35d1_serial.c @@ -639,7 +639,7 @@ static struct console ma35d1serial_console = { .write = ma35d1serial_console_write, .device = uart_console_device, .setup = ma35d1serial_console_setup, - .flags = CON_PRINTBUFFER | CON_ENABLED, + .flags = CON_PRINTBUFFER, .index = -1, .data = &ma35d1serial_reg, }; diff --git a/drivers/tty/serial/max310x.c b/drivers/tty/serial/max310x.c index 9e62778e4191..a0ed70185555 100644 --- a/drivers/tty/serial/max310x.c +++ b/drivers/tty/serial/max310x.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -156,10 +157,17 @@ #define MAX310X_LCR_FORCEPARITY_BIT (1 << 5) /* 9-bit multidrop parity */ #define MAX310X_LCR_TXBREAK_BIT (1 << 6) /* TX break enable */ #define MAX310X_LCR_RTS_BIT (1 << 7) /* RTS pin control */ +/* LCR bits owned by termios; TX break and RTS are driven elsewhere */ +#define MAX310X_LCR_TERMIOS_MASK GENMASK(5, 0) /* IRDA register bits */ #define MAX310X_IRDA_IRDAEN_BIT (1 << 0) /* IRDA mode enable */ #define MAX310X_IRDA_SIR_BIT (1 << 1) /* SIR mode enable */ +#define MAX310X_IRDA_RTSINVERT_BIT (1 << 2) /* Invert RTS output */ + +/* HDPIXDELAY accessor macros */ +#define MAX310X_HDPIXDELAY_SETUP(val) (((val) & 0x0f) << 4) +#define MAX310X_HDPIXDELAY_HOLD(val) ((val) & 0x0f) /* Flow control trigger level register masks */ #define MAX310X_FLOWLVL_HALT_MASK GENMASK(3, 0) /* Flow control halt level */ @@ -288,12 +296,30 @@ struct max310x_devtype { u8 power_bit; /* Bit for sleep or power-off mode (active high). */ }; +/* Software-timed RS485 RTS envelope phase */ +enum max310x_tx_state { + MAX310X_TX_OFF, /* idle, RTS released */ + MAX310X_TX_WAIT_BEFORE_SEND, /* RTS asserted, before-send delay */ + MAX310X_TX_SEND, /* data in flight, awaiting TX-empty */ + MAX310X_TX_WAIT_AFTER_SEND, /* data drained, after-send hold */ +}; + struct max310x_one { struct uart_port port; struct work_struct tx_work; struct work_struct md_work; struct work_struct rs_work; + struct work_struct rts_work; + struct hrtimer tx_delay_tmr; struct regmap *regmap; + unsigned int char_time_us; + unsigned int baud; + bool sw_rts_during_tx; + bool cancel_tx_delay_tmr; + bool tx_teardown; /* envelope being torn down */ + bool rs485_pending; /* rs_work not yet applied */ + bool tx_break; /* break_ctl() owns the transceiver */ + enum max310x_tx_state tx_state; u8 rx_buf[MAX310X_FIFO_SIZE]; }; @@ -678,6 +704,44 @@ static void max310x_batch_read(struct uart_port *port, u8 *rxbuf, unsigned int l regmap_noinc_read(one->regmap, MAX310X_RHR_REG, rxbuf, len); } +static void max310x_rts_ctl(struct uart_port *port, bool rts_state) +{ + max310x_port_update(port, MAX310X_LCR_REG, MAX310X_LCR_RTS_BIT, + rts_state ? MAX310X_LCR_RTS_BIT : 0); +} + +/* RTS level for the transmitting or the idle phase of an RS485 envelope */ +static bool max310x_rts_level(struct uart_port *port, bool active) +{ + return active ? (port->rs485.flags & SER_RS485_RTS_ON_SEND) : + (port->rs485.flags & SER_RS485_RTS_AFTER_SEND); +} + +/* + * Drive the RS485 RTS line to match the current tx_state and break + * ownership. This is the only place that touches RTS, and it reads the + * state rather than a fixed assert/deassert intent, so a newer assert is + * never clobbered by a stale release and an expiring after-send hold never + * releases a break in progress. It also arms the before-send timer once the + * RTS edge is on the wire, so data is never shifted before RTS is asserted. + */ +static void max310x_rts_work_proc(struct work_struct *ws) +{ + struct max310x_one *one = container_of(ws, struct max310x_one, rts_work); + struct uart_port *port = &one->port; + bool rts_on = READ_ONCE(one->tx_state) != MAX310X_TX_OFF || + READ_ONCE(one->tx_break); + + max310x_rts_ctl(port, max310x_rts_level(port, rts_on)); + + guard(spinlock_irqsave)(&port->lock); + if (READ_ONCE(one->tx_state) == MAX310X_TX_WAIT_BEFORE_SEND && + !one->cancel_tx_delay_tmr && !hrtimer_active(&one->tx_delay_tmr)) + hrtimer_start(&one->tx_delay_tmr, + ms_to_ktime(port->rs485.delay_rts_before_send), + HRTIMER_MODE_REL); +} + static void max310x_handle_rx(struct uart_port *port, unsigned int rxlen) { struct max310x_one *one = to_max310x_port(port); @@ -774,6 +838,77 @@ static void max310x_handle_rx(struct uart_port *port, unsigned int rxlen) tty_flip_buffer_push(&port->state->port); } +static enum hrtimer_restart max310x_tmr_tx(struct hrtimer *timer) +{ + struct max310x_one *one = container_of(timer, struct max310x_one, + tx_delay_tmr); + + guard(spinlock_irqsave)(&one->port.lock); + if (!one->cancel_tx_delay_tmr) { + if (READ_ONCE(one->tx_state) == MAX310X_TX_WAIT_AFTER_SEND) { + /* After-send hold elapsed: drop RTS via the rts worker. */ + WRITE_ONCE(one->tx_state, MAX310X_TX_OFF); + schedule_work(&one->rts_work); + } else { + WRITE_ONCE(one->tx_state, MAX310X_TX_SEND); + schedule_work(&one->tx_work); + } + } + + return HRTIMER_NORESTART; +} + +static void max310x_delayed_stop_tx(struct uart_port *port) +{ + struct max310x_one *one = to_max310x_port(port); + unsigned int txlvl; + + if (READ_ONCE(one->tx_state) == MAX310X_TX_OFF) + return; + + /* + * Data still queued for transmission defers the hold: a refill is + * coming and the envelope is not over. Stopped output does not + * count - it drains nowhere, and the envelope must end. + */ + if (!kfifo_is_empty(&port->state->port.xmit_fifo) && + !uart_tx_stopped(port)) + return; + + /* + * The kfifo can be empty while the chip TX FIFO is still draining, so arm + * the after-send hold only once the chip FIFO is empty too - the TX-empty + * interrupt re-invokes us then. Otherwise the hold starts early and RTS + * drops mid-character, clipping the last byte(s). + */ + txlvl = max310x_port_read(port, MAX310X_TXFIFOLVL_REG); + if (txlvl) + return; + + /* + * Runs from tx_work without port->lock, so re-check the state under it: + * shutdown() may have cancelled the envelope meanwhile. Only + * MAX310X_TX_SEND may arm the hold. + */ + guard(spinlock_irqsave)(&one->port.lock); + if (one->cancel_tx_delay_tmr || + READ_ONCE(one->tx_state) != MAX310X_TX_SEND) + return; + + if (!hrtimer_active(&one->tx_delay_tmr)) { + /* + * Add one character for the byte still in the shift register - + * TX-empty fires as it enters, not as it leaves. + */ + ktime_t delay = us_to_ktime(one->char_time_us + + port->rs485.delay_rts_after_send * + USEC_PER_MSEC); + + WRITE_ONCE(one->tx_state, MAX310X_TX_WAIT_AFTER_SEND); + hrtimer_start(&one->tx_delay_tmr, delay, HRTIMER_MODE_REL); + } +} + static void max310x_handle_tx(struct uart_port *port) { struct tty_port *tport = &port->state->port; @@ -785,8 +920,16 @@ static void max310x_handle_tx(struct uart_port *port) return; } - if (kfifo_is_empty(&tport->xmit_fifo) || uart_tx_stopped(port)) + if (kfifo_is_empty(&tport->xmit_fifo) || uart_tx_stopped(port)) { + /* + * Unwind the envelope even if a reconfigure has moved the + * port to the hardware path mid-envelope: a stranded + * tx_state would make a later reconfigure believe a + * software envelope still owns RTS. + */ + max310x_delayed_stop_tx(port); return; + } /* * It's a circ buffer -- wrap around. @@ -811,11 +954,75 @@ static void max310x_handle_tx(struct uart_port *port) uart_write_wakeup(port); } +/* + * Begin a software-timed RTS envelope: set the before-send phase and queue the + * rts worker to assert RTS. tx_state is set synchronously here (start_tx() holds + * port.lock) so close()/shutdown can see an envelope is in flight; rts_work then + * asserts RTS and arms the before-send timer (see there). + */ +static void max310x_delayed_start_tx(struct uart_port *port) +{ + struct max310x_one *one = to_max310x_port(port); + + WRITE_ONCE(one->tx_state, MAX310X_TX_WAIT_BEFORE_SEND); + one->cancel_tx_delay_tmr = false; + schedule_work(&one->rts_work); +} + +/* called with port.lock taken and irqs off */ static void max310x_start_tx(struct uart_port *port) { struct max310x_one *one = to_max310x_port(port); - schedule_work(&one->tx_work); + /* A teardown is in progress; nothing may start an envelope or TX. */ + if (one->tx_teardown) + return; + + /* + * An RS485 reconfigure is scheduled but not applied yet: transmitting + * now would use the old path against half-programmed registers - a + * TIOCSRS485 switching paths followed immediately by a write puts the + * data on the wire with the transceiver released. Leave the data in + * the kfifo; rs_work restarts TX once the configuration is applied. + */ + if (one->rs485_pending) + return; + + if (READ_ONCE(one->sw_rts_during_tx)) { + /* + * The before- and after-send phases share one delay timer. If an + * after-send release is pending, cancel it before starting a new + * TX so the just-asserted RTS is not yanked; re-arming the timer + * for the before-send phase then supersedes the release. + */ + int res = 0; + + if (READ_ONCE(one->tx_state) == MAX310X_TX_WAIT_AFTER_SEND) + res = hrtimer_try_to_cancel(&one->tx_delay_tmr); + if (unlikely(res == -1)) { + one->cancel_tx_delay_tmr = true; + uart_port_unlock(port); + hrtimer_cancel(&one->tx_delay_tmr); + uart_port_lock(port); + /* + * The lock was dropped: a teardown may have run to + * completion or a reconfigure may have been posted + * meanwhile. Re-check before starting. + */ + if (one->tx_teardown || one->rs485_pending) + return; + } + + /* Already sending: pump the new data, don't rewind. */ + if (READ_ONCE(one->tx_state) == MAX310X_TX_SEND) { + schedule_work(&one->tx_work); + return; + } + + max310x_delayed_start_tx(port); + } else { + schedule_work(&one->tx_work); + } } static irqreturn_t max310x_port_irq(struct max310x_port *s, int portno) @@ -840,8 +1047,12 @@ static irqreturn_t max310x_port_irq(struct max310x_port *s, int portno) } if (rxlen) max310x_handle_rx(port, rxlen); + /* + * TXEMPTY latches on the FIFO becoming empty, so a stale + * interrupt cannot pump data during an RTS setup delay. + */ if (ists & MAX310X_IRQ_TXEMPTY_BIT) - max310x_start_tx(port); + schedule_work(&s->p[portno].tx_work); } while (1); return res; @@ -923,17 +1134,198 @@ static void max310x_set_mctrl(struct uart_port *port, unsigned int mctrl) schedule_work(&one->md_work); } +/* + * A reconfigure can move the port off the hardware RTS path while the chip's + * auto-RTS still owns a transmission in flight; tx_state does not track + * those. Take such a transfer over before auto-RTS is disabled: enter + * MAX310X_TX_SEND, so the caller keeps RTS driven across the handover and + * the normal drain path arms the after-send hold. Returns true when a + * transmission owns RTS - adopted here or started concurrently - and false + * when the line is really idle. + */ +static bool max310x_adopt_hw_tx(struct max310x_one *one) +{ + struct uart_port *port = &one->port; + + if (!max310x_port_read(port, MAX310X_TXFIFOLVL_REG) && + kfifo_is_empty(&port->state->port.xmit_fifo)) + return false; + + scoped_guard(spinlock_irqsave, &port->lock) { + if (one->tx_teardown) + return false; + if (READ_ONCE(one->tx_state) != MAX310X_TX_OFF) + return true; + WRITE_ONCE(one->tx_state, MAX310X_TX_SEND); + one->cancel_tx_delay_tmr = false; + } + + return true; +} + +/* + * Pick hardware or software RTS timing for the current port. The chip can + * deliver up to 15 bit-times of setup/hold delay via HDPIXDELAY; anything + * longer (or any RTS polarity the chip cannot produce automatically) must + * be driven by software via tx_delay_tmr and rts_work. + */ +static void max310x_set_rts_ctl_params(struct max310x_one *one) +{ + const unsigned int max_bit_dly = 15; + struct uart_port *port = &one->port; + unsigned int setup = 0, hold = 0; + u8 mode1 = 0, irda = 0; + bool sw_rts = false; + + if (!(port->rs485.flags & SER_RS485_ENABLED)) + goto out; + + /* Convert milliseconds to bit-times, rounding up. */ + setup = DIV_ROUND_UP(one->baud * port->rs485.delay_rts_before_send, + MSEC_PER_SEC); + hold = DIV_ROUND_UP(one->baud * port->rs485.delay_rts_after_send, + MSEC_PER_SEC); + + /* + * Compare in bit-times: a delay of exactly max_bit_dly bit-times + * must stay on the hardware path, which a nanosecond ceiling + * computed from the truncated per-bit time would reject. Without + * a baud rate the conversion is meaningless - use software. + */ + if (!one->baud || setup > max_bit_dly || hold > max_bit_dly || + !!(port->rs485.flags & SER_RS485_RTS_ON_SEND) == + !!(port->rs485.flags & SER_RS485_RTS_AFTER_SEND)) { + sw_rts = true; + setup = 0; + hold = 0; + } + +out: + /* Assign once; a transient false would be seen by other readers. */ + WRITE_ONCE(one->sw_rts_during_tx, sw_rts); + + max310x_port_write(port, MAX310X_HDPIXDELAY_REG, + MAX310X_HDPIXDELAY_SETUP(setup) | + MAX310X_HDPIXDELAY_HOLD(hold)); + + /* + * A break owns the transceiver: break_ctl() disabled auto-RTS and + * drives RTS manually, and restores it from the current + * configuration when the break ends. Touching them here would + * release the transceiver mid-break. + */ + if (one->tx_break) + return; + + if (port->rs485.flags & SER_RS485_ENABLED) { + if (sw_rts) { + /* + * Only settle RTS at idle when no transmission owns it. + * A reconfigure while one is in flight - rs_work runs + * on every TIOCSRS485 - would otherwise release the + * transceiver mid-character. A transfer the hardware + * path owns is invisible to tx_state - adopt it + * instead of settling. The reverse strand also + * exists: an envelope the hardware path inherited + * mid-envelope leaves tx_state set with nothing + * driving the pin. + */ + if (READ_ONCE(one->tx_state) != MAX310X_TX_OFF || + max310x_adopt_hw_tx(one)) { + /* + * The transfer may be running under auto-RTS: + * assert before auto-RTS is disabled below so + * the pin is never released under it, and arm + * the after-send hold - with the chip FIFO + * already drained no TX-empty interrupt + * arrives to arm it. + */ + max310x_rts_ctl(port, + max310x_rts_level(port, true)); + max310x_delayed_stop_tx(port); + } else { + max310x_rts_ctl(port, + max310x_rts_level(port, false)); + /* + * serial_core calls set_termios() without + * port->lock, so an envelope may have started + * while the idle level was written and the + * settle can land after its RTS assert. + * rts_work re-derives the level from + * tx_state; requeue it to converge. + */ + if (READ_ONCE(one->tx_state) != MAX310X_TX_OFF) + schedule_work(&one->rts_work); + } + } else { + mode1 = MAX310X_MODE1_TRNSCVCTRL_BIT; + /* + * The auto-RTS engine asserts RTS high on send; for an + * active-low RTS let IRDA.RTSINVERT invert the output + * stage. + */ + if (!(port->rs485.flags & SER_RS485_RTS_ON_SEND)) + irda = MAX310X_IRDA_RTSINVERT_BIT; + } + } else { + max310x_rts_ctl(port, 0); + } + + max310x_port_update(port, MAX310X_MODE1_REG, + MAX310X_MODE1_TRNSCVCTRL_BIT, mode1); + max310x_port_update(port, MAX310X_IRDA_REG, + MAX310X_IRDA_RTSINVERT_BIT, irda); +} + static void max310x_break_ctl(struct uart_port *port, int break_state) { + struct max310x_one *one = to_max310x_port(port); + + one->tx_break = break_state; + max310x_port_update(port, MAX310X_LCR_REG, MAX310X_LCR_TXBREAK_BIT, break_state ? MAX310X_LCR_TXBREAK_BIT : 0); + + /* + * The chip's auto-RTS asserts the transceiver only while FIFO data is + * shifting out, and a break is not FIFO data. Disable auto-RTS for the + * break duration and drive RTS manually so the break reaches the wire; + * restore auto-RTS when the break ends. For an active-low RTS, + * IRDA.RTSINVERT already inverts the RTS_ output stage, so break_state + * is driven as it is. + */ + if (break_state) { + if (!(port->rs485.flags & SER_RS485_ENABLED)) + return; + if (READ_ONCE(one->sw_rts_during_tx)) { + max310x_rts_ctl(port, max310x_rts_level(port, 1)); + } else { + max310x_port_update(port, MAX310X_MODE1_REG, + MAX310X_MODE1_TRNSCVCTRL_BIT, 0); + max310x_rts_ctl(port, 1); + } + } else { + /* + * Reapply the current configuration: a reconfigure that + * arrived during the break was deferred by the tx_break + * guard, and RS485 may have been disabled outright - the + * manually driven RTS must not leak past the break. On the + * software path the helper also settles the idle level; on + * the hardware path release the manual RTS - auto-RTS owns + * the pin again. + */ + max310x_set_rts_ctl_params(one); + if (!READ_ONCE(one->sw_rts_during_tx)) + max310x_rts_ctl(port, 0); + } } static void max310x_set_termios(struct uart_port *port, struct ktermios *termios, const struct ktermios *old) { + unsigned int frame_bits = tty_get_frame_size(termios->c_cflag); unsigned int lcr = 0, flow = 0; int baud; @@ -967,8 +1359,13 @@ static void max310x_set_termios(struct uart_port *port, if (termios->c_cflag & CSTOPB) lcr |= MAX310X_LCR_STOPLEN_BIT; /* 2 stops */ - /* Update LCR register */ - max310x_port_write(port, MAX310X_LCR_REG, lcr); + /* + * Update LCR register. Leave the TX break and RTS bits alone: they are + * driven by break_ctl() and by the software-timed RS485 RTS, and a + * whole-register write here would end a break in progress or release + * the transceiver mid-character. + */ + max310x_port_update(port, MAX310X_LCR_REG, MAX310X_LCR_TERMIOS_MASK, lcr); /* Set read status mask */ port->read_status_mask = MAX310X_LSR_RXOVR_BIT; @@ -1040,41 +1437,101 @@ static void max310x_set_termios(struct uart_port *port, /* Update timeout according to new baud rate */ uart_update_timeout(port, termios->c_cflag, baud); + + /* + * Cache the new baud rate and the time it takes to clock out one + * character before reprogramming the RS485 RTS delays: the + * millisecond-to-bit-time conversion divides by the baud rate, and + * taking over an in-flight transfer arms the after-send hold from + * the character time. + */ + to_max310x_port(port)->baud = baud; + to_max310x_port(port)->char_time_us = + DIV_ROUND_UP(USEC_PER_SEC * frame_bits, baud); + max310x_set_rts_ctl_params(to_max310x_port(port)); } static void max310x_rs_proc(struct work_struct *ws) { struct max310x_one *one = container_of(ws, struct max310x_one, rs_work); - unsigned int delay, mode1 = 0, mode2 = 0; + unsigned int mode2 = 0; + unsigned long flags; + bool chip_tx_empty; + + /* + * Serialize against break_ctl() and set_termios(), which run under + * port->mutex: the tx_break-guarded register writes must not + * straddle a break starting or ending. + */ + guard(mutex)(&one->port.state->port.mutex); - delay = (one->port.rs485.delay_rts_before_send << 4) | - one->port.rs485.delay_rts_after_send; - max310x_port_write(&one->port, MAX310X_HDPIXDELAY_REG, delay); + /* Flush an rts_work that read tx_state before the disable cleared it. */ + if (!(one->port.rs485.flags & SER_RS485_ENABLED)) + cancel_work_sync(&one->rts_work); - if (one->port.rs485.flags & SER_RS485_ENABLED) { - mode1 = MAX310X_MODE1_TRNSCVCTRL_BIT; + max310x_set_rts_ctl_params(one); - if (!(one->port.rs485.flags & SER_RS485_RX_DURING_TX)) - mode2 = MAX310X_MODE2_ECHOSUPR_BIT; - } + if (one->port.rs485.flags & SER_RS485_ENABLED && + !(one->port.rs485.flags & SER_RS485_RX_DURING_TX)) + mode2 = MAX310X_MODE2_ECHOSUPR_BIT; - max310x_port_update(&one->port, MAX310X_MODE1_REG, - MAX310X_MODE1_TRNSCVCTRL_BIT, mode1); max310x_port_update(&one->port, MAX310X_MODE2_REG, - MAX310X_MODE2_ECHOSUPR_BIT, mode2); + MAX310X_MODE2_ECHOSUPR_BIT, mode2); + + /* + * The configuration is applied: release any TX that start_tx() + * deferred while the reconfigure was pending, now on the right + * path. start_tx() can drop and retake the lock through the + * uart_port API - a raw spinlock guard here would unbalance it. + */ + chip_tx_empty = !max310x_port_read(&one->port, + MAX310X_TXFIFOLVL_REG); + + uart_port_lock_irqsave(&one->port, &flags); + one->rs485_pending = false; + if (one->port.x_char || + !kfifo_is_empty(&one->port.state->port.xmit_fifo)) { + /* + * A send state adopted without chip data is the deferred + * write itself: restart it as a fresh envelope so the + * before-send delay is honoured. + */ + if (chip_tx_empty && + READ_ONCE(one->tx_state) == MAX310X_TX_SEND) + WRITE_ONCE(one->tx_state, MAX310X_TX_OFF); + max310x_start_tx(&one->port); + } + uart_port_unlock_irqrestore(&one->port, flags); } +/* called with port.lock taken and irqs off */ static int max310x_rs485_config(struct uart_port *port, struct ktermios *termios, struct serial_rs485 *rs485) { struct max310x_one *one = to_max310x_port(port); - if ((rs485->delay_rts_before_send > 0x0f) || - (rs485->delay_rts_after_send > 0x0f)) - return -ERANGE; + rs485->delay_rts_before_send = min(rs485->delay_rts_before_send, 100U); + rs485->delay_rts_after_send = min(rs485->delay_rts_after_send, 100U); + + /* + * Make sure no SW-timed RTS toggle survives an RS485 disable, even + * if the delay timer happens to be running right now. + */ + if (!(rs485->flags & SER_RS485_ENABLED)) { + one->tx_teardown = true; + one->cancel_tx_delay_tmr = true; + if (hrtimer_try_to_cancel(&one->tx_delay_tmr) == -1) { + uart_port_unlock(port); + hrtimer_cancel(&one->tx_delay_tmr); + uart_port_lock(port); + } + WRITE_ONCE(one->tx_state, MAX310X_TX_OFF); + one->tx_teardown = false; + } port->rs485 = *rs485; + one->rs485_pending = true; schedule_work(&one->rs_work); return 0; @@ -1082,13 +1539,23 @@ static int max310x_rs485_config(struct uart_port *port, struct ktermios *termios static int max310x_startup(struct uart_port *port) { + struct max310x_one *one = to_max310x_port(port); unsigned int val; max310x_power(port, 1); - /* Configure MODE1 register */ + /* + * Clear a latched break: nothing clears TXBREAK when a port is + * closed with a break still asserted, and set_termios() no longer + * rewrites it. + */ + one->tx_break = false; + max310x_port_update(port, MAX310X_LCR_REG, MAX310X_LCR_TXBREAK_BIT, 0); + + /* Configure MODE1: re-enable the transmitter shutdown() stopped */ max310x_port_update(port, MAX310X_MODE1_REG, - MAX310X_MODE1_TRNSCVCTRL_BIT, 0); + MAX310X_MODE1_TRNSCVCTRL_BIT | + MAX310X_MODE1_TXDIS_BIT, 0); /* Configure MODE2 register & Reset FIFOs*/ val = MAX310X_MODE2_RXEMPTINV_BIT | MAX310X_MODE2_FIFORST_BIT; @@ -1096,21 +1563,22 @@ static int max310x_startup(struct uart_port *port) max310x_port_update(port, MAX310X_MODE2_REG, MAX310X_MODE2_FIFORST_BIT, 0); - /* Configure mode1/mode2 to have rs485/rs232 enabled at startup */ - val = (clamp(port->rs485.delay_rts_before_send, 0U, 15U) << 4) | - clamp(port->rs485.delay_rts_after_send, 0U, 15U); - max310x_port_write(port, MAX310X_HDPIXDELAY_REG, val); + one->tx_teardown = false; - if (port->rs485.flags & SER_RS485_ENABLED) { - max310x_port_update(port, MAX310X_MODE1_REG, - MAX310X_MODE1_TRNSCVCTRL_BIT, - MAX310X_MODE1_TRNSCVCTRL_BIT); + /* + * Configure the RS485 RTS timing (HW auto-RTS vs software-driven) and + * the RS485/RS232 mode bits. Don't hardcode HW auto-RTS here - let + * max310x_set_rts_ctl_params() pick HW or SW per the configured + * delays, otherwise the chip's auto-RTS would override the software + * RTS hold and the after-send delay is lost. + */ + max310x_set_rts_ctl_params(one); - if (!(port->rs485.flags & SER_RS485_RX_DURING_TX)) - max310x_port_update(port, MAX310X_MODE2_REG, - MAX310X_MODE2_ECHOSUPR_BIT, - MAX310X_MODE2_ECHOSUPR_BIT); - } + if (port->rs485.flags & SER_RS485_ENABLED && + !(port->rs485.flags & SER_RS485_RX_DURING_TX)) + max310x_port_update(port, MAX310X_MODE2_REG, + MAX310X_MODE2_ECHOSUPR_BIT, + MAX310X_MODE2_ECHOSUPR_BIT); /* * Configure flow control levels: @@ -1132,9 +1600,91 @@ static int max310x_startup(struct uart_port *port) static void max310x_shutdown(struct uart_port *port) { - /* Disable all interrupts */ + struct max310x_one *one = to_max310x_port(port); + + /* + * Gate new transmissions and interrupts first: a concurrent + * start_tx() either sees the interlock or happens-before it, and + * nothing below may start a new envelope. The timer and the works + * stay live for now - they are what completes a running after-send + * hold. + */ + scoped_guard(spinlock_irqsave, &port->lock) + one->tx_teardown = true; max310x_port_write(port, MAX310X_IRQEN_REG, 0); + /* + * Stop the transmitter: the character in flight completes, data + * still queued is abandoned (the next startup() resets the FIFOs). + */ + max310x_port_update(port, MAX310X_MODE1_REG, + MAX310X_MODE1_TXDIS_BIT, MAX310X_MODE1_TXDIS_BIT); + + if (READ_ONCE(one->sw_rts_during_tx)) { + /* + * Honour a running after-send hold before the port is + * powered down. The bound covers the final character - + * tx_empty() cannot see the transmit shift register - plus + * the hold itself. Data beyond that is abandoned: it is + * only still queued when the tty layer was told not to + * wait, and the release below drives RTS to idle + * regardless. + */ + unsigned int tries = port->rs485.delay_rts_after_send + + 2 * DIV_ROUND_UP(one->char_time_us, USEC_PER_MSEC); + + while (READ_ONCE(one->tx_state) != MAX310X_TX_OFF && tries-- > 0) + fsleep(USEC_PER_MSEC); + } else { + /* + * Let the character in flight finish (the chip has no + * transmitter-idle status), then empty the FIFO: auto-RTS + * releases only once the transmitter is empty, and the + * power-off below would freeze an asserted pin until the + * next open. The hold is at most 15 bit-times. + */ + fsleep(one->char_time_us); + max310x_port_update(port, MAX310X_MODE2_REG, + MAX310X_MODE2_FIFORST_BIT, + MAX310X_MODE2_FIFORST_BIT); + max310x_port_update(port, MAX310X_MODE2_REG, + MAX310X_MODE2_FIFORST_BIT, 0); + if (port->rs485.flags & SER_RS485_ENABLED && one->baud) { + unsigned int hold = DIV_ROUND_UP(one->baud * + port->rs485.delay_rts_after_send, + MSEC_PER_SEC); + + fsleep(max(DIV_ROUND_UP((hold + 1) * USEC_PER_SEC, + one->baud), 100U)); + } + } + + /* + * The wind-down is over: cancel unconditionally. The SW/HW decision + * is recomputed on every reconfigure, so a TIOCSRS485 can clear + * sw_rts_during_tx while an envelope is still in flight, and + * neither the timer nor the works may outlive the port. + */ + scoped_guard(spinlock_irqsave, &port->lock) + one->cancel_tx_delay_tmr = true; + cancel_work_sync(&one->tx_work); + hrtimer_cancel(&one->tx_delay_tmr); + cancel_work_sync(&one->rts_work); + WRITE_ONCE(one->tx_state, MAX310X_TX_OFF); + + if (READ_ONCE(one->sw_rts_during_tx)) { + max310x_rts_ctl(port, max310x_rts_level(port, false)); + /* + * The power-off below stops the UART clock that moves the + * RTS pin: released too late, the write reaches the register + * but the pin stays at its old level until the next startup + * restarts the clock. Give the release one bit time (at + * least 100 us) to reach the pin - the measured propagation + * is about one tick of the 16x oversampling clock. + */ + fsleep(max(one->char_time_us / 10, 100U)); + } + max310x_power(port, 0); } @@ -1300,7 +1850,8 @@ static int max310x_gpio_set_config(struct gpio_chip *chip, unsigned int offset, #endif static const struct serial_rs485 max310x_rs485_supported = { - .flags = SER_RS485_ENABLED | SER_RS485_RTS_ON_SEND | SER_RS485_RX_DURING_TX, + .flags = SER_RS485_ENABLED | SER_RS485_RTS_ON_SEND | + SER_RS485_RTS_AFTER_SEND | SER_RS485_RX_DURING_TX, .delay_rts_before_send = 1, .delay_rts_after_send = 1, }; @@ -1427,6 +1978,11 @@ static int max310x_probe(struct device *dev, const struct max310x_devtype *devty INIT_WORK(&s->p[i].md_work, max310x_md_proc); /* Initialize queue for changing RS485 mode */ INIT_WORK(&s->p[i].rs_work, max310x_rs_proc); + /* Initialize queue for software-driven RTS toggling */ + INIT_WORK(&s->p[i].rts_work, max310x_rts_work_proc); + hrtimer_setup(&s->p[i].tx_delay_tmr, max310x_tmr_tx, + CLOCK_MONOTONIC, HRTIMER_MODE_REL); + s->p[i].tx_state = MAX310X_TX_OFF; } #ifdef CONFIG_GPIOLIB @@ -1538,6 +2094,8 @@ static void max310x_remove(struct device *dev) int i; for (i = 0; i < s->devtype->nr; i++) { + hrtimer_cancel(&s->p[i].tx_delay_tmr); + cancel_work_sync(&s->p[i].rts_work); cancel_work_sync(&s->p[i].tx_work); cancel_work_sync(&s->p[i].md_work); cancel_work_sync(&s->p[i].rs_work); diff --git a/drivers/tty/serial/pmac_zilog.c b/drivers/tty/serial/pmac_zilog.c index f49d6052d11b..a612f1db9f18 100644 --- a/drivers/tty/serial/pmac_zilog.c +++ b/drivers/tty/serial/pmac_zilog.c @@ -233,6 +233,7 @@ static bool pmz_receive_chars(struct uart_pmac_port *uap) ch &= uap->parity_mask; if (ch == 0 && uap->flags & PMACZILOG_FLAG_BREAK) { uap->flags &= ~PMACZILOG_FLAG_BREAK; + r1 |= BRK_ABRT; } #if defined(CONFIG_MAGIC_SYSRQ) && defined(CONFIG_SERIAL_CORE_CONSOLE) diff --git a/drivers/tty/serial/qcom_geni_serial.c b/drivers/tty/serial/qcom_geni_serial.c index a851b8f0ef04..dbb1bb7160cc 100644 --- a/drivers/tty/serial/qcom_geni_serial.c +++ b/drivers/tty/serial/qcom_geni_serial.c @@ -2128,6 +2128,12 @@ static int qcom_geni_serial_resume(struct device *dev) return ret; } + if (console_suspend_enabled && uart_console(uport)) { + ret = pm_runtime_resume(dev); + if (ret < 0) + return ret; + } + ret = uart_resume_port(private_data->drv, uport); if (uart_console(uport)) { geni_icc_set_tag(&port->se, QCOM_ICC_TAG_ALWAYS); diff --git a/drivers/tty/serial/serial_txx9.c b/drivers/tty/serial/serial_txx9.c index 4ae9a45c8e3a..ef56979321b9 100644 --- a/drivers/tty/serial/serial_txx9.c +++ b/drivers/tty/serial/serial_txx9.c @@ -1009,7 +1009,8 @@ static void serial_txx9_unregister_port(int line) struct uart_port *uart = &serial_txx9_ports[line]; mutex_lock(&serial_txx9_mutex); - uart_remove_one_port(&serial_txx9_reg, uart); + if (uart->iobase || uart->mapbase) + uart_remove_one_port(&serial_txx9_reg, uart); uart->flags = 0; uart->type = PORT_UNKNOWN; uart->iobase = 0; @@ -1019,52 +1020,6 @@ static void serial_txx9_unregister_port(int line) mutex_unlock(&serial_txx9_mutex); } -/* - * Register a set of serial devices attached to a platform device. - */ -static int serial_txx9_probe(struct platform_device *dev) -{ - struct uart_port *p = dev_get_platdata(&dev->dev); - struct uart_port port; - int ret, i; - - memset(&port, 0, sizeof(struct uart_port)); - for (i = 0; p && p->uartclk != 0; p++, i++) { - port.iobase = p->iobase; - port.membase = p->membase; - port.irq = p->irq; - port.uartclk = p->uartclk; - port.iotype = p->iotype; - port.flags = p->flags; - port.mapbase = p->mapbase; - port.dev = &dev->dev; - port.has_sysrq = IS_ENABLED(CONFIG_SERIAL_TXX9_CONSOLE); - ret = serial_txx9_register_port(&port); - if (ret < 0) { - dev_err(&dev->dev, "unable to register port at index %d " - "(IO%lx MEM%llx IRQ%d): %d\n", i, - p->iobase, (unsigned long long)p->mapbase, - p->irq, ret); - } - } - return 0; -} - -/* - * Remove serial ports registered against a platform device. - */ -static void serial_txx9_remove(struct platform_device *dev) -{ - int i; - - for (i = 0; i < UART_NR; i++) { - struct uart_port *up = &serial_txx9_ports[i]; - - if (up->dev == &dev->dev) - serial_txx9_unregister_port(i); - } -} - #ifdef CONFIG_PM static int serial_txx9_suspend(struct platform_device *dev, pm_message_t state) { @@ -1096,8 +1051,6 @@ static int serial_txx9_resume(struct platform_device *dev) #endif static struct platform_driver serial_txx9_plat_driver = { - .probe = serial_txx9_probe, - .remove = serial_txx9_remove, #ifdef CONFIG_PM .suspend = serial_txx9_suspend, .resume = serial_txx9_resume, @@ -1251,9 +1204,7 @@ static void __exit serial_txx9_exit(void) platform_driver_unregister(&serial_txx9_plat_driver); platform_device_unregister(serial_txx9_plat_devs); for (i = 0; i < UART_NR; i++) { - struct uart_port *up = &serial_txx9_ports[i]; - if (up->iobase || up->mapbase) - uart_remove_one_port(&serial_txx9_reg, up); + serial_txx9_unregister_port(i); } uart_unregister_driver(&serial_txx9_reg); diff --git a/drivers/tty/serial/sh-sci.c b/drivers/tty/serial/sh-sci.c index 92193eb26abf..50ae9aae6b61 100644 --- a/drivers/tty/serial/sh-sci.c +++ b/drivers/tty/serial/sh-sci.c @@ -3937,12 +3937,12 @@ static int sci_probe(struct platform_device *dev) if (sp->port.fifosize > 1) { ret = device_create_file(&dev->dev, &dev_attr_rx_fifo_trigger); if (ret) - return ret; + goto err_remove_port; ret = device_create_file(&dev->dev, &dev_attr_rx_fifo_timeout); if (ret) { device_remove_file(&dev->dev, &dev_attr_rx_fifo_trigger); - return ret; + goto err_remove_port; } } @@ -3952,6 +3952,10 @@ static int sci_probe(struct platform_device *dev) sci_ports_in_use |= BIT(dev_id); return 0; + +err_remove_port: + uart_remove_one_port(&sci_uart_driver, &sp->port); + return ret; } static int sci_suspend(struct device *dev) diff --git a/drivers/tty/serial/sifive.c b/drivers/tty/serial/sifive.c index f615701fceb7..c720e9888416 100644 --- a/drivers/tty/serial/sifive.c +++ b/drivers/tty/serial/sifive.c @@ -999,7 +999,7 @@ static int sifive_serial_probe(struct platform_device *pdev) } #ifdef CONFIG_SERIAL_SIFIVE_CONSOLE - if (id > SIFIVE_SERIAL_MAX_PORTS) { + if (id >= SIFIVE_SERIAL_MAX_PORTS) { dev_err(&pdev->dev, "too many UARTs (%d)\n", id); return -EINVAL; } diff --git a/drivers/ufs/core/ufshcd.c b/drivers/ufs/core/ufshcd.c index dfbcf036d356..15d1e97e1c38 100644 --- a/drivers/ufs/core/ufshcd.c +++ b/drivers/ufs/core/ufshcd.c @@ -4753,7 +4753,17 @@ void ufshcd_auto_hibern8_update(struct ufs_hba *hba, u32 ahit) if (!pm_runtime_suspended(&hba->ufs_device_wlun->sdev_gendev)) { ufshcd_rpm_get_sync(hba); ufshcd_hold(hba); - ufshcd_configure_auto_hibern8(hba); + /* + * Serialize with the host driver's AHIT control. Skip the + * register write while the driver has AHIT forced off; the + * driver programs hba->ahit back when it re-enables it. + * Mutex is taken here (not across the rpm calls above) so it + * never blocks a resume that the driver's path may need. + */ + mutex_lock(&hba->ahit_mutex); + if (!hba->ahit_disable_depth) + ufshcd_configure_auto_hibern8(hba); + mutex_unlock(&hba->ahit_mutex); ufshcd_release(hba); ufshcd_rpm_put_sync(hba); } @@ -4984,8 +4994,12 @@ int ufshcd_change_power_mode(struct ufs_hba *hba, ret = ufshcd_dme_change_power_mode(hba, pwr_mode, pmc_policy); - if (!ret) - ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, pwr_mode); + /* + * Always notify POST_CHANGE to pair with PRE_CHANGE, even on failure. + * On failure, pass dev_req_params = NULL to indicate nothing to apply. + * POST_CHANGE return value is advisory and does not mask @ret. + */ + ufshcd_vops_pwr_change_notify(hba, POST_CHANGE, ret ? NULL : pwr_mode); return ret; } @@ -5876,18 +5890,26 @@ static irqreturn_t ufshcd_uic_cmd_compl(struct ufs_hba *hba, u32 intr_status) { irqreturn_t retval = IRQ_NONE; struct uic_command *cmd; + bool ah8_err; guard(spinlock_irqsave)(hba->host->host_lock); + + /* + * Auto-hibern8 is performed without a UIC command, so check for + * auto-hibern8 errors before checking for an active UIC command. + */ + ah8_err = ufshcd_is_auto_hibern8_error(hba, intr_status); + if (ah8_err) + hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status); + cmd = hba->active_uic_cmd; if (!cmd) { - dev_err(hba->dev, - "No active UIC command. Maybe a timeout occurred?\n"); + if (!ah8_err) + dev_err(hba->dev, + "No active UIC command. Maybe a timeout occurred?\n"); return retval; } - if (ufshcd_is_auto_hibern8_error(hba, intr_status)) - hba->errors |= (UFSHCD_UIC_HIBERN8_MASK & intr_status); - if (intr_status & UIC_COMMAND_COMPL) { /* * Store the UIC command result in the lowest byte of @@ -11285,6 +11307,8 @@ int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq) mutex_init(&hba->wb_mutex); + mutex_init(&hba->ahit_mutex); + init_rwsem(&hba->clk_scaling_lock); ufshcd_init_clk_gating(hba); diff --git a/drivers/ufs/host/ufs-exynos.c b/drivers/ufs/host/ufs-exynos.c index b2f65c465525..3bcbc9ebbb28 100644 --- a/drivers/ufs/host/ufs-exynos.c +++ b/drivers/ufs/host/ufs-exynos.c @@ -1782,7 +1782,9 @@ static int exynos_ufs_pwr_change_notify(struct ufs_hba *hba, ret = exynos_ufs_pre_pwr_mode(hba, dev_req_params); break; case POST_CHANGE: - ret = exynos_ufs_post_pwr_mode(hba, dev_req_params); + /* NULL when the gear switch failed: nothing to apply */ + if (dev_req_params) + ret = exynos_ufs_post_pwr_mode(hba, dev_req_params); break; } diff --git a/drivers/ufs/host/ufs-mediatek.c b/drivers/ufs/host/ufs-mediatek.c index 12a6d4138e44..ff0a661c1430 100644 --- a/drivers/ufs/host/ufs-mediatek.c +++ b/drivers/ufs/host/ufs-mediatek.c @@ -1521,19 +1521,27 @@ static int ufs_mtk_pwr_change_notify(struct ufs_hba *hba, struct ufs_pa_layer_attr *dev_req_params) { int ret = 0; - static u32 reg; switch (stage) { case PRE_CHANGE: if (ufshcd_is_auto_hibern8_supported(hba)) { - reg = ufshcd_readl(hba, REG_AUTO_HIBERNATE_IDLE_TIMER); + /* Block sysfs AHIT writes while we force AHIT off */ + mutex_lock(&hba->ahit_mutex); + hba->ahit_disable_depth++; + mutex_unlock(&hba->ahit_mutex); ufs_mtk_auto_hibern8_disable(hba); } ret = ufs_mtk_pre_pwr_change(hba, dev_req_params); break; case POST_CHANGE: - if (ufshcd_is_auto_hibern8_supported(hba)) - ufshcd_writel(hba, reg, REG_AUTO_HIBERNATE_IDLE_TIMER); + if (ufshcd_is_auto_hibern8_supported(hba)) { + mutex_lock(&hba->ahit_mutex); + /* re-enable only when the last disabler drops off */ + if (!--hba->ahit_disable_depth) + ufshcd_writel(hba, hba->ahit, + REG_AUTO_HIBERNATE_IDLE_TIMER); + mutex_unlock(&hba->ahit_mutex); + } break; default: ret = -EINVAL; diff --git a/drivers/ufs/host/ufs-qcom.c b/drivers/ufs/host/ufs-qcom.c index 954be9343f42..08f83d789e46 100644 --- a/drivers/ufs/host/ufs-qcom.c +++ b/drivers/ufs/host/ufs-qcom.c @@ -3001,6 +3001,10 @@ static void ufs_qcom_remove(struct platform_device *pdev) platform_device_msi_free_irqs_all(hba->dev); } +static const struct ufs_qcom_drvdata ufs_qcom_milos_drvdata = { + .no_phy_retention = true, +}; + static const struct ufs_qcom_drvdata ufs_qcom_sm8550_drvdata = { .quirks = UFSHCD_QUIRK_BROKEN_LSDBS_CAP, .no_phy_retention = true, @@ -3012,6 +3016,7 @@ static const struct ufs_qcom_drvdata ufs_qcom_sa8255p_drvdata = { static const struct of_device_id ufs_qcom_of_match[] __maybe_unused = { { .compatible = "qcom,ufshc" }, + { .compatible = "qcom,milos-ufshc", .data = &ufs_qcom_milos_drvdata }, { .compatible = "qcom,sm8550-ufshc", .data = &ufs_qcom_sm8550_drvdata }, { .compatible = "qcom,sm8650-ufshc", .data = &ufs_qcom_sm8550_drvdata }, { .compatible = "qcom,sa8255p-ufshc", .data = &ufs_qcom_sa8255p_drvdata }, diff --git a/drivers/ufs/host/ufshcd-pci.c b/drivers/ufs/host/ufshcd-pci.c index 21bb11c724be..668b57403e62 100644 --- a/drivers/ufs/host/ufshcd-pci.c +++ b/drivers/ufs/host/ufshcd-pci.c @@ -166,7 +166,8 @@ static int ufs_intel_lkf_pwr_change_notify(struct ufs_hba *hba, ufs_intel_set_lanes(hba, 2); break; case POST_CHANGE: - if (ufshcd_is_hs_mode(dev_req_params)) { + /* NULL when the gear switch failed: nothing to apply */ + if (dev_req_params && ufshcd_is_hs_mode(dev_req_params)) { u32 peer_granularity; usleep_range(1000, 1250); diff --git a/drivers/usb/gadget/composite.c b/drivers/usb/gadget/composite.c index df39e3487c1f..1b2238147cfe 100644 --- a/drivers/usb/gadget/composite.c +++ b/drivers/usb/gadget/composite.c @@ -2740,7 +2740,7 @@ void usb_composite_setup_continue(struct usb_composite_dev *cdev) spin_lock_irqsave(&cdev->lock, flags); if (cdev->delayed_status == 0) { - WARN(cdev, "%s: Unexpected call\n", __func__); + DBG(cdev, "%s: Ignoring obsolete call\n", __func__); } else if (--cdev->delayed_status == 0) { DBG(cdev, "%s: Completing delayed status\n", __func__); diff --git a/drivers/usb/gadget/function/f_mass_storage.c b/drivers/usb/gadget/function/f_mass_storage.c index fc4818fb2a8b..42fd2d6ffd88 100644 --- a/drivers/usb/gadget/function/f_mass_storage.c +++ b/drivers/usb/gadget/function/f_mass_storage.c @@ -463,7 +463,12 @@ static int fsg_setup(struct usb_function *f, u16 w_value = le16_to_cpu(ctrl->wValue); u16 w_length = le16_to_cpu(ctrl->wLength); - if (!fsg_is_set(fsg->common)) + /* + * fsg_is_set() warns when common->fsg is NULL, but that can happen + * normally while a configuration change installs or removes the active + * function. + */ + if (!fsg->common->fsg) return -EOPNOTSUPP; ++fsg->common->ep0_req_tag; /* Record arrival of a new request */ diff --git a/drivers/usb/gadget/udc/dummy_hcd.c b/drivers/usb/gadget/udc/dummy_hcd.c index 0d30dd67b9ca..3e33f738742e 100644 --- a/drivers/usb/gadget/udc/dummy_hcd.c +++ b/drivers/usb/gadget/udc/dummy_hcd.c @@ -918,7 +918,7 @@ static int dummy_set_selfpowered(struct usb_gadget *_gadget, int value) static void dummy_udc_update_ep0(struct dummy *dum) { if (dum->gadget.speed == USB_SPEED_SUPER) - dum->ep[0].ep.maxpacket = 9; + dum->ep[0].ep.maxpacket = 512; else dum->ep[0].ep.maxpacket = 64; } @@ -1184,6 +1184,7 @@ static struct platform_driver dummy_udc_driver = { .resume = dummy_udc_resume, .driver = { .name = gadget_name, + .suppress_bind_attrs = true, }, }; @@ -2806,6 +2807,7 @@ static struct platform_driver dummy_hcd_driver = { .resume = dummy_hcd_resume, .driver = { .name = driver_name, + .suppress_bind_attrs = true, }, }; diff --git a/drivers/usb/host/pci-quirks.c b/drivers/usb/host/pci-quirks.c index 0404489c2f6a..ba158d63bb8b 100644 --- a/drivers/usb/host/pci-quirks.c +++ b/drivers/usb/host/pci-quirks.c @@ -1073,6 +1073,7 @@ void usb_enable_intel_xhci_ports(struct pci_dev *xhci_pdev) if (companion->class == PCI_CLASS_SERIAL_USB_EHCI && companion->vendor == PCI_VENDOR_ID_INTEL) { ehci_found = true; + pci_dev_put(companion); break; } } diff --git a/drivers/usb/host/xhci-dbgtty.c b/drivers/usb/host/xhci-dbgtty.c index 3d51e8d82659..2249cc16800c 100644 --- a/drivers/usb/host/xhci-dbgtty.c +++ b/drivers/usb/host/xhci-dbgtty.c @@ -535,7 +535,9 @@ static int xhci_dbc_tty_register_device(struct xhci_dbc *dbc) err_free_fifo: kfifo_free(&port->port.xmit_fifo); err_exit_port: + mutex_lock(&dbc_tty_minors_lock); idr_remove(&dbc_tty_minors, port->minor); + mutex_unlock(&dbc_tty_minors_lock); err_idr: xhci_dbc_tty_exit_port(port); diff --git a/drivers/usb/image/microtek.c b/drivers/usb/image/microtek.c index 1f0b3c44d388..787cf5aba55d 100644 --- a/drivers/usb/image/microtek.c +++ b/drivers/usb/image/microtek.c @@ -475,6 +475,7 @@ static void mts_do_sg (struct urb* transfer) if (unlikely(status)) { set_host_byte(context->srb, (status == -ENOENT ? DID_ABORT : DID_ERROR)); mts_transfer_cleanup(transfer); + return; } context->curr_sg = sg_next(context->curr_sg); diff --git a/drivers/usb/mon/mon_main.c b/drivers/usb/mon/mon_main.c index e4fff194fea0..600c9de84c7e 100644 --- a/drivers/usb/mon/mon_main.c +++ b/drivers/usb/mon/mon_main.c @@ -199,6 +199,9 @@ static void mon_bus_remove(struct usb_bus *ubus) { struct mon_bus *mbus = ubus->mon_bus; + if (mbus == NULL) + return; + mutex_lock(&mon_lock); list_del(&mbus->bus_link); if (mbus->text_inited) diff --git a/drivers/usb/musb/da8xx.c b/drivers/usb/musb/da8xx.c index 4209f438ba18..6c859a1a11d0 100644 --- a/drivers/usb/musb/da8xx.c +++ b/drivers/usb/musb/da8xx.c @@ -562,7 +562,7 @@ static int da8xx_probe(struct platform_device *pdev) ret = of_platform_populate(pdev->dev.of_node, NULL, da8xx_auxdata_lookup, &pdev->dev); if (ret) - goto err_unregister_phy; + goto err_depopulate; pinfo = da8xx_dev_info; pinfo.parent = &pdev->dev; @@ -577,12 +577,13 @@ static int da8xx_probe(struct platform_device *pdev) ret = PTR_ERR_OR_ZERO(glue->musb); if (ret) { dev_err(&pdev->dev, "failed to register musb device: %d\n", ret); - goto err_unregister_phy; + goto err_depopulate; } return 0; -err_unregister_phy: +err_depopulate: + of_platform_depopulate(&pdev->dev); usb_phy_generic_unregister(glue->usb_phy); return ret; } @@ -592,6 +593,7 @@ static void da8xx_remove(struct platform_device *pdev) struct da8xx_glue *glue = platform_get_drvdata(pdev); platform_device_unregister(glue->musb); + of_platform_depopulate(&pdev->dev); usb_phy_generic_unregister(glue->usb_phy); } diff --git a/drivers/usb/storage/alauda.c b/drivers/usb/storage/alauda.c index 691fe47009cf..5e7f99ba8ac0 100644 --- a/drivers/usb/storage/alauda.c +++ b/drivers/usb/storage/alauda.c @@ -500,11 +500,14 @@ static int alauda_check_media(struct us_data *us) static int alauda_check_status2(struct us_data *us) { int rc; - unsigned char command[] = { - ALAUDA_BULK_CMD, ALAUDA_BULK_GET_STATUS2, - 0, 0, 0, 0, 3, 0, MEDIA_PORT(us) - }; - unsigned char data[3]; + unsigned char *command = us->iobuf; + unsigned char *data = us->iobuf; + + memset(command, 0, 9); + command[0] = ALAUDA_BULK_CMD; + command[1] = ALAUDA_BULK_GET_STATUS2; + command[6] = 3; + command[8] = MEDIA_PORT(us); rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, command, 9, NULL); @@ -530,10 +533,15 @@ static int alauda_check_status2(struct us_data *us) static int alauda_get_redu_data(struct us_data *us, u16 pba, unsigned char *data) { int rc; - unsigned char command[] = { - ALAUDA_BULK_CMD, ALAUDA_BULK_GET_REDU_DATA, - PBA_HI(pba), PBA_ZONE(pba), 0, PBA_LO(pba), 0, 0, MEDIA_PORT(us) - }; + unsigned char *command = us->iobuf; + + memset(command, 0, 9); + command[0] = ALAUDA_BULK_CMD; + command[1] = ALAUDA_BULK_GET_REDU_DATA; + command[2] = PBA_HI(pba); + command[3] = PBA_ZONE(pba); + command[5] = PBA_LO(pba); + command[8] = MEDIA_PORT(us); rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, command, 9, NULL); @@ -689,11 +697,13 @@ static int alauda_read_map(struct us_data *us, unsigned int zone) * Checks to see whether we have already mapped a certain zone * If we haven't, the map is generated */ -static void alauda_ensure_map_for_zone(struct us_data *us, unsigned int zone) +static int alauda_ensure_map_for_zone(struct us_data *us, unsigned int zone) { if (MEDIA_INFO(us).lba_to_pba[zone] == NULL || MEDIA_INFO(us).pba_to_lba[zone] == NULL) - alauda_read_map(us, zone); + return alauda_read_map(us, zone); + + return 0; } /* @@ -702,14 +712,20 @@ static void alauda_ensure_map_for_zone(struct us_data *us, unsigned int zone) static int alauda_erase_block(struct us_data *us, u16 pba) { int rc; - unsigned char command[] = { - ALAUDA_BULK_CMD, ALAUDA_BULK_ERASE_BLOCK, PBA_HI(pba), - PBA_ZONE(pba), 0, PBA_LO(pba), 0x02, 0, MEDIA_PORT(us) - }; - unsigned char buf[2]; + unsigned char *command = us->iobuf; + unsigned char *buf = us->iobuf; usb_stor_dbg(us, "Erasing PBA %d\n", pba); + memset(command, 0, 9); + command[0] = ALAUDA_BULK_CMD; + command[1] = ALAUDA_BULK_ERASE_BLOCK; + command[2] = PBA_HI(pba); + command[3] = PBA_ZONE(pba); + command[5] = PBA_LO(pba); + command[6] = 0x02; + command[8] = MEDIA_PORT(us); + rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, command, 9, NULL); if (rc != USB_STOR_XFER_GOOD) @@ -732,13 +748,19 @@ static int alauda_read_block_raw(struct us_data *us, u16 pba, unsigned int page, unsigned int pages, unsigned char *data) { int rc; - unsigned char command[] = { - ALAUDA_BULK_CMD, ALAUDA_BULK_READ_BLOCK, PBA_HI(pba), - PBA_ZONE(pba), 0, PBA_LO(pba) + page, pages, 0, MEDIA_PORT(us) - }; + unsigned char *command = us->iobuf; usb_stor_dbg(us, "pba %d page %d count %d\n", pba, page, pages); + memset(command, 0, 9); + command[0] = ALAUDA_BULK_CMD; + command[1] = ALAUDA_BULK_READ_BLOCK; + command[2] = PBA_HI(pba); + command[3] = PBA_ZONE(pba); + command[5] = PBA_LO(pba) + page; + command[6] = pages; + command[8] = MEDIA_PORT(us); + rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, command, 9, NULL); if (rc != USB_STOR_XFER_GOOD) @@ -783,13 +805,19 @@ static int alauda_write_block(struct us_data *us, u16 pba, unsigned char *data) { int rc; struct alauda_info *info = (struct alauda_info *) us->extra; - unsigned char command[] = { - ALAUDA_BULK_CMD, ALAUDA_BULK_WRITE_BLOCK, PBA_HI(pba), - PBA_ZONE(pba), 0, PBA_LO(pba), 32, 0, MEDIA_PORT(us) - }; + unsigned char *command = us->iobuf; usb_stor_dbg(us, "pba %d\n", pba); + memset(command, 0, 9); + command[0] = ALAUDA_BULK_CMD; + command[1] = ALAUDA_BULK_WRITE_BLOCK; + command[2] = PBA_HI(pba); + command[3] = PBA_ZONE(pba); + command[5] = PBA_LO(pba); + command[6] = 32; + command[8] = MEDIA_PORT(us); + rc = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, command, 9, NULL); if (rc != USB_STOR_XFER_GOOD) @@ -823,7 +851,9 @@ static int alauda_write_lba(struct us_data *us, u16 lba, unsigned int new_pba_offset; unsigned int zone = lba / uzonesize; - alauda_ensure_map_for_zone(us, zone); + result = alauda_ensure_map_for_zone(us, zone); + if (result != USB_STOR_TRANSPORT_GOOD) + return result; pba = MEDIA_INFO(us).lba_to_pba[zone][lba_offset]; if (pba == 1) { @@ -919,6 +949,7 @@ static int alauda_read_data(struct us_data *us, unsigned long address, unsigned char *buffer; u16 lba, max_lba; unsigned int page, len, offset; + unsigned int num_zones; unsigned int blockshift = MEDIA_INFO(us).blockshift; unsigned int pageshift = MEDIA_INFO(us).pageshift; unsigned int blocksize = MEDIA_INFO(us).blocksize; @@ -943,7 +974,9 @@ static int alauda_read_data(struct us_data *us, unsigned long address, /* Figure out the initial LBA and page */ lba = address >> blockshift; page = (address & MEDIA_INFO(us).blockmask); - max_lba = MEDIA_INFO(us).capacity >> (blockshift + pageshift); + num_zones = MEDIA_INFO(us).capacity >> (MEDIA_INFO(us).zoneshift + + blockshift + pageshift); + max_lba = num_zones * uzonesize; result = USB_STOR_TRANSPORT_GOOD; offset = 0; @@ -954,7 +987,6 @@ static int alauda_read_data(struct us_data *us, unsigned long address, unsigned int lba_offset = lba - (zone * uzonesize); unsigned int pages; u16 pba; - alauda_ensure_map_for_zone(us, zone); /* Not overflowing capacity? */ if (lba >= max_lba) { @@ -964,6 +996,10 @@ static int alauda_read_data(struct us_data *us, unsigned long address, break; } + result = alauda_ensure_map_for_zone(us, zone); + if (result != USB_STOR_TRANSPORT_GOOD) + break; + /* Find number of pages we can read in this block */ pages = min(sectors, blocksize - page); len = pages << pageshift; @@ -1019,6 +1055,7 @@ static int alauda_write_data(struct us_data *us, unsigned long address, unsigned int pagesize = MEDIA_INFO(us).pagesize; struct scatterlist *sg; u16 lba, max_lba; + unsigned int num_zones; int result; /* @@ -1045,7 +1082,9 @@ static int alauda_write_data(struct us_data *us, unsigned long address, /* Figure out the initial LBA and page */ lba = address >> blockshift; page = (address & MEDIA_INFO(us).blockmask); - max_lba = MEDIA_INFO(us).capacity >> (pageshift + blockshift); + num_zones = MEDIA_INFO(us).capacity >> (MEDIA_INFO(us).zoneshift + + blockshift + pageshift); + max_lba = num_zones * MEDIA_INFO(us).uzonesize; result = USB_STOR_TRANSPORT_GOOD; offset = 0; diff --git a/drivers/vdpa/vdpa_sim/vdpa_sim_blk.c b/drivers/vdpa/vdpa_sim/vdpa_sim_blk.c index 76dd5b0828d7..4d3e36fb59d5 100644 --- a/drivers/vdpa/vdpa_sim/vdpa_sim_blk.c +++ b/drivers/vdpa/vdpa_sim/vdpa_sim_blk.c @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -343,11 +344,17 @@ static void vdpasim_blk_work(struct vdpasim *vdpasim) continue; while (vdpasim_blk_handle_req(vdpasim, vq)) { + bool notify; + /* Make sure used is visible before rasing the interrupt. */ smp_wmb(); local_bh_disable(); - if (vringh_need_notify_iotlb(&vq->vring) > 0) + /* The ring may be in user memory, and we can't take faults here */ + pagefault_disable(); + notify = vringh_need_notify_iotlb(&vq->vring) > 0; + pagefault_enable(); + if (notify) vringh_notify(&vq->vring); local_bh_enable(); diff --git a/drivers/vdpa/vdpa_sim/vdpa_sim_net.c b/drivers/vdpa/vdpa_sim/vdpa_sim_net.c index a6514b5ccd86..543a58abcdb8 100644 --- a/drivers/vdpa/vdpa_sim/vdpa_sim_net.c +++ b/drivers/vdpa/vdpa_sim/vdpa_sim_net.c @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -68,6 +69,8 @@ static struct vdpasim_net *sim_to_net(struct vdpasim *vdpasim) static void vdpasim_net_complete(struct vdpasim_virtqueue *vq, size_t len) { + bool notify; + /* Make sure data is wrote before advancing index */ smp_wmb(); @@ -77,7 +80,11 @@ static void vdpasim_net_complete(struct vdpasim_virtqueue *vq, size_t len) smp_wmb(); local_bh_disable(); - if (vringh_need_notify_iotlb(&vq->vring) > 0) + /* The ring may be in user memory, and we can't take faults here */ + pagefault_disable(); + notify = vringh_need_notify_iotlb(&vq->vring) > 0; + pagefault_enable(); + if (notify) vringh_notify(&vq->vring); local_bh_enable(); } diff --git a/drivers/vfio/cdx/main.c b/drivers/vfio/cdx/main.c index b31ed4be7bdc..28386fdb01f2 100644 --- a/drivers/vfio/cdx/main.c +++ b/drivers/vfio/cdx/main.c @@ -281,9 +281,13 @@ static int vfio_cdx_mmap(struct vfio_device *core_vdev, (vma->vm_flags & VM_READ)) return -EPERM; - if (!(vdev->regions[index].flags & VFIO_REGION_INFO_FLAG_WRITE) && - (vma->vm_flags & VM_WRITE)) - return -EPERM; + /* Prevent read-only region mappings from being upgraded with mprotect() */ + if (!(vdev->regions[index].flags & VFIO_REGION_INFO_FLAG_WRITE)) { + if (vma->vm_flags & VM_WRITE) + return -EPERM; + + vm_flags_clear(vma, VM_MAYWRITE); + } return vfio_cdx_mmap_mmio(vdev->regions[index], vma); } diff --git a/drivers/vfio/device_cdev.c b/drivers/vfio/device_cdev.c index 1d9515c967b0..30362936c7b5 100644 --- a/drivers/vfio/device_cdev.c +++ b/drivers/vfio/device_cdev.c @@ -130,6 +130,18 @@ long vfio_df_ioctl_bind_iommufd(struct vfio_device_file *df, goto out_unlock; } + /* + * The cdev path allows only a single open. Reject a second open here, + * before the VF token and device->kvm updates below would clobber the + * current opener's state on a bind that cannot complete. Return -EBUSY + * rather than -EINVAL since a delayed release of the prior opener can + * make this transient. + */ + if (device->open_count) { + ret = -EBUSY; + goto out_unlock; + } + ret = vfio_df_check_token(device, &bind); if (ret) goto out_unlock; diff --git a/drivers/vfio/fsl-mc/vfio_fsl_mc.c b/drivers/vfio/fsl-mc/vfio_fsl_mc.c index b4c3958201b2..5a6cd78dcc06 100644 --- a/drivers/vfio/fsl-mc/vfio_fsl_mc.c +++ b/drivers/vfio/fsl-mc/vfio_fsl_mc.c @@ -403,9 +403,13 @@ static int vfio_fsl_mc_mmap(struct vfio_device *core_vdev, && (vma->vm_flags & VM_READ)) return -EINVAL; - if (!(vdev->regions[index].flags & VFIO_REGION_INFO_FLAG_WRITE) - && (vma->vm_flags & VM_WRITE)) - return -EINVAL; + /* Prevent read-only region mappings from being upgraded with mprotect() */ + if (!(vdev->regions[index].flags & VFIO_REGION_INFO_FLAG_WRITE)) { + if (vma->vm_flags & VM_WRITE) + return -EINVAL; + + vm_flags_clear(vma, VM_MAYWRITE); + } vma->vm_private_data = mc_dev; diff --git a/drivers/vfio/pci/hisilicon/hisi_acc_vfio_pci.c b/drivers/vfio/pci/hisilicon/hisi_acc_vfio_pci.c index 86362ec424a5..c82c59246a3f 100644 --- a/drivers/vfio/pci/hisilicon/hisi_acc_vfio_pci.c +++ b/drivers/vfio/pci/hisilicon/hisi_acc_vfio_pci.c @@ -16,6 +16,9 @@ #include "hisi_acc_vfio_pci.h" +VFIO_PCI_CORE_DEFINE_CALLBACKS(hisi_acc_vf, struct hisi_acc_vf_core_device, + core_device) + /* Return 0 on VM acc device ready, -ETIMEDOUT hardware timeout */ static int qm_wait_dev_not_ready(struct hisi_qm *qm) { @@ -588,10 +591,7 @@ static int vf_qm_state_save(struct hisi_acc_vf_core_device *hisi_acc_vdev, static struct hisi_acc_vf_core_device *hisi_acc_drvdata(struct pci_dev *pdev) { - struct vfio_pci_core_device *core_device = dev_get_drvdata(&pdev->dev); - - return container_of(core_device, struct hisi_acc_vf_core_device, - core_device); + return pci_get_drvdata(pdev); } /* Check the PF's RAS state and Function INT state */ @@ -1154,14 +1154,16 @@ static void hisi_acc_vf_pci_reset_prepare(struct pci_dev *pdev) { struct hisi_acc_vf_core_device *hisi_acc_vdev = hisi_acc_drvdata(pdev); struct hisi_qm *qm = hisi_acc_vdev->pf_qm; - struct device *dev = &qm->pdev->dev; u32 delay = 0; + if (!hisi_acc_vdev->core_device.vdev.mig_ops) + return; + /* All reset requests need to be queued for processing */ while (test_and_set_bit(QM_RESETTING, &qm->misc_ctl)) { msleep(1); if (++delay > QM_RESET_WAIT_TIMEOUT) { - dev_err(dev, "reset prepare failed\n"); + dev_err(&qm->pdev->dev, "reset prepare failed\n"); return; } } @@ -1174,12 +1176,14 @@ static void hisi_acc_vf_pci_aer_reset_done(struct pci_dev *pdev) struct hisi_acc_vf_core_device *hisi_acc_vdev = hisi_acc_drvdata(pdev); struct hisi_qm *qm = hisi_acc_vdev->pf_qm; - if (hisi_acc_vdev->set_reset_flag) - clear_bit(QM_RESETTING, &qm->misc_ctl); - if (!hisi_acc_vdev->core_device.vdev.mig_ops) return; + if (hisi_acc_vdev->set_reset_flag) { + clear_bit(QM_RESETTING, &qm->misc_ctl); + hisi_acc_vdev->set_reset_flag = false; + } + mutex_lock(&hisi_acc_vdev->state_mutex); hisi_acc_vf_reset(hisi_acc_vdev); mutex_unlock(&hisi_acc_vdev->state_mutex); @@ -1191,13 +1195,6 @@ static int hisi_acc_vf_qm_init(struct hisi_acc_vf_core_device *hisi_acc_vdev) struct hisi_qm *vf_qm = &hisi_acc_vdev->vf_qm; struct hisi_qm *pf_qm = hisi_acc_vdev->pf_qm; struct pci_dev *vf_dev = vdev->pdev; - u32 val; - - val = readl(pf_qm->io_base + QM_MIG_REGION_SEL); - if (pf_qm->ver > QM_HW_V3 && (val & QM_MIG_REGION_EN)) - hisi_acc_vdev->drv_mode = HW_ACC_MIG_PF_CTRL; - else - hisi_acc_vdev->drv_mode = HW_ACC_MIG_VF_CTRL; if (hisi_acc_vdev->drv_mode == HW_ACC_MIG_PF_CTRL) { /* @@ -1416,9 +1413,8 @@ static int hisi_acc_vf_debug_check(struct seq_file *seq, struct vfio_device *vde static int hisi_acc_vf_debug_cmd(struct seq_file *seq, void *data) { struct device *vf_dev = seq->private; - struct vfio_pci_core_device *core_device = dev_get_drvdata(vf_dev); - struct vfio_device *vdev = &core_device->vdev; - struct hisi_acc_vf_core_device *hisi_acc_vdev = hisi_acc_get_vf_dev(vdev); + struct hisi_acc_vf_core_device *hisi_acc_vdev = dev_get_drvdata(vf_dev); + struct vfio_device *vdev = &hisi_acc_vdev->core_device.vdev; struct hisi_qm *vf_qm = &hisi_acc_vdev->vf_qm; u64 value; int ret; @@ -1445,9 +1441,8 @@ static int hisi_acc_vf_debug_cmd(struct seq_file *seq, void *data) static int hisi_acc_vf_dev_read(struct seq_file *seq, void *data) { struct device *vf_dev = seq->private; - struct vfio_pci_core_device *core_device = dev_get_drvdata(vf_dev); - struct vfio_device *vdev = &core_device->vdev; - struct hisi_acc_vf_core_device *hisi_acc_vdev = hisi_acc_get_vf_dev(vdev); + struct hisi_acc_vf_core_device *hisi_acc_vdev = dev_get_drvdata(vf_dev); + struct vfio_device *vdev = &hisi_acc_vdev->core_device.vdev; size_t vf_data_sz = offsetofend(struct acc_vf_data, padding); struct acc_vf_data *vf_data; int ret; @@ -1492,9 +1487,7 @@ static int hisi_acc_vf_dev_read(struct seq_file *seq, void *data) static int hisi_acc_vf_migf_read(struct seq_file *seq, void *data) { struct device *vf_dev = seq->private; - struct vfio_pci_core_device *core_device = dev_get_drvdata(vf_dev); - struct vfio_device *vdev = &core_device->vdev; - struct hisi_acc_vf_core_device *hisi_acc_vdev = hisi_acc_get_vf_dev(vdev); + struct hisi_acc_vf_core_device *hisi_acc_vdev = dev_get_drvdata(vf_dev); size_t vf_data_sz = offsetofend(struct acc_vf_data, padding); struct hisi_acc_vf_migration_file *debug_migf = hisi_acc_vdev->debug_migf; @@ -1665,21 +1658,34 @@ static void hisi_acc_vf_debugfs_exit(struct hisi_acc_vf_core_device *hisi_acc_vd hisi_acc_vdev->debug_migf = NULL; } +static enum hw_drv_mode hisi_acc_vf_get_drv_mode(struct hisi_qm *pf_qm) +{ + u32 val; + + val = readl(pf_qm->io_base + QM_MIG_REGION_SEL); + if (pf_qm->ver > QM_HW_V3 && (val & QM_MIG_REGION_EN)) + return HW_ACC_MIG_PF_CTRL; + + return HW_ACC_MIG_VF_CTRL; +} + static int hisi_acc_vfio_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id) { struct hisi_acc_vf_core_device *hisi_acc_vdev; const struct vfio_device_ops *ops = &hisi_acc_vfio_pci_ops; + enum hw_drv_mode drv_mode = HW_ACC_MIG_VF_CTRL; + resource_size_t func_len; struct hisi_qm *pf_qm; - int vf_id; int ret; pf_qm = hisi_acc_get_pf_qm(pdev); if (pf_qm && pf_qm->ver >= QM_HW_V3) { - vf_id = pci_iov_vf_id(pdev); - if (vf_id >= 0) - ops = &hisi_acc_vfio_pci_migrn_ops; + func_len = pci_resource_len(pdev, VFIO_PCI_BAR2_REGION_INDEX) >> 1; + drv_mode = hisi_acc_vf_get_drv_mode(pf_qm); + if (drv_mode == HW_ACC_MIG_VF_CTRL && func_len < PAGE_SIZE) + pci_warn(pdev, "migration not supported on 64KB pages with QM_HW_V3\n"); else - pci_warn(pdev, "migration support failed, continue with generic interface\n"); + ops = &hisi_acc_vfio_pci_migrn_ops; } hisi_acc_vdev = vfio_alloc_device(hisi_acc_vf_core_device, @@ -1687,7 +1693,9 @@ static int hisi_acc_vfio_pci_probe(struct pci_dev *pdev, const struct pci_device if (IS_ERR(hisi_acc_vdev)) return PTR_ERR(hisi_acc_vdev); - dev_set_drvdata(&pdev->dev, &hisi_acc_vdev->core_device); + hisi_acc_vdev->drv_mode = drv_mode; + + dev_set_drvdata(&pdev->dev, hisi_acc_vdev); ret = vfio_pci_core_register_device(&hisi_acc_vdev->core_device); if (ret) goto out_put_vdev; @@ -1721,7 +1729,7 @@ MODULE_DEVICE_TABLE(pci, hisi_acc_vfio_pci_table); static const struct pci_error_handlers hisi_acc_vf_err_handlers = { .reset_prepare = hisi_acc_vf_pci_reset_prepare, .reset_done = hisi_acc_vf_pci_aer_reset_done, - .error_detected = vfio_pci_core_aer_err_detected, + .error_detected = hisi_acc_vf_aer_err_detected, }; static struct pci_driver hisi_acc_vfio_pci_driver = { @@ -1729,6 +1737,7 @@ static struct pci_driver hisi_acc_vfio_pci_driver = { .id_table = hisi_acc_vfio_pci_table, .probe = hisi_acc_vfio_pci_probe, .remove = hisi_acc_vfio_pci_remove, + .driver = { .pm = pm_ptr(&hisi_acc_vf_pm_ops) }, .err_handler = &hisi_acc_vf_err_handlers, .driver_managed_dma = true, }; diff --git a/drivers/vfio/pci/ism/main.c b/drivers/vfio/pci/ism/main.c index f83e09b915ed..cce3bdf1f070 100644 --- a/drivers/vfio/pci/ism/main.c +++ b/drivers/vfio/pci/ism/main.c @@ -47,6 +47,9 @@ struct ism_vfio_pci_core_device { struct kmem_cache *store_block_cache; }; +VFIO_PCI_CORE_DEFINE_CALLBACKS(ism_vfio, struct ism_vfio_pci_core_device, + core_device) + static int ism_vfio_pci_open_device(struct vfio_device *core_vdev) { struct ism_vfio_pci_core_device *ivpcd; @@ -363,7 +366,7 @@ static int ism_vfio_pci_probe(struct pci_dev *pdev, if (IS_ERR(ivpcd)) return PTR_ERR(ivpcd); - dev_set_drvdata(&pdev->dev, &ivpcd->core_device); + dev_set_drvdata(&pdev->dev, ivpcd); ret = vfio_pci_core_register_device(&ivpcd->core_device); if (ret) @@ -374,12 +377,7 @@ static int ism_vfio_pci_probe(struct pci_dev *pdev, static void ism_vfio_pci_remove(struct pci_dev *pdev) { - struct vfio_pci_core_device *core_device; - struct ism_vfio_pci_core_device *ivpcd; - - core_device = dev_get_drvdata(&pdev->dev); - ivpcd = container_of(core_device, struct ism_vfio_pci_core_device, - core_device); + struct ism_vfio_pci_core_device *ivpcd = pci_get_drvdata(pdev); vfio_pci_core_unregister_device(&ivpcd->core_device); vfio_put_device(&ivpcd->core_device.vdev); @@ -392,12 +390,17 @@ static const struct pci_device_id ism_device_table[] = { }; MODULE_DEVICE_TABLE(pci, ism_device_table); +static const struct pci_error_handlers ism_vfio_err_handlers = { + .error_detected = ism_vfio_aer_err_detected, +}; + static struct pci_driver ism_vfio_pci_driver = { .name = KBUILD_MODNAME, .id_table = ism_device_table, .probe = ism_vfio_pci_probe, .remove = ism_vfio_pci_remove, - .err_handler = &vfio_pci_core_err_handlers, + .driver = { .pm = pm_ptr(&ism_vfio_pm_ops) }, + .err_handler = &ism_vfio_err_handlers, .driver_managed_dma = true, }; diff --git a/drivers/vfio/pci/mlx5/main.c b/drivers/vfio/pci/mlx5/main.c index de306dee1d1a..18a6d224b1fd 100644 --- a/drivers/vfio/pci/mlx5/main.c +++ b/drivers/vfio/pci/mlx5/main.c @@ -21,6 +21,9 @@ #include "cmd.h" +VFIO_PCI_CORE_DEFINE_CALLBACKS(mlx5vf, struct mlx5vf_pci_core_device, + core_device) + /* Device specification max LOAD size */ #define MAX_LOAD_SIZE (BIT_ULL(__mlx5_bit_sz(load_vhca_state_in, size)) - 1) @@ -28,10 +31,7 @@ static struct mlx5vf_pci_core_device *mlx5vf_drvdata(struct pci_dev *pdev) { - struct vfio_pci_core_device *core_device = dev_get_drvdata(&pdev->dev); - - return container_of(core_device, struct mlx5vf_pci_core_device, - core_device); + return pci_get_drvdata(pdev); } static void mlx5vf_disable_fd(struct mlx5_vf_migration_file *migf) @@ -1415,7 +1415,7 @@ static int mlx5vf_pci_probe(struct pci_dev *pdev, if (IS_ERR(mvdev)) return PTR_ERR(mvdev); - dev_set_drvdata(&pdev->dev, &mvdev->core_device); + dev_set_drvdata(&pdev->dev, mvdev); ret = vfio_pci_core_register_device(&mvdev->core_device); if (ret) goto out_put_vdev; @@ -1443,7 +1443,7 @@ MODULE_DEVICE_TABLE(pci, mlx5vf_pci_table); static const struct pci_error_handlers mlx5vf_err_handlers = { .reset_done = mlx5vf_pci_aer_reset_done, - .error_detected = vfio_pci_core_aer_err_detected, + .error_detected = mlx5vf_aer_err_detected, }; static struct pci_driver mlx5vf_pci_driver = { @@ -1451,6 +1451,7 @@ static struct pci_driver mlx5vf_pci_driver = { .id_table = mlx5vf_pci_table, .probe = mlx5vf_pci_probe, .remove = mlx5vf_pci_remove, + .driver = { .pm = pm_ptr(&mlx5vf_pm_ops) }, .err_handler = &mlx5vf_err_handlers, .driver_managed_dma = true, }; diff --git a/drivers/vfio/pci/nvgrace-gpu/main.c b/drivers/vfio/pci/nvgrace-gpu/main.c index 208463c21808..846a1e354c26 100644 --- a/drivers/vfio/pci/nvgrace-gpu/main.c +++ b/drivers/vfio/pci/nvgrace-gpu/main.c @@ -73,6 +73,9 @@ struct nvgrace_gpu_pci_core_device { int cxl_dvsec; }; +VFIO_PCI_CORE_DEFINE_CALLBACKS(nvgrace_gpu, struct nvgrace_gpu_pci_core_device, + core_device) + static void nvgrace_gpu_init_fake_bar_emu_regs(struct vfio_device *core_vdev) { struct nvgrace_gpu_pci_core_device *nvdev = @@ -1356,7 +1359,7 @@ static int nvgrace_gpu_probe(struct pci_dev *pdev, if (ret) goto out_put_vdev; - dev_set_drvdata(&pdev->dev, &nvdev->core_device); + dev_set_drvdata(&pdev->dev, nvdev); if (ops == &nvgrace_gpu_pci_ops) { nvdev->has_mig_hw_bug = nvgrace_gpu_has_mig_hw_bug(pdev); @@ -1387,10 +1390,10 @@ static int nvgrace_gpu_probe(struct pci_dev *pdev, static void nvgrace_gpu_remove(struct pci_dev *pdev) { - struct vfio_pci_core_device *core_device = dev_get_drvdata(&pdev->dev); + struct nvgrace_gpu_pci_core_device *nvdev = pci_get_drvdata(pdev); - vfio_pci_core_unregister_device(core_device); - vfio_put_device(&core_device->vdev); + vfio_pci_core_unregister_device(&nvdev->core_device); + vfio_put_device(&nvdev->core_device.vdev); } static const struct pci_device_id nvgrace_gpu_vfio_pci_table[] = { @@ -1422,17 +1425,14 @@ MODULE_DEVICE_TABLE(pci, nvgrace_gpu_vfio_pci_table); */ static void nvgrace_gpu_vfio_pci_reset_done(struct pci_dev *pdev) { - struct vfio_pci_core_device *core_device = dev_get_drvdata(&pdev->dev); - struct nvgrace_gpu_pci_core_device *nvdev = - container_of(core_device, struct nvgrace_gpu_pci_core_device, - core_device); + struct nvgrace_gpu_pci_core_device *nvdev = pci_get_drvdata(pdev); nvdev->reset_done = true; } static const struct pci_error_handlers nvgrace_gpu_vfio_pci_err_handlers = { .reset_done = nvgrace_gpu_vfio_pci_reset_done, - .error_detected = vfio_pci_core_aer_err_detected, + .error_detected = nvgrace_gpu_aer_err_detected, }; static struct pci_driver nvgrace_gpu_vfio_pci_driver = { @@ -1440,6 +1440,7 @@ static struct pci_driver nvgrace_gpu_vfio_pci_driver = { .id_table = nvgrace_gpu_vfio_pci_table, .probe = nvgrace_gpu_probe, .remove = nvgrace_gpu_remove, + .driver = { .pm = pm_ptr(&nvgrace_gpu_pm_ops) }, .err_handler = &nvgrace_gpu_vfio_pci_err_handlers, .driver_managed_dma = true, }; diff --git a/drivers/vfio/pci/pds/pci_drv.c b/drivers/vfio/pci/pds/pci_drv.c index 4923f1823126..cf7e33d4d17b 100644 --- a/drivers/vfio/pci/pds/pci_drv.c +++ b/drivers/vfio/pci/pds/pci_drv.c @@ -16,6 +16,9 @@ #include "pci_drv.h" #include "cmds.h" +VFIO_PCI_CORE_DEFINE_CALLBACKS(pds_vfio, struct pds_vfio_pci_device, + vfio_coredev) + #define PDS_VFIO_DRV_DESCRIPTION "AMD/Pensando VFIO Device Driver" #define PCI_VENDOR_ID_PENSANDO 0x1dd8 @@ -118,7 +121,7 @@ static int pds_vfio_pci_probe(struct pci_dev *pdev, if (IS_ERR(pds_vfio)) return PTR_ERR(pds_vfio); - dev_set_drvdata(&pdev->dev, &pds_vfio->vfio_coredev); + dev_set_drvdata(&pdev->dev, pds_vfio); err = vfio_pci_core_register_device(&pds_vfio->vfio_coredev); if (err) @@ -173,7 +176,7 @@ static void pds_vfio_pci_aer_reset_done(struct pci_dev *pdev) static const struct pci_error_handlers pds_vfio_pci_err_handlers = { .reset_done = pds_vfio_pci_aer_reset_done, - .error_detected = vfio_pci_core_aer_err_detected, + .error_detected = pds_vfio_aer_err_detected, }; static struct pci_driver pds_vfio_pci_driver = { @@ -181,6 +184,7 @@ static struct pci_driver pds_vfio_pci_driver = { .id_table = pds_vfio_pci_table, .probe = pds_vfio_pci_probe, .remove = pds_vfio_pci_remove, + .driver = { .pm = pm_ptr(&pds_vfio_pm_ops) }, .err_handler = &pds_vfio_pci_err_handlers, .driver_managed_dma = true, }; diff --git a/drivers/vfio/pci/pds/vfio_dev.c b/drivers/vfio/pci/pds/vfio_dev.c index be103c74e969..6d2b2dc61a28 100644 --- a/drivers/vfio/pci/pds/vfio_dev.c +++ b/drivers/vfio/pci/pds/vfio_dev.c @@ -20,10 +20,7 @@ struct device *pds_vfio_to_dev(struct pds_vfio_pci_device *pds_vfio) struct pds_vfio_pci_device *pds_vfio_pci_drvdata(struct pci_dev *pdev) { - struct vfio_pci_core_device *core_device = dev_get_drvdata(&pdev->dev); - - return container_of(core_device, struct pds_vfio_pci_device, - vfio_coredev); + return pci_get_drvdata(pdev); } void pds_vfio_reset(struct pds_vfio_pci_device *pds_vfio, diff --git a/drivers/vfio/pci/qat/main.c b/drivers/vfio/pci/qat/main.c index 60ff907b6a67..69448fa57df4 100644 --- a/drivers/vfio/pci/qat/main.c +++ b/drivers/vfio/pci/qat/main.c @@ -55,6 +55,9 @@ struct qat_vf_core_device { struct qat_vf_migration_file *saving_migf; }; +VFIO_PCI_CORE_DEFINE_CALLBACKS(qat_vf, struct qat_vf_core_device, + core_device) + static int qat_vf_pci_open_device(struct vfio_device *core_vdev) { struct qat_vf_core_device *qat_vdev = @@ -623,9 +626,7 @@ static const struct vfio_device_ops qat_vf_pci_ops = { static struct qat_vf_core_device *qat_vf_drvdata(struct pci_dev *pdev) { - struct vfio_pci_core_device *core_device = pci_get_drvdata(pdev); - - return container_of(core_device, struct qat_vf_core_device, core_device); + return pci_get_drvdata(pdev); } static void qat_vf_pci_aer_reset_done(struct pci_dev *pdev) @@ -651,7 +652,7 @@ qat_vf_vfio_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id) if (IS_ERR(qat_vdev)) return PTR_ERR(qat_vdev); - pci_set_drvdata(pdev, &qat_vdev->core_device); + pci_set_drvdata(pdev, qat_vdev); ret = vfio_pci_core_register_device(&qat_vdev->core_device); if (ret) goto out_put_device; @@ -686,7 +687,7 @@ MODULE_DEVICE_TABLE(pci, qat_vf_vfio_pci_table); static const struct pci_error_handlers qat_vf_err_handlers = { .reset_done = qat_vf_pci_aer_reset_done, - .error_detected = vfio_pci_core_aer_err_detected, + .error_detected = qat_vf_aer_err_detected, }; static struct pci_driver qat_vf_vfio_pci_driver = { @@ -694,6 +695,7 @@ static struct pci_driver qat_vf_vfio_pci_driver = { .id_table = qat_vf_vfio_pci_table, .probe = qat_vf_vfio_pci_probe, .remove = qat_vf_vfio_pci_remove, + .driver = { .pm = pm_ptr(&qat_vf_pm_ops) }, .err_handler = &qat_vf_err_handlers, .driver_managed_dma = true, }; diff --git a/drivers/vfio/pci/vfio_pci.c b/drivers/vfio/pci/vfio_pci.c index 830369ff878d..e7c012febe91 100644 --- a/drivers/vfio/pci/vfio_pci.c +++ b/drivers/vfio/pci/vfio_pci.c @@ -223,13 +223,44 @@ static const struct pci_device_id vfio_pci_table[] = { MODULE_DEVICE_TABLE(pci, vfio_pci_table); +static int __maybe_unused vfio_pci_pm_suspend(struct device *dev) +{ + struct vfio_pci_core_device *vdev = dev_get_drvdata(dev); + + return vfio_pci_core_runtime_suspend(vdev); +} + +static int __maybe_unused vfio_pci_pm_resume(struct device *dev) +{ + struct vfio_pci_core_device *vdev = dev_get_drvdata(dev); + + return vfio_pci_core_runtime_resume(vdev); +} + +static const struct dev_pm_ops vfio_pci_pm_ops = { + SET_RUNTIME_PM_OPS(vfio_pci_pm_suspend, vfio_pci_pm_resume, NULL) +}; + +static pci_ers_result_t vfio_pci_aer_err_detected(struct pci_dev *pdev, + pci_channel_state_t state) +{ + struct vfio_pci_core_device *vdev = pci_get_drvdata(pdev); + + return vfio_pci_core_aer_err_detected(vdev); +} + +static const struct pci_error_handlers vfio_pci_err_handlers = { + .error_detected = vfio_pci_aer_err_detected, +}; + static struct pci_driver vfio_pci_driver = { .name = "vfio-pci", .id_table = vfio_pci_table, .probe = vfio_pci_probe, .remove = vfio_pci_remove, .sriov_configure = vfio_pci_sriov_configure, - .err_handler = &vfio_pci_core_err_handlers, + .err_handler = &vfio_pci_err_handlers, + .driver = { .pm = pm_ptr(&vfio_pci_pm_ops) }, .driver_managed_dma = true, }; diff --git a/drivers/vfio/pci/vfio_pci_core.c b/drivers/vfio/pci/vfio_pci_core.c index 6757054e9d87..5be06e391e5b 100644 --- a/drivers/vfio/pci/vfio_pci_core.c +++ b/drivers/vfio/pci/vfio_pci_core.c @@ -488,10 +488,8 @@ static int vfio_pci_core_pm_exit(struct vfio_pci_core_device *vdev, u32 flags, } #ifdef CONFIG_PM -static int vfio_pci_core_runtime_suspend(struct device *dev) +int vfio_pci_core_runtime_suspend(struct vfio_pci_core_device *vdev) { - struct vfio_pci_core_device *vdev = dev_get_drvdata(dev); - down_write(&vdev->memory_lock); /* * The user can move the device into D3hot state before invoking @@ -516,11 +514,10 @@ static int vfio_pci_core_runtime_suspend(struct device *dev) return 0; } +EXPORT_SYMBOL_GPL(vfio_pci_core_runtime_suspend); -static int vfio_pci_core_runtime_resume(struct device *dev) +int vfio_pci_core_runtime_resume(struct vfio_pci_core_device *vdev) { - struct vfio_pci_core_device *vdev = dev_get_drvdata(dev); - /* * Resume with a pm_wake_eventfd_ctx signals the eventfd and exit * low power mode. @@ -537,6 +534,7 @@ static int vfio_pci_core_runtime_resume(struct device *dev) return 0; } +EXPORT_SYMBOL_GPL(vfio_pci_core_runtime_resume); #endif /* CONFIG_PM */ /* @@ -576,18 +574,6 @@ static void vfio_pci_core_map_bars(struct vfio_pci_core_device *vdev) } } -/* - * The pci-driver core runtime PM routines always save the device state - * before going into suspended state. If the device is going into low power - * state with only with runtime PM ops, then no explicit handling is needed - * for the devices which have NoSoftRst-. - */ -static const struct dev_pm_ops vfio_pci_core_pm_ops = { - SET_RUNTIME_PM_OPS(vfio_pci_core_runtime_suspend, - vfio_pci_core_runtime_resume, - NULL) -}; - int vfio_pci_core_enable(struct vfio_pci_core_device *vdev) { struct pci_dev *pdev = vdev->pdev; @@ -2221,10 +2207,6 @@ int vfio_pci_core_register_device(struct vfio_pci_core_device *vdev) struct device *dev = &pdev->dev; int ret; - /* Drivers must set the vfio_pci_core_device to their drvdata */ - if (WARN_ON(vdev != dev_get_drvdata(dev))) - return -EINVAL; - /* Drivers must set a name. Required for sequestering SR-IOV VFs */ if (WARN_ON(!vdev->vdev.ops->name)) return -EINVAL; @@ -2292,7 +2274,6 @@ int vfio_pci_core_register_device(struct vfio_pci_core_device *vdev) */ vfio_pci_set_power_state(vdev, PCI_D0); - dev->driver->pm = &vfio_pci_core_pm_ops; pm_runtime_allow(dev); if (!vdev->disable_idle_d3) pm_runtime_put(dev); @@ -2333,10 +2314,8 @@ void vfio_pci_core_unregister_device(struct vfio_pci_core_device *vdev) } EXPORT_SYMBOL_GPL(vfio_pci_core_unregister_device); -pci_ers_result_t vfio_pci_core_aer_err_detected(struct pci_dev *pdev, - pci_channel_state_t state) +pci_ers_result_t vfio_pci_core_aer_err_detected(struct vfio_pci_core_device *vdev) { - struct vfio_pci_core_device *vdev = dev_get_drvdata(&pdev->dev); struct vfio_pci_eventfd *eventfd; rcu_read_lock(); @@ -2419,11 +2398,6 @@ int vfio_pci_core_sriov_configure(struct vfio_pci_core_device *vdev, } EXPORT_SYMBOL_GPL(vfio_pci_core_sriov_configure); -const struct pci_error_handlers vfio_pci_core_err_handlers = { - .error_detected = vfio_pci_core_aer_err_detected, -}; -EXPORT_SYMBOL_GPL(vfio_pci_core_err_handlers); - static bool vfio_dev_in_groups(struct vfio_device *vdev, struct vfio_pci_group_info *groups) { @@ -2675,6 +2649,7 @@ static void vfio_pci_dev_set_try_reset(struct vfio_device_set *dev_set) static void vfio_pci_core_cleanup(void) { vfio_pci_uninit_perm_bits(); + rcu_barrier(); } static int __init vfio_pci_core_init(void) diff --git a/drivers/vfio/pci/virtio/main.c b/drivers/vfio/pci/virtio/main.c index d2e5cbca13c8..123ff5193812 100644 --- a/drivers/vfio/pci/virtio/main.c +++ b/drivers/vfio/pci/virtio/main.c @@ -18,6 +18,9 @@ #include "common.h" +VFIO_PCI_CORE_DEFINE_CALLBACKS(virtiovf, struct virtiovf_pci_core_device, + core_device) + static int virtiovf_pci_open_device(struct vfio_device *core_vdev) { struct virtiovf_pci_core_device *virtvdev = container_of(core_vdev, @@ -174,7 +177,7 @@ static int virtiovf_pci_probe(struct pci_dev *pdev, if (sup_lm) virtiovf_set_migratable(virtvdev); - dev_set_drvdata(&pdev->dev, &virtvdev->core_device); + dev_set_drvdata(&pdev->dev, virtvdev); ret = vfio_pci_core_register_device(&virtvdev->core_device); if (ret) goto out; @@ -211,7 +214,7 @@ static void virtiovf_pci_aer_reset_done(struct pci_dev *pdev) static const struct pci_error_handlers virtiovf_err_handlers = { .reset_done = virtiovf_pci_aer_reset_done, - .error_detected = vfio_pci_core_aer_err_detected, + .error_detected = virtiovf_aer_err_detected, }; static struct pci_driver virtiovf_pci_driver = { @@ -219,6 +222,7 @@ static struct pci_driver virtiovf_pci_driver = { .id_table = virtiovf_pci_table, .probe = virtiovf_pci_probe, .remove = virtiovf_pci_remove, + .driver = { .pm = pm_ptr(&virtiovf_pm_ops) }, .err_handler = &virtiovf_err_handlers, .driver_managed_dma = true, }; diff --git a/drivers/vfio/pci/xe/main.c b/drivers/vfio/pci/xe/main.c index cbff5af385ef..fa6a29d8dfd2 100644 --- a/drivers/vfio/pci/xe/main.c +++ b/drivers/vfio/pci/xe/main.c @@ -38,6 +38,9 @@ struct xe_vfio_pci_core_device { struct xe_vfio_pci_migration_file *migf; }; +VFIO_PCI_CORE_DEFINE_CALLBACKS(xe_vfio, struct xe_vfio_pci_core_device, + core_device) + #define xe_vdev_to_dev(xe_vdev) (&(xe_vdev)->core_device.pdev->dev) static void xe_vfio_pci_disable_file(struct xe_vfio_pci_migration_file *migf) @@ -140,7 +143,7 @@ static void xe_vfio_pci_reset_done(struct pci_dev *pdev) static const struct pci_error_handlers xe_vfio_pci_err_handlers = { .reset_prepare = xe_vfio_pci_reset_prepare, .reset_done = xe_vfio_pci_reset_done, - .error_detected = vfio_pci_core_aer_err_detected, + .error_detected = xe_vfio_aer_err_detected, }; static int xe_vfio_pci_open_device(struct vfio_device *core_vdev) @@ -550,7 +553,7 @@ static int xe_vfio_pci_probe(struct pci_dev *pdev, const struct pci_device_id *i if (IS_ERR(xe_vdev)) return PTR_ERR(xe_vdev); - dev_set_drvdata(&pdev->dev, &xe_vdev->core_device); + dev_set_drvdata(&pdev->dev, xe_vdev); ret = vfio_pci_core_register_device(&xe_vdev->core_device); if (ret) { @@ -586,6 +589,7 @@ static struct pci_driver xe_vfio_pci_driver = { .id_table = xe_vfio_pci_table, .probe = xe_vfio_pci_probe, .remove = xe_vfio_pci_remove, + .driver = { .pm = pm_ptr(&xe_vfio_pm_ops) }, .err_handler = &xe_vfio_pci_err_handlers, .driver_managed_dma = true, }; diff --git a/drivers/vfio/platform/vfio_platform_common.c b/drivers/vfio/platform/vfio_platform_common.c index c72db5a99ebd..ab531318f170 100644 --- a/drivers/vfio/platform/vfio_platform_common.c +++ b/drivers/vfio/platform/vfio_platform_common.c @@ -591,9 +591,13 @@ int vfio_platform_mmap(struct vfio_device *core_vdev, struct vm_area_struct *vma && (vma->vm_flags & VM_READ)) return -EINVAL; - if (!(vdev->regions[index].flags & VFIO_REGION_INFO_FLAG_WRITE) - && (vma->vm_flags & VM_WRITE)) - return -EINVAL; + /* Prevent read-only region mappings from being upgraded with mprotect() */ + if (!(vdev->regions[index].flags & VFIO_REGION_INFO_FLAG_WRITE)) { + if (vma->vm_flags & VM_WRITE) + return -EINVAL; + + vm_flags_clear(vma, VM_MAYWRITE); + } vma->vm_private_data = vdev; diff --git a/drivers/vfio/vfio_main.c b/drivers/vfio/vfio_main.c index 423ead48aafe..cb3deb5a4857 100644 --- a/drivers/vfio/vfio_main.c +++ b/drivers/vfio/vfio_main.c @@ -603,13 +603,6 @@ int vfio_df_open(struct vfio_device_file *df) lockdep_assert_held(&device->dev_set->lock); - /* - * Only the group path allows the device to be opened multiple - * times. The device cdev path doesn't have a secure way for it. - */ - if (device->open_count != 0 && !df->group) - return -EINVAL; - device->open_count++; if (device->open_count == 1) { ret = vfio_df_device_first_open(df); diff --git a/drivers/vhost/vringh.c b/drivers/vhost/vringh.c index f027f669460f..12809fced608 100644 --- a/drivers/vhost/vringh.c +++ b/drivers/vhost/vringh.c @@ -1214,7 +1214,7 @@ static inline int getu16_iotlb(const struct vringh *vrh, return ret; if (vrh->use_va) { - ret = __get_user(tmp, (__virtio16 __user *)ivec.iov.iovec[0].iov_base); + ret = get_user(tmp, (__virtio16 __user *)ivec.iov.iovec[0].iov_base); if (ret) return ret; } else { @@ -1252,7 +1252,7 @@ static inline int putu16_iotlb(const struct vringh *vrh, tmp = cpu_to_vringh16(vrh, val); if (vrh->use_va) { - ret = __put_user(tmp, (__virtio16 __user *)ivec.iov.iovec[0].iov_base); + ret = put_user(tmp, (__virtio16 __user *)ivec.iov.iovec[0].iov_base); if (ret) return ret; } else { diff --git a/drivers/video/fbdev/atafb.c b/drivers/video/fbdev/atafb.c index c3011b61a94b..c32576cb1720 100644 --- a/drivers/video/fbdev/atafb.c +++ b/drivers/video/fbdev/atafb.c @@ -1089,7 +1089,7 @@ static int falcon_decode_var(struct fb_info *info, struct fb_var_screeninfo *var /* Choose largest pixelclock <= wanted clock */ int i; unsigned long pcl = ULONG_MAX; - pclock = 0; + pclock = NULL; for (i = 1; i <= 4; i *= 2) { if (f25.t * i >= var->pixclock && f25.t * i < pcl) { @@ -2454,7 +2454,7 @@ static void svblit_fillrect(struct fb_info *info, ((u32 *)info->pseudo_palette)[rect->color] : rect->color; /* draw the first line with the CPU ... */ - line = (u8 *)info->screen_base + rect->dy * pitch + + line = info->screen_buffer + rect->dy * pitch + rect->dx * bytespp; switch (bytespp) { case 1: @@ -2818,29 +2818,6 @@ static void atafb_imageblit(struct fb_info *info, const struct fb_image *image) } } -static int -atafb_ioctl(struct fb_info *info, unsigned int cmd, unsigned long arg) -{ - switch (cmd) { -#ifdef FBCMD_GET_CURRENTPAR - case FBCMD_GET_CURRENTPAR: - if (copy_to_user((void *)arg, ¤t_par, - sizeof(struct atafb_par))) - return -EFAULT; - return 0; -#endif -#ifdef FBCMD_SET_CURRENTPAR - case FBCMD_SET_CURRENTPAR: - if (copy_from_user(¤t_par, (void *)arg, - sizeof(struct atafb_par))) - return -EFAULT; - ata_set_par(¤t_par); - return 0; -#endif - } - return -EINVAL; -} - /* (un)blank/poweroff * 0 = unblank * 1 = blank @@ -2922,7 +2899,6 @@ static struct fb_ops atafb_ops = { .fb_fillrect = atafb_fillrect, .fb_copyarea = atafb_copyarea, .fb_imageblit = atafb_imageblit, - .fb_ioctl = atafb_ioctl, __FB_DEFAULT_IOMEM_OPS_MMAP, }; diff --git a/drivers/video/fbdev/gxt4500.c b/drivers/video/fbdev/gxt4500.c index 1ee0a1efa18e..906b8a0dea77 100644 --- a/drivers/video/fbdev/gxt4500.c +++ b/drivers/video/fbdev/gxt4500.c @@ -719,6 +719,7 @@ static int gxt4500_probe(struct pci_dev *pdev, const struct pci_device_id *ent) err_free_cmap: fb_dealloc_cmap(&info->cmap); err_unmap_all: + arch_phys_wc_del(par->wc_cookie); iounmap(info->screen_base); err_unmap_regs: iounmap(par->regs); diff --git a/drivers/virtio/virtio.c b/drivers/virtio/virtio.c index b6c9e927bef5..a8588d7ad109 100644 --- a/drivers/virtio/virtio.c +++ b/drivers/virtio/virtio.c @@ -264,6 +264,8 @@ void virtio_reset_device(struct virtio_device *dev) #endif dev->config->reset(dev); + /* Flush pending VQ/configuration callbacks. */ + virtio_synchronize_cbs(dev); } EXPORT_SYMBOL_GPL(virtio_reset_device); diff --git a/drivers/virtio/virtio_pci_modern.c b/drivers/virtio/virtio_pci_modern.c index 6d8ae2a6a8ca..b4249afd7f58 100644 --- a/drivers/virtio/virtio_pci_modern.c +++ b/drivers/virtio/virtio_pci_modern.c @@ -364,6 +364,12 @@ static void vp_modern_avq_cleanup(struct virtio_device *vdev) } } +static void vp_modern_del_vqs(struct virtio_device *vdev) +{ + vp_modern_avq_cleanup(vdev); + vp_del_vqs(vdev); +} + static void vp_transport_features(struct virtio_device *vdev, u64 features) { struct virtio_pci_device *vp_dev = to_vp_device(vdev); @@ -558,8 +564,6 @@ static void vp_reset(struct virtio_device *vdev) while (vp_modern_get_status(mdev)) msleep(1); - vp_modern_avq_cleanup(vdev); - /* Flush pending VQ/configuration callbacks. */ vp_synchronize_vectors(vdev); } @@ -1232,7 +1236,7 @@ static const struct virtio_config_ops virtio_pci_config_nodev_ops = { .set_status = vp_set_status, .reset = vp_reset, .find_vqs = vp_modern_find_vqs, - .del_vqs = vp_del_vqs, + .del_vqs = vp_modern_del_vqs, .synchronize_cbs = vp_synchronize_vectors, .get_extended_features = vp_get_features, .finalize_features = vp_finalize_features, @@ -1252,7 +1256,7 @@ static const struct virtio_config_ops virtio_pci_config_ops = { .set_status = vp_set_status, .reset = vp_reset, .find_vqs = vp_modern_find_vqs, - .del_vqs = vp_del_vqs, + .del_vqs = vp_modern_del_vqs, .synchronize_cbs = vp_synchronize_vectors, .get_extended_features = vp_get_features, .finalize_features = vp_finalize_features, diff --git a/fs/btrfs/accessors.c b/fs/btrfs/accessors.c index 1248aa2535d3..d63ac6eb92de 100644 --- a/fs/btrfs/accessors.c +++ b/fs/btrfs/accessors.c @@ -16,7 +16,7 @@ static void __cold report_setget_bounds(const struct extent_buffer *eb, btrfs_warn(eb->fs_info, "bad eb member %s: ptr 0x%lx start %llu member offset %lu size %d", - (member_offset > eb->len ? "start" : "end"), + (member_offset >= eb->len ? "start" : "end"), (unsigned long)ptr, eb->start, member_offset, size); } diff --git a/fs/btrfs/bio.c b/fs/btrfs/bio.c index cc0bd03048ba..19b4855969f5 100644 --- a/fs/btrfs/bio.c +++ b/fs/btrfs/bio.c @@ -180,30 +180,13 @@ static void btrfs_end_repair_bio(struct btrfs_bio *repair_bbio, struct btrfs_failed_bio *fbio = repair_bbio->private; struct btrfs_inode *inode = repair_bbio->inode; struct btrfs_fs_info *fs_info = inode->root->fs_info; - /* - * We can not move forward the saved_iter, as it will be later - * utilized by repair_bbio again. - */ - struct bvec_iter saved_iter = repair_bbio->saved_iter; - const u32 step = min(fs_info->sectorsize, PAGE_SIZE); - const u64 logical = repair_bbio->saved_iter.bi_sector << SECTOR_SHIFT; - const u32 nr_steps = repair_bbio->saved_iter.bi_size / step; int mirror = repair_bbio->mirror_num; - phys_addr_t paddrs[BTRFS_MAX_BLOCKSIZE / PAGE_SIZE]; - phys_addr_t paddr; - unsigned int slot = 0; - /* Repair bbio should be eaxctly one block sized. */ + /* Repair bbio should be exactly one block sized. */ ASSERT(repair_bbio->saved_iter.bi_size == fs_info->sectorsize); - btrfs_bio_for_each_block(paddr, &repair_bbio->bio, &saved_iter, step) { - ASSERT(slot < nr_steps); - paddrs[slot] = paddr; - slot++; - } - if (repair_bbio->bio.bi_status || - !btrfs_data_csum_ok(repair_bbio, dev, 0, paddrs)) { + !btrfs_bio_data_csum_ok(repair_bbio, &repair_bbio->saved_iter, dev)) { bio_reset(&repair_bbio->bio, NULL, REQ_OP_READ); repair_bbio->bio.bi_iter = repair_bbio->saved_iter; @@ -220,9 +203,8 @@ static void btrfs_end_repair_bio(struct btrfs_bio *repair_bbio, do { mirror = prev_repair_mirror(fbio, mirror); - btrfs_repair_io_failure(fs_info, btrfs_ino(inode), - repair_bbio->file_offset, fs_info->sectorsize, - logical, paddrs, step, mirror); + btrfs_repair_bbio_failure(repair_bbio, &repair_bbio->saved_iter, + fs_info->sectorsize, mirror); } while (mirror != fbio->bbio->mirror_num); done: @@ -238,25 +220,21 @@ static void btrfs_end_repair_bio(struct btrfs_bio *repair_bbio, * read succeeded to restore the redundancy. */ static struct btrfs_failed_bio *repair_one_sector(struct btrfs_bio *failed_bbio, - u32 bio_offset, - phys_addr_t paddrs[], + const struct bvec_iter *orig_iter, struct btrfs_failed_bio *fbio) { struct btrfs_inode *inode = failed_bbio->inode; struct btrfs_fs_info *fs_info = inode->root->fs_info; - const u32 sectorsize = fs_info->sectorsize; - const u32 step = min(fs_info->sectorsize, PAGE_SIZE); - const u32 nr_steps = sectorsize / step; - /* - * For bs > ps cases, the saved_iter can be partially moved forward. - * In that case we should round it down to the block boundary. - */ - const u64 logical = round_down(failed_bbio->saved_iter.bi_sector << SECTOR_SHIFT, - sectorsize); struct btrfs_bio *repair_bbio; struct bio *repair_bio; + struct bvec_iter iter = *orig_iter; + const u32 sectorsize = fs_info->sectorsize; + const u32 bio_offset = ((iter.bi_sector - failed_bbio->saved_iter.bi_sector) << + SECTOR_SHIFT); + const u64 logical = (iter.bi_sector << SECTOR_SHIFT); int num_copies; int mirror; + u32 cur = 0; btrfs_debug(fs_info, "repair read error: read error at %llu", failed_bbio->file_offset + bio_offset); @@ -277,17 +255,21 @@ static struct btrfs_failed_bio *repair_one_sector(struct btrfs_bio *failed_bbio, atomic_inc(&fbio->repair_count); - repair_bio = bio_alloc_bioset(NULL, nr_steps, REQ_OP_READ, GFP_NOFS, - &btrfs_repair_bioset); + repair_bio = bio_alloc_bioset(NULL, max(1, sectorsize >> PAGE_SHIFT), + REQ_OP_READ, GFP_NOFS, &btrfs_repair_bioset); repair_bio->bi_iter.bi_sector = logical >> SECTOR_SHIFT; - for (int i = 0; i < nr_steps; i++) { + while (cur < sectorsize) { + struct page *page = bio_iter_page(&failed_bbio->bio, iter); + const u32 pg_off = bio_iter_offset(&failed_bbio->bio, iter); + const u32 cur_len = min(bio_iter_len(&failed_bbio->bio, iter), + sectorsize - cur); int ret; - ASSERT(offset_in_page(paddrs[i]) + step <= PAGE_SIZE); + ret = bio_add_page(repair_bio, page, cur_len, pg_off); + ASSERT(ret == cur_len); - ret = bio_add_page(repair_bio, phys_to_page(paddrs[i]), step, - offset_in_page(paddrs[i])); - ASSERT(ret == step); + bio_advance_iter_single(&failed_bbio->bio, &iter, cur_len); + cur += cur_len; } repair_bbio = btrfs_bio(repair_bio); @@ -305,18 +287,16 @@ static void btrfs_check_read_bio(struct btrfs_bio *bbio, struct btrfs_device *de struct btrfs_inode *inode = bbio->inode; struct btrfs_fs_info *fs_info = inode->root->fs_info; const u32 sectorsize = fs_info->sectorsize; - const u32 step = min(sectorsize, PAGE_SIZE); - const u32 nr_steps = sectorsize / step; - struct bvec_iter *iter = &bbio->saved_iter; + struct bvec_iter iter; blk_status_t status = bbio->bio.bi_status; struct btrfs_failed_bio *fbio = NULL; - phys_addr_t paddrs[BTRFS_MAX_BLOCKSIZE / PAGE_SIZE]; - phys_addr_t paddr; - u32 offset = 0; /* Read-repair requires the inode field to be set by the submitter. */ ASSERT(inode); + /* The original bbio should be sectorsize aligned. */ + ASSERT(IS_ALIGNED(bbio->saved_iter.bi_size, sectorsize)); + /* * Hand off repair bios to the repair code as there is no upper level * submitter for them. @@ -329,16 +309,10 @@ static void btrfs_check_read_bio(struct btrfs_bio *bbio, struct btrfs_device *de /* Clear the I/O error. A failed repair will reset it. */ bbio->bio.bi_status = BLK_STS_OK; - btrfs_bio_for_each_block(paddr, &bbio->bio, iter, step) { - paddrs[(offset / step) % nr_steps] = paddr; - offset += step; - - if (IS_ALIGNED(offset, sectorsize)) { - if (status || - !btrfs_data_csum_ok(bbio, dev, offset - sectorsize, paddrs)) - fbio = repair_one_sector(bbio, offset - sectorsize, - paddrs, fbio); - } + for (iter = bbio->saved_iter; iter.bi_size; + bio_advance_iter(&bbio->bio, &iter, sectorsize)) { + if (status || !btrfs_bio_data_csum_ok(bbio, &iter, dev)) + fbio = repair_one_sector(bbio, &iter, fbio); } if (bbio->csum != bbio->csum_inline) kvfree(bbio->csum); @@ -925,21 +899,23 @@ void btrfs_submit_bbio(struct btrfs_bio *bbio, int mirror_num) * The I/O is issued synchronously to block the repair read completion from * freeing the bio. * - * @ino: Offending inode number - * @fileoff: File offset inside the inode + * @bbio: Original bbio where the repair is needed + * @orig_iter: Points to where the repair starts * @length: Length of the repair write - * @logical: Logical address of the range - * @paddrs: Physical address array of the content - * @step: Length of for each paddrs * @mirror_num: Mirror number to write to. Must not be zero */ -int btrfs_repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 fileoff, - u32 length, u64 logical, const phys_addr_t paddrs[], - unsigned int step, int mirror_num) +int btrfs_repair_bbio_failure(struct btrfs_bio *bbio, const struct bvec_iter *orig_iter, + u32 length, int mirror_num) { - const u32 nr_steps = DIV_ROUND_UP_POW2(length, step); + struct btrfs_inode *inode = bbio->inode; + struct btrfs_fs_info *fs_info = inode->root->fs_info; struct btrfs_io_stripe smap = { 0 }; - struct bio *bio = NULL; + struct bvec_iter iter = *orig_iter; + struct bio *repair_bio = NULL; + const u64 logical = iter.bi_sector << SECTOR_SHIFT; + const u64 fileoff = bbio->file_offset + + ((iter.bi_sector - bbio->saved_iter.bi_sector) << SECTOR_SHIFT); + u32 cur = 0; int ret = 0; BUG_ON(!mirror_num); @@ -950,8 +926,9 @@ int btrfs_repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 fileoff, ASSERT(IS_ALIGNED(fileoff, fs_info->sectorsize)); /* Either it's a single data or metadata block. */ ASSERT(length <= BTRFS_MAX_BLOCKSIZE); - ASSERT(step <= length); - ASSERT(is_power_of_2(step)); + + /* Our current iter should not be before the original bbio saved_iter. */ + ASSERT(iter.bi_sector >= bbio->saved_iter.bi_sector); /* * The fs either mounted RO or hit critical errors, no need @@ -979,15 +956,22 @@ int btrfs_repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 fileoff, goto out_counter_dec; } - bio = bio_alloc(smap.dev->bdev, nr_steps, REQ_OP_WRITE | REQ_SYNC, GFP_NOFS); - bio->bi_iter.bi_sector = smap.physical >> SECTOR_SHIFT; - for (int i = 0; i < nr_steps; i++) { - ret = bio_add_page(bio, phys_to_page(paddrs[i]), step, offset_in_page(paddrs[i])); - /* We should have allocated enough slots to contain all the different pages. */ - ASSERT(ret == step); + repair_bio = bio_alloc(smap.dev->bdev, max(1, length >> PAGE_SHIFT), + REQ_OP_WRITE | REQ_SYNC, GFP_NOFS); + repair_bio->bi_iter.bi_sector = smap.physical >> SECTOR_SHIFT; + while (cur < length) { + struct page *page = bio_iter_page(&bbio->bio, iter); + const u32 pg_off = bio_iter_offset(&bbio->bio, iter); + const u32 cur_len = min(bio_iter_len(&bbio->bio, iter), length - cur); + + ret = bio_add_page(repair_bio, page, cur_len, pg_off); + ASSERT(ret == cur_len); + bio_advance_iter_single(&bbio->bio, &iter, cur_len); + cur += cur_len; } - ret = submit_bio_wait(bio); - bio_put(bio); + + ret = submit_bio_wait(repair_bio); + bio_put(repair_bio); if (ret) { /* try to remap that extent elsewhere? */ btrfs_dev_stat_inc_and_print(smap.dev, BTRFS_DEV_STAT_WRITE_ERRS); @@ -995,8 +979,9 @@ int btrfs_repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 fileoff, } btrfs_info_rl(fs_info, - "read error corrected: ino %llu off %llu (dev %s sector %llu)", - ino, fileoff, btrfs_dev_name(smap.dev), + "read error corrected: root %llu ino %llu off %llu (dev %s sector %llu)", + btrfs_root_id(inode->root), btrfs_ino(inode), fileoff, + btrfs_dev_name(smap.dev), smap.physical >> SECTOR_SHIFT); ret = 0; diff --git a/fs/btrfs/bio.h b/fs/btrfs/bio.h index 303ed6c7103d..b7bd377a0162 100644 --- a/fs/btrfs/bio.h +++ b/fs/btrfs/bio.h @@ -126,8 +126,7 @@ void btrfs_bio_end_io(struct btrfs_bio *bbio, blk_status_t status); void btrfs_submit_bbio(struct btrfs_bio *bbio, int mirror_num); void btrfs_submit_repair_write(struct btrfs_bio *bbio, int mirror_num, bool dev_replace); -int btrfs_repair_io_failure(struct btrfs_fs_info *fs_info, u64 ino, u64 fileoff, - u32 length, u64 logical, const phys_addr_t paddrs[], - unsigned int step, int mirror_num); +int btrfs_repair_bbio_failure(struct btrfs_bio *bbio, const struct bvec_iter *orig_iter, + u32 length, int mirror_num); #endif diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c index ee182369254c..483a30925575 100644 --- a/fs/btrfs/block-group.c +++ b/fs/btrfs/block-group.c @@ -1397,12 +1397,14 @@ struct btrfs_trans_handle *btrfs_start_trans_remove_block_group( ASSERT(map->start == chunk_offset); /* - * We need to reserve 3 + N units from the metadata space info in order + * We need to reserve 4 + N units from the metadata space info in order * to remove a block group (done at btrfs_remove_chunk() and at * btrfs_remove_block_group()), which are used for: * * 1 unit for adding the free space inode's orphan (located in the tree * of tree roots). + * 1 unit for updating the free space inode's item (located in the tree + * of tree roots). * 1 unit for deleting the block group item (located in the extent * tree). * 1 unit for deleting the free space item (located in tree of tree @@ -1415,7 +1417,7 @@ struct btrfs_trans_handle *btrfs_start_trans_remove_block_group( * more device items and remove one chunk item), but this is done at * btrfs_remove_chunk() through a call to check_system_chunk(). */ - num_items = 3 + map->num_stripes; + num_items = 4 + map->num_stripes; btrfs_free_chunk_map(map); return btrfs_start_transaction_fallback_global_rsv(root, num_items); diff --git a/fs/btrfs/btrfs_inode.h b/fs/btrfs/btrfs_inode.h index 1082fa92c145..89e5e9c0c904 100644 --- a/fs/btrfs/btrfs_inode.h +++ b/fs/btrfs/btrfs_inode.h @@ -507,14 +507,10 @@ static inline void btrfs_set_inode_mapping_order(struct btrfs_inode *inode) inode->root->fs_info->block_max_order); } -void btrfs_calculate_block_csum_folio(struct btrfs_fs_info *fs_info, - const phys_addr_t paddr, u8 *dest); -void btrfs_calculate_block_csum_pages(struct btrfs_fs_info *fs_info, - const phys_addr_t paddrs[], u8 *dest); -int btrfs_check_block_csum(struct btrfs_fs_info *fs_info, phys_addr_t paddr, u8 *csum, - const u8 * const csum_expected); -bool btrfs_data_csum_ok(struct btrfs_bio *bbio, struct btrfs_device *dev, - u32 bio_offset, const phys_addr_t paddrs[]); +bool btrfs_bio_data_csum_ok(struct btrfs_bio *bbio, const struct bvec_iter *orig_iter, + struct btrfs_device *dev); +void btrfs_csum_one_bio_block(struct btrfs_fs_info *fs_info, struct bio *bio, + const struct bvec_iter *orig_iter, u8 *csum); noinline int can_nocow_extent(struct btrfs_inode *inode, u64 offset, u64 *len, struct btrfs_file_extent *file_extent, bool nowait); diff --git a/fs/btrfs/ctree.h b/fs/btrfs/ctree.h index 22ba2b4505b3..00d4c4184e76 100644 --- a/fs/btrfs/ctree.h +++ b/fs/btrfs/ctree.h @@ -160,7 +160,7 @@ enum { */ struct btrfs_qgroup_swapped_blocks { spinlock_t lock; - /* RM_EMPTY_ROOT() of above blocks[] */ + /* True if any of the rbtrees in the blocks array below is not empty. */ bool swapped; struct rb_root blocks[BTRFS_MAX_LEVEL]; }; diff --git a/fs/btrfs/defrag.c b/fs/btrfs/defrag.c index 6ec5dd760d42..70f1d7d78c43 100644 --- a/fs/btrfs/defrag.c +++ b/fs/btrfs/defrag.c @@ -815,7 +815,7 @@ static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em, * If the next extent is at its max capacity, defragging current extent * makes no sense, as the total number of extents won't change. */ - if (next->len >= get_extent_max_capacity(fs_info, em)) + if (next->len >= get_extent_max_capacity(fs_info, next)) goto out; /* Skip older extent */ if (next->generation < newer_than) diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c index dc7ad92876c0..b25028ba74f6 100644 --- a/fs/btrfs/disk-io.c +++ b/fs/btrfs/disk-io.c @@ -176,19 +176,24 @@ static int btrfs_repair_eb_io_failure(const struct extent_buffer *eb, int mirror_num) { struct btrfs_fs_info *fs_info = eb->fs_info; - const u32 step = min(fs_info->nodesize, PAGE_SIZE); - const u32 nr_steps = eb->len / step; - phys_addr_t paddrs[BTRFS_MAX_BLOCKSIZE / PAGE_SIZE]; + struct btrfs_bio *bbio; + int ret; if (sb_rdonly(fs_info->sb)) return -EROFS; + /* + * This bbio is only to queue all pages for btrfs_repair_bbio_failure(). + * Thus it will never get its endio called. + */ + bbio = btrfs_bio_alloc(max(1, fs_info->nodesize >> PAGE_SHIFT), REQ_OP_READ, + BTRFS_I(fs_info->btree_inode), eb->start, NULL, NULL); + bbio->bio.bi_iter.bi_sector = eb->start >> SECTOR_SHIFT; for (int i = 0; i < num_extent_pages(eb); i++) { struct folio *folio = eb->folios[i]; /* No large folio support yet. */ ASSERT(folio_order(folio) == 0); - ASSERT(i < nr_steps); /* * For nodesize < page size, there is just one paddr, with some @@ -197,11 +202,17 @@ static int btrfs_repair_eb_io_failure(const struct extent_buffer *eb, * For nodesize >= page size, it's one or more paddrs, and eb->start * must be aligned to page boundary. */ - paddrs[i] = page_to_phys(&folio->page) + offset_in_page(eb->start); + ret = bio_add_page(&bbio->bio, &folio->page, min(PAGE_SIZE, fs_info->nodesize), + offset_in_page(eb->start)); + ASSERT(ret == min(PAGE_SIZE, fs_info->nodesize)); } + /* Since the bbio is never submitted, we have to save the iter manually. */ + bbio->saved_iter = bbio->bio.bi_iter; - return btrfs_repair_io_failure(fs_info, 0, eb->start, eb->len, - eb->start, paddrs, step, mirror_num); + ret = btrfs_repair_bbio_failure(bbio, &bbio->saved_iter, fs_info->nodesize, + mirror_num); + bio_put(&bbio->bio); + return ret; } /* @@ -3898,8 +3909,7 @@ static int write_dev_supers(struct btrfs_device *device, atomic_inc(&device->sb_write_errors); continue; } - if (bytenr + BTRFS_SUPER_INFO_SIZE >= - device->commit_total_bytes) + if (bytenr + BTRFS_SUPER_INFO_SIZE > device->commit_total_bytes) break; btrfs_set_super_bytenr(sb, bytenr_orig); @@ -3977,8 +3987,7 @@ static int wait_dev_supers(struct btrfs_device *device, int max_mirrors) primary_failed = true; continue; } - if (bytenr + BTRFS_SUPER_INFO_SIZE >= - device->commit_total_bytes) + if (bytenr + BTRFS_SUPER_INFO_SIZE > device->commit_total_bytes) break; folio = filemap_get_folio(device->bdev->bd_mapping, diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c index d6a4390ee34a..aa423c690af2 100644 --- a/fs/btrfs/extent-tree.c +++ b/fs/btrfs/extent-tree.c @@ -5227,7 +5227,8 @@ int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans, offset, ins, 1, root_objectid); if (ret) btrfs_pin_extent(trans, ins->objectid, ins->offset); - ret = btrfs_record_squota_delta(fs_info, &delta); + else + ret = btrfs_record_squota_delta(fs_info, &delta); btrfs_put_block_group(block_group); return ret; } diff --git a/fs/btrfs/file-item.c b/fs/btrfs/file-item.c index cf50fd623f41..581ca5653be9 100644 --- a/fs/btrfs/file-item.c +++ b/fs/btrfs/file-item.c @@ -801,25 +801,16 @@ static void csum_one_bio(struct btrfs_bio *bbio, struct bvec_iter *src) { struct btrfs_inode *inode = bbio->inode; struct btrfs_fs_info *fs_info = inode->root->fs_info; - struct bio *bio = &bbio->bio; struct btrfs_ordered_sum *sums = bbio->sums; - struct bvec_iter iter = *src; - phys_addr_t paddr; + struct bvec_iter iter; const u32 blocksize = fs_info->sectorsize; - const u32 step = min(blocksize, PAGE_SIZE); - const u32 nr_steps = blocksize / step; - phys_addr_t paddrs[BTRFS_MAX_BLOCKSIZE / PAGE_SIZE]; - u32 offset = 0; int index = 0; - btrfs_bio_for_each_block(paddr, bio, &iter, step) { - paddrs[(offset / step) % nr_steps] = paddr; - offset += step; + for (iter = *src; iter.bi_size; bio_advance_iter(&bbio->bio, &iter, blocksize)) { + btrfs_csum_one_bio_block(fs_info, &bbio->bio, &iter, + sums->sums + index); - if (IS_ALIGNED(offset, blocksize)) { - btrfs_calculate_block_csum_pages(fs_info, paddrs, sums->sums + index); - index += fs_info->csum_size; - } + index += fs_info->csum_size; } } diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c index e2af75a205ea..4572b3d64210 100644 --- a/fs/btrfs/free-space-cache.c +++ b/fs/btrfs/free-space-cache.c @@ -266,6 +266,16 @@ int btrfs_remove_free_space_inode(struct btrfs_trans_handle *trans, return ret; } clear_nlink(inode); + /* + * Persist the zero link count, so that if the delayed iput below + * doesn't get to evict the inode, the orphan cleanup on the next mount + * evicts it instead of only deleting the orphan item. + */ + ret = btrfs_update_inode(trans, BTRFS_I(inode)); + if (ret) { + btrfs_add_delayed_iput(BTRFS_I(inode)); + return ret; + } /* One for the block groups ref */ spin_lock(&block_group->lock); if (test_and_clear_bit(BLOCK_GROUP_FLAG_IREF, &block_group->runtime_flags)) { diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c index aa1201fe4d7f..019e25f34416 100644 --- a/fs/btrfs/inode.c +++ b/fs/btrfs/inode.c @@ -3387,6 +3387,8 @@ int btrfs_finish_one_ordered(struct btrfs_ordered_extent *ordered_extent) /* * Drop extent maps for the part of the extent we didn't write. + * On error the written part is freed below as well, so drop + * its maps too. * * We have an exception here for the free_space_inode, this is * because when we do btrfs_get_extent() on the free space inode @@ -3402,7 +3404,7 @@ int btrfs_finish_one_ordered(struct btrfs_ordered_extent *ordered_extent) if (!btrfs_is_free_space_inode(inode)) { u64 unwritten_start = start; - if (truncated) + if (truncated && !ret) unwritten_start += logical_len; btrfs_drop_extent_map_range(inode, unwritten_start, @@ -3471,79 +3473,30 @@ int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered) return btrfs_finish_one_ordered(ordered); } -/* - * Calculate the checksum of an fs block at physical memory address @paddr, - * and save the result to @dest. - * - * The folio containing @paddr must be large enough to contain a full fs block. - */ -void btrfs_calculate_block_csum_folio(struct btrfs_fs_info *fs_info, - const phys_addr_t paddr, u8 *dest) -{ - struct folio *folio = page_folio(phys_to_page(paddr)); - const u32 blocksize = fs_info->sectorsize; - const u32 step = min(blocksize, PAGE_SIZE); - const u32 nr_steps = blocksize / step; - phys_addr_t paddrs[BTRFS_MAX_BLOCKSIZE / PAGE_SIZE]; - - /* The full block must be inside the folio. */ - ASSERT(offset_in_folio(folio, paddr) + blocksize <= folio_size(folio)); - - for (int i = 0; i < nr_steps; i++) { - u32 pindex = offset_in_folio(folio, paddr + i * step) >> PAGE_SHIFT; - - /* - * For bs <= ps cases, we will only run the loop once, so the offset - * inside the page will only added to paddrs[0]. - * - * For bs > ps cases, the block must be page aligned, thus offset - * inside the page will always be 0. - */ - paddrs[i] = page_to_phys(folio_page(folio, pindex)) + offset_in_page(paddr); - } - return btrfs_calculate_block_csum_pages(fs_info, paddrs, dest); -} - -/* - * Calculate the checksum of a fs block backed by multiple noncontiguous pages - * at @paddrs[] and save the result to @dest. - * - * The folio containing @paddr must be large enough to contain a full fs block. - */ -void btrfs_calculate_block_csum_pages(struct btrfs_fs_info *fs_info, - const phys_addr_t paddrs[], u8 *dest) +/* Generate data checksum for a single fs block, pointed to by @orig_iter. */ +void btrfs_csum_one_bio_block(struct btrfs_fs_info *fs_info, struct bio *bio, + const struct bvec_iter *orig_iter, u8 *csum) { + struct btrfs_csum_ctx cctx; + struct bvec_iter iter = *orig_iter; const u32 blocksize = fs_info->sectorsize; - const u32 step = min(blocksize, PAGE_SIZE); - const u32 nr_steps = blocksize / step; - struct btrfs_csum_ctx csum; + u32 cur = 0; - btrfs_csum_init(&csum, fs_info->csum_type); - for (int i = 0; i < nr_steps; i++) { - const phys_addr_t paddr = paddrs[i]; + btrfs_csum_init(&cctx, fs_info->csum_type); + while (cur < blocksize) { + struct page *page = bio_iter_page(bio, iter); + const u32 pg_off = bio_iter_offset(bio, iter); + const u32 cur_len = min(bio_iter_len(bio, iter), blocksize - cur); void *kaddr; - ASSERT(offset_in_page(paddr) + step <= PAGE_SIZE); - kaddr = kmap_local_page(phys_to_page(paddr)) + offset_in_page(paddr); - btrfs_csum_update(&csum, kaddr, step); + kaddr = kmap_local_page(page) + pg_off; + btrfs_csum_update(&cctx, kaddr, cur_len); kunmap_local(kaddr); - } - btrfs_csum_final(&csum, dest); -} -/* - * Verify the checksum for a single sector without any extra action that depend - * on the type of I/O. - * - * @kaddr must be a properly kmapped address. - */ -int btrfs_check_block_csum(struct btrfs_fs_info *fs_info, phys_addr_t paddr, u8 *csum, - const u8 * const csum_expected) -{ - btrfs_calculate_block_csum_folio(fs_info, paddr, csum); - if (unlikely(memcmp(csum, csum_expected, fs_info->csum_size) != 0)) - return -EIO; - return 0; + bio_advance_iter_single(bio, &iter, cur_len); + cur += cur_len; + } + btrfs_csum_final(&cctx, csum); } /* @@ -3551,27 +3504,30 @@ int btrfs_check_block_csum(struct btrfs_fs_info *fs_info, phys_addr_t paddr, u8 * different noncontiguous pages. * * @bbio: btrfs_io_bio which contains the csum - * @dev: device the sector is on - * @bio_offset: offset to the beginning of the bio (in bytes) - * @paddrs: physical addresses which back the fs block + * @orig_iter: bvec iter pointing to the start of the block + * @dev: device the sector is on (optional) * * Check if the checksum on a data block is valid. When a checksum mismatch is * detected, report the error and fill the corrupted range with zero. * * Return %true if the sector is ok or had no checksum to start with, else %false. */ -bool btrfs_data_csum_ok(struct btrfs_bio *bbio, struct btrfs_device *dev, - u32 bio_offset, const phys_addr_t paddrs[]) +bool btrfs_bio_data_csum_ok(struct btrfs_bio *bbio, + const struct bvec_iter *orig_iter, + struct btrfs_device *dev) { struct btrfs_inode *inode = bbio->inode; struct btrfs_fs_info *fs_info = inode->root->fs_info; + struct bvec_iter iter = *orig_iter; const u32 blocksize = fs_info->sectorsize; - const u32 step = min(blocksize, PAGE_SIZE); - const u32 nr_steps = blocksize / step; + const u32 bio_offset = (iter.bi_sector - bbio->saved_iter.bi_sector) << SECTOR_SHIFT; u64 file_offset = bbio->file_offset + bio_offset; u64 end = file_offset + blocksize - 1; u8 *csum_expected; u8 csum[BTRFS_CSUM_SIZE]; + u32 cur = 0; + + ASSERT(iter.bi_sector >= bbio->saved_iter.bi_sector); if (!bbio->csum) return true; @@ -3587,7 +3543,7 @@ bool btrfs_data_csum_ok(struct btrfs_bio *bbio, struct btrfs_device *dev, csum_expected = bbio->csum + (bio_offset >> fs_info->sectorsize_bits) * fs_info->csum_size; - btrfs_calculate_block_csum_pages(fs_info, paddrs, csum); + btrfs_csum_one_bio_block(fs_info, &bbio->bio, orig_iter, csum); if (unlikely(memcmp(csum, csum_expected, fs_info->csum_size) != 0)) goto zeroit; return true; @@ -3597,8 +3553,16 @@ bool btrfs_data_csum_ok(struct btrfs_bio *bbio, struct btrfs_device *dev, bbio->mirror_num); if (dev) btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS); - for (int i = 0; i < nr_steps; i++) - memzero_page(phys_to_page(paddrs[i]), offset_in_page(paddrs[i]), step); + while (cur < blocksize) { + struct page *page = bio_iter_page(&bbio->bio, iter); + const u32 pg_off = bio_iter_offset(&bbio->bio, iter); + const u32 cur_len = min(bio_iter_len(&bbio->bio, iter), blocksize - cur); + + memzero_page(page, pg_off, cur_len); + + bio_advance_iter_single(&bbio->bio, &iter, cur_len); + cur += cur_len; + } return false; } diff --git a/fs/btrfs/messages.c b/fs/btrfs/messages.c index 198d1747c80a..5fe5d34ab629 100644 --- a/fs/btrfs/messages.c +++ b/fs/btrfs/messages.c @@ -13,6 +13,8 @@ /* * Characters to print to indicate error conditions or uncommon filesystem state. * RO is not an error. + * Don't use 'E' because that's used to signal that there's an error stored in + * fs_info->fs_error (see btrfs_state_to_string() below). */ static const char fs_state_chars[] = { [BTRFS_FS_STATE_REMOUNTING] = 'M', @@ -24,7 +26,7 @@ static const char fs_state_chars[] = { [BTRFS_FS_STATE_NO_DATA_CSUMS] = 'C', [BTRFS_FS_STATE_SKIP_META_CSUMS] = 'S', [BTRFS_FS_STATE_LOG_CLEANUP_ERROR] = 'L', - [BTRFS_FS_STATE_EMERGENCY_SHUTDOWN] = 'E', + [BTRFS_FS_STATE_EMERGENCY_SHUTDOWN] = 'H', }; static void btrfs_state_to_string(const struct btrfs_fs_info *info, char *buf) @@ -42,9 +44,8 @@ static void btrfs_state_to_string(const struct btrfs_fs_info *info, char *buf) states_printed = true; } - for_each_set_bit(bit, &fs_state, sizeof(fs_state)) { - WARN_ON_ONCE(bit >= BTRFS_FS_STATE_COUNT); - if ((bit < BTRFS_FS_STATE_COUNT) && fs_state_chars[bit]) { + for_each_set_bit(bit, &fs_state, BTRFS_FS_STATE_COUNT) { + if (fs_state_chars[bit]) { *curr++ = fs_state_chars[bit]; states_printed = true; } diff --git a/fs/btrfs/qgroup.c b/fs/btrfs/qgroup.c index f68b696b4bf7..5fd029276508 100644 --- a/fs/btrfs/qgroup.c +++ b/fs/btrfs/qgroup.c @@ -1845,7 +1845,7 @@ int btrfs_remove_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid) struct btrfs_qgroup_list, next_group); ret = __del_qgroup_relation(trans, qgroupid, list->group->qgroupid); - if (ret) + if (ret < 0) goto out; } @@ -4887,7 +4887,7 @@ int btrfs_qgroup_trace_subtree_after_cow(struct btrfs_trans_handle *trans, /* Found one, remove it from @blocks first and update blocks->swapped */ rb_erase(&block->node, &blocks->blocks[level]); for (i = 0; i < BTRFS_MAX_LEVEL; i++) { - if (RB_EMPTY_ROOT(&blocks->blocks[i])) { + if (!RB_EMPTY_ROOT(&blocks->blocks[i])) { swapped = true; break; } diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c index 1ee52a9dcee3..3412f43d5dec 100644 --- a/fs/btrfs/raid56.c +++ b/fs/btrfs/raid56.c @@ -1652,12 +1652,7 @@ static void verify_bio_data_sectors(struct btrfs_raid_bio *rbio, struct bio *bio) { struct btrfs_fs_info *fs_info = rbio->bioc->fs_info; - const u32 step = min(fs_info->sectorsize, PAGE_SIZE); - const u32 nr_steps = rbio->sector_nsteps; int total_sector_nr = get_bio_sector_nr(rbio, bio); - u32 offset = 0; - phys_addr_t paddrs[BTRFS_MAX_BLOCKSIZE / PAGE_SIZE]; - phys_addr_t paddr; /* No data csum for the whole stripe, no need to verify. */ if (!rbio->csum_bitmap || !rbio->csum_buf) @@ -1667,28 +1662,20 @@ static void verify_bio_data_sectors(struct btrfs_raid_bio *rbio, if (total_sector_nr >= rbio->nr_data * rbio->stripe_nsectors) return; - btrfs_bio_for_each_block_all(paddr, bio, step) { + for (struct bvec_iter iter = init_bvec_iter_for_bio(bio); + iter.bi_size; + bio_advance_iter(bio, &iter, fs_info->sectorsize), total_sector_nr++) { u8 csum_buf[BTRFS_CSUM_SIZE]; u8 *expected_csum; - paddrs[(offset / step) % nr_steps] = paddr; - offset += step; - - /* Not yet covering the full fs block, continue to the next step. */ - if (!IS_ALIGNED(offset, fs_info->sectorsize)) - continue; - /* No csum for this sector, skip to the next sector. */ - if (!test_bit(total_sector_nr, rbio->csum_bitmap)) { - total_sector_nr++; + if (!test_bit(total_sector_nr, rbio->csum_bitmap)) continue; - } expected_csum = rbio->csum_buf + total_sector_nr * fs_info->csum_size; - btrfs_calculate_block_csum_pages(fs_info, paddrs, csum_buf); + btrfs_csum_one_bio_block(fs_info, bio, &iter, csum_buf); if (unlikely(memcmp(csum_buf, expected_csum, fs_info->csum_size) != 0)) set_bit(total_sector_nr, rbio->error_bitmap); - total_sector_nr++; } } @@ -1879,11 +1866,34 @@ void raid56_parity_write(struct bio *bio, struct btrfs_io_context *bioc) start_async_work(rbio, rmw_rbio_work); } +static void calculate_block_csum_paddrs(struct btrfs_fs_info *fs_info, + const phys_addr_t paddrs[], u8 *dest) +{ + const u32 blocksize = fs_info->sectorsize; + const u32 step = min(blocksize, PAGE_SIZE); + const u32 nr_steps = blocksize / step; + struct btrfs_csum_ctx csum; + + btrfs_csum_init(&csum, fs_info->csum_type); + for (int i = 0; i < nr_steps; i++) { + const phys_addr_t paddr = paddrs[i]; + void *kaddr; + + ASSERT(offset_in_page(paddr) + step <= PAGE_SIZE); + kaddr = kmap_local_page(phys_to_page(paddr)) + offset_in_page(paddr); + btrfs_csum_update(&csum, kaddr, step); + kunmap_local(kaddr); + } + btrfs_csum_final(&csum, dest); +} + static int verify_one_sector(struct btrfs_raid_bio *rbio, int stripe_nr, int sector_nr) { struct btrfs_fs_info *fs_info = rbio->bioc->fs_info; phys_addr_t *paddrs; + const unsigned int total_sector_nr = + stripe_nr * rbio->stripe_nsectors + sector_nr; u8 csum_buf[BTRFS_CSUM_SIZE]; u8 *csum_expected; @@ -1893,6 +1903,11 @@ static int verify_one_sector(struct btrfs_raid_bio *rbio, /* No way to verify P/Q as they are not covered by data csum. */ if (stripe_nr >= rbio->nr_data) return 0; + + /* No data checksum for this sector. */ + if (!test_bit(total_sector_nr, rbio->csum_bitmap)) + return 0; + /* * If we're rebuilding a read, we have to use pages from the * bio list if possible. @@ -1903,10 +1918,8 @@ static int verify_one_sector(struct btrfs_raid_bio *rbio, paddrs = rbio_stripe_paddrs(rbio, stripe_nr, sector_nr); } - csum_expected = rbio->csum_buf + - (stripe_nr * rbio->stripe_nsectors + sector_nr) * - fs_info->csum_size; - btrfs_calculate_block_csum_pages(fs_info, paddrs, csum_buf); + csum_expected = rbio->csum_buf + total_sector_nr * fs_info->csum_size; + calculate_block_csum_paddrs(fs_info, paddrs, csum_buf); if (unlikely(memcmp(csum_buf, csum_expected, fs_info->csum_size) != 0)) return -EIO; return 0; diff --git a/fs/btrfs/tree-mod-log.c b/fs/btrfs/tree-mod-log.c index a8094928f4c9..bfa348d6483f 100644 --- a/fs/btrfs/tree-mod-log.c +++ b/fs/btrfs/tree-mod-log.c @@ -483,10 +483,17 @@ int btrfs_tree_mod_log_insert_root(struct extent_buffer *old_root, goto out_unlock; } - if (tm_list) + if (tm_list) { ret = tree_mod_log_free_eb(fs_info, tm_list, nritems); - if (!ret) - ret = tree_mod_log_insert(fs_info, tm); + if (ret) + goto out_unlock; + } + + ret = tree_mod_log_insert(fs_info, tm); + if (ret && tm_list) { + for (i = 0; i < nritems; i++) + rb_erase(&tm_list[i]->node, &fs_info->tree_mod_log); + } out_unlock: write_unlock(&fs_info->tree_mod_log_lock); diff --git a/fs/btrfs/verity.c b/fs/btrfs/verity.c index 59ee70bd2374..c29d92c3bbc3 100644 --- a/fs/btrfs/verity.c +++ b/fs/btrfs/verity.c @@ -286,21 +286,17 @@ static int write_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset, * @dest: Buffer to read into. This parameter has slightly tricky * semantics. If it is NULL, the function will not do any copying * and will just return the size of all the items up to len bytes. - * If dest_page is passed, then the function will kmap_local the - * page and ignore dest, but it must still be non-NULL to avoid the - * counting-only behavior. * @len: length in bytes to read - * @dest_folio: copy into this folio instead of the dest buffer * * Helper function to read items from the btree. This returns the number of * bytes read or < 0 for errors. We can return short reads if the items don't * exist on disk or aren't big enough to fill the desired length. Supports - * reading into a provided buffer (dest) or into the page cache + * reading into a provided buffer (dest). * * Returns number of bytes read or a negative error code on failure. */ static int read_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset, - char *dest, u64 len, struct folio *dest_folio) + char *dest, u64 len) { BTRFS_PATH_AUTO_FREE(path); struct btrfs_root *root = inode->root; @@ -320,7 +316,11 @@ static int read_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset, if (!path) return -ENOMEM; - if (dest_folio) + /* + * Merkle items can be large and split across multiple items, so enable + * readahead for such cases. + */ + if (key_type == BTRFS_VERITY_MERKLE_ITEM_KEY) path->reada = READA_FORWARD; key.objectid = btrfs_ino(inode); @@ -364,7 +364,7 @@ static int read_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset, break; } - /* desc = NULL to just sum all the item lengths */ + /* dest == NULL to just sum all the item lengths */ if (!dest) copy_end = item_end; else @@ -377,16 +377,10 @@ static int read_key_bytes(struct btrfs_inode *inode, u8 key_type, u64 offset, copy_offset = offset - key.offset; if (dest) { - if (dest_folio) - kaddr = kmap_local_folio(dest_folio, 0); - data = btrfs_item_ptr(leaf, path->slots[0], void); read_extent_buffer(leaf, kaddr + dest_offset, (unsigned long)data + copy_offset, copy_bytes); - - if (dest_folio) - kunmap_local(kaddr); } offset += copy_bytes; @@ -678,7 +672,7 @@ int btrfs_get_verity_descriptor(struct inode *inode, void *buf, size_t buf_size) memset(&item, 0, sizeof(item)); ret = read_key_bytes(BTRFS_I(inode), BTRFS_VERITY_DESC_ITEM_KEY, 0, - (char *)&item, sizeof(item), NULL); + (char *)&item, sizeof(item)); if (ret < 0) return ret; @@ -695,7 +689,7 @@ int btrfs_get_verity_descriptor(struct inode *inode, void *buf, size_t buf_size) return -ERANGE; ret = read_key_bytes(BTRFS_I(inode), BTRFS_VERITY_DESC_ITEM_KEY, 1, - buf, buf_size, NULL); + buf, buf_size); if (ret < 0) return ret; if (ret != true_size) @@ -721,6 +715,7 @@ static struct page *btrfs_read_merkle_tree_page(struct inode *inode, struct folio *folio; u64 off = (u64)index << PAGE_SHIFT; loff_t merkle_pos = merkle_file_pos(inode); + void *kaddr; int ret; if (merkle_pos < 0) @@ -764,6 +759,7 @@ static struct page *btrfs_read_merkle_tree_page(struct inode *inode, } read_folio: + kaddr = kmap_local_folio(folio, 0); /* * Merkle item keys are indexed from byte 0 in the merkle tree. * They have the form: @@ -771,7 +767,8 @@ static struct page *btrfs_read_merkle_tree_page(struct inode *inode, * [ inode objectid, BTRFS_MERKLE_ITEM_KEY, offset in bytes ] */ ret = read_key_bytes(BTRFS_I(inode), BTRFS_VERITY_MERKLE_ITEM_KEY, off, - folio_address(folio), PAGE_SIZE, folio); + kaddr, PAGE_SIZE); + kunmap_local(kaddr); if (ret < 0) { folio_unlock(folio); folio_put(folio); diff --git a/fs/btrfs/volumes.c b/fs/btrfs/volumes.c index e7d3cd66a98d..8eaabca99b4e 100644 --- a/fs/btrfs/volumes.c +++ b/fs/btrfs/volumes.c @@ -2814,6 +2814,41 @@ static void btrfs_setup_sprout(struct btrfs_fs_info *fs_info, btrfs_set_super_flags(disk_super, super_flags); } +static void btrfs_rollback_sprout(struct btrfs_fs_info *fs_info, + struct btrfs_fs_devices *seed_devices) +{ + struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; + struct btrfs_super_block *disk_super = fs_info->super_copy; + struct btrfs_device *device; + u64 super_flags; + + lockdep_assert_held(&uuid_mutex); + lockdep_assert_held(&fs_devices->device_list_mutex); + + list_del_init(&seed_devices->seed_list); + list_splice_init_rcu(&seed_devices->devices, &fs_devices->devices, synchronize_rcu); + list_for_each_entry(device, &fs_devices->devices, dev_list) { + device->fs_devices = fs_devices; + } + + fs_devices->seeding = true; + fs_devices->num_devices = seed_devices->num_devices; + fs_devices->open_devices = seed_devices->open_devices; + fs_devices->missing_devices = seed_devices->missing_devices; + fs_devices->rotating = seed_devices->rotating; + fs_devices->latest_dev = seed_devices->latest_dev; + + memcpy(fs_devices->fsid, seed_devices->fsid, BTRFS_FSID_SIZE); + memcpy(fs_devices->metadata_uuid, seed_devices->metadata_uuid, BTRFS_FSID_SIZE); + memcpy(disk_super->fsid, seed_devices->fsid, BTRFS_FSID_SIZE); + + super_flags = (btrfs_super_flags(disk_super) | BTRFS_SUPER_FLAG_SEEDING); + btrfs_set_super_flags(disk_super, super_flags); + + seed_devices->opened = 0; + free_fs_devices(seed_devices); +} + /* * Store the expected generation for seed devices in device items. */ @@ -3165,6 +3200,8 @@ int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path orig_super_total_bytes); btrfs_set_super_num_devices(fs_info->super_copy, orig_super_num_devices); + if (seeding_dev) + btrfs_rollback_sprout(fs_info, seed_devices); btrfs_update_per_profile_avail(fs_info); mutex_unlock(&fs_info->chunk_mutex); mutex_unlock(&fs_info->fs_devices->device_list_mutex); diff --git a/fs/btrfs/zoned.c b/fs/btrfs/zoned.c index 08a15465a087..3b41e964d209 100644 --- a/fs/btrfs/zoned.c +++ b/fs/btrfs/zoned.c @@ -2005,10 +2005,12 @@ int btrfs_load_block_group_zone_info(struct btrfs_block_group *cache, bool new) if (!ret) { cache->meta_write_pointer = cache->alloc_offset + cache->start; if (test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &cache->runtime_flags)) { - btrfs_get_block_group(cache); spin_lock(&fs_info->zone_active_bgs_lock); - list_add_tail(&cache->active_bg_list, - &fs_info->zone_active_bgs); + if (list_empty(&cache->active_bg_list)) { + btrfs_get_block_group(cache); + list_add_tail(&cache->active_bg_list, + &fs_info->zone_active_bgs); + } spin_unlock(&fs_info->zone_active_bgs_lock); } } else { diff --git a/fs/ceph/addr.c b/fs/ceph/addr.c index f32a533f4100..edf3ad5a0bfc 100644 --- a/fs/ceph/addr.c +++ b/fs/ceph/addr.c @@ -450,6 +450,17 @@ static void ceph_netfs_issue_read(struct netfs_io_subrequest *subreq) osd_req_op_extent_osd_iter(req, 0, &subreq->io_iter); } if (!ceph_inc_osd_stopping_blocker(fsc->mdsc)) { + struct ceph_osd_data *osd_data = + osd_req_op_extent_osd_data(req, 0); + + if (osd_data->type == CEPH_OSD_DATA_TYPE_PAGES) { + int num_pages = calc_pages_for(osd_data->alignment, + osd_data->length); + + for (int i = 0; i < num_pages; i++) + put_page(osd_data->pages[i]); + kvfree(osd_data->pages); + } err = -EIO; goto out; } @@ -564,6 +575,11 @@ static void ceph_set_page_fscache(struct page *page) folio_start_private_2(page_folio(page)); /* [DEPRECATED] */ } +static void ceph_folio_wait_fscache(struct folio *folio) +{ + folio_wait_private_2(folio); /* [DEPRECATED] */ +} + static void ceph_fscache_write_terminated(void *priv, ssize_t error) { struct inode *inode = priv; @@ -585,6 +601,10 @@ static inline void ceph_set_page_fscache(struct page *page) { } +static inline void ceph_folio_wait_fscache(struct folio *folio) +{ +} + static inline void ceph_fscache_write_to_cache(struct inode *inode, u64 off, u64 len, bool caching) { } @@ -788,6 +808,9 @@ static int write_folio_nounlock(struct folio *folio, ceph_vinop(inode), folio, folio->index, page_off, wlen, snapc, snapc->seq); + /* wait for a cache write left pending by a previously failed attempt */ + ceph_folio_wait_fscache(folio); + if (atomic_long_inc_return(&fsc->writeback_count) > CONGESTION_ON_THRESH(fsc->mount_options->congestion_kb)) fsc->write_congested = true; @@ -1394,8 +1417,6 @@ void ceph_process_folio_batch(struct address_space *mapping, doutc(cl, "%llx.%llx will write folio %p idx %lu\n", ceph_vinop(inode), folio, folio->index); - fsc->write_congested = is_write_congestion_happened(fsc); - rc = move_dirty_folio_in_page_array(mapping, wbc, ceph_wbc, folio); if (rc) { @@ -1408,6 +1429,9 @@ void ceph_process_folio_batch(struct address_space *mapping, break; } + if (is_write_congestion_happened(fsc)) + fsc->write_congested = true; + ceph_wbc->fbatch.folios[i] = NULL; ceph_wbc->len += folio_size(folio); } @@ -1491,28 +1515,32 @@ int ceph_submit_write(struct address_space *mapping, BUG_ON(len < ceph_fscrypt_page_offset(page) + thp_size(page) - offset); if (!ceph_inc_osd_stopping_blocker(fsc->mdsc)) { - for (i = 0; i < folio_batch_count(&ceph_wbc->fbatch); i++) { - struct folio *folio = ceph_wbc->fbatch.folios[i]; - - if (!folio) - continue; - - page = &folio->page; - redirty_page_for_writepage(wbc, page); - unlock_page(page); - } - for (i = 0; i < ceph_wbc->locked_pages; i++) { - page = ceph_fscrypt_pagecache_page(ceph_wbc->pages[i]); + page = ceph_wbc->pages[i]; + if (fscrypt_is_bounce_page(page)) { + page = fscrypt_pagecache_page(page); + fscrypt_free_bounce_page(ceph_wbc->pages[i]); + } - if (!page) - continue; + if (atomic_long_dec_return(&fsc->writeback_count) < + CONGESTION_OFF_THRESH(fsc->mount_options->congestion_kb)) + fsc->write_congested = false; ceph_undo_wrbuffer_claim(inode, page_folio(page)); redirty_page_for_writepage(wbc, page); unlock_page(page); + put_page(page); } + if (ceph_wbc->from_pool) { + mempool_free(ceph_wbc->pages, ceph_wb_pagevec_pool); + ceph_wbc->from_pool = false; + } else { + kfree(ceph_wbc->pages); + } + ceph_wbc->pages = NULL; + ceph_wbc->locked_pages = 0; + ceph_osdc_put_request(req); return -EIO; } @@ -1745,8 +1773,11 @@ static int ceph_writepages_start(struct address_space *mapping, } rc = ceph_submit_write(mapping, wbc, &ceph_wbc); - if (rc) - goto release_folios; + if (rc) { + /* the OSD client is being torn down, don't retry */ + folio_batch_release(&ceph_wbc.fbatch); + goto dec_osd_stopping_blocker; + } ceph_wbc.locked_pages = 0; ceph_wbc.strip_unit_end = 0; diff --git a/fs/ceph/inode.c b/fs/ceph/inode.c index d52e2b389e0b..79c4409f183e 100644 --- a/fs/ceph/inode.c +++ b/fs/ceph/inode.c @@ -993,7 +993,7 @@ static int decode_encrypted_symlink(struct ceph_mds_client *mdsc, kfree(sym); return -EIO; } - sym[declen + 1] = '\0'; + sym[declen] = '\0'; *decsym = sym; return declen; } diff --git a/fs/ceph/super.c b/fs/ceph/super.c index 72935f665f11..416bf86996a0 100644 --- a/fs/ceph/super.c +++ b/fs/ceph/super.c @@ -394,13 +394,18 @@ static int ceph_parse_mon_addr(struct fs_parameter *param, { struct ceph_parse_opts_ctx *pctx = fc->fs_private; struct ceph_mount_options *fsopt = pctx->opts; + int ret; + + ret = ceph_parse_mon_ips(param->string, strlen(param->string), + pctx->copts, fc->log.log, '/'); + if (ret) + return ret; kfree(fsopt->mon_addr); fsopt->mon_addr = param->string; param->string = NULL; - return ceph_parse_mon_ips(fsopt->mon_addr, strlen(fsopt->mon_addr), - pctx->copts, fc->log.log, '/'); + return 0; } static int ceph_parse_mount_param(struct fs_context *fc, @@ -1368,6 +1373,15 @@ static int ceph_get_tree(struct fs_context *fc) doutc(fsc->client, "root %p inode %p ino %llx.%llx\n", res, d_inode(res), ceph_vinop(d_inode(res))); fc->root = fsc->sb->s_root; + + /* + * The mount is up. sget_fc() leaves SB_ACTIVE unset, and, unlike + * filesystems that go through vfs_get_super(), nothing else sets + * it here, so iput_final() would always evict an inode whose + * ->drop_inode() asks to retain it. Set it like nfs_get_tree() + * does. + */ + sb->s_flags |= SB_ACTIVE; return 0; out_splat: diff --git a/fs/ceph/super.h b/fs/ceph/super.h index 72d4e30304dc..1c91e73a63ac 100644 --- a/fs/ceph/super.h +++ b/fs/ceph/super.h @@ -463,7 +463,6 @@ struct ceph_inode_info { wait_queue_head_t i_cap_wq; /* threads waiting on a capability */ unsigned long i_hold_caps_max; /* jiffies */ struct list_head i_cap_delay_list; /* for delayed cap release to mds */ - struct ceph_cap_reservation i_cap_migration_resv; struct list_head i_cap_snaps; /* snapped state pending flush to mds */ struct ceph_snap_context *i_head_snapc; /* set if wr_buffer_head > 0 or dirty|flushing caps */ diff --git a/fs/dcache.c b/fs/dcache.c index f9c9f3b1ba80..7d7d96a098d7 100644 --- a/fs/dcache.c +++ b/fs/dcache.c @@ -32,6 +32,7 @@ #include #include #include +#include #include "internal.h" #include "mount.h" @@ -3537,6 +3538,7 @@ void __init vfs_caches_init(void) inode_init(); files_init(); files_maxfiles_init(); + dquot_cache_init(); mnt_init(); bdev_cache_init(); chrdev_init(); diff --git a/fs/debugfs/file.c b/fs/debugfs/file.c index 08de6652a4f3..170feb75317f 100644 --- a/fs/debugfs/file.c +++ b/fs/debugfs/file.c @@ -1049,98 +1049,37 @@ ssize_t debugfs_read_file_str(struct file *file, char __user *user_buf, return ret; } -static ssize_t debugfs_write_file_str(struct file *file, const char __user *user_buf, - size_t count, loff_t *ppos) -{ - struct dentry *dentry = F_DENTRY(file); - char *old, *new = NULL; - int pos = *ppos; - int r; - - r = debugfs_file_get(dentry); - if (unlikely(r)) - return r; - - old = *(char **)file->private_data; - - /* only allow strict concatenation */ - r = -EINVAL; - if (pos && pos != strlen(old)) - goto error; - - r = -E2BIG; - if (pos + count + 1 > PAGE_SIZE) - goto error; - - r = -ENOMEM; - new = kmalloc(pos + count + 1, GFP_KERNEL); - if (!new) - goto error; - - if (pos) - memcpy(new, old, pos); - - r = -EFAULT; - if (copy_from_user(new + pos, user_buf, count)) - goto error; - - new[pos + count] = '\0'; - strim(new); - - rcu_assign_pointer(*(char __rcu **)file->private_data, new); - synchronize_rcu(); - kfree(old); - - debugfs_file_put(dentry); - return count; - -error: - kfree(new); - debugfs_file_put(dentry); - return r; -} - static const struct file_operations fops_str = { .read = debugfs_read_file_str, - .write = debugfs_write_file_str, - .open = simple_open, - .llseek = default_llseek, -}; - -static const struct file_operations fops_str_ro = { - .read = debugfs_read_file_str, - .open = simple_open, - .llseek = default_llseek, -}; - -static const struct file_operations fops_str_wo = { - .write = debugfs_write_file_str, .open = simple_open, .llseek = default_llseek, }; /** - * debugfs_create_str - create a debugfs file that is used to read and write a string value + * debugfs_create_str - create a debugfs file that is used to read a string value * @name: a pointer to a string containing the name of the file to create. * @mode: the permission that the file should have * @parent: a pointer to the parent dentry for this file. This should be a * directory dentry if set. If this parameter is %NULL, then the * file will be created in the root of the debugfs filesystem. - * @value: a pointer to the variable that the file should read to and write - * from. This pointer and the string it points to must not be %NULL. + * @value: a pointer to the variable that the file should read from. This + * pointer and the string it points to must not be %NULL. * * This function creates a file in debugfs with the given name that - * contains the value of the variable @value. If the @mode variable is so - * set, it can be read from, and written to. + * contains the value of the variable @value. The file can be read from. + * Writable files are not supported; if @mode contains write permission bits, + * no file is created. */ void debugfs_create_str(const char *name, umode_t mode, struct dentry *parent, char **value) { if (WARN_ON(!value || !*value)) return; + if (WARN(mode & 0222, + "%s() does not support writable files\n", __func__)) + return; - debugfs_create_mode_unsafe(name, mode, parent, value, &fops_str, - &fops_str_ro, &fops_str_wo); + debugfs_create_file_unsafe(name, mode, parent, value, &fops_str); } EXPORT_SYMBOL_GPL(debugfs_create_str); diff --git a/fs/dlm/config.c b/fs/dlm/config.c index 53cd33293042..6ebc0fa9a2fa 100644 --- a/fs/dlm/config.c +++ b/fs/dlm/config.c @@ -64,11 +64,37 @@ static void release_node(struct config_item *); static struct configfs_attribute *comm_attrs[]; static struct configfs_attribute *node_attrs[]; +static u32 rsb_hashfn(const void *data, u32 len, u32 seed) +{ + const struct dlm_rsb_key *key = data; + + return jhash(key->name, key->len, 0); +} + +static u32 rsb_obj_hashfn(const void *data, u32 len, u32 seed) +{ + const struct dlm_rsb *r = data; + + return r->res_hash; +} + +static int rsb_obj_cmpfn(struct rhashtable_compare_arg *arg, const void *obj) +{ + const struct dlm_rsb_key *key = arg->key; + const struct dlm_rsb *r = obj; + + if (key->len != r->res_length) + return -1; + + return memcmp(&r->res_name, key->name, key->len); +} + const struct rhashtable_params dlm_rhash_rsb_params = { .nelem_hint = 3, /* start small */ - .key_len = DLM_RESNAME_MAXLEN, - .key_offset = offsetof(struct dlm_rsb, res_name), .head_offset = offsetof(struct dlm_rsb, res_node), + .hashfn = rsb_hashfn, + .obj_hashfn = rsb_obj_hashfn, + .obj_cmpfn = rsb_obj_cmpfn, .automatic_shrinking = true, }; @@ -831,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/dlm_internal.h b/fs/dlm/dlm_internal.h index 9df842421ae0..74c2e77d1b55 100644 --- a/fs/dlm/dlm_internal.h +++ b/fs/dlm/dlm_internal.h @@ -340,6 +340,11 @@ struct dlm_rsb { char res_name[DLM_RESNAME_MAXLEN+1]; }; +struct dlm_rsb_key { + char name[DLM_RESNAME_MAXLEN]; + size_t len; +}; + /* dlm_master_lookup() flags */ #define DLM_LU_RECOVER_DIR 1 diff --git a/fs/dlm/lock.c b/fs/dlm/lock.c index c381e1028446..2609e4fdeba8 100644 --- a/fs/dlm/lock.c +++ b/fs/dlm/lock.c @@ -622,13 +622,17 @@ static int get_rsb_struct(struct dlm_ls *ls, const void *name, int len, return 0; } -int dlm_search_rsb_tree(struct rhashtable *rhash, const void *name, int len, - struct dlm_rsb **r_ret) +int dlm_search_rsb_tree(struct rhashtable *rhash, const void *name, + unsigned int len, struct dlm_rsb **r_ret) { - char key[DLM_RESNAME_MAXLEN] = {}; + struct dlm_rsb_key key = { + .len = len, + }; + if (len > DLM_RESNAME_MAXLEN) return -EINVAL; - memcpy(key, name, len); + + memcpy(key.name, name, len); *r_ret = rhashtable_lookup_fast(rhash, &key, dlm_rhash_rsb_params); if (*r_ret) return 0; @@ -1421,7 +1425,7 @@ void dlm_dump_rsb_name(struct dlm_ls *ls, const char *name, int len) rcu_read_lock(); error = dlm_search_rsb_tree(&ls->ls_rsbtbl, name, len, &r); - if (!error) + if (error) goto out; dlm_dump_rsb(r); @@ -5529,6 +5533,10 @@ static int receive_rcom_lock_args(struct dlm_ls *ls, struct dlm_lkb *lkb, { struct rcom_lock *rl = (struct rcom_lock *) rc->rc_buf; + if (rl->rl_rqmode < DLM_LOCK_IV || rl->rl_rqmode > DLM_LOCK_EX || + rl->rl_grmode < DLM_LOCK_IV || rl->rl_grmode > DLM_LOCK_EX) + return -EINVAL; + lkb->lkb_nodeid = le32_to_cpu(rc->rc_header.h_nodeid); lkb->lkb_ownpid = le32_to_cpu(rl->rl_ownpid); lkb->lkb_remid = le32_to_cpu(rl->rl_lkid); diff --git a/fs/dlm/lock.h b/fs/dlm/lock.h index b23d7b854ed4..c75975937331 100644 --- a/fs/dlm/lock.h +++ b/fs/dlm/lock.h @@ -31,8 +31,8 @@ void resume_scan_timer(struct dlm_ls *ls); int dlm_master_lookup(struct dlm_ls *ls, int from_nodeid, const char *name, int len, unsigned int flags, int *r_nodeid, int *result); -int dlm_search_rsb_tree(struct rhashtable *rhash, const void *name, int len, - struct dlm_rsb **r_ret); +int dlm_search_rsb_tree(struct rhashtable *rhash, const void *name, + unsigned int len, struct dlm_rsb **r_ret); void dlm_recover_purge(struct dlm_ls *ls, const struct list_head *root_list); void dlm_purge_mstcpy_locks(struct dlm_rsb *r); diff --git a/fs/dlm/member.c b/fs/dlm/member.c index f84233a0fe4a..3a1c558ce9f6 100644 --- a/fs/dlm/member.c +++ b/fs/dlm/member.c @@ -402,7 +402,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; @@ -411,8 +411,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 */ @@ -422,10 +422,9 @@ static void make_member_array(struct dlm_ls *ls) all_zero = 1; } - ls->ls_total_weight = total; array = kmalloc_objs(*array, total, GFP_NOFS); if (!array) - return; + return -ENOMEM; list_for_each_entry(memb, &ls->ls_nodes, list) { if (!all_zero && !memb->weight) @@ -442,7 +441,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 */ @@ -617,7 +619,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/erofs/data.c b/fs/erofs/data.c index be63b89f0862..a726be5e27ca 100644 --- a/fs/erofs/data.c +++ b/fs/erofs/data.c @@ -33,7 +33,10 @@ void *erofs_bread(struct erofs_buf *buf, erofs_off_t offset, bool need_kmap) if (buf->page) { folio = page_folio(buf->page); - if (folio_file_page(folio, index) != buf->page) + if (folio->mapping != buf->mapping) + /* the cached folio belongs to another address_space */ + folio = NULL; + else if (folio_file_page(folio, index) != buf->page) erofs_unmap_metabuf(buf); } if (!folio || !folio_contains(folio, index)) { diff --git a/fs/erofs/internal.h b/fs/erofs/internal.h index 12e3a5b80a5a..da58053c1116 100644 --- a/fs/erofs/internal.h +++ b/fs/erofs/internal.h @@ -150,6 +150,7 @@ struct erofs_sb_info { #define EROFS_MOUNT_DAX_NEVER 0x00000080 #define EROFS_MOUNT_DIRECT_IO 0x00000100 #define EROFS_MOUNT_INODE_SHARE 0x00000200 +#define EROFS_MOUNT_SUPERBLOCK_SHARE 0x00000400 #define clear_opt(opt, option) ((opt)->mount_opt &= ~EROFS_MOUNT_##option) #define set_opt(opt, option) ((opt)->mount_opt |= EROFS_MOUNT_##option) diff --git a/fs/erofs/super.c b/fs/erofs/super.c index 0967aace9f7f..ce05557bd998 100644 --- a/fs/erofs/super.c +++ b/fs/erofs/super.c @@ -386,7 +386,7 @@ static void erofs_default_options(struct erofs_sb_info *sbi) enum { Opt_user_xattr, Opt_acl, Opt_cache_strategy, Opt_dax, Opt_dax_enum, Opt_device, Opt_domain_id, Opt_directio, Opt_fsoffset, Opt_inode_share, - Opt_source, + Opt_source, Opt_superblock_share, }; static const struct constant_table erofs_param_cache_strategy[] = { @@ -415,6 +415,7 @@ static const struct fs_parameter_spec erofs_fs_parameters[] = { fsparam_u64("fsoffset", Opt_fsoffset), fsparam_flag("inode_share", Opt_inode_share), fsparam_file_or_string("source", Opt_source), + fsparam_flag("superblock_share", Opt_superblock_share), {} }; @@ -560,6 +561,12 @@ static int erofs_fc_parse_param(struct fs_context *fc, else set_opt(&sbi->opt, INODE_SHARE); break; + case Opt_superblock_share: + if (!IS_ENABLED(CONFIG_EROFS_FS_BACKED_BY_FILE)) + errorfc(fc, "%s option not supported", erofs_fs_parameters[opt].name); + else + set_opt(&sbi->opt, SUPERBLOCK_SHARE); + break; case Opt_source: return erofs_fc_parse_source(fc, param); } @@ -667,6 +674,16 @@ static int erofs_fc_fill_super(struct super_block *sb, struct fs_context *fc) errorfc(fc, "FSDAX is not allowed when inode_share is on"); return -EINVAL; } + if (test_opt(&sbi->opt, SUPERBLOCK_SHARE) && + test_opt(&sbi->opt, INODE_SHARE)) { + errorfc(fc, "superblock_share is not allowed when inode_share is on"); + return -EINVAL; + } + if (test_opt(&sbi->opt, SUPERBLOCK_SHARE) && + sbi->devs->extra_devices) { + errorfc(fc, "superblock_share does not support extra devices"); + return -EINVAL; + } sbi->blkszbits = PAGE_SHIFT; if (erofs_is_fileio_mode(sbi)) { @@ -794,6 +811,36 @@ static int erofs_fc_fill_super(struct super_block *sb, struct fs_context *fc) return 0; } +/* + * The function is used only with a sbi that has SUPERBLOCK_SHARE set, + * so that the memcmp later ensures new_sbi is also shareable. + */ +static int erofs_sb_share_test_super(struct super_block *sb, + struct fs_context *fc) +{ + struct erofs_sb_info *sbi = EROFS_SB(sb); + struct erofs_sb_info *new_sbi = fc->s_fs_info; + + if (sb->s_iflags & SB_I_RETIRED) + return 0; + if (!sbi->dif0.file || !new_sbi->dif0.file) + return 0; + return file_inode(sbi->dif0.file) == file_inode(new_sbi->dif0.file) && + sbi->dif0.fsoff == new_sbi->dif0.fsoff && + !memcmp(&sbi->opt, &new_sbi->opt, sizeof(sbi->opt)) && + !new_sbi->devs->extra_devices; +} + +static int erofs_file_get_tree(struct fs_context *fc) +{ + struct erofs_sb_info *sbi = fc->s_fs_info; + + if (!test_opt(&sbi->opt, SUPERBLOCK_SHARE)) + return get_tree_nodev(fc, erofs_fc_fill_super); + + return get_tree_super(fc, erofs_sb_share_test_super, erofs_fc_fill_super); +} + static int erofs_fc_get_tree(struct fs_context *fc) { struct erofs_sb_info *sbi = fc->s_fs_info; @@ -804,12 +851,11 @@ static int erofs_fc_get_tree(struct fs_context *fc) errorfc(fc, "source fd option not supported"); return -EINVAL; } - if (!S_ISREG(file_inode(sbi->dif0.file)->i_mode) || - !sbi->dif0.file->f_mapping->a_ops->read_folio) { + if (!S_ISREG(file_inode(sbi->dif0.file)->i_mode)) { errorfc(fc, "source is unsupported"); return -EINVAL; } - return get_tree_nodev(fc, erofs_fc_fill_super); + return erofs_file_get_tree(fc); } ret = get_tree_bdev_flags(fc, erofs_fc_fill_super, @@ -825,9 +871,8 @@ static int erofs_fc_get_tree(struct fs_context *fc) return PTR_ERR(file); sbi->dif0.file = file; - if (S_ISREG(file_inode(sbi->dif0.file)->i_mode) && - sbi->dif0.file->f_mapping->a_ops->read_folio) - return get_tree_nodev(fc, erofs_fc_fill_super); + if (S_ISREG(file_inode(sbi->dif0.file)->i_mode)) + return erofs_file_get_tree(fc); } return ret; } @@ -840,6 +885,10 @@ static int erofs_fc_reconfigure(struct fs_context *fc) DBG_BUGON(!sb_rdonly(sb)); + /* Shared superblocks must not be reconfigured. */ + if (test_opt(&sbi->opt, SUPERBLOCK_SHARE)) + return -EBUSY; + if (new_sbi->domain_id) erofs_info(sb, "ignoring reconfiguration for domain_id."); diff --git a/fs/eventpoll.c b/fs/eventpoll.c index e0c4bf88a838..872396a0ad64 100644 --- a/fs/eventpoll.c +++ b/fs/eventpoll.c @@ -1982,11 +1982,22 @@ static int ep_modify(struct eventpoll *ep, struct epitem *epi, { int pwake = 0; poll_table pt; + int error; lockdep_assert_irqs_enabled(); init_poll_funcptr(&pt, NULL); + /* + * Create the wakeup source before committing the new event mask. + * Leave the old mask and data unchanged if allocation fails. + */ + if ((event->events & EPOLLWAKEUP) && !ep_has_wakeup_source(epi)) { + error = ep_create_wakeup_source(epi); + if (error) + return error; + } + /* * Set the new event interest mask before calling f_op->poll(); * otherwise we might miss an event that happens between the @@ -1994,12 +2005,9 @@ static int ep_modify(struct eventpoll *ep, struct epitem *epi, */ epi->event.events = event->events; /* need barrier below */ epi->event.data = event->data; /* protected by mtx */ - if (epi->event.events & EPOLLWAKEUP) { - if (!ep_has_wakeup_source(epi)) - ep_create_wakeup_source(epi); - } else if (ep_has_wakeup_source(epi)) { + if (!(epi->event.events & EPOLLWAKEUP) && + ep_has_wakeup_source(epi)) ep_destroy_wakeup_source(epi); - } /* * The following barrier has two effects: diff --git a/fs/exfat/fatent.c b/fs/exfat/fatent.c index a8b11e2ce43f..9f4607fced7f 100644 --- a/fs/exfat/fatent.c +++ b/fs/exfat/fatent.c @@ -418,28 +418,47 @@ int exfat_zeroed_cluster(struct inode *dir, unsigned int clu) return 0; } +/* + * Newly allocated clusters may still have dirty buffer_heads in the block + * device mapping, e.g. the dentries of a directory that was just removed. + * File data does not go through those buffers, so drop them; otherwise a + * later flush of the block device writes them over the new data. + */ +static void exfat_clean_bdev_aliases(struct super_block *sb, + unsigned int clu, unsigned int count) +{ + struct exfat_sb_info *sbi = EXFAT_SB(sb); + + clean_bdev_aliases(sb->s_bdev, exfat_cluster_to_sector(sbi, clu), + (sector_t)count << sbi->sect_per_clus_bits); +} + int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc, struct exfat_chain *p_chain, bool sync_bmap, bool contig) { int ret = -ENOSPC; unsigned int total_cnt; unsigned int hint_clu, new_clu, last_clu = EXFAT_EOF_CLUSTER; + unsigned int run_clu = EXFAT_EOF_CLUSTER, run_len = 0; 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 */ @@ -509,15 +528,26 @@ int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc, } } p_chain->size++; + sbi->used_clusters++; + + /* clean stale buffers once per contiguous run of clusters */ + if (run_len && new_clu == run_clu + run_len) { + run_len++; + } else { + if (run_len) + exfat_clean_bdev_aliases(sb, run_clu, run_len); + run_clu = new_clu; + run_len = 1; + } last_clu = new_clu; if (p_chain->size == num_alloc) { done: + exfat_clean_bdev_aliases(sb, run_clu, run_len); sbi->clu_srch_ptr = hint_clu; - sbi->used_clusters += p_chain->size; - mutex_unlock(&sbi->bitmap_lock); - return 0; + ret = 0; + goto unlock; } hint_clu = new_clu + 1; diff --git a/fs/ext2/file.c b/fs/ext2/file.c index d4a0a528c342..8ddc149d4884 100644 --- a/fs/ext2/file.c +++ b/fs/ext2/file.c @@ -135,6 +135,13 @@ static ssize_t ext2_dio_write_iter(struct kiocb *iocb, struct iov_iter *from) int ret2; iocb->ki_flags &= ~IOCB_DIRECT; + + /* + * Prevent concurrent direct I/O and buffered I/O to the same file + * range. Wait for in-flight DIO to finish before dirtying pages. + */ + inode_dio_wait(inode); + pos = iocb->ki_pos; status = generic_perform_write(iocb, from); if (unlikely(status < 0)) { diff --git a/fs/ext4/inode.c b/fs/ext4/inode.c index 6697c33d3aa3..bd1c14b98376 100644 --- a/fs/ext4/inode.c +++ b/fs/ext4/inode.c @@ -703,7 +703,7 @@ int ext4_map_blocks(handle_t *handle, struct inode *inode, struct extent_status es; int retval; int ret = 0; - unsigned int orig_mlen = map->m_len; + unsigned int orig_mlen; #ifdef ES_AGGRESSIVE_TEST struct ext4_map_blocks orig_map; @@ -719,6 +719,7 @@ int ext4_map_blocks(handle_t *handle, struct inode *inode, */ if (unlikely(map->m_len > INT_MAX)) map->m_len = INT_MAX; + orig_mlen = map->m_len; /* We can handle the block number less than EXT_MAX_BLOCKS */ if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS)) diff --git a/fs/f2fs/checkpoint.c b/fs/f2fs/checkpoint.c index a84517023e54..0692b198d0b0 100644 --- a/fs/f2fs/checkpoint.c +++ b/fs/f2fs/checkpoint.c @@ -824,15 +824,6 @@ static void __clear_ino_bitmap(struct f2fs_sb_info *sbi, nid_t ino, int type) spin_unlock(&im->ino_lock); } -static void f2fs_wait_for_inode_record(struct f2fs_sb_info *sbi, int mode) -{ - if (mode != APPEND_INO && mode != UPDATE_INO) - return; - - /* Let's wait for some pending updates for APPEND_INO and UPDATE_INO. */ - flush_workqueue(sbi->evict_wq); -} - static void __f2fs_add_ino_entry(struct f2fs_sb_info *sbi, nid_t ino, unsigned int devidx, int type) { @@ -886,8 +877,6 @@ void f2fs_release_ino_entry(struct f2fs_sb_info *sbi, bool all) for (i = all ? ORPHAN_INO : FLUSH_INO; i <= FLUSH_INO; i++) { struct inode_management *im = &sbi->im[i]; - f2fs_wait_for_inode_record(sbi, i); - spin_lock(&im->ino_lock); list_for_each_entry_safe(e, tmp, &im->ino_list, list) { list_del(&e->list); @@ -898,6 +887,9 @@ void f2fs_release_ino_entry(struct f2fs_sb_info *sbi, bool all) spin_unlock(&im->ino_lock); } + /* Wait for pending APPEND/UPDATE inode state updates. */ + flush_workqueue(sbi->evict_wq); + for (i = APPEND_INO; i < MAX_INO_ENTRY; i++) { struct inode_management *im = &sbi->im[i]; diff --git a/fs/f2fs/gc.c b/fs/f2fs/gc.c index 6220d55709e9..8d620799df12 100644 --- a/fs/f2fs/gc.c +++ b/fs/f2fs/gc.c @@ -2323,6 +2323,7 @@ static void update_fs_metadata(struct f2fs_sb_info *sbi, int secs) SM_I(sbi)->segment_count = (int)SM_I(sbi)->segment_count + segs; MAIN_SEGS(sbi) = (int)MAIN_SEGS(sbi) + segs; MAIN_SECS(sbi) += secs; + f2fs_adjust_pinned_area_boundary(sbi); if (sbi->allocate_section_hint > MAIN_SECS(sbi)) sbi->allocate_section_hint = MAIN_SECS(sbi); FREE_I(sbi)->free_sections = (int)FREE_I(sbi)->free_sections + secs; @@ -2354,7 +2355,7 @@ int f2fs_resize_fs(struct file *filp, __u64 block_count) struct f2fs_lock_context lc; struct f2fs_lock_context glc; struct f2fs_lock_context clc; - unsigned int secs; + unsigned int secs, old_tail; int err = 0; __u32 rem; @@ -2463,6 +2464,8 @@ int f2fs_resize_fs(struct file *filp, __u64 block_count) goto recover_out; } + old_tail = F2FS_OPTION(sbi).resizable_tail_secno; + F2FS_OPTION(sbi).resizable_tail_secno -= min(old_tail, secs); update_fs_metadata(sbi, -secs); clear_sbi_flag(sbi, SBI_IS_RESIZEFS); set_sbi_flag(sbi, SBI_IS_DIRTY); @@ -2470,6 +2473,7 @@ int f2fs_resize_fs(struct file *filp, __u64 block_count) stat_inc_cp_call_count(sbi, TOTAL_CALL); err = f2fs_write_checkpoint(sbi, &cpc); if (err) { + F2FS_OPTION(sbi).resizable_tail_secno = old_tail; update_fs_metadata(sbi, secs); update_sb_metadata(sbi, secs); f2fs_commit_super(sbi, false); diff --git a/fs/f2fs/inode.c b/fs/f2fs/inode.c index 96cc0e777567..4a6382b4c6a5 100644 --- a/fs/f2fs/inode.c +++ b/fs/f2fs/inode.c @@ -1055,9 +1055,9 @@ static void f2fs_post_evict_inode(struct inode *inode) goto skip_record; if (is_inode_flag_set(inode, FI_APPEND_WRITE)) - record_bits = BIT(APPEND_INO); + record_bits |= BIT(APPEND_INO); if (is_inode_flag_set(inode, FI_UPDATE_WRITE)) - record_bits = BIT(UPDATE_INO); + record_bits |= BIT(UPDATE_INO); if (!record_bits) goto skip_record; diff --git a/fs/f2fs/node.c b/fs/f2fs/node.c index e166c5a5d170..dff42b74d66f 100644 --- a/fs/f2fs/node.c +++ b/fs/f2fs/node.c @@ -2195,9 +2195,11 @@ int f2fs_sync_node_pages(struct f2fs_sb_info *sbi, /* flush inline_data */ if (folio_test_f2fs_inline(folio)) { + nid_t ino = ino_of_node(folio); + folio_clear_f2fs_inline(folio); folio_unlock(folio); - flush_inline_data(sbi, ino_of_node(folio)); + flush_inline_data(sbi, ino); goto lock_node; } diff --git a/fs/f2fs/segment.c b/fs/f2fs/segment.c index 75f78ed7eb90..c1d78939ce84 100644 --- a/fs/f2fs/segment.c +++ b/fs/f2fs/segment.c @@ -2980,7 +2980,7 @@ static int get_new_segment(struct f2fs_sb_info *sbi, alloc_hint = MAIN_SECS(sbi); if (pinning) { - max_secno = sbi->pinned_area_max_secno; + max_secno = min(sbi->pinned_area_max_secno, MAIN_SECS(sbi)); hint = 0; } else if (alloc_policy == ALLOCATE_FORWARD_FROM_HINT && hint < alloc_hint) { diff --git a/fs/f2fs/segment.h b/fs/f2fs/segment.h index 5949aa5200ac..6c3af51f352c 100644 --- a/fs/f2fs/segment.h +++ b/fs/f2fs/segment.h @@ -91,6 +91,17 @@ static inline void sanity_check_seg_type(struct f2fs_sb_info *sbi, #define GET_ZONE_FROM_SEG(sbi, segno) \ GET_ZONE_FROM_SEC(sbi, GET_SEC_FROM_SEG(sbi, segno)) +static inline void f2fs_adjust_pinned_area_boundary(struct f2fs_sb_info *sbi) +{ + sbi->pinned_area_max_secno = MAIN_SECS(sbi); + if (f2fs_sb_has_blkzoned(sbi) && sbi->first_seq_zone_segno != NULL_SEGNO) + sbi->pinned_area_max_secno = min(sbi->pinned_area_max_secno, + GET_SEC_FROM_SEG(sbi, sbi->first_seq_zone_segno)); + if (F2FS_OPTION(sbi).resizable_tail_secno) + sbi->pinned_area_max_secno = min(sbi->pinned_area_max_secno, + MAIN_SECS(sbi) - F2FS_OPTION(sbi).resizable_tail_secno); +} + #define GET_SUM_BLOCK(sbi, segno) \ (SM_I(sbi)->ssa_blkaddr + (segno / (sbi)->sums_per_block)) #define GET_SUM_BLKOFF(sbi, segno) (segno % (sbi)->sums_per_block) diff --git a/fs/f2fs/super.c b/fs/f2fs/super.c index b18ea09bcbe2..c422a0d15260 100644 --- a/fs/f2fs/super.c +++ b/fs/f2fs/super.c @@ -554,17 +554,6 @@ static inline void adjust_unusable_cap_perc(struct f2fs_sb_info *sbi) F2FS_OPTION(sbi).unusable_cap_perc); } -static inline void adjust_pinned_area_boundary(struct f2fs_sb_info *sbi) -{ - sbi->pinned_area_max_secno = MAIN_SECS(sbi); - if (f2fs_sb_has_blkzoned(sbi) && sbi->first_seq_zone_segno != NULL_SEGNO) - sbi->pinned_area_max_secno = min(sbi->pinned_area_max_secno, - GET_SEC_FROM_SEG(sbi, sbi->first_seq_zone_segno)); - if (F2FS_OPTION(sbi).resizable_tail_secno) - sbi->pinned_area_max_secno = min(sbi->pinned_area_max_secno, - MAIN_SECS(sbi) - F2FS_OPTION(sbi).resizable_tail_secno); -} - static void init_once(void *foo) { struct f2fs_inode_info *fi = (struct f2fs_inode_info *) foo; @@ -2154,6 +2143,25 @@ int f2fs_sync_fs(struct super_block *sb, int sync) return err; } +static int f2fs_sync_fs_super(struct super_block *sb, int sync) +{ + struct f2fs_sb_info *sbi = F2FS_SB(sb); + bool freeze_sync = sync && + sb->s_writers.frozen == SB_FREEZE_PAGEFAULT; + int err; + + /* freeze_super() holds s_umount for write during this sync pass. */ + if (freeze_sync) + sbi->umount_lock_holder = current; + + err = f2fs_sync_fs(sb, sync); + + if (freeze_sync) + sbi->umount_lock_holder = NULL; + + return err; +} + static int f2fs_freeze(struct super_block *sb) { struct f2fs_sb_info *sbi = F2FS_SB(sb); @@ -2864,7 +2872,8 @@ static int __f2fs_remount(struct fs_context *fc, struct super_block *sb) if (!org_mount_opt.s_qf_names[i]) { for (j = 0; j < i; j++) kfree(org_mount_opt.s_qf_names[j]); - return -ENOMEM; + err = -ENOMEM; + goto restore_holder; } } else { org_mount_opt.s_qf_names[i] = NULL; @@ -3078,7 +3087,7 @@ static int __f2fs_remount(struct fs_context *fc, struct super_block *sb) sb->s_flags = (sb->s_flags & ~SB_POSIXACL) | (test_opt(sbi, POSIX_ACL) ? SB_POSIXACL : 0); - adjust_pinned_area_boundary(sbi); + f2fs_adjust_pinned_area_boundary(sbi); limit_reserve_root(sbi); fc->sb_flags = (flags & ~SB_LAZYTIME) | (sb->s_flags & SB_LAZYTIME); @@ -3125,6 +3134,9 @@ static int __f2fs_remount(struct fs_context *fc, struct super_block *sb) sbi->mount_opt = org_mount_opt; sb->s_flags = old_sb_flags; +#ifdef CONFIG_QUOTA +restore_holder: +#endif sbi->umount_lock_holder = NULL; return err; } @@ -3772,7 +3784,7 @@ static const struct super_operations f2fs_sops = { #endif .evict_inode = f2fs_evict_inode, .put_super = f2fs_put_super, - .sync_fs = f2fs_sync_fs, + .sync_fs = f2fs_sync_fs_super, .freeze_fs = f2fs_freeze, .unfreeze_fs = f2fs_unfreeze, .statfs = f2fs_statfs, @@ -4174,6 +4186,12 @@ static int sanity_check_raw_super(struct f2fs_sb_info *sbi, return -EFSCORRUPTED; } + if (__F2FS_HAS_FEATURE(raw_super, F2FS_FEATURE_DEVICE_ALIAS) && + (!RDEV(0).path[0] || !RDEV(1).path[0])) { + f2fs_info(sbi, "Device aliasing requires a multi-device configuration"); + return -EFSCORRUPTED; + } + if (RDEV(0).path[0]) { block_t dev_seg_count = le32_to_cpu(RDEV(0).total_segments); int i = 1; @@ -5385,7 +5403,7 @@ static int f2fs_fill_super(struct super_block *sb, struct fs_context *fc) /* get segno of first zoned block device */ sbi->first_seq_zone_segno = get_first_seq_zone_segno(sbi); - adjust_pinned_area_boundary(sbi); + f2fs_adjust_pinned_area_boundary(sbi); sbi->reserved_pin_section = f2fs_sb_has_blkzoned(sbi) ? ZONED_PIN_SEC_REQUIRED_COUNT : diff --git a/fs/fs-writeback.c b/fs/fs-writeback.c index e2ee11119518..c75c6d8b6714 100644 --- a/fs/fs-writeback.c +++ b/fs/fs-writeback.c @@ -1190,7 +1190,7 @@ int cgroup_writeback_by_id(u64 bdi_id, int memcg_id, struct cgroup_subsys_state *memcg_css; struct bdi_writeback *wb; struct wb_writeback_work *work; - unsigned long dirty; + long dirty; int ret; /* lookup bdi and memcg */ @@ -1219,16 +1219,13 @@ int cgroup_writeback_by_id(u64 bdi_id, int memcg_id, } /* - * The caller is attempting to write out most of - * the currently dirty pages. Let's take the current dirty page - * count and inflate it by 25% which should be large enough to - * flush out most dirty pages while avoiding getting livelocked by - * concurrent dirtiers. - * - * BTW the memcg stats are flushed periodically and this is best-effort - * estimation, so some potential error is ok. + * The caller is attempting to write out most of the target wb's + * currently dirty pages. Size the work from the wb's reclaimable pages + * and inflate the count by 25%, which should be large enough to flush + * out most dirty pages while avoiding getting livelocked by concurrent + * dirtiers. */ - dirty = memcg_page_state(mem_cgroup_from_css(memcg_css), NR_FILE_DIRTY); + dirty = wb_stat_sum(wb, WB_RECLAIMABLE); dirty = dirty * 10 / 8; /* issue the writeback work */ @@ -2582,8 +2579,9 @@ void filemap_dontcache_kick_writeback(struct address_space *mapping) struct wb_lock_cookie cookie = {}; bool need_wakeup = false; + /* An inode which was never dirtied has no wb and nothing to flush. */ wb = unlocked_inode_to_wb_begin(inode, &cookie); - if (wb_has_dirty_io(wb) && + if (wb && wb_has_dirty_io(wb) && !test_bit(WB_start_dontcache, &wb->state) && !test_and_set_bit(WB_start_dontcache, &wb->state)) { wb_get(wb); diff --git a/fs/fs_pin.c b/fs/fs_pin.c index 1a508f2167e0..a4e5a5a7aca8 100644 --- a/fs/fs_pin.c +++ b/fs/fs_pin.c @@ -28,6 +28,19 @@ void pin_insert(struct fs_pin *pin, struct vfsmount *m) spin_unlock(&pin_lock); } +/* + * Unlike autoremove_wake_function(), dequeue even if the waiter was already + * running: pin_kill() trusts @p only while its entry is still queued. + */ +static int pin_kill_wake_function(struct wait_queue_entry *wait, + unsigned int mode, int sync, void *key) +{ + int ret = default_wake_function(wait, mode, sync, key); + + list_del_init_careful(&wait->entry); + return ret; +} + void pin_kill(struct fs_pin *p) { wait_queue_entry_t wait; @@ -36,7 +49,7 @@ void pin_kill(struct fs_pin *p) rcu_read_unlock(); return; } - init_wait(&wait); + init_wait_func(&wait, pin_kill_wake_function); spin_lock_irq(&p->wait.lock); if (likely(!p->done)) { p->done = -1; diff --git a/fs/fuse/dev.c b/fs/fuse/dev.c index 4148e4488d77..6227d5e62a0c 100644 --- a/fs/fuse/dev.c +++ b/fs/fuse/dev.c @@ -466,24 +466,27 @@ static bool fuse_dev_install_with_pq(struct fuse_dev *fud, struct fuse_chan *fch struct fuse_chan *old_fch; guard(spinlock)(&fch->lock); - /* - * Pairs with: - * - xchg() in fuse_dev_release() - * - smp_load_acquire() in fuse_dev_fc_get() - */ - old_fch = cmpxchg(&fud->chan, NULL, fch); - if (old_fch) { + /* protect fud->pq.processing assignment */ + scoped_guard(spinlock, &fud->pq.lock) { /* - * failed to set fud->chan because - * - it was already set to a different fc - * - it was set to disconneted + * Pairs with: + * - xchg() in fuse_dev_release() + * - smp_load_acquire() in fuse_dev_fc_get() */ - kfree(pq); - return false; - } - if (pq) { - WARN_ON(fud->pq.processing); - fud->pq.processing = pq; + old_fch = cmpxchg(&fud->chan, NULL, fch); + if (old_fch) { + /* + * failed to set fud->chan because + * - it was already set to a different fc + * - it was set to disconneted + */ + kfree(pq); + return false; + } + if (pq) { + WARN_ON(fud->pq.processing); + fud->pq.processing = pq; + } } list_add_tail(&fud->entry, &fch->devices); fuse_conn_get(fch->conn); @@ -1148,32 +1151,32 @@ static int fuse_try_move_folio(struct fuse_copy_state *cs, struct folio **foliop if (cs->len != folio_size(oldfolio)) goto out_fallback; - if (!pipe_buf_try_steal(cs->pipe, buf)) - goto out_fallback; - newfolio = page_folio(buf->page); - folio_clear_uptodate(newfolio); - folio_clear_mappedtodisk(newfolio); - if (folio_test_large(newfolio)) - goto out_fallback_unlock; - - if (fuse_check_folio(newfolio) != 0) - goto out_fallback_unlock; + goto out_fallback; /* * This is a new and locked page, it shouldn't be mapped or * have any special flags on it */ if (WARN_ON(folio_mapped(oldfolio))) - goto out_fallback_unlock; + goto out_fallback; if (WARN_ON(folio_has_private(oldfolio))) - goto out_fallback_unlock; + goto out_fallback; if (WARN_ON(folio_test_dirty(oldfolio) || folio_test_writeback(oldfolio))) - goto out_fallback_unlock; + goto out_fallback; if (WARN_ON(folio_test_mlocked(oldfolio))) + goto out_fallback; + + if (!pipe_buf_try_steal(cs->pipe, buf)) + goto out_fallback; + + folio_clear_uptodate(newfolio); + folio_clear_mappedtodisk(newfolio); + + if (fuse_check_folio(newfolio) != 0) goto out_fallback_unlock; err = lock_request(cs->req); @@ -1253,31 +1256,10 @@ static int fuse_ref_folio(struct fuse_copy_state *cs, struct folio *folio, * done atomically */ 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) { - /* - * When the copy is skipped the folio already holds the - * payload, so only the bytes outside [offset, offset + - * count) may be zeroed. - * - * Otherwise, the whole folio is cleared first so that a - * failed copy leaves zeros rather than stale folio - * contents. - */ - if (cs->skip_folio_copy) - folio_zero_segments(folio, 0, offset, - offset + count, size); - else - folio_zero_range(folio, 0, size); - } - } while (!cs->skip_folio_copy && count) { if (cs->write && cs->pipebufs && folio) { @@ -1294,7 +1276,7 @@ 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; @@ -1335,10 +1317,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; diff --git a/fs/fuse/dev.h b/fs/fuse/dev.h index 8d25378c0918..f6c47ae0395b 100644 --- a/fs/fuse/dev.h +++ b/fs/fuse/dev.h @@ -90,7 +90,7 @@ int fuse_backing_close(struct fuse_conn *fc, int backing_id); int fuse_copy_one(struct fuse_copy_state *cs, void *val, unsigned size); int fuse_copy_folio(struct fuse_copy_state *cs, struct folio **foliop, - unsigned offset, unsigned count, int zeroing); + unsigned offset, unsigned count); void fuse_copy_finish(struct fuse_copy_state *cs); #ifdef CONFIG_FUSE_IO_URING diff --git a/fs/fuse/file.c b/fs/fuse/file.c index bf79c6eb3062..f51551165e8f 100644 --- a/fs/fuse/file.c +++ b/fs/fuse/file.c @@ -689,7 +689,7 @@ static void fuse_aio_complete(struct fuse_io_priv *io, int err, ssize_t pos) struct address_space *mapping = io->iocb->ki_filp->f_mapping; ssize_t res = fuse_get_res_by_io(io); - if (res >= 0) { + if (res >= 0 && io->write) { struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_inode *fi = get_fuse_inode(inode); @@ -1895,7 +1895,10 @@ static ssize_t fuse_splice_read(struct file *in, loff_t *ppos, struct fuse_file *ff = in->private_data; /* FOPEN_DIRECT_IO overrides FOPEN_PASSTHROUGH */ - if (fuse_file_passthrough(ff) && !(ff->open_flags & FOPEN_DIRECT_IO)) + + if (ff->open_flags & FOPEN_DIRECT_IO) + return copy_splice_read(in, ppos, pipe, len, flags); + else if (fuse_file_passthrough(ff)) return fuse_passthrough_splice_read(in, ppos, pipe, len, flags); else return filemap_splice_read(in, ppos, pipe, len, flags); diff --git a/fs/fuse/notify.c b/fs/fuse/notify.c index fff059f8ad85..c0428e03d138 100644 --- a/fs/fuse/notify.c +++ b/fs/fuse/notify.c @@ -190,7 +190,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/fuse/req.c b/fs/fuse/req.c index a01ee743d31e..51cfd64ea1ba 100644 --- a/fs/fuse/req.c +++ b/fs/fuse/req.c @@ -10,12 +10,12 @@ static int fuse_fill_creds(struct fuse_mount *fm, struct fuse_args *args, struct kuid_t fsuid = mapped_fsuid(idmap, fc->user_ns); kgid_t fsgid = mapped_fsgid(idmap, fc->user_ns); + if (args->nocreds) + return 0; + args->pid = pid_nr_ns(task_pid(current), fc->pid_ns); if (args->force) { - if (args->nocreds) - return 0; - if (no_idmap) { args->uid = from_kuid_munged(fc->user_ns, current_fsuid()); args->gid = from_kgid_munged(fc->user_ns, current_fsgid()); @@ -26,7 +26,6 @@ static int fuse_fill_creds(struct fuse_mount *fm, struct fuse_args *args, struct return 0; } - WARN_ON(args->nocreds); /* * Keep the old behavior when idmappings support was not * declared by a FUSE server. diff --git a/fs/gfs2/bmap.c b/fs/gfs2/bmap.c index 73c626971163..9c5a434b231b 100644 --- a/fs/gfs2/bmap.c +++ b/fs/gfs2/bmap.c @@ -2416,7 +2416,7 @@ static int gfs2_journaled_truncate_range(struct inode *inode, loff_t offset, if (offs && chunk > PAGE_SIZE) chunk = offs + ((chunk - offs) & PAGE_MASK); - truncate_pagecache_range(inode, offset, chunk); + truncate_pagecache_range(inode, offset, offset + chunk - 1); offset += chunk; length -= chunk; diff --git a/fs/gfs2/inode.c b/fs/gfs2/inode.c index f361876c5583..d5e03ec89127 100644 --- a/fs/gfs2/inode.c +++ b/fs/gfs2/inode.c @@ -1900,7 +1900,7 @@ static int gfs2_rename2(struct mnt_idmap *idmap, struct inode *odir, * * This can handle symlinks of any size. * - * Returns: 0 on success or error code + * Returns: the link target on success, an ERR_PTR() on failure */ static const char *gfs2_get_link(struct dentry *dentry, diff --git a/fs/hfs/btree.c b/fs/hfs/btree.c index 41b4e8fc9463..4f0ddc76e8c5 100644 --- a/fs/hfs/btree.c +++ b/fs/hfs/btree.c @@ -310,15 +310,18 @@ void hfs_btree_close(struct hfs_btree *tree) return; for (i = 0; i < NODE_HASH_SIZE; i++) { + spin_lock(&tree->hash_lock); while ((node = tree->node_hash[i])) { - tree->node_hash[i] = node->next_hash; + hfs_bnode_unhash(node); + spin_unlock(&tree->hash_lock); if (atomic_read(&node->refcnt)) pr_err("node %d:%d still has %d user(s)!\n", node->tree->cnid, node->this, atomic_read(&node->refcnt)); hfs_bnode_free(node); - tree->node_hash_cnt--; + spin_lock(&tree->hash_lock); } + spin_unlock(&tree->hash_lock); } iput(tree->inode); kfree(tree); diff --git a/fs/hfsplus/btree.c b/fs/hfsplus/btree.c index 2ea8cd5658e1..bd4dbdbc8f98 100644 --- a/fs/hfsplus/btree.c +++ b/fs/hfsplus/btree.c @@ -417,16 +417,19 @@ void hfs_btree_close(struct hfs_btree *tree) return; for (i = 0; i < NODE_HASH_SIZE; i++) { + spin_lock(&tree->hash_lock); while ((node = tree->node_hash[i])) { - tree->node_hash[i] = node->next_hash; + hfs_bnode_unhash(node); + spin_unlock(&tree->hash_lock); if (atomic_read(&node->refcnt)) pr_crit("node %d:%d " "still has %d user(s)!\n", node->tree->cnid, node->this, atomic_read(&node->refcnt)); hfs_bnode_free(node); - tree->node_hash_cnt--; + spin_lock(&tree->hash_lock); } + spin_unlock(&tree->hash_lock); } iput(tree->inode); kfree(tree); diff --git a/fs/hugetlbfs/inode.c b/fs/hugetlbfs/inode.c index 7611a8470ea2..2eca1855e097 100644 --- a/fs/hugetlbfs/inode.c +++ b/fs/hugetlbfs/inode.c @@ -841,6 +841,11 @@ static int hugetlbfs_setattr(struct mnt_idmap *idmap, if (error) return error; + if (S_ISREG(inode->i_mode) && (ia_valid & ATTR_MODE) && + (info->seals & F_SEAL_EXEC) && + ((inode->i_mode ^ attr->ia_mode) & 0111)) + return -EPERM; + trace_hugetlbfs_setattr(inode, dentry, attr); if (ia_valid & ATTR_SIZE) { diff --git a/fs/internal.h b/fs/internal.h index c658c8a5ebd5..67aa0444351b 100644 --- a/fs/internal.h +++ b/fs/internal.h @@ -137,7 +137,6 @@ extern int reconfigure_super(struct fs_context *); extern bool super_trylock_shared(struct super_block *sb); struct super_block *user_get_super(dev_t, bool excl); void put_super(struct super_block *sb); -void __init super_dev_init(void); extern bool mount_capable(struct fs_context *); /* diff --git a/fs/iomap/bio.c b/fs/iomap/bio.c index ee85b009c5c1..eed19277f026 100644 --- a/fs/iomap/bio.c +++ b/fs/iomap/bio.c @@ -169,6 +169,7 @@ int iomap_bio_read_folio_range_sync(const struct iomap_iter *iter, { const struct iomap *srcmap = iomap_iter_srcmap(iter); sector_t sector = iomap_sector(srcmap, pos); + struct bvec_iter saved_iter; struct bio_vec bvec; struct bio bio; int error; @@ -178,10 +179,11 @@ int iomap_bio_read_folio_range_sync(const struct iomap_iter *iter, bio_add_folio_nofail(&bio, folio, len, offset_in_folio(folio, pos)); if (srcmap->flags & IOMAP_F_INTEGRITY) fs_bio_integrity_alloc(&bio); + saved_iter = bio.bi_iter; error = submit_bio_wait(&bio); if (bio_integrity(&bio)) { if (!error) - error = fs_bio_integrity_verify(&bio, sector, len); + error = fs_bio_integrity_verify(&bio, &saved_iter); fs_bio_integrity_free(&bio); } bio_uninit(&bio); diff --git a/fs/iomap/direct-io.c b/fs/iomap/direct-io.c index 7f1e85f95a46..06566073a88c 100644 --- a/fs/iomap/direct-io.c +++ b/fs/iomap/direct-io.c @@ -589,12 +589,25 @@ static int iomap_dio_bio_iter(struct iomap_iter *iter, struct iomap_dio *dio) static int iomap_dio_hole_iter(struct iomap_iter *iter, struct iomap_dio *dio) { - loff_t length = iov_iter_zero(iomap_length(iter), dio->submit.iter); + loff_t copied = iov_iter_zero(iomap_length(iter), dio->submit.iter); - dio->size += length; - if (!length) + if (dio->flags & IOMAP_DIO_FSBLOCK_ALIGNED) { + loff_t aligned_copied = round_down(copied, + i_blocksize(iter->inode)); + + /* + * For fs passing IOMAP_DIO_FSBLOCK_ALIGNED flag, if fs block + * size is larger than page size, page fault failure + * can cause @copied to be page aligned but not fs block + * aligned. + */ + iov_iter_revert(dio->submit.iter, copied - aligned_copied); + copied = aligned_copied; + } + dio->size += copied; + if (!copied) return -EFAULT; - return iomap_iter_advance(iter, length); + return iomap_iter_advance(iter, copied); } static int iomap_dio_inline_iter(struct iomap_iter *iomi, struct iomap_dio *dio) diff --git a/fs/iomap/ioend.c b/fs/iomap/ioend.c index c2891d640e82..edc4509300d7 100644 --- a/fs/iomap/ioend.c +++ b/fs/iomap/ioend.c @@ -25,6 +25,7 @@ struct iomap_ioend *iomap_init_ioend(struct inode *inode, ioend->io_parent = NULL; INIT_LIST_HEAD(&ioend->io_list); ioend->io_flags = ioend_flags; + ioend->io_bvec_offset = bio->bi_iter.bi_offset; ioend->io_inode = inode; ioend->io_offset = file_offset; ioend->io_size = bio->bi_iter.bi_size; @@ -319,6 +320,13 @@ ssize_t iomap_add_to_ioend(struct iomap_writepage_ctx *wpc, struct folio *folio, } EXPORT_SYMBOL_GPL(iomap_add_to_ioend); +static int iomap_ioend_integrity_verify(struct iomap_ioend *ioend) +{ + struct bvec_iter data_iter = BVEC_ITER_IOEND(ioend); + + return fs_bio_integrity_verify(&ioend->io_bio, &data_iter); +} + static u32 iomap_finish_ioend(struct iomap_ioend *ioend, int error) { if (ioend->io_parent) { @@ -336,10 +344,8 @@ static u32 iomap_finish_ioend(struct iomap_ioend *ioend, int error) if (!ioend->io_error && bio_integrity(&ioend->io_bio) && - bio_op(&ioend->io_bio) == REQ_OP_READ) { - ioend->io_error = fs_bio_integrity_verify(&ioend->io_bio, - ioend->io_sector, ioend->io_size); - } + bio_op(&ioend->io_bio) == REQ_OP_READ) + ioend->io_error = iomap_ioend_integrity_verify(ioend); if (ioend->io_flags & IOMAP_IOEND_DIRECT) return iomap_finish_ioend_direct(ioend); diff --git a/fs/isofs/dir.c b/fs/isofs/dir.c index 28741251d56e..7a2b5e95c0a5 100644 --- a/fs/isofs/dir.c +++ b/fs/isofs/dir.c @@ -195,7 +195,9 @@ static int do_isofs_readdir(struct inode *inode, struct file *file, if (map) { #ifdef CONFIG_JOLIET if (sbi->s_joliet_level) { - len = get_joliet_filename(de, tmpname, inode); + len = get_joliet_filename(de, tmpname, + JOLIET_NAME_MAX + 1, + inode); p = tmpname; } else #endif diff --git a/fs/isofs/isofs.h b/fs/isofs/isofs.h index 79ca0256843a..47c43a3c6a61 100644 --- a/fs/isofs/isofs.h +++ b/fs/isofs/isofs.h @@ -121,7 +121,16 @@ bool isofs_dir_record_valid(struct iso_directory_record *de, unsigned long offset, unsigned long bufsize); -int get_joliet_filename(struct iso_directory_record *, unsigned char *, struct inode *); +/* + * The longest name the Joliet converter returns, in bytes. A directory + * record is at most 255 bytes long, which leaves room for 111 UTF-16 units + * of name, and no character set needs more than three bytes for one unit. + */ +#define JOLIET_NAME_MAX \ + ((255 - sizeof(struct iso_directory_record)) / 2 * 3) + +int get_joliet_filename(struct iso_directory_record *de, unsigned char *outname, + int outsize, struct inode *inode); int get_acorn_filename(struct iso_directory_record *, char *, struct inode *); extern struct dentry *isofs_lookup(struct inode *, struct dentry *, unsigned int flags); diff --git a/fs/isofs/joliet.c b/fs/isofs/joliet.c index c0f04a1e7f69..d37e67c5e36f 100644 --- a/fs/isofs/joliet.c +++ b/fs/isofs/joliet.c @@ -15,19 +15,26 @@ * Convert Unicode 16 to UTF-8 or ASCII. */ static int -uni16_to_x8(unsigned char *ascii, __be16 *uni, int len, struct nls_table *nls) +uni16_to_x8(unsigned char *ascii, __be16 *uni, int len, struct nls_table *nls, + int outsize) { __be16 *ip, ch; - unsigned char *op; + unsigned char *op, *end; ip = uni; op = ascii; + end = ascii + outsize - 1; /* leave room for the terminator */ while ((ch = get_unaligned(ip)) && len) { int llen; - llen = nls->uni2char(be16_to_cpu(ch), op, NLS_MAX_CHARSET_SIZE); + + if (op >= end) + break; + llen = nls->uni2char(be16_to_cpu(ch), op, end - op); if (llen > 0) op += llen; + else if (llen == -ENAMETOOLONG) + break; else *op++ = '?'; ip++; @@ -38,21 +45,27 @@ uni16_to_x8(unsigned char *ascii, __be16 *uni, int len, struct nls_table *nls) return (op - ascii); } +/* + * Convert the Joliet name of @de into @outname, a buffer of @outsize bytes. + * The result is at most @outsize - 1 bytes long; a longer name is cut at a + * character boundary. + */ int -get_joliet_filename(struct iso_directory_record * de, unsigned char *outname, struct inode * inode) +get_joliet_filename(struct iso_directory_record *de, unsigned char *outname, + int outsize, struct inode *inode) { struct nls_table *nls; - unsigned char len = 0; + int len = 0; nls = ISOFS_SB(inode->i_sb)->s_nls_iocharset; if (!nls) { len = utf16s_to_utf8s((const wchar_t *) de->name, de->name_len[0] >> 1, UTF16_BIG_ENDIAN, - outname, PAGE_SIZE); + outname, outsize - 1); } else { len = uni16_to_x8(outname, (__be16 *) de->name, - de->name_len[0] >> 1, nls); + de->name_len[0] >> 1, nls, outsize); } if ((len > 2) && (outname[len-2] == ';') && (outname[len-1] == '1')) len -= 2; diff --git a/fs/isofs/namei.c b/fs/isofs/namei.c index 4fba1bf7f016..7e4636df968e 100644 --- a/fs/isofs/namei.c +++ b/fs/isofs/namei.c @@ -109,7 +109,8 @@ isofs_find_entry(struct inode *dir, struct dentry *dentry, dpnt = tmpname; #ifdef CONFIG_JOLIET } else if (sbi->s_joliet_level) { - dlen = get_joliet_filename(de, tmpname, dir); + dlen = get_joliet_filename(de, tmpname, + JOLIET_NAME_MAX + 1, dir); dpnt = tmpname; #endif } else if (sbi->s_mapping == 'a') { diff --git a/fs/kernfs/dir.c b/fs/kernfs/dir.c index 82bbaeb326aa..f97bcfce2212 100644 --- a/fs/kernfs/dir.c +++ b/fs/kernfs/dir.c @@ -736,13 +736,19 @@ struct kernfs_node *kernfs_new_node(struct kernfs_node *parent, { struct kernfs_node *kn; - if (parent->mode & S_ISGID) { + /* + * The mode and the gid below are read unlocked on purpose: they feed + * a node that does not exist yet, so nothing orders a racing chmod or + * chown against this creation. + */ + if (READ_ONCE(parent->mode) & S_ISGID) { /* this code block imitates inode_init_owner() for * kernfs */ + struct kernfs_iattrs *attrs = READ_ONCE(parent->iattr); - if (parent->iattr) - gid = parent->iattr->ia_gid; + if (attrs) + gid = KGIDT_INIT(READ_ONCE(attrs->ia_gid.val)); if (flags & KERNFS_DIR) mode |= S_ISGID; @@ -1909,9 +1915,16 @@ static int kernfs_dir_fop_release(struct inode *inode, struct file *filp) return 0; } +/* + * Find where a listing left off. @resumed says whether @pos is still that + * entry; if not, the first entry at or after @hash is returned instead. + */ static struct kernfs_node *kernfs_dir_pos(const struct ns_common *ns, - struct kernfs_node *parent, loff_t hash, struct kernfs_node *pos) + struct kernfs_node *parent, loff_t hash, struct kernfs_node *pos, + bool *resumed) { + if (resumed) + *resumed = false; if (pos) { int valid = kernfs_active(pos) && rcu_access_pointer(pos->__parent) == parent && @@ -1919,23 +1932,26 @@ static struct kernfs_node *kernfs_dir_pos(const struct ns_common *ns, kernfs_put(pos); if (!valid) pos = NULL; + else if (resumed) + *resumed = true; } if (!pos && (hash > 1) && (hash < INT_MAX)) { struct rb_node *node = parent->dir.children.rb_node; - u64 ns_id = kernfs_ns_id(ns); + + /* + * Keep a node only on the way left, so the search ends on the + * first entry at or after @hash. The empty name sorts before + * every entry sharing the hash, so it lands on the first. + */ while (node) { - pos = rb_to_kn(node); + struct kernfs_node *kn = rb_to_kn(node); - if (hash < pos->hash) + if (kernfs_name_compare(hash, "", ns, kn) < 0) { + pos = kn; node = node->rb_left; - else if (hash > pos->hash) + } else { node = node->rb_right; - else if (ns_id < kernfs_ns_id(pos->ns)) - node = node->rb_left; - else if (ns_id > kernfs_ns_id(pos->ns)) - node = node->rb_right; - else - break; + } } } /* Skip over entries which are dying/dead or in the wrong namespace */ @@ -1951,10 +1967,13 @@ static struct kernfs_node *kernfs_dir_pos(const struct ns_common *ns, } static struct kernfs_node *kernfs_dir_next_pos(const struct ns_common *ns, - struct kernfs_node *parent, ino_t ino, struct kernfs_node *pos) + struct kernfs_node *parent, loff_t hash, struct kernfs_node *pos) { - pos = kernfs_dir_pos(ns, parent, ino, pos); - if (pos) { + bool resumed; + + pos = kernfs_dir_pos(ns, parent, hash, pos, &resumed); + /* Step over @pos only if it survived; two entries can share a hash. */ + if (pos && resumed) { do { struct rb_node *node = rb_next(&pos->rb); if (!node) @@ -1984,7 +2003,7 @@ static int kernfs_fop_readdir(struct file *file, struct dir_context *ctx) if (kernfs_ns_enabled(parent)) ns = kernfs_info(dentry->d_sb)->ns; - for (pos = kernfs_dir_pos(ns, parent, ctx->pos, pos); + for (pos = kernfs_dir_pos(ns, parent, ctx->pos, pos, NULL); pos; pos = kernfs_dir_next_pos(ns, parent, ctx->pos, pos)) { const char *name = kernfs_rcu_name(pos); @@ -1996,10 +2015,14 @@ static int kernfs_fop_readdir(struct file *file, struct dir_context *ctx) file->private_data = pos; kernfs_get(pos); - if (!dir_emit(ctx, name, len, ino, type)) { - up_read(&root->kernfs_rwsem); + /* + * dir_emit() can fault, so run it unlocked. @pos is pinned + * above and kernfs_dir_pos() rechecks it on the way back. + */ + up_read(&root->kernfs_rwsem); + if (!dir_emit(ctx, name, len, ino, type)) return 0; - } + down_read(&root->kernfs_rwsem); } up_read(&root->kernfs_rwsem); file->private_data = NULL; diff --git a/fs/kernfs/file.c b/fs/kernfs/file.c index 8e0e90c93372..7e3800526b1e 100644 --- a/fs/kernfs/file.c +++ b/fs/kernfs/file.c @@ -904,9 +904,12 @@ static loff_t kernfs_fop_llseek(struct file *file, loff_t offset, int whence) static void kernfs_notify_workfn(struct work_struct *work) { - struct kernfs_node *kn; + char name_buf[NAME_MAX + 1]; struct kernfs_super_info *info; + struct kernfs_node *kn; struct kernfs_root *root; + struct qstr name; + bool have_name; repeat: /* pop one off the notify_list */ spin_lock_irq(&kernfs_notify_lock); @@ -922,14 +925,20 @@ static void kernfs_notify_workfn(struct work_struct *work) root = kernfs_root(kn); /* kick fsnotify */ + /* + * Sample the name once so kernfs_rwsem need not be held across the + * loop. A name that does not fit is reported without one; fsnotify() + * takes the name as optional, so a watcher loses the name and not the + * event. + */ + have_name = kernfs_name(kn, name_buf, sizeof(name_buf)) >= 0; + name = QSTR(name_buf); + down_read(&root->kernfs_supers_rwsem); - down_read(&root->kernfs_rwsem); - list_for_each_entry(info, &kernfs_root(kn)->supers, node) { + list_for_each_entry(info, &root->supers, node) { struct kernfs_node *parent; struct inode *p_inode = NULL; - const char *kn_name; struct inode *inode; - struct qstr name; /* * We want fsnotify_modify() on @kn but as the @@ -941,15 +950,14 @@ static void kernfs_notify_workfn(struct work_struct *work) if (!inode) continue; - kn_name = kernfs_rcu_name(kn); - name = QSTR(kn_name); parent = kernfs_get_parent(kn); if (parent) { p_inode = ilookup(info->sb, kernfs_ino(parent)); if (p_inode) { fsnotify(FS_MODIFY | FS_EVENT_ON_CHILD, inode, FSNOTIFY_EVENT_INODE, - p_inode, &name, inode, 0); + p_inode, have_name ? &name : NULL, + inode, 0); iput(p_inode); } @@ -962,7 +970,6 @@ static void kernfs_notify_workfn(struct work_struct *work) iput(inode); } - up_read(&root->kernfs_rwsem); up_read(&root->kernfs_supers_rwsem); kernfs_put(kn); goto repeat; diff --git a/fs/kernfs/symlink.c b/fs/kernfs/symlink.c index 90e2b3221b83..3e53105d3abf 100644 --- a/fs/kernfs/symlink.c +++ b/fs/kernfs/symlink.c @@ -31,9 +31,20 @@ struct kernfs_node *kernfs_create_link(struct kernfs_node *parent, kuid_t uid = GLOBAL_ROOT_UID; kgid_t gid = GLOBAL_ROOT_GID; - if (target->iattr) { - uid = target->iattr->ia_uid; - gid = target->iattr->ia_gid; + /* + * A symlink takes its owner from its target, so both fields have to + * come from the same moment: read them under kernfs_iattr_rwsem, or + * a chown of the target racing this could leave the link with the + * old uid and the new gid. The section ends before kernfs_add_one() + * takes kernfs_rwsem. + */ + scoped_guard(rwsem_read, &kernfs_root(target)->kernfs_iattr_rwsem) { + struct kernfs_iattrs *attrs = READ_ONCE(target->iattr); + + if (attrs) { + uid = attrs->ia_uid; + gid = attrs->ia_gid; + } } kn = kernfs_new_node(parent, name, S_IFLNK|0777, uid, gid, KERNFS_LINK); diff --git a/fs/minix/namei.c b/fs/minix/namei.c index 5525ba367ed7..344cc70ba878 100644 --- a/fs/minix/namei.c +++ b/fs/minix/namei.c @@ -172,6 +172,10 @@ static int minix_rmdir(struct inode * dir, struct dentry *dentry) minix_error_inode(dir, "inode has corrupted nlink"); goto out; } + if (inode->i_nlink < 2) { + minix_error_inode(inode, "inode has corrupted nlink"); + goto out; + } err = -ENOTEMPTY; if (!minix_empty_dir(inode)) diff --git a/fs/namei.c b/fs/namei.c index e45e30603215..00ef70a4eaf5 100644 --- a/fs/namei.c +++ b/fs/namei.c @@ -683,8 +683,14 @@ EXPORT_SYMBOL(inode_permission); static __always_inline int lookup_inode_permission_may_exec(struct mnt_idmap *idmap, struct inode *inode, int mask) { - /* Lookup already checked this to return -ENOTDIR */ - VFS_BUG_ON_INODE(!S_ISDIR(inode->i_mode), inode); + /* + * Lookup already checked this to return -ENOTDIR. In rcu-walk that + * check looks at ->d_flags after ->d_seq had been validated, so it can + * see a dentry which went negative and then became a directory while + * nd->inode is still the old non-directory. Any such walk fails the + * next ->d_seq check and gets redone in ref-walk. + */ + VFS_BUG_ON_INODE(!S_ISDIR(inode->i_mode) && !(mask & MAY_NOT_BLOCK), inode); VFS_BUG_ON((mask & ~MAY_NOT_BLOCK) != 0); mask |= MAY_EXEC; diff --git a/fs/namespace.c b/fs/namespace.c index cf627543572b..48b90ffd6b1a 100644 --- a/fs/namespace.c +++ b/fs/namespace.c @@ -6486,8 +6486,6 @@ void __init mnt_init(void) HASH_ZERO, &mp_hash_shift, &mp_hash_mask, 0, 0); - super_dev_init(); - kernfs_init(); err = sysfs_init(); diff --git a/fs/netfs/internal.h b/fs/netfs/internal.h index 786af76da98c..947dbf4c538d 100644 --- a/fs/netfs/internal.h +++ b/fs/netfs/internal.h @@ -473,6 +473,32 @@ void fscache_create_volume(struct fscache_volume *volume, bool wait); #define kleave(FMT, ...) dbgprintk("<== %s()"FMT"", __func__, ##__VA_ARGS__) #define kdebug(FMT, ...) dbgprintk(FMT, ##__VA_ARGS__) +#define FSCACHE_DEBUG_CACHE 0 +#define FSCACHE_DEBUG_COOKIE 1 +#define FSCACHE_DEBUG_OBJECT 2 +#define FSCACHE_DEBUG_OPERATION 3 + +#define FSCACHE_POINT_ENTER 1 +#define FSCACHE_POINT_LEAVE 2 +#define FSCACHE_POINT_DEBUG 4 + +#ifndef FSCACHE_DEBUG_LEVEL +#define FSCACHE_DEBUG_LEVEL CACHE +#endif + +/* + * Determine whether a particular optional debugging point should be logged. + * Three levels of indirection are needed to expand FSCACHE_DEBUG_LEVEL before + * joining it with its prefix. + */ +#define ____do_kdebug(LEVEL, POINT) \ + unlikely(netfs_debug & \ + (FSCACHE_POINT_##POINT << (FSCACHE_DEBUG_ ## LEVEL * 3))) +#define ___do_kdebug(LEVEL, POINT) \ + ____do_kdebug(LEVEL, POINT) +#define __do_kdebug(POINT) \ + ___do_kdebug(FSCACHE_DEBUG_LEVEL, POINT) + #ifdef __KDEBUG #define _enter(FMT, ...) kenter(FMT, ##__VA_ARGS__) #define _leave(FMT, ...) kleave(FMT, ##__VA_ARGS__) @@ -481,19 +507,19 @@ void fscache_create_volume(struct fscache_volume *volume, bool wait); #elif defined(CONFIG_NETFS_DEBUG) #define _enter(FMT, ...) \ do { \ - if (netfs_debug) \ + if (__do_kdebug(ENTER)) \ kenter(FMT, ##__VA_ARGS__); \ } while (0) #define _leave(FMT, ...) \ do { \ - if (netfs_debug) \ + if (__do_kdebug(LEAVE)) \ kleave(FMT, ##__VA_ARGS__); \ } while (0) #define _debug(FMT, ...) \ do { \ - if (netfs_debug) \ + if (__do_kdebug(DEBUG)) \ kdebug(FMT, ##__VA_ARGS__); \ } while (0) diff --git a/fs/nfs/client.c b/fs/nfs/client.c index 60386330aeec..d85711edecbf 100644 --- a/fs/nfs/client.c +++ b/fs/nfs/client.c @@ -256,7 +256,7 @@ static void pnfs_init_server(struct nfs_server *server) */ void nfs_free_client(struct nfs_client *clp) { - nfs_localio_disable_client(clp); + nfs_localio_free_client(clp); /* -EIO all pending I/O */ if (!IS_ERR(clp->cl_rpcclient)) diff --git a/fs/nfs/dir.c b/fs/nfs/dir.c index a26c459ffb04..71a342e9589f 100644 --- a/fs/nfs/dir.c +++ b/fs/nfs/dir.c @@ -1935,7 +1935,7 @@ static int nfs_dentry_delete(const struct dentry *dentry) } /* Ensure that we revalidate inode->i_nlink */ -static void nfs_drop_nlink(struct inode *inode, unsigned long gencount) +void nfs_drop_nlink(struct inode *inode, unsigned long gencount) { struct nfs_inode *nfsi = NFS_I(inode); @@ -1949,6 +1949,7 @@ static void nfs_drop_nlink(struct inode *inode, unsigned long gencount) NFS_INO_INVALID_NLINK); spin_unlock(&inode->i_lock); } +EXPORT_SYMBOL_GPL(nfs_drop_nlink); /* * Called when the dentry loses inode. @@ -2556,7 +2557,6 @@ EXPORT_SYMBOL_GPL(nfs_rmdir); static int nfs_safe_remove(struct dentry *dentry) { struct inode *dir = d_inode(dentry->d_parent); - struct inode *inode = d_inode(dentry); int error = -EBUSY; dfprintk(VFS, "NFS: safe_remove(%pd2)\n", dentry); @@ -2568,14 +2568,7 @@ static int nfs_safe_remove(struct dentry *dentry) } trace_nfs_remove_enter(dir, dentry); - if (inode != NULL) { - unsigned long gencount = READ_ONCE(NFS_I(inode)->attr_gencount); - - error = NFS_PROTO(dir)->remove(dir, dentry); - if (error == 0) - nfs_drop_nlink(inode, gencount); - } else - error = NFS_PROTO(dir)->remove(dir, dentry); + error = NFS_PROTO(dir)->remove(dir, dentry); if (error == -ENOENT) nfs_dentry_handle_enoent(dentry); trace_nfs_remove_exit(dir, dentry, error); diff --git a/fs/nfs/filelayout/filelayout.c b/fs/nfs/filelayout/filelayout.c index 0d53277f972e..727fe1270aab 100644 --- a/fs/nfs/filelayout/filelayout.c +++ b/fs/nfs/filelayout/filelayout.c @@ -55,12 +55,13 @@ static loff_t filelayout_get_dense_offset(struct nfs4_filelayout_segment *flseg, loff_t offset) { - u32 stripe_width = flseg->stripe_unit * flseg->dsaddr->stripe_count; + u64 stripe_width = (u64)flseg->stripe_unit * + flseg->dsaddr->stripe_count; u64 stripe_no; u32 rem; offset -= flseg->pattern_offset; - stripe_no = div_u64(offset, stripe_width); + stripe_no = div64_u64(offset, stripe_width); div_u64_rem(offset, flseg->stripe_unit, &rem); return stripe_no * flseg->stripe_unit + rem; diff --git a/fs/nfs/flexfilelayout/flexfilelayout.c b/fs/nfs/flexfilelayout/flexfilelayout.c index 15980d9dad8e..989f30e7d950 100644 --- a/fs/nfs/flexfilelayout/flexfilelayout.c +++ b/fs/nfs/flexfilelayout/flexfilelayout.c @@ -636,9 +636,12 @@ ff_layout_alloc_lseg(struct pnfs_layout_hdr *lh, if (!p) goto out_sort_mirrors; fls->flags = be32_to_cpup(p); - if (fls->flags & FF_FLAGS_NO_IO_THRU_MDS) + if (fls->flags & FF_FLAGS_NO_IO_THRU_MDS) { set_bit(NFS4_FF_HDR_NO_IO_THRU_MDS, &FF_LAYOUT_FROM_HDR(lh)->flags); + /* Outlives this layout hdr; see NFS_INO_NO_IO_THRU_MDS */ + nfs_set_no_io_thru_mds(lh->plh_inode); + } p = xdr_inline_decode(&stream, 4); if (!p) @@ -961,6 +964,20 @@ ff_layout_get_ds_for_read(struct nfs_pageio_descriptor *pgio, offset, dss_id); } +/* + * Wait before retrying pg_init. Returns false, with pgio->pg_error set, + * if the task was killed or is exiting and must not retry. + */ +static bool ff_layout_pg_retry_wait(struct nfs_pageio_descriptor *pgio) +{ + if (fatal_signal_pending(current) || nfs_current_task_exiting()) { + pgio->pg_error = -ERESTARTSYS; + return false; + } + ssleep(1); + return true; +} + static void ff_layout_pg_get_read(struct nfs_pageio_descriptor *pgio, struct nfs_page *req, @@ -1061,7 +1078,8 @@ ff_layout_pg_init_read(struct nfs_pageio_descriptor *pgio, goto out_mds; pnfs_generic_pg_cleanup(pgio); /* Sleep for 1 second before retrying */ - ssleep(1); + if (!ff_layout_pg_retry_wait(pgio)) + return; goto retry; } @@ -1075,19 +1093,34 @@ ff_layout_pg_init_read(struct nfs_pageio_descriptor *pgio, if (pgio->pg_error < 0) { if (pgio->pg_error != -EAGAIN) return; - /* Retry getting layout segment if lower layer returned -EAGAIN */ - if (pgio->pg_maxretrans && req->wb_nio++ > pgio->pg_maxretrans) { - if (NFS_SERVER(pgio->pg_inode)->flags & NFS_MOUNT_SOFTERR) - pgio->pg_error = -ETIMEDOUT; - else - pgio->pg_error = -EIO; - return; - } - pgio->pg_error = 0; - /* Sleep for 1 second before retrying */ - ssleep(1); - goto retry; + goto retry_nolseg; + } + /* + * No segment, and no error to report either: pnfs_update_layout() + * simply has nothing to give (NFS_LAYOUT_BULK_RECALL, a failed + * pnfs_layout_io_test, blocked LAYOUTGETs, a layout being + * returned). If the server forbids reading this file through the + * MDS there is no fallback to take, so wait for a layout on the + * same terms as the -EAGAIN above. The layout hdr that carried + * FF_FLAGS_NO_IO_THRU_MDS may itself be gone by now, which is why + * this asks the inode and not the hdr. + */ + if (!nfs_no_io_thru_mds(pgio->pg_inode)) + goto out_mds; +retry_nolseg: + /* Retry getting layout segment if lower layer returned -EAGAIN */ + if (pgio->pg_maxretrans && req->wb_nio++ > pgio->pg_maxretrans) { + if (NFS_SERVER(pgio->pg_inode)->flags & NFS_MOUNT_SOFTERR) + pgio->pg_error = -ETIMEDOUT; + else + pgio->pg_error = -EIO; + return; } + pgio->pg_error = 0; + /* Sleep for 1 second before retrying */ + if (!ff_layout_pg_retry_wait(pgio)) + return; + goto retry; out_mds: trace_pnfs_mds_fallback_pg_init_read(pgio->pg_inode, 0, NFS4_MAX_UINT64, IOMODE_READ, @@ -1140,7 +1173,8 @@ ff_layout_pg_init_write(struct nfs_pageio_descriptor *pgio, goto out_mds; pnfs_generic_pg_cleanup(pgio); /* Sleep for 1 second before retrying */ - ssleep(1); + if (!ff_layout_pg_retry_wait(pgio)) + return; goto retry; } pgm = &pgio->pg_mirrors[i]; @@ -1404,6 +1438,23 @@ static int ff_layout_async_handle_error_v4(struct rpc_task *task, if (ff_layout_avoid_mds_available_ds(lseg)) return -NFS4ERR_RESET_TO_PNFS; reset: + /* + * FF_FLAGS_NO_IO_THRU_MDS: never resend through the MDS. The + * caller would do so with force_mds set (ff_layout_reset_read(), + * ff_layout_reset_write(hdr, false) -> pnfs_*_done_resend_to_mds()), + * which builds a descriptor out of the plain MDS page ops and so + * consults no layout at all -- this is the last point at which the + * policy can still be applied. Retry through pNFS instead, which + * takes a fresh LAYOUTGET; that is also the right answer for the + * invalid-layout cases that jump here, since they have just called + * pnfs_destroy_layout(). Having done so they can no longer ask the + * layout hdr about the flag, hence the inode. + */ + if (nfs_no_io_thru_mds(inode)) { + dprintk("%s Retry through pNFS, no MDS fallback. Error %d\n", + __func__, task->tk_status); + return -NFS4ERR_RESET_TO_PNFS; + } dprintk("%s Retry through MDS. Error %d\n", __func__, task->tk_status); return -NFS4ERR_RESET_TO_MDS; diff --git a/fs/nfs/fs_context.c b/fs/nfs/fs_context.c index 1967de7d1dff..a7393ff05494 100644 --- a/fs/nfs/fs_context.c +++ b/fs/nfs/fs_context.c @@ -402,6 +402,7 @@ static void nfs_set_mount_transport_protocol(struct nfs_fs_context *ctx) ctx->mount_server.protocol = XPRT_TRANSPORT_UDP; break; case XPRT_TRANSPORT_TCP: + case XPRT_TRANSPORT_TCP_TLS: case XPRT_TRANSPORT_RDMA: ctx->mount_server.protocol = XPRT_TRANSPORT_TCP; } diff --git a/fs/nfs/internal.h b/fs/nfs/internal.h index abc81f5ae578..ec0b1289864f 100644 --- a/fs/nfs/internal.h +++ b/fs/nfs/internal.h @@ -86,6 +86,7 @@ struct nfs_client_initdata { struct xprtsec_parms xprtsec; unsigned long connect_timeout; unsigned long reconnect_timeout; + rpc_authflavor_t authflavor; /* Auth flavor to use for DS connection */ }; /* @@ -394,6 +395,7 @@ extern unsigned long nfs_access_cache_count(struct shrinker *shrink, struct shrink_control *sc); extern unsigned long nfs_access_cache_scan(struct shrinker *shrink, struct shrink_control *sc); +extern void nfs_drop_nlink(struct inode *inode, unsigned long gencount); struct dentry *nfs_lookup(struct inode *, struct dentry *, unsigned int); void nfs_d_prune_case_insensitive_aliases(struct inode *inode); int nfs_create(struct mnt_idmap *, struct inode *, struct dentry *, @@ -545,6 +547,35 @@ static inline bool nfs_file_io_is_buffered(struct nfs_inode *nfsi) return test_bit(NFS_INO_ODIRECT, &nfsi->flags) == 0; } +/* + * Module-private nfs_inode->flags bit (not in , so no + * exported layout changes): set, and never cleared for the life of the + * in-core inode, once a layout driver has seen the server forbid I/O + * through the MDS for this file (flexfiles sets it from + * FF_FLAGS_NO_IO_THRU_MDS in ff_layout_alloc_lseg()). The RFC 5661 + * mdsthreshold hint must not be acted on for such a file, since the only + * thing pnfs_within_mdsthreshold() can ask for is the one thing the + * layout forbids. Servers are assumed to be consistent in their + * no-fallback policy per file, the same assumption + * ff_layout_hdr_no_fallback_to_mds() already makes; if one were not, the + * only effect is that its mdsthreshold hint - a SHOULD - stops being + * honored for an inode that is already in core. + */ +#define NFS_INO_NO_IO_THRU_MDS (30) + +static inline void nfs_set_no_io_thru_mds(struct inode *inode) +{ + struct nfs_inode *nfsi = NFS_I(inode); + + if (!test_bit(NFS_INO_NO_IO_THRU_MDS, &nfsi->flags)) + set_bit(NFS_INO_NO_IO_THRU_MDS, &nfsi->flags); +} + +static inline bool nfs_no_io_thru_mds(struct inode *inode) +{ + return test_bit(NFS_INO_NO_IO_THRU_MDS, &NFS_I(inode)->flags); +} + /* Must be called with exclusively locked inode->i_rwsem */ static inline void nfs_file_block_o_direct(struct nfs_inode *nfsi) { diff --git a/fs/nfs/nfs3proc.c b/fs/nfs/nfs3proc.c index b80d0c5efc27..b5aa3100b627 100644 --- a/fs/nfs/nfs3proc.c +++ b/fs/nfs/nfs3proc.c @@ -448,13 +448,21 @@ nfs3_proc_remove(struct inode *dir, struct dentry *dentry) .rpc_resp = &res, }; int status = -ENOMEM; + struct inode *inode = d_inode(dentry); + unsigned long gencount; dprintk("NFS call remove %pd2\n", dentry); res.dir_attr = nfs_alloc_fattr(); if (res.dir_attr == NULL) goto out; + if (inode) + gencount = READ_ONCE(NFS_I(inode)->attr_gencount); + status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0); + if (status == 0 && inode) + nfs_drop_nlink(inode, gencount); + nfs_post_op_update_inode(dir, res.dir_attr); nfs_free_fattr(res.dir_attr); out: diff --git a/fs/nfs/nfs4client.c b/fs/nfs/nfs4client.c index b661f446ea49..e7b379f4b4d4 100644 --- a/fs/nfs/nfs4client.c +++ b/fs/nfs/nfs4client.c @@ -229,8 +229,12 @@ struct nfs_client *nfs4_alloc_client(const struct nfs_client_initdata *cl_init) /* * Set up the connection to the server before we add add to the * global list. + * + * Prefer krb5i unless the caller already knows AUTH_UNIX is required. */ - err = nfs_create_rpc_client(clp, cl_init, RPC_AUTH_GSS_KRB5I); + err = -EINVAL; + if (cl_init->authflavor != RPC_AUTH_UNIX) + err = nfs_create_rpc_client(clp, cl_init, RPC_AUTH_GSS_KRB5I); if (err == -EINVAL) err = nfs_create_rpc_client(clp, cl_init, RPC_AUTH_UNIX); if (err < 0) @@ -812,6 +816,7 @@ struct nfs_client *nfs4_set_ds_client(struct nfs_server *mds_srv, .cert_serial = TLS_NO_CERT, .privkey_serial = TLS_NO_PRIVKEY, }, + .authflavor = mds_clp->cl_rpcclient->cl_auth->au_flavor, }; char buf[INET6_ADDRSTRLEN + 1]; diff --git a/fs/nfs/nfs4proc.c b/fs/nfs/nfs4proc.c index e41c792a2725..028459fb6edb 100644 --- a/fs/nfs/nfs4proc.c +++ b/fs/nfs/nfs4proc.c @@ -4969,12 +4969,14 @@ static int nfs4_proc_remove(struct inode *dir, struct dentry *dentry) }; struct inode *inode = d_inode(dentry); int err; + unsigned long gencount; if (inode) { if (inode->i_nlink == 1) nfs4_inode_return_delegation(inode); else nfs4_inode_make_writeable(inode); + gencount = READ_ONCE(NFS_I(inode)->attr_gencount); } do { err = _nfs4_proc_remove(dir, &dentry->d_name, NF4REG); @@ -4982,6 +4984,9 @@ static int nfs4_proc_remove(struct inode *dir, struct dentry *dentry) err = nfs4_handle_exception(NFS_SERVER(dir), err, &exception); } while (exception.retry); + + if (err == 0 && inode) + nfs_drop_nlink(inode, gencount); return err; } diff --git a/fs/nfs/nfs4xdr.c b/fs/nfs/nfs4xdr.c index fc049ce4ba8a..9d0f7ad7525a 100644 --- a/fs/nfs/nfs4xdr.c +++ b/fs/nfs/nfs4xdr.c @@ -5169,8 +5169,7 @@ static int decode_lock_denied(struct xdr_stream *xdr, struct file_lock *fl) p = xdr_decode_hyper(p, &clientid); /* read 8 bytes */ namelen = be32_to_cpup(p); /* read 4 bytes */ /* have read all 32 bytes now */ p = xdr_inline_decode(xdr, namelen); /* variable size field */ - if (likely(!p)) - return -EIO; + /* We have an owner here, return DENIED */ return -NFS4ERR_DENIED; } diff --git a/fs/nfs/pnfs.c b/fs/nfs/pnfs.c index c5d1951d5400..0d51be32b638 100644 --- a/fs/nfs/pnfs.c +++ b/fs/nfs/pnfs.c @@ -2004,7 +2004,9 @@ pnfs_find_lseg(struct pnfs_layout_hdr *lo, * is set to IOMODE_READ for a READ request, and set to IOMODE_RW for a * WRITE request. * - * A return of true means use MDS I/O. + * A return of true means use MDS I/O, so for a file whose layout forbids + * that (see NFS_INO_NO_IO_THRU_MDS) the hint is not evaluated at all: + * there is no answer it could give that this client may act on. * * From rfc 5661: * If a file's size is smaller than the file size threshold, data accesses @@ -2025,6 +2027,14 @@ static bool pnfs_within_mdsthreshold(struct nfs_open_context *ctx, if (t == NULL) return ret; + /* + * The server has told a layout driver that this file's I/O may not + * go through the MDS (flexfiles FF_FLAGS_NO_IO_THRU_MDS). Honor + * that over its own mdsthreshold hint. + */ + if (nfs_no_io_thru_mds(ino)) + return ret; + dprintk("%s bm=0x%x rd_sz=%llu wr_sz=%llu rd_io=%llu wr_io=%llu\n", __func__, t->bm, t->rd_sz, t->wr_sz, t->rd_io_sz, t->wr_io_sz); diff --git a/fs/nfs/proc.c b/fs/nfs/proc.c index 03c2c1f31be9..406d04b52a7d 100644 --- a/fs/nfs/proc.c +++ b/fs/nfs/proc.c @@ -323,9 +323,17 @@ nfs_proc_remove(struct inode *dir, struct dentry *dentry) .rpc_argp = &arg, }; int status; + struct inode *inode = d_inode(dentry); + unsigned long gencount; dprintk("NFS call remove %pd2\n",dentry); + if (inode) + gencount = READ_ONCE(NFS_I(inode)->attr_gencount); + status = rpc_call_sync(NFS_CLIENT(dir), &msg, 0); + if (status == 0 && inode) + nfs_drop_nlink(inode, gencount); + nfs_mark_for_revalidate(dir); dprintk("NFS reply remove: %d\n", status); diff --git a/fs/nfs_common/nfslocalio.c b/fs/nfs_common/nfslocalio.c index 85aa03a7b020..1423a43dbd6e 100644 --- a/fs/nfs_common/nfslocalio.c +++ b/fs/nfs_common/nfslocalio.c @@ -24,6 +24,26 @@ static DEFINE_SPINLOCK(nfs_uuids_lock); * that is protected by nfs_uuids_lock. */ static LIST_HEAD(nfs_uuids); +/* Namespace registration order, protected by nfs_uuids_lock. */ +static u64 nfs_uuid_seq; + +/* The owner waits for temporary users before freeing its nfs_client. */ +static void nfs_uuid_get(nfs_uuid_t *nfs_uuid) +{ + refcount_inc(&nfs_uuid->refs); +} + +static void nfs_uuid_release(nfs_uuid_t *nfs_uuid) +{ + bool released; + + spin_lock(&nfs_uuid->lock); + released = refcount_dec_and_test(&nfs_uuid->refs); + wake_up_var_locked(&nfs_uuid->refs, &nfs_uuid->lock); + spin_unlock(&nfs_uuid->lock); + if (released) + complete(&nfs_uuid->released); +} /* * Lock ordering: @@ -43,6 +63,8 @@ void nfs_uuid_init(nfs_uuid_t *nfs_uuid) INIT_LIST_HEAD(&nfs_uuid->list); INIT_LIST_HEAD(&nfs_uuid->files); spin_lock_init(&nfs_uuid->lock); + refcount_set(&nfs_uuid->refs, 1); + init_completion(&nfs_uuid->released); nfs_uuid->nfs3_localio_probe_count = 0; } EXPORT_SYMBOL_GPL(nfs_uuid_init); @@ -50,7 +72,12 @@ EXPORT_SYMBOL_GPL(nfs_uuid_init); bool nfs_uuid_begin(nfs_uuid_t *nfs_uuid) { spin_lock(&nfs_uuid->lock); - if (rcu_access_pointer(nfs_uuid->net)) { + /* The caller retains the client while temporary UUID users drain. */ + wait_var_event_spinlock(&nfs_uuid->refs, + refcount_read(&nfs_uuid->refs) <= 1, + &nfs_uuid->lock); + if (rcu_access_pointer(nfs_uuid->net) || nfs_uuid->list_lock || + refcount_read(&nfs_uuid->refs) != 1) { /* This nfs_uuid is already in use */ spin_unlock(&nfs_uuid->lock); return false; @@ -77,7 +104,7 @@ void nfs_uuid_end(nfs_uuid_t *nfs_uuid) { if (!rcu_access_pointer(nfs_uuid->net)) { spin_lock(&nfs_uuid->lock); - if (!rcu_access_pointer(nfs_uuid->net)) { + if (!rcu_access_pointer(nfs_uuid->net) && !nfs_uuid->list_lock) { /* Not local, remove from nfs_uuids */ spin_lock(&nfs_uuids_lock); list_del_init(&nfs_uuid->list); @@ -113,28 +140,37 @@ void nfs_uuid_is_local(const uuid_t *uuid, struct list_head *list, spin_unlock(&nfs_uuids_lock); return; } + /* Drop the lookup lock before taking nfs_uuid->lock. */ + nfs_uuid_get(nfs_uuid); + spin_unlock(&nfs_uuids_lock); + + spin_lock(&nfs_uuid->lock); + spin_lock(&nfs_uuids_lock); + /* nfs_uuid_end() may have withdrawn the probe in the meantime. */ + if (nfs_uuid_lookup_locked(uuid) != nfs_uuid) + goto out_unlock; /* * We don't hold a ref on the net, but instead put * ourselves on @list (nn->local_clients) so the net * pointer can be invalidated. */ - spin_lock(list_lock); /* list_lock is nn->local_clients_lock */ - list_move(&nfs_uuid->list, list); - spin_unlock(list_lock); - - spin_unlock(&nfs_uuids_lock); - /* Once nfs_uuid is parented to @list, avoid global nfs_uuids_lock */ - spin_lock(&nfs_uuid->lock); - __module_get(mod); nfsd_mod = mod; + spin_lock(list_lock); /* list_lock is nn->local_clients_lock */ nfs_uuid->list_lock = list_lock; kref_get(&dom->ref); nfs_uuid->dom = dom; rcu_assign_pointer(nfs_uuid->net, net); + nfs_uuid->seq = ++nfs_uuid_seq; + list_move_tail(&nfs_uuid->list, list); + spin_unlock(list_lock); + +out_unlock: + spin_unlock(&nfs_uuids_lock); spin_unlock(&nfs_uuid->lock); + nfs_uuid_release(nfs_uuid); } EXPORT_SYMBOL_GPL(nfs_uuid_is_local); @@ -154,6 +190,10 @@ static bool nfs_uuid_put(nfs_uuid_t *nfs_uuid) struct nfs_file_localio *nfl; spin_lock(&nfs_uuid->lock); + /* A concurrent disabler can drop the lock while closing files. */ + wait_var_event_spinlock(&nfs_uuid->list_lock, + rcu_access_pointer(nfs_uuid->net) || + !nfs_uuid->list_lock, &nfs_uuid->lock); if (unlikely(!rcu_access_pointer(nfs_uuid->net))) { spin_unlock(&nfs_uuid->lock); return false; @@ -211,6 +251,7 @@ static bool nfs_uuid_put(nfs_uuid_t *nfs_uuid) } module_put(nfsd_mod); + wake_up_var_locked(&nfs_uuid->list_lock, &nfs_uuid->lock); spin_unlock(&nfs_uuid->lock); return true; @@ -223,22 +264,50 @@ void nfs_localio_disable_client(struct nfs_client *clp) } EXPORT_SYMBOL_GPL(nfs_localio_disable_client); +void nfs_localio_free_client(struct nfs_client *clp) +{ + nfs_uuid_t *nfs_uuid = &clp->cl_uuid; + + nfs_uuid_end(nfs_uuid); + nfs_localio_disable_client(clp); + /* Unlink before dropping the owner reference, then drain all users. */ + nfs_uuid_release(nfs_uuid); + wait_for_completion(&nfs_uuid->released); +} +EXPORT_SYMBOL_GPL(nfs_localio_free_client); + void nfs_localio_invalidate_clients(struct list_head *nn_local_clients, spinlock_t *nn_local_clients_lock) { - LIST_HEAD(local_clients); - nfs_uuid_t *nfs_uuid, *tmp; + nfs_uuid_t *nfs_uuid; struct nfs_client *clp; + u64 last_seq; spin_lock(nn_local_clients_lock); - list_splice_init(nn_local_clients, &local_clients); - spin_unlock(nn_local_clients_lock); - list_for_each_entry_safe(nfs_uuid, tmp, &local_clients, list) { - if (WARN_ON(nfs_uuid->list_lock != nn_local_clients_lock)) + if (list_empty(nn_local_clients)) + goto out_unlock; + /* New registrations go to the tail and belong to a later sweep. */ + last_seq = list_last_entry(nn_local_clients, nfs_uuid_t, list)->seq; + for (;;) { + nfs_uuid = list_first_entry_or_null(nn_local_clients, + nfs_uuid_t, list); + /* Use a signed difference to allow the sequence to wrap. */ + if (!nfs_uuid || (s64)(nfs_uuid->seq - last_seq) > 0) break; + if (WARN_ON_ONCE(nfs_uuid->list_lock != nn_local_clients_lock)) + break; + /* Teardown unlinks under this lock before dropping its reference. */ + nfs_uuid_get(nfs_uuid); + spin_unlock(nn_local_clients_lock); + clp = container_of(nfs_uuid, struct nfs_client, cl_uuid); nfs_localio_disable_client(clp); + nfs_uuid_release(nfs_uuid); + cond_resched(); + spin_lock(nn_local_clients_lock); } +out_unlock: + spin_unlock(nn_local_clients_lock); } EXPORT_SYMBOL_GPL(nfs_localio_invalidate_clients); diff --git a/fs/nilfs2/namei.c b/fs/nilfs2/namei.c index e037e0c6e31a..d326bb1acb11 100644 --- a/fs/nilfs2/namei.c +++ b/fs/nilfs2/namei.c @@ -341,10 +341,16 @@ static int nilfs_rmdir(struct inode *dir, struct dentry *dentry) err = -ENOTEMPTY; if (nilfs_empty_dir(inode)) { + if (unlikely(inode->i_nlink != 2)) + nilfs_warn(dir->i_sb, + "inconsistent empty directory link count %u (ino=%llu)", + inode->i_nlink, + (unsigned long long)inode->i_ino); + err = nilfs_do_unlink(dir, dentry); if (!err) { inode->i_size = 0; - drop_nlink(inode); + clear_nlink(inode); nilfs_mark_inode_dirty(inode); drop_nlink(dir); nilfs_mark_inode_dirty(dir); diff --git a/fs/nilfs2/recovery.c b/fs/nilfs2/recovery.c index a7086a93480b..01631a35c8ac 100644 --- a/fs/nilfs2/recovery.c +++ b/fs/nilfs2/recovery.c @@ -540,6 +540,23 @@ static int nilfs_recover_dsync_blocks(struct the_nilfs *nilfs, goto failed_inode; } + /* + * Regular files, directories, and symlinks are the only + * inode types with data blocks and an initialized bmap; + * a crafted image can reference some other inode type + * here, whose i_bmap_data was never set up by + * __nilfs_read_inode(). + */ + if (!likely(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || + S_ISLNK(inode->i_mode))) { + nilfs_warn(sb, + "%s: invalid inode type (ino=%lu, mode=0%o)", + __func__, (unsigned long)rb->ino, + inode->i_mode); + err = -EINVAL; + goto failed_inode; + } + pos = rb->blkoff << inode->i_blkbits; err = block_write_begin(inode->i_mapping, pos, blocksize, &folio, nilfs_get_block); diff --git a/fs/nsfs.c b/fs/nsfs.c index c3b6ae76594a..0ef4e1455b7a 100644 --- a/fs/nsfs.c +++ b/fs/nsfs.c @@ -529,8 +529,8 @@ static struct dentry *nsfs_fh_to_dentry(struct super_block *sb, struct fid *fh, /* Check that any trailing bytes are zero. */ if ((fh_len > NSFS_FID_SIZE_U32_LATEST) && - memchr_inv((void *)fid + NSFS_FID_SIZE_U32_LATEST, 0, - fh_len - NSFS_FID_SIZE_U32_LATEST)) + memchr_inv((void *)fid + NSFS_FILE_HANDLE_SIZE_LATEST, 0, + (fh_len - NSFS_FID_SIZE_U32_LATEST) * sizeof(u32))) return NULL; switch (fh_type) { diff --git a/fs/ntfs/aops.c b/fs/ntfs/aops.c index 517d9a1563e7..ad781674fef1 100644 --- a/fs/ntfs/aops.c +++ b/fs/ntfs/aops.c @@ -240,10 +240,11 @@ static void ntfs_readahead(struct readahead_control *rac) }; /* - * Resident files are not cached in the page cache, - * and readahead is not implemented for compressed files. + * Resident files are not cached in the page cache, readahead is not + * implemented for compressed files, and ntfs_read_folio() refuses + * encrypted files because decryption is not implemented. */ - if (!NInoNonResident(ni) || NInoCompressed(ni) || + if (!NInoNonResident(ni) || NInoEncrypted(ni) || NInoCompressed(ni) || NInoWofCompressed(ni)) return; iomap_readahead(&ntfs_read_iomap_ops, &ctx, NULL); diff --git a/fs/ntfs/attrib.c b/fs/ntfs/attrib.c index 1f64680d5c8f..ee54ebdeb7c7 100644 --- a/fs/ntfs/attrib.c +++ b/fs/ntfs/attrib.c @@ -733,8 +733,12 @@ static bool ntfs_non_resident_attr_value_is_valid(const struct attr_record *a) min_len = offsetof(struct attr_record, data.non_resident.initialized_size) + sizeof(a->data.non_resident.initialized_size); - /* Sparse and compressed attributes have the extra compressed_size field */ - if (a->flags & (ATTR_IS_SPARSE | ATTR_COMPRESSION_MASK)) + /* + * Only the first extent of sparse and compressed attributes has the + * extra compressed_size field. + */ + if ((a->flags & (ATTR_IS_SPARSE | ATTR_COMPRESSION_MASK)) && + !a->data.non_resident.lowest_vcn) min_len += sizeof(a->data.non_resident.compressed_size); if (attr_len < min_len) @@ -5183,6 +5187,8 @@ int ntfs_attr_truncate_i_locked(struct ntfs_inode *ni, const s64 newsize, ni, newsize, locked_ni, false); } else err = ntfs_resident_attr_resize(ni, newsize, 0, holes); + if (!err && NInoAttr(ni)) + i_size_write(VFS_I(ni), newsize); ntfs_debug("Return status %d\n", err); return err; } diff --git a/fs/ntfs/attrlist.c b/fs/ntfs/attrlist.c index 78e9a1dc7925..6edd5d2d9bf2 100644 --- a/fs/ntfs/attrlist.c +++ b/fs/ntfs/attrlist.c @@ -256,6 +256,9 @@ int ntfs_attrlist_update_locked(struct ntfs_inode *base_ni, return err; } + /* ntfs_attrlist_repack() below reads the list up to i_size. */ + i_size_write(attr_vi, base_ni->attr_list_size); + /* * Reserve the maximum legal list size while the MFT metadata area is * still easy to allocate contiguously. This prevents a later list entry @@ -283,8 +286,6 @@ int ntfs_attrlist_update_locked(struct ntfs_inode *base_ni, } } - i_size_write(attr_vi, base_ni->attr_list_size); - if (NInoNonResident(attr_ni) && !NInoAttrListNonResident(base_ni)) NInoSetAttrListNonResident(base_ni); @@ -337,8 +338,8 @@ int ntfs_attrlist_entry_add(struct ntfs_inode *ni, struct attr_record *attr) ni_mrec = map_mft_record(ni); if (IS_ERR(ni_mrec)) { - ntfs_debug("Invalid arguments.\n"); - return -EIO; + ntfs_debug("Failed to map mft record.\n"); + return PTR_ERR(ni_mrec); } mref = MK_LE_MREF(ni->mft_no, le16_to_cpu(ni_mrec->sequence_number)); diff --git a/fs/ntfs/bitmap.c b/fs/ntfs/bitmap.c index 5a4457551306..912fdcca8e01 100644 --- a/fs/ntfs/bitmap.c +++ b/fs/ntfs/bitmap.c @@ -20,7 +20,7 @@ int ntfs_trim_fs(struct ntfs_volume *vol, struct fstrim_range *range) struct folio *folio; unsigned long *bitmap; char *kaddr; - u64 end, trimmed = 0, start_buf, end_buf, end_cluster; + u64 end, trimmed = 0, start_buf, end_buf, end_cluster, page_cluster; u64 start_cluster = ntfs_bytes_to_cluster(vol, range->start); u32 dq = bdev_discard_granularity(vol->sb->s_bdev); int ret = 0; @@ -45,8 +45,8 @@ int ntfs_trim_fs(struct ntfs_volume *vol, struct fstrim_range *range) return -ENOMEM; buf_clusters = PAGE_SIZE * 8; - start_index = start_cluster >> 15; - end_index = (end_cluster + buf_clusters - 1) >> 15; + start_index = start_cluster / buf_clusters; + end_index = DIV_ROUND_UP_ULL(end_cluster, buf_clusters); for (index = start_index; index < end_index; index++) { folio = ntfs_get_locked_folio(vol->lcnbmp_ino->i_mapping, @@ -59,19 +59,20 @@ int ntfs_trim_fs(struct ntfs_volume *vol, struct fstrim_range *range) kaddr = kmap_local_folio(folio, 0); bitmap = (unsigned long *)kaddr; - start_buf = max_t(u64, index * buf_clusters, start_cluster); - end_buf = min_t(u64, (index + 1) * buf_clusters, end_cluster); + page_cluster = (u64)index * buf_clusters; + start_buf = max_t(u64, page_cluster, start_cluster); + end_buf = min_t(u64, page_cluster + buf_clusters, end_cluster); end = start_buf; while (end < end_buf) { u64 aligned_start, aligned_end, aligned_count; - u64 start = find_next_zero_bit(bitmap, end_buf - start_buf, - end - start_buf) + start_buf; + u64 start = find_next_zero_bit(bitmap, end_buf - page_cluster, + end - page_cluster) + page_cluster; if (start >= end_buf) break; - end = find_next_bit(bitmap, end_buf - start_buf, - start - start_buf) + start_buf; + end = find_next_bit(bitmap, end_buf - page_cluster, + start - page_cluster) + page_cluster; aligned_start = ALIGN(ntfs_cluster_to_bytes(vol, start), dq); aligned_end = ALIGN_DOWN(ntfs_cluster_to_bytes(vol, end), dq); diff --git a/fs/ntfs/collate.c b/fs/ntfs/collate.c index 77e34038902d..744fdfd7bf58 100644 --- a/fs/ntfs/collate.c +++ b/fs/ntfs/collate.c @@ -73,7 +73,7 @@ static int ntfs_collate_ntofs_ulongs(struct ntfs_volume *vol, if (data1_len != data2_len || data1_len & 3) { ntfs_error(vol->sb, "data1_len or data2_len not valid\n"); - return -1; + return -EINVAL; } len = data1_len; diff --git a/fs/ntfs/compress.c b/fs/ntfs/compress.c index 075b57fc1de6..82c7c7d29073 100644 --- a/fs/ntfs/compress.c +++ b/fs/ntfs/compress.c @@ -182,8 +182,8 @@ static int ntfs_decompress(struct page *dest_pages[], int completed_pages[], u8 *dp_addr; /* Current pointer into dp. */ u8 *dp_sb_start; /* Start of current sub-block in dp. */ u8 *dp_sb_end; /* End of current sb in dp (dp_sb_start + NTFS_SB_SIZE). */ - u16 do_sb_start; /* @dest_ofs when starting this sub-block. */ - u16 do_sb_end; /* @dest_ofs of end of this sb (do_sb_start + NTFS_SB_SIZE). */ + int do_sb_start; /* @dest_ofs when starting this sub-block. */ + int do_sb_end; /* @dest_ofs of end of this sb (do_sb_start + NTFS_SB_SIZE). */ /* Variables for tag and token parsing. */ u8 tag; /* Current tag. */ diff --git a/fs/ntfs/dir.c b/fs/ntfs/dir.c index 09b890b41c4a..b72990c2dd58 100644 --- a/fs/ntfs/dir.c +++ b/fs/ntfs/dir.c @@ -331,7 +331,6 @@ u64 ntfs_lookup_inode_by_name(struct ntfs_inode *dir_ni, const __le16 *uname, } memcpy_from_folio(kaddr, folio, 0, PAGE_SIZE); - post_read_mst_fixup((struct ntfs_record *)kaddr, PAGE_SIZE); folio_unlock(folio); folio_put(folio); fast_descend_into_child_node: @@ -352,6 +351,14 @@ u64 ntfs_lookup_inode_by_name(struct ntfs_inode *dir_ni, const __le16 *uname, vcn, dir_ni->mft_no); goto unm_err_out; } + err = post_read_mst_fixup((struct ntfs_record *)ia, + dir_ni->itype.index.block_size); + if (err) { + ntfs_error(sb, + "MST fixup failed for index block vcn %lld in directory inode 0x%llx.", + vcn, dir_ni->mft_no); + goto unm_err_out; + } err = ntfs_index_block_inconsistent(vol, ia, dir_ni->itype.index.block_size, vcn, COLLATION_FILE_NAME, @@ -628,11 +635,11 @@ static inline int ntfs_filldir(struct ntfs_volume *vol, } mref = MREF_LE(ie->data.dir.indexed_file); - if (ie->key.file_name.file_attributes & + if (ie->key.file_name.file_attributes & FILE_ATTR_REPARSE_POINT) + dt_type = ntfs_reparse_tag_dt_types(vol, mref); + else if (ie->key.file_name.file_attributes & FILE_ATTR_DUP_FILE_NAME_INDEX_PRESENT) dt_type = DT_DIR; - else if (ie->key.file_name.file_attributes & FILE_ATTR_REPARSE_POINT) - dt_type = ntfs_reparse_tag_dt_types(vol, mref); else dt_type = DT_REG; diff --git a/fs/ntfs/ea.c b/fs/ntfs/ea.c index 9e00588ff9b5..082db077a4ed 100644 --- a/fs/ntfs/ea.c +++ b/fs/ntfs/ea.c @@ -37,7 +37,7 @@ static int ntfs_write_ea(struct ntfs_inode *ni, __le32 type, char *value, s64 ea struct ntfs_inode *ea_ni = NTFS_I(ea_vi); if (need_truncate && ea_ni->data_size > ea_off + ea_size) - ntfs_attr_truncate(ea_ni, ea_off + ea_size); + err = ntfs_attr_truncate(ea_ni, ea_off + ea_size); mark_mft_record_dirty(ni); } diff --git a/fs/ntfs/file.c b/fs/ntfs/file.c index f8f4418cbcda..dd98cb3ac5e5 100644 --- a/fs/ntfs/file.c +++ b/fs/ntfs/file.c @@ -475,8 +475,8 @@ static ssize_t ntfs_file_read_iter(struct kiocb *iocb, struct iov_iter *to) if (NVolShutdown(NTFS_SB(sb))) return -EIO; - if ((NInoCompressed(NTFS_I(vi)) || NInoWofCompressed(NTFS_I(vi))) && - iocb->ki_flags & IOCB_DIRECT) + if ((NInoCompressed(NTFS_I(vi)) || NInoWofCompressed(NTFS_I(vi)) || + NInoEncrypted(NTFS_I(vi))) && iocb->ki_flags & IOCB_DIRECT) return -EOPNOTSUPP; inode_lock_shared(vi); @@ -540,8 +540,21 @@ static ssize_t ntfs_dio_write_iter(struct kiocb *iocb, struct iov_iter *from) ssize_t written; int ret2; + if (iocb->ki_flags & IOCB_NOWAIT) { + if (!ret) + ret = -EAGAIN; + goto out; + } + offset = iocb->ki_pos; iocb->ki_flags &= ~IOCB_DIRECT; + + /* + * Prevent concurrent direct I/O and buffered I/O to the same file + * range. Wait for in-flight DIO to finish before dirtying pages. + */ + inode_dio_wait(file_inode(iocb->ki_filp)); + written = iomap_file_buffered_write(iocb, from, &ntfs_write_iomap_ops, &ntfs_iomap_folio_ops, NULL); @@ -888,7 +901,7 @@ static int ntfs_ioctl_fitrim(struct ntfs_volume *vol, unsigned long arg) if (range.len < vol->cluster_size) return -EINVAL; - range.minlen = max_t(u32, range.minlen, bdev_discard_granularity(dev)); + range.minlen = max_t(u64, range.minlen, bdev_discard_granularity(dev)); err = ntfs_trim_fs(vol, &range); if (err < 0) @@ -1163,9 +1176,6 @@ static long ntfs_fallocate(struct file *file, int mode, loff_t offset, loff_t le if (!NVolFreeClusterKnown(vol)) wait_event(vol->free_waitq, NVolFreeClusterKnown(vol)); - if ((ni->vol->mft_zone_end - ni->vol->mft_zone_start) == 0) - return -ENOSPC; - if (NInoNonResident(ni) && !NInoFullyMapped(ni)) { down_write(&ni->runlist.lock); err = ntfs_attr_map_whole_runlist(ni); diff --git a/fs/ntfs/index.c b/fs/ntfs/index.c index 580998990bc9..9a23d0786959 100644 --- a/fs/ntfs/index.c +++ b/fs/ntfs/index.c @@ -489,6 +489,14 @@ static struct index_entry *ntfs_ie_dup_novcn(struct index_entry *ie) return dup; } +/* Offset of the first entry in an index block created by ntfs_ib_alloc(). */ +static u32 ntfs_ib_canonical_entries_offset(u32 block_size) +{ + u32 usa_count = block_size / NTFS_BLOCK_SIZE + 1; + + return (sizeof(struct index_header) + usa_count * 2 + 7) & ~7; +} + /* * Check the consistency of an index block * @@ -548,6 +556,16 @@ int ntfs_index_block_inconsistent(struct ntfs_volume *vol, offsetof(struct index_block, index), inum)) return -EIO; + + if (le32_to_cpu(ib->index.entries_offset) < + ntfs_ib_canonical_entries_offset(block_size)) { + ntfs_error(sb, + "Index block: entries offset %u is below the minimum for a %u-byte block: vcn %lld inode %llu\n", + le32_to_cpu(ib->index.entries_offset), block_size, + vcn, inum); + return -EIO; + } + if (ntfs_index_entries_inconsistent(vol, &ib->index, cr, inum)) return -EIO; return 0; @@ -812,6 +830,9 @@ static int ntfs_icx_parent_dec(struct ntfs_index_context *icx) * after the search @key, i.e. this is the position in the index at which * an index entry with a key of @key would need to be inserted. * + * If the index cannot be searched, a negative error code other than -ENOENT + * is returned and @icx does not describe a valid index entry. + * * When finished with the entry and its data, call ntfs_index_ctx_put() to free * the context and other associated resources. * @@ -877,7 +898,7 @@ int ntfs_index_lookup(const void *key, const u32 key_len, struct ntfs_index_cont /* Child node present, descend into it. */ icx->ia_ni = ntfs_ia_open(icx, ni); if (!icx->ia_ni) { - err = -ENOENT; + err = -EIO; goto err_out; } @@ -957,8 +978,8 @@ static struct index_block *ntfs_ib_alloc(s64 ib_vcn, u32 ib_size, *(__le16 *)((char *)ib + le16_to_cpu(ib->usa_ofs)) = cpu_to_le16(1); ib->lsn = 0; ib->index_block_vcn = cpu_to_le64(ib_vcn); - ib->index.entries_offset = cpu_to_le32((ih_size + - le16_to_cpu(ib->usa_count) * 2 + 7) & ~7); + ib->index.entries_offset = + cpu_to_le32(ntfs_ib_canonical_entries_offset(ib_size)); ib->index.index_length = 0; ib->index.allocated_size = cpu_to_le32(ib_size - (sizeof(struct index_block) - ih_size)); diff --git a/fs/ntfs/inode.c b/fs/ntfs/inode.c index 213c4a12b33a..64c415edc398 100644 --- a/fs/ntfs/inode.c +++ b/fs/ntfs/inode.c @@ -8,6 +8,7 @@ #include #include +#include #include "lcnalloc.h" #include "time.h" @@ -651,6 +652,25 @@ void ntfs_set_vfs_operations(struct inode *inode, mode_t mode, dev_t dev) } } +static bool ntfs_non_resident_sizes_inconsistent(struct inode *vi, + const struct attr_record *a) +{ + s64 allocated_size = le64_to_cpu(a->data.non_resident.allocated_size); + s64 data_size = le64_to_cpu(a->data.non_resident.data_size); + s64 initialized_size = le64_to_cpu(a->data.non_resident.initialized_size); + + if (initialized_size >= 0 && initialized_size <= data_size && + data_size <= allocated_size && + !ntfs_bytes_to_cluster_off(NTFS_I(vi)->vol, allocated_size)) + return false; + + ntfs_error(vi->i_sb, + "Attribute 0x%x of inode 0x%llx is corrupt (initialized size %lld, data size %lld, allocated size %lld).", + le32_to_cpu(a->type), NTFS_I(vi)->mft_no, initialized_size, + data_size, allocated_size); + return true; +} + /* * ntfs_read_locked_inode - read an inode from its device * @vi: inode to read @@ -1138,6 +1158,11 @@ static int ntfs_read_locked_inode(struct inode *vi) } if (a->non_resident) { NInoSetNonResident(ni); + if (a->data.non_resident.lowest_vcn) { + ntfs_error(vi->i_sb, + "First extent of $DATA attribute has non zero lowest_vcn."); + goto unm_err_out; + } if (NInoCompressed(ni) || (NInoSparse(ni) && !NInoWofCompressed(ni))) { if (NInoCompressed(ni) && a->data.non_resident.compression_unit != 4) { @@ -1148,14 +1173,21 @@ static int ntfs_read_locked_inode(struct inode *vi) goto unm_err_out; } + /* + * Windows stores the standard compression unit in + * sparse attributes even when the data is not compressed. + */ if (NInoSparse(ni) && a->data.non_resident.compression_unit && a->data.non_resident.compression_unit != - vol->sparse_compression_unit) { + vol->sparse_compression_unit && + a->data.non_resident.compression_unit != + STANDARD_COMPRESSION_UNIT) { ntfs_error(vi->i_sb, - "Found non-standard compression unit (%u instead of 0 or %d). Cannot handle this.", + "Found non-standard compression unit (%u instead of 0, %d, or %d). Cannot handle this.", a->data.non_resident.compression_unit, - vol->sparse_compression_unit); + vol->sparse_compression_unit, + STANDARD_COMPRESSION_UNIT); err = -EOPNOTSUPP; goto unm_err_out; } @@ -1179,11 +1211,8 @@ static int ntfs_read_locked_inode(struct inode *vi) ni->itype.compressed.size = le64_to_cpu( a->data.non_resident.compressed_size); } - if (a->data.non_resident.lowest_vcn) { - ntfs_error(vi->i_sb, - "First extent of $DATA attribute has non zero lowest_vcn."); + if (ntfs_non_resident_sizes_inconsistent(vi, a)) goto unm_err_out; - } vi->i_size = ni->data_size = le64_to_cpu(a->data.non_resident.data_size); ni->initialized_size = le64_to_cpu(a->data.non_resident.initialized_size); ni->allocated_size = le64_to_cpu(a->data.non_resident.allocated_size); @@ -1407,6 +1436,10 @@ static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi) } } else { NInoSetNonResident(ni); + if (a->data.non_resident.lowest_vcn) { + ntfs_error(vi->i_sb, "First extent of attribute has non-zero lowest_vcn."); + goto unm_err_out; + } /* * Ensure the attribute name is placed before the mapping pairs * array. @@ -1442,10 +1475,8 @@ static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi) ni->itype.compressed.size = le64_to_cpu( a->data.non_resident.compressed_size); } - if (a->data.non_resident.lowest_vcn) { - ntfs_error(vi->i_sb, "First extent of attribute has non-zero lowest_vcn."); + if (ntfs_non_resident_sizes_inconsistent(vi, a)) goto unm_err_out; - } vi->i_size = ni->data_size = le64_to_cpu(a->data.non_resident.data_size); ni->initialized_size = le64_to_cpu(a->data.non_resident.initialized_size); ni->allocated_size = le64_to_cpu(a->data.non_resident.allocated_size); @@ -1675,6 +1706,8 @@ static int ntfs_read_locked_index_inode(struct inode *base_vi, struct inode *vi) "First extent of $INDEX_ALLOCATION attribute has non zero lowest_vcn."); goto unm_err_out; } + if (ntfs_non_resident_sizes_inconsistent(vi, a)) + goto unm_err_out; vi->i_size = ni->data_size = le64_to_cpu(a->data.non_resident.data_size); ni->initialized_size = le64_to_cpu(a->data.non_resident.initialized_size); ni->allocated_size = le64_to_cpu(a->data.non_resident.allocated_size); @@ -2008,6 +2041,8 @@ int ntfs_read_inode_mount(struct inode *vi) "Attribute list has non zero lowest_vcn. $MFT is corrupt. You should run chkdsk."); goto put_err_out; } + if (ntfs_non_resident_sizes_inconsistent(vi, a)) + goto put_err_out; rl = ntfs_mapping_pairs_decompress(vol, a, NULL, &new_rl_count); if (IS_ERR(rl)) { @@ -2450,38 +2485,50 @@ int ntfs_extend_initialized_size(struct inode *vi, const loff_t offset, const loff_t new_size) { struct ntfs_inode *ni = NTFS_I(vi); - loff_t old_init_size; + loff_t old_init_size, clear_size; unsigned long flags; - int err; + int err = 0; + + if (!NInoNonResident(ni)) + return -EINVAL; + filemap_invalidate_lock(vi->i_mapping); read_lock_irqsave(&ni->size_lock, flags); old_init_size = ni->initialized_size; read_unlock_irqrestore(&ni->size_lock, flags); - if (!NInoNonResident(ni)) - return -EINVAL; if (old_init_size >= new_size) - return 0; + goto out; err = ntfs_attr_map_whole_runlist(ni); if (err) - return err; + goto out; - if (!NInoCompressed(ni) && old_init_size < offset) { - err = iomap_zero_range(vi, old_init_size, - offset - old_init_size, - NULL, &ntfs_seek_iomap_ops, - &ntfs_iomap_folio_ops, NULL); - if (err) - return err; + if (!NInoCompressed(ni)) { + /* + * Zeroing skips holes, so discard cached uninitialized bytes + * before making them visible to writes or shared mappings. + */ + clear_size = max_t(loff_t, i_size_read(vi), new_size); + truncate_pagecache_range(vi, old_init_size, clear_size - 1); + + if (old_init_size < offset) { + err = iomap_zero_range(vi, old_init_size, + offset - old_init_size, + NULL, &ntfs_seek_iomap_ops, + &ntfs_iomap_folio_ops, NULL); + if (err) + goto out; + } } - mutex_lock(&ni->mrec_lock); err = ntfs_attr_set_initialized_size(ni, new_size); mutex_unlock(&ni->mrec_lock); if (err) truncate_setsize(vi, old_init_size); +out: + filemap_invalidate_unlock(vi->i_mapping); return err; } @@ -2943,8 +2990,7 @@ int __ntfs_write_inode(struct inode *vi, int sync) * abort if deprotection or checks fail. * * Finally attach the ntfs inode to its base inode @base_ni and return a - * pointer to the ntfs_inode structure on success or NULL on error, with errno - * set to the error code. + * pointer to the ntfs_inode structure on success or ERR_PTR() on error. * * Note, extent inodes are never closed directly. They are automatically * disposed off by the closing of the base inode. @@ -2960,7 +3006,7 @@ static struct ntfs_inode *ntfs_extent_inode_open(struct ntfs_inode *base_ni, struct super_block *sb; if (!base_ni) - return NULL; + return ERR_PTR(-EINVAL); sb = base_ni->vol->sb; ntfs_debug("Opening extent inode %llu (base mft record %llu).\n", @@ -2979,7 +3025,7 @@ static struct ntfs_inode *ntfs_extent_inode_open(struct ntfs_inode *base_ni, if (IS_ERR(ni_mrec)) { ntfs_error(sb, "failed to map mft record for %llu", ni->mft_no); - goto out; + return ERR_CAST(ni_mrec); } /* Verify the sequence number if given. */ seq_no = MSEQNO_LE(mref); @@ -2988,7 +3034,7 @@ static struct ntfs_inode *ntfs_extent_inode_open(struct ntfs_inode *base_ni, ntfs_error(sb, "Found stale extent mft reference mft=%llu", ni->mft_no); unmap_mft_record(ni); - goto out; + return ERR_PTR(-EIO); } unmap_mft_record(ni); goto out; @@ -2997,7 +3043,7 @@ static struct ntfs_inode *ntfs_extent_inode_open(struct ntfs_inode *base_ni, /* Wasn't there, we need to load the extent inode. */ ni = ntfs_new_extent_inode(base_ni->vol->sb, mft_no); if (!ni) - goto out; + return ERR_PTR(-ENOMEM); ni->seq_no = (u16)MSEQNO_LE(mref); ni->nr_extents = -1; @@ -3007,8 +3053,10 @@ static struct ntfs_inode *ntfs_extent_inode_open(struct ntfs_inode *base_ni, i = (base_ni->nr_extents + 4) * sizeof(struct ntfs_inode *); extent_nis = kvzalloc(i, GFP_NOFS); - if (!extent_nis) - goto err_out; + if (!extent_nis) { + ntfs_destroy_ext_inode(ni); + return ERR_PTR(-ENOMEM); + } if (base_ni->nr_extents) { memcpy(extent_nis, base_ni->ext.extent_ntfs_inos, i - 4 * sizeof(struct ntfs_inode *)); @@ -3021,10 +3069,6 @@ static struct ntfs_inode *ntfs_extent_inode_open(struct ntfs_inode *base_ni, out: ntfs_debug("\n"); return ni; -err_out: - ntfs_destroy_ext_inode(ni); - ni = NULL; - goto out; } /* @@ -3062,9 +3106,12 @@ int ntfs_inode_attach_all_extents(struct ntfs_inode *ni) while ((u8 *)ale < ni->attr_list + ni->attr_list_size) { if (ni->mft_no != MREF_LE(ale->mft_reference) && prev_attached != MREF_LE(ale->mft_reference)) { - if (!ntfs_extent_inode_open(ni, ale->mft_reference)) { + struct ntfs_inode *ext_ni; + + ext_ni = ntfs_extent_inode_open(ni, ale->mft_reference); + if (IS_ERR(ext_ni)) { ntfs_debug("Couldn't attach extent inode.\n"); - return -1; + return PTR_ERR(ext_ni); } prev_attached = MREF_LE(ale->mft_reference); } @@ -3657,9 +3704,10 @@ static inline int ntfs_enlarge_attribute(struct inode *vi, s64 pos, s64 count, return -EOPNOTSUPP; if (pos + count > ni->data_size) { - if (ntfs_attr_truncate(ni, pos + count)) { + ret = ntfs_attr_truncate(ni, pos + count); + if (ret) { ntfs_debug("Failed to truncate attribute"); - return -1; + return ret; } ntfs_attr_reinit_search_ctx(ctx); @@ -3747,7 +3795,7 @@ static s64 __ntfs_inode_non_resident_attr_pwrite(struct inode *vi, index = pos >> PAGE_SHIFT; while (count) { - if (count == PAGE_SIZE) { + if (count == PAGE_SIZE && !offset_in_page(pos)) { folio = __filemap_get_folio(vi->i_mapping, index, FGP_CREAT | FGP_LOCK, mapping_gfp_mask(mapping)); @@ -3769,7 +3817,7 @@ static s64 __ntfs_inode_non_resident_attr_pwrite(struct inode *vi, folio_wait_writeback(folio); - if (count == PAGE_SIZE) { + if (count == PAGE_SIZE && !offset_in_page(pos)) { offset = 0; attr_len = count; } else { diff --git a/fs/ntfs/layout.h b/fs/ntfs/layout.h index 9438fd9b668e..e4d246f0159f 100644 --- a/fs/ntfs/layout.h +++ b/fs/ntfs/layout.h @@ -811,14 +811,17 @@ enum { * on XP SP2+. * @data.non_resident.reserved: 5 bytes for 8-byte alignment. * @data.non_resident.allocated_size: - * Allocated disk space in bytes. - * For compressed: logical allocated size. + * Allocated size in bytes, a multiple of + * the cluster size. For compressed and + * sparse attributes holes count as + * allocated; the clusters actually in use + * are in compressed_size. * @data.non_resident.data_size: Logical attribute value size in bytes. - * Can be larger than allocated_size if - * compressed/sparse. + * Never larger than allocated_size, also + * when compressed/sparse. * @data.non_resident.initialized_size: * Initialized portion size in bytes. - * Usually equals data_size. + * Usually equals data_size, never larger. * @data.non_resident.compressed_size: * Compressed on-disk size in bytes. * Only present when compressed or sparse. diff --git a/fs/ntfs/lcnalloc.c b/fs/ntfs/lcnalloc.c index 0d6cd08ee2e7..3ebcac4c2864 100644 --- a/fs/ntfs/lcnalloc.c +++ b/fs/ntfs/lcnalloc.c @@ -375,6 +375,16 @@ struct runlist_element *ntfs_cluster_alloc(struct ntfs_volume *vol, const s64 st has_guess = 1; continue; } + /* + * A contiguous request gets a single run. The scan can + * move on without testing the clusters after the run + * (past a bitmap page that is full, to pass 2 or to + * another zone), so return the run when this cluster + * does not follow it. + */ + if (is_contig && rlpos && + lcn + bmp_pos != prev_lcn + prev_run_len) + goto out; /* * Allocate more memory if needed, including space for * the terminator element. @@ -506,13 +516,32 @@ struct runlist_element *ntfs_cluster_alloc(struct ntfs_volume *vol, const s64 st } if (!used_zone_pos) { + /* + * The run at @start_lcn reached the end of the buffer + * or the zone. A contiguous request gets that run + * alone, not a second one from the zone position. + */ + if (is_contig && rlpos) + goto out; + /* + * Leaving @start_lcn for the zone position starts the + * zone over as if no hint had been given, even if the + * search had already reached pass 2, whose range ends + * at @start_lcn. + */ used_zone_pos = 1; - if (search_zone == 1) + has_guess = 0; + pass = 1; + if (search_zone == 1) { zone_start = vol->mft_zone_pos; - else if (search_zone == 2) + zone_end = vol->mft_zone_end; + } else if (search_zone == 2) { zone_start = vol->data1_zone_pos; - else + zone_end = vol->nr_clusters; + } else { zone_start = vol->data2_zone_pos; + zone_end = vol->mft_zone_start; + } if (!zone_start || zone_start == vol->mft_zone_start || zone_start == vol->mft_zone_end) diff --git a/fs/ntfs/logfile.c b/fs/ntfs/logfile.c index ce38ce87f8fc..2f27ae7a3927 100644 --- a/fs/ntfs/logfile.c +++ b/fs/ntfs/logfile.c @@ -27,7 +27,7 @@ static bool ntfs_check_restart_page_header(struct inode *vi, struct restart_page_header *rp, s64 pos) { u32 logfile_system_page_size, logfile_log_page_size; - u16 ra_ofs, usa_count, usa_ofs, usa_end = 0; + u32 ra_ofs, usa_count, usa_ofs, usa_end = 0; bool have_usa = true; ntfs_debug("Entering."); diff --git a/fs/ntfs/mft.c b/fs/ntfs/mft.c index 482a216ade2c..04ea38a82438 100644 --- a/fs/ntfs/mft.c +++ b/fs/ntfs/mft.c @@ -1352,6 +1352,10 @@ static int ntfs_mft_bitmap_extend_allocation_nolock(struct ntfs_volume *vol) size_t new_rl_count; ntfs_debug("Extending mft bitmap allocation."); + /* The initial bitmap scan must finish before we lock or change a folio. */ + if (!NVolFreeClusterKnown(vol)) + wait_event(vol->free_waitq, NVolFreeClusterKnown(vol)); + mft_ni = NTFS_I(vol->mft_ino); mftbmp_ni = NTFS_I(vol->mftbmp_ino); /* @@ -1395,10 +1399,18 @@ static int ntfs_mft_bitmap_extend_allocation_nolock(struct ntfs_volume *vol) folio_lock(folio); b = (u8 *)kmap_local_folio(folio, 0) + (ll & ~PAGE_MASK); tb = 1 << (lcn & 7ull); - if (*b != 0xff && !(*b & tb)) { + /* + * A page skipped by the initial scan has no free bits recorded. + * Honor that and the space reserved for delayed allocation. + */ + if (*b != 0xff && !(*b & tb) && + vol->lcn_empty_bits_per_page[ll >> PAGE_SHIFT] && + ntfs_available_clusters_count(vol, 1) > 0) { /* Next cluster is free, allocate it. */ *b |= tb; folio_mark_dirty(folio); + ntfs_dec_free_clusters(vol, 1); + ntfs_set_lcn_empty_bits(vol, ll >> PAGE_SHIFT, 1, 1); folio_unlock(folio); kunmap_local(b); folio_put(folio); diff --git a/fs/ntfs/mst.c b/fs/ntfs/mst.c index 7f9faad924ad..cc6363413449 100644 --- a/fs/ntfs/mst.c +++ b/fs/ntfs/mst.c @@ -19,7 +19,7 @@ * magic of the ntfs record header being processed with "BAAD" (in memory only!) * and abort processing. * - * Return 0 on success and -EINVAL on error ("BAAD" magic will be present). + * Return 0 on success and -EIO on error ("BAAD" magic will be present). * * NOTE: We consider the absence / invalidity of an update sequence array to * mean that the structure is not protected at all and hence doesn't need to @@ -71,7 +71,7 @@ int post_read_mst_fixup(struct ntfs_record *b, const u32 size) * Note that magic_BAAD is already converted to le32. */ b->magic = magic_BAAD; - return -EINVAL; + return -EIO; } data_pos += NTFS_BLOCK_SIZE / sizeof(u16); } diff --git a/fs/ntfs/reparse.c b/fs/ntfs/reparse.c index 1a6073e22677..2a6480211fe3 100644 --- a/fs/ntfs/reparse.c +++ b/fs/ntfs/reparse.c @@ -676,7 +676,7 @@ static int update_reparse_data(struct ntfs_inode *ni, struct ntfs_index_context rp_inode = ntfs_attr_iget(VFS_I(ni), AT_REPARSE_POINT, AT_UNNAMED, 0); if (IS_ERR(rp_inode)) - return -EINVAL; + return PTR_ERR(rp_inode); rp_ni = NTFS_I(rp_inode); /* remove the existing reparse data */ diff --git a/fs/ntfs/runlist.c b/fs/ntfs/runlist.c index 89e13a452a84..76ba6ab72b8a 100644 --- a/fs/ntfs/runlist.c +++ b/fs/ntfs/runlist.c @@ -702,9 +702,8 @@ static struct runlist_element *__ntfs_runlists_merge(struct runlist *d_runlist, /* Add an unmapped runlist element. */ if (!slots) { drl = ntfs_rl_realloc_nofail(drl, ds, - ds + 2); + ds + 3); slots = 2; - *new_rl_count += 2; } ds++; /* Need to set vcn if it isn't set already. */ @@ -720,11 +719,11 @@ static struct runlist_element *__ntfs_runlists_merge(struct runlist *d_runlist, ds++; if (!slots) { drl = ntfs_rl_realloc_nofail(drl, ds, ds + 1); - *new_rl_count += 1; } drl[ds].vcn = marker_vcn; drl[ds].lcn = LCN_ENOENT; drl[ds].length = (s64)0; + *new_rl_count = ds + 1; } } } diff --git a/fs/ntfs3/attrib.c b/fs/ntfs3/attrib.c index fd2640878e6a..bc923c33013f 100644 --- a/fs/ntfs3/attrib.c +++ b/fs/ntfs3/attrib.c @@ -1249,6 +1249,10 @@ int attr_data_get_block_locked(struct ntfs_inode *ni, CLST vcn, CLST clen, total_size = total_size0 + ((u64)*len << cluster_bits); if (vcn != vcn0) { + if (vcn0 >= end) { + err = -ENOSPC; + goto undo1; + } if (!run_lookup_entry(run, vcn0, lcn, len, NULL)) { err = -EINVAL; goto out; @@ -2010,7 +2014,7 @@ int attr_allocate_frame(struct ntfs_inode *ni, CLST frame, size_t compr_size, valid_size = le64_to_cpu(attr_b->nres.valid_size); if (new_valid != valid_size) { - attr_b->nres.valid_size = cpu_to_le64(valid_size); + attr_b->nres.valid_size = cpu_to_le64(new_valid); mi_b->dirty = true; } } @@ -2625,8 +2629,8 @@ int attr_insert_range(struct ntfs_inode *ni, u64 vbo, u64 bytes) char *data = Add2Ptr(attr_b, le16_to_cpu(attr_b->res.data_off)); - memmove(data + bytes, data, bytes); - memset(data, 0, bytes); + memmove(data + vbo + bytes, data + vbo, data_size - vbo); + memset(data + vbo, 0, bytes); goto done; } diff --git a/fs/ntfs3/dir.c b/fs/ntfs3/dir.c index 14ca54e54578..c82f3222bf35 100644 --- a/fs/ntfs3/dir.c +++ b/fs/ntfs3/dir.c @@ -525,45 +525,50 @@ static int ntfs_readdir(struct file *file, struct dir_context *ctx) if (!name) return -ENOMEM; + /* + * Keep directory metadata stable for the whole walk. Loading subrecords + * once is not enough if concurrent writeback can still compact ATTR_LIST + * entries and free the record that ntfs_read_hdr() is currently walking. + */ + ni_lock(ni); + if (!ni->mi_loaded && ni->attr_list.size) { /* * Directory inode is locked for read. * Load all subrecords to avoid 'write' access to 'ni' during * directory reading. */ - ni_lock(ni); - if (!ni->mi_loaded && ni->attr_list.size) { - err = ni_load_all_mi(ni); - if (!err) - ni->mi_loaded = true; - } - ni_unlock(ni); + err = ni_load_all_mi(ni); if (err) goto out; + ni->mi_loaded = true; } - /* - * Keep directory metadata stable for the whole walk. Loading subrecords - * once is not enough if concurrent writeback can still compact ATTR_LIST - * entries and free the record that ntfs_read_hdr() is currently walking. - */ - ni_lock(ni); - root = indx_get_root(&ni->dir, ni, NULL, NULL); if (!root) { err = -EINVAL; - goto out_unlock; + goto out; } if (pos >= sbi->record_size) { bit = (pos - sbi->record_size) >> index_bits; } else { + /* + * Release ni_lock before dir_emit (which may fault into + * user pages). root->ihdr lives in the main MFT record + * whose lifetime is bound to the inode, and i_rwsem shared + * prevents concurrent directory modifications. + */ + ni_unlock(ni); + /* * Add each name from root in 'ctx'. */ err = ntfs_read_hdr(sbi, ni, &root->ihdr, 0, pos, name, ctx); if (err) - goto out_unlock; + goto out; + + ni_lock(ni); bit = 0; } @@ -574,7 +579,7 @@ static int ntfs_readdir(struct file *file, struct dir_context *ctx) /* Get the next used index. */ err = indx_used_bit(&ni->dir, ni, &bit); if (err) - goto out_unlock; + goto out; if (bit == MINUS_ONE_T) { /* no more used indexes. end of dir. */ @@ -584,13 +589,19 @@ static int ntfs_readdir(struct file *file, struct dir_context *ctx) if (bit >= max_bit) { /* Corrupted directory. */ err = -EINVAL; - goto out_unlock; + goto out; } err = indx_read_ra(&ni->dir, ni, bit << ni->dir.idx2vbn_bits, &node, &file->f_ra); if (err) - goto out_unlock; + goto out; + + /* + * node->index is a kmalloc'd buffer, safe after ni_unlock. + * Release lock before dir_emit to avoid lock-order issues. + */ + ni_unlock(ni); /* * Add each name from index in 'ctx'. @@ -599,13 +610,14 @@ static int ntfs_readdir(struct file *file, struct dir_context *ctx) ((u64)bit << index_bits) + sbi->record_size, pos, name, ctx); if (err) - goto out_unlock; + goto out; + + ni_lock(ni); } -out_unlock: +out: ni_unlock(ni); -out: kfree(name); put_indx_node(node); diff --git a/fs/ntfs3/file.c b/fs/ntfs3/file.c index 2abf334bfa0c..95dfe6878860 100644 --- a/fs/ntfs3/file.c +++ b/fs/ntfs3/file.c @@ -183,6 +183,9 @@ static int ntfs_ioctl_set_volume_label(struct ntfs_sb_info *sbi, u8 __user *buf) if (!capable(CAP_SYS_ADMIN)) return -EPERM; + if (sb_rdonly(sbi->sb)) + return -EROFS; + if (copy_from_user(user, buf, FSLABEL_MAX)) return -EFAULT; diff --git a/fs/ntfs3/frecord.c b/fs/ntfs3/frecord.c index bead01a953f3..0f56437169e0 100644 --- a/fs/ntfs3/frecord.c +++ b/fs/ntfs3/frecord.c @@ -2190,10 +2190,13 @@ int ni_decompress_file(struct ntfs_inode *ni) /* Clear cached flag. */ ni->ni_flags &= ~NI_FLAG_COMPRESSED_MASK; + /* offs_folio is accessed under run_lock in attr_wof_frame_info(). */ + down_write(&ni->file.run_lock); if (ni->file.offs_folio) { folio_put(ni->file.offs_folio); ni->file.offs_folio = NULL; } + up_write(&ni->file.run_lock); mapping->a_ops = &ntfs_aops; out: @@ -2287,7 +2290,6 @@ int ni_read_frame(struct ntfs_inode *ni, u64 frame_vbo, struct page **pages, u64 vbo_disk; size_t unc_size = 0; u32 frame_size, i, ondisk_size; - struct page *pg; struct ATTRIB *attr; CLST frame, clst_data; @@ -2519,9 +2521,10 @@ int ni_read_frame(struct ntfs_inode *ni, u64 frame_vbo, struct page **pages, #endif vunmap(frame_mem); out: - for (i = 0; i < pages_per_frame; i++) { - pg = pages[i]; - SetPageUptodate(pg); + if (!err) { + for (i = 0; i < pages_per_frame; i++) { + SetPageUptodate(pages[i]); + } } return err; diff --git a/fs/ntfs3/fsntfs.c b/fs/ntfs3/fsntfs.c index 97c04ab2763a..b55311ccd229 100644 --- a/fs/ntfs3/fsntfs.c +++ b/fs/ntfs3/fsntfs.c @@ -2153,6 +2153,9 @@ int ntfs_insert_security(struct ntfs_sb_info *sbi, goto out; while (e) { + if (le16_to_cpu(e->de.size) < SIZEOF_SDH_DIRENTRY) + break; + if (le32_to_cpu(e->sec_hdr.size) == new_sec_size) { err = ntfs_read_run_nb(sbi, &ni->file.run, le64_to_cpu(e->sec_hdr.off), diff --git a/fs/ntfs3/index.c b/fs/ntfs3/index.c index 37e3e16b1f84..9efd2ef02467 100644 --- a/fs/ntfs3/index.c +++ b/fs/ntfs3/index.c @@ -2058,7 +2058,8 @@ int indx_insert_entry(struct ntfs_index *indx, struct ntfs_inode *ni, cmp = get_cmp_func(root); if (unlikely(!cmp)) { WARN_ON_ONCE(1); - return -EINVAL; + err = -EINVAL; + goto out; } if (fnd_is_empty(fnd)) { @@ -2415,7 +2416,8 @@ int indx_delete_entry(struct ntfs_index *indx, struct ntfs_inode *ni, cmp = get_cmp_func(root); if (unlikely(!cmp)) { WARN_ON_ONCE(1); - return -EINVAL; + err = -EINVAL; + goto out; } /* Locate the entry to remove. */ @@ -2711,18 +2713,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); + 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); + 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) { @@ -2796,7 +2808,8 @@ int indx_update_dup(struct ntfs_inode *ni, struct ntfs_sb_info *sbi, cmp = get_cmp_func(root); if (unlikely(!cmp)) { WARN_ON_ONCE(1); - return -EINVAL; + err = -EINVAL; + goto out; } /* Find entry in directory. */ diff --git a/fs/ntfs3/inode.c b/fs/ntfs3/inode.c index fd844f9c556a..70dc0a63c870 100644 --- a/fs/ntfs3/inode.c +++ b/fs/ntfs3/inode.c @@ -213,6 +213,11 @@ static int ntfs_read_mft(struct inode *inode, const struct cpu_str *name, names += 1; fname = Add2Ptr(attr, roff); + + /* Make sure the full name fits in the resident data. */ + if (rsize < fname_full_size(fname)) + goto out; + if (fname->type == FILE_NAME_DOS) goto next_attr; @@ -280,7 +285,9 @@ static int ntfs_read_mft(struct inode *inode, const struct cpu_str *name, break; case ATTR_ROOT: - if (attr->non_res) + if (attr->non_res || + asize < sizeof(struct INDEX_ROOT) + roff || + rsize < sizeof(struct INDEX_ROOT)) goto out; root = Add2Ptr(attr, roff); diff --git a/fs/ntfs3/xattr.c b/fs/ntfs3/xattr.c index fb7276d4a428..7b02da27f5db 100644 --- a/fs/ntfs3/xattr.c +++ b/fs/ntfs3/xattr.c @@ -168,6 +168,8 @@ static int ntfs_read_ea(struct ntfs_inode *ni, struct EA_FULL **ea, ea_size = le32_to_cpu(ef->size); if (ea_size > bytes || packed_size > ea_size) goto out1; + if (bytes < offsetof(struct EA_FULL, name)) + goto out1; continue; } @@ -979,8 +981,10 @@ static noinline int ntfs_setxattr(const struct xattr_handler *handler, NULL); out: - inode_set_ctime_current(inode); - mark_inode_dirty(inode); + if (!err) { + inode_set_ctime_current(inode); + mark_inode_dirty(inode); + } return err; } diff --git a/fs/ocfs2/cluster/heartbeat.c b/fs/ocfs2/cluster/heartbeat.c index dbc146717e8f..7a18e71b507b 100644 --- a/fs/ocfs2/cluster/heartbeat.c +++ b/fs/ocfs2/cluster/heartbeat.c @@ -269,6 +269,8 @@ struct o2hb_region { struct list_head hr_handler_list; /* Serializes timeout arming against failed-start and teardown. */ struct mutex hr_arming_mutex; + /* Serializes the dev, block_bytes, start_block and blocks attributes. */ + struct mutex hr_dev_mutex; bool hr_stopping; /* last hb status, 0 for success, other value for error. */ @@ -1681,6 +1683,7 @@ static ssize_t o2hb_region_block_bytes_store(struct config_item *item, unsigned long block_bytes; unsigned int block_bits; + guard(mutex)(®->hr_dev_mutex); if (reg->hr_bdev_file) return -EINVAL; @@ -1710,6 +1713,7 @@ static ssize_t o2hb_region_start_block_store(struct config_item *item, char *p = (char *)page; ssize_t ret; + guard(mutex)(®->hr_dev_mutex); if (reg->hr_bdev_file) return -EINVAL; @@ -1736,6 +1740,7 @@ static ssize_t o2hb_region_blocks_store(struct config_item *item, char *p = (char *)page; int ret; + guard(mutex)(®->hr_dev_mutex); if (reg->hr_bdev_file) return -EINVAL; @@ -1753,10 +1758,12 @@ static ssize_t o2hb_region_blocks_store(struct config_item *item, static ssize_t o2hb_region_dev_show(struct config_item *item, char *page) { + struct o2hb_region *reg = to_o2hb_region(item); unsigned int ret = 0; - if (to_o2hb_region(item)->hr_bdev_file) - ret = sprintf(page, "%pg\n", reg_bdev(to_o2hb_region(item))); + guard(mutex)(®->hr_dev_mutex); + if (reg->hr_bdev_file) + ret = sprintf(page, "%pg\n", reg_bdev(reg)); return ret; } @@ -1872,11 +1879,9 @@ static int o2hb_populate_slot_data(struct o2hb_region *reg) * this is acting as commit; we set up all of hr_bdev_file and hr_task or * nothing */ -static ssize_t o2hb_region_dev_store(struct config_item *item, - const char *page, - size_t count) +static ssize_t __o2hb_region_dev_store(struct o2hb_region *reg, + const char *page, size_t count) { - struct o2hb_region *reg = to_o2hb_region(item); struct task_struct *hb_task; long fd; int sectsize; @@ -1884,6 +1889,8 @@ static ssize_t o2hb_region_dev_store(struct config_item *item, ssize_t ret = -EINVAL; int live_threshold; + lockdep_assert_held(®->hr_dev_mutex); + if (reg->hr_bdev_file) return -EINVAL; @@ -1971,21 +1978,31 @@ static ssize_t o2hb_region_dev_store(struct config_item *item, atomic_set(®->hr_unsteady_iterations, (live_threshold * 3)); o2hb_set_region_stopping(reg, false); - hb_task = kthread_run(o2hb_thread, reg, "o2hb-%s", - reg->hr_item.ci_name); + hb_task = kthread_create(o2hb_thread, reg, "o2hb-%s", + reg->hr_item.ci_name); if (IS_ERR(hb_task)) { ret = PTR_ERR(hb_task); mlog_errno(ret); goto out; } + /* The thread may exit on its own, so pin it before it can run. */ + get_task_struct(hb_task); spin_lock(&o2hb_live_lock); reg->hr_task = hb_task; spin_unlock(&o2hb_live_lock); + wake_up_process(hb_task); + + /* + * Don't hold hr_dev_mutex across the wait, which can take seconds. + * hr_bdev_file is already set, so other writers still get -EINVAL. + */ + mutex_unlock(®->hr_dev_mutex); ret = wait_event_interruptible(o2hb_steady_queue, atomic_read(®->hr_steady_iterations) == 0 || reg->hr_node_deleted); + mutex_lock(®->hr_dev_mutex); if (ret) { atomic_set(®->hr_steady_iterations, 0); reg->hr_aborted_start = 1; @@ -2027,7 +2044,7 @@ static ssize_t o2hb_region_dev_store(struct config_item *item, spin_unlock(&o2hb_live_lock); if (hb_task) - kthread_stop(hb_task); + kthread_stop_put(hb_task); o2hb_unmap_slot_data(reg); @@ -2037,6 +2054,20 @@ static ssize_t o2hb_region_dev_store(struct config_item *item, return ret; } +static ssize_t o2hb_region_dev_store(struct config_item *item, + const char *page, + size_t count) +{ + struct o2hb_region *reg = to_o2hb_region(item); + ssize_t ret; + + mutex_lock(®->hr_dev_mutex); + ret = __o2hb_region_dev_store(reg, page, count); + mutex_unlock(®->hr_dev_mutex); + + return ret; +} + static ssize_t o2hb_region_pid_show(struct config_item *item, char *page) { struct o2hb_region *reg = to_o2hb_region(item); @@ -2139,6 +2170,7 @@ static struct config_item *o2hb_heartbeat_group_make_item(struct config_group *g INIT_LIST_HEAD(®->hr_all_item); mutex_init(®->hr_arming_mutex); + mutex_init(®->hr_dev_mutex); reg->hr_stopping = true; INIT_DELAYED_WORK(®->hr_write_timeout_work, o2hb_write_timeout); INIT_DELAYED_WORK(®->hr_nego_timeout_work, o2hb_nego_timeout); @@ -2221,7 +2253,7 @@ static void o2hb_heartbeat_group_drop_item(struct config_group *group, spin_unlock(&o2hb_live_lock); if (hb_task) - kthread_stop(hb_task); + kthread_stop_put(hb_task); if (o2hb_global_heartbeat_active()) { spin_lock(&o2hb_live_lock); diff --git a/fs/ocfs2/cluster/tcp.c b/fs/ocfs2/cluster/tcp.c index 0ba26bd2eba1..0eaf2c4a6989 100644 --- a/fs/ocfs2/cluster/tcp.c +++ b/fs/ocfs2/cluster/tcp.c @@ -301,6 +301,11 @@ static int o2net_prep_nsw(struct o2net_node *nn, struct o2net_status_wait *nsw) { int ret; + /* Initialize all completion-visible state before publishing the waiter. */ + init_waitqueue_head(&nsw->ns_wq); + nsw->ns_sys_status = O2NET_ERR_NONE; + nsw->ns_status = 0; + spin_lock(&nn->nn_lock); ret = idr_alloc(&nn->nn_status_idr, nsw, 0, 0, GFP_ATOMIC); if (ret >= 0) { @@ -311,9 +316,6 @@ static int o2net_prep_nsw(struct o2net_node *nn, struct o2net_status_wait *nsw) if (ret < 0) return ret; - init_waitqueue_head(&nsw->ns_wq); - nsw->ns_sys_status = O2NET_ERR_NONE; - nsw->ns_status = 0; return 0; } diff --git a/fs/ocfs2/dlmglue.c b/fs/ocfs2/dlmglue.c index a2a33c34fdf9..c281902e3bec 100644 --- a/fs/ocfs2/dlmglue.c +++ b/fs/ocfs2/dlmglue.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -2854,21 +2855,34 @@ void ocfs2_rename_unlock(struct ocfs2_super *osb) ocfs2_cluster_unlock(osb, lockres, DLM_LOCK_EX); } -int ocfs2_nfs_sync_lock(struct ocfs2_super *osb, int ex) +int ocfs2_nfs_sync_lock(struct ocfs2_super *osb, int ex, unsigned int *nofs_flag) { int status; + unsigned int flags; struct ocfs2_lock_res *lockres = &osb->osb_nfs_sync_lockres; if (ocfs2_is_hard_readonly(osb)) return -EROFS; + /* + * ocfs2_delete_inode() takes this lock from ->evict_inode(), which the + * dentry shrinker reaches while holding fs_reclaim. Anything allocated + * under the lock must therefore stay out of filesystem reclaim, or + * reclaim recurses back into the shrinker and tries to take this lock + * again. Cover the whole critical section, including the cluster lock + * and the sysfile inode locks the callers take below it. + */ + flags = memalloc_nofs_save(); + if (ex) down_write(&osb->nfs_sync_rwlock); else down_read(&osb->nfs_sync_rwlock); - if (ocfs2_mount_local(osb)) + if (ocfs2_mount_local(osb)) { + *nofs_flag = flags; return 0; + } status = ocfs2_cluster_lock(osb, lockres, ex ? LKM_EXMODE : LKM_PRMODE, 0, 0); @@ -2879,12 +2893,17 @@ int ocfs2_nfs_sync_lock(struct ocfs2_super *osb, int ex) up_write(&osb->nfs_sync_rwlock); else up_read(&osb->nfs_sync_rwlock); + memalloc_nofs_restore(flags); + return status; } - return status; + *nofs_flag = flags; + + return 0; } -void ocfs2_nfs_sync_unlock(struct ocfs2_super *osb, int ex) +void ocfs2_nfs_sync_unlock(struct ocfs2_super *osb, int ex, + unsigned int nofs_flag) { struct ocfs2_lock_res *lockres = &osb->osb_nfs_sync_lockres; @@ -2895,6 +2914,8 @@ void ocfs2_nfs_sync_unlock(struct ocfs2_super *osb, int ex) up_write(&osb->nfs_sync_rwlock); else up_read(&osb->nfs_sync_rwlock); + + memalloc_nofs_restore(nofs_flag); } int ocfs2_trim_fs_lock(struct ocfs2_super *osb, diff --git a/fs/ocfs2/dlmglue.h b/fs/ocfs2/dlmglue.h index a3ebd7303ea2..faa58ed8699b 100644 --- a/fs/ocfs2/dlmglue.h +++ b/fs/ocfs2/dlmglue.h @@ -161,8 +161,9 @@ void ocfs2_orphan_scan_unlock(struct ocfs2_super *osb, u32 seqno); int ocfs2_rename_lock(struct ocfs2_super *osb); void ocfs2_rename_unlock(struct ocfs2_super *osb); -int ocfs2_nfs_sync_lock(struct ocfs2_super *osb, int ex); -void ocfs2_nfs_sync_unlock(struct ocfs2_super *osb, int ex); +int ocfs2_nfs_sync_lock(struct ocfs2_super *osb, int ex, unsigned int *nofs_flag); +void ocfs2_nfs_sync_unlock(struct ocfs2_super *osb, int ex, + unsigned int nofs_flag); void ocfs2_trim_fs_lock_res_init(struct ocfs2_super *osb); void ocfs2_trim_fs_lock_res_uninit(struct ocfs2_super *osb); int ocfs2_trim_fs_lock(struct ocfs2_super *osb, diff --git a/fs/ocfs2/export.c b/fs/ocfs2/export.c index 9c2665dd24e2..90b9e510e700 100644 --- a/fs/ocfs2/export.c +++ b/fs/ocfs2/export.c @@ -37,6 +37,7 @@ static struct dentry *ocfs2_get_dentry(struct super_block *sb, struct inode *inode; struct ocfs2_super *osb = OCFS2_SB(sb); u64 blkno = handle->ih_blkno; + unsigned int nofs_flag = 0; int status, set; struct dentry *result; @@ -59,7 +60,7 @@ static struct dentry *ocfs2_get_dentry(struct super_block *sb, * This will synchronize us against ocfs2_delete_inode() on * all nodes */ - status = ocfs2_nfs_sync_lock(osb, 1); + status = ocfs2_nfs_sync_lock(osb, 1, &nofs_flag); if (status < 0) { mlog(ML_ERROR, "getting nfs sync lock(EX) failed %d\n", status); goto check_err; @@ -90,7 +91,7 @@ static struct dentry *ocfs2_get_dentry(struct super_block *sb, inode = ocfs2_iget(osb, blkno, 0, 0); unlock_nfs_sync: - ocfs2_nfs_sync_unlock(osb, 1); + ocfs2_nfs_sync_unlock(osb, 1, nofs_flag); check_err: if (status < 0) { @@ -133,12 +134,13 @@ static struct dentry *ocfs2_get_parent(struct dentry *child) u64 blkno; struct dentry *parent; struct inode *dir = d_inode(child); + unsigned int nofs_flag = 0; int set; trace_ocfs2_get_parent(child, child->d_name.len, child->d_name.name, (unsigned long long)OCFS2_I(dir)->ip_blkno); - status = ocfs2_nfs_sync_lock(OCFS2_SB(dir->i_sb), 1); + status = ocfs2_nfs_sync_lock(OCFS2_SB(dir->i_sb), 1, &nofs_flag); if (status < 0) { mlog(ML_ERROR, "getting nfs sync lock(EX) failed %d\n", status); parent = ERR_PTR(status); @@ -183,7 +185,7 @@ static struct dentry *ocfs2_get_parent(struct dentry *child) ocfs2_inode_unlock(dir, 0); unlock_nfs_sync: - ocfs2_nfs_sync_unlock(OCFS2_SB(dir->i_sb), 1); + ocfs2_nfs_sync_unlock(OCFS2_SB(dir->i_sb), 1, nofs_flag); bail: trace_ocfs2_get_parent_end(parent); diff --git a/fs/ocfs2/inode.c b/fs/ocfs2/inode.c index 9228d6ef23c2..bcfe53bc356e 100644 --- a/fs/ocfs2/inode.c +++ b/fs/ocfs2/inode.c @@ -1109,6 +1109,7 @@ static void ocfs2_delete_inode(struct inode *inode) { int wipe, status; sigset_t oldset; + unsigned int nofs_flag = 0; struct buffer_head *di_bh = NULL; struct ocfs2_dinode *di = NULL; @@ -1143,7 +1144,7 @@ static void ocfs2_delete_inode(struct inode *inode) * shared mode so that all nodes can still concurrently * process deletes. */ - status = ocfs2_nfs_sync_lock(OCFS2_SB(inode->i_sb), 0); + status = ocfs2_nfs_sync_lock(OCFS2_SB(inode->i_sb), 0, &nofs_flag); if (status < 0) { mlog(ML_ERROR, "getting nfs sync lock(PR) failed %d\n", status); ocfs2_cleanup_delete_inode(inode, 0); @@ -1215,7 +1216,7 @@ static void ocfs2_delete_inode(struct inode *inode) brelse(di_bh); bail_unlock_nfs_sync: - ocfs2_nfs_sync_unlock(OCFS2_SB(inode->i_sb), 0); + ocfs2_nfs_sync_unlock(OCFS2_SB(inode->i_sb), 0, nofs_flag); bail_unblock: ocfs2_unblock_signals(&oldset); diff --git a/fs/ocfs2/namei.c b/fs/ocfs2/namei.c index 58c6061ed983..ef03f90e7265 100644 --- a/fs/ocfs2/namei.c +++ b/fs/ocfs2/namei.c @@ -248,7 +248,6 @@ static int ocfs2_mknod(struct mnt_idmap *idmap, int want_meta = 0; int xattr_credits = 0; struct ocfs2_security_xattr_info si = { - .name = NULL, .enable = 1, }; int did_quota_inode = 0; @@ -475,7 +474,7 @@ static int ocfs2_mknod(struct mnt_idmap *idmap, brelse(new_fe_bh); brelse(parent_fe_bh); - kfree(si.value); + ocfs2_free_security_xattrs(&si); ocfs2_acl_init_release(&acl_state); @@ -1831,7 +1830,6 @@ static int ocfs2_symlink(struct mnt_idmap *idmap, int want_clusters = 0; int xattr_credits = 0; struct ocfs2_security_xattr_info si = { - .name = NULL, .enable = 1, }; int did_quota = 0, did_quota_inode = 0; @@ -2063,7 +2061,7 @@ static int ocfs2_symlink(struct mnt_idmap *idmap, brelse(new_fe_bh); brelse(parent_fe_bh); - kfree(si.value); + ocfs2_free_security_xattrs(&si); ocfs2_free_dir_lookup_result(&lookup); if (inode_ac) ocfs2_free_alloc_context(inode_ac); diff --git a/fs/ocfs2/ocfs2.h b/fs/ocfs2/ocfs2.h index 62cad6522c7a..b747cdec1787 100644 --- a/fs/ocfs2/ocfs2.h +++ b/fs/ocfs2/ocfs2.h @@ -502,6 +502,11 @@ struct ocfs2_super */ struct workqueue_struct *ocfs2_wq; + /* deferred reclaim of fully freed suballocator block groups */ + spinlock_t os_suballoc_reclaim_lock; + struct list_head os_suballoc_reclaim_list; + struct work_struct os_suballoc_reclaim_work; + /* sysfs directory per partition */ struct kset *osb_dev_kset; diff --git a/fs/ocfs2/quota_local.c b/fs/ocfs2/quota_local.c index 28c1c9f9403c..a2ce25a33607 100644 --- a/fs/ocfs2/quota_local.c +++ b/fs/ocfs2/quota_local.c @@ -245,6 +245,25 @@ static void ocfs2_release_local_quota_bitmaps(struct list_head *head) } } +/* Check that the on-disk chunk and block counts match the file layout */ +static int ocfs2_check_local_quota_info(struct inode *inode, + unsigned int chunks, + unsigned int blocks) +{ + u64 chunk_len = ol_chunk_blocks(inode->i_sb) + 1; + u64 min_blocks = chunks ? 1 + chunk_len * (chunks - 1) + 1 : 1; + u64 max_blocks = 1 + chunk_len * chunks; + + if (blocks >= min_blocks && blocks <= max_blocks && + blocks <= i_size_read(inode) >> inode->i_sb->s_blocksize_bits) + return 0; + + return ocfs2_error(inode->i_sb, + "Quota file %llu has bad info: %u chunks, %u blocks\n", + (unsigned long long)OCFS2_I(inode)->ip_blkno, + chunks, blocks); +} + /* Load quota bitmaps into memory */ static int ocfs2_load_local_quota_bitmaps(struct inode *inode, struct ocfs2_local_disk_dqinfo *ldinfo, @@ -733,6 +752,11 @@ static int ocfs2_local_read_info(struct super_block *sb, int type) oinfo->dqi_blocks = le32_to_cpu(ldinfo->dqi_blocks); oinfo->dqi_libh = bh; + status = ocfs2_check_local_quota_info(lqinode, oinfo->dqi_chunks, + oinfo->dqi_blocks); + if (status < 0) + goto out_err; + /* We crashed when using local quota file? */ if (!(oinfo->dqi_flags & OLQF_CLEAN)) { rec = OCFS2_SB(sb)->quota_rec; diff --git a/fs/ocfs2/suballoc.c b/fs/ocfs2/suballoc.c index 20c3aec6b987..453b56be9624 100644 --- a/fs/ocfs2/suballoc.c +++ b/fs/ocfs2/suballoc.c @@ -2687,16 +2687,24 @@ static int ocfs2_block_group_clear_bits(handle_t *handle, * cleanup rec/alloc_inode job, then switches to the main bitmap * to reclaim released space. * + * Callers must hold inode_lock() and ocfs2_inode_lock() on + * main_bm_inode, i.e. the global bitmap inode locks must be taken + * before starting the transaction. + * * handle: The transaction handle * alloc_inode: The suballoc inode * alloc_bh: The buffer_head of suballoc inode * group_bh: The group descriptor buffer_head of suballocator managed. - * Caller should release the input group_bh. + * This function takes ownership of it and will release it. + * main_bm_inode: The global bitmap inode + * main_bm_bh: The buffer_head of the global bitmap inode */ static int _ocfs2_reclaim_suballoc_to_main(handle_t *handle, struct inode *alloc_inode, struct buffer_head *alloc_bh, - struct buffer_head *group_bh) + struct buffer_head *group_bh, + struct inode *main_bm_inode, + struct buffer_head *main_bm_bh) { int idx, status = 0; int i, next_free_rec, len = 0; @@ -2706,8 +2714,6 @@ static int _ocfs2_reclaim_suballoc_to_main(handle_t *handle, u64 bg_blkno, start_blk; unsigned int count; struct ocfs2_chain_rec *rec; - struct buffer_head *main_bm_bh = NULL; - struct inode *main_bm_inode = NULL; struct ocfs2_super *osb = OCFS2_SB(alloc_inode->i_sb); struct ocfs2_dinode *fe = (struct ocfs2_dinode *) alloc_bh->b_data; struct ocfs2_chain_list *cl = &fe->id2.i_chain; @@ -2794,24 +2800,12 @@ static int _ocfs2_reclaim_suballoc_to_main(handle_t *handle, ocfs2_remove_from_cache(INODE_CACHE(alloc_inode), group_bh); memset(group, 0, sizeof(struct ocfs2_group_desc)); - /* prepare job for reclaim clusters */ - main_bm_inode = ocfs2_get_system_file_inode(osb, - GLOBAL_BITMAP_SYSTEM_INODE, - OCFS2_INVALID_SLOT); - if (!main_bm_inode) - goto bail; /* ignore the error in reclaim path */ - - inode_lock(main_bm_inode); - - status = ocfs2_inode_lock(main_bm_inode, &main_bm_bh, 1); - if (status < 0) - goto free_bm_inode; /* ignore the error in reclaim path */ - ocfs2_block_to_cluster_group(main_bm_inode, start_blk, &bg_blkno, &start_bit); fe = (struct ocfs2_dinode *) main_bm_bh->b_data; cl = &fe->id2.i_chain; - /* reuse group_bh, caller will release the input group_bh */ + /* release the suballocator group descriptor before reuse */ + brelse(group_bh); group_bh = NULL; /* reclaim clusters to global_bitmap */ @@ -2819,7 +2813,7 @@ static int _ocfs2_reclaim_suballoc_to_main(handle_t *handle, &group_bh); if (status < 0) { mlog_errno(status); - goto free_bm_bh; + goto bail; } group = (struct ocfs2_group_desc *) group_bh->b_data; @@ -2827,7 +2821,7 @@ static int _ocfs2_reclaim_suballoc_to_main(handle_t *handle, ocfs2_error(alloc_inode->i_sb, "reclaim length (%d) beyands block group length (%d)", count + start_bit, le16_to_cpu(group->bg_bits)); - goto free_group_bh; + goto bail; } old_bg_contig_free_bits = group->bg_contig_free_bits; @@ -2837,7 +2831,7 @@ static int _ocfs2_reclaim_suballoc_to_main(handle_t *handle, _ocfs2_clear_bit); if (status < 0) { mlog_errno(status); - goto free_group_bh; + goto bail; } status = ocfs2_journal_access_di(handle, INODE_CACHE(main_bm_inode), @@ -2847,7 +2841,7 @@ static int _ocfs2_reclaim_suballoc_to_main(handle_t *handle, ocfs2_block_group_set_bits(handle, main_bm_inode, group, group_bh, start_bit, count, le16_to_cpu(old_bg_contig_free_bits), 1); - goto free_group_bh; + goto bail; } idx = le16_to_cpu(group->bg_chain); @@ -2858,19 +2852,168 @@ static int _ocfs2_reclaim_suballoc_to_main(handle_t *handle, fe->id1.bitmap1.i_used = cpu_to_le32(tmp_used - count); ocfs2_journal_dirty(handle, main_bm_bh); -free_group_bh: +bail: brelse(group_bh); + return status; +} + +/* + * When a suballocator block group becomes fully freed, its space is + * reclaimed back to the global bitmap. Taking the global bitmap inode + * lock inside the freeing transaction would create a lock dependency + * of "j_trans_barrier -> global bitmap inode i_rwsem", which forms a + * circular dependency with paths like ocfs2_shutdown_local_alloc() that + * take the inode lock before starting a transaction, and can lead to a + * real deadlock with the ocfs2cmt journal commit thread. So queue the + * reclaim to the workqueue and let it run outside the freeing + * transaction. + */ +struct ocfs2_suballoc_reclaim_work { + struct list_head list; + struct inode *alloc_inode; + u64 bg_blkno; +}; + +static void ocfs2_queue_suballoc_reclaim(struct ocfs2_super *osb, + struct inode *alloc_inode, + u64 bg_blkno) +{ + struct ocfs2_suballoc_reclaim_work *reclaim_work; + + reclaim_work = kmalloc_obj(*reclaim_work, GFP_NOFS); + if (!reclaim_work) { + /* + * Reclaim is only a space return optimization. If we can't + * queue it, the freed block group just stays owned by the + * suballocator. + */ + return; + } + + igrab(alloc_inode); + reclaim_work->alloc_inode = alloc_inode; + reclaim_work->bg_blkno = bg_blkno; + + spin_lock(&osb->os_suballoc_reclaim_lock); + list_add_tail(&reclaim_work->list, &osb->os_suballoc_reclaim_list); + spin_unlock(&osb->os_suballoc_reclaim_lock); -free_bm_bh: + queue_work(osb->ocfs2_wq, &osb->os_suballoc_reclaim_work); +} + +static void ocfs2_do_suballoc_reclaim(struct ocfs2_super *osb, + struct ocfs2_suballoc_reclaim_work *reclaim_work) +{ + int status, i; + handle_t *handle; + struct inode *alloc_inode = reclaim_work->alloc_inode; + struct inode *main_bm_inode; + struct buffer_head *alloc_bh = NULL, *group_bh = NULL; + struct buffer_head *main_bm_bh = NULL; + struct ocfs2_dinode *fe; + struct ocfs2_chain_list *cl; + struct ocfs2_chain_rec *rec; + + /* journal already gone, e.g. during dismount cleanup */ + if (!osb->journal) + return; + + inode_lock(alloc_inode); + status = ocfs2_inode_lock(alloc_inode, &alloc_bh, 1); + if (status < 0) + goto out_alloc; + + fe = (struct ocfs2_dinode *) alloc_bh->b_data; + cl = &fe->id2.i_chain; + + /* + * The block group may have been allocated from again since the + * reclaim work was queued, re-check that it is still fully freed. + * A stale work item can also reference a group that is no longer + * chained, whose descriptor would fail validation and trigger a + * spurious ocfs2_error(), so verify chain membership first. + */ + for (i = 0; i < le16_to_cpu(cl->cl_next_free_rec); i++) { + rec = &cl->cl_recs[i]; + if (le64_to_cpu(rec->c_blkno) == reclaim_work->bg_blkno) + break; + } + if (i == le16_to_cpu(cl->cl_next_free_rec) || + ocfs2_is_cluster_bitmap(alloc_inode) || + (le32_to_cpu(rec->c_free) != (le32_to_cpu(rec->c_total) - 1)) || + (le16_to_cpu(cl->cl_next_free_rec) == 1)) + goto out_alloc_unlock; + + status = ocfs2_read_group_descriptor(alloc_inode, fe, + reclaim_work->bg_blkno, &group_bh); + if (status < 0) + goto out_alloc_unlock; + + main_bm_inode = ocfs2_get_system_file_inode(osb, + GLOBAL_BITMAP_SYSTEM_INODE, + OCFS2_INVALID_SLOT); + if (!main_bm_inode) + goto out_group; + + inode_lock(main_bm_inode); + status = ocfs2_inode_lock(main_bm_inode, &main_bm_bh, 1); + if (status < 0) + goto out_main; + + handle = ocfs2_start_trans(osb, OCFS2_SUBALLOC_FREE); + if (IS_ERR(handle)) { + status = PTR_ERR(handle); + mlog_errno(status); + goto out_main_unlock; + } + + status = _ocfs2_reclaim_suballoc_to_main(handle, alloc_inode, + alloc_bh, group_bh, + main_bm_inode, main_bm_bh); + /* group_bh ownership passed to _ocfs2_reclaim_suballoc_to_main() */ + group_bh = NULL; + if (status < 0) + mlog_errno(status); + + ocfs2_commit_trans(osb, handle); + +out_main_unlock: ocfs2_inode_unlock(main_bm_inode, 1); brelse(main_bm_bh); - -free_bm_inode: +out_main: inode_unlock(main_bm_inode); iput(main_bm_inode); +out_group: + brelse(group_bh); +out_alloc_unlock: + ocfs2_inode_unlock(alloc_inode, 1); + brelse(alloc_bh); +out_alloc: + inode_unlock(alloc_inode); +} -bail: - return status; +void ocfs2_suballoc_reclaim_worker(struct work_struct *work) +{ + struct ocfs2_super *osb = container_of(work, struct ocfs2_super, + os_suballoc_reclaim_work); + struct ocfs2_suballoc_reclaim_work *reclaim_work; + + while (1) { + spin_lock(&osb->os_suballoc_reclaim_lock); + if (list_empty(&osb->os_suballoc_reclaim_list)) { + spin_unlock(&osb->os_suballoc_reclaim_lock); + break; + } + reclaim_work = list_first_entry(&osb->os_suballoc_reclaim_list, + struct ocfs2_suballoc_reclaim_work, + list); + list_del(&reclaim_work->list); + spin_unlock(&osb->os_suballoc_reclaim_lock); + + ocfs2_do_suballoc_reclaim(osb, reclaim_work); + iput(reclaim_work->alloc_inode); + kfree(reclaim_work); + } } /* @@ -2955,7 +3098,8 @@ static int _ocfs2_free_suballoc_bits(handle_t *handle, goto bail; } - _ocfs2_reclaim_suballoc_to_main(handle, alloc_inode, alloc_bh, group_bh); + ocfs2_queue_suballoc_reclaim(OCFS2_SB(alloc_inode->i_sb), alloc_inode, + bg_blkno); bail: brelse(group_bh); diff --git a/fs/ocfs2/suballoc.h b/fs/ocfs2/suballoc.h index bcf2ed4a8631..6042abc032f9 100644 --- a/fs/ocfs2/suballoc.h +++ b/fs/ocfs2/suballoc.h @@ -206,7 +206,7 @@ int ocfs2_lock_allocators(struct inode *inode, struct ocfs2_extent_tree *et, int ocfs2_test_inode_bit(struct ocfs2_super *osb, u64 blkno, int *res); - +void ocfs2_suballoc_reclaim_worker(struct work_struct *work); /* * The following two interfaces are for ocfs2_create_inode_in_orphan(). diff --git a/fs/ocfs2/super.c b/fs/ocfs2/super.c index e5482c556552..3072b0386db8 100644 --- a/fs/ocfs2/super.c +++ b/fs/ocfs2/super.c @@ -1785,6 +1785,9 @@ static int ocfs2_mount_volume(struct super_block *sb) out_system_inodes: if (osb->local_alloc_state == OCFS2_LA_ENABLED) ocfs2_shutdown_local_alloc(osb); + /* Drain pending suballoc reclaim work before the journal goes away */ + if (osb->ocfs2_wq) + flush_workqueue(osb->ocfs2_wq); ocfs2_release_system_inodes(osb); /* before journal shutdown, we should release slot_info */ ocfs2_free_slot_info(osb); @@ -1858,6 +1861,14 @@ static void ocfs2_dismount_volume(struct super_block *sb, int mnt_err) if (osb->cconn) ocfs2_super_unlock(osb, 1); + /* + * Drain pending suballoc reclaim work while the system inodes and + * the journal are still alive, since the worker needs to look up + * the global bitmap inode and start a transaction. + */ + if (osb->ocfs2_wq) + flush_workqueue(osb->ocfs2_wq); + ocfs2_release_system_inodes(osb); ocfs2_journal_shutdown(osb); @@ -2144,6 +2155,11 @@ static int ocfs2_initialize_super(struct super_block *sb, INIT_WORK(&osb->dquot_drop_work, ocfs2_drop_dquot_refs); init_llist_head(&osb->dquot_drop_list); + spin_lock_init(&osb->os_suballoc_reclaim_lock); + INIT_LIST_HEAD(&osb->os_suballoc_reclaim_list); + INIT_WORK(&osb->os_suballoc_reclaim_work, + ocfs2_suballoc_reclaim_worker); + /* get some pseudo constants for clustersize bits */ osb->s_clustersize_bits = le32_to_cpu(di->id2.i_super.s_clustersize_bits); diff --git a/fs/ocfs2/xattr.c b/fs/ocfs2/xattr.c index 4d00a26ece3c..3a2da6549f42 100644 --- a/fs/ocfs2/xattr.c +++ b/fs/ocfs2/xattr.c @@ -237,6 +237,21 @@ static int namevalue_size_xe(struct ocfs2_xattr_entry *xe) return namevalue_size(xe->xe_name_len, value_len); } +static int ocfs2_validate_xattr_entry(struct super_block *sb, u64 blkno, + struct ocfs2_xattr_entry *xe) +{ + u64 value_len = le64_to_cpu(xe->xe_value_size); + + if (value_len > OCFS2_XATTR_INLINE_SIZE && + ocfs2_xattr_is_local(xe)) + return ocfs2_error(sb, + "Invalid local xattr in block %llu: value size %llu\n", + (unsigned long long)blkno, + (unsigned long long)value_len); + + return 0; +} + static int ocfs2_xattr_bucket_get_name_value(struct super_block *sb, struct ocfs2_xattr_header *xh, @@ -622,10 +637,15 @@ int ocfs2_calc_security_init(struct inode *dir, int *xattr_credits, struct ocfs2_alloc_context **xattr_ac) { + int i; int ret = 0; struct ocfs2_super *osb = OCFS2_SB(dir->i_sb); - int s_size = ocfs2_xattr_entry_real_size(strlen(si->name), - si->value_len); + int s_size = 0; + + for (i = 0; i < si->count; i++) + s_size += ocfs2_xattr_entry_real_size( + strlen(si->xattrs[i].name), + si->xattrs[i].value_len); /* * The max space of security xattr taken inline is @@ -642,14 +662,27 @@ int ocfs2_calc_security_init(struct inode *dir, *xattr_credits += OCFS2_XATTR_BLOCK_CREATE_CREDITS; } - /* reserve clusters for xattr value which will be set in B tree*/ - if (si->value_len > OCFS2_XATTR_INLINE_SIZE) { - int new_clusters = ocfs2_clusters_for_bytes(dir->i_sb, - si->value_len); + /* + * when blocksize = 512, the security xattrs may not fit in the + * single block reserved above and a bucket has to be allocated + * for them, so reserve the cluster it needs as well. + */ + if (dir->i_sb->s_blocksize == OCFS2_MIN_BLOCKSIZE && + s_size > OCFS2_XATTR_FREE_IN_BLOCK(dir)) { + *want_clusters += 1; + *xattr_credits += ocfs2_blocks_per_xattr_bucket(dir->i_sb); + } - *xattr_credits += ocfs2_clusters_to_blocks(dir->i_sb, - new_clusters); - *want_clusters += new_clusters; + /* reserve clusters for xattr value which will be set in B tree*/ + for (i = 0; i < si->count; i++) { + if (si->xattrs[i].value_len > OCFS2_XATTR_INLINE_SIZE) { + int new_clusters = ocfs2_clusters_for_bytes(dir->i_sb, + si->xattrs[i].value_len); + + *xattr_credits += ocfs2_clusters_to_blocks(dir->i_sb, + new_clusters); + *want_clusters += new_clusters; + } } return ret; } @@ -659,12 +692,16 @@ void ocfs2_calc_xattr_init(struct inode *dir, umode_t mode, int *want_clusters, int *xattr_credits, int *want_meta, struct ocfs2_acl_state *acl_state) { + int i; struct ocfs2_super *osb = OCFS2_SB(dir->i_sb); int s_size = 0, a_size = 0, acl_len = 0, new_clusters; - if (si->enable) - s_size = ocfs2_xattr_entry_real_size(strlen(si->name), - si->value_len); + if (si->enable) { + for (i = 0; i < si->count; i++) + s_size += ocfs2_xattr_entry_real_size( + strlen(si->xattrs[i].name), + si->xattrs[i].value_len); + } if (osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL) { if (acl_state->default_acl && S_ISDIR(mode)) { @@ -711,12 +748,14 @@ void ocfs2_calc_xattr_init(struct inode *dir, umode_t mode, * reserve credits and clusters for xattrs which has large value * and have to be set outside */ - if (si->enable && si->value_len > OCFS2_XATTR_INLINE_SIZE) { - new_clusters = ocfs2_clusters_for_bytes(dir->i_sb, - si->value_len); - *xattr_credits += ocfs2_clusters_to_blocks(dir->i_sb, - new_clusters); - *want_clusters += new_clusters; + for (i = 0; si->enable && i < si->count; i++) { + if (si->xattrs[i].value_len > OCFS2_XATTR_INLINE_SIZE) { + new_clusters = ocfs2_clusters_for_bytes(dir->i_sb, + si->xattrs[i].value_len); + *xattr_credits += ocfs2_clusters_to_blocks(dir->i_sb, + new_clusters); + *want_clusters += new_clusters; + } } if (osb->s_mount_opt & OCFS2_MOUNT_POSIX_ACL) { if (acl_state->default_acl && S_ISDIR(mode)) { @@ -1008,7 +1047,7 @@ static int ocfs2_validate_xattr_entries_flat(struct super_block *sb, u64 blkno, size_t entries_limit = region_size; size_t nv_limit = region_size; size_t max_entries; - int i; + int i, ret; if (region_size < sizeof(*xh)) return ocfs2_error(sb, @@ -1028,6 +1067,11 @@ static int ocfs2_validate_xattr_entries_flat(struct super_block *sb, u64 blkno, struct ocfs2_xattr_entry *xe = &xh->xh_entries[i]; size_t name_offset = le16_to_cpu(xe->xe_name_offset); size_t value_offset; + u64 value_len = le64_to_cpu(xe->xe_value_size); + + ret = ocfs2_validate_xattr_entry(sb, blkno, xe); + if (ret) + return ret; if (name_offset > nv_limit || xe->xe_name_len > nv_limit - name_offset) @@ -1042,8 +1086,7 @@ static int ocfs2_validate_xattr_entries_flat(struct super_block *sb, u64 blkno, (unsigned long long)blkno, i); if (ocfs2_xattr_is_local(xe)) { - if (le64_to_cpu(xe->xe_value_size) > - nv_limit - value_offset) + if (value_len > nv_limit - value_offset) return ocfs2_error(sb, "Invalid xattr in block %llu: entry %d value is out of bounds\n", (unsigned long long)blkno, @@ -1125,10 +1168,29 @@ static int ocfs2_validate_xattr_bucket(struct ocfs2_xattr_bucket *bucket, struct ocfs2_xattr_header *xh = bucket_xh(bucket); u16 xattr_count = le16_to_cpu(xh->xh_count); size_t region_size = (size_t)sb->s_blocksize * bucket->bu_blocks; - size_t entries_limit = sb->s_blocksize; + /* + * The entry array grows up from the header across the whole + * bucket region, so it may extend beyond the first bucket block + * when the blocksize is smaller than OCFS2_XATTR_BUCKET_SIZE. + * Name/value pairs, however, always live within a single block. + */ + size_t entries_limit = region_size; size_t nv_limit = sb->s_blocksize; size_t max_entries; - int i; + int i, ret; + + /* + * The entry array is one contiguous region that may span the + * bucket's buffer_heads. Buckets are allocated within clusters, + * so their first block is always aligned to + * OCFS2_XATTR_BUCKET_SIZE and the whole bucket fits in one page. + * A corrupted xattr tree can point a bucket at blocks straddling + * a page, so reject it before touching the entry array. + */ + if (blkno & (bucket->bu_blocks - 1)) + return ocfs2_error(sb, + "Invalid xattr bucket %llu: unaligned block number\n", + (unsigned long long)blkno); if (region_size < sizeof(*xh)) return ocfs2_error(sb, @@ -1156,6 +1218,11 @@ static int ocfs2_validate_xattr_bucket(struct ocfs2_xattr_bucket *bucket, size_t block_off = name_offset >> sb->s_blocksize_bits; size_t block_offset = name_offset % nv_limit; size_t value_offset; + u64 value_len = le64_to_cpu(xe->xe_value_size); + + ret = ocfs2_validate_xattr_entry(sb, blkno, xe); + if (ret) + return ret; if (name_offset >= region_size || block_off >= bucket->bu_blocks) return ocfs2_error(sb, @@ -1174,8 +1241,7 @@ static int ocfs2_validate_xattr_bucket(struct ocfs2_xattr_bucket *bucket, (unsigned long long)blkno, i); if (ocfs2_xattr_is_local(xe)) { - if (le64_to_cpu(xe->xe_value_size) > - nv_limit - value_offset) + if (value_len > nv_limit - value_offset) return ocfs2_error(sb, "Invalid xattr bucket %llu: entry %d value is out of bounds\n", (unsigned long long)blkno, @@ -1323,7 +1389,7 @@ static int ocfs2_xattr_find_entry(struct inode *inode, int name_index, { struct ocfs2_xattr_entry *entry; size_t name_len; - int i, name_offset, cmp = 1; + int i, name_offset, cmp = 1, ret; if (name == NULL) return -EINVAL; @@ -1346,6 +1412,12 @@ static int ocfs2_xattr_find_entry(struct inode *inode, int name_index, return -EFSCORRUPTED; } cmp = memcmp(name, (xs->base + name_offset), name_len); + if (!cmp) { + ret = ocfs2_validate_xattr_entry(inode->i_sb, + OCFS2_I(inode)->ip_blkno, entry); + if (ret) + return ret; + } } if (cmp == 0) break; @@ -2933,6 +3005,9 @@ static int ocfs2_xattr_has_space_inline(struct inode *inode, * * Find extended attribute in inode block and * fill search info into struct ocfs2_xattr_search. + * + * The inline free-space check races with truncate and allocation, so + * callers must hold ip_alloc_sem for writing. */ static int ocfs2_xattr_ibody_find(struct inode *inode, int name_index, @@ -2944,13 +3019,13 @@ static int ocfs2_xattr_ibody_find(struct inode *inode, int ret; int has_space = 0; + lockdep_assert_held_write(&oi->ip_alloc_sem); + if (inode->i_sb->s_blocksize == OCFS2_MIN_BLOCKSIZE) return 0; if (!(oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL)) { - down_read(&oi->ip_alloc_sem); has_space = ocfs2_xattr_has_space_inline(inode, di); - up_read(&oi->ip_alloc_sem); if (!has_space) return 0; } @@ -3031,6 +3106,7 @@ static int ocfs2_xattr_ibody_init(struct inode *inode, * * Set, replace or remove an extended attribute into inode block. * + * Callers must hold ip_alloc_sem for writing. */ static int ocfs2_xattr_ibody_set(struct inode *inode, struct ocfs2_xattr_info *xi, @@ -3041,16 +3117,17 @@ static int ocfs2_xattr_ibody_set(struct inode *inode, struct ocfs2_inode_info *oi = OCFS2_I(inode); struct ocfs2_xa_loc loc; + lockdep_assert_held_write(&oi->ip_alloc_sem); + if (inode->i_sb->s_blocksize == OCFS2_MIN_BLOCKSIZE) return -ENOSPC; - down_write(&oi->ip_alloc_sem); if (!(oi->ip_dyn_features & OCFS2_INLINE_XATTR_FL)) { ret = ocfs2_xattr_ibody_init(inode, xs->inode_bh, ctxt); if (ret) { if (ret != -ENOSPC) mlog_errno(ret); - goto out; + return ret; } } @@ -3060,13 +3137,10 @@ static int ocfs2_xattr_ibody_set(struct inode *inode, if (ret) { if (ret != -ENOSPC) mlog_errno(ret); - goto out; + return ret; } xs->here = loc.xl_entry; -out: - up_write(&oi->ip_alloc_sem); - return ret; } @@ -3429,12 +3503,21 @@ static int ocfs2_calc_xattr_set_need(struct inode *inode, credits += ocfs2_remove_extent_credits(inode->i_sb); goto out; } else { - meta_add += ocfs2_extend_meta_needed(&xv->xr_list); clusters_add += new_clusters - old_clusters; credits += ocfs2_calc_extend_credits(inode->i_sb, &xv->xr_list); - if (value_size >= OCFS2_XATTR_ROOT_SIZE) + /* + * The old value occupies at least as much room as a + * value root, whether it sat outside or inline, so the + * new root fits where it was and no new xattr block or + * bucket is needed -- only the metadata to extend the + * tree hanging off it. A smaller one is replaced + * outright, which meta_guess below reserves for. + */ + if (value_size >= OCFS2_XATTR_ROOT_SIZE) { + meta_add += ocfs2_extend_meta_needed(&xv->xr_list); goto out; + } } } else { /* @@ -3486,6 +3569,10 @@ static int ocfs2_calc_xattr_set_need(struct inode *inode, * Reserve metadata for the new xattr's value extent tree. * The not_found path above adds credits for this tree but * omits meta_add, leaving meta_ac NULL for large values. + * + * This is all of meta_ac on this side beyond the xattr tree + * above: no xattr block is allocated here, and a new bucket or + * index block is paid for out of data_ac. */ if (xi->xi_value_len > OCFS2_XATTR_INLINE_SIZE) meta_add += ocfs2_extend_meta_needed(&def_xv.xv.xr_list); @@ -3724,6 +3811,18 @@ static int __ocfs2_xattr_set_handle(struct inode *inode, return ret; } +/* + * ip_alloc_sem subclass for inodes being initialized before publication. + * ocfs2_xattr_set_handle() runs inside the create transaction, so taking + * ip_alloc_sem there adds a transaction -> ip_alloc_sem order that would + * form a lockdep cycle with the ip_alloc_sem -> transaction order used + * elsewhere, if not for this separate subclass. The inode is unpublished + * so the acquisition can never contend. + */ +enum { + OCFS2_IP_ALLOC_SEM_UNPUBLISHED = 1, +}; + /* * This helper is only for setting initial ACL or security xattrs on an inode * that is still unpublished, unhashed, and unattached to a dentry. @@ -3785,6 +3884,13 @@ int ocfs2_xattr_set_handle(handle_t *handle, xis.inode_bh = xbs.inode_bh = di_bh; di = (struct ocfs2_dinode *)di_bh->b_data; + /* + * The inode is unpublished and cannot contend, but take the + * semaphore anyway so the helpers' lockdep assertions hold. + */ + down_write_nested(&OCFS2_I(inode)->ip_alloc_sem, + OCFS2_IP_ALLOC_SEM_UNPUBLISHED); + ret = ocfs2_xattr_ibody_find(inode, name_index, name, &xis); if (ret) goto cleanup; @@ -3797,6 +3903,7 @@ int ocfs2_xattr_set_handle(handle_t *handle, ret = __ocfs2_xattr_set_handle(inode, di, &xi, &xis, &xbs, &ctxt); cleanup: + up_write(&OCFS2_I(inode)->ip_alloc_sem); brelse(xbs.xattr_bh); ocfs2_xattr_bucket_free(xbs.bucket); @@ -3865,30 +3972,38 @@ int ocfs2_xattr_set(struct inode *inode, di = (struct ocfs2_dinode *)di_bh->b_data; down_write(&OCFS2_I(inode)->ip_xattr_sem); + /* + * The allocation and truncate paths take ip_alloc_sem before + * starting a transaction, so take it here before xattr + * preparation, allocation reservations and ocfs2_start_trans() + * to keep that order. The xattr helpers below no longer take + * it themselves. + */ + down_write(&OCFS2_I(inode)->ip_alloc_sem); /* * Scan inode and external block to find the same name * extended attribute and collect search information. */ ret = ocfs2_xattr_ibody_find(inode, name_index, name, &xis); if (ret) - goto cleanup; + goto out_free_ac; if (xis.not_found) { ret = ocfs2_xattr_block_find(inode, name_index, name, &xbs); if (ret) - goto cleanup; + goto out_free_ac; } if (xis.not_found && xbs.not_found) { ret = -ENODATA; if (flags & XATTR_REPLACE) - goto cleanup; + goto out_free_ac; ret = 0; if (!value) - goto cleanup; + goto out_free_ac; } else { ret = -EEXIST; if (flags & XATTR_CREATE) - goto cleanup; + goto out_free_ac; } /* Check whether the value is refcounted and do some preparation. */ @@ -3899,7 +4014,7 @@ int ocfs2_xattr_set(struct inode *inode, &ref_meta, &ref_credits); if (ret) { mlog_errno(ret); - goto cleanup; + goto out_free_ac; } } @@ -3910,7 +4025,7 @@ int ocfs2_xattr_set(struct inode *inode, if (ret < 0) { inode_unlock(tl_inode); mlog_errno(ret); - goto cleanup; + goto out_free_ac; } } inode_unlock(tl_inode); @@ -3919,7 +4034,7 @@ int ocfs2_xattr_set(struct inode *inode, &xbs, &ctxt, ref_meta, &credits); if (ret) { mlog_errno(ret); - goto cleanup; + goto out_free_ac; } /* we need to update inode's ctime field, so add credit for it. */ @@ -3937,6 +4052,7 @@ int ocfs2_xattr_set(struct inode *inode, ocfs2_commit_trans(osb, ctxt.handle); out_free_ac: + up_write(&OCFS2_I(inode)->ip_alloc_sem); if (ctxt.data_ac) ocfs2_free_alloc_context(ctxt.data_ac); if (ctxt.meta_ac) @@ -3945,7 +4061,6 @@ int ocfs2_xattr_set(struct inode *inode, ocfs2_schedule_truncate_log_flush(osb, 1); ocfs2_run_deallocs(osb, &ctxt.dealloc); -cleanup: if (ref_tree) ocfs2_unlock_refcount_tree(osb, ref_tree, 1); up_write(&OCFS2_I(inode)->ip_xattr_sem); @@ -4076,6 +4191,10 @@ static int ocfs2_find_xe_in_bucket(struct inode *inode, xe_name = bucket_block(bucket, block_off) + new_offset; if (!memcmp(name, xe_name, name_len)) { + ret = ocfs2_validate_xattr_entry(inode->i_sb, + OCFS2_I(inode)->ip_blkno, xe); + if (ret) + break; *xe_index = i; *found = 1; ret = 0; @@ -4646,6 +4765,10 @@ static void ocfs2_xattr_update_xattr_search(struct inode *inode, xs->here = xs->header->xh_entries; } +/* + * Caller must hold ip_alloc_sem for writing, since a new xattr block + * is allocated and the xattr block header is rewritten. + */ static int ocfs2_xattr_create_index_block(struct inode *inode, struct ocfs2_xattr_info *xi, struct ocfs2_xattr_search *xs, @@ -4662,19 +4785,14 @@ static int ocfs2_xattr_create_index_block(struct inode *inode, struct ocfs2_xattr_tree_root *xr; u16 xb_flags = le16_to_cpu(xb->xb_flags); + lockdep_assert_held_write(&oi->ip_alloc_sem); + trace_ocfs2_xattr_create_index_block_begin( (unsigned long long)xb_bh->b_blocknr); BUG_ON(xb_flags & OCFS2_XATTR_INDEXED); BUG_ON(!xs->bucket); - /* - * XXX: - * We can use this lock for now, and maybe move to a dedicated mutex - * if performance becomes a problem later. - */ - down_write(&oi->ip_alloc_sem); - ret = ocfs2_journal_access_xb(handle, INODE_CACHE(inode), xb_bh, OCFS2_JOURNAL_ACCESS_WRITE); if (ret) { @@ -4736,8 +4854,6 @@ static int ocfs2_xattr_create_index_block(struct inode *inode, ocfs2_journal_dirty(handle, xb_bh); out: - up_write(&oi->ip_alloc_sem); - return ret; } @@ -4817,6 +4933,9 @@ static int ocfs2_defrag_xattr_bucket(struct inode *inode, xe = xh->xh_entries; end = OCFS2_XATTR_BUCKET_SIZE; for (i = 0; i < le16_to_cpu(xh->xh_count); i++, xe++) { + ret = ocfs2_validate_xattr_entry(inode->i_sb, blkno, xe); + if (ret) + goto out; offset = le16_to_cpu(xe->xe_name_offset); len = namevalue_size_xe(xe); @@ -4833,16 +4952,22 @@ static int ocfs2_defrag_xattr_bucket(struct inode *inode, memmove(bucket_buf + end - len, bucket_buf + offset, len); xe->xe_name_offset = cpu_to_le16(end - len); + } else if (end < offset + len) { + ret = ocfs2_error(inode->i_sb, + "Defrag check failed for bucket %llu\n", + (unsigned long long)blkno); + goto out; } - mlog_bug_on_msg(end < offset + len, "Defrag check failed for " - "bucket %llu\n", (unsigned long long)blkno); - end -= len; } - mlog_bug_on_msg(xh_free_start > end, "Defrag check failed for " - "bucket %llu\n", (unsigned long long)blkno); + if (xh_free_start > end) { + ret = ocfs2_error(inode->i_sb, + "Defrag check failed for bucket %llu\n", + (unsigned long long)blkno); + goto out; + } if (xh_free_start == end) goto out; @@ -5107,6 +5232,9 @@ static int ocfs2_divide_xattr_bucket(struct inode *inode, name_value_len = 0; for (i = 0; i < start; i++) { xe = &xh->xh_entries[i]; + ret = ocfs2_validate_xattr_entry(inode->i_sb, blk, xe); + if (ret) + goto out; name_value_len += namevalue_size_xe(xe); if (le16_to_cpu(xe->xe_name_offset) < name_offset) name_offset = le16_to_cpu(xe->xe_name_offset); @@ -7711,17 +7839,46 @@ static int ocfs2_initxattrs(struct inode *inode, const struct xattr *xattr_array { struct ocfs2_security_xattr_info *si = fs_info; const struct xattr *xattr; + struct ocfs2_security_xattr *xattrs; + int count = 0, i; int err = 0; if (si) { - si->value = kmemdup(xattr_array->value, xattr_array->value_len, - GFP_KERNEL); - if (!si->value) + for (xattr = xattr_array; xattr->name != NULL; xattr++) + count++; + + xattrs = kcalloc(count, sizeof(*xattrs), GFP_NOFS); + if (!xattrs) return -ENOMEM; - si->name = xattr_array->name; - si->value_len = xattr_array->value_len; + for (i = 0; i < count; i++) { + xattrs[i].name = kstrdup(xattr_array[i].name, GFP_NOFS); + if (!xattrs[i].name) { + err = -ENOMEM; + goto out_err; + } + + xattrs[i].value = kmemdup(xattr_array[i].value, + xattr_array[i].value_len, + GFP_NOFS); + if (!xattrs[i].value) { + err = -ENOMEM; + goto out_err; + } + xattrs[i].value_len = xattr_array[i].value_len; + } + + si->xattrs = xattrs; + si->count = count; return 0; + +out_err: + for (; i >= 0; i--) { + kfree(xattrs[i].name); + kfree(xattrs[i].value); + } + kfree(xattrs); + return err; } for (xattr = xattr_array; xattr->name != NULL; xattr++) { @@ -7734,6 +7891,19 @@ static int ocfs2_initxattrs(struct inode *inode, const struct xattr *xattr_array return err; } +void ocfs2_free_security_xattrs(struct ocfs2_security_xattr_info *si) +{ + int i; + + for (i = 0; i < si->count; i++) { + kfree(si->xattrs[i].name); + kfree(si->xattrs[i].value); + } + kfree(si->xattrs); + si->xattrs = NULL; + si->count = 0; +} + int ocfs2_init_security_get(struct inode *inode, struct inode *dir, const struct qstr *qstr, @@ -7751,7 +7921,7 @@ int ocfs2_init_security_get(struct inode *inode, * security_inode_init_security() does not return -EOPNOTSUPP, * we have to check the xattr ourselves. */ - if (!ret && !si->name) + if (!ret && !si->count) si->enable = 0; return ret; @@ -7768,10 +7938,21 @@ int ocfs2_init_security_set(handle_t *handle, struct ocfs2_alloc_context *xattr_ac, struct ocfs2_alloc_context *data_ac) { - return ocfs2_xattr_set_handle(handle, inode, di_bh, - OCFS2_XATTR_INDEX_SECURITY, - si->name, si->value, si->value_len, 0, - xattr_ac, data_ac); + int i; + int ret = 0; + + for (i = 0; i < si->count; i++) { + ret = ocfs2_xattr_set_handle(handle, inode, di_bh, + OCFS2_XATTR_INDEX_SECURITY, + si->xattrs[i].name, + si->xattrs[i].value, + si->xattrs[i].value_len, 0, + xattr_ac, data_ac); + if (ret) + break; + } + + return ret; } const struct xattr_handler ocfs2_xattr_security_handler = { diff --git a/fs/ocfs2/xattr.h b/fs/ocfs2/xattr.h index 887cc1a18b1a..1dd08f979e3c 100644 --- a/fs/ocfs2/xattr.h +++ b/fs/ocfs2/xattr.h @@ -20,13 +20,18 @@ enum ocfs2_xattr_type { OCFS2_XATTR_MAX }; -struct ocfs2_security_xattr_info { - int enable; - const char *name; +struct ocfs2_security_xattr { + char *name; void *value; size_t value_len; }; +struct ocfs2_security_xattr_info { + int enable; + struct ocfs2_security_xattr *xattrs; + int count; +}; + extern const struct xattr_handler ocfs2_xattr_user_handler; extern const struct xattr_handler ocfs2_xattr_trusted_handler; extern const struct xattr_handler ocfs2_xattr_security_handler; @@ -49,6 +54,7 @@ int ocfs2_xattr_remove(struct inode *, struct buffer_head *); int ocfs2_init_security_get(struct inode *, struct inode *, const struct qstr *, struct ocfs2_security_xattr_info *); +void ocfs2_free_security_xattrs(struct ocfs2_security_xattr_info *); int ocfs2_init_security_set(handle_t *, struct inode *, struct buffer_head *, struct ocfs2_security_xattr_info *, diff --git a/fs/overlayfs/readdir.c b/fs/overlayfs/readdir.c index e23331212a29..4cd4af097e5c 100644 --- a/fs/overlayfs/readdir.c +++ b/fs/overlayfs/readdir.c @@ -36,12 +36,14 @@ struct ovl_cache_entry { struct ovl_dir_cache { long refcount; u64 version; + bool is_refcounted; struct list_head entries; struct rb_root root; }; struct ovl_readdir_data { struct dir_context ctx; + const struct file *user_file; struct dentry *dentry; bool is_lowest; struct rb_root *root; @@ -376,7 +378,8 @@ static inline int ovl_dir_read(const struct path *realpath, struct file *realfile; int err; - realfile = ovl_path_open(realpath, O_RDONLY | O_LARGEFILE); + realfile = ovl_path_open_realfile(rdd->user_file, realpath, + O_RDONLY | O_LARGEFILE); if (IS_ERR(realfile)) return PTR_ERR(realfile); @@ -420,13 +423,14 @@ static void ovl_dir_reset(struct file *file) } static int ovl_dir_read_merged(struct dentry *dentry, struct list_head *list, - struct rb_root *root) + struct rb_root *root, const struct file *user_file) { int err; struct path realpath; struct ovl_readdir_data rdd = { .ctx.actor = ovl_fill_merge, .ctx.count = INT_MAX, + .user_file = user_file, .dentry = dentry, .list = list, .root = root, @@ -479,13 +483,32 @@ static void ovl_seek_cursor(struct ovl_dir_file *od, loff_t pos) od->cursor = p; } -static struct ovl_dir_cache *ovl_cache_get(struct dentry *dentry) +/* + * Merged (refcounted) and impure (not refcounted) caches are never + * expected to be mixed. On mismatch, detach the cache from the inode + * and leak it rather than misuse it. A merged cache is still freed by + * its last ovl_cache_put(). + */ +static struct ovl_dir_cache *ovl_dir_cache_check(struct inode *inode, + bool is_refcounted) +{ + struct ovl_dir_cache *cache = ovl_dir_cache(inode); + + if (cache && WARN_ON(cache->is_refcounted != is_refcounted)) { + ovl_set_dir_cache(inode, NULL); + return NULL; + } + return cache; +} + +static struct ovl_dir_cache *ovl_dir_cache_get(struct file *file) { int res; + struct dentry *dentry = file->f_path.dentry; struct ovl_dir_cache *cache; struct inode *inode = d_inode(dentry); - cache = ovl_dir_cache(inode); + cache = ovl_dir_cache_check(inode, true); if (cache && ovl_inode_version_get(inode) == cache->version) { WARN_ON(!cache->refcount); cache->refcount++; @@ -498,10 +521,11 @@ static struct ovl_dir_cache *ovl_cache_get(struct dentry *dentry) return ERR_PTR(-ENOMEM); cache->refcount = 1; + cache->is_refcounted = true; INIT_LIST_HEAD(&cache->entries); cache->root = RB_ROOT; - res = ovl_dir_read_merged(dentry, &cache->entries, &cache->root); + res = ovl_dir_read_merged(dentry, &cache->entries, &cache->root, file); if (res) { ovl_cache_free(&cache->entries); kfree(cache); @@ -645,8 +669,8 @@ static bool ovl_fill_plain(struct dir_context *ctx, const char *name, return true; } -static int ovl_dir_read_impure(const struct path *path, struct list_head *list, - struct rb_root *root) +static int ovl_dir_read_impure(const struct path *path, struct list_head *list, + struct rb_root *root, const struct file *user_file) { int err; struct path realpath; @@ -654,6 +678,7 @@ static int ovl_dir_read_impure(const struct path *path, struct list_head *list, struct ovl_readdir_data rdd = { .ctx.actor = ovl_fill_plain, .ctx.count = INT_MAX, + .user_file = user_file, .list = list, .root = root, }; @@ -690,15 +715,16 @@ static int ovl_dir_read_impure(const struct path *path, struct list_head *list, return 0; } -static struct ovl_dir_cache *ovl_cache_get_impure(const struct path *path) +static struct ovl_dir_cache *ovl_cache_get_impure(struct file *file) { int res; + const struct path *path = &file->f_path; struct dentry *dentry = path->dentry; struct inode *inode = d_inode(dentry); struct ovl_fs *ofs = OVL_FS(dentry->d_sb); struct ovl_dir_cache *cache; - cache = ovl_dir_cache(inode); + cache = ovl_dir_cache_check(inode, false); if (cache && ovl_inode_version_get(inode) == cache->version) return cache; @@ -710,7 +736,8 @@ static struct ovl_dir_cache *ovl_cache_get_impure(const struct path *path) if (!cache) return ERR_PTR(-ENOMEM); - res = ovl_dir_read_impure(path, &cache->entries, &cache->root); + cache->is_refcounted = false; + res = ovl_dir_read_impure(path, &cache->entries, &cache->root, file); if (res) { ovl_cache_free(&cache->entries); kfree(cache); @@ -831,7 +858,7 @@ static int ovl_iterate_real(struct file *file, struct dir_context *ctx) dput(parent); if (ovl_is_impure_dir(file)) { - rdt.cache = ovl_cache_get_impure(&file->f_path); + rdt.cache = ovl_cache_get_impure(file); if (IS_ERR(rdt.cache)) return PTR_ERR(rdt.cache); } @@ -845,14 +872,13 @@ static int ovl_iterate_real(struct file *file, struct dir_context *ctx) static int ovl_iterate_merged(struct file *file, struct dir_context *ctx) { struct ovl_dir_file *od = file->private_data; - struct dentry *dentry = file->f_path.dentry; struct ovl_cache_entry *p; int err; if (!od->cache) { struct ovl_dir_cache *cache; - cache = ovl_cache_get(dentry); + cache = ovl_dir_cache_get(file); if (IS_ERR(cache)) return PTR_ERR(cache); @@ -1099,7 +1125,7 @@ int ovl_check_empty_dir(struct dentry *dentry, struct list_head *list) struct rb_root root = RB_ROOT; with_ovl_creds(dentry->d_sb) - err = ovl_dir_read_merged(dentry, list, &root); + err = ovl_dir_read_merged(dentry, list, &root, NULL); if (err) return err; diff --git a/fs/pidfs.c b/fs/pidfs.c index 1bd130eb909a..03422f49be65 100644 --- a/fs/pidfs.c +++ b/fs/pidfs.c @@ -511,6 +511,14 @@ static long pidfd_info(struct file *file, unsigned int cmd, unsigned long arg) kinfo.supported_mask = PIDFD_INFO_SUPPORTED; } + /* Only report fields that fit into the caller's struct. */ + if (usize < PIDFD_INFO_SIZE_VER1) + kinfo.mask &= ~(PIDFD_INFO_COREDUMP | PIDFD_INFO_COREDUMP_SIGNAL); + if (usize < PIDFD_INFO_SIZE_VER2) + kinfo.mask &= ~PIDFD_INFO_COREDUMP_CODE; + if (usize < PIDFD_INFO_SIZE_VER3) + kinfo.mask &= ~PIDFD_INFO_SUPPORTED_MASK; + /* Are there bits in the return mask not present in PIDFD_INFO_SUPPORTED? */ WARN_ON_ONCE(~PIDFD_INFO_SUPPORTED & kinfo.mask); /* diff --git a/fs/proc/base.c b/fs/proc/base.c index 6a39de424f62..1455de58e53c 100644 --- a/fs/proc/base.c +++ b/fs/proc/base.c @@ -2519,17 +2519,23 @@ static int show_timer(struct seq_file *m, void *v) struct k_itimer *timer = hlist_entry((struct hlist_node *)v, struct k_itimer, list); struct timers_private *tp = m->private; int notify = timer->it_sigev_notify; + pid_t nr = 0; guard(spinlock_irq)(&timer->it_lock); if (!posixtimer_valid(timer)) return 0; + if (timer->it_pid && pid_has_task(timer->it_pid, timer->it_pid_type)) + nr = pid_nr_ns(timer->it_pid, tp->ns); + else + notify = SIGEV_NONE; + seq_printf(m, "ID: %d\n", timer->it_id); seq_printf(m, "signal: %d/%px\n", timer->sigq.info.si_signo, timer->sigq.info.si_value.sival_ptr); seq_printf(m, "notify: %s/%s.%d\n", nstr[notify & ~SIGEV_THREAD_ID], (notify & SIGEV_THREAD_ID) ? "tid" : "pid", - pid_nr_ns(timer->it_pid, tp->ns)); + nr); seq_printf(m, "ClockID: %d\n", timer->it_clock); return 0; diff --git a/fs/proc/internal.h b/fs/proc/internal.h index 04bd6c9e65a7..b1913f851b70 100644 --- a/fs/proc/internal.h +++ b/fs/proc/internal.h @@ -395,6 +395,7 @@ struct proc_maps_private { struct inode *inode; struct task_struct *task; struct vma_iterator iter; + struct vma_rcu_iter rvmi; loff_t last_pos; struct proc_maps_locking_ctx lock_ctx; #ifdef CONFIG_NUMA diff --git a/fs/proc/kcore.c b/fs/proc/kcore.c index 390547b992ac..3264c99bd68a 100644 --- a/fs/proc/kcore.c +++ b/fs/proc/kcore.c @@ -531,12 +531,14 @@ static ssize_t read_kcore_iter(struct kiocb *iocb, struct iov_iter *iter) * again until we are done. */ while (true) { - read += vread_iter(iter, src, left); + size_t n = vread_iter(iter, src, left); + + read += n; if (read == tsz) break; - src += read; - left -= read; + src += n; + left -= n; if (fault_in_iov_iter_writeable(iter, left)) { ret = -EFAULT; diff --git a/fs/proc/task_mmu.c b/fs/proc/task_mmu.c index 2eaa79ab1138..a0b12cfb34c3 100644 --- a/fs/proc/task_mmu.c +++ b/fs/proc/task_mmu.c @@ -191,7 +191,7 @@ static struct vm_area_struct *get_next_vma(struct proc_maps_private *priv, return vma_next(&priv->iter); unlock_ctx_vma(lock_ctx); - vma = lock_next_vma(lock_ctx->mm, &priv->iter, last_pos); + vma = lock_next_vma(&priv->rvmi, last_pos); if (!IS_ERR_OR_NULL(vma)) lock_ctx->locked_vma = vma; @@ -341,7 +341,7 @@ static void *m_start(struct seq_file *m, loff_t *ppos) */ if (last_addr > 0) *ppos = last_addr = priv->last_pos; - vma_iter_init(&priv->iter, mm, (unsigned long)last_addr); + vma_rcu_iter_init(&priv->rvmi, mm, &priv->iter, (unsigned long)last_addr); hold_task_mempolicy(priv); if (last_addr == SENTINEL_VMA_GATE) return get_gate_vma(mm); @@ -583,6 +583,7 @@ static struct vm_area_struct *query_vma_find_by_addr(struct proc_maps_locking_ct struct mm_struct *mm = lock_ctx->mm; struct vm_area_struct *vma; struct vma_iterator vmi; + struct vma_rcu_iter rvmi; if (lock_ctx->mmap_locked) return find_vma(mm, addr); @@ -590,8 +591,8 @@ static struct vm_area_struct *query_vma_find_by_addr(struct proc_maps_locking_ct /* Unlock previously locked VMA and find the next one under RCU */ unlock_ctx_vma(lock_ctx); rcu_read_lock(); - vma_iter_init(&vmi, mm, addr); - vma = lock_next_vma(mm, &vmi, addr); + vma_rcu_iter_init(&rvmi, mm, &vmi, addr); + vma = lock_next_vma(&rvmi, addr); rcu_read_unlock(); if (!vma) diff --git a/fs/pstore/ram.c b/fs/pstore/ram.c index 2eb0d4fa2186..aa056d0395a4 100644 --- a/fs/pstore/ram.c +++ b/fs/pstore/ram.c @@ -604,6 +604,7 @@ static int ramoops_init_prz(const char *name, if (IS_ERR(*prz)) { int err = PTR_ERR(*prz); + *prz = NULL; dev_err(dev, "failed to request %s mem region (0x%zx@0x%llx): %d\n", name, sz, (unsigned long long)*paddr, err); return err; diff --git a/fs/pstore/ram_core.c b/fs/pstore/ram_core.c index b4ec8009b8dc..ae941777037b 100644 --- a/fs/pstore/ram_core.c +++ b/fs/pstore/ram_core.c @@ -505,6 +505,12 @@ static int persistent_ram_buffer_map(phys_addr_t start, phys_addr_t size, prz->paddr = start; prz->size = size; + if (size <= sizeof(struct persistent_ram_buffer)) { + pr_err("%s: persistent ram zone too small (%#llx bytes)\n", + prz->label, (unsigned long long)size); + return -EINVAL; + } + if (pfn_valid(start >> PAGE_SHIFT)) prz->vaddr = persistent_ram_vmap(start, size, memtype); else diff --git a/fs/quota/dquot.c b/fs/quota/dquot.c index 1c78c695d0dd..cd142c9cc7e0 100644 --- a/fs/quota/dquot.c +++ b/fs/quota/dquot.c @@ -2942,7 +2942,7 @@ static const struct ctl_table fs_dqstats_table[] = { }, }; -static int __init dquot_init(void) +void __init dquot_cache_init(void) { int i, ret; unsigned long nr_hash; @@ -2950,8 +2950,6 @@ static int __init dquot_init(void) printk(KERN_NOTICE "VFS: Disk quotas %s\n", __DQUOT_VERSION__); - register_sysctl_init("fs/quota", fs_dqstats_table); - dquot_cachep = kmem_cache_create("dquot", sizeof(struct dquot), sizeof(unsigned long) * 4, (SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT| @@ -2992,7 +2990,11 @@ static int __init dquot_init(void) WQ_UNBOUND | WQ_MEM_RECLAIM, WQ_MAX_ACTIVE); if (!quota_unbound_wq) panic("Cannot create quota_unbound_wq\n"); +} +static int __init init_fs_dquot_sysctls(void) +{ + register_sysctl_init("fs/quota", fs_dqstats_table); return 0; } -fs_initcall(dquot_init); +fs_initcall(init_fs_dquot_sysctls); diff --git a/fs/resctrl/rdtgroup.c b/fs/resctrl/rdtgroup.c index 5dcbb0a964e8..6733ed174f51 100644 --- a/fs/resctrl/rdtgroup.c +++ b/fs/resctrl/rdtgroup.c @@ -685,7 +685,7 @@ static int __rdtgroup_move_task(struct task_struct *tsk, static bool is_closid_match(struct task_struct *t, struct rdtgroup *r) { - return (resctrl_arch_alloc_capable() && (r->type == RDTCTRL_GROUP) && + return (r->type == RDTCTRL_GROUP && resctrl_arch_match_closid(t, r->closid)); } diff --git a/fs/smb/client/connect.c b/fs/smb/client/connect.c index 9795aa0661d5..230b7a4a500e 100644 --- a/fs/smb/client/connect.c +++ b/fs/smb/client/connect.c @@ -4184,8 +4184,12 @@ cifs_setup_session(const unsigned int xid, struct cifs_ses *ses, if (rc) { if (new_ses) { + enum securityEnum sectype; + + sectype = server->ops->select_sectype(server, + ses->sectype); cifs_server_dbg(VFS, "failed to create a new SMB session with %s: %d\n", - get_security_type_str(ses->sectype), rc); + get_security_type_str(sectype), rc); } spin_lock(&ses->ses_lock); if (ses->ses_status == SES_IN_SETUP) diff --git a/fs/smb/server/Kconfig b/fs/smb/server/Kconfig index 221ec9717a83..622d8f4d2773 100644 --- a/fs/smb/server/Kconfig +++ b/fs/smb/server/Kconfig @@ -16,6 +16,7 @@ config SMB_SERVER select CRYPTO_AEAD2 select CRYPTO_CCM select CRYPTO_GCM + select CRYPTO_AES select ASN1 select OID_REGISTRY select CRC32 diff --git a/fs/smb/server/connection.c b/fs/smb/server/connection.c index b519376ecc17..d66fc0fbe526 100644 --- a/fs/smb/server/connection.c +++ b/fs/smb/server/connection.c @@ -114,7 +114,7 @@ static int proc_show_clients(struct seq_file *m, void *v) sessions++; rcu_read_unlock(); #if IS_ENABLED(CONFIG_IPV6) - if (!conn->inet_addr) + if (conn->is_ipv6) seq_printf(m, "client:\t%pI6c\n", &conn->inet6_addr); else #endif diff --git a/fs/smb/server/connection.h b/fs/smb/server/connection.h index a4f5a64b36b4..8e0da44a1e0f 100644 --- a/fs/smb/server/connection.h +++ b/fs/smb/server/connection.h @@ -68,6 +68,9 @@ struct ksmbd_conn { u8 inet6_addr[16]; #endif }; +#if IS_ENABLED(CONFIG_IPV6) + bool is_ipv6; +#endif unsigned int inet_hash; char *request_buf; struct ksmbd_transport *transport; diff --git a/fs/smb/server/ksmbd_work.h b/fs/smb/server/ksmbd_work.h index 6877f6838118..be98a2c3be77 100644 --- a/fs/smb/server/ksmbd_work.h +++ b/fs/smb/server/ksmbd_work.h @@ -54,10 +54,7 @@ struct ksmbd_work { /* Current cmd hdr in compound rsp buf*/ int curr_smb2_rsp_hdr_off; - /* - * Current Local FID assigned compound response if SMB2 CREATE - * command is present in compound request - */ + /* FileId generated or used by the previous operation in a compound. */ u64 compound_fid; u64 compound_pfid; u64 compound_sid; @@ -95,6 +92,10 @@ struct ksmbd_work { bool owns_conn_ref:1; bool need_invalidate_rkey:1; bool request_open_chseq_tracked:1; + /* The previous command carries a FileId or is a CREATE. */ + bool compound_fid_present:1; + /* A related command failed because there was no FileId to inherit. */ + bool compound_fid_missing:1; bool session_setup_reauth:1; unsigned int remote_key; diff --git a/fs/smb/server/mgmt/share_config.c b/fs/smb/server/mgmt/share_config.c index cc9f18ede80d..f85134c38cdd 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 @@ -108,6 +109,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); } @@ -182,6 +184,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) { @@ -272,12 +311,12 @@ static struct ksmbd_share_config *share_config_request(struct ksmbd_work *work, } scoped_with_init_fs() - 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 d157545fe7d1..91691b525907 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/mgmt/user_session.c b/fs/smb/server/mgmt/user_session.c index d131809dd08a..260fc07709c4 100644 --- a/fs/smb/server/mgmt/user_session.c +++ b/fs/smb/server/mgmt/user_session.c @@ -4,6 +4,7 @@ */ #include +#include #include #include #include @@ -43,11 +44,6 @@ void ksmbd_session_release_slot(struct ksmbd_conn *conn) atomic64_dec(&conn->session_count); } -struct ksmbd_session_rpc { - int id; - unsigned int method; -}; - #ifdef CONFIG_PROC_FS static const struct ksmbd_const_name ksmbd_sess_cap_const_names[] = { @@ -153,7 +149,7 @@ static int show_proc_session(struct seq_file *m, void *v) const char *name; #if IS_ENABLED(CONFIG_IPV6) - if (chan->conn->inet_addr) + if (!chan->conn->is_ipv6) seq_printf(m, "client:\t%pI4\n", &chan->conn->inet_addr); else @@ -256,7 +252,7 @@ static int show_proc_sessions(struct seq_file *m, void *v) ksmbd_user_session_get(session); #if IS_ENABLED(CONFIG_IPV6) - if (!chan->conn->inet_addr) + if (chan->conn->is_ipv6) seq_printf(m, "client:\t%pI6c\n", &chan->conn->inet6_addr); else #endif @@ -305,32 +301,35 @@ static void free_channel_list(struct ksmbd_session *sess) up_write(&sess->chann_lock); } -static void __session_rpc_close(struct ksmbd_session *sess, - struct ksmbd_session_rpc *entry) +static void ksmbd_session_rpc_free(struct ksmbd_session_rpc *entry) +{ + if (refcount_dec_and_test(&entry->refcount)) { + ksmbd_rpc_id_free(entry->id); + kvfree(entry->pending); + kfree(entry); + } +} + +static void __session_rpc_close(struct ksmbd_session_rpc *entry) { struct ksmbd_rpc_command *resp; - resp = ksmbd_rpc_close(sess, entry->id); + mutex_lock(&entry->lock); + resp = ksmbd_rpc_close(entry); if (!resp) pr_err("Unable to close RPC pipe %d\n", entry->id); - kvfree(resp); - ksmbd_rpc_id_free(entry->id); - kfree(entry); + mutex_unlock(&entry->lock); + ksmbd_session_rpc_free(entry); } -static void ksmbd_session_rpc_clear_list(struct ksmbd_session *sess) +void ksmbd_session_rpc_clear_list(struct ksmbd_session *sess) { struct ksmbd_session_rpc *entry; - long index; - - down_write(&sess->rpc_lock); - xa_for_each(&sess->rpc_handle_list, index, entry) { - xa_erase(&sess->rpc_handle_list, index); - __session_rpc_close(sess, entry); - } - up_write(&sess->rpc_lock); + unsigned long index; + xa_for_each(&sess->rpc_handle_list, index, entry) + ksmbd_session_rpc_close(sess, index); xa_destroy(&sess->rpc_handle_list); } @@ -360,9 +359,9 @@ static int __rpc_method(char *rpc_name) int ksmbd_session_rpc_open(struct ksmbd_session *sess, char *rpc_name) { - struct ksmbd_session_rpc *entry, *old; + struct ksmbd_session_rpc *entry; struct ksmbd_rpc_command *resp; - int method, id; + int method, id, ret; method = __rpc_method(rpc_name); if (method < 0) @@ -374,31 +373,29 @@ int ksmbd_session_rpc_open(struct ksmbd_session *sess, char *rpc_name) entry->method = method; entry->id = id = ksmbd_ipc_id_alloc(); - if (id < 0) - goto free_entry; - - down_write(&sess->rpc_lock); - old = xa_store(&sess->rpc_handle_list, id, entry, KSMBD_DEFAULT_GFP); - if (xa_is_err(old)) { - up_write(&sess->rpc_lock); - goto free_id; + if (id < 0) { + kfree(entry); + return id; } + mutex_init(&entry->lock); + refcount_set(&entry->refcount, 1); - resp = ksmbd_rpc_open(sess, id); + resp = ksmbd_rpc_open(entry); if (!resp) { - xa_erase(&sess->rpc_handle_list, entry->id); - up_write(&sess->rpc_lock); - goto free_id; + ksmbd_session_rpc_free(entry); + return -EINVAL; } + kvfree(resp); + down_write(&sess->rpc_lock); + ret = xa_err(xa_store(&sess->rpc_handle_list, id, entry, + KSMBD_DEFAULT_GFP)); up_write(&sess->rpc_lock); - kvfree(resp); + if (ret) { + __session_rpc_close(entry); + return ret; + } return id; -free_id: - ksmbd_rpc_id_free(entry->id); -free_entry: - kfree(entry); - return -EINVAL; } void ksmbd_session_rpc_close(struct ksmbd_session *sess, int id) @@ -408,8 +405,53 @@ void ksmbd_session_rpc_close(struct ksmbd_session *sess, int id) down_write(&sess->rpc_lock); entry = xa_erase(&sess->rpc_handle_list, id); if (entry) - __session_rpc_close(sess, entry); + WRITE_ONCE(entry->closed, true); up_write(&sess->rpc_lock); + if (entry) + __session_rpc_close(entry); +} + +/* The reference pins the entry while waiting without holding rpc_lock. */ +struct ksmbd_session_rpc *ksmbd_session_rpc_get(struct ksmbd_work *work, + int id) +{ + struct ksmbd_session_rpc *entry; + int err; + + down_read(&work->sess->rpc_lock); + entry = xa_load(&work->sess->rpc_handle_list, id); + if (entry) + refcount_inc(&entry->refcount); + up_read(&work->sess->rpc_lock); + if (!entry) + return ERR_PTR(-ENOENT); + + mutex_lock(&entry->lock); + if (READ_ONCE(work->state) == KSMBD_WORK_CANCELLED) { + err = -ECANCELED; + goto err_put; + } + if (ksmbd_conn_exiting(work->conn) || + ksmbd_conn_releasing(work->conn) || + READ_ONCE(work->sess->tearing_down)) { + err = -ESHUTDOWN; + goto err_put; + } + if (READ_ONCE(entry->closed)) { + err = -EBADF; + goto err_put; + } + return entry; + +err_put: + ksmbd_session_rpc_put(entry); + return ERR_PTR(err); +} + +void ksmbd_session_rpc_put(struct ksmbd_session_rpc *entry) +{ + mutex_unlock(&entry->lock); + ksmbd_session_rpc_free(entry); } int ksmbd_session_rpc_method(struct ksmbd_session *sess, int id) @@ -907,14 +949,14 @@ void destroy_previous_session(struct ksmbd_conn *conn, up_write(&prev_sess->chann_lock); goto out; } - prev_sess->tearing_down = true; + WRITE_ONCE(prev_sess->tearing_down, true); up_write(&prev_sess->chann_lock); ksmbd_all_conn_set_status(prev_sess, KSMBD_SESS_NEED_RECONNECT); err = ksmbd_conn_wait_idle_sess(conn, prev_sess); if (err) { down_write(&prev_sess->chann_lock); - prev_sess->tearing_down = false; + WRITE_ONCE(prev_sess->tearing_down, false); up_write(&prev_sess->chann_lock); ksmbd_all_conn_set_status(prev_sess, KSMBD_SESS_GOOD); goto out; diff --git a/fs/smb/server/mgmt/user_session.h b/fs/smb/server/mgmt/user_session.h index 8e4ddb04f0e6..5f0f6276e316 100644 --- a/fs/smb/server/mgmt/user_session.h +++ b/fs/smb/server/mgmt/user_session.h @@ -7,6 +7,8 @@ #define __USER_SESSION_MANAGEMENT_H__ #include +#include +#include #include #include "../smb_common.h" @@ -17,6 +19,18 @@ #define PREAUTH_HASHVALUE_SIZE 64 struct ksmbd_file_table; +struct ksmbd_rpc_command; +struct ksmbd_work; + +struct ksmbd_session_rpc { + int id; + unsigned int method; + struct mutex lock; + refcount_t refcount; + bool closed; + struct ksmbd_rpc_command *pending; + unsigned int pending_offset; +}; struct channel { char sess_key[CIFS_KEY_SIZE]; @@ -133,7 +147,11 @@ void ksmbd_release_tree_conn_id(struct ksmbd_session *sess, int id); int ksmbd_session_rpc_open(struct ksmbd_session *sess, char *rpc_name); void ksmbd_session_rpc_close(struct ksmbd_session *sess, int id); +void ksmbd_session_rpc_clear_list(struct ksmbd_session *sess); int ksmbd_session_rpc_method(struct ksmbd_session *sess, int id); +struct ksmbd_session_rpc *ksmbd_session_rpc_get(struct ksmbd_work *work, + int id); +void ksmbd_session_rpc_put(struct ksmbd_session_rpc *entry); void ksmbd_user_session_get(struct ksmbd_session *sess); void ksmbd_user_session_put(struct ksmbd_session *sess); int create_proc_sessions(void); diff --git a/fs/smb/server/oplock.c b/fs/smb/server/oplock.c index 313bf01ad350..96b36b8329a6 100644 --- a/fs/smb/server/oplock.c +++ b/fs/smb/server/oplock.c @@ -125,6 +125,12 @@ static void lease_add_table(struct lease *lease, struct lease_table *lb) spin_unlock(&lb->lb_lock); } +static void free_lease_table(struct lease_table *lb) +{ + kfree(lb); +} + +/* The caller holds lease_list_lock for write. */ static void lease_del_table(struct lease *lease) { struct lease_table *lb = lease->l_lb; @@ -143,6 +149,10 @@ static void lease_del_table(struct lease *lease) spin_unlock(&lb->lb_lock); lease_put(lease); + if (list_empty(&lb->lease_list)) { + list_del(&lb->l_entry); + free_lease_table(lb); + } } static struct lease_table *alloc_lease_table(struct oplock_info *opinfo) @@ -155,21 +165,11 @@ static struct lease_table *alloc_lease_table(struct oplock_info *opinfo) memcpy(lb->client_guid, opinfo->conn->ClientGUID, SMB2_CLIENT_GUID_SIZE); - lb->conn = ksmbd_conn_get(opinfo->conn); INIT_LIST_HEAD(&lb->lease_list); spin_lock_init(&lb->lb_lock); return lb; } -static void free_lease_table(struct lease_table *lb) -{ - if (!lb) - return; - - ksmbd_conn_put(lb->conn); - kfree(lb); -} - static struct lease *alloc_lease(struct lease_ctx_info *lctx, struct ksmbd_inode *ci) { @@ -927,8 +927,6 @@ static int smb2_break_collect_channels(struct oplock_info *opinfo, if (lb) { memcpy(guid, lb->client_guid, sizeof(guid)); have_guid = true; - if (lb->conn) - owner->conn = ksmbd_conn_get(lb->conn); } read_unlock(&lease_list_lock); } @@ -1495,25 +1493,17 @@ static void oplock_break_drain_none(struct list_head *head, } } -void destroy_lease_table(struct ksmbd_conn *conn) +void destroy_lease_table(void) { - struct lease_table *lb, *lbtmp; - struct lease *lease, *ltmp; + struct lease_table *lb; + struct lease *lease; write_lock(&lease_list_lock); - if (list_empty(&lease_table_list)) { - write_unlock(&lease_list_lock); - return; - } - - list_for_each_entry_safe(lb, lbtmp, &lease_table_list, l_entry) { - if (conn && memcmp(lb->client_guid, conn->ClientGUID, - SMB2_CLIENT_GUID_SIZE)) - continue; - list_for_each_entry_safe(lease, ltmp, &lb->lease_list, l_entry) - lease_del_table(lease); - list_del(&lb->l_entry); - free_lease_table(lb); + while (!list_empty(&lease_table_list)) { + lb = list_first_entry(&lease_table_list, struct lease_table, + l_entry); + lease = list_first_entry(&lb->lease_list, struct lease, l_entry); + lease_del_table(lease); } write_unlock(&lease_list_lock); } diff --git a/fs/smb/server/oplock.h b/fs/smb/server/oplock.h index e114e2148c30..5ef05166e502 100644 --- a/fs/smb/server/oplock.h +++ b/fs/smb/server/oplock.h @@ -34,7 +34,6 @@ struct lease_ctx_info { struct lease_table { char client_guid[SMB2_CLIENT_GUID_SIZE]; - struct ksmbd_conn *conn; struct list_head lease_list; struct list_head l_entry; spinlock_t lb_lock; @@ -122,7 +121,7 @@ struct oplock_info *lookup_lease_in_table(struct ksmbd_conn *conn, char *lease_key); int find_same_lease_key(struct ksmbd_conn *conn, struct ksmbd_inode *ci, struct lease_ctx_info *lctx); -void destroy_lease_table(struct ksmbd_conn *conn); +void destroy_lease_table(void); void smb_send_parent_lease_break_noti(struct ksmbd_file *fp, struct lease_ctx_info *lctx); void smb_lazy_parent_lease_break_close(struct ksmbd_file *fp); diff --git a/fs/smb/server/server.c b/fs/smb/server/server.c index 0593094f5fd0..064f99427ca6 100644 --- a/fs/smb/server/server.c +++ b/fs/smb/server/server.c @@ -157,7 +157,10 @@ static int __process_request(struct ksmbd_work *work, struct ksmbd_conn *conn, } } - ret = cmds->proc(work); + if (smb2_check_compound_fid(work)) + ret = -EBADF; + else + ret = cmds->proc(work); if (conn->ops->inc_reqs) { struct smb2_hdr *rsp = ksmbd_resp_buf_curr(work); @@ -436,7 +439,6 @@ static int ksmbd_server_process_request(struct ksmbd_conn *conn) static int ksmbd_server_terminate_conn(struct ksmbd_conn *conn) { ksmbd_conn_sessions_cleanup(conn); - destroy_lease_table(conn); return 0; } @@ -666,7 +668,7 @@ static int ksmbd_server_shutdown(void) ksmbd_proc_cleanup(); ksmbd_crypto_destroy(); ksmbd_free_global_file_table(); - destroy_lease_table(NULL); + destroy_lease_table(); ksmbd_work_pool_destroy(); ksmbd_exit_file_cache(); server_conf_free(); diff --git a/fs/smb/server/smb2pdu.c b/fs/smb/server/smb2pdu.c index 1c8037c85de9..828e2cf1dda5 100644 --- a/fs/smb/server/smb2pdu.c +++ b/fs/smb/server/smb2pdu.c @@ -458,6 +458,95 @@ int smb2_set_rsp_credits(struct ksmbd_work *work) return 0; } +static bool smb2_get_file_ids(struct smb2_hdr *hdr, u64 *volatile_id, + u64 *persistent_id) +{ + unsigned int offset; + + switch (hdr->Command) { + case SMB2_CLOSE: + offset = offsetof(struct smb2_close_req, PersistentFileId); + break; + case SMB2_FLUSH: + offset = offsetof(struct smb2_flush_req, PersistentFileId); + break; + case SMB2_READ: + offset = offsetof(struct smb2_read_req, PersistentFileId); + break; + case SMB2_WRITE: + offset = offsetof(struct smb2_write_req, PersistentFileId); + break; + case SMB2_LOCK: + offset = offsetof(struct smb2_lock_req, PersistentFileId); + break; + case SMB2_IOCTL: { + struct smb2_ioctl_req *req = (struct smb2_ioctl_req *)hdr; + + switch (le32_to_cpu(req->CtlCode)) { + case FSCTL_DFS_GET_REFERRALS: + case FSCTL_DFS_GET_REFERRALS_EX: + case FSCTL_QUERY_NETWORK_INTERFACE_INFO: + case FSCTL_VALIDATE_NEGOTIATE_INFO: + case FSCTL_PIPE_WAIT: + return false; + } + offset = offsetof(struct smb2_ioctl_req, PersistentFileId); + break; + } + case SMB2_QUERY_DIRECTORY: + offset = offsetof(struct smb2_query_directory_req, PersistentFileId); + break; + case SMB2_CHANGE_NOTIFY: + offset = offsetof(struct smb2_change_notify_req, PersistentFileId); + break; + case SMB2_QUERY_INFO: + offset = offsetof(struct smb2_query_info_req, PersistentFileId); + break; + case SMB2_SET_INFO: + offset = offsetof(struct smb2_set_info_req, PersistentFileId); + break; + case SMB2_OPLOCK_BREAK: + if (((struct smb2_oplock_break *)hdr)->StructureSize != + cpu_to_le16(OP_BREAK_STRUCT_SIZE_20)) + return false; + offset = offsetof(struct smb2_oplock_break, PersistentFid); + break; + default: + return false; + } + + /* FileId contains consecutive persistent and volatile opaque values. */ + memcpy(persistent_id, (char *)hdr + offset, sizeof(*persistent_id)); + memcpy(volatile_id, (char *)hdr + offset + sizeof(*persistent_id), + sizeof(*volatile_id)); + return true; +} + +/* Called after message validation and signature verification. */ +bool smb2_check_compound_fid(struct ksmbd_work *work) +{ + struct smb2_hdr *req = ksmbd_req_buf_next(work); + struct smb2_hdr *rsp = ksmbd_resp_buf_next(work); + u64 volatile_id, persistent_id; + + if (!work->next_smb2_rcv_hdr_off || + !(req->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) + return false; + + if (!work->compound_fid_missing && + !work->compound_fid_present && + smb2_get_file_ids(req, &volatile_id, &persistent_id)) + work->compound_fid_missing = true; + + if (!work->compound_fid_missing) + return false; + + /* MS-SMB2 3.3.5.2.7.2 requires all subsequent operations to fail too. */ + rsp->Status = STATUS_INVALID_HANDLE; + smb2_set_err_rsp(work); + return true; +} + /** * init_chained_smb2_rsp() - initialize smb2 chained response * @work: smb work containing smb response buffer @@ -470,6 +559,21 @@ static void init_chained_smb2_rsp(struct ksmbd_work *work) struct smb2_hdr *rcv_hdr; int next_hdr_offset = 0; int len, new_len; + u64 volatile_id = KSMBD_NO_FID, persistent_id = KSMBD_NO_FID; + bool req_has_fid; + + req_has_fid = smb2_get_file_ids(req, &volatile_id, &persistent_id); + /* A failed CREATE is handled through compound_status instead. */ + work->compound_fid_present = req_has_fid || req->Command == SMB2_CREATE; + if (!work->compound_fid_present) { + work->compound_fid = KSMBD_NO_FID; + work->compound_pfid = KSMBD_NO_FID; + } + + /* Related requests keep the inherited SessionId. */ + if (!work->next_smb2_rcv_hdr_off || + !(req->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) + work->compound_sid = le64_to_cpu(rsp->SessionId); /* Len of this response = updated RFC len - offset of previous cmd * in the compound rsp @@ -481,48 +585,24 @@ static void init_chained_smb2_rsp(struct ksmbd_work *work) if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) { work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId; work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId; - work->compound_sid = le64_to_cpu(rsp->SessionId); work->compound_status = STATUS_SUCCESS; - } else if ((req->Command == SMB2_FLUSH || - req->Command == SMB2_READ || - req->Command == SMB2_WRITE) && - rsp->Status == STATUS_SUCCESS) { - u64 volatile_id = KSMBD_NO_FID; - u64 persistent_id = KSMBD_NO_FID; - - if (req->Command == SMB2_FLUSH) { - struct smb2_flush_req *flush_req = - (struct smb2_flush_req *)req; - - volatile_id = flush_req->VolatileFileId; - persistent_id = flush_req->PersistentFileId; - } else if (req->Command == SMB2_READ) { - struct smb2_read_req *read_req = - (struct smb2_read_req *)req; - - volatile_id = read_req->VolatileFileId; - persistent_id = read_req->PersistentFileId; + } else if (rsp->Status == STATUS_SUCCESS) { + if (req_has_fid && req->Command != SMB2_CLOSE) { + /* Preserve the inherited FID when the request uses all ones. */ + if (has_file_id(volatile_id)) { + work->compound_fid = volatile_id; + work->compound_pfid = persistent_id; + } } else { - struct smb2_write_req *write_req = - (struct smb2_write_req *)req; - - volatile_id = write_req->VolatileFileId; - persistent_id = write_req->PersistentFileId; - } - - if (has_file_id(volatile_id)) { - work->compound_fid = volatile_id; - work->compound_pfid = persistent_id; - work->compound_sid = le64_to_cpu(rsp->SessionId); - work->compound_status = STATUS_SUCCESS; + work->compound_fid = KSMBD_NO_FID; + work->compound_pfid = KSMBD_NO_FID; } + work->compound_status = STATUS_SUCCESS; } else if (req->Command == SMB2_CREATE) { work->compound_fid = KSMBD_NO_FID; work->compound_pfid = KSMBD_NO_FID; - work->compound_sid = le64_to_cpu(rsp->SessionId); work->compound_status = rsp->Status; } else if (rsp->Status != STATUS_SUCCESS) { - work->compound_sid = le64_to_cpu(rsp->SessionId); /* * Only carry the failed status forward when the failing command * was itself part of the related chain. An unrelated command @@ -561,6 +641,8 @@ static void init_chained_smb2_rsp(struct ksmbd_work *work) work->compound_fid = KSMBD_NO_FID; work->compound_pfid = KSMBD_NO_FID; work->compound_status = STATUS_SUCCESS; + work->compound_fid_present = false; + work->compound_fid_missing = false; } memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2); rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER; @@ -612,6 +694,9 @@ bool is_chained_smb2_message(struct ksmbd_work *work) hdr = ksmbd_req_buf_next(work); next_cmd = le32_to_cpu(hdr->NextCommand); if (next_cmd > 0) { + size_t next_rsp_sz = MAX_CIFS_SMALL_BUFFER_SIZE; + struct smb2_hdr *next_hdr; + if ((u64)work->next_smb2_rcv_hdr_off + next_cmd + __SMB2_HEADER_STRUCTURE_SIZE > get_rfc1002_len(work->request_buf)) { @@ -620,8 +705,19 @@ bool is_chained_smb2_message(struct ksmbd_work *work) return false; } - if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE > - work->response_sz) { + /* + * The next response starts at the 8-byte aligned end of this one. + * smb2_open() appends create contexts without checking the space + * left, so reserve the largest CREATE response for a chained + * CREATE, as smb2_allocate_rsp_buf() does for a single one. + */ + next_hdr = (struct smb2_hdr *)((char *)hdr + next_cmd); + if (le16_to_cpu(next_hdr->Command) == SMB2_CREATE_HE) + next_rsp_sz = max_t(size_t, next_rsp_sz, + work->conn->vals->create_rsp_size); + + if ((u64)ALIGN(get_rfc1002_len(work->response_buf), 8) + + next_rsp_sz > work->response_sz) { pr_err("next response offset exceeds response buffer size\n"); return false; } @@ -896,7 +992,8 @@ int smb2_allocate_rsp_buf(struct ksmbd_work *work) if ((req->InfoType == SMB2_O_INFO_FILE && (req->FileInfoClass == FILE_FULL_EA_INFORMATION || req->FileInfoClass == FILE_ALL_INFORMATION || - req->FileInfoClass == FILE_NORMALIZED_NAME_INFORMATION)) || + req->FileInfoClass == FILE_NORMALIZED_NAME_INFORMATION || + req->FileInfoClass == FILE_STREAM_INFORMATION)) || req->InfoType == SMB2_O_INFO_SECURITY) sz = large_sz; } @@ -3156,7 +3253,7 @@ int smb2_session_logoff(struct ksmbd_work *work) smb2_set_err_rsp(work); return -ENOENT; } - sess->tearing_down = true; + WRITE_ONCE(sess->tearing_down, true); up_write(&sess->chann_lock); ksmbd_all_conn_set_status(sess, KSMBD_SESS_NEED_RECONNECT); @@ -3165,7 +3262,7 @@ int smb2_session_logoff(struct ksmbd_work *work) err = ksmbd_conn_wait_idle_sess(conn, sess); if (err) { down_write(&sess->chann_lock); - sess->tearing_down = false; + WRITE_ONCE(sess->tearing_down, false); up_write(&sess->chann_lock); ksmbd_all_conn_set_status(sess, KSMBD_SESS_GOOD); rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR; @@ -3174,6 +3271,7 @@ int smb2_session_logoff(struct ksmbd_work *work) } ksmbd_close_session_fds(work); + ksmbd_session_rpc_clear_list(sess); if (ksmbd_tree_conn_session_logoff(sess)) { ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId); @@ -3468,8 +3566,9 @@ static noinline int smb2_set_stream_name_xattr(const struct path *path, * AAPL there too. */ static const u8 afpinfo_empty[60] = { - 0x00, 0x05, 0x16, 0x07, /* magic 0x00051607 BE */ - 0x00, 0x02, 0x00, 0x00, /* version 0x00020000 BE */ + 'A', 'F', 'P', 0x00, /* signature */ + 0x00, 0x00, 0x01, 0x00, /* version */ + [15] = 0x80, /* backup time */ }; rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, (void *)afpinfo_empty, @@ -7041,41 +7140,107 @@ static int get_file_normalized_name_info(struct ksmbd_work *work, return 0; } +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) { @@ -7085,69 +7250,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, @@ -7444,7 +7589,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: @@ -8325,6 +8470,11 @@ static int set_file_basic_info(struct ksmbd_file *fp, inode = file_inode(filp); idmap = file_mnt_idmap(filp); + /* MS-FSA FileBasicInformation: a directory can't be marked TEMPORARY */ + if (S_ISDIR(inode->i_mode) && + (file_info->Attributes & FILE_ATTRIBUTE_TEMPORARY_LE)) + return -EINVAL; + if (file_info->CreationTime) fp->create_time = le64_to_cpu(file_info->CreationTime); @@ -8400,10 +8550,11 @@ static int set_file_allocation_info(struct ksmbd_work *work, * properly with any smb.conf option */ - loff_t alloc_blks; - u64 alloc_size; + u64 alloc_size, target, alloc_blks; + u32 alloc_unit; struct inode *inode; struct kstat stat; + struct kstatfs stfs; int rc; if (!(fp->daccess & FILE_WRITE_DATA_LE)) @@ -8416,44 +8567,48 @@ static int set_file_allocation_info(struct ksmbd_work *work, AT_STATX_SYNC_AS_STAT); if (rc) return rc; + rc = vfs_statfs(&fp->filp->f_path, &stfs); + if (rc) + return rc; /* - * AllocationSize is fully client-controlled (the caller only - * validates the fixed 8-byte buffer length). Reject values that - * would overflow the "round up to 512-byte blocks" conversion - * below instead of silently wrapping it to a tiny block count, - * which would truncate the file to a size the client never - * asked for. + * Use the allocation unit advertised in FS_SIZE_INFORMATION. + * Reject requests that overflow when rounded to a whole unit. */ alloc_size = le64_to_cpu(file_alloc_info->AllocationSize); - if (alloc_size > MAX_LFS_FILESIZE - 511) + if (stfs.f_bsize <= 0 || (u64)stfs.f_bsize > U32_MAX) + return -EINVAL; + alloc_unit = stfs.f_bsize; + if (alloc_size > MAX_LFS_FILESIZE - (alloc_unit - 1)) return -EINVAL; - alloc_blks = (alloc_size + 511) >> 9; + target = DIV_ROUND_UP_ULL(alloc_size, alloc_unit) * alloc_unit; + alloc_blks = DIV_ROUND_UP_ULL(target, 512); inode = file_inode(fp->filp); + if (target > inode->i_sb->s_maxbytes) + return -EINVAL; if (alloc_blks > stat.blocks) { smb_break_all_levII_oplock(work, fp, 1); - rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0, - alloc_blks * 512); + rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0, target); if (rc && rc != -EOPNOTSUPP) { pr_err("vfs_fallocate is failed : %d\n", rc); return rc; } } else if (alloc_blks < stat.blocks && - alloc_blks * 512 <= i_size_read(inode)) { + target <= i_size_read(inode)) { /* * Truncate at or below EOF to discard excess allocation. * Truncating above EOF would extend the file on disk. */ - rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512); + rc = ksmbd_vfs_truncate(work, fp, target); if (rc) { pr_err("truncate failed!, err %d\n", rc); return rc; } } - fp->allocation_size = le64_to_cpu(file_alloc_info->AllocationSize); + fp->allocation_size = target; fp->allocation_size_set = true; return 0; } @@ -8843,6 +8998,32 @@ int smb2_set_info(struct ksmbd_work *work) return rc; } +static __le32 smb2_pipe_error_status(int err, __le32 fallback) +{ + switch (err) { + case -ECANCELED: + return STATUS_CANCELLED; + case -ESHUTDOWN: + return STATUS_CONNECTION_DISCONNECTED; + case -EBADF: + case -ENOENT: + return STATUS_FILE_CLOSED; + default: + return fallback; + } +} + +static void smb2_pipe_response_done(struct ksmbd_session_rpc *rpc, + unsigned int nbytes) +{ + rpc->pending_offset += nbytes; + if (rpc->pending_offset == rpc->pending->payload_sz) { + kvfree(rpc->pending); + rpc->pending = NULL; + rpc->pending_offset = 0; + } +} + /** * smb2_read_pipe() - handler for smb2 read from IPC pipe * @work: smb work containing read IPC pipe command buffer @@ -8851,67 +9032,102 @@ int smb2_set_info(struct ksmbd_work *work) */ static noinline int smb2_read_pipe(struct ksmbd_work *work) { - int nbytes = 0, err; + unsigned int nbytes = 0, length; u64 id; struct ksmbd_rpc_command *rpc_resp; + struct ksmbd_session_rpc *rpc; struct smb2_read_req *req; struct smb2_read_rsp *rsp; + void *aux_payload_buf; + int err; WORK_BUFFERS(work, req, rsp); id = req->VolatileFileId; - rpc_resp = ksmbd_rpc_read(work->sess, id); - if (rpc_resp) { - void *aux_payload_buf; + lockdep_assert_not_held(&work->sess->rpc_lock); + down_read(&work->sess->rpc_lock); + if (!ksmbd_session_rpc_method(work->sess, id)) { + up_read(&work->sess->rpc_lock); + rsp->hdr.Status = STATUS_FILE_CLOSED; + smb2_set_err_rsp(work); + return -ENOENT; + } + up_read(&work->sess->rpc_lock); + rpc = ksmbd_session_rpc_get(work, id); + if (IS_ERR(rpc)) { + err = PTR_ERR(rpc); + goto out; + } + + length = le32_to_cpu(req->Length); + if (!length) + goto empty; + + if (!rpc->pending) { + rpc_resp = ksmbd_rpc_read(work->sess, rpc); + if (!rpc_resp) { + err = -EIO; + goto out_put; + } if (rpc_resp->flags != KSMBD_RPC_OK) { + kvfree(rpc_resp); err = -EINVAL; - goto out; + goto out_put; } + rpc->pending = rpc_resp; + } - aux_payload_buf = - kvmalloc(ALIGN(rpc_resp->payload_sz, 8), - KSMBD_DEFAULT_GFP); - if (!aux_payload_buf) { - err = -ENOMEM; - goto out; - } + rpc_resp = rpc->pending; + nbytes = min(length, rpc_resp->payload_sz - rpc->pending_offset); + if (!nbytes) { + smb2_pipe_response_done(rpc, 0); + goto empty; + } - memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz); - if (rpc_resp->payload_sz & 7) - memset(aux_payload_buf + rpc_resp->payload_sz, 0, - ALIGN(rpc_resp->payload_sz, 8) - - rpc_resp->payload_sz); + aux_payload_buf = kvmalloc(ALIGN(nbytes, 8), KSMBD_DEFAULT_GFP); + if (!aux_payload_buf) { + err = -ENOMEM; + goto out_put; + } + memcpy(aux_payload_buf, rpc_resp->payload + rpc->pending_offset, nbytes); + if (nbytes & 7) + memset(aux_payload_buf + nbytes, 0, ALIGN(nbytes, 8) - nbytes); - nbytes = rpc_resp->payload_sz; - err = ksmbd_iov_pin_rsp_read(work, (void *)rsp, - offsetof(struct smb2_read_rsp, Buffer), - aux_payload_buf, nbytes); - if (err) { - kvfree(aux_payload_buf); - goto out; - } - kvfree(rpc_resp); - } else { - err = ksmbd_iov_pin_rsp(work, (void *)rsp, - offsetof(struct smb2_read_rsp, Buffer)); - if (err) - goto out; + err = ksmbd_iov_pin_rsp_read(work, rsp, + offsetof(struct smb2_read_rsp, Buffer), + aux_payload_buf, nbytes); + if (err) { + kvfree(aux_payload_buf); + goto out_put; } + smb2_pipe_response_done(rpc, nbytes); + if (rpc->pending) + rsp->hdr.Status = STATUS_BUFFER_OVERFLOW; + goto done; +empty: + err = ksmbd_iov_pin_rsp(work, rsp, + offsetof(struct smb2_read_rsp, Buffer)); + if (err) + goto out_put; +done: rsp->StructureSize = cpu_to_le16(17); rsp->DataOffset = 80; rsp->Reserved = 0; rsp->DataLength = cpu_to_le32(nbytes); rsp->DataRemaining = 0; rsp->Flags = 0; + ksmbd_session_rpc_put(rpc); return 0; +out_put: + ksmbd_session_rpc_put(rpc); out: - rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR; + rsp->hdr.Status = smb2_pipe_error_status(err, + STATUS_UNEXPECTED_IO_ERROR); smb2_set_err_rsp(work); - kvfree(rpc_resp); return err; } @@ -9470,6 +9686,7 @@ static noinline int smb2_write_pipe(struct ksmbd_work *work) struct smb2_write_req *req; struct smb2_write_rsp *rsp; struct ksmbd_rpc_command *rpc_resp; + struct ksmbd_session_rpc *rpc; u64 id = 0; int err = 0, ret = 0; char *data_buf; @@ -9491,25 +9708,47 @@ static noinline int smb2_write_pipe(struct ksmbd_work *work) goto out; } + lockdep_assert_not_held(&work->sess->rpc_lock); + down_read(&work->sess->rpc_lock); + if (!ksmbd_session_rpc_method(work->sess, id)) { + up_read(&work->sess->rpc_lock); + rsp->hdr.Status = STATUS_FILE_CLOSED; + smb2_set_err_rsp(work); + return -ENOENT; + } + up_read(&work->sess->rpc_lock); + data_buf = (char *)(((char *)&req->hdr.ProtocolId) + data_offset); - rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length); - if (rpc_resp) { - if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) { - rsp->hdr.Status = STATUS_NOT_SUPPORTED; - kvfree(rpc_resp); - smb2_set_err_rsp(work); - return -EOPNOTSUPP; - } - if (rpc_resp->flags != KSMBD_RPC_OK) { - rsp->hdr.Status = STATUS_INVALID_HANDLE; - smb2_set_err_rsp(work); - kvfree(rpc_resp); - return ret; - } + rpc = ksmbd_session_rpc_get(work, id); + if (IS_ERR(rpc)) { + err = PTR_ERR(rpc); + rsp->hdr.Status = smb2_pipe_error_status(err, + STATUS_INVALID_HANDLE); + smb2_set_err_rsp(work); + return err; + } + rpc_resp = ksmbd_rpc_write(work->sess, rpc, data_buf, length); + ksmbd_session_rpc_put(rpc); + if (!rpc_resp) { + rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR; + smb2_set_err_rsp(work); + return -EIO; + } + if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) { + rsp->hdr.Status = STATUS_NOT_SUPPORTED; + kvfree(rpc_resp); + smb2_set_err_rsp(work); + return -EOPNOTSUPP; + } + if (rpc_resp->flags != KSMBD_RPC_OK) { + rsp->hdr.Status = STATUS_INVALID_HANDLE; + smb2_set_err_rsp(work); kvfree(rpc_resp); + return ret; } + kvfree(rpc_resp); rsp->StructureSize = cpu_to_le16(17); rsp->DataOffset = 0; @@ -10673,6 +10912,27 @@ static __be32 idev_ipv4_address(struct in_device *idev) return addr; } +static struct network_interface_info_ioctl_rsp * +ksmbd_iface_entry_init(struct smb2_ioctl_rsp *rsp, int nbytes, + struct net_device *netdev, unsigned long long speed) +{ + struct network_interface_info_ioctl_rsp *nii_rsp; + + nii_rsp = (struct network_interface_info_ioctl_rsp *)&rsp->Buffer[nbytes]; + nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex); + nii_rsp->Capability = 0; + if (netdev->real_num_tx_queues > 1) + nii_rsp->Capability |= RSS_CAPABLE; + if (ksmbd_rdma_capable_netdev(netdev)) + nii_rsp->Capability |= RDMA_CAPABLE; + nii_rsp->Next = cpu_to_le32(152); + nii_rsp->Reserved = 0; + nii_rsp->LinkSpeed = cpu_to_le64(speed); + memset(nii_rsp->SockAddr_Storage, 0, 128); + + return nii_rsp; +} + static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn, struct smb2_ioctl_rsp *rsp, unsigned int out_buf_len) @@ -10683,10 +10943,16 @@ static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn, struct sockaddr_storage_rsp *sockaddr_storage; unsigned int flags; unsigned long long speed; + struct ethtool_link_ksettings cmd; rtnl_lock(); for_each_netdev(&init_net, netdev) { - bool ipv4_set = false; + struct inet6_ifaddr *ifa; + struct inet6_dev *idev6; + struct in_device *idev; + struct in6_addr ip6 = { }; + bool have_ip6 = false; + __be32 ip4 = 0; if (netdev->type == ARPHRD_LOOPBACK) continue; @@ -10697,87 +10963,80 @@ static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn, flags = netif_get_flags(netdev); if (!(flags & IFF_RUNNING)) continue; -ipv6_retry: - if (out_buf_len < - nbytes + sizeof(struct network_interface_info_ioctl_rsp)) { - rtnl_unlock(); - return -ENOSPC; - } - - nii_rsp = (struct network_interface_info_ioctl_rsp *) - &rsp->Buffer[nbytes]; - nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex); - - nii_rsp->Capability = 0; - if (netdev->real_num_tx_queues > 1) - nii_rsp->Capability |= RSS_CAPABLE; - if (ksmbd_rdma_capable_netdev(netdev)) - nii_rsp->Capability |= RDMA_CAPABLE; - nii_rsp->Next = cpu_to_le32(152); - nii_rsp->Reserved = 0; - - if (netdev->ethtool_ops->get_link_ksettings) { - struct ethtool_link_ksettings cmd; - - netdev->ethtool_ops->get_link_ksettings(netdev, &cmd); + if (!__ethtool_get_link_ksettings(netdev, &cmd) && + cmd.base.speed && cmd.base.speed != SPEED_UNKNOWN) { speed = cmd.base.speed; } else { ksmbd_debug(SMB, "%s %s\n", netdev->name, "speed is unknown, defaulting to 1Gb/sec"); speed = SPEED_1000; } - speed *= 1000000; - nii_rsp->LinkSpeed = cpu_to_le64(speed); - sockaddr_storage = (struct sockaddr_storage_rsp *) - nii_rsp->SockAddr_Storage; - memset(sockaddr_storage, 0, 128); + /* + * Query IPv4 and IPv6 independently; emit an entry only when a + * usable address exists, so an interface missing one family is + * still reported for the other and 0.0.0.0 / :: placeholders are + * never advertised. + */ + idev = __in_dev_get_rtnl(netdev); + if (idev) + ip4 = idev_ipv4_address(idev); + + idev6 = __in6_dev_get(netdev); + if (idev6) { + rcu_read_lock(); + list_for_each_entry_rcu(ifa, &idev6->addr_list, if_list) { + if (ifa->flags & (IFA_F_TENTATIVE | IFA_F_DEPRECATED)) + continue; + memcpy(&ip6, ifa->addr.s6_addr, sizeof(ip6)); + have_ip6 = true; + break; + } + rcu_read_unlock(); + } - if (!ipv4_set) { - struct in_device *idev; + if (ip4) { + if (out_buf_len < + nbytes + sizeof(struct network_interface_info_ioctl_rsp)) { + rtnl_unlock(); + return -ENOSPC; + } + nii_rsp = ksmbd_iface_entry_init(rsp, nbytes, netdev, speed); + sockaddr_storage = (struct sockaddr_storage_rsp *)nii_rsp->SockAddr_Storage; sockaddr_storage->Family = INTERNETWORK; sockaddr_storage->addr4.Port = 0; - - idev = __in_dev_get_rtnl(netdev); - if (!idev) - continue; - sockaddr_storage->addr4.IPv4Address = - idev_ipv4_address(idev); + sockaddr_storage->addr4.IPv4Address = ip4; nbytes += sizeof(struct network_interface_info_ioctl_rsp); - ipv4_set = true; - goto ipv6_retry; - } else { - struct inet6_dev *idev6; - struct inet6_ifaddr *ifa; - __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6Address; + } + if (have_ip6) { + if (out_buf_len < + nbytes + sizeof(struct network_interface_info_ioctl_rsp)) { + rtnl_unlock(); + return -ENOSPC; + } + + nii_rsp = ksmbd_iface_entry_init(rsp, nbytes, netdev, speed); + sockaddr_storage = (struct sockaddr_storage_rsp *)nii_rsp->SockAddr_Storage; sockaddr_storage->Family = INTERNETWORKV6; sockaddr_storage->addr6.Port = 0; sockaddr_storage->addr6.FlowInfo = 0; - - idev6 = __in6_dev_get(netdev); - if (!idev6) - continue; - - list_for_each_entry(ifa, &idev6->addr_list, if_list) { - if (ifa->flags & (IFA_F_TENTATIVE | - IFA_F_DEPRECATED)) - continue; - memcpy(ipv6_addr, ifa->addr.s6_addr, 16); - break; - } + memcpy(sockaddr_storage->addr6.IPv6Address, ip6.s6_addr, 16); sockaddr_storage->addr6.ScopeId = 0; nbytes += sizeof(struct network_interface_info_ioctl_rsp); } } rtnl_unlock(); - /* zero if this is last one */ - if (nii_rsp) + /* Clear Next of the last committed entry to terminate the list. */ + if (nbytes > 0) { + nii_rsp = (struct network_interface_info_ioctl_rsp *) + &rsp->Buffer[nbytes - sizeof(*nii_rsp)]; nii_rsp->Next = 0; + } rsp->PersistentFileId = SMB2_NO_FID; rsp->VolatileFileId = SMB2_NO_FID; @@ -10873,49 +11132,91 @@ static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id, return ret; } +static int smb2_ioctl_rsp(struct ksmbd_work *work, struct smb2_ioctl_rsp *rsp, + unsigned int cnt_code, unsigned int nbytes) +{ + rsp->CtlCode = cpu_to_le32(cnt_code); + rsp->InputCount = cpu_to_le32(0); + rsp->InputOffset = cpu_to_le32(112); + rsp->OutputOffset = cpu_to_le32(112); + rsp->OutputCount = cpu_to_le32(nbytes); + rsp->StructureSize = cpu_to_le16(49); + rsp->Reserved = cpu_to_le16(0); + rsp->Flags = cpu_to_le32(0); + rsp->Reserved2 = cpu_to_le32(0); + return ksmbd_iov_pin_rsp(work, rsp, + sizeof(struct smb2_ioctl_rsp) + nbytes); +} + static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id, unsigned int out_buf_len, struct smb2_ioctl_req *req, struct smb2_ioctl_rsp *rsp) { struct ksmbd_rpc_command *rpc_resp; + struct ksmbd_session_rpc *rpc; char *data_buf = (char *)req + le32_to_cpu(req->InputOffset); - int nbytes = 0; + unsigned int nbytes = 0; + int ret; - rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf, - le32_to_cpu(req->InputCount)); - if (rpc_resp) { - if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) { - /* - * set STATUS_SOME_NOT_MAPPED response - * for unknown domain sid. - */ - rsp->hdr.Status = STATUS_SOME_NOT_MAPPED; - } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) { - rsp->hdr.Status = STATUS_NOT_SUPPORTED; - goto out; - } else if (rpc_resp->flags != KSMBD_RPC_OK) { - rsp->hdr.Status = STATUS_INVALID_PARAMETER; - goto out; - } + rpc = ksmbd_session_rpc_get(work, id); + if (IS_ERR(rpc)) { + ret = PTR_ERR(rpc); + rsp->hdr.Status = smb2_pipe_error_status(ret, + STATUS_INVALID_PARAMETER); + smb2_set_err_rsp(work); + return 0; + } - nbytes = rpc_resp->payload_sz; - if (rpc_resp->payload_sz > out_buf_len) { - rsp->hdr.Status = STATUS_BUFFER_OVERFLOW; - nbytes = out_buf_len; - } + if (rpc->pending) { + ksmbd_session_rpc_put(rpc); + rsp->hdr.Status = STATUS_PIPE_BUSY; + smb2_set_err_rsp(work); + return 0; + } - if (!rpc_resp->payload_sz) { - rsp->hdr.Status = - STATUS_UNEXPECTED_IO_ERROR; - goto out; - } + rpc_resp = ksmbd_rpc_ioctl(work->sess, rpc, data_buf, + le32_to_cpu(req->InputCount)); + if (!rpc_resp) { + ksmbd_session_rpc_put(rpc); + rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR; + smb2_set_err_rsp(work); + return 0; + } - memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes); + if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) { + rsp->hdr.Status = STATUS_SOME_NOT_MAPPED; + } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) { + rsp->hdr.Status = STATUS_NOT_SUPPORTED; + goto free_resp; + } else if (rpc_resp->flags != KSMBD_RPC_OK) { + rsp->hdr.Status = STATUS_INVALID_PARAMETER; + goto free_resp; } -out: + + if (!rpc_resp->payload_sz) { + rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR; + goto free_resp; + } + rpc->pending = rpc_resp; + nbytes = rpc_resp->payload_sz - rpc->pending_offset; + if (nbytes > out_buf_len) { + rsp->hdr.Status = STATUS_BUFFER_OVERFLOW; + nbytes = out_buf_len; + } + memcpy(rsp->Buffer, rpc_resp->payload + rpc->pending_offset, nbytes); + ret = smb2_ioctl_rsp(work, rsp, FSCTL_PIPE_TRANSCEIVE, nbytes); + if (!ret) + smb2_pipe_response_done(rpc, nbytes); + ksmbd_session_rpc_put(rpc); + return ret; + +free_resp: kvfree(rpc_resp); - return nbytes; + rsp->hdr.Status = smb2_pipe_error_status(-EINVAL, rsp->hdr.Status); + ksmbd_session_rpc_put(rpc); + smb2_set_err_rsp(work); + return 0; } static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id, @@ -11226,8 +11527,10 @@ int smb2_ioctl(struct ksmbd_work *work) } case FSCTL_PIPE_TRANSCEIVE: out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len); - nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp); - break; + ret = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp); + if (ret) + goto out; + return 0; case FSCTL_VALIDATE_NEGOTIATE_INFO: if (conn->dialect < SMB30_PROT_ID) { ret = -EOPNOTSUPP; @@ -11606,16 +11909,7 @@ int smb2_ioctl(struct ksmbd_work *work) goto out; } - rsp->CtlCode = cpu_to_le32(cnt_code); - rsp->InputCount = cpu_to_le32(0); - rsp->InputOffset = cpu_to_le32(112); - rsp->OutputOffset = cpu_to_le32(112); - rsp->OutputCount = cpu_to_le32(nbytes); - rsp->StructureSize = cpu_to_le16(49); - rsp->Reserved = cpu_to_le16(0); - rsp->Flags = cpu_to_le32(0); - rsp->Reserved2 = cpu_to_le32(0); - ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes); + ret = smb2_ioctl_rsp(work, rsp, cnt_code, nbytes); if (!ret) return ret; @@ -12623,6 +12917,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; + } + buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr); original_msg_size = le32_to_cpu(tr_hdr->OriginalMessageSize); if (buf_data_size < sizeof(struct smb2_compression_hdr) || diff --git a/fs/smb/server/smb2pdu.h b/fs/smb/server/smb2pdu.h index 20a5337459ab..38270130d144 100644 --- a/fs/smb/server/smb2pdu.h +++ b/fs/smb/server/smb2pdu.h @@ -397,6 +397,7 @@ bool is_smb2_rsp(struct ksmbd_work *work); u16 get_smb2_cmd_val(struct ksmbd_work *work); void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err); int init_smb2_rsp_hdr(struct ksmbd_work *work); +bool smb2_check_compound_fid(struct ksmbd_work *work); int smb2_allocate_rsp_buf(struct ksmbd_work *work); bool is_chained_smb2_message(struct ksmbd_work *work); int init_smb2_neg_rsp(struct ksmbd_work *work); diff --git a/fs/smb/server/smb_common.c b/fs/smb/server/smb_common.c index 21ba0ce5abbf..5ddefb5a7078 100644 --- a/fs/smb/server/smb_common.c +++ b/fs/smb/server/smb_common.c @@ -525,8 +525,6 @@ int ksmbd_populate_dot_dotdot_entries(struct ksmbd_work *work, int info_level, * @shortname: destination short filename * * Return: shortname length or 0 when source long name is '.' or '..' - * TODO: Though this function conforms the restriction of 8.3 Filename spec, - * but the result is different with Windows 7's one. need to check. */ int ksmbd_extract_shortname(struct ksmbd_conn *conn, const char *longname, char *shortname) @@ -590,7 +588,7 @@ int ksmbd_extract_shortname(struct ksmbd_conn *conn, const char *longname, if (dot_present) memcpy(out + baselen + 4, extension, 4); else - out[baselen + 4] = '\0'; + out[baselen + 3] = '\0'; smbConvertToUTF16((__le16 *)shortname, out, PATH_MAX, conn->local_nls, 0); len = strlen(out) * 2; diff --git a/fs/smb/server/transport_ipc.c b/fs/smb/server/transport_ipc.c index eb07cdf17410..e8dfc42a1d08 100644 --- a/fs/smb/server/transport_ipc.c +++ b/fs/smb/server/transport_ipc.c @@ -834,7 +834,7 @@ ksmbd_ipc_share_config_request(const char *name) return resp; } -struct ksmbd_rpc_command *ksmbd_rpc_open(struct ksmbd_session *sess, int handle) +struct ksmbd_rpc_command *ksmbd_rpc_open(struct ksmbd_session_rpc *entry) { struct ksmbd_ipc_msg *msg; struct ksmbd_rpc_command *req; @@ -846,8 +846,8 @@ struct ksmbd_rpc_command *ksmbd_rpc_open(struct ksmbd_session *sess, int handle) msg->type = KSMBD_EVENT_RPC_REQUEST; req = (struct ksmbd_rpc_command *)msg->payload; - req->handle = handle; - req->flags = ksmbd_session_rpc_method(sess, handle); + req->handle = entry->id; + req->flags = entry->method; req->flags |= KSMBD_RPC_OPEN_METHOD; req->payload_sz = 0; @@ -856,7 +856,7 @@ struct ksmbd_rpc_command *ksmbd_rpc_open(struct ksmbd_session *sess, int handle) return resp; } -struct ksmbd_rpc_command *ksmbd_rpc_close(struct ksmbd_session *sess, int handle) +struct ksmbd_rpc_command *ksmbd_rpc_close(struct ksmbd_session_rpc *entry) { struct ksmbd_ipc_msg *msg; struct ksmbd_rpc_command *req; @@ -868,8 +868,8 @@ struct ksmbd_rpc_command *ksmbd_rpc_close(struct ksmbd_session *sess, int handle msg->type = KSMBD_EVENT_RPC_REQUEST; req = (struct ksmbd_rpc_command *)msg->payload; - req->handle = handle; - req->flags = ksmbd_session_rpc_method(sess, handle); + req->handle = entry->id; + req->flags = entry->method; req->flags |= KSMBD_RPC_CLOSE_METHOD; req->payload_sz = 0; @@ -878,7 +878,8 @@ struct ksmbd_rpc_command *ksmbd_rpc_close(struct ksmbd_session *sess, int handle return resp; } -struct ksmbd_rpc_command *ksmbd_rpc_write(struct ksmbd_session *sess, int handle, +struct ksmbd_rpc_command *ksmbd_rpc_write(struct ksmbd_session *sess, + struct ksmbd_session_rpc *entry, void *payload, size_t payload_sz) { struct ksmbd_ipc_msg *msg; @@ -892,25 +893,24 @@ struct ksmbd_rpc_command *ksmbd_rpc_write(struct ksmbd_session *sess, int handle if (!msg) return NULL; - lockdep_assert_not_held(&sess->rpc_lock); + lockdep_assert_held(&entry->lock); - down_read(&sess->rpc_lock); msg->type = KSMBD_EVENT_RPC_REQUEST; req = (struct ksmbd_rpc_command *)msg->payload; - req->handle = handle; - req->flags = ksmbd_session_rpc_method(sess, handle); + req->handle = entry->id; + req->flags = entry->method; req->flags |= rpc_context_flags(sess); req->flags |= KSMBD_RPC_WRITE_METHOD; req->payload_sz = payload_sz; memcpy(req->payload, payload, payload_sz); - up_read(&sess->rpc_lock); resp = ipc_msg_send_request(msg, req->handle); ipc_msg_free(msg); return resp; } -struct ksmbd_rpc_command *ksmbd_rpc_read(struct ksmbd_session *sess, int handle) +struct ksmbd_rpc_command *ksmbd_rpc_read(struct ksmbd_session *sess, + struct ksmbd_session_rpc *entry) { struct ksmbd_ipc_msg *msg; struct ksmbd_rpc_command *req; @@ -920,24 +920,23 @@ struct ksmbd_rpc_command *ksmbd_rpc_read(struct ksmbd_session *sess, int handle) if (!msg) return NULL; - lockdep_assert_not_held(&sess->rpc_lock); + lockdep_assert_held(&entry->lock); - down_read(&sess->rpc_lock); msg->type = KSMBD_EVENT_RPC_REQUEST; req = (struct ksmbd_rpc_command *)msg->payload; - req->handle = handle; - req->flags = ksmbd_session_rpc_method(sess, handle); + req->handle = entry->id; + req->flags = entry->method; req->flags |= rpc_context_flags(sess); req->flags |= KSMBD_RPC_READ_METHOD; req->payload_sz = 0; - up_read(&sess->rpc_lock); resp = ipc_msg_send_request(msg, req->handle); ipc_msg_free(msg); return resp; } -struct ksmbd_rpc_command *ksmbd_rpc_ioctl(struct ksmbd_session *sess, int handle, +struct ksmbd_rpc_command *ksmbd_rpc_ioctl(struct ksmbd_session *sess, + struct ksmbd_session_rpc *entry, void *payload, size_t payload_sz) { struct ksmbd_ipc_msg *msg; @@ -951,18 +950,16 @@ struct ksmbd_rpc_command *ksmbd_rpc_ioctl(struct ksmbd_session *sess, int handle if (!msg) return NULL; - lockdep_assert_not_held(&sess->rpc_lock); + lockdep_assert_held(&entry->lock); - down_read(&sess->rpc_lock); msg->type = KSMBD_EVENT_RPC_REQUEST; req = (struct ksmbd_rpc_command *)msg->payload; - req->handle = handle; - req->flags = ksmbd_session_rpc_method(sess, handle); + req->handle = entry->id; + req->flags = entry->method; req->flags |= rpc_context_flags(sess); req->flags |= KSMBD_RPC_IOCTL_METHOD; req->payload_sz = payload_sz; memcpy(req->payload, payload, payload_sz); - up_read(&sess->rpc_lock); resp = ipc_msg_send_request(msg, req->handle); ipc_msg_free(msg); diff --git a/fs/smb/server/transport_ipc.h b/fs/smb/server/transport_ipc.h index e51850f1423b..df94ba116d43 100644 --- a/fs/smb/server/transport_ipc.h +++ b/fs/smb/server/transport_ipc.h @@ -16,6 +16,7 @@ struct ksmbd_login_response_ext * ksmbd_ipc_login_request_ext(const char *account); struct ksmbd_session; +struct ksmbd_session_rpc; struct ksmbd_share_config; struct ksmbd_tree_connect; struct sockaddr; @@ -34,12 +35,15 @@ struct ksmbd_spnego_authen_response * ksmbd_ipc_spnego_authen_request(const char *spnego_blob, int blob_len); int ksmbd_ipc_id_alloc(void); void ksmbd_rpc_id_free(int handle); -struct ksmbd_rpc_command *ksmbd_rpc_open(struct ksmbd_session *sess, int handle); -struct ksmbd_rpc_command *ksmbd_rpc_close(struct ksmbd_session *sess, int handle); -struct ksmbd_rpc_command *ksmbd_rpc_write(struct ksmbd_session *sess, int handle, +struct ksmbd_rpc_command *ksmbd_rpc_open(struct ksmbd_session_rpc *entry); +struct ksmbd_rpc_command *ksmbd_rpc_close(struct ksmbd_session_rpc *entry); +struct ksmbd_rpc_command *ksmbd_rpc_write(struct ksmbd_session *sess, + struct ksmbd_session_rpc *entry, void *payload, size_t payload_sz); -struct ksmbd_rpc_command *ksmbd_rpc_read(struct ksmbd_session *sess, int handle); -struct ksmbd_rpc_command *ksmbd_rpc_ioctl(struct ksmbd_session *sess, int handle, +struct ksmbd_rpc_command *ksmbd_rpc_read(struct ksmbd_session *sess, + struct ksmbd_session_rpc *entry); +struct ksmbd_rpc_command *ksmbd_rpc_ioctl(struct ksmbd_session *sess, + struct ksmbd_session_rpc *entry, void *payload, size_t payload_sz); void ksmbd_ipc_release(void); void ksmbd_ipc_soft_reset(void); diff --git a/fs/smb/server/transport_tcp.c b/fs/smb/server/transport_tcp.c index af3b6a01862b..2c0e6b9abd5e 100644 --- a/fs/smb/server/transport_tcp.c +++ b/fs/smb/server/transport_tcp.c @@ -104,6 +104,7 @@ static struct tcp_transport *alloc_transport(struct socket *client_sk) if (client_sk->sk->sk_family == AF_INET6) { memcpy(&conn->inet6_addr, &client_sk->sk->sk_v6_daddr, 16); conn->inet_hash = ipv6_addr_hash(&client_sk->sk->sk_v6_daddr); + conn->is_ipv6 = true; } else { conn->inet_addr = inet_sk(client_sk->sk)->inet_daddr; conn->inet_hash = ipv4_addr_hash(inet_sk(client_sk->sk)->inet_daddr); @@ -945,10 +946,15 @@ static void ksmbd_tcp_stop_listener(struct interface *iface) void ksmbd_tcp_destroy(void) { struct interface *iface, *tmp; + LIST_HEAD(iface_list_to_free); unregister_netdevice_notifier(&ksmbd_netdev_notifier); - list_for_each_entry_safe(iface, tmp, &iface_list, entry) { + rtnl_lock(); + list_splice_init(&iface_list, &iface_list_to_free); + rtnl_unlock(); + + list_for_each_entry_safe(iface, tmp, &iface_list_to_free, entry) { ksmbd_tcp_stop_listener(iface); list_del(&iface->entry); kfree(iface->name); diff --git a/fs/smb/server/vfs.c b/fs/smb/server/vfs.c index 674e4fcd80cb..f88daeb5ef87 100644 --- a/fs/smb/server/vfs.c +++ b/fs/smb/server/vfs.c @@ -65,12 +65,13 @@ static int ksmbd_vfs_path_lookup(struct ksmbd_share_config *share_conf, if (for_remove) 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; + CLASS(filename_kernel, filename)(pathname); scoped_with_init_fs() err = vfs_path_parent_lookup(filename, flags, path, &last, diff --git a/fs/smb/server/vfs_cache.c b/fs/smb/server/vfs_cache.c index 38196befa03a..c6999ed4e6d6 100644 --- a/fs/smb/server/vfs_cache.c +++ b/fs/smb/server/vfs_cache.c @@ -1283,11 +1283,6 @@ static int __open_id(struct ksmbd_file_table *ft, struct ksmbd_file *fp, u64 id = 0; int ret; - if (type == OPEN_ID_TYPE_VOLATILE_ID && fd_limit_depleted()) { - __open_id_set(fp, KSMBD_NO_FID, type); - return -EMFILE; - } - idr_preload(KSMBD_DEFAULT_GFP); write_lock(&ft->lock); ret = idr_alloc_cyclic(ft->idr, fp, KSMBD_START_FID, INT_MAX - 1, @@ -1297,7 +1292,6 @@ static int __open_id(struct ksmbd_file_table *ft, struct ksmbd_file *fp, ret = 0; } else { id = KSMBD_NO_FID; - fd_limit_close(); } __open_id_set(fp, id, type); @@ -1317,10 +1311,15 @@ struct ksmbd_file *ksmbd_open_fd(struct ksmbd_work *work, struct file *filp) struct ksmbd_file *fp; int ret; + /* Durable reconnects reuse the slot held for the lifetime of fp. */ + if (fd_limit_depleted()) + return ERR_PTR(-EMFILE); + fp = kmem_cache_zalloc(filp_cache, KSMBD_DEFAULT_GFP); if (!fp) { pr_err("Failed to allocate memory\n"); - return ERR_PTR(-ENOMEM); + ret = -ENOMEM; + goto err_fd_limit; } INIT_LIST_HEAD(&fp->blocked_works); @@ -1374,6 +1373,8 @@ struct ksmbd_file *ksmbd_open_fd(struct ksmbd_work *work, struct file *filp) ksmbd_conn_put(fp->conn); ksmbd_share_config_put(fp->share_conf); kmem_cache_free(filp_cache, fp); +err_fd_limit: + fd_limit_close(); return ERR_PTR(ret); } @@ -1921,6 +1922,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; @@ -1937,14 +1940,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/smb/smbdirect/accept.c b/fs/smb/smbdirect/accept.c index e7e5eb75a5ae..85e37d11f43d 100644 --- a/fs/smb/smbdirect/accept.c +++ b/fs/smb/smbdirect/accept.c @@ -234,7 +234,7 @@ static void smbdirect_accept_negotiate_recv_done(struct ib_cq *cq, struct ib_wc struct smbdirect_socket *sc = recv_io->socket; unsigned long flags; - if (unlikely(wc->status != IB_WC_SUCCESS || WARN_ON_ONCE(wc->opcode != IB_WC_RECV))) { + if (unlikely(wc->status != IB_WC_SUCCESS || wc->opcode != IB_WC_RECV)) { if (wc->status != IB_WC_WR_FLUSH_ERR) smbdirect_log_rdma_recv(sc, SMBDIRECT_LOG_ERR, "wc->status=%s (%d) wc->opcode=%d\n", diff --git a/fs/smb/smbdirect/connect.c b/fs/smb/smbdirect/connect.c index 34a3e72c38fb..0d02f03063ac 100644 --- a/fs/smb/smbdirect/connect.c +++ b/fs/smb/smbdirect/connect.c @@ -581,7 +581,7 @@ static void smbdirect_connect_negotiate_recv_done(struct ib_cq *cq, struct ib_wc struct smbdirect_socket *sc = recv_io->socket; unsigned long flags; - if (unlikely(wc->status != IB_WC_SUCCESS || WARN_ON_ONCE(wc->opcode != IB_WC_RECV))) { + if (unlikely(wc->status != IB_WC_SUCCESS || wc->opcode != IB_WC_RECV)) { if (wc->status != IB_WC_WR_FLUSH_ERR) smbdirect_log_rdma_recv(sc, SMBDIRECT_LOG_ERR, "wc->status=%s (%d) wc->opcode=%d\n", diff --git a/fs/smb/smbdirect/connection.c b/fs/smb/smbdirect/connection.c index f48c857bda5a..e6c7b343fe87 100644 --- a/fs/smb/smbdirect/connection.c +++ b/fs/smb/smbdirect/connection.c @@ -1529,7 +1529,7 @@ void smbdirect_connection_recv_io_done(struct ib_cq *cq, struct ib_wc *wc) u32 data_length; u32 remaining_data_length; - if (unlikely(wc->status != IB_WC_SUCCESS || WARN_ON_ONCE(wc->opcode != IB_WC_RECV))) { + if (unlikely(wc->status != IB_WC_SUCCESS || wc->opcode != IB_WC_RECV)) { if (wc->status != IB_WC_WR_FLUSH_ERR) smbdirect_log_rdma_recv(sc, SMBDIRECT_LOG_ERR, "wc->status=%s (%d) wc->opcode=%d\n", diff --git a/fs/splice.c b/fs/splice.c index 96378d3e6558..a815f8c70e65 100644 --- a/fs/splice.c +++ b/fs/splice.c @@ -1856,6 +1856,15 @@ static ssize_t link_pipe(struct pipe_inode_info *ipipe, unsigned int i_tail, o_tail; ssize_t ret = 0; +retry: + ret = ipipe_prep(ipipe, flags); + if (ret) + return ret; + + ret = opipe_prep(opipe, flags); + if (ret) + return ret; + /* * Potential ABBA deadlock, work around it by ordering lock * grabbing by pipe info address. Otherwise two different processes @@ -1877,13 +1886,32 @@ static ssize_t link_pipe(struct pipe_inode_info *ipipe, i_head = ipipe->head; o_tail = opipe->tail; + if (pipe_empty(i_head, i_tail) && !ipipe->writers) + break; + /* * If we have iterated all input buffers or run out of * output room, break. */ if (pipe_empty(i_head, i_tail) || - pipe_full(o_head, o_tail, opipe->max_usage)) - break; + pipe_full(o_head, o_tail, opipe->max_usage)) { + if (ret) + break; + + if (flags & SPLICE_F_NONBLOCK) { + ret = -EAGAIN; + break; + } + + /* + * We raced with another reader/writer and haven't + * linked any buffers. A zero return value means EOF, + * so retry instead. + */ + pipe_unlock(ipipe); + pipe_unlock(opipe); + goto retry; + } ibuf = pipe_buf(ipipe, i_tail); obuf = pipe_buf(opipe, o_head); @@ -1954,16 +1982,7 @@ ssize_t do_tee(struct file *in, struct file *out, size_t len, if ((in->f_flags | out->f_flags) & O_NONBLOCK) flags |= SPLICE_F_NONBLOCK; - /* - * Keep going, unless we encounter an error. The ipipe/opipe - * ordering doesn't really matter. - */ - ret = ipipe_prep(ipipe, flags); - if (!ret) { - ret = opipe_prep(opipe, flags); - if (!ret) - ret = link_pipe(ipipe, opipe, len, flags); - } + ret = link_pipe(ipipe, opipe, len, flags); } if (ret > 0) { diff --git a/fs/super.c b/fs/super.c index 1d5ccf540a9b..c5a0658f7aaf 100644 --- a/fs/super.c +++ b/fs/super.c @@ -25,7 +25,7 @@ #include #include #include -#include +#include #include #include #include /* for the emergency remount stuff */ @@ -274,8 +274,6 @@ static unsigned long super_cache_count(struct shrinker *shrink, return total_objects; } -static struct super_dev *super_dev_alloc(dev_t dev, struct super_block *sb); - static void destroy_super_work(struct work_struct *work) { struct super_block *s = container_of(work, struct super_block, @@ -283,8 +281,6 @@ static void destroy_super_work(struct work_struct *work) fsnotify_sb_free(s); security_sb_free(s); put_user_ns(s->s_user_ns); - /* Only an unregistered entry is still owned by the superblock. */ - kfree(s->s_super_dev); kfree(s->s_subtype); for (int i = 0; i < SB_FREEZE_LEVELS; i++) percpu_free_rwsem(&s->s_writers.rw_sem[i]); @@ -398,9 +394,6 @@ static struct super_block *alloc_super(struct file_system_type *type, int flags, goto fail; if (list_lru_init_memcg(&s->s_inode_lru, s->s_shrink)) goto fail; - s->s_super_dev = super_dev_alloc(0, s); - if (!s->s_super_dev) - goto fail; s->s_min_writeback_pages = MIN_WRITEBACK_PAGES; return s; @@ -435,110 +428,92 @@ void put_super(struct super_block *s) } } -struct super_dev { - dev_t sd_dev; - struct super_block *sd_sb; - refcount_t sd_ref; - struct rhlist_head sd_node; - struct rcu_head sd_rcu; -}; - -static struct rhltable super_dev_table; -static const struct rhashtable_params super_dev_params = { - .key_len = sizeof(dev_t), - .key_offset = offsetof(struct super_dev, sd_dev), - .head_offset = offsetof(struct super_dev, sd_node), -}; - -static struct super_dev *super_dev_alloc(dev_t dev, struct super_block *sb) -{ - struct super_dev *fsd; - - fsd = kzalloc_obj(*fsd); - if (!fsd) - return NULL; - fsd->sd_dev = dev; - fsd->sd_sb = sb; - refcount_set(&fsd->sd_ref, 1); - return fsd; -} - -static void super_dev_put(struct super_dev *fsd) -{ - /* Unlink only once unpinned, so a cursor never resumes from a removed node. */ - if (fsd && refcount_dec_and_test(&fsd->sd_ref)) { - rhltable_remove(&super_dev_table, &fsd->sd_node, super_dev_params); - put_super(fsd->sd_sb); - kfree_rcu(fsd, sd_rcu); - } -} - -void __init super_dev_init(void) -{ - if (rhltable_init(&super_dev_table, &super_dev_params)) - panic("VFS: Cannot initialise super_dev_table\n"); -} +/* + * Superblocks hashed by the devices they claim: s_dev from sget_fc() to + * kill_super_notify() and every block device opened through + * fs_bdev_file_open_by_{dev,path}(). Walks keep their place with a cursor, an + * entry without a superblock. + */ +#define SUPER_DEV_HASH_BITS 8 +static DEFINE_HASHTABLE(super_dev_hash, SUPER_DEV_HASH_BITS); +static DEFINE_SPINLOCK(super_dev_lock); -static int super_dev_insert(struct super_dev *fsd) +static void super_dev_add(struct super_dev *sd, struct super_block *sb, dev_t dev) { - int err; + lockdep_assert_held(&super_dev_lock); - err = rhltable_insert(&super_dev_table, &fsd->sd_node, super_dev_params); - if (!err) - refcount_inc(&fsd->sd_sb->s_passive); - return err; + sd->sd_sb = sb; + sd->sd_dev = dev; + sd->sd_claims = 1; + refcount_inc(&sb->s_passive); + hash_add(super_dev_hash, &sd->sd_hash, dev); } -/* Register @sb under @sb->s_dev as the final fallible act of a set callback. */ -static int super_dev_register(struct super_block *sb) +/* Drop a claim, the last one unhashes the entry. */ +static void super_dev_put(struct super_dev *sd) { - struct super_dev *fsd = sb->s_super_dev; - int err; + struct super_block *sb = sd->sd_sb; - lockdep_assert_held(&sb_lock); - VFS_WARN_ON_ONCE(!sb->s_dev); - VFS_WARN_ON_ONCE(!fsd || fsd->sd_dev); - - fsd->sd_dev = sb->s_dev; - err = super_dev_insert(fsd); - if (err) - fsd->sd_dev = 0; - return err; + scoped_guard(spinlock, &super_dev_lock) { + if (--sd->sd_claims) + return; + hash_del(&sd->sd_hash); + } + if (sd != &sb->s_super_dev) + kfree(sd); + put_super(sb); } -static struct super_dev *super_dev_get(struct rhlist_head *pos) +/* + * Return the superblock of the next claim behind @cursor with a passive + * reference and put @prev. The mount of a superblock that isn't born yet may + * still drop its claim, so wait for it to be born or to die and look again. + */ +static struct super_block *super_dev_next(struct super_dev *cursor, + struct super_block *prev) { - struct super_dev *sb_dev; + struct super_block *sb; + struct super_dev *sd; + + if (prev) + put_super(prev); + + for (;;) { + scoped_guard(spinlock, &super_dev_lock) { + if (!hash_hashed(&cursor->sd_hash)) + hash_add(super_dev_hash, &cursor->sd_hash, cursor->sd_dev); + sd = cursor; + hlist_for_each_entry_continue(sd, sd_hash) { + if (sd->sd_sb && sd->sd_dev == cursor->sd_dev) + break; + } + if (!sd) { + hash_del(&cursor->sd_hash); + return NULL; + } - for (; pos; pos = rcu_dereference_all(pos->next)) { - sb_dev = container_of(pos, struct super_dev, sd_node); - if (refcount_inc_not_zero(&sb_dev->sd_ref)) - return sb_dev; + sb = sd->sd_sb; + refcount_inc(&sb->s_passive); + if (super_flags(sb, SB_BORN | SB_DYING)) { + hash_del(&cursor->sd_hash); + hlist_add_behind(&cursor->sd_hash, &sd->sd_hash); + return sb; + } + } + wait_var_event(&sb->s_flags, super_flags(sb, SB_BORN | SB_DYING)); + put_super(sb); } - return NULL; } -static struct super_dev *super_dev_first(dev_t dev) +/* Unhash the cursor of a walk that stops early. */ +static void super_dev_walk_end(struct super_dev *cursor) { - struct super_dev *sb_dev; - - rcu_read_lock(); - sb_dev = super_dev_get(rhltable_lookup(&super_dev_table, &dev, super_dev_params)); - rcu_read_unlock(); - return sb_dev; + guard(spinlock)(&super_dev_lock); + hash_del(&cursor->sd_hash); } -static struct super_dev *super_dev_next(struct super_dev *prev) -{ - struct super_dev *sb_dev; - - rcu_read_lock(); - sb_dev = super_dev_get(rcu_dereference_all(prev->sd_node.next)); - rcu_read_unlock(); - - super_dev_put(prev); - return sb_dev; -} +#define for_each_dev_super(sb, cursor) \ + for (sb = super_dev_next(cursor, NULL); sb; sb = super_dev_next(cursor, sb)) static void kill_super_notify(struct super_block *sb) { @@ -548,11 +523,8 @@ static void kill_super_notify(struct super_block *sb) if (sb->s_flags & SB_DEAD) return; - /* Drop sget_fc()'s claim; a never-registered entry stays with the sb. */ - if (sb->s_super_dev->sd_dev) { - super_dev_put(sb->s_super_dev); - sb->s_super_dev = NULL; - } + /* Drop sget_fc()'s claim on s_dev. */ + super_dev_put(&sb->s_super_dev); /* * Let concurrent mounts know that this thing is really dead. @@ -880,13 +852,12 @@ struct super_block *sget_fc(struct fs_context *fc, s->s_fs_info = fc->s_fs_info; err = set(s, fc); if (err) { - VFS_WARN_ON_ONCE(s->s_super_dev->sd_dev); s->s_fs_info = NULL; spin_unlock(&sb_lock); destroy_unused_super(s); return ERR_PTR(err); } - VFS_WARN_ON_ONCE(!s->s_super_dev->sd_dev); + VFS_WARN_ON_ONCE(!s->s_dev); fc->s_fs_info = NULL; s->s_type = fc->fs_type; s->s_iflags |= fc->s_iflags; @@ -899,6 +870,8 @@ struct super_block *sget_fc(struct fs_context *fc, list_add_tail(&s->s_list, &super_blocks); hlist_add_head(&s->s_instances, &s->s_type->fs_supers); spin_unlock(&sb_lock); + scoped_guard(spinlock, &super_dev_lock) + super_dev_add(&s->s_super_dev, s, s->s_dev); get_filesystem(s->s_type); shrinker_register(s->s_shrink); return s; @@ -1042,18 +1015,14 @@ EXPORT_SYMBOL(iterate_supers_type); struct super_block *user_get_super(dev_t dev, bool excl) { - struct super_dev *sb_dev; - - for (sb_dev = super_dev_first(dev); sb_dev; sb_dev = super_dev_next(sb_dev)) { - struct super_block *sb = sb_dev->sd_sb; - - if (!super_lock(sb, excl)) - continue; + struct super_dev cursor = { .sd_dev = dev }; + struct super_block *sb; - /* The pinned entry holds a passive reference, take our own. */ - refcount_inc(&sb->s_passive); - super_dev_put(sb_dev); - return sb; + for_each_dev_super(sb, &cursor) { + if (super_lock(sb, excl)) { + super_dev_walk_end(&cursor); + return sb; + } } return NULL; } @@ -1336,16 +1305,7 @@ EXPORT_SYMBOL(free_anon_bdev); int set_anon_super(struct super_block *s, void *data) { - int error; - - error = get_anon_bdev(&s->s_dev); - if (error) - return error; - - error = super_dev_register(s); - if (error) - free_anon_bdev(s->s_dev); - return error; + return get_anon_bdev(&s->s_dev); } EXPORT_SYMBOL(set_anon_super); @@ -1374,7 +1334,17 @@ static int test_single_super(struct super_block *s, struct fs_context *fc) return 1; } -static int vfs_get_super(struct fs_context *fc, +/** + * get_tree_super - Get a superblock, optionally sharing an existing one + * @fc: The filesystem context holding the parameters + * @test: Comparison function to find a matching existing superblock, or NULL + * @fill_super: Helper to initialise a new superblock + * + * If @test is non-NULL and matches an existing superblock, that superblock is + * reused; otherwise a new anonymous superblock is created and initialised with + * @fill_super. Passing NULL for @test always creates a new superblock. + */ +int get_tree_super(struct fs_context *fc, int (*test)(struct super_block *, struct fs_context *), int (*fill_super)(struct super_block *sb, struct fs_context *fc)) @@ -1401,12 +1371,13 @@ static int vfs_get_super(struct fs_context *fc, deactivate_locked_super(sb); return err; } +EXPORT_SYMBOL_GPL(get_tree_super); int get_tree_nodev(struct fs_context *fc, int (*fill_super)(struct super_block *sb, struct fs_context *fc)) { - return vfs_get_super(fc, NULL, fill_super); + return get_tree_super(fc, NULL, fill_super); } EXPORT_SYMBOL(get_tree_nodev); @@ -1414,7 +1385,7 @@ int get_tree_single(struct fs_context *fc, int (*fill_super)(struct super_block *sb, struct fs_context *fc)) { - return vfs_get_super(fc, test_single_super, fill_super); + return get_tree_super(fc, test_single_super, fill_super); } EXPORT_SYMBOL(get_tree_single); @@ -1424,14 +1395,14 @@ int get_tree_keyed(struct fs_context *fc, void *key) { fc->s_fs_info = key; - return vfs_get_super(fc, test_keyed_super, fill_super); + return get_tree_super(fc, test_keyed_super, fill_super); } EXPORT_SYMBOL(get_tree_keyed); static int set_bdev_super(struct super_block *s, void *data) { s->s_dev = *(dev_t *)data; - return super_dev_register(s); + return 0; } static int super_s_dev_set(struct super_block *s, struct fs_context *fc) @@ -1491,14 +1462,12 @@ static int fs_super_thaw(struct super_block *sb) static void fs_bdev_mark_dead(struct block_device *bdev, bool surprise) { - struct super_dev *sb_dev; - dev_t dev = bdev->bd_dev; + struct super_dev cursor = { .sd_dev = bdev->bd_dev }; + struct super_block *sb; mutex_unlock(&bdev->bd_holder_lock); - for (sb_dev = super_dev_first(dev); sb_dev; sb_dev = super_dev_next(sb_dev)) { - struct super_block *sb = sb_dev->sd_sb; - + for_each_dev_super(sb, &cursor) { if (!super_lock_shared(sb)) continue; if (sb->s_root && (sb->s_flags & SB_ACTIVE)) { @@ -1518,14 +1487,12 @@ static void fs_bdev_mark_dead(struct block_device *bdev, bool surprise) static void fs_bdev_sync(struct block_device *bdev) { - struct super_dev *sb_dev; - dev_t dev = bdev->bd_dev; + struct super_dev cursor = { .sd_dev = bdev->bd_dev }; + struct super_block *sb; mutex_unlock(&bdev->bd_holder_lock); - for (sb_dev = super_dev_first(dev); sb_dev; sb_dev = super_dev_next(sb_dev)) { - struct super_block *sb = sb_dev->sd_sb; - + for_each_dev_super(sb, &cursor) { if (!super_lock_shared(sb)) continue; if (sb->s_root && (sb->s_flags & SB_ACTIVE)) @@ -1548,8 +1515,8 @@ static void fs_bdev_sync(struct block_device *bdev) */ static int fs_bdev_freeze(struct block_device *bdev) { - dev_t dev = bdev->bd_dev; - struct super_dev *sb_dev; + struct super_dev cursor = { .sd_dev = bdev->bd_dev }; + struct super_block *sb; unsigned int count = 0; int error = 0, err; @@ -1557,13 +1524,13 @@ static int fs_bdev_freeze(struct block_device *bdev) mutex_unlock(&bdev->bd_holder_lock); - for (sb_dev = super_dev_first(dev); sb_dev; sb_dev = super_dev_next(sb_dev)) { - if (!get_active_super(sb_dev->sd_sb)) + for_each_dev_super(sb, &cursor) { + if (!get_active_super(sb)) continue; - err = fs_super_freeze(sb_dev->sd_sb); + err = fs_super_freeze(sb); if (err && !error) error = err; - deactivate_super(sb_dev->sd_sb); + deactivate_super(sb); count++; } @@ -1593,8 +1560,8 @@ static int fs_bdev_freeze(struct block_device *bdev) */ static int fs_bdev_thaw(struct block_device *bdev) { - dev_t dev = bdev->bd_dev; - struct super_dev *sb_dev; + struct super_dev cursor = { .sd_dev = bdev->bd_dev }; + struct super_block *sb; unsigned int count = 0; int error = 0, err; @@ -1602,13 +1569,13 @@ static int fs_bdev_thaw(struct block_device *bdev) mutex_unlock(&bdev->bd_holder_lock); - for (sb_dev = super_dev_first(dev); sb_dev; sb_dev = super_dev_next(sb_dev)) { - if (!get_active_super(sb_dev->sd_sb)) + for_each_dev_super(sb, &cursor) { + if (!get_active_super(sb)) continue; - err = fs_super_thaw(sb_dev->sd_sb); + err = fs_super_thaw(sb); if (err && !error) error = err; - deactivate_super(sb_dev->sd_sb); + deactivate_super(sb); count++; } @@ -1625,55 +1592,39 @@ static const struct blk_holder_ops fs_holder_ops = { .thaw = fs_bdev_thaw, }; -static struct super_dev *super_dev_lookup(dev_t dev, struct super_block *sb) +static struct super_dev *super_dev_find(dev_t dev, const struct super_block *sb) { - struct super_dev *it; - struct rhlist_head *list, *pos; + struct super_dev *sd; - RCU_LOCKDEP_WARN(!rcu_read_lock_held(), "suspicious super_dev_lookup() usage"); - VFS_WARN_ON_ONCE(!dev); - VFS_WARN_ON_ONCE(!sb); + lockdep_assert_held(&super_dev_lock); - list = rhltable_lookup(&super_dev_table, &dev, super_dev_params); - rhl_for_each_entry_rcu(it, pos, list, sd_node) { - if (it->sd_sb == sb) - return it; + hash_for_each_possible(super_dev_hash, sd, sd_hash, dev) { + if (sd->sd_dev == dev && sd->sd_sb == sb) + return sd; } - return NULL; } -static int fs_bdev_register(struct file *bdev_file, struct super_block *sb) +static int fs_bdev_register(struct block_device *bdev, struct super_block *sb) { - struct super_dev *sb_dev __free(kfree) = NULL; - dev_t dev = file_bdev(bdev_file)->bd_dev; - int err; + struct super_dev *new __free(kfree) = NULL; + struct super_dev *sd; - scoped_guard(rcu) { - sb_dev = super_dev_lookup(dev, sb); - if (sb_dev && refcount_inc_not_zero(&sb_dev->sd_ref)) { - retain_and_null_ptr(sb_dev); - return 0; - } - } + new = kzalloc_obj(*new); - sb_dev = super_dev_alloc(dev, sb); - if (!sb_dev) - return -ENOMEM; - - err = super_dev_insert(sb_dev); - if (err) - return err; - - /* Publish the entry before reading the count; pairs with bdev_freeze(). */ - smp_mb(); - if (atomic_read(&file_bdev(bdev_file)->bd_fsfreeze_count) > 0) { - err = -EBUSY; - super_dev_put(sb_dev); + guard(spinlock)(&super_dev_lock); + sd = super_dev_find(bdev->bd_dev, sb); + if (sd) { + sd->sd_claims++; + return 0; } - - retain_and_null_ptr(sb_dev); - return err; + /* bdev_freeze() raises the count before its walk takes the lock. */ + if (atomic_read(&bdev->bd_fsfreeze_count) > 0) + return -EBUSY; + if (!new) + return -ENOMEM; + super_dev_add(no_free_ptr(new), sb, bdev->bd_dev); + return 0; } /** @@ -1700,7 +1651,7 @@ struct file *fs_bdev_file_open_by_dev(dev_t dev, blk_mode_t mode, void *holder, if (IS_ERR(bdev_file)) return bdev_file; - err = fs_bdev_register(bdev_file, sb); + err = fs_bdev_register(file_bdev(bdev_file), sb); if (err) { bdev_fput(bdev_file); return ERR_PTR(err); @@ -1734,7 +1685,7 @@ struct file *fs_bdev_file_open_by_path(const char *path, blk_mode_t mode, if (IS_ERR(bdev_file)) return bdev_file; - err = fs_bdev_register(bdev_file, sb); + err = fs_bdev_register(file_bdev(bdev_file), sb); if (err) { bdev_fput(bdev_file); return ERR_PTR(err); @@ -1749,21 +1700,20 @@ EXPORT_SYMBOL_GPL(fs_bdev_file_open_by_path); * @sb: superblock the device was claimed for * * The inverse of fs_bdev_register(): drop one claim on the {dev, @sb} entry - * (the last claim unregisters it; a pinning cursor defers the actual unlink) - * without closing the device. A caller that must act on the still-open device - * between unregistering and closing - e.g. re-allow freezing one denied for a - * membership change - pairs this with bdev_fput(). fs_bdev_file_release() is - * the common unregister-and-close. + * (the last claim unregisters it) without closing the device. A caller that + * must act on the still-open device between unregistering and closing - e.g. + * re-allow freezing one denied for a membership change - pairs this with + * bdev_fput(). fs_bdev_file_release() is the common unregister-and-close. */ void fs_bdev_unregister(struct file *bdev_file, struct super_block *sb) { - dev_t dev = file_bdev(bdev_file)->bd_dev; - struct super_dev *sb_dev; + struct super_dev *sd; - rcu_read_lock(); - sb_dev = super_dev_lookup(dev, sb); - rcu_read_unlock(); - super_dev_put(sb_dev); + /* The claim we're dropping keeps the entry hashed. */ + scoped_guard(spinlock, &super_dev_lock) + sd = super_dev_find(file_bdev(bdev_file)->bd_dev, sb); + if (sd) + super_dev_put(sd); } EXPORT_SYMBOL_GPL(fs_bdev_unregister); @@ -1806,8 +1756,7 @@ int setup_bdev_super(struct super_block *sb, int sb_flags, return -EACCES; } - /* The sget_fc() entry is already published; pairs with bdev_freeze(). */ - smp_mb(); + /* sget_fc() hashed @sb, super_dev_lock orders that against bdev_freeze(). */ if (atomic_read(&bdev->bd_fsfreeze_count) > 0) { if (fc) warnf(fc, "%pg: Can't mount, blockdev is frozen", bdev); diff --git a/fs/xattr.c b/fs/xattr.c index d58979115200..44710ef2dfe5 100644 --- a/fs/xattr.c +++ b/fs/xattr.c @@ -332,7 +332,7 @@ vfs_setxattr(struct mnt_idmap *idmap, struct dentry *dentry, const void *orig_value = value; int error; - if (size && strcmp(name, XATTR_NAME_CAPS) == 0) { + if (strcmp(name, XATTR_NAME_CAPS) == 0) { error = cap_convert_nscap(idmap, dentry, &value, size); if (error < 0) return error; diff --git a/include/acpi/acpi_bus.h b/include/acpi/acpi_bus.h index 8b1d329455f7..40df037804a5 100644 --- a/include/acpi/acpi_bus.h +++ b/include/acpi/acpi_bus.h @@ -672,7 +672,7 @@ struct acpi_bus_type { int register_acpi_bus_type(struct acpi_bus_type *); int unregister_acpi_bus_type(struct acpi_bus_type *); int acpi_bind_one(struct device *dev, struct acpi_device *adev); -int acpi_unbind_one(struct device *dev); +void acpi_unbind_one(struct device *dev); enum acpi_bridge_type { ACPI_BRIDGE_TYPE_PCIE = 1, diff --git a/include/acpi/ghes.h b/include/acpi/ghes.h index 8d7e5caef3f1..7acf209061ea 100644 --- a/include/acpi/ghes.h +++ b/include/acpi/ghes.h @@ -85,6 +85,10 @@ int devm_ghes_register_vendor_record_notifier(struct device *dev, struct list_head *ghes_get_devices(void); void ghes_estatus_pool_region_free(unsigned long addr, u32 size); + +struct cxl_cper_sec_prot_err; +void cxl_cper_post_prot_err(struct cxl_cper_sec_prot_err *prot_err, + int severity, u32 len); #else static inline struct list_head *ghes_get_devices(void) { return NULL; } diff --git a/include/asm-generic/mshyperv.h b/include/asm-generic/mshyperv.h index bf601d67cecb..98fe5c0f54ea 100644 --- a/include/asm-generic/mshyperv.h +++ b/include/asm-generic/mshyperv.h @@ -183,8 +183,6 @@ void hv_remove_vmbus_handler(void); void hv_setup_stimer0_handler(void (*handler)(void)); void hv_remove_stimer0_handler(void); -void hv_setup_kexec_handler(void (*handler)(void)); -void hv_remove_kexec_handler(void); void hv_setup_crash_handler(void (*handler)(struct pt_regs *regs)); void hv_remove_crash_handler(void); void hv_setup_mshv_handler(void (*handler)(void)); diff --git a/include/asm-generic/vmlinux.lds.h b/include/asm-generic/vmlinux.lds.h index b2988aa12f66..7a3e9f00d628 100644 --- a/include/asm-generic/vmlinux.lds.h +++ b/include/asm-generic/vmlinux.lds.h @@ -855,7 +855,7 @@ KLP_SYMID #define MODINFO \ - .modinfo : { *(.modinfo) . = ALIGN(8); } + .modinfo (INFO) : { KEEP(*(.modinfo)) } #ifdef CONFIG_GENERIC_BUG #define BUG_TABLE \ diff --git a/include/cxl/event.h b/include/cxl/event.h index b5673384d930..5779e35310c7 100644 --- a/include/cxl/event.h +++ b/include/cxl/event.h @@ -312,13 +312,13 @@ static inline int cxl_cper_prot_err_kfifo_get(struct cxl_cper_prot_err_work_data #endif #ifdef CONFIG_ACPI_APEI_PCIEAER -int cxl_cper_sec_prot_err_valid(struct cxl_cper_sec_prot_err *prot_err); +int cxl_cper_sec_prot_err_valid(struct cxl_cper_sec_prot_err *prot_err, u32 len); int cxl_cper_setup_prot_err_work_data(struct cxl_cper_prot_err_work_data *wd, struct cxl_cper_sec_prot_err *prot_err, int severity); #else static inline int -cxl_cper_sec_prot_err_valid(struct cxl_cper_sec_prot_err *prot_err) +cxl_cper_sec_prot_err_valid(struct cxl_cper_sec_prot_err *prot_err, u32 len) { return -EOPNOTSUPP; } diff --git a/include/drm/drm_timeout.h b/include/drm/drm_timeout.h new file mode 100644 index 000000000000..6ee222a3e97c --- /dev/null +++ b/include/drm/drm_timeout.h @@ -0,0 +1,17 @@ +/* SPDX-License-Identifier: MIT */ +/* + * Function prototypes for timeout conversion helpers for wait ioctls. + * + * Copyright 2017 Red Hat + * Copyright 2016 Advanced Micro Devices, Inc. + */ + +#ifndef __DRM_TIMEOUT_H__ +#define __DRM_TIMEOUT_H__ + +#include + +signed long drm_timeout_abs_to_jiffies(s64 timeout_nsec); +unsigned long drm_timeout_rel_to_jiffies(u64 timeout_nsec); + +#endif diff --git a/include/drm/drm_utils.h b/include/drm/drm_utils.h index 7e077484c5bb..c61dee76451c 100644 --- a/include/drm/drm_utils.h +++ b/include/drm/drm_utils.h @@ -25,6 +25,4 @@ struct drm_panel_backlight_quirk { const struct drm_panel_backlight_quirk * drm_get_panel_backlight_quirk(const struct drm_edid *edid); -signed long drm_timeout_abs_to_jiffies(int64_t timeout_nsec); - #endif diff --git a/include/dt-bindings/clock/qcom,nord-nwgcc.h b/include/dt-bindings/clock/qcom,nord-nwgcc.h index b6253dd2aa85..8beaa129aa81 100644 --- a/include/dt-bindings/clock/qcom,nord-nwgcc.h +++ b/include/dt-bindings/clock/qcom,nord-nwgcc.h @@ -65,5 +65,8 @@ #define NW_GCC_GPU_2_BCR 6 #define NW_GCC_GPU_BCR 7 #define NW_GCC_VIDEO_BCR 8 +#define NW_GCC_VIDEO_AXI0_CLK_ARES 9 +#define NW_GCC_VIDEO_AXI0C_CLK_ARES 10 +#define NW_GCC_VIDEO_AXI1_CLK_ARES 11 #endif diff --git a/include/linux/acpi.h b/include/linux/acpi.h index ddacac812094..f7e3efd328f7 100644 --- a/include/linux/acpi.h +++ b/include/linux/acpi.h @@ -1305,34 +1305,34 @@ void __acpi_handle_debug(struct _ddebug *descriptor, acpi_handle handle, const c #endif /* - * acpi_handle_: Print message with ACPI prefix and object path + * acpi_handle_ - Print a message with ACPI prefix and object path * - * These interfaces acquire the global namespace mutex to obtain an object - * path. In interrupt context, it shows the object path as . + * In thread context, the global namespace mutex is acquired to obtain the + * object path. In interrupt context, the object path is shown as . */ #define acpi_handle_emerg(handle, fmt, ...) \ - acpi_handle_printk(KERN_EMERG, handle, fmt, ##__VA_ARGS__) + acpi_handle_printk(KERN_EMERG, handle, dev_fmt(fmt), ##__VA_ARGS__) #define acpi_handle_alert(handle, fmt, ...) \ - acpi_handle_printk(KERN_ALERT, handle, fmt, ##__VA_ARGS__) + acpi_handle_printk(KERN_ALERT, handle, dev_fmt(fmt), ##__VA_ARGS__) #define acpi_handle_crit(handle, fmt, ...) \ - acpi_handle_printk(KERN_CRIT, handle, fmt, ##__VA_ARGS__) + acpi_handle_printk(KERN_CRIT, handle, dev_fmt(fmt), ##__VA_ARGS__) #define acpi_handle_err(handle, fmt, ...) \ - acpi_handle_printk(KERN_ERR, handle, fmt, ##__VA_ARGS__) + acpi_handle_printk(KERN_ERR, handle, dev_fmt(fmt), ##__VA_ARGS__) #define acpi_handle_warn(handle, fmt, ...) \ - acpi_handle_printk(KERN_WARNING, handle, fmt, ##__VA_ARGS__) + acpi_handle_printk(KERN_WARNING, handle, dev_fmt(fmt), ##__VA_ARGS__) #define acpi_handle_notice(handle, fmt, ...) \ - acpi_handle_printk(KERN_NOTICE, handle, fmt, ##__VA_ARGS__) + acpi_handle_printk(KERN_NOTICE, handle, dev_fmt(fmt), ##__VA_ARGS__) #define acpi_handle_info(handle, fmt, ...) \ - acpi_handle_printk(KERN_INFO, handle, fmt, ##__VA_ARGS__) + acpi_handle_printk(KERN_INFO, handle, dev_fmt(fmt), ##__VA_ARGS__) #if defined(DEBUG) #define acpi_handle_debug(handle, fmt, ...) \ - acpi_handle_printk(KERN_DEBUG, handle, fmt, ##__VA_ARGS__) + acpi_handle_printk(KERN_DEBUG, handle, dev_fmt(fmt), ##__VA_ARGS__) #else #if defined(CONFIG_DYNAMIC_DEBUG) #define acpi_handle_debug(handle, fmt, ...) \ _dynamic_func_call(fmt, __acpi_handle_debug, \ - handle, pr_fmt(fmt), ##__VA_ARGS__) + handle, dev_fmt(fmt), ##__VA_ARGS__) #else #define acpi_handle_debug(handle, fmt, ...) \ ({ \ diff --git a/include/linux/bio-integrity.h b/include/linux/bio-integrity.h index 0ea2a8bf7efb..a954c97be0b3 100644 --- a/include/linux/bio-integrity.h +++ b/include/linux/bio-integrity.h @@ -151,7 +151,6 @@ void bio_integrity_setup_default(struct bio *bio); unsigned int fs_bio_integrity_alloc(struct bio *bio); void fs_bio_integrity_free(struct bio *bio); void fs_bio_integrity_generate(struct bio *bio); -int fs_bio_integrity_verify(struct bio *bio, sector_t sector, - unsigned int size); +int fs_bio_integrity_verify(struct bio *bio, struct bvec_iter *data_iter); #endif /* _LINUX_BIO_INTEGRITY_H */ diff --git a/include/linux/blk-mq.h b/include/linux/blk-mq.h index af878597afb8..aa3b35405edc 100644 --- a/include/linux/blk-mq.h +++ b/include/linux/blk-mq.h @@ -523,10 +523,12 @@ enum hctx_type { * @tag_list_lock: Serializes tag_list accesses. * @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. + * @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 * (BLK_MQ_F_BLOCKING). - * @tags_srcu: SRCU used to defer freeing of tags page_list to prevent - * use-after-free when iterating tags. * @update_nr_hwq_lock: * Synchronize updating nr_hw_queues with add/del disk & * switching elevator. @@ -550,8 +552,9 @@ struct blk_mq_tag_set { struct mutex tag_list_lock; struct list_head tag_list; + spinlock_t quiesce_lock; + unsigned int quiesce_depth; struct srcu_struct *srcu; - struct srcu_struct tags_srcu; struct rw_semaphore update_nr_hwq_lock; }; diff --git a/include/linux/blkdev.h b/include/linux/blkdev.h index 3989bb0dd43b..b5d247474e77 100644 --- a/include/linux/blkdev.h +++ b/include/linux/blkdev.h @@ -1814,8 +1814,11 @@ static inline int bio_split_rw_at(struct bio *bio, */ static inline unsigned int max_integrity_io_size(struct queue_limits *lim) { - return min_t(unsigned int, lim->max_segment_size, - (BLK_INTEGRITY_MAX_SIZE / lim->integrity.metadata_size) << + unsigned int buf_size = min_t(unsigned int, lim->max_segment_size, + BLK_INTEGRITY_MAX_SIZE); + + return min_t(u64, UINT_MAX, + (u64)(buf_size / lim->integrity.metadata_size) << lim->integrity.interval_exp); } diff --git a/include/linux/bpf.h b/include/linux/bpf.h index 0ecb9418dfbd..a628f182bb64 100644 --- a/include/linux/bpf.h +++ b/include/linux/bpf.h @@ -337,6 +337,7 @@ struct bpf_map { bool frozen; /* write-once; write-protected by freeze_mutex */ bool free_after_mult_rcu_gp; bool free_after_rcu_gp; + bool was_inner_map; atomic64_t sleepable_refcnt; s64 __percpu *elem_count; u64 cookie; /* write-once */ @@ -1684,12 +1685,20 @@ static inline void bpf_trampoline_multi_detach(struct bpf_prog *prog, static inline void bpf_trampoline_set_flags(struct bpf_trampoline *tr, u32 flags) {} #endif +/* The contexts that a global function is called in, and is verified for. */ +enum bpf_func_context { + BPF_FUNC_CTX_NON_SLEEPABLE, + BPF_FUNC_CTX_SLEEPABLE, + /* Sleepable code has disabled preemption or interrupts: no RCU read lock. */ + BPF_FUNC_CTX_NO_RCU_LOCK, + BPF_FUNC_CTX_CNT, +}; + struct bpf_func_info_aux { u16 linkage; bool unreliable; - /* Indexed by in_sleepable. */ - bool called[2]; - bool verified[2]; + bool called[BPF_FUNC_CTX_CNT]; + bool verified[BPF_FUNC_CTX_CNT]; }; enum bpf_jit_poke_reason { @@ -1807,12 +1816,12 @@ struct bpf_prog_aux { bool attach_btf_trace; /* true if attaching to BTF-enabled raw tp */ bool attach_tracing_prog; /* true if tracing another tracing program */ bool tramp_linked; /* true if it was ever linked to a trampoline */ + 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; @@ -1824,7 +1833,7 @@ struct bpf_prog_aux { u8 verdict; } sig; 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 */ @@ -1856,6 +1865,7 @@ struct bpf_prog_aux { char name[BPF_OBJ_NAME_LEN]; u64 (*bpf_exception_cb)(u64 cookie, u64 sp, u64 bp, u64, u64); u16 stack_arg_sp_adjust; + u16 freplace_link_cnt; /* counts freplace links extending this prog */ #ifdef CONFIG_SECURITY void *security; #endif @@ -1892,6 +1902,7 @@ struct bpf_prog_aux { union { struct work_struct work; struct rcu_head rcu; + struct rcu_work rwork; }; struct bpf_stream stream[2]; struct mutex st_ops_assoc_mutex; @@ -1940,6 +1951,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; @@ -2821,8 +2841,10 @@ struct bpf_map *bpf_map_get_curr_or_next(u32 *id); struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id); -int bpf_map_alloc_pages(const struct bpf_map *map, int nid, - unsigned long nr_pages, struct page **page_array); +struct page *bpf_alloc_page(int nid, bool sleepable); +int bpf_alloc_pages(int nid, unsigned long nr_pages, + struct llist_head *pages, bool sleepable); +void bpf_free_pages(struct llist_head *pages); #ifdef CONFIG_MEMCG void bpf_map_memcg_enter(const struct bpf_map *map, struct mem_cgroup **old_memcg, struct mem_cgroup **new_memcg); @@ -3017,7 +3039,8 @@ typedef const struct bpf_func_proto * const struct bpf_prog *prog); enum bpf_iter_feature { - BPF_ITER_RESCHED = BIT(0), + BPF_ITER_RESCHED = BIT(0), /* may cond_resched() between objects */ + BPF_ITER_NOSLEEP = BIT(1), /* ->show() can't run sleepable progs */ }; #define BPF_ITER_CTX_ARG_MAX 2 @@ -3667,6 +3690,7 @@ int bpf_dev_bound_kfunc_check(struct bpf_verifier_log *log, void *bpf_dev_bound_resolve_kfunc(struct bpf_prog *prog, u32 func_id); int bpf_prog_dev_bound_init(struct bpf_prog *prog, union bpf_attr *attr); int bpf_prog_dev_bound_inherit(struct bpf_prog *new_prog, struct bpf_prog *old_prog); +void bpf_prog_dev_bound_moved(struct bpf_prog *prog); void bpf_dev_bound_netdev_unregister(struct net_device *dev); static inline bool bpf_prog_is_dev_bound(const struct bpf_prog_aux *aux) @@ -3728,6 +3752,10 @@ static inline int bpf_prog_dev_bound_inherit(struct bpf_prog *new_prog, return -EOPNOTSUPP; } +static inline void bpf_prog_dev_bound_moved(struct bpf_prog *prog) +{ +} + static inline void bpf_dev_bound_netdev_unregister(struct net_device *dev) { } @@ -4140,7 +4168,7 @@ void bpf_put_buffers(void); void bpf_prog_stream_init(struct bpf_prog *prog); void bpf_prog_stream_free(struct bpf_prog *prog); -int bpf_prog_stream_read(struct bpf_prog *prog, enum bpf_stream_id stream_id, void __user *buf, int len); +int bpf_prog_stream_read(struct bpf_prog *prog, enum bpf_stream_id stream_id, void __user *buf, u32 len); void bpf_stream_stage_init(struct bpf_stream_stage *ss); void bpf_stream_stage_free(struct bpf_stream_stage *ss); __printf(2, 3) @@ -4228,6 +4256,9 @@ static inline bool bpf_map_is_percpu_map(enum bpf_map_type map_type) } } +#define BPF_EXIST_FLAGS (BPF_EXIST | BPF_NOEXIST) +#define BPF_CPU_FLAGS (BPF_F_CPU | BPF_F_ALL_CPUS) + static inline int bpf_map_check_op_flags(struct bpf_map *map, u64 flags, u64 allowed_flags) { u32 cpu; diff --git a/include/linux/bpf_local_storage.h b/include/linux/bpf_local_storage.h index 9e4f5c45c974..6c643ac51079 100644 --- a/include/linux/bpf_local_storage.h +++ b/include/linux/bpf_local_storage.h @@ -104,6 +104,19 @@ struct bpf_local_storage { refcount_t owner_refcnt;/* Used to pin owner when map_free is uncharging */ }; +/* + * Drop a reference got by refcount_inc_not_zero(&local_storage->owner_refcnt). + * bpf_local_storage_destroy() may have dropped the owner's reference meanwhile + * and wait for the count to reach zero, so this one can be the last. + */ +static inline void +bpf_local_storage_unpin_owner(struct bpf_local_storage *local_storage) +{ + bool last __maybe_unused; + + last = refcount_dec_and_test(&local_storage->owner_refcnt); +} + /* U16_MAX is much more than enough for sk local storage * considering a tcp_sock is ~2k. */ diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h index b83ec99f1a13..0eda96e1162f 100644 --- a/include/linux/bpf_verifier.h +++ b/include/linux/bpf_verifier.h @@ -243,55 +243,17 @@ enum bpf_stack_slot_type { #define BPF_REG_SIZE 8 /* size of eBPF register in bytes */ +/* + * Largest number of BPF_REG_SIZE stack slots a single frame can have. A frame + * may use any part of the MAX_BPF_STACK budget; check_max_stack_depth() + * enforces the bound on the combined depth of frames sharing the kernel stack + * and on each frame using a private stack. + */ +#define MAX_BPF_STACK_SLOTS (MAX_BPF_STACK / BPF_REG_SIZE) + /* 4-byte stack slot granularity for liveness analysis */ #define BPF_HALF_REG_SIZE 4 #define STACK_SLOT_SZ 4 -#define STACK_SLOTS (MAX_BPF_STACK / BPF_HALF_REG_SIZE) /* 128 */ - -typedef struct { - u64 v[2]; -} spis_t; - -#define SPIS_ZERO ((spis_t){}) -#define SPIS_ALL ((spis_t){{ U64_MAX, U64_MAX }}) - -static inline bool spis_is_zero(spis_t s) -{ - return s.v[0] == 0 && s.v[1] == 0; -} - -static inline bool spis_equal(spis_t a, spis_t b) -{ - return a.v[0] == b.v[0] && a.v[1] == b.v[1]; -} - -static inline spis_t spis_or(spis_t a, spis_t b) -{ - return (spis_t){{ a.v[0] | b.v[0], a.v[1] | b.v[1] }}; -} - -static inline spis_t spis_and(spis_t a, spis_t b) -{ - return (spis_t){{ a.v[0] & b.v[0], a.v[1] & b.v[1] }}; -} - -static inline spis_t spis_not(spis_t s) -{ - return (spis_t){{ ~s.v[0], ~s.v[1] }}; -} - -static inline bool spis_test_bit(spis_t s, u32 slot) -{ - return s.v[slot / 64] & BIT_ULL(slot % 64); -} - -static inline void spis_or_range(spis_t *mask, u32 lo, u32 hi) -{ - u32 w; - - for (w = lo; w <= hi && w < STACK_SLOTS; w++) - mask->v[w / 64] |= BIT_ULL(w % 64); -} #define BPF_REGMASK_ARGS ((1 << BPF_REG_1) | (1 << BPF_REG_2) | \ (1 << BPF_REG_3) | (1 << BPF_REG_4) | \ @@ -375,6 +337,11 @@ struct bpf_func_state { bool in_async_callback_fn; bool in_exception_callback_fn; bool no_stack_arg_load; + /* + * The helper invokes this callback under rcu_read_lock(), so the + * callback and its callees run in an RCU read-side critical section. + */ + bool in_rcu_callback_fn; /* For callback calling functions that limit number of possible * callback executions (e.g. bpf_loop) keeps track of current * simulated iteration number. @@ -425,12 +392,11 @@ struct bpf_jmp_history_entry { /* insn idx can't be bigger than 1 million */ u32 idx : 20; u32 frame : 4; /* stack access frame number */ - u32 spi : 6; /* stack slot index (0..63) */ - u32 : 2; - u32 prev_idx : 20; /* special INSN_F_xxx flags */ u32 flags : 4; - u32 : 8; + u32 : 4; + u32 prev_idx : 20; + u32 spi : 12; /* stack slot index */ /* * additional registers that need precision tracking when this * jump is backtracked, vector of five 11-bit records @@ -439,12 +405,12 @@ struct bpf_jmp_history_entry { }; static_assert(MAX_CALL_FRAMES <= (1 << 4)); -static_assert(MAX_BPF_STACK / 8 <= (1 << 6)); +static_assert(MAX_BPF_STACK_SLOTS <= (1 << 12)); /* Maximum number of bpf_reg_state objects that can exist at once */ #define MAX_STACK_ARG_SLOTS (MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS) -#define BPF_ID_MAP_SIZE ((MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE + \ - MAX_STACK_ARG_SLOTS) * MAX_CALL_FRAMES) +#define BPF_ID_MAP_SIZE ((MAX_BPF_REG + MAX_BPF_STACK_SLOTS + MAX_STACK_ARG_SLOTS) * \ + MAX_CALL_FRAMES) struct bpf_verifier_state { /* call stack tracking */ struct bpf_func_state *frame[MAX_CALL_FRAMES]; @@ -530,12 +496,31 @@ struct bpf_verifier_state { u32 may_goto_depth; }; +/* Number of BPF_REG_SIZE stack slots tracked for the frame so far. */ +static inline u32 bpf_stack_nr_slots(const struct bpf_func_state *frame) +{ + return frame->allocated_stack / BPF_REG_SIZE; +} + +/* + * Stack slot @spi of @frame, covering bytes [fp - (spi + 1) * 8, fp - spi * 8). + * The caller must ensure spi < bpf_stack_nr_slots(frame), see grow_stack_state(). + */ +static inline struct bpf_stack_state *bpf_stack_slot(const struct bpf_func_state *frame, u32 spi) +{ + return &frame->stack[spi]; +} + static inline struct bpf_reg_state * bpf_get_spilled_reg(int slot, struct bpf_func_state *frame, u32 mask) { - if (slot < frame->allocated_stack / BPF_REG_SIZE && - (1 << frame->stack[slot].slot_type[BPF_REG_SIZE - 1]) & mask) - return &frame->stack[slot].spilled_ptr; + struct bpf_stack_state *ss; + + if (slot >= bpf_stack_nr_slots(frame)) + return NULL; + ss = bpf_stack_slot(frame, slot); + if ((1 << ss->slot_type[BPF_REG_SIZE - 1]) & mask) + return &ss->spilled_ptr; return NULL; } @@ -551,7 +536,7 @@ bpf_get_spilled_stack_arg(int slot, struct bpf_func_state *frame) /* Iterate over 'frame', setting 'reg' to either NULL or a spilled register. */ #define bpf_for_each_spilled_reg(iter, frame, reg, mask) \ for (iter = 0, reg = bpf_get_spilled_reg(iter, frame, mask); \ - iter < frame->allocated_stack / BPF_REG_SIZE; \ + iter < bpf_stack_nr_slots(frame); \ iter++, reg = bpf_get_spilled_reg(iter, frame, mask)) /* Iterate over 'frame', setting 'reg' to either NULL or a spilled stack arg. */ @@ -576,7 +561,7 @@ bpf_get_spilled_stack_arg(int slot, struct bpf_func_state *frame) bpf_for_each_spilled_reg(___j, __state, __reg, __mask) { \ if (!__reg) \ continue; \ - __stack = &__state->stack[___j]; \ + __stack = bpf_stack_slot(__state, ___j); \ (void)(__expr); \ } \ __stack = NULL; \ @@ -806,7 +791,11 @@ struct bpf_subprog_info { u32 start; /* insn idx of function entry point */ u32 linfo_idx; /* The idx to the main_prog->aux->linfo */ u32 postorder_start; /* The idx to the env->cfg.insn_postorder */ - u32 exit_idx; /* Index of one of the BPF_EXIT instructions in this subprogram */ + /* + * Index of one of the BPF_EXIT instructions in this subprogram, or + * U32_MAX when it has none. + */ + u32 exit_idx; u16 stack_depth; /* max. stack depth used by this function */ u16 stack_extra; u32 insns_total; @@ -954,6 +943,8 @@ struct bpf_verifier_env { bool bypass_spec_v1; bool bypass_spec_v4; bool seen_direct_write; + /* a global function is verified for BPF_FUNC_CTX_NO_RCU_LOCK */ + bool no_rcu_read_lock; bool seen_exception; bool signature; u32 insn_aux_data_len; @@ -976,14 +967,16 @@ struct bpf_verifier_env { * see bpf_subprog_info->postorder_start. */ int *insn_postorder; + int *postorder_nums; int cur_stack; /* current position in the insn_postorder vector */ int cur_postorder; + u32 gotox_edges; } cfg; struct backtrack_state bt; struct bpf_jmp_history_entry *cur_hist_ent; - /* Per-callsite copy of parent's converged at_stack_in for cross-frame fills. */ - struct arg_track **callsite_at_stack; + /* Per-callsite snapshot of the parent's tracked spill slots for cross-frame fills. */ + struct spill_snapshot **callsite_at_stack; u32 pass_cnt; /* number of times do_check() was called */ u32 subprog_cnt; /* number of instructions analyzed by the verifier */ diff --git a/include/linux/btf.h b/include/linux/btf.h index 7c62ea17b116..19eff0c17b2a 100644 --- a/include/linux/btf.h +++ b/include/linux/btf.h @@ -81,6 +81,7 @@ #define KF_IMPLICIT_ARGS (1 << 16) /* kfunc has implicit arguments supplied by the verifier */ #define KF_SPINLOCK_SAFE (1 << 17) /* kfunc is allowed inside bpf_spin_lock-ed region */ #define KF_PERFMON (1 << 18) /* kfunc requires CAP_PERFMON */ +#define KF_ITER_RET_INDEPENDENT (1 << 19) /* next result outlives the current element */ /* * Tag marking a kernel function as a kfunc. This is meant to minimize the diff --git a/include/linux/clk-provider.h b/include/linux/clk-provider.h index dc8e161f9c2c..58902e8dfd68 100644 --- a/include/linux/clk-provider.h +++ b/include/linux/clk-provider.h @@ -50,6 +50,7 @@ struct clk; struct clk_hw; struct clk_core; struct dentry; +struct module; /** * struct clk_rate_request - Structure encoding the clk constraints that @@ -351,8 +352,9 @@ struct clk_init_data { * @core: pointer to the struct clk_core instance that points back to this * struct clk_hw instance * - * @clk: pointer to the per-user struct clk instance that can be used to call - * into the clk API + * @clk: pointer to the per-user struct clk instance. This will be removed at + * some point in the future, Please consider the field obsolete and do not use + * it. Use clk_hw_get_clk() to get a per-user struct clk from a struct clk_hw. * * @init: pointer to struct clk_init_data that contains the init data shared * with the common clock framework. This pointer will be set to NULL once @@ -1474,10 +1476,24 @@ static inline struct clk_hw *__clk_get_hw(struct clk *clk) } #endif -struct clk *clk_hw_get_clk(struct clk_hw *hw, const char *con_id); +struct clk *__clk_hw_get_clk(struct clk_hw *hw, const char *con_id, + struct module *owner); struct clk *devm_clk_hw_get_clk(struct device *dev, struct clk_hw *hw, const char *con_id); +/** + * clk_hw_get_clk - get clk consumer given a clk_hw + * @hw: clk_hw associated with the clk being consumed + * @con_id: connection ID string on device + * + * Return: new clk consumer + * This is the function to be used by providers which need + * to get a consumer clk and act on the clock element + * Calls to this function must be balanced with calls to clk_put() + */ +#define clk_hw_get_clk(hw, con_id) \ + __clk_hw_get_clk((hw), (con_id), THIS_MODULE) + unsigned int clk_hw_get_num_parents(const struct clk_hw *hw); struct clk_hw *clk_hw_get_parent(const struct clk_hw *hw); struct clk_hw *clk_hw_get_parent_by_index(const struct clk_hw *hw, diff --git a/include/linux/dax.h b/include/linux/dax.h index fe6c3ded1b50..2c9fc81f031b 100644 --- a/include/linux/dax.h +++ b/include/linux/dax.h @@ -54,7 +54,6 @@ struct dax_device *alloc_dax(void *private, const struct dax_operations *ops); void *dax_holder(struct dax_device *dax_dev); void put_dax(struct dax_device *dax_dev); void kill_dax(struct dax_device *dax_dev); -struct dax_device *dax_dev_get(dev_t devt); void dax_write_cache(struct dax_device *dax_dev, bool wc); bool dax_write_cache_enabled(struct dax_device *dax_dev); bool dax_synchronous(struct dax_device *dax_dev); @@ -323,3 +322,5 @@ typedef int (*walk_hmem_fn)(struct device *dev, int target_nid, const struct resource *res); int walk_hmem_resources(struct device *dev, walk_hmem_fn fn); #endif + +struct dax_device *fsdev_dax_from_file(struct file *file); diff --git a/include/linux/device.h b/include/linux/device.h index ae05205742c0..87532f362153 100644 --- a/include/linux/device.h +++ b/include/linux/device.h @@ -1126,6 +1126,7 @@ static inline void device_unlock(struct device *dev) DEFINE_GUARD(device, struct device *, device_lock(_T), device_unlock(_T)) DEFINE_GUARD_COND(device, _intr, device_lock_interruptible(_T), _RET == 0) +DEFINE_GUARD_COND(device, _try, device_trylock(_T)) static inline void device_lock_assert(struct device *dev) { diff --git a/include/linux/dibs.h b/include/linux/dibs.h index d3e0777f25ae..0c10c224bcca 100644 --- a/include/linux/dibs.h +++ b/include/linux/dibs.h @@ -261,12 +261,12 @@ struct dibs_dev_ops { * @vlan_id: deprecated, ignored if device does not support vlan * Upon return in addition the following fields will be valid: * @dmb_tok: for usage by remote and local devices and clients - * @cpu_addr: allocated buffer + * @cpu_addr: allocated, zerorized buffer * @idx: dmb index, unique per dibs device * @dma_addr: to be used by device driver,if applicable * - * Allocate a dmb buffer and register it with this device and for this - * client. + * Allocate and zerorize a dmb buffer and register it with this device + * and for this client. * Return: zero on success */ int (*register_dmb)(struct dibs_dev *dev, struct dibs_dmb *dmb, diff --git a/include/linux/dma-fence.h b/include/linux/dma-fence.h index ffa99b930843..dd07d128adc3 100644 --- a/include/linux/dma-fence.h +++ b/include/linux/dma-fence.h @@ -507,7 +507,7 @@ dma_fence_test_signaled_flag(struct dma_fence *fence) * Returns true if the fence was already signaled, false if not. Since this * function doesn't enable signaling, it is not guaranteed to ever return * true if dma_fence_add_callback(), dma_fence_wait() or - * dma_fence_enable_sw_signaling() haven't been called before. + * dma_fence_enable_signaling() haven't been called before. * * This function requires &dma_fence.lock to be held. * diff --git a/include/linux/etherdevice.h b/include/linux/etherdevice.h index df8f88f63a70..1f833ebd71ed 100644 --- a/include/linux/etherdevice.h +++ b/include/linux/etherdevice.h @@ -38,6 +38,34 @@ int fwnode_get_mac_address(struct fwnode_handle *fwnode, char *addr); u32 eth_get_headlen(const struct net_device *dev, const void *data, u32 len); __be16 eth_type_trans(struct sk_buff *skb, struct net_device *dev); + +/** + * eth_type_trans_careful - eth_type_trans() for skbs coming from the stack + * @skb: buffer, possibly with less than ETH_HLEN bytes in its linear area + * @dev: receiving network device + * + * eth_type_trans() expects ETH_HLEN bytes in skb->head, which NIC drivers + * provide. Devices looping skbs from their transmit path back to the + * receive path (loopback, OVS internal ports) get skbs built by the stack, + * whose link-layer header might have been popped by tc or OVS actions. + * + * Sets skb->protocol on success. + * + * Return: SKB_NOT_DROPPED_YET on success, or a drop reason. In the latter + * case, the caller must free @skb. + */ +static inline enum skb_drop_reason +eth_type_trans_careful(struct sk_buff *skb, struct net_device *dev) +{ + enum skb_drop_reason reason = pskb_may_pull_reason(skb, ETH_HLEN); + + if (unlikely(reason)) + return reason; + + skb->protocol = eth_type_trans(skb, dev); + return SKB_NOT_DROPPED_YET; +} + extern const struct header_ops eth_header_ops; int eth_header(struct sk_buff *skb, struct net_device *dev, unsigned short type, diff --git a/include/linux/firewire.h b/include/linux/firewire.h index fd35a6570cd8..9bf26163a614 100644 --- a/include/linux/firewire.h +++ b/include/linux/firewire.h @@ -337,7 +337,6 @@ struct fw_packet { */ fw_packet_callback_t callback; int ack; - struct list_head link; void *driver_data; }; diff --git a/include/linux/fortify-string.h b/include/linux/fortify-string.h index cf841dc71fef..7e7c369e0a6c 100644 --- a/include/linux/fortify-string.h +++ b/include/linux/fortify-string.h @@ -458,10 +458,8 @@ __FORTIFY_INLINE bool fortify_memset_chk(__kernel_size_t size, * __struct_size() vs __member_size() must be captured here to avoid * evaluating argument side-effects further into the macro layers. */ -#ifndef CONFIG_KMSAN #define memset(p, c, s) __fortify_memset_chk(p, c, s, \ __struct_size(p), __member_size(p)) -#endif /* * To make sure the compiler can enforce protection against buffer overflows, diff --git a/include/linux/fs/super_types.h b/include/linux/fs/super_types.h index ecd96aeb1cee..72f4288e16c5 100644 --- a/include/linux/fs/super_types.h +++ b/include/linux/fs/super_types.h @@ -30,7 +30,6 @@ struct mount; struct mtd_info; struct quotactl_ops; struct shrinker; -struct super_dev; struct unicode_map; struct user_namespace; struct workqueue_struct; @@ -132,10 +131,18 @@ struct super_operations { void (*report_error)(const struct fserror_event *event); }; +/* A superblock's claim on a device, see fs/super.c. */ +struct super_dev { + struct hlist_node sd_hash; + struct super_block *sd_sb; + dev_t sd_dev; + unsigned int sd_claims; +}; + struct super_block { struct list_head s_list; /* Keep this first */ dev_t s_dev; /* search index; _not_ kdev_t */ - struct super_dev *s_super_dev; /* sget_fc()'s device table claim */ + struct super_dev s_super_dev; /* claim on s_dev */ unsigned char s_blocksize_bits; unsigned long s_blocksize; loff_t s_maxbytes; /* Max file size */ diff --git a/include/linux/fs_context.h b/include/linux/fs_context.h index 0d6c8a6d7be2..d1727dffecc5 100644 --- a/include/linux/fs_context.h +++ b/include/linux/fs_context.h @@ -150,6 +150,10 @@ extern int vfs_parse_fs_param_source(struct fs_context *fc, struct fs_parameter *param); extern void fc_drop_locked(struct fs_context *fc); +int get_tree_super(struct fs_context *fc, + int (*test)(struct super_block *, struct fs_context *), + int (*fill_super)(struct super_block *sb, + struct fs_context *fc)); extern int get_tree_nodev(struct fs_context *fc, int (*fill_super)(struct super_block *sb, struct fs_context *fc)); diff --git a/include/linux/ftrace.h b/include/linux/ftrace.h index bd76a16a63af..b041d9142d2b 100644 --- a/include/linux/ftrace.h +++ b/include/linux/ftrace.h @@ -416,6 +416,7 @@ void free_ftrace_hash(struct ftrace_hash *hash); struct ftrace_func_entry *add_ftrace_hash_entry_direct(struct ftrace_hash *hash, unsigned long ip, unsigned long direct); void add_ftrace_hash_entry(struct ftrace_hash *hash, struct ftrace_func_entry *entry); +struct ftrace_func_entry *ftrace_lookup_ip(struct ftrace_hash *hash, unsigned long ip); void ftrace_hash_remove(struct ftrace_hash *hash); /* The hash used to know what functions callbacks trace */ diff --git a/include/linux/hrtimer.h b/include/linux/hrtimer.h index 29072d89e5cb..1877beb81d5c 100644 --- a/include/linux/hrtimer.h +++ b/include/linux/hrtimer.h @@ -12,6 +12,7 @@ #ifndef _LINUX_HRTIMER_H #define _LINUX_HRTIMER_H +#include #include #include #include @@ -201,6 +202,29 @@ extern void destroy_hrtimer_on_stack(struct hrtimer *timer); static inline void destroy_hrtimer_on_stack(struct hrtimer *timer) { } #endif +/* + * The cleanup class pairs on-stack setup with debug-object teardown. Callers + * using it must not call destroy_hrtimer_on_stack() manually. + * + * This class provides debug-object teardown, not timer cancellation. Callers + * must ensure that no hrtimer operation can still access the timer before + * leaving the scope. In particular, the timer must no longer be queued and + * any running callback must have completed. + * + * Callers using hrtimer_setup_on_stack() without this class retain + * responsibility for destroying the timer before its backing storage leaves + * scope. + */ +DEFINE_CLASS(hrtimer_on_stack, struct hrtimer *, + destroy_hrtimer_on_stack(_T), + ({ + hrtimer_setup_on_stack(timer, function, clock_id, mode); + timer; + }), + struct hrtimer *timer, + enum hrtimer_restart (*function)(struct hrtimer *), + clockid_t clock_id, enum hrtimer_mode mode) + /* Basic timer operations: */ extern void hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim, u64 range_ns, const enum hrtimer_mode mode); diff --git a/include/linux/i3c/master.h b/include/linux/i3c/master.h index f7ceec2b4477..72065715feee 100644 --- a/include/linux/i3c/master.h +++ b/include/linux/i3c/master.h @@ -536,6 +536,8 @@ struct i3c_master_controller_ops { * Bit 0: SETDASA * Bit 1: SETAASA * All other bits are reserved. + * @instance: Zero-based instance number of the Bus Controller as defined by the + * DisCo specification I3C Target Address (_ADR) Encoding * @wq: freezable workqueue which can be used by master * drivers if they need to postpone operations that need to take place * in a thread context. Typical examples are Hot Join processing which @@ -573,6 +575,7 @@ struct i3c_master_controller { } boardinfo; struct i3c_bus bus; u8 addr_method; + u8 instance; struct workqueue_struct *wq; struct work_struct hj_work; struct work_struct reg_work; diff --git a/include/linux/iomap.h b/include/linux/iomap.h index bc7ae6327dbf..e9b76647784c 100644 --- a/include/linux/iomap.h +++ b/include/linux/iomap.h @@ -500,6 +500,7 @@ sector_t iomap_bmap(struct address_space *mapping, sector_t bno, struct iomap_ioend { struct list_head io_list; /* next ioend in chain */ u16 io_flags; /* IOMAP_IOEND_* */ + u32 io_bvec_offset; /* offset into first bvec */ struct inode *io_inode; /* file being written to */ size_t io_size; /* size of the extent */ atomic_t io_remaining; /* completetion defer count */ @@ -517,6 +518,13 @@ static inline struct iomap_ioend *iomap_ioend_from_bio(struct bio *bio) return container_of(bio, struct iomap_ioend, io_bio); } +#define BVEC_ITER_IOEND(_ioend) \ +{ \ + .bi_sector = (_ioend)->io_sector, \ + .bi_size = (_ioend)->io_size, \ + .bi_offset = (_ioend)->io_bvec_offset, \ +} + struct iomap_writeback_ops { /* * Performs writeback on the passed in range @@ -657,7 +665,8 @@ struct iomap_dio_ops { #define IOMAP_DIO_PARTIAL (1 << 2) /* - * Ensure each bio is aligned to fs block size. + * Ensure every operation, including bio and hole zeroing, is aligned to fs + * block size. * * For filesystems which need to calculate/verify the checksum of each fs * block. Otherwise they may not be able to handle unaligned bios. diff --git a/include/linux/kernel_stat.h b/include/linux/kernel_stat.h index 9ca6c2259dfe..6e252048b5ad 100644 --- a/include/linux/kernel_stat.h +++ b/include/linux/kernel_stat.h @@ -40,6 +40,9 @@ struct kernel_cpustat { seqcount_t idle_sleeptime_seq; u64 idle_entrytime; u64 idle_stealtime[2]; + u64 idle_dyntick_entry; + u64 idle_tick_period; + u64 idle_tick_overlap; #endif u64 cpustat[NR_STATS]; }; @@ -111,7 +114,7 @@ static inline unsigned long kstat_cpu_irqs_sum(unsigned int cpu) #ifdef CONFIG_HAVE_VIRT_CPU_ACCOUNTING_IDLE static inline void kcpustat_dyntick_start(u64 now) { } -static inline void kcpustat_dyntick_stop(u64 now) { } +static inline void kcpustat_dyntick_stop(u64 now, u64 tick_start) { } static inline void kcpustat_irq_enter(u64 now) { } static inline void kcpustat_irq_exit(u64 now) { } static inline bool kcpustat_idle_dyntick(void) { return false; } @@ -132,7 +135,7 @@ static inline u64 kcpustat_field_iowait(int cpu) #else /* !CONFIG_HAVE_VIRT_CPU_ACCOUNTING_IDLE */ extern void kcpustat_dyntick_start(u64 now); -extern void kcpustat_dyntick_stop(u64 now); +extern void kcpustat_dyntick_stop(u64 now, u64 tick_start); extern void kcpustat_irq_enter(u64 now); extern void kcpustat_irq_exit(u64 now); extern u64 kcpustat_field_idle(int cpu); diff --git a/include/linux/kexec.h b/include/linux/kexec.h index 0af8ae4fdd08..aeb74b47c36e 100644 --- a/include/linux/kexec.h +++ b/include/linux/kexec.h @@ -468,6 +468,7 @@ bool kexec_load_permitted(int kexec_image_type); /* flag to track if kexec reboot is in progress */ extern bool kexec_in_progress; +bool kexec_is_in_progress(void); #ifndef page_to_boot_pfn static inline unsigned long page_to_boot_pfn(struct page *page) @@ -544,6 +545,7 @@ static inline void *kimage_map_segment(struct kimage *image, int idx) { return NULL; } static inline void kimage_unmap_segment(void *buffer) { } #define kexec_in_progress false +static inline bool kexec_is_in_progress(void) { return false; } #endif /* CONFIG_KEXEC_CORE */ #ifdef CONFIG_KEXEC_SIG diff --git a/include/linux/leds.h b/include/linux/leds.h index a515f075c29a..d778709f5b1b 100644 --- a/include/linux/leds.h +++ b/include/linux/leds.h @@ -533,6 +533,9 @@ void led_trigger_blink_oneshot(struct led_trigger *trigger, void led_trigger_set_default(struct led_classdev *led_cdev); int led_trigger_set(struct led_classdev *led_cdev, struct led_trigger *trigger); void led_trigger_remove(struct led_classdev *led_cdev); +void led_trigger_remove_hw_control(struct led_classdev *led_cdev); + +bool led_trigger_is_hw_controlled(struct led_classdev *led_cdev); static inline void led_set_trigger_data(struct led_classdev *led_cdev, void *trigger_data) @@ -584,6 +587,13 @@ static inline int led_trigger_set(struct led_classdev *led_cdev, } static inline void led_trigger_remove(struct led_classdev *led_cdev) {} +static inline void led_trigger_remove_hw_control(struct led_classdev *led_cdev) {} + +static inline bool led_trigger_is_hw_controlled(struct led_classdev *led_cdev) +{ + return false; +} + static inline void led_set_trigger_data(struct led_classdev *led_cdev) {} static inline void *led_get_trigger_data(struct led_classdev *led_cdev) { diff --git a/include/linux/mfd/da9150/core.h b/include/linux/mfd/da9150/core.h index d116d5f3ef56..369698036d1a 100644 --- a/include/linux/mfd/da9150/core.h +++ b/include/linux/mfd/da9150/core.h @@ -65,6 +65,7 @@ struct da9150 { struct regmap_irq_chip_data *regmap_irq_data; int irq; int irq_base; + bool irq_wake_enabled; }; /* Device I/O - Query Interface for FG and standard register access */ diff --git a/include/linux/mm.h b/include/linux/mm.h index dd09c438fa23..cfdf0e303956 100644 --- a/include/linux/mm.h +++ b/include/linux/mm.h @@ -622,7 +622,7 @@ enum { #define VMA_LOCKED_MASK mk_vma_flags(VMA_LOCKED_BIT, VMA_LOCKONFAULT_BIT) /* These flags can be updated atomically via VMA/mmap read lock. */ -#define VM_ATOMIC_SET_ALLOWED VM_MAYBE_GUARD +#define VMA_ATOMIC_SET_ALLOWED mk_vma_flags(VMA_MAYBE_GUARD_BIT) /* Arch-specific flags to clear when updating VM flags on protection change */ #ifndef VM_ARCH_CLEAR @@ -1019,22 +1019,6 @@ static inline void vm_flags_reset(struct vm_area_struct *vma, vm_flags_init(vma, flags); } -static inline void vma_flags_reset_once(struct vm_area_struct *vma, - vma_flags_t *flags) -{ - const unsigned long word = flags->__vma_flags[0]; - - /* It is assumed only the first system word must be written once. */ - vma_flags_overwrite_word_once(&vma->flags, word); - /* The remainder can be copied normally. */ - if (NUM_VMA_FLAG_BITS > BITS_PER_LONG) { - unsigned long *dst = &vma->flags.__vma_flags[1]; - const unsigned long *src = &flags->__vma_flags[1]; - - bitmap_copy(dst, src, NUM_VMA_FLAG_BITS - BITS_PER_LONG); - } -} - static inline void vm_flags_set(struct vm_area_struct *vma, vm_flags_t flags) { @@ -1071,48 +1055,6 @@ static inline void vm_flags_mod(struct vm_area_struct *vma, __vm_flags_mod(vma, set, clear); } -static __always_inline bool __vma_atomic_valid_flag(struct vm_area_struct *vma, - vma_flag_t bit) -{ - const vm_flags_t mask = BIT((__force int)bit); - - /* Only specific flags are permitted */ - if (WARN_ON_ONCE(!(mask & VM_ATOMIC_SET_ALLOWED))) - return false; - - return true; -} - -/* - * Set VMA flag atomically. Requires only VMA/mmap read lock. Only specific - * valid flags are allowed to do this. - */ -static __always_inline void vma_set_atomic_flag(struct vm_area_struct *vma, - vma_flag_t bit) -{ - unsigned long *bitmap = vma->flags.__vma_flags; - - vma_assert_stabilised(vma); - if (__vma_atomic_valid_flag(vma, bit)) - set_bit((__force int)bit, bitmap); -} - -/* - * Test for VMA flag atomically. Requires no locks. Only specific valid flags - * are allowed to do this. - * - * This is necessarily racey, so callers must ensure that serialisation is - * achieved through some other means, or that races are permissible. - */ -static __always_inline bool vma_test_atomic_flag(struct vm_area_struct *vma, - vma_flag_t bit) -{ - if (__vma_atomic_valid_flag(vma, bit)) - return test_bit((__force int)bit, &vma->vm_flags); - - return false; -} - /* Set an individual VMA flag in flags, non-atomically. */ static __always_inline void vma_flags_set_flag(vma_flags_t *flags, vma_flag_t bit) @@ -1334,34 +1276,24 @@ static __always_inline vma_flags_t vma_flags_diff_pair(const vma_flags_t *flags, return dst; } -/* Determine if flags and flags_other have precisely the same flags set. */ +/* + * Determine if flags and flags_other have precisely the same flags set, + * excluding atomic VMA flags. + */ static __always_inline bool vma_flags_same_pair(const vma_flags_t *flags, - const vma_flags_t *flags_other) + const vma_flags_t *flags_other) { - const unsigned long *bitmap = flags->__vma_flags; - const unsigned long *bitmap_other = flags_other->__vma_flags; - - return bitmap_equal(bitmap, bitmap_other, NUM_VMA_FLAG_BITS); -} + vma_flags_t diff = vma_flags_diff_pair(flags, flags_other); -/* Determine if flags and flags_other have precisely the same flags set. */ -static __always_inline bool vma_flags_same_mask(const vma_flags_t *flags, - vma_flags_t flags_other) -{ - const unsigned long *bitmap = flags->__vma_flags; - const unsigned long *bitmap_other = flags_other.__vma_flags; + /* + * Atomic VMA flags may be set concurrently under the VMA read lock, so + * are disregarded for equality testing purposes. + */ + vma_flags_clear_mask(&diff, VMA_ATOMIC_SET_ALLOWED); - return bitmap_equal(bitmap, bitmap_other, NUM_VMA_FLAG_BITS); + return vma_flags_empty(&diff); } -/* - * Helper macro to determine if only the specific flags are set, e.g.: - * - * if (vma_flags_same(&flags, VMA_WRITE_BIT) { ... } - */ -#define vma_flags_same(flags, ...) \ - vma_flags_same_mask(flags, mk_vma_flags(__VA_ARGS__)) - /* * Test whether a specific flag in the VMA is set, e.g.: * @@ -1468,6 +1400,78 @@ static __always_inline void vma_clear_flags_mask(struct vm_area_struct *vma, #define vma_clear_flags(vma, ...) \ vma_clear_flags_mask(vma, mk_vma_flags(__VA_ARGS__)) +static __always_inline bool __vma_atomic_valid_flag(struct vm_area_struct *vma, + vma_flag_t bit) +{ + const vma_flags_t mask = VMA_ATOMIC_SET_ALLOWED; + + /* Is this flag allowed to be set atomically? */ + if (WARN_ON_ONCE(!vma_flags_test(&mask, bit))) + return false; + + return true; +} + +/* + * Set VMA flag atomically. Requires only VMA/mmap read lock. Only specific + * valid flags are allowed to do this. + */ +static __always_inline void vma_set_atomic_flag(struct vm_area_struct *vma, + vma_flag_t bit) +{ + unsigned long *bitmap = vma->flags.__vma_flags; + + vma_assert_stabilised(vma); + if (__vma_atomic_valid_flag(vma, bit)) + set_bit((__force int)bit, bitmap); +} + +/* + * Test for VMA flag atomically. Requires no locks. Only specific valid flags + * are allowed to do this. + * + * This is necessarily racey, so callers must ensure that serialisation is + * achieved through some other means, or that races are permissible. + */ +static __always_inline bool vma_test_atomic_flag(struct vm_area_struct *vma, + vma_flag_t bit) +{ + if (__vma_atomic_valid_flag(vma, bit)) + return test_bit((__force int)bit, &vma->vm_flags); + + return false; +} + +/* + * Overwrite the VMA's flags with new ones, preserving atomic VMA flags in the + * process. The write is done once and once only. + */ +static inline void vma_overwrite_flags(struct vm_area_struct *vma, + vma_flags_t new_flags) +{ + vma_flags_t atomic; + + vma_assert_write_locked(vma); + + /* + * Preserve the VMA's atomic flags, which are kept stable by the VMA + * write lock. + */ + atomic = vma_flags_and_mask(&vma->flags, VMA_ATOMIC_SET_ALLOWED); + vma_flags_clear_mask(&new_flags, VMA_ATOMIC_SET_ALLOWED); + vma_flags_set_mask(&new_flags, atomic); + + /* It is assumed only the first system word must be written once. */ + vma_flags_overwrite_word_once(&vma->flags, new_flags.__vma_flags[0]); + /* The remainder can be copied normally. */ + if (NUM_VMA_FLAG_BITS > BITS_PER_LONG) { + unsigned long *dst = &vma->flags.__vma_flags[1]; + const unsigned long *src = &new_flags.__vma_flags[1]; + + bitmap_copy(dst, src, NUM_VMA_FLAG_BITS - BITS_PER_LONG); + } +} + /* * Test whether a specific VMA flag is set in a VMA descriptor, e.g.: * diff --git a/include/linux/mm_types.h b/include/linux/mm_types.h index f3e5a2fadbe5..44e663981837 100644 --- a/include/linux/mm_types.h +++ b/include/linux/mm_types.h @@ -955,15 +955,19 @@ struct vm_area_struct { * Can only be written (using WRITE_ONCE()) while holding both: * - mmap_lock (in write mode) * - vm_refcnt bit at VM_REFCNT_EXCLUDE_READERS_FLAG is set + * The one exception is __mm_reset_vma_seqcounts(), which stores zero + * (an even value, which can never indicate a write lock) under the + * mmap write lock alone once the mm seqcount has wrapped, so a reader + * holding only vm_refcnt may observe the value change from odd to zero. * Can be read reliably while holding one of: * - mmap_lock (in read or write mode) - * - vm_refcnt bit at VM_REFCNT_EXCLUDE_READERS_BIT is set or vm_refcnt > 1 + * - vm_refcnt bit at VM_REFCNT_EXCLUDE_READERS_BIT is set * Can be read unreliably (using READ_ONCE()) for pessimistic bailout * while holding nothing (except RCU to keep the VMA struct allocated). * - * This sequence counter is explicitly allowed to overflow; sequence - * counter reuse can only lead to occasional unnecessary use of the - * slowpath. + * Assigned the (odd) mm seqcount on write lock and not updated on + * unlock, so a stale value would alias the mm seqcount again 2^31 write + * lock/unlock cycles later. The reset described above prevents this. */ unsigned int vm_lock_seq; #endif diff --git a/include/linux/mmap_lock.h b/include/linux/mmap_lock.h index b8a13b8d36a4..c7f4c8b48882 100644 --- a/include/linux/mmap_lock.h +++ b/include/linux/mmap_lock.h @@ -17,6 +17,13 @@ extern int rcuwait_wake_up(struct rcuwait *w); #define MMAP_LOCK_INITIALIZER(name) \ .mmap_lock = __RWSEM_INITIALIZER((name).mmap_lock), +/* Tie a VMA iterator to mm write lock state at iterator initialisation. */ +struct vma_rcu_iter { + struct mm_struct *mm; + struct vma_iterator *vmi; + unsigned int mm_wr_seq; +}; + DECLARE_TRACEPOINT(mmap_lock_start_locking); DECLARE_TRACEPOINT(mmap_lock_acquire_returned); DECLARE_TRACEPOINT(mmap_lock_released); @@ -156,7 +163,7 @@ static inline void vma_lock_init(struct vm_area_struct *vma, bool reset_refcnt) #endif if (reset_refcnt) refcount_set(&vma->vm_refcnt, 0); - vma->vm_lock_seq = UINT_MAX; + vma->vm_lock_seq = 0; } /* @@ -230,9 +237,10 @@ static inline void vma_refcount_put(struct vm_area_struct *vma) } /* - * Use only while holding mmap read lock which guarantees that locking will not - * fail (nobody can concurrently write-lock the vma). vma_start_read() should - * not be used in such cases because it might fail due to mm_lock_seq overflow. + * Use only while holding mmap read lock which guarantees that vma lock is not + * contended (nobody can concurrently write-lock the vma). vma_start_read() need + * not be used in such cases, as the mmap lock already excludes VMA writers so + * its sequence number checks are redundant. * This functionality is used to obtain vma read lock and drop the mmap read lock. */ static inline bool vma_start_read_locked_nested(struct vm_area_struct *vma, int subclass) @@ -249,9 +257,10 @@ static inline bool vma_start_read_locked_nested(struct vm_area_struct *vma, int } /* - * Use only while holding mmap read lock which guarantees that locking will not - * fail (nobody can concurrently write-lock the vma). vma_start_read() should - * not be used in such cases because it might fail due to mm_lock_seq overflow. + * Use only while holding mmap read lock which guarantees that vma lock is not + * contended (nobody can concurrently write-lock the vma). vma_start_read() need + * not be used in such cases, as the mmap lock already excludes VMA writers so + * its sequence number checks are redundant. * This functionality is used to obtain vma read lock and drop the mmap read lock. */ static inline bool vma_start_read_locked(struct vm_area_struct *vma) @@ -480,9 +489,8 @@ struct vm_area_struct *lock_vma_under_rcu(struct mm_struct *mm, * Returns either a valid locked VMA, NULL if no more VMAs or -EINTR if the * process was interrupted. */ -struct vm_area_struct *lock_next_vma(struct mm_struct *mm, - struct vma_iterator *iter, - unsigned long address); +struct vm_area_struct *lock_next_vma(struct vma_rcu_iter *rvmi, + unsigned long from_addr); #else /* CONFIG_PER_VMA_LOCK */ @@ -532,6 +540,16 @@ static inline void vma_assert_stabilised(struct vm_area_struct *vma) #endif /* CONFIG_PER_VMA_LOCK */ +static inline void vma_rcu_iter_init(struct vma_rcu_iter *rvmi, + struct mm_struct *mm, struct vma_iterator *vmi, + unsigned long addr) +{ + vma_iter_init(vmi, mm, addr); + rvmi->mm = mm; + rvmi->vmi = vmi; + rvmi->mm_wr_seq = UINT_MAX; /* Start odd so changed by default. */ +} + static inline void vma_assert_can_modify(struct vm_area_struct *vma) { if (vma_is_attached(vma)) @@ -566,6 +584,10 @@ static inline int __must_check mmap_write_lock_killable(struct mm_struct *mm) return ret; } +#ifdef CONFIG_PER_VMA_LOCK +void __mm_reset_vma_seqcounts(struct mm_struct *mm); +#endif + /* * Drop all currently-held per-VMA locks. * This is called from the mmap_lock implementation directly before releasing @@ -578,6 +600,18 @@ static inline void vma_end_write_all(struct mm_struct *mm) { mmap_assert_write_locked(mm); mm_lock_seqcount_end(mm); + +#ifdef CONFIG_PER_VMA_LOCK + /* + * VMA seqcounts are not updated on unlock, so once the mm seqcount has + * wrapped, any VMA still carrying a sequence number from before the + * wrap would satisfy __is_vma_write_locked() when that number comes + * round again, and readers would not be excluded. Reset every VMA's + * seqcount so that no stale value survives the wrap. + */ + if (unlikely(!mm->mm_lock_seq.sequence)) + __mm_reset_vma_seqcounts(mm); +#endif } static inline void mmap_write_unlock(struct mm_struct *mm) diff --git a/include/linux/mtd/spinand.h b/include/linux/mtd/spinand.h index 5f4c00ae72a7..0bd3f30ea57e 100644 --- a/include/linux/mtd/spinand.h +++ b/include/linux/mtd/spinand.h @@ -399,7 +399,7 @@ struct spinand_devid { }; /** - * struct manufacurer_ops - SPI NAND manufacturer specific operations + * struct spinand_manufacturer_ops - SPI NAND manufacturer specific operations * @init: initialize a SPI NAND device * @cleanup: cleanup a SPI NAND device * diff --git a/include/linux/netdevice.h b/include/linux/netdevice.h index 3e64af0b932d..1fb51c576758 100644 --- a/include/linux/netdevice.h +++ b/include/linux/netdevice.h @@ -433,6 +433,7 @@ enum { NAPI_STATE_SCHED_THREADED, /* Napi is currently scheduled in threaded mode */ NAPI_STATE_HAS_NOTIFIER, /* Napi has an IRQ notifier */ NAPI_STATE_THREADED_BUSY_POLL, /* The threaded NAPI poller will busy poll */ + NAPI_STATE_DISABLED, /* NAPI is disabled */ }; enum { @@ -448,6 +449,7 @@ enum { NAPIF_STATE_SCHED_THREADED = BIT(NAPI_STATE_SCHED_THREADED), NAPIF_STATE_HAS_NOTIFIER = BIT(NAPI_STATE_HAS_NOTIFIER), NAPIF_STATE_THREADED_BUSY_POLL = BIT(NAPI_STATE_THREADED_BUSY_POLL), + NAPIF_STATE_DISABLED = BIT(NAPI_STATE_DISABLED), }; enum gro_result { @@ -2545,6 +2547,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/nfslocalio.h b/include/linux/nfslocalio.h index 3d91043254e6..1a8cfb045abc 100644 --- a/include/linux/nfslocalio.h +++ b/include/linux/nfslocalio.h @@ -8,8 +8,10 @@ #if IS_ENABLED(CONFIG_NFS_LOCALIO) +#include #include #include +#include #include #include #include @@ -28,6 +30,11 @@ struct nfs_file_localio; typedef struct { uuid_t uuid; unsigned nfs3_localio_probe_count; + /* Owner reference plus temporary references held by nfs_common */ + refcount_t refs; + struct completion released; + /* Namespace registration order, protected by list_lock */ + u64 seq; /* this struct is over a cacheline, avoid bouncing */ spinlock_t ____cacheline_aligned lock; struct list_head list; @@ -46,6 +53,7 @@ void nfs_uuid_is_local(const uuid_t *, struct list_head *, spinlock_t *, void nfs_localio_enable_client(struct nfs_client *clp); void nfs_localio_disable_client(struct nfs_client *clp); +void nfs_localio_free_client(struct nfs_client *clp); void nfs_localio_invalidate_clients(struct list_head *nn_local_clients, spinlock_t *nn_local_clients_lock); @@ -118,6 +126,10 @@ static inline void nfs_localio_disable_client(struct nfs_client *clp) { } +static inline void nfs_localio_free_client(struct nfs_client *clp) +{ +} + #endif /* CONFIG_NFS_LOCALIO */ #endif /* __LINUX_NFSLOCALIO_H */ diff --git a/include/linux/pci.h b/include/linux/pci.h index 272378dd8973..97a1096d5a8a 100644 --- a/include/linux/pci.h +++ b/include/linux/pci.h @@ -1916,12 +1916,14 @@ static inline int pci_irqd_intx_xlate(struct irq_domain *d, #ifdef CONFIG_PCIEPORTBUS extern bool pcie_ports_disabled; extern bool pcie_ports_native; +extern bool pcie_ports_dpc_native; int pcie_set_target_speed(struct pci_dev *port, enum pci_bus_speed speed_req, bool use_lt); #else #define pcie_ports_disabled true #define pcie_ports_native false +#define pcie_ports_dpc_native false static inline int pcie_set_target_speed(struct pci_dev *port, enum pci_bus_speed speed_req, diff --git a/include/linux/platform_data/dmtimer-omap.h b/include/linux/platform_data/dmtimer-omap.h index 726d89143842..b78ee4676b98 100644 --- a/include/linux/platform_data/dmtimer-omap.h +++ b/include/linux/platform_data/dmtimer-omap.h @@ -57,6 +57,8 @@ struct dmtimer_platform_data { u32 timer_errata; int (*get_context_loss_count)(struct device *); const struct omap_dm_timer_ops *timer_ops; + /* always-on timers can be used for clocksource/clockevent */ + bool system_timer_capable; }; #endif /* __PLATFORM_DATA_DMTIMER_OMAP_H__ */ diff --git a/include/linux/platform_data/mipi-i3c-hci.h b/include/linux/platform_data/mipi-i3c-hci.h index ab7395f455f9..6f61d8a02378 100644 --- a/include/linux/platform_data/mipi-i3c-hci.h +++ b/include/linux/platform_data/mipi-i3c-hci.h @@ -3,13 +3,17 @@ #define INCLUDE_PLATFORM_DATA_MIPI_I3C_HCI_H #include +#include /** * struct mipi_i3c_hci_platform_data - Platform-dependent data for mipi_i3c_hci * @base_regs: Register set base address (to support multi-bus instances) + * @instance: Zero-based instance number of the Bus Controller as defined by the + * DisCo specification I3C Target Address (_ADR) Encoding */ struct mipi_i3c_hci_platform_data { void __iomem *base_regs; + u8 instance; }; #endif diff --git a/include/linux/platform_data/x86/asus-wmi.h b/include/linux/platform_data/x86/asus-wmi.h index b5ed8c83ace1..289be6ac7335 100644 --- a/include/linux/platform_data/x86/asus-wmi.h +++ b/include/linux/platform_data/x86/asus-wmi.h @@ -140,8 +140,9 @@ #define ASUS_WMI_DEVID_APU_MEM 0x000600C1 -#define ASUS_WMI_DEVID_DGPU_BASE_TGP 0x00120099 +#define ASUS_WMI_DEVID_DGPU_POWER_STATE 0x00120097 #define ASUS_WMI_DEVID_DGPU_SET_TGP 0x00120098 +#define ASUS_WMI_DEVID_DGPU_BASE_TGP 0x00120099 /* gpu mux switch, 0 = dGPU, 1 = Optimus */ #define ASUS_WMI_DEVID_GPU_MUX 0x00090016 diff --git a/include/linux/ppp_channel.h b/include/linux/ppp_channel.h index 2f63e9a6cc88..15bc3aa4f171 100644 --- a/include/linux/ppp_channel.h +++ b/include/linux/ppp_channel.h @@ -43,6 +43,7 @@ struct ppp_channel { void *ppp; /* opaque to channel */ int speed; /* transfer rate (bytes/second) */ bool direct_xmit; /* no qdisc, xmit directly */ + bool xmit_offload; /* accepts GSO and CHECKSUM_PARTIAL skbs */ }; #ifdef __KERNEL__ diff --git a/include/linux/quotaops.h b/include/linux/quotaops.h index f9c0f9d7c9d9..bbe22c22439e 100644 --- a/include/linux/quotaops.h +++ b/include/linux/quotaops.h @@ -40,6 +40,7 @@ void __quota_error(struct super_block *sb, const char *func, /* * declaration of quota_function calls in kernel. */ +void dquot_cache_init(void); int dquot_initialize(struct inode *inode); bool dquot_initialize_needed(struct inode *inode); void dquot_drop(struct inode *inode); @@ -206,6 +207,10 @@ static inline int sb_has_quota_active(struct super_block *sb, int type) return 0; } +static inline void dquot_cache_init(void) +{ +} + static inline int dquot_initialize(struct inode *inode) { return 0; diff --git a/include/linux/rcuref.h b/include/linux/rcuref.h index 2fb2af6d9824..01fee161b67c 100644 --- a/include/linux/rcuref.h +++ b/include/linux/rcuref.h @@ -34,7 +34,7 @@ static inline void rcuref_init(rcuref_t *ref, unsigned int cnt) * indicate that it is safe to schedule the object, protected by this reference * counter, for deconstruction. * If you want to know if the reference counter has been marked DEAD (as - * signaled by rcuref_put()) please use rcuread_is_dead(). + * signaled by rcuref_put()) please use rcuref_is_dead(). */ static inline unsigned int rcuref_read(rcuref_t *ref) { diff --git a/include/linux/sched.h b/include/linux/sched.h index 78bfc0e32e56..09d90f5edd2b 100644 --- a/include/linux/sched.h +++ b/include/linux/sched.h @@ -2105,10 +2105,9 @@ static inline int test_tsk_thread_flag(struct task_struct *tsk, int flag) static inline void set_tsk_need_resched(struct task_struct *tsk) { - if (tracepoint_enabled(sched_set_need_resched_tp) && - !test_tsk_thread_flag(tsk, TIF_NEED_RESCHED)) + if (!test_and_set_tsk_thread_flag(tsk, TIF_NEED_RESCHED) && + tracepoint_enabled(sched_set_need_resched_tp)) __trace_set_need_resched(tsk, TIF_NEED_RESCHED); - set_tsk_thread_flag(tsk,TIF_NEED_RESCHED); } static inline void clear_tsk_need_resched(struct task_struct *tsk) diff --git a/include/linux/sched/ext.h b/include/linux/sched/ext.h index 36c04797436c..81a29b3c0e5d 100644 --- a/include/linux/sched/ext.h +++ b/include/linux/sched/ext.h @@ -104,6 +104,7 @@ enum scx_ent_flags { SCX_TASK_SUB_INIT = 1 << 4, /* task being initialized for a sub sched */ SCX_TASK_IMMED = 1 << 5, /* task is on local DSQ with %SCX_ENQ_IMMED */ SCX_TASK_PROTECTED = 1 << 6, /* slice and DSQ head position protected */ + SCX_TASK_RUN_TRACKED = 1 << 7, /* task is in an ops.running()/stopping() session */ /* * Bits 8 to 10 are used to carry task state: diff --git a/include/linux/seq_buf.h b/include/linux/seq_buf.h index 9f2839e73f8a..f5a350347bc5 100644 --- a/include/linux/seq_buf.h +++ b/include/linux/seq_buf.h @@ -155,11 +155,11 @@ static inline void seq_buf_commit(struct seq_buf *s, int num) * * Removes the last written character to the seq_buf @s. * - * Returns the last character or -1 if it is empty. + * Returns the last character, or -1 if @s is empty or has overflowed. */ static inline int seq_buf_pop(struct seq_buf *s) { - if (!s->len) + if (!s->len || seq_buf_has_overflowed(s)) return -1; s->len--; diff --git a/include/linux/skbuff.h b/include/linux/skbuff.h index a3ff380d43f0..707082f68f21 100644 --- a/include/linux/skbuff.h +++ b/include/linux/skbuff.h @@ -633,9 +633,9 @@ struct skb_shared_info { * * Transport layers send out clones of payload skbs they hold for * retransmissions. To allow lower layers of the stack to prepend their headers - * we split &skb_shared_info.dataref into two halves. - * The lower 16 bits count the overall number of references. - * The higher 16 bits indicate how many of the references are payload-only. + * we split &skb_shared_info.dataref into two parts. + * The lower 30 bits count the overall number of references. + * Bit 30 indicates whether one of the references is payload-only. * skb_header_cloned() checks if skb is allowed to add / write the headers. * * The creator of the skb (e.g. TCP) marks its skb as &sk_buff.nohdr @@ -655,7 +655,7 @@ struct skb_shared_info { * Having multiple payload-only skbs with different lengths of hdr_len is not * possible. The payload-only skbs should never leave their owner. */ -#define SKB_DATAREF_SHIFT 16 +#define SKB_DATAREF_SHIFT 30 #define SKB_DATAREF_MASK ((1 << SKB_DATAREF_SHIFT) - 1) @@ -1036,8 +1036,6 @@ struct sk_buff { __u16 tc_index; /* traffic control index */ #endif - u16 alloc_cpu; - union { __wsum csum; struct { @@ -1088,6 +1086,8 @@ struct sk_buff { ); /* end headers group */ + u16 alloc_cpu; + /* These elements must be at the end, see alloc_skb() for details. */ sk_buff_data_t tail; sk_buff_data_t end; diff --git a/include/linux/soc/ti/k3-ringacc.h b/include/linux/soc/ti/k3-ringacc.h index 39b022b92598..7b7fc237c08f 100644 --- a/include/linux/soc/ti/k3-ringacc.h +++ b/include/linux/soc/ti/k3-ringacc.h @@ -57,13 +57,13 @@ struct k3_ringacc; struct k3_ring; /** - * enum k3_ring_cfg - RA ring configuration structure + * struct k3_ring_cfg - RA ring configuration structure * * @size: Ring size, number of elements * @elm_size: Ring element size * @mode: Ring operational mode * @flags: Ring configuration flags. Possible values: - * @K3_RINGACC_RING_SHARED: when set allows to request the same ring + * %K3_RINGACC_RING_SHARED: when set allows to request the same ring * few times. It's usable when the same ring is used as Free Host PD ring * for different flows, for example. * Note: Locking should be done by consumer if required @@ -88,11 +88,10 @@ struct k3_ring_cfg { /** * of_k3_ringacc_get_by_phandle - find a RA by phandle property * @np: device node - * @propname: property name containing phandle on RA node + * @property: property name containing phandle on RA node * - * Returns pointer on the RA - struct k3_ringacc - * or -ENODEV if not found, - * or -EPROBE_DEFER if not yet registered + * Return: Pointer to the RA, or ERR_PTR(-ENODEV) if the phandle cannot + * be resolved, or ERR_PTR(-EPROBE_DEFER) if the RA is not yet registered. */ struct k3_ringacc *of_k3_ringacc_get_by_phandle(struct device_node *np, const char *property); @@ -103,10 +102,8 @@ struct k3_ringacc *of_k3_ringacc_get_by_phandle(struct device_node *np, * k3_ringacc_request_ring - request ring from ringacc * @ringacc: pointer on ringacc * @id: ring id or K3_RINGACC_RING_ID_ANY for any general purpose ring - * @flags: - * @K3_RINGACC_RING_USE_PROXY: if set - proxy will be allocated and - * used to access ring memory. Sopported only for rings in - * Message/Credentials/Queue mode. + * @flags: Set %K3_RINGACC_RING_USE_PROXY to allocate a proxy for + * accessing ring memory in Message mode. * * Returns pointer on the Ring - struct k3_ring * or NULL in case of failure. @@ -126,8 +123,9 @@ int k3_ringacc_request_rings_pair(struct k3_ringacc *ringacc, */ void k3_ringacc_ring_reset(struct k3_ring *ring); /** - * k3_ringacc_ring_reset - ring reset for DMA rings + * k3_ringacc_ring_reset_dma - ring reset for DMA rings * @ring: pointer on Ring + * @occ: occupancy used by the DMA reset quirk, or zero to read it from hardware * * Resets ring internal state ((hw)occ, (hw)idx). Should be used for rings * which are read by K3 UDMA, like TX or Free Host PD rings. @@ -217,8 +215,8 @@ int k3_ringacc_ring_push(struct k3_ring *ring, void *elem); * @ring: pointer on ring * @elem: pointer on ring element buffer * - * Push one ring element from the ring head. Size of the ring element is - * determined by ring configuration &struct k3_ring_cfg elm_size.. + * Pop one ring element from the ring head. Size of the ring element is + * determined by ring configuration &struct k3_ring_cfg elm_size. * * Returns 0 on success, errno otherwise. */ @@ -242,7 +240,7 @@ int k3_ringacc_ring_push_head(struct k3_ring *ring, void *elem); * @ring: pointer on ring * @elem: pointer on ring element buffer * - * Push one ring element from the ring tail. Size of the ring element is + * Pop one ring element from the ring tail. Size of the ring element is * determined by ring configuration &struct k3_ring_cfg elm_size. * * Returns 0 on success, errno otherwise. @@ -256,7 +254,10 @@ u32 k3_ringacc_get_tisci_dev_id(struct k3_ring *ring); struct ti_sci_handle; /** - * struct struct k3_ringacc_init_data - Initialization data for DMA rings + * struct k3_ringacc_init_data - Initialization data for DMA rings + * @tisci: TI SCI firmware handle + * @tisci_dev_id: TI SCI device ID of the DMA controller + * @num_rings: Total number of available rings */ struct k3_ringacc_init_data { const struct ti_sci_handle *tisci; diff --git a/include/linux/sunrpc/svc_rdma.h b/include/linux/sunrpc/svc_rdma.h index 76aa5ec4ab40..5ccb13bf906f 100644 --- a/include/linux/sunrpc/svc_rdma.h +++ b/include/linux/sunrpc/svc_rdma.h @@ -142,7 +142,7 @@ enum { #define RPCSVC_MAXPAYLOAD_RDMA RPCSVC_MAXPAYLOAD /** - * svc_rdma_send_cid_init - Initialize a Receive Queue completion ID + * svc_rdma_recv_cid_init - Initialize a Receive Queue completion ID * @rdma: controlling transport * @cid: completion ID to initialize */ diff --git a/include/linux/trace_seq.h b/include/linux/trace_seq.h index 697d619aafdc..7174ebf3f015 100644 --- a/include/linux/trace_seq.h +++ b/include/linux/trace_seq.h @@ -86,7 +86,10 @@ static inline bool trace_seq_has_overflowed(struct trace_seq *s) * * Removes the last written character to the trace_seq @s. * - * Returns the last character or -1 if it is empty. + * Returns the last character, or -1 if the underlying seq_buf is empty or + * has overflowed. Note that only that buffer is consulted: a @s marked + * full by a write that did not fit, which trace_seq_has_overflowed() + * reports as overflowed, still pops the last character written. */ static inline int trace_seq_pop(struct trace_seq *s) { diff --git a/include/linux/userfaultfd_k.h b/include/linux/userfaultfd_k.h index 4c0924c73166..170a5cbce9e9 100644 --- a/include/linux/userfaultfd_k.h +++ b/include/linux/userfaultfd_k.h @@ -167,22 +167,12 @@ static inline bool is_mergeable_vm_userfaultfd_ctx(struct vm_area_struct *vma, } /* - * Never enable huge pmd sharing on some uffd registered vmas: - * - * - VM_UFFD_WP and VM_UFFD_RWP VMAs, because the write protect / access - * tracking information is per pgtable entry. - * - * - VM_UFFD_MINOR VMAs, because otherwise we would never get minor faults for - * VMAs which share huge pmds. (If you have two mappings to the same - * underlying pages, and fault in the non-UFFD-registered one with a write, - * with huge pmd sharing this would *also* setup the second UFFD-registered - * mapping, and we'd not get minor faults.) + * Never enable huge pmd sharing on userfaultfd registered VMAs, because + * userfaultfd state can be tracked per VMA or per page table entry. */ static inline bool uffd_disable_huge_pmd_share(struct vm_area_struct *vma) { - return vma_test_any_mask(vma, - mk_vma_flags_from_masks(VMA_UFFD_WP, VMA_UFFD_RWP, - VMA_UFFD_MINOR)); + return vma->vm_userfaultfd_ctx.ctx; } /* diff --git a/include/linux/vfio_pci_core.h b/include/linux/vfio_pci_core.h index 9a1674c152aa..2f3fa2787737 100644 --- a/include/linux/vfio_pci_core.h +++ b/include/linux/vfio_pci_core.h @@ -8,6 +8,7 @@ * Author: Tom Lyon, pugs@cisco.com */ +#include #include #include #include @@ -16,6 +17,7 @@ #include #include #include +#include #ifndef VFIO_PCI_CORE_H #define VFIO_PCI_CORE_H @@ -168,7 +170,6 @@ int vfio_pci_core_init_dev(struct vfio_device *core_vdev); void vfio_pci_core_release_dev(struct vfio_device *core_vdev); int vfio_pci_core_register_device(struct vfio_pci_core_device *vdev); void vfio_pci_core_unregister_device(struct vfio_pci_core_device *vdev); -extern const struct pci_error_handlers vfio_pci_core_err_handlers; int vfio_pci_core_sriov_configure(struct vfio_pci_core_device *vdev, int nr_virtfn); long vfio_pci_core_ioctl(struct vfio_device *core_vdev, unsigned int cmd, @@ -193,8 +194,6 @@ int vfio_pci_core_match_token_uuid(struct vfio_device *core_vdev, int vfio_pci_core_enable(struct vfio_pci_core_device *vdev); void vfio_pci_core_disable(struct vfio_pci_core_device *vdev); void vfio_pci_core_finish_enable(struct vfio_pci_core_device *vdev); -pci_ers_result_t vfio_pci_core_aer_err_detected(struct pci_dev *pdev, - pci_channel_state_t state); ssize_t vfio_pci_core_do_io_rw(struct vfio_pci_core_device *vdev, bool test_mem, void __iomem *io, char __user *buf, loff_t off, size_t count, size_t x_start, @@ -260,4 +259,40 @@ vfio_pci_core_get_iomap(struct vfio_pci_core_device *vdev, unsigned int bar) int vfio_pci_dma_buf_iommufd_map(struct dma_buf_attachment *attachment, struct phys_vec *phys); +int vfio_pci_core_runtime_suspend(struct vfio_pci_core_device *vdev); +int vfio_pci_core_runtime_resume(struct vfio_pci_core_device *vdev); +pci_ers_result_t vfio_pci_core_aer_err_detected(struct vfio_pci_core_device *vdev); + +/* + * Per-driver PM/AER trampolines. driver_data points to the driver's private + * structure, which embeds a struct vfio_pci_core_device. + * + * @name: prefix for _pm_ops and _aer_err_detected + * @drv_type: type of the driver's private structure, including struct + * @member: member containing the struct vfio_pci_core_device + */ +#define VFIO_PCI_CORE_DEFINE_CALLBACKS(name, drv_type, member) \ +static int __maybe_unused name##_pm_suspend(struct device *dev) \ +{ \ + drv_type *drvdata = dev_get_drvdata(dev); \ + \ + return vfio_pci_core_runtime_suspend(&drvdata->member); \ +} \ +static int __maybe_unused name##_pm_resume(struct device *dev) \ +{ \ + drv_type *drvdata = dev_get_drvdata(dev); \ + \ + return vfio_pci_core_runtime_resume(&drvdata->member); \ +} \ +static const struct dev_pm_ops name##_pm_ops = { \ + SET_RUNTIME_PM_OPS(name##_pm_suspend, name##_pm_resume, NULL) \ +}; \ +static pci_ers_result_t name##_aer_err_detected(struct pci_dev *pdev, \ + pci_channel_state_t state) \ +{ \ + drv_type *drvdata = pci_get_drvdata(pdev); \ + \ + return vfio_pci_core_aer_err_detected(&drvdata->member); \ +} + #endif /* VFIO_PCI_CORE_H */ diff --git a/include/linux/watch_queue.h b/include/linux/watch_queue.h index 429c7b6afead..b87e1babb5f0 100644 --- a/include/linux/watch_queue.h +++ b/include/linux/watch_queue.h @@ -52,10 +52,7 @@ struct watch_queue { * Representation of a watch on an object. */ struct watch { - union { - struct rcu_head rcu; - u32 info_id; /* ID to be OR'd in to info field */ - }; + struct rcu_head rcu; struct watch_queue __rcu *queue; /* Queue to post events to */ struct hlist_node queue_node; /* Link in queue->watches */ struct watch_list __rcu *watch_list; @@ -64,6 +61,7 @@ struct watch { void *private; /* Private data for the watched object */ u64 id; /* Internal identifier */ struct kref usage; /* Object usage count */ + u32 info_id; /* ID to be OR'd in to info field */ }; /* diff --git a/include/net/bluetooth/bluetooth.h b/include/net/bluetooth/bluetooth.h index b624da5026f5..cd9189244566 100644 --- a/include/net/bluetooth/bluetooth.h +++ b/include/net/bluetooth/bluetooth.h @@ -296,9 +296,9 @@ void bt_err_ratelimited(const char *fmt, ...); BT_DBG("%s: " fmt, bt_dev_name(hdev), ##__VA_ARGS__) #define bt_dev_warn_ratelimited(hdev, fmt, ...) \ - bt_warn_ratelimited("%s: " fmt, bt_dev_name(hdev), ##__VA_ARGS__) + bt_warn_ratelimited("%s: " fmt "\n", bt_dev_name(hdev), ##__VA_ARGS__) #define bt_dev_err_ratelimited(hdev, fmt, ...) \ - bt_err_ratelimited("%s: " fmt, bt_dev_name(hdev), ##__VA_ARGS__) + bt_err_ratelimited("%s: " fmt "\n", bt_dev_name(hdev), ##__VA_ARGS__) /* Connection and socket states */ enum bt_sock_state { diff --git a/include/net/bluetooth/hci.h b/include/net/bluetooth/hci.h index 1641d879dbda..9dc714d9145e 100644 --- a/include/net/bluetooth/hci.h +++ b/include/net/bluetooth/hci.h @@ -2527,6 +2527,7 @@ struct hci_le_conn_interval_group { struct hci_rp_le_read_conn_interval { __u8 status; + __u8 min; __u8 num_grps; struct hci_le_conn_interval_group grps[]; } __packed; diff --git a/include/net/bluetooth/hci_h4.h b/include/net/bluetooth/hci_h4.h new file mode 100644 index 000000000000..a37e7df8c9ce --- /dev/null +++ b/include/net/bluetooth/hci_h4.h @@ -0,0 +1,60 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* + * Bluetooth HCI H:4 packet reassembly + * + * Copyright (C) 2000-2001 Qualcomm Incorporated + * Copyright (C) 2002-2003 Maxim Krasnyansky + * Copyright (C) 2004-2005 Marcel Holtmann + */ + +#ifndef __HCI_H4_H +#define __HCI_H4_H + +#include +#include + +struct hci_dev; + +struct h4_recv_pkt { + u8 type; /* Packet type */ + u8 hlen; /* Header length */ + u8 loff; /* Data length offset in header */ + u8 lsize; /* Data length field size */ + u16 maxlen; /* Max overall packet length */ + int (*recv)(struct hci_dev *hdev, struct sk_buff *skb); +}; + +#define H4_RECV_ACL \ + .type = HCI_ACLDATA_PKT, \ + .hlen = HCI_ACL_HDR_SIZE, \ + .loff = 2, \ + .lsize = 2, \ + .maxlen = HCI_MAX_FRAME_SIZE \ + +#define H4_RECV_SCO \ + .type = HCI_SCODATA_PKT, \ + .hlen = HCI_SCO_HDR_SIZE, \ + .loff = 2, \ + .lsize = 1, \ + .maxlen = HCI_MAX_SCO_SIZE + +#define H4_RECV_EVENT \ + .type = HCI_EVENT_PKT, \ + .hlen = HCI_EVENT_HDR_SIZE, \ + .loff = 1, \ + .lsize = 1, \ + .maxlen = HCI_MAX_EVENT_SIZE + +#define H4_RECV_ISO \ + .type = HCI_ISODATA_PKT, \ + .hlen = HCI_ISO_HDR_SIZE, \ + .loff = 2, \ + .lsize = 2, \ + .maxlen = HCI_MAX_FRAME_SIZE \ + +struct sk_buff *h4_recv_skb(struct hci_dev *hdev, u8 *alignment, u8 *padding, + struct sk_buff *skb, const unsigned char *buffer, + int count, const struct h4_recv_pkt *pkts, + int pkts_count); + +#endif /* __HCI_H4_H */ diff --git a/include/net/bluetooth/hci_sync.h b/include/net/bluetooth/hci_sync.h index a6579a868678..59cb918d1405 100644 --- a/include/net/bluetooth/hci_sync.h +++ b/include/net/bluetooth/hci_sync.h @@ -122,6 +122,7 @@ int hci_disable_per_advertising_sync(struct hci_dev *hdev, u8 instance); int hci_remove_advertising_sync(struct hci_dev *hdev, struct sock *sk, u8 instance, bool force); int hci_disable_advertising_sync(struct hci_dev *hdev); +int hci_disable_ext_adv_legacy_instance_sync(struct hci_dev *hdev); int hci_clear_adv_instance_sync(struct hci_dev *hdev, struct sock *sk, u8 instance, bool force); int hci_update_passive_scan_sync(struct hci_dev *hdev); diff --git a/include/net/bluetooth/l2cap.h b/include/net/bluetooth/l2cap.h index 3d9a32094347..84f557d354ca 100644 --- a/include/net/bluetooth/l2cap.h +++ b/include/net/bluetooth/l2cap.h @@ -830,11 +830,13 @@ struct l2cap_chan *l2cap_chan_hold_unless_zero(struct l2cap_chan *c); void l2cap_chan_put(struct l2cap_chan *c); static inline void l2cap_chan_lock(struct l2cap_chan *chan) + __acquires(&chan->lock) { mutex_lock_nested(&chan->lock, atomic_read(&chan->nesting)); } static inline void l2cap_chan_unlock(struct l2cap_chan *chan) + __releases(&chan->lock) { mutex_unlock(&chan->lock); } @@ -960,6 +962,8 @@ int l2cap_add_scid(struct l2cap_chan *chan, __u16 scid); struct l2cap_chan *l2cap_chan_create(void); void l2cap_chan_close(struct l2cap_chan *chan, int reason); +void l2cap_chan_close_unlocked(struct l2cap_chan *chan, int reason) + __must_not_hold(&chan->lock); int l2cap_chan_connect(struct l2cap_chan *chan, __le16 psm, u16 cid, bdaddr_t *dst, u8 dst_type, u16 timeout); int l2cap_chan_reconfigure(struct l2cap_chan *chan, __u16 mtu); @@ -971,7 +975,8 @@ int l2cap_chan_check_security(struct l2cap_chan *chan, bool initiator); void l2cap_chan_set_defaults(struct l2cap_chan *chan, struct l2cap_chan *pchan); int l2cap_ertm_init(struct l2cap_chan *chan); void l2cap_chan_add(struct l2cap_conn *conn, struct l2cap_chan *chan); -void __l2cap_chan_add(struct l2cap_conn *conn, struct l2cap_chan *chan); +void __l2cap_chan_add(struct l2cap_conn *conn, struct l2cap_chan *chan) + __must_hold(&chan->lock); typedef void (*l2cap_chan_func_t)(struct l2cap_chan *chan, void *data); void l2cap_chan_list(struct l2cap_conn *conn, l2cap_chan_func_t func, void *data); @@ -985,4 +990,19 @@ void l2cap_conn_put(struct l2cap_conn *conn); int l2cap_register_user(struct l2cap_conn *conn, struct l2cap_user *user); void l2cap_unregister_user(struct l2cap_conn *conn, struct l2cap_user *user); +bool l2cap_chan_lock_conn(struct l2cap_chan *chan) + __acquires(&chan->lock) __cond_acquires(true, &chan->conn->lock); + +/* Release macro for l2cap_chan_lock_conn, so context analysis understands it */ +#define l2cap_chan_unlock_conn(chan, conn_locked) \ + ({ \ + struct l2cap_chan *__chan = (chan); \ + struct l2cap_conn *__conn = __chan->conn; \ + l2cap_chan_unlock(__chan); \ + if (conn_locked) { \ + mutex_unlock(&__conn->lock); \ + l2cap_conn_put(__conn); \ + } \ + }) + #endif /* __L2CAP_H */ diff --git a/include/net/cfg80211.h b/include/net/cfg80211.h index 97c16d4ff127..0be755acb79d 100644 --- a/include/net/cfg80211.h +++ b/include/net/cfg80211.h @@ -4256,6 +4256,21 @@ struct cfg80211_nan_local_sched { struct cfg80211_nan_channel nan_channels[] __counted_by(n_channels); }; +/** + * struct cfg80211_nan_non_evac_channels - NAN non-evacuable channels + * + * This struct defines the set of NAN local schedule channels that must not + * be evacuated for concurrent operations. + * + * @n_channels: number of channel definitions in %chandefs. + * @chandefs: array of channel definitions that must not be evacuated. Each + * must match a channel of the current local schedule. + */ +struct cfg80211_nan_non_evac_channels { + u8 n_channels; + struct cfg80211_chan_def chandefs[] __counted_by(n_channels); +}; + /** * struct cfg80211_nan_peer_map - NAN peer schedule map * @@ -5204,6 +5219,12 @@ struct mgmt_frame_regs { * schedule, the full new schedule is provided - partial updates are not * supported, and the new schedule completely replaces the previous one. * + * @nan_set_non_evac_channels: set the list of local schedule channels that + * must not be evacuated for concurrent operations. The provided list + * replaces the previous set; channels of the current schedule that are + * not included become evacuable again. All provided channels are + * guaranteed by cfg80211 to belong to the current local schedule. + * * @set_multicast_to_unicast: configure multicast to unicast conversion for BSS * * @get_txq_stats: Get TXQ stats for interface or phy. If wdev is %NULL, this @@ -5590,6 +5611,9 @@ struct cfg80211_ops { int (*nan_set_peer_sched)(struct wiphy *wiphy, struct wireless_dev *wdev, struct cfg80211_nan_peer_sched *sched); + int (*nan_set_non_evac_channels)(struct wiphy *wiphy, + struct wireless_dev *wdev, + struct cfg80211_nan_non_evac_channels *channels); int (*set_multicast_to_unicast)(struct wiphy *wiphy, struct net_device *dev, const bool enabled); @@ -8181,20 +8205,20 @@ bool regulatory_pre_cac_allowed(struct wiphy *wiphy); */ /** - * reg_query_regdb_wmm - Query internal regulatory db for wmm rule - * Regulatory self-managed driver can use it to proactively - * + * reg_query_regdb_wmm - Query internal regulatory db for WMM rules * @alpha2: the ISO/IEC 3166 alpha2 wmm rule to be queried. * @freq: the frequency (in MHz) to be queried. - * @rule: pointer to store the wmm rule from the regulatory db. + * @rule: pointer to store the WMM rule from the regulatory db. * - * Self-managed wireless drivers can use this function to query + * Self-managed wireless drivers can use this function to query * the internal regulatory database to check whether the given - * ISO/IEC 3166 alpha2 country and freq have wmm rule limitations. + * ISO/IEC 3166 alpha2 country and freq have WMM rule limitations. * * Drivers should check the return value, its possible you can get * an -ENODATA. * + * This uses RCU internally so can be called in just about any context. + * * Return: 0 on success. -ENODATA. */ int reg_query_regdb_wmm(char *alpha2, int freq, diff --git a/include/net/cipso_ipv4.h b/include/net/cipso_ipv4.h index d6780d7903f4..b41672221797 100644 --- a/include/net/cipso_ipv4.h +++ b/include/net/cipso_ipv4.h @@ -185,12 +185,12 @@ int cipso_v4_sock_setattr(struct sock *sk, const struct cipso_v4_doi *doi_def, const struct netlbl_lsm_secattr *secattr, bool sk_locked); -void cipso_v4_sock_delattr(struct sock *sk); +int cipso_v4_sock_delattr(struct sock *sk); int cipso_v4_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr); int cipso_v4_req_setattr(struct request_sock *req, const struct cipso_v4_doi *doi_def, const struct netlbl_lsm_secattr *secattr); -void cipso_v4_req_delattr(struct request_sock *req); +int cipso_v4_req_delattr(struct request_sock *req); int cipso_v4_skbuff_setattr(struct sk_buff *skb, const struct cipso_v4_doi *doi_def, const struct netlbl_lsm_secattr *secattr); @@ -221,8 +221,9 @@ static inline int cipso_v4_sock_setattr(struct sock *sk, return -ENOSYS; } -static inline void cipso_v4_sock_delattr(struct sock *sk) +static inline int cipso_v4_sock_delattr(struct sock *sk) { + return 0; } static inline int cipso_v4_sock_getattr(struct sock *sk, @@ -238,9 +239,9 @@ static inline int cipso_v4_req_setattr(struct request_sock *req, return -ENOSYS; } -static inline void cipso_v4_req_delattr(struct request_sock *req) +static inline int cipso_v4_req_delattr(struct request_sock *req) { - return; + return 0; } static inline int cipso_v4_skbuff_setattr(struct sk_buff *skb, diff --git a/include/net/ip.h b/include/net/ip.h index f0aeab1b1a3b..29bb02db8782 100644 --- a/include/net/ip.h +++ b/include/net/ip.h @@ -580,7 +580,7 @@ static inline void ip_select_ident_segs(struct net *net, struct sk_buff *skb, val = atomic_read(&inet_sk(sk)->inet_id); atomic_set(&inet_sk(sk)->inet_id, val + segs); } else { - val = atomic_add_return(segs, &inet_sk(sk)->inet_id); + val = atomic_fetch_add(segs, &inet_sk(sk)->inet_id); } iph->id = htons(val); return; diff --git a/include/net/ip_vs.h b/include/net/ip_vs.h index 32fde731bceb..9a83bff32569 100644 --- a/include/net/ip_vs.h +++ b/include/net/ip_vs.h @@ -36,9 +36,6 @@ #define IP_VS_HDR_INVERSE 1 #define IP_VS_HDR_ICMP 2 -/* Destination Server Flags */ -#define IP_VS_DEST_F_OVERLOAD 0x0002 /* server is overloaded */ - /* Destination Server Config Flags */ #define IP_VS_DEST_CF_AVAILABLE 0x0001 /* server is available */ @@ -973,32 +970,43 @@ struct ip_vs_dest_dst { * and so on. */ struct ip_vs_dest { + /* Cacheline for hash table nodes - read-mostly */ + struct list_head n_list; /* for the dests in the service */ struct hlist_node d_list; /* for table with all the dests */ - u16 af; /* address family */ - __be16 port; /* port number of the server */ - union nf_inet_addr addr; /* IP address of the server */ - volatile unsigned int flags; /* dest status flags */ - atomic_t conn_flags; /* flags to copy to conn */ atomic_t weight; /* server weight */ - unsigned long cflags; /* config flags */ atomic_t last_weight; /* server latest weight */ + + /* connection thresholds */ + u32 l_threshold_val;/* used lower threshold */ + u32 u_threshold_val;/* used upper threshold */ + /* 32/48 */ + u32 l_threshold; /* lower threshold */ + u32 u_threshold; /* upper threshold */ + + unsigned long cflags; /* config flags */ + + /* 44/64 */ + atomic_t conn_flags; /* flags to copy to conn */ + __u16 tun_type; /* tunnel type */ __be16 tun_port; /* tunnel port */ __u16 tun_flags; /* tunnel flags */ - refcount_t refcnt; /* reference counter */ - struct ip_vs_stats stats; /* statistics */ - unsigned long idle_start; /* start time, jiffies */ + u16 af; /* address family */ + __be16 port; /* port number of the server */ + /* 60/80 */ + union nf_inet_addr addr; /* IP address of the server */ - /* connection counters and thresholds */ - atomic_t activeconns; /* active connections */ + /* connection counters */ atomic_t totalconns; /* total connections */ + atomic_t activeconns; /* active connections */ atomic_t persistconns; /* persistent connections */ - __u32 u_threshold; /* upper threshold */ - __u32 l_threshold; /* lower threshold */ - __u32 l_threshold_val;/* used lower threshold */ + + refcount_t refcnt; /* reference counter */ + struct ip_vs_stats stats; /* statistics */ + unsigned long idle_start; /* start time, jiffies */ /* for destination cache */ spinlock_t dst_lock; /* lock of dst_cache */ @@ -1915,7 +1923,13 @@ static inline void ip_vs_dest_put_and_free(struct ip_vs_dest *dest) kfree(dest); } -void ip_vs_dest_update_overload(struct ip_vs_dest *dest, int mode); +void ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload); + +/* Check if dest is in overloaded state */ +static inline bool ip_vs_dest_is_overloaded(const struct ip_vs_dest *dest) +{ + return READ_ONCE(dest->l_threshold_val); +} /* IPVS sync daemon data and function prototypes * (from ip_vs_sync.c) diff --git a/include/net/mac80211.h b/include/net/mac80211.h index ed6a5874ff96..3e918cecb512 100644 --- a/include/net/mac80211.h +++ b/include/net/mac80211.h @@ -923,12 +923,14 @@ struct ieee80211_bss_conf { * @channel_entry: the Channel Entry blob as defined in Wi-Fi Aware * (TM) 4.0 specification Table 100 (Channel Entry format for the NAN * Availability attribute). + * @no_evacuate: if set, this channel must not be evacuated */ struct ieee80211_nan_channel { struct ieee80211_chan_req chanreq; u8 needed_rx_chains; struct ieee80211_chanctx_conf *chanctx_conf; u8 channel_entry[6]; + bool no_evacuate; }; /** diff --git a/include/net/mana/gdma.h b/include/net/mana/gdma.h index 308950f9b54b..f43028a398d6 100644 --- a/include/net/mana/gdma.h +++ b/include/net/mana/gdma.h @@ -58,6 +58,7 @@ enum gdma_work_request_flags { enum gdma_eqe_type { GDMA_EQE_COMPLETION = 3, + GDMA_EQE_THROTTLE = 4, GDMA_EQE_TEST_EVENT = 64, GDMA_EQE_HWC_INIT_EQ_ID_DB = 129, GDMA_EQE_HWC_INIT_DATA = 130, @@ -286,6 +287,7 @@ struct gdma_dev { #define GDMA_EQE_SIZE 16 #define GDMA_MAX_SQE_SIZE 512 #define GDMA_MAX_RQE_SIZE 256 +#define GDMA_EQ_MAX_CHILD_CQ 2 #define GDMA_COMP_DATA_SIZE 0x3C @@ -313,6 +315,11 @@ struct gdma_event { struct gdma_queue; +struct gdma_eq_stats { + u64_stats_t throttle_count; + struct u64_stats_sync syncp; +}; + struct mana_eq { struct gdma_queue *eq; struct dentry *mana_eq_debugfs; @@ -366,6 +373,10 @@ struct gdma_queue { unsigned int irq; u32 log2_throttle_limit; + + struct gdma_eq_stats stats; + + struct gdma_queue __rcu *child_cq[GDMA_EQ_MAX_CHILD_CQ]; } eq; struct { @@ -422,14 +433,72 @@ enum gdma_context_flags { GC_IN_SERVICE = 1, }; +struct gdma_context; + +/** + * struct gdma_bus_ops - transport-specific operations + * + * Lets the bus-agnostic GDMA core drive PCI and CDX devices without + * testing configuration symbols. Each bus driver installs its own + * instance in gdma_context.bus_ops at probe time. + * + * @bus_name: Bus token used to build the per-vector IRQ names. + * @msix_can_alloc_dyn: True if the bus can allocate MSI-X vectors after + * probe time. Buses that size their vector pool at probe and cannot + * grow it later leave this NULL. + * @msix_virq: Return the Linux IRQ number backing an MSI vector, or + * -EINVAL if the vector has not been allocated yet. + * @msix_alloc_at: Allocate an MSI vector on demand and return its IRQ + * number, updating @msi with the index actually assigned. Buses that + * allocate their whole pool up front leave this NULL. + * @msix_free: Release a vector obtained from @msix_alloc_at. Only needed + * by buses that implement @msix_alloc_at. + * @msix_vec_count: Return the number of entries in the device MSI-X table, + * used to clamp the vector count the core asks for. Buses that cannot + * report a table size leave this NULL and the clamp is skipped. + * @setup_hwc_irqs: Set up the interrupts the hardware channel needs before + * it is created. + * @setup_remaining_irqs: Set up the remaining interrupts once the device + * resource limits are known. + * @remove_irqs: Release the interrupts set up by @setup_hwc_irqs and + * @setup_remaining_irqs. + * @dev_reset: Reset the device using the bus-level reset mechanism. + * @schedule_serv_work: Queue device servicing or recovery. Buses without + * a servicing path leave this NULL. + * @drv_cap_flags1: Extra capability bits this transport can honour, OR'ed + * into GDMA_DRV_CAP_FLAGS1 when the driver version is negotiated. + */ +struct gdma_bus_ops { + const char *bus_name; + bool (*msix_can_alloc_dyn)(struct gdma_context *gc); + int (*msix_virq)(struct gdma_context *gc, int msi); + int (*msix_alloc_at)(struct gdma_context *gc, int *msi); + void (*msix_free)(struct gdma_context *gc, int msi, int irq); + int (*msix_vec_count)(struct gdma_context *gc); + int (*setup_hwc_irqs)(struct gdma_context *gc); + int (*setup_remaining_irqs)(struct gdma_context *gc); + void (*remove_irqs)(struct gdma_context *gc); + int (*dev_reset)(struct gdma_context *gc); + int (*schedule_serv_work)(struct gdma_context *gc, + enum gdma_eqe_type type); + u64 drv_cap_flags1; +}; + struct gdma_context { struct device *dev; struct dentry *mana_pci_debugfs; + /* Transport-specific operations, installed by the bus driver */ + const struct gdma_bus_ops *bus_ops; + /* Hardware max number of queues */ unsigned int max_num_queues; /* Per-vPort max number of queues */ unsigned int max_num_queues_vport; + /* Number of vPorts reported by the device, capped at + * MAX_PORTS_IN_MANA_DEV + */ + u16 num_ports; unsigned int max_num_msix; unsigned int num_msix_usable; struct xarray irq_contexts; @@ -529,9 +598,15 @@ ssize_t mana_gd_read_ring(struct gdma_queue *q, char __user *buf, int mana_schedule_serv_work(struct gdma_context *gc, enum gdma_eqe_type type); +int mana_gd_alloc_service_wq(struct gdma_context *gc); + +void mana_gd_free_service_wq(struct gdma_context *gc); + void mana_gd_ring_dim(struct gdma_queue *cq, u32 mod_usec, bool mod_usec_vld, u32 mod_comps, bool mod_comps_vld); +bool mana_gd_detach_cq(struct gdma_context *gc, struct gdma_queue *queue); + struct gdma_wqe { u32 reserved :24; u32 last_vbytes :8; @@ -686,24 +761,35 @@ enum { /* Driver supports non-contiguous queue buffers */ #define GDMA_DRV_CAP_FLAG_1_NON_CONTIGUOUS_BUFFERS BIT(30) +/* Driver supports handling throttled EQEs */ +#define GDMA_DRV_CAP_FLAG_1_THROTTLED_EVENT_QUEUE BIT_ULL(32) + +/* Capabilities in the PCI-only group below rely on dynamic MSI-X allocation + * and on the servicing and reset paths reached through + * mana_schedule_serv_work(). Transports that provide neither leave + * gdma_bus_ops.drv_cap_flags1 unset so the group is not advertised. + */ +#define GDMA_DRV_CAP_FLAGS1_PCI \ + (GDMA_DRV_CAP_FLAG_1_DYNAMIC_IRQ_ALLOC_SUPPORT | \ + GDMA_DRV_CAP_FLAG_1_SELF_RESET_ON_EQE | \ + GDMA_DRV_CAP_FLAG_1_HANDLE_RECONFIG_EQE | \ + GDMA_DRV_CAP_FLAG_1_PROBE_RECOVERY | \ + GDMA_DRV_CAP_FLAG_1_HWC_TIMEOUT_RECOVERY) + #define GDMA_DRV_CAP_FLAGS1 \ (GDMA_DRV_CAP_FLAG_1_EQ_SHARING_MULTI_VPORT | \ GDMA_DRV_CAP_FLAG_1_NAPI_WKDONE_FIX | \ GDMA_DRV_CAP_FLAG_1_HWC_TIMEOUT_RECONFIG | \ GDMA_DRV_CAP_FLAG_1_VARIABLE_INDIRECTION_TABLE_SUPPORT | \ GDMA_DRV_CAP_FLAG_1_DEV_LIST_HOLES_SUP | \ - GDMA_DRV_CAP_FLAG_1_DYNAMIC_IRQ_ALLOC_SUPPORT | \ - GDMA_DRV_CAP_FLAG_1_SELF_RESET_ON_EQE | \ - GDMA_DRV_CAP_FLAG_1_HANDLE_RECONFIG_EQE | \ GDMA_DRV_CAP_FLAG_1_HW_VPORT_LINK_AWARE | \ GDMA_DRV_CAP_FLAG_1_PERIODIC_STATS_QUERY | \ GDMA_DRV_CAP_FLAG_1_SKB_LINEARIZE | \ - GDMA_DRV_CAP_FLAG_1_PROBE_RECOVERY | \ GDMA_DRV_CAP_FLAG_1_HANDLE_STALL_SQ_RECOVERY | \ - GDMA_DRV_CAP_FLAG_1_HWC_TIMEOUT_RECOVERY | \ GDMA_DRV_CAP_FLAG_1_EQ_MSI_UNSHARE_MULTI_VPORT | \ GDMA_DRV_CAP_FLAG_1_DYN_INTERRUPT_MODERATION | \ - GDMA_DRV_CAP_FLAG_1_NON_CONTIGUOUS_BUFFERS) + GDMA_DRV_CAP_FLAG_1_NON_CONTIGUOUS_BUFFERS | \ + GDMA_DRV_CAP_FLAG_1_THROTTLED_EVENT_QUEUE) #define GDMA_DRV_CAP_FLAGS2 0 @@ -1044,7 +1130,24 @@ struct gdma_destroy_dm_resp { struct gdma_resp_hdr hdr; }; /* HW Data */ -int mana_gd_verify_vf_version(struct pci_dev *pdev); +int mana_gd_verify_vf_version(struct gdma_context *gc); +int mana_gd_query_max_resources(struct gdma_context *gc); +int mana_gd_setup(struct gdma_context *gc); +void mana_gd_cleanup(struct gdma_context *gc); +int mana_gd_detect_devices(struct gdma_context *gc); +int mana_gd_init_registers(struct gdma_context *gc); +irqreturn_t mana_gd_intr(int irq, void *arg); +void mana_gd_process_eq_events(void *arg); + +static inline u32 mana_gd_r32(struct gdma_context *g, u64 offset) +{ + return readl(g->bar0_va + offset); +} + +static inline u64 mana_gd_r64(struct gdma_context *g, u64 offset) +{ + return readq(g->bar0_va + offset); +} int mana_gd_register_device(struct gdma_dev *gd); int mana_gd_deregister_device(struct gdma_dev *gd); @@ -1077,8 +1180,6 @@ void mana_unregister_debugfs(void); int mana_rdma_service_event(struct gdma_context *gc, enum gdma_service_type event); -int mana_gd_suspend(struct pci_dev *pdev, pm_message_t state); -int mana_gd_resume(struct pci_dev *pdev); bool mana_need_log(struct gdma_context *gc, int err); @@ -1089,4 +1190,6 @@ void mana_gd_put_gic(struct gdma_context *gc, bool use_msi_bitmap, int msi); int mana_gd_query_device_cfg(struct gdma_context *gc, u32 proto_major_ver, u32 proto_minor_ver, u32 proto_micro_ver, u16 *max_num_vports, u8 *bm_hostmode); +int mana_gd_dev_reset(struct gdma_context *gc); + #endif /* _GDMA_H */ diff --git a/include/net/mana/mana.h b/include/net/mana/mana.h index 8c3dc9d0b299..e46ba02529c2 100644 --- a/include/net/mana/mana.h +++ b/include/net/mana/mana.h @@ -90,6 +90,7 @@ enum mana_priv_flag_bits { /* Update this count whenever the respective structures are changed */ #define MANA_STATS_RX_COUNT (6 + MANA_CQE_COAL_PKTS_8 - 1) #define MANA_STATS_TX_COUNT 11 +#define MANA_STATS_EQ_COUNT 1 #define MANA_RX_FRAG_ALIGNMENT 64 diff --git a/include/net/netfilter/nf_conntrack_seqadj.h b/include/net/netfilter/nf_conntrack_seqadj.h index 883c414b768e..0f5bbb14a25a 100644 --- a/include/net/netfilter/nf_conntrack_seqadj.h +++ b/include/net/netfilter/nf_conntrack_seqadj.h @@ -33,6 +33,7 @@ static inline struct nf_conn_seqadj *nfct_seqadj_ext_add(struct nf_conn *ct) int nf_ct_seqadj_init(struct nf_conn *ct, enum ip_conntrack_info ctinfo, s32 off); +void nf_ct_seqadj_reset(struct nf_conn *ct, enum ip_conntrack_info ctinfo); int nf_ct_seqadj_set(struct nf_conn *ct, enum ip_conntrack_info ctinfo, __be32 seq, s32 off); void nf_ct_tcp_seqadj_set(struct sk_buff *skb, struct nf_conn *ct, diff --git a/include/net/netlabel.h b/include/net/netlabel.h index 02914b1df38b..f896b9d52ed1 100644 --- a/include/net/netlabel.h +++ b/include/net/netlabel.h @@ -477,7 +477,7 @@ int netlbl_sock_setattr(struct sock *sk, u16 family, const struct netlbl_lsm_secattr *secattr, bool sk_locked); -void netlbl_sock_delattr(struct sock *sk); +int netlbl_sock_delattr(struct sock *sk); int netlbl_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr); int netlbl_conn_setattr(struct sock *sk, @@ -485,7 +485,7 @@ int netlbl_conn_setattr(struct sock *sk, const struct netlbl_lsm_secattr *secattr); int netlbl_req_setattr(struct request_sock *req, const struct netlbl_lsm_secattr *secattr); -void netlbl_req_delattr(struct request_sock *req); +int netlbl_req_delattr(struct request_sock *req); int netlbl_skbuff_setattr(struct sk_buff *skb, u16 family, const struct netlbl_lsm_secattr *secattr); @@ -626,8 +626,9 @@ static inline int netlbl_sock_setattr(struct sock *sk, { return -ENOSYS; } -static inline void netlbl_sock_delattr(struct sock *sk) +static inline int netlbl_sock_delattr(struct sock *sk) { + return 0; } static inline int netlbl_sock_getattr(struct sock *sk, struct netlbl_lsm_secattr *secattr) @@ -645,9 +646,9 @@ static inline int netlbl_req_setattr(struct request_sock *req, { return -ENOSYS; } -static inline void netlbl_req_delattr(struct request_sock *req) +static inline int netlbl_req_delattr(struct request_sock *req) { - return; + return 0; } static inline int netlbl_skbuff_setattr(struct sk_buff *skb, u16 family, diff --git a/include/net/netns/netfilter.h b/include/net/netns/netfilter.h index a6a0bf4a247e..7fd78394d1e7 100644 --- a/include/net/netns/netfilter.h +++ b/include/net/netns/netfilter.h @@ -33,5 +33,7 @@ struct netns_nf { #if IS_ENABLED(CONFIG_NF_DEFRAG_IPV6) unsigned int defrag_ipv6_users; #endif + unsigned int hook_base_seq; + unsigned int nat_hook_base_seq; }; #endif diff --git a/include/net/seg6_hmac.h b/include/net/seg6_hmac.h index e9f41725933e..3161a8104b89 100644 --- a/include/net/seg6_hmac.h +++ b/include/net/seg6_hmac.h @@ -48,7 +48,8 @@ extern int seg6_hmac_info_add(struct net *net, u32 key, extern int seg6_hmac_info_del(struct net *net, u32 key); extern int seg6_push_hmac(struct net *net, struct in6_addr *saddr, struct ipv6_sr_hdr *srh); -extern bool seg6_hmac_validate_skb(struct sk_buff *skb); +extern bool seg6_hmac_validate_skb(struct sk_buff *skb, + struct ipv6_sr_hdr *srh); #ifdef CONFIG_IPV6_SEG6_HMAC extern int seg6_hmac_net_init(struct net *net); extern void seg6_hmac_net_exit(struct net *net); diff --git a/include/net/xsk_buff_pool.h b/include/net/xsk_buff_pool.h index a7df573784fd..02e89350faf9 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; @@ -119,6 +121,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/scsi/scsi_cmnd.h b/include/scsi/scsi_cmnd.h index 8ecfb94049db..bf6d69f0249f 100644 --- a/include/scsi/scsi_cmnd.h +++ b/include/scsi/scsi_cmnd.h @@ -394,6 +394,13 @@ static inline unsigned scsi_transfer_length(struct scsi_cmnd *scmd) extern void scsi_build_sense(struct scsi_cmnd *scmd, int desc, u8 key, u8 asc, u8 ascq); +static inline void scsi_set_sense(struct scsi_cmnd *scmd, int desc, + u8 key, u16 code) +{ + scsi_build_sense(scmd, desc, key, scsi_sense_code_asc(code), + scsi_sense_code_ascq(code)); +} + struct request *scsi_alloc_request(struct request_queue *q, blk_opf_t opf, blk_mq_req_flags_t flags); diff --git a/include/scsi/scsi_common.h b/include/scsi/scsi_common.h index 00c8a16d3cd2..6fb2c290ba33 100644 --- a/include/scsi/scsi_common.h +++ b/include/scsi/scsi_common.h @@ -71,8 +71,18 @@ extern u64 scsilun_to_int(struct scsi_lun *); struct scsi_sense_hdr { /* See SPC-3 section 4.5 */ u8 response_code; /* permit: 0x0, 0x70, 0x71, 0x72, 0x73 */ u8 sense_key; - u8 asc; - u8 ascq; + union { + struct { +#if defined(__BIG_ENDIAN) + u8 asc; + u8 ascq; +#elif defined(__LITTLE_ENDIAN) + u8 ascq; + u8 asc; +#endif + }; + u16 sense_code; + }; u8 byte4; u8 byte5; u8 byte6; @@ -87,10 +97,27 @@ static inline bool scsi_sense_valid(const struct scsi_sense_hdr *sshdr) return (sshdr->response_code & 0x70) == 0x70; } +static inline u8 scsi_sense_asc(const struct scsi_sense_hdr *sshdr) +{ + return scsi_sense_code_asc(sshdr->sense_code); +} + +static inline u8 scsi_sense_ascq(const struct scsi_sense_hdr *sshdr) +{ + return scsi_sense_code_ascq(sshdr->sense_code); +} + extern bool scsi_normalize_sense(const u8 *sense_buffer, int sb_len, struct scsi_sense_hdr *sshdr); extern void scsi_build_sense_buffer(int desc, u8 *buf, u8 key, u8 asc, u8 ascq); + +static inline void scsi_set_sense_buffer(int desc, u8 *buf, u8 key, u16 code) +{ + scsi_build_sense_buffer(desc, buf, key, scsi_sense_code_asc(code), + scsi_sense_code_ascq(code)); +} + int scsi_set_sense_information(u8 *buf, int buf_len, u64 info); int scsi_set_sense_field_pointer(u8 *buf, int buf_len, u16 fp, u8 bp, bool cd); extern const u8 * scsi_sense_desc_find(const u8 * sense_buffer, int sb_len, diff --git a/include/scsi/scsi_device.h b/include/scsi/scsi_device.h index 8694eeadd753..11910142ac50 100644 --- a/include/scsi/scsi_device.h +++ b/include/scsi/scsi_device.h @@ -514,20 +514,31 @@ extern void scsi_sanitize_inquiry_string(unsigned char *s, int len); */ #define SCMD_FAILURE_STAT_ANY 0xff /* - * The following can be set to the scsi_failure sense, asc and ascq fields to - * match on any sense, ASC, or ASCQ value. + * The following can be set to the scsi_failure sense key, asc and ascq fields + * to match any sense key, ASC, and ASCQ value. */ -#define SCMD_FAILURE_SENSE_ANY 0xff -#define SCMD_FAILURE_ASC_ANY 0xff -#define SCMD_FAILURE_ASCQ_ANY 0xff +#define SCMD_FAILURE_SENSE_KEY_ANY 0xff +#define SCMD_FAILURE_SENSE_CODE_ANY 0xffff +#define SCMD_FAILURE_ASC_ANY 0xff +#define SCMD_FAILURE_ASCQ_ANY 0xff /* Always retry a matching failure. */ #define SCMD_FAILURE_NO_LIMIT -1 struct scsi_failure { int result; - u8 sense; - u8 asc; - u8 ascq; + u8 sense_key; + union { + struct { +#if defined(__BIG_ENDIAN) + u8 asc; + u8 ascq; +#elif defined(__LITTLE_ENDIAN) + u8 ascq; + u8 asc; +#endif + }; + u16 sense_code; + }; /* * Number of times scsi_execute_cmd will retry the failure. It does * not count for the total_allowed. @@ -537,6 +548,16 @@ struct scsi_failure { s8 retries; }; +static inline u8 scsi_failure_asc(const struct scsi_failure *failure) +{ + return scsi_sense_code_asc(failure->sense_code); +} + +static inline u8 scsi_failure_ascq(const struct scsi_failure *failure) +{ + return scsi_sense_code_ascq(failure->sense_code); +} + struct scsi_failures { /* * If a scsi_failure does not have a retry limit setup this limit will diff --git a/include/scsi/scsi_proto.h b/include/scsi/scsi_proto.h index c6b4a4dc8d9c..f742a3bfeb86 100644 --- a/include/scsi/scsi_proto.h +++ b/include/scsi/scsi_proto.h @@ -12,6 +12,7 @@ #include #include +#include /* * SCSI opcodes @@ -218,25 +219,6 @@ enum sam_status { #define STATUS_MASK 0xfe -/* - * SENSE KEYS - */ -#define NO_SENSE 0x00 -#define RECOVERED_ERROR 0x01 -#define NOT_READY 0x02 -#define MEDIUM_ERROR 0x03 -#define HARDWARE_ERROR 0x04 -#define ILLEGAL_REQUEST 0x05 -#define UNIT_ATTENTION 0x06 -#define DATA_PROTECT 0x07 -#define BLANK_CHECK 0x08 -#define VENDOR_SPECIFIC 0x09 -#define COPY_ABORTED 0x0a -#define ABORTED_COMMAND 0x0b -#define VOLUME_OVERFLOW 0x0d -#define MISCOMPARE 0x0e -#define COMPLETED 0x0f - /* * Additional Sense Codes (ASC). */ diff --git a/include/scsi/scsi_sense.h b/include/scsi/scsi_sense.h new file mode 100644 index 000000000000..6e010a72482e --- /dev/null +++ b/include/scsi/scsi_sense.h @@ -0,0 +1,950 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * Definitions of SCSI sense keys, additional sense codes and additional sense + * code qualifiers. + */ +#ifndef _SCSI_SENSE_H_ +#define _SCSI_SENSE_H_ + +#include + +/* + * Sense keys. + * See: https://www.t10.org/lists/2sensekey.htm + */ +enum scsi_sense_key { + NO_SENSE = 0x00, + RECOVERED_ERROR = 0x01, + NOT_READY = 0x02, + MEDIUM_ERROR = 0x03, + HARDWARE_ERROR = 0x04, + ILLEGAL_REQUEST = 0x05, + UNIT_ATTENTION = 0x06, + DATA_PROTECT = 0x07, + BLANK_CHECK = 0x08, + VENDOR_SPECIFIC = 0x09, + COPY_ABORTED = 0x0a, + ABORTED_COMMAND = 0x0b, + VOLUME_OVERFLOW = 0x0d, + MISCOMPARE = 0x0e, + COMPLETED = 0x0f, +}; + +#define SCSI_ASC_DEF(name) ASC_##name +#define SCSI_ASC(name, code) \ + SCSI_ASC_DEF(name) = (code), \ + name = ((code) << 8) | 0x00 + +/* + * SCSI additional sense codes and sense codes qualifiers. + * See: https://www.t10.org/lists/asc-num.txt + * Additional sense codes and their qualifiers are combined as a single value + * equal to (ASC << 8) | ASCQ. + * + * The definitions are sorted in increasing sense code value order with a naming + * following as close as possible the exact naming used in T10. To avoid + * excessively long code lines when using these macros, some long ASC/ASCQ + * combination names are shortened (E.g. LOGICAL_UNIT_xxx -> LU_xxx). + * Very generic ASC names that potentially may clash with other macros elsewhere + * are prefixed with "SSC_" (e.g. WARNING and WRITE_ERROR). + */ +enum scsi_sense_code { + SCSI_ASC(NO_ADDITIONAL_SENSE_INFORMATION, 0x00), + FILEMARK_DETECTED = 0x0001, + END_OF_PARTITION_MEDIUM_DETECTED = 0x0002, + SETMARK_DETECTED = 0x0003, + BEGINNING_OF_PARTITION_MEDIUM_DETECTED = 0x0004, + END_OF_DATA_DETECTED = 0x0005, + IO_PROCESS_TERMINATED = 0x0006, + PROGRAMMABLE_EARLY_WARNING_DETECTED = 0x0007, + AUDIO_PLAY_OP_IN_PROGRESS = 0x0011, + AUDIO_PLAY_OP_PAUSED = 0x0012, + AUDIO_PLAY_OP_SUCCESSFULLY_COMPLETED = 0x0013, + AUDIO_PLAY_OP_STOPPED_DUE_TO_ERROR = 0x0014, + NO_CURRENT_AUDIO_STATUS_TO_RETURN = 0x0015, + OP_IN_PROGRESS = 0x0016, + CLEANING_REQUESTED = 0x0017, + ERASE_OP_IN_PROGRESS = 0x0018, + LOCATE_OP_IN_PROGRESS = 0x0019, + REWIND_OP_IN_PROGRESS = 0x001A, + SET_CAPACITY_OP_IN_PROGRESS = 0x001B, + VERIFY_OP_IN_PROGRESS = 0x001C, + ATA_PASS_THROUGH_INFORMATION_AVAILABLE = 0x001D, + CONFLICTING_SA_CREATION_REQUEST = 0x001E, + LU_TRANSITIONING_TO_ANOTHER_POWER_CONDITION = 0x001F, + EXTENDED_COPY_INFORMATION_AVAILABLE = 0x0020, + ATOMIC_COMMAND_ABORTED_DUE_TO_ACA = 0x0021, + DEFERRED_MICROCODE_IS_PENDING = 0x0022, + OVERLAPPING_ATOMIC_COMMAND_IN_PROGRESS = 0x0023, + + SCSI_ASC(NO_INDEX_SECTOR_SIGNAL, 0x01), + + SCSI_ASC(NO_SEEK_COMPLETE, 0x02), + + SCSI_ASC(PERIPHERAL_DEVICE_WRITE_FAULT, 0x03), + NO_WRITE_CURRENT = 0x0301, + EXCESSIVE_WRITE_ERRORS = 0x0302, + + SCSI_ASC(LU_NOT_READY, 0x04), + LU_IS_IN_PROCESS_OF_BECOMING_READY = 0x0401, + LU_NOT_READY_INITIALIZING_COMMAND_REQUIRED = 0x0402, + LU_NOT_READY_MANUAL_INTERVENTION_REQUIRED = 0x0403, + LU_NOT_READY_FORMAT_IN_PROGRESS = 0x0404, + LU_NOT_READY_REBUILD_IN_PROGRESS = 0x0405, + LU_NOT_READY_RECALCULATION_IN_PROGRESS = 0x0406, + LU_NOT_READY_OP_IN_PROGRESS = 0x0407, + LU_NOT_READY_LONG_WRITE_IN_PROGRESS = 0x0408, + LU_NOT_READY_SELFTEST_IN_PROGRESS = 0x0409, + LU_NOT_ACCESSIBLE_ASYMMETRIC_ACCESS_STATE_TRANSITION = 0x040A, + LU_NOT_ACCESSIBLE_TARGET_PORT_IN_STANDBY_STATE = 0x040B, + LU_NOT_ACCESSIBLE_TARGET_PORT_IN_UNAVAILABLE_STATE = 0x040C, + LU_NOT_READY_STRUCTURE_CHECK_REQUIRED = 0x040D, + LU_NOT_READY_SECURITY_SESSION_IN_PROGRESS = 0x040E, + LU_NOT_READY_AUXILIARY_MEMORY_NOT_ACCESSIBLE = 0x0410, + LU_NOT_READY_NOTIFY_REQUIRED = 0x0411, + LU_NOT_READY_OFFLINE = 0x0412, + LU_NOT_READY_SA_CREATION_IN_PROGRESS = 0x0413, + LU_NOT_READY_SPACE_ALLOCATION_IN_PROGRESS = 0x0414, + LU_NOT_READY_ROBOTICS_DISABLED = 0x0415, + LU_NOT_READY_CONFIG_REQUIRED = 0x0416, + LU_NOT_READY_CALIBRATION_REQUIRED = 0x0417, + LU_NOT_READY_A_DOOR_IS_OPEN = 0x0418, + LU_NOT_READY_OPERATING_IN_SEQUENTIAL_MODE = 0x0419, + LU_NOT_READY_START_STOP_UNIT_COMMAND_IN_PROGRESS = 0x041A, + LU_NOT_READY_SANITIZE_IN_PROGRESS = 0x041B, + LU_NOT_READY_ADDITIONAL_POWER_USE_NOT_YET_GRANTED = 0x041C, + LU_NOT_READY_CONFIG_IN_PROGRESS = 0x041D, + LU_NOT_READY_MICROCODE_ACTIVATION_REQUIRED = 0x041E, + LU_NOT_READY_MICROCODE_DOWNLOAD_REQUIRED = 0x041F, + LU_NOT_READY_LU_RESET_REQUIRED = 0x0420, + LU_NOT_READY_HARD_RESET_REQUIRED = 0x0421, + LU_NOT_READY_POWER_CYCLE_REQUIRED = 0x0422, + LU_NOT_READY_AFFILIATION_REQUIRED = 0x0423, + DEPOPULATION_IN_PROGRESS = 0x0424, + DEPOPULATION_RESTORATION_IN_PROGRESS = 0x0425, + + SCSI_ASC(LU_DOES_NOT_RESPOND_TO_SELECTION, 0x05), + + SCSI_ASC(NO_REFERENCE_POSITION_FOUND, 0x06), + + SCSI_ASC(MULTIPLE_PERIPHERAL_DEVICES_SELECTED, 0x07), + + SCSI_ASC(LU_COMMUNICATION_FAILURE, 0x08), + LU_COMMUNICATION_TIMEOUT = 0x0801, + LU_COMMUNICATION_PARITY_ERROR = 0x0802, + LU_COMMUNICATION_CRC_ERROR = 0x0803, + UNREACHABLE_COPY_TARGET = 0x0804, + + SCSI_ASC(TRACK_FOLLOWING_ERROR, 0x09), + TRACKING_SERVO_FAILURE = 0x0901, + FOCUS_SERVO_FAILURE = 0x0902, + SPINDLE_SERVO_FAILURE = 0x0903, + HEAD_SELECT_FAULT = 0x0904, + VIBRATION_INDUCED_TRACKING_ERROR = 0x0905, + + SCSI_ASC(ERROR_LOG_OVERFLOW, 0x0A), + + SCSI_ASC(SSC_WARNING, 0x0B), + WARNING_SPECIFIED_TEMPERATURE_EXCEEDED = 0x0B01, + WARNING_ENCLOSURE_DEGRADED = 0x0B02, + WARNING_BACKGROUND_SELFTEST_FAILED = 0x0B03, + WARNING_BACKGROUND_PRESCAN_DETECTED_MEDIUM_ERROR = 0x0B04, + WARNING_BACKGROUND_MEDIUM_SCAN_DETECTED_MEDIUM_ERROR = 0x0B05, + WARNING_NONVOLATILE_CACHE_NOW_VOLATILE = 0x0B06, + WARNING_DEGRADED_POWER_TO_NONVOLATILE_CACHE = 0x0B07, + WARNING_POWER_LOSS_EXPECTED = 0x0B08, + WARNING_DEVICE_STATISTICS_NOTIFICATION_ACTIVE = 0x0B09, + WARNING_HIGH_CRITICAL_TEMPERATURE_LIMIT_EXCEEDED = 0x0B0A, + WARNING_LOW_CRITICAL_TEMPERATURE_LIMIT_EXCEEDED = 0x0B0B, + WARNING_HIGH_OPERATING_TEMPERATURE_LIMIT_EXCEEDED = 0x0B0C, + WARNING_LOW_OPERATING_TEMPERATURE_LIMIT_EXCEEDED = 0x0B0D, + WARNING_HIGH_CRITICAL_HUMIDITY_LIMIT_EXCEEDED = 0x0B0E, + WARNING_LOW_CRITICAL_HUMIDITY_LIMIT_EXCEEDED = 0x0B0F, + WARNING_HIGH_OPERATING_HUMIDITY_LIMIT_EXCEEDED = 0x0B10, + WARNING_LOW_OPERATING_HUMIDITY_LIMIT_EXCEEDED = 0x0B11, + WARNING_MICROCODE_SECURITY_AT_RISK = 0x0B12, + WARNING_MICROCODE_DIGITAL_SIGNATURE_VALIDATION_FAILURE = 0x0B13, + WARNING_PHYSICAL_ELEMENT_STATUS_CHANGE = 0x0B14, + + /* Defined as "WRITE ERROR" in T10. */ + SCSI_ASC(SSC_WRITE_ERROR, 0x0C), + WRITE_ERROR_RECOVERED_WITH_AUTO_REALLOCATION = 0x0C01, + WRITE_ERROR_AUTO_REALLOCATION_FAILED = 0x0C02, + WRITE_ERROR_RECOMMEND_REASSIGNMENT = 0x0C03, + COMPRESSION_CHECK_MISCOMPARE_ERROR = 0x0C04, + DATA_EXPANSION_OCCURRED_DURING_COMPRESSION = 0x0C05, + BLOCK_NOT_COMPRESSIBLE = 0x0C06, + WRITE_ERROR_RECOVERY_NEEDED = 0x0C07, + WRITE_ERROR_RECOVERY_FAILED = 0x0C08, + WRITE_ERROR_LOSS_OF_STREAMING = 0x0C09, + WRITE_ERROR_PADDING_BLOCKS_ADDED = 0x0C0A, + AUXILIARY_MEMORY_WRITE_ERROR = 0x0C0B, + WRITE_ERROR_UNEXPECTED_UNSOLICITED_DATA = 0x0C0C, + WRITE_ERROR_NOT_ENOUGH_UNSOLICITED_DATA = 0x0C0D, + MULTIPLE_WRITE_ERRORS = 0x0C0E, + DEFECTS_IN_ERROR_WINDOW = 0x0C0F, + INCOMPLETE_MULTIPLE_ATOMIC_WRITE_OPERATIONS = 0x0C10, + WRITE_ERROR_RECOVERY_SCAN_NEEDED = 0x0C11, + WRITE_ERROR_INSUFFICIENT_ZONE_RESOURCES = 0x0C12, + + SCSI_ASC(ERROR_DETECTED_BY_THIRD_PARTY_TEMPORARY_INITIATOR, 0x0D), + THIRD_PARTY_DEVICE_FAILURE = 0x0D01, + COPY_TARGET_DEVICE_NOT_REACHABLE = 0x0D02, + INCORRECT_COPY_TARGET_DEVICE_TYPE = 0x0D03, + COPY_TARGET_DEVICE_DATA_UNDERRUN = 0x0D04, + COPY_TARGET_DEVICE_DATA_OVERRUN = 0x0D05, + + SCSI_ASC(INVALID_INFORMATION_UNIT, 0x0E), + INFORMATION_UNIT_TOO_SHORT = 0x0E01, + INFORMATION_UNIT_TOO_LONG = 0x0E02, + INVALID_FIELD_IN_COMMAND_INFORMATION_UNIT = 0x0E03, + + SCSI_ASC(ID_CRC_OR_ECC_ERROR, 0x10), + LOGICAL_BLOCK_GUARD_CHECK_FAILED = 0x1001, + LOGICAL_BLOCK_APPLICATION_TAG_CHECK_FAILED = 0x1002, + LOGICAL_BLOCK_REFERENCE_TAG_CHECK_FAILED = 0x1003, + LOGICAL_BLOCK_PROTECTION_ERROR_ON_RECOVER_BUFFERED_DATA = 0x1004, + LOGICAL_BLOCK_PROTECTION_METHOD_ERROR = 0x1005, + + SCSI_ASC(UNRECOVERED_READ_ERROR, 0x11), + READ_RETRIES_EXHAUSTED = 0x1101, + ERROR_TOO_LONG_TO_CORRECT = 0x1102, + MULTIPLE_READ_ERRORS = 0x1103, + UNRECOVERED_READ_ERROR_AUTO_REALLOCATE_FAILED = 0x1104, + LEC_UNCORRECTABLE_ERROR = 0x1105, + CIRC_UNRECOVERED_ERROR = 0x1106, + DATA_RESYNCHRONIZATION_ERROR = 0x1107, + INCOMPLETE_BLOCK_READ = 0x1108, + NO_GAP_FOUND = 0x1109, + MISCORRECTED_ERROR = 0x110A, + UNRECOVERED_READ_ERROR_RECOMMEND_REASSIGNMENT = 0x110B, + UNRECOVERED_READ_ERROR_RECOMMEND_REWRITE_THE_DATA = 0x110C, + DECOMPRESSION_CRC_ERROR = 0x110D, + CANNOT_DECOMPRESS_USING_DECLARED_ALGORITHM = 0x110E, + ERROR_READING_UPC_EAN_NUMBER = 0x110F, + ERROR_READING_ISRC_NUMBER = 0x1110, + READ_ERROR_LOSS_OF_STREAMING = 0x1111, + AUXILIARY_MEMORY_READ_ERROR = 0x1112, + READ_ERROR_FAILED_RETRANSMISSION_REQUEST = 0x1113, + READ_ERROR_LBA_MARKED_BAD_BY_APPLICATION_CLIENT = 0x1114, + WRITE_AFTER_SANITIZE_REQUIRED = 0x1115, + + SCSI_ASC(ADDRESS_MARK_NOT_FOUND_FOR_ID_FIELD, 0x12), + + SCSI_ASC(ADDRESS_MARK_NOT_FOUND_FOR_DATA_FIELD, 0x13), + + SCSI_ASC(RECORDED_ENTITY_NOT_FOUND, 0x14), + RECORD_NOT_FOUND = 0x1401, + FILEMARK_OR_SETMARK_NOT_FOUND = 0x1402, + END_OF_DATA_NOT_FOUND = 0x1403, + BLOCK_SEQUENCE_ERROR = 0x1404, + RECORD_NOT_FOUND_RECOMMEND_REASSIGNMENT = 0x1405, + RECORD_NOT_FOUND_DATA_AUTO_REALLOCATED = 0x1406, + LOCATE_OPERATION_FAILURE = 0x1407, + + SCSI_ASC(RANDOM_POSITIONING_ERROR, 0x15), + MECHANICAL_POSITIONING_ERROR = 0x1501, + POSITIONING_ERROR_DETECTED_BY_READ_OF_MEDIUM = 0x1502, + + SCSI_ASC(DATA_SYNCHRONIZATION_MARK_ERROR, 0x16), + DATA_SYNC_ERROR_DATA_REWRITTEN = 0x1601, + DATA_SYNC_ERROR_RECOMMEND_REWRITE = 0x1602, + DATA_SYNC_ERROR_DATA_AUTO_REALLOCATED = 0x1603, + DATA_SYNC_ERROR_RECOMMEND_REASSIGNMENT = 0x1604, + + SCSI_ASC(RECOVERED_DATA_WITH_NO_ERROR_CORRECTION_APPLIED, 0x17), + RECOVERED_DATA_WITH_RETRIES = 0x1701, + RECOVERED_DATA_WITH_POSITIVE_HEAD_OFFSET = 0x1702, + RECOVERED_DATA_WITH_NEGATIVE_HEAD_OFFSET = 0x1703, + RECOVERED_DATA_WITH_RETRIES_AND_OR_CIRC_APPLIED = 0x1704, + RECOVERED_DATA_USING_PREVIOUS_SECTOR_ID = 0x1705, + RECOVERED_DATA_WITHOUT_ECC_DATA_AUTO_REALLOCATED = 0x1706, + RECOVERED_DATA_WITHOUT_ECC_RECOMMEND_REASSIGNMENT = 0x1707, + RECOVERED_DATA_WITHOUT_ECC_RECOMMEND_REWRITE = 0x1708, + RECOVERED_DATA_WITHOUT_ECC_DATA_REWRITTEN = 0x1709, + + SCSI_ASC(RECOVERED_DATA_WITH_ERROR_CORRECTION_APPLIED, 0x18), + RECOVERED_DATA_WITH_ERROR_CORRECTION_RETRIES_APPLIED = 0x1801, + RECOVERED_DATA_DATA_AUTO_REALLOCATED = 0x1802, + RECOVERED_DATA_WITH_CIRC = 0x1803, + RECOVERED_DATA_WITH_LEC = 0x1804, + RECOVERED_DATA_RECOMMEND_REASSIGNMENT = 0x1805, + RECOVERED_DATA_RECOMMEND_REWRITE = 0x1806, + RECOVERED_DATA_WITH_ECC_DATA_REWRITTEN = 0x1807, + RECOVERED_DATA_WITH_LINKING = 0x1808, + + SCSI_ASC(DEFECT_LIST_ERROR, 0x19), + DEFECT_LIST_NOT_AVAILABLE = 0x1901, + DEFECT_LIST_ERROR_IN_PRIMARY_LIST = 0x1902, + DEFECT_LIST_ERROR_IN_GROWN_LIST = 0x1903, + + SCSI_ASC(PARAMETER_LIST_LENGTH_ERROR, 0x1A), + + SCSI_ASC(SYNCHRONOUS_DATA_TRANSFER_ERROR, 0x1B), + + SCSI_ASC(DEFECT_LIST_NOT_FOUND, 0x1C), + PRIMARY_DEFECT_LIST_NOT_FOUND = 0x1C01, + GROWN_DEFECT_LIST_NOT_FOUND = 0x1C02, + + SCSI_ASC(MISCOMPARE_DURING_VERIFY_OPERATION, 0x1D), + MISCOMPARE_VERIFY_OF_UNMAPPED_LBA = 0x1D01, + + SCSI_ASC(RECOVERED_ID_WITH_ECC_CORRECTION, 0x1E), + + SCSI_ASC(PARTIAL_DEFECT_LIST_TRANSFER, 0x1F), + + SCSI_ASC(INVALID_COMMAND_OP_CODE, 0x20), + ACCESS_DENIED_INITIATOR_PENDING_ENROLLED = 0x2001, + ACCESS_DENIED_NO_ACCESS_RIGHTS = 0x2002, + ACCESS_DENIED_INVALID_MGMT_ID_KEY = 0x2003, + ILLEGAL_COMMAND_WHILE_IN_WRITE_CAPABLE_STATE = 0x2004, + ILLEGAL_COMMAND_WHILE_IN_EXPLICIT_ADDRESS_MODE = 0x2006, + ILLEGAL_COMMAND_WHILE_IN_IMPLICIT_ADDRESS_MODE = 0x2007, + ACCESS_DENIED_ENROLLMENT_CONFLICT = 0x2008, + ACCESS_DENIED_INVALID_LU_IDENTIFIER = 0x2009, + ACCESS_DENIED_INVALID_PROXY_TOKEN = 0x200A, + ACCESS_DENIED_ACL_LUN_CONFLICT = 0x200B, + ILLEGAL_COMMAND_WHEN_NOT_IN_APPEND_ONLY_MODE = 0x200C, + NOT_AN_ADMINISTRATIVE_LOGICAL_UNIT = 0x200D, + NOT_A_SUBSIDIARY_LOGICAL_UNIT = 0x200E, + NOT_A_CONGLOMERATE_LOGICAL_UNIT = 0x200F, + + SCSI_ASC(LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE, 0x21), + INVALID_ELEMENT_ADDRESS = 0x2101, + INVALID_ADDRESS_FOR_WRITE = 0x2102, + INVALID_WRITE_CROSSING_LAYER_JUMP = 0x2103, + UNALIGNED_WRITE_COMMAND = 0x2104, + WRITE_BOUNDARY_VIOLATION = 0x2105, + ATTEMPT_TO_READ_INVALID_DATA = 0x2106, + READ_BOUNDARY_VIOLATION = 0x2107, + MISALIGNED_WRITE_COMMAND = 0x2108, + ATTEMPT_TO_ACCESS_GAP_ZONE = 0x2109, + + SCSI_ASC(ILLEGAL_FUNCTION, 0x22), + + SCSI_ASC(INVALID_TOKEN_OP, 0x23), + INVALID_TOKEN_OP_UNSUPPORTED_TOKEN_TYPE = 0x2301, + INVALID_TOKEN_OP_REMOTE_TOKEN_USAGE_NOT_SUPPORTED = 0x2302, + INVALID_TOKEN_OP_REMOTE_ROD_TOKEN_CREATION_NOT_SUPPORTED = 0x2303, + INVALID_TOKEN_OP_TOKEN_UNKNOWN = 0x2304, + INVALID_TOKEN_OP_TOKEN_CORRUPT = 0x2305, + INVALID_TOKEN_OP_TOKEN_REVOKED = 0x2306, + INVALID_TOKEN_OP_TOKEN_EXPIRED = 0x2307, + INVALID_TOKEN_OP_TOKEN_CANCELLED = 0x2308, + INVALID_TOKEN_OP_TOKEN_DELETED = 0x2309, + INVALID_TOKEN_OP_INVALID_TOKEN_LENGTH = 0x230A, + + SCSI_ASC(INVALID_FIELD_IN_CDB, 0x24), + CDB_DECRYPTION_ERROR = 0x2401, + SECURITY_AUDIT_VALUE_FROZEN = 0x2404, + SECURITY_WORKING_KEY_FROZEN = 0x2405, + NONCE_NOT_UNIQUE = 0x2406, + NONCE_TIMESTAMP_OUT_OF_RANGE = 0x2407, + INVALID_XCDB = 0x2408, + INVALID_FAST_FORMAT = 0x2409, + + SCSI_ASC(LU_NOT_SUPPORTED, 0x25), + + SCSI_ASC(INVALID_FIELD_IN_PARAMETER_LIST, 0x26), + PARAMETER_NOT_SUPPORTED = 0x2601, + PARAMETER_VALUE_INVALID = 0x2602, + THRESHOLD_PARAMETERS_NOT_SUPPORTED = 0x2603, + INVALID_RELEASE_OF_PERSISTENT_RESERVATION = 0x2604, + DATA_DECRYPTION_ERROR = 0x2605, + TOO_MANY_TARGET_DESCRIPTORS = 0x2606, + UNSUPPORTED_TARGET_DESCRIPTOR_TYPE_CODE = 0x2607, + TOO_MANY_SEGMENT_DESCRIPTORS = 0x2608, + UNSUPPORTED_SEGMENT_DESCRIPTOR_TYPE_CODE = 0x2609, + UNEXPECTED_INEXACT_SEGMENT = 0x260A, + INLINE_DATA_LENGTH_EXCEEDED = 0x260B, + INVALID_OP_FOR_COPY_SOURCE_OR_DESTINATION = 0x260C, + COPY_SEGMENT_GRANULARITY_VIOLATION = 0x260D, + INVALID_PARAMETER_WHILE_PORT_IS_ENABLED = 0x260E, + INVALID_DATA_OUT_BUFFER_INTEGRITY_CHECK_VALUE = 0x260F, + DATA_DECRYPTION_KEY_FAIL_LIMIT_REACHED = 0x2610, + INCOMPLETE_KEY_ASSOCIATED_DATA_SET = 0x2611, + VENDOR_SPECIFIC_KEY_REFERENCE_NOT_FOUND = 0x2612, + APPLICATION_TAG_MODE_PAGE_IS_INVALID = 0x2613, + TAPE_STREAM_MIRRORING_PREVENTED = 0x2614, + COPY_SOURCE_OR_COPY_DESTINATION_NOT_AUTHORIZED = 0x2615, + FAST_COPY_NOT_POSSIBLE = 0x2616, + + SCSI_ASC(WRITE_PROTECTED, 0x27), + HW_WRITE_PROTECTED = 0x2701, + LU_SOFTWARE_WRITE_PROTECTED = 0x2702, + ASSOCIATED_WRITE_PROTECT = 0x2703, + PERSISTENT_WRITE_PROTECT = 0x2704, + PERMANENT_WRITE_PROTECT = 0x2705, + CONDITIONAL_WRITE_PROTECT = 0x2706, + SPACE_ALLOCATION_FAILED_WRITE_PROTECT = 0x2707, + ZONE_IS_READ_ONLY = 0x2708, + + SCSI_ASC(NOT_READY_TO_READY_CHANGE_MEDIUM_MAY_HAVE_CHANGED, 0x28), + IMPORT_OR_EXPORT_ELEMENT_ACCESSED = 0x2801, + FORMAT_LAYER_MAY_HAVE_CHANGED = 0x2802, + IMPORT_EXPORT_ELEMENT_ACCESSED_MEDIUM_CHANGED = 0x2803, + + SCSI_ASC(POWER_ON_RESET_OR_BUS_DEVICE_RESET_OCCURRED, 0x29), + POWER_ON_OCCURRED = 0x2901, + SCSI_BUS_RESET_OCCURRED = 0x2902, + BUS_DEVICE_RESET_FUNCTION_OCCURRED = 0x2903, + DEVICE_INTERNAL_RESET = 0x2904, + TRANSCEIVER_MODE_CHANGED_TO_SINGLE_ENDED = 0x2905, + TRANSCEIVER_MODE_CHANGED_TO_LVD = 0x2906, + I_T_NEXUS_LOSS_OCCURRED = 0x2907, + + SCSI_ASC(PARAMETERS_CHANGED, 0x2A), + MODE_PARAMETERS_CHANGED = 0x2A01, + LOG_PARAMETERS_CHANGED = 0x2A02, + RESERVATIONS_PREEMPTED = 0x2A03, + RESERVATIONS_RELEASED = 0x2A04, + REGISTRATIONS_PREEMPTED = 0x2A05, + ASYMMETRIC_ACCESS_STATE_CHANGED = 0x2A06, + IMPLICIT_ASYMMETRIC_ACCESS_STATE_TRANSITION_FAILED = 0x2A07, + PRIORITY_CHANGED = 0x2A08, + CAPACITY_DATA_HAS_CHANGED = 0x2A09, + ERROR_HISTORY_I_T_NEXUS_CLEARED = 0x2A0A, + ERROR_HISTORY_SNAPSHOT_RELEASED = 0x2A0B, + ERROR_RECOVERY_ATTRIBUTES_HAVE_CHANGED = 0x2A0C, + DATA_ENCRYPTION_CAPABILITIES_CHANGED = 0x2A0D, + TIMESTAMP_CHANGED = 0x2A10, + DATA_ENCRYPTION_PARAMS_CHANGED_BY_ANOTHER_I_T_NEXUS = 0x2A11, + DATA_ENCRYPTION_PARAMS_CHANGED_BY_VENDOR_SPECIFIC_EVENT = 0x2A12, + DATA_ENCRYPTION_KEY_INSTANCE_COUNTER_HAS_CHANGED = 0x2A13, + SA_CREATION_CAPABILITIES_DATA_HAS_CHANGED = 0x2A14, + MEDIUM_REMOVAL_PREVENTION_PREEMPTED = 0x2A15, + ZONE_RESET_WRITE_POINTER_RECOMMENDED = 0x2A16, + + SCSI_ASC(COPY_CANNOT_EXECUTE_SINCE_HOST_CANNOT_DISCONNECT, 0x2B), + + SCSI_ASC(COMMAND_SEQUENCE_ERROR, 0x2C), + TOO_MANY_WINDOWS_SPECIFIED = 0x2C01, + INVALID_COMBINATION_OF_WINDOWS_SPECIFIED = 0x2C02, + CURRENT_PROGRAM_AREA_IS_NOT_EMPTY = 0x2C03, + CURRENT_PROGRAM_AREA_IS_EMPTY = 0x2C04, + ILLEGAL_POWER_CONDITION_REQUEST = 0x2C05, + PERSISTENT_PREVENT_CONFLICT = 0x2C06, + PREVIOUS_BUSY_STATUS = 0x2C07, + PREVIOUS_TASK_SET_FULL_STATUS = 0x2C08, + PREVIOUS_RESERVATION_CONFLICT_STATUS = 0x2C09, + PARTITION_OR_COLLECTION_CONTAINS_USER_OBJECTS = 0x2C0A, + NOT_RESERVED = 0x2C0B, + ORWRITE_GENERATION_DOES_NOT_MATCH = 0x2C0C, + RESET_WRITE_POINTER_NOT_ALLOWED = 0x2C0D, + ZONE_IS_OFFLINE = 0x2C0E, + STREAM_NOT_OPEN = 0x2C0F, + UNWRITTEN_DATA_IN_ZONE = 0x2C10, + DESCRIPTOR_FORMAT_SENSE_DATA_REQUIRED = 0x2C11, + ZONE_IS_INACTIVE = 0x2C12, + WELL_KNOWN_LU_ACCESS_REQUIRED = 0x2C13, + + SCSI_ASC(OVERWRITE_ERROR_ON_UPDATE_IN_PLACE, 0x2D), + + SCSI_ASC(INSUFFICIENT_TIME_FOR_OPERATION, 0x2E), + COMMAND_TIMEOUT_BEFORE_PROCESSING = 0x2E01, + COMMAND_TIMEOUT_DURING_PROCESSING = 0x2E02, + COMMAND_TIMEOUT_DURING_PROCESSING_DUE_TO_ERROR_RECOVERY = 0x2E03, + + SCSI_ASC(COMMANDS_CLEARED_BY_ANOTHER_INITIATOR, 0x2F), + COMMANDS_CLEARED_BY_POWER_LOSS_NOTIFICATION = 0x2F01, + COMMANDS_CLEARED_BY_DEVICE_SERVER = 0x2F02, + SOME_COMMANDS_CLEARED_BY_QUEUING_LAYER_EVENT = 0x2F03, + + SCSI_ASC(INCOMPATIBLE_MEDIUM_INSTALLED, 0x30), + CANNOT_READ_MEDIUM_UNKNOWN_FORMAT = 0x3001, + CANNOT_READ_MEDIUM_INCOMPATIBLE_FORMAT = 0x3002, + CLEANING_CARTRIDGE_INSTALLED = 0x3003, + CANNOT_WRITE_MEDIUM_UNKNOWN_FORMAT = 0x3004, + CANNOT_WRITE_MEDIUM_INCOMPATIBLE_FORMAT = 0x3005, + CANNOT_FORMAT_MEDIUM_INCOMPATIBLE_MEDIUM = 0x3006, + CLEANING_FAILURE = 0x3007, + CANNOT_WRITE_APPLICATION_CODE_MISMATCH = 0x3008, + CURRENT_SESSION_NOT_FIXATED_FOR_APPEND = 0x3009, + CLEANING_REQUEST_REJECTED = 0x300A, + WORM_MEDIUM_OVERWRITE_ATTEMPTED = 0x300C, + WORM_MEDIUM_INTEGRITY_CHECK = 0x300D, + MEDIUM_NOT_FORMATTED = 0x3010, + INCOMPATIBLE_VOLUME_TYPE = 0x3011, + INCOMPATIBLE_VOLUME_QUALIFIER = 0x3012, + CLEANING_VOLUME_EXPIRED = 0x3013, + + SCSI_ASC(MEDIUM_FORMAT_CORRUPTED, 0x31), + FORMAT_COMMAND_FAILED = 0x3101, + ZONED_FORMATTING_FAILED_DUE_TO_SPARE_LINKING = 0x3102, + SANITIZE_COMMAND_FAILED = 0x3103, + DEPOPULATION_FAILED = 0x3104, + DEPOPULATION_RESTORATION_FAILED = 0x3105, + + SCSI_ASC(NO_DEFECT_SPARE_LOCATION_AVAILABLE, 0x32), + DEFECT_LIST_UPDATE_FAILURE = 0x3201, + + SCSI_ASC(TAPE_LENGTH_ERROR, 0x33), + + SCSI_ASC(ENCLOSURE_FAILURE, 0x34), + + SCSI_ASC(ENCLOSURE_SERVICES_FAILURE, 0x35), + UNSUPPORTED_ENCLOSURE_FUNCTION = 0x3501, + ENCLOSURE_SERVICES_UNAVAILABLE = 0x3502, + ENCLOSURE_SERVICES_TRANSFER_FAILURE = 0x3503, + ENCLOSURE_SERVICES_TRANSFER_REFUSED = 0x3504, + ENCLOSURE_SERVICES_CHECKSUM_ERROR = 0x3505, + + SCSI_ASC(RIBBON_INK_OR_TONER_FAILURE, 0x36), + + SCSI_ASC(ROUNDED_PARAMETER, 0x37), + + SCSI_ASC(EVENT_STATUS_NOTIFICATION, 0x38), + ESN_POWER_MANAGEMENT_CLASS_EVENT = 0x3802, + ESN_MEDIA_CLASS_EVENT = 0x3804, + ESN_DEVICE_BUSY_CLASS_EVENT = 0x3806, + THIN_PROVISIONING_SOFT_THRESHOLD_REACHED = 0x3807, + DEPOPULATION_INTERRUPTED = 0x3808, + DEPOPULATION_RESTORATION_INTERRUPTED = 0x3809, + + SCSI_ASC(SAVING_PARAMETERS_NOT_SUPPORTED, 0x39), + + SCSI_ASC(MEDIUM_NOT_PRESENT, 0x3A), + MEDIUM_NOT_PRESENT_TRAY_CLOSED = 0x3A01, + MEDIUM_NOT_PRESENT_TRAY_OPEN = 0x3A02, + MEDIUM_NOT_PRESENT_LOADABLE = 0x3A03, + MEDIUM_NOT_PRESENT_MEDIUM_AUXILIARY_MEMORY_ACCESSIBLE = 0x3A04, + + SCSI_ASC(SEQUENTIAL_POSITIONING_ERROR, 0x3B), + TAPE_POSITION_ERROR_AT_BEGINNING_OF_MEDIUM = 0x3B01, + TAPE_POSITION_ERROR_AT_END_OF_MEDIUM = 0x3B02, + TAPE_OR_ELECTRONIC_VERTICAL_FORMS_UNIT_NOT_READY = 0x3B03, + SLEW_FAILURE = 0x3B04, + PAPER_JAM = 0x3B05, + FAILED_TO_SENSE_TOP_OF_FORM = 0x3B06, + FAILED_TO_SENSE_BOTTOM_OF_FORM = 0x3B07, + REPOSITION_ERROR = 0x3B08, + READ_PAST_END_OF_MEDIUM = 0x3B09, + READ_PAST_BEGINNING_OF_MEDIUM = 0x3B0A, + POSITION_PAST_END_OF_MEDIUM = 0x3B0B, + POSITION_PAST_BEGINNING_OF_MEDIUM = 0x3B0C, + MEDIUM_DESTINATION_ELEMENT_FULL = 0x3B0D, + MEDIUM_SOURCE_ELEMENT_EMPTY = 0x3B0E, + END_OF_MEDIUM_REACHED = 0x3B0F, + MEDIUM_MAGAZINE_NOT_ACCESSIBLE = 0x3B11, + MEDIUM_MAGAZINE_REMOVED = 0x3B12, + MEDIUM_MAGAZINE_INSERTED = 0x3B13, + MEDIUM_MAGAZINE_LOCKED = 0x3B14, + MEDIUM_MAGAZINE_UNLOCKED = 0x3B15, + MECHANICAL_POSITIONING_OR_CHANGER_ERROR = 0x3B16, + READ_PAST_END_OF_USER_OBJECT = 0x3B17, + ELEMENT_DISABLED = 0x3B18, + ELEMENT_ENABLED = 0x3B19, + DATA_TRANSFER_DEVICE_REMOVED = 0x3B1A, + DATA_TRANSFER_DEVICE_INSERTED = 0x3B1B, + TOO_MANY_LOGICAL_OBJECTS_ON_PARTITION_TO_SUPPORT_OP = 0x3B1C, + ELEMENT_STATIC_INFORMATION_CHANGED = 0x3B20, + + SCSI_ASC(INVALID_BITS_IN_IDENTIFY_MESSAGE, 0x3D), + + SCSI_ASC(LU_HAS_NOT_SELF_CONFIGURED_YET, 0x3E), + LU_FAILURE = 0x3E01, + TIMEOUT_ON_LOGICAL_UNIT = 0x3E02, + LU_FAILED_SELF_TEST = 0x3E03, + LU_UNABLE_TO_UPDATE_SELFTEST_LOG = 0x3E04, + + SCSI_ASC(TARGET_OPERATING_CONDITIONS_HAVE_CHANGED, 0x3F), + MICROCODE_HAS_BEEN_CHANGED = 0x3F01, + CHANGED_OPERATING_DEFINITION = 0x3F02, + INQUIRY_DATA_HAS_CHANGED = 0x3F03, + COMPONENT_DEVICE_ATTACHED = 0x3F04, + DEVICE_IDENTIFIER_CHANGED = 0x3F05, + REDUNDANCY_GROUP_CREATED_OR_MODIFIED = 0x3F06, + REDUNDANCY_GROUP_DELETED = 0x3F07, + SPARE_CREATED_OR_MODIFIED = 0x3F08, + SPARE_DELETED = 0x3F09, + VOLUME_SET_CREATED_OR_MODIFIED = 0x3F0A, + VOLUME_SET_DELETED = 0x3F0B, + VOLUME_SET_DEASSIGNED = 0x3F0C, + VOLUME_SET_REASSIGNED = 0x3F0D, + REPORTED_LUNS_DATA_HAS_CHANGED = 0x3F0E, + ECHO_BUFFER_OVERWRITTEN = 0x3F0F, + MEDIUM_LOADABLE = 0x3F10, + MEDIUM_AUXILIARY_MEMORY_ACCESSIBLE = 0x3F11, + iSCSI_IP_ADDRESS_ADDED = 0x3F12, + iSCSI_IP_ADDRESS_REMOVED = 0x3F13, + iSCSI_IP_ADDRESS_CHANGED = 0x3F14, + INSPECT_REFERRALS_SENSE_DESCRIPTORS = 0x3F15, + MICROCODE_HAS_BEEN_CHANGED_WITHOUT_RESET = 0x3F16, + ZONE_TRANSITION_TO_FULL = 0x3F17, + BIND_COMPLETED = 0x3F18, + BIND_REDIRECTED = 0x3F19, + SUBSIDIARY_BINDING_CHANGED = 0x3F1A, + + SCSI_ASC(RAM_FAILURE, 0x40), + /* DIAGNOSTIC_FAILURE_ON_COMPONENT_NN = 0x40NN */ + + SCSI_ASC(DATA_PATH_FAILURE, 0x41), + + SCSI_ASC(POWER_ON_OR_SELFTEST_FAILURE, 0x42), + + SCSI_ASC(MESSAGE_ERROR, 0x43), + + SCSI_ASC(INTERNAL_TARGET_FAILURE, 0x44), + PERSISTENT_RESERVATION_INFORMATION_LOST = 0x4401, + ATA_DEVICE_FAILED_SET_FEATURES = 0x4471, + + SCSI_ASC(SELECT_OR_RESELECT_FAILURE, 0x45), + + SCSI_ASC(UNSUCCESSFUL_SOFT_RESET, 0x46), + + SCSI_ASC(SCSI_PARITY_ERROR, 0x47), + DATA_PHASE_CRC_ERROR_DETECTED = 0x4701, + SCSI_PARITY_ERROR_DETECTED_DURING_ST_DATA_PHASE = 0x4702, + INFORMATION_UNIT_iuCRC_ERROR_DETECTED = 0x4703, + ASYNCHRONOUS_INFORMATION_PROTECTION_ERROR_DETECTED = 0x4704, + PROTOCOL_SERVICE_CRC_ERROR = 0x4705, + PHY_TEST_FUNCTION_IN_PROGRESS = 0x4706, + SOME_COMMANDS_CLEARED_BY_ISCSI_PROTOCOL_EVENT = 0x477F, + + SCSI_ASC(INITIATOR_DETECTED_ERROR_MESSAGE_RECEIVED, 0x48), + + SCSI_ASC(INVALID_MESSAGE_ERROR, 0x49), + + SCSI_ASC(COMMAND_PHASE_ERROR, 0x4A), + + SCSI_ASC(DATA_PHASE_ERROR, 0x4B), + INVALID_TARGET_PORT_TRANSFER_TAG_RECEIVED = 0x4B01, + TOO_MUCH_WRITE_DATA = 0x4B02, + ACK_NAK_TIMEOUT = 0x4B03, + NAK_RECEIVED = 0x4B04, + DATA_OFFSET_ERROR = 0x4B05, + INITIATOR_RESPONSE_TIMEOUT = 0x4B06, + CONNECTION_LOST = 0x4B07, + DATA_IN_BUFFER_OVERFLOW_BUFFER_SIZE = 0x4B08, + DATA_IN_BUFFER_OVERFLOW_BUFFER_DESCRIPTOR_AREA = 0x4B09, + DATA_IN_BUFFER_ERROR = 0x4B0A, + DATA_OUT_BUFFER_OVERFLOW_BUFFER_SIZE = 0x4B0B, + DATA_OUT_BUFFER_OVERFLOW_BUFFER_DESCRIPTOR_AREA = 0x4B0C, + DATA_OUT_BUFFER_ERROR = 0x4B0D, + PCIE_FABRIC_ERROR = 0x4B0E, + PCIE_COMPLETION_TIMEOUT = 0x4B0F, + PCIE_COMPLETER_ABORT = 0x4B10, + PCIE_POISONED_TLP_RECEIVED = 0x4B11, + PCIE_ECRC_CHECK_FAILED = 0x4B12, + PCIE_UNSUPPORTED_REQUEST = 0x4B13, + PCIE_ACS_VIOLATION = 0x4B14, + PCIE_TLP_PREFIX_BLOCKED = 0x4B15, + + SCSI_ASC(LU_FAILED_SELF_CONFIGURATION, 0x4C), + + SCSI_ASC(TAGGED_OVERLAPPED_COMMANDS, 0x4D), + + SCSI_ASC(OVERLAPPED_COMMANDS_ATTEMPTED, 0x4E), + + SCSI_ASC(WRITE_APPEND_ERROR, 0x50), + WRITE_APPEND_POSITION_ERROR = 0x5001, + POSITION_ERROR_RELATED_TO_TIMING = 0x5002, + + SCSI_ASC(ERASE_FAILURE, 0x51), + ERASE_FAILURE_INCOMPLETE_ERASE_OP_DETECTED = 0x5101, + + SCSI_ASC(CARTRIDGE_FAULT, 0x52), + + SCSI_ASC(MEDIA_LOAD_OR_EJECT_FAILED, 0x53), + UNLOAD_TAPE_FAILURE = 0x5301, + MEDIUM_REMOVAL_PREVENTED = 0x5302, + MEDIUM_REMOVAL_PREVENTED_BY_DATA_TRANSFER_ELEMENT = 0x5303, + MEDIUM_THREAD_OR_UNTHREAD_FAILURE = 0x5304, + VOLUME_IDENTIFIER_INVALID = 0x5305, + VOLUME_IDENTIFIER_MISSING = 0x5306, + DUPLICATE_VOLUME_IDENTIFIER = 0x5307, + ELEMENT_STATUS_UNKNOWN = 0x5308, + DATA_TRANSFER_DEVICE_ERR_LOAD_FAILED = 0x5309, + DATA_TRANSFER_DEVICE_ERR_UNLOAD_FAILED = 0x530A, + DATA_TRANSFER_DEVICE_ERR_UNLOAD_MISSING = 0x530B, + DATA_TRANSFER_DEVICE_ERR_EJECT_FAILED = 0x530C, + DATA_TRANSFER_DEVICE_ERR_LIBRARY_COMMUNICATION_FAILED = 0x530D, + + SCSI_ASC(SCSI_TO_HOST_SYSTEM_INTERFACE_FAILURE, 0x54), + + SCSI_ASC(SYSTEM_RESOURCE_FAILURE, 0x55), + SYSTEM_BUFFER_FULL = 0x5501, + INSUFFICIENT_RESERVATION_RESOURCES = 0x5502, + INSUFFICIENT_RESOURCES = 0x5503, + INSUFFICIENT_REGISTRATION_RESOURCES = 0x5504, + INSUFFICIENT_ACCESS_CONTROL_RESOURCES = 0x5505, + AUXILIARY_MEMORY_OUT_OF_SPACE = 0x5506, + QUOTA_ERROR = 0x5507, + MAXIMUM_NUMBER_OF_SUPPLEMENTAL_DECRYPTION_KEYS_EXCEEDED = 0x5508, + MEDIUM_AUXILIARY_MEMORY_NOT_ACCESSIBLE = 0x5509, + DATA_CURRENTLY_UNAVAILABLE = 0x550A, + INSUFFICIENT_POWER_FOR_OPERATION = 0x550B, + INSUFFICIENT_RESOURCES_TO_CREATE_ROD = 0x550C, + INSUFFICIENT_RESOURCES_TO_CREATE_ROD_TOKEN = 0x550D, + INSUFFICIENT_ZONE_RESOURCES = 0x550E, + INSUFFICIENT_ZONE_RESOURCES_TO_COMPLETE_WRITE = 0x550F, + MAXIMUM_NUMBER_OF_STREAMS_OPEN = 0x5510, + INSUFFICIENT_RESOURCES_TO_BIND = 0x5511, + + SCSI_ASC(UNABLE_TO_RECOVER_TABLE_OF_CONTENTS, 0x57), + + SCSI_ASC(GENERATION_DOES_NOT_EXIST, 0x58), + + SCSI_ASC(UPDATED_BLOCK_READ, 0x59), + + SCSI_ASC(OPERATOR_REQUEST_OR_STATE_CHANGE_INPUT, 0x5A), + OPERATOR_MEDIUM_REMOVAL_REQUEST = 0x5A01, + OPERATOR_SELECTED_WRITE_PROTECT = 0x5A02, + OPERATOR_SELECTED_WRITE_PERMIT = 0x5A03, + + SCSI_ASC(LOG_EXCEPTION, 0x5B), + THRESHOLD_CONDITION_MET = 0x5B01, + LOG_COUNTER_AT_MAXIMUM = 0x5B02, + LOG_LIST_CODES_EXHAUSTED = 0x5B03, + + SCSI_ASC(RPL_STATUS_CHANGE, 0x5C), + SPINDLES_SYNCHRONIZED = 0x5C01, + SPINDLES_NOT_SYNCHRONIZED = 0x5C02, + + SCSI_ASC(FAILURE_PREDICTION_THRESHOLD_EXCEEDED, 0x5D), + MEDIA_FAILURE_PREDICTION_THRESHOLD_EXCEEDED = 0x5D01, + LU_FAILURE_PREDICTION_THRESHOLD_EXCEEDED = 0x5D02, + SPARE_AREA_EXHAUSTION_PREDICTION_THRESHOLD_EXCEEDED = 0x5D03, + HW_IMPENDING_FAILURE_GENERAL_HARD_DRIVE_FAILURE = 0x5D10, + HW_IMPENDING_FAILURE_DRIVE_ERROR_RATE_TOO_HIGH = 0x5D11, + HW_IMPENDING_FAILURE_DATA_ERROR_RATE_TOO_HIGH = 0x5D12, + HW_IMPENDING_FAILURE_SEEK_ERROR_RATE_TOO_HIGH = 0x5D13, + HW_IMPENDING_FAILURE_TOO_MANY_BLOCK_REASSIGNS = 0x5D14, + HW_IMPENDING_FAILURE_ACCESS_TIMES_TOO_HIGH = 0x5D15, + HW_IMPENDING_FAILURE_START_UNIT_TIMES_TOO_HIGH = 0x5D16, + HW_IMPENDING_FAILURE_CHANNEL_PARAMETRICS = 0x5D17, + HW_IMPENDING_FAILURE_CONTROLLER_DETECTED = 0x5D18, + HW_IMPENDING_FAILURE_THROUGHPUT_PERFORMANCE = 0x5D19, + HW_IMPENDING_FAILURE_SEEK_TIME_PERFORMANCE = 0x5D1A, + HW_IMPENDING_FAILURE_SPINUP_RETRY_COUNT = 0x5D1B, + HW_IMPENDING_FAILURE_DRIVE_CALIBRATION_RETRY_COUNT = 0x5D1C, + HW_IMPENDING_FAILURE_POWER_LOSS_PROTECTION_CIRCUIT = 0x5D1D, + CONTROLLER_IMPENDING_FAILURE_GENERAL_HARD_DRIVE_FAILURE = 0x5D20, + CONTROLLER_IMPENDING_FAILURE_DRIVE_ERROR_RATE_TOO_HIGH = 0x5D21, + CONTROLLER_IMPENDING_FAILURE_DATA_ERROR_RATE_TOO_HIGH = 0x5D22, + CONTROLLER_IMPENDING_FAILURE_SEEK_ERROR_RATE_TOO_HIGH = 0x5D23, + CONTROLLER_IMPENDING_FAILURE_TOO_MANY_BLOCK_REASSIGNS = 0x5D24, + CONTROLLER_IMPENDING_FAILURE_ACCESS_TIMES_TOO_HIGH = 0x5D25, + CONTROLLER_IMPENDING_FAILURE_START_UNIT_TIMES_TOO_HIGH = 0x5D26, + CONTROLLER_IMPENDING_FAILURE_CHANNEL_PARAMETRICS = 0x5D27, + CONTROLLER_IMPENDING_FAILURE_CONTROLLER_DETECTED = 0x5D28, + CONTROLLER_IMPENDING_FAILURE_THROUGHPUT_PERFORMANCE = 0x5D29, + CONTROLLER_IMPENDING_FAILURE_SEEK_TIME_PERFORMANCE = 0x5D2A, + CONTROLLER_IMPENDING_FAILURE_SPINUP_RETRY_COUNT = 0x5D2B, + CONTROLLER_IMPENDING_FAILURE_DRIVE_CALIBRATION_RETRY_COUNT = 0x5D2C, + DATA_CHANNEL_IMPENDING_FAILURE_GENERAL_HARD_DRIVE_FAILURE = 0x5D30, + DATA_CHANNEL_IMPENDING_FAILURE_DRIVE_ERROR_RATE_TOO_HIGH = 0x5D31, + DATA_CHANNEL_IMPENDING_FAILURE_DATA_ERROR_RATE_TOO_HIGH = 0x5D32, + DATA_CHANNEL_IMPENDING_FAILURE_SEEK_ERROR_RATE_TOO_HIGH = 0x5D33, + DATA_CHANNEL_IMPENDING_FAILURE_TOO_MANY_BLOCK_REASSIGNS = 0x5D34, + DATA_CHANNEL_IMPENDING_FAILURE_ACCESS_TIMES_TOO_HIGH = 0x5D35, + DATA_CHANNEL_IMPENDING_FAILURE_START_UNIT_TIMES_TOO_HIGH = 0x5D36, + DATA_CHANNEL_IMPENDING_FAILURE_CHANNEL_PARAMETRICS = 0x5D37, + DATA_CHANNEL_IMPENDING_FAILURE_CONTROLLER_DETECTED = 0x5D38, + DATA_CHANNEL_IMPENDING_FAILURE_THROUGHPUT_PERFORMANCE = 0x5D39, + DATA_CHANNEL_IMPENDING_FAILURE_SEEK_TIME_PERFORMANCE = 0x5D3A, + DATA_CHANNEL_IMPENDING_FAILURE_SPINUP_RETRY_COUNT = 0x5D3B, + DATA_CHANNEL_IMPENDING_FAILURE_DRIVE_CALIBRATION_RETRY_COUNT = 0x5D3C, + SERVO_IMPENDING_FAILURE_GENERAL_HARD_DRIVE_FAILURE = 0x5D40, + SERVO_IMPENDING_FAILURE_DRIVE_ERROR_RATE_TOO_HIGH = 0x5D41, + SERVO_IMPENDING_FAILURE_DATA_ERROR_RATE_TOO_HIGH = 0x5D42, + SERVO_IMPENDING_FAILURE_SEEK_ERROR_RATE_TOO_HIGH = 0x5D43, + SERVO_IMPENDING_FAILURE_TOO_MANY_BLOCK_REASSIGNS = 0x5D44, + SERVO_IMPENDING_FAILURE_ACCESS_TIMES_TOO_HIGH = 0x5D45, + SERVO_IMPENDING_FAILURE_START_UNIT_TIMES_TOO_HIGH = 0x5D46, + SERVO_IMPENDING_FAILURE_CHANNEL_PARAMETRICS = 0x5D47, + SERVO_IMPENDING_FAILURE_CONTROLLER_DETECTED = 0x5D48, + SERVO_IMPENDING_FAILURE_THROUGHPUT_PERFORMANCE = 0x5D49, + SERVO_IMPENDING_FAILURE_SEEK_TIME_PERFORMANCE = 0x5D4A, + SERVO_IMPENDING_FAILURE_SPINUP_RETRY_COUNT = 0x5D4B, + SERVO_IMPENDING_FAILURE_DRIVE_CALIBRATION_RETRY_COUNT = 0x5D4C, + SPINDLE_IMPENDING_FAILURE_GENERAL_HARD_DRIVE_FAILURE = 0x5D50, + SPINDLE_IMPENDING_FAILURE_DRIVE_ERROR_RATE_TOO_HIGH = 0x5D51, + SPINDLE_IMPENDING_FAILURE_DATA_ERROR_RATE_TOO_HIGH = 0x5D52, + SPINDLE_IMPENDING_FAILURE_SEEK_ERROR_RATE_TOO_HIGH = 0x5D53, + SPINDLE_IMPENDING_FAILURE_TOO_MANY_BLOCK_REASSIGNS = 0x5D54, + SPINDLE_IMPENDING_FAILURE_ACCESS_TIMES_TOO_HIGH = 0x5D55, + SPINDLE_IMPENDING_FAILURE_START_UNIT_TIMES_TOO_HIGH = 0x5D56, + SPINDLE_IMPENDING_FAILURE_CHANNEL_PARAMETRICS = 0x5D57, + SPINDLE_IMPENDING_FAILURE_CONTROLLER_DETECTED = 0x5D58, + SPINDLE_IMPENDING_FAILURE_THROUGHPUT_PERFORMANCE = 0x5D59, + SPINDLE_IMPENDING_FAILURE_SEEK_TIME_PERFORMANCE = 0x5D5A, + SPINDLE_IMPENDING_FAILURE_SPINUP_RETRY_COUNT = 0x5D5B, + SPINDLE_IMPENDING_FAILURE_DRIVE_CALIBRATION_RETRY_COUNT = 0x5D5C, + FW_IMPENDING_FAILURE_GENERAL_HARD_DRIVE_FAILURE = 0x5D60, + FW_IMPENDING_FAILURE_DRIVE_ERROR_RATE_TOO_HIGH = 0x5D61, + FW_IMPENDING_FAILURE_DATA_ERROR_RATE_TOO_HIGH = 0x5D62, + FW_IMPENDING_FAILURE_SEEK_ERROR_RATE_TOO_HIGH = 0x5D63, + FW_IMPENDING_FAILURE_TOO_MANY_BLOCK_REASSIGNS = 0x5D64, + FW_IMPENDING_FAILURE_ACCESS_TIMES_TOO_HIGH = 0x5D65, + FW_IMPENDING_FAILURE_START_UNIT_TIMES_TOO_HIGH = 0x5D66, + FW_IMPENDING_FAILURE_CHANNEL_PARAMETRICS = 0x5D67, + FW_IMPENDING_FAILURE_CONTROLLER_DETECTED = 0x5D68, + FW_IMPENDING_FAILURE_THROUGHPUT_PERFORMANCE = 0x5D69, + FW_IMPENDING_FAILURE_SEEK_TIME_PERFORMANCE = 0x5D6A, + FW_IMPENDING_FAILURE_SPINUP_RETRY_COUNT = 0x5D6B, + FW_IMPENDING_FAILURE_DRIVE_CALIBRATION_RETRY_COUNT = 0x5D6C, + MEDIA_IMPENDING_FAILURE_ENDURANCE_LIMIT_MET = 0x5D73, + FAILURE_PREDICTION_THRESHOLD_EXCEEDED_FALSE = 0x5DFF, + + SCSI_ASC(LOW_POWER_CONDITION_ON, 0x5E), + IDLE_CONDITION_ACTIVATED_BY_TIMER = 0x5E01, + STANDBY_CONDITION_ACTIVATED_BY_TIMER = 0x5E02, + IDLE_CONDITION_ACTIVATED_BY_COMMAND = 0x5E03, + STANDBY_CONDITION_ACTIVATED_BY_COMMAND = 0x5E04, + IDLE_B_CONDITION_ACTIVATED_BY_TIMER = 0x5E05, + IDLE_B_CONDITION_ACTIVATED_BY_COMMAND = 0x5E06, + IDLE_C_CONDITION_ACTIVATED_BY_TIMER = 0x5E07, + IDLE_C_CONDITION_ACTIVATED_BY_COMMAND = 0x5E08, + STANDBY_Y_CONDITION_ACTIVATED_BY_TIMER = 0x5E09, + STANDBY_Y_CONDITION_ACTIVATED_BY_COMMAND = 0x5E0A, + POWER_STATE_CHANGE_TO_ACTIVE = 0x5E41, + POWER_STATE_CHANGE_TO_IDLE = 0x5E42, + POWER_STATE_CHANGE_TO_STANDBY = 0x5E43, + POWER_STATE_CHANGE_TO_SLEEP = 0x5E45, + POWER_STATE_CHANGE_TO_DEVICE_CONTROL = 0x5E47, + + SCSI_ASC(LAMP_FAILURE, 0x60), + + SCSI_ASC(VIDEO_ACQUISITION_ERROR, 0x61), + UNABLE_TO_ACQUIRE_VIDEO = 0x6101, + OUT_OF_FOCUS = 0x6102, + + SCSI_ASC(SCAN_HEAD_POSITIONING_ERROR, 0x62), + + SCSI_ASC(END_OF_USER_AREA_ENCOUNTERED_ON_THIS_TRACK, 0x63), + PACKET_DOES_NOT_FIT_IN_AVAILABLE_SPACE = 0x6301, + + SCSI_ASC(ILLEGAL_MODE_FOR_THIS_TRACK, 0x64), + INVALID_PACKET_SIZE = 0x6401, + + SCSI_ASC(VOLTAGE_FAULT, 0x65), + + SCSI_ASC(AUTOMATIC_DOCUMENT_FEEDER_COVER_UP, 0x66), + AUTOMATIC_DOCUMENT_FEEDER_LIFT_UP = 0x6601, + DOCUMENT_JAM_IN_AUTOMATIC_DOCUMENT_FEEDER = 0x6602, + DOCUMENT_MISS_FEED_AUTOMATIC_IN_DOCUMENT_FEEDER = 0x6603, + + SCSI_ASC(CONFIG_FAILURE, 0x67), + CONFIG_OF_INCAPABLE_LOGICAL_UNITS_FAILED = 0x6701, + ADD_LU_FAILED = 0x6702, + MODIFICATION_OF_LU_FAILED = 0x6703, + EXCHANGE_OF_LU_FAILED = 0x6704, + REMOVE_OF_LU_FAILED = 0x6705, + ATTACHMENT_OF_LU_FAILED = 0x6706, + CREATION_OF_LU_FAILED = 0x6707, + ASSIGN_FAILURE_OCCURRED = 0x6708, + MULTIPLY_ASSIGNED_LOGICAL_UNIT = 0x6709, + SET_TARGET_PORT_GROUPS_COMMAND_FAILED = 0x670A, + ATA_DEVICE_FEATURE_NOT_ENABLED = 0x670B, + COMMAND_REJECTED = 0x670C, + EXPLICIT_BIND_NOT_ALLOWED = 0x670D, + FEATURE_NOT_ENABLED = 0x670E, + + SCSI_ASC(LU_NOT_CONFIGURED, 0x68), + SUBSIDIARY_LU_NOT_CONFIGURED = 0x6801, + + SCSI_ASC(DATA_LOSS_ON_LOGICAL_UNIT, 0x69), + MULTIPLE_LU_FAILURES = 0x6901, + PARITY_DATA_MISMATCH = 0x6902, + + SCSI_ASC(INFORMATIONAL_REFER_TO_LOG, 0x6A), + + SCSI_ASC(STATE_CHANGE_HAS_OCCURRED, 0x6B), + REDUNDANCY_LEVEL_GOT_BETTER = 0x6B01, + REDUNDANCY_LEVEL_GOT_WORSE = 0x6B02, + + SCSI_ASC(REBUILD_FAILURE_OCCURRED, 0x6C), + + SCSI_ASC(RECALCULATE_FAILURE_OCCURRED, 0x6D), + + SCSI_ASC(COMMAND_TO_LU_FAILED, 0x6E), + + SCSI_ASC(COPY_PROTECTION_KEY_EXCHANGE_FAILURE_AUTHENTICATION_FAILURE, 0x6F), + COPY_PROTECTION_KEY_EXCHANGE_FAILURE_KEY_NOT_PRESENT = 0x6F01, + COPY_PROTECTION_KEY_EXCHANGE_FAILURE_KEY_NOT_ESTABLISHED = 0x6F02, + READ_OF_SCRAMBLED_SECTOR_WITHOUT_AUTHENTICATION = 0x6F03, + MEDIA_REGION_CODE_IS_MISMATCHED_TO_LU_REGION = 0x6F04, + DRIVE_REGION_MUST_BE_PERMANENT_REGION_RESET_COUNT_ERROR = 0x6F05, + INSUFFICIENT_BLOCK_COUNT_FOR_BINDING_NONCE_RECORDING = 0x6F06, + CONFLICT_IN_BINDING_NONCE_RECORDING = 0x6F07, + INSUFFICIENT_PERMISSION = 0x6F08, + INVALID_DRIVE_HOST_PAIRING_SERVER = 0x6F09, + DRIVE_HOST_PAIRING_SUSPENDED = 0x6F0A, + + SCSI_ASC(DECOMPRESSION_EXCEPTION_SHORT_ALGORITHM_ID, 0x70), + + SCSI_ASC(DECOMPRESSION_EXCEPTION_LONG_ALGORITHM_ID, 0x71), + + SCSI_ASC(SESSION_FIXATION_ERROR, 0x72), + SESSION_FIXATION_ERROR_WRITING_LEAD_IN = 0x7201, + SESSION_FIXATION_ERROR_WRITING_LEAD_OUT = 0x7202, + SESSION_FIXATION_ERROR_INCOMPLETE_TRACK_IN_SESSION = 0x7203, + EMPTY_OR_PARTIALLY_WRITTEN_RESERVED_TRACK = 0x7204, + NO_MORE_TRACK_RESERVATIONS_ALLOWED = 0x7205, + RMZ_EXTENSION_IS_NOT_ALLOWED = 0x7206, + NO_MORE_TEST_ZONE_EXTENSIONS_ARE_ALLOWED = 0x7207, + + SCSI_ASC(CD_CONTROL_ERROR, 0x73), + POWER_CALIBRATION_AREA_ALMOST_FULL = 0x7301, + POWER_CALIBRATION_AREA_IS_FULL = 0x7302, + POWER_CALIBRATION_AREA_ERROR = 0x7303, + PROGRAM_MEMORY_AREA_UPDATE_FAILURE = 0x7304, + PROGRAM_MEMORY_AREA_IS_FULL = 0x7305, + RMA_PMA_IS_ALMOST_FULL = 0x7306, + CURRENT_POWER_CALIBRATION_AREA_ALMOST_FULL = 0x7310, + CURRENT_POWER_CALIBRATION_AREA_IS_FULL = 0x7311, + RDZ_IS_FULL = 0x7317, + + SCSI_ASC(SECURITY_ERROR, 0x74), + UNABLE_TO_DECRYPT_DATA = 0x7401, + UNENCRYPTED_DATA_ENCOUNTERED_WHILE_DECRYPTING = 0x7402, + INCORRECT_DATA_ENCRYPTION_KEY = 0x7403, + CRYPTOGRAPHIC_INTEGRITY_VALIDATION_FAILED = 0x7404, + ERROR_DECRYPTING_DATA = 0x7405, + UNKNOWN_SIGNATURE_VERIFICATION_KEY = 0x7406, + ENCRYPTION_PARAMS_NOT_USEABLE = 0x7407, + DIGITAL_SIGNATURE_VALIDATION_FAILURE = 0x7408, + ENCRYPTION_MODE_MISMATCH_ON_READ = 0x7409, + ENCRYPTED_BLOCK_NOT_RAW_READ_ENABLED = 0x740A, + INCORRECT_ENCRYPTION_PARAMS = 0x740B, + UNABLE_TO_DECRYPT_PARAMETER_LIST = 0x740C, + ENCRYPTION_ALGORITHM_DISABLED = 0x740D, + SA_CREATION_PARAMETER_VALUE_INVALID = 0x7410, + SA_CREATION_PARAMETER_VALUE_REJECTED = 0x7411, + INVALID_SA_USAGE = 0x7412, + DATA_ENCRYPTION_CONFIG_PREVENTED = 0x7421, + SA_CREATION_PARAMETER_NOT_SUPPORTED = 0x7430, + AUTHENTICATION_FAILED = 0x7440, + EXTERNAL_DATA_ENCRYPTION_KEY_MANAGER_ACCESS_ERROR = 0x7461, + EXTERNAL_DATA_ENCRYPTION_KEY_MANAGER_ERROR = 0x7462, + EXTERNAL_DATA_ENCRYPTION_KEY_NOT_FOUND = 0x7463, + EXTERNAL_DATA_ENCRYPTION_REQUEST_NOT_AUTHORIZED = 0x7464, + EXTERNAL_DATA_ENCRYPTION_CONTROL_TIMEOUT = 0x746E, + EXTERNAL_DATA_ENCRYPTION_CONTROL_ERROR = 0x746F, + LU_ACCESS_NOT_AUTHORIZED = 0x7471, + SECURITY_CONFLICT_IN_TRANSLATED_DEVICE = 0x7479, +}; + +#undef SCSI_ASC_DEF +#undef SCSI_ASC + +/* + * Use this to build non-standard sense codes. + * Note: this is defined as a macro instead of an inline function so that it can + * be used to define SCSI failures array variables (see struct scsi_failure). + */ +#define scsi_sense_code(asc, ascq) \ + ((((asc) & 0xff) << 8) | ((ascq) & 0xff)) + +static inline u8 scsi_sense_code_asc(u16 code) +{ + return (code >> 8) & 0xff; +} + +static inline u8 scsi_sense_code_ascq(u16 code) +{ + return code & 0xff; +} + +#endif /* _SCSI_SENSE_H_ */ diff --git a/include/sound/aw88399.h b/include/sound/aw88399.h index a1e0de6be8ea..974b5774ac2b 100644 --- a/include/sound/aw88399.h +++ b/include/sound/aw88399.h @@ -449,6 +449,11 @@ #define AW88399_NOISE_GATE_EN_MASK \ (~(((1<relaxed_resume && codec->jacktbl.used; + return !codec->relaxed_resume && codec->jacktbl_used; } /* diff --git a/include/sound/hdaudio.h b/include/sound/hdaudio.h index aa994d6e6d35..6da4cf407654 100644 --- a/include/sound/hdaudio.h +++ b/include/sound/hdaudio.h @@ -97,6 +97,7 @@ struct hdac_device { bool caps_overwriting:1; /* caps overwrite being in process */ bool cache_coef:1; /* cache COEF read/write too */ unsigned int registered:1; /* codec was registered */ + bool unsol_disabled; /* unsol events blocked; protected by bus->reg_lock */ }; /* device/driver type used for matching */ @@ -123,6 +124,7 @@ int snd_hdac_device_init(struct hdac_device *dev, struct hdac_bus *bus, const char *name, unsigned int addr); void snd_hdac_device_exit(struct hdac_device *dev); int snd_hdac_device_register(struct hdac_device *codec); +void snd_hdac_device_disable_unsol(struct hdac_device *codec); void snd_hdac_device_unregister(struct hdac_device *codec); int snd_hdac_device_set_chip_name(struct hdac_device *codec, const char *name); int snd_hdac_codec_modalias(const struct hdac_device *hdac, char *buf, size_t size); diff --git a/include/sound/pcm.h b/include/sound/pcm.h index 02d8689354c4..1cf511f8d880 100644 --- a/include/sound/pcm.h +++ b/include/sound/pcm.h @@ -8,6 +8,7 @@ * Abramo Bagnara */ +#include #include #include #include @@ -414,6 +415,7 @@ struct snd_pcm_runtime { snd_pcm_uframes_t twake; /* do transfer (!poll) wakeup if non-zero */ wait_queue_head_t sleep; /* poll sleep */ wait_queue_head_t tsleep; /* transfer sleep */ + struct snd_refcount refcnt; /* refcount for draining, etc */ struct snd_fasync *fasync; bool stop_operating; /* sync_stop will be called */ struct mutex buffer_mutex; /* protect for buffer changes */ diff --git a/include/sound/pcm_oss.h b/include/sound/pcm_oss.h index c96f23c7755b..43f765300031 100644 --- a/include/sound/pcm_oss.h +++ b/include/sound/pcm_oss.h @@ -70,6 +70,7 @@ struct snd_pcm_oss_stream { struct snd_pcm_oss { int reg; unsigned int reg_mask; + bool registered; }; #endif /* __SOUND_PCM_OSS_H */ diff --git a/include/sound/sdca_class.h b/include/sound/sdca_class.h new file mode 100644 index 000000000000..8a6a34a8dd4c --- /dev/null +++ b/include/sound/sdca_class.h @@ -0,0 +1,49 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* + * The MIPI SDCA specification is available for public downloads at + * https://www.mipi.org/mipi-sdca-v1-0-download + * + * Copyright (C) 2025 Cirrus Logic, Inc. and + * Cirrus Logic International Semiconductor Ltd. + */ + +#ifndef __SDCA_CLASS_H__ +#define __SDCA_CLASS_H__ + +#include +#include +#include + +struct device; +struct regmap; +struct sdw_slave; +struct sdca_function_data; + +struct sdca_class_drv { + struct device *dev; + struct regmap *dev_regmap; + struct sdw_slave *sdw; + + struct sdca_interrupt_info *irq_info; + + struct mutex regmap_lock; + /* Serialise function initialisations */ + struct mutex init_lock; + struct work_struct boot_work; +}; + +/* + * PM helpers. Codec drivers embed sdca_class_drv in their own priv, + * own dev_set_drvdata(), and compose these into their own dev_pm_ops: + * + * static int wcd_runtime_suspend(struct device *dev) { + * struct wcd_priv *priv = dev_get_drvdata(dev); + * return sdca_class_runtime_suspend(&priv->class); + * } + */ +int sdca_class_runtime_suspend(struct sdca_class_drv *drv); +int sdca_class_runtime_resume(struct sdca_class_drv *drv); +int sdca_class_system_suspend(struct sdca_class_drv *drv); +int sdca_class_system_resume(struct sdca_class_drv *drv); + +#endif /* __SDCA_CLASS_H__ */ diff --git a/include/sound/soc-component.h b/include/sound/soc-component.h index c49b59630101..bd64ebf2379b 100644 --- a/include/sound/soc-component.h +++ b/include/sound/soc-component.h @@ -423,7 +423,7 @@ int snd_soc_component_compr_set_metadata(struct snd_compr_stream *cstream, int snd_soc_component_compr_get_metadata(struct snd_compr_stream *cstream, struct snd_compr_metadata *metadata); -int snd_soc_pcm_component_pointer(struct snd_pcm_substream *substream); +snd_pcm_uframes_t snd_soc_pcm_component_pointer(struct snd_pcm_substream *substream); int snd_soc_pcm_component_ioctl(struct snd_pcm_substream *substream, unsigned int cmd, void *arg); int snd_soc_pcm_component_sync_stop(struct snd_pcm_substream *substream); diff --git a/include/sound/ump.h b/include/sound/ump.h index 73f97f88e2ed..387143783a9b 100644 --- a/include/sound/ump.h +++ b/include/sound/ump.h @@ -66,6 +66,7 @@ struct snd_ump_endpoint { #if IS_ENABLED(CONFIG_SND_SEQUENCER) struct snd_seq_device *seq_dev; + /* Published after seq_client; calls are covered by UMP core SRCU. */ const struct snd_seq_ump_ops *seq_ops; void *seq_client; #endif @@ -126,6 +127,10 @@ int snd_ump_receive_ump_val(struct snd_ump_endpoint *ump, u32 val); int snd_ump_switch_protocol(struct snd_ump_endpoint *ump, unsigned int protocol); void snd_ump_update_group_attrs(struct snd_ump_endpoint *ump); +#if IS_ENABLED(CONFIG_SND_SEQUENCER) +void snd_ump_detach_seq(struct snd_ump_endpoint *ump); +#endif + /* * Some definitions for UMP */ diff --git a/include/trace/events/iocost.h b/include/trace/events/iocost.h index e772b1bc60d6..eb711343ce4f 100644 --- a/include/trace/events/iocost.h +++ b/include/trace/events/iocost.h @@ -34,6 +34,9 @@ DECLARE_EVENT_CLASS(iocost_iocg_state, ), TP_fast_assign( + u32 hwa, hwi; + + iocg_hweight_cache(iocg, &hwa, &hwi); __assign_str(devname); __assign_str(cgroup); __entry->now = now->now; @@ -44,8 +47,8 @@ DECLARE_EVENT_CLASS(iocost_iocg_state, __entry->vtime = vtime; __entry->weight = iocg->weight; __entry->inuse = iocg->inuse; - __entry->hweight_active = iocg->hweight_active; - __entry->hweight_inuse = iocg->hweight_inuse; + __entry->hweight_active = hwa; + __entry->hweight_inuse = hwi; ), TP_printk("[%s:%s] now=%llu:%llu vrate=%llu " diff --git a/include/trace/events/power.h b/include/trace/events/power.h index 370f8df2fdb4..4d17eb307b6a 100644 --- a/include/trace/events/power.h +++ b/include/trace/events/power.h @@ -497,6 +497,7 @@ DEFINE_EVENT(dev_pm_qos_request, dev_pm_qos_remove_request, TP_ARGS(name, type, new_value) ); +#ifdef CONFIG_CPU_IDLE_GOV_HALTPOLL TRACE_EVENT(guest_halt_poll_ns, TP_PROTO(bool grow, unsigned int new, unsigned int old), @@ -525,6 +526,8 @@ TRACE_EVENT(guest_halt_poll_ns, trace_guest_halt_poll_ns(true, new, old) #define trace_guest_halt_poll_ns_shrink(new, old) \ trace_guest_halt_poll_ns(false, new, old) +#endif /* CONFIG_CPU_IDLE_GOV_HALTPOLL */ + #endif /* _TRACE_POWER_H */ /* This part must be outside protection */ diff --git a/include/trace/events/rxrpc.h b/include/trace/events/rxrpc.h index 554dfb777b93..56dc9b614071 100644 --- a/include/trace/events/rxrpc.h +++ b/include/trace/events/rxrpc.h @@ -28,8 +28,8 @@ EM(afs_abort_unsupported_sec_class, "afs-unsup-sec-class") \ /* rxperf errors */ \ EM(rxperf_abort_general_error, "rxperf-error") \ - EM(rxperf_abort_oom, "rxperf-oom") \ EM(rxperf_abort_op_not_supported, "rxperf-op-notsupp") \ + EM(rxperf_abort_send_error, "rxperf-send-error") \ EM(rxperf_abort_unmarshal_error, "rxperf-unmarshal") \ /* RxKAD security errors */ \ EM(rxkad_abort_1_short_check, "rxkad1-short-check") \ diff --git a/include/uapi/drm/panfrost_drm.h b/include/uapi/drm/panfrost_drm.h index 50d5337f35ef..7831c48c59c0 100644 --- a/include/uapi/drm/panfrost_drm.h +++ b/include/uapi/drm/panfrost_drm.h @@ -47,7 +47,7 @@ extern "C" { * them for anything but debugging purpose. */ #define DRM_IOCTL_PANFROST_PERFCNT_ENABLE DRM_IOW(DRM_COMMAND_BASE + DRM_PANFROST_PERFCNT_ENABLE, struct drm_panfrost_perfcnt_enable) -#define DRM_IOCTL_PANFROST_PERFCNT_DUMP DRM_IOW(DRM_COMMAND_BASE + DRM_PANFROST_PERFCNT_DUMP, struct drm_panfrost_perfcnt_dump) +#define DRM_IOCTL_PANFROST_PERFCNT_DUMP DRM_IOWR(DRM_COMMAND_BASE + DRM_PANFROST_PERFCNT_DUMP, struct drm_panfrost_perfcnt_dump) #define PANFROST_JD_REQ_FS (1 << 0) #define PANFROST_JD_REQ_CYCLE_COUNT (1 << 1) @@ -270,8 +270,35 @@ struct drm_panfrost_perfcnt_enable { __u32 counterset; }; +/* + * The next two flags describe the state of a perfcnt dump request + * as influenced by a device reset. They are the only values the + * perfcnt_dump ioctl state field can take on. + * Only certain state and ioctl retval combinations are legitimate. + */ + +/* A new perfcnt_enable ioctl should be issued before requesting + * more dumps, because a HW reset failed to recreate perfcnt's + * original state. Otherwise further perfcnt_dump's will fail. + * This flag being set means ioctl's retval is always -EIO. + */ +#define PANFROST_PERFCNT_SESSION_DEAD (1 << 0) + +/* A HW reset happened before or during a sample request, and + * perfcnt's internal state was successfully restored. There + * are two possible outcomes depending on the ioctl's retval: + * 0: A reset happened before a dump was requested, but did + * nonetheless succeed. Counter values are relative to last reset. + * -EAGAIN: A reset happened when a counter values sampling + * request was ongoing. Values are undefined so a new dump ioctl + * should be issued. + */ +#define PANFROST_PERFCNT_SESSION_INTERRUPTED_BY_RESET (1 << 1) + struct drm_panfrost_perfcnt_dump { __u64 buf_ptr; + __u32 state; + __u32 pad; /* MBZ */ }; /* madvise provides a way to tell the kernel in case a buffers contents diff --git a/include/uapi/linux/amd-pmf.h b/include/uapi/linux/amd-pmf.h index 24cf9926dc59..151f264cd7d6 100644 --- a/include/uapi/linux/amd-pmf.h +++ b/include/uapi/linux/amd-pmf.h @@ -199,6 +199,9 @@ struct amd_pmf_info { /* BIOS parameters */ __u32 bios_input[AMD_PMF_BIOS_PARAMS_MAX]; __u32 bios_output[AMD_PMF_BIOS_PARAMS_MAX]; + + /* align to 64 bit boundary */ + __u32 __pad; }; #endif /* _UAPI_LINUX_AMD_PMF_H */ diff --git a/include/uapi/linux/firewire-cdev.h b/include/uapi/linux/firewire-cdev.h index 05e3aa8fa8bc..4f83d6babc92 100644 --- a/include/uapi/linux/firewire-cdev.h +++ b/include/uapi/linux/firewire-cdev.h @@ -293,7 +293,7 @@ struct fw_cdev_event_request3 { /** * struct fw_cdev_event_iso_interrupt - Sent when an iso packet was completed * @closure: See &fw_cdev_event_common; - * set by %FW_CDEV_CREATE_ISO_CONTEXT ioctl + * set by %FW_CDEV_IOC_CREATE_ISO_CONTEXT ioctl * @type: See &fw_cdev_event_common; always %FW_CDEV_EVENT_ISO_INTERRUPT * @cycle: Cycle counter of the last completed packet * @header_length: Total length of following headers, in bytes @@ -353,7 +353,7 @@ struct fw_cdev_event_iso_interrupt { /** * struct fw_cdev_event_iso_interrupt_mc - An iso buffer chunk was completed * @closure: See &fw_cdev_event_common; - * set by %FW_CDEV_CREATE_ISO_CONTEXT ioctl + * set by %FW_CDEV_IOC_CREATE_ISO_CONTEXT ioctl * @type: %FW_CDEV_EVENT_ISO_INTERRUPT_MULTICHANNEL * @completed: Offset into the receive buffer; data before this offset is valid * diff --git a/include/uapi/linux/iommufd.h b/include/uapi/linux/iommufd.h index 63a86354e822..010f47f7d3d2 100644 --- a/include/uapi/linux/iommufd.h +++ b/include/uapi/linux/iommufd.h @@ -776,7 +776,7 @@ enum iommufd_hw_info_flags { * @out_data_type: Output the iommu hardware info type as defined in the enum * iommu_hw_info_type. * @out_capabilities: Output the generic iommu capability info type as defined - * in the enum iommu_hw_capabilities. + * in the enum iommufd_hw_capabilities. * @out_max_pasid_log2: Output the width of PASIDs. 0 means no PASID support. * PCI devices turn to out_capabilities to check if the * specific capabilities is supported or not. diff --git a/include/uapi/linux/nl80211.h b/include/uapi/linux/nl80211.h index 020387d76412..107186331967 100644 --- a/include/uapi/linux/nl80211.h +++ b/include/uapi/linux/nl80211.h @@ -1383,6 +1383,13 @@ * from the device to perform an announced schedule update. See * %NL80211_ATTR_NAN_SCHED_DEFERRED for more details. * If not set, the schedule should be applied immediately. + * Setting a new schedule is always allowed and is never treated as an + * evacuation, even if it removes channels that were previously marked as + * non-evacuable with %NL80211_CMD_NAN_SET_NON_EVAC_CHANNELS. The + * non-evacuable marking is a per-channel property of the schedule: + * channels that remain in the new schedule keep their marking, channels + * that are removed simply lose it, and newly added channels are + * evacuable by default. * @NL80211_CMD_NAN_SCHED_UPDATE_DONE: Event sent to user space to notify that * a deferred local NAN schedule update (requested with * %NL80211_CMD_NAN_SET_LOCAL_SCHED and %NL80211_ATTR_NAN_SCHED_DEFERRED) @@ -1427,6 +1434,28 @@ * @NL80211_CMD_STOP_PD: Stop the PD operation, identified by * its %NL80211_ATTR_WDEV interface. * + * @NL80211_CMD_NAN_SET_NON_EVAC_CHANNELS: Set the list of NAN local schedule + * channels that must not be evacuated. NAN must be operational + * (%NL80211_CMD_START_NAN was executed) and a local schedule must have + * been set (%NL80211_CMD_NAN_SET_LOCAL_SCHED). The command carries zero + * or more nested %NL80211_ATTR_NAN_CHANNEL attributes, each identifying a + * channel (by its channel definition) of the current local schedule that + * must not be evacuated for concurrent operations. The provided list + * replaces the previous set of non-evacuable channels; channels of the + * current schedule that are not included become evacuable again. All + * provided channels must exist in the current local schedule, otherwise + * the command fails. This is used to protect channels carrying NDC or + * immutable schedules, whose evacuation would break existing NDP + * connections. + * The non-evacuable marking is a per-channel property of the current + * local schedule and only affects evacuation for concurrent operations; + * it does not prevent the schedule itself from being changed. Removing a + * channel from the schedule with %NL80211_CMD_NAN_SET_LOCAL_SCHED is a + * user-initiated change, not an evacuation, and is allowed even for a + * non-evacuable channel. Across a schedule update, channels that remain + * keep their non-evacuable marking, removed channels lose it, and newly + * added channels are evacuable by default; issue this command again to + * change the non-evacuable set. * @NL80211_CMD_MAX: highest used command number * @__NL80211_CMD_AFTER_LAST: internal use */ @@ -1705,6 +1734,8 @@ enum nl80211_commands { NL80211_CMD_START_PD, NL80211_CMD_STOP_PD, + NL80211_CMD_NAN_SET_NON_EVAC_CHANNELS, + /* add new commands above here */ /* used to define NL80211_CMD_MAX below */ diff --git a/include/ufs/ufshcd.h b/include/ufs/ufshcd.h index dfd302f2dc7c..be62165b785e 100644 --- a/include/ufs/ufshcd.h +++ b/include/ufs/ufshcd.h @@ -1132,6 +1132,14 @@ struct ufs_hba { /* Auto-Hibernate Idle Timer register value */ u32 ahit; + /* Serializes AHIT register access between sysfs and the host driver */ + struct mutex ahit_mutex; + /* + * Nesting count of host-driver paths that have AHIT forced off. + * Non-zero blocks sysfs AHIT writes; AHIT is reprogrammed only when + * the last disabler drops it back to zero. Guarded by ahit_mutex. + */ + int ahit_disable_depth; unsigned long outstanding_tasks; spinlock_t outstanding_lock; diff --git a/include/vdso/math64.h b/include/vdso/math64.h index 22ae212f8b28..2ef4905585c5 100644 --- a/include/vdso/math64.h +++ b/include/vdso/math64.h @@ -21,6 +21,26 @@ __iter_div_u64_rem(u64 dividend, u32 divisor, u64 *remainder) return ret; } +static __always_inline u32 __iter_div64_u64_rem(u64 dividend, u64 divisor, u64 *remainder) +{ + u32 ret = 0; + + while (dividend >= divisor) { + /* + * Prevent the compiler from optimising this loop into a + * modulo operation. + */ + OPTIMIZER_HIDE_VAR(dividend); + + dividend -= divisor; + ret++; + } + + *remainder = dividend; + + return ret; +} + #if defined(CONFIG_ARCH_SUPPORTS_INT128) && defined(__SIZEOF_INT128__) #ifndef mul_u64_u32_add_u64_shr diff --git a/init/do_mounts.c b/init/do_mounts.c index 95e0b3a0f711..b088021b1546 100644 --- a/init/do_mounts.c +++ b/init/do_mounts.c @@ -503,10 +503,18 @@ static int rootfs_init_fs_context(struct fs_context *fc) return ramfs_init_fs_context(fc); } +static void rootfs_kill_sb(struct super_block *sb) +{ + if (IS_ENABLED(CONFIG_TMPFS) && is_tmpfs) + kill_anon_super(sb); + else + ramfs_kill_sb(sb); +} + struct file_system_type rootfs_fs_type = { .name = "rootfs", .init_fs_context = rootfs_init_fs_context, - .kill_sb = kill_anon_super, + .kill_sb = rootfs_kill_sb, }; void __init init_rootfs(void) diff --git a/init/main.c b/init/main.c index 4efcb9956c39..46c1fb7c04df 100644 --- a/init/main.c +++ b/init/main.c @@ -548,12 +548,12 @@ static int __init unknown_bootoption(char *param, char *val, /* Environment option */ unsigned int i; for (i = 0; envp_init[i]; i++) { + if (!strncmp(param, envp_init[i], len+1)) + break; if (i == MAX_INIT_ENVS) { panic_later = "env"; panic_param = param; } - if (!strncmp(param, envp_init[i], len+1)) - break; } envp_init[i] = param; } else { @@ -581,7 +581,7 @@ static int __init init_setup(char *str) * the shell think it should execute a script with such name. * So we ignore all arguments entered _before_ init=... [MJ] */ - for (i = 1; i < MAX_INIT_ARGS; i++) + for (i = 1; i <= MAX_INIT_ARGS; i++) argv_init[i] = NULL; return 1; } @@ -594,7 +594,7 @@ static int __init rdinit_setup(char *str) ramdisk_execute_command = str; ramdisk_execute_command_set = true; /* See "auto" comment in init_setup */ - for (i = 1; i < MAX_INIT_ARGS; i++) + for (i = 1; i <= MAX_INIT_ARGS; i++) argv_init[i] = NULL; return 1; } diff --git a/kernel/bpf/arena.c b/kernel/bpf/arena.c index 7b6847200b43..868589f07330 100644 --- a/kernel/bpf/arena.c +++ b/kernel/bpf/arena.c @@ -146,7 +146,7 @@ static long compute_pgoff(struct bpf_arena *arena, long uaddr) struct apply_range_data { struct bpf_arena *arena; - struct page **pages; + struct llist_head *pages; int i; }; @@ -158,13 +158,17 @@ struct clear_range_data { static int apply_range_set_cb(pte_t *pte, unsigned long addr, void *data) { struct apply_range_data *d = data; + struct llist_node *node; struct page *page; pte_t pteval; if (!data) return 0; - page = d->pages[d->i]; + node = READ_ONCE(d->pages->first); + if (WARN_ON_ONCE(!node)) + return -EINVAL; + page = llist_entry(node, struct page, pcp_llist); /* paranoia, similar to vmap_pages_pte_range() */ if (WARN_ON_ONCE(!pfn_valid(page_to_pfn(page)))) return -EINVAL; @@ -197,6 +201,7 @@ static int apply_range_set_cb(pte_t *pte, unsigned long addr, void *data) return -EBUSY; set_pte_at(&init_mm, addr, pte, pteval); #endif + WARN_ON_ONCE(llist_del_first(d->pages) != node); d->i++; WRITE_ONCE(d->arena->nr_pages, d->arena->nr_pages + 1); return 0; @@ -312,8 +317,8 @@ static struct bpf_map *arena_map_alloc(union bpf_attr *attr) INIT_WORK(&arena->free_work, arena_free_worker); bpf_map_init_from_attr(&arena->map, attr); - err = bpf_map_alloc_pages(&arena->map, NUMA_NO_NODE, 1, &arena->scratch_page); - if (err) + arena->scratch_page = bpf_alloc_page(NUMA_NO_NODE, true); + if (!arena->scratch_page) goto err_free_arena; range_tree_init(&arena->rt); @@ -481,7 +486,10 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf) struct bpf_map *map = vmf->vma->vm_file->private_data; struct bpf_arena *arena = container_of(map, struct bpf_arena, map); struct mem_cgroup *new_memcg, *old_memcg; - struct page *page; + LLIST_HEAD(pages); + struct page *page, *new_page = NULL; + struct apply_range_data data; + vm_fault_t fault_ret; long kbase, kaddr; unsigned long flags; int ret; @@ -489,59 +497,123 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf) kbase = bpf_arena_get_kern_vm_start(arena); kaddr = kbase + (u32)(vmf->address); - if (raw_res_spin_lock_irqsave(&arena->spinlock, flags)) + page = vmalloc_to_page((void *)kaddr); + if (!page && !(arena->map.map_flags & BPF_F_SEGV_ON_FAULT)) { + /* + * Preallocate outside the lock so the allocation can reclaim; + * __GFP_RETRY_MAYFAIL keeps the OOM killer out of it. + */ + bpf_map_memcg_enter(&arena->map, &old_memcg, &new_memcg); + new_page = alloc_pages_node(map->numa_node, + GFP_KERNEL | __GFP_ZERO | + __GFP_ACCOUNT | __GFP_NOWARN | + __GFP_RETRY_MAYFAIL, 0); + bpf_map_memcg_exit(old_memcg, new_memcg); + } + + if (raw_res_spin_lock_irqsave(&arena->spinlock, flags)) { /* * A failed lock means a possible deadlock was detected. Don't * return VM_FAULT_RETRY: this handler never took mmap_lock, but * the fault path would re-take it on retry and deadlock. Fail. */ + if (new_page) + free_pages_nolock(new_page, 0); return VM_FAULT_SIGBUS; + } page = vmalloc_to_page((void *)kaddr); if (page) { - if (page == arena->scratch_page) + if (page == arena->scratch_page) { /* BPF triggered scratch here; don't lazy-alloc over it */ - goto out_sigsegv; + fault_ret = (arena->map.map_flags & BPF_F_SEGV_ON_FAULT) + ? VM_FAULT_SIGSEGV : VM_FAULT_SIGBUS; + goto out_err_locked; + } /* already have a page vmap-ed */ goto out; } + if (arena->map.map_flags & BPF_F_SEGV_ON_FAULT) { + /* + * User space requested to segfault when page is not allocated + * by bpf prog + */ + fault_ret = VM_FAULT_SIGSEGV; + goto out_err_locked; + } + + if (is_range_tree_set(&arena->rt, vmf->pgoff, 1)) { + /* Allocated without a page: reserved or being freed */ + fault_ret = VM_FAULT_SIGBUS; + goto out_err_locked; + } + bpf_map_memcg_enter(&arena->map, &old_memcg, &new_memcg); - if (arena->map.map_flags & BPF_F_SEGV_ON_FAULT) - /* User space requested to segfault when page is not allocated by bpf prog */ - goto out_sigsegv_memcg; + if (!new_page) { + /* + * The probed page was freed meanwhile or preallocation failed; + * try the non-blocking allocator, we cannot sleep here. + */ + new_page = bpf_alloc_page(map->numa_node, false); + if (!new_page) { + fault_ret = VM_FAULT_SIGBUS; + goto out_err_locked_memcg; + } + } ret = range_tree_clear(&arena->rt, vmf->pgoff, 1); - if (ret) - goto out_sigsegv_memcg; - - struct apply_range_data data = { .arena = arena, .pages = &page, .i = 0 }; - /* Account into memcg of the process that created bpf_arena */ - ret = bpf_map_alloc_pages(map, NUMA_NO_NODE, 1, &page); if (ret) { - range_tree_set(&arena->rt, vmf->pgoff, 1); - goto out_sigsegv_memcg; + fault_ret = VM_FAULT_SIGBUS; + goto out_err_locked_memcg; } + llist_add(&new_page->pcp_llist, &pages); + data.arena = arena; + data.pages = &pages; + data.i = 0; ret = apply_to_page_range(&init_mm, kaddr, PAGE_SIZE, apply_range_set_cb, &data); if (ret) { + llist_del_first(&pages); range_tree_set(&arena->rt, vmf->pgoff, 1); - free_pages_nolock(page, 0); - goto out_sigsegv_memcg; + fault_ret = VM_FAULT_SIGBUS; + goto out_err_locked_memcg; } flush_vmap_cache(kaddr, PAGE_SIZE); bpf_map_memcg_exit(old_memcg, new_memcg); + /* new_page was consumed */ + page = new_page; + new_page = NULL; out: page_ref_add(page, 1); raw_res_spin_unlock_irqrestore(&arena->spinlock, flags); - vmf->page = page; - return 0; -out_sigsegv_memcg: + if (new_page) + free_pages_nolock(new_page, 0); + + /* + * A free clears the kernel pte and then takes the page lock before it + * zaps user vma-s. Either it waits for this fault and zaps its pte, or + * the page is gone from here. + */ + lock_page(page); + if (vmalloc_to_page((void *)kaddr) == page && !PageHWPoison(page)) { + vmf->page = page; + return VM_FAULT_LOCKED; + } + /* The page was freed meanwhile. Let the fault start over. */ + fault_ret = PageHWPoison(page) ? VM_FAULT_HWPOISON : VM_FAULT_NOPAGE; + unlock_page(page); + put_page(page); + return fault_ret; + +out_err_locked_memcg: bpf_map_memcg_exit(old_memcg, new_memcg); -out_sigsegv: +out_err_locked: raw_res_spin_unlock_irqrestore(&arena->spinlock, flags); - return VM_FAULT_SIGSEGV; + if (new_page) + free_pages_nolock(new_page, 0); + return fault_ret; } static const struct vm_operations_struct arena_vm_ops = { @@ -661,6 +733,27 @@ static u64 clear_lo32(u64 val) return val & ~(u64)~0U; } +static int arena_adjust_tree(struct bpf_arena *arena, long uaddr, long page_cnt, long *pgoff) +{ + int ret; + + /* Special case where user is requesting specific range. */ + if (uaddr) { + ret = is_range_tree_set(&arena->rt, *pgoff, page_cnt); + if (ret) + return ret; + return range_tree_clear(&arena->rt, *pgoff, page_cnt); + } + + ret = range_tree_find(&arena->rt, page_cnt); + if (ret < 0) + return ret; + + *pgoff = ret; + + return range_tree_clear(&arena->rt, *pgoff, page_cnt); +} + /* * Allocate pages and vmap them into kernel vmalloc area. * Later the pages will be mmaped into user space vma. @@ -673,13 +766,13 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt u64 kern_vm_start = bpf_arena_get_kern_vm_start(arena); struct mem_cgroup *new_memcg, *old_memcg; struct apply_range_data data; - struct page **pages = NULL; - long remaining, mapped = 0; - long alloc_pages; + LLIST_HEAD(pages); + long mapped = 0; unsigned long flags; long pgoff = 0; u32 uaddr32; - int ret, i; + long addr = 0; + int ret; if (node_id != NUMA_NO_NODE && ((unsigned int)node_id >= nr_node_ids || !node_online(node_id))) @@ -696,89 +789,63 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cnt /* requested address will be outside of user VMA */ return 0; } - bpf_map_memcg_enter(&arena->map, &old_memcg, &new_memcg); - /* Cap allocation size to KMALLOC_MAX_CACHE_SIZE so kmalloc_nolock() can succeed. */ - alloc_pages = min(page_cnt, KMALLOC_MAX_CACHE_SIZE / sizeof(struct page *)); - pages = kmalloc_nolock(alloc_pages * sizeof(struct page *), __GFP_ACCOUNT, NUMA_NO_NODE); - if (!pages) { - bpf_map_memcg_exit(old_memcg, new_memcg); - return 0; - } + + ret = bpf_alloc_pages(node_id, page_cnt, &pages, sleepable); + if (ret) + goto out_memcg; + data.arena = arena; - data.pages = pages; + data.pages = &pages; + data.i = 0; if (raw_res_spin_lock_irqsave(&arena->spinlock, flags)) goto out_free_pages; - if (uaddr) { - ret = is_range_tree_set(&arena->rt, pgoff, page_cnt); - if (ret) - goto out_unlock_free_pages; - ret = range_tree_clear(&arena->rt, pgoff, page_cnt); - } else { - ret = pgoff = range_tree_find(&arena->rt, page_cnt); - if (pgoff >= 0) - ret = range_tree_clear(&arena->rt, pgoff, page_cnt); + ret = arena_adjust_tree(arena, uaddr, page_cnt, &pgoff); + if (ret) { + raw_res_spin_unlock_irqrestore(&arena->spinlock, flags); + goto out_free_pages; } - if (ret) - goto out_unlock_free_pages; - remaining = page_cnt; uaddr32 = (u32)(arena->user_vm_start + pgoff * PAGE_SIZE); - while (remaining) { - long this_batch = min(remaining, alloc_pages); - - /* zeroing is needed, since alloc_pages_bulk() only fills in non-zero entries */ - memset(pages, 0, this_batch * sizeof(struct page *)); + /* + * Earlier checks made sure that uaddr32 + page_cnt * PAGE_SIZE - 1 + * will not overflow 32-bit. Lower 32-bit need to represent + * contiguous user address range. + * Map these pages at kern_vm_start base. + * kern_vm_start + uaddr32 + page_cnt * PAGE_SIZE - 1 can overflow + * lower 32-bit and it's ok. + */ + ret = apply_to_page_range(&init_mm, kern_vm_start + uaddr32, + page_cnt << PAGE_SHIFT, apply_range_set_cb, &data); + mapped = data.i; + if (ret) + goto out_unmap; - ret = bpf_map_alloc_pages(&arena->map, node_id, this_batch, pages); - if (ret) - goto out; + flush_vmap_cache(kern_vm_start + uaddr32, mapped << PAGE_SHIFT); + raw_res_spin_unlock_irqrestore(&arena->spinlock, flags); - /* - * Earlier checks made sure that uaddr32 + page_cnt * PAGE_SIZE - 1 - * will not overflow 32-bit. Lower 32-bit need to represent - * contiguous user address range. - * Map these pages at kern_vm_start base. - * kern_vm_start + uaddr32 + page_cnt * PAGE_SIZE - 1 can overflow - * lower 32-bit and it's ok. - */ - data.i = 0; - ret = apply_to_page_range(&init_mm, - kern_vm_start + uaddr32 + (mapped << PAGE_SHIFT), - this_batch << PAGE_SHIFT, apply_range_set_cb, &data); - if (ret) { - /* data.i pages were mapped, account them and free the remaining */ - mapped += data.i; - for (i = data.i; i < this_batch; i++) - free_pages_nolock(pages[i], 0); - goto out; - } + addr = clear_lo32(arena->user_vm_start) + uaddr32; + goto out_memcg; - mapped += this_batch; - remaining -= this_batch; - } +out_unmap: + /* Error handling: Undo partial mappings. */ flush_vmap_cache(kern_vm_start + uaddr32, mapped << PAGE_SHIFT); - raw_res_spin_unlock_irqrestore(&arena->spinlock, flags); - kfree_nolock(pages); - bpf_map_memcg_exit(old_memcg, new_memcg); - return clear_lo32(arena->user_vm_start) + uaddr32; -out: range_tree_set(&arena->rt, pgoff + mapped, page_cnt - mapped); raw_res_spin_unlock_irqrestore(&arena->spinlock, flags); - if (mapped) { - flush_vmap_cache(kern_vm_start + uaddr32, mapped << PAGE_SHIFT); + if (mapped) arena_free_pages(arena, uaddr32, mapped, sleepable); - } - goto out_free_pages; -out_unlock_free_pages: - raw_res_spin_unlock_irqrestore(&arena->spinlock, flags); + out_free_pages: - kfree_nolock(pages); + /* Error handling: Free back any unmapped pages. */ + bpf_free_pages(&pages); + +out_memcg: bpf_map_memcg_exit(old_memcg, new_memcg); - return 0; + + return addr; } /* @@ -807,7 +874,7 @@ static void zap_pages(struct bpf_arena *arena, long uaddr, long page_cnt) * otherwise call B's mark would make call A skip a vml that A has * not yet zapped for A's uaddr range. */ - mutex_lock(&arena->zap_mutex); + lockdep_assert_held(&arena->zap_mutex); mutex_lock(&arena->lock); my_gen = ++arena->zap_gen; for (;;) { @@ -841,49 +908,41 @@ static void zap_pages(struct bpf_arena *arena, long uaddr, long page_cnt) mutex_lock(&arena->lock); } mutex_unlock(&arena->lock); - mutex_unlock(&arena->zap_mutex); } -static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, bool sleepable) +/* + * The range stays allocated in the range tree until the pages are unmapped + * from vmalloc area and from all user space vma-s, so that nobody can + * populate it while stale TLB entries or user ptes are still around. + */ +static int arena_free_range(struct bpf_arena *arena, long uaddr, long page_cnt) { - struct mem_cgroup *new_memcg, *old_memcg; - u64 full_uaddr, uaddr_end; - long kaddr, pgoff; - struct page *page; - struct llist_head free_pages; - struct llist_node *pos, *t; - struct arena_free_span *s; + u64 full_uaddr = clear_lo32(arena->user_vm_start) + uaddr; + long kaddr = bpf_arena_get_kern_vm_start(arena) + uaddr; + long pgoff = compute_pgoff(arena, uaddr); struct clear_range_data cdata; + struct llist_node *pos, *t; + LLIST_HEAD(free_pages); unsigned long flags; - int ret = 0; - - /* only aligned lower 32-bit are relevant */ - uaddr = (u32)uaddr; - uaddr &= PAGE_MASK; - kaddr = bpf_arena_get_kern_vm_start(arena) + uaddr; - full_uaddr = clear_lo32(arena->user_vm_start) + uaddr; - if (full_uaddr < arena->user_vm_start) - return; - uaddr_end = min(arena->user_vm_end, full_uaddr + (page_cnt << PAGE_SHIFT)); - if (full_uaddr >= uaddr_end) - return; - - page_cnt = (uaddr_end - full_uaddr) >> PAGE_SHIFT; - pgoff = compute_pgoff(arena, uaddr); - bpf_map_memcg_enter(&arena->map, &old_memcg, &new_memcg); + struct page *page; + int ret; - if (!sleepable) - goto defer; + /* An overlapping free must not release the range before this one is done */ + guard(mutex)(&arena->zap_mutex); ret = raw_res_spin_lock_irqsave(&arena->spinlock, flags); - - /* Can't proceed without holding the spinlock so defer the free */ if (ret) - goto defer; + return ret; - range_tree_set(&arena->rt, pgoff, page_cnt); + /* + * Take the free pages of the range too. It allocates, and can fail, + * only when the whole range is free. Then there is nothing to do. + */ + if (range_tree_clear(&arena->rt, pgoff, page_cnt)) { + raw_res_spin_unlock_irqrestore(&arena->spinlock, flags); + return 0; + } - init_llist_head(&free_pages); cdata.arena = arena; cdata.free_pages = &free_pages; /* clear ptes and collect struct pages */ @@ -893,6 +952,12 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, /* drop the lock to do the tlb flush and zap pages */ raw_res_spin_unlock_irqrestore(&arena->spinlock, flags); + /* wait for arena_vm_fault() that found the page before its pte was cleared */ + llist_for_each_entry(page, free_pages.first, pcp_llist) { + lock_page(page); + unlock_page(page); + } + /* ensure no stale TLB entries */ flush_tlb_kernel_range(kaddr, kaddr + (page_cnt * PAGE_SIZE)); @@ -911,8 +976,39 @@ static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, zap_pages(arena, full_uaddr, 1); __free_page(page); } - bpf_map_memcg_exit(old_memcg, new_memcg); + /* The callers hold no other rqspinlock, so this one can only time out */ + while (raw_res_spin_lock_irqsave(&arena->spinlock, flags)) + cond_resched(); + range_tree_set(&arena->rt, pgoff, page_cnt); + raw_res_spin_unlock_irqrestore(&arena->spinlock, flags); + return 0; +} + +static void arena_free_pages(struct bpf_arena *arena, long uaddr, long page_cnt, bool sleepable) +{ + struct mem_cgroup *new_memcg, *old_memcg; + u64 full_uaddr, uaddr_end; + struct arena_free_span *s; + + /* only aligned lower 32-bit are relevant */ + uaddr = (u32)uaddr; + uaddr &= PAGE_MASK; + full_uaddr = clear_lo32(arena->user_vm_start) + uaddr; + if (full_uaddr < arena->user_vm_start) + return; + uaddr_end = min(arena->user_vm_end, full_uaddr + (page_cnt << PAGE_SHIFT)); + if (full_uaddr >= uaddr_end) + return; + + page_cnt = (uaddr_end - full_uaddr) >> PAGE_SHIFT; + bpf_map_memcg_enter(&arena->map, &old_memcg, &new_memcg); + + /* Can't proceed without holding the spinlock so defer the free */ + if (!sleepable || arena_free_range(arena, uaddr, page_cnt)) + goto defer; + + bpf_map_memcg_exit(old_memcg, new_memcg); return; defer: @@ -974,66 +1070,18 @@ static void arena_free_worker(struct work_struct *work) { struct bpf_arena *arena = container_of(work, struct bpf_arena, free_work); struct mem_cgroup *new_memcg, *old_memcg; - struct llist_node *list, *pos, *t; + struct llist_node *pos, *t; struct arena_free_span *s; - u64 arena_vm_start, user_vm_start; - struct llist_head free_pages; - struct clear_range_data cdata; - struct page *page; - unsigned long full_uaddr; - long kaddr, page_cnt, pgoff; - unsigned long flags; - - if (raw_res_spin_lock_irqsave(&arena->spinlock, flags)) { - schedule_work(work); - return; - } bpf_map_memcg_enter(&arena->map, &old_memcg, &new_memcg); - init_llist_head(&free_pages); - cdata.arena = arena; - cdata.free_pages = &free_pages; - arena_vm_start = bpf_arena_get_kern_vm_start(arena); - user_vm_start = bpf_arena_get_user_vm_start(arena); - - list = llist_del_all(&arena->free_spans); - llist_for_each(pos, list) { + llist_for_each_safe(pos, t, llist_del_all(&arena->free_spans)) { s = llist_entry(pos, struct arena_free_span, node); - page_cnt = s->page_cnt; - kaddr = arena_vm_start + s->uaddr; - pgoff = compute_pgoff(arena, s->uaddr); - - /* clear ptes and collect pages in free_pages llist */ - apply_to_existing_page_range(&init_mm, kaddr, page_cnt << PAGE_SHIFT, - apply_range_clear_cb, &cdata); - - range_tree_set(&arena->rt, pgoff, page_cnt); - } - raw_res_spin_unlock_irqrestore(&arena->spinlock, flags); - - /* Iterate the list again without holding spinlock to do the tlb flush and zap_pages */ - llist_for_each_safe(pos, t, list) { - s = llist_entry(pos, struct arena_free_span, node); - page_cnt = s->page_cnt; - full_uaddr = clear_lo32(user_vm_start) + s->uaddr; - kaddr = arena_vm_start + s->uaddr; - - /* ensure no stale TLB entries */ - flush_tlb_kernel_range(kaddr, kaddr + (page_cnt * PAGE_SIZE)); - - /* remove pages from user vmas */ - zap_pages(arena, full_uaddr, page_cnt); - + while (arena_free_range(arena, s->uaddr, s->page_cnt)) + cond_resched(); kfree_nolock(s); } - /* free all pages collected by apply_to_existing_page_range() in the first loop */ - llist_for_each_safe(pos, t, __llist_del_all(&free_pages)) { - page = llist_entry(pos, struct page, pcp_llist); - __free_page(page); - } - bpf_map_memcg_exit(old_memcg, new_memcg); } diff --git a/kernel/bpf/arraymap.c b/kernel/bpf/arraymap.c index 0ce26b538075..133f189bf6d2 100644 --- a/kernel/bpf/arraymap.c +++ b/kernel/bpf/arraymap.c @@ -438,15 +438,15 @@ int bpf_percpu_array_update(struct bpf_map *map, void *key, void *value, u32 size; int cpu, off = 0; - if (unlikely((map_flags & BPF_F_LOCK) || (u32)map_flags > BPF_F_ALL_CPUS)) - /* unknown flags */ + if (unlikely(((map_flags & BPF_EXIST_FLAGS) == BPF_EXIST_FLAGS) || + ((u32)map_flags & ~(BPF_EXIST_FLAGS | BPF_CPU_FLAGS)))) return -EINVAL; if (unlikely(index >= array->map.max_entries)) /* all elements were pre-allocated, cannot insert a new one */ return -E2BIG; - if (unlikely(map_flags == BPF_NOEXIST)) + if (unlikely(map_flags & BPF_NOEXIST)) /* all elements already exist */ return -EEXIST; @@ -1035,7 +1035,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/backtrack.c b/kernel/bpf/backtrack.c index 47282ffeeaf9..44d107fd96c4 100644 --- a/kernel/bpf/backtrack.c +++ b/kernel/bpf/backtrack.c @@ -693,10 +693,12 @@ void bpf_mark_all_scalars_precise(struct bpf_verifier_env *env, i, j); } } - for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { - if (!bpf_is_spilled_reg(&func->stack[j])) + for (j = 0; j < bpf_stack_nr_slots(func); j++) { + struct bpf_stack_state *ss = bpf_stack_slot(func, j); + + if (!bpf_is_spilled_reg(ss)) continue; - reg = &func->stack[j].spilled_ptr; + reg = &ss->spilled_ptr; if (reg->type != SCALAR_VALUE || reg->precise) continue; reg->precise = true; @@ -808,6 +810,7 @@ int bpf_mark_chain_precision(struct bpf_verifier_env *env, int subseq_idx = -1; struct bpf_func_state *func; bool tmp, skip_first = true; + struct bpf_stack_state *ss; struct bpf_reg_state *reg; int i, fr, err; @@ -932,16 +935,17 @@ int bpf_mark_chain_precision(struct bpf_verifier_env *env, bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); for_each_set_bit(i, mask, 64) { - if (verifier_bug_if(i >= func->allocated_stack / BPF_REG_SIZE, + if (verifier_bug_if(i >= bpf_stack_nr_slots(func), env, "stack slot %d, total slots %d", - i, func->allocated_stack / BPF_REG_SIZE)) + i, bpf_stack_nr_slots(func))) return -EFAULT; - if (!bpf_is_spilled_scalar_reg(&func->stack[i])) { + ss = bpf_stack_slot(func, i); + if (!bpf_is_spilled_scalar_reg(ss)) { bt_clear_frame_slot(bt, fr, i); continue; } - reg = &func->stack[i].spilled_ptr; + reg = &ss->spilled_ptr; if (reg->precise) { bt_clear_frame_slot(bt, fr, i); } else { diff --git a/kernel/bpf/bpf_insn_array.c b/kernel/bpf/bpf_insn_array.c index a2f84afe6f7c..61d6a076dfdb 100644 --- a/kernel/bpf/bpf_insn_array.c +++ b/kernel/bpf/bpf_insn_array.c @@ -199,12 +199,16 @@ int bpf_insn_array_init(struct bpf_map *map, const struct bpf_prog *prog) return -EBUSY; /* - * Reset all the map indexes to the original values. This is needed, - * e.g., when a replay of verification with different log level should - * be performed. + * Reset the map to its pre-verification state. The xlated and jitted + * offsets and the jitted target pointers are recomputed by the verifier + * and the JIT for this program, so any values left by a previous owner + * must be cleared here. */ - for (i = 0; i < map->max_entries; i++) + for (i = 0; i < map->max_entries; i++) { values[i].xlated_off = values[i].orig_off; + values[i].jitted_off = 0; + insn_array->ips[i] = 0; + } return 0; } @@ -228,7 +232,8 @@ void bpf_insn_array_release(struct bpf_map *map) { struct bpf_insn_array *insn_array = cast_insn_array(map); - atomic_set(&insn_array->used, 0); + /* Paired with atomic_xchg() in bpf_insn_array_init(). */ + atomic_set_release(&insn_array->used, 0); } void bpf_insn_array_adjust(struct bpf_map *map, u32 off, u32 len) diff --git a/kernel/bpf/bpf_iter.c b/kernel/bpf/bpf_iter.c index b40eb404adab..8e5069b477aa 100644 --- a/kernel/bpf/bpf_iter.c +++ b/kernel/bpf/bpf_iter.c @@ -72,6 +72,15 @@ static inline bool bpf_iter_target_support_resched(const struct bpf_iter_target_ return tinfo->reg_info->feature & BPF_ITER_RESCHED; } +/* Only allow sleepable program for resched-able iterator that can run one */ +static bool bpf_iter_target_support_prog(const struct bpf_iter_target_info *tinfo, + const struct bpf_prog *prog) +{ + return !prog->sleepable || + (bpf_iter_target_support_resched(tinfo) && + !(tinfo->reg_info->feature & BPF_ITER_NOSLEEP)); +} + static bool bpf_iter_support_resched(struct seq_file *seq) { struct bpf_iter_priv_data *iter_priv; @@ -342,6 +351,13 @@ int bpf_iter_prog_supported(struct bpf_prog *prog) const char *prefix = BPF_ITER_FUNC_PREFIX; int prefix_len = strlen(prefix); + /* + * The attach function of a program that has a target program is a + * function of that program, whatever its name is. + */ + if (prog->aux->dst_prog) + return -EINVAL; + if (strncmp(attach_fname, prefix, prefix_len)) return -EINVAL; @@ -409,6 +425,8 @@ static int bpf_iter_link_replace(struct bpf_link *link, struct bpf_prog *new_prog, struct bpf_prog *old_prog) { + struct bpf_iter_link *iter_link = + container_of(link, struct bpf_iter_link, link); int ret = 0; mutex_lock(&link_mutex); @@ -419,7 +437,8 @@ static int bpf_iter_link_replace(struct bpf_link *link, if (link->prog->type != new_prog->type || link->prog->expected_attach_type != new_prog->expected_attach_type || - link->prog->aux->attach_btf_id != new_prog->aux->attach_btf_id) { + link->prog->aux->attach_btf_id != new_prog->aux->attach_btf_id || + !bpf_iter_target_support_prog(iter_link->tinfo, new_prog)) { ret = -EINVAL; goto out_unlock; } @@ -544,8 +563,7 @@ int bpf_iter_link_attach(const union bpf_attr *attr, bpfptr_t uattr, if (!tinfo) return -ENOENT; - /* Only allow sleepable program for resched-able iterator */ - if (prog->sleepable && !bpf_iter_target_support_resched(tinfo)) + if (!bpf_iter_target_support_prog(tinfo, prog)) return -EINVAL; link = kzalloc_obj(*link, GFP_USER | __GFP_NOWARN); diff --git a/kernel/bpf/bpf_local_storage.c b/kernel/bpf/bpf_local_storage.c index 6fc6a4b672b5..94b1858ff32d 100644 --- a/kernel/bpf/bpf_local_storage.c +++ b/kernel/bpf/bpf_local_storage.c @@ -199,7 +199,7 @@ static void bpf_selem_unlink_storage_nolock_misc(struct bpf_local_storage_elem * } if (pin_owner) - refcount_dec(&local_storage->owner_refcnt); + bpf_local_storage_unpin_owner(local_storage); } /* local_storage->lock must be held and selem->local_storage == local_storage. @@ -350,7 +350,8 @@ int bpf_selem_unlink(struct bpf_local_storage_elem *selem) static void bpf_selem_unlink_nofail(struct bpf_local_storage_elem *selem, struct bpf_local_storage_map_bucket *b) { - bool in_map_free = !!b, free_storage = false; + bool in_map_free = !!b, free_storage = false, sleepable_users = false; + bool keep_fields = false; struct bpf_local_storage *local_storage; struct bpf_local_storage_map *smap; unsigned long flags; @@ -360,17 +361,26 @@ static void bpf_selem_unlink_nofail(struct bpf_local_storage_elem *selem, smap = rcu_dereference_check(SDATA(selem)->smap, bpf_rcu_lock_held()); if (smap) { + /* A map that is freed, or NULL here, has no program left. */ + sleepable_users = !in_map_free && + (atomic64_read(&smap->map.sleepable_refcnt) || + READ_ONCE(smap->map.was_inner_map)); b = b ? : select_bucket(smap, local_storage); err = raw_res_spin_lock_irqsave(&b->lock, flags); if (!err) { /* * Call bpf_obj_free_fields() under b->lock to make sure it is done * exactly once for an selem. Safe to free special fields immediately - * as no BPF program should be referencing the selem. + * as no BPF program should be referencing the selem, unless it + * is sleepable: see below. */ if (likely(selem_linked_to_map(selem))) { hlist_del_init_rcu(&selem->map_node); - bpf_obj_free_fields(smap->map.record, SDATA(selem)->data); + if (sleepable_users) + keep_fields = true; + else + bpf_obj_free_fields(smap->map.record, + SDATA(selem)->data); unlink++; } raw_res_spin_unlock_irqrestore(&b->lock, flags); @@ -385,7 +395,15 @@ static void bpf_selem_unlink_nofail(struct bpf_local_storage_elem *selem, * with selem1 as raw_res_spin_lock_irqsave() returns -ETIMEDOUT. */ WARN_ON_ONCE(err && in_map_free); - if (!err || in_map_free) + /* + * A sleepable program can still use, and fill, the fields of a value + * that it got before it let go of the owner. As for bpf_selem_unlink(), + * bpf_selem_free_trace_rcu() frees them, and takes smap for that: + * map_free() waits for this RCU read side critical section and then + * for the callback. It must not take smap away from an selem that + * destroy() has unlinked from the map. + */ + if (in_map_free ? err || unlink : !err && !keep_fields) RCU_INIT_POINTER(SDATA(selem)->smap, NULL); } @@ -429,13 +447,18 @@ static void bpf_selem_unlink_nofail(struct bpf_local_storage_elem *selem, * then freed after an RCU grace period. However, if destroy() and map_free() are * racing or rqspinlock returns errors in unlikely situations (unlink != 2), free * the selem only after both map_free() and destroy() see the selem. + * + * The owner that map_free() takes an selem from is alive: sleepable code, which + * is in no RCU read side critical section, may be walking its list for another + * map. And it can still use a value that it got before it let go of an owner + * that destroy() is called for. */ if (unlink == 2 || atomic_cmpxchg(&selem->state, SELEM_UNLINKED, SELEM_TOFREE) == SELEM_UNLINKED) - bpf_selem_free(selem, true); + bpf_selem_free(selem, !in_map_free && !sleepable_users); if (free_storage) - bpf_local_storage_free(local_storage, true); + bpf_local_storage_free(local_storage, !in_map_free); } void __bpf_local_storage_insert_cache(struct bpf_local_storage *local_storage, @@ -507,8 +530,6 @@ int bpf_local_storage_alloc(void *owner, if (err) goto uncharge; - bpf_selem_link_map_nolock(b, first_selem); - owner_storage_ptr = (struct bpf_local_storage **)owner_storage(smap, owner); /* Publish storage to the owner. @@ -523,11 +544,17 @@ int bpf_local_storage_alloc(void *owner, */ prev_storage = cmpxchg(owner_storage_ptr, NULL, storage); if (unlikely(prev_storage)) { - bpf_selem_unlink_map_nolock(first_selem); raw_res_spin_unlock_irqrestore(&b->lock, flags); err = -EAGAIN; goto uncharge; } + /* + * Not before the storage is published: the owner does not wait for + * users of a storage that it knows nothing of, so that nobody may find + * such a storage through the map. b->lock holds off those who find + * first_selem through the owner and want to unlink it. + */ + bpf_selem_link_map_nolock(b, first_selem); raw_res_spin_unlock_irqrestore(&b->lock, flags); return 0; @@ -750,8 +777,8 @@ u32 bpf_local_storage_destroy(struct bpf_local_storage *local_storage) while (refcount_read(&local_storage->owner_refcnt)) cpu_relax(); /* - * Paired with refcount_dec() in bpf_selem_unlink_nofail() - * to make sure destroy() sees the correct local_storage->mem_charge. + * Paired with bpf_local_storage_unpin_owner() to make sure + * destroy() sees the correct local_storage->mem_charge. */ smp_mb(); } diff --git a/kernel/bpf/bpf_lsm.c b/kernel/bpf/bpf_lsm.c index 82c5988417a0..2660a89fc8d7 100644 --- a/kernel/bpf/bpf_lsm.c +++ b/kernel/bpf/bpf_lsm.c @@ -414,8 +414,8 @@ const struct bpf_prog_ops lsm_prog_ops = { }; const struct bpf_verifier_ops lsm_verifier_ops = { - .get_func_proto = bpf_lsm_func_proto, - .is_valid_access = btf_ctx_access, + .get_func_proto = bpf_lsm_func_proto, + .is_valid_access = bpf_tracing_btf_ctx_access, }; /* hooks return 0 or 1 */ diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c index d870bc5e50bc..b13302f33ff5 100644 --- a/kernel/bpf/btf.c +++ b/kernel/bpf/btf.c @@ -1065,6 +1065,8 @@ static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf, } #define BTF_SHOW_MAX_ITER 10 +/* nested structs and arrays shown; __btf_show_indent() has as many columns */ +#define BTF_SHOW_MAX_DEPTH 32 #define BTF_KIND_BIT(kind) (1ULL << kind) @@ -1458,8 +1460,18 @@ static void *btf_show_start_aggr_type(struct btf_show *show, const struct btf_type *t, u32 type_id, void *data) { - void *safe_data = btf_show_start_type(show, t, type_id, data); + void *safe_data; + + /* + * Structs and arrays are shown by recursion. BTF loading bounds the + * depth of one resolve walk, not how deep resolved types may nest. + */ + if (show->state.depth >= BTF_SHOW_MAX_DEPTH) { + show->state.status = -E2BIG; + return NULL; + } + safe_data = btf_show_start_type(show, t, type_id, data); if (!safe_data) return safe_data; @@ -1724,15 +1736,16 @@ static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t) /* Expand 'types' array */ struct btf_type **new_types; - u32 expand_by, new_size; + u32 expand_by, new_size, max_size; - if (btf->start_id + btf->types_size == BTF_MAX_TYPE) { + if (btf->start_id + btf->types_size >= BTF_MAX_TYPE) { btf_verifier_log(env, "Exceeded max num of types"); return -E2BIG; } + max_size = BTF_MAX_TYPE - btf->start_id; expand_by = max_t(u32, btf->types_size >> 2, 16); - new_size = min_t(u32, BTF_MAX_TYPE, + new_size = min_t(u32, max_size, btf->types_size + expand_by); new_types = kvzalloc_objs(*new_types, new_size, @@ -5459,6 +5472,7 @@ static int btf_check_all_metas(struct btf_verifier_env *env) struct btf *btf = env->btf; struct btf_header *hdr; void *cur, *end; + int err; hdr = &btf->hdr; cur = btf->nohdr_data + hdr->type_off; @@ -5473,7 +5487,10 @@ static int btf_check_all_metas(struct btf_verifier_env *env) if (meta_size < 0) return meta_size; - btf_add_type(env, t); + err = btf_add_type(env, t); + if (err) + return err; + cur += meta_size; env->log_type_id++; } @@ -8843,6 +8860,10 @@ static int btf_check_iter_kfuncs(struct btf *btf, const char *func_name, if (!flags || (flags & (flags - 1))) return -EINVAL; + if ((func_flags & KF_ITER_RET_INDEPENDENT) && + (!(flags & KF_ITER_NEXT) || (func_flags & KF_ACQUIRE))) + return -EINVAL; + /* any BPF iter kfunc should have `struct bpf_iter_ *` first arg */ nr_args = btf_type_vlen(func); if (nr_args < 1) @@ -8883,6 +8904,12 @@ static int btf_check_iter_kfuncs(struct btf *btf, const char *func_name, t = btf_type_skip_modifiers(btf, func->type, NULL); if (!t || !btf_type_is_ptr(t)) return -EINVAL; + /* The opt-out applies only to non-acquired struct results. */ + if (func_flags & KF_ITER_RET_INDEPENDENT) { + t = btf_type_skip_modifiers(btf, t->type, NULL); + if (!t || !__btf_type_is_struct(t)) + return -EINVAL; + } } if (flags & KF_ITER_DESTROY) { @@ -8949,7 +8976,8 @@ static int btf_check_kfunc_protos(struct btf *btf, u32 func_id, u32 func_flags) if (!func || !btf_type_is_func_proto(func)) return -EINVAL; - if (func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)) { + if (func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY | + KF_ITER_RET_INDEPENDENT)) { err = btf_check_iter_kfuncs(btf, func_name, func, func_flags); if (err) return err; diff --git a/kernel/bpf/cfg.c b/kernel/bpf/cfg.c index 842c7d1eabcc..5501ccc6649f 100644 --- a/kernel/bpf/cfg.c +++ b/kernel/bpf/cfg.c @@ -9,6 +9,8 @@ #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args) +#define BPF_MAX_GOTOX_EDGES BPF_COMPLEXITY_LIMIT_INSNS + /* non-recursive DFS pseudo code * 1 procedure DFS-iterative(G,v): * 2 label v as discovered @@ -388,6 +390,19 @@ static int visit_gotox_insn(int t, struct bpf_verifier_env *env) return PTR_ERR(jt); env->insn_aux_data[t].jt = jt; + + if (check_add_overflow(env->cfg.gotox_edges, jt->cnt, + &env->cfg.gotox_edges) || + env->cfg.gotox_edges > BPF_MAX_GOTOX_EDGES) { + verbose(env, "number of indirect jump edges in the program exceeds %u\n", + BPF_MAX_GOTOX_EDGES); + bpf_diag_program_structure( + env, t, "too many indirect jump edges", + "Reduce the number of indirect jumps, or the number of distinct targets they can reach.", + "The program has more than %u indirect jump edges in total, counted over every gotox instruction.", + BPF_MAX_GOTOX_EDGES); + return -E2BIG; + } } mark_prune_point(env, t); @@ -430,17 +445,21 @@ static int visit_abnormal_return_insn(struct bpf_verifier_env *env, int t) { struct bpf_subprog_info *subprog; struct bpf_iarray *jt; + u32 n; if (env->insn_aux_data[t].jt) return 0; - jt = bpf_iarray_realloc(NULL, 2); + /* A subprogram without an exit has no hidden exit edge to take. */ + subprog = bpf_find_containing_subprog(env, t); + n = subprog->exit_idx == U32_MAX ? 1 : 2; + jt = bpf_iarray_realloc(NULL, n); if (!jt) return -ENOMEM; - subprog = bpf_find_containing_subprog(env, t); jt->items[0] = t + 1; - jt->items[1] = subprog->exit_idx; + if (n == 2) + jt->items[1] = subprog->exit_idx; env->insn_aux_data[t].jt = jt; return 0; } @@ -510,7 +529,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); if (insn->imm == BPF_FUNC_tail_call) { ret = visit_abnormal_return_insn(env, t); @@ -684,6 +705,11 @@ int bpf_check_cfg(struct bpf_verifier_env *env) return ret; } +struct dfs_state { + u32 traversed:1; + u32 next_succ:31; +}; + /* * For each subprogram 'i' fill array env->cfg.insn_subprogram sub-range * [env->subprog_info[i].postorder_start, env->subprog_info[i+1].postorder_start) @@ -691,43 +717,52 @@ int bpf_check_cfg(struct bpf_verifier_env *env) */ int bpf_compute_postorder(struct bpf_verifier_env *env) { - u32 cur_postorder, i, top, stack_sz, s; - int *stack = NULL, *postorder = NULL, *state = NULL; - struct bpf_iarray *succ; + int *stack = NULL, *postorder = NULL, *postorder_nums = NULL; + int subprog_idx, stack_sz, cur, s, cur_postorder, start; + struct dfs_state *state = NULL; + struct bpf_iarray *succ = NULL; + postorder_nums = kvzalloc_objs(int, env->prog->len, GFP_KERNEL_ACCOUNT); postorder = kvzalloc_objs(int, env->prog->len, GFP_KERNEL_ACCOUNT); - state = kvzalloc_objs(int, env->prog->len, GFP_KERNEL_ACCOUNT); stack = kvzalloc_objs(int, env->prog->len, GFP_KERNEL_ACCOUNT); - if (!postorder || !state || !stack) { + state = kvzalloc_objs(struct dfs_state, env->prog->len, GFP_KERNEL_ACCOUNT); + if (!postorder_nums || !postorder || !stack || !state) { + kvfree(postorder_nums); kvfree(postorder); - kvfree(state); kvfree(stack); + kvfree(state); return -ENOMEM; } cur_postorder = 0; - for (i = 0; i < env->subprog_cnt; i++) { - env->subprog_info[i].postorder_start = cur_postorder; - stack[0] = env->subprog_info[i].start; + for (subprog_idx = 0; subprog_idx < env->subprog_cnt; subprog_idx++) { + start = env->subprog_info[subprog_idx].start; + env->subprog_info[subprog_idx].postorder_start = cur_postorder; + stack[0] = start; stack_sz = 1; + state[start].traversed = true; do { - top = stack[stack_sz - 1]; - state[top] |= DISCOVERED; - if (state[top] & EXPLORED) { - postorder[cur_postorder++] = top; + cur = stack[stack_sz - 1]; + succ = bpf_insn_successors(env, cur); + if (state[cur].next_succ == succ->cnt) { + postorder_nums[cur] = cur_postorder; + postorder[cur_postorder] = cur; + cur_postorder++; stack_sz--; continue; } - succ = bpf_insn_successors(env, top); - for (s = 0; s < succ->cnt; ++s) { - if (!state[succ->items[s]]) { - stack[stack_sz++] = succ->items[s]; - state[succ->items[s]] |= DISCOVERED; - } + s = succ->items[state[cur].next_succ]; + if (!state[s].traversed) { + state[s].traversed = true; + state[s].next_succ = 0; + stack[stack_sz] = s; + stack_sz++; + continue; } - state[top] |= EXPLORED; + state[cur].next_succ++; } while (stack_sz); } - env->subprog_info[i].postorder_start = cur_postorder; + env->subprog_info[subprog_idx].postorder_start = cur_postorder; + env->cfg.postorder_nums = postorder_nums; env->cfg.insn_postorder = postorder; env->cfg.cur_postorder = cur_postorder; kvfree(stack); @@ -749,7 +784,7 @@ int bpf_compute_scc(struct bpf_verifier_env *env) struct bpf_insn_aux_data *aux = env->insn_aux_data; const u32 insn_cnt = env->prog->len; int stack_sz, dfs_sz, err = 0; - u32 *stack, *pre, *low, *dfs; + u32 *stack, *pre, *low, *dfs, *dfs_pos; u32 i, j, t, w; u32 next_preorder_num; u32 next_scc_id; @@ -762,13 +797,16 @@ int bpf_compute_scc(struct bpf_verifier_env *env) * - 'stack' accumulates vertices in DFS order, see invariant comment below; * - 'pre[t] == p' => preorder number of vertex 't' is 'p'; * - 'low[t] == n' => smallest preorder number of the vertex reachable from 't' is 'n'; - * - 'dfs' DFS traversal stack, used to emulate explicit recursion. + * - 'dfs' DFS traversal stack, used to emulate explicit recursion; + * - 'dfs_pos[k] == j' => the frame 'dfs[k]' resumes visiting its + * successors at index 'j'. */ stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); pre = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); low = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); dfs = kvcalloc(insn_cnt, sizeof(*dfs), GFP_KERNEL_ACCOUNT); - if (!stack || !pre || !low || !dfs) { + dfs_pos = kvcalloc(insn_cnt, sizeof(*dfs_pos), GFP_KERNEL_ACCOUNT); + if (!stack || !pre || !low || !dfs || !dfs_pos) { err = -ENOMEM; goto exit; } @@ -851,6 +889,7 @@ int bpf_compute_scc(struct bpf_verifier_env *env) stack_sz = 0; dfs_sz = 1; dfs[0] = i; + dfs_pos[0] = 0; dfs_continue: while (dfs_sz) { w = dfs[dfs_sz - 1]; @@ -860,13 +899,22 @@ int bpf_compute_scc(struct bpf_verifier_env *env) next_preorder_num++; stack[stack_sz++] = w; } - /* Visit 'w' successors */ + /* Visit remaining 'w' successors */ succ = bpf_insn_successors(env, w); - for (j = 0; j < succ->cnt; ++j) { + for (j = dfs_pos[dfs_sz - 1]; j < succ->cnt; ++j) { if (pre[succ->items[j]]) { low[w] = min(low[w], low[succ->items[j]]); } else { - dfs[dfs_sz++] = succ->items[j]; + /* + * Once DFS for succ->items[j] is complete, + * pre[succ->items[j]] is non-zero, hence + * resuming at 'j' allows to follow the + * low[w] = min(...) update branch above. + */ + dfs_pos[dfs_sz - 1] = j; + dfs_pos[dfs_sz] = 0; + dfs[dfs_sz] = succ->items[j]; + dfs_sz++; goto dfs_continue; } } @@ -916,5 +964,6 @@ int bpf_compute_scc(struct bpf_verifier_env *env) kvfree(pre); kvfree(low); kvfree(dfs); + kvfree(dfs_pos); return err; } diff --git a/kernel/bpf/const_fold.c b/kernel/bpf/const_fold.c index 7f1b30059cc8..d8d2d00380ae 100644 --- a/kernel/bpf/const_fold.c +++ b/kernel/bpf/const_fold.c @@ -394,5 +394,7 @@ int bpf_prune_dead_branches(struct bpf_verifier_env *env) /* recompute postorder, since CFG has changed */ kvfree(env->cfg.insn_postorder); env->cfg.insn_postorder = NULL; + kvfree(env->cfg.postorder_nums); + env->cfg.postorder_nums = NULL; return bpf_compute_postorder(env); } diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c index 7f11555a5070..f4682bcaea9d 100644 --- a/kernel/bpf/core.c +++ b/kernel/bpf/core.c @@ -273,6 +273,7 @@ struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size, memcpy(fp, fp_old, fp_old->pages * PAGE_SIZE); fp->pages = pages; fp->aux->prog = fp; + bpf_prog_dev_bound_moved(fp); /* We keep fp->aux from fp_old around in the new * reallocated structure. @@ -1555,8 +1556,7 @@ void bpf_jit_prog_release_other(struct bpf_prog *fp, struct bpf_prog *fp_other) * know whether fp here is the clone or the original. */ fp->aux->prog = fp; - if (fp->aux->offload) - fp->aux->offload->prog = fp; + bpf_prog_dev_bound_moved(fp); bpf_prog_clone_free(fp_other); } @@ -3035,7 +3035,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) @@ -3073,12 +3073,40 @@ static void bpf_free_used_btfs(struct bpf_prog_aux *aux) kfree(aux->used_btfs); } -static void bpf_prog_free_deferred(struct work_struct *work) +static void bpf_prog_free_images(struct work_struct *work) { struct bpf_prog_aux *aux; int i; + aux = container_of(to_rcu_work(work), struct bpf_prog_aux, rwork); + for (i = 0; i < aux->real_func_cnt; i++) { + /* We can just unlink the subprog poke descriptor table as + * it was originally linked to the main program and is also + * released along with it. + */ + aux->func[i]->aux->poke_tab = NULL; + bpf_jit_free(aux->func[i]); + } + if (aux->real_func_cnt) { + kfree(aux->func); + bpf_prog_unlock_free(aux->prog); + } else { + bpf_jit_free(aux->prog); + } +} + +static void bpf_prog_free_deferred(struct work_struct *work) +{ + struct bpf_prog_aux *aux; + bool ksyms; + aux = container_of(work, struct bpf_prog_aux, work); + /* + * A prog that still runs when its last reference goes needs its symbols, + * by which its exception table is found. It has ended by now. + */ + ksyms = aux->real_func_cnt || !list_empty(&aux->ksym.lnode); + bpf_prog_kallsyms_del_all(aux->prog); #ifdef CONFIG_BPF_SYSCALL bpf_free_kfunc_btf_tab(aux->kfunc_btf_tab); bpf_prog_stream_free(aux->prog); @@ -3098,20 +3126,12 @@ static void bpf_prog_free_deferred(struct work_struct *work) #endif if (aux->dst_trampoline) bpf_trampoline_put(aux->dst_trampoline); - for (i = 0; i < aux->real_func_cnt; i++) { - /* We can just unlink the subprog poke descriptor table as - * it was originally linked to the main program and is also - * released along with it. - */ - aux->func[i]->aux->poke_tab = NULL; - bpf_jit_free(aux->func[i]); - } - if (aux->real_func_cnt) { - kfree(aux->func); - bpf_prog_unlock_free(aux->prog); - } else { - bpf_jit_free(aux->prog); - } + /* The symbols are looked up under rcu_read_lock() */ + INIT_RCU_WORK(&aux->rwork, bpf_prog_free_images); + if (ksyms) + queue_rcu_work(system_percpu_wq, &aux->rwork); + else + bpf_prog_free_images(&aux->rwork.work); } void bpf_prog_free(struct bpf_prog *fp) diff --git a/kernel/bpf/cpumap.c b/kernel/bpf/cpumap.c index 5e59ab896f05..eb87131b1bef 100644 --- a/kernel/bpf/cpumap.c +++ b/kernel/bpf/cpumap.c @@ -45,6 +45,7 @@ */ #define CPU_MAP_BULK_SIZE 8 /* 8 == one cacheline on 64-bit archs */ +#define CPU_MAP_HELD_DEVS 2048 struct bpf_cpu_map_entry; struct bpf_cpu_map; @@ -74,6 +75,13 @@ struct bpf_cpu_map_entry { struct completion kthread_running; struct rcu_work free_work; + + /* + * Every frame and skb in the queue holds a reference to its device. + * The kthread keeps it until nothing is left in GRO. + */ + struct net_device *held[CPU_MAP_HELD_DEVS]; + u32 nr_held; }; struct bpf_cpu_map { @@ -129,9 +137,11 @@ static void __cpu_map_ring_cleanup(struct ptr_ring *ring) WARN_ON_ONCE(1); if (unlikely(__ptr_test_bit(0, &ptr))) { __ptr_clear_bit(0, &ptr); + dev_put(((struct sk_buff *)ptr)->dev); kfree_skb(ptr); continue; } + dev_put(((struct xdp_frame *)ptr)->dev_rx); xdp_return_frame(ptr); } } @@ -311,7 +321,7 @@ static int cpu_map_kthread_run(void *data) void *frames[CPUMAP_BATCH]; void *skbs[CPUMAP_BATCH]; u32 i, n, m; - bool empty; + bool empty, full; /* Release CPU reschedule checks */ if (__ptr_ring_empty(rcpu->queue)) { @@ -344,10 +354,12 @@ static int cpu_map_kthread_run(void *data) struct sk_buff *skb = f; __ptr_clear_bit(0, &skb); + rcpu->held[rcpu->nr_held++] = skb->dev; skbs[ret.skb_n++] = skb; continue; } + rcpu->held[rcpu->nr_held++] = ((struct xdp_frame *)f)->dev_rx; frames[ret.xdp_n++] = f; page = virt_to_page(f); @@ -398,10 +410,13 @@ static int cpu_map_kthread_run(void *data) /* Flush either every 64 packets or in case of empty ring */ packets += n; empty = __ptr_ring_empty(rcpu->queue); - if (packets >= NAPI_POLL_WEIGHT || empty) { - cpu_map_gro_flush(rcpu, empty); + full = empty || rcpu->nr_held > CPU_MAP_HELD_DEVS - CPUMAP_BATCH; + if (packets >= NAPI_POLL_WEIGHT || full) { + cpu_map_gro_flush(rcpu, full); packets = 0; } + while (full && rcpu->nr_held) + dev_put(rcpu->held[--rcpu->nr_held]); local_bh_enable(); /* resched point, may call do_softirq() */ } @@ -738,12 +753,14 @@ static void bq_flush_to_queue(struct xdp_bulk_queue *bq) for (i = 0; i < bq->count; i++) { struct xdp_frame *xdpf = bq->q[i]; - int err; - err = __ptr_ring_produce(q, xdpf); - if (err) { + if (__ptr_ring_full(q)) { drops++; xdp_return_frame_rx_napi(xdpf); + } else { + /* The device cannot go before the flush, from now on it can */ + dev_hold(xdpf->dev_rx); + __ptr_ring_produce(q, xdpf); } processed++; } @@ -807,11 +824,15 @@ int cpu_map_generic_redirect(struct bpf_cpu_map_entry *rcpu, __skb_pull(skb, skb->mac_len); skb_set_redirected(skb, false); + dev_hold(skb->dev); __ptr_set_bit(0, &skb); ret = ptr_ring_produce(rcpu->queue, skb); - if (ret < 0) + if (ret < 0) { + __ptr_clear_bit(0, &skb); + dev_put(skb->dev); goto trace; + } wake_up_process(rcpu->kthread); trace: diff --git a/kernel/bpf/devmap.c b/kernel/bpf/devmap.c index dc7b859e8bbf..1b8f0d7f8455 100644 --- a/kernel/bpf/devmap.c +++ b/kernel/bpf/devmap.c @@ -350,6 +350,7 @@ static int dev_map_bpf_prog_run(struct bpf_prog *xdp_prog, xdp_convert_frame_to_buff(xdpf, &xdp); xdp.txq = &txq; + rxq.mem.type = xdpf->mem_type; xdp.rxq = &rxq; act = bpf_prog_run_xdp(xdp_prog, &xdp); diff --git a/kernel/bpf/diagnostics.c b/kernel/bpf/diagnostics.c index 0abbbe177e31..67cd75d1cf38 100644 --- a/kernel/bpf/diagnostics.c +++ b/kernel/bpf/diagnostics.c @@ -794,8 +794,9 @@ static void diag_print_insn_context(struct bpf_verifier_env *env, u32 insn_idx, } } -static void bpf_diag_source(struct bpf_verifier_env *env, u32 insn_idx, const char *label, - const char *fmt, ...) +static __printf(4, 5) void bpf_diag_source(struct bpf_verifier_env *env, + u32 insn_idx, const char *label, + const char *fmt, ...) { struct bpf_diag_scratch *scratch; struct bpf_linfo_source *source_lines; @@ -1087,16 +1088,17 @@ void bpf_diag_ctx_forbidden(struct bpf_verifier_env *env, u32 insn_idx, const char *constraint, *context; u32 depth; - if (env->cur_state->active_rcu_locks) - ctx_kind = BPF_DIAG_CONTEXT_RCU; - else if (env->cur_state->active_preempt_locks) - ctx_kind = BPF_DIAG_CONTEXT_PREEMPT; - else if (env->cur_state->active_irq_id) - ctx_kind = BPF_DIAG_CONTEXT_IRQ; - else if (env->cur_state->active_locks) - ctx_kind = BPF_DIAG_CONTEXT_LOCK; - else - ctx_kind = BPF_DIAG_CONTEXT_NONE; + ctx_kind = BPF_DIAG_CONTEXT_NONE; + if (env->cur_state->in_sleepable) { + if (env->cur_state->active_rcu_locks) + ctx_kind = BPF_DIAG_CONTEXT_RCU; + else if (env->cur_state->active_preempt_locks) + ctx_kind = BPF_DIAG_CONTEXT_PREEMPT; + else if (env->cur_state->active_irq_id) + ctx_kind = BPF_DIAG_CONTEXT_IRQ; + else if (env->cur_state->active_locks) + ctx_kind = BPF_DIAG_CONTEXT_LOCK; + } depth = diag_context_depth(env, ctx_kind); opts = (struct bpf_diag_history_opts) { @@ -1568,9 +1570,9 @@ static struct bpf_reg_state *target_to_reg(struct bpf_verifier_env *env, return NULL; return &state->stack_arg_regs[target->stack_arg]; case BPF_DIAG_MOD_TARGET_STACK_SLOT: - if (target->spi >= state->allocated_stack / BPF_REG_SIZE) + if (target->spi >= bpf_stack_nr_slots(state)) return NULL; - return &state->stack[target->spi].spilled_ptr; + return &bpf_stack_slot(state, target->spi)->spilled_ptr; default: return NULL; } @@ -1586,7 +1588,7 @@ static bool reg_to_target(struct bpf_verifier_env *env, const struct bpf_reg_sta for (frame = 0; frame <= vstate->curframe; frame++) { struct bpf_func_state *state = vstate->frame[frame]; unsigned long start, end; - u32 nslots = state->allocated_stack / BPF_REG_SIZE; + u32 nslots = bpf_stack_nr_slots(state); int spi; start = (unsigned long)state->regs; @@ -1605,6 +1607,11 @@ static bool reg_to_target(struct bpf_verifier_env *env, const struct bpf_reg_sta return true; } + /* + * Map the pointer back to its slot by address, which relies on + * the slots forming one contiguous array as bpf_stack_slot() + * indexes it. + */ start = (unsigned long)state->stack; end = (unsigned long)(state->stack + nslots); if (nslots && addr >= start && addr < end) { diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c index d6f83521fc78..5a5f7ec21f2d 100644 --- a/kernel/bpf/fixups.c +++ b/kernel/bpf/fixups.c @@ -355,6 +355,44 @@ struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 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'. @@ -440,6 +478,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) @@ -638,6 +679,7 @@ int bpf_opt_remove_dead_code(struct bpf_verifier_env *env) int bpf_opt_remove_nops(struct bpf_verifier_env *env) { + struct bpf_insn_aux_data *aux = env->insn_aux_data; struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; bool is_may_goto_0, is_ja; @@ -649,6 +691,8 @@ int bpf_opt_remove_nops(struct bpf_verifier_env *env) if (!is_may_goto_0 && !is_ja) continue; + if (aux[i].indirect_target) + continue; err = verifier_remove_insns(env, i, 1); if (err) @@ -845,7 +889,13 @@ int bpf_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) @@ -1527,6 +1577,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. */ @@ -1804,6 +1878,18 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env) if (bpf_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 @@ -1820,22 +1906,8 @@ int bpf_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) @@ -1847,16 +1919,14 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env) goto next_insn; } else if (bpf_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) @@ -1948,6 +2018,10 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env) if (!bpf_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 @@ -2256,7 +2330,7 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env) cnt = 2; } insn_buf[cnt++] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); - insn_buf[cnt++] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); + insn_buf[cnt++] = BPF_ALU32_IMM(BPF_LSH, BPF_REG_2, 3); insn_buf[cnt++] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); @@ -2477,7 +2551,14 @@ int bpf_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) diff --git a/kernel/bpf/hashtab.c b/kernel/bpf/hashtab.c index 13a2356c84cf..b2b27f87d8f5 100644 --- a/kernel/bpf/hashtab.c +++ b/kernel/bpf/hashtab.c @@ -1107,11 +1107,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; @@ -1180,11 +1186,11 @@ static struct htab_elem *alloc_htab_elem(struct bpf_htab *htab, void *key, static int check_flags(struct bpf_htab *htab, struct htab_elem *l_old, u64 map_flags) { - if (l_old && (map_flags & ~BPF_F_LOCK) == BPF_NOEXIST) + if (l_old && (map_flags & BPF_NOEXIST)) /* elem already exists */ return -EEXIST; - if (!l_old && (map_flags & ~BPF_F_LOCK) == BPF_EXIST) + if (!l_old && (map_flags & BPF_EXIST)) /* elem doesn't exist, cannot update it */ return -ENOENT; @@ -1277,11 +1283,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, cancel - * its reusable special fields before it is available for reuse. + /* + * l_old replaces the extra element that alloc_htab_elem() took. + * Cancel its reusable 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_cancel_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)) @@ -1367,9 +1377,11 @@ static long htab_lru_map_update_elem(struct bpf_map *map, void *key, void *value static int htab_map_check_update_flags(bool onallcpus, u64 map_flags) { + if (unlikely((map_flags & BPF_EXIST_FLAGS) == BPF_EXIST_FLAGS)) + return -EINVAL; if (unlikely(!onallcpus && map_flags > BPF_EXIST)) return -EINVAL; - if (unlikely(onallcpus && ((map_flags & BPF_F_LOCK) || (u32)map_flags > BPF_F_ALL_CPUS))) + if (unlikely(onallcpus && ((u32)map_flags & ~(BPF_EXIST_FLAGS | BPF_CPU_FLAGS)))) return -EINVAL; return 0; } @@ -1467,7 +1479,7 @@ static long __htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key, * to remove older elem from htab and this removal * operation will need a bucket lock. */ - if (map_flags != BPF_EXIST) { + if (!(map_flags & BPF_EXIST)) { l_new = prealloc_lru_pop(htab, key, hash); if (!l_new) return -ENOMEM; diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c index 712dca5a2c5b..7c2e6f0e7409 100644 --- a/kernel/bpf/helpers.c +++ b/kernel/bpf/helpers.c @@ -1183,7 +1183,7 @@ static void bpf_async_refcount_put(struct bpf_async_cb *cb); static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer) { struct bpf_hrtimer *t = container_of(hrtimer, struct bpf_hrtimer, timer); - struct bpf_map *map = t->cb.map; + struct bpf_map *map = READ_ONCE(t->cb.map); void *value = t->cb.value; bpf_callback_t callback_fn; void *key; @@ -1191,7 +1191,7 @@ static enum hrtimer_restart bpf_timer_cb(struct hrtimer *hrtimer) BTF_TYPE_EMIT(struct bpf_timer); callback_fn = rcu_dereference_check(t->cb.callback_fn, rcu_read_lock_bh_held()); - if (!callback_fn) + if (!callback_fn || !map) goto out; /* bpf_timer_cb() runs in hrtimer_run_softirq. It doesn't migrate and @@ -1216,7 +1216,7 @@ static void bpf_wq_work(struct work_struct *work) { struct bpf_work *w = container_of(work, struct bpf_work, work); struct bpf_async_cb *cb = &w->cb; - struct bpf_map *map = cb->map; + struct bpf_map *map; bpf_callback_t callback_fn; void *value = cb->value; void *key; @@ -1224,18 +1224,22 @@ 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(); + + map = READ_ONCE(cb->map); callback_fn = READ_ONCE(cb->callback_fn); - if (!callback_fn) - return; + if (!callback_fn || !map) + 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(); } @@ -1691,6 +1695,8 @@ static void bpf_async_cancel_and_free(struct bpf_async_kern *async) if (!cb) return; + /* Callbacks that run after this see NULL and return. */ + WRITE_ONCE(cb->map, NULL); bpf_async_update_prog_callback(cb, NULL, NULL); /* * No refcount_inc_not_zero(&cb->refcnt) here. Dropping the last @@ -4437,15 +4443,21 @@ static void bpf_task_work_ctx_put(struct bpf_task_work_ctx *ctx) } } -static void bpf_task_work_cancel(struct bpf_task_work_ctx *ctx) +static void bpf_task_work_cancel(struct bpf_task_work_ctx *ctx, + struct task_struct *task) { /* * Scheduled task_work callback holds ctx ref, so if we successfully * cancelled, we put that ref on callback's behalf. If we couldn't * cancel, callback will inevitably run or has already completed * running, and it would have taken care of its ctx ref itself. + * + * The caller passes the task explicitly: the scheduling handler must + * not read ctx->task after the work is published (the callback may + * have reset it), while in the asynchronous cancellation path + * ctx->task is stable, see bpf_task_work_cancel_scheduled(). */ - if (task_work_cancel(ctx->task, &ctx->work)) + if (task_work_cancel(task, &ctx->work)) bpf_task_work_ctx_put(ctx); } @@ -4486,6 +4498,7 @@ static void bpf_task_work_callback(struct callback_head *cb) static void bpf_task_work_irq(struct irq_work *irq_work) { struct bpf_task_work_ctx *ctx = container_of(irq_work, struct bpf_task_work_ctx, irq_work); + struct task_struct *task; enum bpf_task_work_state state; int err; @@ -4496,7 +4509,16 @@ static void bpf_task_work_irq(struct irq_work *irq_work) return; } - err = task_work_add(ctx->task, &ctx->work, ctx->mode); + /* + * Capture the task pointer before the work is published: once the + * callback runs, it may reset ctx->task. The capture happens while + * this round's task reference is held, and every path that can + * release it runs after this handler entered its rcu read-side + * section. bpf_task_release() is put_task_struct_rcu_user(), so the + * task_struct itself cannot be freed before this section ends. + */ + task = ctx->task; + err = task_work_add(task, &ctx->work, ctx->mode); if (err) { bpf_task_work_ctx_reset(ctx); /* @@ -4510,14 +4532,14 @@ static void bpf_task_work_irq(struct irq_work *irq_work) /* * It's technically possible for just scheduled task_work callback to - * complete running by now, going SCHEDULING -> RUNNING and then - * dropping its ctx refcount. Instead of capturing an extra ref just - * to protect below ctx->state access, we rely on rcu_read_lock - * above to prevent kfree_rcu from freeing ctx before we return. + * complete running by now, going SCHEDULING -> RUNNING, resetting + * ctx->task and dropping its ctx refcount. The rcu read-side section + * above keeps both the ctx memory and the captured task pointer + * valid until this handler returns. */ state = cmpxchg(&ctx->state, BPF_TW_SCHEDULING, BPF_TW_SCHEDULED); if (state == BPF_TW_FREED) - bpf_task_work_cancel(ctx); /* clean up if we switched into FREED state */ + bpf_task_work_cancel(ctx, task); /* clean up if we switched into FREED state */ } static struct bpf_task_work_ctx *bpf_task_work_fetch_ctx(struct bpf_task_work *tw, @@ -4537,6 +4559,7 @@ static struct bpf_task_work_ctx *bpf_task_work_fetch_ctx(struct bpf_task_work *t memset(ctx, 0, sizeof(*ctx)); refcount_set(&ctx->refcnt, 1); /* map's own ref */ ctx->state = BPF_TW_STANDBY; + init_irq_work(&ctx->irq_work, bpf_task_work_irq); old_ctx = cmpxchg(&twk->ctx, NULL, ctx); if (old_ctx) { @@ -4579,6 +4602,18 @@ static struct bpf_task_work_ctx *bpf_task_work_acquire_ctx(struct bpf_task_work bpf_task_work_ctx_put(ctx); return ERR_PTR(-EBUSY); } + /* + * STANDBY can be published before the previous scheduling irq_work + * returns. Claim PENDING before checking BUSY to order the check after + * that publication. No irq_work has been queued for this attempt yet, + * so reject reuse and roll back to STANDBY while BUSY is set. Preserve + * FREED if deletion wins the rollback race. + */ + if (unlikely(irq_work_is_busy(&ctx->irq_work))) { + (void)cmpxchg(&ctx->state, BPF_TW_PENDING, BPF_TW_STANDBY); + bpf_task_work_ctx_put(ctx); + return ERR_PTR(-EBUSY); + } /* * If no process or bpffs is holding a reference to the map, no new callbacks should be @@ -4628,7 +4663,6 @@ static int bpf_task_work_schedule(struct task_struct *task, struct bpf_task_work ctx->map = map; ctx->map_val = (void *)tw - map->record->task_work_off; init_task_work(&ctx->work, bpf_task_work_callback); - init_irq_work(&ctx->irq_work, bpf_task_work_irq); irq_work_queue(&ctx->irq_work); return 0; @@ -4777,7 +4811,13 @@ static void bpf_task_work_cancel_scheduled(struct irq_work *irq_work) { struct bpf_task_work_ctx *ctx = container_of(irq_work, struct bpf_task_work_ctx, irq_work); - bpf_task_work_cancel(ctx); /* this might put task_work callback's ref */ + /* + * Deletion observed SCHEDULED and won against the callback's + * transition to RUNNING. The callback takes its FREED exit without + * resetting ctx->task, and the transferred map reference prevents + * destruction until cancellation completes. + */ + bpf_task_work_cancel(ctx, ctx->task); /* this might put task_work callback's ref */ bpf_task_work_ctx_put(ctx); /* and here we put map's own ref that was transferred to us */ } diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c index 301fc60bddc4..acee6f86f847 100644 --- a/kernel/bpf/liveness.c +++ b/kernel/bpf/liveness.c @@ -10,10 +10,39 @@ #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args) -struct per_frame_masks { - spis_t may_read; /* stack slots that may be read by this instruction */ - spis_t must_write; /* stack slots written by this instruction */ - spis_t live_before; /* stack slots that may be read by this insn and its successors */ +/* + * Stack liveness is tracked with a 4-byte (half register) granularity. + * Half-slot 0 covers [fp-4, fp), half-slot 1 covers [fp-8, fp-4), and so on, + * hence FRAME_HALF_SPIS - 1 is the deepest half-slot a frame can have. + */ +#define FRAME_HALF_SPIS (MAX_BPF_STACK / BPF_HALF_REG_SIZE) +#define FRAME_MAX_WORDS BITS_TO_LONGS(FRAME_HALF_SPIS) + +/* Masks tracked for each instruction of a frame */ +enum { + FM_MAY_READ, /* stack slots that may be read by this instruction */ + FM_MUST_WRITE, /* stack slots written by this instruction */ + FM_LIVE_BEFORE, /* stack slots that may be read by this insn and its successors */ + FM_MASK_CNT, +}; + +/* + * Per instruction stack masks for one frame of a function instance. + * + * Most frames use only a fraction of the stack budget, so instead of masks + * wide enough for every half-slot of the largest possible frame, all masks + * of one array share the width @words, and the marking functions widen the + * array as deeper half-slots are recorded. Mask @kind of the instruction at + * relative index @i is at &bits[(i * FM_MASK_CNT + kind) * words]. A + * half-slot at or past @words * BITS_PER_LONG is never read by this frame, + * hence never live. An instruction that may read the whole frame, such as a + * call passing a frame pointer to another subprog, widens the array to + * FRAME_MAX_WORDS, so that the read cannot lose half-slots to a later + * widening. + */ +struct frame_masks { + u32 words; + unsigned long bits[]; }; /* @@ -29,7 +58,7 @@ struct func_instance { u32 subprog_start; /* cached env->subprog_info[subprog].start */ u32 insn_cnt; /* cached number of insns in the function */ /* Per frame, per instruction masks, frames allocated lazily. */ - struct per_frame_masks *frames[MAX_CALL_FRAMES]; + struct frame_masks *frames[MAX_CALL_FRAMES]; bool must_write_initialized; }; @@ -151,50 +180,118 @@ static int relative_idx(struct func_instance *instance, u32 insn_idx) return insn_idx - instance->subprog_start; } -static struct per_frame_masks *get_frame_masks(struct func_instance *instance, - u32 frame, u32 insn_idx) +static u32 frame_mask_bits(struct frame_masks *fm) { - if (!instance->frames[frame]) - return NULL; + return fm->words * BITS_PER_LONG; +} - return &instance->frames[frame][relative_idx(instance, insn_idx)]; +static size_t frame_mask_words(struct func_instance *instance, u32 words) +{ + return (size_t)instance->insn_cnt * FM_MASK_CNT * words; } -static struct per_frame_masks *alloc_frame_masks(struct func_instance *instance, - u32 frame, u32 insn_idx) +/* Mask @kind of the instruction at relative index @rel */ +static unsigned long *rel_mask(struct frame_masks *fm, u32 rel, u32 kind) { - struct per_frame_masks *arr; + return fm->bits + ((size_t)rel * FM_MASK_CNT + kind) * fm->words; +} - if (!instance->frames[frame]) { - arr = kvzalloc_objs(*arr, instance->insn_cnt, - GFP_KERNEL_ACCOUNT); - instance->frames[frame] = arr; - if (!arr) - return ERR_PTR(-ENOMEM); +/* + * Make sure @frame has a mask array at least @words wide, allocating it or + * copying the existing masks into the wider stride as needed. + * @words must be in range [1, FRAME_MAX_WORDS]. + */ +static struct frame_masks *widen_frame_masks(struct func_instance *instance, + u32 frame, u32 words) +{ + struct frame_masks *old = instance->frames[frame], *new; + u32 i, kind; + + if (old && old->words >= words) + return old; + new = kvzalloc_flex(*new, bits, frame_mask_words(instance, words), GFP_KERNEL_ACCOUNT); + if (!new) + return NULL; + new->words = words; + if (old) { + for (i = 0; i < instance->insn_cnt; i++) + for (kind = 0; kind < FM_MASK_CNT; kind++) + memcpy(rel_mask(new, i, kind), rel_mask(old, i, kind), + old->words * sizeof(*old->bits)); + kvfree(old); } - return get_frame_masks(instance, frame, insn_idx); + instance->frames[frame] = new; + return new; } -/* Accumulate may_read masks for @frame at @insn_idx */ -static int mark_stack_read(struct func_instance *instance, u32 frame, u32 insn_idx, spis_t mask) +/* + * Set the inclusive half-slot range [lo, hi] in mask @kind of @frame at @insn_idx. + * An empty range, including one with a negative @hi as computed for a write + * that does not fully cover any half-slot, marks nothing. + */ +static int mark_stack_range(struct func_instance *instance, u32 frame, u32 insn_idx, + u32 kind, s32 lo, s32 hi) { - struct per_frame_masks *masks; + struct frame_masks *fm; - masks = alloc_frame_masks(instance, frame, insn_idx); - if (IS_ERR(masks)) - return PTR_ERR(masks); - masks->may_read = spis_or(masks->may_read, mask); + /* + * An access past the frame bottom is rejected by the main verifier + * pass later, liveness only has to avoid running off the masks. + */ + hi = min_t(s32, hi, FRAME_HALF_SPIS - 1); + if (lo > hi) + return 0; + fm = widen_frame_masks(instance, frame, BITS_TO_LONGS(hi + 1)); + if (!fm) + return -ENOMEM; + bitmap_set(rel_mask(fm, relative_idx(instance, insn_idx), kind), lo, hi - lo + 1); return 0; } -static int mark_stack_write(struct func_instance *instance, u32 frame, u32 insn_idx, spis_t mask) +/* Accumulate may_read for half-slots [lo, hi] of @frame at @insn_idx */ +static int mark_stack_read(struct func_instance *instance, u32 frame, u32 insn_idx, + s32 lo, s32 hi) +{ + return mark_stack_range(instance, frame, insn_idx, FM_MAY_READ, lo, hi); +} + +/* Accumulate must_write for half-slots [lo, hi] of @frame at @insn_idx */ +static int mark_stack_write(struct func_instance *instance, u32 frame, u32 insn_idx, + s32 lo, s32 hi) +{ + return mark_stack_range(instance, frame, insn_idx, FM_MUST_WRITE, lo, hi); +} + +/* + * Mark every half-slot of @frame as possibly read by @insn_idx. This widens + * the masks to the maximum width: a full read recorded at a narrower width + * would leave the bits added by a later widening clear and lose part of it. + */ +static int mark_stack_read_all(struct func_instance *instance, u32 frame, u32 insn_idx) +{ + return mark_stack_read(instance, frame, insn_idx, 0, FRAME_HALF_SPIS - 1); +} + +/* Accumulate @src, a mask @src_words wide, into may_read of @frame at @insn_idx */ +static int mark_stack_read_mask(struct func_instance *instance, u32 frame, u32 insn_idx, + const unsigned long *src, u32 src_words) { - struct per_frame_masks *masks; + u32 nbits = src_words * BITS_PER_LONG; + struct frame_masks *fm; + unsigned long *dst; + u32 last, w; - masks = alloc_frame_masks(instance, frame, insn_idx); - if (IS_ERR(masks)) - return PTR_ERR(masks); - masks->must_write = spis_or(masks->must_write, mask); + last = find_last_bit(src, nbits); + if (last == nbits) + return 0; + fm = widen_frame_masks(instance, frame, BITS_TO_LONGS(last + 1)); + if (!fm) + return -ENOMEM; + dst = rel_mask(fm, relative_idx(instance, insn_idx), FM_MAY_READ); + /* @src has no bits set past @last, hence none past @fm->words either */ + src_words = min(src_words, fm->words); + for (w = 0; w < src_words; w++) + dst[w] |= src[w]; return 0; } @@ -272,33 +369,42 @@ __diag_pop(); static inline bool update_insn(struct bpf_verifier_env *env, struct func_instance *instance, u32 frame, u32 insn_idx) { - spis_t new_before, new_after; - struct per_frame_masks *insn, *succ_insn; + unsigned long new_after[FRAME_MAX_WORDS] = {}; + unsigned long *may_read, *must_write, *live_before; + struct frame_masks *fm = instance->frames[frame]; + u32 rel = relative_idx(instance, insn_idx); struct bpf_iarray *succ; - u32 s; - bool changed; + bool changed = false; + u32 s, w; succ = bpf_insn_successors(env, insn_idx); if (succ->cnt == 0) return false; - changed = false; - insn = get_frame_masks(instance, frame, insn_idx); - new_before = SPIS_ZERO; - new_after = SPIS_ZERO; + /* All instructions of one frame array share the same mask width */ for (s = 0; s < succ->cnt; ++s) { - succ_insn = get_frame_masks(instance, frame, succ->items[s]); - new_after = spis_or(new_after, succ_insn->live_before); + unsigned long *succ_live; + + succ_live = rel_mask(fm, relative_idx(instance, succ->items[s]), FM_LIVE_BEFORE); + for (w = 0; w < fm->words; w++) + new_after[w] |= succ_live[w]; } + may_read = rel_mask(fm, rel, FM_MAY_READ); + must_write = rel_mask(fm, rel, FM_MUST_WRITE); + live_before = rel_mask(fm, rel, FM_LIVE_BEFORE); /* * New "live_before" is a union of all "live_before" of successors * minus slots written by instruction plus slots read by instruction. * new_before = (new_after & ~insn->must_write) | insn->may_read */ - new_before = spis_or(spis_and(new_after, spis_not(insn->must_write)), - insn->may_read); - changed |= !spis_equal(new_before, insn->live_before); - insn->live_before = new_before; + for (w = 0; w < fm->words; w++) { + unsigned long new_before = (new_after[w] & ~must_write[w]) | may_read[w]; + + if (new_before != live_before[w]) { + live_before[w] = new_before; + changed = true; + } + } return changed; } @@ -329,10 +435,12 @@ static void update_instance(struct bpf_verifier_env *env, struct func_instance * static bool is_live_before(struct func_instance *instance, u32 insn_idx, u32 frameno, u32 half_spi) { - struct per_frame_masks *masks; + struct frame_masks *fm = instance->frames[frameno]; - masks = get_frame_masks(instance, frameno, insn_idx); - return masks && spis_test_bit(masks->live_before, half_spi); + /* No recorded access reaches past the masks, so nothing there is live */ + if (!fm || half_spi >= frame_mask_bits(fm)) + return false; + return test_bit(half_spi, rel_mask(fm, relative_idx(instance, insn_idx), FM_LIVE_BEFORE)); } int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_state *st) @@ -430,17 +538,19 @@ static int spi_off(int spi) * When only one half is set, print as "-4h","-8h",... * Runs of 3+ consecutive fully-set SPIs are collapsed: "fp0-8..-24" */ -static char *fmt_spis_mask(struct bpf_verifier_env *env, int frame, bool first, spis_t spis) +static char *fmt_spis_mask(struct bpf_verifier_env *env, int frame, bool first, + const unsigned long *spis, u32 words) { int buf_sz = sizeof(env->tmp_str_buf); + int spi_cnt = words * BITS_PER_LONG / 2; char *buf = env->tmp_str_buf; int spi, n, run_start; buf[0] = '\0'; - for (spi = 0; spi < STACK_SLOTS / 2 && buf_sz > 0; spi++) { - bool lo = spis_test_bit(spis, spi * 2); - bool hi = spis_test_bit(spis, spi * 2 + 1); + for (spi = 0; spi < spi_cnt && buf_sz > 0; spi++) { + bool lo = test_bit(spi * 2, spis); + bool hi = test_bit(spi * 2 + 1, spis); const char *space = first ? "" : " "; if (!lo && !hi) @@ -450,16 +560,16 @@ static char *fmt_spis_mask(struct bpf_verifier_env *env, int frame, bool first, /* half-spi */ n = scnprintf(buf, buf_sz, "%sfp%d%d%s", space, frame, spi_off(spi) + (lo ? STACK_SLOT_SZ : 0), "h"); - } else if (spi + 2 < STACK_SLOTS / 2 && - spis_test_bit(spis, spi * 2 + 2) && - spis_test_bit(spis, spi * 2 + 3) && - spis_test_bit(spis, spi * 2 + 4) && - spis_test_bit(spis, spi * 2 + 5)) { + } else if (spi + 2 < spi_cnt && + test_bit(spi * 2 + 2, spis) && + test_bit(spi * 2 + 3, spis) && + test_bit(spi * 2 + 4, spis) && + test_bit(spi * 2 + 5, spis)) { /* 3+ consecutive full spis */ run_start = spi; - while (spi + 1 < STACK_SLOTS / 2 && - spis_test_bit(spis, (spi + 1) * 2) && - spis_test_bit(spis, (spi + 1) * 2 + 1)) + while (spi + 1 < spi_cnt && + test_bit((spi + 1) * 2, spis) && + test_bit((spi + 1) * 2 + 1, spis)) spi++; n = scnprintf(buf, buf_sz, "%sfp%d%d..%d", space, frame, spi_off(run_start), spi_off(spi)); @@ -478,7 +588,8 @@ static void print_instance(struct bpf_verifier_env *env, struct func_instance *i { int start = env->subprog_info[instance->subprog].start; struct bpf_insn *insns = env->prog->insnsi; - struct per_frame_masks *masks; + struct frame_masks *fm; + unsigned long *mask; int len = instance->insn_cnt; int insn_idx, frame, i; bool has_use, has_def; @@ -501,10 +612,13 @@ static void print_instance(struct bpf_verifier_env *env, struct func_instance *i pos = env->log.end_pos; verbose(env, " use: "); for (frame = instance->depth; frame >= 0; --frame) { - masks = get_frame_masks(instance, frame, insn_idx); - if (!masks || spis_is_zero(masks->may_read)) + fm = instance->frames[frame]; + if (!fm) + continue; + mask = rel_mask(fm, i, FM_MAY_READ); + if (bitmap_empty(mask, frame_mask_bits(fm))) continue; - verbose(env, "%s", fmt_spis_mask(env, frame, !has_use, masks->may_read)); + verbose(env, "%s", fmt_spis_mask(env, frame, !has_use, mask, fm->words)); has_use = true; } if (!has_use) @@ -512,10 +626,13 @@ static void print_instance(struct bpf_verifier_env *env, struct func_instance *i pos = env->log.end_pos; verbose(env, " def: "); for (frame = instance->depth; frame >= 0; --frame) { - masks = get_frame_masks(instance, frame, insn_idx); - if (!masks || spis_is_zero(masks->must_write)) + fm = instance->frames[frame]; + if (!fm) + continue; + mask = rel_mask(fm, i, FM_MUST_WRITE); + if (bitmap_empty(mask, frame_mask_bits(fm))) continue; - verbose(env, "%s", fmt_spis_mask(env, frame, !has_def, masks->must_write)); + verbose(env, "%s", fmt_spis_mask(env, frame, !has_def, mask, fm->words)); has_def = true; } if (!has_def) @@ -584,9 +701,9 @@ static int print_instances(struct bpf_verifier_env *env) * - same frame + different offset -> offset-imprecise * - different frames -> fully-imprecise (bitmask OR) * - * At memory access sites (LDX/STX/ST), offset-imprecise marks only - * the known frame's access mask as SPIS_ALL, while fully-imprecise - * iterates bits in the bitmask and routes each frame to its target. + * At memory access sites (LDX/STX/ST), offset-imprecise marks the known + * frame as fully read, while fully-imprecise iterates bits in the bitmask + * and routes each frame to its target. */ #define MAX_ARG_OFFSETS 4 @@ -605,8 +722,15 @@ enum arg_track_state { ARG_IMPRECISE = -3, /* lost identity; .mask is arg bitmask */ }; -/* Track callee stack slots fp-8 through fp-512 (64 slots of 8 bytes each) */ -#define MAX_ARG_SPILL_SLOTS 64 +/* + * The tracker follows as many spill slots as a subprog addresses directly + * through R10, see subprog_spill_slots(). A frame's slots at a call site are + * kept in a snapshot for the callees that receive pointers into that frame. + */ +struct spill_snapshot { + u32 slots; + struct arg_track at[]; +}; /* * Combined register + stack arg tracking: R0-R10 at indices 0-10, @@ -881,13 +1005,46 @@ static void arg_padd(struct arg_track *at, s64 delta) } /* - * Convert a byte offset from FP to a callee stack slot index. + * Number of 8-byte spill slots to track for the instructions in [@start, @end): + * the 64 slots of a MAX_BPF_STACK frame, which the tracker has always + * followed, or the deepest 8-byte stack access made directly through R10 when + * that reaches further. Spills and fills are compiled as direct R10 accesses, + * so the count covers them whatever the frame size; a fill through a derived + * pointer that reaches past it is treated as imprecise, as one past the frame + * always was. + */ +static u32 subprog_spill_slots(struct bpf_verifier_env *env, int start, int end) +{ + struct bpf_insn *insns = env->prog->insnsi; + int deepest = 0; + + for (int i = start; i < end; i++) { + struct bpf_insn *insn = &insns[i]; + u8 class = BPF_CLASS(insn->code); + u8 base; + + if (BPF_SIZE(insn->code) != BPF_DW) + continue; + if (class == BPF_LDX) + base = insn->src_reg; + else if (class == BPF_STX || class == BPF_ST) + base = insn->dst_reg; + else + continue; + if (base == BPF_REG_FP && insn->off < 0) + deepest = max(deepest, -insn->off); + } + return clamp_t(u32, DIV_ROUND_UP(deepest, 8), MAX_BPF_STACK / BPF_REG_SIZE, MAX_BPF_STACK_SLOTS); +} + +/* + * Convert a byte offset from FP to one of the @nslots tracked stack slots. * Returns -1 if out of range or not 8-byte aligned. * Slot 0 = fp-8, slot 1 = fp-16, ..., slot 7 = fp-64, .... */ -static int fp_off_to_slot(s16 off) +static int fp_off_to_slot(s16 off, u32 nslots) { - if (off >= 0 || off < -(int)(MAX_ARG_SPILL_SLOTS * 8)) + if (off >= 0 || off < -(int)(nslots * 8)) return -1; if (off % 8) return -1; @@ -896,7 +1053,7 @@ static int fp_off_to_slot(s16 off) static struct arg_track fill_from_stack(struct bpf_insn *insn, struct arg_track *at_out, int reg, - struct arg_track *at_stack_out, + struct arg_track *at_stack_out, u32 nslots, int depth) { struct arg_track imp = { @@ -907,7 +1064,7 @@ static struct arg_track fill_from_stack(struct bpf_insn *insn, int cnt, i; if (reg == BPF_REG_FP) { - int slot = fp_off_to_slot(insn->off); + int slot = fp_off_to_slot(insn->off, nslots); return slot >= 0 ? at_stack_out[slot] : imp; } @@ -920,7 +1077,7 @@ static struct arg_track fill_from_stack(struct bpf_insn *insn, if (arg_add(at_out[reg].off[i], insn->off, &fp_off)) return imp; - slot = fp_off_to_slot(fp_off); + slot = fp_off_to_slot(fp_off, nslots); if (slot < 0) return imp; result = __arg_track_join(result, at_stack_out[slot]); @@ -935,7 +1092,7 @@ static struct arg_track fill_from_stack(struct bpf_insn *insn, * When exact offset is unknown conservatively add reg values to all slots in at_stack_out. */ static void spill_to_stack(struct bpf_insn *insn, struct arg_track *at_out, - int reg, struct arg_track *at_stack_out, + int reg, struct arg_track *at_stack_out, u32 nslots, struct arg_track *val, u32 sz) { struct arg_track none = { .frame = ARG_NONE }; @@ -943,7 +1100,7 @@ static void spill_to_stack(struct bpf_insn *insn, struct arg_track *at_out, int cnt, i; if (reg == BPF_REG_FP) { - int slot = fp_off_to_slot(insn->off); + int slot = fp_off_to_slot(insn->off, nslots); if (slot >= 0) at_stack_out[slot] = new_val; @@ -951,7 +1108,7 @@ static void spill_to_stack(struct bpf_insn *insn, struct arg_track *at_out, } cnt = at_out[reg].off_cnt; if (cnt == 0) { - for (int slot = 0; slot < MAX_ARG_SPILL_SLOTS; slot++) + for (int slot = 0; slot < nslots; slot++) at_stack_out[slot] = __arg_track_join(at_stack_out[slot], new_val); return; } @@ -961,7 +1118,7 @@ static void spill_to_stack(struct bpf_insn *insn, struct arg_track *at_out, if (arg_add(at_out[reg].off[i], insn->off, &fp_off)) continue; - slot = fp_off_to_slot(fp_off); + slot = fp_off_to_slot(fp_off, nslots); if (slot < 0) continue; if (cnt == 1) @@ -975,16 +1132,17 @@ static void spill_to_stack(struct bpf_insn *insn, struct arg_track *at_out, * Clear all tracked callee stack slots overlapping the byte range * [off, off+sz-1] where off is a negative FP-relative offset. */ -static void clear_overlapping_stack_slots(struct arg_track *at_stack, s16 off, u32 sz, int cnt) +static void clear_overlapping_stack_slots(struct arg_track *at_stack, u32 nslots, s16 off, + u32 sz, int cnt) { struct arg_track none = { .frame = ARG_NONE }; if (cnt == 0) { - for (int i = 0; i < MAX_ARG_SPILL_SLOTS; i++) + for (int i = 0; i < nslots; i++) at_stack[i] = __arg_track_join(at_stack[i], none); return; } - for (int i = 0; i < MAX_ARG_SPILL_SLOTS; i++) { + for (int i = 0; i < nslots; i++) { int slot_start = -((i + 1) * 8); int slot_end = slot_start + 8; @@ -1002,33 +1160,33 @@ static void clear_overlapping_stack_slots(struct arg_track *at_stack, s16 off, u */ static void clear_stack_for_all_offs(struct bpf_insn *insn, struct arg_track *at_out, int reg, - struct arg_track *at_stack_out, u32 sz) + struct arg_track *at_stack_out, u32 nslots, u32 sz) { int cnt, i; if (reg == BPF_REG_FP) { - clear_overlapping_stack_slots(at_stack_out, insn->off, sz, 1); + clear_overlapping_stack_slots(at_stack_out, nslots, insn->off, sz, 1); return; } cnt = at_out[reg].off_cnt; if (cnt == 0) { - clear_overlapping_stack_slots(at_stack_out, 0, sz, cnt); + clear_overlapping_stack_slots(at_stack_out, nslots, 0, sz, cnt); return; } for (i = 0; i < cnt; i++) { s16 fp_off; if (arg_add(at_out[reg].off[i], insn->off, &fp_off)) { - clear_overlapping_stack_slots(at_stack_out, 0, sz, 0); + clear_overlapping_stack_slots(at_stack_out, nslots, 0, sz, 0); break; } - clear_overlapping_stack_slots(at_stack_out, fp_off, sz, cnt); + clear_overlapping_stack_slots(at_stack_out, nslots, fp_off, sz, cnt); } } static void arg_track_log(struct bpf_verifier_env *env, struct bpf_insn *insn, int idx, struct arg_track *at_in, struct arg_track *at_stack_in, - struct arg_track *at_out, struct arg_track *at_stack_out) + struct arg_track *at_out, struct arg_track *at_stack_out, u32 nslots) { bool printed = false; int i; @@ -1060,7 +1218,7 @@ static void arg_track_log(struct bpf_verifier_env *env, struct bpf_insn *insn, i verbose(env, "\tsa%d: ", i); verbose_arg_track(env, &at_in[ai]); verbose(env, " -> "); verbose_arg_track(env, &at_out[ai]); } - for (i = 0; i < MAX_ARG_SPILL_SLOTS; i++) { + for (i = 0; i < nslots; i++) { if (arg_track_eq(&at_stack_out[i], &at_stack_in[i])) continue; if (!printed) { @@ -1081,6 +1239,29 @@ static bool can_be_local_fp(int depth, int regno, struct arg_track *at) (at->frame == ARG_IMPRECISE && (at->mask & BIT(depth))); } +/* + * Model 8-byte reads through @reg, including load-acquire + * and the old value fetched by atomic operations. + */ +static struct arg_track arg_track_deref(struct bpf_verifier_env *env, struct bpf_insn *insn, + struct arg_track *at_out, int reg, + struct arg_track *at_stack_out, u32 nslots, + int depth, u32 *callsites) +{ + struct arg_track *ptr = &at_out[reg]; + + if (can_be_local_fp(depth, reg, ptr)) + return fill_from_stack(insn, at_out, reg, at_stack_out, nslots, depth); + if (ptr->frame >= 0 && ptr->frame < depth) { + struct spill_snapshot *parent = env->callsite_at_stack[callsites[ptr->frame]]; + + return fill_from_stack(insn, at_out, reg, parent->at, parent->slots, ptr->frame); + } + if (ptr->frame == ARG_IMPRECISE && !(ptr->mask & BIT(depth)) && ptr->mask) + return *ptr; + return (struct arg_track){ .frame = ARG_NONE }; +} + /* * Pure dataflow transfer function for arg_track state. * Updates at_out[] based on how the instruction modifies registers. @@ -1088,7 +1269,7 @@ static bool can_be_local_fp(int depth, int regno, struct arg_track *at) */ static void arg_track_xfer(struct bpf_verifier_env *env, struct bpf_insn *insn, int insn_idx, - struct arg_track *at_out, struct arg_track *at_stack_out, + struct arg_track *at_out, struct arg_track *at_stack_out, u32 nslots, const struct arg_track *at_stack_arg_entry, struct func_instance *instance, u32 *callsites) @@ -1162,55 +1343,42 @@ static void arg_track_xfer(struct bpf_verifier_env *env, struct bpf_insn *insn, for (r = BPF_REG_0; r <= BPF_REG_5; r++) at_out[r] = none; } else if (class == BPF_LDX) { - u32 sz = bpf_size_to_bytes(BPF_SIZE(insn->code)); - bool src_is_local_fp = can_be_local_fp(depth, insn->src_reg, src); - - /* - * Reload from callee stack: if src is current-frame FP-derived - * and the load is an 8-byte BPF_MEM, try to restore the spill - * identity. For imprecise sources fill_from_stack() returns - * ARG_IMPRECISE (off_cnt == 0). - */ - if (src_is_local_fp && BPF_MODE(insn->code) == BPF_MEM && sz == 8) { - *dst = fill_from_stack(insn, at_out, insn->src_reg, at_stack_out, depth); - } else if (src->frame >= 0 && src->frame < depth && - BPF_MODE(insn->code) == BPF_MEM && sz == 8) { - struct arg_track *parent_stack = - env->callsite_at_stack[callsites[src->frame]]; - - *dst = fill_from_stack(insn, at_out, insn->src_reg, - parent_stack, src->frame); - } else if (src->frame == ARG_IMPRECISE && - !(src->mask & BIT(depth)) && src->mask && - BPF_MODE(insn->code) == BPF_MEM && sz == 8) { - /* - * Imprecise src with only parent-frame bits: - * conservative fallback. - */ - *dst = *src; - } else { + /* Only an 8-byte BPF_MEM load can be a fill, see arg_track_deref(). */ + if (BPF_MODE(insn->code) == BPF_MEM && BPF_SIZE(insn->code) == BPF_DW) + *dst = arg_track_deref(env, insn, at_out, insn->src_reg, + at_stack_out, nslots, depth, callsites); + else *dst = none; - } } else if (class == BPF_LD && BPF_MODE(insn->code) == BPF_IMM) { *dst = none; } else if (class == BPF_STX) { u32 sz = bpf_size_to_bytes(BPF_SIZE(insn->code)); - bool dst_is_local_fp; - - /* Track spills to current-frame FP-derived callee stack */ - dst_is_local_fp = can_be_local_fp(depth, insn->dst_reg, dst); - if (dst_is_local_fp && BPF_MODE(insn->code) == BPF_MEM) - spill_to_stack(insn, at_out, insn->dst_reg, - at_stack_out, src, sz); - - if (BPF_MODE(insn->code) == BPF_ATOMIC) { - if (dst_is_local_fp && insn->imm != BPF_LOAD_ACQ) - clear_stack_for_all_offs(insn, at_out, insn->dst_reg, - at_stack_out, sz); + bool dst_is_local_fp = can_be_local_fp(depth, insn->dst_reg, dst); + u8 mode = BPF_MODE(insn->code); + + if (mode == BPF_MEM || (mode == BPF_ATOMIC && insn->imm == BPF_STORE_REL)) { + if (dst_is_local_fp) + spill_to_stack(insn, at_out, insn->dst_reg, + at_stack_out, nslots, src, sz); + } else if (mode == BPF_ATOMIC && insn->imm == BPF_LOAD_ACQ) { + if (sz == 8) + *dst = arg_track_deref(env, insn, at_out, insn->src_reg, + at_stack_out, nslots, depth, callsites); + else + *dst = none; + } else if (mode == BPF_ATOMIC) { + /* BPF_XCHG, BPF_CMPXCHG or BPF_{ADD,AND,OR,XOR} | [BPF_FETCH] */ + struct arg_track old = none; r = bpf_atomic_load_reg(insn); + if (r >= 0 && sz == 8) + old = arg_track_deref(env, insn, at_out, insn->dst_reg, + at_stack_out, nslots, depth, callsites); + if (dst_is_local_fp) + clear_stack_for_all_offs(insn, at_out, insn->dst_reg, + at_stack_out, nslots, sz); if (r >= 0) - at_out[r] = none; + at_out[r] = old; } } else if (class == BPF_ST && BPF_MODE(insn->code) == BPF_MEM) { u32 sz = bpf_size_to_bytes(BPF_SIZE(insn->code)); @@ -1219,7 +1387,7 @@ static void arg_track_xfer(struct bpf_verifier_env *env, struct bpf_insn *insn, /* BPF_ST to FP-derived dst: clear overlapping stack slots */ if (dst_is_local_fp) clear_stack_for_all_offs(insn, at_out, insn->dst_reg, - at_stack_out, sz); + at_stack_out, nslots, sz); } } @@ -1235,7 +1403,6 @@ static int record_stack_access_off(struct func_instance *instance, s64 fp_off, s64 access_bytes, u32 frame, u32 insn_idx) { s32 slot_hi, slot_lo; - spis_t mask; if (fp_off >= 0) /* @@ -1247,27 +1414,19 @@ static int record_stack_access_off(struct func_instance *instance, s64 fp_off, if (access_bytes == S64_MIN) { /* helper/kfunc read unknown amount of bytes from fp_off until fp+0 */ slot_hi = (-fp_off - 1) / STACK_SLOT_SZ; - mask = SPIS_ZERO; - spis_or_range(&mask, 0, slot_hi); - return mark_stack_read(instance, frame, insn_idx, mask); + return mark_stack_read(instance, frame, insn_idx, 0, slot_hi); } if (access_bytes > 0) { /* Mark any touched slot as use */ slot_hi = (-fp_off - 1) / STACK_SLOT_SZ; slot_lo = max_t(s32, (-fp_off - access_bytes) / STACK_SLOT_SZ, 0); - mask = SPIS_ZERO; - spis_or_range(&mask, slot_lo, slot_hi); - return mark_stack_read(instance, frame, insn_idx, mask); + return mark_stack_read(instance, frame, insn_idx, slot_lo, slot_hi); } else if (access_bytes < 0) { /* Mark only fully covered slots as def */ access_bytes = -access_bytes; slot_hi = (-fp_off) / STACK_SLOT_SZ - 1; slot_lo = max_t(s32, (-fp_off - access_bytes + STACK_SLOT_SZ - 1) / STACK_SLOT_SZ, 0); - if (slot_lo <= slot_hi) { - mask = SPIS_ZERO; - spis_or_range(&mask, slot_lo, slot_hi); - return mark_stack_write(instance, frame, insn_idx, mask); - } + return mark_stack_write(instance, frame, insn_idx, slot_lo, slot_hi); } return 0; } @@ -1286,7 +1445,7 @@ static int record_stack_access(struct func_instance *instance, return 0; if (arg->off_cnt == 0) { if (access_bytes > 0 || access_bytes == S64_MIN) - return mark_stack_read(instance, frame, insn_idx, SPIS_ALL); + return mark_stack_read_all(instance, frame, insn_idx); return 0; } if (access_bytes != S64_MIN && access_bytes < 0 && arg->off_cnt != 1) @@ -1314,7 +1473,7 @@ static int record_imprecise(struct func_instance *instance, u32 mask, u32 insn_i if (!(mask & 1)) continue; if (f <= depth) { - err = mark_stack_read(instance, f, insn_idx, SPIS_ALL); + err = mark_stack_read_all(instance, f, insn_idx); if (err) return err; } @@ -1410,7 +1569,7 @@ static int record_arg_access(struct bpf_verifier_env *env, bytes = bpf_kfunc_stack_access_bytes(env, insn, arg_idx, insn_idx); } else { for (int f = 0; f <= depth; f++) { - err = mark_stack_read(instance, f, insn_idx, SPIS_ALL); + err = mark_stack_read_all(instance, f, insn_idx); if (err) return err; } @@ -1517,7 +1676,7 @@ struct subprog_at_info { static void print_subprog_arg_access(struct bpf_verifier_env *env, int subprog, struct subprog_at_info *info, - struct arg_track (*at_stack_in)[MAX_ARG_SPILL_SLOTS]) + struct arg_track *at_stack_in, u32 nslots) { struct bpf_insn *insns = env->prog->insnsi; int start = env->subprog_info[subprog].start; @@ -1550,8 +1709,8 @@ static void print_subprog_arg_access(struct bpf_verifier_env *env, has_extra = true; } if (is_ldx_stx_call) { - for (r = 0; r < MAX_ARG_SPILL_SLOTS; r++) - if (arg_is_fp(&at_stack_in[i][r])) + for (r = 0; r < nslots; r++) + if (arg_is_fp(&at_stack_in[(size_t)i * nslots + r])) has_extra = true; } @@ -1581,11 +1740,11 @@ static void print_subprog_arg_access(struct bpf_verifier_env *env, } if (is_ldx_stx_call) { - for (r = 0; r < MAX_ARG_SPILL_SLOTS; r++) { - if (!arg_is_fp(&at_stack_in[i][r])) + for (r = 0; r < nslots; r++) { + if (!arg_is_fp(&at_stack_in[(size_t)i * nslots + r])) continue; verbose(env, " fp%+d=", -(r + 1) * 8); - verbose_arg_track(env, &at_stack_in[i][r]); + verbose_arg_track(env, &at_stack_in[(size_t)i * nslots + r]); } } @@ -1618,9 +1777,10 @@ static int compute_subprog_args(struct bpf_verifier_env *env, int end = env->subprog_info[subprog + 1].start; int po_end = env->subprog_info[subprog + 1].postorder_start; int len = end - start; + u32 nslots = subprog_spill_slots(env, start, end); struct arg_track (*at_in)[MAX_AT_TRACK_REGS] = NULL; struct arg_track at_out[MAX_AT_TRACK_REGS]; - struct arg_track (*at_stack_in)[MAX_ARG_SPILL_SLOTS] = NULL; + struct arg_track *at_stack_in = NULL; struct arg_track *at_stack_out = NULL; struct arg_track at_stack_arg_entry[MAX_STACK_ARG_SLOTS]; struct arg_track unvisited = { .frame = ARG_UNVISITED }; @@ -1632,19 +1792,19 @@ static int compute_subprog_args(struct bpf_verifier_env *env, if (!at_in) goto err_free; - at_stack_in = kvmalloc_objs(*at_stack_in, len, GFP_KERNEL_ACCOUNT); + at_stack_in = kvmalloc_objs(*at_stack_in, (size_t)len * nslots, GFP_KERNEL_ACCOUNT); if (!at_stack_in) goto err_free; - at_stack_out = kvmalloc_objs(*at_stack_out, MAX_ARG_SPILL_SLOTS, GFP_KERNEL_ACCOUNT); + at_stack_out = kvmalloc_objs(*at_stack_out, nslots, GFP_KERNEL_ACCOUNT); if (!at_stack_out) goto err_free; for (i = 0; i < len; i++) { for (r = 0; r < MAX_AT_TRACK_REGS; r++) at_in[i][r] = unvisited; - for (r = 0; r < MAX_ARG_SPILL_SLOTS; r++) - at_stack_in[i][r] = unvisited; + for (r = 0; r < nslots; r++) + at_stack_in[(size_t)i * nslots + r] = unvisited; } for (r = 0; r < MAX_AT_TRACK_REGS; r++) @@ -1660,8 +1820,8 @@ static int compute_subprog_args(struct bpf_verifier_env *env, } /* Entry: all stack slots are ARG_NONE */ - for (r = 0; r < MAX_ARG_SPILL_SLOTS; r++) - at_stack_in[0][r] = none; + for (r = 0; r < nslots; r++) + at_stack_in[r] = none; /* Entry: incoming stack args from caller, or ARG_NONE for main */ for (r = 0; r < MAX_STACK_ARG_SLOTS; r++) @@ -1683,11 +1843,12 @@ static int compute_subprog_args(struct bpf_verifier_env *env, continue; memcpy(at_out, at_in[i], sizeof(at_out)); - memcpy(at_stack_out, at_stack_in[i], MAX_ARG_SPILL_SLOTS * sizeof(*at_stack_out)); + memcpy(at_stack_out, &at_stack_in[(size_t)i * nslots], nslots * sizeof(*at_stack_out)); - arg_track_xfer(env, insn, idx, at_out, at_stack_out, + arg_track_xfer(env, insn, idx, at_out, at_stack_out, nslots, at_stack_arg_entry, instance, callsites); - arg_track_log(env, insn, idx, at_in[i], at_stack_in[i], at_out, at_stack_out); + arg_track_log(env, insn, idx, at_in[i], &at_stack_in[(size_t)i * nslots], at_out, + at_stack_out, nslots); /* Propagate to successors within this subprogram */ succ = bpf_insn_successors(env, idx); @@ -1704,9 +1865,10 @@ static int compute_subprog_args(struct bpf_verifier_env *env, changed |= arg_track_join(env, idx, target, r, &at_in[ti][r], at_out[r]); - for (r = 0; r < MAX_ARG_SPILL_SLOTS; r++) + for (r = 0; r < nslots; r++) changed |= arg_track_join(env, idx, target, -r - 1, - &at_stack_in[ti][r], at_stack_out[r]); + &at_stack_in[(size_t)ti * nslots + r], + at_stack_out[r]); } } if (changed) @@ -1729,23 +1891,24 @@ static int compute_subprog_args(struct bpf_verifier_env *env, } if (bpf_pseudo_call(insn) || bpf_calls_callback(env, idx)) { + struct spill_snapshot *snap; + kvfree(env->callsite_at_stack[idx]); - env->callsite_at_stack[idx] = - kvmalloc_objs(*env->callsite_at_stack[idx], - MAX_ARG_SPILL_SLOTS, GFP_KERNEL_ACCOUNT); - if (!env->callsite_at_stack[idx]) { + env->callsite_at_stack[idx] = kvmalloc_flex(*snap, at, nslots, GFP_KERNEL_ACCOUNT); + snap = env->callsite_at_stack[idx]; + if (!snap) { err = -ENOMEM; goto err_free; } - memcpy(env->callsite_at_stack[idx], - at_stack_in[i], sizeof(struct arg_track) * MAX_ARG_SPILL_SLOTS); + snap->slots = nslots; + memcpy(snap->at, &at_stack_in[(size_t)i * nslots], nslots * sizeof(*snap->at)); } } info->at_in = at_in; at_in = NULL; info->len = len; - print_subprog_arg_access(env, subprog, info, at_stack_in); + print_subprog_arg_access(env, subprog, info, at_stack_in, nslots); err = 0; err_free: @@ -1772,36 +1935,52 @@ static bool has_fp_args(struct arg_track *args) * may_read: union (any pass might read the slot). * must_write: intersection (only slots written on ALL passes are guaranteed). * live_before is recomputed by a subsequent update_instance() on @dst. + * + * The two instances may have settled on different mask widths for the same + * frame, so @dst is widened to cover @src first. A word only @dst has counts + * as zero on the @src side: it unions into may_read as a no-op and intersects + * must_write to empty. */ -static void merge_instances(struct func_instance *dst, struct func_instance *src) +static int merge_instances(struct func_instance *dst, struct func_instance *src) { - int f, i; + struct frame_masks *d, *s; + u32 f, i, w; for (f = 0; f <= dst->depth; f++) { - if (!src->frames[f]) { + s = src->frames[f]; + d = dst->frames[f]; + if (!s) { /* This pass didn't touch frame f — must_write intersects with empty. */ - if (dst->frames[f]) + if (d) for (i = 0; i < dst->insn_cnt; i++) - dst->frames[f][i].must_write = SPIS_ZERO; + bitmap_zero(rel_mask(d, i, FM_MUST_WRITE), + frame_mask_bits(d)); continue; } - if (!dst->frames[f]) { + if (!d) { /* Previous pass didn't touch frame f — take src, zero must_write. */ - dst->frames[f] = src->frames[f]; + dst->frames[f] = s; src->frames[f] = NULL; for (i = 0; i < dst->insn_cnt; i++) - dst->frames[f][i].must_write = SPIS_ZERO; + bitmap_zero(rel_mask(s, i, FM_MUST_WRITE), frame_mask_bits(s)); continue; } + d = widen_frame_masks(dst, f, s->words); + if (!d) + return -ENOMEM; for (i = 0; i < dst->insn_cnt; i++) { - dst->frames[f][i].may_read = - spis_or(dst->frames[f][i].may_read, - src->frames[f][i].may_read); - dst->frames[f][i].must_write = - spis_and(dst->frames[f][i].must_write, - src->frames[f][i].must_write); + unsigned long *dst_read = rel_mask(d, i, FM_MAY_READ); + unsigned long *dst_write = rel_mask(d, i, FM_MUST_WRITE); + unsigned long *src_read = rel_mask(s, i, FM_MAY_READ); + unsigned long *src_write = rel_mask(s, i, FM_MUST_WRITE); + + for (w = 0; w < d->words; w++) { + dst_read[w] |= w < s->words ? src_read[w] : 0; + dst_write[w] &= w < s->words ? src_write[w] : 0; + } } } + return 0; } static struct func_instance *fresh_instance(struct func_instance *src) @@ -1916,7 +2095,7 @@ static int analyze_subprog(struct bpf_verifier_env *env, if (info[subprog].at_in[j][caller_reg].frame == ARG_NONE) continue; for (int f = 0; f <= depth; f++) { - err = mark_stack_read(instance, f, idx, SPIS_ALL); + err = mark_stack_read_all(instance, f, idx); if (err) goto out_free; } @@ -1955,13 +2134,18 @@ static int analyze_subprog(struct bpf_verifier_env *env, /* Pull callee's entry liveness back to caller's callsite */ { u32 callee_start = callee_instance->subprog_start; - struct per_frame_masks *entry; + struct frame_masks *callee_fm; for (int f = 0; f < callee_instance->depth; f++) { - entry = get_frame_masks(callee_instance, f, callee_start); - if (!entry) + callee_fm = callee_instance->frames[f]; + if (!callee_fm) continue; - err = mark_stack_read(instance, f, idx, entry->live_before); + err = mark_stack_read_mask(instance, f, idx, + rel_mask(callee_fm, + relative_idx(callee_instance, + callee_start), + FM_LIVE_BEFORE), + callee_fm->words); if (err) goto out_free; } @@ -1969,9 +2153,11 @@ static int analyze_subprog(struct bpf_verifier_env *env, } if (prev_instance) { - merge_instances(prev_instance, instance); + err = merge_instances(prev_instance, instance); free_instance(instance); instance = prev_instance; + if (err) + return err; } update_instance(env, instance); return 0; diff --git a/kernel/bpf/log.c b/kernel/bpf/log.c index fb032dfdc0de..d850a7863d2e 100644 --- a/kernel/bpf/log.c +++ b/kernel/bpf/log.c @@ -716,7 +716,8 @@ void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifie verbose(env, "="); print_reg_state(env, state, reg); } - for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { + for (i = 0; i < bpf_stack_nr_slots(state); i++) { + struct bpf_stack_state *slot = bpf_stack_slot(state, i); char types_buf[BPF_REG_SIZE + 1]; const char *sep = ""; bool valid = false; @@ -727,7 +728,7 @@ void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifie continue; for (j = 0; j < BPF_REG_SIZE; j++) { - slot_type = state->stack[i].slot_type[j]; + slot_type = slot->slot_type[j]; if (slot_type != STACK_INVALID && slot_type != STACK_POISON) valid = true; types_buf[j] = slot_type_char[slot_type]; @@ -736,12 +737,12 @@ void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifie if (!valid) continue; - reg = &state->stack[i].spilled_ptr; - switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) { + reg = &slot->spilled_ptr; + switch (slot->slot_type[BPF_REG_SIZE - 1]) { case STACK_SPILL: /* print MISC/ZERO/INVALID slots above subreg spill */ for (j = 0; j < BPF_REG_SIZE; j++) - if (state->stack[i].slot_type[j] == STACK_SPILL) + if (slot->slot_type[j] == STACK_SPILL) break; types_buf[j] = '\0'; @@ -751,7 +752,7 @@ void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifie case STACK_DYNPTR: /* skip to main dynptr slot */ i += BPF_DYNPTR_NR_SLOTS - 1; - reg = &state->stack[i].spilled_ptr; + reg = &bpf_stack_slot(state, i)->spilled_ptr; verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); verbose(env, "=dynptr_%s(", dynptr_type_str(reg->dynptr.type)); diff --git a/kernel/bpf/map_in_map.c b/kernel/bpf/map_in_map.c index d2cbab4bdf64..edad013d260c 100644 --- a/kernel/bpf/map_in_map.c +++ b/kernel/bpf/map_in_map.c @@ -106,10 +106,13 @@ void *bpf_map_fd_get_ptr(struct bpf_map *map, return ERR_PTR(-ENOTSUPP); inner_map_meta = map->inner_map_meta; - if (inner_map_meta->ops->map_meta_equal(inner_map_meta, inner_map)) + if (inner_map_meta->ops->map_meta_equal(inner_map_meta, inner_map)) { bpf_map_inc(inner_map); - else + /* Its users are those of the outer maps from now on */ + WRITE_ONCE(inner_map->was_inner_map, true); + } else { inner_map = ERR_PTR(-EINVAL); + } return inner_map; } diff --git a/kernel/bpf/offload.c b/kernel/bpf/offload.c index d855399812ee..f7bfff1760cc 100644 --- a/kernel/bpf/offload.c +++ b/kernel/bpf/offload.c @@ -96,6 +96,22 @@ static int __bpf_offload_dev_netdev_register(struct bpf_offload_dev *offdev, return err; } +/* + * @prog takes the place of a copy that the caller is about to free. Nothing + * keeps the netdev while a program is loaded: once the lock is dropped, no + * unregistration is left that has got the old copy from offload->prog. + */ +void bpf_prog_dev_bound_moved(struct bpf_prog *prog) +{ + if (!bpf_prog_is_dev_bound(prog->aux)) + return; + + down_read(&bpf_devs_lock); + if (prog->aux->offload) + prog->aux->offload->prog = prog; + up_read(&bpf_devs_lock); +} + static void __bpf_prog_offload_destroy(struct bpf_prog *prog) { struct bpf_prog_offload *offload = prog->aux->offload; @@ -250,7 +266,14 @@ int bpf_prog_dev_bound_init(struct bpf_prog *prog, union bpf_attr *attr) prog->aux->offload_requested = !(attr->prog_flags & BPF_F_XDP_DEV_BOUND_ONLY); down_write(&bpf_devs_lock); - err = __bpf_prog_dev_bound_init(prog, netdev); + /* + * Behind bpf_dev_bound_netdev_unregister() nobody would take the + * program off the device, which goes once the reference is dropped. + */ + if (READ_ONCE(netdev->reg_state) == NETREG_REGISTERED) + err = __bpf_prog_dev_bound_init(prog, netdev); + else + err = -EINVAL; up_write(&bpf_devs_lock); out: diff --git a/kernel/bpf/states.c b/kernel/bpf/states.c index 012b82513a3b..f28b11c18908 100644 --- a/kernel/bpf/states.c +++ b/kernel/bpf/states.c @@ -415,14 +415,14 @@ static void __clean_func_state(struct bpf_verifier_env *env, * half_spi 2*i → lower half: slot_type[0..3] (closer to FP) * half_spi 2*i+1 → upper half: slot_type[4..7] (farther from FP) */ - for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { + for (i = 0; i < bpf_stack_nr_slots(st); i++) { bool lo_live = bpf_stack_slot_alive(env, frame, i * 2); bool hi_live = bpf_stack_slot_alive(env, frame, i * 2 + 1); if (!hi_live || !lo_live) { int start = !lo_live ? 0 : BPF_REG_SIZE / 2; int end = !hi_live ? BPF_REG_SIZE : BPF_REG_SIZE / 2; - u8 stype = st->stack[i].slot_type[7]; + u8 stype = bpf_stack_slot(st, i)->slot_type[7]; /* * Don't clear special slots. @@ -442,7 +442,7 @@ static void __clean_func_state(struct bpf_verifier_env *env, * rejecting as non-scalar register fills. */ if (!hi_live) { - struct bpf_reg_state *spill = &st->stack[i].spilled_ptr; + struct bpf_reg_state *spill = &bpf_stack_slot(st, i)->spilled_ptr; if (lo_live && stype == STACK_SPILL) { if (spill->type != SCALAR_VALUE) @@ -454,7 +454,7 @@ static void __clean_func_state(struct bpf_verifier_env *env, if (bpf_register_is_null(spill)) continue; for (j = 0; j < 4; j++) { - u8 *t = &st->stack[i].slot_type[j]; + u8 *t = &bpf_stack_slot(st, i)->slot_type[j]; if (*t == STACK_SPILL) *t = STACK_MISC; @@ -463,7 +463,7 @@ static void __clean_func_state(struct bpf_verifier_env *env, bpf_mark_reg_not_init(env, spill); } for (j = start; j < end; j++) - st->stack[i].slot_type[j] = STACK_POISON; + bpf_stack_slot(st, i)->slot_type[j] = STACK_POISON; } } } @@ -709,37 +709,38 @@ static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, * didn't use them */ for (i = 0; i < old->allocated_stack; i++) { + struct bpf_stack_state *old_slot, *cur_slot; struct bpf_reg_state *old_reg, *cur_reg; int im = i % BPF_REG_SIZE; + u8 old_type; spi = i / BPF_REG_SIZE; + old_slot = bpf_stack_slot(old, spi); + old_type = old_slot->slot_type[im]; + cur_slot = i < cur->allocated_stack ? bpf_stack_slot(cur, spi) : NULL; if (exact == EXACT) { - u8 old_type = old->stack[spi].slot_type[i % BPF_REG_SIZE]; - u8 cur_type = i < cur->allocated_stack ? - cur->stack[spi].slot_type[i % BPF_REG_SIZE] : STACK_INVALID; + u8 cur_type = cur_slot ? cur_slot->slot_type[im] : STACK_INVALID; /* STACK_INVALID and STACK_POISON are equivalent for pruning */ if (old_type == STACK_POISON) old_type = STACK_INVALID; if (cur_type == STACK_POISON) cur_type = STACK_INVALID; - if (i >= cur->allocated_stack || old_type != cur_type) + if (!cur_slot || old_type != cur_type) return false; } - if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID || - old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_POISON) + if (old_type == STACK_INVALID || old_type == STACK_POISON) continue; - if (env->allow_uninit_stack && - old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) + if (env->allow_uninit_stack && old_type == STACK_MISC) continue; /* explored stack has more populated slots than current stack * and these slots were used */ - if (i >= cur->allocated_stack) + if (!cur_slot) return false; /* @@ -749,8 +750,8 @@ static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, * regsafe() to ensure scalar ids are compared. */ if (im == 0 || im == 4) { - old_reg = scalar_reg_for_stack(env, &old->stack[spi], im); - cur_reg = scalar_reg_for_stack(env, &cur->stack[spi], im); + old_reg = scalar_reg_for_stack(env, old_slot, im); + cur_reg = scalar_reg_for_stack(env, cur_slot, im); if (old_reg && cur_reg) { if (!regsafe(env, old_reg, cur_reg, idmap, exact)) return false; @@ -763,21 +764,19 @@ static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, * it will be safe with zero-initialized stack. * The opposite is not true */ - if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && - cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) + if (old_type == STACK_MISC && cur_slot->slot_type[im] == STACK_ZERO) continue; - if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != - cur->stack[spi].slot_type[i % BPF_REG_SIZE]) + if (old_type != cur_slot->slot_type[im]) /* Ex: old explored (safe) state has STACK_SPILL in * this stack slot, but current has STACK_MISC -> * this verifier states are not equivalent, * return false to continue verification of this path */ return false; - if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) + if (im != BPF_REG_SIZE - 1) continue; /* Both old and cur are having same slot_type */ - switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { + switch (old_type) { case STACK_SPILL: /* when explored and current stack slot are both storing * spilled registers, check that stored pointers types @@ -789,13 +788,13 @@ static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, * such verifier states are not equivalent. * return false to continue verification of this path */ - if (!regsafe(env, &old->stack[spi].spilled_ptr, - &cur->stack[spi].spilled_ptr, idmap, exact)) + if (!regsafe(env, &old_slot->spilled_ptr, &cur_slot->spilled_ptr, + idmap, exact)) return false; break; case STACK_DYNPTR: - old_reg = &old->stack[spi].spilled_ptr; - cur_reg = &cur->stack[spi].spilled_ptr; + old_reg = &old_slot->spilled_ptr; + cur_reg = &cur_slot->spilled_ptr; if (old_reg->dynptr.type != cur_reg->dynptr.type || old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || !check_ids(old_reg->id, cur_reg->id, idmap) || @@ -803,8 +802,8 @@ static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, return false; break; case STACK_ITER: - old_reg = &old->stack[spi].spilled_ptr; - cur_reg = &cur->stack[spi].spilled_ptr; + old_reg = &old_slot->spilled_ptr; + cur_reg = &cur_slot->spilled_ptr; /* iter.depth is not compared between states as it * doesn't matter for correctness and would otherwise * prevent convergence; we maintain it only to prevent @@ -820,8 +819,8 @@ static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, return false; break; case STACK_IRQ_FLAG: - old_reg = &old->stack[spi].spilled_ptr; - cur_reg = &cur->stack[spi].spilled_ptr; + old_reg = &old_slot->spilled_ptr; + cur_reg = &cur_slot->spilled_ptr; if (!check_ids(old_reg->id, cur_reg->id, idmap) || old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class) return false; @@ -953,6 +952,9 @@ static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_stat if (!old->no_stack_arg_load && cur->no_stack_arg_load) return false; + if (old->in_rcu_callback_fn != cur->in_rcu_callback_fn) + return false; + for (i = 0; i < MAX_BPF_REG; i++) if (((1 << i) & live_regs) && !regsafe(env, &old->regs[i], &cur->regs[i], @@ -1045,10 +1047,12 @@ static int propagate_precision(struct bpf_verifier_env *env, first = false; } - for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { - if (!bpf_is_spilled_reg(&state->stack[i])) + for (i = 0; i < bpf_stack_nr_slots(state); i++) { + struct bpf_stack_state *ss = bpf_stack_slot(state, i); + + if (!bpf_is_spilled_reg(ss)) continue; - state_reg = &state->stack[i].spilled_ptr; + state_reg = &ss->spilled_ptr; if (state_reg->type != SCALAR_VALUE || !state_reg->precise) continue; @@ -1194,15 +1198,17 @@ static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf for (fr = old->curframe; fr >= 0; fr--) { state = old->frame[fr]; - for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { - if (state->stack[i].slot_type[0] != STACK_ITER) + for (i = 0; i < bpf_stack_nr_slots(state); i++) { + struct bpf_stack_state *ss = bpf_stack_slot(state, i); + + if (ss->slot_type[0] != STACK_ITER) continue; - slot = &state->stack[i].spilled_ptr; + slot = &ss->spilled_ptr; if (slot->iter.state != BPF_ITER_STATE_ACTIVE) continue; - cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; + cur_slot = &bpf_stack_slot(cur->frame[fr], i)->spilled_ptr; if (cur_slot->iter.depth != slot->iter.depth) return true; } @@ -1224,10 +1230,12 @@ static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_ continue; reg->precise = false; } - for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { - if (!bpf_is_spilled_reg(&func->stack[j])) + for (j = 0; j < bpf_stack_nr_slots(func); j++) { + struct bpf_stack_state *ss = bpf_stack_slot(func, j); + + if (!bpf_is_spilled_reg(ss)) continue; - reg = &func->stack[j].spilled_ptr; + reg = &ss->spilled_ptr; if (reg->type != SCALAR_VALUE) continue; reg->precise = false; @@ -1275,10 +1283,10 @@ int bpf_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 @@ -1330,8 +1338,9 @@ int bpf_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, *iter_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]; @@ -1344,8 +1353,18 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx) * no need for extra (re-)validations */ spi = bpf_get_spi(iter_reg->var_off.value); - iter_state = &bpf_func(env, iter_reg)->stack[spi].spilled_ptr; - if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { + iter_frame = bpf_func(env, iter_reg); + iter_state = &bpf_stack_slot(iter_frame, spi)->spilled_ptr; + old_frame = sl->state.frame[iter_reg->frameno]; + old_iter = &bpf_stack_slot(old_frame, 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->id == old_iter->id) { loop = true; goto hit; } diff --git a/kernel/bpf/stream.c b/kernel/bpf/stream.c index be9ce98e9469..9829d1ebce70 100644 --- a/kernel/bpf/stream.c +++ b/kernel/bpf/stream.c @@ -22,11 +22,11 @@ static struct bpf_stream_elem *bpf_stream_elem_alloc(int len) size_t alloc_size; /* - * Length denotes the amount of data to be written as part of stream element, - * thus includes '\0' byte. We're capped by how much bpf_bprintf_buffers can - * accomodate, therefore deny allocations that won't fit into them. + * Length is the payload pushed into the stream, excluding the + * trailing NUL of the bprintf buffer. Reject anything that cannot + * fit without copying that NUL into the stream element. */ - if (len < 0 || len > max_len) + if (len < 0 || len >= max_len) return NULL; alloc_size = offsetof(struct bpf_stream_elem, str[len]); @@ -68,18 +68,28 @@ static int bpf_stream_consume_capacity(struct bpf_stream *stream, int len) return 0; } -static void bpf_stream_release_capacity(struct bpf_stream *stream, struct bpf_stream_elem *elem) +static void bpf_stream_release_capacity(struct bpf_stream *stream, int len) { - int len = elem->total_len; - atomic_sub(len, &stream->capacity); } static int bpf_stream_push_str(struct bpf_stream *stream, const char *str, int len) { - int ret = bpf_stream_consume_capacity(stream, len); + int ret; + + /* Nothing to publish; do not allocate an element for it. */ + if (!len) + return 0; - return ret ?: __bpf_stream_push_str(&stream->log, str, len); + ret = bpf_stream_consume_capacity(stream, len); + if (ret) + return ret; + + ret = __bpf_stream_push_str(&stream->log, str, len); + if (ret) + bpf_stream_release_capacity(stream, len); + + return ret; } static struct bpf_stream *bpf_stream_get(enum bpf_stream_id stream_id, struct bpf_prog_aux *aux) @@ -162,6 +172,7 @@ static int bpf_stream_read(struct bpf_stream *stream, void __user *buf, int len) while (rem_len) { int pos = len - rem_len; + int chunk, n; bool cont; node = bpf_stream_backlog_peek(stream); @@ -175,20 +186,21 @@ static int bpf_stream_read(struct bpf_stream *stream, void __user *buf, int len) cons_len = elem->consumed_len; cont = bpf_stream_consume_elem(elem, &rem_len) == false; - - ret = copy_to_user(buf + pos, elem->str + cons_len, - elem->consumed_len - cons_len); - /* Restore in case of error. */ - if (ret) { - ret = -EFAULT; - elem->consumed_len = cons_len; + chunk = elem->consumed_len - cons_len; + + n = copy_to_user(buf + pos, elem->str + cons_len, chunk); + if (n) { + /* Keep any successfully copied bytes; -EFAULT only if none. */ + elem->consumed_len -= n; + rem_len += n; + ret = (len == rem_len) ? -EFAULT : 0; break; } if (cont) continue; bpf_stream_backlog_pop(stream); - bpf_stream_release_capacity(stream, elem); + bpf_stream_release_capacity(stream, elem->total_len); bpf_stream_free_elem(elem); } @@ -196,13 +208,15 @@ static int bpf_stream_read(struct bpf_stream *stream, void __user *buf, int len) return ret ? ret : len - rem_len; } -int bpf_prog_stream_read(struct bpf_prog *prog, enum bpf_stream_id stream_id, void __user *buf, int len) +int bpf_prog_stream_read(struct bpf_prog *prog, enum bpf_stream_id stream_id, void __user *buf, u32 len) { struct bpf_stream *stream; stream = bpf_stream_get(stream_id, prog->aux); if (!stream) return -ENOENT; + if (len > INT_MAX) + return -EINVAL; return bpf_stream_read(stream, buf, len); } @@ -238,6 +252,11 @@ __bpf_kfunc int bpf_stream_vprintk(int stream_id, const char *fmt__str, const vo return ret; ret = bstr_printf(data.buf, MAX_BPRINTF_BUF, fmt__str, data.bin_args); + /* Truncation: reject before capacity charge (not -ENOMEM). */ + if (ret >= MAX_BPRINTF_BUF) { + bpf_bprintf_cleanup(&data); + return -E2BIG; + } /* Exclude NULL byte during push. */ ret = bpf_stream_push_str(stream, data.buf, ret); bpf_bprintf_cleanup(&data); @@ -311,17 +330,18 @@ int bpf_stream_stage_printk(struct bpf_stream_stage *ss, const char *fmt, ...) { struct bpf_bprintf_buffers *buf; va_list args; - int ret; + int len, ret; if (bpf_try_get_buffers(&buf)) return -EBUSY; va_start(args, fmt); - ret = vsnprintf(buf->buf, ARRAY_SIZE(buf->buf), fmt, args); + len = vscnprintf(buf->buf, ARRAY_SIZE(buf->buf), fmt, args); va_end(args); - ss->len += ret; - /* Exclude NULL byte during push. */ - ret = __bpf_stream_push_str(&ss->log, buf->buf, ret); + /* Exclude NULL byte during push; skip empty output entirely. */ + ret = len ? __bpf_stream_push_str(&ss->log, buf->buf, len) : 0; + if (!ret) + ss->len += len; bpf_put_buffers(); return ret; } diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c index 96217b99399d..1836cf9403fe 100644 --- a/kernel/bpf/syscall.c +++ b/kernel/bpf/syscall.c @@ -602,38 +602,45 @@ static bool can_alloc_pages(void) !IS_ENABLED(CONFIG_PREEMPT_RT); } -static struct page *__bpf_alloc_page(int nid) +struct page *bpf_alloc_page(int nid, bool sleepable) { - if (!can_alloc_pages()) + if (!sleepable || !can_alloc_pages()) return alloc_pages_nolock(__GFP_ACCOUNT, nid, 0); return alloc_pages_node(nid, GFP_KERNEL | __GFP_ZERO | __GFP_ACCOUNT - | __GFP_NOWARN, + | __GFP_NOWARN | __GFP_RETRY_MAYFAIL, 0); } -int bpf_map_alloc_pages(const struct bpf_map *map, int nid, - unsigned long nr_pages, struct page **pages) +void bpf_free_pages(struct llist_head *pages) { - unsigned long i, j; + struct llist_node *node; + struct page *page, *tmp; + + node = llist_del_all(pages); + llist_for_each_entry_safe(page, tmp, node, pcp_llist) + free_pages_nolock(page, 0); +} + +int bpf_alloc_pages(int nid, unsigned long nr_pages, + struct llist_head *pages, bool sleepable) +{ + unsigned long i; struct page *pg; - int ret = 0; for (i = 0; i < nr_pages; i++) { - pg = __bpf_alloc_page(nid); - - if (pg) { - pages[i] = pg; - continue; - } - for (j = 0; j < i; j++) - free_pages_nolock(pages[j], 0); - ret = -ENOMEM; - break; + pg = bpf_alloc_page(nid, sleepable); + if (!pg) + goto free_pages; + llist_add(&pg->pcp_llist, pages); } - return ret; + return 0; + +free_pages: + bpf_free_pages(pages); + return -ENOMEM; } static int btf_field_cmp(const void *a, const void *b) @@ -2441,6 +2448,9 @@ static void __bpf_prog_put_rcu(struct rcu_head *rcu) { struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu); + btf_put(aux->btf); + kvfree(aux->jited_linfo); + kvfree(aux->linfo); kvfree(aux->func_info); kfree(aux->func_info_aux); free_uid(aux->user); @@ -2457,7 +2467,7 @@ static void __bpf_prog_put_rcu_tasks(struct rcu_head *rcu) { struct bpf_prog *prog = container_of(rcu, struct bpf_prog_aux, rcu)->prog; - if (prog->sleepable) + if (bpf_prog_runs_sleepable(prog)) call_rcu_tasks_trace(rcu, __bpf_prog_put_rcu); else call_rcu(rcu, __bpf_prog_put_rcu); @@ -2465,11 +2475,7 @@ static void __bpf_prog_put_rcu_tasks(struct rcu_head *rcu) static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred) { - bpf_prog_kallsyms_del_all(prog); - btf_put(prog->aux->btf); module_put(prog->aux->mod); - kvfree(prog->aux->jited_linfo); - kvfree(prog->aux->linfo); kfree(prog->aux->kfunc_tab); kfree(prog->aux->ctx_arg_info); if (prog->aux->attach_btf) @@ -2478,7 +2484,7 @@ static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred) if (deferred) { if (IS_ENABLED(CONFIG_TASKS_RCU) && prog->aux->tramp_linked) call_rcu_tasks(&prog->aux->rcu, __bpf_prog_put_rcu_tasks); - else if (prog->sleepable) + else 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); @@ -3824,6 +3830,19 @@ static int bpf_tracing_prog_attach(struct bpf_prog *prog, err = -EINVAL; goto out_unlock; } + /* + * The size of these contexts depends on what the program is attached + * to, or run with. That is compared with max_ctx_offset of the program, + * and nobody looks at the one of its extensions. + */ + if (prog->type == BPF_PROG_TYPE_EXT && + (tgt_prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT || + tgt_prog->type == BPF_PROG_TYPE_TRACEPOINT || + tgt_prog->type == BPF_PROG_TYPE_SYSCALL) && + prog->aux->max_ctx_offset > tgt_prog->aux->max_ctx_offset) { + err = -EINVAL; + goto out_unlock; + } err = bpf_link_prime(&link->link.link, &link_primer); if (err) @@ -3993,19 +4012,19 @@ static int bpf_perf_link_fill_common(const struct perf_event *event, *ulenp = 1; } if (!uname) - return 0; + goto out; if (buf) { err = bpf_copy_to_user(uname, buf, ulen, len); - if (err) - return err; } else { char zero = '\0'; if (put_user(zero, uname)) - return -EFAULT; + err = -EFAULT; } - return 0; +out: + kfree_const(buf); + return err; } #ifdef CONFIG_KPROBE_EVENTS @@ -4062,6 +4081,7 @@ static void bpf_perf_link_fdinfo_kprobe(const struct perf_event *event, name, offset, missed, addr, type == BPF_FD_TYPE_KRETPROBE ? "kretprobe" : "kprobe", event->bpf_cookie); + kfree_const(name); } #endif @@ -4115,6 +4135,7 @@ static void bpf_perf_link_fdinfo_uprobe(const struct perf_event *event, name, offset, ref_ctr_offset, type == BPF_FD_TYPE_URETPROBE ? "uretprobe" : "uprobe", event->bpf_cookie); + kfree_const(name); } #endif @@ -4213,6 +4234,7 @@ static void bpf_tracepoint_link_show_fdinfo(const struct perf_event *event, "event_type:\t%s\n" "cookie:\t%llu\n", name, "tracepoint", event->bpf_cookie); + kfree_const(name); } static void bpf_probe_link_show_fdinfo(const struct perf_event *event, @@ -5420,7 +5442,11 @@ static int bpf_map_get_info_by_fd(struct file *file, info_len = min_t(u32, sizeof(info), info_len); memset(&info, 0, sizeof(info)); - if (copy_from_user(&info, uinfo, info_len)) + if (info_len >= offsetofend(struct bpf_map_info, hash) && + get_user(info.hash, &uinfo->hash)) + return -EFAULT; + if (info_len >= offsetofend(struct bpf_map_info, hash_size) && + get_user(info.hash_size, &uinfo->hash_size)) return -EFAULT; info.type = map->map_type; @@ -5735,11 +5761,13 @@ static int bpf_task_fd_query(const union bpf_attr *attr, err = bpf_get_perf_event_info(event, &prog_id, &fd_type, &buf, &probe_offset, &probe_addr, NULL); - if (!err) + if (!err) { err = bpf_task_fd_query_copy(attr, uattr, prog_id, fd_type, buf, probe_offset, probe_addr); + kfree_const(buf); + } goto put_file; } @@ -6220,7 +6248,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/task_iter.c b/kernel/bpf/task_iter.c index 13e1aabe6f88..2fa6b8dae8c4 100644 --- a/kernel/bpf/task_iter.c +++ b/kernel/bpf/task_iter.c @@ -737,7 +737,11 @@ static const struct bpf_iter_seq_info task_vma_seq_info = { static struct bpf_iter_reg task_vma_reg_info = { .target = "task_vma", .attach_target = bpf_iter_attach_task, - .feature = BPF_ITER_RESCHED, + /* + * ->show() runs with the mmap_lock of the iterated mm held, which a + * sleepable program takes again when it faults on user memory. + */ + .feature = BPF_ITER_RESCHED | BPF_ITER_NOSLEEP, .ctx_arg_info_size = 2, .ctx_arg_info = { { offsetof(struct bpf_iter__task_vma, task), @@ -806,8 +810,14 @@ BPF_CALL_5(bpf_find_vma, struct task_struct *, task, u64, start, vma = find_vma(mm, start); if (vma && vma->vm_start <= start && vma->vm_end > start) { + /* + * The callback must not sleep while mmap_lock is held, and the + * verifier checks it as an RCU read-side critical section. + */ + rcu_read_lock(); callback_fn((u64)(long)task, (u64)(long)vma, (u64)(long)callback_ctx, 0, 0); + rcu_read_unlock(); ret = 0; } bpf_mmap_unlock_mm(work, mm); diff --git a/kernel/bpf/token.c b/kernel/bpf/token.c index e85a179523f0..19660ef95ddb 100644 --- a/kernel/bpf/token.c +++ b/kernel/bpf/token.c @@ -169,8 +169,11 @@ int bpf_token_create(union bpf_attr *attr) FD_PREPARE(fdf, O_CLOEXEC, alloc_file_pseudo(inode, path.mnt, BPF_TOKEN_INODE_NAME, O_RDWR, &bpf_token_fops)); - if (fdf.err) + if (fdf.err) { + /* no file took over the inode reference */ + iput(inode); return fdf.err; + } token = kzalloc_obj(*token, GFP_USER); if (!token) diff --git a/kernel/bpf/trampoline.c b/kernel/bpf/trampoline.c index bf4cb3dd444d..24edb59238f3 100644 --- a/kernel/bpf/trampoline.c +++ b/kernel/bpf/trampoline.c @@ -859,7 +859,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; @@ -873,7 +873,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; } @@ -1023,13 +1023,20 @@ static int __bpf_trampoline_link_prog(struct bpf_tramp_node *node, /* 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_NOP, + BPF_MOD_JUMP, NULL, + node->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 = node->link->prog; - return bpf_arch_text_poke(tr->func.addr, BPF_MOD_NOP, - BPF_MOD_JUMP, NULL, - node->link->prog->bpf_func); + return 0; } err = bpf_trampoline_add_prog(tr, node, cnt); if (err) @@ -1069,7 +1076,7 @@ static int __bpf_trampoline_unlink_prog(struct bpf_tramp_node *node, 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; } bpf_trampoline_remove_prog(tr, node); @@ -1631,6 +1638,14 @@ static int register_fentry_multi(struct bpf_trampoline *tr, struct bpf_tramp_ima unsigned long ip = ftrace_location(tr->ip); struct bpf_tracing_multi_data *data = ptr; + /* + * Different BTF ids get different trampolines, but they can still + * resolve to the same address (aliases, functions of the same name). + * There's only one call site to attach to. + */ + if (ftrace_lookup_ip(data->reg, ip)) + return -EINVAL; + if (bpf_trampoline_use_jmp(tr->flags)) addr = ftrace_jmp_set(addr); diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c index 5f874979b8d7..2ed356a03a57 100644 --- a/kernel/bpf/verifier.c +++ b/kernel/bpf/verifier.c @@ -208,6 +208,9 @@ static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int par static int __release_reference_nomark(struct bpf_verifier_state *state, int id); static int release_reference_nomark(struct bpf_verifier_env *env, int id); static int release_reference(struct bpf_verifier_env *env, int id); +static int invalidate_reference(struct bpf_verifier_env *env, int id); +static u32 reg_lifetime_id(struct bpf_verifier_env *env, + const struct bpf_reg_state *reg); static void invalidate_non_owning_refs(struct bpf_verifier_env *env); static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env); static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); @@ -216,6 +219,7 @@ static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg); static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg); static inline bool in_sleepable_context(struct bpf_verifier_env *env); +static bool in_rcu_callback(struct bpf_verifier_env *env); static const char *non_sleepable_context_description(struct bpf_verifier_env *env); static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); @@ -537,6 +541,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); +} + bool bpf_is_may_goto_insn(struct bpf_insn *insn) { return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; @@ -544,16 +561,17 @@ bool bpf_is_may_goto_insn(struct bpf_insn *insn) static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) { - int allocated_slots = state->allocated_stack / BPF_REG_SIZE; + int allocated_slots = bpf_stack_nr_slots(state); - /* We need to check that slots between [spi - nr_slots + 1, spi] are - * within [0, allocated_stack). - * - * Please note that the spi grows downwards. For example, a dynptr - * takes the size of two stack slots; the first slot will be at - * spi and the second slot will be at spi - 1. - */ - return spi - nr_slots + 1 >= 0 && spi < allocated_slots; + /* + * We need to check that slots between [spi - nr_slots + 1, spi] are + * within [0, allocated_stack). + * + * Please note that the spi grows downwards. For example, a dynptr + * takes the size of two stack slots; the first slot will be at + * spi and the second slot will be at spi - 1. + */ + return spi - nr_slots + 1 >= 0 && spi < allocated_slots; } static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, @@ -668,6 +686,21 @@ static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi); +static int destroy_dynptrs_in_stack_slots(struct bpf_verifier_env *env, + struct bpf_func_state *state, + int first_spi, int last_spi) +{ + int spi, err; + + for (spi = first_spi; spi <= last_spi; spi++) { + err = destroy_if_dynptr_stack_slot(env, state, spi); + if (err) + return err; + } + + return 0; +} + static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, enum bpf_arg_type arg_type, int insn_idx, struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr) @@ -681,7 +714,7 @@ static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_ return spi; /* We cannot assume both spi and spi - 1 belong to the same dynptr, - * hence we need to call destroy_if_dynptr_stack_slot twice for both, + * hence we need to destroy dynptrs in both slots, * to ensure that for the following example: * [d1][d1][d2][d2] * spi 3 2 1 0 @@ -689,16 +722,13 @@ static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_ * case they do belong to same dynptr, second call won't see slot_type * as STACK_DYNPTR and will simply skip destruction. */ - err = destroy_if_dynptr_stack_slot(env, state, spi); - if (err) - return err; - err = destroy_if_dynptr_stack_slot(env, state, spi - 1); + err = destroy_dynptrs_in_stack_slots(env, state, spi - 1, spi); if (err) return err; for (i = 0; i < BPF_REG_SIZE; i++) { - state->stack[spi].slot_type[i] = STACK_DYNPTR; - state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; + bpf_stack_slot(state, spi)->slot_type[i] = STACK_DYNPTR; + bpf_stack_slot(state, spi - 1)->slot_type[i] = STACK_DYNPTR; } type = arg_to_dynptr_type(arg_type); @@ -710,8 +740,8 @@ static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_ if (err) return err; - /* Track parent's id if the parent is a referenced object */ - parent_id = ref_obj->id; + /* All non-clone constructors take their backing object in R1. */ + parent_id = reg_lifetime_id(env, &cur_regs(env)[BPF_REG_1]); if (dynptr_type_referenced(type)) { int id; @@ -731,8 +761,8 @@ static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_ parent_id = dynptr->parent_id; } - mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, - &state->stack[spi - 1].spilled_ptr, type, parent_id); + mark_dynptr_stack_regs(env, &bpf_stack_slot(state, spi)->spilled_ptr, + &bpf_stack_slot(state, spi - 1)->spilled_ptr, type, parent_id); return 0; } @@ -764,7 +794,7 @@ static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_re * all clones and derived slices. For non-referenced dynptr, only * the dynptr and slices derived from it will be invalidated. */ - reg = &state->stack[spi].spilled_ptr; + reg = &bpf_stack_slot(state, spi)->spilled_ptr; return release_reference(env, dynptr_type_referenced(reg->dynptr.type) ? reg->parent_id : reg->id); @@ -803,6 +833,7 @@ static int dynptr_ref_cnt(struct bpf_verifier_env *env, int v_parent_id) static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) { + struct bpf_stack_state *slot = bpf_stack_slot(state, spi); int err = 0; /* We always ensure that STACK_DYNPTR is never set partially, @@ -810,20 +841,22 @@ static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, * different for STACK_SPILL, where it may be only set for * 1 byte, so code has to use is_spilled_reg. */ - if (state->stack[spi].slot_type[0] != STACK_DYNPTR) + if (slot->slot_type[0] != STACK_DYNPTR) return 0; /* Reposition spi to first slot */ - if (!state->stack[spi].spilled_ptr.dynptr.first_slot) + if (!slot->spilled_ptr.dynptr.first_slot) { spi = spi + 1; + slot = bpf_stack_slot(state, spi); + } /* * A referenced dynptr can be overwritten only if there is at * least one other dynptr sharing the same virtual ref parent, * ensuring the reference can still be properly released. */ - if (dynptr_type_referenced(state->stack[spi].spilled_ptr.dynptr.type) && - dynptr_ref_cnt(env, state->stack[spi].spilled_ptr.parent_id) <= 1) { + if (dynptr_type_referenced(slot->spilled_ptr.dynptr.type) && + dynptr_ref_cnt(env, slot->spilled_ptr.parent_id) <= 1) { verbose(env, "cannot overwrite referenced dynptr\n"); bpf_diag_res( env, env->insn_idx, "referenced dynptr overwrite", @@ -833,7 +866,7 @@ static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, } /* Invalidate the dynptr and any derived slices */ - err = release_reference(env, state->stack[spi].spilled_ptr.id); + err = release_reference(env, slot->spilled_ptr.id); if (!err) { mark_stack_slot_scratched(env, spi); mark_stack_slot_scratched(env, spi - 1); @@ -873,6 +906,7 @@ static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_ static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) { struct bpf_func_state *state = bpf_func(env, reg); + struct bpf_stack_state *slot; int i, spi; /* This already represents first slot of initialized bpf_dynptr. @@ -887,12 +921,13 @@ static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_re spi = dynptr_get_spi(env, reg); if (spi < 0) return false; - if (!state->stack[spi].spilled_ptr.dynptr.first_slot) + slot = bpf_stack_slot(state, spi); + if (!slot->spilled_ptr.dynptr.first_slot) return false; for (i = 0; i < BPF_REG_SIZE; i++) { - if (state->stack[spi].slot_type[i] != STACK_DYNPTR || - state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) + if (slot->slot_type[i] != STACK_DYNPTR || + bpf_stack_slot(state, spi - 1)->slot_type[i] != STACK_DYNPTR) return false; } @@ -911,7 +946,7 @@ static enum bpf_dynptr_type dynptr_reg_type(struct bpf_verifier_env *env, struct if (spi < 0) return BPF_DYNPTR_TYPE_INVALID; state = bpf_func(env, reg); - return state->stack[spi].spilled_ptr.dynptr.type; + return bpf_stack_slot(state, spi)->spilled_ptr.dynptr.type; } static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, @@ -947,7 +982,7 @@ static int mark_stack_slots_iter(struct bpf_verifier_env *env, return id; for (i = 0; i < nr_slots; i++) { - struct bpf_stack_state *slot = &state->stack[spi - i]; + struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i); struct bpf_reg_state *st = &slot->spilled_ptr; __mark_reg_known_zero(st); @@ -977,18 +1012,21 @@ static int unmark_stack_slots_iter(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) { struct bpf_func_state *state = bpf_func(env, reg); - int spi, i, j; + int spi, i, j, err; spi = iter_get_spi(env, reg, nr_slots); if (spi < 0) return spi; for (i = 0; i < nr_slots; i++) { - struct bpf_stack_state *slot = &state->stack[spi - i]; + struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i); struct bpf_reg_state *st = &slot->spilled_ptr; - if (i == 0) - WARN_ON_ONCE(release_reference(env, st->id)); + if (i == 0) { + err = release_reference(env, st->id); + if (err) + return err; + } bpf_mark_reg_not_init(env, st); @@ -1018,7 +1056,7 @@ static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, return false; for (i = 0; i < nr_slots; i++) { - struct bpf_stack_state *slot = &state->stack[spi - i]; + struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i); for (j = 0; j < BPF_REG_SIZE; j++) if (slot->slot_type[j] == STACK_ITER) @@ -1039,7 +1077,7 @@ static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_s return -EINVAL; for (i = 0; i < nr_slots; i++) { - struct bpf_stack_state *slot = &state->stack[spi - i]; + struct bpf_stack_state *slot = bpf_stack_slot(state, spi - i); struct bpf_reg_state *st = &slot->spilled_ptr; if (st->type & PTR_UNTRUSTED) @@ -1081,7 +1119,7 @@ static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env, if (id < 0) return id; - slot = &state->stack[spi]; + slot = bpf_stack_slot(state, spi); st = &slot->spilled_ptr; __mark_reg_known_zero(st); @@ -1108,7 +1146,7 @@ static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_r if (spi < 0) return spi; - slot = &state->stack[spi]; + slot = bpf_stack_slot(state, spi); st = &slot->spilled_ptr; if (st->irq.kfunc_class != kfunc_class) { @@ -1177,7 +1215,7 @@ static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bp if (spi < 0) return false; - slot = &state->stack[spi]; + slot = bpf_stack_slot(state, spi); for (i = 0; i < BPF_REG_SIZE; i++) if (slot->slot_type[i] == STACK_IRQ_FLAG) @@ -1196,7 +1234,7 @@ static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_r if (spi < 0) return -EINVAL; - slot = &state->stack[spi]; + slot = bpf_stack_slot(state, spi); st = &slot->spilled_ptr; if (!st->id) @@ -1343,7 +1381,7 @@ static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) { - size_t n = src->allocated_stack / BPF_REG_SIZE; + size_t n = bpf_stack_nr_slots(src); dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), GFP_KERNEL_ACCOUNT); @@ -1382,7 +1420,7 @@ static int resize_reference_state(struct bpf_verifier_state *state, size_t n) */ static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) { - size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; + size_t old_n = bpf_stack_nr_slots(state), n; /* The stack size is always a multiple of BPF_REG_SIZE. */ size = round_up(size, BPF_REG_SIZE); @@ -1530,6 +1568,12 @@ static bool reg_is_referenced(struct bpf_verifier_env *env, const struct bpf_reg return find_reference_state(env->cur_state, reg->id); } +static u32 reg_lifetime_id(struct bpf_verifier_env *env, + const struct bpf_reg_state *reg) +{ + return reg_is_referenced(env, reg) ? reg->id : reg->parent_id; +} + static int release_lock_state(struct bpf_verifier_env *env, int type, int id, void *ptr) { struct bpf_verifier_state *state = env->cur_state; @@ -2406,6 +2450,7 @@ static int add_subprog(struct bpf_verifier_env *env, int off) return -E2BIG; } /* determine subprog starts. The end is one before the next starts */ + env->subprog_info[env->subprog_cnt].exit_idx = U32_MAX; env->subprog_info[env->subprog_cnt++].start = off; sort(env->subprog_info, env->subprog_cnt, sizeof(env->subprog_info[0]), cmp_subprogs, NULL); @@ -3453,17 +3498,18 @@ static void save_register_state(struct bpf_verifier_env *env, int spi, struct bpf_reg_state *reg, int size) { + struct bpf_stack_state *slot = bpf_stack_slot(state, spi); int i; - bpf_diag_mod_begin(env, &state->stack[spi].spilled_ptr, reg, BPF_DIAG_MOD_SPILL); - state->stack[spi].spilled_ptr = *reg; + bpf_diag_mod_begin(env, &slot->spilled_ptr, reg, BPF_DIAG_MOD_SPILL); + slot->spilled_ptr = *reg; for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) - state->stack[spi].slot_type[i - 1] = STACK_SPILL; + slot->slot_type[i - 1] = STACK_SPILL; /* size < 8 bytes spill */ for (; i; i--) - mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); + mark_stack_slot_misc(env, &slot->slot_type[i - 1]); bpf_diag_mod_end(env); } @@ -3505,14 +3551,15 @@ static void check_fastcall_stack_contract(struct bpf_verifier_env *env, static void scrub_special_slot(struct bpf_func_state *state, int spi) { + struct bpf_stack_state *slot = bpf_stack_slot(state, spi); int i; /* regular write of data into stack destroys any spilled ptr */ - state->stack[spi].spilled_ptr.type = NOT_INIT; + slot->spilled_ptr.type = NOT_INIT; /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ - if (is_stack_slot_special(&state->stack[spi])) + if (is_stack_slot_special(slot)) for (i = 0; i < BPF_REG_SIZE; i++) - scrub_spilled_slot(&state->stack[spi].slot_type[i]); + scrub_spilled_slot(&slot->slot_type[i]); } /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, @@ -3530,13 +3577,14 @@ static int check_stack_write_fixed_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg = NULL; int insn_flags = INSN_F_STACK_ACCESS; int hist_spi = spi, hist_frame = state->frameno; + struct bpf_stack_state *ss = bpf_stack_slot(state, spi); /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, * so it's aligned access and [off, off + size) are within stack limits */ if (!env->allow_ptr_leaks && - bpf_is_spilled_reg(&state->stack[spi]) && - !bpf_is_spilled_scalar_reg(&state->stack[spi]) && + bpf_is_spilled_reg(ss) && + !bpf_is_spilled_scalar_reg(ss) && size != BPF_REG_SIZE) { const char *reason; @@ -3558,7 +3606,7 @@ static int check_stack_write_fixed_off(struct bpf_verifier_env *env, bool sanitize = reg && is_pointer_regtype(reg->type); for (i = 0; i < size; i++) { - u8 type = state->stack[spi].slot_type[(slot - i) % + u8 type = ss->slot_type[(slot - i) % BPF_REG_SIZE]; if (type != STACK_MISC && type != STACK_ZERO) { @@ -3575,7 +3623,6 @@ static int check_stack_write_fixed_off(struct bpf_verifier_env *env, if (err) return err; - 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; @@ -3587,7 +3634,7 @@ static int check_stack_write_fixed_off(struct bpf_verifier_env *env, save_register_state(env, state, spi, reg, size); /* Break the relation on a narrowing spill. */ if (!reg_value_fits) - clear_scalar_id(&state->stack[spi].spilled_ptr); + clear_scalar_id(&ss->spilled_ptr); } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && env->bpf_capable) { struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; @@ -3611,8 +3658,8 @@ static int check_stack_write_fixed_off(struct bpf_verifier_env *env, } else { u8 type = STACK_MISC; - if (bpf_is_spilled_reg(&state->stack[spi])) - bpf_diag_record_scrub(env, &state->stack[spi].spilled_ptr, + if (bpf_is_spilled_reg(ss)) + bpf_diag_record_scrub(env, &ss->spilled_ptr, BPF_DIAG_MOD_WRITE); scrub_special_slot(state, spi); @@ -3633,7 +3680,7 @@ static int check_stack_write_fixed_off(struct bpf_verifier_env *env, /* Mark slots affected by this stack write. */ for (i = 0; i < size; i++) - state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; + ss->slot_type[(slot - i) % BPF_REG_SIZE] = type; insn_flags = 0; /* not a register spill */ } @@ -3687,24 +3734,21 @@ static int check_stack_write_var_off(struct bpf_verifier_env *env, (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) writing_zero = true; - for (i = min_off; i < max_off; i++) { - int spi; - - spi = bpf_get_spi(i); - err = destroy_if_dynptr_stack_slot(env, state, spi); - if (err) - return err; - } + err = destroy_dynptrs_in_stack_slots(env, state, bpf_get_spi(max_off - 1), + bpf_get_spi(min_off)); + if (err) + 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++) { + struct bpf_stack_state *ss; u8 new_type, *stype; int slot, spi; slot = -i - 1; spi = slot / BPF_REG_SIZE; - stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; + ss = bpf_stack_slot(state, spi); + stype = &ss->slot_type[slot % BPF_REG_SIZE]; mark_stack_slot_scratched(env, spi); if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { @@ -3727,9 +3771,8 @@ static int check_stack_write_var_off(struct bpf_verifier_env *env, /* If writing_zero and the spi slot contains a spill of value 0, * maintain the spill type. */ - if (writing_zero && *stype == STACK_SPILL && - bpf_is_spilled_scalar_reg(&state->stack[spi])) { - struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; + if (writing_zero && *stype == STACK_SPILL && bpf_is_spilled_scalar_reg(ss)) { + struct bpf_reg_state *spill_reg = &ss->spilled_ptr; if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { zero_used = true; @@ -3809,13 +3852,13 @@ static int mark_reg_stack_read(struct bpf_verifier_env *env, slot = -i - 1; spi = slot / BPF_REG_SIZE; mark_stack_slot_scratched(env, spi); - stype = ptr_state->stack[spi].slot_type; + stype = bpf_stack_slot(ptr_state, spi)->slot_type; if (stype[slot % BPF_REG_SIZE] == STACK_ZERO) { zeros++; continue; } if (stype[slot % BPF_REG_SIZE] == STACK_SPILL && - bpf_register_is_null(&ptr_state->stack[spi].spilled_ptr)) { + bpf_register_is_null(&bpf_stack_slot(ptr_state, spi)->spilled_ptr)) { zero_spill_mask |= 1ull << spi; zeros++; continue; @@ -3876,12 +3919,12 @@ static int check_stack_read_fixed_off(struct bpf_verifier_env *env, int err; int insn_flags = INSN_F_STACK_ACCESS; int hist_spi = spi, hist_frame = reg_state->frameno; + struct bpf_stack_state *ss = bpf_stack_slot(reg_state, spi); - stype = reg_state->stack[spi].slot_type; - reg = ®_state->stack[spi].spilled_ptr; + stype = ss->slot_type; + reg = &ss->spilled_ptr; mark_stack_slot_scratched(env, spi); - check_fastcall_stack_contract(env, state, env->insn_idx, off); /* * Refine the in-progress load record's origin to the source stack slot. @@ -3889,7 +3932,7 @@ static int check_stack_read_fixed_off(struct bpf_verifier_env *env, if (dst_regno >= 0) bpf_diag_mod_begin(env, &state->regs[dst_regno], reg, BPF_DIAG_MOD_WRITE); - if (bpf_is_spilled_reg(®_state->stack[spi])) { + if (bpf_is_spilled_reg(ss)) { u8 spill_size = 1; for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) @@ -3902,11 +3945,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; + if (env->bpf_capable && size == 4 && spill_size == 4 && get_reg_width(reg) <= 32) /* Ensure stack slot has an ID to build a relation @@ -3948,6 +3991,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]); @@ -4068,7 +4114,6 @@ static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg dst_regno); if (err) return err; - check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); return 0; } @@ -4233,7 +4278,12 @@ static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_st } caller = vstate->frame[vstate->curframe - 1]; - arg = &caller->stack_arg_regs[spi]; + arg = bpf_get_spilled_stack_arg(spi, caller); + if (!arg) { + verbose(env, "invalid read from uninitialized stack arg off %d\n", off); + return -EACCES; + } + cur = vstate->frame[vstate->curframe]; bpf_diag_mod_begin(env, &cur->regs[dst_regno], arg, BPF_DIAG_MOD_WRITE); cur->regs[dst_regno] = *arg; @@ -5923,6 +5973,28 @@ BTF_TYPE_SAFE_TRUSTED(struct file) { struct inode *f_inode; }; +/* + * The pointer fields in the sched_ext ops argument containers are pinned by the + * callers for the duration of the ops calls and are never NULL. + */ +BTF_TYPE_SAFE_TRUSTED(struct scx_init_task_args) { +#ifdef CONFIG_EXT_GROUP_SCHED + struct cgroup *cgroup; +#endif +}; + +BTF_TYPE_SAFE_TRUSTED(struct scx_cpu_release_args) { + struct task_struct *task; +}; + +BTF_TYPE_SAFE_TRUSTED(struct scx_sub_attach_args) { + struct sched_ext_ops *ops; +}; + +BTF_TYPE_SAFE_TRUSTED(struct scx_sub_detach_args) { + struct sched_ext_ops *ops; +}; + BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) { struct inode *d_inode; }; @@ -5967,6 +6039,10 @@ static bool type_is_trusted(struct bpf_verifier_env *env, BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); + BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_init_task_args)); + BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_cpu_release_args)); + BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_sub_attach_args)); + BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct scx_sub_detach_args)); return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); } @@ -6145,9 +6221,14 @@ static int check_ptr_to_btf_access(struct bpf_verifier_env *env, } if (atype == BPF_READ && value_regno >= 0) { + u32 parent_id = reg_lifetime_id(env, reg); + ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); if (ret < 0) return ret; + if ((regs[value_regno].type & PTR_TRUSTED) && + !(regs[value_regno].type & (MEM_RCU | MEM_PERCPU | MEM_USER))) + regs[value_regno].parent_id = parent_id; } return 0; @@ -6298,6 +6379,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. */ @@ -6958,6 +7048,7 @@ static int check_stack_range_initialized( } for (i = min_off; i < max_off + access_size; i++) { + struct bpf_stack_state *ss; u8 *stype; slot = -i - 1; @@ -6967,7 +7058,8 @@ static int check_stack_range_initialized( return -EFAULT; } - stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; + ss = bpf_stack_slot(state, spi); + stype = &ss->slot_type[slot % BPF_REG_SIZE]; if (*stype == STACK_MISC) goto mark; if ((*stype == STACK_ZERO) || @@ -6979,13 +7071,18 @@ static int check_stack_range_initialized( goto mark; } - if (bpf_is_spilled_reg(&state->stack[spi]) && - (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || + /* + * 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 && + (ss->spilled_ptr.type == SCALAR_VALUE || env->allow_ptr_leaks)) { if (clobber) { - __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); + __mark_reg_unknown(env, &ss->spilled_ptr); for (j = 0; j < BPF_REG_SIZE; j++) - scrub_spilled_slot(&state->stack[spi].slot_type[j]); + scrub_spilled_slot(&ss->slot_type[j]); } goto mark; } @@ -7705,7 +7802,7 @@ static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_stat mark_stack_slots_scratched(env, spi, BPF_DYNPTR_NR_SLOTS); - reg = &state->stack[spi].spilled_ptr; + reg = &bpf_stack_slot(state, spi)->spilled_ptr; } if (dynptr) { @@ -7732,6 +7829,21 @@ static bool is_iter_destroy_kfunc(struct bpf_call_arg_meta *meta) return meta->kfunc_flags & KF_ITER_DESTROY; } +static bool iter_next_borrows_struct(struct bpf_call_arg_meta *meta) +{ + const struct btf_type *t; + + if (!(meta->kfunc_flags & KF_ITER_NEXT) || + (meta->kfunc_flags & (KF_ITER_RET_INDEPENDENT | KF_ACQUIRE))) + return false; + + t = btf_type_skip_modifiers(meta->btf, meta->func_proto->type, NULL); + if (!t || !btf_type_is_ptr(t)) + return false; + t = btf_type_skip_modifiers(meta->btf, t->type, NULL); + return t && __btf_type_is_struct(t); +} + static bool is_kfunc_arg_iter(struct bpf_call_arg_meta *meta, int arg_idx, const struct btf_param *arg) { @@ -7840,7 +7952,14 @@ static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state * /* remember meta->iter info for process_iter_next_call() */ meta->iter.spi = spi; meta->iter.frameno = reg->frameno; - update_ref_obj(&meta->ref_obj, &state->stack[spi].spilled_ptr); + update_ref_obj(&meta->ref_obj, &bpf_stack_slot(state, spi)->spilled_ptr); + + /* The iterator stays. What was borrowed from the previous element goes. */ + if (iter_next_borrows_struct(meta)) { + err = invalidate_reference(env, meta->ref_obj.id); + if (err) + return err; + } if (is_iter_destroy_kfunc(meta)) { err = unmark_stack_slots_iter(env, reg, nr_slots); @@ -7917,16 +8036,15 @@ static int widen_imprecise_scalars(struct bpf_verifier_env *env, &fold->regs[i], &fcur->regs[i]); - num_slots = min(fold->allocated_stack / BPF_REG_SIZE, - fcur->allocated_stack / BPF_REG_SIZE); + num_slots = min(bpf_stack_nr_slots(fold), bpf_stack_nr_slots(fcur)); for (i = 0; i < num_slots; i++) { - if (!bpf_is_spilled_reg(&fold->stack[i]) || - !bpf_is_spilled_reg(&fcur->stack[i])) + struct bpf_stack_state *old_ss = bpf_stack_slot(fold, i); + struct bpf_stack_state *cur_ss = bpf_stack_slot(fcur, i); + + if (!bpf_is_spilled_reg(old_ss) || !bpf_is_spilled_reg(cur_ss)) continue; - maybe_widen_reg(env, - &fold->stack[i].spilled_ptr, - &fcur->stack[i].spilled_ptr); + maybe_widen_reg(env, &old_ss->spilled_ptr, &cur_ss->spilled_ptr); } } return 0; @@ -7938,7 +8056,7 @@ static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_ int iter_frameno = meta->iter.frameno; int iter_spi = meta->iter.spi; - return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; + return &bpf_stack_slot(cur_st->frame[iter_frameno], iter_spi)->spilled_ptr; } /* process_iter_next_call() is called when verifier gets to iterator's next @@ -8641,6 +8759,7 @@ static int get_constant_map_key(struct bpf_verifier_env *env, s64 *value) { struct bpf_func_state *state = bpf_func(env, key); + struct bpf_stack_state *ss; struct bpf_reg_state *reg; int slot, spi, off; int spill_size = 0; @@ -8660,7 +8779,8 @@ static int get_constant_map_key(struct bpf_verifier_env *env, slot = -stack_off - 1; spi = slot / BPF_REG_SIZE; off = slot % BPF_REG_SIZE; - stype = state->stack[spi].slot_type; + ss = bpf_stack_slot(state, spi); + stype = ss->slot_type; /* First handle precisely tracked STACK_ZERO */ for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--) @@ -8671,14 +8791,14 @@ static int get_constant_map_key(struct bpf_verifier_env *env, } /* Check that stack contains a scalar spill of expected size */ - if (!bpf_is_spilled_scalar_reg(&state->stack[spi])) + if (!bpf_is_spilled_scalar_reg(ss)) return -EOPNOTSUPP; for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--) spill_size++; if (spill_size != key_size) return -EOPNOTSUPP; - reg = &state->stack[spi].spilled_ptr; + reg = &ss->spilled_ptr; if (!tnum_is_const(reg->var_off)) /* Stack value not statically known */ return -EOPNOTSUPP; @@ -9004,12 +9124,71 @@ bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env) bpf_jit_supports_subprog_tailcalls(); } +/* + * Is rcu_read_lock_held() true at run time? Unlike for in_rcu_cs(), disabled + * preemption or interrupts will not do. + */ +static bool has_rcu_read_lock(struct bpf_verifier_env *env) +{ + struct bpf_verifier_state *state = env->cur_state; + + if (state->active_rcu_locks || in_rcu_callback(env)) + return true; + if (in_sleepable(env)) + return false; + return !env->no_rcu_read_lock || state->frame[0]->in_async_callback_fn; +} + +/* May the map be used outside of an RCU read side critical section? */ +static bool map_needs_no_rcu(const struct bpf_map *map) +{ + switch (map->map_type) { + case BPF_MAP_TYPE_HASH: + case BPF_MAP_TYPE_RHASH: + case BPF_MAP_TYPE_LRU_HASH: + case BPF_MAP_TYPE_ARRAY: + case BPF_MAP_TYPE_PERCPU_HASH: + case BPF_MAP_TYPE_PERCPU_ARRAY: + case BPF_MAP_TYPE_LRU_PERCPU_HASH: + case BPF_MAP_TYPE_LPM_TRIE: + case BPF_MAP_TYPE_ARRAY_OF_MAPS: + case BPF_MAP_TYPE_HASH_OF_MAPS: + case BPF_MAP_TYPE_RINGBUF: + case BPF_MAP_TYPE_USER_RINGBUF: + case BPF_MAP_TYPE_INODE_STORAGE: + case BPF_MAP_TYPE_SK_STORAGE: + case BPF_MAP_TYPE_TASK_STORAGE: + case BPF_MAP_TYPE_CGRP_STORAGE: + case BPF_MAP_TYPE_QUEUE: + case BPF_MAP_TYPE_STACK: + case BPF_MAP_TYPE_ARENA: + case BPF_MAP_TYPE_INSN_ARRAY: + case BPF_MAP_TYPE_PROG_ARRAY: + case BPF_MAP_TYPE_BLOOM_FILTER: + return true; + default: + return false; + } +} + static int check_map_func_compatibility(struct bpf_verifier_env *env, struct bpf_map *map, int func_id) { if (!map) return 0; + /* + * check_map_prog_compatibility() asks the program. That misses the + * sleepable callback of another program, and an inner map. They may + * use any map under the RCU read lock. Disabled preemption or + * interrupts will not do: the maps ask for rcu_read_lock_held(). + */ + if (!has_rcu_read_lock(env) && !map_needs_no_rcu(map)) { + verbose(env, "map '%s' needs bpf_rcu_read_lock() in sleepable context\n", + map->name); + return -EINVAL; + } + /* We need a two way check, first is from map perspective ... */ switch (map->map_type) { case BPF_MAP_TYPE_PROG_ARRAY: @@ -9470,8 +9649,8 @@ static int idstack_pop(struct bpf_idmap *idmap) return idmap->map[--idmap->cnt].old; } -/* Release id and objects derived from it iteratively in a DFS manner */ -static int release_reference(struct bpf_verifier_env *env, int id) +/* Invalidate id and objects derived from it iteratively in a DFS manner */ +static int invalidate_reference(struct bpf_verifier_env *env, int id) { u32 mask = (1 << STACK_SPILL) | (1 << STACK_DYNPTR); struct bpf_verifier_state *vstate = env->cur_state; @@ -9486,11 +9665,6 @@ static int release_reference(struct bpf_verifier_env *env, int id) if (err) return err; - if (find_reference_state(vstate, id)) { - err = release_reference_nomark(env, id); - WARN_ON_ONCE(err); - } - while ((id = idstack_pop(idstack))) { /* * Child references are inaccessible after parent is released, @@ -9542,6 +9716,14 @@ static int release_reference(struct bpf_verifier_env *env, int id) return 0; } +static int release_reference(struct bpf_verifier_env *env, int id) +{ + if (find_reference_state(env->cur_state, id)) + WARN_ON_ONCE(release_reference_nomark(env, id)); + + return invalidate_reference(env, id); +} + static void invalidate_non_owning_refs(struct bpf_verifier_env *env) { struct bpf_func_state *unused; @@ -9863,6 +10045,10 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins err = btf_check_subprog_call(env, subprog, caller->regs); if (err == -EFAULT) return err; + if (bpf_in_stack_arg_cnt(&env->subprog_info[subprog])) { + verbose(env, "callback subprog cannot have stack args\n"); + return -EINVAL; + } /* set_callee_state is used for direct subprog calls, but we are * interested in validating only BPF helpers that can call subprogs as @@ -9891,8 +10077,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); @@ -9958,11 +10146,16 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, } if (env->subprog_info[subprog].might_sleep && !in_sleepable_context(env)) { + const char *suggestion; + verbose(env, "sleepable global function %s() called in %s\n", sub_name, non_sleepable_context_description(env)); + if (in_sleepable(env)) + suggestion = "Move the call outside the critical section, or use a non-sleepable function."; + else + suggestion = "Mark the program sleepable if the program type allows it, or use a non-sleepable function."; operation = bpf_diag_fmt(env, "sleepable global function %s()", sub_name); - bpf_diag_ctx_forbidden(env, *insn_idx, operation, - "Move the call outside the critical section, or use a non-sleepable function."); + bpf_diag_ctx_forbidden(env, *insn_idx, operation, suggestion); return -EINVAL; } @@ -9975,7 +10168,12 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, if (env->log.level & BPF_LOG_LEVEL) verbose(env, "Func#%d ('%s') is global and assumed valid.\n", subprog, sub_name); - sub_aux->called[in_sleepable_context(env)] = true; + if (in_sleepable_context(env)) + sub_aux->called[BPF_FUNC_CTX_SLEEPABLE] = true; + else if (has_rcu_read_lock(env)) + sub_aux->called[BPF_FUNC_CTX_NON_SLEEPABLE] = true; + else + sub_aux->called[BPF_FUNC_CTX_NO_RCU_LOCK] = true; returns_void = subprog_returns_void(env, subprog); if (env->subprog_info[subprog].changes_pkt_data) clear_all_pkt_pointers(env); @@ -10105,6 +10303,19 @@ static int set_map_elem_callback_state(struct bpf_verifier_env *env, if (err) return err; + switch (map->map_type) { + case BPF_MAP_TYPE_HASH: + case BPF_MAP_TYPE_PERCPU_HASH: + case BPF_MAP_TYPE_LRU_HASH: + case BPF_MAP_TYPE_LRU_PERCPU_HASH: + case BPF_MAP_TYPE_RHASH: + /* Hash tables run the callback under rcu_read_lock(). */ + callee->in_rcu_callback_fn = true; + break; + default: + break; + } + callee->in_callback_fn = true; callee->callback_ret_range = retval_range(0, 1); return 0; @@ -10191,6 +10402,8 @@ static int set_find_vma_callback_state(struct bpf_verifier_env *env, bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); callee->in_callback_fn = true; + /* bpf_find_vma() runs the callback under mmap_lock and RCU. */ + callee->in_rcu_callback_fn = true; callee->callback_ret_range = retval_range(0, 1); return 0; } @@ -10409,6 +10622,12 @@ static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) bpf_diag_mod_end(env); } + /* Invalidate callee-local dynptrs and their slices before the frame goes away. */ + err = destroy_dynptrs_in_stack_slots(env, callee, 0, + callee->allocated_stack / BPF_REG_SIZE - 1); + if (err) + return err; + /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, * there function call logic would reschedule callback visit. If iteration * converges is_state_visited() would prune that visit eventually. @@ -10796,22 +11015,37 @@ int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id, return *ptr && (*ptr)->func ? 0 : -EINVAL; } +/* Is any frame on the current path a callback that runs under RCU? */ +static bool in_rcu_callback(struct bpf_verifier_env *env) +{ + struct bpf_verifier_state *state = env->cur_state; + int i; + + for (i = 0; i <= state->curframe; i++) + if (state->frame[i]->in_rcu_callback_fn) + return true; + return false; +} + /* Check if we're in a sleepable context. */ static inline bool in_sleepable_context(struct bpf_verifier_env *env) { - return !in_rcu_cs(env); + return !in_rcu_cs(env) && !in_rcu_callback(env); } static const char *non_sleepable_context_description(struct bpf_verifier_env *env) { - if (env->cur_state->active_rcu_locks) - return "rcu_read_lock region"; - if (env->cur_state->active_preempt_locks) - return "non-preemptible region"; - if (env->cur_state->active_irq_id) - return "IRQ-disabled region"; - if (env->cur_state->active_locks) - return "lock region"; + if (in_sleepable(env)) { + if (env->cur_state->active_rcu_locks) + return "rcu_read_lock region"; + if (env->cur_state->active_preempt_locks) + return "non-preemptible region"; + if (env->cur_state->active_irq_id) + return "IRQ-disabled region"; + if (env->cur_state->active_locks) + return "lock region"; + return "callback running under rcu_read_lock"; + } return "non-sleepable prog"; } @@ -10903,12 +11137,17 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn } if (fn->might_sleep && !in_sleepable_context(env)) { + const char *suggestion; + verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id, non_sleepable_context_description(env)); + if (in_sleepable(env)) + suggestion = "Move the helper call outside the critical section, or use a non-sleepable helper."; + else + suggestion = "Mark the program sleepable if the program type allows it, or use a non-sleepable helper."; operation = bpf_diag_fmt(env, "sleepable helper %s#%d", func_id_name(func_id), func_id); - bpf_diag_ctx_forbidden(env, insn_idx, operation, - "Move the helper call outside the critical section, or use a non-sleepable helper."); + bpf_diag_ctx_forbidden(env, insn_idx, operation, suggestion); return -EINVAL; } @@ -13574,13 +13813,14 @@ s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn * goto out; } - /* ptr + __sz/__szk pair: size is in the next register */ + /* ptr + __sz/__szk pair: the size follows the pointer */ if (arg + 1 < nargs && (btf_param_match_suffix(btf, &args[arg + 1], "__sz") || btf_param_match_suffix(btf, &args[arg + 1], "__szk"))) { int size_reg = BPF_REG_1 + arg + 1; - if (aux->const_reg_mask & BIT(size_reg)) { + if (size_reg <= MAX_BPF_FUNC_REG_ARGS && + (aux->const_reg_mask & BIT(size_reg))) { size = (s64)aux->const_reg_vals[size_reg]; goto out; } @@ -13872,11 +14112,20 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, } sleepable = bpf_is_kfunc_sleepable(&meta); - if (sleepable && !in_sleepable(env)) { - verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); + if (sleepable && !in_sleepable_context(env)) { + const char *suggestion; + + if (in_sleepable(env)) { + verbose(env, "kernel func %s is sleepable within %s\n", + func_name, non_sleepable_context_description(env)); + suggestion = "Move the kfunc call outside the critical section, or use a non-sleepable kfunc."; + } else { + verbose(env, "program must be sleepable to call sleepable kfunc %s\n", + func_name); + suggestion = "Mark the program sleepable if the program type allows it, or use a non-sleepable kfunc."; + } operation = bpf_diag_fmt(env, "sleepable kfunc %s", func_name); - bpf_diag_ctx_forbidden(env, insn_idx, operation, - "Mark the program sleepable if the program type allows it, or use a non-sleepable kfunc."); + bpf_diag_ctx_forbidden(env, insn_idx, operation, suggestion); return -EACCES; } @@ -13976,15 +14225,6 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, invalidate_rcu_protected_refs(env); } - if (sleepable && !in_sleepable_context(env)) { - verbose(env, "kernel func %s is sleepable within %s\n", - func_name, non_sleepable_context_description(env)); - operation = bpf_diag_fmt(env, "sleepable kfunc %s", func_name); - bpf_diag_ctx_forbidden(env, insn_idx, operation, - "Move the kfunc call outside the critical section, or use a non-sleepable kfunc."); - return -EACCES; - } - if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); return -EACCES; @@ -14142,6 +14382,8 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, regs[BPF_REG_0].btf = desc_btf; regs[BPF_REG_0].type = type; regs[BPF_REG_0].btf_id = ptr_type_id; + if (iter_next_borrows_struct(&meta) && !(type & MEM_RCU)) + regs[BPF_REG_0].parent_id = meta.ref_obj.id; } if (is_kfunc_ret_null(&meta)) { @@ -16607,7 +16849,7 @@ static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor * bit 1 is set, which we can readily use in adjustments. */ - if (!is_power_of_2(val)) + if (hweight64(val) != 1) break; if (is_jmp32) { t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); @@ -16893,10 +17135,12 @@ static void collect_linked_regs(struct bpf_verifier_env *env, reg = &func->regs[j]; __collect_linked_regs(linked_regs, reg, id, i, j, true); } - for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { - if (!bpf_is_spilled_reg(&func->stack[j])) + for (j = 0; j < bpf_stack_nr_slots(func); j++) { + struct bpf_stack_state *ss = bpf_stack_slot(func, j); + + if (!bpf_is_spilled_reg(ss)) continue; - reg = &func->stack[j].spilled_ptr; + reg = &ss->spilled_ptr; __collect_linked_regs(linked_regs, reg, id, i, j, false); } } @@ -16916,7 +17160,7 @@ static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_s for (i = 0; i < linked_regs->cnt; ++i) { e = &linked_regs->entries[i]; reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] - : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; + : &bpf_stack_slot(vstate->frame[e->frameno], e->spi)->spilled_ptr; if (reg->type != SCALAR_VALUE || reg == known_reg) continue; if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) @@ -18872,35 +19116,11 @@ static int check_map_prog_compatibility(struct bpf_verifier_env *env, return -EINVAL; } - if (prog->sleepable) - switch (map->map_type) { - case BPF_MAP_TYPE_HASH: - case BPF_MAP_TYPE_RHASH: - case BPF_MAP_TYPE_LRU_HASH: - case BPF_MAP_TYPE_ARRAY: - case BPF_MAP_TYPE_PERCPU_HASH: - case BPF_MAP_TYPE_PERCPU_ARRAY: - case BPF_MAP_TYPE_LRU_PERCPU_HASH: - case BPF_MAP_TYPE_LPM_TRIE: - case BPF_MAP_TYPE_ARRAY_OF_MAPS: - case BPF_MAP_TYPE_HASH_OF_MAPS: - case BPF_MAP_TYPE_RINGBUF: - case BPF_MAP_TYPE_USER_RINGBUF: - case BPF_MAP_TYPE_INODE_STORAGE: - case BPF_MAP_TYPE_SK_STORAGE: - case BPF_MAP_TYPE_TASK_STORAGE: - case BPF_MAP_TYPE_CGRP_STORAGE: - case BPF_MAP_TYPE_QUEUE: - case BPF_MAP_TYPE_STACK: - case BPF_MAP_TYPE_ARENA: - case BPF_MAP_TYPE_INSN_ARRAY: - case BPF_MAP_TYPE_PROG_ARRAY: - break; - default: - verbose(env, - "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); - return -EINVAL; - } + if (prog->sleepable && !map_needs_no_rcu(map)) { + verbose(env, + "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); + return -EINVAL; + } if (bpf_map_is_cgroup_storage(map) && bpf_cgroup_storage_assign(env->prog->aux, map)) { @@ -18961,7 +19181,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, @@ -19488,7 +19708,8 @@ static void free_states(struct bpf_verifier_env *env) } } -static int do_check_common(struct bpf_verifier_env *env, int subprog, bool is_sleepable) +static int do_check_common(struct bpf_verifier_env *env, int subprog, + enum bpf_func_context context) { bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); struct bpf_subprog_info *sub = subprog_info(env, subprog); @@ -19508,7 +19729,8 @@ static int do_check_common(struct bpf_verifier_env *env, int subprog, bool is_sl state->curframe = 0; state->speculative = false; state->branches = 1; - state->in_sleepable = is_sleepable; + state->in_sleepable = context == BPF_FUNC_CTX_SLEEPABLE; + env->no_rcu_read_lock = context == BPF_FUNC_CTX_NO_RCU_LOCK; state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT); if (!state->frame[0]) { kfree(state); @@ -19565,8 +19787,12 @@ static int do_check_common(struct bpf_verifier_env *env, int subprog, bool is_sl reg->type = SCALAR_VALUE; mark_reg_unknown(env, regs, i); } else if (arg->arg_type == ARG_PTR_TO_DYNPTR) { - /* assume unspecial LOCAL dynptr type */ - __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen, 0); + /* + * 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, 0); } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { reg->type = PTR_TO_MEM; reg->type |= arg->arg_type & @@ -19722,7 +19948,7 @@ static int do_check_subprogs(struct bpf_verifier_env *env) /* * We can't loop forever as each pass verifies at least one new context, - * and there are only two contexts per global subprog. + * and there are only three contexts per global subprog. */ if (new_cnt) goto again; @@ -20195,6 +20421,15 @@ int bpf_check_attach_target(struct bpf_verifier_log *log, "Extension programs should be JITed\n"); return -EINVAL; } + /* + * How much of the buffer of the tracepoint is used + * is checked for the program that is attached to it. + */ + if (tgt_prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE) { + bpf_log(log, + "Cannot extend a writable raw tracepoint program\n"); + return -EINVAL; + } tgt_changes_pkt_data = aux->func ? aux->func[subprog]->aux->changes_pkt_data : aux->changes_pkt_data; @@ -21540,6 +21775,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, vfree(env->insn_aux_data); kvfree(env->fd_array); bpf_stack_liveness_free(env); + kvfree(env->cfg.postorder_nums); kvfree(env->cfg.insn_postorder); kvfree(env->scc_info); kvfree(env->succ); diff --git a/kernel/cgroup/cgroup-internal.h b/kernel/cgroup/cgroup-internal.h index 58797123b752..f2684f9f8e0a 100644 --- a/kernel/cgroup/cgroup-internal.h +++ b/kernel/cgroup/cgroup-internal.h @@ -254,7 +254,7 @@ void cgroup_procs_write_finish(struct task_struct *task, enum cgroup_attach_lock_mode lock_mode) __releases(&cgroup_threadgroup_rwsem); -void cgroup_lock_and_drain_offline(struct cgroup *cgrp); +int cgroup_lock_and_drain_offline(struct cgroup *cgrp); int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode); int cgroup_rmdir(struct kernfs_node *kn); diff --git a/kernel/cgroup/cgroup-v1.c b/kernel/cgroup/cgroup-v1.c index a4337c9b5287..167bf6555a49 100644 --- a/kernel/cgroup/cgroup-v1.c +++ b/kernel/cgroup/cgroup-v1.c @@ -506,8 +506,8 @@ static ssize_t __cgroup1_procs_write(struct kernfs_open_file *of, enum cgroup_attach_lock_mode lock_mode; cgrp = cgroup_kn_lock_live(of->kn, false); - if (!cgrp) - return -ENODEV; + if (IS_ERR(cgrp)) + return PTR_ERR(cgrp); task = cgroup_procs_write_start(buf, threadgroup, &lock_mode); ret = PTR_ERR_OR_ZERO(task); @@ -569,8 +569,8 @@ static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of, return -EPERM; cgrp = cgroup_kn_lock_live(of->kn, false); - if (!cgrp) - return -ENODEV; + if (IS_ERR(cgrp)) + return PTR_ERR(cgrp); spin_lock(&release_agent_path_lock); strscpy(cgrp->root->release_agent_path, strstrip(buf), sizeof(cgrp->root->release_agent_path)); @@ -1097,7 +1097,9 @@ int cgroup1_reconfigure(struct fs_context *fc) int ret = 0; u32 added_mask, removed_mask; - cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp); + ret = cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp); + if (unlikely(ret)) + return ret; /* See what subsystems are wanted */ ret = check_cgroupfs_options(fc); @@ -1262,7 +1264,9 @@ int cgroup1_get_tree(struct fs_context *fc) if (!ns_capable(ctx->ns->user_ns, CAP_SYS_ADMIN)) return -EPERM; - cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp); + ret = cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp); + if (unlikely(ret)) + return ret; ret = cgroup1_root_to_use(fc); if (!ret && !percpu_ref_tryget_live(&ctx->root->cgrp.self.refcnt)) diff --git a/kernel/cgroup/cgroup.c b/kernel/cgroup/cgroup.c index 2d582603a711..37be027ce140 100644 --- a/kernel/cgroup/cgroup.c +++ b/kernel/cgroup/cgroup.c @@ -1379,7 +1379,10 @@ static void cgroup_destroy_root(struct cgroup_root *root) trace_cgroup_destroy_root(root); - cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp); + /* runs off a workqueue, no signal can interrupt the drain */ + ret = cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp); + if (WARN_ON_ONCE(ret)) + cgroup_lock(); BUG_ON(atomic_read(&root->nr_cgrps)); BUG_ON(!list_empty(&cgrp->self.children)); @@ -1685,9 +1688,10 @@ void cgroup_kn_unlock(struct kernfs_node *kn) * This helper is to be used by a cgroup kernfs method currently servicing * @kn. It breaks the active protection, performs cgroup locking and * verifies that the associated cgroup is alive. Returns the cgroup if - * alive; otherwise, %NULL. A successful return should be undone by a - * matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the - * cgroup is drained of offlining csses before return. + * alive; otherwise, an ERR_PTR value. A successful return should be undone by + * a matching cgroup_kn_unlock() invocation. If @drain_offline is %true, the + * cgroup is drained of offlining csses before return, and an interrupted drain + * fails with -ERESTARTSYS. * * Any cgroup kernfs method implementation which requires locking the * associated cgroup should use this helper. It avoids nesting cgroup @@ -1697,6 +1701,7 @@ void cgroup_kn_unlock(struct kernfs_node *kn) struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline) { struct cgroup *cgrp; + int ret; if (kernfs_type(kn) == KERNFS_DIR) cgrp = kn->priv; @@ -1710,19 +1715,25 @@ struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline) * break the active_ref protection. */ if (!cgroup_tryget(cgrp)) - return NULL; + return ERR_PTR(-ENODEV); kernfs_break_active_protection(kn); - if (drain_offline) - cgroup_lock_and_drain_offline(cgrp); - else + if (drain_offline) { + ret = cgroup_lock_and_drain_offline(cgrp); + if (unlikely(ret)) { + kernfs_unbreak_active_protection(kn); + cgroup_put(cgrp); + return ERR_PTR(ret); + } + } else { cgroup_lock(); + } if (!cgroup_is_dead(cgrp)) return cgrp; cgroup_kn_unlock(kn); - return NULL; + return ERR_PTR(-ENODEV); } static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft) @@ -3320,16 +3331,20 @@ static int cgroup_update_dfl_csses(struct cgroup *cgrp) * @cgrp: root of the target subtree * * Because css offlining is asynchronous, userland may try to re-enable a - * controller while the previous css is still around. This function grabs - * cgroup_mutex and drains the previous css instances of @cgrp's subtree. + * controller while the previous css is still around. This function grabs + * cgroup_mutex and waits until no css in @cgrp's subtree is dying. A dying css + * offlines only after every task that still pins it has finished exiting, which + * can take arbitrarily long, so the wait is interruptible. + * + * Returns 0 with cgroup_mutex held once the subtree is drained, or -ERESTARTSYS + * without it if interrupted by a signal. */ -void cgroup_lock_and_drain_offline(struct cgroup *cgrp) - __acquires(&cgroup_mutex) +int cgroup_lock_and_drain_offline(struct cgroup *cgrp) { struct cgroup *dsct; struct cgroup_subsys_state *d_css; struct cgroup_subsys *ss; - int ssid; + int ssid, ret; restart: cgroup_lock(); @@ -3343,17 +3358,20 @@ void cgroup_lock_and_drain_offline(struct cgroup *cgrp) continue; cgroup_get_live(dsct); - prepare_to_wait(&dsct->offline_waitq, &wait, - TASK_UNINTERRUPTIBLE); - + ret = prepare_to_wait_event(&dsct->offline_waitq, &wait, + TASK_INTERRUPTIBLE); cgroup_unlock(); - schedule(); + if (!ret) + schedule(); finish_wait(&dsct->offline_waitq, &wait); - cgroup_put(dsct); + if (unlikely(ret)) + return ret; goto restart; } } + + return 0; } /** @@ -3650,8 +3668,8 @@ static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of, } cgrp = cgroup_kn_lock_live(of->kn, true); - if (!cgrp) - return -ENODEV; + if (IS_ERR(cgrp)) + return PTR_ERR(cgrp); for_each_subsys(ss, ssid) { if (enable & (1 << ssid)) { @@ -3790,8 +3808,8 @@ static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf, /* drain dying csses before we re-apply (threaded) subtree control */ cgrp = cgroup_kn_lock_live(of->kn, true); - if (!cgrp) - return -ENOENT; + if (IS_ERR(cgrp)) + return PTR_ERR(cgrp); /* threaded can only be enabled */ ret = cgroup_enable_threaded(cgrp); @@ -3833,8 +3851,8 @@ static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of, return -ERANGE; cgrp = cgroup_kn_lock_live(of->kn, false); - if (!cgrp) - return -ENOENT; + if (IS_ERR(cgrp)) + return PTR_ERR(cgrp); WRITE_ONCE(cgrp->max_descendants, descendants); @@ -3876,8 +3894,8 @@ static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of, return -ERANGE; cgrp = cgroup_kn_lock_live(of->kn, false); - if (!cgrp) - return -ENOENT; + if (IS_ERR(cgrp)) + return PTR_ERR(cgrp); WRITE_ONCE(cgrp->max_depth, depth); @@ -4075,8 +4093,8 @@ static ssize_t pressure_write(struct kernfs_open_file *of, char *buf, ssize_t ret = 0; cgrp = cgroup_kn_lock_live(of->kn, false); - if (!cgrp) - return -ENODEV; + if (IS_ERR(cgrp)) + return PTR_ERR(cgrp); ctx = of->priv; if (!ctx) { @@ -4192,8 +4210,8 @@ static ssize_t cgroup_pressure_write(struct kernfs_open_file *of, return -ERANGE; cgrp = cgroup_kn_lock_live(of->kn, false); - if (!cgrp) - return -ENOENT; + if (IS_ERR(cgrp)) + return PTR_ERR(cgrp); psi = cgroup_psi(cgrp); if (psi->enabled != enable) { @@ -4268,8 +4286,8 @@ static ssize_t cgroup_freeze_write(struct kernfs_open_file *of, return -ERANGE; cgrp = cgroup_kn_lock_live(of->kn, false); - if (!cgrp) - return -ENOENT; + if (IS_ERR(cgrp)) + return PTR_ERR(cgrp); cgroup_freeze(cgrp, freeze); @@ -4330,8 +4348,8 @@ static ssize_t cgroup_kill_write(struct kernfs_open_file *of, char *buf, return -ERANGE; cgrp = cgroup_kn_lock_live(of->kn, false); - if (!cgrp) - return -ENOENT; + if (IS_ERR(cgrp)) + return PTR_ERR(cgrp); /* * Killing is a process directed operation, i.e. the whole thread-group @@ -5488,8 +5506,8 @@ static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf, enum cgroup_attach_lock_mode lock_mode; dst_cgrp = cgroup_kn_lock_live(of->kn, false); - if (!dst_cgrp) - return -ENODEV; + if (IS_ERR(dst_cgrp)) + return PTR_ERR(dst_cgrp); task = cgroup_procs_write_start(buf, threadgroup, &lock_mode); ret = PTR_ERR_OR_ZERO(task); @@ -6123,8 +6141,8 @@ int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode) return -EINVAL; parent = cgroup_kn_lock_live(parent_kn, false); - if (!parent) - return -ENODEV; + if (IS_ERR(parent)) + return PTR_ERR(parent); if (!cgroup_check_hierarchy_limits(parent)) { ret = -EAGAIN; @@ -6400,7 +6418,7 @@ int cgroup_rmdir(struct kernfs_node *kn) int ret = 0; cgrp = cgroup_kn_lock_live(kn, false); - if (!cgrp) + if (IS_ERR(cgrp)) return 0; ret = cgroup_destroy_locked(cgrp); diff --git a/kernel/cgroup/cpuset-internal.h b/kernel/cgroup/cpuset-internal.h index e7d010661fd3..33990902cdc8 100644 --- a/kernel/cgroup/cpuset-internal.h +++ b/kernel/cgroup/cpuset-internal.h @@ -35,6 +35,7 @@ enum prs_errcode { PERR_HKEEPING, PERR_ACCESS, PERR_REMOTE, + PERR_ISOPARENT, }; /* bits in struct cpuset flags field */ @@ -160,6 +161,11 @@ struct cpuset { */ bool remote_partition; + /* + * 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 86b5921998af..6f336ace3033 100644 --- a/kernel/cgroup/cpuset.c +++ b/kernel/cgroup/cpuset.c @@ -60,6 +60,7 @@ static const char * const perr_strings[] = { [PERR_HKEEPING] = "partition config conflicts with housekeeping setup", [PERR_ACCESS] = "Enable partition not permitted", [PERR_REMOTE] = "Have remote partition underneath", + [PERR_ISOPARENT] = "Root partition is not allowed with isolated parent", }; /* @@ -254,15 +255,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. */ @@ -792,8 +784,8 @@ static int validate_change(struct cpuset *cur, struct cpuset *trial) * For v1, effective_cpus == cpus_allowed & user_xcpus() returns * cpus_allowed. * - * For v2, is_cpu_exclusive() & is_sched_load_balance() are true only - * for non-isolated partition root. At this point, the target + * For v2, is_partition_valid(cur) & is_sched_load_balance() are true + * only for non-isolated partition root. At this point, the target * effective_cpus isn't computed yet. user_xcpus() is the best * approximation. * @@ -802,7 +794,8 @@ static int validate_change(struct cpuset *cur, struct cpuset *trial) * becomes an issue. */ ret = -EBUSY; - if (is_cpu_exclusive(cur) && is_sched_load_balance(cur) && + if ((is_partition_valid(cur) || (!cpuset_v2() && is_cpu_exclusive(cur))) && + is_sched_load_balance(cur) && !cpuset_cpumask_can_shrink(cur->effective_cpus, user_xcpus(trial))) goto out; @@ -1280,6 +1273,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 cs->remote_partition; +} + +static inline bool is_local_partition(struct cpuset *cs) +{ + return is_partition_valid(cs) && !is_remote_partition(cs); +} + /* Return true if isolated_cpus changes. */ static bool isolated_cpu_update(int new_prs, int cpu) { @@ -1322,6 +1325,45 @@ static void isolated_cpus_update(int old_prs, int new_prs, struct cpumask *xcpus update_housekeeping = true; } +/* + * 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 @@ -1377,65 +1419,98 @@ static void 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 HK_TYPE_DOMAIN_BOOT. + * 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; - if (del_cpus && cpumask_weight_and(del_cpus, - housekeeping_cpumask(HK_TYPE_KERNEL_NOISE))) + /* + * 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 (housekeeping_enabled(HK_TYPE_DOMAIN_BOOT) && (new_prs == PRS_ROOT) && + !cpumask_subset(new_cpus, housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT))) 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), + housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT)); + 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 HK_TYPE_DOMAIN_BOOT, if defined, can only be used in an - * isolated partition. - */ -static bool prstate_housekeeping_conflict(int prstate, struct cpumask *new_cpus) -{ - if (!housekeeping_enabled(HK_TYPE_DOMAIN_BOOT)) - return false; - - if ((prstate != PRS_ISOLATED) && - !cpumask_subset(new_cpus, housekeeping_cpumask(HK_TYPE_DOMAIN_BOOT))) - return true; - - return false; -} - /* * cpuset_update_sd_hk_unlock - Rebuild sched domains, update HK & unlock * @@ -1572,16 +1647,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 cs->remote_partition; -} - -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 @@ -1617,9 +1682,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); @@ -1721,13 +1784,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) partition_xcpus_add(prs, NULL, tmp->addmask); @@ -1749,6 +1813,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: @@ -1759,7 +1824,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 * @@ -1774,11 +1839,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. * @@ -1801,7 +1866,6 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd, int deleting; /* Deleting cpus from parent's effective_cpus */ int old_prs, new_prs; int part_error = PERR_NONE; /* Partition error? */ - struct cpumask *xcpus = user_xcpus(cs); int parent_prs = parent->partition_root_state; bool nocpu; @@ -1844,34 +1908,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)) + if (prstate_housekeeping_conflict(new_prs, parent_prs, tmp->delmask, NULL)) return PERR_HKEEPING; - if ((new_prs == PRS_ISOLATED) && (new_prs != parent_prs) && - !isolated_cpus_can_update(xcpus, NULL)) - return PERR_HKEEPING; - - if (tasks_nocpu_error(parent, cs, xcpus)) + if (nocpu) return PERR_NOCPUS; /* @@ -1883,16 +1943,14 @@ 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; } 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); @@ -1907,9 +1965,13 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd, part_error = PERR_CPUSEMPTY; goto write_error; } + if ((parent_prs == PRS_ISOLATED) && (old_prs == -PRS_ROOT)) { + part_error = PERR_ISOPARENT; + 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: @@ -1940,22 +2002,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. @@ -1980,7 +2026,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() @@ -1991,39 +2037,72 @@ 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, cs->effective_xcpus, parent->effective_xcpus); - } else if (is_partition_invalid(cs) && !cpumask_empty(xcpus) && - cpumask_subset(xcpus, parent->effective_xcpus)) { + } else if ((parent_prs == PRS_ISOLATED) && + ((old_prs == PRS_ROOT) || (old_prs == -PRS_ROOT))) { + part_error = PERR_ISOPARENT; + if (old_prs == PRS_ROOT) { + cpumask_copy(tmp->addmask, cs->effective_xcpus); + adding = true; + } + } 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: @@ -2120,8 +2199,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) @@ -2130,16 +2207,19 @@ static void compute_partition_effective_cpumask(struct cpuset *cs, struct cpuset *child; bool populated = partition_is_populated(cs, NULL); + 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) { @@ -2151,22 +2231,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; spin_unlock_irq(&callback_lock); notify_partition_change(child, old_prs); continue; @@ -2206,16 +2284,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; } @@ -2269,7 +2350,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; @@ -2277,12 +2360,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); @@ -2297,10 +2388,16 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp, if (update_parent) { update_parent_effective_cpumask(cp, partcmd_update, NULL, tmp); /* - * The cpuset partition_root_state may become - * invalid. Capture it. + * Capture current partition_root_state as it may have + * changed. Recompute effective cpumask if changed. */ new_prs = cp->partition_root_state; + if (new_prs != old_prs) { + if (new_prs > 0) + compute_partition_effective_cpumask(cp, tmp->new_cpus); + else + compute_effective_cpumask(tmp->new_cpus, cp, parent); + } } spin_lock_irq(&callback_lock); @@ -2433,10 +2530,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; @@ -2453,14 +2546,36 @@ static enum prs_errcode validate_partition(struct cpuset *cs, struct cpuset *tri * 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; @@ -2816,6 +2931,8 @@ static void update_nodemasks_hier(struct cpuset *cs, nodemask_t *new_mems) continue; rcu_read_unlock(); + check_insane_mems_config(new_mems); + spin_lock_irq(&callback_lock); cp->effective_mems = *new_mems; spin_unlock_irq(&callback_lock); @@ -2869,8 +2986,6 @@ static int update_nodemask(struct cpuset *cs, struct cpuset *trialcs, if (retval < 0) return retval; - check_insane_mems_config(&trialcs->mems_allowed); - spin_lock_irq(&callback_lock); cs->mems_allowed = trialcs->mems_allowed; spin_unlock_irq(&callback_lock); @@ -2957,7 +3072,9 @@ static int update_prstate(struct cpuset *cs, int new_prs) int err = PERR_NONE, old_prs = cs->partition_root_state; struct cpuset *parent = parent_cs(cs); struct tmpmasks tmpmask; + int parent_prs = parent->partition_root_state; bool isolcpus_updated = false; + bool disable_partition = false; if (old_prs == new_prs) return 0; @@ -3005,26 +3122,45 @@ static int update_prstate(struct cpuset *cs, int new_prs) enum partition_cmd cmd = (new_prs == PRS_ROOT) ? partcmd_enable : partcmd_enablei; + /* + * It is not allowed to create a root partition under + * an isolated parent partition. + */ + if ((new_prs == PRS_ROOT) && (parent_prs == PRS_ISOLATED)) { + err = PERR_ISOPARENT; + goto out; + } err = update_parent_effective_cpumask(cs, cmd, NULL, &tmpmask); } else { 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)) err = PERR_HKEEPING; - else + else if (parent_prs == PRS_ISOLATED) + err = PERR_ISOPARENT; + + if (!err) isolcpus_updated = true; + else + disable_partition = 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 @@ -3033,7 +3169,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: @@ -3055,8 +3191,8 @@ static int update_prstate(struct cpuset *cs, int new_prs) isolated_cpus_update(old_prs, new_prs, cs->effective_xcpus); spin_unlock_irq(&callback_lock); - /* 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) @@ -4017,9 +4153,12 @@ static void cpuset_hotplug_update_tasks(struct cpuset *cs, struct tmpmasks *tmp) if (partcmd >= 0) { update_parent_effective_cpumask(cs, partcmd, NULL, tmp); - if ((partcmd == partcmd_invalidate) || is_partition_valid(cs)) { + if (is_partition_valid(cs)) { compute_partition_effective_cpumask(cs, &new_cpus); cpuset_force_rebuild(); + } else if (partcmd == partcmd_invalidate) { + compute_effective_cpumask(&new_cpus, cs, parent); + cpuset_force_rebuild(); } } @@ -4336,7 +4475,7 @@ int cpuset_num_cpus(struct cgroup *cgrp) int nr = num_online_cpus(); struct cpuset *cs; - if (is_in_v2_mode()) { + if (cpuset_v2()) { guard(rcu)(); cs = css_cs(cgroup_e_css(cgrp, &cpuset_cgrp_subsys)); if (cs) @@ -4378,10 +4517,21 @@ nodemask_t cpuset_mems_allowed(struct task_struct *tsk) * @nodemask: the nodemask to be checked * * Are any of the nodes in the nodemask allowed in current->mems_allowed? + * + * A cpuset update rebinds the task's mempolicy and changes mems_allowed in + * separate steps, so retry if an update raced with the check. */ int cpuset_nodemask_valid_mems_allowed(const nodemask_t *nodemask) { - return nodes_intersects(*nodemask, current->mems_allowed); + unsigned int seq; + int ret; + + do { + seq = read_mems_allowed_begin(); + ret = nodes_intersects(*nodemask, current->mems_allowed); + } while (read_mems_allowed_retry(seq)); + + return ret; } /* diff --git a/kernel/cgroup/debug.c b/kernel/cgroup/debug.c index 883347b87842..96004cd65d09 100644 --- a/kernel/cgroup/debug.c +++ b/kernel/cgroup/debug.c @@ -45,7 +45,7 @@ static int current_css_set_read(struct seq_file *seq, void *v) struct cgroup_subsys_state *css; int i, refcnt; - if (!cgroup_kn_lock_live(of->kn, false)) + if (IS_ERR(cgroup_kn_lock_live(of->kn, false))) return -ENODEV; spin_lock_irq(&css_set_lock); @@ -206,8 +206,8 @@ static int cgroup_subsys_states_read(struct seq_file *seq, void *v) int i; cgrp = cgroup_kn_lock_live(of->kn, false); - if (!cgrp) - return -ENODEV; + if (IS_ERR(cgrp)) + return PTR_ERR(cgrp); for_each_subsys(ss, i) { css = rcu_dereference_check(cgrp->subsys[ss->id], true); @@ -254,8 +254,8 @@ static int cgroup_masks_read(struct seq_file *seq, void *v) struct cgroup *cgrp; cgrp = cgroup_kn_lock_live(of->kn, false); - if (!cgrp) - return -ENODEV; + if (IS_ERR(cgrp)) + return PTR_ERR(cgrp); cgroup_masks_read_one(seq, "subtree_control", cgrp->subtree_control); cgroup_masks_read_one(seq, "subtree_ss_mask", cgrp->subtree_ss_mask); diff --git a/kernel/cgroup/dmem.c b/kernel/cgroup/dmem.c index 4683f3d68022..10e148d64e85 100644 --- a/kernel/cgroup/dmem.c +++ b/kernel/cgroup/dmem.c @@ -706,8 +706,8 @@ EXPORT_SYMBOL_GPL(dmem_cgroup_uncharge); * * When this function fails with -EAGAIN and @ret_limit_pool is non-null, it * will be set to the pool for which the limit is hit. This can be used for - * eviction as argument to dmem_cgroup_evict_valuable(). This reference must be freed - * with @dmem_cgroup_pool_state_put(). + * eviction as argument to dmem_cgroup_state_evict_valuable(). This reference + * must be freed with @dmem_cgroup_pool_state_put(). * * Return: 0 on success, -EAGAIN on hitting a limit, or a negative errno on failure. */ diff --git a/kernel/debug/kdb/kdb_io.c b/kernel/debug/kdb/kdb_io.c index c399f11740ef..f5b1b7d4c9c8 100644 --- a/kernel/debug/kdb/kdb_io.c +++ b/kernel/debug/kdb/kdb_io.c @@ -22,7 +22,6 @@ #include #include "kdb_private.h" -#define CMD_BUFLEN 256 char kdb_prompt_str[CMD_BUFLEN]; int kdb_trap_printk; diff --git a/kernel/debug/kdb/kdb_main.c b/kernel/debug/kdb/kdb_main.c index ddce56b47b25..40c332d2179d 100644 --- a/kernel/debug/kdb/kdb_main.c +++ b/kernel/debug/kdb/kdb_main.c @@ -338,6 +338,7 @@ static int kdb_setenv(const char *var, const char *val) } } + kfree(ep); return KDB_ENVFULL; } @@ -783,8 +784,6 @@ static int kdb_exec_defcmd(int argc, const char **argv) /* Command history */ #define KDB_CMD_HISTORY_COUNT 32 -#define CMD_BUFLEN 200 /* kdb_printf: max printline - * size == 256 */ static unsigned int cmd_head, cmd_tail; static unsigned int cmdptr; static char cmd_hist[KDB_CMD_HISTORY_COUNT][CMD_BUFLEN]; @@ -1265,8 +1264,8 @@ static int kdb_local(kdb_reason_t reason, int error, struct pt_regs *regs, do_full_getstr: /* PROMPT can only be set if we have MEM_READ permission. */ - snprintf(kdb_prompt_str, CMD_BUFLEN, kdbgetenv("PROMPT"), - raw_smp_processor_id()); + snprintf(kdb_prompt_str, CMD_BUFLEN, + kdbgetenv("PROMPT"), raw_smp_processor_id()); /* * Fetch command from keyboard diff --git a/kernel/debug/kdb/kdb_private.h b/kernel/debug/kdb/kdb_private.h index 92a28b8ab604..722e8aa50724 100644 --- a/kernel/debug/kdb/kdb_private.h +++ b/kernel/debug/kdb/kdb_private.h @@ -225,7 +225,8 @@ extern void kdb_kbd_cleanup_state(void); #define kdb_kbd_cleanup_state() #endif /* ! CONFIG_KDB_KEYBOARD */ -extern char kdb_prompt_str[]; +#define CMD_BUFLEN 256 +extern char kdb_prompt_str[CMD_BUFLEN]; #define KDB_WORD_SIZE ((int)sizeof(unsigned long)) diff --git a/kernel/dma/debug.c b/kernel/dma/debug.c index 026d50de340e..36c1f7cbb2ae 100644 --- a/kernel/dma/debug.c +++ b/kernel/dma/debug.c @@ -489,8 +489,10 @@ static int active_cacheline_insert(struct dma_debug_entry *entry, /* If the device is not writing memory then we don't have any * concerns about the cpu consuming stale data. This mitigates * legitimate usages of overlapping mappings. + * MMIO mappings are never CPU-cacheable and do not need tracking either. */ - if (entry->direction == DMA_TO_DEVICE) + if (entry->direction == DMA_TO_DEVICE || + entry->attrs & DMA_ATTR_MMIO) return 0; spin_lock_irqsave(&radix_lock, flags); @@ -519,7 +521,8 @@ static void active_cacheline_remove(struct dma_debug_entry *entry) unsigned long flags; /* ...mirror the insert case */ - if (entry->direction == DMA_TO_DEVICE) + if (entry->direction == DMA_TO_DEVICE || + entry->attrs & DMA_ATTR_MMIO) return; spin_lock_irqsave(&radix_lock, flags); diff --git a/kernel/dma/direct.c b/kernel/dma/direct.c index da665ca22d5c..a31bd3129f3f 100644 --- a/kernel/dma/direct.c +++ b/kernel/dma/direct.c @@ -179,6 +179,22 @@ 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 | __DMA_ATTR_ALLOC_CC_SHARED)) != + DMA_ATTR_NO_KERNEL_MAPPING) + return false; + if (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) { @@ -226,8 +242,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 | __DMA_ATTR_ALLOC_CC_SHARED)) == - DMA_ATTR_NO_KERNEL_MAPPING) && !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)) { @@ -374,8 +389,7 @@ void dma_direct_free(struct device *dev, size_t size, if (attrs & __DMA_ATTR_ALLOC_CC_SHARED) mark_mem_encrypted = true; - if (((attrs & (DMA_ATTR_NO_KERNEL_MAPPING | __DMA_ATTR_ALLOC_CC_SHARED)) == - DMA_ATTR_NO_KERNEL_MAPPING) && !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 9b90b6831de7..e8293a0e7945 100644 --- a/kernel/events/core.c +++ b/kernel/events/core.c @@ -5434,6 +5434,9 @@ attach_task_ctx_data(struct task_struct *task, struct kmem_cache *ctx_cache, return -ENOMEM; for (;;) { + /* Protect @old until inc_not_zero(&old->refcount) */ + guard(rcu)(); + if (try_cmpxchg(&task->perf_ctx_data, &old, cd)) { if (old) perf_free_ctx_data_rcu(old); diff --git a/kernel/fork.c b/kernel/fork.c index 48d7ca064404..ddd3dbc0850b 100644 --- a/kernel/fork.c +++ b/kernel/fork.c @@ -971,10 +971,10 @@ static struct task_struct *dup_task_struct(struct task_struct *orig, int node) dup_user_cpus_ptr(tsk, orig, node); /* - * One for the user space visible state that goes away when reaped. - * One for the scheduler. + * Nobody can keep the task while copy_process() may still fail, which + * frees it no matter what. */ - refcount_set(&tsk->rcu_users, 2); + refcount_set(&tsk->rcu_users, 0); /* One for the rcu users */ refcount_set(&tsk->usage, 1); #ifdef CONFIG_BLK_DEV_IO_TRACE @@ -2522,6 +2522,12 @@ __latent_entropy struct task_struct *copy_process( /* No more failure paths after this point. */ + /* + * One for the user space visible state that goes away when reaped. + * One for the scheduler. + */ + refcount_set(&p->rcu_users, 2); + /* * Copy seccomp details explicitly here, in case they were changed * before holding sighand lock. diff --git a/kernel/kcov.c b/kernel/kcov.c index 54eaae97bfd6..9402227bd7ba 100644 --- a/kernel/kcov.c +++ b/kernel/kcov.c @@ -198,6 +198,16 @@ static notrace unsigned long canonicalize_ip(unsigned long ip) return ip; } +#ifdef CONFIG_KCOV_SELFTEST +static unsigned long __init decanonicalize_ip(unsigned long ip) +{ +#ifdef CONFIG_RANDOMIZE_BASE + ip += kaslr_offset(); +#endif + return ip; +} +#endif + /* * Entry point from instrumented code. * This is called once per basic-block/edge. @@ -1107,9 +1117,11 @@ struct kcov_common_handle_id kcov_common_handle(void) EXPORT_SYMBOL(kcov_common_handle); #ifdef CONFIG_KCOV_SELFTEST +static unsigned long selftest_area[16] __initdata; + static void __init selftest(void) { - unsigned long start; + unsigned long start, i, ip, count; pr_err("running self test\n"); /* @@ -1119,15 +1131,26 @@ static void __init selftest(void) * leaks out of that section and leads to spurious coverage. * It's hard to call the actual interrupt handler directly, * so we just loop here for a bit waiting for a timer interrupt. - * We set kcov_mode to enable tracing, but don't setup the area, - * so any attempt to trace will crash. Note: we must not call any + * A small coverage area records the PCs of any leaks. The first word + * holds the count, leaving room for 15 PCs. Note: we must not call any * potentially traced functions in this region. */ + kcov_start(current, NULL, ARRAY_SIZE(selftest_area), + selftest_area, KCOV_MODE_TRACE_PC, 0); start = jiffies; - WRITE_ONCE(current->kcov_mode, KCOV_MODE_TRACE_PC); while ((jiffies - start) * MSEC_PER_SEC / HZ < 300) - ; - WRITE_ONCE(current->kcov_mode, 0); + cpu_relax(); + kcov_stop(current); + + count = READ_ONCE(selftest_area[0]); + if (count) { + pr_err("spurious coverage detected during interrupt selftest:\n"); + for (i = 1; i <= count; i++) { + ip = decanonicalize_ip(selftest_area[i]); + pr_err(" %pB\n", (void *)ip); + } + panic("kcov: interrupt selftest detected spurious coverage"); + } pr_err("done running self test\n"); } #endif diff --git a/kernel/kexec_core.c b/kernel/kexec_core.c index dc770b9a6d05..282c7b3c6c35 100644 --- a/kernel/kexec_core.c +++ b/kernel/kexec_core.c @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -54,6 +55,12 @@ atomic_t __kexec_lock = ATOMIC_INIT(0); /* Flag to indicate we are going to kexec a new kernel */ bool kexec_in_progress = false; +bool kexec_is_in_progress(void) +{ + return kexec_in_progress; +} +EXPORT_SYMBOL_GPL(kexec_is_in_progress); + bool kexec_file_dbg_print; /* diff --git a/kernel/kexec_file.c b/kernel/kexec_file.c index 59fb9d71e9d8..01a64d98fbcd 100644 --- a/kernel/kexec_file.c +++ b/kernel/kexec_file.c @@ -484,7 +484,9 @@ static int locate_mem_hole_top_down(unsigned long start, unsigned long end, /* align down start */ temp_start = ALIGN_DOWN(temp_start, kbuf->buf_align); - if (temp_start < start || temp_start < kbuf->buf_min) + /* A candidate above the range means the walk wrapped around */ + if (temp_start < start || temp_start < kbuf->buf_min || + temp_start > end) return 0; temp_end = temp_start + kbuf->memsz - 1; diff --git a/kernel/kthread.c b/kernel/kthread.c index a3f95c90456b..0dbff3b68ffb 100644 --- a/kernel/kthread.c +++ b/kernel/kthread.c @@ -343,7 +343,7 @@ static void kthread_fetch_affinity(struct kthread *kthread, struct cpumask *cpum } cpumask_and(cpumask, pref, housekeeping_cpumask(HK_TYPE_DOMAIN)); - if (cpumask_empty(cpumask)) + if (!cpumask_intersects(cpumask, cpu_online_mask)) cpumask_copy(cpumask, housekeeping_cpumask(HK_TYPE_DOMAIN)); } diff --git a/kernel/module/tracking.c b/kernel/module/tracking.c index 9033ff54c4e2..9e8902600c32 100644 --- a/kernel/module/tracking.c +++ b/kernel/module/tracking.c @@ -38,8 +38,8 @@ int try_add_tainted_module(struct module *mod) return -ENOMEM; strscpy(mod_taint->name, mod->name, MODULE_NAME_LEN); mod_taint->taints = mod->taints; - list_add_rcu(&mod_taint->list, &unloaded_tainted_modules); mod_taint->count = 1; + list_add_rcu(&mod_taint->list, &unloaded_tainted_modules); out: return 0; } diff --git a/kernel/nsproxy.c b/kernel/nsproxy.c index 3fb1595a4a59..028019f3e387 100644 --- a/kernel/nsproxy.c +++ b/kernel/nsproxy.c @@ -355,6 +355,7 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset) { struct task_struct *me = current; + nsset->flags = flags; nsset->nsproxy = create_new_namespaces(0, me, current_user_ns(), me->fs); if (IS_ERR(nsset->nsproxy)) return PTR_ERR(nsset->nsproxy); @@ -375,7 +376,6 @@ static int prepare_nsset(unsigned flags, struct nsset *nsset) goto out; } - nsset->flags = flags; return 0; out: diff --git a/kernel/power/suspend.c b/kernel/power/suspend.c index 57c44268698f..32c055df02da 100644 --- a/kernel/power/suspend.c +++ b/kernel/power/suspend.c @@ -306,20 +306,24 @@ static void platform_resume_finish(suspend_state_t state) static int platform_suspend_begin(suspend_state_t state) { - if (state == PM_SUSPEND_TO_IDLE && s2idle_ops && s2idle_ops->begin) - return s2idle_ops->begin(); - else if (suspend_ops && suspend_ops->begin) + if (state == PM_SUSPEND_TO_IDLE) { + if (s2idle_ops && s2idle_ops->begin) + return s2idle_ops->begin(); + } else if (suspend_ops && suspend_ops->begin) { return suspend_ops->begin(state); - else - return 0; + } + + return 0; } static void platform_resume_end(suspend_state_t state) { - if (state == PM_SUSPEND_TO_IDLE && s2idle_ops && s2idle_ops->end) - s2idle_ops->end(); - else if (suspend_ops && suspend_ops->end) + if (state == PM_SUSPEND_TO_IDLE) { + if (s2idle_ops && s2idle_ops->end) + s2idle_ops->end(); + } else if (suspend_ops && suspend_ops->end) { suspend_ops->end(); + } } static void platform_recover(suspend_state_t state) diff --git a/kernel/profile.c b/kernel/profile.c index 1fcf1adcf4eb..e7defa90a34c 100644 --- a/kernel/profile.c +++ b/kernel/profile.c @@ -156,7 +156,7 @@ read_profile(struct file *file, char __user *buf, size_t count, loff_t *ppos) unsigned long p = *ppos; ssize_t read; char *pnt; - unsigned long sample_step = 1UL << prof_shift; + unsigned int sample_step = (unsigned int)(1UL << prof_shift); if (p >= (prof_len+1)*sizeof(unsigned int)) return 0; diff --git a/kernel/rcu/rcutorture.c b/kernel/rcu/rcutorture.c index 794937e13e7c..83819424cf35 100644 --- a/kernel/rcu/rcutorture.c +++ b/kernel/rcu/rcutorture.c @@ -3856,7 +3856,7 @@ static int __init rcu_torture_fwd_prog_init(void) } if (fwd_progress_holdoff <= 0) fwd_progress_holdoff = 1; - if (fwd_progress_div <= 0) + if (fwd_progress_div < 2) fwd_progress_div = 4; rfp = kzalloc_objs(*rfp, fwd_progress); fwd_prog_tasks = kzalloc_objs(*fwd_prog_tasks, fwd_progress); diff --git a/kernel/rcu/srcutree.c b/kernel/rcu/srcutree.c index ad27880dd690..700d2c30feb2 100644 --- a/kernel/rcu/srcutree.c +++ b/kernel/rcu/srcutree.c @@ -218,7 +218,12 @@ static int init_srcu_struct_fields(struct srcu_struct *ssp, bool is_static) mutex_init(&ssp->srcu_sup->srcu_barrier_mutex); atomic_set(&ssp->srcu_sup->srcu_barrier_cpu_cnt, 0); INIT_DELAYED_WORK(&ssp->srcu_sup->work, process_srcu); - init_irq_work(&ssp->srcu_sup->irq_work, srcu_irq_work); + /* + * trace events started on the command line require SRCU before + * the irq_work kthread starts. Since all it does is a simple + * wakeup, having it as a hard irq, even on PREEMPT_RT is fine. + */ + ssp->srcu_sup->irq_work = IRQ_WORK_INIT_HARD(srcu_irq_work); ssp->srcu_sup->sda_is_static = is_static; if (!is_static) { ssp->sda = alloc_percpu(struct srcu_data); diff --git a/kernel/rcu/tree_nocb.h b/kernel/rcu/tree_nocb.h index 19bb42672baf..b6cfee4e5039 100644 --- a/kernel/rcu/tree_nocb.h +++ b/kernel/rcu/tree_nocb.h @@ -1332,9 +1332,8 @@ lazy_rcu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc) rcu_nocb_try_flush_bypass(rdp, jiffies); rcu_nocb_unlock_irqrestore(rdp, flags); wake_nocb_gp(rdp); - sc->nr_to_scan -= _count; count += _count; - if (sc->nr_to_scan <= 0) + if (count >= sc->nr_to_scan) break; } diff --git a/kernel/reboot.c b/kernel/reboot.c index 5b9691f45f5f..bc2716677a6c 100644 --- a/kernel/reboot.c +++ b/kernel/reboot.c @@ -813,8 +813,8 @@ SYSCALL_DEFINE4(reboot, int, magic1, int, magic2, unsigned int, cmd, #ifdef CONFIG_HIBERNATION case LINUX_REBOOT_CMD_SW_SUSPEND: - ret = hibernate(); - break; + mutex_unlock(&system_transition_mutex); + return hibernate(); #endif default: diff --git a/kernel/resource_kunit.c b/kernel/resource_kunit.c index 42785796f1db..9eeb2b1a85c0 100644 --- a/kernel/resource_kunit.c +++ b/kernel/resource_kunit.c @@ -225,6 +225,9 @@ static void resource_test_region_intersects(struct kunit *test) struct resource *parent; resource_size_t start; + if (!IS_ENABLED(CONFIG_GET_FREE_REGION)) + kunit_skip(test, "CONFIG_GET_FREE_REGION is disabled"); + /* Find an iomem_resource hole to hold test resources */ parent = alloc_free_mem_region(&iomem_resource, RES_TEST_TOTAL_SIZE, SZ_1M, "test resources"); diff --git a/kernel/sched/core.c b/kernel/sched/core.c index 1754d9f95f2c..4a051764e711 100644 --- a/kernel/sched/core.c +++ b/kernel/sched/core.c @@ -1196,6 +1196,7 @@ static void __resched_curr(struct rq *rq, int tif) { struct task_struct *curr = rq->curr; struct thread_info *cti = task_thread_info(curr); + bool need_ipi; int cpu; lockdep_assert_rq_held(rq); @@ -1212,15 +1213,17 @@ static void __resched_curr(struct rq *rq, int tif) cpu = cpu_of(rq); - trace_sched_set_need_resched_tp(curr, cpu, tif); if (cpu == smp_processor_id()) { set_ti_thread_flag(cti, tif); if (tif == TIF_NEED_RESCHED) set_preempt_need_resched(); + trace_sched_set_need_resched_tp(curr, cpu, tif); return; } - if (set_nr_and_not_polling(cti, tif)) { + need_ipi = set_nr_and_not_polling(cti, tif); + trace_sched_set_need_resched_tp(curr, cpu, tif); + if (need_ipi) { if (tif == TIF_NEED_RESCHED) smp_send_reschedule(cpu); } else { @@ -3773,6 +3776,7 @@ static inline void proxy_reset_donor(struct rq *rq) WARN_ON_ONCE(rq->donor == rq->curr); put_prev_set_next_task(rq, rq->donor, rq->curr); + rq->next_class = rq->curr->sched_class; rq_set_donor(rq, rq->curr); zap_balance_callbacks(rq); resched_curr(rq); @@ -6517,7 +6521,7 @@ static bool try_steal_cookie(int this, int that) return false; do { - if (p == src->core_pick || p == src->curr) + if (p == src->core_pick || p == src->curr || p == src->donor) goto next; if (!is_cpu_allowed(p, this)) @@ -7051,6 +7055,14 @@ find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf) owner->blocked_donor = p; } WARN_ON_ONCE(owner && !owner->on_rq); + + if (owner && !sched_cpu_cookie_match(rq, owner)) { + if (curr_in_chain) + return proxy_resched_idle(rq); + p = donor; /* Deactivate the donor, not the runnable owner */ + clear_task_blocked_on(p, NULL); + goto deactivate; + } return owner; deactivate: @@ -7184,13 +7196,12 @@ static void __sched notrace __schedule(int sched_mode) } } else if (!preempt && prev_state) { /* - * We pass task_is_blocked() as the should_block arg - * in order to keep mutex-blocked tasks on the runqueue - * for slection with proxy-exec (without proxy-exec - * task_is_blocked() will always be false). + * Keep mutex-blocked tasks on the runqueue for proxy execution + * only when their scheduling class allows it. Without proxy + * execution, task_is_blocked() always returns false. */ try_to_block_task(rq, prev, &prev_state, - !task_is_blocked(prev)); + !task_is_blocked(prev) || !scx_allow_proxy_exec(prev)); switch_count = &prev->nvcsw; } @@ -7211,6 +7222,7 @@ static void __sched notrace __schedule(int sched_mode) } if (next == rq->idle) { zap_balance_callbacks(rq); + scx_proxy_reenqueue_retry(rq, next); goto keep_resched; } } @@ -7229,8 +7241,10 @@ static void __sched notrace __schedule(int sched_mode) * on_cpu. */ donor->sched_class->put_prev_task(rq, donor, donor); - donor->sched_class->set_next_task(rq, donor, true); + donor->sched_class->set_next_task(rq, donor, SNT_PICK); } + scx_proxy_donor_start(rq); + scx_proxy_reenqueue_retry(rq, next); } else { rq_set_donor(rq, next); } @@ -10852,11 +10866,10 @@ static void __mm_update_max_cids(struct mm_mm_cid *mc) static inline unsigned int mm_cid_calc_pcpu_thrs(struct mm_mm_cid *mc) { - unsigned int opt_cids; + unsigned int nr_cpus = mc->nr_cpus_allowed; - opt_cids = min(mc->nr_cpus_allowed, mc->users); /* Has to be at least 1 because 0 indicates PCPU mode off */ - return max(min(opt_cids - opt_cids / 4, num_possible_cpus() / 2), 1); + return max(min(nr_cpus - nr_cpus / 4, num_possible_cpus() / 2), 1); } static bool mm_update_max_cids(struct mm_struct *mm) diff --git a/kernel/sched/cputime.c b/kernel/sched/cputime.c index 06bddaa738e5..a19e61890c74 100644 --- a/kernel/sched/cputime.c +++ b/kernel/sched/cputime.c @@ -381,9 +381,9 @@ void thread_group_cputime(struct task_struct *tsk, struct task_cputime *times) * softirq as those do not count in task exec_runtime any more. */ static void irqtime_account_process_tick(struct task_struct *p, int user_tick, - int ticks) + u64 cputime) { - u64 other, cputime = TICK_NSEC * ticks; + u64 other; /* * When returning from idle, many ticks can get accounted at @@ -418,7 +418,7 @@ static void irqtime_account_process_tick(struct task_struct *p, int user_tick, #else /* !CONFIG_IRQ_TIME_ACCOUNTING: */ static inline void irqtime_account_process_tick(struct task_struct *p, int user_tick, - int nr_ticks) { } + u64 cputime) { } #endif /* !CONFIG_IRQ_TIME_ACCOUNTING */ #if defined(CONFIG_NO_HZ_COMMON) && !defined(CONFIG_HAVE_VIRT_CPU_ACCOUNTING_IDLE) @@ -468,18 +468,43 @@ static void kcpustat_idle_start(struct kernel_cpustat *kc, u64 now) write_seqcount_end(&kc->idle_sleeptime_seq); } -void kcpustat_dyntick_stop(u64 now) +void kcpustat_dyntick_stop(u64 now, u64 tick_start) { struct kernel_cpustat *kc = kcpustat_this_cpu; if (!vtime_generic_enabled_this_cpu()) { WARN_ON_ONCE(!kc->idle_dyntick); + if (kc->idle_tick_period != tick_start) { + kc->idle_tick_period = tick_start; + kc->idle_tick_overlap = 0; + } + tick_start = max(tick_start, kc->idle_dyntick_entry); + /* + * After a switch from the jiffies clocksource the tick can be + * armed more than a tick ahead, so the period may not have + * started yet. + */ + if (now > tick_start) + kc->idle_tick_overlap += now - tick_start; kcpustat_idle_stop(kc, now); kc->idle_dyntick = false; vtime_dyntick_stop(); } } +/* + * The first tick after dyntick-idle covers a period that the dyntick-idle + * accounting may already have accounted in part. + */ +static inline u64 kcpustat_tick_overlap(void) +{ + struct kernel_cpustat *kc = kcpustat_this_cpu; + u64 overlap = kc->idle_tick_overlap; + + kc->idle_tick_overlap = 0; + return overlap; +} + void kcpustat_dyntick_start(u64 now) { struct kernel_cpustat *kc = kcpustat_this_cpu; @@ -487,6 +512,7 @@ void kcpustat_dyntick_start(u64 now) if (!vtime_generic_enabled_this_cpu()) { vtime_dyntick_start(); kc->idle_dyntick = true; + kc->idle_dyntick_entry = now; kcpustat_idle_start(kc, now); } } @@ -555,6 +581,11 @@ u64 kcpustat_field_iowait(int cpu) } EXPORT_SYMBOL_GPL(kcpustat_field_iowait); #else +static inline u64 kcpustat_tick_overlap(void) +{ + return 0; +} + static u64 kcpustat_field_dyntick(int cpu, enum cpu_usage_stat idx, bool compute_delta, ktime_t now) { @@ -695,12 +726,13 @@ void account_process_tick(struct task_struct *p, int user_tick) if (kcpustat_idle_dyntick()) return; + cputime = TICK_NSEC - kcpustat_tick_overlap(); + if (irqtime_enabled()) { - irqtime_account_process_tick(p, user_tick, 1); + irqtime_account_process_tick(p, user_tick, cputime); return; } - cputime = TICK_NSEC; steal = steal_account_process_time(ULONG_MAX); if (steal >= cputime) diff --git a/kernel/sched/deadline.c b/kernel/sched/deadline.c index 0663c00c41c0..1502a45d76aa 100644 --- a/kernel/sched/deadline.c +++ b/kernel/sched/deadline.c @@ -2773,11 +2773,14 @@ static void start_hrtick_dl(struct rq *rq, struct sched_dl_entity *dl_se) * DL keeps current in tree, because ->deadline is not typically changed while * a task is runnable. */ -static void set_next_task_dl(struct rq *rq, struct task_struct *p, bool first) +static void set_next_task_dl(struct rq *rq, struct task_struct *p, enum snt_e type) { struct sched_dl_entity *dl_se = &p->dl; struct dl_rq *dl_rq = &rq->dl; + if (type == SNT_REPICK) + return; + p->se.exec_start = rq_clock_task(rq); if (on_dl_rq(&p->dl)) update_stats_wait_end_dl(dl_rq, dl_se); @@ -2788,7 +2791,7 @@ static void set_next_task_dl(struct rq *rq, struct task_struct *p, bool first) WARN_ON_ONCE(dl_rq->curr); dl_rq->curr = dl_se; - if (!first) + if (type != SNT_PICK) return; if (rq->donor->sched_class != &dl_sched_class) diff --git a/kernel/sched/ext/cid.c b/kernel/sched/ext/cid.c index 4b08866d75f6..3d0687184b44 100644 --- a/kernel/sched/ext/cid.c +++ b/kernel/sched/ext/cid.c @@ -287,6 +287,12 @@ s32 scx_cid_init(struct scx_sched *sch) * empty shard. */ cids_in_core = cpumask_weight(core_scratch); + if (cids_in_core > SCX_CID_SHARD_MAX_CPUS) { + scx_error(sch, "core with %u cpus exceeds max shard size %d", + cids_in_core, SCX_CID_SHARD_MAX_CPUS); + return -E2BIG; + } + max_cores = cores_per_shard + (shard_local < nr_large ? 1 : 0); if (cores_in_shard && (cores_in_shard >= max_cores || diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c index 84774147a1d5..4b04ed0441fc 100644 --- a/kernel/sched/ext/ext.c +++ b/kernel/sched/ext/ext.c @@ -24,6 +24,11 @@ DEFINE_RAW_SPINLOCK(scx_sched_lock); +bool scx_allow_proxy_exec(const struct task_struct *p) +{ + return true; +} + /* * NOTE: sched_ext is in the process of growing multiple scheduler support and * scx_root usage is in a transitional state. Naked dereferences are safe if the @@ -322,7 +327,6 @@ static const struct sched_class *scx_setscheduler_class(struct task_struct *p) static struct scx_dispatch_q *bypass_enq_target_dsq(struct scx_sched *sch, s32 cpu) { -#ifdef CONFIG_EXT_SUB_SCHED /* * If @sch is a sub-sched which is bypassing, its tasks should go into * the bypass DSQs of the nearest ancestor which is not bypassing. The @@ -334,11 +338,7 @@ static struct scx_dispatch_q *bypass_enq_target_dsq(struct scx_sched *sch, s32 c * are re-enqueued after scx_bypassing() is turned on, guaranteeing that * all tasks are transferred to the right DSQs. */ - while (scx_parent(sch) && scx_bypassing(sch, cpu)) - sch = scx_parent(sch); -#endif /* CONFIG_EXT_SUB_SCHED */ - - return scx_bypass_dsq(sch, cpu); + return scx_bypass_dsq(scx_exec_sched(sch, cpu), cpu); } /** @@ -1064,9 +1064,10 @@ static void schedule_deferred_locked(struct rq *rq) return; /* - * If in dispatch, the balance callbacks will be called before rq lock - * is released. Schedule one. - * + * If in dispatch without proxy execution, the balance callbacks will + * be called before rq lock is released. Schedule one. With proxy + * execution, proxy resolution can zap the callbacks without another + * SCX dispatch to requeue them, so use irq_work instead. * * We can't directly insert the callback into the * rq's list: The call can drop its lock and make the pending balance @@ -1074,7 +1075,7 @@ static void schedule_deferred_locked(struct rq *rq) * * Just let dispatch_one() know that it must do it itself. */ - if (rq->scx.flags & SCX_RQ_IN_DISPATCH) { + if ((rq->scx.flags & SCX_RQ_IN_DISPATCH) && !sched_proxy_exec()) { rq->scx.flags |= SCX_RQ_BAL_CB_PENDING; return; } @@ -1087,6 +1088,10 @@ static void schedule_deferred_locked(struct rq *rq) schedule_deferred(rq); } +void scx_proxy_reenqueue_retry(struct rq *rq, struct task_struct *next) +{ +} + void schedule_dsq_reenq(struct scx_sched *sch, struct scx_dispatch_q *dsq, u64 reenq_flags, struct rq *locked_rq) { @@ -2328,10 +2333,10 @@ static bool dequeue_task_scx(struct rq *rq, struct task_struct *p, int core_deq_ ops_dequeue(rq, p, deq_flags); /* - * A currently running task which is going off @rq first gets dequeued - * and then stops running. As we want running <-> stopping transitions - * to be contained within runnable <-> quiescent transitions, trigger - * ->stopping() early here instead of in put_prev_task_scx(). + * A current scheduling context which is going off @rq first gets + * dequeued and then stops running. As we want running <-> stopping + * transitions to be contained within runnable <-> quiescent transitions, + * trigger ->stopping() early here instead of in put_prev_task_scx(). * * @p may go through multiple stopping <-> running transitions between * here and put_prev_task_scx() if task attribute changes occur while @@ -2339,11 +2344,13 @@ static bool dequeue_task_scx(struct rq *rq, struct task_struct *p, int core_deq_ * information meaningful to the BPF scheduler and can be suppressed by * skipping the callbacks if the task is !QUEUED. */ - if (task_current(rq, p) && - (SCX_HAS_OP(sch, stopping) || unlikely(p == scx_rescuee(rq)))) { - update_curr_scx(rq); - if (SCX_HAS_OP(sch, stopping)) - SCX_CALL_OP_TASK(sch, stopping, rq, p, false); + if (task_current_donor(rq, p) && (p->scx.flags & SCX_TASK_RUN_TRACKED)) { + if (SCX_HAS_OP(sch, stopping) || unlikely(p == scx_rescuee(rq))) { + update_curr_scx(rq); + if (SCX_HAS_OP(sch, stopping)) + SCX_CALL_OP_TASK(sch, stopping, rq, p, false); + } + p->scx.flags &= ~SCX_TASK_RUN_TRACKED; } if (SCX_HAS_OP(sch, quiescent) && !task_on_rq_migrating(p)) @@ -3052,18 +3059,40 @@ static enum scx_dsp_verdict dispatch_one(struct rq *rq, struct task_struct *prev * * - A non-IMMED HEAD task can get queued in front of an IMMED task * between the IMMED queueing and the subsequent scheduling event. + * + * - When dispatch keeps @prev, even a lone IMMED task queued during the + * dispatch can't run right away. */ - if (unlikely(rq->scx.local_dsq.nr > 1 && rq->scx.nr_immed)) + if (unlikely((rq->scx.local_dsq.nr > 1 || verdict == SCX_DSP_PREV) && + rq->scx.nr_immed)) scx_schedule_reenq_local(rq, 0); rq->scx.flags &= ~SCX_RQ_IN_DISPATCH; return verdict; } -static void set_next_task_scx(struct rq *rq, struct task_struct *p, bool first) +static void scx_start_task_running(struct rq *rq, struct task_struct *p) { struct scx_sched *sch = scx_task_sched(p); + if (p->scx.flags & SCX_TASK_RUN_TRACKED) + return; + + scx_cid_sched_update(rq, sch); + + if (SCX_HAS_OP(sch, running)) + SCX_CALL_OP_TASK(sch, running, rq, p); + + p->scx.flags |= SCX_TASK_RUN_TRACKED; +} + +static void set_next_task_scx(struct rq *rq, struct task_struct *p, enum snt_e type) +{ + bool first = type == SNT_PICK; + + if (type == SNT_REPICK) + return; + if (p->scx.flags & SCX_TASK_QUEUED) { /* * Core-sched might decide to execute @p before it is @@ -3075,9 +3104,20 @@ static void set_next_task_scx(struct rq *rq, struct task_struct *p, bool first) p->se.exec_start = rq_clock_task(rq); - /* see dequeue_task_scx() on why we skip when !QUEUED */ - if (SCX_HAS_OP(sch, running) && (p->scx.flags & SCX_TASK_QUEUED)) - SCX_CALL_OP_TASK(sch, running, rq, p); + /* + * See dequeue_task_scx() for why we skip when !QUEUED. + * + * During a normal switch (@first), a blocked task is only a provisional + * donor. Proxy resolution may fail or migrate the donor to another CPU, + * so defer ops.running() until scx_proxy_donor_start() confirms that + * resolution succeeded. + * + * !@first denotes restoration after a SAVE/RESTORE cycle. The matching + * dequeue already issued ops.stopping(), so restart the session here + * regardless of the donor state. + */ + if ((p->scx.flags & SCX_TASK_QUEUED) && !(p->is_blocked && first)) + scx_start_task_running(rq, p); clr_task_runnable(p, true); @@ -3121,6 +3161,16 @@ static void set_next_task_scx(struct rq *rq, struct task_struct *p, bool first) } } +void scx_proxy_donor_start(struct rq *rq) +{ + struct task_struct *donor = rq->donor; + + lockdep_assert_rq_held(rq); + + if (donor->sched_class == &ext_sched_class && (donor->scx.flags & SCX_TASK_QUEUED)) + scx_start_task_running(rq, donor); +} + static enum scx_cpu_preempt_reason preempt_reason_from_class(const struct sched_class *class) { @@ -3194,9 +3244,17 @@ static void put_prev_task_scx(struct rq *rq, struct task_struct *p, scx_task_slice_ended(rq, p); } - /* see dequeue_task_scx() on why we skip when !QUEUED */ - if (SCX_HAS_OP(sch, stopping) && (p->scx.flags & SCX_TASK_QUEUED)) - SCX_CALL_OP_TASK(sch, stopping, rq, p, true); + /* + * Preserve the running session when proxy execution refreshes the same + * donor around an execution-context switch on this rq. + */ + if (next != p && (p->scx.flags & SCX_TASK_QUEUED) && + (p->scx.flags & SCX_TASK_RUN_TRACKED)) { + if (SCX_HAS_OP(sch, stopping)) + SCX_CALL_OP_TASK(sch, stopping, rq, p, true); + + p->scx.flags &= ~SCX_TASK_RUN_TRACKED; + } if (p->scx.flags & SCX_TASK_QUEUED) { set_task_runnable(rq, p); @@ -3270,8 +3328,10 @@ static void put_prev_task_scx(struct rq *rq, struct task_struct *p, } switch_class: - if (next && next->sched_class != &ext_sched_class) + if (next && next->sched_class != &ext_sched_class) { + scx_cid_sched_update(rq, NULL); switch_class(rq, next); + } } static void kick_sync_wait_bal_cb(struct rq *rq) @@ -4432,6 +4492,13 @@ static void switching_to_scx(struct rq *rq, struct task_struct *p) static void switched_from_scx(struct rq *rq, struct task_struct *p) { + /* + * A class change of the running task: sched_change_begin() put @p with + * no successor, which leaves rq->scx.sched set. + */ + if (task_current_donor(rq, p)) + scx_cid_sched_update(rq, NULL); + if (task_dead_and_done(p)) return; @@ -5918,6 +5985,110 @@ bool scx_hardlockup(int cpu) return true; } +/** + * bypass_lb_reenq_home - Reenqueue a task at its home from the balancer + * @rq: @p's home rq, locked + * @p: task off any DSQ, taken from the bypass DSQ of @dsq_cpu + * @dsq_cpu: cpu whose bypass DSQ gave up @p + * + * @p came off the bypass DSQ of @dsq_cpu with no donee able to take it. A drain + * sends a migration-disabled @p here unless the donee picked for it is its + * home, as every other cpu refuses it. The enqueue sends @p to rescue when the + * host lacks %SCX_CAP_BASE at home and rescue is enabled, and to the home's + * bypass DSQ otherwise. When @p must run at home, migration-disabled or with a + * migration pending, and the host lacks BASE there, it is admitted to the + * home's local DSQ in either case, see bypass_enq_target_dsq(). No DSQ lock may + * be held, as the enqueue takes one. + */ +static void bypass_lb_reenq_home(struct rq *rq, struct task_struct *p, s32 dsq_cpu) +{ + lockdep_assert_rq_held(rq); + + WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK); + p->scx.flags |= SCX_TASK_REENQ_CAP; + p->scx.reenq_reason_caps = SCX_CAP_BASE; + p->scx.reenq_reason_cid = __scx_cpu_to_cid(dsq_cpu); + scx_do_enqueue_task(rq, p, SCX_ENQ_REENQ, -1); +} + +/** + * bypass_lb_can_move - Test whether @p can move to the bypass DSQ of @donee + * @sch: host sched whose bypass DSQs are balanced + * @p: task on a bypass DSQ of @sch, homed anywhere + * @donee: cpu whose bypass DSQ would receive @p, -1 for none + * + * @p's rq lock pins @p's affinity. Without it the answer is a hint. A task + * whose donee is its own cpu can always run there, and + * task_can_run_on_remote_rq() warns when asked about a task's own cpu. + */ +static bool bypass_lb_can_move(struct scx_sched *sch, struct task_struct *p, s32 donee) +{ + return donee >= 0 && (donee == task_cpu(p) || + task_can_run_on_remote_rq(sch, p, cpu_rq(donee), false)); +} + +/** + * bypass_lb_move - Move one task off a bypass DSQ for the balancer + * @sch: host sched whose bypass DSQs are balanced + * @donor_rq: rq of the cpu whose bypass DSQ gives up @p, locked + * @donor_dsq: @sch's bypass DSQ on @donor_rq's cpu, locked + * @p: task on @donor_dsq, homed anywhere + * @donee: cpu whose bypass DSQ receives @p, -1 for none + * + * Take @p off @donor_dsq and insert it into the bypass DSQ of @donee. The + * caller tests bypass_lb_can_move() without @p's rq lock for a task homed + * elsewhere, and not at all for a drain, so the test is repeated here under + * @p's rq lock. A task that fails it is not put back, as the host may no longer + * consume @donor_dsq. bypass_lb_reenq_home() reenqueues it at its home instead. + * + * The insert and the reenqueue run under @p's rq lock. A task homed on + * @donor_rq is dequeued in place. unlink_dsq_and_switch_rq_lock() takes one + * homed elsewhere off and switches the rq lock from @donor_rq to its own. The + * switch can lose to a dequeue, and @p then belongs to the dequeuer. + * + * @donor_rq and @donor_dsq are locked on entry and on return. @donor_dsq is + * unlocked in between, and @donor_rq too while the lock is switched, so the + * caller's walk must find its place in @donor_dsq again after the call. + * + * Return the cpu that received @p, or -1 if @p was lost to a dequeue. + */ +static s32 bypass_lb_move(struct scx_sched *sch, struct rq *donor_rq, + struct scx_dispatch_q *donor_dsq, struct task_struct *p, s32 donee) +{ + struct rq *rq = task_rq(p); + s32 ret; + + lockdep_assert_rq_held(donor_rq); + lockdep_assert_held(&donor_dsq->lock); + + if (rq == donor_rq) { + scx_wait_dispatching(p); + dispatch_dequeue_locked(p, donor_dsq); + raw_spin_unlock(&donor_dsq->lock); + } else if (!unlink_dsq_and_switch_rq_lock(p, donor_dsq, donor_rq, rq)) { + /* lost to a dequeue, @p is the dequeuer's now */ + ret = -1; + goto out; + } + + if (bypass_lb_can_move(sch, p, donee)) { + scx_dispatch_enqueue(sch, rq, scx_bypass_dsq(sch, donee), p, 0, 0, 0); + ret = donee; + } else { + /* + * No donee, or @p can't run on it. Reenqueue @p at home + * instead, see bypass_lb_reenq_home(). + */ + bypass_lb_reenq_home(rq, p, cpu_of(donor_rq)); + ret = cpu_of(rq); + } +out: + if (rq != donor_rq) + switch_rq_lock(rq, donor_rq); + raw_spin_lock(&donor_dsq->lock); + return ret; +} + static u32 bypass_lb_cpu(struct scx_sched *sch, s32 donor, struct cpumask *donee_mask, struct cpumask *resched_mask, u32 nr_donor_target, u32 nr_donee_target) @@ -5933,87 +6104,94 @@ static u32 bypass_lb_cpu(struct scx_sched *sch, s32 donor, * All we want to guarantee is reasonable forward progress. No reason to * fine tune. Assuming every task on @donor_dsq runs their full slice, * consider offloading iff the total queued duration is over the - * threshold. + * threshold. A zero target is a drain and empties the DSQ regardless. */ min_delta_us = READ_ONCE(scx_bypass_lb_intv_us) / SCX_BYPASS_LB_MIN_DELTA_DIV; - if (delta < DIV_ROUND_UP(min_delta_us, READ_ONCE(scx_slice_bypass_us))) + if (nr_donor_target && + delta < DIV_ROUND_UP(min_delta_us, READ_ONCE(scx_slice_bypass_us))) return 0; raw_spin_rq_lock_irq(donor_rq); raw_spin_lock(&donor_dsq->lock); + /* bound the walk to the tasks queued now, see the seq test below */ + cursor.priv = donor_dsq->seq; list_add(&cursor.node, &donor_dsq->list); resume: n = container_of(&cursor, struct task_struct, scx.dsq_list); n = nldsq_next_task(donor_dsq, n, false); while ((p = n)) { - struct scx_dispatch_q *donee_dsq; - int donee; + s32 donee, cpu; n = nldsq_next_task(donor_dsq, n, false); if (donor_dsq->nr <= nr_donor_target) break; - if (cpumask_empty(donee_mask)) - break; - /* - * If an earlier pass placed @p on @donor_dsq from a different - * CPU and the donee hasn't consumed it yet, @p is still on the - * previous CPU and task_rq(@p) != @donor_rq. @p can't be moved - * without its rq locked. Skip. + * Without a donee, a balancing donor has nothing to do. A drain + * still sends its tasks home. */ - if (task_rq(p) != donor_rq) - continue; - - donee = cpumask_any_and_distribute(donee_mask, p->cpus_ptr); - if (donee >= nr_cpu_ids) - continue; - - donee_dsq = scx_bypass_dsq(sch, donee); + if (cpumask_empty(donee_mask) && nr_donor_target) + break; /* - * $p's rq is not locked but $p's DSQ lock protects its - * scheduling properties making this test safe. + * A task queued after the walk began, including one the walk + * itself reenqueued, is left for the next pass. */ - if (!task_can_run_on_remote_rq(sch, p, cpu_rq(donee), false)) + if (u32_before(cursor.priv, p->scx.dsq_seq)) continue; /* - * Moving $p from one non-local DSQ to another. The source rq - * and DSQ are already locked. Do an abbreviated dequeue and - * then perform enqueue without unlocking $donor_dsq. - * - * We don't want to drop and reacquire the lock on each - * iteration as @donor_dsq can be very long and potentially - * highly contended. Donee DSQs are less likely to be contended. - * The nested locking is safe as only this LB moves tasks - * between bypass DSQs. + * A balancing donor leaves a task that can't move where it is. + * A home reenqueue would push one homed on the donor to the + * back of @donor_dsq on every pass. A drain sends it home. */ - dispatch_dequeue_locked(p, donor_dsq); - scx_dispatch_enqueue(sch, cpu_rq(donee), donee_dsq, p, 0, 0, SCX_ENQ_NESTED); + donee = cpumask_any_and_distribute(donee_mask, p->cpus_ptr); + if (donee >= nr_cpu_ids) + donee = -1; + if (nr_donor_target && !bypass_lb_can_move(sch, p, donee)) + continue; /* - * $donee might have been idle and need to be woken up. No need - * to be clever. Kick every CPU that receives tasks. + * The move drops @donor_dsq's lock, and the rq lock too when + * @p is homed elsewhere. The donor cpu's dispatch and its + * enqueuers can reach @donor_dsq then. Park the cursor behind + * @p and resume from it afterwards. The seq test above keeps a + * task enqueued meanwhile out of the pass. */ - cpumask_set_cpu(donee, resched_mask); + list_move(&cursor.node, &p->scx.dsq_list.node); + cpu = bypass_lb_move(sch, donor_rq, donor_dsq, p, donee); + if (cpu >= 0) { + /* + * @cpu might have been idle and need to be woken up. + * No need to be clever. Reschedule every cpu that + * receives tasks. + */ + cpumask_set_cpu(cpu, resched_mask); - if (READ_ONCE(donee_dsq->nr) >= nr_donee_target) - cpumask_clear_cpu(donee, donee_mask); + if (READ_ONCE(scx_bypass_dsq(sch, cpu)->nr) >= nr_donee_target) + cpumask_clear_cpu(cpu, donee_mask); - nr_balanced++; - if (!(nr_balanced % SCX_BYPASS_LB_BATCH) && n) { - list_move_tail(&cursor.node, &n->scx.dsq_list.node); - raw_spin_unlock(&donor_dsq->lock); - scx_rq_lock_drop(donor_rq); - raw_spin_rq_unlock_irq(donor_rq); - cpu_relax(); - raw_spin_rq_lock_irq(donor_rq); - raw_spin_lock(&donor_dsq->lock); - goto resume; + /* + * The rq lock is held across the walk, not cycled per + * move. @donor_dsq can be very long and contended, and + * the rq lock is what keeps its consumer and enqueuers + * away while the walk cycles the DSQ lock. The rare + * move of a task homed elsewhere does switch it away, + * see the cursor comment above. The walk can still take + * a while, so let the cpu breathe every so often. + */ + if (!(++nr_balanced % SCX_BYPASS_LB_BATCH)) { + raw_spin_unlock(&donor_dsq->lock); + scx_rq_lock_drop(donor_rq); + raw_spin_rq_unlock_irq(donor_rq); + cpu_relax(); + raw_spin_rq_lock_irq(donor_rq); + raw_spin_lock(&donor_dsq->lock); + } } + goto resume; } list_del_init(&cursor.node); @@ -6029,6 +6207,7 @@ static void bypass_lb_node(struct scx_sched *sch, int node) const struct cpumask *node_mask = cpumask_of_node(node); struct cpumask *donee_mask = sch->bypass_lb_donee_cpumask; struct cpumask *resched_mask = sch->bypass_lb_resched_cpumask; + u32 intv_us = READ_ONCE(scx_bypass_lb_intv_us); u32 nr_tasks = 0, nr_cpus = 0, nr_balanced = 0; u32 nr_target, nr_donor_target; u32 before_min = U32_MAX, before_max = 0; @@ -6040,13 +6219,15 @@ static void bypass_lb_node(struct scx_sched *sch, int node) u32 nr = READ_ONCE(scx_bypass_dsq(sch, cpu)->nr); nr_tasks += nr; - nr_cpus++; + /* only a cpu whose dispatch consumes its DSQ is capacity */ + if (!scx_missing_caps(sch, cpu, SCX_CAP_BASE)) + nr_cpus++; before_min = min(nr, before_min); before_max = max(nr, before_max); } - if (!nr_cpus) + if (!nr_tasks) return; /* @@ -6054,27 +6235,39 @@ static void bypass_lb_node(struct scx_sched *sch, int node) * balancing to fill donee CPUs upto $nr_target. Once targets are * calculated, find the donee CPUs. */ - nr_target = DIV_ROUND_UP(nr_tasks, nr_cpus); + nr_target = nr_cpus ? DIV_ROUND_UP(nr_tasks, nr_cpus) : 0; nr_donor_target = DIV_ROUND_UP(nr_target * SCX_BYPASS_LB_DONOR_PCT, 100); cpumask_clear(donee_mask); for_each_cpu_and(cpu, cpu_online_mask, node_mask) { - if (READ_ONCE(scx_bypass_dsq(sch, cpu)->nr) < nr_target) + /* a donee's DSQ is consumed only if @sch holds %SCX_CAP_BASE */ + if (READ_ONCE(scx_bypass_dsq(sch, cpu)->nr) < nr_target && + !scx_missing_caps(sch, cpu, SCX_CAP_BASE)) cpumask_set_cpu(cpu, donee_mask); } - /* iterate !donee CPUs and see if they should be offloaded */ + /* + * Offload the !donee cpus. A cpu where the host lost %SCX_CAP_BASE no + * longer consumes its DSQ. Drain it as a donor with a target of zero. A + * zero interval disables the balancing, not the drain. + */ cpumask_clear(resched_mask); for_each_cpu_and(cpu, cpu_online_mask, node_mask) { - if (cpumask_empty(donee_mask)) - break; - if (cpumask_test_cpu(cpu, donee_mask)) + u32 target = nr_donor_target; + + if (unlikely(scx_missing_caps(sch, cpu, SCX_CAP_BASE))) { + /* the mask may predate the loss, keep this cpu out */ + cpumask_clear_cpu(cpu, donee_mask); + target = 0; + } else if (!intv_us || cpumask_empty(donee_mask) || + cpumask_test_cpu(cpu, donee_mask)) { continue; - if (READ_ONCE(scx_bypass_dsq(sch, cpu)->nr) <= nr_donor_target) + } + if (READ_ONCE(scx_bypass_dsq(sch, cpu)->nr) <= target) continue; nr_balanced += bypass_lb_cpu(sch, cpu, donee_mask, resched_mask, - nr_donor_target, nr_target); + target, nr_target); } for_each_cpu(cpu, resched_mask) @@ -6113,9 +6306,28 @@ static void scx_bypass_lb_timerfn(struct timer_list *timer) for_each_node_with_cpus(node) bypass_lb_node(sch, node); + /* + * A kick during this run can leave the timer pending at now, see + * scx_bypass_lb_kick(). timer_reduce() only brings the expiry forward, + * so that kick is kept. + */ intv_us = READ_ONCE(scx_bypass_lb_intv_us); if (intv_us) - mod_timer(timer, jiffies + usecs_to_jiffies(intv_us)); + timer_reduce(timer, jiffies + usecs_to_jiffies(intv_us)); +} + +/** + * scx_bypass_lb_kick - Run the bypass load balancer now + * @sch: sched that lost %SCX_CAP_BASE on a cpu + * + * @sch no longer consumes its bypass DSQ on that cpu. Have the balancer drain + * it without waiting for the next interval, see bypass_lb_node(). A loss during + * a run leaves the timer pending at now, and the run that follows sees it. + */ +void scx_bypass_lb_kick(struct scx_sched *sch) +{ + if (scx_bypass_dsp_enabled(sch)) + mod_timer(&sch->bypass_lb_timer, jiffies); } static bool inc_bypass_depth(struct scx_sched *sch) @@ -6184,11 +6396,12 @@ static void enable_bypass_dsp(struct scx_sched *sch) /* * The LB timer will stop running if bypass dispatch is disabled. Start - * after enabling bypass dispatch. + * after enabling bypass dispatch. A kick from a BASE loss can have set + * the timer to expire now in the meantime, see scx_bypass_lb_kick(). + * timer_reduce() keeps that expiry. */ - if (intv_us && !timer_pending(&host->bypass_lb_timer)) - mod_timer(&host->bypass_lb_timer, - jiffies + usecs_to_jiffies(intv_us)); + if (intv_us) + timer_reduce(&host->bypass_lb_timer, jiffies + usecs_to_jiffies(intv_us)); } /* may be called without holding scx_bypass_lock */ @@ -6360,6 +6573,24 @@ void scx_bypass(struct scx_sched *sch, bool bypass) continue; } + /* + * Bypass trumps protection. Cycling the queued tasks below + * clears theirs. The current task isn't on the runnable list, + * so strip its protection here. + * + * When bypass lifts, the current task keeps running on its + * slice without a cap check. Evict it if it can't stay on the + * cpu. + */ + p = rq->curr; + if (p->sched_class == &ext_sched_class && + scx_is_descendant(scx_task_sched(p), sch)) { + if (bypass) + scx_task_slice_ended(rq, p); + else if (!scx_task_can_stay_on_cpu(rq, p)) + scx_set_task_slice(p, 0); + } + /* * The use of list_for_each_entry_safe_reverse() is required * because each task is going to be removed from and added back @@ -6372,13 +6603,6 @@ void scx_bypass(struct scx_sched *sch, bool bypass) if (!scx_is_descendant(scx_task_sched(p), sch)) continue; - /* - * Bypass trumps protection. Cycling clears for queued - * tasks but current task needs explicit stripping. - */ - if (bypass && task_current(rq, p)) - scx_task_slice_ended(rq, p); - /* cycling deq/enq is enough, see the function comment */ scoped_guard (sched_change, p, DEQUEUE_SAVE | DEQUEUE_MOVE) { /* nothing */ ; @@ -6710,6 +6934,8 @@ static void scx_root_disable(struct scx_sched *sch) } } + scx_ops_cid_sched_updated_disable(sch); + /* no task is on scx, turn off all the switches and flush in-progress calls */ static_branch_disable(&__scx_enabled); static_branch_disable(&__scx_is_cid_type); @@ -7902,6 +8128,8 @@ static void scx_root_enable_workfn(struct kthread_work *work) if (((void (**)(void))ops)[i]) set_bit(i, sch->has_op); + scx_ops_cid_sched_updated_enable(sch); + if (sch->ops.cpu_acquire || sch->ops.cpu_release) sch->ops.flags |= SCX_OPS_HAS_CPU_PREEMPT; @@ -8548,6 +8776,8 @@ static void sched_ext_ops_cid__set_cmask(struct task_struct *p, const struct scx static void sched_ext_ops_cid__enable(struct task_struct *p, struct scx_enable_args *args) {} static void sched_ext_ops__sub_caps_updated(const struct scx_cmask *cmask__arena, u64 caps) {} static void sched_ext_ops__sub_ecaps_updated(s32 cid, u64 before, u64 after) {} +static void sched_ext_ops__sub_cid_sched_updated(s32 cid, u64 sched) {} +static void sched_ext_ops__sub_child_ecaps_updated(u64 cgroup_id, s32 cid, u64 before, u64 after) {} static struct sched_ext_ops_cid __bpf_ops_sched_ext_ops_cid = { .select_cid = sched_ext_ops__select_cpu, @@ -8582,6 +8812,8 @@ static struct sched_ext_ops_cid __bpf_ops_sched_ext_ops_cid = { .sub_detach = sched_ext_ops__sub_detach, .sub_caps_updated = sched_ext_ops__sub_caps_updated, .sub_ecaps_updated = sched_ext_ops__sub_ecaps_updated, + .sub_cid_sched_updated = sched_ext_ops__sub_cid_sched_updated, + .sub_child_ecaps_updated = sched_ext_ops__sub_child_ecaps_updated, .cid_online = sched_ext_ops__cpu_online, .cid_offline = sched_ext_ops__cpu_offline, .init_cids = sched_ext_ops__init_cids, @@ -10985,6 +11217,31 @@ static const struct btf_kfunc_id_set scx_kfunc_set_any = { .filter = scx_kfunc_context_filter, }; +/* + * Kfuncs that tracing programs can't call. A tracing program can run in any + * kernel context, including with an rq lock held. scx_locked_rq() only tracks + * rq locks held across SCX callbacks and returns NULL there. + * + * scx_bpf_cpuperf_set() and scx_bpf_cidperf_set() take the target cpu's rq lock + * when scx_locked_rq() returns NULL. Taking it while the context already holds + * an rq lock, the same one or another cpu's, can deadlock. + * + * Before returning, scx_bpf_sub_grant() and scx_bpf_sub_revoke() invoke + * ops.sub_caps_updated() of the sub-schedulers whose caps changed, so those ops + * run in the tracing program's context. No SCX op expects to run from an + * arbitrary tracing context. One that calls scx_bpf_cidperf_set() hits the + * deadlock above. + * + * Members must also stay in scx_kfunc_ids_any so that struct_ops and syscall + * programs keep their access. + */ +BTF_KFUNCS_START(scx_kfunc_ids_no_tracing) +BTF_ID_FLAGS(func, scx_bpf_cpuperf_set, KF_IMPLICIT_ARGS) +BTF_ID_FLAGS(func, scx_bpf_cidperf_set, KF_IMPLICIT_ARGS) +BTF_ID_FLAGS(func, scx_bpf_sub_grant, KF_IMPLICIT_ARGS) +BTF_ID_FLAGS(func, scx_bpf_sub_revoke, KF_IMPLICIT_ARGS) +BTF_KFUNCS_END(scx_kfunc_ids_no_tracing) + /* * cpu-form kfuncs that are forbidden from cid-form schedulers * (bpf_sched_ext_ops_cid). Programs targeting the cid struct_ops type must @@ -11065,6 +11322,7 @@ static const u32 scx_kf_allow_flags[] = { [SCX_OP_IDX(sub_attach)] = SCX_KF_ALLOW_UNLOCKED, [SCX_OP_IDX(sub_detach)] = SCX_KF_ALLOW_UNLOCKED, [SCX_OP_IDX(sub_ecaps_updated)] = SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH, + [SCX_OP_IDX(sub_child_ecaps_updated)] = SCX_KF_ALLOW_ENQUEUE | SCX_KF_ALLOW_DISPATCH, [SCX_OP_IDX(cpu_online)] = SCX_KF_ALLOW_UNLOCKED, [SCX_OP_IDX(cpu_offline)] = SCX_KF_ALLOW_UNLOCKED, [SCX_OP_IDX(init_cids)] = SCX_KF_ALLOW_UNLOCKED | SCX_KF_ALLOW_INIT_CIDS, @@ -11092,6 +11350,7 @@ int scx_kfunc_context_filter(const struct bpf_prog *prog, u32 kfunc_id) bool in_any = btf_id_set8_contains(&scx_kfunc_ids_any, kfunc_id); bool in_cpu_only = btf_id_set8_contains(&scx_kfunc_ids_cpu_only, kfunc_id); bool in_cid = btf_id_set8_contains(&scx_kfunc_ids_cid, kfunc_id); + bool in_no_tracing = btf_id_set8_contains(&scx_kfunc_ids_no_tracing, kfunc_id); u32 moff, flags; /* Not an SCX kfunc - allow. */ @@ -11104,7 +11363,7 @@ int scx_kfunc_context_filter(const struct bpf_prog *prog, u32 kfunc_id) return (in_unlocked || in_select_cpu || in_idle || in_any || in_cid) ? 0 : -EACCES; if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) - return (in_any || in_idle || in_cid) ? 0 : -EACCES; + return (!in_no_tracing && (in_any || in_idle || in_cid)) ? 0 : -EACCES; /* * add_subprog_and_kfunc() collects all kfunc calls, including dead code @@ -11208,6 +11467,8 @@ static int __init scx_init(void) CID_OFFSET_MATCH(sub_detach, sub_detach); CID_OFFSET_MATCH(sub_caps_updated, sub_caps_updated); CID_OFFSET_MATCH(sub_ecaps_updated, sub_ecaps_updated); + CID_OFFSET_MATCH(sub_cid_sched_updated, sub_cid_sched_updated); + CID_OFFSET_MATCH(sub_child_ecaps_updated, sub_child_ecaps_updated); CID_OFFSET_MATCH(init_cids, init_cids); CID_OFFSET_MATCH(init, init); CID_OFFSET_MATCH(exit, exit); diff --git a/kernel/sched/ext/ext.h b/kernel/sched/ext/ext.h index 0b7fc46aee08..3cfbfeb1bf9d 100644 --- a/kernel/sched/ext/ext.h +++ b/kernel/sched/ext/ext.h @@ -20,6 +20,9 @@ void scx_rq_deactivate(struct rq *rq); int scx_check_setscheduler(struct task_struct *p, int policy); bool task_should_scx(int policy); bool scx_allow_ttwu_queue(const struct task_struct *p); +bool scx_allow_proxy_exec(const struct task_struct *p); +void scx_proxy_donor_start(struct rq *rq); +void scx_proxy_reenqueue_retry(struct rq *rq, struct task_struct *next); void init_sched_ext_class(void); static inline u32 scx_cpuperf_target(s32 cpu) @@ -54,6 +57,10 @@ static inline void scx_rq_deactivate(struct rq *rq) {} static inline int scx_check_setscheduler(struct task_struct *p, int policy) { return 0; } static inline bool task_on_scx(const struct task_struct *p) { return false; } static inline bool scx_allow_ttwu_queue(const struct task_struct *p) { return true; } +static inline bool scx_allow_proxy_exec(const struct task_struct *p) { return true; } +static inline void scx_proxy_donor_start(struct rq *rq) {} +static inline void scx_proxy_reenqueue_retry(struct rq *rq, + struct task_struct *next) {} static inline void init_sched_ext_class(void) {} #endif /* CONFIG_SCHED_CLASS_EXT */ diff --git a/kernel/sched/ext/inlines.h b/kernel/sched/ext/inlines.h index 8de9d8fb4b25..1e39d12678c4 100644 --- a/kernel/sched/ext/inlines.h +++ b/kernel/sched/ext/inlines.h @@ -39,10 +39,18 @@ scx_dispatch_sched(struct scx_sched *sch, struct rq *rq, if (scx_consume_global_dsq(sch, rq)) return SCX_DSP_LOCAL; + /* + * A bypass consume puts a task on the cpu being dispatched for, to run + * right away. That is an IMMED insert and needs only + * %SCX_CAP_ENQ_IMMED, the base cap. Dispatch descends into @sch only on + * a cpu where @sch holds the base cap, so @sch holds it here. The same + * holds for the consume at the end of this function. + */ if (scx_bypass_dsp_enabled(sch)) { /* if @sch is bypassing, only the bypass DSQs are active */ if (scx_bypassing(sch, cpu)) { - if (scx_consume_dispatch_q(sch, rq, scx_bypass_dsq(sch, cpu), 0)) + if (scx_consume_dispatch_q(sch, rq, scx_bypass_dsq(sch, cpu), + SCX_ENQ_IMMED)) return SCX_DSP_LOCAL; return SCX_DSP_NONE; } @@ -63,7 +71,8 @@ scx_dispatch_sched(struct scx_sched *sch, struct rq *rq, struct scx_sched_pcpu *pcpu = per_cpu_ptr(sch->pcpu, cpu); if (!(pcpu->bypass_host_seq++ % SCX_BYPASS_HOST_NTH) && - scx_consume_dispatch_q(sch, rq, scx_bypass_dsq(sch, cpu), 0)) { + scx_consume_dispatch_q(sch, rq, scx_bypass_dsq(sch, cpu), + SCX_ENQ_IMMED)) { __scx_add_event(sch, SCX_EV_SUB_BYPASS_DISPATCH, 1); return SCX_DSP_LOCAL; } @@ -135,7 +144,7 @@ scx_dispatch_sched(struct scx_sched *sch, struct rq *rq, * scheduler's ops.dispatch() doesn't yield any tasks. */ if (scx_bypass_dsp_enabled(sch) && - scx_consume_dispatch_q(sch, rq, scx_bypass_dsq(sch, cpu), 0)) { + scx_consume_dispatch_q(sch, rq, scx_bypass_dsq(sch, cpu), SCX_ENQ_IMMED)) { __scx_add_event(sch, SCX_EV_SUB_BYPASS_DISPATCH, 1); return SCX_DSP_LOCAL; } diff --git a/kernel/sched/ext/internal.h b/kernel/sched/ext/internal.h index 352547aedbb7..68703b10d899 100644 --- a/kernel/sched/ext/internal.h +++ b/kernel/sched/ext/internal.h @@ -336,6 +336,18 @@ struct scx_sub_detach_args { char *cgroup_path; }; +/* + * What a sched sees running on a cid, as reported by + * ops.sub_cid_sched_updated(): NONE when the cid is idle or runs a task outside + * the sched's subtree, SELF for the sched itself, or a direct child by its + * cgroup id. The sentinels lie outside the cgroup id space, whose low 32 bits + * are an idr value of at most INT_MAX. + */ +enum scx_cid_sched_consts { + SCX_CID_SCHED_NONE = (u64)-2, + SCX_CID_SCHED_SELF = (u64)-1, +}; + /** * struct sched_ext_ops - Operation table for BPF scheduler implementation * @@ -477,6 +489,12 @@ struct sched_ext_ops { * Therefore, always use scx_bpf_task_cpu(@p) to determine the * target CPU the task is going to use. * + * Under proxy execution, the BPF scheduler continues to observe the + * donor as the current scheduling context. A blocked donor enters a + * ->running()/->stopping() session while its scheduling context drives + * the lock owner. The lock owner executing on its behalf is intentionally + * not reported through these callbacks. + * * See ->runnable() for explanation on the task state notifiers. */ void (*running)(struct task_struct *p); @@ -828,6 +846,11 @@ struct sched_ext_ops { /** * @sub_detach: Detach a sub-scheduler * @args: argument container, see the struct definition + * + * The sub-scheduler holds no caps by this point and can no longer + * affect any cid. Its caps went away without a + * sub_child_ecaps_updated() report, so whatever was delegated to it, + * e.g. cpuperf targets, is the parent's to restore here. */ void (*sub_detach)(struct scx_sub_detach_args *args); @@ -864,6 +887,41 @@ struct sched_ext_ops { */ void (*sub_ecaps_updated)(s32 cid, u64 before, u64 after); + /** + * @sub_cid_sched_updated: The sched running on a cid changed + * @cid: cid whose running sched changed + * @sched: what this sched now sees running there + * + * Invoked when the sched owning the task running on @cid changes. + * @sched is %SCX_CID_SCHED_NONE when no task of this sched's subtree + * runs there, %SCX_CID_SCHED_SELF for its own task, or the cgroup id of + * the direct child whose subtree the task belongs to. Changes inside a + * child's subtree, whether across tasks or nested sub-scheds, are not + * reported. Every sched for which @sched changes is notified. + * + * Runs with the rq lock held on the context switch path. + */ + void (*sub_cid_sched_updated)(s32 cid, u64 sched); + + /** + * @sub_child_ecaps_updated: A child's effective caps on a cid changed + * @cgroup_id: cgroup id of the direct child + * @cid: the cid whose effective caps changed + * @before: the child's effective caps as of the last delivery + * @after: the child's effective caps now + * + * Invoked right after the child's sub_ecaps_updated(), once a grant or + * revoke is in effect on the cpu. From here on the parent can act on a + * cap the child lost, e.g. reset the cpuperf target or schedule on the + * cid. A detaching child's caps go away without a report, see + * sub_detach(). A cpu going offline drops caps without a report. + * + * Runs in dispatch context with rq lock held, and can perform all + * operations allowed in ops.dispatch() including inserting/moving + * tasks. + */ + void (*sub_child_ecaps_updated)(u64 cgroup_id, s32 cid, u64 before, u64 after); + /* * All online ops must come before ops.cpu_online(). */ @@ -911,6 +969,9 @@ struct sched_ext_ops { * ops.exit() is also called on ops.init() failure, which is a bit * unusual. This is to allow rich reporting through @info on how * ops.init() failed. + * + * A sub-scheduler holds no caps by the time ops.exit() runs. Its + * cap-gated kfuncs are denied. */ void (*exit)(struct scx_exit_info *info); @@ -1118,6 +1179,8 @@ struct sched_ext_ops_cid { void (*sub_detach)(struct scx_sub_detach_args *args); void (*sub_caps_updated)(const struct scx_cmask *cmask__arena, u64 caps); void (*sub_ecaps_updated)(s32 cid, u64 before, u64 after); + void (*sub_cid_sched_updated)(s32 cid, u64 sched); + void (*sub_child_ecaps_updated)(u64 cgroup_id, s32 cid, u64 before, u64 after); void (*cid_online)(s32 cid); void (*cid_offline)(s32 cid); s32 (*init_cids)(void); @@ -1380,7 +1443,10 @@ struct scx_sched_pcpu { struct llist_node ecaps_to_sync_node; /* owed a forced update_idle() re-notify on this cpu */ bool idle_renotify; - /* effective caps as of the last sub_ecaps_updated() delivery */ + /* + * ecaps as of the last sub_ecaps_updated() and + * sub_child_ecaps_updated() delivery. See __scx_process_sync_ecaps(). + */ u64 reported_ecaps; /* @@ -2137,6 +2203,7 @@ void scx_cgroup_unlock(void); s32 scx_alloc_kern_arena_objs(struct scx_sched *sch); void scx_disable_bypass_dsp(struct scx_sched *sch); void scx_bypass(struct scx_sched *sch, bool bypass); +void scx_bypass_lb_kick(struct scx_sched *sch); s32 scx_link_sched(struct scx_sched *sch); void scx_unlink_sched(struct scx_sched *sch); void scx_disable_dump(struct scx_sched *sch); @@ -2539,4 +2606,21 @@ static inline struct scx_sched *scx_parent(struct scx_sched *sch) { return NULL; #endif /* CONFIG_EXT_SUB_SCHED */ +/** + * scx_exec_sched - Find the sched running @sch's tasks on @cpu + * @sch: sched owning the tasks + * @cpu: cpu of interest + * + * A bypassing sched's tasks are run by its nearest ancestor that isn't + * bypassing. Return @sch if it isn't bypassing on @cpu, otherwise that + * ancestor, or the root if every ancestor is bypassing. Hold @cpu's rq lock for + * a stable answer. + */ +static inline struct scx_sched *scx_exec_sched(struct scx_sched *sch, s32 cpu) +{ + while (scx_parent(sch) && scx_bypassing(sch, cpu)) + sch = scx_parent(sch); + return sch; +} + #endif /* _KERNEL_SCHED_EXT_INTERNAL_H */ diff --git a/kernel/sched/ext/sub.c b/kernel/sched/ext/sub.c index 212de1cb8502..cb75d1912a7b 100644 --- a/kernel/sched/ext/sub.c +++ b/kernel/sched/ext/sub.c @@ -28,6 +28,13 @@ */ DEFINE_STATIC_KEY_FALSE(__scx_has_subs); +/* + * On while a loaded sched implements ops.sub_cid_sched_updated(), see + * scx_ops_cid_sched_updated_enable(). + */ +static DEFINE_STATIC_KEY_FALSE(__scx_ops_cid_sched_updated_enabled); +static s32 scx_nr_ops_cid_sched_updated; /* such scheds, under scx_enable_mutex */ + /* latched at root enable before any rescue runs */ static s32 scx_rescue_bw_1024; static s64 scx_rescue_quantum_ns; @@ -92,6 +99,161 @@ struct scx_sched *scx_next_descendant_pre(struct scx_sched *pos, struct scx_sche return scx_skip_subtree_pre(pos, root); } +/** + * scx_cid_sched_id_from - Resolve what @from sees when @sch runs on a cid + * @sch: sched whose task runs there, %NULL for none + * @from: sched asking + * + * Return %SCX_CID_SCHED_NONE when @sch is %NULL or outside @from's subtree, + * %SCX_CID_SCHED_SELF for @from itself, or else the cgroup id of the direct + * child of @from on the way down to @sch. + */ +static u64 scx_cid_sched_id_from(struct scx_sched *sch, struct scx_sched *from) +{ + if (!sch || !scx_is_descendant(sch, from)) + return SCX_CID_SCHED_NONE; + if (sch == from) + return SCX_CID_SCHED_SELF; + return sch->ancestors[from->level + 1]->ops.sub_cgroup_id; +} + +/* notify @from of what it now sees running on @rq's cid */ +static void scx_cid_notify_sched_updated(struct rq *rq, struct scx_sched *sch, + struct scx_sched *from) +{ + if (SCX_HAS_OP(from, sub_cid_sched_updated)) + SCX_CALL_OP(from, sub_cid_sched_updated, rq, __scx_cpu_to_cid(cpu_of(rq)), + scx_cid_sched_id_from(sch, from)); +} + +/** + * scx_cid_sched_update - Update rq->scx.sched and notify the scheds affected + * @rq: rq whose running session opens or closes + * @sch: sched starting a session, %NULL to close the open one + * + * Every sched whose scx_cid_sched_id_from() value changes is notified of the + * new one. Above the deepest common ancestor of the two scheds, both map to the + * same child, so the walk stops there. With root R, children A and B, and A's + * child A1, a switch from an A1 task to a B task reports: + * + * R R: A -> B + * / \ + * A B A: A1 -> NONE B: NONE -> SELF + * | + * A1 A1: SELF -> NONE + * + * When the task on one side is not an ext task, there is no common ancestor and + * only the other side is walked. + */ +void scx_cid_sched_update(struct rq *rq, struct scx_sched *sch) +{ + struct scx_sched *prev = rq->scx.sched; + s32 level, common = -1; + + lockdep_assert_rq_held(rq); + + if (!static_branch_unlikely(&__scx_ops_cid_sched_updated_enabled) || prev == sch) + return; + + rq->scx.sched = sch; + + if (prev && sch) { + for (level = min(prev->level, sch->level); level >= 0; level--) + if (prev->ancestors[level] == sch->ancestors[level]) + break; + common = level; + scx_cid_notify_sched_updated(rq, sch, prev->ancestors[common]); + } + if (prev) + for (level = common + 1; level <= prev->level; level++) + scx_cid_notify_sched_updated(rq, sch, prev->ancestors[level]); + if (sch) + for (level = common + 1; level <= sch->level; level++) + scx_cid_notify_sched_updated(rq, sch, sch->ancestors[level]); +} + +/** + * scx_ops_cid_sched_updated_enable - Maintain rq->scx.sched if @sch has the op + * @sch: sched being enabled, its has_op filled in + * + * rq->scx.sched is maintained only while a loaded sched implements + * ops.sub_cid_sched_updated(), so that everyone else pays one static branch per + * session open or close. The first such sched turns the key on and then + * initializes every rq from the task running there, in that order so that no + * session change in between goes unrecorded. While the key is off every + * rq->scx.sched is NULL, see scx_ops_cid_sched_updated_disable(). + */ +void scx_ops_cid_sched_updated_enable(struct scx_sched *sch) +{ + s32 cpu; + + lockdep_assert_held(&scx_enable_mutex); + + if (!SCX_HAS_OP(sch, sub_cid_sched_updated) || scx_nr_ops_cid_sched_updated++) + return; + + static_branch_enable(&__scx_ops_cid_sched_updated_enabled); + + for_each_possible_cpu(cpu) { + struct rq *rq = cpu_rq(cpu); + struct task_struct *p; + + guard(rq_lock_irqsave)(rq); + p = rq->donor; + if (p->sched_class == &ext_sched_class && + (p->scx.flags & SCX_TASK_RUN_TRACKED)) + rq->scx.sched = scx_task_sched(p); + } +} + +/** + * scx_ops_cid_sched_updated_disable - Stop maintaining rq->scx.sched for @sch + * @sch: sched being disabled, its tasks all gone + * + * Close the session on every rq that still points at @sch, before ops.exit(), + * so that no sched is notified of @sch once it is gone. The last sched with the + * op turns the key off first and clears every rq, so while the key is off every + * rq->scx.sched is NULL. A sched whose enable failed before its has_op fill was + * never counted, so has_op gates the decrement. + */ +void scx_ops_cid_sched_updated_disable(struct scx_sched *sch) +{ + bool last; + s32 cpu; + + lockdep_assert_held(&scx_enable_mutex); + + last = SCX_HAS_OP(sch, sub_cid_sched_updated) && !--scx_nr_ops_cid_sched_updated; + if (last) + static_branch_disable(&__scx_ops_cid_sched_updated_enabled); + + /* + * Re-homing restarts a running task's session under its new sched. A + * task that blocked while its cpu's dispatch had the rq lock dropped is + * put and set next again without a restart, so rq->scx.sched keeps @sch + * until the pick completes: + * + * cpu 0, __schedule() cpu 1, scx_sub_disable(@sch) + * T of @sch blocks, stops running + * dispatch drops the rq lock + * re-home T, nothing to restart + * this sweep + * pick N, N's session opens + * + * Closing the session here reports NONE to @sch and its ancestors now + * and lets the pick report N's sched from NONE instead of from @sch. + */ + for_each_possible_cpu(cpu) { + struct rq *rq = cpu_rq(cpu); + + guard(rq_lock_irqsave)(rq); + if (rq->scx.sched == sch) + scx_cid_sched_update(rq, NULL); + if (last) + rq->scx.sched = NULL; + } +} + static struct scx_sched *scx_find_sub_sched(u64 cgroup_id) { return rhashtable_lookup(&scx_sched_hash, &cgroup_id, @@ -239,9 +401,7 @@ void scx_init_root_caps(struct scx_sched *sch) /* unserved remainder of @rq's rescuee's admitted slice, 0 once fully served */ static s64 scx_rescue_slice_remaining(struct rq *rq) { - s64 served = rq->scx.rescue.curr->se.sum_exec_runtime - rq->scx.rescue.exec_snap; - - return max(rq->scx.rescue.slice - served, 0); + return max(rq->scx.rescue.slice - rq->scx.rescue.served, 0); } /* @@ -276,6 +436,14 @@ void scx_rescue_charge(struct rq *rq, s64 delta_exec) lockdep_assert_rq_held(rq); + /* + * Count @delta_exec as served before the clamp below, which bounds only + * the budget charge. update_curr_scx() took the same delta off the + * slice, so a slice set to the unserved remainder, as escalation does, + * reaches zero when the remainder does, see scx_rescue_keep(). + */ + rq->scx.rescue.served += delta_exec; + /* * A rescue slice is bounded by one quantum and tick-driven expiry can * overshoot by up to a tick. Clamp to avoid wild over-charges on VMs. @@ -335,7 +503,9 @@ bool scx_rescue_keep(struct rq *rq, struct task_struct *p) scx_bypassing(scx_task_sched(p), cpu_of(rq))) return false; - scx_set_task_slice(p, remaining); + /* never called on a protected rescuee, so the write can't be refused */ + if (WARN_ON_ONCE(!scx_set_task_slice(p, remaining))) + return false; return true; } @@ -418,10 +588,9 @@ static void scx_rescue_timer_arm(struct rq *rq) * @slice: CPU time to grant * * The schedulers keep their normal control over @p and may preempt or reslice - * it. @slice is measured on served CPU time against the snapshot taken here, so - * neither shortens the rescue, see scx_rescue_charge() and scx_rescue_keep(). - * Prolonged denial escalates into protected execution, see - * scx_rescue_timerfn(). + * it. @slice is measured on served CPU time, so neither shortens the rescue, + * see scx_rescue_charge() and scx_rescue_keep(). Prolonged denial escalates + * into protected execution, see scx_rescue_timerfn(). */ static void scx_rescue_admit(struct rq *rq, struct task_struct *p, s64 slice) { @@ -430,7 +599,7 @@ static void scx_rescue_admit(struct rq *rq, struct task_struct *p, s64 slice) rq->scx.rescue.curr = p; rq->scx.rescue.slice = slice; - rq->scx.rescue.exec_snap = p->se.sum_exec_runtime; + rq->scx.rescue.served = 0; scx_set_task_slice(p, slice); scx_rescue_timer_arm(rq); } @@ -755,18 +924,21 @@ struct scx_dispatch_q *scx_resolve_local_dsq(struct scx_sched *sch, struct rq *r /* @p lost the caps needed to stay on @rq's local DSQ? Record reason if so. */ bool scx_task_reenq_on_cap_revoke(struct rq *rq, struct task_struct *p) { + s32 cpu = cpu_of(rq); u64 missing; /* migration-disabled tasks and the rescuee are admitted capless */ if (is_migration_disabled(p) || p == scx_rescuee(rq)) return false; - missing = scx_missing_caps(scx_task_sched(p), cpu_of(rq), scx_caps_for_task(p)); + /* check caps against the sched running a bypassed task */ + missing = scx_missing_caps(scx_exec_sched(scx_task_sched(p), cpu), cpu, + scx_caps_for_task(p)); if (likely(!missing)) return false; p->scx.reenq_reason_caps = missing; - p->scx.reenq_reason_cid = __scx_cpu_to_cid(cpu_of(rq)); + p->scx.reenq_reason_cid = __scx_cpu_to_cid(cpu); return true; } @@ -1008,27 +1180,51 @@ void scx_process_sync_ecaps(struct rq *rq, struct task_struct *prev) lost_all |= lost; /* - * Tell the sched its effective caps on this cid changed. The - * invocation is equivalent to the dispatch path and may drop - * and re-acquire the rq lock temporarily while the rest of - * @batch is held privately, see scx_discard_ecaps_to_sync(). - * The dispatch kfuncs resolve their context on the executing - * cpu, which under core scheduling can differ from @rq's cpu, - * so the context is set up there. The rq recorded in it keeps - * the dispatches targeting @rq. + * The bypass DSQ on this cpu is no longer consumed, so drain + * it. A bypassing sched's own bypass DSQs are empty, as its + * tasks sit on the host's. */ - if (ecaps != pcpu->reported_ecaps && - SCX_HAS_OP(pcpu->sch, sub_ecaps_updated) && - !scx_bypassing(pcpu->sch, cpu)) { - struct scx_dsp_ctx *dspc = &this_cpu_ptr(pcpu->sch->pcpu)->dsp_ctx; + if ((lost & SCX_CAP_BASE) && !scx_bypassing(pcpu->sch, cpu)) + scx_bypass_lb_kick(pcpu->sch); + + /* + * Tell the sched and its parent that the sched's effective caps + * on this cid changed. The invocations are equivalent to the + * dispatch path and may drop and re-acquire the rq lock + * temporarily while the rest of @batch is held privately, see + * scx_discard_ecaps_to_sync(). The dispatch kfuncs resolve + * their context on the executing cpu, which under core + * scheduling can differ from @rq's cpu, so the context is set + * up there. The rq recorded in it keeps the dispatches + * targeting @rq. + * + * Bypass propagates down the hierarchy, so a sched that isn't + * bypassing has no bypassing parent. The child's bypass state + * gates both deliveries. Both report the same before value, so + * one reported_ecaps covers them. + */ + if (ecaps != pcpu->reported_ecaps && !scx_bypassing(pcpu->sch, cpu)) { + struct scx_sched *parent = scx_parent(pcpu->sch); + struct scx_dsp_ctx *dspc; - dspc->rq = rq; /* stash @prev so nested dispatches can access it */ rq->scx.sub_dispatch_prev = prev; - SCX_CALL_OP(pcpu->sch, sub_ecaps_updated, rq, scx_cpu_arg(cpu), - pcpu->reported_ecaps, ecaps); + if (SCX_HAS_OP(pcpu->sch, sub_ecaps_updated)) { + dspc = &this_cpu_ptr(pcpu->sch->pcpu)->dsp_ctx; + dspc->rq = rq; + SCX_CALL_OP(pcpu->sch, sub_ecaps_updated, rq, + scx_cpu_arg(cpu), pcpu->reported_ecaps, ecaps); + scx_flush_dispatch_buf(pcpu->sch, rq); + } + if (SCX_HAS_OP(parent, sub_child_ecaps_updated)) { + dspc = &this_cpu_ptr(parent->pcpu)->dsp_ctx; + dspc->rq = rq; + SCX_CALL_OP(parent, sub_child_ecaps_updated, rq, + pcpu->sch->ops.sub_cgroup_id, scx_cpu_arg(cpu), + pcpu->reported_ecaps, ecaps); + scx_flush_dispatch_buf(parent, rq); + } rq->scx.sub_dispatch_prev = NULL; - scx_flush_dispatch_buf(pcpu->sch, rq); pcpu->reported_ecaps = ecaps; } @@ -1153,6 +1349,34 @@ void scx_offline_ecaps(struct rq *rq) } } +/* + * Clear every cap @sch holds. The pshard caps go first as they are the source a + * pending sync recomputes ecaps from. ecaps are then zeroed directly for the + * cap checks. + */ +static void clear_all_caps(struct scx_sched *sch) +{ + s32 si, cpu; + u32 cap_bit; + + /* enable may have failed before scx_alloc_pshards() */ + if (!sch->pshard) + return; + + for (si = 0; si < sch->nr_pshards; si++) { + struct scx_pshard *ps = sch->pshard[si]; + + guard(raw_spinlock_irqsave)(&ps->lock); + for (cap_bit = 0; cap_bit < __SCX_NR_CAPS; cap_bit++) + scx_cmask_clear(&ps->caps[cap_bit].cmask); + } + + for_each_possible_cpu(cpu) { + guard(rq_lock_irqsave)(cpu_rq(cpu)); + WRITE_ONCE(per_cpu_ptr(sch->pcpu, cpu)->ecaps, 0); + } +} + /* * @pcpu's sched was unhashed before the grace period, so nothing re-queues its * sync node. Remove the node from @rq's pending list so the pcpu can be freed. @@ -1616,6 +1840,8 @@ void scx_sub_disable(struct scx_sched *sch) scx_cgroup_unlock(); percpu_up_write(&scx_fork_rwsem); + scx_ops_cid_sched_updated_disable(sch); + /* * All tasks are moved off of @sch but there may still be on-going * operations (e.g. ops.select_cpu()). Drain them by flushing RCU. Use @@ -1628,6 +1854,12 @@ void scx_sub_disable(struct scx_sched *sch) scx_unlink_sched(sch); + /* + * The parent restores what it delegated in ops.sub_detach(). @sch must + * hold no caps by then. + */ + clear_all_caps(sch); + mutex_unlock(&scx_enable_mutex); /* @@ -1787,6 +2019,15 @@ void scx_sub_enable_workfn(struct kthread_work *work) if (ret) goto err_disable; + /* + * Bypass before @sch is linked and grants can reach it. The parent's + * delivery advances reported_ecaps, so a sync consumed before @sch's + * ops are registered would reach the parent and never be replayed to + * @sch. While bypassed, the syncs are consumed without a delivery and + * replayed to both at unbypass. + */ + scx_bypass(sch, true); + ret = scx_link_sched(sch); if (ret) goto err_disable; @@ -1832,12 +2073,12 @@ void scx_sub_enable_workfn(struct kthread_work *work) } sch->sub_attached = true; - scx_bypass(sch, true); - for (i = SCX_OPI_BEGIN; i < SCX_OPI_END; i++) if (((void (**)(void))ops)[i]) set_bit(i, sch->has_op); + scx_ops_cid_sched_updated_enable(sch); + percpu_down_write(&scx_fork_rwsem); scx_cgroup_lock(); @@ -2220,6 +2461,12 @@ __bpf_kfunc_start_defs(); * child schedulers. The child scheduler runs its dispatch operation to * move tasks from dispatch queues to the local runqueue. * + * Dispatch into a child while the local DSQ is empty, when the cpu needs a + * task. A child holding only %SCX_CAP_ENQ_IMMED can insert only IMMED tasks, + * and the consume of its bypassing descendants' bypass DSQs is one such insert. + * With a task already queued on the local DSQ, such an insert fails and the + * task is reenqueued. + * * Returns: true on success, false if cgroup_id is invalid, not a direct * child, or caller lacks dispatch permission. */ @@ -2306,8 +2553,8 @@ static s32 sub_cap_preamble(u64 cgroup_id, u64 caps, const struct bpf_prog_aux * * All-or-nothing keeps the caller-visible result binary per cid, so the denied * mask is one mask to interpret rather than a per-cap matrix. * - * Return 0 on full success, -EPERM if any cid was refused, or a negative - * errno on other failures. + * Return 0 on full success, -EPERM if any cid was refused, -ENODEV if the child + * is gone or being disabled, or a negative errno on other failures. */ __bpf_kfunc s32 scx_bpf_sub_grant(u64 cgroup_id, u64 caps, const struct scx_cmask *cmask__arena, @@ -2361,6 +2608,12 @@ __bpf_kfunc s32 scx_bpf_sub_grant(u64 cgroup_id, u64 caps, scoped_guard (raw_spinlock, &pps->lock) { guard(raw_spinlock_nested)(&cps->lock); + /* the child is being disabled, see clear_all_caps() */ + if (unlikely(READ_ONCE(child->aborting))) { + ret = -ENODEV; + goto out; + } + /* * Narrow granted_cids to cids the parent holds every * requested cap on. All-or-nothing per cid. @@ -2413,9 +2666,10 @@ __bpf_kfunc s32 scx_bpf_sub_grant(u64 cgroup_id, u64 caps, } } + ret = any_denied ? -EPERM : 0; +out: caps_updated_deliver(&to_deliver); - - return any_denied ? -EPERM : 0; + return ret; } /** diff --git a/kernel/sched/ext/sub.h b/kernel/sched/ext/sub.h index f7bcdfda8dd8..bcf0ab51e531 100644 --- a/kernel/sched/ext/sub.h +++ b/kernel/sched/ext/sub.h @@ -16,6 +16,9 @@ struct scx_sched *scx_skip_subtree_pre(struct scx_sched *pos, struct scx_sched *root); struct scx_sched *scx_next_descendant_pre(struct scx_sched *pos, struct scx_sched *root); +void scx_cid_sched_update(struct rq *rq, struct scx_sched *sch); +void scx_ops_cid_sched_updated_enable(struct scx_sched *sch); +void scx_ops_cid_sched_updated_disable(struct scx_sched *sch); void scx_set_task_sched(struct task_struct *p, struct scx_sched *sch); struct cgroup *sch_cgroup(struct scx_sched *sch); void set_cgroup_sched(struct cgroup *cgrp, struct scx_sched *sch); @@ -76,6 +79,9 @@ static inline void scx_dec_has_subs(struct scx_sched *sch) static inline struct scx_sched *scx_next_descendant_pre(struct scx_sched *pos, struct scx_sched *root) { return pos ? NULL : root; } static inline struct scx_sched *scx_skip_subtree_pre(struct scx_sched *pos, struct scx_sched *root) { return NULL; } +static inline void scx_cid_sched_update(struct rq *rq, struct scx_sched *sch) {} +static inline void scx_ops_cid_sched_updated_enable(struct scx_sched *sch) {} +static inline void scx_ops_cid_sched_updated_disable(struct scx_sched *sch) {} static inline void scx_set_task_sched(struct task_struct *p, struct scx_sched *sch) {} static inline struct cgroup *sch_cgroup(struct scx_sched *sch) { return NULL; } static inline const char *sch_cgrp_path(struct scx_sched *sch) { return "/"; } @@ -199,6 +205,8 @@ static inline u64 scx_caps_implied(u64 cap) /* may @p keep running on @rq's cpu? requires baseline cpu access */ static inline bool scx_task_can_stay_on_cpu(struct rq *rq, struct task_struct *p) { + s32 cpu = cpu_of(rq); + if (!scx_has_subs()) return true; @@ -206,7 +214,9 @@ static inline bool scx_task_can_stay_on_cpu(struct rq *rq, struct task_struct *p if (unlikely(is_migration_disabled(p))) return true; - return likely(!scx_missing_caps(scx_task_sched(p), cpu_of(rq), SCX_CAP_BASE)); + /* check caps against the sched running a bypassed task */ + return likely(!scx_missing_caps(scx_exec_sched(scx_task_sched(p), cpu), cpu, + SCX_CAP_BASE)); } /* the task admitted for rescue on @rq, NULL if none */ diff --git a/kernel/sched/fair.c b/kernel/sched/fair.c index 913630c0b059..327d5f8f4596 100644 --- a/kernel/sched/fair.c +++ b/kernel/sched/fair.c @@ -12128,6 +12128,14 @@ static void record_sg_llc_stats(struct lb_env *env, if (env->sd->child != rcu_dereference_all(per_cpu(sd_llc, env->dst_cpu))) return; + /* + * A redo repeats stats published on the first pass. Hotplug can + * still leave env->cpus partial, so util would not match capacity. + */ + if ((env->flags & LBF_ALL_PINNED) || + !cpumask_subset(sched_group_span(group), env->cpus)) + return; + /* * At this point we know this group spans a LLC domain. * Record the statistic of this group in its corresponding @@ -15539,14 +15547,18 @@ static void switched_to_fair(struct rq *rq, struct task_struct *p) } } -static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first) +static void set_next_task_fair(struct rq *rq, struct task_struct *p, enum snt_e type) { struct sched_entity *se = &p->se; - bool throttled = false; struct cfs_rq *cfs_rq = &rq->cfs; unsigned long weight = NICE_0_LOAD; + bool first = type == SNT_PICK; + bool throttled = false; bool on_rq = se->on_rq; + if (type == SNT_REPICK) + goto repick; + clear_buddies(cfs_rq, se); if (on_rq) @@ -15590,11 +15602,18 @@ static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first) WARN_ON_ONCE(se->sched_delayed); - if (hrtick_enabled_fair(rq)) - hrtick_start_fair(rq, p); - update_misfit_status(p, rq); sched_fair_update_stop_tick(rq, p); + +repick: + /* + * A same-task repick skips put_prev_task_fair(), but + * pick_task_fair() refreshed the entity hrtick_start_fair() reads + * before selecting it again. rq->cfs.curr identifies that entity, + * including with group scheduling. + */ + if (hrtick_enabled_fair(rq)) + hrtick_start_fair(rq, p); } void init_cfs_rq(struct cfs_rq *cfs_rq) diff --git a/kernel/sched/idle.c b/kernel/sched/idle.c index eb73b65ce6c4..e0c10a5dbda2 100644 --- a/kernel/sched/idle.c +++ b/kernel/sched/idle.c @@ -429,13 +429,17 @@ void play_idle_precise(u64 duration_ns, u64 latency_ns) cpuidle_use_deepest_state(latency_ns); it.done = 0; - hrtimer_setup_on_stack(&it.timer, idle_inject_timer_fn, CLOCK_MONOTONIC, - HRTIMER_MODE_REL_HARD); - hrtimer_start(&it.timer, ns_to_ktime(duration_ns), - HRTIMER_MODE_REL_PINNED_HARD); + { + CLASS(hrtimer_on_stack, timer)(&it.timer, idle_inject_timer_fn, + CLOCK_MONOTONIC, + HRTIMER_MODE_REL_HARD); - while (!READ_ONCE(it.done)) - do_idle(); + hrtimer_start(timer, ns_to_ktime(duration_ns), + HRTIMER_MODE_REL_PINNED_HARD); + + while (!READ_ONCE(it.done)) + do_idle(); + } cpuidle_use_deepest_state(0); current->flags &= ~PF_IDLE; @@ -487,8 +491,11 @@ static void put_prev_task_idle(struct rq *rq, struct task_struct *prev, struct t update_rq_avg_idle(rq); } -static void set_next_task_idle(struct rq *rq, struct task_struct *next, bool first) +static void set_next_task_idle(struct rq *rq, struct task_struct *next, enum snt_e type) { + if (type == SNT_REPICK) + return; + update_idle_core(rq); scx_update_idle(rq, true, true); schedstat_inc(rq->sched_goidle); diff --git a/kernel/sched/rt.c b/kernel/sched/rt.c index 85303add726d..1535046a23ff 100644 --- a/kernel/sched/rt.c +++ b/kernel/sched/rt.c @@ -1654,11 +1654,14 @@ static void wakeup_preempt_rt(struct rq *rq, struct task_struct *p, int flags) check_preempt_equal_prio(rq, p); } -static inline void set_next_task_rt(struct rq *rq, struct task_struct *p, bool first) +static inline void set_next_task_rt(struct rq *rq, struct task_struct *p, enum snt_e type) { struct sched_rt_entity *rt_se = &p->rt; struct rt_rq *rt_rq = &rq->rt; + if (type == SNT_REPICK) + return; + p->se.exec_start = rq_clock_task(rq); if (on_rt_rq(&p->rt)) update_stats_wait_end_rt(rt_rq, rt_se); @@ -1666,7 +1669,7 @@ static inline void set_next_task_rt(struct rq *rq, struct task_struct *p, bool f /* The running task is never eligible for pushing */ dequeue_pushable_task(rq, p); - if (!first) + if (type != SNT_PICK) return; /* diff --git a/kernel/sched/sched.h b/kernel/sched/sched.h index 4c25fbe84fb5..8d805aa7c85d 100644 --- a/kernel/sched/sched.h +++ b/kernel/sched/sched.h @@ -803,7 +803,7 @@ struct scx_rq_rescue { u64 clock; /* last budget accrual timestamp */ struct task_struct *curr; /* task being rescued, one at a time */ s64 slice; /* curr's admitted slice */ - u64 exec_snap; /* sum_exec_runtime at admission */ + s64 served; /* curr's served time */ struct timer_list timer; /* paces admission and escalation */ u64 kill_at; /* last ejection, init before any */ }; @@ -830,6 +830,8 @@ struct scx_rq { #endif u64 clock; /* current per-rq clock -- see scx_bpf_now() */ #ifdef CONFIG_EXT_SUB_SCHED + /* sched of the open running session, see scx_cid_sched_update() */ + struct scx_sched *sched; struct llist_head ecaps_to_sync; /* pending ecaps syncs */ struct task_struct *sub_dispatch_prev; #endif @@ -2620,6 +2622,12 @@ struct affinity_context { extern s64 update_curr_common(struct rq *rq); +enum snt_e { + SNT_NORMAL, /* set_next_task() */ + SNT_PICK, /* put_prev_set_next_task(): prev != next */ + SNT_REPICK, /* put_prev_set_next_task(): prev == next */ +}; + struct sched_class { #ifdef CONFIG_UCLAMP_TASK @@ -2677,7 +2685,7 @@ struct sched_class { * __schedule: rq->lock */ void (*put_prev_task)(struct rq *rq, struct task_struct *p, struct task_struct *next); - void (*set_next_task)(struct rq *rq, struct task_struct *p, bool first); + void (*set_next_task)(struct rq *rq, struct task_struct *p, enum snt_e type); /* * select_task_rq: p->pi_lock @@ -2780,7 +2788,7 @@ static inline void put_prev_task(struct rq *rq, struct task_struct *prev) static inline void set_next_task(struct rq *rq, struct task_struct *next) { - next->sched_class->set_next_task(rq, next, false); + next->sched_class->set_next_task(rq, next, SNT_NORMAL); } static inline void @@ -2801,11 +2809,13 @@ static inline void put_prev_set_next_task(struct rq *rq, __put_prev_set_next_dl_server(rq, prev, next); - if (next == prev) + if (next == prev) { + next->sched_class->set_next_task(rq, next, SNT_REPICK); return; + } prev->sched_class->put_prev_task(rq, prev, next); - next->sched_class->set_next_task(rq, next, true); + next->sched_class->set_next_task(rq, next, SNT_PICK); } /* diff --git a/kernel/sched/stop_task.c b/kernel/sched/stop_task.c index c909ca0d8c87..1e0109ec36b3 100644 --- a/kernel/sched/stop_task.c +++ b/kernel/sched/stop_task.c @@ -27,8 +27,11 @@ wakeup_preempt_stop(struct rq *rq, struct task_struct *p, int flags) /* we're never preempted */ } -static void set_next_task_stop(struct rq *rq, struct task_struct *stop, bool first) +static void set_next_task_stop(struct rq *rq, struct task_struct *stop, enum snt_e type) { + if (type == SNT_REPICK) + return; + stop->se.exec_start = rq_clock_task(rq); } diff --git a/kernel/signal.c b/kernel/signal.c index 6e3950939acb..f13be2963332 100644 --- a/kernel/signal.c +++ b/kernel/signal.c @@ -684,12 +684,13 @@ static int dequeue_synchronous_signal(kernel_siginfo_t *info) return 0; /* - * Return the first synchronous signal in the queue. + * Return the first unblocked synchronous signal in the queue. */ list_for_each_entry(q, &pending->list, list) { /* Synchronous signals have a positive si_code */ if ((q->info.si_code > SI_USER) && - (sigmask(q->info.si_signo) & SYNCHRONOUS_MASK)) { + (sigmask(q->info.si_signo) & SYNCHRONOUS_MASK) && + !sigismember(&tsk->blocked, q->info.si_signo)) { sync = q; goto next; } diff --git a/kernel/time/hrtimer.c b/kernel/time/hrtimer.c index cbf1693c86b3..12e136d5691f 100644 --- a/kernel/time/hrtimer.c +++ b/kernel/time/hrtimer.c @@ -1975,8 +1975,12 @@ EXPORT_SYMBOL_GPL(hrtimer_setup); * @clock_id: The clock to be used * @mode: The timer mode * - * Similar to hrtimer_setup(), except that this one must be used if struct hrtimer is in stack - * memory. + * Similar to hrtimer_setup(), except that this one must be used if struct + * hrtimer is in stack memory. + * + * Callers that do not use the hrtimer_on_stack cleanup class must call + * destroy_hrtimer_on_stack() before the stack storage goes out of scope. The + * cleanup class pairs setup and destruction automatically. */ void hrtimer_setup_on_stack(struct hrtimer *timer, enum hrtimer_restart (*function)(struct hrtimer *), diff --git a/kernel/time/tick-sched.c b/kernel/time/tick-sched.c index baa3ac9b48f8..6546e196645f 100644 --- a/kernel/time/tick-sched.c +++ b/kernel/time/tick-sched.c @@ -775,12 +775,18 @@ static ktime_t tick_forward_now(ktime_t expires, ktime_t now) return expires + TICK_NSEC; } +static void tick_nohz_forward_last_tick(struct tick_sched *ts, ktime_t now) +{ + if (now >= ts->last_tick) + ts->last_tick = tick_forward_now(ts->last_tick, now); +} + static void tick_nohz_restart(struct tick_sched *ts, ktime_t now) { - ktime_t expires = ts->last_tick; + ktime_t expires; - if (now >= expires) - expires = tick_forward_now(expires, now); + tick_nohz_forward_last_tick(ts, now); + expires = ts->last_tick; if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES)) { hrtimer_start(&ts->sched_timer, expires, HRTIMER_MODE_ABS_PINNED_HARD); @@ -1341,6 +1347,12 @@ unsigned long tick_nohz_get_idle_calls_cpu(int cpu) return ts->idle_calls; } +static void tick_nohz_dyntick_stop(struct tick_sched *ts, ktime_t now) +{ + tick_nohz_forward_last_tick(ts, now); + kcpustat_dyntick_stop(now, ts->last_tick - TICK_NSEC); +} + void tick_nohz_idle_restart_tick(void) { struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched); @@ -1353,7 +1365,7 @@ void tick_nohz_idle_restart_tick(void) * no tiny amount of idle time is accounted twice. */ ts->idle_entrytime = ktime_get(); - kcpustat_dyntick_stop(ts->idle_entrytime); + tick_nohz_dyntick_stop(ts, ts->idle_entrytime); tick_nohz_restart_sched_tick(ts, ts->idle_entrytime); } } @@ -1397,7 +1409,7 @@ void tick_nohz_idle_exit(void) if (tick_sched_flag_test(ts, TS_FLAG_STOPPED)) { now = ktime_get(); - kcpustat_dyntick_stop(now); + tick_nohz_dyntick_stop(ts, now); tick_nohz_idle_update_tick(ts, now); } diff --git a/kernel/time/timeconv.c b/kernel/time/timeconv.c index 59b922c826e7..aed3af950fa0 100644 --- a/kernel/time/timeconv.c +++ b/kernel/time/timeconv.c @@ -49,8 +49,9 @@ void time64_to_tm(time64_t totalsecs, int offset, struct tm *result) u32 u32tmp, day_of_century, year_of_century, day_of_year, month, day; u64 u64tmp, udays, century, year; bool is_Jan_or_Feb, is_leap_year; - long days, rem; int remainder; + long rem; + s64 days; days = div_s64_rem(totalsecs, SECS_PER_DAY, &remainder); rem = remainder; @@ -70,7 +71,8 @@ void time64_to_tm(time64_t totalsecs, int offset, struct tm *result) result->tm_sec = rem % 60; /* January 1, 1970 was a Thursday. */ - result->tm_wday = (4 + days) % 7; + div_s64_rem(days + 4, 7, &remainder); + result->tm_wday = remainder; if (result->tm_wday < 0) result->tm_wday += 7; diff --git a/kernel/time/timer.c b/kernel/time/timer.c index ae9abf14688e..fc374444acb6 100644 --- a/kernel/time/timer.c +++ b/kernel/time/timer.c @@ -44,6 +44,7 @@ #include #include #include +#include #include #include @@ -2541,6 +2542,7 @@ int timers_dead_cpu(unsigned int cpu) for (i = 0; i < WHEEL_SIZE; i++) migrate_timer_list(new_base, old_base->vectors + i); + bitmap_zero(old_base->pending_map, WHEEL_SIZE); raw_spin_unlock(&old_base->lock); raw_spin_unlock_irq(&new_base->lock); put_cpu_ptr(&timer_bases); diff --git a/kernel/time/vsyscall.c b/kernel/time/vsyscall.c index aa59919b8f2c..0e4b499328c0 100644 --- a/kernel/time/vsyscall.c +++ b/kernel/time/vsyscall.c @@ -41,14 +41,12 @@ static inline void update_vdso_time_data(struct vdso_time_data *vdata, struct ti nsec = tk->tkr_mono.xtime_nsec; nsec += ((u64)tk->wall_to_monotonic.tv_nsec << tk->tkr_mono.shift); - while (nsec >= (((u64)NSEC_PER_SEC) << tk->tkr_mono.shift)) { - nsec -= (((u64)NSEC_PER_SEC) << tk->tkr_mono.shift); - vdso_ts->sec++; - } - vdso_ts->nsec = nsec; + vdso_ts->sec += __iter_div64_u64_rem(nsec, (u64)NSEC_PER_SEC << tk->tkr_mono.shift, + &vdso_ts->nsec); /* Copy MONOTONIC time for BOOTTIME */ sec = vdso_ts->sec; + nsec = vdso_ts->nsec; /* Add the boot offset */ sec += tk->monotonic_to_boot.tv_sec; nsec += (u64)tk->monotonic_to_boot.tv_nsec << tk->tkr_mono.shift; @@ -56,12 +54,8 @@ static inline void update_vdso_time_data(struct vdso_time_data *vdata, struct ti /* CLOCK_BOOTTIME */ vdso_ts = &vc[CS_HRES_COARSE].basetime[CLOCK_BOOTTIME]; vdso_ts->sec = sec; - - while (nsec >= (((u64)NSEC_PER_SEC) << tk->tkr_mono.shift)) { - nsec -= (((u64)NSEC_PER_SEC) << tk->tkr_mono.shift); - vdso_ts->sec++; - } - vdso_ts->nsec = nsec; + vdso_ts->sec += __iter_div64_u64_rem(nsec, (u64)NSEC_PER_SEC << tk->tkr_mono.shift, + &vdso_ts->nsec); /* CLOCK_MONOTONIC_RAW */ vdso_ts = &vc[CS_RAW].basetime[CLOCK_MONOTONIC_RAW]; @@ -161,11 +155,11 @@ void vdso_time_update_aux(struct timekeeper *tk) vdso_ts->sec = tk->xtime_sec + tk->monotonic_to_aux.tv_sec; - nsec = tk->tkr_mono.xtime_nsec >> tk->tkr_mono.shift; - nsec += tk->monotonic_to_aux.tv_nsec; - vdso_ts->sec += __iter_div_u64_rem(nsec, NSEC_PER_SEC, &nsec); - nsec = nsec << tk->tkr_mono.shift; - vdso_ts->nsec = nsec; + nsec = tk->tkr_mono.xtime_nsec; + nsec += (u64)tk->monotonic_to_aux.tv_nsec << tk->tkr_mono.shift; + vdso_ts->sec += __iter_div64_u64_rem(nsec, + (u64)NSEC_PER_SEC << tk->tkr_mono.shift, + &vdso_ts->nsec); } __arch_update_vdso_clock(vc); diff --git a/kernel/trace/bpf_trace.c b/kernel/trace/bpf_trace.c index 29260951aa87..08ddadd80056 100644 --- a/kernel/trace/bpf_trace.c +++ b/kernel/trace/bpf_trace.c @@ -823,6 +823,7 @@ const struct bpf_func_proto bpf_task_pt_regs_proto = { struct send_signal_irq_work { struct irq_work irq_work; + /* The claim: NULL marks the slot free for the next caller. */ struct task_struct *task; u32 sig; enum pid_type type; @@ -842,6 +843,8 @@ static void do_bpf_send_signal(struct irq_work *entry) group_send_sig_info(work->sig, siginfo, work->task, work->type); put_task_struct(work->task); + /* Release once the fields are consumed. */ + smp_store_release(&work->task, NULL); } static int bpf_send_signal_common(u32 sig, enum pid_type type, struct task_struct *task, u64 value) @@ -864,15 +867,12 @@ static int bpf_send_signal_common(u32 sig, enum pid_type type, struct task_struc siginfo = &info; } - /* Similar to bpf_probe_write_user, task needs to be - * in a sound condition and kernel memory access be - * permitted in order to send signal to the current - * task. + /* + * Similar to bpf_probe_write_user, task needs to be + * in a sound condition. */ if (unlikely(task->flags & (PF_KTHREAD | PF_EXITING))) return -EPERM; - if (unlikely(!nmi_uaccess_okay())) - return -EPERM; /* Task should not be pid=1 to avoid kernel panic. */ if (unlikely(is_global_init(task))) return -EPERM; @@ -885,14 +885,14 @@ static int bpf_send_signal_common(u32 sig, enum pid_type type, struct task_struc return -EINVAL; work = this_cpu_ptr(&send_signal_work); - if (irq_work_is_busy(&work->irq_work)) + if (cmpxchg(&work->task, NULL, task)) return -EBUSY; /* Add the current task, which is the target of sending signal, * to the irq_work. The current task may change when queued * irq works get executed. */ - work->task = get_task_struct(task); + get_task_struct(task); work->has_siginfo = siginfo == &info; if (work->has_siginfo) copy_siginfo(&work->info, &info); @@ -2206,6 +2206,7 @@ int bpf_probe_unregister(struct bpf_raw_event_map *btp, struct bpf_raw_tp_link * return tracepoint_probe_unregister(btp->tp, (void *)btp->bpf_func, link); } +/* On success the caller releases *buf with kfree_const() */ int bpf_get_perf_event_info(const struct perf_event *event, u32 *prog_id, u32 *fd_type, const char **buf, u64 *probe_offset, u64 *probe_addr, @@ -2215,6 +2216,12 @@ int bpf_get_perf_event_info(const struct perf_event *event, u32 *prog_id, struct bpf_prog *prog; int flags, err = 0; + /* + * The list of dynamic events is walked, and a probe which has siblings + * can be deleted, with its strings, while its event is in use. + */ + guard(mutex)(&event_mutex); + prog = event->prog; if (!prog) return -ENOENT; @@ -2255,6 +2262,12 @@ int bpf_get_perf_event_info(const struct perf_event *event, u32 *prog_id, #endif } + if (!err && *buf) { + *buf = kstrdup_const(*buf, GFP_KERNEL); + if (!*buf) + err = -ENOMEM; + } + return err; } diff --git a/kernel/trace/rv/monitors/wakeup/wakeup.c b/kernel/trace/rv/monitors/wakeup/wakeup.c index 01b47416f24e..2e803e79181e 100644 --- a/kernel/trace/rv/monitors/wakeup/wakeup.c +++ b/kernel/trace/rv/monitors/wakeup/wakeup.c @@ -128,7 +128,7 @@ static void disable_wakeup(void) ltl_monitor_destroy(); } -static struct rv_monitor rv_wakeup = { +static struct rv_monitor rv_this = { .name = "wakeup", .description = "Monitor that real-time tasks are not woken by lower-priority tasks", .enable = enable_wakeup, @@ -137,12 +137,12 @@ static struct rv_monitor rv_wakeup = { static int __init register_wakeup(void) { - return rv_register_monitor(&rv_wakeup, &rv_rtapp); + return rv_register_monitor(&rv_this, &rv_rtapp); } static void __exit unregister_wakeup(void) { - rv_unregister_monitor(&rv_wakeup); + rv_unregister_monitor(&rv_this); } module_init(register_wakeup); diff --git a/kernel/trace/rv/rv_reactors.c b/kernel/trace/rv/rv_reactors.c index 2f5fc8d18dea..ff7d478227c3 100644 --- a/kernel/trace/rv/rv_reactors.c +++ b/kernel/trace/rv/rv_reactors.c @@ -465,7 +465,15 @@ int init_rv_reactors(struct dentry *root_dir) void rv_react(struct rv_monitor *monitor, const char *msg, ...) { - static DEFINE_WAIT_OVERRIDE_MAP(rv_react_map, LD_WAIT_FREE); + /* + * Reactors must not explicitly take locks, so they should be + * LD_WAIT_FREE. However, reactor callbacks can run with preemption + * enabled, meaning the preempting code (e.g. the scheduler taking + * rq->__lock at LD_WAIT_SPIN) may violate that constraint. Use + * LD_WAIT_SPIN to avoid false-positive lockdep reports. + * But you should still NOT be using locks in reactors. + */ + static DEFINE_WAIT_OVERRIDE_MAP(rv_react_map, LD_WAIT_SPIN); va_list args; if (!rv_reacting_on() || !monitor->react) diff --git a/kernel/trace/trace.h b/kernel/trace/trace.h index 3749485a7d85..9044f03fe2d9 100644 --- a/kernel/trace/trace.h +++ b/kernel/trace/trace.h @@ -1006,9 +1006,6 @@ struct ftrace_hash { struct rcu_head rcu; }; -struct ftrace_func_entry * -ftrace_lookup_ip(struct ftrace_hash *hash, unsigned long ip); - static __always_inline bool ftrace_hash_empty(struct ftrace_hash *hash) { return !hash || !(hash->count || (hash->flags & FTRACE_HASH_FL_MOD)); diff --git a/kernel/trace/trace_btf.c b/kernel/trace/trace_btf.c index ee7a04886bf6..b8370ae9bd54 100644 --- a/kernel/trace/trace_btf.c +++ b/kernel/trace/trace_btf.c @@ -15,6 +15,9 @@ const struct btf_type *btf_find_func_proto(const char *func_name, struct btf **b const struct btf_type *t; s32 id; + if (unlikely(in_atomic() || irqs_disabled())) + return NULL; + id = bpf_find_btf_id(func_name, BTF_KIND_FUNC, btf_p); if (id < 0) return NULL; diff --git a/kernel/trace/trace_events_hist.c b/kernel/trace/trace_events_hist.c index 3915159b1236..642b354d23b0 100644 --- a/kernel/trace/trace_events_hist.c +++ b/kernel/trace/trace_events_hist.c @@ -279,6 +279,14 @@ static u64 hist_field_pstring(struct hist_field *hist_field, return (u64)(unsigned long)*addr; } +static bool hist_field_is_signed(struct hist_field *hist_field) +{ + if (hist_field->field) + return hist_field->field->is_signed; + + return hist_field->is_signed; +} + static u64 hist_field_log2(struct hist_field *hist_field, struct tracing_map_elt *elt, struct trace_buffer *buffer, @@ -1725,7 +1733,7 @@ static const char *get_hist_field_flags(struct hist_field *hist_field) flags_str = "percent"; else if (hist_field->flags & HIST_FIELD_FL_GRAPH) flags_str = "graph"; - else if (hist_field->flags & HIST_FIELD_FL_STACKTRACE) + else if (hist_field->flags & HIST_FIELD_FL_STACKTRACE && hist_field->field) flags_str = "stacktrace"; return flags_str; @@ -5568,15 +5576,24 @@ static void hist_trigger_print_key(struct seq_file *m, *(u64 *)(key + key_field->offset)); } else if (key_field->flags & HIST_FIELD_FL_BUCKET) { unsigned long buckets = key_field->buckets; + u64 end; + uval = *(u64 *)(key + key_field->offset); + end = uval + buckets - 1; + if (end < uval) + end = U64_MAX; seq_printf(m, "%s: ~ %llu-%llu", field_name, - uval, uval + buckets -1); + uval, end); } else if (key_field->flags & HIST_FIELD_FL_STRING) { seq_printf(m, "%s: %-50s", field_name, (char *)(key + key_field->offset)); } else { uval = *(u64 *)(key + key_field->offset); - seq_printf(m, "%s: %10llu", field_name, uval); + if (hist_field_is_signed(key_field)) + seq_printf(m, "%s: %10lld", field_name, + (s64)uval); + else + seq_printf(m, "%s: %10llu", field_name, uval); } } @@ -6208,7 +6225,7 @@ static void hist_field_print(struct seq_file *m, struct hist_field *hist_field) } } if (hist_field->buckets) - seq_printf(m, "=%ld", hist_field->buckets); + seq_printf(m, "=%lu", hist_field->buckets); } static int event_hist_trigger_print(struct seq_file *m, diff --git a/kernel/ucount.c b/kernel/ucount.c index c3de5b94d25f..94b70502dc9d 100644 --- a/kernel/ucount.c +++ b/kernel/ucount.c @@ -285,9 +285,12 @@ static void do_dec_rlimit_put_ucounts(struct ucounts *ucounts, { struct ucounts *iter, *next; for (iter = ucounts; iter != last; iter = next) { - long dec = atomic_long_sub_return(1, &iter->rlimit[type]); - WARN_ON_ONCE(dec < 0); + long dec; + + /* Our count pins @iter; once it is dropped @iter may be freed. */ next = iter->ns->ucounts; + dec = atomic_long_sub_return(1, &iter->rlimit[type]); + WARN_ON_ONCE(dec < 0); if (dec == 0) put_ucounts(iter); } diff --git a/kernel/watch_queue.c b/kernel/watch_queue.c index 932a88ac1f39..453dcf613205 100644 --- a/kernel/watch_queue.c +++ b/kernel/watch_queue.c @@ -212,7 +212,7 @@ void __post_watch_notification(struct watch_list *wlist, if (watch->id != id) continue; n->info &= ~WATCH_INFO_ID; - n->info |= watch->info_id; + n->info |= watch->info_id & WATCH_INFO_ID; wqueue = rcu_dereference(watch->queue); wf = rcu_dereference(wqueue->filter); diff --git a/kernel/watchdog_perf.c b/kernel/watchdog_perf.c index cf05775a96d3..a4f677c16b20 100644 --- a/kernel/watchdog_perf.c +++ b/kernel/watchdog_perf.c @@ -301,10 +301,10 @@ void __init hardlockup_config_perf_event(const char *str) } else { unsigned int len = comma - str; - if (len > sizeof(buf)) + if (len >= sizeof(buf)) return; - strscpy(buf, str, len); + strscpy(buf, str, len + 1); if (kstrtoull(buf, 16, &config)) return; } diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug index 6b24a2c89b84..1dc11129f3c2 100644 --- a/lib/Kconfig.debug +++ b/lib/Kconfig.debug @@ -2776,7 +2776,6 @@ config RESOURCE_KUNIT_TEST tristate "KUnit test for resource API" if !KUNIT_ALL_TESTS depends on KUNIT default KUNIT_ALL_TESTS - select GET_FREE_REGION help This builds the resource API unit test. Tests the logic of API provided by resource.c and ioport.h. diff --git a/lib/bitmap-str.c b/lib/bitmap-str.c index dd9aa0635fa5..cafd6388892f 100644 --- a/lib/bitmap-str.c +++ b/lib/bitmap-str.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include "kstrtox.h" @@ -186,10 +187,12 @@ struct region { static void bitmap_set_region(const struct region *r, unsigned long *bitmap) { - unsigned int start; + unsigned int start = r->start; - for (start = r->start; start <= r->end; start += r->group_len) + do { bitmap_set(bitmap, start, min(r->end - start + 1, r->off)); + } while (!check_add_overflow(start, r->group_len, &start) && + start <= r->end); } static int bitmap_check_region(const struct region *r) @@ -299,7 +302,14 @@ static const char *bitmap_parse_region(const char *str, struct region *r) if (*str != '/') return ERR_PTR(-EINVAL); - return bitmap_getnum(str + 1, &r->group_len, lastbit); + str = bitmap_getnum(str + 1, &r->group_len, lastbit); + if (IS_ERR(str)) + return str; + + if (!end_of_region(*str)) + return ERR_PTR(-EINVAL); + + return end_of_str(*str) ? NULL : str; no_end: r->end = r->start; @@ -414,8 +424,12 @@ static const char *bitmap_get_x32_reverse(const char *start, goto out; } - if (hex_to_bin(*end--) >= 0) - return ERR_PTR(-EOVERFLOW); + /* + * Eight digits have been consumed and the next character is not a + * separator: another hex digit means the chunk does not fit in 32 + * bits, anything else is an illegal character. + */ + return ERR_PTR(hex_to_bin(*end) >= 0 ? -EOVERFLOW : -EINVAL); out: *num = ret; return end; diff --git a/lib/decompress_unlz4.c b/lib/decompress_unlz4.c index c0dbb3cea915..86e9aaec04f6 100644 --- a/lib/decompress_unlz4.c +++ b/lib/decompress_unlz4.c @@ -139,6 +139,10 @@ STATIC inline int INIT unlz4(u8 *input, long in_len, if (!fill) { inp += 4; size -= 4; + if (chunksize > size) { + error("data corrupted"); + goto exit_2; + } } else { if (chunksize > LZ4_compressBound(uncomp_chunksize)) { error("chunk length is longer than allocated"); diff --git a/lib/kobject.c b/lib/kobject.c index e7b010a989fb..76214cb6fd5a 100644 --- a/lib/kobject.c +++ b/lib/kobject.c @@ -855,7 +855,7 @@ EXPORT_SYMBOL_GPL(kobj_sysfs_ops); * kset_register() - Initialize and add a kset. * @k: kset. * - * NOTE: On error, the kset.kobj.name allocated by() kobj_set_name() + * NOTE: On error, the kset.kobj.name allocated by kobject_set_name() * is freed, it can not be used any more. */ int kset_register(struct kset *k) diff --git a/lib/maple_tree.c b/lib/maple_tree.c index 1aba6cced713..0b0036c9f848 100644 --- a/lib/maple_tree.c +++ b/lib/maple_tree.c @@ -763,43 +763,6 @@ static inline void ma_set_meta(struct maple_node *mn, enum maple_type mt, meta->end = end; } -/* - * mt_clear_meta() - clear the metadata information of a node, if it exists - * @mt: The maple tree - * @mn: The maple node - * @type: The maple node type - */ -static inline void mt_clear_meta(struct maple_tree *mt, struct maple_node *mn, - enum maple_type type) -{ - struct maple_metadata *meta; - unsigned long *pivots; - void __rcu **slots; - void *next; - - switch (type) { - case maple_range_64: - pivots = mn->mr64.pivot; - if (unlikely(pivots[MAPLE_RANGE64_SLOTS - 2])) { - slots = mn->mr64.slot; - next = mt_slot_locked(mt, slots, - MAPLE_RANGE64_SLOTS - 1); - if (unlikely((mte_to_node(next) && - mte_node_type(next)))) - return; /* no metadata, could be node */ - } - fallthrough; - case maple_arange_64: - meta = ma_meta(mn, type); - break; - default: - return; - } - - meta->gap = 0; - meta->end = 0; -} - /* * ma_meta_end() - Get the data end of a node from the metadata * @mn: The maple node @@ -4789,9 +4752,7 @@ static void mt_free_walk(struct rcu_head *head) type = mte_node_type(enode); slots = ma_slots(mte_to_node(enode), type); - if ((offset < mt_slots[type]) && - rcu_dereference_protected(slots[offset], - lock_is_held(&rcu_callback_map))) + if (offset < mte_to_node(enode)->slot_len) slots = mte_dead_walk(&enode, offset); node = mte_to_node(enode); } while ((node != start) || (node->slot_len < offset)); @@ -4885,8 +4846,6 @@ static void mt_destroy_walk(struct maple_enode *enode, struct maple_tree *mt, free_leaf: if (free) kfree(node); - else - mt_clear_meta(mt, node, node->type); } /* diff --git a/lib/region_alloc_benchmark.c b/lib/region_alloc_benchmark.c index e88b4cf55c62..a644f3d5431a 100644 --- a/lib/region_alloc_benchmark.c +++ b/lib/region_alloc_benchmark.c @@ -78,11 +78,13 @@ static size_t __init ida_size(unsigned long nr_ids) static unsigned long __init benchmark_ida(unsigned long cap) { - struct ida ida = IDA_INIT(ida); + struct ida ida; unsigned long cnt, idx, off, nr_ids = 0; ktime_t alloc_time, free_time; int id = -ENOSPC; + ida_init(&ida); + alloc_time = ktime_get(); for (cnt = 0; cnt <= cap; cnt++) { for (off = 0; off < reg_sz[cnt]; off++) { @@ -125,12 +127,14 @@ static unsigned long __init benchmark_ida(unsigned long cap) static unsigned long __init benchmark_maple_tree(unsigned long cap) { - struct maple_tree mt = MTREE_INIT(mt, MT_FLAGS_ALLOC_RANGE); + struct maple_tree mt; unsigned long cnt, idx; ktime_t alloc_time, free_time; size_t sz; int ret; + mt_init_flags(&mt, MT_FLAGS_ALLOC_RANGE); + alloc_time = ktime_get(); for (cnt = 0; cnt <= cap; cnt++) { ret = mtree_alloc_range(&mt, &idx, xa_mk_value(cnt + 1), diff --git a/lib/seq_buf.c b/lib/seq_buf.c index a92093f346da..35a5964370b4 100644 --- a/lib/seq_buf.c +++ b/lib/seq_buf.c @@ -128,7 +128,7 @@ void seq_buf_do_printk(struct seq_buf *s, const char *lvl) } /* No trailing LF */ - if (start < s->buffer + s->len) + if (*start) printk("%s%s\n", lvl, start); } EXPORT_SYMBOL_GPL(seq_buf_do_printk); diff --git a/lib/test_hmm.c b/lib/test_hmm.c index 6911daa9f854..b409c42bfe6f 100644 --- a/lib/test_hmm.c +++ b/lib/test_hmm.c @@ -1624,6 +1624,8 @@ static long dmirror_fops_unlocked_ioctl(struct file *filp, if (cmd.addr & ~PAGE_MASK) return -EINVAL; + if (cmd.npages > ULONG_MAX >> PAGE_SHIFT) + return -EINVAL; if (cmd.addr >= (cmd.addr + (cmd.npages << PAGE_SHIFT))) return -EINVAL; diff --git a/lib/test_sysctl.c b/lib/test_sysctl.c index 909cfcf76dbf..dd795979558a 100644 --- a/lib/test_sysctl.c +++ b/lib/test_sysctl.c @@ -321,11 +321,11 @@ module_init(test_sysctl_init); static void __exit test_sysctl_exit(void) { - kfree(test_data.bitmap_0001); for (int i = 0; i < TEST_H_SIZE; i++) { if (ctl_headers[i]) unregister_sysctl_table(ctl_headers[i]); } + kfree(test_data.bitmap_0001); } module_exit(test_sysctl_exit); diff --git a/lib/tests/seq_buf_kunit.c b/lib/tests/seq_buf_kunit.c index eb466386bbef..de491f96c1ac 100644 --- a/lib/tests/seq_buf_kunit.c +++ b/lib/tests/seq_buf_kunit.c @@ -6,7 +6,9 @@ */ #include +#include #include +#include static void seq_buf_init_test(struct kunit *test) { @@ -113,6 +115,47 @@ static void seq_buf_putc_test(struct kunit *test) KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), ""); } +static void seq_buf_pop_test(struct kunit *test) +{ + DECLARE_SEQ_BUF(s, 8); + struct seq_buf t; + char *buf; + + /* Nothing to pop. */ + KUNIT_EXPECT_EQ(test, seq_buf_pop(&s), -1); + KUNIT_EXPECT_EQ(test, s.len, 0); + + seq_buf_puts(&s, "hello"); + KUNIT_EXPECT_EQ(test, seq_buf_pop(&s), 'o'); + KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 4); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), "hell"); + + /* A 0xff byte must not be mistaken for an empty buffer. */ + seq_buf_putc(&s, 0xff); + KUNIT_EXPECT_EQ(test, seq_buf_pop(&s), 0xff); + + /* A full buffer pops its last byte. */ + seq_buf_puts(&s, "abc"); + seq_buf_putc(&s, 'd'); + KUNIT_EXPECT_FALSE(test, seq_buf_has_overflowed(&s)); + KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 8); + KUNIT_EXPECT_EQ(test, seq_buf_pop(&s), 'd'); + KUNIT_EXPECT_EQ(test, seq_buf_used(&s), 7); + KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), "hellabc"); + + /* + * An overflowed buffer has nothing to pop, and stays overflowed. Use + * a buffer allocated at its exact size, so that KASAN reports any + * read past its end. + */ + buf = kunit_kmalloc(test, 16, GFP_KERNEL); + KUNIT_ASSERT_NOT_NULL(test, buf); + seq_buf_init(&t, buf, 16); + KUNIT_EXPECT_EQ(test, seq_buf_printf(&t, "%s", "longer than sixteen"), -1); + KUNIT_EXPECT_EQ(test, seq_buf_pop(&t), -1); + KUNIT_EXPECT_TRUE(test, seq_buf_has_overflowed(&t)); +} + static void seq_buf_printf_test(struct kunit *test) { DECLARE_SEQ_BUF(s, 32); @@ -216,6 +259,135 @@ static void seq_buf_putmem_hex_overflow_test(struct kunit *test) KUNIT_EXPECT_STREQ(test, seq_buf_str(&s), expected); } +/* + * Counters for the console that seq_buf_do_printk_test() registers while it + * runs. Only records carrying the marker are counted, so unrelated kernel + * messages do not disturb them. + * + * An empty record carries nothing to recognize it by, so count one only + * where the flaw puts it: directly after a record of ours, with nothing in + * between. That still misreads a bare line feed printed by another CPU in + * exactly that gap, but no longer counts one printed at any point while the + * console happens to be registered. + */ +#define SEQ_BUF_PRINTK_MARKER "sbdpkx" + +static unsigned int seq_buf_printk_marked; +static unsigned int seq_buf_printk_empty; +static bool seq_buf_printk_last_was_ours; + +static void seq_buf_printk_capture(struct console *con, + const char *s, unsigned int count) +{ + const char *text = s; + const char *prefix; + + /* + * Skip what printk() puts in front of the message: a timestamp, + * and the caller id as well under CONFIG_PRINTK_CALLER, so strip + * every bracketed group rather than just the first. + */ + while (count && text[0] == '[') { + prefix = memchr(text, ']', count); + if (!prefix) + break; + count -= prefix + 1 - text; + text = prefix + 1; + if (count && text[0] == ' ') { + text++; + count--; + } + } + + if (strnstr(text, SEQ_BUF_PRINTK_MARKER, count)) { + seq_buf_printk_marked++; + seq_buf_printk_last_was_ours = true; + return; + } + + if (seq_buf_printk_last_was_ours && + (count == 0 || (count == 1 && text[0] == '\n'))) + seq_buf_printk_empty++; + + seq_buf_printk_last_was_ours = false; +} + +static void seq_buf_printk_run(struct console *capture, struct seq_buf *s) +{ + seq_buf_printk_marked = 0; + seq_buf_printk_empty = 0; + seq_buf_printk_last_was_ours = false; + + /* + * register_console() will not take an unmatched console without + * CON_ENABLED, and unregister_console() clears it, so set it on + * every run to keep the test repeatable. + */ + capture->flags = CON_ENABLED; + register_console(capture); + seq_buf_do_printk(s, KERN_INFO); + unregister_console(capture); +} + +static void seq_buf_do_printk_test(struct kunit *test) +{ + /* + * A registered console is a global object: printk() reaches it + * through the console list from any CPU, and the console code writes + * back into it, so keep it out of this function's stack frame the + * way every other console in the tree does. + */ + static struct console capture = { + .name = "sbufcap", + .write = seq_buf_printk_capture, + .index = -1, + }; + DECLARE_SEQ_BUF(s, 8); + DECLARE_SEQ_BUF(t, 16); + DECLARE_SEQ_BUF(u, 8); + + /* + * Fill the buffer exactly, so that the NUL takes the place of the + * last byte and the string ends with the line feed before it. + */ + seq_buf_puts(&s, SEQ_BUF_PRINTK_MARKER); + seq_buf_putc(&s, '\n'); + seq_buf_putc(&s, '!'); + KUNIT_ASSERT_FALSE(test, seq_buf_has_overflowed(&s)); + KUNIT_ASSERT_EQ(test, seq_buf_used(&s), 8); + KUNIT_ASSERT_EQ(test, strlen(seq_buf_str(&s)), 7); + + seq_buf_printk_run(&capture, &s); + + /* The one line that was written, and nothing after it. */ + KUNIT_EXPECT_EQ(test, seq_buf_printk_marked, 1); + KUNIT_EXPECT_EQ(test, seq_buf_printk_empty, 0); + + /* Check that lines without a trailing newline are shown. */ + seq_buf_puts(&t, SEQ_BUF_PRINTK_MARKER "\n" SEQ_BUF_PRINTK_MARKER); + KUNIT_ASSERT_FALSE(test, seq_buf_has_overflowed(&t)); + + seq_buf_printk_run(&capture, &t); + + KUNIT_EXPECT_EQ(test, seq_buf_printk_marked, 2); + KUNIT_EXPECT_EQ(test, seq_buf_printk_empty, 0); + + /* + * The buffer above was exactly full, where "len" equals the size. A + * buffer that actually overflowed reaches the same bug by the other + * route the old test had, with "len" one past the size. + */ + seq_buf_puts(&u, SEQ_BUF_PRINTK_MARKER "\n"); + KUNIT_EXPECT_EQ(test, seq_buf_puts(&u, "yy"), -1); + KUNIT_ASSERT_TRUE(test, seq_buf_has_overflowed(&u)); + KUNIT_ASSERT_EQ(test, u.len, u.size + 1); + + seq_buf_printk_run(&capture, &u); + + KUNIT_EXPECT_EQ(test, seq_buf_printk_marked, 1); + KUNIT_EXPECT_EQ(test, seq_buf_printk_empty, 0); +} + static struct kunit_case seq_buf_test_cases[] = { KUNIT_CASE(seq_buf_init_test), KUNIT_CASE(seq_buf_declare_test), @@ -223,11 +395,13 @@ static struct kunit_case seq_buf_test_cases[] = { KUNIT_CASE(seq_buf_puts_test), KUNIT_CASE(seq_buf_puts_overflow_test), KUNIT_CASE(seq_buf_putc_test), + KUNIT_CASE(seq_buf_pop_test), KUNIT_CASE(seq_buf_printf_test), KUNIT_CASE(seq_buf_printf_overflow_test), KUNIT_CASE(seq_buf_get_buf_commit_test), KUNIT_CASE(seq_buf_putmem_hex_test), KUNIT_CASE(seq_buf_putmem_hex_overflow_test), + KUNIT_CASE(seq_buf_do_printk_test), {} }; diff --git a/lib/vdso/gettimeofday.c b/lib/vdso/gettimeofday.c index f7a591aba59f..6e9b03051bee 100644 --- a/lib/vdso/gettimeofday.c +++ b/lib/vdso/gettimeofday.c @@ -374,8 +374,8 @@ __cvdso_gettimeofday_data(const struct vdso_time_data *vd, if (vdso_is_timens_clock(vc)) vd = vdso_timens_data(vd); - tz->tz_minuteswest = vd[CS_HRES_COARSE].tz_minuteswest; - tz->tz_dsttime = vd[CS_HRES_COARSE].tz_dsttime; + tz->tz_minuteswest = vd->tz_minuteswest; + tz->tz_dsttime = vd->tz_dsttime; } return 0; diff --git a/mm/gup.c b/mm/gup.c index 4f58ad22a756..9a387ed1e5f5 100644 --- a/mm/gup.c +++ b/mm/gup.c @@ -1987,6 +1987,7 @@ static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start, struct vm_area_struct *vma; bool must_unlock = false; vm_flags_t vm_flags; + int ret, err = -EFAULT; long i; if (!nr_pages) @@ -2003,6 +2004,10 @@ static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start, *locked = 1; } + /* See the MMU variant: support the traditional behavior. */ + if (pages && !(foll_flags & FOLL_PIN)) + foll_flags |= FOLL_GET; + /* calculate required read or write permissions. * If FOLL_FORCE is set, we only require the "MAY" flags. */ @@ -2023,8 +2028,14 @@ static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start, if (pages) { pages[i] = virt_to_page((void *)start); - if (pages[i]) - get_page(pages[i]); + if (!pages[i]) + break; + ret = try_grab_folio(page_folio(pages[i]), 1, foll_flags); + if (unlikely(ret)) { + pages[i] = NULL; + err = ret; + break; + } } start = (start + PAGE_SIZE) & PAGE_MASK; @@ -2035,7 +2046,7 @@ static long __get_user_pages_locked(struct mm_struct *mm, unsigned long start, *locked = 0; } - return i ? : -EFAULT; + return i ? : err; } #endif /* !CONFIG_MMU */ diff --git a/mm/gup_test.c b/mm/gup_test.c index 44c1cdfb9c37..ba74bf3f4104 100644 --- a/mm/gup_test.c +++ b/mm/gup_test.c @@ -116,7 +116,8 @@ static int __gup_test_ioctl(unsigned int cmd, bool needs_mmap_lock = cmd != GUP_FAST_BENCHMARK && cmd != PIN_FAST_BENCHMARK; - if (gup->addr > ULONG_MAX || gup->size > ULONG_MAX) + if (gup->addr > ULONG_MAX || gup->size > ULONG_MAX || !gup->size || + !gup->nr_pages_per_call || !PAGE_ALIGNED(gup->size)) return -EINVAL; if (check_add_overflow((unsigned long)gup->addr, (unsigned long)gup->size, &end)) @@ -139,11 +140,9 @@ static int __gup_test_ioctl(unsigned int cmd, if (nr != gup->nr_pages_per_call) break; + nr = min_t(unsigned long, nr, (end - addr) / PAGE_SIZE); + next = addr + nr * PAGE_SIZE; - if (next > end) { - next = end; - nr = (next - addr) / PAGE_SIZE; - } switch (cmd) { case GUP_FAST_BENCHMARK: @@ -188,7 +187,7 @@ static int __gup_test_ioctl(unsigned int cmd, nr_pages = i; gup->get_delta_usec = ktime_us_delta(end_time, start_time); - gup->size = addr - gup->addr; + gup->size = nr_pages * PAGE_SIZE; /* * Take an un-benchmark-timed moment to verify DMA pinned diff --git a/mm/hugetlb.c b/mm/hugetlb.c index 860c3c6b7673..82963b9977b4 100644 --- a/mm/hugetlb.c +++ b/mm/hugetlb.c @@ -6364,6 +6364,7 @@ int hugetlb_mfill_atomic_pte(pte_t *dst_pte, return -EEXIST; } + VM_WARN_ON_ONCE(size == PMD_SIZE && hugetlb_pmd_shared(dst_pte)); _dst_pte = make_pte_marker(PTE_MARKER_POISONED); set_huge_pte_at(dst_mm, dst_addr, dst_pte, _dst_pte, size); diff --git a/mm/madvise.c b/mm/madvise.c index 222c10eb61eb..7291d03d6692 100644 --- a/mm/madvise.c +++ b/mm/madvise.c @@ -158,7 +158,7 @@ static int madvise_update_vma(vm_flags_t new_flags, bool set_new_anon_name = madv_behavior->behavior == __MADV_SET_ANON_VMA_NAME; VMA_ITERATOR(vmi, madv_behavior->mm, range->start); - if (vma_flags_same_mask(&vma->flags, new_vma_flags) && + if (vma_flags_same_pair(&vma->flags, &new_vma_flags) && (!set_new_anon_name || anon_vma_name_eq(anon_vma_name(vma), anon_name))) return 0; @@ -177,7 +177,10 @@ static int madvise_update_vma(vm_flags_t new_flags, /* vm_flags is protected by the mmap_lock held in write mode. */ vma_start_write(vma); - vma->flags = new_vma_flags; + if (set_new_anon_name) + return replace_anon_vma_name(vma, anon_name); + + vma_overwrite_flags(vma, new_vma_flags); /* * If the vma become good for khugepaged to scan, * register it here without waiting a page fault that @@ -186,9 +189,6 @@ static int madvise_update_vma(vm_flags_t new_flags, if (vma_flags_test(&new_vma_flags, VMA_HUGEPAGE_BIT)) khugepaged_enter_vma(vma, vma_flags_to_legacy(new_vma_flags)); - if (set_new_anon_name) - return replace_anon_vma_name(vma, anon_name); - return 0; } diff --git a/mm/memblock.c b/mm/memblock.c index e6fdf95a0534..37e6abfcf4e3 100644 --- a/mm/memblock.c +++ b/mm/memblock.c @@ -2828,12 +2828,17 @@ static int __init reserve_mem(char *p) if (*p != ':') goto err_param; + if (!IS_ALIGNED(size, PAGE_SIZE) || !IS_ALIGNED(align, PAGE_SIZE)) { + pr_err("reserve_mem: size and align must be multiples of the page size\n"); + return -EINVAL; + } + /* * memblock_phys_alloc() doesn't like a zero size align, * but it is OK for this command to have it. */ - if (align < SMP_CACHE_BYTES) - align = SMP_CACHE_BYTES; + if (!align) + align = PAGE_SIZE; name = p + 1; len = strlen(name); diff --git a/mm/memory_hotplug.c b/mm/memory_hotplug.c index 226ab9cb078a..0a4df6ba2d53 100644 --- a/mm/memory_hotplug.c +++ b/mm/memory_hotplug.c @@ -384,6 +384,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; @@ -417,8 +418,11 @@ 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, + params->pgmap); break; + } cond_resched(); } vmemmap_populate_print_last(); diff --git a/mm/mlock.c b/mm/mlock.c index 4fb43cddafa8..d88683ca2a6f 100644 --- a/mm/mlock.c +++ b/mm/mlock.c @@ -443,7 +443,7 @@ static void mlock_vma_pages_range(struct vm_area_struct *vma, if (vma_flags_test(new_vma_flags, VMA_LOCKED_BIT)) vma_flags_set(new_vma_flags, VMA_IO_BIT); vma_start_write(vma); - vma_flags_reset_once(vma, new_vma_flags); + vma_overwrite_flags(vma, *new_vma_flags); lru_add_drain(); walk_page_range_vma(vma, start, end, &mlock_walk_ops, NULL); @@ -451,7 +451,7 @@ static void mlock_vma_pages_range(struct vm_area_struct *vma, if (vma_flags_test(new_vma_flags, VMA_IO_BIT)) { vma_flags_clear(new_vma_flags, VMA_IO_BIT); - vma_flags_reset_once(vma, new_vma_flags); + vma_overwrite_flags(vma, *new_vma_flags); } } @@ -507,7 +507,7 @@ static int mlock_fixup(struct vma_iterator *vmi, struct vm_area_struct *vma, vma_flags_test(&old_vma_flags, VMA_LOCKED_BIT)) { /* No work to do, and mlocking twice would be wrong */ vma_start_write(vma); - vma->flags = *new_vma_flags; + vma_overwrite_flags(vma, *new_vma_flags); } else { mlock_vma_pages_range(vma, start, end, new_vma_flags); } diff --git a/mm/mmap_lock.c b/mm/mmap_lock.c index 898c2ef1e958..9a77343cfbc9 100644 --- a/mm/mmap_lock.c +++ b/mm/mmap_lock.c @@ -13,6 +13,8 @@ #include #include +#include "internal.h" + EXPORT_TRACEPOINT_SYMBOL(mmap_lock_start_locking); EXPORT_TRACEPOINT_SYMBOL(mmap_lock_acquire_returned); EXPORT_TRACEPOINT_SYMBOL(mmap_lock_released); @@ -197,21 +199,38 @@ void __vma_exclude_readers_for_detach(struct vm_area_struct *vma) WARN_ON_ONCE(!ves.detached); } +/* Do the VMA, mm seqcounts indicate the VMA is write locked? */ +static bool vma_seqcount_is_write_locked(unsigned int vma_seq, unsigned int mm_seq) +{ + /* VMA and mm sequence numbers must match for a write lock. */ + if (vma_seq != mm_seq) + return false; + + /* + * The VMA seqcount is always odd if locked. For an attached VMA an even + * value can only be the zero stored by __mm_reset_vma_seqcounts(), + * never a write lock. + */ + return vma_seq & 1; +} + /* * Try to read-lock a vma. The function is allowed to occasionally yield false * locked result to avoid performance overhead, in which case we fall back to * using mmap_lock. The function should never yield false unlocked result. - * False locked result is possible if mm_lock_seq overflows or if vma gets - * reused and attached to a different mm before we lock it. + * False locked result is possible if vma gets reused and attached to a + * different mm before we lock it. * Returns the vma on success, NULL on failure to lock and EAGAIN if vma got * detached. * * IMPORTANT: RCU lock must be held upon entering the function, but upon error * IT IS RELEASED. The caller must handle this correctly. */ -static inline struct vm_area_struct *vma_start_read(struct mm_struct *mm, - struct vm_area_struct *vma) +static struct vm_area_struct *vma_start_read(struct mm_struct *mm, + struct vm_area_struct *vma) { + unsigned int vma_seq; + unsigned int mm_seq; struct mm_struct *other_mm; int oldcnt; @@ -223,7 +242,9 @@ static inline struct vm_area_struct *vma_start_read(struct mm_struct *mm, * we don't rely on for anything - the mm_lock_seq read against which we * need ordering is below. */ - if (READ_ONCE(vma->vm_lock_seq) == READ_ONCE(mm->mm_lock_seq.sequence)) { + vma_seq = READ_ONCE(vma->vm_lock_seq); + mm_seq = READ_ONCE(mm->mm_lock_seq.sequence); + if (vma_seqcount_is_write_locked(vma_seq, mm_seq)) { vma = NULL; goto err; } @@ -249,17 +270,26 @@ static inline struct vm_area_struct *vma_start_read(struct mm_struct *mm, goto err_unstable; /* - * Overflow of vm_lock_seq/mm_lock_seq might produce false locked result. - * False unlocked result is impossible because we modify and check + * False unlocked result is impossible because a write lock sets * vma->vm_lock_seq under vma->vm_refcnt protection and mm->mm_lock_seq * modification invalidates all existing locks. * - * We must use ACQUIRE semantics for the mm_lock_seq so that if we are - * racing with vma_end_write_all(), we only start reading from the VMA - * after it has been unlocked. - * This pairs with RELEASE semantics in vma_end_write_all(). + * ACQUIRE semantics are required for both reads. + * + * __mm_reset_vma_seqcounts() might reset vma->vm_lock_seq to zero + * after an overflow. A reader observing that zero must also observe + * the VMA modifications made under the write lock which just ended, so + * the ACQUIRE pairs with the smp_wmb() in do_raw_write_seqcount_end() + * that precedes the reset stores. + * + * The ACQUIRE semantics for the mm_lock_seq read is required so that, + * if we are racing with vma_end_write_all(), we only start reading from + * the VMA after it has been unlocked. This pairs with the RELEASE + * semantics in vma_end_write_all(). */ - if (unlikely(vma->vm_lock_seq == raw_read_seqcount(&mm->mm_lock_seq))) { + vma_seq = smp_load_acquire(&vma->vm_lock_seq); + mm_seq = raw_read_seqcount(&mm->mm_lock_seq); + if (unlikely(vma_seqcount_is_write_locked(vma_seq, mm_seq))) { vma_refcount_put(vma); vma = NULL; goto err; @@ -366,21 +396,53 @@ static struct vm_area_struct *lock_next_vma_under_mmap_lock(struct mm_struct *mm return vma; } -struct vm_area_struct *lock_next_vma(struct mm_struct *mm, - struct vma_iterator *vmi, +/* Is there no VMA in [start, last]? */ +static bool vma_range_is_empty(struct mm_struct *mm, unsigned long start, + unsigned long last) +{ + VMA_ITERATOR(vmi, mm, start); + + return !vma_iter_load(&vmi) && vma_iter_end(&vmi) - 1 >= last; +} + +/* Might the VMA tree have been modified since last mm speculation? */ +static bool vma_rcu_iter_maybe_changed(const struct vma_rcu_iter *rvmi) +{ + return (rvmi->mm_wr_seq & 1) || /* Odd implies write-lock. */ + mmap_lock_speculate_retry(rvmi->mm, rvmi->mm_wr_seq); +} + +/* Could the VMA iterator have skipped a VMA due to the tree changing? */ +static bool vma_rcu_iter_may_have_skipped(const struct vma_rcu_iter *rvmi, + unsigned long from, unsigned long to) +{ + return vma_rcu_iter_maybe_changed(rvmi) && + !vma_range_is_empty(rvmi->mm, from, to); +} + +struct vm_area_struct *lock_next_vma(struct vma_rcu_iter *rvmi, unsigned long from_addr) { + struct mm_struct *mm = rvmi->mm; + struct vma_iterator *vmi = rvmi->vmi; struct vm_area_struct *vma; - unsigned int mm_wr_seq; - bool mmap_unlocked; RCU_LOCKDEP_WARN(!rcu_read_lock_held(), "no rcu read lock held"); retry: - /* Start mmap_lock speculation in case we need to verify the vma later */ - mmap_unlocked = mmap_lock_speculate_try_begin(mm, &mm_wr_seq); + /* Only trust the iterator's position if the tree cannot have changed. */ + if (vma_rcu_iter_maybe_changed(rvmi)) { + vma_iter_set(vmi, from_addr); + mmap_lock_speculate_try_begin(mm, &rvmi->mm_wr_seq); + } vma = vma_next(vmi); - if (!vma) - return NULL; + if (!vma) { + /* No reason to fallback if nothing left in range. */ + if (!vma_rcu_iter_may_have_skipped(rvmi, from_addr, ULONG_MAX)) + return NULL; + + rcu_read_unlock(); + goto fallback; + } vma = vma_start_read(mm, vma); if (IS_ERR_OR_NULL(vma)) { @@ -409,14 +471,9 @@ struct vm_area_struct *lock_next_vma(struct mm_struct *mm, * installed ahead of it. Otherwise we might observe a gap that should * not be there. */ - if (from_addr < vma->vm_start) { - /* Verify only if the address space might have changed since vma lookup. */ - if (!mmap_unlocked || mmap_lock_speculate_retry(mm, mm_wr_seq)) { - vma_iter_set(vmi, from_addr); - if (vma != vma_next(vmi)) - goto fallback_unlock; - } - } + if (from_addr < vma->vm_start && + vma_rcu_iter_may_have_skipped(rvmi, from_addr, vma->vm_start - 1)) + goto fallback_unlock; return vma; @@ -431,6 +488,43 @@ struct vm_area_struct *lock_next_vma(struct mm_struct *mm, return vma; } + +/* + * Called with mmap write lock held after mm->mm_lock_seq just overflowed (and + * therefore zero), with all VMA write locks now released. + * + * The stores below follow the smp_wmb() in do_raw_write_seqcount_end(), so + * a reader that observes a reset value also observes this cycle's VMA + * modifications (ordered by the ACQUIRE on vma->vm_lock_seq in + * vma_start_read()). + */ +void __mm_reset_vma_seqcounts(struct mm_struct *mm) +{ + struct vm_area_struct *vma; + VMA_ITERATOR(vmi, mm, 0); + + mmap_assert_write_locked(mm); + VM_WARN_ON_ONCE(mm->mm_lock_seq.sequence); + + /* + * Failing to reset means stale vma->vm_lock_seq values could result in + * those VMAs becoming spuriously write locked when mm->mm_lock_seq + * happens to match their values. + * + * This is problematic, as it causes the VMA write lock to not exclude + * readers, which can result in concurrent readers while a VMA write + * lock is held. + * + * Avoid this by resetting to an even value (indicates no write lock + * held). + * + * Readers will either observe zero (not write locked) or the previous + * value, so this is safe. + */ + for_each_vma(vmi, vma) + WRITE_ONCE(vma->vm_lock_seq, 0); +} +EXPORT_SYMBOL(__mm_reset_vma_seqcounts); #endif /* CONFIG_PER_VMA_LOCK */ #ifdef CONFIG_LOCK_MM_AND_FIND_VMA diff --git a/mm/mprotect.c b/mm/mprotect.c index 2888ee638d87..e923a3bf4f68 100644 --- a/mm/mprotect.c +++ b/mm/mprotect.c @@ -834,7 +834,7 @@ mprotect_fixup(struct vma_iterator *vmi, struct mmu_gather *tlb, * held in write mode. */ vma_start_write(vma); - vma_flags_reset_once(vma, &new_vma_flags); + vma_overwrite_flags(vma, new_vma_flags); if (vma_wants_manual_pte_write_upgrade(vma)) mm_cp_flags |= MM_CP_TRY_CHANGE_WRITABLE; vma_set_page_prot(vma); diff --git a/mm/shmem.c b/mm/shmem.c index 597bbc2e7321..eac9017cfb8d 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -1447,16 +1447,21 @@ static void shmem_evict_inode(struct inode *inode) } spin_unlock(&sbinfo->shrinklist_lock); } - while (!list_empty(&info->swaplist)) { - /* Wait while shmem_unuse() is scanning this inode... */ + /* + * Writeout may still use the inode after swapoff has removed it + * from the swaplist, so always wait at least once. + */ + do { wait_var_event(&info->stop_eviction, !atomic_read(&info->stop_eviction)); + if (list_empty(&info->swaplist)) + break; spin_lock(&shmem_swaplist_lock); /* ...but beware of the race if we peeked too early */ if (!atomic_read(&info->stop_eviction)) list_del_init(&info->swaplist); spin_unlock(&shmem_swaplist_lock); - } + } while (!list_empty(&info->swaplist)); } simple_xattrs_free(&sbinfo->xa_cache, &info->xattrs, sbinfo->max_inodes ? &freed : NULL); @@ -1737,6 +1742,13 @@ int shmem_writeout(struct swap_io_ctx *ctx, struct folio *folio, spin_unlock(&shmem_swaplist_lock); } + /* + * Once the folio has left the page cache, its lock no longer + * keeps the inode from being evicted and freed: hold eviction + * off, in case the folio has to be put back below. + */ + atomic_inc(&info->stop_eviction); + folio_dup_swap(folio, NULL); shmem_delete_from_page_cache(folio, swp_to_radix_entry(folio->swap)); @@ -1744,6 +1756,8 @@ int shmem_writeout(struct swap_io_ctx *ctx, struct folio *folio, error = swap_writeout(ctx, folio); if (error != AOP_WRITEPAGE_ACTIVATE) { /* folio has been unlocked */ + if (atomic_dec_and_test(&info->stop_eviction)) + wake_up_var(&info->stop_eviction); return error; } @@ -1760,6 +1774,8 @@ int shmem_writeout(struct swap_io_ctx *ctx, struct folio *folio, shmem_recalc_inode(inode, 0, -nr_pages); folio_put_swap(folio, NULL); } + if (atomic_dec_and_test(&info->stop_eviction)) + wake_up_var(&info->stop_eviction); /* * The swap_cache_del_folio() below could be left for diff --git a/mm/slab_common.c b/mm/slab_common.c index de11edfd1a0b..84366c112f4b 100644 --- a/mm/slab_common.c +++ b/mm/slab_common.c @@ -311,7 +311,7 @@ __kmem_cache_alias(const char *name, unsigned int size, slab_flags_t flags, * &SLAB_TYPESAFE_BY_RCU - Slab page (not individual objects) freeing delayed * by a grace period - see the full description before using. * - * Context: Cannot be called within a interrupt, but can be interrupted. + * Context: Cannot be called within an interrupt, but can be interrupted. * * Return: a pointer to the cache on success, NULL on failure. */ @@ -422,7 +422,7 @@ static struct kmem_cache *kmem_buckets_cache __ro_after_init; * to/from userspace. * @ctor: A constructor for the objects, run when new allocations are made. * - * Cannot be called within an interrupt, but can be interrupted. + * Context: Cannot be called within an interrupt, but can be interrupted. * * Return: a pointer to the cache on success, NULL on failure. When * CONFIG_SLAB_BUCKETS is not enabled, ZERO_SIZE_PTR is returned, and diff --git a/mm/slub.c b/mm/slub.c index 544cff39762c..6bb75db087a2 100644 --- a/mm/slub.c +++ b/mm/slub.c @@ -7778,6 +7778,7 @@ static void early_kmem_cache_node_alloc(int node) n = next_slab_obj(kmem_cache_node, &iter); BUG_ON(!n); + set_freepointer(kmem_cache_node, n, NULL); slab->inuse = 1; build_slab_freelist(kmem_cache_node, slab, &iter); diff --git a/mm/userfaultfd.c b/mm/userfaultfd.c index f8e2b7f2f61c..49a04ba1cd13 100644 --- a/mm/userfaultfd.c +++ b/mm/userfaultfd.c @@ -2286,6 +2286,9 @@ static struct vm_area_struct *userfaultfd_clear_vma(struct vma_iterator *vmi, return ret; } +static void wake_userfault_range(struct userfaultfd_ctx *ctx, + unsigned long start, unsigned long end); + /* Assumes mmap write lock taken, and mm_struct pinned. */ static int userfaultfd_register_range(struct userfaultfd_ctx *ctx, struct vm_area_struct *vma, @@ -2303,6 +2306,9 @@ static int userfaultfd_register_range(struct userfaultfd_ctx *ctx, prev = vma; for_each_vma_range(vmi, vma, end) { + const bool any_mode_removed = vma->vm_flags & __VM_UFFD_FLAGS & ~vm_flags; + const vma_flags_t curr_vma_flags = vma_flags_and_mask(&vma->flags, __VMA_UFFD_FLAGS); + cond_resched(); VM_WARN_ON_ONCE(!vma_can_userfault(vma, vm_flags, wp_async)); @@ -2315,7 +2321,7 @@ static int userfaultfd_register_range(struct userfaultfd_ctx *ctx, * userfaultfd and with the right tracking mode too. */ if (vma->vm_userfaultfd_ctx.ctx == ctx && - vma_test_all_mask(vma, vma_flags)) + vma_flags_same_pair(&curr_vma_flags, &vma_flags)) goto skip; /* @@ -2348,6 +2354,10 @@ static int userfaultfd_register_range(struct userfaultfd_ctx *ctx, */ userfaultfd_set_ctx(vma, ctx, vm_flags); + /* Retry faults for removed modes while the VMA is write-locked. */ + if (any_mode_removed) + wake_userfault_range(ctx, start, vma_end); + if (is_vm_hugetlb_page(vma) && uffd_disable_huge_pmd_share(vma)) hugetlb_unshare_all_pmds(vma); @@ -3664,6 +3674,17 @@ static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx, __wake_userfault(ctx, range); } +static void wake_userfault_range(struct userfaultfd_ctx *ctx, + unsigned long start, unsigned long end) +{ + struct userfaultfd_wake_range range = { + .start = start, + .len = end - start, + }; + + wake_userfault(ctx, &range); +} + static __always_inline int validate_unaligned_range( struct mm_struct *mm, __u64 start, __u64 len) { diff --git a/mm/vma.c b/mm/vma.c index e382fd32f0ff..a9ebccea2719 100644 --- a/mm/vma.c +++ b/mm/vma.c @@ -807,6 +807,27 @@ static void vmg_adjust_set_range(struct vma_merge_struct *vmg) } } +static void propagate_sticky_flags(struct vma_merge_struct *vmg, + struct vm_area_struct *vma) +{ + const vma_flags_t sticky = + vma_flags_and_mask(&vma->flags, VMA_STICKY_FLAGS); + + /* Write lock prevents concurrent atomic VMA flag updates. */ + vma_assert_write_locked(vma); + vma_flags_set_mask(&vmg->vma_flags, sticky); +} + +static void commit_sticky_flags(struct vma_merge_struct *vmg) +{ + const vma_flags_t sticky = + vma_flags_and_mask(&vmg->vma_flags, VMA_STICKY_FLAGS); + struct vm_area_struct *target = vmg->target; + + vma_assert_write_locked(target); + vma_set_flags_mask(target, sticky); +} + /* * Actually perform the VMA merge operation. * @@ -842,6 +863,8 @@ static int commit_merge(struct vma_merge_struct *vmg) return -ENOMEM; vma_prepare(&vp); + /* Must be made visible before vma_complete() for rmap walkers. */ + commit_sticky_flags(vmg); /* * THP pages may need to do additional splits if we increase * middle->vm_start. @@ -881,8 +904,8 @@ static bool can_merge_remove_vma(struct vm_area_struct *vma) * merge. * * As part of this operation, if a merge occurs, the @vmg object will have its - * vma, start, end, and pgoff fields modified to execute the merge. Subsequent - * calls to this function should reset these fields. + * vma, start, end, pgoff and vma_flags fields modified to execute the merge. + * Subsequent calls to this function should reset these fields. * * Returns: The merged VMA if merge succeeds, or NULL otherwise. * @@ -896,8 +919,6 @@ static bool can_merge_remove_vma(struct vm_area_struct *vma) static __must_check struct vm_area_struct *vma_merge_existing_range( struct vma_merge_struct *vmg) { - vma_flags_t sticky_flags = vma_flags_and_mask(&vmg->vma_flags, - VMA_STICKY_FLAGS); struct vm_area_struct *middle = vmg->middle; struct vm_area_struct *prev = vmg->prev; struct vm_area_struct *next; @@ -993,24 +1014,18 @@ static __must_check struct vm_area_struct *vma_merge_existing_range( /* No matter what happens, we will be adjusting middle. */ vma_start_write(middle); + propagate_sticky_flags(vmg, middle); if (merge_right) { - vma_flags_t next_sticky; - vma_start_write(next); vmg->target = next; - next_sticky = vma_flags_and_mask(&next->flags, VMA_STICKY_FLAGS); - vma_flags_set_mask(&sticky_flags, next_sticky); + propagate_sticky_flags(vmg, next); } if (merge_left) { - vma_flags_t prev_sticky; - vma_start_write(prev); vmg->target = prev; - - prev_sticky = vma_flags_and_mask(&prev->flags, VMA_STICKY_FLAGS); - vma_flags_set_mask(&sticky_flags, prev_sticky); + propagate_sticky_flags(vmg, prev); } if (merge_both) { @@ -1081,7 +1096,6 @@ static __must_check struct vm_area_struct *vma_merge_existing_range( if (err || commit_merge(vmg)) goto abort; - vma_set_flags_mask(vmg->target, sticky_flags); khugepaged_enter_vma(vmg->target, vmg->vm_flags); vmg->state = VMA_MERGE_SUCCESS; return vmg->target; @@ -1274,16 +1288,11 @@ int vma_expand(struct vma_merge_struct *vmg) struct vm_area_struct *target = vmg->target; struct vm_area_struct *next = vmg->next; bool remove_next = false; - vma_flags_t sticky_flags = - vma_flags_and_mask(&vmg->vma_flags, VMA_STICKY_FLAGS); - vma_flags_t target_sticky; int ret = 0; mmap_assert_write_locked(vmg->mm); vma_start_write(target); - target_sticky = vma_flags_and_mask(&target->flags, VMA_STICKY_FLAGS); - if (next && target != next && vmg->end == next->vm_end) remove_next = true; @@ -1298,7 +1307,7 @@ int vma_expand(struct vma_merge_struct *vmg) VM_WARN_ON_VMG(target->vm_start < vmg->start || target->vm_end > vmg->end, vmg); - vma_flags_set_mask(&sticky_flags, target_sticky); + propagate_sticky_flags(vmg, target); /* * If we are removing the next VMA or copying from a VMA @@ -1315,18 +1324,14 @@ int vma_expand(struct vma_merge_struct *vmg) goto nomem; if (remove_next) { - vma_flags_t next_sticky; - vma_start_write(next); vmg->__remove_next = true; - next_sticky = vma_flags_and_mask(&next->flags, VMA_STICKY_FLAGS); - vma_flags_set_mask(&sticky_flags, next_sticky); + propagate_sticky_flags(vmg, next); } if (commit_merge(vmg)) goto nomem; - vma_set_flags_mask(target, sticky_flags); return 0; nomem: @@ -1882,12 +1887,28 @@ struct vm_area_struct *vma_merge_extend(struct vma_iterator *vmi, struct vm_area_struct *vma, unsigned long delta) { - VMG_VMA_STATE(vmg, vmi, vma, vma, vma->vm_end, vma->vm_end + delta); + const bool can_merge = !vma_test_any(vma, VMA_PFNMAP_BIT, + VMA_DONTEXPAND_BIT, VMA_MIXEDMAP_BIT) && + !is_vm_hugetlb_page(vma); + const unsigned long start = + can_merge ? vma->vm_end : vma->vm_start; + VMG_VMA_STATE(vmg, vmi, vma, vma, start, vma->vm_end + delta); - vmg.next = vma_iter_next_rewind(vmi, NULL); vmg.middle = NULL; /* We use the VMA to populate VMG fields only. */ - return vma_merge_new_range(&vmg); + if (can_merge) { + vmg.next = vma_iter_next_rewind(vmi, NULL); + return vma_merge_new_range(&vmg); + } + + /* Mixed mappings are permitted to be expanded, not merged. */ + VM_WARN_ON_ONCE(vma_test_any(vma, VMA_PFNMAP_BIT, VMA_DONTEXPAND_BIT)); + VM_WARN_ON_ONCE(!vma_test(vma, VMA_MIXEDMAP_BIT)); + vma_prev(vmi); /* Reposition to start of VMA. */ + vmg.target = vma; + if (vma_expand(&vmg)) + return NULL; + return vma; } void unlink_file_vma_batch_init(struct unlink_vma_file_batch *vb) diff --git a/net/9p/trans_xen.c b/net/9p/trans_xen.c index 71a4d276321e..69a5129a9b64 100644 --- a/net/9p/trans_xen.c +++ b/net/9p/trans_xen.c @@ -291,14 +291,14 @@ static void xen_9pfs_front_free(struct xen_9pfs_front_priv *priv) for (i = 0; i < XEN_9PFS_NUM_RINGS; i++) { struct xen_9pfs_dataring *ring = &priv->rings[i]; - cancel_work_sync(&ring->work); - if (!ring->intf) break; if (ring->irq >= 0) { unbind_from_irqhandler(ring->irq, ring); ring->irq = -1; } + cancel_work_sync(&ring->work); + if (ring->data.in) { for (j = 0; j < (1 << ring->intf->ring_order); j++) { diff --git a/net/Kconfig b/net/Kconfig index e38477393551..76ab44aa439a 100644 --- a/net/Kconfig +++ b/net/Kconfig @@ -68,7 +68,6 @@ config SKB_EXTENSIONS config NET_DEVMEM def_bool y - select GENERIC_ALLOCATOR depends on DMA_SHARED_BUFFER depends on PAGE_POOL diff --git a/net/bluetooth/6lowpan.c b/net/bluetooth/6lowpan.c index 20fb20eea8e7..99fee6f4de88 100644 --- a/net/bluetooth/6lowpan.c +++ b/net/bluetooth/6lowpan.c @@ -706,6 +706,7 @@ static int setup_netdev(struct l2cap_chan *chan, struct lowpan_btle_dev **dev) spin_lock(&devices_lock); list_del_rcu(&(*dev)->list); spin_unlock(&devices_lock); + synchronize_rcu(); free_netdev(netdev); goto out; } @@ -912,18 +913,27 @@ 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_close_unlocked(chan, ENOENT); + l2cap_chan_put(chan); return 0; } @@ -1025,9 +1035,9 @@ static void disconnect_all_peers(void) struct lowpan_peer *peer; int nchans; - /* l2cap_chan_close() cannot be called from RCU, and lock ordering - * chan->lock > devices_lock prevents taking write side lock, so copy - * then close. + /* l2cap_chan_close_unlocked() cannot be called from RCU, and lock + * ordering chan->lock > devices_lock prevents taking write side lock, + * so copy then close. */ rcu_read_lock(); @@ -1062,9 +1072,7 @@ static void disconnect_all_peers(void) spin_unlock(&devices_lock); for (i = 0; i < nchans; ++i) { - l2cap_chan_lock(chans[i]); - l2cap_chan_close(chans[i], ENOENT); - l2cap_chan_unlock(chans[i]); + l2cap_chan_close_unlocked(chans[i], ENOENT); l2cap_chan_put(chans[i]); } } while (nchans); @@ -1082,9 +1090,7 @@ static void do_enable_set(bool flag) mutex_lock(&set_lock); if (listen_chan) { - l2cap_chan_lock(listen_chan); - l2cap_chan_close(listen_chan, 0); - l2cap_chan_unlock(listen_chan); + l2cap_chan_close_unlocked(listen_chan, 0); l2cap_chan_put(listen_chan); } @@ -1132,9 +1138,7 @@ static ssize_t lowpan_control_write(struct file *fp, mutex_lock(&set_lock); if (listen_chan) { - l2cap_chan_lock(listen_chan); - l2cap_chan_close(listen_chan, 0); - l2cap_chan_unlock(listen_chan); + l2cap_chan_close_unlocked(listen_chan, 0); l2cap_chan_put(listen_chan); listen_chan = NULL; } @@ -1270,7 +1274,7 @@ static int device_event(struct notifier_block *unused, if (entry->netdev == netdev) { BT_DBG("Unregistered netdev %s %p", netdev->name, netdev); - list_del(&entry->list); + list_del_rcu(&entry->list); break; } } @@ -1304,10 +1308,9 @@ static void __exit bt_6lowpan_exit(void) debugfs_remove(lowpan_control_debugfs); if (listen_chan) { - l2cap_chan_lock(listen_chan); - l2cap_chan_close(listen_chan, 0); - l2cap_chan_unlock(listen_chan); + l2cap_chan_close_unlocked(listen_chan, 0); l2cap_chan_put(listen_chan); + listen_chan = NULL; } disconnect_devices(); diff --git a/net/bluetooth/Makefile b/net/bluetooth/Makefile index ff466ea97436..b78ad98864d4 100644 --- a/net/bluetooth/Makefile +++ b/net/bluetooth/Makefile @@ -14,7 +14,7 @@ bluetooth_6lowpan-y := 6lowpan.o bluetooth-y := af_bluetooth.o hci_core.o hci_conn.o hci_event.o mgmt.o \ hci_sock.o hci_sysfs.o l2cap_core.o l2cap_sock.o smp.o lib.o \ ecdh_helper.o mgmt_util.o mgmt_config.o hci_codec.o eir.o hci_sync.o \ - hci_drv.o + hci_drv.o hci_h4.o bluetooth-$(CONFIG_DEV_COREDUMP) += coredump.o diff --git a/net/bluetooth/hci_core.c b/net/bluetooth/hci_core.c index 74d9865e08c2..becac4a223df 100644 --- a/net/bluetooth/hci_core.c +++ b/net/bluetooth/hci_core.c @@ -1153,16 +1153,16 @@ struct smp_ltk *hci_find_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr, continue; if (smp_ltk_is_sc(k) || ltk_role(k->type) == role) { - rcu_read_unlock(); - if (hci_is_blocked_key(hdev, HCI_BLOCKED_KEY_TYPE_LTK, k->val)) { bt_dev_warn_ratelimited(hdev, "LTK blocked for %pMR", &k->bdaddr); + rcu_read_unlock(); return NULL; } + rcu_read_unlock(); return k; } } diff --git a/net/bluetooth/hci_event.c b/net/bluetooth/hci_event.c index 03b805207ab0..3288f92fe41b 100644 --- a/net/bluetooth/hci_event.c +++ b/net/bluetooth/hci_event.c @@ -1247,8 +1247,6 @@ static u8 hci_cc_le_read_conn_interval(struct hci_dev *hdev, void *data, struct sk_buff *skb) { struct hci_rp_le_read_conn_interval *rp = data; - u16 min_interval = 0; - int i; bt_dev_dbg(hdev, "status 0x%2.2x", rp->status); @@ -1261,17 +1259,11 @@ static u8 hci_cc_le_read_conn_interval(struct hci_dev *hdev, void *data, return HCI_ERROR_UNSPECIFIED; } - /* Store the smallest minimum supported connection interval reported by - * the controller so the default rate parameters can be clamped to it. + /* Store the minimum supported connection interval so the default rate + * parameters can be clamped to it. It is reported on its own rather + * than derived from the groups, as there may be none. */ - for (i = 0; i < rp->num_grps; i++) { - u16 min = le16_to_cpu(rp->grps[i].min); - - if (!min_interval || min < min_interval) - min_interval = min; - } - - hdev->le_min_rate_interval = min_interval; + hdev->le_min_rate_interval = rp->min; return rp->status; } @@ -1617,6 +1609,39 @@ static u8 hci_cc_le_set_adv_enable(struct hci_dev *hdev, void *data, return rp->status; } +/* Update the enabled state of the instance(s) using the advertising set + * identified by handle. + * + * Instances may share handle 0x00 with instance 0 (Global Advertising), e.g. + * when the controller supports a single advertising set, in which case the + * set is owned by the instance last enabled (hdev->cur_adv_instance) and any + * other instance sharing it shall be considered disabled. + */ +static void hci_le_ext_adv_set_enabled(struct hci_dev *hdev, u8 handle, + bool enable) +{ + struct adv_info *adv; + bool owned = false; + + list_for_each_entry(adv, &hdev->adv_instances, list) { + if (adv->handle != handle) + continue; + + adv->enabled = enable && + (handle || + adv->instance == hdev->cur_adv_instance); + owned |= adv->enabled; + } + + if (handle) + return; + + if (enable && !owned) + hci_dev_set_flag(hdev, HCI_LE_ADV_0); + else + hci_dev_clear_flag(hdev, HCI_LE_ADV_0); +} + static u8 hci_cc_le_set_ext_adv_enable(struct hci_dev *hdev, void *data, struct sk_buff *skb) { @@ -1638,18 +1663,13 @@ static u8 hci_cc_le_set_ext_adv_enable(struct hci_dev *hdev, void *data, hci_dev_lock(hdev); - if (cp->num_of_sets) - adv = hci_find_adv_instance(hdev, set->handle); - if (cp->enable) { struct hci_conn *conn; hci_dev_set_flag(hdev, HCI_LE_ADV); - if (adv) - adv->enabled = true; - else if (!set->handle) - hci_dev_set_flag(hdev, HCI_LE_ADV_0); + if (cp->num_of_sets) + hci_le_ext_adv_set_enabled(hdev, set->handle, true); conn = hci_lookup_le_connect(hdev); if (conn) @@ -1658,21 +1678,25 @@ static u8 hci_cc_le_set_ext_adv_enable(struct hci_dev *hdev, void *data, conn->conn_timeout); } else { if (cp->num_of_sets) { - if (adv) - adv->enabled = false; - else if (!set->handle) - hci_dev_clear_flag(hdev, HCI_LE_ADV_0); + hci_le_ext_adv_set_enabled(hdev, set->handle, false); /* If just one instance was disabled check if there are - * any other instance enabled before clearing HCI_LE_ADV + * any other instance enabled, including instance 0, + * before clearing HCI_LE_ADV */ + if (hci_dev_test_flag(hdev, HCI_LE_ADV_0)) + goto unlock; + list_for_each_entry_safe(adv, n, &hdev->adv_instances, list) { if (adv->enabled) goto unlock; } } else { - /* All instances shall be considered disabled */ + /* All instances shall be considered disabled, except + * instance 0 whose state is preserved so it can be + * re-enabled by hci_resume_advertising_sync. + */ list_for_each_entry_safe(adv, n, &hdev->adv_instances, list) adv->enabled = false; @@ -2957,8 +2981,25 @@ static void hci_cs_le_read_remote_features(struct hci_dev *hdev, u8 status) hci_dev_lock(hdev); conn = hci_conn_hash_lookup_handle(hdev, __le16_to_cpu(cp->handle)); - if (conn && conn->state == BT_CONFIG) + if (conn && 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_dev_unlock(hdev); } @@ -4007,8 +4048,17 @@ static void hci_cs_le_read_all_remote_features(struct hci_dev *hdev, u8 status) hci_dev_lock(hdev); conn = hci_conn_hash_lookup_handle(hdev, __le16_to_cpu(cp->handle)); - if (conn && conn->state == BT_CONFIG) + if (conn && conn->state == BT_CONFIG) { + /* See hci_cs_le_read_remote_features() */ + 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_dev_unlock(hdev); } diff --git a/net/bluetooth/hci_h4.c b/net/bluetooth/hci_h4.c new file mode 100644 index 000000000000..86f809018062 --- /dev/null +++ b/net/bluetooth/hci_h4.c @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * Bluetooth HCI H:4 packet reassembly + * + * Copyright (C) 2000-2001 Qualcomm Incorporated + * Copyright (C) 2002-2003 Maxim Krasnyansky + * Copyright (C) 2004-2005 Marcel Holtmann + */ + +#include +#include +#include + +#include +#include +#include + +/* h4_recv_skb - Reassemble H:4 framed packets + * @hdev: HCI device the packets are received on + * @alignment: optional packet alignment, NULL or 0 means no alignment + * @padding: optional padding state carried over between calls + * @skb: partially received packet from a previous call, may be NULL or an + * ERR_PTR returned by a previous call + * @buffer: buffer holding the received data + * @count: number of bytes in @buffer + * @pkts: table of supported packet types + * @pkts_count: number of entries in @pkts + * + * Returns the partially received packet to be passed to the next call, or an + * ERR_PTR on error. The returned value can be fed back into this function as + * is, but must be checked with IS_ERR() before being freed. + */ +struct sk_buff *h4_recv_skb(struct hci_dev *hdev, u8 *alignment, u8 *padding, + struct sk_buff *skb, const unsigned char *buffer, + int count, const struct h4_recv_pkt *pkts, + int pkts_count) +{ + u8 align = alignment && *alignment ? *alignment : 1; + + /* Check for error from previous call */ + if (IS_ERR(skb)) + skb = NULL; + + while (count) { + int i, len; + + /* remove padding bytes from buffer */ + if (padding) { + for (; (*padding) && count > 0; (*padding)--) { + count--; + buffer++; + } + } + + if (!count) + break; + + if (!skb) { + for (i = 0; i < pkts_count; i++) { + if (buffer[0] != pkts[i].type) + continue; + + skb = bt_skb_alloc(pkts[i].maxlen, + GFP_ATOMIC); + if (!skb) + return ERR_PTR(-ENOMEM); + + hci_skb_pkt_type(skb) = pkts[i].type; + hci_skb_expect(skb) = pkts[i].hlen; + break; + } + + /* Check for invalid packet type */ + if (!skb) + return ERR_PTR(-EILSEQ); + + count -= 1; + buffer += 1; + } + + len = min_t(uint, hci_skb_expect(skb) - skb->len, count); + skb_put_data(skb, buffer, len); + + count -= len; + buffer += len; + + /* Check for partial packet */ + if (skb->len < hci_skb_expect(skb)) + continue; + + for (i = 0; i < pkts_count; i++) { + if (hci_skb_pkt_type(skb) == pkts[i].type) + break; + } + + if (i >= pkts_count) { + kfree_skb(skb); + return ERR_PTR(-EILSEQ); + } + + if (skb->len == pkts[i].hlen) { + u16 dlen; + + switch (pkts[i].lsize) { + case 0: + /* No variable data length */ + dlen = 0; + break; + case 1: + /* Single octet variable length */ + dlen = skb->data[pkts[i].loff]; + hci_skb_expect(skb) += dlen; + + if (skb_tailroom(skb) < dlen) { + kfree_skb(skb); + return ERR_PTR(-EMSGSIZE); + } + break; + case 2: + /* Double octet variable length */ + dlen = get_unaligned_le16(skb->data + + pkts[i].loff); + hci_skb_expect(skb) += dlen; + + if (skb_tailroom(skb) < dlen) { + kfree_skb(skb); + return ERR_PTR(-EMSGSIZE); + } + break; + default: + /* Unsupported variable length */ + kfree_skb(skb); + return ERR_PTR(-EILSEQ); + } + + if (!dlen) { + if (padding) { + *padding = (skb->len + 1) % align; + *padding = (align - *padding) % align; + } + + /* No more data, complete frame */ + pkts[i].recv(hdev, skb); + skb = NULL; + } + } else { + if (padding) { + *padding = (skb->len + 1) % align; + *padding = (align - *padding) % align; + } + + /* Complete frame */ + pkts[i].recv(hdev, skb); + skb = NULL; + } + } + + return skb; +} +EXPORT_SYMBOL_GPL(h4_recv_skb); diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c index 5b99da7028b9..4e5c47872c30 100644 --- a/net/bluetooth/hci_sync.c +++ b/net/bluetooth/hci_sync.c @@ -1158,14 +1158,38 @@ int hci_update_random_address_sync(struct hci_dev *hdev, bool require_privacy, return 0; } -static int hci_disable_ext_adv_legacy_instance_sync(struct hci_dev *hdev) +/* Check if the advertising set with handle 0x00 is in use, either by instance + * 0 or by an instance sharing its advertising set. + */ +static bool hci_ext_adv_handle_0_enabled(struct hci_dev *hdev) +{ + struct adv_info *adv; + bool enabled; + + hci_dev_lock(hdev); + + enabled = hci_dev_test_flag(hdev, HCI_LE_ADV_0); + + list_for_each_entry(adv, &hdev->adv_instances, list) { + if (!adv->handle && adv->enabled) { + enabled = true; + break; + } + } + + hci_dev_unlock(hdev); + + return enabled; +} + +int hci_disable_ext_adv_legacy_instance_sync(struct hci_dev *hdev) { struct hci_cp_le_set_ext_adv_enable *cp; struct hci_cp_ext_adv_set *set; u8 data[sizeof(*cp) + sizeof(*set) * 1]; u8 size; - if (!hci_dev_test_flag(hdev, HCI_LE_ADV_0)) + if (!hci_ext_adv_handle_0_enabled(hdev)) return 0; memset(data, 0, sizeof(data)); @@ -1411,6 +1435,9 @@ int hci_setup_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance) return -EINVAL; } } else { + /* Disable the advertising set with handle 0x00, including any + * instance sharing it, since it is going to be overridden. + */ err = hci_disable_ext_adv_legacy_instance_sync(hdev); if (err) return err; @@ -1672,12 +1699,19 @@ int hci_enable_ext_advertising_sync(struct hci_dev *hdev, u8 instance) * scheduling it. */ if (adv && adv->timeout) { - u16 duration = adv->timeout * MSEC_PER_SEC; + u16 duration = adv->mesh ? adv->timeout : + adv->timeout * MSEC_PER_SEC; /* Time = N * 10 ms */ set->duration = cpu_to_le16(duration / 10); } + /* Track which instance owns the advertising set since the handle + * alone is ambiguous when instances share handle 0x00, see + * hci_cc_le_set_ext_adv_enable. + */ + hdev->cur_adv_instance = instance; + return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_ADV_ENABLE, sizeof(*cp) + sizeof(*set) * cp->num_of_sets, @@ -2103,7 +2137,8 @@ int hci_schedule_adv_instance_sync(struct hci_dev *hdev, u8 instance, hdev->adv_instance_timeout = timeout; queue_delayed_work(hdev->req_workqueue, &hdev->adv_instance_expire, - secs_to_jiffies(timeout)); + adv->mesh ? msecs_to_jiffies(timeout) : + secs_to_jiffies(timeout)); } /* If we're just re-scheduling the same instance again then do not @@ -2556,13 +2591,19 @@ static int hci_le_set_privacy_mode_sync(struct hci_dev *hdev, if (!(params->flags & HCI_CONN_FLAG_DEVICE_PRIVACY)) 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; + } memset(&cp, 0, sizeof(cp)); cp.bdaddr_type = irk->addr_type; bacpy(&cp.bdaddr, &irk->bdaddr); + rcu_read_unlock(); + cp.mode = HCI_DEVICE_PRIVACY; /* Note: params->privacy_mode is not updated since it is a copy */ @@ -2577,7 +2618,7 @@ static int hci_le_set_privacy_mode_sync(struct hci_dev *hdev, */ static int hci_le_add_accept_list_sync(struct hci_dev *hdev, struct conn_params *params, - u8 *num_entries) + u8 *num_entries, bool force_filter) { struct hci_cp_le_add_to_accept_list cp; int err; @@ -2590,6 +2631,11 @@ static int hci_le_add_accept_list_sync(struct hci_dev *hdev, return 0; } + /* Host-resolved peers need unfiltered scanning while awake. */ + if (!force_filter && !hdev->suspended && !ll_privacy_capable(hdev) && + hci_find_irk_by_addr(hdev, ¶ms->addr, params->addr_type)) + return -EINVAL; + /* Select filter policy to accept all advertising */ if (*num_entries >= hdev->le_accept_list_size) return -ENOSPC; @@ -2921,7 +2967,7 @@ static u8 hci_update_accept_list_sync(struct hci_dev *hdev) num_entries = 1; err = hci_le_add_accept_list_sync(hdev, &pa, - &num_entries); + &num_entries, true); goto done; } else { rcu_read_unlock(); @@ -2985,7 +3031,7 @@ static u8 hci_update_accept_list_sync(struct hci_dev *hdev) for (i = 0; i < n; ++i) { err = hci_le_add_accept_list_sync(hdev, ¶ms[i], - &num_entries); + &num_entries, false); if (err) { kvfree(params); goto done; @@ -3007,7 +3053,7 @@ static u8 hci_update_accept_list_sync(struct hci_dev *hdev) for (i = 0; i < n; ++i) { err = hci_le_add_accept_list_sync(hdev, ¶ms[i], - &num_entries); + &num_entries, false); if (err) { kvfree(params); goto done; @@ -5444,7 +5490,9 @@ int hci_dev_open_sync(struct hci_dev *hdev) goto done; } + hci_dev_lock(hdev); hci_devcd_reset(hdev); + hci_dev_unlock(hdev); set_bit(HCI_RUNNING, &hdev->flags); hci_sock_dev_event(hdev, HCI_DEV_OPEN); diff --git a/net/bluetooth/iso.c b/net/bluetooth/iso.c index d6ac5b1f49bc..8768d9c0cf51 100644 --- a/net/bluetooth/iso.c +++ b/net/bluetooth/iso.c @@ -287,8 +287,11 @@ static void iso_chan_del(struct sock *sk, int err) parent = bt_sk(sk)->parent; if (parent) { + /* Unlinking the child allows the parent to be freed. */ + sock_hold(parent); bt_accept_unlink(sk); parent->sk_data_ready(parent); + sock_put(parent); } else { sk->sk_state_change(sk); } diff --git a/net/bluetooth/l2cap_core.c b/net/bluetooth/l2cap_core.c index 47f0449588ea..443392cb1748 100644 --- a/net/bluetooth/l2cap_core.c +++ b/net/bluetooth/l2cap_core.c @@ -59,6 +59,7 @@ static void l2cap_tx(struct l2cap_chan *chan, struct l2cap_ctrl *control, static void l2cap_retrans_timeout(struct work_struct *work); static void l2cap_monitor_timeout(struct work_struct *work); static void l2cap_ack_timeout(struct work_struct *work); +static void __l2cap_chan_close(struct l2cap_chan *chan, int reason); static inline u8 bdaddr_type(u8 link_type, u8 bdaddr_type) { @@ -109,7 +110,7 @@ static struct l2cap_chan *__l2cap_get_chan_by_scid(struct l2cap_conn *conn, } /* Find channel with given SCID. - * Returns a reference locked channel. + * Returns a reference. */ static struct l2cap_chan *l2cap_get_chan_by_scid(struct l2cap_conn *conn, u16 cid) @@ -117,18 +118,14 @@ static struct l2cap_chan *l2cap_get_chan_by_scid(struct l2cap_conn *conn, struct l2cap_chan *c; c = __l2cap_get_chan_by_scid(conn, cid); - if (c) { - /* Only lock if chan reference is not 0 */ + if (c) c = l2cap_chan_hold_unless_zero(c); - if (c) - l2cap_chan_lock(c); - } return c; } /* Find channel with given DCID. - * Returns a reference locked channel. + * Returns a reference. */ static struct l2cap_chan *l2cap_get_chan_by_dcid(struct l2cap_conn *conn, u16 cid) @@ -136,12 +133,8 @@ static struct l2cap_chan *l2cap_get_chan_by_dcid(struct l2cap_conn *conn, struct l2cap_chan *c; c = __l2cap_get_chan_by_dcid(conn, cid); - if (c) { - /* Only lock if chan reference is not 0 */ + if (c) c = l2cap_chan_hold_unless_zero(c); - if (c) - l2cap_chan_lock(c); - } return c; } @@ -456,7 +449,7 @@ static void l2cap_chan_timeout(struct work_struct *work) else reason = ETIMEDOUT; - l2cap_chan_close(chan, reason); + __l2cap_chan_close(chan, reason); chan->ops->close(chan); @@ -703,7 +696,9 @@ void __l2cap_chan_add(struct l2cap_conn *conn, struct l2cap_chan *chan) void l2cap_chan_add(struct l2cap_conn *conn, struct l2cap_chan *chan) { mutex_lock(&conn->lock); + l2cap_chan_lock(chan); __l2cap_chan_add(conn, chan); + l2cap_chan_unlock(chan); mutex_unlock(&conn->lock); } @@ -865,7 +860,7 @@ static void l2cap_chan_connect_reject(struct l2cap_chan *chan) l2cap_send_cmd(conn, chan->ident, L2CAP_CONN_RSP, sizeof(rsp), &rsp); } -void l2cap_chan_close(struct l2cap_chan *chan, int reason) +static void __l2cap_chan_close(struct l2cap_chan *chan, int reason) { struct l2cap_conn *conn = chan->conn; @@ -914,8 +909,58 @@ void l2cap_chan_close(struct l2cap_chan *chan, int reason) break; } } + +void l2cap_chan_close(struct l2cap_chan *chan, int reason) +{ + __l2cap_chan_close(chan, reason); +} EXPORT_SYMBOL(l2cap_chan_close); +/* Take chan->lock. If chan->conn is non-NULL, take new reference on it, take + * chan->conn->lock, and return true. Otherwise return false. + */ +bool l2cap_chan_lock_conn(struct l2cap_chan *chan) + __context_unsafe(/* conditional locking */) +{ + /* Handle conn->lock > chan->lock ordering + race on chan->conn */ + for (;;) { + struct l2cap_conn *conn; + + l2cap_chan_lock(chan); + conn = chan->conn; + if (conn) + l2cap_conn_get(conn); + l2cap_chan_unlock(chan); + + if (conn) + mutex_lock(&conn->lock); + + l2cap_chan_lock(chan); + + if (chan->conn != conn) { + l2cap_chan_unlock(chan); + if (conn) { + mutex_unlock(&conn->lock); + l2cap_conn_put(conn); + } + schedule(); + continue; + } + + return chan->conn; + } +} + +void l2cap_chan_close_unlocked(struct l2cap_chan *chan, int reason) +{ + bool have_conn; + + have_conn = l2cap_chan_lock_conn(chan); + __l2cap_chan_close(chan, reason); + l2cap_chan_unlock_conn(chan, have_conn); +} +EXPORT_SYMBOL(l2cap_chan_close_unlocked); + static inline u8 l2cap_get_auth_type(struct l2cap_chan *chan) { switch (chan->chan_type) { @@ -1606,7 +1651,7 @@ static void l2cap_conn_start(struct l2cap_conn *conn) if (!l2cap_mode_supported(chan->mode, conn->feat_mask) && test_bit(CONF_STATE2_DEVICE, &chan->conf_state)) { - l2cap_chan_close(chan, ECONNRESET); + __l2cap_chan_close(chan, ECONNRESET); l2cap_chan_unlock(chan); continue; } @@ -1614,7 +1659,7 @@ static void l2cap_conn_start(struct l2cap_conn *conn) if (l2cap_check_enc_key_size(conn->hcon, chan)) l2cap_start_connection(chan); else - l2cap_chan_close(chan, ECONNREFUSED); + __l2cap_chan_close(chan, ECONNREFUSED); } else if (chan->state == BT_CONNECT2) { struct l2cap_conn_rsp rsp; @@ -4136,6 +4181,8 @@ static struct l2cap_chan *l2cap_new_connection(struct l2cap_conn *conn, if (!chan) return NULL; + l2cap_chan_lock(chan); + l2cap_chan_set_defaults(chan, pchan); chan->ops = pchan->ops; @@ -4144,15 +4191,19 @@ static struct l2cap_chan *l2cap_new_connection(struct l2cap_conn *conn, if (pchan->ops->new_connection && pchan->ops->new_connection(pchan, chan) < 0) { l2cap_chan_del(chan, 0); + l2cap_chan_unlock(chan); l2cap_chan_put(chan); return NULL; } + l2cap_chan_unlock(chan); + return chan; } static void l2cap_connect(struct l2cap_conn *conn, struct l2cap_cmd_hdr *cmd, u8 *data, u8 rsp_code) + __context_unsafe(/* conditional locking */) { struct l2cap_conn_req *req = (struct l2cap_conn_req *) data; struct l2cap_conn_rsp rsp; @@ -4439,6 +4490,8 @@ static inline int l2cap_config_req(struct l2cap_conn *conn, return 0; } + l2cap_chan_lock(chan); + if (chan->state != BT_CONFIG && chan->state != BT_CONNECT2 && chan->state != BT_CONNECTED) { cmd_reject_invalid_cid(conn, cmd->ident, chan->scid, @@ -4556,6 +4609,8 @@ static inline int l2cap_config_rsp(struct l2cap_conn *conn, if (!chan) return 0; + l2cap_chan_lock(chan); + /* Connected channels may also receive reconfiguration responses. */ if (chan->state != BT_CONFIG && chan->state != BT_CONNECTED) goto done; @@ -4669,6 +4724,8 @@ static inline int l2cap_disconnect_req(struct l2cap_conn *conn, return 0; } + l2cap_chan_lock(chan); + rsp.dcid = cpu_to_le16(chan->scid); rsp.scid = cpu_to_le16(chan->dcid); l2cap_send_cmd(conn, cmd->ident, L2CAP_DISCONN_RSP, sizeof(rsp), &rsp); @@ -4706,6 +4763,8 @@ static inline int l2cap_disconnect_rsp(struct l2cap_conn *conn, return 0; } + l2cap_chan_lock(chan); + if (chan->state != BT_DISCONN) { l2cap_chan_unlock(chan); l2cap_chan_put(chan); @@ -5130,6 +5189,8 @@ static int l2cap_le_connect_req(struct l2cap_conn *conn, goto response_unlock; } + l2cap_chan_lock(chan); + bacpy(&chan->src, &conn->hcon->src); bacpy(&chan->dst, &conn->hcon->dst); chan->src_type = bdaddr_src_type(conn->hcon); @@ -5163,6 +5224,8 @@ static int l2cap_le_connect_req(struct l2cap_conn *conn, result = L2CAP_CR_LE_SUCCESS; } + l2cap_chan_unlock(chan); + response_unlock: l2cap_chan_unlock(pchan); l2cap_chan_put(pchan); @@ -5209,6 +5272,8 @@ static inline int l2cap_le_credits(struct l2cap_conn *conn, if (!chan) return -EBADSLT; + l2cap_chan_lock(chan); + max_credits = LE_FLOWCTL_MAX_CREDITS - chan->tx_credits; if (credits > max_credits) { BT_ERR("LE credits overflow"); @@ -5353,6 +5418,8 @@ static inline int l2cap_ecred_conn_req(struct l2cap_conn *conn, continue; } + l2cap_chan_lock(chan); + bacpy(&chan->src, &conn->hcon->src); bacpy(&chan->dst, &conn->hcon->dst); chan->src_type = bdaddr_src_type(conn->hcon); @@ -5385,6 +5452,8 @@ static inline int l2cap_ecred_conn_req(struct l2cap_conn *conn, } else { l2cap_chan_ready(chan); } + + l2cap_chan_unlock(chan); } unlock: @@ -5436,12 +5505,14 @@ static inline int l2cap_ecred_conn_rsp(struct l2cap_conn *conn, chan->state == BT_CONNECTED) continue; + l2cap_chan_hold(chan); l2cap_chan_lock(chan); /* Check that there is a dcid for each pending channel */ if (cmd_len < sizeof(dcid)) { l2cap_chan_del(chan, ECONNREFUSED); l2cap_chan_unlock(chan); + l2cap_chan_put(chan); continue; } @@ -5480,6 +5551,8 @@ static inline int l2cap_ecred_conn_rsp(struct l2cap_conn *conn, __set_chan_timer(orig, 0); l2cap_chan_unlock(orig); } + + l2cap_chan_put(chan); continue; } @@ -5525,6 +5598,7 @@ static inline int l2cap_ecred_conn_rsp(struct l2cap_conn *conn, } l2cap_chan_unlock(chan); + l2cap_chan_put(chan); } return err; @@ -7076,6 +7150,8 @@ static void l2cap_data_channel(struct l2cap_conn *conn, u16 cid, return; } + l2cap_chan_lock(chan); + BT_DBG("chan %p, len %d", chan, skb->len); /* If we receive data on a fixed channel before the info req/rsp @@ -7662,6 +7738,8 @@ static void l2cap_connect_cfm(struct hci_conn *hcon, u8 status) * we left off, because the list lock would prevent calling the * potentially sleeping l2cap_chan_lock() function. */ + mutex_lock(&conn->lock); + pchan = l2cap_global_fixed_chan(NULL, hcon); while (pchan) { struct l2cap_chan *chan, *next; @@ -7686,6 +7764,8 @@ static void l2cap_connect_cfm(struct hci_conn *hcon, u8 status) pchan = next; } + mutex_unlock(&conn->lock); + l2cap_conn_ready(conn); } @@ -7726,7 +7806,7 @@ static inline void l2cap_check_encryption(struct l2cap_chan *chan, u8 encrypt) __set_chan_timer(chan, L2CAP_ENC_TIMEOUT); } else if (chan->sec_level == BT_SECURITY_HIGH || chan->sec_level == BT_SECURITY_FIPS) - l2cap_chan_close(chan, ECONNREFUSED); + __l2cap_chan_close(chan, ECONNREFUSED); } else { if (chan->sec_level == BT_SECURITY_MEDIUM) __clear_chan_timer(chan); diff --git a/net/bluetooth/l2cap_sock.c b/net/bluetooth/l2cap_sock.c index 1eab4478abf4..1796929f61b8 100644 --- a/net/bluetooth/l2cap_sock.c +++ b/net/bluetooth/l2cap_sock.c @@ -1249,40 +1249,68 @@ static void l2cap_publish_rx_avail(struct l2cap_chan *chan) l2cap_chan_rx_avail(chan, -1); } -static int l2cap_sock_recvmsg(struct socket *sock, struct msghdr *msg, - size_t len, int flags) +static int l2cap_sock_defer(struct sock *sk) { - struct sock *sk = sock->sk; - struct l2cap_pinfo *pi = l2cap_pi(sk); - int err; + struct l2cap_chan *chan = l2cap_pi(sk)->chan; + bool have_conn; + int err = 0; - if (unlikely(flags & MSG_ERRQUEUE)) - return sock_recv_errqueue(sk, msg, len, SOL_BLUETOOTH, - BT_SCM_ERROR); + /* Fast path check */ + lock_sock(sk); + if (sk->sk_state != BT_CONNECT2) { + release_sock(sk); + return 0; + } + release_sock(sk); + have_conn = l2cap_chan_lock_conn(chan); lock_sock(sk); if (sk->sk_state == BT_CONNECT2 && test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) { - if (pi->chan->mode == L2CAP_MODE_EXT_FLOWCTL) { + err = 1; + + if (!have_conn) { + release_sock(sk); + err = -ENOTCONN; + } else if (chan->mode == L2CAP_MODE_EXT_FLOWCTL) { sk->sk_state = BT_CONNECTED; - pi->chan->state = BT_CONNECTED; - __l2cap_ecred_conn_rsp_defer(pi->chan); - } else if (bdaddr_type_is_le(pi->chan->src_type)) { + chan->state = BT_CONNECTED; + release_sock(sk); + __l2cap_ecred_conn_rsp_defer(chan); + } else if (bdaddr_type_is_le(chan->src_type)) { sk->sk_state = BT_CONNECTED; - pi->chan->state = BT_CONNECTED; - __l2cap_le_connect_rsp_defer(pi->chan); + chan->state = BT_CONNECTED; + release_sock(sk); + __l2cap_le_connect_rsp_defer(chan); } else { sk->sk_state = BT_CONFIG; - pi->chan->state = BT_CONFIG; - __l2cap_connect_rsp_defer(pi->chan); + chan->state = BT_CONFIG; + release_sock(sk); + __l2cap_connect_rsp_defer(chan); } - - err = 0; - goto done; + } else { + release_sock(sk); } - release_sock(sk); + l2cap_chan_unlock_conn(chan, have_conn); + return err; +} + +static int l2cap_sock_recvmsg(struct socket *sock, struct msghdr *msg, + size_t len, int flags) +{ + struct sock *sk = sock->sk; + struct l2cap_pinfo *pi = l2cap_pi(sk); + int err; + + if (unlikely(flags & MSG_ERRQUEUE)) + return sock_recv_errqueue(sk, msg, len, SOL_BLUETOOTH, + BT_SCM_ERROR); + + err = l2cap_sock_defer(sk); + if (err) + return err < 0 ? err : 0; if (sock->type == SOCK_STREAM) err = bt_sock_stream_recvmsg(sock, msg, len, flags); @@ -1412,7 +1440,6 @@ static int l2cap_sock_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; struct l2cap_chan *chan; - struct l2cap_conn *conn; int err = 0; BT_DBG("sock %p, sk %p, how %d", sock, sk, how); @@ -1469,23 +1496,7 @@ static int l2cap_sock_shutdown(struct socket *sock, int how) sk->sk_shutdown |= SEND_SHUTDOWN; release_sock(sk); - l2cap_chan_lock(chan); - /* prevent conn structure from being freed */ - conn = l2cap_conn_hold_unless_zero(chan->conn); - l2cap_chan_unlock(chan); - - if (conn) - /* mutex lock must be taken before l2cap_chan_lock() */ - mutex_lock(&conn->lock); - - l2cap_chan_lock(chan); - l2cap_chan_close(chan, 0); - l2cap_chan_unlock(chan); - - if (conn) { - mutex_unlock(&conn->lock); - l2cap_conn_put(conn); - } + l2cap_chan_close_unlocked(chan, 0); lock_sock(sk); @@ -1790,6 +1801,7 @@ static void l2cap_sock_state_change_cb(struct l2cap_chan *chan, int state, static struct sk_buff *l2cap_sock_alloc_skb_cb(struct l2cap_chan *chan, unsigned long hdr_len, unsigned long len, int nb) + __must_hold(&chan->lock) { struct sock *sk = chan->data; struct sk_buff *skb; diff --git a/net/bluetooth/mgmt.c b/net/bluetooth/mgmt.c index 251a896babd5..11f01b8d53f8 100644 --- a/net/bluetooth/mgmt.c +++ b/net/bluetooth/mgmt.c @@ -4906,6 +4906,13 @@ static int set_quality_report_func(struct sock *sk, struct hci_dev *hdev, hci_req_sync_lock(hdev); + if (hci_dev_test_flag(hdev, HCI_UNREGISTER)) { + err = mgmt_cmd_status(sk, hdev->id, + MGMT_OP_SET_EXP_FEATURE, + MGMT_STATUS_INVALID_INDEX); + goto unlock_quality_report; + } + val = !!cp->param[0]; changed = (val != hci_dev_test_flag(hdev, HCI_QUALITY_REPORT)); @@ -6533,7 +6540,12 @@ static void set_advertising_complete(struct hci_dev *hdev, void *data, int err) return; } - if (hci_dev_test_flag(hdev, HCI_LE_ADV)) + /* With extended advertising global advertising (instance 0) has its + * own advertising set so only consider its state, other instances may + * still be enabled. + */ + if (ext_adv_capable(hdev) ? hci_dev_test_flag(hdev, HCI_LE_ADV_0) : + hci_dev_test_flag(hdev, HCI_LE_ADV)) hci_dev_set_flag(hdev, HCI_ADVERTISING); else hci_dev_clear_flag(hdev, HCI_ADVERTISING); @@ -6553,6 +6565,34 @@ static void set_advertising_complete(struct hci_dev *hdev, void *data, int err) list_empty(&hdev->adv_instances)) return; + /* With extended advertising instances are not overridden by global + * advertising, except the ones sharing its set, so only (re)start the + * instances that are not already enabled. + * + * Lookup instances by identifier while holding hdev->lock since the + * list may change while waiting for the HCI commands to complete. + */ + if (ext_adv_capable(hdev)) { + u16 i; + + for (i = 1; i <= hdev->le_num_of_adv_sets + 1; i++) { + bool enabled; + + hci_dev_lock(hdev); + adv_instance = hci_find_adv_instance(hdev, i); + enabled = !adv_instance || adv_instance->enabled; + hci_dev_unlock(hdev); + + if (enabled) + continue; + + err = hci_schedule_adv_instance_sync(hdev, i, true); + enable_advertising_instance(hdev, err); + } + + return; + } + instance = hdev->cur_adv_instance; if (!instance) { adv_instance = list_first_entry_or_null(&hdev->adv_instances, @@ -6608,6 +6648,11 @@ static int set_adv_sync(struct hci_dev *hdev, void *data) hci_update_scan_rsp_data_sync(hdev, 0x00); hci_enable_advertising_sync(hdev); } + } else if (ext_adv_capable(hdev)) { + /* Only disable global advertising (instance 0) leaving other + * instances untouched. + */ + hci_disable_ext_adv_legacy_instance_sync(hdev); } else { hci_disable_advertising_sync(hdev); } @@ -8289,8 +8334,10 @@ static int load_conn_subrate(struct sock *sk, struct hci_dev *hdev, void *data, hci_param->cont_num = cont_num; hci_param->rate_supv_timeout = supv_timeout; - /* If the device is connected as central check if the - * connection rate parameters need to be updated. + /* If the device is connected check if the connection rate + * parameters need to be updated, either role can initiate the + * Connection Rate Update procedure, e.g. a HID device acting + * as peripheral once the HID host requests a HID SCI mode. */ if (!i && param_count == 1) { struct hci_conn *conn; @@ -8299,7 +8346,6 @@ static int load_conn_subrate(struct sock *sk, struct hci_dev *hdev, void *data, &hci_param->addr, addr_type); if (conn && conn->state == BT_CONNECTED && - conn->role == HCI_ROLE_MASTER && (conn->le_rate_interval < min || conn->le_rate_interval > max || conn->le_subrate < subrate_min || @@ -8939,6 +8985,21 @@ static bool adv_busy(struct hci_dev *hdev) return pending_find(MGMT_OP_SET_LE, hdev); } +/* Global advertising, enabled with MGMT_OP_SET_ADVERTISING, uses instance 0 + * and takes precedence over any instance that would share its advertising + * set: with legacy advertising there is only a single set so all instances + * are overridden, whereas with extended advertising only an instance using + * handle 0x00 is. + */ +static bool adv_overridden_by_global(struct hci_dev *hdev, + struct adv_info *adv) +{ + if (!hci_dev_test_flag(hdev, HCI_ADVERTISING)) + return false; + + return !ext_adv_capable(hdev) || !adv->handle; +} + static void add_adv_complete(struct hci_dev *hdev, struct sock *sk, u8 instance, int err) { @@ -9100,13 +9161,19 @@ static int add_advertising(struct sock *sk, struct hci_dev *hdev, schedule_instance = cp->instance; } - /* If the HCI_ADVERTISING flag is set or the device isn't powered or - * there is no instance to be advertised then we have no HCI - * communication to make. Simply return. + /* If the instance is overridden by global advertising or the device + * isn't powered or there is no instance to be advertised then we have + * no HCI communication to make. Simply return. */ if (!hdev_is_powered(hdev) || - hci_dev_test_flag(hdev, HCI_ADVERTISING) || + adv_overridden_by_global(hdev, adv) || !schedule_instance) { + /* Instance has been accepted so it shall no longer be + * considered pending, otherwise a later failure in + * add_adv_complete would remove it. + */ + adv->pending = false; + rp.instance = cp->instance; err = mgmt_cmd_complete(sk, hdev->id, MGMT_OP_ADD_ADVERTISING, MGMT_STATUS_SUCCESS, &rp, sizeof(rp)); @@ -9280,20 +9347,24 @@ static int add_ext_adv_params(struct sock *sk, struct hci_dev *hdev, goto unlock; } - /* Submit request for advertising params if ext adv available */ - if (ext_adv_capable(hdev)) { + /* Submit request for advertising params if ext adv available, unless + * the set is in use by global advertising in which case the params + * will be programmed once the instance is scheduled. + */ + if (ext_adv_capable(hdev) && !adv_overridden_by_global(hdev, adv)) { cmd = mgmt_pending_new(sk, MGMT_OP_ADD_EXT_ADV_PARAMS, hdev, data, data_len); if (!cmd) { err = -ENOMEM; - hci_remove_adv_instance(hdev, cp->instance); - goto unlock; + goto remove; } err = hci_cmd_sync_queue(hdev, add_ext_adv_params_sync, cmd, add_ext_adv_params_complete); - if (err < 0) + if (err < 0) { mgmt_pending_free(cmd); + goto remove; + } } else { rp.instance = cp->instance; rp.tx_power = HCI_ADV_TX_POWER_NO_PREFERENCE; @@ -9304,6 +9375,18 @@ static int add_ext_adv_params(struct sock *sk, struct hci_dev *hdev, MGMT_STATUS_SUCCESS, &rp, sizeof(rp)); } + goto unlock; + +remove: + /* The instance may have been modified already so remove it, like it + * is done in add_ext_adv_params_complete, signaling it has been + * removed if it was previously added. + */ + if (!adv->pending) + mgmt_advertising_removed(sk, hdev, cp->instance); + + hci_remove_adv_instance(hdev, cp->instance); + unlock: hci_dev_unlock(hdev); @@ -9431,11 +9514,12 @@ static int add_ext_adv_data(struct sock *sk, struct hci_dev *hdev, void *data, schedule_instance = cp->instance; } - /* If the HCI_ADVERTISING flag is set or there is no instance to - * be advertised then we have no HCI communication to make. + /* If the instance is overridden by global advertising or there is no + * instance to be advertised then we have no HCI communication to make. * Simply return. */ - if (hci_dev_test_flag(hdev, HCI_ADVERTISING) || !schedule_instance) { + if (adv_overridden_by_global(hdev, adv_instance) || + !schedule_instance) { if (adv_instance->pending) { mgmt_advertising_added(sk, hdev, cp->instance); adv_instance->pending = false; @@ -9511,7 +9595,11 @@ static int remove_advertising_sync(struct hci_dev *hdev, void *data) if (err) return err; - if (list_empty(&hdev->adv_instances)) + /* Don't disable advertising if global advertising (instance 0) is + * enabled since it is not affected by removing instances. + */ + if (list_empty(&hdev->adv_instances) && + !hci_dev_test_flag(hdev, HCI_ADVERTISING)) err = hci_disable_advertising_sync(hdev); return err; diff --git a/net/bluetooth/msft.c b/net/bluetooth/msft.c index d9dd722db3eb..2559c5b1bef0 100644 --- a/net/bluetooth/msft.c +++ b/net/bluetooth/msft.c @@ -654,8 +654,10 @@ void msft_do_open(struct hci_dev *hdev) msft->features = 0; if (!read_supported_features(hdev, msft)) { + hci_dev_lock(hdev); hdev->msft_data = NULL; kfree(msft); + hci_dev_unlock(hdev); return; } @@ -681,6 +683,8 @@ void msft_do_close(struct hci_dev *hdev) bt_dev_dbg(hdev, "Cleanup of MSFT extension"); + hci_dev_lock(hdev); + /* The controller will silently remove all monitors on power off. * Therefore, remove handle_data mapping and reset monitor state. */ @@ -695,6 +699,8 @@ void msft_do_close(struct hci_dev *hdev) kfree(handle_data); } + hci_dev_unlock(hdev); + mutex_lock(&msft->filter_lock); list_for_each_entry_safe(address_filter, n, &msft->address_filters, list) { diff --git a/net/bpf/test_run.c b/net/bpf/test_run.c index 513354e928cb..3043a7393c29 100644 --- a/net/bpf/test_run.c +++ b/net/bpf/test_run.c @@ -1237,7 +1237,13 @@ int bpf_prog_test_run_skb(struct bpf_prog *prog, const union bpf_attr *kattr, memset(__skb_push(skb, hh_len), 0, hh_len); } - if (kattr->test.flags & BPF_F_TEST_SKB_CHECKSUM_COMPLETE) { + /* + * A helper such as bpf_skb_change_tail() may have downgraded the skb + * from CHECKSUM_COMPLETE. skb->csum is then unused by the stack and + * there is nothing to validate. + */ + if ((kattr->test.flags & BPF_F_TEST_SKB_CHECKSUM_COMPLETE) && + skb->ip_summed == CHECKSUM_COMPLETE) { const int off = skb_network_offset(skb); int len = skb->len - off; __wsum csum; @@ -1650,20 +1656,19 @@ int bpf_prog_test_run_sk_lookup(struct bpf_prog *prog, const union bpf_attr *kat ctx.selected_sk = NULL; retval = BPF_PROG_SK_LOOKUP_RUN_ARRAY(progs, ctx, bpf_prog_run); } while (bpf_test_timer_continue(&t, 1, repeat, &ret, &duration)); - bpf_test_timer_leave(&t); - - if (ret < 0) - goto out; + /* Nothing but RCU keeps the selected socket */ user_ctx->cookie = 0; - if (ctx.selected_sk) { - if (ctx.selected_sk->sk_reuseport && !ctx.no_reuseport) { + if (!ret && ctx.selected_sk) { + if (ctx.selected_sk->sk_reuseport && !ctx.no_reuseport) ret = -EOPNOTSUPP; - goto out; - } - - user_ctx->cookie = sock_gen_cookie(ctx.selected_sk); + else + user_ctx->cookie = sock_gen_cookie(ctx.selected_sk); } + bpf_test_timer_leave(&t); + + if (ret < 0) + goto out; ret = bpf_test_finish(kattr, uattr, NULL, NULL, 0, 0, retval, duration); if (!ret) diff --git a/net/bridge/br_mdb.c b/net/bridge/br_mdb.c index a01bd280c722..0adcd1524ab2 100644 --- a/net/bridge/br_mdb.c +++ b/net/bridge/br_mdb.c @@ -819,6 +819,7 @@ static int br_mdb_add_group_src_fwd(const struct br_mdb_config *cfg, struct br_mdb_config sg_cfg; struct br_ip sg_ip; u8 flags = 0; + int err; sg_ip = cfg->group; sg_ip.src = src_ip->src; @@ -842,7 +843,11 @@ static int br_mdb_add_group_src_fwd(const struct br_mdb_config *cfg, sg_cfg.filter_mode = MCAST_INCLUDE; sg_cfg.rt_protocol = cfg->rt_protocol; sg_cfg.nlflags = cfg->nlflags; - return br_mdb_add_group_sg(&sg_cfg, sgmp, brmctx, flags, extack); + err = br_mdb_add_group_sg(&sg_cfg, sgmp, brmctx, flags, extack); + if (err) + br_multicast_del_group(sgmp); + + return err; } static int br_mdb_add_group_src(const struct br_mdb_config *cfg, @@ -1047,6 +1052,7 @@ static int br_mdb_add_group(const struct br_mdb_config *cfg, struct net_bridge_mcast *brmctx; struct br_ip group = cfg->group; unsigned char flags = 0; + int err; brmctx = __br_mdb_choose_context(br, entry, extack); if (!brmctx) @@ -1073,9 +1079,13 @@ static int br_mdb_add_group(const struct br_mdb_config *cfg, flags |= MDB_PG_FLAGS_PERMANENT; if (br_multicast_is_star_g(&group)) - return br_mdb_add_group_star_g(cfg, mp, brmctx, flags, extack); + err = br_mdb_add_group_star_g(cfg, mp, brmctx, flags, extack); else - return br_mdb_add_group_sg(cfg, mp, brmctx, flags, extack); + err = br_mdb_add_group_sg(cfg, mp, brmctx, flags, extack); + if (err) + br_multicast_del_group(mp); + + return err; } static int __br_mdb_add(const struct br_mdb_config *cfg, diff --git a/net/bridge/br_multicast.c b/net/bridge/br_multicast.c index 3fbad7b59769..ecc74b73a3e1 100644 --- a/net/bridge/br_multicast.c +++ b/net/bridge/br_multicast.c @@ -647,6 +647,14 @@ static void br_multicast_del_mdb_entry(struct net_bridge_mdb_entry *mp) queue_work(system_long_wq, &br->mcast_gc_work); } +void br_multicast_del_group(struct net_bridge_mdb_entry *mp) +{ + if (mp->ports || mp->host_joined) + return; + + br_multicast_del_mdb_entry(mp); +} + static void br_multicast_group_expired(struct timer_list *t) { struct net_bridge_mdb_entry *mp = timer_container_of(mp, t, timer); @@ -1554,6 +1562,7 @@ __br_multicast_add_group(struct net_bridge_mcast *brmctx, p = br_multicast_new_port_group(pmctx->port, group, *pp, 0, src, filter_mode, RTPROT_KERNEL, NULL); if (unlikely(!p)) { + br_multicast_del_group(mp); p = ERR_PTR(-ENOMEM); goto out; } diff --git a/net/bridge/br_netlink.c b/net/bridge/br_netlink.c index b2cd4e39326d..8ed86bf71a00 100644 --- a/net/bridge/br_netlink.c +++ b/net/bridge/br_netlink.c @@ -540,7 +540,7 @@ static int br_fill_ifinfo(struct sk_buff *skb, else err = br_fill_ifvlaninfo(skb, vg); - if (port && test_bit(BR_VLAN_TUNNEL_BIT, &port->flags)) + if (!err && port && test_bit(BR_VLAN_TUNNEL_BIT, &port->flags)) err = br_fill_vlan_tunnel_info(skb, vg); rcu_read_unlock(); if (err) diff --git a/net/bridge/br_private.h b/net/bridge/br_private.h index b01997ea9508..ff746f036f54 100644 --- a/net/bridge/br_private.h +++ b/net/bridge/br_private.h @@ -998,6 +998,7 @@ struct net_bridge_mdb_entry * br_mdb_ip_get(struct net_bridge *br, struct br_ip *dst); struct net_bridge_mdb_entry * br_multicast_new_group(struct net_bridge *br, struct br_ip *group); +void br_multicast_del_group(struct net_bridge_mdb_entry *mp); struct net_bridge_port_group * br_multicast_new_port_group(struct net_bridge_port *port, const struct br_ip *group, diff --git a/net/ceph/messenger_v1.c b/net/ceph/messenger_v1.c index c9e002d96319..b3ff3274344e 100644 --- a/net/ceph/messenger_v1.c +++ b/net/ceph/messenger_v1.c @@ -887,6 +887,12 @@ static int process_connect(struct ceph_connection *con) return -1; } + if (le32_to_cpu(con->v1.in_reply.connect_seq) != + con->v1.connect_seq + 1) { + con->error_msg = "protocol error, bad connect_seq"; + return -1; + } + WARN_ON(con->state != CEPH_CON_S_V1_CONNECT_MSG); con->state = CEPH_CON_S_OPEN; con->v1.auth_retry = 0; /* we authenticated; clear flag */ @@ -898,8 +904,6 @@ static int process_connect(struct ceph_connection *con) con->v1.peer_global_seq, le32_to_cpu(con->v1.in_reply.connect_seq), con->v1.connect_seq); - WARN_ON(con->v1.connect_seq != - le32_to_cpu(con->v1.in_reply.connect_seq)); if (con->v1.in_reply.flags & CEPH_MSG_CONNECT_LOSSY) ceph_con_flag_set(con, CEPH_CON_F_LOSSYTX); diff --git a/net/core/bpf_ksock.c b/net/core/bpf_ksock.c index e9943aeeadd3..6fbbd5745d64 100644 --- a/net/core/bpf_ksock.c +++ b/net/core/bpf_ksock.c @@ -274,7 +274,12 @@ BTF_ID_FLAGS(func, bpf_ksock_send, KF_SLEEPABLE) BTF_KFUNCS_END(ksock_kfunc_btf_ids) #ifdef CONFIG_BPF_LSM -BTF_ID_LIST_SINGLE(bpf_lsm_socket_sendmsg_id, func, bpf_lsm_socket_sendmsg) +BTF_ID_LIST(bpf_lsm_socket_sendmsg_id) +#ifdef CONFIG_SECURITY_NETWORK +BTF_ID(func, bpf_lsm_socket_sendmsg) +#else +BTF_ID_UNUSED +#endif #endif static int bpf_ksock_kfunc_filter(const struct bpf_prog *prog, u32 kfunc_id) diff --git a/net/core/bpf_sk_storage.c b/net/core/bpf_sk_storage.c index 1d295a8769fa..ea22ec5ef5b1 100644 --- a/net/core/bpf_sk_storage.c +++ b/net/core/bpf_sk_storage.c @@ -164,6 +164,13 @@ int bpf_sk_storage_clone(const struct sock *sk, struct sock *newsk) if (!sk_storage || hlist_empty(&sk_storage->list)) goto out; + /* + * The maps lead to newsk as soon as an element is linked, but + * sk_clone() sets sk_refcnt only later. Until then it holds whatever + * the slab object held before: no reference can be had yet. + */ + refcount_set(&newsk->sk_refcnt, 0); + hlist_for_each_entry_rcu(selem, &sk_storage->list, snode) { struct bpf_local_storage_elem *copy_selem; struct bpf_local_storage_map *smap; @@ -692,8 +699,37 @@ struct bpf_iter_seq_sk_storage_map_info { struct bpf_map *map; unsigned int bucket_id; unsigned skip_elems; + struct rcu_head *dead_sks; }; +/* + * sock_put() in two halves. The end of a socket may want process context: + * rfcomm_sock_destruct() takes a mutex. If the iterator drops the last + * reference, it keeps the socket until it has left the RCU read side critical + * section. Nobody uses sk_rcu before sk_destruct(). + */ +static void +bpf_sk_storage_map_seq_put_sk(struct bpf_iter_seq_sk_storage_map_info *info, + struct sock *sk) +{ + if (refcount_dec_and_test(&sk->sk_refcnt)) { + sk->sk_rcu.next = info->dead_sks; + info->dead_sks = &sk->sk_rcu; + } +} + +static void +bpf_sk_storage_map_seq_free_sks(struct bpf_iter_seq_sk_storage_map_info *info) +{ + struct sock *sk; + + while (info->dead_sks) { + sk = container_of(info->dead_sks, struct sock, sk_rcu); + info->dead_sks = sk->sk_rcu.next; + sk_free(sk); + } +} + static struct bpf_local_storage_elem * bpf_sk_storage_map_seq_find_next(struct bpf_iter_seq_sk_storage_map_info *info, struct bpf_local_storage_elem *prev_selem) @@ -722,6 +758,7 @@ bpf_sk_storage_map_seq_find_next(struct bpf_iter_seq_sk_storage_map_info *info, /* not found, unlock and go to the next bucket */ b = &smap->buckets[bucket_id++]; rcu_read_unlock(); + bpf_sk_storage_map_seq_free_sks(info); skip_elems = 0; break; } @@ -789,12 +826,44 @@ DEFINE_BPF_ITER_FUNC(bpf_sk_storage_map, struct bpf_iter_meta *meta, struct bpf_map *map, struct sock *sk, void *value) +/* + * Take a reference on the socket which owns @selem. RCU keeps the element, not + * its owner. As long as the element is linked under the lock of the storage, + * the owner has not got past bpf_sk_storage_free(), unless that has given up + * on the lock. Then it still waits for owner_refcnt. + */ +static struct sock * +bpf_sk_storage_selem_get_sk(struct bpf_local_storage_elem *selem) +{ + struct bpf_local_storage *sk_storage; + struct sock *sk = NULL; + unsigned long flags; + + sk_storage = rcu_dereference(selem->local_storage); + /* reset since ->next() looked: the socket goes away */ + if (!sk_storage) + return NULL; + + if (raw_res_spin_lock_irqsave(&sk_storage->lock, flags)) + return NULL; + + if (!hlist_unhashed(&selem->snode) && + refcount_inc_not_zero(&sk_storage->owner_refcnt)) { + sk = sk_storage->owner; + if (!refcount_inc_not_zero(&sk->sk_refcnt)) + sk = NULL; + bpf_local_storage_unpin_owner(sk_storage); + } + raw_res_spin_unlock_irqrestore(&sk_storage->lock, flags); + + return sk; +} + static int __bpf_sk_storage_map_seq_show(struct seq_file *seq, struct bpf_local_storage_elem *selem) { struct bpf_iter_seq_sk_storage_map_info *info = seq->private; struct bpf_iter__bpf_sk_storage_map ctx = {}; - struct bpf_local_storage *sk_storage; struct bpf_iter_meta meta; struct bpf_prog *prog; int ret = 0; @@ -805,11 +874,14 @@ static int __bpf_sk_storage_map_seq_show(struct seq_file *seq, ctx.meta = &meta; ctx.map = info->map; if (selem) { - sk_storage = rcu_dereference(selem->local_storage); - ctx.sk = sk_storage->owner; + ctx.sk = bpf_sk_storage_selem_get_sk(selem); + if (!ctx.sk) + return SEQ_SKIP; ctx.value = SDATA(selem)->data; } ret = bpf_iter_run_prog(prog, &ctx); + if (ctx.sk) + bpf_sk_storage_map_seq_put_sk(info, ctx.sk); } return ret; @@ -827,6 +899,7 @@ static void bpf_sk_storage_map_seq_stop(struct seq_file *seq, void *v) (void)__bpf_sk_storage_map_seq_show(seq, v); else rcu_read_unlock(); + bpf_sk_storage_map_seq_free_sks(seq->private); } static int bpf_iter_init_sk_storage_map(void *priv_data, diff --git a/net/core/dev.c b/net/core/dev.c index f803d8ba866f..6ebba16aff1c 100644 --- a/net/core/dev.c +++ b/net/core/dev.c @@ -2463,14 +2463,22 @@ EXPORT_SYMBOL_GPL(is_skb_forwardable); static int __dev_forward_skb2(struct net_device *dev, struct sk_buff *skb, bool check_mtu) { - int ret = ____dev_forward_skb(dev, skb, check_mtu); + enum skb_drop_reason reason; + int ret; + + ret = ____dev_forward_skb(dev, skb, check_mtu); + if (unlikely(ret)) + return ret; - if (likely(!ret)) { - skb->protocol = eth_type_trans(skb, dev); - skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN); + reason = eth_type_trans_careful(skb, dev); + if (unlikely(reason)) { + dev_core_stats_rx_dropped_inc(dev); + kfree_skb_reason(skb, reason); + return NET_RX_DROP; } + skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN); - return ret; + return 0; } int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb) @@ -3003,7 +3011,7 @@ int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask, goto out_no_old_maps; for (j = 0; j < dev_maps->nr_ids; j++) { - for (i = num_tc, tci = j * dev_maps->num_tc; i--; tci++) { + for (i = dev_maps->num_tc, tci = j * dev_maps->num_tc; i--; tci++) { map = xmap_dereference(dev_maps->attr_map[tci]); if (!map) continue; @@ -4178,7 +4186,7 @@ static enum skb_drop_reason qdisc_pkt_len_segs_init(struct sk_buff *skb) { struct skb_shared_info *shinfo = skb_shinfo(skb); unsigned int hdr_len, tlen; - u16 gso_segs; + u32 gso_segs; qdisc_skb_cb(skb)->pkt_len = skb->len; if (!shinfo->gso_size) { @@ -4231,6 +4239,15 @@ static enum skb_drop_reason qdisc_pkt_len_segs_init(struct sk_buff *skb) if (payload <= 0) return SKB_DROP_REASON_SKB_BAD_GSO; gso_segs = DIV_ROUND_UP(payload, shinfo->gso_size); + /* shinfo->gso_segs is a 16bit field. + * Also make sure untrusted gso_size/hdr_len can not inflate + * qdisc_pkt_len() beyond QDISC_PKT_LEN_MAX, or deficit + * schedulers could spin in their refill loops. + */ + if (unlikely(gso_segs > GSO_MAX_SEGS || + skb->len + (u64)(gso_segs - 1) * hdr_len > + QDISC_PKT_LEN_MAX)) + return SKB_DROP_REASON_SKB_BAD_GSO; shinfo->gso_segs = gso_segs; qdisc_skb_cb(skb)->pkt_segs = gso_segs; } @@ -6972,7 +6989,7 @@ static void skb_defer_free_flush(void) struct skb_defer_node *sdn; int node; - for_each_node(node) { + for_each_online_node(node) { sdn = this_cpu_ptr(net_hotdata.skb_defer_nodes) + node; __skb_defer_free_flush(sdn, 1); } @@ -7266,6 +7283,13 @@ static void napi_stop_kthread(struct napi_struct *napi) { unsigned long val, new; + /* Instance is disabled, we can immediately stop the kthread */ + if (test_bit(NAPI_STATE_DISABLED, &napi->state)) { + clear_bit(NAPI_STATE_THREADED, &napi->state); + clear_bit(NAPI_STATE_THREADED_BUSY_POLL, &napi->state); + goto stop; + } + /* Wait until the napi STATE_THREADED is unset. */ while (true) { val = READ_ONCE(napi->state); @@ -7296,6 +7320,7 @@ static void napi_stop_kthread(struct napi_struct *napi) msleep(20); } +stop: kthread_stop(napi->thread); napi->thread = NULL; } @@ -7691,6 +7716,7 @@ void netif_napi_add_weight_locked(struct net_device *dev, napi->list_owner = -1; set_bit(NAPI_STATE_SCHED, &napi->state); set_bit(NAPI_STATE_NPSVC, &napi->state); + set_bit(NAPI_STATE_DISABLED, &napi->state); netif_napi_dev_list_add(dev, napi); /* default settings from sysfs are applied to all NAPIs. any per-NAPI @@ -7727,7 +7753,8 @@ void napi_disable_locked(struct napi_struct *n) val = READ_ONCE(n->state); } - new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC; + new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC | + NAPIF_STATE_DISABLED; new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_THREADED_BUSY_POLL | NAPIF_STATE_PREFER_BUSY_POLL); @@ -7772,7 +7799,8 @@ void napi_enable_locked(struct napi_struct *n) do { BUG_ON(!test_bit(NAPI_STATE_SCHED, &val)); - new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC); + new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC | + NAPIF_STATE_DISABLED); if (n->dev->threaded && n->thread) new |= NAPIF_STATE_THREADED; } while (!try_cmpxchg(&n->state, &val, new)); diff --git a/net/core/dev.h b/net/core/dev.h index 04fb0e9a571e..f159a7c7beaa 100644 --- a/net/core/dev.h +++ b/net/core/dev.h @@ -95,6 +95,7 @@ extern int netdev_unregister_timeout_secs; extern int weight_p; extern int dev_weight_rx_bias; extern int dev_weight_tx_bias; +extern bool netdev_rss_key_initialized; extern struct rw_semaphore dev_addr_sem; diff --git a/net/core/devmem.c b/net/core/devmem.c index f4d60654ce7f..87f238020c91 100644 --- a/net/core/devmem.c +++ b/net/core/devmem.c @@ -8,7 +8,6 @@ */ #include -#include #include #include #include @@ -30,25 +29,6 @@ static DEFINE_XARRAY_FLAGS(net_devmem_dmabuf_bindings, XA_FLAGS_ALLOC1); static const struct memory_provider_ops dmabuf_devmem_ops; -static void net_devmem_dmabuf_free_chunk_owner(struct gen_pool *genpool, - struct gen_pool_chunk *chunk, - void *not_used) -{ - struct dmabuf_genpool_chunk_owner *owner = chunk->owner; - - kvfree(owner->area.niovs); - kfree(owner); -} - -static dma_addr_t net_devmem_get_dma_addr(const struct net_iov *niov) -{ - struct dmabuf_genpool_chunk_owner *owner; - - owner = net_devmem_iov_to_chunk_owner(niov); - return owner->base_dma_addr + - ((dma_addr_t)net_iov_idx(niov) << owner->binding->niov_shift); -} - static void net_devmem_dmabuf_binding_release(struct percpu_ref *ref) { struct net_devmem_dmabuf_binding *binding = @@ -62,24 +42,19 @@ void __net_devmem_dmabuf_binding_free(struct work_struct *wq) { struct net_devmem_dmabuf_binding *binding = container_of(wq, typeof(*binding), unbind_w); - size_t size, avail; - - gen_pool_for_each_chunk(binding->chunk_pool, - net_devmem_dmabuf_free_chunk_owner, NULL); - - size = gen_pool_size(binding->chunk_pool); - avail = gen_pool_avail(binding->chunk_pool); - - if (!WARN(size != avail, "can't destroy genpool. size=%zu, avail=%zu", - size, avail)) - gen_pool_destroy(binding->chunk_pool); + if (binding->freelist) + WARN(binding->free_count != binding->area.num_niovs, + "destroying dmabuf binding with outstanding net_iovs: total=%zu, free=%zu", + binding->area.num_niovs, binding->free_count); + kvfree(binding->area.niovs); dma_buf_unmap_attachment_unlocked(binding->attachment, binding->sgt, binding->direction); dma_buf_detach(binding->dmabuf, binding->attachment); dma_buf_put(binding->dmabuf); xa_destroy(&binding->bound_rxqs); percpu_ref_exit(&binding->ref); + kvfree(binding->freelist); kvfree(binding->tx_vec); kfree(binding); } @@ -87,21 +62,15 @@ void __net_devmem_dmabuf_binding_free(struct work_struct *wq) struct net_iov * net_devmem_alloc_dmabuf(struct net_devmem_dmabuf_binding *binding) { - struct dmabuf_genpool_chunk_owner *owner; - unsigned long dma_addr; struct net_iov *niov; - ssize_t offset; - ssize_t index; - - dma_addr = gen_pool_alloc_owner(binding->chunk_pool, - 1UL << binding->niov_shift, - (void **)&owner); - if (!dma_addr) + spin_lock_bh(&binding->freelist_lock); + if (unlikely(!binding->free_count)) { + spin_unlock_bh(&binding->freelist_lock); return NULL; + } - offset = dma_addr - owner->base_dma_addr; - index = offset >> binding->niov_shift; - niov = &owner->area.niovs[index]; + niov = binding->freelist[--binding->free_count]; + spin_unlock_bh(&binding->freelist_lock); niov->desc.pp_magic = 0; niov->desc.pp = NULL; @@ -113,14 +82,15 @@ net_devmem_alloc_dmabuf(struct net_devmem_dmabuf_binding *binding) void net_devmem_free_dmabuf(struct net_iov *niov) { struct net_devmem_dmabuf_binding *binding = net_devmem_iov_binding(niov); - unsigned long dma_addr = net_devmem_get_dma_addr(niov); - size_t niov_size = 1UL << binding->niov_shift; - if (WARN_ON(!gen_pool_has_addr(binding->chunk_pool, dma_addr, - niov_size))) + spin_lock_bh(&binding->freelist_lock); + if (WARN_ON_ONCE(binding->free_count >= binding->area.num_niovs)) { + spin_unlock_bh(&binding->freelist_lock); return; + } - gen_pool_free(binding->chunk_pool, dma_addr, niov_size); + binding->freelist[binding->free_count++] = niov; + spin_unlock_bh(&binding->freelist_lock); } void net_devmem_unbind_dmabuf(struct net_devmem_dmabuf_binding *binding) @@ -191,6 +161,7 @@ net_devmem_bind_dmabuf(struct net_device *dev, void *vdev, enum dma_data_direction direction, unsigned int dmabuf_fd, unsigned int niov_shift, struct netdev_nl_sock *priv, + const struct sock *nl_sk, struct netlink_ext_ack *extack) { struct net_devmem_dmabuf_binding *binding; @@ -198,8 +169,9 @@ net_devmem_bind_dmabuf(struct net_device *dev, void *vdev, static u32 id_alloc_next; struct scatterlist *sg; struct dma_buf *dmabuf; - unsigned int sg_idx, i; - unsigned long virtual; + unsigned int sg_idx; + size_t niov_idx; + size_t i; int err; if (!dma_dev) { @@ -220,6 +192,8 @@ net_devmem_bind_dmabuf(struct net_device *dev, void *vdev, binding->dev = dev; binding->vdev = vdev; + write_pnet(&binding->net, sock_net(nl_sk)); + binding->uid = sk_uid(nl_sk); binding->niov_shift = niov_shift; xa_init_flags(&binding->bound_rxqs, XA_FLAGS_ALLOC); @@ -249,33 +223,46 @@ net_devmem_bind_dmabuf(struct net_device *dev, void *vdev, goto err_detach; } + if (!IS_ALIGNED(dmabuf->size, niov_size)) { + err = -EINVAL; + NL_SET_ERR_MSG_FMT(extack, + "dmabuf size %zu not aligned to niov size %zu", + dmabuf->size, niov_size); + goto err_unmap; + } + + binding->area.base_virtual = 0; + binding->area.num_niovs = dmabuf->size >> niov_shift; if (direction == DMA_TO_DEVICE) { - if (!IS_ALIGNED(dmabuf->size, PAGE_SIZE)) { - err = -EINVAL; - NL_SET_ERR_MSG(extack, "TX dma-buf size must be a multiple of PAGE_SIZE"); - goto err_unmap; - } binding->tx_vec = kvmalloc_objs(struct net_iov *, - dmabuf->size / PAGE_SIZE); + binding->area.num_niovs); if (!binding->tx_vec) { err = -ENOMEM; goto err_unmap; } + } else { + spin_lock_init(&binding->freelist_lock); + binding->freelist = kvmalloc_array(binding->area.num_niovs, + sizeof(binding->freelist[0]), + GFP_KERNEL); + if (!binding->freelist) { + err = -ENOMEM; + goto err_unmap; + } } - - binding->chunk_pool = gen_pool_create(niov_shift, - dev_to_node(&dev->dev)); - if (!binding->chunk_pool) { + binding->area.niovs = kvmalloc_objs(*binding->area.niovs, + binding->area.num_niovs); + if (!binding->area.niovs) { err = -ENOMEM; - goto err_tx_vec; + goto err_free_freelist; } - virtual = 0; + niov_idx = 0; for_each_sgtable_dma_sg(binding->sgt, sg, sg_idx) { dma_addr_t dma_addr = sg_dma_address(sg); - struct dmabuf_genpool_chunk_owner *owner; size_t len = sg_dma_len(sg); struct net_iov *niov; + size_t nr_niovs; if (!IS_ALIGNED(dma_addr, niov_size) || !IS_ALIGNED(len, niov_size)) { @@ -283,64 +270,37 @@ net_devmem_bind_dmabuf(struct net_device *dev, void *vdev, NL_SET_ERR_MSG_FMT(extack, "dmabuf sg entry (addr=%pad, len=%zu) not aligned to niov size %zu", &dma_addr, len, niov_size); - goto err_free_chunks; - } - - owner = kzalloc_node(sizeof(*owner), GFP_KERNEL, - dev_to_node(&dev->dev)); - if (!owner) { - err = -ENOMEM; - goto err_free_chunks; + goto err_free_niovs; } - owner->area.base_virtual = virtual; - owner->base_dma_addr = dma_addr; - owner->area.num_niovs = len >> niov_shift; - owner->binding = binding; - - err = gen_pool_add_owner(binding->chunk_pool, dma_addr, - dma_addr, len, dev_to_node(&dev->dev), - owner); - if (err) { - kfree(owner); - err = -EINVAL; - goto err_free_chunks; - } - - owner->area.niovs = kvmalloc_objs(*owner->area.niovs, - owner->area.num_niovs); - if (!owner->area.niovs) { - err = -ENOMEM; - goto err_free_chunks; - } - - for (i = 0; i < owner->area.num_niovs; i++) { - niov = &owner->area.niovs[i]; - net_iov_init(niov, &owner->area, NET_IOV_DMABUF); + nr_niovs = len >> niov_shift; + for (i = 0; i < nr_niovs; i++, niov_idx++) { + niov = &binding->area.niovs[niov_idx]; + net_iov_init(niov, &binding->area, NET_IOV_DMABUF); page_pool_set_dma_addr_netmem(net_iov_to_netmem(niov), - net_devmem_get_dma_addr(niov)); + dma_addr); if (direction == DMA_TO_DEVICE) - binding->tx_vec[owner->area.base_virtual / PAGE_SIZE + i] = niov; + binding->tx_vec[niov_idx] = niov; + else + binding->freelist[binding->free_count++] = niov; + dma_addr += niov_size; } - - virtual += len; } err = xa_alloc_cyclic(&net_devmem_dmabuf_bindings, &binding->id, binding, xa_limit_32b, &id_alloc_next, GFP_KERNEL); if (err < 0) - goto err_free_chunks; + goto err_free_niovs; list_add(&binding->list, &priv->bindings); return binding; -err_free_chunks: - gen_pool_for_each_chunk(binding->chunk_pool, - net_devmem_dmabuf_free_chunk_owner, NULL); - gen_pool_destroy(binding->chunk_pool); -err_tx_vec: +err_free_niovs: + kvfree(binding->area.niovs); +err_free_freelist: + kvfree(binding->freelist); kvfree(binding->tx_vec); err_unmap: dma_buf_unmap_attachment_unlocked(binding->attachment, binding->sgt, @@ -390,7 +350,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 4a293a7d1149..71c7bd9d6e39 100644 --- a/net/core/devmem.h +++ b/net/core/devmem.h @@ -10,12 +10,14 @@ #ifndef _NET_DEVMEM_H #define _NET_DEVMEM_H +#include #include #include struct netlink_ext_ack; struct net_devmem_dmabuf_binding { + struct net_iov_area area; struct dma_buf *dmabuf; struct dma_buf_attachment *attachment; struct sg_table *sgt; @@ -26,7 +28,8 @@ struct net_devmem_dmabuf_binding { * dereferenced. */ void *vdev; - struct gen_pool *chunk_pool; + possible_net_t net; + kuid_t uid; /* Protect dev */ struct mutex lock; @@ -57,6 +60,10 @@ struct net_devmem_dmabuf_binding { /* rxq's this binding is active on. */ struct xarray bound_rxqs; + spinlock_t freelist_lock ____cacheline_aligned_in_smp; + size_t free_count; + struct net_iov **freelist; + /* ID of this binding. Globally unique to all bindings currently * active. */ @@ -77,19 +84,6 @@ struct net_devmem_dmabuf_binding { }; #if defined(CONFIG_NET_DEVMEM) -/* Owner of the dma-buf chunks inserted into the gen pool. Each scatterlist - * entry from the dmabuf is inserted into the genpool as a chunk, and needs - * this owner struct to keep track of some metadata necessary to create - * allocations from this chunk. - */ -struct dmabuf_genpool_chunk_owner { - struct net_iov_area area; - struct net_devmem_dmabuf_binding *binding; - - /* dma_addr of the start of the chunk. */ - dma_addr_t base_dma_addr; -}; - void __net_devmem_dmabuf_binding_free(struct work_struct *wq); struct net_devmem_dmabuf_binding * net_devmem_bind_dmabuf(struct net_device *dev, void *vdev, @@ -97,6 +91,7 @@ net_devmem_bind_dmabuf(struct net_device *dev, void *vdev, enum dma_data_direction direction, unsigned int dmabuf_fd, unsigned int niov_shift, 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); @@ -104,18 +99,11 @@ int net_devmem_bind_dmabuf_to_queue(struct net_device *dev, u32 rxq_idx, struct net_devmem_dmabuf_binding *binding, struct netlink_ext_ack *extack); -static inline struct dmabuf_genpool_chunk_owner * -net_devmem_iov_to_chunk_owner(const struct net_iov *niov) -{ - struct net_iov_area *owner = net_iov_owner(niov); - - return container_of(owner, struct dmabuf_genpool_chunk_owner, area); -} - static inline struct net_devmem_dmabuf_binding * net_devmem_iov_binding(const struct net_iov *niov) { - return net_devmem_iov_to_chunk_owner(niov)->binding; + return container_of(net_iov_owner(niov), + struct net_devmem_dmabuf_binding, area); } static inline u32 net_devmem_iov_binding_id(const struct net_iov *niov) @@ -125,11 +113,11 @@ static inline u32 net_devmem_iov_binding_id(const struct net_iov *niov) static inline unsigned long net_iov_virtual_addr(const struct net_iov *niov) { - struct dmabuf_genpool_chunk_owner *co = - net_devmem_iov_to_chunk_owner(niov); + struct net_devmem_dmabuf_binding *binding = + net_devmem_iov_binding(niov); return net_iov_owner(niov)->base_virtual + - ((unsigned long)net_iov_idx(niov) << co->binding->niov_shift); + ((unsigned long)net_iov_idx(niov) << binding->niov_shift); } static inline bool @@ -181,6 +169,7 @@ net_devmem_bind_dmabuf(struct net_device *dev, void *vdev, unsigned int dmabuf_fd, unsigned int niov_shift, 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 d3e5a2843d5e..0ad1507759de 100644 --- a/net/core/filter.c +++ b/net/core/filter.c @@ -1715,6 +1715,24 @@ static inline void bpf_pull_mac_rcsum(struct sk_buff *skb) skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len); } +/* + * The source of a write through a dynptr may be a slice of the same skb. + * Making the skb writable can move its head: follow the move. + */ +static int bpf_try_make_writable_from(struct sk_buff *skb, u32 write_len, + const void **from) +{ + const void *head = skb->head; + bool in_head = *from >= head && + *from < (const void *)skb_end_pointer(skb); + int err; + + err = bpf_try_make_writable(skb, write_len); + if (!err && in_head) + *from = skb->head + (*from - head); + return err; +} + BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset, const void *, from, u32, len, u64, flags) { @@ -1724,14 +1742,15 @@ BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset, return -EINVAL; if (unlikely(offset > INT_MAX)) return -EFAULT; - if (unlikely(bpf_try_make_writable(skb, offset + len))) + if (unlikely(bpf_try_make_writable_from(skb, offset + len, &from))) return -EFAULT; ptr = skb->data + offset; if (flags & BPF_F_RECOMPUTE_CSUM) __skb_postpull_rcsum(skb, ptr, len, offset); - memcpy(ptr, from, len); + /* through a dynptr the source may be an overlapping slice of the skb */ + memmove(ptr, from, len); if (flags & BPF_F_RECOMPUTE_CSUM) __skb_postpush_rcsum(skb, ptr, len, offset); @@ -1770,7 +1789,7 @@ BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset, if (unlikely(!ptr)) goto err_clear; if (ptr != to) - memcpy(to, ptr, len); + memmove(to, ptr, len); return 0; err_clear: @@ -1852,7 +1871,7 @@ BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb, ptr = start + offset; if (likely(ptr + len <= end)) { - memcpy(to, ptr, len); + memmove(to, ptr, len); return 0; } @@ -3619,6 +3638,14 @@ static int bpf_skb_net_grow(struct sk_buff *skb, u32 off, u32 len_diff, return -ENOTSUPP; } + /* + * The MSS is lowered by len_diff. Leave the least that the stack lets a + * TCP GSO packet have, or gso_segs can overflow. + */ + if (skb_is_gso(skb) && !(flags & BPF_F_ADJ_ROOM_FIXED_GSO) && + skb_shinfo(skb)->gso_size < len_diff + TCP_MIN_GSO_SIZE) + return -ENOTSUPP; + ret = skb_cow_head(skb, meta_len + len_diff); if (unlikely(ret < 0)) return ret; @@ -4278,7 +4305,7 @@ BPF_CALL_4(bpf_xdp_load_bytes, struct xdp_buff *, xdp, u32, offset, if (!ptr) bpf_xdp_copy_buf(xdp, offset, buf, len, false); else - memcpy(buf, ptr, len); + memmove(buf, ptr, len); return 0; } @@ -4310,7 +4337,8 @@ BPF_CALL_4(bpf_xdp_store_bytes, struct xdp_buff *, xdp, u32, offset, if (!ptr) bpf_xdp_copy_buf(xdp, offset, buf, len, true); else - memcpy(ptr, buf, len); + /* through a dynptr the source may be an overlapping slice */ + memmove(ptr, buf, len); return 0; } @@ -7024,15 +7052,15 @@ static void bpf_update_srh_state(struct sk_buff *skb) { struct seg6_bpf_srh_state *srh_state = this_cpu_ptr(&seg6_bpf_srh_states); - int srhoff = 0; - if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) { - srh_state->srh = NULL; - } else { - srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff); + /* Behind a decapsulation this is a header that nobody has looked at */ + srh_state->srh = seg6_get_srh(skb, 0); + if (srh_state->srh) { srh_state->hdrlen = srh_state->srh->hdrlen << 3; srh_state->valid = true; } + /* it may have been pulled into the head */ + bpf_compute_data_pointers(skb); } BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb, @@ -7065,9 +7093,14 @@ BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb, if (ipv6_find_hdr(skb, &hdroff, IPPROTO_IPV6, NULL, NULL) < 0) return -EBADMSG; - if (!pskb_pull(skb, hdroff)) + /* As long as nothing has been changed, the program goes on */ + if (!pskb_may_pull(skb, hdroff + sizeof(struct ipv6hdr))) { + /* but the head may have moved */ + bpf_update_srh_state(skb); return -EBADMSG; + } + __skb_pull(skb, hdroff); skb_postpull_rcsum(skb, skb_network_header(skb), hdroff); skb_reset_network_header(skb); skb_reset_transport_header(skb); @@ -7081,8 +7114,8 @@ BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb, return -EBADMSG; err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6_INLINE, param, param_len); - if (!err) - bpf_update_srh_state(skb); + /* The header can be in place although err says otherwise */ + bpf_update_srh_state(skb); return err; case SEG6_LOCAL_ACTION_END_B6_ENCAP: @@ -7090,8 +7123,8 @@ BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb, return -EBADMSG; err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6, param, param_len); - if (!err) - bpf_update_srh_state(skb); + /* The header can be in place although err says otherwise */ + bpf_update_srh_state(skb); return err; default: @@ -7607,8 +7640,8 @@ bool bpf_tcp_sock_is_valid_access(int off, int size, enum bpf_access_type type, return false; switch (off) { - case offsetof(struct bpf_tcp_sock, bytes_received): - case offsetof(struct bpf_tcp_sock, bytes_acked): + case bpf_ctx_range(struct bpf_tcp_sock, bytes_received): + case bpf_ctx_range(struct bpf_tcp_sock, bytes_acked): return size == sizeof(__u64); default: return size == sizeof(__u32); @@ -12409,7 +12442,7 @@ int __bpf_skb_meta_store_bytes(struct sk_buff *skb, u32 offset, { if (unlikely(flags)) return -EINVAL; - if (unlikely(bpf_try_make_writable(skb, 0))) + if (unlikely(bpf_try_make_writable_from(skb, 0, &from))) return -EFAULT; memmove(bpf_skb_meta_pointer(skb, offset), from, len); diff --git a/net/core/gro.c b/net/core/gro.c index ff828a3dce3c..1b033855a20d 100644 --- a/net/core/gro.c +++ b/net/core/gro.c @@ -513,9 +513,10 @@ static enum gro_result dev_gro_receive(struct gro_node *gro, NAPI_GRO_CB(skb)->count = 1; if (unlikely(skb_is_gso(skb))) { NAPI_GRO_CB(skb)->count = skb_shinfo(skb)->gso_segs; - /* Only support TCP and non DODGY users. */ + /* Only support TCP and non DODGY users, with a sane gso_segs. */ if (!skb_is_gso_tcp(skb) || - (skb_shinfo(skb)->gso_type & SKB_GSO_DODGY)) + (skb_shinfo(skb)->gso_type & SKB_GSO_DODGY) || + !NAPI_GRO_CB(skb)->count) NAPI_GRO_CB(skb)->flush = 1; } diff --git a/net/core/net-sysfs.c b/net/core/net-sysfs.c index 352173df7578..2b3dab9611c0 100644 --- a/net/core/net-sysfs.c +++ b/net/core/net-sysfs.c @@ -1088,6 +1088,13 @@ 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; + /* Do not accept too large tables. */ if (mask > (INT_MAX / sizeof(*table) - 1)) return -EINVAL; diff --git a/net/core/netdev-genl.c b/net/core/netdev-genl.c index 33b9f4eb9565..2f772fc124ab 100644 --- a/net/core/netdev-genl.c +++ b/net/core/netdev-genl.c @@ -1094,7 +1094,7 @@ int netdev_nl_bind_rx_doit(struct sk_buff *skb, struct genl_info *info) binding = net_devmem_bind_dmabuf(netdev, NULL, dma_dev, DMA_FROM_DEVICE, dmabuf_fd, niov_shift, priv, - info->extack); + NETLINK_CB(skb).sk, info->extack); if (IS_ERR(binding)) { err = PTR_ERR(binding); goto err_rxq_bitmap; @@ -1243,7 +1243,8 @@ int netdev_nl_bind_tx_doit(struct sk_buff *skb, struct genl_info *info) binding = net_devmem_bind_dmabuf(bind_dev, bind_dev != netdev ? netdev : NULL, dma_dev, DMA_TO_DEVICE, dmabuf_fd, - PAGE_SHIFT, priv, info->extack); + PAGE_SHIFT, priv, NETLINK_CB(skb).sk, + info->extack); if (IS_ERR(binding)) { err = PTR_ERR(binding); goto err_unlock_bind_dev; @@ -1487,6 +1488,12 @@ static int netdev_genl_netdevice_event(struct notifier_block *nb, netdev_unlock_full_to_ops(netdev); break; case NETDEV_UNREGISTER: + /* netdev_wait_allrefs_any() rebroadcasts NETDEV_UNREGISTER + * while waiting for the last references to be dropped; the + * netns may already be torn down by then. Notify only once. + */ + if (READ_ONCE(netdev->reg_state) == NETREG_UNREGISTERED) + break; netdev_lock(netdev); netdev_genl_dev_notify(netdev, NETDEV_CMD_DEV_DEL_NTF); netdev_unlock(netdev); diff --git a/net/core/selftests.c b/net/core/selftests.c index 36b949ae520b..80029a67b2d2 100644 --- a/net/core/selftests.c +++ b/net/core/selftests.c @@ -170,7 +170,7 @@ static int net_test_loopback_validate(struct sk_buff *skb, struct tcphdr *thdr; struct iphdr *ihdr; - skb = skb_unshare(skb, GFP_ATOMIC); + skb = skb_share_check(skb, GFP_ATOMIC); if (!skb) goto out; diff --git a/net/core/skbuff.c b/net/core/skbuff.c index ea4c38dee19f..512eddc0fc3d 100644 --- a/net/core/skbuff.c +++ b/net/core/skbuff.c @@ -1593,7 +1593,6 @@ static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old) #ifdef CONFIG_NET_RX_BUSY_POLL CHECK_SKB_FIELD(napi_id); #endif - CHECK_SKB_FIELD(alloc_cpu); #ifdef CONFIG_XPS CHECK_SKB_FIELD(sender_cpu); #endif @@ -1625,6 +1624,7 @@ static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb) C(pfmemalloc); C(pp_recycle); n->destructor = NULL; + C(alloc_cpu); C(tail); C(end); C(head); @@ -4747,10 +4747,13 @@ struct sk_buff *skb_segment_list(struct sk_buff *skb, else tail->next = nskb; - if (unlikely(err)) { - nskb->next = list_skb; + /* nskb may be a clone with a NULL ->next: keep the remaining + * members linked so that err_linearize frees them. + */ + nskb->next = list_skb; + + if (unlikely(err)) goto err_linearize; - } tail = nskb; diff --git a/net/core/sock.c b/net/core/sock.c index 1108543f9fec..a74be1cc9302 100644 --- a/net/core/sock.c +++ b/net/core/sock.c @@ -769,6 +769,7 @@ bool sk_mc_loop(const struct sock *sk) { if (dev_recursion_level()) return false; + sk = sk_const_to_full_sk(sk); if (!sk) return true; /* IPV6_ADDRFORM can change sk->sk_family under us. */ @@ -2496,7 +2497,7 @@ struct sock *sk_clone(const struct sock *sk, const gfp_t priority, RCU_INIT_POINTER(newsk->sk_bpf_storage, NULL); #endif #if IS_ENABLED(CONFIG_INET_PSP) - RCU_INIT_POINTER(newsk->psp_assoc, NULL); + DEBUG_NET_WARN_ON_ONCE(rcu_access_pointer(sk->psp_assoc)); #endif /* SANITY */ diff --git a/net/core/sysctl_net_core.c b/net/core/sysctl_net_core.c index eb35da3556f4..aa3dcc289e29 100644 --- a/net/core/sysctl_net_core.c +++ b/net/core/sysctl_net_core.c @@ -336,10 +336,15 @@ static int proc_do_rss_key(const struct ctl_table *table, int write, { char buf[NETDEV_RSS_KEY_LEN * 3]; struct ctl_table fake_table; + bool initialized; char *pos = buf; + initialized = READ_ONCE(netdev_rss_key_initialized); + /* Pair with smp_wmb() in netdev_rss_key_fill(). */ + smp_rmb(); + for (int i = 0; i < NETDEV_RSS_KEY_LEN; i++) { - pos = hex_byte_pack(pos, netdev_rss_key[i]); + pos = hex_byte_pack(pos, initialized ? netdev_rss_key[i] : 0); *pos++ = ':'; } *(--pos) = 0; diff --git a/net/dcb/dcbnl.c b/net/dcb/dcbnl.c index 35164bfa563d..593c9d89d36a 100644 --- a/net/dcb/dcbnl.c +++ b/net/dcb/dcbnl.c @@ -281,6 +281,7 @@ static int dcbnl_getpfccfg(struct net_device *netdev, struct nlmsghdr *nlh, if (!getall && !data[i]) continue; + value = 0; netdev->dcbnl_ops->getpfccfg(netdev, i - DCB_PFC_UP_ATTR_0, &value); ret = nla_put_u8(skb, i, value); @@ -1395,6 +1396,7 @@ static int dcbnl_cee_fill(struct sk_buff *skb, struct net_device *netdev) goto nla_put_failure; for (i = DCB_PFC_UP_ATTR_0; i <= DCB_PFC_UP_ATTR_7; i++) { + value = 0; ops->getpfccfg(netdev, i - DCB_PFC_UP_ATTR_0, &value); if (nla_put_u8(skb, i, value)) goto nla_put_failure; diff --git a/net/devlink/region.c b/net/devlink/region.c index 537779bbff07..c22016f23a4a 100644 --- a/net/devlink/region.c +++ b/net/devlink/region.c @@ -719,6 +719,11 @@ int devlink_nl_region_new_doit(struct sk_buff *skb, struct genl_info *info) if (!snapshot_id_attr) { struct sk_buff *msg; + /* Drop the allocation reference, the snapshot + * now holds its own. + */ + __devlink_snapshot_id_decrement(devlink, snapshot_id); + snapshot = devlink_region_snapshot_get_by_id(region, snapshot_id); if (WARN_ON(!snapshot)) { diff --git a/net/ethtool/ioctl.c b/net/ethtool/ioctl.c index 4b0bc503f930..b2820f02ca27 100644 --- a/net/ethtool/ioctl.c +++ b/net/ethtool/ioctl.c @@ -34,6 +34,7 @@ #include #include +#include "../core/dev.h" #include "common.h" /* State held across locks and calls for commands which have devlink fallback */ @@ -1302,11 +1303,17 @@ static int ethtool_copy_validate_indir(u32 *indir, void __user *useraddr, } u8 netdev_rss_key[NETDEV_RSS_KEY_LEN] __read_mostly; +bool netdev_rss_key_initialized __read_mostly; void netdev_rss_key_fill(void *buffer, size_t len) { BUG_ON(len > sizeof(netdev_rss_key)); net_get_random_once(netdev_rss_key, sizeof(netdev_rss_key)); + if (unlikely(!READ_ONCE(netdev_rss_key_initialized))) { + /* Pair with smp_rmb() in proc_do_rss_key(). */ + smp_wmb(); + WRITE_ONCE(netdev_rss_key_initialized, true); + } memcpy(buffer, netdev_rss_key, len); } EXPORT_SYMBOL(netdev_rss_key_fill); diff --git a/net/ipv4/cipso_ipv4.c b/net/ipv4/cipso_ipv4.c index e65a3f29d2ca..ee0c72fbc877 100644 --- a/net/ipv4/cipso_ipv4.c +++ b/net/ipv4/cipso_ipv4.c @@ -2004,11 +2004,16 @@ static int cipso_v4_delopt(struct ip_options_rcu __rcu **opt_ptr) if (!opt || opt->opt.cipso == 0) return 0; if (opt->opt.srr || opt->opt.rr || opt->opt.ts || opt->opt.router_alert) { + struct ip_options_rcu *old_opt = opt; u8 cipso_len; u8 cipso_off; unsigned char *cipso_ptr; int optlen_new; + /* ip_options_rcu must not be modified in place, use a copy */ + opt = kmemdup(opt, sizeof(*opt) + opt->opt.optlen, GFP_ATOMIC); + if (!opt) + return -ENOMEM; cipso_off = opt->opt.cipso - sizeof(struct iphdr); cipso_ptr = &opt->opt.__data[cipso_off]; cipso_len = cipso_ptr[1]; @@ -2036,6 +2041,8 @@ static int cipso_v4_delopt(struct ip_options_rcu __rcu **opt_ptr) memset(&opt->opt.__data[optlen_new], IPOPT_END, opt->opt.optlen - optlen_new); + rcu_assign_pointer(*opt_ptr, opt); + kfree_rcu(old_opt, rcu); } else { /* only the cipso option was present on the socket so we can * remove the entire option struct */ @@ -2055,7 +2062,7 @@ static int cipso_v4_delopt(struct ip_options_rcu __rcu **opt_ptr) * Removes the CIPSO option from a socket, if present. * */ -void cipso_v4_sock_delattr(struct sock *sk) +int cipso_v4_sock_delattr(struct sock *sk) { struct inet_sock *sk_inet; int hdr_delta; @@ -2068,6 +2075,7 @@ void cipso_v4_sock_delattr(struct sock *sk) sk_conn->icsk_ext_hdr_len -= hdr_delta; sk_conn->icsk_sync_mss(sk, sk_conn->icsk_pmtu_cookie); } + return (hdr_delta < 0) ? hdr_delta : 0; } /** @@ -2078,9 +2086,11 @@ void cipso_v4_sock_delattr(struct sock *sk) * Removes the CIPSO option from a request socket, if present. * */ -void cipso_v4_req_delattr(struct request_sock *req) +int cipso_v4_req_delattr(struct request_sock *req) { - cipso_v4_delopt(&inet_rsk(req)->ireq_opt); + int hdr_delta = cipso_v4_delopt(&inet_rsk(req)->ireq_opt); + + return (hdr_delta < 0) ? hdr_delta : 0; } /** diff --git a/net/ipv4/devinet.c b/net/ipv4/devinet.c index 5b6b11c943e4..f9a361621f74 100644 --- a/net/ipv4/devinet.c +++ b/net/ipv4/devinet.c @@ -2379,8 +2379,8 @@ static int inet_netconf_get_devconf(struct sk_buff *in_skb, struct net *net = sock_net(in_skb->sk); struct nlattr *tb[NETCONFA_MAX + 1]; const struct ipv4_devconf *devconf; - struct in_device *in_dev = NULL; - struct net_device *dev = NULL; + struct in_device *in_dev; + struct net_device *dev; struct sk_buff *skb; int ifindex; int err; @@ -2392,7 +2392,13 @@ static int inet_netconf_get_devconf(struct sk_buff *in_skb, if (!tb[NETCONFA_IFINDEX]) return -EINVAL; + skb = nlmsg_new(inet_netconf_msgsize_devconf(NETCONFA_ALL), GFP_KERNEL); + if (!skb) + return -ENOBUFS; + ifindex = nla_get_s32(tb[NETCONFA_IFINDEX]); + + rcu_read_lock(); switch (ifindex) { case NETCONFA_IFINDEX_ALL: devconf = net->ipv4.devconf_all; @@ -2402,36 +2408,29 @@ static int inet_netconf_get_devconf(struct sk_buff *in_skb, break; default: err = -ENODEV; - dev = dev_get_by_index(net, ifindex); - if (dev) - in_dev = in_dev_get(dev); + dev = dev_get_by_index_rcu(net, ifindex); + if (!dev) + goto out_unlock; + in_dev = __in_dev_get_rcu(dev); if (!in_dev) - goto errout; + goto out_unlock; devconf = &in_dev->cnf; break; } - err = -ENOBUFS; - skb = nlmsg_new(inet_netconf_msgsize_devconf(NETCONFA_ALL), GFP_KERNEL); - if (!skb) - goto errout; - err = inet_netconf_fill_devconf(skb, ifindex, devconf, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWNETCONF, 0, NETCONFA_ALL); +out_unlock: + rcu_read_unlock(); if (err < 0) { /* -EMSGSIZE implies BUG in inet_netconf_msgsize_devconf() */ WARN_ON(err == -EMSGSIZE); kfree_skb(skb); - goto errout; + return err; } - err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); -errout: - if (in_dev) - in_dev_put(in_dev); - dev_put(dev); - return err; + return rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); } static int inet_netconf_dump_devconf(struct sk_buff *skb, diff --git a/net/ipv4/gre_offload.c b/net/ipv4/gre_offload.c index 5028c72d494a..c8129782d39d 100644 --- a/net/ipv4/gre_offload.c +++ b/net/ipv4/gre_offload.c @@ -242,7 +242,7 @@ static int gre_gro_complete(struct sk_buff *skb, int nhoff) __be16 type; skb->encapsulation = 1; - skb_shinfo(skb)->gso_type = SKB_GSO_GRE; + skb_shinfo(skb)->gso_type |= SKB_GSO_GRE; type = greh->protocol; if (greh->flags & GRE_KEY) diff --git a/net/ipv4/inet_connection_sock.c b/net/ipv4/inet_connection_sock.c index a1fe2531cb59..71b0c344579f 100644 --- a/net/ipv4/inet_connection_sock.c +++ b/net/ipv4/inet_connection_sock.c @@ -446,7 +446,8 @@ void inet_csk_update_fastreuse(const struct sock *sk, { bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN; - if (hlist_empty(&tb->bhash2)) { + if (hlist_is_singular_node(&tb2->bhash_node, &tb->bhash2) && + hlist_empty(&tb2->owners)) { tb->fastreuse = reuse; if (sk->sk_reuseport) { tb->fastreuseport = FASTREUSEPORT_ANY; diff --git a/net/ipv4/inet_fragment.c b/net/ipv4/inet_fragment.c index 0b8d22ffafca..f330d0a39823 100644 --- a/net/ipv4/inet_fragment.c +++ b/net/ipv4/inet_fragment.c @@ -17,6 +17,7 @@ #include #include #include +#include #include #include @@ -519,6 +520,43 @@ int inet_frag_queue_insert(struct inet_frag_queue *q, struct sk_buff *skb, } EXPORT_SYMBOL(inet_frag_queue_insert); +/* When a socket owned fragment completes a queue, the truesize of all + * other fragments is charged to its sk_wmem_alloc, although they were + * orphaned when queued and possibly sent by someone else. + * Bound this like ip_append_data() bounds the memory a socket can + * allocate (2 * sk_sndbuf), plus slack for fragments inflated by a + * refragmentation using a small MTU. Otherwise, several reassembled skbs + * alive at the same time can saturate sk_wmem_alloc, and leak the socket. + * + * Several queues can complete at the same time for the same socket, + * and some sockets (tun) use sk_sndbuf = INT_MAX. The charge is reserved + * with a cmpxchg() loop, a refcount_t has no helper for this. + */ +#define INET_FRAG_WMEM_SLACK SZ_4M + +static bool inet_frag_wmem_reserve(struct sock *sk, unsigned int charge) +{ + u64 limit = 2ULL * READ_ONCE(sk->sk_sndbuf) + INET_FRAG_WMEM_SLACK; + int old = refcount_read(&sk->sk_wmem_alloc); + + limit = min_t(u64, limit, INET_FRAG_MAX_TRUESIZE); + do { + if (old <= 0 || (u64)old + charge > limit) + return false; + } while (!atomic_try_cmpxchg(&sk->sk_wmem_alloc.refs, &old, + old + charge)); + + return true; +} + +static void inet_frag_wmem_adjust(struct sock *sk, int delta) +{ + if (delta >= 0) + refcount_add(delta, &sk->sk_wmem_alloc); + else + WARN_ON_ONCE(refcount_sub_and_test(-delta, &sk->sk_wmem_alloc)); +} + void *inet_frag_reasm_prepare(struct inet_frag_queue *q, struct sk_buff *skb, struct sk_buff *parent) { @@ -530,6 +568,11 @@ void *inet_frag_reasm_prepare(struct inet_frag_queue *q, struct sk_buff *skb, int delta; if (sk && is_skb_wmem(skb)) { + /* skb->truesize is already charged to sk, and is part of + * q->truesize. inet_frag_reasm_finish() settles the charge. + */ + if (!inet_frag_wmem_reserve(sk, q->truesize - skb->truesize)) + return NULL; /* TX: skb->sk might have been passed as argument to * dst->output and must remain valid until tx completes. * @@ -605,17 +648,18 @@ void *inet_frag_reasm_prepare(struct inet_frag_queue *q, struct sk_buff *skb, out_restore_sk: if (orig_truesize) { - int ts_delta = head->truesize - orig_truesize; - /* if this reassembled skb is fragmented later, * fraglist skbs will get skb->sk assigned from head->sk, * and each frag skb will be released via sock_wfree. - * - * Update sk_wmem_alloc. */ head->sk = sk; head->destructor = destructor; - refcount_add(ts_delta, &sk->sk_wmem_alloc); + /* On failure, head stays in the queue and will be freed + * with the queue: only charge its truesize. + */ + if (!nextp) + inet_frag_wmem_adjust(sk, (int)head->truesize - + (int)q->truesize); } return nextp; @@ -626,7 +670,6 @@ void inet_frag_reasm_finish(struct inet_frag_queue *q, struct sk_buff *head, void *reasm_data, bool try_coalesce) { struct sock *sk = is_skb_wmem(head) ? head->sk : NULL; - const unsigned int head_truesize = head->truesize; struct sk_buff **nextp = reasm_data; struct rb_node *rbn; struct sk_buff *fp; @@ -691,8 +734,12 @@ void inet_frag_reasm_finish(struct inet_frag_queue *q, struct sk_buff *head, head->tstamp = q->stamp; head->tstamp_type = q->tstamp_type; + /* After inet_frag_reasm_prepare(), q->truesize is charged to sk. + * sum_truesize also includes what it added (skb_unclone() and + * frag_list clone). + */ if (sk) - refcount_add(sum_truesize - head_truesize, &sk->sk_wmem_alloc); + inet_frag_wmem_adjust(sk, sum_truesize - (int)q->truesize); } EXPORT_SYMBOL(inet_frag_reasm_finish); diff --git a/net/ipv4/ip_fragment.c b/net/ipv4/ip_fragment.c index 36105dd19282..ef7fd61284a3 100644 --- a/net/ipv4/ip_fragment.c +++ b/net/ipv4/ip_fragment.c @@ -413,16 +413,19 @@ static int ip_frag_reasm(struct ipq *qp, struct sk_buff *skb, goto out_fail; } + /* Check the size on the first fragment, which will become the head: + * inet_frag_reasm_finish() must follow inet_frag_reasm_prepare(). + */ + len = ip_hdrlen(skb_rb_first(&qp->q.rb_fragments)) + qp->q.len; + err = -E2BIG; + if (len > 65535) + goto out_oversize; + /* Make the one we just received the head. */ reasm_data = inet_frag_reasm_prepare(&qp->q, skb, prev_tail); if (!reasm_data) goto out_nomem; - len = ip_hdrlen(skb) + qp->q.len; - err = -E2BIG; - if (len > 65535) - goto out_oversize; - inet_frag_reasm_finish(&qp->q, skb, reasm_data, ip_frag_coalesce_ok(qp)); diff --git a/net/ipv4/ip_output.c b/net/ipv4/ip_output.c index eaa6fabda347..3396f177a18d 100644 --- a/net/ipv4/ip_output.c +++ b/net/ipv4/ip_output.c @@ -1414,6 +1414,7 @@ struct sk_buff *__ip_make_skb(struct sock *sk, struct iphdr *iph; u8 pmtudisc, ttl; __be16 df = 0; + int segs; skb = __skb_dequeue(queue); if (!skb) @@ -1468,7 +1469,19 @@ struct sk_buff *__ip_make_skb(struct sock *sk, iph->ttl = ttl; iph->protocol = sk->sk_protocol; ip_copy_addrs(iph, fl4); - ip_select_ident(net, skb, sk); + + /* UDP GSO packets are segmented later (see udp_send_skb()): + * reserve one IP ID per segment. + */ + segs = 1; + if (cork->gso_size && sk_is_udp(sk)) { + int datalen = skb->len - skb_transport_offset(skb) - + sizeof(struct udphdr); + + if (datalen > cork->gso_size) + segs = DIV_ROUND_UP(datalen, cork->gso_size); + } + ip_select_ident_segs(net, skb, sk, segs); if (opt) { iph->ihl += opt->optlen >> 2; diff --git a/net/ipv4/ip_tunnel.c b/net/ipv4/ip_tunnel.c index e6bcf01411d0..13b5e35e8790 100644 --- a/net/ipv4/ip_tunnel.c +++ b/net/ipv4/ip_tunnel.c @@ -491,19 +491,17 @@ int ip_tunnel_encap_setup(struct ip_tunnel *t, { int hlen; - memset(&t->encap, 0, sizeof(t->encap)); - hlen = ip_encap_hlen(ipencap); if (hlen < 0) return hlen; - t->encap.type = ipencap->type; - t->encap.sport = ipencap->sport; - t->encap.dport = ipencap->dport; - t->encap.flags = ipencap->flags; + WRITE_ONCE(t->encap.type, ipencap->type); + WRITE_ONCE(t->encap.sport, ipencap->sport); + WRITE_ONCE(t->encap.dport, ipencap->dport); + WRITE_ONCE(t->encap.flags, ipencap->flags); - t->encap_hlen = hlen; - t->hlen = t->encap_hlen + t->tun_hlen; + WRITE_ONCE(t->encap_hlen, hlen); + WRITE_ONCE(t->hlen, hlen + t->tun_hlen); return 0; } diff --git a/net/ipv4/ipmr.c b/net/ipv4/ipmr.c index f51014b37178..5bfbb8d88bf4 100644 --- a/net/ipv4/ipmr.c +++ b/net/ipv4/ipmr.c @@ -554,6 +554,11 @@ static netdev_tx_t reg_vif_xmit(struct sk_buff *skb, struct net_device *dev) DEV_STATS_ADD(dev, tx_bytes, skb->len); DEV_STATS_INC(dev, tx_packets); + /* skb->cb[] holds qdisc/tc state at this point, not IPCB. + * ipmr_cache_report() reads it as IPCB to build IP_PKTINFO. + */ + memset(IPCB(skb), 0, sizeof(*IPCB(skb))); + /* Pairs with WRITE_ONCE() in vif_add() and vif_delete() */ ipmr_cache_report(mrt, skb, READ_ONCE(mrt->mroute_reg_vif_num), IGMPMSG_WHOLEPKT); diff --git a/net/ipv4/syncookies.c b/net/ipv4/syncookies.c index 4b2d2713653b..4e0ff3b82062 100644 --- a/net/ipv4/syncookies.c +++ b/net/ipv4/syncookies.c @@ -406,12 +406,12 @@ static struct request_sock *cookie_tcp_check(struct net *net, struct sock *sk, */ struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb) { - struct ip_options *opt = &TCP_SKB_CB(skb)->header.h4.opt; const struct tcphdr *th = tcp_hdr(skb); struct tcp_sock *tp = tcp_sk(sk); struct inet_request_sock *ireq; struct net *net = sock_net(sk); struct tcp_request_sock *treq; + struct ip_options_rcu *opt; struct request_sock *req; struct sock *ret = sk; struct flowi4 fl4; @@ -451,6 +451,8 @@ struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb) SKB_DR_SET(reason, SECURITY_HOOK); goto out_free; } + /* Load ireq->ireq_opt after the LSM hook, which can replace it. */ + opt = rcu_dereference_protected(ireq->ireq_opt, true); tcp_ao_syncookie(sk, skb, req, AF_INET); @@ -463,7 +465,7 @@ struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb) flowi4_init_output(&fl4, ireq->ir_iif, ireq->ir_mark, ip_sock_rt_tos(sk), ip_sock_rt_scope(sk), IPPROTO_TCP, inet_sk_flowi_flags(sk), - opt->srr ? opt->faddr : ireq->ir_rmt_addr, + (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr, ireq->ir_loc_addr, th->source, th->dest, sk_uid(sk)); security_req_classify_flow(req, flowi4_to_flowi_common(&fl4)); @@ -472,6 +474,12 @@ struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb) SKB_DR_SET(reason, IP_OUTNOROUTES); goto out_free; } + /* Same check as in inet_csk_route_req(). */ + if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway) { + ip_rt_put(rt); + SKB_DR_SET(reason, IP_OUTNOROUTES); + goto out_free; + } /* Try to redo what tcp_v4_send_synack did. */ req->rsk_window_clamp = READ_ONCE(tp->window_clamp) ? : diff --git a/net/ipv4/tcp.c b/net/ipv4/tcp.c index 87ef6d5cbfeb..73d5b7c8e3c7 100644 --- a/net/ipv4/tcp.c +++ b/net/ipv4/tcp.c @@ -1169,14 +1169,18 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size) zc = MSG_SPLICE_PAGES; } - if (!sockc_err && sockc.dmabuf_id && (zc != MSG_ZEROCOPY || !binding)) { - err = -EINVAL; + if (sockc.dmabuf_id && (zc != MSG_ZEROCOPY || !binding)) { + err = sockc_err ?: -EINVAL; goto out_err; } if (unlikely(flags & MSG_FASTOPEN || inet_test_bit(DEFER_CONNECT, sk)) && !tp->repair) { + if (binding) { + err = -EINVAL; + goto out_err; + } err = tcp_sendmsg_fastopen(sk, msg, &copied_syn, size, uarg); if (err == -EINPROGRESS && copied_syn > 0) goto out; @@ -1200,6 +1204,10 @@ int tcp_sendmsg_locked(struct sock *sk, struct msghdr *msg, size_t size) } if (unlikely(tp->repair)) { + if (binding) { + err = -EINVAL; + goto out_err; + } if (tp->repair_queue == TCP_RECV_QUEUE) { copied = tcp_send_rcvq(sk, msg, size); goto out_nopush; @@ -5116,6 +5124,8 @@ void tcp_done(struct sock *sk) int tcp_abort(struct sock *sk, int err) { int state = inet_sk_state_load(sk); + bool listener = false; + int ret = 0; if (state == TCP_NEW_SYN_RECV) { struct request_sock *req = inet_reqsk(sk); @@ -5150,21 +5160,31 @@ int tcp_abort(struct sock *sk, int err) if (sk->sk_state == TCP_LISTEN) { tcp_set_state(sk, TCP_CLOSE); inet_csk_listen_stop(sk); + listener = true; } /* Don't race with BH socket closes such as inet_csk_listen_stop. */ local_bh_disable(); bh_lock_sock(sk); + /* An unaccepted child might have been closed by + * inet_csk_listen_stop() while we were not holding its BH lock. + */ + if (!listener && sk->sk_state == TCP_CLOSE) { + ret = -ENOENT; + goto out; + } + if (tcp_need_reset(sk->sk_state)) tcp_send_active_reset(sk, SK_RST_REASON_TCP_STATE); tcp_done_with_error(sk, err); +out: bh_unlock_sock(sk); local_bh_enable(); if (!has_current_bpf_ctx()) release_sock(sk); - return 0; + return ret; } EXPORT_SYMBOL_GPL(tcp_abort); diff --git a/net/ipv4/tcp_bic.c b/net/ipv4/tcp_bic.c index 65444ff14241..27d2e38ff793 100644 --- a/net/ipv4/tcp_bic.c +++ b/net/ipv4/tcp_bic.c @@ -27,15 +27,25 @@ */ static int fast_convergence = 1; -static int max_increment = 16; +static unsigned int max_increment = 16; static int low_window = 14; static int beta = 819; /* = 819/1024 (BICTCP_BETA_SCALE) */ static int initial_ssthresh; static int smooth_part = 20; +static int max_increment_set(const char *val, const struct kernel_param *kp) +{ + return param_set_uint_minmax(val, kp, 1, INT_MAX); +} + +static const struct kernel_param_ops max_increment_ops = { + .set = max_increment_set, + .get = param_get_uint, +}; + module_param(fast_convergence, int, 0644); MODULE_PARM_DESC(fast_convergence, "turn on/off fast convergence"); -module_param(max_increment, int, 0644); +module_param_cb(max_increment, &max_increment_ops, &max_increment, 0644); MODULE_PARM_DESC(max_increment, "Limit on increment allowed during binary search"); module_param(low_window, int, 0644); MODULE_PARM_DESC(low_window, "lower bound on congestion window (for TCP friendliness)"); diff --git a/net/ipv4/tcp_bpf.c b/net/ipv4/tcp_bpf.c index 2e234d155b5e..0ce583f68d3b 100644 --- a/net/ipv4/tcp_bpf.c +++ b/net/ipv4/tcp_bpf.c @@ -581,6 +581,7 @@ static int tcp_bpf_sendmsg(struct sock *sk, struct msghdr *msg, size_t size) copy); if (ret < 0) { sk_msg_trim(sk, msg_tx, osize); + err = ret; goto out_err; } diff --git a/net/ipv4/tcp_cubic.c b/net/ipv4/tcp_cubic.c index 119bf8cbb007..a88e4bf86150 100644 --- a/net/ipv4/tcp_cubic.c +++ b/net/ipv4/tcp_cubic.c @@ -500,16 +500,26 @@ static const struct btf_kfunc_id_set tcp_cubic_kfunc_set = { static int __init cubictcp_register(void) { + int b = READ_ONCE(beta); int ret; BUILD_BUG_ON(sizeof(struct bictcp) > ICSK_CA_PRIV_SIZE); + if (b < 0 || b >= BICTCP_BETA_SCALE || + bic_scale <= 0 || bic_scale > INT_MAX / 10) { + pr_err("tcp_cubic: invalid beta %d or bic_scale %d\n", + b, bic_scale); + return -EINVAL; + } + /* Precompute a bunch of the scaling factors that are used per-packet * based on SRTT of 100ms */ - beta_scale = 8*(BICTCP_BETA_SCALE+beta) / 3 - / (BICTCP_BETA_SCALE - beta); + beta_scale = 8 * (BICTCP_BETA_SCALE + b) / 3 + / (BICTCP_BETA_SCALE - b); + /* bictcp_update() needs (cwnd * beta_scale) >> 3 to be >= 1 */ + beta_scale = max(beta_scale, 8U); cube_rtt_scale = (bic_scale * 10); /* 1024*c/rtt */ diff --git a/net/ipv4/tcp_hybla.c b/net/ipv4/tcp_hybla.c index abd7d91807e5..b9b482180d30 100644 --- a/net/ipv4/tcp_hybla.c +++ b/net/ipv4/tcp_hybla.c @@ -26,8 +26,20 @@ struct hybla { }; /* Hybla reference round trip time (default= 1/40 sec = 25 ms), in ms */ -static int rtt0 = 25; -module_param(rtt0, int, 0644); +static unsigned int rtt0 = 25; + +static int rtt0_set(const char *val, const struct kernel_param *kp) +{ + /* avoid rtt0 * USEC_PER_MSEC overflow */ + return param_set_uint_minmax(val, kp, 1, U32_MAX / USEC_PER_MSEC); +} + +static const struct kernel_param_ops rtt0_ops = { + .set = rtt0_set, + .get = param_get_uint, +}; + +module_param_cb(rtt0, &rtt0_ops, &rtt0, 0644); MODULE_PARM_DESC(rtt0, "reference rout trip time (ms)"); /* This is called to refresh values for hybla parameters */ diff --git a/net/ipv4/tcp_ipv4.c b/net/ipv4/tcp_ipv4.c index bebc5a8d1ab6..b41431338102 100644 --- a/net/ipv4/tcp_ipv4.c +++ b/net/ipv4/tcp_ipv4.c @@ -238,6 +238,9 @@ int tcp_v4_connect(struct sock *sk, struct sockaddr_unsized *uaddr, int addr_len if (usin->sin_family != AF_INET) return -EAFNOSUPPORT; + if (psp_sk_assoc(sk)) + return -EINVAL; + nexthop = daddr = usin->sin_addr.s_addr; inet_opt = rcu_dereference_protected(inet->inet_opt, lockdep_sock_is_held(sk)); @@ -291,9 +294,9 @@ int tcp_v4_connect(struct sock *sk, struct sockaddr_unsized *uaddr, int addr_len inet->inet_dport = usin->sin_port; sk_daddr_set(sk, daddr); - inet_csk(sk)->icsk_ext_hdr_len = psp_sk_overhead(sk); + inet_csk(sk)->icsk_ext_hdr_len = 0; if (inet_opt) - inet_csk(sk)->icsk_ext_hdr_len += inet_opt->opt.optlen; + inet_csk(sk)->icsk_ext_hdr_len = inet_opt->opt.optlen; tp->rx_opt.mss_clamp = TCP_MSS_DEFAULT; @@ -1720,6 +1723,12 @@ struct sock *tcp_v4_syn_recv_sock(const struct sock *sk, struct sk_buff *skb, if (READ_ONCE(sock_net(sk)->ipv4.sysctl_tcp_reflect_tos)) newinet->tos = tcp_rsk(req)->syn_tos & ~INET_ECN_MASK; +#if IS_ENABLED(CONFIG_IPV6) + /* Detach IPv6 state before a route lookup can fail. */ + if (opt_child_init) + opt_child_init(newsk, sk); +#endif + if (!dst) { dst = inet_csk_route_child_sock(sk, newsk, req); if (!dst) @@ -1729,10 +1738,6 @@ struct sock *tcp_v4_syn_recv_sock(const struct sock *sk, struct sk_buff *skb, } sk_setup_caps(newsk, dst); -#if IS_ENABLED(CONFIG_IPV6) - if (opt_child_init) - opt_child_init(newsk, sk); -#endif tcp_ca_openreq_child(newsk, dst); tcp_sync_mss(newsk, dst4_mtu(dst)); diff --git a/net/ipv4/tcp_metrics.c b/net/ipv4/tcp_metrics.c index dc0c081fc1f3..d58f99c67d4d 100644 --- a/net/ipv4/tcp_metrics.c +++ b/net/ipv4/tcp_metrics.c @@ -161,16 +161,26 @@ static void tcpm_check_stamp(struct tcp_metrics_block *tm, rcu_dereference_protected(p, lockdep_is_held(&tcp_metrics_lock)) static struct tcp_metrics_block *tcpm_new(struct dst_entry *dst, + struct net *net, struct inetpeer_addr *saddr, struct inetpeer_addr *daddr, unsigned int hash) { struct tcp_metrics_block *tm; bool reclaim = false; - struct net *net; spin_lock_bh(&tcp_metrics_lock); - net = dst_dev_net_rcu(dst); + + /* Do not add entries to a dismantling netns: they would not be + * flushed again. Callers are in an RCU read-side section, and + * cleanup_net() waits for a grace period after the netns refcount + * reached zero and before tcp_metrics_flush_all(NULL) runs, so an + * entry added after a successful check_net() is seen by the flush. + */ + if (unlikely(!check_net(net))) { + tm = NULL; + goto out_unlock; + } /* While waiting for the spin-lock the cache might have been populated * with this entry and so we have to check again. @@ -273,7 +283,7 @@ static struct tcp_metrics_block *__tcp_get_metrics_req(struct request_sock *req, return NULL; } - net = dst_dev_net_rcu(dst); + net = sock_net(req_to_sk(req)); hash ^= net_hash_mix(net); hash = hash_32(hash, tcp_metrics_hash_log); @@ -318,7 +328,7 @@ static struct tcp_metrics_block *tcp_get_metrics(struct sock *sk, else return NULL; - net = dst_dev_net_rcu(dst); + net = sock_net(sk); hash ^= net_hash_mix(net); hash = hash_32(hash, tcp_metrics_hash_log); @@ -326,7 +336,7 @@ static struct tcp_metrics_block *tcp_get_metrics(struct sock *sk, if (tm == TCP_METRICS_RECLAIM_PTR) tm = NULL; if (!tm && create) - tm = tcpm_new(dst, &saddr, &daddr, hash); + tm = tcpm_new(dst, net, &saddr, &daddr, hash); else tcpm_check_stamp(tm, dst); diff --git a/net/ipv4/tcp_offload.c b/net/ipv4/tcp_offload.c index e74d99ca9fac..b84fcd07c723 100644 --- a/net/ipv4/tcp_offload.c +++ b/net/ipv4/tcp_offload.c @@ -315,14 +315,20 @@ struct sk_buff *tcp_gro_receive(struct list_head *head, struct sk_buff *skb, mss = skb_shinfo(p)->gso_size; - /* If skb is a GRO packet, make sure its gso_size matches prior packet mss. + /* If skb is a GRO packet, make sure its gso_size matches prior packet + * mss, and that its payload is consistent with its gso_segs + * (the last segment can be short). * If it is a single frame, do not aggregate it if its length * is bigger than our mss. */ - if (unlikely(skb_is_gso(skb))) + if (unlikely(skb_is_gso(skb))) { + unsigned int segs = NAPI_GRO_CB(skb)->count; + flush |= (mss != skb_shinfo(skb)->gso_size); - else + flush |= len <= (segs - 1) * mss || len > segs * mss; + } else { flush |= (len - 1) >= mss; + } flush |= (ntohl(th2->seq) + skb_gro_len(p)) ^ ntohl(th->seq); flush |= skb_cmp_decrypted(p, skb); diff --git a/net/ipv6/calipso.c b/net/ipv6/calipso.c index a0192b4fef33..e399a42e3083 100644 --- a/net/ipv6/calipso.c +++ b/net/ipv6/calipso.c @@ -283,7 +283,7 @@ static int calipso_cache_add(const unsigned char *calipso_ptr, goto cache_add_failure; } entry->key_len = calipso_ptr_len; - entry->hash = calipso_map_cache_hash(calipso_ptr, calipso_ptr_len); + entry->hash = calipso_map_cache_hash(entry->key, calipso_ptr_len); refcount_inc(&secattr->cache->refcount); entry->lsm_data = secattr->cache; @@ -1428,6 +1428,10 @@ static int calipso_skbuff_delattr(struct sk_buff *skb) skb_pull(skb, delta); memmove((char *)ip6_hdr + delta, ip6_hdr, size); skb_reset_network_header(skb); + ip6_hdr = ipv6_hdr(skb); + /* BIG TCP packets have payload_len == 0 */ + if (ip6_hdr->payload_len) + be16_add_cpu(&ip6_hdr->payload_len, -delta); } return 0; diff --git a/net/ipv6/exthdrs.c b/net/ipv6/exthdrs.c index 09a4552f7f08..3ef3c2635581 100644 --- a/net/ipv6/exthdrs.c +++ b/net/ipv6/exthdrs.c @@ -387,7 +387,7 @@ static int ipv6_srh_rcv(struct sk_buff *skb, struct inet6_dev *idev) } #ifdef CONFIG_IPV6_SEG6_HMAC - if (!seg6_hmac_validate_skb(skb)) { + if (!seg6_hmac_validate_skb(skb, hdr)) { kfree_skb(skb); return -1; } diff --git a/net/ipv6/ip6_fib.c b/net/ipv6/ip6_fib.c index 9ff761962b45..ef65dd9870ea 100644 --- a/net/ipv6/ip6_fib.c +++ b/net/ipv6/ip6_fib.c @@ -1228,9 +1228,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(); } /* @@ -1274,9 +1272,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; } } diff --git a/net/ipv6/ip6mr.c b/net/ipv6/ip6mr.c index ed9d786f1a42..8e647213ade1 100644 --- a/net/ipv6/ip6mr.c +++ b/net/ipv6/ip6mr.c @@ -652,6 +652,12 @@ 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); + /* 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(); diff --git a/net/ipv6/netfilter/nf_conntrack_reasm.c b/net/ipv6/netfilter/nf_conntrack_reasm.c index 599c49bf0a0a..f25ff2a12a82 100644 --- a/net/ipv6/netfilter/nf_conntrack_reasm.c +++ b/net/ipv6/netfilter/nf_conntrack_reasm.c @@ -330,11 +330,10 @@ static int nf_ct_frag6_reasm(struct frag_queue *fq, struct sk_buff *skb, if (unlikely(ecn == 0xff)) goto err; - reasm_data = inet_frag_reasm_prepare(&fq->q, skb, prev_tail); - if (!reasm_data) - goto err; - - payload_len = -skb_network_offset(skb) - + /* Check the size on the first fragment, which will become the head: + * inet_frag_reasm_finish() must follow inet_frag_reasm_prepare(). + */ + payload_len = -skb_network_offset(skb_rb_first(&fq->q.rb_fragments)) - sizeof(struct ipv6hdr) + fq->q.len - sizeof(struct frag_hdr); if (payload_len > IPV6_MAXPLEN) { @@ -343,6 +342,10 @@ static int nf_ct_frag6_reasm(struct frag_queue *fq, struct sk_buff *skb, goto err; } + reasm_data = inet_frag_reasm_prepare(&fq->q, skb, prev_tail); + if (!reasm_data) + goto err; + /* We have to remove fragment header from datagram and to relocate * header in order to calculate ICV correctly. */ skb_network_header(skb)[fq->nhoffset] = skb_transport_header(skb)[0]; @@ -398,7 +401,7 @@ find_prev_fhdr(struct sk_buff *skb, u8 *prevhdrp, int *prevhoff, int *fhoff) { u8 nexthdr = ipv6_hdr(skb)->nexthdr; const int netoff = skb_network_offset(skb); - u8 prev_nhoff = netoff + offsetof(struct ipv6hdr, nexthdr); + int prev_nhoff = netoff + offsetof(struct ipv6hdr, nexthdr); int start = netoff + sizeof(struct ipv6hdr); int len = skb->len - start; u8 prevhdr = NEXTHDR_IPV6; diff --git a/net/ipv6/reassembly.c b/net/ipv6/reassembly.c index 8418ed9423f4..91a65fe67350 100644 --- a/net/ipv6/reassembly.c +++ b/net/ipv6/reassembly.c @@ -275,16 +275,19 @@ static int ip6_frag_reasm(struct frag_queue *fq, struct sk_buff *skb, if (unlikely(ecn == 0xff)) goto out_fail; - reasm_data = inet_frag_reasm_prepare(&fq->q, skb, prev_tail); - if (!reasm_data) - goto out_oom; - - payload_len = -skb_network_offset(skb) - + /* Check the size on the first fragment, which will become the head: + * inet_frag_reasm_finish() must follow inet_frag_reasm_prepare(). + */ + payload_len = -skb_network_offset(skb_rb_first(&fq->q.rb_fragments)) - sizeof(struct ipv6hdr) + fq->q.len - sizeof(struct frag_hdr); if (payload_len > IPV6_MAXPLEN) goto out_oversize; + reasm_data = inet_frag_reasm_prepare(&fq->q, skb, prev_tail); + if (!reasm_data) + goto out_oom; + /* We have to remove fragment header from datagram and to relocate * header in order to calculate ICV correctly. */ nhoff = fq->nhoffset; diff --git a/net/ipv6/route.c b/net/ipv6/route.c index bd6bc9ada539..b8f51cabca3c 100644 --- a/net/ipv6/route.c +++ b/net/ipv6/route.c @@ -1503,6 +1503,15 @@ static struct rt6_info *rt6_make_pcpu_route(struct net *net, */ static DEFINE_SPINLOCK(rt6_exception_lock); +/* Exceptions are accounted to the netns their dst was allocated in. + * Unlike dev_net(dst->dev), it does not change when the device moves to + * another netns or when dst_dev_put() points the dst to blackhole_netdev. + */ +static struct net *rt6_exception_net(const struct rt6_info *rt) +{ + return container_of(rt->dst.ops, struct net, ipv6.ip6_dst_ops); +} + /* Remove rt6_ex from hash table and free the memory * Caller must hold rt6_exception_lock */ @@ -1514,7 +1523,7 @@ static void rt6_remove_exception(struct rt6_exception_bucket *bucket, if (!bucket || !rt6_ex) return; - net = dev_net(rt6_ex->rt6i->dst.dev); + net = rt6_exception_net(rt6_ex->rt6i); net->ipv6.rt6_stats->fib_rt_cache--; /* purge completely the exception to allow releasing the held resources: @@ -1783,7 +1792,7 @@ static int rt6_insert_exception(struct rt6_info *nrt, rt6_ex->stamp = jiffies; hlist_add_head_rcu(&rt6_ex->hlist, &bucket->chain); bucket->depth++; - net->ipv6.rt6_stats->fib_rt_cache++; + rt6_exception_net(nrt)->ipv6.rt6_stats->fib_rt_cache++; /* Randomize max depth to avoid some side channels attacks. */ max_depth = FIB6_MAX_DEPTH + get_random_u32_below(FIB6_MAX_DEPTH); @@ -4900,8 +4909,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) @@ -5439,6 +5450,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); @@ -5525,10 +5537,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, @@ -5583,11 +5597,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) @@ -5597,9 +5613,11 @@ 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, + RT_DEL_REASON_UNSPEC); } + 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); @@ -6500,7 +6518,9 @@ void fib6_info_hw_flags_set(struct net *net, struct fib6_info *f6i, if (!fib_notify_on_flag_change) return; - skb = nlmsg_new(rt6_nlmsg_size(f6i), GFP_KERNEL); + rcu_read_lock(); + + skb = nlmsg_new(rt6_nlmsg_size(f6i), GFP_ATOMIC); if (!skb) { err = -ENOBUFS; goto errout; @@ -6513,10 +6533,13 @@ void fib6_info_hw_flags_set(struct net *net, struct fib6_info *f6i, goto errout; } + rcu_read_unlock(); + rtnl_notify(skb, net, 0, RTNLGRP_IPV6_ROUTE, NULL, GFP_KERNEL); return; errout: + rcu_read_unlock(); rtnl_set_sk_err(net, RTNLGRP_IPV6_ROUTE, err); } EXPORT_SYMBOL(fib6_info_hw_flags_set); diff --git a/net/ipv6/seg6_hmac.c b/net/ipv6/seg6_hmac.c index e6964c6b0d38..bd2704d4c7a0 100644 --- a/net/ipv6/seg6_hmac.c +++ b/net/ipv6/seg6_hmac.c @@ -173,13 +173,12 @@ EXPORT_SYMBOL(seg6_hmac_compute); * * called with rcu_read_lock() */ -bool seg6_hmac_validate_skb(struct sk_buff *skb) +bool seg6_hmac_validate_skb(struct sk_buff *skb, struct ipv6_sr_hdr *srh) { u8 hmac_output[SEG6_HMAC_FIELD_LEN]; struct net *net = dev_net(skb->dev); struct seg6_hmac_info *hinfo; struct sr6_tlv_hmac *tlv; - struct ipv6_sr_hdr *srh; struct inet6_dev *idev; int require_hmac; @@ -187,8 +186,6 @@ bool seg6_hmac_validate_skb(struct sk_buff *skb) if (!idev) return false; - srh = (struct ipv6_sr_hdr *)skb_transport_header(skb); - tlv = seg6_get_tlv_hmac(srh); require_hmac = READ_ONCE(idev->cnf.seg6_require_hmac); diff --git a/net/ipv6/seg6_local.c b/net/ipv6/seg6_local.c index 53f7b2452575..0c3d1be7f129 100644 --- a/net/ipv6/seg6_local.c +++ b/net/ipv6/seg6_local.c @@ -222,7 +222,7 @@ static struct ipv6_sr_hdr *get_and_validate_srh(struct sk_buff *skb) return NULL; #ifdef CONFIG_IPV6_SEG6_HMAC - if (!seg6_hmac_validate_skb(skb)) + if (!seg6_hmac_validate_skb(skb, srh)) return NULL; #endif @@ -239,7 +239,7 @@ static bool decap_and_validate(struct sk_buff *skb, int proto) return false; #ifdef CONFIG_IPV6_SEG6_HMAC - if (srh && !seg6_hmac_validate_skb(skb)) + if (srh && !seg6_hmac_validate_skb(skb, srh)) return false; #endif @@ -841,7 +841,7 @@ static int end_flv8986_core(struct sk_buff *skb, struct seg6_local_lwt *slwt) srhoff = srh ? ((unsigned char *)srh - skb->data) : 0; pinfo = seg6_get_srh_pktinfo(srh); #ifdef CONFIG_IPV6_SEG6_HMAC - if (srh && !seg6_hmac_validate_skb(skb)) + if (srh && !seg6_hmac_validate_skb(skb, srh)) goto drop; #endif flvmask = finfo->flv_ops; diff --git a/net/ipv6/sit.c b/net/ipv6/sit.c index 19b7fa8d1a2a..9a2bbd76d379 100644 --- a/net/ipv6/sit.c +++ b/net/ipv6/sit.c @@ -395,7 +395,7 @@ ipip6_tunnel_add_prl(struct ip_tunnel *t, struct ip_tunnel_prl *a, int chg) goto out; } - p = kzalloc_obj(struct ip_tunnel_prl_entry); + p = kzalloc_obj(struct ip_tunnel_prl_entry, GFP_KERNEL_ACCOUNT); if (!p) { err = -ENOBUFS; goto out; @@ -436,7 +436,7 @@ ipip6_tunnel_del_prl(struct ip_tunnel *t, struct ip_tunnel_prl *a) (x = rtnl_dereference(*p)) != NULL; p = &x->next) { if (x->addr == a->addr) { - *p = x->next; + rcu_assign_pointer(*p, rtnl_dereference(x->next)); kfree_rcu(x, rcu_head); t->prl_count--; goto out; @@ -447,8 +447,8 @@ ipip6_tunnel_del_prl(struct ip_tunnel *t, struct ip_tunnel_prl *a) x = rtnl_dereference(t->prl); if (x) { t->prl_count = 0; + RCU_INIT_POINTER(t->prl, NULL); call_rcu(&x->rcu_head, prl_list_destroy_rcu); - t->prl = NULL; } } out: diff --git a/net/ipv6/tcp_ipv6.c b/net/ipv6/tcp_ipv6.c index 7fa4ed2fd4f1..be50b2fe1274 100644 --- a/net/ipv6/tcp_ipv6.c +++ b/net/ipv6/tcp_ipv6.c @@ -153,6 +153,9 @@ static int tcp_v6_connect(struct sock *sk, struct sockaddr_unsized *uaddr, if (usin->sin6_family != AF_INET6) return -EAFNOSUPPORT; + if (psp_sk_assoc(sk)) + return -EINVAL; + fl6 = &inet_sk(sk)->cork.fl.u.ip6; memset(fl6, 0, sizeof(*fl6)); @@ -311,10 +314,10 @@ static int tcp_v6_connect(struct sock *sk, struct sockaddr_unsized *uaddr, sk->sk_gso_type = SKB_GSO_TCPV6; ip6_dst_store(sk, dst, false, false); - icsk->icsk_ext_hdr_len = psp_sk_overhead(sk); + icsk->icsk_ext_hdr_len = 0; if (opt) - icsk->icsk_ext_hdr_len += opt->opt_flen + - opt->opt_nflen; + icsk->icsk_ext_hdr_len = opt->opt_flen + + opt->opt_nflen; tp->rx_opt.mss_clamp = IPV6_MIN_MTU - sizeof(struct tcphdr) - sizeof(struct ipv6hdr); diff --git a/net/mac80211/cfg.c b/net/mac80211/cfg.c index a1753335eb9d..7cbd3a3c2ebd 100644 --- a/net/mac80211/cfg.c +++ b/net/mac80211/cfg.c @@ -1477,6 +1477,7 @@ ieee80211_assign_beacon(struct ieee80211_sub_if_data *sdata, struct beacon_data *new, *old; int new_head_len, new_tail_len; int size, err; + u8 *pos; u64 _changed = BSS_CHANGED_BEACON; struct ieee80211_bss_conf *link_conf = link->conf; @@ -1501,13 +1502,19 @@ ieee80211_assign_beacon(struct ieee80211_sub_if_data *sdata, size = sizeof(*new) + new_head_len + new_tail_len; + /* new or old multiple BSSID elements? */ if (params->mbssid_ies) { mbssid = params->mbssid_ies; + rnr = params->rnr_ies; + } else if (old && old->mbssid_ies) { + mbssid = old->mbssid_ies; + rnr = old->rnr_ies; + } + + if (mbssid) { size += struct_size(new->mbssid_ies, elem, mbssid->cnt); - if (params->rnr_ies) { - rnr = params->rnr_ies; + if (rnr) size += struct_size(new->rnr_ies, elem, rnr->cnt); - } size += ieee80211_get_mbssid_beacon_len(mbssid, rnr, mbssid->cnt); } @@ -1519,26 +1526,38 @@ ieee80211_assign_beacon(struct ieee80211_sub_if_data *sdata, /* start filling the new info now */ /* - * pointers go into the block we allocated, - * memory is | beacon_data | head | tail | mbssid_ies | rnr_ies + * pointers go into the block we allocated, the order in memory is + * - struct beacon_data + * - struct mbssid_ies (including variable array) + * - struct rnr_ies (including variable array) + * - beacon head + * - beacon tail + * - mbssid/rnr elements + * so that the structs (which contain pointers) are all aligned */ - new->head = ((u8 *) new) + sizeof(*new); - new->tail = new->head + new_head_len; - new->head_len = new_head_len; - new->tail_len = new_tail_len; - /* copy in optional mbssid_ies */ + pos = (u8 *)(new + 1); if (mbssid) { - u8 *pos = new->tail + new->tail_len; - new->mbssid_ies = (void *)pos; pos += struct_size(new->mbssid_ies, elem, mbssid->cnt); - pos += ieee80211_copy_mbssid_beacon(pos, new->mbssid_ies, - mbssid); if (rnr) { new->rnr_ies = (void *)pos; pos += struct_size(new->rnr_ies, elem, rnr->cnt); - ieee80211_copy_rnr_beacon(pos, new->rnr_ies, rnr); } + } + + new->head = pos; + new->head_len = new_head_len; + pos += new_head_len; + new->tail = pos; + new->tail_len = new_tail_len; + pos += new_tail_len; + + /* copy in optional mbssid_ies */ + if (mbssid) { + pos += ieee80211_copy_mbssid_beacon(pos, new->mbssid_ies, + mbssid); + if (rnr) + ieee80211_copy_rnr_beacon(pos, new->rnr_ies, rnr); /* update bssid_indicator */ if (new->mbssid_ies->cnt && new->mbssid_ies->elem[0].len > 2) link_conf->bssid_indicator = @@ -5987,6 +6006,18 @@ ieee80211_set_peer_nan_sched(struct wiphy *wiphy, return ieee80211_nan_set_peer_sched(sdata, sched); } +static int +ieee80211_set_nan_non_evac_channels(struct wiphy *wiphy, + struct wireless_dev *wdev, + struct cfg80211_nan_non_evac_channels *channels) +{ + struct ieee80211_sub_if_data *sdata = IEEE80211_WDEV_TO_SUB_IF(wdev); + + lockdep_assert_wiphy(wiphy); + + return ieee80211_nan_set_non_evac_channels(sdata, channels); +} + const struct cfg80211_ops mac80211_config_ops = { .add_virtual_intf = ieee80211_add_iface, .del_virtual_intf = ieee80211_del_iface, @@ -6105,4 +6136,5 @@ const struct cfg80211_ops mac80211_config_ops = { .set_epcs = ieee80211_set_epcs, .nan_set_local_sched = ieee80211_set_local_nan_sched, .nan_set_peer_sched = ieee80211_set_peer_nan_sched, + .nan_set_non_evac_channels = ieee80211_set_nan_non_evac_channels, }; diff --git a/net/mac80211/debugfs.c b/net/mac80211/debugfs.c index e38631d7cfb4..1f914b48e3bb 100644 --- a/net/mac80211/debugfs.c +++ b/net/mac80211/debugfs.c @@ -96,8 +96,8 @@ static ssize_t aqm_read(struct file *file, "RW fq_quantum %u\n", fq->flows_cnt, fq->backlog, - fq->overmemory, fq->overlimit, + fq->overmemory, fq->collisions, fq->memory_usage, fq->memory_limit, diff --git a/net/mac80211/ieee80211_i.h b/net/mac80211/ieee80211_i.h index 9374c2942489..cdd2581d7f59 100644 --- a/net/mac80211/ieee80211_i.h +++ b/net/mac80211/ieee80211_i.h @@ -52,7 +52,7 @@ struct ieee80211_mesh_fast_tx; /* Required encryption head and tailroom */ #define IEEE80211_ENCRYPT_HEADROOM 8 -#define IEEE80211_ENCRYPT_TAILROOM 18 +#define IEEE80211_ENCRYPT_TAILROOM 26 /* current max: GMAC/CMAC-256 MME */ /* power level hasn't been configured (or set to automatic) */ #define IEEE80211_UNSET_POWER_LEVEL INT_MIN @@ -1459,6 +1459,7 @@ struct ieee80211_local { spinlock_t active_txq_lock[IEEE80211_NUM_ACS]; struct list_head active_txqs[IEEE80211_NUM_ACS]; u16 schedule_round[IEEE80211_NUM_ACS]; + bool schedule_open[IEEE80211_NUM_ACS]; /* serializes ieee80211_handle_wake_tx_queue */ spinlock_t handle_wake_tx_queue_lock; @@ -2078,6 +2079,8 @@ int ieee80211_nan_set_local_sched(struct ieee80211_sub_if_data *sdata, struct cfg80211_nan_local_sched *sched); int ieee80211_nan_set_peer_sched(struct ieee80211_sub_if_data *sdata, struct cfg80211_nan_peer_sched *sched); +int ieee80211_nan_set_non_evac_channels(struct ieee80211_sub_if_data *sdata, + struct cfg80211_nan_non_evac_channels *channels); void ieee80211_nan_free_peer_sched(struct ieee80211_nan_peer_sched *sched); void ieee80211_nan_update_ndi_carrier(struct ieee80211_sub_if_data *ndi_sdata); struct ieee80211_nan_channel * @@ -2388,7 +2391,6 @@ ieee80211_he_op_ie_to_bss_conf(struct ieee80211_vif *vif, const struct ieee80211_he_operation *he_op_ie_elem); /* S1G */ -void ieee80211_s1g_sta_rate_init(struct sta_info *sta); bool ieee80211_s1g_is_twt_setup(struct sk_buff *skb); void ieee80211_s1g_rx_twt_action(struct ieee80211_sub_if_data *sdata, struct sk_buff *skb); diff --git a/net/mac80211/main.c b/net/mac80211/main.c index 6408e8464338..674f35663b3e 100644 --- a/net/mac80211/main.c +++ b/net/mac80211/main.c @@ -1732,6 +1732,8 @@ void ieee80211_unregister_hw(struct ieee80211_hw *hw) cancel_work_sync(&local->restart_work); + tasklet_kill(&local->wake_txqs_tasklet); + ieee80211_clear_tx_pending(local); rate_control_deinitialize(local); diff --git a/net/mac80211/mesh_pathtbl.c b/net/mac80211/mesh_pathtbl.c index 07a21dfa8674..0485a979b3c2 100644 --- a/net/mac80211/mesh_pathtbl.c +++ b/net/mac80211/mesh_pathtbl.c @@ -247,9 +247,10 @@ static struct mesh_path *mpath_lookup(struct mesh_table *tbl, const u8 *dst, mpath = rhashtable_lookup(&tbl->rhead, dst, mesh_rht_params); - if (mpath && mpath_expired(mpath)) { + if (mpath) { spin_lock_bh(&mpath->state_lock); - mpath->flags &= ~MESH_PATH_ACTIVE; + if (mpath_expired(mpath)) + mpath->flags &= ~MESH_PATH_ACTIVE; spin_unlock_bh(&mpath->state_lock); } return mpath; @@ -290,11 +291,11 @@ __mesh_path_lookup_by_idx(struct mesh_table *tbl, int idx) if (!mpath) return NULL; - if (mpath_expired(mpath)) { - spin_lock_bh(&mpath->state_lock); + spin_lock_bh(&mpath->state_lock); + if (mpath_expired(mpath)) mpath->flags &= ~MESH_PATH_ACTIVE; - spin_unlock_bh(&mpath->state_lock); - } + spin_unlock_bh(&mpath->state_lock); + return mpath; } @@ -679,7 +680,7 @@ void mesh_fast_tx_flush_addr(struct ieee80211_sub_if_data *sdata, * @sdata: local subif * @dst: destination address of the path (ETH_ALEN length) * - * Returns: 0 on success + * Returns: the new or the existing path on success, an ERR_PTR() on failure * * State: the initial state of the new path is set to 0 */ @@ -711,7 +712,7 @@ struct mesh_path *mesh_path_add(struct ieee80211_sub_if_data *sdata, &new_mpath->rhash, mesh_rht_params); if (!mpath) - hlist_add_head(&new_mpath->walk_list, &tbl->walk_head); + hlist_add_head_rcu(&new_mpath->walk_list, &tbl->walk_head); spin_unlock_bh(&tbl->walk_lock); if (mpath) { diff --git a/net/mac80211/mlme.c b/net/mac80211/mlme.c index 3c31c16860ab..d1c847dcce2f 100644 --- a/net/mac80211/mlme.c +++ b/net/mac80211/mlme.c @@ -6347,7 +6347,6 @@ static bool ieee80211_assoc_config_link(struct ieee80211_link_data *link, } static int ieee80211_mgd_setup_link_sta(struct ieee80211_link_data *link, - struct sta_info *sta, struct link_sta_info *link_sta, struct cfg80211_bss *cbss) { @@ -6362,11 +6361,9 @@ static int ieee80211_mgd_setup_link_sta(struct ieee80211_link_data *link, memcpy(link_sta->addr, cbss->bssid, ETH_ALEN); memcpy(link_sta->pub->addr, cbss->bssid, ETH_ALEN); - /* TODO: S1G Basic Rate Set is expressed elsewhere */ - if (cbss->channel->band == NL80211_BAND_S1GHZ) { - ieee80211_s1g_sta_rate_init(sta); + /* S1G does not use basic rates */ + if (cbss->channel->band == NL80211_BAND_S1GHZ) return 0; - } sband = local->hw.wiphy->bands[cbss->channel->band]; @@ -7107,7 +7104,7 @@ static bool ieee80211_assoc_success(struct ieee80211_sub_if_data *sdata, } } - err = ieee80211_mgd_setup_link_sta(link, sta, link_sta, + err = ieee80211_mgd_setup_link_sta(link, link_sta, assoc_data->link[link_id].bss); if (err) goto out_err; @@ -9699,8 +9696,7 @@ static int ieee80211_prep_connection(struct ieee80211_sub_if_data *sdata, goto out_err; } - err = ieee80211_mgd_setup_link_sta(link, new_sta, - link_sta, cbss); + err = ieee80211_mgd_setup_link_sta(link, link_sta, cbss); if (err) { rcu_read_unlock(); sta_info_free(local, new_sta); @@ -11090,7 +11086,7 @@ ieee80211_process_ml_reconf_resp(struct ieee80211_sub_if_data *sdata, goto disconnect; } - if (ieee80211_mgd_setup_link_sta(link, sta, link_sta, + if (ieee80211_mgd_setup_link_sta(link, link_sta, add_links_data->link[link_id].bss)) goto disconnect; diff --git a/net/mac80211/nan.c b/net/mac80211/nan.c index c7769da9617b..dc14b5d676fc 100644 --- a/net/mac80211/nan.c +++ b/net/mac80211/nan.c @@ -248,6 +248,35 @@ ieee80211_nan_find_free_channel(struct ieee80211_nan_sched_cfg *sched_cfg) return NULL; } +int +ieee80211_nan_set_non_evac_channels(struct ieee80211_sub_if_data *sdata, + struct cfg80211_nan_non_evac_channels *channels) +{ + struct ieee80211_nan_sched_cfg *sched_cfg = &sdata->vif.cfg.nan_sched; + + /* + * cfg80211 already validated that all provided channels belong to the + * current schedule, so just clear all non-evacuable flags and set the + * ones in the list. + */ + for (int j = 0; j < ARRAY_SIZE(sched_cfg->channels); j++) + sched_cfg->channels[j].no_evacuate = false; + + for (int i = 0; i < channels->n_channels; i++) { + for (int j = 0; j < ARRAY_SIZE(sched_cfg->channels); j++) { + if (!sched_cfg->channels[j].chanreq.oper.chan) + continue; + if (cfg80211_chandef_identical(&sched_cfg->channels[j].chanreq.oper, + &channels->chandefs[i])) { + sched_cfg->channels[j].no_evacuate = true; + break; + } + } + } + + return 0; +} + int ieee80211_nan_set_local_sched(struct ieee80211_sub_if_data *sdata, struct cfg80211_nan_local_sched *sched) { @@ -785,6 +814,10 @@ ieee80211_nan_find_evac_chan(struct ieee80211_local *local, usable_channels++; + /* No-evacuate channel is usable but cannot be evacuated */ + if (chan->no_evacuate) + continue; + chan_ctx = container_of(chan->chanctx_conf, struct ieee80211_chanctx, conf); diff --git a/net/mac80211/rate.c b/net/mac80211/rate.c index e910f03af777..f75257a19064 100644 --- a/net/mac80211/rate.c +++ b/net/mac80211/rate.c @@ -57,7 +57,6 @@ void rate_control_rate_init(struct link_sta_info *link_sta) /* TODO: check for minstrel_s1g ? */ if (sband->band == NL80211_BAND_S1GHZ) { - ieee80211_s1g_sta_rate_init(sta); rcu_read_unlock(); return; } diff --git a/net/mac80211/rx.c b/net/mac80211/rx.c index 7ead509304eb..aa8e3e375e07 100644 --- a/net/mac80211/rx.c +++ b/net/mac80211/rx.c @@ -2309,6 +2309,7 @@ ieee80211_reassemble_add(struct ieee80211_fragment_cache *cache, entry->rx_queue = rx_queue; entry->last_frag = frag; entry->check_sequential_pn = false; + entry->is_protected = false; entry->extra_len = 0; return entry; diff --git a/net/mac80211/s1g.c b/net/mac80211/s1g.c index bd7baf481836..4b70afa6e6d7 100644 --- a/net/mac80211/s1g.c +++ b/net/mac80211/s1g.c @@ -9,14 +9,6 @@ #include "ieee80211_i.h" #include "driver-ops.h" -void ieee80211_s1g_sta_rate_init(struct sta_info *sta) -{ - /* avoid indicating legacy bitrates for S1G STAs */ - sta->deflink.tx_stats.last_rate.flags |= IEEE80211_TX_RC_S1G_MCS; - sta->deflink.rx_stats.last_rate = - STA_STATS_FIELD(TYPE, STA_STATS_RATE_TYPE_S1G); -} - bool ieee80211_s1g_is_twt_setup(struct sk_buff *skb) { struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *)skb->data; diff --git a/net/mac80211/tx.c b/net/mac80211/tx.c index 27bae2a4fa86..0492205459f0 100644 --- a/net/mac80211/tx.c +++ b/net/mac80211/tx.c @@ -574,6 +574,43 @@ ieee80211_select_link_key(struct ieee80211_tx_data *tx) return NULL; } +/* + * An 802.3 frame is always a data frame, so there are no 802.11 addresses to + * look at: with a station the pairwise key is all that can apply, without one + * the frame is group addressed. On an MLD the driver has to pick the group key + * itself, as the same frame goes out on several links that each have their own. + */ +static ieee80211_tx_result +ieee80211_select_key_8023(struct ieee80211_tx_data *tx) +{ + struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); + + if (unlikely(info->flags & IEEE80211_TX_INTFL_DONT_ENCRYPT)) + return TX_CONTINUE; + + if (tx->sta) { + tx->key = rcu_dereference(tx->sta->ptk[tx->sta->ptk_idx]); + if (!tx->key) + tx->key = rcu_dereference(tx->sdata->default_unicast_key); + + if (!tx->key && test_sta_flag(tx->sta, WLAN_STA_USES_ENCRYPTION)) + return TX_DROP; + } else if (!ieee80211_vif_is_mld(&tx->sdata->vif)) { + tx->key = rcu_dereference(tx->sdata->deflink.default_multicast_key); + } + + if (!tx->key) + return TX_CONTINUE; + + if (unlikely(tx->key->flags & KEY_FLAG_TAINTED)) + return TX_DROP; + + if (tx->key->flags & KEY_FLAG_UPLOADED_TO_HARDWARE) + info->control.hw_key = &tx->key->conf; + + return TX_CONTINUE; +} + static ieee80211_tx_result debug_noinline ieee80211_tx_h_select_key(struct ieee80211_tx_data *tx) { @@ -581,6 +618,9 @@ ieee80211_tx_h_select_key(struct ieee80211_tx_data *tx) struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data; + if (info->flags & IEEE80211_TX_CTL_HW_80211_ENCAP) + return ieee80211_select_key_8023(tx); + if (unlikely(info->flags & IEEE80211_TX_INTFL_DONT_ENCRYPT)) { tx->key = NULL; return TX_CONTINUE; @@ -597,12 +637,6 @@ ieee80211_tx_h_select_key(struct ieee80211_tx_data *tx) else tx->key = NULL; - if (info->flags & IEEE80211_TX_CTL_HW_80211_ENCAP) { - if (tx->key && tx->key->flags & KEY_FLAG_UPLOADED_TO_HARDWARE) - info->control.hw_key = &tx->key->conf; - return TX_CONTINUE; - } - if (tx->key) { bool skip_hw = false; @@ -2140,6 +2174,27 @@ static bool ieee80211_rate_bw_usable(u16 rate_flags, return width <= cfg80211_chandef_get_width(chandef); } +static bool +ieee80211_vht_tx_rate_supported(const struct ieee80211_sta_vht_cap *vht_cap, + u8 mcs, u8 nss) +{ + u16 map = le16_to_cpu(vht_cap->vht_mcs.tx_mcs_map); + + if (!vht_cap->vht_supported) + return false; + + switch ((map >> (2 * (nss - 1))) & 3) { + case IEEE80211_VHT_MCS_SUPPORT_0_7: + return mcs <= 7; + case IEEE80211_VHT_MCS_SUPPORT_0_8: + return mcs <= 8; + case IEEE80211_VHT_MCS_SUPPORT_0_9: + return mcs <= 9; + default: + return false; + } +} + bool ieee80211_parse_tx_radiotap(struct sk_buff *skb, struct net_device *dev, const struct cfg80211_chan_def *chandef) @@ -2149,8 +2204,6 @@ bool ieee80211_parse_tx_radiotap(struct sk_buff *skb, struct ieee80211_radiotap_header *rthdr = (struct ieee80211_radiotap_header *) skb->data; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); - int ret = ieee80211_radiotap_iterator_init(&iterator, rthdr, skb->len, - NULL); u16 txflags; u16 rate = 0; bool rate_found = false; @@ -2159,11 +2212,14 @@ bool ieee80211_parse_tx_radiotap(struct sk_buff *skb, u8 mcs_known, mcs_flags, mcs_bw; u16 vht_known; u8 vht_mcs = 0, vht_nss = 0; - int i; + int ret, i; if (!ieee80211_validate_radiotap_len(skb)) return false; + ret = ieee80211_radiotap_iterator_init(&iterator, rthdr, skb->len, + NULL); + info->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT | IEEE80211_TX_CTL_DONTFRAG; @@ -2333,14 +2389,20 @@ bool ieee80211_parse_tx_radiotap(struct sk_buff *skb, hweight8(info->control.antennas)) info->control.antennas = 0; - info->control.rates[0].idx = rate; + /* MCS 32 and up aren't handled, e.g. by TX status */ + if (sband && sband->ht_cap.ht_supported && rate < 32 && + sband->ht_cap.mcs.rx_mask[rate / 8] & BIT(rate % 8)) + info->control.rates[0].idx = rate; } else if (rate_flags & IEEE80211_TX_RC_VHT_MCS) { /* reset antennas if not enough */ if (vht_nss > hweight8(info->control.antennas)) info->control.antennas = 0; - ieee80211_rate_set_vht(info->control.rates, vht_mcs, - vht_nss); + if (sband && + ieee80211_vht_tx_rate_supported(&sband->vht_cap, + vht_mcs, vht_nss)) + ieee80211_rate_set_vht(info->control.rates, + vht_mcs, vht_nss); } else if (sband) { for (i = 0; i < sband->n_bitrates; i++) { if (rate * 5 != sband->bitrates[i].bitrate) @@ -2668,6 +2730,29 @@ static void ieee80211_remove_ack_skb(struct ieee80211_local *local, u16 info_id) kfree_skb(ack_skb); } +static int ieee80211_ap_tx_addr_get(struct ieee80211_sub_if_data *sdata, + struct sta_info *sta, u8 *addr, u8 *link_id) +{ + struct ieee80211_link_data *link; + + if (!ieee80211_vif_is_mld(&sdata->vif) || sta->sta.mlo) { + memcpy(addr, sdata->vif.addr, ETH_ALEN); + return 0; + } + + guard(rcu)(); + + link = rcu_dereference(sdata->link[sta->deflink.link_id]); + if (WARN_ON(!link)) + return -ENOLINK; + + memcpy(addr, link->conf->addr, ETH_ALEN); + if (link_id) + *link_id = sta->deflink.link_id; + + return 0; +} + /** * ieee80211_build_hdr - build 802.11 header in the given frame * @sdata: virtual interface to build the header for @@ -2736,7 +2821,10 @@ static struct sk_buff *ieee80211_build_hdr(struct ieee80211_sub_if_data *sdata, fc |= cpu_to_le16(IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS); /* RA TA DA SA */ memcpy(hdr.addr1, sta->sta.addr, ETH_ALEN); - memcpy(hdr.addr2, sdata->vif.addr, ETH_ALEN); + ret = ieee80211_ap_tx_addr_get(sdata, sta, hdr.addr2, + &link_id); + if (ret) + goto free; memcpy(hdr.addr3, skb->data, ETH_ALEN); memcpy(hdr.addr4, skb->data + ETH_ALEN, ETH_ALEN); hdrlen = 30; @@ -2761,18 +2849,12 @@ static struct sk_buff *ieee80211_build_hdr(struct ieee80211_sub_if_data *sdata, /* DA BSSID SA */ memcpy(hdr.addr1, skb->data, ETH_ALEN); - if (ieee80211_vif_is_mld(&sdata->vif) && sta && !sta->sta.mlo) { - struct ieee80211_link_data *link; - - link_id = sta->deflink.link_id; - link = rcu_dereference(sdata->link[link_id]); - if (WARN_ON(!link)) { - ret = -ENOLINK; + if (sta) { + ret = ieee80211_ap_tx_addr_get(sdata, sta, hdr.addr2, + &link_id); + if (ret) goto free; - } - memcpy(hdr.addr2, link->conf->addr, ETH_ALEN); - } else if (link_id == IEEE80211_LINK_UNSPECIFIED || - (sta && sta->sta.mlo)) { + } else if (link_id == IEEE80211_LINK_UNSPECIFIED) { memcpy(hdr.addr2, sdata->vif.addr, ETH_ALEN); } else { struct ieee80211_bss_conf *conf; @@ -2989,8 +3071,7 @@ static struct sk_buff *ieee80211_build_hdr(struct ieee80211_sub_if_data *sdata, } if (unlikely(!multicast && - (sk_requests_wifi_status(skb->sk) || - ctrl_flags & IEEE80211_TX_CTL_REQ_TX_STATUS))) + (sk_requests_wifi_status(skb->sk) || cookie))) info_id = ieee80211_store_ack_skb(local, skb, &info_flags, cookie); @@ -3259,7 +3340,9 @@ void ieee80211_check_fast_xmit(struct sta_info *sta) IEEE80211_FCTL_TODS); /* RA TA DA SA */ memcpy(hdr->addr1, sta->sta.addr, ETH_ALEN); - memcpy(hdr->addr2, sdata->vif.addr, ETH_ALEN); + if (ieee80211_ap_tx_addr_get(sdata, sta, hdr->addr2, + NULL)) + goto out; build.da_offs = offsetof(struct ieee80211_hdr, addr3); build.sa_offs = offsetof(struct ieee80211_hdr, addr4); build.hdr_len = 30; @@ -3270,21 +3353,8 @@ void ieee80211_check_fast_xmit(struct sta_info *sta) fc |= cpu_to_le16(IEEE80211_FCTL_FROMDS); /* DA BSSID SA */ build.da_offs = offsetof(struct ieee80211_hdr, addr1); - if (sta->sta.mlo || !ieee80211_vif_is_mld(&sdata->vif)) { - memcpy(hdr->addr2, sdata->vif.addr, ETH_ALEN); - } else { - unsigned int link_id = sta->deflink.link_id; - struct ieee80211_link_data *link; - - rcu_read_lock(); - link = rcu_dereference(sdata->link[link_id]); - if (WARN_ON(!link)) { - rcu_read_unlock(); - goto out; - } - memcpy(hdr->addr2, link->conf->addr, ETH_ALEN); - rcu_read_unlock(); - } + if (ieee80211_ap_tx_addr_get(sdata, sta, hdr->addr2, NULL)) + goto out; build.sa_offs = offsetof(struct ieee80211_hdr, addr3); build.hdr_len = 24; break; @@ -3923,6 +3993,38 @@ static bool ieee80211_xmit_fast(struct ieee80211_sub_if_data *sdata, return true; } +static bool ieee80211_drop_unauth_port(struct ieee80211_tx_data *tx) +{ + struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); + struct ieee80211_hdr *hdr; + + if (likely(test_sta_flag(tx->sta, WLAN_STA_AUTHORIZED))) + return false; + + if (info->flags & IEEE80211_TX_CTL_INJECTED) + return false; + + if (ieee80211_vif_is_mesh(&tx->sdata->vif) || + tx->sdata->vif.type == NL80211_IFTYPE_OCB) + return false; + + /* no need to check forwarding here */ + if (info->flags & IEEE80211_TX_CTL_HW_80211_ENCAP) + return !(info->control.flags & IEEE80211_TX_CTRL_PORT_CTRL_PROTO); + + hdr = (struct ieee80211_hdr *)tx->skb->data; + + if (!ieee80211_is_data_present(hdr->frame_control) || + is_multicast_ether_addr(hdr->addr1)) + return false; + + if ((info->control.flags & IEEE80211_TX_CTRL_PORT_CTRL_PROTO) && + ieee80211_is_our_addr(tx->sdata, hdr->addr2, NULL)) + return false; + + return true; +} + struct sk_buff *ieee80211_tx_dequeue(struct ieee80211_hw *hw, struct ieee80211_txq *txq) { @@ -3989,20 +4091,8 @@ struct sk_buff *ieee80211_tx_dequeue(struct ieee80211_hw *hw, if (txq->sta) { tx.sta = container_of(txq->sta, struct sta_info, sta); - /* - * Drop unicast frames to unauthorised stations unless they are - * injected frames or EAPOL frames from the local station. - */ - if (unlikely(!(info->flags & IEEE80211_TX_CTL_INJECTED) && - ieee80211_is_data_present(hdr->frame_control) && - !ieee80211_vif_is_mesh(&tx.sdata->vif) && - tx.sdata->vif.type != NL80211_IFTYPE_OCB && - !is_multicast_ether_addr(hdr->addr1) && - !test_sta_flag(tx.sta, WLAN_STA_AUTHORIZED) && - (!(info->control.flags & - IEEE80211_TX_CTRL_PORT_CTRL_PROTO) || - !ieee80211_is_our_addr(tx.sdata, hdr->addr2, - NULL)))) { + + if (unlikely(ieee80211_drop_unauth_port(&tx))) { I802_DEBUG_INC(local->tx_handlers_drop_unauth_port); ieee80211_free_txskb(&local->hw, skb); goto begin; @@ -4174,7 +4264,7 @@ struct ieee80211_txq *ieee80211_next_txq(struct ieee80211_hw *hw, u8 ac) spin_lock_bh(&local->active_txq_lock[ac]); - if (!local->schedule_round[ac]) + if (!local->schedule_open[ac]) goto out; begin: @@ -4399,12 +4489,12 @@ void ieee80211_txq_schedule_start(struct ieee80211_hw *hw, u8 ac) spin_lock_bh(&local->active_txq_lock[ac]); - if (ieee80211_txq_schedule_airtime_check(local, ac)) { + local->schedule_open[ac] = + ieee80211_txq_schedule_airtime_check(local, ac); + if (local->schedule_open[ac]) { local->schedule_round[ac]++; if (!local->schedule_round[ac]) local->schedule_round[ac]++; - } else { - local->schedule_round[ac] = 0; } spin_unlock_bh(&local->active_txq_lock[ac]); @@ -5679,7 +5769,8 @@ __ieee80211_beacon_get_ap(struct ieee80211_hw *hw, skb = dev_alloc_skb(local->tx_headroom + beacon->head_len + beacon->tail_len + 256 + - local->hw.extra_beacon_tailroom + mbssid_len); + local->hw.extra_beacon_tailroom + mbssid_len + + IEEE80211_ENCRYPT_TAILROOM); if (!skb) return NULL; @@ -6608,9 +6699,6 @@ int ieee80211_tx_control_port(struct wiphy *wiphy, struct net_device *dev, if (unencrypted) flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT; - if (cookie) - ctrl_flags |= IEEE80211_TX_CTL_REQ_TX_STATUS; - flags |= IEEE80211_TX_INTFL_NL80211_FRAME_TX; skb = dev_alloc_skb(local->hw.extra_tx_headroom + diff --git a/net/mctp/route.c b/net/mctp/route.c index e7c95eeacb48..3d79c2031eba 100644 --- a/net/mctp/route.c +++ b/net/mctp/route.c @@ -552,8 +552,16 @@ static int mctp_dst_input(struct mctp_dst *dst, struct sk_buff *skb) * can do is drop. */ rc = mctp_key_add(key, msk); - if (!rc) + if (!rc) { trace_mctp_key_acquire(key); + } else { + /* key_add failed: the key is not observable by + * any cleanup path, so free the fragment we + * just queued on it to avoid leaking the skb. + */ + kfree_skb(key->reasm_head); + key->reasm_head = NULL; + } /* we don't need to release key->lock on exit, so * clean up here and suppress the unlock via diff --git a/net/mptcp/options.c b/net/mptcp/options.c index ce0de02f5a3a..966e785a4f0f 100644 --- a/net/mptcp/options.c +++ b/net/mptcp/options.c @@ -126,8 +126,11 @@ static void mptcp_parse_option(const struct sk_buff *skb, ptr += 2; } pr_debug("MP_CAPABLE version=%x, flags=%x, optlen=%d sndr=%llu, rcvr=%llu len=%d csum=%u\n", - version, flags, opsize, mp_opt->sndr_key, - mp_opt->rcvr_key, mp_opt->data_len, mp_opt->csum); + version, flags, opsize, + opsize >= TCPOLEN_MPTCP_MPC_SYNACK ? mp_opt->sndr_key : 0, + opsize >= TCPOLEN_MPTCP_MPC_ACK ? mp_opt->rcvr_key : 0, + opsize >= TCPOLEN_MPTCP_MPC_ACK_DATA ? mp_opt->data_len : 0, + opsize == TCPOLEN_MPTCP_MPC_ACK_DATA_CSUM ? mp_opt->csum : 0); break; case MPTCPOPT_MP_JOIN: @@ -256,7 +259,7 @@ static void mptcp_parse_option(const struct sk_buff *skb, pr_debug("data_seq=%llu subflow_seq=%u data_len=%u csum=%d:%u\n", mp_opt->data_seq, mp_opt->subflow_seq, mp_opt->data_len, !!(mp_opt->suboptions & OPTION_MPTCP_CSUMREQD), - mp_opt->csum); + (mp_opt->suboptions & OPTION_MPTCP_CSUMREQD) ? mp_opt->csum : 0); } break; diff --git a/net/netfilter/core.c b/net/netfilter/core.c index 675a1034b340..940dea2663e9 100644 --- a/net/netfilter/core.c +++ b/net/netfilter/core.c @@ -386,6 +386,15 @@ static void nf_static_key_dec(const struct nf_hook_ops *reg, int pf) #endif } +static void bump_hook_base_seq(struct net *net) +{ + unsigned int base_seq = READ_ONCE(net->nf.hook_base_seq); + + while (++base_seq == 0) + ; + smp_store_release(&net->nf.hook_base_seq, base_seq); +} + static int __nf_register_net_hook(struct net *net, int pf, const struct nf_hook_ops *reg) { @@ -430,6 +439,7 @@ static int __nf_register_net_hook(struct net *net, int pf, if (!IS_ERR(new_hooks)) { hooks_validate(new_hooks); rcu_assign_pointer(*pp, new_hooks); + bump_hook_base_seq(net); } mutex_unlock(&nf_hook_mutex); @@ -483,6 +493,7 @@ static void __nf_unregister_net_hook(struct net *net, int pf, { struct nf_hook_entries __rcu **pp; struct nf_hook_entries *p; + bool found; pp = nf_hook_entry_head(net, pf, reg->hooknum, reg->dev); if (!pp) @@ -496,7 +507,8 @@ static void __nf_unregister_net_hook(struct net *net, int pf, return; } - if (nf_remove_net_hook(p, reg)) { + found = nf_remove_net_hook(p, reg); + if (found) { #ifdef CONFIG_NETFILTER_INGRESS if (nf_ingress_hook(reg, pf)) net_dec_ingress_queue(); @@ -511,6 +523,8 @@ static void __nf_unregister_net_hook(struct net *net, int pf, } p = __nf_hook_entries_try_shrink(p, pp); + if (found) + bump_hook_base_seq(net); mutex_unlock(&nf_hook_mutex); if (!p) return; @@ -784,6 +798,8 @@ static int __net_init netfilter_net_init(struct net *net) return -ENOMEM; } #endif + net->nf.hook_base_seq = 1; + net->nf.nat_hook_base_seq = 1; return 0; } diff --git a/net/netfilter/ipvs/ip_vs_conn.c b/net/netfilter/ipvs/ip_vs_conn.c index cb009208826f..94f25fb7d87e 100644 --- a/net/netfilter/ipvs/ip_vs_conn.c +++ b/net/netfilter/ipvs/ip_vs_conn.c @@ -1153,8 +1153,8 @@ ip_vs_bind_dest(struct ip_vs_conn *cp, struct ip_vs_dest *dest) if (!(flags & IP_VS_CONN_F_INACTIVE)) atomic_inc(&dest->activeconns); tc = atomic_inc_return(&dest->totalconns); - if (tc == READ_ONCE(dest->u_threshold)) - ip_vs_dest_update_overload(dest, 1); + if (tc >= READ_ONCE(dest->u_threshold_val)) + ip_vs_dest_update_overload(dest, true); } else { /* It is a persistent connection/template, so increase the persistent connection counter */ @@ -1246,8 +1246,8 @@ static inline void ip_vs_unbind_dest(struct ip_vs_conn *cp) if (!(cp->flags & IP_VS_CONN_F_INACTIVE)) atomic_dec(&dest->activeconns); tc = atomic_fetch_dec(&dest->totalconns); - if (tc == READ_ONCE(dest->l_threshold_val)) - ip_vs_dest_update_overload(dest, -1); + if (tc <= READ_ONCE(dest->l_threshold_val)) + ip_vs_dest_update_overload(dest, false); } else { /* It is a persistent connection/template, so decrease the persistent connection counter */ diff --git a/net/netfilter/ipvs/ip_vs_ctl.c b/net/netfilter/ipvs/ip_vs_ctl.c index 4c1c739446b7..3003547dcabe 100644 --- a/net/netfilter/ipvs/ip_vs_ctl.c +++ b/net/netfilter/ipvs/ip_vs_ctl.c @@ -1309,32 +1309,32 @@ void ip_vs_stats_free(struct ip_vs_stats *stats) * - conns reach u_threshold and exceed it: set the flag * - conns go below l_threshold (or 75% of u_threshold): clear the flag */ -static void __ip_vs_dest_update_overload(struct ip_vs_dest *dest, int mode) +static void __ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload) { int conns; u32 l, u; lockdep_assert_held(&dest->dst_lock); u = READ_ONCE(dest->u_threshold); - if (!u) - goto unset; - l = READ_ONCE(dest->l_threshold_val); - conns = atomic_read(&dest->totalconns); - if (conns >= (mode > 0 ? l : u)) { - dest->flags |= IP_VS_DEST_F_OVERLOAD; - return; + if (u) { + /* Low threshold defaults to 75% of upper threshold */ + l = READ_ONCE(dest->l_threshold) ? : (u - (u >> 2)); + conns = atomic_read(&dest->totalconns); + if (conns >= (overload ? l : u)) { + WRITE_ONCE(dest->u_threshold_val, INT_MAX); + WRITE_ONCE(dest->l_threshold_val, l); + return; + } } - if (conns >= (mode < 0 ? u : l)) - return; -unset: - dest->flags &= ~IP_VS_DEST_F_OVERLOAD; + WRITE_ONCE(dest->u_threshold_val, u ? : INT_MAX); + WRITE_ONCE(dest->l_threshold_val, 0); } -void ip_vs_dest_update_overload(struct ip_vs_dest *dest, int mode) +void ip_vs_dest_update_overload(struct ip_vs_dest *dest, bool overload) { spin_lock_bh(&dest->dst_lock); - __ip_vs_dest_update_overload(dest, mode); + __ip_vs_dest_update_overload(dest, overload); spin_unlock_bh(&dest->dst_lock); } @@ -1406,15 +1406,13 @@ __ip_vs_update_dest(struct ip_vs_service *svc, struct ip_vs_dest *dest, if (READ_ONCE(dest->u_threshold) != udest->u_threshold || READ_ONCE(dest->l_threshold) != udest->l_threshold) { + bool overload; + spin_lock_bh(&dest->dst_lock); WRITE_ONCE(dest->u_threshold, udest->u_threshold); WRITE_ONCE(dest->l_threshold, udest->l_threshold); - /* Low threshold defaults to 75% of upper threshold */ - WRITE_ONCE(dest->l_threshold_val, - udest->l_threshold ? : - (udest->u_threshold - - (udest->u_threshold >> 2))); - __ip_vs_dest_update_overload(dest, 0); + overload = ip_vs_dest_is_overloaded(dest); + __ip_vs_dest_update_overload(dest, overload); spin_unlock_bh(&dest->dst_lock); } diff --git a/net/netfilter/ipvs/ip_vs_dh.c b/net/netfilter/ipvs/ip_vs_dh.c index 43abed7a26a6..95e52950adbb 100644 --- a/net/netfilter/ipvs/ip_vs_dh.c +++ b/net/netfilter/ipvs/ip_vs_dh.c @@ -195,16 +195,6 @@ static int ip_vs_dh_dest_changed(struct ip_vs_service *svc, } -/* - * If the dest flags is set with IP_VS_DEST_F_OVERLOAD, - * consider that the server is overloaded here. - */ -static inline int is_overloaded(struct ip_vs_dest *dest) -{ - return dest->flags & IP_VS_DEST_F_OVERLOAD; -} - - /* * Destination hashing scheduling */ @@ -219,10 +209,8 @@ ip_vs_dh_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, s = (struct ip_vs_dh_state *) svc->sched_data; dest = ip_vs_dh_get(svc->af, s, &iph->daddr); - if (!dest || - !(dest->cflags & IP_VS_DEST_CF_AVAILABLE) - || atomic_read(&dest->weight) <= 0 - || is_overloaded(dest)) { + if (!dest || atomic_read(&dest->weight) <= 0 || + ip_vs_dest_is_overloaded(dest)) { ip_vs_scheduler_err(svc, "no destination available"); return NULL; } diff --git a/net/netfilter/ipvs/ip_vs_fo.c b/net/netfilter/ipvs/ip_vs_fo.c index d657b47c6511..e07fa33f6d52 100644 --- a/net/netfilter/ipvs/ip_vs_fo.c +++ b/net/netfilter/ipvs/ip_vs_fo.c @@ -29,7 +29,7 @@ ip_vs_fo_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, * Find virtual server with highest weight and send it traffic */ list_for_each_entry_rcu(dest, &svc->destinations, n_list) { - if (!(dest->flags & IP_VS_DEST_F_OVERLOAD) && + if (!ip_vs_dest_is_overloaded(dest) && atomic_read(&dest->weight) > hw) { hweight = dest; hw = atomic_read(&dest->weight); diff --git a/net/netfilter/ipvs/ip_vs_lblc.c b/net/netfilter/ipvs/ip_vs_lblc.c index 55af77a56929..e1111c3b2721 100644 --- a/net/netfilter/ipvs/ip_vs_lblc.c +++ b/net/netfilter/ipvs/ip_vs_lblc.c @@ -418,7 +418,7 @@ __ip_vs_lblc_schedule(struct ip_vs_service *svc) * new connection. */ list_for_each_entry_rcu(dest, &svc->destinations, n_list) { - if (dest->flags & IP_VS_DEST_F_OVERLOAD) + if (ip_vs_dest_is_overloaded(dest)) continue; if (atomic_read(&dest->weight) > 0) { least = dest; @@ -433,7 +433,7 @@ __ip_vs_lblc_schedule(struct ip_vs_service *svc) */ nextstage: list_for_each_entry_continue_rcu(dest, &svc->destinations, n_list) { - if (dest->flags & IP_VS_DEST_F_OVERLOAD) + if (ip_vs_dest_is_overloaded(dest)) continue; doh = ip_vs_dest_conn_overhead(dest); diff --git a/net/netfilter/ipvs/ip_vs_lblcr.c b/net/netfilter/ipvs/ip_vs_lblcr.c index 858393b1d2d1..dfb5bf83750d 100644 --- a/net/netfilter/ipvs/ip_vs_lblcr.c +++ b/net/netfilter/ipvs/ip_vs_lblcr.c @@ -166,7 +166,7 @@ static inline struct ip_vs_dest *ip_vs_dest_set_min(struct ip_vs_dest_set *set) /* select the first destination server, whose weight > 0 */ list_for_each_entry_rcu(e, &set->list, list) { least = e->dest; - if (least->flags & IP_VS_DEST_F_OVERLOAD) + if (ip_vs_dest_is_overloaded(least)) continue; if ((atomic_read(&least->weight) > 0) && @@ -181,7 +181,7 @@ static inline struct ip_vs_dest *ip_vs_dest_set_min(struct ip_vs_dest_set *set) nextstage: list_for_each_entry_continue_rcu(e, &set->list, list) { dest = e->dest; - if (dest->flags & IP_VS_DEST_F_OVERLOAD) + if (ip_vs_dest_is_overloaded(dest)) continue; doh = ip_vs_dest_conn_overhead(dest); @@ -580,7 +580,7 @@ __ip_vs_lblcr_schedule(struct ip_vs_service *svc) * new connection. */ list_for_each_entry_rcu(dest, &svc->destinations, n_list) { - if (dest->flags & IP_VS_DEST_F_OVERLOAD) + if (ip_vs_dest_is_overloaded(dest)) continue; if (atomic_read(&dest->weight) > 0) { @@ -596,7 +596,7 @@ __ip_vs_lblcr_schedule(struct ip_vs_service *svc) */ nextstage: list_for_each_entry_continue_rcu(dest, &svc->destinations, n_list) { - if (dest->flags & IP_VS_DEST_F_OVERLOAD) + if (ip_vs_dest_is_overloaded(dest)) continue; doh = ip_vs_dest_conn_overhead(dest); diff --git a/net/netfilter/ipvs/ip_vs_lc.c b/net/netfilter/ipvs/ip_vs_lc.c index 18b976a7c4d2..9002f491bff6 100644 --- a/net/netfilter/ipvs/ip_vs_lc.c +++ b/net/netfilter/ipvs/ip_vs_lc.c @@ -38,7 +38,7 @@ ip_vs_lc_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, */ list_for_each_entry_rcu(dest, &svc->destinations, n_list) { - if ((dest->flags & IP_VS_DEST_F_OVERLOAD) || + if (ip_vs_dest_is_overloaded(dest) || atomic_read(&dest->weight) == 0) continue; doh = ip_vs_dest_conn_overhead(dest); diff --git a/net/netfilter/ipvs/ip_vs_mh.c b/net/netfilter/ipvs/ip_vs_mh.c index 020863047562..d70b23aec5fe 100644 --- a/net/netfilter/ipvs/ip_vs_mh.c +++ b/net/netfilter/ipvs/ip_vs_mh.c @@ -80,7 +80,7 @@ static inline void generate_hash_secret(hsiphash_key_t *hash1, static inline bool is_unavailable(struct ip_vs_dest *dest) { return atomic_read(&dest->weight) <= 0 || - dest->flags & IP_VS_DEST_F_OVERLOAD; + ip_vs_dest_is_overloaded(dest); } /* Returns hash value for IPVS MH entry */ diff --git a/net/netfilter/ipvs/ip_vs_nq.c b/net/netfilter/ipvs/ip_vs_nq.c index ada158c610ce..7cc28902086e 100644 --- a/net/netfilter/ipvs/ip_vs_nq.c +++ b/net/netfilter/ipvs/ip_vs_nq.c @@ -72,7 +72,7 @@ ip_vs_nq_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, list_for_each_entry_rcu(dest, &svc->destinations, n_list) { - if (dest->flags & IP_VS_DEST_F_OVERLOAD || + if (ip_vs_dest_is_overloaded(dest) || !atomic_read(&dest->weight)) continue; diff --git a/net/netfilter/ipvs/ip_vs_ovf.c b/net/netfilter/ipvs/ip_vs_ovf.c index c5c67df80a0b..eaa3a7ae6efa 100644 --- a/net/netfilter/ipvs/ip_vs_ovf.c +++ b/net/netfilter/ipvs/ip_vs_ovf.c @@ -33,7 +33,7 @@ ip_vs_ovf_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, */ list_for_each_entry_rcu(dest, &svc->destinations, n_list) { w = atomic_read(&dest->weight); - if ((dest->flags & IP_VS_DEST_F_OVERLOAD) || + if (ip_vs_dest_is_overloaded(dest) || atomic_read(&dest->activeconns) > w || w == 0) continue; diff --git a/net/netfilter/ipvs/ip_vs_rr.c b/net/netfilter/ipvs/ip_vs_rr.c index 4125ee561cdc..bd17cdd092f5 100644 --- a/net/netfilter/ipvs/ip_vs_rr.c +++ b/net/netfilter/ipvs/ip_vs_rr.c @@ -66,7 +66,7 @@ ip_vs_rr_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, list_for_each_entry_continue_rcu(dest, &svc->destinations, n_list) { - if (!(dest->flags & IP_VS_DEST_F_OVERLOAD) && + if (!ip_vs_dest_is_overloaded(dest) && atomic_read(&dest->weight) > 0) /* HIT */ goto out; diff --git a/net/netfilter/ipvs/ip_vs_sed.c b/net/netfilter/ipvs/ip_vs_sed.c index 245a323c84cd..7925f4d28fce 100644 --- a/net/netfilter/ipvs/ip_vs_sed.c +++ b/net/netfilter/ipvs/ip_vs_sed.c @@ -75,7 +75,7 @@ ip_vs_sed_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, */ list_for_each_entry_rcu(dest, &svc->destinations, n_list) { - if (!(dest->flags & IP_VS_DEST_F_OVERLOAD) && + if (!ip_vs_dest_is_overloaded(dest) && atomic_read(&dest->weight) > 0) { least = dest; loh = ip_vs_sed_dest_overhead(least); @@ -90,7 +90,7 @@ ip_vs_sed_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, */ nextstage: list_for_each_entry_continue_rcu(dest, &svc->destinations, n_list) { - if (dest->flags & IP_VS_DEST_F_OVERLOAD) + if (ip_vs_dest_is_overloaded(dest)) continue; doh = ip_vs_sed_dest_overhead(dest); if ((__s64)loh * atomic_read(&dest->weight) > diff --git a/net/netfilter/ipvs/ip_vs_sh.c b/net/netfilter/ipvs/ip_vs_sh.c index cd67066e3b26..c24dd5cb7e47 100644 --- a/net/netfilter/ipvs/ip_vs_sh.c +++ b/net/netfilter/ipvs/ip_vs_sh.c @@ -73,7 +73,7 @@ struct ip_vs_sh_state { static inline bool is_unavailable(struct ip_vs_dest *dest) { return atomic_read(&dest->weight) <= 0 || - dest->flags & IP_VS_DEST_F_OVERLOAD; + ip_vs_dest_is_overloaded(dest); } /* diff --git a/net/netfilter/ipvs/ip_vs_sync.c b/net/netfilter/ipvs/ip_vs_sync.c index 69dc28153ec1..1a30817fbbaf 100644 --- a/net/netfilter/ipvs/ip_vs_sync.c +++ b/net/netfilter/ipvs/ip_vs_sync.c @@ -543,13 +543,15 @@ static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, struct ip_vs_sync_conn_v0 *s; struct ip_vs_sync_buff *buff; struct ipvs_master_sync_state *ms; - int id; + u32 flags, seq_mask; unsigned int len; + int id; if (unlikely(cp->af != AF_INET)) return; + flags = READ_ONCE(cp->flags); /* Do not sync ONE PACKET */ - if (cp->flags & IP_VS_CONN_F_ONE_PACKET) + if (flags & IP_VS_CONN_F_ONE_PACKET) return; if (!ip_vs_sync_conn_needed(ipvs, cp, pkts)) @@ -564,8 +566,8 @@ static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, id = select_master_thread_id(ipvs, cp); ms = &ipvs->ms[id]; buff = ms->sync_buff; - len = (cp->flags & IP_VS_CONN_F_SEQ_MASK) ? FULL_CONN_SIZE : - SIMPLE_CONN_SIZE; + seq_mask = flags & IP_VS_CONN_F_SEQ_MASK; + len = seq_mask ? FULL_CONN_SIZE : SIMPLE_CONN_SIZE; if (buff) { m = (struct ip_vs_sync_mesg_v0 *) buff->mesg; /* Send buffer if it is for v1 */ @@ -597,9 +599,9 @@ static void ip_vs_sync_conn_v0(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, s->caddr = cp->caddr.ip; s->vaddr = cp->vaddr.ip; s->daddr = cp->daddr.ip; - s->flags = htons(cp->flags & ~IP_VS_CONN_F_HASHED); + s->flags = htons(flags & ~IP_VS_CONN_F_HASHED); s->state = htons(cp->state); - if (cp->flags & IP_VS_CONN_F_SEQ_MASK) { + if (seq_mask) { struct ip_vs_sync_conn_options *opt = (struct ip_vs_sync_conn_options *)&s[1]; memcpy(opt, &cp->sync_conn_opt, sizeof(*opt)); @@ -635,6 +637,7 @@ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts) int id; __u8 *p; unsigned int len, pe_name_len, pad; + u32 flags, seq_mask; /* Handle old version of the protocol */ if (sysctl_sync_ver(ipvs) == 0) { @@ -647,6 +650,7 @@ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts) sloop: if (!ip_vs_sync_conn_needed(ipvs, cp, pkts)) goto control; + flags = READ_ONCE(cp->flags); /* Sanity checks */ pe_name_len = 0; @@ -674,7 +678,8 @@ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts) #endif len = sizeof(struct ip_vs_sync_v4); - if (cp->flags & IP_VS_CONN_F_SEQ_MASK) + seq_mask = flags & IP_VS_CONN_F_SEQ_MASK; + if (seq_mask) len += sizeof(struct ip_vs_sync_conn_options) + 2; if (cp->pe_data_len) @@ -720,7 +725,7 @@ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts) /* Set message type & copy members */ s->v4.type = (cp->af == AF_INET6 ? STYPE_F_INET6 : 0); s->v4.ver_size = htons(len & SVER_MASK); /* Version 0 */ - s->v4.flags = htonl(cp->flags & ~IP_VS_CONN_F_HASHED); + s->v4.flags = htonl(flags & ~IP_VS_CONN_F_HASHED); s->v4.state = htons(cp->state); s->v4.protocol = cp->protocol; s->v4.cport = cp->cport; @@ -744,7 +749,7 @@ void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts) s->v4.vaddr = cp->vaddr.ip; s->v4.daddr = cp->daddr.ip; } - if (cp->flags & IP_VS_CONN_F_SEQ_MASK) { + if (seq_mask) { *(p++) = IPVS_OPT_SEQ_DATA; *(p++) = sizeof(struct ip_vs_sync_conn_options); hton_seq(&cp->in_seq, (struct ip_vs_seq *)p); diff --git a/net/netfilter/ipvs/ip_vs_twos.c b/net/netfilter/ipvs/ip_vs_twos.c index dbb7f5fd4688..86186122a1f0 100644 --- a/net/netfilter/ipvs/ip_vs_twos.c +++ b/net/netfilter/ipvs/ip_vs_twos.c @@ -52,7 +52,7 @@ static struct ip_vs_dest *ip_vs_twos_schedule(struct ip_vs_service *svc, /* Generate a random weight between [0,sum of all weights) */ list_for_each_entry_rcu(dest, &svc->destinations, n_list) { - if (!(dest->flags & IP_VS_DEST_F_OVERLOAD)) { + if (!ip_vs_dest_is_overloaded(dest)) { weight = atomic_read(&dest->weight); if (weight > 0) { total_weight += weight; @@ -75,7 +75,7 @@ static struct ip_vs_dest *ip_vs_twos_schedule(struct ip_vs_service *svc, /* Pick two weighted servers */ list_for_each_entry_rcu(dest, &svc->destinations, n_list) { - if (dest->flags & IP_VS_DEST_F_OVERLOAD) + if (ip_vs_dest_is_overloaded(dest)) continue; weight = atomic_read(&dest->weight); diff --git a/net/netfilter/ipvs/ip_vs_wlc.c b/net/netfilter/ipvs/ip_vs_wlc.c index 9da445ca09a1..08e9e22f72bf 100644 --- a/net/netfilter/ipvs/ip_vs_wlc.c +++ b/net/netfilter/ipvs/ip_vs_wlc.c @@ -47,7 +47,7 @@ ip_vs_wlc_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, */ list_for_each_entry_rcu(dest, &svc->destinations, n_list) { - if (!(dest->flags & IP_VS_DEST_F_OVERLOAD) && + if (!ip_vs_dest_is_overloaded(dest) && atomic_read(&dest->weight) > 0) { least = dest; loh = ip_vs_dest_conn_overhead(least); @@ -62,7 +62,7 @@ ip_vs_wlc_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, */ nextstage: list_for_each_entry_continue_rcu(dest, &svc->destinations, n_list) { - if (dest->flags & IP_VS_DEST_F_OVERLOAD) + if (ip_vs_dest_is_overloaded(dest)) continue; doh = ip_vs_dest_conn_overhead(dest); if ((__s64)loh * atomic_read(&dest->weight) > diff --git a/net/netfilter/ipvs/ip_vs_wrr.c b/net/netfilter/ipvs/ip_vs_wrr.c index 2dcff1040da5..fad69bae5a22 100644 --- a/net/netfilter/ipvs/ip_vs_wrr.c +++ b/net/netfilter/ipvs/ip_vs_wrr.c @@ -176,7 +176,7 @@ ip_vs_wrr_schedule(struct ip_vs_service *svc, const struct sk_buff *skb, list_for_each_entry_continue_rcu(dest, &svc->destinations, n_list) { - if (!(dest->flags & IP_VS_DEST_F_OVERLOAD) && + if (!ip_vs_dest_is_overloaded(dest) && atomic_read(&dest->weight) >= mark->cw) goto found; if (dest == stop) diff --git a/net/netfilter/nf_conntrack_core.c b/net/netfilter/nf_conntrack_core.c index d0d9e5ea84a0..6cba999e8056 100644 --- a/net/netfilter/nf_conntrack_core.c +++ b/net/netfilter/nf_conntrack_core.c @@ -2507,6 +2507,11 @@ void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list) goto i_see_dead_people; } + /* must wait for current scan loop, worker also looks at + * struct nf_conntrack_net, which is about to be free'd. + */ + flush_work(&conntrack_gc_work.dwork.work); + list_for_each_entry(net, net_exit_list, exit_list) { warn_on_keymap_list_leak(net); nf_conntrack_ecache_pernet_fini(net); diff --git a/net/netfilter/nf_conntrack_seqadj.c b/net/netfilter/nf_conntrack_seqadj.c index 220216a4edc5..cc6a9037df6b 100644 --- a/net/netfilter/nf_conntrack_seqadj.c +++ b/net/netfilter/nf_conntrack_seqadj.c @@ -32,6 +32,23 @@ int nf_ct_seqadj_init(struct nf_conn *ct, enum ip_conntrack_info ctinfo, } EXPORT_SYMBOL_GPL(nf_ct_seqadj_init); +void nf_ct_seqadj_reset(struct nf_conn *ct, enum ip_conntrack_info ctinfo) +{ + struct nf_conn_seqadj *seqadj = nfct_seqadj(ct); + enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo); + struct nf_ct_seqadj *this_way; + + if (unlikely(!seqadj)) + return; + + spin_lock_bh(&ct->lock); + this_way = &seqadj->seq[dir]; + this_way->offset_before = 0; + this_way->offset_after = 0; + spin_unlock_bh(&ct->lock); +} +EXPORT_SYMBOL_GPL(nf_ct_seqadj_reset); + int nf_ct_seqadj_set(struct nf_conn *ct, enum ip_conntrack_info ctinfo, __be32 seq, s32 off) { diff --git a/net/netfilter/nf_flow_table_ip.c b/net/netfilter/nf_flow_table_ip.c index c8c29a9a1684..bb894c4f2b4a 100644 --- a/net/netfilter/nf_flow_table_ip.c +++ b/net/netfilter/nf_flow_table_ip.c @@ -170,14 +170,14 @@ static void nf_flow_tuple_encap(struct nf_flowtable_ctx *ctx, int i = 0; if (skb_vlan_tag_present(skb)) { - tuple->encap[i].id = skb_vlan_tag_get(skb); + tuple->encap[i].id = skb_vlan_tag_get_id(skb); tuple->encap[i].proto = skb->vlan_proto; i++; } switch (skb->protocol) { case htons(ETH_P_8021Q): veth = (struct vlan_ethhdr *)skb_mac_header(skb); - tuple->encap[i].id = ntohs(veth->h_vlan_TCI); + tuple->encap[i].id = ntohs(veth->h_vlan_TCI) & VLAN_VID_MASK; tuple->encap[i].proto = skb->protocol; offset += VLAN_HLEN; break; @@ -502,6 +502,7 @@ static int nf_flow_offload_forward(struct nf_flowtable_ctx *ctx, nf_flow_encap_pop(ctx, skb, tuplehash); thoff -= ctx->offset; + skb_set_transport_header(skb, thoff); iph = ip_hdr(skb); nf_flow_nat_ip(flow, skb, thoff, dir, iph); @@ -1097,6 +1098,7 @@ static int nf_flow_offload_ipv6_forward(struct nf_flowtable_ctx *ctx, flow_offload_refresh(flow_table, flow, false); nf_flow_encap_pop(ctx, 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_core.c b/net/netfilter/nf_nat_core.c index cc8e1e81006d..b214e0f0a5c8 100644 --- a/net/netfilter/nf_nat_core.c +++ b/net/netfilter/nf_nat_core.c @@ -1161,6 +1161,15 @@ nfnetlink_parse_nat_setup(struct nf_conn *ct, } #endif +static void bump_nat_hook_base_seq(struct net *net) +{ + unsigned int base_seq = READ_ONCE(net->nf.nat_hook_base_seq); + + while (++base_seq == 0) + ; + smp_store_release(&net->nf.nat_hook_base_seq, base_seq); +} + static struct nf_ct_helper_expectfn follow_master_nat = { .name = "nat-follow-master", .expectfn = nf_nat_follow_master, @@ -1245,6 +1254,7 @@ int nf_nat_register_fn(struct net *net, u8 pf, const struct nf_hook_ops *ops, nat_proto_net->nat_hook_ops = nat_ops; nat_proto_net->users++; + bump_nat_hook_base_seq(net); mutex_unlock(&nf_nat_proto_mutex); @@ -1299,6 +1309,7 @@ void nf_nat_unregister_fn(struct net *net, u8 pf, const struct nf_hook_ops *ops, goto unlock; priv = nat_ops[hooknum].priv; nf_hook_entries_delete_raw(&priv->entries, ops); + bump_nat_hook_base_seq(net); if (nat_proto_net->users == 0) { nf_unregister_net_hooks(net, nat_ops, ops_count); diff --git a/net/netfilter/nf_synproxy_core.c b/net/netfilter/nf_synproxy_core.c index acd360515972..37f88702980a 100644 --- a/net/netfilter/nf_synproxy_core.c +++ b/net/netfilter/nf_synproxy_core.c @@ -686,7 +686,7 @@ ipv4_synproxy_hook(void *priv, struct sk_buff *skb, * adjustments, they will get initialized once the connection is * reestablished. */ - nf_ct_seqadj_init(ct, ctinfo, 0); + nf_ct_seqadj_reset(ct, ctinfo); synproxy->tsoff = 0; this_cpu_inc(snet->stats->conn_reopened); fallthrough; @@ -1116,7 +1116,7 @@ ipv6_synproxy_hook(void *priv, struct sk_buff *skb, * adjustments, they will get initialized once the connection is * reestablished. */ - nf_ct_seqadj_init(ct, ctinfo, 0); + nf_ct_seqadj_reset(ct, ctinfo); synproxy->tsoff = 0; this_cpu_inc(snet->stats->conn_reopened); fallthrough; diff --git a/net/netfilter/nfnetlink_hook.c b/net/netfilter/nfnetlink_hook.c index 95005e9a6066..b05fd79397c5 100644 --- a/net/netfilter/nfnetlink_hook.c +++ b/net/netfilter/nfnetlink_hook.c @@ -54,7 +54,6 @@ static int nf_netlink_dump_start_rcu(struct sock *nlsk, struct sk_buff *skb, struct nfnl_dump_hook_data { char devname[IFNAMSIZ]; - unsigned long headv; u8 hook; }; @@ -338,27 +337,47 @@ nfnl_hook_entries_head(u8 pf, unsigned int hook, struct net *net, const char *de } static int nfnl_hook_dump_nat(struct sk_buff *nlskb, - const struct nfnl_dump_hook_data *ctx, - const struct nf_hook_ops *ops, - int family, unsigned int seq) + struct netlink_callback *cb, + const struct nf_hook_ops *ops, int family) { struct nf_nat_lookup_hook_priv *priv = ops->priv; - struct nf_hook_entries *e = rcu_dereference(priv->entries); + struct nfnl_dump_hook_data *ctx = cb->data; + struct net *net = sock_net(nlskb->sk); struct nf_hook_ops **nat_ops; - int i, err; + unsigned int i = cb->args[1]; + struct nf_hook_entries *e; + unsigned int base_seq; + int err = 0; + base_seq = smp_load_acquire(&net->nf.nat_hook_base_seq); + + e = rcu_dereference(priv->entries); if (!e) - return 0; + goto out; nat_ops = nf_hook_entries_get_hook_ops(e); - for (i = 0; i < e->num_hook_entries; i++) { - err = nfnl_hook_dump_one(nlskb, ctx, nat_ops[i], - ops->priority, family, seq); + for (; i < e->num_hook_entries; i++) { + err = nfnl_hook_dump_one(nlskb, ctx, + READ_ONCE(nat_ops[i]), + ops->priority, family, + cb->nlh->nlmsg_seq); if (err) - return err; + break; + } - return 0; +out: + if (!err) + i = 0; + cb->args[1] = i; + + if (cb->args[2] && base_seq != cb->args[2]) { + cb->seq++; + err = -EINTR; + } + cb->args[2] = base_seq; + + return err; } static int nfnl_hook_dump(struct sk_buff *nlskb, @@ -373,35 +392,31 @@ static int nfnl_hook_dump(struct sk_buff *nlskb, unsigned int i = cb->args[0]; rcu_read_lock(); + cb->seq = smp_load_acquire(&net->nf.hook_base_seq); e = nfnl_hook_entries_head(family, ctx->hook, net, ctx->devname); - if (!e) + if (!e || IS_ERR(e)) goto done; - if (IS_ERR(e)) { - cb->seq++; - goto done; - } - - if ((unsigned long)e != ctx->headv || i >= e->num_hook_entries) - cb->seq++; - ops = nf_hook_entries_get_hook_ops(e); for (; i < e->num_hook_entries; i++) { - if (ops[i]->hook_ops_type == NF_HOOK_OP_NAT) - err = nfnl_hook_dump_nat(nlskb, ctx, ops[i], family, - cb->nlh->nlmsg_seq); - else - err = nfnl_hook_dump_one(nlskb, ctx, ops[i], - ops[i]->priority, family, + const struct nf_hook_ops *cur = READ_ONCE(ops[i]); + + if (cur->hook_ops_type == NF_HOOK_OP_NAT) { + err = nfnl_hook_dump_nat(nlskb, cb, cur, family); + } else { + err = nfnl_hook_dump_one(nlskb, ctx, cur, + cur->priority, family, cb->nlh->nlmsg_seq); + } if (err) break; } done: - nl_dump_check_consistent(cb, nlmsg_hdr(nlskb)); + if (nlskb->len > 0) + nl_dump_check_consistent(cb, nlmsg_hdr(nlskb)); rcu_read_unlock(); cb->args[0] = i; return nlskb->len; @@ -442,10 +457,7 @@ static int nfnl_hook_dump_start(struct netlink_callback *cb) return -ENOMEM; strscpy(ctx->devname, name, sizeof(ctx->devname)); - ctx->headv = (unsigned long)head; ctx->hook = hooknum; - - cb->seq = 1; cb->data = ctx; return 0; diff --git a/net/netfilter/nft_compat.c b/net/netfilter/nft_compat.c index 63864b928259..88ddaf47f587 100644 --- a/net/netfilter/nft_compat.c +++ b/net/netfilter/nft_compat.c @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -45,6 +46,20 @@ static int nft_compat_chain_validate_dependency(const struct nft_ctx *ctx, type = NFT_CHAIN_T_NAT; if (basechain->type->type != type) return -EINVAL; + } else if (strcmp(tablename, "raw") == 0) { + /* iptables-nft emulates the legacy raw table, which only + * ever has prerouting/output chains at this exact priority. + */ + if (ctx->family != NFPROTO_IPV4 && + ctx->family != NFPROTO_IPV6) + return -EINVAL; + + if (basechain->ops.hooknum != NF_INET_PRE_ROUTING && + basechain->ops.hooknum != NF_INET_LOCAL_OUT) + return -EINVAL; + + if (basechain->ops.priority != NF_IP_PRI_RAW) + return -EINVAL; } return 0; diff --git a/net/netfilter/nft_set_rbtree.c b/net/netfilter/nft_set_rbtree.c index 12431b55752f..fbe1750f1ca2 100644 --- a/net/netfilter/nft_set_rbtree.c +++ b/net/netfilter/nft_set_rbtree.c @@ -1091,7 +1091,8 @@ static void nft_rbtree_commit(struct nft_set *set) * representation. Use next start element to complete this * interval. */ - if (nft_rbtree_interval_start(rbe) && + if (nft_set_is_anonymous(set) && + nft_rbtree_interval_start(rbe) && nft_rbtree_interval_start(prev_rbe) && priv->array_next->intervals[num_intervals].from) priv->array_next->intervals[num_intervals++].to = &prev_rbe->ext; diff --git a/net/netfilter/xt_dccp.c b/net/netfilter/xt_dccp.c index 3db81e041af9..23a4e3e8df7d 100644 --- a/net/netfilter/xt_dccp.c +++ b/net/netfilter/xt_dccp.c @@ -62,7 +62,7 @@ dccp_find_option(u_int8_t option, return true; } - if (op[i] < 2 || i == optlen - 1) + if (op[i] <= DCCPO_MAX_RESERVED || i == optlen - 1) i++; else i += op[i + 1] ? : 1; diff --git a/net/netlabel/netlabel_kapi.c b/net/netlabel/netlabel_kapi.c index 3583fa63dd01..c0eddb6afef3 100644 --- a/net/netlabel/netlabel_kapi.c +++ b/net/netlabel/netlabel_kapi.c @@ -1045,18 +1045,18 @@ int netlbl_sock_setattr(struct sock *sk, * ensuring that @sk is locked. * */ -void netlbl_sock_delattr(struct sock *sk) +int netlbl_sock_delattr(struct sock *sk) { switch (sk->sk_family) { case AF_INET: - cipso_v4_sock_delattr(sk); - break; + return cipso_v4_sock_delattr(sk); #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: calipso_sock_delattr(sk); break; #endif /* IPv6 */ } + return 0; } /** @@ -1156,8 +1156,7 @@ int netlbl_conn_setattr(struct sock *sk, case NETLBL_NLTYPE_UNLABELED: /* just delete the protocols we support for right now * but we could remove other protocols if needed */ - netlbl_sock_delattr(sk); - ret_val = 0; + ret_val = netlbl_sock_delattr(sk); break; default: ret_val = -ENOENT; @@ -1185,8 +1184,7 @@ int netlbl_conn_setattr(struct sock *sk, case NETLBL_NLTYPE_UNLABELED: /* just delete the protocols we support for right now * but we could remove other protocols if needed */ - netlbl_sock_delattr(sk); - ret_val = 0; + ret_val = netlbl_sock_delattr(sk); break; default: ret_val = -ENOENT; @@ -1234,8 +1232,7 @@ int netlbl_req_setattr(struct request_sock *req, entry->cipso, secattr); break; case NETLBL_NLTYPE_UNLABELED: - netlbl_req_delattr(req); - ret_val = 0; + ret_val = netlbl_req_delattr(req); break; default: ret_val = -ENOENT; @@ -1255,8 +1252,7 @@ int netlbl_req_setattr(struct request_sock *req, entry->calipso, secattr); break; case NETLBL_NLTYPE_UNLABELED: - netlbl_req_delattr(req); - ret_val = 0; + ret_val = netlbl_req_delattr(req); break; default: ret_val = -ENOENT; @@ -1280,18 +1276,18 @@ int netlbl_req_setattr(struct request_sock *req, * Remove all the NetLabel labeling from @req. * */ -void netlbl_req_delattr(struct request_sock *req) +int netlbl_req_delattr(struct request_sock *req) { switch (req->rsk_ops->family) { case AF_INET: - cipso_v4_req_delattr(req); - break; + return cipso_v4_req_delattr(req); #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: calipso_req_delattr(req); break; #endif /* IPv6 */ } + return 0; } /** diff --git a/net/netlink/af_netlink.c b/net/netlink/af_netlink.c index 3029894edad1..510fb5ebf9ff 100644 --- a/net/netlink/af_netlink.c +++ b/net/netlink/af_netlink.c @@ -2160,8 +2160,12 @@ void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group) struct netlink_table *tbl = &nl_table[ksk->sk_protocol]; struct hlist_node *tmp; - sk_for_each_bound_safe(sk, tmp, &tbl->mc_list) + sk_for_each_bound_safe(sk, tmp, &tbl->mc_list) { + /* bitmap predates the group, can't be a member */ + if (group - 1 >= nlk_sk(sk)->ngroups) + continue; netlink_update_socket_mc(nlk_sk(sk), group, 0); + } } struct nlmsghdr * @@ -2321,9 +2325,13 @@ static int netlink_dump(struct sock *sk, bool lock_taken) if (!skb) goto errout_skb; + /* Check the limit before charging the skb: netlink_recvmsg() continues + * the dump at or below half of sk_rcvbuf, and the skb must be queued + * then. Keep sk_rmem_alloc at or below INT_MAX. + */ rcvbuf = READ_ONCE(sk->sk_rcvbuf); rmem = atomic_add_return(skb->truesize, &sk->sk_rmem_alloc); - if (rmem != skb->truesize && rmem >= rcvbuf) { + if (rmem - skb->truesize >= rcvbuf || rmem > INT_MAX) { atomic_sub(skb->truesize, &sk->sk_rmem_alloc); goto errout_skb; } diff --git a/net/openvswitch/actions.c b/net/openvswitch/actions.c index 27152bca8a8c..12e339cbf791 100644 --- a/net/openvswitch/actions.c +++ b/net/openvswitch/actions.c @@ -595,6 +595,9 @@ static int set_udp(struct sk_buff *skb, struct sw_flow_key *flow_key, __be16 src, dst; int err; + if (flow_key->ip.frag == OVS_FRAG_TYPE_LATER) + return 0; + err = skb_ensure_writable(skb, skb_transport_offset(skb) + sizeof(struct udphdr)); if (unlikely(err)) @@ -638,6 +641,9 @@ static int set_tcp(struct sk_buff *skb, struct sw_flow_key *flow_key, __be16 src, dst; int err; + if (flow_key->ip.frag == OVS_FRAG_TYPE_LATER) + return 0; + err = skb_ensure_writable(skb, skb_transport_offset(skb) + sizeof(struct tcphdr)); if (unlikely(err)) @@ -668,6 +674,9 @@ static int set_sctp(struct sk_buff *skb, struct sw_flow_key *flow_key, __le32 old_correct_csum, new_csum, old_csum; int err; + if (flow_key->ip.frag != OVS_FRAG_TYPE_NONE) + return -EINVAL; + err = skb_ensure_writable(skb, sctphoff + sizeof(struct sctphdr)); if (unlikely(err)) return err; diff --git a/net/openvswitch/vport-internal_dev.c b/net/openvswitch/vport-internal_dev.c index 125d310871e9..06a363df8155 100644 --- a/net/openvswitch/vport-internal_dev.c +++ b/net/openvswitch/vport-internal_dev.c @@ -186,6 +186,7 @@ static void internal_dev_destroy(struct vport *vport) static int internal_dev_recv(struct sk_buff *skb) { struct net_device *netdev = skb->dev; + enum skb_drop_reason reason; if (unlikely(!(netdev->flags & IFF_UP))) { kfree_skb(skb); @@ -197,7 +198,12 @@ static int internal_dev_recv(struct sk_buff *skb) nf_reset_ct(skb); skb->pkt_type = PACKET_HOST; - skb->protocol = eth_type_trans(skb, netdev); + reason = eth_type_trans_careful(skb, netdev); + if (unlikely(reason)) { + dev_core_stats_rx_dropped_inc(netdev); + kfree_skb_reason(skb, reason); + return NETDEV_TX_OK; + } skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN); dev_sw_netstats_rx_add(netdev, skb->len); diff --git a/net/psp/psp_sock.c b/net/psp/psp_sock.c index e9b53eedf8db..70fa137bd811 100644 --- a/net/psp/psp_sock.c +++ b/net/psp/psp_sock.c @@ -139,6 +139,12 @@ int psp_sock_assoc_set_rx(struct sock *sk, struct psp_assoc *pas, lock_sock(sk); + if (sk->sk_state != TCP_ESTABLISHED) { + NL_SET_ERR_MSG(extack, "Socket must be in established state"); + err = -ENOTCONN; + goto exit_unlock; + } + if (psp_sk_assoc(sk)) { NL_SET_ERR_MSG(extack, "Socket already has PSP state"); err = -EBUSY; @@ -188,6 +194,12 @@ int psp_sock_assoc_set_tx(struct sock *sk, struct psp_dev *psd, lock_sock(sk); + if (sk->sk_state != TCP_ESTABLISHED) { + NL_SET_ERR_MSG(extack, "Socket must be in established state"); + err = -ENOTCONN; + goto exit_unlock; + } + pas = psp_sk_assoc(sk); if (!pas) { NL_SET_ERR_MSG(extack, "Socket has no Rx key"); diff --git a/net/rds/af_rds.c b/net/rds/af_rds.c index d5defe9172e3..fb6b8ddb2d11 100644 --- a/net/rds/af_rds.c +++ b/net/rds/af_rds.c @@ -136,8 +136,7 @@ static int rds_getname(struct socket *sock, struct sockaddr *uaddr, sin6->sin6_port = rs->rs_conn_port; sin6->sin6_addr = rs->rs_conn_addr; sin6->sin6_flowinfo = 0; - /* scope_id is the same as in the bound address. */ - sin6->sin6_scope_id = rs->rs_bound_scope_id; + sin6->sin6_scope_id = rs->rs_conn_scope_id; uaddr_len = sizeof(*sin6); } } else { @@ -572,6 +571,7 @@ static int rds_connect(struct socket *sock, struct sockaddr_unsized *uaddr, } ipv6_addr_set_v4mapped(sin->sin_addr.s_addr, &rs->rs_conn_addr); rs->rs_conn_port = sin->sin_port; + rs->rs_conn_scope_id = 0; break; #if IS_ENABLED(CONFIG_IPV6) @@ -616,11 +616,14 @@ static int rds_connect(struct socket *sock, struct sockaddr_unsized *uaddr, ret = -EINVAL; break; } - /* Remember the connected address scope ID. It will - * be checked against the binding local address when - * the socket is bound. + /* Remember the connected address scope ID. It is + * checked against the binding local address when + * the socket is bound, and gives a send without a + * destination its scope. */ - rs->rs_bound_scope_id = sin6->sin6_scope_id; + rs->rs_conn_scope_id = sin6->sin6_scope_id; + } else { + rs->rs_conn_scope_id = 0; } rs->rs_conn_addr = sin6->sin6_addr; rs->rs_conn_port = sin6->sin6_port; @@ -922,8 +925,11 @@ static void rds6_sock_info(struct socket *sock, unsigned int len, } #endif +static bool rds_initialized; + static void rds_exit(void) { + rds_initialized = false; sock_unregister(rds_family_ops.family); proto_unregister(&rds_proto); rds_conn_exit(); @@ -944,6 +950,16 @@ module_exit(rds_exit); u32 rds_gen_num; +/* When RDS is built in, a failed rds_init() does not stop the rds_rdma + * and rds_tcp initcalls from running against a core that has already + * been torn down (rds_wq in particular). Let them bail out early. + */ +bool rds_is_initialized(void) +{ + return rds_initialized; +} +EXPORT_SYMBOL_GPL(rds_is_initialized); + static int __init rds_init(void) { int ret; @@ -980,6 +996,7 @@ static int __init rds_init(void) rds_info_register_func(RDS6_INFO_SOCKETS, rds6_sock_info); rds_info_register_func(RDS6_INFO_RECV_MESSAGES, rds6_sock_inc_info); #endif + rds_initialized = true; goto out; diff --git a/net/rds/bind.c b/net/rds/bind.c index f800d920d969..3ac59cd512a2 100644 --- a/net/rds/bind.c +++ b/net/rds/bind.c @@ -233,8 +233,8 @@ int rds_bind(struct socket *sock, struct sockaddr_unsized *uaddr, int addr_len) * non-link local address (scope_id is 0). */ if (!ipv6_addr_any(&rs->rs_conn_addr) && scope_id && - rs->rs_bound_scope_id && - scope_id != rs->rs_bound_scope_id) { + rs->rs_conn_scope_id && + scope_id != rs->rs_conn_scope_id) { ret = -EINVAL; goto out; } diff --git a/net/rds/ib_sysctl.c b/net/rds/ib_sysctl.c index 2af678e71e3c..bc97a3eecad6 100644 --- a/net/rds/ib_sysctl.c +++ b/net/rds/ib_sysctl.c @@ -114,7 +114,7 @@ void rds_ib_sysctl_exit(void) int rds_ib_sysctl_init(void) { rds_ib_sysctl_hdr = register_net_sysctl(&init_net, "net/rds/ib", rds_ib_sysctl_table); - if (!rds_ib_sysctl_hdr) + if (!rds_ib_sysctl_hdr && IS_ENABLED(CONFIG_SYSCTL)) return -ENOMEM; return 0; } diff --git a/net/rds/rdma_transport.c b/net/rds/rdma_transport.c index 7be38be1228e..cc6a7d29791a 100644 --- a/net/rds/rdma_transport.c +++ b/net/rds/rdma_transport.c @@ -325,6 +325,9 @@ static int __init rds_rdma_init(void) { int ret; + if (!rds_is_initialized()) + return -ENODEV; + ret = rds_ib_init(); if (ret) goto out; diff --git a/net/rds/rds.h b/net/rds/rds.h index 2db49573dacd..e3937c1ff3a1 100644 --- a/net/rds/rds.h +++ b/net/rds/rds.h @@ -646,6 +646,8 @@ struct rds_sock { struct in6_addr rs_conn_addr; #define rs_conn_addr_v4 rs_conn_addr.s6_addr32[3] __be16 rs_conn_port; + /* scope of rs_conn_addr when it is link-local, 0 otherwise */ + __u32 rs_conn_scope_id; struct rds_transport *rs_transport; /* @@ -1040,6 +1042,7 @@ extern unsigned int rds_sysctl_trace_level; int rds_threads_init(void); void rds_threads_exit(void); extern struct workqueue_struct *rds_wq; +bool rds_is_initialized(void); void rds_queue_reconnect(struct rds_conn_path *cp); void rds_connect_worker(struct work_struct *); void rds_shutdown_worker(struct work_struct *); diff --git a/net/rds/recv.c b/net/rds/recv.c index 93ee4546ae36..00ab60f2d996 100644 --- a/net/rds/recv.c +++ b/net/rds/recv.c @@ -791,7 +791,16 @@ int rds_recvmsg(struct socket *sock, struct msghdr *msg, size_t size, sin6->sin6_port = inc->i_hdr.h_sport; sin6->sin6_addr = inc->i_saddr; sin6->sin6_flowinfo = 0; - sin6->sin6_scope_id = rs->rs_bound_scope_id; + /* A link-local sender is reported with the + * interface recorded on its connection (the + * accepting socket's device for TCP, the one + * resolved for the local address on IB); any + * other sender has no scope. + */ + sin6->sin6_scope_id = + (ipv6_addr_type(&inc->i_saddr) & + IPV6_ADDR_LINKLOCAL) ? + inc->i_conn->c_dev_if : 0; msg->msg_namelen = sizeof(*sin6); } } diff --git a/net/rds/send.c b/net/rds/send.c index 1afa981e5c06..f38967f65af1 100644 --- a/net/rds/send.c +++ b/net/rds/send.c @@ -1256,7 +1256,11 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len) lock_sock(sk); daddr = rs->rs_conn_addr; dport = rs->rs_conn_port; - scope_id = rs->rs_bound_scope_id; + /* The connected peer's scope for a link-local peer, else + * the bound scope, as an explicit send to that peer would + * compute below. + */ + scope_id = rs->rs_conn_scope_id ?: rs->rs_bound_scope_id; release_sock(sk); } @@ -1342,7 +1346,8 @@ int rds_sendmsg(struct socket *sock, struct msghdr *msg, size_t payload_len) /* rds_conn_create has a spinlock that runs with IRQ off. * Caching the conn in the socket helps a lot. */ if (rs->rs_conn && ipv6_addr_equal(&rs->rs_conn->c_faddr, &daddr) && - rs->rs_tos == rs->rs_conn->c_tos) { + rs->rs_tos == rs->rs_conn->c_tos && + rs->rs_conn->c_dev_if == scope_id) { conn = rs->rs_conn; } else { conn = rds_conn_create_outgoing(sock_net(sock->sk), diff --git a/net/rds/sysctl.c b/net/rds/sysctl.c index 025f518a4349..968d6279bbd3 100644 --- a/net/rds/sysctl.c +++ b/net/rds/sysctl.c @@ -103,7 +103,7 @@ int rds_sysctl_init(void) rds_sysctl_reg_table = register_net_sysctl(&init_net, "net/rds", rds_sysctl_rds_table); - if (!rds_sysctl_reg_table) + if (!rds_sysctl_reg_table && IS_ENABLED(CONFIG_SYSCTL)) return -ENOMEM; return 0; } diff --git a/net/rds/tcp.c b/net/rds/tcp.c index 774a71f88d37..c1ad37505417 100644 --- a/net/rds/tcp.c +++ b/net/rds/tcp.c @@ -637,7 +637,7 @@ static __net_init int rds_tcp_init_net(struct net *net) tbl[RDS_TCP_RCVBUF].data = &rtn->rcvbuf_size; rtn->rds_tcp_sysctl = register_net_sysctl_sz(net, "net/rds/tcp", tbl, ARRAY_SIZE(rds_tcp_sysctl_table)); - if (!rtn->rds_tcp_sysctl) { + if (!rtn->rds_tcp_sysctl && IS_ENABLED(CONFIG_SYSCTL)) { pr_warn("could not register sysctl\n"); err = -ENOMEM; goto fail; @@ -815,6 +815,9 @@ static int __init rds_tcp_init(void) { int ret; + if (!rds_is_initialized()) + return -ENODEV; + rds_tcp_conn_slab = KMEM_CACHE(rds_tcp_connection, 0); if (!rds_tcp_conn_slab) { ret = -ENOMEM; diff --git a/net/rxrpc/rxperf.c b/net/rxrpc/rxperf.c index 6a815a4bb314..0bc3de061b93 100644 --- a/net/rxrpc/rxperf.c +++ b/net/rxrpc/rxperf.c @@ -495,18 +495,6 @@ static int rxperf_deliver_request(struct rxperf_call *call) call->unmarshal++; fallthrough; case 2: - ret = rxperf_extract_data(call, true); - if (ret < 0) - return ret; - - /* Deal with the terminal magic cookie. */ - call->iov_len = 4; - call->kvec[0].iov_len = call->iov_len; - call->kvec[0].iov_base = call->tmp; - iov_iter_kvec(&call->iter, READ, call->kvec, 1, call->iov_len); - call->unmarshal++; - fallthrough; - case 3: ret = rxperf_extract_data(call, false); if (ret < 0) return ret; @@ -539,7 +527,7 @@ static int rxperf_process_call(struct rxperf_call *call) ret = rxrpc_kernel_send_data(rxperf_socket, call->rxcall, &msg, rxperf_notify_end_reply_tx); if (ret < 0) - return ret; + goto send_error; reply_len -= len; } @@ -550,10 +538,11 @@ static int rxperf_process_call(struct rxperf_call *call) msg.msg_flags = 0; ret = rxrpc_kernel_send_data(rxperf_socket, call->rxcall, &msg, rxperf_notify_end_reply_tx); - if (ret == -ENOMEM) - rxrpc_kernel_abort_call(rxperf_socket, call->rxcall, - RXGEN_SS_MARSHAL, -ENOMEM, - rxperf_abort_oom); + if (ret == 0) + return 0; +send_error: + rxrpc_kernel_abort_call(rxperf_socket, call->rxcall, RXGEN_SS_MARSHAL, + ret, rxperf_abort_send_error); return ret; } @@ -605,7 +594,7 @@ static int rxperf_add_yfs_rxgk_key(struct key *keyring, u32 enctype) for (int i = 0; i < krb5->key_len; i++) key[i] = i; - sprintf(name, "%u:6:1:%u", RX_PERF_SERVICE, enctype); + sprintf(name, "%u:6:0:%u", RX_PERF_SERVICE, enctype); kref = key_create_or_update(make_key_ref(keyring, true), "rxrpc_s", name, diff --git a/net/rxrpc/sendmsg.c b/net/rxrpc/sendmsg.c index 393a2dcfda07..312be27ca75b 100644 --- a/net/rxrpc/sendmsg.c +++ b/net/rxrpc/sendmsg.c @@ -374,9 +374,9 @@ static int rxrpc_send_data(struct rxrpc_sock *rx, ret = -EMSGSIZE; if (call->tx_total_len != -1) { - if (len - copied > call->tx_total_len) + if (len > call->tx_total_len) goto maybe_error; - if (!more && len - copied != call->tx_total_len) + if (!more && len != call->tx_total_len) goto maybe_error; } @@ -402,7 +402,7 @@ static int rxrpc_send_data(struct rxrpc_sock *rx, * the security header is going to be in the padded * region (enc blocksize), but the trailer is not. */ - remain = more ? INT_MAX : msg_data_left(msg); + remain = more ? INT_MAX : len; txb = call->conn->security->alloc_txbuf(call, remain, sk->sk_allocation); if (!txb) { ret = -ENOMEM; @@ -416,8 +416,8 @@ static int rxrpc_send_data(struct rxrpc_sock *rx, _debug("append"); /* append next segment of data to the current buffer */ - if (msg_data_left(msg) > 0) { - size_t copy = umin(txb->space, msg_data_left(msg)); + if (len > 0) { + size_t copy = min3(txb->space, len, msg_data_left(msg)); _debug("add %zu", copy); if (!copy_from_iter_full(txb->data + txb->offset, @@ -428,6 +428,7 @@ static int rxrpc_send_data(struct rxrpc_sock *rx, txb->len += copy; txb->offset += copy; copied += copy; + len -= copy; if (call->tx_total_len != -1) call->tx_total_len -= copy; } @@ -439,8 +440,8 @@ static int rxrpc_send_data(struct rxrpc_sock *rx, /* add the packet to the send queue if it's now full */ if (!txb->space || - (msg_data_left(msg) == 0 && !more)) { - if (msg_data_left(msg) == 0 && !more) + (len == 0 && !more)) { + if (len == 0 && !more) txb->flags |= RXRPC_LAST_PACKET; ret = call->security->secure_packet(call, txb); @@ -449,7 +450,7 @@ static int rxrpc_send_data(struct rxrpc_sock *rx, rxrpc_queue_packet(rx, call, txb, notify_end_tx); call->tx_pending = NULL; } - } while (msg_data_left(msg) > 0); + } while (len > 0 && msg_data_left(msg) > 0); success: ret = copied; diff --git a/net/sched/act_api.c b/net/sched/act_api.c index 9eb1dec14cb1..3918e277464f 100644 --- a/net/sched/act_api.c +++ b/net/sched/act_api.c @@ -1544,6 +1544,9 @@ int tcf_action_init(struct net *net, struct tcf_proto *tp, struct nlattr *nla, err = -EINVAL; goto err; } + /* Other filters share an existing action */ + if (init_res[i - 1] != ACT_P_CREATED) + continue; if (skip_sw) act->tcfa_flags |= TCA_ACT_FLAGS_SKIP_SW; if (skip_hw) @@ -2025,7 +2028,7 @@ static int tca_action_gd(struct net *net, struct nlattr *nla, struct nlmsghdr *n, u32 portid, int event, struct netlink_ext_ack *extack) { - int i, ret; + int i, j, ret; struct nlattr *tb[TCA_ACT_MAX_PRIO + 1]; struct tc_action *act; size_t attr_size = 0; @@ -2050,6 +2053,25 @@ tca_action_gd(struct net *net, struct nlattr *nla, struct nlmsghdr *n, ret = PTR_ERR(act); goto err; } + + /* A delete consumes two references per slot (tcf_action_put() + * and tcf_idr_delete_index()) but each entry takes one, so a + * repeated action would hit zero mid-walk. GET balances its + * own references and keeps accepting duplicates. + */ + if (event == RTM_DELACTION) { + for (j = 0; j < i - 1; j++) { + if (actions[j] != act) + continue; + + tcf_action_put(act); + NL_SET_ERR_MSG(extack, + "Duplicate TC action in a delete batch"); + ret = -EINVAL; + goto err; + } + } + attr_size += tcf_action_fill_size(act); actions[i - 1] = act; } diff --git a/net/sched/sch_etf.c b/net/sched/sch_etf.c index ada87a81da6a..aaafcf640bc7 100644 --- a/net/sched/sch_etf.c +++ b/net/sched/sch_etf.c @@ -147,6 +147,7 @@ static void report_sock_error(struct sk_buff *skb, u32 err, u8 code) return; serr = SKB_EXT_ERR(clone); + memset(serr, 0, sizeof(*serr)); serr->ee.ee_errno = err; serr->ee.ee_origin = SO_EE_ORIGIN_TXTIME; serr->ee.ee_type = 0; diff --git a/net/sched/sch_gred.c b/net/sched/sch_gred.c index f04f425c6c44..f3d9a7252949 100644 --- a/net/sched/sch_gred.c +++ b/net/sched/sch_gred.c @@ -442,13 +442,6 @@ static int gred_change_table_def(struct Qdisc *sch, struct nlattr *dps, red_flags_changed = table->red_flags != sopt->flags; table->red_flags = sopt->flags; - /* - * Every entry point to GRED is synchronized with the above code - * and the DP is checked against DPs, i.e. shadowed VQs can no - * longer be found so we can unlock right here. - */ - sch_tree_unlock(sch); - if (sopt->grio) { gred_enable_rio_mode(table); gred_disable_wred_mode(table); @@ -474,6 +467,15 @@ static int gred_change_table_def(struct Qdisc *sch, struct nlattr *dps, } } + /* + * Keep the lock until every field the datapath reads (the + * RIO/WRED mode bits, the per-VQ red_flags and the tab[] slots) + * has been updated: gred_enqueue()/gred_dequeue() read them under + * the same lock, so publishing them after the unlock races with + * the enqueue path. + */ + sch_tree_unlock(sch); + gred_offload(sch, TC_GRED_REPLACE); return 0; } diff --git a/net/sched/sch_taprio.c b/net/sched/sch_taprio.c index 0eb0803047a1..324c02fa2345 100644 --- a/net/sched/sch_taprio.c +++ b/net/sched/sch_taprio.c @@ -2577,7 +2577,11 @@ static int __init taprio_module_init(void) if (err) return err; - return register_qdisc(&taprio_qdisc_ops); + err = register_qdisc(&taprio_qdisc_ops); + if (err) + unregister_netdevice_notifier(&taprio_device_notifier); + + return err; } static void __exit taprio_module_exit(void) diff --git a/net/sctp/ipv6.c b/net/sctp/ipv6.c index ef26878f1282..97390569c4bd 100644 --- a/net/sctp/ipv6.c +++ b/net/sctp/ipv6.c @@ -725,7 +725,8 @@ static int sctp_v6_available(union sctp_addr *addr, struct sctp_sock *sp) * SCTP. * * Output: - * Return 0 - If the address is a non-unicast or an illegal address. + * Return 0 - If the address is a non-unicast or an illegal address, + * or a non-v4-mapped address on a non-PF_INET6 socket. * Return 1 - If the address is a unicast. */ static int sctp_v6_addr_valid(union sctp_addr *addr, @@ -749,6 +750,9 @@ static int sctp_v6_addr_valid(union sctp_addr *addr, if (!(ret & IPV6_ADDR_UNICAST)) return 0; + if (sp && sctp_opt2sk(sp)->sk_family != PF_INET6) + return 0; + return 1; } diff --git a/net/sctp/sm_make_chunk.c b/net/sctp/sm_make_chunk.c index 0896ec6c75ce..90de27284251 100644 --- a/net/sctp/sm_make_chunk.c +++ b/net/sctp/sm_make_chunk.c @@ -1740,7 +1740,9 @@ struct sctp_association *sctp_unpack_cookie( struct sctp_cookie *bear_cookie; struct sctp_chunkhdr *ch; unsigned int len, chlen; + union sctp_addr paddr; enum sctp_scope scope; + struct sctp_af *af; ktime_t kt; /* Header size is static data prior to the actual cookie, including @@ -1849,6 +1851,11 @@ struct sctp_association *sctp_unpack_cookie( goto fail; } + paddr = bear_cookie->peer_addr; + af = sctp_get_af_specific(paddr.sa.sa_family); + if (!af || !af->addr_valid(&paddr, sctp_sk(ep->base.sk), NULL)) + goto malformed; + /* Make a new base association. */ scope = sctp_scope(sctp_source(chunk)); retval = sctp_association_new(ep, ep->base.sk, scope, gfp); @@ -1865,6 +1872,7 @@ struct sctp_association *sctp_unpack_cookie( /* Populate the association from the cookie. */ memcpy(&retval->c, bear_cookie, sizeof(*bear_cookie)); + retval->c.peer_addr = paddr; if (sctp_assoc_set_bind_addr_from_cookie(retval, bear_cookie, GFP_ATOMIC) < 0) { @@ -2389,8 +2397,8 @@ int sctp_process_init(struct sctp_association *asoc, struct sctp_chunk *chunk, (param.p->type == SCTP_PARAM_IPV4_ADDRESS || param.p->type == SCTP_PARAM_IPV6_ADDRESS)) { af = sctp_get_af_specific(param_type2af(param.p->type)); - if (!af->from_addr_param(&addr, param.addr, - chunk->sctp_hdr->source, 0)) + if (!af || !af->from_addr_param(&addr, param.addr, + chunk->sctp_hdr->source, 0)) continue; if (sctp_cmp_addr_exact(sctp_source(chunk), &addr)) src_match = 1; @@ -2562,17 +2570,11 @@ static int sctp_process_param(struct sctp_association *asoc, */ switch (param.p->type) { case SCTP_PARAM_IPV6_ADDRESS: - if (PF_INET6 != asoc->base.sk->sk_family) - break; - goto do_addr_param; - case SCTP_PARAM_IPV4_ADDRESS: - /* v4 addresses are not allowed on v6-only socket */ - if (ipv6_only_sock(asoc->base.sk)) - break; -do_addr_param: af = sctp_get_af_specific(param_type2af(param.p->type)); - if (!af->from_addr_param(&addr, param.addr, htons(asoc->peer.port), 0)) + if (!af || !af->from_addr_param(&addr, param.addr, + htons(asoc->peer.port), 0) || + !af->addr_valid(&addr, sctp_sk(asoc->base.sk), NULL)) break; scope = sctp_scope(peer_addr); if (sctp_in_scope(net, &addr, scope)) diff --git a/net/sctp/sm_statefuns.c b/net/sctp/sm_statefuns.c index 8dc65498763c..b2f609f177fb 100644 --- a/net/sctp/sm_statefuns.c +++ b/net/sctp/sm_statefuns.c @@ -814,7 +814,7 @@ enum sctp_disposition sctp_sf_do_5_1D_ce(struct net *net, * effects--it is safe to run them here. */ if (!sctp_process_init(new_asoc, chunk, - &chunk->subh.cookie_hdr->c.peer_addr, + &new_asoc->c.peer_addr, peer_init, GFP_ATOMIC)) goto nomem_init; diff --git a/net/smc/smc_pnet.c b/net/smc/smc_pnet.c index ff9c9c35cc2f..61ef1d697eee 100644 --- a/net/smc/smc_pnet.c +++ b/net/smc/smc_pnet.c @@ -30,7 +30,8 @@ #include "smc_core.h" static struct net_device *__pnet_find_base_ndev(struct net_device *ndev); -static struct net_device *pnet_find_base_ndev(struct net_device *ndev); +static struct net_device *pnet_find_base_ndev(struct net_device *ndev, + netdevice_tracker *tracker); static const struct nla_policy smc_pnet_policy[SMC_PNETID_MAX + 1] = { [SMC_PNETID_NAME] = { @@ -356,6 +357,7 @@ static int smc_pnet_add_eth(struct smc_pnettable *pnettable, struct net *net, struct smc_pnetentry *tmp_pe, *new_pe; struct net_device *ndev, *base_ndev; u8 ndev_pnetid[SMC_MAX_PNETID_LEN]; + netdevice_tracker base_tracker; bool new_netdev; int rc; @@ -365,10 +367,13 @@ static int smc_pnet_add_eth(struct smc_pnettable *pnettable, struct net *net, rc = -EEXIST; ndev = dev_get_by_name(net, eth_name); /* dev_hold() */ if (ndev) { - base_ndev = pnet_find_base_ndev(ndev); + base_ndev = pnet_find_base_ndev(ndev, &base_tracker); if (!smc_pnetid_by_dev_port(base_ndev->dev.parent, - base_ndev->dev_port, ndev_pnetid)) + base_ndev->dev_port, ndev_pnetid)) { + netdev_put(base_ndev, &base_tracker); goto out_put; + } + netdev_put(base_ndev, &base_tracker); } /* add a new netdev entry to the pnet table if there isn't one */ @@ -945,10 +950,13 @@ static struct net_device *__pnet_find_base_ndev(struct net_device *ndev) * (for instance with bonding slaves), just the first device * is used to reach a base device. */ -static struct net_device *pnet_find_base_ndev(struct net_device *ndev) +static struct net_device *pnet_find_base_ndev(struct net_device *ndev, + netdevice_tracker *tracker) { rtnl_lock(); ndev = __pnet_find_base_ndev(ndev); + /* keep ndev alive after dropping RTNL, callers must netdev_put() */ + netdev_hold(ndev, tracker, GFP_KERNEL); rtnl_unlock(); return ndev; } @@ -1085,17 +1093,20 @@ static void smc_pnet_find_roce_by_pnetid(struct net_device *ndev, { u8 ndev_pnetid[SMC_MAX_PNETID_LEN]; struct net_device *base_ndev; + netdevice_tracker base_tracker; struct net *net; - base_ndev = pnet_find_base_ndev(ndev); + base_ndev = pnet_find_base_ndev(ndev, &base_tracker); net = dev_net(ndev); if (smc_pnetid_by_dev_port(base_ndev->dev.parent, base_ndev->dev_port, ndev_pnetid) && smc_pnet_find_ndev_pnetid_by_table(base_ndev, ndev_pnetid) && smc_pnet_find_ndev_pnetid_by_table(ndev, ndev_pnetid)) { smc_pnet_find_rdma_dev(base_ndev, ini); + netdev_put(base_ndev, &base_tracker); return; /* pnetid could not be determined */ } + netdev_put(base_ndev, &base_tracker); _smc_pnet_find_roce_by_pnetid(ndev_pnetid, ini, NULL, net); } @@ -1103,13 +1114,16 @@ static void smc_pnet_find_ism_by_pnetid(struct net_device *ndev, struct smc_init_info *ini) { u8 ndev_pnetid[SMC_MAX_PNETID_LEN]; + netdevice_tracker base_tracker; struct smcd_dev *ismdev; - ndev = pnet_find_base_ndev(ndev); + ndev = pnet_find_base_ndev(ndev, &base_tracker); if (smc_pnetid_by_dev_port(ndev->dev.parent, ndev->dev_port, ndev_pnetid) && - smc_pnet_find_ndev_pnetid_by_table(ndev, ndev_pnetid)) + smc_pnet_find_ndev_pnetid_by_table(ndev, ndev_pnetid)) { + netdev_put(ndev, &base_tracker); return; /* pnetid could not be determined */ + } mutex_lock(&smcd_dev_list.mutex); list_for_each_entry(ismdev, &smcd_dev_list.list, list) { @@ -1123,6 +1137,7 @@ static void smc_pnet_find_ism_by_pnetid(struct net_device *ndev, } } mutex_unlock(&smcd_dev_list.mutex); + netdev_put(ndev, &base_tracker); } /* PNET table analysis for a given sock: diff --git a/net/sunrpc/xprtsock.c b/net/sunrpc/xprtsock.c index 7f60723fa64d..963e46a51421 100644 --- a/net/sunrpc/xprtsock.c +++ b/net/sunrpc/xprtsock.c @@ -375,8 +375,18 @@ xs_sock_process_cmsg(struct socket *sock, struct msghdr *msg, break; case TLS_RECORD_TYPE_ALERT: tls_alert_recv(sock->sk, msg, &level, &description); - ret = (level == TLS_ALERT_LEVEL_FATAL) ? - -EACCES : -EAGAIN; + /* RFC 8446 Section 6: every alert but a closure alert is + * an error alert, whatever the legacy AlertLevel octet + * says. + */ + switch (description) { + case TLS_ALERT_DESC_CLOSE_NOTIFY: + case TLS_ALERT_DESC_USER_CANCELED: + ret = -EAGAIN; + break; + default: + ret = -EACCES; + } break; default: /* discard this record type */ @@ -407,9 +417,25 @@ xs_sock_recv_cmsg(struct socket *sock, unsigned int *msg_flags, int flags) iov_iter_kvec(&msg.msg_iter, ITER_DEST, &alert_kvec, 1, alert_kvec.iov_len); ret = sock_recvmsg(sock, &msg, flags); - if (ret > 0) { - if (tls_get_record_type(sock->sk, &u.cmsg) == TLS_RECORD_TYPE_ALERT) + /* put_cmsg() shrinks msg_controllen, so a short one means + * kTLS filled in u.cmsg. + */ + if (ret >= 0 && msg.msg_controllen < sizeof(u)) { + if (tls_get_record_type(sock->sk, &u.cmsg) == + TLS_RECORD_TYPE_ALERT) { + /* RFC 8446 Section 5.1 requires a record with an + * Alert type to carry exactly one message. An alert + * is two octets. tls_alert_recv() reads both without + * checking the length. alert_kvec caps the count at + * two, so a longer record fills it as well. kTLS + * sets MSG_EOR only once the record has been + * drained. + */ + if (ret != sizeof(alert) || + !(msg.msg_flags & MSG_EOR)) + return -EACCES; iov_iter_revert(&msg.msg_iter, ret); + } ret = xs_sock_process_cmsg(sock, &msg, msg_flags, &u.cmsg, -EAGAIN); } diff --git a/net/tipc/bearer.c b/net/tipc/bearer.c index 05dcd2f9e887..5e7e220fa7f5 100644 --- a/net/tipc/bearer.c +++ b/net/tipc/bearer.c @@ -659,6 +659,10 @@ static int tipc_l2_rcv_msg(struct sk_buff *skb, struct net_device *dev, { struct tipc_bearer *b; + skb = skb_share_check(skb, GFP_ATOMIC); + if (!skb) + return NET_RX_DROP; + rcu_read_lock(); b = rcu_dereference(dev->tipc_ptr) ?: rcu_dereference(orig_dev->tipc_ptr); diff --git a/net/tipc/node.c b/net/tipc/node.c index d7cbfa786c13..53b0993c2c23 100644 --- a/net/tipc/node.c +++ b/net/tipc/node.c @@ -303,6 +303,7 @@ static void tipc_node_free(struct rcu_head *rp) #ifdef CONFIG_TIPC_CRYPTO tipc_crypto_stop(&n->crypto_rx); #endif + kfree(n->bc_entry.link); kfree(n); } @@ -310,7 +311,6 @@ static void tipc_node_kref_release(struct kref *kref) { struct tipc_node *n = container_of(kref, struct tipc_node, kref); - kfree(n->bc_entry.link); call_rcu(&n->rcu, tipc_node_free); } diff --git a/net/tls/tls_device.c b/net/tls/tls_device.c index f11d0528fc43..9f7bd589dfc3 100644 --- a/net/tls/tls_device.c +++ b/net/tls/tls_device.c @@ -783,8 +783,15 @@ void tls_device_rx_resync_new_rec(struct sock *sk, u32 rcd_len, u32 seq) if (tls_ctx->rx_conf != TLS_HW) return; + + /* The parser also runs in process context, without an RCU read lock. + * Protect the driver's resync_async state before checking the flags: + * device-down sets DEGRADED and waits for synchronize_net() before + * freeing it, without taking the socket lock. + */ + rcu_read_lock(); if (unlikely(test_bit(TLS_RX_DEV_DEGRADED, &tls_ctx->flags))) - return; + goto out; prot = &tls_ctx->prot_info; rx_ctx = tls_offload_ctx_rx(tls_ctx); @@ -799,11 +806,11 @@ void tls_device_rx_resync_new_rec(struct sock *sk, u32 rcd_len, u32 seq) if (likely(!is_req_pending) || req_seq != seq || !atomic64_try_cmpxchg(&rx_ctx->resync_req, &resync_req, 0)) - return; + goto out; break; case TLS_OFFLOAD_SYNC_TYPE_CORE_NEXT_HINT: if (likely(!rx_ctx->resync_nh_do_now)) - return; + goto out; /* head of next rec is already in, note that the sock_inq will * include the currently parsed message when called from parser @@ -812,7 +819,7 @@ void tls_device_rx_resync_new_rec(struct sock *sk, u32 rcd_len, u32 seq) if (sock_data > rcd_len) { trace_tls_device_rx_resync_nh_delay(sk, sock_data, rcd_len); - return; + goto out; } rx_ctx->resync_nh_do_now = 0; @@ -823,16 +830,18 @@ void tls_device_rx_resync_new_rec(struct sock *sk, u32 rcd_len, u32 seq) resync_req = atomic64_read(&rx_ctx->resync_async->req); is_req_pending = resync_req; if (likely(!is_req_pending)) - return; + goto out; if (!tls_device_rx_resync_async(rx_ctx->resync_async, resync_req, &seq, &rcd_delta)) - return; + goto out; tls_bigint_subtract(rcd_sn, rcd_delta); break; } tls_device_resync_rx(tls_ctx, sk, seq, rcd_sn); +out: + rcu_read_unlock(); } static void tls_device_core_ctrl_rx_resync(struct tls_context *tls_ctx, @@ -1022,6 +1031,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) { @@ -1157,6 +1180,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, @@ -1227,6 +1255,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_obj(*context); if (!context) { rc = -ENOMEM; diff --git a/net/tls/tls_main.c b/net/tls/tls_main.c index fbb274287aa5..f13faafe58d2 100644 --- a/net/tls/tls_main.c +++ b/net/tls/tls_main.c @@ -701,8 +701,8 @@ static int do_tls_setsockopt_conf(struct sock *sk, sockptr_t optval, goto err_crypto_info; } - rc = copy_from_sockptr_offset(crypto_info + 1, optval, - sizeof(*crypto_info), + rc = copy_from_sockptr_offset((u8 *)crypto_ctx + sizeof(*crypto_info), + optval, sizeof(*crypto_info), optlen - sizeof(*crypto_info)); if (rc) { rc = -EFAULT; @@ -833,15 +833,26 @@ static int do_tls_setsockopt_no_pad(struct sock *sk, sockptr_t optval, return rc; } +static bool tls_tx_record_is_open(struct tls_context *ctx) +{ + switch (ctx->tx_conf) { + case TLS_SW: + return !!tls_sw_ctx_tx(ctx)->open_rec; + case TLS_HW: + return !!tls_offload_ctx_tx(ctx)->open_record; + default: + return false; + } +} + static int do_tls_setsockopt_tx_payload_len(struct sock *sk, sockptr_t optval, unsigned int optlen) { struct tls_context *ctx = tls_get_ctx(sk); - struct tls_sw_context_tx *sw_ctx = tls_sw_ctx_tx(ctx); u16 value; bool tls_13 = ctx->prot_info.version == TLS_1_3_VERSION; - if (sw_ctx && sw_ctx->open_rec) + if (tls_tx_record_is_open(ctx)) return -EBUSY; if (sockptr_is_null(optval) || optlen != sizeof(value)) @@ -862,6 +873,7 @@ static int do_tls_setsockopt_tx_payload_len(struct sock *sk, sockptr_t optval, static int do_tls_setsockopt(struct sock *sk, int optname, sockptr_t optval, unsigned int optlen) { + struct tls_context *ctx; int rc = 0; switch (optname) { @@ -881,9 +893,15 @@ static int do_tls_setsockopt(struct sock *sk, int optname, sockptr_t optval, rc = do_tls_setsockopt_no_pad(sk, optval, optlen); break; case TLS_TX_MAX_PAYLOAD_LEN: + ctx = tls_get_ctx(sk); + /* Senders sleep with tx_lock held, so take it interruptible */ + rc = mutex_lock_interruptible(&ctx->tx_lock); + if (rc) + break; lock_sock(sk); rc = do_tls_setsockopt_tx_payload_len(sk, optval, optlen); release_sock(sk); + mutex_unlock(&ctx->tx_lock); break; default: rc = -ENOPROTOOPT; diff --git a/net/tls/tls_sw.c b/net/tls/tls_sw.c index d1ad31986cf2..79639ed79821 100644 --- a/net/tls/tls_sw.c +++ b/net/tls/tls_sw.c @@ -2007,10 +2007,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; @@ -2024,8 +2028,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, flags & SPLICE_F_NONBLOCK, - true, false); + err = tls_rx_rec_wait(sk, nonblock, true, false); if (err <= 0) goto splice_read_end; diff --git a/net/wireless/core.c b/net/wireless/core.c index cde3ca85494d..3ac3b2a67a9c 100644 --- a/net/wireless/core.c +++ b/net/wireless/core.c @@ -348,6 +348,41 @@ int cfg80211_nan_set_local_schedule(struct cfg80211_registered_device *rdev, return 0; } +int cfg80211_nan_set_non_evac_channels(struct cfg80211_registered_device *rdev, + struct wireless_dev *wdev, + struct cfg80211_nan_non_evac_channels *channels) +{ + lockdep_assert_held(&rdev->wiphy.mtx); + + if (wdev->iftype != NL80211_IFTYPE_NAN || !wdev_running(wdev)) + return -EINVAL; + + /* + * Don't allow updating the non-evacuable channels while a deferred + * schedule update is pending, as the set of channels may still change. + */ + if (wdev->u.nan.sched_update_pending) + return -EBUSY; + + /* All provided channels must belong to the current local schedule. */ + for (int i = 0; i < channels->n_channels; i++) { + bool found = false; + + for (int j = 0; j < wdev->u.nan.n_channels; j++) { + if (cfg80211_chandef_identical(&wdev->u.nan.chandefs[j], + &channels->chandefs[i])) { + found = true; + break; + } + } + + if (!found) + return -ENOENT; + } + + return rdev_nan_set_non_evac_channels(rdev, wdev, channels); +} + void cfg80211_stop_pd(struct cfg80211_registered_device *rdev, struct wireless_dev *wdev) { diff --git a/net/wireless/core.h b/net/wireless/core.h index 6138d207caf4..add43b6b19f1 100644 --- a/net/wireless/core.h +++ b/net/wireless/core.h @@ -575,6 +575,10 @@ int cfg80211_nan_set_local_schedule(struct cfg80211_registered_device *rdev, struct wireless_dev *wdev, struct cfg80211_nan_local_sched *sched); +int cfg80211_nan_set_non_evac_channels(struct cfg80211_registered_device *rdev, + struct wireless_dev *wdev, + struct cfg80211_nan_non_evac_channels *channels); + struct cfg80211_internal_bss * cfg80211_bss_update(struct cfg80211_registered_device *rdev, struct cfg80211_internal_bss *tmp, diff --git a/net/wireless/nl80211.c b/net/wireless/nl80211.c index ddce61ec016a..d6c43083f8e3 100644 --- a/net/wireless/nl80211.c +++ b/net/wireless/nl80211.c @@ -529,11 +529,11 @@ nl80211_pmsr_attr_policy[NL80211_PMSR_ATTR_MAX + 1] = { static const struct nla_policy he_obss_pd_policy[NL80211_HE_OBSS_PD_ATTR_MAX + 1] = { [NL80211_HE_OBSS_PD_ATTR_MIN_OFFSET] = - NLA_POLICY_RANGE(NLA_U8, 1, 20), + NLA_POLICY_RANGE(NLA_U8, 0, 20), [NL80211_HE_OBSS_PD_ATTR_MAX_OFFSET] = - NLA_POLICY_RANGE(NLA_U8, 1, 20), + NLA_POLICY_RANGE(NLA_U8, 0, 20), [NL80211_HE_OBSS_PD_ATTR_NON_SRG_MAX_OFFSET] = - NLA_POLICY_RANGE(NLA_U8, 1, 20), + NLA_POLICY_RANGE(NLA_U8, 0, 20), [NL80211_HE_OBSS_PD_ATTR_BSS_COLOR_BITMAP] = NLA_POLICY_EXACT_LEN(8), [NL80211_HE_OBSS_PD_ATTR_PARTIAL_BSSID_BITMAP] = @@ -6538,6 +6538,9 @@ nl80211_parse_mbssid_elems(struct wiphy *wiphy, struct nlattr *attrs, num_elems++; } + if (!num_elems) + return ERR_PTR(-EINVAL); + elems = kzalloc_flex(*elems, elem, num_elems); if (!elems) return ERR_PTR(-ENOMEM); @@ -6573,6 +6576,9 @@ nl80211_parse_rnr_elems(struct wiphy *wiphy, struct nlattr *attrs, num_elems++; } + if (!num_elems) + return ERR_PTR(-EINVAL); + elems = kzalloc_flex(*elems, elem, num_elems); if (!elems) return ERR_PTR(-ENOMEM); @@ -6816,7 +6822,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; } @@ -17766,6 +17773,69 @@ static int nl80211_nan_set_local_sched(struct sk_buff *skb, return cfg80211_nan_set_local_schedule(rdev, wdev, sched); } +static int +nl80211_parse_non_evac_channel(struct cfg80211_registered_device *rdev, + struct nlattr *channel, struct genl_info *info, + struct cfg80211_chan_def *chandef) +{ + struct nlattr **channel_parsed __free(kfree) = + kcalloc(NL80211_ATTR_MAX + 1, sizeof(*channel_parsed), + GFP_KERNEL); + int ret; + + if (!channel_parsed) + return -ENOMEM; + + ret = nla_parse_nested(channel_parsed, NL80211_ATTR_MAX, channel, NULL, + info->extack); + if (ret) + return ret; + + return nl80211_parse_chandef(rdev, info->extack, channel_parsed, + chandef, false); +} + +static int nl80211_nan_set_non_evac_channels(struct sk_buff *skb, + struct genl_info *info) +{ + struct cfg80211_registered_device *rdev = info->user_ptr[0]; + struct wireless_dev *wdev = info->user_ptr[1]; + int rem, i = 0, n_channels = 0; + struct nlattr *channel; + + if (wdev->iftype != NL80211_IFTYPE_NAN) + return -EOPNOTSUPP; + + if (!wdev_running(wdev)) + return -ENOTCONN; + + /* Count how many channel attributes we got */ + nlmsg_for_each_attr_type(channel, NL80211_ATTR_NAN_CHANNEL, + info->nlhdr, GENL_HDRLEN, rem) + n_channels++; + + struct cfg80211_nan_non_evac_channels *channels __free(kfree) = + kzalloc(struct_size(channels, chandefs, n_channels), + GFP_KERNEL); + if (!channels) + return -ENOMEM; + + channels->n_channels = n_channels; + + nlmsg_for_each_attr_type(channel, NL80211_ATTR_NAN_CHANNEL, + info->nlhdr, GENL_HDRLEN, rem) { + int ret; + + ret = nl80211_parse_non_evac_channel(rdev, channel, info, + &channels->chandefs[i]); + if (ret) + return ret; + i++; + } + + return cfg80211_nan_set_non_evac_channels(rdev, wdev, channels); +} + static int nl80211_get_protocol_features(struct sk_buff *skb, struct genl_info *info) { @@ -20622,6 +20692,12 @@ static const struct genl_small_ops nl80211_small_ops[] = { .flags = GENL_ADMIN_PERM, .internal_flags = IFLAGS(NL80211_FLAG_NEED_WDEV_UP), }, + { + .cmd = NL80211_CMD_NAN_SET_NON_EVAC_CHANNELS, + .doit = nl80211_nan_set_non_evac_channels, + .flags = GENL_ADMIN_PERM, + .internal_flags = IFLAGS(NL80211_FLAG_NEED_WDEV_UP), + }, }; static struct genl_family nl80211_fam __ro_after_init = { diff --git a/net/wireless/rdev-ops.h b/net/wireless/rdev-ops.h index adcfd0278da3..e5ad7d07e254 100644 --- a/net/wireless/rdev-ops.h +++ b/net/wireless/rdev-ops.h @@ -1096,6 +1096,23 @@ rdev_nan_set_peer_sched(struct cfg80211_registered_device *rdev, return ret; } +static inline int +rdev_nan_set_non_evac_channels(struct cfg80211_registered_device *rdev, + struct wireless_dev *wdev, + struct cfg80211_nan_non_evac_channels *channels) +{ + int ret; + + trace_rdev_nan_set_non_evac_channels(&rdev->wiphy, wdev, channels); + if (rdev->ops->nan_set_non_evac_channels) + ret = rdev->ops->nan_set_non_evac_channels(&rdev->wiphy, wdev, + channels); + else + ret = -EOPNOTSUPP; + trace_rdev_return_int(&rdev->wiphy, ret); + return ret; +} + static inline int rdev_start_pd(struct cfg80211_registered_device *rdev, struct wireless_dev *wdev) { diff --git a/net/wireless/reg.c b/net/wireless/reg.c index 44226687349e..bd83743fb35d 100644 --- a/net/wireless/reg.c +++ b/net/wireless/reg.c @@ -590,7 +590,7 @@ static inline int call_crda(const char *alpha2) #endif /* CONFIG_CFG80211_CRDA_SUPPORT */ /* code to directly load a firmware database through request_firmware */ -static const struct fwdb_header *regdb; +static const struct fwdb_header __rcu *global_regdb; struct fwdb_country { u8 alpha2[2]; @@ -895,16 +895,19 @@ static int __regdb_query_wmm(const struct fwdb_header *db, int reg_query_regdb_wmm(char *alpha2, int freq, struct ieee80211_reg_rule *rule) { - const struct fwdb_header *hdr = regdb; const struct fwdb_country *country; + const struct fwdb_header *regdb; + guard(rcu)(); + + regdb = rcu_dereference(global_regdb); if (!regdb) return -ENODATA; if (IS_ERR(regdb)) return PTR_ERR(regdb); - country = &hdr->country[0]; + country = ®db->country[0]; while (country->coll_ptr) { if (alpha2_equal(alpha2, country->alpha2)) return __regdb_query_wmm(regdb, country, freq, rule); @@ -973,15 +976,13 @@ static int regdb_query_country(const struct fwdb_header *db, static int query_regdb(const char *alpha2) { - const struct fwdb_header *hdr = regdb; + const struct fwdb_header *regdb = rtnl_dereference(global_regdb); const struct fwdb_country *country; - ASSERT_RTNL(); - if (IS_ERR(regdb)) return PTR_ERR(regdb); - country = &hdr->country[0]; + country = ®db->country[0]; while (country->coll_ptr) { if (alpha2_equal(alpha2, country->alpha2)) return regdb_query_country(regdb, country); @@ -993,6 +994,7 @@ static int query_regdb(const char *alpha2) static void regdb_fw_cb(const struct firmware *fw, void *context) { + const struct fwdb_header *regdb; int set_error = 0; bool restore = true; void *db; @@ -1006,6 +1008,7 @@ static void regdb_fw_cb(const struct firmware *fw, void *context) } rtnl_lock(); + regdb = rtnl_dereference(global_regdb); if (regdb && !IS_ERR(regdb)) { /* negative case - a bug * positive case - can happen due to race in case of multiple cb's in @@ -1014,11 +1017,11 @@ static void regdb_fw_cb(const struct firmware *fw, void *context) * Either case, just restore and free new db. */ } else if (set_error) { - regdb = ERR_PTR(set_error); + rcu_assign_pointer(global_regdb, ERR_PTR(set_error)); } else if (fw) { db = kmemdup(fw->data, fw->size, GFP_KERNEL); if (db) { - regdb = db; + rcu_assign_pointer(global_regdb, db); restore = context && query_regdb(context); } else { restore = true; @@ -1043,7 +1046,7 @@ static int query_regdb_file(const char *alpha2) ASSERT_RTNL(); - if (regdb) + if (rcu_access_pointer(global_regdb)) return query_regdb(alpha2); alpha2 = kmemdup(alpha2, 2, GFP_KERNEL); @@ -1061,8 +1064,8 @@ static int query_regdb_file(const char *alpha2) int reg_reload_regdb(void) { + const struct fwdb_header *db, *old; const struct firmware *fw; - void *db; int err; const struct ieee80211_regdomain *current_regdomain; struct regulatory_request *request; @@ -1083,9 +1086,7 @@ int reg_reload_regdb(void) } rtnl_lock(); - if (!IS_ERR_OR_NULL(regdb)) - kfree(regdb); - regdb = db; + old = rcu_replace_pointer_rtnl(global_regdb, db); /* reset regulatory domain */ current_regdomain = get_cfg80211_regdom(); @@ -1106,6 +1107,11 @@ int reg_reload_regdb(void) out_unlock: rtnl_unlock(); + + if (!IS_ERR_OR_NULL(old)) { + synchronize_rcu(); + kfree(old); + } out: release_firmware(fw); return err; @@ -4388,6 +4394,7 @@ void regulatory_exit(void) { struct regulatory_request *reg_request, *tmp; struct reg_beacon *reg_beacon, *btmp; + const struct fwdb_header *db; cancel_work_sync(®_work); cancel_crda_timeout_sync(); @@ -4417,8 +4424,10 @@ void regulatory_exit(void) kfree(reg_request); } - if (!IS_ERR_OR_NULL(regdb)) - kfree(regdb); + /* RCU is irrelevant on the way out */ + db = rcu_dereference_protected(global_regdb, true); + if (!IS_ERR_OR_NULL(db)) + kfree(db); if (!IS_ERR_OR_NULL(cfg80211_user_regdom)) kfree(cfg80211_user_regdom); diff --git a/net/wireless/sme.c b/net/wireless/sme.c index 2a719b5c487e..a74b9aeb0244 100644 --- a/net/wireless/sme.c +++ b/net/wireless/sme.c @@ -872,6 +872,25 @@ void __cfg80211_connect_result(struct net_device *dev, cfg80211_upload_connect_keys(wdev); + if (!wdev->u.client.ssid_len) { + rcu_read_lock(); + for_each_valid_link(cr, link) { + u32 ssid_len; + + ssid = ieee80211_bss_get_elem(cr->links[link].bss, + WLAN_EID_SSID); + + if (!ssid || !ssid->datalen) + continue; + + ssid_len = min(ssid->datalen, IEEE80211_MAX_SSID_LEN); + memcpy(wdev->u.client.ssid, ssid->data, ssid_len); + wdev->u.client.ssid_len = ssid_len; + break; + } + rcu_read_unlock(); + } + rcu_read_lock(); for_each_valid_link(cr, link) { country_elem = @@ -897,25 +916,6 @@ void __cfg80211_connect_result(struct net_device *dev, country_data, country_datalen); kfree(country_data); - if (!wdev->u.client.ssid_len) { - rcu_read_lock(); - for_each_valid_link(cr, link) { - u32 ssid_len; - - ssid = ieee80211_bss_get_elem(cr->links[link].bss, - WLAN_EID_SSID); - - if (!ssid || !ssid->datalen) - continue; - - ssid_len = min(ssid->datalen, IEEE80211_MAX_SSID_LEN); - memcpy(wdev->u.client.ssid, ssid->data, ssid_len); - wdev->u.client.ssid_len = ssid_len; - break; - } - rcu_read_unlock(); - } - return; out: for_each_valid_link(cr, link) diff --git a/net/wireless/trace.h b/net/wireless/trace.h index 8c2a91b85c39..435dc58cafbe 100644 --- a/net/wireless/trace.h +++ b/net/wireless/trace.h @@ -2483,6 +2483,31 @@ TRACE_EVENT(rdev_nan_set_peer_sched, ) ); +TRACE_EVENT(rdev_nan_set_non_evac_channels, + TP_PROTO(struct wiphy *wiphy, struct wireless_dev *wdev, + struct cfg80211_nan_non_evac_channels *channels), + TP_ARGS(wiphy, wdev, channels), + TP_STRUCT__entry( + WIPHY_ENTRY + WDEV_ENTRY + __field(u8, n_channels) + __dynamic_array(u32, freqs, channels->n_channels) + ), + TP_fast_assign( + u32 *freqs = __get_dynamic_array(freqs); + + WIPHY_ASSIGN; + WDEV_ASSIGN; + __entry->n_channels = channels->n_channels; + for (int i = 0; i < channels->n_channels; i++) + freqs[i] = channels->chandefs[i].chan->center_freq; + ), + TP_printk(WIPHY_PR_FMT ", " WDEV_PR_FMT ", n_channels: %u, freqs: %s", + WIPHY_PR_ARG, WDEV_PR_ARG, __entry->n_channels, + __print_array(__get_dynamic_array(freqs), + __entry->n_channels, sizeof(u32))) +); + TRACE_EVENT(rdev_set_mac_acl, TP_PROTO(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_acl_data *params), diff --git a/net/xdp/xsk.c b/net/xdp/xsk.c index 33475b180ea6..781ba46eb152 100644 --- a/net/xdp/xsk.c +++ b/net/xdp/xsk.c @@ -2145,6 +2145,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 e836eca469b0..7750d2ec4ee2 100644 --- a/net/xdp/xsk_buff_pool.c +++ b/net/xdp/xsk_buff_pool.c @@ -173,7 +173,7 @@ int xp_assign_dev(struct xsk_buff_pool *pool, u32 frame_size; int err = 0; - ASSERT_RTNL(); + netdev_assert_locked_ops_compat(netdev); force_zc = flags & XDP_ZEROCOPY; force_copy = flags & XDP_COPY; @@ -205,6 +205,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. */ @@ -245,7 +250,6 @@ int xp_assign_dev(struct xsk_buff_pool *pool, bpf.xsk.pool = pool; bpf.xsk.queue_id = queue_id; - netdev_assert_locked_ops_compat(netdev); err = netdev->netdev_ops->ndo_bpf(netdev, &bpf); if (err) goto err_unreg_pool; @@ -267,6 +271,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; @@ -289,19 +295,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_assert_locked_ops_compat(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) @@ -339,7 +365,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/rust/Makefile b/rust/Makefile index da1a7409d984..3879411d7bb9 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -514,13 +514,20 @@ endif bindgen_c_flags_final = $(bindgen_c_flags_lto) -fno-builtin -D__BINDGEN__ # `--rust-target` points to our minimum supported Rust version. +# +# `bindgen` 0.73 emits the blob of some opaque types as a +# `__BindgenOpaqueArray[]` newtype, which the custom derives do not +# reach. Derive `Zeroable` for those wrappers, so that a struct embedding such +# an opaque type (e.g. `spinlock_t` with lockdep) is still `Zeroable`. The +# pattern also matches the unformatted output used when `rustfmt` is missing. quiet_cmd_bindgen = BINDGEN $@ cmd_bindgen = \ $(BINDGEN) $< $(bindgen_target_flags) --rust-target 1.85 \ --use-core --with-derive-default --ctypes-prefix ffi --no-layout-tests \ --no-debug '.*' --enable-function-attribute-detection \ -o $@ -- $(bindgen_c_flags_final) -DMODULE \ - $(bindgen_target_cflags) $(bindgen_target_extra) + $(bindgen_target_cflags) $(bindgen_target_extra); \ + sed -Ei 's/pub struct __BindgenOpaqueArray[0-9]* *< *T *> *\( *pub T *\) *;/$(pound)[derive(pin_init::Zeroable)] &/g' $@ $(obj)/bindings/bindings_generated.rs: private bindgen_target_flags = \ $(shell grep -Ev '^#|^$$' $(src)/bindgen_parameters) diff --git a/rust/helpers/dma.c b/rust/helpers/dma.c index 9fbeb507b08c..ff8f24dae9df 100644 --- a/rust/helpers/dma.c +++ b/rust/helpers/dma.c @@ -49,3 +49,8 @@ __rust_helper void rust_helper_dma_set_max_seg_size(struct device *dev, { dma_set_max_seg_size(dev, size); } + +__rust_helper unsigned int rust_helper_dma_get_max_seg_size(struct device *dev) +{ + return dma_get_max_seg_size(dev); +} diff --git a/rust/kernel/bitmap.rs b/rust/kernel/bitmap.rs index 053821fff74b..4b4c6fef4125 100644 --- a/rust/kernel/bitmap.rs +++ b/rust/kernel/bitmap.rs @@ -487,7 +487,13 @@ pub fn last_bit(&self) -> Option { /// Finds next set bit, starting from `start`. /// - /// Returns `None` if `start` is greater or equal to `self.nbits`. + /// Returns `None` if no bits are set on or after the given index. The + /// index `start` must be in bounds. + /// + /// # Panics + /// + /// Panics if `CONFIG_RUST_BITMAP_HARDENED` is enabled and `start` is + /// out of bounds. #[inline] pub fn next_bit(&self, start: usize) -> Option { bitmap_assert!( @@ -507,7 +513,14 @@ pub fn next_bit(&self, start: usize) -> Option { } /// Finds next zero bit, starting from `start`. - /// Returns `None` if `start` is greater than or equal to `self.len()`. + /// + /// Returns `None` if no bits are zero on or after the given index. The + /// index `start` must be in bounds. + /// + /// # Panics + /// + /// Panics if `CONFIG_RUST_BITMAP_HARDENED` is enabled and `start` is + /// out of bounds. #[inline] pub fn next_zero_bit(&self, start: usize) -> Option { bitmap_assert!( diff --git a/rust/kernel/block/mq/tag_set.rs b/rust/kernel/block/mq/tag_set.rs index dae9df408a86..00d29688f920 100644 --- a/rust/kernel/block/mq/tag_set.rs +++ b/rust/kernel/block/mq/tag_set.rs @@ -83,3 +83,10 @@ fn drop(self: Pin<&mut Self>) { unsafe { bindings::blk_mq_free_tag_set(self.inner.get()) }; } } + +// SAFETY: It is safe to transfer ownership of `TagSet` between threads. +unsafe impl Send for TagSet {} + +// SAFETY: It is safe to share `&TagSet` across threads. `TagSet` exposes no +// `&self` methods that mutate the contained `blk_mq_tag_set`. +unsafe impl Sync for TagSet {} diff --git a/rust/kernel/clk.rs b/rust/kernel/clk.rs index 7abbd0767d8c..f04f5c4a03d6 100644 --- a/rust/kernel/clk.rs +++ b/rust/kernel/clk.rs @@ -35,16 +35,31 @@ impl Hertz { const GHZ_TO_HZ: c_ulong = 1_000_000_000; /// Create a new instance from kilohertz (kHz) + /// + /// # Panics + /// + /// Panics if `CONFIG_RUST_OVERFLOW_CHECKS` is enabled and `khz` is greater + /// than `c_ulong::MAX / 1_000`. pub const fn from_khz(khz: c_ulong) -> Self { Self(khz * Self::KHZ_TO_HZ) } /// Create a new instance from megahertz (MHz) + /// + /// # Panics + /// + /// Panics if `CONFIG_RUST_OVERFLOW_CHECKS` is enabled and `mhz` is greater + /// than `c_ulong::MAX / 1_000_000`. pub const fn from_mhz(mhz: c_ulong) -> Self { Self(mhz * Self::MHZ_TO_HZ) } /// Create a new instance from gigahertz (GHz) + /// + /// # Panics + /// + /// Panics if `CONFIG_RUST_OVERFLOW_CHECKS` is enabled and `ghz` is greater + /// than `c_ulong::MAX / 1_000_000_000`. pub const fn from_ghz(ghz: c_ulong) -> Self { Self(ghz * Self::GHZ_TO_HZ) } diff --git a/rust/kernel/configfs.rs b/rust/kernel/configfs.rs index 2b3325cd9e1f..ff53b3fb31c2 100644 --- a/rust/kernel/configfs.rs +++ b/rust/kernel/configfs.rs @@ -135,8 +135,9 @@ pub struct Subsystem { // SAFETY: We do not provide any operations on `Subsystem`. unsafe impl Sync for Subsystem {} -// SAFETY: Ownership of `Subsystem` can safely be transferred to other threads. -unsafe impl Send for Subsystem {} +// SAFETY: Ownership of `Subsystem` can safely be transferred to other threads +// if its data can be transferred as well. +unsafe impl Send for Subsystem {} impl Subsystem { /// Create an initializer for a [`Subsystem`]. @@ -249,6 +250,13 @@ pub struct Group { data: Data, } +// SAFETY: We do not provide any operations on `Group`. +unsafe impl Sync for Group {} + +// SAFETY: Ownership of `Group` can safely be transferred to other threads if +// its data can be transferred as well. +unsafe impl Send for Group {} + impl Group { /// Create an initializer for a new group. /// @@ -338,7 +346,9 @@ unsafe fn get_group_data<'a, Parent>(this: *mut bindings::config_group) -> &'a P impl GroupOperationsVTable where Parent: GroupOperations, - Child: 'static, + // We transfer `Arc>` across a thread boundary in `make_group` + // and `drop_item`. + Arc>: Send, { /// # Safety /// @@ -357,8 +367,9 @@ impl GroupOperationsVTable this: *mut bindings::config_group, name: *const kernel::ffi::c_char, ) -> *mut bindings::config_group { - // SAFETY: By function safety requirements of this function, this call - // is safe. + // SAFETY: By function safety requirements, `this` points to a configfs + // group containing `Parent`. The `GroupOperations` bound guarantees + // that `Parent: Sync`, so it is safe to share it with this thread. let parent_data = unsafe { get_group_data(this) }; let group_init = match Parent::make_group( @@ -403,8 +414,9 @@ impl GroupOperationsVTable this: *mut bindings::config_group, item: *mut bindings::config_item, ) { - // SAFETY: By function safety requirements of this function, this call - // is safe. + // SAFETY: By function safety requirements, `this` points to a configfs + // group containing `Parent`. The `GroupOperations` bound guarantees + // that `Parent: Sync`, so it is safe to share it with this thread. let parent_data = unsafe { get_group_data(this) }; // SAFETY: By function safety requirements, `item` is embedded in a @@ -416,7 +428,9 @@ impl GroupOperationsVTable if Parent::HAS_DROP_ITEM { // SAFETY: We called `into_raw` to produce `r_child_group_ptr` in - // `make_group`. + // `make_group`. This function may be executing on a different + // thread than `into_raw`. As `Arc>: Send` this + // ownership transfer is safe. let arc: Arc> = unsafe { Arc::from_raw(r_child_group_ptr.cast_mut()) }; Parent::drop_item(parent_data, arc.as_arc_borrow()); @@ -447,6 +461,8 @@ const fn vtable_ptr() -> *const bindings::configfs_group_operations { impl ItemOperationsVTable, Data> where Data: 'static, + // We transfer `Arc>` across a thread boundary in `release`. + Arc>: Send, { /// # Safety /// @@ -463,8 +479,9 @@ impl ItemOperationsVTable, Data> // embedded within a `Group`. let r_group_ptr = unsafe { Group::::container_of(c_group_ptr) }; - // SAFETY: We called `into_raw` on `r_group_ptr` in - // `make_group`. + // SAFETY: We called `into_raw` on `r_group_ptr` in `make_group`. This + // function may be running on a different thread than the thread that + // called `into_raw`. As `Arc>: Send`, this is safe. let pin_self: Arc> = unsafe { Arc::from_raw(r_group_ptr.cast_mut()) }; drop(pin_self); } @@ -496,12 +513,12 @@ const fn vtable_ptr() -> *const bindings::configfs_item_operations { /// /// Implement this trait on structs that embed a [`Subsystem`] or a [`Group`]. #[vtable] -pub trait GroupOperations { +pub trait GroupOperations: Sync { /// The child data object type. /// /// This group will create subgroups (subdirectories) backed by this kind of /// object. - type Child: 'static; + type Child: 'static + Send; /// Creates a new subgroup. /// @@ -568,8 +585,10 @@ impl Attribute // `config_group`. unsafe { container_of!(item, bindings::config_group, cg_item) }; - // SAFETY: The function safety requirements for this function satisfy - // the conditions for this call. + // SAFETY: By function safety requirements, `c_group` points to a + // configfs group containing `Data`. The `AttributeOperations` bound + // guarantees that `Data: Sync`, so it is safe to share it with this + // thread. let data: &Data = unsafe { get_group_data(c_group) }; // SAFETY: By function safety requirements, `page` is writable for `PAGE_SIZE`. @@ -602,8 +621,10 @@ impl Attribute // `config_group`. unsafe { container_of!(item, bindings::config_group, cg_item) }; - // SAFETY: The function safety requirements for this function satisfy - // the conditions for this call. + // SAFETY: By function safety requirements, `c_group` points to a + // configfs group containing `Data`. The `AttributeOperations` bound + // guarantees that `Data: Sync`, so it is safe to share it with this + // thread. let data: &Data = unsafe { get_group_data(c_group) }; let ret = O::store( @@ -656,7 +677,7 @@ pub const fn new(name: &'static CStr) -> Self { pub trait AttributeOperations { /// The type of the object that contains the field that is backing the /// attribute for this operation. - type Data; + type Data: Sync; /// Renders the value of an attribute. /// @@ -762,7 +783,8 @@ pub const fn new_with_child_ctor( ) -> Self where Data: GroupOperations, - Child: 'static, + Arc>: Send, + Arc>: Send, { Self { item_type: Opaque::new(bindings::config_item_type { @@ -780,7 +802,10 @@ pub const fn new_with_child_ctor( pub const fn new( owner: &'static ThisModule, attributes: &'static AttributeList, - ) -> Self { + ) -> Self + where + Arc>: Send, + { Self { item_type: Opaque::new(bindings::config_item_type { ct_owner: owner.as_ptr(), diff --git a/rust/kernel/i2c.rs b/rust/kernel/i2c.rs index 0487bae811fb..b4ff25c830fc 100644 --- a/rust/kernel/i2c.rs +++ b/rust/kernel/i2c.rs @@ -5,7 +5,6 @@ // I2C Driver abstractions. use crate::{ acpi, - container_of, device, device_id::{ RawDeviceId, @@ -517,26 +516,6 @@ fn as_ref(&self) -> &device::Device { } } -impl TryFrom<&device::Device> for &I2cClient { - type Error = kernel::error::Error; - - fn try_from(dev: &device::Device) -> Result { - // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a - // `struct device`. - if unsafe { bindings::i2c_verify_client(dev.as_raw()).is_null() } { - return Err(EINVAL); - } - - // SAFETY: We've just verified that the type of `dev` equals to - // `bindings::i2c_client_type`, hence `dev` must be embedded in a valid - // `struct i2c_client` as guaranteed by the corresponding C code. - let idev = unsafe { container_of!(dev.as_raw(), bindings::i2c_client, dev) }; - - // SAFETY: `idev` is a valid pointer to a `struct i2c_client`. - Ok(unsafe { &*idev.cast() }) - } -} - // SAFETY: A `I2cClient` is always reference-counted and can be released from any thread. unsafe impl Send for I2cClient {} diff --git a/rust/kernel/id_pool.rs b/rust/kernel/id_pool.rs index 384753fe0e44..c8b346554802 100644 --- a/rust/kernel/id_pool.rs +++ b/rust/kernel/id_pool.rs @@ -224,7 +224,13 @@ pub fn grow(&mut self, mut resizer: PoolResizer) { /// Finds an unused ID in the bitmap. /// /// Upon success, returns its index. Otherwise, returns [`None`] - /// to indicate that a [`Self::grow_request`] is needed. + /// to indicate that a [`Self::grow_request`] is needed. `offset` must be + /// within bounds. + /// + /// # Panics + /// + /// Panics if `CONFIG_RUST_BITMAP_HARDENED` is enabled and `offset` is out + /// of bounds. #[inline] #[must_use] pub fn find_unused_id(&mut self, offset: usize) -> Option> { @@ -236,6 +242,13 @@ pub fn find_unused_id(&mut self, offset: usize) -> Option> { } /// Releases an ID. + /// + /// The `id` must be within bounds. + /// + /// # Panics + /// + /// Panics if `CONFIG_RUST_BITMAP_HARDENED` is enabled and `id` is out of + /// bounds. #[inline] pub fn release_id(&mut self, id: usize) { self.map.clear_bit(id); diff --git a/rust/kernel/scatterlist.rs b/rust/kernel/scatterlist.rs index b83c468b5c63..44eeafed05e3 100644 --- a/rust/kernel/scatterlist.rs +++ b/rust/kernel/scatterlist.rs @@ -350,15 +350,23 @@ fn new( page_vec.push(page.as_ptr(), flags)?; } + // Cap segments at both the DMA mapping-path limit and the device's declared + // max segment size. + // // `dma_max_mapping_size` returns `size_t`, but `sg_alloc_table_from_pages_segment()` takes // an `unsigned int`. // // SAFETY: `dev.as_raw()` is a valid pointer to a `struct device`. - let max_segment = match unsafe { bindings::dma_max_mapping_size(dev.as_raw()) } { + let max_mapping_size = match unsafe { bindings::dma_max_mapping_size(dev.as_raw()) } { 0 => u32::MAX, - max_segment => u32::try_from(max_segment).unwrap_or(u32::MAX), + max_mapping_size => u32::try_from(max_mapping_size).unwrap_or(u32::MAX), }; + // SAFETY: `dev.as_raw()` is a valid pointer to a `struct device`. + let max_seg_size = unsafe { bindings::dma_get_max_seg_size(dev.as_raw()) }; + + let max_segment = max_mapping_size.min(max_seg_size); + Ok(try_pin_init!(&this in Self { // SAFETY: // - `page_vec` is a `KVec` of valid `struct page *` obtained from `pages`. diff --git a/rust/kernel/sync/completion.rs b/rust/kernel/sync/completion.rs index 35ff049ff078..1771bfc0ade2 100644 --- a/rust/kernel/sync/completion.rs +++ b/rust/kernel/sync/completion.rs @@ -38,7 +38,7 @@ /// done <- Completion::new(), /// }), GFP_KERNEL)?; /// -/// let _ = workqueue::system().enqueue(this.clone()); +/// let _ = workqueue::system_dfl().enqueue(this.clone()); /// /// Ok(this) /// } diff --git a/rust/kernel/sync/lock/spinlock.rs b/rust/kernel/sync/lock/spinlock.rs index aafc80125f59..92ad133262b6 100644 --- a/rust/kernel/sync/lock/spinlock.rs +++ b/rust/kernel/sync/lock/spinlock.rs @@ -450,7 +450,7 @@ fn run(this: Arc) { fn spinlock_irq_condvar() -> Result { let testdata = Test::new()?; - let _ = workqueue::system().enqueue(testdata.clone()); + let _ = workqueue::system_dfl().enqueue(testdata.clone()); // Let the updater know when we're ready to wait let mut state = testdata.state.lock(); diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 7e253b6f299c..a872f9fffb90 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -67,7 +67,7 @@ //! /// This method will enqueue the struct for execution on the system workqueue, where its value //! /// will be printed. //! fn print_later(val: Arc) { -//! let _ = workqueue::system().enqueue(val); +//! let _ = workqueue::system_dfl().enqueue(val); //! } //! # print_later(MyStruct::new(42).unwrap()); //! ``` @@ -121,11 +121,11 @@ //! } //! //! fn print_1_later(val: Arc) { -//! let _ = workqueue::system().enqueue::, 1>(val); +//! let _ = workqueue::system_dfl().enqueue::, 1>(val); //! } //! //! fn print_2_later(val: Arc) { -//! let _ = workqueue::system().enqueue::, 2>(val); +//! let _ = workqueue::system_dfl().enqueue::, 2>(val); //! } //! # print_1_later(MyStruct::new(24, 25).unwrap()); //! # print_2_later(MyStruct::new(41, 42).unwrap()); @@ -171,13 +171,13 @@ //! /// This method will enqueue the struct for execution on the system workqueue, where its value //! /// will be printed 12 jiffies later. //! fn print_later(val: Arc) { -//! let _ = workqueue::system().enqueue_delayed(val, 12); +//! let _ = workqueue::system_dfl().enqueue_delayed(val, 12); //! } //! //! /// It is also possible to use the ordinary `enqueue` method together with `DelayedWork`. This //! /// is equivalent to calling `enqueue_delayed` with a delay of zero. //! fn print_now(val: Arc) { -//! let _ = workqueue::system().enqueue(val); +//! let _ = workqueue::system_dfl().enqueue(val); //! } //! # print_later(MyStruct::new(42).unwrap()); //! # print_now(MyStruct::new(42).unwrap()); @@ -1024,20 +1024,32 @@ unsafe impl RawDelayedWorkItem for ARef { } -/// Returns the system work queue (`system_wq`). +/// Returns the system per-cpu work queue (`system_percpu_wq`). /// /// It is the one used by `schedule[_delayed]_work[_on]()`. Multi-CPU multi-threaded. There are /// users which expect relatively short queue flush time. /// /// Callers shouldn't queue work items which can run for too long. -pub fn system() -> &'static Queue { - // SAFETY: `system_wq` is a C global, always available. - unsafe { Queue::from_raw(bindings::system_wq) } +#[inline] +pub fn system_percpu() -> &'static Queue { + // SAFETY: `system_percpu_wq` is a C global, always available. + unsafe { Queue::from_raw(bindings::system_percpu_wq) } +} + +/// Returns the system default (unbound) work queue (`system_dfl_wq`). +/// +/// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items +/// are executed immediately as long as `max_active` limit is not reached and resources are +/// available. +#[inline] +pub fn system_dfl() -> &'static Queue { + // SAFETY: `system_dfl_wq` is a C global, always available. + unsafe { Queue::from_raw(bindings::system_dfl_wq) } } /// Returns the system high-priority work queue (`system_highpri_wq`). /// -/// It is similar to the one returned by [`system`] but for work items which require higher +/// It is similar to the one returned by [`system_percpu`] but for work items which require higher /// scheduling priority. pub fn system_highpri() -> &'static Queue { // SAFETY: `system_highpri_wq` is a C global, always available. @@ -1046,26 +1058,16 @@ pub fn system_highpri() -> &'static Queue { /// Returns the system work queue for potentially long-running work items (`system_long_wq`). /// -/// It is similar to the one returned by [`system`] but may host long running work items. Queue -/// flushing might take relatively long. +/// It is similar to the one returned by [`system_percpu`] but may host long running work items. +/// Queue flushing might take relatively long. pub fn system_long() -> &'static Queue { // SAFETY: `system_long_wq` is a C global, always available. unsafe { Queue::from_raw(bindings::system_long_wq) } } -/// Returns the system unbound work queue (`system_unbound_wq`). -/// -/// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items -/// are executed immediately as long as `max_active` limit is not reached and resources are -/// available. -pub fn system_unbound() -> &'static Queue { - // SAFETY: `system_unbound_wq` is a C global, always available. - unsafe { Queue::from_raw(bindings::system_unbound_wq) } -} - /// Returns the system freezable work queue (`system_freezable_wq`). /// -/// It is equivalent to the one returned by [`system`] except that it's freezable. +/// It is equivalent to the one returned by [`system_percpu`] except that it's freezable. /// /// A freezable workqueue participates in the freeze phase of the system suspend operations. Work /// items on the workqueue are drained and no new work item starts execution until thawed. @@ -1078,7 +1080,7 @@ pub fn system_freezable() -> &'static Queue { /// /// It is inclined towards saving power and is converted to "unbound" variants if the /// `workqueue.power_efficient` kernel parameter is specified; otherwise, it is similar to the one -/// returned by [`system`]. +/// returned by [`system_percpu`]. pub fn system_power_efficient() -> &'static Queue { // SAFETY: `system_power_efficient_wq` is a C global, always available. unsafe { Queue::from_raw(bindings::system_power_efficient_wq) } @@ -1097,7 +1099,7 @@ pub fn system_freezable_power_efficient() -> &'static Queue { /// Returns the system bottom halves work queue (`system_bh_wq`). /// -/// It is similar to the one returned by [`system`] but for work items which +/// It is similar to the one returned by [`system_percpu`] but for work items which /// need to run from a softirq context. pub fn system_bh() -> &'static Queue { // SAFETY: `system_bh_wq` is a C global, always available. diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index 24f96feaeb34..ea2e232b61b1 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -129,7 +129,7 @@ /// # Supported argument types /// - `type`: type which implements the [`Module`] trait (required). /// - `name`: ASCII string literal of the name of the kernel module (required). -/// - `authors`: array of ASCII string literals of the authors of the kernel module. +/// - `authors`: array of string literals of the authors of the kernel module. /// - `description`: string literal of the description of the kernel module. /// - `license`: ASCII string literal of the license of the kernel module (required). /// - `alias`: array of ASCII string literals of the alias names of the kernel module. diff --git a/rust/macros/module.rs b/rust/macros/module.rs index bc7027f8dbb2..0a7b9e24c960 100644 --- a/rust/macros/module.rs +++ b/rust/macros/module.rs @@ -369,7 +369,7 @@ pub(crate) struct ModuleInfo { type_: Type, license: AsciiLitStr, name: AsciiLitStr, - authors: Option>, + authors: Option>, description: Option, alias: Option>, firmware: Option>, diff --git a/rust/zerocopy-derive/README.md b/rust/zerocopy-derive/README.md index d62c79804342..49de31b8e082 100644 --- a/rust/zerocopy-derive/README.md +++ b/rust/zerocopy-derive/README.md @@ -8,7 +8,7 @@ non-ASCII identifiers. For copyright details, please see: - https://github.com/google/zerocopy/blob/v0.8.54/README.md?plain=1 + https://github.com/google/zerocopy/blob/v0.8.54/zerocopy/README.md?plain=1 https://github.com/google/zerocopy/blob/v0.8.54/LICENSE-BSD https://github.com/google/zerocopy/blob/v0.8.54/LICENSE-APACHE https://github.com/google/zerocopy/blob/v0.8.54/LICENSE-MIT diff --git a/rust/zerocopy/README.md b/rust/zerocopy/README.md index 3d11a6502cf0..8443f6166008 100644 --- a/rust/zerocopy/README.md +++ b/rust/zerocopy/README.md @@ -7,7 +7,7 @@ modified to tweak the SPDX license identifiers. For copyright details, please see: - https://github.com/google/zerocopy/blob/v0.8.54/README.md?plain=1 + https://github.com/google/zerocopy/blob/v0.8.54/zerocopy/README.md?plain=1 https://github.com/google/zerocopy/blob/v0.8.54/LICENSE-BSD https://github.com/google/zerocopy/blob/v0.8.54/LICENSE-APACHE https://github.com/google/zerocopy/blob/v0.8.54/LICENSE-MIT diff --git a/scripts/Makefile.vmlinux b/scripts/Makefile.vmlinux index fcae1e432d9a..95b523fe4f9e 100644 --- a/scripts/Makefile.vmlinux +++ b/scripts/Makefile.vmlinux @@ -89,11 +89,8 @@ remove-section-$(CONFIG_ARCH_VMLINUX_NEEDS_RELOCS) += '.rel.*' remove-symbols := -w --strip-unneeded-symbol='__mod_device_table__*' -# To avoid warnings: "empty loadable segment detected at ..." from GNU objcopy, -# it is necessary to remove the PT_LOAD flag from the segment. quiet_cmd_strip_relocs = OBJCOPY $@ - cmd_strip_relocs = $(OBJCOPY) $(patsubst %,--set-section-flags %=noload,$(remove-section-y)) $< $@; \ - $(OBJCOPY) $(addprefix --remove-section=,$(remove-section-y)) $(remove-symbols) $@ + cmd_strip_relocs = $(OBJCOPY) $(addprefix --remove-section=,$(remove-section-y)) $(remove-symbols) $< $@ targets += vmlinux vmlinux: vmlinux.unstripped FORCE @@ -102,21 +99,8 @@ vmlinux: vmlinux.unstripped FORCE # modules.builtin.modinfo # --------------------------------------------------------------------------- -# .modinfo in vmlinux.unstripped is aligned to 8 bytes for compatibility with -# tools that expect vmlinux to have sufficiently aligned sections but the -# additional bytes used for padding .modinfo to satisfy this requirement break -# certain versions of kmod with -# -# depmod: ERROR: kmod_builtin_iter_next: unexpected string without modname prefix -# -# Strip the trailing padding bytes after extracting .modinfo to comply with -# what kmod expects to parse. quiet_cmd_modules_builtin_modinfo = GEN $@ - cmd_modules_builtin_modinfo = $(cmd_objcopy); \ - sed -i 's/\x00\+$$/\x00/g' $@; \ - chmod -x $@ - -OBJCOPYFLAGS_modules.builtin.modinfo := -j .modinfo -O binary + cmd_modules_builtin_modinfo = $(OBJCOPY) -O binary -j .modinfo --dump-section .modinfo=$@ $< /dev/null targets += modules.builtin.modinfo modules.builtin.modinfo: vmlinux.unstripped FORCE diff --git a/scripts/Makefile.vmlinux_o b/scripts/Makefile.vmlinux_o index 24a3a4fd271c..0b37bd5dc3a4 100644 --- a/scripts/Makefile.vmlinux_o +++ b/scripts/Makefile.vmlinux_o @@ -19,7 +19,7 @@ quiet_cmd_gen_initcalls_lds = GEN $@ .tmp_initcalls.lds: $(srctree)/scripts/generate_initcall_order.pl \ vmlinux.a $(KBUILD_VMLINUX_LIBS) FORCE - $(call if_changed,gen_initcalls_lds) + +$(call if_changed,gen_initcalls_lds) targets := .tmp_initcalls.lds diff --git a/scripts/checkkconfigsymbols.py b/scripts/checkkconfigsymbols.py index 36c920e71313..9f7aed98d91c 100755 --- a/scripts/checkkconfigsymbols.py +++ b/scripts/checkkconfigsymbols.py @@ -245,7 +245,7 @@ def tree_is_dirty(): """Return true if the current working tree is dirty (i.e., if any file has been added, deleted, modified, renamed or copied but not committed).""" stdout = execute(["git", "status", "--porcelain"]) - for line in stdout: + for line in stdout.splitlines(): if re.findall(r"[URMADC]{1}", line[:2]): return True return False diff --git a/scripts/checkpatch.pl b/scripts/checkpatch.pl index 8a7787d228a6..f424dafce5bc 100755 --- a/scripts/checkpatch.pl +++ b/scripts/checkpatch.pl @@ -1206,6 +1206,8 @@ sub seed_camelcase_includes { my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`; chomp $git_last_include_commit; $camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit"; + } elsif (not defined $root) { + return; } else { my $last_mod_date = 0; $files = `find $root/include -name "*.h"`; diff --git a/scripts/clang-tools/run-clang-tools.py b/scripts/clang-tools/run-clang-tools.py index e78be82aa693..79d58b34e7ac 100755 --- a/scripts/clang-tools/run-clang-tools.py +++ b/scripts/clang-tools/run-clang-tools.py @@ -12,6 +12,7 @@ compile_commands.json. import argparse import json import multiprocessing +import os import subprocess import sys diff --git a/scripts/gcc-plugins/randomize_layout_plugin.c b/scripts/gcc-plugins/randomize_layout_plugin.c index ff65a4f87f24..e2bd9ba08089 100644 --- a/scripts/gcc-plugins/randomize_layout_plugin.c +++ b/scripts/gcc-plugins/randomize_layout_plugin.c @@ -698,6 +698,63 @@ static void handle_local_var_initializers(void) } } +/* + * Does @container reach a field of type @member_type by a chain of + * by-value members? That is the relationship container_of() expresses -- + * its @member argument may be a dotted path, e.g. + * container_of(inode, struct ceph_inode_info, netfs.inode) -- so a cast + * from @member_type * to @container * is legitimate rather than a + * layout-confusing one. + * + * container_of() used to leave a "void *__mptr" temporary behind, and this + * pass recognised such casts by that name. Commit f9e7a7564834 + * ("container_of: remove local __mptr variable") removed it to stop nested + * container_of() shadowing itself, and the cast now folds to a bare SSA + * copy when the member sits at offset 0, leaving nothing syntactic to key + * on. Match the type relationship instead. + * + * The depth bound keeps this cheap; container_of() paths are one or two + * members deep in practice. + */ +#define CONTAINER_OF_MAX_DEPTH 4 + +static bool is_container_of_cast(const_tree container, const_tree member_type, + int depth) +{ + const_tree field; + + if (container == NULL_TREE || depth > CONTAINER_OF_MAX_DEPTH) + return false; + + if (TREE_CODE(container) != RECORD_TYPE && + TREE_CODE(container) != UNION_TYPE) + return false; + + for (field = TYPE_FIELDS(container); field; field = DECL_CHAIN(field)) { + const_tree field_type; + + if (TREE_CODE(field) != FIELD_DECL) + continue; + + /* + * Only a member at offset 0 can reach here: for any other + * offset container_of()'s subtraction survives folding, the + * cast's rhs stays void *, and the caller skipped it above. + */ + if (!integer_zerop(byte_position(field))) + continue; + + field_type = TYPE_MAIN_VARIANT(TREE_TYPE(field)); + if (field_type == member_type) + return true; + + if (is_container_of_cast(field_type, member_type, depth + 1)) + return true; + } + + return false; +} + /* * iterate over all statements to find "bad" casts: * those where the address of the start of a structure is cast @@ -799,10 +856,8 @@ static unsigned int find_bad_casts_execute(void) #endif MISMATCH(gimple_location(stmt), "op0", ptr_lhs_type, op0_type); } else { - const_tree ssa_name_var = SSA_NAME_VAR(rhs1); /* skip bogus type casts introduced by container_of */ - if (ssa_name_var != NULL_TREE && DECL_NAME(ssa_name_var) && - !strcmp((const char *)DECL_NAME_POINTER(ssa_name_var), "__mptr")) + if (is_container_of_cast(ptr_lhs_type, ptr_rhs_type, 0)) continue; #ifndef __DEBUG_PLUGIN if (lookup_attribute("randomize_performed", TYPE_ATTRIBUTES(ptr_rhs_type))) diff --git a/scripts/gdb/linux/radixtree.py b/scripts/gdb/linux/radixtree.py index bc2954e45c32..8ce9936dfa50 100644 --- a/scripts/gdb/linux/radixtree.py +++ b/scripts/gdb/linux/radixtree.py @@ -27,6 +27,24 @@ def entry_to_node(node): indirect_ptr = node.cast(long_type) & ~constants.LX_RADIX_TREE_INTERNAL_NODE return indirect_ptr.cast(radix_tree_node_type.get_type().pointer()) +def is_node(entry): + # Like xa_is_node(): internal entries below 4096 are sibling, retry + # or zero entries rather than pointers to a struct xa_node. + ulong_type = utils.get_ulong_type() + return is_internal_node(entry) and entry.cast(ulong_type) > 4096 + +def is_sibling(entry): + # Like xa_is_sibling(): a multi-index entry occupies several slots, + # and all but the first hold a sibling entry that encodes the offset + # of the first one. + ulong_type = utils.get_ulong_type() + return is_internal_node(entry) and entry.cast(ulong_type) < \ + xa_mk_internal(constants.LX_RADIX_TREE_MAP_SIZE - 1) + +def sibling_offset(entry): + ulong_type = utils.get_ulong_type() + return int(entry.cast(ulong_type)) >> 2 + def node_maxindex(node): return (constants.LX_RADIX_TREE_MAP_SIZE << node['shift']) - 1 @@ -40,39 +58,35 @@ def resolve_root(root): def lookup(root, index): root = resolve_root(root) - node = root['xa_head'] - if node == 0: - return None + entry = root['xa_head'] - if not (is_internal_node(node)): - if (index > 0): + if is_node(entry): + node = entry_to_node(entry) + if index > node_maxindex(node): return None - return node - node = entry_to_node(node) - maxindex = node_maxindex(node) - - if (index > maxindex): - return None - - shift = node['shift'] + constants.LX_RADIX_TREE_MAP_SHIFT - - while True: - offset = (index >> node['shift']) & constants.LX_RADIX_TREE_MAP_MASK - slot = node['slots'][offset] + # Walk down the tree like xas_load() does. + while True: + offset = (index >> node['shift']) & constants.LX_RADIX_TREE_MAP_MASK + entry = node['slots'][offset] - if slot == 0: - return None + while is_sibling(entry): + entry = node['slots'][sibling_offset(entry)] + if node['shift'] and is_node(entry): + # xas_descend() turns this into a retry entry. + return None - node = slot.cast(node.type.pointer()).dereference() - if node == 0: - return None + if not is_node(entry) or node['shift'] == 0: + break + node = entry_to_node(entry) + elif index > 0: + return None - shift -= constants.LX_RADIX_TREE_MAP_SHIFT - if (shift <= 0): - break + # Empty slots and retry or zero entries hold no data. + if entry == 0 or is_internal_node(entry): + return None - return node + return entry def descend(parent, index): offset = (index >> int(parent["shift"])) & constants.LX_RADIX_TREE_MAP_MASK diff --git a/scripts/gdb/linux/stackdepot.py b/scripts/gdb/linux/stackdepot.py index 37313a5a51a0..aaa18af25cd1 100644 --- a/scripts/gdb/linux/stackdepot.py +++ b/scripts/gdb/linux/stackdepot.py @@ -39,7 +39,7 @@ def stack_depot_fetch(handle): pool_index = parts['pool_index_plus_1'] - 1 if pool_index >= pools_num: - gdb.write("pool index %d out of bounds (%d) for stack id 0x%08x\n" % (parts['pool_index'], pools_num, handle)) + gdb.write("pool index %d out of bounds (%d) for stack id 0x%08x\n" % (pool_index, pools_num, handle)) return gdb.Value(0), 0 stack_pools = gdb.parse_and_eval('stack_pools') diff --git a/scripts/kconfig/conf.c b/scripts/kconfig/conf.c index fe8ba09b0039..31c6fd25e6ec 100644 --- a/scripts/kconfig/conf.c +++ b/scripts/kconfig/conf.c @@ -186,12 +186,23 @@ static void conf_set_all_new_symbols(enum conf_def_mode mode) if (mode == def_random) { int n, p[3]; + bool warned = false; char *env = getenv("KCONFIG_PROBABILITY"); n = 0; while (env && *env) { char *endp; - int tmp = strtol(env, &endp, 10); + long tmp = strtol(env, &endp, 10); + + if (!isdigit((unsigned char)*env) || + (*endp && *endp != ':') || + (*endp == ':' && (!endp[1] || n == 2))) { + if (!warned) { + fprintf(stderr, + "warning: KCONFIG_PROBABILITY has malformed format\n"); + warned = true; + } + } if (tmp >= 0 && tmp <= 100) { p[n++] = tmp; @@ -227,6 +238,9 @@ static void conf_set_all_new_symbols(enum conf_def_mode mode) perror("KCONFIG_PROBABILITY"); exit(1); } + + if (warned && getenv("KCONFIG_WERROR")) + exit(1); } menu_for_each_entry(menu) { @@ -469,6 +483,9 @@ static void conf_choice(struct menu *menu) } printf("\n"); } + /* Nothing to ask if none of the choice values is visible. */ + if (!cnt) + return; printf("%*schoice", indent - 1, ""); if (cnt == 1) { printf("[1]: 1\n"); diff --git a/scripts/kconfig/symbol.c b/scripts/kconfig/symbol.c index 7e81b3676ee9..1536db1599f4 100644 --- a/scripts/kconfig/symbol.c +++ b/scripts/kconfig/symbol.c @@ -157,7 +157,12 @@ static long long sym_get_range_val(struct symbol *sym, int base) return strtoll(sym->curr.val, NULL, base); } -static void sym_validate_range(struct symbol *sym) +/* + * Return the nearest range bound for an out-of-range default value. + * Return NULL if the value is valid or the symbol has no active range. + */ +static struct symbol *sym_get_near_range_bound(struct symbol *sym, + const char *value) { struct property *prop; struct symbol *range_sym; @@ -172,21 +177,31 @@ static void sym_validate_range(struct symbol *sym) base = 16; break; default: - return; + return NULL; } prop = sym_get_range_prop(sym); if (!prop) - return; - val = strtoll(sym->curr.val, NULL, base); + return NULL; + val = strtoll(value, NULL, base); range_sym = prop->expr->left.sym; val2 = sym_get_range_val(range_sym, base); if (val >= val2) { range_sym = prop->expr->right.sym; val2 = sym_get_range_val(range_sym, base); if (val <= val2) - return; + return NULL; } - sym->curr.val = range_sym->curr.val; + + return range_sym; +} + +static void sym_validate_range(struct symbol *sym) +{ + struct symbol *range_sym; + + range_sym = sym_get_near_range_bound(sym, sym->curr.val); + if (range_sym) + sym->curr.val = range_sym->curr.val; } static void sym_set_changed(struct symbol *sym) @@ -812,7 +827,7 @@ bool sym_set_string_value(struct symbol *sym, const char *newval) const char *sym_get_string_default(struct symbol *sym) { struct property *prop; - struct symbol *ds; + struct symbol *ds, *range_sym; const char *str = ""; tristate val; @@ -830,11 +845,6 @@ const char *sym_get_string_default(struct symbol *sym) val = EXPR_AND(expr_calc_value(prop->expr), prop->visible.tri); break; default: - /* - * The following fails to handle the situation - * where a default value is further limited by - * the valid range. - */ ds = prop_get_symbol(prop); if (ds != NULL) { sym_calc_value(ds); @@ -878,6 +888,11 @@ const char *sym_get_string_default(struct symbol *sym) default: break; } + + range_sym = sym_get_near_range_bound(sym, str); + if (range_sym) + str = range_sym->curr.val; + return str; } diff --git a/scripts/kconfig/tests/conftest.py b/scripts/kconfig/tests/conftest.py index 66f95e4ed58c..1f25de43128d 100644 --- a/scripts/kconfig/tests/conftest.py +++ b/scripts/kconfig/tests/conftest.py @@ -57,9 +57,12 @@ class Conf: # Override 'srctree' environment to make the test as the top directory extra_env['srctree'] = self._test_dir - # Clear KCONFIG_DEFCONFIG_LIST to keep unit tests from being affected - # by the user's environment. - extra_env['KCONFIG_DEFCONFIG_LIST'] = '' + # Clear all KCONFIG_* environment variables + env = { + varname: os.environ[varname] + for varname in os.environ.keys() + if not varname.startswith("KCONFIG_") + } # Run Kconfig in a temporary directory. # This directory is automatically removed when done. @@ -75,7 +78,7 @@ class Conf: stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=temp_dir, - env=dict(os.environ, **extra_env)) + env=dict(env, **extra_env)) # If input key sequence is given, feed it to stdin. if in_keys: @@ -232,7 +235,8 @@ class Conf: dot_config: .config file for input returncode: exit status of the Kconfig executable """ - return self._run_conf('--savedefconfig', out_file='defconfig') + return self._run_conf('--savedefconfig={}'.format(out_file), + dot_config=dot_config, out_file='defconfig') def listnewconfig(self, dot_config=None): """Run listnewconfig. @@ -312,6 +316,12 @@ class Conf: return self._matches('stderr', expected) +@pytest.fixture(autouse=True) +def clear_werror(monkeypatch): + # extra_env can set strict mode, but cannot remove an inherited flag. + monkeypatch.delenv('KCONFIG_WERROR', raising=False) + + @pytest.fixture(scope="module") def conf(request): """Create a Conf instance and provide it to test functions.""" diff --git a/scripts/kconfig/tests/randconfig_probability/Kconfig b/scripts/kconfig/tests/randconfig_probability/Kconfig new file mode 100644 index 000000000000..84f4e5fcc51e --- /dev/null +++ b/scripts/kconfig/tests/randconfig_probability/Kconfig @@ -0,0 +1,12 @@ +# SPDX-License-Identifier: GPL-2.0-only + +config MODULES + bool + default y + modules + +config BOOL + bool "Bool" + +config TRI + tristate "Tristate" diff --git a/scripts/kconfig/tests/randconfig_probability/__init__.py b/scripts/kconfig/tests/randconfig_probability/__init__.py new file mode 100644 index 000000000000..e6e5dda10ad9 --- /dev/null +++ b/scripts/kconfig/tests/randconfig_probability/__init__.py @@ -0,0 +1,130 @@ +# SPDX-License-Identifier: GPL-2.0-only +"""Validate KCONFIG_PROBABILITY without changing the supported distributions.""" + + +def test_malformed_warns(conf): + probabilities = [ + 'invalid', ' ', '50%', '50 ', '0x32', '10 20', '10:20x', + '10:20:invalid', '10:20:30x', + ':50', '50:', '10::20', '10:20:', '10:20:30:', '10:20:30:40', + '-0', '+0', '+', '-', '+100:0', ' \t100:0', '0: \t100:0', + ] + for probability in probabilities: + assert conf._run_conf('--randconfig', extra_env={ + 'KCONFIG_PROBABILITY': probability, + 'KCONFIG_SEED': '0', + }) == 0, repr(probability) + assert ('warning: KCONFIG_PROBABILITY has malformed format' in + conf.stderr), repr(probability) + assert conf.stderr.count('warning:') == 1, repr(probability) + assert conf.config is not None, repr(probability) + + +def test_malformed_preserves_config(conf): + probabilities = [('50%', '50:0:0'), ('-0', '0')] + for seed in range(20): + for probability, equivalent in probabilities: + context = 'probability={!r}, equivalent={!r}, seed={}'.format( + probability, equivalent, seed) + assert conf._run_conf('--randconfig', extra_env={ + 'KCONFIG_PROBABILITY': probability, + 'KCONFIG_SEED': hex(seed), + }) == 0, context + assert ('warning: KCONFIG_PROBABILITY has malformed format' in + conf.stderr), context + assert conf.stderr.count('warning:') == 1, context + malformed = conf.config + + assert conf._run_conf('--randconfig', extra_env={ + 'KCONFIG_PROBABILITY': equivalent, + 'KCONFIG_SEED': hex(seed), + }) == 0, context + assert 'warning:' not in conf.stderr, context + assert conf.config == malformed, context + + +def test_werror(conf): + probabilities = [ + ('', 0), ('50', 0), ('50%', 1), ('-0', 1), ('10:20:30:40', 1), + ] + for probability, status in probabilities: + for werror in ['', '0', '1']: + context = 'probability={!r}, werror={!r}'.format( + probability, werror) + assert conf._run_conf('--randconfig', extra_env={ + 'KCONFIG_PROBABILITY': probability, + 'KCONFIG_SEED': '0', + 'KCONFIG_WERROR': werror, + }) == status, context + if status: + assert ('warning: KCONFIG_PROBABILITY has malformed format' in + conf.stderr), context + assert conf.stderr.count('warning:') == 1, context + else: + assert 'warning:' not in conf.stderr, context + + +def test_out_of_range(conf): + probabilities = [ + '-1', '101', '+101', '0:101', '0:0:101', '60:41', '0:60:41', + '4294967296', '-4294967296', + '999999999999999999999999', '-999999999999999999999999', + ] + for probability in probabilities: + assert conf._run_conf('--randconfig', extra_env={ + 'KCONFIG_PROBABILITY': probability, + 'KCONFIG_SEED': '0', + }) == 1, repr(probability) + assert 'KCONFIG_PROBABILITY:' in conf.stderr, repr(probability) + + +def test_valid(conf): + probabilities = [ + ('0', 'n', 'n'), + ('0:0', 'n', 'n'), + ('100:0', 'y', 'y'), + ('0:100', 'y', 'm'), + ('100:0:0', 'y', 'n'), + ('0:100:0', 'n', 'y'), + ('0:0:100', 'n', 'm'), + ('000:000:100', 'n', 'm'), + ] + for probability, boolean, tristate in probabilities: + assert conf._run_conf('--randconfig', extra_env={ + 'KCONFIG_PROBABILITY': probability, + 'KCONFIG_SEED': '0', + }) == 0, repr(probability) + assert 'warning:' not in conf.stderr, repr(probability) + for symbol, value in [('BOOL', boolean), ('TRI', tristate)]: + if value == 'n': + expected = '# CONFIG_{} is not set'.format(symbol) + else: + expected = 'CONFIG_{}={}'.format(symbol, value) + assert expected in conf.config.splitlines(), repr(probability) + + +def test_single_probability_matches_tristate_split(conf): + for seed in range(20): + context = 'seed={}'.format(seed) + assert conf._run_conf('--randconfig', extra_env={ + 'KCONFIG_PROBABILITY': '50', + 'KCONFIG_SEED': hex(seed), + }) == 0, context + assert 'warning:' not in conf.stderr, context + single = conf.config + + # 50% boolean y; 25% tristate y, 25% m, and 50% n. + assert conf._run_conf('--randconfig', extra_env={ + 'KCONFIG_PROBABILITY': '50:25:25', + 'KCONFIG_SEED': hex(seed), + }) == 0, context + assert 'warning:' not in conf.stderr, context + assert conf.config == single, context + + +def test_empty(conf): + assert conf._run_conf('--randconfig', extra_env={ + 'KCONFIG_PROBABILITY': '', + 'KCONFIG_SEED': '0', + }) == 0 + assert 'warning:' not in conf.stderr diff --git a/scripts/kconfig/tests/savedefconfig_range/Kconfig b/scripts/kconfig/tests/savedefconfig_range/Kconfig new file mode 100644 index 000000000000..fd59d9082ed5 --- /dev/null +++ b/scripts/kconfig/tests/savedefconfig_range/Kconfig @@ -0,0 +1,60 @@ +# SPDX-License-Identifier: GPL-2.0 + +# Static default and range values + +config INT_DEFAULT_ABOVE_RANGE + int + range 1 1 + default 16 + +config INT_DEFAULT_BELOW_RANGE + int + range 4 8 + default 2 + +# Default and range values determined by other options + +config RANGE_UPPER_BOUND + int + default 3 + +config INT_DYNAMIC_RANGE + int + range 0 RANGE_UPPER_BOUND + default 4 + +# Hex + +config HEX_DEFAULT_ABOVE_RANGE + hex + range 0x10 0x20 + default 0x40 + +# Implicit default value of 0 + +config INT_IMPLICIT_DEFAULT_ZERO + int + range 1 4 + +# Conditional range + +config USE_FIRST_RANGE + bool + default y + +config INT_CONDITIONAL_RANGE + int + range 1 2 if USE_FIRST_RANGE + range 3 4 if !USE_FIRST_RANGE + default 3 + +# Conditional default + +config USE_DEFAULT + bool + default y + +config INT_CONDITIONAL_DEFAULT + int + range 1 2 + default 3 if USE_DEFAULT diff --git a/scripts/kconfig/tests/savedefconfig_range/__init__.py b/scripts/kconfig/tests/savedefconfig_range/__init__.py new file mode 100644 index 000000000000..961454be732c --- /dev/null +++ b/scripts/kconfig/tests/savedefconfig_range/__init__.py @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: GPL-2.0 +"""Test savedefconfig with numerical defaults outside of ranges.""" + + +def test(conf): + assert conf._run_conf('--savedefconfig=defconfig', dot_config='config', + out_file='defconfig') == 0 + assert conf.config_matches('expected_defconfig') diff --git a/scripts/kconfig/tests/savedefconfig_range/config b/scripts/kconfig/tests/savedefconfig_range/config new file mode 100644 index 000000000000..d939cfe5fd34 --- /dev/null +++ b/scripts/kconfig/tests/savedefconfig_range/config @@ -0,0 +1,7 @@ +CONFIG_INT_DEFAULT_ABOVE_RANGE=1 +CONFIG_INT_DEFAULT_BELOW_RANGE=4 +CONFIG_INT_DYNAMIC_RANGE=3 +CONFIG_HEX_DEFAULT_ABOVE_RANGE=0x20 +CONFIG_INT_IMPLICIT_DEFAULT_ZERO=1 +CONFIG_INT_CONDITIONAL_RANGE=2 +CONFIG_INT_CONDITIONAL_DEFAULT=2 diff --git a/scripts/kconfig/tests/savedefconfig_range/expected_defconfig b/scripts/kconfig/tests/savedefconfig_range/expected_defconfig new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/scripts/make_fit.py b/scripts/make_fit.py index 15ba26974fd7..9bd35aa72119 100755 --- a/scripts/make_fit.py +++ b/scripts/make_fit.py @@ -292,7 +292,8 @@ def process_dtb(fname, args): if 'scripts/dtc/fdtoverlay' in cmd: # This depends on the structure of the composite DTB command - files = cmd.split() + # Ignore any subsequent commands, such as schema validation + files = cmd.split(';', 1)[0].split() files = files[files.index('-i') + 1:] else: files = [fname] diff --git a/security/apparmor/af_inet.c b/security/apparmor/af_inet.c index 516c9016537c..2a933572fa95 100644 --- a/security/apparmor/af_inet.c +++ b/security/apparmor/af_inet.c @@ -196,6 +196,9 @@ static int bind_map_addr(const struct sock *sk, struct sockaddr *addr, * AF_UNSPEC if the address is INADDR_ANY */ addr4 = (struct sockaddr_in *)addr; + /* Length check from inet_bind_sk() */ + if (addrlen < sizeof(struct sockaddr_in)) + return -EINVAL; if (addr4->sin_addr.s_addr != htonl(INADDR_ANY)) return -EAFNOSUPPORT; family = AF_INET; @@ -425,7 +428,7 @@ int aa_inet_connect_perm(struct socket *sock, struct sockaddr *addr, if (addrlen < offsetofend(struct sockaddr, sa_family)) return -EINVAL; if (addr->sa_family == AF_UNSPEC) - return 0; + return aa_sk_perm(OP_CONNECT, AA_MAY_CONNECT, sock->sk); /* do we need early bailout for !family ... */ return sk_has_perm2(sock->sk, OP_CONNECT, AA_MAY_CONNECT, profile, ad, diff --git a/security/apparmor/include/match.h b/security/apparmor/include/match.h index f7bd7855f1bd..66485f76d331 100644 --- a/security/apparmor/include/match.h +++ b/security/apparmor/include/match.h @@ -12,6 +12,7 @@ #define __AA_MATCH_H #include +#include #define DFA_NOMATCH 0 #define DFA_START 1 @@ -120,7 +121,15 @@ struct aa_dfa { static inline size_t table_size(size_t len, size_t el_size) { - return ALIGN(sizeof(struct table_header) + len * el_size, 8); + size_t size; + + /* Need check_*_overflow for 32 bit machines */ + if (check_mul_overflow(len, el_size, &size) || + check_add_overflow(size, sizeof(struct table_header), &size) || + size > SIZE_MAX - 7) + return 0; + + return ALIGN(size, 8); } #define aa_state_t unsigned int diff --git a/security/apparmor/label.c b/security/apparmor/label.c index 42ed476fe89d..fd67262330f9 100644 --- a/security/apparmor/label.c +++ b/security/apparmor/label.c @@ -1954,12 +1954,18 @@ struct aa_label *aa_label_strn_parse(struct aa_label *base, const char *str, goto out; } - if (create) + if (create) { label = aa_vec_find_or_create_label(vec, len, gfp); - else + if (!label) { + /* not absence: creating only fails on allocation */ + label = ERR_PTR(-ENOMEM); + goto out; + } + } else { label = vec_find(vec, len); - if (!label) - goto fail; + if (!label) + goto fail; + } out: /* use adjusted len from after vec_unique, not original */ diff --git a/security/apparmor/lsm.c b/security/apparmor/lsm.c index d502ad0ac26f..de6633e238f3 100644 --- a/security/apparmor/lsm.c +++ b/security/apparmor/lsm.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -1405,6 +1406,23 @@ static int apparmor_socket_connect(struct socket *sock, return aa_sk_perm(OP_CONNECT, AA_MAY_CONNECT, sock->sk); } +static int apparmor_sctp_bind_connect(struct sock *sk, int optname, + struct sockaddr *address, int addrlen) +{ + switch (optname) { + /* Bind checks */ + case SCTP_SET_PEER_PRIMARY_ADDR: + case SCTP_SOCKOPT_BINDX_ADD: + return aa_sk_perm(OP_BIND, AA_MAY_BIND, sk); + /* Connect checks */ + case SCTP_SOCKOPT_CONNECTX: + case SCTP_SENDMSG_CONNECT: + return aa_sk_perm(OP_CONNECT, AA_MAY_CONNECT, sk); + } + + return 0; +} + static int apparmor_socket_listen(struct socket *sock, int backlog) { AA_BUG(!sock); @@ -1823,6 +1841,7 @@ static struct security_hook_list apparmor_hooks[] __ro_after_init = { LSM_HOOK_INIT(socket_getsockopt, apparmor_socket_getsockopt), LSM_HOOK_INIT(socket_setsockopt, apparmor_socket_setsockopt), LSM_HOOK_INIT(socket_shutdown, apparmor_socket_shutdown), + LSM_HOOK_INIT(sctp_bind_connect, apparmor_sctp_bind_connect), #ifdef CONFIG_NETWORK_SECMARK LSM_HOOK_INIT(socket_sock_rcv_skb, apparmor_socket_sock_rcv_skb), #endif diff --git a/security/apparmor/match.c b/security/apparmor/match.c index ca30a4292c42..cf3b35a6b1cd 100644 --- a/security/apparmor/match.c +++ b/security/apparmor/match.c @@ -58,7 +58,7 @@ static struct table_header *unpack_table(const char *blob, size_t bsize) if (th.td_lolen == 0) goto out; tsize = table_size(th.td_lolen, th.td_flags); - if (bsize < tsize) + if (!tsize || bsize < tsize) goto out; table = kvzalloc(tsize, GFP_KERNEL); @@ -281,6 +281,10 @@ static struct table_header *remap_data16_to_data32(struct table_header *old) u32 i; tsize = table_size(old->td_lolen, YYTD_DATA32); + if (!tsize) { + kvfree(old); + return NULL; + } new = kvzalloc(tsize, GFP_KERNEL); if (!new) { kvfree(old); @@ -613,7 +617,7 @@ aa_state_t aa_dfa_match_until(const struct aa_dfa *dfa, aa_state_t start, u32 *next = NEXT_TABLE(dfa); u32 *check = CHECK_TABLE(dfa); u32 *accept = ACCEPT_TABLE(dfa); - aa_state_t state = start, pos; + aa_state_t state = start; if (state == DFA_NOMATCH) return DFA_NOMATCH; @@ -624,22 +628,18 @@ aa_state_t aa_dfa_match_until(const struct aa_dfa *dfa, aa_state_t start, u8 *equiv = EQUIV_TABLE(dfa); /* default is direct to next state */ while (*str) { - pos = base_idx(base[state]) + equiv[(u8) *str++]; - if (check[pos] == state) - state = next[pos]; - else - state = def[state]; + u8 c = equiv[(u8) *str++]; + + match_char(state, def, base, next, check, c); if (accept[state]) break; } } else { /* default is direct to next state */ while (*str) { - pos = base_idx(base[state]) + (u8) *str++; - if (check[pos] == state) - state = next[pos]; - else - state = def[state]; + u8 c = (u8) *str++; + + match_char(state, def, base, next, check, c); if (accept[state]) break; } @@ -674,7 +674,7 @@ aa_state_t aa_dfa_matchn_until(const struct aa_dfa *dfa, aa_state_t start, u32 *next = NEXT_TABLE(dfa); u32 *check = CHECK_TABLE(dfa); u32 *accept = ACCEPT_TABLE(dfa); - aa_state_t state = start, pos; + aa_state_t state = start; *retpos = NULL; if (state == DFA_NOMATCH) @@ -686,22 +686,18 @@ aa_state_t aa_dfa_matchn_until(const struct aa_dfa *dfa, aa_state_t start, u8 *equiv = EQUIV_TABLE(dfa); /* default is direct to next state */ for (; n; n--) { - pos = base_idx(base[state]) + equiv[(u8) *str++]; - if (check[pos] == state) - state = next[pos]; - else - state = def[state]; + u8 c = equiv[(u8) *str++]; + + match_char(state, def, base, next, check, c); if (accept[state]) break; } } else { /* default is direct to next state */ for (; n; n--) { - pos = base_idx(base[state]) + (u8) *str++; - if (check[pos] == state) - state = next[pos]; - else - state = def[state]; + u8 c = (u8) *str++; + + match_char(state, def, base, next, check, c); if (accept[state]) break; } @@ -750,7 +746,7 @@ static aa_state_t leftmatch_fb(const struct aa_dfa *dfa, aa_state_t start, u32 *base = BASE_TABLE(dfa); u32 *next = NEXT_TABLE(dfa); u32 *check = CHECK_TABLE(dfa); - aa_state_t state = start, pos; + aa_state_t state = start; AA_BUG(!dfa); AA_BUG(!str); @@ -768,13 +764,10 @@ static aa_state_t leftmatch_fb(const struct aa_dfa *dfa, aa_state_t start, /* default is direct to next state */ while (*str) { unsigned int adjust; + u8 c = equiv[(u8) *str++]; wb->history[wb->pos] = state; - pos = base_idx(base[state]) + equiv[(u8) *str++]; - if (check[pos] == state) - state = next[pos]; - else - state = def[state]; + match_char(state, def, base, next, check, c); if (is_loop(wb, state, &adjust)) { state = aa_dfa_match(dfa, state, str); *count -= adjust; @@ -787,13 +780,10 @@ static aa_state_t leftmatch_fb(const struct aa_dfa *dfa, aa_state_t start, /* default is direct to next state */ while (*str) { unsigned int adjust; + u8 c = (u8) *str++; wb->history[wb->pos] = state; - pos = base_idx(base[state]) + (u8) *str++; - if (check[pos] == state) - state = next[pos]; - else - state = def[state]; + match_char(state, def, base, next, check, c); if (is_loop(wb, state, &adjust)) { state = aa_dfa_match(dfa, state, str); *count -= adjust; diff --git a/security/apparmor/net.c b/security/apparmor/net.c index a333e6aff926..136d14226b97 100644 --- a/security/apparmor/net.c +++ b/security/apparmor/net.c @@ -24,6 +24,7 @@ struct aa_sfs_entry aa_sfs_entry_network[] = { AA_SFS_FILE_STRING("af_mask", AA_SFS_AF_MASK), AA_SFS_FILE_BOOLEAN("tcp-fast-open", 1), + AA_SFS_FILE_BOOLEAN("sctp", 1), { } }; @@ -260,7 +261,6 @@ int aa_profile_af_perm(struct aa_profile *profile, AA_BUG(family >= AF_MAX); AA_BUG(type < 0 || type >= SOCK_MAX); - AA_BUG(profile_unconfined(profile)); state = RULE_MEDIATES_NET(rules); if (state) { @@ -268,7 +268,7 @@ int aa_profile_af_perm(struct aa_profile *profile, type, protocol, &p, &ad->info); return aa_do_perms(profile, rules->policy, state, request, p, ad); - } /* else */ + } /* else - not mediated this covers the profile_unconfined() case */ return 0; } diff --git a/security/apparmor/policy_ns.c b/security/apparmor/policy_ns.c index ae9168c1a85e..7d5c768493e8 100644 --- a/security/apparmor/policy_ns.c +++ b/security/apparmor/policy_ns.c @@ -265,10 +265,12 @@ struct aa_ns *__aa_find_or_create_ns(struct aa_ns *parent, const char *name, /* try and find the specified ns */ /* released by caller */ ns = aa_get_ns(__aa_find_ns(&parent->sub_ns, name)); - if (!ns) + if (!ns) { ns = __aa_create_ns(parent, name, dir); - else + } else { + aa_put_ns(ns); ns = ERR_PTR(-EEXIST); + } /* return ref */ return ns; diff --git a/security/apparmor/policy_unpack.c b/security/apparmor/policy_unpack.c index 99dd61e3b103..35dfa3b451f3 100644 --- a/security/apparmor/policy_unpack.c +++ b/security/apparmor/policy_unpack.c @@ -558,6 +558,9 @@ static int unpack_strs_table(struct aa_ext *e, const char *name, bool multi, /* aa_unpack_strdup verifies that the last character is * null termination byte. */ + /* publish before validating; the error path frees it */ + table[i].strs = str; + table[i].size = size2; c = process_strs_entry(str, size2, multi); if (c <= 0) { AA_DEBUG(DEBUG_UNPACK, "process_strs %d i %d pos %ld", @@ -570,9 +573,7 @@ static int unpack_strs_table(struct aa_ext *e, const char *name, bool multi, /* fail - all other cases with embedded \0 */ goto fail; } - table[i].strs = str; table[i].count = c; - table[i].size = size2; } if (!aa_unpack_nameX(e, AA_ARRAYEND, NULL)) goto fail; @@ -1052,6 +1053,11 @@ static int unpack_pdb(struct aa_ext *e, struct aa_policydb **policy, u16 tdflags = pdb->dfa->tables[YYTD_ID_ACCEPT]->td_flags; size_t tsize = table_size(noents, tdflags); + if (!tsize) { + *info = "invalid dfa flags table size"; + error = -EPROTO; + goto fail; + } pdb->dfa->tables[YYTD_ID_ACCEPT2] = kvzalloc(tsize, GFP_KERNEL); if (!pdb->dfa->tables[YYTD_ID_ACCEPT2]) { *info = "failed to alloc dfa flags table"; diff --git a/security/integrity/ima/ima_template.c b/security/integrity/ima/ima_template.c index 7034573fb41e..2467caefbd70 100644 --- a/security/integrity/ima/ima_template.c +++ b/security/integrity/ima/ima_template.c @@ -450,6 +450,11 @@ int ima_restore_measurement_list(loff_t size, void *buf) return -EINVAL; } + if (khdr->buffer_size > size) { + pr_err("attempting to restore a corrupted measurement list"); + return -EINVAL; + } + bitmap_zero(hdr_mask, HDR__LAST); bitmap_set(hdr_mask, HDR_PCR, 1); bitmap_set(hdr_mask, HDR_DIGEST, 1); diff --git a/security/ipe/audit.c b/security/ipe/audit.c index 93fb59fbddd6..a299bb35e0d1 100644 --- a/security/ipe/audit.c +++ b/security/ipe/audit.c @@ -262,18 +262,10 @@ void ipe_audit_policy_load(const struct ipe_policy *const p) */ void ipe_audit_enforce(bool new_enforce, bool old_enforce) { - struct audit_buffer *ab; - - ab = audit_log_start(audit_context(), GFP_KERNEL, AUDIT_MAC_STATUS); - if (!ab) - return; - audit_log(audit_context(), GFP_KERNEL, AUDIT_MAC_STATUS, "enforcing=%d old_enforcing=%d auid=%u ses=%u" " enabled=1 old-enabled=1 lsm=ipe res=1", new_enforce, old_enforce, from_kuid(&init_user_ns, audit_get_loginuid(current)), audit_get_sessionid(current)); - - audit_log_end(ab); } diff --git a/security/security.c b/security/security.c index 2ee276ab15c5..208738238e37 100644 --- a/security/security.c +++ b/security/security.c @@ -2486,9 +2486,8 @@ void security_backing_file_free(struct file *backing_file) { void *blob = backing_file_security(backing_file); - call_void_hook(backing_file_free, backing_file); - if (blob) { + call_void_hook(backing_file_free, backing_file); backing_file_set_security(backing_file, NULL); kmem_cache_free(lsm_backing_file_cache, blob); } diff --git a/security/selinux/netlabel.c b/security/selinux/netlabel.c index d51dfe892312..24b11d1891d8 100644 --- a/security/selinux/netlabel.c +++ b/security/selinux/netlabel.c @@ -557,9 +557,10 @@ static int selinux_netlbl_socket_connect_helper(struct sock *sk, * is set to AF_UNSPEC, if that is what is happening we want to reset * the socket */ if (addr->sa_family == AF_UNSPEC) { - netlbl_sock_delattr(sk); + rc = netlbl_sock_delattr(sk); + if (rc) + return rc; sksec->nlbl_state = NLBL_REQSKB; - rc = 0; return rc; } secattr = selinux_netlbl_sock_genattr(sk); diff --git a/security/smack/smack_lsm.c b/security/smack/smack_lsm.c index 8e88ac65fd7f..3dd6c1ec15ca 100644 --- a/security/smack/smack_lsm.c +++ b/security/smack/smack_lsm.c @@ -2653,22 +2653,26 @@ static int smack_netlbl_add(struct sock *sk) * * Remove the outbound smack value from a socket */ -static void smack_netlbl_delete(struct sock *sk) +static int smack_netlbl_delete(struct sock *sk) { struct socket_smack *ssp = smack_sock(sk); + int rc; /* * Take the label off the socket if one is set. */ if (ssp->smk_state != SMK_NETLBL_LABELED) - return; + return 0; local_bh_disable(); bh_lock_sock_nested(sk); - netlbl_sock_delattr(sk); + rc = netlbl_sock_delattr(sk); bh_unlock_sock(sk); local_bh_enable(); + if (rc) + return rc; ssp->smk_state = SMK_NETLBL_UNLABELED; + return 0; } /** @@ -2708,7 +2712,7 @@ static int smk_ipv4_check(struct sock *sk, struct sockaddr_in *sap) * Clear the socket netlabel if it's set. */ if (!rc) - smack_netlbl_delete(sk); + rc = smack_netlbl_delete(sk); } rcu_read_unlock(); @@ -4545,7 +4549,7 @@ static int smack_inet_conn_request(const struct sock *sk, struct sk_buff *skb, if (hskp == NULL) rc = netlbl_req_setattr(req, &ssp->smk_out->smk_netlabel); else - netlbl_req_delattr(req); + rc = netlbl_req_delattr(req); return rc; } diff --git a/sound/core/control_led.c b/sound/core/control_led.c index ec0e6c7ad657..501387287ae6 100644 --- a/sound/core/control_led.c +++ b/sound/core/control_led.c @@ -563,12 +563,43 @@ static ssize_t set_led_id(struct snd_ctl_led_card *led_card, const char *buf, si return count; } +/* + * snd_ctl_led_disconnect() removes these files with card->controls_rwsem + * held. so don't let the removal wait for a callback that takes it. + */ +static struct kernfs_node *snd_ctl_led_sysfs_enter(struct device *dev, + struct device_attribute *attr) +{ + struct kernfs_node *kn; + + if (!try_module_get(THIS_MODULE)) + return NULL; + kn = sysfs_break_active_protection(&dev->kobj, &attr->attr); + if (!kn) + module_put(THIS_MODULE); + return kn; +} + +static void snd_ctl_led_sysfs_exit(struct kernfs_node *kn) +{ + sysfs_unbreak_active_protection(kn); + module_put(THIS_MODULE); +} + static ssize_t attach_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct snd_ctl_led_card *led_card = container_of(dev, struct snd_ctl_led_card, dev); - return set_led_id(led_card, buf, count, true); + struct kernfs_node *kn; + ssize_t ret; + + kn = snd_ctl_led_sysfs_enter(dev, attr); + if (!kn) + return -ENODEV; + ret = set_led_id(led_card, buf, count, true); + snd_ctl_led_sysfs_exit(kn); + return ret; } static ssize_t detach_store(struct device *dev, @@ -576,7 +607,15 @@ static ssize_t detach_store(struct device *dev, const char *buf, size_t count) { struct snd_ctl_led_card *led_card = container_of(dev, struct snd_ctl_led_card, dev); - return set_led_id(led_card, buf, count, false); + struct kernfs_node *kn; + ssize_t ret; + + kn = snd_ctl_led_sysfs_enter(dev, attr); + if (!kn) + return -ENODEV; + ret = set_led_id(led_card, buf, count, false); + snd_ctl_led_sysfs_exit(kn); + return ret; } static ssize_t reset_store(struct device *dev, @@ -594,10 +633,8 @@ static ssize_t reset_store(struct device *dev, return count; } -static ssize_t list_show(struct device *dev, - struct device_attribute *attr, char *buf) +static ssize_t snd_ctl_led_list(struct snd_ctl_led_card *led_card, char *buf) { - struct snd_ctl_led_card *led_card = container_of(dev, struct snd_ctl_led_card, dev); struct snd_ctl_led_ctl *lctl; size_t l = 0; struct snd_card *card __free(snd_card_unref) = @@ -620,6 +657,21 @@ static ssize_t list_show(struct device *dev, return l; } +static ssize_t list_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct snd_ctl_led_card *led_card = container_of(dev, struct snd_ctl_led_card, dev); + struct kernfs_node *kn; + ssize_t ret; + + kn = snd_ctl_led_sysfs_enter(dev, attr); + if (!kn) + return -ENODEV; + ret = snd_ctl_led_list(led_card, buf); + snd_ctl_led_sysfs_exit(kn); + return ret; +} + static DEVICE_ATTR_WO(attach); static DEVICE_ATTR_WO(detach); static DEVICE_ATTR_WO(reset); diff --git a/sound/core/ctljack.c b/sound/core/ctljack.c index 6b6ab34fbde8..36700fda79f3 100644 --- a/sound/core/ctljack.c +++ b/sound/core/ctljack.c @@ -38,6 +38,7 @@ static int get_available_index(struct snd_card *card, const char *name) sid.iface = SNDRV_CTL_ELEM_IFACE_CARD; strscpy(sid.name, name, sizeof(sid.name)); + guard(rwsem_read)(&card->controls_rwsem); while (snd_ctl_find_id(card, &sid)) { sid.index++; /* reset numid; otherwise snd_ctl_find_id() hits this again */ diff --git a/sound/core/info.c b/sound/core/info.c index 3b8ccda04e1a..c4d57d0809ad 100644 --- a/sound/core/info.c +++ b/sound/core/info.c @@ -528,6 +528,8 @@ int snd_info_card_register(struct snd_card *card) void snd_info_card_id_change(struct snd_card *card) { guard(mutex)(&info_mutex); + if (card->shutdown) + return; if (card->proc_root_link) { proc_remove(card->proc_root_link); card->proc_root_link = NULL; @@ -555,7 +557,6 @@ void snd_info_card_disconnect(struct snd_card *card) if (card->proc_root) snd_info_clear_entries(card->proc_root); card->proc_root_link = NULL; - card->proc_root = NULL; } /* diff --git a/sound/core/init.c b/sound/core/init.c index a51b71812fd9..972db4a8cea6 100644 --- a/sound/core/init.c +++ b/sound/core/init.c @@ -82,8 +82,24 @@ static int module_slot_match(struct module *module, int idx) } #if IS_ENABLED(CONFIG_SND_MIXER_OSS) -int (*snd_mixer_oss_notify_callback)(struct snd_card *card, int free_flag); -EXPORT_SYMBOL(snd_mixer_oss_notify_callback); +static DEFINE_MUTEX(mixer_oss_notify_mutex); +static int (*mixer_oss_notify_callback)(struct snd_card *card, int cmd); + +void snd_mixer_oss_notify(struct snd_card *card, int cmd) +{ + guard(mutex)(&mixer_oss_notify_mutex); + if (mixer_oss_notify_callback) + mixer_oss_notify_callback(card, cmd); +} +EXPORT_SYMBOL(snd_mixer_oss_notify); + +void snd_mixer_oss_set_notify(int (*callback)(struct snd_card *, int)) +{ + /* Wait for callbacks, including a final module_put(), to return. */ + guard(mutex)(&mixer_oss_notify_mutex); + mixer_oss_notify_callback = callback; +} +EXPORT_SYMBOL(snd_mixer_oss_set_notify); #endif static int check_empty_slot(struct module *module, int slot) @@ -356,7 +372,7 @@ static int snd_card_init(struct snd_card *card, struct device *parent, err = snd_info_card_create(card); if (err < 0) { dev_err(parent, "unable to create card info\n"); - goto __error_ctl; + goto __error; } #ifdef CONFIG_SND_DEBUG @@ -365,16 +381,16 @@ static int snd_card_init(struct snd_card *card, struct device *parent, #endif #ifdef CONFIG_SND_CTL_DEBUG card->value_buf = kmalloc_obj(*card->value_buf); - if (!card->value_buf) - return -ENOMEM; + if (!card->value_buf) { + err = -ENOMEM; + goto __error; + } #endif return 0; - __error_ctl: - snd_device_free_all(card); __error: - put_device(&card->card_dev); - return err; + snd_card_free(card); + return err; } /** @@ -530,8 +546,7 @@ void snd_card_disconnect(struct snd_card *card) /* at this point, they cannot respond to any calls except release() */ #if IS_ENABLED(CONFIG_SND_MIXER_OSS) - if (snd_mixer_oss_notify_callback) - snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_DISCONNECT); + snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_DISCONNECT); #endif /* notify all devices that we are disconnected */ @@ -557,6 +572,8 @@ void snd_card_disconnect(struct snd_card *card) clear_bit(card->number, snd_cards_lock); } + /* order card->shutdown store against power_ref read */ + smp_mb(); snd_power_sync_ref(card); } EXPORT_SYMBOL(snd_card_disconnect); @@ -587,8 +604,7 @@ static int snd_card_do_free(struct snd_card *card) card->releasing = true; #if IS_ENABLED(CONFIG_SND_MIXER_OSS) - if (snd_mixer_oss_notify_callback) - snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_FREE); + snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_FREE); #endif snd_device_free_all(card); kfree(card->components); @@ -932,8 +948,7 @@ int snd_card_register(struct snd_card *card) return err; #if IS_ENABLED(CONFIG_SND_MIXER_OSS) - if (snd_mixer_oss_notify_callback) - snd_mixer_oss_notify_callback(card, SND_MIXER_OSS_NOTIFY_REGISTER); + snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_REGISTER); #endif return 0; } @@ -1174,6 +1189,8 @@ EXPORT_SYMBOL(snd_card_file_remove); int snd_power_ref_and_wait(struct snd_card *card) { snd_power_ref(card); + /* order power_ref increment against card->shutdown read */ + smp_mb__after_atomic(); if (snd_power_get_state(card) != SNDRV_CTL_POWER_D0) { wait_event_cmd(card->power_sleep, card->shutdown || diff --git a/sound/core/jack.c b/sound/core/jack.c index 0f04018181ac..b14db9fe864f 100644 --- a/sound/core/jack.c +++ b/sound/core/jack.c @@ -68,6 +68,9 @@ static int snd_jack_dev_free(struct snd_device *device) struct snd_card *card = device->card; struct snd_jack_kctl *jack_kctl, *tmp_jack_kctl; + /* Remove debugfs while the controls are still linked. */ + snd_jack_remove_debugfs(jack); + list_for_each_entry_safe(jack_kctl, tmp_jack_kctl, &jack->kctl_list, list) { list_del_init(&jack_kctl->list); snd_ctl_remove(card, jack_kctl->kctl); @@ -303,6 +306,7 @@ static ssize_t jack_type_read(struct file *file, } static const struct file_operations jack_type_fops = { + .owner = THIS_MODULE, .open = simple_open, .read = jack_type_read, .llseek = default_llseek, @@ -310,6 +314,7 @@ static const struct file_operations jack_type_fops = { #endif static const struct file_operations sw_inject_enable_fops = { + .owner = THIS_MODULE, .open = simple_open, .read = sw_inject_enable_read, .write = sw_inject_enable_write, @@ -317,24 +322,28 @@ static const struct file_operations sw_inject_enable_fops = { }; static const struct file_operations jackin_inject_fops = { + .owner = THIS_MODULE, .open = simple_open, .write = jackin_inject_write, .llseek = default_llseek, }; static const struct file_operations jack_kctl_id_fops = { + .owner = THIS_MODULE, .open = simple_open, .read = jack_kctl_id_read, .llseek = default_llseek, }; static const struct file_operations jack_kctl_mask_bits_fops = { + .owner = THIS_MODULE, .open = simple_open, .read = jack_kctl_mask_bits_read, .llseek = default_llseek, }; static const struct file_operations jack_kctl_status_fops = { + .owner = THIS_MODULE, .open = simple_open, .read = jack_kctl_status_read, .llseek = default_llseek, @@ -450,7 +459,7 @@ static struct snd_jack_kctl * snd_jack_kctl_new(struct snd_card *card, const cha return jack_kctl; error: - snd_ctl_free_one(kctl); + snd_ctl_remove(card, kctl); return NULL; } diff --git a/sound/core/misc.c b/sound/core/misc.c index 066fb9ecdcdc..6fe199e76e83 100644 --- a/sound/core/misc.c +++ b/sound/core/misc.c @@ -183,11 +183,13 @@ void snd_refcount_init(struct snd_refcount *ref) { atomic_set(&ref->count, 0); init_waitqueue_head(&ref->waiter); + spin_lock_init(&ref->lock); } EXPORT_SYMBOL_GPL(snd_refcount_init); void snd_refcount_put(struct snd_refcount *ref) { + guard(spinlock_irqsave)(&ref->lock); if (atomic_dec_and_test(&ref->count)) wake_up(&ref->waiter); } @@ -195,6 +197,7 @@ EXPORT_SYMBOL_GPL(snd_refcount_put); void snd_refcount_sync(struct snd_refcount *ref) { - wait_event(ref->waiter, !atomic_read(&ref->count)); + guard(spinlock_irq)(&ref->lock); + wait_event_lock_irq(ref->waiter, !atomic_read(&ref->count), ref->lock); } EXPORT_SYMBOL_GPL(snd_refcount_sync); diff --git a/sound/core/oss/mixer_oss.c b/sound/core/oss/mixer_oss.c index c533d767c29a..c3f53eb64f92 100644 --- a/sound/core/oss/mixer_oss.c +++ b/sound/core/oss/mixer_oss.c @@ -1308,13 +1308,22 @@ static int snd_mixer_oss_free1(void *private) static int snd_mixer_oss_notify_handler(struct snd_card *card, int cmd) { struct snd_mixer_oss *mixer; + int err; if (cmd == SND_MIXER_OSS_NOTIFY_REGISTER) { - int idx, err; + int idx; + + /* Module loading and card registration can both notify us. */ + if (card->mixer_oss) + return 0; mixer = kzalloc_objs(*mixer, 2); if (mixer == NULL) return -ENOMEM; + if (!try_module_get(THIS_MODULE)) { + kfree(mixer); + return -ENODEV; + } mutex_init(&mixer->reg_mutex); err = snd_register_oss_device(SNDRV_OSS_DEVICE_TYPE_MIXER, card, 0, @@ -1324,6 +1333,7 @@ static int snd_mixer_oss_notify_handler(struct snd_card *card, int cmd) "unable to register OSS mixer device %i:%i\n", card->number, 0); kfree(mixer); + module_put(THIS_MODULE); return err; } mixer->oss_dev_alloc = 1; @@ -1357,7 +1367,10 @@ static int snd_mixer_oss_notify_handler(struct snd_card *card, int cmd) if (cmd == SND_MIXER_OSS_NOTIFY_DISCONNECT) return 0; snd_mixer_oss_proc_done(mixer); - return snd_mixer_oss_free1(mixer); + err = snd_mixer_oss_free1(mixer); + if (!err) + module_put(THIS_MODULE); + return err; } return 0; } @@ -1366,12 +1379,12 @@ static int __init alsa_mixer_oss_init(void) { struct snd_card *card; int idx; - - snd_mixer_oss_notify_callback = snd_mixer_oss_notify_handler; + + snd_mixer_oss_set_notify(snd_mixer_oss_notify_handler); for (idx = 0; idx < SNDRV_CARDS; idx++) { card = snd_card_ref(idx); if (card) { - snd_mixer_oss_notify_handler(card, SND_MIXER_OSS_NOTIFY_REGISTER); + snd_mixer_oss_notify(card, SND_MIXER_OSS_NOTIFY_REGISTER); snd_card_unref(card); } } @@ -1380,17 +1393,8 @@ static int __init alsa_mixer_oss_init(void) static void __exit alsa_mixer_oss_exit(void) { - struct snd_card *card; - int idx; - - snd_mixer_oss_notify_callback = NULL; - for (idx = 0; idx < SNDRV_CARDS; idx++) { - card = snd_card_ref(idx); - if (card) { - snd_mixer_oss_notify_handler(card, SND_MIXER_OSS_NOTIFY_FREE); - snd_card_unref(card); - } - } + /* Live adapters hold module references and prevent normal unload. */ + snd_mixer_oss_set_notify(NULL); } module_init(alsa_mixer_oss_init) diff --git a/sound/core/oss/pcm_oss.c b/sound/core/oss/pcm_oss.c index bd19328dca9e..e8df27d09b97 100644 --- a/sound/core/oss/pcm_oss.c +++ b/sound/core/oss/pcm_oss.c @@ -3151,6 +3151,12 @@ static void register_oss_dsp(struct snd_pcm *pcm, int index) static int snd_pcm_oss_register_minor(struct snd_pcm *pcm) { + if (pcm->oss.registered) + return 0; + if (!try_module_get(THIS_MODULE)) + return -ENODEV; + pcm->oss.registered = true; + pcm->oss.reg = 0; if (dsp_map[pcm->card->number] == (int)pcm->device) { char name[128]; @@ -3205,8 +3211,14 @@ static int snd_pcm_oss_disconnect_minor(struct snd_pcm *pcm) static int snd_pcm_oss_unregister_minor(struct snd_pcm *pcm) { + /* BUILD-state and creation-error cleanup need not have registered us. */ + if (!pcm->oss.registered) + return 0; + snd_pcm_oss_disconnect_minor(pcm); snd_pcm_oss_proc_done(pcm); + pcm->oss.registered = false; + module_put(THIS_MODULE); return 0; } diff --git a/sound/core/pcm.c b/sound/core/pcm.c index 41c2cab7a52c..7e2874cf2ff2 100644 --- a/sound/core/pcm.c +++ b/sound/core/pcm.c @@ -819,6 +819,9 @@ static void snd_pcm_free_stream(struct snd_pcm_str * pstr) /* free all proc files under the stream */ snd_pcm_stream_proc_done(pstr); + /* Drain channel-map callbacks before freeing the substreams. */ + free_chmap(pstr); + substream = pstr->substream; while (substream) { substream_next = substream->next; @@ -833,7 +836,6 @@ static void snd_pcm_free_stream(struct snd_pcm_str * pstr) kfree(setup); } #endif - free_chmap(pstr); if (pstr->substream_count) put_device(pstr->dev); } @@ -853,8 +855,10 @@ static int snd_pcm_free(struct snd_pcm *pcm) { if (!pcm) return 0; - if (!pcm->internal) - pcm_call_notify(pcm, n_unregister); + if (!pcm->internal) { + scoped_guard(mutex, ®ister_mutex) + pcm_call_notify(pcm, n_unregister); + } if (pcm->private_free) pcm->private_free(pcm); snd_pcm_lib_preallocate_free_for_all(pcm); @@ -919,6 +923,8 @@ int snd_pcm_attach_substream(struct snd_pcm *pcm, int stream, return -ENODEV; if (! SUBSTREAM_BUSY(substream)) return -EBADFD; + if (is_oss_stream(substream)) + return -EINVAL; substream->ref_count++; *rsubstream = substream; return 0; @@ -957,6 +963,7 @@ int snd_pcm_attach_substream(struct snd_pcm *pcm, int stream, init_waitqueue_head(&runtime->sleep); init_waitqueue_head(&runtime->tsleep); + snd_refcount_init(&runtime->refcnt); __snd_pcm_set_state(runtime, SNDRV_PCM_STATE_OPEN); mutex_init(&runtime->buffer_mutex); diff --git a/sound/core/pcm_compat.c b/sound/core/pcm_compat.c index 55ecf87586c4..359197aa6076 100644 --- a/sound/core/pcm_compat.c +++ b/sound/core/pcm_compat.c @@ -219,8 +219,8 @@ static int snd_pcm_status_user_compat64(struct snd_pcm_substream *substream, .audio_tstamp_data = status.audio_tstamp_data, .audio_tstamp_sec = status.audio_tstamp_sec, .audio_tstamp_nsec = status.audio_tstamp_nsec, - .driver_tstamp_sec = status.audio_tstamp_sec, - .driver_tstamp_nsec = status.audio_tstamp_nsec, + .driver_tstamp_sec = status.driver_tstamp_sec, + .driver_tstamp_nsec = status.driver_tstamp_nsec, .audio_tstamp_accuracy = status.audio_tstamp_accuracy, }; diff --git a/sound/core/pcm_lib.c b/sound/core/pcm_lib.c index 4d665b4148d7..1ec7db324196 100644 --- a/sound/core/pcm_lib.c +++ b/sound/core/pcm_lib.c @@ -2496,6 +2496,7 @@ static int pcm_chmap_ctl_get(struct snd_kcontrol *kcontrol, unsigned int idx = snd_ctl_get_ioffidx(kcontrol, &ucontrol->id); struct snd_pcm_substream *substream; const struct snd_pcm_chmap_elem *map; + unsigned int channels; if (!info->chmap) return -EINVAL; @@ -2504,11 +2505,20 @@ static int pcm_chmap_ctl_get(struct snd_kcontrol *kcontrol, return -ENODEV; memset(ucontrol->value.integer.value, 0, sizeof(long) * info->max_channels); - if (!substream->runtime) - return 0; /* no channels set */ + /* + * PCM disconnect takes open_mutex before removing controls. + * Use trylock to avoid a deadlock with controls_rwsem. + */ + scoped_cond_guard(mutex_try, return -EBUSY, + &info->pcm->open_mutex) { + if (!substream->runtime) + return 0; /* no channels set */ + channels = substream->runtime->channels; + } for (map = info->chmap; map->channels; map++) { int i; - if (map->channels == substream->runtime->channels && + + if (map->channels == channels && valid_chmap_channels(info, map->channels)) { for (i = 0; i < map->channels; i++) ucontrol->value.integer.value[i] = map->map[i]; diff --git a/sound/core/pcm_local.h b/sound/core/pcm_local.h index ecb21697ae3a..4b134d435c24 100644 --- a/sound/core/pcm_local.h +++ b/sound/core/pcm_local.h @@ -80,4 +80,10 @@ static inline void snd_pcm_dma_buffer_sync(struct snd_pcm_substream *substream, snd_dma_buffer_sync(snd_pcm_get_dma_buf(substream), mode); } +#if IS_ENABLED(CONFIG_SND_PCM_OSS) +#define is_oss_stream(substream) ((substream)->oss.oss) +#else +#define is_oss_stream(substream) false +#endif + #endif /* __SOUND_CORE_PCM_LOCAL_H */ diff --git a/sound/core/pcm_native.c b/sound/core/pcm_native.c index 6d32c12fb79b..f64ff3add229 100644 --- a/sound/core/pcm_native.c +++ b/sound/core/pcm_native.c @@ -772,17 +772,32 @@ int snd_pcm_runtime_buffer_set_silence(struct snd_pcm_runtime *runtime) } EXPORT_SYMBOL_GPL(snd_pcm_runtime_buffer_set_silence); -#if IS_ENABLED(CONFIG_SND_PCM_OSS) -#define is_oss_stream(substream) ((substream)->oss.oss) -#else -#define is_oss_stream(substream) false -#endif +static void pcm_qos_req_clear(struct snd_pcm_substream *substream) +{ + if (cpu_latency_qos_request_active(&substream->latency_pm_qos_req)) + cpu_latency_qos_remove_request(&substream->latency_pm_qos_req); +} + +static void pcm_qos_req_update(struct snd_pcm_substream *substream, int usecs) +{ + if (usecs < 0) { + pcm_qos_req_clear(substream); + return; + } + + if (cpu_latency_qos_request_active(&substream->latency_pm_qos_req)) + cpu_latency_qos_update_request(&substream->latency_pm_qos_req, + usecs); + else + cpu_latency_qos_add_request(&substream->latency_pm_qos_req, + usecs); +} static int snd_pcm_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_pcm_runtime *runtime; - int err, usecs; + int err; unsigned int bits; snd_pcm_uframes_t frames; @@ -889,12 +904,6 @@ static int snd_pcm_hw_params(struct snd_pcm_substream *substream, snd_pcm_timer_resolution_change(substream); snd_pcm_set_state(substream, SNDRV_PCM_STATE_SETUP); - if (cpu_latency_qos_request_active(&substream->latency_pm_qos_req)) - cpu_latency_qos_remove_request(&substream->latency_pm_qos_req); - usecs = period_to_usecs(runtime); - if (usecs >= 0) - cpu_latency_qos_add_request(&substream->latency_pm_qos_req, - usecs); err = 0; _error: if (err) { @@ -971,7 +980,7 @@ static int snd_pcm_hw_free(struct snd_pcm_substream *substream) goto unlock; result = do_hw_free(substream); snd_pcm_set_state(substream, SNDRV_PCM_STATE_OPEN); - cpu_latency_qos_remove_request(&substream->latency_pm_qos_req); + pcm_qos_req_clear(substream); unlock: snd_pcm_buffer_access_unlock(runtime); return result; @@ -1191,8 +1200,8 @@ static int snd_pcm_status_user32(struct snd_pcm_substream *substream, .audio_tstamp_data = status64.audio_tstamp_data, .audio_tstamp_sec = status64.audio_tstamp_sec, .audio_tstamp_nsec = status64.audio_tstamp_nsec, - .driver_tstamp_sec = status64.audio_tstamp_sec, - .driver_tstamp_nsec = status64.audio_tstamp_nsec, + .driver_tstamp_sec = status64.driver_tstamp_sec, + .driver_tstamp_nsec = status64.driver_tstamp_nsec, .audio_tstamp_accuracy = status64.audio_tstamp_accuracy, }; @@ -2005,6 +2014,7 @@ static int snd_pcm_do_prepare(struct snd_pcm_substream *substream, err = substream->ops->prepare(substream); if (err < 0) return err; + pcm_qos_req_update(substream, period_to_usecs(substream->runtime)); return snd_pcm_do_reset(substream, state); } @@ -2179,9 +2189,6 @@ static int snd_pcm_drain(struct snd_pcm_substream *substream, for (;;) { long tout; struct snd_pcm_runtime *to_check; - unsigned int drain_rate; - snd_pcm_uframes_t drain_bufsz; - bool drain_no_period_wakeup; if (signal_pending(current)) { result = -ERESTARTSYS; @@ -2196,45 +2203,35 @@ static int snd_pcm_drain(struct snd_pcm_substream *substream, runtime = s->runtime; if (runtime->state == SNDRV_PCM_STATE_DRAINING) { to_check = runtime; + /* pin the draining substream */ + snd_refcount_get(&to_check->refcnt); + + init_wait_entry(&wait, 0); + prepare_to_wait(&to_check->sleep, &wait, + TASK_INTERRUPTIBLE); + if (to_check->no_period_wakeup) { + tout = MAX_SCHEDULE_TIMEOUT; + } else { + tout = 100; + if (to_check->rate) { + long t = to_check->buffer_size * + 1100 / to_check->rate; + tout = max(t, tout); + } + tout = msecs_to_jiffies(tout); + } break; } } snd_pcm_group_unref(group, substream); if (!to_check) break; /* all drained */ - /* - * Cache the runtime fields needed after unlock. - * A concurrent close() on the linked stream may free - * its runtime via snd_pcm_detach_substream() once we - * release the stream lock below. - */ - drain_no_period_wakeup = to_check->no_period_wakeup; - drain_rate = to_check->rate; - drain_bufsz = to_check->buffer_size; - init_wait_entry(&wait, 0); - prepare_to_wait(&to_check->sleep, &wait, TASK_INTERRUPTIBLE); snd_pcm_stream_unlock_irq(substream); - if (drain_no_period_wakeup) - tout = MAX_SCHEDULE_TIMEOUT; - else { - tout = 100; - if (drain_rate) { - long t = drain_bufsz * 1100 / drain_rate; - tout = max(t, tout); - } - tout = msecs_to_jiffies(tout); - } tout = schedule_timeout(tout); - snd_pcm_stream_lock_irq(substream); - group = snd_pcm_stream_group_ref(substream); - snd_pcm_group_for_each_entry(s, substream) { - if (s->runtime == to_check) { - finish_wait(&to_check->sleep, &wait); - break; - } - } - snd_pcm_group_unref(group, substream); + finish_wait(&to_check->sleep, &wait); + /* unpin the draining substream again now */ + snd_refcount_put(&to_check->refcnt); if (card->shutdown) { result = -ENODEV; @@ -2776,27 +2773,23 @@ static int snd_pcm_hw_constraints_complete(struct snd_pcm_substream *substream) return 0; } -static void pcm_release_private(struct snd_pcm_substream *substream) -{ - if (snd_pcm_stream_linked(substream)) - snd_pcm_unlink(substream); -} - void snd_pcm_release_substream(struct snd_pcm_substream *substream) { substream->ref_count--; if (substream->ref_count > 0) return; + snd_pcm_unlink(substream); + snd_pcm_drop(substream); if (substream->hw_opened) { + snd_refcount_sync(&substream->runtime->refcnt); if (substream->runtime->state != SNDRV_PCM_STATE_OPEN) do_hw_free(substream); substream->ops->close(substream); substream->hw_opened = 0; } - if (cpu_latency_qos_request_active(&substream->latency_pm_qos_req)) - cpu_latency_qos_remove_request(&substream->latency_pm_qos_req); + pcm_qos_req_clear(substream); if (substream->pcm_release) { substream->pcm_release(substream); substream->pcm_release = NULL; @@ -2872,8 +2865,6 @@ static int snd_pcm_open_file(struct file *file, return -ENOMEM; } pcm_file->substream = substream; - if (substream->ref_count == 1) - substream->pcm_release = pcm_release_private; file->private_data = pcm_file; return 0; @@ -3063,11 +3054,15 @@ static snd_pcm_sframes_t rewind_appl_ptr(struct snd_pcm_substream *substream, static snd_pcm_sframes_t snd_pcm_rewind(struct snd_pcm_substream *substream, snd_pcm_uframes_t frames) { + struct snd_pcm_runtime *runtime = substream->runtime; snd_pcm_sframes_t ret; if (frames == 0) return 0; + /* Keep the DMA buffer alive through the sync below. */ + if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) + return -EBUSY; scoped_guard(pcm_stream_lock_irq, substream) { ret = do_pcm_hwsync(substream); if (!ret) @@ -3076,17 +3071,22 @@ static snd_pcm_sframes_t snd_pcm_rewind(struct snd_pcm_substream *substream, } if (ret >= 0) snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_DEVICE); + atomic_dec(&runtime->buffer_accessing); return ret; } static snd_pcm_sframes_t snd_pcm_forward(struct snd_pcm_substream *substream, snd_pcm_uframes_t frames) { + struct snd_pcm_runtime *runtime = substream->runtime; snd_pcm_sframes_t ret; if (frames == 0) return 0; + /* Keep the DMA buffer alive through the sync below. */ + if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) + return -EBUSY; scoped_guard(pcm_stream_lock_irq, substream) { ret = do_pcm_hwsync(substream); if (!ret) @@ -3095,20 +3095,26 @@ static snd_pcm_sframes_t snd_pcm_forward(struct snd_pcm_substream *substream, } if (ret >= 0) snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_DEVICE); + atomic_dec(&runtime->buffer_accessing); return ret; } static int snd_pcm_delay(struct snd_pcm_substream *substream, snd_pcm_sframes_t *delay) { + struct snd_pcm_runtime *runtime = substream->runtime; int err; + /* Keep the DMA buffer alive through the sync below. */ + if (!atomic_inc_unless_negative(&runtime->buffer_accessing)) + return -EBUSY; scoped_guard(pcm_stream_lock_irq, substream) { err = do_pcm_hwsync(substream); if (delay && !err) *delay = snd_pcm_calc_delay(substream); } snd_pcm_dma_buffer_sync(substream, SNDRV_DMA_SYNC_CPU); + atomic_dec(&runtime->buffer_accessing); return err; } diff --git a/sound/core/rawmidi.c b/sound/core/rawmidi.c index 2617bb5b4faf..9ef2c0e95b67 100644 --- a/sound/core/rawmidi.c +++ b/sound/core/rawmidi.c @@ -557,6 +557,9 @@ static void close_substream(struct snd_rawmidi *rmidi, substream->opened = 0; substream->append = 0; } + /* Drain input work queued after the earlier cancellation. */ + if (substream->stream == SNDRV_RAWMIDI_STREAM_INPUT) + cancel_work_sync(&substream->runtime->event_work); substream->ops->close(substream); if (substream->runtime->private_free) substream->runtime->private_free(substream); diff --git a/sound/core/seq/seq_clientmgr.c b/sound/core/seq/seq_clientmgr.c index 239809ce48d7..ba5619d0b0b0 100644 --- a/sound/core/seq/seq_clientmgr.c +++ b/sound/core/seq/seq_clientmgr.c @@ -95,23 +95,18 @@ static inline int snd_seq_write_pool_allocated(struct snd_seq_client *client) return snd_seq_total_cells(client->pool) > 0; } -/* return pointer to client structure for specified id; call under RCU read-lock */ -static struct snd_seq_client *__clientptr(int clientid) +/* return pointer to client structure for specified id; + * the caller must guarantee the client's lifetime by itself, as neither RCU + * nor a use_lock reference is taken here. + */ +static struct snd_seq_client *clientptr(int clientid) { if (clientid < 0 || clientid >= SNDRV_SEQ_MAX_CLIENTS) { pr_debug("ALSA: seq: oops. Trying to get pointer to client %d\n", clientid); return NULL; } - return rcu_dereference_check(clienttab[clientid], - lockdep_is_held(&clients_lock)); -} - -/* return pointer to client structure for specified id */ -static struct snd_seq_client *clientptr(int clientid) -{ - guard(rcu)(); - return __clientptr(clientid); + return rcu_dereference_protected(clienttab[clientid], true); } static struct snd_seq_client *client_use_ptr(int clientid, bool load_module) @@ -124,7 +119,7 @@ static struct snd_seq_client *client_use_ptr(int clientid, bool load_module) return NULL; } scoped_guard(rcu) { - client = __clientptr(clientid); + client = rcu_dereference(clienttab[clientid]); if (client) return snd_seq_client_ref(client); if (clienttablock[clientid]) @@ -159,7 +154,7 @@ static struct snd_seq_client *client_use_ptr(int clientid, bool load_module) } } scoped_guard(rcu) { - client = __clientptr(clientid); + client = rcu_dereference(clienttab[clientid]); if (client) return snd_seq_client_ref(client); } diff --git a/sound/core/seq/seq_compat.c b/sound/core/seq/seq_compat.c index 80110501da6f..57aaa39afb9d 100644 --- a/sound/core/seq/seq_compat.c +++ b/sound/core/seq/seq_compat.c @@ -25,7 +25,9 @@ struct snd_seq_port_info32 { u32 kernel; /* reserved for kernel use (must be NULL) */ u32 flags; /* misc. conditioning */ unsigned char time_queue; /* queue # for timestamping */ - char reserved[59]; /* for future use */ + unsigned char direction; /* port usage direction (r/w/bidir) */ + unsigned char ump_group; /* 0 = UMP EP (no conversion), 1-16 = UMP group number */ + char reserved[57]; /* for future use */ }; static int snd_seq_call_port_info_ioctl(struct snd_seq_client *client, unsigned int cmd, @@ -40,7 +42,9 @@ static int snd_seq_call_port_info_ioctl(struct snd_seq_client *client, unsigned if (copy_from_user(data, data32, sizeof(*data32)) || get_user(data->flags, &data32->flags) || - get_user(data->time_queue, &data32->time_queue)) + get_user(data->time_queue, &data32->time_queue) || + get_user(data->direction, &data32->direction) || + get_user(data->ump_group, &data32->ump_group)) return -EFAULT; data->kernel = NULL; @@ -50,9 +54,12 @@ static int snd_seq_call_port_info_ioctl(struct snd_seq_client *client, unsigned if (err < 0) return err; - if (copy_to_user(data32, data, sizeof(*data32)) || + if (copy_to_user(data32, data, + offsetof(struct snd_seq_port_info32, kernel)) || put_user(data->flags, &data32->flags) || - put_user(data->time_queue, &data32->time_queue)) + put_user(data->time_queue, &data32->time_queue) || + put_user(data->direction, &data32->direction) || + put_user(data->ump_group, &data32->ump_group)) return -EFAULT; return err; diff --git a/sound/core/seq/seq_ports.c b/sound/core/seq/seq_ports.c index eb67eb0eeb14..b582d034437f 100644 --- a/sound/core/seq/seq_ports.c +++ b/sound/core/seq/seq_ports.c @@ -248,17 +248,9 @@ static void clear_subscriber_list(struct snd_seq_client *client, } /* delete port data */ -static int port_delete(struct snd_seq_client *client, - struct snd_seq_client_port *port) +static void port_free(struct snd_seq_client *client, + struct snd_seq_client_port *port) { - /* set closing flag and wait for all port access are gone */ - port->closing = 1; - /* the port has already been unlinked from the client's port list; - * wait for a grace period so that RCU readers still traversing the - * list can no longer take a new use_lock reference, then drain the - * outstanding references before freeing - */ - synchronize_rcu(); snd_use_lock_sync(&port->use_lock); /* clear subscribers info */ @@ -272,6 +264,20 @@ static int port_delete(struct snd_seq_client *client, snd_BUG_ON(port->c_dest.count != 0); kfree(port); +} + +static int port_delete(struct snd_seq_client *client, + struct snd_seq_client_port *port) +{ + /* set closing flag and wait for all port access are gone */ + port->closing = 1; + /* the port has already been unlinked from the client's port list; + * wait for a grace period so that RCU readers still traversing the + * list can no longer take a new use_lock reference, then drain the + * outstanding references before freeing + */ + synchronize_rcu(); + port_free(client, port); return 0; } @@ -302,18 +308,25 @@ int snd_seq_delete_port(struct snd_seq_client *client, int port) int snd_seq_delete_all_ports(struct snd_seq_client *client) { struct snd_seq_client_port *port, *tmp; + LIST_HEAD(deleted); - /* unlink and delete each port; port_delete() waits for an RCU grace - * period before draining the port, so concurrent lockless readers can - * no longer take a new use_lock reference on it + /* unlink all ports first and wait for a single RCU grace period + * before draining and freeing them, so concurrent lockless readers + * can no longer take a new use_lock reference on any of them */ guard(mutex)(&client->ports_mutex); list_for_each_entry_safe(port, tmp, &client->ports_list_head, list) { list_del_rcu(&port->list); client->num_ports--; + port->closing = 1; + list_add_tail(&port->delete_list, &deleted); snd_seq_system_client_ev_port_exit(port->addr.client, port->addr.port); - port_delete(client, port); } + if (list_empty(&deleted)) + return 0; + synchronize_rcu(); + list_for_each_entry_safe(port, tmp, &deleted, delete_list) + port_free(client, port); return 0; } diff --git a/sound/core/seq/seq_ports.h b/sound/core/seq/seq_ports.h index 12ad86bf1489..ef1787d6c2dd 100644 --- a/sound/core/seq/seq_ports.h +++ b/sound/core/seq/seq_ports.h @@ -49,6 +49,7 @@ struct snd_seq_client_port { struct module *owner; /* owner of this port */ char name[64]; /* port name */ struct list_head list; /* port list */ + struct list_head delete_list; /* used by snd_seq_delete_all_ports() */ snd_use_lock_t use_lock; /* subscribers */ diff --git a/sound/core/seq/seq_ump_client.c b/sound/core/seq/seq_ump_client.c index 4c1e81db376f..ca9dcec19883 100644 --- a/sound/core/seq/seq_ump_client.c +++ b/sound/core/seq/seq_ump_client.c @@ -353,12 +353,12 @@ static int create_ump_endpoint_port(struct seq_ump_client *client) /* release the client resources */ static void seq_ump_client_free(struct seq_ump_client *client) { + snd_ump_detach_seq(client->ump); cancel_work_sync(&client->group_notify_work); if (client->seq_client >= 0) snd_seq_delete_kernel_client(client->seq_client); - client->ump->seq_ops = NULL; client->ump->seq_client = NULL; kfree(client); @@ -523,7 +523,8 @@ static int snd_seq_ump_probe(struct snd_seq_device *dev) snd_seq_kernel_client_put(cptr); ump->seq_client = client; - ump->seq_ops = &seq_ump_ops; + /* Publish the initialized client before callbacks can observe seq_ops. */ + smp_store_release(&ump->seq_ops, &seq_ump_ops); return 0; error: diff --git a/sound/core/timer.c b/sound/core/timer.c index 69a59b25fe0a..905176bf6948 100644 --- a/sound/core/timer.c +++ b/sound/core/timer.c @@ -2173,6 +2173,7 @@ static long snd_utimer_ioctl(struct file *file, unsigned int ioctl, unsigned lon } static const struct file_operations snd_utimer_fops = { + .owner = THIS_MODULE, .llseek = noop_llseek, .release = snd_utimer_release, .unlocked_ioctl = snd_utimer_ioctl, diff --git a/sound/core/ump.c b/sound/core/ump.c index 3d1a2ed3b476..20cae15e76fc 100644 --- a/sound/core/ump.c +++ b/sound/core/ump.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -18,6 +19,31 @@ #define ump_info(ump, fmt, args...) dev_info((ump)->core.dev, fmt, ##args) #define ump_dbg(ump, fmt, args...) dev_dbg((ump)->core.dev, fmt, ##args) +#if IS_ENABLED(CONFIG_SND_SEQUENCER) +DEFINE_STATIC_SRCU(ump_seq_srcu); + +static const struct snd_seq_ump_ops *seq_ops_load(struct snd_ump_endpoint *ump) +{ + /* Pair with publication after seq_client has been initialized. */ + return smp_load_acquire(&ump->seq_ops); +} + +/** + * snd_ump_detach_seq - stop callbacks to a sequencer binding + * @ump: UMP endpoint + * + * Withdraw the binding and wait for all callbacks already in progress. + * The caller can then drain binding work and free the sequencer client. + * Must not be called from one of the binding callbacks. + */ +void snd_ump_detach_seq(struct snd_ump_endpoint *ump) +{ + WRITE_ONCE(ump->seq_ops, NULL); + synchronize_srcu(&ump_seq_srcu); +} +EXPORT_SYMBOL_GPL(snd_ump_detach_seq); +#endif + static int snd_ump_dev_register(struct snd_rawmidi *rmidi); static int snd_ump_dev_unregister(struct snd_rawmidi *rmidi); static long snd_ump_ioctl(struct snd_rawmidi *rmidi, unsigned int cmd, @@ -66,7 +92,7 @@ static void safe_copy_string(void *dst, size_t max_dst_size, if (!max_dst_size--) return; - for (s = src; max_dst_size && *s && max_src_size--; s++) { + for (s = src; max_dst_size && max_src_size-- && *s; s++) { if (!isascii(*s) || !isprint(*s)) continue; *d++ = *s; @@ -348,8 +374,13 @@ int snd_ump_receive(struct snd_ump_endpoint *ump, const u32 *buffer, int count) continue; ump_handle_stream_msg(ump, ump->input_buf, n); #if IS_ENABLED(CONFIG_SND_SEQUENCER) - if (ump->seq_ops) - ump->seq_ops->input_receive(ump, ump->input_buf, n); + scoped_guard(srcu, &ump_seq_srcu) { + const struct snd_seq_ump_ops *ops; + + ops = seq_ops_load(ump); + if (ops) + ops->input_receive(ump, ump->input_buf, n); + } #endif process_legacy_input(ump, ump->input_buf, n); } @@ -699,8 +730,12 @@ static void choose_default_protocol(struct snd_ump_endpoint *ump) static void seq_notify_ep_change(struct snd_ump_endpoint *ump) { #if IS_ENABLED(CONFIG_SND_SEQUENCER) - if (ump->parsed && ump->seq_ops && ump->seq_ops->notify_ep_change) - ump->seq_ops->notify_ep_change(ump); + const struct snd_seq_ump_ops *ops; + + guard(srcu)(&ump_seq_srcu); + ops = seq_ops_load(ump); + if (ump->parsed && ops && ops->notify_ep_change) + ops->notify_ep_change(ump); #endif } @@ -797,8 +832,12 @@ static int ump_handle_product_id_msg(struct snd_ump_endpoint *ump, static void seq_notify_protocol(struct snd_ump_endpoint *ump) { #if IS_ENABLED(CONFIG_SND_SEQUENCER) - if (ump->seq_ops && ump->seq_ops->switch_protocol) - ump->seq_ops->switch_protocol(ump); + const struct snd_seq_ump_ops *ops; + + guard(srcu)(&ump_seq_srcu); + ops = seq_ops_load(ump); + if (ops && ops->switch_protocol) + ops->switch_protocol(ump); #endif /* CONFIG_SND_SEQUENCER */ } @@ -893,8 +932,12 @@ static void seq_notify_fb_change(struct snd_ump_endpoint *ump, struct snd_ump_block *fb) { #if IS_ENABLED(CONFIG_SND_SEQUENCER) - if (ump->seq_ops && ump->seq_ops->notify_fb_change) - ump->seq_ops->notify_fb_change(ump, fb); + const struct snd_seq_ump_ops *ops; + + guard(srcu)(&ump_seq_srcu); + ops = seq_ops_load(ump); + if (ops && ops->notify_fb_change) + ops->notify_fb_change(ump, fb); #endif } diff --git a/sound/core/vmaster.c b/sound/core/vmaster.c index cd3dcaaf9f72..f43144ba2797 100644 --- a/sound/core/vmaster.c +++ b/sound/core/vmaster.c @@ -287,6 +287,8 @@ EXPORT_SYMBOL(_snd_ctl_add_follower); * * Adds the multiple follower kcontrols with the given names. * Returns 0 for success or a negative error code. + * + * Note that this function takes card->controls_rwsem lock internally. */ int snd_ctl_add_followers(struct snd_card *card, struct snd_kcontrol *master, const char * const *list) @@ -294,6 +296,7 @@ int snd_ctl_add_followers(struct snd_card *card, struct snd_kcontrol *master, struct snd_kcontrol *follower; int err; + guard(rwsem_write)(&card->controls_rwsem); for (; *list; list++) { follower = snd_ctl_find_id_mixer(card, *list); if (follower) { @@ -463,6 +466,7 @@ EXPORT_SYMBOL(snd_ctl_make_virtual_master); /** * snd_ctl_add_vmaster_hook - Add a hook to a vmaster control + * @card: the card instance * @kcontrol: vmaster kctl element * @hook: the hook function * @private_data: the private_data pointer to be saved @@ -470,13 +474,17 @@ EXPORT_SYMBOL(snd_ctl_make_virtual_master); * Adds the given hook to the vmaster control element so that it's called * at each time when the value is changed. * + * Takes the card's controls_rwsem lock internally. + * * Return: Zero. */ -int snd_ctl_add_vmaster_hook(struct snd_kcontrol *kcontrol, +int snd_ctl_add_vmaster_hook(struct snd_card *card, struct snd_kcontrol *kcontrol, void (*hook)(void *private_data, int), void *private_data) { struct link_master *master = snd_kcontrol_chip(kcontrol); + + guard(rwsem_write)(&card->controls_rwsem); master->hook = hook; master->hook_private_data = private_data; return 0; diff --git a/sound/drivers/aloop.c b/sound/drivers/aloop.c index 38fe3f4ce5d8..824d320b665b 100644 --- a/sound/drivers/aloop.c +++ b/sound/drivers/aloop.c @@ -100,7 +100,7 @@ struct loopback_ops { struct loopback_cable { spinlock_t lock; struct loopback_pcm *streams[2]; - /* in-flight peer stops running outside cable->lock */ + /* in-flight PCM callbacks running outside cable->lock */ struct snd_refcount stop_count; struct snd_pcm_hardware hw; /* flags */ @@ -876,6 +876,8 @@ static void loopback_snd_timer_period_elapsed(struct loopback_cable *cable, valid_runtime = (running & (1 << SNDRV_PCM_STREAM_PLAYBACK)) ? dpcm_play->substream->runtime : dpcm_capt->substream->runtime; + /* Keep runtimes alive through the PCM callbacks. */ + snd_refcount_get(&cable->stop_count); /* resolution is only valid for SNDRV_TIMER_EVENT_TICK events */ if (event == SNDRV_TIMER_EVENT_TICK) { @@ -911,13 +913,16 @@ static void loopback_snd_timer_period_elapsed(struct loopback_cable *cable, snd_pcm_stop_xrun(substream_play); if (substream_capt) snd_pcm_stop_xrun(substream_capt); - return; + goto exit; } if (substream_play) snd_pcm_period_elapsed(substream_play); if (substream_capt) snd_pcm_period_elapsed(substream_capt); + +exit: + snd_refcount_put(&cable->stop_count); } static void loopback_snd_timer_function(struct snd_timer_instance *timeri, @@ -1177,7 +1182,7 @@ static void free_cable(struct snd_pcm_substream *substream) other_alive = cable->streams[!substream->stream]; } - /* Pair with the stop_count increment in loopback_check_format(). */ + /* Wait for PCM callbacks running outside cable->lock. */ snd_refcount_sync(&cable->stop_count); if (other_alive) return; @@ -1378,7 +1383,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; @@ -1387,7 +1392,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_obj(*dpcm); if (!dpcm) return -ENOMEM; @@ -1482,6 +1486,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; @@ -1893,13 +1905,10 @@ static int loopback_cable_proc_new(struct loopback *loopback, int cidx) static void loopback_set_timer_source(struct loopback *loopback, const char *value) { - if (loopback->timer_source) { - devm_kfree(loopback->card->dev, loopback->timer_source); - loopback->timer_source = NULL; - } + kfree(loopback->timer_source); + loopback->timer_source = NULL; if (value && *value) - loopback->timer_source = devm_kstrdup(loopback->card->dev, - value, GFP_KERNEL); + loopback->timer_source = kstrdup(value, GFP_KERNEL); } static void print_timer_source_info(struct snd_info_entry *entry, @@ -1930,6 +1939,13 @@ static int loopback_timer_source_proc_new(struct loopback *loopback) change_timer_source_info); } +static void loopback_private_free(struct snd_card *card) +{ + struct loopback *loopback = card->private_data; + + kfree(loopback->timer_source); +} + static int loopback_probe(struct platform_device *devptr) { struct snd_card *card; @@ -1955,6 +1971,7 @@ static int loopback_probe(struct platform_device *devptr) pcm_substreams[dev] = MAX_PCM_SUBSTREAMS; loopback->card = card; + card->private_free = loopback_private_free; loopback_set_timer_source(loopback, timer_source[dev]); mutex_init(&loopback->cable_lock); diff --git a/sound/drivers/pcmtest.c b/sound/drivers/pcmtest.c index 186e982d42e1..a42d9d818e4a 100644 --- a/sound/drivers/pcmtest.c +++ b/sound/drivers/pcmtest.c @@ -72,13 +72,32 @@ static u8 playback_capture_test; static u8 ioctl_reset_test; static struct dentry *driver_debug_dir; +static int fill_mode_set(const char *val, const struct kernel_param *kp) +{ + short mode; + int err; + + err = kstrtos16(val, 0, &mode); + if (err) + return err; + if (mode != FILL_MODE_RAND && mode != FILL_MODE_PAT) + return -EINVAL; + fill_mode = mode; + return 0; +} + +static const struct kernel_param_ops fill_mode_ops = { + .set = fill_mode_set, + .get = param_get_short, +}; + module_param(index, int, 0444); MODULE_PARM_DESC(index, "Index value for pcmtest soundcard"); module_param(id, charp, 0444); MODULE_PARM_DESC(id, "ID string for pcmtest soundcard"); module_param(enable, bool, 0444); MODULE_PARM_DESC(enable, "Enable pcmtest soundcard."); -module_param(fill_mode, short, 0600); +module_param_cb(fill_mode, &fill_mode_ops, &fill_mode, 0600); MODULE_PARM_DESC(fill_mode, "Buffer fill mode: rand(0) or pattern(1)"); module_param(inject_delay, int, 0600); MODULE_PARM_DESC(inject_delay, "Inject delays during playback/capture (in jiffies)"); @@ -345,6 +364,7 @@ static void timer_timeout(struct timer_list *data) v_iter = timer_container_of(v_iter, data, timer_instance); substream = v_iter->substream; + guard(pcm_stream_lock_irqsave)(substream); if (v_iter->suspend) return; @@ -358,7 +378,7 @@ static void timer_timeout(struct timer_list *data) v_iter->period_pos += v_iter->b_rw; if (v_iter->period_pos >= v_iter->period_bytes) { v_iter->period_pos %= v_iter->period_bytes; - snd_pcm_period_elapsed(substream); + snd_pcm_period_elapsed_under_stream_lock(substream); } if (!v_iter->suspend) @@ -445,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) { } @@ -562,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_obj(*pcmtst); - 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; @@ -603,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; @@ -619,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, @@ -637,7 +612,6 @@ static struct platform_device pcmtst_pdev = { static struct platform_driver pcmtst_pdrv = { .probe = pcmtst_probe, - .remove = pdev_remove, .driver = { .name = "pcmtest", }, @@ -683,6 +657,7 @@ static ssize_t pattern_read(struct file *file, char __user *u_buff, size_t len, } static const struct file_operations fill_pattern_fops = { + .owner = THIS_MODULE, .read = pattern_read, .write = pattern_write, }; @@ -742,6 +717,9 @@ static int __init mod_init(void) { int err = 0; + if (!enable) + return -ENODEV; + buf_allocated = setup_patt_bufs(); if (!buf_allocated) return -ENOMEM; diff --git a/sound/hda/codecs/realtek/alc269.c b/sound/hda/codecs/realtek/alc269.c index 49c4d01759b0..350003d406e7 100644 --- a/sound/hda/codecs/realtek/alc269.c +++ b/sound/hda/codecs/realtek/alc269.c @@ -1642,6 +1642,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) @@ -3682,6 +3690,28 @@ static void alc287_fixup_yoga9_14iap7_bass_spk_pin(struct hda_codec *codec, } } +/* + * The Lenovo Xiaoxin 14 GT (SSID 17aa:3912) uses the same bass-speaker + * pin wiring as its 0x390d/0x3911/0x391a siblings, but on this board the + * codec's vendor processing coefficients (node 0x20) are left at their + * power-on default instead of being programmed the way the vendor + * (Windows) driver programs them. That leaves audible hiss/crackle on + * both the headphone jack and the internal speakers, independent of + * volume, regardless of which pin/DAC routing is used. + * + * This single coefficient write was captured from the vendor driver's + * own init sequence (via a VFIO pass-through of the physical codec to a + * Windows VM) and confirmed to eliminate the headphone jack noise. + */ +static void alc287_fixup_lenovo_xiaoxin_14gt_hp_noise(struct hda_codec *codec, + const struct hda_fixup *fix, int action) +{ + if (action != HDA_FIXUP_ACT_INIT) + return; + + alc_write_coef_idx(codec, 0x36, 0x77d7); +} + static void alc_fixup_yoga_pro7_audio(struct hda_codec *codec, const struct hda_fixup *fix, int action) { @@ -4214,6 +4244,7 @@ enum { ALC294_FIXUP_ASUS_I2C_HEADSET_MIC, ALC294_FIXUP_ASUS_SPI_HEADSET_MIC, ALC294_FIXUP_ASUS_SPK, + ALC294_FIXUP_ASUS_Q423SA, ALC293_FIXUP_SYSTEM76_MIC_NO_PRESENCE, ALC285_FIXUP_LENOVO_PC_BEEP_IN_NOISE, ALC255_FIXUP_ACER_HEADSET_MIC, @@ -4342,6 +4373,7 @@ enum { ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK, ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN, ALC287_FIXUP_YOGA9_14IMH9_BASS_SPK_PIN, + ALC287_FIXUP_LENOVO_XIAOXIN_14GT_HP_NOISE, ALC295_FIXUP_DELL_INSPIRON_TOP_SPEAKERS, ALC236_FIXUP_DELL_DUAL_CODECS, ALC287_FIXUP_CS35L41_I2C_2_THINKPAD_ACPI, @@ -4400,6 +4432,7 @@ enum { ALC245_FIXUP_BASS_HP_DAC, ALC245_FIXUP_ACER_MICMUTE_LED, ALC245_FIXUP_CS35L41_I2C_2_MUTE_LED, + ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED, ALC256_FIXUP_HONOR_MRB_XXX_M1020_AUDIO, ALC245_FIXUP_HP_ENVY_X360_15_FH0XXX, ALC287_FIXUP_ACER_MICMUTE_LED, @@ -5742,6 +5775,17 @@ static const struct hda_fixup alc269_fixups[] = { .chained = true, .chain_id = ALC294_FIXUP_ASUS_HEADSET_MIC }, + [ALC294_FIXUP_ASUS_Q423SA] = { + .type = HDA_FIXUP_VERBS, + .v.verbs = (const struct hda_verb[]) { + /* Restore bit 10 lost after reboot from Windows */ + { 0x20, AC_VERB_SET_COEF_INDEX, 0x1b }, + { 0x20, AC_VERB_SET_PROC_COEF, 0x4e4b }, + { } + }, + .chained = true, + .chain_id = ALC2XX_FIXUP_HEADSET_MIC, + }, [ALC295_FIXUP_CHROME_BOOK] = { .type = HDA_FIXUP_FUNC, .v.func = alc295_fixup_chromebook, @@ -6832,6 +6876,12 @@ static const struct hda_fixup alc269_fixups[] = { .chained = true, .chain_id = ALC287_FIXUP_CS35L41_I2C_2, }, + [ALC287_FIXUP_LENOVO_XIAOXIN_14GT_HP_NOISE] = { + .type = HDA_FIXUP_FUNC, + .v.func = alc287_fixup_lenovo_xiaoxin_14gt_hp_noise, + .chained = true, + .chain_id = ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN, + }, [ALC295_FIXUP_DELL_INSPIRON_TOP_SPEAKERS] = { .type = HDA_FIXUP_FUNC, .v.func = alc295_fixup_dell_inspiron_top_speakers, @@ -7148,6 +7198,12 @@ static const struct hda_fixup alc269_fixups[] = { .chained = true, .chain_id = ALC287_FIXUP_CS35L41_I2C_2, }, + [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, + }, [ALC256_FIXUP_HONOR_MRB_XXX_M1020_AUDIO] = { .type = HDA_FIXUP_PINS, .v.pins = (const struct hda_pintbl[]) { @@ -7719,10 +7775,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 x360 2-in-1 Laptop 15-fh0xxx", ALC245_FIXUP_HP_ENVY_X360_15_FH0XXX), 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), @@ -7899,7 +7955,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { SND_PCI_QUIRK(0x1043, 0x10a1, "ASUS UX391UA", ALC294_FIXUP_ASUS_SPK), SND_PCI_QUIRK(0x1043, 0x10a4, "ASUS TP3407SA", ALC287_FIXUP_TAS2781_I2C), SND_PCI_QUIRK(0x1043, 0x10c0, "ASUS X540SA", ALC256_FIXUP_ASUS_MIC), - SND_PCI_QUIRK(0x1043, 0x10c4, "ASUS Vivobook S14 S5406SA", ALC2XX_FIXUP_HEADSET_MIC), + SND_PCI_QUIRK(0x1043, 0x10c4, "ASUS S5406SA/Q423SA", ALC294_FIXUP_ASUS_Q423SA), SND_PCI_QUIRK(0x1043, 0x10d0, "ASUS X540LA/X540LJ", ALC255_FIXUP_ASUS_MIC_NO_PRESENCE), SND_PCI_QUIRK(0x1043, 0x10d3, "ASUS K6500ZC", ALC294_FIXUP_ASUS_SPK), SND_PCI_QUIRK(0x1043, 0x1154, "ASUS TP3607SH", ALC287_FIXUP_TAS2781_I2C), @@ -8390,7 +8446,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = { HDA_CODEC_QUIRK(0x17aa, 0x3907, "Legion Pro 7i 16IAX10H / Y9000P IAX10", ALC287_FIXUP_LENOVO_LEGION_AW88399), SND_PCI_QUIRK(0x17aa, 0x390d, "Lenovo Yoga Pro 7 14ASP10", ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN_HEADSET), SND_PCI_QUIRK(0x17aa, 0x3911, "Lenovo Yoga Pro 7 14IAH10", ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN), - SND_PCI_QUIRK(0x17aa, 0x3912, "Lenovo Xiaoxin 14 GT", ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN), + SND_PCI_QUIRK(0x17aa, 0x3912, "Lenovo Xiaoxin 14 GT", ALC287_FIXUP_LENOVO_XIAOXIN_14GT_HP_NOISE), SND_PCI_QUIRK(0x17aa, 0x3913, "Lenovo 145", ALC236_FIXUP_LENOVO_INV_DMIC), SND_PCI_QUIRK(0x17aa, 0x391f, "Yoga S990-16 pro Quad YC Quad", ALC287_FIXUP_TXNW2781_I2C), SND_PCI_QUIRK(0x17aa, 0x3920, "Yoga S990-16 pro Quad VECO Quad", ALC287_FIXUP_YOGA9_SPEAKER2_TO_DAC1), diff --git a/sound/hda/common/bind.c b/sound/hda/common/bind.c index 6a728a773556..957feace0f58 100644 --- a/sound/hda/common/bind.c +++ b/sound/hda/common/bind.c @@ -89,8 +89,12 @@ static int hda_codec_driver_probe(struct device *dev) struct hda_codec *codec = dev_to_hda_codec(dev); struct module *owner = dev->driver->owner; struct hda_codec_driver *driver = hda_codec_to_driver(codec); + bool probed = false; int err; + /* unsol events are still blocked until registered */ + codec->core.unsol_disabled = false; + if (codec->bus->core.ext_ops) { if (WARN_ON(!codec->bus->core.ext_ops->hdev_attach)) return -EINVAL; @@ -119,7 +123,8 @@ static int hda_codec_driver_probe(struct device *dev) err = driver->ops->probe(codec, codec->preset); if (err < 0) - goto error_module_put; + goto error_module; + probed = true; err = snd_hda_codec_build_pcms(codec); if (err < 0) goto error_module; @@ -138,7 +143,9 @@ static int hda_codec_driver_probe(struct device *dev) return 0; error_module: - if (driver->ops->remove) + snd_hdac_device_disable_unsol(&codec->core); + cancel_delayed_work_sync(&codec->jackpoll_work); + if (probed && driver->ops->remove) driver->ops->remove(codec); error_module_put: module_put(owner); @@ -154,6 +161,10 @@ static int hda_codec_driver_remove(struct device *dev) struct hda_codec *codec = dev_to_hda_codec(dev); struct hda_codec_driver *driver = hda_codec_to_driver(codec); + /* stop asynchronous jack handling before freeing driver resources */ + snd_hdac_device_disable_unsol(&codec->core); + cancel_delayed_work_sync(&codec->jackpoll_work); + if (codec->bus->core.ext_ops) { if (WARN_ON(!codec->bus->core.ext_ops->hdev_detach)) return -EINVAL; diff --git a/sound/hda/common/codec.c b/sound/hda/common/codec.c index 7c2b967aebe9..27cb6419e64b 100644 --- a/sound/hda/common/codec.c +++ b/sound/hda/common/codec.c @@ -921,7 +921,6 @@ snd_hda_codec_device_init(struct hda_bus *bus, unsigned int codec_addr, snd_array_init(&codec->driver_pins, sizeof(struct hda_pincfg), 16); snd_array_init(&codec->cvt_setups, sizeof(struct hda_cvt_setup), 8); snd_array_init(&codec->spdif_out, sizeof(struct hda_spdif_out), 16); - snd_array_init(&codec->jacktbl, sizeof(struct hda_jack_tbl), 16); snd_array_init(&codec->verbs, sizeof(struct hda_verb *), 8); INIT_LIST_HEAD(&codec->conn_list); INIT_LIST_HEAD(&codec->pcm_list_head); @@ -2024,7 +2023,7 @@ int snd_hda_add_vmaster_hook(struct hda_codec *codec, if (!hook->hook || !hook->sw_kctl) return 0; hook->codec = codec; - snd_ctl_add_vmaster_hook(hook->sw_kctl, vmaster_hook, hook); + snd_ctl_add_vmaster_hook(codec->card, hook->sw_kctl, vmaster_hook, hook); return 0; } EXPORT_SYMBOL_GPL(snd_hda_add_vmaster_hook); @@ -3046,6 +3045,7 @@ void snd_hda_codec_shutdown(struct hda_codec *codec) codec->jackpoll_interval = 0; /* don't poll any longer */ cancel_delayed_work_sync(&codec->jackpoll_work); + snd_hdac_device_disable_unsol(&codec->core); list_for_each_entry(cpcm, &codec->pcm_list_head, list) snd_pcm_suspend_all(cpcm->pcm); diff --git a/sound/hda/common/hda_jack.h b/sound/hda/common/hda_jack.h index e9b9970c59ed..a06b315e4b05 100644 --- a/sound/hda/common/hda_jack.h +++ b/sound/hda/common/hda_jack.h @@ -44,6 +44,7 @@ struct hda_jack_tbl { int type; int button_state; struct snd_jack *jack; + struct hda_jack_tbl *next; }; struct hda_jack_keymap { diff --git a/sound/hda/common/jack.c b/sound/hda/common/jack.c index 1d6b0f0e6f27..6b8aa1a6c008 100644 --- a/sound/hda/common/jack.c +++ b/sound/hda/common/jack.c @@ -76,12 +76,11 @@ static u32 read_pin_sense(struct hda_codec *codec, hda_nid_t nid, int dev_id) struct hda_jack_tbl * snd_hda_jack_tbl_get_mst(struct hda_codec *codec, hda_nid_t nid, int dev_id) { - struct hda_jack_tbl *jack = codec->jacktbl.list; - int i; + struct hda_jack_tbl *jack; - if (!nid || !jack) + if (!nid) return NULL; - for (i = 0; i < codec->jacktbl.used; i++, jack++) + for (jack = codec->jacktbl; jack; jack = jack->next) if (jack->nid == nid && jack->dev_id == dev_id) return jack; return NULL; @@ -98,12 +97,11 @@ struct hda_jack_tbl * snd_hda_jack_tbl_get_from_tag(struct hda_codec *codec, unsigned char tag, int dev_id) { - struct hda_jack_tbl *jack = codec->jacktbl.list; - int i; + struct hda_jack_tbl *jack; - if (!tag || !jack) + if (!tag) return NULL; - for (i = 0; i < codec->jacktbl.used; i++, jack++) + for (jack = codec->jacktbl; jack; jack = jack->next) if (jack->tag == tag && jack->dev_id == dev_id) return jack; return NULL; @@ -113,12 +111,11 @@ EXPORT_SYMBOL_GPL(snd_hda_jack_tbl_get_from_tag); static struct hda_jack_tbl * any_jack_tbl_get_from_nid(struct hda_codec *codec, hda_nid_t nid) { - struct hda_jack_tbl *jack = codec->jacktbl.list; - int i; + struct hda_jack_tbl *jack; - if (!nid || !jack) + if (!nid) return NULL; - for (i = 0; i < codec->jacktbl.used; i++, jack++) + for (jack = codec->jacktbl; jack; jack = jack->next) if (jack->nid == nid) return jack; return NULL; @@ -142,12 +139,19 @@ snd_hda_jack_tbl_new(struct hda_codec *codec, hda_nid_t nid, int dev_id) if (jack) return jack; - jack = snd_array_new(&codec->jacktbl); + jack = kzalloc_obj(*jack); if (!jack) return NULL; jack->nid = nid; jack->dev_id = dev_id; jack->jack_dirty = 1; + if (!codec->jacktbl) + codec->jacktbl = jack; + else + codec->jacktbl_last->next = jack; + codec->jacktbl_last = jack; + codec->jacktbl_used++; + if (existing_nid_jack) { jack->tag = existing_nid_jack->tag; @@ -158,7 +162,7 @@ snd_hda_jack_tbl_new(struct hda_codec *codec, hda_nid_t nid, int dev_id) */ jack->jack_detect = existing_nid_jack->jack_detect; } else { - jack->tag = codec->jacktbl.used; + jack->tag = codec->jacktbl_used; } return jack; @@ -166,10 +170,9 @@ snd_hda_jack_tbl_new(struct hda_codec *codec, hda_nid_t nid, int dev_id) void snd_hda_jack_tbl_disconnect(struct hda_codec *codec) { - struct hda_jack_tbl *jack = codec->jacktbl.list; - int i; + struct hda_jack_tbl *jack; - for (i = 0; i < codec->jacktbl.used; i++, jack++) { + for (jack = codec->jacktbl; jack; jack = jack->next) { if (!codec->bus->shutdown && jack->jack) snd_device_disconnect(codec->card, jack->jack); } @@ -177,22 +180,31 @@ void snd_hda_jack_tbl_disconnect(struct hda_codec *codec) void snd_hda_jack_tbl_clear(struct hda_codec *codec) { - struct hda_jack_tbl *jack = codec->jacktbl.list; - int i; + struct hda_jack_tbl *jack, *jack_next; - for (i = 0; i < codec->jacktbl.used; i++, jack++) { + for (jack = codec->jacktbl; jack; jack = jack_next) { struct hda_jack_callback *cb, *next; - /* free jack instances manually when clearing/reconfiguring */ - if (!codec->bus->shutdown && jack->jack) - snd_device_free(codec->card, jack->jack); + jack_next = jack->next; + + if (jack->jack) { + /* fingers away from stale data */ + jack->jack->private_data = NULL; + jack->jack->private_free = NULL; + /* free jack instances manually when clearing/reconfiguring */ + if (!codec->bus->shutdown) + snd_device_free(codec->card, jack->jack); + } for (cb = jack->callback; cb; cb = next) { next = cb->next; kfree(cb); } + kfree(jack); } - snd_array_free(&codec->jacktbl); + + codec->jacktbl = codec->jacktbl_last = NULL; + codec->jacktbl_used = 0; } #define get_jack_plug_state(sense) !!(sense & AC_PINSENSE_PRESENCE) @@ -238,10 +250,9 @@ static void jack_detect_update(struct hda_codec *codec, */ void snd_hda_jack_set_dirty_all(struct hda_codec *codec) { - struct hda_jack_tbl *jack = codec->jacktbl.list; - int i; + struct hda_jack_tbl *jack; - for (i = 0; i < codec->jacktbl.used; i++, jack++) + for (jack = codec->jacktbl; jack; jack = jack->next) if (jack->nid) jack->jack_dirty = 1; } @@ -389,12 +400,15 @@ EXPORT_SYMBOL_GPL(snd_hda_jack_detect_enable); int snd_hda_jack_set_gating_jack(struct hda_codec *codec, hda_nid_t gated_nid, hda_nid_t gating_nid) { - struct hda_jack_tbl *gated = snd_hda_jack_tbl_new(codec, gated_nid, 0); - struct hda_jack_tbl *gating = - snd_hda_jack_tbl_new(codec, gating_nid, 0); + struct hda_jack_tbl *gated, *gating; WARN_ON(codec->dp_mst); + if (!snd_hda_jack_tbl_new(codec, gated_nid, 0) || + !snd_hda_jack_tbl_new(codec, gating_nid, 0)) + return -ENOMEM; + gated = snd_hda_jack_tbl_get_mst(codec, gated_nid, 0); + gating = snd_hda_jack_tbl_get_mst(codec, gating_nid, 0); if (!gated || !gating) return -EINVAL; @@ -475,19 +489,17 @@ EXPORT_SYMBOL_GPL(snd_hda_jack_set_button_state); void snd_hda_jack_report_sync(struct hda_codec *codec) { struct hda_jack_tbl *jack; - int i, state; + int state; /* update all jacks at first */ - jack = codec->jacktbl.list; - for (i = 0; i < codec->jacktbl.used; i++, jack++) + for (jack = codec->jacktbl; jack; jack = jack->next) if (jack->nid) jack_detect_update(codec, jack); /* report the updated jacks; it's done after updating all jacks * to make sure that all gating jacks properly have been set */ - jack = codec->jacktbl.list; - for (i = 0; i < codec->jacktbl.used; i++, jack++) + for (jack = codec->jacktbl; jack; jack = jack->next) if (jack->nid) { if (!jack->jack || jack->block_report) continue; @@ -755,10 +767,10 @@ EXPORT_SYMBOL_GPL(snd_hda_jack_unsol_event); */ void snd_hda_jack_poll_all(struct hda_codec *codec) { - struct hda_jack_tbl *jack = codec->jacktbl.list; - int i, changes = 0; + struct hda_jack_tbl *jack; + int changes = 0; - for (i = 0; i < codec->jacktbl.used; i++, jack++) { + for (jack = codec->jacktbl; jack; jack = jack->next) { unsigned int old_sense; if (!jack->nid || !jack->jack_dirty || jack->phantom_jack) continue; diff --git a/sound/hda/controllers/intel.c b/sound/hda/controllers/intel.c index 24015c73a67f..6b80b59b8743 100644 --- a/sound/hda/controllers/intel.c +++ b/sound/hda/controllers/intel.c @@ -1184,7 +1184,7 @@ static const struct dev_pm_ops azx_pm = { }; -static int azx_probe_continue(struct azx *chip); +static int azx_probe_continue(struct azx *chip, bool free_on_error); #ifdef SUPPORT_VGA_SWITCHEROO static struct pci_dev *get_bound_vga(struct pci_dev *pci); @@ -1211,8 +1211,10 @@ static void azx_vs_set_state(struct pci_dev *pci, if (!disabled) { dev_info(chip->card->dev, "Start delayed initialization\n"); - if (azx_probe_continue(chip) < 0) + if (azx_probe_continue(chip, false) < 0) { + hda->init_failed = 1; dev_err(chip->card->dev, "initialization error\n"); + } } } else { dev_info(chip->card->dev, "%s via vga_switcheroo\n", @@ -1251,8 +1253,6 @@ static bool azx_vs_can_switch(struct pci_dev *pci) struct hda_intel *hda = container_of(chip, struct hda_intel, chip); wait_for_completion(&hda->probe_wait); - if (hda->init_failed) - return false; if (chip->disabled || !hda->probe_continued) return true; if (snd_hda_lock_devices(&chip->bus)) @@ -1380,7 +1380,6 @@ static void azx_free(struct azx *chip) * actually stop the chip) to allow GPU to suspend via * vga_switcheroo, and print a warning. */ - dev_warn(&pci->dev, "GPU sound probed, but not operational: please add a quirk to driver_denylist\n"); pm_runtime_disable(&pci->dev); pm_runtime_set_suspended(&pci->dev); pm_runtime_enable(&pci->dev); @@ -1738,7 +1737,12 @@ static void azx_check_snoop_available(struct azx *chip) static void azx_probe_work(struct work_struct *work) { struct hda_intel *hda = container_of(work, struct hda_intel, probe_work.work); - azx_probe_continue(&hda->chip); + + if (azx_probe_continue(&hda->chip, false) < 0) { + hda->init_failed = 1; + complete_all(&hda->probe_wait); + snd_card_disconnect(hda->chip.card); + } } static int default_bdl_pos_adj(struct azx *chip) @@ -2356,7 +2360,7 @@ static const unsigned int azx_max_codecs[AZX_NUM_DRIVERS] = { [AZX_DRIVER_TERA] = 1, }; -static int azx_probe_continue(struct azx *chip) +static int azx_probe_continue(struct azx *chip, bool free_on_error) { struct hda_intel *hda = container_of(chip, struct hda_intel, chip); struct hdac_bus *bus = azx_bus(chip); @@ -2447,8 +2451,12 @@ static int azx_probe_continue(struct azx *chip) out_free: if (err < 0) { - pci_set_drvdata(pci, NULL); - snd_card_free(chip->card); + if (hda->vga_switcheroo_registered) + dev_warn(&pci->dev, "GPU sound probed, but not operational: please add a quirk to driver_denylist\n"); + if (free_on_error) { + pci_set_drvdata(pci, NULL); + snd_card_free(chip->card); + } return err; } @@ -2481,12 +2489,17 @@ static void azx_remove(struct pci_dev *pci) static void azx_shutdown(struct pci_dev *pci) { struct snd_card *card = pci_get_drvdata(pci); + struct hda_intel *hda; struct azx *chip; if (!card) return; chip = card->private_data; - if (chip && chip->running) + if (!chip) + return; + hda = container_of(chip, struct hda_intel, chip); + cancel_delayed_work_sync(&hda->probe_work); + if (chip->running) __azx_shutdown_chip(chip, true); } diff --git a/sound/hda/core/bus.c b/sound/hda/core/bus.c index 81498f1e413e..5ccfa0b6c7ca 100644 --- a/sound/hda/core/bus.c +++ b/sound/hda/core/bus.c @@ -180,17 +180,39 @@ static void snd_hdac_bus_process_unsol_events(struct work_struct *work) if (!(caddr & (1 << 4))) /* no unsolicited event? */ continue; codec = bus->caddr_tbl[caddr & 0x0f]; - if (!codec || !codec->registered) + if (!codec || !codec->registered || codec->unsol_disabled) + continue; + if (!codec->dev.driver) continue; - spin_unlock_irq(&bus->reg_lock); drv = drv_to_hdac_driver(codec->dev.driver); - if (drv->unsol_event) - drv->unsol_event(codec, res); + if (!drv->unsol_event) + continue; + spin_unlock_irq(&bus->reg_lock); + drv->unsol_event(codec, res); spin_lock_irq(&bus->reg_lock); } spin_unlock_irq(&bus->reg_lock); } +/** + * snd_hdac_device_disable_unsol - block and flush unsol events for the codec + * @codec: the HDA core device + * + * Stop dispatching the unsolicited events to the given codec, and wait for + * the pending unsol event handler to finish. Called at unbinding the codec + * driver before releasing the driver resources. + */ +void snd_hdac_device_disable_unsol(struct hdac_device *codec) +{ + struct hdac_bus *bus = codec->bus; + + spin_lock_irq(&bus->reg_lock); + codec->unsol_disabled = true; + spin_unlock_irq(&bus->reg_lock); + flush_work(&bus->unsol_work); +} +EXPORT_SYMBOL_GPL(snd_hdac_device_disable_unsol); + /** * snd_hdac_bus_add_device - Add a codec to bus * @bus: HDA core bus diff --git a/sound/pci/oxygen/oxygen_pcm.c b/sound/pci/oxygen/oxygen_pcm.c index b716356010b8..75efbf59a675 100644 --- a/sound/pci/oxygen/oxygen_pcm.c +++ b/sound/pci/oxygen/oxygen_pcm.c @@ -171,16 +171,14 @@ static int oxygen_open(struct snd_pcm_substream *substream, snd_pcm_set_sync(substream); chip->streams[channel] = substream; - guard(mutex)(&chip->mutex); - chip->pcm_active |= 1 << channel; - if (channel == PCM_SPDIF) { - chip->spdif_pcm_bits = chip->spdif_bits; - chip->controls[CONTROL_SPDIF_PCM]->vd[0].access &= - ~SNDRV_CTL_ELEM_ACCESS_INACTIVE; - snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE | - SNDRV_CTL_EVENT_MASK_INFO, - &chip->controls[CONTROL_SPDIF_PCM]->id); + scoped_guard(mutex, &chip->mutex) { + chip->pcm_active |= 1 << channel; + if (channel == PCM_SPDIF) + chip->spdif_pcm_bits = chip->spdif_bits; } + if (channel == PCM_SPDIF) + snd_ctl_activate_id(chip->card, + &chip->controls[CONTROL_SPDIF_PCM]->id, 1); return 0; } @@ -220,19 +218,16 @@ static int oxygen_close(struct snd_pcm_substream *substream) struct oxygen *chip = snd_pcm_substream_chip(substream); unsigned int channel = oxygen_substream_channel(substream); - guard(mutex)(&chip->mutex); - chip->pcm_active &= ~(1 << channel); - if (channel == PCM_SPDIF) { - chip->controls[CONTROL_SPDIF_PCM]->vd[0].access |= - SNDRV_CTL_ELEM_ACCESS_INACTIVE; - snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE | - SNDRV_CTL_EVENT_MASK_INFO, - &chip->controls[CONTROL_SPDIF_PCM]->id); - } - if (channel == PCM_SPDIF || channel == PCM_MULTICH) - oxygen_update_spdif_source(chip); + scoped_guard(mutex, &chip->mutex) { + chip->pcm_active &= ~(1 << channel); + if (channel == PCM_SPDIF || channel == PCM_MULTICH) + oxygen_update_spdif_source(chip); - chip->streams[channel] = NULL; + chip->streams[channel] = NULL; + } + if (channel == PCM_SPDIF) + snd_ctl_activate_id(chip->card, + &chip->controls[CONTROL_SPDIF_PCM]->id, 0); return 0; } diff --git a/sound/pci/via82xx.c b/sound/pci/via82xx.c index 24ee1302f27d..58816dea4996 100644 --- a/sound/pci/via82xx.c +++ b/sound/pci/via82xx.c @@ -1242,11 +1242,7 @@ static int snd_via8233_playback_open(struct snd_pcm_substream *substream) VIA_DXS_MAX_VOLUME - (dxs_init_volume & 31); chip->playback_volume[stream][1] = VIA_DXS_MAX_VOLUME - (dxs_init_volume & 31); - chip->dxs_controls[stream]->vd[0].access &= - ~SNDRV_CTL_ELEM_ACCESS_INACTIVE; - snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_VALUE | - SNDRV_CTL_EVENT_MASK_INFO, - &chip->dxs_controls[stream]->id); + snd_ctl_activate_id(chip->card, &chip->dxs_controls[stream]->id, 1); } return 0; } @@ -1333,10 +1329,7 @@ static int snd_via8233_playback_close(struct snd_pcm_substream *substream) stream = viadev->reg_offset / 0x10; if (chip->dxs_controls[stream]) { - chip->dxs_controls[stream]->vd[0].access |= - SNDRV_CTL_ELEM_ACCESS_INACTIVE; - snd_ctl_notify(chip->card, SNDRV_CTL_EVENT_MASK_INFO, - &chip->dxs_controls[stream]->id); + snd_ctl_activate_id(chip->card, &chip->dxs_controls[stream]->id, 0); } return snd_via82xx_pcm_close(substream); } diff --git a/sound/sh/aica.c b/sound/sh/aica.c index 078fc7fc08f9..04f80c8c89c0 100644 --- a/sound/sh/aica.c +++ b/sound/sh/aica.c @@ -94,7 +94,7 @@ static void spu_memset(u32 toi, u32 what, int length) local_irq_save(flags); writel(what, toi + SPU_MEMORY_BASE); local_irq_restore(flags); - toi++; + toi += sizeof(what); } } diff --git a/sound/soc/amd/acp-es8336.c b/sound/soc/amd/acp-es8336.c index 9f3f11256788..0cb0ee76191d 100644 --- a/sound/soc/amd/acp-es8336.c +++ b/sound/soc/amd/acp-es8336.c @@ -30,7 +30,6 @@ static unsigned long acp2x_machine_id; static struct snd_soc_jack st_jack; -static struct device *codec_dev; static struct gpio_desc *gpio_pa; static int sof_es8316_speaker_power_event(struct snd_soc_dapm_widget *w, @@ -191,6 +190,7 @@ static const struct acpi_gpio_mapping acpi_es8336_gpios[] = { static int st_es8336_late_probe(struct snd_soc_card *card) { + struct device *codec_dev __free(put_device) = NULL; struct acpi_device *adev; int ret; @@ -198,7 +198,7 @@ static int st_es8336_late_probe(struct snd_soc_card *card) if (!adev) return -ENODEV; - codec_dev = acpi_get_first_physical_node(adev); + codec_dev = acpi_bus_get_primary_device(adev); acpi_dev_put(adev); if (!codec_dev) { dev_err(card->dev, "can not find codec dev\n"); @@ -213,7 +213,6 @@ static int st_es8336_late_probe(struct snd_soc_card *card) if (IS_ERR(gpio_pa)) { ret = dev_err_probe(card->dev, PTR_ERR(gpio_pa), "could not get pa-enable GPIO\n"); - put_device(codec_dev); return ret; } return 0; diff --git a/sound/soc/amd/acp/Kconfig b/sound/soc/amd/acp/Kconfig index e880e44b9763..b7b7b4f4a55c 100644 --- a/sound/soc/amd/acp/Kconfig +++ b/sound/soc/amd/acp/Kconfig @@ -167,7 +167,7 @@ config SND_SOC_AMD_SOF_SDW_MACH config SND_SOC_AMD_LEGACY_SDW_MACH tristate "AMD Legacy(No DSP) Soundwire Machine Driver Support" - depends on X86 && PCI && ACPI + depends on X86 && PCI && ACPI && EFI depends on SOUNDWIRE select SND_SOC_AMD_SDW_MACH_COMMON select SND_SOC_SDW_UTILS @@ -181,7 +181,7 @@ config SND_SOC_AMD_LEGACY_SDW_MACH select SND_SOC_RT715_SDW select SND_SOC_RT715_SDCA_SDW select SND_SOC_RT722_SDCA_SDW - select SND_SOC_TAS2783_SDW + select SND_SOC_TAS2783_SDW if SND_SOC_SDCA && EFI help This option enables Legacy(No DSP) sound card support for SoundWire enabled AMD platforms along with ACP PDM controller. diff --git a/sound/soc/amd/acp/acp-platform.c b/sound/soc/amd/acp/acp-platform.c index 6b1e18b31c1c..ba6dfe8fb6b7 100644 --- a/sound/soc/amd/acp/acp-platform.c +++ b/sound/soc/amd/acp/acp-platform.c @@ -248,7 +248,7 @@ static int acp_dma_open(struct snd_soc_component *component, struct snd_pcm_subs list_add_tail(&stream->list, &chip->stream_list); spin_unlock_irq(&chip->acp_lock); - return ret; + return 0; } static int acp_dma_hw_params(struct snd_soc_component *component, diff --git a/sound/soc/amd/acp/acp3x-es83xx/acp3x-es83xx.c b/sound/soc/amd/acp/acp3x-es83xx/acp3x-es83xx.c index 3a640e652314..eb0e9a6af6ef 100644 --- a/sound/soc/amd/acp/acp3x-es83xx/acp3x-es83xx.c +++ b/sound/soc/amd/acp/acp3x-es83xx/acp3x-es83xx.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -41,6 +42,11 @@ struct acp3x_es83xx_private { struct snd_soc_dapm_route mic_map[2]; }; +static void acp3x_es83xx_put_codec_device(void *data) +{ + put_device(data); +} + static const unsigned int channels[] = { DUAL_CHANNEL, }; @@ -428,7 +434,7 @@ static int acp3x_es83xx_probe(struct snd_soc_card *card) return -ENXIO; } - codec_dev = acpi_get_first_physical_node(adev); + codec_dev = acpi_bus_get_primary_device(adev); acpi_dev_put(adev); if (!codec_dev) { dev_warn(dev, "Error cannot find codec device, will defer probe\n"); @@ -441,6 +447,12 @@ static int acp3x_es83xx_probe(struct snd_soc_card *card) return -ENOMEM; } + ret = devm_add_action_or_reset(dev, + acp3x_es83xx_put_codec_device, + codec_dev); + if (ret) + return ret; + priv->codec_dev = codec_dev; priv->quirk = (unsigned long)dmi_id->driver_data; acp_drvdata->mach_priv = priv; diff --git a/sound/soc/amd/ps/ps-pdm-dma.c b/sound/soc/amd/ps/ps-pdm-dma.c index 04c014349347..28e0686e9373 100644 --- a/sound/soc/amd/ps/ps-pdm-dma.c +++ b/sound/soc/amd/ps/ps-pdm-dma.c @@ -211,7 +211,7 @@ static int acp63_pdm_dma_open(struct snd_soc_component *component, pdm_data->acp63_base = adata->acp63_base; runtime->private_data = pdm_data; - return ret; + return 0; } static int acp63_pdm_dma_hw_params(struct snd_soc_component *component, diff --git a/sound/soc/amd/ps/ps-sdw-dma.c b/sound/soc/amd/ps/ps-sdw-dma.c index f27ebbd21379..553fe11a2e50 100644 --- a/sound/soc/amd/ps/ps-sdw-dma.c +++ b/sound/soc/amd/ps/ps-sdw-dma.c @@ -337,7 +337,7 @@ static int acp63_sdw_dma_open(struct snd_soc_component *component, stream->stream_id = cpu_dai->id; stream->instance = amd_manager->instance; runtime->private_data = stream; - return ret; + return 0; } static int acp63_sdw_dma_hw_params(struct snd_soc_component *component, diff --git a/sound/soc/amd/raven/acp3x-pcm-dma.c b/sound/soc/amd/raven/acp3x-pcm-dma.c index 37ea5c572eb9..01e6ac75f35b 100644 --- a/sound/soc/amd/raven/acp3x-pcm-dma.c +++ b/sound/soc/amd/raven/acp3x-pcm-dma.c @@ -237,7 +237,7 @@ static int acp3x_dma_open(struct snd_soc_component *component, i2s_data->acp3x_base = adata->acp3x_base; runtime->private_data = i2s_data; - return ret; + return 0; } @@ -354,6 +354,8 @@ static int acp3x_dma_close(struct snd_soc_component *component, } } + kfree(ins); + return 0; } diff --git a/sound/soc/amd/renoir/acp3x-pdm-dma.c b/sound/soc/amd/renoir/acp3x-pdm-dma.c index 3f59b753243d..c0481a9ba858 100644 --- a/sound/soc/amd/renoir/acp3x-pdm-dma.c +++ b/sound/soc/amd/renoir/acp3x-pdm-dma.c @@ -233,7 +233,7 @@ static int acp_pdm_dma_open(struct snd_soc_component *component, pdm_data->acp_base = adata->acp_base; runtime->private_data = pdm_data; - return ret; + return 0; } static int acp_pdm_dma_hw_params(struct snd_soc_component *component, diff --git a/sound/soc/amd/vangogh/acp5x-pcm-dma.c b/sound/soc/amd/vangogh/acp5x-pcm-dma.c index 831e30e9b042..33d59d992ee0 100644 --- a/sound/soc/amd/vangogh/acp5x-pcm-dma.c +++ b/sound/soc/amd/vangogh/acp5x-pcm-dma.c @@ -231,7 +231,7 @@ static int acp5x_dma_open(struct snd_soc_component *component, } i2s_data->acp5x_base = adata->acp5x_base; runtime->private_data = i2s_data; - return ret; + return 0; } static int acp5x_dma_hw_params(struct snd_soc_component *component, diff --git a/sound/soc/amd/yc/acp6x-pdm-dma.c b/sound/soc/amd/yc/acp6x-pdm-dma.c index 40c4d833f4ed..afa9f66533e3 100644 --- a/sound/soc/amd/yc/acp6x-pdm-dma.c +++ b/sound/soc/amd/yc/acp6x-pdm-dma.c @@ -209,7 +209,7 @@ static int acp6x_pdm_dma_open(struct snd_soc_component *component, pdm_data->acp6x_base = adata->acp6x_base; runtime->private_data = pdm_data; - return ret; + return 0; } static int acp6x_pdm_dma_hw_params(struct snd_soc_component *component, diff --git a/sound/soc/atmel/atmel-i2s.c b/sound/soc/atmel/atmel-i2s.c index d9ad262ec44d..6ca230f8adc8 100644 --- a/sound/soc/atmel/atmel-i2s.c +++ b/sound/soc/atmel/atmel-i2s.c @@ -466,11 +466,21 @@ static int atmel_i2s_switch_mck_generator(struct atmel_i2s_dev *dev, mr |= ATMEL_I2SC_MR_IMCKMODE_I2SMCK; ret = regmap_update_bits(dev->regmap, ATMEL_I2SC_MR, mr_mask, mr); if (ret) - return ret; + goto err_disable_gclk; /* Finally enable the I2S Master Clock generator. */ - return regmap_write(dev->regmap, ATMEL_I2SC_CR, - ATMEL_I2SC_CR_CKEN); + ret = regmap_write(dev->regmap, ATMEL_I2SC_CR, ATMEL_I2SC_CR_CKEN); + if (ret) + goto err_reset_mr; + + return 0; + +err_reset_mr: + regmap_update_bits(dev->regmap, ATMEL_I2SC_MR, mr_mask, 0); +err_disable_gclk: + clk_disable_unprepare(dev->gclk); + + return ret; } static int atmel_i2s_trigger(struct snd_pcm_substream *substream, int cmd, @@ -579,21 +589,15 @@ static int atmel_i2s_sama5d2_mck_init(struct atmel_i2s_dev *dev, struct device_node *np) { struct clk *muxclk; - int err; if (!dev->gclk) return 0; - /* muxclk is optional, so we return error for probe defer only */ - muxclk = devm_clk_get(dev->dev, "muxclk"); - if (IS_ERR(muxclk)) { - err = PTR_ERR(muxclk); - if (err == -EPROBE_DEFER) - return -EPROBE_DEFER; - dev_dbg(dev->dev, - "failed to get the I2S clock control: %d\n", err); - return 0; - } + /* muxclk is optional */ + muxclk = devm_clk_get_optional(dev->dev, "muxclk"); + if (IS_ERR(muxclk)) + return dev_err_probe(dev->dev, PTR_ERR(muxclk), + "failed to get the I2S clock control\n"); return clk_set_parent(muxclk, dev->gclk); } @@ -666,13 +670,10 @@ static int atmel_i2s_probe(struct platform_device *pdev) } /* Get audio clock to generate the I2S Master Clock (I2S_MCK) */ - dev->gclk = devm_clk_get(&pdev->dev, "gclk"); - if (IS_ERR(dev->gclk)) { - if (PTR_ERR(dev->gclk) == -EPROBE_DEFER) - return -EPROBE_DEFER; - /* Master Mode not supported */ - dev->gclk = NULL; - } + dev->gclk = devm_clk_get_optional(&pdev->dev, "gclk"); + if (IS_ERR(dev->gclk)) + return PTR_ERR(dev->gclk); + dev->dev = &pdev->dev; dev->regmap = regmap; platform_set_drvdata(pdev, dev); diff --git a/sound/soc/atmel/atmel-pcm-pdc.c b/sound/soc/atmel/atmel-pcm-pdc.c index 374f93fa6e0b..552bfa30d4ba 100644 --- a/sound/soc/atmel/atmel-pcm-pdc.c +++ b/sound/soc/atmel/atmel-pcm-pdc.c @@ -295,6 +295,8 @@ static int atmel_pcm_open(struct snd_soc_component *component, } runtime->private_data = prtd; + return 0; + out: return ret; } diff --git a/sound/soc/codecs/ab8500-codec.c b/sound/soc/codecs/ab8500-codec.c index e1a0e35836e6..35df09705440 100644 --- a/sound/soc/codecs/ab8500-codec.c +++ b/sound/soc/codecs/ab8500-codec.c @@ -299,7 +299,6 @@ static const struct snd_soc_dapm_widget ab8500_dapm_widgets[] = { SND_SOC_DAPM_REGULATOR_SUPPLY("V-AUD", 0, 0), SND_SOC_DAPM_REGULATOR_SUPPLY("V-AMIC1", 0, 0), SND_SOC_DAPM_REGULATOR_SUPPLY("V-AMIC2", 0, 0), - SND_SOC_DAPM_REGULATOR_SUPPLY("V-DMIC", 0, 0), /* Power */ SND_SOC_DAPM_SUPPLY("Audio Power", @@ -324,7 +323,6 @@ static const struct snd_soc_dapm_widget ab8500_dapm_widgets[] = { SND_SOC_DAPM_AIF_OUT("AD_OUT1", NULL, 0, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_AIF_OUT("AD_OUT2", NULL, 0, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_AIF_OUT("AD_OUT3", NULL, 0, SND_SOC_NOPM, 0, 0), - SND_SOC_DAPM_AIF_OUT("AD_OUT4", NULL, 0, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_AIF_OUT("AD_OUT57", NULL, 0, SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_AIF_OUT("AD_OUT68", NULL, 0, SND_SOC_NOPM, 0, 0), @@ -584,36 +582,6 @@ static const struct snd_soc_dapm_widget ab8500_dapm_widgets[] = { SND_SOC_DAPM_SUPPLY("AD5768 Enable", AB8500_ADPATHENA, AB8500_ADPATHENA_ENAD5768, 0, NULL, 0), - /* Digital Microphone path */ - - SND_SOC_DAPM_INPUT("DMic 1"), - SND_SOC_DAPM_INPUT("DMic 2"), - SND_SOC_DAPM_INPUT("DMic 3"), - SND_SOC_DAPM_INPUT("DMic 4"), - SND_SOC_DAPM_INPUT("DMic 5"), - SND_SOC_DAPM_INPUT("DMic 6"), - - SND_SOC_DAPM_MIXER("DMIC1", - AB8500_DIGMICCONF, AB8500_DIGMICCONF_ENDMIC1, 0, - NULL, 0), - SND_SOC_DAPM_MIXER("DMIC2", - AB8500_DIGMICCONF, AB8500_DIGMICCONF_ENDMIC2, 0, - NULL, 0), - SND_SOC_DAPM_MIXER("DMIC3", - AB8500_DIGMICCONF, AB8500_DIGMICCONF_ENDMIC3, 0, - NULL, 0), - SND_SOC_DAPM_MIXER("DMIC4", - AB8500_DIGMICCONF, AB8500_DIGMICCONF_ENDMIC4, 0, - NULL, 0), - SND_SOC_DAPM_MIXER("DMIC5", - AB8500_DIGMICCONF, AB8500_DIGMICCONF_ENDMIC5, 0, - NULL, 0), - SND_SOC_DAPM_MIXER("DMIC6", - AB8500_DIGMICCONF, AB8500_DIGMICCONF_ENDMIC6, 0, - NULL, 0), - SND_SOC_DAPM_MIXER("AD4 Channel Volume", - SND_SOC_NOPM, 0, 0, - NULL, 0), /* Acoustical Noise Cancellation path */ SND_SOC_DAPM_MUX("ANC Source", @@ -648,6 +616,40 @@ static const struct snd_soc_dapm_widget ab8500_dapm_widgets[] = { NULL, 0), }; +static const struct snd_soc_dapm_widget ab8500_dmic_dapm_widgets[] = { + SND_SOC_DAPM_REGULATOR_SUPPLY("V-DMIC", 0, 0), + SND_SOC_DAPM_AIF_OUT("AD_OUT4", NULL, 0, SND_SOC_NOPM, 0, 0), + + SND_SOC_DAPM_INPUT("DMic 1"), + SND_SOC_DAPM_INPUT("DMic 2"), + SND_SOC_DAPM_INPUT("DMic 3"), + SND_SOC_DAPM_INPUT("DMic 4"), + SND_SOC_DAPM_INPUT("DMic 5"), + SND_SOC_DAPM_INPUT("DMic 6"), + + SND_SOC_DAPM_MIXER("DMIC1", + AB8500_DIGMICCONF, AB8500_DIGMICCONF_ENDMIC1, 0, + NULL, 0), + SND_SOC_DAPM_MIXER("DMIC2", + AB8500_DIGMICCONF, AB8500_DIGMICCONF_ENDMIC2, 0, + NULL, 0), + SND_SOC_DAPM_MIXER("DMIC3", + AB8500_DIGMICCONF, AB8500_DIGMICCONF_ENDMIC3, 0, + NULL, 0), + SND_SOC_DAPM_MIXER("DMIC4", + AB8500_DIGMICCONF, AB8500_DIGMICCONF_ENDMIC4, 0, + NULL, 0), + SND_SOC_DAPM_MIXER("DMIC5", + AB8500_DIGMICCONF, AB8500_DIGMICCONF_ENDMIC5, 0, + NULL, 0), + SND_SOC_DAPM_MIXER("DMIC6", + AB8500_DIGMICCONF, AB8500_DIGMICCONF_ENDMIC6, 0, + NULL, 0), + SND_SOC_DAPM_MIXER("AD4 Channel Volume", + SND_SOC_NOPM, 0, 0, + NULL, 0), +}; + /* * DAPM-routes */ @@ -853,35 +855,6 @@ static const struct snd_soc_dapm_route ab8500_dapm_routes[] = { {"AD_OUT68", NULL, "Main Supply"}, {"AD_OUT68", NULL, "AD6 Channel Volume"}, - /* Digital Microphone path */ - - {"DMic 1", NULL, "V-DMIC"}, - {"DMic 2", NULL, "V-DMIC"}, - {"DMic 3", NULL, "V-DMIC"}, - {"DMic 4", NULL, "V-DMIC"}, - {"DMic 5", NULL, "V-DMIC"}, - {"DMic 6", NULL, "V-DMIC"}, - - {"DMIC1", NULL, "DMic 1"}, - {"DMIC2", NULL, "DMic 2"}, - {"DMIC3", NULL, "DMic 3"}, - {"DMIC4", NULL, "DMic 4"}, - {"DMIC5", NULL, "DMic 5"}, - {"DMIC6", NULL, "DMic 6"}, - - {"AD1 Source Select", "DMic 1", "DMIC1"}, - {"AD2 Source Select", "DMic 2", "DMIC2"}, - {"AD3 Source Select", "DMic 3", "DMIC3"}, - {"AD5 Source Select", "DMic 5", "DMIC5"}, - {"AD6 Source Select", "DMic 6", "DMIC6"}, - - {"AD4 Channel Volume", NULL, "DMIC4"}, - {"AD4 Channel Volume", NULL, "AD34 Enable"}, - - {"ab8500_0c", NULL, "AD_OUT4"}, - {"AD_OUT4", NULL, "Main Supply"}, - {"AD_OUT4", NULL, "AD4 Channel Volume"}, - /* LineIn Bypass path */ {"LINL to HSL Volume", NULL, "LINL Enable"}, @@ -911,7 +884,6 @@ static const struct snd_soc_dapm_route ab8500_dapm_routes[] = { {"Sidetone Left Source", "Headset Left", "DA_IN1"}, {"Sidetone Right Source", "LineIn Right", "AD2 Channel Volume"}, {"Sidetone Right Source", "Mic 1", "AD3 Channel Volume"}, - {"Sidetone Right Source", "DMic 4", "AD4 Channel Volume"}, {"Sidetone Right Source", "Headset Right", "DA_IN2"}, {"STFIR1 Control", NULL, "Sidetone Left Source"}, @@ -924,6 +896,37 @@ static const struct snd_soc_dapm_route ab8500_dapm_routes[] = { {"DA2 Enable", NULL, "STFIR2 Volume"}, }; +static const struct snd_soc_dapm_route ab8500_dmic_dapm_routes[] = { + {"DMic 1", NULL, "V-DMIC"}, + {"DMic 2", NULL, "V-DMIC"}, + {"DMic 3", NULL, "V-DMIC"}, + {"DMic 4", NULL, "V-DMIC"}, + {"DMic 5", NULL, "V-DMIC"}, + {"DMic 6", NULL, "V-DMIC"}, + + {"DMIC1", NULL, "DMic 1"}, + {"DMIC2", NULL, "DMic 2"}, + {"DMIC3", NULL, "DMic 3"}, + {"DMIC4", NULL, "DMic 4"}, + {"DMIC5", NULL, "DMic 5"}, + {"DMIC6", NULL, "DMic 6"}, + + {"AD1 Source Select", "DMic 1", "DMIC1"}, + {"AD2 Source Select", "DMic 2", "DMIC2"}, + {"AD3 Source Select", "DMic 3", "DMIC3"}, + {"AD5 Source Select", "DMic 5", "DMIC5"}, + {"AD6 Source Select", "DMic 6", "DMIC6"}, + + {"AD4 Channel Volume", NULL, "DMIC4"}, + {"AD4 Channel Volume", NULL, "AD34 Enable"}, + + {"ab8500_0c", NULL, "AD_OUT4"}, + {"AD_OUT4", NULL, "Main Supply"}, + {"AD_OUT4", NULL, "AD4 Channel Volume"}, + + {"Sidetone Right Source", "DMic 4", "AD4 Channel Volume"}, +}; + static const struct snd_soc_dapm_route ab8500_dapm_routes_mic1a_vamicx[] = { {"MIC1A V-AMICx Enable", NULL, "V-AMIC1"}, {"MIC1A V-AMICx Enable", NULL, "V-AMIC2"}, @@ -2043,13 +2046,30 @@ static int ab8500_codec_probe(struct snd_soc_component *component) { struct device *dev = component->dev; struct device_node *np = dev->of_node; + struct ab8500 *ab8500 = dev_get_drvdata(dev->parent); struct ab8500_codec_platform_data codec_pdata; + struct snd_soc_dapm_context *dapm; int status; dev_dbg(dev, "%s: Enter.\n", __func__); ab8500_codec_of_probe(dev, np, &codec_pdata); + if (is_ab8500(ab8500)) { + dapm = snd_soc_component_to_dapm(component); + status = snd_soc_dapm_new_controls(dapm, + ab8500_dmic_dapm_widgets, + ARRAY_SIZE(ab8500_dmic_dapm_widgets)); + if (status) + return status; + + status = snd_soc_dapm_add_routes(dapm, + ab8500_dmic_dapm_routes, + ARRAY_SIZE(ab8500_dmic_dapm_routes)); + if (status) + return status; + } + status = ab8500_audio_init_audioblock(component); if (status < 0) { dev_err(dev, "%s: failed to init audio-block (%d)!\n", diff --git a/sound/soc/codecs/adau17x1.c b/sound/soc/codecs/adau17x1.c index 26d7eb437ad1..00efaff44e92 100644 --- a/sound/soc/codecs/adau17x1.c +++ b/sound/soc/codecs/adau17x1.c @@ -989,9 +989,7 @@ int adau17x1_resume(struct snd_soc_component *component) if (adau->switch_mode) adau->switch_mode(component->dev); - regcache_sync(adau->regmap); - - return 0; + return regcache_sync(adau->regmap); } EXPORT_SYMBOL_GPL(adau17x1_resume); diff --git a/sound/soc/codecs/ak4642.c b/sound/soc/codecs/ak4642.c index 08ec2035b270..37ac298835d6 100644 --- a/sound/soc/codecs/ak4642.c +++ b/sound/soc/codecs/ak4642.c @@ -533,8 +533,7 @@ static int ak4642_resume(struct snd_soc_component *component) struct regmap *regmap = dev_get_regmap(component->dev, NULL); regcache_cache_only(regmap, false); - regcache_sync(regmap); - return 0; + return regcache_sync(regmap); } static int ak4642_probe(struct snd_soc_component *component) { diff --git a/sound/soc/codecs/aw88399-lib.c b/sound/soc/codecs/aw88399-lib.c index 809c2faa0c0c..1ba0147cf4df 100644 --- a/sound/soc/codecs/aw88399-lib.c +++ b/sound/soc/codecs/aw88399-lib.c @@ -183,6 +183,19 @@ static int aw_dev_check_sysst(struct aw88399 *aw88399) else check_val = AW88399_BIT_SYSST_SWS_CHECK; + /* + * When an external power supply (EPS) is used to feed the amplifier + * (EN_HVBAT bit in BSTCTRL10 set), the boost converter is bypassed, + * and BSTS (boost finished) will never assert. Skip the BSTS check in + * this case, matching the vendor driver's behavior. + */ + ret = regmap_read(aw_dev->regmap, AW88399_BSTCTRL10_REG, ®_val); + if (ret) + return ret; + + if (reg_val & (~AW88399_EPS_EN_MASK)) + check_val &= ~AW88399_BSTS_FINISHED_VALUE; + /* * On some hardware the BSTS (boost-finished) status bit does not * reliably assert even when audio output is working normally. diff --git a/sound/soc/codecs/cs42l56.c b/sound/soc/codecs/cs42l56.c index f0ea5309a6d4..a259440db0f5 100644 --- a/sound/soc/codecs/cs42l56.c +++ b/sound/soc/codecs/cs42l56.c @@ -419,7 +419,6 @@ static const struct snd_kcontrol_new cs42l56_snd_controls[] = { CS42L56_PGAB_MUX_VOLUME, 0, 0x34, 0x24, pga_tlv), SOC_DOUBLE_R_TLV("ADC Volume", CS42L56_ADCA_ATTENUATOR, CS42L56_ADCB_ATTENUATOR, 0, 0x00, 1, adc_tlv), - SOC_DOUBLE("ADC Mute Switch", CS42L56_MISC_ADC_CTL, 2, 3, 1, 1), SOC_DOUBLE("ADC Boost Switch", CS42L56_GAIN_BIAS_CTL, 3, 2, 1, 1), SOC_DOUBLE_R_SX_TLV("Headphone Volume", CS42L56_HPA_VOLUME, diff --git a/sound/soc/codecs/da7213.c b/sound/soc/codecs/da7213.c index 923b997efbc4..4990feaa8259 100644 --- a/sound/soc/codecs/da7213.c +++ b/sound/soc/codecs/da7213.c @@ -2091,16 +2091,6 @@ static int da7213_probe(struct snd_soc_component *component) pm_runtime_put_sync(component->dev); - /* Check if MCLK provided */ - da7213->mclk = devm_clk_get_optional(component->dev, "mclk"); - if (IS_ERR(da7213->mclk)) - return PTR_ERR(da7213->mclk); - if (da7213->mclk) - /* Do automatic PLL handling assuming fixed clock until - * set_pll() has been called. This makes the codec usable - * with the simple-audio-card driver. */ - da7213->fixed_clk_auto_pll = true; - /* Default infinite tone gen, start/stop by Kcontrol */ snd_soc_component_write(component, DA7213_TONE_GEN_CYCLES, DA7213_BEEP_CYCLES_MASK); @@ -2229,6 +2219,19 @@ static int da7213_i2c_probe(struct i2c_client *i2c) mutex_init(&da7213->ctrl_lock); + /* Check if MCLK provided */ + da7213->mclk = devm_clk_get_optional(&i2c->dev, "mclk"); + if (IS_ERR(da7213->mclk)) + return dev_err_probe(&i2c->dev, PTR_ERR(da7213->mclk), + "failed to get mclk\n"); + if (da7213->mclk) + /* + * Do automatic PLL handling assuming fixed clock until + * set_pll() has been called. This makes the codec usable + * with the simple-audio-card driver. + */ + da7213->fixed_clk_auto_pll = true; + pm_runtime_set_autosuspend_delay(&i2c->dev, 100); pm_runtime_use_autosuspend(&i2c->dev); pm_runtime_set_active(&i2c->dev); diff --git a/sound/soc/codecs/da732x.c b/sound/soc/codecs/da732x.c index 12d1ac98461e..f7a2bb42c811 100644 --- a/sound/soc/codecs/da732x.c +++ b/sound/soc/codecs/da732x.c @@ -511,7 +511,7 @@ static const struct snd_kcontrol_new da732x_snd_controls[] = { SOC_SINGLE_TLV("ACD2 EQ Band 5 Volume", DA732X_REG_ADC2_EQ5, DA732X_EQ_BAND5_SHIFT, DA732X_EQ_VOL_VAL_MAX, DA732X_INVERT, eq_band_pga_tlv), - SOC_SINGLE_TLV("ADC2 EQ Overall Volume", DA732X_REG_ADC1_EQ5, + SOC_SINGLE_TLV("ADC2 EQ Overall Volume", DA732X_REG_ADC2_EQ5, DA732X_EQ_OVERALL_SHIFT, DA732X_EQ_OVERALL_VOL_VAL_MAX, DA732X_INVERT, eq_overall_tlv), diff --git a/sound/soc/codecs/es8316.c b/sound/soc/codecs/es8316.c index 24ec8b211cdb..4c33a243c1e1 100644 --- a/sound/soc/codecs/es8316.c +++ b/sound/soc/codecs/es8316.c @@ -810,9 +810,7 @@ static int es8316_resume(struct snd_soc_component *component) struct es8316_priv *es8316 = snd_soc_component_get_drvdata(component); regcache_cache_only(es8316->regmap, false); - regcache_sync(es8316->regmap); - - return 0; + return regcache_sync(es8316->regmap); } static int es8316_suspend(struct snd_soc_component *component) diff --git a/sound/soc/codecs/es8323.c b/sound/soc/codecs/es8323.c index b926340256be..03d516d70c43 100644 --- a/sound/soc/codecs/es8323.c +++ b/sound/soc/codecs/es8323.c @@ -733,9 +733,7 @@ static int es8323_resume(struct snd_soc_component *component) struct es8323_priv *es8323 = snd_soc_component_get_drvdata(component); regcache_cache_only(es8323->regmap, false); - regcache_sync(es8323->regmap); - - return 0; + return regcache_sync(es8323->regmap); } static const struct snd_soc_component_driver soc_component_dev_es8323 = { diff --git a/sound/soc/codecs/es8326.c b/sound/soc/codecs/es8326.c index b6eadc2e9659..61396671cf9f 100644 --- a/sound/soc/codecs/es8326.c +++ b/sound/soc/codecs/es8326.c @@ -264,7 +264,7 @@ static const struct snd_kcontrol_new es8326_snd_controls[] = { SOC_SINGLE_TLV("DRE Gate Volume", ES8326_ADC_DRE_GATE, 4, 0x07, 0, dre_gate_tlv), SOC_SINGLE("ALC Capture Switch", ES8326_ALC_RECOVERY, 3, 1, 0), - SOC_SINGLE_TLV("ALC Capture Recovery Level", ES8326_ALC_LEVEL, + SOC_SINGLE_TLV("ALC Capture Recovery Level", ES8326_ALC_RECOVERY, 0, 4, 0, drc_recovery_tlv), SOC_ENUM("ALC Capture Winsize", alc_winsize), SOC_SINGLE_TLV("ALC Capture Target Level", ES8326_ALC_LEVEL, @@ -1130,18 +1130,28 @@ static int es8326_resume(struct snd_soc_component *component) { struct es8326_priv *es8326 = snd_soc_component_get_drvdata(component); unsigned int reg; + int ret; regcache_cache_only(es8326->regmap, false); regcache_cache_bypass(es8326->regmap, true); - regmap_read(es8326->regmap, ES8326_CLK_RESAMPLE, ®); + ret = regmap_read(es8326->regmap, ES8326_CLK_RESAMPLE, ®); regcache_cache_bypass(es8326->regmap, false); + if (ret) + return ret; + /* reset internal clock state */ - if (reg == 0x05) - regmap_write(es8326->regmap, ES8326_CLK_CTL, ES8326_CLK_ON); - else + if (reg == 0x05) { + ret = regmap_write(es8326->regmap, ES8326_CLK_CTL, + ES8326_CLK_ON); + if (ret) + return ret; + } else { es8326_init(component); + } - regcache_sync(es8326->regmap); + ret = regcache_sync(es8326->regmap); + if (ret) + return ret; es8326_irq(es8326->irq, es8326); return 0; diff --git a/sound/soc/codecs/es8375.c b/sound/soc/codecs/es8375.c index e8747bc24433..8a3e3a6a748f 100644 --- a/sound/soc/codecs/es8375.c +++ b/sound/soc/codecs/es8375.c @@ -577,20 +577,24 @@ static int es8375_resume(struct snd_soc_component *component) { struct es8375_priv *es8375 = snd_soc_component_get_drvdata(component); unsigned int reg; + int ret; regcache_cache_only(es8375->regmap, false); regcache_cache_bypass(es8375->regmap, true); - regmap_read(es8375->regmap, ES8375_CLK_MGR2, ®); + ret = regmap_read(es8375->regmap, ES8375_CLK_MGR2, ®); regcache_cache_bypass(es8375->regmap, false); + if (ret) + return ret; - if (reg == 0x00) + if (reg == 0x00) { es8375_init(component); - else - es8375_set_bias_level(component, SND_SOC_BIAS_ON); - - regcache_sync(es8375->regmap); + } else { + ret = es8375_set_bias_level(component, SND_SOC_BIAS_ON); + if (ret) + return ret; + } - return 0; + return regcache_sync(es8375->regmap); } static int es8375_codec_probe(struct snd_soc_component *component) @@ -661,7 +665,7 @@ static int es8375_read_device_properities(struct device *dev, struct es8375_priv return ret; } - es8375->mclk = devm_clk_get(dev, "mclk"); + es8375->mclk = devm_clk_get_optional(dev, "mclk"); if (IS_ERR(es8375->mclk)) return dev_err_probe(dev, PTR_ERR(es8375->mclk), "unable to get mclk\n"); diff --git a/sound/soc/codecs/es8375.h b/sound/soc/codecs/es8375.h index 11e3ceec9b68..70e56813fae7 100644 --- a/sound/soc/codecs/es8375.h +++ b/sound/soc/codecs/es8375.h @@ -91,7 +91,7 @@ // Function values #define ES8375_ADC_OSR_GAIN_MAX 0x3F -#define ES8375_DMIC_GAIN_MAX 0x04 +#define ES8375_DMIC_GAIN_MAX 0x03 #define ES8375_ADC_AUTOMUTE_ATTN_MAX 0x1F #define ES8375_AUTOMUTE_NG_MAX 0x07 #define ES8375_ADC_VOLUME_MAX 0xFF diff --git a/sound/soc/codecs/es8389.c b/sound/soc/codecs/es8389.c index 2ea0c4052ce1..7d6d47e3065b 100644 --- a/sound/soc/codecs/es8389.c +++ b/sound/soc/codecs/es8389.c @@ -1032,20 +1032,28 @@ static int es8389_resume(struct snd_soc_component *component) { struct es8389_private *es8389 = snd_soc_component_get_drvdata(component); unsigned int regv; + int ret; regcache_cache_only(es8389->regmap, false); regcache_cache_bypass(es8389->regmap, true); - regmap_read(es8389->regmap, ES8389_RESET, ®v); + ret = regmap_read(es8389->regmap, ES8389_RESET, ®v); + if (ret) + goto disable_bypass; - if (regv == 0xff) + if (regv == 0xff) { es8389_init(component); - else - es8389_set_bias_level(component, SND_SOC_BIAS_ON); + } else { + ret = es8389_set_bias_level(component, SND_SOC_BIAS_ON); + if (ret) + goto disable_bypass; + } +disable_bypass: regcache_cache_bypass(es8389->regmap, false); - regcache_sync(es8389->regmap); + if (ret) + return ret; - return 0; + return regcache_sync(es8389->regmap); } static int es8389_probe(struct snd_soc_component *component) diff --git a/sound/soc/codecs/fs210x.c b/sound/soc/codecs/fs210x.c index 510cbeea5b62..316f3fe80d93 100644 --- a/sound/soc/codecs/fs210x.c +++ b/sound/soc/codecs/fs210x.c @@ -610,8 +610,9 @@ static int fs210x_init_chip(struct fs210x_priv *fs210x) if (!ret) { regcache_cache_only(fs210x->regmap, false); regcache_mark_dirty(fs210x->regmap); - regcache_sync(fs210x->regmap); - fs210x->is_inited = true; + ret = regcache_sync(fs210x->regmap); + if (!ret) + fs210x->is_inited = true; } return ret; diff --git a/sound/soc/codecs/mt6359-accdet.c b/sound/soc/codecs/mt6359-accdet.c index e1190c644021..54ec1c6bd64b 100644 --- a/sound/soc/codecs/mt6359-accdet.c +++ b/sound/soc/codecs/mt6359-accdet.c @@ -914,6 +914,14 @@ int mt6359_accdet_enable_jack_detect(struct snd_soc_component *component, } EXPORT_SYMBOL_GPL(mt6359_accdet_enable_jack_detect); +static void mt6359_accdet_destroy_workqueues(void *data) +{ + struct mt6359_accdet *priv = data; + + destroy_workqueue(priv->jd_workqueue); + destroy_workqueue(priv->accdet_workqueue); +} + static int mt6359_accdet_probe(struct platform_device *pdev) { struct mt6359_accdet *priv; @@ -955,6 +963,26 @@ static int mt6359_accdet_probe(struct platform_device *pdev) } mutex_init(&priv->res_lock); + priv->accdet_workqueue = create_singlethread_workqueue("accdet"); + INIT_WORK(&priv->accdet_work, mt6359_accdet_work); + if (!priv->accdet_workqueue) { + dev_err(&pdev->dev, "Failed to create accdet workqueue\n"); + return -ENOMEM; + } + + priv->jd_workqueue = create_singlethread_workqueue("mt6359_accdet_jd"); + INIT_WORK(&priv->jd_work, mt6359_accdet_jd_work); + if (!priv->jd_workqueue) { + dev_err(&pdev->dev, "Failed to create jack detect workqueue\n"); + destroy_workqueue(priv->accdet_workqueue); + return -ENOMEM; + } + + ret = devm_add_action_or_reset(&pdev->dev, + mt6359_accdet_destroy_workqueues, priv); + if (ret) + return ret; + priv->accdet_irq = platform_get_irq(pdev, 0); if (priv->accdet_irq >= 0) { ret = devm_request_threaded_irq(&pdev->dev, priv->accdet_irq, @@ -1000,22 +1028,6 @@ static int mt6359_accdet_probe(struct platform_device *pdev) } } - priv->accdet_workqueue = create_singlethread_workqueue("accdet"); - INIT_WORK(&priv->accdet_work, mt6359_accdet_work); - if (!priv->accdet_workqueue) { - dev_err(&pdev->dev, "Failed to create accdet workqueue\n"); - ret = -1; - goto err_accdet_wq; - } - - priv->jd_workqueue = create_singlethread_workqueue("mt6359_accdet_jd"); - INIT_WORK(&priv->jd_work, mt6359_accdet_jd_work); - if (!priv->jd_workqueue) { - dev_err(&pdev->dev, "Failed to create jack detect workqueue\n"); - ret = -1; - goto err_eint_wq; - } - platform_set_drvdata(pdev, priv); ret = devm_snd_soc_register_component(&pdev->dev, &mt6359_accdet_soc_driver, @@ -1034,12 +1046,6 @@ static int mt6359_accdet_probe(struct platform_device *pdev) mt6359_accdet_jack_report(priv); return 0; - -err_eint_wq: - destroy_workqueue(priv->accdet_workqueue); -err_accdet_wq: - dev_err(&pdev->dev, "%s error. now exit.!\n", __func__); - return ret; } static struct platform_driver mt6359_accdet_driver = { diff --git a/sound/soc/codecs/nau8540.c b/sound/soc/codecs/nau8540.c index fefbd5722c00..6c421e2386aa 100644 --- a/sound/soc/codecs/nau8540.c +++ b/sound/soc/codecs/nau8540.c @@ -897,9 +897,7 @@ static int __maybe_unused nau8540_resume(struct snd_soc_component *component) struct nau8540 *nau8540 = snd_soc_component_get_drvdata(component); regcache_cache_only(nau8540->regmap, false); - regcache_sync(nau8540->regmap); - - return 0; + return regcache_sync(nau8540->regmap); } static const struct snd_soc_component_driver nau8540_component_driver = { diff --git a/sound/soc/codecs/nau8822.c b/sound/soc/codecs/nau8822.c index b4ae269873c4..07c9109cca7a 100644 --- a/sound/soc/codecs/nau8822.c +++ b/sound/soc/codecs/nau8822.c @@ -1059,10 +1059,14 @@ static int nau8822_suspend(struct snd_soc_component *component) { struct nau8822 *nau8822 = snd_soc_component_get_drvdata(component); struct snd_soc_dapm_context *dapm = snd_soc_component_to_dapm(component); + int ret; snd_soc_dapm_force_bias_level(dapm, SND_SOC_BIAS_OFF); - regulator_bulk_disable(NAU8822_NUM_SUPPLIES, nau8822->supplies); + ret = regulator_bulk_disable(NAU8822_NUM_SUPPLIES, nau8822->supplies); + if (ret) + return ret; + regcache_cache_only(nau8822->regmap, true); regcache_mark_dirty(nau8822->regmap); return 0; @@ -1072,7 +1076,9 @@ static int nau8822_resume(struct snd_soc_component *component) { struct nau8822 *nau8822 = snd_soc_component_get_drvdata(component); struct snd_soc_dapm_context *dapm = snd_soc_component_to_dapm(component); - int ret = regulator_bulk_enable(NAU8822_NUM_SUPPLIES, nau8822->supplies); + int ret; + + ret = regulator_bulk_enable(NAU8822_NUM_SUPPLIES, nau8822->supplies); if (ret) { dev_err(component->dev, @@ -1082,7 +1088,10 @@ static int nau8822_resume(struct snd_soc_component *component) fsleep(100); - regcache_sync(nau8822->regmap); + regcache_cache_only(nau8822->regmap, false); + ret = regcache_sync(nau8822->regmap); + if (ret) + return ret; snd_soc_dapm_force_bias_level(dapm, SND_SOC_BIAS_STANDBY); diff --git a/sound/soc/codecs/rt1011.c b/sound/soc/codecs/rt1011.c index 15488a059283..6e783c3d14ae 100644 --- a/sound/soc/codecs/rt1011.c +++ b/sound/soc/codecs/rt1011.c @@ -2094,9 +2094,7 @@ static int rt1011_resume(struct snd_soc_component *component) struct rt1011_priv *rt1011 = snd_soc_component_get_drvdata(component); regcache_cache_only(rt1011->regmap, false); - regcache_sync(rt1011->regmap); - - return 0; + return regcache_sync(rt1011->regmap); } #else #define rt1011_suspend NULL diff --git a/sound/soc/codecs/rt1015.c b/sound/soc/codecs/rt1015.c index ff0c08ff610e..c6cb8d3ec045 100644 --- a/sound/soc/codecs/rt1015.c +++ b/sound/soc/codecs/rt1015.c @@ -488,35 +488,72 @@ static int rt1015_bypass_boost_get(struct snd_kcontrol *kcontrol, return 0; } -static void rt1015_calibrate(struct rt1015_priv *rt1015) +static int rt1015_calibrate(struct rt1015_priv *rt1015) { struct snd_soc_component *component = rt1015->component; struct snd_soc_dapm_context *dapm = snd_soc_component_to_dapm(component); struct regmap *regmap = rt1015->regmap; + int ret, sync_ret; snd_soc_dapm_mutex_lock(dapm); regcache_cache_bypass(regmap, true); - regmap_write(regmap, RT1015_CLK_DET, 0x0000); - regmap_write(regmap, RT1015_PWR4, 0x00B2); - regmap_write(regmap, RT1015_PWR_STATE_CTRL, 0x0009); + ret = regmap_write(regmap, RT1015_CLK_DET, 0x0000); + if (ret) + goto restore_cache; + + ret = regmap_write(regmap, RT1015_PWR4, 0x00B2); + if (ret) + goto restore_cache; + + ret = regmap_write(regmap, RT1015_PWR_STATE_CTRL, 0x0009); + if (ret) + goto restore_cache; + msleep(100); - regmap_write(regmap, RT1015_PWR_STATE_CTRL, 0x000A); + ret = regmap_write(regmap, RT1015_PWR_STATE_CTRL, 0x000A); + if (ret) + goto restore_cache; + msleep(100); - regmap_write(regmap, RT1015_PWR_STATE_CTRL, 0x000C); + ret = regmap_write(regmap, RT1015_PWR_STATE_CTRL, 0x000C); + if (ret) + goto restore_cache; + msleep(100); - regmap_write(regmap, RT1015_CLSD_INTERNAL8, 0x2028); - regmap_write(regmap, RT1015_CLSD_INTERNAL9, 0x0140); - regmap_write(regmap, RT1015_PWR_STATE_CTRL, 0x000D); + ret = regmap_write(regmap, RT1015_CLSD_INTERNAL8, 0x2028); + if (ret) + goto restore_cache; + + ret = regmap_write(regmap, RT1015_CLSD_INTERNAL9, 0x0140); + if (ret) + goto restore_cache; + + ret = regmap_write(regmap, RT1015_PWR_STATE_CTRL, 0x000D); + if (ret) + goto restore_cache; + msleep(300); - regmap_write(regmap, RT1015_PWR_STATE_CTRL, 0x0008); - regmap_write(regmap, RT1015_SYS_RST1, 0x05F5); - regmap_write(regmap, RT1015_CLK_DET, 0x8000); + ret = regmap_write(regmap, RT1015_PWR_STATE_CTRL, 0x0008); + if (ret) + goto restore_cache; + + ret = regmap_write(regmap, RT1015_SYS_RST1, 0x05F5); + if (ret) + goto restore_cache; + + ret = regmap_write(regmap, RT1015_CLK_DET, 0x8000); + +restore_cache: regcache_cache_bypass(regmap, false); regcache_mark_dirty(regmap); - regcache_sync(regmap); + sync_ret = regcache_sync(regmap); + if (!ret) + ret = sync_ret; snd_soc_dapm_mutex_unlock(dapm); + + return ret; } static int rt1015_bypass_boost_put(struct snd_kcontrol *kcontrol, @@ -525,6 +562,8 @@ static int rt1015_bypass_boost_put(struct snd_kcontrol *kcontrol, struct snd_soc_component *component = snd_kcontrol_chip(kcontrol); struct rt1015_priv *rt1015 = snd_soc_component_get_drvdata(component); + int bypass_boost = rt1015->bypass_boost; + int ret; if (rt1015->dac_is_used) { dev_err(component->dev, "DAC is being used!\n"); @@ -534,13 +573,23 @@ static int rt1015_bypass_boost_put(struct snd_kcontrol *kcontrol, rt1015->bypass_boost = ucontrol->value.integer.value[0]; if (rt1015->bypass_boost == RT1015_Bypass_Boost && !rt1015->cali_done) { - rt1015_calibrate(rt1015); - rt1015->cali_done = 1; + ret = rt1015_calibrate(rt1015); + if (ret) + goto restore_boost; + + ret = regmap_write(rt1015->regmap, RT1015_MONO_DYNA_CTRL, + 0x0010); + if (ret) + goto restore_boost; - regmap_write(rt1015->regmap, RT1015_MONO_DYNA_CTRL, 0x0010); + rt1015->cali_done = 1; } return 0; + +restore_boost: + rt1015->bypass_boost = bypass_boost; + return ret; } static const char * const rt1015_dac_output_vol_select[] = { diff --git a/sound/soc/codecs/rt1016.c b/sound/soc/codecs/rt1016.c index 11c8c45574a1..12b97c04d033 100644 --- a/sound/soc/codecs/rt1016.c +++ b/sound/soc/codecs/rt1016.c @@ -570,9 +570,7 @@ static int rt1016_resume(struct snd_soc_component *component) struct rt1016_priv *rt1016 = snd_soc_component_get_drvdata(component); regcache_cache_only(rt1016->regmap, false); - regcache_sync(rt1016->regmap); - - return 0; + return regcache_sync(rt1016->regmap); } #else #define rt1016_suspend NULL diff --git a/sound/soc/codecs/rt1305.c b/sound/soc/codecs/rt1305.c index 2d5fad76cf52..601cbf9eb1e2 100644 --- a/sound/soc/codecs/rt1305.c +++ b/sound/soc/codecs/rt1305.c @@ -896,9 +896,7 @@ static int rt1305_resume(struct snd_soc_component *component) struct rt1305_priv *rt1305 = snd_soc_component_get_drvdata(component); regcache_cache_only(rt1305->regmap, false); - regcache_sync(rt1305->regmap); - - return 0; + return regcache_sync(rt1305->regmap); } #else #define rt1305_suspend NULL diff --git a/sound/soc/codecs/rt1308.c b/sound/soc/codecs/rt1308.c index 630946cd7cdf..df95cfbd76d6 100644 --- a/sound/soc/codecs/rt1308.c +++ b/sound/soc/codecs/rt1308.c @@ -715,9 +715,7 @@ static int rt1308_resume(struct snd_soc_component *component) struct rt1308_priv *rt1308 = snd_soc_component_get_drvdata(component); regcache_cache_only(rt1308->regmap, false); - regcache_sync(rt1308->regmap); - - return 0; + return regcache_sync(rt1308->regmap); } #else #define rt1308_suspend NULL diff --git a/sound/soc/codecs/rt1318.c b/sound/soc/codecs/rt1318.c index 55607f1b9a1e..3dcec7564b82 100644 --- a/sound/soc/codecs/rt1318.c +++ b/sound/soc/codecs/rt1318.c @@ -1075,8 +1075,7 @@ static int rt1318_resume(struct snd_soc_component *component) struct rt1318_priv *rt1318 = snd_soc_component_get_drvdata(component); regcache_cache_only(rt1318->regmap, false); - regcache_sync(rt1318->regmap); - return 0; + return regcache_sync(rt1318->regmap); } #else #define rt1318_suspend NULL diff --git a/sound/soc/codecs/rt1320-sdw.c b/sound/soc/codecs/rt1320-sdw.c index 72af413306fa..444a91755be9 100644 --- a/sound/soc/codecs/rt1320-sdw.c +++ b/sound/soc/codecs/rt1320-sdw.c @@ -2470,7 +2470,7 @@ static int rt1320_io_init(struct device *dev, struct sdw_slave *slave) dev_dbg(dev, "%s amp func_status=0x%x\n", __func__, amp_func_status); /* initialization write */ - if ((amp_func_status & FUNCTION_NEEDS_INITIALIZATION) || !rt1320->first_hw_init) { + if ((amp_func_status & FUNCTION_NEEDS_INITIALIZATION)) { switch (rt1320->dev_id) { case RT1320_DEV_ID: if (rt1320->version_id < RT1320_VC) diff --git a/sound/soc/codecs/rt5616.c b/sound/soc/codecs/rt5616.c index 46ee412dc81d..73a3d1d008f4 100644 --- a/sound/soc/codecs/rt5616.c +++ b/sound/soc/codecs/rt5616.c @@ -1248,8 +1248,7 @@ static int rt5616_resume(struct snd_soc_component *component) struct rt5616_priv *rt5616 = snd_soc_component_get_drvdata(component); regcache_cache_only(rt5616->regmap, false); - regcache_sync(rt5616->regmap); - return 0; + return regcache_sync(rt5616->regmap); } #else #define rt5616_suspend NULL diff --git a/sound/soc/codecs/rt5645.c b/sound/soc/codecs/rt5645.c index 7313ea71c958..3c4354d88509 100644 --- a/sound/soc/codecs/rt5645.c +++ b/sound/soc/codecs/rt5645.c @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -4292,10 +4293,10 @@ static void rt5645_i2c_remove(struct i2c_client *i2c) free_irq(i2c->irq, rt5645); /* - * Since the rt5645_btn_check_callback() can queue jack_detect_work, - * the timer need to be delted first + * The timer and jack_detect_work can rearm each other. Shut down the + * timer before cancelling the work. */ - timer_delete_sync(&rt5645->btn_check_timer); + timer_shutdown_sync(&rt5645->btn_check_timer); cancel_delayed_work_sync(&rt5645->jack_detect_work); cancel_delayed_work_sync(&rt5645->rcclock_work); diff --git a/sound/soc/codecs/rt5659.c b/sound/soc/codecs/rt5659.c index 3097ee6d4e89..47f0c7e097a8 100644 --- a/sound/soc/codecs/rt5659.c +++ b/sound/soc/codecs/rt5659.c @@ -3703,9 +3703,7 @@ static int rt5659_resume(struct snd_soc_component *component) struct rt5659_priv *rt5659 = snd_soc_component_get_drvdata(component); regcache_cache_only(rt5659->regmap, false); - regcache_sync(rt5659->regmap); - - return 0; + return regcache_sync(rt5659->regmap); } #else #define rt5659_suspend NULL @@ -4113,10 +4111,14 @@ static int rt5659_i2c_probe(struct i2c_client *i2c) rt5659->gpiod_ldo1_en = devm_gpiod_get_optional(&i2c->dev, "ldo1-en", GPIOD_OUT_HIGH); if (IS_ERR(rt5659->gpiod_ldo1_en)) - dev_warn(&i2c->dev, "Request ldo1-en GPIO failed\n"); + return dev_err_probe(&i2c->dev, PTR_ERR(rt5659->gpiod_ldo1_en), + "failed to get ldo1-en GPIO\n"); rt5659->gpiod_reset = devm_gpiod_get_optional(&i2c->dev, "reset", GPIOD_OUT_HIGH); + if (IS_ERR(rt5659->gpiod_reset)) + return dev_err_probe(&i2c->dev, PTR_ERR(rt5659->gpiod_reset), + "failed to get reset GPIO\n"); /* Sleep for 300 ms minimum */ msleep(300); diff --git a/sound/soc/codecs/rt5660.c b/sound/soc/codecs/rt5660.c index edf2e3e346e4..830498c947e0 100644 --- a/sound/soc/codecs/rt5660.c +++ b/sound/soc/codecs/rt5660.c @@ -1148,9 +1148,7 @@ static int rt5660_resume(struct snd_soc_component *component) msleep(350); regcache_cache_only(rt5660->regmap, false); - regcache_sync(rt5660->regmap); - - return 0; + return regcache_sync(rt5660->regmap); } #else #define rt5660_suspend NULL diff --git a/sound/soc/codecs/rt5665.c b/sound/soc/codecs/rt5665.c index 1d987472ba42..6e4967ed12c3 100644 --- a/sound/soc/codecs/rt5665.c +++ b/sound/soc/codecs/rt5665.c @@ -4388,9 +4388,7 @@ static int rt5665_resume(struct snd_soc_component *component) struct rt5665_priv *rt5665 = snd_soc_component_get_drvdata(component); regcache_cache_only(rt5665->regmap, false); - regcache_sync(rt5665->regmap); - - return 0; + return regcache_sync(rt5665->regmap); } #else #define rt5665_suspend NULL diff --git a/sound/soc/codecs/rt5682-sdw.c b/sound/soc/codecs/rt5682-sdw.c index 23c7d2a9dbee..5f2897c58ad7 100644 --- a/sound/soc/codecs/rt5682-sdw.c +++ b/sound/soc/codecs/rt5682-sdw.c @@ -704,8 +704,7 @@ static void rt5682_sdw_remove(struct sdw_slave *slave) { struct rt5682_priv *rt5682 = dev_get_drvdata(&slave->dev); - if (rt5682->hw_init) - cancel_delayed_work_sync(&rt5682->jack_detect_work); + cancel_delayed_work_sync(&rt5682->jack_detect_work); pm_runtime_disable(&slave->dev); } diff --git a/sound/soc/codecs/rt711-sdca-sdw.c b/sound/soc/codecs/rt711-sdca-sdw.c index e292b28b029e..f74b193c720d 100644 --- a/sound/soc/codecs/rt711-sdca-sdw.c +++ b/sound/soc/codecs/rt711-sdca-sdw.c @@ -369,10 +369,8 @@ static void rt711_sdca_sdw_remove(struct sdw_slave *slave) { struct rt711_sdca_priv *rt711 = dev_get_drvdata(&slave->dev); - if (rt711->hw_init) { - cancel_delayed_work_sync(&rt711->jack_detect_work); - cancel_delayed_work_sync(&rt711->jack_btn_check_work); - } + cancel_delayed_work_sync(&rt711->jack_detect_work); + cancel_delayed_work_sync(&rt711->jack_btn_check_work); pm_runtime_disable(&slave->dev); diff --git a/sound/soc/codecs/rt711-sdw.c b/sound/soc/codecs/rt711-sdw.c index 4ad2b1da1954..798d181d5c90 100644 --- a/sound/soc/codecs/rt711-sdw.c +++ b/sound/soc/codecs/rt711-sdw.c @@ -461,11 +461,9 @@ static void rt711_sdw_remove(struct sdw_slave *slave) { struct rt711_priv *rt711 = dev_get_drvdata(&slave->dev); - if (rt711->hw_init) { - cancel_delayed_work_sync(&rt711->jack_detect_work); - cancel_delayed_work_sync(&rt711->jack_btn_check_work); - cancel_work_sync(&rt711->calibration_work); - } + cancel_delayed_work_sync(&rt711->jack_detect_work); + cancel_delayed_work_sync(&rt711->jack_btn_check_work); + cancel_work_sync(&rt711->calibration_work); pm_runtime_disable(&slave->dev); diff --git a/sound/soc/codecs/rt712-sdca-sdw.c b/sound/soc/codecs/rt712-sdca-sdw.c index edba0367d9ce..a9d4e0795175 100644 --- a/sound/soc/codecs/rt712-sdca-sdw.c +++ b/sound/soc/codecs/rt712-sdca-sdw.c @@ -386,10 +386,8 @@ static void rt712_sdca_sdw_remove(struct sdw_slave *slave) { struct rt712_sdca_priv *rt712 = dev_get_drvdata(&slave->dev); - if (rt712->hw_init) { - cancel_delayed_work_sync(&rt712->jack_detect_work); - cancel_delayed_work_sync(&rt712->jack_btn_check_work); - } + cancel_delayed_work_sync(&rt712->jack_detect_work); + cancel_delayed_work_sync(&rt712->jack_btn_check_work); pm_runtime_disable(&slave->dev); diff --git a/sound/soc/codecs/rt712-sdca.c b/sound/soc/codecs/rt712-sdca.c index 38052cb19790..a4b3dd11d36b 100644 --- a/sound/soc/codecs/rt712-sdca.c +++ b/sound/soc/codecs/rt712-sdca.c @@ -1952,7 +1952,8 @@ int rt712_sdca_io_init(struct device *dev, struct sdw_slave *slave) pm_runtime_get_noresume(&slave->dev); - rt712_sdca_reset(rt712); + if (!rt712->first_hw_init) + rt712_sdca_reset(rt712); rt712_sdca_index_read(rt712, RT712_VENDOR_REG, RT712_JD_PRODUCT_NUM, &val); rt712->hw_id = (val & 0xf000) >> 12; @@ -1981,7 +1982,7 @@ int rt712_sdca_io_init(struct device *dev, struct sdw_slave *slave) * if set_jack callback occurred early than io_init, * we set up the jack detection function now */ - if (rt712->hs_jack) + if (rt712->hs_jack && (!rt712->first_hw_init)) rt712_sdca_jack_init(rt712); rt712_sdca_index_write(rt712, RT712_VENDOR_REG, RT712_SW_CONFIG1, 0x0001); diff --git a/sound/soc/codecs/rt721-sdca-sdw.c b/sound/soc/codecs/rt721-sdca-sdw.c index 910583162d3e..c65e4d1369c9 100644 --- a/sound/soc/codecs/rt721-sdca-sdw.c +++ b/sound/soc/codecs/rt721-sdca-sdw.c @@ -422,10 +422,8 @@ static void rt721_sdca_sdw_remove(struct sdw_slave *slave) { struct rt721_sdca_priv *rt721 = dev_get_drvdata(&slave->dev); - if (rt721->hw_init) { - cancel_delayed_work_sync(&rt721->jack_detect_work); - cancel_delayed_work_sync(&rt721->jack_btn_check_work); - } + cancel_delayed_work_sync(&rt721->jack_detect_work); + cancel_delayed_work_sync(&rt721->jack_btn_check_work); if (rt721->first_hw_init) pm_runtime_disable(&slave->dev); diff --git a/sound/soc/codecs/rt722-sdca-sdw.c b/sound/soc/codecs/rt722-sdca-sdw.c index 5bc9aed58d14..078255fbe1fc 100644 --- a/sound/soc/codecs/rt722-sdca-sdw.c +++ b/sound/soc/codecs/rt722-sdca-sdw.c @@ -471,10 +471,8 @@ static void rt722_sdca_sdw_remove(struct sdw_slave *slave) { struct rt722_sdca_priv *rt722 = dev_get_drvdata(&slave->dev); - if (rt722->hw_init) { - cancel_delayed_work_sync(&rt722->jack_detect_work); - cancel_delayed_work_sync(&rt722->jack_btn_check_work); - } + cancel_delayed_work_sync(&rt722->jack_detect_work); + cancel_delayed_work_sync(&rt722->jack_btn_check_work); if (rt722->first_hw_init) pm_runtime_disable(&slave->dev); diff --git a/sound/soc/codecs/sma1307.c b/sound/soc/codecs/sma1307.c index adb369a29b9d..653cbafee23e 100644 --- a/sound/soc/codecs/sma1307.c +++ b/sound/soc/codecs/sma1307.c @@ -1701,7 +1701,9 @@ static void sma1307_setting_loaded(struct sma1307_priv *sma1307, const char *fil __func__, setting_file, ERR_PTR(ret)); sma1307->set.status = false; return; - } else if ((fw->size) < SMA1307_SETTING_HEADER_SIZE) { + } else if (fw->size % sizeof(int) || + fw->size < (SMA1307_SETTING_HEADER_SIZE + + SMA1307_SETTING_DEFAULT_SIZE) * sizeof(int)) { dev_err(sma1307->dev, "%s: Invalid file\n", __func__); sma1307->set.status = false; return; @@ -1720,6 +1722,10 @@ static void sma1307_setting_loaded(struct sma1307_priv *sma1307, const char *fil sma1307->set.checksum = data[sma1307->set.header_size - 2]; sma1307->set.num_mode = data[sma1307->set.header_size - 1]; num_mode = sma1307->set.num_mode; + if (num_mode < 0 || num_mode > ARRAY_SIZE(sma1307->set.mode_set)) { + sma1307->set.status = false; + return; + } sma1307->set.header = devm_kmalloc_array(sma1307->dev, sma1307->set.header_size, sizeof(int), @@ -1755,7 +1761,11 @@ static void sma1307_setting_loaded(struct sma1307_priv *sma1307, const char *fil /* MODE */ offset = sma1307->set.header_size + sma1307->set.def_size; - sma1307->set.mode_size = DIV_ROUND_CLOSEST(size - offset, num_mode + 1); + if ((size - offset) % (num_mode + 1)) { + sma1307->set.status = false; + return; + } + sma1307->set.mode_size = (size - offset) / (num_mode + 1); for (int i = 0; i < num_mode; i++) { sma1307->set.mode_set[i] = devm_kzalloc(sma1307->dev, diff --git a/sound/soc/codecs/sta32x.c b/sound/soc/codecs/sta32x.c index d6de739212f9..5c0c760b8163 100644 --- a/sound/soc/codecs/sta32x.c +++ b/sound/soc/codecs/sta32x.c @@ -342,27 +342,48 @@ static int sta32x_sync_coef_shadow(struct snd_soc_component *component) { struct sta32x_priv *sta32x = snd_soc_component_get_drvdata(component); unsigned int cfud; - int i; + int i, ret; /* preserve reserved bits in STA32X_CFUD */ - regmap_read(sta32x->regmap, STA32X_CFUD, &cfud); + ret = regmap_read(sta32x->regmap, STA32X_CFUD, &cfud); + if (ret) + return ret; + cfud &= 0xf0; for (i = 0; i < STA32X_COEF_COUNT; i++) { - regmap_write(sta32x->regmap, STA32X_CFADDR2, i); - regmap_write(sta32x->regmap, STA32X_B1CF1, - (sta32x->coef_shadow[i] >> 16) & 0xff); - regmap_write(sta32x->regmap, STA32X_B1CF2, - (sta32x->coef_shadow[i] >> 8) & 0xff); - regmap_write(sta32x->regmap, STA32X_B1CF3, - (sta32x->coef_shadow[i]) & 0xff); + ret = regmap_write(sta32x->regmap, STA32X_CFADDR2, i); + if (ret) + return ret; + + ret = regmap_write(sta32x->regmap, STA32X_B1CF1, + (sta32x->coef_shadow[i] >> 16) & 0xff); + if (ret) + return ret; + + ret = regmap_write(sta32x->regmap, STA32X_B1CF2, + (sta32x->coef_shadow[i] >> 8) & 0xff); + if (ret) + return ret; + + ret = regmap_write(sta32x->regmap, STA32X_B1CF3, + sta32x->coef_shadow[i] & 0xff); + if (ret) + return ret; + /* * chip documentation does not say if the bits are * self-clearing, so do it explicitly */ - regmap_write(sta32x->regmap, STA32X_CFUD, cfud); - regmap_write(sta32x->regmap, STA32X_CFUD, cfud | 0x01); + ret = regmap_write(sta32x->regmap, STA32X_CFUD, cfud); + if (ret) + return ret; + + ret = regmap_write(sta32x->regmap, STA32X_CFUD, cfud | 0x01); + if (ret) + return ret; } + return 0; } @@ -370,15 +391,24 @@ static int sta32x_cache_sync(struct snd_soc_component *component) { struct sta32x_priv *sta32x = snd_soc_component_get_drvdata(component); unsigned int mute; - int rc; + int restore_ret, ret; /* mute during register sync */ - regmap_read(sta32x->regmap, STA32X_MMUTE, &mute); - regmap_write(sta32x->regmap, STA32X_MMUTE, mute | STA32X_MMUTE_MMUTE); - sta32x_sync_coef_shadow(component); - rc = regcache_sync(sta32x->regmap); - regmap_write(sta32x->regmap, STA32X_MMUTE, mute); - return rc; + ret = regmap_read(sta32x->regmap, STA32X_MMUTE, &mute); + if (ret) + return ret; + + ret = regmap_write(sta32x->regmap, STA32X_MMUTE, + mute | STA32X_MMUTE_MMUTE); + if (ret) + return ret; + + ret = sta32x_sync_coef_shadow(component); + if (!ret) + ret = regcache_sync(sta32x->regmap); + + restore_ret = regmap_write(sta32x->regmap, STA32X_MMUTE, mute); + return ret ?: restore_ret; } /* work around ESD issue where sta32x resets and loses all configuration */ @@ -461,8 +491,8 @@ SOC_SINGLE("Ch2 Tone Control Bypass Switch", STA32X_C2CFG, STA32X_CxCFG_TCB_SHIF SOC_SINGLE("Ch1 EQ Bypass Switch", STA32X_C1CFG, STA32X_CxCFG_EQBP_SHIFT, 1, 0), SOC_SINGLE("Ch2 EQ Bypass Switch", STA32X_C2CFG, STA32X_CxCFG_EQBP_SHIFT, 1, 0), SOC_SINGLE("Ch1 Master Volume Bypass Switch", STA32X_C1CFG, STA32X_CxCFG_VBP_SHIFT, 1, 0), -SOC_SINGLE("Ch2 Master Volume Bypass Switch", STA32X_C1CFG, STA32X_CxCFG_VBP_SHIFT, 1, 0), -SOC_SINGLE("Ch3 Master Volume Bypass Switch", STA32X_C1CFG, STA32X_CxCFG_VBP_SHIFT, 1, 0), +SOC_SINGLE("Ch2 Master Volume Bypass Switch", STA32X_C2CFG, STA32X_CxCFG_VBP_SHIFT, 1, 0), +SOC_SINGLE("Ch3 Master Volume Bypass Switch", STA32X_C3CFG, STA32X_CxCFG_VBP_SHIFT, 1, 0), SOC_ENUM("Ch1 Limiter Select", sta32x_limiter_ch1_enum), SOC_ENUM("Ch2 Limiter Select", sta32x_limiter_ch2_enum), SOC_ENUM("Ch3 Limiter Select", sta32x_limiter_ch3_enum), @@ -477,21 +507,21 @@ SOC_ENUM("Limiter2 Release Rate (dB/ms)", sta32x_limiter2_release_rate_enum), * two different enum definitions; provide both */ SOC_SINGLE_TLV("Limiter1 Attack Threshold (AC Mode)", STA32X_L1ATRT, STA32X_LxA_SHIFT, - 16, 0, sta32x_limiter_ac_attack_tlv), + 15, 0, sta32x_limiter_ac_attack_tlv), SOC_SINGLE_TLV("Limiter2 Attack Threshold (AC Mode)", STA32X_L2ATRT, STA32X_LxA_SHIFT, - 16, 0, sta32x_limiter_ac_attack_tlv), + 15, 0, sta32x_limiter_ac_attack_tlv), SOC_SINGLE_TLV("Limiter1 Release Threshold (AC Mode)", STA32X_L1ATRT, STA32X_LxR_SHIFT, - 16, 0, sta32x_limiter_ac_release_tlv), + 15, 0, sta32x_limiter_ac_release_tlv), SOC_SINGLE_TLV("Limiter2 Release Threshold (AC Mode)", STA32X_L2ATRT, STA32X_LxR_SHIFT, - 16, 0, sta32x_limiter_ac_release_tlv), + 15, 0, sta32x_limiter_ac_release_tlv), SOC_SINGLE_TLV("Limiter1 Attack Threshold (DRC Mode)", STA32X_L1ATRT, STA32X_LxA_SHIFT, - 16, 0, sta32x_limiter_drc_attack_tlv), + 15, 0, sta32x_limiter_drc_attack_tlv), SOC_SINGLE_TLV("Limiter2 Attack Threshold (DRC Mode)", STA32X_L2ATRT, STA32X_LxA_SHIFT, - 16, 0, sta32x_limiter_drc_attack_tlv), + 15, 0, sta32x_limiter_drc_attack_tlv), SOC_SINGLE_TLV("Limiter1 Release Threshold (DRC Mode)", STA32X_L1ATRT, STA32X_LxR_SHIFT, - 16, 0, sta32x_limiter_drc_release_tlv), + 15, 0, sta32x_limiter_drc_release_tlv), SOC_SINGLE_TLV("Limiter2 Release Threshold (DRC Mode)", STA32X_L2ATRT, STA32X_LxR_SHIFT, - 16, 0, sta32x_limiter_drc_release_tlv), + 15, 0, sta32x_limiter_drc_release_tlv), BIQUAD_COEFS("Ch1 - Biquad 1", 0), BIQUAD_COEFS("Ch1 - Biquad 2", 5), @@ -794,9 +824,9 @@ static int sta32x_startup_sequence(struct sta32x_priv *sta32x) static int sta32x_set_bias_level(struct snd_soc_component *component, enum snd_soc_bias_level level) { - int ret; struct sta32x_priv *sta32x = snd_soc_component_get_drvdata(component); struct snd_soc_dapm_context *dapm = snd_soc_component_to_dapm(component); + int cleanup_ret, ret; dev_dbg(component->dev, "level = %d\n", level); switch (level) { @@ -820,15 +850,28 @@ static int sta32x_set_bias_level(struct snd_soc_component *component, return ret; } - sta32x_startup_sequence(sta32x); - sta32x_cache_sync(component); + ret = sta32x_startup_sequence(sta32x); + if (!ret) + ret = sta32x_cache_sync(component); + if (ret) + goto restore_failed; + + ret = regmap_update_bits(sta32x->regmap, STA32X_CONFF, + STA32X_CONFF_PWDN | STA32X_CONFF_EAPD, + 0); + if (ret) + goto restore_failed; + sta32x_watchdog_start(sta32x); + break; } /* Power down */ - regmap_update_bits(sta32x->regmap, STA32X_CONFF, - STA32X_CONFF_PWDN | STA32X_CONFF_EAPD, - 0); + ret = regmap_update_bits(sta32x->regmap, STA32X_CONFF, + STA32X_CONFF_PWDN | STA32X_CONFF_EAPD, + 0); + if (ret) + return ret; break; @@ -846,6 +889,16 @@ static int sta32x_set_bias_level(struct snd_soc_component *component, break; } return 0; + +restore_failed: + gpiod_set_value(sta32x->gpiod_nreset, 0); + regcache_mark_dirty(sta32x->regmap); + cleanup_ret = regulator_bulk_disable(ARRAY_SIZE(sta32x->supplies), + sta32x->supplies); + if (cleanup_ret) + dev_warn(component->dev, "Failed to disable supplies: %d\n", + cleanup_ret); + return ret; } static const struct snd_soc_dai_ops sta32x_dai_ops = { diff --git a/sound/soc/codecs/sta350.c b/sound/soc/codecs/sta350.c index 2ba35076732b..9976348b0954 100644 --- a/sound/soc/codecs/sta350.c +++ b/sound/soc/codecs/sta350.c @@ -477,9 +477,9 @@ SOC_SINGLE("Ch2 EQ Bypass Switch", SOC_SINGLE("Ch1 Master Volume Bypass Switch", STA350_C1CFG, STA350_CxCFG_VBP_SHIFT, 1, 0), SOC_SINGLE("Ch2 Master Volume Bypass Switch", - STA350_C1CFG, STA350_CxCFG_VBP_SHIFT, 1, 0), + STA350_C2CFG, STA350_CxCFG_VBP_SHIFT, 1, 0), SOC_SINGLE("Ch3 Master Volume Bypass Switch", - STA350_C1CFG, STA350_CxCFG_VBP_SHIFT, 1, 0), + STA350_C3CFG, STA350_CxCFG_VBP_SHIFT, 1, 0), SOC_ENUM("Ch1 Binary Output Select", sta350_binary_output_ch1_enum), SOC_ENUM("Ch2 Binary Output Select", sta350_binary_output_ch2_enum), SOC_ENUM("Ch3 Binary Output Select", sta350_binary_output_ch3_enum), @@ -502,28 +502,28 @@ SOC_ENUM("Limiter2 Release Rate (dB/ms)", sta350_limiter2_release_rate_enum), */ SOC_SINGLE_TLV("Limiter1 Attack Threshold (AC Mode)", STA350_L1ATRT, STA350_LxA_SHIFT, - 16, 0, sta350_limiter_ac_attack_tlv), + 15, 0, sta350_limiter_ac_attack_tlv), SOC_SINGLE_TLV("Limiter2 Attack Threshold (AC Mode)", STA350_L2ATRT, STA350_LxA_SHIFT, - 16, 0, sta350_limiter_ac_attack_tlv), + 15, 0, sta350_limiter_ac_attack_tlv), SOC_SINGLE_TLV("Limiter1 Release Threshold (AC Mode)", STA350_L1ATRT, STA350_LxR_SHIFT, - 16, 0, sta350_limiter_ac_release_tlv), + 15, 0, sta350_limiter_ac_release_tlv), SOC_SINGLE_TLV("Limiter2 Release Threshold (AC Mode)", STA350_L2ATRT, STA350_LxR_SHIFT, - 16, 0, sta350_limiter_ac_release_tlv), + 15, 0, sta350_limiter_ac_release_tlv), SOC_SINGLE_TLV("Limiter1 Attack Threshold (DRC Mode)", STA350_L1ATRT, STA350_LxA_SHIFT, - 16, 0, sta350_limiter_drc_attack_tlv), + 15, 0, sta350_limiter_drc_attack_tlv), SOC_SINGLE_TLV("Limiter2 Attack Threshold (DRC Mode)", STA350_L2ATRT, STA350_LxA_SHIFT, - 16, 0, sta350_limiter_drc_attack_tlv), + 15, 0, sta350_limiter_drc_attack_tlv), SOC_SINGLE_TLV("Limiter1 Release Threshold (DRC Mode)", STA350_L1ATRT, STA350_LxR_SHIFT, - 16, 0, sta350_limiter_drc_release_tlv), + 15, 0, sta350_limiter_drc_release_tlv), SOC_SINGLE_TLV("Limiter2 Release Threshold (DRC Mode)", STA350_L2ATRT, STA350_LxR_SHIFT, - 16, 0, sta350_limiter_drc_release_tlv), + 15, 0, sta350_limiter_drc_release_tlv), BIQUAD_COEFS("Ch1 - Biquad 1", 0), BIQUAD_COEFS("Ch1 - Biquad 2", 5), diff --git a/sound/soc/codecs/tas2781-fmwlib.c b/sound/soc/codecs/tas2781-fmwlib.c index 2b9efccf1a0b..c2f79c18fcd5 100644 --- a/sound/soc/codecs/tas2781-fmwlib.c +++ b/sound/soc/codecs/tas2781-fmwlib.c @@ -1960,7 +1960,8 @@ static void dspbin_type_check(struct tasdevice_priv *tas_priv, tas_priv->dspbin_typ = TASDEV_ALPHA; } if ((tas_priv->dspbin_typ != TASDEV_BASIC) && - (ppcver < PPC3_VERSION_TAS5825_BASE)) + (ppcver < PPC3_VERSION_TAS5825_BASE || + tas_priv->chip_id == TAS2781)) tas_priv->fw_parse_fct_param_address = fw_parse_fct_param_address; } @@ -1971,7 +1972,8 @@ static int dspfw_default_callback(struct tasdevice_priv *tas_priv, int rc = 0; if (drv_ver == 0x100) { - if (ppcver >= PPC3_VERSION_TAS5825_BASE) { + if (ppcver >= PPC3_VERSION_TAS5825_BASE && + tas_priv->chip_id == TAS5825) { tas_priv->fw_parse_variable_header = fw_parse_variable_header_kernel; tas_priv->fw_parse_program_data = diff --git a/sound/soc/codecs/tlv320adc3xxx.c b/sound/soc/codecs/tlv320adc3xxx.c index d7d958ecd8db..f8b28562f8aa 100644 --- a/sound/soc/codecs/tlv320adc3xxx.c +++ b/sound/soc/codecs/tlv320adc3xxx.c @@ -691,7 +691,7 @@ static const struct snd_kcontrol_new adc3xxx_snd_controls[] = { SOC_DOUBLE_R("AGC Capture Switch", ADC3XXX_LEFT_CHN_AGC_1, ADC3XXX_RIGHT_CHN_AGC_1, 7, 1, 0), SOC_DOUBLE_R_TLV("AGC Target Level Capture Volume", ADC3XXX_LEFT_CHN_AGC_1, - ADC3XXX_RIGHT_CHN_AGC_2, 4, 0x07, 1, agc_target_tlv), + ADC3XXX_RIGHT_CHN_AGC_1, 4, 0x07, 1, agc_target_tlv), SOC_DOUBLE_R_TLV("AGC Noise Threshold Capture Volume", ADC3XXX_LEFT_CHN_AGC_2, ADC3XXX_RIGHT_CHN_AGC_2, 1, 0x1f, 1, agc_thresh_tlv), SOC_DOUBLE_R_TLV("AGC Hysteresis Capture Volume", ADC3XXX_LEFT_CHN_AGC_2, diff --git a/sound/soc/codecs/tlv320aic32x4.c b/sound/soc/codecs/tlv320aic32x4.c index 9e0e4aa2b09c..1695441a1f20 100644 --- a/sound/soc/codecs/tlv320aic32x4.c +++ b/sound/soc/codecs/tlv320aic32x4.c @@ -1063,7 +1063,7 @@ static const struct snd_kcontrol_new aic32x4_tas2505_snd_controls[] = { SOC_ENUM("DAC Playback PowerTune Switch", l_ptm_enum), SOC_SINGLE_TLV("HP Driver Gain Volume", - AIC32X4_HPLGAIN, 0, 0x74, 1, tlv_tas_driver_gain), + TAS2505_HPVOL, 0, 0x74, 1, tlv_tas_driver_gain), SOC_SINGLE("HP DAC Playback Switch", AIC32X4_HPLGAIN, 6, 1, 1), SOC_SINGLE_TLV("Speaker Driver Playback Volume", diff --git a/sound/soc/codecs/tlv320aic32x4.h b/sound/soc/codecs/tlv320aic32x4.h index cfab6f8ce5ac..d0c2e1002e99 100644 --- a/sound/soc/codecs/tlv320aic32x4.h +++ b/sound/soc/codecs/tlv320aic32x4.h @@ -94,6 +94,7 @@ int aic32x4_register_clocks(struct device *dev, const char *mclk_name); #define AIC32X4_LOLGAIN AIC32X4_REG(1, 18) #define AIC32X4_LORGAIN AIC32X4_REG(1, 19) #define AIC32X4_HEADSTART AIC32X4_REG(1, 20) +#define TAS2505_HPVOL AIC32X4_REG(1, 22) #define TAS2505_SPK AIC32X4_REG(1, 45) #define TAS2505_SPKVOL1 AIC32X4_REG(1, 46) #define TAS2505_SPKVOL2 AIC32X4_REG(1, 48) diff --git a/sound/soc/codecs/wcd-mbhc-v2.c b/sound/soc/codecs/wcd-mbhc-v2.c index bb0c8478a8eb..850be84d65ce 100644 --- a/sound/soc/codecs/wcd-mbhc-v2.c +++ b/sound/soc/codecs/wcd-mbhc-v2.c @@ -864,7 +864,7 @@ static int wcd_measure_adc_continuous(struct wcd_mbhc *mbhc) u8 adc_en; /* Pre-requisites for ADC continuous measurement */ - /* Read legacy electircal detection and disable */ + /* Read legacy electrical detection and disable */ wcd_mbhc_write_field(mbhc, WCD_MBHC_ELECT_SCHMT_ISRC, 0x00); /* Set ADC to continuous measurement */ wcd_mbhc_write_field(mbhc, WCD_MBHC_ADC_MODE, 1); @@ -965,7 +965,7 @@ static int wcd_check_cross_conn(struct wcd_mbhc *mbhc) if (wcd_mbhc_read_field(mbhc, WCD_MBHC_HPH_PA_EN)) return -EINVAL; - /* Read legacy electircal detection and disable */ + /* Read legacy electrical detection and disable */ elect_ctl = wcd_mbhc_read_field(mbhc, WCD_MBHC_ELECT_SCHMT_ISRC); wcd_mbhc_write_field(mbhc, WCD_MBHC_ELECT_SCHMT_ISRC, 0); @@ -1470,14 +1470,14 @@ int wcd_dt_parse_mbhc_data(struct device *dev, struct wcd_mbhc_config *cfg) ret = of_property_read_u32(np, "qcom,mbhc-headset-vthreshold-microvolt", µvolt); if (ret) - dev_dbg(dev, "missing qcom,mbhc-hs-mic-max-vthreshold--microvolt in dt node\n"); + dev_dbg(dev, "missing qcom,mbhc-headset-vthreshold-microvolt in dt node\n"); else cfg->hs_thr = microvolt/1000; ret = of_property_read_u32(np, "qcom,mbhc-headphone-vthreshold-microvolt", µvolt); if (ret) - dev_dbg(dev, "missing qcom,mbhc-hs-mic-min-vthreshold-microvolt entry\n"); + dev_dbg(dev, "missing qcom,mbhc-headphone-vthreshold-microvolt entry\n"); else cfg->hph_thr = microvolt/1000; diff --git a/sound/soc/codecs/wcd937x.c b/sound/soc/codecs/wcd937x.c index 0dd05604f5b8..7ffbb445f8ac 100644 --- a/sound/soc/codecs/wcd937x.c +++ b/sound/soc/codecs/wcd937x.c @@ -2536,23 +2536,23 @@ static int wcd937x_soc_codec_probe(struct snd_soc_component *component) WCD937X_IRQ_AUX_PDM_WD_INT); /* Request for watchdog interrupt */ - ret = devm_request_threaded_irq(dev, wcd937x->hphr_pdm_wd_int, NULL, wcd937x_wd_handle_irq, - IRQF_ONESHOT | IRQF_TRIGGER_RISING, - "HPHR PDM WDOG INT", wcd937x); + ret = request_threaded_irq(wcd937x->hphr_pdm_wd_int, NULL, wcd937x_wd_handle_irq, + IRQF_ONESHOT | IRQF_TRIGGER_RISING, + "HPHR PDM WDOG INT", wcd937x); if (ret) - dev_err(dev, "Failed to request HPHR watchdog interrupt (%d)\n", ret); + goto err_free_clsh; - ret = devm_request_threaded_irq(dev, wcd937x->hphl_pdm_wd_int, NULL, wcd937x_wd_handle_irq, - IRQF_ONESHOT | IRQF_TRIGGER_RISING, - "HPHL PDM WDOG INT", wcd937x); + ret = request_threaded_irq(wcd937x->hphl_pdm_wd_int, NULL, wcd937x_wd_handle_irq, + IRQF_ONESHOT | IRQF_TRIGGER_RISING, + "HPHL PDM WDOG INT", wcd937x); if (ret) - dev_err(dev, "Failed to request HPHL watchdog interrupt (%d)\n", ret); + goto err_free_hphr_irq; - ret = devm_request_threaded_irq(dev, wcd937x->aux_pdm_wd_int, NULL, wcd937x_wd_handle_irq, - IRQF_ONESHOT | IRQF_TRIGGER_RISING, - "AUX PDM WDOG INT", wcd937x); + ret = request_threaded_irq(wcd937x->aux_pdm_wd_int, NULL, wcd937x_wd_handle_irq, + IRQF_ONESHOT | IRQF_TRIGGER_RISING, + "AUX PDM WDOG INT", wcd937x); if (ret) - dev_err(dev, "Failed to request Aux watchdog interrupt (%d)\n", ret); + goto err_free_hphl_irq; /* Disable watchdog interrupt for HPH and AUX */ disable_irq_nosync(wcd937x->hphr_pdm_wd_int); @@ -2564,23 +2564,33 @@ static int wcd937x_soc_codec_probe(struct snd_soc_component *component) ARRAY_SIZE(wcd9375_dapm_widgets)); if (ret < 0) { dev_err(component->dev, "Failed to add snd_ctls\n"); - wcd_clsh_ctrl_free(wcd937x->clsh_info); - return ret; + goto err_free_irqs; } ret = snd_soc_dapm_add_routes(dapm, wcd9375_audio_map, ARRAY_SIZE(wcd9375_audio_map)); if (ret < 0) { dev_err(component->dev, "Failed to add routes\n"); - wcd_clsh_ctrl_free(wcd937x->clsh_info); - return ret; + goto err_free_irqs; } } ret = wcd937x_mbhc_init(component); - if (ret) + if (ret) { dev_err(component->dev, "mbhc initialization failed\n"); + goto err_free_irqs; + } + + return ret; +err_free_irqs: + free_irq(wcd937x->aux_pdm_wd_int, wcd937x); +err_free_hphl_irq: + free_irq(wcd937x->hphl_pdm_wd_int, wcd937x); +err_free_hphr_irq: + free_irq(wcd937x->hphr_pdm_wd_int, wcd937x); +err_free_clsh: + wcd_clsh_ctrl_free(wcd937x->clsh_info); return ret; } diff --git a/sound/soc/codecs/wcd939x.c b/sound/soc/codecs/wcd939x.c index 26fe0b6313cd..2d463f062e6d 100644 --- a/sound/soc/codecs/wcd939x.c +++ b/sound/soc/codecs/wcd939x.c @@ -1794,8 +1794,9 @@ static int wcd939x_get_swr_port(struct snd_kcontrol *kcontrol, struct wcd939x_priv *wcd939x = snd_soc_component_get_drvdata(comp); struct wcd939x_sdw_priv *wcd = wcd939x->sdw_priv[mixer->shift]; unsigned int portidx = wcd->ch_info[mixer->reg].port_num; + u8 ch_mask = wcd->ch_info[mixer->reg].ch_mask; - ucontrol->value.integer.value[0] = wcd->port_enable[portidx] ? 1 : 0; + ucontrol->value.integer.value[0] = !!(wcd->port_config[portidx - 1].ch_mask & ch_mask); return 0; } @@ -1821,10 +1822,13 @@ static int wcd939x_set_swr_port(struct snd_kcontrol *kcontrol, struct wcd939x_priv *wcd939x = snd_soc_component_get_drvdata(comp); struct wcd939x_sdw_priv *wcd = wcd939x->sdw_priv[mixer->shift]; unsigned int portidx = wcd->ch_info[mixer->reg].port_num; + u8 ch_mask = wcd->ch_info[mixer->reg].ch_mask; + bool enable = !!ucontrol->value.integer.value[0]; - wcd->port_enable[portidx] = !!ucontrol->value.integer.value[0]; + if (enable == !!(wcd->port_config[portidx - 1].ch_mask & ch_mask)) + return 0; - wcd939x_connect_port(wcd, portidx, mixer->reg, wcd->port_enable[portidx]); + wcd939x_connect_port(wcd, portidx, mixer->reg, enable); return 1; } diff --git a/sound/soc/codecs/wcd939x.h b/sound/soc/codecs/wcd939x.h index 6bd2366587a8..dab7ef108b48 100644 --- a/sound/soc/codecs/wcd939x.h +++ b/sound/soc/codecs/wcd939x.h @@ -899,7 +899,6 @@ struct wcd939x_sdw_priv { struct sdw_stream_runtime *sruntime; struct sdw_port_config port_config[WCD939X_MAX_SWR_PORTS]; const struct wcd_sdw_ch_info *ch_info; - bool port_enable[WCD939X_MAX_SWR_CH_IDS]; int active_ports; bool is_tx; struct wcd939x_priv *wcd939x; diff --git a/sound/soc/codecs/wm5100.c b/sound/soc/codecs/wm5100.c index 2fe937a93026..d0f5c4e89556 100644 --- a/sound/soc/codecs/wm5100.c +++ b/sound/soc/codecs/wm5100.c @@ -658,7 +658,7 @@ SOC_SINGLE_TLV("EQ2 Band 4 Volume", WM5100_EQ2_2, WM5100_EQ2_B4_GAIN_SHIFT, SOC_SINGLE_TLV("EQ2 Band 5 Volume", WM5100_EQ2_2, WM5100_EQ2_B5_GAIN_SHIFT, 24, 0, eq_tlv), -SOC_SINGLE_TLV("EQ3 Band 1 Volume", WM5100_EQ1_1, WM5100_EQ3_B1_GAIN_SHIFT, +SOC_SINGLE_TLV("EQ3 Band 1 Volume", WM5100_EQ3_1, WM5100_EQ3_B1_GAIN_SHIFT, 24, 0, eq_tlv), SOC_SINGLE_TLV("EQ3 Band 2 Volume", WM5100_EQ3_1, WM5100_EQ3_B2_GAIN_SHIFT, 24, 0, eq_tlv), diff --git a/sound/soc/codecs/wm8510.c b/sound/soc/codecs/wm8510.c index 137dcd3d7487..c611eaf0ef5d 100644 --- a/sound/soc/codecs/wm8510.c +++ b/sound/soc/codecs/wm8510.c @@ -134,7 +134,7 @@ SOC_SINGLE("Master Playback Volume", WM8510_DACVOL, 0, 127, 0), SOC_SINGLE("High Pass Filter Switch", WM8510_ADC, 8, 1, 0), SOC_SINGLE("High Pass Cut Off", WM8510_ADC, 4, 7, 0), -SOC_SINGLE("ADC Inversion Switch", WM8510_COMP, 0, 1, 0), +SOC_SINGLE("ADC Inversion Switch", WM8510_ADC, 0, 1, 0), SOC_SINGLE("Capture Volume", WM8510_ADCVOL, 0, 127, 0), diff --git a/sound/soc/codecs/wm8737.c b/sound/soc/codecs/wm8737.c index 33a3f88fffb3..0734f6032c8d 100644 --- a/sound/soc/codecs/wm8737.c +++ b/sound/soc/codecs/wm8737.c @@ -148,13 +148,13 @@ SOC_DOUBLE_R_TLV("Mic Boost Volume", WM8737_AUDIO_PATH_L, WM8737_AUDIO_PATH_R, 6, 3, 0, micboost_tlv), SOC_DOUBLE_R("Mic Boost Switch", WM8737_AUDIO_PATH_L, WM8737_AUDIO_PATH_R, 4, 1, 0), -SOC_DOUBLE("Mic ZC Switch", WM8737_AUDIO_PATH_L, WM8737_AUDIO_PATH_R, - 3, 1, 0), +SOC_DOUBLE_R("Mic ZC Switch", WM8737_AUDIO_PATH_L, WM8737_AUDIO_PATH_R, + 3, 1, 0), SOC_DOUBLE_R_TLV("Capture Volume", WM8737_LEFT_PGA_VOLUME, WM8737_RIGHT_PGA_VOLUME, 0, 255, 0, pga_tlv), -SOC_DOUBLE("Capture ZC Switch", WM8737_AUDIO_PATH_L, WM8737_AUDIO_PATH_R, - 2, 1, 0), +SOC_DOUBLE_R("Capture ZC Switch", WM8737_AUDIO_PATH_L, WM8737_AUDIO_PATH_R, + 2, 1, 0), SOC_DOUBLE("INPUT1 DC Bias Switch", WM8737_MISC_BIAS_CONTROL, 0, 1, 1, 0), diff --git a/sound/soc/codecs/wm8750.c b/sound/soc/codecs/wm8750.c index d3f1178c2d34..df49d813aa4c 100644 --- a/sound/soc/codecs/wm8750.c +++ b/sound/soc/codecs/wm8750.c @@ -171,7 +171,7 @@ SOC_SINGLE("ALC Capture Hold Time", WM8750_ALC2, 0, 15, 0), SOC_SINGLE("ALC Capture Decay Time", WM8750_ALC3, 4, 15, 0), SOC_SINGLE("ALC Capture Attack Time", WM8750_ALC3, 0, 15, 0), SOC_SINGLE("ALC Capture NG Threshold", WM8750_NGATE, 3, 31, 0), -SOC_ENUM("ALC Capture NG Type", wm8750_enum[4]), +SOC_ENUM("ALC Capture NG Type", wm8750_enum[7]), SOC_SINGLE("ALC Capture NG Switch", WM8750_NGATE, 0, 1, 0), SOC_SINGLE("Left ADC Capture Volume", WM8750_LADC, 0, 255, 0), diff --git a/sound/soc/codecs/wm8955.c b/sound/soc/codecs/wm8955.c index c897a9ab764d..d872d4e00529 100644 --- a/sound/soc/codecs/wm8955.c +++ b/sound/soc/codecs/wm8955.c @@ -426,7 +426,7 @@ static const char *treble_cutoff_text[] = { "High", "Low" }; -static SOC_ENUM_SINGLE_DECL(treble_cutoff, WM8955_TREBLE_CONTROL, 2, +static SOC_ENUM_SINGLE_DECL(treble_cutoff, WM8955_TREBLE_CONTROL, 6, treble_cutoff_text); static const DECLARE_TLV_DB_SCALE(digital_tlv, -12750, 50, 1); diff --git a/sound/soc/codecs/wm8983.c b/sound/soc/codecs/wm8983.c index fab25f35fd14..5639dad90405 100644 --- a/sound/soc/codecs/wm8983.c +++ b/sound/soc/codecs/wm8983.c @@ -234,7 +234,7 @@ static const struct snd_kcontrol_new wm8983_snd_controls[] = { 8, 1, 0, pga_boost_tlv), SOC_DOUBLE("ADC Inversion Switch", WM8983_ADC_CONTROL, 0, 1, 1, 0), - SOC_SINGLE("ADC 128x Oversampling Switch", WM8983_ADC_CONTROL, 8, 1, 0), + SOC_SINGLE("ADC 128x Oversampling Switch", WM8983_ADC_CONTROL, 3, 1, 0), SOC_DOUBLE_R_TLV("Playback Volume", WM8983_LEFT_DAC_DIGITAL_VOL, WM8983_RIGHT_DAC_DIGITAL_VOL, 0, 255, 0, dac_tlv), diff --git a/sound/soc/codecs/wm8985.c b/sound/soc/codecs/wm8985.c index 2a64d5a851da..f400f528321d 100644 --- a/sound/soc/codecs/wm8985.c +++ b/sound/soc/codecs/wm8985.c @@ -327,7 +327,7 @@ static const struct snd_kcontrol_new wm8985_common_snd_controls[] = { 8, 1, 0, pga_boost_tlv), SOC_DOUBLE("ADC Inversion Switch", WM8985_ADC_CONTROL, 0, 1, 1, 0), - SOC_SINGLE("ADC 128x Oversampling Switch", WM8985_ADC_CONTROL, 8, 1, 0), + SOC_SINGLE("ADC 128x Oversampling Switch", WM8985_ADC_CONTROL, 3, 1, 0), SOC_DOUBLE_R_TLV("Playback Volume", WM8985_LEFT_DAC_DIGITAL_VOL, WM8985_RIGHT_DAC_DIGITAL_VOL, 0, 255, 0, dac_tlv), diff --git a/sound/soc/codecs/wm8990.c b/sound/soc/codecs/wm8990.c index 11dfbbbdcd92..5674d97fcd84 100644 --- a/sound/soc/codecs/wm8990.c +++ b/sound/soc/codecs/wm8990.c @@ -97,8 +97,8 @@ static const struct snd_kcontrol_new wm8990_snd_controls[] = { SOC_SINGLE("LIN12 PGA Boost", WM8990_INPUT_MIXER3, WM8990_L12MNBST_BIT, 1, 0), SOC_SINGLE("LIN34 PGA Boost", WM8990_INPUT_MIXER3, WM8990_L34MNBST_BIT, 1, 0), /* INMIXR */ -SOC_SINGLE("RIN12 PGA Boost", WM8990_INPUT_MIXER3, WM8990_R12MNBST_BIT, 1, 0), -SOC_SINGLE("RIN34 PGA Boost", WM8990_INPUT_MIXER3, WM8990_R34MNBST_BIT, 1, 0), +SOC_SINGLE("RIN12 PGA Boost", WM8990_INPUT_MIXER4, WM8990_R12MNBST_BIT, 1, 0), +SOC_SINGLE("RIN34 PGA Boost", WM8990_INPUT_MIXER4, WM8990_R34MNBST_BIT, 1, 0), /* LOMIX */ SOC_SINGLE_TLV("LOMIX LIN3 Bypass Volume", WM8990_OUTPUT_MIXER3, @@ -112,7 +112,7 @@ SOC_SINGLE_TLV("LOMIX RIN3 Bypass Volume", WM8990_OUTPUT_MIXER5, SOC_SINGLE_TLV("LOMIX AINRMUX Bypass Volume", WM8990_OUTPUT_MIXER5, WM8990_LRBLOVOL_SHIFT, WM8990_LRBLOVOL_MASK, 1, out_mix_tlv), SOC_SINGLE_TLV("LOMIX AINLMUX Bypass Volume", WM8990_OUTPUT_MIXER5, - WM8990_LRBLOVOL_SHIFT, WM8990_LRBLOVOL_MASK, 1, out_mix_tlv), + WM8990_LLBLOVOL_SHIFT, WM8990_LLBLOVOL_MASK, 1, out_mix_tlv), /* ROMIX */ SOC_SINGLE_TLV("ROMIX RIN3 Bypass Volume", WM8990_OUTPUT_MIXER4, @@ -377,9 +377,9 @@ SOC_DAPM_SINGLE_TLV("Record Right Volume", WM8990_INPUT_MIXER4, WM8990_RDBVOL_SHIFT, WM8990_RDBVOL_MASK, 0, in_mix_tlv), SOC_DAPM_SINGLE_TLV("RIN2 Volume", WM8990_INPUT_MIXER6, WM8990_RI2BVOL_SHIFT, 7, 0, in_mix_tlv), -SOC_DAPM_SINGLE("RINPGA12 Switch", WM8990_INPUT_MIXER3, WM8990_L12MNB_BIT, +SOC_DAPM_SINGLE("RINPGA12 Switch", WM8990_INPUT_MIXER4, WM8990_R12MNB_BIT, 1, 0), -SOC_DAPM_SINGLE("RINPGA34 Switch", WM8990_INPUT_MIXER3, WM8990_L34MNB_BIT, +SOC_DAPM_SINGLE("RINPGA34 Switch", WM8990_INPUT_MIXER4, WM8990_R34MNB_BIT, 1, 0), }; diff --git a/sound/soc/codecs/wm8991.c b/sound/soc/codecs/wm8991.c index 225c235d3d89..471310257123 100644 --- a/sound/soc/codecs/wm8991.c +++ b/sound/soc/codecs/wm8991.c @@ -169,8 +169,8 @@ static const struct snd_kcontrol_new wm8991_snd_controls[] = { SOC_SINGLE("LIN12 PGA Boost", WM8991_INPUT_MIXER3, WM8991_L12MNBST_BIT, 1, 0), SOC_SINGLE("LIN34 PGA Boost", WM8991_INPUT_MIXER3, WM8991_L34MNBST_BIT, 1, 0), /* INMIXR */ - SOC_SINGLE("RIN12 PGA Boost", WM8991_INPUT_MIXER3, WM8991_R12MNBST_BIT, 1, 0), - SOC_SINGLE("RIN34 PGA Boost", WM8991_INPUT_MIXER3, WM8991_R34MNBST_BIT, 1, 0), + SOC_SINGLE("RIN12 PGA Boost", WM8991_INPUT_MIXER4, WM8991_R12MNBST_BIT, 1, 0), + SOC_SINGLE("RIN34 PGA Boost", WM8991_INPUT_MIXER4, WM8991_R34MNBST_BIT, 1, 0), /* LOMIX */ SOC_SINGLE_TLV("LOMIX LIN3 Bypass Volume", WM8991_OUTPUT_MIXER3, @@ -184,7 +184,7 @@ static const struct snd_kcontrol_new wm8991_snd_controls[] = { SOC_SINGLE_TLV("LOMIX AINRMUX Bypass Volume", WM8991_OUTPUT_MIXER5, WM8991_LRBLOVOL_SHIFT, WM8991_LRBLOVOL_MASK, 1, out_mix_tlv), SOC_SINGLE_TLV("LOMIX AINLMUX Bypass Volume", WM8991_OUTPUT_MIXER5, - WM8991_LRBLOVOL_SHIFT, WM8991_LRBLOVOL_MASK, 1, out_mix_tlv), + WM8991_LLBLOVOL_SHIFT, WM8991_LLBLOVOL_MASK, 1, out_mix_tlv), /* ROMIX */ SOC_SINGLE_TLV("ROMIX RIN3 Bypass Volume", WM8991_OUTPUT_MIXER4, @@ -446,9 +446,9 @@ static const struct snd_kcontrol_new wm8991_dapm_inmixr_controls[] = { WM8991_RDBVOL_SHIFT, WM8991_RDBVOL_MASK, 0, in_mix_tlv), SOC_DAPM_SINGLE_TLV("RIN2 Volume", WM8991_INPUT_MIXER6, WM8991_RI2BVOL_SHIFT, 7, 0, in_mix_tlv), - SOC_DAPM_SINGLE("RINPGA12 Switch", WM8991_INPUT_MIXER3, WM8991_L12MNB_BIT, + SOC_DAPM_SINGLE("RINPGA12 Switch", WM8991_INPUT_MIXER4, WM8991_R12MNB_BIT, 1, 0), - SOC_DAPM_SINGLE("RINPGA34 Switch", WM8991_INPUT_MIXER3, WM8991_L34MNB_BIT, + SOC_DAPM_SINGLE("RINPGA34 Switch", WM8991_INPUT_MIXER4, WM8991_R34MNB_BIT, 1, 0), }; diff --git a/sound/soc/codecs/wm8994.c b/sound/soc/codecs/wm8994.c index 58cfdd60d8ab..5d27cefd9d54 100644 --- a/sound/soc/codecs/wm8994.c +++ b/sound/soc/codecs/wm8994.c @@ -163,9 +163,12 @@ static void wm8958_micd_set_rate(struct snd_soc_component *component) static int configure_aif_clock(struct snd_soc_component *component, int aif) { struct wm8994_priv *wm8994 = snd_soc_component_get_drvdata(component); + struct clk *mclk = NULL; + bool switch_mclk; int rate; int reg1 = 0; int offset; + int ret; if (aif) offset = 4; @@ -174,11 +177,13 @@ static int configure_aif_clock(struct snd_soc_component *component, int aif) switch (wm8994->sysclk[aif]) { case WM8994_SYSCLK_MCLK1: + mclk = wm8994->mclk[WM8994_MCLK1].clk; rate = wm8994->mclk_rate[0]; break; case WM8994_SYSCLK_MCLK2: reg1 |= 0x8; + mclk = wm8994->mclk[WM8994_MCLK2].clk; rate = wm8994->mclk_rate[1]; break; @@ -196,6 +201,20 @@ static int configure_aif_clock(struct snd_soc_component *component, int aif) return -EINVAL; } + /* + * If the AIF clock is running, enable the new MCLK before switching + * to it and release the previous one afterwards. + */ + switch_mclk = wm8994->aif_clk_on[aif] && mclk != wm8994->aif_mclk[aif]; + if (switch_mclk) { + ret = clk_prepare_enable(mclk); + if (ret < 0) { + dev_err(component->dev, + "Failed to enable MCLK for AIF%d\n", aif + 1); + return ret; + } + } + if (rate >= 13500000) { rate /= 2; reg1 |= WM8994_AIF1CLK_DIV; @@ -210,6 +229,11 @@ static int configure_aif_clock(struct snd_soc_component *component, int aif) WM8994_AIF1CLK_SRC_MASK | WM8994_AIF1CLK_DIV, reg1); + if (switch_mclk) { + clk_disable_unprepare(wm8994->aif_mclk[aif]); + wm8994->aif_mclk[aif] = mclk; + } + return 0; } @@ -701,17 +725,17 @@ static const char *wm8958_ng_text[] = { static SOC_ENUM_SINGLE_DECL(wm8958_aif1dac1_ng_hold, WM8958_AIF1_DAC1_NOISE_GATE, - WM8958_AIF1DAC1_NG_THR_SHIFT, + WM8958_AIF1DAC1_NG_HLD_SHIFT, wm8958_ng_text); static SOC_ENUM_SINGLE_DECL(wm8958_aif1dac2_ng_hold, WM8958_AIF1_DAC2_NOISE_GATE, - WM8958_AIF1DAC2_NG_THR_SHIFT, + WM8958_AIF1DAC2_NG_HLD_SHIFT, wm8958_ng_text); static SOC_ENUM_SINGLE_DECL(wm8958_aif2dac_ng_hold, WM8958_AIF2_DAC_NOISE_GATE, - WM8958_AIF2DAC_NG_THR_SHIFT, + WM8958_AIF2DAC_NG_HLD_SHIFT, wm8958_ng_text); static const struct snd_kcontrol_new wm8958_snd_controls[] = { @@ -1059,13 +1083,25 @@ static int aif_mclk_set(struct snd_soc_component *component, int aif, bool enabl unsigned int offset, val, clk_idx; int ret; + /* + * The AIF clock source may be changed while the AIF clock is + * running, so release the MCLK which has been enabled for it + * instead of the one currently selected. + */ + if (!enable) { + clk_disable_unprepare(wm8994->aif_mclk[aif]); + wm8994->aif_mclk[aif] = NULL; + wm8994->aif_clk_on[aif] = false; + return 0; + } + if (aif) offset = 4; else offset = 0; val = snd_soc_component_read(component, WM8994_AIF1_CLOCKING_1 + offset); - val &= WM8994_AIF1CLK_SRC_MASK; + val = (val & WM8994_AIF1CLK_SRC_MASK) >> WM8994_AIF1CLK_SRC_SHIFT; switch (val) { case 0: @@ -1075,19 +1111,18 @@ static int aif_mclk_set(struct snd_soc_component *component, int aif, bool enabl clk_idx = WM8994_MCLK2; break; default: + wm8994->aif_clk_on[aif] = true; return 0; } - if (enable) { - ret = clk_prepare_enable(wm8994->mclk[clk_idx].clk); - if (ret < 0) { - dev_err(component->dev, "Failed to enable MCLK%d\n", - clk_idx); - return ret; - } - } else { - clk_disable_unprepare(wm8994->mclk[clk_idx].clk); + ret = clk_prepare_enable(wm8994->mclk[clk_idx].clk); + if (ret < 0) { + dev_err(component->dev, "Failed to enable MCLK%d\n", + clk_idx + 1); + return ret; } + wm8994->aif_mclk[aif] = wm8994->mclk[clk_idx].clk; + wm8994->aif_clk_on[aif] = true; return 0; } @@ -2199,6 +2234,44 @@ static int wm8994_get_fll_config(struct wm8994 *control, struct fll_div *fll, return 0; } +/* + * If SYSCLK is less than 50kHz adjust AIFnCLK dividers for detection, + * restoring the original ones once SYSCLK is fast enough again. + */ +static void wm8994_update_aif_clk_rate(struct snd_soc_component *component) +{ + struct wm8994_priv *wm8994 = snd_soc_component_get_drvdata(component); + + if (max(wm8994->aifclk[0], wm8994->aifclk[1]) < 50000) { + /* Don't overwrite the saved dividers with the 128fs ones */ + if (!wm8994->aifdiv[0]) { + dev_dbg(component->dev, "Configuring AIFs for 128fs\n"); + + wm8994->aifdiv[0] = snd_soc_component_read(component, + WM8994_AIF1_RATE) + & WM8994_AIF1CLK_RATE_MASK; + wm8994->aifdiv[1] = snd_soc_component_read(component, + WM8994_AIF2_RATE) + & WM8994_AIF1CLK_RATE_MASK; + } + + snd_soc_component_update_bits(component, WM8994_AIF1_RATE, + WM8994_AIF1CLK_RATE_MASK, 0x1); + snd_soc_component_update_bits(component, WM8994_AIF2_RATE, + WM8994_AIF2CLK_RATE_MASK, 0x1); + } else if (wm8994->aifdiv[0]) { + snd_soc_component_update_bits(component, WM8994_AIF1_RATE, + WM8994_AIF1CLK_RATE_MASK, + wm8994->aifdiv[0]); + snd_soc_component_update_bits(component, WM8994_AIF2_RATE, + WM8994_AIF2CLK_RATE_MASK, + wm8994->aifdiv[1]); + + wm8994->aifdiv[0] = 0; + wm8994->aifdiv[1] = 0; + } +} + static int _wm8994_set_fll(struct snd_soc_component *component, int id, int src, unsigned int freq_in, unsigned int freq_out) { @@ -2433,33 +2506,7 @@ static int _wm8994_set_fll(struct snd_soc_component *component, int id, int src, configure_clock(component); - /* - * If SYSCLK will be less than 50kHz adjust AIFnCLK dividers - * for detection. - */ - if (max(wm8994->aifclk[0], wm8994->aifclk[1]) < 50000) { - dev_dbg(component->dev, "Configuring AIFs for 128fs\n"); - - wm8994->aifdiv[0] = snd_soc_component_read(component, WM8994_AIF1_RATE) - & WM8994_AIF1CLK_RATE_MASK; - wm8994->aifdiv[1] = snd_soc_component_read(component, WM8994_AIF2_RATE) - & WM8994_AIF1CLK_RATE_MASK; - - snd_soc_component_update_bits(component, WM8994_AIF1_RATE, - WM8994_AIF1CLK_RATE_MASK, 0x1); - snd_soc_component_update_bits(component, WM8994_AIF2_RATE, - WM8994_AIF2CLK_RATE_MASK, 0x1); - } else if (wm8994->aifdiv[0]) { - snd_soc_component_update_bits(component, WM8994_AIF1_RATE, - WM8994_AIF1CLK_RATE_MASK, - wm8994->aifdiv[0]); - snd_soc_component_update_bits(component, WM8994_AIF2_RATE, - WM8994_AIF2CLK_RATE_MASK, - wm8994->aifdiv[1]); - - wm8994->aifdiv[0] = 0; - wm8994->aifdiv[1] = 0; - } + wm8994_update_aif_clk_rate(component); return 0; } @@ -2519,7 +2566,7 @@ static int wm8994_set_dai_sysclk(struct snd_soc_dai *dai, case WM8994_SYSCLK_MCLK1: wm8994->sysclk[dai->id - 1] = WM8994_SYSCLK_MCLK1; - ret = wm8994_set_mclk_rate(wm8994, dai->id - 1, &freq); + ret = wm8994_set_mclk_rate(wm8994, WM8994_MCLK1, &freq); if (ret < 0) return ret; @@ -2532,7 +2579,7 @@ static int wm8994_set_dai_sysclk(struct snd_soc_dai *dai, /* TODO: Set GPIO AF */ wm8994->sysclk[dai->id - 1] = WM8994_SYSCLK_MCLK2; - ret = wm8994_set_mclk_rate(wm8994, dai->id - 1, &freq); + ret = wm8994_set_mclk_rate(wm8994, WM8994_MCLK2, &freq); if (ret < 0) return ret; @@ -2577,33 +2624,7 @@ static int wm8994_set_dai_sysclk(struct snd_soc_dai *dai, configure_clock(component); - /* - * If SYSCLK will be less than 50kHz adjust AIFnCLK dividers - * for detection. - */ - if (max(wm8994->aifclk[0], wm8994->aifclk[1]) < 50000) { - dev_dbg(component->dev, "Configuring AIFs for 128fs\n"); - - wm8994->aifdiv[0] = snd_soc_component_read(component, WM8994_AIF1_RATE) - & WM8994_AIF1CLK_RATE_MASK; - wm8994->aifdiv[1] = snd_soc_component_read(component, WM8994_AIF2_RATE) - & WM8994_AIF1CLK_RATE_MASK; - - snd_soc_component_update_bits(component, WM8994_AIF1_RATE, - WM8994_AIF1CLK_RATE_MASK, 0x1); - snd_soc_component_update_bits(component, WM8994_AIF2_RATE, - WM8994_AIF2CLK_RATE_MASK, 0x1); - } else if (wm8994->aifdiv[0]) { - snd_soc_component_update_bits(component, WM8994_AIF1_RATE, - WM8994_AIF1CLK_RATE_MASK, - wm8994->aifdiv[0]); - snd_soc_component_update_bits(component, WM8994_AIF2_RATE, - WM8994_AIF2CLK_RATE_MASK, - wm8994->aifdiv[1]); - - wm8994->aifdiv[0] = 0; - wm8994->aifdiv[1] = 0; - } + wm8994_update_aif_clk_rate(component); return 0; } diff --git a/sound/soc/codecs/wm8994.h b/sound/soc/codecs/wm8994.h index b28398aa9e48..e7df0a1a2314 100644 --- a/sound/soc/codecs/wm8994.h +++ b/sound/soc/codecs/wm8994.h @@ -81,6 +81,8 @@ struct wm8994_priv { struct wm_hubs_data hubs; struct wm8994 *wm8994; struct clk_bulk_data mclk[WM8994_NUM_MCLK]; + struct clk *aif_mclk[2]; + bool aif_clk_on[2]; int sysclk[2]; int sysclk_rate[2]; int mclk_rate[2]; diff --git a/sound/soc/codecs/wm_hubs.c b/sound/soc/codecs/wm_hubs.c index f80dfc488e3c..ce16f2750979 100644 --- a/sound/soc/codecs/wm_hubs.c +++ b/sound/soc/codecs/wm_hubs.c @@ -427,7 +427,7 @@ SOC_SINGLE_TLV("Right Output Mixer IN2RP Volume", SOC_SINGLE_TLV("Right Output Mixer Left Input Volume", WM8993_OUTPUT_MIXER6, 3, 7, 1, outmix_tlv), SOC_SINGLE_TLV("Right Output Mixer Right Input Volume", - WM8993_OUTPUT_MIXER6, 6, 7, 1, outmix_tlv), + WM8993_OUTPUT_MIXER6, 0, 7, 1, outmix_tlv), SOC_SINGLE_TLV("Right Output Mixer DAC Volume", WM8993_OUTPUT_MIXER6, 9, 7, 1, outmix_tlv), diff --git a/sound/soc/codecs/wsa881x.c b/sound/soc/codecs/wsa881x.c index 47ac3e4985a5..4f3e6bc29c7e 100644 --- a/sound/soc/codecs/wsa881x.c +++ b/sound/soc/codecs/wsa881x.c @@ -1115,11 +1115,19 @@ static int wsa881x_probe(struct sdw_slave *pdev, if (!wsa881x) return -ENOMEM; - wsa881x->sd_n = devm_gpiod_get_optional(dev, "powerdown", GPIOD_OUT_LOW); + /* + * The powerdown GPIO may be shared between several amplifiers. Request + * it asserted, so the shared GPIO proxy treats powerdown as the default + * state and keeps the line de-asserted as long as any amplifier needs + * it, then power up this amplifier. + */ + wsa881x->sd_n = devm_gpiod_get_optional(dev, "powerdown", GPIOD_OUT_HIGH); if (IS_ERR(wsa881x->sd_n)) return dev_err_probe(dev, PTR_ERR(wsa881x->sd_n), "Shutdown Control GPIO not found\n"); + gpiod_set_value_cansleep(wsa881x->sd_n, 0); + dev_set_drvdata(dev, wsa881x); wsa881x->slave = pdev; wsa881x->dev = dev; @@ -1154,7 +1162,7 @@ static int wsa881x_runtime_suspend(struct device *dev) struct regmap *regmap = dev_get_regmap(dev, NULL); struct wsa881x_priv *wsa881x = dev_get_drvdata(dev); - gpiod_direction_output(wsa881x->sd_n, 1); + gpiod_set_value_cansleep(wsa881x->sd_n, 1); regcache_cache_only(regmap, true); regcache_mark_dirty(regmap); @@ -1169,11 +1177,11 @@ static int wsa881x_runtime_resume(struct device *dev) struct wsa881x_priv *wsa881x = dev_get_drvdata(dev); int ret; - gpiod_direction_output(wsa881x->sd_n, 0); + gpiod_set_value_cansleep(wsa881x->sd_n, 0); ret = sdw_slave_wait_for_init(slave, WSA881X_PROBE_TIMEOUT); if (ret) { - gpiod_direction_output(wsa881x->sd_n, 1); + gpiod_set_value_cansleep(wsa881x->sd_n, 1); return ret; } @@ -1182,7 +1190,7 @@ static int wsa881x_runtime_resume(struct device *dev) if (ret) { regcache_cache_only(regmap, true); regcache_mark_dirty(regmap); - gpiod_direction_output(wsa881x->sd_n, 1); + gpiod_set_value_cansleep(wsa881x->sd_n, 1); return ret; } diff --git a/sound/soc/codecs/wsa883x.c b/sound/soc/codecs/wsa883x.c index ccd4404c1644..17d8babc6123 100644 --- a/sound/soc/codecs/wsa883x.c +++ b/sound/soc/codecs/wsa883x.c @@ -552,7 +552,7 @@ static struct sdw_dpn_prop wsa_sink_dpn_prop[WSA883X_MAX_SWR_PORTS] = { .num = WSA883X_PORT_VISENSE + 1, .type = SDW_DPN_SIMPLE, .min_ch = 1, - .max_ch = 1, + .max_ch = 2, .simple_ch_prep_sm = true, .read_only_wordlength = true, } @@ -573,7 +573,7 @@ static const struct sdw_port_config wsa883x_pconfig[WSA883X_MAX_SWR_PORTS] = { }, [WSA883X_PORT_VISENSE] = { .num = WSA883X_PORT_VISENSE + 1, - .ch_mask = 0x1, + .ch_mask = 0x3, }, }; @@ -1669,7 +1669,9 @@ static int wsa883x_probe(struct sdw_slave *pdev, pm_runtime_use_autosuspend(dev); pm_runtime_mark_last_busy(dev); pm_runtime_set_active(dev); - pm_runtime_enable(dev); + ret = devm_pm_runtime_enable(dev); + if (ret) + goto err; ret = devm_snd_soc_register_component(dev, &wsa883x_component_drv, diff --git a/sound/soc/codecs/wsa884x.c b/sound/soc/codecs/wsa884x.c index f0857c0588d5..acf32af5aae3 100644 --- a/sound/soc/codecs/wsa884x.c +++ b/sound/soc/codecs/wsa884x.c @@ -859,7 +859,7 @@ static struct sdw_dpn_prop wsa884x_sink_dpn_prop[WSA884X_MAX_SWR_PORTS] = { .num = WSA884X_PORT_VISENSE + 1, .type = SDW_DPN_SIMPLE, .min_ch = 1, - .max_ch = 1, + .max_ch = 2, .simple_ch_prep_sm = true, .read_only_wordlength = true, }, @@ -892,7 +892,7 @@ static const struct sdw_port_config wsa884x_pconfig[WSA884X_MAX_SWR_PORTS] = { }, [WSA884X_PORT_VISENSE] = { .num = WSA884X_PORT_VISENSE + 1, - .ch_mask = 0x1, + .ch_mask = 0x3, }, [WSA884X_PORT_CPS] = { .num = WSA884X_PORT_CPS + 1, @@ -2125,7 +2125,9 @@ static int wsa884x_probe(struct sdw_slave *pdev, pm_runtime_use_autosuspend(dev); pm_runtime_mark_last_busy(dev); pm_runtime_set_active(dev); - pm_runtime_enable(dev); + ret = devm_pm_runtime_enable(dev); + if (ret) + return ret; return devm_snd_soc_register_component(dev, &wsa884x_component_drv, diff --git a/sound/soc/dwc/dwc-i2s.c b/sound/soc/dwc/dwc-i2s.c index 2e9fb79b1cd8..2f483b78a227 100644 --- a/sound/soc/dwc/dwc-i2s.c +++ b/sound/soc/dwc/dwc-i2s.c @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -913,13 +914,16 @@ static int jh7110_i2stx0_clk_cfg(struct i2s_clk_config_data *config) static int dw_i2s_probe(struct platform_device *pdev) { - const struct i2s_platform_data *pdata = pdev->dev.platform_data; + const struct i2s_platform_data *pdata = device_get_match_data(&pdev->dev); struct dw_i2s_dev *dev; struct resource *res; int ret, irq; struct snd_soc_dai_driver *dw_i2s_dai; const char *clk_id; + if (!pdata) + pdata = dev_get_platdata(&pdev->dev); + dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; diff --git a/sound/soc/fsl/fsl_asrc.c b/sound/soc/fsl/fsl_asrc.c index b24737add001..d80afe1bf4be 100644 --- a/sound/soc/fsl/fsl_asrc.c +++ b/sound/soc/fsl/fsl_asrc.c @@ -521,10 +521,10 @@ static int fsl_asrc_config_pair(struct fsl_asrc_pair *pair, bool use_ideal_rate) ASRCTR_USR(index)); /* Set the input and output clock sources */ - regmap_update_bits(asrc->regmap, REG_ASRCSR, - ASRCSR_AICSi_MASK(index) | ASRCSR_AOCSi_MASK(index), - ASRCSR_AICS(index, clk_index[IN]) | - ASRCSR_AOCS(index, clk_index[OUT])); + regmap_write_bits(asrc->regmap, REG_ASRCSR, + ASRCSR_AICSi_MASK(index) | ASRCSR_AOCSi_MASK(index), + ASRCSR_AICS(index, clk_index[IN]) | + ASRCSR_AOCS(index, clk_index[OUT])); /* Calculate the input clock divisors */ indiv = fsl_asrc_cal_asrck_divisor(pair, div[IN]); diff --git a/sound/soc/fsl/fsl_asrc_dma.c b/sound/soc/fsl/fsl_asrc_dma.c index 2f662bdf14d0..64f2b0612274 100644 --- a/sound/soc/fsl/fsl_asrc_dma.c +++ b/sound/soc/fsl/fsl_asrc_dma.c @@ -248,6 +248,11 @@ static int fsl_asrc_dma_hw_params(struct snd_soc_component *component, /* Get DMA request of Front-End */ tmp_chan = asrc->get_dma_channel(pair, dir); + if (!tmp_chan) { + dma_release_channel(pair->dma_chan[!dir]); + pair->dma_chan[!dir] = NULL; + return -EINVAL; + } tmp_data = tmp_chan->private; pair->dma_data.dma_request2 = tmp_data->dma_request; pair->dma_data.peripheral_type = tmp_data->peripheral_type; diff --git a/sound/soc/fsl/fsl_asrc_m2m.c b/sound/soc/fsl/fsl_asrc_m2m.c index 4bc40f328f58..a90a1c8ed34d 100644 --- a/sound/soc/fsl/fsl_asrc_m2m.c +++ b/sound/soc/fsl/fsl_asrc_m2m.c @@ -320,7 +320,7 @@ static int fsl_asrc_m2m_comp_open(struct snd_compr_stream *stream) if (ret) goto error_alloc_out_buf; - ret = pm_runtime_get_sync(dev); + ret = pm_runtime_resume_and_get(dev); if (ret < 0) { dev_err(dev, "Failed to power up asrc\n"); goto err_pm_runtime; @@ -475,6 +475,7 @@ static int fsl_asrc_m2m_comp_task_create(struct snd_compr_stream *stream, task->input = dma_buf_export(&exp_info_in); if (IS_ERR(task->input)) { ret = PTR_ERR(task->input); + task->input = NULL; return ret; } @@ -485,6 +486,7 @@ static int fsl_asrc_m2m_comp_task_create(struct snd_compr_stream *stream, task->output = dma_buf_export(&exp_info_out); if (IS_ERR(task->output)) { ret = PTR_ERR(task->output); + task->output = NULL; return ret; } diff --git a/sound/soc/fsl/imx-pcm-rpmsg.c b/sound/soc/fsl/imx-pcm-rpmsg.c index 7086fb7fc1eb..30e75fee5175 100644 --- a/sound/soc/fsl/imx-pcm-rpmsg.c +++ b/sound/soc/fsl/imx-pcm-rpmsg.c @@ -269,7 +269,7 @@ static int imx_rpmsg_pcm_open(struct snd_soc_component *component, info->stream_timer[substream->stream].substream = substream; timer_setup(&info->stream_timer[substream->stream].timer, imx_rpmsg_timer_callback, 0); - return ret; + return 0; } static int imx_rpmsg_pcm_close(struct snd_soc_component *component, diff --git a/sound/soc/intel/atom/sst-mfld-platform-pcm.c b/sound/soc/intel/atom/sst-mfld-platform-pcm.c index a4c8cbfba096..db1fb3b26909 100644 --- a/sound/soc/intel/atom/sst-mfld-platform-pcm.c +++ b/sound/soc/intel/atom/sst-mfld-platform-pcm.c @@ -341,7 +341,7 @@ static int sst_media_open(struct snd_pcm_substream *substream, stream = NULL; - return ret_val; + return 0; } static void sst_media_close(struct snd_pcm_substream *substream, diff --git a/sound/soc/intel/avs/pcm.c b/sound/soc/intel/avs/pcm.c index 880cd7a9fb34..13a38ec8c917 100644 --- a/sound/soc/intel/avs/pcm.c +++ b/sound/soc/intel/avs/pcm.c @@ -461,6 +461,8 @@ static int avs_dai_hda_be_prepare(struct snd_pcm_substream *substream, struct sn link_stream = data->link_stream; p = &be->dpcm[substream->stream].hw_params; + if (substream->runtime->state != SNDRV_PCM_STATE_PREPARED) + link_stream->link_prepared = false; if (link_stream->link_prepared) return 0; diff --git a/sound/soc/intel/avs/utils.c b/sound/soc/intel/avs/utils.c index ea14ec173855..f19a62e7e8b5 100644 --- a/sound/soc/intel/avs/utils.c +++ b/sound/soc/intel/avs/utils.c @@ -116,9 +116,11 @@ avs_module_ida_alloc(struct avs_dev *adev, struct avs_mods_info *newinfo, bool p int i; if (!purge && oldinfo) { - if (oldinfo->count >= newinfo->count) - dev_warn(adev->dev, "refreshing %d modules info with %d\n", + if (oldinfo->count >= newinfo->count) { + dev_warn(adev->dev, "modules info underflow, old: %d, new: %d\n", oldinfo->count, newinfo->count); + return -EPROTO; + } tocopy_count = oldinfo->count; } diff --git a/sound/soc/mediatek/common/mtk-afe-fe-dai.c b/sound/soc/mediatek/common/mtk-afe-fe-dai.c index 2a20fa5dba49..002953400938 100644 --- a/sound/soc/mediatek/common/mtk-afe-fe-dai.c +++ b/sound/soc/mediatek/common/mtk-afe-fe-dai.c @@ -75,8 +75,10 @@ int mtk_afe_fe_startup(struct snd_pcm_substream *substream, ret = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS); - if (ret < 0) + if (ret < 0) { dev_err(afe->dev, "snd_pcm_hw_constraint_integer failed\n"); + return ret; + } /* dynamic allocate irq to memif */ if (memif->irq_usage < 0) { @@ -88,10 +90,10 @@ int mtk_afe_fe_startup(struct snd_pcm_substream *substream, } else { dev_err(afe->dev, "%s() error: no more asys irq\n", __func__); - ret = -EBUSY; + return -EBUSY; } } - return ret; + return 0; } EXPORT_SYMBOL_GPL(mtk_afe_fe_startup); diff --git a/sound/soc/mediatek/common/mtk-soundcard-driver.c b/sound/soc/mediatek/common/mtk-soundcard-driver.c index 2d39ff23f854..a84f4ab4488b 100644 --- a/sound/soc/mediatek/common/mtk-soundcard-driver.c +++ b/sound/soc/mediatek/common/mtk-soundcard-driver.c @@ -129,6 +129,11 @@ void clean_card_reference(struct snd_soc_card *card) } EXPORT_SYMBOL_GPL(clean_card_reference); +static void mtk_soundcard_put_card_reference(void *data) +{ + clean_card_reference(data); +} + int mtk_soundcard_startup(struct snd_pcm_substream *substream, enum mtk_pcm_constraint_type ctype) { @@ -180,6 +185,43 @@ const struct snd_soc_ops mtk_soundcard_common_capture_ops = { }; EXPORT_SYMBOL_GPL(mtk_soundcard_common_capture_ops); +struct mtk_soundcard_name { + struct snd_soc_card *card; + const char *name; +}; + +static void mtk_soundcard_restore_name(void *data) +{ + struct mtk_soundcard_name *saved = data; + + saved->card->name = saved->name; + saved->card->topology_shortname = NULL; +} + +/* + * The card is static and outlives this probe, but the topology name is + * devm-allocated. Restore the original name when the probe's resources are + * released, so that a deferred or failed probe does not leave the card name + * pointing to freed memory for the next one. + */ +static int mtk_soundcard_set_topology_name(struct device *dev, + struct snd_soc_card *card) +{ + struct mtk_soundcard_name *saved; + + saved = devm_kzalloc(dev, sizeof(*saved), GFP_KERNEL); + if (!saved) + return -ENOMEM; + + saved->card = card; + saved->name = card->name; + card->topology_shortname = NULL; + + snd_soc_card_set_topology_name(card, "sof"); + + return devm_add_action_or_reset(dev, mtk_soundcard_restore_name, saved); +} + int mtk_soundcard_common_probe(struct platform_device *pdev) { struct device_node *platform_node, *adsp_node, *accdet_node; @@ -287,7 +329,12 @@ int mtk_soundcard_common_probe(struct platform_device *pdev) card->probe = mtk_sof_card_probe; card->late_probe = mtk_sof_card_late_probe; - snd_soc_card_set_topology_name(card, "sof"); + ret = mtk_soundcard_set_topology_name(&pdev->dev, card); + if (ret) { + of_node_put(adsp_node); + of_node_put(platform_node); + return ret; + } } /* @@ -325,8 +372,22 @@ int mtk_soundcard_common_probe(struct platform_device *pdev) ret = devm_snd_soc_register_card(&pdev->dev, card); - if (!needs_legacy_probe) - clean_card_reference(card); + /* + * When a component is still missing, snd_soc_bind_card() queues the + * card for a later rebind and returns success, so the card is not + * instantiated yet. That rebind reuses this same dai_link array, so + * the codec references parsed from the devicetree must be kept until + * the device is unbound: dropping them leaves both name and of_node + * unset and the rebind fails the dai link sanity check instead. + */ + if (!needs_legacy_probe) { + if (ret || snd_soc_card_is_instantiated(card)) + clean_card_reference(card); + else + ret = devm_add_action_or_reset(&pdev->dev, + mtk_soundcard_put_card_reference, + card); + } if (ret) { dev_err_probe(&pdev->dev, ret, "Cannot register card\n"); diff --git a/sound/soc/mediatek/mt6797/mt6797-afe-clk.c b/sound/soc/mediatek/mt6797/mt6797-afe-clk.c index 6f3e6acfcfab..0ac04d73b777 100644 --- a/sound/soc/mediatek/mt6797/mt6797-afe-clk.c +++ b/sound/soc/mediatek/mt6797/mt6797-afe-clk.c @@ -63,21 +63,21 @@ int mt6797_afe_enable_clock(struct mtk_base_afe *afe) if (ret) { dev_err(afe->dev, "%s(), clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_INFRA_SYS_AUD], ret); - goto CLK_INFRA_SYS_AUDIO_ERR; + return ret; } ret = clk_prepare_enable(afe_priv->clk[CLK_INFRA_SYS_AUD_26M]); if (ret) { dev_err(afe->dev, "%s(), clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_INFRA_SYS_AUD_26M], ret); - goto CLK_INFRA_SYS_AUD_26M_ERR; + goto CLK_INFRA_SYS_AUDIO_ERR; } ret = clk_prepare_enable(afe_priv->clk[CLK_TOP_MUX_AUD]); if (ret) { dev_err(afe->dev, "%s(), clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD], ret); - goto CLK_MUX_AUDIO_ERR; + goto CLK_INFRA_SYS_AUD_26M_ERR; } ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD], @@ -93,13 +93,11 @@ int mt6797_afe_enable_clock(struct mtk_base_afe *afe) if (ret) { dev_err(afe->dev, "%s(), clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_BUS], ret); - goto CLK_MUX_AUDIO_INTBUS_ERR; + goto CLK_MUX_AUDIO_ERR; } - return ret; + return 0; -CLK_MUX_AUDIO_INTBUS_ERR: - clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_BUS]); CLK_MUX_AUDIO_ERR: clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD]); CLK_INFRA_SYS_AUD_26M_ERR: @@ -107,7 +105,7 @@ int mt6797_afe_enable_clock(struct mtk_base_afe *afe) CLK_INFRA_SYS_AUDIO_ERR: clk_disable_unprepare(afe_priv->clk[CLK_INFRA_SYS_AUD]); - return 0; + return ret; } int mt6797_afe_disable_clock(struct mtk_base_afe *afe) diff --git a/sound/soc/mediatek/mt8183/mt8183-afe-clk.c b/sound/soc/mediatek/mt8183/mt8183-afe-clk.c index cc4f8f4d3dab..06556689976d 100644 --- a/sound/soc/mediatek/mt8183/mt8183-afe-clk.c +++ b/sound/soc/mediatek/mt8183/mt8183-afe-clk.c @@ -137,7 +137,7 @@ int mt8183_afe_enable_clock(struct mtk_base_afe *afe) dev_err(afe->dev, "%s(), clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_MUX_AUDIO], aud_clks[CLK_CLK26M], ret); - goto CLK_MUX_AUDIO_ERR; + goto CLK_MUX_AUDIO_INTBUS_ERR; } ret = clk_prepare_enable(afe_priv->clk[CLK_MUX_AUDIOINTBUS]); @@ -153,7 +153,7 @@ int mt8183_afe_enable_clock(struct mtk_base_afe *afe) dev_err(afe->dev, "%s(), clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_MUX_AUDIOINTBUS], aud_clks[CLK_TOP_SYSPLL_D2_D4], ret); - goto CLK_MUX_AUDIO_INTBUS_ERR; + goto CLK_AFE_ERR; } ret = clk_prepare_enable(afe_priv->clk[CLK_AFE]); @@ -271,7 +271,6 @@ static int apll1_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_ENG1], aud_clks[CLK_CLK26M], ret); - goto EXIT; } clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_ENG1]); @@ -281,7 +280,6 @@ static int apll1_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_1], aud_clks[CLK_CLK26M], ret); - goto EXIT; } clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_1]); } @@ -298,7 +296,6 @@ static int apll1_mux_setting(struct mtk_base_afe *afe, bool enable) afe_priv->clk[CLK_CLK26M]); clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_1]); ERR_ENABLE_CLK_TOP_MUX_AUD_1: -EXIT: return ret; } @@ -345,7 +342,6 @@ static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_ENG2], aud_clks[CLK_CLK26M], ret); - goto EXIT; } clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_ENG2]); @@ -355,7 +351,6 @@ static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_2], aud_clks[CLK_CLK26M], ret); - goto EXIT; } clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_2]); } @@ -372,7 +367,6 @@ static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) afe_priv->clk[CLK_CLK26M]); clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_2]); ERR_ENABLE_CLK_TOP_MUX_AUD_2: -EXIT: return ret; } @@ -382,7 +376,9 @@ int mt8183_apll1_enable(struct mtk_base_afe *afe) int ret; /* setting for APLL */ - apll1_mux_setting(afe, true); + ret = apll1_mux_setting(afe, true); + if (ret) + return ret; ret = clk_prepare_enable(afe_priv->clk[CLK_APLL22M]); if (ret) { @@ -411,6 +407,8 @@ int mt8183_apll1_enable(struct mtk_base_afe *afe) ERR_CLK_APLL1_TUNER: clk_disable_unprepare(afe_priv->clk[CLK_APLL22M]); ERR_CLK_APLL22M: + apll1_mux_setting(afe, false); + return ret; } @@ -436,7 +434,9 @@ int mt8183_apll2_enable(struct mtk_base_afe *afe) int ret; /* setting for APLL */ - apll2_mux_setting(afe, true); + ret = apll2_mux_setting(afe, true); + if (ret) + return ret; ret = clk_prepare_enable(afe_priv->clk[CLK_APLL24M]); if (ret) { @@ -465,6 +465,8 @@ int mt8183_apll2_enable(struct mtk_base_afe *afe) ERR_CLK_APLL2_TUNER: clk_disable_unprepare(afe_priv->clk[CLK_APLL24M]); ERR_CLK_APLL24M: + apll2_mux_setting(afe, false); + return ret; } diff --git a/sound/soc/mediatek/mt8186/mt8186-afe-clk.c b/sound/soc/mediatek/mt8186/mt8186-afe-clk.c index daaca36a2d08..62b008b7caca 100644 --- a/sound/soc/mediatek/mt8186/mt8186-afe-clk.c +++ b/sound/soc/mediatek/mt8186/mt8186-afe-clk.c @@ -98,7 +98,7 @@ static int apll1_mux_setting(struct mtk_base_afe *afe, bool enable) if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_1], ret); - return ret; + goto ERR_ENABLE_CLK_TOP_MUX_AUD_1; } ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_1], afe_priv->clk[CLK_TOP_APLL1_CK]); @@ -106,7 +106,7 @@ static int apll1_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_1], aud_clks[CLK_TOP_APLL1_CK], ret); - return ret; + goto ERR_SELECT_CLK_TOP_MUX_AUD_1; } /* 180.6336 / 8 = 22.5792MHz */ @@ -114,7 +114,7 @@ static int apll1_mux_setting(struct mtk_base_afe *afe, bool enable) if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_ENG1], ret); - return ret; + goto ERR_ENABLE_CLK_TOP_MUX_AUD_ENG1; } ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_ENG1], afe_priv->clk[CLK_TOP_APLL1_D8]); @@ -122,7 +122,7 @@ static int apll1_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_ENG1], aud_clks[CLK_TOP_APLL1_D8], ret); - return ret; + goto ERR_SELECT_CLK_TOP_MUX_AUD_ENG1; } } else { ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_ENG1], @@ -131,7 +131,6 @@ static int apll1_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_ENG1], aud_clks[CLK_CLK26M], ret); - return ret; } clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_ENG1]); @@ -141,12 +140,23 @@ static int apll1_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_1], aud_clks[CLK_CLK26M], ret); - return ret; } clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_1]); } return 0; + +ERR_SELECT_CLK_TOP_MUX_AUD_ENG1: + clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_ENG1], + afe_priv->clk[CLK_CLK26M]); + clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_ENG1]); +ERR_ENABLE_CLK_TOP_MUX_AUD_ENG1: +ERR_SELECT_CLK_TOP_MUX_AUD_1: + clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_1], + afe_priv->clk[CLK_CLK26M]); + clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_1]); +ERR_ENABLE_CLK_TOP_MUX_AUD_1: + return ret; } static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) @@ -159,7 +169,7 @@ static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_2], ret); - return ret; + goto ERR_ENABLE_CLK_TOP_MUX_AUD_2; } ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_2], afe_priv->clk[CLK_TOP_APLL2_CK]); @@ -167,7 +177,7 @@ static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_2], aud_clks[CLK_TOP_APLL2_CK], ret); - return ret; + goto ERR_SELECT_CLK_TOP_MUX_AUD_2; } /* 196.608 / 8 = 24.576MHz */ @@ -175,7 +185,7 @@ static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_ENG2], ret); - return ret; + goto ERR_ENABLE_CLK_TOP_MUX_AUD_ENG2; } ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_ENG2], afe_priv->clk[CLK_TOP_APLL2_D8]); @@ -183,7 +193,7 @@ static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_ENG2], aud_clks[CLK_TOP_APLL2_D8], ret); - return ret; + goto ERR_SELECT_CLK_TOP_MUX_AUD_ENG2; } } else { ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_ENG2], @@ -192,7 +202,6 @@ static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_ENG2], aud_clks[CLK_CLK26M], ret); - return ret; } clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_ENG2]); @@ -202,12 +211,23 @@ static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_2], aud_clks[CLK_CLK26M], ret); - return ret; } clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_2]); } return 0; + +ERR_SELECT_CLK_TOP_MUX_AUD_ENG2: + clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_ENG2], + afe_priv->clk[CLK_CLK26M]); + clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_ENG2]); +ERR_ENABLE_CLK_TOP_MUX_AUD_ENG2: +ERR_SELECT_CLK_TOP_MUX_AUD_2: + clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_2], + afe_priv->clk[CLK_CLK26M]); + clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_2]); +ERR_ENABLE_CLK_TOP_MUX_AUD_2: + return ret; } int mt8186_afe_enable_cgs(struct mtk_base_afe *afe) @@ -268,7 +288,7 @@ int mt8186_afe_enable_clock(struct mtk_base_afe *afe) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_MUX_AUDIO], aud_clks[CLK_CLK26M], ret); - goto clk_mux_audio_err; + goto clk_mux_audio_intbus_err; } ret = clk_prepare_enable(afe_priv->clk[CLK_MUX_AUDIOINTBUS]); @@ -295,24 +315,22 @@ int mt8186_afe_enable_clock(struct mtk_base_afe *afe) if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_AFE], ret); - goto clk_afe_err; + goto clk_mux_audio_h_parent_err; } return 0; -clk_afe_err: - clk_disable_unprepare(afe_priv->clk[CLK_AFE]); clk_mux_audio_h_parent_err: -clk_mux_audio_intbus_parent_err: mt8186_set_audio_int_bus_parent(afe, CLK_CLK26M); -clk_mux_audio_intbus_err: +clk_mux_audio_intbus_parent_err: clk_disable_unprepare(afe_priv->clk[CLK_MUX_AUDIOINTBUS]); -clk_mux_audio_err: +clk_mux_audio_intbus_err: clk_disable_unprepare(afe_priv->clk[CLK_MUX_AUDIO]); -clk_infra_sys_audio_err: - clk_disable_unprepare(afe_priv->clk[CLK_INFRA_SYS_AUDIO]); -clk_infra_audio_26m_err: +clk_mux_audio_err: clk_disable_unprepare(afe_priv->clk[CLK_INFRA_AUDIO_26M]); +clk_infra_audio_26m_err: + clk_disable_unprepare(afe_priv->clk[CLK_INFRA_SYS_AUDIO]); +clk_infra_sys_audio_err: return ret; } @@ -335,7 +353,9 @@ int mt8186_apll1_enable(struct mtk_base_afe *afe) int ret; /* setting for APLL */ - apll1_mux_setting(afe, true); + ret = apll1_mux_setting(afe, true); + if (ret) + return ret; ret = clk_prepare_enable(afe_priv->clk[CLK_APLL22M]); if (ret) { @@ -360,9 +380,9 @@ int mt8186_apll1_enable(struct mtk_base_afe *afe) return 0; err_clk_apll1_tuner: - clk_disable_unprepare(afe_priv->clk[CLK_APLL1_TUNER]); -err_clk_apll22m: clk_disable_unprepare(afe_priv->clk[CLK_APLL22M]); +err_clk_apll22m: + apll1_mux_setting(afe, false); return ret; } @@ -388,7 +408,9 @@ int mt8186_apll2_enable(struct mtk_base_afe *afe) int ret; /* setting for APLL */ - apll2_mux_setting(afe, true); + ret = apll2_mux_setting(afe, true); + if (ret) + return ret; ret = clk_prepare_enable(afe_priv->clk[CLK_APLL24M]); if (ret) { @@ -413,9 +435,9 @@ int mt8186_apll2_enable(struct mtk_base_afe *afe) return 0; err_clk_apll2_tuner: - clk_disable_unprepare(afe_priv->clk[CLK_APLL2_TUNER]); -err_clk_apll24m: clk_disable_unprepare(afe_priv->clk[CLK_APLL24M]); +err_clk_apll24m: + apll2_mux_setting(afe, false); return ret; } @@ -498,7 +520,7 @@ int mt8186_mck_enable(struct mtk_base_afe *afe, int mck_id, int rate) if (ret) { dev_err(afe->dev, "%s(), clk_prepare_enable %s fail %d\n", __func__, aud_clks[m_sel_id], ret); - return ret; + goto ERR_ENABLE_MCLK; } ret = clk_set_parent(afe_priv->clk[m_sel_id], afe_priv->clk[apll_clk_id]); @@ -506,7 +528,7 @@ int mt8186_mck_enable(struct mtk_base_afe *afe, int mck_id, int rate) dev_err(afe->dev, "%s(), clk_set_parent %s-%s fail %d\n", __func__, aud_clks[m_sel_id], aud_clks[apll_clk_id], ret); - return ret; + goto ERR_SELECT_MCLK; } } @@ -515,16 +537,25 @@ int mt8186_mck_enable(struct mtk_base_afe *afe, int mck_id, int rate) if (ret) { dev_err(afe->dev, "%s(), clk_prepare_enable %s fail %d\n", __func__, aud_clks[div_clk_id], ret); - return ret; + goto ERR_ENABLE_MCLK_DIV; } ret = clk_set_rate(afe_priv->clk[div_clk_id], rate); if (ret) { dev_err(afe->dev, "%s(), clk_set_rate %s, rate %d, fail %d\n", __func__, aud_clks[div_clk_id], rate, ret); - return ret; + goto ERR_SET_MCLK_RATE; } return 0; + +ERR_SET_MCLK_RATE: + clk_disable_unprepare(afe_priv->clk[div_clk_id]); +ERR_ENABLE_MCLK_DIV: +ERR_SELECT_MCLK: + if (m_sel_id >= 0) + clk_disable_unprepare(afe_priv->clk[m_sel_id]); +ERR_ENABLE_MCLK: + return ret; } void mt8186_mck_disable(struct mtk_base_afe *afe, int mck_id) diff --git a/sound/soc/mediatek/mt8188/mt8188-afe-clk.c b/sound/soc/mediatek/mt8188/mt8188-afe-clk.c index fc6cb3f0469e..1ff975ef98ec 100644 --- a/sound/soc/mediatek/mt8188/mt8188-afe-clk.c +++ b/sound/soc/mediatek/mt8188/mt8188-afe-clk.c @@ -260,15 +260,28 @@ static int mt8188_afe_enable_tuner_clk(struct mtk_base_afe *afe, unsigned int id) { struct mt8188_afe_private *afe_priv = afe->platform_priv; + int ret; switch (id) { case MT8188_AUD_PLL1: - mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_APLL]); - mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_APLL1_TUNER]); + ret = mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_APLL]); + if (ret) + return ret; + ret = mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_APLL1_TUNER]); + if (ret) { + mt8188_afe_disable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_APLL]); + return ret; + } break; case MT8188_AUD_PLL2: - mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_APLL2]); - mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_APLL2_TUNER]); + ret = mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_APLL2]); + if (ret) + return ret; + ret = mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_APLL2_TUNER]); + if (ret) { + mt8188_afe_disable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_APLL2]); + return ret; + } break; default: return -EINVAL; @@ -554,9 +567,7 @@ static int mt8188_afe_enable_top_cg(struct mtk_base_afe *afe, unsigned int cg_ty unsigned int mask = get_top_cg_mask(cg_type); unsigned int val = get_top_cg_on_val(cg_type); - regmap_update_bits(afe->regmap, reg, mask, val); - - return 0; + return regmap_update_bits(afe->regmap, reg, mask, val); } static int mt8188_afe_disable_top_cg(struct mtk_base_afe *afe, unsigned int cg_type) @@ -565,30 +576,53 @@ static int mt8188_afe_disable_top_cg(struct mtk_base_afe *afe, unsigned int cg_t unsigned int mask = get_top_cg_mask(cg_type); unsigned int val = get_top_cg_off_val(cg_type); - regmap_update_bits(afe->regmap, reg, mask, val); - - return 0; + return regmap_update_bits(afe->regmap, reg, mask, val); } int mt8188_afe_enable_reg_rw_clk(struct mtk_base_afe *afe) { struct mt8188_afe_private *afe_priv = afe->platform_priv; - + int ret; /* bus clock for AFE external access, like DRAM */ - mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_TOP_AUDIO_LOCAL_BUS_SEL]); + ret = mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_TOP_AUDIO_LOCAL_BUS_SEL]); + if (ret) + goto err_local_bus; /* bus clock for AFE internal access, like AFE SRAM */ - mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_TOP_AUD_INTBUS_SEL]); + ret = mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_TOP_AUD_INTBUS_SEL]); + if (ret) + goto err_intbus; /* audio 26m clock source */ - mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_ADSP_AUDIO_26M]); + ret = mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_ADSP_AUDIO_26M]); + if (ret) + goto err_26m; /* AFE hw clock */ - mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_AFE]); - mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_A1SYS_HP]); - mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_A1SYS]); + ret = mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_AFE]); + if (ret) + goto err_afe; + ret = mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_A1SYS_HP]); + if (ret) + goto err_a1sys_hp; + ret = mt8188_afe_enable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_A1SYS]); + if (ret) + goto err_a1sys; return 0; + +err_a1sys: + mt8188_afe_disable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_A1SYS_HP]); +err_a1sys_hp: + mt8188_afe_disable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_AFE]); +err_afe: + mt8188_afe_disable_clk(afe, afe_priv->clk[MT8188_CLK_ADSP_AUDIO_26M]); +err_26m: + mt8188_afe_disable_clk(afe, afe_priv->clk[MT8188_CLK_TOP_AUD_INTBUS_SEL]); +err_intbus: + mt8188_afe_disable_clk(afe, afe_priv->clk[MT8188_CLK_TOP_AUDIO_LOCAL_BUS_SEL]); +err_local_bus: + return ret; } int mt8188_afe_disable_reg_rw_clk(struct mtk_base_afe *afe) @@ -607,14 +641,12 @@ int mt8188_afe_disable_reg_rw_clk(struct mtk_base_afe *afe) static int mt8188_afe_enable_afe_on(struct mtk_base_afe *afe) { - regmap_update_bits(afe->regmap, AFE_DAC_CON0, 0x1, 0x1); - return 0; + return regmap_update_bits(afe->regmap, AFE_DAC_CON0, 0x1, 0x1); } static int mt8188_afe_disable_afe_on(struct mtk_base_afe *afe) { - regmap_update_bits(afe->regmap, AFE_DAC_CON0, 0x1, 0x0); - return 0; + return regmap_update_bits(afe->regmap, AFE_DAC_CON0, 0x1, 0x0); } static int mt8188_afe_enable_a1sys(struct mtk_base_afe *afe) @@ -626,7 +658,13 @@ static int mt8188_afe_enable_a1sys(struct mtk_base_afe *afe) if (ret) return ret; - return mt8188_afe_enable_top_cg(afe, MT8188_TOP_CG_A1SYS_TIMING); + ret = mt8188_afe_enable_top_cg(afe, MT8188_TOP_CG_A1SYS_TIMING); + if (ret) { + mt8188_afe_disable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_A1SYS]); + return ret; + } + + return 0; } static int mt8188_afe_disable_a1sys(struct mtk_base_afe *afe) @@ -647,7 +685,13 @@ static int mt8188_afe_enable_a2sys(struct mtk_base_afe *afe) if (ret) return ret; - return mt8188_afe_enable_top_cg(afe, MT8188_TOP_CG_A2SYS_TIMING); + ret = mt8188_afe_enable_top_cg(afe, MT8188_TOP_CG_A2SYS_TIMING); + if (ret) { + mt8188_afe_disable_clk(afe, afe_priv->clk[MT8188_CLK_AUD_A2SYS]); + return ret; + } + + return 0; } static int mt8188_afe_disable_a2sys(struct mtk_base_afe *afe) @@ -735,8 +779,18 @@ int mt8188_apll2_disable(struct mtk_base_afe *afe) int mt8188_afe_enable_main_clock(struct mtk_base_afe *afe) { - mt8188_afe_enable_top_cg(afe, MT8188_TOP_CG_26M_TIMING); - mt8188_afe_enable_afe_on(afe); + int ret; + + ret = mt8188_afe_enable_top_cg(afe, MT8188_TOP_CG_26M_TIMING); + if (ret) + return ret; + + ret = mt8188_afe_enable_afe_on(afe); + if (ret) { + mt8188_afe_disable_top_cg(afe, MT8188_TOP_CG_26M_TIMING); + return ret; + } + return 0; } diff --git a/sound/soc/mediatek/mt8188/mt8188-afe-pcm.c b/sound/soc/mediatek/mt8188/mt8188-afe-pcm.c index 7b1f5d05f4d6..4174ddbb9407 100644 --- a/sound/soc/mediatek/mt8188/mt8188-afe-pcm.c +++ b/sound/soc/mediatek/mt8188/mt8188-afe-pcm.c @@ -320,6 +320,9 @@ static int mt8188_afe_fe_startup(struct snd_pcm_substream *substream, MT8188_MEMIF_DL7_MAX_PERIOD_SIZE); if (ret < 0) dev_dbg(afe->dev, "hw_constraint_minmax failed\n"); + else + ret = 0; + out: return ret; } @@ -3030,22 +3033,33 @@ static int mt8188_afe_runtime_resume(struct device *dev) struct mtk_base_afe *afe = dev_get_drvdata(dev); struct mt8188_afe_private *afe_priv = afe->platform_priv; struct arm_smccc_res res; + int ret; arm_smccc_smc(MTK_SIP_AUDIO_CONTROL, MTK_AUDIO_SMC_OP_DOMAIN_SIDEBANDS, 0, 0, 0, 0, 0, 0, &res); - mt8188_afe_enable_reg_rw_clk(afe); + ret = mt8188_afe_enable_reg_rw_clk(afe); + if (ret) + return ret; if (!afe->regmap || afe_priv->pm_runtime_bypass_reg_ctl) - goto skip_regmap; + return 0; regcache_cache_only(afe->regmap, false); - regcache_sync(afe->regmap); + ret = regcache_sync(afe->regmap); + if (ret) + goto err; + + ret = mt8188_afe_enable_main_clock(afe); + if (ret) + goto err; - mt8188_afe_enable_main_clock(afe); -skip_regmap: return 0; +err: + mt8188_afe_disable_reg_rw_clk(afe); + regcache_cache_only(afe->regmap, true); + return ret; } static int init_memif_priv_data(struct mtk_base_afe *afe) diff --git a/sound/soc/mediatek/mt8188/mt8188-audsys-clk.c b/sound/soc/mediatek/mt8188/mt8188-audsys-clk.c index 972f097a13ca..9f3b3a777577 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_obj(*cl); - 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/mediatek/mt8188/mt8188-mt6359.c b/sound/soc/mediatek/mt8188/mt8188-mt6359.c index 75c90d1d165f..f07aeb637108 100644 --- a/sound/soc/mediatek/mt8188/mt8188-mt6359.c +++ b/sound/soc/mediatek/mt8188/mt8188-mt6359.c @@ -1142,6 +1142,9 @@ static struct snd_soc_dai_link mt8188_mt6359_dai_links[] = { }, .dynamic = 1, .capture_only = 1, + .dpcm_merged_chan = 1, + .dpcm_merged_rate = 1, + .dpcm_merged_format = 1, SND_SOC_DAILINK_REG(capture8), }, [DAI_LINK_UL9_FE] = { diff --git a/sound/soc/mediatek/mt8189/mt8189-afe-clk.c b/sound/soc/mediatek/mt8189/mt8189-afe-clk.c index fc7a7a73b0cf..1132c924158d 100644 --- a/sound/soc/mediatek/mt8189/mt8189-afe-clk.c +++ b/sound/soc/mediatek/mt8189/mt8189-afe-clk.c @@ -454,30 +454,47 @@ int mt8189_apll1_enable(struct mtk_base_afe *afe) ret = mt8189_afe_enable_top_cg(afe, MT8189_CG_APLL1_CK); if (ret) - return ret; + goto err_clear_mux_setting; ret = mt8189_afe_enable_top_cg(afe, MT8189_PDN_APLL_TUNER1); if (ret) - return ret; + goto err_disable_apll1_ck; /* sel 44.1kHz:1, apll_div:7, upper bound:3 */ - regmap_update_bits(afe->regmap, AFE_APLL1_TUNER_CFG, - XTAL_EN_128FS_SEL_MASK_SFT | APLL_DIV_MASK_SFT | - UPPER_BOUND_MASK_SFT, - (0x1 << XTAL_EN_128FS_SEL_SFT) | (7 << APLL_DIV_SFT) | - (3 << UPPER_BOUND_SFT)); + ret = regmap_update_bits(afe->regmap, AFE_APLL1_TUNER_CFG, + XTAL_EN_128FS_SEL_MASK_SFT | APLL_DIV_MASK_SFT | + UPPER_BOUND_MASK_SFT, + (0x1 << XTAL_EN_128FS_SEL_SFT) | (7 << APLL_DIV_SFT) | + (3 << UPPER_BOUND_SFT)); + if (ret) + goto err_disable_apll_tuner1; /* apll1 freq tuner enable */ - regmap_update_bits(afe->regmap, AFE_APLL1_TUNER_CFG, - FREQ_TUNER_EN_MASK_SFT, - 0x1 << FREQ_TUNER_EN_SFT); + ret = regmap_update_bits(afe->regmap, AFE_APLL1_TUNER_CFG, + FREQ_TUNER_EN_MASK_SFT, + 0x1 << FREQ_TUNER_EN_SFT); + if (ret) + goto err_disable_apll_tuner1; /* audio apll1 on */ ret = mt8189_afe_enable_top_cg(afe, MT8189_AUDIO_APLL1_EN_ON); if (ret) - return ret; + goto err_clear_freq_tuner_en; return 0; + +err_clear_freq_tuner_en: + regmap_update_bits(afe->regmap, AFE_APLL1_TUNER_CFG, + FREQ_TUNER_EN_MASK_SFT, + 0x0); +err_disable_apll_tuner1: + mt8189_afe_disable_top_cg(afe, MT8189_PDN_APLL_TUNER1); +err_disable_apll1_ck: + mt8189_afe_disable_top_cg(afe, MT8189_CG_APLL1_CK); +err_clear_mux_setting: + apll1_mux_setting(afe, false); + + return ret; } void mt8189_apll1_disable(struct mtk_base_afe *afe) @@ -506,30 +523,47 @@ int mt8189_apll2_enable(struct mtk_base_afe *afe) ret = mt8189_afe_enable_top_cg(afe, MT8189_CG_APLL2_CK); if (ret) - return ret; + goto err_clear_mux_setting; ret = mt8189_afe_enable_top_cg(afe, MT8189_PDN_APLL_TUNER2); if (ret) - return ret; + goto err_disable_apll2_ck; /* sel 48kHz: 2, apll_div: 7, upper bound: 3*/ - regmap_update_bits(afe->regmap, AFE_APLL2_TUNER_CFG, - XTAL_EN_128FS_SEL_MASK_SFT | APLL_DIV_MASK_SFT | - UPPER_BOUND_MASK_SFT, - (0x2 << XTAL_EN_128FS_SEL_SFT) | (7 << APLL_DIV_SFT) | - (3 << UPPER_BOUND_SFT)); + ret = regmap_update_bits(afe->regmap, AFE_APLL2_TUNER_CFG, + XTAL_EN_128FS_SEL_MASK_SFT | APLL_DIV_MASK_SFT | + UPPER_BOUND_MASK_SFT, + (0x2 << XTAL_EN_128FS_SEL_SFT) | (7 << APLL_DIV_SFT) | + (3 << UPPER_BOUND_SFT)); + if (ret) + goto err_disable_apll_tuner2; /* apll2 freq tuner enable */ - regmap_update_bits(afe->regmap, AFE_APLL2_TUNER_CFG, - FREQ_TUNER_EN_MASK_SFT, - 0x1 << FREQ_TUNER_EN_SFT); + ret = regmap_update_bits(afe->regmap, AFE_APLL2_TUNER_CFG, + FREQ_TUNER_EN_MASK_SFT, + 0x1 << FREQ_TUNER_EN_SFT); + if (ret) + goto err_disable_apll_tuner2; /* audio apll2 on */ ret = mt8189_afe_enable_top_cg(afe, MT8189_AUDIO_APLL2_EN_ON); if (ret) - return ret; + goto err_clear_freq_tuner_en; return 0; + +err_clear_freq_tuner_en: + regmap_update_bits(afe->regmap, AFE_APLL2_TUNER_CFG, + FREQ_TUNER_EN_MASK_SFT, + 0x0); +err_disable_apll_tuner2: + mt8189_afe_disable_top_cg(afe, MT8189_PDN_APLL_TUNER2); +err_disable_apll2_ck: + mt8189_afe_disable_top_cg(afe, MT8189_CG_APLL2_CK); +err_clear_mux_setting: + apll2_mux_setting(afe, false); + + return ret; } void mt8189_apll2_disable(struct mtk_base_afe *afe) @@ -605,7 +639,7 @@ int mt8189_mck_enable(struct mtk_base_afe *afe, int mck_id, int rate) ret = mt8189_afe_set_clk_parent(afe, afe_priv->clk[m_sel_id], afe_priv->clk[apll_clk_id]); if (ret) - return ret; + goto err_disable_m_sel_clk; } /* enable div, set rate */ @@ -616,13 +650,21 @@ int mt8189_mck_enable(struct mtk_base_afe *afe, int mck_id, int rate) ret = mt8189_afe_enable_clk(afe, afe_priv->clk[div_clk_id]); if (ret) - return ret; + goto err_disable_m_sel_clk; ret = mt8189_afe_set_clk_rate(afe, afe_priv->clk[div_clk_id], rate); if (ret) - return ret; + goto err_disable_div_clk; return 0; + +err_disable_div_clk: + mt8189_afe_disable_clk(afe, afe_priv->clk[div_clk_id]); +err_disable_m_sel_clk: + if (m_sel_id >= 0) + mt8189_afe_disable_clk(afe, afe_priv->clk[m_sel_id]); + + return ret; } int mt8189_mck_disable(struct mtk_base_afe *afe, int mck_id) @@ -633,8 +675,8 @@ int mt8189_mck_disable(struct mtk_base_afe *afe, int mck_id) dev_dbg(afe->dev, "mck_id: %d.\n", mck_id); - if (mck_id < 0) { - dev_err(afe->dev, "mck_id = %d < 0\n", mck_id); + if (mck_id >= MT8189_MCK_NUM || mck_id < 0) { + dev_err(afe->dev, "mck_id = %d\n", mck_id); return -EINVAL; } @@ -658,17 +700,36 @@ int mt8189_mck_disable(struct mtk_base_afe *afe, int mck_id) int mt8189_afe_enable_reg_rw_clk(struct mtk_base_afe *afe) { struct mt8189_afe_private *afe_priv = afe->platform_priv; + int ret; /* bus clock for AFE internal access, like AFE SRAM */ - mt8189_afe_enable_clk(afe, afe_priv->clk[MT8189_CLK_TOP_MUX_AUDIOINTBUS]); - mt8189_afe_set_clk_parent(afe, afe_priv->clk[MT8189_CLK_TOP_MUX_AUDIOINTBUS], - afe_priv->clk[MT8189_CLK_TOP_CLK26M]); + ret = mt8189_afe_enable_clk(afe, afe_priv->clk[MT8189_CLK_TOP_MUX_AUDIOINTBUS]); + if (ret) + return ret; + + ret = mt8189_afe_set_clk_parent(afe, afe_priv->clk[MT8189_CLK_TOP_MUX_AUDIOINTBUS], + afe_priv->clk[MT8189_CLK_TOP_CLK26M]); + if (ret) + goto err_disable_audiointbus_clk; + /* enable audio clock source */ - mt8189_afe_enable_clk(afe, afe_priv->clk[MT8189_CLK_TOP_MUX_AUDIO_H]); - mt8189_afe_set_clk_parent(afe, afe_priv->clk[MT8189_CLK_TOP_MUX_AUDIO_H], - afe_priv->clk[MT8189_CLK_TOP_CLK26M]); + ret = mt8189_afe_enable_clk(afe, afe_priv->clk[MT8189_CLK_TOP_MUX_AUDIO_H]); + if (ret) + goto err_disable_audiointbus_clk; + + ret = mt8189_afe_set_clk_parent(afe, afe_priv->clk[MT8189_CLK_TOP_MUX_AUDIO_H], + afe_priv->clk[MT8189_CLK_TOP_CLK26M]); + if (ret) + goto err_disable_audio_h_clk; return 0; + +err_disable_audio_h_clk: + mt8189_afe_disable_clk(afe, afe_priv->clk[MT8189_CLK_TOP_MUX_AUDIO_H]); +err_disable_audiointbus_clk: + mt8189_afe_disable_clk(afe, afe_priv->clk[MT8189_CLK_TOP_MUX_AUDIOINTBUS]); + + return ret; } int mt8189_afe_disable_reg_rw_clk(struct mtk_base_afe *afe) diff --git a/sound/soc/mediatek/mt8189/mt8189-afe-pcm.c b/sound/soc/mediatek/mt8189/mt8189-afe-pcm.c index 77cf2b604f6c..311d8dcab5e2 100644 --- a/sound/soc/mediatek/mt8189/mt8189-afe-pcm.c +++ b/sound/soc/mediatek/mt8189/mt8189-afe-pcm.c @@ -155,8 +155,10 @@ static int mt8189_fe_startup(struct snd_pcm_substream *substream, ret = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS); - if (ret < 0) + if (ret < 0) { dev_warn(afe->dev, "snd_pcm_hw_constraint_integer failed\n"); + return ret; + } /* dynamic allocate irq to memif */ if (memif->irq_usage < 0) { @@ -168,11 +170,11 @@ static int mt8189_fe_startup(struct snd_pcm_substream *substream, } else { dev_err(afe->dev, "%s() error: no more asys irq\n", __func__); - ret = -EBUSY; + return -EBUSY; } } - return ret; + return 0; } static void mt8189_fe_shutdown(struct snd_pcm_substream *substream, @@ -2332,20 +2334,40 @@ static int mt8189_afe_runtime_resume(struct device *dev) } regcache_cache_only(afe->regmap, false); - regcache_sync(afe->regmap); + ret = regcache_sync(afe->regmap); + if (ret) + goto err_set_cache_only; /* set audio 26M request */ - regmap_update_bits(afe->regmap, AFE_SPM_CONTROL_REQ, 0x1, 0x1); - regmap_update_bits(afe->regmap, AFE_CBIP_CFG0, 0x1, 0x1); + ret = regmap_update_bits(afe->regmap, AFE_SPM_CONTROL_REQ, 0x1, 0x1); + if (ret) + goto err_set_cache_only; + + ret = regmap_update_bits(afe->regmap, AFE_CBIP_CFG0, 0x1, 0x1); + if (ret) + goto err_clear_26m_req; /* force cpu use 8_24 format when writing 32bit data */ - regmap_update_bits(afe->regmap, AFE_MEMIF_CON0, - CPU_HD_ALIGN_MASK_SFT, 0 << CPU_HD_ALIGN_SFT); + ret = regmap_update_bits(afe->regmap, AFE_MEMIF_CON0, + CPU_HD_ALIGN_MASK_SFT, 0 << CPU_HD_ALIGN_SFT); + if (ret) + goto err_clear_26m_req; /* enable AFE */ - mt8189_afe_enable_main_clock(afe); + ret = mt8189_afe_enable_main_clock(afe); + if (ret) + goto err_clear_26m_req; return 0; + +err_clear_26m_req: + regmap_update_bits(afe->regmap, + AFE_SPM_CONTROL_REQ, 0x1, 0x0); +err_set_cache_only: + regcache_cache_only(afe->regmap, true); + mt8189_afe_disable_reg_rw_clk(afe); + + return ret; } static int mt8189_afe_component_probe(struct snd_soc_component *component) diff --git a/sound/soc/mediatek/mt8189/mt8189-dai-i2s.c b/sound/soc/mediatek/mt8189/mt8189-dai-i2s.c index 94c49a662e2d..c9e80ef42f60 100644 --- a/sound/soc/mediatek/mt8189/mt8189-dai-i2s.c +++ b/sound/soc/mediatek/mt8189/mt8189-dai-i2s.c @@ -485,6 +485,7 @@ static int mtk_apll_event(struct snd_soc_dapm_widget *w, { struct snd_soc_component *cmpnt = snd_soc_dapm_to_component(w->dapm); struct mtk_base_afe *afe = snd_soc_component_get_drvdata(cmpnt); + int ret; dev_dbg(cmpnt->dev, "%s(), name %s, event 0x%x\n", __func__, w->name, event); @@ -492,9 +493,11 @@ static int mtk_apll_event(struct snd_soc_dapm_widget *w, switch (event) { case SND_SOC_DAPM_PRE_PMU: if (strcmp(w->name, APLL1_W_NAME) == 0) - mt8189_apll1_enable(afe); + ret = mt8189_apll1_enable(afe); else - mt8189_apll2_enable(afe); + ret = mt8189_apll2_enable(afe); + if (ret) + return ret; break; case SND_SOC_DAPM_POST_PMD: if (strcmp(w->name, APLL1_W_NAME) == 0) @@ -516,6 +519,7 @@ static int mtk_mclk_en_event(struct snd_soc_dapm_widget *w, struct snd_soc_component *cmpnt = snd_soc_dapm_to_component(w->dapm); struct mtk_base_afe *afe = snd_soc_component_get_drvdata(cmpnt); struct mtk_afe_i2s_priv *i2s_priv; + int ret; dev_dbg(cmpnt->dev, "%s(), name %s, event 0x%x\n", __func__, w->name, event); @@ -526,17 +530,18 @@ static int mtk_mclk_en_event(struct snd_soc_dapm_widget *w, switch (event) { case SND_SOC_DAPM_PRE_PMU: - mt8189_mck_enable(afe, i2s_priv->mclk_id, i2s_priv->mclk_rate); + ret = mt8189_mck_enable(afe, i2s_priv->mclk_id, i2s_priv->mclk_rate); break; case SND_SOC_DAPM_POST_PMD: i2s_priv->mclk_rate = 0; - mt8189_mck_disable(afe, i2s_priv->mclk_id); + ret = mt8189_mck_disable(afe, i2s_priv->mclk_id); break; default: + ret = 0; break; } - return 0; + return ret; } static const struct snd_soc_dapm_widget mtk_dai_i2s_widgets[] = { @@ -1282,6 +1287,9 @@ static int mtk_dai_i2s_set_sysclk(struct snd_soc_dai *dai, dir != SND_SOC_CLOCK_OUT) return -EINVAL; + if (!freq) + return -EINVAL; + i2s_priv = afe_priv->dai_priv[dai->id]; if (!i2s_priv) return -EINVAL; diff --git a/sound/soc/mediatek/mt8189/mt8189-dai-tdm.c b/sound/soc/mediatek/mt8189/mt8189-dai-tdm.c index 5d68a55ccc45..e113c52fe06a 100644 --- a/sound/soc/mediatek/mt8189/mt8189-dai-tdm.c +++ b/sound/soc/mediatek/mt8189/mt8189-dai-tdm.c @@ -261,22 +261,24 @@ static int mtk_tdm_bck_en_event(struct snd_soc_dapm_widget *w, struct mt8189_afe_private *afe_priv = afe->platform_priv; int dai_id = get_tdm_id_by_name(w->name); struct mtk_afe_tdm_priv *tdm_priv = afe_priv->dai_priv[dai_id]; + int ret; dev_dbg(cmpnt->dev, "name %s, event 0x%x, dai_id %d, bck: %d\n", w->name, event, dai_id, tdm_priv->bck_rate); switch (event) { case SND_SOC_DAPM_PRE_PMU: - mt8189_mck_enable(afe, tdm_priv->bck_id, tdm_priv->bck_rate); + ret = mt8189_mck_enable(afe, tdm_priv->bck_id, tdm_priv->bck_rate); break; case SND_SOC_DAPM_POST_PMD: - mt8189_mck_disable(afe, tdm_priv->bck_id); + ret = mt8189_mck_disable(afe, tdm_priv->bck_id); break; default: + ret = 0; break; } - return 0; + return ret; } static int mtk_tdm_mck_en_event(struct snd_soc_dapm_widget *w, @@ -288,23 +290,25 @@ static int mtk_tdm_mck_en_event(struct snd_soc_dapm_widget *w, struct mt8189_afe_private *afe_priv = afe->platform_priv; int dai_id = get_tdm_id_by_name(w->name); struct mtk_afe_tdm_priv *tdm_priv = afe_priv->dai_priv[dai_id]; + int ret; dev_dbg(cmpnt->dev, "name %s, event 0x%x, dai_id %d, mclk %d\n", w->name, event, dai_id, tdm_priv->mclk_rate); switch (event) { case SND_SOC_DAPM_PRE_PMU: - mt8189_mck_enable(afe, tdm_priv->mclk_id, tdm_priv->mclk_rate); + ret = mt8189_mck_enable(afe, tdm_priv->mclk_id, tdm_priv->mclk_rate); break; case SND_SOC_DAPM_POST_PMD: tdm_priv->mclk_rate = 0; - mt8189_mck_disable(afe, tdm_priv->mclk_id); + ret = mt8189_mck_disable(afe, tdm_priv->mclk_id); break; default: + ret = 0; break; } - return 0; + return ret; } static const struct snd_soc_dapm_widget mtk_dai_tdm_widgets[] = { @@ -379,6 +383,9 @@ static int mtk_dai_tdm_cal_mclk(struct mtk_base_afe *afe, int apll; int apll_rate; + if (freq <= 0) + return -EINVAL; + apll = mt8189_get_apll_by_rate(afe, freq); apll_rate = mt8189_get_apll_rate(afe, apll); diff --git a/sound/soc/mediatek/mt8192/mt8192-afe-clk.c b/sound/soc/mediatek/mt8192/mt8192-afe-clk.c index 416aff726253..9b9a3465ddb5 100644 --- a/sound/soc/mediatek/mt8192/mt8192-afe-clk.c +++ b/sound/soc/mediatek/mt8192/mt8192-afe-clk.c @@ -87,7 +87,7 @@ static int apll1_mux_setting(struct mtk_base_afe *afe, bool enable) if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_1], ret); - goto EXIT; + return ret; } ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_1], afe_priv->clk[CLK_TOP_APLL1_CK]); @@ -95,7 +95,7 @@ static int apll1_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_1], aud_clks[CLK_TOP_APLL1_CK], ret); - goto EXIT; + goto err_disable_mux_aud_1; } /* 180.6336 / 4 = 45.1584MHz */ @@ -103,7 +103,7 @@ static int apll1_mux_setting(struct mtk_base_afe *afe, bool enable) if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_ENG1], ret); - goto EXIT; + goto err_set_parent_mux_aud_1; } ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_ENG1], afe_priv->clk[CLK_TOP_APLL1_D4]); @@ -111,31 +111,36 @@ static int apll1_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_ENG1], aud_clks[CLK_TOP_APLL1_D4], ret); - goto EXIT; + goto err_disable_mux_aud_eng1; } } else { ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_ENG1], afe_priv->clk[CLK_CLK26M]); - if (ret) { + if (ret) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_ENG1], aud_clks[CLK_CLK26M], ret); - goto EXIT; - } clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_ENG1]); ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_1], afe_priv->clk[CLK_CLK26M]); - if (ret) { + if (ret) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_1], aud_clks[CLK_CLK26M], ret); - goto EXIT; - } clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_1]); } -EXIT: + return 0; + +err_disable_mux_aud_eng1: + clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_ENG1]); +err_set_parent_mux_aud_1: + clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_1], + afe_priv->clk[CLK_CLK26M]); +err_disable_mux_aud_1: + clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_1]); + return ret; } @@ -149,7 +154,7 @@ static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_2], ret); - goto EXIT; + return ret; } ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_2], afe_priv->clk[CLK_TOP_APLL2_CK]); @@ -157,7 +162,7 @@ static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_2], aud_clks[CLK_TOP_APLL2_CK], ret); - goto EXIT; + goto err_disable_mux_aud_2; } /* 196.608 / 4 = 49.152MHz */ @@ -165,7 +170,7 @@ static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_ENG2], ret); - goto EXIT; + goto err_set_parent_mux_aud_2; } ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_ENG2], afe_priv->clk[CLK_TOP_APLL2_D4]); @@ -173,31 +178,36 @@ static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_ENG2], aud_clks[CLK_TOP_APLL2_D4], ret); - goto EXIT; + goto err_disable_mux_aud_eng2; } } else { ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_ENG2], afe_priv->clk[CLK_CLK26M]); - if (ret) { + if (ret) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_ENG2], aud_clks[CLK_CLK26M], ret); - goto EXIT; - } clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_ENG2]); ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_2], afe_priv->clk[CLK_CLK26M]); - if (ret) { + if (ret) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUD_2], aud_clks[CLK_CLK26M], ret); - goto EXIT; - } clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_2]); } -EXIT: + return 0; + +err_disable_mux_aud_eng2: + clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_ENG2]); +err_set_parent_mux_aud_2: + clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUD_2], + afe_priv->clk[CLK_CLK26M]); +err_disable_mux_aud_2: + clk_disable_unprepare(afe_priv->clk[CLK_TOP_MUX_AUD_2]); + return ret; } @@ -210,21 +220,21 @@ int mt8192_afe_enable_clock(struct mtk_base_afe *afe) if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_INFRA_SYS_AUDIO], ret); - goto EXIT; + return ret; } ret = clk_prepare_enable(afe_priv->clk[CLK_INFRA_AUDIO_26M]); if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_INFRA_AUDIO_26M], ret); - goto EXIT; + goto err_disable_infra_sys_audio; } ret = clk_prepare_enable(afe_priv->clk[CLK_MUX_AUDIO]); if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_MUX_AUDIO], ret); - goto EXIT; + goto err_disable_infra_audio_26m; } ret = clk_set_parent(afe_priv->clk[CLK_MUX_AUDIO], afe_priv->clk[CLK_CLK26M]); @@ -232,14 +242,14 @@ int mt8192_afe_enable_clock(struct mtk_base_afe *afe) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_MUX_AUDIO], aud_clks[CLK_CLK26M], ret); - goto EXIT; + goto err_disable_mux_audio; } ret = clk_prepare_enable(afe_priv->clk[CLK_MUX_AUDIOINTBUS]); if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_MUX_AUDIOINTBUS], ret); - goto EXIT; + goto err_disable_mux_audio; } ret = mt8192_set_audio_int_bus_parent(afe, CLK_CLK26M); @@ -247,7 +257,7 @@ int mt8192_afe_enable_clock(struct mtk_base_afe *afe) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_MUX_AUDIOINTBUS], aud_clks[CLK_CLK26M], ret); - goto EXIT; + goto err_disable_mux_audiointbus; } ret = clk_set_parent(afe_priv->clk[CLK_TOP_MUX_AUDIO_H], @@ -256,17 +266,27 @@ int mt8192_afe_enable_clock(struct mtk_base_afe *afe) dev_err(afe->dev, "%s clk_set_parent %s-%s fail %d\n", __func__, aud_clks[CLK_TOP_MUX_AUDIO_H], aud_clks[CLK_TOP_APLL2_CK], ret); - goto EXIT; + goto err_disable_mux_audiointbus; } ret = clk_prepare_enable(afe_priv->clk[CLK_AFE]); if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_AFE], ret); - goto EXIT; + goto err_disable_mux_audiointbus; } -EXIT: + return 0; + +err_disable_mux_audiointbus: + clk_disable_unprepare(afe_priv->clk[CLK_MUX_AUDIOINTBUS]); +err_disable_mux_audio: + clk_disable_unprepare(afe_priv->clk[CLK_MUX_AUDIO]); +err_disable_infra_audio_26m: + clk_disable_unprepare(afe_priv->clk[CLK_INFRA_AUDIO_26M]); +err_disable_infra_sys_audio: + clk_disable_unprepare(afe_priv->clk[CLK_INFRA_SYS_AUDIO]); + return ret; } @@ -288,20 +308,22 @@ int mt8192_apll1_enable(struct mtk_base_afe *afe) int ret; /* setting for APLL */ - apll1_mux_setting(afe, true); + ret = apll1_mux_setting(afe, true); + if (ret) + return ret; ret = clk_prepare_enable(afe_priv->clk[CLK_APLL22M]); if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_APLL22M], ret); - goto EXIT; + goto err_disable_mux_setting; } ret = clk_prepare_enable(afe_priv->clk[CLK_APLL1_TUNER]); if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_APLL1_TUNER], ret); - goto EXIT; + goto err_disable_apll22m; } regmap_update_bits(afe->regmap, AFE_APLL1_TUNER_CFG, @@ -312,7 +334,13 @@ int mt8192_apll1_enable(struct mtk_base_afe *afe) AFE_22M_ON_MASK_SFT, 0x1 << AFE_22M_ON_SFT); -EXIT: + return 0; + +err_disable_apll22m: + clk_disable_unprepare(afe_priv->clk[CLK_APLL22M]); +err_disable_mux_setting: + apll1_mux_setting(afe, false); + return ret; } @@ -338,20 +366,22 @@ int mt8192_apll2_enable(struct mtk_base_afe *afe) int ret; /* setting for APLL */ - apll2_mux_setting(afe, true); + ret = apll2_mux_setting(afe, true); + if (ret) + return ret; ret = clk_prepare_enable(afe_priv->clk[CLK_APLL24M]); if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_APLL24M], ret); - goto EXIT; + goto err_disable_mux_setting; } ret = clk_prepare_enable(afe_priv->clk[CLK_APLL2_TUNER]); if (ret) { dev_err(afe->dev, "%s clk_prepare_enable %s fail %d\n", __func__, aud_clks[CLK_APLL2_TUNER], ret); - goto EXIT; + goto err_disable_apll24m; } regmap_update_bits(afe->regmap, AFE_APLL2_TUNER_CFG, @@ -362,7 +392,13 @@ int mt8192_apll2_enable(struct mtk_base_afe *afe) AFE_24M_ON_MASK_SFT, 0x1 << AFE_24M_ON_SFT); -EXIT: + return 0; + +err_disable_apll24m: + clk_disable_unprepare(afe_priv->clk[CLK_APLL24M]); +err_disable_mux_setting: + apll2_mux_setting(afe, false); + return ret; } @@ -583,7 +619,7 @@ int mt8192_mck_enable(struct mtk_base_afe *afe, int mck_id, int rate) dev_err(afe->dev, "%s(), clk_set_parent %s-%s fail %d\n", __func__, aud_clks[m_sel_id], aud_clks[apll_clk_id], ret); - return ret; + goto err_disable_m_sel; } } @@ -592,17 +628,25 @@ int mt8192_mck_enable(struct mtk_base_afe *afe, int mck_id, int rate) if (ret) { dev_err(afe->dev, "%s(), clk_prepare_enable %s fail %d\n", __func__, aud_clks[div_clk_id], ret); - return ret; + goto err_disable_m_sel; } ret = clk_set_rate(afe_priv->clk[div_clk_id], rate); if (ret) { dev_err(afe->dev, "%s(), clk_set_rate %s, rate %d, fail %d\n", __func__, aud_clks[div_clk_id], rate, ret); - return ret; + goto err_disable_div_clk; } return 0; + +err_disable_div_clk: + clk_disable_unprepare(afe_priv->clk[div_clk_id]); +err_disable_m_sel: + if (m_sel_id >= 0) + clk_disable_unprepare(afe_priv->clk[m_sel_id]); + + return ret; } void mt8192_mck_disable(struct mtk_base_afe *afe, int mck_id) @@ -628,13 +672,10 @@ int mt8192_init_clock(struct mtk_base_afe *afe) return -ENOMEM; for (i = 0; i < CLK_NUM; i++) { - afe_priv->clk[i] = devm_clk_get(afe->dev, aud_clks[i]); - if (IS_ERR(afe_priv->clk[i])) { - dev_warn(afe->dev, "%s devm_clk_get %s fail, ret %ld\n", - __func__, - aud_clks[i], PTR_ERR(afe_priv->clk[i])); - afe_priv->clk[i] = NULL; - } + afe_priv->clk[i] = devm_clk_get_optional(afe->dev, aud_clks[i]); + if (IS_ERR(afe_priv->clk[i])) + return dev_err_probe(afe->dev, PTR_ERR(afe_priv->clk[i]), + "failed to get clock %s\n", aud_clks[i]); } afe_priv->apmixedsys = syscon_regmap_lookup_by_phandle(of_node, diff --git a/sound/soc/mediatek/mt8192/mt8192-afe-gpio.c b/sound/soc/mediatek/mt8192/mt8192-afe-gpio.c index b993ca2dbd7c..f2d5e61fbb63 100644 --- a/sound/soc/mediatek/mt8192/mt8192-afe-gpio.c +++ b/sound/soc/mediatek/mt8192/mt8192-afe-gpio.c @@ -151,13 +151,17 @@ int mt8192_afe_gpio_init(struct device *dev) } } - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_CLK_MOSI_ON); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_CLK_MOSI_ON); + if (ret) + return ret; /* gpio status init */ - mt8192_afe_gpio_request(dev, false, MT8192_DAI_ADDA, 0); - mt8192_afe_gpio_request(dev, false, MT8192_DAI_ADDA, 1); + ret = mt8192_afe_gpio_request(dev, false, MT8192_DAI_ADDA, 0); + if (ret) + return ret; + ret = mt8192_afe_gpio_request(dev, false, MT8192_DAI_ADDA, 1); - return 0; + return ret; } EXPORT_SYMBOL(mt8192_afe_gpio_init); @@ -208,98 +212,104 @@ static int mt8192_afe_gpio_adda_ch34_ul(struct device *dev, bool enable) int mt8192_afe_gpio_request(struct device *dev, bool enable, int dai, int uplink) { + int ret; + guard(mutex)(&gpio_request_mutex); switch (dai) { case MT8192_DAI_ADDA: if (uplink) - mt8192_afe_gpio_adda_ul(dev, enable); + ret = mt8192_afe_gpio_adda_ul(dev, enable); else - mt8192_afe_gpio_adda_dl(dev, enable); + ret = mt8192_afe_gpio_adda_dl(dev, enable); break; case MT8192_DAI_ADDA_CH34: if (uplink) - mt8192_afe_gpio_adda_ch34_ul(dev, enable); + ret = mt8192_afe_gpio_adda_ch34_ul(dev, enable); else - mt8192_afe_gpio_adda_ch34_dl(dev, enable); + ret = mt8192_afe_gpio_adda_ch34_dl(dev, enable); break; case MT8192_DAI_I2S_0: if (enable) - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S0_ON); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S0_ON); else - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S0_OFF); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S0_OFF); break; case MT8192_DAI_I2S_1: if (enable) - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S1_ON); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S1_ON); else - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S1_OFF); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S1_OFF); break; case MT8192_DAI_I2S_2: if (enable) - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S2_ON); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S2_ON); else - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S2_OFF); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S2_OFF); break; case MT8192_DAI_I2S_3: if (enable) - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S3_ON); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S3_ON); else - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S3_OFF); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S3_OFF); break; case MT8192_DAI_I2S_5: if (enable) - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S5_ON); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S5_ON); else - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S5_OFF); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S5_OFF); break; case MT8192_DAI_I2S_6: if (enable) - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S6_ON); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S6_ON); else - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S6_OFF); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S6_OFF); break; case MT8192_DAI_I2S_7: if (enable) - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S7_ON); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S7_ON); else - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S7_OFF); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S7_OFF); break; case MT8192_DAI_I2S_8: if (enable) - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S8_ON); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S8_ON); else - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S8_OFF); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S8_OFF); break; case MT8192_DAI_I2S_9: if (enable) - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S9_ON); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S9_ON); else - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S9_OFF); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_I2S9_OFF); break; case MT8192_DAI_TDM: if (enable) - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_TDM_ON); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_TDM_ON); else - mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_TDM_OFF); + ret = mt8192_afe_gpio_select(dev, MT8192_AFE_GPIO_TDM_OFF); break; case MT8192_DAI_VOW: if (enable) { - mt8192_afe_gpio_select(dev, - MT8192_AFE_GPIO_VOW_CLK_ON); - mt8192_afe_gpio_select(dev, - MT8192_AFE_GPIO_VOW_DAT_ON); + ret = mt8192_afe_gpio_select(dev, + MT8192_AFE_GPIO_VOW_CLK_ON); + if (ret) + break; + ret = mt8192_afe_gpio_select(dev, + MT8192_AFE_GPIO_VOW_DAT_ON); } else { - mt8192_afe_gpio_select(dev, - MT8192_AFE_GPIO_VOW_CLK_OFF); - mt8192_afe_gpio_select(dev, - MT8192_AFE_GPIO_VOW_DAT_OFF); + ret = mt8192_afe_gpio_select(dev, + MT8192_AFE_GPIO_VOW_CLK_OFF); + if (ret) + break; + ret = mt8192_afe_gpio_select(dev, + MT8192_AFE_GPIO_VOW_DAT_OFF); } break; default: dev_warn(dev, "%s(), invalid dai %d\n", __func__, dai); - return -EINVAL; + ret = -EINVAL; } - return 0; + return ret; } EXPORT_SYMBOL(mt8192_afe_gpio_request); diff --git a/sound/soc/mediatek/mt8192/mt8192-afe-pcm.c b/sound/soc/mediatek/mt8192/mt8192-afe-pcm.c index db0ae44a86af..5e633e9573a3 100644 --- a/sound/soc/mediatek/mt8192/mt8192-afe-pcm.c +++ b/sound/soc/mediatek/mt8192/mt8192-afe-pcm.c @@ -2104,7 +2104,11 @@ static int mt8192_afe_runtime_resume(struct device *dev) goto skip_regmap; regcache_cache_only(afe->regmap, false); - regcache_sync(afe->regmap); + ret = regcache_sync(afe->regmap); + if (ret) { + regcache_cache_only(afe->regmap, true); + mt8192_afe_disable_clock(afe); + } /* enable audio sys DCM for power saving */ regmap_update_bits(afe_priv->infracfg, diff --git a/sound/soc/mediatek/mt8192/mt8192-dai-adda.c b/sound/soc/mediatek/mt8192/mt8192-dai-adda.c index f8cb84621d38..c5c726a6e423 100644 --- a/sound/soc/mediatek/mt8192/mt8192-dai-adda.c +++ b/sound/soc/mediatek/mt8192/mt8192-dai-adda.c @@ -218,10 +218,13 @@ static int mtk_adda_ul_event(struct snd_soc_dapm_widget *w, struct mtk_base_afe *afe = snd_soc_component_get_drvdata(cmpnt); struct mt8192_afe_private *afe_priv = afe->platform_priv; int mtkaif_dmic = afe_priv->mtkaif_dmic; + int ret; switch (event) { case SND_SOC_DAPM_PRE_PMU: - mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA, 1); + ret = mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA, 1); + if (ret) + return ret; /* update setting to dmic */ if (mtkaif_dmic) { @@ -239,7 +242,9 @@ static int mtk_adda_ul_event(struct snd_soc_dapm_widget *w, case SND_SOC_DAPM_POST_PMD: /* should delayed 1/fs(smallest is 8k) = 125us before afe off */ usleep_range(125, 135); - mt8192_afe_gpio_request(afe->dev, false, MT8192_DAI_ADDA, 1); + ret = mt8192_afe_gpio_request(afe->dev, false, MT8192_DAI_ADDA, 1); + if (ret) + return ret; break; default: break; @@ -257,11 +262,14 @@ static int mtk_adda_ch34_ul_event(struct snd_soc_dapm_widget *w, struct mt8192_afe_private *afe_priv = afe->platform_priv; int mtkaif_dmic = afe_priv->mtkaif_dmic_ch34; int mtkaif_adda6_only = afe_priv->mtkaif_adda6_only; + int ret; switch (event) { case SND_SOC_DAPM_PRE_PMU: - mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA_CH34, - 1); + ret = mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA_CH34, + 1); + if (ret) + return ret; /* update setting to dmic */ if (mtkaif_dmic) { @@ -291,8 +299,10 @@ static int mtk_adda_ch34_ul_event(struct snd_soc_dapm_widget *w, case SND_SOC_DAPM_POST_PMD: /* should delayed 1/fs(smallest is 8k) = 125us before afe off */ usleep_range(125, 135); - mt8192_afe_gpio_request(afe->dev, false, MT8192_DAI_ADDA_CH34, - 1); + ret = mt8192_afe_gpio_request(afe->dev, false, MT8192_DAI_ADDA_CH34, + 1); + if (ret) + return ret; /* reset dmic */ afe_priv->mtkaif_dmic_ch34 = 0; @@ -446,15 +456,20 @@ static int mtk_adda_dl_event(struct snd_soc_dapm_widget *w, { struct snd_soc_component *cmpnt = snd_soc_dapm_to_component(w->dapm); struct mtk_base_afe *afe = snd_soc_component_get_drvdata(cmpnt); + int ret; switch (event) { case SND_SOC_DAPM_PRE_PMU: - mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA, 0); + ret = mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA, 0); + if (ret) + return ret; break; case SND_SOC_DAPM_POST_PMD: /* should delayed 1/fs(smallest is 8k) = 125us before afe off */ usleep_range(125, 135); - mt8192_afe_gpio_request(afe->dev, false, MT8192_DAI_ADDA, 0); + ret = mt8192_afe_gpio_request(afe->dev, false, MT8192_DAI_ADDA, 0); + if (ret) + return ret; break; default: break; @@ -469,17 +484,22 @@ static int mtk_adda_ch34_dl_event(struct snd_soc_dapm_widget *w, { struct snd_soc_component *cmpnt = snd_soc_dapm_to_component(w->dapm); struct mtk_base_afe *afe = snd_soc_component_get_drvdata(cmpnt); + int ret; switch (event) { case SND_SOC_DAPM_PRE_PMU: - mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA_CH34, - 0); + ret = mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA_CH34, + 0); + if (ret) + return ret; break; case SND_SOC_DAPM_POST_PMD: /* should delayed 1/fs(smallest is 8k) = 125us before afe off */ usleep_range(125, 135); - mt8192_afe_gpio_request(afe->dev, false, MT8192_DAI_ADDA_CH34, - 0); + ret = mt8192_afe_gpio_request(afe->dev, false, MT8192_DAI_ADDA_CH34, + 0); + if (ret) + return ret; break; default: break; diff --git a/sound/soc/mediatek/mt8192/mt8192-dai-i2s.c b/sound/soc/mediatek/mt8192/mt8192-dai-i2s.c index 1632fc94776d..5608b534af0d 100644 --- a/sound/soc/mediatek/mt8192/mt8192-dai-i2s.c +++ b/sound/soc/mediatek/mt8192/mt8192-dai-i2s.c @@ -586,6 +586,7 @@ static int mtk_i2s_en_event(struct snd_soc_dapm_widget *w, struct snd_soc_component *cmpnt = snd_soc_dapm_to_component(w->dapm); struct mtk_base_afe *afe = snd_soc_component_get_drvdata(cmpnt); struct mtk_afe_i2s_priv *i2s_priv; + int ret; i2s_priv = get_i2s_priv_by_name(afe, w->name); @@ -599,16 +600,17 @@ static int mtk_i2s_en_event(struct snd_soc_dapm_widget *w, switch (event) { case SND_SOC_DAPM_PRE_PMU: - mt8192_afe_gpio_request(afe->dev, true, i2s_priv->id, 0); + ret = mt8192_afe_gpio_request(afe->dev, true, i2s_priv->id, 0); break; case SND_SOC_DAPM_POST_PMD: - mt8192_afe_gpio_request(afe->dev, false, i2s_priv->id, 0); + ret = mt8192_afe_gpio_request(afe->dev, false, i2s_priv->id, 0); break; default: + ret = 0; break; } - return 0; + return ret; } static int mtk_apll_event(struct snd_soc_dapm_widget *w, @@ -617,6 +619,7 @@ static int mtk_apll_event(struct snd_soc_dapm_widget *w, { struct snd_soc_component *cmpnt = snd_soc_dapm_to_component(w->dapm); struct mtk_base_afe *afe = snd_soc_component_get_drvdata(cmpnt); + int ret; dev_dbg(cmpnt->dev, "%s(), name %s, event 0x%x\n", __func__, w->name, event); @@ -624,9 +627,11 @@ static int mtk_apll_event(struct snd_soc_dapm_widget *w, switch (event) { case SND_SOC_DAPM_PRE_PMU: if (snd_soc_dapm_widget_name_cmp(w, APLL1_W_NAME) == 0) - mt8192_apll1_enable(afe); + ret = mt8192_apll1_enable(afe); else - mt8192_apll2_enable(afe); + ret = mt8192_apll2_enable(afe); + if (ret) + return ret; break; case SND_SOC_DAPM_POST_PMD: if (snd_soc_dapm_widget_name_cmp(w, APLL1_W_NAME) == 0) @@ -704,6 +709,7 @@ static int mtk_mclk_en_event(struct snd_soc_dapm_widget *w, struct snd_soc_component *cmpnt = snd_soc_dapm_to_component(w->dapm); struct mtk_base_afe *afe = snd_soc_component_get_drvdata(cmpnt); struct mtk_afe_i2s_priv *i2s_priv; + int ret; dev_dbg(cmpnt->dev, "%s(), name %s, event 0x%x\n", __func__, w->name, event); @@ -716,7 +722,9 @@ static int mtk_mclk_en_event(struct snd_soc_dapm_widget *w, switch (event) { case SND_SOC_DAPM_PRE_PMU: - mt8192_mck_enable(afe, i2s_priv->mclk_id, i2s_priv->mclk_rate); + ret = mt8192_mck_enable(afe, i2s_priv->mclk_id, i2s_priv->mclk_rate); + if (ret) + return ret; break; case SND_SOC_DAPM_POST_PMD: i2s_priv->mclk_rate = 0; diff --git a/sound/soc/mediatek/mt8192/mt8192-dai-tdm.c b/sound/soc/mediatek/mt8192/mt8192-dai-tdm.c index 49440db370af..36fa0f32ed1c 100644 --- a/sound/soc/mediatek/mt8192/mt8192-dai-tdm.c +++ b/sound/soc/mediatek/mt8192/mt8192-dai-tdm.c @@ -250,6 +250,7 @@ static int mtk_tdm_en_event(struct snd_soc_dapm_widget *w, struct mt8192_afe_private *afe_priv = afe->platform_priv; int dai_id = get_tdm_id_by_name(w->name); struct mtk_afe_tdm_priv *tdm_priv = afe_priv->dai_priv[dai_id]; + int ret; if (!tdm_priv) { dev_warn(afe->dev, "%s(), tdm_priv == NULL", __func__); @@ -261,16 +262,17 @@ static int mtk_tdm_en_event(struct snd_soc_dapm_widget *w, switch (event) { case SND_SOC_DAPM_PRE_PMU: - mt8192_afe_gpio_request(afe->dev, true, tdm_priv->id, 0); + ret = mt8192_afe_gpio_request(afe->dev, true, tdm_priv->id, 0); break; case SND_SOC_DAPM_POST_PMD: - mt8192_afe_gpio_request(afe->dev, false, tdm_priv->id, 0); + ret = mt8192_afe_gpio_request(afe->dev, false, tdm_priv->id, 0); break; default: + ret = 0; break; } - return 0; + return ret; } static int mtk_tdm_bck_en_event(struct snd_soc_dapm_widget *w, @@ -282,6 +284,7 @@ static int mtk_tdm_bck_en_event(struct snd_soc_dapm_widget *w, struct mt8192_afe_private *afe_priv = afe->platform_priv; int dai_id = get_tdm_id_by_name(w->name); struct mtk_afe_tdm_priv *tdm_priv = afe_priv->dai_priv[dai_id]; + int ret; if (!tdm_priv) { dev_warn(afe->dev, "%s(), tdm_priv == NULL", __func__); @@ -293,7 +296,9 @@ static int mtk_tdm_bck_en_event(struct snd_soc_dapm_widget *w, switch (event) { case SND_SOC_DAPM_PRE_PMU: - mt8192_mck_enable(afe, tdm_priv->bck_id, tdm_priv->bck_rate); + ret = mt8192_mck_enable(afe, tdm_priv->bck_id, tdm_priv->bck_rate); + if (ret) + return ret; break; case SND_SOC_DAPM_POST_PMD: mt8192_mck_disable(afe, tdm_priv->bck_id); @@ -314,6 +319,7 @@ static int mtk_tdm_mck_en_event(struct snd_soc_dapm_widget *w, struct mt8192_afe_private *afe_priv = afe->platform_priv; int dai_id = get_tdm_id_by_name(w->name); struct mtk_afe_tdm_priv *tdm_priv = afe_priv->dai_priv[dai_id]; + int ret; if (!tdm_priv) { dev_warn(afe->dev, "%s(), tdm_priv == NULL", __func__); @@ -325,7 +331,9 @@ static int mtk_tdm_mck_en_event(struct snd_soc_dapm_widget *w, switch (event) { case SND_SOC_DAPM_PRE_PMU: - mt8192_mck_enable(afe, tdm_priv->mclk_id, tdm_priv->mclk_rate); + ret = mt8192_mck_enable(afe, tdm_priv->mclk_id, tdm_priv->mclk_rate); + if (ret) + return ret; break; case SND_SOC_DAPM_POST_PMD: tdm_priv->mclk_rate = 0; diff --git a/sound/soc/mediatek/mt8192/mt8192-mt6359-rt1015-rt5682.c b/sound/soc/mediatek/mt8192/mt8192-mt6359-rt1015-rt5682.c index c86348691641..b010726e9b57 100644 --- a/sound/soc/mediatek/mt8192/mt8192-mt6359-rt1015-rt5682.c +++ b/sound/soc/mediatek/mt8192/mt8192-mt6359-rt1015-rt5682.c @@ -163,12 +163,23 @@ static int mt8192_mt6359_mtkaif_calibration(struct snd_soc_pcm_runtime *rtd) int chosen_phase_1, chosen_phase_2, chosen_phase_3; int counter; int mtkaif_calib_ok; + int ret = 0; - pm_runtime_get_sync(afe->dev); - mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA, 1); - mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA, 0); - mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA_CH34, 1); - mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA_CH34, 0); + ret = pm_runtime_resume_and_get(afe->dev); + if (ret < 0) + return ret; + ret = mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA, 1); + if (ret) + goto err_pm_put; + ret = mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA, 0); + if (ret) + goto err_disable_adda_1; + ret = mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA_CH34, 1); + if (ret) + goto err_disable_adda_0; + ret = mt8192_afe_gpio_request(afe->dev, true, MT8192_DAI_ADDA_CH34, 0); + if (ret) + goto err_disable_adda_ch34_1; mt6359_mtkaif_calibration_enable(cmpnt_codec); @@ -289,10 +300,14 @@ static int mt8192_mt6359_mtkaif_calibration(struct snd_soc_pcm_runtime *rtd) mt6359_mtkaif_calibration_disable(cmpnt_codec); - mt8192_afe_gpio_request(afe->dev, false, MT8192_DAI_ADDA, 1); - mt8192_afe_gpio_request(afe->dev, false, MT8192_DAI_ADDA, 0); - mt8192_afe_gpio_request(afe->dev, false, MT8192_DAI_ADDA_CH34, 1); mt8192_afe_gpio_request(afe->dev, false, MT8192_DAI_ADDA_CH34, 0); +err_disable_adda_ch34_1: + mt8192_afe_gpio_request(afe->dev, false, MT8192_DAI_ADDA_CH34, 1); +err_disable_adda_0: + mt8192_afe_gpio_request(afe->dev, false, MT8192_DAI_ADDA, 0); +err_disable_adda_1: + mt8192_afe_gpio_request(afe->dev, false, MT8192_DAI_ADDA, 1); +err_pm_put: pm_runtime_put(afe->dev); dev_dbg(afe->dev, "%s(), mtkaif_chosen_phase[0/1/2]:%d/%d/%d\n", @@ -301,7 +316,7 @@ static int mt8192_mt6359_mtkaif_calibration(struct snd_soc_pcm_runtime *rtd) afe_priv->mtkaif_chosen_phase[1], afe_priv->mtkaif_chosen_phase[2]); - return 0; + return ret; } static int mt8192_mt6359_init(struct snd_soc_pcm_runtime *rtd) @@ -319,9 +334,7 @@ static int mt8192_mt6359_init(struct snd_soc_pcm_runtime *rtd) afe_priv->mtkaif_protocol = MTKAIF_PROTOCOL_2_CLK_P2; /* mtkaif calibration */ - mt8192_mt6359_mtkaif_calibration(rtd); - - return 0; + return mt8192_mt6359_mtkaif_calibration(rtd); } static int mt8192_rt5682_init(struct snd_soc_pcm_runtime *rtd) diff --git a/sound/soc/mediatek/mt8195/mt8195-afe-clk.c b/sound/soc/mediatek/mt8195/mt8195-afe-clk.c index 618d8400913a..c6990a377af4 100644 --- a/sound/soc/mediatek/mt8195/mt8195-afe-clk.c +++ b/sound/soc/mediatek/mt8195/mt8195-afe-clk.c @@ -241,21 +241,35 @@ static int mt8195_afe_enable_tuner_clk(struct mtk_base_afe *afe, unsigned int id) { struct mt8195_afe_private *afe_priv = afe->platform_priv; + int ret; switch (id) { case MT8195_AUD_PLL1: - mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL]); - mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL1_TUNER]); + ret = mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL]); + if (ret) + return ret; + ret = mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL1_TUNER]); + if (ret) { + mt8195_afe_disable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL]); + return ret; + } break; case MT8195_AUD_PLL2: - mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL2]); - mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL2_TUNER]); + ret = mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL2]); + if (ret) + return ret; + ret = mt8195_afe_enable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL2_TUNER]); + if (ret) { + mt8195_afe_disable_clk(afe, afe_priv->clk[MT8195_CLK_AUD_APLL2]); + return ret; + } break; default: + ret = 0; break; } - return 0; + return ret; } static int mt8195_afe_disable_tuner_clk(struct mtk_base_afe *afe, @@ -588,7 +602,7 @@ static int mt8195_afe_disable_top_cg(struct mtk_base_afe *afe, unsigned int cg_t int mt8195_afe_enable_reg_rw_clk(struct mtk_base_afe *afe) { struct mt8195_afe_private *afe_priv = afe->platform_priv; - int i; + int i, ret; static const unsigned int clk_array[] = { MT8195_CLK_SCP_ADSP_AUDIODSP, /* bus clock for infra */ MT8195_CLK_TOP_AUDIO_H_SEL, /* clock for ADSP bus */ @@ -600,10 +614,19 @@ int mt8195_afe_enable_reg_rw_clk(struct mtk_base_afe *afe) MT8195_CLK_AUD_A1SYS, /* AFE HW clock */ }; - for (i = 0; i < ARRAY_SIZE(clk_array); i++) - mt8195_afe_enable_clk(afe, afe_priv->clk[clk_array[i]]); + for (i = 0; i < ARRAY_SIZE(clk_array); i++) { + ret = mt8195_afe_enable_clk(afe, afe_priv->clk[clk_array[i]]); + if (ret) + goto err_disable_clk; + } return 0; + +err_disable_clk: + while (--i >= 0) + mt8195_afe_disable_clk(afe, afe_priv->clk[clk_array[i]]); + + return ret; } int mt8195_afe_disable_reg_rw_clk(struct mtk_base_afe *afe) @@ -642,7 +665,7 @@ static int mt8195_afe_disable_afe_on(struct mtk_base_afe *afe) static int mt8195_afe_enable_timing_sys(struct mtk_base_afe *afe) { struct mt8195_afe_private *afe_priv = afe->platform_priv; - int i; + int i, ret; static const unsigned int clk_array[] = { MT8195_CLK_AUD_A1SYS, MT8195_CLK_AUD_A2SYS, @@ -653,13 +676,22 @@ static int mt8195_afe_enable_timing_sys(struct mtk_base_afe *afe) MT8195_TOP_CG_26M_TIMING, }; - for (i = 0; i < ARRAY_SIZE(clk_array); i++) - mt8195_afe_enable_clk(afe, afe_priv->clk[clk_array[i]]); + for (i = 0; i < ARRAY_SIZE(clk_array); i++) { + ret = mt8195_afe_enable_clk(afe, afe_priv->clk[clk_array[i]]); + if (ret) + goto err_disable_clk; + } for (i = 0; i < ARRAY_SIZE(cg_array); i++) mt8195_afe_enable_top_cg(afe, cg_array[i]); return 0; + +err_disable_clk: + while (--i >= 0) + mt8195_afe_disable_clk(afe, afe_priv->clk[clk_array[i]]); + + return ret; } static int mt8195_afe_disable_timing_sys(struct mtk_base_afe *afe) @@ -687,14 +719,31 @@ static int mt8195_afe_disable_timing_sys(struct mtk_base_afe *afe) int mt8195_afe_enable_main_clock(struct mtk_base_afe *afe) { - mt8195_afe_enable_timing_sys(afe); + int ret; + + ret = mt8195_afe_enable_timing_sys(afe); + if (ret) + return ret; mt8195_afe_enable_afe_on(afe); - mt8195_afe_enable_apll_tuner(afe, MT8195_AUD_PLL1); - mt8195_afe_enable_apll_tuner(afe, MT8195_AUD_PLL2); + ret = mt8195_afe_enable_apll_tuner(afe, MT8195_AUD_PLL1); + if (ret) + goto err_disable_afe_on; + + ret = mt8195_afe_enable_apll_tuner(afe, MT8195_AUD_PLL2); + if (ret) + goto err_disable_apll1_tuner; return 0; + +err_disable_apll1_tuner: + mt8195_afe_disable_apll_tuner(afe, MT8195_AUD_PLL1); +err_disable_afe_on: + mt8195_afe_disable_afe_on(afe); + mt8195_afe_disable_timing_sys(afe); + + return ret; } int mt8195_afe_disable_main_clock(struct mtk_base_afe *afe) diff --git a/sound/soc/mediatek/mt8195/mt8195-afe-pcm.c b/sound/soc/mediatek/mt8195/mt8195-afe-pcm.c index bc0a63457cd7..8e38c50a8bd4 100644 --- a/sound/soc/mediatek/mt8195/mt8195-afe-pcm.c +++ b/sound/soc/mediatek/mt8195/mt8195-afe-pcm.c @@ -286,15 +286,23 @@ mt8195_afe_paired_memif_clk_prepare(struct snd_pcm_substream *substream, struct mt8195_afe_private *afe_priv = afe->platform_priv; int id = snd_soc_rtd_to_cpu(rtd, 0)->id; int clk_id; + int ret; if (id != MT8195_AFE_MEMIF_DL8 && id != MT8195_AFE_MEMIF_DL10) return 0; if (enable) { clk_id = MT8195_CLK_AUD_MEMIF_DL10; - mt8195_afe_prepare_clk(afe, afe_priv->clk[clk_id]); + ret = mt8195_afe_prepare_clk(afe, afe_priv->clk[clk_id]); + if (ret) + return ret; clk_id = MT8195_CLK_AUD_MEMIF_DL8; - mt8195_afe_prepare_clk(afe, afe_priv->clk[clk_id]); + ret = mt8195_afe_prepare_clk(afe, afe_priv->clk[clk_id]); + if (ret) { + clk_id = MT8195_CLK_AUD_MEMIF_DL10; + mt8195_afe_unprepare_clk(afe, afe_priv->clk[clk_id]); + return ret; + } } else { clk_id = MT8195_CLK_AUD_MEMIF_DL8; mt8195_afe_unprepare_clk(afe, afe_priv->clk[clk_id]); @@ -315,6 +323,7 @@ mt8195_afe_paired_memif_clk_enable(struct snd_pcm_substream *substream, struct mt8195_afe_private *afe_priv = afe->platform_priv; int id = snd_soc_rtd_to_cpu(rtd, 0)->id; int clk_id; + int ret; if (id != MT8195_AFE_MEMIF_DL8 && id != MT8195_AFE_MEMIF_DL10) return 0; @@ -322,11 +331,18 @@ mt8195_afe_paired_memif_clk_enable(struct snd_pcm_substream *substream, if (enable) { /* DL8_DL10_MEM */ clk_id = MT8195_CLK_AUD_MEMIF_DL10; - mt8195_afe_enable_clk_atomic(afe, afe_priv->clk[clk_id]); + ret = mt8195_afe_enable_clk_atomic(afe, afe_priv->clk[clk_id]); + if (ret) + return ret; udelay(1); /* DL8_DL10_AGENT */ clk_id = MT8195_CLK_AUD_MEMIF_DL8; - mt8195_afe_enable_clk_atomic(afe, afe_priv->clk[clk_id]); + ret = mt8195_afe_enable_clk_atomic(afe, afe_priv->clk[clk_id]); + if (ret) { + clk_id = MT8195_CLK_AUD_MEMIF_DL10; + mt8195_afe_disable_clk_atomic(afe, afe_priv->clk[clk_id]); + return ret; + } } else { /* DL8_DL10_AGENT */ clk_id = MT8195_CLK_AUD_MEMIF_DL8; @@ -348,24 +364,38 @@ static int mt8195_afe_fe_startup(struct snd_pcm_substream *substream, int id = snd_soc_rtd_to_cpu(rtd, 0)->id; int ret = 0; - mt8195_afe_paired_memif_clk_prepare(substream, dai, 1); + ret = mt8195_afe_paired_memif_clk_prepare(substream, dai, 1); + if (ret) + return ret; ret = mtk_afe_fe_startup(substream, dai); + if (ret < 0) + goto err_clk_unprepare; + + ret = snd_pcm_hw_constraint_step(runtime, 0, + SNDRV_PCM_HW_PARAM_BUFFER_BYTES, + MT8195_MEMIF_BUFFER_BYTES_ALIGN); + if (ret) + goto err_fe_shutdow; + + if (id == MT8195_AFE_MEMIF_DL7) { + ret = snd_pcm_hw_constraint_minmax(runtime, + SNDRV_PCM_HW_PARAM_PERIOD_SIZE, + 1, + MT8195_MEMIF_DL7_MAX_PERIOD_SIZE); + if (ret < 0) { + dev_dbg(afe->dev, "hw_constraint_minmax failed\n"); + goto err_fe_shutdow; + } + } - snd_pcm_hw_constraint_step(runtime, 0, - SNDRV_PCM_HW_PARAM_BUFFER_BYTES, - MT8195_MEMIF_BUFFER_BYTES_ALIGN); + return 0; - if (id != MT8195_AFE_MEMIF_DL7) - goto out; +err_fe_shutdow: + mtk_afe_fe_shutdown(substream, dai); +err_clk_unprepare: + mt8195_afe_paired_memif_clk_prepare(substream, dai, 0); - ret = snd_pcm_hw_constraint_minmax(runtime, - SNDRV_PCM_HW_PARAM_PERIOD_SIZE, - 1, - MT8195_MEMIF_DL7_MAX_PERIOD_SIZE); - if (ret < 0) - dev_dbg(afe->dev, "hw_constraint_minmax failed\n"); -out: return ret; } @@ -436,7 +466,14 @@ static int mt8195_afe_fe_trigger(struct snd_pcm_substream *substream, int cmd, switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: - mt8195_afe_paired_memif_clk_enable(substream, dai, 1); + if (ret) + break; + + ret = mt8195_afe_paired_memif_clk_enable(substream, dai, 1); + if (ret) { + mtk_afe_fe_trigger(substream, SNDRV_PCM_TRIGGER_STOP, dai); + mt8195_afe_enable_cm(afe, cm, false); + } break; case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: @@ -2928,18 +2965,31 @@ static int mt8195_afe_runtime_resume(struct device *dev) { struct mtk_base_afe *afe = dev_get_drvdata(dev); struct mt8195_afe_private *afe_priv = afe->platform_priv; + int ret; - mt8195_afe_enable_reg_rw_clk(afe); + ret = mt8195_afe_enable_reg_rw_clk(afe); + if (ret) + return ret; if (!afe->regmap || afe_priv->pm_runtime_bypass_reg_ctl) - goto skip_regmap; + return 0; regcache_cache_only(afe->regmap, false); - regcache_sync(afe->regmap); + ret = regcache_sync(afe->regmap); + if (ret) + goto err_restore_cache; + + ret = mt8195_afe_enable_main_clock(afe); + if (ret) + goto err_restore_cache; - mt8195_afe_enable_main_clock(afe); -skip_regmap: return 0; + +err_restore_cache: + regcache_cache_only(afe->regmap, true); + mt8195_afe_disable_reg_rw_clk(afe); + + return ret; } static int init_memif_priv_data(struct mtk_base_afe *afe) @@ -3082,7 +3132,7 @@ static int mt8195_afe_pcm_dev_probe(struct platform_device *pdev) /* request irq */ irq_id = platform_get_irq(pdev, 0); if (irq_id < 0) - return -ENXIO; + return irq_id; ret = devm_request_irq(dev, irq_id, mt8195_afe_irq_handler, IRQF_TRIGGER_NONE, "asys-isr", (void *)afe); diff --git a/sound/soc/mediatek/mt8195/mt8195-dai-etdm.c b/sound/soc/mediatek/mt8195/mt8195-dai-etdm.c index 1a20adb2cbf5..8fa830a57502 100644 --- a/sound/soc/mediatek/mt8195/mt8195-dai-etdm.c +++ b/sound/soc/mediatek/mt8195/mt8195-dai-etdm.c @@ -1549,9 +1549,7 @@ static int mtk_dai_etdm_enable_mclk(struct mtk_base_afe *afe, int dai_id) if (clkdiv_id < 0) return -EINVAL; - mt8195_afe_enable_clk(afe, afe_priv->clk[clkdiv_id]); - - return 0; + return mt8195_afe_enable_clk(afe, afe_priv->clk[clkdiv_id]); } static int mtk_dai_etdm_disable_mclk(struct mtk_base_afe *afe, int dai_id) @@ -1577,36 +1575,66 @@ static int mtk_dai_etdm_startup(struct snd_pcm_substream *substream, int cg_id; int mst_dai_id; int slv_dai_id; - int i; + int i, ret; if (is_cowork_mode(dai)) { mst_dai_id = get_etdm_cowork_master_id(dai); if (!mt8195_afe_etdm_is_valid(mst_dai_id)) return -EINVAL; - mtk_dai_etdm_enable_mclk(afe, mst_dai_id); + ret = mtk_dai_etdm_enable_mclk(afe, mst_dai_id); + if (ret) + return ret; cg_id = mtk_dai_etdm_get_cg_id_by_dai_id(mst_dai_id); - if (cg_id >= 0) - mt8195_afe_enable_clk(afe, afe_priv->clk[cg_id]); + if (cg_id >= 0) { + ret = mt8195_afe_enable_clk(afe, afe_priv->clk[cg_id]); + if (ret) + goto err_disable_mclk; + } mst_etdm_data = afe_priv->dai_priv[mst_dai_id]; for (i = 0; i < mst_etdm_data->cowork_slv_count; i++) { slv_dai_id = mst_etdm_data->cowork_slv_id[i]; cg_id = mtk_dai_etdm_get_cg_id_by_dai_id(slv_dai_id); - if (cg_id >= 0) - mt8195_afe_enable_clk(afe, - afe_priv->clk[cg_id]); + if (cg_id >= 0) { + ret = mt8195_afe_enable_clk(afe, + afe_priv->clk[cg_id]); + if (ret) + goto err_disable_slv_clk; + } } } else { - mtk_dai_etdm_enable_mclk(afe, dai->id); + ret = mtk_dai_etdm_enable_mclk(afe, dai->id); + if (ret) + return ret; cg_id = mtk_dai_etdm_get_cg_id_by_dai_id(dai->id); - if (cg_id >= 0) - mt8195_afe_enable_clk(afe, afe_priv->clk[cg_id]); + if (cg_id >= 0) { + ret = mt8195_afe_enable_clk(afe, afe_priv->clk[cg_id]); + if (ret) + goto err_disable_mclk; + } } return 0; + +err_disable_slv_clk: + while (--i >= 0) { + slv_dai_id = mst_etdm_data->cowork_slv_id[i]; + cg_id = mtk_dai_etdm_get_cg_id_by_dai_id(slv_dai_id); + if (cg_id >= 0) + mt8195_afe_disable_clk(afe, afe_priv->clk[cg_id]); + } + + cg_id = mtk_dai_etdm_get_cg_id_by_dai_id(mst_dai_id); + if (cg_id >= 0) + mt8195_afe_disable_clk(afe, afe_priv->clk[cg_id]); + +err_disable_mclk: + mtk_dai_etdm_disable_mclk(afe, is_cowork_mode(dai) ? mst_dai_id : dai->id); + + return ret; } static void mtk_dai_etdm_shutdown(struct snd_pcm_substream *substream, @@ -2293,13 +2321,25 @@ static int mtk_dai_hdmitx_dptx_startup(struct snd_pcm_substream *substream, struct mtk_base_afe *afe = snd_soc_dai_get_drvdata(dai); struct mt8195_afe_private *afe_priv = afe->platform_priv; int cg_id = mtk_dai_etdm_get_cg_id_by_dai_id(dai->id); + int ret; - if (cg_id >= 0) - mt8195_afe_enable_clk(afe, afe_priv->clk[cg_id]); + if (cg_id >= 0) { + ret = mt8195_afe_enable_clk(afe, afe_priv->clk[cg_id]); + if (ret) + return ret; + } - mtk_dai_etdm_enable_mclk(afe, dai->id); + ret = mtk_dai_etdm_enable_mclk(afe, dai->id); + if (ret) + goto err_disable_cg_clk; return 0; + +err_disable_cg_clk: + if (cg_id >= 0) + mt8195_afe_disable_clk(afe, afe_priv->clk[cg_id]); + + return ret; } static void mtk_dai_hdmitx_dptx_shutdown(struct snd_pcm_substream *substream, @@ -2463,6 +2503,7 @@ static int mtk_dai_etdm_probe(struct snd_soc_dai *dai) struct mtk_base_afe *afe = snd_soc_dai_get_drvdata(dai); struct mt8195_afe_private *afe_priv = afe->platform_priv; struct mtk_dai_etdm_priv *etdm_data; + int ret; dev_dbg(dai->dev, "%s id %d\n", __func__, dai->id); @@ -2470,15 +2511,23 @@ static int mtk_dai_etdm_probe(struct snd_soc_dai *dai) return -EINVAL; etdm_data = afe_priv->dai_priv[dai->id]; - if (etdm_data->mclk_freq) { - dev_dbg(afe->dev, "MCLK always on, rate %d\n", - etdm_data->mclk_freq); - pm_runtime_get_sync(afe->dev); - mtk_dai_etdm_mclk_configure(afe, dai->id); - mtk_dai_etdm_enable_mclk(afe, dai->id); - pm_runtime_put_sync(afe->dev); - } - return 0; + if (!etdm_data->mclk_freq) + return 0; + + dev_dbg(afe->dev, "MCLK always on, rate %d\n", + etdm_data->mclk_freq); + ret = pm_runtime_resume_and_get(afe->dev); + if (ret) + return ret; + ret = mtk_dai_etdm_mclk_configure(afe, dai->id); + if (ret) + goto err_put_pm; + ret = mtk_dai_etdm_enable_mclk(afe, dai->id); + +err_put_pm: + pm_runtime_put_sync(afe->dev); + + return ret; } static const struct snd_soc_dai_ops mtk_dai_hdmitx_dptx_ops = { diff --git a/sound/soc/mediatek/mt8196/mt8196-afe-clk.c b/sound/soc/mediatek/mt8196/mt8196-afe-clk.c index 286e39f53ae0..dbfd02d20338 100644 --- a/sound/soc/mediatek/mt8196/mt8196-afe-clk.c +++ b/sound/soc/mediatek/mt8196/mt8196-afe-clk.c @@ -220,33 +220,39 @@ static int apll1_mux_setting(struct mtk_base_afe *afe, bool enable) ret = mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUD_ENG1], MT8196_AUD_ENG1_CLK); if (ret) - return ret; + goto err_disable_eng1; ret = mt8196_afe_enable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H]); if (ret) - return ret; + goto err_restore_eng1; ret = mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H], apll_rate); if (ret) - return ret; + goto err_disable_audio_h; } else { - ret = mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUD_ENG1], - MT8196_AFE_26M); - if (ret) - return ret; + mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUD_ENG1], + MT8196_AFE_26M); mt8196_afe_disable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUD_ENG1]); - ret = mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H], - MT8196_AFE_26M); - if (ret) - return ret; + mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H], + MT8196_AFE_26M); mt8196_afe_disable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H]); } return 0; + +err_disable_audio_h: + mt8196_afe_disable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H]); +err_restore_eng1: + mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUD_ENG1], + MT8196_AFE_26M); +err_disable_eng1: + mt8196_afe_disable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUD_ENG1]); + + return ret; } static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) @@ -268,33 +274,39 @@ static int apll2_mux_setting(struct mtk_base_afe *afe, bool enable) ret = mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUD_ENG2], MT8196_AUD_ENG2_CLK); if (ret) - return ret; + goto err_disable_eng2; ret = mt8196_afe_enable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H]); if (ret) - return ret; + goto err_restore_eng2; ret = mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H], apll_rate); if (ret) - return ret; + goto err_disable_audio_h; } else { - ret = mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUD_ENG2], - MT8196_AFE_26M); - if (ret) - return ret; + mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUD_ENG2], + MT8196_AFE_26M); mt8196_afe_disable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUD_ENG2]); - ret = mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H], - MT8196_AFE_26M); - if (ret) - return ret; + mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H], + MT8196_AFE_26M); mt8196_afe_disable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H]); } return 0; + +err_disable_audio_h: + mt8196_afe_disable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H]); +err_restore_eng2: + mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUD_ENG2], + MT8196_AFE_26M); +err_disable_eng2: + mt8196_afe_disable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUD_ENG2]); + + return ret; } int mt8196_apll1_enable(struct mtk_base_afe *afe) @@ -302,15 +314,17 @@ int mt8196_apll1_enable(struct mtk_base_afe *afe) int ret; /* setting for APLL */ - apll1_mux_setting(afe, true); + ret = apll1_mux_setting(afe, true); + if (ret) + return ret; ret = mt8196_afe_enable_top_cg(afe, MT8196_CG_APLL1_CK); if (ret) - goto err_clk_apll1; + goto err_disable_mux; ret = mt8196_afe_enable_top_cg(afe, MT8196_PDN_APLL_TUNER1); if (ret) - goto err_clk_apll1_tuner; + goto err_disable_apll1_ck; /* sel 44.1kHz:1, apll_div:7, upper bound:3 */ regmap_update_bits(afe->regmap, AFE_APLL1_TUNER_CFG, @@ -324,14 +338,22 @@ int mt8196_apll1_enable(struct mtk_base_afe *afe) 0x1 << FREQ_TUNER_EN_SFT); /* audio apll1 on */ - mt8196_afe_enable_top_cg(afe, MT8196_AUDIO_APLL1_EN_ON); + ret = mt8196_afe_enable_top_cg(afe, MT8196_AUDIO_APLL1_EN_ON); + if (ret) + goto err_disable_tuner; return 0; -err_clk_apll1_tuner: +err_disable_tuner: + regmap_update_bits(afe->regmap, AFE_APLL1_TUNER_CFG, + FREQ_TUNER_EN_MASK_SFT, + 0x0); mt8196_afe_disable_top_cg(afe, MT8196_PDN_APLL_TUNER1); -err_clk_apll1: +err_disable_apll1_ck: mt8196_afe_disable_top_cg(afe, MT8196_CG_APLL1_CK); +err_disable_mux: + apll1_mux_setting(afe, false); + return ret; } @@ -355,15 +377,17 @@ int mt8196_apll2_enable(struct mtk_base_afe *afe) int ret; /* setting for APLL */ - apll2_mux_setting(afe, true); + ret = apll2_mux_setting(afe, true); + if (ret) + return ret; ret = mt8196_afe_enable_top_cg(afe, MT8196_CG_APLL2_CK); if (ret) - goto err_clk_apll2; + goto err_disable_mux; ret = mt8196_afe_enable_top_cg(afe, MT8196_PDN_APLL_TUNER2); if (ret) - goto err_clk_apll2_tuner; + goto err_disable_apll2_ck; /* sel 48kHz: 2, apll_div: 7, upper bound: 3*/ regmap_update_bits(afe->regmap, AFE_APLL2_TUNER_CFG, @@ -377,14 +401,23 @@ int mt8196_apll2_enable(struct mtk_base_afe *afe) 0x1 << FREQ_TUNER_EN_SFT); /* audio apll2 on */ - mt8196_afe_enable_top_cg(afe, MT8196_AUDIO_APLL2_EN_ON); + ret = mt8196_afe_enable_top_cg(afe, MT8196_AUDIO_APLL2_EN_ON); + if (ret) + goto err_disable_tuner2; + return 0; -err_clk_apll2_tuner: +err_disable_tuner2: + regmap_update_bits(afe->regmap, AFE_APLL2_TUNER_CFG, + FREQ_TUNER_EN_MASK_SFT, + 0x0); mt8196_afe_disable_top_cg(afe, MT8196_PDN_APLL_TUNER2); -err_clk_apll2: +err_disable_apll2_ck: mt8196_afe_disable_top_cg(afe, MT8196_CG_APLL2_CK); - return 0; +err_disable_mux: + apll2_mux_setting(afe, false); + + return ret; } void mt8196_apll2_disable(struct mtk_base_afe *afe) @@ -469,8 +502,10 @@ int mt8196_mck_enable(struct mtk_base_afe *afe, int mck_id, int rate) return ret; ret = mt8196_afe_set_clk_rate(afe, afe_priv->clk[div_clk_id], rate); - if (ret) + if (ret) { + mt8196_afe_disable_clk(afe, afe_priv->clk[div_clk_id]); return ret; + } return 0; } @@ -511,26 +546,41 @@ int mt8196_afe_enable_reg_rw_clk(struct mtk_base_afe *afe) int ret; /* bus clock for AFE external access, like DRAM */ - mt8196_afe_enable_clk(afe, afe_priv->clk[MT8196_CLK_TOP_ADSP_SEL]); + ret = mt8196_afe_enable_clk(afe, afe_priv->clk[MT8196_CLK_TOP_ADSP_SEL]); + if (ret) + return ret; /* bus clock for AFE internal access, like AFE SRAM */ - mt8196_afe_enable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIOINTBUS]); + ret = mt8196_afe_enable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIOINTBUS]); + if (ret) + goto err_disable_adsp_sel; ret = mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIOINTBUS], MT8196_AFE_26M); if (ret) - return ret; + goto err_disable_audiointbus; /* enable audio h clock */ - mt8196_afe_enable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H]); + ret = mt8196_afe_enable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H]); + if (ret) + goto err_disable_audiointbus; ret = mt8196_afe_set_clk_rate(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H], MT8196_AFE_26M); if (ret) - return ret; + goto err_disable_audio_h; /* AFE hw clock */ /* IPM2.0: USE HOPPING & 26M */ /* set in the regmap_register_patch */ return 0; + +err_disable_audio_h: + mt8196_afe_disable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIO_H]); +err_disable_audiointbus: + mt8196_afe_disable_clk(afe, afe_priv->clk[MT8196_CLK_VLP_MUX_AUDIOINTBUS]); +err_disable_adsp_sel: + mt8196_afe_disable_clk(afe, afe_priv->clk[MT8196_CLK_TOP_ADSP_SEL]); + + return ret; } int mt8196_afe_disable_reg_rw_clk(struct mtk_base_afe *afe) @@ -548,14 +598,12 @@ int mt8196_afe_disable_reg_rw_clk(struct mtk_base_afe *afe) int mt8196_afe_enable_main_clock(struct mtk_base_afe *afe) { - mt8196_afe_enable_top_cg(afe, MT8196_AUDIO_26M_EN_ON); - return 0; + return mt8196_afe_enable_top_cg(afe, MT8196_AUDIO_26M_EN_ON); } int mt8196_afe_disable_main_clock(struct mtk_base_afe *afe) { - mt8196_afe_disable_top_cg(afe, MT8196_AUDIO_26M_EN_ON); - return 0; + return mt8196_afe_disable_top_cg(afe, MT8196_AUDIO_26M_EN_ON); } int mt8196_init_clock(struct mtk_base_afe *afe) diff --git a/sound/soc/mediatek/mt8196/mt8196-afe-pcm.c b/sound/soc/mediatek/mt8196/mt8196-afe-pcm.c index a1ae8322d8b6..f8e9059170a5 100644 --- a/sound/soc/mediatek/mt8196/mt8196-afe-pcm.c +++ b/sound/soc/mediatek/mt8196/mt8196-afe-pcm.c @@ -2211,7 +2211,7 @@ static int mt8196_afe_runtime_suspend(struct device *dev) static int mt8196_afe_runtime_resume(struct device *dev) { struct mtk_base_afe *afe = dev_get_drvdata(dev); - int ret = 0; + int ret; ret = mt8196_afe_enable_reg_rw_clk(afe); if (ret) @@ -2222,7 +2222,9 @@ static int mt8196_afe_runtime_resume(struct device *dev) goto skip_regmap; } regcache_cache_only(afe->regmap, false); - regcache_sync(afe->regmap); + ret = regcache_sync(afe->regmap); + if (ret) + goto err_set_cache_only; /* set audio 26M request */ regmap_update_bits(afe->regmap, AFE_SPM_CONTROL_REQ, 0x1, 0x1); @@ -2233,10 +2235,20 @@ static int mt8196_afe_runtime_resume(struct device *dev) CPU_HD_ALIGN_MASK_SFT, 0 << CPU_HD_ALIGN_SFT); /* enable AFE */ - mt8196_afe_enable_main_clock(afe); + ret = mt8196_afe_enable_main_clock(afe); + if (ret) + goto err_reset_26m_req; skip_regmap: return 0; + +err_reset_26m_req: + regmap_update_bits(afe->regmap, AFE_SPM_CONTROL_REQ, 0x1, 0x0); +err_set_cache_only: + regcache_cache_only(afe->regmap, true); + mt8196_afe_disable_reg_rw_clk(afe); + + return ret; } static int mt8196_afe_component_probe(struct snd_soc_component *component) diff --git a/sound/soc/mediatek/mt8196/mt8196-dai-i2s.c b/sound/soc/mediatek/mt8196/mt8196-dai-i2s.c index ef5cde0ba829..adebf75629be 100644 --- a/sound/soc/mediatek/mt8196/mt8196-dai-i2s.c +++ b/sound/soc/mediatek/mt8196/mt8196-dai-i2s.c @@ -985,27 +985,30 @@ static int mtk_apll_event(struct snd_soc_dapm_widget *w, { struct snd_soc_component *cmpnt = snd_soc_dapm_to_component(w->dapm); struct mtk_base_afe *afe = snd_soc_component_get_drvdata(cmpnt); + int ret; dev_dbg(cmpnt->dev, "name %s, event 0x%x\n", w->name, event); switch (event) { case SND_SOC_DAPM_PRE_PMU: if (strcmp(w->name, APLL1_W_NAME) == 0) - mt8196_apll1_enable(afe); + ret = mt8196_apll1_enable(afe); else - mt8196_apll2_enable(afe); + ret = mt8196_apll2_enable(afe); break; case SND_SOC_DAPM_POST_PMD: if (strcmp(w->name, APLL1_W_NAME) == 0) mt8196_apll1_disable(afe); else mt8196_apll2_disable(afe); + ret = 0; break; default: + ret = 0; break; } - return 0; + return ret; } static int mtk_mclk_en_event(struct snd_soc_dapm_widget *w, @@ -1015,6 +1018,7 @@ static int mtk_mclk_en_event(struct snd_soc_dapm_widget *w, struct snd_soc_component *cmpnt = snd_soc_dapm_to_component(w->dapm); struct mtk_base_afe *afe = snd_soc_component_get_drvdata(cmpnt); struct mtk_afe_i2s_priv *i2s_priv; + int ret; dev_dbg(cmpnt->dev, "name %s, event 0x%x\n", w->name, event); @@ -1025,17 +1029,18 @@ static int mtk_mclk_en_event(struct snd_soc_dapm_widget *w, switch (event) { case SND_SOC_DAPM_PRE_PMU: - mt8196_mck_enable(afe, i2s_priv->mclk_id, i2s_priv->mclk_rate); + ret = mt8196_mck_enable(afe, i2s_priv->mclk_id, i2s_priv->mclk_rate); break; case SND_SOC_DAPM_POST_PMD: i2s_priv->mclk_rate = 0; - mt8196_mck_disable(afe, i2s_priv->mclk_id); + ret = mt8196_mck_disable(afe, i2s_priv->mclk_id); break; default: + ret = 0; break; } - return 0; + return ret; } static const struct snd_soc_dapm_widget mtk_dai_i2s_widgets[] = { diff --git a/sound/soc/mediatek/mt8196/mt8196-dai-tdm.c b/sound/soc/mediatek/mt8196/mt8196-dai-tdm.c index b7aeee939d88..44bd08f5c1fb 100644 --- a/sound/soc/mediatek/mt8196/mt8196-dai-tdm.c +++ b/sound/soc/mediatek/mt8196/mt8196-dai-tdm.c @@ -256,22 +256,24 @@ static int mtk_tdm_bck_en_event(struct snd_soc_dapm_widget *w, struct mt8196_afe_private *afe_priv = afe->platform_priv; int dai_id = get_tdm_id_by_name(w->name); struct mtk_afe_tdm_priv *tdm_priv = afe_priv->dai_priv[dai_id]; + int ret; dev_dbg(cmpnt->dev, "name %s, event 0x%x, dai_id %d\n", w->name, event, dai_id); switch (event) { case SND_SOC_DAPM_PRE_PMU: - mt8196_mck_enable(afe, tdm_priv->bck_id, tdm_priv->bck_rate); + ret = mt8196_mck_enable(afe, tdm_priv->bck_id, tdm_priv->bck_rate); break; case SND_SOC_DAPM_POST_PMD: - mt8196_mck_disable(afe, tdm_priv->bck_id); + ret = mt8196_mck_disable(afe, tdm_priv->bck_id); break; default: + ret = 0; break; } - return 0; + return ret; } static int mtk_tdm_mck_en_event(struct snd_soc_dapm_widget *w, @@ -283,23 +285,25 @@ static int mtk_tdm_mck_en_event(struct snd_soc_dapm_widget *w, struct mt8196_afe_private *afe_priv = afe->platform_priv; int dai_id = get_tdm_id_by_name(w->name); struct mtk_afe_tdm_priv *tdm_priv = afe_priv->dai_priv[dai_id]; + int ret; dev_dbg(cmpnt->dev, "name %s, event 0x%x, dai_id %d\n", w->name, event, dai_id); switch (event) { case SND_SOC_DAPM_PRE_PMU: - mt8196_mck_enable(afe, tdm_priv->mclk_id, tdm_priv->mclk_rate); + ret = mt8196_mck_enable(afe, tdm_priv->mclk_id, tdm_priv->mclk_rate); break; case SND_SOC_DAPM_POST_PMD: tdm_priv->mclk_rate = 0; - mt8196_mck_disable(afe, tdm_priv->mclk_id); + ret = mt8196_mck_disable(afe, tdm_priv->mclk_id); break; default: + ret = 0; break; } - return 0; + return ret; } static const struct snd_soc_dapm_widget mtk_dai_tdm_widgets[] = { diff --git a/sound/soc/mediatek/mt8365/mt8365-afe-pcm.c b/sound/soc/mediatek/mt8365/mt8365-afe-pcm.c index e9497246f37c..314235557fdf 100644 --- a/sound/soc/mediatek/mt8365/mt8365-afe-pcm.c +++ b/sound/soc/mediatek/mt8365/mt8365-afe-pcm.c @@ -514,11 +514,14 @@ static int mt8365_afe_fe_startup(struct snd_pcm_substream *substream, snd_soc_set_runtime_hwparams(substream, afe->mtk_afe_hardware); ret = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS); - if (ret < 0) + if (ret < 0) { dev_err(afe->dev, "snd_pcm_hw_constraint_integer failed\n"); + return ret; + } mt8365_afe_enable_main_clk(afe); - return ret; + + return 0; } static void mt8365_afe_fe_shutdown(struct snd_pcm_substream *substream, diff --git a/sound/soc/mediatek/mt8365/mt8365-dai-i2s.c b/sound/soc/mediatek/mt8365/mt8365-dai-i2s.c index a058973662b3..2e678f4aa4b1 100644 --- a/sound/soc/mediatek/mt8365/mt8365-dai-i2s.c +++ b/sound/soc/mediatek/mt8365/mt8365-dai-i2s.c @@ -267,7 +267,7 @@ static const u32 *get_iir_coef(unsigned int input_fs, if (k >= IIR_NO_NEED) { } else if (k == IIR_RATIOVER) { } else if (k == IIR_INV_COEF) { - } else { + } else if (k < ARRAY_SIZE(iir_coef_tbl_list)) { coef = iir_coef_tbl_list[k].coef; cnt = iir_coef_tbl_list[k].cnt; } diff --git a/sound/soc/qcom/qdsp6/q6apm.c b/sound/soc/qcom/qdsp6/q6apm.c index 8a756249e588..dea1dc2a7935 100644 --- a/sound/soc/qcom/qdsp6/q6apm.c +++ b/sound/soc/qcom/qdsp6/q6apm.c @@ -917,6 +917,7 @@ static int apm_probe(gpr_device_t *gdev) static void apm_remove(gpr_device_t *gdev) { + g_apm = NULL; of_platform_depopulate(&gdev->dev); snd_soc_unregister_component(&gdev->dev); } diff --git a/sound/soc/qcom/sdm845.c b/sound/soc/qcom/sdm845.c index 6843ab8ba017..a777b3b83775 100644 --- a/sound/soc/qcom/sdm845.c +++ b/sound/soc/qcom/sdm845.c @@ -38,6 +38,7 @@ struct sdm845_snd_data { bool stream_prepared[AFE_PORT_MAX]; uint32_t pri_mi2s_clk_count; uint32_t sec_mi2s_clk_count; + uint32_t quat_mi2s_clk_count; uint32_t quat_tdm_clk_count; }; @@ -365,9 +366,11 @@ static int sdm845_snd_startup(struct snd_pcm_substream *substream) break; case QUATERNARY_MI2S_RX: codec_dai_fmt |= SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_I2S; - snd_soc_dai_set_sysclk(cpu_dai, - Q6AFE_LPASS_CLK_ID_QUAD_MI2S_IBIT, - MI2S_BCLK_RATE, SNDRV_PCM_STREAM_PLAYBACK); + if (++(data->quat_mi2s_clk_count) == 1) { + snd_soc_dai_set_sysclk(cpu_dai, + Q6AFE_LPASS_CLK_ID_QUAD_MI2S_IBIT, + MI2S_BCLK_RATE, SNDRV_PCM_STREAM_PLAYBACK); + } snd_soc_dai_set_fmt(cpu_dai, fmt); snd_soc_dai_set_fmt(codec_dai, codec_dai_fmt); break; @@ -454,8 +457,16 @@ static void sdm845_snd_shutdown(struct snd_pcm_substream *substream) 0, SNDRV_PCM_STREAM_PLAYBACK); } break; - case SLIMBUS_0_RX...SLIMBUS_6_TX: + case QUATERNARY_MI2S_RX: + if (--(data->quat_mi2s_clk_count) == 0) { + snd_soc_dai_set_sysclk(cpu_dai, + Q6AFE_LPASS_CLK_ID_QUAD_MI2S_IBIT, + 0, SNDRV_PCM_STREAM_PLAYBACK); + } + break; + + case SLIMBUS_0_RX...SLIMBUS_6_TX: break; default: diff --git a/sound/soc/renesas/rcar/msiof.c b/sound/soc/renesas/rcar/msiof.c index 128543fc4fc9..9fead9a22cdc 100644 --- a/sound/soc/renesas/rcar/msiof.c +++ b/sound/soc/renesas/rcar/msiof.c @@ -427,10 +427,12 @@ static int msiof_open(struct snd_soc_component *component, ret = snd_pcm_hw_constraint_integer(substream->runtime, SNDRV_PCM_HW_PARAM_PERIODS); open_err_dma: - if (ret < 0) + if (ret < 0) { dma_release_channel(chan); + return ret; + } - return ret; + return 0; } static int msiof_close(struct snd_soc_component *component, diff --git a/sound/soc/rockchip/rk3288_hdmi_analog.c b/sound/soc/rockchip/rk3288_hdmi_analog.c index 541163ed56fc..9bb02d41d901 100644 --- a/sound/soc/rockchip/rk3288_hdmi_analog.c +++ b/sound/soc/rockchip/rk3288_hdmi_analog.c @@ -201,36 +201,59 @@ static int snd_rk_mc_probe(struct platform_device *pdev) if (ret) { dev_err(&pdev->dev, "Unable to parse property 'rockchip,audio-codec'\n"); - return ret; + goto put_codec_of_node; } ret = snd_soc_get_dai_name(&args, &rk_dailink.codecs[0].dai_name); - if (ret) - return dev_err_probe(&pdev->dev, ret, - "Unable to get codec_dai_name\n"); + of_node_put(args.np); + if (ret) { + dev_err_probe(&pdev->dev, ret, + "Unable to get codec_dai_name\n"); + goto put_codec_of_node; + } rk_dailink.cpus->of_node = of_parse_phandle(np, "rockchip,i2s-controller", 0); if (!rk_dailink.cpus->of_node) { dev_err(&pdev->dev, "Property 'rockchip,i2s-controller' missing or invalid\n"); - return -EINVAL; + ret = -EINVAL; + goto put_codec_of_node; } rk_dailink.platforms->of_node = rk_dailink.cpus->of_node; ret = snd_soc_of_parse_audio_routing(card, "rockchip,routing"); if (ret) - return ret; + goto put_cpu_of_node; snd_soc_card_set_drvdata(card, machine); ret = devm_snd_soc_register_card(&pdev->dev, card); - if (ret) - return dev_err_probe(&pdev->dev, ret, - "Soc register card failed\n"); + if (ret) { + dev_err_probe(&pdev->dev, ret, + "Soc register card failed\n"); + goto put_cpu_of_node; + } return 0; + +put_cpu_of_node: + of_node_put(rk_dailink.cpus->of_node); + rk_dailink.cpus->of_node = NULL; +put_codec_of_node: + of_node_put(rk_dailink.codecs[0].of_node); + rk_dailink.codecs[0].of_node = NULL; + + return ret; +} + +static void snd_rk_mc_remove(struct platform_device *pdev) +{ + of_node_put(rk_dailink.cpus->of_node); + rk_dailink.cpus->of_node = NULL; + of_node_put(rk_dailink.codecs[0].of_node); + rk_dailink.codecs[0].of_node = NULL; } static const struct of_device_id rockchip_sound_of_match[] = { @@ -242,6 +265,7 @@ MODULE_DEVICE_TABLE(of, rockchip_sound_of_match); static struct platform_driver rockchip_sound_driver = { .probe = snd_rk_mc_probe, + .remove = snd_rk_mc_remove, .driver = { .name = DRV_NAME, .pm = &snd_soc_pm_ops, diff --git a/sound/soc/rockchip/rockchip_i2s.c b/sound/soc/rockchip/rockchip_i2s.c index 261f36d4c2fd..e7ea71783e37 100644 --- a/sound/soc/rockchip/rockchip_i2s.c +++ b/sound/soc/rockchip/rockchip_i2s.c @@ -244,7 +244,9 @@ static int rockchip_i2s_set_fmt(struct snd_soc_dai *cpu_dai, unsigned int mask = 0, val = 0; int ret = 0; - pm_runtime_get_sync(cpu_dai->dev); + ret = pm_runtime_resume_and_get(cpu_dai->dev); + if (ret) + return ret; mask = I2S_CKR_MSS_MASK; switch (fmt & SND_SOC_DAIFMT_CLOCK_PROVIDER_MASK) { case SND_SOC_DAIFMT_BP_FP: diff --git a/sound/soc/rockchip/rockchip_sai.c b/sound/soc/rockchip/rockchip_sai.c index 30b5e71d0937..264a99e618a5 100644 --- a/sound/soc/rockchip/rockchip_sai.c +++ b/sound/soc/rockchip/rockchip_sai.c @@ -487,7 +487,9 @@ static int rockchip_sai_set_fmt(struct snd_soc_dai *dai, unsigned int fmt) unsigned long flags; int ret = 0; - pm_runtime_get_sync(dai->dev); + ret = pm_runtime_resume_and_get(dai->dev); + if (ret) + return ret; mask = SAI_CKR_MSS_MASK; switch (fmt & SND_SOC_DAIFMT_CLOCK_PROVIDER_MASK) { diff --git a/sound/soc/samsung/midas_wm1811.c b/sound/soc/samsung/midas_wm1811.c index d43af5069baf..11466dd3539e 100644 --- a/sound/soc/samsung/midas_wm1811.c +++ b/sound/soc/samsung/midas_wm1811.c @@ -25,7 +25,8 @@ */ #define MCLK1_RATE 24000000U #define MCLK2_RATE 32768U -#define DEFAULT_FLL1_RATE 11289600U +/* Matches the codec's default AIF1 configuration: 48kHz, 256fs */ +#define DEFAULT_FLL1_RATE 12288000U struct midas_priv { struct gpio_desc *gpio_fm_sel; @@ -34,6 +35,7 @@ struct midas_priv { struct gpio_desc *gpio_headset_key; struct iio_channel *adc_headset_detect; unsigned int fll1_rate; + unsigned int aif1clk_rate; struct snd_soc_jack headset_jack; }; @@ -171,11 +173,12 @@ static int midas_start_fll1(struct snd_soc_pcm_runtime *rtd, unsigned int rate) if (!rate) rate = priv->fll1_rate; /* - * If no new rate is requested, set FLL1 to a sane default for jack - * detection. + * If no new rate is requested, set FLL1 to the rate the codec's AIF1 + * is currently configured for, as its digital paths can be powered + * up without an active stream. */ if (!rate) - rate = DEFAULT_FLL1_RATE; + rate = priv->aif1clk_rate ?: DEFAULT_FLL1_RATE; if (rate != priv->fll1_rate && priv->fll1_rate) { /* while reconfiguring, switch to MCLK2 for SYSCLK */ @@ -241,6 +244,7 @@ static int midas_aif1_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 midas_priv *priv = snd_soc_card_get_drvdata(rtd->card); unsigned int pll_out; /* AIF1CLK should be at least 3MHz for "optimal performance" */ @@ -249,6 +253,8 @@ static int midas_aif1_hw_params(struct snd_pcm_substream *substream, else pll_out = params_rate(params) * 256; + priv->aif1clk_rate = pll_out; + return midas_start_fll1(rtd, pll_out); } diff --git a/sound/soc/sdca/sdca_class.c b/sound/soc/sdca/sdca_class.c index e0e7aff70f93..3cabed663008 100644 --- a/sound/soc/sdca/sdca_class.c +++ b/sound/soc/sdca/sdca_class.c @@ -20,7 +20,7 @@ #include #include #include -#include "sdca_class.h" +#include #define CLASS_SDW_ATTACH_TIMEOUT_MS 5000 @@ -199,30 +199,42 @@ static void class_sdw_remove(struct sdw_slave *sdw) cancel_work_sync(&drv->boot_work); } -static int class_suspend(struct device *dev) +/** + * sdca_class_system_suspend - SDCA class system suspend helper + * @drv: caller-owned sdca_class_drv. + * + * Codec drivers compose this into their own dev_pm_ops. Disables the + * SoundWire interrupt and forces runtime suspend of the underlying + * class regmap. + */ +int sdca_class_system_suspend(struct sdca_class_drv *drv) { - struct sdca_class_drv *drv = dev_get_drvdata(dev); int ret; disable_irq(drv->sdw->irq); - ret = pm_runtime_force_suspend(dev); + ret = pm_runtime_force_suspend(drv->dev); if (ret) { - dev_err(dev, "failed to force suspend: %d\n", ret); + dev_err(drv->dev, "failed to force suspend: %d\n", ret); + enable_irq(drv->sdw->irq); return ret; } return 0; } +EXPORT_SYMBOL_NS_GPL(sdca_class_system_suspend, "SND_SOC_SDCA_CLASS"); -static int class_resume(struct device *dev) +/** + * sdca_class_system_resume - SDCA class system resume helper + * @drv: caller-owned sdca_class_drv. + */ +int sdca_class_system_resume(struct sdca_class_drv *drv) { - struct sdca_class_drv *drv = dev_get_drvdata(dev); int ret; - ret = pm_runtime_force_resume(dev); + ret = pm_runtime_force_resume(drv->dev); if (ret) { - dev_err(dev, "failed to force resume: %d\n", ret); + dev_err(drv->dev, "failed to force resume: %d\n", ret); return ret; } @@ -230,11 +242,14 @@ static int class_resume(struct device *dev) return 0; } +EXPORT_SYMBOL_NS_GPL(sdca_class_system_resume, "SND_SOC_SDCA_CLASS"); -static int class_runtime_suspend(struct device *dev) +/** + * sdca_class_runtime_suspend - SDCA class runtime suspend helper + * @drv: caller-owned sdca_class_drv. + */ +int sdca_class_runtime_suspend(struct sdca_class_drv *drv) { - struct sdca_class_drv *drv = dev_get_drvdata(dev); - /* * Whilst the driver doesn't power the chip down here, going into runtime * suspend lets the SoundWire bus power down, which means the driver @@ -244,10 +259,14 @@ static int class_runtime_suspend(struct device *dev) return 0; } +EXPORT_SYMBOL_NS_GPL(sdca_class_runtime_suspend, "SND_SOC_SDCA_CLASS"); -static int class_runtime_resume(struct device *dev) +/** + * sdca_class_runtime_resume - SDCA class runtime resume helper + * @drv: caller-owned sdca_class_drv. + */ +int sdca_class_runtime_resume(struct sdca_class_drv *drv) { - struct sdca_class_drv *drv = dev_get_drvdata(dev); int ret; ret = sdw_slave_wait_for_init(drv->sdw, CLASS_SDW_ATTACH_TIMEOUT_MS); @@ -270,10 +289,37 @@ static int class_runtime_resume(struct device *dev) return ret; } +EXPORT_SYMBOL_NS_GPL(sdca_class_runtime_resume, "SND_SOC_SDCA_CLASS"); + +/* + * Convenience dev_pm_ops used by the built-in class_sdw_driver, which + * stashes its sdca_class_drv in drvdata directly. Codec drivers that + * embed sdca_class_drv in their own priv compose their own dev_pm_ops + * using the sdca_class_*_suspend/resume helpers above. + */ +static int class_pm_system_suspend(struct device *dev) +{ + return sdca_class_system_suspend(dev_get_drvdata(dev)); +} + +static int class_pm_system_resume(struct device *dev) +{ + return sdca_class_system_resume(dev_get_drvdata(dev)); +} + +static int class_pm_runtime_suspend(struct device *dev) +{ + return sdca_class_runtime_suspend(dev_get_drvdata(dev)); +} + +static int class_pm_runtime_resume(struct device *dev) +{ + return sdca_class_runtime_resume(dev_get_drvdata(dev)); +} -static const struct dev_pm_ops class_pm_ops = { - SYSTEM_SLEEP_PM_OPS(class_suspend, class_resume) - RUNTIME_PM_OPS(class_runtime_suspend, class_runtime_resume, NULL) +static const struct dev_pm_ops sdca_class_pm_ops = { + SYSTEM_SLEEP_PM_OPS(class_pm_system_suspend, class_pm_system_resume) + RUNTIME_PM_OPS(class_pm_runtime_suspend, class_pm_runtime_resume, NULL) }; static const struct sdw_device_id class_sdw_id[] = { @@ -287,7 +333,7 @@ MODULE_DEVICE_TABLE(sdw, class_sdw_id); static struct sdw_driver class_sdw_driver = { .driver = { .name = "sdca_class", - .pm = pm_ptr(&class_pm_ops), + .pm = pm_ptr(&sdca_class_pm_ops), }, .probe = class_sdw_probe, diff --git a/sound/soc/sdca/sdca_class.h b/sound/soc/sdca/sdca_class.h deleted file mode 100644 index 57f7f8d08f49..000000000000 --- a/sound/soc/sdca/sdca_class.h +++ /dev/null @@ -1,35 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0 */ -/* - * The MIPI SDCA specification is available for public downloads at - * https://www.mipi.org/mipi-sdca-v1-0-download - * - * Copyright (C) 2025 Cirrus Logic, Inc. and - * Cirrus Logic International Semiconductor Ltd. - */ - -#ifndef __SDCA_CLASS_H__ -#define __SDCA_CLASS_H__ - -#include -#include -#include - -struct device; -struct regmap; -struct sdw_slave; -struct sdca_function_data; - -struct sdca_class_drv { - struct device *dev; - struct regmap *dev_regmap; - struct sdw_slave *sdw; - - struct sdca_interrupt_info *irq_info; - - struct mutex regmap_lock; - /* Serialise function initialisations */ - struct mutex init_lock; - struct work_struct boot_work; -}; - -#endif /* __SDCA_CLASS_H__ */ diff --git a/sound/soc/sdca/sdca_class_function.c b/sound/soc/sdca/sdca_class_function.c index 610931ae5531..616d5f973671 100644 --- a/sound/soc/sdca/sdca_class_function.c +++ b/sound/soc/sdca/sdca_class_function.c @@ -26,7 +26,7 @@ #include #include #include -#include "sdca_class.h" +#include #include "sdca_function_device.h" struct class_function_drv { diff --git a/sound/soc/sdca/sdca_fdl.c b/sound/soc/sdca/sdca_fdl.c index 150e36ed24bc..7fc809707944 100644 --- a/sound/soc/sdca/sdca_fdl.c +++ b/sound/soc/sdca/sdca_fdl.c @@ -199,7 +199,6 @@ static int fdl_load_file(struct sdca_interrupt *interrupt, struct sdca_fdl_file *fdl_file; char *disk_filename; int ret; - int i; if (!set) { dev_err(dev, "request to load SWF with no set\n"); @@ -209,9 +208,18 @@ static int fdl_load_file(struct sdca_interrupt *interrupt, fdl_file = &set->files[file_index]; if (fdl_data->swft) { - tmp = fdl_data->swft->files; - for (i = 0; i < fdl_data->swft->header.length; i += tmp->file_length, - tmp = ACPI_ADD_PTR(struct acpi_sw_file, tmp, tmp->file_length)) { + struct acpi_sw_file *table_end, *next; + + table_end = ACPI_ADD_PTR(struct acpi_sw_file, fdl_data->swft, + fdl_data->swft->header.length); + for (tmp = fdl_data->swft->files; tmp + 1 <= table_end; tmp = next) { + next = ACPI_ADD_PTR(struct acpi_sw_file, tmp, tmp->file_length); + + if (tmp->file_length < sizeof(*tmp) || next > table_end) { + dev_err(dev, "bad file length in SWFT: %u\n", tmp->file_length); + break; + } + if (tmp->vendor_id == fdl_file->vendor_id && tmp->file_id == fdl_file->file_id) { dev_dbg(dev, "located SWF in ACPI: %x-%x-%x\n", @@ -293,6 +301,8 @@ static struct sdca_fdl_set *fdl_get_set(struct sdca_interrupt *interrupt) range = sdca_selector_find_range(dev, xu, SDCA_CTL_XU_FDL_SET_INDEX, SDCA_FDL_SET_INDEX_NCOLS, 0); + if (!range) + return NULL; val = sdca_range_search(range, SDCA_FDL_SET_INDEX_SET_NUMBER, val, SDCA_FDL_SET_INDEX_FILE_SET_ID); diff --git a/sound/soc/soc-ac97.c b/sound/soc/soc-ac97.c index 5f81e3606655..5c573c8dc249 100644 --- a/sound/soc/soc-ac97.c +++ b/sound/soc/soc-ac97.c @@ -241,10 +241,12 @@ struct snd_ac97 *snd_soc_new_ac97_component(struct snd_soc_component *component, ret = snd_soc_ac97_init_gpio(ac97, component); if (ret) - goto err_put_device; + goto err_del_device; return ac97; +err_del_device: + device_del(&ac97->dev); err_put_device: put_device(&ac97->dev); return ERR_PTR(ret); diff --git a/sound/soc/soc-card-test.c b/sound/soc/soc-card-test.c index 47dfd8b1babc..610b8220786d 100644 --- a/sound/soc/soc-card-test.c +++ b/sound/soc/soc-card-test.c @@ -70,6 +70,7 @@ static void test_snd_soc_card_get_kcontrol(struct kunit *test) static int soc_card_test_case_init(struct kunit *test) { struct soc_card_test_priv *priv; + struct device *dev; int ret; priv = kunit_kzalloc(test, sizeof(*priv), GFP_KERNEL); @@ -82,8 +83,10 @@ static int soc_card_test_case_init(struct kunit *test) if (!priv->card) return -ENOMEM; - priv->card_dev = kunit_device_register(test, "sound-soc-card-test"); - priv->card_dev = get_device(priv->card_dev); + dev = kunit_device_register(test, "sound-soc-card-test"); + if (IS_ERR(dev)) + return PTR_ERR(dev); + priv->card_dev = get_device(dev); if (!priv->card_dev) return -ENODEV; diff --git a/sound/soc/soc-component.c b/sound/soc/soc-component.c index dc7d203cb76a..c4d9e80a9d85 100644 --- a/sound/soc/soc-component.c +++ b/sound/soc/soc-component.c @@ -935,7 +935,7 @@ int snd_soc_component_test_bits(struct snd_soc_component *component, } EXPORT_SYMBOL_GPL(snd_soc_component_test_bits); -int snd_soc_pcm_component_pointer(struct snd_pcm_substream *substream) +snd_pcm_uframes_t snd_soc_pcm_component_pointer(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = snd_soc_substream_to_rtd(substream); struct snd_soc_component *component; diff --git a/sound/soc/soc-link.c b/sound/soc/soc-link.c index 02fd68f2e702..50ff9ba3ac87 100644 --- a/sound/soc/soc-link.c +++ b/sound/soc/soc-link.c @@ -161,7 +161,7 @@ int snd_soc_link_trigger(struct snd_pcm_substream *substream, int cmd, break; ret = soc_link_trigger(substream, cmd); - soc_link_mark_pop(rtd, startup); + soc_link_mark_pop(rtd, trigger); } return ret; diff --git a/sound/soc/soc-ops.c b/sound/soc/soc-ops.c index c935571d43e9..59ab521f99a8 100644 --- a/sound/soc/soc-ops.c +++ b/sound/soc/soc-ops.c @@ -406,7 +406,7 @@ EXPORT_SYMBOL_GPL(snd_soc_put_volsw_sx); static int snd_soc_clip_to_platform_max(struct snd_kcontrol *kctl) { struct soc_mixer_control *mc = (struct soc_mixer_control *)kctl->private_value; - struct snd_ctl_elem_value *uctl; + struct snd_ctl_elem_value *uctl __free(kfree) = NULL; int ret; if (!mc->platform_max) @@ -418,7 +418,7 @@ static int snd_soc_clip_to_platform_max(struct snd_kcontrol *kctl) ret = kctl->get(kctl, uctl); if (ret < 0) - goto out; + return ret; if (uctl->value.integer.value[0] > mc->platform_max) uctl->value.integer.value[0] = mc->platform_max; @@ -428,10 +428,10 @@ static int snd_soc_clip_to_platform_max(struct snd_kcontrol *kctl) uctl->value.integer.value[1] = mc->platform_max; ret = kctl->put(kctl, uctl); + if (ret < 0) + return ret; -out: - kfree(uctl); - return ret; + return 0; } /** diff --git a/sound/soc/soc-topology-test.c b/sound/soc/soc-topology-test.c index 346a52d3006a..fb7e4d5690cd 100644 --- a/sound/soc/soc-topology-test.c +++ b/sound/soc/soc-topology-test.c @@ -24,8 +24,12 @@ static struct device *test_dev; static int snd_soc_tplg_test_init(struct kunit *test) { - test_dev = kunit_device_register(test, "sound-soc-topology-test"); - test_dev = get_device(test_dev); + struct device *dev; + + dev = kunit_device_register(test, "sound-soc-topology-test"); + if (IS_ERR(dev)) + return PTR_ERR(dev); + test_dev = get_device(dev); if (!test_dev) return -ENODEV; diff --git a/sound/soc/sof/amd/acp.c b/sound/soc/sof/amd/acp.c index f89ad86260b4..5570f3d1348d 100644 --- a/sound/soc/sof/amd/acp.c +++ b/sound/soc/sof/amd/acp.c @@ -1038,6 +1038,8 @@ int amd_sof_acp_probe(struct snd_sof_dev *sdev) free_ipc_irq: free_irq(sdev->ipc_irq, sdev); + if (adata->sdw) + amd_sof_sdw_exit(sdev); unregister_dev: platform_device_unregister(adata->dmic_dev); return ret; @@ -1048,12 +1050,12 @@ void amd_sof_acp_remove(struct snd_sof_dev *sdev) { struct acp_dev_data *adata = sdev->pdata->hw_pdata; - if (adata->sdw) - amd_sof_sdw_exit(sdev); - if (sdev->ipc_irq) free_irq(sdev->ipc_irq, sdev); + if (adata->sdw) + amd_sof_sdw_exit(sdev); + if (adata->dmic_dev) platform_device_unregister(adata->dmic_dev); @@ -1197,7 +1199,8 @@ int amd_sof_acp7x_suspend(struct snd_sof_dev *sdev, u32 target_state) enable = true; break; default: - break; + dev_err(sdev->dev, "Unexpected PCI revision: 0x%x\n", acp_data->pci_rev); + return -EINVAL; } snd_sof_dsp_write(sdev, ACP_DSP_BAR, ACP_CONTROL, enable); snd_sof_dsp_write(sdev, ACP_DSP_BAR, ACP7X_ZSC_DSP_CTRL, 1); diff --git a/sound/soc/sof/imx/imx-common.c b/sound/soc/sof/imx/imx-common.c index 7a03c8cc5dd4..436fe49246ba 100644 --- a/sound/soc/sof/imx/imx-common.c +++ b/sound/soc/sof/imx/imx-common.c @@ -34,6 +34,7 @@ void imx8_get_registers(struct snd_sof_dev *sdev, /* first read registers */ sof_mailbox_read(sdev, offset, xoops, sizeof(*xoops)); + xoops->plat_hdr.numaregs = 0; /* then get panic info */ if (xoops->arch_hdr.totalsize > EXCEPT_MAX_HDR_SIZE) { diff --git a/sound/soc/sof/intel/hda-codec.c b/sound/soc/sof/intel/hda-codec.c index 32fcc1cd3f92..a2b2ecf1e7e6 100644 --- a/sound/soc/sof/intel/hda-codec.c +++ b/sound/soc/sof/intel/hda-codec.c @@ -87,7 +87,7 @@ void hda_codec_jack_wake_enable(struct snd_sof_dev *sdev, bool enable) list_for_each_codec(codec, hbus) { /* only set WAKEEN when needed for HDaudio codecs */ mask |= BIT(codec->core.addr); - if (codec->jacktbl.used) + if (codec->jacktbl_used) val |= BIT(codec->core.addr); } } else { @@ -116,7 +116,7 @@ void hda_codec_jack_check(struct snd_sof_dev *sdev) * Wake up all jack-detecting codecs regardless whether an event * has been recorded in STATESTS */ - if (codec->jacktbl.used) + if (codec->jacktbl_used) pm_request_resume(&codec->core.dev); } EXPORT_SYMBOL_NS_GPL(hda_codec_jack_check, "SND_SOC_SOF_HDA_AUDIO_CODEC"); diff --git a/sound/soc/sof/intel/hda-ctrl.c b/sound/soc/sof/intel/hda-ctrl.c index aeb34310eebd..333f6bbea753 100644 --- a/sound/soc/sof/intel/hda-ctrl.c +++ b/sound/soc/sof/intel/hda-ctrl.c @@ -349,6 +349,7 @@ void hda_dsp_ctrl_stop_chip(struct snd_sof_dev *sdev) bus->chip_init = false; } +EXPORT_SYMBOL_NS(hda_dsp_ctrl_stop_chip, "SND_SOC_SOF_INTEL_HDA_COMMON"); MODULE_LICENSE("Dual BSD/GPL"); MODULE_DESCRIPTION("SOF helpers for HDaudio platforms"); diff --git a/sound/soc/sof/intel/hda.c b/sound/soc/sof/intel/hda.c index 4dbba9186b29..2a40cb9bf24d 100644 --- a/sound/soc/sof/intel/hda.c +++ b/sound/soc/sof/intel/hda.c @@ -939,6 +939,7 @@ int hda_dsp_probe(struct snd_sof_dev *sdev) hda_dsp_ctrl_ppcap_enable(sdev, false); } free_ipc_irq: + hda_dsp_ctrl_stop_chip(sdev); free_irq(sdev->ipc_irq, sdev); free_irq_vector: if (sdev->msi_enabled) @@ -1006,6 +1007,9 @@ void hda_dsp_remove(struct snd_sof_dev *sdev) snd_dma_free_pages(&hda->iccmax_dmab); skip_disable_dsp: + /* stop CORB/RIRB and position buffer DMA before the buffers are freed */ + hda_dsp_ctrl_stop_chip(sdev); + free_irq(sdev->ipc_irq, sdev); if (sdev->msi_enabled) pci_free_irq_vectors(pci); diff --git a/sound/soc/xilinx/xlnx_formatter_pcm.c b/sound/soc/xilinx/xlnx_formatter_pcm.c index 95312b4ddc5b..4d1de7cb9c61 100644 --- a/sound/soc/xilinx/xlnx_formatter_pcm.c +++ b/sound/soc/xilinx/xlnx_formatter_pcm.c @@ -6,6 +6,7 @@ // // Author: Maruthi Srinivas Bayyavarapu +#include #include #include #include @@ -55,8 +56,8 @@ #define CFG_S2MM_XFER_SHIFT 29 #define CFG_S2MM_PKG_MASK BIT(28) -#define AUD_CTRL_DATA_WIDTH_SHIFT 16 -#define AUD_CTRL_ACTIVE_CH_SHIFT 19 +#define AUD_CTRL_DATA_WIDTH_MASK GENMASK(18, 16) +#define AUD_CTRL_ACTIVE_CH_MASK GENMASK(22, 19) #define PERIOD_CFG_PERIODS_SHIFT 16 #define PERIODS_MIN 2 @@ -507,28 +508,29 @@ static int xlnx_formatter_pcm_hw_params(struct snd_soc_component *component, writel(high, stream_data->mmio + XLNX_AUD_BUFF_ADDR_MSB); val = readl(stream_data->mmio + XLNX_AUD_CTRL); + val &= ~(AUD_CTRL_DATA_WIDTH_MASK | AUD_CTRL_ACTIVE_CH_MASK); bits_per_sample = params_width(params); switch (bits_per_sample) { case 8: - val |= (BIT_DEPTH_8 << AUD_CTRL_DATA_WIDTH_SHIFT); + val |= FIELD_PREP(AUD_CTRL_DATA_WIDTH_MASK, BIT_DEPTH_8); break; case 16: - val |= (BIT_DEPTH_16 << AUD_CTRL_DATA_WIDTH_SHIFT); + val |= FIELD_PREP(AUD_CTRL_DATA_WIDTH_MASK, BIT_DEPTH_16); break; case 20: - val |= (BIT_DEPTH_20 << AUD_CTRL_DATA_WIDTH_SHIFT); + val |= FIELD_PREP(AUD_CTRL_DATA_WIDTH_MASK, BIT_DEPTH_20); break; case 24: - val |= (BIT_DEPTH_24 << AUD_CTRL_DATA_WIDTH_SHIFT); + val |= FIELD_PREP(AUD_CTRL_DATA_WIDTH_MASK, BIT_DEPTH_24); break; case 32: - val |= (BIT_DEPTH_32 << AUD_CTRL_DATA_WIDTH_SHIFT); + val |= FIELD_PREP(AUD_CTRL_DATA_WIDTH_MASK, BIT_DEPTH_32); break; default: return -EINVAL; } - val |= active_ch << AUD_CTRL_ACTIVE_CH_SHIFT; + val |= FIELD_PREP(AUD_CTRL_ACTIVE_CH_MASK, active_ch); writel(val, stream_data->mmio + XLNX_AUD_CTRL); val = (params_periods(params) << PERIOD_CFG_PERIODS_SHIFT) diff --git a/sound/usb/6fire/control.c b/sound/usb/6fire/control.c index 10104cb42165..020e9676d106 100644 --- a/sound/usb/6fire/control.c +++ b/sound/usb/6fire/control.c @@ -20,6 +20,7 @@ #include "control.h" #include "comm.h" #include "chip.h" +#include "pcm.h" static const char * const opt_coax_texts[2] = { "Optical", "Coax" }; static const char * const line_phono_texts[2] = { "Line", "Phono" }; @@ -383,6 +384,12 @@ static int usb6fire_control_digital_thru_put(struct snd_kcontrol *kcontrol, struct control_runtime *rt = snd_kcontrol_chip(kcontrol); int changed = 0; + /* + * with Digital Thru on, streaming_update() selects the altsetting and + * writes the clock register of an idle card; prepare does the same + * under stream_mutex + */ + guard(mutex)(&rt->chip->pcm->stream_mutex); if (rt->digital_thru_switch != ucontrol->value.integer.value[0]) { rt->digital_thru_switch = ucontrol->value.integer.value[0]; usb6fire_control_streaming_update(rt); diff --git a/sound/usb/caiaq/device.c b/sound/usb/caiaq/device.c index f604846ec6e6..5e89047c9d9c 100644 --- a/sound/usb/caiaq/device.c +++ b/sound/usb/caiaq/device.c @@ -142,7 +142,7 @@ static void usb_ep1_command_reply_dispatch (struct urb* urb) return; } if (urb->actual_length < 1) - return; + goto resubmit; payload_len = urb->actual_length - 1; @@ -192,6 +192,7 @@ static void usb_ep1_command_reply_dispatch (struct urb* urb) break; } + resubmit: cdev->ep1_in_urb->actual_length = 0; ret = usb_submit_urb(cdev->ep1_in_urb, GFP_ATOMIC); if (ret < 0) @@ -212,6 +213,8 @@ int snd_usb_caiaq_send_command(struct snd_usb_caiaqdev *cdev, if (len > EP1_BUFSIZE - 1) len = EP1_BUFSIZE - 1; + guard(mutex)(&cdev->ep1_out_mutex); + if (buffer && len > 0) memcpy(cdev->ep1_out_buf+1, buffer, len); @@ -235,6 +238,8 @@ int snd_usb_caiaq_send_command_bank(struct snd_usb_caiaqdev *cdev, if (len > EP1_BUFSIZE - 2) len = EP1_BUFSIZE - 2; + guard(mutex)(&cdev->ep1_out_mutex); + if (buffer && len > 0) memcpy(cdev->ep1_out_buf+2, buffer, len); @@ -443,6 +448,8 @@ static int create_card(struct usb_device *usb_dev, cdev->chip.usb_id = USB_ID(le16_to_cpu(usb_dev->descriptor.idVendor), le16_to_cpu(usb_dev->descriptor.idProduct)); spin_lock_init(&cdev->spinlock); + spin_lock_init(&cdev->midi_lock); + mutex_init(&cdev->ep1_out_mutex); *cardp = card; return 0; diff --git a/sound/usb/caiaq/device.h b/sound/usb/caiaq/device.h index 1c6f34693fa8..7b15cbffdec1 100644 --- a/sound/usb/caiaq/device.h +++ b/sound/usb/caiaq/device.h @@ -2,6 +2,8 @@ #ifndef CAIAQ_DEVICE_H #define CAIAQ_DEVICE_H +#include + #include "../usbaudio.h" #define USB_VID_NATIVEINSTRUMENTS 0x17cc @@ -68,10 +70,12 @@ struct snd_usb_caiaqdev { unsigned char ep1_in_buf[EP1_BUFSIZE]; unsigned char ep1_out_buf[EP1_BUFSIZE]; + struct mutex ep1_out_mutex; /* protects ep1_out_buf */ unsigned char midi_out_buf[EP1_BUFSIZE]; struct caiaq_device_spec spec; - spinlock_t spinlock; + spinlock_t spinlock; /* for PCM audio */ + spinlock_t midi_lock; /* midi_x_stream, midi_out_active */ wait_queue_head_t ep1_wait_queue; wait_queue_head_t prepare_wait_queue; int spec_received, audio_parm_answer; diff --git a/sound/usb/caiaq/input.c b/sound/usb/caiaq/input.c index 309a361ca9f7..f826d9baf96e 100644 --- a/sound/usb/caiaq/input.c +++ b/sound/usb/caiaq/input.c @@ -41,11 +41,11 @@ static const unsigned short keycode_kore[] = { BTN_3, BTN_2, BTN_1, - BTN_8, - BTN_7, - BTN_6, BTN_5, - KEY_BRL_DOT4, /* touch sensitive knobs */ + BTN_6, + BTN_7, + BTN_8, + KEY_BRL_DOT4, /* touch sensitive knobs (Kore 2 order) */ KEY_BRL_DOT3, KEY_BRL_DOT2, KEY_BRL_DOT1, @@ -55,6 +55,21 @@ static const unsigned short keycode_kore[] = { KEY_BRL_DOT5 }; +/* index of the first touch sensor in keycode_kore */ +#define KORE_TOUCH_KEYS 24 + +/* the first Kore controller reports its touch sensors in this order */ +static const unsigned short keycode_kore1_touch[] = { + KEY_BRL_DOT4, + KEY_BRL_DOT8, + KEY_BRL_DOT3, + KEY_BRL_DOT7, + KEY_BRL_DOT2, + KEY_BRL_DOT6, + KEY_BRL_DOT1, + KEY_BRL_DOT5 +}; + #define MASCHINE_BUTTONS (42) #define MASCHINE_BUTTON(X) ((X) + BTN_MISC) #define MASCHINE_PADS (16) @@ -666,6 +681,12 @@ int snd_usb_caiaq_input_init(struct snd_usb_caiaqdev *cdev) input->absbit[BIT_WORD(ABS_MISC)] |= BIT_MASK(ABS_MISC); BUILD_BUG_ON(sizeof(cdev->keycode) < sizeof(keycode_kore)); memcpy(cdev->keycode, keycode_kore, sizeof(keycode_kore)); + BUILD_BUG_ON(KORE_TOUCH_KEYS + ARRAY_SIZE(keycode_kore1_touch) > + ARRAY_SIZE(keycode_kore)); + if (cdev->chip.usb_id == + USB_ID(USB_VID_NATIVEINSTRUMENTS, USB_PID_KORECONTROLLER)) + memcpy(cdev->keycode + KORE_TOUCH_KEYS, keycode_kore1_touch, + sizeof(keycode_kore1_touch)); input->keycodemax = ARRAY_SIZE(keycode_kore); input_set_abs_params(input, ABS_HAT0X, 0, 999, 0, 10); input_set_abs_params(input, ABS_HAT0Y, 0, 999, 0, 10); diff --git a/sound/usb/caiaq/midi.c b/sound/usb/caiaq/midi.c index 18529484c8dc..b7d7d24937a7 100644 --- a/sound/usb/caiaq/midi.c +++ b/sound/usb/caiaq/midi.c @@ -79,6 +79,7 @@ static void snd_usb_caiaq_midi_output_trigger(struct snd_rawmidi_substream *subs { struct snd_usb_caiaqdev *cdev = substream->rmidi->private_data; + guard(spinlock_irqsave)(&cdev->midi_lock); if (up) { cdev->midi_out_substream = substream; if (!cdev->midi_out_active) @@ -151,6 +152,7 @@ void snd_usb_caiaq_midi_output_done(struct urb* urb) { struct snd_usb_caiaqdev *cdev = urb->context; + guard(spinlock_irqsave)(&cdev->midi_lock); cdev->midi_out_active = 0; if (urb->status != 0) return; diff --git a/sound/usb/line6/capture.c b/sound/usb/line6/capture.c index 32922b7f2ffc..626274e503c7 100644 --- a/sound/usb/line6/capture.c +++ b/sound/usb/line6/capture.c @@ -129,7 +129,8 @@ void line6_capture_copy(struct snd_line6_pcm *line6pcm, char *fbuf, int fsize) } else { /* copy single chunk */ memcpy(runtime->dma_area + - line6pcm->in.pos_done * bytes_per_frame, fbuf, fsize); + line6pcm->in.pos_done * bytes_per_frame, fbuf, + frames * bytes_per_frame); } line6pcm->in.pos_done += frames; diff --git a/sound/usb/line6/pcm.c b/sound/usb/line6/pcm.c index b4c594add1ae..d17baf7761c6 100644 --- a/sound/usb/line6/pcm.c +++ b/sound/usb/line6/pcm.c @@ -155,7 +155,7 @@ static int line6_buffer_acquire(struct snd_line6_pcm *line6pcm, /* Invoked multiple times in a row so allocate once only */ if (!test_and_set_bit(type, &pstr->opened) && !pstr->buffer) { pstr->buffer = - kmalloc(array3_size(line6pcm->line6->iso_buffers, + kzalloc(array3_size(line6pcm->line6->iso_buffers, LINE6_ISO_PACKETS, pkt_size), GFP_KERNEL); if (!pstr->buffer) @@ -562,7 +562,11 @@ int line6_init_pcm(struct usb_line6 *line6, line6pcm->max_packet_size_out = usb_maxpacket(line6->usbdev, usb_sndisocpipe(line6->usbdev, ep_write)); - if (!line6pcm->max_packet_size_in || !line6pcm->max_packet_size_out) { + /* reject max packet sizes smaller than bytes-per-frame; + * (the magic number 6 is taken from the playback case) + */ + if (line6pcm->max_packet_size_in < 6 || + line6pcm->max_packet_size_out < 6) { dev_err(line6pcm->line6->ifcdev, "cannot get proper max packet size\n"); return -EINVAL; diff --git a/sound/usb/mixer.c b/sound/usb/mixer.c index ecaa8bc08d7c..9d0c5665639e 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; @@ -430,7 +445,7 @@ int snd_usb_get_cur_mix_value(struct usb_mixer_elem_info *cval, { int err; - if (cval->cached & BIT(channel)) { + if (test_bit(channel, cval->cached)) { *value = cval->cache_val[index]; return 0; } @@ -447,7 +462,7 @@ int snd_usb_get_cur_mix_value(struct usb_mixer_elem_info *cval, cval->control, channel, err); return err; } - cval->cached |= BIT(channel); + set_bit(channel, cval->cached); cval->cache_val[index] = *value; return 0; } @@ -478,6 +493,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); @@ -532,7 +551,7 @@ int snd_usb_set_cur_mix_value(struct usb_mixer_elem_info *cval, int channel, value); if (err < 0) return err; - cval->cached |= BIT(channel); + set_bit(channel, cval->cached); cval->cache_val[index] = value; return 0; } @@ -577,20 +596,25 @@ static int check_matrix_bitmap(unsigned char *bmap, /* * add an alsa control element - * search and increment the index until an empty slot is found. + * when @look_for_empty is set, search and increment the index until an empty + * slot is found. * * if failed, give up and free the control instance. */ int snd_usb_mixer_add_list(struct usb_mixer_elem_list *list, struct snd_kcontrol *kctl, - bool is_std_info) + bool is_std_info, + bool look_for_empty) { struct usb_mixer_interface *mixer = list->mixer; int err; - while (snd_ctl_find_id(mixer->chip->card, &kctl->id)) - kctl->id.index++; + if (look_for_empty) { + while (snd_ctl_find_id(mixer->chip->card, &kctl->id)) + kctl->id.index++; + } + err = snd_ctl_add(mixer->chip->card, kctl); if (err < 0) { usb_audio_dbg(mixer->chip, "cannot add control (err = %d)\n", @@ -1398,7 +1422,7 @@ static int get_min_max_with_quirks(struct usb_mixer_elem_info *cval, * properly. */ if (ret) - cval->cached = 0; + bitmap_zero(cval->cached, MAX_CHANNELS + 1); cval->initialized = 1; } @@ -1480,6 +1504,7 @@ static int mixer_ctl_feature_info(struct snd_kcontrol *kcontrol, struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol); int ret; + guard(mutex)(&cval->head.mixer->lock); if (cval->val_type == USB_MIXER_BOOLEAN || cval->val_type == USB_MIXER_INV_BOOLEAN) uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN; @@ -1514,6 +1539,7 @@ static int mixer_ctl_feature_get(struct snd_kcontrol *kcontrol, struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol); int c, cnt, val, err; + guard(mutex)(&cval->head.mixer->lock); ucontrol->value.integer.value[0] = cval->min; if (cval->cmask) { cnt = 0; @@ -1544,10 +1570,12 @@ static int mixer_ctl_feature_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol); - int max_val = get_max_exposed(cval); + int max_val; int c, cnt, val, oval, err; int changed = 0; + guard(mutex)(&cval->head.mixer->lock); + max_val = get_max_exposed(cval); if (cval->cmask) { cnt = 0; for (c = 0; c < MAX_CHANNELS; c++) { @@ -1595,6 +1623,7 @@ static int mixer_ctl_master_bool_get(struct snd_kcontrol *kcontrol, struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol); int val, err; + guard(mutex)(&cval->head.mixer->lock); err = snd_usb_get_cur_mix_value(cval, 0, 0, &val); if (err < 0) return filter_error(cval, err); @@ -2326,7 +2355,7 @@ static bool mixer_bitmap_overflow(struct uac_mixer_unit_descriptor *desc, */ static void build_mixer_unit_ctl(struct mixer_build *state, struct uac_mixer_unit_descriptor *desc, - int in_pin, int in_ch, int num_outs, + int in_ch, int num_outs, int unitid, struct usb_audio_term *iterm) { struct usb_mixer_elem_info *cval; @@ -2345,6 +2374,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); @@ -2417,24 +2450,13 @@ static int parse_audio_input_terminal(struct mixer_build *state, int unitid, /* * parse a mixer unit */ -static int parse_audio_mixer_unit(struct mixer_build *state, int unitid, - void *raw_desc) +/* UAC1 mixer unit */ +static int parse_audio_mixer_unit_v1(struct mixer_build *state, int unitid, + int input_pins, int num_outs, + struct uac_mixer_unit_descriptor *desc) { - struct uac_mixer_unit_descriptor *desc = raw_desc; struct usb_audio_term iterm; - int input_pins, num_ins, num_outs; - int pin, ich, err; - - err = uac_mixer_unit_get_channels(state, desc); - if (err < 0) { - usb_audio_err(state->chip, - "invalid MIXER UNIT descriptor %d\n", - unitid); - return err; - } - - num_outs = err; - input_pins = desc->bNrInPins; + int num_ins, pin, ich, och, err; num_ins = 0; ich = 0; @@ -2453,25 +2475,90 @@ static int parse_audio_mixer_unit(struct mixer_build *state, int unitid, num_ins, num_outs)) break; for (; ich < num_ins; ich++) { - int och, ich_has_controls = 0; - for (och = 0; och < num_outs; och++) { __u8 *c = uac_mixer_unit_bmControls(desc, state->mixer->protocol); - if (check_matrix_bitmap(c, ich, och, num_outs)) { - ich_has_controls = 1; + if (check_matrix_bitmap(c, ich, och, num_outs)) break; - } } - if (ich_has_controls) - build_mixer_unit_ctl(state, desc, pin, ich, num_outs, + if (och < num_outs) + build_mixer_unit_ctl(state, desc, ich, num_outs, unitid, &iterm); } } return 0; } +/* UAC2/UAC3 mixer unit */ +static int parse_audio_mixer_unit_v2(struct mixer_build *state, int unitid, + int input_pins, int num_outs, + struct uac_mixer_unit_descriptor *desc) +{ + struct usb_audio_term iterm; + int pin, och, err; + + if (input_pins * num_outs > 256 || + mixer_bitmap_overflow(desc, state->mixer->protocol, + input_pins, num_outs)) { + usb_audio_err(state->chip, + "invalid channels for MIXER UNIT %d: input=%d, output=%d\n", + unitid, input_pins, num_outs); + return -EINVAL; + } + + for (pin = 0; pin < input_pins; pin++) { + err = parse_audio_unit(state, desc->baSourceID[pin]); + if (err < 0) + continue; + if (!num_outs) + continue; + err = check_input_term(state, desc->baSourceID[pin], &iterm); + if (err < 0) + return err; + + for (och = 0; och < num_outs; och++) { + __u8 *c = uac_mixer_unit_bmControls(desc, + state->mixer->protocol); + + if (check_matrix_bitmap(c, pin, och, num_outs)) + break; + } + if (och < num_outs) + build_mixer_unit_ctl(state, desc, pin, num_outs, + unitid, &iterm); + } + return 0; +} + +static int parse_audio_mixer_unit(struct mixer_build *state, int unitid, + void *raw_desc) +{ + struct uac_mixer_unit_descriptor *desc = raw_desc; + int num_outs; + + num_outs = uac_mixer_unit_get_channels(state, desc); + if (num_outs < 0) { + usb_audio_err(state->chip, + "invalid MIXER UNIT descriptor %d\n", + unitid); + return num_outs; + } + + switch (state->mixer->protocol) { + case UAC_VERSION_1: + default: + return parse_audio_mixer_unit_v1(state, unitid, + desc->bNrInPins, num_outs, + desc); + case UAC_VERSION_2: + case UAC_VERSION_3: + return parse_audio_mixer_unit_v2(state, unitid, + desc->bNrInPins, num_outs, + desc); + } +} + /* * Processing Unit / Extension Unit */ @@ -2483,6 +2570,7 @@ static int mixer_ctl_procunit_get(struct snd_kcontrol *kcontrol, struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol); int err, val; + guard(mutex)(&cval->head.mixer->lock); err = get_cur_ctl_value(cval, cval->control << 8, &val); if (err < 0) { ucontrol->value.integer.value[0] = cval->min; @@ -2500,6 +2588,7 @@ static int mixer_ctl_procunit_put(struct snd_kcontrol *kcontrol, struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol); int val, oval, err; + guard(mutex)(&cval->head.mixer->lock); err = get_cur_ctl_value(cval, cval->control << 8, &oval); if (err < 0) return filter_error(cval, err); @@ -2851,6 +2940,7 @@ static int mixer_ctl_selector_get(struct snd_kcontrol *kcontrol, struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol); int val, err; + guard(mutex)(&cval->head.mixer->lock); err = get_cur_ctl_value(cval, cval->control << 8, &val); if (err < 0) { ucontrol->value.enumerated.item[0] = 0; @@ -2868,6 +2958,7 @@ static int mixer_ctl_selector_put(struct snd_kcontrol *kcontrol, struct usb_mixer_elem_info *cval = snd_kcontrol_chip(kcontrol); int val, oval, err; + guard(mutex)(&cval->head.mixer->lock); err = get_cur_ctl_value(cval, cval->control << 8, &oval); if (err < 0) return filter_error(cval, err); @@ -3140,6 +3231,7 @@ static void snd_usb_mixer_free(struct usb_mixer_interface *mixer) } usb_free_urb(mixer->rc_urb); kfree(mixer->rc_setup_packet); + mutex_destroy(&mixer->lock); kfree(mixer); } @@ -3550,7 +3642,7 @@ void snd_usb_mixer_notify_id(struct usb_mixer_interface *mixer, int unitid) info = mixer_elem_list_to_info(list); /* invalidate cache, so the value is read from the device */ if (!info->get_cur_broken) - info->cached = 0; + bitmap_zero(info->cached, MAX_CHANNELS + 1); snd_ctl_notify(mixer->chip->card, SNDRV_CTL_EVENT_MASK_VALUE, &list->kctl->id); } @@ -3617,7 +3709,7 @@ static void snd_usb_mixer_interrupt_v2(struct usb_mixer_interface *mixer, __u8 channel = value & 0xff; unsigned int count = 0; - if (channel >= MAX_CHANNELS) { + if (channel > MAX_CHANNELS) { usb_audio_dbg(mixer->chip, "%s(): bogus channel number %d\n", __func__, channel); @@ -3649,9 +3741,9 @@ static void snd_usb_mixer_interrupt_v2(struct usb_mixer_interface *mixer, /* invalidate cache, so the value is read from the device */ if (!info->get_cur_broken) { if (channel) - info->cached &= ~BIT(channel); + clear_bit(channel, info->cached); else /* master channel */ - info->cached = 0; + bitmap_zero(info->cached, MAX_CHANNELS + 1); } snd_ctl_notify(mixer->chip->card, SNDRV_CTL_EVENT_MASK_VALUE, @@ -3784,6 +3876,8 @@ int snd_usb_create_mixer(struct snd_usb_audio *chip, int ctrlif) return -ENOMEM; } + mutex_init(&mixer->lock); + mixer->hostif = &usb_ifnum_to_if(chip->dev, ctrlif)->altsetting[0]; switch (get_iface_desc(mixer->hostif)->bInterfaceProtocol) { case UAC_VERSION_1: @@ -3887,7 +3981,7 @@ static int restore_mixer_value(struct usb_mixer_elem_list *list) for (c = 0; c < MAX_CHANNELS; c++) { if (!(cval->cmask & BIT(c))) continue; - if (cval->cached & BIT(c + 1)) { + if (test_bit(c + 1, cval->cached)) { err = snd_usb_set_cur_mix_value(cval, c + 1, idx, cval->cache_val[idx]); if (err < 0) @@ -3897,7 +3991,7 @@ static int restore_mixer_value(struct usb_mixer_elem_list *list) } } else { /* master */ - if (cval->cached) + if (test_bit(0, cval->cached)) snd_usb_set_cur_mix_value(cval, 0, 0, *cval->cache_val); } diff --git a/sound/usb/mixer.h b/sound/usb/mixer.h index 037b446d8b6f..c40f832852be 100644 --- a/sound/usb/mixer.h +++ b/sound/usb/mixer.h @@ -18,6 +18,7 @@ struct usb_mixer_interface { struct usb_host_interface *hostif; struct list_head list; unsigned int ignore_ctl_error; + struct mutex lock; /* lock for feature unit callbacks */ /* UAC2 status interrupt endpoint; owned by mixer.c */ struct urb *urb; /* array[MAX_ID_ELEMS], indexed by unit id */ @@ -92,11 +93,13 @@ struct usb_mixer_elem_info { int min, max, res; int max_exposed; /* control API exposes the value in 0..max_exposed */ int dBmin, dBmax; - int cached; + DECLARE_BITMAP(cached, MAX_CHANNELS + 1); int cache_val[MAX_CHANNELS]; u8 initialized; u8 min_mute; u8 get_cur_broken; + u8 num_outputs; + bool v2_mixer; void *private_data; }; @@ -110,10 +113,11 @@ int snd_usb_mixer_set_ctl_value(struct usb_mixer_elem_info *cval, int snd_usb_mixer_add_list(struct usb_mixer_elem_list *list, struct snd_kcontrol *kctl, - bool is_std_info); + bool is_std_info, + bool look_for_empty); #define snd_usb_mixer_add_control(list, kctl) \ - snd_usb_mixer_add_list(list, kctl, true) + snd_usb_mixer_add_list(list, kctl, true, true) void snd_usb_mixer_elem_init_std(struct usb_mixer_elem_list *list, struct usb_mixer_interface *mixer, diff --git a/sound/usb/mixer_quirks.c b/sound/usb/mixer_quirks.c index fc622eb95dc5..5755771247f9 100644 --- a/sound/usb/mixer_quirks.c +++ b/sound/usb/mixer_quirks.c @@ -166,7 +166,7 @@ static int add_single_ctl_with_resume(struct usb_mixer_interface *mixer, } kctl->private_free = snd_usb_mixer_elem_free; /* don't use snd_usb_mixer_add_control() here, this is a special list element */ - return snd_usb_mixer_add_list(list, kctl, false); + return snd_usb_mixer_add_list(list, kctl, false, true); } /* diff --git a/sound/usb/mixer_scarlett.c b/sound/usb/mixer_scarlett.c index 369968565c19..6808730ef047 100644 --- a/sound/usb/mixer_scarlett.c +++ b/sound/usb/mixer_scarlett.c @@ -292,7 +292,7 @@ static int forte_get_ctl_value(struct usb_mixer_elem_info *elem, int *value) /* Device may not support reading input controls. * Return cached value or default to avoid blocking module load. */ - if (elem->cached) + if (test_bit(0, elem->cached)) *value = elem->cache_val[0]; else *value = 0; /* Default: first option */ @@ -353,7 +353,7 @@ static int forte_input_gain_put(struct snd_kcontrol *kctl, err = forte_set_ctl_value(elem, val); if (err < 0) return err; - elem->cached |= 1; + set_bit(0, elem->cached); elem->cache_val[0] = val; return 1; } @@ -364,7 +364,7 @@ static int forte_input_gain_resume(struct usb_mixer_elem_list *list) { struct usb_mixer_elem_info *elem = mixer_elem_list_to_info(list); - if (elem->cached) + if (test_bit(0, elem->cached)) forte_set_ctl_value(elem, *elem->cache_val); return 0; } @@ -405,7 +405,7 @@ static int forte_ctl_enum_put(struct snd_kcontrol *kctl, err = forte_set_ctl_value(elem, val); if (err < 0) return err; - elem->cached |= 1; + set_bit(0, elem->cached); elem->cache_val[0] = val; return 1; } @@ -416,7 +416,7 @@ static int forte_ctl_enum_resume(struct usb_mixer_elem_list *list) { struct usb_mixer_elem_info *elem = mixer_elem_list_to_info(list); - if (elem->cached) + if (test_bit(0, elem->cached)) forte_set_ctl_value(elem, *elem->cache_val); return 0; } @@ -454,7 +454,7 @@ static int forte_ctl_switch_put(struct snd_kcontrol *kctl, err = forte_set_ctl_value(elem, val); if (err < 0) return err; - elem->cached |= 1; + set_bit(0, elem->cached); elem->cache_val[0] = val; return 1; } @@ -465,7 +465,7 @@ static int forte_ctl_switch_resume(struct usb_mixer_elem_list *list) { struct usb_mixer_elem_info *elem = mixer_elem_list_to_info(list); - if (elem->cached) + if (test_bit(0, elem->cached)) forte_set_ctl_value(elem, *elem->cache_val); return 0; } @@ -532,7 +532,7 @@ static int scarlett_ctl_resume(struct usb_mixer_elem_list *list) int i; for (i = 0; i < elem->channels; i++) - if (elem->cached & (1 << i)) + if (test_bit(i, elem->cached)) snd_usb_set_cur_mix_value(elem, i, i, elem->cache_val[i]); return 0; @@ -692,7 +692,7 @@ static int scarlett_ctl_enum_resume(struct usb_mixer_elem_list *list) { struct usb_mixer_elem_info *elem = mixer_elem_list_to_info(list); - if (elem->cached) + if (test_bit(0, elem->cached)) snd_usb_set_cur_mix_value(elem, 0, 0, *elem->cache_val); return 0; } diff --git a/sound/usb/mixer_us16x08.c b/sound/usb/mixer_us16x08.c index 14fb1ad764a7..18e8c2bd2678 100644 --- a/sound/usb/mixer_us16x08.c +++ b/sound/usb/mixer_us16x08.c @@ -189,6 +189,7 @@ static int snd_us16x08_route_get(struct snd_kcontrol *kcontrol, struct usb_mixer_elem_info *elem = snd_kcontrol_chip(kcontrol); int index = ucontrol->id.index; + guard(mutex)(&elem->head.mixer->lock); /* route has no bias */ ucontrol->value.enumerated.item[0] = elem->cache_val[index]; @@ -204,6 +205,7 @@ static int snd_us16x08_route_put(struct snd_kcontrol *kcontrol, char buf[sizeof(route_msg)]; int val, val_org, err; + guard(mutex)(&elem->head.mixer->lock); /* get the new value (no bias for routes) */ val = ucontrol->value.enumerated.item[0]; @@ -236,7 +238,7 @@ static int snd_us16x08_route_put(struct snd_kcontrol *kcontrol, return err; } - elem->cached |= 1 << index; + set_bit(index, elem->cached); elem->cache_val[index] = val; return 1; } @@ -258,6 +260,7 @@ static int snd_us16x08_master_get(struct snd_kcontrol *kcontrol, struct usb_mixer_elem_info *elem = snd_kcontrol_chip(kcontrol); int index = ucontrol->id.index; + guard(mutex)(&elem->head.mixer->lock); ucontrol->value.integer.value[0] = elem->cache_val[index]; return 0; @@ -272,6 +275,7 @@ static int snd_us16x08_master_put(struct snd_kcontrol *kcontrol, int val, err; int index = ucontrol->id.index; + guard(mutex)(&elem->head.mixer->lock); /* new control value incl. bias*/ val = ucontrol->value.integer.value[0]; @@ -295,7 +299,7 @@ static int snd_us16x08_master_put(struct snd_kcontrol *kcontrol, return err; } - elem->cached |= 1 << index; + set_bit(index, elem->cached); elem->cache_val[index] = val; return 1; } @@ -310,6 +314,7 @@ static int snd_us16x08_bus_put(struct snd_kcontrol *kcontrol, val = ucontrol->value.integer.value[0]; + guard(mutex)(&elem->head.mixer->lock); /* prepare the message buffer from template */ switch (elem->head.id) { case SND_US16X08_ID_BYPASS: @@ -336,7 +341,7 @@ static int snd_us16x08_bus_put(struct snd_kcontrol *kcontrol, return err; } - elem->cached |= 1; + set_bit(0, elem->cached); elem->cache_val[0] = val; return 1; } @@ -346,6 +351,7 @@ static int snd_us16x08_bus_get(struct snd_kcontrol *kcontrol, { struct usb_mixer_elem_info *elem = snd_kcontrol_chip(kcontrol); + guard(mutex)(&elem->head.mixer->lock); switch (elem->head.id) { case SND_US16X08_ID_BUSS_OUT: ucontrol->value.integer.value[0] = elem->cache_val[0]; @@ -368,6 +374,7 @@ static int snd_us16x08_channel_get(struct snd_kcontrol *kcontrol, struct usb_mixer_elem_info *elem = snd_kcontrol_chip(kcontrol); int index = ucontrol->id.index; + guard(mutex)(&elem->head.mixer->lock); ucontrol->value.integer.value[0] = elem->cache_val[index]; return 0; @@ -382,6 +389,7 @@ static int snd_us16x08_channel_put(struct snd_kcontrol *kcontrol, int val, err; int index = ucontrol->id.index; + guard(mutex)(&elem->head.mixer->lock); val = ucontrol->value.integer.value[0]; /* sanity check */ @@ -404,7 +412,7 @@ static int snd_us16x08_channel_put(struct snd_kcontrol *kcontrol, return err; } - elem->cached |= 1 << index; + set_bit(index, elem->cached); elem->cache_val[index] = val; return 1; } @@ -428,6 +436,7 @@ static int snd_us16x08_comp_get(struct snd_kcontrol *kcontrol, int index = ucontrol->id.index; int val_idx = COMP_STORE_IDX(elem->head.id); + guard(mutex)(&elem->head.mixer->lock); ucontrol->value.integer.value[0] = store->val[val_idx][index]; return 0; @@ -445,6 +454,7 @@ static int snd_us16x08_comp_put(struct snd_kcontrol *kcontrol, int threshold, ratio, attack, release, gain, switch_on; int err; + guard(mutex)(&elem->head.mixer->lock); val = ucontrol->value.integer.value[0]; /* sanity check */ @@ -508,7 +518,7 @@ static int snd_us16x08_comp_put(struct snd_kcontrol *kcontrol, } store->val[val_idx][index] = val; - elem->cached |= 1 << index; + set_bit(index, elem->cached); elem->cache_val[index] = val; return 1; } @@ -521,6 +531,7 @@ static int snd_us16x08_eqswitch_get(struct snd_kcontrol *kcontrol, struct snd_us16x08_eq_store *store = elem->private_data; int index = ucontrol->id.index; + guard(mutex)(&elem->head.mixer->lock); /* get low switch from cache is enough, cause all bands are together */ val = store->val[EQ_STORE_BAND_IDX(elem->head.id)] [EQ_STORE_PARAM_IDX(elem->head.id)][index]; @@ -540,6 +551,7 @@ static int snd_us16x08_eqswitch_put(struct snd_kcontrol *kcontrol, int val, err = 0; int b_idx; + guard(mutex)(&elem->head.mixer->lock); /* new control value incl. bias*/ val = ucontrol->value.integer.value[0] + SND_US16X08_KCBIAS(kcontrol); @@ -567,7 +579,7 @@ static int snd_us16x08_eqswitch_put(struct snd_kcontrol *kcontrol, return err; } - elem->cached |= 1 << index; + set_bit(index, elem->cached); elem->cache_val[index] = val; return 1; } @@ -582,6 +594,7 @@ static int snd_us16x08_eq_get(struct snd_kcontrol *kcontrol, int b_idx = EQ_STORE_BAND_IDX(elem->head.id) - 1; int p_idx = EQ_STORE_PARAM_IDX(elem->head.id); + guard(mutex)(&elem->head.mixer->lock); val = store->val[b_idx][p_idx][index]; ucontrol->value.integer.value[0] = val; @@ -601,6 +614,7 @@ static int snd_us16x08_eq_put(struct snd_kcontrol *kcontrol, int b_idx = EQ_STORE_BAND_IDX(elem->head.id) - 1; int p_idx = EQ_STORE_PARAM_IDX(elem->head.id); + guard(mutex)(&elem->head.mixer->lock); val = ucontrol->value.integer.value[0]; /* sanity check */ @@ -631,7 +645,7 @@ static int snd_us16x08_eq_put(struct snd_kcontrol *kcontrol, store->val[b_idx][p_idx][index] = val; /* store new value in EQ band cache */ - elem->cached |= 1 << index; + set_bit(index, elem->cached); elem->cache_val[index] = val; return 1; } @@ -729,6 +743,7 @@ static int snd_us16x08_meter_get(struct snd_kcontrol *kcontrol, struct snd_us16x08_meter_store *store = elem->private_data; u8 meter_urb[64] = {0}; + guard(mutex)(&elem->head.mixer->lock); switch (kcontrol->private_value) { case 0: { char tmp[sizeof(mix_init_msg1)]; @@ -788,6 +803,7 @@ static int snd_us16x08_meter_put(struct snd_kcontrol *kcontrol, struct snd_us16x08_meter_store *store = elem->private_data; int val; + guard(mutex)(&elem->head.mixer->lock); val = ucontrol->value.integer.value[0]; /* sanity check */ @@ -1118,7 +1134,8 @@ static int add_new_ctl(struct usb_mixer_interface *mixer, strscpy(kctl->id.name, name, sizeof(kctl->id.name)); - err = snd_usb_mixer_add_control(&elem->head, kctl); + /* look_for_empty=false, as we want the fixed id.index as channel */ + err = snd_usb_mixer_add_list(&elem->head, kctl, true, false); if (err < 0) return err; @@ -1352,7 +1369,7 @@ int snd_us16x08_controls_create(struct usb_mixer_interface *mixer) } for (i = 0; i < 8; i++) elem->cache_val[i] = i < 2 ? i : i + 2; - elem->cached = 0xff; + bitmap_set(elem->cached, 0, 8); /* create compressor mixer elements */ comp_store = snd_us16x08_create_comp_store(); @@ -1374,7 +1391,7 @@ int snd_us16x08_controls_create(struct usb_mixer_interface *mixer) if (err < 0) return err; elem->cache_val[0] = master_controls[i].default_val; - elem->cached = 1; + set_bit(0, elem->cached); } /* add channel controls */ @@ -1394,7 +1411,7 @@ int snd_us16x08_controls_create(struct usb_mixer_interface *mixer) elem->cache_val[j] = channel_controls[i].default_val; } - elem->cached = 0xffff; + bitmap_set(elem->cached, 0, SND_US16X08_MAX_CHANNELS); } /* create eq store */ diff --git a/sound/usb/quirks-table.h b/sound/usb/quirks-table.h index 0426cbda314b..4c0bc2dd7d3e 100644 --- a/sound/usb/quirks-table.h +++ b/sound/usb/quirks-table.h @@ -2813,6 +2813,7 @@ YAMAHA_DEVICE(0x7010, "UB99"), .rates = SNDRV_PCM_RATE_96000, .ep_attr = USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ASYNC, + .datainterval = 1, .rate_min = 96000, .rate_max = 96000, .nr_rates = 1, @@ -2835,6 +2836,7 @@ YAMAHA_DEVICE(0x7010, "UB99"), .rates = SNDRV_PCM_RATE_96000, .ep_attr = USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ASYNC, + .datainterval = 1, .rate_min = 96000, .rate_max = 96000, .nr_rates = 1, diff --git a/sound/usb/quirks.c b/sound/usb/quirks.c index b96cb3421cc1..fbda7fa543ab 100644 --- a/sound/usb/quirks.c +++ b/sound/usb/quirks.c @@ -1705,8 +1705,15 @@ int snd_usb_apply_boot_quirk_once(struct usb_device *dev, } /* Behringer devices may need explicit device descriptor read at boot */ - if (USB_ID_VENDOR(id) == 0x1397) + if (USB_ID_VENDOR(id) == 0x1397) { + /* the quirk seems breaking on some Behringer devices */ + switch (id) { + case USB_ID(0x1397, 0x0508): /* UMC204HD */ + case USB_ID(0x1397, 0x0509): /* UMC404HD */ + return 0; + } return snd_usb_cm1a_boot_quirk(dev); + } return 0; } diff --git a/sound/usb/usx2y/us122l.c b/sound/usb/usx2y/us122l.c index 9b4ec9bdc138..6e491736ca5b 100644 --- a/sound/usb/usx2y/us122l.c +++ b/sound/usb/usx2y/us122l.c @@ -204,7 +204,7 @@ static int usb_stream_hwdep_mmap(struct snd_hwdep *hw, } area->vm_ops = &usb_stream_hwdep_vm_ops; - vm_flags_set(area, VM_DONTDUMP); + vm_flags_set(area, VM_MIXEDMAP | VM_DONTDUMP); if (!read) vm_flags_set(area, VM_DONTEXPAND); area->vm_private_data = us122l; diff --git a/sound/virtio/virtio_pcm.h b/sound/virtio/virtio_pcm.h index 368dafa5df3f..8837dfc12828 100644 --- a/sound/virtio/virtio_pcm.h +++ b/sound/virtio/virtio_pcm.h @@ -118,6 +118,8 @@ int virtsnd_pcm_msg_alloc(struct virtio_pcm_substream *vss, void virtsnd_pcm_msg_free(struct virtio_pcm_substream *vss); +void virtsnd_pcm_msg_reset(struct virtio_pcm_substream *vss); + int virtsnd_pcm_msg_send(struct virtio_pcm_substream *vss, unsigned long offset, unsigned long bytes); diff --git a/sound/virtio/virtio_pcm_msg.c b/sound/virtio/virtio_pcm_msg.c index a5c4e7027717..72103f606716 100644 --- a/sound/virtio/virtio_pcm_msg.c +++ b/sound/virtio/virtio_pcm_msg.c @@ -182,6 +182,25 @@ void virtsnd_pcm_msg_free(struct virtio_pcm_substream *vss) vss->nmsgs = 0; } +/** + * virtsnd_pcm_msg_reset() - Reset the fill level of all I/O messages. + * @vss: VirtIO PCM substream. + * + * Messages that were only partially filled by the application when the + * substream was stopped are never sent to the device, so their length must be + * cleared before the substream is started again. + * + * Context: Any context. Takes and releases the VirtIO substream spinlock. + */ +void virtsnd_pcm_msg_reset(struct virtio_pcm_substream *vss) +{ + unsigned int i; + + guard(spinlock_irqsave)(&vss->lock); + for (i = 0; vss->msgs && i < vss->nmsgs; ++i) + vss->msgs[i]->length = 0; +} + /** * virtsnd_pcm_msg_send() - Send asynchronous I/O messages. * @vss: VirtIO PCM substream. diff --git a/sound/virtio/virtio_pcm_ops.c b/sound/virtio/virtio_pcm_ops.c index 1105e7ff3523..1091100a4c98 100644 --- a/sound/virtio/virtio_pcm_ops.c +++ b/sound/virtio/virtio_pcm_ops.c @@ -299,6 +299,7 @@ static int virtsnd_pcm_prepare(struct snd_pcm_substream *substream) vss->xfer_xrun = false; vss->suspended = false; vss->msg_count = 0; + virtsnd_pcm_msg_reset(vss); memset(&vss->pcm_indirect, 0, sizeof(vss->pcm_indirect)); vss->pcm_indirect.sw_buffer_size = diff --git a/tools/bpf/bpftool/Documentation/bpftool-prog.rst b/tools/bpf/bpftool/Documentation/bpftool-prog.rst index 90fa2a48cc26..90fe8c61bf42 100644 --- a/tools/bpf/bpftool/Documentation/bpftool-prog.rst +++ b/tools/bpf/bpftool/Documentation/bpftool-prog.rst @@ -217,7 +217,14 @@ bpftool prog run *PROG* data_in *FILE* [data_out *FILE* [data_size_out *L*]] [ct bpftool prog profile *PROG* [duration *DURATION*] *METRICs* Profile *METRICs* for bpf program *PROG* for *DURATION* seconds or until user hits . *DURATION* is optional. If *DURATION* is not specified, - the profiling will run up to **UINT_MAX** seconds. + the profiling will run up to **UINT_MAX** seconds. Selected metrics form a + perf event group on each CPU so that ratios use counters scheduled over the + same intervals. Plain output scales each per-CPU metric value to correct + for perf event multiplexing. When **cycles** is selected, it also reports + cycles per program run. + + In JSON output, **value** is raw, **value_scaled** is scaled, and + **run_cnt** is the total number of program runs. bpftool prog help Print short help message. @@ -360,7 +367,7 @@ EXAMPLES :: 51397 run_cnt - 40176203 cycles (83.05%) + 40176203 cycles # 781.68 cycles per run (83.05%) 42518139 instructions # 1.06 insns per cycle (83.39%) 123 llc_misses # 2.89 LLC misses per million insns (83.15%) diff --git a/tools/bpf/bpftool/btf.c b/tools/bpf/bpftool/btf.c index c9589026da8d..bca0a3982f09 100644 --- a/tools/bpf/bpftool/btf.c +++ b/tools/bpf/bpftool/btf.c @@ -805,9 +805,13 @@ static int dump_btf_c(const struct btf *btf, if (sort_dump) datums = sort_btf_c(btf); - for (i = 1; i < cnt; i++) { + for (i = 0; i < cnt; i++) { int idx = datums ? datums[i].index : i; + /* type ID 0 is void, skip it */ + if (idx == 0) + continue; + err = btf_dump__dump_type(d, idx); if (err) goto done; diff --git a/tools/bpf/bpftool/common.c b/tools/bpf/bpftool/common.c index ef366ccc9650..f9b87efa7c9a 100644 --- a/tools/bpf/bpftool/common.c +++ b/tools/bpf/bpftool/common.c @@ -31,6 +31,7 @@ #include #include #include /* libbpf_num_possible_cpus */ +#include #include #include @@ -655,6 +656,45 @@ unsigned int get_possible_cpus(void) return cpus; } +int get_possible_cpu_ids(int **cpu_ids) +{ + const char *possible_cpus_file = "/sys/devices/system/cpu/possible"; + bool *mask = NULL; + int mask_sz, nr_cpus = 0; + int *ids = NULL; + int i, res; + + *cpu_ids = NULL; + + res = parse_cpu_mask_file(possible_cpus_file, &mask, &mask_sz); + if (res) { + p_err("failed to parse possible CPU mask: %s", strerror(-res)); + return res; + } + + for (i = 0; i < mask_sz; i++) + nr_cpus += mask[i]; + + ids = calloc(nr_cpus, sizeof(*ids)); + if (!ids) { + p_err("mem alloc failed"); + res = -ENOMEM; + goto out; + } + + for (i = 0, nr_cpus = 0; i < mask_sz; i++) { + if (mask[i]) + ids[nr_cpus++] = i; + } + *cpu_ids = ids; + ids = NULL; + res = nr_cpus; +out: + free(ids); + free(mask); + return res; +} + static char * ifindex_to_name_ns(__u32 ifindex, __u32 ns_dev, __u32 ns_ino, char *buf) { diff --git a/tools/bpf/bpftool/gen.c b/tools/bpf/bpftool/gen.c index a50540ef6521..ee680f7c2116 100644 --- a/tools/bpf/bpftool/gen.c +++ b/tools/bpf/bpftool/gen.c @@ -500,16 +500,6 @@ static void print_hex(const char *data, int data_sz) } } -static size_t bpf_map_mmap_sz(const struct bpf_map *map) -{ - long page_sz = sysconf(_SC_PAGE_SIZE); - size_t map_sz; - - map_sz = (size_t)roundup(bpf_map__value_size(map), 8) * bpf_map__max_entries(map); - map_sz = roundup(map_sz, page_sz); - return map_sz; -} - /* Emit type size asserts for all top-level fields in memory-mapped internal maps. */ static void codegen_asserts(struct bpf_object *obj, const char *obj_name) { @@ -686,8 +676,8 @@ static void codegen_destroy(struct bpf_object *obj, const char *obj_name) if (!get_map_ident(map, ident, sizeof(ident))) continue; if (is_skel_data(map, ident, sizeof(ident))) - printf("\tskel_free_map_data(skel->%1$s, skel->maps.%1$s.initial_value, %2$zu);\n", - ident, bpf_map_mmap_sz(map)); + printf("\tskel_free_map_data(skel->%1$s, skel->maps.%1$s.initial_value, %2$u, %3$u);\n", + ident, bpf_map__value_size(map), bpf_map__max_entries(map)); codegen("\ \n\ skel_closenz(skel->maps.%1$s.map_fd); \n\ @@ -771,13 +761,13 @@ static int gen_trace(struct bpf_object *obj, const char *obj_name, const char *h \n\ \"; \n\ \n\ - skel->%1$s = (__typeof__(skel->%1$s))skel_prep_map_data((void *)data, %2$zd,\n\ + skel->%1$s = (__typeof__(skel->%1$s))skel_prep_map_data((void *)data, %2$u, %3$u,\n\ sizeof(data) - 1);\n\ if (!skel->%1$s) \n\ goto cleanup; \n\ skel->maps.%1$s.initial_value = (__u64) (long) skel->%1$s;\n\ } \n\ - ", ident, bpf_map_mmap_sz(map)); + ", ident, bpf_map__value_size(map), bpf_map__max_entries(map)); } codegen("\ \n\ @@ -871,14 +861,14 @@ static int gen_trace(struct bpf_object *obj, const char *obj_name, const char *h if (bpf_map__type(map) == BPF_MAP_TYPE_PERCPU_ARRAY) { codegen("\ \n\ - err = skel_protect_map_data(skel->%1$s, &skel->maps.%1$s.initial_value, %2$zd);\n\ + err = skel_protect_map_data(skel->%1$s, &skel->maps.%1$s.initial_value, %2$u, %3$u);\n\ if (err) \n\ return err; \n\ #ifdef __KERNEL__ \n\ skel->%1$s = NULL; \n\ #endif \n\ ", - ident, bpf_map_mmap_sz(map)); + ident, bpf_map__value_size(map), bpf_map__max_entries(map)); continue; } @@ -890,11 +880,11 @@ static int gen_trace(struct bpf_object *obj, const char *obj_name, const char *h codegen("\ \n\ skel->%1$s = (__typeof__(skel->%1$s))skel_finalize_map_data(&skel->maps.%1$s.initial_value,\n\ - %2$zd, %3$s, skel->maps.%1$s.map_fd);\n\ + %2$u, %3$u, %4$s, skel->maps.%1$s.map_fd);\n\ if (!skel->%1$s) \n\ return -ENOMEM; \n\ ", - ident, bpf_map_mmap_sz(map), mmap_flags); + ident, bpf_map__value_size(map), bpf_map__max_entries(map), mmap_flags); } codegen("\ \n\ diff --git a/tools/bpf/bpftool/link.c b/tools/bpf/bpftool/link.c index 088d1d206065..5cffa2d283b4 100644 --- a/tools/bpf/bpftool/link.c +++ b/tools/bpf/bpftool/link.c @@ -364,7 +364,7 @@ show_kprobe_multi_json(struct bpf_link_info *info, json_writer_t *wtr) } jsonw_uint_field(json_wtr, "cookie", data[j].cookie); jsonw_end_object(json_wtr); - if (j++ == info->kprobe_multi.count) + if (++j == info->kprobe_multi.count) break; } jsonw_end_array(json_wtr); @@ -867,7 +867,7 @@ static void show_kprobe_multi_plain(struct bpf_link_info *info) else printf(" "); - if (j++ == info->kprobe_multi.count) + if (++j == info->kprobe_multi.count) break; } error: diff --git a/tools/bpf/bpftool/main.c b/tools/bpf/bpftool/main.c index c91e1a6e1a1e..7a0c214f08a0 100644 --- a/tools/bpf/bpftool/main.c +++ b/tools/bpf/bpftool/main.c @@ -365,7 +365,11 @@ static int do_batch(int argc, char **argv) if (json_output) jsonw_start_array(json_wtr); - while (fgets(buf, sizeof(buf), fp)) { + for (;;) { + errno = 0; + if (!fgets(buf, sizeof(buf), fp)) + break; + cp = strchr(buf, '#'); if (cp) *cp = '\0'; @@ -467,16 +471,6 @@ int main(int argc, char **argv) setlinebuf(stdout); -#ifdef USE_LIBCAP - /* Libcap < 2.63 hooks before main() to compute the number of - * capabilities of the running kernel, and doing so it calls prctl() - * which may fail and set errno to non-zero. - * Let's reset errno to make sure this does not interfere with the - * batch mode. - */ - errno = 0; -#endif - last_do_help = do_help; pretty_output = false; json_output = false; diff --git a/tools/bpf/bpftool/main.h b/tools/bpf/bpftool/main.h index 78b6e0ebb85d..6540b632a3ac 100644 --- a/tools/bpf/bpftool/main.h +++ b/tools/bpf/bpftool/main.h @@ -216,6 +216,7 @@ void print_hex_data_json(uint8_t *data, size_t len); unsigned int get_page_size(void); unsigned int get_possible_cpus(void); +int get_possible_cpu_ids(int **cpu_ids); const char * ifindex_to_arch(__u32 ifindex, __u64 ns_dev, __u64 ns_ino, const char **opt); diff --git a/tools/bpf/bpftool/map.c b/tools/bpf/bpftool/map.c index 684a8fb72414..20d59eab09a1 100644 --- a/tools/bpf/bpftool/map.c +++ b/tools/bpf/bpftool/map.c @@ -70,7 +70,7 @@ static void *alloc_value(struct bpf_map_info *info) static int do_dump_btf(const struct btf_dumper *d, struct bpf_map_info *map_info, void *key, - void *value) + void *value, const int *cpu_ids, int cpu_cnt) { __u32 value_id; int ret = 0; @@ -93,15 +93,15 @@ static int do_dump_btf(const struct btf_dumper *d, jsonw_name(d->jw, "value"); ret = btf_dumper_type(d, value_id, value); } else { - unsigned int i, n, step; + unsigned int step; + int i; jsonw_name(d->jw, "values"); jsonw_start_array(d->jw); - n = get_possible_cpus(); step = round_up(map_info->value_size, 8); - for (i = 0; i < n; i++) { + for (i = 0; i < cpu_cnt; i++) { jsonw_start_object(d->jw); - jsonw_int_field(d->jw, "cpu", i); + jsonw_int_field(d->jw, "cpu", cpu_ids[i]); jsonw_name(d->jw, "value"); ret = btf_dumper_type(d, value_id, value + i * step); jsonw_end_object(d->jw); @@ -130,7 +130,8 @@ static json_writer_t *get_btf_writer(void) } static void print_entry_json(struct bpf_map_info *info, unsigned char *key, - unsigned char *value, struct btf *btf) + unsigned char *value, struct btf *btf, + const int *cpu_ids, int cpu_cnt) { jsonw_start_object(json_wtr); @@ -150,12 +151,12 @@ static void print_entry_json(struct bpf_map_info *info, unsigned char *key, }; jsonw_name(json_wtr, "formatted"); - do_dump_btf(&d, info, key, value); + do_dump_btf(&d, info, key, value, cpu_ids, cpu_cnt); } } else { - unsigned int i, n, step; + unsigned int step; + int i; - n = get_possible_cpus(); step = round_up(info->value_size, 8); jsonw_name(json_wtr, "key"); @@ -163,10 +164,10 @@ static void print_entry_json(struct bpf_map_info *info, unsigned char *key, jsonw_name(json_wtr, "values"); jsonw_start_array(json_wtr); - for (i = 0; i < n; i++) { + for (i = 0; i < cpu_cnt; i++) { jsonw_start_object(json_wtr); - jsonw_int_field(json_wtr, "cpu", i); + jsonw_int_field(json_wtr, "cpu", cpu_ids[i]); jsonw_name(json_wtr, "value"); print_hex_data_json(value + i * step, @@ -183,7 +184,7 @@ static void print_entry_json(struct bpf_map_info *info, unsigned char *key, }; jsonw_name(json_wtr, "formatted"); - do_dump_btf(&d, info, key, value); + do_dump_btf(&d, info, key, value, cpu_ids, cpu_cnt); } } @@ -245,7 +246,7 @@ print_entry_error(struct bpf_map_info *map_info, void *key, int lookup_errno) } static void print_entry_plain(struct bpf_map_info *info, unsigned char *key, - unsigned char *value) + unsigned char *value, const int *cpu_ids, int cpu_cnt) { if (!map_is_per_cpu(info->type)) { bool single_line, break_names; @@ -273,9 +274,9 @@ static void print_entry_plain(struct bpf_map_info *info, unsigned char *key, printf("\n"); } else { - unsigned int i, n, step; + unsigned int step; + int i; - n = get_possible_cpus(); step = round_up(info->value_size, 8); if (info->key_size) { @@ -284,9 +285,9 @@ static void print_entry_plain(struct bpf_map_info *info, unsigned char *key, printf("\n"); } if (info->value_size) { - for (i = 0; i < n; i++) { - printf("value (CPU %02u):%c", - i, info->value_size > 16 ? '\n' : ' '); + for (i = 0; i < cpu_cnt; i++) { + printf("value (CPU %02d):%c", + cpu_ids[i], info->value_size > 16 ? '\n' : ' '); fprint_hex(stdout, value + i * step, info->value_size, " "); printf("\n"); @@ -742,7 +743,7 @@ static int do_show(int argc, char **argv) static int dump_map_elem(int fd, void *key, void *value, struct bpf_map_info *map_info, struct btf *btf, - json_writer_t *btf_wtr) + json_writer_t *btf_wtr, const int *cpu_ids, int cpu_cnt) { if (bpf_map_lookup_elem(fd, key, value)) { print_entry_error(map_info, key, errno); @@ -750,7 +751,7 @@ static int dump_map_elem(int fd, void *key, void *value, } if (json_output) { - print_entry_json(map_info, key, value, btf); + print_entry_json(map_info, key, value, btf, cpu_ids, cpu_cnt); } else if (btf) { struct btf_dumper d = { .btf = btf, @@ -758,9 +759,9 @@ static int dump_map_elem(int fd, void *key, void *value, .is_plain_text = true, }; - do_dump_btf(&d, map_info, key, value); + do_dump_btf(&d, map_info, key, value, cpu_ids, cpu_cnt); } else { - print_entry_plain(map_info, key, value); + print_entry_plain(map_info, key, value, cpu_ids, cpu_cnt); } return 0; @@ -833,6 +834,8 @@ map_dump(int fd, struct bpf_map_info *info, json_writer_t *wtr, void *key, *value, *prev_key; unsigned int num_elems = 0; struct btf *btf = NULL; + int *cpu_ids = NULL; + int cpu_cnt = 0; int err; key = malloc(info->key_size); @@ -845,6 +848,14 @@ map_dump(int fd, struct bpf_map_info *info, json_writer_t *wtr, prev_key = NULL; + if (map_is_per_cpu(info->type)) { + cpu_cnt = get_possible_cpu_ids(&cpu_ids); + if (cpu_cnt < 0) { + err = cpu_cnt; + goto exit_free; + } + } + if (wtr) { err = get_map_kv_btf(info, &btf); if (err) { @@ -876,7 +887,8 @@ map_dump(int fd, struct bpf_map_info *info, json_writer_t *wtr, err = 0; break; } - if (!dump_map_elem(fd, key, value, info, btf, wtr)) + if (!dump_map_elem(fd, key, value, info, btf, wtr, + cpu_ids, cpu_cnt)) num_elems++; prev_key = key; } @@ -893,6 +905,7 @@ map_dump(int fd, struct bpf_map_info *info, json_writer_t *wtr, exit_free: free(key); free(value); + free(cpu_ids); free_map_kv_btf(btf); return err; @@ -1035,17 +1048,30 @@ static int do_update(int argc, char **argv) return err; } -static void print_key_value(struct bpf_map_info *info, void *key, - void *value) +static int print_key_value(struct bpf_map_info *info, void *key, + void *value) { json_writer_t *btf_wtr; struct btf *btf; + int *cpu_ids = NULL; + int cpu_cnt = 0; + int err = 0; - if (get_map_kv_btf(info, &btf)) - return; + if (map_is_per_cpu(info->type)) { + cpu_cnt = get_possible_cpu_ids(&cpu_ids); + + if (cpu_cnt < 0) { + err = cpu_cnt; + goto out; + } + } + + err = get_map_kv_btf(info, &btf); + if (err) + goto out; if (json_output) { - print_entry_json(info, key, value, btf); + print_entry_json(info, key, value, btf, cpu_ids, cpu_cnt); } else if (btf) { /* if here json_wtr wouldn't have been initialised, * so let's create separate writer for btf @@ -1055,7 +1081,7 @@ static void print_key_value(struct bpf_map_info *info, void *key, p_info("failed to create json writer for btf. falling back to plain output"); free_map_kv_btf(btf); btf = NULL; - print_entry_plain(info, key, value); + print_entry_plain(info, key, value, cpu_ids, cpu_cnt); } else { struct btf_dumper d = { .btf = btf, @@ -1063,13 +1089,16 @@ static void print_key_value(struct bpf_map_info *info, void *key, .is_plain_text = true, }; - do_dump_btf(&d, info, key, value); + do_dump_btf(&d, info, key, value, cpu_ids, cpu_cnt); jsonw_destroy(&btf_wtr); } } else { - print_entry_plain(info, key, value); + print_entry_plain(info, key, value, cpu_ids, cpu_cnt); } free_map_kv_btf(btf); +out: + free(cpu_ids); + return err; } static int do_lookup(int argc, char **argv) @@ -1114,7 +1143,7 @@ static int do_lookup(int argc, char **argv) } /* here means bpf_map_lookup_elem() succeeded */ - print_key_value(&info, key, value); + err = print_key_value(&info, key, value); exit_free: free(key); @@ -1404,7 +1433,7 @@ static int do_pop_dequeue(int argc, char **argv) goto exit_free; } - print_key_value(&info, key, value); + err = print_key_value(&info, key, value); exit_free: free(key); diff --git a/tools/bpf/bpftool/prog.c b/tools/bpf/bpftool/prog.c index a9f730d407a9..b454165e8cd0 100644 --- a/tools/bpf/bpftool/prog.c +++ b/tools/bpf/bpftool/prog.c @@ -1769,7 +1769,7 @@ static int load_with_options(int argc, char **argv, bool first_prog_only) } if (prog_type == BPF_PROG_TYPE_XDP && xdpmeta_ifindex) { - bpf_program__set_flags(pos, BPF_F_XDP_DEV_BOUND_ONLY); + bpf_program__set_flags(pos, bpf_program__flags(pos) | BPF_F_XDP_DEV_BOUND_ONLY); bpf_program__set_ifindex(pos, xdpmeta_ifindex); } else { bpf_program__set_ifindex(pos, offload_ifindex); @@ -2062,37 +2062,52 @@ static int do_profile(int argc, char **argv) #include "profiler.skel.h" +enum ratio_metric { + METRIC_NONE = -2, + METRIC_RUN_CNT = -1, + METRIC_CYCLES = 0, + METRIC_INSTRUCTIONS = 1, + METRIC_L1D_LOADS = 2, + METRIC_LLC_MISSES = 3, + METRIC_ITLB_MISSES = 4, + METRIC_DTLB_MISSES = 5, +}; + struct profile_metric { const char *name; struct bpf_perf_event_value val; + __u64 scaled_val; struct perf_event_attr attr; bool selected; /* calculate ratios like instructions per cycle */ - const int ratio_metric; /* 0 for N/A, 1 for index 0 (cycles) */ + const enum ratio_metric ratio_metric; const char *ratio_desc; const float ratio_mul; } metrics[] = { - { + [METRIC_CYCLES] = { .name = "cycles", .attr = { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES, .exclude_user = 1, }, + .ratio_metric = METRIC_RUN_CNT, + .ratio_desc = "cycles per run", + .ratio_mul = 1.0, }, - { + [METRIC_INSTRUCTIONS] = { .name = "instructions", .attr = { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS, .exclude_user = 1, }, - .ratio_metric = 1, + .ratio_metric = METRIC_CYCLES, .ratio_desc = "insns per cycle", .ratio_mul = 1.0, }, - { + [METRIC_L1D_LOADS] = { .name = "l1d_loads", .attr = { .type = PERF_TYPE_HW_CACHE, @@ -2102,8 +2117,9 @@ struct profile_metric { (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16), .exclude_user = 1, }, + .ratio_metric = METRIC_NONE, }, - { + [METRIC_LLC_MISSES] = { .name = "llc_misses", .attr = { .type = PERF_TYPE_HW_CACHE, @@ -2113,11 +2129,11 @@ struct profile_metric { (PERF_COUNT_HW_CACHE_RESULT_MISS << 16), .exclude_user = 1 }, - .ratio_metric = 2, + .ratio_metric = METRIC_INSTRUCTIONS, .ratio_desc = "LLC misses per million insns", .ratio_mul = 1e6, }, - { + [METRIC_ITLB_MISSES] = { .name = "itlb_misses", .attr = { .type = PERF_TYPE_HW_CACHE, @@ -2127,11 +2143,11 @@ struct profile_metric { (PERF_COUNT_HW_CACHE_RESULT_MISS << 16), .exclude_user = 1 }, - .ratio_metric = 2, + .ratio_metric = METRIC_INSTRUCTIONS, .ratio_desc = "itlb misses per million insns", .ratio_mul = 1e6, }, - { + [METRIC_DTLB_MISSES] = { .name = "dtlb_misses", .attr = { .type = PERF_TYPE_HW_CACHE, @@ -2141,13 +2157,16 @@ struct profile_metric { (PERF_COUNT_HW_CACHE_RESULT_MISS << 16), .exclude_user = 1 }, - .ratio_metric = 2, + .ratio_metric = METRIC_INSTRUCTIONS, .ratio_desc = "dtlb misses per million insns", .ratio_mul = 1e6, }, }; static __u64 profile_total_count; +static int profile_cpu_cnt; +static int *profile_cpu_ids; +static int profile_cpu_id_span; #define MAX_NUM_PROFILE_METRICS 4 @@ -2182,9 +2201,9 @@ static int profile_parse_metrics(int argc, char **argv) return selected_cnt; } -static void profile_read_values(struct profiler_bpf *obj) +static int profile_read_values(struct profiler_bpf *obj) { - __u32 m, cpu, num_cpu = obj->rodata->num_cpu; + __u32 m, cpu, num_cpu = profile_cpu_cnt; int reading_map_fd, count_map_fd; __u64 counts[num_cpu]; __u32 key = 0; @@ -2192,15 +2211,11 @@ static void profile_read_values(struct profiler_bpf *obj) reading_map_fd = bpf_map__fd(obj->maps.accum_readings); count_map_fd = bpf_map__fd(obj->maps.counts); - if (reading_map_fd < 0 || count_map_fd < 0) { - p_err("failed to get fd for map"); - return; - } err = bpf_map_lookup_elem(count_map_fd, &key, counts); if (err) { p_err("failed to read count_map: %s", strerror(errno)); - return; + return err; } profile_total_count = 0; @@ -2208,24 +2223,37 @@ static void profile_read_values(struct profiler_bpf *obj) profile_total_count += counts[cpu]; for (m = 0; m < ARRAY_SIZE(metrics); m++) { - struct bpf_perf_event_value values[num_cpu]; + struct bpf_perf_event_value values[num_cpu], *val; + double scale; if (!metrics[m].selected) continue; err = bpf_map_lookup_elem(reading_map_fd, &key, values); if (err) { - p_err("failed to read reading_map: %s", - strerror(errno)); - return; + p_err("failed to read reading_map: %s", strerror(errno)); + return err; } + for (cpu = 0; cpu < num_cpu; cpu++) { - metrics[m].val.counter += values[cpu].counter; - metrics[m].val.enabled += values[cpu].enabled; - metrics[m].val.running += values[cpu].running; + val = &values[cpu]; + if (counts[cpu] && !val->running) { + p_err("perf event %s was not counted on CPU %d", + metrics[m].name, profile_cpu_ids[cpu]); + return -EAGAIN; + } + metrics[m].val.enabled += val->enabled; + metrics[m].val.running += val->running; + metrics[m].val.counter += val->counter; + if (val->running) { + /* Scale values to account for perf event multiplexing. */ + scale = (double)val->enabled / val->running; + metrics[m].scaled_val += val->counter * scale; + } } key++; } + return 0; } static void profile_print_readings_json(void) @@ -2242,6 +2270,7 @@ static void profile_print_readings_json(void) jsonw_lluint_field(json_wtr, "value", metrics[m].val.counter); jsonw_lluint_field(json_wtr, "enabled", metrics[m].val.enabled); jsonw_lluint_field(json_wtr, "running", metrics[m].val.running); + jsonw_lluint_field(json_wtr, "value_scaled", metrics[m].scaled_val); jsonw_end_object(json_wtr); } @@ -2250,24 +2279,34 @@ static void profile_print_readings_json(void) static void profile_print_readings_plain(void) { - __u32 m; + __u32 i; printf("\n%18llu %-20s\n", profile_total_count, "run_cnt"); - for (m = 0; m < ARRAY_SIZE(metrics); m++) { - struct bpf_perf_event_value *val = &metrics[m].val; + for (i = 0; i < ARRAY_SIZE(metrics); i++) { + struct profile_metric *m = &metrics[i]; + struct bpf_perf_event_value *val = &m->val; int r; + __u64 ratio; - if (!metrics[m].selected) + if (!m->selected) continue; - printf("%18llu %-20s", val->counter, metrics[m].name); + printf("%18llu %-20s", m->scaled_val, m->name); - r = metrics[m].ratio_metric - 1; - if (r >= 0 && metrics[r].selected && - metrics[r].val.counter > 0) { + r = m->ratio_metric; + switch (r) { + case METRIC_RUN_CNT: + ratio = profile_total_count; + break; + case METRIC_NONE: + ratio = 0; + break; + default: + ratio = metrics[r].scaled_val; + } + if (ratio) { printf("# %8.2f %-30s", - val->counter * metrics[m].ratio_mul / - metrics[r].val.counter, - metrics[m].ratio_desc); + m->scaled_val * m->ratio_mul / ratio, + m->ratio_desc); } else { printf("%-41s", ""); } @@ -2350,7 +2389,7 @@ static char *profile_tgt_name; static int *profile_perf_events; static int profile_perf_event_cnt; -static void profile_close_perf_events(struct profiler_bpf *obj) +static void profile_close_perf_events(void) { int i; @@ -2358,89 +2397,115 @@ static void profile_close_perf_events(struct profiler_bpf *obj) close(profile_perf_events[i]); free(profile_perf_events); + profile_perf_events = NULL; profile_perf_event_cnt = 0; } -static int profile_open_perf_event(int mid, int cpu, int map_fd) +static int profile_open_perf_event(int mid, int cpu, + int map_fd, int group_fd, __u32 map_key) { + struct perf_event_attr attr = metrics[mid].attr; + bool group_leader = group_fd < 0; int pmu_fd; + int err; - pmu_fd = syscall(__NR_perf_event_open, &metrics[mid].attr, - -1 /*pid*/, cpu, -1 /*group_fd*/, 0); + attr.disabled = group_leader; + pmu_fd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, cpu, + group_fd, 0); if (pmu_fd < 0) { - if (errno == ENODEV) { - p_info("cpu %d may be offline, skip %s profiling.", - cpu, metrics[mid].name); - profile_perf_event_cnt++; - return 0; - } - return -1; + err = -errno; + if (errno == ENODEV && group_leader) + p_info("cpu %d may be offline, skip profiling.", cpu); + return err; } - if (bpf_map_update_elem(map_fd, - &profile_perf_event_cnt, - &pmu_fd, BPF_ANY) || - ioctl(pmu_fd, PERF_EVENT_IOC_ENABLE, 0)) { + if (bpf_map_update_elem(map_fd, &map_key, &pmu_fd, BPF_ANY)) { + err = -errno; close(pmu_fd); - return -1; + return err; } profile_perf_events[profile_perf_event_cnt++] = pmu_fd; - return 0; + return pmu_fd; } static int profile_open_perf_events(struct profiler_bpf *obj) { + __u32 map_key; unsigned int cpu, m; - int map_fd; + int group_fd, map_fd, pmu_fd; + int err; - profile_perf_events = calloc( - obj->rodata->num_cpu * obj->rodata->num_metric, sizeof(int)); + profile_perf_events = calloc(profile_cpu_cnt * obj->rodata->num_metric, + sizeof(*profile_perf_events)); if (!profile_perf_events) { p_err("failed to allocate memory for perf_event array: %s", strerror(errno)); - return -1; + return -ENOMEM; } + map_fd = bpf_map__fd(obj->maps.events); - if (map_fd < 0) { - p_err("failed to get fd for events map"); - return -1; - } + for (cpu = 0; cpu < (unsigned int)profile_cpu_cnt; cpu++) { + int cpu_id = profile_cpu_ids[cpu]; - for (m = 0; m < ARRAY_SIZE(metrics); m++) { - if (!metrics[m].selected) - continue; - for (cpu = 0; cpu < obj->rodata->num_cpu; cpu++) { - if (profile_open_perf_event(m, cpu, map_fd)) { - p_err("failed to create event %s on cpu %u", - metrics[m].name, cpu); - return -1; + group_fd = -1; + map_key = cpu_id; + for (m = 0; m < ARRAY_SIZE(metrics); m++) { + if (!metrics[m].selected) + continue; + + pmu_fd = profile_open_perf_event(m, cpu_id, map_fd, group_fd, + map_key); + if (pmu_fd == -ENODEV && group_fd < 0) + break; + if (pmu_fd < 0) { + p_err("failed to add event %s to group on CPU %d: %s", + metrics[m].name, cpu_id, strerror(-pmu_fd)); + return pmu_fd; } + if (group_fd < 0) + group_fd = pmu_fd; + map_key += profile_cpu_id_span; + } + if (group_fd < 0) + continue; + if (ioctl(group_fd, PERF_EVENT_IOC_ENABLE, PERF_IOC_FLAG_GROUP)) { + err = -errno; + p_err("failed to enable perf event group on CPU %d: %s", + cpu_id, strerror(-err)); + return err; } } return 0; } -static void profile_print_and_cleanup(void) +static int profile_print_and_cleanup(void) { - profile_close_perf_events(profile_obj); - profile_read_values(profile_obj); - profile_print_readings(); + int err; + + profile_close_perf_events(); + err = profile_read_values(profile_obj); + if (!err) + profile_print_readings(); profiler_bpf__destroy(profile_obj); close(profile_tgt_fd); free(profile_tgt_name); + free(profile_cpu_ids); + profile_cpu_ids = NULL; + profile_cpu_cnt = 0; + profile_cpu_id_span = 0; + return err; } static void int_exit(int signo) { - profile_print_and_cleanup(); - exit(0); + exit(!!profile_print_and_cleanup()); } static int do_profile(int argc, char **argv) { - int num_metric, num_cpu, err = -1; + int num_metric, err = -1; struct bpf_program *prog; unsigned long duration; char *endptr; @@ -2471,11 +2536,12 @@ static int do_profile(int argc, char **argv) if (num_metric <= 0) goto out; - num_cpu = libbpf_num_possible_cpus(); - if (num_cpu <= 0) { + profile_cpu_cnt = get_possible_cpu_ids(&profile_cpu_ids); + if (profile_cpu_cnt <= 0) { p_err("failed to identify number of CPUs"); goto out; } + profile_cpu_id_span = profile_cpu_ids[profile_cpu_cnt - 1] + 1; profile_obj = profiler_bpf__open(); if (!profile_obj) { @@ -2483,11 +2549,12 @@ static int do_profile(int argc, char **argv) goto out; } - profile_obj->rodata->num_cpu = num_cpu; profile_obj->rodata->num_metric = num_metric; + profile_obj->rodata->cpu_id_span = profile_cpu_id_span; /* adjust map sizes */ - bpf_map__set_max_entries(profile_obj->maps.events, num_metric * num_cpu); + bpf_map__set_max_entries(profile_obj->maps.events, + num_metric * profile_cpu_id_span); bpf_map__set_max_entries(profile_obj->maps.fentry_readings, num_metric); bpf_map__set_max_entries(profile_obj->maps.accum_readings, num_metric); bpf_map__set_max_entries(profile_obj->maps.counts, 1); @@ -2525,15 +2592,18 @@ static int do_profile(int argc, char **argv) signal(SIGINT, int_exit); sleep(duration); - profile_print_and_cleanup(); - return 0; + return profile_print_and_cleanup(); out: - profile_close_perf_events(profile_obj); + profile_close_perf_events(); if (profile_obj) profiler_bpf__destroy(profile_obj); close(profile_tgt_fd); free(profile_tgt_name); + free(profile_cpu_ids); + profile_cpu_ids = NULL; + profile_cpu_cnt = 0; + profile_cpu_id_span = 0; return err; } diff --git a/tools/bpf/bpftool/skeleton/profiler.bpf.c b/tools/bpf/bpftool/skeleton/profiler.bpf.c index f48c783cb9f7..0d47a9bdc5b4 100644 --- a/tools/bpf/bpftool/skeleton/profiler.bpf.c +++ b/tools/bpf/bpftool/skeleton/profiler.bpf.c @@ -10,7 +10,7 @@ struct bpf_perf_event_value___local { __u64 running; } __attribute__((preserve_access_index)); -/* map of perf event fds, num_cpu * num_metric entries */ +/* map of perf event fds, cpu_id_span * num_metric entries */ struct { __uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY); __uint(key_size, sizeof(u32)); @@ -38,36 +38,29 @@ struct { __uint(value_size, sizeof(u64)); } counts SEC(".maps"); -const volatile __u32 num_cpu = 1; const volatile __u32 num_metric = 1; +const volatile __u32 cpu_id_span = 1; #define MAX_NUM_METRICS 4 SEC("fentry/XXX") int BPF_PROG(fentry_XXX) { - struct bpf_perf_event_value___local *ptrs[MAX_NUM_METRICS]; u32 key = bpf_get_smp_processor_id(); u32 i; - /* look up before reading, to reduce error */ for (i = 0; i < num_metric && i < MAX_NUM_METRICS; i++) { + struct bpf_perf_event_value___local *reading; u32 flag = i; - - ptrs[i] = bpf_map_lookup_elem(&fentry_readings, &flag); - if (!ptrs[i]) - return 0; - } - - for (i = 0; i < num_metric && i < MAX_NUM_METRICS; i++) { - struct bpf_perf_event_value___local reading; int err; - err = bpf_perf_event_read_value(&events, key, (void *)&reading, - sizeof(reading)); + reading = bpf_map_lookup_elem(&fentry_readings, &flag); + if (!reading) + return 0; + err = bpf_perf_event_read_value(&events, key, (void *)reading, + sizeof(*reading)); if (err) return 0; - *(ptrs[i]) = reading; - key += num_cpu; + key += cpu_id_span; } return 0; @@ -80,7 +73,7 @@ fexit_update_maps(u32 id, struct bpf_perf_event_value___local *after) before = bpf_map_lookup_elem(&fentry_readings, &id); /* only account samples with a valid fentry_reading */ - if (before && before->counter) { + if (before && before->enabled) { struct bpf_perf_event_value___local *accum; diff.counter = after->counter - before->counter; @@ -107,7 +100,7 @@ int BPF_PROG(fexit_XXX) /* read all events before updating the maps, to reduce error */ for (i = 0; i < num_metric && i < MAX_NUM_METRICS; i++) { - err = bpf_perf_event_read_value(&events, cpu + i * num_cpu, + err = bpf_perf_event_read_value(&events, cpu + i * cpu_id_span, (void *)(readings + i), sizeof(*readings)); if (err) diff --git a/tools/bpf/bpftool/tracelog.c b/tools/bpf/bpftool/tracelog.c index 573a8d99f009..e104748c8350 100644 --- a/tools/bpf/bpftool/tracelog.c +++ b/tools/bpf/bpftool/tracelog.c @@ -86,7 +86,7 @@ static bool get_tracefs_pipe(char *mnt) fclose(fp); /* The string from fscanf() might be truncated, check mnt is valid */ - if (found && validate_tracefs_mnt(mnt, TRACEFS_MAGIC)) + if (found && !validate_tracefs_mnt(mnt, TRACEFS_MAGIC)) goto exit_found; if (block_mount) diff --git a/tools/bpf/resolve_btfids/main.c b/tools/bpf/resolve_btfids/main.c index 37d7e7224207..2a93517ca9ec 100644 --- a/tools/bpf/resolve_btfids/main.c +++ b/tools/bpf/resolve_btfids/main.c @@ -1842,8 +1842,7 @@ int main(int argc, const char **argv) goto out; } - if (!(fatal_warnings && warnings)) - err = 0; + err = fatal_warnings && warnings ? -1 : 0; out: btf__free(obj.base_btf); btf__free(obj.btf); diff --git a/tools/build/feature/test-libdw.c b/tools/build/feature/test-libdw.c index aabd63ca76b4..46f75cde5947 100644 --- a/tools/build/feature/test-libdw.c +++ b/tools/build/feature/test-libdw.c @@ -49,8 +49,16 @@ int test_elfutils(void) return 0; } +/* Needs elfutils 0.160: taking its address fails the probe, not the link. */ +int test_libdw_cu_getdwarf(void) +{ + void *sym = (void *)dwarf_cu_getdwarf; + + return sym == NULL; +} + int main(void) { return test_libdw() + test_libdw_unwind() + test_libdw_getlocations() + - test_libdw_getcfi() + test_elfutils(); + test_libdw_getcfi() + test_libdw_cu_getdwarf() + test_elfutils(); } diff --git a/tools/cgroup/iocost_monitor.py b/tools/cgroup/iocost_monitor.py index bdd78ba271b0..8a4f844c98d4 100644 --- a/tools/cgroup/iocost_monitor.py +++ b/tools/cgroup/iocost_monitor.py @@ -149,8 +149,11 @@ class IocgStat: self.weight = iocg.weight.value_() / WEIGHT_ONE self.active = iocg.active.value_() / WEIGHT_ONE self.inuse = iocg.inuse.value_() / WEIGHT_ONE - self.hwa_pct = iocg.hweight_active.value_() * 100 / WEIGHT_ONE - self.hwi_pct = iocg.hweight_inuse.value_() * 100 / WEIGHT_ONE + hweight_cache = iocg.hweight_cache.counter.value_() + hwa = ((hweight_cache >> 16) & (WEIGHT_ONE - 1)) + 1 + hwi = (hweight_cache & (WEIGHT_ONE - 1)) + 1 + self.hwa_pct = hwa * 100 / WEIGHT_ONE + self.hwi_pct = hwi * 100 / WEIGHT_ONE self.address = iocg.value_() vdone = iocg.done_vtime.counter.value_() diff --git a/tools/cgroup/memcg_shrinker.py b/tools/cgroup/memcg_shrinker.py index e81c3017ada9..714772449c6b 100644 --- a/tools/cgroup/memcg_shrinker.py +++ b/tools/cgroup/memcg_shrinker.py @@ -31,7 +31,7 @@ def scan_shrinkers(shrinker_debugfs): items = line.split(' ') ino = int(items[0]) # (count, shrinker, memcg ino) - shrinkers.append((int(items[1]), shrinker, ino)) + shrinkers.append((sum(map(int, items[1:])), shrinker, ino)) return shrinkers diff --git a/tools/hv/vmbus_bufring.c b/tools/hv/vmbus_bufring.c index bac32c1109df..23542e59a2ee 100644 --- a/tools/hv/vmbus_bufring.c +++ b/tools/hv/vmbus_bufring.c @@ -58,12 +58,6 @@ void vmbus_br_setup(struct vmbus_br *br, void *buf, unsigned int blen) br->dsize = blen - sizeof(struct vmbus_bufring); } -static inline __always_inline void -rte_smp_mb(void) -{ - asm volatile("lock addl $0, -128(%%rsp); " ::: "memory"); -} - static inline int rte_atomic32_cmpset(volatile uint32_t *dst, uint32_t exp, uint32_t src) { diff --git a/tools/include/nolibc/dirent.h b/tools/include/nolibc/dirent.h index 4e02ef25e72d..f6dbe3a66e90 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/include/nolibc/err.h b/tools/include/nolibc/err.h index e22ae87a7289..61978d537ed8 100644 --- a/tools/include/nolibc/err.h +++ b/tools/include/nolibc/err.h @@ -60,7 +60,7 @@ void verr(int eval, const char *fmt, va_list args) static __attribute__((noreturn, unused)) void verrx(int eval, const char *fmt, va_list args) { - warnx(fmt, args); + vwarnx(fmt, args); exit(eval); } diff --git a/tools/include/nolibc/stdlib.h b/tools/include/nolibc/stdlib.h index 1816c2368b68..e14d054c7a1a 100644 --- a/tools/include/nolibc/stdlib.h +++ b/tools/include/nolibc/stdlib.h @@ -130,9 +130,11 @@ void *malloc(size_t len) { struct nolibc_heap *heap; - /* Always allocate memory with size multiple of 4096. */ - len = sizeof(*heap) + len; - len = (len + 4095UL) & -4096UL; + if (__builtin_expect(__builtin_add_overflow(len, sizeof(*heap), &len), 0)) { + SET_ERRNO(ENOMEM); + return NULL; + } + heap = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0); if (__builtin_expect(heap == MAP_FAILED, 0)) diff --git a/tools/include/nolibc/sys/select.h b/tools/include/nolibc/sys/select.h index 6d65d9ef3d6a..f299c79939f5 100644 --- a/tools/include/nolibc/sys/select.h +++ b/tools/include/nolibc/sys/select.h @@ -26,7 +26,7 @@ typedef struct { int __fd = (fd); \ if (__fd >= 0) \ __set->fds[__fd / FD_SETIDXMASK] &= \ - ~(1U << (__fd & FD_SETBITMASK)); \ + ~(1UL << (__fd & FD_SETBITMASK)); \ } while (0) #define FD_SET(fd, set) do { \ @@ -34,7 +34,7 @@ typedef struct { int __fd = (fd); \ if (__fd >= 0) \ __set->fds[__fd / FD_SETIDXMASK] |= \ - 1 << (__fd & FD_SETBITMASK); \ + 1UL << (__fd & FD_SETBITMASK); \ } while (0) #define FD_ISSET(fd, set) ({ \ @@ -43,7 +43,7 @@ typedef struct { int __r = 0; \ if (__fd >= 0) \ __r = !!(__set->fds[__fd / FD_SETIDXMASK] & \ -1U << (__fd & FD_SETBITMASK)); \ +1UL << (__fd & FD_SETBITMASK)); \ __r; \ }) diff --git a/tools/include/nolibc/types.h b/tools/include/nolibc/types.h index 8f3cb18df7f1..4373bd8a5b5f 100644 --- a/tools/include/nolibc/types.h +++ b/tools/include/nolibc/types.h @@ -119,7 +119,7 @@ struct timeval { #define WEXITSTATUS(status) (((status) & 0xff00) >> 8) #define WIFEXITED(status) (((status) & 0x7f) == 0) #define WTERMSIG(status) ((status) & 0x7f) -#define WIFSIGNALED(status) ((status) - 1 < 0xff) +#define WIFSIGNALED(status) ((status) - 1U < 0xff) /* standard exit() codes */ #define EXIT_SUCCESS 0 diff --git a/tools/lib/api/fd/array.c b/tools/lib/api/fd/array.c index 67b73481df27..3200746d1657 100644 --- a/tools/lib/api/fd/array.c +++ b/tools/lib/api/fd/array.c @@ -116,6 +116,10 @@ int fdarray__filter(struct fdarray *fda, short revents, return 0; for (fd = 0; fd < fda->nr; ++fd) { + /* + * Explicitly bypass nonfilterable items (e.g. control descriptors). + * This ensures their fd, events, and revents remain completely untouched. + */ if (fda->priv[fd].flags & fdarray_flag__nonfilterable) continue; diff --git a/tools/lib/bpf/btf.c b/tools/lib/bpf/btf.c index 8417de92d028..908bd344229d 100644 --- a/tools/lib/bpf/btf.c +++ b/tools/lib/bpf/btf.c @@ -3364,7 +3364,7 @@ static int btf_ext_parse_sec_info(struct btf_ext *btf_ext, { const struct btf_ext_info_sec *sinfo; struct btf_ext_info *ext_info; - __u32 info_left, record_size; + __u32 data_left, info_left, record_size; size_t sec_cnt = 0; void *info; @@ -3377,16 +3377,20 @@ static int btf_ext_parse_sec_info(struct btf_ext *btf_ext, return -EINVAL; } - /* The start of the info sec (including the __u32 record_size). */ - info = btf_ext->data + btf_ext->hdr->hdr_len + ext_sec->off; - info_left = ext_sec->len; + if (btf_ext->hdr->hdr_len > btf_ext->data_size) + return -EINVAL; - if (btf_ext->data + btf_ext->data_size < info + ext_sec->len) { + data_left = btf_ext->data_size - btf_ext->hdr->hdr_len; + if (ext_sec->off > data_left || ext_sec->len > data_left - ext_sec->off) { pr_debug("%s section (off:%u len:%u) is beyond the end of the ELF section .BTF.ext\n", ext_sec->desc, ext_sec->off, ext_sec->len); return -EINVAL; } + /* The start of the info sec (including the __u32 record_size). */ + info = btf_ext->data + btf_ext->hdr->hdr_len + ext_sec->off; + info_left = ext_sec->len; + /* At least a record size */ if (info_left < sizeof(__u32)) { pr_debug(".BTF.ext %s record size not found\n", ext_sec->desc); @@ -4827,7 +4831,7 @@ static bool btf_dedup_identical_types(struct btf_dedup *d, __u32 id1, __u32 id2, return false; a1 = btf_array(t1); - a2 = btf_array(t1); + a2 = btf_array(t2); if (a1->index_type != a2->index_type && !btf_dedup_identical_types(d, a1->index_type, a2->index_type, depth - 1)) diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c index bfa64ae6c94d..4c3b79239a27 100644 --- a/tools/lib/bpf/libbpf.c +++ b/tools/lib/bpf/libbpf.c @@ -759,7 +759,12 @@ struct bpf_object { int *fd_array; size_t fd_array_cap; - size_t fd_array_cnt; + /* + * Slots handed out so far, slot 0 included. A kfunc insn names a module + * BTF slot through its offset, slot 0 stands for vmlinux BTF and stays + * empty, so the array goes to the kernel without a count. + */ + size_t fd_array_used; struct usdt_manager *usdt_man; @@ -1223,6 +1228,12 @@ static int bpf_map__init_kern_struct_ops(struct bpf_map *map) const char *mname; mname = btf__name_by_offset(btf, member->name_off); + if (btf_member_bitfield_size(type, i)) { + pr_warn("struct_ops init_kern %s: local bitfield %s is not supported\n", + map->name, mname); + return -ENOTSUP; + } + moff = member->offset / 8; mdata = data + moff; msize = btf__resolve_size(btf, member->type); @@ -1259,8 +1270,7 @@ static int bpf_map__init_kern_struct_ops(struct bpf_map *map) } kern_member_idx = kern_member - btf_members(kern_type); - if (btf_member_bitfield_size(type, i) || - btf_member_bitfield_size(kern_type, kern_member_idx)) { + if (btf_member_bitfield_size(kern_type, kern_member_idx)) { pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n", map->name, mname); return -ENOTSUP; @@ -7886,6 +7896,19 @@ static int tracing_multi_mod_fd(struct bpf_program *prog, int *btf_obj_fd) return 0; } +static int libbpf_setup_prog_flags(struct bpf_program *prog, long cookie) +{ + enum sec_def_flags def = cookie; + + if (def & SEC_SLEEPABLE) + prog->prog_flags |= BPF_F_SLEEPABLE; + + if (def & SEC_XDP_FRAGS) + prog->prog_flags |= BPF_F_XDP_HAS_FRAGS; + + return 0; +} + /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */ static int libbpf_prepare_prog_load(struct bpf_program *prog, struct bpf_prog_load_opts *opts, long cookie) @@ -7896,12 +7919,6 @@ static int libbpf_prepare_prog_load(struct bpf_program *prog, if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE)) opts->expected_attach_type = 0; - if (def & SEC_SLEEPABLE) - opts->prog_flags |= BPF_F_SLEEPABLE; - - if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS)) - opts->prog_flags |= BPF_F_XDP_HAS_FRAGS; - /* special check for usdt to use uprobe_multi link */ if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) { /* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type @@ -8844,22 +8861,22 @@ static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj, /* set index for module BTF fd in fd_array, if unset */ if (mod_btf && !mod_btf->fd_array_idx) { /* insn->off is s16 */ - if (obj->fd_array_cnt == INT16_MAX) { + if (obj->fd_array_used == INT16_MAX) { pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n", ext->name, mod_btf->fd_array_idx); return -E2BIG; } /* Cannot use index 0 for module BTF fd */ - if (!obj->fd_array_cnt) - obj->fd_array_cnt = 1; + if (!obj->fd_array_used) + obj->fd_array_used = 1; ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int), - obj->fd_array_cnt + 1); + obj->fd_array_used + 1); if (ret) return ret; - mod_btf->fd_array_idx = obj->fd_array_cnt; + mod_btf->fd_array_idx = obj->fd_array_used; /* we assume module BTF FD is always >0 */ - obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd; + obj->fd_array[obj->fd_array_used++] = mod_btf->fd; } ext->is_set = true; @@ -9144,7 +9161,8 @@ static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const ch * permit cross-endian creation of "light skeleton". */ if (obj->gen_loader) { - bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps); + bpf_gen__init(obj->gen_loader, obj->log_level | extra_log_level, + obj->nr_programs, obj->nr_maps); } else if (!is_native_endianness(obj)) { pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name); return libbpf_err(-LIBBPF_ERRNO__ENDIAN); @@ -10023,7 +10041,7 @@ int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts attr.prog_ifindex = OPTS_GET(opts, prog_ifindex, 0) ?: prog->prog_ifindex; attr.kern_version = OPTS_GET(opts, kern_version, 0) ?: obj->kern_version; attr.fd_array = OPTS_GET(opts, fd_array, NULL) ?: obj->fd_array; - attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0) ?: obj->fd_array_cnt; + attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0); attr.token_fd = OPTS_GET(opts, token_fd, 0) ?: obj->token_fd; if (attr.token_fd) attr.prog_flags |= BPF_F_TOKEN_FD; @@ -10106,6 +10124,7 @@ int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts .prog_type = BPF_PROG_TYPE_##ptype, \ .expected_attach_type = atype, \ .cookie = (long)(flags), \ + .prog_setup_fn = libbpf_setup_prog_flags, \ .prog_prepare_load_fn = libbpf_prepare_prog_load, \ __VA_ARGS__ \ } diff --git a/tools/lib/bpf/skel_internal.h b/tools/lib/bpf/skel_internal.h index 1f3f332dffbe..9e16b8e8cb7c 100644 --- a/tools/lib/bpf/skel_internal.h +++ b/tools/lib/bpf/skel_internal.h @@ -11,6 +11,7 @@ #include #else #include +#include #include #include #include @@ -127,7 +128,7 @@ static inline void skel_free(const void *p) * either bpf_probe_read_kernel() or bpf_copy_from_user() from initial_value * depending on bpf_loader_ctx->flags. */ -static inline void skel_free_map_data(void *p, __u64 addr, size_t sz) +static inline void skel_free_map_data(void *p, __u64 addr, size_t val_sz, __u32 max_entries) { if (addr != ~0ULL) kvfree(p); @@ -138,18 +139,20 @@ static inline void skel_free_map_data(void *p, __u64 addr, size_t sz) */ } -static inline void *skel_prep_map_data(const void *val, size_t mmap_sz, size_t val_sz) +static inline void *skel_prep_map_data(const void *val, size_t val_sz, __u32 max_entries, + size_t data_sz) { void *addr; - addr = kvmalloc(val_sz, GFP_KERNEL); + addr = kvmalloc(data_sz, GFP_KERNEL); if (!addr) return NULL; - memcpy(addr, val, val_sz); + memcpy(addr, val, data_sz); return addr; } -static inline void *skel_finalize_map_data(__u64 *init_val, size_t mmap_sz, int flags, int fd) +static inline void *skel_finalize_map_data(__u64 *init_val, size_t val_sz, __u32 max_entries, + int flags, int fd) { struct bpf_map *map; void *addr = NULL; @@ -172,9 +175,10 @@ static inline void *skel_finalize_map_data(__u64 *init_val, size_t mmap_sz, int return addr; } -static inline int skel_protect_map_data(void *p, __u64 *init_val, size_t sz) +static inline int skel_protect_map_data(void *p, __u64 *init_val, size_t val_sz, __u32 max_entries) { - (void)sz; + (void)val_sz; + (void)max_entries; kvfree(p); *init_val = ~0ULL; @@ -193,25 +197,39 @@ static inline void skel_free(void *p) free(p); } -static inline void skel_free_map_data(void *p, __u64 addr, size_t sz) +static inline size_t skel_map_mmap_sz(size_t val_sz, __u32 max_entries) { - munmap(p, sz); + const long page_sz = sysconf(_SC_PAGE_SIZE); + size_t mmap_sz; + + mmap_sz = roundup(val_sz, 8) * max_entries; + mmap_sz = roundup(mmap_sz, page_sz); + return mmap_sz; } -static inline void *skel_prep_map_data(const void *val, size_t mmap_sz, size_t val_sz) +static inline void skel_free_map_data(void *p, __u64 addr, size_t val_sz, __u32 max_entries) { + munmap(p, skel_map_mmap_sz(val_sz, max_entries)); +} + +static inline void *skel_prep_map_data(const void *val, size_t val_sz, __u32 max_entries, + size_t data_sz) +{ + size_t mmap_sz = skel_map_mmap_sz(val_sz, max_entries); void *addr; addr = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); if (addr == (void *) -1) return NULL; - memcpy(addr, val, val_sz); + memcpy(addr, val, data_sz); return addr; } -static inline void *skel_finalize_map_data(__u64 *init_val, size_t mmap_sz, int flags, int fd) +static inline void *skel_finalize_map_data(__u64 *init_val, size_t val_sz, __u32 max_entries, + int flags, int fd) { + size_t mmap_sz = skel_map_mmap_sz(val_sz, max_entries); void *addr; addr = mmap((void *) (long) *init_val, mmap_sz, flags, MAP_SHARED | MAP_FIXED, fd, 0); @@ -220,11 +238,13 @@ static inline void *skel_finalize_map_data(__u64 *init_val, size_t mmap_sz, int return addr; } -static inline int skel_protect_map_data(void *p, __u64 *init_val, size_t sz) +static inline int skel_protect_map_data(void *p, __u64 *init_val, size_t val_sz, __u32 max_entries) { + size_t mmap_sz = skel_map_mmap_sz(val_sz, max_entries); + (void)init_val; - if (mprotect(p, sz, PROT_READ)) + if (mprotect(p, mmap_sz, PROT_READ)) return -errno; return 0; } diff --git a/tools/lib/bpf/usdt.c b/tools/lib/bpf/usdt.c index 2e56e3ab5b6c..ee9d1b614883 100644 --- a/tools/lib/bpf/usdt.c +++ b/tools/lib/bpf/usdt.c @@ -608,8 +608,12 @@ static bool has_nop_combo(int fd, long off) unsigned char nop_combo[11] = { 0x90, 0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, }; + long page_sz = getpagesize(); unsigned char buf[11]; + /* the kernel can't attach to a nop10 that crosses a page boundary */ + if ((off + 1) % page_sz + 10 > page_sz) + return false; if (pread(fd, buf, 11, off) != 11) return false; return memcmp(buf, nop_combo, 11) == 0; diff --git a/tools/lib/perf/evlist.c b/tools/lib/perf/evlist.c index 1f210dadd666..c1c5b0684eed 100644 --- a/tools/lib/perf/evlist.c +++ b/tools/lib/perf/evlist.c @@ -79,8 +79,9 @@ static void __perf_evlist__propagate_maps(struct perf_evlist *evlist, } } - /* Ensure cpus only references valid PMU CPUs. */ - if (!perf_cpu_map__has_any_cpu(evsel->cpus) && + /* Ensure cpus only references valid PMU CPUs, except for uncore PMUs. */ + if (!evsel->is_pmu_uncore && + !perf_cpu_map__has_any_cpu(evsel->cpus) && !perf_cpu_map__is_subset(evsel->pmu_cpus, evsel->cpus)) { struct perf_cpu_map *tmp = perf_cpu_map__intersect(evsel->pmu_cpus, evsel->cpus); diff --git a/tools/lib/perf/include/internal/evsel.h b/tools/lib/perf/include/internal/evsel.h index b988034f1371..35447bed0f95 100644 --- a/tools/lib/perf/include/internal/evsel.h +++ b/tools/lib/perf/include/internal/evsel.h @@ -128,6 +128,8 @@ struct perf_evsel { bool requires_cpu; /** Is the PMU for the event a core one? Effects the handling of own_cpus. */ bool is_pmu_core; + /** Is the PMU for the event an uncore one? */ + bool is_pmu_uncore; /** Does the evsel on read on the first CPU index such as tool time events? */ bool reads_only_on_cpu_idx0; int idx; diff --git a/tools/lib/perf/mmap.c b/tools/lib/perf/mmap.c index ec124eb0ec0a..ab3adf1d8baf 100644 --- a/tools/lib/perf/mmap.c +++ b/tools/lib/perf/mmap.c @@ -200,7 +200,7 @@ void perf_mmap__read_done(struct perf_mmap *map) /* * Check if event was unmapped due to a POLLHUP/POLLERR. */ - if (!refcount_read(&map->refcnt)) + if (!refcount_read(&map->refcnt) || !map->overwrite) return; map->prev = perf_mmap__read_head(map); diff --git a/tools/perf/Build b/tools/perf/Build index e18c80a5c1bc..bf9949fe813a 100644 --- a/tools/perf/Build +++ b/tools/perf/Build @@ -103,4 +103,6 @@ $(OUTPUT)%.pylint_log: % $(call rule_mkdir) $(Q)$(call echo-cmd,test)pylint "$<" > $@ || (cat $@ && rm $@ && false) -perf-y += $(PYLINT_TEST_LOGS) +.PHONY: pylint +pylint: $(addprefix $(OUTPUT),$(PYLINT_TEST_LOGS)) + @: diff --git a/tools/perf/Documentation/perf-c2c.txt b/tools/perf/Documentation/perf-c2c.txt index 8775889bc0a3..9e58a51c55de 100644 --- a/tools/perf/Documentation/perf-c2c.txt +++ b/tools/perf/Documentation/perf-c2c.txt @@ -341,7 +341,7 @@ output fields set for cacheline offsets output: Code address, Code symbol, Shared Object, Source line dso - coalesced by shared object -By default the coalescing is setup with 'pid,iaddr'. +By default, coalescing uses `iaddr`. STDIO OUTPUT ------------ diff --git a/tools/perf/Documentation/perf-record.txt b/tools/perf/Documentation/perf-record.txt index 178f483140ed..dc72606cb25d 100644 --- a/tools/perf/Documentation/perf-record.txt +++ b/tools/perf/Documentation/perf-record.txt @@ -293,7 +293,7 @@ OPTIONS --call-graph:: Setup and enable call-graph (stack chain/backtrace) recording, - implies -g. Default is "fp" (for user space). + implies -g. Default is "fp" for user space (s390 uses "dwarf"). The unwinding method used for kernel space is dependent on the unwinder used by the active kernel configuration, i.e @@ -329,6 +329,11 @@ OPTIONS enable deferred user callchain which will collect user-space callchains when the thread returns to the user space. + On s390, the "fp" method uses back chain instead of frame pointers, + which requires user space to maintain a back chain (e.g. compiler + option -mbackchain). Without a maintained back chain this produces + bogus call graphs. In that case use "dwarf" instead. + -q:: --quiet:: Don't print any warnings or messages, useful for scripting. diff --git a/tools/perf/Documentation/perf-sched.txt b/tools/perf/Documentation/perf-sched.txt index 4da06215163a..fe0abef2bd13 100644 --- a/tools/perf/Documentation/perf-sched.txt +++ b/tools/perf/Documentation/perf-sched.txt @@ -95,8 +95,10 @@ There are several variants of 'perf sched': events, ``try_to_wakeup()`` call among others. This is useful in understanding the scheduler behavior for the workload. - Note: The tool will not give correct results if there is topological reordering or - online/offline of cpus in between capturing snapshots of `/proc/schedstat`. + Note: Reports reject incomplete snapshots and mismatched CPU or domain IDs. + Topology changes that retain the same IDs, including CPUs going offline + and returning online between snapshots, cannot be detected and may still + produce incorrect results. Example usage: perf sched stats record -- sleep 1 diff --git a/tools/perf/Makefile.config b/tools/perf/Makefile.config index 4d5993da9f94..f74220779361 100644 --- a/tools/perf/Makefile.config +++ b/tools/perf/Makefile.config @@ -38,7 +38,7 @@ ifeq ($(CC_NO_CLANG), 0) # Default to host architecture if ARCH is not explicitly given. ifeq ($(ARCH), $(HOSTARCH)) - CLANG_TARGET_FLAGS := $(shell $(CLANG) -print-target-triple) + CLANG_TARGET_FLAGS := $(shell $(CC) -print-target-triple) else CLANG_TARGET_FLAGS := $(CLANG_TARGET_FLAGS_$(ARCH)) endif @@ -53,8 +53,15 @@ ifeq ($(CC_NO_CLANG), 0) CLANG_FLAGS += --target=$(notdir $(CROSS_COMPILE:%-=%)) endif # CROSS_COMPILE - CC := $(CLANG) $(CLANG_FLAGS) -fintegrated-as - CXX := $(CXX) $(CLANG_FLAGS) -fintegrated-as + CC := $(CC) $(CLANG_FLAGS) -fintegrated-as + + # CC being clang says nothing about CXX: "make LLVM=1" overrides both, but + # "make CC=clang" leaves CXX as g++. Probe CXX the way Makefile.include + # probes CC rather than assuming the two match. + CXX_NO_CLANG := $(shell if command -v $(firstword $(CXX)) >/dev/null 2>&1; then $(CXX) -dM -E -x c++ /dev/null; fi | grep -Fq "__clang__"; echo $$?) + ifeq ($(CXX_NO_CLANG), 0) + CXX := $(CXX) $(CLANG_FLAGS) -fintegrated-as + endif # Enabled Wthread-safety analysis for clang builds. CFLAGS += -Wthread-safety @@ -470,7 +477,7 @@ else else ifneq ($(feature-libdw), 1) ifndef NO_LIBDW - $(warning No libdw.h found or old libdw.h found or elfutils is older than 0.157, disables dwarf support. Please install new elfutils-devel/libdw-dev) + $(warning No libdw.h found or old libdw.h found or elfutils is older than 0.160, disables dwarf support. Please install new elfutils-devel/libdw-dev) NO_LIBDW := 1 endif endif # Dwarf support diff --git a/tools/perf/Makefile.perf b/tools/perf/Makefile.perf index 29cfd44c427f..00f6a13f9a1b 100644 --- a/tools/perf/Makefile.perf +++ b/tools/perf/Makefile.perf @@ -64,9 +64,6 @@ include ../scripts/utilities.mak # # Define NO_LIBBIONIC if you do not want bionic support # -# Define NO_LIBDW_DWARF_UNWIND if you do not want libdw support -# for dwarf backtrace post unwind. -# # Define NO_LIBTRACEEVENT=1 if you don't want libtraceevent to be linked, # this will remove multiple features and tools, such as 'perf trace', # that need it to read tracefs event format files, etc. @@ -485,8 +482,8 @@ endif EXTLIBS := $(call filter-out,$(EXCLUDE_EXTLIBS),$(EXTLIBS)) LIBS = -Wl,--whole-archive $(PERFLIBS) $(EXTRA_PERFLIBS) -Wl,--no-whole-archive -Wl,--start-group $(EXTLIBS) -Wl,--end-group -PERFLIBS_PY := $(call filter-out,$(LIBPERF_BENCH) $(LIBPERF_TEST),$(PERFLIBS)) -LIBS_PY = -Wl,--whole-archive $(PERFLIBS_PY) $(EXTRA_PERFLIBS) -Wl,--no-whole-archive -Wl,--start-group $(EXTLIBS) -Wl,--end-group +PERFLIBS_PY := $(call filter-out,$(LIBPERF_BENCH) $(LIBPERF_TEST),$(PERFLIBS)) $(EXTRA_PERFLIBS) +LIBS_PY = -Wl,--whole-archive $(PERFLIBS_PY) -Wl,--no-whole-archive -Wl,--start-group $(EXTLIBS) -Wl,--end-group export INSTALL SHELL_PATH @@ -518,6 +515,7 @@ $(shell [ -d '$(OUTPUT)python' ] || mkdir -p '$(OUTPUT)python') $(OUTPUT)python/perf$(PYTHON_EXTENSION_SUFFIX): util/python.c util/setup.py python/perf.pyi $(PERFLIBS_PY) $(QUIET_GEN)LDSHARED="$(CC) -pthread -shared" \ CFLAGS='$(CFLAGS)' LDFLAGS='$(LDFLAGS) $(LIBS_PY)' \ + PYTHON_EXT_DEPS='$(PERFLIBS_PY)' \ $(PYTHON_WORD) util/setup.py \ $(python_setup_quiet) build_ext; \ cp $(PYTHON_EXTBUILD_LIB)perf*.so $(OUTPUT)python/; \ @@ -537,6 +535,7 @@ strip: $(PROGRAMS) $(OUTPUT)perf $(STRIP) $(STRIP_OPTS) $(PROGRAMS) $(OUTPUT)perf PERF_IN := $(OUTPUT)perf-in.o + export NO_JEVENTS build := -f $(srctree)/tools/build/Makefile.build dir=. obj @@ -592,6 +591,20 @@ $(SCRIPTS) : $(OUTPUT)% : %.sh $(OUTPUT)PERF-VERSION-FILE: .FORCE-PERF-VERSION-FILE $(Q)$(SHELL_PATH) util/PERF-VERSION-GEN $(OUTPUT) +ifdef PYLINT +# Run Python checks after the extension is ready, independently of C builds. +all: pylint-perf pylint-tests +.PHONY: pylint-perf pylint-tests + +pylint-perf pylint-tests: | $(LANG_BINDINGS) + +pylint-perf: + $(Q)$(MAKE) $(build)=perf pylint + +pylint-tests: + $(Q)$(MAKE) $(build)=perf-test dir=tests pylint +endif + # These can record PERF_VERSION perf.spec $(SCRIPTS) \ : $(OUTPUT)PERF-VERSION-FILE @@ -951,7 +964,7 @@ clean:: $(LIBAPI)-clean $(LIBBPF)-clean $(LIBSUBCMD)-clean $(LIBSYMBOL)-clean $( -name '\.*.cmd' -delete -o -name '\.*.d' -delete -o -name '*.shellcheck_log' -delete $(Q)$(RM) $(OUTPUT).config-detected $(call QUIET_CLEAN, core-progs) $(RM) $(ALL_PROGRAMS) perf perf-read-vdso32 \ - perf-read-vdsox32 $(OUTPUT)$(LIBJVMTI).so + perf-read-vdsox32 $(OUTPUT)$(LIBJVMTI).so $(OUTPUT)libperf-gtk.so $(call QUIET_CLEAN, core-gen) $(RM) *.spec *.pyc *.pyo */*.pyc */*.pyo \ TAGS tags cscope* $(OUTPUT)PERF-VERSION-FILE \ $(OUTPUT)FEATURE-DUMP $(OUTPUT)util/*-bison* $(OUTPUT)util/*-flex* \ diff --git a/tools/perf/arch/arm/tests/dwarf-unwind.c b/tools/perf/arch/arm/tests/dwarf-unwind.c index f421910e0709..d4707e9ffd2a 100644 --- a/tools/perf/arch/arm/tests/dwarf-unwind.c +++ b/tools/perf/arch/arm/tests/dwarf-unwind.c @@ -34,6 +34,7 @@ static int sample_ustack(struct perf_sample *sample, } stack_size = map__end(map) - sp; + map__put(map); stack_size = stack_size > STACK_SIZE ? STACK_SIZE : stack_size; memcpy(buf, (void *) sp, stack_size); diff --git a/tools/perf/arch/arm64/tests/dwarf-unwind.c b/tools/perf/arch/arm64/tests/dwarf-unwind.c index 440d00f0de14..fbc161a49369 100644 --- a/tools/perf/arch/arm64/tests/dwarf-unwind.c +++ b/tools/perf/arch/arm64/tests/dwarf-unwind.c @@ -34,6 +34,7 @@ static int sample_ustack(struct perf_sample *sample, } stack_size = map__end(map) - sp; + map__put(map); stack_size = stack_size > STACK_SIZE ? STACK_SIZE : stack_size; memcpy(buf, (void *) sp, stack_size); diff --git a/tools/perf/arch/powerpc/tests/dwarf-unwind.c b/tools/perf/arch/powerpc/tests/dwarf-unwind.c index 66af884baa66..b4bade5d59e2 100644 --- a/tools/perf/arch/powerpc/tests/dwarf-unwind.c +++ b/tools/perf/arch/powerpc/tests/dwarf-unwind.c @@ -34,6 +34,7 @@ static int sample_ustack(struct perf_sample *sample, } stack_size = map__end(map) - sp; + map__put(map); stack_size = stack_size > STACK_SIZE ? STACK_SIZE : stack_size; memcpy(buf, (void *) sp, stack_size); diff --git a/tools/perf/arch/powerpc/util/skip-callchain-idx.c b/tools/perf/arch/powerpc/util/skip-callchain-idx.c index e57f10798fa6..472714cfad38 100644 --- a/tools/perf/arch/powerpc/util/skip-callchain-idx.c +++ b/tools/perf/arch/powerpc/util/skip-callchain-idx.c @@ -152,9 +152,10 @@ static int check_return_addr(struct dso *dso, Dwarf_Addr mapped_pc) Dwarf_Addr end = mapped_pc; bool signalp; + mutex_lock(dso__lock(dso)); dwfl = dso__libdw_dwfl(dso); if (!dwfl) - return -1; + goto out; mod = dwfl_addrmodule(dwfl, mapped_pc); if (!mod) { @@ -183,6 +184,7 @@ static int check_return_addr(struct dso *dso, Dwarf_Addr mapped_pc) rc = check_return_reg(ra_regno, frame); out: + mutex_unlock(dso__lock(dso)); return rc; } diff --git a/tools/perf/arch/x86/tests/topdown.c b/tools/perf/arch/x86/tests/topdown.c index 2b6f47ce4932..520075329c37 100644 --- a/tools/perf/arch/x86/tests/topdown.c +++ b/tools/perf/arch/x86/tests/topdown.c @@ -1,5 +1,7 @@ // SPDX-License-Identifier: GPL-2.0 #include +#include +#include #include "arch-tests.h" #include "../util/topdown.h" #include "debug.h" @@ -229,10 +231,38 @@ static int test__x86_topdown_slots_injection(struct test_suite *test __maybe_unu return TEST_OK; } +/* + * An explicit "slots,metrics_clear=1" event is still the slots event and + * must not cause an extra slots event to be injected into the group. + */ +static int test__x86_topdown_metrics_clear(struct test_suite *test __maybe_unused, + int subtest __maybe_unused) +{ + struct perf_pmu *pmu; + char event_str[128]; + int ret; + + if (!topdown_sys_has_perf_metrics()) + return TEST_OK; + + pmu = perf_pmus__find_by_type(PERF_TYPE_RAW); + if (!pmu || !perf_pmu__has_format(pmu, "metrics_clear")) + return TEST_OK; + + snprintf(event_str, sizeof(event_str), + "{%s/slots,metrics_clear=1/,%s/topdown-retiring/}", + pmu->name, pmu->name); + ret = test_sort(event_str, 2, 1); + TEST_ASSERT_EQUAL("explicit metrics_clear slots event isn't duplicated", ret, TEST_OK); + + return TEST_OK; +} + static struct test_case x86_topdown_tests[] = { TEST_CASE("topdown events", x86_topdown), TEST_CASE("topdown sorting", x86_topdown_sorting), TEST_CASE("topdown slots injection", x86_topdown_slots_injection), + TEST_CASE("topdown metrics_clear no extra slots", x86_topdown_metrics_clear), { .name = NULL, } }; diff --git a/tools/perf/arch/x86/util/topdown.c b/tools/perf/arch/x86/util/topdown.c index bafd285119d7..64bc64e335a2 100644 --- a/tools/perf/arch/x86/util/topdown.c +++ b/tools/perf/arch/x86/util/topdown.c @@ -37,8 +37,7 @@ bool topdown_sys_has_perf_metrics(void) bool arch_is_topdown_slots(const struct evsel *evsel) { return evsel->core.attr.type == PERF_TYPE_RAW && - evsel->core.attr.config == TOPDOWN_SLOTS && - evsel->core.attr.config1 == 0; + evsel->core.attr.config == TOPDOWN_SLOTS; } bool arch_is_topdown_metrics(const struct evsel *evsel) diff --git a/tools/perf/builtin-buildid-list.c b/tools/perf/builtin-buildid-list.c index e0881b0ac38f..5555f5dcefe4 100644 --- a/tools/perf/builtin-buildid-list.c +++ b/tools/perf/builtin-buildid-list.c @@ -87,6 +87,7 @@ static bool dso__skip_buildid(struct dso *dso, int with_hits) static int perf_session__list_build_ids(bool force, bool with_hits) { struct perf_session *session; + bool has_auxtrace, has_build_id; struct perf_data data = { .path = input_name, .mode = PERF_DATA_MODE_READ, @@ -118,11 +119,19 @@ static int perf_session__list_build_ids(bool force, bool with_hits) * We take all buildids when the file contains AUX area tracing data * because we do not decode the trace because it would take too long. */ - if (!perf_data__is_pipe(&data) && - perf_header__has_feat(&session->header, HEADER_AUXTRACE)) + has_auxtrace = !perf_data__is_pipe(&data) && + perf_header__has_feat(&session->header, HEADER_AUXTRACE); + has_build_id = perf_header__has_feat(&session->header, HEADER_BUILD_ID); + + if (has_auxtrace) with_hits = false; - if (!perf_header__has_feat(&session->header, HEADER_BUILD_ID)) + /* + * Without a build-ID header, the event stream is processed below to find + * build IDs in MMAP2 records. For AUX data keep all DSOs because the trace + * is not decoded and consequently none of them can be marked as hit. + */ + if (!has_build_id && !has_auxtrace) with_hits = true; if (zstd_init(&(session->zstd_data), 0) < 0) @@ -132,7 +141,7 @@ static int perf_session__list_build_ids(bool force, bool with_hits) * in pipe-mode, the only way to get the buildids is to parse * the record stream. Buildids are stored as RECORD_HEADER_BUILD_ID */ - if (with_hits || perf_data__is_pipe(&data)) + if (with_hits || perf_data__is_pipe(&data) || !has_build_id) perf_session__process_events(session); perf_session__fprintf_dsos_buildid(session, stdout, dso__skip_buildid, with_hits); diff --git a/tools/perf/builtin-c2c.c b/tools/perf/builtin-c2c.c index 715b75d42f2a..0beda148cdf3 100644 --- a/tools/perf/builtin-c2c.c +++ b/tools/perf/builtin-c2c.c @@ -2087,6 +2087,11 @@ static int c2c_hists__reinit(struct c2c_hists *c2c_hists, return ret; } +static void c2c_hists__exit(struct c2c_hists *c2c_hists) +{ + perf_hpp__reset_output_field(&c2c_hists->list); +} + #define DISPLAY_LINE_LIMIT 0.001 static u8 filter_display(u32 val, u32 sum) @@ -2495,7 +2500,7 @@ static void print_pareto(FILE *out, struct perf_env *env) ret = hpp_list__parse(&hpp_list, cl_output, /*evlist=*/NULL, env); if (WARN_ONCE(ret, "failed to setup sort entries\n")) - return; + goto out; nd = rb_first_cached(&c2c.hists.hists.entries); @@ -2509,6 +2514,9 @@ static void print_pareto(FILE *out, struct perf_env *env) c2c_he = container_of(he, struct c2c_hist_entry, he); print_cacheline(c2c_he->hists, he, &hpp_list, out); } + +out: + perf_hpp__reset_output_field(&hpp_list); } static void print_c2c_info(FILE *out, struct perf_session *session) @@ -3211,12 +3219,12 @@ static int perf_c2c__report(int argc, const char **argv) err = setup_nodes(session); if (err) { pr_err("Failed setup nodes\n"); - goto out_session; + goto out_hists; } err = mem2node__init(&c2c.mem2node, env); if (err) - goto out_session; + goto out_hists; err = setup_callchain(session->evlist); if (err) @@ -3336,6 +3344,8 @@ static int perf_c2c__report(int argc, const char **argv) out_mem2node: mem2node__exit(&c2c.mem2node); +out_hists: + c2c_hists__exit(&c2c.hists); out_session: perf_session__delete(session); out: diff --git a/tools/perf/builtin-inject.c b/tools/perf/builtin-inject.c index 70bbfad5653e..1446e5c0f63e 100644 --- a/tools/perf/builtin-inject.c +++ b/tools/perf/builtin-inject.c @@ -2880,6 +2880,9 @@ int cmd_inject(int argc, const char **argv) goto out_close_output; } + if (inject.aslr) + aslr_tool__register_session(tool, inject.session); + if (zstd_init(&(inject.session->zstd_data), 0) < 0) pr_warning("Decompression initialization failed.\n"); diff --git a/tools/perf/builtin-lock.c b/tools/perf/builtin-lock.c index d5c0d55cb82d..778923c92f42 100644 --- a/tools/perf/builtin-lock.c +++ b/tools/perf/builtin-lock.c @@ -975,6 +975,7 @@ static int report_lock_contention_begin_event(struct perf_sample *sample) struct machine *machine = &session->machines.host; struct map *kmap; struct symbol *sym; + u64 *callstack = NULL; ret = get_key_by_aggr_mode(&key, addr, sample); if (ret < 0) @@ -1010,33 +1011,6 @@ static int report_lock_contention_begin_event(struct perf_sample *sample) } } - 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(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; @@ -1066,7 +1040,7 @@ static int report_lock_contention_begin_event(struct perf_sample *sample) } if (needs_callstack()) { - u64 *callstack = get_callstack(sample, max_stack_depth); + callstack = get_callstack(sample, max_stack_depth); if (callstack == NULL) return 0; @@ -1074,7 +1048,38 @@ static int report_lock_contention_begin_event(struct perf_sample *sample) 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(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/builtin-record.c b/tools/perf/builtin-record.c index a57987851cf0..ad81458989b5 100644 --- a/tools/perf/builtin-record.c +++ b/tools/perf/builtin-record.c @@ -1169,6 +1169,21 @@ static int record__update_evlist_pollfd_from_thread(struct record *rec, int e_pos = rec->index_map[i].evlist_pollfd_index; int t_pos = rec->index_map[i].thread_pollfd_index; + if (e_entries[e_pos].fd == -1 || e_entries[e_pos].events == 0) { + /* + * If the control file descriptor was closed, then evlist__ctlfd_process() + * will have called evlist__finalize_ctlfd() on the PREVIOUS loop iteration + * to cleanly set the core evlist's e_entries[e_pos].fd to -1. + * + * Since nonfilterable items are skipped by fdarray__filter(), the + * thread's local t_entries[t_pos] retains its original state. + * We must explicitly propagate the finalized -1 state to t_entries + * BEFORE evaluating the strict equivalence check below. + */ + t_entries[t_pos].fd = -1; + t_entries[t_pos].events = 0; + } + if (e_entries[e_pos].fd != t_entries[t_pos].fd || e_entries[e_pos].events != t_entries[t_pos].events) { pr_err("Thread and evlist pollfd index mismatch\n"); diff --git a/tools/perf/builtin-sched.c b/tools/perf/builtin-sched.c index dd39a4fb6c7a..9e7d170b30ad 100644 --- a/tools/perf/builtin-sched.c +++ b/tools/perf/builtin-sched.c @@ -4281,18 +4281,18 @@ struct schedstat_cpu { }; static struct list_head cpu_head = LIST_HEAD_INIT(cpu_head); -static struct schedstat_cpu *cpu_second_pass; -static struct schedstat_domain *domain_second_pass; +static struct list_head *cpu_second_pass; +static struct list_head *domain_second_pass; +static u64 schedstat_timestamp; static bool after_workload_flag; static bool verbose_field; static void free_schedstat(struct list_head *head); -static void store_schedstat_cpu_diff(struct schedstat_cpu *after_workload) +static void store_schedstat_cpu_diff(struct perf_record_schedstat_cpu *before, + struct perf_record_schedstat_cpu *after) { - struct perf_record_schedstat_cpu *before = cpu_second_pass->cpu_data; - struct perf_record_schedstat_cpu *after = after_workload->cpu_data; - __u16 version = after_workload->cpu_data->version; + __u16 version = after->version; #define CPU_FIELD(_type, _name, _desc, _format, _is_pct, _pct_of, _ver) \ (before->_ver._name = after->_ver._name - before->_ver._name) @@ -4308,11 +4308,10 @@ static void store_schedstat_cpu_diff(struct schedstat_cpu *after_workload) #undef CPU_FIELD } -static void store_schedstat_domain_diff(struct schedstat_domain *after_workload) +static void store_schedstat_domain_diff(struct perf_record_schedstat_domain *before, + struct perf_record_schedstat_domain *after) { - struct perf_record_schedstat_domain *before = domain_second_pass->domain_data; - struct perf_record_schedstat_domain *after = after_workload->domain_data; - __u16 version = after_workload->domain_data->version; + __u16 version = after->version; #define DOMAIN_FIELD(_type, _name, _desc, _format, _is_jiffies, _ver) \ (before->_ver._name = after->_ver._name - before->_ver._name) @@ -4814,12 +4813,35 @@ static int show_schedstat_data(struct list_head *head1, struct cpu_domain_map ** * other after completion of the workload. The above linked list stores the diff of the cpu and * domain statistics. */ +static int schedstat_snapshot_error(void) +{ + pr_err("Incompatible or incomplete schedstat snapshots\n"); + return -EINVAL; +} + +static bool schedstat_domains_complete(void) +{ + struct schedstat_cpu *cpu; + + if (!domain_second_pass) + return true; + cpu = list_entry(cpu_second_pass, struct schedstat_cpu, cpu_list); + return domain_second_pass == &cpu->domain_head; +} + +static int schedstat_snapshots_complete(void) +{ + if (!after_workload_flag || !cpu_second_pass || + cpu_second_pass->next != &cpu_head || !schedstat_domains_complete()) + return schedstat_snapshot_error(); + return 0; +} + static int perf_sched__process_schedstat(const struct perf_tool *tool __maybe_unused, struct perf_session *session __maybe_unused, union perf_event *event) { struct perf_cpu this_cpu; - static __u32 initial_cpu; switch (event->header.type) { case PERF_RECORD_SCHEDSTAT_CPU: @@ -4836,63 +4858,91 @@ static int perf_sched__process_schedstat(const struct perf_tool *tool __maybe_un return 0; if (event->header.type == PERF_RECORD_SCHEDSTAT_CPU) { - struct schedstat_cpu *temp = zalloc(sizeof(*temp)); - - if (!temp) - return -ENOMEM; - - temp->cpu_data = zalloc(sizeof(*temp->cpu_data)); - if (!temp->cpu_data) - return -ENOMEM; + struct perf_record_schedstat_cpu *data = &event->schedstat_cpu; + struct schedstat_cpu *cpu; - memcpy(temp->cpu_data, &event->schedstat_cpu, sizeof(*temp->cpu_data)); - - if (!list_empty(&cpu_head) && temp->cpu_data->cpu == initial_cpu) - after_workload_flag = true; - - if (!after_workload_flag) { - if (list_empty(&cpu_head)) - initial_cpu = temp->cpu_data->cpu; - - list_add_tail(&temp->cpu_list, &cpu_head); - INIT_LIST_HEAD(&temp->domain_head); - } else { - if (temp->cpu_data->cpu == initial_cpu) { - cpu_second_pass = list_first_entry(&cpu_head, struct schedstat_cpu, - cpu_list); - cpu_second_pass->cpu_data->timestamp = - temp->cpu_data->timestamp - cpu_second_pass->cpu_data->timestamp; - } else { - cpu_second_pass = list_next_entry(cpu_second_pass, cpu_list); + if (list_empty(&cpu_head)) { + after_workload_flag = false; + cpu_second_pass = &cpu_head; + domain_second_pass = NULL; + schedstat_timestamp = data->timestamp; + } else if (!after_workload_flag) { + cpu = list_last_entry(&cpu_head, struct schedstat_cpu, cpu_list); + /* Snapshots share a timestamp and list CPUs in increasing order. */ + if (data->timestamp != schedstat_timestamp || + data->cpu <= cpu->cpu_data->cpu) { + after_workload_flag = true; + schedstat_timestamp = data->timestamp; } - domain_second_pass = list_first_entry(&cpu_second_pass->domain_head, - struct schedstat_domain, domain_list); - store_schedstat_cpu_diff(temp); - free(temp->cpu_data); - free(temp); } - } else if (event->header.type == PERF_RECORD_SCHEDSTAT_DOMAIN) { - struct schedstat_cpu *cpu_tail; - struct schedstat_domain *temp = zalloc(sizeof(*temp)); - if (!temp) - return -ENOMEM; + if (after_workload_flag) { + if (data->timestamp != schedstat_timestamp || !schedstat_domains_complete()) + return schedstat_snapshot_error(); + cpu_second_pass = cpu_second_pass->next; + if (cpu_second_pass == &cpu_head) + return schedstat_snapshot_error(); + cpu = list_entry(cpu_second_pass, struct schedstat_cpu, cpu_list); + if (data->cpu != cpu->cpu_data->cpu || + data->version != cpu->cpu_data->version || + data->timestamp < cpu->cpu_data->timestamp) + return schedstat_snapshot_error(); + cpu->cpu_data->timestamp = data->timestamp - cpu->cpu_data->timestamp; + store_schedstat_cpu_diff(cpu->cpu_data, data); + domain_second_pass = cpu->domain_head.next; + return 0; + } - temp->domain_data = zalloc(sizeof(*temp->domain_data)); - if (!temp->domain_data) + cpu = zalloc(sizeof(*cpu)); + if (!cpu) return -ENOMEM; + cpu->cpu_data = memdup(data, sizeof(*data)); + if (!cpu->cpu_data) { + free(cpu); + return -ENOMEM; + } + INIT_LIST_HEAD(&cpu->domain_head); + list_add_tail(&cpu->cpu_list, &cpu_head); + } else { + struct perf_record_schedstat_domain *data = &event->schedstat_domain; + struct schedstat_domain *domain; + struct schedstat_cpu *cpu; + + if (list_empty(&cpu_head) || data->timestamp != schedstat_timestamp) + return schedstat_snapshot_error(); + if (after_workload_flag) { + cpu = list_entry(cpu_second_pass, struct schedstat_cpu, cpu_list); + if (domain_second_pass == &cpu->domain_head) + return schedstat_snapshot_error(); + domain = list_entry(domain_second_pass, struct schedstat_domain, + domain_list); + if (data->cpu != domain->domain_data->cpu || + data->domain != domain->domain_data->domain || + data->version != domain->domain_data->version) + return schedstat_snapshot_error(); + store_schedstat_domain_diff(domain->domain_data, data); + domain_second_pass = domain_second_pass->next; + return 0; + } - memcpy(temp->domain_data, &event->schedstat_domain, sizeof(*temp->domain_data)); - - if (!after_workload_flag) { - cpu_tail = list_last_entry(&cpu_head, struct schedstat_cpu, cpu_list); - list_add_tail(&temp->domain_list, &cpu_tail->domain_head); - } else { - store_schedstat_domain_diff(temp); - domain_second_pass = list_next_entry(domain_second_pass, domain_list); - free(temp->domain_data); - free(temp); + cpu = list_last_entry(&cpu_head, struct schedstat_cpu, cpu_list); + if (data->cpu != cpu->cpu_data->cpu || data->version != cpu->cpu_data->version) + return schedstat_snapshot_error(); + if (!list_empty(&cpu->domain_head)) { + domain = list_last_entry(&cpu->domain_head, struct schedstat_domain, + domain_list); + if (data->domain <= domain->domain_data->domain) + return schedstat_snapshot_error(); } + domain = zalloc(sizeof(*domain)); + if (!domain) + return -ENOMEM; + domain->domain_data = memdup(data, sizeof(*data)); + if (!domain->domain_data) { + free(domain); + return -ENOMEM; + } + list_add_tail(&domain->domain_list, &cpu->domain_head); } return 0; @@ -4947,6 +4997,8 @@ static int perf_sched__schedstat_report(struct perf_sched *sched) user_requested_cpus = evlist__core(session->evlist)->user_requested_cpus; err = perf_session__process_events(session); + if (!err) + err = schedstat_snapshots_complete(); if (!err) { setup_pager(); @@ -4976,7 +5028,7 @@ static int perf_sched__schedstat_diff(struct perf_sched *sched, struct list_head cpu_head_ses0, cpu_head_ses1; struct perf_session *session[2]; struct perf_data data[2] = {0}; - int ret = 0, err = 0; + int ret = 0; static const char *defaults[] = { "perf.data.old", "perf.data", @@ -5009,8 +5061,10 @@ static int perf_sched__schedstat_diff(struct perf_sched *sched, goto out_delete_ses0; } - err = perf_session__process_events(session[0]); - if (err) { + ret = perf_session__process_events(session[0]); + if (!ret) + ret = schedstat_snapshots_complete(); + if (ret) { free_schedstat(&cpu_head); goto out_delete_ses0; } @@ -5028,8 +5082,10 @@ static int perf_sched__schedstat_diff(struct perf_sched *sched, goto out_delete_ses1; } - err = perf_session__process_events(session[1]); - if (err) { + ret = perf_session__process_events(session[1]); + if (!ret) + ret = schedstat_snapshots_complete(); + if (ret) { free_schedstat(&cpu_head); goto out_delete_ses1; } @@ -5152,6 +5208,9 @@ static int perf_sched__schedstat_live(struct perf_sched *sched, user_requested_cpus); if (err) goto out; + err = schedstat_snapshots_complete(); + if (err) + goto out; setup_pager(); diff --git a/tools/perf/builtin-stat.c b/tools/perf/builtin-stat.c index c50cf230f16e..37752d6bfef4 100644 --- a/tools/perf/builtin-stat.c +++ b/tools/perf/builtin-stat.c @@ -777,7 +777,6 @@ static int __run_perf_stat(int argc, const char **argv, int run_idx) int interval = stat_config.interval; int times = stat_config.times; int timeout = stat_config.timeout; - char msg[BUFSIZ]; unsigned long long t0, t1; struct evsel *counter; size_t l; @@ -908,6 +907,9 @@ static int __run_perf_stat(int argc, const char **argv, int run_idx) } } if (!has_supported_counters && !stat_config.null_run) { + char msg[BUFSIZ]; + + msg[0] = '\0'; if (open_err) { evsel__open_strerror(evlist__first(evsel_list), &target, open_err, msg, sizeof(msg)); diff --git a/tools/perf/builtin-trace.c b/tools/perf/builtin-trace.c index c3c7f1f85c53..9c9360eaa9f0 100644 --- a/tools/perf/builtin-trace.c +++ b/tools/perf/builtin-trace.c @@ -1066,7 +1066,7 @@ static size_t btf_struct_scnprintf(const struct btf_type *type, struct btf *btf, return 0; /* pretty print the struct data here */ - if (btf_dump__dump_type_data(btf_dump, type_id, arg->augmented.args->value, type->size, &dump_data_opts) == 0) + if (btf_dump__dump_type_data(btf_dump, type_id, arg->augmented.args->value, type->size, &dump_data_opts) <= 0) return 0; consumed = sizeof(*augmented_arg) + augmented_arg->size; @@ -4016,7 +4016,12 @@ static int trace__bpf_sys_enter_beauty_map(struct trace *trace, int e_machine, i continue; bt = sc->arg_fmt[i].type; - beauty_array[i] = bt->size; + /* Copy a sockaddr as a buffer sized by the next argument, e.g. addrlen. */ + if (strcmp(name, "sockaddr") == 0 && field->next && + strstr(field->next->name, "len")) + beauty_array[i] = -((i + 1) + 1); + else + beauty_array[i] = bt->size; can_augment = true; } else if (field->flags & TEP_FIELD_IS_POINTER && /* string */ strcmp(field->type, "const char *") == 0 && diff --git a/tools/perf/pmu-events/Build b/tools/perf/pmu-events/Build index 372773b998e4..4c7b082cb2bb 100644 --- a/tools/perf/pmu-events/Build +++ b/tools/perf/pmu-events/Build @@ -223,9 +223,11 @@ ifneq ($(strip $(ORPHAN_FILES)),) # of a build step. quiet_cmd_rm = RM ...$(words $^) orphan file(s)... -# The list of files can be long. Use xargs to prevent issues. +# The list of files can be long. Remove the $(OUT_DIR)/ prefix, and +# restore it with printf, to prevent "Argument list too long" +# (see scripts/Makefile.clean). prune_orphans: $(ORPHAN_FILES) - $(Q)$(call echo-cmd,rm)echo "$^" | xargs rm -f + $(Q)$(call echo-cmd,rm)printf '$(OUT_DIR)/%s ' $(patsubst $(OUT_DIR)/%,%,$(ORPHAN_FILES)) | xargs rm -f JEVENTS_DEPS += prune_orphans endif diff --git a/tools/perf/pmu-events/arch/x86/clearwaterforest/pipeline.json b/tools/perf/pmu-events/arch/x86/clearwaterforest/pipeline.json index f73686174af9..6cea91277d5c 100644 --- a/tools/perf/pmu-events/arch/x86/clearwaterforest/pipeline.json +++ b/tools/perf/pmu-events/arch/x86/clearwaterforest/pipeline.json @@ -934,6 +934,7 @@ "Counter": "0,1,2,3,4,5,6,7", "EventCode": "0xc2", "EventName": "UOPS_RETIRED.X87", - "SampleAfterValue": "1000003" + "SampleAfterValue": "1000003", + "UMask": "0x100" } ] diff --git a/tools/perf/pmu-events/arch/x86/clearwaterforest/uncore-cache.json b/tools/perf/pmu-events/arch/x86/clearwaterforest/uncore-cache.json index 278837f2068a..e065236e9525 100644 --- a/tools/perf/pmu-events/arch/x86/clearwaterforest/uncore-cache.json +++ b/tools/perf/pmu-events/arch/x86/clearwaterforest/uncore-cache.json @@ -700,6 +700,7 @@ "EventName": "UNC_CHA_REMOTE_SF.DIRBACKED_ONLY", "Experimental": "1", "PerPkg": "1", + "UMask": "0x4000", "Unit": "CHA" }, { @@ -729,6 +730,7 @@ "EventName": "UNC_CHA_REMOTE_SF.INCLUSIVE_ONLY", "Experimental": "1", "PerPkg": "1", + "UMask": "0x2000", "Unit": "CHA" }, { @@ -747,6 +749,7 @@ "EventName": "UNC_CHA_REMOTE_SF.UPDATE_EXCLUSIVE", "Experimental": "1", "PerPkg": "1", + "UMask": "0x100", "Unit": "CHA" }, { @@ -766,6 +769,7 @@ "EventName": "UNC_CHA_REMOTE_SF.VICTIM_EXCLUSIVE", "Experimental": "1", "PerPkg": "1", + "UMask": "0x400", "Unit": "CHA" }, { @@ -775,6 +779,7 @@ "EventName": "UNC_CHA_REMOTE_SF.VICTIM_SHARED", "Experimental": "1", "PerPkg": "1", + "UMask": "0x200", "Unit": "CHA" }, { diff --git a/tools/perf/pmu-events/arch/x86/clearwaterforest/uncore-interconnect.json b/tools/perf/pmu-events/arch/x86/clearwaterforest/uncore-interconnect.json index 1f6e0970141a..7fa6def25379 100644 --- a/tools/perf/pmu-events/arch/x86/clearwaterforest/uncore-interconnect.json +++ b/tools/perf/pmu-events/arch/x86/clearwaterforest/uncore-interconnect.json @@ -515,6 +515,7 @@ "EventName": "UNC_B2CMI_IMC_WRITES.NI", "Experimental": "1", "PerPkg": "1", + "UMask": "0x300", "Unit": "B2CMI" }, { @@ -524,6 +525,7 @@ "EventName": "UNC_B2CMI_IMC_WRITES.NI_MISS", "Experimental": "1", "PerPkg": "1", + "UMask": "0x500", "Unit": "B2CMI" }, { diff --git a/tools/perf/pmu-events/arch/x86/lunarlake/cache.json b/tools/perf/pmu-events/arch/x86/lunarlake/cache.json index 5b350233a5e1..c77040e87639 100644 --- a/tools/perf/pmu-events/arch/x86/lunarlake/cache.json +++ b/tools/perf/pmu-events/arch/x86/lunarlake/cache.json @@ -848,6 +848,7 @@ "EventName": "MEM_LOAD_L3_MISS_RETIRED.MEMSIDE_CACHE", "PublicDescription": "Retired load instructions which data source is memory side cache. Available PDIST counters: 0,1", "SampleAfterValue": "100007", + "UMask": "0x100", "Unit": "cpu_core" }, { @@ -901,6 +902,7 @@ "EventName": "MEM_LOAD_RETIRED.L1_HIT_L1", "PublicDescription": "Counts retired load instructions with at least one uop that hit in the Level 1 of the L1 data cache. Available PDIST counters: 0,1", "SampleAfterValue": "1000003", + "UMask": "0x100", "Unit": "cpu_core" }, { @@ -1093,6 +1095,7 @@ "EventCode": "0x44", "EventName": "MEM_STORE_RETIRED.MEMSIDE_CACHE", "SampleAfterValue": "100021", + "UMask": "0x400", "Unit": "cpu_core" }, { diff --git a/tools/perf/pmu-events/arch/x86/lunarlake/pipeline.json b/tools/perf/pmu-events/arch/x86/lunarlake/pipeline.json index 8be3ea336bb8..5d8bd972d463 100644 --- a/tools/perf/pmu-events/arch/x86/lunarlake/pipeline.json +++ b/tools/perf/pmu-events/arch/x86/lunarlake/pipeline.json @@ -190,6 +190,7 @@ "EventName": "BR_INST_RETIRED.COND_TAKEN_FWD", "PublicDescription": "Counts taken forward conditional branch instructions retired. Available PDIST counters: 0,1", "SampleAfterValue": "400009", + "UMask": "0x100", "Unit": "cpu_core" }, { @@ -474,6 +475,7 @@ "EventName": "BR_MISP_RETIRED.COND_TAKEN_FWD", "PublicDescription": "Counts taken forward conditional mispredicted branch instructions retired. Available PDIST counters: 0,1", "SampleAfterValue": "400009", + "UMask": "0x100", "Unit": "cpu_core" }, { diff --git a/tools/perf/pmu-events/arch/x86/sierraforest/uncore-cache.json b/tools/perf/pmu-events/arch/x86/sierraforest/uncore-cache.json index 35b1763b0020..0b95faa5e469 100644 --- a/tools/perf/pmu-events/arch/x86/sierraforest/uncore-cache.json +++ b/tools/perf/pmu-events/arch/x86/sierraforest/uncore-cache.json @@ -701,6 +701,7 @@ "EventName": "UNC_CHA_REMOTE_SF.DIRBACKED_ONLY", "Experimental": "1", "PerPkg": "1", + "UMask": "0x4000", "Unit": "CHA" }, { @@ -730,6 +731,7 @@ "EventName": "UNC_CHA_REMOTE_SF.INCLUSIVE_ONLY", "Experimental": "1", "PerPkg": "1", + "UMask": "0x2000", "Unit": "CHA" }, { @@ -748,6 +750,7 @@ "EventName": "UNC_CHA_REMOTE_SF.UPDATE_EXCLUSIVE", "Experimental": "1", "PerPkg": "1", + "UMask": "0x100", "Unit": "CHA" }, { @@ -767,6 +770,7 @@ "EventName": "UNC_CHA_REMOTE_SF.VICTIM_EXCLUSIVE", "Experimental": "1", "PerPkg": "1", + "UMask": "0x400", "Unit": "CHA" }, { @@ -776,6 +780,7 @@ "EventName": "UNC_CHA_REMOTE_SF.VICTIM_SHARED", "Experimental": "1", "PerPkg": "1", + "UMask": "0x200", "Unit": "CHA" }, { diff --git a/tools/perf/pmu-events/arch/x86/sierraforest/uncore-interconnect.json b/tools/perf/pmu-events/arch/x86/sierraforest/uncore-interconnect.json index 1f6e0970141a..7fa6def25379 100644 --- a/tools/perf/pmu-events/arch/x86/sierraforest/uncore-interconnect.json +++ b/tools/perf/pmu-events/arch/x86/sierraforest/uncore-interconnect.json @@ -515,6 +515,7 @@ "EventName": "UNC_B2CMI_IMC_WRITES.NI", "Experimental": "1", "PerPkg": "1", + "UMask": "0x300", "Unit": "B2CMI" }, { @@ -524,6 +525,7 @@ "EventName": "UNC_B2CMI_IMC_WRITES.NI_MISS", "Experimental": "1", "PerPkg": "1", + "UMask": "0x500", "Unit": "B2CMI" }, { diff --git a/tools/perf/pmu-events/arch/x86/skylakex/uncore-interconnect.json b/tools/perf/pmu-events/arch/x86/skylakex/uncore-interconnect.json index eef801c68bd2..08311bdb2b20 100644 --- a/tools/perf/pmu-events/arch/x86/skylakex/uncore-interconnect.json +++ b/tools/perf/pmu-events/arch/x86/skylakex/uncore-interconnect.json @@ -13462,6 +13462,7 @@ "EventName": "UNC_UPI_TxL_HDR_MATCH.DATA_HDR", "Experimental": "1", "PerPkg": "1", + "UMask": "0x800", "Unit": "UPI" }, { @@ -13472,6 +13473,7 @@ "EventName": "UNC_UPI_TxL_HDR_MATCH.DUAL_SLOT_HDR", "Experimental": "1", "PerPkg": "1", + "UMask": "0x2000", "Unit": "UPI" }, { @@ -13482,6 +13484,7 @@ "EventName": "UNC_UPI_TxL_HDR_MATCH.LOC", "Experimental": "1", "PerPkg": "1", + "UMask": "0x200", "Unit": "UPI" }, { @@ -13514,6 +13517,7 @@ "EventName": "UNC_UPI_TxL_HDR_MATCH.NON_DATA_HDR", "Experimental": "1", "PerPkg": "1", + "UMask": "0x1000", "Unit": "UPI" }, { @@ -13524,6 +13528,7 @@ "EventName": "UNC_UPI_TxL_HDR_MATCH.REM", "Experimental": "1", "PerPkg": "1", + "UMask": "0x400", "Unit": "UPI" }, { @@ -13567,6 +13572,7 @@ "EventName": "UNC_UPI_TxL_HDR_MATCH.SGL_SLOT_HDR", "Experimental": "1", "PerPkg": "1", + "UMask": "0x4000", "Unit": "UPI" }, { diff --git a/tools/perf/pmu-events/arch/x86/snowridgex/uncore-cache.json b/tools/perf/pmu-events/arch/x86/snowridgex/uncore-cache.json index a81776deb2e6..c32f1f3f826a 100644 --- a/tools/perf/pmu-events/arch/x86/snowridgex/uncore-cache.json +++ b/tools/perf/pmu-events/arch/x86/snowridgex/uncore-cache.json @@ -1592,6 +1592,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Cache Lookups : All Request Filter : Counts the number of times the LLC was accessed - this includes code, data, prefetches and hints coming from L2. This has numerous filters available. Note the non-standard filtering equation. This event will count requests that lookup the cache multiple times with multiple increments. One must ALWAYS select a state or states (in the umask field) to match. Otherwise, the event will count nothing. : Any local or remote transaction to the LLC, including prefetch.", + "UMask": "0x2000", "Unit": "CHA" }, { @@ -1624,6 +1625,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Cache Lookups : CRd Request Filter : Counts the number of times the LLC was accessed - this includes code, data, prefetches and hints coming from L2. This has numerous filters available. Note the non-standard filtering equation. This event will count requests that lookup the cache multiple times with multiple increments. One must ALWAYS select a state or states (in the umask field) to match. Otherwise, the event will count nothing. : Local or remote CRd transactions to the LLC. This includes CRd prefetch.", + "UMask": "0x1000", "Unit": "CHA" }, { @@ -1645,6 +1647,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Cache Lookups : Local request Filter : Counts the number of times the LLC was accessed - this includes code, data, prefetches and hints coming from L2. This has numerous filters available. Note the non-standard filtering equation. This event will count requests that lookup the cache multiple times with multiple increments. One must ALWAYS select a state or states (in the umask field) to match. Otherwise, the event will count nothing. : Any local transaction to the LLC, including prefetches from the Core", + "UMask": "0x4000", "Unit": "CHA" }, { @@ -1687,6 +1690,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Cache Lookups : Data Read Request Filter : Counts the number of times the LLC was accessed - this includes code, data, prefetches and hints coming from L2. This has numerous filters available. Note the non-standard filtering equation. This event will count requests that lookup the cache multiple times with multiple increments. One must ALWAYS select a state or states (in the umask field) to match. Otherwise, the event will count nothing. : Read transactions.", + "UMask": "0x100", "Unit": "CHA" }, { @@ -1752,6 +1756,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Cache Lookups : Flush or Invalidate Filter : Counts the number of times the LLC was accessed - this includes code, data, prefetches and hints coming from L2. This has numerous filters available. Note the non-standard filtering equation. This event will count requests that lookup the cache multiple times with multiple increments. One must ALWAYS select a state or states (in the umask field) to match. Otherwise, the event will count nothing.", + "UMask": "0x400", "Unit": "CHA" }, { @@ -1773,6 +1778,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Cache Lookups : Transactions homed locally Filter : Counts the number of times the LLC was accessed - this includes code, data, prefetches and hints coming from L2. This has numerous filters available. Note the non-standard filtering equation. This event will count requests that lookup the cache multiple times with multiple increments. One must ALWAYS select a state or states (in the umask field) to match. Otherwise, the event will count nothing. : Transaction whose address resides in the local MC.", + "UMask": "0x80000", "Unit": "CHA" }, { @@ -1805,6 +1811,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Cache Lookups : Write Request Filter : Counts the number of times the LLC was accessed - this includes code, data, prefetches and hints coming from L2. This has numerous filters available. Note the non-standard filtering equation. This event will count requests that lookup the cache multiple times with multiple increments. One must ALWAYS select a state or states (in the umask field) to match. Otherwise, the event will count nothing. : Writeback transactions to the LLC This includes all write transactions -- both Cacheable and UC.", + "UMask": "0x200", "Unit": "CHA" }, { @@ -1925,6 +1932,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Cache Lookups : RFO Request Filter : Counts the number of times the LLC was accessed - this includes code, data, prefetches and hints coming from L2. This has numerous filters available. Note the non-standard filtering equation. This event will count requests that lookup the cache multiple times with multiple increments. One must ALWAYS select a state or states (in the umask field) to match. Otherwise, the event will count nothing. : Local or remote RFO transactions to the LLC. This includes RFO prefetch.", + "UMask": "0x800", "Unit": "CHA" }, { @@ -2077,6 +2085,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Lines Victimized : Local Only : Counts the number of lines that were victimized on a fill. This can be filtered by the state that the line was in.", + "UMask": "0x2000", "Unit": "CHA" }, { @@ -2195,6 +2204,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x10000000", "Unit": "CHA" }, { @@ -2205,6 +2215,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x20000000", "Unit": "CHA" }, { @@ -2215,6 +2226,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x80000", "Unit": "CHA" }, { @@ -2225,6 +2237,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x8000000", "Unit": "CHA" }, { @@ -2235,6 +2248,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x200", "Unit": "CHA" }, { @@ -2289,6 +2303,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x40000000", "Unit": "CHA" }, { @@ -2299,6 +2314,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x10000", "Unit": "CHA" }, { @@ -2309,6 +2325,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x2000", "Unit": "CHA" }, { @@ -2319,6 +2336,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x100", "Unit": "CHA" }, { @@ -2329,6 +2347,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x200000", "Unit": "CHA" }, { @@ -2339,6 +2358,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x4000000", "Unit": "CHA" }, { @@ -2349,6 +2369,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x800000", "Unit": "CHA" }, { @@ -2359,6 +2380,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x1000000", "Unit": "CHA" }, { @@ -2369,6 +2391,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x400", "Unit": "CHA" }, { @@ -2379,6 +2402,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x8000", "Unit": "CHA" }, { @@ -2411,6 +2435,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x100000", "Unit": "CHA" }, { @@ -2421,6 +2446,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x20000", "Unit": "CHA" }, { @@ -2431,6 +2457,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x400000", "Unit": "CHA" }, { @@ -2441,6 +2468,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x2000000", "Unit": "CHA" }, { @@ -2451,6 +2479,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x1000", "Unit": "CHA" }, { @@ -2461,6 +2490,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x80000000", "Unit": "CHA" }, { @@ -2471,6 +2501,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x100000000", "Unit": "CHA" }, { @@ -2481,6 +2512,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x200000000", "Unit": "CHA" }, { @@ -2491,6 +2523,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "Pipe Rejects : More Miscellaneous events in the Cbo.", + "UMask": "0x4000", "Unit": "CHA" }, { @@ -2523,6 +2556,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "CHA iMC CHNx READ Credits Empty : MC10 : Counts the number of times when there are no credits available for sending reads from the CHA into the iMC. In order to send reads into the memory controller, the HA must first acquire a credit for the iMC's AD Ingress queue. : Filter for memory controller 10 only.", + "UMask": "0x400", "Unit": "CHA" }, { @@ -2533,6 +2567,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "CHA iMC CHNx READ Credits Empty : MC11 : Counts the number of times when there are no credits available for sending reads from the CHA into the iMC. In order to send reads into the memory controller, the HA must first acquire a credit for the iMC's AD Ingress queue. : Filter for memory controller 11 only.", + "UMask": "0x800", "Unit": "CHA" }, { @@ -2543,6 +2578,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "CHA iMC CHNx READ Credits Empty : MC12 : Counts the number of times when there are no credits available for sending reads from the CHA into the iMC. In order to send reads into the memory controller, the HA must first acquire a credit for the iMC's AD Ingress queue. : Filter for memory controller 12 only.", + "UMask": "0x1000", "Unit": "CHA" }, { @@ -2553,6 +2589,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "CHA iMC CHNx READ Credits Empty : MC13 : Counts the number of times when there are no credits available for sending reads from the CHA into the iMC. In order to send reads into the memory controller, the HA must first acquire a credit for the iMC's AD Ingress queue. : Filter for memory controller 13 only.", + "UMask": "0x2000", "Unit": "CHA" }, { @@ -2629,6 +2666,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "CHA iMC CHNx READ Credits Empty : MC8 : Counts the number of times when there are no credits available for sending reads from the CHA into the iMC. In order to send reads into the memory controller, the HA must first acquire a credit for the iMC's AD Ingress queue. : Filter for memory controller 8 only.", + "UMask": "0x100", "Unit": "CHA" }, { @@ -2639,6 +2677,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "CHA iMC CHNx READ Credits Empty : MC9 : Counts the number of times when there are no credits available for sending reads from the CHA into the iMC. In order to send reads into the memory controller, the HA must first acquire a credit for the iMC's AD Ingress queue. : Filter for memory controller 9 only.", + "UMask": "0x200", "Unit": "CHA" }, { @@ -5047,6 +5086,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Inserts : DDR4 Access : Counts the number of entries successfully inserted into the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x400", "Unit": "CHA" }, { @@ -5057,6 +5097,7 @@ "EventName": "UNC_CHA_TOR_INSERTS.DDR4", "Experimental": "1", "PerPkg": "1", + "UMask": "0x400", "Unit": "CHA" }, { @@ -5078,6 +5119,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Inserts : Just Hits : Counts the number of entries successfully inserted into the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x100", "Unit": "CHA" }, { @@ -5687,6 +5729,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Inserts : Just ISOC : Counts the number of entries successfully inserted into the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x200000000", "Unit": "CHA" }, { @@ -5697,6 +5740,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Inserts : Just Local Targets : Counts the number of entries successfully inserted into the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x8000", "Unit": "CHA" }, { @@ -5740,6 +5784,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Inserts : Match the Opcode in b[29:19] of the extended umask field : Counts the number of entries successfully inserted into the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x20000", "Unit": "CHA" }, { @@ -5750,6 +5795,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Inserts : Just Misses : Counts the number of entries successfully inserted into the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x200", "Unit": "CHA" }, { @@ -5760,6 +5806,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Inserts : MMCFG Access : Counts the number of entries successfully inserted into the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x2000", "Unit": "CHA" }, { @@ -5770,6 +5817,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Inserts : Just NearMem : Counts the number of entries successfully inserted into the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x40000000", "Unit": "CHA" }, { @@ -5780,6 +5828,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Inserts : Just NonCoherent : Counts the number of entries successfully inserted into the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x100000000", "Unit": "CHA" }, { @@ -5790,6 +5839,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Inserts : Just NotNearMem : Counts the number of entries successfully inserted into the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x80000000", "Unit": "CHA" }, { @@ -5800,6 +5850,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Inserts : Match the PreMorphed Opcode in b[29:19] of the extended umask field : Counts the number of entries successfully inserted into the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x40000", "Unit": "CHA" }, { @@ -5832,6 +5883,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Occupancy : DDR4 Access : For each cycle, this event accumulates the number of valid entries in the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x400", "Unit": "CHA" }, { @@ -5853,6 +5905,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Occupancy : Just Hits : For each cycle, this event accumulates the number of valid entries in the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x100", "Unit": "CHA" }, { @@ -6440,6 +6493,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Occupancy : Just ISOC : For each cycle, this event accumulates the number of valid entries in the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x200000000", "Unit": "CHA" }, { @@ -6450,6 +6504,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Occupancy : Just Local Targets : For each cycle, this event accumulates the number of valid entries in the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x8000", "Unit": "CHA" }, { @@ -6493,6 +6548,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Occupancy : Match the Opcode in b[29:19] of the extended umask field : For each cycle, this event accumulates the number of valid entries in the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x20000", "Unit": "CHA" }, { @@ -6503,6 +6559,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Occupancy : Just Misses : For each cycle, this event accumulates the number of valid entries in the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x200", "Unit": "CHA" }, { @@ -6513,6 +6570,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Occupancy : MMCFG Access : For each cycle, this event accumulates the number of valid entries in the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x2000", "Unit": "CHA" }, { @@ -6523,6 +6581,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Occupancy : Just NearMem : For each cycle, this event accumulates the number of valid entries in the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x40000000", "Unit": "CHA" }, { @@ -6533,6 +6592,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Occupancy : Just NonCoherent : For each cycle, this event accumulates the number of valid entries in the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x100000000", "Unit": "CHA" }, { @@ -6543,6 +6603,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Occupancy : Just NotNearMem : For each cycle, this event accumulates the number of valid entries in the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x80000000", "Unit": "CHA" }, { @@ -6553,6 +6614,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "TOR Occupancy : Match the PreMorphed Opcode in b[29:19] of the extended umask field : For each cycle, this event accumulates the number of valid entries in the TOR that match qualifications specified by the subevent. Does not include addressless requests such as locks and interrupts.", + "UMask": "0x40000", "Unit": "CHA" }, { @@ -8356,6 +8418,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "CHA iMC CHNx WRITE Credits Empty : MC10 : Counts the number of times when there are no credits available for sending WRITEs from the CHA into the iMC. In order to send WRITEs into the memory controller, the HA must first acquire a credit for the iMC's BL Ingress queue. : Filter for memory controller 10 only.", + "UMask": "0x400", "Unit": "CHA" }, { @@ -8366,6 +8429,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "CHA iMC CHNx WRITE Credits Empty : MC11 : Counts the number of times when there are no credits available for sending WRITEs from the CHA into the iMC. In order to send WRITEs into the memory controller, the HA must first acquire a credit for the iMC's BL Ingress queue. : Filter for memory controller 11 only.", + "UMask": "0x800", "Unit": "CHA" }, { @@ -8376,6 +8440,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "CHA iMC CHNx WRITE Credits Empty : MC12 : Counts the number of times when there are no credits available for sending WRITEs from the CHA into the iMC. In order to send WRITEs into the memory controller, the HA must first acquire a credit for the iMC's BL Ingress queue. : Filter for memory controller 12 only.", + "UMask": "0x1000", "Unit": "CHA" }, { @@ -8386,6 +8451,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "CHA iMC CHNx WRITE Credits Empty : MC13 : Counts the number of times when there are no credits available for sending WRITEs from the CHA into the iMC. In order to send WRITEs into the memory controller, the HA must first acquire a credit for the iMC's BL Ingress queue. : Filter for memory controller 13 only.", + "UMask": "0x2000", "Unit": "CHA" }, { @@ -8462,6 +8528,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "CHA iMC CHNx WRITE Credits Empty : MC8 : Counts the number of times when there are no credits available for sending WRITEs from the CHA into the iMC. In order to send WRITEs into the memory controller, the HA must first acquire a credit for the iMC's BL Ingress queue. : Filter for memory controller 8 only.", + "UMask": "0x100", "Unit": "CHA" }, { @@ -8472,6 +8539,7 @@ "Experimental": "1", "PerPkg": "1", "PublicDescription": "CHA iMC CHNx WRITE Credits Empty : MC9 : Counts the number of times when there are no credits available for sending WRITEs from the CHA into the iMC. In order to send WRITEs into the memory controller, the HA must first acquire a credit for the iMC's BL Ingress queue. : Filter for memory controller 9 only.", + "UMask": "0x200", "Unit": "CHA" }, { diff --git a/tools/perf/pmu-events/arch/x86/snowridgex/uncore-interconnect.json b/tools/perf/pmu-events/arch/x86/snowridgex/uncore-interconnect.json index 88ee90b8a2d9..9667e4f48c13 100644 --- a/tools/perf/pmu-events/arch/x86/snowridgex/uncore-interconnect.json +++ b/tools/perf/pmu-events/arch/x86/snowridgex/uncore-interconnect.json @@ -2210,6 +2210,7 @@ "EventName": "UNC_M2M_IMC_WRITES.CH0_FROM_TGR", "Experimental": "1", "PerPkg": "1", + "UMask": "0x500", "Unit": "M2M" }, { @@ -2239,6 +2240,7 @@ "EventName": "UNC_M2M_IMC_WRITES.CH0_NI_MISS", "Experimental": "1", "PerPkg": "1", + "UMask": "0x2000", "Unit": "M2M" }, { @@ -2278,6 +2280,7 @@ "EventName": "UNC_M2M_IMC_WRITES.CH1_FROM_TGR", "Experimental": "1", "PerPkg": "1", + "UMask": "0x900", "Unit": "M2M" }, { @@ -2307,6 +2310,7 @@ "EventName": "UNC_M2M_IMC_WRITES.CH1_NI_MISS", "Experimental": "1", "PerPkg": "1", + "UMask": "0xc00", "Unit": "M2M" }, { @@ -2336,6 +2340,7 @@ "EventName": "UNC_M2M_IMC_WRITES.FROM_TGR", "Experimental": "1", "PerPkg": "1", + "UMask": "0x1d00", "Unit": "M2M" }, { @@ -2365,6 +2370,7 @@ "EventName": "UNC_M2M_IMC_WRITES.NI_MISS", "Experimental": "1", "PerPkg": "1", + "UMask": "0x1c00", "Unit": "M2M" }, { @@ -2837,6 +2843,7 @@ "EventName": "UNC_M2M_PREFCAM_DROP_REASONS_CH0.RPQ_PROXY", "Experimental": "1", "PerPkg": "1", + "UMask": "0x100", "Unit": "M2M" }, { @@ -2866,6 +2873,7 @@ "EventName": "UNC_M2M_PREFCAM_DROP_REASONS_CH0.XPT_THRESH", "Experimental": "1", "PerPkg": "1", + "UMask": "0x200", "Unit": "M2M" }, { @@ -2935,6 +2943,7 @@ "EventName": "UNC_M2M_PREFCAM_DROP_REASONS_CH1.RPQ_PROXY", "Experimental": "1", "PerPkg": "1", + "UMask": "0x100", "Unit": "M2M" }, { @@ -2964,6 +2973,7 @@ "EventName": "UNC_M2M_PREFCAM_DROP_REASONS_CH1.XPT_THRESH", "Experimental": "1", "PerPkg": "1", + "UMask": "0x200", "Unit": "M2M" }, { diff --git a/tools/perf/pmu-events/jevents.py b/tools/perf/pmu-events/jevents.py index 860027bb71b2..d81fe6757915 100755 --- a/tools/perf/pmu-events/jevents.py +++ b/tools/perf/pmu-events/jevents.py @@ -1450,6 +1450,13 @@ const char *describe_metricgroup(const char *group) } """) +# Upper bound on the number of workers reading JSON files in parallel. +_max_parallel_workers = 32 + +def _parallel_worker_count(num_tasks: int) -> int: + return max(1, min(getattr(os, 'process_cpu_count', os.cpu_count)() or 1, + _max_parallel_workers, num_tasks)) + def _parallel_read_json_events(task: Tuple[str, str]) -> Tuple[str, str, Sequence[JsonEvent]]: path, topic = task return path, topic, _read_json_events_impl(path, topic) @@ -1549,7 +1556,9 @@ struct pmu_table_entry { preprocess_arch_std_files(arch_path) ftw(arch_path, [], collect_json) - with concurrent.futures.ProcessPoolExecutor(initializer=_init_worker, initargs=(_arch_std_events,)) as executor: + with concurrent.futures.ProcessPoolExecutor(max_workers=_parallel_worker_count(len(tasks)), + initializer=_init_worker, + initargs=(_arch_std_events,)) as executor: for path, topic, events in executor.map(_parallel_read_json_events, tasks): _json_cache[(path, topic)] = events diff --git a/tools/perf/tests/Build b/tools/perf/tests/Build index 66944a4f4968..8c6a9c4d39b4 100644 --- a/tools/perf/tests/Build +++ b/tools/perf/tests/Build @@ -118,4 +118,6 @@ $(OUTPUT)%.pylint_log: % $(call rule_mkdir) $(Q)$(call echo-cmd,test)pylint "$<" > $@ || (cat $@ && rm $@ && false) -perf-test-y += $(PYLINT_TEST_LOGS) +.PHONY: pylint +pylint: $(addprefix $(OUTPUT)tests/,$(PYLINT_TEST_LOGS)) + @: diff --git a/tools/perf/tests/code-reading.c b/tools/perf/tests/code-reading.c index f0e8ea8754ef..c50b526f44fb 100644 --- a/tools/perf/tests/code-reading.c +++ b/tools/perf/tests/code-reading.c @@ -716,10 +716,8 @@ static int do_test_code_reading(bool try_kcore) perf_env__init(&host_env); machine = machine__new_host(&host_env); - - ret = machine__create_kernel_maps(machine); - if (ret < 0) { - pr_debug("machine__create_kernel_maps failed\n"); + if (!machine) { + pr_debug("machine__new_host failed\n"); goto out_err; } @@ -739,8 +737,10 @@ static int do_test_code_reading(bool try_kcore) have_kcore = dso__is_kcore(dso); /* 2nd time through we just try kcore */ - if (try_kcore && !have_kcore) - return TEST_CODE_READING_NO_KCORE; + if (try_kcore && !have_kcore) { + err = TEST_CODE_READING_NO_KCORE; + goto out_err; + } /* No point getting kernel events if there is no kernel object */ if (!have_vmlinux && !have_kcore) diff --git a/tools/perf/tests/demangle-java-test.c b/tools/perf/tests/demangle-java-test.c index 0fb3e5a4a0ed..a8eb0f4effad 100644 --- a/tools/perf/tests/demangle-java-test.c +++ b/tools/perf/tests/demangle-java-test.c @@ -33,6 +33,7 @@ static int test__demangle_java(struct test_suite *test __maybe_unused, int subte if (!buf) { pr_debug("FAILED to demangle: \"%s\"\n \"%s\"\n", test_cases[i].mangled, test_cases[i].demangled); + ret = TEST_FAIL; continue; } if (strcmp(buf, test_cases[i].demangled)) { diff --git a/tools/perf/tests/demangle-rust-v0-test.c b/tools/perf/tests/demangle-rust-v0-test.c index 904f966c65d7..ee4ddb61174b 100644 --- a/tools/perf/tests/demangle-rust-v0-test.c +++ b/tools/perf/tests/demangle-rust-v0-test.c @@ -58,6 +58,7 @@ static int test__demangle_rust(struct test_suite *test __maybe_unused, int subte if (!buf) { pr_debug("FAILED to demangle: \"%s\"\n \"%s\"\n", test_cases[i].mangled, test_cases[i].demangled); + ret = TEST_FAIL; continue; } if (strcmp(buf, test_cases[i].demangled)) { diff --git a/tools/perf/tests/fdarray.c b/tools/perf/tests/fdarray.c index 40983c3574b1..23860edb8ef0 100644 --- a/tools/perf/tests/fdarray.c +++ b/tools/perf/tests/fdarray.c @@ -80,6 +80,38 @@ static int test__fdarray__filter(struct test_suite *test __maybe_unused, int sub goto out_delete; } + fdarray__init_revents(fda, POLLHUP); + fda->priv[2].flags = fdarray_flag__nonfilterable; + + pr_debug("\nfiltering all but fda->entries[2] (nonfilterable):"); + fdarray__fprintf_prefix(fda, "before", stderr); + + /* + * Note: fdarray__filter() in tools/lib/api/fd/array.c evaluates the + * fdarray_flag__nonfilterable flag at the very top of its loop via an + * early continue. Therefore, it completely skips all processing for this + * descriptor, guaranteeing its fd, events, and revents fields remain + * entirely untouched by the filter mask evaluation below it. + */ + nr_fds = fdarray__filter(fda, POLLHUP, NULL, NULL); + fdarray__fprintf_prefix(fda, " after", stderr); + + if (nr_fds != 0) { + pr_debug("\nfdarray__filter()=%d != 0, should be 0\n", + nr_fds); + goto out_delete; + } + if (fda->entries[2].fd == -1) { + pr_debug("\nfdarray__filter() illegally modified nonfilterable fd!"); + goto out_delete; + } + if (fda->entries[2].revents != POLLHUP) { + pr_debug("\nfdarray__filter() illegally modified nonfilterable revents!"); + goto out_delete; + } + + fda->priv[2].flags = 0; /* reset flags */ + pr_debug("\n"); err = 0; diff --git a/tools/perf/tests/hists_cumulate.c b/tools/perf/tests/hists_cumulate.c index 9356451a172e..c4a11a3255bc 100644 --- a/tools/perf/tests/hists_cumulate.c +++ b/tools/perf/tests/hists_cumulate.c @@ -723,7 +723,7 @@ static int test__hists_cumulate(struct test_suite *test __maybe_unused, int subt goto out; err = TEST_FAIL; - if (machines__init(&machines)) + if (machines__init(&machines, /*session=*/NULL)) goto out; /* setup threads/dso/map/symbols also */ diff --git a/tools/perf/tests/hists_filter.c b/tools/perf/tests/hists_filter.c index f9eaa511487b..6c7e4cdc71a7 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; - if (machines__init(&machines)) + if (machines__init(&machines, /*session=*/NULL)) goto out; /* setup threads/dso/map/symbols also */ diff --git a/tools/perf/tests/hists_link.c b/tools/perf/tests/hists_link.c index d88591bcbe50..cd32c8277627 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; - if (machines__init(&machines)) + if (machines__init(&machines, /*session=*/NULL)) goto out; /* setup threads/dso/map/symbols also */ diff --git a/tools/perf/tests/hists_output.c b/tools/perf/tests/hists_output.c index f58c8d18fe33..35d230a83e43 100644 --- a/tools/perf/tests/hists_output.c +++ b/tools/perf/tests/hists_output.c @@ -610,7 +610,7 @@ static int test__hists_output(struct test_suite *test __maybe_unused, int subtes goto out; err = TEST_FAIL; - if (machines__init(&machines)) + if (machines__init(&machines, /*session=*/NULL)) goto out; /* setup threads/dso/map/symbols also */ diff --git a/tools/perf/tests/make b/tools/perf/tests/make index d2c2f526e1db..c4c3cf4737fe 100644 --- a/tools/perf/tests/make +++ b/tools/perf/tests/make @@ -155,7 +155,6 @@ run += make_no_demangle run += make_no_libelf run += make_no_libdw run += make_libunwind -run += make_no_libdw_dwarf_unwind run += make_no_backtrace run += make_no_libcapstone run += make_libcapstone_dlopen @@ -165,10 +164,8 @@ run += make_no_libbpf run += make_no_libbpf_DEBUG run += make_no_libllvm run += make_no_sdt -run += make_no_syscall_tbl run += make_no_babeltrace2 run += make_with_coresight -run += make_with_clangllvm run += make_no_libpfm4 run += make_refcnt_check run += make_help diff --git a/tools/perf/tests/pe-file-parsing.c b/tools/perf/tests/pe-file-parsing.c index 30c7da79e109..3979f38bf127 100644 --- a/tools/perf/tests/pe-file-parsing.c +++ b/tools/perf/tests/pe-file-parsing.c @@ -59,7 +59,7 @@ static int run_dir(const char *d) TEST_ASSERT_VAL("Failed to get dso", dso); ret = dso__load_bfd_symbols(dso, debugfile); - TEST_ASSERT_VAL("Failed to load symbols", ret == 0); + TEST_ASSERT_VAL("Failed to load symbols", ret > 0); dso__sort_by_name(dso); sym = dso__find_symbol_by_name(dso, "main", &idx); diff --git a/tools/perf/tests/sample-parsing.c b/tools/perf/tests/sample-parsing.c index 32dbc484487a..bd30f6d4c31b 100644 --- a/tools/perf/tests/sample-parsing.c +++ b/tools/perf/tests/sample-parsing.c @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-2.0 #include +#include #include #include #include @@ -417,6 +418,98 @@ static int do_test(u64 sample_type, u64 sample_regs, u64 read_format) return ret; } +static int test_truncated_branch_stack(void) +{ + struct perf_event_attr attr = { + .sample_type = PERF_SAMPLE_BRANCH_STACK, + }; + struct { + struct perf_event_header header; + u64 nr; + struct branch_entry entry; + } input = { + .header = { + .type = PERF_RECORD_SAMPLE, + .size = sizeof(input.header) + sizeof(input.nr), + }, + .nr = 1, + }; + struct perf_sample sample; + struct evsel *evsel; + u64 flags = 1; + int err; + + input.entry.flags.value = flags; + evsel = evsel__new(&attr); + if (!evsel) + return -1; + + evsel->sample_size = __evsel__sample_size(attr.sample_type); + err = __evsel__parse_sample(evsel, (union perf_event *)&input, + &sample, /*needs_swap=*/true); + perf_sample__exit(&sample); + evsel__put(evsel); + + if (err != -EFAULT) { + pr_debug("truncated branch stack returned %d, expected -EFAULT\n", err); + return -1; + } + if (input.entry.flags.value != flags) { + pr_debug("truncated branch stack modified data past the event\n"); + return -1; + } + return 0; +} + +static int test_truncated_swapped_raw(u16 event_size, u32 raw_size) +{ + struct perf_event_attr attr = { + .sample_type = PERF_SAMPLE_RAW, + }; + struct { + struct perf_event_header header; + union { + u64 value; + u32 words[2]; + } raw; + u64 canary; + } input = { + .header = { + .type = PERF_RECORD_SAMPLE, + .size = event_size, + }, + /* Parsing a pre-swapped word exchanges these two u32 values. */ + .raw.words = { 0x12345678, raw_size }, + .canary = 0x8877665544332211ULL, + }; + struct perf_sample sample; + struct evsel *evsel; + u64 raw = input.raw.value; + u64 canary = input.canary; + int err; + + evsel = evsel__new(&attr); + if (!evsel) + return -1; + + evsel->sample_size = __evsel__sample_size(attr.sample_type); + err = __evsel__parse_sample(evsel, (union perf_event *)&input, + &sample, /*needs_swap=*/true); + perf_sample__exit(&sample); + evsel__put(evsel); + + if (err != -EFAULT) { + pr_debug("truncated swapped RAW sample (size %u, raw %u) returned %d, expected -EFAULT\n", + event_size, raw_size, err); + return -1; + } + if (input.raw.value != raw || input.canary != canary) { + pr_debug("truncated swapped RAW sample modified data before validation\n"); + return -1; + } + return 0; +} + /** * test__sample_parsing - test sample parsing. * @@ -433,6 +526,22 @@ static int test__sample_parsing(struct test_suite *test __maybe_unused, int subt size_t i; int err; + err = test_truncated_branch_stack(); + if (err) + return err; + + /* The declared RAW payload extends past an otherwise aligned event. */ + err = test_truncated_swapped_raw(sizeof(struct perf_event_header) + + sizeof(u64), 16); + if (err) + return err; + + /* The final complete word touched by mem_bswap_64() extends past it. */ + err = test_truncated_swapped_raw(sizeof(struct perf_event_header) + + sizeof(u32) + 9, 9); + if (err) + return err; + /* * Fail the test if it has not been updated when new sample format bits * were added. Please actually update the test rather than just change diff --git a/tools/perf/tests/shell/attr.sh b/tools/perf/tests/shell/attr.sh index 5a4e43b2471d..ca3ca4a19397 100755 --- a/tools/perf/tests/shell/attr.sh +++ b/tools/perf/tests/shell/attr.sh @@ -4,6 +4,10 @@ err=0 +shelldir=$(dirname "$0") +# shellcheck source=lib/setup_python.sh +. "${shelldir}"/lib/setup_python.sh + cleanup() { trap - EXIT TERM INT } @@ -17,6 +21,7 @@ trap trap_cleanup EXIT TERM INT shelldir=$(dirname "$0") perf_path=$(which perf) -python "${shelldir}"/lib/attr.py -d "${shelldir}"/attr -v -p "$perf_path" +$PYTHON "${shelldir}"/lib/attr.py -d "${shelldir}"/attr -v -p "$perf_path" +err=$? cleanup exit $err diff --git a/tools/perf/tests/shell/attr/README b/tools/perf/tests/shell/attr/README index 67c4ca76b85d..c7b49cdf8729 100644 --- a/tools/perf/tests/shell/attr/README +++ b/tools/perf/tests/shell/attr/README @@ -49,10 +49,10 @@ Following tests are defined (with perf commands): perf record --call-graph dwarf kill (test-record-graph-dwarf) perf record --call-graph fp kill (test-record-graph-fp) perf record --call-graph fp kill (test-record-graph-fp-aarch64) - perf record -e '{cycles,instructions}' kill (test-record-group1) - perf record -e '{cycles/period=1/,instructions/period=2/}:S' kill (test-record-group2) - perf record -e '{cycles,cache-misses}:S' kill (test-record-group-sampling1) - perf record -c 10000 -e '{cycles,cache-misses}:S' kill (test-record-group-sampling2) + perf record -e '{cycles,default_core/legacy-hardware-config=1/}' kill (test-record-group1) + perf record -e '{cycles/period=1234000/,default_core/legacy-hardware-config=1,period=6789000/}:S' kill (test-record-group2) + perf record -e '{cycles,default_core/legacy-hardware-config=3/}:S' kill (test-record-group-sampling1) + perf record -c 10000 -e '{cycles,default_core/legacy-hardware-config=3/}:S' kill (test-record-group-sampling2) perf record -D kill (test-record-no-delay) perf record -i kill (test-record-no-inherit) perf record -n kill (test-record-no-samples) @@ -67,5 +67,5 @@ Following tests are defined (with perf commands): perf stat -d kill (test-stat-detailed-1) perf stat -dd kill (test-stat-detailed-2) perf stat -ddd kill (test-stat-detailed-3) - perf stat -e '{cycles,instructions}' kill (test-stat-group1) + perf stat -e '{cycles,default_core/legacy-hardware-config=1/}' kill (test-stat-group1) perf stat -i -e cycles kill (test-stat-no-inherit) diff --git a/tools/perf/tests/shell/attr/base-record b/tools/perf/tests/shell/attr/base-record index b44e4e6e4443..a4597d4c0cd1 100644 --- a/tools/perf/tests/shell/attr/base-record +++ b/tools/perf/tests/shell/attr/base-record @@ -5,7 +5,7 @@ group_fd=-1 flags=0|8 cpu=* type=0|1 -size=136 +size=176 config=0|1 sample_period=* sample_type=263 diff --git a/tools/perf/tests/shell/attr/base-stat b/tools/perf/tests/shell/attr/base-stat index fccd8ec4d1b0..67d6eea89470 100644 --- a/tools/perf/tests/shell/attr/base-stat +++ b/tools/perf/tests/shell/attr/base-stat @@ -5,7 +5,7 @@ group_fd=-1 flags=0|8 cpu=* type=0 -size=136 +size=176 config=0 sample_period=0 sample_type=65536 diff --git a/tools/perf/tests/shell/attr/base-stat-group b/tools/perf/tests/shell/attr/base-stat-group new file mode 100644 index 000000000000..9bcb8ab3687f --- /dev/null +++ b/tools/perf/tests/shell/attr/base-stat-group @@ -0,0 +1,45 @@ +[event] +fd=1 +group_fd=-1 +# 0 or PERF_FLAG_FD_CLOEXEC flag +flags=0|8 +cpu=* +type=0 +size=176 +config=0 +sample_period=0 +sample_type=65536 +# The default and -d/-dd/-ddd metrics open part of their events in groups: +# the members get read_format=15 and are enabled right away, the standalone +# ones keep read_format=3 and wait for the exec, and the leaders get 15 when +# their group has members, 3 when alone, as create_perf_stat_counter() goes. +read_format=3|15 +disabled=0|1 +inherit=1 +pinned=0 +exclusive=0 +exclude_user=0 +exclude_kernel=0|1 +exclude_hv=0|1 +exclude_idle=0 +mmap=0 +comm=0 +freq=0 +inherit_stat=0 +enable_on_exec=0|1 +task=0 +watermark=0 +precise_ip=0 +mmap_data=0 +sample_id_all=0 +exclude_host=0|1 +exclude_guest=0|1 +exclude_callchain_kernel=0 +exclude_callchain_user=0 +wakeup_events=0 +bp_type=0 +config1=0 +config2=0 +branch_sample_type=0 +sample_regs_user=0 +sample_stack_user=0 diff --git a/tools/perf/tests/shell/attr/system-wide-dummy b/tools/perf/tests/shell/attr/system-wide-dummy index a1e1d6a263bf..b062ad7f3c1c 100644 --- a/tools/perf/tests/shell/attr/system-wide-dummy +++ b/tools/perf/tests/shell/attr/system-wide-dummy @@ -7,7 +7,7 @@ cpu=* pid=-1 flags=8 type=1 -size=136 +size=176 config=9 sample_period=1 # PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_TIME | diff --git a/tools/perf/tests/shell/attr/test-record-dummy-C0 b/tools/perf/tests/shell/attr/test-record-dummy-C0 index 91499405fff4..54adb835d203 100644 --- a/tools/perf/tests/shell/attr/test-record-dummy-C0 +++ b/tools/perf/tests/shell/attr/test-record-dummy-C0 @@ -10,7 +10,7 @@ cpu=0 pid=-1 flags=8 type=1 -size=136 +size=176 config=9 sample_period=4000 # PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_TIME | diff --git a/tools/perf/tests/shell/attr/test-record-graph-dwarf b/tools/perf/tests/shell/attr/test-record-graph-dwarf index ae92061d611d..fbe0faa8cdb6 100644 --- a/tools/perf/tests/shell/attr/test-record-graph-dwarf +++ b/tools/perf/tests/shell/attr/test-record-graph-dwarf @@ -4,7 +4,7 @@ args = --no-bpf-event --call-graph dwarf -- kill >/dev/null 2>&1 ret = 1 [event:base-record] -sample_type=45359 +sample_type=12583 exclude_callchain_user=1 sample_stack_user=8192 # TODO different for each arch, no support for that now diff --git a/tools/perf/tests/shell/attr/test-record-group-sampling b/tools/perf/tests/shell/attr/test-record-group-sampling index 86a940d7895d..766aadef2f1f 100644 --- a/tools/perf/tests/shell/attr/test-record-group-sampling +++ b/tools/perf/tests/shell/attr/test-record-group-sampling @@ -1,6 +1,6 @@ [config] command = record -args = --no-bpf-event -e '{cycles,cache-misses}:S' kill >/dev/null 2>&1 +args = --no-bpf-event -e '{cycles,default_core/legacy-hardware-config=3/}:S' kill >/dev/null 2>&1 ret = 1 kernel_until = 6.12 @@ -15,7 +15,7 @@ inherit=0 fd=2 group_fd=1 -# cache-misses +# cache-misses, explicitly requested with the legacy hardware encoding type=0 config=3 diff --git a/tools/perf/tests/shell/attr/test-record-group-sampling1 b/tools/perf/tests/shell/attr/test-record-group-sampling1 index 4748ab7bf684..5be9a1a2a4ff 100644 --- a/tools/perf/tests/shell/attr/test-record-group-sampling1 +++ b/tools/perf/tests/shell/attr/test-record-group-sampling1 @@ -1,6 +1,6 @@ [config] command = record -args = --no-bpf-event -e '{cycles,cache-misses}:S' kill >/dev/null 2>&1 +args = --no-bpf-event -e '{cycles,default_core/legacy-hardware-config=3/}:S' kill >/dev/null 2>&1 ret = 1 kernel_since = 6.12 @@ -30,7 +30,7 @@ inherit=1 fd=2 group_fd=1 -# cache-misses +# cache-misses, explicitly requested with the legacy hardware encoding type=0 config=3 diff --git a/tools/perf/tests/shell/attr/test-record-group-sampling2 b/tools/perf/tests/shell/attr/test-record-group-sampling2 index e0432244a0eb..c05225167ec3 100644 --- a/tools/perf/tests/shell/attr/test-record-group-sampling2 +++ b/tools/perf/tests/shell/attr/test-record-group-sampling2 @@ -1,6 +1,6 @@ [config] command = record -args = --no-bpf-event -c 10000 -e '{cycles,cache-misses}:S' kill >/dev/null 2>&1 +args = --no-bpf-event -c 10000 -e '{cycles,default_core/legacy-hardware-config=3/}:S' kill >/dev/null 2>&1 ret = 1 kernel_since = 6.12 @@ -36,7 +36,7 @@ write_backward=0 fd=2 group_fd=1 -# cache-misses +# cache-misses, explicitly requested with the legacy hardware encoding type=0 config=3 diff --git a/tools/perf/tests/shell/attr/test-record-group1 b/tools/perf/tests/shell/attr/test-record-group1 index eeb1db392bc9..0437ea4939e8 100644 --- a/tools/perf/tests/shell/attr/test-record-group1 +++ b/tools/perf/tests/shell/attr/test-record-group1 @@ -1,6 +1,6 @@ [config] command = record -args = --no-bpf-event -e '{cycles,instructions}' kill >/dev/null 2>&1 +args = --no-bpf-event -e '{cycles,default_core/legacy-hardware-config=1/}' kill >/dev/null 2>&1 ret = 1 [event-1:base-record] diff --git a/tools/perf/tests/shell/attr/test-record-group2 b/tools/perf/tests/shell/attr/test-record-group2 index 891d41a7bddf..ca5bbf441968 100644 --- a/tools/perf/tests/shell/attr/test-record-group2 +++ b/tools/perf/tests/shell/attr/test-record-group2 @@ -1,6 +1,6 @@ [config] command = record -args = --no-bpf-event -e '{cycles/period=1234000/,instructions/period=6789000/}:S' kill >/dev/null 2>&1 +args = --no-bpf-event -e '{cycles/period=1234000/,default_core/legacy-hardware-config=1,period=6789000/}:S' kill >/dev/null 2>&1 ret = 1 kernel_until = 6.12 diff --git a/tools/perf/tests/shell/attr/test-record-group3 b/tools/perf/tests/shell/attr/test-record-group3 index 249be884959e..8191b3af936d 100644 --- a/tools/perf/tests/shell/attr/test-record-group3 +++ b/tools/perf/tests/shell/attr/test-record-group3 @@ -1,6 +1,6 @@ [config] command = record -args = --no-bpf-event -e '{cycles/period=1234000/,instructions/period=6789000/}:S' kill >/dev/null 2>&1 +args = --no-bpf-event -e '{cycles/period=1234000/,default_core/legacy-hardware-config=1,period=6789000/}:S' kill >/dev/null 2>&1 ret = 1 kernel_since = 6.12 diff --git a/tools/perf/tests/shell/attr/test-stat-default b/tools/perf/tests/shell/attr/test-stat-default index 8dd27c1fb661..ed4129de7d6c 100644 --- a/tools/perf/tests/shell/attr/test-stat-default +++ b/tools/perf/tests/shell/attr/test-stat-default @@ -4,72 +4,72 @@ args = kill >/dev/null 2>&1 ret = 1 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_TASK_CLOCK -[event1:base-stat] +[event1:base-stat-group] fd=1 type=1 config=1 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_CONTEXT_SWITCHES -[event2:base-stat] +[event2:base-stat-group] fd=2 type=1 config=3 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_CPU_MIGRATIONS -[event3:base-stat] +[event3:base-stat-group] fd=3 type=1 config=4 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_PAGE_FAULTS -[event4:base-stat] +[event4:base-stat-group] fd=4 type=1 config=2 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_CPU_CYCLES -[event5:base-stat] +[event5:base-stat-group] fd=5 type=0 config=0 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_STALLED_CYCLES_FRONTEND -[event6:base-stat] +[event6:base-stat-group] fd=6 type=0 config=7 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_STALLED_CYCLES_BACKEND -[event7:base-stat] +[event7:base-stat-group] fd=7 type=0 config=8 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_INSTRUCTIONS -[event8:base-stat] +[event8:base-stat-group] fd=8 type=0 config=1 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_BRANCH_INSTRUCTIONS -[event9:base-stat] +[event9:base-stat-group] fd=9 type=0 config=4 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_BRANCH_MISSES -[event10:base-stat] +[event10:base-stat-group] fd=10 type=0 config=5 optional=1 # PERF_TYPE_RAW / slots (0x400) -[event11:base-stat] +[event11:base-stat-group] fd=11 group_fd=-1 type=4 @@ -78,7 +78,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-retiring (0x8000) -[event12:base-stat] +[event12:base-stat-group] fd=12 group_fd=11 type=4 @@ -89,7 +89,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-bad-spec (0x8100) -[event13:base-stat] +[event13:base-stat-group] fd=13 group_fd=11 type=4 @@ -100,7 +100,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-fe-bound (0x8200) -[event14:base-stat] +[event14:base-stat-group] fd=14 group_fd=11 type=4 @@ -111,7 +111,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-be-bound (0x8300) -[event15:base-stat] +[event15:base-stat-group] fd=15 group_fd=11 type=4 @@ -122,7 +122,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-heavy-ops (0x8400) -[event16:base-stat] +[event16:base-stat-group] fd=16 group_fd=11 type=4 @@ -133,7 +133,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-br-mispredict (0x8500) -[event17:base-stat] +[event17:base-stat-group] fd=17 group_fd=11 type=4 @@ -144,7 +144,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-fetch-lat (0x8600) -[event18:base-stat] +[event18:base-stat-group] fd=18 group_fd=11 type=4 @@ -155,7 +155,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-mem-bound (0x8700) -[event19:base-stat] +[event19:base-stat-group] fd=19 group_fd=11 type=4 @@ -166,71 +166,99 @@ read_format=15 optional=1 # PERF_TYPE_RAW / INT_MISC.UOP_DROPPING -[event20:base-stat] +[event20:base-stat-group] fd=20 type=4 config=4109 optional=1 # PERF_TYPE_RAW / cpu/INT_MISC.RECOVERY_CYCLES,cmask=1,edge/ -[event21:base-stat] +[event21:base-stat-group] fd=21 type=4 config=17039629 optional=1 -# PERF_TYPE_RAW / CPU_CLK_UNHALTED.THREAD -[event22:base-stat] +# PERF_TYPE_RAW / cpu-cycles (core PMU sysfs event; Intel 0x3c, AMD 0x76) +[event22:base-stat-group] fd=22 type=4 -config=60 +config=60|118 optional=1 # PERF_TYPE_RAW / INT_MISC.RECOVERY_CYCLES_ANY -[event23:base-stat] +[event23:base-stat-group] fd=23 type=4 config=2097421 optional=1 # PERF_TYPE_RAW / CPU_CLK_UNHALTED.REF_XCLK -[event24:base-stat] +[event24:base-stat-group] fd=24 type=4 config=316 optional=1 # PERF_TYPE_RAW / IDQ_UOPS_NOT_DELIVERED.CORE -[event25:base-stat] +[event25:base-stat-group] fd=25 type=4 config=412 optional=1 # PERF_TYPE_RAW / CPU_CLK_UNHALTED.ONE_THREAD_ACTIVE -[event26:base-stat] +[event26:base-stat-group] fd=26 type=4 config=572 optional=1 # PERF_TYPE_RAW / UOPS_RETIRED.RETIRE_SLOTS -[event27:base-stat] +[event27:base-stat-group] fd=27 type=4 config=706 optional=1 # PERF_TYPE_RAW / UOPS_ISSUED.ANY -[event28:base-stat] +[event28:base-stat-group] fd=28 type=4 config=270 optional=1 # PERF_TYPE_RAW / INT_MISC.UOP_DROPPING -[event29:base-stat] +[event29:base-stat-group] fd=29 type=4 config=4269 +optional=1 + +# PERF_TYPE_RAW / instructions (core PMU sysfs event) +[event30:base-stat-group] +fd=30 +type=4 +config=192 +optional=1 + +# PERF_TYPE_RAW / branch-misses (core PMU sysfs event; Intel 0xc5, AMD 0xc3) +[event31:base-stat-group] +fd=31 +type=4 +config=197|195 +optional=1 + +# PERF_TYPE_RAW / stalled-cycles-frontend (core PMU sysfs event; Intel 0x180010e, AMD 0xd0/0x287/0xa9) +[event32:base-stat-group] +fd=32 +type=4 +config=25166094|208|647|169 +optional=1 + +# PERF_TYPE_RAW / stalled-cycles-backend (core PMU sysfs event; Intel 0x18001b1/0x1803fb1, AMD 0xd1/0x187) +[event33:base-stat-group] +fd=33 +type=4 +config=25166257|25182129|209|391 optional=1 \ No newline at end of file diff --git a/tools/perf/tests/shell/attr/test-stat-detailed-1 b/tools/perf/tests/shell/attr/test-stat-detailed-1 index 12a2ebf4e64a..44fd0d6a3510 100644 --- a/tools/perf/tests/shell/attr/test-stat-detailed-1 +++ b/tools/perf/tests/shell/attr/test-stat-detailed-1 @@ -5,73 +5,73 @@ ret = 1 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_TASK_CLOCK -[event1:base-stat] +[event1:base-stat-group] fd=1 type=1 config=1 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_CONTEXT_SWITCHES -[event2:base-stat] +[event2:base-stat-group] fd=2 type=1 config=3 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_CPU_MIGRATIONS -[event3:base-stat] +[event3:base-stat-group] fd=3 type=1 config=4 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_PAGE_FAULTS -[event4:base-stat] +[event4:base-stat-group] fd=4 type=1 config=2 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_CPU_CYCLES -[event5:base-stat] +[event5:base-stat-group] fd=5 type=0 config=0 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_STALLED_CYCLES_FRONTEND -[event6:base-stat] +[event6:base-stat-group] fd=6 type=0 config=7 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_STALLED_CYCLES_BACKEND -[event7:base-stat] +[event7:base-stat-group] fd=7 type=0 config=8 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_INSTRUCTIONS -[event8:base-stat] +[event8:base-stat-group] fd=8 type=0 config=1 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_BRANCH_INSTRUCTIONS -[event9:base-stat] +[event9:base-stat-group] fd=9 type=0 config=4 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_BRANCH_MISSES -[event10:base-stat] +[event10:base-stat-group] fd=10 type=0 config=5 optional=1 # PERF_TYPE_RAW / slots (0x400) -[event11:base-stat] +[event11:base-stat-group] fd=11 group_fd=-1 type=4 @@ -80,7 +80,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-retiring (0x8000) -[event12:base-stat] +[event12:base-stat-group] fd=12 group_fd=11 type=4 @@ -91,7 +91,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-bad-spec (0x8100) -[event13:base-stat] +[event13:base-stat-group] fd=13 group_fd=11 type=4 @@ -102,7 +102,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-fe-bound (0x8200) -[event14:base-stat] +[event14:base-stat-group] fd=14 group_fd=11 type=4 @@ -113,7 +113,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-be-bound (0x8300) -[event15:base-stat] +[event15:base-stat-group] fd=15 group_fd=11 type=4 @@ -124,7 +124,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-heavy-ops (0x8400) -[event16:base-stat] +[event16:base-stat-group] fd=16 group_fd=11 type=4 @@ -135,7 +135,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-br-mispredict (0x8500) -[event17:base-stat] +[event17:base-stat-group] fd=17 group_fd=11 type=4 @@ -146,7 +146,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-fetch-lat (0x8600) -[event18:base-stat] +[event18:base-stat-group] fd=18 group_fd=11 type=4 @@ -157,7 +157,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-mem-bound (0x8700) -[event19:base-stat] +[event19:base-stat-group] fd=19 group_fd=11 type=4 @@ -168,63 +168,63 @@ read_format=15 optional=1 # PERF_TYPE_RAW / INT_MISC.UOP_DROPPING -[event20:base-stat] +[event20:base-stat-group] fd=20 type=4 config=4109 optional=1 # PERF_TYPE_RAW / cpu/INT_MISC.RECOVERY_CYCLES,cmask=1,edge/ -[event21:base-stat] +[event21:base-stat-group] fd=21 type=4 config=17039629 optional=1 -# PERF_TYPE_RAW / CPU_CLK_UNHALTED.THREAD -[event22:base-stat] +# PERF_TYPE_RAW / cpu-cycles (core PMU sysfs event; Intel 0x3c, AMD 0x76) +[event22:base-stat-group] fd=22 type=4 -config=60 +config=60|118 optional=1 # PERF_TYPE_RAW / INT_MISC.RECOVERY_CYCLES_ANY -[event23:base-stat] +[event23:base-stat-group] fd=23 type=4 config=2097421 optional=1 # PERF_TYPE_RAW / CPU_CLK_UNHALTED.REF_XCLK -[event24:base-stat] +[event24:base-stat-group] fd=24 type=4 config=316 optional=1 # PERF_TYPE_RAW / IDQ_UOPS_NOT_DELIVERED.CORE -[event25:base-stat] +[event25:base-stat-group] fd=25 type=4 config=412 optional=1 # PERF_TYPE_RAW / CPU_CLK_UNHALTED.ONE_THREAD_ACTIVE -[event26:base-stat] +[event26:base-stat-group] fd=26 type=4 config=572 optional=1 # PERF_TYPE_RAW / UOPS_RETIRED.RETIRE_SLOTS -[event27:base-stat] +[event27:base-stat-group] fd=27 type=4 config=706 optional=1 # PERF_TYPE_RAW / UOPS_ISSUED.ANY -[event28:base-stat] +[event28:base-stat-group] fd=28 type=4 config=270 @@ -234,7 +234,7 @@ optional=1 # PERF_COUNT_HW_CACHE_L1D << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) -[event29:base-stat] +[event29:base-stat-group] fd=29 type=3 config=0 @@ -244,7 +244,7 @@ optional=1 # PERF_COUNT_HW_CACHE_L1D << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) -[event30:base-stat] +[event30:base-stat-group] fd=30 type=3 config=65536 @@ -254,7 +254,7 @@ optional=1 # PERF_COUNT_HW_CACHE_LL << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) -[event31:base-stat] +[event31:base-stat-group] fd=31 type=3 config=2 @@ -264,15 +264,43 @@ optional=1 # PERF_COUNT_HW_CACHE_LL << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) -[event32:base-stat] +[event32:base-stat-group] fd=32 type=3 config=65538 optional=1 # PERF_TYPE_RAW / INT_MISC.UOP_DROPPING -[event33:base-stat] +[event33:base-stat-group] fd=33 type=4 config=4269 +optional=1 + +# PERF_TYPE_RAW / instructions (core PMU sysfs event) +[event34:base-stat-group] +fd=34 +type=4 +config=192 +optional=1 + +# PERF_TYPE_RAW / branch-misses (core PMU sysfs event; Intel 0xc5, AMD 0xc3) +[event35:base-stat-group] +fd=35 +type=4 +config=197|195 +optional=1 + +# PERF_TYPE_RAW / stalled-cycles-frontend (core PMU sysfs event; Intel 0x180010e, AMD 0xd0/0x287/0xa9) +[event36:base-stat-group] +fd=36 +type=4 +config=25166094|208|647|169 +optional=1 + +# PERF_TYPE_RAW / stalled-cycles-backend (core PMU sysfs event; Intel 0x18001b1/0x1803fb1, AMD 0xd1/0x187) +[event37:base-stat-group] +fd=37 +type=4 +config=25166257|25182129|209|391 optional=1 \ No newline at end of file diff --git a/tools/perf/tests/shell/attr/test-stat-detailed-2 b/tools/perf/tests/shell/attr/test-stat-detailed-2 index 66ea25b7d38f..d6fd10fbff3e 100644 --- a/tools/perf/tests/shell/attr/test-stat-detailed-2 +++ b/tools/perf/tests/shell/attr/test-stat-detailed-2 @@ -5,73 +5,73 @@ ret = 1 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_TASK_CLOCK -[event1:base-stat] +[event1:base-stat-group] fd=1 type=1 config=1 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_CONTEXT_SWITCHES -[event2:base-stat] +[event2:base-stat-group] fd=2 type=1 config=3 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_CPU_MIGRATIONS -[event3:base-stat] +[event3:base-stat-group] fd=3 type=1 config=4 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_PAGE_FAULTS -[event4:base-stat] +[event4:base-stat-group] fd=4 type=1 config=2 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_CPU_CYCLES -[event5:base-stat] +[event5:base-stat-group] fd=5 type=0 config=0 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_STALLED_CYCLES_FRONTEND -[event6:base-stat] +[event6:base-stat-group] fd=6 type=0 config=7 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_STALLED_CYCLES_BACKEND -[event7:base-stat] +[event7:base-stat-group] fd=7 type=0 config=8 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_INSTRUCTIONS -[event8:base-stat] +[event8:base-stat-group] fd=8 type=0 config=1 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_BRANCH_INSTRUCTIONS -[event9:base-stat] +[event9:base-stat-group] fd=9 type=0 config=4 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_BRANCH_MISSES -[event10:base-stat] +[event10:base-stat-group] fd=10 type=0 config=5 optional=1 # PERF_TYPE_RAW / slots (0x400) -[event11:base-stat] +[event11:base-stat-group] fd=11 group_fd=-1 type=4 @@ -80,7 +80,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-retiring (0x8000) -[event12:base-stat] +[event12:base-stat-group] fd=12 group_fd=11 type=4 @@ -91,7 +91,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-bad-spec (0x8100) -[event13:base-stat] +[event13:base-stat-group] fd=13 group_fd=11 type=4 @@ -102,7 +102,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-fe-bound (0x8200) -[event14:base-stat] +[event14:base-stat-group] fd=14 group_fd=11 type=4 @@ -113,7 +113,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-be-bound (0x8300) -[event15:base-stat] +[event15:base-stat-group] fd=15 group_fd=11 type=4 @@ -124,7 +124,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-heavy-ops (0x8400) -[event16:base-stat] +[event16:base-stat-group] fd=16 group_fd=11 type=4 @@ -135,7 +135,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-br-mispredict (0x8500) -[event17:base-stat] +[event17:base-stat-group] fd=17 group_fd=11 type=4 @@ -146,7 +146,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-fetch-lat (0x8600) -[event18:base-stat] +[event18:base-stat-group] fd=18 group_fd=11 type=4 @@ -157,7 +157,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-mem-bound (0x8700) -[event19:base-stat] +[event19:base-stat-group] fd=19 group_fd=11 type=4 @@ -168,63 +168,63 @@ read_format=15 optional=1 # PERF_TYPE_RAW / INT_MISC.UOP_DROPPING -[event20:base-stat] +[event20:base-stat-group] fd=20 type=4 config=4109 optional=1 # PERF_TYPE_RAW / cpu/INT_MISC.RECOVERY_CYCLES,cmask=1,edge/ -[event21:base-stat] +[event21:base-stat-group] fd=21 type=4 config=17039629 optional=1 -# PERF_TYPE_RAW / CPU_CLK_UNHALTED.THREAD -[event22:base-stat] +# PERF_TYPE_RAW / cpu-cycles (core PMU sysfs event; Intel 0x3c, AMD 0x76) +[event22:base-stat-group] fd=22 type=4 -config=60 +config=60|118 optional=1 # PERF_TYPE_RAW / INT_MISC.RECOVERY_CYCLES_ANY -[event23:base-stat] +[event23:base-stat-group] fd=23 type=4 config=2097421 optional=1 # PERF_TYPE_RAW / CPU_CLK_UNHALTED.REF_XCLK -[event24:base-stat] +[event24:base-stat-group] fd=24 type=4 config=316 optional=1 # PERF_TYPE_RAW / IDQ_UOPS_NOT_DELIVERED.CORE -[event25:base-stat] +[event25:base-stat-group] fd=25 type=4 config=412 optional=1 # PERF_TYPE_RAW / CPU_CLK_UNHALTED.ONE_THREAD_ACTIVE -[event26:base-stat] +[event26:base-stat-group] fd=26 type=4 config=572 optional=1 # PERF_TYPE_RAW / UOPS_RETIRED.RETIRE_SLOTS -[event27:base-stat] +[event27:base-stat-group] fd=27 type=4 config=706 optional=1 # PERF_TYPE_RAW / UOPS_ISSUED.ANY -[event28:base-stat] +[event28:base-stat-group] fd=28 type=4 config=270 @@ -234,7 +234,7 @@ optional=1 # PERF_COUNT_HW_CACHE_L1D << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) -[event29:base-stat] +[event29:base-stat-group] fd=29 type=3 config=0 @@ -244,7 +244,7 @@ optional=1 # PERF_COUNT_HW_CACHE_L1D << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) -[event30:base-stat] +[event30:base-stat-group] fd=30 type=3 config=65536 @@ -254,7 +254,7 @@ optional=1 # PERF_COUNT_HW_CACHE_LL << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) -[event31:base-stat] +[event31:base-stat-group] fd=31 type=3 config=2 @@ -264,7 +264,7 @@ optional=1 # PERF_COUNT_HW_CACHE_LL << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) -[event32:base-stat] +[event32:base-stat-group] fd=32 type=3 config=65538 @@ -274,7 +274,7 @@ optional=1 # PERF_COUNT_HW_CACHE_L1I << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) -[event33:base-stat] +[event33:base-stat-group] fd=33 type=3 config=1 @@ -284,7 +284,7 @@ optional=1 # PERF_COUNT_HW_CACHE_L1I << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) -[event34:base-stat] +[event34:base-stat-group] fd=34 type=3 config=65537 @@ -294,7 +294,7 @@ optional=1 # PERF_COUNT_HW_CACHE_DTLB << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) -[event35:base-stat] +[event35:base-stat-group] fd=35 type=3 config=3 @@ -304,7 +304,7 @@ optional=1 # PERF_COUNT_HW_CACHE_DTLB << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) -[event36:base-stat] +[event36:base-stat-group] fd=36 type=3 config=65539 @@ -314,7 +314,7 @@ optional=1 # PERF_COUNT_HW_CACHE_ITLB << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) -[event37:base-stat] +[event37:base-stat-group] fd=37 type=3 config=4 @@ -324,15 +324,43 @@ optional=1 # PERF_COUNT_HW_CACHE_ITLB << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) -[event38:base-stat] +[event38:base-stat-group] fd=38 type=3 config=65540 optional=1 # PERF_TYPE_RAW / INT_MISC.UOP_DROPPING -[event39:base-stat] +[event39:base-stat-group] fd=39 type=4 config=4269 +optional=1 + +# PERF_TYPE_RAW / instructions (core PMU sysfs event) +[event40:base-stat-group] +fd=40 +type=4 +config=192 +optional=1 + +# PERF_TYPE_RAW / branch-misses (core PMU sysfs event; Intel 0xc5, AMD 0xc3) +[event41:base-stat-group] +fd=41 +type=4 +config=197|195 +optional=1 + +# PERF_TYPE_RAW / stalled-cycles-frontend (core PMU sysfs event; Intel 0x180010e, AMD 0xd0/0x287/0xa9) +[event42:base-stat-group] +fd=42 +type=4 +config=25166094|208|647|169 +optional=1 + +# PERF_TYPE_RAW / stalled-cycles-backend (core PMU sysfs event; Intel 0x18001b1/0x1803fb1, AMD 0xd1/0x187) +[event43:base-stat-group] +fd=43 +type=4 +config=25166257|25182129|209|391 optional=1 \ No newline at end of file diff --git a/tools/perf/tests/shell/attr/test-stat-detailed-3 b/tools/perf/tests/shell/attr/test-stat-detailed-3 index 4a27bbfb9f87..9a41a1a1d6dd 100644 --- a/tools/perf/tests/shell/attr/test-stat-detailed-3 +++ b/tools/perf/tests/shell/attr/test-stat-detailed-3 @@ -5,73 +5,73 @@ ret = 1 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_TASK_CLOCK -[event1:base-stat] +[event1:base-stat-group] fd=1 type=1 config=1 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_CONTEXT_SWITCHES -[event2:base-stat] +[event2:base-stat-group] fd=2 type=1 config=3 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_CPU_MIGRATIONS -[event3:base-stat] +[event3:base-stat-group] fd=3 type=1 config=4 # PERF_TYPE_SOFTWARE / PERF_COUNT_SW_PAGE_FAULTS -[event4:base-stat] +[event4:base-stat-group] fd=4 type=1 config=2 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_CPU_CYCLES -[event5:base-stat] +[event5:base-stat-group] fd=5 type=0 config=0 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_STALLED_CYCLES_FRONTEND -[event6:base-stat] +[event6:base-stat-group] fd=6 type=0 config=7 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_STALLED_CYCLES_BACKEND -[event7:base-stat] +[event7:base-stat-group] fd=7 type=0 config=8 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_INSTRUCTIONS -[event8:base-stat] +[event8:base-stat-group] fd=8 type=0 config=1 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_BRANCH_INSTRUCTIONS -[event9:base-stat] +[event9:base-stat-group] fd=9 type=0 config=4 optional=1 # PERF_TYPE_HARDWARE / PERF_COUNT_HW_BRANCH_MISSES -[event10:base-stat] +[event10:base-stat-group] fd=10 type=0 config=5 optional=1 # PERF_TYPE_RAW / slots (0x400) -[event11:base-stat] +[event11:base-stat-group] fd=11 group_fd=-1 type=4 @@ -80,7 +80,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-retiring (0x8000) -[event12:base-stat] +[event12:base-stat-group] fd=12 group_fd=11 type=4 @@ -91,7 +91,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-bad-spec (0x8100) -[event13:base-stat] +[event13:base-stat-group] fd=13 group_fd=11 type=4 @@ -102,7 +102,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-fe-bound (0x8200) -[event14:base-stat] +[event14:base-stat-group] fd=14 group_fd=11 type=4 @@ -113,7 +113,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-be-bound (0x8300) -[event15:base-stat] +[event15:base-stat-group] fd=15 group_fd=11 type=4 @@ -124,7 +124,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-heavy-ops (0x8400) -[event16:base-stat] +[event16:base-stat-group] fd=16 group_fd=11 type=4 @@ -135,7 +135,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-br-mispredict (0x8500) -[event17:base-stat] +[event17:base-stat-group] fd=17 group_fd=11 type=4 @@ -146,7 +146,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-fetch-lat (0x8600) -[event18:base-stat] +[event18:base-stat-group] fd=18 group_fd=11 type=4 @@ -157,7 +157,7 @@ read_format=15 optional=1 # PERF_TYPE_RAW / topdown-mem-bound (0x8700) -[event19:base-stat] +[event19:base-stat-group] fd=19 group_fd=11 type=4 @@ -168,63 +168,63 @@ read_format=15 optional=1 # PERF_TYPE_RAW / INT_MISC.UOP_DROPPING -[event20:base-stat] +[event20:base-stat-group] fd=20 type=4 config=4109 optional=1 # PERF_TYPE_RAW / cpu/INT_MISC.RECOVERY_CYCLES,cmask=1,edge/ -[event21:base-stat] +[event21:base-stat-group] fd=21 type=4 config=17039629 optional=1 -# PERF_TYPE_RAW / CPU_CLK_UNHALTED.THREAD -[event22:base-stat] +# PERF_TYPE_RAW / cpu-cycles (core PMU sysfs event; Intel 0x3c, AMD 0x76) +[event22:base-stat-group] fd=22 type=4 -config=60 +config=60|118 optional=1 # PERF_TYPE_RAW / INT_MISC.RECOVERY_CYCLES_ANY -[event23:base-stat] +[event23:base-stat-group] fd=23 type=4 config=2097421 optional=1 # PERF_TYPE_RAW / CPU_CLK_UNHALTED.REF_XCLK -[event24:base-stat] +[event24:base-stat-group] fd=24 type=4 config=316 optional=1 # PERF_TYPE_RAW / IDQ_UOPS_NOT_DELIVERED.CORE -[event25:base-stat] +[event25:base-stat-group] fd=25 type=4 config=412 optional=1 # PERF_TYPE_RAW / CPU_CLK_UNHALTED.ONE_THREAD_ACTIVE -[event26:base-stat] +[event26:base-stat-group] fd=26 type=4 config=572 optional=1 # PERF_TYPE_RAW / UOPS_RETIRED.RETIRE_SLOTS -[event27:base-stat] +[event27:base-stat-group] fd=27 type=4 config=706 optional=1 # PERF_TYPE_RAW / UOPS_ISSUED.ANY -[event28:base-stat] +[event28:base-stat-group] fd=28 type=4 config=270 @@ -234,7 +234,7 @@ optional=1 # PERF_COUNT_HW_CACHE_L1D << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) -[event29:base-stat] +[event29:base-stat-group] fd=29 type=3 config=0 @@ -244,7 +244,7 @@ optional=1 # PERF_COUNT_HW_CACHE_L1D << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) -[event30:base-stat] +[event30:base-stat-group] fd=30 type=3 config=65536 @@ -254,7 +254,7 @@ optional=1 # PERF_COUNT_HW_CACHE_LL << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) -[event31:base-stat] +[event31:base-stat-group] fd=31 type=3 config=2 @@ -264,7 +264,7 @@ optional=1 # PERF_COUNT_HW_CACHE_LL << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) -[event32:base-stat] +[event32:base-stat-group] fd=32 type=3 config=65538 @@ -274,7 +274,7 @@ optional=1 # PERF_COUNT_HW_CACHE_L1I << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) -[event33:base-stat] +[event33:base-stat-group] fd=33 type=3 config=1 @@ -284,7 +284,7 @@ optional=1 # PERF_COUNT_HW_CACHE_L1I << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) -[event34:base-stat] +[event34:base-stat-group] fd=34 type=3 config=65537 @@ -294,7 +294,7 @@ optional=1 # PERF_COUNT_HW_CACHE_DTLB << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) -[event35:base-stat] +[event35:base-stat-group] fd=35 type=3 config=3 @@ -304,7 +304,7 @@ optional=1 # PERF_COUNT_HW_CACHE_DTLB << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) -[event36:base-stat] +[event36:base-stat-group] fd=36 type=3 config=65539 @@ -314,7 +314,7 @@ optional=1 # PERF_COUNT_HW_CACHE_ITLB << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) -[event37:base-stat] +[event37:base-stat-group] fd=37 type=3 config=4 @@ -324,7 +324,7 @@ optional=1 # PERF_COUNT_HW_CACHE_ITLB << 0 | # (PERF_COUNT_HW_CACHE_OP_READ << 8) | # (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) -[event38:base-stat] +[event38:base-stat-group] fd=38 type=3 config=65540 @@ -334,7 +334,7 @@ optional=1 # PERF_COUNT_HW_CACHE_L1D << 0 | # (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) | # (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) -[event39:base-stat] +[event39:base-stat-group] fd=39 type=3 config=512 @@ -344,15 +344,43 @@ optional=1 # PERF_COUNT_HW_CACHE_L1D << 0 | # (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) | # (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) -[event40:base-stat] +[event40:base-stat-group] fd=40 type=3 config=66048 optional=1 # PERF_TYPE_RAW / INT_MISC.UOP_DROPPING -[event41:base-stat] +[event41:base-stat-group] fd=41 type=4 config=4269 +optional=1 + +# PERF_TYPE_RAW / instructions (core PMU sysfs event) +[event42:base-stat-group] +fd=42 +type=4 +config=192 +optional=1 + +# PERF_TYPE_RAW / branch-misses (core PMU sysfs event; Intel 0xc5, AMD 0xc3) +[event43:base-stat-group] +fd=43 +type=4 +config=197|195 +optional=1 + +# PERF_TYPE_RAW / stalled-cycles-frontend (core PMU sysfs event; Intel 0x180010e, AMD 0xd0/0x287/0xa9) +[event44:base-stat-group] +fd=44 +type=4 +config=25166094|208|647|169 +optional=1 + +# PERF_TYPE_RAW / stalled-cycles-backend (core PMU sysfs event; Intel 0x18001b1/0x1803fb1, AMD 0xd1/0x187) +[event45:base-stat-group] +fd=45 +type=4 +config=25166257|25182129|209|391 optional=1 \ No newline at end of file diff --git a/tools/perf/tests/shell/attr/test-stat-group1 b/tools/perf/tests/shell/attr/test-stat-group1 index 1746751123dc..fa2ca74e4cf2 100644 --- a/tools/perf/tests/shell/attr/test-stat-group1 +++ b/tools/perf/tests/shell/attr/test-stat-group1 @@ -1,6 +1,6 @@ [config] command = stat -args = -e '{cycles,instructions}' kill >/dev/null 2>&1 +args = -e '{cycles,default_core/legacy-hardware-config=1/}' kill >/dev/null 2>&1 ret = 1 [event-1:base-stat] diff --git a/tools/perf/tests/shell/c2c.sh b/tools/perf/tests/shell/c2c.sh index 2471d44595c3..f5f223cbf9cc 100755 --- a/tools/perf/tests/shell/c2c.sh +++ b/tools/perf/tests/shell/c2c.sh @@ -39,6 +39,7 @@ test_c2c_record_report() { # Run a workload that does some memory operations. if ! perf c2c record -o "${perfdata}" -- perf test -w datasym 1 > /dev/null 2>&1 ; then echo "c2c record and report test [Skipped: perf c2c record failed during workload]" + err=2 return fi diff --git a/tools/perf/tests/shell/coresight/callchain.sh b/tools/perf/tests/shell/coresight/callchain.sh index 13cca7dc1118..43ad90bc3034 100755 --- a/tools/perf/tests/shell/coresight/callchain.sh +++ b/tools/perf/tests/shell/coresight/callchain.sh @@ -30,6 +30,11 @@ skip_if_system_is_not_ready() return 2 } + [ -e /proc/kcore ] || { + echo "[Skip] /proc/kcore is not available" >&2 + return 2 + } + return 0 } @@ -43,7 +48,7 @@ record_trace() mkfifo "$cf" "$af" - perf record -o "$data" -e cs_etm// --per-thread -D -1 --control fifo:"$cf","$af" -- \ + perf record --kcore -o "$data" -e cs_etm// --per-thread -D -1 --control fifo:"$cf","$af" -- \ perf test --record-ctl fifo:"$cf","$af" -w callchain >/dev/null 2>&1 && # It is safe to use 'i3i' with a three-instruction interval, since the diff --git a/tools/perf/tests/shell/data_type_profiling.sh b/tools/perf/tests/shell/data_type_profiling.sh index eca694600a04..a916c410274a 100755 --- a/tools/perf/tests/shell/data_type_profiling.sh +++ b/tools/perf/tests/shell/data_type_profiling.sh @@ -19,6 +19,15 @@ perfout=$(mktemp /tmp/__perf_test.perf.out.XXXXX) perf mem record -o /dev/null -- true 2>&1 | \ grep -q "failed: no PMU supports the memory events" && exit 2 +# Skip if per-thread mem record is not supported on this PMU (e.g. AMD IBS +# needs system-wide '-a'): it is what the test records with below, and a +# failing record must not be reported as a test failure. +if ! perf mem record -o /dev/null -- true 2>/dev/null +then + echo "Skip: cannot record memory events on this PMU" + exit 2 +fi + cleanup() { rm -rf "${perfdata}" "${perfout}" rm -rf "${perfdata}".old @@ -52,25 +61,42 @@ test_basic_annotate() { index=1 ;; esac + # Under 'set -e' a bare failing command aborts the script through the EXIT + # trap, so the commands that report a failure have to be the condition of + # an 'if' for that reporting to ever happen. if [ "x${mode}" == "xBasic" ] then - perf mem record -o "${perfdata}" ${testprogs[$index]} 2> /dev/null + if ! perf mem record -o "${perfdata}" ${testprogs[$index]} 2> /dev/null + then + echo "${mode} annotate [Failed: perf record]" + err=1 + return + fi else - perf mem record -o - ${testprogs[$index]} 2> /dev/null > "${perfdata}" - fi - if [ "x$?" != "x0" ] - then - echo "${mode} annotate [Failed: perf record]" - err=1 - return + if ! perf mem record -o - ${testprogs[$index]} 2> /dev/null > "${perfdata}" + then + echo "${mode} annotate [Failed: perf record]" + err=1 + return + fi fi # Generate the annotated output file if [ "x${mode}" == "xBasic" ] then - perf annotate --code-with-type -i "${perfdata}" --stdio --percent-limit 1 2> /dev/null > "${perfout}" + if ! perf annotate --code-with-type -i "${perfdata}" --stdio --percent-limit 1 2> /dev/null > "${perfout}" + then + echo "${mode} annotate [Failed: perf annotate]" + err=1 + return + fi else - perf annotate --code-with-type -i - --stdio 2> /dev/null --percent-limit 1 < "${perfdata}" > "${perfout}" + if ! perf annotate --code-with-type -i - --stdio 2> /dev/null --percent-limit 1 < "${perfdata}" > "${perfout}" + then + echo "${mode} annotate [Failed: perf annotate]" + err=1 + return + fi fi # check if it has the target data type diff --git a/tools/perf/tests/shell/lib/attr.py b/tools/perf/tests/shell/lib/attr.py index bfccc727d9b2..54635082d630 100644 --- a/tools/perf/tests/shell/lib/attr.py +++ b/tools/perf/tests/shell/lib/attr.py @@ -307,7 +307,7 @@ class Test(object): else: raise Unsup(self) - def compare(self, expect, result): + def compare(self, expect, result, strict_groups=True): match = {} log.debug(" compare"); @@ -341,8 +341,9 @@ class Test(object): match[exp_name] = exp_list - # For each defined group in the expected events - # check we match the same group in the result. + # Check that each expected group is matched in the result; an event + # opened in a group may match an expectation that doesn't declare + # one, as those only verify the event attributes. for exp_name, exp_event in expect.items(): group = exp_event.group @@ -351,6 +352,8 @@ class Test(object): for res_name in match[exp_name]: res_group = result[res_name].group + if res_group == '' and not strict_groups: + continue if res_group not in match[group]: raise Fail(self, 'group failure') @@ -389,7 +392,7 @@ class Test(object): # do the expectation - results matching - both ways self.compare(self.expect, self.result) - self.compare(self.result, self.expect) + self.compare(self.result, self.expect, strict_groups=False) finally: # cleanup diff --git a/tools/perf/tests/shell/schedstat_snapshots.sh b/tools/perf/tests/shell/schedstat_snapshots.sh new file mode 100755 index 000000000000..a4bdf2673d43 --- /dev/null +++ b/tools/perf/tests/shell/schedstat_snapshots.sh @@ -0,0 +1,155 @@ +#!/bin/sh +# Validate CPU and domain pairing in perf sched stats snapshots +# SPDX-License-Identifier: GPL-2.0 + +set -e + +# shellcheck source=lib/setup_python.sh +. "$(dirname "$0")/lib/setup_python.sh" + +if ! perf version --build-options | grep -q 'libtraceevent:.*on'; then + echo "[Skip] perf sched requires libtraceevent" + exit 2 +fi + +$PYTHON - <<'PY' +import os +import re +import struct +import subprocess +import sys +import tempfile + +# Native-endian perf.data with only NRCPUS and CPU_DOMAIN_INFO features. +endian = '<' if sys.byteorder == 'little' else '>' + + +def pack(fmt, *values): + return struct.pack(endian + fmt, *values) + + +def string(value): + data = value.encode() + b'\0' + return pack('I', len(data)) + data + + +def cpu(cpu_id, timestamp, value, version): + return pack('IHHQIHH6I3Q', 85, 0, 72, timestamp, cpu_id, version, 0, + *([value] * 9)) + + +def domain(cpu_id, domain_id, timestamp, value, version): + # All supported versions use the largest union member's record size. + return pack('IHHQIHH45I4x', 86, 0, 208, timestamp, cpu_id, version, + domain_id, *([value] * 45)) + + +def snapshot(timestamp, value, version=17, cpus=(0, 1, 2), domains=(0, 1)): + records = [] + for cpu_id in cpus: + records.append(cpu(cpu_id, timestamp, value + cpu_id * 100, version)) + for domain_id in domains: + records.append(domain(cpu_id, domain_id, timestamp, + value + cpu_id * 100, version)) + return records + + +def write_file(path, records, version=17): + metadata = pack('II', version, 2) + for cpu_id in range(3): + metadata += pack('II', cpu_id, 2) + for domain_id in range(2): + metadata += pack('I', domain_id) + if version >= 17: + metadata += string('SMT' if domain_id == 0 else 'MC') + metadata += string('7') + string('0-2') + features = [pack('II', 3, 3), metadata] + data = b''.join(records) + offset = 104 + len(data) + 16 * len(features) + sections = b'' + for feature in features: + sections += pack('QQ', offset, len(feature)) + offset += len(feature) + header = pack('13Q', 0x32454c4946524550, 104, 144, 104, 0, + 104, len(data), 0, 0, (1 << 7) | (1 << 32), 0, 0, 0) + with open(path, 'wb') as output: + output.write(header + data + sections + b''.join(features)) + + +def run(args, valid, domains=True): + result = subprocess.run(['perf', 'sched', 'stats'] + args, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, timeout=10) + if valid: + assert result.returncode == 0, result.stderr + assert re.search(r'^yld_count\s+:\s+10\b', result.stdout, re.M), result.stdout + if domains: + assert re.search(r'^busy_lb_count\s+:\s+10\b', result.stdout, re.M), result.stdout + else: + assert 'busy_lb_count' not in result.stdout, result.stdout + else: + assert result.returncode > 0, (args, result.returncode, result.stdout) + assert 'Incompatible or incomplete schedstat snapshots' in result.stderr + assert not result.stdout, result.stdout + assert 'Sanitizer' not in result.stderr, result.stderr + + +with tempfile.TemporaryDirectory(prefix='perf-schedstat-') as directory: + good = os.path.join(directory, 'good.data') + test = os.path.join(directory, 'test.data') + before = snapshot(100, 1000) + after = snapshot(200, 1010) + write_file(good, before + after) + + for version in (15, 16, 17): + for timestamp in (100, 200): + write_file(test, snapshot(100, 1000, version) + + snapshot(timestamp, 1010, version), version) + run(['report', '-C', '0,1,2', '-i', test], True) + run(['diff', test, test], True) + print('Matching snapshots, including equal timestamps: [Success]') + + write_file(test, snapshot(100, 1000, domains=()) + + snapshot(200, 1010, domains=())) + run(['report', '-C', '0,1,2', '-i', test], True, domains=False) + run(['diff', test, test], True, domains=False) + print('CPUs without domains: [Success]') + + write_file(test, before + snapshot(200, 1010, cpus=(0, 1))) + run(['report', '-C', '0,1', '-i', test], True) + run(['report', '-C', '1', '-i', good], True) + write_file(test, snapshot(100, 1000, cpus=(0, 1)) + + snapshot(200, 1010, cpus=(0, 1))) + run(['diff', good, test], True) + print('CPU filtering and different CPU sets across files: [Success]') + + write_file(test, snapshot(100, 0xfffffffa, cpus=(0,)) + + snapshot(200, 4, cpus=(0,))) + run(['report', '-C', '0', '-i', test], True) + print('Wrapping 32-bit counters: [Success]') + + cases = { + 'missing first CPU': before + snapshot(200, 1010, cpus=(1, 2)), + 'missing middle CPU': before + snapshot(200, 1010, cpus=(0, 2)), + 'missing last CPU': before + snapshot(200, 1010, cpus=(0, 1)), + 'added CPU': snapshot(100, 1000, cpus=(0, 1)) + after, + 'reordered CPUs': before + snapshot(200, 1010, cpus=(0, 2, 1)), + 'equal timestamp, missing first CPU': before + snapshot(100, 1010, cpus=(1, 2)), + 'missing first domain': before + snapshot(200, 1010, domains=(1,)), + 'missing last domain': before + after[:-1], + 'added domain': snapshot(100, 1000, domains=(0,)) + after, + 'reordered domains': before + snapshot(200, 1010, domains=(1, 0)), + 'domain without CPU': before[1:] + after, + 'wrong domain CPU': before + [after[0], domain(1, 0, 200, 1010, 17)] + after[2:], + 'changed version': before + snapshot(200, 1010, version=16), + 'backwards timestamp': before + snapshot(50, 1010), + 'third snapshot': before + after + snapshot(300, 1020), + 'missing second snapshot': before, + } + for name, records in cases.items(): + write_file(test, records) + run(['report', '-C', '0,1,2', '-i', test], False) + run(['diff', test, good], False) + run(['diff', good, test], False) + print(name + ': [Success]') +PY diff --git a/tools/perf/tests/shell/stat.sh b/tools/perf/tests/shell/stat.sh index 298ce454b45a..1f5d4cc05807 100755 --- a/tools/perf/tests/shell/stat.sh +++ b/tools/perf/tests/shell/stat.sh @@ -583,6 +583,11 @@ test_hide_zero_events_stat() { # Check that --metric-only works with --hide-zero-events if ! perf stat --hide-zero-events --metric-only -e instructions,cycles true > "${stat_output}" 2>&1 then + if grep -sq 'No supported events found' "${stat_output}" + then + echo "Hide zero events stat test [Skipped - events not supported]" + return + fi echo "Hide zero events stat test [Failed - metric-only command failed]" err=1 return diff --git a/tools/perf/tests/shell/test_event_open_fallback.sh b/tools/perf/tests/shell/test_event_open_fallback.sh index 9420a7557c13..27d440a5355d 100755 --- a/tools/perf/tests/shell/test_event_open_fallback.sh +++ b/tools/perf/tests/shell/test_event_open_fallback.sh @@ -57,8 +57,6 @@ ret=0 test_decrease_precise_ip || ret=$? ; count_result $ret ; ret=0 test_decrease_precise_ip_complicated || ret=$? ; count_result $ret ; ret=0 -cleanup - if [ ${err_cnt} -gt 0 ] ; then exit 1 fi diff --git a/tools/perf/tests/symbols.c b/tools/perf/tests/symbols.c index c09e04f36035..b644d95c6be9 100644 --- a/tools/perf/tests/symbols.c +++ b/tools/perf/tests/symbols.c @@ -2,6 +2,7 @@ #include #include #include +#include #include #include "debug.h" #include "dso.h" @@ -223,4 +224,97 @@ static int test__symbols(struct test_suite *test __maybe_unused, int subtest __m return ret; } -DEFINE_SUITE("Symbols", symbols); +struct kallsyms_sym { + u64 start; + const char *name; +}; + +/* + * kallsyms from an x86 host where nf_tables was loaded in the page right + * after the last symbol of dca, plus a kernel symbol followed closely by a + * module and a module far away from the others. + */ +static const struct kallsyms_sym kallsyms_syms[] = { + { 0xffffffff81000000, "_stext" }, + { 0xffffffff81000ff0, "last_kernel_symbol" }, + { 0xffffffff81001000, "near_module_symbol\t[near]" }, + { 0xffffffffc0c4aa40, "dca_exit\t[dca]" }, + { 0xffffffffc0c4aa50, "dca_sysfs_exit\t[dca]" }, + { 0xffffffffc0c4b000, "__nft_trace_packet\t[nf_tables]" }, + { 0xffffffffc0c4b0b0, "nft_do_chain\t[nf_tables]" }, + { 0xffffffffc0c4b4e0, "nf_tables_core_module_exit\t[nf_tables]" }, + { 0xffffffffc2000000, "far_module_symbol\t[far]" }, +}; + +static int check_symbol(struct dso *dso, u64 addr, const char *name, u64 end) +{ + struct symbol *sym = dso__find_symbol_nocache(dso, addr); + + if (!sym || strcmp(sym->name, name)) { + pr_debug("%#" PRIx64 ": expected %s, got %s\n", addr, name, + sym ? sym->name : "no symbol"); + return TEST_FAIL; + } + if (sym->end != end) { + pr_debug("%s: expected end %#" PRIx64 ", got %#" PRIx64 "\n", + name, end, sym->end); + return TEST_FAIL; + } + return TEST_OK; +} + +static int test__kallsyms_fixup_end(struct test_suite *test __maybe_unused, + int subtest __maybe_unused) +{ + struct dso *dso = dso__new("[kernel.kallsyms]"); + int ret = TEST_FAIL; + + if (!dso) + return TEST_FAIL; + + for (unsigned int i = 0; i < ARRAY_SIZE(kallsyms_syms); i++) { + struct symbol *sym = symbol__new(kallsyms_syms[i].start, 0, 0, 0, + kallsyms_syms[i].name); + + if (!sym) + goto out; + symbols__insert(dso__symbols(dso), sym); + } + + symbols__fixup_end(dso__symbols(dso), true); + + ret = TEST_OK; + /* The next symbol is too close for the end of the page. */ + if (check_symbol(dso, 0xffffffff81000ff8, "last_kernel_symbol", + 0xffffffff81001000)) + ret = TEST_FAIL; + if (check_symbol(dso, 0xffffffffc0c4aa58, "dca_sysfs_exit\t[dca]", + 0xffffffffc0c4b000)) + ret = TEST_FAIL; + if (check_symbol(dso, 0xffffffffc0c4b280, "nft_do_chain\t[nf_tables]", + 0xffffffffc0c4b4e0)) + ret = TEST_FAIL; + + /* Far from the next module, the end of the page is still used. */ + if (check_symbol(dso, 0xffffffffc0c4b4f0, + "nf_tables_core_module_exit\t[nf_tables]", + 0xffffffffc0c4d000)) + ret = TEST_FAIL; + if (check_symbol(dso, 0xffffffff81001008, "near_module_symbol\t[near]", + 0xffffffff81002000)) + ret = TEST_FAIL; +out: + dso__put(dso); + return ret; +} + +static struct test_case tests__symbols[] = { + TEST_CASE("Symbols", symbols), + TEST_CASE("Kallsyms symbol ends", kallsyms_fixup_end), + { .name = NULL, } +}; + +struct test_suite suite__symbols = { + .desc = "Symbols", + .test_cases = tests__symbols, +}; diff --git a/tools/perf/tests/thread-maps-share.c b/tools/perf/tests/thread-maps-share.c index 0431bff31b3a..4a0bbf715acb 100644 --- a/tools/perf/tests/thread-maps-share.c +++ b/tools/perf/tests/thread-maps-share.c @@ -27,7 +27,8 @@ static int test__thread_maps_share(struct test_suite *test __maybe_unused, int s * other group (pid: 4, tids: 4, 5) */ - TEST_ASSERT_VAL("failed to init machines", machines__init(&machines) == 0); + TEST_ASSERT_VAL("failed to init machines", + machines__init(&machines, /*session=*/NULL) == 0); machine = &machines.host; /* create process with 4 threads */ diff --git a/tools/perf/tests/workloads/code_with_type.c b/tools/perf/tests/workloads/code_with_type.c index 65d7be7dac24..d2d437b86e0c 100644 --- a/tools/perf/tests/workloads/code_with_type.c +++ b/tools/perf/tests/workloads/code_with_type.c @@ -6,7 +6,7 @@ #include #include "../tests.h" -extern void test_rs(uint count); +extern void test_rs(unsigned int count); static volatile sig_atomic_t done; diff --git a/tools/perf/ui/browsers/annotate-data.c b/tools/perf/ui/browsers/annotate-data.c index aa8c89fe2e82..1080ed1a40d2 100644 --- a/tools/perf/ui/browsers/annotate-data.c +++ b/tools/perf/ui/browsers/annotate-data.c @@ -370,7 +370,7 @@ static void browser__write_overhead(struct ui_browser *uib, u64 period = hist->period; double percent = total->period ? (100.0 * period / total->period) : 0; bool current = ui_browser__is_current_entry(uib, row); - int nr_samples = 0; + int nr_samples = hist->nr_samples; ui_browser__set_percent_color(uib, percent, current); diff --git a/tools/perf/util/Build b/tools/perf/util/Build index b26a0b1ddfa3..776b2230309c 100644 --- a/tools/perf/util/Build +++ b/tools/perf/util/Build @@ -340,7 +340,7 @@ bison_flags := -DYYENABLE_NLS=0 -Wno-unused-but-set-variable # Old clangs don't grok -Wno-unused-but-set-variable, remove it ifeq ($(CC_NO_CLANG), 0) - CLANG_VERSION := $(shell $(CLANG) --version | head -1 | sed 's/.*clang version \([[:digit:]]\+.[[:digit:]]\+.[[:digit:]]\+\).*/\1/g') + CLANG_VERSION := $(shell $(CC) --version | head -1 | sed 's/.*clang version \([[:digit:]]\+.[[:digit:]]\+.[[:digit:]]\+\).*/\1/g') ifeq ($(call version-lt3,$(CLANG_VERSION),13.0.0),1) bison_flags := $(subst -Wno-unused-but-set-variable,,$(bison_flags)) flex_flags := $(subst -Wno-unused-but-set-variable,,$(flex_flags)) diff --git a/tools/perf/util/addr2line.c b/tools/perf/util/addr2line.c index 4b0d349ed334..960dd48701bb 100644 --- a/tools/perf/util/addr2line.c +++ b/tools/perf/util/addr2line.c @@ -15,6 +15,7 @@ #include #include #include +#include #define MAX_INLINE_NEST 1024 @@ -284,7 +285,7 @@ int cmd__addr2line(const char *dso_name, u64 addr, struct inline_node *node, struct symbol *sym __maybe_unused) { - struct child_process *a2l = dso__a2l(dso); + struct child_process *a2l; char *record_function = NULL; char *record_filename = NULL; unsigned int record_line_nr = 0; @@ -296,24 +297,42 @@ int cmd__addr2line(const char *dso_name, u64 addr, ssize_t written; struct io io = { .eof = false }; enum cmd_a2l_style cmd_a2l_style; + const char *current_dso_name; + bool a2l_synced = false; + + mutex_lock(dso__lock(dso)); + current_dso_name = dso__symsrc_filename(dso) ?: dso_name; + a2l = dso__a2l(dso); if (!a2l) { - if (!filename__has_section(dso_name, ".debug_line")) - goto out; + if (!filename__has_section(current_dso_name, ".debug_line")) + goto out_unlock; dso__set_a2l(dso, - addr2line_subprocess_init(symbol_conf.addr2line_path, dso_name)); + addr2line_subprocess_init(symbol_conf.addr2line_path, + current_dso_name)); a2l = dso__a2l(dso); } if (a2l == NULL) { if (!symbol_conf.addr2line_disable_warn) pr_warning("%s %s: addr2line_subprocess_init failed\n", __func__, dso_name); - goto out; + ret = -1; + goto out_unlock; } cmd_a2l_style = cmd_addr2line_configure(a2l, dso_name); - if (cmd_a2l_style == BROKEN) - goto out; + if (cmd_a2l_style == BROKEN) { + ret = -1; + goto out_unlock; + } + + /* + * Take ownership of the a2l subprocess so we can safely perform + * blocking IPC without holding the dso lock. If another thread + * resolves a symbol concurrently, it will spawn a new a2l process. + */ + dso__set_a2l(dso, NULL); + mutex_unlock(dso__lock(dso)); /* * Send our request and then *deliberately* send something that can't be @@ -329,6 +348,7 @@ int cmd__addr2line(const char *dso_name, u64 addr, if (written != len) { if (!symbol_conf.addr2line_disable_warn) pr_warning("%s %s: could not send request\n", __func__, dso_name); + ret = -1; goto out; } io__init(&io, a2l->out, buf, sizeof(buf)); @@ -338,6 +358,7 @@ int cmd__addr2line(const char *dso_name, u64 addr, case -1: if (!symbol_conf.addr2line_disable_warn) pr_warning("%s %s: could not read first record\n", __func__, dso_name); + ret = -1; goto out; case 0: /* @@ -358,6 +379,7 @@ int cmd__addr2line(const char *dso_name, u64 addr, break; case 0: /* The sentinel as expected. */ + a2l_synced = true; break; default: if (!symbol_conf.addr2line_disable_warn) @@ -373,17 +395,23 @@ int cmd__addr2line(const char *dso_name, u64 addr, if (file) { *file = strdup(record_filename); - ret = 1; + if (!*file) { + ret = -ENOMEM; + goto out; + } } if (line_nr) *line_nr = record_line_nr; + ret = 1; if (unwind_inlines) { if (node && inline_list__append_record(dso, node, sym, record_function, record_filename, record_line_nr)) { - ret = 0; + if (file && *file) + zfree(file); + ret = -ENOMEM; goto out; } } @@ -406,20 +434,34 @@ int cmd__addr2line(const char *dso_name, u64 addr, record_function, record_filename, record_line_nr)) { - ret = 0; + if (file && *file) + zfree(file); + inline_node__clear_frames(node); + ret = -ENOMEM; goto out; } ret = 1; /* found at least one inline frame */ } } + if (record_status == 0) + a2l_synced = true; out: + mutex_lock(dso__lock(dso)); free(record_function); free(record_filename); - if (io.eof) { - dso__set_a2l(dso, NULL); + + current_dso_name = dso__symsrc_filename(dso) ?: dso__long_name(dso); + if (a2l_synced && !io.eof && dso__a2l(dso) == NULL && current_dso_name && + !strcmp(current_dso_name, dso_name)) + dso__set_a2l(dso, a2l); + else addr2line_subprocess_cleanup(a2l); - } + mutex_unlock(dso__lock(dso)); + return ret; + +out_unlock: + mutex_unlock(dso__lock(dso)); return ret; } diff --git a/tools/perf/util/annotate-data.c b/tools/perf/util/annotate-data.c index 4e4c58764082..d6f3d1b55f6d 100644 --- a/tools/perf/util/annotate-data.c +++ b/tools/perf/util/annotate-data.c @@ -645,6 +645,8 @@ struct global_var_entry { u64 start; u64 end; u64 die_offset; + int die_tag; + bool from_alt; /* die_offset is relative to the alt (dwz) file */ }; static int global_var_cmp(const void *_key, const struct rb_node *node) @@ -682,7 +684,7 @@ static struct global_var_entry *global_var__find(struct data_loc_info *dloc, u64 } static bool global_var__add(struct data_loc_info *dloc, u64 addr, - const char *name, Dwarf_Die *type_die) + const char *name, Dwarf_Die *type_die, bool from_alt) { struct dso *dso = map__dso(dloc->ms->map); struct global_var_entry *gvar; @@ -704,6 +706,8 @@ static bool global_var__add(struct data_loc_info *dloc, u64 addr, gvar->start = addr; gvar->end = addr + size; gvar->die_offset = dwarf_dieoffset(type_die); + gvar->die_tag = dwarf_tag(type_die); + gvar->from_alt = from_alt; rb_add(&gvar->node, dso__global_vars(dso), global_var_less); return true; @@ -778,12 +782,14 @@ static void global_var__collect(struct data_loc_info *dloc) if (pos->reg != -1) continue; - if (!dwarf_offdie(dwarf, pos->die_off, &type_die)) + if (!die_get_type_die(dwarf, pos->die_off, pos->die_tag, + pos->from_alt, &type_die)) continue; get_global_var_info(dloc, pos->addr, &var_name, &var_offset); - global_var__add(dloc, pos->addr, var_name, &type_die); + global_var__add(dloc, pos->addr, var_name, &type_die, + pos->from_alt); } delete_var_types(var_types); @@ -808,7 +814,8 @@ bool get_global_var_type(Dwarf_Die *cu_die, struct data_loc_info *dloc, gvar = global_var__find(dloc, var_addr); if (gvar) { - if (!dwarf_offdie(dloc->di->dbg, gvar->die_offset, type_die)) + if (!die_get_type_die(dloc->di->dbg, gvar->die_offset, + gvar->die_tag, gvar->from_alt, type_die)) return false; *var_offset = var_addr - gvar->start; @@ -838,7 +845,8 @@ bool get_global_var_type(Dwarf_Die *cu_die, struct data_loc_info *dloc, ok: /* The address should point to the start of the variable */ - global_var__add(dloc, var_addr - *var_offset, var_name, type_die); + global_var__add(dloc, var_addr - *var_offset, var_name, type_die, + !die_same_file(cu_die, type_die)); return true; } @@ -893,7 +901,8 @@ static void update_var_state(struct type_state *state, struct data_loc_info *dlo continue; } /* Get the type DIE using the offset */ - if (!dwarf_offdie(dloc->di->dbg, var->die_off, &mem_die)) + if (!die_get_type_die(dloc->di->dbg, var->die_off, + var->die_tag, var->from_alt, &mem_die)) continue; if (var->reg == DWARF_REG_FB || var->reg == fbreg || var->reg == state->stack_reg) { diff --git a/tools/perf/util/aslr.c b/tools/perf/util/aslr.c index 027695d96779..76eba1a23bc7 100644 --- a/tools/perf/util/aslr.c +++ b/tools/perf/util/aslr.c @@ -1243,7 +1243,7 @@ static int aslr_tool__init(struct aslr_tool *aslr, struct perf_tool *delegate) delegate_tool__init(&aslr->tool, delegate); aslr->tool.tool.ordered_events = true; - if (machines__init(&aslr->machines)) + if (machines__init(&aslr->machines, /*session=*/NULL)) return -ENOMEM; hashmap__init(&aslr->remap_addresses, @@ -1343,6 +1343,14 @@ void aslr_tool__delete(struct perf_tool *tool) free(aslr); } +void aslr_tool__register_session(struct perf_tool *tool, struct perf_session *session) +{ + struct delegate_tool *del_tool = container_of(tool, struct delegate_tool, tool); + struct aslr_tool *aslr = container_of(del_tool, struct aslr_tool, tool); + + aslr->machines.session = session; +} + int aslr_tool__cache_orig_attrs(struct perf_tool *tool, struct evsel *evsel) { struct delegate_tool *del_tool = container_of(tool, struct delegate_tool, tool); diff --git a/tools/perf/util/aslr.h b/tools/perf/util/aslr.h index 522e31c8e2c0..9cc14f0263db 100644 --- a/tools/perf/util/aslr.h +++ b/tools/perf/util/aslr.h @@ -28,6 +28,7 @@ PERF_SAMPLE_CODE_PAGE_SIZE | \ PERF_SAMPLE_AUX) +struct perf_session; struct perf_tool; struct evsel; struct evlist; @@ -36,6 +37,7 @@ union perf_event; struct perf_tool *aslr_tool__new(struct perf_tool *delegate); void aslr_tool__delete(struct perf_tool *tool); +void aslr_tool__register_session(struct perf_tool *tool, struct perf_session *session); void aslr_tool__strip_attr_event(union perf_event *event, struct evlist *evlist); int aslr_tool__cache_orig_attrs(struct perf_tool *tool, struct evsel *evsel); void aslr_tool__strip_evlist(const struct perf_tool *tool, struct evlist *evlist); diff --git a/tools/perf/util/bpf-filter.c b/tools/perf/util/bpf-filter.c index bcd81084e342..72e83ac1d6a4 100644 --- a/tools/perf/util/bpf-filter.c +++ b/tools/perf/util/bpf-filter.c @@ -56,6 +56,7 @@ #include "util/debug.h" #include "util/evsel.h" #include "util/target.h" +#include "util/thread_map.h" #include "util/bpf-utils.h" #include "util/bpf-filter.h" @@ -202,31 +203,6 @@ static int get_filter_entries(struct evsel *evsel, struct perf_bpf_filter_entry return 0; } -static int convert_to_tgid(int tid) -{ - char path[128]; - char *buf, *p, *q; - int tgid; - size_t len; - - scnprintf(path, sizeof(path), "%d/status", tid); - if (procfs__read_str(path, &buf, &len) < 0) - return -1; - - p = strstr(buf, "Tgid:"); - if (p == NULL) { - free(buf); - return -1; - } - - tgid = strtol(p + 6, &q, 0); - free(buf); - if (*q != '\n') - return -1; - - return tgid; -} - /* * The event might be closed already so we cannot get the list of ids using FD * like in create_event_hash() below, let's iterate the event_hash map and @@ -407,14 +383,13 @@ static int create_idx_hash(struct evsel *evsel, struct perf_bpf_filter_entry *en last = -1; nr = perf_thread_map__nr(threads); for (int i = 0; i < nr; i++) { - int pid = perf_thread_map__pid(threads, i); int tgid; struct idx_hash_key key = { .evt_id = event_id, }; /* it actually needs tgid, let's get tgid from /proc. */ - tgid = convert_to_tgid(pid); + tgid = thread_map__tgid(threads, i); if (tgid < 0) { /* the thread may be dead, ignore. */ continue; diff --git a/tools/perf/util/cs-etm.c b/tools/perf/util/cs-etm.c index 114b3cd2da49..1ac627d33982 100644 --- a/tools/perf/util/cs-etm.c +++ b/tools/perf/util/cs-etm.c @@ -309,27 +309,27 @@ static int cs_etm__map_trace_id_v0(struct cs_etm_auxtrace *etm, u8 trace_chan_id { struct cs_etm_queue *etmq; - /* - * If the queue is unformatted then only save one mapping in the - * queue associated with that CPU so only one decoder is made. - */ etmq = cs_etm__get_queue(etm, cpu_metadata[CS_ETM_CPU]); if (!etmq) return -EINVAL; + /* + * If the queue is unformatted then only save one mapping in the + * queue associated with that CPU so only one decoder is made. + */ if (etmq->format == UNFORMATTED) return cs_etm__insert_trace_id_node(etmq, trace_chan_id, cpu_metadata); /* * Otherwise, version 0 trace IDs are global so save them into every - * queue. + * formatted queue. */ for (unsigned int i = 0; i < etm->queues.nr_queues; ++i) { int ret; etmq = etm->queues.queue_array[i].priv; - if (!etmq) + if (!etmq || etmq->format == UNFORMATTED) continue; ret = cs_etm__insert_trace_id_node(etmq, trace_chan_id, diff --git a/tools/perf/util/debug.c b/tools/perf/util/debug.c index 6b5ffe81f141..b7095519419e 100644 --- a/tools/perf/util/debug.c +++ b/tools/perf/util/debug.c @@ -55,7 +55,7 @@ FILE *debug_file(void) { if (!_debug_file) { debug_set_file(stderr); - pr_warning_once("debug_file not set"); + pr_warning_once("%s not set\n", __func__); } return _debug_file; } diff --git a/tools/perf/util/dso.c b/tools/perf/util/dso.c index 42bfe30a3b51..9e90de92fcfa 100644 --- a/tools/perf/util/dso.c +++ b/tools/perf/util/dso.c @@ -1,38 +1,44 @@ // SPDX-License-Identifier: GPL-2.0 +#include "dso.h" + +#include +#include + #include +#include #include #include #include -#include #include -#include #include +#include +#include #include -#include -#include -#include -#ifdef HAVE_LIBBPF_SUPPORT -#include -#include "bpf-event.h" -#include "bpf-utils.h" -#endif + +#include "annotate-data.h" +#include "auxtrace.h" #include "compress.h" +#include "debug.h" +#include "dsos.h" #include "env.h" +#include "libbfd.h" +#include "libdw.h" +#include "machine.h" +#include "map.h" #include "namespaces.h" #include "path.h" -#include "map.h" -#include "symbol.h" #include "srcline.h" -#include "dso.h" -#include "dsos.h" -#include "machine.h" -#include "auxtrace.h" -#include "util.h" /* O_CLOEXEC for older systems */ -#include "debug.h" #include "string2.h" +#include "symbol.h" +#include "util.h" /* O_CLOEXEC for older systems */ #include "vdso.h" -#include "annotate-data.h" -#include "libdw.h" + +#ifdef HAVE_LIBBPF_SUPPORT +#include + +#include "bpf-event.h" +#include "bpf-utils.h" +#endif static const char * const debuglink_paths[] = { "%.0s%s", @@ -1757,6 +1763,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_libdw(dso); dso__free_symsrc_filename(dso); nsinfo__zput(RC_CHK_ACCESS(dso)->nsinfo); @@ -2075,3 +2082,13 @@ struct debuginfo *dso__debuginfo(struct dso *dso) free(name); return dinfo; } + +void dso__set_symsrc_filename(struct dso *dso, char *val) +{ + RC_CHK_ACCESS(dso)->symsrc_filename = val; + dso__free_libdw(dso); + dso__free_a2l(dso); + dso__free_a2l_libbfd(dso); + dso__set_has_srcline(dso, true); + dso__set_a2l_fails(dso, 0); +} diff --git a/tools/perf/util/dso.h b/tools/perf/util/dso.h index 55c4aaa53c38..9c4927f556c2 100644 --- a/tools/perf/util/dso.h +++ b/tools/perf/util/dso.h @@ -304,7 +304,12 @@ DECLARE_RC_STRUCT(dso) { const char *short_name; const char *long_name; void *a2l; +#ifdef HAVE_LIBBFD_SUPPORT + void *a2l_libbfd; +#endif +#ifdef HAVE_LIBDW_SUPPORT void *libdw; +#endif char *symsrc_filename; struct nsinfo *nsinfo; struct auxtrace_cache *auxtrace_cache; @@ -368,6 +373,20 @@ 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 + +struct Dwfl; +#ifdef HAVE_LIBDW_SUPPORT static inline void *dso__libdw(const struct dso *dso) { return RC_CHK_ACCESS(dso)->libdw; @@ -378,8 +397,6 @@ static inline void dso__set_libdw(struct dso *dso, void *val) RC_CHK_ACCESS(dso)->libdw = val; } -struct Dwfl; -#ifdef HAVE_LIBDW_SUPPORT struct Dwfl *dso__libdw_dwfl(struct dso *dso); #else static inline struct Dwfl *dso__libdw_dwfl(struct dso *dso __maybe_unused) @@ -735,10 +752,7 @@ static inline const char *dso__symsrc_filename(const struct dso *dso) return RC_CHK_ACCESS(dso)->symsrc_filename; } -static inline void dso__set_symsrc_filename(struct dso *dso, char *val) -{ - RC_CHK_ACCESS(dso)->symsrc_filename = val; -} +void dso__set_symsrc_filename(struct dso *dso, char *val) EXCLUSIVE_LOCKS_REQUIRED(dso__lock(dso)); static inline void dso__free_symsrc_filename(struct dso *dso) { diff --git a/tools/perf/util/dwarf-aux.c b/tools/perf/util/dwarf-aux.c index d7160f87ac7d..c16dbf8193f0 100644 --- a/tools/perf/util/dwarf-aux.c +++ b/tools/perf/util/dwarf-aux.c @@ -1632,6 +1632,15 @@ Dwarf_Die *die_find_variable_by_addr(Dwarf_Die *sc_die, Dwarf_Addr addr, return result; } +/* + * Whether two DIEs live in the same debug file: dwarf_dieoffset() is + * relative to the file the DIE is in. + */ +bool die_same_file(Dwarf_Die *die_a, Dwarf_Die *die_b) +{ + return dwarf_cu_getdwarf(die_a->cu) == dwarf_cu_getdwarf(die_b->cu); +} + static int __die_collect_vars_cb(Dwarf_Die *die_mem, void *arg) { struct die_var_type **var_types = arg; @@ -1676,6 +1685,8 @@ static int __die_collect_vars_cb(Dwarf_Die *die_mem, void *arg) vt->is_reg_var_addr = true; vt->die_off = dwarf_dieoffset(&type_die); + vt->die_tag = dwarf_tag(&type_die); + vt->from_alt = !die_same_file(die_mem, &type_die); vt->addr = start; vt->end = end; vt->has_range = (end != 0 || start != 0); @@ -1695,7 +1706,8 @@ static int __die_collect_vars_cb(Dwarf_Die *die_mem, void *arg) * * Save all variables and parameters in the @sc_die and save them to @var_types. * The @var_types is a singly-linked list containing type and location info. - * Actual type can be retrieved using dwarf_offdie() with 'die_off' later. + * Actual type can be retrieved using die_get_type_die() with 'die_off', + * 'die_tag' and 'from_alt' later. * * Callers should free @var_types. */ @@ -1741,6 +1753,8 @@ static int __die_collect_global_vars_cb(Dwarf_Die *die_mem, void *arg) return DIE_FIND_CB_END; vt->die_off = dwarf_dieoffset(&type_die); + vt->die_tag = dwarf_tag(&type_die); + vt->from_alt = !die_same_file(die_mem, &type_die); vt->addr = ops->number; vt->end = 0; vt->has_range = false; @@ -1752,6 +1766,43 @@ static int __die_collect_global_vars_cb(Dwarf_Die *die_mem, void *arg) return DIE_FIND_CB_SIBLING; } +/** + * die_get_type_die - Get a type DIE saved by die_collect_vars() + * @dbg: the main debug info + * @die_off: offset of the type DIE, from dwarf_dieoffset() + * @die_tag: tag that DIE had when the offset was saved + * @from_alt: whether the type DIE is in the dwz alt file + * @die_mem: where to store the resulting DIE + * + * Resolve @die_off in the file it was recorded as belonging to, with no + * fallback; @die_tag is a sanity check. + */ +Dwarf_Die *die_get_type_die(Dwarf *dbg, u64 die_off, int die_tag, bool from_alt, + Dwarf_Die *die_mem) +{ + Dwarf *target = dbg; + Dwarf_Die die; + + if (from_alt) { + /* No fallback: an alt offset here parses whatever is at it. */ + target = dwarf_getalt(dbg); + if (target == NULL) { + pr_debug("DWARF: no alt (dwz) debug file to resolve the type DIE at offset 0x%lx in\n", + (unsigned long)die_off); + return NULL; + } + } + + if (dwarf_offdie(target, die_off, &die) && dwarf_tag(&die) == die_tag) { + *die_mem = die; + return die_mem; + } + + pr_debug("DWARF: no DIE with tag %d at offset 0x%lx in the %s debug file\n", + die_tag, (unsigned long)die_off, from_alt ? "alt" : "main"); + return NULL; +} + /** * die_collect_global_vars - Save all global variables * @cu_die: a CU DIE @@ -1759,7 +1810,8 @@ static int __die_collect_global_vars_cb(Dwarf_Die *die_mem, void *arg) * * Save all global variables in the @cu_die and save them to @var_types. * The @var_types is a singly-linked list containing type and location info. - * Actual type can be retrieved using dwarf_offdie() with 'die_off' later. + * Actual type can be retrieved using die_get_type_die() with 'die_off', + * 'die_tag' and 'from_alt' later. * * Callers should free @var_types. */ diff --git a/tools/perf/util/dwarf-aux.h b/tools/perf/util/dwarf-aux.h index 161f0bf980b6..415d487d8c23 100644 --- a/tools/perf/util/dwarf-aux.h +++ b/tools/perf/util/dwarf-aux.h @@ -152,6 +152,8 @@ int die_get_scopes(Dwarf_Die *cu_die, Dwarf_Addr pc, Dwarf_Die **scopes); struct die_var_type { struct die_var_type *next; u64 die_off; + int die_tag; + bool from_alt; /* die_off is relative to the alt (dwz) file */ u64 addr; u64 end; /* end address of location range */ int reg; @@ -183,6 +185,17 @@ Dwarf_Die *die_find_variable_by_addr(Dwarf_Die *sc_die, Dwarf_Addr addr, /* Save all variables and parameters in this scope */ void die_collect_vars(Dwarf_Die *sc_die, struct die_var_type **var_types); +/* + * Get the type DIE saved by die_collect_vars()/die_collect_global_vars(): + * @from_alt says which file the offset must be resolved in, @die_tag is + * a sanity check. + */ +Dwarf_Die *die_get_type_die(Dwarf *dbg, u64 die_off, int die_tag, bool from_alt, + Dwarf_Die *die_mem); + +/* Whether two DIEs live in the same debug file */ +bool die_same_file(Dwarf_Die *die_a, Dwarf_Die *die_b); + /* Save all global variables in this CU */ void die_collect_global_vars(Dwarf_Die *cu_die, struct die_var_type **var_types); diff --git a/tools/perf/util/evlist.c b/tools/perf/util/evlist.c index c3d784727810..4fda65eacc5c 100644 --- a/tools/perf/util/evlist.c +++ b/tools/perf/util/evlist.c @@ -773,13 +773,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(evlist) >= n) return -1; *id = array[evlist__id_pos(evlist)]; } else { + u16 size = evsel__event_size(evlist__first(evlist), event); + + n = (size - sizeof(event->header)) >> 3; if (evlist__is_pos(evlist) > n) return -1; n -= evlist__is_pos(evlist); diff --git a/tools/perf/util/evsel.c b/tools/perf/util/evsel.c index 5db43520f25e..12e05676b0da 100644 --- a/tools/perf/util/evsel.c +++ b/tools/perf/util/evsel.c @@ -551,6 +551,7 @@ struct evsel *evsel__clone(struct evsel *orig) evsel->core.system_wide = orig->core.system_wide; evsel->core.requires_cpu = orig->core.requires_cpu; evsel->core.is_pmu_core = orig->core.is_pmu_core; + evsel->core.is_pmu_uncore = orig->core.is_pmu_uncore; if (orig->name) { evsel->name = strdup(orig->name); @@ -1092,9 +1093,9 @@ static void __evsel__config_callchain(struct evsel *evsel, const struct record_o bool function = evsel__is_function_event(evsel); struct perf_event_attr *attr = &evsel->core.attr; - if (EM_HOST == EM_S390 && param->record_mode == CALLCHAIN_FP) { - pr_warning_once( - "Framepointer unwinding lacks kernel support. Use '--call-graph dwarf'\n"); + if (EM_HOST == EM_S390 && evsel->pmu && !perf_pmu__is_software(evsel->pmu)) { + pr_warning_once("Cannot use hardware PMU 'cpum_cf' / 'cpum_sf' event with callchain. " + "Use a software 'cpu-clock' / 'task-clock' event.\n"); } evsel__set_sample_bit(evsel, CALLCHAIN); @@ -2996,6 +2997,12 @@ static int evsel__open_cpu(struct evsel *evsel, struct perf_cpu_map *cpus, enum rlimit_action set_rlimit = NO_CHANGE; struct perf_cpu cpu; + /* + * A failed attempt being retried after evsel__fallback() would + * otherwise keep group members out of their group in get_group_fd(). + */ + evsel->supported = true; + if (evsel__is_retire_lat(evsel)) { err = evsel__tpebs_open(evsel); goto out; @@ -3197,7 +3204,7 @@ static int perf_evsel__parse_id_sample(const union perf_event *event, const __u64 *array = event->sample.array; bool swapped = evsel->needs_swap; union u64_swap u; - int i = ((event->header.size - sizeof(event->header)) / sizeof(u64)) - 1; + int i = ((evsel__event_size(evsel, event) - sizeof(event->header)) / sizeof(u64)) - 1; if (type & PERF_SAMPLE_IDENTIFIER) { if (i < 0) @@ -3596,7 +3603,10 @@ int __evsel__parse_sample(struct evsel *evsel, union perf_event *event, } if (type & PERF_SAMPLE_RAW) { + const __u64 *raw; + OVERFLOW_CHECK_u64(array); + raw = array; u.val64 = *array; /* @@ -3612,16 +3622,14 @@ int __evsel__parse_sample(struct evsel *evsel, union perf_event *event, } data->raw_size = u.val32[0]; - /* - * The raw data is aligned on 64bits including the - * u32 size, so it's safe to use mem_bswap_64. - */ - if (swapped) - mem_bswap_64((void *) array, data->raw_size); - array = (void *)array + sizeof(u32); - OVERFLOW_CHECK(array, data->raw_size, max_size); + if (swapped) { + /* mem_bswap_64() accesses complete 64-bit words. */ + sz = roundup((u64)data->raw_size, sizeof(u64)); + OVERFLOW_CHECK(raw, sz, max_size); + mem_bswap_64((void *)raw, data->raw_size); + } data->raw_data = (void *)array; array = (void *)array + data->raw_size; } @@ -3651,6 +3659,8 @@ int __evsel__parse_sample(struct evsel *evsel, union perf_event *event, e = (struct branch_entry *)&data->branch_stack->hw_idx; } + OVERFLOW_CHECK(array, sz, max_size); + if (swapped) { /* * struct branch_flag does not have endian @@ -3666,7 +3676,6 @@ int __evsel__parse_sample(struct evsel *evsel, union perf_event *event, e->flags.value = evsel__bitfield_swap_branch_flags(e->flags.value); } - OVERFLOW_CHECK(array, sz, max_size); array = (void *)array + sz; if (evsel__has_branch_counters(evsel)) { @@ -3871,6 +3880,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 d9ecc6628217..0cf7faaff72b 100644 --- a/tools/perf/util/evsel.h +++ b/tools/perf/util/evsel.h @@ -468,6 +468,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/header.c b/tools/perf/util/header.c index 7db7da090a1e..128aff15fbbe 100644 --- a/tools/perf/util/header.c +++ b/tools/perf/util/header.c @@ -1264,7 +1264,11 @@ static int cpu_cache_level__read(struct cpu_cache_level *cache, u32 cpu, u16 lev return -1; cache->type[len] = 0; - cache->type = strim(cache->type); + { + char *trimmed = strim(cache->type); + + memmove(cache->type, trimmed, strlen(trimmed) + 1); + } scnprintf(file, PATH_MAX, "%s/size", path); if (sysfs__read_str(file, &cache->size, &len)) { @@ -1273,7 +1277,11 @@ static int cpu_cache_level__read(struct cpu_cache_level *cache, u32 cpu, u16 lev } cache->size[len] = 0; - cache->size = strim(cache->size); + { + char *trimmed = strim(cache->size); + + memmove(cache->size, trimmed, strlen(trimmed) + 1); + } scnprintf(file, PATH_MAX, "%s/shared_cpu_list", path); if (sysfs__read_str(file, &cache->map, &len)) { @@ -1283,7 +1291,11 @@ static int cpu_cache_level__read(struct cpu_cache_level *cache, u32 cpu, u16 lev } cache->map[len] = 0; - cache->map = strim(cache->map); + { + char *trimmed = strim(cache->map); + + memmove(cache->map, trimmed, strlen(trimmed) + 1); + } return 0; } diff --git a/tools/perf/util/jitdump.c b/tools/perf/util/jitdump.c index 83005b30b9bf..d25a9fe9b020 100644 --- a/tools/perf/util/jitdump.c +++ b/tools/perf/util/jitdump.c @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -117,6 +118,8 @@ jit_close(struct jit_buf_desc *jd) funlockfile(jd->in); fclose(jd->in); jd->in = NULL; + zfree(&jd->debug_data); + zfree(&jd->unwinding_data); } static int @@ -143,6 +146,7 @@ jit_open(struct jit_buf_desc *jd, const char *name) ssize_t bs, bsz = 0; void *n, *buf = NULL; int ret, retval = -1; + char *dname; nsinfo__mountns_enter(jd->nsi, &nsc); jd->in = fopen(name, "r"); @@ -154,7 +158,7 @@ jit_open(struct jit_buf_desc *jd, const char *name) buf = malloc(bsz); if (!buf) - goto error; + goto error_noflock; /* * protect from writer modifying the file while we are reading it @@ -224,10 +228,12 @@ jit_open(struct jit_buf_desc *jd, const char *name) n = realloc(buf, bs); if (!n) goto error; - bsz = bs; buf = n; - /* read extra we do not know about */ - ret = fread(buf, bs - bsz, 1, jd->in); + bsz = bs; + } + if (bs > 0) { + /* consume extended header bytes from the stream */ + ret = fread(buf, bs, 1, jd->in); if (ret != 1) goto error; } @@ -236,13 +242,16 @@ jit_open(struct jit_buf_desc *jd, const char *name) */ strncpy(jd->dir, name, PATH_MAX - 1); jd->dir[PATH_MAX - 1] = '\0'; - dirname(jd->dir); + dname = dirname(jd->dir); + if (dname != jd->dir) + strlcpy(jd->dir, dname, sizeof(jd->dir)); free(buf); return 0; error: - free(buf); funlockfile(jd->in); +error_noflock: + free(buf); fclose(jd->in); return retval; } @@ -315,14 +324,32 @@ jit_get_next_entry(struct jit_buf_desc *jd) switch(id) { case JIT_CODE_DEBUG_INFO: if (jd->needs_bswap) { + void *end = (void *)jr + jr->prefix.total_size; + struct debug_entry *ent; uint64_t n; + jr->info.code_addr = bswap_64(jr->info.code_addr); jr->info.nr_entry = bswap_64(jr->info.nr_entry); - for (n = 0 ; n < jr->info.nr_entry; n++) { - jr->info.entries[n].addr = bswap_64(jr->info.entries[n].addr); - jr->info.entries[n].lineno = bswap_32(jr->info.entries[n].lineno); - jr->info.entries[n].discrim = bswap_32(jr->info.entries[n].discrim); + + /* + * debug_entry has a variable-length name[], so array + * indexing would compute wrong offsets — use + * debug_entry_next() and bounds-check each entry. + */ + ent = &jr->info.entries[0]; + for (n = 0; n < jr->info.nr_entry; n++) { + if ((void *)ent + sizeof(*ent) > end) + break; + /* name must be NUL-terminated within the record */ + if (!memchr(ent->name, '\0', (char *)end - ent->name)) + break; + ent->addr = bswap_64(ent->addr); + ent->lineno = bswap_32(ent->lineno); + ent->discrim = bswap_32(ent->discrim); + ent = debug_entry_next(ent); } + /* clamp so downstream consumers don't overrun */ + jr->info.nr_entry = n; } break; case JIT_CODE_UNWINDING_INFO: @@ -435,7 +462,8 @@ static int jit_repipe_code_load(struct jit_buf_desc *jd, union jr_entry *jr) u16 idr_size; const char *sym; uint64_t count; - int ret, csize, usize; + int ret, csize; + uint64_t usize; pid_t nspid, pid, tid; struct { u32 pid, tid; @@ -448,8 +476,25 @@ static int jit_repipe_code_load(struct jit_buf_desc *jd, union jr_entry *jr) csize = jr->load.code_size; usize = jd->unwinding_mapped_size; addr = jr->load.code_addr; + + /* code blob lives at the end of the record, validate it fits */ + if (jr->load.p.total_size < sizeof(jr->load) || + jr->load.code_size > jr->load.p.total_size - sizeof(jr->load) || + jr->load.code_size > INT_MAX) { + pr_warning("jitdump: invalid code_size %" PRIu64 " (total_size=%u) in code_load record\n", + (uint64_t)jr->load.code_size, jr->load.p.total_size); + return -1; + } + sym = (void *)((unsigned long)jr + sizeof(jr->load)); code = (unsigned long)jr + jr->load.p.total_size - csize; + + /* sym string lives between the load header and the code blob */ + if (!memchr(sym, '\0', code - (unsigned long)sym)) { + pr_warning("jitdump: unterminated symbol name in code_load record\n"); + return -1; + } + count = jr->load.code_index; idr_size = jd->machine->id_hdr_size; @@ -462,6 +507,9 @@ static int jit_repipe_code_load(struct jit_buf_desc *jd, union jr_entry *jr) jd->dir, nspid, count); + /* snprintf returns would-be length on truncation, clamp to buffer */ + if (size >= sizeof(event->mmap2.filename)) + size = sizeof(event->mmap2.filename) - 1; size++; /* for \0 */ @@ -496,7 +544,7 @@ static int jit_repipe_code_load(struct jit_buf_desc *jd, union jr_entry *jr) event->mmap2.pgoff = GEN_ELF_TEXT_OFFSET; event->mmap2.start = addr; - event->mmap2.len = usize ? ALIGN_8(csize) + usize : csize; + event->mmap2.len = usize ? ALIGN_8((uint64_t)csize) + usize : (uint64_t)csize; event->mmap2.pid = pid; event->mmap2.tid = tid; event->mmap2.ino = st.st_ino; @@ -565,7 +613,7 @@ static int jit_repipe_code_move(struct jit_buf_desc *jd, union jr_entry *jr) char *filename; size_t size; struct stat st; - int usize; + uint64_t usize; u16 idr_size; int ret; pid_t nspid, pid, tid; @@ -592,6 +640,9 @@ static int jit_repipe_code_move(struct jit_buf_desc *jd, union jr_entry *jr) jd->dir, nspid, jr->move.code_index); + /* snprintf returns would-be length on truncation, clamp to buffer */ + if (size >= sizeof(event->mmap2.filename)) + size = sizeof(event->mmap2.filename) - 1; size++; /* for \0 */ @@ -645,17 +696,24 @@ static int jit_repipe_code_move(struct jit_buf_desc *jd, union jr_entry *jr) build_id__mark_dso_hit(tool, event, &sample, jd->machine); out: perf_sample__exit(&sample); + free(event); return ret; } static int jit_repipe_debug_info(struct jit_buf_desc *jd, union jr_entry *jr) { - void *data; - size_t sz; + struct debug_entry *ent; + void *data, *end; + size_t sz, valid; + uint64_t i; if (!(jd && jr)) return -1; + /* total_size must cover at least the fixed header */ + if (jr->prefix.total_size < sizeof(jr->info)) + return -1; + sz = jr->prefix.total_size - sizeof(jr->info); data = malloc(sz); if (!data) @@ -663,13 +721,29 @@ static int jit_repipe_debug_info(struct jit_buf_desc *jd, union jr_entry *jr) memcpy(data, &jr->info.entries, sz); + zfree(&jd->debug_data); jd->debug_data = data; /* - * we must use nr_entry instead of size here because - * we cannot distinguish actual entry from padding otherwise + * Clamp nr_debug_entries to entries that actually fit in the + * payload. The byte-swap path already does this for cross-endian + * files; validate on the native path too, since downstream + * jit_process_debug_info() iterates via debug_entry_next() which + * calls strlen() on each entry's name field. */ - jd->nr_debug_entries = jr->info.nr_entry; + end = data + sz; + ent = data; + valid = 0; + for (i = 0; i < jr->info.nr_entry; i++) { + if ((void *)ent + sizeof(*ent) > end) + break; + /* name must be NUL-terminated within the payload */ + if (!memchr(ent->name, '\0', (char *)end - ent->name)) + break; + ent = debug_entry_next(ent); + valid++; + } + jd->nr_debug_entries = valid; return 0; } @@ -683,7 +757,23 @@ jit_repipe_unwinding_info(struct jit_buf_desc *jd, union jr_entry *jr) if (!(jd && jr)) return -1; + /* total_size must cover at least the fixed header */ + if (jr->prefix.total_size < sizeof(jr->unwinding)) + return -1; + unwinding_data_size = jr->prefix.total_size - sizeof(jr->unwinding); + + /* + * Validate sizes before allocating — jit_add_eh_frame_info() + * computes unwinding_size - eh_frame_hdr_size and uses the + * result as a buffer length for libelf. + */ + if (jr->unwinding.unwinding_size > unwinding_data_size || + jr->unwinding.eh_frame_hdr_size > jr->unwinding.unwinding_size) { + pr_warning("jitdump: invalid unwinding sizes in unwinding_info record\n"); + return -1; + } + unwinding_data = malloc(unwinding_data_size); if (!unwinding_data) return -1; diff --git a/tools/perf/util/libbfd.c b/tools/perf/util/libbfd.c index 33dc6158b2b1..397fb4ad761f 100644 --- a/tools/perf/util/libbfd.c +++ b/tools/perf/util/libbfd.c @@ -39,13 +39,13 @@ struct a2l_data { asymbol **syms; }; -static bool perf_bfd_lock(void *bfd_mutex) +static bool perf_bfd_lock(void *bfd_mutex) NO_THREAD_SAFETY_ANALYSIS { mutex_lock(bfd_mutex); return true; } -static bool perf_bfd_unlock(void *bfd_mutex) +static bool perf_bfd_unlock(void *bfd_mutex) NO_THREAD_SAFETY_ANALYSIS { mutex_unlock(bfd_mutex); return true; @@ -72,6 +72,23 @@ static void ensure_bfd_init(void) pthread_once(&bfd_init_once, perf_bfd_init); } +/* + * Flags from libiberty's demangle.h. bfd.h declares bfd_demangle but not the + * flags to pass to it, and demangle.h isn't installed by every binutils + * package. + */ +#ifndef DMGL_PARAMS +#define DMGL_PARAMS (1 << 0) /* Include function arguments. */ +#define DMGL_ANSI (1 << 1) /* Include const, volatile, etc. */ +#endif + +char *libbfd__demangle_sym(const char *str, bool params, bool modifiers) +{ + int flags = (params ? DMGL_PARAMS : 0) | (modifiers ? DMGL_ANSI : 0); + + return bfd_demangle(/*abfd=*/NULL, str, flags); +} + static int bfd_error(const char *string) { const char *errmsg; @@ -210,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; @@ -226,17 +243,22 @@ 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; + + mutex_lock(dso__lock(dso)); + dso_name = dso__symsrc_filename(dso) ?: dso_name; + 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) { if (!symbol_conf.addr2line_disable_warn) pr_warning("addr2line_init failed for %s\n", dso_name); - return 0; + ret = -1; + goto out; } a2l->addr = addr; @@ -244,14 +266,19 @@ int libbfd__addr2line(const char *dso_name, u64 addr, bfd_map_over_sections(a2l->abfd, find_address_in_section, a2l); - if (!a2l->found) - return 0; + if (!a2l->found) { + ret = 0; + goto out; + } if (unwind_inlines) { int cnt = 0; - if (node && inline_list__append_dso_a2l(dso, node, sym)) - return 0; + if (node && inline_list__append_dso_a2l(dso, node, sym)) { + inline_node__clear_frames(node); + ret = -ENOMEM; + goto out; + } while (bfd_find_inliner_info(a2l->abfd, &a2l->filename, &a2l->funcname, &a2l->line) && @@ -261,35 +288,48 @@ int libbfd__addr2line(const char *dso_name, u64 addr, a2l->filename = NULL; if (node != NULL) { - if (inline_list__append_dso_a2l(dso, node, sym)) - return 0; - // found at least one inline frame - ret = 1; + if (inline_list__append_dso_a2l(dso, node, sym)) { + inline_node__clear_frames(node); + ret = -ENOMEM; + goto out; + } } } } if (file) { *file = a2l->filename ? strdup(a2l->filename) : NULL; - ret = *file ? 1 : 0; + if (!*file) { + ret = a2l->filename ? -ENOMEM : 0; + goto out; + } } if (line) *line = a2l->line; + /* + * The address was found, report success so that the caller doesn't try + * another addr2line implementation that would append the inline frames + * above a second time. + */ + ret = 1; + +out: + mutex_unlock(dso__lock(dso)); return ret; } 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) @@ -411,7 +451,7 @@ int dso__load_bfd_symbols(struct dso *dso, const char *debugfile) symbols__fixup_duplicate(dso__symbols(dso)); dso__set_adjust_symbols(dso, true); - err = 0; + err = dso__has_symbols(dso); out_free: free(symbols); out_close: diff --git a/tools/perf/util/libbfd.h b/tools/perf/util/libbfd.h index 953886f3d62f..14171db8b112 100644 --- a/tools/perf/util/libbfd.h +++ b/tools/perf/util/libbfd.h @@ -31,6 +31,8 @@ int libbfd_filename__read_debuglink(const char *filename, char *debuglink, size_ int symbol__disassemble_bpf_libbfd(struct symbol *sym, struct annotate_args *args); +char *libbfd__demangle_sym(const char *str, bool params, bool modifiers); + #else // !defined(HAVE_LIBBFD_SUPPORT) #include "annotate.h" @@ -77,6 +79,13 @@ static inline int symbol__disassemble_bpf_libbfd(struct symbol *sym __always_unu return SYMBOL_ANNOTATE_ERRNO__NO_LIBOPCODES_FOR_BPF; } +static inline char *libbfd__demangle_sym(const char *str __always_unused, + bool params __always_unused, + bool modifiers __always_unused) +{ + return NULL; +} + #endif // defined(HAVE_LIBBFD_SUPPORT) #endif /* __PERF_LIBBFD_H */ diff --git a/tools/perf/util/libdw.c b/tools/perf/util/libdw.c index 4ca7e7e4fbe9..e660623338d5 100644 --- a/tools/perf/util/libdw.c +++ b/tools/perf/util/libdw.c @@ -7,6 +7,7 @@ #include "callchain.h" #include #include +#include #include static const Dwfl_Callbacks offline_callbacks = { @@ -35,7 +36,7 @@ struct Dwfl *dso__libdw_dwfl(struct dso *dso) if (dwfl) return dwfl; - dso_name = dso__long_name(dso); + dso_name = dso__symsrc_filename(dso) ?: dso__long_name(dso); /* * Initialize Dwfl session. * We need to open the DSO file to report it to libdw. @@ -167,32 +168,55 @@ int libdw__addr2line(u64 addr, char **file, unsigned int *line_nr, struct dso *dso, bool unwind_inlines, struct inline_node *node, struct symbol *sym) { - Dwfl *dwfl = dso__libdw_dwfl(dso); + Dwfl *dwfl; Dwfl_Module *mod; Dwfl_Line *dwline; Dwarf_Addr bias; const char *src; int lineno = 0; + int ret = 0; - if (!dwfl) + if (!dso__has_srcline(dso)) return 0; + mutex_lock(dso__lock(dso)); + dwfl = dso__libdw_dwfl(dso); + if (!dwfl) { + ret = -1; + goto out; + } + mod = dwfl_addrmodule(dwfl, addr); - if (!mod) - return 0; + if (!mod) { + ret = 0; + goto out; + } /* * Get/ignore the dwarf information. Determine the bias, difference * between the regular ELF addr2line addresses and those to use with * libdw. */ - if (!dwfl_module_getdwarf(mod, &bias)) - return 0; + if (!dwfl_module_getdwarf(mod, &bias)) { + /* + * Free the Dwfl session so the mmap'd ELF binary is unmapped + * immediately, and mark the DSO as lacking srcline/DWARF info + * so neither libdw nor slower fallback backends (addr2line + * subprocess, libbfd) are repeatedly invoked on stripped DSOs. + */ + dso__free_libdw(dso); + dso__set_has_srcline(dso, false); + ret = 0; + goto out; + } /* Find source line information for the address. */ dwline = dwfl_module_getsrc(mod, addr + bias); - if (!dwline) - return 0; + if (!dwline) { + /* conclusively missing information -> abort fallbacks */ + ret = 0; + goto out; + } /* Get line information. */ src = dwfl_lineinfo(dwline, /*addr=*/NULL, &lineno, /*col=*/NULL, /*mtime=*/NULL, @@ -219,7 +243,8 @@ int libdw__addr2line(u64 addr, char **file, unsigned int *line_nr, free(*file); *file = NULL; } - return 0; + ret = -ENOMEM; + goto out; } /* Walk from the parent down to the leaf. */ @@ -235,8 +260,13 @@ int libdw__addr2line(u64 addr, char **file, unsigned int *line_nr, *file = NULL; } inline_node__clear_frames(node); - return 0; + ret = args.err; + goto out; } } - return 1; + ret = 1; + +out: + mutex_unlock(dso__lock(dso)); + return ret; } diff --git a/tools/perf/util/libdw.h b/tools/perf/util/libdw.h index b12094737415..c8f319ce35df 100644 --- a/tools/perf/util/libdw.h +++ b/tools/perf/util/libdw.h @@ -23,7 +23,8 @@ struct symbol; * finds the source line information for the given address, and optionally * resolves inline function call chains. * - * Returns 1 on success (found), 0 on failure (not found). + * Returns 1 on success (found), 0 when DWARF/line info is conclusively + * missing, and < 0 on initialization or uncompiled error. */ int libdw__addr2line(u64 addr, char **file, unsigned int *line_nr, struct dso *dso, @@ -47,7 +48,7 @@ static inline int libdw__addr2line(u64 addr __maybe_unused, char **file __maybe_ struct inline_node *node __maybe_unused, struct symbol *sym __maybe_unused) { - return 0; + return -1; } static inline void dso__free_libdw(struct dso *dso __maybe_unused) diff --git a/tools/perf/util/llvm-c-helpers.cpp b/tools/perf/util/llvm-c-helpers.cpp index 004081bd12c9..d990166100f0 100644 --- a/tools/perf/util/llvm-c-helpers.cpp +++ b/tools/perf/util/llvm-c-helpers.cpp @@ -50,20 +50,20 @@ static LLVMSymbolizer *get_symbolizer() return instance; } -/* Returns 0 on error, 1 on success. */ +/* Returns < 0 on error, 0 when line info is missing, 1 on success. */ static int extract_file_and_line(const DILineInfo &line_info, char **file, unsigned int *line) { - if (file) { - if (line_info.FileName == "") { - /* Match the convention of libbfd. */ + if (line_info.FileName == "") { + if (file) *file = nullptr; - } else { - /* The caller expects to get something it can free(). */ - *file = strdup(line_info.FileName.c_str()); - if (*file == nullptr) - return 0; - } + return 0; + } + if (file) { + /* The caller expects to get something it can free(). */ + *file = strdup(line_info.FileName.c_str()); + if (*file == nullptr) + return -ENOMEM; } if (line) *line = line_info.Line; @@ -86,30 +86,42 @@ int llvm_addr2line(const char *dso_name, u64 addr, Expected res_or_err = symbolizer->symbolizeInlinedCode(dso_name, sectioned_addr); - if (!res_or_err) - return 0; + if (!res_or_err) { + consumeError(res_or_err.takeError()); + return -1; + } unsigned num_frames = res_or_err->getNumberOfFrames(); if (num_frames == 0) return 0; - if (extract_file_and_line(res_or_err->getFrame(0), - file, line) == 0) - return 0; + int ret = extract_file_and_line(res_or_err->getFrame(0), + file, line); + if (ret <= 0) + return ret; *inline_frames = (llvm_a2l_frame *)calloc( num_frames, sizeof(**inline_frames)); - if (*inline_frames == nullptr) - return 0; + if (*inline_frames == nullptr) { + if (file) + zfree(file); + return -ENOMEM; + } for (unsigned i = 0; i < num_frames; ++i) { const DILineInfo &src = res_or_err->getFrame(i); llvm_a2l_frame &dst = (*inline_frames)[i]; - if (src.FileName == "") - /* Match the convention of libbfd. */ - dst.filename = nullptr; - else - dst.filename = strdup(src.FileName.c_str()); + if (src.FileName == "") { + for (unsigned j = 0; j < i; ++j) { + zfree(&(*inline_frames)[j].filename); + zfree(&(*inline_frames)[j].funcname); + } + zfree(inline_frames); + if (file) + zfree(file); + return 0; + } + dst.filename = strdup(src.FileName.c_str()); dst.funcname = strdup(src.FunctionName.c_str()); dst.line = src.Line; @@ -120,7 +132,9 @@ int llvm_addr2line(const char *dso_name, u64 addr, zfree(&(*inline_frames)[j].funcname); } zfree(inline_frames); - return 0; + if (file) + zfree(file); + return -ENOMEM; } } @@ -131,8 +145,10 @@ int llvm_addr2line(const char *dso_name, u64 addr, Expected res_or_err = symbolizer->symbolizeCode(dso_name, sectioned_addr); - if (!res_or_err) - return 0; + if (!res_or_err) { + consumeError(res_or_err.takeError()); + return -1; + } return extract_file_and_line(*res_or_err, file, line); } } diff --git a/tools/perf/util/llvm.c b/tools/perf/util/llvm.c index a0deb742a733..cdf26a31599e 100644 --- a/tools/perf/util/llvm.c +++ b/tools/perf/util/llvm.c @@ -42,8 +42,11 @@ int llvm__addr2line(const char *dso_name __maybe_unused, u64 addr __maybe_unused int num_frames = llvm_addr2line(dso_name, addr, file, line, node && unwind_inlines, &inline_frames); - if (num_frames == 0 || !inline_frames) { - /* Error, or we didn't want inlines. */ + if (num_frames <= 0 || !inline_frames) { + /* + * Error (< 0 -> iterate fallbacks), missing line info (0), or + * we resolved lines without wanting inlines (1). + */ return num_frames; } @@ -58,8 +61,11 @@ int llvm__addr2line(const char *dso_name __maybe_unused, u64 addr __maybe_unused inline_frames[i].line); } if (inline_list__append(inline_sym, srcline, node) != 0) { + if (file) + zfree(file); + inline_node__clear_frames(node); free_llvm_inline_frames(inline_frames, num_frames); - return 0; + return -1; } } free_llvm_inline_frames(inline_frames, num_frames); @@ -254,8 +260,10 @@ int symbol__disassemble_llvm(const char *filename, struct symbol *sym, (unsigned int *)&args->line_nr, false, NULL); dl = disasm_line__new(args); - if (dl == NULL) + if (dl == NULL) { + free(args->fileloc); goto err; + } annotation_line__add(&dl->al, ¬es->src->source); diff --git a/tools/perf/util/machine.c b/tools/perf/util/machine.c index 10a88c070814..076d167380f2 100644 --- a/tools/perf/util/machine.c +++ b/tools/perf/util/machine.c @@ -233,10 +233,12 @@ void machine__delete(struct machine *machine) } } -int machines__init(struct machines *machines) +int machines__init(struct machines *machines, struct perf_session *session) { int err = machine__init(&machines->host, "", HOST_KERNEL_ID); + machines->session = session; + machines->host.machines = machines; machines->guests = RB_ROOT_CACHED; return err; } diff --git a/tools/perf/util/machine.h b/tools/perf/util/machine.h index 26f9827062f5..973a59f7c26a 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; }; -int machines__init(struct machines *machines); +int 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/mem-events.c b/tools/perf/util/mem-events.c index 0b49fce251fc..4e490f9cd348 100644 --- a/tools/perf/util/mem-events.c +++ b/tools/perf/util/mem-events.c @@ -610,7 +610,7 @@ int perf_script__meminfo_scnprintf(char *out, size_t sz, const struct mem_info * i += scnprintf(out, sz, "|OP "); i += perf_mem__op_scnprintf(out + i, sz - i, mem_info); i += scnprintf(out + i, sz - i, "|LVL "); - i += perf_mem__lvl_scnprintf(out + i, sz, mem_info); + i += perf_mem__lvl_scnprintf(out + i, sz - i, mem_info); i += scnprintf(out + i, sz - i, "|SNP "); i += perf_mem__snp_scnprintf(out + i, sz - i, mem_info); i += scnprintf(out + i, sz - i, "|TLB "); diff --git a/tools/perf/util/mmap.c b/tools/perf/util/mmap.c index 358e70c4f3ed..6dcc4a9304b9 100644 --- a/tools/perf/util/mmap.c +++ b/tools/perf/util/mmap.c @@ -330,7 +330,7 @@ int mmap__mmap(struct mmap *map, struct mmap_params *mp, int fd, struct perf_cpu int perf_mmap__push(struct mmap *md, void *to, int push(struct mmap *map, void *to, void *buf, size_t size)) { - u64 head = perf_mmap__read_head(&md->core); + u64 head; unsigned char *data = md->core.base + page_size; unsigned long size; void *buf; @@ -340,6 +340,7 @@ int perf_mmap__push(struct mmap *md, void *to, if (rc < 0) return (rc == -EAGAIN) ? 1 : -1; + head = md->core.overwrite ? md->core.start : md->core.end; size = md->core.end - md->core.start; if ((md->core.start & md->core.mask) + size != (md->core.end & md->core.mask)) { diff --git a/tools/perf/util/parse-events.c b/tools/perf/util/parse-events.c index cc7ad331a49f..5a84da4548e3 100644 --- a/tools/perf/util/parse-events.c +++ b/tools/perf/util/parse-events.c @@ -1,10 +1,10 @@ // SPDX-License-Identifier: GPL-2.0 +#include #include #include #include #include #include -#include #include #include #include "cpumap.h" @@ -269,6 +269,7 @@ __add_event(struct list_head *list, int *idx, evsel->core.pmu_cpus = pmu_cpus; evsel->core.requires_cpu = pmu ? pmu->is_uncore : false; evsel->core.is_pmu_core = is_pmu_core; + evsel->core.is_pmu_uncore = pmu ? pmu->is_uncore : false; evsel->core.reads_only_on_cpu_idx0 = perf_pmu__reads_only_on_cpu_idx0(attr); evsel->pmu = pmu; evsel->alternate_hw_config = alternate_hw_config; diff --git a/tools/perf/util/pmus.c b/tools/perf/util/pmus.c index e0a4cb2428ca..1355b317f3ed 100644 --- a/tools/perf/util/pmus.c +++ b/tools/perf/util/pmus.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include "cpumap.h" @@ -571,7 +572,7 @@ static int cmp_sevent(const void *a, const void *b) } /* Order by event name. */ - return strcmp(as->name, bs->name); + return strcmp(as->name ?: "", bs->name ?: ""); } static bool pmu_alias_is_duplicate(struct sevent *a, struct sevent *b) @@ -581,7 +582,7 @@ static bool pmu_alias_is_duplicate(struct sevent *a, struct sevent *b) return false; /* Don't remove duplicates for different PMUs */ - return strcmp(a->pmu_name, b->pmu_name) == 0; + return strcmp(a->pmu_name ?: "", b->pmu_name ?: "") == 0; } struct events_callback_state { @@ -597,8 +598,18 @@ static int perf_pmus__print_pmu_events__callback(void *vstate, struct sevent *s; if (state->index >= state->aliases_len) { - pr_err("Unexpected event %s/%s/\n", info->pmu->name, info->name); - return 1; + size_t new_len = max_t(size_t, 16, state->aliases_len * 2); + struct sevent *new_aliases; + + new_aliases = realloc(state->aliases, new_len * sizeof(struct sevent)); + if (!new_aliases) { + pr_err("Unexpected event %s/%s/\n", info->pmu->name, info->name); + return 1; + } + memset(&new_aliases[state->aliases_len], 0, + (new_len - state->aliases_len) * sizeof(struct sevent)); + state->aliases = new_aliases; + state->aliases_len = new_len; } assert(info->pmu != NULL || info->name != NULL); s = &state->aliases[state->index]; @@ -654,6 +665,8 @@ void perf_pmus__print_pmu_events(const struct print_callbacks *print_cb, void *p perf_pmu__for_each_event(pmu, skip_duplicate_pmus, &state, perf_pmus__print_pmu_events__callback); } + aliases = state.aliases; + len = state.index; qsort(aliases, len, sizeof(struct sevent), cmp_sevent); for (int j = 0; j < len; j++) { /* Skip duplicates */ diff --git a/tools/perf/util/print_insn.h b/tools/perf/util/print_insn.h index cefa5c5f246e..3de9438af9cd 100644 --- a/tools/perf/util/print_insn.h +++ b/tools/perf/util/print_insn.h @@ -4,6 +4,7 @@ #include #include +#include #include diff --git a/tools/perf/util/python.c b/tools/perf/util/python.c index c504b83be39f..58052a4e6a1f 100644 --- a/tools/perf/util/python.c +++ b/tools/perf/util/python.c @@ -4245,6 +4245,7 @@ PyMODINIT_FUNC PyInit_perf(void) /* The page_size is placed in util object. */ page_size = sysconf(_SC_PAGE_SIZE); + perf_debug_setup(); Py_INCREF(&pyrf_evlist__type); PyModule_AddObject(module, "evlist", (PyObject *)&pyrf_evlist__type); diff --git a/tools/perf/util/session.c b/tools/perf/util/session.c index 3237870a1a34..1505a6f125be 100644 --- a/tools/perf/util/session.c +++ b/tools/perf/util/session.c @@ -161,7 +161,7 @@ struct perf_session *__perf_session__new(struct perf_data *data, session->active_decomp = &session->decomp_data; INIT_LIST_HEAD(&session->auxtrace_index); perf_env__init(&session->header.env); - if (machines__init(&session->machines)) + if (machines__init(&session->machines, session)) goto out_delete; ordered_events__init(&session->ordered_events, diff --git a/tools/perf/util/setup.py b/tools/perf/util/setup.py index 8380980ade4c..3b6a59f66944 100644 --- a/tools/perf/util/setup.py +++ b/tools/perf/util/setup.py @@ -173,6 +173,7 @@ def main() -> None: perf = Extension( 'perf', sources=[os.path.join(src_perf, 'util/python.c')], + depends=shlex.split(os.getenv('PYTHON_EXT_DEPS', '')), include_dirs=['util/include'], extra_compile_args=cflags, ) diff --git a/tools/perf/util/srcline.c b/tools/perf/util/srcline.c index b082178c279b..23951c35fb66 100644 --- a/tools/perf/util/srcline.c +++ b/tools/perf/util/srcline.c @@ -1,40 +1,49 @@ // SPDX-License-Identifier: GPL-2.0 #include "srcline.h" + +#include +#include +#include +#include + +#include +#include + #include "addr2line.h" -#include "dso.h" #include "callchain.h" +#include "debug.h" +#include "dso.h" #include "libbfd.h" +#include "libdw.h" #include "llvm.h" #include "symbol.h" -#include "libdw.h" -#include "debug.h" #include "util.h" -#include -#include -#include -#include - bool srcline_full_filename; char *srcline__unknown = (char *)"??:0"; -static const char *srcline_dso_name(struct dso *dso) +static char *srcline_dso_name(struct dso *dso) { const char *dso_name; + char *ret = NULL; + mutex_lock(dso__lock(dso)); if (dso__symsrc_filename(dso)) dso_name = dso__symsrc_filename(dso); else dso_name = dso__long_name(dso); if (dso_name[0] == '[') - return NULL; + goto out; if (is_perf_pid_map_name(dso_name)) - return NULL; + goto out; - return dso_name; + ret = strdup(dso_name); +out: + mutex_unlock(dso__lock(dso)); + return ret; } int inline_list__append(struct symbol *symbol, char *srcline, struct inline_node *node) @@ -172,9 +181,9 @@ static int addr2line(const char *dso_name, u64 addr, char **file, unsigned int * break; case A2L_STYLE_UNKNOWN: default: - break; + return 0; } - if (ret > 0) + if (ret >= 0) return ret; } @@ -241,6 +250,10 @@ static struct inline_node *addr2inlines(const char *dso_name, u64 addr, addr2line(dso_name, addr, /*file=*/NULL, /*line_nr=*/NULL, dso, /*unwind_inlines=*/true, node, sym); + if (!dso__has_srcline(dso) && list_empty(&node->val)) { + inline_node__delete(node); + return NULL; + } return node; } @@ -258,7 +271,7 @@ char *__get_srcline(struct dso *dso, u64 addr, struct symbol *sym, char *file = NULL; unsigned line = 0; char *srcline; - const char *dso_name; + char *dso_name; if (!dso__has_srcline(dso)) goto out; @@ -267,9 +280,12 @@ char *__get_srcline(struct dso *dso, u64 addr, struct symbol *sym, if (dso_name == NULL) goto out_err; - if (!addr2line(dso_name, addr, &file, &line, dso, - unwind_inlines, /*node=*/NULL, sym)) + if (addr2line(dso_name, addr, &file, &line, dso, + unwind_inlines, /*node=*/NULL, sym) <= 0) { + free(dso_name); goto out_err; + } + free(dso_name); srcline = srcline_from_fileline(file, line); free(file); @@ -277,16 +293,22 @@ char *__get_srcline(struct dso *dso, u64 addr, struct symbol *sym, if (!srcline) goto out_err; + mutex_lock(dso__lock(dso)); dso__set_a2l_fails(dso, 0); + mutex_unlock(dso__lock(dso)); return srcline; out_err: + mutex_lock(dso__lock(dso)); dso__set_a2l_fails(dso, dso__a2l_fails(dso) + 1); if (dso__a2l_fails(dso) > A2L_FAIL_LIMIT) { dso__set_has_srcline(dso, false); dso__free_a2l(dso); + dso__free_a2l_libbfd(dso); + dso__free_libdw(dso); } + mutex_unlock(dso__lock(dso)); out: if (!show_addr) return (show_sym && sym) ? @@ -305,7 +327,7 @@ char *__get_srcline(struct dso *dso, u64 addr, struct symbol *sym, char *get_srcline_split(struct dso *dso, u64 addr, unsigned *line) { char *file = NULL; - const char *dso_name; + char *dso_name; if (!dso__has_srcline(dso)) return NULL; @@ -314,19 +336,28 @@ char *get_srcline_split(struct dso *dso, u64 addr, unsigned *line) if (dso_name == NULL) goto out_err; - if (!addr2line(dso_name, addr, &file, line, dso, /*unwind_inlines=*/true, - /*node=*/NULL, /*sym=*/NULL)) + if (addr2line(dso_name, addr, &file, line, dso, /*unwind_inlines=*/true, + /*node=*/NULL, /*sym=*/NULL) <= 0) { + free(dso_name); goto out_err; + } + free(dso_name); + mutex_lock(dso__lock(dso)); dso__set_a2l_fails(dso, 0); + mutex_unlock(dso__lock(dso)); return file; out_err: + mutex_lock(dso__lock(dso)); dso__set_a2l_fails(dso, dso__a2l_fails(dso) + 1); if (dso__a2l_fails(dso) > A2L_FAIL_LIMIT) { dso__set_has_srcline(dso, false); dso__free_a2l(dso); + dso__free_a2l_libbfd(dso); + dso__free_libdw(dso); } + mutex_unlock(dso__lock(dso)); return NULL; } @@ -420,13 +451,19 @@ void srcline__tree_delete(struct rb_root_cached *tree) struct inline_node *dso__parse_addr_inlines(struct dso *dso, u64 addr, struct symbol *sym) { - const char *dso_name; + char *dso_name; + struct inline_node *node; + + if (!dso__has_srcline(dso)) + return NULL; dso_name = srcline_dso_name(dso); if (dso_name == NULL) return NULL; - return addr2inlines(dso_name, addr, dso, sym); + node = addr2inlines(dso_name, addr, dso, sym); + free(dso_name); + return node; } void inline_node__clear_frames(struct inline_node *node) diff --git a/tools/perf/util/symbol.c b/tools/perf/util/symbol.c index 3587ad243159..3a5488e74590 100644 --- a/tools/perf/util/symbol.c +++ b/tools/perf/util/symbol.c @@ -27,6 +27,7 @@ #include "dso.h" #include "util.h" // lsdir() #include "event.h" +#include "libbfd.h" #include "machine.h" #include "map.h" #include "symbol.h" @@ -300,6 +301,10 @@ void symbols__fixup_end(struct rb_root_cached *symbols, bool is_kallsyms) else prev->end = curr->start; + /* The next module can start within that page */ + if (prev->end > curr->start) + prev->end = curr->start; + pr_debug4("%s sym:%s end:%#" PRIx64 "\n", __func__, prev->name, prev->end); } @@ -1924,9 +1929,9 @@ int dso__load(struct dso *dso, struct map *map) if (nsexit) nsinfo__mountns_enter(dso__nsinfo(dso), &nsc); - if (bfdrc == 0) { - ret = 0; - break; + if (bfdrc > 0) { + ret = 1; + goto out_destroy; } if (!is_reg || sirc < 0) @@ -1991,6 +1996,7 @@ int dso__load(struct dso *dso, struct map *map) ret += nr_plt; } +out_destroy: for (; ss_pos > 0; ss_pos--) symsrc__destroy(&ss_[ss_pos - 1]); out_free: @@ -2707,13 +2713,24 @@ static bool want_demangle(bool is_kernel_sym) * version. */ #ifndef HAVE_CXA_DEMANGLE_SUPPORT +#ifdef HAVE_CPLUS_DEMANGLE_SUPPORT +/* + * Declarations from libiberty's demangle.h, the header isn't installed by + * every binutils package. + */ +#ifndef DMGL_PARAMS +#define DMGL_PARAMS (1 << 0) /* Include function arguments. */ +#define DMGL_ANSI (1 << 1) /* Include const, volatile, etc. */ +#endif + +char *cplus_demangle(const char *mangled, int options); +#endif + char *cxx_demangle_sym(const char *str __maybe_unused, bool params __maybe_unused, bool modifiers __maybe_unused) { #ifdef HAVE_LIBBFD_SUPPORT - int flags = (params ? DMGL_PARAMS : 0) | (modifiers ? DMGL_ANSI : 0); - - return bfd_demangle(NULL, str, flags); + return libbfd__demangle_sym(str, params, modifiers); #elif defined(HAVE_CPLUS_DEMANGLE_SUPPORT) int flags = (params ? DMGL_PARAMS : 0) | (modifiers ? DMGL_ANSI : 0); @@ -2749,17 +2766,16 @@ char *dso__demangle_sym(struct dso *dso, int kmodule, const char *elf_name) buf_len < 1024 * 1024; buf_len += 32) { char *tmp = realloc(demangled, buf_len); - if (!tmp) { - /* Failure to grow output buffer, return what is there. */ - return demangled; - } + if (!tmp) + break; demangled = tmp; if (rust_demangle_display_demangle(&rust_demangle, demangled, buf_len, /*alternate=*/true) == OverflowOk) return demangled; } - /* Buffer exceeded sensible bounds, return what is there. */ - return demangled; + /* Failure to grow output buffer or buffer exceeded sensible bounds. */ + free(demangled); + return NULL; } demangled = cxx_demangle_sym(elf_name, verbose > 0, verbose > 0); diff --git a/tools/perf/util/synthetic-events.c b/tools/perf/util/synthetic-events.c index 0c150193cca8..f5c90d4f4262 100644 --- a/tools/perf/util/synthetic-events.c +++ b/tools/perf/util/synthetic-events.c @@ -2776,6 +2776,8 @@ static union perf_event *__synthesize_schedstat_domain(struct io *io, __u16 vers size = sizeof(*ds); size = PERF_ALIGN(size, sizeof(u64)); event = zalloc(size); + if (!event) + return NULL; ds = &event->schedstat_domain; ds->header.type = PERF_RECORD_SCHEDSTAT_DOMAIN; @@ -2817,7 +2819,6 @@ int perf_event__synthesize_schedstat(const struct perf_tool *tool, struct perf_cpu_map *user_requested_cpus) { char *line = NULL, path[PATH_MAX]; - union perf_event *event = NULL; size_t line_len = 0; char bf[BUFSIZ]; __u64 timestamp; @@ -2858,6 +2859,7 @@ int perf_event__synthesize_schedstat(const struct perf_tool *tool, * for filtered out cpus. */ for (ch = io__get_char(&io); !io.eof; ch = io__get_char(&io)) { + union perf_event *event = NULL; struct perf_cpu this_cpu; if (ch == 'c') { @@ -2872,12 +2874,12 @@ int perf_event__synthesize_schedstat(const struct perf_tool *tool, this_cpu.cpu = cpu; - if (user_requested_cpus && !perf_cpu_map__has(user_requested_cpus, this_cpu)) - continue; - - if (process(tool, event, NULL, NULL) < 0) { - free(event); - goto out_free_line; + if (!user_requested_cpus || + perf_cpu_map__has(user_requested_cpus, this_cpu)) { + if (process(tool, event, NULL, NULL) < 0) { + free(event); + goto out_free_line; + } } free(event); diff --git a/tools/perf/util/thread.c b/tools/perf/util/thread.c index e483ffcb5d93..8b8ca94e89ea 100644 --- a/tools/perf/util/thread.c +++ b/tools/perf/util/thread.c @@ -531,12 +531,10 @@ uint16_t thread__e_machine_endian(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/perf/util/thread_map.c b/tools/perf/util/thread_map.c index 48c70f149e92..918ab3180232 100644 --- a/tools/perf/util/thread_map.c +++ b/tools/perf/util/thread_map.c @@ -395,3 +395,29 @@ int thread_map__remove(struct perf_thread_map *threads, int idx) threads->nr--; return 0; } + +/* The tgid of the thread at idx, read from /proc, or -1 if it has exited. */ +pid_t thread_map__tgid(struct perf_thread_map *threads, int idx) +{ + char path[128]; + char *buf, *p, *q; + pid_t tgid; + size_t len; + + snprintf(path, sizeof(path), "%d/status", perf_thread_map__pid(threads, idx)); + if (procfs__read_str(path, &buf, &len) < 0) + return -1; + + /* From a line start, as the Name: line before it can contain "Tgid:". */ + p = strstr(buf, "\nTgid:"); + if (p == NULL) { + free(buf); + return -1; + } + + tgid = strtol(p + 6, &q, 0); + if (*q != '\n') + tgid = -1; + free(buf); + return tgid; +} diff --git a/tools/perf/util/thread_map.h b/tools/perf/util/thread_map.h index fc16d87f32fb..d700a22b7ae4 100644 --- a/tools/perf/util/thread_map.h +++ b/tools/perf/util/thread_map.h @@ -24,4 +24,5 @@ size_t thread_map__fprintf(struct perf_thread_map *threads, FILE *fp); void thread_map__read_comms(struct perf_thread_map *threads); bool thread_map__has(struct perf_thread_map *threads, pid_t pid); int thread_map__remove(struct perf_thread_map *threads, int idx); +pid_t thread_map__tgid(struct perf_thread_map *threads, int idx); #endif /* __PERF_THREAD_MAP_H */ diff --git a/tools/perf/util/tp_pmu.c b/tools/perf/util/tp_pmu.c index c2be8c9f9084..5ac732e06841 100644 --- a/tools/perf/util/tp_pmu.c +++ b/tools/perf/util/tp_pmu.c @@ -151,7 +151,9 @@ static int for_each_event_cb(void *state, const char *sys_name, const char *evt_ static int for_each_event_sys_cb(void *state, const char *sys_name) { - return tp_pmu__for_each_tp_event(sys_name, state, for_each_event_cb); + int ret = tp_pmu__for_each_tp_event(sys_name, state, for_each_event_cb); + + return ret == -ENOENT ? 0 : ret; } int tp_pmu__for_each_event(struct perf_pmu *pmu, void *state, pmu_event_callback cb) @@ -176,7 +178,9 @@ static int num_events_cb(void *state, const char *sys_name __maybe_unused, static int num_events_sys_cb(void *state, const char *sys_name) { - return tp_pmu__for_each_tp_event(sys_name, state, num_events_cb); + int ret = tp_pmu__for_each_tp_event(sys_name, state, num_events_cb); + + return ret == -ENOENT ? 0 : ret; } size_t tp_pmu__num_events(struct perf_pmu *pmu __maybe_unused) diff --git a/tools/perf/util/unwind-libdw.c b/tools/perf/util/unwind-libdw.c index 63a5c2253174..f2f734cb3c81 100644 --- a/tools/perf/util/unwind-libdw.c +++ b/tools/perf/util/unwind-libdw.c @@ -42,8 +42,10 @@ static int __find_debuginfo(Dwfl_Module *mod __maybe_unused, void **userdata, const struct dso *dso = *userdata; assert(dso); + mutex_lock(dso__lock((struct dso *)dso)); if (dso__symsrc_filename(dso) && strcmp(file_name, dso__symsrc_filename(dso))) *debuginfo_file_name = strdup(dso__symsrc_filename(dso)); + mutex_unlock(dso__lock((struct dso *)dso)); return -1; } diff --git a/tools/perf/util/unwind-libunwind.c b/tools/perf/util/unwind-libunwind.c index 73d191ce51a5..6052383e862b 100644 --- a/tools/perf/util/unwind-libunwind.c +++ b/tools/perf/util/unwind-libunwind.c @@ -1,20 +1,28 @@ // SPDX-License-Identifier: GPL-2.0 +#include "unwind.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + #include "callchain.h" #include "debug.h" #include "dso.h" #include "env.h" +#include "libunwind-arch/libunwind-arch.h" #include "map.h" #include "perf_regs.h" #include "session.h" #include "symbol.h" #include "thread.h" -#include "unwind.h" -#include "libunwind-arch/libunwind-arch.h" -#include -#include -#include -#include -#include #define DW_EH_PE_FORMAT_MASK 0x0f /* format of the encoded value */ #define DW_EH_PE_APPL_MASK 0x70 /* how the value is to be applied */ @@ -293,10 +301,19 @@ static int read_unwind_spec_debug_frame(struct dso *dso, } if (ofs <= 0) { - fd = open(dso__symsrc_filename(dso), O_RDONLY); - if (fd >= 0) { - ofs = elf_section_offset(fd, ".debug_frame"); - close(fd); + char *alloc_name; + + mutex_lock(dso__lock(dso)); + alloc_name = dso__symsrc_filename(dso) ? + strdup(dso__symsrc_filename(dso)) : NULL; + mutex_unlock(dso__lock(dso)); + if (alloc_name) { + fd = open(alloc_name, O_RDONLY); + if (fd >= 0) { + ofs = elf_section_offset(fd, ".debug_frame"); + close(fd); + } + free(alloc_name); } } @@ -321,6 +338,7 @@ static int read_unwind_spec_debug_frame(struct dso *dso, } } if (ofs > 0) { + mutex_lock(dso__lock(dso)); if (dso__symsrc_filename(dso) != NULL) { pr_warning( "%s: overwrite symsrc(%s,%s)\n", @@ -330,6 +348,7 @@ static int read_unwind_spec_debug_frame(struct dso *dso, dso__free_symsrc_filename(dso); } dso__set_symsrc_filename(dso, debuglink); + mutex_unlock(dso__lock(dso)); } else { free(debuglink); } @@ -429,12 +448,23 @@ int __libunwind__find_proc_info(void *as, uint64_t ip, void *pi, int need_unwind dso__data_put_fd(dso); } - symfile = dso__symsrc_filename(dso) ?: dso__name(dso); - - if (libunwind_arch__dwarf_find_debug_frame(ui->e_machine, /*found=*/0, &di, ip, - base, symfile, start, map__end(map))) { - ret = libunwind_arch__dwarf_search_unwind_table(ui->e_machine, as, ip, &di, pi, - need_unwind_info, arg); + mutex_lock(dso__lock(dso)); + symfile = dso__symsrc_filename(dso) ? + strdup(dso__symsrc_filename(dso)) : + strdup(dso__name(dso)); + mutex_unlock(dso__lock(dso)); + + if (symfile) { + if (libunwind_arch__dwarf_find_debug_frame(ui->e_machine, + /*found=*/0, &di, ip, + base, symfile, start, + map__end(map))) { + ret = libunwind_arch__dwarf_search_unwind_table(ui->e_machine, as, + ip, &di, pi, + need_unwind_info, + arg); + } + free((char *)symfile); } } map__put(map); diff --git a/tools/power/x86/turbostat/turbostat.c b/tools/power/x86/turbostat/turbostat.c index cb3d571f121e..7e6e84d3d9c6 100644 --- a/tools/power/x86/turbostat/turbostat.c +++ b/tools/power/x86/turbostat/turbostat.c @@ -1995,15 +1995,17 @@ int pmt_telemdir_filter(const struct dirent *e) { unsigned int dummy; - return sscanf(e->d_name, "telem%u", &dummy); + return (sscanf(e->d_name, "telem%u", &dummy) == 1); } int pmt_telemdir_sort(const struct dirent **a, const struct dirent **b) { unsigned int aidx = 0, bidx = 0; - sscanf((*a)->d_name, "telem%u", &aidx); - sscanf((*b)->d_name, "telem%u", &bidx); + if (sscanf((*a)->d_name, "telem%u", &aidx) != 1) + aidx = 0; + if (sscanf((*b)->d_name, "telem%u", &bidx) != 1) + bidx = 0; return (aidx > bidx) ? 1 : (aidx < bidx) ? -1 : 0; } diff --git a/tools/power/x86/x86_energy_perf_policy/x86_energy_perf_policy.c b/tools/power/x86/x86_energy_perf_policy/x86_energy_perf_policy.c index 0dc959e30076..f45ca6e209fe 100644 --- a/tools/power/x86/x86_energy_perf_policy/x86_energy_perf_policy.c +++ b/tools/power/x86/x86_energy_perf_policy/x86_energy_perf_policy.c @@ -335,22 +335,22 @@ int parse_optarg_string(char *s) int i; char *endptr; - if (!strncmp(s, "default", 7)) + if (strcmp(s, "default") == 0) return OPTARG_NORMAL; - if (!strncmp(s, "normal", 6)) + if (strcmp(s, "normal") == 0) return OPTARG_NORMAL; - if (!strncmp(s, "power", 9)) + if (strcmp(s, "power") == 0) return OPTARG_POWER; - if (!strncmp(s, "balance-power", 17)) + if (strcmp(s, "balance-power") == 0) return OPTARG_BALANCE_POWER; - if (!strncmp(s, "balance-performance", 19)) + if (strcmp(s, "balance-performance") == 0) return OPTARG_BALANCE_PERFORMANCE; - if (!strncmp(s, "performance", 11)) + if (strcmp(s, "performance") == 0) return OPTARG_PERFORMANCE; i = strtol(s, &endptr, 0); @@ -783,7 +783,11 @@ void err_on_hypervisor(void) err(1, "Failed to find 'flags' in /proc/cpuinfo"); } rewind(cpuinfo); - fseek(cpuinfo, flags - buffer, SEEK_SET); + if (fseek(cpuinfo, flags - buffer, SEEK_SET) != 0) { + fclose(cpuinfo); + free(buffer); + err(1, "Failed to seek in /proc/cpuinfo"); + } if (!fgets(buffer, 4096, cpuinfo)) { fclose(cpuinfo); free(buffer); diff --git a/tools/sched_ext/include/scx/enum_defs.autogen.h b/tools/sched_ext/include/scx/enum_defs.autogen.h index 63b6b14b19bd..6cb26ad5033c 100644 --- a/tools/sched_ext/include/scx/enum_defs.autogen.h +++ b/tools/sched_ext/include/scx/enum_defs.autogen.h @@ -105,6 +105,7 @@ #define HAVE_SCX_TASK_SUB_INIT #define HAVE_SCX_TASK_IMMED #define HAVE_SCX_TASK_PROTECTED +#define HAVE_SCX_TASK_RUN_TRACKED #define HAVE_SCX_TASK_STATE_SHIFT #define HAVE_SCX_TASK_STATE_BITS #define HAVE_SCX_TASK_STATE_MASK diff --git a/tools/sched_ext/scx_flatcg.bpf.c b/tools/sched_ext/scx_flatcg.bpf.c index 454ebb820c5e..5e6abd0bccb3 100644 --- a/tools/sched_ext/scx_flatcg.bpf.c +++ b/tools/sched_ext/scx_flatcg.bpf.c @@ -144,7 +144,7 @@ static bool cgv_node_less(struct bpf_rb_node *a, const struct bpf_rb_node *b) cgc_a = container_of(a, struct cgv_node, rb_node); cgc_b = container_of(b, struct cgv_node, rb_node); - return cgc_a->cvtime < cgc_b->cvtime; + return time_before(cgc_a->cvtime, cgc_b->cvtime); } static struct fcg_cpu_ctx *find_cpu_ctx(void) diff --git a/tools/testing/cxl/test/cxl.c b/tools/testing/cxl/test/cxl.c index 62bd92b3be45..221be4addb0e 100644 --- a/tools/testing/cxl/test/cxl.c +++ b/tools/testing/cxl/test/cxl.c @@ -1945,7 +1945,7 @@ static int cxl_type2_mem_init(void) 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) @@ -1974,7 +1974,7 @@ static int cxl_type3_mem_init(void) 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) @@ -1991,7 +1991,7 @@ static int cxl_type3_mem_init(void) 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) @@ -2009,7 +2009,7 @@ static int cxl_type3_mem_init(void) 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/Makefile b/tools/testing/selftests/Makefile index bc4fdb6f5337..45ab2d8eacff 100644 --- a/tools/testing/selftests/Makefile +++ b/tools/testing/selftests/Makefile @@ -232,7 +232,7 @@ all: $(MAKE) OUTPUT=$$BUILD_TARGET -C $$TARGET \ O=$(abs_objtree) \ $(if $(FORCE_TARGETS),|| exit); \ - ret=$$((ret * $$?)); \ + [ $$? -eq 0 ] && ret=0; \ done; exit $$ret; run_tests: all @@ -299,7 +299,7 @@ ifdef INSTALL_PATH OBJ_PATH=$(INSTALL_PATH) \ O=$(abs_objtree) \ $(if $(FORCE_TARGETS),|| exit); \ - ret=$$((ret * $$?)); \ + [ $$? -eq 0 ] && ret=0; \ done; exit $$ret; diff --git a/tools/testing/selftests/alsa/mixer-test.c b/tools/testing/selftests/alsa/mixer-test.c index 0857d64c322a..01933ef9b349 100644 --- a/tools/testing/selftests/alsa/mixer-test.c +++ b/tools/testing/selftests/alsa/mixer-test.c @@ -261,6 +261,8 @@ static int wait_for_event(struct ctl_data *ctl, int timeout) if (ev_id != snd_ctl_elem_info_get_numid(ctl->info)) { ksft_print_msg("Event for unexpected ctl %s\n", snd_ctl_event_elem_get_name(event)); + /* The loop condition must not see the other control's mask */ + mask = 0; continue; } diff --git a/tools/testing/selftests/alsa/test-pcmtest-driver.c b/tools/testing/selftests/alsa/test-pcmtest-driver.c index 95065ef3b441..18ee72d5d4c9 100644 --- a/tools/testing/selftests/alsa/test-pcmtest-driver.c +++ b/tools/testing/selftests/alsa/test-pcmtest-driver.c @@ -10,9 +10,11 @@ #include "kselftest_harness.h" #define CH_NUM 4 +/* The driver accepts patterns of up to 4096 bytes */ +#define MAX_PATTERN_LEN 4096 struct pattern_buf { - char buf[1024]; + char buf[MAX_PATTERN_LEN]; int len; }; @@ -166,7 +168,7 @@ FIXTURE_SETUP(pcmtest) { TEST_F(pcmtest, playback) { snd_pcm_t *handle; unsigned char *it; - size_t write_res; + snd_pcm_sframes_t write_res; int test_results; int i, cur_ch, pos_in_ch; void *samples; @@ -190,7 +192,7 @@ TEST_F(pcmtest, playback) { it[i] = patterns[cur_ch].buf[pos_in_ch % patterns[cur_ch].len]; } write_res = snd_pcm_writei(handle, samples, params->rate * params->time); - ASSERT_GE(write_res, 0); + ASSERT_EQ(write_res, params->rate * params->time); snd_pcm_close(handle); free(samples); @@ -206,7 +208,7 @@ TEST_F(pcmtest, playback) { TEST_F(pcmtest, capture) { snd_pcm_t *handle; unsigned char *it; - size_t read_res; + snd_pcm_sframes_t read_res; int i, cur_ch, pos_in_ch; void *samples; struct pcmtest_test_params *params = &self->params; @@ -222,7 +224,7 @@ TEST_F(pcmtest, capture) { snd_pcm_format_set_silence(params->format, samples, params->rate * params->channels * params->time); read_res = snd_pcm_readi(handle, samples, params->rate * params->time); - ASSERT_GE(read_res, 0); + ASSERT_EQ(read_res, params->rate * params->time); snd_pcm_close(handle); it = (unsigned char *)samples; for (i = 0; i < self->params.sec_buf_len * self->params.time; i++) { @@ -239,7 +241,8 @@ TEST_F(pcmtest, ni_capture) { snd_pcm_t *handle; struct pcmtest_test_params params = self->params; char **chan_samples; - size_t i, j, read_res; + snd_pcm_sframes_t read_res; + size_t i, j; chan_samples = calloc(CH_NUM, sizeof(*chan_samples)); ASSERT_NE(chan_samples, NULL); @@ -257,12 +260,12 @@ TEST_F(pcmtest, ni_capture) { for (i = 0; i < 1; i++) { read_res = snd_pcm_readn(handle, (void **)chan_samples, params.rate * params.time); - ASSERT_GE(read_res, 0); + ASSERT_EQ(read_res, params.rate * params.time); } snd_pcm_close(handle); for (i = 0; i < CH_NUM; i++) { - for (j = 0; j < params.rate * params.time; j++) + for (j = 0; j < params.rate * params.time * params.sample_size; j++) ASSERT_EQ(chan_samples[i][j], patterns[i].buf[j % patterns[i].len]); free(chan_samples[i]); } @@ -273,7 +276,8 @@ TEST_F(pcmtest, ni_playback) { snd_pcm_t *handle; struct pcmtest_test_params params = self->params; char **chan_samples; - size_t i, j, read_res; + snd_pcm_sframes_t write_res; + size_t i, j; int test_res; chan_samples = calloc(CH_NUM, sizeof(*chan_samples)); @@ -294,8 +298,9 @@ TEST_F(pcmtest, ni_playback) { } for (i = 0; i < 1; i++) { - read_res = snd_pcm_writen(handle, (void **)chan_samples, params.rate * params.time); - ASSERT_GE(read_res, 0); + write_res = snd_pcm_writen(handle, (void **)chan_samples, + params.rate * params.time); + ASSERT_EQ(write_res, params.rate * params.time); } snd_pcm_close(handle); diff --git a/tools/testing/selftests/arm64/signal/Makefile b/tools/testing/selftests/arm64/signal/Makefile index 1381039fb36f..c4df4be41636 100644 --- a/tools/testing/selftests/arm64/signal/Makefile +++ b/tools/testing/selftests/arm64/signal/Makefile @@ -17,8 +17,8 @@ TEST_GEN_PROGS := $(notdir $(PROGS)) # the toplevel makefile include ../../lib.mk -$(TEST_GEN_PROGS): $(PROGS) - cp $(PROGS) $(OUTPUT)/ +$(TEST_GEN_PROGS): $(OUTPUT)/%: testcases/% + cp $< $@ # Common test-unit targets to build common-layout test-cases executables # Needs secondary expansion to properly include the testcase c-file in pre-reqs diff --git a/tools/testing/selftests/bpf/Makefile b/tools/testing/selftests/bpf/Makefile index 93c707116fad..81c5db5f57fb 100644 --- a/tools/testing/selftests/bpf/Makefile +++ b/tools/testing/selftests/bpf/Makefile @@ -118,7 +118,9 @@ TEST_GEN_PROGS += test_progs-cpuv4 TEST_INST_SUBDIRS += cpuv4 endif -TEST_FILES = xsk_prereqs.sh $(wildcard progs/btf_dump_test_case_*.c) +TEST_FILES = xsk_prereqs.sh $(wildcard progs/btf_dump_test_case_*.c) \ + bpftool_btf_dump_sorted.expected \ + bpftool_btf_dump_unsorted.expected # Order correspond to 'make run_tests' order TEST_PROGS := test_kmod.sh \ @@ -882,7 +884,9 @@ TRUNNER_EXTRA_FILES := $(OUTPUT)/urandom_read \ ima_setup.sh \ $(VERIFY_SIG_SETUP) \ $(wildcard progs/btf_dump_test_case_*.c) \ - $(wildcard progs/*.bpf.o) + $(wildcard progs/*.bpf.o) \ + bpftool_btf_dump_sorted.expected \ + bpftool_btf_dump_unsorted.expected TRUNNER_BPF_BUILD_RULE := CLANG_BPF_BUILD_RULE TRUNNER_BPF_CFLAGS := $(BPF_CFLAGS) $(CLANG_CFLAGS) -DENABLE_ATOMICS_TESTS $(eval $(call DEFINE_TEST_RUNNER,test_progs)) diff --git a/tools/testing/selftests/bpf/bpftool_btf_dump_sorted.expected b/tools/testing/selftests/bpf/bpftool_btf_dump_sorted.expected new file mode 100644 index 000000000000..5470b2b43229 --- /dev/null +++ b/tools/testing/selftests/bpf/bpftool_btf_dump_sorted.expected @@ -0,0 +1,48 @@ +#ifndef __VMLINUX_H__ +#define __VMLINUX_H__ + +#ifndef BPF_NO_PRESERVE_ACCESS_INDEX +#pragma clang attribute push (__attribute__((preserve_access_index)), apply_to = record) +#endif + +#ifndef __ksym +#define __ksym __attribute__((section(".ksyms"))) +#endif + +#ifndef __weak +#define __weak __attribute__((weak)) +#endif + +#ifndef __bpf_fastcall +#if __has_attribute(bpf_fastcall) +#define __bpf_fastcall __attribute__((bpf_fastcall)) +#else +#define __bpf_fastcall +#endif +#endif + +enum { + E0 = 1, +}; + +struct holey { + int c; + long: 32; + long: 32; + int tail; +}; + +struct s { + int f; +}; + + +/* BPF kfuncs */ +#ifndef BPF_NO_KFUNC_PROTOTYPES +#endif + +#ifndef BPF_NO_PRESERVE_ACCESS_INDEX +#pragma clang attribute pop +#endif + +#endif /* __VMLINUX_H__ */ diff --git a/tools/testing/selftests/bpf/bpftool_btf_dump_unsorted.expected b/tools/testing/selftests/bpf/bpftool_btf_dump_unsorted.expected new file mode 100644 index 000000000000..4310adc2ed51 --- /dev/null +++ b/tools/testing/selftests/bpf/bpftool_btf_dump_unsorted.expected @@ -0,0 +1,48 @@ +#ifndef __VMLINUX_H__ +#define __VMLINUX_H__ + +#ifndef BPF_NO_PRESERVE_ACCESS_INDEX +#pragma clang attribute push (__attribute__((preserve_access_index)), apply_to = record) +#endif + +#ifndef __ksym +#define __ksym __attribute__((section(".ksyms"))) +#endif + +#ifndef __weak +#define __weak __attribute__((weak)) +#endif + +#ifndef __bpf_fastcall +#if __has_attribute(bpf_fastcall) +#define __bpf_fastcall __attribute__((bpf_fastcall)) +#else +#define __bpf_fastcall +#endif +#endif + +struct holey { + int c; + long: 32; + long: 32; + int tail; +}; + +enum { + E0 = 1, +}; + +struct s { + int f; +}; + + +/* BPF kfuncs */ +#ifndef BPF_NO_KFUNC_PROTOTYPES +#endif + +#ifndef BPF_NO_PRESERVE_ACCESS_INDEX +#pragma clang attribute pop +#endif + +#endif /* __VMLINUX_H__ */ diff --git a/tools/testing/selftests/bpf/bpftool_helpers.c b/tools/testing/selftests/bpf/bpftool_helpers.c index 0a2a4f0a2794..c49fdd90eb03 100644 --- a/tools/testing/selftests/bpf/bpftool_helpers.c +++ b/tools/testing/selftests/bpf/bpftool_helpers.c @@ -53,6 +53,7 @@ static int run_command(char *args, char *output_buf, size_t output_max_len) static char bpftool_path[PATH_MAX] = {}; bool suppress_output = !(output_buf && output_max_len); char command[BPFTOOL_FULL_CMD_MAX_LEN]; + size_t n; FILE *f; int ret; @@ -68,8 +69,10 @@ static int run_command(char *args, char *output_buf, size_t output_max_len) if (!f) return 1; - if (!suppress_output) - fread(output_buf, 1, output_max_len, f); + if (!suppress_output) { + n = fread(output_buf, 1, output_max_len - 1, f); + output_buf[n] = '\0'; + } ret = pclose(f); return ret; diff --git a/tools/testing/selftests/bpf/network_helpers.c b/tools/testing/selftests/bpf/network_helpers.c index cdf2d7d3ab32..d27dc79475de 100644 --- a/tools/testing/selftests/bpf/network_helpers.c +++ b/tools/testing/selftests/bpf/network_helpers.c @@ -49,6 +49,8 @@ errno = __save; \ }) +#define CONNECT_MIN_TIMEOUT_MS 5000 + struct ipv4_packet pkt_v4 = { .eth.h_proto = __bpf_constant_htons(ETH_P_IP), .iph.ihl = 5, @@ -291,6 +293,37 @@ int client_socket(int family, int type, return -1; } +static int connect_with_timeout(int fd, const struct sockaddr_storage *addr, + socklen_t addrlen, int timeout_ms) +{ + int connect_timeout_ms = MAX(timeout_ms, CONNECT_MIN_TIMEOUT_MS); + + /* + * Override timeout configuration with a larger value for the + * connection + */ + if (settimeo(fd, connect_timeout_ms)) { + log_err("Failed to set connect timeout"); + return -1; + } + + if (connect(fd, (const struct sockaddr *)addr, addrlen)) { + log_err("Failed to connect"); + return -1; + } + + /* + * If the timeout configured by the test is different from the + * connect timeout, restore it + */ + if (timeout_ms != connect_timeout_ms && settimeo(fd, timeout_ms)) { + log_err("Failed to set timeout for connected socket"); + return -1; + } + + return 0; +} + int connect_to_addr(int type, const struct sockaddr_storage *addr, socklen_t addrlen, const struct network_helper_opts *opts) { @@ -305,8 +338,7 @@ int connect_to_addr(int type, const struct sockaddr_storage *addr, socklen_t add return -1; } - if (connect(fd, (const struct sockaddr *)addr, addrlen)) { - log_err("Failed to connect to server"); + if (connect_with_timeout(fd, addr, addrlen, opts->timeout_ms)) { save_errno_close(fd); return -1; } @@ -376,20 +408,12 @@ int connect_fd_to_fd(int client_fd, int server_fd, int timeout_ms) struct sockaddr_storage addr; socklen_t len = sizeof(addr); - if (settimeo(client_fd, timeout_ms)) - return -1; - if (getsockname(server_fd, (struct sockaddr *)&addr, &len)) { log_err("Failed to get server addr"); return -1; } - if (connect(client_fd, (const struct sockaddr *)&addr, len)) { - log_err("Failed to connect to server"); - return -1; - } - - return 0; + return connect_with_timeout(client_fd, &addr, len, timeout_ms); } int make_sockaddr(int family, const char *addr_str, __u16 port, diff --git a/tools/testing/selftests/bpf/prog_tests/bpftool_btf_dump.c b/tools/testing/selftests/bpf/prog_tests/bpftool_btf_dump.c new file mode 100644 index 000000000000..d5b25302b0c8 --- /dev/null +++ b/tools/testing/selftests/bpf/prog_tests/bpftool_btf_dump.c @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: GPL-2.0 +#include +#include +#include +#include +#include +#include "btf_helpers.h" +#include "testing_helpers.h" + +#define DUMP_BUF_SZ (16 * 1024) + +#define EXPECTED_SORTED "bpftool_btf_dump_sorted.expected" +#define EXPECTED_UNSORTED "bpftool_btf_dump_unsorted.expected" + +/* + * struct holey { + * int c; + * <64-bit hole> + * int tail; + * }; + * enum { E0 = 1 }; + * struct s { int f; }; + */ +static struct btf *mk_btf(void) +{ + struct btf *btf; + + btf = btf__new_empty(); + if (!ASSERT_OK_PTR(btf, "new_empty")) + return NULL; + + btf__add_int(btf, "int", 4, BTF_INT_SIGNED); + btf__add_int(btf, "long int", 4, BTF_INT_SIGNED); + + btf__add_struct(btf, "holey", 16); + btf__add_field(btf, "c", 1, 0, 0); + btf__add_field(btf, "tail", 1, 96, 0); + + btf__add_enum(btf, NULL, 4); + btf__add_enum_value(btf, "E0", 1); + + btf__add_struct(btf, "s", 4); + btf__add_field(btf, "f", 1, 0, 0); + + VALIDATE_RAW_BTF( + btf, + "[1] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED", + "[2] INT 'long int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED", + "[3] STRUCT 'holey' size=16 vlen=2\n" + "\t'c' type_id=1 bits_offset=0\n" + "\t'tail' type_id=1 bits_offset=96", + "[4] ENUM '(anon)' encoding=UNSIGNED size=4 vlen=1\n" + "\t'E0' val=1", + "[5] STRUCT 's' size=4 vlen=1\n" + "\t'f' type_id=1 bits_offset=0"); + + return btf; +} + +static int btf_to_tmpfile(const struct btf *btf, char *path) +{ + ssize_t written; + const void *raw; + __u32 sz; + int fd; + + raw = btf__raw_data(btf, &sz); + if (!ASSERT_OK_PTR(raw, "raw_data")) + return -1; + + snprintf(path, PATH_MAX, "/tmp/bpftool_btf_dump.XXXXXX"); + fd = mkstemp(path); + if (!ASSERT_OK_FD(fd, "mkstemp_btf")) + return -1; + + written = write(fd, raw, sz); + close(fd); + if (!ASSERT_EQ(written, sz, "write_btf")) { + unlink(path); + return -1; + } + + return 0; +} + +static char *dump_c(const char *btf_path, bool sorted) +{ + char args[MAX_BPFTOOL_CMD_LEN]; + char *buf; + int err; + + buf = malloc(DUMP_BUF_SZ); + if (!ASSERT_OK_PTR(buf, "alloc_dump")) + return NULL; + + snprintf(args, sizeof(args), "btf dump file %s format c%s", + btf_path, sorted ? "" : " unsorted"); + + err = get_bpftool_command_output(args, buf, DUMP_BUF_SZ); + if (!ASSERT_OK(err, "btf_dump_format_c")) { + free(buf); + return NULL; + } + + return buf; +} + +static char *read_expected(const char *path) +{ + char *buf = NULL; + size_t cap = 0; + FILE *f; + int err; + + f = fopen(path, "r"); + if (!f) { + err = errno; + PRINT_FAIL("can't open expected output '%s': errno %d\n", path, err); + return NULL; + } + + /* no NUL in a generated header, so this reads to the end */ + if (getdelim(&buf, &cap, '\0', f) < 0) { + err = errno; + PRINT_FAIL("can't read expected output '%s': errno %d\n", path, err); + free(buf); + buf = NULL; + } + + fclose(f); + return buf; +} + +static void test_dump(const char *btf_path, bool sorted) +{ + const char *exp_path; + char *dump, *exp; + int err; + + exp_path = sorted ? EXPECTED_SORTED : EXPECTED_UNSORTED; + + dump = dump_c(btf_path, sorted); + if (!dump) + return; + + exp = read_expected(exp_path); + if (!exp) + goto out_dump; + + err = compare_text_to_expected(dump, exp); + ASSERT_OK(err, sorted ? "cmp_sorted" : "cmp_unsorted"); + + free(exp); +out_dump: + free(dump); +} + +void test_bpftool_btf_dump(void) +{ + char path[PATH_MAX]; + struct btf *btf; + + btf = mk_btf(); + if (!btf) + return; + + if (btf_to_tmpfile(btf, path)) + goto out_btf; + + if (test__start_subtest("c_sorted")) + test_dump(path, true); + if (test__start_subtest("c_unsorted")) + test_dump(path, false); + + unlink(path); +out_btf: + btf__free(btf); +} diff --git a/tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c b/tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c index 3bd27d2ea668..cc6ab2c263da 100644 --- a/tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c +++ b/tools/testing/selftests/bpf/prog_tests/cgroup_hierarchical_stats.c @@ -110,7 +110,7 @@ static void cleanup_bpffs(void) ASSERT_OK(rmdir(BPFFS_ATTACH_COUNTERS), "rmdir "BPFFS_ATTACH_COUNTERS); /* Unmount bpffs, if it wasn't already mounted when we started */ - if (mounted_bpffs) + if (!mounted_bpffs) return; ASSERT_OK(umount(BPFFS_ROOT), "unmount bpffs"); @@ -151,7 +151,7 @@ static void cleanup_cgroups(void) /* Sets up cgroup hiearchary, returns 0 on success. */ static int setup_hierarchy(void) { - return setup_bpffs() || setup_cgroups(); + return setup_cgroups() || setup_bpffs(); } static void destroy_hierarchy(void) diff --git a/tools/testing/selftests/bpf/prog_tests/dmabuf_iter.c b/tools/testing/selftests/bpf/prog_tests/dmabuf_iter.c index fb2cea710db3..1a5dc1adae73 100644 --- a/tools/testing/selftests/bpf/prog_tests/dmabuf_iter.c +++ b/tools/testing/selftests/bpf/prog_tests/dmabuf_iter.c @@ -188,8 +188,9 @@ static void subtest_dmabuf_iter_check_default_iter(struct dmabuf_iter *skel) ASSERT_EQ(sscanf(line, "%ld", &bufinfo.size), 1, "read size"); } else if (f % FIELD_COUNT == NAME) { - ASSERT_EQ(sscanf(line, "%s", bufinfo.name), 1, - "read name"); + /* Keep an empty name for a buffer without one */ + if (sscanf(line, "%s", bufinfo.name) != 1) + bufinfo.name[0] = '\0'; } else if (f % FIELD_COUNT == EXPORTER) { ASSERT_EQ(sscanf(line, "%31s", bufinfo.exporter), 1, "read exporter"); diff --git a/tools/testing/selftests/bpf/prog_tests/empty_skb.c b/tools/testing/selftests/bpf/prog_tests/empty_skb.c index c9fcb70cbafb..a3938c16557b 100644 --- a/tools/testing/selftests/bpf/prog_tests/empty_skb.c +++ b/tools/testing/selftests/bpf/prog_tests/empty_skb.c @@ -24,7 +24,7 @@ void test_empty_skb(void) int *ifindex; int err; int ret; - int lwt_egress_ret; /* expected retval at lwt/egress */ + int lwt_ret; /* expected retval at lwt */ __be16 h_proto; bool success_on_tc; bool adjust_room; @@ -82,7 +82,7 @@ void test_empty_skb(void) .data_size_in = sizeof(eth_hlen), .ifindex = &veth_ifindex, .ret = -ERANGE, - .lwt_egress_ret = -ERANGE, + .lwt_ret = -ERANGE, .success_on_tc = true, }, { @@ -96,17 +96,23 @@ void test_empty_skb(void) .data_size_in = sizeof(eth_hlen), .ifindex = &ipip_ifindex, .ret = -ERANGE, - .lwt_egress_ret = -ERANGE, + .lwt_ret = -ERANGE, }, - /* ETH_HLEN+1-sized packet should be redirected. */ + /* ETH_HLEN+1-sized packet should be redirected at TC. + * At LWT, the Ethernet header is not part of the skb, and + * a 1-byte packet is too short for an Ethernet device. + */ { .msg = "veth ETH_HLEN+1 packet ingress", .data_in = eth_hlen_pp, .data_size_in = sizeof(eth_hlen_pp), .ifindex = &veth_ifindex, - .lwt_egress_ret = 1, /* veth_xmit NET_XMIT_DROP */ + /* lwt: skb->len=1, dropped by veth_xmit() at egress + * and by __dev_forward_skb2() at ingress. + */ + .lwt_ret = 1, /* NET_XMIT_DROP / NET_RX_DROP */ }, { .msg = "ipip ETH_HLEN+1 packet ingress", @@ -144,7 +150,6 @@ void test_empty_skb(void) eth_hlen.h_proto = tests[i].h_proto; bpf_object__for_each_program(prog, bpf_obj->obj) { - bool at_egress = strstr(bpf_program__name(prog), "egress") != NULL; bool at_tc = !strncmp(bpf_program__section_name(prog), "tc", 2); bool is_adjust_room = !strcmp(bpf_program__name(prog), "tc_adjust_room"); int expected_ret; @@ -153,7 +158,7 @@ void test_empty_skb(void) if (tests[i].adjust_room != is_adjust_room) continue; - expected_ret = at_egress && !at_tc ? tests[i].lwt_egress_ret : tests[i].ret; + expected_ret = at_tc ? tests[i].ret : tests[i].lwt_ret; tattr.data_in = tests[i].data_in; tattr.data_size_in = tests[i].data_size_in; diff --git a/tools/testing/selftests/bpf/prog_tests/flow_dissector.c b/tools/testing/selftests/bpf/prog_tests/flow_dissector.c index fb4892681464..f6fefb14cda3 100644 --- a/tools/testing/selftests/bpf/prog_tests/flow_dissector.c +++ b/tools/testing/selftests/bpf/prog_tests/flow_dissector.c @@ -706,7 +706,7 @@ void test_flow_dissector_skb_less_direct_attach(void) struct bpf_flow *skel; struct netns_obj *ns; - ns = netns_new("flow_dissector_skb_less_indirect_attach_ns", true); + ns = netns_new("flow_dissector_skb_less_direct_attach_ns", true); if (!ASSERT_OK_PTR(ns, "create and open netns")) return; diff --git a/tools/testing/selftests/bpf/prog_tests/global_data_init.c b/tools/testing/selftests/bpf/prog_tests/global_data_init.c index 5671c31085cd..7c539cbcf3a1 100644 --- a/tools/testing/selftests/bpf/prog_tests/global_data_init.c +++ b/tools/testing/selftests/bpf/prog_tests/global_data_init.c @@ -68,12 +68,9 @@ static void test_percpu_data_on_cpus(struct bpf_map *map, int map_fd, int prog_f { struct test_global_percpu_data__percpu *data = NULL; int i, err, key = 0, num_online, run = 0; - __u64 args[2] = {0x1234ULL, 0x5678ULL}; size_t data_sz; bool *online; LIBBPF_OPTS(bpf_test_run_opts, topts, - .ctx_in = args, - .ctx_size_in = sizeof(args), .flags = BPF_F_TEST_RUN_ON_CPU, ); @@ -81,7 +78,7 @@ static void test_percpu_data_on_cpus(struct bpf_map *map, int map_fd, int prog_f if (!ASSERT_OK(err, "parse_cpu_mask_file")) return; - data_sz = map ? bpf_map__value_size(map) : sizeof(*data); + data_sz = sizeof(*data); data = calloc(1, data_sz); if (!ASSERT_OK_PTR(data, "calloc percpu data")) goto out; @@ -109,7 +106,7 @@ static void test_percpu_data_on_cpus(struct bpf_map *map, int map_fd, int prog_f break; ASSERT_EQ(*runp, ++run, "run"); - ASSERT_EQ(data->cpu_id[0], i, "cpu_id"); + ASSERT_EQ(data->cpu_id, i, "cpu_id"); ASSERT_EQ(data->data, 1, "data"); ASSERT_TRUE(data->set, "set"); ASSERT_EQ(data->nums[6], 0xc0de, "nums[6]"); @@ -127,7 +124,6 @@ static void test_global_percpu_data_init(void) { struct test_global_percpu_data__percpu init_value = {}; struct test_global_percpu_data__percpu *init_data; - const __u32 desired_sz = sysconf(_SC_PAGE_SIZE); struct test_global_percpu_data *skel = NULL; size_t init_data_sz; struct bpf_map *map; @@ -163,9 +159,11 @@ static void test_global_percpu_data_init(void) if (!ASSERT_EQ(bpf_map__type(map), BPF_MAP_TYPE_PERCPU_ARRAY, "bpf_map__type")) goto out; + init_value.set = 1; init_value.data = 2; init_value.nums[6] = -1; init_value.struct_data.i = 2; + init_value.struct_data.set = 1; init_value.struct_data.nums[6] = -1; err = bpf_map__set_initial_value(map, &init_value, sizeof(init_value)); if (!ASSERT_OK(err, "bpf_map__set_initial_value")) @@ -177,35 +175,24 @@ static void test_global_percpu_data_init(void) ASSERT_EQ(init_data->data, init_value.data, "init_value data"); ASSERT_EQ(init_data->set, init_value.set, "init_value set"); + ASSERT_EQ(init_data->nums[6], init_value.nums[6], "init_value nums[6]"); ASSERT_EQ(init_data->struct_data.i, init_value.struct_data.i, "init_value struct_data.i"); + ASSERT_EQ(init_data->struct_data.set, init_value.struct_data.set, + "init_value struct_data.set"); ASSERT_EQ(init_data->struct_data.nums[6], init_value.struct_data.nums[6], "init_value struct_data.nums[6]"); ASSERT_EQ(init_data_sz, sizeof(init_value), "init_value size"); ASSERT_EQ((void *) init_data, (void *) skel->percpu, "skel->percpu eq init_data"); ASSERT_EQ(skel->percpu->data, init_value.data, "skel->percpu->data"); ASSERT_EQ(skel->percpu->set, init_value.set, "skel->percpu->set"); + ASSERT_EQ(skel->percpu->nums[6], init_value.nums[6], "skel->percpu->nums[6]"); ASSERT_EQ(skel->percpu->struct_data.i, init_value.struct_data.i, "skel->percpu->struct_data.i"); + ASSERT_EQ(skel->percpu->struct_data.set, init_value.struct_data.set, + "skel->percpu->struct_data.set"); ASSERT_EQ(skel->percpu->struct_data.nums[6], init_value.struct_data.nums[6], "skel->percpu->struct_data.nums[6]"); - ASSERT_GT(desired_sz, sizeof(init_value), "desired_sz"); - err = bpf_map__set_value_size(map, desired_sz); - if (!ASSERT_OK(err, "bpf_map__set_value_size")) - goto out; - if (!ASSERT_EQ(bpf_map__value_size(map), desired_sz, "percpu value size")) - goto out; - if (!ASSERT_NEQ(bpf_map__btf_value_type_id(map), 0, "percpu BTF value type")) - goto out; - - init_data = bpf_map__initial_value(map, &init_data_sz); - if (!ASSERT_OK_PTR(init_data, "resized bpf_map__initial_value")) - goto out; - if (!ASSERT_EQ(init_data_sz, desired_sz, "resized initial value size")) - goto out; - if (!ASSERT_EQ(init_data->data, init_value.data, "resized initial value data")) - goto out; - err = test_global_percpu_data__load(skel); if (!ASSERT_OK(err, "test_global_percpu_data__load")) goto out; @@ -236,6 +223,67 @@ static void test_global_percpu_data_lskel(void) test_global_percpu_data_lskel__destroy(lskel); } +#define PCPU_MIN_UNIT_SIZE (32 << 10) + +static void test_global_percpu_data_map_resize(void) +{ + const __u32 page_size = sysconf(_SC_PAGE_SIZE); + const __u32 pcpu_max_value_size = ALIGN(PCPU_MIN_UNIT_SIZE, page_size); + const __u32 desired_sz = page_size * 2; + struct test_global_percpu_data *skel; + const int arr_value = -1; + struct bpf_map *map; + int err, prog_fd; + size_t data_sz; + + skel = test_global_percpu_data__open(); + if (!ASSERT_OK_PTR(skel, "test_global_percpu_data__open")) + return; + + map = skel->maps.percpu_arr; + skel->percpu_arr->arr[0] = arr_value; + err = bpf_map__set_value_size(map, desired_sz); + if (!ASSERT_OK(err, "bpf_map__set_value_size")) + goto out; + if (!ASSERT_EQ(bpf_map__value_size(map), desired_sz, "bpf_map__value_size")) + goto out; + if (!ASSERT_NEQ(bpf_map__btf_value_type_id(map), 0, "bpf_map__btf_value_type_id")) + goto out; + + skel->percpu_arr = bpf_map__initial_value(map, &data_sz); + if (!ASSERT_EQ(data_sz, desired_sz, "data_sz")) + goto out; + if (!ASSERT_OK_PTR(skel->percpu_arr, "skel->percpu_arr")) + goto out; + if (!ASSERT_EQ(skel->percpu_arr->arr[0], arr_value, "arr[0]")) + goto out; + + err = test_global_percpu_data__load(skel); + if (bpf_map__value_size(map) > pcpu_max_value_size) { + if (ASSERT_EQ(err, -E2BIG, "test_global_percpu_data__load E2BIG")) + /* + * When the PAGE_SIZE is 64KiB, the new value size will + * be 128KiB. Creating a percpu_array map with the new + * value size will fail with -E2BIG due to percpu_array + * map value size limit 64KiB, which is calculated by + * PFN_ALIGN(32KiB). + * Let's skip the test for such case. + */ + test__skip(); + goto out; + } + if (!ASSERT_OK(err, "test_global_percpu_data__load")) + goto out; + + map = skel->maps.percpu; + prog_fd = bpf_program__fd(skel->progs.update_percpu_data); + test_percpu_data_on_cpus(map, bpf_map__fd(map), prog_fd, &skel->bss->run); + ASSERT_EQ(skel->bss->arr_sum, arr_value * skel->bss->run, "arr_sum"); + +out: + test_global_percpu_data__destroy(skel); +} + static int create_rdonly_percpu_array(void) { LIBBPF_OPTS(bpf_map_create_opts, map_opts, @@ -388,6 +436,8 @@ void test_global_percpu_data(void) test_global_percpu_data_init(); if (test__start_subtest("lskel")) test_global_percpu_data_lskel(); + if (test__start_subtest("map_resize")) + test_global_percpu_data_map_resize(); if (test__start_subtest("rdonly_direct_read")) test_global_percpu_data_rdonly_direct_read(); if (test__start_subtest("rdonly_direct_write")) diff --git a/tools/testing/selftests/bpf/prog_tests/lwt_ip_encap.c b/tools/testing/selftests/bpf/prog_tests/lwt_ip_encap.c index 39e8a3b8b6af..5c5560d45c5b 100644 --- a/tools/testing/selftests/bpf/prog_tests/lwt_ip_encap.c +++ b/tools/testing/selftests/bpf/prog_tests/lwt_ip_encap.c @@ -1,5 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only +#include #include +#include #include "network_helpers.h" #include "test_progs.h" @@ -141,6 +143,54 @@ static int set_bottom_addr(const char *ns1, const char *ns2, const char *ns3) return 1; } +/* + * A veth whose peer sits in another netns with the same ifindex gets its + * carrier-on handled as a non-urgent linkwatch event, i.e. up to 1s late. + * Until then IPv6 considers the link not ready (no ff00::/8 route, no + * link-local address) and silently drops neighbour solicitations, so wait + * for all links to be operationally up (IFF_RUNNING) before sending traffic. + */ +static int wait_for_oper_up(const char *ns, const char *dev) +{ + struct nstoken *nstoken; + struct ifreq ifr = {}; + int i, fd, ret = -1; + + nstoken = open_netns(ns); + if (!ASSERT_OK_PTR(nstoken, "open ns")) + return -1; + + fd = socket(AF_INET, SOCK_DGRAM, 0); + if (!ASSERT_OK_FD(fd, "socket")) + goto out; + + strncpy(ifr.ifr_name, dev, IFNAMSIZ - 1); + for (i = 0; i < 50; i++) { + if (!ASSERT_OK(ioctl(fd, SIOCGIFFLAGS, &ifr), "SIOCGIFFLAGS")) + break; + if (ifr.ifr_flags & IFF_RUNNING) { + ret = 0; + break; + } + usleep(100000); + } + close(fd); +out: + ASSERT_OK(ret, dev); + close_netns(nstoken); + return ret; +} + +static int wait_for_links(const char *ns1, const char *ns2, const char *ns3) +{ + if (wait_for_oper_up(ns1, "veth1") || wait_for_oper_up(ns1, "veth5") || + wait_for_oper_up(ns2, "veth2") || wait_for_oper_up(ns2, "veth3") || + wait_for_oper_up(ns2, "veth6") || wait_for_oper_up(ns2, "veth7") || + wait_for_oper_up(ns3, "veth4") || wait_for_oper_up(ns3, "veth8")) + return -1; + return 0; +} + static int configure_vrf(const char *ns1, const char *ns2) { if (!ns1 || !ns2) @@ -304,6 +354,9 @@ static int setup_network(char *ns1, char *ns2, char *ns3, const char *vrf) if (!ASSERT_OK(configure_ns3(ns3), "configure ns3 routes")) goto fail; + if (!ASSERT_OK(wait_for_links(ns1, ns2, ns3), "wait for links")) + goto fail; + /* Link bottom route to the GRE tunnels */ SYS(fail, "ip -n %s route add %s/32 dev veth5 via %s %s", ns1, IP4_ADDR_GRE, IP4_ADDR_6, vrf); diff --git a/tools/testing/selftests/bpf/prog_tests/missed.c b/tools/testing/selftests/bpf/prog_tests/missed.c index ed8857ae914a..b5fb0267e944 100644 --- a/tools/testing/selftests/bpf/prog_tests/missed.c +++ b/tools/testing/selftests/bpf/prog_tests/missed.c @@ -36,7 +36,7 @@ static void test_missed_perf_kprobe(void) ASSERT_EQ(info.type, BPF_LINK_TYPE_PERF_EVENT, "info.type"); ASSERT_EQ(info.perf_event.type, BPF_PERF_EVENT_KPROBE, "info.perf_event.type"); - ASSERT_EQ(info.perf_event.kprobe.missed, 1, "info.perf_event.kprobe.missed"); + ASSERT_GE(info.perf_event.kprobe.missed, 1, "info.perf_event.kprobe.missed"); cleanup: missed_kprobe__destroy(skel); @@ -120,9 +120,9 @@ static void test_missed_tp_recursion(void) ASSERT_EQ(topts.retval, 0, "test_run"); ASSERT_EQ(get_missed_count(bpf_program__fd(skel->progs.test1)), 0, "test1_recursion_misses"); - ASSERT_EQ(get_missed_count(bpf_program__fd(skel->progs.test2)), 1, "test2_recursion_misses"); - ASSERT_EQ(get_missed_count(bpf_program__fd(skel->progs.test3)), 1, "test3_recursion_misses"); - ASSERT_EQ(get_missed_count(bpf_program__fd(skel->progs.test4)), 1, "test4_recursion_misses"); + ASSERT_GE(get_missed_count(bpf_program__fd(skel->progs.test2)), 1, "test2_recursion_misses"); + ASSERT_GE(get_missed_count(bpf_program__fd(skel->progs.test3)), 1, "test3_recursion_misses"); + ASSERT_GE(get_missed_count(bpf_program__fd(skel->progs.test4)), 1, "test4_recursion_misses"); cleanup: missed_tp_recursion__destroy(skel); diff --git a/tools/testing/selftests/bpf/prog_tests/prog_tests_framework.c b/tools/testing/selftests/bpf/prog_tests/prog_tests_framework.c index 7607cfc2408c..274568abc052 100644 --- a/tools/testing/selftests/bpf/prog_tests/prog_tests_framework.c +++ b/tools/testing/selftests/bpf/prog_tests/prog_tests_framework.c @@ -13,6 +13,7 @@ static void clear_test_state(struct test_state *state) void test_prog_tests_framework(void) { struct test_state *state = env.test_state; + int subtest_cnt; /* in all the ASSERT calls below we need to return on the first * error due to the fact that we are cleaning the test state after @@ -30,25 +31,30 @@ void test_prog_tests_framework(void) return; clear_test_state(state); + subtest_cnt = 0; if (test__start_subtest("test_skip_subtest")) { test__skip(); test__end_subtest(); + subtest_cnt++; } if (test__start_subtest("test_skip_subtest")) { test__skip(); test__end_subtest(); + subtest_cnt++; } - if (!ASSERT_EQ(state->skip_cnt, 2, "skip_cnt_check")) + if (!ASSERT_EQ(state->skip_cnt, subtest_cnt, "skip_cnt_check")) return; if (!ASSERT_EQ(state->subtest_num, 3, "subtest_num_check")) return; clear_test_state(state); + subtest_cnt = 0; if (test__start_subtest("test_fail_subtest")) { test__fail(); test__end_subtest(); + subtest_cnt++; } - if (!ASSERT_EQ(state->error_cnt, 1, "error_cnt_check")) + if (!ASSERT_EQ(state->error_cnt, subtest_cnt, "error_cnt_check")) return; if (!ASSERT_EQ(state->subtest_num, 4, "subtest_num_check")) return; @@ -163,6 +169,12 @@ void test_prog_tests_framework_expected_msgs(void) for (i = 0; i < ARRAY_SIZE(cases); i++) { if (test__start_subtest(cases[i].name)) { + if (!env.subtest_state->stdout_saved) { + test__skip(); + test__end_subtest(); + continue; + } + error_cnt = env.subtest_state->error_cnt; msgs.patterns = cases[i].pats; msgs.cnt = 0; diff --git a/tools/testing/selftests/bpf/prog_tests/sockopt.c b/tools/testing/selftests/bpf/prog_tests/sockopt.c index 6c96f2d9fccf..7dfdc4c12dec 100644 --- a/tools/testing/selftests/bpf/prog_tests/sockopt.c +++ b/tools/testing/selftests/bpf/prog_tests/sockopt.c @@ -955,7 +955,7 @@ static struct sockopt_test { /* ==================== prog_type ==================== */ { - .descr = "can attach only BPF_CGROUP_SETSOCKOP", + .descr = "can attach only BPF_CGROUP_SETSOCKOPT", .insns = { /* return 1 */ BPF_MOV64_IMM(BPF_REG_0, 1), @@ -969,7 +969,7 @@ static struct sockopt_test { }, { - .descr = "can attach only BPF_CGROUP_GETSOCKOP", + .descr = "can attach only BPF_CGROUP_GETSOCKOPT", .insns = { /* return 1 */ BPF_MOV64_IMM(BPF_REG_0, 1), diff --git a/tools/testing/selftests/bpf/prog_tests/test_struct_ops_assoc.c b/tools/testing/selftests/bpf/prog_tests/test_struct_ops_assoc.c index 461ded722351..9b646d134a45 100644 --- a/tools/testing/selftests/bpf/prog_tests/test_struct_ops_assoc.c +++ b/tools/testing/selftests/bpf/prog_tests/test_struct_ops_assoc.c @@ -136,7 +136,8 @@ static void test_st_ops_assoc_in_timer(void) struct_ops_assoc_in_timer__destroy(skel); } -static void test_st_ops_assoc_in_timer_no_uref(void) +static void run_st_ops_assoc_in_timer_no_uref(int timer_ns, int wait_map_free, + int spin_loops) { struct struct_ops_assoc_in_timer *skel = NULL; struct bpf_link *link; @@ -148,7 +149,8 @@ static void test_st_ops_assoc_in_timer_no_uref(void) err = bpf_program__assoc_struct_ops(skel->progs.syscall_prog, skel->maps.st_ops_map, NULL); - ASSERT_OK(err, "bpf_program__assoc_struct_ops"); + if (!ASSERT_OK(err, "bpf_program__assoc_struct_ops")) + goto out; link = bpf_map__attach_struct_ops(skel->maps.st_ops_map); if (!ASSERT_OK_PTR(link, "bpf_map__attach_struct_ops")) @@ -157,12 +159,18 @@ static void test_st_ops_assoc_in_timer_no_uref(void) /* * Run .test_1 by calling kfunc bpf_kfunc_multi_st_ops_test_1_prog_arg() and checks * the return value. .test_1 will also schedule timer_cb that runs .test_1 again. - * timer_cb will run 500ms after syscall_prog runs, when the user space no longer - * holds a reference to st_ops_map. + * timer_cb will run timer_ns after syscall_prog runs and, with wait_map_free, every + * timer_ns after that until the map is freed. With 500ms, it first runs when the + * user space no longer holds a reference to st_ops_map. */ - skel->bss->timer_ns = 500000000; + skel->bss->timer_ns = timer_ns; + skel->bss->wait_map_free = wait_map_free; + skel->bss->spin_loops = spin_loops; err = bpf_prog_test_run_opts(bpf_program__fd(skel->progs.syscall_prog), NULL); - ASSERT_OK(err, "bpf_prog_test_run_opts"); + if (!ASSERT_OK(err, "bpf_prog_test_run_opts")) { + bpf_link__destroy(link); + goto out; + } /* Detach and close struct_ops map to cause it to be freed */ bpf_link__destroy(link); @@ -178,6 +186,21 @@ static void test_st_ops_assoc_in_timer_no_uref(void) struct_ops_assoc_in_timer__destroy(skel); } +static void test_st_ops_assoc_in_timer_no_uref(void) +{ + run_st_ops_assoc_in_timer_no_uref(500000000, 1, 0); +} + +/* + * Keep calling .test_1 through the association from the timer callback, and + * stay in it for a while each time, while the map is being freed. The map + * must not be freed under a running .test_1. + */ +static void test_st_ops_assoc_in_timer_free(void) +{ + run_st_ops_assoc_in_timer_no_uref(0, 1, 1 << 20); +} + void test_struct_ops_assoc(void) { if (test__start_subtest("st_ops_assoc")) @@ -188,4 +211,6 @@ void test_struct_ops_assoc(void) test_st_ops_assoc_in_timer(); if (test__start_subtest("st_ops_assoc_in_timer_no_uref")) test_st_ops_assoc_in_timer_no_uref(); + if (test__start_subtest("st_ops_assoc_in_timer_free")) + test_st_ops_assoc_in_timer_free(); } diff --git a/tools/testing/selftests/bpf/prog_tests/test_task_work.c b/tools/testing/selftests/bpf/prog_tests/test_task_work.c index 774b31a5f6ca..fe0cb1702eaa 100644 --- a/tools/testing/selftests/bpf/prog_tests/test_task_work.c +++ b/tools/testing/selftests/bpf/prog_tests/test_task_work.c @@ -85,7 +85,7 @@ static void task_work_run(const char *prog_name, const char *map_name) skel = task_work__open(); if (!ASSERT_OK_PTR(skel, "task_work__open")) - return; + goto cleanup; bpf_object__for_each_program(prog, skel->obj) { bpf_program__set_autoload(prog, false); diff --git a/tools/testing/selftests/bpf/prog_tests/test_tc_edt.c b/tools/testing/selftests/bpf/prog_tests/test_tc_edt.c index 462512fb191f..1391978a3e30 100644 --- a/tools/testing/selftests/bpf/prog_tests/test_tc_edt.c +++ b/tools/testing/selftests/bpf/prog_tests/test_tc_edt.c @@ -90,7 +90,7 @@ static void cleanup(void) remove_netns(SERVER_NS); } -static void run_test(void) +static void run_test(struct test_tc_edt *skel) { int server_fd, client_fd, err; double rate_mbps, rate_error; @@ -113,12 +113,19 @@ static void run_test(void) if (!ASSERT_OK_FD(client_fd, "connect client")) return; - ts_start = get_time_ns(); err = send_recv_data(server_fd, client_fd, TX_BYTES_COUNT); ts_end = get_time_ns(); close_netns(nstoken); ASSERT_OK(err, "send_recv_data"); + /* + * Start from the first packet with data rather than before + * send_recv_data(), which also sets up the sender. + */ + ts_start = skel->bss->tx_start_ns; + if (!ASSERT_GT(ts_start, 0, "tx_start_ns")) + return; + rate_mbps = TX_BYTES_COUNT / ((ts_end - ts_start) / 1000.0); rate_error = fabs((rate_mbps - TARGET_RATE_MBPS) * 100.0 / TARGET_RATE_MBPS); @@ -138,7 +145,7 @@ void test_tc_edt(void) if (!ASSERT_OK(setup(skel), "global setup")) return; - run_test(); + run_test(skel); cleanup(); test_tc_edt__destroy(skel); diff --git a/tools/testing/selftests/bpf/prog_tests/test_tunnel.c b/tools/testing/selftests/bpf/prog_tests/test_tunnel.c index eb9309931272..7b35bf949805 100644 --- a/tools/testing/selftests/bpf/prog_tests/test_tunnel.c +++ b/tools/testing/selftests/bpf/prog_tests/test_tunnel.c @@ -161,9 +161,9 @@ static int add_vxlan_tunnel(void) IP4_ADDR2_VETH1, MAC_VETH1); /* root namespace */ - SYS(fail, "ip link add dev %s type vxlan external gbp dstport 4789", - VXLAN_TUNL_DEV1); - SYS(fail, "ip link set dev %s address %s up", VXLAN_TUNL_DEV1, MAC_TUNL_DEV1); + SYS(fail, "ip link add dev %s address %s type vxlan external gbp dstport 4789", + VXLAN_TUNL_DEV1, MAC_TUNL_DEV1); + SYS(fail, "ip link set dev %s up", VXLAN_TUNL_DEV1); SYS(fail, "ip addr add dev %s %s/24", VXLAN_TUNL_DEV1, IP4_ADDR_TUNL_DEV1); SYS(fail, "ip neigh add %s lladdr %s dev %s", IP4_ADDR_TUNL_DEV0, MAC_TUNL_DEV0, VXLAN_TUNL_DEV1); @@ -198,11 +198,10 @@ static int add_ip6vxlan_tunnel(void) IP6VXLAN_TUNL_DEV0, MAC_TUNL_DEV0); /* root namespace */ - SYS(fail, "ip link add dev %s type vxlan external dstport 4789", - IP6VXLAN_TUNL_DEV1); - SYS(fail, "ip addr add dev %s %s/24", IP6VXLAN_TUNL_DEV1, IP4_ADDR_TUNL_DEV1); - SYS(fail, "ip link set dev %s address %s up", + SYS(fail, "ip link add dev %s address %s type vxlan external dstport 4789", IP6VXLAN_TUNL_DEV1, MAC_TUNL_DEV1); + SYS(fail, "ip addr add dev %s %s/24", IP6VXLAN_TUNL_DEV1, IP4_ADDR_TUNL_DEV1); + SYS(fail, "ip link set dev %s up", IP6VXLAN_TUNL_DEV1); return 0; fail: diff --git a/tools/testing/selftests/bpf/prog_tests/uprobe_multi_test.c b/tools/testing/selftests/bpf/prog_tests/uprobe_multi_test.c index f0baf5738b75..7fbcfddc3cc3 100644 --- a/tools/testing/selftests/bpf/prog_tests/uprobe_multi_test.c +++ b/tools/testing/selftests/bpf/prog_tests/uprobe_multi_test.c @@ -94,14 +94,14 @@ static int child_func(void *arg) /* wait for parent's kick */ err = read(child->go[0], &c, 1); if (err != 1) - exit(err); + _exit(err); uprobe_multi_func_1(); uprobe_multi_func_2(); uprobe_multi_func_3(); usdt_trigger(); - exit(errno); + _exit(errno); } static int spawn_child_flag(struct child *child, bool clone_vm) diff --git a/tools/testing/selftests/bpf/prog_tests/wq.c b/tools/testing/selftests/bpf/prog_tests/wq.c index 84831eecc935..97926e35aaf2 100644 --- a/tools/testing/selftests/bpf/prog_tests/wq.c +++ b/tools/testing/selftests/bpf/prog_tests/wq.c @@ -64,10 +64,9 @@ static void test_failure_map_no_btf(void) goto out; err = bpf_map__reuse_fd(skel->maps.array, map_fd); - if (!ASSERT_OK(err, "map reuse fd")) { - close(map_fd); + close(map_fd); + if (!ASSERT_OK(err, "map reuse fd")) goto out; - } insns = bpf_program__insns(skel->progs.test_map_no_btf); if (!ASSERT_OK_PTR(insns, "insns ptr")) diff --git a/tools/testing/selftests/bpf/progs/cpumask_success.c b/tools/testing/selftests/bpf/progs/cpumask_success.c index 36f77b9732d4..ddaba4318c57 100644 --- a/tools/testing/selftests/bpf/progs/cpumask_success.c +++ b/tools/testing/selftests/bpf/progs/cpumask_success.c @@ -460,6 +460,9 @@ int BPF_PROG(test_insert_leave, struct task_struct *task, u64 clone_flags) { struct bpf_cpumask *cpumask; + if (!is_test_task()) + return 0; + cpumask = create_cpumask(); if (!cpumask) return 0; @@ -476,6 +479,9 @@ int BPF_PROG(test_insert_remove_release, struct task_struct *task, u64 clone_fla struct bpf_cpumask *cpumask; struct __cpumask_map_value *v; + if (!is_test_task()) + return 0; + cpumask = create_cpumask(); if (!cpumask) return 0; diff --git a/tools/testing/selftests/bpf/progs/dynptr_fail.c b/tools/testing/selftests/bpf/progs/dynptr_fail.c index 1cd61d72c166..55c9a6be7fc5 100644 --- a/tools/testing/selftests/bpf/progs/dynptr_fail.c +++ b/tools/testing/selftests/bpf/progs/dynptr_fail.c @@ -125,9 +125,9 @@ static int missing_release_callback_fn(__u32 index, void *data) return 0; } -/* Any dynptr initialized within a callback must have bpf_dynptr_put called */ +/* A callback cannot return with the last dynptr for a referenced resource. */ SEC("?raw_tp") -__failure __msg("Unreleased reference id") +__failure __msg("cannot overwrite referenced dynptr") int ringbuf_missing_release_callback(void *ctx) { bpf_loop(10, missing_release_callback_fn, NULL, 0); diff --git a/tools/testing/selftests/bpf/progs/struct_ops_assoc_in_timer.c b/tools/testing/selftests/bpf/progs/struct_ops_assoc_in_timer.c index 0bed49e9f217..47a44c8e8b11 100644 --- a/tools/testing/selftests/bpf/progs/struct_ops_assoc_in_timer.c +++ b/tools/testing/selftests/bpf/progs/struct_ops_assoc_in_timer.c @@ -25,6 +25,13 @@ int test_err; int timer_ns; int timer_test_1_ret; int timer_cb_run; +int wait_map_free; +int spin_loops; + +static int spin(u32 i, void *ctx) +{ + return 0; +} __noinline static int timer_cb(void *map, int *key, struct bpf_timer *timer) { @@ -34,6 +41,12 @@ __noinline static int timer_cb(void *map, int *key, struct bpf_timer *timer) timer_test_1_ret = bpf_kfunc_multi_st_ops_test_1_assoc(&args); recur--; + /* Try again later until the map is freed */ + if (wait_map_free && timer_test_1_ret != -1) { + bpf_timer_start(timer, timer_ns, 0); + return 0; + } + timer_cb_run++; return 0; @@ -53,6 +66,9 @@ int BPF_PROG(test_1, struct st_ops_args *args) bpf_timer_init(timer, &array_map, 1); bpf_timer_set_callback(timer, timer_cb); bpf_timer_start(timer, timer_ns, 0); + } else if (spin_loops) { + /* Stay in the trampoline while the map may be freed */ + bpf_loop(spin_loops, spin, NULL, 0); } return MAP_MAGIC; diff --git a/tools/testing/selftests/bpf/progs/test_global_percpu_data.c b/tools/testing/selftests/bpf/progs/test_global_percpu_data.c index 5dc21b3b4cb5..2765cd46e9af 100644 --- a/tools/testing/selftests/bpf/progs/test_global_percpu_data.c +++ b/tools/testing/selftests/bpf/progs/test_global_percpu_data.c @@ -8,9 +8,12 @@ int loong SEC(".percpu.looooooooong"); int data3 SEC(".data.percpu"); int data2 SEC(".percpu.data"); +/* Used for testing bpf_map__set_value_size(). */ +int arr[1] SEC(".percpu.arr"); +int arr_sum; + int run; -/* cpu_id as array to verify map value resizing. */ -int cpu_id[1] SEC(".percpu"); +int cpu_id SEC(".percpu"); int data SEC(".percpu") = -1; int nums[7] SEC(".percpu"); bool set SEC(".percpu") = false; @@ -34,7 +37,8 @@ int update_percpu_data(void *ctx) data = 1; run++; set = true; - cpu_id[0] = bpf_get_smp_processor_id(); + cpu_id = bpf_get_smp_processor_id(); + arr_sum += arr[0]; return 0; } diff --git a/tools/testing/selftests/bpf/progs/test_tc_edt.c b/tools/testing/selftests/bpf/progs/test_tc_edt.c index 4f6f03122d61..69f4b16acbef 100644 --- a/tools/testing/selftests/bpf/progs/test_tc_edt.c +++ b/tools/testing/selftests/bpf/progs/test_tc_edt.c @@ -24,6 +24,7 @@ struct { } flow_map SEC(".maps"); __uint64_t target_rate; +__uint64_t tx_start_ns; static inline int throttle_flow(struct __sk_buff *skb) { @@ -62,7 +63,8 @@ static inline int throttle_flow(struct __sk_buff *skb) return TC_ACT_OK; } -static inline int handle_tcp(struct __sk_buff *skb, struct tcphdr *tcp) +static inline int handle_tcp(struct __sk_buff *skb, struct tcphdr *tcp, + uint32_t hdr_len) { void *data_end = (void *)(long)skb->data_end; @@ -70,8 +72,12 @@ static inline int handle_tcp(struct __sk_buff *skb, struct tcphdr *tcp) if ((void *)(tcp + 1) > data_end) return TC_ACT_SHOT; - if (tcp->source == bpf_htons(9000)) + if (tcp->source == bpf_htons(9000)) { + /* Note when the first packet with data goes out */ + if (!tx_start_ns && skb->len > hdr_len + tcp->doff * 4) + tx_start_ns = bpf_ktime_get_ns(); return throttle_flow(skb); + } return TC_ACT_OK; } @@ -94,7 +100,8 @@ static inline int handle_ipv4(struct __sk_buff *skb) return TC_ACT_SHOT; if (iph->protocol == IPPROTO_TCP) - return handle_tcp(skb, (struct tcphdr *)(((void *)iph) + ihl)); + return handle_tcp(skb, (struct tcphdr *)(((void *)iph) + ihl), + sizeof(struct ethhdr) + ihl); return TC_ACT_OK; } diff --git a/tools/testing/selftests/bpf/progs/test_tc_link.c b/tools/testing/selftests/bpf/progs/test_tc_link.c index 630f12e51b07..2a91793674dd 100644 --- a/tools/testing/selftests/bpf/progs/test_tc_link.c +++ b/tools/testing/selftests/bpf/progs/test_tc_link.c @@ -4,6 +4,8 @@ #include #include +#include +#include #include #include #include @@ -119,11 +121,19 @@ SEC("tc/egress") int tc8(struct __sk_buff *skb) { struct net_device *dev = BPF_CORE_READ((struct sk_buff *)skb, dev); + struct iphdr iph = {}; + if (skb->protocol != __bpf_constant_htons(ETH_P_IP)) + goto out; + if (bpf_skb_load_bytes(skb, sizeof(struct ethhdr), &iph, sizeof(iph))) + goto out; + if (iph.protocol != IPPROTO_ICMP) + goto out; seen_tc8 = true; mark = skb->mark; prio = skb->priority; headroom = BPF_CORE_READ(dev, needed_headroom); tailroom = BPF_CORE_READ(dev, needed_tailroom); +out: return TCX_PASS; } diff --git a/tools/testing/selftests/bpf/progs/verifier_jit_inline.c b/tools/testing/selftests/bpf/progs/verifier_jit_inline.c index 02e562f56f9d..5b92da2ab75c 100644 --- a/tools/testing/selftests/bpf/progs/verifier_jit_inline.c +++ b/tools/testing/selftests/bpf/progs/verifier_jit_inline.c @@ -11,7 +11,7 @@ __jited(" addq %gs:{{.*}}, %rax") __arch_arm64 __jited(" mrs x8, SP_EL0") __arch_riscv64 -__jited(" mv a5, tp") +__jited(" mv t6, tp") __arch_loongarch __jited(" move $a5, $tp") int inline_bpf_get_current_task(void) diff --git a/tools/testing/selftests/bpf/progs/verifier_ldsx.c b/tools/testing/selftests/bpf/progs/verifier_ldsx.c index 41340877dc9d..614f64d4534b 100644 --- a/tools/testing/selftests/bpf/progs/verifier_ldsx.c +++ b/tools/testing/selftests/bpf/progs/verifier_ldsx.c @@ -286,6 +286,19 @@ __jited("add x11, x0, x28") __jited("ldrsh x22, [x11, #0x18]") __jited("add x11, x0, x28") __jited("ldrsb x22, [x11, #0x20]") +__arch_riscv64 +__jited("add t2, t6, s7") +__jited("lw s3, 0x10(t2)") +__jited("add t2, t6, s7") +__jited("lh s3, 0x18(t2)") +__jited("add t2, t6, s7") +__jited("lb s3, 0x20(t2)") +__jited("add t2, a0, s7") +__jited("lw s4, 0x10(t2)") +__jited("add t2, a0, s7") +__jited("lh s4, 0x18(t2)") +__jited("add t2, a0, s7") +__jited("lb s4, 0x20(t2)") __naked void arena_ldsx_disasm(void *ctx) { asm volatile ( @@ -317,6 +330,7 @@ __description("Arena LDSX Exception") __success __retval(0) __arch_x86_64 __arch_arm64 +__arch_riscv64 __naked void arena_ldsx_exception(void *ctx) { asm volatile ( @@ -338,6 +352,7 @@ __description("Arena LDSX, S8") __success __retval(-1) __arch_x86_64 __arch_arm64 +__arch_riscv64 __naked void arena_ldsx_s8(void *ctx) { asm volatile ( @@ -369,6 +384,7 @@ __description("Arena LDSX, S16") __success __retval(-1) __arch_x86_64 __arch_arm64 +__arch_riscv64 __naked void arena_ldsx_s16(void *ctx) { asm volatile ( @@ -400,6 +416,7 @@ __description("Arena LDSX, S32") __success __retval(-1) __arch_x86_64 __arch_arm64 +__arch_riscv64 __naked void arena_ldsx_s32(void *ctx) { asm volatile ( diff --git a/tools/testing/selftests/bpf/progs/verifier_stack_arg.c b/tools/testing/selftests/bpf/progs/verifier_stack_arg.c index 7e0ce5db28a0..14152dae2a8f 100644 --- a/tools/testing/selftests/bpf/progs/verifier_stack_arg.c +++ b/tools/testing/selftests/bpf/progs/verifier_stack_arg.c @@ -116,8 +116,8 @@ SEC("tc") __description("stack_arg: pruning with different stack arg types") __failure __log_level(2) __flag(BPF_F_TEST_STATE_FREQ) -__msg("arg JOIN insn 9 -> 10 r1: fp0-8 + _ => fp0-8|fp0+0") -__msg("arg JOIN insn 9 -> 10 sa0: fp0-8 + _ => fp0-8|fp0+0") +__msg("arg JOIN insn 8 -> 10 r1: _ + fp0-8 => fp0-8|fp0+0") +__msg("arg JOIN insn 8 -> 10 sa0: _ + fp0-8 => fp0-8|fp0+0") __msg("R{{[0-9]}} invalid mem access 'scalar'") __naked void stack_arg_pruning_type_mismatch(void) { diff --git a/tools/testing/selftests/bpf/test_progs.c b/tools/testing/selftests/bpf/test_progs.c index 46eb201b96a3..168d84cf4eb7 100644 --- a/tools/testing/selftests/bpf/test_progs.c +++ b/tools/testing/selftests/bpf/test_progs.c @@ -2065,8 +2065,11 @@ int main(int argc, char **argv) libbpf_set_print(libbpf_print_fn); err = register_session_key((const char *)test_progs_verification_cert, test_progs_verification_cert_len); - if (err < 0) + if (err < 0) { + fprintf(stderr, "Failed to add libbpf_session_key to the session keyring: %s\n", + strerror(errno)); return err; + } traffic_monitor_set_print(traffic_monitor_print_fn); diff --git a/tools/testing/selftests/bpf/unpriv_helpers.c b/tools/testing/selftests/bpf/unpriv_helpers.c index f997d7ec8fd0..9dadcacaef0c 100644 --- a/tools/testing/selftests/bpf/unpriv_helpers.c +++ b/tools/testing/selftests/bpf/unpriv_helpers.c @@ -72,8 +72,8 @@ static int config_contains(const char *pat) static bool cmdline_contains(const char *pat) { + int fd, cnt, ret = false; char cmdline[4096], *c; - int fd, ret = false; fd = open("/proc/cmdline", O_RDONLY); if (fd < 0) { @@ -81,14 +81,15 @@ static bool cmdline_contains(const char *pat) return false; } - if (read(fd, cmdline, sizeof(cmdline) - 1) < 0) { + cnt = read(fd, cmdline, sizeof(cmdline) - 1); + if (cnt < 0) { perror("read /proc/cmdline"); goto out; } - cmdline[sizeof(cmdline) - 1] = '\0'; + cmdline[cnt] = '\0'; for (c = strtok(cmdline, " \n"); c; c = strtok(NULL, " \n")) { - if (strncmp(c, pat, strlen(c))) + if (strcmp(c, pat)) continue; ret = true; break; diff --git a/tools/testing/selftests/cgroup/test_cpuset_prs.sh b/tools/testing/selftests/cgroup/test_cpuset_prs.sh index f7cc9da57b55..78ed0500e11d 100755 --- a/tools/testing/selftests/cgroup/test_cpuset_prs.sh +++ b/tools/testing/selftests/cgroup/test_cpuset_prs.sh @@ -278,6 +278,7 @@ TEST_MATRIX=( " C0-3 C1-3 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 X1-3 X2-3 . . P2 . . 0 A1:4|A2:1-3|A3:1-3 A2:P2 1-3" " C4:X0-3 X1-3 X2-3 . . . P2 . 0 A1:4|A2:4|A3:2-3 A3:P2 2-3" + " CX1-6 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 C1-3 C2-3 C4-5 X2-3 X2-3:P1 P2 P1 0 A1:0-1|A2:|A3:2-3|B1:4-5 \ @@ -288,16 +289,19 @@ TEST_MATRIX=( A1:P0|A2:P1|A3:P0|B1:P1" " C0-3 C1-3 C3 C4 X2-3 X2-3:P1 P2 P1 0 A1:0-1|A2:2|A3:3|B1:4 \ A1:P0|A2:P1|A3:P2|B1:P1 2-4|3" - " C0-4 C1-4 C2-4 . X2-4 X2-4:P2 X4:P1 . 0 A1:0-1|A2:2-3|A3:4 \ - A1:P0|A2:P2|A3:P1 2-4|2-3" - " C0-4 C1-4 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 C1-4:X2-4:P2 C2-4:X4:P1 \ - . . X5 . . 0 A1:0-4|A2:1-4|A3:2-4 \ - A1:P0|A2:P-2|A3:P-1 ." - " C0-4:X2-4 C1-4:X2-4: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" + " C1-6:P1 C3-6:P1 C5-6:P1 . . P2 . . 0 A1:1-2|A2:3-6|A3:5-6 \ + A1:P1|A2:P2|A3:P-1 3-6" + " C1-6:P2 C3-6:P2 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 C2-4:X3-4:P1 C3-4:X4:P2 \ + . . X5 . . 0 A1:1-4|A2:2-4|A3:3-4 \ + A1:P0|A2:P-1|A3:P-2 ." + " C1-5:X3-5:P2 C3-5:X4-5:P2 C4-5:X5:P2 \ + . X1-4 . . . 0 A1:1-3|A2:4|A3:4 \ + A1:P2|A2:P2|A3:P-2 1-4" + " C1-4:X2-4 C1-4:X3-4:P1 C3-4:X4:P2 \ + . . . X1 . 0 A1:1-2|A2:3-4|A3:3-4 \ + A1:P0|A2:P1|A3:P-2 ." " CX1-3:P1 CX1-3 CX1-3 . . . P1 . 0 A1:1-3|A2:1-3|A3:1-3 \ A1:P1|A2:P0|A3:P-1" @@ -331,8 +335,8 @@ TEST_MATRIX=( " C0-3:X1-3:P2 C1-3:X2-3:P2 C2-3:X3:P2 \ . . C4:X . . 0 A1:1-3|A2:1-3|A3:2-3|XA2:|XA3: A1:P2|A2:P-2|A3:P-2 1-3" # Local partition CPU change tests - " C0-5:P2 C4-5:P1 . . . C3-5 . . 0 A1:0-2|A2:3-5 A1:P2|A2:P1 0-2" - " C0-5:P2 C4-5:P1 . . C1-5 . . . 0 A1:1-3|A2:4-5 A1:P2|A2:P1 1-3" + " C0-5:P1 C4-5:P2 . . . C3-5 . . 0 A1:0-2|A2:3-5 A1:P1|A2:P2 3-5" + " C0-5:P1 C4-5:P2 . . C1-5 . . . 0 A1:1-3|A2:4-5 A1:P1|A2:P2 4-5" # cpus_allowed/exclusive_cpus update tests " C0-3:X2-3 C1-3:X2-3 C2-3:X2-3 \ @@ -360,6 +364,10 @@ TEST_MATRIX=( # cpuset.cpus is allowed, but those extra CPUs are ignored. " C2-3:P1 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 CX3-4:P1 . . X1-2 . . . 0 A1:1-2|A2:1-2|XA2: A1:P1|A2:P-1" + " CX1-4:P1 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 C3:P1 . . T C2-3 . . 0 A1:2-3|A2:2-3 A1:P1|A2:P-1" @@ -433,6 +441,28 @@ TEST_MATRIX=( # cpuset.cpus can become empty with task in it as it inherits parent's effective CPUs " C1-3 C2 . . . T:C . . 0 A1:1-3|A2:1-3" + # Creation of root partition under an isolated partition is not allowed + " C1-3:P2 C2 . . . P1 . . 0 A1:1-3|A2:2 A1:P2|A2:P-1 1-3" + " C1-3:P2 C2 . . . P2 . . 0 A1:1,3|A2:2 A1:P2|A2:P2 1-3" + " C1-3:P2 C2:P2 . . . P1 . . 0 A1:1-3|A2:2 A1:P2|A2:P-1 1-3" + " C1-3:P2 C2:P1 . . . C2-3 . . 0 A1:1-3|A2:2-3 A1:P2|A2:P-1 1-3" + + # 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 CX2-4:P2 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 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 C3-4:P2 . . T:C4-6 . . . 0 A1:5-6|A2:4 A1:P1|A2:P2 4" + " C1-4:P1 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/cgroup/test_zswap.c b/tools/testing/selftests/cgroup/test_zswap.c index 8df54b59513a..5c4f785e81e4 100644 --- a/tools/testing/selftests/cgroup/test_zswap.c +++ b/tools/testing/selftests/cgroup/test_zswap.c @@ -346,7 +346,16 @@ static int attempt_writeback(const char *cgroup, void *arg) * it can't writeback to swap. */ ret = cg_write_numeric(cgroup, "memory.reclaim", memsize); - if (!wb_enabled) + + /* + * When writeback is enabled, memory.reclaim may still fail to reclaim + * the requested amount of memory due to a slow swap device. + * Ignore -EAGAIN here. The caller determines pass/fail based on the + * zswap writeback counter. + */ + if (wb_enabled && ret == -EAGAIN) + ret = 0; + else if (!wb_enabled) ret = (ret == -EAGAIN) ? 0 : -1; out: @@ -652,11 +661,14 @@ static int test_no_kmem_bypass(const char *root) break; /* If memory was pushed to zswap, verify it belongs to memcg */ if (stored_pages > stored_pages_threshold) { - int zswapped = cg_read_key_long(test_group, "memory.stat", "zswapped "); - int delta = stored_pages * page_size - zswapped; - int result_ok = delta < stored_pages * page_size / 4; - - ret = result_ok ? KSFT_PASS : KSFT_FAIL; + long zswapped = cg_read_key_long( + test_group, "memory.stat", "zswapped "); + long long delta = + (long long)stored_pages * page_size - zswapped; + long long max_delta = + (long long)stored_pages * page_size / 4; + + ret = (delta < max_delta) ? KSFT_PASS : KSFT_FAIL; break; } } diff --git a/tools/testing/selftests/clone3/clone3_clear_sighand.c b/tools/testing/selftests/clone3/clone3_clear_sighand.c index de0c9d62015d..0ad62b80ada2 100644 --- a/tools/testing/selftests/clone3/clone3_clear_sighand.c +++ b/tools/testing/selftests/clone3/clone3_clear_sighand.c @@ -50,12 +50,12 @@ static void test_clone3_clear_sighand(void) * Check that CLONE_CLEAR_SIGHAND and CLONE_SIGHAND are mutually * exclusive. */ - args.flags |= CLONE_CLEAR_SIGHAND | CLONE_SIGHAND; + args.flags |= CLONE_VM | CLONE_CLEAR_SIGHAND | CLONE_SIGHAND; args.exit_signal = SIGCHLD; pid = sys_clone3(&args, sizeof(args)); - if (pid > 0) + if (pid != -1 || errno != EINVAL) ksft_exit_fail_msg( - "clone3(CLONE_CLEAR_SIGHAND | CLONE_SIGHAND) succeeded\n"); + "clone3(CLONE_CLEAR_SIGHAND | CLONE_SIGHAND) did not fail with EINVAL\n"); act.sa_handler = nop_handler; ret = sigemptyset(&act.sa_mask); diff --git a/tools/testing/selftests/coredump/coredump_test_helpers.c b/tools/testing/selftests/coredump/coredump_test_helpers.c index 2a20faf9cb0a..524fa5370593 100644 --- a/tools/testing/selftests/coredump/coredump_test_helpers.c +++ b/tools/testing/selftests/coredump/coredump_test_helpers.c @@ -235,10 +235,10 @@ bool read_coredump_req(int fd, struct coredump_req *req) fprintf(stderr, "Read coredump request with size %u and mask 0x%llx\n", req->size, (unsigned long long)req->mask); - if (user_size > kernel_size) - remaining_size = user_size - kernel_size; - else + if (kernel_size > user_size) remaining_size = kernel_size - user_size; + else + remaining_size = 0; if (PAGE_SIZE <= remaining_size) return false; @@ -250,7 +250,7 @@ bool read_coredump_req(int fd, struct coredump_req *req) if (remaining_size) { char buffer[PAGE_SIZE]; - ret = recv(fd, buffer, sizeof(buffer), MSG_WAITALL); + ret = recv(fd, buffer, remaining_size, MSG_WAITALL); if (ret != remaining_size) return false; fprintf(stderr, "Discarded %zu bytes of data after coredump request\n", remaining_size); diff --git a/tools/testing/selftests/damon/sysfs_no_op_commit_break.py b/tools/testing/selftests/damon/sysfs_no_op_commit_break.py index 2c65cffe6b54..81774ddc55ac 100755 --- a/tools/testing/selftests/damon/sysfs_no_op_commit_break.py +++ b/tools/testing/selftests/damon/sysfs_no_op_commit_break.py @@ -47,26 +47,27 @@ def main(): print('kdamond start failed: %s' % err) exit(1) - before_commit_status, err = \ - dump_damon_status_dict(kdamonds.kdamonds[0].pid) - if err is not None: - print('before-commit status dump failed: %s' % err) - exit(1) + try: + before_commit_status, err = \ + dump_damon_status_dict(kdamonds.kdamonds[0].pid) + if err is not None: + print('before-commit status dump failed: %s' % err) + exit(1) - kdamonds.kdamonds[0].commit() + kdamonds.kdamonds[0].commit() - after_commit_status, err = \ - dump_damon_status_dict(kdamonds.kdamonds[0].pid) - if err is not None: - print('after-commit status dump failed: %s' % err) - exit(1) - - if before_commit_status != after_commit_status: - print(f'before: {json.dumps(before_commit_status, indent=2)}') - print(f'after: {json.dumps(after_commit_status, indent=2)}') - exit(1) + after_commit_status, err = \ + dump_damon_status_dict(kdamonds.kdamonds[0].pid) + if err is not None: + print('after-commit status dump failed: %s' % err) + exit(1) - kdamonds.stop() + if before_commit_status != after_commit_status: + print(f'before: {json.dumps(before_commit_status, indent=2)}') + print(f'after: {json.dumps(after_commit_status, indent=2)}') + exit(1) + finally: + kdamonds.stop() if __name__ == '__main__': main() diff --git a/tools/testing/selftests/drivers/net/psp.py b/tools/testing/selftests/drivers/net/psp.py index a5b1e14f120f..b29d8b58275c 100755 --- a/tools/testing/selftests/drivers/net/psp.py +++ b/tools/testing/selftests/drivers/net/psp.py @@ -11,6 +11,8 @@ import struct import termios import time +from contextlib import contextmanager + from lib.py import defer from lib.py import ksft_run, ksft_exit, ksft_pr from lib.py import ksft_true, ksft_eq, ksft_ne, ksft_gt, ksft_raises @@ -58,6 +60,17 @@ def _make_psp_conn(cfg, version=0, ipver=None): return s +@contextmanager +def _make_lo_conn(): + # After tx-assoc, the client's egress is dropped, since lo has no + # psp_dev, so its FIN never reaches the server. Closing the server + # resets the unaccepted child, and the client accepts the cleartext + # RST because it hasn't received any PSP traffic yet. + with socket.create_server(("localhost", 0)) as srv, \ + socket.create_connection(srv.getsockname()[:2]) as s: + yield s + + def _close_conn(cfg, s): _send_with_ack(cfg, b'data close\0') s.close() @@ -200,20 +213,18 @@ def dev_rotate_spi(cfg): _init_psp_dev(cfg) top_a = top_b = 0 - with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s: + with _make_lo_conn() as s: assoc_a = cfg.pspnl.rx_assoc({"version": 0, "dev-id": cfg.psp_dev_id, "sock-fd": s.fileno()}) top_a = assoc_a['rx-key']['spi'] >> 31 - s.close() rot = cfg.pspnl.key_rotate({"id": cfg.psp_dev_id}) - with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s: + with _make_lo_conn() as s: ksft_eq(rot['id'], cfg.psp_dev_id) assoc_b = cfg.pspnl.rx_assoc({"version": 0, "dev-id": cfg.psp_dev_id, "sock-fd": s.fileno()}) top_b = assoc_b['rx-key']['spi'] >> 31 - s.close() ksft_ne(top_a, top_b) @@ -221,7 +232,7 @@ def assoc_basic(cfg): """ Test creating associations """ _init_psp_dev(cfg) - with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s: + with _make_lo_conn() as s: assoc = cfg.pspnl.rx_assoc({"version": 0, "dev-id": cfg.psp_dev_id, "sock-fd": s.fileno()}) @@ -234,7 +245,6 @@ def assoc_basic(cfg): "tx-key": assoc['rx-key'], "sock-fd": s.fileno()}) ksft_eq(len(assoc), 0) - s.close() def assoc_bad_dev(cfg): @@ -309,6 +319,32 @@ def assoc_sk_only_unconn(cfg): ksft_eq(the_exception.nl_msg.error, -errno.EINVAL) +def assoc_rx_unconnected(cfg): + """ Test that an Rx assoc is rejected on an unconnected socket """ + _init_psp_dev(cfg) + + with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s: + with ksft_raises(NlError) as cm: + cfg.pspnl.rx_assoc({"version": 0, + "dev-id": cfg.psp_dev_id, + "sock-fd": s.fileno()}) + ksft_eq(cm.exception.nl_msg.error, -errno.ENOTCONN) + ksft_eq(cm.exception.nl_msg.extack['bad-attr'], ".sock-fd") + + +def assoc_rx_listener(cfg): + """ Test that an Rx assoc is rejected on a listening socket """ + _init_psp_dev(cfg) + + with socket.create_server(("localhost", 0)) as s: + with ksft_raises(NlError) as cm: + cfg.pspnl.rx_assoc({"version": 0, + "dev-id": cfg.psp_dev_id, + "sock-fd": s.fileno()}) + ksft_eq(cm.exception.nl_msg.error, -errno.ENOTCONN) + ksft_eq(cm.exception.nl_msg.extack['bad-attr'], ".sock-fd") + + def assoc_version_mismatch(cfg): """ Test creating associations where Rx and Tx PSP versions do not match """ _init_psp_dev(cfg) @@ -320,7 +356,7 @@ def assoc_version_mismatch(cfg): # Translate versions to integers versions = [cfg.pspnl.consts["version"].entries[v].value for v in versions] - with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s: + with _make_lo_conn() as s: rx = cfg.pspnl.rx_assoc({"version": versions[0], "dev-id": cfg.psp_dev_id, "sock-fd": s.fileno()}) @@ -393,7 +429,7 @@ def assoc_twice(cfg): return assoc - with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s: + with _make_lo_conn() as s: assoc = rx_assoc_check(s) tx = cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id, "version": 0, @@ -402,7 +438,7 @@ def assoc_twice(cfg): ksft_eq(len(tx), 0) # Use the same Tx assoc second time - with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s2: + with _make_lo_conn() as s2: rx_assoc_check(s2) tx = cfg.pspnl.tx_assoc({"dev-id": cfg.psp_dev_id, "version": 0, @@ -410,8 +446,6 @@ def assoc_twice(cfg): "sock-fd": s2.fileno()}) ksft_eq(len(tx), 0) - s.close() - def _data_basic_send(cfg, version, ipver): """ Test basic data send """ diff --git a/tools/testing/selftests/exec/Makefile b/tools/testing/selftests/exec/Makefile index b640af8f02b5..bb10d9523e7f 100644 --- a/tools/testing/selftests/exec/Makefile +++ b/tools/testing/selftests/exec/Makefile @@ -63,7 +63,7 @@ TEST_GEN_FILES += bpf_interp.bpf.o nix_origin.bpf.o transparent.bpf.o TEST_GEN_FILES += loader.bpf.o interp_bind.bpf.o TEST_GEN_FILES += binfmt_bpf_interp binfmt_bpf_app binfmt_bind_interp else -$(info exec selftests: skipping binfmt_misc_bpf, needs clang, bpftool, vmlinux BTF and libbpf) +$(warning exec selftests: skipping binfmt_misc_bpf, needs clang, bpftool, vmlinux BTF and libbpf) endif EXTRA_CLEAN := $(OUTPUT)/subdir.moved $(OUTPUT)/execveat.moved $(OUTPUT)/xxxxx* \ diff --git a/tools/testing/selftests/filelock/ofdlocks.c b/tools/testing/selftests/filelock/ofdlocks.c index 68bac28b234b..0ab484cb075b 100644 --- a/tools/testing/selftests/filelock/ofdlocks.c +++ b/tools/testing/selftests/filelock/ofdlocks.c @@ -40,7 +40,7 @@ int main(void) int fd2 = open("/tmp/aa", O_RDONLY); ksft_print_header(); - ksft_set_plan(4); + ksft_set_plan(5); unlink("/tmp/aa"); assert(fd != -1); diff --git a/tools/testing/selftests/filesystems/epoll/epoll_wakeup_test.c b/tools/testing/selftests/filesystems/epoll/epoll_wakeup_test.c index 81a994943e12..b4dcbcd79773 100644 --- a/tools/testing/selftests/filesystems/epoll/epoll_wakeup_test.c +++ b/tools/testing/selftests/filesystems/epoll/epoll_wakeup_test.c @@ -74,6 +74,24 @@ static void *waiter_entry1ap(void *data) return NULL; } +static void *waiter_entry1ap_loop(void *data) +{ + struct pollfd pfd; + struct epoll_event e; + struct epoll_mtcontext *ctx = data; + + pfd.fd = ctx->efd[0]; + pfd.events = POLLIN; + while (poll(&pfd, 1, 2000) > 0) { + if (epoll_wait(ctx->efd[0], &e, 1, 0) > 0) { + __sync_fetch_and_add(&ctx->count, 1); + break; + } + } + + return NULL; +} + static void *waiter_entry1o(void *data) { struct epoll_event e; @@ -809,7 +827,7 @@ TEST(epoll16) ASSERT_EQ(epoll_ctl(ctx.efd[0], EPOLL_CTL_ADD, ctx.sfd[2], events), 0); ctx.main = pthread_self(); - ASSERT_EQ(pthread_create(&ctx.waiter, NULL, waiter_entry1ap, &ctx), 0); + ASSERT_EQ(pthread_create(&ctx.waiter, NULL, waiter_entry1ap_loop, &ctx), 0); ASSERT_EQ(pthread_create(&emitter, NULL, emitter_entry2, &ctx), 0); if (epoll_wait(ctx.efd[0], events, 1, -1) > 0) @@ -2925,7 +2943,7 @@ TEST(epoll56) ASSERT_EQ(epoll_ctl(ctx.efd[0], EPOLL_CTL_ADD, ctx.efd[2], &e), 0); ctx.main = pthread_self(); - ASSERT_EQ(pthread_create(&ctx.waiter, NULL, waiter_entry1ap, &ctx), 0); + ASSERT_EQ(pthread_create(&ctx.waiter, NULL, waiter_entry1ap_loop, &ctx), 0); ASSERT_EQ(pthread_create(&emitter, NULL, emitter_entry2, &ctx), 0); if (epoll_wait(ctx.efd[0], &e, 1, -1) > 0) @@ -3030,7 +3048,6 @@ TEST(epoll57) TEST(epoll58) { pthread_t emitter; - struct pollfd pfd; struct epoll_event e; struct epoll_mtcontext ctx = { 0 }; @@ -3061,15 +3078,10 @@ TEST(epoll58) ASSERT_EQ(epoll_ctl(ctx.efd[0], EPOLL_CTL_ADD, ctx.efd[2], &e), 0); ctx.main = pthread_self(); - ASSERT_EQ(pthread_create(&ctx.waiter, NULL, waiter_entry1ap, &ctx), 0); + ASSERT_EQ(pthread_create(&ctx.waiter, NULL, waiter_entry1ap_loop, &ctx), 0); ASSERT_EQ(pthread_create(&emitter, NULL, emitter_entry2, &ctx), 0); - pfd.fd = ctx.efd[0]; - pfd.events = POLLIN; - if (poll(&pfd, 1, -1) > 0) { - if (epoll_wait(ctx.efd[0], &e, 1, 0) > 0) - __sync_fetch_and_add(&ctx.count, 1); - } + waiter_entry1ap_loop(&ctx); ASSERT_EQ(pthread_join(ctx.waiter, NULL), 0); EXPECT_EQ(ctx.count, 2); diff --git a/tools/testing/selftests/filesystems/fscontext_ns/.gitignore b/tools/testing/selftests/filesystems/fscontext_ns/.gitignore new file mode 100644 index 000000000000..a632905257a3 --- /dev/null +++ b/tools/testing/selftests/filesystems/fscontext_ns/.gitignore @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: GPL-2.0-only +fscontext_ns_test diff --git a/tools/testing/selftests/filesystems/overlayfs/set_layers_via_fds.c b/tools/testing/selftests/filesystems/overlayfs/set_layers_via_fds.c index 7a293544233d..83bbacb2550f 100644 --- a/tools/testing/selftests/filesystems/overlayfs/set_layers_via_fds.c +++ b/tools/testing/selftests/filesystems/overlayfs/set_layers_via_fds.c @@ -686,23 +686,23 @@ TEST_F(set_layers_via_fds, set_layers_via_detached_mount_fds) while (getline(&line, &len, f_mountinfo) != -1) { char *haystack = line; - if (strstr(haystack, "workdir=/tmp/w")) + if (strstr(haystack, "workdir=/work")) layers_found[0] = true; - if (strstr(haystack, "upperdir=/tmp/u")) + if (strstr(haystack, "upperdir=/upper")) layers_found[1] = true; - if (strstr(haystack, "lowerdir+=/tmp/l1")) + if (strstr(haystack, "lowerdir+=/")) layers_found[2] = true; - if (strstr(haystack, "lowerdir+=/tmp/l2")) + if (strstr(haystack, "lowerdir+=/")) layers_found[3] = true; - if (strstr(haystack, "lowerdir+=/tmp/l3")) + if (strstr(haystack, "lowerdir+=/")) layers_found[4] = true; - if (strstr(haystack, "lowerdir+=/tmp/l4")) + if (strstr(haystack, "lowerdir+=/")) layers_found[5] = true; - if (strstr(haystack, "datadir+=/tmp/d1")) + if (strstr(haystack, "datadir+=/")) layers_found[6] = true; - if (strstr(haystack, "datadir+=/tmp/d2")) + if (strstr(haystack, "datadir+=/")) layers_found[7] = true; - if (strstr(haystack, "datadir+=/tmp/d3")) + if (strstr(haystack, "datadir+=/")) layers_found[8] = true; } free(line); diff --git a/tools/testing/selftests/ftrace/ftracetest b/tools/testing/selftests/ftrace/ftracetest index 246d7e1d015c..95804610e079 100755 --- a/tools/testing/selftests/ftrace/ftracetest +++ b/tools/testing/selftests/ftrace/ftracetest @@ -243,7 +243,7 @@ else mkdir -p $LOG_DIR || errexit "Failed to make a log directory: $LOG_DIR" date > $LOG_FILE if [ "x-$LINK_PTR" != "x-" ]; then - unlink $LINK_PTR + rm -f $LINK_PTR ln -fs $LOG_DATE $LINK_PTR fi fi diff --git a/tools/testing/selftests/namespaces/ns_active_ref_test.c b/tools/testing/selftests/namespaces/ns_active_ref_test.c index 093268f0efaa..ab5ffe4de521 100644 --- a/tools/testing/selftests/namespaces/ns_active_ref_test.c +++ b/tools/testing/selftests/namespaces/ns_active_ref_test.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -20,6 +21,10 @@ #include "../filesystems/utils.h" #include "wrappers.h" +#ifndef PIDFD_THREAD +#define PIDFD_THREAD O_EXCL +#endif + #ifndef FD_NSFS_ROOT #define FD_NSFS_ROOT -10003 /* Root of the nsfs filesystem */ #endif @@ -2120,6 +2125,7 @@ TEST(ns_mixed_types_same_owner) /* Thread test helpers and structures */ struct thread_ns_info { __u64 ns_id; + int pidfd; int pipefd; int syncfd_read; int syncfd_write; @@ -2152,6 +2158,13 @@ static void *thread_create_namespace(void *arg) return NULL; } + /* Open a pidfd so the main thread can later poll it to detect actual thread exit. */ + info->pidfd = syscall(__NR_pidfd_open, gettid(), PIDFD_THREAD); + if (info->pidfd < 0) { + info->exit_code = 6; + return NULL; + } + /* Send namespace ID to main thread */ if (write(info->pipefd, &info->ns_id, sizeof(info->ns_id)) != sizeof(info->ns_id)) { info->exit_code = 4; @@ -2169,6 +2182,20 @@ static void *thread_create_namespace(void *arg) return NULL; } +/* + * pthread_join() returns once exit_mm() wakes the CLEARTID futex, before + * exit_nsproxy_namespaces() drops the namespace reference. A pidfd becomes + * readable only from exit_notify(), after that point. + */ +static int wait_thread_exited(int pidfd) +{ + struct pollfd pfd = { .fd = pidfd, .events = POLLIN }; + int ret = poll(&pfd, 1, -1); + + close(pidfd); + return ret; +} + /* * Test that namespace becomes inactive after thread exits. * This verifies active reference counting works with threads, not just processes. @@ -2234,6 +2261,7 @@ TEST(thread_ns_inactive_after_exit) close(syncpipe[1]); /* Wait for thread to exit */ + ASSERT_EQ(wait_thread_exited(info.pidfd), 1); ASSERT_EQ(pthread_join(thread, NULL), 0); close(pipefd[0]); close(pipefd[1]); @@ -2317,6 +2345,7 @@ TEST(thread_ns_fd_keeps_active) close(syncpipe[1]); /* Wait for thread to exit */ + ASSERT_EQ(wait_thread_exited(info.pidfd), 1); pthread_join(thread, NULL); close(pipefd[0]); close(pipefd[1]); diff --git a/tools/testing/selftests/net/lib/csum.c b/tools/testing/selftests/net/lib/csum.c index e28884ce3ab3..ad960e07e31b 100644 --- a/tools/testing/selftests/net/lib/csum.c +++ b/tools/testing/selftests/net/lib/csum.c @@ -2,8 +2,7 @@ /* Test hardware checksum offload: Rx + Tx, IPv4 + IPv6, TCP + UDP. * - * The test runs on two machines to exercise the NIC. For this reason it - * is not integrated in kselftests. + * The test runs on two machines to exercise the NIC. * * CMD=$((./csum -[46] -[tu] -S $SADDR -D $DADDR -[RT] -r 1 $EXTRA_ARGS)) * @@ -236,7 +235,8 @@ static void *build_packet_udp(void *_uh) uh->source = 0; uh->source = checksum(uh, IPPROTO_UDP, sizeof(*uh) + cfg_payload_len); - fprintf(stderr, "tx: changing sport: %hu -> %hu\n", + fprintf(stderr, "%s: changing sport: %hu -> %hu\n", + cfg_do_tx ? "tx" : "rx", cfg_port_src, ntohs(uh->source)); cfg_port_src = ntohs(uh->source); } @@ -249,7 +249,8 @@ static void *build_packet_udp(void *_uh) if (cfg_bad_csum) uh->check = ~uh->check; - fprintf(stderr, "tx: sending checksum: 0x%x\n", uh->check); + if (cfg_do_tx) + fprintf(stderr, "tx: sending checksum: 0x%x\n", uh->check); return uh + 1; } @@ -571,15 +572,36 @@ static int recv_prepare_packet(void) static int recv_udp(int fd) { static char buf[MAX_PAYLOAD_LEN]; + struct sockaddr_storage addr; + socklen_t addrlen; int ret, count = 0; while (1) { - ret = recv(fd, buf, sizeof(buf), MSG_DONTWAIT); + addrlen = sizeof(addr); + ret = recvfrom(fd, buf, sizeof(buf), MSG_DONTWAIT, + (struct sockaddr *)&addr, &addrlen); if (ret == -1 && errno == EAGAIN) break; if (ret == -1) error(1, errno, "recv r"); + if (cfg_family == PF_INET) { + struct sockaddr_in *sin = (void *)&addr; + + if (sin->sin_addr.s_addr != cfg_saddr4.sin_addr.s_addr) + continue; + if (sin->sin_port != htons(cfg_port_src)) + continue; + } else { + struct sockaddr_in6 *sin6 = (void *)&addr; + + if (memcmp(&sin6->sin6_addr, &cfg_saddr6.sin6_addr, + sizeof(sin6->sin6_addr))) + continue; + if (sin6->sin6_port != htons(cfg_port_src)) + continue; + } + fprintf(stderr, "rx: udp: len=%u\n", ret); count++; } @@ -620,6 +642,9 @@ static int recv_verify_packet_tcp(void *th, int len) if (len < sizeof(*tcph) || tcph->dest != htons(cfg_port_dst)) return -1; + if (tcph->source != htons(cfg_port_src)) + return -1; + return recv_verify_csum(th, len, ntohs(tcph->source), tcph->check); } @@ -647,6 +672,9 @@ static int recv_verify_packet_udp(void *th, int len) return recv_verify_packet_udp_encap(udph + 1, len - sizeof(*udph)); + if (udph->source != htons(cfg_port_src)) + return -1; + return recv_verify_csum(th, len, ntohs(udph->source), udph->check); } @@ -659,6 +687,9 @@ static int recv_verify_packet_ipv4(void *nh, int len) if (len < sizeof(*iph) || iph->protocol != proto) return -1; + if (iph->saddr != cfg_saddr4.sin_addr.s_addr) + return -1; + ip_len = ntohs(iph->tot_len); if (ip_len > len || ip_len < sizeof(*iph)) return -1; @@ -680,6 +711,9 @@ static int recv_verify_packet_ipv6(void *nh, int len) if (len < sizeof(*ip6h) || ip6h->nexthdr != proto) return -1; + if (memcmp(&ip6h->saddr, &cfg_saddr6.sin6_addr, sizeof(ip6h->saddr))) + return -1; + payload_len = ntohs(ip6h->payload_len); if (payload_len > len - sizeof(*ip6h)) return -1; @@ -940,6 +974,9 @@ static void do_tx(void) cfg_payload_len = rand() % MAX_PAYLOAD_LEN; buf = build_packet(_buf, sizeof(_buf), &len); } + + /* avoid bursting */ + usleep(20); } if (close(fd)) @@ -952,6 +989,14 @@ static void do_rx(int fdp, int fdr) long tleft, tstop; struct pollfd pfd; + if (!cfg_do_tx && cfg_zero_sum) { + static char _buf[MAX_HEADER_LEN + MAX_PAYLOAD_LEN]; + int len; + + /* calculate source port that causes csum to add up to zero */ + build_packet(_buf, sizeof(_buf), &len); + } + tstop = gettimeofday_ms() + cfg_timeout_ms; tleft = cfg_timeout_ms; diff --git a/tools/testing/selftests/net/lib/gro.c b/tools/testing/selftests/net/lib/gro.c index 7a333155de1a..1bc92e7a625f 100644 --- a/tools/testing/selftests/net/lib/gro.c +++ b/tools/testing/selftests/net/lib/gro.c @@ -1246,7 +1246,6 @@ static void check_capacity_pkts(int fd) int coalesced[num_flows]; struct tcphdr *tcph; int ip_ext_len = 0; - int total_data = 0; int pkt_size = -1; int data_len = 0; int flow_id; @@ -1309,7 +1308,6 @@ static void check_capacity_pkts(int fd) } num_pkt++; - total_data += data_len; } /* Check flow ordering. We expect to see all non-coalesced first segs diff --git a/tools/testing/selftests/net/netfilter/conntrack_vrf.sh b/tools/testing/selftests/net/netfilter/conntrack_vrf.sh index 207b79932d91..2dbfabaadf4b 100755 --- a/tools/testing/selftests/net/netfilter/conntrack_vrf.sh +++ b/tools/testing/selftests/net/netfilter/conntrack_vrf.sh @@ -84,7 +84,7 @@ busywait $BUSYWAIT_TIMEOUT listener_ready "$ns1" # as decided by the first iteration of the ruleset. test_ct_zone_in() { -ip netns exec "$ns0" nft -f - < /dev/null # should be in zone 1, not zone 2 @@ -113,6 +119,7 @@ EOF echo "PASS: entry found in conntrack zone 1" else echo "FAIL: entry not found in conntrack zone 1" + ret=1 count=$(ip netns exec "$ns0" conntrack -L -s $IP1 -d $IP0 -p icmp --zone 2 2> /dev/null | wc -l) if [ "$count" -eq 1 ]; then echo "FAIL: entry found in zone 2 instead" @@ -137,7 +144,7 @@ test_masquerade_vrf() ip netns exec "$ns0" conntrack -F 2>/dev/null -ip netns exec "$ns0" nft -f - < /dev/null;then echo "FAIL: connect failure with masquerade + sport rewrite on vrf device" ret=1 @@ -184,7 +197,7 @@ EOF test_masquerade_veth() { ip netns exec "$ns0" conntrack -F 2>/dev/null -ip netns exec "$ns0" nft -f - < /dev/null;then echo "FAIL: connect failure with masquerade + sport rewrite on veth device" ret=1 diff --git a/tools/testing/selftests/net/tcp_mmap.c b/tools/testing/selftests/net/tcp_mmap.c index 487ae659a1f1..86241bed7f08 100644 --- a/tools/testing/selftests/net/tcp_mmap.c +++ b/tools/testing/selftests/net/tcp_mmap.c @@ -85,7 +85,6 @@ static int rcvbuf; /* Default: autotuning. Can be set with -r option static int sndbuf; /* Default: autotuning. Can be set with -w option */ static int zflg; /* zero copy option. (MSG_ZEROCOPY for sender, mmap() for receiver */ static int xflg; /* hash received data (simple xor) (-h option) */ -static int keepflag; /* -k option: receiver shall keep all received file in memory (no munmap() calls) */ static int integrity; /* -i option: sender and receiver compute sha256 over the data.*/ static size_t chunk_size = 512*1024; @@ -456,7 +455,7 @@ int main(int argc, char *argv[]) int sflg = 0; int mss = 0; - while ((c = getopt(argc, argv, "46p:svr:w:H:zxkP:M:C:a:i")) != -1) { + while ((c = getopt(argc, argv, "46p:svr:w:H:zxP:M:C:a:i")) != -1) { switch (c) { case '4': cfg_family = PF_INET; @@ -490,9 +489,6 @@ int main(int argc, char *argv[]) case 'x': xflg = 1; break; - case 'k': - keepflag = 1; - break; case 'P': max_pacing_rate = atoi(optarg) ; break; diff --git a/tools/testing/selftests/net/txtimestamp.c b/tools/testing/selftests/net/txtimestamp.c index 170be192f5c7..f7bdf30b78d9 100644 --- a/tools/testing/selftests/net/txtimestamp.c +++ b/tools/testing/selftests/net/txtimestamp.c @@ -418,19 +418,25 @@ static uint16_t get_ip_csum(const uint16_t *start, int num_words, return ~sum; } -static uint16_t get_udp_csum(const struct udphdr *udph, int alen) +static uint16_t get_udp_csum(const struct udphdr *udph, bool is_ipv4) { - unsigned long pseudo_sum, csum_len; - const void *csum_start = udph; + const void *addr = is_ipv4 ? (void *)&daddr.sin_addr : &daddr6.sin6_addr; + int alen = is_ipv4 ? sizeof(struct in_addr) : sizeof(struct in6_addr); + uint16_t addr16[sizeof(struct in6_addr) / sizeof(uint16_t)]; + unsigned long pseudo_sum; + int i; pseudo_sum = htons(IPPROTO_UDP); pseudo_sum += udph->len; - /* checksum ip(v6) addresses + udp header + payload */ - csum_start -= alen * 2; - csum_len = ntohs(udph->len) + alen * 2; + /* pseudo-header source and destination: both are daddr */ + memcpy(addr16, addr, alen); + for (i = 0; i < alen / 2; i++) + pseudo_sum += 2 * addr16[i]; - return get_ip_csum(csum_start, csum_len >> 1, pseudo_sum); + /* checksum udp header + payload */ + return get_ip_csum((const uint16_t *)udph, ntohs(udph->len) >> 1, + pseudo_sum); } static int fill_header_ipv4(void *p) @@ -479,8 +485,7 @@ static void fill_header_udp(void *p, bool is_ipv4) udph->len = ntohs(sizeof(*udph) + cfg_payload_len); udph->check = 0; - udph->check = get_udp_csum(udph, is_ipv4 ? sizeof(struct in_addr) : - sizeof(struct in6_addr)); + udph->check = get_udp_csum(udph, is_ipv4); } static void do_test(int family, unsigned int report_opt) diff --git a/tools/testing/selftests/nolibc/Makefile b/tools/testing/selftests/nolibc/Makefile index 6bace04227a7..6981c220eed7 100644 --- a/tools/testing/selftests/nolibc/Makefile +++ b/tools/testing/selftests/nolibc/Makefile @@ -10,7 +10,7 @@ cc-option = $(call __cc-option, $(CC),,$(1),$(2)) include Makefile.include $(OUTPUT)/nolibc-test: CFLAGS = -nostdlib -nostdinc -static \ - -isystem $(top_srcdir)/tools/include/nolibc -isystem $(top_srcdir)/usr/include \ + -isystem $(top_srcdir)/tools/include/nolibc $(KHDR_INCLUDES) \ $(CFLAGS_NOLIBC_TEST) $(OUTPUT)/nolibc-test: LDLIBS = $(if $(LLVM),,-lgcc) $(OUTPUT)/nolibc-test: $(NOLIBC_TEST_SOURCES) | headers diff --git a/tools/testing/selftests/pidfd/pidfd_open_test.c b/tools/testing/selftests/pidfd/pidfd_open_test.c index 318e6f09c8e0..c6698b7cdb47 100644 --- a/tools/testing/selftests/pidfd/pidfd_open_test.c +++ b/tools/testing/selftests/pidfd/pidfd_open_test.c @@ -168,7 +168,7 @@ int main(int argc, char **argv) } if (info.ppid != getppid()) { ksft_print_msg("ppid %d does not match ppid from ioctl %d\n", - pid, info.pid); + getppid(), info.ppid); goto on_error; } if (info.ruid != getuid()) { diff --git a/tools/testing/selftests/proc/proc-pid-vm.c b/tools/testing/selftests/proc/proc-pid-vm.c index 4e6a3e53f975..98e882e56815 100644 --- a/tools/testing/selftests/proc/proc-pid-vm.c +++ b/tools/testing/selftests/proc/proc-pid-vm.c @@ -47,10 +47,6 @@ #include #include -#ifndef __maybe_unused -#define __maybe_unused __attribute__((__unused__)) -#endif - #include "kselftest.h" static inline long sys_execveat(int dirfd, const char *pathname, char **argv, char **envp, int flags) @@ -214,7 +210,6 @@ static int make_exe(const uint8_t *payload, size_t len) return fd1; } -#endif /* * 0: vsyscall VMA doesn't exist vsyscall=none @@ -222,15 +217,14 @@ static int make_exe(const uint8_t *payload, size_t len) * 2: vsyscall VMA is r-xp vsyscall=emulate */ static volatile int g_vsyscall; -static const char *str_vsyscall __maybe_unused; +static const char *str_vsyscall; -static const char str_vsyscall_0[] __maybe_unused = ""; -static const char str_vsyscall_1[] __maybe_unused = +static const char str_vsyscall_0[] = ""; +static const char str_vsyscall_1[] = "ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0 [vsyscall]\n"; -static const char str_vsyscall_2[] __maybe_unused = +static const char str_vsyscall_2[] = "ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]\n"; -#ifdef __x86_64__ static void sigaction_SIGSEGV(int _, siginfo_t *__, void *___) { _exit(g_vsyscall); diff --git a/tools/testing/selftests/rdma/config b/tools/testing/selftests/rdma/config index e1ff54ec0f57..1be43c4274bb 100644 --- a/tools/testing/selftests/rdma/config +++ b/tools/testing/selftests/rdma/config @@ -1,5 +1,7 @@ -CONFIG_TUN -CONFIG_VETH -CONFIG_DUMMY -CONFIG_NET_NS -CONFIG_RDMA_RXE +CONFIG_TUN=m +CONFIG_VETH=m +CONFIG_DUMMY=m +CONFIG_NET_NS=y +CONFIG_INFINIBAND=m +CONFIG_INFINIBAND_USER_ACCESS=m +CONFIG_RDMA_RXE=m diff --git a/tools/testing/selftests/rdma/rxe_sent_rcvd_bytes.sh b/tools/testing/selftests/rdma/rxe_sent_rcvd_bytes.sh index 0e4fbfeebd22..89218ccfba4c 100755 --- a/tools/testing/selftests/rdma/rxe_sent_rcvd_bytes.sh +++ b/tools/testing/selftests/rdma/rxe_sent_rcvd_bytes.sh @@ -4,6 +4,8 @@ PORT=4791 MODS=("tun" "rdma_rxe") +source "$(dirname "$0")/../kselftest/ktap_helpers.sh" + exec > /dev/null # --- Helper: Cleanup Routine --- @@ -24,6 +26,10 @@ if [[ $EUID -ne 0 ]]; then fi for m in "${MODS[@]}"; do + if ! modinfo "$m" >/dev/null 2>&1; then + echo "SKIP: Kernel module '$m' not found." >&2 + exit $KSFT_SKIP + fi modprobe "$m" || { echo "Error: Failed to load $m"; exit 1; } done diff --git a/tools/testing/selftests/sched_ext/hotplug.c b/tools/testing/selftests/sched_ext/hotplug.c index 0cfbb111a2d0..10b8d42bd89b 100644 --- a/tools/testing/selftests/sched_ext/hotplug.c +++ b/tools/testing/selftests/sched_ext/hotplug.c @@ -21,15 +21,17 @@ static bool is_cpu_online(void) return file_read_long(online_path) > 0; } -static void toggle_online_status(bool online) +static int toggle_online_status(bool online) { long val = online ? 1 : 0; int ret; ret = file_write_long(online_path, val); if (ret != 0) - fprintf(stderr, "Failed to bring CPU %s (%s)", + fprintf(stderr, "Failed to bring CPU %s (%s)\n", online ? "online" : "offline", strerror(errno)); + + return ret; } static enum scx_test_status setup(void **ctx) @@ -44,6 +46,7 @@ static enum scx_test_status test_hotplug(bool onlining, bool cbs_defined) { struct hotplug *skel; struct bpf_link *link; + enum scx_test_status status = SCX_TEST_FAIL; long kind, code; SCX_ASSERT(is_cpu_online()); @@ -54,8 +57,8 @@ static enum scx_test_status test_hotplug(bool onlining, bool cbs_defined) SCX_FAIL_IF(hotplug__load(skel), "Failed to load skel"); /* Testing the offline -> online path, so go offline before starting */ - if (onlining) - toggle_online_status(0); + if (onlining && toggle_online_status(0)) + goto out_destroy_skel; if (cbs_defined) { kind = SCX_KIND_VAL(SCX_EXIT_UNREG_BPF); @@ -79,7 +82,8 @@ static enum scx_test_status test_hotplug(bool onlining, bool cbs_defined) return SCX_TEST_FAIL; } - toggle_online_status(onlining ? 1 : 0); + if (toggle_online_status(onlining ? 1 : 0)) + goto out_destroy_link; while (!UEI_EXITED(skel, uei)) sched_yield(); @@ -87,20 +91,23 @@ static enum scx_test_status test_hotplug(bool onlining, bool cbs_defined) SCX_EQ(skel->data->uei.kind, kind); SCX_EQ(UEI_REPORT(skel, uei), code); - if (!onlining) - toggle_online_status(1); + if (!onlining && toggle_online_status(1)) + goto out_destroy_link; + status = SCX_TEST_PASS; +out_destroy_link: bpf_link__destroy(link); +out_destroy_skel: hotplug__destroy(skel); - return SCX_TEST_PASS; + return status; } static enum scx_test_status test_hotplug_attach(void) { struct hotplug *skel; struct bpf_link *link; - enum scx_test_status status = SCX_TEST_PASS; + enum scx_test_status status = SCX_TEST_FAIL; long kind, code; SCX_ASSERT(is_cpu_online()); @@ -115,10 +122,12 @@ static enum scx_test_status test_hotplug_attach(void) * Take the CPU offline to increment the global hotplug seq, which * should cause attach to fail due to us setting the hotplug seq above */ - toggle_online_status(0); + if (toggle_online_status(0)) + goto out_destroy_skel; link = bpf_map__attach_struct_ops(skel->maps.hotplug_nocb_ops); - toggle_online_status(1); + if (toggle_online_status(1)) + goto out_destroy_link; SCX_ASSERT(link); while (!UEI_EXITED(skel, uei)) @@ -130,7 +139,10 @@ static enum scx_test_status test_hotplug_attach(void) SCX_EQ(skel->data->uei.kind, kind); SCX_EQ(UEI_REPORT(skel, uei), code); + status = SCX_TEST_PASS; +out_destroy_link: bpf_link__destroy(link); +out_destroy_skel: hotplug__destroy(skel); return status; diff --git a/tools/testing/selftests/sched_ext/rt_stall.c b/tools/testing/selftests/sched_ext/rt_stall.c index a5041fc2e44f..a1552b38a6e8 100644 --- a/tools/testing/selftests/sched_ext/rt_stall.c +++ b/tools/testing/selftests/sched_ext/rt_stall.c @@ -17,7 +17,6 @@ #include #include "rt_stall.bpf.skel.h" #include "scx_test.h" -#include "../kselftest.h" #define CORE_ID 0 /* CPU to pin tasks to */ #define RUN_TIME 5 /* How long to run the test in seconds */ @@ -35,15 +34,17 @@ static void signal_ready(int fd) } /* Wait for a child to signal readiness via a pipe */ -static void wait_ready(int fd) +static bool wait_ready(int fd) { + bool ready; char c; - if (read(fd, &c, 1) != 1) { + ready = read(fd, &c, 1) == 1; + if (!ready) perror("read from ready pipe"); - exit(EXIT_FAILURE); - } close(fd); + + return ready; } /* Simple busy-wait function for test tasks */ @@ -151,13 +152,11 @@ static bool sched_stress_test(bool is_ext) float ext_runtime, rt_runtime, actual_ratio; int ext_pid, rt_pid; int ext_ready[2], rt_ready[2]; - - ksft_print_header(); - ksft_set_plan(1); + bool ret = false; if (pipe(ext_ready) || pipe(rt_ready)) { perror("pipe"); - ksft_exit_fail(); + return false; } /* Create and set up a EXT task */ @@ -172,7 +171,7 @@ static bool sched_stress_test(bool is_ext) exit(0); } else if (ext_pid < 0) { perror("fork task"); - ksft_exit_fail(); + return false; } /* Create an RT task */ @@ -188,7 +187,7 @@ static bool sched_stress_test(bool is_ext) exit(0); } else if (rt_pid < 0) { perror("fork for RT task"); - ksft_exit_fail(); + goto out_kill_ext; } /* @@ -199,45 +198,47 @@ static bool sched_stress_test(bool is_ext) */ close(ext_ready[1]); close(rt_ready[1]); - wait_ready(ext_ready[0]); - wait_ready(rt_ready[0]); + if (!wait_ready(ext_ready[0]) || !wait_ready(rt_ready[0])) + goto out_kill; /* Let the processes run for the specified time */ sleep(RUN_TIME); /* Get runtime for the EXT task */ ext_runtime = get_process_runtime(ext_pid); - if (ext_runtime == -1) - ksft_exit_fail_msg("Error getting runtime for %s task (PID %d)\n", - class_str, ext_pid); - ksft_print_msg("Runtime of %s task (PID %d) is %f seconds\n", - class_str, ext_pid, ext_runtime); + if (ext_runtime == -1) { + fprintf(stderr, "Failed to read %s task runtime\n", class_str); + goto out_kill; + } /* Get runtime for the RT task */ rt_runtime = get_process_runtime(rt_pid); - if (rt_runtime == -1) - ksft_exit_fail_msg("Error getting runtime for RT task (PID %d)\n", rt_pid); - ksft_print_msg("Runtime of RT task (PID %d) is %f seconds\n", rt_pid, rt_runtime); - - /* Kill the processes */ - kill(ext_pid, SIGKILL); - kill(rt_pid, SIGKILL); - waitpid(ext_pid, NULL, 0); - waitpid(rt_pid, NULL, 0); + if (rt_runtime == -1) { + fprintf(stderr, "Failed to read RT task runtime\n"); + goto out_kill; + } /* Verify that the scx task got enough runtime */ actual_ratio = ext_runtime / (ext_runtime + rt_runtime); - ksft_print_msg("%s task got %.2f%% of total runtime\n", - class_str, actual_ratio * 100); + fprintf(stderr, "%s task ran %.3fs, RT task ran %.3fs (%.2f%% of runtime)\n", + class_str, ext_runtime, rt_runtime, actual_ratio * 100); - if (actual_ratio >= expected_min_ratio) { - ksft_test_result_pass("PASS: %s task got more than %.2f%% of runtime\n", - class_str, expected_min_ratio * 100); - return true; + if (actual_ratio < expected_min_ratio) { + fprintf(stderr, "%s task got less than %.2f%% of runtime\n", + class_str, expected_min_ratio * 100); + goto out_kill; } - ksft_test_result_fail("FAIL: %s task got less than %.2f%% of runtime\n", - class_str, expected_min_ratio * 100); - return false; + + ret = true; + +out_kill: + kill(rt_pid, SIGKILL); + waitpid(rt_pid, NULL, 0); +out_kill_ext: + kill(ext_pid, SIGKILL); + waitpid(ext_pid, NULL, 0); + + return ret; } static enum scx_test_status run(void *ctx) @@ -263,14 +264,17 @@ static enum scx_test_status run(void *ctx) link = bpf_map__attach_struct_ops(skel->maps.rt_stall_ops); SCX_FAIL_IF(!link, "Failed to attach scheduler"); } + res = sched_stress_test(is_ext); + if (is_ext) { - SCX_EQ(skel->data->uei.kind, EXIT_KIND(SCX_EXIT_NONE)); + int exit_kind = skel->data->uei.kind; bpf_link__destroy(link); + SCX_EQ(exit_kind, EXIT_KIND(SCX_EXIT_NONE)); } if (!res) - ksft_exit_fail(); + return SCX_TEST_FAIL; } return SCX_TEST_PASS; diff --git a/tools/testing/selftests/sched_ext/runner.c b/tools/testing/selftests/sched_ext/runner.c index c264807caa91..57dda75384f1 100644 --- a/tools/testing/selftests/sched_ext/runner.c +++ b/tools/testing/selftests/sched_ext/runner.c @@ -243,7 +243,7 @@ int main(int argc, char **argv) printf(" - %s\n", failed_tests[i]); } - return failed > 0 ? 1 : 0; + return failed > 0 || exit_req ? 1 : 0; } void scx_test_register(struct scx_test *test) diff --git a/tools/testing/selftests/tc-testing/tc-tests/qdiscs/hfsc.json b/tools/testing/selftests/tc-testing/tc-tests/qdiscs/hfsc.json index 4f6bbb8b57f9..557730eef055 100644 --- a/tools/testing/selftests/tc-testing/tc-tests/qdiscs/hfsc.json +++ b/tools/testing/selftests/tc-testing/tc-tests/qdiscs/hfsc.json @@ -181,7 +181,7 @@ "requires": "nsPlugin" }, "setup": [ - "ip link set lo up", + "$IP link set lo up", "$TC qdisc add dev lo handle 1: root hfsc default 30", "$TC class add dev lo parent 1: classid 1:1 hfsc rt m2 100kbit", "$TC class add dev lo parent 1:1 classid 1:10 hfsc rt m2 50kbit", diff --git a/tools/testing/selftests/thermal/intel/power_floor/Makefile b/tools/testing/selftests/thermal/intel/power_floor/Makefile index 07463c2160e0..16d26eab5565 100644 --- a/tools/testing/selftests/thermal/intel/power_floor/Makefile +++ b/tools/testing/selftests/thermal/intel/power_floor/Makefile @@ -1,12 +1,10 @@ # SPDX-License-Identifier: GPL-2.0 -ifndef CROSS_COMPILE -ARCH ?= $(shell uname -m 2>/dev/null || echo not) -override ARCH := $(shell echo $(ARCH) | sed -e s/i.86/x86/ -e s/x86_64/x86/) +top_srcdir = ../../../../../.. +include $(top_srcdir)/scripts/subarch.include +ARCH_PROCESSED := $(shell echo $(or $(ARCH),$(SUBARCH)) | sed -e s/i.86/x86/ -e s/x86_64/x86/) -ifeq ($(ARCH),x86) +ifeq ($(ARCH_PROCESSED),x86) TEST_GEN_PROGS := power_floor_test +endif include ../../../lib.mk - -endif -endif diff --git a/tools/testing/selftests/thermal/intel/workload_hint/Makefile b/tools/testing/selftests/thermal/intel/workload_hint/Makefile index 49e3bc2b20f9..e53d6ecd9f8d 100644 --- a/tools/testing/selftests/thermal/intel/workload_hint/Makefile +++ b/tools/testing/selftests/thermal/intel/workload_hint/Makefile @@ -1,12 +1,10 @@ # SPDX-License-Identifier: GPL-2.0 -ifndef CROSS_COMPILE -ARCH ?= $(shell uname -m 2>/dev/null || echo not) -override ARCH := $(shell echo $(ARCH) | sed -e s/i.86/x86/ -e s/x86_64/x86/) +top_srcdir = ../../../../../.. +include $(top_srcdir)/scripts/subarch.include +ARCH_PROCESSED := $(shell echo $(or $(ARCH),$(SUBARCH)) | sed -e s/i.86/x86/ -e s/x86_64/x86/) -ifeq ($(ARCH),x86) +ifeq ($(ARCH_PROCESSED),x86) TEST_GEN_PROGS := workload_hint_test +endif include ../../../lib.mk - -endif -endif diff --git a/tools/testing/selftests/timers/clocksource-switch.c b/tools/testing/selftests/timers/clocksource-switch.c index db62a764c29e..2e86f56d953e 100644 --- a/tools/testing/selftests/timers/clocksource-switch.c +++ b/tools/testing/selftests/timers/clocksource-switch.c @@ -40,16 +40,23 @@ int get_clocksources(char list[][30]) { int fd, i; - size_t size; + ssize_t size; char buf[512]; char *head, *tmp; fd = open("/sys/devices/system/clocksource/clocksource0/available_clocksource", O_RDONLY); + if (fd < 0) + return 0; - size = read(fd, buf, 512); + size = read(fd, buf, sizeof(buf) - 1); close(fd); + if (size <= 0) + return 0; + + buf[size] = '\0'; + for (i = 0; i < 10; i++) list[i][0] = '\0'; @@ -74,11 +81,21 @@ int get_clocksources(char list[][30]) int get_cur_clocksource(char *buf, size_t size) { + ssize_t len; int fd; fd = open("/sys/devices/system/clocksource/clocksource0/current_clocksource", O_RDONLY); + if (fd < 0) + return -1; + + len = read(fd, buf, size - 1); + + close(fd); + + if (len <= 0) + return -1; - size = read(fd, buf, size); + buf[len] = '\0'; return 0; } diff --git a/tools/testing/selftests/ublk/fault_inject.c b/tools/testing/selftests/ublk/fault_inject.c index 150896e02ff8..4b59f17a918c 100644 --- a/tools/testing/selftests/ublk/fault_inject.c +++ b/tools/testing/selftests/ublk/fault_inject.c @@ -11,7 +11,7 @@ #include "kublk.h" struct fi_opts { - long long delay_ns; + struct __kernel_timespec delay; bool die_during_fetch; }; @@ -47,7 +47,8 @@ static int ublk_fault_inject_tgt_init(const struct dev_ctx *ctx, return -ENOMEM; } - opts->delay_ns = ctx->fault_inject.delay_us * 1000; + opts->delay.tv_sec = ctx->fault_inject.delay_us / 1000000; + opts->delay.tv_nsec = ctx->fault_inject.delay_us % 1000000 * 1000; opts->die_during_fetch = ctx->fault_inject.die_during_fetch; dev->private_data = opts; @@ -85,12 +86,13 @@ static int ublk_fault_inject_queue_io(struct ublk_thread *t, const struct ublksrv_io_desc *iod = ublk_get_iod(q, tag); struct io_uring_sqe *sqe; struct fi_opts *opts = q->dev->private_data; - struct __kernel_timespec ts = { - .tv_nsec = opts->delay_ns, - }; + /* + * Pass a timespec that outlives this function, since io_uring + * reads it only when the SQE is submitted. + */ ublk_io_alloc_sqes(t, &sqe, 1); - io_uring_prep_timeout(sqe, &ts, 1, 0); + io_uring_prep_timeout(sqe, &opts->delay, 0, 0); sqe->user_data = build_user_data(tag, ublksrv_get_op(iod), 0, q->q_id, 1); ublk_queued_tgt_io(t, q, tag, 1); diff --git a/tools/testing/selftests/vfio/lib/sysfs.c b/tools/testing/selftests/vfio/lib/sysfs.c index 98a46a2543cd..d88e348a1e0d 100644 --- a/tools/testing/selftests/vfio/lib/sysfs.c +++ b/tools/testing/selftests/vfio/lib/sysfs.c @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only #include +#include #include #include #include diff --git a/tools/testing/shared/linux.c b/tools/testing/shared/linux.c index e0a0693df08f..a37d2f86d325 100644 --- a/tools/testing/shared/linux.c +++ b/tools/testing/shared/linux.c @@ -83,7 +83,7 @@ void *kmem_cache_alloc_lru(struct kmem_cache *cachep, struct list_lru *lru, } else { pthread_mutex_unlock(&cachep->lock); if (cachep->align) { - if (posix_memalign(&p, cachep->align, cachep->size) < 0) + if (posix_memalign(&p, cachep->align, cachep->size)) return NULL; } else { p = malloc(cachep->size); @@ -191,7 +191,7 @@ bool kmem_cache_alloc_bulk(struct kmem_cache *cachep, gfp_t gfp, size_t size, if (cachep->align) { if (posix_memalign(&p[i], cachep->align, - cachep->size) < 0) + cachep->size)) break; } else { p[i] = malloc(cachep->size); diff --git a/tools/testing/vma/include/dup.h b/tools/testing/vma/include/dup.h index 4c58487b764e..daa57ab5dabb 100644 --- a/tools/testing/vma/include/dup.h +++ b/tools/testing/vma/include/dup.h @@ -374,6 +374,9 @@ enum { #define VMA_LOCKED_MASK mk_vma_flags(VMA_LOCKED_BIT, VMA_LOCKONFAULT_BIT) +/* These flags can be updated atomically via VMA/mmap read lock. */ +#define VMA_ATOMIC_SET_ALLOWED mk_vma_flags(VMA_MAYBE_GUARD_BIT) + #define RLIMIT_STACK 3 /* max stack size */ #define RLIMIT_MEMLOCK 8 /* max locked-in-memory address space */ @@ -899,22 +902,6 @@ static inline void vm_flags_reset(struct vm_area_struct *vma, vm_flags_init(vma, flags); } -static inline void vma_flags_reset_once(struct vm_area_struct *vma, - vma_flags_t *flags) -{ - const unsigned long word = flags->__vma_flags[0]; - - /* It is assumed only the first system word must be written once. */ - vma_flags_overwrite_word_once(&vma->flags, word); - /* The remainder can be copied normally. */ - if (NUM_VMA_FLAG_BITS > BITS_PER_LONG) { - unsigned long *dst = &vma->flags.__vma_flags[1]; - const unsigned long *src = &flags->__vma_flags[1]; - - bitmap_copy(dst, src, NUM_VMA_FLAG_BITS - BITS_PER_LONG); - } -} - static inline void vm_flags_set(struct vm_area_struct *vma, vm_flags_t flags) { @@ -1041,27 +1028,24 @@ static __always_inline vma_flags_t vma_flags_diff_pair(const vma_flags_t *flags, return dst; } +/* + * Determine if flags and flags_other have precisely the same flags set, + * excluding atomic VMA flags. + */ static __always_inline bool vma_flags_same_pair(const vma_flags_t *flags, - const vma_flags_t *flags_other) + const vma_flags_t *flags_other) { - const unsigned long *bitmap = flags->__vma_flags; - const unsigned long *bitmap_other = flags_other->__vma_flags; - - return bitmap_equal(bitmap, bitmap_other, NUM_VMA_FLAG_BITS); -} + vma_flags_t diff = vma_flags_diff_pair(flags, flags_other); -static __always_inline bool vma_flags_same_mask(const vma_flags_t *flags, - vma_flags_t flags_other) -{ - const unsigned long *bitmap = flags->__vma_flags; - const unsigned long *bitmap_other = flags_other.__vma_flags; + /* + * Atomic VMA flags may be set concurrently under the VMA read lock, so + * are disregarded for equality testing purposes. + */ + vma_flags_clear_mask(&diff, VMA_ATOMIC_SET_ALLOWED); - return bitmap_equal(bitmap, bitmap_other, NUM_VMA_FLAG_BITS); + return vma_flags_empty(&diff); } -#define vma_flags_same(flags, ...) \ - vma_flags_same_mask(flags, mk_vma_flags(__VA_ARGS__)) - static __always_inline bool vma_test(const struct vm_area_struct *vma, vma_flag_t bit) { @@ -1110,6 +1094,36 @@ static __always_inline void vma_clear_flags_mask(struct vm_area_struct *vma, #define vma_clear_flags(vma, ...) \ vma_clear_flags_mask(vma, mk_vma_flags(__VA_ARGS__)) +/* + * Overwrite the VMA's flags with new ones, preserving atomic VMA flags in the + * process. The write is done once and once only. + */ +static inline void vma_overwrite_flags(struct vm_area_struct *vma, + vma_flags_t new_flags) +{ + vma_flags_t atomic; + + vma_assert_write_locked(vma); + + /* + * Preserve the VMA's atomic flags, which are kept stable by the VMA + * write lock. + */ + atomic = vma_flags_and_mask(&vma->flags, VMA_ATOMIC_SET_ALLOWED); + vma_flags_clear_mask(&new_flags, VMA_ATOMIC_SET_ALLOWED); + vma_flags_set_mask(&new_flags, atomic); + + /* It is assumed only the first system word must be written once. */ + vma_flags_overwrite_word_once(&vma->flags, new_flags.__vma_flags[0]); + /* The remainder can be copied normally. */ + if (NUM_VMA_FLAG_BITS > BITS_PER_LONG) { + unsigned long *dst = &vma->flags.__vma_flags[1]; + const unsigned long *src = &new_flags.__vma_flags[1]; + + bitmap_copy(dst, src, NUM_VMA_FLAG_BITS - BITS_PER_LONG); + } +} + static __always_inline bool vma_desc_test(const struct vm_area_desc *desc, vma_flag_t bit) { @@ -1202,7 +1216,7 @@ static inline void vma_assert_detached(struct vm_area_struct *vma) WARN_ON_ONCE(vma_is_attached(vma)); } -static inline void vma_assert_write_locked(struct vm_area_struct *); +static inline void vma_assert_write_locked(const struct vm_area_struct *); static inline void vma_mark_attached(struct vm_area_struct *vma) { vma_assert_write_locked(vma); @@ -1229,7 +1243,7 @@ static inline void vma_init(struct vm_area_struct *vma, struct mm_struct *mm) vma->vm_mm = mm; vma->vm_ops = &vma_dummy_vm_ops; INIT_LIST_HEAD(&vma->anon_vma_chain); - vma->vm_lock_seq = UINT_MAX; + vma->vm_lock_seq = 0; } /* diff --git a/tools/testing/vma/include/stubs.h b/tools/testing/vma/include/stubs.h index ab441162ac10..227652c9b81b 100644 --- a/tools/testing/vma/include/stubs.h +++ b/tools/testing/vma/include/stubs.h @@ -298,7 +298,7 @@ static inline void anon_vma_lock_write(struct anon_vma *anon_vma) { } -static inline void vma_assert_write_locked(struct vm_area_struct *vma) +static inline void vma_assert_write_locked(const struct vm_area_struct *vma) { } diff --git a/tools/testing/vma/shared.c b/tools/testing/vma/shared.c index 4a39c9d50489..4ba7786be5f1 100644 --- a/tools/testing/vma/shared.c +++ b/tools/testing/vma/shared.c @@ -56,7 +56,7 @@ struct vm_area_struct *alloc_and_link_vma(struct mm_struct *mm, * begun. Linking to the tree will have caused this to be incremented, * which means we will get a false positive otherwise. */ - vma->vm_lock_seq = UINT_MAX; + vma->vm_lock_seq = 0; return vma; } @@ -88,13 +88,13 @@ int cleanup_mm(struct mm_struct *mm, struct vma_iterator *vmi) bool vma_write_started(struct vm_area_struct *vma) { - int seq = vma->vm_lock_seq; + unsigned int seq = vma->vm_lock_seq; /* We reset after each check. */ - vma->vm_lock_seq = UINT_MAX; + vma->vm_lock_seq = 0; /* The vma_start_write() stub simply increments this value. */ - return seq > -1; + return seq > 0; } void __vma_set_dummy_anon_vma(struct vm_area_struct *vma, diff --git a/tools/testing/vma/shared.h b/tools/testing/vma/shared.h index 97cd7a679dc1..646edf367d7c 100644 --- a/tools/testing/vma/shared.h +++ b/tools/testing/vma/shared.h @@ -51,17 +51,21 @@ __TO_SCALAR(__val1), __TO_SCALAR(__val2)); \ } while (0) -#define ASSERT_FLAGS_SAME_MASK(_flags, _flags_other) \ - ASSERT_TRUE(vma_flags_same_mask((_flags), (_flags_other))) +#define ASSERT_FLAGS_SAME_MASK(_flags, _flags_other) do { \ + const vma_flags_t __flags_other = (_flags_other); \ + ASSERT_TRUE(vma_flags_same_pair((_flags), &__flags_other)); \ + } while (0) -#define ASSERT_FLAGS_NOT_SAME_MASK(_flags, _flags_other) \ - ASSERT_FALSE(vma_flags_same_mask((_flags), (_flags_other))) +#define ASSERT_FLAGS_NOT_SAME_MASK(_flags, _flags_other) do { \ + const vma_flags_t __flags_other = (_flags_other); \ + ASSERT_FALSE(vma_flags_same_pair((_flags), &__flags_other)); \ + } while (0) #define ASSERT_FLAGS_SAME(_flags, ...) \ - ASSERT_TRUE(vma_flags_same(_flags, __VA_ARGS__)) + ASSERT_FLAGS_SAME_MASK(_flags, mk_vma_flags(__VA_ARGS__)) #define ASSERT_FLAGS_NOT_SAME(_flags, ...) \ - ASSERT_FALSE(vma_flags_same(_flags, __VA_ARGS__)) + ASSERT_FLAGS_NOT_SAME_MASK(_flags, mk_vma_flags(__VA_ARGS__)) #define ASSERT_FLAGS_EMPTY(_flags) \ ASSERT_TRUE(vma_flags_empty(_flags)) diff --git a/tools/thermal/tmon/tmon.c b/tools/thermal/tmon/tmon.c index 7eb3216a27f4..0c8deee4652e 100644 --- a/tools/thermal/tmon/tmon.c +++ b/tools/thermal/tmon/tmon.c @@ -230,7 +230,7 @@ int main(int argc, char **argv) switch (c) { case 'c': no_control = 0; - strncpy(ctrl_cdev, optarg, CDEV_NAME_SIZE); + snprintf(ctrl_cdev, sizeof(ctrl_cdev), "%s", optarg); break; case 'd': start_daemon_mode(); diff --git a/tools/tracing/rtla/tests/engine.sh b/tools/tracing/rtla/tests/engine.sh index 4287cd64ac31..4fe7bcbab8b7 100644 --- a/tools/tracing/rtla/tests/engine.sh +++ b/tools/tracing/rtla/tests/engine.sh @@ -7,7 +7,7 @@ test_begin() { # Set test directory to the directory of the script scriptfile=$(realpath "$0") testdir=$(dirname "$scriptfile") - [ -z "$RTLA" ] && RTLA="./rtla" + [ -z "$RTLA" ] && RTLA="$(pwd)/rtla" [ -n "$TEST_COUNT" ] && echo "1..$TEST_COUNT" } diff --git a/usr/gen_init_cpio.c b/usr/gen_init_cpio.c index b7296edc6626..0f0c61ec21ca 100644 --- a/usr/gen_init_cpio.c +++ b/usr/gen_init_cpio.c @@ -756,6 +756,7 @@ int main (int argc, char *argv[]) "ERROR: incorrect format, newline required line %d: '%s'\n", line_nr, line); ec = -1; + break; } for (type_idx = 0; file_handler_table[type_idx].type; type_idx++) {